holycodex 0.16.3 → 0.16.4-dev.77.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 +23 -5
  2. package/dist/agent.js +142 -0
  3. package/dist/assets/plugin/plugin.json +2 -2
  4. package/dist/assets/plugin/skills/code-review/SKILL.md +5 -12
  5. package/dist/assets/plugin/skills/code-review/agents/openai.yaml +1 -1
  6. package/dist/assets/plugin/skills/commit/SKILL.md +23 -7
  7. package/dist/assets/plugin/skills/commit/agents/openai.yaml +1 -1
  8. package/dist/assets/plugin/skills/compress/SKILL.md +4 -6
  9. package/dist/assets/plugin/skills/compress/agents/openai.yaml +1 -1
  10. package/dist/assets/plugin/skills/context7-cli/SKILL.md +4 -10
  11. package/dist/assets/plugin/skills/context7-cli/agents/openai.yaml +1 -1
  12. package/dist/assets/plugin/skills/debugging/SKILL.md +4 -18
  13. package/dist/assets/plugin/skills/debugging/agents/openai.yaml +1 -1
  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 +5 -6
  17. package/dist/assets/plugin/skills/handoff/agents/openai.yaml +2 -2
  18. package/dist/assets/plugin/skills/operations/SKILL.md +11 -0
  19. package/dist/assets/plugin/skills/operations/agents/openai.yaml +6 -0
  20. package/dist/assets/plugin/skills/plan/SKILL.md +6 -9
  21. package/dist/assets/plugin/skills/plan/agents/openai.yaml +1 -1
  22. package/dist/assets/plugin/skills/plan-review/SKILL.md +5 -7
  23. package/dist/assets/plugin/skills/plan-review/agents/openai.yaml +1 -1
  24. package/dist/assets/plugin/skills/programming/SKILL.md +4 -7
  25. package/dist/assets/plugin/skills/programming/agents/openai.yaml +1 -1
  26. package/dist/assets/plugin/skills/refactor/SKILL.md +4 -7
  27. package/dist/assets/plugin/skills/refactor/agents/openai.yaml +1 -1
  28. package/dist/assets/plugin/skills/rules/SKILL.md +4 -6
  29. package/dist/assets/plugin/skills/rules/agents/openai.yaml +1 -1
  30. package/dist/assets/plugin/skills/stop-slop/SKILL.md +5 -34
  31. package/dist/assets/plugin/skills/stop-slop/agents/openai.yaml +1 -1
  32. package/dist/assets/plugin/skills/testing-quality.md +10 -26
  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 -40
  35. package/dist/assets/plugin/skills/writing-for-agents/agents/openai.yaml +1 -1
  36. package/dist/index.js +103 -57
  37. package/package.json +8 -5
package/dist/index.js CHANGED
@@ -1,35 +1,69 @@
1
1
  #!/usr/bin/env bun
2
- import{createInterface as e}from"node:readline/promises";import{lstat as t,mkdir as n,mkdtemp as r,open as i,readFile as a,readdir as o,realpath as s,rename as c,rm as l,rmdir as u,stat as d,unlink as f,writeFile as p}from"node:fs/promises";import{delimiter as m,dirname as h,isAbsolute as g,join as _,posix as ee,relative as te,resolve as ne,sep as re,win32 as ie}from"node:path";import{spawn as ae}from"node:child_process";import{fileURLToPath as oe}from"node:url";import{homedir as se}from"node:os";var ce=Object.defineProperty,v=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(e){throw n=[e],e}},le=(e,t)=>{let n={};for(var r in e)ce(n,r,{get:e[r],enumerable:!0});return t||ce(n,Symbol.toStringTag,{value:`Module`}),n};function ue(e,t=new WeakSet){if(!t.has(e)){t.add(e);for(let n of Reflect.ownKeys(e)){let r=Object.getOwnPropertyDescriptor(e,n);r&&`value`in r&&de(r.value)&&ue(r.value,t)}Object.freeze(e)}}function de(e){return typeof e==`object`&&!!e}var fe,pe,me=v((()=>{fe=`0.15`,pe=`state-0.16`}));function he(e){return{ok:!0,value:e}}function ge(e){return{ok:!1,error:e}}function _e(e,t){return new y(`invalid_input`,`Invalid ${e}.`,{field:e},t===void 0?void 0:{cause:t})}var y,ve=v((()=>{me(),y=class extends Error{code;details;constructor(e,t,n={},r){super(t,r),this.name=`CoreError`,this.code=e,this.details=n,ue(this.details),Object.freeze(this)}}}));function b(e,t,n,r,i,a,o,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 i(r(n(t(e))));case 6:return a(i(r(n(t(e)))));case 7:return o(a(i(r(n(t(e))))));case 8:return s(o(a(i(r(n(t(e)))))));case 9:return c(s(o(a(i(r(n(t(e))))))));default:{let e=arguments[0];for(let t=1;t<arguments.length;t++)e=arguments[t](e);return e}}}var ye,x,be,xe,Se,Ce,we,Te,S=v((()=>{ye=e=>typeof e==`function`,x=function(e,t){if(typeof e==`function`)return function(){return e(arguments)?t.apply(this,arguments):e=>t(e,...arguments)};switch(e){case 0:case 1:throw RangeError(`Invalid arity ${e}`);case 2:return function(e,n){return arguments.length>=2?t(e,n):function(n){return t(n,e)}};case 3:return function(e,n,r){return arguments.length>=3?t(e,n,r):function(r){return t(r,e,n)}};case 4:return function(e,n,r,i){return arguments.length>=4?t(e,n,r,i):function(i){return t(i,e,n,r)}};case 5:return function(e,n,r,i,a){return arguments.length>=5?t(e,n,r,i,a):function(a){return t(a,e,n,r,i)}};default:return function(){if(arguments.length>=e)return t.apply(this,arguments);let n=arguments;return function(e){return t(e,...n)}}}},be=e=>e,xe=e=>()=>e,Se=xe(!0),Ce=xe(!1),we=xe(void 0),Te=we})),Ee,De,Oe,ke,Ae,je,Me,Ne=v((()=>{S(),Ee=e=>(t,n)=>t===n||e(t,n),De=(e,t)=>e===t,Oe=()=>De,ke=Oe(),Ae=x(2,(e,t)=>Ee((n,r)=>e(t(n),t(r)))),je=Ae(ke,e=>e.getTime()),Me=e=>Ee((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})})),Pe,Fe,C,Ie=v((()=>{Pe=`effect/GlobalValue`,C=(e,t)=>(Fe||=(globalThis[Pe]??=new Map,globalThis[Pe]),Fe.has(e)||Fe.set(e,t()),Fe.get(e))})),Le,Re,ze,Be,Ve,He,Ue,We,Ge,Ke,qe,w,Je,Ye,Xe,Ze,Qe,$e,et,tt,T=v((()=>{S(),Le=e=>!!e,Re=e=>typeof e==`string`,ze=e=>typeof e==`number`,Be=e=>typeof e==`boolean`,Ve=e=>typeof e==`bigint`,He=e=>typeof e==`symbol`,Ue=ye,We=e=>e===void 0,Ge=e=>!1,Ke=e=>typeof e==`object`&&!!e,qe=e=>Ke(e)||Ue(e),w=x(2,(e,t)=>qe(e)&&t in e),Je=x(2,(e,t)=>w(e,`_tag`)&&e._tag===t),Ye=e=>e==null,Xe=e=>e!=null,Ze=e=>e instanceof Uint8Array,Qe=e=>e instanceof Date,$e=e=>typeof e==`string`||w(e,Symbol.iterator),et=e=>Ke(e)&&!Array.isArray(e),tt=e=>w(e,`then`)&&Ue(e.then)})),nt,rt=v((()=>{nt=e=>`BUG: ${e} - please report an issue at https://github.com/Effect-TS/effect/issues`}));function it(e,t,n,r,i){let a=(n>>>16)*(i&65535)>>>0,o=(n&65535)*(i>>>16)>>>0,s=(n&65535)*(i&65535)>>>0,c=(n>>>16)*(i>>>16)+((o>>>16)+(a>>>16))>>>0;o=o<<16>>>0,s=s+o>>>0,s>>>0<o>>>0&&(c=c+1>>>0),a=a<<16>>>0,s=s+a>>>0,s>>>0<a>>>0&&(c=c+1>>>0),c=c+Math.imul(n,r)>>>0,c=c+Math.imul(t,i)>>>0,e[0]=c,e[1]=s}function at(e,t,n,r,i){let a=t+r>>>0,o=n+i>>>0;o>>>0<n>>>0&&(a=a+1|0),e[0]=a,e[1]=o}function ot(e){if(typeof e==`object`&&e&&ht in e)return e[ht]();throw Error(nt(`yieldWrapGet`))}var st,ct,lt,ut,dt,ft,pt,mt,ht,gt,_t,vt,yt,bt,xt,St=v((()=>{Ie(),rt(),T(),st=class e{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 e(this.self)}},ct=335903614,lt=4150755663,ut=1481765933,dt=1284865837,ft=9007199254740992,pt=134217728,mt=class{_state;constructor(e,t,n,r){return Ye(t)&&Ye(e)?(t=Math.random()*4294967295>>>0,e=0):Ye(t)&&(t=e,e=0),Ye(r)&&Ye(n)?(r=this._state?this._state[3]:lt,n=this._state?this._state[2]:ct):Ye(r)&&(r=n,n=0),this._state=new Int32Array([0,0,n>>>0,((r||0)|1)>>>0]),this._next(),at(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()*(2**53-1))%e}number(){let e=(this._next()&67108863)*1,t=(this._next()&134217727)*1;return(e*pt+t)/ft}_next(){let e=this._state[0]>>>0,t=this._state[1]>>>0;it(this._state,e,t,ut,dt),at(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 i=(r>>>27|n<<5)>>>0,a=e>>>27,o=(-a>>>0&31)>>>0;return(i>>>a|i<<o)>>>0}},ht=Symbol.for(`effect/Utils/YieldWrap`),gt=class{#e;constructor(e){this.#e=e}[ht](){return this.#e}},_t=C(`effect/Utils/isStructuralRegion`,()=>({enabled:!1,tester:void 0})),vt={effect_internal_function:e=>e()},yt={effect_internal_function:e=>{try{return e()}finally{}}},bt=vt.effect_internal_function(()=>Error().stack)?.includes(`effect_internal_function`)===!0,xt=bt?vt.effect_internal_function:yt.effect_internal_function,function*(){}.constructor})),Ct,E,D,wt,O,Tt,Et,Dt,Ot,kt,At,jt,k,Mt=v((()=>{S(),Ie(),T(),St(),Ct=C(Symbol.for(`effect/Hash/randomHashCache`),()=>new WeakMap),E=Symbol.for(`effect/Hash`),D=e=>{if(_t.enabled===!0)return 0;switch(typeof e){case`number`:return Dt(e);case`bigint`:return Ot(e.toString(10));case`boolean`:return Ot(String(e));case`symbol`:return Ot(String(e));case`string`:return Ot(e);case`undefined`:return Ot(`undefined`);case`function`:case`object`:return e===null?Ot(`null`):e instanceof Date?Number.isNaN(e.getTime())?Ot(`Invalid Date`):D(e.toISOString()):e instanceof URL?D(e.href):Et(e)?e[E]():wt(e);default:throw Error(`BUG: unhandled typeof ${typeof e} - please report an issue at https://github.com/Effect-TS/effect/issues`)}},wt=e=>(Ct.has(e)||Ct.set(e,Dt(Math.floor(Math.random()*(2**53-1)))),Ct.get(e)),O=e=>t=>t*53^e,Tt=e=>e&3221225471|e>>>1&1073741824,Et=e=>w(e,E),Dt=e=>{if(e!==e||e===1/0)return 0;let t=e|0;for(t!==e&&(t^=e*4294967295);e>4294967295;)t^=e/=4294967295;return Tt(t)},Ot=e=>{let t=5381,n=e.length;for(;n;)t=t*33^e.charCodeAt(--n);return Tt(t)},kt=(e,t)=>{let n=12289;for(let r=0;r<t.length;r++)n^=b(Ot(t[r]),O(D(e[t[r]])));return Tt(n)},At=e=>kt(e,Object.keys(e)),jt=e=>{let t=6151;for(let n=0;n<e.length;n++)t=b(t,O(D(e[n])));return Tt(t)},k=function(){if(arguments.length===1){let e=arguments[0];return function(t){return Object.defineProperty(e,E,{value(){return t},enumerable:!1}),t}}let e=arguments[0],t=arguments[1];return Object.defineProperty(e,E,{value(){return t},enumerable:!1}),t}}));function A(){return arguments.length===1?e=>Nt(e,arguments[0]):Nt(arguments[0],arguments[1])}function Nt(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(Pt(e)&&Pt(t))return D(e)===D(t)&&e[j](t)?!0:_t.enabled&&_t.tester?_t.tester(e,t):!1;if(e instanceof Date&&t instanceof Date){let n=e.getTime(),r=t.getTime();return n===r||Number.isNaN(n)&&Number.isNaN(r)}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((e,n)=>Nt(e,t[n]));if(Object.getPrototypeOf(e)===Object.prototype&&Object.getPrototypeOf(t)===Object.prototype){let n=Object.keys(e),r=Object.keys(t);if(n.length===r.length){for(let r of n)if(!(r in t&&Nt(e[r],t[r])))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 j,Pt,Ft,M=v((()=>{Mt(),T(),St(),j=Symbol.for(`effect/Equal`),Pt=e=>w(e,j),Ft=()=>A}));function It(e){try{return e.toISOString()}catch{return`Invalid Date`}}function Lt(e){try{let t=e.toString();return typeof t==`string`?t:String(t)}catch{return`[toString threw]`}}function Rt(e){return Re(e)?JSON.stringify(e):String(e)}function zt(e,t){let n=t?.space??0,r=new WeakSet,i=n?ze(n)?` `.repeat(n):n:``,a=e=>i.repeat(e),o=(e,t)=>{let n=e?.constructor;return n&&n!==Object.prototype.constructor&&n.name?`${n.name}(${t})`:t},s=e=>{try{return Reflect.ownKeys(e)}catch{return[`[ownKeys threw]`]}};function c(e,n=0){if(Array.isArray(e)){if(r.has(e))return Vt;if(r.add(e),!i||e.length<=1)return`[${e.map(e=>c(e,n)).join(`,`)}]`;let t=e.map(e=>c(e,n+1)).join(`,
3
- `+a(n+1));return`[\n${a(n+1)}${t}\n${a(n)}]`}if(Qe(e))return It(e);if(!t?.ignoreToString&&w(e,`toString`)&&Ue(e.toString)&&e.toString!==Object.prototype.toString&&e.toString!==Array.prototype.toString){let t=Lt(e);return e instanceof Error&&e.cause?`${t} (cause: ${c(e.cause,n)})`:t}if(Re(e))return JSON.stringify(e);if(ze(e)||e==null||Be(e)||He(e))return String(e);if(Ve(e))return String(e)+`n`;if(e instanceof Set||e instanceof Map)return r.has(e)?Vt:(r.add(e),`${e.constructor.name}(${c(Array.from(e),n)})`);if(qe(e)){if(r.has(e))return Vt;r.add(e);let t=s(e);if(!i||t.length<=1){let r=`{${t.map(t=>`${Rt(t)}:${c(e[t],n)}`).join(`,`)}}`;return o(e,r)}let l=`{\n${t.map(t=>`${a(n+1)}${Rt(t)}: ${c(e[t],n+1)}`).join(`,
4
- `)}\n${a(n)}}`;return o(e,l)}return String(e)}return c(e,0)}var N,Bt,Vt,Ht,Ut,Wt,Gt,Kt,qt,Jt,Yt,Xt=v((()=>{Ie(),T(),N=Symbol.for(`nodejs.util.inspect.custom`),Bt=e=>{try{if(w(e,`toJSON`)&&Ue(e.toJSON)&&e.toJSON.length===0)return e.toJSON();if(Array.isArray(e))return e.map(Bt)}catch{return{}}return Yt(e)},Vt=`[Circular]`,Ht=e=>JSON.stringify(e,null,2),Ut=(e,t=2)=>{if(typeof e==`string`)return e;try{return typeof e==`object`?Wt(e,t):String(e)}catch{return String(e)}},Wt=(e,t)=>{let n=[],r=JSON.stringify(e,(e,t)=>typeof t==`object`&&t?n.includes(t)?void 0:n.push(t)&&(qt.fiberRefs!==void 0&&Kt(t)?t[Gt](qt.fiberRefs):t):t,t);return n=void 0,r},Gt=Symbol.for(`effect/Inspectable/Redactable`),Kt=e=>typeof e==`object`&&!!e&&Gt in e,qt=C(`effect/Inspectable/redactableState`,()=>({fiberRefs:void 0})),Jt=(e,t)=>{let n=qt.fiberRefs;qt.fiberRefs=e;try{return t()}finally{qt.fiberRefs=n}},Yt=e=>Kt(e)&&qt.fiberRefs!==void 0?e[Gt](qt.fiberRefs):e})),P,F=v((()=>{P=(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 e=0,r=t.length;e<r;e++)n=t[e](n);return n}}}})),Zt,Qt,$t,en,tn,nn,rn,an,on,sn,cn,ln,un,dn,fn=v((()=>{Zt=`Async`,Qt=`Commit`,$t=`Failure`,en=`OnFailure`,tn=`OnSuccess`,nn=`OnSuccessAndFailure`,rn=`Success`,an=`Sync`,on=`UpdateRuntimeFlags`,sn=`While`,cn=`Iterator`,ln=`WithRuntime`,un=`Yield`,dn=`RevertFlags`})),pn,mn,hn=v((()=>{pn=`3.22.1`,mn=()=>pn})),gn,_n,vn,yn,bn,xn,Sn,Cn,wn,Tn,En,Dn,On=v((()=>{M(),Mt(),F(),St(),fn(),hn(),gn=Symbol.for(`effect/Effect`),_n=Symbol.for(`effect/Stream`),vn=Symbol.for(`effect/Sink`),yn=Symbol.for(`effect/Channel`),bn={_R:e=>e,_E:e=>e,_A:e=>e,_V:mn()},xn={_A:e=>e,_In:e=>e,_L:e=>e,_E:e=>e,_R:e=>e},Sn={_Env:e=>e,_InErr:e=>e,_InElem:e=>e,_InDone:e=>e,_OutErr:e=>e,_OutElem:e=>e,_OutDone:e=>e},Cn={[gn]:bn,[_n]:bn,[vn]:xn,[yn]:Sn,[j](e){return this===e},[E](){return k(this,wt(this))},[Symbol.iterator](){return new st(new gt(this))},pipe(){return P(this,arguments)}},wn={[E](){return k(this,At(this))},[j](e){let t=Object.keys(this),n=Object.keys(e);if(t.length!==n.length)return!1;for(let n of t)if(!(n in e&&A(this[n],e[n])))return!1;return!0}},Tn={...Cn,_op:Qt},En={...Tn,...wn},Dn=function(){function e(){}return e.prototype=Tn,e}()})),kn,An,jn,Mn,Nn,Pn,Fn,In,Ln,Rn,zn=v((()=>{M(),Mt(),Xt(),T(),On(),kn=Symbol.for(`effect/Option`),An={...Cn,[kn]:{_A:e=>e},[N](){return this.toJSON()},toString(){return Ht(this.toJSON())}},jn=Object.assign(Object.create(An),{_tag:`Some`,_op:`Some`,[j](e){return Pn(e)&&In(e)&&A(this.value,e.value)},[E](){return k(this,O(D(this._tag))(D(this.value)))},toJSON(){return{_id:`Option`,_tag:this._tag,value:Bt(this.value)}}}),Mn=D(`None`),Nn=Object.assign(Object.create(An),{_tag:`None`,_op:`None`,[j](e){return Pn(e)&&Fn(e)},[E](){return Mn},toJSON(){return{_id:`Option`,_tag:this._tag}}}),Pn=e=>w(e,kn),Fn=e=>e._tag===`None`,In=e=>e._tag===`Some`,Ln=Object.create(Nn),Rn=e=>{let t=Object.create(jn);return t.value=e,t}})),Bn,Vn,Hn,Un,Wn,Gn,Kn,qn,Jn,Yn,Xn=v((()=>{M(),S(),Mt(),Xt(),T(),On(),zn(),Bn=Symbol.for(`effect/Either`),Vn={...Cn,[Bn]:{_R:e=>e},[N](){return this.toJSON()},toString(){return Ht(this.toJSON())}},Hn=Object.assign(Object.create(Vn),{_tag:`Right`,_op:`Right`,[j](e){return Wn(e)&&Kn(e)&&A(this.right,e.right)},[E](){return O(D(this._tag))(D(this.right))},toJSON(){return{_id:`Either`,_tag:this._tag,right:Bt(this.right)}}}),Un=Object.assign(Object.create(Vn),{_tag:`Left`,_op:`Left`,[j](e){return Wn(e)&&Gn(e)&&A(this.left,e.left)},[E](){return O(D(this._tag))(D(this.left))},toJSON(){return{_id:`Either`,_tag:this._tag,left:Bt(this.left)}}}),Wn=e=>w(e,Bn),Gn=e=>e._tag===`Left`,Kn=e=>e._tag===`Right`,qn=e=>{let t=Object.create(Un);return t.left=e,t},Jn=e=>{let t=Object.create(Hn);return t.right=e,t},Yn=x(2,(e,t)=>Fn(e)?qn(t()):Jn(e.value))})),I,L,Zn,Qn,$n,er,tr,nr,rr,ir,ar,or,sr,cr,lr=v((()=>{S(),Xn(),T(),I=Jn,L=qn,Zn=Yn,Qn=e=>{if(Ue(e))try{return I(e())}catch(e){return L(e)}try{return I(e.try())}catch(t){return L(e.catch(t))}},$n=Wn,er=Gn,tr=Kn,nr=x(2,(e,{onLeft:t,onRight:n})=>er(e)?L(t(e.left)):I(n(e.right))),rr=x(2,(e,t)=>er(e)?L(t(e.left)):I(e.right)),ir=x(2,(e,t)=>tr(e)?I(t(e.right)):L(e.left)),ar=x(2,(e,{onLeft:t,onRight:n})=>er(e)?t(e.left):n(e.right)),or=ar({onLeft:be,onRight:be}),sr=x(2,(e,t)=>{if(tr(e))return e.right;throw t(e.left)}),cr=sr(()=>Error(`getOrThrow called on a Left`))})),ur,dr=v((()=>{ur=e=>e.length>0})),fr,pr,mr,hr,gr=v((()=>{S(),fr=e=>(t,n)=>t===n?0:e(t,n),pr=fr((e,t)=>e<t?-1:1),mr=x(2,(e,t)=>fr((n,r)=>e(t(n),t(r)))),hr=e=>x(2,(t,n)=>e(t,n)===1)})),R,z,_r,vr,yr,br,xr,Sr,Cr,wr,Tr,Er,Dr,Or,kr,Ar,jr,Mr,Nr,Pr,Fr,Ir,Lr,Rr=v((()=>{M(),Ne(),S(),zn(),R=()=>Ln,z=Rn,_r=Pn,vr=Fn,yr=In,br=x(2,(e,{onNone:t,onSome:n})=>vr(e)?t():n(e.value)),xr=x(2,(e,t)=>vr(e)?t():e.value),Sr=x(2,(e,t)=>vr(e)?t():e),Cr=x(2,(e,t)=>vr(e)?z(t()):e),wr=e=>e==null?R():z(e),Tr=xr(we),Er=e=>(...t)=>{try{return z(e(...t))}catch{return R()}},Dr=x(2,(e,t)=>{if(yr(e))return e.value;throw t()}),Or=x(2,(e,t)=>vr(e)?R():z(t(e.value))),kr=x(2,(e,t)=>vr(e)?R():t(e.value)),Ar=x(2,(e,t)=>vr(e)?R():wr(t(e.value))),jr=kr,Mr=x(2,(e,t)=>jr(e,e=>t(e)?Rn(e):Ln)),Nr=e=>Ee((t,n)=>vr(t)?vr(n):!vr(n)&&e(t.value,n.value)),Pr=e=>x(2,(t,n)=>!vr(t)&&e(t.value,n)),Fr=Ft(),Ir=Pr(Fr),Lr=x(2,(e,t)=>!vr(e)&&t(e.value))})),zr,Br=v((()=>{T(),zr=(...e)=>e})),Vr,Hr,Ur,Wr,Gr,Kr,qr,Jr,Yr,Xr,Zr,Qr,$r,ei,ti,ni,ri,ii,ai,oi,si,ci,li,ui,di,fi,pi,mi,hi,gi,_i,vi,yi,bi,xi,Si,Ci,wi,Ti,Ei,Di,Oi,ki,Ai,ji,Mi,Ni,Pi=v((()=>{M(),Ne(),S(),dr(),Rr(),Br(),Vr=e=>Array(e),Hr=x(2,(e,t)=>{let n=Math.max(1,Math.floor(e)),r=Array(n);for(let e=0;e<n;e++)r[e]=t(e);return r}),Ur=e=>Array.isArray(e)?e:Array.from(e),Wr=e=>Array.isArray(e)?e:[e],Gr=x(2,(e,{onEmpty:t,onNonEmpty:n})=>$r(e)?n(ai(e),ci(e)):t()),Kr=x(2,(e,t)=>[t,...e]),qr=x(2,(e,t)=>[...e,t]),Jr=x(2,(e,t)=>Ur(e).concat(Ur(t))),Yr=Array.isArray,Xr=e=>e.length===0,Zr=Xr,Qr=ur,$r=ur,ei=(e,t)=>e<0||e>=t.length,ti=(e,t)=>Math.floor(Math.min(Math.max(0,e),t.length)),ni=x(2,(e,t)=>{let n=Math.floor(t);return ei(n,e)?R():z(e[n])}),ri=x(2,(e,t)=>{let n=Math.floor(t);if(ei(n,e))throw Error(`Index ${n} out of bounds`);return e[n]}),ii=ni(0),ai=ri(0),oi=e=>$r(e)?z(si(e)):R(),si=e=>e[e.length-1],ci=e=>e.slice(1),li=(e,t)=>{let n=0;for(let r of e){if(!t(r,n))break;n++}return n},ui=x(2,(e,t)=>_i(e,li(e,t))),di=x(2,(e,t)=>{let n=Ur(e);return n.slice(ti(t,n),n.length)}),fi=e=>Array.from(e).reverse(),pi=x(2,(e,t)=>{let n=Array.from(e);return n.sort(t),n}),mi=x(2,(e,t)=>hi(e,t,zr)),hi=x(3,(e,t,n)=>{let r=Ur(e),i=Ur(t);if($r(r)&&$r(i)){let e=[n(ai(r),ai(i))],t=Math.min(r.length,i.length);for(let a=1;a<t;a++)e[a]=n(r[a],i[a]);return e}return[]}),gi=Ft(),_i=x(2,(e,t)=>{let n=Array.from(e),r=Math.floor(t);return $r(n)?r>=1?vi(n,r):[[],n]:[n,[]]}),vi=x(2,(e,t)=>{let n=Math.max(1,Math.floor(t));return n>=e.length?[yi(e),[]]:[Kr(e.slice(1,n),ai(e)),e.slice(n)]}),yi=e=>e.slice(),bi=x(3,(e,t,n)=>{let r=Ur(e),i=Ur(t);return $r(r)?$r(i)?ji(n)(Jr(r,i)):r:i}),xi=x(2,(e,t)=>bi(e,t,gi)),Si=()=>[],Ci=e=>[e],wi=x(2,(e,t)=>e.map(t)),Ti=x(2,(e,t)=>{if(Zr(e))return[];let n=[];for(let r=0;r<e.length;r++){let i=t(e[r],r);for(let e=0;e<i.length;e++)n.push(i[e])}return n}),Ei=Ti(be),Di=x(2,(e,t)=>{let n=Ur(e),r=[];for(let e=0;e<n.length;e++){let i=t(n[e],e);yr(i)&&r.push(i.value)}return r}),Oi=x(3,(e,t,n)=>Ur(e).reduce((e,t,r)=>n(e,t,r),t)),ki=(e,t)=>{let n=[],r=e,i;for(;yr(i=t(r));){let[e,t]=i.value;n.push(e),r=t}return n},Ai=Me,ji=x(2,(e,t)=>{let n=Ur(e);if($r(n)){let e=[ai(n)],r=ci(n);for(let n of r)e.every(e=>!t(n,e))&&e.push(n);return e}return[]}),Mi=e=>ji(e,Ft()),Ni=x(2,(e,t)=>Ur(e).join(t))})),Fi,Ii,Li,Ri,zi,Bi,Vi,Hi,Ui,Wi,Gi,Ki,qi,Ji,Yi,Xi,Zi,Qi,$i,ea,ta,na,ra=v((()=>{M(),Ne(),S(),Mt(),Xt(),Rr(),F(),T(),Fi=/^[+-]?\d+$/,Ii=Symbol.for(`effect/BigDecimal`),Li={[Ii]:Ii,[E](){let e=Wi(this);return b(D(e.value),O(Dt(e.scale)),k(this))},[j](e){return Ri(e)&&Ji(this,e)},toString(){return`BigDecimal(${Qi(this)})`},toJSON(){return{_id:`BigDecimal`,value:String(this.value),scale:this.scale}},[N](){return this.toJSON()},pipe(){return P(this,arguments)}},Ri=e=>w(e,Ii),zi=(e,t)=>{let n=Object.create(Li);return n.value=e,n.scale=t,n},Bi=(e,t)=>{if(e!==Vi&&e%Hi===Vi)throw RangeError(`Value must be normalized`);let n=zi(e,t);return n.normalized=n,n},Vi=BigInt(0),Hi=BigInt(10),Ui=Bi(Vi,0),Wi=e=>{if(e.normalized===void 0){if(e.value===Vi)e.normalized=Ui;else{let t=`${e.value}`,n=0;for(let e=t.length-1;e>=0&&t[e]===`0`;e--)n++;n===0&&(e.normalized=e);let r=BigInt(t.substring(0,t.length-n)),i=e.scale-n;e.normalized=Bi(r,i)}}return e.normalized},Gi=x(2,(e,t)=>t>e.scale?zi(e.value*Hi**BigInt(t-e.scale),t):t<e.scale?zi(e.value/Hi**BigInt(e.scale-t),t):e),Ki=e=>e.value<Vi?zi(-e.value,e.scale):e,qi=Ee((e,t)=>e.scale>t.scale?Gi(t,e.scale).value===e.value:e.scale<t.scale?Gi(e,t.scale).value===t.value:e.value===t.value),Ji=x(2,(e,t)=>qi(e,t)),Yi=e=>Dr(Xi(e),()=>RangeError(`Number must be finite, got ${e}`)),Xi=e=>{if(!Number.isFinite(e))return R();let t=`${e}`;if(t.includes(`e`))return Zi(t);let[n,r=``]=t.split(`.`);return z(zi(BigInt(`${n}${r}`),r.length))},Zi=e=>{if(e===``)return z(Ui);let t,n,r=e.search(/[eE]/);if(r!==-1){let i=e.slice(r+1);if(t=e.slice(0,r),n=Number(i),t===``||!Number.isSafeInteger(n)||!Fi.test(i))return R()}else t=e,n=0;let i,a,o=t.search(/\./);if(o!==-1){let e=t.slice(0,o),n=t.slice(o+1);i=`${e}${n}`,a=n.length}else i=t,a=0;if(!Fi.test(i))return R();let s=a-n;return Number.isSafeInteger(s)?z(zi(BigInt(i),s)):R()},Qi=e=>{let t=Wi(e);if(Math.abs(t.scale)>=16)return $i(t);let n=t.value<Vi,r=n?`${t.value}`.substring(1):`${t.value}`,i,a;if(t.scale>=r.length)i=`0`,a=`0`.repeat(t.scale-r.length)+r;else{let e=r.length-t.scale;if(e>r.length){let t=e-r.length;i=`${r}${`0`.repeat(t)}`,a=``}else a=r.slice(e),i=r.slice(0,e)}let o=a===``?i:`${i}.${a}`;return n?`-${o}`:o},$i=e=>{if(ta(e))return`0e+0`;let t=Wi(e),n=`${Ki(t).value}`,r=n.slice(0,1),i=n.slice(1),a=`${na(t)?`-`:``}${r}`;i!==``&&(a+=`.${i}`);let o=i.length-t.scale;return`${a}e${o>=0?`+`:``}${o}`},ea=e=>Number(Qi(e)),ta=e=>e.value===Vi,na=e=>e.value<Vi})),ia,aa,oa,sa=v((()=>{Rr(),ia=e=>e>BigInt(2**53-1)||e<BigInt(-(2**53-1))?R():z(Number(e)),aa=e=>{try{return e.trim()===``?R():z(BigInt(e))}catch{return R()}},oa=e=>{if(e>2**53-1||e<-(2**53-1))return R();try{return z(BigInt(e))}catch{return R()}}})),ca,la=v((()=>{ca=e=>!e}));function ua(e,t,n,r,i){for(let a=t;a<Math.min(e.length,t+i);a++)n[r+a-t]=e[a];return n}var da,fa,pa,ma,ha,ga,_a,va,ya,ba,xa,Sa,Ca,wa,Ta,Ea,Da,Oa,ka,Aa,ja,Ma,Na,Pa,Fa,Ia,La,Ra,za,Ba=v((()=>{Pi(),M(),Ne(),S(),Mt(),Xt(),F(),T(),da=Symbol.for(`effect/Chunk`),fa=[],pa=e=>Ee((t,n)=>t.length===n.length&&Ta(t).every((t,r)=>e(t,Aa(n,r)))),ma=pa(A),ha={[da]:{_A:e=>e},toString(){return Ht(this.toJSON())},toJSON(){return{_id:`Chunk`,values:Ta(this).map(Bt)}},[N](){return this.toJSON()},[j](e){return _a(e)&&ma(this,e)},[E](){return k(this,jt(Ta(this)))},[Symbol.iterator](){switch(this.backing._tag){case`IArray`:return this.backing.array[Symbol.iterator]();case`IEmpty`:return fa[Symbol.iterator]();default:return Ta(this)[Symbol.iterator]()}},pipe(){return P(this,arguments)}},ga=e=>{let t=Object.create(ha);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=va,t.right=va;break;case`ISingleton`:t.length=1,t.depth=0,t.left=va,t.right=va;break;case`ISlice`:t.length=e.length,t.depth=e.chunk.depth+1,t.left=va,t.right=va}return t},_a=e=>w(e,da),va=ga({_tag:`IEmpty`}),ya=()=>va,ba=(...e)=>ka(e),xa=e=>ga({_tag:`ISingleton`,a:e}),Sa=e=>_a(e)?e:Oa(Ur(e)),Ca=(e,t,n)=>{switch(e.backing._tag){case`IArray`:ua(e.backing.array,0,t,n,e.length);break;case`IConcat`:Ca(e.left,t,n),Ca(e.right,t,n+e.left.length);break;case`ISingleton`:t[n]=e.backing.a;break;case`ISlice`:{let r=0,i=n;for(;r<e.length;)t[i]=Aa(e,r),r+=1,i+=1;break}}},wa=e=>{switch(e.backing._tag){case`IEmpty`:return fa;case`IArray`:return e.backing.array;default:{let t=Array(e.length);return Ca(e,t,0),e.backing={_tag:`IArray`,array:t},e.left=va,e.right=va,e.depth=0,t}}},Ta=wa,Ea=e=>{switch(e.backing._tag){case`IEmpty`:case`ISingleton`:return e;case`IArray`:return ga({_tag:`IArray`,array:fi(e.backing.array)});case`IConcat`:return ga({_tag:`IConcat`,left:Da(e.backing.right),right:Da(e.backing.left)});case`ISlice`:return Oa(fi(Ta(e)))}},Da=Ea,Oa=e=>e.length===0?ya():e.length===1?xa(e[0]):ga({_tag:`IArray`,array:e}),ka=e=>Oa(e),Aa=x(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?Aa(e.left,t):Aa(e.right,t-e.left.length);case`ISlice`:return Aa(e.backing.chunk,t+e.backing.offset)}}),ja=x(2,(e,t)=>Pa(e,xa(t))),Ma=x(2,(e,t)=>Pa(xa(t),e)),Na=x(2,(e,t)=>{if(t<=0)return e;if(t>=e.length)return va;switch(e.backing._tag){case`ISlice`:return ga({_tag:`ISlice`,chunk:e.backing.chunk,offset:e.backing.offset+t,length:e.backing.length-t});case`IConcat`:return t>e.left.length?Na(e.right,t-e.left.length):ga({_tag:`IConcat`,left:Na(e.left,t),right:e.right});default:return ga({_tag:`ISlice`,chunk:e,offset:t,length:e.length-t})}}),Pa=x(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 ga({_tag:`IConcat`,left:e,right:t});if(n<-1){if(e.left.depth>=e.right.depth){let n=Pa(e.right,t);return ga({_tag:`IConcat`,left:e.left,right:n})}{let n=Pa(e.right.right,t);if(n.depth===e.depth-3){let t=ga({_tag:`IConcat`,left:e.right.left,right:n});return ga({_tag:`IConcat`,left:e.left,right:t})}{let t=ga({_tag:`IConcat`,left:e.left,right:e.right.left});return ga({_tag:`IConcat`,left:t,right:n})}}}if(t.right.depth>=t.left.depth){let n=Pa(e,t.left);return ga({_tag:`IConcat`,left:n,right:t.right})}{let n=Pa(e,t.left.left);if(n.depth===t.depth-3){let e=ga({_tag:`IConcat`,left:n,right:t.left.right});return ga({_tag:`IConcat`,left:e,right:t.right})}{let e=ga({_tag:`IConcat`,left:t.left.right,right:t.right});return ga({_tag:`IConcat`,left:n,right:e})}}}),Fa=e=>e.length===0,Ia=e=>e.length>0,La=e=>Aa(e,0),Ra=La,za=e=>Na(e,1)})),Va,Ha,Ua,Wa,Ga=v((()=>{Va=32,Ha=Va-1,Ua=Va/2,Wa=Va/4}));function Ka(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 qa(e,t){return t>>>e&Ha}function Ja(e){return 1<<e}function Ya(e,t){return Ka(e&t-1)}var Xa=v((()=>{Ga()})),Za,Qa=v((()=>{Za=(e,t)=>({value:e,previous:t})}));function $a(e,t,n,r){let i=r;if(!e){let e=r.length;i=Array(e);for(let t=0;t<e;++t)i[t]=r[t]}return i[t]=n,i}function eo(e,t,n){let r=n.length-1,i=0,a=0,o=n;if(e)i=a=t;else for(o=Array(r);i<t;)o[a++]=n[i++];for(++i;i<=r;)o[a++]=n[i++];return e&&(o.length=r),o}function to(e,t,n,r){let i=r.length;if(e){let e=i;for(;e>=t;)r[e--]=r[e];return r[t]=n,r}let a=0,o=0,s=Array(i+1);for(;a<t;)s[o++]=r[a++];for(s[t]=n;a<i;)s[++o]=r[a++];return s}var no=v((()=>{}));function ro(e){return Je(e,`EmptyNode`)}function io(e){return ro(e)||e._tag===`LeafNode`||e._tag===`CollisionNode`}function ao(e,t){return!ro(e)&&t===e.edit}function oo(e,t,n,r){let i=Array(t-1),a=0,o=0;for(let e=0,t=r.length;e<t;++e)if(e!==n){let t=r[e];t&&!ro(t)&&(i[a++]=t,o|=1<<e)}return new mo(e,o,i)}function so(e,t,n,r,i){let a=[],o=r,s=0;for(let e=0;o;++e)o&1&&(a[e]=i[s++]),o>>>=1;return a[t]=n,new ho(e,s+1,a)}function co(e,t,n,r,i,a){if(n===i)return new po(e,n,[a,r]);let o=qa(t,n),s=qa(t,i);if(o===s)return t=>new mo(e,Ja(o)|Ja(s),[t]);{let t=o<s?[r,a]:[a,r];return new mo(e,Ja(o)|Ja(s),t)}}function lo(e,t,n,r,i,a){let o,s=t;for(;;){let t=co(e,s,n,r,i,a);if(typeof t==`function`)o=Za(t,o),s+=5;else{let e=t;for(;o!=null;)e=o.value(e),o=o.previous;return e}}}var uo,fo,po,mo,ho,go=v((()=>{M(),Rr(),T(),Qa(),no(),Xa(),Ga(),uo=class e{_tag=`EmptyNode`;modify(t,n,r,i,a,o){let s=r(R());return vr(s)?new e:(++o.value,new fo(t,i,a,s))}},fo=class e{edit;hash;key;value;_tag=`LeafNode`;constructor(e,t,n,r){this.edit=e,this.hash=t,this.key=n,this.value=r}modify(t,n,r,i,a,o){if(A(a,this.key)){let n=r(this.value);return n===this.value?this:vr(n)?(--o.value,new uo):ao(this,t)?(this.value=n,this):new e(t,i,a,n)}let s=r(R());return vr(s)?this:(++o.value,lo(t,n,this.hash,this,i,new e(t,i,a,s)))}},po=class e{edit;hash;children;_tag=`CollisionNode`;constructor(e,t,n){this.edit=e,this.hash=t,this.children=n}modify(t,n,r,i,a,o){if(i===this.hash){let n=ao(this,t),i=this.updateCollisionList(n,t,this.hash,this.children,r,a,o);return i===this.children?this:i.length>1?new e(t,this.hash,i):i[0]}let s=r(R());return vr(s)?this:(++o.value,lo(t,n,this.hash,this,i,new fo(t,i,a,s)))}updateCollisionList(e,t,n,r,i,a,o){let s=r.length;for(let c=0;c<s;++c){let s=r[c];if(`key`in s&&A(a,s.key)){let l=s.value,u=i(l);return u===l?r:vr(u)?(--o.value,eo(e,c,r)):$a(e,c,new fo(t,n,a,u),r)}}let c=i(R());return vr(c)?r:(++o.value,$a(e,s,new fo(t,n,a,c),r))}},mo=class e{edit;mask;children;_tag=`IndexedNode`;constructor(e,t,n){this.edit=e,this.mask=t,this.children=n}modify(t,n,r,i,a,o){let s=this.mask,c=this.children,l=qa(n,i),u=Ja(l),d=Ya(s,u),f=s&u,p=ao(this,t);if(!f){let f=new uo().modify(t,n+5,r,i,a,o);return f?c.length>=Ua?so(t,l,f,s,c):new e(t,s|u,to(p,d,f,c)):this}let m=c[d],h=m.modify(t,n+5,r,i,a,o);if(m===h)return this;let g=s,_;if(ro(h)){if(g&=~u,!g)return new uo;if(c.length<=2&&io(c[d^1]))return c[d^1];_=eo(p,d,c)}else _=$a(p,d,h,c);return p?(this.mask=g,this.children=_,this):new e(t,g,_)}},ho=class e{edit;size;children;_tag=`ArrayNode`;constructor(e,t,n){this.edit=e,this.size=t,this.children=n}modify(t,n,r,i,a,o){let s=this.size,c=this.children,l=qa(n,i),u=c[l],d=(u||new uo).modify(t,n+5,r,i,a,o);if(u===d)return this;let f=ao(this,t),p;if(ro(u)&&!ro(d))++s,p=$a(f,l,d,c);else if(!ro(u)&&ro(d)){if(--s,s<=Wa)return oo(t,s,l,c);p=$a(f,l,new uo,c)}else p=$a(f,l,d,c);return f?(this.size=s,this.children=p,this):new e(t,s,p)}}})),_o,vo,yo,bo,xo,So,Co,wo,To,Eo,Do,Oo,ko,Ao,jo,Mo,No,Po,Fo,Io,Lo,Ro,zo,Bo,Vo,Ho,Uo,Wo,Go=v((()=>{M(),S(),Mt(),Xt(),Rr(),F(),T(),Xa(),Ga(),go(),_o=`effect/HashMap`,vo=Symbol.for(_o),yo={[vo]:vo,[Symbol.iterator](){return new xo(this,(e,t)=>[e,t])},[E](){let e=D(_o);for(let t of this)e^=b(D(t[0]),O(D(t[1])));return k(this,e)},[j](e){if(Oo(e)){if(e._size!==this._size)return!1;for(let t of this){let n=b(e,jo(t[0],D(t[0])));if(vr(n)||!A(t[1],n.value))return!1}return!0}return!1},toString(){return Ht(this.toJSON())},toJSON(){return{_id:`HashMap`,values:Array.from(this).map(Bt)}},[N](){return this.toJSON()},pipe(){return P(this,arguments)}},bo=(e,t,n,r)=>{let i=Object.create(yo);return i._editable=e,i._edit=t,i._root=n,i._size=r,i},xo=class e{map;f;v;constructor(e,t){this.map=e,this.f=t,this.v=Co(this.map._root,this.f,void 0)}next(){if(vr(this.v))return{done:!0,value:void 0};let e=this.v.value;return this.v=So(e.cont),{done:!1,value:e.value}}[Symbol.iterator](){return new e(this.map,this.f)}},So=e=>e?wo(e[0],e[1],e[2],e[3],e[4]):R(),Co=(e,t,n=void 0)=>{switch(e._tag){case`LeafNode`:return yr(e.value)?z({value:t(e.key,e.value.value),cont:n}):So(n);case`CollisionNode`:case`ArrayNode`:case`IndexedNode`:{let r=e.children;return wo(r.length,r,0,t,n)}default:return So(n)}},wo=(e,t,n,r,i)=>{for(;n<e;){let a=t[n++];if(a&&!ro(a))return Co(a,r,[e,t,n,r,i])}return So(i)},To=bo(!1,0,new uo,0),Eo=()=>To,Do=e=>{let t=Lo(Eo());for(let n of e)No(t,n[0],n[1]);return Ro(t)},Oo=e=>w(e,vo),ko=e=>e&&ro(e._root),Ao=x(2,(e,t)=>jo(e,t,D(t))),jo=x(3,(e,t,n)=>{let r=e._root,i=0;for(;;)switch(r._tag){case`LeafNode`:return A(t,r.key)?r.value:R();case`CollisionNode`:if(n===r.hash){let e=r.children;for(let n=0,r=e.length;n<r;++n){let r=e[n];if(`key`in r&&A(t,r.key))return r.value}}return R();case`IndexedNode`:{let e=Ja(qa(i,n));if(r.mask&e){r=r.children[Ya(r.mask,e)],i+=5;break}return R()}case`ArrayNode`:if(r=r.children[qa(i,n)],r){i+=5;break}return R();default:return R()}}),Mo=x(2,(e,t)=>yr(jo(e,t,D(t)))),No=x(3,(e,t,n)=>zo(e,t,()=>z(n))),Po=x(3,(e,t,n)=>e._editable?(e._root=t,e._size=n,e):t===e._root?e:bo(e._editable,e._edit,t,n)),Fo=e=>new xo(e,e=>e),Io=e=>e._size,Lo=e=>bo(!0,e._edit+1,e._root,e._size),Ro=e=>(e._editable=!1,e),zo=x(3,(e,t,n)=>Bo(e,t,D(t),n)),Bo=x(4,(e,t,n,r)=>{let i={value:e._size},a=e._root.modify(e._editable?e._edit:NaN,0,r,n,t,i);return b(e,Po(a,i.value))}),Vo=x(2,(e,t)=>zo(e,t,R)),Ho=x(2,(e,t)=>Wo(e,Eo(),(e,n,r)=>No(e,r,t(n,r)))),Uo=x(2,(e,t)=>Wo(e,void 0,(e,n,r)=>t(n,r))),Wo=x(3,(e,t,n)=>{let r=e._root;if(r._tag===`LeafNode`)return yr(r.value)?n(t,r.value.value,r.key):t;if(r._tag===`EmptyNode`)return t;let i=[r.children],a;for(;a=i.pop();)for(let e=0,r=a.length;e<r;){let r=a[e++];r&&!ro(r)&&(r._tag===`LeafNode`?yr(r.value)&&(t=n(t,r.value.value,r.key)):i.push(r.children))}return t})})),Ko,qo,Jo,Yo,Xo,Zo,Qo,$o,es,ts,ns,rs,is,as,os,ss,cs,ls,us,ds,fs=v((()=>{M(),S(),Mt(),Xt(),F(),T(),Go(),Ko=`effect/HashSet`,qo=Symbol.for(Ko),Jo={[qo]:qo,[Symbol.iterator](){return Fo(this._keyMap)},[E](){return k(this,O(D(this._keyMap))(D(Ko)))},[j](e){return Xo(e)?Io(this._keyMap)===Io(e._keyMap)&&A(this._keyMap,e._keyMap):!1},toString(){return Ht(this.toJSON())},toJSON(){return{_id:`HashSet`,values:Array.from(this).map(Bt)}},[N](){return this.toJSON()},pipe(){return P(this,arguments)}},Yo=e=>{let t=Object.create(Jo);return t._keyMap=e,t},Xo=e=>w(e,qo),Zo=Yo(Eo()),Qo=()=>Zo,$o=e=>{let t=rs(Qo());for(let n of e)os(t,n);return is(t)},es=(...e)=>{let t=rs(Qo());for(let n of e)os(t,n);return is(t)},ts=x(2,(e,t)=>Mo(e._keyMap,t)),ns=e=>Io(e._keyMap),rs=e=>Yo(Lo(e._keyMap)),is=e=>(e._keyMap._editable=!1,e),as=x(2,(e,t)=>{let n=rs(e);return t(n),is(n)}),os=x(2,(e,t)=>e._keyMap._editable?(No(t,!0)(e._keyMap),e):Yo(No(t,!0)(e._keyMap))),ss=x(2,(e,t)=>e._keyMap._editable?(Vo(t)(e._keyMap),e):Yo(Vo(t)(e._keyMap))),cs=x(2,(e,t)=>as(e,e=>{for(let n of t)ss(e,n)})),ls=x(2,(e,t)=>as(Qo(),n=>{us(e,e=>os(n,e));for(let e of t)os(n,e)})),us=x(2,(e,t)=>Uo(e._keyMap,(e,n)=>t(n))),ds=x(3,(e,t,n)=>Wo(e._keyMap,t,(e,t,r)=>n(e,r)))})),ps,ms,hs,gs,_s,vs,ys,bs,xs,Ss,Cs=v((()=>{fs(),ps=Qo,ms=$o,hs=es,gs=ts,_s=ns,vs=os,ys=ss,bs=cs,xs=ls,Ss=ds})),ws,Ts,Es,Ds,Os,ks=v((()=>{ws=`Empty`,Ts=`Fail`,Es=`Interrupt`,Ds=`Parallel`,Os=`Sequential`})),As,js,Ms,Ns,Ps,Fs,Is,Ls,Rs,zs,Bs,Vs,Hs,Us,Ws,Gs,Ks,qs,Js,Ys,Xs,Zs,Qs,$s,ec,tc,nc,rc,ic,ac,oc,sc,cc,lc,uc,dc,fc,pc,mc,hc,gc,_c,vc,yc,bc=v((()=>{Pi(),Ba(),lr(),M(),S(),Ie(),Mt(),Cs(),Xt(),Rr(),F(),T(),rt(),ks(),As=`effect/Cause`,js=Symbol.for(As),Ms={_E:e=>e},Ns={[js]:Ms,[E](){return b(D(As),O(D(tc(this))),k(this))},[j](e){return Bs(e)&&ec(this,e)},pipe(){return P(this,arguments)},toJSON(){switch(this._tag){case`Empty`:return{_id:`Cause`,_tag:this._tag};case`Die`:return{_id:`Cause`,_tag:this._tag,defect:Bt(this.defect)};case`Interrupt`:return{_id:`Cause`,_tag:this._tag,fiberId:this.fiberId.toJSON()};case`Fail`:return{_id:`Cause`,_tag:this._tag,failure:Bt(this.error)};case`Sequential`:case`Parallel`:return{_id:`Cause`,_tag:this._tag,left:Bt(this.left),right:Bt(this.right)}}},toString(){return dc(this)},[N](){return this.toJSON()}},Ps=(()=>{let e=Object.create(Ns);return e._tag=ws,e})(),Fs=e=>{let t=Object.create(Ns);return t._tag=Ts,t.error=e,t},Is=e=>{let t=Object.create(Ns);return t._tag=`Die`,t.defect=e,t},Ls=e=>{let t=Object.create(Ns);return t._tag=Es,t.fiberId=e,t},Rs=(e,t)=>{let n=Object.create(Ns);return n._tag=Ds,n.left=e,n.right=t,n},zs=(e,t)=>{let n=Object.create(Ns);return n._tag=Os,n.left=e,n.right=t,n},Bs=e=>w(e,js),Vs=e=>e._tag===ws,Hs=e=>e._tag===Ts,Us=e=>e._tag===`Empty`||lc(e,!0,(e,t)=>{switch(t._tag){case ws:return z(e);case`Die`:case Ts:case Es:return z(!1);default:return R()}}),Ws=e=>yr(Zs(e)),Gs=e=>uc(void 0,ac)(e),Ks=e=>Da(lc(e,ya(),(e,t)=>t._tag===`Fail`?z(b(e,Ma(t.error))):R())),qs=e=>Da(lc(e,ya(),(e,t)=>t._tag===`Die`?z(b(e,Ma(t.defect))):R())),Js=e=>lc(e,ps(),(e,t)=>t._tag===`Interrupt`?z(b(e,vs(t.fiberId))):R()),Ys=e=>rc(e,e=>e._tag===`Fail`?z(e.error):R()),Xs=e=>{let t=Ys(e);switch(t._tag){case`None`:return I(e);case`Some`:return L(t.value)}},Zs=e=>rc(e,e=>e._tag===`Interrupt`?z(e.fiberId):R()),Qs=e=>cc(e,{onEmpty:Ps,onFail:()=>Ps,onDie:Is,onInterrupt:Ls,onSequential:zs,onParallel:Rs}),$s=e=>cc(e,{onEmpty:Ps,onFail:Is,onDie:Is,onInterrupt:Ls,onSequential:zs,onParallel:Rs}),ec=(e,t)=>{let n=xa(e),r=xa(t);for(;Ia(n)&&Ia(r);){let[e,t]=b(Ra(n),lc([ps(),ya()],([e,t],n)=>{let[r,i]=ic(n);return z([b(e,xs(r)),b(t,Pa(i))])})),[i,a]=b(Ra(r),lc([ps(),ya()],([e,t],n)=>{let[r,i]=ic(n);return z([b(e,xs(r)),b(t,Pa(i))])}));if(!A(e,i))return!1;n=t,r=a}return!0},tc=e=>nc(xa(e),ya()),nc=(e,t)=>{for(;;){let[n,r]=b(e,Oi([ps(),ya()],([e,t],n)=>{let[r,i]=ic(n);return[b(e,xs(r)),b(t,Pa(i))]})),i=_s(n)>0?b(t,Ma(n)):t;if(Fa(r))return Da(i);e=r,t=i}throw Error(nt(`Cause.flattenCauseLoop`))},rc=x(2,(e,t)=>{let n=[e];for(;n.length>0;){let e=n.pop(),r=t(e);switch(r._tag){case`None`:switch(e._tag){case Os:case Ds:n.push(e.right),n.push(e.left)}break;case`Some`:return r}}return R()}),ic=e=>{let t=e,n=[],r=ps(),i=ya();for(;t!==void 0;)switch(t._tag){case ws:if(n.length===0)return[r,i];t=n.pop();break;case Ts:if(r=vs(r,ba(t._tag,t.error)),n.length===0)return[r,i];t=n.pop();break;case`Die`:if(r=vs(r,ba(t._tag,t.defect)),n.length===0)return[r,i];t=n.pop();break;case Es:if(r=vs(r,ba(t._tag,t.fiberId)),n.length===0)return[r,i];t=n.pop();break;case Os:switch(t.left._tag){case ws:t=t.right;break;case Os:t=zs(t.left.left,zs(t.left.right,t.right));break;case Ds:t=Rs(zs(t.left.left,t.right),zs(t.left.right,t.right));break;default:i=Ma(i,t.right),t=t.left}break;case Ds:n.push(t.right),t=t.left}throw Error(nt(`Cause.evaluateCauseLoop`))},ac={emptyCase:Se,failCase:Ce,dieCase:Ce,interruptCase:Se,sequentialCase:(e,t,n)=>t&&n,parallelCase:(e,t,n)=>t&&n},oc=`SequentialCase`,sc=`ParallelCase`,cc=x(2,(e,{onDie:t,onEmpty:n,onFail:r,onInterrupt:i,onParallel:a,onSequential:o})=>uc(e,void 0,{emptyCase:()=>n,failCase:(e,t)=>r(t),dieCase:(e,n)=>t(n),interruptCase:(e,t)=>i(t),sequentialCase:(e,t,n)=>o(t,n),parallelCase:(e,t,n)=>a(t,n)})),lc=x(3,(e,t,n)=>{let r=t,i=e,a=[];for(;i!==void 0;){let e=n(r,i);switch(r=yr(e)?e.value:r,i._tag){case Os:a.push(i.right),i=i.left;break;case Ds:a.push(i.right),i=i.left;break;default:i=void 0}i===void 0&&a.length>0&&(i=a.pop())}return r}),uc=x(3,(e,t,n)=>{let r=[e],i=[];for(;r.length>0;){let e=r.pop();switch(e._tag){case ws:i.push(I(n.emptyCase(t)));break;case Ts:i.push(I(n.failCase(t,e.error)));break;case`Die`:i.push(I(n.dieCase(t,e.defect)));break;case Es:i.push(I(n.interruptCase(t,e.fiberId)));break;case Os:r.push(e.right),r.push(e.left),i.push(L({_tag:oc}));break;case Ds:r.push(e.right),r.push(e.left),i.push(L({_tag:sc}))}}let a=[];for(;i.length>0;){let e=i.pop();switch(e._tag){case`Left`:switch(e.left._tag){case oc:{let e=a.pop(),r=a.pop(),i=n.sequentialCase(t,e,r);a.push(i);break}case sc:{let e=a.pop(),r=a.pop(),i=n.parallelCase(t,e,r);a.push(i);break}}break;case`Right`:a.push(e.right)}}if(a.length===0)throw Error(`BUG: Cause.reduceWithContext - please report an issue at https://github.com/Effect-TS/effect/issues`);return a.pop()}),dc=(e,t)=>Gs(e)?`All fibers interrupted without errors.`:yc(e).map(function(e){return t?.renderErrorCause!==!0||e.cause===void 0?e.stack:`${e.stack} {\n${fc(e.cause,` `)}\n}`}).join(`
5
- `),fc=(e,t)=>{let n=e.stack.split(`
6
- `),r=`${t}[cause]: ${n[0]}`;for(let e=1,i=n.length;e<i;e++)r+=`\n${t}${n[e]}`;return e.cause&&(r+=` {\n${fc(e.cause,`${t} `)}\n${t}}`),r},pc=e=>{let t=typeof e==`object`&&!!e,n=Error.stackTraceLimit;Error.stackTraceLimit=1;let r=Error(mc(e),t&&`cause`in e&&e.cause!==void 0?{cause:pc(e.cause)}:void 0);return Error.stackTraceLimit=n,r.message===``&&(r.message=`An error has occurred`),Error.stackTraceLimit=n,r.name=e instanceof Error?e.name:`Error`,t&&(vc in e&&(r.span=e[vc]),Object.keys(e).forEach(t=>{t in r||(r[t]=e[t])})),r.stack=_c(`${r.name}: ${r.message}`,e instanceof Error&&e.stack?e.stack:``,r.span),r},mc=e=>{if(typeof e==`string`)return e;if(typeof e==`object`&&e&&e instanceof Error)return e.message;try{if(w(e,`toString`)&&Ue(e.toString)&&e.toString!==Object.prototype.toString&&e.toString!==globalThis.Array.prototype.toString)return e.toString()}catch{}return Wt(e)},hc=/\((.*)\)/g,gc=C(`effect/Tracer/spanToTrace`,()=>new WeakMap),_c=(e,t,n)=>{let r=[e],i=t.startsWith(e)?t.slice(e.length).split(`
2
+ // @bun
3
+ var x=(e,t,n)=>()=>{if(e)try{t=e(e=0)}catch(r){n=[r]}if(n)throw n[0];return t};function Yn(e,t=new WeakSet){if(t.has(e))return;t.add(e);for(let n of Reflect.ownKeys(e)){let r=Object.getOwnPropertyDescriptor(e,n);if(r&&"value"in r&&Vf(r.value))Yn(r.value,t)}Object.freeze(e)}function Vf(e){return typeof e==="object"&&e!==null}var vr="0.15",Tn="state-0.16";var B_=()=>{};function Zi(e){return{ok:!0,value:e}}function Jo(e){return{ok:!1,error:e}}function ys(e,t){return new We("invalid_input",`Invalid ${e}.`,{field:e},t===void 0?void 0:{cause:t})}var We;var Xi=x(()=>{We=class We extends Error{code;details;constructor(e,t,n={},r){super(t,r);this.name="CoreError",this.code=e,this.details=n,Yn(this.details),Object.freeze(this)}}});function g(e,t,n,r,o,i,a,s,c){switch(arguments.length){case 1:return e;case 2:return t(e);case 3:return n(t(e));case 4:return r(n(t(e)));case 5:return o(r(n(t(e))));case 6:return i(o(r(n(t(e)))));case 7:return a(i(o(r(n(t(e))))));case 8:return s(a(i(o(r(n(t(e)))))));case 9:return c(s(a(i(o(r(n(t(e))))))));default:{let l=arguments[0];for(let u=1;u<arguments.length;u++)l=arguments[u](l);return l}}}var Bf=(e)=>typeof e==="function",d=function(e,t){if(typeof e==="function")return function(){if(e(arguments))return t.apply(this,arguments);return(n)=>t(n,...arguments)};switch(e){case 0:case 1:throw RangeError(`Invalid arity ${e}`);case 2:return function(n,r){if(arguments.length>=2)return t(n,r);return function(o){return t(o,n)}};case 3:return function(n,r,o){if(arguments.length>=3)return t(n,r,o);return function(i){return t(i,n,r)}};case 4:return function(n,r,o,i){if(arguments.length>=4)return t(n,r,o,i);return function(a){return t(a,n,r,o)}};case 5:return function(n,r,o,i,a){if(arguments.length>=5)return t(n,r,o,i,a);return function(s){return t(s,n,r,o,i)}};default:return function(){if(arguments.length>=e)return t.apply(this,arguments);let n=arguments;return function(r){return t(r,...n)}}}},ue=(e)=>e,xs=(e)=>()=>e,Ss,no,zl,_s;var j=x(()=>{Ss=xs(!0),no=xs(!1),zl=xs(void 0),_s=zl});var ws=(e)=>(t,n)=>t===n||e(t,n),XI=(e,t)=>e===t,QI=()=>XI,eM,Kf,K_,z_=(e)=>ws((t,n)=>{if(t.length!==n.length)return!1;for(let r=0;r<t.length;r++)if(!e(t[r],n[r]))return!1;return!0});var vs=x(()=>{j();eM=QI(),Kf=d(2,(e,t)=>ws((n,r)=>e(t(n),t(r)))),K_=Kf(eM,(e)=>e.getTime())});var Ts,V=(e,t)=>{if(!Ts)globalThis["effect/GlobalValue"]??=new Map,Ts=globalThis["effect/GlobalValue"];if(!Ts.has(e))Ts.set(e,t());return Ts.get(e)};var gt=(e)=>typeof e==="string",Qt=(e)=>typeof e==="number",Go=(e)=>typeof e==="boolean",ro=(e)=>typeof e==="bigint",Yo=(e)=>typeof e==="symbol",oo,W_=(e)=>e===void 0,J_=(e)=>!1,Es=(e)=>typeof e==="object"&&e!==null,qt=(e)=>Es(e)||oo(e),C,Os,Zo=(e)=>e===null||e===void 0,G_=(e)=>e!==null&&e!==void 0,Jl=(e)=>e instanceof Date,zf=(e)=>typeof e==="string"||C(e,Symbol.iterator),Wf=(e)=>Es(e)&&!Array.isArray(e),Y_=(e)=>C(e,"then")&&oo(e.then);var ye=x(()=>{j();oo=Bf,C=d(2,(e,t)=>qt(e)&&(t in e)),Os=d(2,(e,t)=>C(e,"_tag")&&e._tag===t)});var Xo=(e)=>`BUG: ${e} - please report an issue at https://github.com/Effect-TS/effect/issues`;class Gf{_state;constructor(e,t,n,r){if(Zo(t)&&Zo(e))t=Math.random()*4294967295>>>0,e=0;else if(Zo(t))t=e,e=0;if(Zo(r)&&Zo(n))r=this._state?this._state[3]:nM,n=this._state?this._state[2]:tM;else if(Zo(r))r=n,n=0;return this._state=new Int32Array([0,0,n>>>0,((r||0)|1)>>>0]),this._next(),Z_(this._state,this._state[0],this._state[1],e>>>0,t>>>0),this._next(),this}getState(){return[this._state[0],this._state[1],this._state[2],this._state[3]]}setState(e){this._state[0]=e[0],this._state[1]=e[1],this._state[2]=e[2],this._state[3]=e[3]|1}integer(e){return Math.round(this.number()*Number.MAX_SAFE_INTEGER)%e}number(){let e=(this._next()&67108863)*1,t=(this._next()&134217727)*1;return(e*aM+t)/iM}_next(){let e=this._state[0]>>>0,t=this._state[1]>>>0;sM(this._state,e,t,rM,oM),Z_(this._state,this._state[0],this._state[1],this._state[2],this._state[3]);let n=e>>>18,r=(t>>>18|e<<14)>>>0;n=(n^e)>>>0,r=(r^t)>>>0;let o=(r>>>27|n<<5)>>>0,i=e>>>27,a=(-i>>>0&31)>>>0;return(o>>>i|o<<a)>>>0}}function sM(e,t,n,r,o){let i=(n>>>16)*(o&65535)>>>0,a=(n&65535)*(o>>>16)>>>0,s=(n&65535)*(o&65535)>>>0,c=(n>>>16)*(o>>>16)+((a>>>16)+(i>>>16))>>>0;if(a=a<<16>>>0,s=s+a>>>0,s>>>0<a>>>0)c=c+1>>>0;if(i=i<<16>>>0,s=s+i>>>0,s>>>0<i>>>0)c=c+1>>>0;c=c+Math.imul(n,r)>>>0,c=c+Math.imul(t,o)>>>0,e[0]=c,e[1]=s}function Z_(e,t,n,r,o){let i=t+r>>>0,a=n+o>>>0;if(a>>>0<n>>>0)i=i+1|0;e[0]=i,e[1]=a}function Yf(e){if(typeof e==="object"&&e!==null&&Jf in e)return e[Jf]();throw Error(Xo("yieldWrapGet"))}var ea,tM=335903614,nM=4150755663,rM=1481765933,oM=1284865837,iM=9007199254740992,aM=134217728,Jf,Tr,$t,X_,cM,lM,yt,v1;var io=x(()=>{ye();ea=class ea{self;called=!1;constructor(e){this.self=e}next(e){return this.called?{value:e,done:!0}:(this.called=!0,{value:this.self,done:!1})}return(e){return{value:e,done:!0}}throw(e){throw e}[Symbol.iterator](){return new ea(this.self)}};Jf=Symbol.for("effect/Utils/YieldWrap");Tr=class Tr{#e;constructor(e){this.#e=e}[Jf](){return this.#e}};$t=V("effect/Utils/isStructuralRegion",()=>({enabled:!1,tester:void 0})),X_={effect_internal_function:(e)=>e()},cM={effect_internal_function:(e)=>{try{return e()}finally{}}},lM=X_.effect_internal_function(()=>Error().stack)?.includes("effect_internal_function")===!0,yt=lM?X_.effect_internal_function:cM.effect_internal_function,v1=function*(){}.constructor});var Zf,M,E=(e)=>{if($t.enabled===!0)return 0;switch(typeof e){case"number":return Yl(e);case"bigint":return he(e.toString(10));case"boolean":return he(String(e));case"symbol":return he(String(e));case"string":return he(e);case"undefined":return he("undefined");case"function":case"object":if(e===null)return he("null");else if(e instanceof Date){if(Number.isNaN(e.getTime()))return he("Invalid Date");return E(e.toISOString())}else if(e instanceof URL)return E(e.href);else if(pM(e))return e[M]();else return Rs(e);default:throw Error(`BUG: unhandled typeof ${typeof e} - please report an issue at https://github.com/Effect-TS/effect/issues`)}},Rs=(e)=>{if(!Zf.has(e))Zf.set(e,Yl(Math.floor(Math.random()*Number.MAX_SAFE_INTEGER)));return Zf.get(e)},G=(e)=>(t)=>t*53^e,Gl=(e)=>e&3221225471|e>>>1&1073741824,pM=(e)=>C(e,M),Yl=(e)=>{if(e!==e||e===1/0)return 0;let t=e|0;if(t!==e)t^=e*4294967295;while(e>4294967295)t^=e/=4294967295;return Gl(t)},he=(e)=>{let t=5381,n=e.length;while(n)t=t*33^e.charCodeAt(--n);return Gl(t)},dM=(e,t)=>{let n=12289;for(let r=0;r<t.length;r++)n^=g(he(t[r]),G(E(e[t[r]])));return Gl(n)},Zl=(e)=>dM(e,Object.keys(e)),en=(e)=>{let t=6151;for(let n=0;n<e.length;n++)t=g(t,G(E(e[n])));return Gl(t)},ie=function(){if(arguments.length===1){let n=arguments[0];return function(r){return Object.defineProperty(n,M,{value(){return r},enumerable:!1}),r}}let e=arguments[0],t=arguments[1];return Object.defineProperty(e,M,{value(){return t},enumerable:!1}),t};var Me=x(()=>{j();ye();io();Zf=V(Symbol.for("effect/Hash/randomHashCache"),()=>new WeakMap),M=Symbol.for("effect/Hash")});function O(){if(arguments.length===1)return(e)=>Xl(e,arguments[0]);return Xl(arguments[0],arguments[1])}function Xl(e,t){if(e===t)return!0;let n=typeof e;if(n!==typeof t)return!1;if(n==="object"||n==="function"){if(e!==null&&t!==null){if(ks(e)&&ks(t))if(E(e)===E(t)&&e[I](t))return!0;else return $t.enabled&&$t.tester?$t.tester(e,t):!1;else if(e instanceof Date&&t instanceof Date){let r=e.getTime(),o=t.getTime();return r===o||Number.isNaN(r)&&Number.isNaN(o)}else if(e instanceof URL&&t instanceof URL)return e.href===t.href}if($t.enabled){if(e===null||t===null)return!1;if(Array.isArray(e)&&Array.isArray(t))return e.length===t.length&&e.every((r,o)=>Xl(r,t[o]));if(Object.getPrototypeOf(e)===Object.prototype&&Object.getPrototypeOf(t)===Object.prototype){let r=Object.keys(e),o=Object.keys(t);if(r.length===o.length){for(let i of r)if(!((i in t)&&Xl(e[i],t[i])))return $t.tester?$t.tester(e,t):!1;return!0}}return $t.tester?$t.tester(e,t):!1}}return $t.enabled&&$t.tester?$t.tester(e,t):!1}var I,ks=(e)=>C(e,I),Cs=()=>O;var pe=x(()=>{Me();ye();io();I=Symbol.for("effect/Equal")});function fM(e){try{return e.toISOString()}catch{return"Invalid Date"}}function mM(e){try{let t=e.toString();return typeof t==="string"?t:String(t)}catch{return"[toString threw]"}}function As(e){return gt(e)?JSON.stringify(e):String(e)}function Zn(e,t){let n=t?.space??0,r=new WeakSet,o=!n?"":Qt(n)?" ".repeat(n):n,i=(l)=>o.repeat(l),a=(l,u)=>{let p=l?.constructor;return p&&p!==Object.prototype.constructor&&p.name?`${p.name}(${u})`:u},s=(l)=>{try{return Reflect.ownKeys(l)}catch{return["[ownKeys threw]"]}};function c(l,u=0){if(Array.isArray(l)){if(r.has(l))return Xf;if(r.add(l),!o||l.length<=1)return`[${l.map((f)=>c(f,u)).join(",")}]`;let p=l.map((f)=>c(f,u+1)).join(`,
4
+ `+i(u+1));return`[
5
+ ${i(u+1)}${p}
6
+ ${i(u)}]`}if(Jl(l))return fM(l);if(!t?.ignoreToString&&C(l,"toString")&&oo(l.toString)&&l.toString!==Object.prototype.toString&&l.toString!==Array.prototype.toString){let p=mM(l);if(l instanceof Error&&l.cause)return`${p} (cause: ${c(l.cause,u)})`;return p}if(gt(l))return JSON.stringify(l);if(Qt(l)||l==null||Go(l)||Yo(l))return String(l);if(ro(l))return String(l)+"n";if(l instanceof Set||l instanceof Map){if(r.has(l))return Xf;return r.add(l),`${l.constructor.name}(${c(Array.from(l),u)})`}if(qt(l)){if(r.has(l))return Xf;r.add(l);let p=s(l);if(!o||p.length<=1){let h=`{${p.map((m)=>`${As(m)}:${c(l[m],u)}`).join(",")}}`;return a(l,h)}let f=`{
7
+ ${p.map((h)=>`${i(u+1)}${As(h)}: ${c(l[h],u+1)}`).join(`,
8
+ `)}
9
+ ${i(u)}}`;return a(l,f)}return String(l)}return c(e,0)}var ne,de=(e)=>{try{if(C(e,"toJSON")&&oo(e.toJSON)&&e.toJSON.length===0)return e.toJSON();else if(Array.isArray(e))return e.map(de)}catch{return{}}return tb(e)},Xf="[Circular]",ge=(e)=>JSON.stringify(e,null,2),P1,Er=(e,t=2)=>{if(typeof e==="string")return e;try{return typeof e==="object"?Ql(e,t):String(e)}catch{return String(e)}},Ql=(e,t)=>{let n=[],r=JSON.stringify(e,(o,i)=>typeof i==="object"&&i!==null?n.includes(i)?void 0:n.push(i)&&(Qo.fiberRefs!==void 0&&Q_(i)?i[Qf](Qo.fiberRefs):i):i,t);return n=void 0,r},Qf,Q_=(e)=>typeof e==="object"&&e!==null&&(Qf in e),Qo,eb=(e,t)=>{let n=Qo.fiberRefs;Qo.fiberRefs=e;try{return t()}finally{Qo.fiberRefs=n}},tb=(e)=>{if(Q_(e)&&Qo.fiberRefs!==void 0)return e[Qf](Qo.fiberRefs);return e};var Ve=x(()=>{ye();ne=Symbol.for("nodejs.util.inspect.custom");P1={toJSON(){return de(this)},[ne](){return this.toJSON()},toString(){return ge(this.toJSON())}},Qf=Symbol.for("effect/Inspectable/Redactable"),Qo=V("effect/Inspectable/redactableState",()=>({fiberRefs:void 0}))});var T=(e,t)=>{switch(t.length){case 0:return e;case 1:return t[0](e);case 2:return t[1](t[0](e));case 3:return t[2](t[1](t[0](e)));case 4:return t[3](t[2](t[1](t[0](e))));case 5:return t[4](t[3](t[2](t[1](t[0](e)))));case 6:return t[5](t[4](t[3](t[2](t[1](t[0](e))))));case 7:return t[6](t[5](t[4](t[3](t[2](t[1](t[0](e)))))));case 8:return t[7](t[6](t[5](t[4](t[3](t[2](t[1](t[0](e))))))));case 9:return t[8](t[7](t[6](t[5](t[4](t[3](t[2](t[1](t[0](e)))))))));default:{let n=e;for(let r=0,o=t.length;r<o;r++)n=t[r](n);return n}}};var be=()=>{};var ti="Async",ni="Commit",jt="Failure",Ps="OnFailure",ta="OnSuccess",na="OnSuccessAndFailure",Vt="Success",eu="Sync",nb="Tag",ri="UpdateRuntimeFlags",ra="While",oa="Iterator",tu="WithRuntime",ia="Yield",Is="RevertFlags";var hM="3.22.1",Ms=()=>hM;var ob,ib,ab,sb,ao,gM,yM,Or,Ns,so,tm,cb;var Rr=x(()=>{pe();Me();be();io();ob=Symbol.for("effect/Effect"),ib=Symbol.for("effect/Stream"),ab=Symbol.for("effect/Sink"),sb=Symbol.for("effect/Channel"),ao={_R:(e)=>e,_E:(e)=>e,_A:(e)=>e,_V:Ms()},gM={_A:(e)=>e,_In:(e)=>e,_L:(e)=>e,_E:(e)=>e,_R:(e)=>e},yM={_Env:(e)=>e,_InErr:(e)=>e,_InElem:(e)=>e,_InDone:(e)=>e,_OutErr:(e)=>e,_OutElem:(e)=>e,_OutDone:(e)=>e},Or={[ob]:ao,[ib]:ao,[ab]:gM,[sb]:yM,[I](e){return this===e},[M](){return ie(this,Rs(this))},[Symbol.iterator](){return new ea(new Tr(this))},pipe(){return T(this,arguments)}},Ns={[M](){return ie(this,Zl(this))},[I](e){let t=Object.keys(this),n=Object.keys(e);if(t.length!==n.length)return!1;for(let r of t)if(!((r in e)&&O(this[r],e[r])))return!1;return!0}},so={...Or,_op:ni},tm={...so,...Ns},cb=function(){function e(){}return e.prototype=so,e}()});var ub,pb,xM,SM,_M,nm=(e)=>C(e,ub),rm=(e)=>e._tag==="None",om=(e)=>e._tag==="Some",nu,Fs=(e)=>{let t=Object.create(xM);return t.value=e,t};var im=x(()=>{pe();Me();Ve();ye();Rr();ub=Symbol.for("effect/Option"),pb={...Or,[ub]:{_A:(e)=>e},[ne](){return this.toJSON()},toString(){return ge(this.toJSON())}},xM=Object.assign(Object.create(pb),{_tag:"Some",_op:"Some",[I](e){return nm(e)&&om(e)&&O(this.value,e.value)},[M](){return ie(this,G(E(this._tag))(E(this.value)))},toJSON(){return{_id:"Option",_tag:this._tag,value:de(this.value)}}}),SM=E("None"),_M=Object.assign(Object.create(pb),{_tag:"None",_op:"None",[I](e){return nm(e)&&rm(e)},[M](){return SM},toJSON(){return{_id:"Option",_tag:this._tag}}}),nu=Object.create(_M)});var am,fb,bM,wM,ru=(e)=>C(e,am),sm=(e)=>e._tag==="Left",cm=(e)=>e._tag==="Right",mb=(e)=>{let t=Object.create(wM);return t.left=e,t},hb=(e)=>{let t=Object.create(bM);return t.right=e,t};var gb=x(()=>{pe();Me();Ve();ye();Rr();am=Symbol.for("effect/Either"),fb={...Or,[am]:{_R:(e)=>e},[ne](){return this.toJSON()},toString(){return ge(this.toJSON())}},bM=Object.assign(Object.create(fb),{_tag:"Right",_op:"Right",[I](e){return ru(e)&&cm(e)&&O(this.right,e.right)},[M](){return G(E(this._tag))(E(this.right))},toJSON(){return{_id:"Either",_tag:this._tag,right:de(this.right)}}}),wM=Object.assign(Object.create(fb),{_tag:"Left",_op:"Left",[I](e){return ru(e)&&sm(e)&&O(this.left,e.left)},[M](){return G(E(this._tag))(E(this.left))},toJSON(){return{_id:"Either",_tag:this._tag,left:de(this.left)}}})});var Q,W,lm,Ee,Ot,ou,yb,Ls,xb,um,Sb;var tn=x(()=>{j();gb();Q=hb,W=mb,lm=ru,Ee=sm,Ot=cm,ou=d(2,(e,t)=>Ee(e)?W(t(e.left)):Q(e.right)),yb=d(2,(e,t)=>Ot(e)?Q(t(e.right)):W(e.left)),Ls=d(2,(e,{onLeft:t,onRight:n})=>Ee(e)?t(e.left):n(e.right)),xb=Ls({onLeft:ue,onRight:ue}),um=d(2,(e,t)=>{if(Ot(e))return e.right;throw t(e.left)}),Sb=um(()=>Error("getOrThrow called on a Left"))});var pm=(e)=>e.length>0;var _b=(e)=>(t,n)=>t===n?0:e(t,n),bb,iu,dm=(e)=>d(2,(t,n)=>e(t,n)===1);var au=x(()=>{j();bb=_b((e,t)=>e<t?-1:1),iu=d(2,(e,t)=>_b((n,r)=>e(t(n),t(r))))});var A=()=>nu,F,Ne,Re,Je,Oe,En,wb,kr=(e)=>e==null?A():F(e),Bt,vb=(e)=>(...t)=>{try{return F(e(...t))}catch{return A()}},On,Rn,Tb,OM=(e)=>d(2,(t,n)=>Ne(t)?!1:e(t.value,n)),RM,Eb,Ob;var Ge=x(()=>{pe();j();im();F=Fs,Ne=rm,Re=om,Je=d(2,(e,{onNone:t,onSome:n})=>Ne(e)?t():n(e.value)),Oe=d(2,(e,t)=>Ne(e)?t():e.value),En=d(2,(e,t)=>Ne(e)?t():e),wb=d(2,(e,t)=>Ne(e)?F(t()):e),Bt=Oe(zl),On=d(2,(e,t)=>Ne(e)?A():F(t(e.value))),Rn=d(2,(e,t)=>Ne(e)?A():t(e.value)),Tb=d(2,(e,t)=>Ne(e)?A():kr(t(e.value))),RM=Cs(),Eb=OM(RM),Ob=d(2,(e,t)=>Ne(e)?!1:t(e.value))});var Rb=(...e)=>e;var kb=()=>{};var oi=(e)=>Array(e),mm,ke=(e)=>Array.isArray(e)?e:Array.from(e),hm=(e)=>Array.isArray(e)?e:[e],Cb,aa,Ab,gm,ym,CM=(e)=>e.length===0,Pb,co,we,Ib=(e,t)=>e<0||e>=t.length,AM=(e,t)=>Math.floor(Math.min(Math.max(0,e),t.length)),PM,xm,Cr,et,Mb=(e)=>we(e)?F(Sm(e)):A(),Sm=(e)=>e[e.length-1],kn=(e)=>e.slice(1),IM=(e,t)=>{let n=0;for(let r of e){if(!t(r,n))break;n++}return n},Nb,Fb,_m=(e)=>Array.from(e).reverse(),Ar,bm,Lb,MM,NM,FM,sa=(e)=>e.slice(),LM,lo,Pr=()=>[],Rt=(e)=>[e],Cn,Ds,su,cu,ca,wm=(e,t)=>{let n=[],r=e,o;while(Re(o=t(r))){let[i,a]=o.value;n.push(i),r=a}return n},uo,Db,vm=(e)=>Db(e,Cs()),Ir;var Be=x(()=>{pe();vs();j();Ge();kb();mm=d(2,(e,t)=>{let n=Math.max(1,Math.floor(e)),r=Array(n);for(let o=0;o<n;o++)r[o]=t(o);return r}),Cb=d(2,(e,{onEmpty:t,onNonEmpty:n})=>we(e)?n(et(e),kn(e)):t()),aa=d(2,(e,t)=>[t,...e]),Ab=d(2,(e,t)=>[...e,t]),gm=d(2,(e,t)=>ke(e).concat(ke(t))),ym=Array.isArray,Pb=CM,co=pm,we=pm,PM=d(2,(e,t)=>{let n=Math.floor(t);return Ib(n,e)?A():F(e[n])}),xm=d(2,(e,t)=>{let n=Math.floor(t);if(Ib(n,e))throw Error(`Index ${n} out of bounds`);return e[n]}),Cr=PM(0),et=xm(0),Nb=d(2,(e,t)=>NM(e,IM(e,t))),Fb=d(2,(e,t)=>{let n=ke(e);return n.slice(AM(t,n),n.length)}),Ar=d(2,(e,t)=>{let n=Array.from(e);return n.sort(t),n}),bm=d(2,(e,t)=>Lb(e,t,Rb)),Lb=d(3,(e,t,n)=>{let r=ke(e),o=ke(t);if(we(r)&&we(o)){let i=[n(et(r),et(o))],a=Math.min(r.length,o.length);for(let s=1;s<a;s++)i[s]=n(r[s],o[s]);return i}return[]}),MM=Cs(),NM=d(2,(e,t)=>{let n=Array.from(e),r=Math.floor(t);if(we(n)){if(r>=1)return FM(n,r);return[[],n]}return[n,[]]}),FM=d(2,(e,t)=>{let n=Math.max(1,Math.floor(t));return n>=e.length?[sa(e),[]]:[aa(e.slice(1,n),et(e)),e.slice(n)]}),LM=d(3,(e,t,n)=>{let r=ke(e),o=ke(t);if(we(r)){if(we(o))return Db(n)(gm(r,o));return r}return o}),lo=d(2,(e,t)=>LM(e,t,MM)),Cn=d(2,(e,t)=>e.map(t)),Ds=d(2,(e,t)=>{if(Pb(e))return[];let n=[];for(let r=0;r<e.length;r++){let o=t(e[r],r);for(let i=0;i<o.length;i++)n.push(o[i])}return n}),su=Ds(ue),cu=d(2,(e,t)=>{let n=ke(e),r=[];for(let o=0;o<n.length;o++){let i=t(n[o],o);if(Re(i))r.push(i.value)}return r}),ca=d(3,(e,t,n)=>ke(e).reduce((r,o,i)=>n(r,o,i),t)),uo=z_,Db=d(2,(e,t)=>{let n=ke(e);if(we(n)){let r=[et(n)],o=kn(n);for(let i of o)if(r.every((a)=>!t(i,a)))r.push(i);return r}return[]}),Ir=d(2,(e,t)=>ke(e).join(t))});function HM(e,t,n,r,o){for(let i=t;i<Math.min(e.length,t+o);i++)n[r+i-t]=e[i];return n}var Ub,Hb,$M=(e)=>ws((t,n)=>t.length===n.length&&Mr(t).every((r,o)=>e(r,la(n,o)))),jM,VM,ot=(e)=>{let t=Object.create(VM);switch(t.backing=e,e._tag){case"IEmpty":{t.length=0,t.depth=0,t.left=t,t.right=t;break}case"IConcat":{t.length=e.left.length+e.right.length,t.depth=1+Math.max(e.left.depth,e.right.depth),t.left=e.left,t.right=e.right;break}case"IArray":{t.length=e.array.length,t.depth=0,t.left=Xn,t.right=Xn;break}case"ISingleton":{t.length=1,t.depth=0,t.left=Xn,t.right=Xn;break}case"ISlice":{t.length=e.length,t.depth=e.chunk.depth+1,t.left=Xn,t.right=Xn;break}}return t},$b=(e)=>C(e,Ub),Xn,dn=()=>Xn,qs=(...e)=>zM(e),tt=(e)=>ot({_tag:"ISingleton",a:e}),lu=(e)=>$b(e)?e:Us(ke(e)),Tm=(e,t,n)=>{switch(e.backing._tag){case"IArray":{HM(e.backing.array,0,t,n,e.length);break}case"IConcat":{Tm(e.left,t,n),Tm(e.right,t,n+e.left.length);break}case"ISingleton":{t[n]=e.backing.a;break}case"ISlice":{let r=0,o=n;while(r<e.length)t[o]=la(e,r),r+=1,o+=1;break}}},BM=(e)=>{switch(e.backing._tag){case"IEmpty":return Hb;case"IArray":return e.backing.array;default:{let t=Array(e.length);return Tm(e,t,0),e.backing={_tag:"IArray",array:t},e.left=Xn,e.right=Xn,e.depth=0,t}}},Mr,KM=(e)=>{switch(e.backing._tag){case"IEmpty":case"ISingleton":return e;case"IArray":return ot({_tag:"IArray",array:_m(e.backing.array)});case"IConcat":return ot({_tag:"IConcat",left:po(e.backing.right),right:po(e.backing.left)});case"ISlice":return Us(_m(Mr(e)))}},po,Us=(e)=>e.length===0?dn():e.length===1?tt(e[0]):ot({_tag:"IArray",array:e}),zM=(e)=>Us(e),la,jb,kt,Em,nn,Vb=(e)=>e.length===0,An=(e)=>e.length>0,Om=(e)=>la(e,0),Pn,In=(e)=>Em(e,1);var Qn=x(()=>{Be();pe();vs();j();Me();Ve();be();ye();Ub=Symbol.for("effect/Chunk");Hb=[],jM=$M(O),VM={[Ub]:{_A:(e)=>e},toString(){return ge(this.toJSON())},toJSON(){return{_id:"Chunk",values:Mr(this).map(de)}},[ne](){return this.toJSON()},[I](e){return $b(e)&&jM(this,e)},[M](){return ie(this,en(Mr(this)))},[Symbol.iterator](){switch(this.backing._tag){case"IArray":return this.backing.array[Symbol.iterator]();case"IEmpty":return Hb[Symbol.iterator]();default:return Mr(this)[Symbol.iterator]()}},pipe(){return T(this,arguments)}},Xn=ot({_tag:"IEmpty"}),Mr=BM,po=KM,la=d(2,(e,t)=>{switch(e.backing._tag){case"IEmpty":throw Error("Index out of bounds");case"ISingleton":{if(t!==0)throw Error("Index out of bounds");return e.backing.a}case"IArray":{if(t>=e.length||t<0)throw Error("Index out of bounds");return e.backing.array[t]}case"IConcat":return t<e.left.length?la(e.left,t):la(e.right,t-e.left.length);case"ISlice":return la(e.backing.chunk,t+e.backing.offset)}}),jb=d(2,(e,t)=>nn(e,tt(t))),kt=d(2,(e,t)=>nn(tt(t),e)),Em=d(2,(e,t)=>{if(t<=0)return e;else if(t>=e.length)return Xn;else switch(e.backing._tag){case"ISlice":return ot({_tag:"ISlice",chunk:e.backing.chunk,offset:e.backing.offset+t,length:e.backing.length-t});case"IConcat":{if(t>e.left.length)return Em(e.right,t-e.left.length);return ot({_tag:"IConcat",left:Em(e.left,t),right:e.right})}default:return ot({_tag:"ISlice",chunk:e,offset:t,length:e.length-t})}}),nn=d(2,(e,t)=>{if(e.backing._tag==="IEmpty")return t;if(t.backing._tag==="IEmpty")return e;let n=t.depth-e.depth;if(Math.abs(n)<=1)return ot({_tag:"IConcat",left:e,right:t});else if(n<-1)if(e.left.depth>=e.right.depth){let r=nn(e.right,t);return ot({_tag:"IConcat",left:e.left,right:r})}else{let r=nn(e.right.right,t);if(r.depth===e.depth-3){let o=ot({_tag:"IConcat",left:e.right.left,right:r});return ot({_tag:"IConcat",left:e.left,right:o})}else{let o=ot({_tag:"IConcat",left:e.left,right:e.right.left});return ot({_tag:"IConcat",left:o,right:r})}}else if(t.right.depth>=t.left.depth){let r=nn(e,t.left);return ot({_tag:"IConcat",left:r,right:t.right})}else{let r=nn(e,t.left.left);if(r.depth===t.depth-3){let o=ot({_tag:"IConcat",left:r,right:t.left.right});return ot({_tag:"IConcat",left:o,right:t.right})}else{let o=ot({_tag:"IConcat",left:t.left.right,right:t.right});return ot({_tag:"IConcat",left:r,right:o})}}}),Pn=Om});var fo=5,Rm,Bb,Kb,zb;var uu=x(()=>{Rm=Math.pow(2,5),Bb=Rm-1,Kb=Rm/2,zb=Rm/4});function WM(e){return e-=e>>1&1431655765,e=(e&858993459)+(e>>2&858993459),e=e+(e>>4)&252645135,e+=e>>8,e+=e>>16,e&127}function mo(e,t){return t>>>e&Bb}function ho(e){return 1<<e}function pu(e,t){return WM(e&t-1)}var km=x(()=>{uu()});var Wb=(e,t)=>({value:e,previous:t});function ii(e,t,n,r){let o=r;if(!e){let i=r.length;o=Array(i);for(let a=0;a<i;++a)o[a]=r[a]}return o[t]=n,o}function Cm(e,t,n){let r=n.length-1,o=0,i=0,a=n;if(e)o=i=t;else{a=Array(r);while(o<t)a[i++]=n[o++]}++o;while(o<=r)a[i++]=n[o++];if(e)a.length=r;return a}function Jb(e,t,n,r){let o=r.length;if(e){let c=o;while(c>=t)r[c--]=r[c];return r[t]=n,r}let i=0,a=0,s=Array(o+1);while(i<t)s[a++]=r[i++];s[t]=n;while(i<o)s[++a]=r[i++];return s}class Fr{_tag="EmptyNode";modify(e,t,n,r,o,i){let a=n(A());if(Ne(a))return new Fr;return++i.value,new ai(e,r,o,a)}}function fn(e){return Os(e,"EmptyNode")}function GM(e){return fn(e)||e._tag==="LeafNode"||e._tag==="CollisionNode"}function du(e,t){return fn(e)?!1:t===e.edit}class ai{edit;hash;key;value;_tag="LeafNode";constructor(e,t,n,r){this.edit=e,this.hash=t,this.key=n,this.value=r}modify(e,t,n,r,o,i){if(O(o,this.key)){let s=n(this.value);if(s===this.value)return this;else if(Ne(s))return--i.value,new Fr;if(du(this,e))return this.value=s,this;return new ai(e,r,o,s)}let a=n(A());if(Ne(a))return this;return++i.value,Gb(e,t,this.hash,this,r,new ai(e,r,o,a))}}class Am{edit;hash;children;_tag="CollisionNode";constructor(e,t,n){this.edit=e,this.hash=t,this.children=n}modify(e,t,n,r,o,i){if(r===this.hash){let s=du(this,e),c=this.updateCollisionList(s,e,this.hash,this.children,n,o,i);if(c===this.children)return this;return c.length>1?new Am(e,this.hash,c):c[0]}let a=n(A());if(Ne(a))return this;return++i.value,Gb(e,t,this.hash,this,r,new ai(e,r,o,a))}updateCollisionList(e,t,n,r,o,i,a){let s=r.length;for(let l=0;l<s;++l){let u=r[l];if("key"in u&&O(i,u.key)){let p=u.value,f=o(p);if(f===p)return r;if(Ne(f))return--a.value,Cm(e,l,r);return ii(e,l,new ai(t,n,i,f),r)}}let c=o(A());if(Ne(c))return r;return++a.value,ii(e,s,new ai(t,n,i,c),r)}}class ua{edit;mask;children;_tag="IndexedNode";constructor(e,t,n){this.edit=e,this.mask=t,this.children=n}modify(e,t,n,r,o,i){let a=this.mask,s=this.children,c=mo(t,r),l=ho(c),u=pu(a,l),p=a&l,f=du(this,e);if(!p){let y=new Fr().modify(e,t+fo,n,r,o,i);if(!y)return this;return s.length>=Kb?ZM(e,c,y,a,s):new ua(e,a|l,Jb(f,u,y,s))}let h=s[u],m=h.modify(e,t+fo,n,r,o,i);if(h===m)return this;let w=a,S;if(fn(m)){if(w&=~l,!w)return new Fr;if(s.length<=2&&GM(s[u^1]))return s[u^1];S=Cm(f,u,s)}else S=ii(f,u,m,s);if(f)return this.mask=w,this.children=S,this;return new ua(e,w,S)}}class Pm{edit;size;children;_tag="ArrayNode";constructor(e,t,n){this.edit=e,this.size=t,this.children=n}modify(e,t,n,r,o,i){let a=this.size,s=this.children,c=mo(t,r),l=s[c],u=(l||new Fr).modify(e,t+fo,n,r,o,i);if(l===u)return this;let p=du(this,e),f;if(fn(l)&&!fn(u))++a,f=ii(p,c,u,s);else if(!fn(l)&&fn(u)){if(--a,a<=zb)return YM(e,a,c,s);f=ii(p,c,new Fr,s)}else f=ii(p,c,u,s);if(p)return this.size=a,this.children=f,this;return new Pm(e,a,f)}}function YM(e,t,n,r){let o=Array(t-1),i=0,a=0;for(let s=0,c=r.length;s<c;++s)if(s!==n){let l=r[s];if(l&&!fn(l))o[i++]=l,a|=1<<s}return new ua(e,a,o)}function ZM(e,t,n,r,o){let i=[],a=r,s=0;for(let c=0;a;++c){if(a&1)i[c]=o[s++];a>>>=1}return i[t]=n,new Pm(e,s+1,i)}function XM(e,t,n,r,o,i){if(n===o)return new Am(e,n,[i,r]);let a=mo(t,n),s=mo(t,o);if(a===s)return(c)=>new ua(e,ho(a)|ho(s),[c]);else{let c=a<s?[r,i]:[i,r];return new ua(e,ho(a)|ho(s),c)}}function Gb(e,t,n,r,o,i){let a=void 0,s=t;while(!0){let c=XM(e,s,n,r,o,i);if(typeof c==="function")a=Wb(c,a),s=s+fo;else{let l=c;while(a!=null)l=a.value(l),a=a.previous;return l}}}var Yb=x(()=>{pe();Ge();ye();km();uu()});var Zb="effect/HashMap",fu,eN,Im=(e,t,n,r)=>{let o=Object.create(eN);return o._editable=e,o._edit=t,o._root=n,o._size=r,o},hu,mu=(e)=>e?Qb(e[0],e[1],e[2],e[3],e[4]):A(),Xb=(e,t,n=void 0)=>{switch(e._tag){case"LeafNode":{if(Re(e.value))return F({value:t(e.key,e.value.value),cont:n});return mu(n)}case"CollisionNode":case"ArrayNode":case"IndexedNode":{let r=e.children;return Qb(r.length,r,0,t,n)}default:return mu(n)}},Qb=(e,t,n,r,o)=>{while(n<e){let i=t[n++];if(i&&!fn(i))return Xb(i,r,[e,t,n,r,o])}return mu(o)},tN,pa=()=>tN,ew=(e)=>{let t=xu(pa());for(let n of e)si(t,n[0],n[1]);return ow(t)},tw=(e)=>C(e,fu),nw=(e)=>e&&fn(e._root),rw,gu,Mm,si,nN,yu=(e)=>new hu(e,(t)=>t),Hs=(e)=>e._size,xu=(e)=>Im(!0,e._edit+1,e._root,e._size),ow=(e)=>(e._editable=!1,e),Su,iw,_u,aw,Nm,da;var Fm=x(()=>{pe();j();j();Me();Ve();Ge();be();ye();km();uu();Yb();fu=Symbol.for(Zb),eN={[fu]:fu,[Symbol.iterator](){return new hu(this,(e,t)=>[e,t])},[M](){let e=E(Zb);for(let t of this)e^=g(E(t[0]),G(E(t[1])));return ie(this,e)},[I](e){if(tw(e)){if(e._size!==this._size)return!1;for(let t of this){let n=g(e,gu(t[0],E(t[0])));if(Ne(n))return!1;else if(!O(t[1],n.value))return!1}return!0}return!1},toString(){return ge(this.toJSON())},toJSON(){return{_id:"HashMap",values:Array.from(this).map(de)}},[ne](){return this.toJSON()},pipe(){return T(this,arguments)}};hu=class hu{map;f;v;constructor(e,t){this.map=e,this.f=t,this.v=Xb(this.map._root,this.f,void 0)}next(){if(Ne(this.v))return{done:!0,value:void 0};let e=this.v.value;return this.v=mu(e.cont),{done:!1,value:e.value}}[Symbol.iterator](){return new hu(this.map,this.f)}};tN=Im(!1,0,new Fr,0),rw=d(2,(e,t)=>gu(e,t,E(t))),gu=d(3,(e,t,n)=>{let r=e._root,o=0;while(!0)switch(r._tag){case"LeafNode":return O(t,r.key)?r.value:A();case"CollisionNode":{if(n===r.hash){let i=r.children;for(let a=0,s=i.length;a<s;++a){let c=i[a];if("key"in c&&O(t,c.key))return c.value}}return A()}case"IndexedNode":{let i=mo(o,n),a=ho(i);if(r.mask&a){r=r.children[pu(r.mask,a)],o+=fo;break}return A()}case"ArrayNode":{if(r=r.children[mo(o,n)],r){o+=fo;break}return A()}default:return A()}}),Mm=d(2,(e,t)=>Re(gu(e,t,E(t)))),si=d(3,(e,t,n)=>Su(e,t,()=>F(n))),nN=d(3,(e,t,n)=>{if(e._editable)return e._root=t,e._size=n,e;return t===e._root?e:Im(e._editable,e._edit,t,n)}),Su=d(3,(e,t,n)=>iw(e,t,E(t),n)),iw=d(4,(e,t,n,r)=>{let o={value:e._size},i=e._root.modify(e._editable?e._edit:NaN,0,r,n,t,o);return g(e,nN(i,o.value))}),_u=d(2,(e,t)=>Su(e,t,A)),aw=d(2,(e,t)=>da(e,pa(),(n,r,o)=>si(n,o,t(r,o)))),Nm=d(2,(e,t)=>da(e,void 0,(n,r,o)=>t(r,o))),da=d(3,(e,t,n)=>{let r=e._root;if(r._tag==="LeafNode")return Re(r.value)?n(t,r.value.value,r.key):t;if(r._tag==="EmptyNode")return t;let o=[r.children],i;while(i=o.pop())for(let a=0,s=i.length;a<s;){let c=i[a++];if(c&&!fn(c))if(c._tag==="LeafNode"){if(Re(c.value))t=n(t,c.value.value,c.key)}else o.push(c.children)}return t})});var cw="effect/HashSet",bu,rN,wu=(e)=>{let t=Object.create(rN);return t._keyMap=e,t},lw=(e)=>C(e,bu),oN,$s=()=>oN,uw=(e)=>{let t=vu($s());for(let n of e)fa(t,n);return Tu(t)},pw=(...e)=>{let t=vu($s());for(let n of e)fa(t,n);return Tu(t)},dw,fw=(e)=>Hs(e._keyMap),vu=(e)=>wu(xu(e._keyMap)),Tu=(e)=>(e._keyMap._editable=!1,e),Lm,fa,Dm,mw,hw,gw,yw;var xw=x(()=>{pe();j();Me();Ve();be();ye();Fm();bu=Symbol.for(cw),rN={[bu]:bu,[Symbol.iterator](){return yu(this._keyMap)},[M](){return ie(this,G(E(this._keyMap))(E(cw)))},[I](e){if(lw(e))return Hs(this._keyMap)===Hs(e._keyMap)&&O(this._keyMap,e._keyMap);return!1},toString(){return ge(this.toJSON())},toJSON(){return{_id:"HashSet",values:Array.from(this).map(de)}},[ne](){return this.toJSON()},pipe(){return T(this,arguments)}},oN=wu(pa()),dw=d(2,(e,t)=>Mm(e._keyMap,t)),Lm=d(2,(e,t)=>{let n=vu(e);return t(n),Tu(n)}),fa=d(2,(e,t)=>e._keyMap._editable?(si(t,!0)(e._keyMap),e):wu(si(t,!0)(e._keyMap))),Dm=d(2,(e,t)=>e._keyMap._editable?(_u(t)(e._keyMap),e):wu(_u(t)(e._keyMap))),mw=d(2,(e,t)=>Lm(e,(n)=>{for(let r of t)Dm(n,r)})),hw=d(2,(e,t)=>Lm($s(),(n)=>{gw(e,(r)=>fa(n,r));for(let r of t)fa(n,r)})),gw=d(2,(e,t)=>Nm(e._keyMap,(n,r)=>t(r))),yw=d(3,(e,t,n)=>da(e._keyMap,t,(r,o,i)=>n(r,i)))});var er,Sw,ci,_w,js,li,qm,Um,Lr,ui;var pi=x(()=>{xw();er=$s,Sw=uw,ci=pw,_w=dw,js=fw,li=fa,qm=Dm,Um=mw,Lr=hw,ui=yw});var ha="Die",go="Empty",yo="Fail",di="Interrupt",fi="Parallel",mi="Sequential";var vw="effect/Cause",jm,sN,ga,Dr,ya=(e)=>{let t=Object.create(ga);return t._tag=yo,t.error=e,t},rn=(e)=>{let t=Object.create(ga);return t._tag=ha,t.defect=e,t},Mn=(e)=>{let t=Object.create(ga);return t._tag=di,t.fiberId=e,t},yi=(e,t)=>{let n=Object.create(ga);return n._tag=fi,n.left=e,n.right=t,n},Ct=(e,t)=>{let n=Object.create(ga);return n._tag=mi,n.left=e,n.right=t,n},Tw=(e)=>C(e,jm),Vm=(e)=>e._tag===go,Ew=(e)=>e._tag===yo,Eu=(e)=>{if(e._tag===go)return!0;return hi(e,!0,(t,n)=>{switch(n._tag){case go:return F(t);case ha:case yo:case di:return F(!1);default:return A()}})},Ou=(e)=>Re(Ow(e)),xa=(e)=>Cu(void 0,pN)(e),Bm=(e)=>po(hi(e,dn(),(t,n)=>n._tag===yo?F(g(t,kt(n.error))):A())),Km=(e)=>po(hi(e,dn(),(t,n)=>n._tag===ha?F(g(t,kt(n.defect))):A())),zm=(e)=>hi(e,er(),(t,n)=>n._tag===di?F(g(t,li(n.fiberId))):A()),Wm=(e)=>Jm(e,(t)=>t._tag===yo?F(t.error):A()),Ru=(e)=>{let t=Wm(e);switch(t._tag){case"None":return Q(e);case"Some":return W(t.value)}},Ow=(e)=>Jm(e,(t)=>t._tag===di?F(t.fiberId):A()),ku=(e)=>Gm(e,{onEmpty:Dr,onFail:()=>Dr,onDie:rn,onInterrupt:Mn,onSequential:Ct,onParallel:yi}),Rw=(e)=>Gm(e,{onEmpty:Dr,onFail:rn,onDie:rn,onInterrupt:Mn,onSequential:Ct,onParallel:yi}),cN=(e,t)=>{let n=tt(e),r=tt(t);while(An(n)&&An(r)){let[o,i]=g(Pn(n),hi([er(),dn()],([c,l],u)=>{let[p,f]=Hm(u);return F([g(c,Lr(p)),g(l,nn(f))])})),[a,s]=g(Pn(r),hi([er(),dn()],([c,l],u)=>{let[p,f]=Hm(u);return F([g(c,Lr(p)),g(l,nn(f))])}));if(!O(o,a))return!1;n=i,r=s}return!0},lN=(e)=>uN(tt(e),dn()),uN=(e,t)=>{while(!0){let[n,r]=g(e,ca([er(),dn()],([i,a],s)=>{let[c,l]=Hm(s);return[g(i,Lr(c)),g(a,nn(l))]})),o=js(n)>0?g(t,kt(n)):t;if(Vb(r))return po(o);e=r,t=o}throw Error(Xo("Cause.flattenCauseLoop"))},Jm,Hm=(e)=>{let t=e,n=[],r=er(),o=dn();while(t!==void 0)switch(t._tag){case go:{if(n.length===0)return[r,o];t=n.pop();break}case yo:{if(r=li(r,qs(t._tag,t.error)),n.length===0)return[r,o];t=n.pop();break}case ha:{if(r=li(r,qs(t._tag,t.defect)),n.length===0)return[r,o];t=n.pop();break}case di:{if(r=li(r,qs(t._tag,t.fiberId)),n.length===0)return[r,o];t=n.pop();break}case mi:{switch(t.left._tag){case go:{t=t.right;break}case mi:{t=Ct(t.left.left,Ct(t.left.right,t.right));break}case fi:{t=yi(Ct(t.left.left,t.right),Ct(t.left.right,t.right));break}default:{o=kt(o,t.right),t=t.left;break}}break}case fi:{n.push(t.right),t=t.left;break}}throw Error(Xo("Cause.evaluateCauseLoop"))},pN,bw="SequentialCase",ww="ParallelCase",Gm,hi,Cu,Nn=(e,t)=>{if(xa(e))return"All fibers interrupted without errors.";return Vs(e).map(function(n){if(t?.renderErrorCause!==!0||n.cause===void 0)return n.stack;return`${n.stack} {
10
+ ${kw(n.cause," ")}
11
+ }`}).join(`
12
+ `)},kw=(e,t)=>{let n=e.stack.split(`
13
+ `),r=`${t}[cause]: ${n[0]}`;for(let o=1,i=n.length;o<i;o++)r+=`
14
+ ${t}${n[o]}`;if(e.cause)r+=` {
15
+ ${kw(e.cause,`${t} `)}
16
+ ${t}}`;return r},$m=(e)=>{let t=typeof e==="object"&&e!==null,n=Error.stackTraceLimit;Error.stackTraceLimit=1;let r=Error(dN(e),t&&"cause"in e&&typeof e.cause<"u"?{cause:$m(e.cause)}:void 0);if(Error.stackTraceLimit=n,r.message==="")r.message="An error has occurred";if(Error.stackTraceLimit=n,r.name=e instanceof Error?e.name:"Error",t){if(gi in e)r.span=e[gi];Object.keys(e).forEach((o)=>{if(!(o in r))r[o]=e[o]})}return r.stack=hN(`${r.name}: ${r.message}`,e instanceof Error&&e.stack?e.stack:"",r.span),r},dN=(e)=>{if(typeof e==="string")return e;if(typeof e==="object"&&e!==null&&e instanceof Error)return e.message;try{if(C(e,"toString")&&oo(e.toString)&&e.toString!==Object.prototype.toString&&e.toString!==globalThis.Array.prototype.toString)return e.toString()}catch{}return Ql(e)},fN,mN,hN=(e,t,n)=>{let r=[e],o=t.startsWith(e)?t.slice(e.length).split(`
7
17
  `):t.split(`
8
- `);for(let e=1;e<i.length;e++){if(i[e].includes(` at new BaseEffectError`)||i[e].includes(` at new YieldableError`)){e++;continue}if(i[e].includes(`Generator.next`)||i[e].includes(`effect_internal_function`))break;r.push(i[e].replace(/at .*effect_instruction_i.*\((.*)\)/,`at $1`).replace(/EffectPrimitive\.\w+/,`<anonymous>`))}if(n){let e=n,t=0;for(;e&&e._tag===`Span`&&t<10;){let n=gc.get(e);if(typeof n==`function`){let t=n();if(typeof t==`string`){let n=t.matchAll(hc),i=!1;for(let[,t]of n)i=!0,r.push(` at ${e.name} (${t})`);i||r.push(` at ${e.name} (${t.replace(/^at /,``)})`)}else r.push(` at ${e.name}`)}else r.push(` at ${e.name}`);e=Tr(e.parent),t++}}return r.join(`
9
- `)},vc=Symbol.for(`effect/SpanAnnotation`),yc=e=>uc(e,void 0,{emptyCase:()=>[],dieCase:(e,t)=>[pc(t)],failCase:(e,t)=>[pc(t)],interruptCase:()=>[],parallelCase:(e,t,n)=>[...t,...n],sequentialCase:(e,t,n)=>[...t,...n]})})),xc,Sc,Cc,wc,Tc,Ec,Dc,Oc,kc,Ac,jc,Mc,Nc,Pc,Fc,Ic,Lc,Rc,zc,Bc,Vc,Hc,Uc,Wc,Gc,Kc,qc=v((()=>{M(),S(),Ie(),Mt(),Xt(),F(),T(),On(),zn(),xc=Symbol.for(`effect/Context/Tag`),Sc=Symbol.for(`effect/Context/Reference`),Cc=`effect/STM`,wc=Symbol.for(Cc),Tc={...Cn,_op:`Tag`,[wc]:bn,[xc]:{_Service:e=>e,_Identifier:e=>e},toString(){return Ht(this.toJSON())},toJSON(){return{_id:`Tag`,key:this.key,stack:this.stack}},[N](){return this.toJSON()},of(e){return e},context(e){return Rc(this,e)}},Ec={...Tc,[Sc]:Sc},Dc=e=>{let t=Error.stackTraceLimit;Error.stackTraceLimit=2;let n=Error();Error.stackTraceLimit=t;let r=Object.create(Tc);return Object.defineProperty(r,"stack",{get(){return n.stack}}),r.key=e,r},Oc=e=>()=>{let t=Error.stackTraceLimit;Error.stackTraceLimit=2;let n=Error();Error.stackTraceLimit=t;function r(){}return Object.setPrototypeOf(r,Tc),r.key=e,Object.defineProperty(r,"stack",{get(){return n.stack}}),r},kc=()=>(e,t)=>{let n=Error.stackTraceLimit;Error.stackTraceLimit=2;let r=Error();Error.stackTraceLimit=n;function i(){}return Object.setPrototypeOf(i,Ec),i.key=e,i.defaultValue=t.defaultValue,Object.defineProperty(i,"stack",{get(){return r.stack}}),i},Ac=Symbol.for(`effect/Context`),jc={[Ac]:{_Services:e=>e},[j](e){if(Pc(e)&&this.unsafeMap.size===e.unsafeMap.size){for(let t of this.unsafeMap.keys())if(!e.unsafeMap.has(t)||!A(this.unsafeMap.get(t),e.unsafeMap.get(t)))return!1;return!0}return!1},[E](){return k(this,Dt(this.unsafeMap.size))},pipe(){return P(this,arguments)},toString(){return Ht(this.toJSON())},toJSON(){return{_id:`Context`,services:Array.from(this.unsafeMap).map(Bt)}},[N](){return this.toJSON()}},Mc=e=>{let t=Object.create(jc);return t.unsafeMap=e,t},Nc=e=>{let t=Error(`Service not found${e.key?`: ${String(e.key)}`:``}`);if(e.stack){let n=e.stack.split(`
10
- `);if(n.length>2){let e=n[2].match(/at (.*)/);e&&(t.message+=` (defined at ${e[1]})`)}}if(t.stack){let e=t.stack.split(`
11
- `);e.splice(1,3),t.stack=e.join(`
12
- `)}return t},Pc=e=>w(e,Ac),Fc=e=>w(e,Sc),Ic=Mc(new Map),Lc=()=>Ic,Rc=(e,t)=>Mc(new Map([[e.key,t]])),zc=x(3,(e,t,n)=>{let r=new Map(e.unsafeMap);return r.set(t.key,n),Mc(r)}),Bc=C(`effect/Context/defaultValueCache`,()=>new Map),Vc=e=>{if(Bc.has(e.key))return Bc.get(e.key);let t=e.defaultValue();return Bc.set(e.key,t),t},Hc=(e,t)=>e.unsafeMap.has(t.key)?e.unsafeMap.get(t.key):Vc(t),Uc=x(2,(e,t)=>{if(!e.unsafeMap.has(t.key)){if(Sc in t)return Vc(t);throw Nc(t)}return e.unsafeMap.get(t.key)}),Wc=Uc,Gc=x(2,(e,t)=>e.unsafeMap.has(t.key)?Rn(e.unsafeMap.get(t.key)):Fc(t)?Rn(Vc(t)):Ln),Kc=x(2,(e,t)=>{let n=new Map(e.unsafeMap);for(let[e,r]of t.unsafeMap)n.set(e,r);return Mc(n)})})),Jc,Yc,Xc,Zc,Qc,$c,el,tl,nl,rl,il=v((()=>{qc(),Jc=Dc,Yc=Lc,Xc=Rc,Zc=zc,Qc=Wc,$c=Uc,el=Gc,tl=Kc,nl=Oc,rl=kc})),al,ol,sl,cl,ll,ul,dl,fl,pl,ml,hl,gl,_l,vl,yl,bl,xl,Sl,Cl,wl,Tl,El,Dl,Ol,kl,Al,jl,Ml,Nl,Pl,Fl,Il,Ll,Rl,zl,Bl,Vl,Hl,Ul=v((()=>{M(),S(),Mt(),Xt(),Rr(),F(),T(),al=Symbol.for(`effect/Duration`),ol=BigInt(0),sl=BigInt(24),cl=BigInt(60),ll=BigInt(1e3),ul=BigInt(1e6),dl=BigInt(1e9),fl=/^(-?\d+(?:\.\d+)?)\s+(nanos?|micros?|millis?|seconds?|minutes?|hours?|days?|weeks?)$/,pl=e=>{if(vl(e))return e;if(ze(e))return Tl(e);if(Ve(e))return Cl(e);if(Array.isArray(e)&&e.length===2&&e.every(ze))return e[0]===-1/0||e[1]===-1/0||Number.isNaN(e[0])||Number.isNaN(e[1])?xl:e[0]===1/0||e[1]===1/0?Sl:Cl(BigInt(Math.round(e[0]*1e9))+BigInt(Math.round(e[1])));if(Re(e)){let t=fl.exec(e);if(t){let[e,n,r]=t,i=Number(n);switch(r){case`nano`:case`nanos`:return Cl(BigInt(n));case`micro`:case`micros`:return wl(BigInt(n));case`milli`:case`millis`:return Tl(i);case`second`:case`seconds`:return El(i);case`minute`:case`minutes`:return Dl(i);case`hour`:case`hours`:return Ol(i);case`day`:case`days`:return kl(i);case`week`:case`weeks`:return Al(i)}}}throw Error(`Invalid DurationInput`)},ml={_tag:`Millis`,millis:0},hl={_tag:`Infinity`},gl={[al]:al,[E](){return k(this,At(this.value))},[j](e){return vl(e)&&Bl(this,e)},toString(){return`Duration(${Hl(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:Pl(this)};case`Infinity`:return{_id:`Duration`,_tag:`Infinity`}}},[N](){return this.toJSON()},pipe(){return P(this,arguments)}},_l=e=>{let t=Object.create(gl);return t.value=ze(e)?isNaN(e)||e<=0?ml:Number.isFinite(e)?Number.isInteger(e)?{_tag:`Millis`,millis:e}:{_tag:`Nanos`,nanos:BigInt(Math.round(e*1e6))}:hl:e<=ol?ml:{_tag:`Nanos`,nanos:e},t},vl=e=>w(e,al),yl=e=>e.value._tag!==`Infinity`,bl=e=>{switch(e.value._tag){case`Millis`:return e.value.millis===0;case`Nanos`:return e.value.nanos===ol;case`Infinity`:return!1}},xl=_l(0),Sl=_l(1/0),Cl=e=>_l(e),wl=e=>_l(e*ll),Tl=e=>_l(e),El=e=>_l(e*1e3),Dl=e=>_l(e*6e4),Ol=e=>_l(e*36e5),kl=e=>_l(e*864e5),Al=e=>_l(e*6048e5),jl=e=>Fl(e,{onMillis:e=>e,onNanos:e=>Number(e)/1e6}),Ml=e=>{let t=pl(e);switch(t.value._tag){case`Infinity`:return R();case`Nanos`:return z(t.value.nanos);case`Millis`:return z(BigInt(Math.round(t.value.millis*1e6)))}},Nl=e=>{let t=pl(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))}},Pl=e=>{let t=pl(e);switch(t.value._tag){case`Infinity`:return[1/0,0];case`Nanos`:return[Number(t.value.nanos/dl),Number(t.value.nanos%dl)];case`Millis`:return[Math.floor(t.value.millis/1e3),Math.round(t.value.millis%1e3*1e6)]}},Fl=x(2,(e,t)=>{let n=pl(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)}}),Il=x(3,(e,t,n)=>{let r=pl(e),i=pl(t);if(r.value._tag===`Infinity`||i.value._tag===`Infinity`)return n.onMillis(jl(r),jl(i));if(r.value._tag===`Nanos`||i.value._tag===`Nanos`){let e=r.value._tag===`Nanos`?r.value.nanos:BigInt(Math.round(r.value.millis*1e6)),t=i.value._tag===`Nanos`?i.value.nanos:BigInt(Math.round(i.value.millis*1e6));return n.onNanos(e,t)}return n.onMillis(r.value.millis,i.value.millis)}),Ll=(e,t)=>Il(e,t,{onMillis:(e,t)=>e===t,onNanos:(e,t)=>e===t}),Rl=x(2,(e,t)=>Il(e,t,{onMillis:(e,t)=>e<=t,onNanos:(e,t)=>e<=t})),zl=x(2,(e,t)=>Il(e,t,{onMillis:(e,t)=>e>=t,onNanos:(e,t)=>e>=t})),Bl=x(2,(e,t)=>Ll(pl(e),pl(t))),Vl=e=>{let t=pl(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=Nl(t),r=n/ul,i=r/ll,a=i/cl,o=a/cl,s=o/sl;return{days:Number(s),hours:Number(o%sl),minutes:Number(a%cl),seconds:Number(i%cl),millis:Number(r%ll),nanos:Number(n%ul)}},Hl=e=>{let t=pl(e);if(t.value._tag===`Infinity`)return`Infinity`;if(bl(t))return`0`;let n=Vl(t),r=[];return n.days!==0&&r.push(`${n.days}d`),n.hours!==0&&r.push(`${n.hours}h`),n.minutes!==0&&r.push(`${n.minutes}m`),n.seconds!==0&&r.push(`${n.seconds}s`),n.millis!==0&&r.push(`${n.millis}ms`),n.nanos!==0&&r.push(`${n.nanos}ns`),r.join(` `)}})),Wl,Gl,Kl,ql,Jl,Yl=v((()=>{S(),Xt(),F(),Wl=Symbol.for(`effect/MutableRef`),Gl={[Wl]:Wl,toString(){return Ht(this.toJSON())},toJSON(){return{_id:`MutableRef`,current:Bt(this.current)}},[N](){return this.toJSON()},pipe(){return P(this,arguments)}},Kl=e=>{let t=Object.create(Gl);return t.current=e,t},ql=e=>e.current,Jl=x(2,(e,t)=>(e.current=t,e))})),Xl,Zl,Ql,$l,eu,tu,nu,ru,iu,au,ou,su,cu,lu,uu,du,fu,pu=v((()=>{M(),S(),Ie(),Mt(),Cs(),Xt(),Yl(),T(),Xl=`effect/FiberId`,Zl=Symbol.for(Xl),Ql=`None`,$l=`Runtime`,eu=`Composite`,tu=Ot(`${Xl}-${Ql}`),nu=class{[Zl]=Zl;_tag=Ql;id=-1;startTimeMillis=-1;[E](){return tu}[j](e){return cu(e)&&e._tag===Ql}toString(){return Ht(this.toJSON())}toJSON(){return{_id:`FiberId`,_tag:this._tag}}[N](){return this.toJSON()}},ru=class{id;startTimeMillis;[Zl]=Zl;_tag=$l;constructor(e,t){this.id=e,this.startTimeMillis=t}[E](){return k(this,Ot(`${Xl}-${this._tag}-${this.id}-${this.startTimeMillis}`))}[j](e){return cu(e)&&e._tag===$l&&this.id===e.id&&this.startTimeMillis===e.startTimeMillis}toString(){return Ht(this.toJSON())}toJSON(){return{_id:`FiberId`,_tag:this._tag,id:this.id,startTimeMillis:this.startTimeMillis}}[N](){return this.toJSON()}},iu=class{left;right;[Zl]=Zl;_tag=eu;constructor(e,t){this.left=e,this.right=t}_hash;[E](){return b(Ot(`${Xl}-${this._tag}`),O(D(this.left)),O(D(this.right)),k(this))}[j](e){return cu(e)&&e._tag===eu&&A(this.left,e.left)&&A(this.right,e.right)}toString(){return Ht(this.toJSON())}toJSON(){return{_id:`FiberId`,_tag:this._tag,left:Bt(this.left),right:Bt(this.right)}}[N](){return this.toJSON()}},au=new nu,ou=(e,t)=>new ru(e,t),su=(e,t)=>new iu(e,t),cu=e=>w(e,Zl),lu=e=>{switch(e._tag){case Ql:return ps();case $l:return hs(e.id);case eu:return b(lu(e.left),xs(lu(e.right)))}},uu=C(Symbol.for(`effect/Fiber/Id/_fiberCounter`),()=>Kl(0)),du=e=>Array.from(lu(e)).map(e=>`#${e}`).join(`,`),fu=()=>{let e=ql(uu);return b(uu,Jl(e+1)),new ru(e,Date.now())}})),mu,hu,gu,_u,vu,yu,bu=v((()=>{pu(),mu=au,hu=ou,gu=su,_u=cu,vu=du,yu=fu})),xu,Su,Cu,wu,Tu,Eu,Du,Ou,ku,Au=v((()=>{Go(),xu=Eo,Su=Do,Cu=ko,wu=Ao,Tu=No,Eu=Fo,Du=zo,Ou=Ho,ku=Wo})),ju,Mu,Nu,Pu,Fu,Iu,Lu,Ru,zu,Bu,Vu,Hu,Uu,Wu,Gu,Ku,qu,Ju,Yu,Xu,Zu,Qu=v((()=>{Pi(),M(),Ne(),S(),Mt(),Xt(),F(),T(),ju=Symbol.for(`effect/List`),Mu=e=>Ur(e),Nu=e=>Ae(Ai(e),Mu),Pu=Nu(A),Fu={[ju]:ju,_tag:`Cons`,toString(){return Ht(this.toJSON())},toJSON(){return{_id:`List`,_tag:`Cons`,values:Mu(this).map(Bt)}},[N](){return this.toJSON()},[j](e){return Bu(e)&&this._tag===e._tag&&Pu(this,e)},[E](){return k(this,jt(Mu(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(t){return e||=!0,{done:!0,value:t}}}},pipe(){return P(this,arguments)}},Iu=(e,t)=>{let n=Object.create(Fu);return n.head=e,n.tail=t,n},Lu=Ot(`Nil`),Ru={[ju]:ju,_tag:`Nil`,toString(){return Ht(this.toJSON())},toJSON(){return{_id:`List`,_tag:`Nil`}},[N](){return this.toJSON()},[E](){return Lu},[j](e){return Bu(e)&&this._tag===e._tag},[Symbol.iterator](){return{next(){return{done:!0,value:void 0}}}},pipe(){return P(this,arguments)}},zu=Object.create(Ru),Bu=e=>w(e,ju),Vu=e=>e._tag===`Nil`,Hu=e=>e._tag===`Cons`,Uu=()=>zu,Wu=(e,t)=>Iu(e,t),Gu=Uu,Ku=e=>Iu(e,zu),qu=x(2,(e,t)=>Yu(t,e)),Ju=x(2,(e,t)=>Wu(t,e)),Yu=x(2,(e,t)=>{if(Vu(e))return t;if(Vu(t))return e;{let n=Iu(t.head,e),r=n,i=t.tail;for(;!Vu(i);){let t=Iu(i.head,e);r.tail=t,r=t,i=i.tail}return n}}),Xu=x(3,(e,t,n)=>{let r=t,i=e;for(;!Vu(i);)r=n(r,i.head),i=i.tail;return r}),Zu=e=>{let t=Gu(),n=e;for(;!Vu(n);)t=Ju(t,n.head),n=n.tail;return t}})),$u,ed=v((()=>{M(),Mt(),On(),Array.prototype,$u=function(){function e(e){e&&Object.assign(this,e)}return e.prototype=wn,e}()}));function td(e){return e}var nd,rd,id,ad,od,sd,cd,ld,ud,dd,fd,pd,md,hd,gd,_d=v((()=>{Ba(),M(),S(),qc(),ed(),nd=Symbol.for(`effect/DifferContextPatch`),rd={...$u.prototype,[nd]:{_Value:td,_Patch:td}},id=Object.create(Object.assign(Object.create(rd),{_tag:`Empty`})),ad=()=>id,od=Object.assign(Object.create(rd),{_tag:`AndThen`}),sd=(e,t)=>{let n=Object.create(od);return n.first=e,n.second=t,n},cd=Object.assign(Object.create(rd),{_tag:`AddService`}),ld=(e,t)=>{let n=Object.create(cd);return n.key=e,n.service=t,n},ud=Object.assign(Object.create(rd),{_tag:`RemoveService`}),dd=e=>{let t=Object.create(ud);return t.key=e,t},fd=Object.assign(Object.create(rd),{_tag:`UpdateService`}),pd=(e,t)=>{let n=Object.create(fd);return n.key=e,n.update=t,n},md=(e,t)=>{let n=new Map(e.unsafeMap),r=ad();for(let[e,i]of t.unsafeMap.entries())if(n.has(e)){let t=n.get(e);n.delete(e),A(t,i)||(r=hd(pd(e,()=>i))(r))}else n.delete(e),r=hd(ld(e,i))(r);for(let[e]of n.entries())r=hd(dd(e))(r);return r},hd=x(2,(e,t)=>sd(e,t)),gd=x(2,(e,t)=>{if(e._tag===`Empty`)return t;let n=!1,r=xa(e),i=new Map(t.unsafeMap);for(;Ia(r);){let e=Ra(r),t=za(r);switch(e._tag){case`Empty`:r=t;break;case`AddService`:i.set(e.key,e.service),r=t;break;case`AndThen`:r=Ma(Ma(t,e.second),e.first);break;case`RemoveService`:i.delete(e.key),r=t;break;case`UpdateService`:i.set(e.key,e.update(i.get(e.key))),n=!0,r=t}}if(!n)return Mc(i);let a=new Map;for(let[e]of t.unsafeMap)i.has(e)&&(a.set(e,i.get(e)),i.delete(e));for(let[e,t]of i)a.set(e,t);return Mc(a)})}));function vd(e){return e}var yd,bd,xd,Sd,Cd,wd,Td,Ed,Dd,Od,kd,Ad,jd,Md=v((()=>{Ba(),S(),Cs(),ed(),yd=Symbol.for(`effect/DifferHashSetPatch`),bd={...$u.prototype,[yd]:{_Value:vd,_Key:vd,_Patch:vd}},xd=Object.create(Object.assign(Object.create(bd),{_tag:`Empty`})),Sd=()=>xd,Cd=Object.assign(Object.create(bd),{_tag:`AndThen`}),wd=(e,t)=>{let n=Object.create(Cd);return n.first=e,n.second=t,n},Td=Object.assign(Object.create(bd),{_tag:`Add`}),Ed=e=>{let t=Object.create(Td);return t.value=e,t},Dd=Object.assign(Object.create(bd),{_tag:`Remove`}),Od=e=>{let t=Object.create(Dd);return t.value=e,t},kd=(e,t)=>{let[n,r]=Ss([e,Sd()],([e,t],n)=>gs(n)(e)?[ys(n)(e),t]:[e,Ad(Ed(n))(t)])(t);return Ss(r,(e,t)=>Ad(Od(t))(e))(n)},Ad=x(2,(e,t)=>wd(e,t)),jd=x(2,(e,t)=>{if(e._tag===`Empty`)return t;let n=t,r=xa(e);for(;Ia(r);){let e=Ra(r),t=za(r);switch(e._tag){case`Empty`:r=t;break;case`AndThen`:r=Ma(e.first)(Ma(e.second)(t));break;case`Add`:n=vs(e.value)(n),r=t;break;case`Remove`:n=ys(e.value)(n),r=t}}return n})}));function Nd(e){return e}var Pd,Fd,Id,Ld,Rd,zd,Bd,Vd,Hd,Ud,Wd,Gd,Kd,qd,Jd,Yd=v((()=>{Pi(),M(),S(),ed(),Pd=Symbol.for(`effect/DifferReadonlyArrayPatch`),Fd={...$u.prototype,[Pd]:{_Value:Nd,_Patch:Nd}},Id=Object.create(Object.assign(Object.create(Fd),{_tag:`Empty`})),Ld=()=>Id,Rd=Object.assign(Object.create(Fd),{_tag:`AndThen`}),zd=(e,t)=>{let n=Object.create(Rd);return n.first=e,n.second=t,n},Bd=Object.assign(Object.create(Fd),{_tag:`Append`}),Vd=e=>{let t=Object.create(Bd);return t.values=e,t},Hd=Object.assign(Object.create(Fd),{_tag:`Slice`}),Ud=(e,t)=>{let n=Object.create(Hd);return n.from=e,n.until=t,n},Wd=Object.assign(Object.create(Fd),{_tag:`Update`}),Gd=(e,t)=>{let n=Object.create(Wd);return n.index=e,n.patch=t,n},Kd=e=>{let t=0,n=Ld();for(;t<e.oldValue.length&&t<e.newValue.length;){let r=e.oldValue[t],i=e.newValue[t],a=e.differ.diff(r,i);A(a,e.differ.empty)||(n=qd(n,Gd(t,a))),t+=1}return t<e.oldValue.length&&(n=qd(n,Ud(0,t))),t<e.newValue.length&&(n=qd(n,Vd(di(t)(e.newValue)))),n},qd=x(2,(e,t)=>zd(e,t)),Jd=x(3,(e,t,n)=>{if(e._tag===`Empty`)return t;let r=t.slice(),i=Ci(e);for(;Qr(i);){let e=ai(i),t=ci(i);switch(e._tag){case`Empty`:i=t;break;case`AndThen`:t.unshift(e.first,e.second),i=t;break;case`Append`:for(let t of e.values)r.push(t);i=t;break;case`Slice`:r=r.slice(e.from,e.until),i=t;break;case`Update`:r[e.index]=n.patch(e.patch,r[e.index]),i=t}}return r})})),Xd,Zd,Qd,$d,ef,tf,nf,rf,af=v((()=>{M(),S(),F(),_d(),Md(),Yd(),Xd=Symbol.for(`effect/Differ`),Zd={[Xd]:{_P:be,_V:be},pipe(){return P(this,arguments)}},Qd=e=>{let t=Object.create(Zd);return t.empty=e.empty,t.diff=e.diff,t.combine=e.combine,t.patch=e.patch,t},$d=()=>Qd({empty:ad(),combine:(e,t)=>hd(t)(e),diff:(e,t)=>md(e,t),patch:(e,t)=>gd(t)(e)}),ef=()=>Qd({empty:Sd(),combine:(e,t)=>Ad(t)(e),diff:(e,t)=>kd(e,t),patch:(e,t)=>jd(t)(e)}),tf=e=>Qd({empty:Ld(),combine:(e,t)=>qd(e,t),diff:(t,n)=>Kd({oldValue:t,newValue:n,differ:e}),patch:(t,n)=>Jd(t,n,e)}),nf=()=>rf((e,t)=>t),rf=e=>Qd({empty:be,combine:(e,t)=>e===be?t:t===be?e:n=>t(e(n)),diff:(e,t)=>A(e,t)?be:xe(t),patch:(t,n)=>e(n,t(n))})})),of,sf,cf,lf,uf,df,ff,pf,mf,hf,gf,_f=v((()=>{S(),of=255,sf=8,cf=e=>e&of,lf=e=>e>>sf&of,uf=(e,t)=>(e&of)+((t&e&of)<<sf),df=uf(0,0),ff=e=>uf(e,e),pf=e=>uf(e,0),mf=x(2,(e,t)=>uf(cf(e)&~t,lf(e))),hf=x(2,(e,t)=>e|t),gf=e=>~e>>>0&of})),vf,yf,bf,xf,Sf,Cf,wf,Tf,Ef,Df,Of,kf,Af=v((()=>{S(),af(),_f(),vf=e=>Sf(e,32),yf=x(2,(e,t)=>e|t),bf=e=>xf(e)&&!Ef(e),xf=e=>Sf(e,1),Sf=x(2,(e,t)=>(e&t)!==0),Cf=(...e)=>e.reduce((e,t)=>e|t,0),wf=Cf(0),Tf=e=>Sf(e,4),Ef=e=>Sf(e,16),Df=x(2,(e,t)=>uf(e^t,t)),Of=x(2,(e,t)=>e&(gf(cf(t))|lf(t))|cf(t)&lf(t)),kf=Qd({empty:df,diff:(e,t)=>Df(e,t),combine:(e,t)=>hf(t)(e),patch:(e,t)=>Of(t,e)})})),jf,Mf,Nf,Pf=v((()=>{_f(),jf=ff,Mf=pf,Nf=mf})),Ff,If,Lf,Rf,zf,Bf,Vf,Hf,Uf,Wf,Gf,Kf,qf,Jf,Yf,Xf,Zf,Qf,$f,ep,tp,np=v((()=>{Ba(),M(),Au(),Qu(),Rr(),Ff=(e,t)=>({_tag:`Par`,left:e,right:t}),If=(e,t)=>({_tag:`Seq`,left:e,right:t}),Lf=e=>{let t=Ku(e),n=Gu();for(;;){let[e,r]=Xu(t,[Uf(),Gu()],([e,t],n)=>{let[r,i]=Rf(n);return[Gf(e,r),qu(t,i)]});if(n=zf(n,e),Vu(r))return Zu(n);t=r}throw Error(`BUG: BlockedRequests.flatten - please report an issue at https://github.com/Effect-TS/effect/issues`)},Rf=e=>{let t=e,n=Uf(),r=Gu(),i=Gu();for(;;)switch(t._tag){case`Empty`:if(Vu(r))return[n,i];t=r.head,r=r.tail;break;case`Par`:r=Wu(t.right,r),t=t.left;break;case`Seq`:{let e=t.left,n=t.right;switch(e._tag){case`Empty`:t=n;break;case`Par`:{let r=e.left,i=e.right;t=Ff(If(r,n),If(i,n));break}case`Seq`:{let r=e.left,i=e.right;t=If(r,If(i,n));break}case`Single`:t=e,i=Wu(n,i)}break}case`Single`:if(n=Wf(n,t),Vu(r))return[n,i];t=r.head,r=r.tail}throw Error(`BUG: BlockedRequests.step - please report an issue at https://github.com/Effect-TS/effect/issues`)},zf=(e,t)=>{if(Vu(e))return Ku(Jf(t));if(Kf(t))return e;let n=ep(e.head),r=qf(t);return n.length===1&&r.length===1&&A(n[0],r[0])?Wu($f(e.head,Jf(t)),e.tail):Wu(Jf(t),e)},Bf=Symbol.for(`effect/RequestBlock/RequestBlockParallel`),Vf={_R:e=>e},Hf=class{map;[Bf]=Vf;constructor(e){this.map=e}},Uf=()=>new Hf(xu()),Wf=(e,t)=>new Hf(Du(e.map,t.dataSource,e=>Cr(Or(e,ja(t.blockedRequest)),()=>xa(t.blockedRequest)))),Gf=(e,t)=>new Hf(ku(e.map,t.map,(e,t,n)=>Tu(e,n,br(wu(e,n),{onNone:()=>t,onSome:e=>Pa(t,e)})))),Kf=e=>Cu(e.map),qf=e=>Array.from(Eu(e.map)),Jf=e=>Qf(Ou(e.map,e=>xa(e))),Yf=Symbol.for(`effect/RequestBlock/RequestBlockSequential`),Xf={_R:e=>e},Zf=class{map;[Yf]=Xf;constructor(e){this.map=e}},Qf=e=>new Zf(e),$f=(e,t)=>new Zf(ku(t.map,e.map,(e,t,n)=>Tu(e,n,br(wu(e,n),{onNone:()=>ya(),onSome:e=>Pa(e,t)})))),ep=e=>Array.from(Eu(e.map)),tp=e=>Array.from(e.map)})),rp,ip,ap=v((()=>{rp=`Pending`,ip=`Done`})),op,sp,cp,lp,up,dp=v((()=>{ap(),op=`effect/Deferred`,sp=Symbol.for(op),cp={_E:e=>e,_A:e=>e},lp=e=>({_tag:rp,joiners:e}),up=e=>({_tag:ip,effect:e})})),fp,pp=v((()=>{fp=class e{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 e(this.self)}}})),mp,hp,gp,_p,vp,yp,bp,xp,Sp,Cp,wp,Tp,Ep,Dp,Op,kp,Ap,jp,Mp,Np,Pp,Fp,Ip,Lp,Rp,zp,Bp,Vp,Hp,B,Up,Wp,Gp,Kp,qp,Jp,Yp,Xp,Zp,Qp,$p,em,tm,nm,rm,V,im,am,om,sm,cm,lm,um,dm,fm,pm,mm,hm,gm,_m,vm,ym,bm,xm,Sm,Cm,wm,Tm,Em,Dm,Om,km,Am,jm,Mm,Nm,Pm,Fm,Im,Lm,Rm,zm,Bm,Vm,Hm,Um,Wm,Gm,Km,qm,Jm,Ym,Xm,Zm,Qm,$m,eh,th,nh,rh,ih,ah,oh,sh,ch,lh,uh,dh,fh,ph,mh,hh,gh,_h,vh,yh,bh,xh,Sh,Ch,wh,Th,Eh,Dh,Oh,kh,Ah,jh,Mh,Nh,Ph,Fh,Ih,Lh,Rh,zh,Bh,Vh=v((()=>{Pi(),Ba(),il(),lr(),M(),bu(),S(),Ie(),Mt(),Au(),Xt(),Qu(),Yl(),Rr(),F(),T(),Pf(),St(),bc(),dp(),af(),On(),rt(),ap(),fn(),Af(),pp(),mp=(e,t)=>{let n=new vp(`Blocked`);return n.effect_instruction_i0=e,n.effect_instruction_i1=t,n},hp=e=>{let t=new vp(`RunBlocked`);return t.effect_instruction_i0=e,t},gp=Symbol.for(`effect/Effect`),_p=class{patch;op;_op=dn;constructor(e,t){this.patch=e,this.op=t}},vp=class{_op;effect_instruction_i0=void 0;effect_instruction_i1=void 0;effect_instruction_i2=void 0;trace=void 0;[gp]=bn;constructor(e){this._op=e}[j](e){return this===e}[E](){return k(this,wt(this))}pipe(){return P(this,arguments)}toJSON(){return{_id:`Effect`,_op:this._op,effect_instruction_i0:Bt(this.effect_instruction_i0),effect_instruction_i1:Bt(this.effect_instruction_i1),effect_instruction_i2:Bt(this.effect_instruction_i2)}}toString(){return Ht(this.toJSON())}[N](){return this.toJSON()}[Symbol.iterator](){return new fp(new gt(this))}},yp=class{_op;effect_instruction_i0=void 0;effect_instruction_i1=void 0;effect_instruction_i2=void 0;trace=void 0;[gp]=bn;constructor(e){this._op=e,this._tag=e}[j](e){return gh(e)&&e._op===`Failure`&&A(this.effect_instruction_i0,e.effect_instruction_i0)}[E](){return b(Ot(this._tag),O(D(this.effect_instruction_i0)),k(this))}get cause(){return this.effect_instruction_i0}pipe(){return P(this,arguments)}toJSON(){return{_id:`Exit`,_tag:this._op,cause:this.cause.toJSON()}}toString(){return Ht(this.toJSON())}[N](){return this.toJSON()}[Symbol.iterator](){return new fp(new gt(this))}},bp=class{_op;effect_instruction_i0=void 0;effect_instruction_i1=void 0;effect_instruction_i2=void 0;trace=void 0;[gp]=bn;constructor(e){this._op=e,this._tag=e}[j](e){return gh(e)&&e._op===`Success`&&A(this.effect_instruction_i0,e.effect_instruction_i0)}[E](){return b(Ot(this._tag),O(D(this.effect_instruction_i0)),k(this))}get value(){return this.effect_instruction_i0}pipe(){return P(this,arguments)}toJSON(){return{_id:`Exit`,_tag:this._op,value:Bt(this.value)}}toString(){return Ht(this.toJSON())}[N](){return this.toJSON()}[Symbol.iterator](){return new fp(new gt(this))}},xp=e=>w(e,gp),Sp=e=>{let t=new vp(ln);return t.effect_instruction_i0=e,t},Cp=x(3,(e,t,n)=>sm(r=>B(e,e=>B(Ip(rm(()=>r(t(e)))),t=>rm(()=>n(e,t)).pipe(Kp({onFailure:e=>{switch(t._tag){case $t:return zp(zs(t.effect_instruction_i0,e));case rn:return zp(e)}},onSuccess:()=>t})))))),wp=x(2,(e,t)=>B(e,()=>nm(t))),Tp=e=>wp(e,void 0),Ep=function(){let e=new vp(Qt);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(nt(`you're not supposed to end up here`))}return e},Dp=(e,t=mu)=>{let n=new vp(Zt),r;return n.effect_instruction_i0=t=>{r=e(t)},n.effect_instruction_i1=t,tm(n,e=>xp(r)?r:cm)},Op=(e,t=mu)=>rm(()=>Dp(e,t)),kp=(e,t=mu)=>Ep(e,function(){let e,n;function r(t){e?e(t):n===void 0&&(n=t)}let i=new vp(Zt);i.effect_instruction_i0=t=>{e=t,n&&t(n)},i.effect_instruction_i1=t;let a,o;return this.effect_instruction_i0.length===1?a=xt(()=>this.effect_instruction_i0(r)):(o=new AbortController,a=xt(()=>this.effect_instruction_i0(r,o.signal))),a||o?tm(i,e=>(o&&o.abort(),a??cm)):i}),Ap=x(2,(e,t)=>qp(e,{onFailure:t,onSuccess:nm})),jp=Symbol.for(`effect/OriginalAnnotation`),Mp=(e,t)=>yr(t)?new Proxy(e,{has(e,t){return t===vc||t===jp||t in e},get(n,r){return r===vc?t.value:r===jp?e:n[r]}}):e,Np=e=>qe(e)&&!(vc in e)?Sp(t=>zp(Is(Mp(e,Bh(t))))):zp(Is(e)),Pp=e=>Bp(()=>Is(new sh(e))),Fp=e=>qp(e,{onFailure:e=>nm(L(e)),onSuccess:e=>nm(I(e))}),Ip=e=>Gp(e,{onFailure:Ch,onSuccess:Dh}),Lp=e=>qe(e)&&!(vc in e)?Sp(t=>zp(Fs(Mp(e,Bh(t))))):zp(Fs(e)),Rp=e=>B(V(e),Lp),zp=e=>{let t=new yp($t);return t.effect_instruction_i0=e,t},Bp=e=>B(V(e),zp),Vp=Sp(e=>nm(e.id())),Hp=e=>Sp(t=>e(t.id())),B=x(2,(e,t)=>{let n=new vp(tn);return n.effect_instruction_i0=e,n.effect_instruction_i1=t,n}),Up=e=>{let t=new vp(`OnStep`);return t.effect_instruction_i0=e,t},Wp=e=>B(e,be),Gp=x(2,(e,t)=>Kp(e,{onFailure:e=>nm(t.onFailure(e)),onSuccess:e=>nm(t.onSuccess(e))})),Kp=x(2,(e,t)=>{let n=new vp(nn);return n.effect_instruction_i0=e,n.effect_instruction_i1=t.onFailure,n.effect_instruction_i2=t.onSuccess,n}),qp=x(2,(e,t)=>Kp(e,{onFailure:e=>{if(qs(e).length>0)return zp($s(e));let n=Ks(e);return n.length>0?t.onFailure(La(n)):zp(e)},onSuccess:t.onSuccess})),Jp=x(2,(e,t)=>rm(()=>{let n=Ur(e),r=Vr(n.length),i=0;return wp(um({while:()=>i<n.length,body:()=>t(n[i],i),step:e=>{r[i++]=e}}),r)})),Yp=x(2,(e,t)=>rm(()=>{let n=Ur(e),r=0;return um({while:()=>r<n.length,body:()=>t(n[r],r),step:()=>{r++}})})),Xp=e=>{let t=new vp(on);return t.effect_instruction_i0=jf(1),t.effect_instruction_i1=()=>e,t},Zp=x(2,(e,t)=>B(e,e=>V(()=>t(e)))),Qp=x(2,(e,t)=>qp(e,{onFailure:e=>Rp(()=>t.onFailure(e)),onSuccess:e=>V(()=>t.onSuccess(e))})),$p=x(2,(e,t)=>Kp(e,{onFailure:e=>{let n=Xs(e);switch(n._tag){case`Left`:return Rp(()=>t(n.left));case`Right`:return zp(n.right)}},onSuccess:nm})),em=x(2,(e,t)=>sm(n=>Kp(n(e),{onFailure:e=>{let n=Ch(e);return Kp(t(n),{onFailure:t=>Ch(zs(e,t)),onSuccess:()=>n})},onSuccess:e=>{let n=Dh(e);return mm(t(n),n)}}))),tm=x(2,(e,t)=>em(e,Eh({onFailure:e=>Gs(e)?Tp(t(Js(e))):cm,onSuccess:()=>cm}))),nm=e=>{let t=new bp(rn);return t.effect_instruction_i0=e,t},rm=e=>{let t=new vp(Qt);return t.commit=e,t},V=e=>{let t=new vp(an);return t.effect_instruction_i0=e,t},im=x(e=>e.length===3||e.length===2&&!(qe(e[1])&&`onlyEffect`in e[1]),(e,t)=>B(e,e=>{let n=typeof t==`function`?t(e):t;return xp(n)?wp(n,e):tt(n)?Dp(t=>{n.then(n=>t(nm(e)),e=>t(Lp(new hh(e,`An unknown error occurred in Effect.tap`))))}):nm(e)})),am=e=>Sp(t=>{let n=b(t.getFiberRef(Zm),xr(()=>t.scope()));return e(Mm(Zm,z(n)))}),om=e=>{let t=new vp(on);return t.effect_instruction_i0=Mf(1),t.effect_instruction_i1=()=>e,t},sm=e=>Ep(e,function(){let e=new vp(on);return e.effect_instruction_i0=Mf(1),e.effect_instruction_i1=e=>xf(e)?xt(()=>this.effect_instruction_i0(Xp)):xt(()=>this.effect_instruction_i0(om)),e}),cm=nm(void 0),lm=e=>{let t=new vp(on);return t.effect_instruction_i0=e,t.effect_instruction_i1=void 0,t},um=e=>{let t=new vp(sn);return t.effect_instruction_i0=e.while,t.effect_instruction_i1=e.body,t.effect_instruction_i2=e.step,t},dm=e=>{let t=new vp(un);return e?.priority===void 0?t:Gm(t,e.priority)},fm=x(2,(e,t)=>B(e,e=>Zp(t,t=>[e,t]))),pm=x(2,(e,t)=>B(e,e=>wp(t,e))),mm=x(2,(e,t)=>B(e,()=>t)),hm=e=>B(Vp,t=>b(e,gm(t))),gm=x(2,(e,t)=>B(e.interruptAsFork(t),()=>e.await)),_m={_tag:`All`,syslog:0,label:`ALL`,ordinal:-(2**53-1),pipe(){return P(this,arguments)}},vm={_tag:`Fatal`,syslog:2,label:`FATAL`,ordinal:5e4,pipe(){return P(this,arguments)}},ym={_tag:`Error`,syslog:3,label:`ERROR`,ordinal:4e4,pipe(){return P(this,arguments)}},bm={_tag:`Warning`,syslog:4,label:`WARN`,ordinal:3e4,pipe(){return P(this,arguments)}},xm={_tag:`Info`,syslog:6,label:`INFO`,ordinal:2e4,pipe(){return P(this,arguments)}},Sm={_tag:`Debug`,syslog:7,label:`DEBUG`,ordinal:1e4,pipe(){return P(this,arguments)}},Cm={_tag:`Trace`,syslog:7,label:`TRACE`,ordinal:0,pipe(){return P(this,arguments)}},wm={_tag:`None`,syslog:7,label:`OFF`,ordinal:2**53-1,pipe(){return P(this,arguments)}},Tm=`effect/FiberRef`,Em=Symbol.for(Tm),Dm={_A:e=>e},Om=e=>Sp(t=>Dh(t.getFiberRef(e))),km=x(2,(e,t)=>B(Om(e),t)),Am=x(2,(e,t)=>jm(e,()=>[void 0,t])),jm=x(2,(e,t)=>Sp(n=>{let[r,i]=t(n.getFiberRef(e));return n.setFiberRef(e,i),nm(r)})),Mm=x(3,(e,t,n)=>Cp(pm(Om(t),Am(t,n)),()=>e,e=>Am(t,e))),Nm=(e,t)=>Lm(e,{differ:nf(),fork:t?.fork??be,join:t?.join}),Pm=e=>{let t=ef();return Lm(e,{differ:t,fork:t.empty})},Fm=e=>{let t=tf(nf());return Lm(e,{differ:t,fork:t.empty})},Im=e=>{let t=$d();return Lm(e,{differ:t,fork:t.empty})},Lm=(e,t)=>({...Tn,[Em]:Dm,initial:e,commit(){return Om(this)},diff:(e,n)=>t.differ.diff(e,n),combine:(e,n)=>t.differ.combine(e,n),patch:e=>n=>t.differ.patch(e,n),fork:t.fork,join:t.join??((e,t)=>t)}),Rm=e=>Lm(e,{differ:kf,fork:kf.empty}),zm=C(Symbol.for(`effect/FiberRef/currentContext`),()=>Im(Yc())),Bm=C(Symbol.for(`effect/FiberRef/currentSchedulingPriority`),()=>Nm(0)),Vm=C(Symbol.for(`effect/FiberRef/currentMaxOpsBeforeYield`),()=>Nm(2048)),Hm=C(Symbol.for(`effect/FiberRef/currentLogAnnotation`),()=>Nm(xu())),Um=C(Symbol.for(`effect/FiberRef/currentLogLevel`),()=>Nm(xm)),Wm=C(Symbol.for(`effect/FiberRef/currentLogSpan`),()=>Nm(Gu())),Gm=x(2,(e,t)=>Mm(e,Bm,t)),Km=C(Symbol.for(`effect/FiberRef/currentConcurrency`),()=>Nm(`unbounded`)),qm=C(Symbol.for(`effect/FiberRef/currentRequestBatching`),()=>Nm(!0)),Jm=C(Symbol.for(`effect/FiberRef/currentUnhandledErrorLogLevel`),()=>Nm(z(Sm))),Ym=C(Symbol.for(`effect/FiberRef/versionMismatchErrorLogLevel`),()=>Nm(z(bm))),Xm=C(Symbol.for(`effect/FiberRef/currentMetricLabels`),()=>Fm(Si())),Zm=C(Symbol.for(`effect/FiberRef/currentForkScopeOverride`),()=>Nm(R(),{fork:()=>R(),join:(e,t)=>e})),Qm=C(Symbol.for(`effect/FiberRef/currentInterruptedCause`),()=>Nm(Ps,{fork:()=>Ps,join:(e,t)=>e})),$m=Symbol.for(`effect/Scope`),eh=Symbol.for(`effect/CloseableScope`),th=(e,t)=>e.addFinalizer(()=>Tp(t)),nh=(e,t)=>e.close(t),rh=(e,t)=>e.fork(t),ih=function(){class e extends globalThis.Error{commit(){return Lp(this)}toJSON(){let e={...this};return this.message&&(e.message=this.message),this.cause&&(e.cause=this.cause),e}[N](){return this.toString===globalThis.Error.prototype.toString?`Bun`in globalThis?dc(Fs(this),{renderErrorCause:!0}):this:this.stack?`${this.toString()}\n${this.stack.split(`
13
- `).slice(1).join(`
14
- `)}`:this.toString()}}return Object.assign(e.prototype,En),e}(),ah=(e,t)=>{class n extends ih{_tag=t}return Object.assign(n.prototype,e),n.prototype.name=t,n},oh=Symbol.for(`effect/Cause/errors/RuntimeException`),sh=ah({[oh]:oh},`RuntimeException`),ch=Symbol.for(`effect/Cause/errors/InterruptedException`),lh=e=>w(e,ch),uh=Symbol.for(`effect/Cause/errors/IllegalArgument`),dh=ah({[uh]:uh},`IllegalArgumentException`),fh=Symbol.for(`effect/Cause/errors/NoSuchElement`),ph=ah({[fh]:fh},`NoSuchElementException`),mh=Symbol.for(`effect/Cause/errors/UnknownException`),hh=function(){class e extends ih{_tag=`UnknownException`;error;constructor(e,t){super(t??`An unknown error occurred`,{cause:e}),this.error=e}}return Object.assign(e.prototype,{[mh]:mh,name:`UnknownException`}),e}(),gh=e=>xp(e)&&`_tag`in e&&(e._tag===`Success`||e._tag===`Failure`),_h=e=>e._tag===`Success`,vh=x(2,(e,t)=>{switch(e._tag){case $t:return Ch(e.effect_instruction_i0);case rn:return Dh(t)}}),yh=e=>vh(e,void 0),bh=(e,t)=>Ah(e,t?.parallel?Rs:zs),xh=e=>Ch(Is(e)),Sh=e=>Ch(Fs(e)),Ch=e=>{let t=new yp($t);return t.effect_instruction_i0=e,t},wh=e=>Ch(Ls(e)),Th=x(2,(e,t)=>{switch(e._tag){case $t:return Ch(e.effect_instruction_i0);case rn:return Dh(t(e.effect_instruction_i0))}}),Eh=x(2,(e,{onFailure:t,onSuccess:n})=>{switch(e._tag){case $t:return t(e.effect_instruction_i0);case rn:return n(e.effect_instruction_i0)}}),Dh=e=>{let t=new bp(rn);return t.effect_instruction_i0=e,t},Oh=Dh(void 0),kh=x(3,(e,t,{onFailure:n,onSuccess:r})=>{switch(e._tag){case $t:switch(t._tag){case rn:return Ch(e.effect_instruction_i0);case $t:return Ch(n(e.effect_instruction_i0,t.effect_instruction_i0))}case rn:switch(t._tag){case rn:return Dh(r(e.effect_instruction_i0,t.effect_instruction_i0));case $t:return Ch(t.effect_instruction_i0)}}}),Ah=(e,t)=>{let n=Sa(e);return Ia(n)?b(za(n),Oi(b(Ra(n),Th(xa)),(e,n)=>b(e,kh(n,{onSuccess:(e,t)=>b(e,Ma(t)),onFailure:t}))),Th(Da),Th(e=>Ta(e)),z):R()},jh=e=>({...Tn,[sp]:cp,state:Kl(lp([])),commit(){return Mh(this)},blockingOn:e}),Mh=e=>Op(t=>{let n=ql(e.state);switch(n._tag){case ip:return t(n.effect);case rp:return n.joiners.push(t),Ph(e,t)}},e.blockingOn),Nh=(e,t)=>{let n=ql(e.state);if(n._tag===`Pending`){Jl(e.state,up(t));for(let e=0,r=n.joiners.length;e<r;e++)n.joiners[e](t)}},Ph=(e,t)=>V(()=>{let n=ql(e.state);if(n._tag===`Pending`){let e=n.joiners.indexOf(t);e>=0&&n.joiners.splice(e,1)}}),Fh=Sp(e=>Dh(e.currentContext)),Ih=()=>Fh,Lh=e=>B(Ih(),e),Rh=x(2,(e,t)=>Mm(zm,t)(e)),zh=x(2,(e,t)=>Lh(n=>Rh(e,t(n)))),Bh=e=>{let t=e.currentSpan;return t!==void 0&&t._tag===`Span`?z(t):R()}})),Hh,Uh,Wh,Gh=v((()=>{bc(),Vh(),Hh=Hs,Uh=dh,Wh=dc})),Kh,qh,Jh,Yh,Xh=v((()=>{Kh=`InvalidData`,qh=`MissingData`,Jh=`SourceUnavailable`,Yh=`Unsupported`})),Zh,Qh,$h,eg,tg,ng,rg,ig,ag,og,sg,cg=v((()=>{Pi(),lr(),S(),Xh(),Zh=`effect/ConfigError`,Qh=Symbol.for(Zh),$h={_tag:`ConfigError`,[Qh]:Qh},eg=(e,t)=>{let n=Object.create($h);return n._op=`And`,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},tg=(e,t)=>{let n=Object.create($h);return n._op=`Or`,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},ng=(e,t,n={pathDelim:`.`})=>{let r=Object.create($h);return r._op=Kh,r.path=e,r.message=t,Object.defineProperty(r,"toString",{enumerable:!1,value(){return`(Invalid data at ${b(this.path,Ni(n.pathDelim))}: "${this.message}")`}}),r},rg=(e,t,n={pathDelim:`.`})=>{let r=Object.create($h);return r._op=qh,r.path=e,r.message=t,Object.defineProperty(r,"toString",{enumerable:!1,value(){return`(Missing data at ${b(this.path,Ni(n.pathDelim))}: "${this.message}")`}}),r},ig=(e,t,n,r={pathDelim:`.`})=>{let i=Object.create($h);return i._op=Jh,i.path=e,i.message=t,i.cause=n,Object.defineProperty(i,"toString",{enumerable:!1,value(){return`(Source unavailable at ${b(this.path,Ni(r.pathDelim))}: "${this.message}")`}}),i},ag=(e,t,n={pathDelim:`.`})=>{let r=Object.create($h);return r._op=Yh,r.path=e,r.message=t,Object.defineProperty(r,"toString",{enumerable:!1,value(){return`(Unsupported operation at ${b(this.path,Ni(n.pathDelim))}: "${this.message}")`}}),r},og=x(2,(e,t)=>{switch(e._op){case`And`:return eg(og(e.left,t),og(e.right,t));case`Or`:return tg(og(e.left,t),og(e.right,t));case Kh:return ng([...t,...e.path],e.message);case qh:return rg([...t,...e.path],e.message);case Jh:return ig([...t,...e.path],e.message,e.cause);case Yh:return ag([...t,...e.path],e.message)}}),sg=x(3,(e,t,n)=>{let r=[e],i=[];for(;r.length>0;){let e=r.pop();switch(e._op){case`And`:r.push(e.right),r.push(e.left),i.push(L({_op:`AndCase`}));break;case`Or`:r.push(e.right),r.push(e.left),i.push(L({_op:`OrCase`}));break;case Kh:i.push(I(n.invalidDataCase(t,e.path,e.message)));break;case qh:i.push(I(n.missingDataCase(t,e.path,e.message)));break;case Jh:i.push(I(n.sourceUnavailableCase(t,e.path,e.message,e.cause)));break;case Yh:i.push(I(n.unsupportedCase(t,e.path,e.message)))}}let a=[];for(;i.length>0;){let e=i.pop();switch(e._op){case`Left`:switch(e.left._op){case`AndCase`:{let e=a.pop(),r=a.pop(),i=n.andCase(t,e,r);a.push(i);break}case`OrCase`:{let e=a.pop(),r=a.pop(),i=n.orCase(t,e,r);a.push(i);break}}break;case`Right`:a.push(e.right)}}if(a.length===0)throw Error(`BUG: ConfigError.reduceWithContext - please report an issue at https://github.com/Effect-TS/effect/issues`);return a.pop()})})),lg,ug,dg,fg,pg,mg,hg,gg,_g,vg=v((()=>{il(),Ul(),S(),Vh(),lg=`effect/Clock`,ug=Symbol.for(lg),dg=Jc(`effect/Clock`),fg=2**31-1,pg={unsafeSchedule(e,t){let n=jl(t);if(n>fg)return Ce;let r=!1,i=setTimeout(()=>{r=!0,e()},n);return()=>(clearTimeout(i),!r)}},mg=function(){let e=BigInt(1e6);if(typeof performance>`u`||typeof performance.now!=`function`)return()=>BigInt(Date.now())*e;let t;return()=>(t===void 0&&(t=BigInt(Date.now())*e-BigInt(Math.round(performance.now()*1e6))),t+BigInt(Math.round(performance.now()*1e6)))}(),hg=function(){let e=typeof process==`object`&&`hrtime`in process&&typeof process.hrtime.bigint==`function`?process.hrtime:void 0;if(!e)return mg;let t=mg()-e.bigint();return()=>t+e.bigint()}(),gg=class{[ug]=ug;unsafeCurrentTimeMillis(){return Date.now()}unsafeCurrentTimeNanos(){return hg()}currentTimeMillis=V(()=>this.unsafeCurrentTimeMillis());currentTimeNanos=V(()=>this.unsafeCurrentTimeNanos());scheduler(){return nm(pg)}sleep(e){return kp(t=>{let n=pg.unsafeSchedule(()=>t(cm),e);return Tp(V(n))})}},_g=()=>new gg})),yg,bg,xg=v((()=>{zn(),gr(),yg=pr,bg=e=>{if(e===`NaN`)return Rn(NaN);if(e===`Infinity`)return Rn(1/0);if(e===`-Infinity`)return Rn(-1/0);if(e.trim()===``)return Ln;let t=Number(e);return Number.isNaN(t)?Ln:Rn(t)}})),Sg,Cg=v((()=>{Sg=e=>e.replace(/[/\\^$*+?.()|[\]{}]/g,`\\$&`)})),wg,Tg,Eg=v((()=>{Pi(),lr(),S(),Qu(),Rr(),cg(),wg={_tag:`Empty`},Tg=x(2,(e,t)=>{let n=Ku(t),r=e;for(;Hu(n);){let e=n.head;switch(e._tag){case`Empty`:n=n.tail;break;case`AndThen`:n=Wu(e.first,Wu(e.second,n.tail));break;case`MapName`:r=wi(r,e.f),n=n.tail;break;case`Nested`:r=Kr(r,e.name),n=n.tail;break;case`Unnested`:if(b(ii(r),Ir(e.name)))r=ci(r),n=n.tail;else return L(rg(r,`Expected ${e.name} to be in path in ConfigProvider#unnested`))}}return I(r)})})),Dg,Og,kg,Ag,jg,Mg,Ng,Pg,Fg,Ig,Lg,Rg,zg=v((()=>{Dg=`Constant`,Og=`Fail`,kg=`Fallback`,Ag=`Described`,jg=`Lazy`,Mg=`MapOrFail`,Ng=`Nested`,Pg=`Primitive`,Fg=`Redacted`,Ig=`Sequence`,Lg=`HashMap`,Rg=`ZipWith`})),Bg,Vg,Hg,Ug,Wg,Gg,Kg,qg,Jg,Yg,Xg,Zg,Qg,$g,e_,t_,n_,r_,i_,a_,o_,s_,c_,l_=v((()=>{Pi(),il(),lr(),S(),Au(),Cs(),xg(),Rr(),F(),Cg(),cg(),Eg(),Vh(),zg(),Bg=(e,t)=>[...e,...t],Vg=`effect/ConfigProvider`,Hg=Symbol.for(Vg),Ug=Jc(`effect/ConfigProvider`),Wg=`effect/ConfigProviderFlat`,Gg=Symbol.for(Wg),Kg=e=>({[Hg]:Hg,pipe(){return P(this,arguments)},...e}),qg=e=>({[Gg]:Gg,patch:e.patch,load:(t,n,r=!0)=>e.load(t,n,r),enumerateChildren:e.enumerateChildren}),Jg=e=>Kg({load:t=>B(e_(e,Si(),t,!1),e=>br(ii(e),{onNone:()=>Lp(rg(Si(),`Expected a single value having structure: ${t}`)),onSome:nm})),flattened:e}),Yg=e=>{let{pathDelim:t,seqDelim:n}=Object.assign({},{pathDelim:`_`,seqDelim:`,`},e),r=e=>b(e,Ni(t)),i=e=>e.split(t),a=()=>typeof process<`u`&&`env`in process&&typeof process.env==`object`?process.env:{};return Jg(qg({load:(e,t,i=!0)=>{let o=r(e),s=a();return b(o in s?z(s[o]):R(),$p(()=>rg(e,`Expected ${o} to exist in the process context`)),B(r=>r_(r,e,t,n,i)))},enumerateChildren:e=>V(()=>{let t=a(),n=Object.keys(t).map(e=>i(e.toUpperCase())).filter(t=>{for(let n=0;n<e.length;n++){let r=b(e,ri(n)),i=t[n];if(i===void 0||r!==i)return!1}return!0}).flatMap(t=>t.slice(e.length,e.length+1));return ms(n)}),patch:wg}))},Xg=(e,t,n,r)=>{let i=ki(n.length,t=>t>=r.length?R():z([e(t),t+1])),a=ki(r.length,e=>e>=n.length?R():z([t(e),e+1]));return[Bg(n,i),Bg(r,a)]},Zg=(e,t)=>{let n=t;if(n._tag===`Nested`){let t=e.slice();for(;n._tag===`Nested`;)t.push(n.name),n=n.config;return t}return e},Qg={andCase:(e,t,n)=>eg(t,n),orCase:(e,t,n)=>tg(t,n),invalidDataCase:(e,t)=>ng(t,`<redacted>`),missingDataCase:(e,t)=>rg(t,`<redacted>`),sourceUnavailableCase:(e,t,n,r)=>ig(t,`<redacted>`,r),unsupportedCase:(e,t)=>ag(t,`<redacted>`)},$g=e=>sg(e,void 0,Qg),e_=(e,t,n,r)=>{let i=n;switch(i._tag){case Dg:return nm(Ci(i.value));case Ag:return rm(()=>e_(e,t,i.config,r));case Og:return Lp(rg(t,i.message));case kg:return b(rm(()=>e_(e,t,i.first,r)),Ap(n=>i.condition(n)?b(e_(e,t,i.second,r),Ap(e=>Lp(tg(n,e)))):Lp(n)));case jg:return rm(()=>e_(e,t,i.config(),r));case Mg:return rm(()=>b(e_(e,t,i.original,r),B(Jp(e=>b(i.mapOrFail(e),$p(og(Zg(t,i.original))))))));case Ng:return rm(()=>e_(e,Bg(t,Ci(i.name)),i.config,r));case Pg:return b(Tg(t,e.patch),B(t=>b(e.load(t,i,r),B(e=>{if(e.length===0){let e=b(oi(t),xr(()=>`<n/a>`));return Lp(rg([],`Expected ${i.description} with name ${e}`))}return nm(e)}))));case Fg:return rm(()=>b(e_(e,t,i.original,r),$p($g),Zp(wi(i.redact))));case Ig:return b(Tg(t,e.patch),B(n=>b(e.enumerateChildren(n),B(a_),B(n=>n.length===0?rm(()=>Zp(e_(e,t,i.config,!0),Ci)):b(Jp(n,n=>e_(e,qr(t,`[${n}]`),i.config,!0)),Zp(e=>{let t=Ei(e);return t.length===0?Ci(Si()):Ci(t)}))))));case Lg:return rm(()=>b(Tg(t,e.patch),B(t=>b(e.enumerateChildren(t),B(n=>b(n,Jp(n=>e_(e,Bg(t,Ci(n)),i.valueConfig,r)),Zp(e=>e.length===0?Ci(xu()):b(i_(e),wi(e=>Su(mi(Ur(n),e)))))))))));case Rg:return rm(()=>b(e_(e,t,i.left,r),Fp,B(n=>b(e_(e,t,i.right,r),Fp,B(e=>{if(er(n)&&er(e))return Lp(eg(n.left,e.left));if(er(n)&&tr(e))return Lp(n.left);if(tr(n)&&er(e))return Lp(e.left);if(tr(n)&&tr(e)){let r=b(t,Ni(`.`)),a=t_(t,r),[o,s]=Xg(a,a,b(n.right,wi(I)),b(e.right,wi(I)));return b(o,mi(s),Jp(([e,t])=>b(fm(e,t),Zp(([e,t])=>i.zip(e,t)))))}throw Error(`BUG: ConfigProvider.fromFlatLoop - please report an issue at https://github.com/Effect-TS/effect/issues`)})))))}},t_=(e,t)=>n=>L(rg(e,`The element at index ${n} in a sequence at path "${t}" was missing`)),n_=(e,t)=>e.split(RegExp(`\\s*${Sg(t)}\\s*`)),r_=(e,t,n,r,i)=>i?b(n_(e,r),Jp(e=>n.parse(e.trim())),$p(og(t))):b(n.parse(e),Qp({onFailure:og(t),onSuccess:Ci})),i_=e=>Object.keys(e[0]).map(t=>e.map(e=>e[t])),a_=e=>b(Jp(e,s_),Qp({onFailure:()=>Si(),onSuccess:pi(yg)}),Fp,Zp(or)),o_=/^(\[(\d+)\])$/,s_=e=>{let t=e.match(o_);if(t!==null){let e=t[2];return b(e!==void 0&&e.length>0?z(e):R(),kr(c_))}return R()},c_=e=>{let t=Number.parseInt(e);return Number.isNaN(t)?R():z(t)}})),u_,d_,f_,p_=v((()=>{il(),Vh(),u_=Symbol.for(`effect/Console`),d_=Jc(`effect/Console`),f_={[u_]:u_,assert(e,...t){return V(()=>{console.assert(e,...t)})},clear:V(()=>{console.clear()}),count(e){return V(()=>{console.count(e)})},countReset(e){return V(()=>{console.countReset(e)})},debug(...e){return V(()=>{console.debug(...e)})},dir(e,t){return V(()=>{console.dir(e,t)})},dirxml(...e){return V(()=>{console.dirxml(...e)})},error(...e){return V(()=>{console.error(...e)})},group(e){return e?.collapsed?V(()=>console.groupCollapsed(e?.label)):V(()=>console.group(e?.label))},groupEnd:V(()=>{console.groupEnd()}),info(...e){return V(()=>{console.info(...e)})},log(...e){return V(()=>{console.log(...e)})},table(e,t){return V(()=>{console.table(e,t)})},time(e){return V(()=>console.time(e))},timeEnd(e){return V(()=>console.timeEnd(e))},timeLog(e,...t){return V(()=>{console.timeLog(e,...t)})},trace(...e){return V(()=>{console.trace(...e)})},warn(...e){return V(()=>{console.warn(...e)})},unsafe:console}})),m_,h_,g_,__,v_,y_,b_,x_=v((()=>{Ba(),il(),S(),Mt(),St(),Vh(),m_=`effect/Random`,h_=Symbol.for(m_),g_=Jc(`effect/Random`),__=class{seed;[h_]=h_;PRNG;constructor(e){this.seed=e,this.PRNG=new mt(e)}get next(){return V(()=>this.PRNG.number())}get nextBoolean(){return Zp(this.next,e=>e>.5)}get nextInt(){return V(()=>this.PRNG.integer(2**53-1))}nextRange(e,t){return Zp(this.next,n=>(t-e)*n+e)}nextIntBetween(e,t){return V(()=>this.PRNG.integer(t-e)+e)}shuffle(e){return v_(e,e=>this.nextIntBetween(0,e))}},v_=(e,t)=>rm(()=>b(V(()=>Array.from(e)),B(e=>{let n=[];for(let t=e.length;t>=2;--t)n.push(t);return b(n,Yp(n=>b(t(n),Zp(t=>y_(e,n-1,t)))),wp(Sa(e)))}))),y_=(e,t,n)=>{let r=e[t];return e[t]=e[n],e[n]=r,e},b_=e=>new __(D(e))})),S_,C_,w_,T_,E_,D_,O_,k_,A_=v((()=>{il(),S(),S_=Symbol.for(`effect/Tracer`),C_=e=>({[S_]:S_,...e}),w_=Jc(`effect/Tracer`),T_=Jc(`effect/ParentSpan`),E_=function(){return function(e){let t=``;for(let n=0;n<e;n++)t+=`abcdef0123456789`.charAt(Math.floor(Math.random()*16));return t}}(),D_=class{name;parent;context;startTime;kind;_tag=`Span`;spanId;traceId=`native`;sampled=!0;status;attributes;events=[];links;constructor(e,t,n,r,i,a){this.name=e,this.parent=t,this.context=n,this.startTime=i,this.kind=a,this.status={_tag:`Started`,startTime:i},this.attributes=new Map,this.traceId=t._tag===`Some`?t.value.traceId:E_(32),this.spanId=E_(16),this.links=Array.from(r)}end(e,t){this.status={_tag:`Ended`,endTime:e,exit:t,startTime:this.status.startTime}}attribute(e,t){this.attributes.set(e,t)}event(e,t,n){this.events.push([e,t,n??{}])}addLinks(e){this.links.push(...e)}},O_=C_({span:(e,t,n,r,i,a)=>new D_(e,t,n,r,i,a),context:e=>e()}),k_=rl()(`effect/Tracer/DisablePropagation`,{defaultValue:Ce})})),j_,M_,N_=v((()=>{il(),S(),Ie(),vg(),l_(),Vh(),p_(),x_(),A_(),j_=b(Yc(),Zc(dg,_g()),Zc(d_,f_),Zc(g_,b_(Math.random())),Zc(Ug,Yg()),Zc(w_,O_)),M_=C(Symbol.for(`effect/DefaultServices/currentServices`),()=>Im(j_))})),P_,F_,I_=v((()=>{Vh(),P_=function(){let e=Symbol.for(`effect/Data/Error/plainArgs`);return{BaseEffectError:class extends ih{constructor(t){super(t?.message,t?.cause?{cause:t.cause}:void 0),t&&(Object.assign(this,t),Object.defineProperty(this,e,{value:t,enumerable:!1}))}toJSON(){return{...this[e],...this}}}}.BaseEffectError}(),F_=e=>{let t={BaseEffectError:class extends P_{_tag=e}};return t.BaseEffectError.prototype.name=e,t.BaseEffectError}})),L_,R_,z_,B_=v((()=>{On(),L_=Cn,R_=Dn,z_=class extends R_{}})),V_,H_,U_,W_,G_,K_,q_,J_,Y_=v((()=>{V_=`Sequential`,H_=`Parallel`,U_=`ParallelN`,W_={_tag:V_},G_={_tag:H_},K_=e=>({_tag:U_,parallelism:e}),q_=e=>e._tag===V_,J_=e=>e._tag===H_})),X_,Z_,Q_,$_=v((()=>{Y_(),X_=W_,Z_=G_,Q_=K_}));function ev(e){return new rv(e)}function tv(){return ev(new Map)}var nv,rv,iv,av,ov,sv,cv,lv,uv,dv,fv,pv,mv=v((()=>{Pi(),M(),S(),Rr(),F(),nv=Symbol.for(`effect/FiberRefs`),rv=class{locals;[nv]=nv;constructor(e){this.locals=e}pipe(){return P(this,arguments)}},iv=(e,t,n,r=!1)=>{let i=e,a=t,o=n,s=r,c;for(;c===void 0;)if($r(a)&&$r(o)){let e=ai(a)[0],t=ci(a),n=ai(o)[0],r=ai(o)[1],i=ci(o);e.startTimeMillis<n.startTimeMillis?(o=i,s=!0):e.startTimeMillis>n.startTimeMillis?a=t:e.id<n.id?(o=i,s=!0):e.id>n.id?a=t:c=[r,s]}else c=[i.initial,!0];return c},av=x(3,(e,t,n)=>{let r=new Map(e.locals);return n.locals.forEach((e,n)=>{let i=e[0][1];if(!e[0][0][j](t)){if(!r.has(n)){if(A(i,n.initial))return;r.set(n,[[t,n.join(n.initial,i)]]);return}let a=r.get(n),[o,s]=iv(n,a,e);if(s){let e=n.diff(o,i),s=a[0][1],c=n.join(s,n.patch(e)(s));if(!A(s,c)){let e,i=a[0][0];e=i[j](t)?[[i,c],...a.slice(1)]:[[t,c],...a],r.set(n,e)}}}}),new rv(r)}),ov=x(2,(e,t)=>{let n=new Map;return sv(e,n,t),new rv(n)}),sv=(e,t,n)=>{e.locals.forEach((e,r)=>{let i=e[0][1],a=r.patch(r.fork)(i);A(i,a)?t.set(r,e):t.set(r,[[n,a],...e])})},cv=x(2,(e,t)=>{let n=new Map(e.locals);return n.delete(t),new rv(n)}),lv=x(2,(e,t)=>e.locals.has(t)?z(ai(e.locals.get(t))[1]):R()),uv=x(2,(e,t)=>b(lv(e,t),xr(()=>t.initial))),dv=x(2,(e,{fiberId:t,fiberRef:n,value:r})=>{if(e.locals.size===0)return new rv(new Map([[n,[[t,r]]]]));let i=new Map(e.locals);return fv(i,t,n,r),new rv(i)}),fv=(e,t,n,r)=>{let i=e.get(n)??[],a;if($r(i)){let[e,n]=ai(i);if(e[j](t)){if(A(n,r))return;a=[[t,r],...i.slice(1)]}else a=[[t,r],...i]}else a=[[t,r]];e.set(n,a)},pv=x(2,(e,{entries:t,forkAs:n})=>{if(e.locals.size===0)return new rv(new Map(t));let r=new Map(e.locals);return n!==void 0&&sv(e,r,n),t.forEach(([e,t])=>{t.length===1?fv(r,t[0][0],e,t[0][1]):t.forEach(([t,n])=>{fv(r,t,e,n)})}),new rv(r)})})),hv,gv,_v,vv=v((()=>{mv(),hv=uv,gv=pv,_v=tv})),yv,bv,xv,Sv,Cv,wv,Tv,Ev,Dv=v((()=>{Pi(),M(),S(),mv(),yv=`Empty`,bv=`Remove`,xv=`Update`,Sv=`AndThen`,Cv={_tag:yv},wv=(e,t)=>{let n=new Map(e.locals),r=Cv;for(let[e,i]of t.locals.entries()){let t=ai(i)[1],a=n.get(e);if(a!==void 0){let n=ai(a)[1];A(n,t)||(r=Tv({_tag:xv,fiberRef:e,patch:e.diff(n,t)})(r))}else r=Tv({_tag:`Add`,fiberRef:e,value:t})(r);n.delete(e)}for(let[e]of n.entries())r=Tv({_tag:bv,fiberRef:e})(r);return r},Tv=x(2,(e,t)=>({_tag:Sv,first:e,second:t})),Ev=x(3,(e,t,n)=>{let r=n,i=Ci(e);for(;$r(i);){let e=ai(i),n=ci(i);switch(e._tag){case yv:i=n;break;case`Add`:r=dv(r,{fiberId:t,fiberRef:e.fiberRef,value:e.value}),i=n;break;case bv:r=cv(r,e.fiberRef),i=n;break;case xv:{let a=uv(r,e.fiberRef);r=dv(r,{fiberId:t,fiberRef:e.fiberRef,value:e.fiberRef.patch(e.patch)(a)}),i=n;break}case Sv:i=Kr(e.first)(Kr(e.second)(n))}}return r})})),Ov,kv,Av=v((()=>{Dv(),Ov=wv,kv=Ev})),jv,Mv,Nv,Pv,Fv,Iv,Lv,Rv,zv,Bv,Vv,Hv,Uv,Wv,Gv=v((()=>{M(),S(),Mt(),T(),jv=`effect/FiberStatus`,Mv=Symbol.for(jv),Nv=`Done`,Pv=`Running`,Fv=`Suspended`,Iv=Ot(`${jv}-${Nv}`),Lv=class{[Mv]=Mv;_tag=Nv;[E](){return Iv}[j](e){return Uv(e)&&e._tag===`Done`}},Rv=class{runtimeFlags;[Mv]=Mv;_tag=Pv;constructor(e){this.runtimeFlags=e}[E](){return b(D(jv),O(D(this._tag)),O(D(this.runtimeFlags)),k(this))}[j](e){return Uv(e)&&e._tag===`Running`&&this.runtimeFlags===e.runtimeFlags}},zv=class{runtimeFlags;blockingOn;[Mv]=Mv;_tag=Fv;constructor(e,t){this.runtimeFlags=e,this.blockingOn=t}[E](){return b(D(jv),O(D(this._tag)),O(D(this.runtimeFlags)),O(D(this.blockingOn)),k(this))}[j](e){return Uv(e)&&e._tag===`Suspended`&&this.runtimeFlags===e.runtimeFlags&&A(this.blockingOn,e.blockingOn)}},Bv=new Lv,Vv=e=>new Rv(e),Hv=(e,t)=>new zv(e,t),Uv=e=>w(e,Mv),Wv=e=>e._tag===Nv})),Kv,qv,Jv,Yv,Xv=v((()=>{Gv(),Kv=Bv,qv=Vv,Jv=Hv,Yv=Wv})),Zv,Qv,$v,ey,ty,ny,ry,iy,ay,oy,sy,cy=v((()=>{S(),Vh(),xg(),gr(),Zv=_m,Qv=vm,$v=ym,ey=bm,ty=xm,ny=Sm,ry=Cm,iy=wm,ay=b(yg,mr(e=>e.ordinal)),oy=hr(ay),sy=e=>{switch(e){case`All`:return Zv;case`Debug`:return ny;case`Error`:return $v;case`Fatal`:return Qv;case`Info`:return ty;case`Trace`:return ry;case`None`:return iy;case`Warning`:return ey}}}));function ly(e){return Zy(`Micro.evaluate: Not implemented`)}var uy,dy,fy,py,my,hy,gy,_y,vy,yy,by,xy,Sy,Cy,wy,Ty,Ey,Dy,Oy,ky,Ay,jy,My,Ny,Py,Fy,Iy,Ly,Ry,zy,By,Vy,Hy,Uy,Wy,Gy,Ky,qy,Jy,Yy,Xy,Zy,Qy,$y,eb,tb,nb,rb,ib,ab,ob,sb,cb,lb,ub,db,fb,pb,mb,hb=v((()=>{il(),B_(),M(),S(),Ie(),Mt(),Xt(),qc(),On(),F(),T(),St(),uy=Symbol.for(`effect/Micro`),dy=Symbol.for(`effect/Micro/MicroExit`),fy=Symbol.for(`effect/Micro/MicroCause`),py={_E:be},my=class extends globalThis.Error{_tag;traces;[fy];constructor(e,t,n){let r=`MicroCause.${e}`,i,a,o;if(t instanceof globalThis.Error){i=`(${r}) ${t.name}`,a=t.message;let e=a.split(`
15
- `).length;o=t.stack?`(${r}) ${t.stack.split(`
16
- `).slice(0,e+3).join(`
17
- `)}`:`${i}: ${a}`}else i=r,a=Ut(t,0),o=`${i}: ${a}`;n.length>0&&(o+=`\n ${n.join(`
18
- `)}`),super(a),this._tag=e,this.traces=n,this[fy]=py,this.name=i,this.stack=o}pipe(){return P(this,arguments)}toString(){return this.stack}[N](){return this.stack}},hy=class extends my{error;constructor(e,t=[]){super(`Fail`,e,t),this.error=e}},gy=(e,t=[])=>new hy(e,t),_y=class extends my{defect;constructor(e,t=[]){super(`Die`,e,t),this.defect=e}},vy=(e,t=[])=>new _y(e,t),yy=class extends my{constructor(e=[]){super(`Interrupt`,`interrupted`,e)}},by=(e=[])=>new yy(e),xy=e=>e._tag===`Interrupt`,Sy=Symbol.for(`effect/Micro/MicroFiber`),Cy={_A:be,_E:be},wy=class{context;interruptible;[Sy];_stack=[];_observers=[];_exit;_children;currentOpCount=0;constructor(e,t=!0){this.context=e,this.interruptible=t,this[Sy]=Cy}getRef(e){return Hc(this.context,e)}addObserver(e){return this._exit?(e(this._exit),Te):(this._observers.push(e),()=>{let t=this._observers.indexOf(e);t>=0&&this._observers.splice(t,1)})}_interrupted=!1;unsafeInterrupt(){this._exit||(this._interrupted=!0,this.interruptible&&this.evaluate(Xy))}unsafePoll(){return this._exit}evaluate(e){if(this._exit)return;if(this._yielded!==void 0){let e=this._yielded;this._yielded=void 0,e()}let t=this.runLoop(e);if(t===My)return;let n=Ty.interruptChildren&&Ty.interruptChildren(this);if(n!==void 0)return this.evaluate(Gy(n,()=>t));this._exit=t;for(let e=0;e<this._observers.length;e++)this._observers[e](t);this._observers.length=0}runLoop(e){let t=!1,n=e;this.currentOpCount=0;try{for(;;){if(this.currentOpCount++,!t&&this.getRef(ib).shouldYield(this)){t=!0;let e=n;n=Gy(Hy,()=>e)}if(n=n[Oy](this),n===My){let e=this._yielded;return dy in e?(this._yielded=void 0,e):My}}}catch(e){return w(n,Oy)?Zy(e):Zy(`MicroFiber.runLoop: Not a valid effect: ${String(n)}`)}}getCont(e){for(;;){let t=this._stack.pop();if(!t)return;let n=t[jy]&&t[jy](this);if(n)return{[e]:n};if(t[e])return t}}_yielded=void 0;yieldWith(e){return this._yielded=e,My}children(){return this._children??=new Set}},Ty=C(`effect/Micro/fiberMiddleware`,()=>({interruptChildren:void 0})),Ey=Symbol.for(`effect/Micro/identifier`),Dy=Symbol.for(`effect/Micro/args`),Oy=Symbol.for(`effect/Micro/evaluate`),ky=Symbol.for(`effect/Micro/successCont`),Ay=Symbol.for(`effect/Micro/failureCont`),jy=Symbol.for(`effect/Micro/ensureCont`),My=Symbol.for(`effect/Micro/Yield`),Ny={_A:be,_E:be,_R:be},Py={...L_,_op:`Micro`,[uy]:Ny,pipe(){return P(this,arguments)},[Symbol.iterator](){return new st(new gt(this))},toJSON(){return{_id:`Micro`,op:this[Ey],...Dy in this?{args:this[Dy]}:void 0}},toString(){return Ht(this)},[N](){return Ht(this)}},Fy=e=>({...Py,[Ey]:e.op,[Oy]:e.eval??ly,[ky]:e.contA,[Ay]:e.contE,[jy]:e.ensure}),Iy=e=>{let t=Fy(e);return function(){let n=Object.create(t);return n[Dy]=e.single===!1?arguments:arguments[0],n}},Ly=e=>{let t={...Fy(e),[dy]:dy,_tag:e.op,get[e.prop](){return this[Dy]},toJSON(){return{_id:`MicroExit`,_tag:e.op,[e.prop]:this[Dy]}},[j](t){return qy(t)&&t._tag===e.op&&A(this[Dy],t[Dy])},[E](){return k(this,O(Ot(e.op))(D(this[Dy])))}};return function(e){let n=Object.create(t);return n[Dy]=e,n[ky]=void 0,n[Ay]=void 0,n[jy]=void 0,n}},Ry=Ly({op:`Success`,prop:`value`,eval(e){let t=e.getCont(ky);return t?t[ky](this[Dy],e):e.yieldWith(this)}}),zy=Ly({op:`Failure`,prop:`cause`,eval(e){let t=e.getCont(Ay);for(;xy(this[Dy])&&t&&e.interruptible;)t=e.getCont(Ay);return t?t[Ay](this[Dy],e):e.yieldWith(this)}}),By=e=>zy(gy(e)),Vy=Iy({op:`Yield`,eval(e){let t=!1;return e.getRef(ib).scheduleTask(()=>{t||e.evaluate(Qy)},this[Dy]??0),e.yieldWith(()=>{t=!0})}}),Hy=Vy(0),Uy=Ry(void 0),Wy=Iy({op:`WithMicroFiber`,eval(e){return this[Dy](e)}}),Gy=x(2,(e,t)=>{let n=Object.create(Ky);return n[Dy]=e,n[ky]=t,n}),Ky=Fy({op:`OnSuccess`,eval(e){return e._stack.push(this),this[Dy]}}),qy=e=>w(e,dy),Jy=Ry,Yy=zy,Xy=Yy(by()),Zy=e=>Yy(vy(e)),Qy=Jy(void 0),$y=`setImmediate`in globalThis?globalThis.setImmediate:e=>setTimeout(e,0),eb=class{tasks=[];running=!1;scheduleTask(e,t){this.tasks.push(e),this.running||(this.running=!0,$y(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(rb)}flush(){for(;this.tasks.length>0;)this.runTasks()}},tb=x(2,(e,t)=>Wy(n=>{let r=n.context;return n.context=t(r),sb(e,()=>(n.context=r,Uy))})),nb=x(2,(e,t)=>tb(e,tl(t))),rb=class extends rl()(`effect/Micro/currentMaxOpsBeforeYield`,{defaultValue:()=>2048}){},rl()(`effect/Micro/currentConcurrency`,{defaultValue:()=>`unbounded`}),ib=class extends rl()(`effect/Micro/currentScheduler`,{defaultValue:()=>new eb}){},ab=x(2,(e,t)=>{let n=Object.create(ob);return n[Dy]=e,n[ky]=t.onSuccess,n[Ay]=t.onFailure,n}),ob=Fy({op:`OnSuccessAndFailure`,eval(e){return e._stack.push(this),this[Dy]}}),sb=x(2,(e,t)=>ub(n=>ab(n(e),{onFailure:e=>Gy(t(Yy(e)),()=>zy(e)),onSuccess:e=>Gy(t(Jy(e)),()=>Ry(e))}))),cb=Iy({op:`SetInterruptible`,ensure(e){if(e.interruptible=this[Dy],e._interrupted&&e.interruptible)return()=>Xy}}),lb=e=>Wy(t=>t.interruptible?e:(t.interruptible=!0,t._stack.push(cb(!1)),t._interrupted?Xy:e)),ub=e=>Wy(t=>t.interruptible?(t.interruptible=!1,t._stack.push(cb(!0)),e(lb)):e(be)),db=(e,t)=>{let n=new wy(ib.context(t?.scheduler??new eb));if(n.evaluate(e),t?.signal){if(t.signal.aborted)n.unsafeInterrupt();else{let e=()=>n.unsafeInterrupt();t.signal.addEventListener(`abort`,e,{once:!0}),n.addObserver(()=>t.signal.removeEventListener(`abort`,e))}}return n},fb=function(){class e extends globalThis.Error{}return Object.assign(e.prototype,Py,wn,{[Ey]:`Failure`,[Oy](){return By(this)},toString(){return this.message?`${this.name}: ${this.message}`:this.name},toJSON(){return{...this}},[N](){let e=this.stack;return e?`${this.toString()}\n${e.split(`
18
+ `);for(let i=1;i<o.length;i++){if(o[i].includes(" at new BaseEffectError")||o[i].includes(" at new YieldableError")){i++;continue}if(o[i].includes("Generator.next"))break;if(o[i].includes("effect_internal_function"))break;r.push(o[i].replace(/at .*effect_instruction_i.*\((.*)\)/,"at $1").replace(/EffectPrimitive\.\w+/,"<anonymous>"))}if(n){let i=n,a=0;while(i&&i._tag==="Span"&&a<10){let s=mN.get(i);if(typeof s==="function"){let c=s();if(typeof c==="string"){let l=c.matchAll(fN),u=!1;for(let[,p]of l)u=!0,r.push(` at ${i.name} (${p})`);if(!u)r.push(` at ${i.name} (${c.replace(/^at /,"")})`)}else r.push(` at ${i.name}`)}else r.push(` at ${i.name}`);i=Bt(i.parent),a++}}return r.join(`
19
+ `)},gi,Vs=(e)=>Cu(e,void 0,{emptyCase:()=>[],dieCase:(t,n)=>[$m(n)],failCase:(t,n)=>[$m(n)],interruptCase:()=>[],parallelCase:(t,n,r)=>[...n,...r],sequentialCase:(t,n,r)=>[...n,...r]});var Sa=x(()=>{Be();Qn();tn();pe();j();Me();pi();Ve();Ge();be();ye();jm=Symbol.for(vw),sN={_E:(e)=>e},ga={[jm]:sN,[M](){return g(E(vw),G(E(lN(this))),ie(this))},[I](e){return Tw(e)&&cN(this,e)},pipe(){return T(this,arguments)},toJSON(){switch(this._tag){case"Empty":return{_id:"Cause",_tag:this._tag};case"Die":return{_id:"Cause",_tag:this._tag,defect:de(this.defect)};case"Interrupt":return{_id:"Cause",_tag:this._tag,fiberId:this.fiberId.toJSON()};case"Fail":return{_id:"Cause",_tag:this._tag,failure:de(this.error)};case"Sequential":case"Parallel":return{_id:"Cause",_tag:this._tag,left:de(this.left),right:de(this.right)}}},toString(){return Nn(this)},[ne](){return this.toJSON()}},Dr=(()=>{let e=Object.create(ga);return e._tag=go,e})(),Jm=d(2,(e,t)=>{let n=[e];while(n.length>0){let r=n.pop(),o=t(r);switch(o._tag){case"None":{switch(r._tag){case mi:case fi:{n.push(r.right),n.push(r.left);break}}break}case"Some":return o}}return A()}),pN={emptyCase:Ss,failCase:no,dieCase:no,interruptCase:Ss,sequentialCase:(e,t,n)=>t&&n,parallelCase:(e,t,n)=>t&&n},Gm=d(2,(e,{onDie:t,onEmpty:n,onFail:r,onInterrupt:o,onParallel:i,onSequential:a})=>Cu(e,void 0,{emptyCase:()=>n,failCase:(s,c)=>r(c),dieCase:(s,c)=>t(c),interruptCase:(s,c)=>o(c),sequentialCase:(s,c,l)=>a(c,l),parallelCase:(s,c,l)=>i(c,l)})),hi=d(3,(e,t,n)=>{let r=t,o=e,i=[];while(o!==void 0){let a=n(r,o);switch(r=Re(a)?a.value:r,o._tag){case mi:{i.push(o.right),o=o.left;break}case fi:{i.push(o.right),o=o.left;break}default:{o=void 0;break}}if(o===void 0&&i.length>0)o=i.pop()}return r}),Cu=d(3,(e,t,n)=>{let r=[e],o=[];while(r.length>0){let a=r.pop();switch(a._tag){case go:{o.push(Q(n.emptyCase(t)));break}case yo:{o.push(Q(n.failCase(t,a.error)));break}case ha:{o.push(Q(n.dieCase(t,a.defect)));break}case di:{o.push(Q(n.interruptCase(t,a.fiberId)));break}case mi:{r.push(a.right),r.push(a.left),o.push(W({_tag:bw}));break}case fi:{r.push(a.right),r.push(a.left),o.push(W({_tag:ww}));break}}}let i=[];while(o.length>0){let a=o.pop();switch(a._tag){case"Left":{switch(a.left._tag){case bw:{let s=i.pop(),c=i.pop(),l=n.sequentialCase(t,s,c);i.push(l);break}case ww:{let s=i.pop(),c=i.pop(),l=n.parallelCase(t,s,c);i.push(l);break}}break}case"Right":{i.push(a.right);break}}}if(i.length===0)throw Error("BUG: Cause.reduceWithContext - please report an issue at https://github.com/Effect-TS/effect/issues");return i.pop()}),fN=/\((.*)\)/g,mN=V("effect/Tracer/spanToTrace",()=>new WeakMap),gi=Symbol.for("effect/SpanAnnotation")});var Cw,Ks,gN="effect/STM",yN,Aw,xN,Pw=(e)=>{let t=Error.stackTraceLimit;Error.stackTraceLimit=2;let n=Error();Error.stackTraceLimit=t;let r=Object.create(Aw);return Object.defineProperty(r,"stack",{get(){return n.stack}}),r.key=e,r},Iw=()=>(e,t)=>{let n=Error.stackTraceLimit;Error.stackTraceLimit=2;let r=Error();Error.stackTraceLimit=n;function o(){}return Object.setPrototypeOf(o,xN),o.key=e,o.defaultValue=t.defaultValue,Object.defineProperty(o,"stack",{get(){return r.stack}}),o},Zm,SN,xo=(e)=>{let t=Object.create(SN);return t.unsafeMap=e,t},_N=(e)=>{let t=Error(`Service not found${e.key?`: ${String(e.key)}`:""}`);if(e.stack){let n=e.stack.split(`
20
+ `);if(n.length>2){let r=n[2].match(/at (.*)/);if(r)t.message=t.message+` (defined at ${r[1]})`}}if(t.stack){let n=t.stack.split(`
21
+ `);n.splice(1,3),t.stack=n.join(`
22
+ `)}return t},Mw=(e)=>C(e,Zm),Nw=(e)=>C(e,Ks),bN,Fw=()=>bN,Xm=(e,t)=>xo(new Map([[e.key,t]])),Lw,Ym,Qm=(e)=>{if(Ym.has(e.key))return Ym.get(e.key);let t=e.defaultValue();return Ym.set(e.key,t),t},Dw=(e,t)=>e.unsafeMap.has(t.key)?e.unsafeMap.get(t.key):Qm(t),eh,qw,Uw,Hw;var Au=x(()=>{pe();j();Me();Ve();be();ye();Rr();im();Cw=Symbol.for("effect/Context/Tag"),Ks=Symbol.for("effect/Context/Reference"),yN=Symbol.for(gN),Aw={...Or,_op:"Tag",[yN]:ao,[Cw]:{_Service:(e)=>e,_Identifier:(e)=>e},toString(){return ge(this.toJSON())},toJSON(){return{_id:"Tag",key:this.key,stack:this.stack}},[ne](){return this.toJSON()},of(e){return e},context(e){return Xm(this,e)}},xN={...Aw,[Ks]:Ks},Zm=Symbol.for("effect/Context"),SN={[Zm]:{_Services:(e)=>e},[I](e){if(Mw(e)){if(this.unsafeMap.size===e.unsafeMap.size){for(let t of this.unsafeMap.keys())if(!e.unsafeMap.has(t)||!O(this.unsafeMap.get(t),e.unsafeMap.get(t)))return!1;return!0}}return!1},[M](){return ie(this,Yl(this.unsafeMap.size))},pipe(){return T(this,arguments)},toString(){return ge(this.toJSON())},toJSON(){return{_id:"Context",services:Array.from(this.unsafeMap).map(de)}},[ne](){return this.toJSON()}},bN=xo(new Map),Lw=d(3,(e,t,n)=>{let r=new Map(e.unsafeMap);return r.set(t.key,n),xo(r)}),Ym=V("effect/Context/defaultValueCache",()=>new Map),eh=d(2,(e,t)=>{if(!e.unsafeMap.has(t.key)){if(Ks in t)return Qm(t);throw _N(t)}return e.unsafeMap.get(t.key)}),qw=eh,Uw=d(2,(e,t)=>{if(!e.unsafeMap.has(t.key))return Nw(t)?Fs(Qm(t)):nu;return Fs(e.unsafeMap.get(t.key))}),Hw=d(2,(e,t)=>{let n=new Map(e.unsafeMap);for(let[r,o]of t.unsafeMap)n.set(r,o);return xo(n)})});var Kt,So,jw,tr,zs,Ws,_o,Js,Gs;var mn=x(()=>{Au();Kt=Pw,So=Fw,jw=Xm,tr=Lw,zs=qw,Ws=eh,_o=Uw,Js=Hw,Gs=Iw});var nh,Ww,Vw,Pu,rh,Bw,Kw,wN,qr=(e)=>{if(Jw(e))return e;else if(Qt(e))return Iu(e);else if(ro(e))return th(e);else if(Array.isArray(e)&&e.length===2&&e.every(Qt)){if(e[0]===-1/0||e[1]===-1/0||Number.isNaN(e[0])||Number.isNaN(e[1]))return oh;if(e[0]===1/0||e[1]===1/0)return ON;return th(BigInt(Math.round(e[0]*1e9))+BigInt(Math.round(e[1])))}else if(gt(e)){let t=wN.exec(e);if(t){let[n,r,o]=t,i=Number(r);switch(o){case"nano":case"nanos":return th(BigInt(r));case"micro":case"micros":return RN(BigInt(r));case"milli":case"millis":return Iu(i);case"second":case"seconds":return kN(i);case"minute":case"minutes":return CN(i);case"hour":case"hours":return AN(i);case"day":case"days":return PN(i);case"week":case"weeks":return IN(i)}}}throw Error("Invalid DurationInput")},zw,vN,TN,nr=(e)=>{let t=Object.create(TN);if(Qt(e))if(isNaN(e)||e<=0)t.value=zw;else if(!Number.isFinite(e))t.value=vN;else if(!Number.isInteger(e))t.value={_tag:"Nanos",nanos:BigInt(Math.round(e*1e6))};else t.value={_tag:"Millis",millis:e};else if(e<=Ww)t.value=zw;else t.value={_tag:"Nanos",nanos:e};return t},Jw=(e)=>C(e,nh),EN=(e)=>{switch(e.value._tag){case"Millis":return e.value.millis===0;case"Nanos":return e.value.nanos===Ww;case"Infinity":return!1}},oh,ON,th=(e)=>nr(e),RN=(e)=>nr(e*rh),Iu=(e)=>nr(e),kN=(e)=>nr(e*1000),CN=(e)=>nr(e*60000),AN=(e)=>nr(e*3600000),PN=(e)=>nr(e*86400000),IN=(e)=>nr(e*604800000),Mu=(e)=>FN(e,{onMillis:(t)=>t,onNanos:(t)=>Number(t)/1e6}),MN=(e)=>{let t=qr(e);switch(t.value._tag){case"Infinity":throw Error("Cannot convert infinite duration to nanos");case"Nanos":return t.value.nanos;case"Millis":return BigInt(Math.round(t.value.millis*1e6))}},NN=(e)=>{let t=qr(e);switch(t.value._tag){case"Infinity":return[1/0,0];case"Nanos":return[Number(t.value.nanos/Kw),Number(t.value.nanos%Kw)];case"Millis":return[Math.floor(t.value.millis/1000),Math.round(t.value.millis%1000*1e6)]}},FN,ih,LN=(e,t)=>ih(e,t,{onMillis:(n,r)=>n===r,onNanos:(n,r)=>n===r}),Gw,Yw,DN,qN=(e)=>{let t=qr(e);if(t.value._tag==="Infinity")return{days:1/0,hours:1/0,minutes:1/0,seconds:1/0,millis:1/0,nanos:1/0};let n=MN(t),r=n/Bw,o=r/rh,i=o/Pu,a=i/Pu,s=a/Vw;return{days:Number(s),hours:Number(a%Vw),minutes:Number(i%Pu),seconds:Number(o%Pu),millis:Number(r%rh),nanos:Number(n%Bw)}},UN=(e)=>{let t=qr(e);if(t.value._tag==="Infinity")return"Infinity";if(EN(t))return"0";let n=qN(t),r=[];if(n.days!==0)r.push(`${n.days}d`);if(n.hours!==0)r.push(`${n.hours}h`);if(n.minutes!==0)r.push(`${n.minutes}m`);if(n.seconds!==0)r.push(`${n.seconds}s`);if(n.millis!==0)r.push(`${n.millis}ms`);if(n.nanos!==0)r.push(`${n.nanos}ns`);return r.join(" ")};var ah=x(()=>{pe();j();Me();Ve();be();ye();nh=Symbol.for("effect/Duration"),Ww=BigInt(0),Vw=BigInt(24),Pu=BigInt(60),rh=BigInt(1000),Bw=BigInt(1e6),Kw=BigInt(1e9),wN=/^(-?\d+(?:\.\d+)?)\s+(nanos?|micros?|millis?|seconds?|minutes?|hours?|days?|weeks?)$/,zw={_tag:"Millis",millis:0},vN={_tag:"Infinity"},TN={[nh]:nh,[M](){return ie(this,Zl(this.value))},[I](e){return Jw(e)&&DN(this,e)},toString(){return`Duration(${UN(this)})`},toJSON(){switch(this.value._tag){case"Millis":return{_id:"Duration",_tag:"Millis",millis:this.value.millis};case"Nanos":return{_id:"Duration",_tag:"Nanos",hrtime:NN(this)};case"Infinity":return{_id:"Duration",_tag:"Infinity"}}},[ne](){return this.toJSON()},pipe(){return T(this,arguments)}},oh=nr(0),ON=nr(1/0),FN=d(2,(e,t)=>{let n=qr(e);switch(n.value._tag){case"Nanos":return t.onNanos(n.value.nanos);case"Infinity":return t.onMillis(1/0);case"Millis":return t.onMillis(n.value.millis)}}),ih=d(3,(e,t,n)=>{let r=qr(e),o=qr(t);if(r.value._tag==="Infinity"||o.value._tag==="Infinity")return n.onMillis(Mu(r),Mu(o));else if(r.value._tag==="Nanos"||o.value._tag==="Nanos"){let i=r.value._tag==="Nanos"?r.value.nanos:BigInt(Math.round(r.value.millis*1e6)),a=o.value._tag==="Nanos"?o.value.nanos:BigInt(Math.round(o.value.millis*1e6));return n.onNanos(i,a)}return n.onMillis(r.value.millis,o.value.millis)}),Gw=d(2,(e,t)=>ih(e,t,{onMillis:(n,r)=>n<=r,onNanos:(n,r)=>n<=r})),Yw=d(2,(e,t)=>ih(e,t,{onMillis:(n,r)=>n>=r,onNanos:(n,r)=>n>=r})),DN=d(2,(e,t)=>LN(qr(e),qr(t)))});var Xw,HN,Nu=(e)=>{let t=Object.create(HN);return t.current=e,t},_a=(e)=>e.current,Fu;var sh=x(()=>{j();Ve();be();Xw=Symbol.for("effect/MutableRef"),HN={[Xw]:Xw,toString(){return ge(this.toJSON())},toJSON(){return{_id:"MutableRef",current:de(this.current)}},[ne](){return this.toJSON()},pipe(){return T(this,arguments)}},Fu=d(2,(e,t)=>(e.current=t,e))});var lh="effect/FiberId",ba,Lu="None",ch="Runtime",$N="Composite",jN,tv,nv,rv,uh=(e)=>C(e,ba),Du=(e)=>{switch(e._tag){case Lu:return er();case ch:return ci(e.id);case $N:return g(Du(e.left),Lr(Du(e.right)))}},ev,qu=(e)=>Array.from(Du(e)).map((n)=>`#${n}`).join(","),ov=()=>{let e=_a(ev);return g(ev,Fu(e+1)),new nv(e,Date.now())};var ph=x(()=>{pe();j();Me();pi();Ve();sh();ye();ba=Symbol.for(lh),jN=he(`${lh}-${Lu}`);tv=class tv{[ba]=ba;_tag=Lu;id=-1;startTimeMillis=-1;[M](){return jN}[I](e){return uh(e)&&e._tag===Lu}toString(){return ge(this.toJSON())}toJSON(){return{_id:"FiberId",_tag:this._tag}}[ne](){return this.toJSON()}};nv=class nv{id;startTimeMillis;[ba]=ba;_tag=ch;constructor(e,t){this.id=e,this.startTimeMillis=t}[M](){return ie(this,he(`${lh}-${this._tag}-${this.id}-${this.startTimeMillis}`))}[I](e){return uh(e)&&e._tag===ch&&this.id===e.id&&this.startTimeMillis===e.startTimeMillis}toString(){return ge(this.toJSON())}toJSON(){return{_id:"FiberId",_tag:this._tag,id:this.id,startTimeMillis:this.startTimeMillis}}[ne](){return this.toJSON()}};rv=new tv,ev=V(Symbol.for("effect/Fiber/Id/_fiberCounter"),()=>Nu(0))});var hn,av,Uu;var wa=x(()=>{ph();hn=rv,av=qu,Uu=ov});var va,sv,cv,dh,fh,mh,lv,uv,hh;var Hu=x(()=>{Fm();va=pa,sv=ew,cv=nw,dh=rw,fh=si,mh=yu,lv=Su,uv=aw,hh=da});var Zs,yh=(e)=>ke(e),VN=(e)=>Kf(uo(e),yh),BN,KN,$u=(e,t)=>{let n=Object.create(KN);return n.head=e,n.tail=t,n},zN,WN,pv,dv=(e)=>C(e,Zs),rr=(e)=>e._tag==="Nil",xh=(e)=>e._tag==="Cons",JN=()=>pv,Ur=(e,t)=>$u(e,t),bo,Xs=(e)=>$u(e,pv),fv,GN,YN,mv,hv=(e)=>{let t=bo(),n=e;while(!rr(n))t=GN(t,n.head),n=n.tail;return t};var ju=x(()=>{Be();pe();vs();j();Me();Ve();be();ye();Zs=Symbol.for("effect/List"),BN=VN(O),KN={[Zs]:Zs,_tag:"Cons",toString(){return ge(this.toJSON())},toJSON(){return{_id:"List",_tag:"Cons",values:yh(this).map(de)}},[ne](){return this.toJSON()},[I](e){return dv(e)&&this._tag===e._tag&&BN(this,e)},[M](){return ie(this,en(yh(this)))},[Symbol.iterator](){let e=!1,t=this;return{next(){if(e)return this.return();if(t._tag==="Nil")return e=!0,this.return();let n=t.head;return t=t.tail,{done:e,value:n}},return(n){if(!e)e=!0;return{done:!0,value:n}}}},pipe(){return T(this,arguments)}},zN=he("Nil"),WN={[Zs]:Zs,_tag:"Nil",toString(){return ge(this.toJSON())},toJSON(){return{_id:"List",_tag:"Nil"}},[ne](){return this.toJSON()},[M](){return zN},[I](e){return dv(e)&&this._tag===e._tag},[Symbol.iterator](){return{next(){return{done:!0,value:void 0}}}},pipe(){return T(this,arguments)}},pv=Object.create(WN),bo=JN,fv=d(2,(e,t)=>YN(t,e)),GN=d(2,(e,t)=>Ur(t,e)),YN=d(2,(e,t)=>{if(rr(e))return t;else if(rr(t))return e;else{let n=$u(t.head,e),r=n,o=t.tail;while(!rr(o)){let i=$u(o.head,e);r.tail=i,r=i,o=o.tail}return n}}),mv=d(3,(e,t,n)=>{let r=t,o=e;while(!rr(o))r=n(r,o.head),o=o.tail;return r})});var rK,Ta;var Vu=x(()=>{pe();Me();Rr();rK=Object.assign(Object.create(Array.prototype),{[M](){return ie(this,en(this))},[I](e){if(Array.isArray(e)&&this.length===e.length)return this.every((t,n)=>O(t,e[n]));else return!1}}),Ta=function(){function e(t){if(t)Object.assign(this,t)}return e.prototype=Ns,e}()});function gv(e){return e}var XN,ec,QN,e0,_h=()=>e0,t0,n0=(e,t)=>{let n=Object.create(t0);return n.first=e,n.second=t,n},r0,o0=(e,t)=>{let n=Object.create(r0);return n.key=e,n.service=t,n},i0,a0=(e)=>{let t=Object.create(i0);return t.key=e,t},s0,c0=(e,t)=>{let n=Object.create(s0);return n.key=e,n.update=t,n},yv=(e,t)=>{let n=new Map(e.unsafeMap),r=_h();for(let[o,i]of t.unsafeMap.entries())if(n.has(o)){let a=n.get(o);if(n.delete(o),!O(a,i))r=Qs(c0(o,()=>i))(r)}else n.delete(o),r=Qs(o0(o,i))(r);for(let[o]of n.entries())r=Qs(a0(o))(r);return r},Qs,xv;var Sv=x(()=>{Qn();pe();j();Au();Vu();XN=Symbol.for("effect/DifferContextPatch");ec={...Ta.prototype,[XN]:{_Value:gv,_Patch:gv}},QN=Object.assign(Object.create(ec),{_tag:"Empty"}),e0=Object.create(QN),t0=Object.assign(Object.create(ec),{_tag:"AndThen"}),r0=Object.assign(Object.create(ec),{_tag:"AddService"}),i0=Object.assign(Object.create(ec),{_tag:"RemoveService"}),s0=Object.assign(Object.create(ec),{_tag:"UpdateService"}),Qs=d(2,(e,t)=>n0(e,t)),xv=d(2,(e,t)=>{if(e._tag==="Empty")return t;let n=!1,r=tt(e),o=new Map(t.unsafeMap);while(An(r)){let a=Pn(r),s=In(r);switch(a._tag){case"Empty":{r=s;break}case"AddService":{o.set(a.key,a.service),r=s;break}case"AndThen":{r=kt(kt(s,a.second),a.first);break}case"RemoveService":{o.delete(a.key),r=s;break}case"UpdateService":{o.set(a.key,a.update(o.get(a.key))),n=!0,r=s;break}}}if(!n)return xo(o);let i=new Map;for(let[a]of t.unsafeMap)if(o.has(a))i.set(a,o.get(a)),o.delete(a);for(let[a,s]of o)i.set(a,s);return xo(i)})});function bh(e){return e}var u0,Ku,p0,d0,wh=()=>d0,f0,m0=(e,t)=>{let n=Object.create(f0);return n.first=e,n.second=t,n},h0,g0=(e)=>{let t=Object.create(h0);return t.value=e,t},y0,x0=(e)=>{let t=Object.create(y0);return t.value=e,t},_v=(e,t)=>{let[n,r]=ui([e,wh()],([o,i],a)=>{if(_w(a)(o))return[qm(a)(o),i];return[o,Bu(g0(a))(i)]})(t);return ui(r,(o,i)=>Bu(x0(i))(o))(n)},Bu,bv;var wv=x(()=>{Qn();j();pi();Vu();u0=Symbol.for("effect/DifferHashSetPatch");Ku={...Ta.prototype,[u0]:{_Value:bh,_Key:bh,_Patch:bh}},p0=Object.assign(Object.create(Ku),{_tag:"Empty"}),d0=Object.create(p0),f0=Object.assign(Object.create(Ku),{_tag:"AndThen"}),h0=Object.assign(Object.create(Ku),{_tag:"Add"}),y0=Object.assign(Object.create(Ku),{_tag:"Remove"}),Bu=d(2,(e,t)=>m0(e,t)),bv=d(2,(e,t)=>{if(e._tag==="Empty")return t;let n=t,r=tt(e);while(An(r)){let o=Pn(r),i=In(r);switch(o._tag){case"Empty":{r=i;break}case"AndThen":{r=kt(o.first)(kt(o.second)(i));break}case"Add":{n=li(o.value)(n),r=i;break}case"Remove":n=qm(o.value)(n),r=i}}return n})});function vv(e){return e}var _0,nc,b0,w0,vh=()=>w0,v0,T0=(e,t)=>{let n=Object.create(v0);return n.first=e,n.second=t,n},E0,O0=(e)=>{let t=Object.create(E0);return t.values=e,t},R0,k0=(e,t)=>{let n=Object.create(R0);return n.from=e,n.until=t,n},C0,A0=(e,t)=>{let n=Object.create(C0);return n.index=e,n.patch=t,n},Tv=(e)=>{let t=0,n=vh();while(t<e.oldValue.length&&t<e.newValue.length){let r=e.oldValue[t],o=e.newValue[t],i=e.differ.diff(r,o);if(!O(i,e.differ.empty))n=tc(n,A0(t,i));t=t+1}if(t<e.oldValue.length)n=tc(n,k0(0,t));if(t<e.newValue.length)n=tc(n,O0(Fb(t)(e.newValue)));return n},tc,Ev;var Ov=x(()=>{Be();pe();j();Vu();_0=Symbol.for("effect/DifferReadonlyArrayPatch");nc={...Ta.prototype,[_0]:{_Value:vv,_Patch:vv}},b0=Object.assign(Object.create(nc),{_tag:"Empty"}),w0=Object.create(b0),v0=Object.assign(Object.create(nc),{_tag:"AndThen"}),E0=Object.assign(Object.create(nc),{_tag:"Append"}),R0=Object.assign(Object.create(nc),{_tag:"Slice"}),C0=Object.assign(Object.create(nc),{_tag:"Update"}),tc=d(2,(e,t)=>T0(e,t)),Ev=d(3,(e,t,n)=>{if(e._tag==="Empty")return t;let r=t.slice(),o=Rt(e);while(co(o)){let i=et(o),a=kn(o);switch(i._tag){case"Empty":{o=a;break}case"AndThen":{a.unshift(i.first,i.second),o=a;break}case"Append":{for(let s of i.values)r.push(s);o=a;break}case"Slice":{r=r.slice(i.from,i.until),o=a;break}case"Update":{r[i.index]=n.patch(i.patch,r[i.index]),o=a;break}}}return r})});var Rv,I0,wo=(e)=>{let t=Object.create(I0);return t.empty=e.empty,t.diff=e.diff,t.combine=e.combine,t.patch=e.patch,t},Th=()=>wo({empty:_h(),combine:(e,t)=>Qs(t)(e),diff:(e,t)=>yv(e,t),patch:(e,t)=>xv(t)(e)}),Eh=()=>wo({empty:wh(),combine:(e,t)=>Bu(t)(e),diff:(e,t)=>_v(e,t),patch:(e,t)=>bv(t)(e)}),Oh=(e)=>wo({empty:vh(),combine:(t,n)=>tc(t,n),diff:(t,n)=>Tv({oldValue:t,newValue:n,differ:e}),patch:(t,n)=>Ev(t,n,e)}),zu=()=>kv((e,t)=>t),kv=(e)=>wo({empty:ue,combine:(t,n)=>{if(t===ue)return n;if(n===ue)return t;return(r)=>n(t(r))},diff:(t,n)=>{if(O(t,n))return ue;return xs(n)},patch:(t,n)=>e(n,t(n))});var Wu=x(()=>{pe();j();be();Sv();wv();Ov();Rv=Symbol.for("effect/Differ"),I0={[Rv]:{_P:ue,_V:ue},pipe(){return T(this,arguments)}}});var rc=255,Cv=8,Ju=(e)=>e&rc,Gu=(e)=>e>>Cv&rc,xi=(e,t)=>(e&rc)+((t&e&rc)<<Cv),kh,Av=(e)=>xi(e,e),Pv=(e)=>xi(e,0),Iv,Ch,Mv=(e)=>~e>>>0&rc;var Ah=x(()=>{j();kh=xi(0,0),Iv=d(2,(e,t)=>xi(Ju(e)&~t,Gu(e))),Ch=d(2,(e,t)=>e|t)});var M0=0,Hr=1,Fv=2,Ph=4,Yu=16,Ih=32,Lv=(e)=>Zu(e,Ih),Mh,$r=(e)=>Nh(e)&&!N0(e),Nh=(e)=>Zu(e,Hr),Zu,Fh=(...e)=>e.reduce((t,n)=>t|n,0),Dv,Lh=(e)=>Zu(e,Ph),N0=(e)=>Zu(e,Yu),oc,ic,Dh;var ac=x(()=>{j();Wu();Ah();Mh=d(2,(e,t)=>e|t),Zu=d(2,(e,t)=>(e&t)!==0),Dv=Fh(M0),oc=d(2,(e,t)=>xi(e^t,t)),ic=d(2,(e,t)=>e&(Mv(Ju(t))|Gu(t))|Ju(t)&Gu(t)),Dh=wo({empty:kh,diff:(e,t)=>oc(e,t),combine:(e,t)=>Ch(t)(e),patch:(e,t)=>ic(t,e)})});var qv,Uh,Hh;var $h=x(()=>{Ah();qv=Av,Uh=Pv,Hh=Iv});var Vh=(e,t)=>({_tag:"Par",left:e,right:t}),Xu=(e,t)=>({_tag:"Seq",left:e,right:t}),Hv=(e)=>{let t=Xs(e),n=bo();while(!0){let[r,o]=mv(t,[$v(),bo()],([i,a],s)=>{let[c,l]=F0(s);return[H0(i,c),fv(a,l)]});if(n=L0(n,r),rr(o))return hv(n);t=o}throw Error("BUG: BlockedRequests.flatten - please report an issue at https://github.com/Effect-TS/effect/issues")},F0=(e)=>{let t=e,n=$v(),r=bo(),o=bo();while(!0)switch(t._tag){case"Empty":{if(rr(r))return[n,o];t=r.head,r=r.tail;break}case"Par":{r=Ur(t.right,r),t=t.left;break}case"Seq":{let i=t.left,a=t.right;switch(i._tag){case"Empty":{t=a;break}case"Par":{let{left:s,right:c}=i;t=Vh(Xu(s,a),Xu(c,a));break}case"Seq":{let{left:s,right:c}=i;t=Xu(s,Xu(c,a));break}case"Single":{t=i,o=Ur(a,o);break}}break}case"Single":{if(n=U0(n,t),rr(r))return[n,o];t=r.head,r=r.tail;break}}throw Error("BUG: BlockedRequests.step - please report an issue at https://github.com/Effect-TS/effect/issues")},L0=(e,t)=>{if(rr(e))return Xs(jh(t));if($0(t))return e;let n=W0(e.head),r=j0(t);if(n.length===1&&r.length===1&&O(n[0],r[0]))return Ur(z0(e.head,jh(t)),e.tail);return Ur(jh(t),e)},D0,q0,Qu,$v=()=>new Qu(va()),U0=(e,t)=>new Qu(lv(e.map,t.dataSource,(n)=>wb(On(n,jb(t.blockedRequest)),()=>tt(t.blockedRequest)))),H0=(e,t)=>new Qu(hh(e.map,t.map,(n,r,o)=>fh(n,o,Je(dh(n,o),{onNone:()=>r,onSome:(i)=>nn(r,i)})))),$0=(e)=>cv(e.map),j0=(e)=>Array.from(mh(e.map)),jh=(e)=>K0(uv(e.map,(t)=>tt(t))),V0,B0,Bh,K0=(e)=>new Bh(e),z0=(e,t)=>new Bh(hh(t.map,e.map,(n,r,o)=>fh(n,o,Je(dh(n,o),{onNone:()=>dn(),onSome:(i)=>nn(i,r)})))),W0=(e)=>Array.from(mh(e.map)),jv=(e)=>Array.from(e.map);var Vv=x(()=>{Qn();pe();Hu();ju();Ge();D0=Symbol.for("effect/RequestBlock/RequestBlockParallel"),q0={_R:(e)=>e};Qu=class Qu{map;[D0]=q0;constructor(e){this.map=e}};V0=Symbol.for("effect/RequestBlock/RequestBlockSequential"),B0={_R:(e)=>e};Bh=class Bh{map;[V0]=B0;constructor(e){this.map=e}}});var Ea="Pending",ep="Done";var G0="effect/Deferred",Kv,zv,Wv=(e)=>({_tag:Ea,joiners:e}),Jv=(e)=>({_tag:ep,effect:e});var Gv=x(()=>{Kv=Symbol.for(G0),zv={_E:(e)=>e,_A:(e)=>e}});var Oa;var Yv=x(()=>{Oa=class Oa{self;called=!1;constructor(e){this.self=e}next(e){return this.called?{value:e,done:!0}:(this.called=!0,{value:this.self,done:!1})}return(e){return{value:e,done:!0}}throw(e){throw e}[Symbol.iterator](){return new Oa(this.self)}}});class Jh{patch;op;_op=Is;constructor(e,t){this.patch=e,this.op=t}}var rp=(e,t)=>{let n=new pt("Blocked");return n.effect_instruction_i0=e,n.effect_instruction_i1=t,n},Wh=(e)=>{let t=new pt("RunBlocked");return t.effect_instruction_i0=e,t},vo,pt,Gh,Yh,Ra=(e)=>C(e,vo),xt=(e)=>{let t=new pt(tu);return t.effect_instruction_i0=e,t},iT,jr,Vr=(e)=>jr(e,void 0),Zh=function(){let e=new pt(ni);switch(arguments.length){case 2:{e.effect_instruction_i0=arguments[0],e.commit=arguments[1];break}case 3:{e.effect_instruction_i0=arguments[0],e.effect_instruction_i1=arguments[1],e.commit=arguments[2];break}case 4:{e.effect_instruction_i0=arguments[0],e.effect_instruction_i1=arguments[1],e.effect_instruction_i2=arguments[2],e.commit=arguments[3];break}default:throw Error(Xo("you're not supposed to end up here"))}return e},sc=(e,t=hn)=>{let n=new pt(ti),r=void 0;return n.effect_instruction_i0=(o)=>{r=e(o)},n.effect_instruction_i1=t,pc(n,(o)=>Ra(r)?r:nt)},aT=(e,t=hn)=>Ce(()=>sc(e,t)),To=(e,t=hn)=>Zh(e,function(){let n=void 0,r=void 0;function o(c){if(n)n(c);else if(r===void 0)r=c}let i=new pt(ti);i.effect_instruction_i0=(c)=>{if(n=c,r)c(r)},i.effect_instruction_i1=t;let a=void 0,s=void 0;if(this.effect_instruction_i0.length!==1)s=new AbortController,a=yt(()=>this.effect_instruction_i0(o,s.signal));else a=yt(()=>this.effect_instruction_i0(o));return a||s?pc(i,(c)=>{if(s)s.abort();return a??nt}):i}),cc,Zv,op=(e,t)=>{if(Re(t))return new Proxy(e,{has(n,r){return r===gi||r===Zv||r in n},get(n,r){if(r===gi)return t.value;if(r===Zv)return e;return n[r]}});return e},ip=(e)=>qt(e)&&!(gi in e)?xt((t)=>At(rn(op(e,bp(t))))):At(rn(e)),Xh=(e)=>sT(()=>rn(new oF(e))),Si=(e)=>ka(e,{onFailure:(t)=>fe(W(t)),onSuccess:(t)=>fe(Q(t))}),Eo=(e)=>cT(e,{onFailure:ve,onSuccess:Ie}),dt=(e)=>qt(e)&&!(gi in e)?xt((t)=>At(ya(op(e,bp(t))))):At(ya(e)),Qh=(e)=>B(D(e),dt),At=(e)=>{let t=new Gh(jt);return t.effect_instruction_i0=e,t},sT=(e)=>B(D(e),At),eg,lc=(e)=>xt((t)=>e(t.id())),B,tg=(e)=>{let t=new pt("OnStep");return t.effect_instruction_i0=e,t},uc=(e)=>B(e,ue),cT,gn,ka,yn,_i,ap=(e)=>{let t=new pt(ri);return t.effect_instruction_i0=qv(Hr),t.effect_instruction_i1=()=>e,t},Ke,sp,bi,Ca,pc,fe=(e)=>{let t=new Yh(Vt);return t.effect_instruction_i0=e,t},Ce=(e)=>{let t=new pt(ni);return t.commit=e,t},D=(e)=>{let t=new pt(eu);return t.effect_instruction_i0=e,t},cp,ng=(e)=>xt((t)=>{let n=t.getFiberRef(np),r=g(n,Oe(()=>t.scope()));return e(ko(np,F(r)))}),lp=(e)=>{let t=new pt(ri);return t.effect_instruction_i0=Uh(Hr),t.effect_instruction_i1=()=>e,t},Oo=(e)=>Zh(e,function(){let t=new pt(ri);return t.effect_instruction_i0=Uh(Hr),t.effect_instruction_i1=(n)=>Nh(n)?yt(()=>this.effect_instruction_i0(ap)):yt(()=>this.effect_instruction_i0(lp)),t}),nt,rg=(e)=>{let t=new pt(ri);return t.effect_instruction_i0=e,t.effect_instruction_i1=void 0,t},dc=(e)=>{let t=new pt(ra);return t.effect_instruction_i0=e.while,t.effect_instruction_i1=e.body,t.effect_instruction_i2=e.step,t},fc=(e)=>{let t=new pt(ia);return typeof e?.priority<"u"?ST(t,e.priority):t},up,pp,Ro,mc,lT=(e)=>B(eg,(t)=>g(e,hc(t))),hc,uT,pT,dT,og,ig,ag,fT,mT,Q0="effect/FiberRef",eF,tF,dp=(e)=>xt((t)=>Ie(t.getFiberRef(e))),wi,Kh,nF,ko,St=(e,t)=>vi(e,{differ:zu(),fork:t?.fork??ue,join:t?.join}),hT=(e)=>{let t=Eh();return vi(e,{differ:t,fork:t.empty})},rF=(e)=>{let t=Oh(zu());return vi(e,{differ:t,fork:t.empty})},fp=(e)=>{let t=Th();return vi(e,{differ:t,fork:t.empty})},vi=(e,t)=>({...so,[eF]:tF,initial:e,commit(){return dp(this)},diff:(r,o)=>t.differ.diff(r,o),combine:(r,o)=>t.differ.combine(r,o),patch:(r)=>(o)=>t.differ.patch(r,o),fork:t.fork,join:t.join??((r,o)=>o)}),gT=(e)=>vi(e,{differ:Dh,fork:Dh.empty}),Ti,Aa,sg,yT,cg,xT,ST,_T,bT,wT,vT,gc,np,yc,mp,hp,gp=(e,t)=>e.addFinalizer(()=>Vr(t)),lg=(e,t)=>e.close(t),Pa=(e,t)=>e.fork(t),yp,Ei=(e,t)=>{class n extends yp{_tag=t}return Object.assign(n.prototype,e),n.prototype.name=t,n},Xv,oF,zh,NK,TT=(e)=>C(e,zh),Qv,iF,eT,xc,tT,FK,nT,LK,rT,DK,oT,aF,Ia=(e)=>Ra(e)&&("_tag"in e)&&(e._tag==="Success"||e._tag==="Failure"),ug=(e)=>e._tag==="Success",ET,Sc=(e)=>ET(e,void 0),Oi=(e,t)=>sF(e,t?.parallel?yi:Ct),pg=(e)=>ve(rn(e)),_c=(e)=>ve(ya(e)),ve=(e)=>{let t=new Gh(jt);return t.effect_instruction_i0=e,t},dg=(e)=>ve(Mn(e)),tp,xp,Ie=(e)=>{let t=new Yh(Vt);return t.effect_instruction_i0=e,t},xn,fg,sF=(e,t)=>{let n=lu(e);if(!An(n))return A();return g(In(n),ca(g(Pn(n),tp(tt)),(r,o)=>g(r,fg(o,{onSuccess:(i,a)=>g(i,kt(a)),onFailure:t}))),tp(po),tp((r)=>Mr(r)),F)},OT=(e)=>({...so,[Kv]:zv,state:Nu(Wv([])),commit(){return Sp(this)},blockingOn:e}),Sp=(e)=>aT((t)=>{let n=_a(e.state);switch(n._tag){case ep:return t(n.effect);case Ea:return n.joiners.push(t),cF(e,t)}},e.blockingOn),_p=(e,t)=>{let n=_a(e.state);if(n._tag===Ea){Fu(e.state,Jv(t));for(let r=0,o=n.joiners.length;r<o;r++)n.joiners[r](t)}},cF=(e,t)=>D(()=>{let n=_a(e.state);if(n._tag===Ea){let r=n.joiners.indexOf(t);if(r>=0)n.joiners.splice(r,1)}}),lF,RT=()=>lF,Ri=(e)=>B(RT(),e),uF,mg,bp=(e)=>{let t=e.currentSpan;return t!==void 0&&t._tag==="Span"?F(t):A()};var rt=x(()=>{Be();Qn();mn();tn();pe();wa();j();Me();Hu();Ve();ju();sh();Ge();be();ye();$h();io();Sa();Gv();Wu();Rr();ac();Yv();vo=Symbol.for("effect/Effect");pt=class pt{_op;effect_instruction_i0=void 0;effect_instruction_i1=void 0;effect_instruction_i2=void 0;trace=void 0;[vo]=ao;constructor(e){this._op=e}[I](e){return this===e}[M](){return ie(this,Rs(this))}pipe(){return T(this,arguments)}toJSON(){return{_id:"Effect",_op:this._op,effect_instruction_i0:de(this.effect_instruction_i0),effect_instruction_i1:de(this.effect_instruction_i1),effect_instruction_i2:de(this.effect_instruction_i2)}}toString(){return ge(this.toJSON())}[ne](){return this.toJSON()}[Symbol.iterator](){return new Oa(new Tr(this))}};Gh=class Gh{_op;effect_instruction_i0=void 0;effect_instruction_i1=void 0;effect_instruction_i2=void 0;trace=void 0;[vo]=ao;constructor(e){this._op=e,this._tag=e}[I](e){return Ia(e)&&e._op==="Failure"&&O(this.effect_instruction_i0,e.effect_instruction_i0)}[M](){return g(he(this._tag),G(E(this.effect_instruction_i0)),ie(this))}get cause(){return this.effect_instruction_i0}pipe(){return T(this,arguments)}toJSON(){return{_id:"Exit",_tag:this._op,cause:this.cause.toJSON()}}toString(){return ge(this.toJSON())}[ne](){return this.toJSON()}[Symbol.iterator](){return new Oa(new Tr(this))}};Yh=class Yh{_op;effect_instruction_i0=void 0;effect_instruction_i1=void 0;effect_instruction_i2=void 0;trace=void 0;[vo]=ao;constructor(e){this._op=e,this._tag=e}[I](e){return Ia(e)&&e._op==="Success"&&O(this.effect_instruction_i0,e.effect_instruction_i0)}[M](){return g(he(this._tag),G(E(this.effect_instruction_i0)),ie(this))}get value(){return this.effect_instruction_i0}pipe(){return T(this,arguments)}toJSON(){return{_id:"Exit",_tag:this._op,value:de(this.value)}}toString(){return ge(this.toJSON())}[ne](){return this.toJSON()}[Symbol.iterator](){return new Oa(new Tr(this))}};iT=d(3,(e,t,n)=>Oo((r)=>B(e,(o)=>B(Eo(Ce(()=>r(t(o)))),(i)=>Ce(()=>n(o,i)).pipe(gn({onFailure:(a)=>{switch(i._tag){case jt:return At(Ct(i.effect_instruction_i0,a));case Vt:return At(a)}},onSuccess:()=>i})))))),jr=d(2,(e,t)=>B(e,()=>fe(t))),cc=d(2,(e,t)=>ka(e,{onFailure:t,onSuccess:fe})),Zv=Symbol.for("effect/OriginalAnnotation"),eg=xt((e)=>fe(e.id())),B=d(2,(e,t)=>{let n=new pt(ta);return n.effect_instruction_i0=e,n.effect_instruction_i1=t,n}),cT=d(2,(e,t)=>gn(e,{onFailure:(n)=>fe(t.onFailure(n)),onSuccess:(n)=>fe(t.onSuccess(n))})),gn=d(2,(e,t)=>{let n=new pt(na);return n.effect_instruction_i0=e,n.effect_instruction_i1=t.onFailure,n.effect_instruction_i2=t.onSuccess,n}),ka=d(2,(e,t)=>gn(e,{onFailure:(n)=>{if(Km(n).length>0)return At(Rw(n));let o=Bm(n);if(o.length>0)return t.onFailure(Om(o));return At(n)},onSuccess:t.onSuccess})),yn=d(2,(e,t)=>Ce(()=>{let n=ke(e),r=oi(n.length),o=0;return jr(dc({while:()=>o<n.length,body:()=>t(n[o],o),step:(i)=>{r[o++]=i}}),r)})),_i=d(2,(e,t)=>Ce(()=>{let n=ke(e),r=0;return dc({while:()=>r<n.length,body:()=>t(n[r],r),step:()=>{r++}})})),Ke=d(2,(e,t)=>B(e,(n)=>D(()=>t(n)))),sp=d(2,(e,t)=>ka(e,{onFailure:(n)=>Qh(()=>t.onFailure(n)),onSuccess:(n)=>D(()=>t.onSuccess(n))})),bi=d(2,(e,t)=>gn(e,{onFailure:(n)=>{let r=Ru(n);switch(r._tag){case"Left":return Qh(()=>t(r.left));case"Right":return At(r.right)}},onSuccess:fe})),Ca=d(2,(e,t)=>Oo((n)=>gn(n(e),{onFailure:(r)=>{let o=ve(r);return gn(t(o),{onFailure:(i)=>ve(Ct(r,i)),onSuccess:()=>o})},onSuccess:(r)=>{let o=Ie(r);return Ro(t(o),o)}}))),pc=d(2,(e,t)=>Ca(e,xp({onFailure:(n)=>xa(n)?Vr(t(zm(n))):nt,onSuccess:()=>nt}))),cp=d((e)=>e.length===3||e.length===2&&!(qt(e[1])&&("onlyEffect"in e[1])),(e,t)=>B(e,(n)=>{let r=typeof t==="function"?t(n):t;if(Ra(r))return jr(r,n);else if(Y_(r))return sc((o)=>{r.then((i)=>o(fe(n)),(i)=>o(dt(new aF(i,"An unknown error occurred in Effect.tap"))))});return fe(n)})),nt=fe(void 0),up=d(2,(e,t)=>B(e,(n)=>Ke(t,(r)=>[n,r]))),pp=d(2,(e,t)=>B(e,(n)=>jr(t,n))),Ro=d(2,(e,t)=>B(e,()=>t)),mc=aT(()=>{let e=setInterval(()=>{},2147483647);return D(()=>clearInterval(e))}),hc=d(2,(e,t)=>B(e.interruptAsFork(t),()=>e.await)),uT={_tag:"All",syslog:0,label:"ALL",ordinal:Number.MIN_SAFE_INTEGER,pipe(){return T(this,arguments)}},pT={_tag:"Fatal",syslog:2,label:"FATAL",ordinal:50000,pipe(){return T(this,arguments)}},dT={_tag:"Error",syslog:3,label:"ERROR",ordinal:40000,pipe(){return T(this,arguments)}},og={_tag:"Warning",syslog:4,label:"WARN",ordinal:30000,pipe(){return T(this,arguments)}},ig={_tag:"Info",syslog:6,label:"INFO",ordinal:20000,pipe(){return T(this,arguments)}},ag={_tag:"Debug",syslog:7,label:"DEBUG",ordinal:1e4,pipe(){return T(this,arguments)}},fT={_tag:"Trace",syslog:7,label:"TRACE",ordinal:0,pipe(){return T(this,arguments)}},mT={_tag:"None",syslog:7,label:"OFF",ordinal:Number.MAX_SAFE_INTEGER,pipe(){return T(this,arguments)}},eF=Symbol.for(Q0),tF={_A:(e)=>e},wi=d(2,(e,t)=>B(dp(e),t)),Kh=d(2,(e,t)=>nF(e,()=>[void 0,t])),nF=d(2,(e,t)=>xt((n)=>{let[r,o]=t(n.getFiberRef(e));return n.setFiberRef(e,o),fe(r)})),ko=d(3,(e,t,n)=>iT(pp(dp(t),Kh(t,n)),()=>e,(r)=>Kh(t,r))),Ti=V(Symbol.for("effect/FiberRef/currentContext"),()=>fp(So())),Aa=V(Symbol.for("effect/FiberRef/currentSchedulingPriority"),()=>St(0)),sg=V(Symbol.for("effect/FiberRef/currentMaxOpsBeforeYield"),()=>St(2048)),yT=V(Symbol.for("effect/FiberRef/currentLogAnnotation"),()=>St(va())),cg=V(Symbol.for("effect/FiberRef/currentLogLevel"),()=>St(ig)),xT=V(Symbol.for("effect/FiberRef/currentLogSpan"),()=>St(bo())),ST=d(2,(e,t)=>ko(e,Aa,t)),_T=V(Symbol.for("effect/FiberRef/currentConcurrency"),()=>St("unbounded")),bT=V(Symbol.for("effect/FiberRef/currentRequestBatching"),()=>St(!0)),wT=V(Symbol.for("effect/FiberRef/currentUnhandledErrorLogLevel"),()=>St(F(ag))),vT=V(Symbol.for("effect/FiberRef/versionMismatchErrorLogLevel"),()=>St(F(og))),gc=V(Symbol.for("effect/FiberRef/currentMetricLabels"),()=>rF(Pr())),np=V(Symbol.for("effect/FiberRef/currentForkScopeOverride"),()=>St(A(),{fork:()=>A(),join:(e,t)=>e})),yc=V(Symbol.for("effect/FiberRef/currentInterruptedCause"),()=>St(Dr,{fork:()=>Dr,join:(e,t)=>e})),mp=Symbol.for("effect/Scope"),hp=Symbol.for("effect/CloseableScope"),yp=function(){class e extends globalThis.Error{commit(){return dt(this)}toJSON(){let t={...this};if(this.message)t.message=this.message;if(this.cause)t.cause=this.cause;return t}[ne](){if(this.toString!==globalThis.Error.prototype.toString)return this.stack?`${this.toString()}
23
+ ${this.stack.split(`
19
24
  `).slice(1).join(`
20
- `)}`:this.toString()}}),e}(),pb=function(){return class extends fb{constructor(e){super(),e&&Object.assign(this,e)}}}(),mb=e=>{class t extends pb{_tag=e}return t.prototype.name=e,t},mb(`NoSuchElementException`),mb(`TimeoutException`)})),gb,_b,vb,yb,bb,xb,Sb=v((()=>{Ie(),Vh(),gb=class e{scheduleDrain;running=!1;tasks=new _b;constructor(e){this.scheduleDrain=e}starveInternal=e=>{let t=this.tasks.buckets;this.tasks.buckets=[];for(let[e,n]of t)for(let e=0;e<n.length;e++)n[e]();this.tasks.buckets.length===0?this.running=!1:this.starve(e)};starve(e=0){this.scheduleDrain(e,this.starveInternal)}scheduleTask(e,t){this.tasks.scheduleTask(e,t),this.running||(this.running=!0,this.starve())}static cached(t){let n=new e(t),r=new WeakMap;return i=>{if(i===void 0)return n;let a=r.get(i);return a===void 0&&(a=new e(t),r.set(i,a)),a}}},_b=class{buckets=[];scheduleTask(e,t){let n=this.buckets.length,r,i=0;for(;i<n&&this.buckets[i][0]<=t;i++)r=this.buckets[i];r&&r[0]===t?r[1].push(e):i===n?this.buckets.push([t,[e]]):this.buckets.splice(i,0,[t,[e]])}},vb=class{maxNextTickBeforeTimer;getRunner=gb.cached((e,t)=>{e>=this.maxNextTickBeforeTimer?setTimeout(()=>t(0),0):Promise.resolve(void 0).then(()=>t(e+1))});constructor(e){this.maxNextTickBeforeTimer=e}shouldYield(e){return e.currentOpCount>e.getFiberRef(Vm)&&e.getFiberRef(Bm)}scheduleTask(e,t,n){this.getRunner(n).scheduleTask(e,t)}},yb=C(Symbol.for(`effect/Scheduler/defaultScheduler`),()=>new vb(2048)),bb=class{tasks=new _b;deferred=!1;scheduleTask(e,t,n){this.deferred?yb.scheduleTask(e,t,n):this.tasks.scheduleTask(e,t)}shouldYield(e){return e.currentOpCount>e.getFiberRef(Vm)&&e.getFiberRef(Bm)}flush(){for(;this.tasks.buckets.length>0;){let e=this.tasks.buckets;this.tasks.buckets=[];for(let[t,n]of e)for(let e=0;e<n.length;e++)n[e]()}this.deferred=!0}},xb=C(Symbol.for(`effect/FiberRef/currentScheduler`),()=>Nm(yb))})),Cb,wb=v((()=>{Ie(),Vh(),Cb=C(Symbol.for(`effect/FiberRef/currentRequestMap`),()=>Nm(new Map))})),Tb,Eb=v((()=>{Vh(),Tb=(e,t,n,r)=>{switch(e){case void 0:return t();case`unbounded`:return n();case`inherit`:return km(Km,e=>e===`unbounded`?n():e>1?r(e):t());default:return e>1?r(e):t()}}})),Db,Ob,kb=v((()=>{Db=e=>e.replace(/[\s="]/g,`_`),Ob=e=>t=>`${Db(t.label)}=${e-t.startTime}ms`})),Ab,jb,Mb,Nb,Pb,Fb=v((()=>{M(),Mt(),F(),T(),Ab=`effect/MetricLabel`,jb=Symbol.for(Ab),Mb=class{key;value;[jb]=jb;_hash;constructor(e,t){this.key=e,this.value=t,this._hash=Ot(Ab+this.key+this.value)}[E](){return this._hash}[j](e){return Pb(e)&&this.key===e.key&&this.value===e.value}pipe(){return P(this,arguments)}},Nb=(e,t)=>new Mb(e,t),Pb=e=>w(e,jb)})),Ib,Lb=v((()=>{il(),Rr(),A_(),Ib=kr(e=>Qc(e.context,k_)?e._tag===`Span`?Ib(e.parent):R():z(e))})),Rb,zb=v((()=>{Vh(),Rb=_h})),Bb,Vb,Hb,Ub,Wb,Gb,Kb,qb,Jb=v((()=>{Bb=`InterruptSignal`,Vb=`Stateful`,Hb=`Resume`,Ub=`YieldNow`,Wb=e=>({_tag:Bb,cause:e}),Gb=e=>({_tag:Vb,onFiber:e}),Kb=e=>({_tag:Hb,effect:e}),qb=()=>({_tag:Ub})})),Yb,Xb,Zb,Qb,$b,ex,tx=v((()=>{bu(),Ie(),Jb(),Yb=`effect/FiberScope`,Xb=Symbol.for(Yb),Zb=class{[Xb]=Xb;fiberId=mu;roots=new Set;add(e,t){this.roots.add(t),t.addObserver(()=>{this.roots.delete(t)})}},Qb=class{fiberId;parent;[Xb]=Xb;constructor(e,t){this.fiberId=e,this.parent=t}add(e,t){this.parent.tell(Gb(e=>{e.addChild(t),t.addObserver(()=>{e.removeChild(t)})}))}},$b=e=>new Qb(e.id(),e),ex=C(Symbol.for(`effect/FiberScope/Global`),()=>new Zb)})),nx,rx,ix,ax,ox,sx,cx,lx,ux=v((()=>{bu(),Rr(),F(),Vh(),On(),nx=`effect/Fiber`,rx=Symbol.for(nx),ix={_E:e=>e,_A:e=>e},ax={[rx]:ix,pipe(){return P(this,arguments)}},ox=`effect/Fiber`,sx=Symbol.for(ox),cx=e=>pm(Wp(e.await),e.inheritAll),{...Tn},{...ax},lx=`effect/FiberCurrent`})),dx,fx,px,mx,hx,gx,_x,vx,yx,bx,xx=v((()=>{Pi(),Xt(),F(),bc(),pu(),kb(),dx=`effect/Logger`,fx=Symbol.for(dx),px={_Message:e=>e,_Output:e=>e},mx=e=>({[fx]:px,log:e,pipe(){return P(this,arguments)}}),hx=/^[^\s"=]*$/,gx=(e,t)=>({annotations:n,cause:r,date:i,fiberId:a,logLevel:o,message:s,spans:c})=>{let l=t=>t.match(hx)?t:e(t),u=(e,t)=>`${Db(e)}=${l(t)}`,d=(e,t)=>` `+u(e,t),f=u(`timestamp`,i.toISOString());f+=d(`level`,o.label),f+=d(`fiber`,du(a));let p=Wr(s);for(let e=0;e<p.length;e++)f+=d(`message`,Ut(p[e],t));Vs(r)||(f+=d(`cause`,dc(r,{renderErrorCause:!0})));for(let e of c)f+=` `+Ob(i.getTime())(e);for(let[e,r]of n)f+=d(e,Ut(r,t));return f},_x=e=>`"${e.replace(/\\([\s\S])|(")/g,`\\$1$2`)}"`,vx=mx(gx(_x)),yx={bold:`1`,red:`31`,green:`32`,yellow:`33`,blue:`34`,cyan:`36`,white:`37`,gray:`90`,black:`30`,bgBrightRed:`101`},yx.gray,yx.blue,yx.green,yx.yellow,yx.red,yx.bgBrightRed,yx.black,bx=typeof process==`object`&&process!==null&&typeof process.stdout==`object`&&process.stdout!==null,bx&&process.stdout.isTTY,bx||`Deno`in globalThis})),Sx,Cx,wx,Tx,Ex,Dx,Ox=v((()=>{Pi(),Ba(),M(),S(),Mt(),F(),T(),Sx=`effect/MetricBoundaries`,Cx=Symbol.for(Sx),wx=class{values;[Cx]=Cx;constructor(e){this.values=e,this._hash=b(Ot(Sx),O(jt(this.values)))}_hash;[E](){return this._hash}[j](e){return Tx(e)&&A(this.values,e.values)}pipe(){return P(this,arguments)}},Tx=e=>w(e,Cx),Ex=e=>{let t=b(e,Jr(xa(1/0)),Mi);return new wx(t)},Dx=e=>b(Hr(e.count-1,t=>e.start*e.factor**+t),Oa,Ex)})),kx,Ax,jx,Mx,Nx,Px,Fx,Ix,Lx,Rx,zx,Bx,Vx,Hx,Ux,Wx,Gx,Kx,qx,Jx,Yx,Xx,Zx=v((()=>{M(),S(),Mt(),F(),T(),kx=`effect/MetricKeyType`,Ax=Symbol.for(kx),jx=`effect/MetricKeyType/Counter`,Mx=Symbol.for(jx),Nx=`effect/MetricKeyType/Frequency`,Px=Symbol.for(Nx),Fx=`effect/MetricKeyType/Gauge`,Ix=Symbol.for(Fx),Lx=`effect/MetricKeyType/Histogram`,Rx=Symbol.for(Lx),zx=`effect/MetricKeyType/Summary`,Bx=Symbol.for(zx),Vx={_In:e=>e,_Out:e=>e},Hx=class{incremental;bigint;[Ax]=Vx;[Mx]=Mx;constructor(e,t){this.incremental=e,this.bigint=t,this._hash=Ot(jx)}_hash;[E](){return this._hash}[j](e){return Kx(e)}pipe(){return P(this,arguments)}},Ux=class{boundaries;[Ax]=Vx;[Rx]=Rx;constructor(e){this.boundaries=e,this._hash=b(Ot(Lx),O(D(this.boundaries)))}_hash;[E](){return this._hash}[j](e){return Yx(e)&&A(this.boundaries,e.boundaries)}pipe(){return P(this,arguments)}},Wx=e=>new Hx(e?.incremental??!1,e?.bigint??!1),Gx=e=>new Ux(e),Kx=e=>w(e,Mx),qx=e=>w(e,Px),Jx=e=>w(e,Ix),Yx=e=>w(e,Rx),Xx=e=>w(e,Bx)})),Qx,$x,eS,tS,nS,rS,iS,aS,oS,sS=v((()=>{Pi(),M(),S(),Mt(),Rr(),F(),T(),Zx(),Qx=`effect/MetricKey`,$x=Symbol.for(Qx),eS={_Type:e=>e},tS=Ai(A),nS=class{name;keyType;description;tags;[$x]=eS;constructor(e,t,n,r=[]){this.name=e,this.keyType=t,this.description=n,this.tags=r,this._hash=b(Ot(this.name+this.description),O(D(this.keyType)),O(jt(this.tags)))}_hash;[E](){return this._hash}[j](e){return rS(e)&&this.name===e.name&&A(this.keyType,e.keyType)&&A(this.description,e.description)&&tS(this.tags,e.tags)}pipe(){return P(this,arguments)}},rS=e=>w(e,$x),iS=(e,t)=>new nS(e,Wx(t),wr(t?.description)),aS=(e,t,n)=>new nS(e,Gx(t),wr(n)),oS=x(2,(e,t)=>t.length===0?e:new nS(e.name,e.keyType,e.description,xi(e.tags,t)))})),cS,lS,uS,dS,fS,pS,mS,hS,gS,_S,vS=v((()=>{M(),S(),Mt(),Xt(),Rr(),F(),cS=Symbol.for(`effect/MutableHashMap`),lS={[cS]:cS,[Symbol.iterator](){return new uS(this)},toString(){return Ht(this.toJSON())},toJSON(){return{_id:`MutableHashMap`,values:Array.from(this).map(Bt)}},[N](){return this.toJSON()},pipe(){return P(this,arguments)}},uS=class e{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();return e.done?(this.bucketIterator=new dS(this.self.buckets.values()),this.next()):e}[Symbol.iterator](){return new e(this.self)}},dS=class{backing;constructor(e){this.backing=e}currentBucket;next(){if(this.currentBucket===void 0){let e=this.backing.next();if(e.done)return e;this.currentBucket=e.value[Symbol.iterator]()}let e=this.currentBucket.next();return e.done?(this.currentBucket=void 0,this.next()):e}},fS=()=>{let e=Object.create(lS);return e.referential=new Map,e.buckets=new Map,e.bucketsSize=0,e},pS=x(2,(e,t)=>{if(Pt(t)===!1)return e.referential.has(t)?z(e.referential.get(t)):R();let n=t[E](),r=e.buckets.get(n);return r===void 0?R():mS(e,r,t)}),mS=(e,t,n,r=!1)=>{for(let i=0,a=t.length;i<a;i++)if(n[j](t[i][0])){let n=t[i][1];return r&&(t.splice(i,1),e.bucketsSize--),z(n)}return R()},hS=x(2,(e,t)=>yr(pS(e,t))),gS=x(3,(e,t,n)=>{if(Pt(t)===!1)return e.referential.set(t,n),e;let r=t[E](),i=e.buckets.get(r);return i===void 0?(e.buckets.set(r,[[t,n]]),e.bucketsSize++,e):(_S(e,i,t),i.push([t,n]),e.bucketsSize++,e)}),_S=(e,t,n)=>{for(let r=0,i=t.length;r<i;r++)if(n[j](t[r][0])){t.splice(r,1),e.bucketsSize--;return}}})),yS,bS,xS,SS,CS,wS,TS,ES,DS,OS,kS,AS,jS,MS,NS,PS,FS,IS,LS,RS,zS,BS,VS,HS,US,WS,GS,KS,qS,JS=v((()=>{Pi(),M(),S(),Mt(),F(),T(),yS=`effect/MetricState`,bS=Symbol.for(yS),xS=`effect/MetricState/Counter`,SS=Symbol.for(xS),CS=`effect/MetricState/Frequency`,wS=Symbol.for(CS),TS=`effect/MetricState/Gauge`,ES=Symbol.for(TS),DS=`effect/MetricState/Histogram`,OS=Symbol.for(DS),kS=`effect/MetricState/Summary`,AS=Symbol.for(kS),jS={_A:e=>e},MS=class{count;[bS]=jS;[SS]=SS;constructor(e){this.count=e}[E](){return b(D(xS),O(D(this.count)),k(this))}[j](e){return US(e)&&this.count===e.count}pipe(){return P(this,arguments)}},NS=Ai(A),PS=class{occurrences;[bS]=jS;[wS]=wS;constructor(e){this.occurrences=e}_hash;[E](){return b(Ot(CS),O(jt(Ur(this.occurrences.entries()))),k(this))}[j](e){return WS(e)&&NS(Ur(this.occurrences.entries()),Ur(e.occurrences.entries()))}pipe(){return P(this,arguments)}},FS=class{value;[bS]=jS;[ES]=ES;constructor(e){this.value=e}[E](){return b(D(TS),O(D(this.value)),k(this))}[j](e){return GS(e)&&this.value===e.value}pipe(){return P(this,arguments)}},IS=class{buckets;count;min;max;sum;[bS]=jS;[OS]=OS;constructor(e,t,n,r,i){this.buckets=e,this.count=t,this.min=n,this.max=r,this.sum=i}[E](){return b(D(DS),O(D(this.buckets)),O(D(this.count)),O(D(this.min)),O(D(this.max)),O(D(this.sum)),k(this))}[j](e){return KS(e)&&A(this.buckets,e.buckets)&&this.count===e.count&&this.min===e.min&&this.max===e.max&&this.sum===e.sum}pipe(){return P(this,arguments)}},LS=class{error;quantiles;count;min;max;sum;[bS]=jS;[AS]=AS;constructor(e,t,n,r,i,a){this.error=e,this.quantiles=t,this.count=n,this.min=r,this.max=i,this.sum=a}[E](){return b(D(kS),O(D(this.error)),O(D(this.quantiles)),O(D(this.count)),O(D(this.min)),O(D(this.max)),O(D(this.sum)),k(this))}[j](e){return qS(e)&&this.error===e.error&&A(this.quantiles,e.quantiles)&&this.count===e.count&&this.min===e.min&&this.max===e.max&&this.sum===e.sum}pipe(){return P(this,arguments)}},RS=e=>new MS(e),zS=e=>new PS(e),BS=e=>new FS(e),VS=e=>new IS(e.buckets,e.count,e.min,e.max,e.sum),HS=e=>new LS(e.error,e.quantiles,e.count,e.min,e.max,e.sum),US=e=>w(e,SS),WS=e=>w(e,wS),GS=e=>w(e,ES),KS=e=>w(e,OS),qS=e=>w(e,AS)})),YS,XS,ZS,QS,$S,eC,tC,nC,rC,iC,aC,oC,sC=v((()=>{Pi(),Ul(),S(),xg(),Rr(),F(),JS(),YS=`effect/MetricHook`,XS=Symbol.for(YS),ZS={_In:e=>e,_Out:e=>e},QS=e=>({[XS]:ZS,pipe(){return P(this,arguments)},...e}),$S=BigInt(0),eC=e=>{let t=e.keyType.bigint?$S:0,n=e.keyType.incremental?e.keyType.bigint?e=>e>=$S:e=>e>=0:e=>!0,r=e=>{n(e)&&(t+=e)};return QS({get:()=>RS(t),update:r,modify:r})},tC=e=>{let t=new Map;for(let n of e.keyType.preregisteredWords)t.set(n,0);let n=e=>{let n=t.get(e)??0;t.set(e,n+1)};return QS({get:()=>zS(t),update:n,modify:n})},nC=(e,t)=>{let n=t;return QS({get:()=>BS(n),update:e=>{n=e},modify:e=>{n+=e}})},rC=e=>{let t=e.keyType.boundaries.values,n=t.length,r=new Uint32Array(n+1),i=new Float64Array(n),a=0,o=0,s=Number.MAX_VALUE,c=Number.MIN_VALUE;b(t,pi(yg),wi((e,t)=>{i[t]=e}));let l=e=>{let t=0,l=n;for(;t!==l;){let n=Math.floor(t+(l-t)/2);e<=i[n]?l=n:t=n,l===t+1&&(e<=i[t]?l=t:t=l)}r[t]=r[t]+1,a+=1,o+=e,e<s&&(s=e),e>c&&(c=e)},u=()=>{let e=Vr(n),t=0;for(let a=0;a<n;a++){let n=i[a],o=r[a];t+=o,e[a]=[n,t]}return e};return QS({get:()=>VS({buckets:u(),count:a,min:s,max:c,sum:o}),update:l,modify:l})},iC=e=>{let{error:t,maxAge:n,maxSize:r,quantiles:i}=e.keyType,a=b(i,pi(yg)),o=Vr(r),s=0,c=0,l=0,u=0,d=0,f=e=>{let i=[],s=0;for(;s!==r-1;){let t=o[s];if(t!=null){let[r,a]=t,o=Tl(e-r);zl(o,xl)&&Rl(o,n)&&i.push(a)}s+=1}return aC(t,a,pi(i,yg))},p=(e,t)=>{if(r>0){s+=1;let n=s%r;o[n]=[t,e]}u=c===0?e:Math.min(u,e),d=c===0?e:Math.max(d,e),c+=1,l+=e};return QS({get:()=>HS({error:t,quantiles:f(Date.now()),count:c,min:u,max:d,sum:l}),update:([e,t])=>p(e,t),modify:([e,t])=>p(e,t)})},aC=(e,t,n)=>{let r=n.length;if(!$r(t))return Si();let i=t[0],a=t.slice(1),o=oC(e,r,R(),0,i,n),s=Ci(o);return a.forEach(t=>{s.push(oC(e,r,o.value,o.consumed,t,o.rest))}),wi(s,e=>[e.quantile,e.value])},oC=(e,t,n,r,i,a)=>{let o=e,s=t,c=n,l=r,u=i,d=a,f=e,p=t,m=n,h=r,g=i,_=a;for(;;){if(!$r(d))return{quantile:u,value:R(),consumed:l,rest:[]};if(u===1)return{quantile:u,value:z(si(d)),consumed:l+d.length,rest:[]};let e=ai(d),t=ui(d,t=>t===e),n=u*s,r=o/2*n,i=l+t[0].length,a=Math.abs(i-n);if(i<n-r){f=o,p=s,m=ii(d),h=i,g=u,_=t[1],o=f,s=p,c=m,l=h,u=g,d=_;continue}if(i>n+r){let t=vr(c)?z(e):c;return{quantile:u,value:t,consumed:l,rest:d}}switch(c._tag){case`None`:f=o,p=s,m=ii(d),h=i,g=u,_=t[1],o=f,s=p,c=m,l=h,u=g,d=_;continue;case`Some`:if(a<Math.abs(n-c.value)){f=o,p=s,m=ii(d),h=i,g=u,_=t[1],o=f,s=p,c=m,l=h,u=g,d=_;continue}return{quantile:u,value:z(c.value),consumed:l,rest:d}}}throw Error(`BUG: MetricHook.resolveQuantiles - please report an issue at https://github.com/Effect-TS/effect/issues`)}})),cC,lC,uC,dC,fC=v((()=>{F(),cC=`effect/MetricPair`,lC=Symbol.for(cC),uC={_Type:e=>e},dC=(e,t)=>({[lC]:uC,metricKey:e,metricState:t,pipe(){return P(this,arguments)}})})),pC,mC,hC,gC,_C=v((()=>{S(),vS(),Rr(),sC(),Zx(),fC(),pC=`effect/MetricRegistry`,mC=Symbol.for(pC),hC=class{[mC]=mC;map=fS();snapshot(){let e=[];for(let[t,n]of this.map)e.push(dC(t,n.get()));return e}get(e){let t=b(this.map,pS(e),Tr);if(t==null){if(Kx(e.keyType))return this.getCounter(e);if(Jx(e.keyType))return this.getGauge(e);if(qx(e.keyType))return this.getFrequency(e);if(Yx(e.keyType))return this.getHistogram(e);if(Xx(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`)}return t}getCounter(e){let t=b(this.map,pS(e),Tr);if(t==null){let n=eC(e);b(this.map,hS(e))||b(this.map,gS(e,n)),t=n}return t}getFrequency(e){let t=b(this.map,pS(e),Tr);if(t==null){let n=tC(e);b(this.map,hS(e))||b(this.map,gS(e,n)),t=n}return t}getGauge(e){let t=b(this.map,pS(e),Tr);if(t==null){let n=nC(e,e.keyType.bigint?BigInt(0):0);b(this.map,hS(e))||b(this.map,gS(e,n)),t=n}return t}getHistogram(e){let t=b(this.map,pS(e),Tr);if(t==null){let n=rC(e);b(this.map,hS(e))||b(this.map,gS(e,n)),t=n}return t}getSummary(e){let t=b(this.map,pS(e),Tr);if(t==null){let n=iC(e);b(this.map,hS(e))||b(this.map,gS(e,n)),t=n}return t}},gC=()=>new hC})),vC,yC,bC,xC,SC,CC,wC,TC,EC,DC,OC,kC=v((()=>{Pi(),S(),Ie(),F(),Vh(),sS(),Fb(),_C(),vC=`effect/Metric`,yC=Symbol.for(vC),bC={_Type:e=>e,_In:e=>e,_Out:e=>e},xC=C(Symbol.for(`effect/Metric/globalMetricRegistry`),()=>gC()),SC=function(e,t,n,r){let i=Object.assign(e=>im(e,e=>OC(i,e)),{[yC]:bC,keyType:e,unsafeUpdate:t,unsafeValue:n,unsafeModify:r,register(){return this.unsafeValue([]),this},pipe(){return P(this,arguments)}});return i},CC=(e,t)=>wC(iS(e,t)),wC=e=>{let t,n=new WeakMap,r=r=>{if(r.length===0)return t===void 0&&(t=xC.get(e)),t;let i=n.get(r);return i===void 0?(i=xC.get(oS(e,r)),n.set(r,i),i):i};return SC(e.keyType,(e,t)=>r(t).update(e),e=>r(e).get(),(e,t)=>r(t).modify(e))},TC=(e,t,n)=>wC(aS(e,t,n)),EC=x(3,(e,t,n)=>DC(e,[Nb(t,n)])),DC=x(2,(e,t)=>SC(e.keyType,(n,r)=>e.unsafeUpdate(n,xi(t,r)),n=>e.unsafeValue(xi(t,n)),(n,r)=>e.unsafeModify(n,xi(t,r)))),OC=x(2,(e,t)=>km(Xm,n=>V(()=>e.unsafeUpdate(t,n))))})),AC,jC=v((()=>{S(),wb(),Vh(),On(),{...wn},AC=x(2,(e,t)=>km(Cb,n=>V(()=>{if(n.has(e)){let r=n.get(e);r.state.completed||(r.state.completed=!0,Nh(r.result,t))}})))})),MC,NC,PC,FC,IC,LC,RC,zC,BC,VC=v((()=>{S(),Ie(),T(),Vh(),MC=`effect/Supervisor`,NC=Symbol.for(MC),PC={_T:e=>e},FC=class e{underlying;value0;[NC]=PC;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(t){return new e(this,b(this.value,Zp(t)))}zip(e){return new IC(this,e)}},IC=class e{left;right;_tag=`Zip`;[NC]=PC;constructor(e,t){this.left=e,this.right=t}get value(){return fm(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 FC(this,b(this.value,Zp(e)))}zip(t){return new e(this,t)}},LC=e=>w(e,NC)&&Je(e,`Zip`),RC=class{effect;[NC]=PC;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 FC(this,b(this.value,Zp(e)))}zip(e){return new IC(this,e)}onRun(e,t){return e()}},zC=e=>new RC(e),BC=C(`effect/Supervisor/none`,()=>zC(cm))})),HC,UC=v((()=>{af(),HC=Qd})),WC,GC,KC,qC,JC,YC,XC,ZC,QC,$C,ew,tw,nw=v((()=>{Ba(),UC(),M(),S(),Cs(),VC(),WC=`Empty`,GC=`AddSupervisor`,KC=`RemoveSupervisor`,qC=`AndThen`,JC={_tag:WC},YC=(e,t)=>({_tag:qC,first:e,second:t}),XC=(e,t)=>ZC(t,xa(e)),ZC=(e,t)=>{let n=e,r=t;for(;Ia(r);){let e=Ra(r);switch(e._tag){case WC:r=za(r);break;case GC:n=n.zip(e.supervisor),r=za(r);break;case KC:n=QC(n,e.supervisor),r=za(r);break;case qC:r=Ma(e.first)(Ma(e.second)(za(r)))}}return n},QC=(e,t)=>A(e,t)?BC:LC(e)?QC(e.left,t).zip(QC(e.right,t)):e,$C=e=>A(e,BC)?ps():LC(e)?b($C(e.left),xs($C(e.right))):hs(e),ew=(e,t)=>{if(A(e,t))return JC;let n=$C(e),r=$C(t),i=b(r,bs(n),Ss(JC,(e,t)=>YC(e,{_tag:GC,supervisor:t}))),a=b(n,bs(r),Ss(JC,(e,t)=>YC(e,{_tag:KC,supervisor:t})));return YC(i,a)},tw=HC({empty:JC,patch:XC,combine:YC,diff:ew})})),rw,iw,aw,ow,sw,cw,lw,uw,dw,fw,pw,mw,hw,gw,_w,vw,yw,bw,xw,Sw,Cw,ww,Tw,Ew,Dw,Ow,kw,Aw,jw,Mw,Nw,Pw,Fw,Iw,Lw,Rw,zw,Bw,Vw,Hw,Uw,Ww,Gw,Kw,qw,Jw=v((()=>{Pi(),Ba(),il(),B_(),$_(),bu(),vv(),Av(),Xv(),S(),Ie(),Cs(),Xt(),cy(),hb(),Rr(),F(),T(),Pf(),Sb(),St(),np(),bc(),vg(),wb(),Eb(),Lb(),Vh(),N_(),p_(),Y_(),ux(),Jb(),mv(),tx(),xx(),kC(),Ox(),fn(),jC(),Af(),VC(),nw(),A_(),hn(),rw=CC(`effect_fiber_started`,{incremental:!0}),iw=CC(`effect_fiber_active`),aw=CC(`effect_fiber_successes`,{incremental:!0}),ow=CC(`effect_fiber_failures`,{incremental:!0}),sw=EC(TC(`effect_fiber_lifetimes`,Dx({start:.5,factor:2,count:35})),`time_unit`,`milliseconds`),cw=`Continue`,lw=`Done`,uw=`Yield`,dw={_E:e=>e,_A:e=>e},fw=e=>{throw Error(`BUG: FiberRuntime - ${Ut(e)} - please report an issue at https://github.com/Effect-TS/effect/issues`)},pw=Symbol.for(`effect/internal/fiberRuntime/YieldedOp`),mw=C(`effect/internal/fiberRuntime/yieldedOpChannel`,()=>({currentOp:null})),hw={[tn]:(e,t,n)=>xt(()=>t.effect_instruction_i1(n)),OnStep:(e,t,n)=>Dh(Dh(n)),[nn]:(e,t,n)=>xt(()=>t.effect_instruction_i2(n)),[dn]:(e,t,n)=>(e.patchRuntimeFlags(e.currentRuntimeFlags,t.patch),bf(e.currentRuntimeFlags)&&e.isInterrupted()?Ch(e.getInterruptedCause()):Dh(n)),[sn]:(e,t,n)=>(xt(()=>t.effect_instruction_i2(n)),xt(()=>t.effect_instruction_i0())?(e.pushStack(t),xt(()=>t.effect_instruction_i1())):cm),[cn]:(e,t,n)=>{for(;;){let r=xt(()=>t.effect_instruction_i0.next(n));if(r.done)return Dh(r.value);let i=ot(r.value);if(!gh(i))return e.pushStack(t),i;if(i._tag===`Failure`)return i;n=i.value}}},gw={[Bb]:(e,t,n,r)=>(e.processNewInterruptSignal(r.cause),bf(t)?Ch(r.cause):n),[Hb]:(e,t,n,r)=>{throw Error(`It is illegal to have multiple concurrent run loops in a single fiber`)},[Vb]:(e,t,n,r)=>(r.onFiber(e,qv(t)),n),[Ub]:(e,t,n,r)=>B(dm(),()=>n)},_w=e=>Yp(Lf(e),e=>Dw(tp(e),([e,t])=>{let n=new Map,r=[];for(let e of t){r.push(Ta(e));for(let t of e)n.set(t.request,t)}let i=r.flat();return Mm(qw(e.runAll(r),i,()=>i.forEach(e=>{e.listeners.interrupted=!0})),Cb,n)},!1,!1)),vw=mn(),yw=class extends z_{[rx]=ix;[sx]=dw;_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){if(super(),this.currentRuntimeFlags=n,this._fiberId=e,this._fiberRefs=t,Tf(n)){let e=this.getFiberRef(Xm);rw.unsafeUpdate(1,e),iw.unsafeUpdate(1,e)}this.refreshRefCache()}commit(){return cx(this)}id(){return this._fiberId}resume(e){this.tell(Kb(e))}get status(){return this.ask((e,t)=>t)}get runtimeFlags(){return this.ask((e,t)=>Yv(t)?e.currentRuntimeFlags:t.runtimeFlags)}scope(){return $b(this)}get children(){return this.ask(e=>Array.from(e.getChildren()))}getChildren(){return this._children===null&&(this._children=new Set),this._children}getInterruptedCause(){return this.getFiberRef(Qm)}fiberRefs(){return this.ask(e=>e.getFiberRefs())}ask(e){return rm(()=>{let t=jh(this._fiberId);return this.tell(Gb((n,r)=>{Nh(t,V(()=>e(n,r)))})),Mh(t)})}tell(e){this._queue.push(e),this._running||(this._running=!0,this.drainQueueLaterOnExecutor())}get await(){return kp(e=>{let t=t=>e(nm(t));if(this._exitValue!==null){t(this._exitValue);return}return this.tell(Gb((e,n)=>{e._exitValue===null?e.addObserver(t):t(this._exitValue)})),V(()=>this.tell(Gb((e,n)=>{e.removeObserver(t)})))},this.id())}get inheritAll(){return Sp((e,t)=>{let n=e.id(),r=e.getFiberRefs(),i=t.runtimeFlags,a=this.getFiberRefs(),o=av(r,n,a);e.setFiberRefs(o);let s=e.getFiberRef(Ww),c=b(Df(i,s),Nf(1),Nf(16));return lm(c)})}get poll(){return V(()=>wr(this._exitValue))}unsafePoll(){return this._exitValue}interruptAsFork(e){return V(()=>this.tell(Wb(Ls(e))))}unsafeInterruptAsFork(e){this.tell(Wb(Ls(e)))}addObserver(e){this._exitValue===null?this._observers.push(e):e(this._exitValue)}removeObserver(e){this._observers=this._observers.filter(t=>t!==e)}getFiberRefs(){return this.setFiberRef(Ww,this.currentRuntimeFlags),this._fiberRefs}unsafeDeleteFiberRef(e){this._fiberRefs=cv(this._fiberRefs,e)}getFiberRef(e){return this._fiberRefs.locals.has(e)?this._fiberRefs.locals.get(e)[0][1]:e.initial}setFiberRef(e,t){this._fiberRefs=dv(this._fiberRefs,{fiberId:this._fiberId,fiberRef:e,value:t}),this.refreshRefCache()}refreshRefCache(){this.currentDefaultServices=this.getFiberRef(M_),this.currentTracer=this.currentDefaultServices.unsafeMap.get(w_.key),this.currentSupervisor=this.getFiberRef(Gw),this.currentScheduler=this.getFiberRef(xb),this.currentContext=this.getFiberRef(zm),this.currentSpan=this.currentContext.unsafeMap.get(T_.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)n._exitValue===null&&e.add(this.currentRuntimeFlags,n)}drainQueueOnCurrentThread(){let e=!0;for(;e;){let t=cw,n=globalThis[lx];globalThis[lx]=this;try{for(;t===cw;)t=this._queue.length===0?lw:this.evaluateMessageWhileSuspended(this._queue.splice(0,1)[0])}finally{this._running=!1,globalThis[lx]=n}this._queue.length>0&&!this._running?(this._running=!0,t===uw?(this.drainQueueLaterOnExecutor(),e=!1):e=!0):e=!1}}drainQueueLaterOnExecutor(){this.currentScheduler.scheduleTask(this.run,this.getFiberRef(Bm),this)}drainQueueWhileRunning(e,t){let n=t;for(;this._queue.length>0;){let t=this._queue.splice(0,1)[0];n=gw[t._tag](this,e,n,t)}return n}isInterrupted(){return!Us(this.getFiberRef(Qm))}addInterruptedCause(e){let t=this.getFiberRef(Qm);this.setFiberRef(Qm,zs(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(Wb(Ls(this.id()))),e=!0;return e}interruptAllChildren(){if(this.sendInterruptSignalToAllChildren()){let e=this._children.values();this._children=null;let t=!1;return um({while:()=>!t,body:()=>{let n=e.next();return n.done?V(()=>{t=!0}):Tp(n.value.await)},step:()=>{}})}return null}reportExitValue(e){if(Tf(this.currentRuntimeFlags)){let t=this.getFiberRef(Xm),n=this.id().startTimeMillis,r=Date.now();switch(sw.unsafeUpdate(r-n,t),iw.unsafeUpdate(-1,t),e._tag){case rn:aw.unsafeUpdate(1,t);break;case $t:ow.unsafeUpdate(1,t)}}if(e._tag===`Failure`){let t=this.getFiberRef(Jm);!Gs(e.cause)&&t._tag===`Some`&&this.log(`Fiber terminated with an unhandled error`,e.cause,t)}}setExitValue(e){this._exitValue=e,this.reportExitValue(e);for(let t=this._observers.length-1;t>=0;t--)this._observers[t](e);this._observers=[]}getLoggers(){return this.getFiberRef(ww)}log(e,t,n){let r=yr(n)?n.value:this.getFiberRef(Um),i=this.getFiberRef(bw);if(oy(i,r))return;let a=this.getFiberRef(Wm),o=this.getFiberRef(Hm),s=this.getLoggers(),c=this.getFiberRefs();if(_s(s)>0){let n=Qc(this.getFiberRef(M_),dg),i=new Date(n.unsafeCurrentTimeMillis());Jt(c,()=>{for(let n of s)n.log({fiberId:this.id(),logLevel:r,message:e,cause:t,context:c,spans:a,annotations:o,date:i})})}}evaluateMessageWhileSuspended(e){switch(e._tag){case Ub:return uw;case Bb:return this.processNewInterruptSignal(e.cause),this._asyncInterruptor!==null&&(this._asyncInterruptor(Ch(e.cause)),this._asyncInterruptor=null),cw;case Hb:return this._asyncInterruptor=null,this._asyncBlockingOn=null,this.evaluateEffect(e.effect),cw;case Vb:return e.onFiber(this,this._exitValue===null?Jv(this.currentRuntimeFlags,this._asyncBlockingOn):Kv),cw;default:return fw(e)}}evaluateEffect(e){this.currentSupervisor.onResume(this);try{let t=bf(this.currentRuntimeFlags)&&this.isInterrupted()?Ch(this.getInterruptedCause()):e;for(;t!==null;){let e=t,n=this.runLoop(e);if(n===pw){let e=mw.currentOp;mw.currentOp=null,e._op===`Yield`?vf(this.currentRuntimeFlags)?(this.tell(qb()),this.tell(Kb(Oh)),t=null):t=Oh:e._op===`Async`&&(t=null)}else{this.currentRuntimeFlags=b(this.currentRuntimeFlags,yf(16));let e=this.interruptAllChildren();e===null?(this._queue.length===0?this.setExitValue(n):this.tell(Kb(n)),t=null):t=B(e,()=>n)}}}finally{this.currentSupervisor.onSuspend(this)}}start(e){if(this._running)this.tell(Kb(e));else{this._running=!0;let t=globalThis[lx];globalThis[lx]=this;try{this.evaluateEffect(e)}finally{this._running=!1,globalThis[lx]=t,this._queue.length>0&&this.drainQueueLaterOnExecutor()}}}startFork(e){this.tell(Kb(e))}patchRuntimeFlags(e,t){let n=Of(e,t);return globalThis[lx]=this,this.currentRuntimeFlags=n,n}initiateAsync(e,t){let n=!1,r=e=>{n||(n=!0,this.tell(Kb(e)))};bf(e)&&(this._asyncInterruptor=r);try{t(r)}catch(e){r(zp(Is(e)))}}pushStack(e){this._stack.push(e),e._op===`OnStep`&&this._steps.push({refs:this.getFiberRefs(),flags:this.currentRuntimeFlags})}popStack(){let e=this._stack.pop();if(e)return e._op===`OnStep`&&this._steps.pop(),e}getNextSuccessCont(){let e=this.popStack();for(;e;){if(e._op!==`OnFailure`)return e;e=this.popStack()}}getNextFailCont(){let e=this.popStack();for(;e;){if(e._op!==`OnSuccess`&&e._op!==`While`&&e._op!==`Iterator`)return e;e=this.popStack()}}Tag(e){return V(()=>$c(this.currentContext,e))}Left(e){return Lp(e.left)}None(e){return Lp(new ph)}Right(e){return Dh(e.right)}Some(e){return Dh(e.value)}Micro(e){return Dp(t=>{let n=t,r=db(nb(e,this.currentContext));return r.addObserver(e=>{if(e._tag===`Success`)return n(Dh(e.value));switch(e.cause._tag){case`Interrupt`:return n(Ch(Ls(mu)));case`Fail`:return n(Lp(e.cause.error));case`Die`:return n(Np(e.cause.defect))}}),Dp(e=>{n=t=>{e(cm)},r.unsafeInterrupt()})})}[an](e){let t=xt(()=>e.effect_instruction_i0()),n=this.getNextSuccessCont();return n===void 0?(mw.currentOp=Dh(t),pw):(n._op in hw||fw(n),hw[n._op](this,n,t))}[rn](e){let t=e,n=this.getNextSuccessCont();return n===void 0?(mw.currentOp=t,pw):(n._op in hw||fw(n),hw[n._op](this,n,t.effect_instruction_i0))}[$t](e){let t=e.effect_instruction_i0,n=this.getNextFailCont();if(n!==void 0)switch(n._op){case en:case nn:return bf(this.currentRuntimeFlags)&&this.isInterrupted()?Ch(Qs(t)):xt(()=>n.effect_instruction_i1(t));case`OnStep`:return bf(this.currentRuntimeFlags)&&this.isInterrupted()?Ch(Qs(t)):Dh(Ch(t));case dn:return this.patchRuntimeFlags(this.currentRuntimeFlags,n.patch),bf(this.currentRuntimeFlags)&&this.isInterrupted()?Ch(zs(t,this.getInterruptedCause())):Ch(t);default:fw(n)}else return mw.currentOp=Ch(t),pw}[ln](e){return xt(()=>e.effect_instruction_i0(this,qv(this.currentRuntimeFlags)))}Blocked(e){let t=this.getFiberRefs(),n=this.currentRuntimeFlags;if(this._steps.length>0){let r=[],i=this._steps[this._steps.length-1],a=this.popStack();for(;a&&a._op!==`OnStep`;)r.push(a),a=this.popStack();this.setFiberRefs(i.refs),this.currentRuntimeFlags=i.flags;let o=Ov(i.refs,t),s=Df(i.flags,n);return Dh(mp(e.effect_instruction_i0,Sp(t=>{for(;r.length>0;)t.pushStack(r.pop());return t.setFiberRefs(kv(t.id(),t.getFiberRefs())(o)),t.currentRuntimeFlags=Of(s)(t.currentRuntimeFlags),e.effect_instruction_i1})))}return sm(t=>B(kw(hp(e.effect_instruction_i0)),()=>t(e.effect_instruction_i1)))}RunBlocked(e){return _w(e.effect_instruction_i0)}[on](e){let t=e.effect_instruction_i0,n=this.currentRuntimeFlags,r=Of(n,t);if(bf(r)&&this.isInterrupted())return Ch(this.getInterruptedCause());if(this.patchRuntimeFlags(this.currentRuntimeFlags,t),e.effect_instruction_i1){let t=Df(r,n);return this.pushStack(new _p(t,e)),xt(()=>e.effect_instruction_i1(n))}return Oh}[tn](e){return this.pushStack(e),e.effect_instruction_i0}OnStep(e){return this.pushStack(e),e.effect_instruction_i0}[en](e){return this.pushStack(e),e.effect_instruction_i0}[nn](e){return this.pushStack(e),e.effect_instruction_i0}[Zt](e){return this._asyncBlockingOn=e.effect_instruction_i1,this.initiateAsync(this.currentRuntimeFlags,e.effect_instruction_i0),mw.currentOp=e,pw}[un](e){return this._isYielding=!1,mw.currentOp=e,pw}[sn](e){let t=e.effect_instruction_i0,n=e.effect_instruction_i1;return t()?(this.pushStack(e),n()):Oh}[cn](e){return hw[cn](this,e,void 0)}[Qt](e){return xt(()=>e.commit())}runLoop(e){let t=e;for(this.currentOpCount=0;;){if(this.currentRuntimeFlags&2&&this.currentSupervisor.onEffect(this,t),this._queue.length>0&&(t=this.drainQueueWhileRunning(this.currentRuntimeFlags,t)),!this._isYielding){this.currentOpCount+=1;let e=this.currentScheduler.shouldYield(this);if(e!==!1){this._isYielding=!0,this.currentOpCount=0;let n=t;t=B(dm({priority:e}),()=>n)}}try{if(t=this.currentTracer.context(()=>{if(vw!==t[gp]._V){let e=this.getFiberRef(Ym);if(e._tag===`Some`){let n=t[gp]._V;this.log(`Executing an Effect versioned ${n} with a Runtime of version ${mn()}, 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`,Ps,e)}}return this[t._op](t)},this),t===pw){let e=mw.currentOp;return e._op===`Yield`||e._op===`Async`?pw:(mw.currentOp=null,e._op===`Success`||e._op===`Failure`?e:Ch(Is(e)))}}catch(e){t=t!==pw&&!w(t,`_op`)||!(t._op in this)?Pp(`Not a valid effect: ${Ut(t)}`):lh(e)?Ch(zs(Is(e),Ls(mu))):Np(e)}}}run=()=>{this.drainQueueOnCurrentThread()}},bw=C(`effect/FiberRef/currentMinimumLogLevel`,()=>Nm(sy(`Info`))),xw=e=>mx(t=>{let n=hv(t.context,M_);Qc(n,d_).unsafe.log(e.log(t))}),Sw=C(Symbol.for(`effect/Logger/defaultLogger`),()=>xw(vx)),Cw=C(Symbol.for(`effect/Logger/tracerLogger`),()=>mx(({annotations:e,cause:t,context:n,fiberId:r,logLevel:i,message:a})=>{let o=Ib(el(uv(n,zm),T_));if(o._tag===`None`||o.value._tag===`ExternalSpan`)return;let s=$c(uv(n,M_),dg),c={};for(let[t,n]of e)c[t]=n;c[`effect.fiberId`]=vu(r),c[`effect.logLevel`]=i.label,t!==null&&t._tag!==`Empty`&&(c[`effect.cause`]=dc(t,{renderErrorCause:!0})),o.value.event(Ut(Array.isArray(a)&&a.length===1?a[0]:a),s.unsafeCurrentTimeNanos(),c)})),ww=C(Symbol.for(`effect/FiberRef/currentLoggers`),()=>Pm(hs(Sw,Cw))),Tw=x(e=>$e(e[0]),(e,t,n)=>Sp(r=>{let i=n?.batching===!0||n?.batching===`inherit`&&r.getFiberRef(qm);return n?.discard?Tb(n.concurrency,()=>Iw(X_,n?.concurrentFinalizers)(n=>i?Dw(e,(e,r)=>n(t(e,r)),!0,!1,1):Yp(e,(e,r)=>n(t(e,r)))),()=>Iw(Z_,n?.concurrentFinalizers)(n=>Dw(e,(e,r)=>n(t(e,r)),i,!1)),r=>Iw(Q_(r),n?.concurrentFinalizers)(n=>Dw(e,(e,r)=>n(t(e,r)),i,!1,r))):Tb(n?.concurrency,()=>Iw(X_,n?.concurrentFinalizers)(n=>i?Ow(e,1,(e,r)=>n(t(e,r)),!0):Jp(e,(e,r)=>n(t(e,r)))),()=>Iw(Z_,n?.concurrentFinalizers)(n=>Ew(e,(e,r)=>n(t(e,r)),i)),r=>Iw(Q_(r),n?.concurrentFinalizers)(n=>Ow(e,r,(e,r)=>n(t(e,r)),i)))})),Ew=(e,t,n)=>rm(()=>{let r=Ur(e),i=Array(r.length);return mm(Dw(r,(e,n)=>B(t(e,n),e=>V(()=>i[n]=e)),n,!1),nm(i))}),Dw=(e,t,n,r,i)=>sm(a=>am(o=>Sp(s=>{let c=Array.from(e).reverse(),l=c.length;if(l===0)return cm;let u=0,d=!1,f=i?Math.min(c.length,i):c.length,p=new Set,m=[],h=()=>p.forEach(e=>{e.currentScheduler.scheduleTask(()=>{e.unsafeInterruptAsFork(s.id())},0,e)}),g=[],_=[],ee=[],te=()=>{let e=m.filter(({exit:e})=>e._tag===`Failure`).sort((e,t)=>e.index<t.index?-1:e.index===t.index?0:1).map(({exit:e})=>e);return e.length===0&&e.push(Oh),e},ne=(e,t=!1)=>{let n=om(o(e)),r=jw(n,s,s.currentRuntimeFlags,ex);return s.currentScheduler.scheduleTask(()=>{t&&r.unsafeInterruptAsFork(s.id()),r.resume(n)},0,r),r},re=()=>{r||(l-=c.length,c=[]),d=!0,h()},ie=n?Up:Ip,ae=ne(kp(e=>{let r=(e,t)=>{e._op===`Blocked`?ee.push(e):(m.push({index:t,exit:e}),e._op===`Failure`&&!d&&re())},o=()=>{if(c.length>0){let f=c.pop(),h=u++,re=()=>{let e=c.pop();return h=u++,B(dm(),()=>B(ie(a(t(e,h))),ae))},ae=e=>c.length>0&&(r(e,h),c.length>0)?re():nm(e),oe=B(ie(a(t(f,h))),ae),se=ne(oe);g.push(se),p.add(se),d&&se.currentScheduler.scheduleTask(()=>{se.unsafeInterruptAsFork(s.id())},0,se),se.addObserver(t=>{let a;if(a=t._op===`Failure`?t:t.effect_instruction_i0,_.push(se),p.delete(se),r(a,h),m.length===l)e(nm(xr(bh(te(),{parallel:!0}),()=>Oh)));else if(ee.length+m.length===l){let t=te(),r=ee.map(e=>e.effect_instruction_i0).reduce(Ff);e(nm(mp(r,Dw([xr(bh(t,{parallel:!0}),()=>Oh),...ee.map(e=>e.effect_instruction_i1)],e=>e,n,!0,i))))}else o()})}};for(let e=0;e<f;e++)o()}));return Tp(em(Wp(a(cx(ae))),Eh({onFailure:e=>{re();let t=ee.length+1,n=Math.min(typeof i==`number`?i:ee.length,ee.length),r=Array.from(ee);return kp(i=>{let a=[],o=0,s=0,c=(n,s)=>c=>{a[n]=c,o++,o===t&&i(Dh(Ch(e))),r.length>0&&s&&l()},l=()=>{ne(r.pop(),!0).addObserver(c(s,!0)),s++};ae.addObserver(c(s,!1)),s++;for(let e=0;e<n;e++)l()})},onSuccess:()=>Jp(_,e=>e.inheritAll)})))}))),Ow=(e,t,n,r)=>rm(()=>{let i=Ur(e),a=Array(i.length);return mm(Dw(i,(e,t)=>Zp(n(e,t),e=>a[t]=e),r,!1,t),nm(a))}),kw=e=>Nw(e,ex),Aw=(e,t,n,r=null)=>{let i=Mw(e,t,n,r);return i.resume(e),i},jw=(e,t,n,r=null)=>Mw(e,t,n,r),Mw=(e,t,n,r=null)=>{let i=yu(),a=t.getFiberRefs(),o=ov(a,i),s=new yw(i,o,n),c=uv(o,zm),l=s.currentSupervisor;return l.onStart(c,e,z(t),s),s.addObserver(e=>l.onEnd(e,s)),(r===null?b(t.getFiberRef(Zm),xr(()=>t.scope())):r).add(n,s),s},Nw=(e,t)=>Sp((n,r)=>nm(Aw(e,n,r.runtimeFlags,t))),Pw=e=>Lh(t=>br(el(t,Rw),{onNone:()=>e,onSome:t=>{switch(t.strategy._tag){case`Parallel`:return e;case`Sequential`:case`ParallelN`:return B(rh(t,Z_),t=>Hw(e,t))}}})),Fw=e=>t=>Lh(n=>br(el(n,Rw),{onNone:()=>t,onSome:n=>n.strategy._tag===`ParallelN`&&n.strategy.parallelism===e?t:B(rh(n,Q_(e)),e=>Hw(t,e))})),Iw=(e,t)=>n=>Lh(r=>br(el(r,Rw),{onNone:()=>n(be),onSome:r=>{if(t===!0){let t=e._tag===`Parallel`?Pw:e._tag===`Sequential`?Lw:Fw(e.parallelism);switch(r.strategy._tag){case`Parallel`:return t(n(Pw));case`Sequential`:return t(n(Lw));case`ParallelN`:return t(n(Fw(r.strategy.parallelism)))}}else return n(be)}})),Lw=e=>Lh(t=>br(el(t,Rw),{onNone:()=>e,onSome:t=>{switch(t.strategy._tag){case`Sequential`:return e;case`Parallel`:case`ParallelN`:return B(rh(t,X_),t=>Hw(e,t))}}})),Rw=Jc(`effect/Scope`),zw=(e,t)=>{e.state._tag===`Open`&&e.state.finalizers.set({},t)},Bw={[$m]:$m,[eh]:eh,pipe(){return P(this,arguments)},fork(e){return V(()=>{let t=Vw(e);if(this.state._tag===`Closed`)return t.state=this.state,t;let n={};return this.state.finalizers.set(n,e=>t.close(e)),zw(t,e=>V(()=>{this.state._tag===`Open`&&this.state.finalizers.delete(n)})),t})},close(e){return rm(()=>{if(this.state._tag===`Closed`)return cm;let t=Array.from(this.state.finalizers.values()).reverse();return this.state={_tag:`Closed`,exit:e},t.length===0?cm:q_(this.strategy)?b(Jp(t,t=>Ip(t(e))),B(e=>b(bh(e),Or(yh),xr(()=>Oh)))):J_(this.strategy)?b(Ew(t,t=>Ip(t(e)),!1),B(e=>b(bh(e,{parallel:!0}),Or(yh),xr(()=>Oh)))):b(Ow(t,this.strategy.parallelism,t=>Ip(t(e)),!1),B(e=>b(bh(e,{parallel:!0}),Or(yh),xr(()=>Oh))))})},addFinalizer(e){return rm(()=>this.state._tag===`Closed`?e(this.state.exit):(this.state.finalizers.set({},e),cm))}},Vw=(e=W_)=>{let t=Object.create(Bw);return t.strategy=e,t.state={_tag:`Open`,finalizers:new Map},t},Hw=x(2,(e,t)=>zh(e,tl(Xc(Rw,t)))),Uw=e=>Lm(e,{differ:tw,fork:JC}),Ww=Rm(wf),Gw=Uw(BC),Kw=x(2,(e,t)=>sm(n=>Kp(n(e),{onFailure:e=>Kp(t,{onFailure:t=>zp(zs(e,t)),onSuccess:()=>zp(e)}),onSuccess:e=>wp(t,e)}))),qw=(e,t,n)=>Hp(r=>Kw(B(kw(Xp(e)),e=>kp(r=>{let i=t.map(e=>e.listeners.count),a=()=>{i.every(e=>e===0)&&t.every(e=>e.result.state.current._tag===`Pending`||!!(e.result.state.current._tag===`Done`&&gh(e.result.state.current.effect)&&e.result.state.current.effect._tag===`Failure`&&Ws(e.result.state.current.effect.cause)))&&(o.forEach(e=>e()),n?.(),r(hm(e)))};e.addObserver(e=>{o.forEach(e=>e()),r(e)});let o=t.map((e,t)=>{let n=e=>{i[t]=e,a()};return e.listeners.addObserver(n),()=>e.listeners.removeObserver(n)});return a(),V(()=>{o.forEach(e=>e())})})),rm(()=>{let e=t.flatMap(e=>e.state.completed?[]:[e]);return Yp(e,e=>AC(e.request,wh(r)))})))})),Yw,Xw,Zw=v((()=>{Vh(),Yw=nh,Xw=rh})),Qw,$w,eT,tT,nT,rT,iT,aT,oT,sT,cT,lT,uT,dT,fT,pT,mT,hT=v((()=>{il(),M(),bu(),vv(),Xt(),Rr(),F(),Sb(),Zw(),bc(),Vh(),Y_(),Jw(),tx(),Af(),VC(),Qw=e=>function(){if(arguments.length===1){let t=arguments[0];return(n,...r)=>e(t,n,...r)}return e.apply(this,arguments)},$w=Qw((e,t,n)=>{let r=yu(),i=[[zm,[[r,e.context]]]];n?.scheduler&&i.push([xb,[[r,n.scheduler]]]);let a=gv(e.fiberRefs,{entries:i,forkAs:r});n?.updateRefs&&(a=n.updateRefs(a,r));let o=new yw(r,a,e.runtimeFlags),s=t;n?.scope&&(s=B(Xw(n.scope,W_),e=>mm(th(e,Hp(e=>A(e,o.id())?cm:gm(o,e))),em(t,t=>Yw(e,t)))));let c=o.currentSupervisor;return c!==BC&&(c.onStart(e.context,s,R(),o),o.addObserver(e=>c.onEnd(e,o))),ex.add(e.runtimeFlags,o),n?.immediate===!1?o.resume(s):o.start(s),o}),eT=Qw((e,t)=>{let n=cT(e)(t);if(n._tag===`Failure`)throw oT(n.effect_instruction_i0);return n.effect_instruction_i0}),tT=class 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}},nT=e=>{let t=Error.stackTraceLimit;Error.stackTraceLimit=0;let n=new tT(e);return Error.stackTraceLimit=t,n},rT=Symbol.for(`effect/Runtime/FiberFailure`),iT=Symbol.for(`effect/Runtime/FiberFailure/Cause`),aT=class extends Error{[rT];[iT];constructor(e){let t=yc(e)[0];super(t?.message||`An error has occurred`),this[rT]=rT,this[iT]=e,this.name=t?`(FiberFailure) ${t.name}`:`FiberFailure`,t?.stack&&(this.stack=t.stack)}toJSON(){return{_id:`FiberFailure`,cause:this[iT].toJSON()}}toString(){return`(FiberFailure) `+dc(this[iT],{renderErrorCause:!0})}[N](){return this.toString()}},oT=e=>{let t=Error.stackTraceLimit;Error.stackTraceLimit=0;let n=new aT(e);return Error.stackTraceLimit=t,n},sT=e=>{let t=e;switch(t._op){case`Failure`:case`Success`:return t;case`Left`:return Sh(t.left);case`Right`:return Dh(t.right);case`Some`:return Dh(t.value);case`None`:return Sh(new ph)}},cT=Qw((e,t)=>{let n=sT(t);if(n)return n;let r=new bb,i=$w(e)(t,{scheduler:r});return r.flush(),i.unsafePoll()||xh(Mp(nT(i),Bh(i)))}),lT=class{context;runtimeFlags;fiberRefs;constructor(e,t,n){this.context=e,this.runtimeFlags=t,this.fiberRefs=n}pipe(){return P(this,arguments)}},uT=e=>new lT(e.context,e.runtimeFlags,e.fiberRefs),dT=Cf(1,32,4),fT=uT({context:Yc(),runtimeFlags:dT,fiberRefs:_v()}),pT=$w(fT),mT=eT(fT)})),gT,_T,vT,yT,bT,xT,ST,CT,wT,TT,ET,DT,OT,kT,AT,jT,MT,NT,PT,FT,IT,LT,RT,zT,BT,VT,HT,UT,WT,GT,KT,qT,JT,YT,XT,ZT,QT,$T,eE,tE,nE,rE,iE,aE,oE,sE,cE,lE,uE,dE,fE=v((()=>{Gh(),M(),Ne(),S(),Ie(),Mt(),Xt(),Rr(),F(),T(),gT=Symbol.for(`effect/DateTime`),_T=Symbol.for(`effect/DateTime/TimeZone`),vT={[gT]:gT,pipe(){return P(this,arguments)},[N](){return this.toString()},toJSON(){return ZT(this).toJSON()}},yT={...vT,_tag:`Utc`,[E](){return k(this,Dt(this.epochMillis))},[j](e){return TT(e)&&e._tag===`Utc`&&this.epochMillis===e.epochMillis},toString(){return`DateTime.Utc(${ZT(this).toJSON()})`}},bT={...vT,_tag:`Zoned`,[E](){return b(Dt(this.epochMillis),O(D(this.zone)),k(this))},[j](e){return TT(e)&&e._tag===`Zoned`&&this.epochMillis===e.epochMillis&&A(this.zone,e.zone)},toString(){return`DateTime.Zoned(${dE(this)})`}},xT={[_T]:_T,[N](){return this.toString()}},ST={...xT,_tag:`Named`,[E](){return k(this,Ot(`Named:${this.id}`))},[j](e){return ET(e)&&e._tag===`Named`&&this.id===e.id},toString(){return`TimeZone.Named(${this.id})`},toJSON(){return{_id:`TimeZone`,_tag:`Named`,id:this.id}}},CT={...xT,_tag:`Offset`,[E](){return k(this,Ot(`Offset:${this.offset}`))},[j](e){return ET(e)&&e._tag===`Offset`&&this.offset===e.offset},toString(){return`TimeZone.Offset(${eE(this.offset)})`},toJSON(){return{_id:`TimeZone`,_tag:`Offset`,offset:this.offset}}},wT=(e,t,n)=>{let r=Object.create(bT);return r.epochMillis=e,r.zone=t,Object.defineProperty(r,"partsUtc",{value:n,enumerable:!1,writable:!0}),Object.defineProperty(r,"adjustedEpochMillis",{value:void 0,enumerable:!1,writable:!0}),Object.defineProperty(r,"partsAdjusted",{value:void 0,enumerable:!1,writable:!0}),r},TT=e=>w(e,gT),ET=e=>w(e,_T),DT=e=>ET(e)&&e._tag===`Offset`,OT=e=>ET(e)&&e._tag===`Named`,kT=e=>e._tag===`Utc`,AT=e=>e._tag===`Zoned`,jT=Ee((e,t)=>e.epochMillis===t.epochMillis),MT=e=>{let t=Object.create(yT);return t.epochMillis=e,Object.defineProperty(t,"partsUtc",{value:void 0,enumerable:!1,writable:!0}),t},NT=e=>{let t=e.getTime();if(Number.isNaN(t))throw new Uh(`Invalid date`);return MT(t)},PT=e=>{if(TT(e))return e;if(e instanceof Date)return NT(e);if(typeof e==`object`){let t=new Date(0);return rE(t,e),NT(t)}return typeof e==`string`&&!FT(e)?NT(new Date(e+`Z`)):NT(new Date(e))},FT=e=>/Z|[+-]\d{2}$|[+-]\d{2}:?\d{2}$|\]$/.test(e),IT=-864e13+432e5,LT=864e13-504e5,RT=(e,t)=>{if(t?.timeZone===void 0&&TT(e)&&AT(e))return e;let n=PT(e);if(n.epochMillis<IT||n.epochMillis>LT)throw RangeError(`Epoch millis out of range: ${n.epochMillis}`);let r;if(t?.timeZone===void 0){let e=new Date(n.epochMillis).getTimezoneOffset()*-60*1e3;r=KT(e)}else if(ET(t?.timeZone))r=t.timeZone;else if(typeof t?.timeZone==`number`)r=KT(t.timeZone);else{let e=YT(t.timeZone);if(vr(e))throw new Uh(`Invalid time zone: ${t.timeZone}`);r=e.value}return t?.adjustForTimeZone===!0?aE(n.epochMillis,r,t?.disambiguation??`compatible`):wT(n.epochMillis,r,n.partsUtc)},zT=Er(RT),BT=/^(.{17,35})\[(.+)\]$/,VT=e=>{let t=BT.exec(e);if(t===null){let t=sE(e);return t===null?R():zT(e,{timeZone:t})}let[,n,r]=t;return zT(n,{timeZone:r})},HT=C(`effect/DateTime/validZoneCache`,()=>new Map),UT={day:`numeric`,month:`numeric`,year:`numeric`,hour:`numeric`,minute:`numeric`,second:`numeric`,timeZoneName:`longOffset`,fractionalSecondDigits:3,hourCycle:`h23`},WT=e=>{let t=e.resolvedOptions().timeZone;if(HT.has(t))return HT.get(t);let n=Object.create(ST);return n.id=t,n.format=e,HT.set(t,n),n},GT=e=>{if(HT.has(e))return HT.get(e);try{return WT(new Intl.DateTimeFormat(`en-US`,{...UT,timeZone:e}))}catch{throw new Uh(`Invalid time zone: ${e}`)}},KT=e=>{let t=Object.create(CT);return t.offset=e,t},qT=Er(GT),JT=/^(?:GMT|[+-])/,YT=e=>{if(JT.test(e)){let t=sE(e);return t===null?R():z(KT(t))}return qT(e)},XT=e=>e._tag===`Offset`?eE(e.offset):e.id,ZT=e=>new Date(e.epochMillis),QT=e=>{if(e._tag===`Utc`)return new Date(e.epochMillis);if(e.zone._tag===`Offset`)return new Date(e.epochMillis+e.zone.offset);if(e.adjustedEpochMillis!==void 0)return new Date(e.adjustedEpochMillis);let t=e.zone.format.formatToParts(e.epochMillis).filter(e=>e.type!==`literal`),n=new Date(0);return n.setUTCFullYear(Number(t[2].value),Number(t[0].value)-1,Number(t[1].value)),n.setUTCHours(Number(t[3].value),Number(t[4].value),Number(t[5].value),Number(t[6].value)),e.adjustedEpochMillis=n.getTime(),n},$T=e=>QT(e).getTime()-nE(e),eE=e=>{let t=Math.abs(e),n=Math.floor(t/36e5),r=Math.round(t%36e5/6e4);return r===60&&(n+=1,r=0),`${e<0?`-`:`+`}${String(n).padStart(2,`0`)}:${String(r).padStart(2,`0`)}`},tE=e=>eE($T(e)),nE=e=>e.epochMillis,rE=(e,t)=>{if(t.year!==void 0&&e.setUTCFullYear(t.year),t.month!==void 0&&e.setUTCMonth(t.month-1),t.day!==void 0&&e.setUTCDate(t.day),t.weekDay!==void 0){let n=t.weekDay-e.getUTCDay();e.setUTCDate(e.getUTCDate()+n)}t.hours!==void 0&&e.setUTCHours(t.hours),t.minutes!==void 0&&e.setUTCMinutes(t.minutes),t.seconds!==void 0&&e.setUTCSeconds(t.seconds),t.millis!==void 0&&e.setUTCMilliseconds(t.millis)},iE=864e5,aE=(e,t,n)=>{if(t._tag===`Offset`)return wT(e-t.offset,t);let r=cE(e-iE,e,t),i=cE(e+iE,e,t);if(r===i)return wT(e-r,t);let a=r<i,o=r-i;if(a){if(cE(e-i,e,t)===i)return wT(e-i,t);let a=wT(e-r,t);if(e!==QT(a).getTime())switch(n){case`reject`:{let n=new Date(e).toISOString();throw RangeError(`Gap time: ${n} does not exist in time zone ${t.id}`)}case`earlier`:return wT(e-i,t);case`compatible`:case`later`:return a}return a}if(cE(e-r,e,t)===r){if(n===`earlier`||n===`compatible`||cE(e-r+o,e+o,t)===r)return wT(e-r,t);if(n===`reject`){let n=new Date(e).toISOString();throw RangeError(`Ambiguous time: ${n} occurs twice in time zone ${t.id}`)}}return wT(e-i,t)},oE=/([+-])(\d{2}):(\d{2})$/,sE=e=>{let t=oE.exec(e);if(t===null)return null;let[,n,r,i]=t;return(n===`+`?1:-1)*(Number(r)*60+Number(i))*60*1e3},cE=(e,t,n)=>{let r=n.format.formatToParts(e).find(e=>e.type===`timeZoneName`)?.value??``;if(r===`GMT`)return 0;let i=sE(r);return i===null?$T(wT(t,n)):i},lE=e=>ZT(e).toISOString(),uE=e=>{let t=QT(e);return e._tag===`Utc`?t.toISOString():`${t.toISOString().slice(0,-1)}${tE(e)}`},dE=e=>e.zone._tag===`Offset`?uE(e):`${uE(e)}[${e.zone.id}]`})),pE,mE,hE,gE,_E,vE=v((()=>{pE=e=>e.toUpperCase(),mE=e=>e.toLowerCase(),hE=e=>e.length===0?e:pE(e[0])+e.slice(1),gE=e=>e.length===0?e:mE(e[0])+e.slice(1),_E=e=>e.length>0})),yE,bE,xE,SE,CE,wE,TE,EE,DE,OE,kE,AE,jE=v((()=>{Vh(),Jw(),hT(),yE=xp,bE=Tw,xE=rm,SE=cm,CE=Ap,wE=Zp,TE=Qp,EE=$p,DE=Fp,OE=B,kE=pT,AE=mT})),ME,NE,PE,FE,IE,LE,RE,zE,BE,VE,HE,UE,WE,GE,KE,qE,JE,YE,XE=v((()=>{il(),fE(),ME=TT,NE=DT,PE=OT,FE=kT,IE=AT,LE=jT,RE=NT,zE=PT,BE=RT,VE=VT,HE=GT,UE=KT,WE=YT,GE=XT,KE=ZT,qE=nE,nl(`effect/DateTime/CurrentTimeZone`)(),JE=lE,YE=dE})),ZE,QE,$E,eD,tD,nD,rD=v((()=>{Xt(),ZE=(e,t)=>{switch(t._tag){case`StringKeyword`:case`TemplateLiteral`:return Object.keys(e);case`SymbolKeyword`:return Object.getOwnPropertySymbols(e);case`Refinement`:return ZE(e,t.from)}},QE=e=>{let t=!1,n;return()=>t?n:(n=e(),t=!0,n)},$E=e=>Array.isArray(e),eD=e=>!Array.isArray(e),tD=e=>`[${Rt(e)}]`,nD=e=>$E(e)?e.map(tD).join(``):tD(e)})),iD,aD,oD,sD,cD,lD,uD,dD,fD=v((()=>{Pi(),Xt(),rD(),iD=(e,t,n,r)=>{let i=e;return n&&$r(n)&&(i+=`\nat path: ${nD(n)}`),t!==void 0&&(i+=`\ndetails: ${t}`),r&&(i+=`\nschema (${r._tag}): ${r}`),i},aD=e=>iD(`Unsupported key schema`,void 0,void 0,e),oD=e=>iD(`Unsupported literal`,`literal value: ${zt(e)}`),sD=e=>iD(`Duplicate index signature`,`${e} index signature`),cD=iD(`Unsupported index signature parameter`,"An index signature parameter type must be `string`, `symbol`, a template literal type or a refinement of the previous types"),lD=iD(`Invalid element`,`A required element cannot follow an optional element. ts(1257)`),uD=e=>iD(`Duplicate property signature transformation`,`Duplicate key ${zt(e)}`),dD=e=>iD(`Duplicate property signature`,`Duplicate key ${zt(e)}`)})),pD,mD,hD,gD,_D,vD,yD,bD,xD,SD,CD,wD,TD,ED,DD,OD=v((()=>{pD=Symbol.for(`effect/SchemaId/DateFromSelf`),mD=Symbol.for(`effect/SchemaId/GreaterThan`),hD=Symbol.for(`effect/SchemaId/GreaterThanOrEqualTo`),gD=Symbol.for(`effect/SchemaId/LessThan`),_D=Symbol.for(`effect/SchemaId/LessThanOrEqualTo`),vD=Symbol.for(`effect/SchemaId/Int`),yD=Symbol.for(`effect/SchemaId/NonNaN`),bD=Symbol.for(`effect/SchemaId/Finite`),xD=Symbol.for(`effect/SchemaId/JsonNumber`),SD=Symbol.for(`effect/SchemaId/Between`),CD=Symbol.for(`effect/SchemaId/GreaterThanOrEqualToBigint`),wD=Symbol.for(`effect/SchemaId/BetweenBigint`),TD=Symbol.for(`effect/SchemaId/MinLength`),ED=Symbol.for(`effect/SchemaId/MaxLength`),DD=Symbol.for(`effect/SchemaId/Length`)}));function kD(e,t){let n=!1,r=Vr(e.length);for(let i=0;i<e.length;i++){let a=e[i],o=t(a);o!==a&&(n=!0),r[i]=o}return n?r:e}function AD(e){return br(tO(e),{onNone:()=>``,onSome:e=>e.map(e=>` & Brand<${zt(e)}>`).join(``)})}var jD,MD,ND,PD,FD,ID,LD,RD,zD,BD,VD,HD,UD,WD,GD,KD,qD,JD,YD,XD,ZD,QD,$D,eO,tO,nO,rO,iO,aO,oO,sO,cO,lO,uO,dO,fO,pO,mO,hO,gO,_O,vO,yO,bO,xO,SO,CO,wO,TO,EO,DO,OO,kO,AO,jO,MO,NO,PO,FO,IO,LO,RO,zO,BO,VO,HO,UO,WO,GO,KO,qO,JO,YO,XO,ZO,QO,$O,ek,tk,nk,rk,ik,ak,ok,sk,ck,lk,uk,dk,fk,pk,mk,hk,gk,_k,vk,yk,bk,xk,Sk,Ck,wk,Tk,Ek,Dk,Ok,kk,Ak,jk,Mk,Nk,Pk,Fk,Ik,Lk,Rk=v((()=>{Pi(),S(),Ie(),Xt(),fD(),rD(),xg(),Rr(),gr(),T(),Cg(),jD=Symbol.for(`effect/annotation/TypeConstructor`),MD=Symbol.for(`effect/annotation/Brand`),ND=Symbol.for(`effect/annotation/SchemaId`),PD=Symbol.for(`effect/annotation/Message`),FD=Symbol.for(`effect/annotation/MissingMessage`),ID=Symbol.for(`effect/annotation/Identifier`),LD=Symbol.for(`effect/annotation/Title`),RD=Symbol.for(`effect/annotation/AutoTitle`),zD=Symbol.for(`effect/annotation/Description`),BD=Symbol.for(`effect/annotation/Examples`),VD=Symbol.for(`effect/annotation/Default`),HD=Symbol.for(`effect/annotation/JSONSchema`),UD=Symbol.for(`effect/annotation/Arbitrary`),WD=Symbol.for(`effect/annotation/Pretty`),GD=Symbol.for(`effect/annotation/Equivalence`),KD=Symbol.for(`effect/annotation/Documentation`),qD=Symbol.for(`effect/annotation/Concurrency`),JD=Symbol.for(`effect/annotation/Batching`),YD=Symbol.for(`effect/annotation/ParseIssueTitle`),XD=Symbol.for(`effect/annotation/ParseOptions`),ZD=Symbol.for(`effect/annotation/DecodingFallback`),QD=Symbol.for(`effect/annotation/Surrogate`),$D=Symbol.for(`effect/annotation/StableFilter`),eO=x(2,(e,t)=>Object.prototype.hasOwnProperty.call(e.annotations,t)?z(e.annotations[t]):R()),tO=eO(MD),nO=eO(PD),rO=eO(FD),iO=eO(LD),aO=eO(RD),oO=eO(ID),sO=eO(zD),cO=eO(qD),lO=eO(JD),uO=eO(YD),dO=eO(XD),fO=eO(ZD),pO=eO(QD),mO=eO($D),hO=e=>Lr(mO(e),e=>e===!0),gO=Symbol.for(`effect/annotation/JSONIdentifier`),_O=eO(gO),vO=e=>Sr(_O(e),()=>oO(e)),yO=class{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 xr(Lk(this),()=>`<declaration schema>`)}toJSON(){return{_tag:this._tag,typeParameters:this.typeParameters.map(e=>e.toJSON()),annotations:Nk(this.annotations)}}},bO=e=>t=>t._tag===e,xO=class{literal;annotations;_tag=`Literal`;constructor(e,t={}){this.literal=e,this.annotations=t}toString(){return xr(Lk(this),()=>zt(this.literal))}toJSON(){return{_tag:this._tag,literal:Ve(this.literal)?String(this.literal):this.literal,annotations:Nk(this.annotations)}}},SO=bO(`Literal`),CO=new xO(null),wO=class{symbol;annotations;_tag=`UniqueSymbol`;constructor(e,t={}){this.symbol=e,this.annotations=t}toString(){return xr(Lk(this),()=>zt(this.symbol))}toJSON(){return{_tag:this._tag,symbol:String(this.symbol),annotations:Nk(this.annotations)}}},TO=class{annotations;_tag=`UndefinedKeyword`;constructor(e={}){this.annotations=e}toString(){return Fk(this)}toJSON(){return{_tag:this._tag,annotations:Nk(this.annotations)}}},EO=new TO({[LD]:`undefined`}),DO=class{annotations;_tag=`NeverKeyword`;constructor(e={}){this.annotations=e}toString(){return Fk(this)}toJSON(){return{_tag:this._tag,annotations:Nk(this.annotations)}}},OO=new DO({[LD]:`never`}),kO=class{annotations;_tag=`UnknownKeyword`;constructor(e={}){this.annotations=e}toString(){return Fk(this)}toJSON(){return{_tag:this._tag,annotations:Nk(this.annotations)}}},AO=new kO({[LD]:`unknown`}),jO=class{annotations;_tag=`AnyKeyword`;constructor(e={}){this.annotations=e}toString(){return Fk(this)}toJSON(){return{_tag:this._tag,annotations:Nk(this.annotations)}}},MO=new jO({[LD]:`any`}),NO=class{annotations;_tag=`StringKeyword`;constructor(e={}){this.annotations=e}toString(){return Fk(this)}toJSON(){return{_tag:this._tag,annotations:Nk(this.annotations)}}},PO=new NO({[LD]:`string`,[zD]:`a string`}),FO=bO(`StringKeyword`),IO=class{annotations;_tag=`NumberKeyword`;constructor(e={}){this.annotations=e}toString(){return Fk(this)}toJSON(){return{_tag:this._tag,annotations:Nk(this.annotations)}}},LO=new IO({[LD]:`number`,[zD]:`a number`}),RO=class{annotations;_tag=`BooleanKeyword`;constructor(e={}){this.annotations=e}toString(){return Fk(this)}toJSON(){return{_tag:this._tag,annotations:Nk(this.annotations)}}},zO=new RO({[LD]:`boolean`,[zD]:`a boolean`}),BO=class{annotations;_tag=`BigIntKeyword`;constructor(e={}){this.annotations=e}toString(){return Fk(this)}toJSON(){return{_tag:this._tag,annotations:Nk(this.annotations)}}},VO=new BO({[LD]:`bigint`,[zD]:`a bigint`}),HO=class{annotations;_tag=`SymbolKeyword`;constructor(e={}){this.annotations=e}toString(){return Fk(this)}toJSON(){return{_tag:this._tag,annotations:Nk(this.annotations)}}},UO=new HO({[LD]:`symbol`,[zD]:`a symbol`}),WO=bO(`SymbolKeyword`),GO=class{type;annotations;constructor(e,t={}){this.type=e,this.annotations=t}toJSON(){return{type:this.type.toJSON(),annotations:Nk(this.annotations)}}toString(){return String(this.type)}},KO=class extends GO{isOptional;constructor(e,t,n={}){super(e,n),this.isOptional=t}toJSON(){return{type:this.type.toJSON(),isOptional:this.isOptional,annotations:Nk(this.annotations)}}toString(){return String(this.type)+(this.isOptional?`?`:``)}},qO=e=>e.map(e=>e.type),JO=class{elements;rest;isReadonly;annotations;_tag=`TupleType`;constructor(e,t,n,r={}){this.elements=e,this.rest=t,this.isReadonly=n,this.annotations=r;let i=!1,a=!1;for(let t of e)if(t.isOptional)i=!0;else if(i){a=!0;break}if(a||i&&t.length>1)throw Error(lD)}toString(){return xr(Lk(this),()=>YO(this))}toJSON(){return{_tag:this._tag,elements:this.elements.map(e=>e.toJSON()),rest:this.rest.map(e=>e.toJSON()),isReadonly:this.isReadonly,annotations:Nk(this.annotations)}}},YO=e=>{let t=e.elements.map(String).join(`, `);return Gr(e.rest,{onEmpty:()=>`readonly [${t}]`,onNonEmpty:(n,r)=>{let i=String(n),a=i.includes(` | `)?`(${i})`:i;if(r.length>0){let n=r.map(String).join(`, `);return e.elements.length>0?`readonly [${t}, ...${a}[], ${n}]`:`readonly [...${a}[], ${n}]`}return e.elements.length>0?`readonly [${t}, ...${a}[]]`:`ReadonlyArray<${i}>`}})},XO=class extends KO{name;isReadonly;constructor(e,t,n,r,i){super(t,n,i),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:Nk(this.annotations)}}},ZO=e=>{switch(e._tag){case`StringKeyword`:case`SymbolKeyword`:case`TemplateLiteral`:return!0;case`Refinement`:return ZO(e.from)}return!1},QO=class{type;isReadonly;parameter;constructor(e,t,n){if(this.type=t,this.isReadonly=n,ZO(e))this.parameter=e;else throw Error(cD)}toString(){return(this.isReadonly?`readonly `:``)+`[x: ${this.parameter}]: ${this.type}`}toJSON(){return{parameter:this.parameter.toJSON(),type:this.type.toJSON(),isReadonly:this.isReadonly}}},$O=class{annotations;_tag=`TypeLiteral`;propertySignatures;indexSignatures;constructor(e,t,n={}){this.annotations=n;let r={};for(let t=0;t<e.length;t++){let n=e[t].name;if(Object.prototype.hasOwnProperty.call(r,n))throw Error(dD(n));r[n]=null}let i={string:!1,symbol:!1};for(let e=0;e<t.length;e++){let n=Pk(t[e].parameter);if(FO(n)){if(i.string)throw Error(sD(`string`));i.string=!0}else if(WO(n)){if(i.symbol)throw Error(sD(`symbol`));i.symbol=!0}}this.propertySignatures=e,this.indexSignatures=t}toString(){return xr(Lk(this),()=>tk(this))}toJSON(){return{_tag:this._tag,propertySignatures:this.propertySignatures.map(e=>e.toJSON()),indexSignatures:this.indexSignatures.map(e=>e.toJSON()),annotations:Nk(this.annotations)}}},ek=e=>e.map(String).join(`; `),tk=e=>{if(e.propertySignatures.length>0){let t=e.propertySignatures.map(String).join(`; `);return e.indexSignatures.length>0?`{ ${t}; ${ek(e.indexSignatures)} }`:`{ ${t} }`}return e.indexSignatures.length>0?`{ ${ek(e.indexSignatures)} }`:`{}`},nk=pi(mr(yg,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})),rk={string:`StringKeyword`,number:`NumberKeyword`,boolean:`BooleanKeyword`,bigint:`BigIntKeyword`},ik=e=>Ti(e,e=>lk(e)?ik(e.types):[e]),ak=e=>{let t=nk(e),n=[],r={},i=[];for(let e of t)switch(e._tag){case`NeverKeyword`:break;case`AnyKeyword`:return[MO];case`UnknownKeyword`:return[AO];case`ObjectKeyword`:case`UndefinedKeyword`:case`VoidKeyword`:case`StringKeyword`:case`NumberKeyword`:case`BooleanKeyword`:case`BigIntKeyword`:case`SymbolKeyword`:r[e._tag]||(r[e._tag]=e,n.push(e));break;case`Literal`:{let t=typeof e.literal;switch(t){case`string`:case`number`:case`bigint`:case`boolean`:!r[rk[t]]&&!i.includes(e.literal)&&(i.push(e.literal),n.push(e));break;case`object`:i.includes(e.literal)||(i.push(e.literal),n.push(e))}break}case`UniqueSymbol`:!r.SymbolKeyword&&!i.includes(e.symbol)&&(i.push(e.symbol),n.push(e));break;case`TupleType`:r.ObjectKeyword||n.push(e);break;case`TypeLiteral`:e.propertySignatures.length===0&&e.indexSignatures.length===0?r[`{}`]||(r[`{}`]=e,n.push(e)):r.ObjectKeyword||n.push(e);break;default:n.push(e)}return n},ok=class e{types;annotations;static make=(t,n)=>ck(t)?new e(t,n):t.length===1?t[0]:OO;static unify=(t,n)=>e.make(ak(ik(t)),n);_tag=`Union`;constructor(e,t={}){this.types=e,this.annotations=t}toString(){return xr(Lk(this),()=>this.types.map(String).join(` | `))}toJSON(){return{_tag:this._tag,types:this.types.map(e=>e.toJSON()),annotations:Nk(this.annotations)}}},sk=(e,t)=>e.map(t),ck=e=>e.length>1,lk=bO(`Union`),uk=C(Symbol.for(`effect/Schema/AST/toJSONMemoMap`),()=>new WeakMap),dk=class{f;annotations;_tag=`Suspend`;constructor(e,t={}){this.f=e,this.annotations=t,this.f=QE(e)}toString(){return Lk(this).pipe(Sr(()=>kr(Er(this.f)(),e=>Lk(e))),xr(()=>`<suspended schema>`))}toJSON(){let e=this.f(),t=uk.get(e);return t||(uk.set(e,{_tag:this._tag}),t={_tag:this._tag,ast:e.toJSON(),annotations:Nk(this.annotations)},uk.set(e,t),t)}},fk=class{from;filter;annotations;_tag=`Refinement`;constructor(e,t,n={}){this.from=e,this.filter=t,this.annotations=n}toString(){return oO(this).pipe(xr(()=>br(Ik(this),{onNone:()=>`{ ${this.from} | filter }`,onSome:e=>pk(this.from)?String(this.from)+` & `+e:e})))}toJSON(){return{_tag:this._tag,from:this.from.toJSON(),annotations:Nk(this.annotations)}}},pk=bO(`Refinement`),mk={},hk=class{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 xr(Lk(this),()=>`(${String(this.from)} <-> ${String(this.to)})`)}toJSON(){return{_tag:this._tag,from:this.from.toJSON(),to:this.to.toJSON(),annotations:Nk(this.annotations)}}},gk=class{decode;encode;_tag=`FinalTransformation`;constructor(e,t){this.decode=e,this.encode=t}},_k=class{from;to;decode;encode;constructor(e,t,n,r){this.from=e,this.to=t,this.decode=n,this.encode=r}},vk=class{propertySignatureTransformations;_tag=`TypeLiteralTransformation`;constructor(e){this.propertySignatureTransformations=e;let t={},n={};for(let r of e){let e=r.from;if(t[e])throw Error(uD(e));t[e]=!0;let i=r.to;if(n[i])throw Error(uD(i));n[i]=!0}}},yk=(e,t)=>{let n=Object.getOwnPropertyDescriptors(e),r={...e.annotations};delete r[ID];let i={...r,...t},a=pO(e);return yr(a)&&(i[QD]=yk(a.value,t)),n.annotations.value=i,Object.create(Object.getPrototypeOf(e),n)},bk=`[\\s\\S]*?`,xk=`[+-]?\\d*\\.?\\d+(?:[Ee][+-]?\\d+)?`,Sk=(e,t)=>{switch(e._tag){case`Literal`:return Sg(String(e.literal));case`StringKeyword`:return bk;case`NumberKeyword`:return xk;case`TemplateLiteral`:return wk(e,t,!1);case`Union`:return e.types.map(e=>Sk(e,t)).join(`|`)}},Ck=(e,t,n,r)=>{if(lk(e)){if(n&&!r)return`(?:${t})`}else if(!n||!r)return t;return`(${t})`},wk=(e,t,n)=>{let r=``;if(e.head!==``){let i=Sg(e.head);r+=t&&n?`(${i})`:i}for(let i of e.spans){let e=Sk(i.type,t);if(r+=Ck(i.type,e,t,n),i.literal!==``){let e=Sg(i.literal);r+=t&&n?`(${e})`:e}}return r},Tk=e=>RegExp(`^${wk(e,!1,!0)}$`),Ek=(e,t)=>{let n=[],r=[],i=e=>{switch(e._tag){case`NeverKeyword`:break;case`StringKeyword`:case`SymbolKeyword`:case`TemplateLiteral`:case`Refinement`:r.push(new QO(e,t,!0));break;case`Literal`:if(Re(e.literal)||ze(e.literal))n.push(new XO(e.literal,t,!1,!0));else throw Error(oD(e.literal));break;case`Enums`:for(let[r,i]of e.enums)n.push(new XO(i,t,!1,!0));break;case`UniqueSymbol`:n.push(new XO(e.symbol,t,!1,!0));break;case`Union`:e.types.forEach(i);break;default:throw Error(aD(e))}};return i(e),{propertySignatures:n,indexSignatures:r}},Dk=e=>t=>{let n;for(let r of e)Object.prototype.hasOwnProperty.call(t.annotations,r)&&(n===void 0&&(n={}),n[r]=t.annotations[r]);return n},Ok=Dk([BD,VD,HD,UD,WD,GD]),kk=e=>{switch(e._tag){case`Declaration`:{let t=kD(e.typeParameters,kk);return t===e.typeParameters?e:new yO(t,e.decodeUnknown,e.encodeUnknown,e.annotations)}case`TupleType`:{let t=kD(e.elements,e=>{let t=kk(e.type);return t===e.type?e:new KO(t,e.isOptional)}),n=qO(e.rest),r=kD(n,kk);return t===e.elements&&r===n?e:new JO(t,r.map(e=>new GO(e)),e.isReadonly,e.annotations)}case`TypeLiteral`:{let t=kD(e.propertySignatures,e=>{let t=kk(e.type);return t===e.type?e:new XO(e.name,t,e.isOptional,e.isReadonly)}),n=kD(e.indexSignatures,e=>{let t=kk(e.type);return t===e.type?e:new QO(e.parameter,t,e.isReadonly)});return t===e.propertySignatures&&n===e.indexSignatures?e:new $O(t,n,e.annotations)}case`Union`:{let t=kD(e.types,kk);return t===e.types?e:ok.make(t,e.annotations)}case`Suspend`:return new dk(()=>kk(e.f()),e.annotations);case`Refinement`:{let t=kk(e.from);return t===e.from?e:new fk(t,e.filter,e.annotations)}case`Transformation`:{let t=Ok(e);return kk(t===void 0?e.to:yk(e.to,t))}}return e},Ak=e=>{switch(e._tag){case`Transformation`:return e.from;case`Refinement`:return Ak(e.from);case`Suspend`:return Ak(e.f())}},jk=(e,t)=>{switch(e._tag){case`Declaration`:{let n=kD(e.typeParameters,e=>jk(e,t));return n===e.typeParameters?e:new yO(n,e.decodeUnknown,e.encodeUnknown)}case`TupleType`:{let n=kD(e.elements,e=>{let n=jk(e.type,t);return n===e.type?e:new KO(n,e.isOptional)}),r=qO(e.rest),i=kD(r,e=>jk(e,t));return n===e.elements&&i===r?e:new JO(n,i.map(e=>new GO(e)),e.isReadonly)}case`TypeLiteral`:{let n=kD(e.propertySignatures,e=>{let n=jk(e.type,t);return n===e.type?e:new XO(e.name,n,e.isOptional,e.isReadonly)}),r=kD(e.indexSignatures,e=>{let n=jk(e.type,t);return n===e.type?e:new QO(e.parameter,n,e.isReadonly)});return n===e.propertySignatures&&r===e.indexSignatures?e:new $O(n,r)}case`Union`:{let n=kD(e.types,e=>jk(e,t));return n===e.types?e:ok.make(n)}case`Suspend`:{let n,r=vO(e);if(yr(r)){let e=t?`Bound`:``;n={[gO]:`${r.value}Encoded${e}`}}return new dk(()=>jk(e.f(),t),n)}case`Refinement`:{let n=jk(e.from,t);return t?n===e.from?e:Ak(e.from)===void 0&&hO(e)?new fk(n,e.filter,e.annotations):n:n}case`Transformation`:return jk(e.from,t)}return e},Mk=e=>jk(e,!1),Nk=e=>{let t={};for(let n of Object.getOwnPropertySymbols(e))t[String(n)]=e[n];return t},Pk=e=>{switch(e._tag){case`StringKeyword`:case`SymbolKeyword`:case`TemplateLiteral`:return e;case`Refinement`:return Pk(e.from)}},Fk=e=>xr(Lk(e),()=>e._tag),Ik=e=>iO(e).pipe(Sr(()=>sO(e)),Sr(()=>aO(e)),Or(t=>t+AD(e))),Lk=e=>Sr(oO(e),()=>Ik(e))}));function zk(e){return e.sort(OA).map(e=>e[1])}function Bk(e){return sO(e).pipe(Sr(()=>iO(e)),Sr(()=>aO(e)),Sr(()=>oO(e)),xr(()=>`{ ${e.from} | filter }`))}function Vk(e){return e.message===void 0?`Expected ${pk(e.ast)?Bk(e.ast):String(e.ast)}, actual ${zt(e.actual)}`:e.message}var Hk,Uk,Wk,Gk,Kk,qk,Jk,Yk,Xk,Zk,Qk,$k,eA,tA,nA,rA,iA,aA,oA,sA,cA,lA,uA,dA,fA,pA,mA,hA,gA,_A,vA,yA,bA,xA,SA,CA,wA,TA,EA,DA,OA,kA,AA,jA,MA,NA,PA,FA,IA,LA,RA,zA,BA,VA,HA,UA,WA,GA,KA,qA,JA,YA,XA,ZA=v((()=>{Pi(),Gh(),I_(),jE(),lr(),zb(),S(),Ie(),Xt(),rD(),Rr(),T(),Sb(),Rk(),Hk=class{path;actual;issue;_tag=`Pointer`;constructor(e,t,n){this.path=e,this.actual=t,this.issue=n}},Uk=class{actual;message;_tag=`Unexpected`;constructor(e,t){this.actual=e,this.message=t}},Wk=class{ast;message;_tag=`Missing`;actual=void 0;constructor(e,t){this.ast=e,this.message=t}},Gk=class{ast;actual;issues;output;_tag=`Composite`;constructor(e,t,n,r){this.ast=e,this.actual=t,this.issues=n,this.output=r}},Kk=class{ast;actual;kind;issue;_tag=`Refinement`;constructor(e,t,n,r){this.ast=e,this.actual=t,this.kind=n,this.issue=r}},qk=class{ast;actual;kind;issue;_tag=`Transformation`;constructor(e,t,n,r){this.ast=e,this.actual=t,this.kind=n,this.issue=r}},Jk=class{ast;actual;message;_tag=`Type`;constructor(e,t,n){this.ast=e,this.actual=t,this.message=n}},Yk=class{ast;actual;message;_tag=`Forbidden`;constructor(e,t,n){this.ast=e,this.actual=t,this.message=n}},Xk=Symbol.for(`effect/Schema/ParseErrorTypeId`),Zk=class extends F_(`ParseError`){[Xk]=Xk;get message(){return this.toString()}toString(){return jA.formatIssueSync(this.issue)}toJSON(){return{_id:`ParseError`,message:this.toString()}}[N](){return this.toJSON()}},Qk=e=>new Zk({issue:e}),$k=I,eA=L,tA=Qn,nA=Zn,rA=$n,iA=x(2,(e,t)=>rA(e)?ar(e,{onLeft:L,onRight:t}):OE(e,t)),aA=x(2,(e,t)=>rA(e)?ir(e,t):wE(e,t)),oA=x(2,(e,t)=>rA(e)?rr(e,t):EE(e,t)),sA=x(2,(e,t)=>rA(e)?nr(e,{onLeft:t.onFailure,onRight:t.onSuccess}):TE(e,t)),cA=x(2,(e,t)=>rA(e)?ar(e,{onLeft:t,onRight:I}):CE(e,t)),lA=(e,t)=>t===void 0||ze(t)?e:e===void 0?t:{...e,...t},uA=(e,t,n)=>{let r=yA(e,t);return(e,t)=>r(e,lA(n,t))},dA=(e,t,n)=>{let r=uA(e,t,n);return(e,t)=>sr(r(e,t),Qk)},fA=(e,t,n)=>{let r=yA(e,t);return(e,t)=>r(e,{...lA(n,t),isEffectAllowed:!0})},pA=(e,t)=>uA(e.ast,!0,t),mA=(e,t)=>fA(e.ast,!0,t),hA=(e,t)=>fA(e.ast,!1,t),gA=(e,t)=>dA(kk(e.ast),!0,t),_A=C(Symbol.for(`effect/ParseResult/decodeMemoMap`),()=>new WeakMap),vA=C(Symbol.for(`effect/ParseResult/encodeMemoMap`),()=>new WeakMap),yA=(e,t)=>{let n=t?_A:vA,r=n.get(e);if(r)return r;let i=SA(e,t),a=dO(e),o=yr(a)?(e,t)=>i(e,lA(t,a.value)):i,s=fO(e),c=t&&yr(s)?(t,n)=>DA(cA(o(t,n),s.value),e,t,n):o;return n.set(e,c),c},bA=e=>Tr(cO(e)),xA=e=>Tr(lO(e)),SA=(e,t)=>{switch(e._tag){case`Refinement`:if(t){let t=yA(e.from,!0);return(n,r)=>{r??=mk;let i=r?.errors===`all`,a=iA(cA(t(n,r),t=>{let a=new Kk(e,n,`From`,t);return i&&hO(e)&&BA(t)?br(e.filter(n,r,e),{onNone:()=>L(a),onSome:t=>L(new Gk(e,n,[a,new Kk(e,n,`Predicate`,t)]))}):L(a)}),t=>br(e.filter(t,r,e),{onNone:()=>I(t),onSome:t=>L(new Kk(e,n,`Predicate`,t))}));return DA(a,e,n,r)}}{let t=yA(kk(e),!0),n=yA(EA(e.from),!1);return(r,i)=>DA(iA(t(r,i),e=>n(e,i)),e,r,i)}case`Transformation`:{let n=kA(e.transformation,t),r=t?yA(e.from,!0):yA(e.to,!1),i=t?yA(e.to,!0):yA(e.from,!1);return(a,o)=>DA(iA(oA(r(a,o),n=>new qk(e,a,t?`Encoded`:`Type`,n)),r=>iA(oA(n(r,o??mk,e,a),t=>new qk(e,a,`Transformation`,t)),n=>oA(i(n,o),n=>new qk(e,a,t?`Type`:`Encoded`,n)))),e,a,o)}case`Declaration`:{let n=t?e.decodeUnknown(...e.typeParameters):e.encodeUnknown(...e.typeParameters);return(t,r)=>DA(n(t,r??mk,e),e,t,r)}case`Literal`:return CA(e,t=>t===e.literal);case`UniqueSymbol`:return CA(e,t=>t===e.symbol);case`UndefinedKeyword`:return CA(e,We);case`NeverKeyword`:return CA(e,Ge);case`UnknownKeyword`:case`AnyKeyword`:case`VoidKeyword`:return I;case`StringKeyword`:return CA(e,Re);case`NumberKeyword`:return CA(e,ze);case`BooleanKeyword`:return CA(e,Be);case`BigIntKeyword`:return CA(e,Ve);case`SymbolKeyword`:return CA(e,He);case`ObjectKeyword`:return CA(e,qe);case`Enums`:return CA(e,t=>e.enums.some(([e,n])=>n===t));case`TemplateLiteral`:{if(e.spans.every(e=>FO(e.type)))return CA(e,t=>{if(!Re(t)||!t.startsWith(e.head))return!1;let n=e.head.length;for(let r=0;r<e.spans.length-1;r++){let i=e.spans[r].literal,a=t.indexOf(i,n);if(a===-1)return!1;n=a+i.length}let r=e.spans[e.spans.length-1].literal;return t.endsWith(r)&&t.length-r.length>=n});let t=Tk(e);return CA(e,e=>Re(e)&&t.test(e))}case`TupleType`:{let n=e.elements.map(e=>yA(e.type,t)),r=e.rest.map(e=>yA(e.type,t)),i=e.elements.filter(e=>!e.isOptional);e.rest.length>0&&(i=i.concat(e.rest.slice(1)));let a=i.length,o=e.elements.length>0?e.elements.map((e,t)=>t).join(` | `):`never`,s=bA(e),c=xA(e);return(t,l)=>{if(!Yr(t))return L(new Jk(e,t));let u=l?.errors===`all`,d=[],f=0,p=[],m=t.length;for(let n=m;n<=a-1;n++){let r=new Hk(n,t,new Wk(i[n-m]));if(u){d.push([f++,r]);continue}return L(new Gk(e,t,r,p))}if(e.rest.length===0)for(let n=e.elements.length;n<=m-1;n++){let r=new Hk(n,t,new Uk(t[n],`is unexpected, expected: ${o}`));if(u){d.push([f++,r]);continue}return L(new Gk(e,t,r,p))}let h=0,g;for(;h<n.length;h++)if(m<h+1){if(e.elements[h].isOptional)continue}else{let r=n[h],i=r(t[h],l);if(rA(i)){if(er(i)){let n=new Hk(h,t,i.left);if(u){d.push([f++,n]);continue}return L(new Gk(e,t,n,zk(p)))}p.push([f++,i.right])}else{let n=f++,r=h;g||=[],g.push(({es:a,output:o})=>OE(DE(i),i=>{if(er(i)){let s=new Hk(r,t,i.left);return u?(a.push([n,s]),SE):L(new Gk(e,t,s,zk(o)))}return o.push([n,i.right]),SE}))}}if($r(r)){let[n,...i]=r;for(;h<m-i.length;h++){let r=n(t[h],l);if(rA(r)){if(er(r)){let n=new Hk(h,t,r.left);if(u){d.push([f++,n]);continue}return L(new Gk(e,t,n,zk(p)))}p.push([f++,r.right])}else{let n=f++,i=h;g||=[],g.push(({es:a,output:o})=>OE(DE(r),r=>{if(er(r)){let s=new Hk(i,t,r.left);return u?(a.push([n,s]),SE):L(new Gk(e,t,s,zk(o)))}return o.push([n,r.right]),SE}))}}for(let n=0;n<i.length;n++){let r=h+n;if(!(m<r+1)){let a=i[n](t[r],l);if(rA(a)){if(er(a)){let n=new Hk(r,t,a.left);if(u){d.push([f++,n]);continue}return L(new Gk(e,t,n,zk(p)))}p.push([f++,a.right])}else{let n=f++;g||=[],g.push(({es:i,output:o})=>OE(DE(a),a=>{if(er(a)){let s=new Hk(r,t,a.left);return u?(i.push([n,s]),SE):L(new Gk(e,t,s,zk(o)))}return o.push([n,a.right]),SE}))}}}}let _=({es:n,output:r})=>Qr(n)?L(new Gk(e,t,zk(n),zk(r))):I(zk(r));if(g&&g.length>0){let e=g;return xE(()=>{let t={es:yi(d),output:yi(p)};return OE(bE(e,e=>e(t),{concurrency:s,batching:c,discard:!0}),()=>_(t))})}return _({output:p,es:d})}}case`TypeLiteral`:{if(e.propertySignatures.length===0&&e.indexSignatures.length===0)return CA(e,Xe);let n=[],r={},i=[];for(let a of e.propertySignatures)n.push([yA(a.type,t),a]),r[a.name]=null,i.push(a.name);let a=e.indexSignatures.map(e=>[yA(e.parameter,t),yA(e.type,t),e.parameter]),o=ok.make(e.indexSignatures.map(e=>e.parameter).concat(i.map(e=>He(e)?new wO(e):new xO(e)))),s=yA(o,t),c=bA(e),l=xA(e);return(t,u)=>{if(!et(t))return L(new Jk(e,t));let d=u?.errors===`all`,f=[],p=0,m=u?.onExcessProperty===`error`,h=u?.onExcessProperty===`preserve`,g={},_;if(m||h){_=Reflect.ownKeys(t);for(let n of _){let r=s(n,u);if(rA(r)&&er(r)){if(m){let r=new Hk(n,t,new Uk(t[n],`is unexpected, expected: ${String(o)}`));if(d){f.push([p++,r]);continue}return L(new Gk(e,t,r,g))}g[n]=t[n]}}}let ee,te=u?.exact===!0;for(let r=0;r<n.length;r++){let i=n[r][1],a=i.name,o=Object.prototype.hasOwnProperty.call(t,a);if(!o){if(i.isOptional)continue;if(te){let n=new Hk(a,t,new Wk(i));if(d){f.push([p++,n]);continue}return L(new Gk(e,t,n,g))}}let s=n[r][0],c=s(t[a],u);if(rA(c)){if(er(c)){let n=new Hk(a,t,o?c.left:new Wk(i));if(d){f.push([p++,n]);continue}return L(new Gk(e,t,n,g))}g[a]=c.right}else{let n=p++,r=a;ee||=[],ee.push(({es:a,output:s})=>OE(DE(c),c=>{if(er(c)){let l=new Hk(r,t,o?c.left:new Wk(i));return d?(a.push([n,l]),SE):L(new Gk(e,t,l,s))}return s[r]=c.right,SE}))}}for(let n=0;n<a.length;n++){let i=a[n],o=i[0],s=i[1],c=ZE(t,i[2]);for(let n of c){let i=o(n,u);if(rA(i)&&tr(i)){let i=s(t[n],u);if(rA(i)){if(er(i)){let r=new Hk(n,t,i.left);if(d){f.push([p++,r]);continue}return L(new Gk(e,t,r,g))}Object.prototype.hasOwnProperty.call(r,n)||(g[n]=i.right)}else{let a=p++,o=n;ee||=[],ee.push(({es:s,output:c})=>OE(DE(i),i=>{if(er(i)){let n=new Hk(o,t,i.left);return d?(s.push([a,n]),SE):L(new Gk(e,t,n,c))}return Object.prototype.hasOwnProperty.call(r,n)||(c[n]=i.right),SE}))}}}}let ne=({es:n,output:r})=>{if(Qr(n))return L(new Gk(e,t,zk(n),r));if(u?.propertyOrder===`original`){let e=_||Reflect.ownKeys(t);for(let t of i)e.indexOf(t)===-1&&e.push(t);let n={};for(let t of e)Object.prototype.hasOwnProperty.call(r,t)&&(n[t]=r[t]);return I(n)}return I(r)};if(ee&&ee.length>0){let e=ee;return xE(()=>{let t={es:yi(f),output:Object.assign({},g)};return OE(bE(e,e=>e(t),{concurrency:c,batching:l,discard:!0}),()=>ne(t))})}return ne({es:f,output:g})}}case`Union`:{let n=TA(e.types,t),r=Reflect.ownKeys(n.keys),i=r.length,a=e.types.length,o=new Map;for(let n=0;n<a;n++)o.set(e.types[n],yA(e.types[n],t));let s=bA(e)??1,c=xA(e);return(t,l)=>{let u=[],d=0,f=[];if(i>0){if(Ke(t))for(let e=0;e<i;e++){let i=r[e],o=n.keys[i].buckets;if(Object.prototype.hasOwnProperty.call(t,i)){let e=String(t[i]);if(Object.prototype.hasOwnProperty.call(o,e))f=f.concat(o[e]);else{let{candidates:e,literals:r}=n.keys[i],o=ok.make(r),s=e.length===a?new $O([new XO(i,o,!1,!0)],[]):ok.make(e);u.push([d++,new Gk(s,t,new Hk(i,t,new Jk(o,t[i])))])}}else{let{candidates:e,literals:r}=n.keys[i],o=new XO(i,ok.make(r),!1,!0),s=e.length===a?new $O([o],[]):ok.make(e);u.push([d++,new Gk(s,t,new Hk(i,t,new Wk(o)))])}}else{let r=n.candidates.length===a?e:ok.make(n.candidates);u.push([d++,new Jk(r,t)])}}n.otherwise.length>0&&(f=f.concat(n.otherwise));let p;for(let e=0;e<f.length;e++){let n=f[e],r=o.get(n)(t,l);if(rA(r)&&(!p||p.length===0)){if(tr(r))return r;u.push([d++,r.left])}else{let e=d++;p||=[],p.push(t=>xE(()=>`finalResult`in t?SE:OE(DE(r),n=>(tr(n)?t.finalResult=n:t.es.push([e,n.left]),SE))))}}let m=n=>Qr(n)?n.length===1&&n[0][1]._tag===`Type`?L(n[0][1]):L(new Gk(e,t,zk(n))):L(new Jk(e,t));if(p&&p.length>0){let e=p;return xE(()=>{let t={es:yi(u)};return OE(bE(e,e=>e(t),{concurrency:s,batching:c,discard:!0}),()=>`finalResult`in t?t.finalResult:m(t.es))})}return m(u)}}case`Suspend`:{let n=QE(()=>yA(e.f(),t));return(e,t)=>n()(e,t)}}},CA=(e,t)=>n=>t(n)?I(n):L(new Jk(e,n)),wA=(e,t)=>{switch(e._tag){case`Declaration`:{let n=pO(e);if(yr(n))return wA(n.value,t);break}case`TypeLiteral`:{let n=[];for(let r=0;r<e.propertySignatures.length;r++){let i=e.propertySignatures[r],a=t?Mk(i.type):kk(i.type);SO(a)&&!i.isOptional&&n.push([i.name,a])}return n}case`TupleType`:{let n=[];for(let r=0;r<e.elements.length;r++){let i=e.elements[r],a=t?Mk(i.type):kk(i.type);SO(a)&&!i.isOptional&&n.push([r,a])}return n}case`Refinement`:return wA(e.from,t);case`Suspend`:return wA(e.f(),t);case`Transformation`:return wA(t?e.from:e.to,t)}return[]},TA=(e,t)=>{let n={},r=[],i=[];for(let a=0;a<e.length;a++){let o=e[a],s=wA(o,t);if(s.length>0){i.push(o);for(let e=0;e<s.length;e++){let[t,r]=s[e],i=String(r.literal);n[t]=n[t]||{buckets:{},literals:[],candidates:[]};let a=n[t].buckets;if(Object.prototype.hasOwnProperty.call(a,i)){if(e<s.length-1)continue;a[i].push(o),n[t].literals.push(r),n[t].candidates.push(o)}else{a[i]=[o],n[t].literals.push(r),n[t].candidates.push(o);break}}}else r.push(o)}return{keys:n,otherwise:r,candidates:i}},EA=e=>pk(e)?EA(e.from):e,DA=(e,t,n,r)=>{if(r?.isEffectAllowed===!0||rA(e))return e;let i=new bb,a=kE(e,{scheduler:i});i.flush();let o=a.unsafePoll();if(o){if(Rb(o))return I(o.value);let e=o.cause;return Hh(e)?L(e.error):L(new Yk(t,n,Wh(e)))}return L(new Yk(t,n,`cannot be be resolved synchronously, this is caused by using runSync on an effect that performs async work`))},OA=([e],[t])=>e>t?1:e<t?-1:0,kA=(e,t)=>{switch(e._tag){case`FinalTransformation`:return t?e.decode:e.encode;case`ComposeTransformation`:return I;case`TypeLiteralTransformation`:return n=>{let r=I(n);for(let n of e.propertySignatureTransformations){let[e,i]=t?[n.from,n.to]:[n.to,n.from],a=t?n.decode:n.encode;r=aA(r,t=>{let n=a(Object.prototype.hasOwnProperty.call(t,e)?z(t[e]):R());return delete t[e],yr(n)&&(t[i]=n.value),t})}return r}}},AA=(e,t=[])=>({value:e,forest:t}),jA={formatIssue:e=>aA(XA(e),MA),formatIssueSync:e=>{let t=jA.formatIssue(e);return rA(t)?cr(t):AE(t)},formatError:e=>jA.formatIssue(e.issue),formatErrorSync:e=>jA.formatIssueSync(e.issue)},MA=e=>e.value+NA(`
21
- `,e.forest),NA=(e,t)=>{let n=``,r=t.length,i;for(let a=0;a<r;a++){i=t[a];let o=a===r-1;n+=e+(o?`└`:`├`)+`─ `+i.value,n+=NA(e+(r>1&&!o?`│ `:` `),i.forest)}return n},PA=e=>{switch(e){case`Encoded`:return`Encoded side transformation failure`;case`Transformation`:return`Transformation process failure`;case`Type`:return`Type side transformation failure`}},FA=e=>{switch(e){case`From`:return`From side refinement failure`;case`Predicate`:return`Predicate refinement failure`}},IA=e=>`ast`in e?z(e.ast):R(),LA=I(void 0),RA=e=>IA(e).pipe(kr(nO),br({onNone:()=>LA,onSome:t=>{let n=t(e);return Re(n)?I({message:n,override:!1}):yE(n)?wE(n,e=>({message:e,override:!1})):Re(n.message)?I({message:n.message,override:n.override}):wE(n.message,e=>({message:e,override:n.override}))}})),zA=e=>t=>t._tag===e,BA=zA(`Composite`),VA=zA(`Refinement`),HA=zA(`Transformation`),UA=e=>iA(RA(e),t=>t===void 0?LA:!t.override&&(BA(e)||VA(e)&&e.kind===`From`||HA(e)&&e.kind!==`Transformation`)?HA(e)||VA(e)?UA(e.issue):LA:I(t.message)),WA=e=>IA(e).pipe(kr(uO),Ar(t=>t(e)),Tr),GA=e=>aA(UA(e),t=>t??WA(e)??Vk(e)),KA=e=>WA(e)??String(e.ast),qA=e=>e.message??`is forbidden`,JA=e=>e.message??`is unexpected`,YA=e=>{let t=rO(e.ast);if(yr(t)){let e=t.value();return Re(e)?I(e):e}return I(e.message??`is missing`)},XA=e=>{switch(e._tag){case`Type`:return aA(GA(e),AA);case`Forbidden`:return I(AA(KA(e),[AA(qA(e))]));case`Unexpected`:return I(AA(JA(e)));case`Missing`:return aA(YA(e),AA);case`Transformation`:return iA(UA(e),t=>t===void 0?aA(XA(e.issue),t=>AA(KA(e),[AA(PA(e.kind),[t])])):I(AA(t)));case`Refinement`:return iA(UA(e),t=>t===void 0?aA(XA(e.issue),t=>AA(KA(e),[AA(FA(e.kind),[t])])):I(AA(t)));case`Pointer`:return aA(XA(e.issue),t=>AA(nD(e.path),[t]));case`Composite`:return iA(UA(e),t=>{if(t!==void 0)return I(AA(t));let n=KA(e);return $E(e.issues)?aA(bE(e.issues,XA),e=>AA(n,e)):aA(XA(e.issues),e=>AA(n,[e]))})}}})),QA,$A,ej=v((()=>{S(),T(),QA=x(e=>qe(e[0]),(e,...t)=>{let n={};for(let r of t)r in e&&(n[r]=e[r]);return n}),$A=x(e=>qe(e[0]),(e,...t)=>{let n={...e};for(let e of t)delete n[e];return n})}));function tj(e){return class{[_j]=vj;static ast=e;static annotations(e){return tj(xj(this.ast,e))}static pipe(){return P(this,arguments)}static toString(){return String(e)}static Type;static Encoded;static Context;static[_j]=vj}}function nj(e){return ck(e)?ok.make(sk(e,e=>new xO(e))):new xO(e[0])}function rj(e,t=nj(e)){return class extends tj(t){static annotations(e){return rj(this.literals,xj(this.ast,e))}static literals=[...e]}}function H(...e){return $r(e)?rj(e):jj}function ij(e,t){return class extends tj(t){static annotations(e){return ij(this.typeParameters,xj(this.ast,e))}static typeParameters=[...e]}}function aj(e,t=Ij(e)){return class extends tj(t){static annotations(e){return aj(this.members,xj(this.ast,e))}static members=[...e]}}function U(...e){return ck(e)?aj(e):$r(e)?e[0]:jj}function oj(e,t,n=Bj(e,t)){return class extends tj(n){static annotations(e){return oj(this.elements,this.rest,xj(this.ast,e))}static elements=[...e];static rest=[...t]}}function sj(...e){return Array.isArray(e[0])?oj(e[0],e.slice(1)):oj(e,[])}function cj(e,t){return class extends oj([],[e],t){static annotations(e){return cj(this.value,xj(this.ast,e))}static value=e}}function lj(e,t,n=nM(e,t)){return class extends tj(n){static annotations(e){return lj(this.fields,this.records,xj(this.ast,e))}static fields={...e};static records=[...t];static make=(t,n)=>{let r=rM(e,{...t});return gj(n)?r:gA(this)(r)};static pick(...t){return W(QA(e,...t))}static omit(...t){return W($A(e,...t))}}}function W(e,...t){return lj(e,t)}function uj(e,t,n){return class extends lj({},[{key:e,value:t}],n){static annotations(n){return uj(e,t,xj(this.ast,n))}static key=e;static value=t}}function dj(e,t){return class extends tj(t){static annotations(e){return dj(this.from,xj(this.ast,e))}static make=(e,t)=>gj(t)?e:gA(this)(e);static from=e}}function fj(e,t,n){return class extends tj(n){static annotations(e){return fj(this.from,this.filter,xj(this.ast,e))}static[lM]=e;static from=e;static filter=t;static make=(e,t)=>gj(t)?e:gA(this)(e)}}function pj(e,t){return n=>{function r(t,n,r){return dM(e(t,n,r),r,t)}return fj(n,r,new fk(n.ast,r,bj(t)))}}function mj(e,t,n){return class extends tj(n){static annotations(e){return mj(this.from,this.to,xj(this.ast,e))}static from=e;static to=t}}function hj(e){return fM(e,Fj,{strict:!1,decode:(e,t,n)=>nA(bg(e),()=>new Jk(n,e,`Unable to decode ${JSON.stringify(e)} into a number`)),encode:e=>$k(String(e))})}function gj(e){return Be(e)?e:e?.disableValidation??!1}var _j,vj,yj,bj,xj,Sj,Cj,wj,Tj,Ej,G,Dj,Oj,kj,Aj,jj,Mj,Nj,Pj,K,Fj,q,Ij,Lj,Rj,zj,Bj,Vj,Hj,Uj,Wj,Gj,Kj,qj,Jj,Yj,Xj,Zj,Qj,$j,eM,J,tM,nM,rM,iM,aM,oM,sM,cM,lM,uM,dM,fM,pM,mM,hM,gM,_M,vM,yM,bM,xM,SM,CM,wM,TM,EM,DM,OM,kM,AM,jM,MM,NM,PM,FM,IM,LM,RM,zM,BM,VM,HM,UM,WM,GM,KM,qM,JM,YM,XM,ZM,QM,$M,eN,tN,nN,rN,iN,aN,oN,sN,cN,lN,uN,dN,fN,pN,mN,hN,gN,_N,vN,yN,bN,xN,SN,CN,wN,TN,EN,DN,ON,kN,AN,jN,MN,NN,PN,FN,IN,LN,RN,zN,BN,VN,HN,UN,WN,GN,KN,qN,JN,YN,XN,ZN,QN,$N,eP,tP,nP,rP,iP,aP,oP,sP,cP,lP,uP,dP,fP,pP=v((()=>{Pi(),ra(),sa(),la(),XE(),Ul(),lr(),M(),Ne(),bu(),S(),Xt(),bc(),OD(),rD(),xg(),Rr(),ZA(),F(),T(),Rk(),vE(),ej(),_j=Symbol.for(`effect/Schema`),vj={_A:e=>e,_I:e=>e,_R:e=>e},yj={typeConstructor:jD,schemaId:ND,message:PD,missingMessage:FD,identifier:ID,title:LD,description:zD,examples:BD,default:VD,documentation:KD,jsonSchema:HD,arbitrary:UD,pretty:WD,equivalence:GD,concurrency:qD,batching:JD,parseIssueTitle:YD,parseOptions:XD,decodingFallback:ZD},bj=e=>{if(!e)return{};let t={...e};for(let n in yj)if(n in e){let r=yj[n];t[r]=e[n],delete t[n]}return t},xj=(e,t)=>yk(e,bj(t)),Sj=e=>String(e.ast),Cj=(e,t)=>{let n=pA(e,t);return(e,t)=>rr(n(e,t),Qk)},wj=e=>w(e,_j)&&qe(e[_j]),Tj=(e,t,n)=>ij(e,new yO(e.map(e=>e.ast),(...e)=>t.decode(...e.map(tj)),(...e)=>t.encode(...e.map(tj)),bj(n))),Ej=(e,t)=>{let n=()=>(t,n,r)=>e(t)?$k(t):eA(new Jk(r,t));return ij([],new yO([],n,n,bj(t)))},G=function(){if(Array.isArray(arguments[0])){let e=arguments[0],t=arguments[1],n=arguments[2];return Tj(e,t,n)}let e=arguments[0],t=arguments[1];return Ej(e,t)},Dj=Symbol.for(`effect/SchemaId/InstanceOf`),Oj=(e,t)=>G(t=>t instanceof e,{title:e.name,description:`an instance of ${e.name}`,pretty:()=>String,schemaId:Dj,[Dj]:{constructor:e},...t}),kj=class extends tj(EO){},Aj=class extends tj(CO){},jj=class extends tj(OO){},Mj=class extends tj(AO){},Nj=class extends tj(VO){},Pj=class extends tj(UO){},K=class extends tj(PO){},Fj=class extends tj(LO){},q=class extends tj(zO){},Ij=e=>ok.make(e.map(e=>e.ast)),Lj=e=>U(e,kj),Rj=e=>new zj(new KO(e.ast,!1),e),zj=class e{ast;from;[_j];_Token;constructor(e,t){this.ast=e,this.from=t}annotations(t){return new e(new KO(this.ast.type,this.ast.isOptional,{...this.ast.annotations,...bj(t)}),this.from)}toString(){return`${this.ast.type}${this.ast.isOptional?`?`:``}`}},Bj=(e,t)=>new JO(e.map(e=>wj(e)?new KO(e.ast,!1):e.ast),t.map(e=>wj(e)?new GO(e.ast):e.ast),!0),Vj=e=>cj(e),Hj=e=>e?`"?:"`:`":"`,Uj=class extends KO{isReadonly;defaultValue;_tag=`PropertySignatureDeclaration`;constructor(e,t,n,r,i){super(e,t,r),this.isReadonly=n,this.defaultValue=i}toString(){let e=Hj(this.isOptional),t=String(this.type);return`PropertySignature<${e}, ${t}, never, ${e}, ${t}>`}},Wj=class extends KO{isReadonly;defaultValue;constructor(e,t,n,r,i){super(e,t,r),this.isReadonly=n,this.defaultValue=i}},Gj=e=>e===void 0?`never`:Re(e)?JSON.stringify(e):String(e),Kj=class{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<${Hj(this.to.isOptional)}, ${this.to.type}, ${Gj(this.from.fromKey)}, ${Hj(this.from.isOptional)}, ${this.from.type}>`}},qj=(e,t)=>{switch(e._tag){case`PropertySignatureDeclaration`:return new Uj(e.type,e.isOptional,e.isReadonly,{...e.annotations,...t},e.defaultValue);case`PropertySignatureTransformation`:return new Kj(e.from,new Wj(e.to.type,e.to.isOptional,e.to.isReadonly,{...e.to.annotations,...t},e.to.defaultValue),e.decode,e.encode)}},Jj=Symbol.for(`effect/PropertySignature`),Yj=e=>w(e,Jj),Xj=class e{ast;[_j];[Jj]=null;_TypeToken;_Key;_EncodedToken;_HasDefault;constructor(e){this.ast=e}pipe(){return P(this,arguments)}annotations(t){return new e(qj(this.ast,bj(t)))}toString(){return String(this.ast)}},Zj=e=>new Xj(e),Qj=class e extends Xj{from;constructor(e,t){super(e),this.from=t}annotations(t){return new e(qj(this.ast,bj(t)),this.from)}},$j=e=>new Qj(new Uj(e.ast,!1,!0,{},void 0),e),eM=x(2,(e,t)=>{let n=e.ast;switch(n._tag){case`PropertySignatureDeclaration`:return Zj(new Uj(n.type,n.isOptional,n.isReadonly,n.annotations,t));case`PropertySignatureTransformation`:return Zj(new Kj(n.from,new Wj(n.to.type,n.to.isOptional,n.to.isReadonly,n.to.annotations,t),n.decode,n.encode))}}),J=e=>{let t=e.ast===EO||e.ast===OO?EO:Lj(e).ast;return new Qj(new Uj(t,!0,!0,{},void 0),e)},tM=Dk([FD]),nM=(e,t)=>{let n=Reflect.ownKeys(e),r=[];if(n.length>0){let i=[],a=[],o=[];for(let t=0;t<n.length;t++){let s=n[t],c=e[s];if(Yj(c)){let e=c.ast;switch(e._tag){case`PropertySignatureDeclaration`:{let t=e.type,n=e.isOptional,o=e.annotations;i.push(new XO(s,t,n,!0,tM(e))),a.push(new XO(s,kk(t),n,!0,o)),r.push(new XO(s,t,n,!0,o));break}case`PropertySignatureTransformation`:{let t=e.from.fromKey??s;i.push(new XO(t,e.from.type,e.from.isOptional,!0,e.from.annotations)),a.push(new XO(s,e.to.type,e.to.isOptional,!0,e.to.annotations)),o.push(new _k(t,s,e.decode,e.encode));break}}}else i.push(new XO(s,c.ast,!1,!0)),a.push(new XO(s,kk(c.ast),!1,!0)),r.push(new XO(s,c.ast,!1,!0))}if($r(o)){let e=[],n=[];for(let r of t){let{indexSignatures:t,propertySignatures:o}=Ek(r.key.ast,r.value.ast);o.forEach(e=>{i.push(e),a.push(new XO(e.name,kk(e.type),e.isOptional,e.isReadonly,e.annotations))}),t.forEach(t=>{e.push(t),n.push(new QO(t.parameter,kk(t.type),t.isReadonly))})}return new hk(new $O(i,e,{[RD]:`Struct (Encoded side)`}),new $O(a,n,{[RD]:`Struct (Type side)`}),new vk(o))}}let i=[];for(let e of t){let{indexSignatures:t,propertySignatures:n}=Ek(e.key.ast,e.value.ast);n.forEach(e=>r.push(e)),t.forEach(e=>i.push(e))}return new $O(r,i)},rM=(e,t)=>{let n=Reflect.ownKeys(e);for(let r of n){let n=e[r];if(t[r]===void 0&&Yj(n)){let e=n.ast,i=e._tag===`PropertySignatureDeclaration`?e.defaultValue:e.to.defaultValue;i!==void 0&&(t[r]=i())}}return t},iM=e=>H(e).pipe($j,eM(()=>e)),aM=(e,t)=>W({_tag:iM(e),...t}),oM=e=>uj(e.key,e.value),sM=(e,t)=>n=>{let r=br(tO(n.ast),{onNone:()=>[e],onSome:t=>[...t,e]});return dj(n,yk(n.ast,bj({[MD]:r,...t})))},cM=e=>tj(new dk(()=>e().ast)),lM=Symbol.for(`effect/SchemaId/Refine`),uM=(e,t,n)=>{if(Be(e))return e?R():z(new Jk(t,n));if(Re(e))return z(new Jk(t,n,e));if(e!==void 0){if(`_tag`in e)return z(e);let r=new Jk(t,n,e.message);return z($r(e.path)?new Hk(e.path,n,r):r)}return R()},dM=(e,t,n)=>{if(eD(e))return uM(e,t,n);if($r(e)){let r=Di(e,e=>uM(e,t,n));if($r(r))return z(r.length===1?r[0]:new Gk(t,n,r))}return R()},fM=x(e=>wj(e[0])&&wj(e[1]),(e,t,n)=>mj(e,t,new hk(e.ast,t.ast,new gk(n.decode,n.encode)))),pM=x(e=>wj(e[0])&&wj(e[1]),(e,t,n)=>fM(e,t,{strict:!0,decode:(e,t,r,i)=>$k(n.decode(e,i)),encode:(e,t,r,i)=>$k(n.encode(e,i))})),mM=Symbol.for(`effect/SchemaId/Trimmed`),hM=e=>t=>t.pipe(pj(e=>e===e.trim(),{schemaId:mM,title:`trimmed`,description:`a string with no leading or trailing whitespace`,jsonSchema:{pattern:`^\\S[\\s\\S]*\\S$|^\\S$|^$`},...e})),gM=ED,_M=(e,t)=>n=>n.pipe(pj(t=>t.length<=e,{schemaId:gM,title:`maxLength(${e})`,description:`a string at most ${e} character(s) long`,jsonSchema:{maxLength:e},...t})),vM=TD,yM=(e,t)=>n=>n.pipe(pj(t=>t.length>=e,{schemaId:vM,title:`minLength(${e})`,description:`a string at least ${e} character(s) long`,jsonSchema:{minLength:e},...t})),bM=DD,xM=(e,t)=>n=>{let r=qe(e)?Math.max(0,Math.floor(e.min)):Math.max(0,Math.floor(e)),i=qe(e)?Math.max(r,Math.floor(e.max)):r;return r===i?n.pipe(pj(e=>e.length===r,{schemaId:bM,title:`length(${r})`,description:r===1?`a single character`:`a string ${r} character(s) long`,jsonSchema:{minLength:r,maxLength:r},...t})):n.pipe(pj(e=>e.length>=r&&e.length<=i,{schemaId:bM,title:`length({ min: ${r}, max: ${i})`,description:`a string at least ${r} character(s) and at most ${i} character(s) long`,jsonSchema:{minLength:r,maxLength:i},...t}))},SM=Symbol.for(`effect/SchemaId/Pattern`),CM=(e,t)=>n=>{let r=e.source;return n.pipe(pj(t=>(e.lastIndex=0,e.test(t)),{schemaId:SM,[SM]:{regex:e},description:`a string matching the pattern ${r}`,jsonSchema:{pattern:r},...t}))},wM=Symbol.for(`effect/SchemaId/Lowercased`),TM=e=>t=>t.pipe(pj(e=>e===e.toLowerCase(),{schemaId:wM,title:`lowercased`,description:`a lowercase string`,jsonSchema:{pattern:`^[^A-Z]*$`},...e})),EM=class extends K.pipe(TM({identifier:`Lowercased`})){},DM=Symbol.for(`effect/SchemaId/Uppercased`),OM=e=>t=>t.pipe(pj(e=>e===e.toUpperCase(),{schemaId:DM,title:`uppercased`,description:`an uppercase string`,jsonSchema:{pattern:`^[^a-z]*$`},...e})),kM=class extends K.pipe(OM({identifier:`Uppercased`})){},AM=Symbol.for(`effect/SchemaId/Capitalized`),jM=e=>t=>t.pipe(pj(e=>e[0]?.toUpperCase()===e[0],{schemaId:AM,title:`capitalized`,description:`a capitalized string`,jsonSchema:{pattern:`^[^a-z]?.*$`},...e})),MM=class extends K.pipe(jM({identifier:`Capitalized`})){},NM=Symbol.for(`effect/SchemaId/Uncapitalized`),PM=e=>t=>t.pipe(pj(e=>e[0]?.toLowerCase()===e[0],{schemaId:NM,title:`uncapitalized`,description:`a uncapitalized string`,jsonSchema:{pattern:`^[^A-Z]?.*$`},...e})),FM=class extends K.pipe(PM({identifier:`Uncapitalized`})){},K.pipe(xM(1,{identifier:`Char`})),IM=e=>yM(1,{title:`nonEmptyString`,description:`a non empty string`,...e}),pM(K.annotations({description:`a string that will be converted to lowercase`}),EM,{strict:!0,decode:e=>e.toLowerCase(),encode:be}).annotations({identifier:`Lowercase`}),pM(K.annotations({description:`a string that will be converted to uppercase`}),kM,{strict:!0,decode:e=>e.toUpperCase(),encode:be}).annotations({identifier:`Uppercase`}),pM(K.annotations({description:`a string that will be converted to a capitalized format`}),MM,{strict:!0,decode:e=>hE(e),encode:be}).annotations({identifier:`Capitalize`}),pM(K.annotations({description:`a string that will be converted to an uncapitalized format`}),FM,{strict:!0,decode:e=>gE(e),encode:be}).annotations({identifier:`Uncapitalize`}),LM=class extends K.pipe(hM({identifier:`Trimmed`})){},RM=class extends LM.pipe(IM({identifier:`NonEmptyTrimmedString`})){},pM(K.annotations({description:`a string that will be trimmed`}),LM,{strict:!0,decode:e=>e.trim(),encode:be}).annotations({identifier:`Trim`}),zM=e=>e instanceof Error?e.message:String(e),K.pipe(IM({identifier:`NonEmptyString`})),BM=Symbol.for(`effect/SchemaId/UUID`),VM=/^[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,K.pipe(CM(VM,{schemaId:BM,identifier:`UUID`,jsonSchema:{format:`uuid`,pattern:VM.source},description:`a Universally Unique Identifier`,arbitrary:()=>e=>e.uuid()})),HM=Symbol.for(`effect/SchemaId/ULID`),UM=/^[0-7][0-9A-HJKMNP-TV-Z]{25}$/i,K.pipe(CM(UM,{schemaId:HM,identifier:`ULID`,description:`a Universally Unique Lexicographically Sortable Identifier`,arbitrary:()=>e=>e.ulid()})),WM=class extends Oj(URL,{typeConstructor:{_tag:`URL`},identifier:`URLFromSelf`,arbitrary:()=>e=>e.webUrl().map(e=>new URL(e)),pretty:()=>e=>e.toString()}){},fM(K.annotations({description:`a string to be decoded into a URL`}),WM,{strict:!0,decode:(e,t,n)=>tA({try:()=>new URL(e),catch:t=>new Jk(n,e,`Unable to decode ${JSON.stringify(e)} into a URL. ${zM(t)}`)}),encode:e=>$k(e.toString())}).annotations({identifier:`URL`,pretty:()=>e=>e.toString()}),GM=bD,KM=e=>t=>t.pipe(pj(Number.isFinite,{schemaId:GM,title:`finite`,description:`a finite number`,jsonSchema:{},...e})),qM=mD,JM=(e,t)=>n=>n.pipe(pj(t=>t>e,{schemaId:qM,title:`greaterThan(${e})`,description:e===0?`a positive number`:`a number greater than ${e}`,jsonSchema:{exclusiveMinimum:e},...t})),YM=hD,XM=(e,t)=>n=>n.pipe(pj(t=>t>=e,{schemaId:YM,title:`greaterThanOrEqualTo(${e})`,description:e===0?`a non-negative number`:`a number greater than or equal to ${e}`,jsonSchema:{minimum:e},...t})),ZM=vD,QM=e=>t=>t.pipe(pj(e=>Number.isSafeInteger(e),{schemaId:ZM,title:`int`,description:`an integer`,jsonSchema:{type:`integer`},...e})),$M=gD,eN=(e,t)=>n=>n.pipe(pj(t=>t<e,{schemaId:$M,title:`lessThan(${e})`,description:e===0?`a negative number`:`a number less than ${e}`,jsonSchema:{exclusiveMaximum:e},...t})),tN=_D,nN=(e,t)=>n=>n.pipe(pj(t=>t<=e,{schemaId:tN,title:`lessThanOrEqualTo(${e})`,description:e===0?`a non-positive number`:`a number less than or equal to ${e}`,jsonSchema:{maximum:e},...t})),rN=SD,iN=(e,t,n)=>r=>r.pipe(pj(n=>n>=e&&n<=t,{schemaId:rN,title:`between(${e}, ${t})`,description:`a number between ${e} and ${t}`,jsonSchema:{minimum:e,maximum:t},...n})),aN=yD,oN=e=>t=>t.pipe(pj(e=>!Number.isNaN(e),{schemaId:aN,title:`nonNaN`,description:`a number excluding NaN`,...e})),sN=e=>JM(0,{title:`positive`,...e}),cN=e=>eN(0,{title:`negative`,...e}),lN=e=>nN(0,{title:`nonPositive`,...e}),uN=e=>XM(0,{title:`nonNegative`,...e}),hj(K.annotations({description:`a string to be decoded into a number`})).annotations({identifier:`NumberFromString`}),Fj.pipe(KM({identifier:`Finite`})),dN=class extends Fj.pipe(QM({identifier:`Int`})){},Fj.pipe(oN({identifier:`NonNaN`})),Fj.pipe(sN({identifier:`Positive`})),Fj.pipe(cN({identifier:`Negative`})),Fj.pipe(lN({identifier:`NonPositive`})),fN=class extends Fj.pipe(uN({identifier:`NonNegative`})){},pN=xD,Fj.pipe(KM({schemaId:pN,identifier:`JsonNumber`})),pM(q.annotations({description:`a boolean that will be negated`}),q,{strict:!0,decode:e=>ca(e),encode:e=>ca(e)}),mN=(e,t)=>{let n=Symbol.keyFor(e);return n===void 0?eA(new Jk(t,e,`Unable to encode a unique symbol ${String(e)} into a string`)):$k(n)},hN=e=>$k(Symbol.for(e)),fM(K.annotations({description:`a string to be decoded into a globally shared symbol`}),Pj,{strict:!1,decode:e=>hN(e),encode:(e,t,n)=>mN(e,n)}).annotations({identifier:`Symbol`}),gN=CD,_N=(e,t)=>n=>n.pipe(pj(t=>t>=e,{schemaId:gN,[gN]:{min:e},title:`greaterThanOrEqualToBigInt(${e})`,description:e===0n?`a non-negative bigint`:`a bigint greater than or equal to ${e}n`,...t})),vN=wD,yN=(e,t,n)=>r=>r.pipe(pj(n=>n>=e&&n<=t,{schemaId:vN,[vN]:{min:e,max:t},title:`betweenBigInt(${e}, ${t})`,description:`a bigint between ${e}n and ${t}n`,...n})),bN=e=>_N(0n,{title:`nonNegativeBigInt`,...e}),xN=class extends fM(K.annotations({description:`a string to be decoded into a bigint`}),Nj,{strict:!0,decode:(e,t,n)=>nA(aa(e),()=>new Jk(n,e,`Unable to decode ${JSON.stringify(e)} into a bigint`)),encode:e=>$k(String(e))}).annotations({identifier:`BigInt`}){},SN=Nj.pipe(bN({identifier:`NonNegativeBigintFromSelf`})),fM(Fj.annotations({description:`a number to be decoded into a bigint`}),Nj.pipe(yN(BigInt(-(2**53-1)),BigInt(2**53-1))),{strict:!0,decode:(e,t,n)=>nA(oa(e),()=>new Jk(n,e,`Unable to decode ${e} into a bigint`)),encode:(e,t,n)=>nA(ia(e),()=>new Jk(n,e,`Unable to encode ${e}n into a number`))}).annotations({identifier:`BigIntFromNumber`}),CN=(e,t,n,r)=>sA(e,{onFailure:e=>new Gk(n,r,e),onSuccess:t}),wN=class extends G(vl,{typeConstructor:{_tag:`effect/Duration`},identifier:`DurationFromSelf`,pretty:()=>String,arbitrary:()=>e=>e.oneof(e.constant(Sl),e.bigInt({min:0n}).map(e=>Cl(e)),e.maxSafeNat().map(e=>Tl(e))),equivalence:()=>Ll}){},fM(SN.annotations({description:`a bigint to be decoded into a Duration`}),wN.pipe(pj(e=>yl(e),{description:`a finite duration`})),{strict:!0,decode:e=>$k(Cl(e)),encode:(e,t,n)=>br(Ml(e),{onNone:()=>eA(new Jk(n,e,`Unable to encode ${e} into a bigint`)),onSome:e=>$k(e)})}).annotations({identifier:`DurationFromNanos`}),TN=fN.pipe(QM()).annotations({identifier:`NonNegativeInt`}),pM(fN.annotations({description:`a non-negative number to be decoded into a Duration`}),wN,{strict:!0,decode:e=>Tl(e),encode:e=>jl(e)}).annotations({identifier:`DurationFromMillis`}),EN=aM(`Millis`,{millis:TN}),DN=aM(`Nanos`,{nanos:xN}),ON=aM(`Infinity`,{}),kN=ON.make({}),AN=U(EN,DN,ON).annotations({identifier:`DurationValue`,description:`an JSON-compatible tagged union to be decoded into a Duration`}),jN=U(sj(Rj(TN).annotations({title:`seconds`}),Rj(TN).annotations({title:`nanos`})).annotations({identifier:`FiniteHRTime`}),sj(H(-1),H(0)).annotations({identifier:`InfiniteHRTime`})).annotations({identifier:`HRTime`,description:`a tuple of seconds and nanos to be decoded into a Duration`}),MN=e=>typeof e==`object`,pM(U(AN,jN),wN,{strict:!0,decode:e=>{if(MN(e))switch(e._tag){case`Millis`:return Tl(e.millis);case`Nanos`:return Cl(e.nanos);case`Infinity`:return Sl}let[t,n]=e;return t===-1?Sl:Cl(BigInt(t)*BigInt(1e9)+BigInt(n))},encode:e=>{switch(e.value._tag){case`Millis`:return EN.make({millis:e.value.millis});case`Nanos`:return DN.make({nanos:e.value.nanos});case`Infinity`:return kN}}}).annotations({identifier:`Duration`}),NN=class extends G(Ze,{typeConstructor:{_tag:`Uint8Array`},identifier:`Uint8ArrayFromSelf`,pretty:()=>e=>`new Uint8Array(${JSON.stringify(Array.from(e))})`,arbitrary:()=>e=>e.uint8Array(),equivalence:()=>Ai(A)}){},PN=class extends Fj.pipe(iN(0,255,{identifier:`Uint8`,description:`a 8-bit unsigned integer`})){},pM(Vj(PN).annotations({description:`an array of 8-bit unsigned integers to be decoded into a Uint8Array`}),NN,{strict:!0,decode:e=>Uint8Array.from(e),encode:e=>Array.from(e)}).annotations({identifier:`Uint8Array`}),FN=Symbol.for(`effect/SchemaId/ValidDate`),IN=e=>t=>t.pipe(pj(e=>!Number.isNaN(e.getTime()),{schemaId:FN,[FN]:{noInvalidDate:!0},title:`validDate`,description:`a valid Date`,...e})),LN=pD,RN=class extends G(Qe,{typeConstructor:{_tag:`Date`},identifier:`DateFromSelf`,schemaId:LN,[LN]:{noInvalidDate:!1},description:`a potentially invalid Date instance`,pretty:()=>e=>`new Date(${JSON.stringify(e)})`,arbitrary:()=>e=>e.date({noInvalidDate:!1}),equivalence:()=>je}){},RN.pipe(IN({identifier:`ValidDateFromSelf`,description:`a valid Date instance`})),zN=class extends pM(K.annotations({description:`a string to be decoded into a Date`}),RN,{strict:!0,decode:e=>new Date(e),encode:e=>It(e)}).annotations({identifier:`DateFromString`}){},zN.pipe(IN({identifier:`Date`})),pM(Fj.annotations({description:`a number to be decoded into a Date`}),RN,{strict:!0,decode:e=>new Date(e),encode:e=>e.getTime()}).annotations({identifier:`DateFromNumber`}),BN=class extends G(e=>ME(e)&&FE(e),{typeConstructor:{_tag:`effect/DateTime.Utc`},identifier:`DateTimeUtcFromSelf`,description:`a DateTime.Utc instance`,pretty:()=>e=>e.toString(),arbitrary:()=>e=>e.date({noInvalidDate:!0}).map(e=>RE(e)),equivalence:()=>LE}){},VN=(e,t)=>tA({try:()=>zE(e),catch:()=>new Jk(t,e,`Unable to decode ${zt(e)} into a DateTime.Utc`)}),fM(Fj.annotations({description:`a number to be decoded into a DateTime.Utc`}),BN,{strict:!0,decode:(e,t,n)=>VN(e,n),encode:e=>$k(qE(e))}).annotations({identifier:`DateTimeUtcFromNumber`}),fM(RN.annotations({description:`a Date to be decoded into a DateTime.Utc`}),BN,{strict:!0,decode:(e,t,n)=>VN(e,n),encode:e=>$k(KE(e))}).annotations({identifier:`DateTimeUtcFromDate`}),fM(K.annotations({description:`a string to be decoded into a DateTime.Utc`}),BN,{strict:!0,decode:(e,t,n)=>VN(e,n),encode:e=>$k(JE(e))}).annotations({identifier:`DateTimeUtc`}),HN=()=>e=>e.integer({min:-432e5,max:504e5}).map(UE),UN=class extends G(NE,{typeConstructor:{_tag:`effect/DateTime.TimeZone.Offset`},identifier:`TimeZoneOffsetFromSelf`,description:`a TimeZone.Offset instance`,pretty:()=>e=>e.toString(),arbitrary:HN}){},pM(Fj.annotations({description:`a number to be decoded into a TimeZone.Offset`}),UN,{strict:!0,decode:e=>UE(e),encode:e=>e.offset}).annotations({identifier:`TimeZoneOffset`}),WN=()=>e=>e.constantFrom(...Intl.supportedValuesOf(`timeZone`)).map(HE),GN=class extends G(PE,{typeConstructor:{_tag:`effect/DateTime.TimeZone.Named`},identifier:`TimeZoneNamedFromSelf`,description:`a TimeZone.Named instance`,pretty:()=>e=>e.toString(),arbitrary:WN}){},fM(K.annotations({description:`a string to be decoded into a TimeZone.Named`}),GN,{strict:!0,decode:(e,t,n)=>tA({try:()=>HE(e),catch:()=>new Jk(n,e,`Unable to decode ${JSON.stringify(e)} into a TimeZone.Named`)}),encode:e=>$k(e.id)}).annotations({identifier:`TimeZoneNamed`}),KN=class extends U(UN,GN){},fM(K.annotations({description:`a string to be decoded into a TimeZone`}),KN,{strict:!0,decode:(e,t,n)=>br(WE(e),{onNone:()=>eA(new Jk(n,e,`Unable to decode ${JSON.stringify(e)} into a TimeZone`)),onSome:$k}),encode:e=>$k(GE(e))}).annotations({identifier:`TimeZone`}),qN=e=>e.oneof(HN()(e),WN()(e)),JN=class extends G(e=>ME(e)&&IE(e),{typeConstructor:{_tag:`effect/DateTime.Zoned`},identifier:`DateTimeZonedFromSelf`,description:`a DateTime.Zoned instance`,pretty:()=>e=>e.toString(),arbitrary:()=>e=>e.tuple(e.integer({min:-31536e9,max:31536e9}),qN(e)).map(([e,t])=>BE(e,{timeZone:t})),equivalence:()=>LE}){},fM(K.annotations({description:`a string to be decoded into a DateTime.Zoned`}),JN,{strict:!0,decode:(e,t,n)=>br(VE(e),{onNone:()=>eA(new Jk(n,e,`Unable to decode ${JSON.stringify(e)} into a DateTime.Zoned`)),onSome:$k}),encode:e=>$k(YE(e))}).annotations({identifier:`DateTimeZoned`}),YN=e=>e._tag===`None`?R():z(e.value),XN=(e,t)=>n=>n.oneof(t,n.record({_tag:n.constant(`None`)}),n.record({_tag:n.constant(`Some`),value:e(n)})).map(YN),ZN=e=>br({onNone:()=>`none()`,onSome:t=>`some(${e(t)})`}),QN=e=>(t,n,r)=>_r(t)?vr(t)?$k(R()):CN(e(t.value,n),z,r,t):eA(new Jk(r,t)),$N=e=>G([e],{decode:e=>QN(mA(e)),encode:e=>QN(hA(e))},{typeConstructor:{_tag:`effect/Option`},pretty:ZN,arbitrary:XN,equivalence:Nr}),eP=e=>$N(e).annotations({description:`Option<${Sj(e)}>`}),pM(K,eP(RM),{strict:!0,decode:e=>Mr(z(e.trim()),_E),encode:e=>xr(e,()=>``)}),tP=()=>e=>`BigDecimal(${Qi(Wi(e))})`,nP=()=>e=>e.tuple(e.bigInt(),e.integer({min:-18,max:18})).map(([e,t])=>zi(e,t)),rP=class extends G(Ri,{typeConstructor:{_tag:`effect/BigDecimal`},identifier:`BigDecimalFromSelf`,pretty:tP,arbitrary:nP,equivalence:()=>qi}){},fM(K.annotations({description:`a string to be decoded into a BigDecimal`}),rP,{strict:!0,decode:(e,t,n)=>Zi(e).pipe(br({onNone:()=>eA(new Jk(n,e,`Unable to decode ${JSON.stringify(e)} into a BigDecimal`)),onSome:e=>$k(Wi(e))})),encode:e=>$k(Qi(Wi(e)))}).annotations({identifier:`BigDecimal`}),pM(Fj.annotations({description:`a number to be decoded into a BigDecimal`}),rP,{strict:!0,decode:e=>Yi(e),encode:e=>ea(e)}).annotations({identifier:`BigDecimalFromNumber`}),iP=U(W({_tag:H(`None`)}).annotations({identifier:`FiberIdNoneEncoded`}),W({_tag:H(`Runtime`),id:dN,startTimeMillis:dN}).annotations({identifier:`FiberIdRuntimeEncoded`}),W({_tag:H(`Composite`),left:cM(()=>iP),right:cM(()=>iP)}).annotations({identifier:`FiberIdCompositeEncoded`})).annotations({identifier:`FiberIdEncoded`}),aP=e=>e.letrec(t=>({None:e.record({_tag:e.constant(`None`)}),Runtime:e.record({_tag:e.constant(`Runtime`),id:e.integer(),startTimeMillis:e.integer()}),Composite:e.record({_tag:e.constant(`Composite`),left:t(`FiberId`),right:t(`FiberId`)}),FiberId:e.oneof(t(`None`),t(`Runtime`),t(`Composite`))})).FiberId.map(cP),oP=e=>{switch(e._tag){case`None`:return`FiberId.none`;case`Runtime`:return`FiberId.runtime(${e.id}, ${e.startTimeMillis})`;case`Composite`:return`FiberId.composite(${oP(e.right)}, ${oP(e.left)})`}},sP=class extends G(_u,{typeConstructor:{_tag:`effect/FiberId`},identifier:`FiberIdFromSelf`,pretty:()=>oP,arbitrary:()=>aP}){},cP=e=>{switch(e._tag){case`None`:return mu;case`Runtime`:return hu(e.id,e.startTimeMillis);case`Composite`:return gu(cP(e.left),cP(e.right))}},lP=e=>{switch(e._tag){case`None`:return{_tag:`None`};case`Runtime`:return{_tag:`Runtime`,id:e.id,startTimeMillis:e.startTimeMillis};case`Composite`:return{_tag:`Composite`,left:lP(e.left),right:lP(e.right)}}},pM(iP,sP,{strict:!0,decode:e=>cP(e),encode:e=>lP(e)}).annotations({identifier:`FiberId`}),pM(Mj,Mj,{strict:!0,decode:e=>{if(qe(e)&&`message`in e&&typeof e.message==`string`){let t=Error(e.message,{cause:e});return`name`in e&&typeof e.name==`string`&&(t.name=e.name),t.stack=`stack`in e&&typeof e.stack==`string`?e.stack:``,t}return mc(e)},encode:e=>e instanceof Error?{name:e.name,message:e.message}:mc(e)}).annotations({identifier:`Defect`}),pM(Mj,q,{strict:!0,decode:e=>Le(e),encode:be}).annotations({identifier:`BooleanFromUnknown`}),pM(H(`true`,`false`).annotations({description:`a string to be decoded into a boolean`}),q,{strict:!0,decode:e=>e===`true`,encode:e=>e?`true`:`false`}).annotations({identifier:`BooleanFromString`}),uP=aM(`symbol`,{key:K}).annotations({description:`an object to be decoded into a globally shared symbol`}),dP=fM(uP,Pj,{strict:!0,decode:e=>hN(e.key),encode:(e,t,n)=>aA(mN(e,n),e=>uP.make({key:e}))}),fP=class extends U(K,Fj,dP).annotations({identifier:`PropertyKey`}){},W({_tag:$j(H(`Pointer`,`Unexpected`,`Missing`,`Composite`,`Refinement`,`Transformation`,`Type`,`Forbidden`)).annotations({description:`The tag identifying the type of parse issue`}),path:$j(Vj(fP)).annotations({description:`The path to the property where the issue occurred`}),message:$j(K).annotations({description:`A descriptive message explaining the issue`})}).annotations({identifier:`ArrayFormatterIssue`,description:`Represents an issue returned by the ArrayFormatter formatter`})}));function mP(e,t){return Cj(e,hP)(t)}var hP,gP=v((()=>{pP(),hP={onExcessProperty:`error`}}));function _P(e,t){if(typeof t!=`string`)return;let n=e.lastIndexOf(`@`);if(n<=0)return;let r=e.slice(0,n),i=e.slice(n+1);if(!(!bP(r)||!yP(i)||t!==i))return{pluginName:r,marketplaceName:i,canonicalPluginId:`${r}@openai-curated`}}function vP(e){let t=e.lastIndexOf(`@`);if(t<=0)return;let n=e.slice(0,t),r=e.slice(t+1);return bP(n)&&yP(r)?`${n}@openai-curated`:void 0}function yP(e){return wP.includes(e)}function bP(e){return TP.includes(e)}function xP(e,t){let n=t??AP;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 SP(e,t=[]){let n=[],r=new Set;for(let t of kP)if(e[t])for(let e of OP[t].pluginIds)r.has(e)||(r.add(e),n.push(e));for(let e of t)r.has(e)||(r.add(e),n.push(e));return n}var CP,wP,TP,EP,DP,OP,kP,AP,jP=v((()=>{pP(),CP=H(`computer_use`,`work`,`frontend`,`security`),H(`computer_use`,`work`,`frontend`,`security`),H(`installed`,`disabled`,`missing`,`uncertain`),H(`healthy`,`missing`,`disabled`,`uncertain`),wP=Object.freeze([`openai-curated`,`openai-curated-remote`]),TP=Object.freeze([`build-web-apps`,`codex-security`]),EP=Object.freeze({coding:!0,computer_use:!1,work:!1,frontend:!0,security:!0}),DP={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:EP.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:EP.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:EP.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:EP.computer_use,migrationKey:`computer_use`,semanticSkillIds:[`computer-use:computer-use`],ownership:`shared-preserve`}},OP=Object.freeze(DP),kP=Object.freeze([`computer_use`,`work`,`frontend`,`security`]),AP=Object.freeze({computer_use:EP.computer_use,work:EP.work,frontend:EP.frontend,security:EP.security})}));function MP(e){return W({identifier:H(e),label:K,requiresRootApproval:q})}function NP(e){let t=e.map(e=>e.label),n=t.at(-1);return n===void 0?``:t.length===1?n:`${t.slice(0,-1).join(`, `)}, and ${n}`}function PP(e){return e.length===0?e:`${e[0]?.toUpperCase()??``}${e.slice(1)}`}var FP,IP,LP,RP,zP,BP=v((()=>{pP(),me(),FP=H(`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`),W({identifier:FP,label:K,requiresRootApproval:q}),W({localRepositoryEdit:MP(`local.repository.edit`),localRepositoryCheck:MP(`local.repository.check`),localRepositoryLint:MP(`local.repository.lint`),localRepositoryFormat:MP(`local.repository.format`),localRepositoryCommit:MP(`local.repository.commit`),externalRead:MP(`external.read`),specialistDispatch:MP(`specialist.dispatch`),versionControlServerMutation:MP(`vcs.server.mutation`),versionControlServerCiTrigger:MP(`vcs.server.ci-trigger`),unknownEffect:MP(`unknown.effect`)}),IP={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}},ue(IP),H(`never`,`root`),LP=Object.values(IP),RP=LP.filter(e=>!e.requiresRootApproval),zP=LP.filter(e=>e.requiresRootApproval),Object.freeze({noRootApproval:`${PP(NP(RP))} actions do not require Root approval.`,rootApproval:`${PP(NP(zP))} require Root approval.`})}));function VP(e){let t=mP(WP,e);return er(t)?ge(_e(`sha256 digest`,t.left)):he(t.right)}var HP,UP,WP,GP=v((()=>{lr(),pP(),ve(),gP(),HP=K.pipe(CM(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u)),UP=K.pipe(CM(/^[0-9a-f]{64}$/u)),HP.pipe(sM(`RunId`)),HP.pipe(sM(`ProjectId`)),HP.pipe(sM(`TrustId`)),WP=UP.pipe(sM(`Sha256Digest`)),W({run_id:HP,objective_lineage:HP,parent_run_id:J(U(HP,Aj))}),W({project_id:HP,trust_id:HP,trust_digest:UP}),W({project_id:HP,project_digest:UP}),K.pipe(CM(/^state-[0-9]+\.[0-9]+$/u))}));function KP(e){return e===`Go`?`go`:e}function qP(e){return typeof e==`string`&&aF.has(e)}function JP(e){if(typeof e!=`object`||!e||!(`role`in e)||!(`task`in e))return!1;let t=e.role,n=e.task;return!qP(t)||typeof n!=`string`?!1:iF.get(t)?.tasks.some(e=>e.name===n)===!0}function YP(e,t){return typeof t==`string`&&iF.get(e)?.tasks.some(e=>e.name===t)===!0}function XP(e){return typeof e==`string`&&sF.has(e)}function ZP(e){let t=`${e.role}.${e.task}`;if(!lF.has(t))throw Error(`Unknown native specialist agent type.`);return t}function QP(e){let t=iF.get(e.role)?.tasks.find(t=>t.name===e.task);if(t===void 0)throw Error(`Unknown specialist task policy.`);return t.instruction}function $P(e){let t=iF.get(e.role)?.tasks.find(t=>t.name===e.task);if(t===void 0)throw Error(`Unknown specialist task policy.`);return t.description}var eF,tF,nF,rF,iF,aF,oF,sF,cF,lF,uF,dF,fF,pF,mF=v((()=>{pP(),me(),eF=H(`go`,`plus-low`,`plus`,`plus-high`,`pro-5x`,`pro-20x`),tF=H(`Go`),U(eF,tF),nF=H(`standard`,`fast`,`fast-all`),H(`low`,`medium`,`high`,`xhigh`,`max`),rF=[{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 assigned repository scope; Git/VCS 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 assigned current sources without repository mutation; Git/VCS 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 assigned seam; Git/VCS and material choices remain Root-only.`,evidence:`Return changed files, verification results, and remaining risk.`,completion:`Finish the assigned seam with proportional proof or an exact blocker.`,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; 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.`,permissions:{network:!1,write:!0}}],ue(rF),iF=new Map(rF.map(e=>[e.role,e])),aF=new Set(rF.map(e=>e.role)),oF=rF.flatMap(e=>e.tasks.map(t=>`${e.role}:${t.name}`)),sF=new Set(oF),cF=oF.map(e=>e.replace(`:`,`.`)),lF=new Set(cF),uF=G(qP),G(e=>YP(`Explorer`,e)),G(e=>YP(`Librarian`,e)),G(e=>YP(`Worker`,e)),G(e=>YP(`Reviewer`,e)),dF=G(JP),fF=Object.freeze(oF.filter(e=>XP(e))),G(XP),pF=Object.freeze(cF.filter(e=>lF.has(e))),G(e=>typeof e==`string`&&lF.has(e)),W({plan:eF,service_tier:J(nF)})}));function hF(e,t){return new y(`invalid_canonical_value`,`Cannot canonicalize ${e}: ${t}.`,{path:e,reason:t})}function gF(e,t,n){if(e===null)return`null`;switch(typeof e){case`string`:{let n=JSON.stringify(e);if(n===void 0)throw hF(t,`invalid string`);return n}case`boolean`:return e?`true`:`false`;case`number`:{if(!Number.isFinite(e))throw hF(t,`non-finite number`);let n=JSON.stringify(e);if(n===void 0)throw hF(t,`invalid number`);return n}case`undefined`:throw hF(t,`undefined is not JSON`);case`bigint`:throw hF(t,`bigint is not JSON`);case`function`:throw hF(t,`function is not JSON`);case`symbol`:throw hF(t,`symbol is not JSON`)}if(n.has(e))throw hF(t,`cyclic value`);n.add(e);try{if(Array.isArray(e)){for(let n of Object.getOwnPropertySymbols(e))throw hF(t,`symbol property ${String(n)}`);let r=e,i=[];for(let e=0;e<r.length;e+=1){let a=Object.getOwnPropertyDescriptor(r,String(e));if(!a||!a.enumerable||!(`value`in a))throw hF(`${t}[${e}]`,`sparse or accessor array item`);i.push(gF(a.value,`${t}[${e}]`,n))}for(let e of Object.getOwnPropertyNames(r)){if(e===`length`)continue;let n=Number(e);if(!Number.isInteger(n)||n<0||n>=r.length||String(n)!==e)throw hF(t,`non-index array property ${e}`);let i=Object.getOwnPropertyDescriptor(r,e);if(!i||!i.enumerable||!(`value`in i))throw hF(`${t}[${n}]`,`non-enumerable or accessor array item`)}return`[${i.join(`,`)}]`}let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)throw hF(t,`only plain objects are supported`);for(let n of Object.getOwnPropertySymbols(e))throw hF(t,`symbol property ${String(n)}`);for(let n of Object.getOwnPropertyNames(e)){let r=Object.getOwnPropertyDescriptor(e,n);if(!r||!r.enumerable||!(`value`in r))throw hF(`${t}.${n}`,`non-enumerable or accessor property`)}let i=[];for(let r of Object.keys(e).sort()){let a=Object.getOwnPropertyDescriptor(e,r);if(!a||!(`value`in a))throw hF(`${t}.${r}`,`accessor property`);i.push(`${JSON.stringify(r)}:${gF(a.value,`${t}.${r}`,n)}`)}return`{${i.join(`,`)}}`}finally{n.delete(e)}}function _F(e){return gF(e,`$`,new Set)}function vF(e){return new TextEncoder().encode(_F(e))}function yF(e,t){if(e.length===0||e.includes(`\0`))throw new y(`invalid_digest_domain`,`Digest domains must be non-empty and NUL-free.`,{field:`domain`});let n=new TextEncoder().encode(`holycodex-sha256\0`),r=new TextEncoder().encode(e),i=n.byteLength+8+r.byteLength;for(let e of t){if(e.byteLength>4294967295||i>4294967291-e.byteLength)throw new y(`invalid_digest_domain`,`Digest input is too large.`);i+=4+e.byteLength}let a=new Uint8Array(i),o=new DataView(a.buffer);a.set(n,0);let s=n.byteLength;o.setUint32(s,r.byteLength,!1),s+=4,a.set(r,s),s+=r.byteLength,o.setUint32(s,t.length,!1),s+=4;for(let e of t)o.setUint32(s,e.byteLength,!1),s+=4,a.set(e,s),s+=e.byteLength;return a}function bF(e){let t=``;for(let n of e)t+=n.toString(16).padStart(2,`0`);return t}async function xF(e,t){let n=globalThis.crypto?.subtle;if(!n)throw new y(`crypto_unavailable`,`The standards-based crypto API is unavailable.`);let r=await n.digest(`SHA-256`,SF(yF(e,t)));return bF(new Uint8Array(r))}function SF(e){let t=new Uint8Array(e.byteLength);return t.set(e),t}var CF=v((()=>{ve(),GP()}));function wF(e){try{return _F(e)!==void 0}catch{return!1}}function TF(e){let t=mP(JF,e);return er(t)?ge(_e(`CLI envelope`,t.left)):he(t.right)}var EF,DF,OF,kF,AF,jF,MF,NF,PF,FF,IF,LF,RF,zF,BF,VF,HF,UF,WF,GF,KF,qF,JF,YF=v((()=>{lr(),pP(),CF(),jP(),me(),ve(),GP(),mF(),gP(),EF=H(`blocked`,`completed`,`failed`,`partial`),DF=U(H(`high`,`max`,`xhigh`),Aj),OF=G(e=>wF(e)),kF=G(e=>de(e)&&!Array.isArray(e)&&wF(e)),W({blocked:q,changed_files:Vj(K),confidence:Fj,context_owner:U(K,Aj),material_findings:Vj(K),needs_more_context:q,needs_root_decision:q,needs_verification:q,relevant_files:Vj(K),remaining_risk:Vj(K),reuse_recommended:q,status:EF,suggested_followup:U(K,Aj),suggested_luna_effort:DF,suggested_specialist:U(uF,Aj),verification:Vj(K),verification_passed:q}),AF=`holycodex-specialist-outcome-2`,jF=K.pipe(yM(1)),MF={protocol_version:H(AF),route:dF,evidence:Vj(jF)},W(MF),NF=W({...MF,status:H(`completed`),summary:jF}),PF=W({...MF,status:H(`blocked`),reason:jF,needs_root_decision:q}),FF=W({...MF,status:H(`partial`),summary:jF,completed:Vj(jF),remaining:Vj(jF),needs_root_decision:q}),IF=W({...MF,status:H(`failed`),error:jF}),U(NF,PF,FF,IF),LF={protocol_version:H(AF),capability:CP,route:U(dF,Aj),evidence:Vj(jF),data:OF},RF=W({...LF,status:H(`completed`),summary:jF}),zF=W({...LF,status:H(`blocked`),reason:jF,needs_root_decision:q}),BF=W({...LF,status:H(`partial`),summary:jF,completed:Vj(jF),remaining:Vj(jF),needs_root_decision:q}),VF=W({...LF,status:H(`failed`),error:jF}),U(RF,zF,BF,VF),HF=Vj(K),UF=K.pipe(CM(/^[a-z][a-z0-9-]*(?: [a-z][a-z0-9-]*)*$/u)),WF=H(fe),GF=W({code:HP,message:K,details:kF}),KF=W({schema_version:WF,ok:H(!0),command:UF,data:OF,warnings:HF}),qF=W({schema_version:WF,ok:H(!1),command:UF,error:GF,warnings:HF}),JF=U(KF,qF)}));function XF(e,t,n){return{key:`${e}:${t}`,role:e,task:t,model:`Luna`,effort:n}}function ZF(e){let t=iI.get(e);if(t===void 0)throw new y(`catalog_invalid`,`A specialist plan has no route effort policy.`,{plan:e});return rF.flatMap(n=>n.tasks.map(r=>{let i=`${n.role}:${r.name}`,a=t.efforts[i];if(a===void 0)throw new y(`catalog_invalid`,`A route effort policy is incomplete.`,{plan:e,route:i});return XF(n.role,r.name,a)}))}function QF(e){return{...e,specialistModel:`Luna`,defaultServiceTier:`standard`,routes:ZF(e.name)}}function $F(e){let t=[`go`,`plus-low`,`plus`,`plus-high`,`pro-5x`,`pro-20x`];if(e.length!==t.length)throw new y(`catalog_invalid`,`The plan catalog has an invalid size.`);for(let n=0;n<t.length;n+=1){let r=e[n],i=t[n];if(!r||r.name!==i)throw new y(`catalog_invalid`,`The plan catalog order is invalid.`,{index:n});let a=r.name===`go`?{model:`Terra`,effort:`high`}:r.name===`plus-low`?{model:`Sol`,effort:`low`}:r.name===`plus`?{model:`Sol`,effort:`medium`}:r.name===`pro-20x`?{model:`Sol`,effort:`xhigh`}:{model:`Sol`,effort:`high`};if(r.root.model!==a.model||r.root.effort!==a.effort)throw new y(`catalog_invalid`,`A plan has an invalid Root route.`,{plan:r.name});if(r.specialistModel!==`Luna`||r.defaultServiceTier!==`standard`)throw new y(`catalog_invalid`,`A plan has an invalid specialist policy.`,{plan:r.name});if(r.routes.length!==fF.length)throw new y(`catalog_invalid`,`A specialist plan is incomplete.`,{plan:r.name});let o=new Set;for(let e of r.routes){if(o.has(e.key)||!tI.has(e.key)||e.model!==`Luna`||`${e.role}:${e.task}`!==e.key)throw new y(`catalog_invalid`,`A plan contains an invalid route.`,{plan:r.name});o.add(e.key)}if(o.size!==fF.length)throw new y(`catalog_invalid`,`A plan is missing a specialist route.`,{plan:r.name})}let n=e[0]?.routes,r=e[1]?.routes;if(!n||!r||n.length!==r.length||n.some((e,t)=>e.key!==r[t]?.key||e.model!==r[t]?.model||e.effort!==r[t]?.effort))throw new y(`catalog_invalid`,`go must use the plus-low specialist route matrix.`);let i=e;for(let e=0;e<fF.length;e+=1){let t=-1;for(let n of i){let r=n.routes[e];if(!r||nI[r.effort]<t)throw new y(`catalog_invalid`,`Plan route effort is not monotonic.`,{route:fF[e]??`unknown`});t=nI[r.effort]}}}function eI(e){let t=mP(eF,e);if(er(t))return ge(new y(`invalid_plan`,`Unknown plan selection.`,{field:`plan`},{cause:t.left}));let n=sI.get(t.right);return n?he(n):ge(new y(`invalid_plan`,`Unknown plan selection.`,{plan:t.right}))}var tI,nI,rI,iI,aI,oI,sI,cI,lI=v((()=>{lr(),me(),ve(),mF(),gP(),tI=new Set(fF),nI={low:0,medium:1,high:2,xhigh:3,max:4},rI=[{plan:`plus-low`,rationale:`Preserve the approved plus-low route effort policy.`,efforts:{"Explorer:lookup":`medium`,"Explorer:trace":`high`,"Librarian:lookup":`medium`,"Librarian:research":`high`,"Worker:mechanical":`high`,"Worker:implementation":`high`,"Worker:integration":`xhigh`,"Worker:operations":`high`,"Reviewer:plan":`high`,"Reviewer:code":`xhigh`,"Reviewer:artifact":`high`}},{plan:`plus`,rationale:`Preserve the approved plus route effort policy.`,efforts:{"Explorer:lookup":`medium`,"Explorer:trace":`high`,"Librarian:lookup":`medium`,"Librarian:research":`high`,"Worker:mechanical":`high`,"Worker:implementation":`xhigh`,"Worker:integration":`xhigh`,"Worker:operations":`high`,"Reviewer:plan":`high`,"Reviewer:code":`xhigh`,"Reviewer:artifact":`high`}},{plan:`plus-high`,rationale:`Preserve the approved plus-high route effort policy.`,efforts:{"Explorer:lookup":`medium`,"Explorer:trace":`xhigh`,"Librarian:lookup":`medium`,"Librarian:research":`xhigh`,"Worker:mechanical":`high`,"Worker:implementation":`xhigh`,"Worker:integration":`max`,"Worker:operations":`xhigh`,"Reviewer:plan":`xhigh`,"Reviewer:code":`max`,"Reviewer:artifact":`xhigh`}},{plan:`pro-5x`,rationale:`Preserve the approved pro-5x route effort policy.`,efforts:{"Explorer:lookup":`high`,"Explorer:trace":`xhigh`,"Librarian:lookup":`high`,"Librarian:research":`xhigh`,"Worker:mechanical":`high`,"Worker:implementation":`max`,"Worker:integration":`max`,"Worker:operations":`xhigh`,"Reviewer:plan":`xhigh`,"Reviewer:code":`max`,"Reviewer:artifact":`xhigh`}},{plan:`pro-20x`,rationale:`Preserve the approved pro-20x route effort policy.`,efforts:{"Explorer:lookup":`high`,"Explorer:trace":`xhigh`,"Librarian:lookup":`high`,"Librarian:research":`max`,"Worker:mechanical":`xhigh`,"Worker:implementation":`max`,"Worker:integration":`max`,"Worker:operations":`xhigh`,"Reviewer:plan":`max`,"Reviewer:code":`max`,"Reviewer:artifact":`max`}}],ue(rI),iI=new Map(rI.map(e=>[e.plan,e])),aI=[{name:`go`,root:{model:`Terra`,effort:`high`},specialistModel:`Luna`,defaultServiceTier:`standard`,routes:ZF(`plus-low`)},QF({name:`plus-low`,root:{model:`Sol`,effort:`low`}}),QF({name:`plus`,root:{model:`Sol`,effort:`medium`}}),QF({name:`plus-high`,root:{model:`Sol`,effort:`high`}}),QF({name:`pro-5x`,root:{model:`Sol`,effort:`high`}}),QF({name:`pro-20x`,root:{model:`Sol`,effort:`xhigh`}})],$F(aI),ue(aI),oI=aI,sI=new Map,cI=new Map;for(let e of oI){sI.set(e.name,e);let t=new Map;for(let n of e.routes)t.set(n.key,n);cI.set(e.name,t)}})),uI=v((()=>{me(),ve(),gP(),jP(),BP(),GP(),mF(),YF(),lI(),CF()}));uI();const dI=Object.freeze([{name:`yes`,kind:`boolean`,usage:`--yes`,description:`Confirm installation.`},{name:`plan`,kind:`value`,usage:`--plan <go|plus-low|plus|plus-high|pro-5x|pro-20x>`,description:`Select routing (default: plus).`},{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.`}]),fI=new Set([`codex-home`,`plan`,`tier`,`add-plugin`]),pI=new Set([`yes`,`json`,`verbose`,`dry-run`,`computer-use`,`no-computer-use`,`work`,`no-work`,`frontend`,`no-frontend`,`security`,`no-security`]);var mI=class extends Error{code;details;constructor(e,t,n={}){super(t),this.name=`ArgumentError`,this.code=e,this.details=n}};function hI(e){if(e.length===0)throw new mI(`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 hI([`version`,...e.slice(1)]);let t=e[0];if(t!==`install`&&t!==`doctor`&&t!==`remove`&&t!==`version`)throw new mI(`unknown_command`,`Unknown command.`,{command:t??``});let n=[],r={};for(let t=1;t<e.length;t+=1){let i=e[t];if(i===void 0)continue;if(i===`-`||!i.startsWith(`-`)){n.push(i);continue}if(!i.startsWith(`--`)||i===`--`)throw new mI(`invalid_argument`,`Short options are not supported.`,{option:i});let a=i.slice(2),o=a.indexOf(`=`),s=o>=0?a.slice(0,o):a,c=o>=0?a.slice(o+1):void 0,l=s.replaceAll(`_`,`-`);if(!fI.has(l)&&!pI.has(l))throw new mI(`invalid_argument`,`Unknown option.`,{option:`--${s}`});if(fI.has(l)){let n=c??e[t+1];if(n===void 0||n.length===0||n.startsWith(`-`))throw new mI(`invalid_argument`,`Option --${s} requires a value.`,{option:`--${s}`});if(c===void 0&&(t+=1),l===`add-plugin`){let e=r[l];r[l]=Array.isArray(e)?[...e,n]:[n]}else{if(r[l]!==void 0)throw new mI(`invalid_argument`,`Option --${s} may only be supplied once.`,{option:`--${s}`});r[l]=n}continue}if(c!==void 0&&c!==`true`&&c!==`false`)throw new mI(`invalid_argument`,`Option --${s} is boolean.`,{option:`--${s}`});if(r[l]!==void 0)throw new mI(`invalid_argument`,`Option --${s} may only be supplied once.`,{option:`--${s}`});r[l]=c!==`false`}return gI(t,n,r),{command:t,positionals:n,options:r}}function gI(e,t,n){let r=_I(e);for(let t of Object.keys(n))if(!r.has(t))throw new mI(`invalid_argument`,`Option --${t} is not valid for ${e}.`,{option:`--${t}`});let i=e===`version`?{min:0,max:1}:{min:0,max:0};if(t.length<i.min||t.length>i.max)throw new mI(`invalid_argument`,`Invalid positional arguments for ${e}.`);let a=n.plan;if(typeof a==`string`&&!eI(a).ok)throw new mI(`invalid_argument`,`The plan is not supported.`,{plan:a});let o=n.tier;if(typeof o==`string`&&o!==`standard`&&o!==`fast`&&o!==`fast-all`)throw new mI(`invalid_argument`,`The tier is not supported.`,{tier:o});for(let[e,t]of[[`computer-use`,`no-computer-use`],[`work`,`no-work`],[`frontend`,`no-frontend`],[`security`,`no-security`]])if(n[e]!==void 0&&n[t]!==void 0)throw new mI(`invalid_argument`,`Conflicting --${e} and --${t} options.`);if(e===`install`&&n.yes===!1)throw new mI(`invalid_argument`,`--yes cannot be false.`);if(e!==`install`&&Object.keys(n).some(e=>[`plan`,`tier`,`work`,`no-work`,`frontend`,`no-frontend`,`security`,`no-security`,`computer-use`,`no-computer-use`,`add-plugin`].includes(e)))throw new mI(`invalid_argument`,`Installation options are not valid for ${e}.`)}function _I(e){switch(e){case`install`:return new Set([...dI.map(e=>e.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}}const vI=`Install HolyCodex through Codex native plugin management.
25
+ `)}`:this.toString();else if("Bun"in globalThis)return Nn(ya(this),{renderErrorCause:!0});return this}}return Object.assign(e.prototype,tm),e}(),Xv=Symbol.for("effect/Cause/errors/RuntimeException"),oF=Ei({[Xv]:Xv},"RuntimeException"),zh=Symbol.for("effect/Cause/errors/InterruptedException"),NK=Ei({[zh]:zh},"InterruptedException"),Qv=Symbol.for("effect/Cause/errors/IllegalArgument"),iF=Ei({[Qv]:Qv},"IllegalArgumentException"),eT=Symbol.for("effect/Cause/errors/NoSuchElement"),xc=Ei({[eT]:eT},"NoSuchElementException"),tT=Symbol.for("effect/Cause/errors/InvalidPubSubCapacityException"),FK=Ei({[tT]:tT},"InvalidPubSubCapacityException"),nT=Symbol.for("effect/Cause/errors/ExceededCapacityException"),LK=Ei({[nT]:nT},"ExceededCapacityException"),rT=Symbol.for("effect/Cause/errors/Timeout"),DK=Ei({[rT]:rT},"TimeoutException"),oT=Symbol.for("effect/Cause/errors/UnknownException"),aF=function(){class e extends yp{_tag="UnknownException";error;constructor(t,n){super(n??"An unknown error occurred",{cause:t});this.error=t}}return Object.assign(e.prototype,{[oT]:oT,name:"UnknownException"}),e}(),ET=d(2,(e,t)=>{switch(e._tag){case jt:return ve(e.effect_instruction_i0);case Vt:return Ie(t)}}),tp=d(2,(e,t)=>{switch(e._tag){case jt:return ve(e.effect_instruction_i0);case Vt:return Ie(t(e.effect_instruction_i0))}}),xp=d(2,(e,{onFailure:t,onSuccess:n})=>{switch(e._tag){case jt:return t(e.effect_instruction_i0);case Vt:return n(e.effect_instruction_i0)}}),xn=Ie(void 0),fg=d(3,(e,t,{onFailure:n,onSuccess:r})=>{switch(e._tag){case jt:switch(t._tag){case Vt:return ve(e.effect_instruction_i0);case jt:return ve(n(e.effect_instruction_i0,t.effect_instruction_i0))}case Vt:switch(t._tag){case Vt:return Ie(r(e.effect_instruction_i0,t.effect_instruction_i0));case jt:return ve(t.effect_instruction_i0)}}}),lF=xt((e)=>Ie(e.currentContext)),uF=d(2,(e,t)=>ko(Ti,t)(e)),mg=d(2,(e,t)=>Ri((n)=>uF(e,t(n))))});var kT,CT;var AT=x(()=>{Sa();kT=Ew,CT=Nn});var wp="And",vp="Or",Tp="InvalidData",Ep="MissingData",Op="SourceUnavailable",Rp="Unsupported";var fF="effect/ConfigError",PT,Ma,kp=(e,t)=>{let n=Object.create(Ma);return n._op=wp,n.left=e,n.right=t,Object.defineProperty(n,"toString",{enumerable:!1,value(){return`${this.left} and ${this.right}`}}),Object.defineProperty(n,"message",{enumerable:!1,get(){return this.toString()}}),n},Cp=(e,t)=>{let n=Object.create(Ma);return n._op=vp,n.left=e,n.right=t,Object.defineProperty(n,"toString",{enumerable:!1,value(){return`${this.left} or ${this.right}`}}),Object.defineProperty(n,"message",{enumerable:!1,get(){return this.toString()}}),n},hg=(e,t,n={pathDelim:"."})=>{let r=Object.create(Ma);return r._op=Tp,r.path=e,r.message=t,Object.defineProperty(r,"toString",{enumerable:!1,value(){return`(Invalid data at ${g(this.path,Ir(n.pathDelim))}: "${this.message}")`}}),r},or=(e,t,n={pathDelim:"."})=>{let r=Object.create(Ma);return r._op=Ep,r.path=e,r.message=t,Object.defineProperty(r,"toString",{enumerable:!1,value(){return`(Missing data at ${g(this.path,Ir(n.pathDelim))}: "${this.message}")`}}),r},gg=(e,t,n,r={pathDelim:"."})=>{let o=Object.create(Ma);return o._op=Op,o.path=e,o.message=t,o.cause=n,Object.defineProperty(o,"toString",{enumerable:!1,value(){return`(Source unavailable at ${g(this.path,Ir(r.pathDelim))}: "${this.message}")`}}),o},yg=(e,t,n={pathDelim:"."})=>{let r=Object.create(Ma);return r._op=Rp,r.path=e,r.message=t,Object.defineProperty(r,"toString",{enumerable:!1,value(){return`(Unsupported operation at ${g(this.path,Ir(n.pathDelim))}: "${this.message}")`}}),r},Co,IT;var xg=x(()=>{Be();tn();j();PT=Symbol.for(fF),Ma={_tag:"ConfigError",[PT]:PT},Co=d(2,(e,t)=>{switch(e._op){case wp:return kp(Co(e.left,t),Co(e.right,t));case vp:return Cp(Co(e.left,t),Co(e.right,t));case Tp:return hg([...t,...e.path],e.message);case Ep:return or([...t,...e.path],e.message);case Op:return gg([...t,...e.path],e.message,e.cause);case Rp:return yg([...t,...e.path],e.message)}}),IT=d(3,(e,t,n)=>{let r=[e],o=[];while(r.length>0){let a=r.pop();switch(a._op){case wp:{r.push(a.right),r.push(a.left),o.push(W({_op:"AndCase"}));break}case vp:{r.push(a.right),r.push(a.left),o.push(W({_op:"OrCase"}));break}case Tp:{o.push(Q(n.invalidDataCase(t,a.path,a.message)));break}case Ep:{o.push(Q(n.missingDataCase(t,a.path,a.message)));break}case Op:{o.push(Q(n.sourceUnavailableCase(t,a.path,a.message,a.cause)));break}case Rp:{o.push(Q(n.unsupportedCase(t,a.path,a.message)));break}}}let i=[];while(o.length>0){let a=o.pop();switch(a._op){case"Left":{switch(a.left._op){case"AndCase":{let s=i.pop(),c=i.pop(),l=n.andCase(t,s,c);i.push(l);break}case"OrCase":{let s=i.pop(),c=i.pop(),l=n.orCase(t,s,c);i.push(l);break}}break}case"Right":{i.push(a.right);break}}}if(i.length===0)throw Error("BUG: ConfigError.reduceWithContext - please report an issue at https://github.com/Effect-TS/effect/issues");return i.pop()})});var mF="effect/Clock",NT,bc,hF=2147483647,FT,LT,gF,DT,qT=()=>new DT;var Sg=x(()=>{mn();ah();j();rt();NT=Symbol.for(mF),bc=Kt("effect/Clock"),FT={unsafeSchedule(e,t){let n=Mu(t);if(n>hF)return no;let r=!1,o=setTimeout(()=>{r=!0,e()},n);return()=>(clearTimeout(o),!r)}},LT=function(){let e=BigInt(1e6);if(typeof performance>"u"||typeof performance.now!=="function")return()=>BigInt(Date.now())*e;let t;return()=>{if(t===void 0)t=BigInt(Date.now())*e-BigInt(Math.round(performance.now()*1e6));return t+BigInt(Math.round(performance.now()*1e6))}}(),gF=function(){let e=typeof process==="object"&&"hrtime"in process&&typeof process.hrtime.bigint==="function"?process.hrtime:void 0;if(!e)return LT;let t=LT()-e.bigint();return()=>t+e.bigint()}();DT=class DT{[NT]=NT;unsafeCurrentTimeMillis(){return Date.now()}unsafeCurrentTimeNanos(){return gF()}currentTimeMillis=D(()=>this.unsafeCurrentTimeMillis());currentTimeNanos=D(()=>this.unsafeCurrentTimeNanos());scheduler(){return fe(FT)}sleep(e){return To((t)=>{let n=FT.unsafeSchedule(()=>t(nt),e);return Vr(D(n))})}}});var ir;var wc=x(()=>{au();ir=bb});var Na=(e)=>e.replace(/[/\\^$*+?.()|[\]{}]/g,"\\$&");var _g=()=>{};var $T,Pp;var jT=x(()=>{Be();tn();j();ju();Ge();xg();$T={_tag:"Empty"},Pp=d(2,(e,t)=>{let n=Xs(t),r=e;while(xh(n)){let o=n.head;switch(o._tag){case"Empty":{n=n.tail;break}case"AndThen":{n=Ur(o.first,Ur(o.second,n.tail));break}case"MapName":{r=Cn(r,o.f),n=n.tail;break}case"Nested":{r=aa(r,o.name),n=n.tail;break}case"Unnested":{if(g(Cr(r),Eb(o.name)))r=kn(r),n=n.tail;else return W(or(r,`Expected ${o.name} to be in path in ConfigProvider#unnested`));break}}}return Q(r)})});var VT="Constant",BT="Fail",KT="Fallback",zT="Described",WT="Lazy",JT="MapOrFail",GT="Nested",YT="Primitive",ZT="Redacted",XT="Sequence",QT="HashMap",eE="ZipWith";var Ip=(e,t)=>[...e,...t],vF="effect/ConfigProvider",tE,rE,TF="effect/ConfigProviderFlat",nE,EF=(e)=>({[tE]:tE,pipe(){return T(this,arguments)},...e}),OF=(e)=>({[nE]:nE,patch:e.patch,load:(t,n,r=!0)=>e.load(t,n,r),enumerateChildren:e.enumerateChildren}),RF=(e)=>EF({load:(t)=>B(on(e,Pr(),t,!1),(n)=>Je(Cr(n),{onNone:()=>dt(or(Pr(),`Expected a single value having structure: ${t}`)),onSome:fe})),flattened:e}),oE=(e)=>{let{pathDelim:t,seqDelim:n}=Object.assign({},{pathDelim:"_",seqDelim:","},e),r=(c)=>g(c,Ir(t)),o=(c)=>c.split(t),i=()=>typeof process<"u"&&("env"in process)&&typeof process.env==="object"?process.env:{};return RF(OF({load:(c,l,u=!0)=>{let p=r(c),f=i(),h=p in f?F(f[p]):A();return g(h,bi(()=>or(c,`Expected ${p} to exist in the process context`)),B((m)=>NF(m,c,l,n,u)))},enumerateChildren:(c)=>D(()=>{let l=i(),f=Object.keys(l).map((h)=>o(h.toUpperCase())).filter((h)=>{for(let m=0;m<c.length;m++){let w=g(c,xm(m)),S=h[m];if(S===void 0||w!==S)return!1}return!0}).flatMap((h)=>h.slice(c.length,c.length+1));return Sw(f)}),patch:$T}))},kF=(e,t,n,r)=>{let o=wm(n.length,(c)=>c>=r.length?A():F([e(c),c+1])),i=wm(r.length,(c)=>c>=n.length?A():F([t(c),c+1])),a=Ip(n,o),s=Ip(r,i);return[a,s]},CF=(e,t)=>{let n=t;if(n._tag==="Nested"){let r=e.slice();while(n._tag==="Nested")r.push(n.name),n=n.config;return r}return e},AF,PF=(e)=>IT(e,void 0,AF),on=(e,t,n,r)=>{let o=n;switch(o._tag){case VT:return fe(Rt(o.value));case zT:return Ce(()=>on(e,t,o.config,r));case BT:return dt(or(t,o.message));case KT:return g(Ce(()=>on(e,t,o.first,r)),cc((i)=>{if(o.condition(i))return g(on(e,t,o.second,r),cc((a)=>dt(Cp(i,a))));return dt(i)}));case WT:return Ce(()=>on(e,t,o.config(),r));case JT:return Ce(()=>g(on(e,t,o.original,r),B(yn((i)=>g(o.mapOrFail(i),bi(Co(CF(t,o.original))))))));case GT:return Ce(()=>on(e,Ip(t,Rt(o.name)),o.config,r));case YT:return g(Pp(t,e.patch),B((i)=>g(e.load(i,o,r),B((a)=>{if(a.length===0){let s=g(Mb(i),Oe(()=>"<n/a>"));return dt(or([],`Expected ${o.description} with name ${s}`))}return fe(a)}))));case ZT:return Ce(()=>g(on(e,t,o.original,r),bi(PF),Ke(Cn(o.redact))));case XT:return g(Pp(t,e.patch),B((i)=>g(e.enumerateChildren(i),B(LF),B((a)=>{if(a.length===0)return Ce(()=>Ke(on(e,t,o.config,!0),Rt));return g(yn(a,(s)=>on(e,Ab(t,`[${s}]`),o.config,!0)),Ke((s)=>{let c=su(s);if(c.length===0)return Rt(Pr());return Rt(c)}))}))));case QT:return Ce(()=>g(Pp(t,e.patch),B((i)=>g(e.enumerateChildren(i),B((a)=>g(a,yn((s)=>on(e,Ip(i,Rt(s)),o.valueConfig,r)),Ke((s)=>{if(s.length===0)return Rt(va());return g(FF(s),Cn((c)=>sv(bm(ke(a),c))))})))))));case eE:return Ce(()=>g(on(e,t,o.left,r),Si,B((i)=>g(on(e,t,o.right,r),Si,B((a)=>{if(Ee(i)&&Ee(a))return dt(kp(i.left,a.left));if(Ee(i)&&Ot(a))return dt(i.left);if(Ot(i)&&Ee(a))return dt(a.left);if(Ot(i)&&Ot(a)){let s=g(t,Ir(".")),c=IF(t,s),[l,u]=kF(c,c,g(i.right,Cn(Q)),g(a.right,Cn(Q)));return g(l,bm(u),yn(([p,f])=>g(up(p,f),Ke(([h,m])=>o.zip(h,m)))))}throw Error("BUG: ConfigProvider.fromFlatLoop - please report an issue at https://github.com/Effect-TS/effect/issues")})))))}},IF=(e,t)=>(n)=>W(or(e,`The element at index ${n} in a sequence at path "${t}" was missing`)),MF=(e,t)=>e.split(new RegExp(`\\s*${Na(t)}\\s*`)),NF=(e,t,n,r,o)=>{if(!o)return g(n.parse(e),sp({onFailure:Co(t),onSuccess:Rt}));return g(MF(e,r),yn((i)=>n.parse(i.trim())),bi(Co(t)))},FF=(e)=>Object.keys(e[0]).map((t)=>e.map((n)=>n[t])),LF=(e)=>g(yn(e,qF),sp({onFailure:()=>Pr(),onSuccess:Ar(ir)}),Si,Ke(xb)),DF,qF=(e)=>{let t=e.match(DF);if(t!==null){let n=t[2];return g(n!==void 0&&n.length>0?F(n):A(),Rn(UF))}return A()},UF=(e)=>{let t=Number.parseInt(e);return Number.isNaN(t)?A():F(t)};var iE=x(()=>{Be();mn();tn();j();Hu();pi();wc();Ge();be();_g();xg();jT();rt();tE=Symbol.for(vF),rE=Kt("effect/ConfigProvider"),nE=Symbol.for(TF),AF={andCase:(e,t,n)=>kp(t,n),orCase:(e,t,n)=>Cp(t,n),invalidDataCase:(e,t)=>hg(t,"<redacted>"),missingDataCase:(e,t)=>or(t,"<redacted>"),sourceUnavailableCase:(e,t,n,r)=>gg(t,"<redacted>",r),unsupportedCase:(e,t)=>yg(t,"<redacted>")},DF=/^(\[(\d+)\])$/});var aE,Mp,sE;var bg=x(()=>{mn();rt();aE=Symbol.for("effect/Console"),Mp=Kt("effect/Console"),sE={[aE]:aE,assert(e,...t){return D(()=>{console.assert(e,...t)})},clear:D(()=>{console.clear()}),count(e){return D(()=>{console.count(e)})},countReset(e){return D(()=>{console.countReset(e)})},debug(...e){return D(()=>{console.debug(...e)})},dir(e,t){return D(()=>{console.dir(e,t)})},dirxml(...e){return D(()=>{console.dirxml(...e)})},error(...e){return D(()=>{console.error(...e)})},group(e){return e?.collapsed?D(()=>console.groupCollapsed(e?.label)):D(()=>console.group(e?.label))},groupEnd:D(()=>{console.groupEnd()}),info(...e){return D(()=>{console.info(...e)})},log(...e){return D(()=>{console.log(...e)})},table(e,t){return D(()=>{console.table(e,t)})},time(e){return D(()=>console.time(e))},timeEnd(e){return D(()=>console.timeEnd(e))},timeLog(e,...t){return D(()=>{console.timeLog(e,...t)})},trace(...e){return D(()=>{console.trace(...e)})},warn(...e){return D(()=>{console.warn(...e)})},unsafe:console}});var jF="effect/Random",cE,lE,uE,VF=(e,t)=>Ce(()=>g(D(()=>Array.from(e)),B((n)=>{let r=[];for(let o=n.length;o>=2;o=o-1)r.push(o);return g(r,_i((o)=>g(t(o),Ke((i)=>BF(n,o-1,i)))),jr(lu(n)))}))),BF=(e,t,n)=>{let r=e[t];return e[t]=e[n],e[n]=r,e},pE=(e)=>new uE(E(e));var dE=x(()=>{Qn();mn();j();Me();io();rt();cE=Symbol.for(jF),lE=Kt("effect/Random");uE=class uE{seed;[cE]=cE;PRNG;constructor(e){this.seed=e,this.PRNG=new Gf(e)}get next(){return D(()=>this.PRNG.number())}get nextBoolean(){return Ke(this.next,(e)=>e>0.5)}get nextInt(){return D(()=>this.PRNG.integer(Number.MAX_SAFE_INTEGER))}nextRange(e,t){return Ke(this.next,(n)=>(t-e)*n+e)}nextIntBetween(e,t){return D(()=>this.PRNG.integer(t-e)+e)}shuffle(e){return VF(e,(t)=>this.nextIntBetween(0,t))}}});class hE{name;parent;context;startTime;kind;_tag="Span";spanId;traceId="native";sampled=!0;status;attributes;events=[];links;constructor(e,t,n,r,o,i){this.name=e,this.parent=t,this.context=n,this.startTime=o,this.kind=i,this.status={_tag:"Started",startTime:o},this.attributes=new Map,this.traceId=t._tag==="Some"?t.value.traceId:mE(32),this.spanId=mE(16),this.links=Array.from(r)}end(e,t){this.status={_tag:"Ended",endTime:e,exit:t,startTime:this.status.startTime}}attribute(e,t){this.attributes.set(e,t)}event(e,t,n){this.events.push([e,t,n??{}])}addLinks(e){this.links.push(...e)}}var fE,zF=(e)=>({[fE]:fE,...e}),vc,Np,mE,gE,yE;var Fp=x(()=>{mn();j();fE=Symbol.for("effect/Tracer"),vc=Kt("effect/Tracer"),Np=Kt("effect/ParentSpan"),mE=function(){return function(n){let r="";for(let o=0;o<n;o++)r+="abcdef0123456789".charAt(Math.floor(Math.random()*16));return r}}();gE=zF({span:(e,t,n,r,o,i)=>new hE(e,t,n,r,o,i),context:(e)=>e()}),yE=Gs()("effect/Tracer/DisablePropagation",{defaultValue:no})});var GF,Tc;var xE=x(()=>{mn();j();Sg();iE();rt();bg();dE();Fp();GF=g(So(),tr(bc,qT()),tr(Mp,sE),tr(lE,pE(Math.random())),tr(rE,oE()),tr(vc,gE)),Tc=V(Symbol.for("effect/DefaultServices/currentServices"),()=>fp(GF))});var ZF,SE=(e)=>{let t={BaseEffectError:class extends ZF{_tag=e}};return t.BaseEffectError.prototype.name=e,t.BaseEffectError};var _E=x(()=>{rt();ZF=function(){let e=Symbol.for("effect/Data/Error/plainArgs");return{BaseEffectError:class extends yp{constructor(n){super(n?.message,n?.cause?{cause:n.cause}:void 0);if(n)Object.assign(this,n),Object.defineProperty(this,e,{value:n,enumerable:!1})}toJSON(){return{...this[e],...this}}}}.BaseEffectError}()});var bE,XF,vg;var Tg=x(()=>{Rr();bE=Or,XF=cb;vg=class vg extends XF{}});var vE="Sequential",TE="Parallel",QF="ParallelN",Fa,EE,OE=(e)=>({_tag:QF,parallelism:e}),Eg=(e)=>e._tag===vE,Og=(e)=>e._tag===TE;var Lp=x(()=>{Fa={_tag:vE},EE={_tag:TE}});var Dp,qp,Up;var RE=x(()=>{Lp();Dp=Fa,qp=EE,Up=OE});function kE(e){return new Br(e)}function CE(){return kE(new Map)}var kg,Br,tL=(e,t,n,r=!1)=>{let o=e,i=t,a=n,s=r,c=void 0;while(c===void 0)if(we(i)&&we(a)){let l=et(i)[0],u=kn(i),p=et(a)[0],f=et(a)[1],h=kn(a);if(l.startTimeMillis<p.startTimeMillis)a=h,s=!0;else if(l.startTimeMillis>p.startTimeMillis)i=u;else if(l.id<p.id)a=h,s=!0;else if(l.id>p.id)i=u;else c=[f,s]}else c=[o.initial,!0];return c},Ag,Pg,AE=(e,t,n)=>{e.locals.forEach((r,o)=>{let i=r[0][1],a=o.patch(o.fork)(i);if(O(i,a))t.set(o,r);else t.set(o,[[n,a],...r])})},Ec,Ig,Ao,La,Cg=(e,t,n,r)=>{let o=e.get(n)??[],i;if(we(o)){let[a,s]=et(o);if(a[I](t))if(O(s,r))return;else i=[[t,r],...o.slice(1)];else i=[[t,r],...o]}else i=[[t,r]];e.set(n,i)},PE;var Hp=x(()=>{Be();pe();j();Ge();be();kg=Symbol.for("effect/FiberRefs");Br=class Br{locals;[kg]=kg;constructor(e){this.locals=e}pipe(){return T(this,arguments)}};Ag=d(3,(e,t,n)=>{let r=new Map(e.locals);return n.locals.forEach((o,i)=>{let a=o[0][1];if(!o[0][0][I](t)){if(!r.has(i)){if(O(a,i.initial))return;r.set(i,[[t,i.join(i.initial,a)]]);return}let s=r.get(i),[c,l]=tL(i,s,o);if(l){let u=i.diff(c,a),p=s[0][1],f=i.join(p,i.patch(u)(p));if(!O(p,f)){let h,m=s[0][0];if(m[I](t))h=[[m,f],...s.slice(1)];else h=[[t,f],...s];r.set(i,h)}}}}),new Br(r)}),Pg=d(2,(e,t)=>{let n=new Map;return AE(e,n,t),new Br(n)}),Ec=d(2,(e,t)=>{let n=new Map(e.locals);return n.delete(t),new Br(n)}),Ig=d(2,(e,t)=>{if(!e.locals.has(t))return A();return F(et(e.locals.get(t))[1])}),Ao=d(2,(e,t)=>g(Ig(e,t),Oe(()=>t.initial))),La=d(2,(e,{fiberId:t,fiberRef:n,value:r})=>{if(e.locals.size===0)return new Br(new Map([[n,[[t,r]]]]));let o=new Map(e.locals);return Cg(o,t,n,r),new Br(o)}),PE=d(2,(e,{entries:t,forkAs:n})=>{if(e.locals.size===0)return new Br(new Map(t));let r=new Map(e.locals);if(n!==void 0)AE(e,r,n);return t.forEach(([o,i])=>{if(i.length===1)Cg(r,i[0][0],o,i[0][1]);else i.forEach(([a,s])=>{Cg(r,a,o,s)})}),new Br(r)})});var IE,ME,NE;var Ng=x(()=>{Hp();IE=Ao,ME=PE,NE=CE});var LE="Empty",DE="Add",qE="Remove",UE="Update",HE="AndThen",$E,jE=(e,t)=>{let n=new Map(e.locals),r=$E;for(let[o,i]of t.locals.entries()){let a=et(i)[1],s=n.get(o);if(s!==void 0){let c=et(s)[1];if(!O(c,a))r=$p({_tag:UE,fiberRef:o,patch:o.diff(c,a)})(r)}else r=$p({_tag:DE,fiberRef:o,value:a})(r);n.delete(o)}for(let[o]of n.entries())r=$p({_tag:qE,fiberRef:o})(r);return r},$p,VE;var BE=x(()=>{Be();pe();j();Hp();$E={_tag:LE},$p=d(2,(e,t)=>({_tag:HE,first:e,second:t})),VE=d(3,(e,t,n)=>{let r=n,o=Rt(e);while(we(o)){let i=et(o),a=kn(o);switch(i._tag){case LE:{o=a;break}case DE:{r=La(r,{fiberId:t,fiberRef:i.fiberRef,value:i.value}),o=a;break}case qE:{r=Ec(r,i.fiberRef),o=a;break}case UE:{let s=Ao(r,i.fiberRef);r=La(r,{fiberId:t,fiberRef:i.fiberRef,value:i.fiberRef.patch(i.patch)(s)}),o=a;break}case HE:{o=aa(i.first)(aa(i.second)(a));break}}}return r})});var KE,zE;var WE=x(()=>{BE();KE=jE,zE=VE});var Vp="effect/FiberStatus",Po,jp="Done",JE="Running",GE="Suspended",oL,YE,ZE,XE,QE,eO=(e)=>new ZE(e),tO=(e,t)=>new XE(e,t),Bp=(e)=>C(e,Po),nO=(e)=>e._tag===jp;var rO=x(()=>{pe();j();Me();ye();Po=Symbol.for(Vp),oL=he(`${Vp}-${jp}`);YE=class YE{[Po]=Po;_tag=jp;[M](){return oL}[I](e){return Bp(e)&&e._tag===jp}};ZE=class ZE{runtimeFlags;[Po]=Po;_tag=JE;constructor(e){this.runtimeFlags=e}[M](){return g(E(Vp),G(E(this._tag)),G(E(this.runtimeFlags)),ie(this))}[I](e){return Bp(e)&&e._tag===JE&&this.runtimeFlags===e.runtimeFlags}};XE=class XE{runtimeFlags;blockingOn;[Po]=Po;_tag=GE;constructor(e,t){this.runtimeFlags=e,this.blockingOn=t}[M](){return g(E(Vp),G(E(this._tag)),G(E(this.runtimeFlags)),G(E(this.blockingOn)),ie(this))}[I](e){return Bp(e)&&e._tag===GE&&this.runtimeFlags===e.runtimeFlags&&O(this.blockingOn,e.blockingOn)}};QE=new YE});var oO,Fg,iO,aO;var sO=x(()=>{rO();oO=QE,Fg=eO,iO=tO,aO=nO});var sL,cL,lL,uL,pL,dL,fL,mL,hL,cO,lO=(e)=>{switch(e){case"All":return sL;case"Debug":return dL;case"Error":return lL;case"Fatal":return cL;case"Info":return pL;case"Trace":return fL;case"None":return mL;case"Warning":return uL}};var uO=x(()=>{j();rt();wc();au();sL=uT,cL=pT,lL=dT,uL=og,pL=ig,dL=ag,fL=fT,mL=mT,hL=g(ir,iu((e)=>e.ordinal)),cO=dm(hL)});function EL(e){return Dg("Micro.evaluate: Not implemented")}class Bg{tasks=[];running=!1;scheduleTask(e,t){if(this.tasks.push(e),!this.running)this.running=!0,IL(this.afterScheduled)}afterScheduled=()=>{this.running=!1,this.runTasks()};runTasks(){let e=this.tasks;this.tasks=[];for(let t=0,n=e.length;t<n;t++)e[t]()}shouldYield(e){return e.currentOpCount>=e.getRef(wO)}flush(){while(this.tasks.length>0)this.runTasks()}}var yL,zp,pO,xL,qg,mO,SL=(e,t=[])=>new mO(e,t),hO,_L=(e=[])=>new hO(e),bL=(e)=>e._tag==="Interrupt",dO,wL,gO,fO,yO,it,Lg,qa,Da,Wp,Kp,vL,TL,Gp=(e)=>({...TL,[yO]:e.op,[Lg]:e.eval??EL,[qa]:e.contA,[Da]:e.contE,[Wp]:e.ensure}),Ug=(e)=>{let t=Gp(e);return function(){let n=Object.create(t);return n[it]=e.single===!1?arguments:arguments[0],n}},xO=(e)=>{let t={...Gp(e),[zp]:zp,_tag:e.op,get[e.prop](){return this[it]},toJSON(){return{_id:"MicroExit",_tag:e.op,[e.prop]:this[it]}},[I](n){return AL(n)&&n._tag===e.op&&O(this[it],n[it])},[M](){return ie(this,G(he(e.op))(E(this[it])))}};return function(n){let r=Object.create(t);return r[it]=n,r[qa]=void 0,r[Da]=void 0,r[Wp]=void 0,r}},Hg,SO,OL,RL,kL,$g,Jp,CL,AL=(e)=>C(e,zp),_O,jg,Vg,Dg=(e)=>jg(SL(e)),PL,IL,ML,bO,wO,Yp,NL,FL,LL,vO,DL=(e)=>$g((t)=>{if(t.interruptible)return e;if(t.interruptible=!0,t._stack.push(vO(!1)),t._interrupted)return Vg;return e}),qL=(e)=>$g((t)=>{if(!t.interruptible)return e(ue);return t.interruptible=!1,t._stack.push(vO(!0)),e(DL)}),TO=(e,t)=>{let n=new gO(Yp.context(t?.scheduler??new Bg));if(n.evaluate(e),t?.signal)if(t.signal.aborted)n.unsafeInterrupt();else{let r=()=>n.unsafeInterrupt();t.signal.addEventListener("abort",r,{once:!0}),n.addObserver(()=>t.signal.removeEventListener("abort",r))}return n};var EO=x(()=>{mn();Tg();pe();j();Me();Ve();Au();be();ye();io();yL=Symbol.for("effect/Micro"),zp=Symbol.for("effect/Micro/MicroExit"),pO=Symbol.for("effect/Micro/MicroCause"),xL={_E:ue};qg=class qg extends globalThis.Error{_tag;traces;[pO];constructor(e,t,n){let r=`MicroCause.${e}`,o,i,a;if(t instanceof globalThis.Error){o=`(${r}) ${t.name}`,i=t.message;let s=i.split(`
26
+ `).length;a=t.stack?`(${r}) ${t.stack.split(`
27
+ `).slice(0,s+3).join(`
28
+ `)}`:`${o}: ${i}`}else o=r,i=Er(t,0),a=`${o}: ${i}`;if(n.length>0)a+=`
29
+ ${n.join(`
30
+ `)}`;super(i);this._tag=e,this.traces=n,this[pO]=xL,this.name=o,this.stack=a}pipe(){return T(this,arguments)}toString(){return this.stack}[ne](){return this.stack}};mO=class mO extends qg{defect;constructor(e,t=[]){super("Die",e,t);this.defect=e}};hO=class hO extends qg{constructor(e=[]){super("Interrupt","interrupted",e)}};dO=Symbol.for("effect/Micro/MicroFiber"),wL={_A:ue,_E:ue};gO=class gO{context;interruptible;[dO];_stack=[];_observers=[];_exit;_children;currentOpCount=0;constructor(e,t=!0){this.context=e,this.interruptible=t,this[dO]=wL}getRef(e){return Dw(this.context,e)}addObserver(e){if(this._exit)return e(this._exit),_s;return this._observers.push(e),()=>{let t=this._observers.indexOf(e);if(t>=0)this._observers.splice(t,1)}}_interrupted=!1;unsafeInterrupt(){if(this._exit)return;if(this._interrupted=!0,this.interruptible)this.evaluate(Vg)}unsafePoll(){return this._exit}evaluate(e){if(this._exit)return;else if(this._yielded!==void 0){let r=this._yielded;this._yielded=void 0,r()}let t=this.runLoop(e);if(t===Kp)return;let n=fO.interruptChildren&&fO.interruptChildren(this);if(n!==void 0)return this.evaluate(Jp(n,()=>t));this._exit=t;for(let r=0;r<this._observers.length;r++)this._observers[r](t);this._observers.length=0}runLoop(e){let t=!1,n=e;this.currentOpCount=0;try{while(!0){if(this.currentOpCount++,!t&&this.getRef(Yp).shouldYield(this)){t=!0;let r=n;n=Jp(RL,()=>r)}if(n=n[Lg](this),n===Kp){let r=this._yielded;if(zp in r)return this._yielded=void 0,r;return Kp}}}catch(r){if(!C(n,Lg))return Dg(`MicroFiber.runLoop: Not a valid effect: ${String(n)}`);return Dg(r)}}getCont(e){while(!0){let t=this._stack.pop();if(!t)return;let n=t[Wp]&&t[Wp](this);if(n)return{[e]:n};if(t[e])return t}}_yielded=void 0;yieldWith(e){return this._yielded=e,Kp}children(){return this._children??=new Set}};fO=V("effect/Micro/fiberMiddleware",()=>({interruptChildren:void 0})),yO=Symbol.for("effect/Micro/identifier"),it=Symbol.for("effect/Micro/args"),Lg=Symbol.for("effect/Micro/evaluate"),qa=Symbol.for("effect/Micro/successCont"),Da=Symbol.for("effect/Micro/failureCont"),Wp=Symbol.for("effect/Micro/ensureCont"),Kp=Symbol.for("effect/Micro/Yield"),vL={_A:ue,_E:ue,_R:ue},TL={...bE,_op:"Micro",[yL]:vL,pipe(){return T(this,arguments)},[Symbol.iterator](){return new ea(new Tr(this))},toJSON(){return{_id:"Micro",op:this[yO],...it in this?{args:this[it]}:void 0}},toString(){return ge(this)},[ne](){return ge(this)}};Hg=xO({op:"Success",prop:"value",eval(e){let t=e.getCont(qa);return t?t[qa](this[it],e):e.yieldWith(this)}}),SO=xO({op:"Failure",prop:"cause",eval(e){let t=e.getCont(Da);while(bL(this[it])&&t&&e.interruptible)t=e.getCont(Da);return t?t[Da](this[it],e):e.yieldWith(this)}}),OL=Ug({op:"Yield",eval(e){let t=!1;return e.getRef(Yp).scheduleTask(()=>{if(t)return;e.evaluate(PL)},this[it]??0),e.yieldWith(()=>{t=!0})}}),RL=OL(0),kL=Hg(void 0),$g=Ug({op:"WithMicroFiber",eval(e){return this[it](e)}}),Jp=d(2,(e,t)=>{let n=Object.create(CL);return n[it]=e,n[qa]=t,n}),CL=Gp({op:"OnSuccess",eval(e){return e._stack.push(this),this[it]}}),_O=Hg,jg=SO,Vg=jg(_L()),PL=_O(void 0),IL="setImmediate"in globalThis?globalThis.setImmediate:(e)=>setTimeout(e,0);ML=d(2,(e,t)=>$g((n)=>{let r=n.context;return n.context=t(r),LL(e,()=>(n.context=r,kL))})),bO=d(2,(e,t)=>ML(e,Js(t)));wO=class wO extends Gs()("effect/Micro/currentMaxOpsBeforeYield",{defaultValue:()=>2048}){};Yp=class Yp extends Gs()("effect/Micro/currentScheduler",{defaultValue:()=>new Bg}){};NL=d(2,(e,t)=>{let n=Object.create(FL);return n[it]=e,n[qa]=t.onSuccess,n[Da]=t.onFailure,n}),FL=Gp({op:"OnSuccessAndFailure",eval(e){return e._stack.push(this),this[it]}}),LL=d(2,(e,t)=>qL((n)=>NL(n(e),{onFailure:(r)=>Jp(t(jg(r)),()=>SO(r)),onSuccess:(r)=>Jp(t(_O(r)),()=>Hg(r))}))),vO=Ug({op:"SetInterruptible",ensure(e){if(e.interruptible=this[it],e._interrupted&&e.interruptible)return()=>Vg}})});class Zp{scheduleDrain;running=!1;tasks=new Kg;constructor(e){this.scheduleDrain=e}starveInternal=(e)=>{let t=this.tasks.buckets;this.tasks.buckets=[];for(let[n,r]of t)for(let o=0;o<r.length;o++)r[o]();if(this.tasks.buckets.length===0)this.running=!1;else this.starve(e)};starve(e=0){this.scheduleDrain(e,this.starveInternal)}scheduleTask(e,t){if(this.tasks.scheduleTask(e,t),!this.running)this.running=!0,this.starve()}static cached(e){let t=new Zp(e),n=new WeakMap;return(r)=>{if(r===void 0)return t;let o=n.get(r);if(o===void 0)o=new Zp(e),n.set(r,o);return o}}}class Kg{buckets=[];scheduleTask(e,t){let n=this.buckets.length,r=void 0,o=0;for(;o<n;o++)if(this.buckets[o][0]<=t)r=this.buckets[o];else break;if(r&&r[0]===t)r[1].push(e);else if(o===n)this.buckets.push([t,[e]]);else this.buckets.splice(o,0,[t,[e]])}}class OO{maxNextTickBeforeTimer;getRunner=Zp.cached((e,t)=>{if(e>=this.maxNextTickBeforeTimer)setTimeout(()=>t(0),0);else Promise.resolve(void 0).then(()=>t(e+1))});constructor(e){this.maxNextTickBeforeTimer=e}shouldYield(e){return e.currentOpCount>e.getFiberRef(sg)?e.getFiberRef(Aa):!1}scheduleTask(e,t,n){this.getRunner(n).scheduleTask(e,t)}}class Oc{tasks=new Kg;deferred=!1;scheduleTask(e,t,n){if(this.deferred)RO.scheduleTask(e,t,n);else this.tasks.scheduleTask(e,t)}shouldYield(e){return e.currentOpCount>e.getFiberRef(sg)?e.getFiberRef(Aa):!1}flush(){while(this.tasks.buckets.length>0){let e=this.tasks.buckets;this.tasks.buckets=[];for(let[t,n]of e)for(let r=0;r<n.length;r++)n[r]()}this.deferred=!0}}var RO,Xp;var Qp=x(()=>{rt();RO=V(Symbol.for("effect/Scheduler/defaultScheduler"),()=>new OO(2048));Xp=V(Symbol.for("effect/FiberRef/currentScheduler"),()=>St(RO))});var ed;var zg=x(()=>{rt();ed=V(Symbol.for("effect/FiberRef/currentRequestMap"),()=>St(new Map))});var Wg=(e,t,n,r)=>{switch(e){case void 0:return t();case"unbounded":return n();case"inherit":return wi(_T,(o)=>o==="unbounded"?n():o>1?r(o):t());default:return e>1?r(e):t()}};var CO=x(()=>{rt()});var Jg=(e)=>e.replace(/[\s="]/g,"_"),AO=(e)=>(t)=>`${Jg(t.label)}=${e-t.startTime}ms`;var PO="effect/MetricLabel",Gg,IO,MO=(e,t)=>new IO(e,t),VL=(e)=>C(e,Gg);var NO=x(()=>{pe();Me();be();ye();Gg=Symbol.for(PO);IO=class IO{key;value;[Gg]=Gg;_hash;constructor(e,t){this.key=e,this.value=t,this._hash=he(PO+this.key+this.value)}[M](){return this._hash}[I](e){return VL(e)&&this.key===e.key&&this.value===e.value}pipe(){return T(this,arguments)}}});var Yg;var FO=x(()=>{mn();Ge();Fp();Yg=Rn((e)=>zs(e.context,yE)?e._tag==="Span"?Yg(e.parent):A():F(e))});var LO;var DO=x(()=>{rt();LO=ug});var Zg="InterruptSignal",Xg="Stateful",Qg="Resume",ey="YieldNow",td=(e)=>({_tag:"InterruptSignal",cause:e}),Ua=(e)=>({_tag:"Stateful",onFiber:e}),ki=(e)=>({_tag:"Resume",effect:e}),qO=()=>({_tag:"YieldNow"});var GL="effect/FiberScope",nd,HO,$O,jO=(e)=>new $O(e.id(),e),Rc;var ty=x(()=>{wa();nd=Symbol.for(GL);HO=class HO{[nd]=nd;fiberId=hn;roots=new Set;add(e,t){this.roots.add(t),t.addObserver(()=>{this.roots.delete(t)})}};$O=class $O{fiberId;parent;[nd]=nd;constructor(e,t){this.fiberId=e,this.parent=t}add(e,t){this.parent.tell(Ua((n)=>{n.addChild(t),t.addObserver(()=>{n.removeChild(t)})}))}};Rc=V(Symbol.for("effect/FiberScope/Global"),()=>new HO)});var XL="effect/Fiber",ny,ry,QL,eD="effect/Fiber",BO,rd=(e)=>pp(uc(e.await),e.inheritAll),xW,Io="effect/FiberCurrent";var KO=x(()=>{wa();Ge();be();rt();Rr();ny=Symbol.for(XL),ry={_E:(e)=>e,_A:(e)=>e},QL={[ny]:ry,pipe(){return T(this,arguments)}},BO=Symbol.for(eD),xW={...so,commit(){return rd(this)},...QL,id:()=>hn,await:mc,children:fe([]),inheritAll:mc,poll:fe(A()),interruptAsFork:()=>mc}});var nD="effect/Logger",zO,WO,od=(e)=>({[zO]:WO,log:e,pipe(){return T(this,arguments)}}),bW,rD,oD=(e,t)=>({annotations:n,cause:r,date:o,fiberId:i,logLevel:a,message:s,spans:c})=>{let l=(m)=>m.match(rD)?m:e(m),u=(m,w)=>`${Jg(m)}=${l(w)}`,p=(m,w)=>" "+u(m,w),f=u("timestamp",o.toISOString());f+=p("level",a.label),f+=p("fiber",qu(i));let h=hm(s);for(let m=0;m<h.length;m++)f+=p("message",Er(h[m],t));if(!Vm(r))f+=p("cause",Nn(r,{renderErrorCause:!0}));for(let m of c)f+=" "+AO(o.getTime())(m);for(let[m,w]of n)f+=p(m,Er(w,t));return f},iD=(e)=>`"${e.replace(/\\([\s\S])|(")/g,"\\$1$2")}"`,JO,Ci,wW,GO,vW,TW;var YO=x(()=>{Be();j();Ve();be();Sa();ph();zO=Symbol.for(nD),WO={_Message:(e)=>e,_Output:(e)=>e},bW={[zO]:WO,log:_s,pipe(){return T(this,arguments)}},rD=/^[^\s"=]*$/,JO=od(oD(iD)),Ci={bold:"1",red:"31",green:"32",yellow:"33",blue:"34",cyan:"36",white:"37",gray:"90",black:"30",bgBrightRed:"101"},wW={None:[],All:[],Trace:[Ci.gray],Debug:[Ci.blue],Info:[Ci.green],Warning:[Ci.yellow],Error:[Ci.red],Fatal:[Ci.bgBrightRed,Ci.black]},GO=typeof process==="object"&&process!==null&&typeof process.stdout==="object"&&process.stdout!==null,vW=GO&&process.stdout.isTTY===!0,TW=GO||"Deno"in globalThis});var ZO="effect/MetricBoundaries",oy,XO,sD=(e)=>C(e,oy),cD=(e)=>{let t=g(e,gm(tt(Number.POSITIVE_INFINITY)),vm);return new XO(t)},QO=(e)=>g(mm(e.count-1,(t)=>e.start*Math.pow(e.factor,t)),Us,cD);var eR=x(()=>{Be();Qn();pe();j();Me();be();ye();oy=Symbol.for(ZO);XO=class XO{values;[oy]=oy;constructor(e){this.values=e,this._hash=g(he(ZO),G(en(this.values)))}_hash;[M](){return this._hash}[I](e){return sD(e)&&O(this.values,e.values)}pipe(){return T(this,arguments)}}});var uD="effect/MetricKeyType",tR,nR="effect/MetricKeyType/Counter",iy,pD="effect/MetricKeyType/Frequency",dD,fD="effect/MetricKeyType/Gauge",mD,rR="effect/MetricKeyType/Histogram",ay,hD="effect/MetricKeyType/Summary",gD,oR,iR,aR,sR=(e)=>new iR(e?.incremental??!1,e?.bigint??!1),cR=(e)=>new aR(e),sy=(e)=>C(e,iy),lR=(e)=>C(e,dD),uR=(e)=>C(e,mD),cy=(e)=>C(e,ay),pR=(e)=>C(e,gD);var ly=x(()=>{pe();j();Me();be();ye();tR=Symbol.for(uD),iy=Symbol.for(nR),dD=Symbol.for(pD),mD=Symbol.for(fD),ay=Symbol.for(rR),gD=Symbol.for(hD),oR={_In:(e)=>e,_Out:(e)=>e};iR=class iR{incremental;bigint;[tR]=oR;[iy]=iy;constructor(e,t){this.incremental=e,this.bigint=t,this._hash=he(nR)}_hash;[M](){return this._hash}[I](e){return sy(e)}pipe(){return T(this,arguments)}};aR=class aR{boundaries;[tR]=oR;[ay]=ay;constructor(e){this.boundaries=e,this._hash=g(he(rR),G(E(this.boundaries)))}_hash;[M](){return this._hash}[I](e){return cy(e)&&O(this.boundaries,e.boundaries)}pipe(){return T(this,arguments)}}});var yD="effect/MetricKey",fR,xD,SD,id,_D=(e)=>C(e,fR),mR=(e,t)=>new id(e,sR(t),kr(t?.description)),hR=(e,t,n)=>new id(e,cR(t),kr(n)),gR;var yR=x(()=>{Be();pe();j();Me();Ge();be();ye();ly();fR=Symbol.for(yD),xD={_Type:(e)=>e},SD=uo(O);id=class id{name;keyType;description;tags;[fR]=xD;constructor(e,t,n,r=[]){this.name=e,this.keyType=t,this.description=n,this.tags=r,this._hash=g(he(this.name+this.description),G(E(this.keyType)),G(en(this.tags)))}_hash;[M](){return this._hash}[I](e){return _D(e)&&this.name===e.name&&O(this.keyType,e.keyType)&&O(this.description,e.description)&&SD(this.tags,e.tags)}pipe(){return T(this,arguments)}};gR=d(2,(e,t)=>t.length===0?e:new id(e.name,e.keyType,e.description,lo(e.tags,t)))});class SR{backing;constructor(e){this.backing=e}currentBucket;next(){if(this.currentBucket===void 0){let t=this.backing.next();if(t.done)return t;this.currentBucket=t.value[Symbol.iterator]()}let e=this.currentBucket.next();if(e.done)return this.currentBucket=void 0,this.next();return e}}var xR,wD,uy,_R=()=>{let e=Object.create(wD);return e.referential=new Map,e.buckets=new Map,e.bucketsSize=0,e},Mo,vD=(e,t,n,r=!1)=>{for(let o=0,i=t.length;o<i;o++)if(n[I](t[o][0])){let a=t[o][1];if(r)t.splice(o,1),e.bucketsSize--;return F(a)}return A()},Ha,$a,TD=(e,t,n)=>{for(let r=0,o=t.length;r<o;r++)if(n[I](t[r][0])){t.splice(r,1),e.bucketsSize--;return}};var bR=x(()=>{pe();j();Me();Ve();Ge();be();xR=Symbol.for("effect/MutableHashMap"),wD={[xR]:xR,[Symbol.iterator](){return new uy(this)},toString(){return ge(this.toJSON())},toJSON(){return{_id:"MutableHashMap",values:Array.from(this).map(de)}},[ne](){return this.toJSON()},pipe(){return T(this,arguments)}};uy=class uy{self;referentialIterator;bucketIterator;constructor(e){this.self=e,this.referentialIterator=e.referential[Symbol.iterator]()}next(){if(this.bucketIterator!==void 0)return this.bucketIterator.next();let e=this.referentialIterator.next();if(e.done)return this.bucketIterator=new SR(this.self.buckets.values()),this.next();return e}[Symbol.iterator](){return new uy(this.self)}};Mo=d(2,(e,t)=>{if(ks(t)===!1)return e.referential.has(t)?F(e.referential.get(t)):A();let n=t[M](),r=e.buckets.get(n);if(r===void 0)return A();return vD(e,r,t)}),Ha=d(2,(e,t)=>Re(Mo(e,t))),$a=d(3,(e,t,n)=>{if(ks(t)===!1)return e.referential.set(t,n),e;let r=t[M](),o=e.buckets.get(r);if(o===void 0)return e.buckets.set(r,[[t,n]]),e.bucketsSize++,e;return TD(e,o,t),o.push([t,n]),e.bucketsSize++,e})});var OD="effect/MetricState",kc,wR="effect/MetricState/Counter",py,vR="effect/MetricState/Frequency",dy,TR="effect/MetricState/Gauge",fy,ER="effect/MetricState/Histogram",my,OR="effect/MetricState/Summary",hy,Cc,RR,RD,kR,CR,AR,PR,IR=(e)=>new RR(e),MR=(e)=>new kR(e),NR=(e)=>new CR(e),FR=(e)=>new AR(e.buckets,e.count,e.min,e.max,e.sum),LR=(e)=>new PR(e.error,e.quantiles,e.count,e.min,e.max,e.sum),kD=(e)=>C(e,py),CD=(e)=>C(e,dy),AD=(e)=>C(e,fy),PD=(e)=>C(e,my),ID=(e)=>C(e,hy);var DR=x(()=>{Be();pe();j();Me();be();ye();kc=Symbol.for(OD),py=Symbol.for(wR),dy=Symbol.for(vR),fy=Symbol.for(TR),my=Symbol.for(ER),hy=Symbol.for(OR),Cc={_A:(e)=>e};RR=class RR{count;[kc]=Cc;[py]=py;constructor(e){this.count=e}[M](){return g(E(wR),G(E(this.count)),ie(this))}[I](e){return kD(e)&&this.count===e.count}pipe(){return T(this,arguments)}};RD=uo(O);kR=class kR{occurrences;[kc]=Cc;[dy]=dy;constructor(e){this.occurrences=e}_hash;[M](){return g(he(vR),G(en(ke(this.occurrences.entries()))),ie(this))}[I](e){return CD(e)&&RD(ke(this.occurrences.entries()),ke(e.occurrences.entries()))}pipe(){return T(this,arguments)}};CR=class CR{value;[kc]=Cc;[fy]=fy;constructor(e){this.value=e}[M](){return g(E(TR),G(E(this.value)),ie(this))}[I](e){return AD(e)&&this.value===e.value}pipe(){return T(this,arguments)}};AR=class AR{buckets;count;min;max;sum;[kc]=Cc;[my]=my;constructor(e,t,n,r,o){this.buckets=e,this.count=t,this.min=n,this.max=r,this.sum=o}[M](){return g(E(ER),G(E(this.buckets)),G(E(this.count)),G(E(this.min)),G(E(this.max)),G(E(this.sum)),ie(this))}[I](e){return PD(e)&&O(this.buckets,e.buckets)&&this.count===e.count&&this.min===e.min&&this.max===e.max&&this.sum===e.sum}pipe(){return T(this,arguments)}};PR=class PR{error;quantiles;count;min;max;sum;[kc]=Cc;[hy]=hy;constructor(e,t,n,r,o,i){this.error=e,this.quantiles=t,this.count=n,this.min=r,this.max=o,this.sum=i}[M](){return g(E(OR),G(E(this.error)),G(E(this.quantiles)),G(E(this.count)),G(E(this.min)),G(E(this.max)),G(E(this.sum)),ie(this))}[I](e){return ID(e)&&this.error===e.error&&O(this.quantiles,e.quantiles)&&this.count===e.count&&this.min===e.min&&this.max===e.max&&this.sum===e.sum}pipe(){return T(this,arguments)}}});var ND="effect/MetricHook",FD,LD,Ac=(e)=>({[FD]:LD,pipe(){return T(this,arguments)},...e}),qR,HR=(e)=>{let t=e.keyType.bigint?qR:0,n=e.keyType.incremental?e.keyType.bigint?(o)=>o>=qR:(o)=>o>=0:(o)=>!0,r=(o)=>{if(n(o))t=t+o};return Ac({get:()=>IR(t),update:r,modify:r})},$R=(e)=>{let t=new Map;for(let r of e.keyType.preregisteredWords)t.set(r,0);let n=(r)=>{let o=t.get(r)??0;t.set(r,o+1)};return Ac({get:()=>MR(t),update:n,modify:n})},jR=(e,t)=>{let n=t;return Ac({get:()=>NR(n),update:(r)=>{n=r},modify:(r)=>{n=n+r}})},VR=(e)=>{let t=e.keyType.boundaries.values,n=t.length,r=new Uint32Array(n+1),o=new Float64Array(n),i=0,a=0,{MAX_VALUE:s,MIN_VALUE:c}=Number;g(t,Ar(ir),Cn((p,f)=>{o[f]=p}));let l=(p)=>{let f=0,h=n;while(f!==h){let m=Math.floor(f+(h-f)/2),w=o[m];if(p<=w)h=m;else f=m;if(h===f+1)if(p<=o[f])h=f;else f=h}if(r[f]=r[f]+1,i=i+1,a=a+p,p<s)s=p;if(p>c)c=p},u=()=>{let p=oi(n),f=0;for(let h=0;h<n;h++){let m=o[h],w=r[h];f=f+w,p[h]=[m,f]}return p};return Ac({get:()=>FR({buckets:u(),count:i,min:s,max:c,sum:a}),update:l,modify:l})},BR=(e)=>{let{error:t,maxAge:n,maxSize:r,quantiles:o}=e.keyType,i=g(o,Ar(ir)),a=oi(r),s=0,c=0,l=0,u=0,p=0,f=(m)=>{let w=[],S=0;while(S!==r-1){let y=a[S];if(y!=null){let[R,P]=y,z=Iu(m-R);if(Yw(z,oh)&&Gw(z,n))w.push(P)}S=S+1}return DD(t,i,Ar(w,ir))},h=(m,w)=>{if(r>0){s=s+1;let S=s%r;a[S]=[w,m]}u=c===0?m:Math.min(u,m),p=c===0?m:Math.max(p,m),c=c+1,l=l+m};return Ac({get:()=>LR({error:t,quantiles:f(Date.now()),count:c,min:u,max:p,sum:l}),update:([m,w])=>h(m,w),modify:([m,w])=>h(m,w)})},DD=(e,t,n)=>{let r=n.length;if(!we(t))return Pr();let o=t[0],i=t.slice(1),a=UR(e,r,A(),0,o,n),s=Rt(a);return i.forEach((c)=>{s.push(UR(e,r,a.value,a.consumed,c,a.rest))}),Cn(s,(c)=>[c.quantile,c.value])},UR=(e,t,n,r,o,i)=>{let a=e,s=t,c=n,l=r,u=o,p=i,f=e,h=t,m=n,w=r,S=o,y=i;while(!0){if(!we(p))return{quantile:u,value:A(),consumed:l,rest:[]};if(u===1)return{quantile:u,value:F(Sm(p)),consumed:l+p.length,rest:[]};let R=et(p),P=Nb(p,(L)=>L===R),z=u*s,X=a/2*z,U=l+P[0].length,te=Math.abs(U-z);if(U<z-X){f=a,h=s,m=Cr(p),w=U,S=u,y=P[1],a=f,s=h,c=m,l=w,u=S,p=y;continue}if(U>z+X){let L=Ne(c)?F(R):c;return{quantile:u,value:L,consumed:l,rest:p}}switch(c._tag){case"None":{f=a,h=s,m=Cr(p),w=U,S=u,y=P[1],a=f,s=h,c=m,l=w,u=S,p=y;continue}case"Some":{let L=Math.abs(z-c.value);if(te<L){f=a,h=s,m=Cr(p),w=U,S=u,y=P[1],a=f,s=h,c=m,l=w,u=S,p=y;continue}return{quantile:u,value:F(c.value),consumed:l,rest:p}}}}throw Error("BUG: MetricHook.resolveQuantiles - please report an issue at https://github.com/Effect-TS/effect/issues")};var KR=x(()=>{Be();ah();j();wc();Ge();be();DR();FD=Symbol.for(ND),LD={_In:(e)=>e,_Out:(e)=>e},qR=BigInt(0)});var UD="effect/MetricPair",HD,$D,zR=(e,t)=>({[HD]:$D,metricKey:e,metricState:t,pipe(){return T(this,arguments)}});var WR=x(()=>{be();HD=Symbol.for(UD),$D={_Type:(e)=>e}});var VD="effect/MetricRegistry",JR,GR,YR=()=>new GR;var ZR=x(()=>{j();bR();Ge();KR();ly();WR();JR=Symbol.for(VD);GR=class GR{[JR]=JR;map=_R();snapshot(){let e=[];for(let[t,n]of this.map)e.push(zR(t,n.get()));return e}get(e){let t=g(this.map,Mo(e),Bt);if(t==null){if(sy(e.keyType))return this.getCounter(e);if(uR(e.keyType))return this.getGauge(e);if(lR(e.keyType))return this.getFrequency(e);if(cy(e.keyType))return this.getHistogram(e);if(pR(e.keyType))return this.getSummary(e);throw Error("BUG: MetricRegistry.get - unknown MetricKeyType - please report an issue at https://github.com/Effect-TS/effect/issues")}else return t}getCounter(e){let t=g(this.map,Mo(e),Bt);if(t==null){let n=HR(e);if(!g(this.map,Ha(e)))g(this.map,$a(e,n));t=n}return t}getFrequency(e){let t=g(this.map,Mo(e),Bt);if(t==null){let n=$R(e);if(!g(this.map,Ha(e)))g(this.map,$a(e,n));t=n}return t}getGauge(e){let t=g(this.map,Mo(e),Bt);if(t==null){let n=jR(e,e.keyType.bigint?BigInt(0):0);if(!g(this.map,Ha(e)))g(this.map,$a(e,n));t=n}return t}getHistogram(e){let t=g(this.map,Mo(e),Bt);if(t==null){let n=VR(e);if(!g(this.map,Ha(e)))g(this.map,$a(e,n));t=n}return t}getSummary(e){let t=g(this.map,Mo(e),Bt);if(t==null){let n=BR(e);if(!g(this.map,Ha(e)))g(this.map,$a(e,n));t=n}return t}}});var KD="effect/Metric",zD,WD,XR,QR=function(e,t,n,r){let o=Object.assign((i)=>cp(i,(a)=>GD(o,a)),{[zD]:WD,keyType:e,unsafeUpdate:t,unsafeValue:n,unsafeModify:r,register(){return this.unsafeValue([]),this},pipe(){return T(this,arguments)}});return o},Pc=(e,t)=>ek(mR(e,t)),ek=(e)=>{let t,n=new WeakMap,r=(o)=>{if(o.length===0){if(t!==void 0)return t;return t=XR.get(e),t}let i=n.get(o);if(i!==void 0)return i;return i=XR.get(gR(e,o)),n.set(o,i),i};return QR(e.keyType,(o,i)=>r(i).update(o),(o)=>r(o).get(),(o,i)=>r(i).modify(o))},tk=(e,t,n)=>ek(hR(e,t,n)),nk,JD,GD;var rk=x(()=>{Be();j();be();rt();yR();NO();ZR();zD=Symbol.for(KD),WD={_Type:(e)=>e,_In:(e)=>e,_Out:(e)=>e},XR=V(Symbol.for("effect/Metric/globalMetricRegistry"),()=>YR()),nk=d(3,(e,t,n)=>JD(e,[MO(t,n)])),JD=d(2,(e,t)=>QR(e.keyType,(n,r)=>e.unsafeUpdate(n,lo(t,r)),(n)=>e.unsafeValue(lo(t,n)),(n,r)=>e.unsafeModify(n,lo(t,r)))),GD=d(2,(e,t)=>wi(gc,(n)=>D(()=>e.unsafeUpdate(t,n))))});var ZD="effect/Request",XD,QD,tJ,ok;var ik=x(()=>{j();zg();rt();Rr();XD=Symbol.for(ZD),QD={_E:(e)=>e,_A:(e)=>e},tJ={...Ns,[XD]:QD},ok=d(2,(e,t)=>wi(ed,(n)=>D(()=>{if(n.has(e)){let r=n.get(e);if(!r.state.completed)r.state.completed=!0,_p(r.result,t)}})))});var eq="effect/Supervisor",ad,gy,sd,cd,yy=(e)=>C(e,ad)&&Os(e,"Zip"),ak,tq=(e)=>new ak(e),Ai;var ld=x(()=>{j();ye();rt();ad=Symbol.for(eq),gy={_T:(e)=>e};sd=class sd{underlying;value0;[ad]=gy;constructor(e,t){this.underlying=e,this.value0=t}get value(){return this.value0}onStart(e,t,n,r){this.underlying.onStart(e,t,n,r)}onEnd(e,t){this.underlying.onEnd(e,t)}onEffect(e,t){this.underlying.onEffect(e,t)}onSuspend(e){this.underlying.onSuspend(e)}onResume(e){this.underlying.onResume(e)}map(e){return new sd(this,g(this.value,Ke(e)))}zip(e){return new cd(this,e)}};cd=class cd{left;right;_tag="Zip";[ad]=gy;constructor(e,t){this.left=e,this.right=t}get value(){return up(this.left.value,this.right.value)}onStart(e,t,n,r){this.left.onStart(e,t,n,r),this.right.onStart(e,t,n,r)}onEnd(e,t){this.left.onEnd(e,t),this.right.onEnd(e,t)}onEffect(e,t){this.left.onEffect(e,t),this.right.onEffect(e,t)}onSuspend(e){this.left.onSuspend(e),this.right.onSuspend(e)}onResume(e){this.left.onResume(e),this.right.onResume(e)}map(e){return new sd(this,g(this.value,Ke(e)))}zip(e){return new cd(this,e)}};ak=class ak{effect;[ad]=gy;constructor(e){this.effect=e}get value(){return this.effect}onStart(e,t,n,r){}onEnd(e,t){}onEffect(e,t){}onSuspend(e){}onResume(e){}map(e){return new sd(this,g(this.value,Ke(e)))}zip(e){return new cd(this,e)}onRun(e,t){return e()}};Ai=V("effect/Supervisor/none",()=>tq(nt))});var sk;var ck=x(()=>{Wu();sk=wo});var lk="Empty",uk="AddSupervisor",pk="RemoveSupervisor",dk="AndThen",ja,ud=(e,t)=>({_tag:dk,first:e,second:t}),rq=(e,t)=>oq(t,tt(e)),oq=(e,t)=>{let n=e,r=t;while(An(r)){let o=Pn(r);switch(o._tag){case lk:{r=In(r);break}case uk:{n=n.zip(o.supervisor),r=In(r);break}case pk:{n=Sy(n,o.supervisor),r=In(r);break}case dk:{r=kt(o.first)(kt(o.second)(In(r)));break}}}return n},Sy=(e,t)=>{if(O(e,t))return Ai;else if(yy(e))return Sy(e.left,t).zip(Sy(e.right,t));else return e},pd=(e)=>{if(O(e,Ai))return er();else if(yy(e))return g(pd(e.left),Lr(pd(e.right)));else return ci(e)},iq=(e,t)=>{if(O(e,t))return ja;let n=pd(e),r=pd(t),o=g(r,Um(n),ui(ja,(a,s)=>ud(a,{_tag:uk,supervisor:s}))),i=g(n,Um(r),ui(ja,(a,s)=>ud(a,{_tag:pk,supervisor:s})));return ud(o,i)},fk;var mk=x(()=>{Qn();ck();pe();j();pi();ld();ja={_tag:lk},fk=sk({empty:ja,patch:rq,combine:ud,diff:iq})});var hq,hk,gq,yq,xq,Ic="Continue",Sq="Done",gk="Yield",_q,dd=(e)=>{throw Error(`BUG: FiberRuntime - ${Er(e)} - please report an issue at https://github.com/Effect-TS/effect/issues`)},Kr,zr,Mc,bq,wq=(e)=>_i(Hv(e),(t)=>Pi(jv(t),([n,r])=>{let o=new Map,i=[];for(let s of r){i.push(Mr(s));for(let c of s)o.set(c.request,c)}let a=i.flat();return ko(Dq(n.runAll(i),a,()=>a.forEach((s)=>{s.listeners.interrupted=!0})),ed,o)},!1,!1)),vq,fd,Tq,Eq=(e)=>od((t)=>{let n=IE(t.context,Tc);zs(n,Mp).unsafe.log(e.log(t))}),Oq,Rq,kq,Sk,_k=(e,t,n)=>Ce(()=>{let r=ke(e),o=Array(r.length);return Ro(Pi(r,(a,s)=>B(t(a,s),(c)=>D(()=>o[s]=c)),n,!1),fe(o))}),Pi=(e,t,n,r,o)=>Oo((i)=>ng((a)=>xt((s)=>{let c=Array.from(e).reverse(),l=c.length;if(l===0)return nt;let u=0,p=!1,f=o?Math.min(c.length,o):c.length,h=new Set,m=[],w=()=>h.forEach((L)=>{L.currentScheduler.scheduleTask(()=>{L.unsafeInterruptAsFork(s.id())},0,L)}),S=[],y=[],R=[],P=()=>{let L=m.filter(({exit:se})=>se._tag==="Failure").sort((se,ce)=>se.index<ce.index?-1:se.index===ce.index?0:1).map(({exit:se})=>se);if(L.length===0)L.push(xn);return L},z=(L,se=!1)=>{let ce=lp(a(L)),ee=Aq(ce,s,s.currentRuntimeFlags,Rc);return s.currentScheduler.scheduleTask(()=>{if(se)ee.unsafeInterruptAsFork(s.id());ee.resume(ce)},0,ee),ee},X=()=>{if(!r)l-=c.length,c=[];p=!0,w()},U=n?tg:Eo,te=z(To((L)=>{let se=(ee,Ae)=>{if(ee._op==="Blocked")R.push(ee);else if(m.push({index:Ae,exit:ee}),ee._op==="Failure"&&!p)X()},ce=()=>{if(c.length>0){let ee=c.pop(),Ae=u++,vt=()=>{let je=c.pop();return Ae=u++,B(fc(),()=>B(U(i(t(je,Ae))),Ft))},Ft=(je)=>{if(c.length>0){if(se(je,Ae),c.length>0)return vt()}return fe(je)},Lt=B(U(i(t(ee,Ae))),Ft),De=z(Lt);if(S.push(De),h.add(De),p)De.currentScheduler.scheduleTask(()=>{De.unsafeInterruptAsFork(s.id())},0,De);De.addObserver((je)=>{let Tt;if(je._op==="Failure")Tt=je;else Tt=je.effect_instruction_i0;if(y.push(De),h.delete(De),se(Tt,Ae),m.length===l)L(fe(Oe(Oi(P(),{parallel:!0}),()=>xn)));else if(R.length+m.length===l){let Et=P(),Gi=R.map((to)=>to.effect_instruction_i0).reduce(Vh);L(fe(rp(Gi,Pi([Oe(Oi(Et,{parallel:!0}),()=>xn),...R.map((to)=>to.effect_instruction_i1)],(to)=>to,n,!0,o))))}else ce()})}};for(let ee=0;ee<f;ee++)ce()}));return Vr(Ca(uc(i(rd(te))),xp({onFailure:(L)=>{X();let se=R.length+1,ce=Math.min(typeof o==="number"?o:R.length,R.length),ee=Array.from(R);return To((Ae)=>{let vt=[],Ft=0,Lt=0,De=(Tt,Et)=>(Gi)=>{if(vt[Tt]=Gi,Ft++,Ft===se)Ae(Ie(ve(L)));if(ee.length>0&&Et)je()},je=()=>{z(ee.pop(),!0).addObserver(De(Lt,!0)),Lt++};te.addObserver(De(Lt,!1)),Lt++;for(let Tt=0;Tt<ce;Tt++)je()})},onSuccess:()=>yn(y,(L)=>L.inheritAll)})))}))),_y=(e,t,n,r)=>Ce(()=>{let o=ke(e),i=Array(o.length);return Ro(Pi(o,(s,c)=>Ke(n(s,c),(l)=>i[c]=l),r,!1,t),fe(i))}),vy=(e)=>Pq(e,Rc),Cq=(e,t,n,r=null)=>{let o=bk(e,t,n,r);return o.resume(e),o},Aq=(e,t,n,r=null)=>bk(e,t,n,r),bk=(e,t,n,r=null)=>{let o=Uu(),i=t.getFiberRefs(),a=Pg(i,o),s=new fd(o,a,n),c=Ao(a,Ti),l=s.currentSupervisor;return l.onStart(c,e,F(t),s),s.addObserver((p)=>l.onEnd(p,s)),(r!==null?r:g(t.getFiberRef(np),Oe(()=>t.scope()))).add(n,s),s},Pq=(e,t)=>xt((n,r)=>fe(Cq(e,n,r.runtimeFlags,t))),by=(e)=>Ri((t)=>Je(_o(t,Nc),{onNone:()=>e,onSome:(n)=>{switch(n.strategy._tag){case"Parallel":return e;case"Sequential":case"ParallelN":return B(Pa(n,qp),(r)=>Ty(e,r))}}})),yk=(e)=>(t)=>Ri((n)=>Je(_o(n,Nc),{onNone:()=>t,onSome:(r)=>{if(r.strategy._tag==="ParallelN"&&r.strategy.parallelism===e)return t;return B(Pa(r,Up(e)),(o)=>Ty(t,o))}})),Va=(e,t)=>(n)=>Ri((r)=>Je(_o(r,Nc),{onNone:()=>n(ue),onSome:(o)=>{if(t===!0){let i=e._tag==="Parallel"?by:e._tag==="Sequential"?wy:yk(e.parallelism);switch(o.strategy._tag){case"Parallel":return i(n(by));case"Sequential":return i(n(wy));case"ParallelN":return i(n(yk(o.strategy.parallelism)))}}else return n(ue)}})),wy=(e)=>Ri((t)=>Je(_o(t,Nc),{onNone:()=>e,onSome:(n)=>{switch(n.strategy._tag){case"Sequential":return e;case"Parallel":case"ParallelN":return B(Pa(n,Dp),(r)=>Ty(e,r))}}})),Nc,Iq=(e,t)=>{if(e.state._tag==="Open")e.state.finalizers.set({},t)},Mq,Nq=(e=Fa)=>{let t=Object.create(Mq);return t.strategy=e,t.state={_tag:"Open",finalizers:new Map},t},Ty,Fq=(e)=>vi(e,{differ:fk,fork:ja}),xk,Lq,wk,Dq=(e,t,n)=>lc((r)=>wk(B(vy(ap(e)),(o)=>To((i)=>{let a=t.map((l)=>l.listeners.count),s=()=>{if(a.every((l)=>l===0)){if(t.every((l)=>{if(l.result.state.current._tag==="Pending")return!0;else if(l.result.state.current._tag==="Done"&&Ia(l.result.state.current.effect)&&l.result.state.current.effect._tag==="Failure"&&Ou(l.result.state.current.effect.cause))return!0;else return!1}))c.forEach((l)=>l()),n?.(),i(lT(o))}};o.addObserver((l)=>{c.forEach((u)=>u()),i(l)});let c=t.map((l,u)=>{let p=(f)=>{a[u]=f,s()};return l.listeners.addObserver(p),()=>l.listeners.removeObserver(p)});return s(),D(()=>{c.forEach((l)=>l())})})),Ce(()=>{let o=t.flatMap((i)=>{if(!i.state.completed)return[i];return[]});return _i(o,(i)=>ok(i.request,dg(r)))})));var Ey=x(()=>{Be();Qn();mn();Tg();RE();wa();Ng();WE();sO();j();pi();Ve();uO();EO();Ge();be();ye();$h();Qp();io();Vv();Sa();Sg();zg();CO();FO();rt();xE();bg();Lp();KO();Hp();ty();YO();rk();eR();ik();ac();ac();ld();mk();Fp();hq=Pc("effect_fiber_started",{incremental:!0}),hk=Pc("effect_fiber_active"),gq=Pc("effect_fiber_successes",{incremental:!0}),yq=Pc("effect_fiber_failures",{incremental:!0}),xq=nk(tk("effect_fiber_lifetimes",QO({start:0.5,factor:2,count:35})),"time_unit","milliseconds"),_q={_E:(e)=>e,_A:(e)=>e},Kr=Symbol.for("effect/internal/fiberRuntime/YieldedOp"),zr=V("effect/internal/fiberRuntime/yieldedOpChannel",()=>({currentOp:null})),Mc={[ta]:(e,t,n)=>yt(()=>t.effect_instruction_i1(n)),["OnStep"]:(e,t,n)=>Ie(Ie(n)),[na]:(e,t,n)=>yt(()=>t.effect_instruction_i2(n)),[Is]:(e,t,n)=>{if(e.patchRuntimeFlags(e.currentRuntimeFlags,t.patch),$r(e.currentRuntimeFlags)&&e.isInterrupted())return ve(e.getInterruptedCause());else return Ie(n)},[ra]:(e,t,n)=>{if(yt(()=>t.effect_instruction_i2(n)),yt(()=>t.effect_instruction_i0()))return e.pushStack(t),yt(()=>t.effect_instruction_i1());else return nt},[oa]:(e,t,n)=>{while(!0){let r=yt(()=>t.effect_instruction_i0.next(n));if(r.done)return Ie(r.value);let o=Yf(r.value);if(!Ia(o))return e.pushStack(t),o;else if(o._tag==="Failure")return o;n=o.value}}},bq={[Zg]:(e,t,n,r)=>(e.processNewInterruptSignal(r.cause),$r(t)?ve(r.cause):n),[Qg]:(e,t,n,r)=>{throw Error("It is illegal to have multiple concurrent run loops in a single fiber")},[Xg]:(e,t,n,r)=>(r.onFiber(e,Fg(t)),n),[ey]:(e,t,n,r)=>B(fc(),()=>n)},vq=Ms();fd=class fd extends vg{[ny]=ry;[BO]=_q;_fiberRefs;_fiberId;_queue=[];_children=null;_observers=[];_running=!1;_stack=[];_asyncInterruptor=null;_asyncBlockingOn=null;_exitValue=null;_steps=[];_isYielding=!1;currentRuntimeFlags;currentOpCount=0;currentSupervisor;currentScheduler;currentTracer;currentSpan;currentContext;currentDefaultServices;constructor(e,t,n){super();if(this.currentRuntimeFlags=n,this._fiberId=e,this._fiberRefs=t,Lh(n)){let r=this.getFiberRef(gc);hq.unsafeUpdate(1,r),hk.unsafeUpdate(1,r)}this.refreshRefCache()}commit(){return rd(this)}id(){return this._fiberId}resume(e){this.tell(ki(e))}get status(){return this.ask((e,t)=>t)}get runtimeFlags(){return this.ask((e,t)=>{if(aO(t))return e.currentRuntimeFlags;return t.runtimeFlags})}scope(){return jO(this)}get children(){return this.ask((e)=>Array.from(e.getChildren()))}getChildren(){if(this._children===null)this._children=new Set;return this._children}getInterruptedCause(){return this.getFiberRef(yc)}fiberRefs(){return this.ask((e)=>e.getFiberRefs())}ask(e){return Ce(()=>{let t=OT(this._fiberId);return this.tell(Ua((n,r)=>{_p(t,D(()=>e(n,r)))})),Sp(t)})}tell(e){if(this._queue.push(e),!this._running)this._running=!0,this.drainQueueLaterOnExecutor()}get await(){return To((e)=>{let t=(n)=>e(fe(n));if(this._exitValue!==null){t(this._exitValue);return}return this.tell(Ua((n,r)=>{if(n._exitValue!==null)t(this._exitValue);else n.addObserver(t)})),D(()=>this.tell(Ua((n,r)=>{n.removeObserver(t)})))},this.id())}get inheritAll(){return xt((e,t)=>{let n=e.id(),r=e.getFiberRefs(),o=t.runtimeFlags,i=this.getFiberRefs(),a=Ag(r,n,i);e.setFiberRefs(a);let s=e.getFiberRef(xk),c=g(oc(o,s),Hh(Hr),Hh(Yu));return rg(c)})}get poll(){return D(()=>kr(this._exitValue))}unsafePoll(){return this._exitValue}interruptAsFork(e){return D(()=>this.tell(td(Mn(e))))}unsafeInterruptAsFork(e){this.tell(td(Mn(e)))}addObserver(e){if(this._exitValue!==null)e(this._exitValue);else this._observers.push(e)}removeObserver(e){this._observers=this._observers.filter((t)=>t!==e)}getFiberRefs(){return this.setFiberRef(xk,this.currentRuntimeFlags),this._fiberRefs}unsafeDeleteFiberRef(e){this._fiberRefs=Ec(this._fiberRefs,e)}getFiberRef(e){if(this._fiberRefs.locals.has(e))return this._fiberRefs.locals.get(e)[0][1];return e.initial}setFiberRef(e,t){this._fiberRefs=La(this._fiberRefs,{fiberId:this._fiberId,fiberRef:e,value:t}),this.refreshRefCache()}refreshRefCache(){this.currentDefaultServices=this.getFiberRef(Tc),this.currentTracer=this.currentDefaultServices.unsafeMap.get(vc.key),this.currentSupervisor=this.getFiberRef(Lq),this.currentScheduler=this.getFiberRef(Xp),this.currentContext=this.getFiberRef(Ti),this.currentSpan=this.currentContext.unsafeMap.get(Np.key)}setFiberRefs(e){this._fiberRefs=e,this.refreshRefCache()}addChild(e){this.getChildren().add(e)}removeChild(e){this.getChildren().delete(e)}transferChildren(e){let t=this._children;if(this._children=null,t!==null&&t.size>0){for(let n of t)if(n._exitValue===null)e.add(this.currentRuntimeFlags,n)}}drainQueueOnCurrentThread(){let e=!0;while(e){let t=Ic,n=globalThis[Io];globalThis[Io]=this;try{while(t===Ic)t=this._queue.length===0?Sq:this.evaluateMessageWhileSuspended(this._queue.splice(0,1)[0])}finally{this._running=!1,globalThis[Io]=n}if(this._queue.length>0&&!this._running)if(this._running=!0,t===gk)this.drainQueueLaterOnExecutor(),e=!1;else e=!0;else e=!1}}drainQueueLaterOnExecutor(){this.currentScheduler.scheduleTask(this.run,this.getFiberRef(Aa),this)}drainQueueWhileRunning(e,t){let n=t;while(this._queue.length>0){let r=this._queue.splice(0,1)[0];n=bq[r._tag](this,e,n,r)}return n}isInterrupted(){return!Eu(this.getFiberRef(yc))}addInterruptedCause(e){let t=this.getFiberRef(yc);this.setFiberRef(yc,Ct(t,e))}processNewInterruptSignal(e){this.addInterruptedCause(e),this.sendInterruptSignalToAllChildren()}sendInterruptSignalToAllChildren(){if(this._children===null||this._children.size===0)return!1;let e=!1;for(let t of this._children)t.tell(td(Mn(this.id()))),e=!0;return e}interruptAllChildren(){if(this.sendInterruptSignalToAllChildren()){let e=this._children.values();this._children=null;let t=!1;return dc({while:()=>!t,body:()=>{let r=e.next();if(!r.done)return Vr(r.value.await);else return D(()=>{t=!0})},step:()=>{}})}return null}reportExitValue(e){if(Lh(this.currentRuntimeFlags)){let t=this.getFiberRef(gc),n=this.id().startTimeMillis,r=Date.now();switch(xq.unsafeUpdate(r-n,t),hk.unsafeUpdate(-1,t),e._tag){case Vt:{gq.unsafeUpdate(1,t);break}case jt:{yq.unsafeUpdate(1,t);break}}}if(e._tag==="Failure"){let t=this.getFiberRef(wT);if(!xa(e.cause)&&t._tag==="Some")this.log("Fiber terminated with an unhandled error",e.cause,t)}}setExitValue(e){this._exitValue=e,this.reportExitValue(e);for(let t=this._observers.length-1;t>=0;t--)this._observers[t](e);this._observers=[]}getLoggers(){return this.getFiberRef(kq)}log(e,t,n){let r=Re(n)?n.value:this.getFiberRef(cg),o=this.getFiberRef(Tq);if(cO(o,r))return;let i=this.getFiberRef(xT),a=this.getFiberRef(yT),s=this.getLoggers(),c=this.getFiberRefs();if(js(s)>0){let l=zs(this.getFiberRef(Tc),bc),u=new Date(l.unsafeCurrentTimeMillis());eb(c,()=>{for(let p of s)p.log({fiberId:this.id(),logLevel:r,message:e,cause:t,context:c,spans:i,annotations:a,date:u})})}}evaluateMessageWhileSuspended(e){switch(e._tag){case ey:return gk;case Zg:{if(this.processNewInterruptSignal(e.cause),this._asyncInterruptor!==null)this._asyncInterruptor(ve(e.cause)),this._asyncInterruptor=null;return Ic}case Qg:return this._asyncInterruptor=null,this._asyncBlockingOn=null,this.evaluateEffect(e.effect),Ic;case Xg:return e.onFiber(this,this._exitValue!==null?oO:iO(this.currentRuntimeFlags,this._asyncBlockingOn)),Ic;default:return dd(e)}}evaluateEffect(e){this.currentSupervisor.onResume(this);try{let t=$r(this.currentRuntimeFlags)&&this.isInterrupted()?ve(this.getInterruptedCause()):e;while(t!==null){let n=t,r=this.runLoop(n);if(r===Kr){let o=zr.currentOp;if(zr.currentOp=null,o._op===ia)if(Lv(this.currentRuntimeFlags))this.tell(qO()),this.tell(ki(xn)),t=null;else t=xn;else if(o._op===ti)t=null}else{this.currentRuntimeFlags=g(this.currentRuntimeFlags,Mh(Yu));let o=this.interruptAllChildren();if(o!==null)t=B(o,()=>r);else{if(this._queue.length===0)this.setExitValue(r);else this.tell(ki(r));t=null}}}}finally{this.currentSupervisor.onSuspend(this)}}start(e){if(!this._running){this._running=!0;let t=globalThis[Io];globalThis[Io]=this;try{this.evaluateEffect(e)}finally{if(this._running=!1,globalThis[Io]=t,this._queue.length>0)this.drainQueueLaterOnExecutor()}}else this.tell(ki(e))}startFork(e){this.tell(ki(e))}patchRuntimeFlags(e,t){let n=ic(e,t);return globalThis[Io]=this,this.currentRuntimeFlags=n,n}initiateAsync(e,t){let n=!1,r=(o)=>{if(!n)n=!0,this.tell(ki(o))};if($r(e))this._asyncInterruptor=r;try{t(r)}catch(o){r(At(rn(o)))}}pushStack(e){if(this._stack.push(e),e._op==="OnStep")this._steps.push({refs:this.getFiberRefs(),flags:this.currentRuntimeFlags})}popStack(){let e=this._stack.pop();if(e){if(e._op==="OnStep")this._steps.pop();return e}return}getNextSuccessCont(){let e=this.popStack();while(e){if(e._op!==Ps)return e;e=this.popStack()}}getNextFailCont(){let e=this.popStack();while(e){if(e._op!==ta&&e._op!==ra&&e._op!==oa)return e;e=this.popStack()}}[nb](e){return D(()=>Ws(this.currentContext,e))}["Left"](e){return dt(e.left)}["None"](e){return dt(new xc)}["Right"](e){return Ie(e.right)}["Some"](e){return Ie(e.value)}["Micro"](e){return sc((t)=>{let n=t,r=TO(bO(e,this.currentContext));return r.addObserver((o)=>{if(o._tag==="Success")return n(Ie(o.value));switch(o.cause._tag){case"Interrupt":return n(ve(Mn(hn)));case"Fail":return n(dt(o.cause.error));case"Die":return n(ip(o.cause.defect))}}),sc((o)=>{n=(i)=>{o(nt)},r.unsafeInterrupt()})})}[eu](e){let t=yt(()=>e.effect_instruction_i0()),n=this.getNextSuccessCont();if(n!==void 0){if(!(n._op in Mc))dd(n);return Mc[n._op](this,n,t)}else return zr.currentOp=Ie(t),Kr}[Vt](e){let t=e,n=this.getNextSuccessCont();if(n!==void 0){if(!(n._op in Mc))dd(n);return Mc[n._op](this,n,t.effect_instruction_i0)}else return zr.currentOp=t,Kr}[jt](e){let t=e.effect_instruction_i0,n=this.getNextFailCont();if(n!==void 0)switch(n._op){case Ps:case na:if(!($r(this.currentRuntimeFlags)&&this.isInterrupted()))return yt(()=>n.effect_instruction_i1(t));else return ve(ku(t));case"OnStep":if(!($r(this.currentRuntimeFlags)&&this.isInterrupted()))return Ie(ve(t));else return ve(ku(t));case Is:if(this.patchRuntimeFlags(this.currentRuntimeFlags,n.patch),$r(this.currentRuntimeFlags)&&this.isInterrupted())return ve(Ct(t,this.getInterruptedCause()));else return ve(t);default:dd(n)}else return zr.currentOp=ve(t),Kr}[tu](e){return yt(()=>e.effect_instruction_i0(this,Fg(this.currentRuntimeFlags)))}["Blocked"](e){let t=this.getFiberRefs(),n=this.currentRuntimeFlags;if(this._steps.length>0){let r=[],o=this._steps[this._steps.length-1],i=this.popStack();while(i&&i._op!=="OnStep")r.push(i),i=this.popStack();this.setFiberRefs(o.refs),this.currentRuntimeFlags=o.flags;let a=KE(o.refs,t),s=oc(o.flags,n);return Ie(rp(e.effect_instruction_i0,xt((c)=>{while(r.length>0)c.pushStack(r.pop());return c.setFiberRefs(zE(c.id(),c.getFiberRefs())(a)),c.currentRuntimeFlags=ic(s)(c.currentRuntimeFlags),e.effect_instruction_i1})))}return Oo((r)=>B(vy(Wh(e.effect_instruction_i0)),()=>r(e.effect_instruction_i1)))}["RunBlocked"](e){return wq(e.effect_instruction_i0)}[ri](e){let t=e.effect_instruction_i0,n=this.currentRuntimeFlags,r=ic(n,t);if($r(r)&&this.isInterrupted())return ve(this.getInterruptedCause());else if(this.patchRuntimeFlags(this.currentRuntimeFlags,t),e.effect_instruction_i1){let o=oc(r,n);return this.pushStack(new Jh(o,e)),yt(()=>e.effect_instruction_i1(n))}else return xn}[ta](e){return this.pushStack(e),e.effect_instruction_i0}["OnStep"](e){return this.pushStack(e),e.effect_instruction_i0}[Ps](e){return this.pushStack(e),e.effect_instruction_i0}[na](e){return this.pushStack(e),e.effect_instruction_i0}[ti](e){return this._asyncBlockingOn=e.effect_instruction_i1,this.initiateAsync(this.currentRuntimeFlags,e.effect_instruction_i0),zr.currentOp=e,Kr}[ia](e){return this._isYielding=!1,zr.currentOp=e,Kr}[ra](e){let{effect_instruction_i0:t,effect_instruction_i1:n}=e;if(t())return this.pushStack(e),n();else return xn}[oa](e){return Mc[oa](this,e,void 0)}[ni](e){return yt(()=>e.commit())}runLoop(e){let t=e;this.currentOpCount=0;while(!0){if((this.currentRuntimeFlags&Fv)!==0)this.currentSupervisor.onEffect(this,t);if(this._queue.length>0)t=this.drainQueueWhileRunning(this.currentRuntimeFlags,t);if(!this._isYielding){this.currentOpCount+=1;let n=this.currentScheduler.shouldYield(this);if(n!==!1){this._isYielding=!0,this.currentOpCount=0;let r=t;t=B(fc({priority:n}),()=>r)}}try{if(t=this.currentTracer.context(()=>{if(vq!==t[vo]._V){let n=this.getFiberRef(vT);if(n._tag==="Some"){let r=t[vo]._V;this.log(`Executing an Effect versioned ${r} with a Runtime of version ${Ms()}, you may want to dedupe the effect dependencies, you can use the language service plugin to detect this at compile time: https://github.com/Effect-TS/language-service`,Dr,n)}}return this[t._op](t)},this),t===Kr){let n=zr.currentOp;if(n._op===ia||n._op===ti)return Kr;return zr.currentOp=null,n._op===Vt||n._op===jt?n:ve(rn(n))}}catch(n){if(t!==Kr&&!C(t,"_op")||!(t._op in this))t=Xh(`Not a valid effect: ${Er(t)}`);else if(TT(n))t=ve(Ct(rn(n),Mn(hn)));else t=ip(n)}}}run=()=>{this.drainQueueOnCurrentThread()}};Tq=V("effect/FiberRef/currentMinimumLogLevel",()=>St(lO("Info"))),Oq=V(Symbol.for("effect/Logger/defaultLogger"),()=>Eq(JO)),Rq=V(Symbol.for("effect/Logger/tracerLogger"),()=>od(({annotations:e,cause:t,context:n,fiberId:r,logLevel:o,message:i})=>{let a=Yg(_o(Ao(n,Ti),Np));if(a._tag==="None"||a.value._tag==="ExternalSpan")return;let s=Ws(Ao(n,Tc),bc),c={};for(let[l,u]of e)c[l]=u;if(c["effect.fiberId"]=av(r),c["effect.logLevel"]=o.label,t!==null&&t._tag!=="Empty")c["effect.cause"]=Nn(t,{renderErrorCause:!0});a.value.event(Er(Array.isArray(i)&&i.length===1?i[0]:i),s.unsafeCurrentTimeNanos(),c)})),kq=V(Symbol.for("effect/FiberRef/currentLoggers"),()=>hT(ci(Oq,Rq))),Sk=d((e)=>zf(e[0]),(e,t,n)=>xt((r)=>{let o=n?.batching===!0||n?.batching==="inherit"&&r.getFiberRef(bT);if(n?.discard)return Wg(n.concurrency,()=>Va(Dp,n?.concurrentFinalizers)((i)=>o?Pi(e,(a,s)=>i(t(a,s)),!0,!1,1):_i(e,(a,s)=>i(t(a,s)))),()=>Va(qp,n?.concurrentFinalizers)((i)=>Pi(e,(a,s)=>i(t(a,s)),o,!1)),(i)=>Va(Up(i),n?.concurrentFinalizers)((a)=>Pi(e,(s,c)=>a(t(s,c)),o,!1,i)));return Wg(n?.concurrency,()=>Va(Dp,n?.concurrentFinalizers)((i)=>o?_y(e,1,(a,s)=>i(t(a,s)),!0):yn(e,(a,s)=>i(t(a,s)))),()=>Va(qp,n?.concurrentFinalizers)((i)=>_k(e,(a,s)=>i(t(a,s)),o)),(i)=>Va(Up(i),n?.concurrentFinalizers)((a)=>_y(e,i,(s,c)=>a(t(s,c)),o)))})),Nc=Kt("effect/Scope"),Mq={[mp]:mp,[hp]:hp,pipe(){return T(this,arguments)},fork(e){return D(()=>{let t=Nq(e);if(this.state._tag==="Closed")return t.state=this.state,t;let n={},r=(o)=>t.close(o);return this.state.finalizers.set(n,r),Iq(t,(o)=>D(()=>{if(this.state._tag==="Open")this.state.finalizers.delete(n)})),t})},close(e){return Ce(()=>{if(this.state._tag==="Closed")return nt;let t=Array.from(this.state.finalizers.values()).reverse();if(this.state={_tag:"Closed",exit:e},t.length===0)return nt;return Eg(this.strategy)?g(yn(t,(n)=>Eo(n(e))),B((n)=>g(Oi(n),On(Sc),Oe(()=>xn)))):Og(this.strategy)?g(_k(t,(n)=>Eo(n(e)),!1),B((n)=>g(Oi(n,{parallel:!0}),On(Sc),Oe(()=>xn)))):g(_y(t,this.strategy.parallelism,(n)=>Eo(n(e)),!1),B((n)=>g(Oi(n,{parallel:!0}),On(Sc),Oe(()=>xn))))})},addFinalizer(e){return Ce(()=>{if(this.state._tag==="Closed")return e(this.state.exit);return this.state.finalizers.set({},e),nt})}},Ty=d(2,(e,t)=>mg(e,Js(jw(Nc,t)))),xk=gT(Dv),Lq=Fq(Ai),wk=d(2,(e,t)=>Oo((n)=>gn(n(e),{onFailure:(r)=>gn(t,{onFailure:(o)=>At(Ct(r,o)),onSuccess:()=>At(r)}),onSuccess:(r)=>jr(t,r)})))});var Tk,Ek;var Ok=x(()=>{rt();Tk=lg,Ek=Pa});class Ak{context;runtimeFlags;fiberRefs;constructor(e,t,n){this.context=e,this.runtimeFlags=t,this.fiberRefs=n}pipe(){return T(this,arguments)}}var Ry=(e)=>function(){if(arguments.length===1){let t=arguments[0];return(n,...r)=>e(t,n,...r)}return e.apply(this,arguments)},Rk,$q,kk,jq=(e)=>{let t=Error.stackTraceLimit;Error.stackTraceLimit=0;let n=new kk(e);return Error.stackTraceLimit=t,n},Oy,md,Ck,Vq=(e)=>{let t=Error.stackTraceLimit;Error.stackTraceLimit=0;let n=new Ck(e);return Error.stackTraceLimit=t,n},Bq=(e)=>{let t=e;switch(t._op){case"Failure":case"Success":return t;case"Left":return _c(t.left);case"Right":return Ie(t.right);case"Some":return Ie(t.value);case"None":return _c(new xc)}},Kq,zq=(e)=>new Ak(e.context,e.runtimeFlags,e.fiberRefs),Wq,Pk,Ik,Mk;var Nk=x(()=>{mn();pe();wa();Ng();Ve();Ge();be();Qp();Ok();Sa();rt();Lp();Ey();ty();ac();ld();Rk=Ry((e,t,n)=>{let r=Uu(),o=[[Ti,[[r,e.context]]]];if(n?.scheduler)o.push([Xp,[[r,n.scheduler]]]);let i=ME(e.fiberRefs,{entries:o,forkAs:r});if(n?.updateRefs)i=n.updateRefs(i,r);let a=new fd(r,i,e.runtimeFlags),s=t;if(n?.scope)s=B(Ek(n.scope,Fa),(l)=>Ro(gp(l,lc((u)=>O(u,a.id())?nt:hc(a,u))),Ca(t,(u)=>Tk(l,u))));let c=a.currentSupervisor;if(c!==Ai)c.onStart(e.context,s,A(),a),a.addObserver((l)=>c.onEnd(l,a));if(Rc.add(e.runtimeFlags,a),n?.immediate===!1)a.resume(s);else a.start(s);return a}),$q=Ry((e,t)=>{let n=Kq(e)(t);if(n._tag==="Failure")throw Vq(n.effect_instruction_i0);return n.effect_instruction_i0});kk=class kk extends Error{fiber;_tag="AsyncFiberException";constructor(e){super(`Fiber #${e.id().id} cannot be resolved synchronously. This is caused by using runSync on an effect that performs async work`);this.fiber=e,this.name=this._tag,this.stack=this.message}};Oy=Symbol.for("effect/Runtime/FiberFailure"),md=Symbol.for("effect/Runtime/FiberFailure/Cause");Ck=class Ck extends Error{[Oy];[md];constructor(e){let t=Vs(e)[0];super(t?.message||"An error has occurred");if(this[Oy]=Oy,this[md]=e,this.name=t?`(FiberFailure) ${t.name}`:"FiberFailure",t?.stack)this.stack=t.stack}toJSON(){return{_id:"FiberFailure",cause:this[md].toJSON()}}toString(){return"(FiberFailure) "+Nn(this[md],{renderErrorCause:!0})}[ne](){return this.toString()}};Kq=Ry((e,t)=>{let n=Bq(t);if(n)return n;let r=new Oc,o=Rk(e)(t,{scheduler:r});r.flush();let i=o.unsafePoll();if(i)return i;return pg(op(jq(o),bp(o)))});Wq=Fh(Hr,Ih,Ph),Pk=zq({context:So(),runtimeFlags:Wq,fiberRefs:NE()}),Ik=Rk(Pk),Mk=$q(Pk)});var Fk,Fc,Lc,an,Lk,hd,Dk,Ii,Ln,qk,Uk;var Hk=x(()=>{rt();Ey();Nk();Fk=Ra,Fc=Sk,Lc=Ce,an=nt,Lk=cc,hd=Ke,Dk=bi,Ii=Si,Ln=B,qk=Ik,Uk=Mk});var ky=(e,t)=>{switch(t._tag){case"StringKeyword":case"TemplateLiteral":return Object.keys(e);case"SymbolKeyword":return Object.getOwnPropertySymbols(e);case"Refinement":return ky(e,t.from)}},Dc=(e)=>{let t=!1,n;return()=>{if(t)return n;return n=e(),t=!0,n}},Cy=(e)=>Array.isArray(e),jk=(e)=>!Array.isArray(e),$k=(e)=>`[${As(e)}]`,gd=(e)=>Cy(e)?e.map($k).join(""):$k(e);var qc=x(()=>{Ve()});var No=(e,t,n,r)=>{let o=e;if(n&&we(n))o+=`
31
+ at path: ${gd(n)}`;if(t!==void 0)o+=`
32
+ details: ${t}`;if(r)o+=`
33
+ schema (${r._tag}): ${r}`;return o},Vk=(e)=>No("Invalid Argument",e),Bk=(e)=>No("Unsupported key schema",void 0,void 0,e),Kk=(e)=>No("Unsupported literal",`literal value: ${Zn(e)}`),Ay=(e)=>No("Duplicate index signature",`${e} index signature`),zk,Wk,Py=(e)=>No("Duplicate property signature transformation",`Duplicate key ${Zn(e)}`),Iy=(e)=>No("Duplicate property signature",`Duplicate key ${Zn(e)}`);var My=x(()=>{Be();Ve();qc();zk=No("Unsupported index signature parameter","An index signature parameter type must be `string`, `symbol`, a template literal type or a refinement of the previous types"),Wk=No("Invalid element","A required element cannot follow an optional element. ts(1257)")});var Gk,Yk,Zk,Xk,Qk,eC,tC;var nC=x(()=>{Gk=Symbol.for("effect/SchemaId/DateFromSelf"),Yk=Symbol.for("effect/SchemaId/GreaterThan"),Zk=Symbol.for("effect/SchemaId/GreaterThanOrEqualTo"),Xk=Symbol.for("effect/SchemaId/Int"),Qk=Symbol.for("effect/SchemaId/MinLength"),eC=Symbol.for("effect/SchemaId/MaxLength"),tC=Symbol.for("effect/SchemaId/MinItems")});class Ba{typeParameters;decodeUnknown;encodeUnknown;annotations;_tag="Declaration";constructor(e,t,n,r={}){this.typeParameters=e,this.decodeUnknown=t,this.encodeUnknown=n,this.annotations=r}toString(){return Oe(sr(this),()=>"<declaration schema>")}toJSON(){return{_tag:this._tag,typeParameters:this.typeParameters.map((e)=>e.toJSON()),annotations:He(this.annotations)}}}class Mi{literal;annotations;_tag="Literal";constructor(e,t={}){this.literal=e,this.annotations=t}toString(){return Oe(sr(this),()=>Zn(this.literal))}toJSON(){return{_tag:this._tag,literal:ro(this.literal)?String(this.literal):this.literal,annotations:He(this.annotations)}}}class wd{symbol;annotations;_tag="UniqueSymbol";constructor(e,t={}){this.symbol=e,this.annotations=t}toString(){return Oe(sr(this),()=>Zn(this.symbol))}toJSON(){return{_tag:this._tag,symbol:String(this.symbol),annotations:He(this.annotations)}}}class hC{annotations;_tag="UndefinedKeyword";constructor(e={}){this.annotations=e}toString(){return Dn(this)}toJSON(){return{_tag:this._tag,annotations:He(this.annotations)}}}class gC{annotations;_tag="VoidKeyword";constructor(e={}){this.annotations=e}toString(){return Dn(this)}toJSON(){return{_tag:this._tag,annotations:He(this.annotations)}}}class yC{annotations;_tag="NeverKeyword";constructor(e={}){this.annotations=e}toString(){return Dn(this)}toJSON(){return{_tag:this._tag,annotations:He(this.annotations)}}}class xC{annotations;_tag="UnknownKeyword";constructor(e={}){this.annotations=e}toString(){return Dn(this)}toJSON(){return{_tag:this._tag,annotations:He(this.annotations)}}}class SC{annotations;_tag="AnyKeyword";constructor(e={}){this.annotations=e}toString(){return Dn(this)}toJSON(){return{_tag:this._tag,annotations:He(this.annotations)}}}class bC{annotations;_tag="StringKeyword";constructor(e={}){this.annotations=e}toString(){return Dn(this)}toJSON(){return{_tag:this._tag,annotations:He(this.annotations)}}}class vC{annotations;_tag="NumberKeyword";constructor(e={}){this.annotations=e}toString(){return Dn(this)}toJSON(){return{_tag:this._tag,annotations:He(this.annotations)}}}class EC{annotations;_tag="BooleanKeyword";constructor(e={}){this.annotations=e}toString(){return Dn(this)}toJSON(){return{_tag:this._tag,annotations:He(this.annotations)}}}class RC{annotations;_tag="BigIntKeyword";constructor(e={}){this.annotations=e}toString(){return Dn(this)}toJSON(){return{_tag:this._tag,annotations:He(this.annotations)}}}class kC{annotations;_tag="SymbolKeyword";constructor(e={}){this.annotations=e}toString(){return Dn(this)}toJSON(){return{_tag:this._tag,annotations:He(this.annotations)}}}class AC{annotations;_tag="ObjectKeyword";constructor(e={}){this.annotations=e}toString(){return Dn(this)}toJSON(){return{_tag:this._tag,annotations:He(this.annotations)}}}class Ka{type;annotations;constructor(e,t={}){this.type=e,this.annotations=t}toJSON(){return{type:this.type.toJSON(),annotations:He(this.annotations)}}toString(){return String(this.type)}}class $c{elements;rest;isReadonly;annotations;_tag="TupleType";constructor(e,t,n,r={}){this.elements=e,this.rest=t,this.isReadonly=n,this.annotations=r;let o=!1,i=!1;for(let a of e)if(a.isOptional)o=!0;else if(o){i=!0;break}if(i||o&&t.length>1)throw Error(Wk)}toString(){return Oe(sr(this),()=>o2(this))}toJSON(){return{_tag:this._tag,elements:this.elements.map((e)=>e.toJSON()),rest:this.rest.map((e)=>e.toJSON()),isReadonly:this.isReadonly,annotations:He(this.annotations)}}}class za{type;isReadonly;parameter;constructor(e,t,n){if(this.type=t,this.isReadonly=n,IC(e))this.parameter=e;else throw Error(zk)}toString(){return(this.isReadonly?"readonly ":"")+`[x: ${this.parameter}]: ${this.type}`}toJSON(){return{parameter:this.parameter.toJSON(),type:this.type.toJSON(),isReadonly:this.isReadonly}}}class cr{annotations;_tag="TypeLiteral";propertySignatures;indexSignatures;constructor(e,t,n={}){this.annotations=n;let r={};for(let i=0;i<e.length;i++){let a=e[i].name;if(Object.prototype.hasOwnProperty.call(r,a))throw Error(Iy(a));r[a]=null}let o={string:!1,symbol:!1};for(let i=0;i<t.length;i++){let a=px(t[i].parameter);if(Ed(a)){if(o.string)throw Error(Ay("string"));o.string=!0}else if(CC(a)){if(o.symbol)throw Error(Ay("symbol"));o.symbol=!0}}this.propertySignatures=e,this.indexSignatures=t}toString(){return Oe(sr(this),()=>i2(this))}toJSON(){return{_tag:this._tag,propertySignatures:this.propertySignatures.map((e)=>e.toJSON()),indexSignatures:this.indexSignatures.map((e)=>e.toJSON()),annotations:He(this.annotations)}}}class Ut{types;annotations;static make=(e,t)=>Od(e)?new Ut(e,t):e.length===1?e[0]:Td;static unify=(e,t)=>Ut.make(c2(MC(e)),t);_tag="Union";constructor(e,t={}){this.types=e,this.annotations=t}toString(){return Oe(sr(this),()=>this.types.map(String).join(" | "))}toJSON(){return{_tag:this._tag,types:this.types.map((e)=>e.toJSON()),annotations:He(this.annotations)}}}class Rd{f;annotations;_tag="Suspend";constructor(e,t={}){this.f=e,this.annotations=t,this.f=Dc(e)}toString(){return sr(this).pipe(En(()=>Rn(vb(this.f)(),(e)=>sr(e))),Oe(()=>"<suspended schema>"))}toJSON(){let e=this.f(),t=Ny.get(e);if(t)return t;return Ny.set(e,{_tag:this._tag}),t={_tag:this._tag,ast:e.toJSON(),annotations:He(this.annotations)},Ny.set(e,t),t}}class jc{from;filter;annotations;_tag="Refinement";constructor(e,t,n={}){this.from=e,this.filter=t,this.annotations=n}toString(){return Uc(this).pipe(Oe(()=>Je(qC(this),{onNone:()=>`{ ${this.from} | filter }`,onSome:(e)=>Vc(this.from)?String(this.from)+" & "+e:e})))}toJSON(){return{_tag:this._tag,from:this.from.toJSON(),annotations:He(this.annotations)}}}class ax{from;to;transformation;annotations;_tag="Transformation";constructor(e,t,n,r={}){this.from=e,this.to=t,this.transformation=n,this.annotations=r}toString(){return Oe(sr(this),()=>`(${String(this.from)} <-> ${String(this.to)})`)}toJSON(){return{_tag:this._tag,from:this.from.toJSON(),to:this.to.toJSON(),annotations:He(this.annotations)}}}class sx{from;to;decode;encode;constructor(e,t,n,r){this.from=e,this.to=t,this.decode=n,this.encode=r}}class cx{propertySignatureTransformations;_tag="TypeLiteralTransformation";constructor(e){this.propertySignatureTransformations=e;let t={},n={};for(let r of e){let o=r.from;if(t[o])throw Error(Py(o));t[o]=!0;let i=r.to;if(n[i])throw Error(Py(i));n[i]=!0}}}function Sn(e,t){let n=!1,r=oi(e.length);for(let o=0;o<e.length;o++){let i=e[o],a=t(i);if(a!==i)n=!0;r[o]=a}return n?r:e}function f2(e){return Je(Zy(e),{onNone:()=>"",onSome:(t)=>t.map((n)=>` & Brand<${Zn(n)}>`).join("")})}var oC,Ly,iC,Dy,xd,Sd,zt,_d,Wr,qy,Uy,Hy,$y,jy,Vy,aC,By,Ky,zy,Wy,Jy,Gy,Yy,Pt,Zy,sC,cC,Xy,Qy,Uc,ex,lC,uC,pC,dC,fC,tx,Zq,nx=(e)=>Ob(Zq(e),(t)=>t===!0),rx,Xq,Qq=(e)=>En(Xq(e),()=>Uc(e)),Hc=(e)=>(t)=>t._tag===e,bd,mC,vd,e2,Td,ox,_C,wC,Ed,TC,OC,t2,n2,CC,r2,Fo,PC=(e)=>e.map((t)=>t.type),o2=(e)=>{let t=e.elements.map(String).join(", ");return Cb(e.rest,{onEmpty:()=>`readonly [${t}]`,onNonEmpty:(n,r)=>{let o=String(n),i=o.includes(" | ")?`(${o})`:o;if(r.length>0){let a=r.map(String).join(", ");if(e.elements.length>0)return`readonly [${t}, ...${i}[], ${a}]`;else return`readonly [...${i}[], ${a}]`}else if(e.elements.length>0)return`readonly [${t}, ...${i}[]]`;else return`ReadonlyArray<${o}>`}})},st,IC=(e)=>{switch(e._tag){case"StringKeyword":case"SymbolKeyword":case"TemplateLiteral":return!0;case"Refinement":return IC(e.from)}return!1},rC=(e)=>e.map(String).join("; "),i2=(e)=>{if(e.propertySignatures.length>0){let t=e.propertySignatures.map(String).join("; ");if(e.indexSignatures.length>0)return`{ ${t}; ${rC(e.indexSignatures)} }`;else return`{ ${t} }`}else if(e.indexSignatures.length>0)return`{ ${rC(e.indexSignatures)} }`;else return"{}"},a2,s2,MC=(e)=>Ds(e,(t)=>ix(t)?MC(t.types):[t]),c2=(e)=>{let t=a2(e),n=[],r={},o=[];for(let i of t)switch(i._tag){case"NeverKeyword":break;case"AnyKeyword":return[_C];case"UnknownKeyword":return[ox];case"ObjectKeyword":case"UndefinedKeyword":case"VoidKeyword":case"StringKeyword":case"NumberKeyword":case"BooleanKeyword":case"BigIntKeyword":case"SymbolKeyword":{if(!r[i._tag])r[i._tag]=i,n.push(i);break}case"Literal":{let a=typeof i.literal;switch(a){case"string":case"number":case"bigint":case"boolean":{let s=s2[a];if(!r[s]&&!o.includes(i.literal))o.push(i.literal),n.push(i);break}case"object":{if(!o.includes(i.literal))o.push(i.literal),n.push(i);break}}break}case"UniqueSymbol":{if(!r.SymbolKeyword&&!o.includes(i.symbol))o.push(i.symbol),n.push(i);break}case"TupleType":{if(!r.ObjectKeyword)n.push(i);break}case"TypeLiteral":{if(i.propertySignatures.length===0&&i.indexSignatures.length===0){if(!r["{}"])r["{}"]=i,n.push(i)}else if(!r.ObjectKeyword)n.push(i);break}default:n.push(i)}return n},NC=(e,t)=>e.map(t),Od=(e)=>e.length>1,ix,Ny,Vc,kd,Bc=(e,t)=>{let n=Object.getOwnPropertyDescriptors(e),r={...e.annotations};delete r[Sd];let o={...r,...t},i=tx(e);if(Re(i))o[Gy]=Bc(i.value,t);return n.annotations.value=o,Object.create(Object.getPrototypeOf(e),n)},l2="[\\s\\S]*?",u2="[+-]?\\d*\\.?\\d+(?:[Ee][+-]?\\d+)?",FC=(e,t)=>{switch(e._tag){case"Literal":return Na(String(e.literal));case"StringKeyword":return l2;case"NumberKeyword":return u2;case"TemplateLiteral":return LC(e,t,!1);case"Union":return e.types.map((n)=>FC(n,t)).join("|")}},p2=(e,t,n,r)=>{if(ix(e)){if(n&&!r)return`(?:${t})`}else if(!n||!r)return t;return`(${t})`},LC=(e,t,n)=>{let r="";if(e.head!==""){let o=Na(e.head);r+=t&&n?`(${o})`:o}for(let o of e.spans){let i=FC(o.type,t);if(r+=p2(o.type,i,t,n),o.literal!==""){let a=Na(o.literal);r+=t&&n?`(${a})`:a}}return r},DC=(e)=>new RegExp(`^${LC(e,!1,!0)}$`),lx=(e,t)=>{let n=[],r=[],o=(i)=>{switch(i._tag){case"NeverKeyword":break;case"StringKeyword":case"SymbolKeyword":case"TemplateLiteral":case"Refinement":r.push(new za(i,t,!0));break;case"Literal":if(gt(i.literal)||Qt(i.literal))n.push(new st(i.literal,t,!1,!0));else throw Error(Kk(i.literal));break;case"Enums":{for(let[a,s]of i.enums)n.push(new st(s,t,!1,!0));break}case"UniqueSymbol":n.push(new st(i.symbol,t,!1,!0));break;case"Union":i.types.forEach(o);break;default:throw Error(Bk(i))}};return o(e),{propertySignatures:n,indexSignatures:r}},ux=(e)=>(t)=>{let n=void 0;for(let r of e)if(Object.prototype.hasOwnProperty.call(t.annotations,r)){if(n===void 0)n={};n[r]=t.annotations[r]}return n},d2,at=(e)=>{switch(e._tag){case"Declaration":{let t=Sn(e.typeParameters,at);return t===e.typeParameters?e:new Ba(t,e.decodeUnknown,e.encodeUnknown,e.annotations)}case"TupleType":{let t=Sn(e.elements,(o)=>{let i=at(o.type);return i===o.type?o:new Fo(i,o.isOptional)}),n=PC(e.rest),r=Sn(n,at);return t===e.elements&&r===n?e:new $c(t,r.map((o)=>new Ka(o)),e.isReadonly,e.annotations)}case"TypeLiteral":{let t=Sn(e.propertySignatures,(r)=>{let o=at(r.type);return o===r.type?r:new st(r.name,o,r.isOptional,r.isReadonly)}),n=Sn(e.indexSignatures,(r)=>{let o=at(r.type);return o===r.type?r:new za(r.parameter,o,r.isReadonly)});return t===e.propertySignatures&&n===e.indexSignatures?e:new cr(t,n,e.annotations)}case"Union":{let t=Sn(e.types,at);return t===e.types?e:Ut.make(t,e.annotations)}case"Suspend":return new Rd(()=>at(e.f()),e.annotations);case"Refinement":{let t=at(e.from);return t===e.from?e:new jc(t,e.filter,e.annotations)}case"Transformation":{let t=d2(e);return at(t!==void 0?Bc(e.to,t):e.to)}}return e},Fy=(e)=>{switch(e._tag){case"Transformation":return e.from;case"Refinement":return Fy(e.from);case"Suspend":return Fy(e.f())}},ar=(e,t)=>{switch(e._tag){case"Declaration":{let n=Sn(e.typeParameters,(r)=>ar(r,t));return n===e.typeParameters?e:new Ba(n,e.decodeUnknown,e.encodeUnknown)}case"TupleType":{let n=Sn(e.elements,(i)=>{let a=ar(i.type,t);return a===i.type?i:new Fo(a,i.isOptional)}),r=PC(e.rest),o=Sn(r,(i)=>ar(i,t));return n===e.elements&&o===r?e:new $c(n,o.map((i)=>new Ka(i)),e.isReadonly)}case"TypeLiteral":{let n=Sn(e.propertySignatures,(o)=>{let i=ar(o.type,t);return i===o.type?o:new st(o.name,i,o.isOptional,o.isReadonly)}),r=Sn(e.indexSignatures,(o)=>{let i=ar(o.type,t);return i===o.type?o:new za(o.parameter,i,o.isReadonly)});return n===e.propertySignatures&&r===e.indexSignatures?e:new cr(n,r)}case"Union":{let n=Sn(e.types,(r)=>ar(r,t));return n===e.types?e:Ut.make(n)}case"Suspend":{let n=void 0,r=Qq(e);if(Re(r)){let o=t?"Bound":"";n={[rx]:`${r.value}Encoded${o}`}}return new Rd(()=>ar(e.f(),t),n)}case"Refinement":{let n=ar(e.from,t);if(t){if(n===e.from)return e;if(Fy(e.from)===void 0&&nx(e))return new jc(n,e.filter,e.annotations);return n}else return n}case"Transformation":return ar(e.from,t)}return e},Cd=(e)=>ar(e,!1),He=(e)=>{let t={};for(let n of Object.getOwnPropertySymbols(e))t[String(n)]=e[n];return t},px=(e)=>{switch(e._tag){case"StringKeyword":case"SymbolKeyword":case"TemplateLiteral":return e;case"Refinement":return px(e.from)}},Dn=(e)=>Oe(sr(e),()=>e._tag),qC=(e)=>Xy(e).pipe(En(()=>ex(e)),En(()=>Qy(e)),On((t)=>t+f2(e))),sr=(e)=>En(Uc(e),()=>qC(e));var dx=x(()=>{Be();j();Ve();My();qc();wc();Ge();au();ye();_g();oC=Symbol.for("effect/annotation/TypeConstructor"),Ly=Symbol.for("effect/annotation/Brand"),iC=Symbol.for("effect/annotation/SchemaId"),Dy=Symbol.for("effect/annotation/Message"),xd=Symbol.for("effect/annotation/MissingMessage"),Sd=Symbol.for("effect/annotation/Identifier"),zt=Symbol.for("effect/annotation/Title"),_d=Symbol.for("effect/annotation/AutoTitle"),Wr=Symbol.for("effect/annotation/Description"),qy=Symbol.for("effect/annotation/Examples"),Uy=Symbol.for("effect/annotation/Default"),Hy=Symbol.for("effect/annotation/JSONSchema"),$y=Symbol.for("effect/annotation/Arbitrary"),jy=Symbol.for("effect/annotation/Pretty"),Vy=Symbol.for("effect/annotation/Equivalence"),aC=Symbol.for("effect/annotation/Documentation"),By=Symbol.for("effect/annotation/Concurrency"),Ky=Symbol.for("effect/annotation/Batching"),zy=Symbol.for("effect/annotation/ParseIssueTitle"),Wy=Symbol.for("effect/annotation/ParseOptions"),Jy=Symbol.for("effect/annotation/DecodingFallback"),Gy=Symbol.for("effect/annotation/Surrogate"),Yy=Symbol.for("effect/annotation/StableFilter"),Pt=d(2,(e,t)=>Object.prototype.hasOwnProperty.call(e.annotations,t)?F(e.annotations[t]):A()),Zy=Pt(Ly),sC=Pt(Dy),cC=Pt(xd),Xy=Pt(zt),Qy=Pt(_d),Uc=Pt(Sd),ex=Pt(Wr),lC=Pt(By),uC=Pt(Ky),pC=Pt(zy),dC=Pt(Wy),fC=Pt(Jy),tx=Pt(Gy),Zq=Pt(Yy),rx=Symbol.for("effect/annotation/JSONIdentifier"),Xq=Pt(rx);bd=Hc("Literal"),mC=new Mi(null);vd=new hC({[zt]:"undefined"});e2=new gC({[zt]:"void"});Td=new yC({[zt]:"never"});ox=new xC({[zt]:"unknown"});_C=new SC({[zt]:"any"});wC=new bC({[zt]:"string",[Wr]:"a string"}),Ed=Hc("StringKeyword");TC=new vC({[zt]:"number",[Wr]:"a number"});OC=new EC({[zt]:"boolean",[Wr]:"a boolean"});t2=new RC({[zt]:"bigint",[Wr]:"a bigint"});n2=new kC({[zt]:"symbol",[Wr]:"a symbol"}),CC=Hc("SymbolKeyword");r2=new AC({[zt]:"object",[Wr]:"an object in the TypeScript meaning, i.e. the `object` type"});Fo=class Fo extends Ka{isOptional;constructor(e,t,n={}){super(e,n);this.isOptional=t}toJSON(){return{type:this.type.toJSON(),isOptional:this.isOptional,annotations:He(this.annotations)}}toString(){return String(this.type)+(this.isOptional?"?":"")}};st=class st extends Fo{name;isReadonly;constructor(e,t,n,r,o){super(t,n,o);this.name=e,this.isReadonly=r}toString(){return(this.isReadonly?"readonly ":"")+String(this.name)+(this.isOptional?"?":"")+": "+this.type}toJSON(){return{name:String(this.name),type:this.type.toJSON(),isOptional:this.isOptional,isReadonly:this.isReadonly,annotations:He(this.annotations)}}};a2=Ar(iu(ir,(e)=>{switch(e._tag){case"AnyKeyword":return 0;case"UnknownKeyword":return 1;case"ObjectKeyword":return 2;case"StringKeyword":case"NumberKeyword":case"BooleanKeyword":case"BigIntKeyword":case"SymbolKeyword":return 3}return 4})),s2={string:"StringKeyword",number:"NumberKeyword",boolean:"BooleanKeyword",bigint:"BigIntKeyword"};ix=Hc("Union"),Ny=V(Symbol.for("effect/Schema/AST/toJSONMemoMap"),()=>new WeakMap);Vc=Hc("Refinement"),kd={};d2=ux([qy,Uy,Hy,$y,jy,Vy])});class ct{path;actual;issue;_tag="Pointer";constructor(e,t,n){this.path=e,this.actual=t,this.issue=n}}class hx{actual;message;_tag="Unexpected";constructor(e,t){this.actual=e,this.message=t}}class Wa{ast;message;_tag="Missing";actual=void 0;constructor(e,t){this.ast=e,this.message=t}}class $e{ast;actual;issues;output;_tag="Composite";constructor(e,t,n,r){this.ast=e,this.actual=t,this.issues=n,this.output=r}}class Pd{ast;actual;kind;issue;_tag="Refinement";constructor(e,t,n,r){this.ast=e,this.actual=t,this.kind=n,this.issue=r}}class Id{ast;actual;kind;issue;_tag="Transformation";constructor(e,t,n,r){this.ast=e,this.actual=t,this.kind=n,this.issue=r}}class _n{ast;actual;message;_tag="Type";constructor(e,t,n){this.ast=e,this.actual=t,this.message=n}}class gx{ast;actual;message;_tag="Forbidden";constructor(e,t,n){this.ast=e,this.actual=t,this.message=n}}function qn(e){return e.sort(x2).map((t)=>t[1])}function T2(e){return ex(e).pipe(En(()=>Xy(e)),En(()=>Qy(e)),En(()=>Uc(e)),Oe(()=>`{ ${e.from} | filter }`))}function E2(e){if(e.message!==void 0)return e.message;return`Expected ${Vc(e.ast)?T2(e.ast):String(e.ast)}, actual ${Zn(e.actual)}`}var HC,VC,xx=(e)=>new VC({issue:e}),BC,KC,Jt,Jr,Un,Md,zC,WC=(e,t)=>{if(t===void 0||Qt(t))return e;if(e===void 0)return t;return{...e,...t}},JC=(e,t,n)=>{let r=It(e,t);return(o,i)=>r(o,WC(n,i))},m2=(e,t,n)=>{let r=JC(e,t,n);return(o,i)=>um(r(o,i),xx)},GC=(e,t)=>JC(e.ast,!0,t),Nd=(e,t)=>m2(at(e.ast),!0,t),h2,g2,It=(e,t)=>{let n=t?h2:g2,r=n.get(e);if(r)return r;let o=y2(e,t),i=dC(e),a=Re(i)?(l,u)=>o(l,WC(u,i.value)):o,s=fC(e),c=t&&Re(s)?(l,u)=>zc(zC(a(l,u),s.value),e,l,u):a;return n.set(e,c),c},fx=(e)=>Bt(lC(e)),mx=(e)=>Bt(uC(e)),y2=(e,t)=>{switch(e._tag){case"Refinement":if(t){let n=It(e.from,!0);return(r,o)=>{o=o??kd;let i=o?.errors==="all",a=Jr(zC(n(r,o),(s)=>{let c=new Pd(e,r,"From",s);if(i&&nx(e)&&eA(s))return Je(e.filter(r,o,e),{onNone:()=>W(c),onSome:(l)=>W(new $e(e,r,[c,new Pd(e,r,"Predicate",l)]))});return W(c)}),(s)=>Je(e.filter(s,o,e),{onNone:()=>Q(s),onSome:(c)=>W(new Pd(e,r,"Predicate",c))}));return zc(a,e,r,o)}}else{let n=It(at(e),!0),r=It(ZC(e.from),!1);return(o,i)=>zc(Jr(n(o,i),(a)=>r(a,i)),e,o,i)}case"Transformation":{let n=S2(e.transformation,t),r=t?It(e.from,!0):It(e.to,!1),o=t?It(e.to,!0):It(e.from,!1);return(i,a)=>zc(Jr(Md(r(i,a),(s)=>new Id(e,i,t?"Encoded":"Type",s)),(s)=>Jr(Md(n(s,a??kd,e,i),(c)=>new Id(e,i,"Transformation",c)),(c)=>Md(o(c,a),(l)=>new Id(e,i,t?"Type":"Encoded",l)))),e,i,a)}case"Declaration":{let n=t?e.decodeUnknown(...e.typeParameters):e.encodeUnknown(...e.typeParameters);return(r,o)=>zc(n(r,o??kd,e),e,r,o)}case"Literal":return Wt(e,(n)=>n===e.literal);case"UniqueSymbol":return Wt(e,(n)=>n===e.symbol);case"UndefinedKeyword":return Wt(e,W_);case"NeverKeyword":return Wt(e,J_);case"UnknownKeyword":case"AnyKeyword":case"VoidKeyword":return Q;case"StringKeyword":return Wt(e,gt);case"NumberKeyword":return Wt(e,Qt);case"BooleanKeyword":return Wt(e,Go);case"BigIntKeyword":return Wt(e,ro);case"SymbolKeyword":return Wt(e,Yo);case"ObjectKeyword":return Wt(e,qt);case"Enums":return Wt(e,(n)=>e.enums.some(([r,o])=>o===n));case"TemplateLiteral":{if(e.spans.every((r)=>Ed(r.type)))return Wt(e,(r)=>{if(!gt(r)||!r.startsWith(e.head))return!1;let o=e.head.length;for(let a=0;a<e.spans.length-1;a++){let s=e.spans[a].literal,c=r.indexOf(s,o);if(c===-1)return!1;o=c+s.length}let i=e.spans[e.spans.length-1].literal;return r.endsWith(i)&&r.length-i.length>=o});let n=DC(e);return Wt(e,(r)=>gt(r)&&n.test(r))}case"TupleType":{let n=e.elements.map((l)=>It(l.type,t)),r=e.rest.map((l)=>It(l.type,t)),o=e.elements.filter((l)=>!l.isOptional);if(e.rest.length>0)o=o.concat(e.rest.slice(1));let i=o.length,a=e.elements.length>0?e.elements.map((l,u)=>u).join(" | "):"never",s=fx(e),c=mx(e);return(l,u)=>{if(!ym(l))return W(new _n(e,l));let p=u?.errors==="all",f=[],h=0,m=[],w=l.length;for(let P=w;P<=i-1;P++){let z=new ct(P,l,new Wa(o[P-w]));if(p){f.push([h++,z]);continue}else return W(new $e(e,l,z,m))}if(e.rest.length===0)for(let P=e.elements.length;P<=w-1;P++){let z=new ct(P,l,new hx(l[P],`is unexpected, expected: ${a}`));if(p){f.push([h++,z]);continue}else return W(new $e(e,l,z,m))}let S=0,y=void 0;for(;S<n.length;S++)if(w<S+1){if(e.elements[S].isOptional)continue}else{let P=n[S],z=P(l[S],u);if(Jt(z)){if(Ee(z)){let X=new ct(S,l,z.left);if(p){f.push([h++,X]);continue}else return W(new $e(e,l,X,qn(m)))}m.push([h++,z.right])}else{let X=h++,U=S;if(!y)y=[];y.push(({es:te,output:L})=>Ln(Ii(z),(se)=>{if(Ee(se)){let ce=new ct(U,l,se.left);if(p)return te.push([X,ce]),an;else return W(new $e(e,l,ce,qn(L)))}return L.push([X,se.right]),an}))}}if(we(r)){let[P,...z]=r;for(;S<w-z.length;S++){let X=P(l[S],u);if(Jt(X))if(Ee(X)){let U=new ct(S,l,X.left);if(p){f.push([h++,U]);continue}else return W(new $e(e,l,U,qn(m)))}else m.push([h++,X.right]);else{let U=h++,te=S;if(!y)y=[];y.push(({es:L,output:se})=>Ln(Ii(X),(ce)=>{if(Ee(ce)){let ee=new ct(te,l,ce.left);if(p)return L.push([U,ee]),an;else return W(new $e(e,l,ee,qn(se)))}else return se.push([U,ce.right]),an}))}}for(let X=0;X<z.length;X++){let U=S+X;if(w<U+1)continue;else{let te=z[X](l[U],u);if(Jt(te)){if(Ee(te)){let L=new ct(U,l,te.left);if(p){f.push([h++,L]);continue}else return W(new $e(e,l,L,qn(m)))}m.push([h++,te.right])}else{let L=h++;if(!y)y=[];y.push(({es:se,output:ce})=>Ln(Ii(te),(ee)=>{if(Ee(ee)){let Ae=new ct(U,l,ee.left);if(p)return se.push([L,Ae]),an;else return W(new $e(e,l,Ae,qn(ce)))}return ce.push([L,ee.right]),an}))}}}}let R=({es:P,output:z})=>co(P)?W(new $e(e,l,qn(P),qn(z))):Q(qn(z));if(y&&y.length>0){let P=y;return Lc(()=>{let z={es:sa(f),output:sa(m)};return Ln(Fc(P,(X)=>X(z),{concurrency:s,batching:c,discard:!0}),()=>R(z))})}return R({output:m,es:f})}}case"TypeLiteral":{if(e.propertySignatures.length===0&&e.indexSignatures.length===0)return Wt(e,G_);let n=[],r={},o=[];for(let u of e.propertySignatures)n.push([It(u.type,t),u]),r[u.name]=null,o.push(u.name);let i=e.indexSignatures.map((u)=>[It(u.parameter,t),It(u.type,t),u.parameter]),a=Ut.make(e.indexSignatures.map((u)=>u.parameter).concat(o.map((u)=>Yo(u)?new wd(u):new Mi(u)))),s=It(a,t),c=fx(e),l=mx(e);return(u,p)=>{if(!Wf(u))return W(new _n(e,u));let f=p?.errors==="all",h=[],m=0,w=p?.onExcessProperty==="error",S=p?.onExcessProperty==="preserve",y={},R;if(w||S){R=Reflect.ownKeys(u);for(let U of R){let te=s(U,p);if(Jt(te)&&Ee(te))if(w){let L=new ct(U,u,new hx(u[U],`is unexpected, expected: ${String(a)}`));if(f){h.push([m++,L]);continue}else return W(new $e(e,u,L,y))}else y[U]=u[U]}}let P=void 0,z=p?.exact===!0;for(let U=0;U<n.length;U++){let te=n[U][1],L=te.name,se=Object.prototype.hasOwnProperty.call(u,L);if(!se){if(te.isOptional)continue;else if(z){let Ae=new ct(L,u,new Wa(te));if(f){h.push([m++,Ae]);continue}else return W(new $e(e,u,Ae,y))}}let ce=n[U][0],ee=ce(u[L],p);if(Jt(ee)){if(Ee(ee)){let Ae=new ct(L,u,se?ee.left:new Wa(te));if(f){h.push([m++,Ae]);continue}else return W(new $e(e,u,Ae,y))}y[L]=ee.right}else{let Ae=m++,vt=L;if(!P)P=[];P.push(({es:Ft,output:Lt})=>Ln(Ii(ee),(De)=>{if(Ee(De)){let je=new ct(vt,u,se?De.left:new Wa(te));if(f)return Ft.push([Ae,je]),an;else return W(new $e(e,u,je,Lt))}return Lt[vt]=De.right,an}))}}for(let U=0;U<i.length;U++){let te=i[U],L=te[0],se=te[1],ce=ky(u,te[2]);for(let ee of ce){let Ae=L(ee,p);if(Jt(Ae)&&Ot(Ae)){let vt=se(u[ee],p);if(Jt(vt)){if(Ee(vt)){let Ft=new ct(ee,u,vt.left);if(f){h.push([m++,Ft]);continue}else return W(new $e(e,u,Ft,y))}else if(!Object.prototype.hasOwnProperty.call(r,ee))y[ee]=vt.right}else{let Ft=m++,Lt=ee;if(!P)P=[];P.push(({es:De,output:je})=>Ln(Ii(vt),(Tt)=>{if(Ee(Tt)){let Et=new ct(Lt,u,Tt.left);if(f)return De.push([Ft,Et]),an;else return W(new $e(e,u,Et,je))}else{if(!Object.prototype.hasOwnProperty.call(r,ee))je[ee]=Tt.right;return an}}))}}}}let X=({es:U,output:te})=>{if(co(U))return W(new $e(e,u,qn(U),te));if(p?.propertyOrder==="original"){let L=R||Reflect.ownKeys(u);for(let ce of o)if(L.indexOf(ce)===-1)L.push(ce);let se={};for(let ce of L)if(Object.prototype.hasOwnProperty.call(te,ce))se[ce]=te[ce];return Q(se)}return Q(te)};if(P&&P.length>0){let U=P;return Lc(()=>{let te={es:sa(h),output:Object.assign({},y)};return Ln(Fc(U,(L)=>L(te),{concurrency:c,batching:l,discard:!0}),()=>X(te))})}return X({es:h,output:y})}}case"Union":{let n=YC(e.types,t),r=Reflect.ownKeys(n.keys),o=r.length,i=e.types.length,a=new Map;for(let l=0;l<i;l++)a.set(e.types[l],It(e.types[l],t));let s=fx(e)??1,c=mx(e);return(l,u)=>{let p=[],f=0,h=[];if(o>0)if(Es(l))for(let S=0;S<o;S++){let y=r[S],R=n.keys[y].buckets;if(Object.prototype.hasOwnProperty.call(l,y)){let P=String(l[y]);if(Object.prototype.hasOwnProperty.call(R,P))h=h.concat(R[P]);else{let{candidates:z,literals:X}=n.keys[y],U=Ut.make(X),te=z.length===i?new cr([new st(y,U,!1,!0)],[]):Ut.make(z);p.push([f++,new $e(te,l,new ct(y,l,new _n(U,l[y])))])}}else{let{candidates:P,literals:z}=n.keys[y],X=new st(y,Ut.make(z),!1,!0),U=P.length===i?new cr([X],[]):Ut.make(P);p.push([f++,new $e(U,l,new ct(y,l,new Wa(X)))])}}else{let S=n.candidates.length===i?e:Ut.make(n.candidates);p.push([f++,new _n(S,l)])}if(n.otherwise.length>0)h=h.concat(n.otherwise);let m=void 0;for(let S=0;S<h.length;S++){let y=h[S],R=a.get(y)(l,u);if(Jt(R)&&(!m||m.length===0))if(Ot(R))return R;else p.push([f++,R.left]);else{let P=f++;if(!m)m=[];m.push((z)=>Lc(()=>{if("finalResult"in z)return an;else return Ln(Ii(R),(X)=>{if(Ot(X))z.finalResult=X;else z.es.push([P,X.left]);return an})}))}}let w=(S)=>co(S)?S.length===1&&S[0][1]._tag==="Type"?W(S[0][1]):W(new $e(e,l,qn(S))):W(new _n(e,l));if(m&&m.length>0){let S=m;return Lc(()=>{let y={es:sa(p)};return Ln(Fc(S,(R)=>R(y),{concurrency:s,batching:c,discard:!0}),()=>{if("finalResult"in y)return y.finalResult;return w(y.es)})})}return w(p)}}case"Suspend":{let n=Dc(()=>It(e.f(),t));return(r,o)=>n()(r,o)}}},Wt=(e,t)=>(n)=>t(n)?Q(n):W(new _n(e,n)),Kc=(e,t)=>{switch(e._tag){case"Declaration":{let n=tx(e);if(Re(n))return Kc(n.value,t);break}case"TypeLiteral":{let n=[];for(let r=0;r<e.propertySignatures.length;r++){let o=e.propertySignatures[r],i=t?Cd(o.type):at(o.type);if(bd(i)&&!o.isOptional)n.push([o.name,i])}return n}case"TupleType":{let n=[];for(let r=0;r<e.elements.length;r++){let o=e.elements[r],i=t?Cd(o.type):at(o.type);if(bd(i)&&!o.isOptional)n.push([r,i])}return n}case"Refinement":return Kc(e.from,t);case"Suspend":return Kc(e.f(),t);case"Transformation":return Kc(t?e.from:e.to,t)}return[]},YC=(e,t)=>{let n={},r=[],o=[];for(let i=0;i<e.length;i++){let a=e[i],s=Kc(a,t);if(s.length>0){o.push(a);for(let c=0;c<s.length;c++){let[l,u]=s[c],p=String(u.literal);n[l]=n[l]||{buckets:{},literals:[],candidates:[]};let f=n[l].buckets;if(Object.prototype.hasOwnProperty.call(f,p)){if(c<s.length-1)continue;f[p].push(a),n[l].literals.push(u),n[l].candidates.push(a)}else{f[p]=[a],n[l].literals.push(u),n[l].candidates.push(a);break}}}else r.push(a)}return{keys:n,otherwise:r,candidates:o}},ZC=(e)=>Vc(e)?ZC(e.from):e,zc=(e,t,n,r)=>{if(r?.isEffectAllowed===!0)return e;if(Jt(e))return e;let o=new Oc,i=qk(e,{scheduler:o});o.flush();let a=i.unsafePoll();if(a){if(LO(a))return Q(a.value);let s=a.cause;if(kT(s))return W(s.error);return W(new gx(t,n,CT(s)))}return W(new gx(t,n,"cannot be be resolved synchronously, this is caused by using runSync on an effect that performs async work"))},x2=([e],[t])=>e>t?1:e<t?-1:0,S2=(e,t)=>{switch(e._tag){case"FinalTransformation":return t?e.decode:e.encode;case"ComposeTransformation":return Q;case"TypeLiteralTransformation":return(n)=>{let r=Q(n);for(let o of e.propertySignatureTransformations){let[i,a]=t?[o.from,o.to]:[o.to,o.from],s=t?o.decode:o.encode;r=Un(r,(l)=>{let u=s(Object.prototype.hasOwnProperty.call(l,i)?F(l[i]):A());if(delete l[i],Re(u))l[a]=u.value;return l})}return r}}},Ht=(e,t=[])=>({value:e,forest:t}),Wc,_2=(e)=>e.value+XC(`
34
+ `,e.forest),XC=(e,t)=>{let n="",r=t.length,o;for(let i=0;i<r;i++){o=t[i];let a=i===r-1;n+=e+(a?"\u2514":"\u251C")+"\u2500 "+o.value,n+=XC(e+(r>1&&!a?"\u2502 ":" "),o.forest)}return n},b2=(e)=>{switch(e){case"Encoded":return"Encoded side transformation failure";case"Transformation":return"Transformation process failure";case"Type":return"Type side transformation failure"}},w2=(e)=>{switch(e){case"From":return"From side refinement failure";case"Predicate":return"Predicate refinement failure"}},QC=(e)=>("ast"in e)?F(e.ast):A(),yx,v2=(e)=>QC(e).pipe(Rn(sC),Je({onNone:()=>yx,onSome:(t)=>{let n=t(e);if(gt(n))return Q({message:n,override:!1});if(Fk(n))return hd(n,(r)=>({message:r,override:!1}));if(gt(n.message))return Q({message:n.message,override:n.override});return hd(n.message,(r)=>({message:r,override:n.override}))}})),Sx=(e)=>(t)=>t._tag===e,eA,$C,jC,Jc=(e)=>Jr(v2(e),(t)=>{if(t!==void 0)return!t.override&&(eA(e)||$C(e)&&e.kind==="From"||jC(e)&&e.kind!=="Transformation")?jC(e)||$C(e)?Jc(e.issue):yx:Q(t.message);return yx}),tA=(e)=>QC(e).pipe(Rn(pC),Tb((t)=>t(e)),Bt),O2=(e)=>Un(Jc(e),(t)=>t??tA(e)??E2(e)),Ad=(e)=>tA(e)??String(e.ast),R2=(e)=>e.message??"is forbidden",k2=(e)=>e.message??"is unexpected",C2=(e)=>{let t=cC(e.ast);if(Re(t)){let n=t.value();return gt(n)?Q(n):n}return Q(e.message??"is missing")},Ja=(e)=>{switch(e._tag){case"Type":return Un(O2(e),Ht);case"Forbidden":return Q(Ht(Ad(e),[Ht(R2(e))]));case"Unexpected":return Q(Ht(k2(e)));case"Missing":return Un(C2(e),Ht);case"Transformation":return Jr(Jc(e),(t)=>{if(t!==void 0)return Q(Ht(t));return Un(Ja(e.issue),(n)=>Ht(Ad(e),[Ht(b2(e.kind),[n])]))});case"Refinement":return Jr(Jc(e),(t)=>{if(t!==void 0)return Q(Ht(t));return Un(Ja(e.issue),(n)=>Ht(Ad(e),[Ht(w2(e.kind),[n])]))});case"Pointer":return Un(Ja(e.issue),(t)=>Ht(gd(e.path),[t]));case"Composite":return Jr(Jc(e),(t)=>{if(t!==void 0)return Q(Ht(t));let n=Ad(e);return Cy(e.issues)?Un(Fc(e.issues,Ja),(r)=>Ht(n,r)):Un(Ja(e.issues),(r)=>Ht(n,[r]))})}};var nA=x(()=>{Be();AT();_E();Hk();tn();DO();j();Ve();qc();Ge();ye();Qp();dx();HC=Symbol.for("effect/Schema/ParseErrorTypeId");VC=class VC extends SE("ParseError"){[HC]=HC;get message(){return this.toString()}toString(){return Wc.formatIssueSync(this.issue)}toJSON(){return{_id:"ParseError",message:this.toString()}}[ne](){return this.toJSON()}};BC=Q,KC=W,Jt=lm,Jr=d(2,(e,t)=>Jt(e)?Ls(e,{onLeft:W,onRight:t}):Ln(e,t)),Un=d(2,(e,t)=>Jt(e)?yb(e,t):hd(e,t)),Md=d(2,(e,t)=>Jt(e)?ou(e,t):Dk(e,t)),zC=d(2,(e,t)=>Jt(e)?Ls(e,{onLeft:t,onRight:Q}):Lk(e,t)),h2=V(Symbol.for("effect/ParseResult/decodeMemoMap"),()=>new WeakMap),g2=V(Symbol.for("effect/ParseResult/encodeMemoMap"),()=>new WeakMap);Wc={formatIssue:(e)=>Un(Ja(e),_2),formatIssueSync:(e)=>{let t=Wc.formatIssue(e);return Jt(t)?Sb(t):Uk(t)},formatError:(e)=>Wc.formatIssue(e.issue),formatErrorSync:(e)=>Wc.formatIssueSync(e.issue)},yx=Q(void 0),eA=Sx("Composite"),$C=Sx("Refinement"),jC=Sx("Transformation")});var rA,oA;var iA=x(()=>{j();ye();rA=d((e)=>qt(e[0]),(e,...t)=>{let n={};for(let r of t)if(r in e)n[r]=e[r];return n}),oA=d((e)=>qt(e[0]),(e,...t)=>{let n={...e};for(let r of t)delete n[r];return n})});function _t(e){return class{[Gc]=aA;static ast=e;static annotations(n){return _t(lr(this.ast,n))}static pipe(){return T(this,arguments)}static toString(){return String(e)}static Type;static Encoded;static Context;static[Gc]=aA}}function I2(e){return Od(e)?Ut.make(NC(e,(t)=>new Mi(t))):new Mi(e[0])}function mA(e,t=I2(e)){return class extends _t(t){static annotations(r){return mA(this.literals,lr(this.ast,r))}static literals=[...e]}}function v(...e){return we(e)?mA(e):wx}function bx(e,t){return class extends _t(t){static annotations(r){return bx(this.typeParameters,lr(this.ast,r))}static typeParameters=[...e]}}function gA(e,t=F2(e)){return class extends _t(t){static annotations(r){return gA(this.members,lr(this.ast,r))}static members=[...e]}}function xe(...e){return Od(e)?gA(e):we(e)?e[0]:wx}function Fd(e,t,n=D2(e,t)){return class extends _t(n){static annotations(o){return Fd(this.elements,this.rest,lr(this.ast,o))}static elements=[...e];static rest=[...t]}}function yA(...e){return Array.isArray(e[0])?Fd(e[0],e.slice(1)):Fd(e,[])}function xA(e,t){return class extends Fd([],[e],t){static annotations(r){return xA(this.value,lr(this.ast,r))}static value=e}}class _A{from;to;decode;encode;_tag="PropertySignatureTransformation";constructor(e,t,n,r){this.from=e,this.to=t,this.decode=n,this.encode=r}toString(){return`PropertySignature<${_x(this.to.isOptional)}, ${this.to.type}, ${q2(this.from.fromKey)}, ${_x(this.from.isOptional)}, ${this.from.type}>`}}function Rx(e,t,n=H2(e,t)){return class extends _t(n){static annotations(o){return Rx(this.fields,this.records,lr(this.ast,o))}static fields={...e};static records=[...t];static make=(o,i)=>{let a=$2(e,{...o});return Px(i)?a:Nd(this)(a)};static pick(...o){return _(rA(e,...o))}static omit(...o){return _(oA(e,...o))}}}function _(e,...t){return Rx(e,t)}function TA(e,t,n){return class extends Rx({},[{key:e,value:t}],n){static annotations(o){return TA(e,t,lr(this.ast,o))}static key=e;static value=t}}function EA(e,t){return class extends _t(t){static annotations(r){return EA(this.from,lr(this.ast,r))}static make=(r,o)=>Px(o)?r:Nd(this)(r);static from=e}}function OA(e,t,n){return class extends _t(n){static annotations(o){return OA(this.from,this.filter,lr(this.ast,o))}static[j2]=e;static from=e;static filter=t;static make=(o,i)=>Px(i)?o:Nd(this)(o)}}function Ze(e,t){return(n)=>{function r(i,a,s){return V2(e(i,a,s),s,i)}let o=new jc(n.ast,r,Ni(t));return OA(n,r,o)}}function Px(e){return Go(e)?e:e?.disableValidation??!1}var Gc,aA,sA,Ni=(e)=>{if(!e)return{};let t={...e};for(let n in sA)if(n in e){let r=sA[n];t[r]=e[n],delete t[n]}return t},lr=(e,t)=>Bc(e,Ni(t)),fA=(e,t)=>{let n=GC(e,t);return(r,o)=>ou(n(r,o),xx)},cA=(e)=>C(e,Gc)&&qt(e[Gc]),M2=(e,t,n)=>bx(e,new Ba(e.map((r)=>r.ast),(...r)=>t.decode(...r.map(_t)),(...r)=>t.encode(...r.map(_t)),Ni(n))),N2=(e,t)=>{let n=()=>(o,i,a)=>e(o)?BC(o):KC(new _n(a,o));return bx([],new Ba([],n,n,Ni(t)))},H=function(){if(Array.isArray(arguments[0])){let n=arguments[0],r=arguments[1],o=arguments[2];return M2(n,r,o)}let e=arguments[0],t=arguments[1];return N2(e,t)},hA,lt,wx,vx,k,Gt,J,F2=(e)=>Ut.make(e.map((t)=>t.ast)),L2=(e)=>xe(e,hA),D2=(e,t)=>new $c(e.map((n)=>cA(n)?new Fo(n.ast,!1):n.ast),t.map((n)=>cA(n)?new Ka(n.ast):n.ast),!0),q=(e)=>xA(e),_x=(e)=>e?'"?:"':'":"',Tx,SA,q2=(e)=>{if(e===void 0)return"never";if(gt(e))return JSON.stringify(e);return String(e)},bA=(e,t)=>{switch(e._tag){case"PropertySignatureDeclaration":return new Tx(e.type,e.isOptional,e.isReadonly,{...e.annotations,...t},e.defaultValue);case"PropertySignatureTransformation":return new _A(e.from,new SA(e.to.type,e.to.isOptional,e.to.isReadonly,{...e.to.annotations,...t},e.to.defaultValue),e.decode,e.encode)}},wA,vA=(e)=>C(e,wA),Ex,Ox,b=(e)=>{let t=e.ast===vd||e.ast===Td?vd:L2(e).ast;return new Ox(new Tx(t,!0,!0,{},void 0),e)},U2,H2=(e,t)=>{let n=Reflect.ownKeys(e),r=[];if(n.length>0){let i=[],a=[],s=[];for(let c=0;c<n.length;c++){let l=n[c],u=e[l];if(vA(u)){let p=u.ast;switch(p._tag){case"PropertySignatureDeclaration":{let{type:f,isOptional:h,annotations:m}=p;i.push(new st(l,f,h,!0,U2(p))),a.push(new st(l,at(f),h,!0,m)),r.push(new st(l,f,h,!0,m));break}case"PropertySignatureTransformation":{let f=p.from.fromKey??l;i.push(new st(f,p.from.type,p.from.isOptional,!0,p.from.annotations)),a.push(new st(l,p.to.type,p.to.isOptional,!0,p.to.annotations)),s.push(new sx(f,l,p.decode,p.encode));break}}}else i.push(new st(l,u.ast,!1,!0)),a.push(new st(l,at(u.ast),!1,!0)),r.push(new st(l,u.ast,!1,!0))}if(we(s)){let c=[],l=[];for(let u of t){let{indexSignatures:p,propertySignatures:f}=lx(u.key.ast,u.value.ast);f.forEach((h)=>{i.push(h),a.push(new st(h.name,at(h.type),h.isOptional,h.isReadonly,h.annotations))}),p.forEach((h)=>{c.push(h),l.push(new za(h.parameter,at(h.type),h.isReadonly))})}return new ax(new cr(i,c,{[_d]:"Struct (Encoded side)"}),new cr(a,l,{[_d]:"Struct (Type side)"}),new cx(s))}}let o=[];for(let i of t){let{indexSignatures:a,propertySignatures:s}=lx(i.key.ast,i.value.ast);s.forEach((c)=>r.push(c)),a.forEach((c)=>o.push(c))}return new cr(r,o)},$2=(e,t)=>{let n=Reflect.ownKeys(e);for(let r of n){let o=e[r];if(t[r]===void 0&&vA(o)){let i=o.ast,a=i._tag==="PropertySignatureDeclaration"?i.defaultValue:i.to.defaultValue;if(a!==void 0)t[r]=a()}}return t},Ld=(e)=>TA(e.key,e.value),Yc=(e,t)=>(n)=>{let r=Je(Zy(n.ast),{onNone:()=>[e],onSome:(i)=>[...i,e]}),o=Bc(n.ast,Ni({[Ly]:r,...t}));return EA(n,o)},j2,lA=(e,t,n)=>{if(Go(e))return e?A():F(new _n(t,n));if(gt(e))return F(new _n(t,n,e));if(e!==void 0){if("_tag"in e)return F(e);let r=new _n(t,n,e.message);return F(we(e.path)?new ct(e.path,n,r):r)}return A()},V2=(e,t,n)=>{if(jk(e))return lA(e,t,n);if(we(e)){let r=cu(e,(o)=>lA(o,t,n));if(we(r))return F(r.length===1?r[0]:new $e(t,n,r))}return A()},B2,kx=(e,t)=>(n)=>n.pipe(Ze((r)=>r.length<=e,{schemaId:B2,title:`maxLength(${e})`,description:`a string at most ${e} character(s) long`,jsonSchema:{maxLength:e},...t})),K2,Ga=(e,t)=>(n)=>n.pipe(Ze((r)=>r.length>=e,{schemaId:K2,title:`minLength(${e})`,description:`a string at least ${e} character(s) long`,jsonSchema:{minLength:e},...t})),uA,le=(e,t)=>(n)=>{let r=e.source;return n.pipe(Ze((o)=>(e.lastIndex=0,e.test(o)),{schemaId:uA,[uA]:{regex:e},description:`a string matching the pattern ${r}`,jsonSchema:{pattern:r},...t}))},z2,pA,W2,J2,Cx=(e,t)=>(n)=>n.pipe(Ze((r)=>r>e,{schemaId:J2,title:`greaterThan(${e})`,description:e===0?"a positive number":`a number greater than ${e}`,jsonSchema:{exclusiveMinimum:e},...t})),G2,RA=(e,t)=>(n)=>n.pipe(Ze((r)=>r>=e,{schemaId:G2,title:`greaterThanOrEqualTo(${e})`,description:e===0?"a non-negative number":`a number greater than or equal to ${e}`,jsonSchema:{minimum:e},...t})),Y2,Dd=(e)=>(t)=>t.pipe(Ze((n)=>Number.isSafeInteger(n),{schemaId:Y2,title:"int",description:"an integer",jsonSchema:{type:"integer"},...e})),Ax=(e)=>Cx(0,{title:"positive",...e}),qd,Z2,Zc=(e,t)=>(n)=>{let r=Math.floor(e);if(r<1)throw Error(Vk(`Expected an integer greater than or equal to 1, actual ${e}`));return n.pipe(Ze((o)=>o.length>=r,{schemaId:Z2,title:`minItems(${r})`,description:`an array of at least ${r} item(s)`,jsonSchema:{minItems:r},[Yy]:!0,...t}))},dA,X2;var bt=x(()=>{Be();tn();vs();My();nC();qc();Ge();nA();be();ye();dx();iA();Gc=Symbol.for("effect/Schema");aA={_A:(e)=>e,_I:(e)=>e,_R:(e)=>e},sA={typeConstructor:oC,schemaId:iC,message:Dy,missingMessage:xd,identifier:Sd,title:zt,description:Wr,examples:qy,default:Uy,documentation:aC,jsonSchema:Hy,arbitrary:$y,pretty:jy,equivalence:Vy,concurrency:By,batching:Ky,parseIssueTitle:zy,parseOptions:Wy,decodingFallback:Jy};hA=class hA extends _t(vd){};lt=class lt extends _t(mC){};wx=class wx extends _t(Td){};vx=class vx extends _t(ox){};k=class k extends _t(wC){};Gt=class Gt extends _t(TC){};J=class J extends _t(OC){};Tx=class Tx extends Fo{isReadonly;defaultValue;_tag="PropertySignatureDeclaration";constructor(e,t,n,r,o){super(e,t,r);this.isReadonly=n,this.defaultValue=o}toString(){let e=_x(this.isOptional),t=String(this.type);return`PropertySignature<${e}, ${t}, never, ${e}, ${t}>`}};SA=class SA extends Fo{isReadonly;defaultValue;constructor(e,t,n,r,o){super(e,t,r);this.isReadonly=n,this.defaultValue=o}};wA=Symbol.for("effect/PropertySignature");Ex=class Ex{ast;[Gc];[wA]=null;_TypeToken;_Key;_EncodedToken;_HasDefault;constructor(e){this.ast=e}pipe(){return T(this,arguments)}annotations(e){return new Ex(bA(this.ast,Ni(e)))}toString(){return String(this.ast)}};Ox=class Ox extends Ex{from;constructor(e,t){super(e);this.from=t}annotations(e){return new Ox(bA(this.ast,Ni(e)),this.from)}};U2=ux([xd]);j2=Symbol.for("effect/SchemaId/Refine");B2=eC,K2=Qk,uA=Symbol.for("effect/SchemaId/Pattern"),z2=Symbol.for("effect/SchemaId/UUID"),pA=/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/i;W2=class W2 extends k.pipe(le(pA,{schemaId:z2,identifier:"UUID",jsonSchema:{format:"uuid",pattern:pA.source},description:"a Universally Unique Identifier",arbitrary:()=>(e)=>e.uuid()})){};J2=Yk,G2=Zk,Y2=Xk;qd=class qd extends Gt.pipe(Dd({identifier:"Int"})){};Z2=tC,dA=Gk;X2=class X2 extends H(Jl,{typeConstructor:{_tag:"Date"},identifier:"DateFromSelf",schemaId:dA,[dA]:{noInvalidDate:!1},description:"a potentially invalid Date instance",pretty:()=>(e)=>`new Date(${JSON.stringify(e)})`,arbitrary:()=>(e)=>e.date({noInvalidDate:!1}),equivalence:()=>K_}){}});function bn(e,t){return fA(e,Q2)(t)}var Q2;var Ya=x(()=>{bt();Q2={onExcessProperty:"error"}});function Mx(e,t){if(typeof t!=="string")return;let n=e.lastIndexOf("@");if(n<=0)return;let r=e.slice(0,n),o=e.slice(n+1);if(!AA(r)||!CA(o)||t!==o)return;return{pluginName:r,marketplaceName:o,canonicalPluginId:`${r}@openai-curated`}}function Hn(e){let t=e.lastIndexOf("@");if(t<=0)return;let n=e.slice(0,t),r=e.slice(t+1);return AA(n)&&CA(r)?`${n}@openai-curated`:void 0}function CA(e){return kA.includes(e)}function AA(e){return Ud.includes(e)}function Nx(e,t){let n=t??ur;return{computer_use:e?.computer_use??n.computer_use,work:e?.work??n.work,frontend:e?.frontend??n.frontend,security:e?.security??n.security}}function Qc(e,t=[]){let n=[],r=new Set;for(let o of PA){if(!e[o])continue;for(let i of Xc[o].pluginIds)if(!r.has(i))r.add(i),n.push(i)}for(let o of t)if(!r.has(o))r.add(o),n.push(o);return n}var Ix,eU,tU,nU,kA,Ud,Gr,rU,Xc,PA,ur;var Fx=x(()=>{bt();Ix=v("computer_use","work","frontend","security"),eU=v("computer_use","work","frontend","security"),tU=v("installed","disabled","missing","uncertain"),nU=v("healthy","missing","disabled","uncertain"),kA=Object.freeze(["openai-curated","openai-curated-remote"]),Ud=Object.freeze(["build-web-apps","codex-security"]);Gr=Object.freeze({coding:!0,computer_use:!1,work:!1,frontend:!0,security:!0}),rU={work:{name:"work",pluginIds:["documents@openai-primary-runtime","pdf@openai-primary-runtime","presentations@openai-primary-runtime","spreadsheets@openai-primary-runtime","template-creator@openai-primary-runtime"],defaultSelected:Gr.work,migrationKey:"work",semanticSkillIds:["documents:documents","pdf:pdf","presentations:Presentations","spreadsheets:Spreadsheets","template-creator:template-creator"],ownership:"shared-preserve"},frontend:{name:"frontend",pluginIds:["build-web-apps@openai-curated"],defaultSelected:Gr.frontend,migrationKey:"frontend",semanticSkillIds:["build-web-apps:frontend-app-builder","build-web-apps:frontend-testing-debugging","build-web-apps:react-best-practices"],ownership:"shared-preserve"},security:{name:"security",pluginIds:["codex-security@openai-curated"],defaultSelected:Gr.security,migrationKey:"security",semanticSkillIds:["codex-security:security-scan","codex-security:security-diff-scan","codex-security:threat-model"],ownership:"shared-preserve"},computer_use:{name:"computer_use",pluginIds:["computer-use@openai-bundled"],defaultSelected:Gr.computer_use,migrationKey:"computer_use",semanticSkillIds:["computer-use:computer-use"],ownership:"shared-preserve"}},Xc=Object.freeze(rU),PA=Object.freeze(["computer_use","work","frontend","security"]),ur=Object.freeze({computer_use:Gr.computer_use,work:Gr.work,frontend:Gr.frontend,security:Gr.security})});function pr(e){return _({identifier:v(e),label:k,requiresRootApproval:J})}function IA(e){let t=e.map((r)=>r.label),n=t.at(-1);if(n===void 0)return"";if(t.length===1)return n;return`${t.slice(0,-1).join(", ")}, and ${n}`}function MA(e){return e.length===0?e:`${e[0]?.toUpperCase()??""}${e.slice(1)}`}var NA,oU,iU,Lx,aU,FA,sU,cU,lU;var LA=x(()=>{bt();NA=v("local.repository.edit","local.repository.check","local.repository.lint","local.repository.format","local.repository.commit","external.read","specialist.dispatch","vcs.server.mutation","vcs.server.ci-trigger","unknown.effect"),oU=_({identifier:NA,label:k,requiresRootApproval:J});iU=_({localRepositoryEdit:pr("local.repository.edit"),localRepositoryCheck:pr("local.repository.check"),localRepositoryLint:pr("local.repository.lint"),localRepositoryFormat:pr("local.repository.format"),localRepositoryCommit:pr("local.repository.commit"),externalRead:pr("external.read"),specialistDispatch:pr("specialist.dispatch"),versionControlServerMutation:pr("vcs.server.mutation"),versionControlServerCiTrigger:pr("vcs.server.ci-trigger"),unknownEffect:pr("unknown.effect")}),Lx={localRepositoryEdit:{identifier:"local.repository.edit",label:"local repository edit",requiresRootApproval:!1},localRepositoryCheck:{identifier:"local.repository.check",label:"local repository check",requiresRootApproval:!1},localRepositoryLint:{identifier:"local.repository.lint",label:"local repository lint",requiresRootApproval:!1},localRepositoryFormat:{identifier:"local.repository.format",label:"local repository format",requiresRootApproval:!1},localRepositoryCommit:{identifier:"local.repository.commit",label:"local repository commit",requiresRootApproval:!1},externalRead:{identifier:"external.read",label:"external read",requiresRootApproval:!1},specialistDispatch:{identifier:"specialist.dispatch",label:"specialist dispatch",requiresRootApproval:!1},versionControlServerMutation:{identifier:"vcs.server.mutation",label:"version-control-server mutation",requiresRootApproval:!0},versionControlServerCiTrigger:{identifier:"vcs.server.ci-trigger",label:"version-control-server CI triggering",requiresRootApproval:!0},unknownEffect:{identifier:"unknown.effect",label:"unclassified effect",requiresRootApproval:!0}};Yn(Lx);aU=v("never","root"),FA=Object.values(Lx);sU=FA.filter((e)=>!e.requiresRootApproval),cU=FA.filter((e)=>e.requiresRootApproval),lU=Object.freeze({noRootApproval:`${MA(IA(sU))} actions do not require Root approval.`,rootApproval:`${MA(IA(cU))} require Root approval.`})});function Hd(e){let t=bn(uU,e);if(Ee(t))return Jo(ys("sha256 digest",t.left));return Zi(t.right)}var $n,Dx,Y6,Z6,X6,uU,pU,dU,fU,mU;var $d=x(()=>{tn();bt();Xi();Ya();$n=k.pipe(le(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u)),Dx=k.pipe(le(/^[0-9a-f]{64}$/u)),Y6=$n.pipe(Yc("RunId")),Z6=$n.pipe(Yc("ProjectId")),X6=$n.pipe(Yc("TrustId")),uU=Dx.pipe(Yc("Sha256Digest"));pU=_({run_id:$n,objective_lineage:$n,parent_run_id:b(xe($n,lt))}),dU=_({project_id:$n,trust_id:$n,trust_digest:Dx}),fU=_({project_id:$n,project_digest:Dx}),mU=k.pipe(le(/^state-[0-9]+\.[0-9]+$/u))});function qx(e){switch(e){case"go":case"Go":throw Error(`Legacy profile ${e} was removed and requires an explicit replacement.`);case"plus-low":return"low";case"plus":return"default";case"plus-high":return"high";case"pro-5x":case"pro-20x":throw Error(`Legacy profile ${e} was removed and requires an explicit replacement.`);default:return e}}function HA(e){return typeof e==="string"&&gU.has(e)}function xU(e){if(typeof e!=="object"||e===null||!("role"in e)||!("task"in e))return!1;let{role:t,task:n}=e;if(!HA(t)||typeof n!=="string")return!1;return el.get(t)?.tasks.some((r)=>r.name===n)===!0}function Vd(e,t){return typeof t==="string"&&el.get(e)?.tasks.some((n)=>n.name===t)===!0}function $A(e){return typeof e==="string"&&yU.has(e)}function jx(e){let t=`${e.role}.${e.task}`;if(!Hx.has(t))throw Error("Unknown native specialist agent type.");return t}function Vx(e){let t=el.get(e.role)?.tasks.find((n)=>n.name===e.task);if(t===void 0)throw Error("Unknown specialist task policy.");return t.instruction}function Bx(e){let t=el.get(e.role)?.tasks.find((n)=>n.name===e.task);if(t===void 0)throw Error("Unknown specialist task policy.");return t.description}function VA(e){let t=el.get(e);if(t===void 0)throw Error("Unknown specialist role.");return t}function Kx(e){let t=VA(e.role),n=e.role==="Worker"&&e.task==="operations"?"exact_ref_or_sha":t.permissions.network?"current_sources":"disabled";return Object.freeze({network:n!=="disabled",write:t.permissions.write,networkScope:n})}var Lo,DA,jd,Fi,hU,qA="Make the smallest complete edit set within the authorized boundary, touch no unrelated paths, avoid speculative refactors or formatting churn, and perform no redundant writes or operations; preserve unrelated work and stop for Root input before expanding scope.",jn,el,gU,Ux,yU,UA,Hx,$x,SU,_U,bU,wU,tl,Li,jA,Za,vU,BA,TU,Do;var nl=x(()=>{bt();Lo=v("low","default","high"),DA=v("go","Go","plus-low","plus","plus-high","pro-5x","pro-20x"),jd=xe(Lo,DA);Fi=v("standard","fast","fast-all"),hU=v("low","medium","high","xhigh","max"),jn=[{role:"Explorer",tasks:[{name:"lookup",description:"Repository fact lookup specialist.",instruction:"Locate the exact requested repository fact."},{name:"trace",description:"Repository execution and reference tracing specialist.",instruction:"Trace the complete in-scope execution or reference path."}],capability:"repository-read",authority:"Read only the delegated Assignment repository scope; Git/VCS, lifecycle, and decisions remain Root-only.",evidence:"Return exact paths, symbols, callers, tests, and constraints.",completion:"Account for every in-scope caller and constraint.",permissions:{network:!1,write:!1}},{role:"Librarian",tasks:[{name:"lookup",description:"Authoritative external fact lookup specialist.",instruction:"Locate the exact requested authoritative external fact."},{name:"research",description:"Current authoritative-source research specialist.",instruction:"Synthesize the assigned current sources with citations."}],capability:"current-research",authority:"Research only the delegated Assignment current sources without repository mutation; Git/VCS, lifecycle, and decisions remain Root-only.",evidence:"Return sourced facts, dates, and explicit uncertainty.",completion:"Resolve the assigned external fact or report the exact evidence gap.",permissions:{network:!0,write:!1}},{role:"Worker",tasks:[{name:"mechanical",description:"Deterministic bounded-edit specialist.",instruction:"Apply only deterministic, already-decided edits."},{name:"implementation",description:"Bounded behavior implementation specialist.",instruction:"Implement and verify the bounded behavior seam."},{name:"integration",description:"Decided seam integration specialist.",instruction:"Integrate the decided seams and verify them together."},{name:"operations",description:"Exact-ref or SHA terminal operations observer.",instruction:"Observe the assigned post-VCS external gate."},{name:"validation",description:"Independent local behavioral validation specialist.",instruction:"When independent proof is useful, run the smallest relevant local checks for the delegated seam, classify failures, and report evidence without redesigning the solution or replacing code review."}],capability:"bounded-write",authority:"Change only the delegated Assignment seam; Intent lifecycle, Git/VCS, and material choices remain Root-only.",evidence:"Return changed files, verification results, and remaining risk.",completion:"Finish the delegated Assignment with proportional proof or an exact blocker and return a compact structured outcome.",permissions:{network:!1,write:!0}},{role:"Reviewer",tasks:[{name:"plan",description:"Adversarial implementation-plan review specialist.",instruction:"Review the complete plan to a fixed point."},{name:"code",description:"Adversarial implemented-code review specialist.",instruction:"Review and repair the implemented code to a fixed point."},{name:"artifact",description:"Adversarial produced-artifact review specialist.",instruction:"Review and repair the produced artifact to a fixed point."}],capability:"bounded-review",authority:"Inspect and repair only reviewer-owned defects within the delegated Assignment; Intent lifecycle, Git/VCS, and material choices remain Root-only.",evidence:"Return findings, repaired paths, verification, and residual risk.",completion:"Reach a fixed point or report each reproducible blocker as a compact structured outcome.",permissions:{network:!1,write:!0}}];Yn(jn);el=new Map(jn.map((e)=>[e.role,e])),gU=new Set(jn.map((e)=>e.role)),Ux=jn.flatMap((e)=>e.tasks.map((t)=>`${e.role}:${t.name}`)),yU=new Set(Ux),UA=Ux.map((e)=>e.replace(":",".")),Hx=new Set(UA);$x=H(HA),SU=H((e)=>Vd("Explorer",e)),_U=H((e)=>Vd("Librarian",e)),bU=H((e)=>Vd("Worker",e)),wU=H((e)=>Vd("Reviewer",e)),tl=H(xU),Li=Object.freeze(Ux.filter((e)=>$A(e))),jA=H($A),Za=Object.freeze(UA.filter((e)=>Hx.has(e))),vU=H((e)=>typeof e==="string"&&Hx.has(e));BA=_({profile:Lo,service_tier:b(Fi)}),TU=v("git_vcs","computer_use"),Do=Object.freeze({requiresDelegation:!0,trivialWorkRequiresDelegation:!0,directExecutionExceptions:Object.freeze(["git_vcs","computer_use"]),requestUserInputGates:Object.freeze(["plan_approval","installation_profile_approval","remote_origin_server_vcs_mutation","public_publication_or_release","ambiguity_or_missing_material_input"]),surgicalMutationRule:qA,specialistOutcomes:Object.freeze(["completed","blocked","needs_root_input","failed"]),materialDecisionsRemainRootOwned:!0,lifecycleRemainsRootOwned:!0,integrationAndCompletionRemainRootOwned:!0,codeReviewRequiredForImplementation:!0,codeReviewRequiredBeforeVcs:!0,externalVerificationMustBeTerminal:!0,postVcsFlow:"discover_topology_observe_repair_repeat"})});function Nt(e,t){return new We("invalid_canonical_value",`Cannot canonicalize ${e}: ${t}.`,{path:e,reason:t})}function zx(e,t,n){if(e===null)return"null";switch(typeof e){case"string":{let r=JSON.stringify(e);if(r===void 0)throw Nt(t,"invalid string");return r}case"boolean":return e?"true":"false";case"number":{if(!Number.isFinite(e))throw Nt(t,"non-finite number");let r=JSON.stringify(e);if(r===void 0)throw Nt(t,"invalid number");return r}case"undefined":throw Nt(t,"undefined is not JSON");case"bigint":throw Nt(t,"bigint is not JSON");case"function":throw Nt(t,"function is not JSON");case"symbol":throw Nt(t,"symbol is not JSON");case"object":break}if(n.has(e))throw Nt(t,"cyclic value");n.add(e);try{if(Array.isArray(e)){for(let s of Object.getOwnPropertySymbols(e))throw Nt(t,`symbol property ${String(s)}`);let i=e,a=[];for(let s=0;s<i.length;s+=1){let c=Object.getOwnPropertyDescriptor(i,String(s));if(!c||!c.enumerable||!("value"in c))throw Nt(`${t}[${s}]`,"sparse or accessor array item");a.push(zx(c.value,`${t}[${s}]`,n))}for(let s of Object.getOwnPropertyNames(i)){if(s==="length")continue;let c=Number(s);if(!Number.isInteger(c)||c<0||c>=i.length||String(c)!==s)throw Nt(t,`non-index array property ${s}`);let l=Object.getOwnPropertyDescriptor(i,s);if(!l||!l.enumerable||!("value"in l))throw Nt(`${t}[${c}]`,"non-enumerable or accessor array item")}return`[${a.join(",")}]`}let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)throw Nt(t,"only plain objects are supported");for(let i of Object.getOwnPropertySymbols(e))throw Nt(t,`symbol property ${String(i)}`);for(let i of Object.getOwnPropertyNames(e)){let a=Object.getOwnPropertyDescriptor(e,i);if(!a||!a.enumerable||!("value"in a))throw Nt(`${t}.${i}`,"non-enumerable or accessor property")}let o=[];for(let i of Object.keys(e).sort()){let a=Object.getOwnPropertyDescriptor(e,i);if(!a||!("value"in a))throw Nt(`${t}.${i}`,"accessor property");o.push(`${JSON.stringify(i)}:${zx(a.value,`${t}.${i}`,n)}`)}return`{${o.join(",")}}`}finally{n.delete(e)}}function dr(e){return zx(e,"$",new Set)}function Yr(e){return new TextEncoder().encode(dr(e))}function KA(e,t){if(e.length===0||e.includes("\x00"))throw new We("invalid_digest_domain","Digest domains must be non-empty and NUL-free.",{field:"domain"});let n=new TextEncoder().encode("holycodex-sha256\x00"),r=new TextEncoder().encode(e),o=n.byteLength+8+r.byteLength;for(let c of t){if(c.byteLength>4294967295||o>4294967291-c.byteLength)throw new We("invalid_digest_domain","Digest input is too large.");o+=4+c.byteLength}let i=new Uint8Array(o),a=new DataView(i.buffer);i.set(n,0);let s=n.byteLength;a.setUint32(s,r.byteLength,!1),s+=4,i.set(r,s),s+=r.byteLength,a.setUint32(s,t.length,!1),s+=4;for(let c of t)a.setUint32(s,c.byteLength,!1),s+=4,i.set(c,s),s+=c.byteLength;return i}function OU(e){let t="";for(let n of e)t+=n.toString(16).padStart(2,"0");return t}async function Zr(e,t){let n=globalThis.crypto?.subtle;if(!n)throw new We("crypto_unavailable","The standards-based crypto API is unavailable.");let r=await n.digest("SHA-256",RU(KA(e,t)));return OU(new Uint8Array(r))}function RU(e){let t=new Uint8Array(e.byteLength);return t.set(e),t}var Wx=x(()=>{Xi();$d()});function JA(e){try{return dr(e)!==void 0}catch{return!1}}function Kd(e){let t=bn(tP,e);if(Ee(t))return Jo(ys("CLI envelope",t.left));return Zi(t.right)}var zA,WA,GA,kU,CU,Jx="holycodex-specialist-outcome-2",Yt,rl,AU,PU,IU,MU,NU,FU,Bd,LU,DU,qU,UU,HU,YA,ZA,XA,$U,QA,eP,tP;var nP=x(()=>{tn();bt();Wx();Fx();Xi();$d();nl();Ya();zA=v("blocked","completed","failed","partial"),WA=xe(v("high","max","xhigh"),lt);GA=H((e)=>JA(e)),kU=H((e)=>Vf(e)&&!Array.isArray(e)&&JA(e)),CU=_({blocked:J,changed_files:q(k),confidence:Gt,context_owner:xe(k,lt),material_findings:q(k),needs_more_context:J,needs_root_decision:J,needs_verification:J,relevant_files:q(k),remaining_risk:q(k),reuse_recommended:J,status:zA,suggested_followup:xe(k,lt),suggested_luna_effort:WA,suggested_specialist:xe($x,lt),verification:q(k),verification_passed:J}),Yt=k.pipe(Ga(1)),rl={protocol_version:v(Jx),route:tl,evidence:q(Yt)},AU=_(rl),PU=_({...rl,status:v("completed"),summary:Yt}),IU=_({...rl,status:v("blocked"),reason:Yt,needs_root_decision:J}),MU=_({...rl,status:v("partial"),summary:Yt,completed:q(Yt),remaining:q(Yt),needs_root_decision:J}),NU=_({...rl,status:v("failed"),error:Yt}),FU=xe(PU,IU,MU,NU),Bd={protocol_version:v(Jx),capability:Ix,route:xe(tl,lt),evidence:q(Yt),data:GA},LU=_({...Bd,status:v("completed"),summary:Yt}),DU=_({...Bd,status:v("blocked"),reason:Yt,needs_root_decision:J}),qU=_({...Bd,status:v("partial"),summary:Yt,completed:q(Yt),remaining:q(Yt),needs_root_decision:J}),UU=_({...Bd,status:v("failed"),error:Yt}),HU=xe(LU,DU,qU,UU),YA=q(k),ZA=k.pipe(le(/^[a-z][a-z0-9-]*(?: [a-z][a-z0-9-]*)*$/u)),XA=v(vr),$U=_({code:$n,message:k,details:kU}),QA=_({schema_version:XA,ok:v(!0),command:ZA,data:GA,warnings:YA}),eP=_({schema_version:XA,ok:v(!1),command:ZA,error:$U,warnings:YA}),tP=xe(QA,eP)});function jU(e,t,n){return{key:`${e}:${t}`,role:e,task:t,model:oP,effort:n}}function KU(e){let t=BU.get(e);if(t===void 0)throw new We("catalog_invalid","A profile has no route effort policy.",{profile:e});return jn.flatMap((n)=>n.tasks.map((r)=>{let o=`${n.role}:${r.name}`,i=t.efforts[o];if(i===void 0)throw new We("catalog_invalid","A route effort policy is incomplete.",{profile:e,route:o});return jU(n.role,r.name,i)}))}function Gx(e){return{name:e.name,root:{model:"gpt-6-astra",effort:e.effort},specialistModel:"gpt-5.6-luna",defaultServiceTier:"standard",routes:KU(e.name)}}function zU(e){let t=["low","default","high"];if(e.length!==t.length)throw new We("catalog_invalid","The profile catalog has an invalid size.");for(let n=0;n<t.length;n+=1){let r=e[n],o=t[n];if(!r||r.name!==o)throw new We("catalog_invalid","The profile catalog order is invalid.",{index:n});let i=o==="low"?"low":o==="default"?"medium":"high";if(r.root.model!=="gpt-6-astra"||r.root.effort!==i||r.specialistModel!=="gpt-5.6-luna")throw new We("catalog_invalid","A profile has an invalid model route.",{profile:r.name});if(r.routes.length!==Li.length)throw new We("catalog_invalid","A profile is incomplete.",{profile:r.name});let a=new Set;for(let s of r.routes){if(a.has(s.key)||!VU.has(s.key)||s.model!=="gpt-5.6-luna"||`${s.role}:${s.task}`!==s.key)throw new We("catalog_invalid","A profile contains an invalid route.",{profile:r.name});a.add(s.key)}if(a.size!==Li.length)throw new We("catalog_invalid","A profile is missing a specialist route.",{profile:r.name})}for(let n=0;n<Li.length;n+=1){let r=-1;for(let o of e){let i=o.routes[n];if(!i||rP[i.effort]<r)throw new We("catalog_invalid","Profile route effort is not monotonic.",{route:Li[n]??"unknown"});r=rP[i.effort]}}}function fr(e){let t=bn(Lo,e);if(Ee(t))return Jo(new We("invalid_profile","Unknown profile selection.",{field:"profile"},{cause:t.left}));let n=aP.get(t.right);if(!n)return Jo(new We("invalid_profile","Unknown profile selection.",{profile:t.right}));return Zi(n)}var oP="gpt-5.6-luna",VU,rP,Yx,BU,Zx,iP,aP,WU;var sP=x(()=>{tn();Xi();nl();Ya();VU=new Set(Li),rP={low:0,medium:1,high:2,xhigh:3,max:4},Yx=[{profile:"low",rationale:"The low profile keeps bounded specialist work economical.",efforts:{"Explorer:lookup":"medium","Explorer:trace":"high","Librarian:lookup":"medium","Librarian:research":"high","Worker:mechanical":"high","Worker:implementation":"high","Worker:integration":"max","Worker:operations":"high","Worker:validation":"medium","Reviewer:plan":"high","Reviewer:code":"max","Reviewer:artifact":"high"}},{profile:"default",rationale:"The default profile is the recommended balanced route.",efforts:{"Explorer:lookup":"medium","Explorer:trace":"xhigh","Librarian:lookup":"medium","Librarian:research":"xhigh","Worker:mechanical":"high","Worker:implementation":"xhigh","Worker:integration":"max","Worker:operations":"high","Worker:validation":"high","Reviewer:plan":"xhigh","Reviewer:code":"max","Reviewer:artifact":"xhigh"}},{profile:"high",rationale:"The high profile maximizes specialist reasoning where specified.",efforts:{"Explorer:lookup":"medium","Explorer:trace":"max","Librarian:lookup":"medium","Librarian:research":"max","Worker:mechanical":"xhigh","Worker:implementation":"max","Worker:integration":"max","Worker:operations":"xhigh","Worker:validation":"xhigh","Reviewer:plan":"max","Reviewer:code":"max","Reviewer:artifact":"max"}}];Yn(Yx);BU=new Map(Yx.map((e)=>[e.profile,e]));Zx=[Gx({name:"low",effort:"low"}),Gx({name:"default",effort:"medium"}),Gx({name:"high",effort:"high"})];zU(Zx);Yn(Zx);iP=Zx,aP=new Map,WU=new Map;for(let e of iP){aP.set(e.name,e);let t=new Map;for(let n of e.routes)t.set(n.key,n);WU.set(e.name,t)}});import{execFile as JU}from"child_process";import{promisify as GU}from"util";var lP="holycodex-intent-1",uP="holycodex-plan-1",pP="holycodex-assignment-1",zd="toon-4",Z,qo,Xx,dP,ol,Vn,Xe,wY,Qx,Di,eS,tS,YU,cP,ZU,XU,nS,fP,mP,QU,vY,eH,tH,nH,rH,oH,iH,aH,TY;var hP=x(()=>{bt();nl();Ya();Z=k.pipe(Ze((e)=>e.trim().length>0)),qo=k.pipe(le(/^[a-z0-9][a-z0-9-]{0,95}$/u)),Xx=k.pipe(le(/^[a-f0-9]{64}$/u)),dP=k.pipe(le(/^[a-f0-9]{40}$/u)),ol=qd.pipe(RA(1)),Vn=k.pipe(Ze((e)=>!Number.isNaN(Date.parse(e)))),Xe=q(Z),wY=_({pid:qd.pipe(Cx(0)),token:Z}),Qx=_({role:v("Explorer","Librarian","Worker","Reviewer"),task:Z}).pipe(Ze((e)=>jn.some((t)=>t.role===e.role&&t.tasks.some((n)=>n.name===e.task)))),Di=_({kind:v("changed_path","check","repository_fact","ci","behavior","uncertainty"),value:Z,result:b(v("passed","failed","observed","unknown"))}),eS=_({root:Z,git_common_dir:Z,initial_head:Z,expected_head:Z,expected_changes:Xe,expected_status_digest:Xx,integrated_commit:b(dP),updated_at:Vn}),tS=v("scoping","ready","executing","verifying","reviewing","blocked","needs_root_input","complete","abandoned"),YU=v("scoping","ready","executing","verifying","reviewing"),cP=_({required:J,status:v("not_required","missing","passed","failed","accepted","rejected"),evidence:q(Di)}),ZU=_({schema_version:v(lP),toon_compatibility:v(zd),id:qo,slug:qo,title:Z,goal:Z,acceptance_criteria:Xe,state:tS,revision:ol,plan_required:J,active_plan_revision:b(ol),active_plan_digest:b(Xx),blockers:Xe,resume_state:b(YU),verification:cP,review:cP,acceptance_met:J,root_readiness:J,evidence:q(Di),baseline:eS,created_at:Vn,updated_at:Vn}),XU=_({schema_version:v(uP),toon_compatibility:v(zd),intent_id:qo,revision:ol,predecessor_digest:b(Xx),approach:Z,scope:Xe,exclusions:Xe,assignments:Xe,dependencies:Xe,architecture:Xe,risks:Xe,assumptions:Xe,open_questions:Xe,verification:Xe,recovery:Xe,updated_at:Vn}),nS=v("completed","blocked","needs_root_input","failed"),fP=v("pending","executing","completed","blocked","needs_root_input","failed"),mP=_({id:qo,outcome:nS,started_at:Vn,finished_at:Vn,summary:Z,evidence:q(Di),blocker:b(Z),remaining_risk:Xe}),QU=_({schema_version:v(pP),toon_compatibility:v(zd),intent_id:qo,id:qo,objective:Z,owner:Qx,scope:Xe,constraints:Xe,exclusions:Xe,dependencies:Xe,acceptance_criteria:Xe,status:fP,revision:ol,invocations:q(mP),active_invocation_id:b(Z),active_started_at:b(Vn),evidence:q(Di),blocker:b(Z),remaining_risk:Xe,created_at:Vn,updated_at:Vn}),vY=_({schema_version:v("holycodex-intent-0"),id:qo,slug:qo,title:Z,goal:Z,acceptance_criteria:Xe,state:tS,revision:ol,baseline:eS,created_at:Vn,updated_at:Vn}),eH=_({title:Z,goal:Z,acceptanceCriteria:q(Z).pipe(Zc(1)),planRequired:b(J),verificationRequired:b(J),reviewRequired:b(J)}),tH=_({approach:Z,scope:b(q(Z)),exclusions:b(q(Z)),assignments:b(q(Z)),dependencies:b(q(Z)),architecture:b(q(Z)),risks:b(q(Z)),assumptions:b(q(Z)),openQuestions:b(q(Z)),verification:b(q(Z)),recovery:b(q(Z))}),nH=_({id:b(Z),objective:Z,owner:Qx,scope:q(Z).pipe(Zc(1)),constraints:b(q(Z)),exclusions:b(q(Z)),dependencies:b(q(Z)),acceptanceCriteria:q(Z).pipe(Zc(1))}),rH=_({scope:q(Z).pipe(Zc(1))}),oH=_({commit:dP}),iH=_({invocationId:b(Z),outcome:nS,startedAt:b(Z),summary:Z,evidence:b(q(Di)),blocker:b(Z),remainingRisk:b(q(Z))}),aH=_({evidence:b(q(Di)),verification:b(v("passed","failed")),review:b(v("accepted","rejected")),acceptanceMet:b(J),rootReadiness:b(J),clearBlockers:b(J)}),TY=GU(JU)});var ut=x(()=>{B_();Xi();Ya();Fx();LA();$d();nl();nP();sP();Wx();hP()});function re(e){if(typeof e!=="object"||e===null||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function Fe(e){try{return dr(e),!0}catch{return!1}}function SH(e){switch(e){case"invalid_external_data":case"manifest_invalid":case"empty_output_directory":return"validation";case"discovery_failed":return"identity";case"protocol_mismatch":case"method_unsupported":case"server_request_unsupported":case"unexpected_response":return"protocol";case"invalid_transport_line":case"transport_closed":case"transport_failure":return"transport";case"approval_required":case"permission_denied":return"approval";case"cancellation":return"interruption";case"timeout":return"timeout";case"turn_failed":return"turn";case"closed":return"closed";case"server_error":return"server"}}function xP(e){return{ok:!1,error:e}}function SP(e){return{ok:!0,value:e}}function sn(e,t=512){let n="";for(let r of e){let o=r.codePointAt(0)??0;n+=o<=8||o===11||o===12||o>=14&&o<=31||o===127?" ":r}return n.replace(/\s+/gu," ").trim().slice(0,t)}function qi(e,t=0){if(t>3)return"[truncated]";if(e===null||typeof e==="boolean")return e;if(typeof e==="string")return sn(e,256);if(typeof e==="number")return Number.isFinite(e)?e:null;if(Array.isArray(e))return e.slice(0,32).map((n)=>qi(n,t+1));if(re(e)){let n={};for(let[r,o]of Object.entries(e).slice(0,32)){let i=sn(r,96);if(i.length>0)n[i]=qi(o,t+1)}return n}return"[redacted]"}function _P(e){let t=qi(e);return re(t)?t:{value:t}}function Le(e,t,n){return new K("invalid_external_data",`Invalid ${e}.`,{field:e,received:qi(t)},n===void 0?void 0:{cause:n})}function Pe(e,t,n){let r=bn(e,t);if(Ee(r))throw Le(n,t,String(r.left));return r.right}function bP(e,t){try{return Pe(e,t,"value"),!0}catch{return!1}}var iS,cl=1048576,aS=65536,cn,Uo,_5,Xr,xH,K;var mr=x(()=>{ut();tn();bt();iS=vr;cn=H((e)=>Fe(e)),Uo=H((e)=>re(e)&&Fe(e)),_5=k.pipe(le(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u)),Xr=k.pipe(Ze((e)=>e.length>0&&e.length<=4096)),xH=Gt.pipe(Ze((e)=>Number.isFinite(e)&&e>=0));K=class K extends Error{code;kind;details;retryable;constructor(e,t,n={},r){super(t,r?.cause===void 0?void 0:{cause:r.cause});this.name="CodexError",this.code=e,this.kind=SH(e),this.details=n,this.retryable=r?.retryable??!1,Object.freeze(this.details),Object.freeze(this)}}});var sS,ll,ul,cS,lS,uS,pS="turn/completed";var Yd=x(()=>{sS=["initialize","thread/start","thread/resume","thread/read","thread/list","thread/fork","thread/unsubscribe","turn/start","turn/steer","turn/interrupt","model/list","modelProvider/capabilities/read","config/read","permissionProfile/list"],ll=["item/commandExecution/requestApproval","item/fileChange/requestApproval","applyPatchApproval","execCommandApproval"],ul=["item/permissions/requestApproval"],cS=["mcpServer/elicitation/request"],lS=["item/tool/call"],uS={method:"initialized"}});function Xa(e,t=new Set){if(e===null||typeof e==="string"||typeof e==="boolean")return!0;if(typeof e==="number")return Number.isFinite(e);if(typeof e!=="object")return!1;if(t.has(e))return!1;t.add(e);try{if(Array.isArray(e))return e.every((n)=>Xa(n,t));return re(e)&&Object.values(e).every((n)=>Xa(n,t))}finally{t.delete(e)}}function hr(e){return re(e)&&Xa(e)}function dS(e){let t=[],n=0,r=!1,o=!1;for(let i=0;i<=e.length;i+=1){let a=e[i];if(i===e.length||a==="."&&!r){let s=e.slice(n,i),c=s.startsWith('"')?bH(s):s;if(!/^[A-Za-z][A-Za-z0-9_-]*$/u.test(c)&&!Za.includes(c))throw Le("TOML key path",e);t.push(c),n=i+1;continue}if(r){if(o)o=!1;else if(a==="\\")o=!0;else if(a==='"')r=!1}else if(a==='"')r=!0}if(r||o||t.length===0)throw Le("TOML key path",e);if(t.some((i)=>i==="__proto__"||i==="constructor"||i==="prototype"))throw Le("TOML key path",e);return t}function bH(e){try{let t=JSON.parse(e);if(typeof t==="string")return t}catch{}throw Le("TOML quoted key",e)}function Te(e,t){if(!hr(e))throw Le("TOML document",e);let n=e;for(let r of dS(t)){if(!hr(n)||!Object.prototype.hasOwnProperty.call(n,r))return;n=n[r]}return n}function Zd(e){if(Array.isArray(e))return e.map(Zd);if(re(e))return Object.fromEntries(Object.entries(e).map(([t,n])=>[t,Zd(n)]));return e}function Xd(e){return Zd(e)}function dl(e,t,n){if(!hr(e)||!Xa(n))throw Le("TOML write",{keyPath:t});let r=dS(t),o={...Xd(e)},i=o;for(let a of r.slice(0,-1)){let s=i[a];if(s!==void 0&&!hr(s))throw Le("TOML table path",t);let c=s===void 0?{}:{...s};i[a]=c,i=c}return i[r.at(-1)]=Zd(n),o}function fl(e,t){if(!hr(e))throw Le("TOML document",e);let n=dS(t),r={...Xd(e)},o=[],i=r;for(let s of n.slice(0,-1)){let c=i[s];if(!hr(c))return r;let l={...c};o.push({table:i,key:s}),i[s]=l,i=l}let a=n.at(-1);if(!Object.prototype.hasOwnProperty.call(i,a))return r;delete i[a];for(let s=o.length-1;s>=0;s-=1){let c=o[s],l=c.table[c.key];if(hr(l)&&Object.keys(l).length===0)delete c.table[c.key];else break}return r}function ml(e){if(typeof e!=="string")return!1;if(vP.includes(e))return!0;if(/^agents\.(?:explorer|librarian|worker|reviewer)\.config_file$/u.test(e))return!0;return Za.some((t)=>e===`agents."${t}".config_file`)}function Qd(e){return ml(e)}function Ho(e){return typeof e==="string"&&vH.test(e)}function fS(e){return e==="gpt-6-astra"||e==="gpt-5.6-terra"||e==="gpt-5.6-sol"||e==="gpt-5.6-luna"||e==="low"||e==="medium"||e==="high"||e==="xhigh"||e==="max"||e==="default"||e==="fast"}function TH(e){return typeof e==="string"&&/^[a-f0-9]{64}$/u.test(e)}function mS(e,t){let n=new Set(t);return Object.keys(e).every((r)=>n.has(r))}function hS(e){if(!re(e)||!mS(e,["kind","value"])||typeof e.kind!=="string")return!1;switch(e.kind){case"enum":return fS(e.value);case"boolean":return typeof e.value==="boolean";case"relative_path":return typeof e.value==="string"&&nf(e.value);case"digest":return TH(e.value);default:return!1}}function wP(e,t){switch(yS(e)){case"boolean":return t.kind==="boolean";case"relative_path":return t.kind==="relative_path";case"digest":return t.kind==="digest";case"enum":if(t.kind!=="enum")return!1;if(e==="model")return t.value==="gpt-6-astra"||t.value==="gpt-5.6-terra"||t.value==="gpt-5.6-sol"||t.value==="gpt-5.6-luna";if(e==="model_reasoning_effort")return t.value==="low"||t.value==="medium"||t.value==="high"||t.value==="xhigh"||t.value==="max";if(e==="service_tier")return t.value==="default"||t.value==="fast";return t.value==="low"||t.value==="medium"||t.value==="high"}}function RP(e){return re(e)&&e.kind==="absent"?Object.keys(e).length===1:hS(e)}function kP(e){return re(e)&&mS(e,["owner","schema","installId","keyPath","originalValue","lastManagedValue"])&&e.owner==="holycodex"&&typeof e.schema==="string"&&Ho(e.schema)&&Ho(e.installId)&&Qd(e.keyPath)&&RP(e.originalValue)&&hS(e.lastManagedValue)&&wP(e.keyPath,e.lastManagedValue)&&(e.originalValue.kind==="absent"||wP(e.keyPath,e.originalValue))}function Qa(e){if(!re(e)||!mS(e,["owner","schema","installId","managed"])||e.owner!=="holycodex"||!Ho(e.schema)||!Ho(e.installId)||!re(e.managed))return!1;return Object.entries(e.managed).every(([t,n])=>Qd(t)&&kP(n)&&n.keyPath===t)}function tf(e){if(!Ho(e.schema)||!Ho(e.installId))throw Le("managed runtime config metadata",{schema:e.schema});return{owner:"holycodex",schema:e.schema,installId:e.installId,managed:{}}}function nf(e){if(e.length===0||e.includes("\x00")||/^[\\/]|^[A-Za-z]:[\\/]/u.test(e))return!1;let t=e.replaceAll("\\","/").split("/");return t.some((n)=>n!==".")&&t.every((n)=>n.length>0&&n!=="..")}function gS(e){if(!nf(e))throw Le("relative config path","[redacted]");return e.replaceAll("\\","/").split("/").filter((t)=>t!==".").join("/")}function hl(e,t){let n=gS(t),r=e.replaceAll("\\","/").split("/");r.pop();let o=[...r,...n.split("/")].join("/"),i=[];for(let c of o.split("/")){if(c.length===0||c===".")continue;if(c==="..")i.pop();else i.push(c)}let a=e.replaceAll("\\","/");return`${a.startsWith("//")?"//":a.startsWith("/")?"/":""}${i.join("/")}`}function yS(e){if(e==="developer_instructions")return"digest";if(e.endsWith(".config_file"))return"relative_path";if(e==="suppress_unstable_features_warning"||e==="features.default_mode_request_user_input"||e==="features.multi_agent_v2"||e==="features.context_management"||e==="features.context_management.experimental_mode")return"boolean";return"enum"}function EH(e,t){let n=yS(e);if(n==="boolean")return typeof t==="boolean";if(n==="relative_path")return typeof t==="string"&&nf(t);if(n==="digest")return typeof t==="string";return typeof t==="string"&&fS(t)}async function gr(e,t){if(!Qd(e)||!Xa(t))throw Le("managed config value",{keyPath:e});let n=yS(e);if(n==="boolean"&&typeof t==="boolean")return{kind:n,value:t};if(n==="relative_path"&&typeof t==="string"&&nf(t))return{kind:n,value:gS(t)};if(n==="enum"&&typeof t==="string"&&fS(t))return{kind:n,value:t};return{kind:"digest",value:await Zr("holycodex-managed-config-value",[Yr({keyPath:e,value:t})])}}function OH(e){if(e.kind==="enum"||e.kind==="boolean"||e.kind==="relative_path")return e.value;return}async function gl(e,t,n,r){if(!hr(e)||!Qa(t)||!Ho(r.schema)||!Ho(r.installId))throw Le("managed runtime config",{});let o={...t.managed},i=Xd(e),a=[];for(let[c,l]of Object.entries(n)){if(!ml(c)||typeof l!=="string"&&typeof l!=="boolean")throw Le("managed config key",c);let u=c,p=t.managed[u],f=Te(i,u);if(p&&(p.schema!==r.schema||p.installId!==r.installId)){a.push(u);continue}if(p&&p.owner==="holycodex"){let m=f===void 0?void 0:await gr(u,f);if(m===void 0||JSON.stringify(m)!==JSON.stringify(p.lastManagedValue)){a.push(u);continue}}let h=p?.originalValue??(f===void 0?{kind:"absent"}:await gr(u,f));if(!EH(u,l))throw Le("managed config value",{keyPath:u});i=dl(i,u,l),o[u]={owner:"holycodex",schema:r.schema,installId:r.installId,keyPath:u,originalValue:h,lastManagedValue:await gr(u,l)}}let s={owner:"holycodex",schema:r.schema,installId:r.installId,managed:o};if(!Qa(s))throw Le("managed runtime config state",{});return{document:i,state:s,driftedKeys:a}}async function Ui(e,t,n){if(!hr(e)||!Qa(t))throw Le("managed runtime config",{});let r=Xd(e),o={...t.managed},i=[],a=[],s=[];for(let[c,l]of Object.entries(t.managed)){if(!Qd(c))throw Le("managed config key",c);let u=c;if(l.owner!=="holycodex"||l.schema!==n.schema||l.installId!==n.installId){if(l.schema!==n.schema||l.installId!==n.installId)s.push(u);continue}let p=Te(r,u);if(!(p!==void 0&&JSON.stringify(await gr(u,p))===JSON.stringify(l.lastManagedValue))){a.push(u);continue}if(l.originalValue.kind==="absent")r=fl(r,u),i.push(u),delete o[u];else{let h=OH(l.originalValue);if(h===void 0){s.push(u),a.push(u);continue}r=dl(r,u,h),i.push(u),delete o[u]}}return{document:r,state:{...t,managed:o},restoredKeys:i,preservedKeys:a,unresolvedKeys:s}}async function es(e,t,n){if(!ml(n)||!Qa(t))throw Le("managed config key",n);let r=t.managed[n],o=Te(e,n),i=o===void 0?void 0:await gr(n,o);if(!r)return i===void 0?{keyPath:n,status:"unmanaged"}:{keyPath:n,status:"unmanaged",current:i};return{keyPath:n,status:i!==void 0&&JSON.stringify(i)===JSON.stringify(r.lastManagedValue)?"unchanged":"drifted",expected:r.lastManagedValue,...i===void 0?{}:{current:i}}}var _H,pl,vP,wH,TP,EP,OP,ef,vH;var rf=x(()=>{ut();ut();bt();mr();_H=H((e)=>Xa(e)),pl=H((e)=>hr(e));vP=["model","model_reasoning_effort","service_tier","model_verbosity","developer_instructions","suppress_unstable_features_warning","features.default_mode_request_user_input","features.multi_agent_v2","features.context_management","features.context_management.experimental_mode"],wH=H((e)=>ml(e));TP=H((e)=>hS(e)),EP=H((e)=>RP(e)),OP=H((e)=>kP(e)),ef=H((e)=>Qa(e)),vH=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u});function kH(e){return typeof e==="number"&&Number.isFinite(e)&&e>=0}function CP(e,t,n){let r=new Set([...t,n]),o=Object.keys(e);if(Object.keys(e).some((i)=>!r.has(i)))return!1;return o.length>0&&o.every((i)=>kH(e[i]))}function IP(e){if(!re(e)||!Fe(e))return!1;return CP(e,["inputTokens","cachedInputTokens","outputTokens","reasoningOutputTokens"],"totalTokens")||CP(e,["input_tokens","cached_input_tokens","output_tokens","reasoning_output_tokens"],"total_tokens")}function of(e){return re(e)&&Fe(e)&&typeof e.id==="string"&&/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u.test(e.id)}function MP(e){return re(e)&&Fe(e)&&of(e.thread)}function PH(e){return re(e)&&Fe(e)&&typeof e.id==="string"}function $o(e){return re(e)&&Fe(e)&&typeof e.threadId==="string"&&e.threadId.length>0}function NP(e){return re(e)&&Fe(e)&&typeof e.id==="string"&&e.id.length>0&&(e.usage===void 0||IP(e.usage))}function IH(e){return re(e)&&Fe(e)&&typeof e.id==="string"&&typeof e.model==="string"&&(e.supportedReasoningEfforts===void 0||Array.isArray(e.supportedReasoningEfforts)&&e.supportedReasoningEfforts.every((t)=>re(t)&&typeof t.reasoningEffort==="string"))&&(e.serviceTiers===void 0||Array.isArray(e.serviceTiers)&&e.serviceTiers.every((t)=>re(t)&&typeof t.id==="string"))&&(e.defaultServiceTier===void 0||e.defaultServiceTier===null||typeof e.defaultServiceTier==="string")&&(e.multiAgentVersion===void 0||e.multiAgentVersion===null||e.multiAgentVersion==="disabled"||e.multiAgentVersion==="v1"||e.multiAgentVersion==="v2")}function FP(e){if(ul.some((t)=>t===e))return"permissions";if(ll.some((t)=>t===e))return"approval";if(cS.some((t)=>t===e))return"elicitation";if(lS.some((t)=>t===e))return"dynamic_tool";return"other"}var AP,yl,PP,xl,RH,xS,Sl,CH,af,SS,_S,AH,_l,bS,wS,vS,TS,ES,OS,RS,kS,CS,AS,PS,IS,MS,NS,FS,LS,DS,qS,US,HS,$S,jS,VS,BS,KS,zS,WS,JS,A5,MH,P5;var GS=x(()=>{bt();mr();Yd();rf();AP=k.pipe(le(/^[A-Za-z][A-Za-z0-9_./:-]{0,127}$/u)),yl=xe(k.pipe(Ga(1)),Gt.pipe(Ze((e)=>Number.isSafeInteger(e)))),PP=_({code:Gt.pipe(Ze((e)=>Number.isSafeInteger(e))),message:k,data:b(cn)}),xl=xe(_({id:yl,result:cn}),_({id:yl,error:PP})),RH=_({id:yl,error:PP}),xS=_({method:AP,params:b(cn)}),Sl=_({id:yl,method:AP,params:b(cn),trace:b(cn)});CH=H(IP),af=_({clientInfo:_({name:Xr,version:Xr,title:xe(Xr,lt)}),capabilities:xe(_({experimentalApi:J,requestAttestation:J,mcpServerOpenaiFormElicitation:b(J),optOutNotificationMethods:b(xe(q(k),lt)),extensions:b(Uo)}),lt)}),SS=H((e)=>re(e)&&Fe(e)&&typeof e.userAgent==="string"&&typeof e.codexHome==="string"&&typeof e.platformFamily==="string"&&typeof e.platformOs==="string"),_S=_({method:v("initialized")});AH=H(of);_l=H((e)=>MP(e)||PH(e)),bS=_l,wS=_l,vS=H($o),TS=H((e)=>re(e)&&Fe(e)&&(e.status==="notLoaded"||e.status==="notSubscribed"||e.status==="unsubscribed")),ES=H((e)=>MP(e)),OS=H((e)=>{if(!re(e)||!Fe(e))return!1;let t=Array.isArray(e.data)&&e.data.every((r)=>of(r)),n=Array.isArray(e.threads)&&e.threads.every((r)=>of(r));return t&&e.threads===void 0||n&&e.data===void 0}),RS=H((e)=>re(e)&&Fe(e));kS=H($o),CS=H($o),AS=H($o),PS=H((e)=>re(e)&&Fe(e));IS=H((e)=>$o(e)&&(Array.isArray(e.input)&&e.input.every((t)=>Fe(t))||typeof e.prompt==="string"&&e.prompt.length>0)),MS=H((e)=>$o(e)&&typeof e.expectedTurnId==="string"&&Array.isArray(e.input)&&e.input.every((t)=>Fe(t))),NS=H((e)=>re(e)&&Fe(e)&&(e.turn!==void 0&&NP(e.turn)||typeof e.turnId==="string"&&e.turnId.length>0||typeof e.id==="string"&&e.id.length>0)),FS=H((e)=>re(e)&&Fe(e)&&typeof e.turnId==="string"&&e.turnId.length>0),LS=H((e)=>$o(e)&&typeof e.turnId==="string"&&e.turnId.length>0),DS=H((e)=>re(e)&&Fe(e)),qS=H((e)=>$o(e)&&(e.turn!==void 0&&NP(e.turn)||typeof e.turnId==="string"&&e.turnId.length>0)),US=H((e)=>re(e)&&Fe(e));HS=H((e)=>re(e)&&Fe(e)&&Array.isArray(e.data)&&e.data.every((t)=>IH(t))),$S=Uo,jS=Uo,VS=_({includeLayers:b(J),cwd:b(xe(k,lt))}),BS=_({config:pl,origins:Uo,layers:xe(q(Uo),lt)}),KS=Uo,zS=Uo,WS=H((e)=>re(e)&&Fe(e)&&(typeof e.id==="string"||typeof e.id==="number"&&Number.isSafeInteger(e.id))&&typeof e.method==="string"&&re(e.params)&&(e.category==="approval"||e.category==="dynamic_tool"||e.category==="elicitation"||e.category==="other"||e.category==="permissions")),JS=cn,A5=H((e)=>re(e)&&Fe(e)&&typeof e.kind==="string"&&typeof e.method==="string");MH=xe(v("stable","experimental","disabled"),J),P5=Ld({key:k,value:MH})});class sf{transport;maxLineBytes;requestTimeoutMs;signal;notificationListeners=new Set;serverRequestHandlers=new Set;pending=new Map;serverRequestWork=new Set;serverRequestTasks=new Set;nextRequestId=1;readerPromise;initializePromise;transportClosePromise;initializeAttempted=!1;initialized=!1;closed=!1;constructor(e,t={}){if(this.transport=e,this.maxLineBytes=t.maxLineBytes??cl,this.requestTimeoutMs=t.requestTimeoutMs,this.signal=t.signal,!Number.isSafeInteger(this.maxLineBytes)||this.maxLineBytes<1)throw new K("invalid_external_data","The maximum line size is invalid.");if(this.requestTimeoutMs!==void 0&&(!Number.isSafeInteger(this.requestTimeoutMs)||this.requestTimeoutMs<1))throw new K("invalid_external_data","The request timeout is invalid.");if(t.onNotification)this.notificationListeners.add(t.onNotification);if(t.onServerRequest)this.serverRequestHandlers.add(t.onServerRequest);if(this.signal?.aborted)this.close();else if(this.signal)this.signal.addEventListener("abort",()=>void this.close(),{once:!0})}get isInitialized(){return this.initialized}onNotification(e){return this.notificationListeners.add(e),()=>this.notificationListeners.delete(e)}onServerRequest(e){return this.serverRequestHandlers.add(e),()=>this.serverRequestHandlers.delete(e)}async initialize(e=NH){if(this.initializePromise)return this.initializePromise;if(this.initializeAttempted)throw new K("invalid_external_data","The App Server initialize handshake was already attempted.");this.ensureOpen();let t=Pe(af,e,"initialize parameters");return this.initializeAttempted=!0,this.initializePromise=this.performInitialize(t),this.initializePromise}async startThread(e={}){return this.action("thread/start",RS,e,_l)}async resumeThread(e){let t=typeof e==="string"?{threadId:e}:e;return this.action("thread/resume",kS,t,bS)}async readThread(e){let t=typeof e==="string"?{threadId:e}:e;return this.action("thread/read",CS,t,ES)}async listThreads(e={}){return this.action("thread/list",PS,e,OS)}async forkThread(e){let t=typeof e==="string"?{threadId:e}:e;return this.action("thread/fork",AS,t,wS)}async unsubscribeThread(e){let t=typeof e==="string"?{threadId:e}:e;return this.action("thread/unsubscribe",vS,t,TS)}async startTurn(e){return this.action("turn/start",IS,e,NS)}async steerTurn(e){return this.action("turn/steer",MS,e,FS)}async interruptTurn(e,t){let n=typeof e==="string"?{threadId:e,turnId:t??""}:e;return this.action("turn/interrupt",LS,n,DS)}async listModels(e={}){return this.action("model/list",US,e,HS)}async readModelProviderCapabilities(e={}){return this.action("modelProvider/capabilities/read",$S,e,jS)}async readConfig(e={}){return this.action("config/read",VS,e,BS)}async listPermissionProfiles(e={}){return this.action("permissionProfile/list",KS,e,zS)}async call(e,t={}){if(e==="initialize"){let r=await this.initialize(Pe(af,t,"initialize parameters"));return Pe(cn,r,"initialize result")}let n=Pe(Sl,{id:1,method:e,params:t},"App Server method");if(!FH.has(n.method))throw new K("method_unsupported",`Unsupported App Server method: ${e}.`,{method:e});return this.request(n.method,n.params===void 0?{}:n.params)}async close(){await this.closeWithError(new K("closed","The App Server client is closed."))}async performInitialize(e){try{let t=await this.request("initialize",Pe(cn,e,"initialize parameters")),n=Pe(SS,t,"initialize result"),r=Pe(_S,uS,"initialized notification");return await this.transport.writeLine(JSON.stringify(r)),this.initialized=!0,n}catch(t){let n=t instanceof K?t:new K("transport_failure","The initialize handshake failed.",{},{cause:t});throw await this.closeWithError(n),n}}async action(e,t,n,r){let o=Pe(t,n,`${e} parameters`),i=Pe(cn,o,`${e} parameters`),a=await this.request(e,i);return Pe(r,a,`${e} result`)}async request(e,t){if(this.ensureOpen(),e!=="initialize"&&!this.initialized)throw new K("invalid_external_data",`The ${e} action requires an initialized App Server client.`);this.startReader();let n=this.nextRequestId;this.nextRequestId+=1;let r=Pe(Sl,{id:n,method:e,params:t},`${e} request`);return new Promise((o,i)=>{let a=!1,s,c,l=(p)=>{if(a)return;if(a=!0,this.pending.delete(n),s!==void 0)clearTimeout(s);c?.(),i(p)};if(this.requestTimeoutMs!==void 0)s=setTimeout(()=>l(new K("timeout",`The ${e} request timed out.`,{method:e})),this.requestTimeoutMs);if(this.signal){let p=()=>l(new K("cancellation",`The ${e} request was cancelled.`,{method:e}));this.signal.addEventListener("abort",p,{once:!0}),c=()=>this.signal?.removeEventListener("abort",p)}let u={method:e,resolve:(p)=>{if(a)return;if(a=!0,s!==void 0)clearTimeout(s);c?.(),o(p)},reject:l,...s===void 0?{}:{timer:s},...c===void 0?{}:{removeAbortListener:c}};this.pending.set(n,u),this.transport.writeLine(JSON.stringify(r)).catch((p)=>{l(p instanceof K?p:new K("transport_failure","The App Server request could not be written.",{},{cause:p}))})})}startReader(){if(!this.readerPromise)this.readerPromise=this.readLoop().catch((e)=>this.handleReaderFailure(e)).catch(()=>{return})}async readLoop(){while(!this.closed){let e=await this.transport.readLine();if(e===null){if(!this.closed)throw new K("transport_closed","The App Server transport closed.");return}if(new TextEncoder().encode(e).byteLength>this.maxLineBytes)throw new K("invalid_transport_line","An App Server line exceeded the limit.");this.handleLine(e)}}async handleReaderFailure(e){let t=e instanceof K?e:new K("transport_failure","The App Server transport failed.",{},{cause:e});await this.closeWithError(t)}handleLine(e){let t;try{t=JSON.parse(e)}catch(i){throw new K("invalid_transport_line","The App Server emitted invalid JSON.",{},{cause:i})}let n=this.tryDecode(xl,t);if(n!==void 0){this.handleResponse(n);return}let r=this.tryDecode(Sl,t);if(r!==void 0){this.handleServerRequest(r);return}let o=this.tryDecode(xS,t);if(o!==void 0){this.handleNotification(o);return}throw Le("JSON-RPC message",t)}tryDecode(e,t){try{return Pe(e,t,"JSON-RPC message")}catch{return}}handleResponse(e){let t=this.pending.get(e.id);if(!t)throw new K("unexpected_response","The App Server returned an unknown request id.",{id:e.id});if(this.pending.delete(e.id),"error"in e){let n=e.error.code===-32001,r=DH(t.method);t.reject(new K(r,`The App Server rejected ${t.method}: ${sn(e.error.message)}.`,{method:t.method,serverCode:e.error.code,retryable:n,...e.error.data===void 0?{}:{data:qi(e.error.data)}},{retryable:n}));return}t.resolve(e.result)}handleServerRequest(e){let t=e.params??{},n=Pe(WS,{...e,params:t,category:FP(e.method)},"server request");this.emitNotification({kind:"server_request",method:e.method,params:t});let r=[...this.serverRequestHandlers];if(r.length===0){this.trackServerRequestTask(this.writeServerError(e.id,-32601,`No handler for ${e.method}.`));return}let o=r[0];if(o===void 0){this.trackServerRequestTask(this.writeServerError(e.id,-32601,`No handler for ${e.method}.`));return}let i={active:!0};this.serverRequestWork.add(i);let a;try{a=o(n)}catch(s){this.completeServerRequest(i,()=>this.writeServerError(e.id,-32000,sn(String(s))));return}if(a instanceof Promise){this.trackServerRequestTask(a.then((s)=>this.completeServerRequest(i,()=>this.writeValidatedServerResult(e.id,s)),(s)=>this.completeServerRequest(i,()=>this.writeServerError(e.id,-32000,sn(String(s))))));return}this.completeServerRequest(i,()=>this.writeValidatedServerResult(e.id,a))}writeValidatedServerResult(e,t){try{let n=Pe(JS,t,"server response");return this.writeServerResult(e,n)}catch(n){return this.writeServerError(e,-32000,sn(String(n)))}}completeServerRequest(e,t){if(!e.active)return;e.active=!1,this.serverRequestWork.delete(e);try{this.trackServerRequestTask(t())}catch{}}trackServerRequestTask(e){let t=e.catch(()=>{return});this.serverRequestTasks.add(t),t.then(()=>this.serverRequestTasks.delete(t),()=>this.serverRequestTasks.delete(t))}async writeServerResult(e,t){let n=Pe(xl,{id:e,result:t},"server response");await this.transport.writeLine(JSON.stringify(n))}async writeServerError(e,t,n){let r=Pe(xl,{id:e,error:{code:t,message:LH(n)}},"server error response");await this.transport.writeLine(JSON.stringify(r))}handleNotification(e){let t=e.params;if(e.method===pS){let n=Pe(qS,t,"turn/completed notification");this.emitNotification({kind:"turn_completed",method:e.method,params:n});return}if(e.method.includes("agent")||e.method.includes("subagent")){this.emitNotification({kind:"multi_agent",method:e.method,...t===void 0?{}:{params:t}});return}this.emitNotification({kind:"unknown",method:e.method,metadata:_P({params:qi(t)})})}emitNotification(e){for(let t of this.notificationListeners)try{t(e)}catch{}}rejectPending(e){for(let t of this.pending.values())t.reject(e);this.pending.clear()}async closeWithError(e){if(this.transportClosePromise!==void 0){await this.transportClosePromise;return}this.closed=!0,this.rejectPending(e);for(let t of this.serverRequestWork)t.active=!1;this.serverRequestWork.clear(),this.serverRequestTasks.clear(),this.transportClosePromise=Promise.resolve().then(()=>this.transport.close()).catch(()=>{return}),await this.transportClosePromise}ensureOpen(){if(this.closed)throw new K("closed","The App Server client is closed.")}}function LH(e){let t=sn(e);return t.length>0?t:"server request failed"}function DH(e){if(ul.some((t)=>t===e))return"permission_denied";if(ll.some((t)=>t===e))return"approval_required";if(e==="turn/interrupt")return"cancellation";if(e.startsWith("turn/"))return"turn_failed";return"server_error"}var NH,FH;var YS=x(()=>{mr();Yd();GS();NH={clientInfo:{name:"holycodex",title:null,version:iS},capabilities:null},FH=new Set(sS)});import{isAbsolute as qH}from"path";function jo(e=process.env){let t=["PATH","HOME","USER","CODEX_HOME","TMPDIR","TEMP","TMP","LANG","LC_ALL"],n={};for(let r of t){let o=e[r];if(o!==void 0&&o.length>0)n[r]=o}return n}function ZS(e=process.env){return Object.freeze(jo(e))}async function cf(e,t){let n=e.getReader(),r=[],o=0;try{while(!0){let s=await n.read();if(s.done)break;if(o+=s.value.byteLength,o>t)throw new K("invalid_transport_line","A subprocess stream exceeded its limit.");r.push(s.value)}}finally{n.releaseLock()}let i=new Uint8Array(o),a=0;for(let s of r)i.set(s,a),a+=s.byteLength;return i}function lf(e,t){try{return new TextDecoder("utf-8",{fatal:!0}).decode(e)}catch(n){throw new K("invalid_transport_line",`Invalid UTF-8 in ${t}.`,{},{cause:n})}}function ts(e){return sn(e.replace(/Bearer\s+[^\s]+/giu,"Bearer [redacted]").replace(/((?:api[_-]?key|authorization|cookie|password|secret|token)\s*[:=]\s*)[^\s,;]+/giu,"$1[redacted]"),512)}class uf{process;stdin;stdoutReader;stderrStream;maxLineBytes;maxDiagnosticBytes;lineDecoder=new TextDecoder("utf-8",{fatal:!0});stderrDiagnostics=[];stdoutBuffer=new Uint8Array(0);stderrPromise;closed=!1;constructor(e){if(!qH(e.executablePath))throw new K("discovery_failed","The Codex executable path must be absolute.");if(this.maxLineBytes=e.maxLineBytes??cl,this.maxDiagnosticBytes=e.maxDiagnosticBytes??aS,this.maxLineBytes<1||this.maxDiagnosticBytes<1)throw new K("invalid_external_data","The transport bounds are invalid.");if(this.process=Bun.spawn([e.executablePath,"app-server"],{...e.cwd===void 0?{}:{cwd:e.cwd},env:jo(e.environment),stdin:"pipe",stdout:"pipe",stderr:"pipe"}),!(this.process.stdout instanceof ReadableStream)||!(this.process.stderr instanceof ReadableStream))throw new K("transport_failure","The Codex App Server did not expose stdio pipes.");if(typeof this.process.stdin==="number"||this.process.stdin===void 0)throw new K("transport_failure","The Codex App Server did not expose stdin.");if(this.stdin=this.process.stdin,this.stdoutReader=this.process.stdout,this.stderrStream=this.process.stderr,this.stderrPromise=this.collectStderr(),e.signal)if(e.signal.aborted)this.close();else e.signal.addEventListener("abort",()=>void this.close(),{once:!0})}get diagnostics(){return[...this.stderrDiagnostics]}async readLine(){if(this.closed&&this.stdoutBuffer.byteLength===0)return null;let e=this.stdoutReader.getReader();try{while(!0){let t=this.stdoutBuffer.indexOf(10);if(t>=0){if(t>this.maxLineBytes)throw await this.close(),new K("invalid_transport_line","The App Server emitted an overlong line.");let o=this.stdoutBuffer.slice(0,t);this.stdoutBuffer=this.stdoutBuffer.slice(t+1);let i=o.at(-1)===13?o.slice(0,-1):o;return this.lineDecoder.decode(i)}if(this.stdoutBuffer.byteLength>this.maxLineBytes)throw await this.close(),new K("invalid_transport_line","The App Server emitted an overlong line.");let n=await e.read();if(n.done){if(this.stdoutBuffer.byteLength===0)return null;if(this.stdoutBuffer.byteLength>this.maxLineBytes)throw await this.close(),new K("invalid_transport_line","The App Server emitted an overlong line.");let o=this.stdoutBuffer;return this.stdoutBuffer=new Uint8Array(0),this.lineDecoder.decode(o)}let r=new Uint8Array(this.stdoutBuffer.byteLength+n.value.byteLength);r.set(this.stdoutBuffer,0),r.set(n.value,this.stdoutBuffer.byteLength),this.stdoutBuffer=r}}catch(t){if(t instanceof K)throw t;throw new K("transport_failure","The App Server stdout could not be read.",{},{cause:t})}finally{e.releaseLock()}}async writeLine(e){if(this.closed)throw new K("closed","The App Server transport is closed.");if(new TextEncoder().encode(e).byteLength>this.maxLineBytes)throw new K("invalid_transport_line","The App Server request exceeded the line limit.");try{await this.stdin.write(`${e}
35
+ `),await this.stdin.flush()}catch(t){throw new K("transport_failure","The App Server stdin could not be written.",{},{cause:t})}}async close(){if(this.closed)return;this.closed=!0;try{await Promise.resolve(this.stdin.end())}catch{}try{this.process.kill()}catch{}await Promise.race([this.process.exited,new Promise((e)=>setTimeout(()=>e(-1),1000))]),await this.stderrPromise.catch(()=>{return})}async collectStderr(){try{let e=await cf(this.stderrStream,this.maxDiagnosticBytes),t=lf(e,"Codex stderr");for(let n of t.split(/\r?\n/u).slice(0,128)){let r=ts(n);if(r.length>0)this.stderrDiagnostics.push(r)}}catch{this.stderrDiagnostics.push("[stderr unavailable]")}}}var pf=x(()=>{mr()});import{lstat as $5,mkdir as j5,readFile as UH,readdir as V5,realpath as HH,stat as $H}from"fs/promises";import{delimiter as jH,isAbsolute as K5,join as z5,relative as W5,resolve as LP}from"path";async function BH(e){let t=[];if(e.executablePath!==void 0)t.push(LP(e.cwd??process.cwd(),e.executablePath));else{let n=e.pathValue??e.environment?.PATH??process.env.PATH??"",r=process.platform==="win32"?["codex.exe","codex.cmd","codex"]:["codex"];for(let o of n.split(jH).filter((i)=>i.length>0))for(let i of r)t.push(LP(o,i))}for(let n of t)try{let r=await $H(n);if(!r.isFile())continue;if(process.platform!=="win32"&&(r.mode&73)===0)continue;return await HH(n)}catch{if(e.executablePath!==void 0)throw new K("discovery_failed","The explicit Codex executable was not found.",{path:n})}throw new K("discovery_failed","No Codex executable was found on the allowlisted PATH.")}async function KH(e,t){let n=Bun.spawn([e,"--version"],{env:t,stdin:"ignore",stdout:"pipe",stderr:"pipe"});if(!(n.stdout instanceof ReadableStream)||!(n.stderr instanceof ReadableStream))throw new K("discovery_failed","The Codex version command did not expose output pipes.");try{let[r,o,i]=await WH(Promise.all([cf(n.stdout,16384),cf(n.stderr,16384),n.exited]),()=>n.kill(),"The Codex version command timed out."),a=sn(lf(r,"Codex version output"));if(i!==0||a.length===0){let s=ts(lf(o,"Codex version diagnostics"));throw new K("discovery_failed","The Codex executable did not provide a version.",{exitCode:i,diagnostics:s})}return a}catch(r){try{n.kill()}catch{}if(r instanceof K)throw r;throw new K("discovery_failed","The Codex version command failed.",{},{cause:r})}}async function zH(e){let t=await UH(e),n=await crypto.subtle.digest("SHA-256",t),r=[...new Uint8Array(n)].map((i)=>i.toString(16).padStart(2,"0")).join(""),o=Hd(r);if(!o.ok)throw new K("discovery_failed","The Codex executable digest was invalid.");return o.value}async function XS(e={}){let t=await BH(e),n=jo(e.environment),r=e.versionRunner?sn(await e.versionRunner(t,n)):await KH(t,n);if(r.length===0)throw new K("discovery_failed","The Codex version output was empty.");return{path:t,version:r,sha256:await zH(t)}}async function WH(e,t,n){let r;try{return await Promise.race([e,new Promise((o,i)=>{r=setTimeout(()=>{try{t()}catch{}i(new K("timeout",n))},VH)})])}finally{if(r!==void 0)clearTimeout(r)}}var VH=30000,Z5;var DP=x(()=>{ut();bt();mr();pf();Z5=_({exitCode:Gt.pipe(Ze((e)=>Number.isSafeInteger(e))),stdout:k.pipe(kx(1048576)),stderr:k.pipe(kx(1048576))})});var JH="packages/codex/generated",GH,YH,QS,t4,n4;var qP=x(()=>{ut();bt();mr();GH=/^codex-cli \d+\.\d+\.\d+$/u,YH=/^codex-app-server-\d+\.\d+\.\d+$/u,QS=k.pipe(le(/^[a-f0-9]{64}$/u)),t4=_({schema_version:v("holycodex-generated-v2"),artifact_root:v(JH),codex_cli_version:k.pipe(le(GH)),codex_cli_digest:QS,protocol_epoch:k.pipe(le(YH)),generator:_({command:yA(v("app-server"),v("generate-ts")),supported_surface:v("codex app-server generators")}),typescript_root:v("typescript"),files:_({count:Gt.pipe(Dd(),Ax()),digest:QS})}),n4=_({path:k.pipe(Ga(1)),size:Gt.pipe(Dd(),Ax()),sha256:QS})});var ZH;var UP=x(()=>{bt();rf();ZH=_({owner:v("holycodex"),schema:k.pipe(le(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u)),installId:k.pipe(le(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u))})});import{spawn as XH}from"child_process";import{lstat as Bo,mkdir as QH,mkdtemp as e$,readFile as t$,readdir as n$,realpath as e_,rename as r$,rm as o$,stat as c4}from"fs/promises";import{dirname as $P,isAbsolute as i_,join as Vo,relative as jP,resolve as ff,sep as VP}from"path";async function KP(e){let t=l_(e.selectedPluginIds);if(t.length===0)return;if(GP(e.timeoutMs,e.pollIntervalMs),e.signal?.aborted)throw new Se("cancelled","Official Codex marketplace bootstrap was cancelled.");let n=e.readSnapshot??((s)=>c_(s,e.selectedPluginIds)),r=await n(e.codexHome);if(r!==void 0&&hf(r,t))return r;let o=e.initializeRuntime??(()=>h$(e)),i,a;try{i=await o()}catch(s){a=Y("marketplace_unavailable","Codex runtime initialization could not start the official marketplace sync. Check that Codex is available and its network/policy settings permit the official marketplace.",s)}if(a===void 0)try{let s=e.timeoutMs??s_,c=e.pollIntervalMs??i$,l=Date.now();while(Date.now()-l<=s){if(e.signal?.aborted)throw new Se("cancelled","Official Codex marketplace bootstrap was cancelled.");let u=await n(e.codexHome);if(u!==void 0&&hf(u,t))return u;let p=s-(Date.now()-l);if(p<=0)break;await(e.sleep??y$)(Math.min(c,p))}a=Y("marketplace_timeout","The official Codex marketplace did not become ready before the bounded wait expired. Check network access and Codex marketplace policy, then retry.")}catch(s){if(s instanceof Se&&s.code==="cancelled")throw s;a=s instanceof Se?s:Y("marketplace_unavailable","The official Codex marketplace sync failed before its bounded wait completed.",s)}finally{await i?.()}if(e.gitFallback!==!1)try{return await zP({codexHome:e.codexHome,selectedPluginIds:e.selectedPluginIds,...e.environment===void 0?{}:{environment:e.environment},...e.timeoutMs===void 0?{}:{timeoutMs:e.timeoutMs},...e.signal===void 0?{}:{signal:e.signal},...e.gitFallback===void 0?{}:e.gitFallback})}catch(s){if(s instanceof Se)throw s;throw Y("marketplace_unavailable",`The official marketplace could not be populated after runtime startup (${a?.code??"unavailable"}). Check network access and retry.`,s)}throw a??Y("marketplace_timeout","The official Codex marketplace did not become ready before the bounded wait expired.")}async function zP(e){let t=l_(e.selectedPluginIds);if(t.length===0)throw Y("marketplace_invalid","The official marketplace fallback requires at least one selected provider plugin.");if(GP(e.timeoutMs,void 0),!i_(e.codexHome))throw Y("marketplace_invalid","The Codex home for official marketplace fallback must be absolute.");if(e.signal?.aborted)throw new Se("cancelled","Official Codex marketplace fallback was cancelled.");let n=jo(e.environment),r=e.gitRunner??XP("git",{environment:n,...e.timeoutMs===void 0?{}:{timeoutMs:e.timeoutMs}}),o=e.timeoutMs??s_,i;try{i=await c$(r,o,e.signal)}catch(u){if(u instanceof Se)throw u;throw Y("marketplace_unavailable","The official Codex marketplace remote HEAD could not be resolved. Check network access and retry.",u)}let a=Vo(e.codexHome,"plugins"),s=Vo(a,a_[1]);if(await u$(a,e.codexHome),await Bo(s).catch((u)=>{if(Tl(u))return;throw Y("marketplace_invalid","The reserved official marketplace path could not be inspected safely.",u)})!==void 0)throw Y("marketplace_invalid","The reserved official marketplace path appeared during bootstrap; refusing to overwrite it.");let l=await e$(Vo(a,".openai-plugins-stage-"));try{if(await n_(e.codexHome,l),e.cloneSnapshot!==void 0)try{await e.cloneSnapshot(Hi,l)}catch(m){if(g$(m))throw Y("marketplace_invalid","The staged official marketplace could not be created as a safe file tree.",m);throw m}else{let m=await r.run(["clone","--depth=1","--no-tags",Hi,l],{...e.signal===void 0?{}:{signal:e.signal},timeoutMs:o});if(m.exitCode!==0)throw Y("marketplace_unavailable","The official Codex marketplace could not be downloaded. Check network access and retry.",m.stderr)}await mf(l);let u=await WP(l,e.codexHome,t);if(u===void 0||!hf(u,t))throw Y("marketplace_invalid","The downloaded official marketplace is missing the selected plugin entries or manifest.");if(await l$(r,l,o,e.signal)!==i)throw Y("marketplace_invalid","The downloaded official marketplace did not match the verified remote HEAD.");if(await Bo(s).catch((m)=>{if(Tl(m))return;throw Y("marketplace_invalid","The reserved official marketplace path could not be checked before publication.",m)})!==void 0)throw Y("marketplace_invalid","The reserved official marketplace path appeared during staging; refusing to overwrite it.");await r$(l,s);let h=await c_(e.codexHome,e.selectedPluginIds);if(h===void 0||!hf(h,t))throw Y("marketplace_invalid","The published official marketplace failed validation.");return h}catch(u){if(u instanceof Se)throw u;throw Y("marketplace_unavailable","The official Codex marketplace fallback failed safely. Check network access and retry.",u)}finally{await o$(l,{recursive:!0,force:!0}).catch(()=>{return})}}async function c$(e,t,n){let r=await e.run(["ls-remote",Hi,"HEAD"],{...n===void 0?{}:{signal:n},timeoutMs:t});if(r.exitCode!==0)throw Y("marketplace_unavailable","The official Codex marketplace remote HEAD could not be resolved. Check network access and retry.",r.stderr);let o=r.stdout.trim().split(/\r?\n/u).map((a)=>a.trim()).filter((a)=>a.length>0),i=o.length===1?/^([0-9a-f]{40}|[0-9a-f]{64})\s+HEAD$/iu.exec(o[0]??""):null;if(i?.[1]===void 0)throw Y("marketplace_invalid","The official Codex marketplace remote HEAD response was malformed.");return i[1].toLowerCase()}async function l$(e,t,n,r){let o=await e.run(["rev-parse","HEAD"],{timeoutMs:n,cwd:t,...r===void 0?{}:{signal:r}}),i=o.stdout.trim().toLowerCase();if(o.exitCode!==0||!/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/u.test(i))throw Y("marketplace_invalid","The downloaded official marketplace checkout did not expose a valid HEAD.",o.stderr);return i}async function u$(e,t){await t_(t,e),await QH(e,{recursive:!0}),await t_(t,e)}async function t_(e,t){let n=ff(e),r=ff(t);while(!0){if((await Bo(r).catch((a)=>{if(Tl(a))return;throw a}))?.isSymbolicLink())throw Y("marketplace_invalid","The official marketplace path cannot contain symlinks.");if(r===n)return;let i=$P(r);if(i===r||i!==n&&!p$(n,i))throw Y("marketplace_invalid","The official marketplace path escaped CODEX_HOME.");r=i}}function p$(e,t){let n=jP(e,t);return n.length>0&&n!==".."&&!n.startsWith(`..${VP}`)&&!i_(n)}async function mf(e){let t=await Bo(e);if(t.isSymbolicLink())throw Y("marketplace_invalid","The official marketplace snapshot cannot contain symlinks.");if(!t.isDirectory())throw Y("marketplace_invalid","The official marketplace snapshot is not a directory.");let n=await n$(e,{withFileTypes:!0});for(let r of n){let o=Vo(e,r.name),i=await Bo(o);if(i.isSymbolicLink())throw Y("marketplace_invalid","The official marketplace snapshot cannot contain symlinks.");if(i.isDirectory())await mf(o)}}async function c_(e,t=[]){return await WP(Vo(e,...a_),e,l_(t))}async function WP(e,t,n=[]){if(t!==void 0)await t_(t,e);let r=await Bo(e).catch((l)=>{if(Tl(l))return;throw Y("marketplace_invalid","The reserved openai-curated marketplace path could not be read safely.",l)});if(r===void 0)return;if(r.isSymbolicLink()||!r.isDirectory())throw Y("marketplace_invalid","The reserved openai-curated marketplace path is not a real directory.");if(t!==void 0)await n_(t,e);else await mf(e);if(t!==void 0)await mf(e);let o=await e_(e),i=[Vo(o,".agents","plugins","marketplace.json"),Vo(o,".codex-plugin","marketplace.json"),Vo(o,"marketplace.json")],a,s;for(let l of i){let u=await Bo(l).catch((p)=>{if(Tl(p))return;throw Y("marketplace_invalid","The official marketplace manifest could not be read safely.",p)});if(u===void 0)continue;if(u.isSymbolicLink()||!u.isFile())throw Y("marketplace_invalid","The official marketplace manifest is not a regular file.");if(await n_(o,l),a!==void 0)throw Y("marketplace_invalid","The reserved official marketplace contains more than one manifest.");a=l;try{s=new TextDecoder("utf-8",{fatal:!0}).decode(await t$(l))}catch(p){throw Y("marketplace_invalid","The official marketplace manifest is not valid UTF-8.",p)}}if(a===void 0||s===void 0)return;let c;try{c=JSON.parse(s)}catch(l){throw Y("marketplace_invalid","The official marketplace manifest is not valid JSON.",l)}return JP(c,o,a,n)}function JP(e,t=`${a_.join("/")}`,n=`${t}/marketplace.json`,r=[]){if(!re(e)||e.name!==vl)throw Y("marketplace_invalid","The reserved official marketplace manifest has an unexpected name.");d$(e);let o=e.plugins;if(!Array.isArray(o)||o.length===0)throw Y("marketplace_invalid","The official marketplace manifest has no plugin entries.");let i=[],a=new Set;for(let s of o){if(!re(s)||typeof s.name!=="string"){if(r.length>0)continue;throw Y("marketplace_invalid","The official marketplace contains a malformed plugin entry.")}let c=s.name;if(!/^[a-z][a-z0-9._-]{1,63}$/u.test(c)){if(r.length>0)continue;throw Y("marketplace_invalid","The official marketplace contains an invalid plugin name.")}if(a.has(c)){if(r.length>0&&!r.includes(c))continue;throw Y("marketplace_invalid","The official marketplace contains a duplicate plugin name.")}if(a.add(c),r.length>0&&!r.includes(c))continue;let l=f$(s);if(!m$(l))throw Y("marketplace_invalid",`The official marketplace source for ${c} is unsafe.`);i.push({name:c,source:l})}if(r.some((s)=>!i.some((c)=>c.name===s)))throw Y("marketplace_invalid","The official marketplace is missing a selected plugin entry.");return{name:vl,source:Hi,rootPath:t,manifestPath:n,plugins:i}}function d$(e){for(let t of["source","repository","repo","url"]){let n=e[t];if(n===void 0)continue;if((typeof n==="string"?n:re(n)&&typeof n.url==="string"?n.url:void 0)!==Hi)throw Y("marketplace_invalid","The reserved official marketplace source is not the approved OpenAI repository.")}}function f$(e){let t=e.source;if(typeof t==="string")return t;if(re(t)&&typeof t.path==="string")return t.path;if(typeof e.path==="string")return e.path;return}function m$(e){if(e===void 0||e.length===0||i_(e))return!1;if(/^[A-Za-z]:[\\/]/u.test(e))return!1;let t=e.replaceAll("\\","/");if(t.startsWith("/")||/^[A-Za-z][A-Za-z0-9+.-]*:/u.test(t))return!1;return t.split("/").every((n)=>n.length===0||n==="."||n!=="..")}function l_(e){let t=[],n=new Set;for(let r of e){let o=r.lastIndexOf("@");if(o<1)continue;let i=r.slice(o+1);if(i!==vl&&i!=="openai-curated-remote")continue;let a=r.slice(0,o);if(!/^[a-z][a-z0-9._-]{1,63}$/u.test(a))throw Y("marketplace_invalid","A selected official marketplace plugin id is invalid.");if(!YP(a))continue;if(!n.has(a))n.add(a),t.push(a)}return t}function hf(e,t){return t.every((n)=>{let r=e.plugins.find((i)=>i.name===n);if(r===void 0)return!1;return r.source.replaceAll("\\","/").replace(/\/+$/u,"").split("/").at(-1)===n})}async function h$(e){let t=jo(e.environment),n;try{n=new uf({executablePath:e.executablePath,environment:t,...e.signal===void 0?{}:{signal:e.signal}});let r=new sf(n,{requestTimeoutMs:Math.min(e.timeoutMs??s_,1e4),...e.signal===void 0?{}:{signal:e.signal}});return await r.initialize(),async()=>{await r.close()}}catch(r){throw await n?.close().catch(()=>{return}),r}}function GP(e,t){if(e!==void 0&&(!Number.isSafeInteger(e)||e<1||e>300000))throw Y("marketplace_invalid","The official marketplace timeout is invalid.");if(t!==void 0&&(!Number.isSafeInteger(t)||t<0||t>60000))throw Y("marketplace_invalid","The official marketplace poll interval is invalid.")}async function n_(e,t){let n=await e_(e),r=await e_(t),o=jP(n,r);if(o===""||o===".."||o.startsWith(`..${VP}`))throw Y("marketplace_invalid","The reserved official marketplace is outside CODEX_HOME.");let i=ff(e),a=ff(t);while(!0){if((await Bo(a)).isSymbolicLink())throw Y("marketplace_invalid","The reserved official marketplace path cannot contain symlinks.");if(a===i)break;let c=$P(a);if(c===a)throw Y("marketplace_invalid","The reserved official marketplace path is outside CODEX_HOME.");a=c}}function Tl(e){return typeof e==="object"&&e!==null&&"code"in e&&e.code==="ENOENT"}function g$(e){return typeof e==="object"&&e!==null&&"code"in e&&(e.code==="EPERM"||e.code==="EACCES")}async function y$(e){await new Promise((t)=>setTimeout(t,e))}function Y(e,t,n){return new Se(e,t,n instanceof Error?{cause:ts(n.message)}:{})}function yr(e,t){let n=Hn(t);if(n===void 0||n!==t)return;let o=[...e.installed,...e.available].flatMap((i)=>{let a=Mx(i.pluginId,i.marketplaceName);return a?.canonicalPluginId===n?[{identity:a,entry:i}]:[]});return o.find((i)=>i.entry.pluginId===n&&i.entry.installed)??o.find((i)=>i.entry.installed)??o.find((i)=>i.entry.pluginId===n)??o[0]}function YP(e){return Ud.includes(e)}function ZP(e){if(!bP(o_,e))return xP(Le("live official plugin list",e));return SP(Pe(o_,e,"live official plugin list"))}function gf(e){let t=e.runner??XP(e.executable,{environment:e.environment??jo(),...e.timeoutMs===void 0?{}:{timeoutMs:e.timeoutMs},...e.stdoutLimit===void 0?{}:{stdoutLimit:e.stdoutLimit},...e.stderrLimit===void 0?{}:{stderrLimit:e.stderrLimit}}),n=async()=>{let r=await t.run(["plugin","list","--json"]);if(r.exitCode!==0)throw df("list",r);let o;try{o=JSON.parse(r.stdout)}catch{throw new Se("command_failed","Codex returned invalid plugin data.")}let i=ZP(o);if(!i.ok)throw new Se("command_failed","Codex returned an invalid official plugin list.");return i.value};return{list:n,ensureOfficialMarketplace:async(r)=>{if(e.codexHome===void 0)throw new Se("marketplace_unavailable","Codex home is unavailable; the official marketplace cannot be bootstrapped safely.");await KP({codexHome:e.codexHome,executablePath:e.executable,selectedPluginIds:r,...e.environment===void 0?{}:{environment:e.environment},...e.timeoutMs===void 0?{}:{timeoutMs:e.timeoutMs},...e.officialMarketplaceFallback===void 0?{}:{gitFallback:e.officialMarketplaceFallback}})},addMarketplace:async(r,o)=>{let i=Pe(wl,r,"plugin marketplace source");if(i===vl||i===Hi)throw new Se("marketplace_invalid","The reserved openai-curated marketplace must be populated by Codex runtime startup; it cannot be added manually.");let a=await t.run(["plugin","marketplace","add",i],o===void 0?void 0:{signal:o});if(a.exitCode!==0&&!/already (?:exists|added)/iu.test(a.stderr))throw df("marketplace add",a,i)},add:async(r,o)=>{let i=Pe(wl,r,"official plugin id"),a=await t.run(["plugin","add",i,"--json"],o===void 0?void 0:{signal:o});if(a.exitCode!==0)throw df("add",a,i);let s=await n(),c=yr(s,i),l=Hn(i),u=[...s.installed,...s.available].filter((f)=>f.pluginId===i&&(l===void 0||f.marketplaceName==null)),p=c?.entry??u.find((f)=>f.installed)??u[0];if(!p)throw new Se("readback_mismatch",`Codex did not report ${i} after installation.`,{plugin_id:i});if(!p.installed)throw new Se("plugin_missing",`Codex reported ${i} as unavailable after installation.`,{plugin_id:i});if(!p.enabled)throw new Se("plugin_disabled",`Codex installed ${i} but it is disabled; enable it in Codex and retry.`,{plugin_id:i})},remove:async(r,o)=>{let i=Pe(wl,r,"official plugin id"),a=i;if(Hn(i)===i){let u=await n(),p=yr(u,i);if(p?.entry.installed)a=p.entry.pluginId}let s=await t.run(["plugin","remove",a,"--json"],o===void 0?void 0:{signal:o});if(s.exitCode!==0&&!/not (?:installed|found)|missing/iu.test(s.stderr))throw df("remove",s,a);let c=await n(),l=[...c.installed,...c.available].find((u)=>u.pluginId===a);if(l?.installed)throw new Se("readback_mismatch",`Codex still reports ${i} after removal.`,{plugin_id:i,observed_plugin_id:l.pluginId})}}}function df(e,t,n){let r=ts(t.stderr).trim().slice(0,512),o=r.length>0?`: ${r}`:"";return new Se("command_failed",`Codex plugin ${e} failed${n===void 0?"":` for ${n}`}${o}`,{exit_code:t.exitCode})}function XP(e,t){let n=t.timeoutMs??30000,r=t.stdoutLimit??131072,o=t.stderrLimit??16384;return{run:(i,a)=>S$(e,i,{...t.environment===void 0?{}:{environment:t.environment},timeoutMs:a?.timeoutMs??n,stdoutLimit:r,stderrLimit:o,...a?.cwd===void 0?{}:{cwd:a.cwd},...a?.signal===void 0?{}:{signal:a.signal}})}}async function S$(e,t,n){if(n.signal?.aborted)throw new Se("cancelled","The Codex plugin command was cancelled.");let r=XH(e,[...t],{env:n.environment===void 0?void 0:{...n.environment},...n.cwd===void 0?{}:{cwd:n.cwd},stdio:["ignore","pipe","pipe"],windowsHide:!0}),o=HP(r.stdout,n.stdoutLimit),i=HP(r.stderr,n.stderrLimit),a=new Promise((p,f)=>{r.once("error",f),r.once("close",(h)=>p(h??-1))}),s,c,l=new Promise((p,f)=>{c=()=>{try{r.kill()}catch{}f(new Se("cancelled","The Codex plugin command was cancelled."))},n.signal?.addEventListener("abort",c,{once:!0})}),u=new Promise((p,f)=>{s=setTimeout(()=>{try{r.kill()}catch{}f(new Se("timeout","The Codex plugin command timed out."))},n.timeoutMs)});try{let[p,f,h]=await Promise.race([Promise.all([o,i,a]),l,u]);return{stdout:p,stderr:f,exitCode:h}}catch(p){try{r.kill()}catch{}if(p instanceof Se)throw p;throw new Se("command_failed","The Codex plugin command failed.")}finally{if(s!==void 0)clearTimeout(s);if(c!==void 0)n.signal?.removeEventListener("abort",c)}}function HP(e,t){if(e===null)return Promise.reject(new Se("command_failed","Codex plugin command output is unavailable."));return new Promise((n,r)=>{let o=[],i=0;e.on("data",(a)=>{let s=typeof a==="string"?new TextEncoder().encode(a):a instanceof Uint8Array?a:void 0;if(s===void 0){r(new Se("command_failed","Codex plugin output was invalid."));return}if(i+=s.byteLength,i>t){r(new Se("output_limit","Codex plugin output exceeded its limit."));return}o.push(s)}),e.once("end",()=>{let a=new Uint8Array(i),s=0;for(let c of o)a.set(c,s),s+=c.byteLength;try{n(new TextDecoder("utf-8",{fatal:!0}).decode(a))}catch(c){r(c)}}),e.once("error",(a)=>r(a))})}var vl="openai-curated",Hi="https://github.com/openai/plugins.git",a_,s_=30000,i$=100,BP,a$,bl,wl,s$,x$,r_,o_,Se;var u_=x(()=>{ut();bt();YS();mr();pf();a_=["plugins","openai-plugins"],BP=k.pipe(le(/^[a-z][a-z0-9._-]{1,63}$/u)),a$=k.pipe(le(/^[0-9]+\.[0-9]+\.[0-9]+(?:[-+][A-Za-z0-9.-]+)?$/u)),bl=q(k),wl=k.pipe(le(/^[A-Za-z0-9][A-Za-z0-9._:@/-]{0,255}$/u)),s$=_({name:BP,version:a$,description:Xr,author:b(cn),license:b(Xr),homepage:b(Xr),repository:b(Xr),keywords:b(bl),skills:b(bl),commands:b(bl),hooks:b(bl),assets:b(bl),official:b(J)});x$=_({id:BP,selected:v(!0)}),r_=_({pluginId:wl,installed:J,enabled:J,name:b(xe(k,lt)),marketplaceName:b(xe(k,lt)),version:b(xe(k,lt))},Ld({key:k,value:vx})),o_=_({installed:q(r_),available:q(r_)});Se=class Se extends Error{code;details;constructor(e,t,n={}){super(t);this.name="OfficialPluginAdapterError",this.code=e,this.details=n}}});var El=x(()=>{mr();mr();Yd();GS();YS();pf();DP();qP();UP();rf();u_();u_()});function Zt(e){if(!ns(e))throw Error("The value is not JSON serializable.");return dr(e),e}function ns(e,t=new Set){if(e===null||typeof e==="string"||typeof e==="boolean")return!0;if(typeof e==="number")return Number.isFinite(e);if(typeof e!=="object"||t.has(e))return!1;t.add(e);try{if(Array.isArray(e))return e.every((n)=>ns(n,t));return Object.getPrototypeOf(e)===Object.prototype&&Object.values(e).every((n)=>ns(n,t))}finally{t.delete(e)}}var Ol=x(()=>{ut()});function mt(e,t){let n=bn(e,t);return Ot(n)?n.right:void 0}function nI(e){return mt(xf,e)!==void 0}var xf,Q4,p_,Sf,_$,os,b$,w$,v$,eI,Rl,_f,rs,d_,yf,T$,QP,E$,f_,is,O$,tI,R$,k$,ln;var as=x(()=>{El();ut();tn();bt();Ol();xf=H((e)=>typeof e==="object"&&e!==null&&!Array.isArray(e)&&ns(e)),Q4=H(ns),p_=k.pipe(le(/^(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)$/u)),Sf=k.pipe(le(/^[0-9a-f]{64}$/u)),_$=k.pipe(le(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u)),os=k.pipe(le(/^[A-Za-z0-9][A-Za-z0-9._:@/-]{0,255}$/u)),b$=k.pipe(Ze((e)=>!Number.isNaN(Date.parse(e)))),w$=_({path:k.pipe(le(/^[A-Za-z0-9][A-Za-z0-9._/-]{0,255}$/u)),digest:Sf}),v$=_({computer_use:J,work:J,frontend:J,security:J,coding:v(!0)}),eI=_({computer_use:b(J),work:b(J),frontend:b(J),security:b(J)}),Rl=_({profile:b(Lo),tier:b(Fi),optional:b(eI),officialPlugins:b(q(os))}),_f=Rl,rs=_({selected:J,status:v("disabled","pending","healthy","missing","provider_disabled","uncertain","unavailable"),plugin_ids:q(os),reason:b(k)}),d_=_({computer_use:rs,work:rs,frontend:rs,security:rs}),yf=_({presence:v("absent","present"),digest:Sf,safe_value:b(xe(_({kind:v("boolean"),value:J}),_({kind:v("marketplace"),source_type:v("git"),source:v("https://github.com/davidbasilefilho/holycodex.git")})))}),T$=_({plugin_id:v("holycodex@holycodex"),before:_({preference:yf,marketplace:yf}),after:_({preference:yf,marketplace:yf})}),QP=_({presence:v("absent","present"),digest:Sf,safe_value:b(_({kind:v("boolean"),value:J}))}),E$=_({plugin_id:os,before:QP,after:QP}),f_={owner:v("holycodex"),schema_epoch:v(Tn),install_id:_$,version:p_,digest:Sf,profile:Lo,tier:Fi,optional_selections:v$,explicit_optional_selections:eI,official_plugins:b(q(os)),capability_state:b(d_),managed_artifacts:q(w$),installed_at:b$,status:b(v("active")),step:b(v("active")),managed_config:b(ef),plugin_snapshot:b(q(_({plugin_id:os,status:v("installed","available","missing","disabled","uncertain","unknown")}))),plugin_config:b(T$),provider_config:b(q(E$)),owned_plugins:b(q(os))},is=_(f_),O$=(({profile:e,...t})=>t)(f_),tI=xe(_({...f_,profile:jd}),_({...O$,plan:jd})),R$=v("preparing","conflicted"),k$=v("validated","plugins_snapshotted","roles_prepared","plugins_installed","config_published","verified","conflicted"),ln=_({...is.fields,status:R$,step:k$})});import{lstat as C$,mkdir as A$}from"fs/promises";import{homedir as P$}from"os";import{dirname as I$,join as $i,posix as rI,resolve as M$,sep as oI,win32 as iI}from"path";function ji(e={},t=process.env){let n=P$(),r=e.paths?.codexHome??t.CODEX_HOME??$i(n,".codex"),o=h_(r,"CODEX_HOME"),i=$i(o,N$);return{codexHome:o,stateRoot:i,activeRecord:$i(i,F$),preparingRecord:$i(i,L$),conflictedRecord:$i(i,D$),roleRoot:$i(i,"agents"),configFile:$i(o,"config.toml")}}function h_(e,t,n=process.platform==="win32"?"win32":"posix"){if(typeof e!=="string"||U$(e))throw new wn("invalid_path",`${t} contains invalid characters.`);let r=n==="win32"?iI:rI,o=m_(e,n);if(typeof o!=="string"||o.length===0||!r.isAbsolute(o))throw new wn("invalid_path",`${t} must be an absolute path.`);let i=r.normalize(o);if(i.split(n==="win32"?"\\":oI).filter((s)=>s.length>0).length===0||i===r.dirname(i))throw new wn("broad_path",`${t} is too broad.`);if(o.split(/[\\/]/u).some((s)=>s===".."))throw new wn("invalid_path",`${t} cannot contain traversal.`);return r.resolve(i)}function U$(e){for(let t of e){let n=t.codePointAt(0)??0;if(n<=31||n===127)return!0}return!1}async function kl(e){h_(e,"owned path"),await xr(e),await A$(e,{recursive:!0}),await xr(e)}async function xr(e){let n=M$(e);while(!0){try{if((await C$(n)).isSymbolicLink())throw new wn("path_symlink","A managed path cannot contain a symlink.")}catch(o){if(o instanceof wn)throw o;if(!ht(o,"ENOENT"))throw o}let r=I$(n);if(r===n)break;n=r}}async function Cl(e){await xr(e)}function ss(e,t,n=process.platform==="win32"?"win32":"posix"){let r=n==="win32"?iI:rI,o=r.resolve(m_(e,n)),i=r.resolve(m_(t,n)),a=r.relative(o,i);return a.length>0&&!a.startsWith(`..${n==="win32"?"\\":oI}`)&&a!==".."&&!r.isAbsolute(a)}function m_(e,t){if(t==="win32"&&/^\/[A-Za-z](?:\/|$)/u.test(e))return`${e[1]?.toUpperCase()??""}:${e.slice(2).replaceAll("/","\\")}`;return e}function ht(e,t){return typeof e==="object"&&e!==null&&"code"in e&&e.code===t}var N$="holycodex",F$="active.json",L$="preparing.json",D$="conflicted.json",q$,wn;var Vi=x(()=>{ut();q$=Tn;wn=class wn extends Error{code;constructor(e,t){super(t);this.name="PathBoundaryError",this.code=e}}});import{lstat as aI,open as H$,readFile as sI,rename as $$,unlink as j$,writeFile as V$}from"fs/promises";import{dirname as B$}from"path";async function cI(e){let t;try{t=await H$(e,"r"),await t.sync()}catch(n){if(!lI(n))throw n}finally{await t?.close().catch(()=>{return})}}async function z$(e){await cI(e).catch((t)=>{if(!lI(t))throw t})}async function Ko(e,t){await Qr(e,`${dr(t)}
36
+ `)}async function Qr(e,t){let n=B$(e);await kl(n),await xr(e);let r=`${e}.tmp-${process.pid}-${crypto.randomUUID()}`;try{await V$(r,t,{encoding:"utf8",mode:384}),await cI(r),await $$(r,e),await z$(n)}catch(o){throw await j$(r).catch(()=>{return}),o}}async function W$(e,t){let n=await aI(e);if(!n.isFile()||n.isSymbolicLink())throw new Bi("state_corrupt","A persisted file is not a regular file.");let r;try{r=JSON.parse(await sI(e,"utf8"))}catch(i){throw new Bi("state_corrupt","A persisted file is not valid JSON.",i)}let o=mt(t,r);if(o===void 0)throw new Bi("state_corrupt","A persisted file failed schema validation.");return o}async function Xt(e){try{let t=await aI(e);if(!t.isFile()||t.isSymbolicLink())throw new Bi("state_corrupt","A persisted file is not a regular file.");return await sI(e,"utf8")}catch(t){if(ht(t,"ENOENT"))return;throw t}}async function Bn(e,t){try{return await W$(e,t)}catch(n){if(ht(n,"ENOENT"))return;throw n}}function lI(e){if(typeof e==="object"&&e!==null&&"code"in e&&typeof e.code==="string")return K$.has(e.code)||process.platform==="win32"&&e.code==="EPERM";return!1}var K$,Bi;var cs=x(()=>{ut();Vi();as();K$=new Set(["EBADF","EINVAL","ENOSYS","ENOTSUP","EISDIR"]);Bi=class Bi extends Error{code;causeValue;constructor(e,t,n){super(t);this.name="StorageError",this.code=e,this.causeValue=n}}});import{readFile as J$}from"fs/promises";import{dirname as G$,resolve as Y$}from"path";import{fileURLToPath as Z$}from"url";async function uI(e=Al){let t=JSON.parse(await J$(e,"utf8")),n=mt(Q$,t);if(n===void 0)throw new Pl("manifest_invalid","The public package manifest is invalid.");return n}async function bf(e=Al){return(await uI(e)).version}async function ls(e=Al){return(await bf(e)).split("-",1)[0]??""}async function g_(e,t,n=Al){let r=await uI(n),o=await ls(n),i=ej(e,o);if(!t)await Ko(n,{...r,version:i});return{previous:o,next:i}}function ej(e,t){if(e!=="patch"&&e!=="minor"){if(mt(p_,e)===void 0)throw new Pl("version_invalid","The version target is invalid.");return e}let n=t.split("."),r=Number(n[1]),o=Number(n[2]);return e==="minor"?`0.${r+1}.0`:`0.${r}.${o+1}`}var X$,Q$,Al,Pl;var Il=x(()=>{bt();as();cs();X$=k.pipe(le(/^(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)(?:-dev\.[1-9]\d*\.[1-9]\d*)?$/u)),Q$=H((e)=>nI(e)&&e.name==="holycodex"&&mt(X$,e.version)!==void 0),Al=Y$(G$(Z$(import.meta.url)),"../package.json");Pl=class Pl extends Error{code;constructor(e,t){super(t);this.name="ManifestError",this.code=e}}});import{lstat as wf,readFile as vf,rm as Tf}from"fs/promises";import{join as un,relative as pI}from"path";function Ki(e,t="standard"){let n=fr(e);if(!n.ok)return[];return n.value.routes.map((r)=>{let o={role:r.role,task:r.task};return{name:jx(o),rolePolicy:jn.find((i)=>i.role===r.role),description:Bx(o),taskInstruction:Vx(o),permissions:Kx(o),model:"gpt-5.6-luna",effort:r.effort,serviceTier:t==="standard"?"default":"fast"}})}function x_(e,t="standard"){let n=fr(e);if(!n.ok)throw Error("Unknown profile.");return{name:"root",description:"Root-directed HolyCodex control agent.",model:n.value.root.model,effort:n.value.root.effort,serviceTier:t==="fast-all"?"fast":"default"}}function S_(e=!1){if(!Do.requiresDelegation||!Do.trivialWorkRequiresDelegation||!Do.codeReviewRequiredForImplementation||!Do.codeReviewRequiredBeforeVcs||!Do.externalVerificationMustBeTerminal)throw Error("The Root orchestration policy is incomplete.");let t=["You are the HolyCodex Root/session orchestrator running gpt-6-astra. Own the user goal, acceptance, material product or architecture choices, lifecycle, integration, external effects, and final completion.","Represent every specialist work unit, including trivial work, with one active bounded Assignment and dispatch it to the native Explorer, Librarian, Worker, or Reviewer route. Small work may use one Assignment. Git/VCS is Root-only; Computer Use is Root-only only when --computer-use was selected. Do the underlying implementation, research, testing, review, and CI observation through specialists.","Use holycodex-agent semantic operations for Intent, optional Plan, and Assignment state. Never edit TOON state or create standalone handoff, Decision, or blocker files.",`Surgical mutation rule: ${Do.surgicalMutationRule}`,"Infer routine safe choices and keep moving. Finish authorized read-only, reversible, preparatory, and independent work before asking. Use request_user_input only for a material unresolved choice, an explicit approval boundary such as plan approval, installation profile approval, remote/origin/server VCS mutation, or public publication/release, or a genuine blocker that can change the outcome, and persist the resulting needs_root_input state.","Dispatch independent non-overlapping Assignments concurrently when useful, keep dependent phases ordered, and serialize writes to one mutable seam. Use writing-for-agents to author compact Luna contracts without repeating effective receiver instructions.","For complex work, make each phase a coherent dependency, decision, or integration boundary. Resolve only choices needed by the current phase, persist its Plan and Assignment evidence, and advance after acceptance; do not ask later-phase questions prematurely.","Use proportional proof and inspect specialist evidence before integration. Worker.validation is an optional independent local proof route when risk or integration complexity warrants it; it does not replace implementation proof or Reviewer.code. Reviewer.code fixed-point review is mandatory after implementation or a major codebase change and before completion or VCS, with no recursive review or testing ceremony.","After integration, Root performs approved VCS actions and dispatches Worker.operations with the exact ref or SHA for terminal CI or release evidence. Pending is never success. Discover the actual topology; repair failures through bounded Assignments and repeat integration, fixed-point review, VCS, and terminal observation until the applicable gate is green."];if(e)t.push("Interactive GUI, browser, and Computer Use execution is Root-only and must not be delegated.");else t.push("Computer Use is not selected for this installation; delegate GUI, browser, and Computer Use execution to an appropriate bounded specialist.");return t.join(`
37
+ `)}async function __(e,t,n=[],r="standard"){let o=un(e,"holycodex","agents"),i=[],a=[],s=Ki(t,r).map((p)=>({path:un(o,`${p.name}.toml`),contents:Rf(p)})),c=new Map(n.map((p)=>[un(e,p.path),p])),l=new Map;for(let p of s){let f=await y_(p.path);l.set(p.path,f);let h=c.get(p.path);if(f!==void 0&&h===void 0&&f!==p.contents)throw Error(`A pre-existing HolyCodex role file is not owned by this installation: ${p.path}`)}let u=[];try{for(let m of s){let w=l.get(m.path),S=c.get(m.path);if(w!==void 0&&S!==void 0){if(await us(w)!==S.digest&&w!==m.contents){i.push(m.path),u.push({path:pI(e,m.path).replaceAll("\\","/"),digest:S.digest});continue}}if(w===void 0||w!==m.contents)await Qr(m.path,m.contents),a.push({path:m.path,previous:w,installedDigest:await us(m.contents)});u.push({path:pI(e,m.path).replaceAll("\\","/"),digest:await us(m.contents)})}let p=un(e,"agents","root.toml"),f=await y_(p),h=await dI(p);if(h==="preserved")i.push(p);if(h==="removed"&&f!==void 0)a.push({path:p,previous:f,installedDigest:void 0});for(let m of n){let w=un(e,m.path);if(!s.some((S)=>S.path===w)){if(!oj(e,w,m.path)){i.push(w);continue}let S=await ij(w,m.digest);if(S.status==="preserved")i.push(w);else if(S.previous!==void 0)a.push({path:w,previous:S.previous,installedDigest:void 0})}}for(let m of n){let w=un(e,m.path);if(i.includes(w)&&!u.some((S)=>un(e,S.path)===w))u.push(m)}return{managed_artifacts:u,preserved:i,rollback:a}}catch(p){throw await Ef(a).catch(()=>{return}),p}}async function Ef(e){let t=[],n=[];for(let r of[...e].reverse()){let o=await y_(r.path);if(!(r.installedDigest===void 0?o===void 0:o!==void 0&&await us(o)===r.installedDigest)){n.push(r.path);continue}if(r.previous===void 0)await Tf(r.path,{force:!1}).catch((a)=>{if(!ht(a,"ENOENT"))throw a}),t.push(r.path);else await Qr(r.path,r.previous)}return{removed:t,preserved:n}}async function Of(e,t){let n=[],r=[],o=un(e,"agents"),i=un(e,"holycodex","agents");for(let c of t){let l=un(e,c.path);if(!ss(e,l)||!ss(o,l)&&!ss(i,l)&&l!==un(e,"config.toml")){r.push(l);continue}try{await xr(l);let u=await wf(l);if(u.isSymbolicLink()||!u.isFile()){r.push(l);continue}let p=await vf(l);if(await us(p)!==c.digest){r.push(l);continue}await Tf(l,{force:!1}),n.push(l)}catch(u){if(!ht(u,"ENOENT"))r.push(l)}}let a=un(e,"agents","root.toml"),s=await dI(a);if(s==="removed")n.push(a);if(s==="preserved")r.push(a);return{removed:n,preserved:r}}function Rf(e){let t=[tj,e.taskInstruction].join(`
38
+ `);return[`name = ${JSON.stringify(e.name)}`,`description = ${JSON.stringify(e.description)}`,`model = ${JSON.stringify(e.model)}`,`model_reasoning_effort = ${JSON.stringify(e.effort)}`,`service_tier = ${JSON.stringify(e.serviceTier)}`,'model_reasoning_summary = "none"','model_verbosity = "low"',`sandbox_mode = ${JSON.stringify(e.permissions.write?"workspace-write":"read-only")}`,'approval_policy = "never"',`web_search = ${JSON.stringify(e.permissions.network?"live":"disabled")}`,`developer_instructions = ${JSON.stringify(t)}`,"","[agents]","enabled = false","interrupt_message = false","","[features]","multi_agent_v2 = false","multi_agent = false","computer_use = false","browser_use = false","in_app_browser = false",""].join(`
39
+ `)}function nj(e,t,n){return['name = "root"','description = "Root-directed HolyCodex control agent."',`model = ${JSON.stringify(e)}`,`model_reasoning_effort = ${JSON.stringify(t)}`,`service_tier = ${JSON.stringify(n)}`,'model_verbosity = "low"',""].join(`
40
+ `)}function ps(e){return rj.has(e)}function oj(e,t,n){if(n==="agents/root.toml")return!0;if(/^holycodex\/agents\/(?:explorer|librarian|worker|reviewer)\.toml$/u.test(n))return!0;return ss(un(e,"agents"),t)&&/^(?:Explorer|Librarian|Worker|Reviewer)\.(?:lookup|trace|research|mechanical|implementation|integration|operations|plan|code|artifact)\.toml$/u.test(n.slice(7))}async function dI(e){try{await xr(e);let t=await wf(e);if(!t.isFile()||t.isSymbolicLink())return"preserved";let n=await vf(e,"utf8");if(!ps(n))return"preserved";return await Tf(e,{force:!1}),"removed"}catch(t){if(ht(t,"ENOENT"))return"absent";throw t}}async function y_(e){try{await xr(e);let t=await wf(e);if(t.isSymbolicLink()||!t.isFile())throw Error(`Invalid managed path: ${e}`);return new TextDecoder("utf-8",{fatal:!0}).decode(await vf(e))}catch(t){if(ht(t,"ENOENT"))return;throw t}}async function ij(e,t){try{await xr(e);let n=await wf(e);if(n.isSymbolicLink()||!n.isFile())return{status:"preserved"};let r=new TextDecoder("utf-8",{fatal:!0}).decode(await vf(e));if(await us(r)===t)return await Tf(e,{force:!1}),{status:"removed",previous:r};return{status:"preserved"}}catch(n){if(ht(n,"ENOENT"))return{status:"removed"};throw n}}async function us(e){let t=typeof e==="string"?new TextEncoder().encode(e):e,n=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(n),(r)=>r.toString(16).padStart(2,"0")).join("")}var tj="You are a HolyCodex GPT-5.6 Luna specialist executing one active bounded Assignment. Follow its exact boundary, exclusions, acceptance criteria, and evidence requirements. Make the smallest complete edit set within that boundary, preserve unrelated work, and perform no redundant writes. Do not delegate, message peers, mutate global Intent lifecycle, make material decisions, or perform Git/VCS. Return exactly one compact outcome (`completed`, `blocked`, `needs_root_input`, or `failed`) with changed paths, checks, observable evidence, blockers, and remaining risk.",rj;var kf=x(()=>{ut();Vi();cs();rj=new Set([{model:"gpt-5.6-terra",effort:"high"},{model:"gpt-5.6-sol",effort:"low"},{model:"gpt-5.6-sol",effort:"medium"},{model:"gpt-5.6-sol",effort:"high"}].flatMap(({model:e,effort:t})=>["default","fast"].map((n)=>nj(e,t,n))))});class zo{adapter;observedIdentities={};constructor(e){if("run"in e){let t=gf({executable:"codex",runner:e});this.adapter=t}else this.adapter=e}static async discover(e=process.env){let t=await XS({environment:e}),n=gf({executable:t.path,environment:ZS(e),...e.CODEX_HOME===void 0?{}:{codexHome:e.CODEX_HOME}});return new zo(n)}async list(){try{return await this.adapter.list()}catch(e){throw Ml("list",e)}}async add(e){try{await this.adapter.add(e)}catch(t){throw Ml("add",t,e)}}async ensureOfficialMarketplace(e){if(this.adapter.ensureOfficialMarketplace===void 0)return;try{await this.adapter.ensureOfficialMarketplace(e)}catch(t){throw Ml("bootstrap",t)}}async remove(e){try{await this.adapter.remove(e)}catch(t){throw Ml("remove",t,e)}}async addMarketplace(e){try{await this.adapter.addMarketplace(e)}catch(t){throw Ml("add",t,e)}}async status(e){let t=await this.list(),n={},r=new Map;for(let i of[...t.installed,...t.available])if(!r.has(i.pluginId)||i.installed)r.set(i.pluginId,i);let o=Object.fromEntries(e.map((i)=>{let a=yr(t,i),s=Hn(i),c=r.get(i),l=a?.entry??(s===void 0||c?.marketplaceName==null?c:void 0),u=a;if(l!==void 0)n[i]=u?.entry.pluginId??l.pluginId;let p=l===void 0?"missing":l.installed&&l.enabled?"installed":l.installed?"disabled":"missing";return[i,p]}));return this.observedIdentities=Object.freeze(n),o}getObservedIdentities(){return this.observedIdentities}}function Ml(e,t,n){if(t instanceof Sr)return t;let o=(t instanceof Se?t:void 0)?.code,i=o==="timeout"||o==="output_limit"||o==="cancelled"||o==="readback_mismatch"||o==="plugin_disabled"||o==="plugin_missing"||o==="marketplace_invalid"||o==="marketplace_timeout"||o==="marketplace_unavailable"?o:o==="command_failed"?e==="list"?"list_failed":e==="remove"?"remove_failed":e==="bootstrap"?"marketplace_unavailable":"add_failed":e==="list"?"list_failed":e==="bootstrap"?"marketplace_unavailable":"add_failed",a=t instanceof Error?t.message:e==="list"?"Codex could not list official plugins.":e==="remove"?`Codex could not remove ${n??"the selected official plugin"}.`:e==="bootstrap"?"Codex could not initialize the official marketplace.":`Codex could not add ${n??"the selected official plugin"}.`;return new Sr(i,a,t,n===void 0?{}:{plugin_id:n})}var Sr;var Nl=x(()=>{El();ut();Sr=class Sr extends Error{code;causeValue;details;constructor(e,t,n,r={}){super(t);this.name="OfficialPluginManagerError",this.code=e,this.causeValue=n,this.details=r}}});function mI(e){let t={},n=[];for(let r of e.split(/\r?\n/u)){let o=sj(r).trim();if(o.length===0)continue;if(o.startsWith("[[")||o.endsWith("]]"))throw Error("Array-of-tables are not supported by the validated fallback.");if(o.startsWith("[")&&o.endsWith("]")){n=b_(o.slice(1,-1).trim()),aj(t,n);continue}let i=xI(o);if(i<1)throw Error("TOML assignment is invalid.");let a=b_(o.slice(0,i).trim()),s=Cf(o.slice(i+1).trim());yI(t,[...n,...a],s)}return t}function hI(e){let t=[];return gI(e,[],t),t.join(`
41
+ `)}function gI(e,t,n){let r=[],o=[];for(let[i,a]of Object.entries(e))if(v_(a))o.push([i,a]);else r.push([i,a]);if(t.length>0){if(n.length>0)n.push("");n.push(`[${t.map(fI).join(".")}]`)}for(let[i,a]of r)n.push(`${fI(i)} = ${SI(a)}`);for(let[i,a]of o)gI(a,[...t,i],n)}function Cf(e){if(e.length===0)throw Error("TOML value is missing.");if(e.startsWith('"')){let t=JSON.parse(e);if(typeof t!=="string")throw Error("TOML string is invalid.");return t}if(e.startsWith("'")){if(!e.endsWith("'")||e.length<2)throw Error("TOML string is invalid.");return e.slice(1,-1)}if(e==="true")return!0;if(e==="false")return!1;if(e.startsWith("[")){if(!e.endsWith("]"))throw Error("TOML array is invalid.");let t=e.slice(1,-1).trim();return t.length===0?[]:w_(t,",").map(Cf)}if(e.startsWith("{")){if(!e.endsWith("}"))throw Error("TOML inline table is invalid.");let t=e.slice(1,-1).trim(),n={};if(t.length===0)return n;for(let r of w_(t,",")){let o=xI(r);if(o<1)throw Error("TOML inline table entry is invalid.");yI(n,b_(r.slice(0,o).trim()),Cf(r.slice(o+1).trim()))}return n}if(/^[+-]?(?:0|[1-9]\d*)(?:\.\d+)?$/u.test(e)){let t=Number(e);if(Number.isFinite(t))return t}throw Error("TOML value is unsupported.")}function b_(e){let t=w_(e,".").map((n)=>n.trim());if(t.length===0||t.some((n)=>!/^(?:[A-Za-z0-9_-]+|"(?:[^"\\]|\\.)*"|'[^']*')$/u.test(n)||n==="__proto__"||n==="constructor"||n==="prototype"))throw Error("TOML key is invalid.");return t.map((n)=>n.startsWith('"')||n.startsWith("'")?Cf(n):n)}function yI(e,t,n){if(t.length===0)throw Error("TOML key is missing.");let r=e;for(let i of t.slice(0,-1)){let a=r[i];if(a===void 0){let s={};r[i]=s,r=s}else if(v_(a))r=a;else throw Error("TOML key conflicts with a scalar.")}let o=t.at(-1);if(Object.prototype.hasOwnProperty.call(r,o))throw Error("TOML key is duplicated.");r[o]=n}function aj(e,t){let n=e;for(let r of t){let o=n[r];if(o===void 0){let i={};n[r]=i,n=i}else if(v_(o))n=o;else throw Error("TOML table conflicts with a scalar.")}}function w_(e,t){let n=[],r=0,o=0,i,a=!1;for(let s=0;s<e.length;s+=1){let c=e[s];if(i!==void 0){if(i==='"'&&a)a=!1;else if(i==='"'&&c==="\\")a=!0;else if(c===i)i=void 0;continue}if(c==='"'||c==="'")i=c;else if(c==="["||c==="{")o+=1;else if(c==="]"||c==="}")o-=1;else if(c===t&&o===0)n.push(e.slice(r,s)),r=s+1}if(i!==void 0||o!==0)throw Error("TOML value is unbalanced.");return n.push(e.slice(r)),n}function xI(e){let t,n=!1,r=0;for(let o=0;o<e.length;o+=1){let i=e[o];if(t!==void 0){if(t==='"'&&n)n=!1;else if(t==='"'&&i==="\\")n=!0;else if(i===t)t=void 0}else if(i==='"'||i==="'")t=i;else if(i==="["||i==="{")r+=1;else if(i==="]"||i==="}")r-=1;else if(i==="="&&r===0)return o}return-1}function sj(e){let t,n=!1;for(let r=0;r<e.length;r+=1){let o=e[r];if(t!==void 0){if(t==='"'&&n)n=!1;else if(t==='"'&&o==="\\")n=!0;else if(o===t)t=void 0}else if(o==='"'||o==="'")t=o;else if(o==="#")return e.slice(0,r)}return e}function v_(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function fI(e){return/^[A-Za-z0-9_-]+$/u.test(e)?e:JSON.stringify(e)}function SI(e){if(typeof e==="string")return JSON.stringify(e);if(typeof e==="boolean"||typeof e==="number"){if(typeof e==="number"&&!Number.isFinite(e))throw Error("TOML number is invalid.");return String(e)}if(Array.isArray(e))return`[${e.map(SI).join(", ")}]`;if(e===null)throw Error("TOML null is not serializable.");throw Error("TOML nested values must be tables.")}import{rm as E_,rmdir as _I}from"fs/promises";async function k_(e={},t=process.env){let n=ji(e,t),r={};try{await Cl(n.codexHome),await Cl(n.stateRoot),r.paths=Fl({state_root:n.stateRoot})}catch(l){r.paths=wt(["path_symlink"],{error:_r(l)})}let[o,i,a]=await Promise.all([ms(n).catch((l)=>{r.configuration=wt(["state_corrupt"],{error:_r(l)});return}),Bn(n.preparingRecord,ln).catch((l)=>{r.transaction=wt(["state_corrupt"],{path:n.preparingRecord,error:_r(l)});return}),Bn(n.conflictedRecord,ln).catch((l)=>{r.transaction=wt(["state_corrupt"],{path:n.conflictedRecord,error:_r(l)});return})]);if(i!==void 0&&r.transaction?.status!=="failed")r.transaction=wt(["incomplete_install_state"]);if(a!==void 0&&r.transaction?.status!=="failed")r.transaction=wt(["conflicted_state"]);if(!r.configuration)if(!o)r.configuration=wt(["configuration_missing"]);else if(await Dl(o))r.configuration=Fl({profile:o.profile,tier:o.tier,install_id:o.install_id});else r.configuration=wt(["configuration_changed"],{path:n.activeRecord});if(o){r.runtime_config=await lj(n,o),r.native_roles=await uj(n,o.profile,o.tier);let l=Object.entries(o.capability_state??{}).find(([,u])=>u.selected&&u.status!=="healthy");if(l)r.capabilities=wt(["selected_capability_not_healthy"],{capability:l[0],status:l[1].status})}try{let l=await Xt(`${n.codexHome}/agents/root.toml`);if(l!==void 0&&ps(l)){let u=r.native_roles;r.native_roles={status:"failed",reasons:[...u?.reasons??[],"stale_legacy_root"],details:{...u?.details,path:`${n.codexHome}/agents/root.toml`}}}}catch(l){r.native_roles=wt(["native_role_invalid"],{error:_r(l)})}let s=e.officialPluginManager??await zo.discover({...t,CODEX_HOME:n.codexHome}).catch(()=>{return});if(o&&s?.status){let l=[...new Set([br,...Qc({computer_use:o.optional_selections.computer_use,work:o.optional_selections.work,frontend:o.optional_selections.frontend,security:o.optional_selections.security},o.official_plugins),...o.owned_plugins??[]])];try{let u=await s.status(l),p=Object.entries(u).filter(([,h])=>h!=="installed").map(([h])=>h),f=s.getObservedIdentities?.()??{};r.native_plugins=p.length===0?Fl({status:u,observed_identities:f}):wt(["native_plugin_disagreement"],{missing:p,status:u,observed_identities:f})}catch(u){r.native_plugins=wt(["native_plugin_status_failed"],{error:_r(u)})}}else r.native_plugins={status:"unsupported",reasons:["native_plugin_manager_unavailable"],details:{}};let c=Object.values(r).flatMap((l)=>l.reasons);return{healthy:Object.values(r).every((l)=>l.status!=="failed"),checks:r,reasons:[...new Set(c)]}}async function Ll(e={},t=process.env){let n=ji(e,t);await Cl(n.codexHome),await Cl(n.stateRoot);let r=await ms(n),[o,i]=await Promise.all([Bn(n.preparingRecord,ln),Bn(n.conflictedRecord,ln)]),a=i??o??r;T_(e,{stage:"removal",status:"started",message:"Removing HolyCodex-owned state"});let s=new Set(pj(a)),c=[],l=[],u=[];if(r&&!await Dl(r))return l.push(n.activeRecord),u.push("configuration_changed"),{removed:c,preserved:l,reasons:u};if(a===void 0)return T_(e,{stage:"removal",status:"completed",message:"Nothing to remove"}),{removed:c,preserved:l,reasons:u};let p=await Xt(n.configFile),f=eo(p),h=a?.managed_config;if(h){let y=await Ui(f,h,{schema:h.schema,installId:h.installId});if(y.preservedKeys.length>0||y.unresolvedKeys.length>0)return l.push(n.configFile),u.push("managed_config_changed"),await Kn(n,a??ds()),{removed:c,preserved:l,reasons:u}}if(a?.plugin_config){if((await O_(f,a.plugin_config)).preserved.length>0)return l.push(n.configFile),u.push("plugin_config_changed"),await Kn(n,a),{removed:c,preserved:l,reasons:u}}if(a?.provider_config){if((await R_(f,a.provider_config,s)).preserved.length>0)return l.push(n.configFile),u.push("provider_config_changed"),await Kn(n,a),{removed:c,preserved:l,reasons:u}}let m;try{m=e.officialPluginManager??await zo.discover({...t,CODEX_HOME:n.codexHome})}catch(y){throw new N("capability_denied","Native Codex plugin removal is unavailable.",y,{recovery:"Install or expose Codex, then retry."})}if(m===void 0||!m.remove||!m.list)throw new N("capability_denied","Native Codex plugin removal and readback are unavailable.");let w=await Of(n.codexHome,a?.managed_artifacts??[]);if(c.push(...w.removed),l.push(...w.preserved),w.preserved.length>0)u.push("managed_artifact_changed");for(let y of s)try{let R=await m.list(),P=dj(R,y);if(P?.entry.installed!==!0)continue;let z=P.entry.pluginId;await m.remove(z);let X=await m.list();if(yr(X,y)?.entry?.installed===!0||[...X.installed,...X.available].some((L)=>L.pluginId===y&&L.installed))throw new N("capability_denied",`Codex still reports ${y} after removal.`);c.push(y)}catch(R){throw u.push("native_plugin_remove_failed"),await Kn(n,a??ds()),new N("capability_denied",`Codex native plugin removal did not converge for ${y}: ${_r(R)}`,R)}if(w.preserved.length>0)return await Kn(n,a??ds()),{removed:c,preserved:l,reasons:u};let S;try{let y=f,R=h;if(R){let P=await Ui(y,R,{schema:R.schema,installId:R.installId});if(P.preservedKeys.length>0||P.unresolvedKeys.length>0)return l.push(n.configFile),u.push("managed_config_changed"),await Kn(n,a??ds()),{removed:c,preserved:l,reasons:u};y=P.document,R=P.state}if(a?.plugin_config){let P=await O_(y,a.plugin_config,{allowBeforeState:!0});if(P.preserved.length>0)return l.push(n.configFile),u.push("plugin_config_changed"),await Kn(n,a),{removed:c,preserved:l,reasons:u};y=P.document}if(a?.provider_config){let P=await R_(y,a.provider_config,s,{allowBeforeState:!0});if(P.preserved.length>0)return l.push(n.configFile),u.push("provider_config_changed"),await Kn(n,a),{removed:c,preserved:l,reasons:u};y=P.document}if(a?.managed_config||a?.plugin_config||a?.provider_config)S=R===void 0?{document:y}:{document:y,state:R};if(S!==void 0)if(Object.keys(S.document).length===0&&p===void 0)await E_(n.configFile,{force:!1});else await Qr(n.configFile,A_(S.document))}catch(y){if(y instanceof N)throw await Kn(n,a??ds()),y;return l.push(n.configFile),u.push("managed_config_write_failed"),await Kn(n,a??ds()),{removed:c,preserved:l,reasons:u}}if(r)try{await E_(n.activeRecord,{force:!1}),c.push(n.activeRecord)}catch(y){if(!ht(y,"ENOENT"))return l.push(n.activeRecord),u.push("state_remove_failed"),await Kn(n,a??r),{removed:c,preserved:l,reasons:u}}if(l.length===0)for(let[y,R]of[[n.preparingRecord,o!==void 0],[n.conflictedRecord,i!==void 0]]){if(!R)continue;try{await fj(y),c.push(y)}catch{l.push(y),u.push("state_remove_failed")}}if(l.length===0)try{await _I(n.roleRoot),c.push(n.roleRoot)}catch(y){if(!ht(y,"ENOENT"))l.push(n.roleRoot),u.push("role_directory_not_empty")}if(l.length===0)try{await _I(n.stateRoot),c.push(n.stateRoot)}catch(y){if(ht(y,"ENOENT"))c.push(n.stateRoot);else l.push(n.stateRoot),u.push("state_directory_not_empty")}return T_(e,{stage:"removal",status:"completed",message:"HolyCodex removal complete"}),{removed:c,preserved:l,reasons:u}}async function C_(e={},t=process.env,n={}){let r=ji(e,t),[o,i,a]=await Promise.all([ms(r),Bn(r.preparingRecord,ln),Bn(r.conflictedRecord,ln)]),s=a??i??o;if(s===void 0)throw new N("not_installed","HolyCodex is not installed in the selected Codex home.",void 0,{recovery:"Run `holycodex install --yes` first."});if(o!==void 0&&!await Dl(o))throw new N("state_corrupt","The existing HolyCodex configuration has changed and cannot be upgraded safely.",void 0,{path:r.activeRecord});let c;try{c=await ls()}catch(f){throw new N("upgrade_failed","The running HolyCodex version is unavailable.",f)}let l=cj(c,s.version);if(l<0)throw new N("upgrade_downgrade",`The running HolyCodex version ${c} is older than the installed version ${s.version}.`,void 0,{installed_version:s.version,running_version:c});let u=s.managed_config?.managed["features.context_management.experimental_mode"]!==void 0,p=[...l>0?["version"]:[],...u?["context-management configuration migration"]:[],...l>0||u?["Root/session configuration","Luna role definitions"]:[],...a??i?["interrupted transaction recovery"]:[]];if(p.length===0)return{status:n.dryRun===!0?"dry_run":"current",from_version:s.version,to_version:c,changes:[],record:o,preserved:[],warnings:[]};if(n.dryRun===!0)return{status:"dry_run",from_version:s.version,to_version:c,changes:p,record:o,preserved:[],warnings:[]};try{let f=await fs({profile:s.profile,tier:s.tier,optional:s.explicit_optional_selections,officialPlugins:s.official_plugins},e,t);return{status:"upgraded",from_version:s.version,to_version:c,changes:p,record:f.record,preserved:f.preserved,warnings:f.warnings}}catch(f){if(f instanceof N)throw f;throw new N("upgrade_failed",`HolyCodex upgrade failed: ${_r(f)}`,f)}}function cj(e,t){let n=e.split(".").map(Number),r=t.split(".").map(Number);for(let o=0;o<3;o+=1){if((n[o]??0)<(r[o]??0))return-1;if((n[o]??0)>(r[o]??0))return 1}return 0}async function lj(e,t){if(!t.managed_config)return wt(["incomplete_install_state"]);try{let n=eo(await Xt(e.configFile)),r=Pf(t.profile,t.tier,t.optional_selections.computer_use),o=[];for(let[i,a]of Object.entries(r))if((await es(n,t.managed_config,i)).status!=="unchanged"||i!=="developer_instructions"&&Te(n,i)!==a)o.push(i);return o.length===0?Fl({managed_keys:Object.keys(r).length}):wt(["changed_holycodex_config"],{keys:o})}catch(n){return wt(["config_unreadable"],{error:_r(n)})}}async function uj(e,t,n){try{let r=eo(await Xt(e.configFile)),o=[];for(let a of Ki(t,n)){let s=Te(r,`agents."${a.name}".config_file`),c=`${e.roleRoot}/${a.name}.toml`.replaceAll("\\","/");if(typeof s!=="string"||hl(e.configFile,s).replaceAll("\\","/")!==c){o.push(`${a.name}:registration`);continue}let l=await Xt(`${e.roleRoot}/${a.name}.toml`);if(l===void 0){o.push(`${a.name}:missing`);continue}if(l!==Rf(a)){o.push(`${a.name}:changed`);continue}let u=eo(l);if(u.name!==a.name||typeof u.description!=="string"||typeof u.developer_instructions!=="string"||u.model!=="gpt-5.6-luna"||u.model_reasoning_summary!=="none"||u.model_verbosity!=="low"||u.tool_output_token_limit!==void 0||u.service_tier!==(n==="standard"?"default":"fast")||u.sandbox_mode!==(a.permissions.write?"workspace-write":"read-only")||u.approval_policy!=="never"||u.web_search!==(a.permissions.network?"live":"disabled")||Te(u,"agents.enabled")!==!1||Te(u,"features.multi_agent_v2")!==!1||Te(u,"features.multi_agent")!==!1||Te(u,"features.computer_use")!==!1||Te(u,"features.browser_use")!==!1||Te(u,"features.in_app_browser")!==!1)o.push(`${a.name}:malformed`)}let i=await Xt(`${e.codexHome}/agents/root.toml`);if(i!==void 0&&ps(i))o.push("root:stale");return o.length===0?Fl({role_root:e.roleRoot,agent_types:Ki(t,n).map((a)=>a.name)}):wt(["native_role_disagreement"],{roles:o})}catch(r){return wt(["native_role_invalid"],{error:_r(r)})}}async function Kn(e,t){let n={...t,status:"conflicted",step:"conflicted",managed_config:t.managed_config??{owner:"holycodex",schema:t.schema_epoch,installId:t.install_id,managed:{}},plugin_snapshot:t.plugin_snapshot??[],owned_plugins:t.owned_plugins??[]};if(mt(ln,n)!==void 0)await Ko(e.conflictedRecord,Zt(n))}function ds(){return{owner:"holycodex",schema_epoch:"state-0.16",install_id:"remove-conflict",version:"0.0.0",digest:"0".repeat(64),profile:"default",tier:"standard",optional_selections:{computer_use:!1,work:!1,frontend:!1,security:!1,coding:!0},explicit_optional_selections:{},managed_artifacts:[],installed_at:new Date(0).toISOString()}}function pj(e){if(e?.owned_plugins!==void 0)return[...new Set(e.owned_plugins)];let t=(e?.plugin_snapshot??[]).filter((o)=>o.status==="missing"||o.status==="available").map((o)=>o.plugin_id),n=e?.plugin_config?.before.preference.presence==="absent"&&e.plugin_config.after.preference.presence==="present"?[br]:[],r=(e?.provider_config??[]).filter((o)=>o.before.presence==="absent"&&o.after.presence==="present").map((o)=>o.plugin_id);return[...new Set([...t,...n,...r])]}function dj(e,t){let n=yr(e,t);if(n!==void 0)return n;let r=[...e.installed,...e.available].find((o)=>o.pluginId===t);return r===void 0?void 0:{entry:r}}function Fl(e){return{status:"healthy",reasons:[],details:e}}function wt(e,t={}){return{status:"failed",reasons:e,details:t}}async function fj(e){await E_(e,{force:!1}).catch((t)=>{if(!ht(t,"ENOENT"))throw t})}function _r(e){return e instanceof Error?e.message.slice(0,256):"operation failed"}function T_(e,t){try{e.onProgress?.(t)}catch{}}var Af=x(()=>{El();ut();ql();Ol();Il();kf();Nl();Vi();as();cs()});import{rm as AI}from"fs/promises";import{join as mj}from"path";function wr(e){let t=mt(_f,e);if(t===void 0)throw new N("install_failed","The installation options are invalid.");return t}async function fs(e={},t={},n=process.env){if(mt(Rl,e)===void 0)throw new N("install_failed","The installation options are invalid.");let r=ji(t,n);zn(t,{stage:"validation",status:"started",message:"Validating Codex target"}),await kl(r.stateRoot);let o=await Bn(r.preparingRecord,ln),a=await Bn(r.conflictedRecord,ln)??o;if(a!==void 0){await Promise.resolve().then(() => Af());let qe=await Ll(t,n);if(qe.preserved.length>0||qe.reasons.length>0)throw new N("state_corrupt","The interrupted HolyCodex installation could not be reconciled safely.",void 0,{preserved:qe.preserved.join(","),reasons:qe.reasons.join(",")});return await fs({profile:e.profile??a.profile,tier:e.tier??a.tier,optional:{computer_use:e.optional?.computer_use??a.optional_selections.computer_use,work:e.optional?.work??a.optional_selections.work,frontend:e.optional?.frontend??a.optional_selections.frontend,security:e.optional?.security??a.optional_selections.security},officialPlugins:e.officialPlugins??OI(a)},t,n)}let s=await ms(r);if(s!==void 0&&!await Dl(s))throw new N("state_corrupt","The existing HolyCodex configuration has changed and cannot be replaced.",void 0,{path:r.activeRecord});let c=kj(e.profile,s?.profile),l=Cj(e.tier,s?.tier),u=Aj(e.optional,s?.optional_selections),p=Ej(s?.explicit_optional_selections,e.optional),f=e.officialPlugins??OI(s),h=[...new Set(Qc(MI(u),f).map((ae)=>Hn(ae)??ae))],m;try{m=t.officialPluginManager??await zo.discover({...n,CODEX_HOME:r.codexHome})}catch(ae){throw new N("capability_denied","Native Codex plugin installation is unavailable.",ae,{recovery:"Install or expose Codex, then retry."})}if(!m.addMarketplace||!m.add||!m.list)throw new N("install_failed","Native Codex plugin installation and verification are unavailable.");let w;try{w=await m.list()}catch(ae){throw new N("capability_denied","Native Codex plugin state could not be read safely.",ae)}let S=h.filter((ae)=>{if(Hn(ae)!==ae)return!1;let qe=$l(w,ae);return!(qe?.installed&&qe.enabled)});if(m.ensureOfficialMarketplace!==void 0&&S.length>0)try{await m.ensureOfficialMarketplace(S)}catch(ae){throw new N("capability_denied",`The selected official Codex provider marketplace is unavailable: ${CI(ae)}`,ae,{recovery:"Check Codex network and marketplace policy, then retry."})}zn(t,{stage:"validation",status:"completed",message:"Codex target validated"});let y=s?.install_id??crypto.randomUUID().replaceAll("-",""),R=await ls(),P=(t.now?.()??new Date).toISOString(),z=await Xt(r.configFile),X=eo(z),U=s?.plugin_config?.before??await wI(X),te=[...new Set([...h,...(s?.provider_config??[]).map((ae)=>ae.plugin_id),...s?.owned_plugins??[]])].filter((ae)=>ae!==br),se=(await vI(X,te)).map((ae)=>{let qe=s?.provider_config?.find((Gn)=>Gn.plugin_id===ae.plugin_id);return qe===void 0?ae:{plugin_id:ae.plugin_id,before:qe.before,after:qe.before}}),ce=s?.managed_config??tf({schema:Tn,installId:y}),ee=await TI(X,ce,s),Ae=await EI(ee.document,ee.state),{document:vt,state:Ft}=Ae;_j(vt,Ft);let Lt=Pf(c,l,u.computer_use),De;try{De=await gl(vt,Ft,Lt,{schema:Tn,installId:y})}catch(ae){if(ae instanceof N)throw ae;throw new N("state_corrupt","The existing Codex configuration has an incompatible shape for HolyCodex settings.",ae,{recovery:"Converge the conflicting Codex setting, then retry."})}if(De.driftedKeys.length>0)throw new N("state_corrupt","HolyCodex-owned Codex settings changed and cannot be replaced safely.",void 0,{keys:De.driftedKeys.join(",")});let je;try{je=await bj({list:()=>m.list()},[...new Set([br,...h,...s?.owned_plugins??[]])])}catch(ae){throw new N("capability_denied","Native Codex plugin state could not be read safely.",ae)}let Tt={owner:"holycodex",schema_epoch:Tn,install_id:y,version:R,digest:s?.digest??"0".repeat(64),profile:c,tier:l,optional_selections:u,explicit_optional_selections:p,official_plugins:h,capability_state:kI(u),managed_artifacts:s?.managed_artifacts??[],installed_at:P,status:"preparing",step:"validated",managed_config:De.state,plugin_snapshot:je,plugin_config:{plugin_id:br,before:U,after:U},provider_config:se,owned_plugins:[...new Set(s?.owned_plugins??[])]};await Ul(r.preparingRecord,Tt);let Et,Gi=!1,to=new Set,Yi=new Set(s?.owned_plugins??[]),Df=new Set,Dt=Tt,q_=!1,U_=!1,qf=z,gs=De.state;try{zn(t,{stage:"roles",status:"started",message:"Installing subagent roles"}),await kl(r.roleRoot),Et=await __(r.codexHome,c,s?.managed_artifacts,l),Dt={...Tt,step:"roles_prepared",managed_artifacts:Et.managed_artifacts},await Ul(r.preparingRecord,Dt),zn(t,{stage:"roles",status:"completed",message:"Subagent roles installed"}),zn(t,{stage:"plugins",status:"started",message:"Installing selected capabilities"}),q_=!0,await m.addMarketplace(hj),await Rj({list:()=>m.list(),add:(vn)=>m.add(vn)},[br,...h],(vn,jf)=>{if(jf==="new")to.add(vn),Yi.add(vn),Dt={...Dt,owned_plugins:[...Yi]};else Df.add(vn),Yi.add(vn),Dt={...Dt,owned_plugins:[...Yi]}}),Dt={...Dt,step:"plugins_installed"},await Ul(r.preparingRecord,Dt),zn(t,{stage:"plugins",status:"completed",message:"Selected capabilities installed"});let qe=await Xt(r.configFile);qf=qe;let Gn=eo(qe),H_=await TI(Gn,ce,s),$_=await EI(H_.document,H_.state),{document:Bl,state:j_}=$_,Uf=await wI(Bl),Hf=(await vI(Bl,te)).map((vn)=>({plugin_id:vn.plugin_id,before:se.find((jf)=>jf.plugin_id===vn.plugin_id)?.before??vn.before,after:vn.before}));await Sj(Bl,vt,j_,Lt);let Kl=await gl(Bl,j_,Lt,{schema:Tn,installId:y});if(Kl.driftedKeys.length>0)throw new N("state_corrupt","HolyCodex-owned Codex settings changed during native plugin setup.",void 0,{keys:Kl.driftedKeys.join(",")});U_=!0,zn(t,{stage:"config",status:"started",message:"Configuring Root"}),gs=Kl.state,Dt={...Dt,managed_config:gs,plugin_config:{plugin_id:br,before:U,after:Uf},provider_config:Hf},await Qr(r.configFile,A_(Kl.document)),Gi=!0,Dt={...Dt,step:"config_published"},await Ul(r.preparingRecord,Dt),zn(t,{stage:"config",status:"completed",message:"Root configuration published"}),zn(t,{stage:"verification",status:"started",message:"Verifying installation"}),await vj(r,c,l,u.computer_use,gs,Et.preserved),zn(t,{stage:"verification",status:"completed",message:"Installation verified"});let V_=kI(u),ZI=await If({owner:"holycodex",install_id:y,version:R,profile:c,tier:l,optional_selections:u,explicit_optional_selections:p,official_plugins:h,capability_state:V_,managed_artifacts:Et.managed_artifacts,managed_config:gs,plugin_config:{plugin_id:br,before:U,after:Uf},provider_config:Hf,plugin_snapshot:je,owned_plugins:[...Yi]}),$f={owner:"holycodex",schema_epoch:Tn,install_id:y,version:R,digest:ZI,profile:c,tier:l,optional_selections:u,explicit_optional_selections:p,official_plugins:h,capability_state:V_,managed_artifacts:Et.managed_artifacts,installed_at:P,status:"active",step:"active",managed_config:gs,plugin_snapshot:je,plugin_config:{plugin_id:br,before:U,after:Uf},provider_config:Hf,owned_plugins:[...Yi]};if(mt(is,$f)===void 0)throw new N("state_corrupt","The HolyCodex configuration is invalid.");return await Ko(r.activeRecord,Zt($f)),await P_(r.preparingRecord),await P_(r.conflictedRecord),zn(t,{stage:"complete",status:"completed",message:"HolyCodex installation complete"}),{record:$f,optional_plugins:h,preserved:Et.preserved,warnings:Et.preserved.length===0?[]:["modified managed files were preserved"]}}catch(ae){let qe=[];if(Gi)try{await wj(r.configFile,qf)}catch{qe.push("config")}if(q_&&!U_){if(await Xt(r.configFile).catch(()=>{return})!==qf)qe.push("config")}if(Et!==void 0)try{if((await Ef(Et.rollback)).preserved.length>0)qe.push("roles")}catch{qe.push("roles")}if(Df.size>0)qe.push(...[...Df].map((Gn)=>`plugin:${Gn}`));for(let Gn of to)try{await m.remove?.(Gn)}catch{qe.push(`plugin:${Gn}`)}if(qe.length>0)await Ul(r.conflictedRecord,{...Dt,step:"conflicted",status:"conflicted"}).catch(()=>{return});else await P_(r.preparingRecord).catch(()=>{return});if(ae instanceof wn)throw ae;if(ae instanceof N)throw ae;throw new N(ae instanceof Sr||ae instanceof Hl?"capability_denied":"install_failed",CI(ae),ae,qe.length>0?{recovery:"Resolve conflicted state before retrying."}:{})}}async function ms(e){let t=await Bn(e.activeRecord,xf);if(t===void 0)return;let n=mt(is,t);if(n!==void 0)return n;let r=mt(tI,t);if(r===void 0)throw new N("state_corrupt","The HolyCodex configuration is invalid.");if(!await LI(r))throw new N("state_corrupt","The existing HolyCodex configuration has an invalid digest.",void 0,{path:e.activeRecord});let o="profile"in r&&r.profile!==void 0?r.profile:("plan"in r)?r.plan:void 0;if(o===void 0)throw new N("state_corrupt","The persisted installation has neither profile nor legacy plan state.",void 0,{path:e.activeRecord});let i;try{i=qx(o)}catch(c){throw new N("state_corrupt",`The persisted profile ${o} was removed and requires an explicit replacement.`,c,{path:e.activeRecord,profile:o})}let s={..."plan"in r?Object.fromEntries(Object.entries(r).filter(([c])=>c!=="plan")):r,profile:i,digest:await If({owner:r.owner,install_id:r.install_id,version:r.version,profile:i,tier:r.tier,optional_selections:r.optional_selections,explicit_optional_selections:r.explicit_optional_selections,official_plugins:r.official_plugins??[],capability_state:r.capability_state??null,managed_artifacts:r.managed_artifacts,...r.managed_config===void 0?{}:{managed_config:r.managed_config},...r.plugin_config===void 0?{}:{plugin_config:r.plugin_config},...r.provider_config===void 0?{}:{provider_config:r.provider_config},...r.plugin_snapshot===void 0?{}:{plugin_snapshot:r.plugin_snapshot},...r.owned_plugins===void 0?{}:{owned_plugins:r.owned_plugins}})};return await Ko(e.activeRecord,Zt(s)),s}function MI(e){return{computer_use:e.computer_use,work:e.work,frontend:e.frontend,security:e.security}}function eo(e){if(e===void 0||e.trim().length===0)return{};try{let t=globalThis.Bun,n=t?.TOML?.parse?t.TOML.parse(e):mI(e),r=mt(pl,n);if(r===void 0)throw Error("TOML document contains unsupported values.");return r}catch(t){throw new N("state_corrupt","The Codex config.toml is not valid TOML.",t)}}function A_(e){try{let t=globalThis.Bun;return`${((t?.TOML?.stringify)?t.TOML.stringify(e):hI(e)).trimEnd()}
42
+ `}catch(t){throw new N("install_failed","The merged Codex configuration is not writable.",t)}}async function wI(e){return{preference:await jl(e,"plugins",PI),marketplace:await jl(e,"marketplaces",II)}}async function vI(e,t){return await Promise.all(t.map(async(n)=>{let r=await jl(e,"plugins",n),o={presence:r.presence,digest:r.digest,...r.safe_value?.kind==="boolean"?{safe_value:r.safe_value}:{}};return{plugin_id:n,before:o,after:o}}))}async function O_(e,t,n={}){let r=e,o=[],i=[],a=[];for(let[s,c,l]of[["preference","plugins",PI],["marketplace","marketplaces",II]]){let u=t.before[s],p=t.after[s],f=await jl(e,c,l);if(n.allowBeforeState===!0&&f.digest===u.digest)continue;if(f.digest!==p.digest){a.push(s);continue}if(u.presence==="absent"){if(f.presence==="present")r=FI(r,c,l),i.push(s);continue}if(u.safe_value===void 0){a.push(s);continue}r=NI(r,c,l,xj(u.safe_value)),o.push(s)}return{document:r,restored:o,removed:i,preserved:a}}async function R_(e,t,n,r={}){let o=e,i=[],a=[],s=[];for(let c of t){if(!n.has(c.plugin_id))continue;let{before:l,after:u}=c,p=await jl(e,"plugins",c.plugin_id);if(r.allowBeforeState===!0&&p.digest===l.digest)continue;if(p.digest!==u.digest){s.push(c.plugin_id);continue}if(l.presence==="absent"){if(p.presence==="present")o=FI(o,"plugins",c.plugin_id),a.push(c.plugin_id);continue}if(l.safe_value===void 0){s.push(c.plugin_id);continue}o=NI(o,"plugins",c.plugin_id,{enabled:l.safe_value.value}),i.push(c.plugin_id)}return{document:o,restored:i,removed:a,preserved:s}}async function jl(e,t,n){let r=gj(e,t,n),o=await Zr("holycodex-plugin-config",[Yr(Zt({key:`${t}.${n}`,value:r===void 0?{presence:"absent"}:r}))]),i=yj(t,r);return{presence:r===void 0?"absent":"present",digest:o,...i===void 0?{}:{safe_value:i}}}function gj(e,t,n){let r=e[t];if(!hs(r))return;return r[n]}function yj(e,t){if(!hs(t))return;let n=Object.keys(t);if(e==="plugins"){if(n.length!==1||n[0]!=="enabled"||typeof t.enabled!=="boolean")return;return{kind:"boolean",value:t.enabled}}if(n.length!==2||!n.includes("source_type")||!n.includes("source")||t.source_type!=="git"||t.source!==bI)return;return{kind:"marketplace",source_type:"git",source:bI}}function xj(e){if(e.kind==="boolean")return{enabled:e.value};return{source_type:e.source_type,source:e.source}}function NI(e,t,n,r){let o={...e},i=o[t];if(i!==void 0&&!hs(i))throw new N("state_corrupt",`The ${t} Codex config table is invalid.`);return o[t]={...i,[n]:r},o}function FI(e,t,n){let r=e[t];if(!hs(r)||!Object.prototype.hasOwnProperty.call(r,n))return e;let o={...e},i={...r};if(delete i[n],Object.keys(i).length===0)delete o[t];else o[t]=i;return o}function hs(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function Pf(e,t,n=!1){let r=x_(e,t),o={model:r.model,model_reasoning_effort:r.effort,service_tier:r.serviceTier,model_verbosity:"low",developer_instructions:S_(n),suppress_unstable_features_warning:!0,"features.default_mode_request_user_input":!0,"features.multi_agent_v2":!0,"features.context_management":!0};for(let i of Za)o[`agents."${i}".config_file`]=`holycodex/agents/${i}.toml`;return o}async function Sj(e,t,n,r){let o=[];for(let i of Object.keys(r)){let a=i;if(n.managed[a]!==void 0){if((await es(e,n,a)).status==="drifted")o.push(a);continue}let c=Te(t,a),l=Te(e,a);if(c!==l)o.push(a)}if(o.length>0)throw new N("state_corrupt","Codex settings changed during native plugin setup.",void 0,{keys:o.join(",")})}async function TI(e,t,n){let r=["agents.explorer.config_file","agents.librarian.config_file","agents.worker.config_file","agents.reviewer.config_file"],o=Object.fromEntries(r.flatMap((c)=>{let l=t.managed[c];return l===void 0?[]:[[c,l]]})),i=e,a=t;if(Object.keys(o).length>0){let c=await Ui(e,{...t,managed:o},{schema:t.schema,installId:t.installId});if(c.preservedKeys.length>0||c.unresolvedKeys.length>0)throw new N("state_corrupt","Legacy HolyCodex agent registrations changed and cannot be migrated safely.",void 0,{keys:[...new Set([...c.preservedKeys,...c.unresolvedKeys])].join(",")});i=c.document,a={...t,managed:Object.fromEntries(Object.entries(t.managed).filter(([l])=>!r.includes(l)))}}if(!n)return{document:i,state:a};let s=n.managed_artifacts.map((c)=>c.path);for(let c of["explorer","librarian","worker","reviewer"]){if(!s.some((h)=>h.startsWith(`agents/${c[0]?.toUpperCase()}${c.slice(1)}.`)||h===`holycodex/agents/${c}.toml`))continue;let u=`agents.${c}.config_file`,p=Te(i,u);if(typeof p!=="string")continue;let f=p.replaceAll("\\","/").replace(/^\.\//u,"");if(f===`agents/${c}.toml`||f===`holycodex/agents/${c}.toml`)i=fl(i,u)}return{document:i,state:a}}async function EI(e,t){let o=t.managed["features.context_management.experimental_mode"];if(o===void 0)return{document:e,state:t};let i=Te(e,"features.context_management.experimental_mode"),a=Te(e,"features.context_management"),s=hs(a)?void 0:a;if(hs(a)&&Object.keys(a).some((p)=>p!=="experimental_mode"))throw new N("state_corrupt","The legacy context-management table contains unrelated settings and cannot be migrated without changing user configuration.",void 0,{key:"features.context_management",recovery:"Move unrelated settings, then retry the upgrade."});if(i!==void 0){let p=await gr("features.context_management.experimental_mode",i);if(JSON.stringify(p)!==JSON.stringify(o.lastManagedValue))throw new N("state_corrupt","The legacy context-management setting changed and cannot be migrated safely.",void 0,{key:"features.context_management.experimental_mode"});if(s!==void 0&&JSON.stringify(s)!==JSON.stringify(i))throw new N("state_corrupt","Both legacy and canonical context-management settings are present with different values.",void 0,{keys:"features.context_management.experimental_mode,features.context_management"})}if(i===void 0&&s!==void 0){let p=await gr("features.context_management",s);if(JSON.stringify(p)!==JSON.stringify(o.lastManagedValue))throw new N("state_corrupt","The canonical context-management setting changed and cannot be migrated safely.",void 0,{key:"features.context_management"})}if(i===void 0&&s===void 0)throw new N("state_corrupt","The owned legacy context-management setting is missing and cannot be migrated safely.",void 0,{key:"features.context_management.experimental_mode"});let c=e;if(i!==void 0){if(c=fl(c,"features.context_management.experimental_mode"),s===void 0)c=dl(c,"features.context_management",i)}let l=Te(c,"features.context_management");if(l===void 0)throw new N("state_corrupt","The canonical context-management setting is missing.");let u={...t.managed};return u["features.context_management"]={...o,keyPath:"features.context_management",lastManagedValue:await gr("features.context_management",l)},delete u["features.context_management.experimental_mode"],{document:c,state:{...t,managed:u}}}function _j(e,t){if(Te(e,"developer_instructions")!==void 0&&t.managed.developer_instructions===void 0)throw new N("state_corrupt","Existing developer_instructions cannot be displaced safely; remove it or converge managed state first.")}async function bj(e,t){let n=await e.list();return t.map((r)=>{let o=$l(n,r),i=o===void 0?"missing":o.installed&&o.enabled?"installed":o.installed?"disabled":"available";return{plugin_id:r,status:i}})}async function Ul(e,t){if(mt(ln,t)===void 0)throw new N("state_corrupt","The HolyCodex transaction state is invalid.");await Ko(e,Zt(t))}async function P_(e){await AI(e,{force:!1}).catch((t)=>{if(!ht(t,"ENOENT"))throw t})}async function wj(e,t){if(t===void 0){await AI(e,{force:!1}).catch((n)=>{if(!ht(n,"ENOENT"))throw n});return}await Qr(e,t)}async function vj(e,t,n,r,o,i=[]){let a=await Xt(e.configFile),s=eo(a),c=Pf(t,n,r);for(let[p,f]of Object.entries(c)){let h=Te(s,p);if(p==="developer_instructions"){if(typeof h!=="string"||await Tj(p,h)!==o.managed[p]?.lastManagedValue.value)throw new N("install_failed","The effective Root instructions did not converge.")}else if(h!==f)throw new N("install_failed",`The effective Codex setting ${p} did not converge.`)}let l=Ki(t,n);for(let p of l){let f=`agents."${p.name}".config_file`,h=Te(s,f);if(typeof h!=="string")throw new N("install_failed",`The ${p.name} registration is missing.`);let m=mj(e.roleRoot,`${p.name}.toml`),w=m.replaceAll("\\","/");if(hl(e.configFile,h).replaceAll("\\","/")!==w)throw new N("install_failed",`The ${p.name} registration is stale.`);let y=await Xt(m);if(y===void 0)throw new N("install_failed",`The ${p.name} role file is missing.`);if(i.includes(m))continue;let R=eo(y);if(R.name!==p.name||typeof R.description!=="string"||typeof R.model!=="string"||typeof R.model_reasoning_effort!=="string"||typeof R.service_tier!=="string"||typeof R.developer_instructions!=="string"||R.sandbox_mode!==(p.permissions.write?"workspace-write":"read-only")||R.approval_policy!=="never"||R.web_search!==(p.permissions.network?"live":"disabled")||R.tool_output_token_limit!==void 0||Te(R,"agents.enabled")!==!1||Te(R,"features.multi_agent_v2")!==!1||Te(R,"features.multi_agent")!==!1||Te(R,"features.computer_use")!==!1||Te(R,"features.browser_use")!==!1||Te(R,"features.in_app_browser")!==!1)throw new N("install_failed",`The ${p.name} role file is malformed.`)}let u=await Xt(`${e.codexHome}/agents/root.toml`);if(u!==void 0&&ps(u))throw new N("install_failed","A stale HolyCodex Root role remains installed.")}async function Tj(e,t){return await Zr("holycodex-managed-config-value",[Yr({keyPath:e,value:t})])}function Ej(e,t){let n={};for(let r of["computer_use","work","frontend","security"]){let o=t?.[r]??e?.[r];if(o!==void 0)n[r]=o}return n}function Oj(e){return["computer_use","work","frontend","security"].find((t)=>Xc[t].pluginIds.includes(e))}function OI(e){return(e?.official_plugins??[]).filter((t)=>{let n=Oj(t);return n===void 0||e?.optional_selections[n]!==!0})}async function Rj(e,t,n){for(let r of t){let o;try{o=$l(await e.list(),r)}catch(s){throw I_("list",s,r)}if(o?.installed&&!o.enabled)throw new Hl("uncertain",`${r} is disabled`);let i=!(o?.installed&&o.enabled);if(!(o?.installed&&o.enabled))try{await e.add(r)}catch(s){try{let c=$l(await e.list(),r);if(!RI(o,c))n?.(r,"uncertain")}catch{n?.(r,"uncertain")}throw I_("add",s,r)}let a;try{a=$l(await e.list(),r)}catch(s){if(i)n?.(r,"uncertain");throw I_("list",s,r)}if(!a?.installed){if(i&&!RI(o,a))n?.(r,"uncertain");throw new Hl("missing",`${r} is not installed after add`)}if(i&&a.enabled)n?.(r,"new");if(!a.enabled){if(i)n?.(r,"new");throw new Hl("uncertain",`${r} is disabled after add`)}}}function RI(e,t){return e?.pluginId===t?.pluginId&&e?.installed===t?.installed&&e?.enabled===t?.enabled&&e?.marketplaceName===t?.marketplaceName}function I_(e,t,n){if(t instanceof Sr)return t;return new Sr(e==="list"?"list_failed":"add_failed",e==="list"?`Codex could not read the status of ${n}.`:`Codex could not add ${n}.`,t,{plugin_id:n})}function $l(e,t){let n=yr(e,t);if(n!==void 0)return n.entry;let r=Hn(t);return[...e.installed,...e.available].find((o)=>o.pluginId===t&&(r===void 0||o.marketplaceName==null))}function kj(e,t){let n=e??t??"default";if(!fr(n).ok)throw new N("install_failed","Unknown profile.");return n}function Cj(e,t){let n=e??t??"standard";if(mt(Fi,n)===void 0)throw new N("install_failed","The tier is not supported.");return n}function Aj(e,t){let n=t?MI(t):ur,r=Nx(e,n);return{computer_use:r.computer_use,work:r.work,frontend:r.frontend,security:r.security,coding:!0}}function kI(e,t=new Map){return Object.fromEntries(["computer_use","work","frontend","security"].map((r)=>{let o=e[r],i={selected:o,status:o?t.get(r)??"healthy":"disabled",plugin_ids:[...Xc[r].pluginIds]};return[r,i]}))}async function If(e){let{profile:t,plan:n,...r}=e,o=n===void 0?{...r,profile:t}:{...r,plan:n};return await Zr("install-record",[Yr(Zt(o))])}async function Dl(e){return await LI(e)}async function LI(e){return await If({owner:e.owner,install_id:e.install_id,version:e.version,...e.profile===void 0?{}:{profile:e.profile},...e.plan===void 0?{}:{plan:e.plan},tier:e.tier,optional_selections:e.optional_selections,explicit_optional_selections:e.explicit_optional_selections,official_plugins:e.official_plugins??[],capability_state:e.capability_state??null,managed_artifacts:e.managed_artifacts,...e.managed_config===void 0?{}:{managed_config:e.managed_config},...e.plugin_config===void 0?{}:{plugin_config:e.plugin_config},...e.provider_config===void 0?{}:{provider_config:e.provider_config},...e.plugin_snapshot===void 0?{}:{plugin_snapshot:e.plugin_snapshot},...e.owned_plugins===void 0?{}:{owned_plugins:e.owned_plugins}})===e.digest}function CI(e){return e instanceof Error?e.message.slice(0,256):"operation failed"}function zn(e,t){try{e.onProgress?.(t)}catch{}}var hj="davidbasilefilho/holycodex",br="holycodex@holycodex",bI="https://github.com/davidbasilefilho/holycodex.git",PI="holycodex@holycodex",II="holycodex",Hl,N;var ql=x(()=>{El();ut();Ol();Il();kf();Nl();Vi();as();cs();as();Hl=class Hl extends Error{status;constructor(e,t){super(t);this.name="PluginVerificationError",this.status=e}};N=class N extends Error{code;causeValue;details;constructor(e,t,n,r={}){super(t,n===void 0?void 0:{cause:n});this.name="InstallerError",this.code=e,this.causeValue=n,this.details=r}}});import{createInterface as s1}from"readline/promises";ut();ut();ut();var rS=Object.freeze([{name:"yes",kind:"boolean",usage:"--yes",description:"Confirm installation."},{name:"profile",kind:"value",usage:"--profile <low|default|high>",description:"Select routing (default: default)."},{name:"tier",kind:"value",usage:"--tier <standard|fast|fast-all>",description:"Select service handling (default: standard)."},{name:"work",kind:"boolean",usage:"--work / --no-work",description:"Work plugins (default: false)."},{name:"frontend",kind:"boolean",usage:"--frontend / --no-frontend",description:"Frontend plugins via build-web-apps (default: true)."},{name:"security",kind:"boolean",usage:"--security / --no-security",description:"Security plugins (default: true)."},{name:"computer-use",kind:"boolean",usage:"--computer-use / --no-computer-use",description:"Computer Use plugins (default: false)."},{name:"add-plugin",kind:"value",usage:"--add-plugin <id>",description:"Add a Codex plugin; repeatable."},{name:"json",kind:"boolean",usage:"--json",description:"Emit one JSON envelope."}]),gP=new Set(["codex-home","profile","tier","add-plugin"]),sH=new Set(["yes","json","verbose","dry-run","computer-use","no-computer-use","work","no-work","frontend","no-frontend","security","no-security"]);class ze extends Error{code;details;constructor(e,t,n={}){super(t);this.name="ArgumentError",this.code=e,this.details=n}}function Wd(e){if(e.length===0)throw new ze("unknown_command","A command is required.");if(e.includes("-h")||e.includes("--help")||e.includes("--help=true"))return{command:"help",positionals:[],options:{}};if(e[0]==="help")return{command:"help",positionals:e.slice(1),options:{}};if(e[0]==="-v"||e[0]==="--version"||e[0]==="--version=true")return Wd(["version",...e.slice(1)]);let t=e[0];if(t!=="install"&&t!=="doctor"&&t!=="remove"&&t!=="upgrade"&&t!=="version")throw new ze("unknown_command","Unknown command.",{command:t??""});let n=[],r={};for(let o=1;o<e.length;o+=1){let i=e[o];if(i===void 0)continue;if(i==="-"||!i.startsWith("-")){n.push(i);continue}if(!i.startsWith("--")||i==="--")throw new ze("invalid_argument","Short options are not supported.",{option:i});let a=i.slice(2),s=a.indexOf("="),c=s>=0?a.slice(0,s):a,l=s>=0?a.slice(s+1):void 0,u=c.replaceAll("_","-");if(u==="plan")throw new ze("invalid_argument","The --plan option was removed; use --profile <low|default|high>.",{option:"--plan",replacement:"--profile"});if(!gP.has(u)&&!sH.has(u))throw new ze("invalid_argument","Unknown option.",{option:`--${c}`});if(gP.has(u)){let p=l??e[o+1];if(p===void 0||p.length===0||p.startsWith("-"))throw new ze("invalid_argument",`Option --${c} requires a value.`,{option:`--${c}`});if(l===void 0)o+=1;if(u==="add-plugin"){let f=r[u];r[u]=Array.isArray(f)?[...f,p]:[p]}else{if(r[u]!==void 0)throw new ze("invalid_argument",`Option --${c} may only be supplied once.`,{option:`--${c}`});r[u]=p}continue}if(l!==void 0&&l!=="true"&&l!=="false")throw new ze("invalid_argument",`Option --${c} is boolean.`,{option:`--${c}`});if(r[u]!==void 0)throw new ze("invalid_argument",`Option --${c} may only be supplied once.`,{option:`--${c}`});r[u]=l==="false"?!1:!0}return cH(t,n,r),{command:t,positionals:n,options:r}}function cH(e,t,n){let r=uH(e);for(let s of Object.keys(n))if(!r.has(s))throw new ze("invalid_argument",`Option --${s} is not valid for ${e}.`,{option:`--${s}`});let o=e==="version"?{min:0,max:1}:{min:0,max:0};if(t.length<o.min||t.length>o.max)throw new ze("invalid_argument",`Invalid positional arguments for ${e}.`);let i=n.profile;if(typeof i==="string"&&!fr(i).ok){let s=lH[i];if(s!==void 0)throw new ze("invalid_argument",`Legacy profile ${i} was removed; use --profile ${s}.`,{profile:i,replacement:s});if(i==="go"||i==="Go"||i==="pro-5x"||i==="pro-20x")throw new ze("invalid_argument",`Legacy profile ${i} was removed and requires an explicit replacement using --profile <low|default|high>.`,{profile:i});throw new ze("invalid_argument","The profile is not supported.",{profile:i})}let a=n.tier;if(typeof a==="string"&&a!=="standard"&&a!=="fast"&&a!=="fast-all")throw new ze("invalid_argument","The tier is not supported.",{tier:a});for(let[s,c]of[["computer-use","no-computer-use"],["work","no-work"],["frontend","no-frontend"],["security","no-security"]])if(n[s]!==void 0&&n[c]!==void 0)throw new ze("invalid_argument",`Conflicting --${s} and --${c} options.`);if(["install","remove","upgrade"].includes(e)&&n.yes===!1)throw new ze("invalid_argument","--yes cannot be false.");if(e!=="install"&&Object.keys(n).some((s)=>["profile","tier","work","no-work","frontend","no-frontend","security","no-security","computer-use","no-computer-use","add-plugin"].includes(s)))throw new ze("invalid_argument",`Installation options are not valid for ${e}.`)}var lH={"plus-low":"low",plus:"default","plus-high":"high"};function uH(e){switch(e){case"install":return new Set([...rS.map((t)=>t.name),"no-work","no-frontend","no-security","no-computer-use","codex-home","verbose"]);case"doctor":return new Set(["json","verbose","codex-home"]);case"remove":return new Set(["yes","json","verbose","codex-home"]);case"upgrade":return new Set(["yes","json","verbose","dry-run","codex-home"]);case"version":return new Set(["json","verbose","dry-run"]);default:return new Set}}var pH=`HolyCodex
22
43
 
23
44
  Usage:
24
45
  holycodex install [options]
46
+ holycodex remove [options]
47
+ holycodex upgrade [options]
48
+ holycodex doctor [options]
49
+ holycodex version [<0.x.y|patch|minor>] [options]
25
50
 
26
- Plans control routing only:
27
- go Root gpt-5.6-terra/high; leaves use plus-low Luna route efforts.
28
- plus-low Root gpt-5.6-sol/low; leaves use plus-low Luna route efforts.
29
- plus Root gpt-5.6-sol/medium; leaves use plus Luna route efforts.
30
- plus-high, pro-5x Root gpt-5.6-sol/high; each keeps its Luna route efforts.
31
- pro-20x Root gpt-5.6-sol/xhigh; leaves use pro-20x Luna route efforts.
32
- Default plan: plus.
51
+ Options:
52
+ --help, -h Show this help.
53
+ --version, -v Print the canonical version.
54
+ --json Emit one validated JSON envelope.
55
+
56
+ Use --json for scripts. Install and remove use native Codex plugin management.
57
+ `,dH=`Install HolyCodex through Codex native plugin management.
58
+
59
+ Usage:
60
+ holycodex install [options]
61
+
62
+ Profiles control routing only:
63
+ low Root gpt-6-astra/low; specialists use the low Luna matrix.
64
+ default Root gpt-6-astra/medium; recommended default routing.
65
+ high Root gpt-6-astra/high; specialists use the high Luna matrix.
66
+ Default profile: default.
33
67
 
34
68
  Tier is independent service handling (CLI values are lowercase only):
35
69
  standard Standard service handling (default).
@@ -37,7 +71,7 @@ Tier is independent service handling (CLI values are lowercase only):
37
71
  fast-all Fast service handling for Root and leaves.
38
72
 
39
73
  Options:
40
- ${dI.map(e=>` ${e.usage.padEnd(48)} ${e.description}`).join(`
74
+ ${rS.map((e)=>` ${e.usage.padEnd(48)} ${e.description}`).join(`
41
75
  `)}
42
76
  --no-work / --no-frontend / --no-security /
43
77
  --no-computer-use Disable the corresponding plugin.
@@ -45,48 +79,60 @@ ${dI.map(e=>` ${e.usage.padEnd(48)} ${e.description}`).join(`
45
79
 
46
80
  Capability defaults: Work false, Frontend true (mapped to build-web-apps),
47
81
  Security true, and Computer Use false. --add-plugin may be repeated.
48
- `;function yI(e){switch(e){case`install`:return vI;case`remove`:return`Remove HolyCodex-owned state through Codex native plugin management.
82
+ On an interactive TTY, install opens one wizard and final review with Install,
83
+ Change options / Redo, and Cancel. The wizard never asks for CODEX_HOME.
84
+ Additional plugin IDs in the wizard are separated by whitespace; --add-plugin
85
+ remains repeatable on the command line.
86
+ `,fH=`Remove HolyCodex-owned state through Codex native plugin management.
49
87
 
50
88
  Usage:
51
89
  holycodex remove [--yes] [--json] [--codex-home <absolute-path>]
52
90
 
53
91
  Only HolyCodex-owned state is removed. Shared and unrelated Codex plugins and
54
92
  configuration are preserved; changed owned files are preserved for review.
55
- `;case`doctor`:return`Inspect HolyCodex-owned configuration and native plugin state without mutating it.
93
+ `,mH=`Inspect HolyCodex-owned configuration and native plugin state without mutating it.
56
94
 
57
95
  Usage:
58
96
  holycodex doctor [--json] [--codex-home <absolute-path>]
59
- `;case`version`:return`Read or update the canonical public package version.
97
+ `,hH=`Migrate an existing HolyCodex installation in place.
98
+
99
+ Usage:
100
+ holycodex upgrade [--dry-run] [--yes] [--json] [--codex-home <absolute-path>]
101
+
102
+ Upgrade preserves your selected profile, service tier, capabilities, additional
103
+ plugins, and unrelated Codex configuration while applying the running version.
104
+ Use --dry-run to preview changes. It does not download or install a new binary.
105
+ `,gH=`Read or update the canonical public package version.
60
106
 
61
107
  Usage:
62
108
  holycodex version [<0.x.y|patch|minor>] [--dry-run] [--json]
63
109
  holycodex --version
64
110
  holycodex -v
65
- `;default:return`HolyCodex
66
-
67
- Usage:
68
- holycodex install [options]
69
- holycodex remove [options]
70
- holycodex doctor [options]
71
- holycodex version [<0.x.y|patch|minor>] [options]
72
-
73
- Options:
74
- --help, -h Show this help.
75
- --version, -v Print the canonical version.
76
- --json Emit one validated JSON envelope.
77
-
78
- Use --json for scripts. Install and remove use native Codex plugin management.
79
- `}}function bI(e,t={}){let n=CI({...t,stream:`stdout`});return yI(e).split(`
80
- `).map(e=>e===`HolyCodex`||/^(?:Usage|Options|Plans control routing only|Tier is independent service handling|Capability defaults).*:$/u.test(e)?wI(e,`heading`,n):e.replace(/--[a-z][a-z0-9-]*/gu,e=>wI(e,`option`,n)).replace(/<[^>]+>/gu,e=>wI(e,`argument`,n))).join(`
81
- `)}function xI(e){return e.some(e=>e===`-h`||e===`--help`||e===`--help=true`)}function SI(e){let t=e.filter(e=>!e.startsWith(`-`));return t[0]===`help`?t[1]:t[0]===`--version`||t[0]===`version`||t[0]===`-v`?`version`:t[0]}function CI(e){let t=e.env??{};return t.NO_COLOR!==void 0||t.TERM===`dumb`?!1:t.FORCE_COLOR!==void 0&&t.FORCE_COLOR!==`0`?!0:t.CI!==void 0&&t.CI!==`false`?!1:(e.stream===`stderr`?e.stderrIsTTY:e.stdoutIsTTY)===!0}function wI(e,t,n){return n?`\u001b[${{heading:`1`,option:`36`,argument:`2`}[t]}m${e}\u001b[0m`:e}function Y(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function TI(e){try{return _F(e),!0}catch{return!1}}function EI(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 DI(e){return{ok:!1,error:e}}function OI(e){return{ok:!0,value:e}}function kI(e,t=512){let n=``;for(let t of e){let e=t.codePointAt(0)??0;n+=e<=8||e===11||e===12||e>=14&&e<=31||e===127?` `:t}return n.replace(/\s+/gu,` `).trim().slice(0,t)}function AI(e,t=0){if(t>3)return`[truncated]`;if(e===null||typeof e==`boolean`)return e;if(typeof e==`string`)return kI(e,256);if(typeof e==`number`)return Number.isFinite(e)?e:null;if(Array.isArray(e))return e.slice(0,32).map(e=>AI(e,t+1));if(Y(e)){let n={};for(let[r,i]of Object.entries(e).slice(0,32)){let e=kI(r,96);e.length>0&&(n[e]=AI(i,t+1))}return n}return`[redacted]`}function jI(e){let t=AI(e);return Y(t)?t:{value:t}}function MI(e,t,n){return new X(`invalid_external_data`,`Invalid ${e}.`,{field:e,received:AI(t)},n===void 0?void 0:{cause:n})}function NI(e,t,n){let r=mP(e,t);if(er(r))throw MI(n,t,String(r.left));return r.right}function PI(e,t){try{return NI(e,t,`value`),!0}catch{return!1}}var FI,II,LI,RI,X,zI=v((()=>{uI(),lr(),pP(),FI=fe,II=G(e=>TI(e)),LI=G(e=>Y(e)&&TI(e)),K.pipe(CM(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u)),RI=K.pipe(pj(e=>e.length>0&&e.length<=4096)),Fj.pipe(pj(e=>Number.isFinite(e)&&e>=0)),X=class 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=EI(e),this.details=n,this.retryable=r?.retryable??!1,Object.freeze(this.details),Object.freeze(this)}}})),BI,VI,HI,UI,WI,GI,KI=v((()=>{BI=[`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`],VI=[`item/commandExecution/requestApproval`,`item/fileChange/requestApproval`,`applyPatchApproval`,`execCommandApproval`],HI=[`item/permissions/requestApproval`],UI=[`mcpServer/elicitation/request`],WI=[`item/tool/call`],GI={method:`initialized`}}));function qI(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{return Array.isArray(e)?e.every(e=>qI(e,t)):Y(e)&&Object.values(e).every(e=>qI(e,t))}finally{t.delete(e)}}function JI(e){return Y(e)&&qI(e)}function YI(e){let t=[],n=0,r=!1,i=!1;for(let a=0;a<=e.length;a+=1){let o=e[a];if(a===e.length||o===`.`&&!r){let r=e.slice(n,a),i=r.startsWith(`"`)?XI(r):r;if(!/^[A-Za-z][A-Za-z0-9_-]*$/u.test(i)&&!pF.includes(i))throw MI(`TOML key path`,e);t.push(i),n=a+1;continue}r?i?i=!1:o===`\\`?i=!0:o===`"`&&(r=!1):o===`"`&&(r=!0)}if(r||i||t.length===0||t.some(e=>e===`__proto__`||e===`constructor`||e===`prototype`))throw MI(`TOML key path`,e);return t}function XI(e){try{let t=JSON.parse(e);if(typeof t==`string`)return t}catch{}throw MI(`TOML quoted key`,e)}function ZI(e,t){if(!JI(e))throw MI(`TOML document`,e);let n=e;for(let e of YI(t)){if(!JI(n)||!Object.prototype.hasOwnProperty.call(n,e))return;n=n[e]}return n}function QI(e){return Array.isArray(e)?e.map(QI):Y(e)?Object.fromEntries(Object.entries(e).map(([e,t])=>[e,QI(t)])):e}function $I(e){return QI(e)}function eL(e,t,n){if(!JI(e)||!qI(n))throw MI(`TOML write`,{keyPath:t});let r=YI(t),i={...$I(e)},a=i;for(let e of r.slice(0,-1)){let n=a[e];if(n!==void 0&&!JI(n))throw MI(`TOML table path`,t);let r=n===void 0?{}:{...n};a[e]=r,a=r}return a[r.at(-1)]=QI(n),i}function tL(e,t){if(!JI(e))throw MI(`TOML document`,e);let n=YI(t),r={...$I(e)},i=[],a=r;for(let e of n.slice(0,-1)){let t=a[e];if(!JI(t))return r;let n={...t};i.push({table:a,key:e}),a[e]=n,a=n}let o=n.at(-1);if(!Object.prototype.hasOwnProperty.call(a,o))return r;delete a[o];for(let e=i.length-1;e>=0;--e){let t=i[e],n=t.table[t.key];if(JI(n)&&Object.keys(n).length===0)delete t.table[t.key];else break}return r}function nL(e){return typeof e==`string`?wL.includes(e)||/^agents\.(?:explorer|librarian|worker|reviewer)\.config_file$/u.test(e)?!0:pF.some(t=>e===`agents."${t}".config_file`):!1}function rL(e){return typeof e==`string`&&EL.test(e)}function iL(e){return 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 aL(e){return typeof e==`string`&&/^[a-f0-9]{64}$/u.test(e)}function oL(e,t){let n=new Set(t);return Object.keys(e).every(e=>n.has(e))}function sL(e){if(!Y(e)||!oL(e,[`kind`,`value`])||typeof e.kind!=`string`)return!1;switch(e.kind){case`enum`:return iL(e.value);case`boolean`:return typeof e.value==`boolean`;case`relative_path`:return typeof e.value==`string`&&pL(e.value);case`digest`:return aL(e.value);default:return!1}}function cL(e,t){switch(gL(e)){case`boolean`:return t.kind===`boolean`;case`relative_path`:return t.kind===`relative_path`;case`digest`:return t.kind===`digest`;case`enum`:return t.kind===`enum`?e===`model`?t.value===`gpt-5.6-terra`||t.value===`gpt-5.6-sol`||t.value===`gpt-5.6-luna`:e===`model_reasoning_effort`?t.value===`low`||t.value===`medium`||t.value===`high`||t.value===`xhigh`||t.value===`max`:e===`service_tier`?t.value==="default"||t.value===`fast`:t.value===`low`||t.value===`medium`||t.value===`high`:!1}}function lL(e){return Y(e)&&e.kind===`absent`?Object.keys(e).length===1:sL(e)}function uL(e){return Y(e)&&oL(e,[`owner`,`schema`,`installId`,`keyPath`,`originalValue`,`lastManagedValue`])&&e.owner===`holycodex`&&typeof e.schema==`string`&&rL(e.schema)&&rL(e.installId)&&nL(e.keyPath)&&lL(e.originalValue)&&sL(e.lastManagedValue)&&cL(e.keyPath,e.lastManagedValue)&&(e.originalValue.kind===`absent`||cL(e.keyPath,e.originalValue))}function dL(e){return!Y(e)||!oL(e,[`owner`,`schema`,`installId`,`managed`])||e.owner!==`holycodex`||!rL(e.schema)||!rL(e.installId)||!Y(e.managed)?!1:Object.entries(e.managed).every(([e,t])=>nL(e)&&uL(t)&&t.keyPath===e)}function fL(e){if(!rL(e.schema)||!rL(e.installId))throw MI(`managed runtime config metadata`,{schema:e.schema});return{owner:`holycodex`,schema:e.schema,installId:e.installId,managed:{}}}function pL(e){if(e.length===0||e.includes(`\0`)||/^[\\/]|^[A-Za-z]:[\\/]/u.test(e))return!1;let t=e.replaceAll(`\\`,`/`).split(`/`);return t.some(e=>e!==`.`)&&t.every(e=>e.length>0&&e!==`..`)}function mL(e){if(!pL(e))throw MI(`relative config path`,`[redacted]`);return e.replaceAll(`\\`,`/`).split(`/`).filter(e=>e!==`.`).join(`/`)}function hL(e,t){let n=mL(t),r=e.replaceAll(`\\`,`/`).split(`/`);r.pop();let i=[...r,...n.split(`/`)].join(`/`),a=[];for(let e of i.split(`/`))e.length!==0&&e!==`.`&&(e===`..`?a.pop():a.push(e));let o=e.replaceAll(`\\`,`/`);return`${o.startsWith(`//`)?`//`:o.startsWith(`/`)?`/`:``}${a.join(`/`)}`}function gL(e){return e===`developer_instructions`?`digest`:e.endsWith(`.config_file`)?`relative_path`:e===`suppress_unstable_features_warning`||e===`features.default_mode_request_user_input`||e===`features.multi_agent_v2`||e===`features.context_management.experimental_mode`?`boolean`:`enum`}function _L(e,t){let n=gL(e);return n===`boolean`?typeof t==`boolean`:n===`relative_path`?typeof t==`string`&&pL(t):n===`digest`?typeof t==`string`:typeof t==`string`&&iL(t)}async function vL(e,t){if(!nL(e)||!qI(t))throw MI(`managed config value`,{keyPath:e});let n=gL(e);return n===`boolean`&&typeof t==`boolean`?{kind:n,value:t}:n===`relative_path`&&typeof t==`string`&&pL(t)?{kind:n,value:mL(t)}:n===`enum`&&typeof t==`string`&&iL(t)?{kind:n,value:t}:{kind:`digest`,value:await xF(`holycodex-managed-config-value`,[vF({keyPath:e,value:t})])}}function yL(e){if(e.kind===`enum`||e.kind===`boolean`||e.kind===`relative_path`)return e.value}async function bL(e,t,n,r){if(!JI(e)||!dL(t)||!rL(r.schema)||!rL(r.installId))throw MI(`managed runtime config`,{});let i={...t.managed},a=$I(e),o=[];for(let[e,s]of Object.entries(n)){if(!nL(e)||typeof s!=`string`&&typeof s!=`boolean`)throw MI(`managed config key`,e);let n=e,c=t.managed[n],l=ZI(a,n);if(c&&(c.schema!==r.schema||c.installId!==r.installId)){o.push(n);continue}if(c&&c.owner===`holycodex`){let e=l===void 0?void 0:await vL(n,l);if(e===void 0||JSON.stringify(e)!==JSON.stringify(c.lastManagedValue)){o.push(n);continue}}let u=c?.originalValue??(l===void 0?{kind:`absent`}:await vL(n,l));if(!_L(n,s))throw MI(`managed config value`,{keyPath:n});a=eL(a,n,s),i[n]={owner:`holycodex`,schema:r.schema,installId:r.installId,keyPath:n,originalValue:u,lastManagedValue:await vL(n,s)}}let s={owner:`holycodex`,schema:r.schema,installId:r.installId,managed:i};if(!dL(s))throw MI(`managed runtime config state`,{});return{document:a,state:s,driftedKeys:o}}async function xL(e,t,n){if(!JI(e)||!dL(t))throw MI(`managed runtime config`,{});let r=$I(e),i={...t.managed},a=[],o=[],s=[];for(let[e,c]of Object.entries(t.managed)){if(!nL(e))throw MI(`managed config key`,e);let t=e;if(c.owner!==`holycodex`||c.schema!==n.schema||c.installId!==n.installId)continue;let l=ZI(r,t);if(l===void 0||JSON.stringify(await vL(t,l))!==JSON.stringify(c.lastManagedValue)){o.push(t);continue}if(c.originalValue.kind===`absent`)r=tL(r,t),a.push(t),delete i[t];else{let e=yL(c.originalValue);if(e===void 0){s.push(t),o.push(t);continue}r=eL(r,t,e),a.push(t),delete i[t]}}return{document:r,state:{...t,managed:i},restoredKeys:a,preservedKeys:o,unresolvedKeys:s}}async function SL(e,t,n){if(!nL(n)||!dL(t))throw MI(`managed config key`,n);let r=t.managed[n],i=ZI(e,n),a=i===void 0?void 0:await vL(n,i);return r?{keyPath:n,status:a!==void 0&&JSON.stringify(a)===JSON.stringify(r.lastManagedValue)?`unchanged`:`drifted`,expected:r.lastManagedValue,...a===void 0?{}:{current:a}}:a===void 0?{keyPath:n,status:`unmanaged`}:{keyPath:n,status:`unmanaged`,current:a}}var CL,wL,TL,EL,DL=v((()=>{uI(),pP(),zI(),G(e=>qI(e)),CL=G(e=>JI(e)),wL=[`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`],G(e=>nL(e)),G(e=>sL(e)),G(e=>lL(e)),G(e=>uL(e)),TL=G(e=>dL(e)),EL=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u}));function OL(e){return typeof e==`number`&&Number.isFinite(e)&&e>=0}function kL(e,t,n){let r=new Set([...t,n]),i=Object.keys(e);return!Object.keys(e).some(e=>!r.has(e))&&i.length>0&&i.every(t=>OL(e[t]))}function AL(e){return!Y(e)||!TI(e)?!1:kL(e,[`inputTokens`,`cachedInputTokens`,`outputTokens`,`reasoningOutputTokens`],`totalTokens`)||kL(e,[`input_tokens`,`cached_input_tokens`,`output_tokens`,`reasoning_output_tokens`],`total_tokens`)}function jL(e){return Y(e)&&TI(e)&&typeof e.id==`string`&&/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u.test(e.id)}function ML(e){return Y(e)&&TI(e)&&jL(e.thread)}function NL(e){return Y(e)&&TI(e)&&typeof e.id==`string`}function PL(e){return Y(e)&&TI(e)&&typeof e.threadId==`string`&&e.threadId.length>0}function FL(e){return Y(e)&&TI(e)&&typeof e.id==`string`&&e.id.length>0&&(e.usage===void 0||AL(e.usage))}function IL(e){return Y(e)&&TI(e)&&typeof e.id==`string`&&typeof e.model==`string`&&(e.supportedReasoningEfforts===void 0||Array.isArray(e.supportedReasoningEfforts)&&e.supportedReasoningEfforts.every(e=>Y(e)&&typeof e.reasoningEffort==`string`))&&(e.serviceTiers===void 0||Array.isArray(e.serviceTiers)&&e.serviceTiers.every(e=>Y(e)&&typeof e.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 LL(e){return HI.some(t=>t===e)?`permissions`:VI.some(t=>t===e)?`approval`:UI.some(t=>t===e)?`elicitation`:WI.some(t=>t===e)?`dynamic_tool`:`other`}var RL,zL,BL,VL,HL,UL,WL,GL,KL,qL,JL,YL,XL,ZL,QL,$L,eR,tR,nR,rR,iR,aR,oR,sR,cR,lR,uR,dR,fR,pR,mR,hR,gR,_R,vR,yR,bR,xR,SR,CR=v((()=>{pP(),zI(),KI(),DL(),RL=K.pipe(CM(/^[A-Za-z][A-Za-z0-9_./:-]{0,127}$/u)),zL=U(K.pipe(yM(1)),Fj.pipe(pj(e=>Number.isSafeInteger(e)))),BL=W({code:Fj.pipe(pj(e=>Number.isSafeInteger(e))),message:K,data:J(II)}),VL=U(W({id:zL,result:II}),W({id:zL,error:BL})),W({id:zL,error:BL}),HL=W({method:RL,params:J(II)}),UL=W({id:zL,method:RL,params:J(II),trace:J(II)}),G(AL),WL=W({clientInfo:W({name:RI,version:RI,title:U(RI,Aj)}),capabilities:U(W({experimentalApi:q,requestAttestation:q,mcpServerOpenaiFormElicitation:J(q),optOutNotificationMethods:J(U(Vj(K),Aj)),extensions:J(LI)}),Aj)}),GL=G(e=>Y(e)&&TI(e)&&typeof e.userAgent==`string`&&typeof e.codexHome==`string`&&typeof e.platformFamily==`string`&&typeof e.platformOs==`string`),KL=W({method:H(`initialized`)}),G(jL),qL=G(e=>ML(e)||NL(e)),JL=qL,YL=qL,XL=G(PL),ZL=G(e=>Y(e)&&TI(e)&&(e.status===`notLoaded`||e.status===`notSubscribed`||e.status===`unsubscribed`)),QL=G(e=>ML(e)),$L=G(e=>{if(!Y(e)||!TI(e))return!1;let t=Array.isArray(e.data)&&e.data.every(e=>jL(e)),n=Array.isArray(e.threads)&&e.threads.every(e=>jL(e));return t&&e.threads===void 0||n&&e.data===void 0}),eR=G(e=>Y(e)&&TI(e)),tR=G(PL),nR=G(PL),rR=G(PL),iR=G(e=>Y(e)&&TI(e)),aR=G(e=>PL(e)&&(Array.isArray(e.input)&&e.input.every(e=>TI(e))||typeof e.prompt==`string`&&e.prompt.length>0)),oR=G(e=>PL(e)&&typeof e.expectedTurnId==`string`&&Array.isArray(e.input)&&e.input.every(e=>TI(e))),sR=G(e=>Y(e)&&TI(e)&&(e.turn!==void 0&&FL(e.turn)||typeof e.turnId==`string`&&e.turnId.length>0||typeof e.id==`string`&&e.id.length>0)),cR=G(e=>Y(e)&&TI(e)&&typeof e.turnId==`string`&&e.turnId.length>0),lR=G(e=>PL(e)&&typeof e.turnId==`string`&&e.turnId.length>0),uR=G(e=>Y(e)&&TI(e)),dR=G(e=>PL(e)&&(e.turn!==void 0&&FL(e.turn)||typeof e.turnId==`string`&&e.turnId.length>0)),fR=G(e=>Y(e)&&TI(e)),pR=G(e=>Y(e)&&TI(e)&&Array.isArray(e.data)&&e.data.every(e=>IL(e))),mR=LI,hR=LI,gR=W({includeLayers:J(q),cwd:J(U(K,Aj))}),_R=W({config:CL,origins:LI,layers:U(Vj(LI),Aj)}),vR=LI,yR=LI,bR=G(e=>Y(e)&&TI(e)&&(typeof e.id==`string`||typeof e.id==`number`&&Number.isSafeInteger(e.id))&&typeof e.method==`string`&&Y(e.params)&&(e.category===`approval`||e.category===`dynamic_tool`||e.category===`elicitation`||e.category===`other`||e.category===`permissions`)),xR=II,G(e=>Y(e)&&TI(e)&&typeof e.kind==`string`&&typeof e.method==`string`),SR=U(H(`stable`,`experimental`,`disabled`),q),oM({key:K,value:SR})}));function wR(e){let t=kI(e);return t.length>0?t:`server request failed`}function TR(e){return HI.some(t=>t===e)?`permission_denied`:VI.some(t=>t===e)?`approval_required`:e===`turn/interrupt`?`cancellation`:e.startsWith(`turn/`)?`turn_failed`:`server_error`}var ER,DR,OR,kR=v((()=>{zI(),KI(),CR(),ER={clientInfo:{name:`holycodex`,title:null,version:FI},capabilities:null},DR=new Set(BI),OR=class{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??1048576,this.requestTimeoutMs=t.requestTimeoutMs,this.signal=t.signal,!Number.isSafeInteger(this.maxLineBytes)||this.maxLineBytes<1)throw new X(`invalid_external_data`,`The maximum line size is invalid.`);if(this.requestTimeoutMs!==void 0&&(!Number.isSafeInteger(this.requestTimeoutMs)||this.requestTimeoutMs<1))throw new X(`invalid_external_data`,`The request timeout is invalid.`);t.onNotification&&this.notificationListeners.add(t.onNotification),t.onServerRequest&&this.serverRequestHandlers.add(t.onServerRequest),this.signal?.aborted?this.close():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=ER){if(this.initializePromise)return this.initializePromise;if(this.initializeAttempted)throw new X(`invalid_external_data`,`The App Server initialize handshake was already attempted.`);this.ensureOpen();let t=NI(WL,e,`initialize parameters`);return this.initializeAttempted=!0,this.initializePromise=this.performInitialize(t),this.initializePromise}async startThread(e={}){return this.action(`thread/start`,eR,e,qL)}async resumeThread(e){let t=typeof e==`string`?{threadId:e}:e;return this.action(`thread/resume`,tR,t,JL)}async readThread(e){let t=typeof e==`string`?{threadId:e}:e;return this.action(`thread/read`,nR,t,QL)}async listThreads(e={}){return this.action(`thread/list`,iR,e,$L)}async forkThread(e){let t=typeof e==`string`?{threadId:e}:e;return this.action(`thread/fork`,rR,t,YL)}async unsubscribeThread(e){let t=typeof e==`string`?{threadId:e}:e;return this.action(`thread/unsubscribe`,XL,t,ZL)}async startTurn(e){return this.action(`turn/start`,aR,e,sR)}async steerTurn(e){return this.action(`turn/steer`,oR,e,cR)}async interruptTurn(e,t){let n=typeof e==`string`?{threadId:e,turnId:t??``}:e;return this.action(`turn/interrupt`,lR,n,uR)}async listModels(e={}){return this.action(`model/list`,fR,e,pR)}async readModelProviderCapabilities(e={}){return this.action(`modelProvider/capabilities/read`,mR,e,hR)}async readConfig(e={}){return this.action(`config/read`,gR,e,_R)}async listPermissionProfiles(e={}){return this.action(`permissionProfile/list`,vR,e,yR)}async call(e,t={}){if(e===`initialize`){let e=await this.initialize(NI(WL,t,`initialize parameters`));return NI(II,e,`initialize result`)}let n=NI(UL,{id:1,method:e,params:t},`App Server method`);if(!DR.has(n.method))throw new X(`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 X(`closed`,`The App Server client is closed.`))}async performInitialize(e){try{let t=await this.request(`initialize`,NI(II,e,`initialize parameters`)),n=NI(GL,t,`initialize result`),r=NI(KL,GI,`initialized notification`);return await this.transport.writeLine(JSON.stringify(r)),this.initialized=!0,n}catch(e){let t=e instanceof X?e:new X(`transport_failure`,`The initialize handshake failed.`,{},{cause:e});throw await this.closeWithError(t),t}}async action(e,t,n,r){let i=NI(t,n,`${e} parameters`),a=NI(II,i,`${e} parameters`);return NI(r,await this.request(e,a),`${e} result`)}async request(e,t){if(this.ensureOpen(),e!==`initialize`&&!this.initialized)throw new X(`invalid_external_data`,`The ${e} action requires an initialized App Server client.`);this.startReader();let n=this.nextRequestId;this.nextRequestId+=1;let r=NI(UL,{id:n,method:e,params:t},`${e} request`);return new Promise((t,i)=>{let a=!1,o,s,c=e=>{a||(a=!0,this.pending.delete(n),o!==void 0&&clearTimeout(o),s?.(),i(e))};if(this.requestTimeoutMs!==void 0&&(o=setTimeout(()=>c(new X(`timeout`,`The ${e} request timed out.`,{method:e})),this.requestTimeoutMs)),this.signal){let t=()=>c(new X(`cancellation`,`The ${e} request was cancelled.`,{method:e}));this.signal.addEventListener(`abort`,t,{once:!0}),s=()=>this.signal?.removeEventListener(`abort`,t)}let l={method:e,resolve:e=>{a||(a=!0,o!==void 0&&clearTimeout(o),s?.(),t(e))},reject:c,...o===void 0?{}:{timer:o},...s===void 0?{}:{removeAbortListener:s}};this.pending.set(n,l),this.transport.writeLine(JSON.stringify(r)).catch(e=>{c(e instanceof X?e:new X(`transport_failure`,`The App Server request could not be written.`,{},{cause:e}))})})}startReader(){this.readerPromise||=this.readLoop().catch(e=>this.handleReaderFailure(e)).catch(()=>void 0)}async readLoop(){for(;!this.closed;){let e=await this.transport.readLine();if(e===null){if(!this.closed)throw new X(`transport_closed`,`The App Server transport closed.`);return}if(new TextEncoder().encode(e).byteLength>this.maxLineBytes)throw new X(`invalid_transport_line`,`An App Server line exceeded the limit.`);this.handleLine(e)}}async handleReaderFailure(e){let t=e instanceof X?e:new X(`transport_failure`,`The App Server transport failed.`,{},{cause:e});await this.closeWithError(t)}handleLine(e){let t;try{t=JSON.parse(e)}catch(e){throw new X(`invalid_transport_line`,`The App Server emitted invalid JSON.`,{},{cause:e})}let n=this.tryDecode(VL,t);if(n!==void 0){this.handleResponse(n);return}let r=this.tryDecode(UL,t);if(r!==void 0){this.handleServerRequest(r);return}let i=this.tryDecode(HL,t);if(i!==void 0){this.handleNotification(i);return}throw MI(`JSON-RPC message`,t)}tryDecode(e,t){try{return NI(e,t,`JSON-RPC message`)}catch{return}}handleResponse(e){let t=this.pending.get(e.id);if(!t)throw new X(`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=TR(t.method);t.reject(new X(r,`The App Server rejected ${t.method}: ${kI(e.error.message)}.`,{method:t.method,serverCode:e.error.code,retryable:n,...e.error.data===void 0?{}:{data:AI(e.error.data)}},{retryable:n}));return}t.resolve(e.result)}handleServerRequest(e){let t=e.params??{},n=NI(bR,{...e,params:t,category:LL(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 i=r[0];if(i===void 0){this.trackServerRequestTask(this.writeServerError(e.id,-32601,`No handler for ${e.method}.`));return}let a={active:!0};this.serverRequestWork.add(a);let o;try{o=i(n)}catch(t){this.completeServerRequest(a,()=>this.writeServerError(e.id,-32e3,kI(String(t))));return}if(o instanceof Promise){this.trackServerRequestTask(o.then(t=>this.completeServerRequest(a,()=>this.writeValidatedServerResult(e.id,t)),t=>this.completeServerRequest(a,()=>this.writeServerError(e.id,-32e3,kI(String(t))))));return}this.completeServerRequest(a,()=>this.writeValidatedServerResult(e.id,o))}writeValidatedServerResult(e,t){try{let n=NI(xR,t,`server response`);return this.writeServerResult(e,n)}catch(t){return this.writeServerError(e,-32e3,kI(String(t)))}}completeServerRequest(e,t){if(e.active){e.active=!1,this.serverRequestWork.delete(e);try{this.trackServerRequestTask(t())}catch{}}}trackServerRequestTask(e){let t=e.catch(()=>void 0);this.serverRequestTasks.add(t),t.then(()=>this.serverRequestTasks.delete(t),()=>this.serverRequestTasks.delete(t))}async writeServerResult(e,t){let n=NI(VL,{id:e,result:t},`server response`);await this.transport.writeLine(JSON.stringify(n))}async writeServerError(e,t,n){let r=NI(VL,{id:e,error:{code:t,message:wR(n)}},`server error response`);await this.transport.writeLine(JSON.stringify(r))}handleNotification(e){let t=e.params;if(e.method===`turn/completed`){let n=NI(dR,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:jI({params:AI(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 e of this.serverRequestWork)e.active=!1;this.serverRequestWork.clear(),this.serverRequestTasks.clear(),this.transportClosePromise=Promise.resolve().then(()=>this.transport.close()).catch(()=>void 0),await this.transportClosePromise}ensureOpen(){if(this.closed)throw new X(`closed`,`The App Server client is closed.`)}}}));function AR(e=process.env){let t=[`PATH`,`HOME`,`USER`,`CODEX_HOME`,`TMPDIR`,`TEMP`,`TMP`,`LANG`,`LC_ALL`],n={};for(let r of t){let t=e[r];t!==void 0&&t.length>0&&(n[r]=t)}return n}function jR(e=process.env){return Object.freeze(AR(e))}async function MR(e,t){let n=e.getReader(),r=[],i=0;try{for(;;){let e=await n.read();if(e.done)break;if(i+=e.value.byteLength,i>t)throw new X(`invalid_transport_line`,`A subprocess stream exceeded its limit.`);r.push(e.value)}}finally{n.releaseLock()}let a=new Uint8Array(i),o=0;for(let e of r)a.set(e,o),o+=e.byteLength;return a}function NR(e,t){try{return new TextDecoder(`utf-8`,{fatal:!0}).decode(e)}catch(e){throw new X(`invalid_transport_line`,`Invalid UTF-8 in ${t}.`,{},{cause:e})}}function PR(e){return kI(e.replace(/Bearer\s+[^\s]+/giu,`Bearer [redacted]`).replace(/((?:api[_-]?key|authorization|cookie|password|secret|token)\s*[:=]\s*)[^\s,;]+/giu,`$1[redacted]`),512)}var FR,IR=v((()=>{zI(),FR=class{process;stdin;stdoutReader;stderrStream;maxLineBytes;maxDiagnosticBytes;lineDecoder=new TextDecoder(`utf-8`,{fatal:!0});stderrDiagnostics=[];stdoutBuffer=new Uint8Array;stderrPromise;closed=!1;constructor(e){if(!g(e.executablePath))throw new X(`discovery_failed`,`The Codex executable path must be absolute.`);if(this.maxLineBytes=e.maxLineBytes??1048576,this.maxDiagnosticBytes=e.maxDiagnosticBytes??65536,this.maxLineBytes<1||this.maxDiagnosticBytes<1)throw new X(`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:AR(e.environment),stdin:`pipe`,stdout:`pipe`,stderr:`pipe`}),!(this.process.stdout instanceof ReadableStream)||!(this.process.stderr instanceof ReadableStream))throw new X(`transport_failure`,`The Codex App Server did not expose stdio pipes.`);if(typeof this.process.stdin==`number`||this.process.stdin===void 0)throw new X(`transport_failure`,`The Codex App Server did not expose stdin.`);this.stdin=this.process.stdin,this.stdoutReader=this.process.stdout,this.stderrStream=this.process.stderr,this.stderrPromise=this.collectStderr(),e.signal&&(e.signal.aborted?this.close():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{for(;;){let t=this.stdoutBuffer.indexOf(10);if(t>=0){if(t>this.maxLineBytes)throw await this.close(),new X(`invalid_transport_line`,`The App Server emitted an overlong line.`);let e=this.stdoutBuffer.slice(0,t);this.stdoutBuffer=this.stdoutBuffer.slice(t+1);let n=e.at(-1)===13?e.slice(0,-1):e;return this.lineDecoder.decode(n)}if(this.stdoutBuffer.byteLength>this.maxLineBytes)throw await this.close(),new X(`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 X(`invalid_transport_line`,`The App Server emitted an overlong line.`);let e=this.stdoutBuffer;return this.stdoutBuffer=new Uint8Array,this.lineDecoder.decode(e)}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(e){throw e instanceof X?e:new X(`transport_failure`,`The App Server stdout could not be read.`,{},{cause:e})}finally{e.releaseLock()}}async writeLine(e){if(this.closed)throw new X(`closed`,`The App Server transport is closed.`);if(new TextEncoder().encode(e).byteLength>this.maxLineBytes)throw new X(`invalid_transport_line`,`The App Server request exceeded the line limit.`);try{await this.stdin.write(`${e}\n`),await this.stdin.flush()}catch(e){throw new X(`transport_failure`,`The App Server stdin could not be written.`,{},{cause:e})}}async close(){if(!this.closed){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),1e3))]),await this.stderrPromise.catch(()=>void 0)}}async collectStderr(){try{let e=NR(await MR(this.stderrStream,this.maxDiagnosticBytes),`Codex stderr`);for(let t of e.split(/\r?\n/u).slice(0,128)){let e=PR(t);e.length>0&&this.stderrDiagnostics.push(e)}}catch{this.stderrDiagnostics.push(`[stderr unavailable]`)}}}}));async function LR(e){let t=[];if(e.executablePath!==void 0)t.push(ne(e.cwd??process.cwd(),e.executablePath));else{let n=e.pathValue??process.env.PATH??``,r=process.platform===`win32`?[`codex.exe`,`codex.cmd`,`codex`]:[`codex`];for(let e of n.split(m).filter(e=>e.length>0))for(let n of r)t.push(ne(e,n))}for(let n of t)try{let e=await d(n);if(!e.isFile()||process.platform!==`win32`&&!(e.mode&73))continue;return await s(n)}catch{if(e.executablePath!==void 0)throw new X(`discovery_failed`,`The explicit Codex executable was not found.`,{path:n})}throw new X(`discovery_failed`,`No Codex executable was found on the allowlisted PATH.`)}async function RR(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 X(`discovery_failed`,`The Codex version command did not expose output pipes.`);try{let[e,t,r]=await VR(Promise.all([MR(n.stdout,16384),MR(n.stderr,16384),n.exited]),()=>n.kill(),`The Codex version command timed out.`),i=kI(NR(e,`Codex version output`));if(r!==0||i.length===0){let e=PR(NR(t,`Codex version diagnostics`));throw new X(`discovery_failed`,`The Codex executable did not provide a version.`,{exitCode:r,diagnostics:e})}return i}catch(e){try{n.kill()}catch{}throw e instanceof X?e:new X(`discovery_failed`,`The Codex version command failed.`,{},{cause:e})}}async function zR(e){let t=await a(e),n=await crypto.subtle.digest(`SHA-256`,t),r=VP([...new Uint8Array(n)].map(e=>e.toString(16).padStart(2,`0`)).join(``));if(!r.ok)throw new X(`discovery_failed`,`The Codex executable digest was invalid.`);return r.value}async function BR(e={}){let t=await LR(e),n=AR(e.environment),r=e.versionRunner?kI(await e.versionRunner(t,n)):await RR(t,n);if(r.length===0)throw new X(`discovery_failed`,`The Codex version output was empty.`);return{path:t,version:r,sha256:await zR(t)}}async function VR(e,t,n){let r;try{return await Promise.race([e,new Promise((e,i)=>{r=setTimeout(()=>{try{t()}catch{}i(new X(`timeout`,n))},HR)})])}finally{r!==void 0&&clearTimeout(r)}}var HR,UR=v((()=>{uI(),pP(),zI(),IR(),HR=3e4,W({exitCode:Fj.pipe(pj(e=>Number.isSafeInteger(e))),stdout:K.pipe(_M(1048576)),stderr:K.pipe(_M(1048576))})})),WR,GR,KR,qR,JR=v((()=>{uI(),pP(),zI(),WR=`packages/codex/generated`,GR=/^codex-cli \d+\.\d+\.\d+$/u,KR=/^codex-app-server-\d+\.\d+\.\d+$/u,qR=K.pipe(CM(/^[a-f0-9]{64}$/u)),W({schema_version:H(`holycodex-generated-v2`),artifact_root:H(WR),codex_cli_version:K.pipe(CM(GR)),codex_cli_digest:qR,protocol_epoch:K.pipe(CM(KR)),generator:W({command:sj(H(`app-server`),H(`generate-ts`)),supported_surface:H(`codex app-server generators`)}),typescript_root:H(`typescript`),files:W({count:Fj.pipe(QM(),sN()),digest:qR})}),W({path:K.pipe(yM(1)),size:Fj.pipe(QM(),sN()),sha256:qR})})),YR=v((()=>{pP(),DL(),W({owner:H(`holycodex`),schema:K.pipe(CM(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u)),installId:K.pipe(CM(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u))})}));async function XR(e){let t=uz(e.selectedPluginIds);if(t.length===0)return;if(pz(e.timeoutMs,e.pollIntervalMs),e.signal?.aborted)throw new Lz(`cancelled`,`Official Codex marketplace bootstrap was cancelled.`);let n=e.readSnapshot??(t=>iz(t,e.selectedPluginIds)),r=await n(e.codexHome);if(r!==void 0&&dz(r,t))return r;let i=e.initializeRuntime??(()=>fz(e)),a,o;try{a=await i()}catch(e){o=Z(`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.`,e)}if(o===void 0)try{let r=e.timeoutMs??kz,i=e.pollIntervalMs??Az,a=Date.now();for(;Date.now()-a<=r;){if(e.signal?.aborted)throw new Lz(`cancelled`,`Official Codex marketplace bootstrap was cancelled.`);let o=await n(e.codexHome);if(o!==void 0&&dz(o,t))return o;let s=r-(Date.now()-a);if(s<=0)break;await(e.sleep??_z)(Math.min(i,s))}o=Z(`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(e){if(e instanceof Lz&&e.code===`cancelled`)throw e;o=e instanceof Lz?e:Z(`marketplace_unavailable`,`The official Codex marketplace sync failed before its bounded wait completed.`,e)}finally{await a?.()}if(e.gitFallback!==!1)try{return await ZR({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(e){throw e instanceof Lz?e:Z(`marketplace_unavailable`,`The official marketplace could not be populated after runtime startup (${o?.code??`unavailable`}). Check network access and retry.`,e)}throw o??Z(`marketplace_timeout`,`The official Codex marketplace did not become ready before the bounded wait expired.`)}async function ZR(e){let n=uz(e.selectedPluginIds);if(n.length===0)throw Z(`marketplace_invalid`,`The official marketplace fallback requires at least one selected provider plugin.`);if(pz(e.timeoutMs,void 0),!g(e.codexHome))throw Z(`marketplace_invalid`,`The Codex home for official marketplace fallback must be absolute.`);if(e.signal?.aborted)throw new Lz(`cancelled`,`Official Codex marketplace fallback was cancelled.`);let i=AR(e.environment),a=e.gitRunner??Cz(`git`,{environment:i,...e.timeoutMs===void 0?{}:{timeoutMs:e.timeoutMs}}),o=e.timeoutMs??kz,s;try{s=await QR(a,o,e.signal)}catch(e){throw e instanceof Lz?e:Z(`marketplace_unavailable`,`The official Codex marketplace remote HEAD could not be resolved. Check network access and retry.`,e)}let u=_(e.codexHome,`plugins`),d=_(u,Oz[1]);if(await ez(u,e.codexHome),await t(d).catch(e=>{if(!hz(e))throw Z(`marketplace_invalid`,`The reserved official marketplace path could not be inspected safely.`,e)})!==void 0)throw Z(`marketplace_invalid`,`The reserved official marketplace path appeared during bootstrap; refusing to overwrite it.`);let f=await r(_(u,`.openai-plugins-stage-`));try{if(await mz(e.codexHome,f),e.cloneSnapshot!==void 0)try{await e.cloneSnapshot(Dz,f)}catch(e){throw gz(e)?Z(`marketplace_invalid`,`The staged official marketplace could not be created as a safe file tree.`,e):e}else{let t=await a.run([`clone`,`--depth=1`,`--no-tags`,Dz,f],{...e.signal===void 0?{}:{signal:e.signal},timeoutMs:o});if(t.exitCode!==0)throw Z(`marketplace_unavailable`,`The official Codex marketplace could not be downloaded. Check network access and retry.`,t.stderr)}await rz(f);let r=await az(f,e.codexHome,n);if(r===void 0||!dz(r,n))throw Z(`marketplace_invalid`,`The downloaded official marketplace is missing the selected plugin entries or manifest.`);if(await $R(a,f,o,e.signal)!==s)throw Z(`marketplace_invalid`,`The downloaded official marketplace did not match the verified remote HEAD.`);if(await t(d).catch(e=>{if(!hz(e))throw Z(`marketplace_invalid`,`The reserved official marketplace path could not be checked before publication.`,e)})!==void 0)throw Z(`marketplace_invalid`,`The reserved official marketplace path appeared during staging; refusing to overwrite it.`);await c(f,d);let i=await iz(e.codexHome,e.selectedPluginIds);if(i===void 0||!dz(i,n))throw Z(`marketplace_invalid`,`The published official marketplace failed validation.`);return i}catch(e){throw e instanceof Lz?e:Z(`marketplace_unavailable`,`The official Codex marketplace fallback failed safely. Check network access and retry.`,e)}finally{await l(f,{recursive:!0,force:!0}).catch(()=>void 0)}}async function QR(e,t,n){let r=await e.run([`ls-remote`,Dz,`HEAD`],{...n===void 0?{}:{signal:n},timeoutMs:t});if(r.exitCode!==0)throw Z(`marketplace_unavailable`,`The official Codex marketplace remote HEAD could not be resolved. Check network access and retry.`,r.stderr);let i=r.stdout.trim().split(/\r?\n/u).map(e=>e.trim()).filter(e=>e.length>0),a=i.length===1?/^([0-9a-f]{40}|[0-9a-f]{64})\s+HEAD$/iu.exec(i[0]??``):null;if(a?.[1]===void 0)throw Z(`marketplace_invalid`,`The official Codex marketplace remote HEAD response was malformed.`);return a[1].toLowerCase()}async function $R(e,t,n,r){let i=await e.run([`rev-parse`,`HEAD`],{timeoutMs:n,cwd:t,...r===void 0?{}:{signal:r}}),a=i.stdout.trim().toLowerCase();if(i.exitCode!==0||!/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/u.test(a))throw Z(`marketplace_invalid`,`The downloaded official marketplace checkout did not expose a valid HEAD.`,i.stderr);return a}async function ez(e,t){await tz(t,e),await n(e,{recursive:!0}),await tz(t,e)}async function tz(e,n){let r=ne(e),i=ne(n);for(;;){if((await t(i).catch(e=>{if(!hz(e))throw e}))?.isSymbolicLink())throw Z(`marketplace_invalid`,`The official marketplace path cannot contain symlinks.`);if(i===r)return;let e=h(i);if(e===i||e!==r&&!nz(r,e))throw Z(`marketplace_invalid`,`The official marketplace path escaped CODEX_HOME.`);i=e}}function nz(e,t){let n=te(e,t);return n.length>0&&n!==`..`&&!n.startsWith(`..${re}`)&&!g(n)}async function rz(e){let n=await t(e);if(n.isSymbolicLink())throw Z(`marketplace_invalid`,`The official marketplace snapshot cannot contain symlinks.`);if(!n.isDirectory())throw Z(`marketplace_invalid`,`The official marketplace snapshot is not a directory.`);let r=await o(e,{withFileTypes:!0});for(let n of r){let r=_(e,n.name),i=await t(r);if(i.isSymbolicLink())throw Z(`marketplace_invalid`,`The official marketplace snapshot cannot contain symlinks.`);i.isDirectory()&&await rz(r)}}async function iz(e,t=[]){return await az(_(e,...Oz),e,uz(t))}async function az(e,n,r=[]){n!==void 0&&await tz(n,e);let i=await t(e).catch(e=>{if(!hz(e))throw Z(`marketplace_invalid`,`The reserved openai-curated marketplace path could not be read safely.`,e)});if(i===void 0)return;if(i.isSymbolicLink()||!i.isDirectory())throw Z(`marketplace_invalid`,`The reserved openai-curated marketplace path is not a real directory.`);n===void 0?await rz(e):await mz(n,e),n!==void 0&&await rz(e);let o=await s(e),c=[_(o,`.agents`,`plugins`,`marketplace.json`),_(o,`.codex-plugin`,`marketplace.json`),_(o,`marketplace.json`)],l,u;for(let e of c){let n=await t(e).catch(e=>{if(!hz(e))throw Z(`marketplace_invalid`,`The official marketplace manifest could not be read safely.`,e)});if(n!==void 0){if(n.isSymbolicLink()||!n.isFile())throw Z(`marketplace_invalid`,`The official marketplace manifest is not a regular file.`);if(await mz(o,e),l!==void 0)throw Z(`marketplace_invalid`,`The reserved official marketplace contains more than one manifest.`);l=e;try{u=new TextDecoder(`utf-8`,{fatal:!0}).decode(await a(e))}catch(e){throw Z(`marketplace_invalid`,`The official marketplace manifest is not valid UTF-8.`,e)}}}if(l===void 0||u===void 0)return;let d;try{d=JSON.parse(u)}catch(e){throw Z(`marketplace_invalid`,`The official marketplace manifest is not valid JSON.`,e)}return oz(d,o,l,r)}function oz(e,t=`${Oz.join(`/`)}`,n=`${t}/marketplace.json`,r=[]){if(!Y(e)||e.name!==`openai-curated`)throw Z(`marketplace_invalid`,`The reserved official marketplace manifest has an unexpected name.`);sz(e);let i=e.plugins;if(!Array.isArray(i)||i.length===0)throw Z(`marketplace_invalid`,`The official marketplace manifest has no plugin entries.`);let a=[],o=new Set;for(let e of i){if(!Y(e)||typeof e.name!=`string`){if(r.length>0)continue;throw Z(`marketplace_invalid`,`The official marketplace contains a malformed plugin entry.`)}let t=e.name;if(!/^[a-z][a-z0-9._-]{1,63}$/u.test(t)){if(r.length>0)continue;throw Z(`marketplace_invalid`,`The official marketplace contains an invalid plugin name.`)}if(o.has(t)){if(r.length>0&&!r.includes(t))continue;throw Z(`marketplace_invalid`,`The official marketplace contains a duplicate plugin name.`)}if(o.add(t),r.length>0&&!r.includes(t))continue;let n=cz(e);if(!lz(n))throw Z(`marketplace_invalid`,`The official marketplace source for ${t} is unsafe.`);a.push({name:t,source:n})}if(r.some(e=>!a.some(t=>t.name===e)))throw Z(`marketplace_invalid`,`The official marketplace is missing a selected plugin entry.`);return{name:Ez,source:Dz,rootPath:t,manifestPath:n,plugins:a}}function sz(e){for(let t of[`source`,`repository`,`repo`,`url`]){let n=e[t];if(n!==void 0&&(typeof n==`string`?n:Y(n)&&typeof n.url==`string`?n.url:void 0)!==`https://github.com/openai/plugins.git`)throw Z(`marketplace_invalid`,`The reserved official marketplace source is not the approved OpenAI repository.`)}}function cz(e){let t=e.source;if(typeof t==`string`)return t;if(Y(t)&&typeof t.path==`string`)return t.path;if(typeof e.path==`string`)return e.path}function lz(e){if(e===void 0||e.length===0||g(e)||/^[A-Za-z]:[\\/]/u.test(e))return!1;let t=e.replaceAll(`\\`,`/`);return t.startsWith(`/`)||/^[A-Za-z][A-Za-z0-9+.-]*:/u.test(t)?!1:t.split(`/`).every(e=>e.length===0||e===`.`||e!==`..`)}function uz(e){let t=[],n=new Set;for(let r of e){let e=r.lastIndexOf(`@`);if(e<1)continue;let i=r.slice(e+1);if(i!==`openai-curated`&&i!==`openai-curated-remote`)continue;let a=r.slice(0,e);if(!/^[a-z][a-z0-9._-]{1,63}$/u.test(a))throw Z(`marketplace_invalid`,`A selected official marketplace plugin id is invalid.`);yz(a)&&(n.has(a)||(n.add(a),t.push(a)))}return t}function dz(e,t){return t.every(t=>{let n=e.plugins.find(e=>e.name===t);return n!==void 0&&n.source.replaceAll(`\\`,`/`).replace(/\/+$/u,``).split(`/`).at(-1)===t})}async function fz(e){let t=AR(e.environment),n;try{n=new FR({executablePath:e.executablePath,environment:t,...e.signal===void 0?{}:{signal:e.signal}});let r=new OR(n,{requestTimeoutMs:Math.min(e.timeoutMs??kz,1e4),...e.signal===void 0?{}:{signal:e.signal}});return await r.initialize(),async()=>{await r.close()}}catch(e){throw await n?.close().catch(()=>void 0),e}}function pz(e,t){if(e!==void 0&&(!Number.isSafeInteger(e)||e<1||e>3e5))throw Z(`marketplace_invalid`,`The official marketplace timeout is invalid.`);if(t!==void 0&&(!Number.isSafeInteger(t)||t<0||t>6e4))throw Z(`marketplace_invalid`,`The official marketplace poll interval is invalid.`)}async function mz(e,n){let r=await s(e),i=await s(n),a=te(r,i);if(a===``||a===`..`||a.startsWith(`..${re}`))throw Z(`marketplace_invalid`,`The reserved official marketplace is outside CODEX_HOME.`);let o=ne(e),c=ne(n);for(;;){if((await t(c)).isSymbolicLink())throw Z(`marketplace_invalid`,`The reserved official marketplace path cannot contain symlinks.`);if(c===o)break;let e=h(c);if(e===c)throw Z(`marketplace_invalid`,`The reserved official marketplace path is outside CODEX_HOME.`);c=e}}function hz(e){return typeof e==`object`&&!!e&&`code`in e&&e.code===`ENOENT`}function gz(e){return typeof e==`object`&&!!e&&`code`in e&&(e.code===`EPERM`||e.code===`EACCES`)}async function _z(e){await new Promise(t=>setTimeout(t,e))}function Z(e,t,n){return new Lz(e,t,n instanceof Error?{cause:PR(n.message)}:{})}function vz(e,t){let n=vP(t);if(n===void 0||n!==t)return;let r=[...e.installed,...e.available].flatMap(e=>{let t=_P(e.pluginId,e.marketplaceName);return t?.canonicalPluginId===n?[{identity:t,entry:e}]:[]});return r.find(e=>e.entry.pluginId===n&&e.entry.installed)??r.find(e=>e.entry.installed)??r.find(e=>e.entry.pluginId===n)??r[0]}function yz(e){return TP.includes(e)}function bz(e){return PI(Iz,e)?OI(NI(Iz,e,`live official plugin list`)):DI(MI(`live official plugin list`,e))}function xz(e){let t=e.runner??Cz(e.executable,{environment:e.environment??AR(),...e.timeoutMs===void 0?{}:{timeoutMs:e.timeoutMs},...e.stdoutLimit===void 0?{}:{stdoutLimit:e.stdoutLimit},...e.stderrLimit===void 0?{}:{stderrLimit:e.stderrLimit}}),n=async()=>{let e=await t.run([`plugin`,`list`,`--json`]);if(e.exitCode!==0)throw Sz(`list`,e);let n;try{n=JSON.parse(e.stdout)}catch{throw new Lz(`command_failed`,`Codex returned invalid plugin data.`)}let r=bz(n);if(!r.ok)throw new Lz(`command_failed`,`Codex returned an invalid official plugin list.`);return r.value};return{list:n,ensureOfficialMarketplace:async t=>{if(e.codexHome===void 0)throw new Lz(`marketplace_unavailable`,`Codex home is unavailable; the official marketplace cannot be bootstrapped safely.`);await XR({codexHome:e.codexHome,executablePath:e.executable,selectedPluginIds:t,...e.environment===void 0?{}:{environment:e.environment},...e.timeoutMs===void 0?{}:{timeoutMs:e.timeoutMs},...e.officialMarketplaceFallback===void 0?{}:{gitFallback:e.officialMarketplaceFallback}})},addMarketplace:async(e,n)=>{let r=NI(Pz,e,`plugin marketplace source`);if(r===`openai-curated`||r===`https://github.com/openai/plugins.git`)throw new Lz(`marketplace_invalid`,`The reserved openai-curated marketplace must be populated by Codex runtime startup; it cannot be added manually.`);let i=await t.run([`plugin`,`marketplace`,`add`,r],n===void 0?void 0:{signal:n});if(i.exitCode!==0&&!/already (?:exists|added)/iu.test(i.stderr))throw Sz(`marketplace add`,i,r)},add:async(e,r)=>{let i=NI(Pz,e,`official plugin id`),a=await t.run([`plugin`,`add`,i,`--json`],r===void 0?void 0:{signal:r});if(a.exitCode!==0)throw Sz(`add`,a,i);let o=await n(),s=vz(o,i),c=vP(i),l=[...o.installed,...o.available].filter(e=>e.pluginId===i&&(c===void 0||e.marketplaceName==null)),u=s?.entry??l.find(e=>e.installed)??l[0];if(!u)throw new Lz(`readback_mismatch`,`Codex did not report ${i} after installation.`,{plugin_id:i});if(!u.installed)throw new Lz(`plugin_missing`,`Codex reported ${i} as unavailable after installation.`,{plugin_id:i});if(!u.enabled)throw new Lz(`plugin_disabled`,`Codex installed ${i} but it is disabled; enable it in Codex and retry.`,{plugin_id:i})},remove:async(e,r)=>{let i=NI(Pz,e,`official plugin id`),a=i;if(vP(i)===i){let e=vz(await n(),i);e?.entry.installed&&(a=e.entry.pluginId)}let o=await t.run([`plugin`,`remove`,a,`--json`],r===void 0?void 0:{signal:r});if(o.exitCode!==0&&!/not (?:installed|found)|missing/iu.test(o.stderr))throw Sz(`remove`,o,a);let s=await n(),c=[...s.installed,...s.available].find(e=>e.pluginId===a);if(c?.installed)throw new Lz(`readback_mismatch`,`Codex still reports ${i} after removal.`,{plugin_id:i,observed_plugin_id:c.pluginId})}}}function Sz(e,t,n){let r=PR(t.stderr).trim().slice(0,512),i=r.length>0?`: ${r}`:``;return new Lz(`command_failed`,`Codex plugin ${e} failed${n===void 0?``:` for ${n}`}${i}`,{exit_code:t.exitCode})}function Cz(e,t){let n=t.timeoutMs??3e4,r=t.stdoutLimit??131072,i=t.stderrLimit??16384;return{run:(a,o)=>wz(e,a,{...t.environment===void 0?{}:{environment:t.environment},timeoutMs:o?.timeoutMs??n,stdoutLimit:r,stderrLimit:i,...o?.cwd===void 0?{}:{cwd:o.cwd},...o?.signal===void 0?{}:{signal:o.signal}})}}async function wz(e,t,n){if(n.signal?.aborted)throw new Lz(`cancelled`,`The Codex plugin command was cancelled.`);let r=ae(e,[...t],{env:n.environment===void 0?void 0:{...n.environment},...n.cwd===void 0?{}:{cwd:n.cwd},stdio:[`ignore`,`pipe`,`pipe`],windowsHide:!0}),i=Tz(r.stdout,n.stdoutLimit),a=Tz(r.stderr,n.stderrLimit),o=new Promise((e,t)=>{r.once(`error`,t),r.once(`close`,t=>e(t??-1))}),s,c,l=new Promise((e,t)=>{c=()=>{try{r.kill()}catch{}t(new Lz(`cancelled`,`The Codex plugin command was cancelled.`))},n.signal?.addEventListener(`abort`,c,{once:!0})}),u=new Promise((e,t)=>{s=setTimeout(()=>{try{r.kill()}catch{}t(new Lz(`timeout`,`The Codex plugin command timed out.`))},n.timeoutMs)});try{let[e,t,n]=await Promise.race([Promise.all([i,a,o]),l,u]);return{stdout:e,stderr:t,exitCode:n}}catch(e){try{r.kill()}catch{}throw e instanceof Lz?e:new Lz(`command_failed`,`The Codex plugin command failed.`)}finally{s!==void 0&&clearTimeout(s),c!==void 0&&n.signal?.removeEventListener(`abort`,c)}}function Tz(e,t){return e===null?Promise.reject(new Lz(`command_failed`,`Codex plugin command output is unavailable.`)):new Promise((n,r)=>{let i=[],a=0;e.on(`data`,e=>{let n=typeof e==`string`?new TextEncoder().encode(e):e instanceof Uint8Array?e:void 0;if(n===void 0){r(new Lz(`command_failed`,`Codex plugin output was invalid.`));return}if(a+=n.byteLength,a>t){r(new Lz(`output_limit`,`Codex plugin output exceeded its limit.`));return}i.push(n)}),e.once(`end`,()=>{let e=new Uint8Array(a),t=0;for(let n of i)e.set(n,t),t+=n.byteLength;try{n(new TextDecoder(`utf-8`,{fatal:!0}).decode(e))}catch(e){r(e)}}),e.once(`error`,e=>r(e))})}var Ez,Dz,Oz,kz,Az,jz,Mz,Nz,Pz,Fz,Iz,Lz,Rz=v((()=>{uI(),pP(),kR(),zI(),IR(),Ez=`openai-curated`,Dz=`https://github.com/openai/plugins.git`,Oz=[`plugins`,`openai-plugins`],kz=3e4,Az=100,jz=K.pipe(CM(/^[a-z][a-z0-9._-]{1,63}$/u)),Mz=K.pipe(CM(/^[0-9]+\.[0-9]+\.[0-9]+(?:[-+][A-Za-z0-9.-]+)?$/u)),Nz=Vj(K),Pz=K.pipe(CM(/^[A-Za-z0-9][A-Za-z0-9._:@/-]{0,255}$/u)),W({name:jz,version:Mz,description:RI,author:J(II),license:J(RI),homepage:J(RI),repository:J(RI),keywords:J(Nz),skills:J(Nz),commands:J(Nz),hooks:J(Nz),assets:J(Nz),official:J(q)}),W({id:jz,selected:H(!0)}),Fz=W({pluginId:Pz,installed:q,enabled:q,name:J(U(K,Aj)),marketplaceName:J(U(K,Aj)),version:J(U(K,Aj))},oM({key:K,value:Mj})),Iz=W({installed:Vj(Fz),available:Vj(Fz)}),Lz=class extends Error{code;details;constructor(e,t,n={}){super(t),this.name=`OfficialPluginAdapterError`,this.code=e,this.details=n}}})),zz=v((()=>{zI(),KI(),CR(),kR(),IR(),UR(),JR(),YR(),DL(),Rz()}));function Bz(e){if(!Vz(e))throw Error(`The value is not JSON serializable.`);return _F(e),e}function Vz(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{return Array.isArray(e)?e.every(e=>Vz(e,t)):Object.getPrototypeOf(e)===Object.prototype&&Object.values(e).every(e=>Vz(e,t))}finally{t.delete(e)}}var Hz=v((()=>{uI()}));function Uz(e,t){let n=mP(e,t);return tr(n)?n.right:void 0}function Wz(e){return Uz(Gz,e)!==void 0}var Gz,Kz,qz,Jz,Yz,Xz,Zz,Qz,$z,eB,tB,nB,rB,iB,aB,oB,sB,cB,lB,uB,dB,fB,pB=v((()=>{zz(),uI(),lr(),pP(),Hz(),Gz=G(e=>typeof e==`object`&&!!e&&!Array.isArray(e)&&Vz(e)),G(Vz),Kz=K.pipe(CM(/^(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)$/u)),qz=K.pipe(CM(/^[0-9a-f]{64}$/u)),Jz=K.pipe(CM(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u)),Yz=K.pipe(CM(/^[A-Za-z0-9][A-Za-z0-9._:@/-]{0,255}$/u)),Xz=K.pipe(pj(e=>!Number.isNaN(Date.parse(e)))),Zz=W({path:K.pipe(CM(/^[A-Za-z0-9][A-Za-z0-9._/-]{0,255}$/u)),digest:qz}),Qz=W({computer_use:q,work:q,frontend:q,security:q,coding:H(!0)}),$z=W({computer_use:J(q),work:J(q),frontend:J(q),security:J(q)}),eB=W({plan:J(eF),tier:J(nF),optional:J($z),officialPlugins:J(Vj(Yz))}),tB=W({selected:q,status:H(`disabled`,`pending`,`healthy`,`missing`,`provider_disabled`,`uncertain`,`unavailable`),plugin_ids:Vj(Yz),reason:J(K)}),nB=W({computer_use:tB,work:tB,frontend:tB,security:tB}),rB=W({presence:H(`absent`,`present`),digest:qz,safe_value:J(U(W({kind:H(`boolean`),value:q}),W({kind:H(`marketplace`),source_type:H(`git`),source:H(`https://github.com/davidbasilefilho/holycodex.git`)})))}),iB=W({plugin_id:H(`holycodex@holycodex`),before:W({preference:rB,marketplace:rB}),after:W({preference:rB,marketplace:rB})}),aB=W({presence:H(`absent`,`present`),digest:qz,safe_value:J(W({kind:H(`boolean`),value:q}))}),oB=W({plugin_id:Yz,before:aB,after:aB}),sB={owner:H(`holycodex`),schema_epoch:H(pe),install_id:Jz,version:Kz,digest:qz,plan:eF,tier:nF,optional_selections:Qz,explicit_optional_selections:$z,official_plugins:J(Vj(Yz)),capability_state:J(nB),managed_artifacts:Vj(Zz),installed_at:Xz,status:J(H(`active`)),step:J(H(`active`)),managed_config:J(TL),plugin_snapshot:J(Vj(W({plugin_id:Yz,status:H(`installed`,`available`,`missing`,`disabled`,`uncertain`,`unknown`)}))),plugin_config:J(iB),provider_config:J(Vj(oB)),owned_plugins:J(Vj(Yz))},cB=W(sB),lB=W({...sB,plan:U(eF,H(`Go`))}),uB=H(`preparing`,`conflicted`),dB=H(`validated`,`plugins_snapshotted`,`roles_prepared`,`plugins_installed`,`config_published`,`verified`,`conflicted`),fB=W({...cB.fields,status:uB,step:dB})}));function mB(e={},t=process.env){let n=se(),r=hB(e.paths?.codexHome??t.CODEX_HOME??_(n,`.codex`),`CODEX_HOME`),i=_(r,CB);return{codexHome:r,stateRoot:i,activeRecord:_(i,wB),preparingRecord:_(i,TB),conflictedRecord:_(i,EB),roleRoot:_(i,`agents`),configFile:_(r,`config.toml`)}}function hB(e,t,n=process.platform===`win32`?`win32`:`posix`){if(typeof e!=`string`||gB(e))throw new OB(`invalid_path`,`${t} contains invalid characters.`);let r=n===`win32`?ie:ee,i=xB(e,n);if(typeof i!=`string`||i.length===0||!r.isAbsolute(i))throw new OB(`invalid_path`,`${t} must be an absolute path.`);let a=r.normalize(i);if(a.split(n===`win32`?`\\`:re).filter(e=>e.length>0).length===0||a===r.dirname(a))throw new OB(`broad_path`,`${t} is too broad.`);if(i.split(/[\\/]/u).some(e=>e===`..`))throw new OB(`invalid_path`,`${t} cannot contain traversal.`);return r.resolve(a)}function gB(e){for(let t of e){let e=t.codePointAt(0)??0;if(e<=31||e===127)return!0}return!1}async function _B(e){hB(e,`owned path`),await vB(e),await n(e,{recursive:!0}),await vB(e)}async function vB(e){let n=ne(e);for(;;){try{if((await t(n)).isSymbolicLink())throw new OB(`path_symlink`,`A managed path cannot contain a symlink.`)}catch(e){if(e instanceof OB||!SB(e,`ENOENT`))throw e}let e=h(n);if(e===n)break;n=e}}async function yB(e){await vB(e)}function bB(e,t,n=process.platform===`win32`?`win32`:`posix`){let r=n===`win32`?ie:ee,i=r.resolve(xB(e,n)),a=r.resolve(xB(t,n)),o=r.relative(i,a);return o.length>0&&!o.startsWith(`..${n===`win32`?`\\`:re}`)&&o!==`..`&&!r.isAbsolute(o)}function xB(e,t){return t===`win32`&&/^\/[A-Za-z](?:\/|$)/u.test(e)?`${e[1]?.toUpperCase()??``}:${e.slice(2).replaceAll(`/`,`\\`)}`:e}function SB(e,t){return typeof e==`object`&&!!e&&`code`in e&&e.code===t}var CB,wB,TB,EB,DB,OB,kB=v((()=>{uI(),CB=`holycodex`,wB=`active.json`,TB=`preparing.json`,EB=`conflicted.json`,DB=pe,OB=class extends Error{code;constructor(e,t){super(t),this.name=`PathBoundaryError`,this.code=e}}}));async function AB(e){let t;try{t=await i(e,`r`),await t.sync()}catch(e){if(!LB(e))throw e}finally{await t?.close().catch(()=>void 0)}}async function jB(e){await AB(e).catch(e=>{if(!LB(e))throw e})}async function MB(e,t){await NB(e,`${_F(t)}\n`)}async function NB(e,t){let n=h(e);await _B(n),await vB(e);let r=`${e}.tmp-${process.pid}-${crypto.randomUUID()}`;try{await p(r,t,{encoding:`utf8`,mode:384}),await AB(r),await c(r,e),await jB(n)}catch(e){throw await f(r).catch(()=>void 0),e}}async function PB(e,n){let r=await t(e);if(!r.isFile()||r.isSymbolicLink())throw new zB(`state_corrupt`,`A persisted file is not a regular file.`);let i;try{i=JSON.parse(await a(e,`utf8`))}catch(e){throw new zB(`state_corrupt`,`A persisted file is not valid JSON.`,e)}let o=Uz(n,i);if(o===void 0)throw new zB(`state_corrupt`,`A persisted file failed schema validation.`);return o}async function FB(e){try{let n=await t(e);if(!n.isFile()||n.isSymbolicLink())throw new zB(`state_corrupt`,`A persisted file is not a regular file.`);return await a(e,`utf8`)}catch(e){if(SB(e,`ENOENT`))return;throw e}}async function IB(e,t){try{return await PB(e,t)}catch(e){if(SB(e,`ENOENT`))return;throw e}}function LB(e){return typeof e==`object`&&e&&`code`in e&&typeof e.code==`string`?RB.has(e.code)||process.platform===`win32`&&e.code===`EPERM`:!1}var RB,zB,BB=v((()=>{uI(),kB(),pB(),RB=new Set([`EBADF`,`EINVAL`,`ENOSYS`,`ENOTSUP`,`EISDIR`]),zB=class extends Error{code;causeValue;constructor(e,t,n){super(t),this.name=`StorageError`,this.code=e,this.causeValue=n}}}));async function VB(e=JB){let t=JSON.parse(await a(e,`utf8`)),n=Uz(qB,t);if(n===void 0)throw new YB(`manifest_invalid`,`The public package manifest is invalid.`);return n}async function HB(e=JB){return(await VB(e)).version}async function UB(e=JB){return(await HB(e)).split(`-`,1)[0]??``}async function WB(e,t,n=JB){let r=await VB(n),i=await UB(n),a=GB(e,i);return t||await MB(n,{...r,version:a}),{previous:i,next:a}}function GB(e,t){if(e!==`patch`&&e!==`minor`){if(Uz(Kz,e)===void 0)throw new YB(`version_invalid`,`The version target is invalid.`);return e}let n=t.split(`.`),r=Number(n[1]),i=Number(n[2]);return e===`minor`?`0.${r+1}.0`:`0.${r}.${i+1}`}var KB,qB,JB,YB,XB=v((()=>{pP(),pB(),BB(),KB=K.pipe(CM(/^(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)(?:-dev\.[1-9]\d*\.[1-9]\d*)?$/u)),qB=G(e=>Wz(e)&&e.name===`holycodex`&&Uz(KB,e.version)!==void 0),JB=ne(h(oe(import.meta.url)),`../package.json`),YB=class extends Error{code;constructor(e,t){super(t),this.name=`ManifestError`,this.code=e}}}));function ZB(e,t=`standard`){let n=eI(e);return n.ok?n.value.routes.map(e=>{let n={role:e.role,task:e.task};return{name:ZP(n),rolePolicy:rF.find(t=>t.role===e.role),description:$P(n),taskInstruction:QP(n),model:`gpt-5.6-luna`,effort:e.effort,serviceTier:t===`standard`?`default`:`fast`}}):[]}function QB(e,t=`standard`){let n=eI(e);if(!n.ok)throw Error(`Unknown plan.`);return{name:`root`,description:`Root-directed HolyCodex control agent.`,model:n.value.root.model===`Terra`?`gpt-5.6-terra`:`gpt-5.6-sol`,effort:n.value.root.effort,serviceTier:t===`fast-all`?`fast`:`default`}}function $B(e=!1){let t=[`You are the HolyCodex Root orchestrator.`,`Own user intent and scope; architecture, product, policy, and material choices; integration; external state and effects; Git/VCS; contradictory-evidence resolution; and final readiness.`,`Proceed autonomously with safe local inspection, implementation, and proportional verification inside approved scope. Use request_user_input for genuinely required information or approval, including material scope or product choices and destructive, remote, or externally consequential effects.`,`Delegate substantive specialist work when it has a bounded scope and observable completion. Apply writing-for-agents before dispatch; keep routine Root-owned inspection, synthesis, and coordination local.`,`Inspect returned evidence before integration. Use planning and review gates when architecture, scope, coordination, risk, or material choices justify them, including an adversarial Reviewer.code fixed-point gate for substantive implementation where appropriate.`];return e&&t.push(`Interactive GUI, browser, and Computer Use execution is Root-only and must not be delegated.`),t.join(`
82
- `)}async function eV(e,t,n=[],r=`standard`){let i=_(e,`holycodex`,`agents`),a=[],o=[],s=ZB(t,r).map(e=>({path:_(i,`${e.name}.toml`),contents:rV(e)})),c=new Map(n.map(t=>[_(e,t.path),t])),l=new Map;for(let e of s){let t=await cV(e.path);l.set(e.path,t);let n=c.get(e.path);if(t!==void 0&&n===void 0&&t!==e.contents)throw Error(`A pre-existing HolyCodex role file is not owned by this installation: ${e.path}`)}let u=[];try{for(let t of s){let n=l.get(t.path),r=c.get(t.path);if(n!==void 0&&r!==void 0&&await uV(n)!==r.digest&&n!==t.contents){a.push(t.path),u.push({path:te(e,t.path).replaceAll(`\\`,`/`),digest:r.digest});continue}(n===void 0||n!==t.contents)&&(await NB(t.path,t.contents),o.push({path:t.path,previous:n,installedDigest:await uV(t.contents)})),u.push({path:te(e,t.path).replaceAll(`\\`,`/`),digest:await uV(t.contents)})}let t=_(e,`agents`,`root.toml`),r=await cV(t),i=await sV(t);i===`preserved`&&a.push(t),i===`removed`&&r!==void 0&&o.push({path:t,previous:r,installedDigest:void 0});for(let t of n){let n=_(e,t.path);if(!s.some(e=>e.path===n)){if(!oV(e,n,t.path)){a.push(n);continue}let r=await lV(n,t.digest);r.status===`preserved`?a.push(n):r.previous!==void 0&&o.push({path:n,previous:r.previous,installedDigest:void 0})}}for(let t of n){let n=_(e,t.path);a.includes(n)&&!u.some(t=>_(e,t.path)===n)&&u.push(t)}return{managed_artifacts:u,preserved:a,rollback:o}}catch(e){throw await tV(o).catch(()=>void 0),e}}async function tV(e){let t=[],n=[];for(let r of[...e].reverse()){let e=await cV(r.path);if(!(r.installedDigest===void 0?e===void 0:e!==void 0&&await uV(e)===r.installedDigest)){n.push(r.path);continue}r.previous===void 0?(await l(r.path,{force:!1}).catch(e=>{if(!SB(e,`ENOENT`))throw e}),t.push(r.path)):await NB(r.path,r.previous)}return{removed:t,preserved:n}}async function nV(e,n){let r=[],i=[],o=_(e,`agents`),s=_(e,`holycodex`,`agents`);for(let c of n){let n=_(e,c.path);if(!bB(e,n)||!bB(o,n)&&!bB(s,n)&&n!==_(e,`config.toml`)){i.push(n);continue}try{await vB(n);let e=await t(n);if(e.isSymbolicLink()||!e.isFile()){i.push(n);continue}if(await uV(await a(n))!==c.digest){i.push(n);continue}await l(n,{force:!1}),r.push(n)}catch(e){SB(e,`ENOENT`)?r.push(n):i.push(n)}}let c=_(e,`agents`,`root.toml`),u=await sV(c);return u===`removed`&&r.push(c),u===`preserved`&&i.push(c),{removed:r,preserved:i}}function rV(e){let t=e.rolePolicy,n=[`${t.role} shared policy: ${t.authority}`,t.evidence,t.completion,e.taskInstruction].join(`
83
- `);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(t.permissions.write?`workspace-write`:`read-only`)}`,`approval_policy = "never"`,`web_search = ${JSON.stringify(t.permissions.network?`live`:`disabled`)}`,`developer_instructions = ${JSON.stringify(n)}`,``,`[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(`
84
- `)}function iV(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_verbosity = "low"`,``].join(`
85
- `)}function aV(e){return dV.has(e)}function oV(e,t,n){return n===`agents/root.toml`||/^holycodex\/agents\/(?:explorer|librarian|worker|reviewer)\.toml$/u.test(n)?!0:bB(_(e,`agents`),t)&&/^(?:Explorer|Librarian|Worker|Reviewer)\.(?:lookup|trace|research|mechanical|implementation|integration|operations|plan|code|artifact)\.toml$/u.test(n.slice(7))}async function sV(e){try{await vB(e);let n=await t(e);return!n.isFile()||n.isSymbolicLink()||!aV(await a(e,`utf8`))?`preserved`:(await l(e,{force:!1}),`removed`)}catch(e){if(SB(e,`ENOENT`))return`absent`;throw e}}async function cV(e){try{await vB(e);let n=await t(e);if(n.isSymbolicLink()||!n.isFile())throw Error(`Invalid managed path: ${e}`);return new TextDecoder(`utf-8`,{fatal:!0}).decode(await a(e))}catch(e){if(SB(e,`ENOENT`))return;throw e}}async function lV(e,n){try{await vB(e);let r=await t(e);if(r.isSymbolicLink()||!r.isFile())return{status:`preserved`};let i=new TextDecoder(`utf-8`,{fatal:!0}).decode(await a(e));return await uV(i)===n?(await l(e,{force:!1}),{status:`removed`,previous:i}):{status:`preserved`}}catch(e){if(SB(e,`ENOENT`))return{status:`removed`};throw e}}async function uV(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),e=>e.toString(16).padStart(2,`0`)).join(``)}var dV,fV=v((()=>{uI(),kB(),BB(),dV=new Set([`go`,`plus-low`,`plus`,`plus-high`,`pro-5x`,`pro-20x`].flatMap(e=>[`standard`,`fast`,`fast-all`].map(t=>iV(QB(e,t)))))}));function pV(e,t,n){if(t instanceof hV)return t;let r=(t instanceof Lz?t:void 0)?.code,i=r===`timeout`||r===`output_limit`||r===`cancelled`||r===`readback_mismatch`||r===`plugin_disabled`||r===`plugin_missing`||r===`marketplace_invalid`||r===`marketplace_timeout`||r===`marketplace_unavailable`?r:r===`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 hV(i,a,t,n===void 0?{}:{plugin_id:n})}var mV,hV,gV=v((()=>{zz(),uI(),mV=class e{adapter;observedIdentities={};constructor(e){if(`run`in e){let t=xz({executable:`codex`,runner:e});this.adapter=t}else this.adapter=e}static async discover(t=process.env){let n=xz({executable:(await BR({environment:t})).path,environment:jR(t),...t.CODEX_HOME===void 0?{}:{codexHome:t.CODEX_HOME}});return new e(n)}async list(){try{return await this.adapter.list()}catch(e){throw pV(`list`,e)}}async add(e){try{await this.adapter.add(e)}catch(t){throw pV(`add`,t,e)}}async ensureOfficialMarketplace(e){if(this.adapter.ensureOfficialMarketplace!==void 0)try{await this.adapter.ensureOfficialMarketplace(e)}catch(e){throw pV(`bootstrap`,e)}}async remove(e){try{await this.adapter.remove(e)}catch(t){throw pV(`remove`,t,e)}}async addMarketplace(e){try{await this.adapter.addMarketplace(e)}catch(t){throw pV(`add`,t,e)}}async status(e){let t=await this.list(),n={},r=new Map;for(let e of[...t.installed,...t.available])(!r.has(e.pluginId)||e.installed)&&r.set(e.pluginId,e);let i=Object.fromEntries(e.map(e=>{let i=vz(t,e),a=vP(e),o=r.get(e),s=i?.entry??(a===void 0||o?.marketplaceName==null?o:void 0);return s!==void 0&&(n[e]=i?.entry.pluginId??s.pluginId),[e,s===void 0?`missing`:s.installed&&s.enabled?`installed`:s.installed?`disabled`:`missing`]}));return this.observedIdentities=Object.freeze(n),i}getObservedIdentities(){return this.observedIdentities}},hV=class 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 _V(e){let t={},n=[];for(let r of e.split(/\r?\n/u)){let e=EV(r).trim();if(e.length===0)continue;if(e.startsWith(`[[`)||e.endsWith(`]]`))throw Error(`Array-of-tables are not supported by the validated fallback.`);if(e.startsWith(`[`)&&e.endsWith(`]`)){n=xV(e.slice(1,-1).trim()),CV(t,n);continue}let i=TV(e);if(i<1)throw Error(`TOML assignment is invalid.`);let a=xV(e.slice(0,i).trim()),o=bV(e.slice(i+1).trim());SV(t,[...n,...a],o)}return t}function vV(e){let t=[];return yV(e,[],t),t.join(`
86
- `)}function yV(e,t,n){let r=[],i=[];for(let[t,n]of Object.entries(e))DV(n)?i.push([t,n]):r.push([t,n]);t.length>0&&(n.length>0&&n.push(``),n.push(`[${t.map(OV).join(`.`)}]`));for(let[e,t]of r)n.push(`${OV(e)} = ${kV(t)}`);for(let[e,r]of i)yV(r,[...t,e],n)}function bV(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?[]:wV(t,`,`).map(bV)}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 e of wV(t,`,`)){let t=TV(e);if(t<1)throw Error(`TOML inline table entry is invalid.`);SV(n,xV(e.slice(0,t).trim()),bV(e.slice(t+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 xV(e){let t=wV(e,`.`).map(e=>e.trim());if(t.length===0||t.some(e=>!/^(?:[A-Za-z0-9_-]+|"(?:[^"\\]|\\.)*"|'[^']*')$/u.test(e)||e===`__proto__`||e===`constructor`||e===`prototype`))throw Error(`TOML key is invalid.`);return t.map(e=>e.startsWith(`"`)||e.startsWith(`'`)?bV(e):e)}function SV(e,t,n){if(t.length===0)throw Error(`TOML key is missing.`);let r=e;for(let e of t.slice(0,-1)){let t=r[e];if(t===void 0){let t={};r[e]=t,r=t}else if(DV(t))r=t;else throw Error(`TOML key conflicts with a scalar.`)}let i=t.at(-1);if(Object.prototype.hasOwnProperty.call(r,i))throw Error(`TOML key is duplicated.`);r[i]=n}function CV(e,t){let n=e;for(let e of t){let t=n[e];if(t===void 0){let t={};n[e]=t,n=t}else if(DV(t))n=t;else throw Error(`TOML table conflicts with a scalar.`)}}function wV(e,t){let n=[],r=0,i=0,a,o=!1;for(let s=0;s<e.length;s+=1){let c=e[s];if(a!==void 0){a===`"`&&o?o=!1:a===`"`&&c===`\\`?o=!0:c===a&&(a=void 0);continue}c===`"`||c===`'`?a=c:c===`[`||c===`{`?i+=1:c===`]`||c===`}`?--i:c===t&&i===0&&(n.push(e.slice(r,s)),r=s+1)}if(a!==void 0||i!==0)throw Error(`TOML value is unbalanced.`);return n.push(e.slice(r)),n}function TV(e){let t,n=!1,r=0;for(let i=0;i<e.length;i+=1){let a=e[i];if(t!==void 0)t===`"`&&n?n=!1:t===`"`&&a===`\\`?n=!0:a===t&&(t=void 0);else if(a===`"`||a===`'`)t=a;else if(a===`[`||a===`{`)r+=1;else if(a===`]`||a===`}`)--r;else if(a===`=`&&r===0)return i}return-1}function EV(e){let t,n=!1;for(let r=0;r<e.length;r+=1){let i=e[r];if(t!==void 0)t===`"`&&n?n=!1:t===`"`&&i===`\\`?n=!0:i===t&&(t=void 0);else if(i===`"`||i===`'`)t=i;else if(i===`#`)return e.slice(0,r)}return e}function DV(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function OV(e){return/^[A-Za-z0-9_-]+$/u.test(e)?e:JSON.stringify(e)}function kV(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(kV).join(`, `)}]`;throw Error(e===null?`TOML null is not serializable.`:`TOML nested values must be tables.`)}var AV=v((()=>{})),jV=le({doctorHolyCodex:()=>MV,removeHolyCodex:()=>NV});async function MV(e={},t=process.env){let n=mB(e,t),r={};try{await yB(n.codexHome),await yB(n.stateRoot),r.paths=zV({state_root:n.stateRoot})}catch(e){r.paths=BV([`path_symlink`],{error:HV(e)})}let[i,a,o]=await Promise.all([GV(n).catch(e=>{r.configuration=BV([`state_corrupt`],{error:HV(e)})}),IB(n.preparingRecord,fB).catch(e=>{r.transaction=BV([`state_corrupt`],{path:n.preparingRecord,error:HV(e)})}),IB(n.conflictedRecord,fB).catch(e=>{r.transaction=BV([`state_corrupt`],{path:n.conflictedRecord,error:HV(e)})})]);if(a!==void 0&&r.transaction?.status!==`failed`&&(r.transaction=BV([`incomplete_install_state`])),o!==void 0&&r.transaction?.status!==`failed`&&(r.transaction=BV([`conflicted_state`])),r.configuration||=i?await OH(i)?zV({plan:i.plan,tier:i.tier,install_id:i.install_id}):BV([`configuration_changed`],{path:n.activeRecord}):BV([`configuration_missing`]),i){r.runtime_config=await PV(n,i),r.native_roles=await FV(n,i.plan,i.tier);let e=Object.entries(i.capability_state??{}).find(([,e])=>e.selected&&e.status!==`healthy`);e&&(r.capabilities=BV([`selected_capability_not_healthy`],{capability:e[0],status:e[1].status}))}try{let e=await FB(`${n.codexHome}/agents/root.toml`);if(e!==void 0&&aV(e)){let e=r.native_roles;r.native_roles={status:`failed`,reasons:[...e?.reasons??[],`stale_legacy_root`],details:{...e?.details,path:`${n.codexHome}/agents/root.toml`}}}}catch(e){r.native_roles=BV([`native_role_invalid`],{error:HV(e)})}let s=e.officialPluginManager??await mV.discover({...t,CODEX_HOME:n.codexHome}).catch(()=>void 0);if(i&&s?.status){let e=[...new Set([MH,...SP({computer_use:i.optional_selections.computer_use,work:i.optional_selections.work,frontend:i.optional_selections.frontend,security:i.optional_selections.security},i.official_plugins),...i.owned_plugins??[]])];try{let t=await s.status(e),n=Object.entries(t).filter(([,e])=>e!==`installed`).map(([e])=>e),i=s.getObservedIdentities?.()??{};r.native_plugins=n.length===0?zV({status:t,observed_identities:i}):BV([`native_plugin_disagreement`],{missing:n,status:t,observed_identities:i})}catch(e){r.native_plugins=BV([`native_plugin_status_failed`],{error:HV(e)})}}else r.native_plugins={status:`unsupported`,reasons:[`native_plugin_manager_unavailable`],details:{}};let c=Object.values(r).flatMap(e=>e.reasons);return{healthy:Object.values(r).every(e=>e.status!==`failed`),checks:r,reasons:[...new Set(c)]}}async function NV(e={},t=process.env){let n=mB(e,t);await yB(n.codexHome),await yB(n.stateRoot);let r=await GV(n),[i,a]=await Promise.all([IB(n.preparingRecord,fB),IB(n.conflictedRecord,fB)]),o=a??i??r,s=new Set(RV(o)),c=[],d=[],f=[];if(r&&!await OH(r))return d.push(n.activeRecord),f.push(`configuration_changed`),{removed:c,preserved:d,reasons:f};let p=await FB(n.configFile),m=qV(p);if(o?.managed_config){let e=await xL(m,o.managed_config,{schema:o.managed_config.schema,installId:o.managed_config.installId});if(e.preservedKeys.length>0||e.unresolvedKeys.length>0)return d.push(n.configFile),f.push(`managed_config_changed`),await IV(n,o),{removed:c,preserved:d,reasons:f}}if(o?.plugin_config&&(await ZV(m,o.plugin_config)).preserved.length>0)return d.push(n.configFile),f.push(`plugin_config_changed`),await IV(n,o),{removed:c,preserved:d,reasons:f};if(o?.provider_config&&(await QV(m,o.provider_config,s)).preserved.length>0)return d.push(n.configFile),f.push(`provider_config_changed`),await IV(n,o),{removed:c,preserved:d,reasons:f};let h;try{h=e.officialPluginManager??await mV.discover({...t,CODEX_HOME:n.codexHome})}catch(e){throw new Q(`capability_denied`,`Native Codex plugin removal is unavailable.`,e,{recovery:`Install or expose Codex, then retry.`})}if(h===void 0||!h.remove||!h.list)throw new Q(`capability_denied`,`Native Codex plugin removal and readback are unavailable.`);let g=await nV(n.codexHome,o?.managed_artifacts??[]);c.push(...g.removed),d.push(...g.preserved),g.preserved.length>0&&f.push(`managed_artifact_changed`);for(let e of s)try{let t=vz(await h.list(),e),n=t?.entry.installed?t.entry.pluginId:e;await h.remove(n);let r=await h.list();if(vz(r,e)?.entry?.installed===!0||[...r.installed,...r.available].some(t=>t.pluginId===e&&t.installed))throw new Q(`capability_denied`,`Codex still reports ${e} after removal.`);c.push(e)}catch(t){throw f.push(`native_plugin_remove_failed`),await IV(n,o??LV()),new Q(`capability_denied`,`Codex native plugin removal did not converge for ${e}: ${HV(t)}`,t)}if(g.preserved.length>0)return await IV(n,o??LV()),{removed:c,preserved:d,reasons:f};let _;try{let e=qV(await FB(n.configFile)),t=o?.managed_config;if(t){let r=await xL(e,t,{schema:t.schema,installId:t.installId});if(r.preservedKeys.length>0||r.unresolvedKeys.length>0)return d.push(n.configFile),f.push(`managed_config_changed`),await IV(n,o??LV()),{removed:c,preserved:d,reasons:f};e=r.document,t=r.state}if(o?.plugin_config){let t=await ZV(e,o.plugin_config,{allowBeforeState:!0});if(t.preserved.length>0)return d.push(n.configFile),f.push(`plugin_config_changed`),await IV(n,o),{removed:c,preserved:d,reasons:f};e=t.document}if(o?.provider_config){let t=await QV(e,o.provider_config,s,{allowBeforeState:!0});if(t.preserved.length>0)return d.push(n.configFile),f.push(`provider_config_changed`),await IV(n,o),{removed:c,preserved:d,reasons:f};e=t.document}(o?.managed_config||o?.plugin_config||o?.provider_config)&&(_=t===void 0?{document:e}:{document:e,state:t}),_!==void 0&&(Object.keys(_.document).length===0&&p===void 0?await l(n.configFile,{force:!1}):await NB(n.configFile,JV(_.document)))}catch(e){if(e instanceof Q)throw await IV(n,o??LV()),e;return d.push(n.configFile),f.push(`managed_config_write_failed`),await IV(n,o??LV()),{removed:c,preserved:d,reasons:f}}if(r)try{await l(n.activeRecord,{force:!1}),c.push(n.activeRecord)}catch(e){if(SB(e,`ENOENT`))c.push(n.activeRecord);else return d.push(n.activeRecord),f.push(`state_remove_failed`),await IV(n,o??r),{removed:c,preserved:d,reasons:f}}if(d.length===0){for(let[e,t]of[[n.preparingRecord,i!==void 0],[n.conflictedRecord,a!==void 0]])if(t)try{await VV(e),c.push(e)}catch{d.push(e),f.push(`state_remove_failed`)}}if(d.length===0)try{await u(n.roleRoot),c.push(n.roleRoot)}catch(e){SB(e,`ENOENT`)||(d.push(n.roleRoot),f.push(`role_directory_not_empty`))}if(d.length===0)try{await u(n.stateRoot),c.push(n.stateRoot)}catch(e){SB(e,`ENOENT`)?c.push(n.stateRoot):(d.push(n.stateRoot),f.push(`state_directory_not_empty`))}return{removed:c,preserved:d,reasons:f}}async function PV(e,t){if(!t.managed_config)return BV([`incomplete_install_state`]);try{let n=qV(await FB(e.configFile)),r=oH(t.plan,t.tier,t.optional_selections.computer_use),i=[];for(let[e,a]of Object.entries(r))((await SL(n,t.managed_config,e)).status!==`unchanged`||e!==`developer_instructions`&&ZI(n,e)!==a)&&i.push(e);return i.length===0?zV({managed_keys:Object.keys(r).length}):BV([`changed_holycodex_config`],{keys:i})}catch(e){return BV([`config_unreadable`],{error:HV(e)})}}async function FV(e,t,n){try{let r=qV(await FB(e.configFile)),i=[];for(let a of ZB(t,n)){let t=ZI(r,`agents."${a.name}".config_file`),o=`${e.roleRoot}/${a.name}.toml`.replaceAll(`\\`,`/`);if(typeof t!=`string`||hL(e.configFile,t).replaceAll(`\\`,`/`)!==o){i.push(`${a.name}:registration`);continue}let s=await FB(`${e.roleRoot}/${a.name}.toml`);if(s===void 0){i.push(`${a.name}:missing`);continue}if(s!==rV(a)){i.push(`${a.name}:changed`);continue}let c=qV(s);(c.name!==a.name||typeof c.description!=`string`||typeof c.developer_instructions!=`string`||c.model!==`gpt-5.6-luna`||c.model_reasoning_summary!==`none`||c.model_verbosity!==`low`||c.tool_output_token_limit!==void 0||c.service_tier!==(n===`standard`?`default`:`fast`)||c.sandbox_mode!==(a.rolePolicy.permissions.write?`workspace-write`:`read-only`)||c.approval_policy!==`never`||c.web_search!==(a.rolePolicy.permissions.network?`live`:`disabled`)||ZI(c,`agents.enabled`)!==!1||ZI(c,`features.multi_agent_v2`)!==!1||ZI(c,`features.multi_agent`)!==!1||ZI(c,`features.computer_use`)!==!1||ZI(c,`features.browser_use`)!==!1||ZI(c,`features.in_app_browser`)!==!1)&&i.push(`${a.name}:malformed`)}let a=await FB(`${e.codexHome}/agents/root.toml`);return a!==void 0&&aV(a)&&i.push(`root:stale`),i.length===0?zV({role_root:e.roleRoot,agent_types:ZB(t,n).map(e=>e.name)}):BV([`native_role_disagreement`],{roles:i})}catch(e){return BV([`native_role_invalid`],{error:HV(e)})}}async function IV(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??[]};Uz(fB,n)!==void 0&&await MB(e.conflictedRecord,Bz(n))}function LV(){return{owner:`holycodex`,schema_epoch:`state-0.16`,install_id:`remove-conflict`,version:`0.0.0`,digest:`0`.repeat(64),plan:`plus`,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 RV(e){if(e?.owned_plugins!==void 0)return[...new Set(e.owned_plugins)];let t=(e?.plugin_snapshot??[]).filter(e=>e.plugin_id!==`holycodex@holycodex`&&e.status!==`installed`).map(e=>e.plugin_id);return[...new Set([MH,...t])]}function zV(e){return{status:`healthy`,reasons:[],details:e}}function BV(e,t={}){return{status:`failed`,reasons:e,details:t}}async function VV(e){await l(e,{force:!1}).catch(e=>{if(!SB(e,`ENOENT`))throw e})}function HV(e){return e instanceof Error?e.message.slice(0,256):`operation failed`}var UV=v((()=>{zz(),uI(),LH(),Hz(),fV(),gV(),kB(),pB(),BB()}));async function WV(e={},t={},n=process.env){if(Uz(eB,e)===void 0)throw new Q(`install_failed`,`The installation options are invalid.`);let r=mB(t,n);await _B(r.stateRoot);let i=await IB(r.preparingRecord,fB),a=await IB(r.conflictedRecord,fB)??i;if(a!==void 0){let{removeHolyCodex:r}=await Promise.resolve().then(()=>(UV(),jV)),i=await r(t,n);if(i.preserved.length>0||i.reasons.length>0)throw new Q(`state_corrupt`,`The interrupted HolyCodex installation could not be reconciled safely.`,void 0,{preserved:i.preserved.join(`,`),reasons:i.reasons.join(`,`)});return await WV({plan:e.plan??a.plan,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??vH(a)},t,n)}let o=await GV(r);if(o!==void 0&&!await OH(o))throw new Q(`state_corrupt`,`The existing HolyCodex configuration has changed and cannot be replaced.`,void 0,{path:r.activeRecord});let s=CH(e.plan,o?.plan),c=wH(e.tier,o?.tier),l=TH(e.optional,o?.optional_selections),u=gH(o?.explicit_optional_selections,e.optional),d=e.officialPlugins??vH(o),f=[...new Set(SP(KV(l),d).map(e=>vP(e)??e))],p;try{p=t.officialPluginManager??await mV.discover({...n,CODEX_HOME:r.codexHome})}catch(e){throw new Q(`capability_denied`,`Native Codex plugin installation is unavailable.`,e,{recovery:`Install or expose Codex, then retry.`})}if(!p.addMarketplace||!p.add||!p.list)throw new Q(`install_failed`,`Native Codex plugin installation and verification are unavailable.`);let m;try{m=await p.list()}catch(e){throw new Q(`capability_denied`,`Native Codex plugin state could not be read safely.`,e)}let h=f.filter(e=>{if(vP(e)!==e)return!1;let t=SH(m,e);return!(t?.installed&&t.enabled)});if(p.ensureOfficialMarketplace!==void 0&&h.length>0)try{await p.ensureOfficialMarketplace(h)}catch(e){throw new Q(`capability_denied`,`The selected official Codex provider marketplace is unavailable: ${AH(e)}`,e,{recovery:`Check Codex network and marketplace policy, then retry.`})}let g=o?.install_id??crypto.randomUUID().replaceAll(`-`,``),_=await UB(),ee=(t.now?.()??new Date).toISOString(),te=await FB(r.configFile),ne=qV(te),re=o?.plugin_config?.before??await YV(ne),ie=[...new Set([...f,...(o?.provider_config??[]).map(e=>e.plugin_id),...o?.owned_plugins??[]])].filter(e=>e!==MH),ae=(await XV(ne,ie)).map(e=>{let t=o?.provider_config?.find(t=>t.plugin_id===e.plugin_id);return t===void 0?e:{plugin_id:e.plugin_id,before:t.before,after:t.before}}),oe=await cH(ne,o?.managed_config??fL({schema:`state-0.16`,installId:g}),o),se=oe.document,ce=oe.state;lH(se,ce);let v=oH(s,c,l.computer_use),le=await bL(se,ce,v,{schema:pe,installId:g});if(le.driftedKeys.length>0)throw new Q(`state_corrupt`,`HolyCodex-owned Codex settings changed and cannot be replaced safely.`,void 0,{keys:le.driftedKeys.join(`,`)});let ue;try{ue=await uH({list:()=>p.list()},[...new Set([MH,...f,...o?.owned_plugins??[]])])}catch(e){throw new Q(`capability_denied`,`Native Codex plugin state could not be read safely.`,e)}let de={owner:`holycodex`,schema_epoch:pe,install_id:g,version:_,digest:o?.digest??`0`.repeat(64),plan:s,tier:c,optional_selections:l,explicit_optional_selections:u,official_plugins:f,capability_state:EH(l),managed_artifacts:o?.managed_artifacts??[],installed_at:ee,status:`preparing`,step:`validated`,managed_config:le.state,plugin_snapshot:ue,plugin_config:{plugin_id:MH,before:re,after:re},provider_config:ae,owned_plugins:[...new Set(o?.owned_plugins??[])]};await dH(r.preparingRecord,de);let fe,me=!1,he=new Set,ge=new Set(o?.owned_plugins??[]),_e=new Set,y=de,ve=!1,b=!1,ye=te,x=le.state;try{await _B(r.roleRoot),fe=await eV(r.codexHome,s,o?.managed_artifacts,c),y={...de,step:`roles_prepared`,managed_artifacts:fe.managed_artifacts},await dH(r.preparingRecord,y),ve=!0,await p.addMarketplace(jH),await yH({list:()=>p.list(),add:e=>p.add(e)},[MH,...f],(e,t)=>{t===`new`?(he.add(e),ge.add(e),y={...y,owned_plugins:[...ge]}):(_e.add(e),ge.add(e),y={...y,owned_plugins:[...ge]})}),y={...y,step:`plugins_installed`},await dH(r.preparingRecord,y);let e=await FB(r.configFile);ye=e;let t=qV(e),n=await YV(t),i=(await XV(t,ie)).map(e=>({plugin_id:e.plugin_id,before:ae.find(t=>t.plugin_id===e.plugin_id)?.before??e.before,after:e.before}));await sH(t,se,ce,v);let a=await bL(t,ce,v,{schema:pe,installId:g});if(a.driftedKeys.length>0)throw new Q(`state_corrupt`,`HolyCodex-owned Codex settings changed during native plugin setup.`,void 0,{keys:a.driftedKeys.join(`,`)});b=!0,x=a.state,y={...y,managed_config:x,plugin_config:{plugin_id:MH,before:re,after:n},provider_config:i},await NB(r.configFile,JV(a.document)),me=!0,y={...y,step:`config_published`},await dH(r.preparingRecord,y),await mH(r,s,c,l.computer_use,x,fe.preserved);let d=EH(l),m=await DH({owner:`holycodex`,install_id:g,version:_,plan:s,tier:c,optional_selections:l,explicit_optional_selections:u,official_plugins:f,capability_state:d,managed_artifacts:fe.managed_artifacts,managed_config:x,plugin_config:{plugin_id:MH,before:re,after:n},provider_config:i,plugin_snapshot:ue,owned_plugins:[...ge]}),h={owner:`holycodex`,schema_epoch:pe,install_id:g,version:_,digest:m,plan:s,tier:c,optional_selections:l,explicit_optional_selections:u,official_plugins:f,capability_state:d,managed_artifacts:fe.managed_artifacts,installed_at:ee,status:`active`,step:`active`,managed_config:x,plugin_snapshot:ue,plugin_config:{plugin_id:MH,before:re,after:n},provider_config:i,owned_plugins:[...ge]};if(Uz(cB,h)===void 0)throw new Q(`state_corrupt`,`The HolyCodex configuration is invalid.`);return await MB(r.activeRecord,Bz(h)),await fH(r.preparingRecord),await fH(r.conflictedRecord),{record:h,optional_plugins:f,preserved:fe.preserved,warnings:fe.preserved.length===0?[]:[`modified managed files were preserved`]}}catch(e){let t=[];if(me)try{await pH(r.configFile,ye)}catch{t.push(`config`)}if(ve&&!b&&await FB(r.configFile).catch(()=>void 0)!==ye&&t.push(`config`),fe!==void 0)try{(await tV(fe.rollback)).preserved.length>0&&t.push(`roles`)}catch{t.push(`roles`)}_e.size>0&&t.push(...[..._e].map(e=>`plugin:${e}`));for(let e of he)try{await p.remove?.(e)}catch{t.push(`plugin:${e}`)}throw t.length>0?await dH(r.conflictedRecord,{...y,step:`conflicted`,status:`conflicted`}).catch(()=>void 0):await fH(r.preparingRecord).catch(()=>void 0),e instanceof OB||e instanceof Q?e:new Q(e instanceof hV||e instanceof IH?`capability_denied`:`install_failed`,AH(e),e,t.length>0?{recovery:`Resolve conflicted state before retrying.`}:{})}}async function GV(e){let t=await IB(e.activeRecord,Gz);if(t===void 0)return;let n=Uz(cB,t);if(n!==void 0)return n;let r=Uz(lB,t);if(r===void 0)throw new Q(`state_corrupt`,`The HolyCodex configuration is invalid.`);if(!await kH(r))throw new Q(`state_corrupt`,`The existing HolyCodex configuration has an invalid digest.`,void 0,{path:e.activeRecord});let i=KP(r.plan);return{...r,plan:i,digest:await DH({owner:r.owner,install_id:r.install_id,version:r.version,plan: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}})}}function KV(e){return{computer_use:e.computer_use,work:e.work,frontend:e.frontend,security:e.security}}function qV(e){if(e===void 0||e.trim().length===0)return{};try{let t=globalThis.Bun,n=t?.TOML?.parse?t.TOML.parse(e):_V(e),r=Uz(CL,n);if(r===void 0)throw Error(`TOML document contains unsupported values.`);return r}catch(e){throw new Q(`state_corrupt`,`The Codex config.toml is not valid TOML.`,e)}}function JV(e){try{let t=globalThis.Bun;return`${(t?.TOML?.stringify?t.TOML.stringify(e):vV(e)).trimEnd()}\n`}catch(e){throw new Q(`install_failed`,`The merged Codex configuration is not writable.`,e)}}async function YV(e){return{preference:await $V(e,`plugins`,PH),marketplace:await $V(e,`marketplaces`,FH)}}async function XV(e,t){return await Promise.all(t.map(async t=>{let n=await $V(e,`plugins`,t),r={presence:n.presence,digest:n.digest,...n.safe_value?.kind===`boolean`?{safe_value:n.safe_value}:{}};return{plugin_id:t,before:r,after:r}}))}async function ZV(e,t,n={}){let r=e,i=[],a=[],o=[];for(let[s,c,l]of[[`preference`,`plugins`,PH],[`marketplace`,`marketplaces`,FH]]){let u=t.before[s],d=t.after[s],f=await $V(e,c,l);if(n.allowBeforeState!==!0||f.digest!==u.digest){if(f.digest!==d.digest){o.push(s);continue}if(u.presence===`absent`){f.presence===`present`&&(r=iH(r,c,l),a.push(s));continue}if(u.safe_value===void 0){o.push(s);continue}r=rH(r,c,l,nH(u.safe_value)),i.push(s)}}return{document:r,restored:i,removed:a,preserved:o}}async function QV(e,t,n,r={}){let i=e,a=[],o=[],s=[];for(let c of t){if(!n.has(c.plugin_id))continue;let t=c.before,l=c.after,u=await $V(e,`plugins`,c.plugin_id);if(r.allowBeforeState!==!0||u.digest!==t.digest){if(u.digest!==l.digest){s.push(c.plugin_id);continue}if(t.presence===`absent`){u.presence===`present`&&(i=iH(i,`plugins`,c.plugin_id),o.push(c.plugin_id));continue}if(t.safe_value===void 0){s.push(c.plugin_id);continue}i=rH(i,`plugins`,c.plugin_id,{enabled:t.safe_value.value}),a.push(c.plugin_id)}}return{document:i,restored:a,removed:o,preserved:s}}async function $V(e,t,n){let r=eH(e,t,n),i=await xF(`holycodex-plugin-config`,[vF(Bz({key:`${t}.${n}`,value:r===void 0?{presence:`absent`}:r}))]),a=tH(t,r);return{presence:r===void 0?`absent`:`present`,digest:i,...a===void 0?{}:{safe_value:a}}}function eH(e,t,n){let r=e[t];if(aH(r))return r[n]}function tH(e,t){if(!aH(t))return;let n=Object.keys(t);if(e===`plugins`)return n.length!==1||n[0]!==`enabled`||typeof t.enabled!=`boolean`?void 0:{kind:`boolean`,value:t.enabled};if(!(n.length!==2||!n.includes(`source_type`)||!n.includes(`source`)||t.source_type!==`git`||t.source!==NH))return{kind:`marketplace`,source_type:`git`,source:NH}}function nH(e){return e.kind===`boolean`?{enabled:e.value}:{source_type:e.source_type,source:e.source}}function rH(e,t,n,r){let i={...e},a=i[t];if(a!==void 0&&!aH(a))throw new Q(`state_corrupt`,`The ${t} Codex config table is invalid.`);return i[t]={...a,[n]:r},i}function iH(e,t,n){let r=e[t];if(!aH(r)||!Object.prototype.hasOwnProperty.call(r,n))return e;let i={...e},a={...r};return delete a[n],Object.keys(a).length===0?delete i[t]:i[t]=a,i}function aH(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function oH(e,t,n=!1){let r=QB(e,t),i={model:r.model,model_reasoning_effort:r.effort,service_tier:r.serviceTier,model_verbosity:`low`,developer_instructions:$B(n),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 e of pF)i[`agents."${e}".config_file`]=`holycodex/agents/${e}.toml`;return i}async function sH(e,t,n,r){let i=[];for(let a of Object.keys(r)){let r=a;if(n.managed[r]!==void 0){(await SL(e,n,r)).status===`drifted`&&i.push(r);continue}ZI(t,r)!==ZI(e,r)&&i.push(r)}if(i.length>0)throw new Q(`state_corrupt`,`Codex settings changed during native plugin setup.`,void 0,{keys:i.join(`,`)})}async function cH(e,t,n){let r=[`agents.explorer.config_file`,`agents.librarian.config_file`,`agents.worker.config_file`,`agents.reviewer.config_file`],i=Object.fromEntries(r.flatMap(e=>{let n=t.managed[e];return n===void 0?[]:[[e,n]]})),a=e,o=t;if(Object.keys(i).length>0){let n=await xL(e,{...t,managed:i},{schema:t.schema,installId:t.installId});if(n.preservedKeys.length>0||n.unresolvedKeys.length>0)throw new Q(`state_corrupt`,`Legacy HolyCodex agent registrations changed and cannot be migrated safely.`,void 0,{keys:[...new Set([...n.preservedKeys,...n.unresolvedKeys])].join(`,`)});a=n.document,o={...t,managed:Object.fromEntries(Object.entries(t.managed).filter(([e])=>!r.includes(e)))}}if(!n)return{document:a,state:o};let s=n.managed_artifacts.map(e=>e.path);for(let e of[`explorer`,`librarian`,`worker`,`reviewer`]){if(!s.some(t=>t.startsWith(`agents/${e[0]?.toUpperCase()}${e.slice(1)}.`)||t===`holycodex/agents/${e}.toml`))continue;let t=`agents.${e}.config_file`,n=ZI(a,t);if(typeof n!=`string`)continue;let r=n.replaceAll(`\\`,`/`).replace(/^\.\//u,``);(r===`agents/${e}.toml`||r===`holycodex/agents/${e}.toml`)&&(a=tL(a,t))}return{document:a,state:o}}function lH(e,t){if(ZI(e,`developer_instructions`)!==void 0&&t.managed.developer_instructions===void 0)throw new Q(`state_corrupt`,`Existing developer_instructions cannot be displaced safely; remove it or converge managed state first.`)}async function uH(e,t){let n=await e.list();return t.map(e=>{let t=SH(n,e);return{plugin_id:e,status:t===void 0?`missing`:t.installed&&t.enabled?`installed`:t.installed?`disabled`:`available`}})}async function dH(e,t){if(Uz(fB,t)===void 0)throw new Q(`state_corrupt`,`The HolyCodex transaction state is invalid.`);await MB(e,Bz(t))}async function fH(e){await l(e,{force:!1}).catch(e=>{if(!SB(e,`ENOENT`))throw e})}async function pH(e,t){if(t===void 0){await l(e,{force:!1}).catch(e=>{if(!SB(e,`ENOENT`))throw e});return}await NB(e,t)}async function mH(e,t,n,r,i,a=[]){let o=qV(await FB(e.configFile)),s=oH(t,n,r);for(let[e,t]of Object.entries(s)){let n=ZI(o,e);if(e===`developer_instructions`){if(typeof n!=`string`||await hH(e,n)!==i.managed[e]?.lastManagedValue.value)throw new Q(`install_failed`,`The effective Root instructions did not converge.`)}else if(n!==t)throw new Q(`install_failed`,`The effective Codex setting ${e} did not converge.`)}let c=ZB(t,n);for(let t of c){let n=ZI(o,`agents."${t.name}".config_file`);if(typeof n!=`string`)throw new Q(`install_failed`,`The ${t.name} registration is missing.`);let r=_(e.roleRoot,`${t.name}.toml`),i=r.replaceAll(`\\`,`/`);if(hL(e.configFile,n).replaceAll(`\\`,`/`)!==i)throw new Q(`install_failed`,`The ${t.name} registration is stale.`);let s=await FB(r);if(s===void 0)throw new Q(`install_failed`,`The ${t.name} role file is missing.`);if(a.includes(r))continue;let c=qV(s);if(c.name!==t.name||typeof c.description!=`string`||typeof c.model!=`string`||typeof c.model_reasoning_effort!=`string`||typeof c.service_tier!=`string`||typeof c.developer_instructions!=`string`||c.sandbox_mode!==(t.rolePolicy.permissions.write?`workspace-write`:`read-only`)||c.approval_policy!==`never`||c.web_search!==(t.rolePolicy.permissions.network?`live`:`disabled`)||c.tool_output_token_limit!==void 0||ZI(c,`agents.enabled`)!==!1||ZI(c,`features.multi_agent_v2`)!==!1||ZI(c,`features.multi_agent`)!==!1||ZI(c,`features.computer_use`)!==!1||ZI(c,`features.browser_use`)!==!1||ZI(c,`features.in_app_browser`)!==!1)throw new Q(`install_failed`,`The ${t.name} role file is malformed.`)}let l=await FB(`${e.codexHome}/agents/root.toml`);if(l!==void 0&&aV(l))throw new Q(`install_failed`,`A stale HolyCodex Root role remains installed.`)}async function hH(e,t){return await xF(`holycodex-managed-config-value`,[vF({keyPath:e,value:t})])}function gH(e,t){let n={};for(let r of[`computer_use`,`work`,`frontend`,`security`]){let i=t?.[r]??e?.[r];i!==void 0&&(n[r]=i)}return n}function _H(e){return[`computer_use`,`work`,`frontend`,`security`].find(t=>OP[t].pluginIds.includes(e))}function vH(e){return(e?.official_plugins??[]).filter(t=>{let n=_H(t);return n===void 0||e?.optional_selections[n]!==!0})}async function yH(e,t,n){for(let r of t){let t;try{t=SH(await e.list(),r)}catch(e){throw xH(`list`,e,r)}if(t?.installed&&!t.enabled)throw new IH(`uncertain`,`${r} is disabled`);let i=!(t?.installed&&t.enabled);if(!(t?.installed&&t.enabled))try{await e.add(r)}catch(i){try{let i=SH(await e.list(),r);bH(t,i)||n?.(r,`uncertain`)}catch{n?.(r,`uncertain`)}throw xH(`add`,i,r)}let a;try{a=SH(await e.list(),r)}catch(e){throw i&&n?.(r,`uncertain`),xH(`list`,e,r)}if(!a?.installed)throw i&&!bH(t,a)&&n?.(r,`uncertain`),new IH(`missing`,`${r} is not installed after add`);if(i&&a.enabled&&n?.(r,`new`),!a.enabled)throw i&&n?.(r,`new`),new IH(`uncertain`,`${r} is disabled after add`)}}function bH(e,t){return e?.pluginId===t?.pluginId&&e?.installed===t?.installed&&e?.enabled===t?.enabled&&e?.marketplaceName===t?.marketplaceName}function xH(e,t,n){return t instanceof hV?t:new hV(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 SH(e,t){let n=vz(e,t);if(n!==void 0)return n.entry;let r=vP(t);return[...e.installed,...e.available].find(e=>e.pluginId===t&&(r===void 0||e.marketplaceName==null))}function CH(e,t){let n=e??t??`plus`;if(!eI(n).ok)throw new Q(`install_failed`,`Unknown plan.`);return n}function wH(e,t){let n=e??t??`standard`;if(Uz(nF,n)===void 0)throw new Q(`install_failed`,`The tier is not supported.`);return n}function TH(e,t){let n=xP(e,t?KV(t):AP);return{computer_use:n.computer_use,work:n.work,frontend:n.frontend,security:n.security,coding:!0}}function EH(e,t=new Map){return Object.fromEntries([`computer_use`,`work`,`frontend`,`security`].map(n=>{let r=e[n];return[n,{selected:r,status:r?t.get(n)??`healthy`:`disabled`,plugin_ids:[...OP[n].pluginIds]}]}))}async function DH(e){return await xF(`install-record`,[vF(Bz(e))])}async function OH(e){return await kH(e)}async function kH(e){return await DH({owner:e.owner,install_id:e.install_id,version:e.version,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 AH(e){return e instanceof Error?e.message.slice(0,256):`operation failed`}var jH,MH,NH,PH,FH,IH,Q,LH=v((()=>{zz(),uI(),Hz(),XB(),fV(),gV(),kB(),pB(),BB(),AV(),jH=`davidbasilefilho/holycodex`,MH=`holycodex@holycodex`,NH=`https://github.com/davidbasilefilho/holycodex.git`,PH=`holycodex@holycodex`,FH=`holycodex`,IH=class extends Error{status;constructor(e,t){super(t),this.name=`PluginVerificationError`,this.status=e}},Q=class extends Error{code;causeValue;details;constructor(e,t,n,r={}){super(t),this.name=`InstallerError`,this.code=e,this.causeValue=n,this.details=r}}}));uI(),LH(),Hz(),UV(),XB(),gV(),kB(),BB();async function RH(e,t={}){if(xI(e)||e[0]===`help`){let t=e[0]===`help`?e.slice(1).filter(e=>!e.startsWith(`-`))[0]:SI(e);return{envelope:XH(t===void 0?`help`:`${t} help`,{help:yI(t)}),exitCode:0}}let n;try{n=hI(e);let r=await zH(n,t);return{envelope:XH(n.command,r),exitCode:QH(n.command,r)}}catch(t){return ZH(n?.command??eU(e),t)}}async function zH(e,t){switch(e.command){case`install`:return Bz(await BH(e,t));case`doctor`:return Bz(await MV(YH(e,t),t.env));case`remove`:return Bz(await VH(e,t));case`version`:return Bz(await HH(e,t));case`help`:return{help:yI(e.positionals[0])};default:throw new yU(`invalid_argument`,`Unknown command.`)}}async function BH(e,t){let n=e.options.json===!0;if(!await UH(e,t,`Install HolyCodex into the selected Codex home?`))throw new yU(`non_tty_confirmation_required`,`Install requires --yes in non-interactive mode.`);rU(t,n,`Validating Codex target`),rU(t,n,`Installing HolyCodex`),rU(t,n,`Installing selected capabilities`),rU(t,n,`Configuring Root`),rU(t,n,`Installing subagent roles`);let r=await WV({...KH(e)===void 0?{}:{plan:KH(e)},...qH(e)===void 0?{}:{tier:qH(e)},...GH(e)===void 0?{}:{optional:GH(e)},...JH(e,`add-plugin`).length===0?{}:{officialPlugins:JH(e,`add-plugin`)}},YH(e,t),t.env);return rU(t,n,`Verifying installation`),rU(t,n,`HolyCodex installation complete`),r}async function VH(e,t){let n=e.options.json===!0;if(!await UH(e,t,`Remove HolyCodex-owned Codex state?`))throw new yU(`non_tty_confirmation_required`,`Remove requires --yes in non-interactive mode.`);rU(t,n,`Validating HolyCodex ownership`);let r=await NV(YH(e,t),t.env);return rU(t,n,`Removing HolyCodex-owned state`),rU(t,n,`HolyCodex removal complete`),r}async function HH(e,t){let n=e.positionals[0];return n?await WB(n,e.options[`dry-run`]===!0):{version:await HB()}}async function UH(e,t,n){return e.options.yes===!0?!0:e.options.json===!0||t.io?.stdoutIsTTY!==!0?!1:await WH(t,n)}async function WH(e,t){return e.io?.confirm?await e.io.confirm(t):!1}function GH(e){let t={};for(let n of[`computer_use`,`work`,`frontend`,`security`]){let r=n.replaceAll(`_`,`-`);e.options[r]===!0?t[n]=!0:(e.options[r]===!1||e.options[`no-${r}`]===!0)&&(t[n]=!1)}return Object.keys(t).length===0?void 0:t}function KH(e){let t=e.options.plan;if(typeof t!=`string`)return;let n=eI(t);return n.ok?n.value.name:void 0}function qH(e){let t=e.options.tier;return t===`standard`||t===`fast`||t===`fast-all`?t:void 0}function JH(e,t){let n=e.options[t];return Array.isArray(n)?n.filter(e=>typeof e==`string`):[]}function YH(e,t){let n=t.installer??{},r=e.options[`codex-home`];return typeof r==`string`?{...n,paths:{...n.paths,codexHome:r},...t.now?{now:t.now}:{}}:{...n,...t.now?{now:t.now}:{}}}function XH(e,t){let n=TF({schema_version:fe,ok:!0,command:e,data:t,warnings:[]});if(!n.ok)throw new yU(`internal_error`,`The success envelope failed validation.`);return n.value}function ZH(e,t){let n=$H(t),r=TF({schema_version:fe,ok:!1,command:e,error:{code:n.code,message:n.message,details:n.details},warnings:[]});return r.ok?{envelope:r.value,exitCode:n.exitCode}:{envelope:{schema_version:fe,ok:!1,command:`internal-error`,error:{code:`internal_error`,message:`The CLI failure envelope was invalid.`,details:{}},warnings:[]},exitCode:5}}function QH(e,t){return e===`doctor`&&nU(t)&&t.healthy===!1?4:0}function $H(e){if(e instanceof mI)return{code:e.code,message:tU(e.message),details:e.details,exitCode:1};if(e instanceof yU)return{code:e.code,message:tU(e.message),details:{},exitCode:e.code===`internal_error`?5:1};if(e instanceof OB)return{code:`trust_boundary_failed`,message:tU(e.message),details:{},exitCode:4};if(e instanceof Q){let t=e.code===`capability_denied`?2:e.code===`state_corrupt`?4:3;return{code:e.code,message:tU(e.message),details:e.details,exitCode:t}}if(e instanceof hV){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:tU(e.message),details:e.details,exitCode:t?4:n?2:3}}return e instanceof zB?{code:e.code,message:tU(e.message),details:{},exitCode:4}:e instanceof YB?{code:e.code,message:tU(e.message),details:{},exitCode:1}:(e instanceof Error,{code:`internal_error`,message:`The command failed unexpectedly.`,details:{},exitCode:5})}function eU(e){return e.find(e=>!e.startsWith(`-`))??`unknown`}function tU(e){return Array.from(e).map(e=>{let t=e.codePointAt(0)??0;return t<=31||t===127?` `:e}).join(``).replace(/\s+/gu,` `).trim().slice(0,512)}function nU(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function rU(e,t,n){t||e.io?.stderrIsTTY===!1||e.io?.writeStderr?.(`${aU(n,{stderrIsTTY:e.io?.stderrIsTTY,env:e.env})}\n`)}function iU(e,t={}){let n=CI(t);if(e.envelope.ok)return e.envelope.command===`version`?oU(e.envelope.data):e.envelope.command===`install`?sU(e.envelope.data,n):e.envelope.command===`remove`?cU(e.envelope.data,n):e.envelope.command===`doctor`?lU(e.envelope.data,n):`${$(`✔`,`green`,n)} ${$(e.envelope.command,`heading`,n)}\n${hU(e.envelope.data,n)}`;let r=e.envelope.error,i=vU(r.code,e.envelope.command);return[`${$(`✖`,`red`,n)} ${$(e.envelope.command,`heading`,n)}`,` ${$(r.code,`red`,n)}: ${r.message}`,...gU(r.details,n),...i===void 0?[]:[` hint: ${i}`],``].join(`
87
- `)}function aU(e,t={}){return`${$(`•`,`cyan`,CI({...t,stream:`stderr`}))} ${e}`}function oU(e){if(nU(e)&&typeof e.version==`string`)return`holycodex ${e.version}\n`;if(nU(e)&&typeof e.next==`string`){let t=typeof e.previous==`string`?` (from ${e.previous})`:``;return`holycodex version updated to ${e.next}${t}\n`}return`holycodex version completed
88
- `}function sU(e,t){let n=uU(e,`record`),r=fU(n,`version`)??`unknown`,i=fU(n,`plan`)??`unknown`,a=fU(n,`tier`)??`unknown`,o=uU(n,`optional_selections`),s=uU(n,`capability_state`),c=[`frontend`,`security`,`work`,`computer_use`].filter(e=>o?.[e]===!0).map(e=>{let t=fU(uU(s,e),`status`);return t===void 0||t===`healthy`?e:`${e} (${t})`}),l=pU(e,`preserved`),u=pU(e,`warnings`),d=c.length===0?`none`:c.join(`, `),f=l.length===0?`none`:`${l.length} managed item${l.length===1?``:`s`} (review before retrying)`;return`${[`${$(`✔`,`green`,t)} ${$(`install`,`heading`,t)}`,` ${$(`version`,`option`,t)}: ${r}`,` ${$(`plan`,`option`,t)}: ${i}`,` ${$(`tier`,`option`,t)}: ${a}`,` ${$(`capabilities`,`option`,t)}: ${d}`,` ${$(`preserved`,`option`,t)}: ${f}`,...u.map(e=>` ${$(`warning`,`red`,t)}: ${mU(e)}`)].join(`
89
- `)}\n`}function cU(e,t){let n=pU(e,`removed`),r=pU(e,`preserved`),i=pU(e,`reasons`),a=r.length===0?`none`:`${r.length} item${r.length===1?``:`s`} (review before retrying)`;return`${[`${$(`✔`,`green`,t)} ${$(`remove`,`heading`,t)}`,` ${$(`removed`,`option`,t)}: ${n.length} owned item${n.length===1?``:`s`}`,` ${$(`preserved`,`option`,t)}: ${a}`,...i.map(e=>` ${$(`reason`,`option`,t)}: ${mU(e)}`)].join(`
90
- `)}\n`}function lU(e,t){let n=dU(e,`healthy`)===!0,r=uU(e,`checks`),i=r===void 0?[]:Object.entries(r),a=i.flatMap(([e,n])=>{let r=nU(n)?n:void 0,i=fU(r,`status`);if(i===void 0||i===`healthy`)return[];let a=pU(r,`reasons`);return[` ${$(e,`option`,t)}: ${a.length===0?i:a.map(mU).join(`, `)}`]});return`${[`${n?$(`✔`,`green`,t):$(`✖`,`red`,t)} ${$(`doctor`,`heading`,t)}`,` ${$(`status`,`option`,t)}: ${n?`healthy`:`needs attention`}`,` ${$(`checks`,`option`,t)}: ${i.length}`,...a.length===0?[]:[` ${$(`issues`,`option`,t)}:`,...a]].join(`
91
- `)}\n`}function uU(e,t){if(nU(e))return nU(e[t])?e[t]:void 0}function dU(e,t){return nU(e)?e[t]:void 0}function fU(e,t){let n=e?.[t];return typeof n==`string`?n:void 0}function pU(e,t){return!nU(e)||!Array.isArray(e[t])?[]:e[t]}function mU(e){return typeof e==`string`?e.replaceAll(`_`,` `):`operation requires review`}function hU(e,t){if(typeof e!=`object`||!e||Array.isArray(e))return` ${$(_U(e),`dim`,t)}\n`;let n=Object.entries(e);if(n.length===0)return``;let r=Math.max(...n.map(([e])=>e.length));return`${n.map(([e,n])=>` ${$(e.padEnd(r),`option`,t)}: ${_U(n)}`).join(`
92
- `)}\n`}function gU(e,t){return Object.entries(e).map(([e,n])=>` ${$(e,`option`,t)}: ${$(_U(n),`dim`,t)}`)}function _U(e){return typeof e==`string`?e:e===null||typeof e==`number`||typeof e==`boolean`?String(e):JSON.stringify(e)}function vU(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"}function $(e,t,n){return n?`\u001b[${{red:`31`,green:`32`,cyan:`36`,dim:`2`,heading:`1`,option:`36`}[t]}m${e}\u001b[0m`:e}var yU=class extends Error{code;constructor(e,t){super(t),this.name=`CliCommandError`,this.code=e}};async function bU(e=Bun.argv.slice(2),t=xU()){let n={env:process.env,cwd:process.cwd(),io:{stdin:t.stdin??CU(),stdoutIsTTY:t.stdoutIsTTY??process.stdout.isTTY===!0,stderrIsTTY:t.stderrIsTTY??process.stderr.isTTY===!0,...t.confirm===void 0?{}:{confirm:t.confirm},writeStdout:t.writeStdout,writeStderr:t.writeStderr}},r=await RH(e,n);return(xI(e)||e[0]===`help`)&&!SU(e)?n.io?.writeStdout?.(bI(SI(e),{stdoutIsTTY:n.io?.stdoutIsTTY,stderrIsTTY:n.io?.stderrIsTTY,env:n.env,stream:`stdout`})):SU(e)?n.io?.writeStdout?.(`${JSON.stringify(r.envelope)}\n`):r.envelope.ok?n.io?.writeStdout?.(iU(r,{stdoutIsTTY:n.io?.stdoutIsTTY,stderrIsTTY:n.io?.stderrIsTTY,env:n.env,stream:`stdout`})):n.io?.writeStderr?.(iU(r,{stdoutIsTTY:n.io?.stderrIsTTY,stderrIsTTY:n.io?.stderrIsTTY,env:n.env,stream:`stderr`})),r.exitCode}function xU(){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 t=>{let n=e({input:process.stdin,output:process.stderr});try{let e=await n.question(`${t} [y/N] `);return/^(?:y|yes)$/iu.test(e.trim())}finally{n.close()}}}}function SU(e){let t=!1;for(let n of e)n===`--json`||n===`--json=true`?t=!0:n===`--json=false`&&(t=!1);return t}async function*CU(){let e=new TextDecoder;for await(let t of process.stdin)typeof t==`string`?yield t:yield e.decode(t,{stream:!0});let t=e.decode();t.length>0&&(yield t)}LH(),UV(),XB(),kB(),gV(),fV(),pB();const wU=`holycodex`;import.meta.main&&(process.exitCode=await bU());export{mI as ArgumentError,tB as CapabilityInstallStateSchema,nB as CapabilityStateRecordSchema,mV as CodexOfficialPluginManager,cB as InstallRecordSchema,eB as InstallRequestSchema,Q as InstallerError,hV as OfficialPluginManagerError,OB as PathBoundaryError,DB as STATE_SCHEMA,hB as assertRootText,MV as doctorHolyCodex,zH as executeCommand,xI as helpRequested,yI as helpText,SI as helpTopic,WV as installHolyCodex,eV as installNativeAgents,DH as installRecordDigest,wU as packageName,hI as parseArgv,bB as pathWithin,ZB as projectNativeAgents,QB as projectRootAgent,JB as publicManifestPath,GV as readActiveInstallRecord,UB as readCanonicalBaseVersion,HB as readCanonicalVersion,NV as removeHolyCodex,nV as removeManagedNativeAgents,bI as renderHelp,iU as renderHuman,rV as renderNativeAgent,aU as renderProgress,mB as resolveInstallerPaths,tV as rollbackNativeAgentInstall,bU as runBinary,RH as runCli,WB as updateCanonicalVersion};
111
+ `;function il(e){switch(e){case"install":return dH;case"remove":return fH;case"doctor":return mH;case"upgrade":return hH;case"version":return gH;default:return pH}}function oS(e,t={}){let n=Gd({...t,stream:"stdout"});return il(e).split(`
112
+ `).map((r)=>{if(r==="HolyCodex")return Jd(r,"heading",n);if(/^(?:Usage|Options|Profiles control routing only|Tier is independent service handling|Capability defaults).*:$/u.test(r))return Jd(r,"heading",n);return r.replace(/--[a-z][a-z0-9-]*/gu,(o)=>Jd(o,"option",n)).replace(/<[^>]+>/gu,(o)=>Jd(o,"argument",n))}).join(`
113
+ `)}function al(e){return e.some((t)=>t==="-h"||t==="--help"||t==="--help=true")}function sl(e){let t=e.filter((n)=>!n.startsWith("-"));if(t[0]==="help")return t[1];if(t[0]==="--version"||t[0]==="version"||t[0]==="-v")return"version";return t[0]}function Gd(e){let t=e.env??{};if(t.NO_COLOR!==void 0||t.TERM==="dumb")return!1;if(t.FORCE_COLOR!==void 0&&t.FORCE_COLOR!=="0")return!0;if(t.CI!==void 0&&t.CI!=="false")return!1;return(e.stream==="stderr"?e.stderrIsTTY:e.stdoutIsTTY)===!0}function Jd(e,t,n){if(!n)return e;return`\x1B[${{heading:"1",option:"36",argument:"2"}[t]}m${e}\x1B[0m`}ut();ql();var Pj=["low","default","high"],Ij=["standard","fast","fast-all"],Wn=["work","frontend","security","computer_use"];async function M_(e={}){let t=wr(e),n=await import("@opentui/core"),r=$I(t),o=await n.createCliRenderer({exitOnCtrlC:!0,clearOnShutdown:!0}),i=new n.TextRenderable(o,{content:UI(r,0)});return o.root.add(i),await new Promise((a,s)=>{let c=0,l=!1,u=0,p=!1,f=(S)=>{if(p)return;p=!0,o.keyInput.off("keypress",w),o.destroy(),a(S)},h=(S)=>{if(p)return;p=!0,o.keyInput.off("keypress",w),o.destroy(),s(S)},m=()=>{i.content=l?BI(r,u):UI(r,c),o.requestRender()},w=(S)=>{try{let y=S.name.toLowerCase();if(y==="escape"||S.ctrl===!0&&y==="c"){f({action:"cancel"});return}if(l){if(y==="up"||y==="k")u=(u+2)%3;else if(y==="down"||y==="j")u=(u+1)%3;else if(y==="return"||y==="enter"||y==="linefeed"){if(u===0)f({action:"install",request:HI(r)});else if(u===1)l=!1,c=0;else f({action:"cancel"});return}m();return}if(c===Wn.length+2){if(y==="backspace")r.pluginInput=r.pluginInput.slice(0,-1);else if(y==="space")r.pluginInput+=" ";else if(y==="return"||y==="enter"||y==="linefeed")r.plugins=VI(r.pluginInput),l=!0,u=0;else if(!S.ctrl&&!S.meta&&S.name.length===1&&!Lj(S.name))r.pluginInput+=S.name;m();return}if(y==="up"||y==="k")c=Math.max(0,c-1);else if(y==="down"||y==="j")c=Math.min(Wn.length+2,c+1);else if(y==="space"&&c>=2)jI(r,c-2);else if(y==="left"||y==="h")DI(r,c,-1);else if(y==="right"||y==="l")DI(r,c,1);else if(y==="return"||y==="enter"||y==="linefeed"){if(c<Wn.length+2)c+=1}if(c===Wn.length+2)r.pluginInput=r.plugins.join(" ");m()}catch(y){h(y)}};o.keyInput.on("keypress",w);try{o.start()}catch(S){h(S)}})}function HI(e){let t=e.plugins.length>0?{profile:e.profile,tier:e.tier,optional:{...e.optional},officialPlugins:[...e.plugins]}:{profile:e.profile,tier:e.tier,optional:{...e.optional}};return wr(t)}function Mj(e,t="install"){let n=$I(wr(e));return BI(n,t==="install"?0:t==="change"?1:2)}function $I(e){let t={...ur,...e.optional};return{profile:e.profile??"default",tier:e.tier??"standard",optional:{computer_use:t.computer_use??ur.computer_use,work:t.work??ur.work,frontend:t.frontend??ur.frontend,security:t.security??ur.security},plugins:[...e.officialPlugins??[]],pluginInput:(e.officialPlugins??[]).join(" ")}}function DI(e,t,n){if(t===0)e.profile=qI(Pj,e.profile,n);else if(t===1)e.tier=qI(Ij,e.tier,n);else if(t>=2&&t<Wn.length+2)jI(e,t-2)}function jI(e,t){let n=Wn[t];if(n!==void 0)e.optional[n]=!e.optional[n]}function qI(e,t,n){let r=e.indexOf(t);return e[(r+n+e.length)%e.length]??e[0]}function VI(e){let t=[...new Set(e.split(/\s+/u).map((n)=>n.trim()).filter(Boolean))];if(t.length===0)return[];return wr({officialPlugins:t}),t}function UI(e,t){let n=t<2?t===0?"Choose the routing profile for the Root session.":"Choose how quickly services handle work.":t<Wn.length+2?Nj(Wn[t-2]):"Optional plugin IDs separated by spaces. Enter continues to review.";return`${["HolyCodex \xB7 install","\u2191/\u2193 move \u2190/\u2192 change Space toggle Enter review Esc cancel","","PROFILE",`${t===0?"\u276F":" "} Profile ${e.profile}`,`${t===1?"\u276F":" "} Service tier ${e.tier}`,"","OPTIONAL CAPABILITIES",...Wn.map((o,i)=>`${t===i+2?"\u276F":" "} ${zI(o).padEnd(14)} ${e.optional[o]?"[x] enabled":"[ ] disabled"}`),"","ADDITIONAL PLUGINS",...KI(`${t===Wn.length+2?"\u276F":" "} ${e.pluginInput||"(none)"}`),"",n].join(`
114
+ `)}
115
+ `}function BI(e,t){let n=["Install","Change options / Redo","Cancel"];return`${["HolyCodex \xB7 review","Review configuration","\u2191/\u2193 choose Enter confirm Esc cancel","",`Profile: ${e.profile}`,`Service tier: ${e.tier}`,"","CAPABILITIES",...Wn.map((o)=>` ${zI(o)}: ${Fj(e.optional[o])}`),...KI(` Additional plugins: ${e.plugins.length===0?"none":e.plugins.join(" ")}`),"",...n.map((o,i)=>`${i===t?"\u203A":" "} ${o}`)].join(`
116
+ `)}
117
+ `}function Nj(e){switch(e){case"work":return"Work plugins for documents, spreadsheets, and presentations.";case"frontend":return"Frontend tools for building and testing web experiences.";case"security":return"Security review and vulnerability analysis tools.";case"computer_use":return"Computer Use tools for interactive GUI and browser tasks."}}function KI(e,t=76){if(e.length<=t)return[e];let n=[],r=e;while(r.length>t){let o=r.lastIndexOf(" ",t),i=o>0?o:t;n.push(r.slice(0,i)),r=r.slice(o>0?i+1:i)}if(r.length>0)n.push(r);return n}function zI(e){return e==="computer_use"?"Computer Use":`${e[0].toUpperCase()}${e.slice(1)}`}function Fj(e){return e?"enabled":"disabled"}function Lj(e){let t=e.codePointAt(0)??0;return t<=31||t===127}ql();Ol();Af();Il();Nl();Vi();cs();async function F_(e,t={}){if(al(e)||e[0]==="help"){let r=e[0]==="help"?e.slice(1).filter((o)=>!o.startsWith("-"))[0]:sl(e);return{envelope:WI(r===void 0?"help":`${r} help`,{help:il(r)}),exitCode:0}}let n;try{n=Wd(e);let r=await JI(n,t);return{envelope:WI(n.command,r),exitCode:Gj(n.command,r)}}catch(r){return Jj(n?.command??Zj(e),r)}}async function JI(e,t){switch(e.command){case"install":return Zt(await Dj(e,t));case"doctor":return Zt(await k_(Mf(e,t),t.env));case"remove":return Zt(await Hj(e,t));case"upgrade":return Zt(await $j(e,t));case"version":return Zt(await jj(e,t));case"help":return{help:il(e.positionals[0])};default:throw new Ji("invalid_argument","Unknown command.")}}async function Dj(e,t){let n=Uj(e),r=await qj(e,t,n);if("cancelled"in r)return r;return await fs(r,Mf(e,t),t.env)}async function qj(e,t,n){if(e.options.json!==!0&&e.options.yes!==!0&&t.io?.stdoutIsTTY===!0&&t.io?.stderrIsTTY===!0){let i=await(t.io?.installWizard??M_)(n);if(i.action==="cancel")return{cancelled:!0};return wr(i.request)}let o=await L_(e,t,"Install HolyCodex into the selected Codex home?");if(o==="cancelled")return{cancelled:!0};if(o==="unavailable")throw new Ji("non_tty_confirmation_required","Install requires --yes in non-interactive mode.");return wr(n)}function Uj(e){let t=Kj(e),n=zj(e),r=Bj(e),o=Wj(e,"add-plugin");return wr({...t===void 0?{}:{profile:t},...n===void 0?{}:{tier:n},...r===void 0?{}:{optional:r},...o.length===0?{}:{officialPlugins:o}})}async function Hj(e,t){let n=await L_(e,t,"Remove HolyCodex-owned Codex state?");if(n==="cancelled")return{cancelled:!0,removed:[],preserved:[],reasons:["cancelled"]};if(n==="unavailable")throw new Ji("non_tty_confirmation_required","Remove requires --yes in non-interactive mode.");return await Ll(Mf(e,t),t.env)}async function $j(e,t){let n=e.options["dry-run"]===!0;if(!n){let r=await L_(e,t,"Upgrade the existing HolyCodex installation in place?");if(r==="cancelled")return{cancelled:!0,status:"cancelled",changes:[]};if(r==="unavailable")throw new Ji("non_tty_confirmation_required","Upgrade requires --yes in non-interactive mode.")}return await C_(Mf(e,t),t.env,{dryRun:n})}async function jj(e,t){let n=e.positionals[0];if(!n)return{version:await bf()};return await g_(n,e.options["dry-run"]===!0)}async function L_(e,t,n){if(e.options.yes===!0)return"confirmed";if(e.options.json===!0||t.io?.stdoutIsTTY!==!0||t.io?.stderrIsTTY!==!0)return"unavailable";return await Vj(t,n)}async function Vj(e,t){if(e.io?.confirm===void 0)return"unavailable";let n=await e.io.confirm(t);if(n==="confirmed"||n==="cancelled"||n==="unavailable")return n;return n?"confirmed":"cancelled"}function Bj(e){let t={};for(let n of["computer_use","work","frontend","security"]){let r=n.replaceAll("_","-");if(e.options[r]===!0)t[n]=!0;else if(e.options[r]===!1)t[n]=!1;else if(e.options[`no-${r}`]===!0)t[n]=!1}return Object.keys(t).length===0?void 0:t}function Kj(e){let t=e.options.profile;if(typeof t!=="string")return;let n=fr(t);return n.ok?n.value.name:void 0}function zj(e){let t=e.options.tier;return t==="standard"||t==="fast"||t==="fast-all"?t:void 0}function Wj(e,t){let n=e.options[t];return Array.isArray(n)?n.filter((r)=>typeof r==="string"):[]}function Mf(e,t){let n=t.installer??{},r=e.options.json===!0,o=(a)=>{n.onProgress?.(a),t.onProgress?.(a),Xj(t,r,a.message)},i=e.options["codex-home"];if(typeof i!=="string")return{...n,onProgress:o,...t.now?{now:t.now}:{}};return{...n,paths:{...n.paths,codexHome:i},onProgress:o,...t.now?{now:t.now}:{}}}function WI(e,t){let n=Kd({schema_version:vr,ok:!0,command:e,data:t,warnings:[]});if(!n.ok)throw new Ji("internal_error","The success envelope failed validation.");return n.value}function Jj(e,t){let n=Yj(t),r=Kd({schema_version:vr,ok:!1,command:e,error:{code:n.code,message:n.message,details:n.details},warnings:[]});if(!r.ok)return{envelope:{schema_version:vr,ok:!1,command:"internal-error",error:{code:"internal_error",message:"The CLI failure envelope was invalid.",details:{}},warnings:[]},exitCode:5};return{envelope:r.value,exitCode:n.exitCode}}function Gj(e,t){return e==="doctor"&&Jn(t)&&t.healthy===!1?4:0}function Yj(e){if(e instanceof ze)return{code:e.code,message:zi(e.message),details:e.details,exitCode:1};if(e instanceof Ji)return{code:e.code,message:zi(e.message),details:{},exitCode:e.code==="internal_error"?5:1};if(e instanceof wn)return{code:"trust_boundary_failed",message:zi(e.message),details:{},exitCode:4};if(e instanceof N){let t=e.code==="capability_denied"?2:e.code==="state_corrupt"?4:3;return{code:e.code,message:zi(e.message),details:e.details,exitCode:t}}if(e instanceof Sr){let t=["timeout","output_limit","cancelled","readback_mismatch"].includes(e.code),n=e.code==="plugin_disabled"||e.code==="plugin_missing"||e.code==="command_failed";return{code:t?"effect_uncertain":n?"capability_denied":"install_failed",message:zi(e.message),details:e.details,exitCode:t?4:n?2:3}}if(e instanceof Bi)return{code:e.code,message:zi(e.message),details:{},exitCode:4};if(e instanceof Pl)return{code:e.code,message:zi(e.message),details:{},exitCode:1};if(e instanceof Error)return{code:"internal_error",message:"The command failed unexpectedly.",details:{},exitCode:5};return{code:"internal_error",message:"The command failed unexpectedly.",details:{},exitCode:5}}function Zj(e){return e.find((t)=>!t.startsWith("-"))??"unknown"}function zi(e){return Array.from(e).map((t)=>{let n=t.codePointAt(0)??0;return n<=31||n===127?" ":t}).join("").replace(/\s+/gu," ").trim().slice(0,512)}function Jn(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function Xj(e,t,n){if(t||e.io?.stderrIsTTY===!1)return;e.io?.writeStderr?.(`${GI(n,{stderrIsTTY:e.io?.stderrIsTTY,env:e.env})}
118
+ `)}function Nf(e,t={}){let n=Gd(t);if(e.envelope.ok){if(e.envelope.command==="version")return Qj(e.envelope.data);if(e.envelope.command==="install")return e1(e.envelope.data,n);if(e.envelope.command==="remove")return t1(e.envelope.data,n);if(e.envelope.command==="upgrade")return n1(e.envelope.data,n);if(e.envelope.command==="doctor")return r1(e.envelope.data,n);return`${oe("\u2714","green",n)} ${oe(e.envelope.command,"heading",n)}
119
+ ${o1(e.envelope.data,n)}`}let r=e.envelope.error,o=a1(r.code,e.envelope.command);return[`${oe("\u2716","red",n)} ${oe(e.envelope.command,"heading",n)}`,` ${oe(r.code,"red",n)}: ${r.message}`,...i1(r.details,n),...o===void 0?[]:[` hint: ${o}`],""].join(`
120
+ `)}function GI(e,t={}){return`${oe("\u2022","cyan",Gd({...t,stream:"stderr"}))} ${e}`}function Qj(e){if(Jn(e)&&typeof e.version==="string")return`holycodex ${e.version}
121
+ `;if(Jn(e)&&typeof e.next==="string"){let t=typeof e.previous==="string"?` (from ${e.previous})`:"";return`holycodex version updated to ${e.next}${t}
122
+ `}return`holycodex version completed
123
+ `}function e1(e,t){if(Ff(e,"cancelled")===!0)return`${oe("\u21A9","cyan",t)} ${oe("install","heading",t)} cancelled
124
+ `;let n=Vl(e,"record"),r=Wo(n,"version")??"unknown",o=Wo(n,"profile")??"unknown",i=Wo(n,"tier")??"unknown",a=Vl(n,"optional_selections"),s=Vl(n,"capability_state"),c=["frontend","security","work","computer_use"].filter((m)=>a?.[m]===!0).map((m)=>{let w=Wo(Vl(s,m),"status");return w===void 0||w==="healthy"?m:`${m} (${w})`}),l=Wi(e,"preserved"),u=Wi(e,"warnings"),p=c.length===0?"none":c.join(", "),f=l.length===0?"none":`${l.length} managed item${l.length===1?"":"s"} (review before retrying)`;return`${[`${oe("\u2714","green",t)} ${oe("install","heading",t)}`,` ${oe("version","option",t)}: ${r}`,` ${oe("profile","option",t)}: ${o}`,` ${oe("tier","option",t)}: ${i}`,` ${oe("capabilities","option",t)}: ${p}`,` ${oe("preserved","option",t)}: ${f}`,...u.map((m)=>` ${oe("warning","red",t)}: ${Lf(m)}`)].join(`
125
+ `)}
126
+ `}function t1(e,t){if(Ff(e,"cancelled")===!0)return`${oe("\u21A9","cyan",t)} ${oe("remove","heading",t)} cancelled
127
+ `;let n=Wi(e,"removed"),r=Wi(e,"preserved"),o=Wi(e,"reasons"),i=r.length===0?"none":`${r.length} item${r.length===1?"":"s"} (review before retrying)`;return`${[`${oe("\u2714","green",t)} ${oe("remove","heading",t)}`,` ${oe("removed","option",t)}: ${n.length} owned item${n.length===1?"":"s"}`,` ${oe("preserved","option",t)}: ${i}`,...o.map((s)=>` ${oe("reason","option",t)}: ${Lf(s)}`)].join(`
128
+ `)}
129
+ `}function n1(e,t){if(Ff(e,"cancelled")===!0)return`${oe("\u21A9","cyan",t)} ${oe("upgrade","heading",t)} cancelled
130
+ `;let n=Wo(Jn(e)?e:void 0,"status")??"completed",r=Wo(Jn(e)?e:void 0,"from_version"),o=Wo(Jn(e)?e:void 0,"to_version"),i=Wi(e,"changes"),a=r!==void 0&&o!==void 0?` (${r} \u2192 ${o})`:"";return`${[`${oe("\u2714","green",t)} ${oe("upgrade","heading",t)}${a}`,` ${oe("status","option",t)}: ${n}`,` ${oe("changes","option",t)}: ${i.length===0?"none":i.map(Lf).join(", ")}`].join(`
131
+ `)}
132
+ `}function r1(e,t){let n=Ff(e,"healthy")===!0,r=Vl(e,"checks"),o=r===void 0?[]:Object.entries(r),i=o.flatMap(([c,l])=>{let u=Jn(l)?l:void 0,p=Wo(u,"status");if(p===void 0||p==="healthy")return[];let f=Wi(u,"reasons");return[` ${oe(c,"option",t)}: ${f.length===0?p:f.map(Lf).join(", ")}`]});return`${[`${n?oe("\u2714","green",t):oe("\u2716","red",t)} ${oe("doctor","heading",t)}`,` ${oe("status","option",t)}: ${n?"healthy":"needs attention"}`,` ${oe("checks","option",t)}: ${o.length}`,...i.length===0?[]:[` ${oe("issues","option",t)}:`,...i]].join(`
133
+ `)}
134
+ `}function Vl(e,t){if(!Jn(e))return;return Jn(e[t])?e[t]:void 0}function Ff(e,t){return Jn(e)?e[t]:void 0}function Wo(e,t){let n=e?.[t];return typeof n==="string"?n:void 0}function Wi(e,t){if(!Jn(e)||!Array.isArray(e[t]))return[];return e[t]}function Lf(e){if(typeof e!=="string")return"operation requires review";return e.replaceAll("_"," ")}function o1(e,t){if(typeof e!=="object"||e===null||Array.isArray(e))return` ${oe(N_(e),"dim",t)}
135
+ `;let n=Object.entries(e);if(n.length===0)return"";let r=Math.max(...n.map(([o])=>o.length));return`${n.map(([o,i])=>` ${oe(o.padEnd(r),"option",t)}: ${N_(i)}`).join(`
136
+ `)}
137
+ `}function i1(e,t){return Object.entries(e).map(([n,r])=>` ${oe(n,"option",t)}: ${oe(N_(r),"dim",t)}`)}function N_(e){if(typeof e==="string")return e;if(e===null||typeof e==="number"||typeof e==="boolean")return String(e);return JSON.stringify(e)}function a1(e,t){if(e==="invalid_argument"||e==="unknown_command")return`holycodex ${t} --help`;if(e==="non_tty_confirmation_required")return"rerun with --yes or use an interactive terminal";if(e==="capability_denied")return"run `holycodex doctor` to inspect capability availability";return}function oe(e,t,n){if(!n)return e;return`\x1B[${{red:"31",green:"32",cyan:"36",dim:"2",heading:"1",option:"36"}[t]}m${e}\x1B[0m`}class Ji extends Error{code;constructor(e,t){super(t);this.name="CliCommandError",this.code=e}}async function D_(e=Bun.argv.slice(2),t=c1()){let n={env:process.env,cwd:process.cwd(),io:{stdin:t.stdin??l1(),stdoutIsTTY:t.stdoutIsTTY??process.stdout.isTTY===!0,stderrIsTTY:t.stderrIsTTY??process.stderr.isTTY===!0,...t.confirm===void 0?{}:{confirm:t.confirm},...t.installWizard===void 0?{}:{installWizard:t.installWizard},writeStdout:t.writeStdout,writeStderr:t.writeStderr}},r=await F_(e,n);if((al(e)||e[0]==="help")&&!YI(e))n.io?.writeStdout?.(oS(sl(e),{stdoutIsTTY:n.io?.stdoutIsTTY,stderrIsTTY:n.io?.stderrIsTTY,env:n.env,stream:"stdout"}));else if(YI(e))n.io?.writeStdout?.(`${JSON.stringify(r.envelope)}
138
+ `);else if(r.envelope.ok)n.io?.writeStdout?.(Nf(r,{stdoutIsTTY:n.io?.stdoutIsTTY,stderrIsTTY:n.io?.stderrIsTTY,env:n.env,stream:"stdout"}));else n.io?.writeStderr?.(Nf(r,{stdoutIsTTY:n.io?.stderrIsTTY,stderrIsTTY:n.io?.stderrIsTTY,env:n.env,stream:"stderr"}));return r.exitCode}function c1(){return{stdoutIsTTY:process.stdout.isTTY===!0,stderrIsTTY:process.stderr.isTTY===!0,writeStdout:(e)=>process.stdout.write(e),writeStderr:(e)=>process.stderr.write(e),confirm:async(e)=>{let t=s1({input:process.stdin,output:process.stderr});try{let n=await t.question(`${e} [y/N] `);return/^(?:y|yes)$/iu.test(n.trim())}finally{t.close()}}}}function YI(e){let t=!1;for(let n of e)if(n==="--json"||n==="--json=true")t=!0;else if(n==="--json=false")t=!1;return t}async function*l1(){let e=new TextDecoder;for await(let n of process.stdin)if(typeof n==="string")yield n;else yield e.decode(n,{stream:!0});let t=e.decode();if(t.length>0)yield t}ql();Af();Il();Vi();Nl();kf();var bZ="holycodex";if(import.meta.main)process.exitCode=await D_();export{ze as ArgumentError,rs as CapabilityInstallStateSchema,d_ as CapabilityStateRecordSchema,zo as CodexOfficialPluginManager,_f as InstallOptionsSchema,is as InstallRecordSchema,Rl as InstallRequestSchema,N as InstallerError,Sr as OfficialPluginManagerError,wn as PathBoundaryError,q$ as STATE_SCHEMA,h_ as assertRootText,k_ as doctorHolyCodex,JI as executeCommand,al as helpRequested,il as helpText,sl as helpTopic,fs as installHolyCodex,__ as installNativeAgents,If as installRecordDigest,bZ as packageName,Wd as parseArgv,VI as parsePluginInput,ss as pathWithin,Ki as projectNativeAgents,x_ as projectRootAgent,Al as publicManifestPath,ms as readActiveInstallRecord,ls as readCanonicalBaseVersion,bf as readCanonicalVersion,Ll as removeHolyCodex,Of as removeManagedNativeAgents,oS as renderHelp,Nf as renderHuman,Mj as renderInstallWizardReview,Rf as renderNativeAgent,GI as renderProgress,ji as resolveInstallerPaths,Ef as rollbackNativeAgentInstall,S_ as rootDeveloperInstructions,D_ as runBinary,F_ as runCli,M_ as runOpenTuiInstallWizard,HI as toInstallOptions,g_ as updateCanonicalVersion,C_ as upgradeHolyCodex,wr as validateInstallOptions};