holycodex 0.16.10 → 0.16.11-dev.120.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,49 +1,41 @@
1
1
  #!/usr/bin/env bun
2
2
  // @bun
3
- var w=(e,t,n)=>()=>{if(e)try{t=e(e=0)}catch(r){n=[r]}if(n)throw n[0];return t};function jr(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&&Ig(r.value))jr(r.value,t)}Object.freeze(e)}function Ig(e){return typeof e==="object"&&e!==null}var So="0.15",On="state-0.16";var jR=()=>{};function Os(e){return{ok:!0,value:e}}function fa(e){return{ok:!1,error:e}}function ul(e,t){return new gt("invalid_input",`Invalid ${e}.`,{field:e},t===void 0?void 0:{cause:t})}var gt;var ks=w(()=>{gt=class gt extends Error{code;details;constructor(e,t,n={},r){super(t,r);this.name="CoreError",this.code=e,this.details=n,jr(this.details),Object.freeze(this)}}});function b(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 Ag=(e)=>typeof e==="function",h=function(e,t){if(typeof e==="function")return function(){if(e(arguments))return t.apply(this,arguments);return(n)=>t(n,...arguments)};switch(e){case 0:case 1:throw RangeError(`Invalid arity ${e}`);case 2:return function(n,r){if(arguments.length>=2)return t(n,r);return function(o){return t(o,n)}};case 3:return function(n,r,o){if(arguments.length>=3)return t(n,r,o);return function(i){return t(i,n,r)}};case 4:return function(n,r,o,i){if(arguments.length>=4)return t(n,r,o,i);return function(a){return t(a,n,r,o)}};case 5:return function(n,r,o,i,a){if(arguments.length>=5)return t(n,r,o,i,a);return function(s){return t(s,n,r,o,i)}};default:return function(){if(arguments.length>=e)return t.apply(this,arguments);let n=arguments;return function(r){return t(r,...n)}}}},ve=(e)=>e,dl=(e)=>()=>e,pl,ui,ap,fl;var ne=w(()=>{pl=dl(!0),ui=dl(!1),ap=dl(void 0),fl=ap});var hl=(e)=>(t,n)=>t===n||e(t,n),qL=(e,t)=>e===t,UL=()=>qL,$L,Pg,HR,BR=(e)=>hl((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 gl=w(()=>{ne();$L=UL(),Pg=h(2,(e,t)=>hl((n,r)=>e(t(n),t(r)))),HR=Pg($L,(e)=>e.getTime())});var yl,re=(e,t)=>{if(!yl)globalThis["effect/GlobalValue"]??=new Map,yl=globalThis["effect/GlobalValue"];if(!yl.has(e))yl.set(e,t());return yl.get(e)};var Ut=(e)=>typeof e==="string",kn=(e)=>typeof e==="number",ma=(e)=>typeof e==="boolean",di=(e)=>typeof e==="bigint",ha=(e)=>typeof e==="symbol",pi,VR=(e)=>e===void 0,WR=(e)=>!1,xl=(e)=>typeof e==="object"&&e!==null,rn=(e)=>xl(e)||pi(e),H,Sl,ga=(e)=>e===null||e===void 0,zR=(e)=>e!==null&&e!==void 0,cp=(e)=>e instanceof Date,Mg=(e)=>typeof e==="string"||H(e,Symbol.iterator),Ng=(e)=>xl(e)&&!Array.isArray(e),KR=(e)=>H(e,"then")&&pi(e.then);var Ae=w(()=>{ne();pi=Ag,H=h(2,(e,t)=>rn(e)&&(t in e)),Sl=h(2,(e,t)=>H(e,"_tag")&&e._tag===t)});var ya=(e)=>`BUG: ${e} - please report an issue at https://github.com/Effect-TS/effect/issues`;class Lg{_state;constructor(e,t,n,r){if(ga(t)&&ga(e))t=Math.random()*4294967295>>>0,e=0;else if(ga(t))t=e,e=0;if(ga(r)&&ga(n))r=this._state?this._state[3]:HL,n=this._state?this._state[2]:jL;else if(ga(r))r=n,n=0;return this._state=new Int32Array([0,0,n>>>0,((r||0)|1)>>>0]),this._next(),JR(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*zL+t)/WL}_next(){let e=this._state[0]>>>0,t=this._state[1]>>>0;KL(this._state,e,t,BL,VL),JR(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 KL(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 JR(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 Dg(e){if(typeof e==="object"&&e!==null&&Fg in e)return e[Fg]();throw Error(ya("yieldWrapGet"))}var Is,jL=335903614,HL=4150755663,BL=1481765933,VL=1284865837,WL=9007199254740992,zL=134217728,Fg,bo,pn,GR,JL,GL,$t,dG;var fi=w(()=>{Ae();Is=class Is{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 Is(this.self)}};Fg=Symbol.for("effect/Utils/YieldWrap");bo=class bo{#e;constructor(e){this.#e=e}[Fg](){return this.#e}};pn=re("effect/Utils/isStructuralRegion",()=>({enabled:!1,tester:void 0})),GR={effect_internal_function:(e)=>e()},JL={effect_internal_function:(e)=>{try{return e()}finally{}}},GL=GR.effect_internal_function(()=>Error().stack)?.includes("effect_internal_function")===!0,$t=GL?GR.effect_internal_function:JL.effect_internal_function,dG=function*(){}.constructor});var qg,J,U=(e)=>{if(pn.enabled===!0)return 0;switch(typeof e){case"number":return up(e);case"bigint":return ke(e.toString(10));case"boolean":return ke(String(e));case"symbol":return ke(String(e));case"string":return ke(e);case"undefined":return ke("undefined");case"function":case"object":if(e===null)return ke("null");else if(e instanceof Date){if(Number.isNaN(e.getTime()))return ke("Invalid Date");return U(e.toISOString())}else if(e instanceof URL)return U(e.href);else if(ZL(e))return e[J]();else return bl(e);default:throw Error(`BUG: unhandled typeof ${typeof e} - please report an issue at https://github.com/Effect-TS/effect/issues`)}},bl=(e)=>{if(!qg.has(e))qg.set(e,up(Math.floor(Math.random()*Number.MAX_SAFE_INTEGER)));return qg.get(e)},le=(e)=>(t)=>t*53^e,lp=(e)=>e&3221225471|e>>>1&1073741824,ZL=(e)=>H(e,J),up=(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 lp(t)},ke=(e)=>{let t=5381,n=e.length;while(n)t=t*33^e.charCodeAt(--n);return lp(t)},XL=(e,t)=>{let n=12289;for(let r=0;r<t.length;r++)n^=b(ke(t[r]),le(U(e[t[r]])));return lp(n)},dp=(e)=>XL(e,Object.keys(e)),En=(e)=>{let t=6151;for(let n=0;n<e.length;n++)t=b(t,le(U(e[n])));return lp(t)},xe=function(){if(arguments.length===1){let n=arguments[0];return function(r){return Object.defineProperty(n,J,{value(){return r},enumerable:!1}),r}}let e=arguments[0],t=arguments[1];return Object.defineProperty(e,J,{value(){return t},enumerable:!1}),t};var Ge=w(()=>{ne();Ae();fi();qg=re(Symbol.for("effect/Hash/randomHashCache"),()=>new WeakMap),J=Symbol.for("effect/Hash")});function j(){if(arguments.length===1)return(e)=>pp(e,arguments[0]);return pp(arguments[0],arguments[1])}function pp(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(wl(e)&&wl(t))if(U(e)===U(t)&&e[z](t))return!0;else return pn.enabled&&pn.tester?pn.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(pn.enabled){if(e===null||t===null)return!1;if(Array.isArray(e)&&Array.isArray(t))return e.length===t.length&&e.every((r,o)=>pp(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)&&pp(e[i],t[i])))return pn.tester?pn.tester(e,t):!1;return!0}}return pn.tester?pn.tester(e,t):!1}}return pn.enabled&&pn.tester?pn.tester(e,t):!1}var z,wl=(e)=>H(e,z),_l=()=>j;var Re=w(()=>{Ge();Ae();fi();z=Symbol.for("effect/Equal")});function QL(e){try{return e.toISOString()}catch{return"Invalid Date"}}function eD(e){try{let t=e.toString();return typeof t==="string"?t:String(t)}catch{return"[toString threw]"}}function vl(e){return Ut(e)?JSON.stringify(e):String(e)}function Hr(e,t){let n=t?.space??0,r=new WeakSet,o=!n?"":kn(n)?" ".repeat(n):n,i=(l)=>o.repeat(l),a=(l,u)=>{let d=l?.constructor;return d&&d!==Object.prototype.constructor&&d.name?`${d.name}(${u})`:u},s=(l)=>{try{return Reflect.ownKeys(l)}catch{return["[ownKeys threw]"]}};function c(l,u=0){if(Array.isArray(l)){if(r.has(l))return Ug;if(r.add(l),!o||l.length<=1)return`[${l.map((p)=>c(p,u)).join(",")}]`;let d=l.map((p)=>c(p,u+1)).join(`,
4
- `+i(u+1));return`[
5
- ${i(u+1)}${d}
6
- ${i(u)}]`}if(cp(l))return QL(l);if(!t?.ignoreToString&&H(l,"toString")&&pi(l.toString)&&l.toString!==Object.prototype.toString&&l.toString!==Array.prototype.toString){let d=eD(l);if(l instanceof Error&&l.cause)return`${d} (cause: ${c(l.cause,u)})`;return d}if(Ut(l))return JSON.stringify(l);if(kn(l)||l==null||ma(l)||ha(l))return String(l);if(di(l))return String(l)+"n";if(l instanceof Set||l instanceof Map){if(r.has(l))return Ug;return r.add(l),`${l.constructor.name}(${c(Array.from(l),u)})`}if(rn(l)){if(r.has(l))return Ug;r.add(l);let d=s(l);if(!o||d.length<=1){let m=`{${d.map((f)=>`${vl(f)}:${c(l[f],u)}`).join(",")}}`;return a(l,m)}let p=`{
7
- ${d.map((m)=>`${i(u+1)}${vl(m)}: ${c(l[m],u+1)}`).join(`,
3
+ var ok=Object.defineProperty;var ak=(e)=>e;function sk(e,t){this[e]=ak.bind(null,t)}var ck=(e,t)=>{for(var n in t)ok(e,n,{get:t[n],enumerable:!0,configurable:!0,set:sk.bind(t,n)})};var L=(e,t,n)=>()=>{if(e)try{t=e(e=0)}catch(r){n=[r]}if(n)throw n[0];return t};var en=(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,i=t.length;r<i;r++)n=t[r](n);return n}}},Ud,Za;var Ir=L(()=>{Ud={pipe(){return en(this,arguments)}},Za=function(){function e(){}return e.prototype=Ud,e}()});function Qa(e){let t=new WeakMap;return(n)=>{let r=t.get(n);if(r!==void 0)return r;let i=e(n);return t.set(n,i),i}}function Mo(e){let t=new WeakMap;return(n)=>{let r=t.get(n);if(r!==void 0)return r;let i=e(n);if(t.set(n,i),i!==n)t.set(i,i);return i}}var Y=function(e,t){if(typeof e==="function")return function(){return e(arguments)?t.apply(this,arguments):(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(i){return t(i,n)}};case 3:return function(n,r,i){if(arguments.length>=3)return t(n,r,i);return function(o){return t(o,n,r)}};default:return function(){if(arguments.length>=e)return t.apply(this,arguments);let n=arguments;return function(r){return t(r,...n)}}}},Xe=(e)=>e,Ol=(e)=>()=>e,$d,NS,Xa,jd;var ln=L(()=>{$d=Ol(!0),NS=Ol(!1),Xa=Ol(void 0),jd=Xa});var es=(e)=>{let t=new Set(Reflect.ownKeys(e));if(e.constructor===Object)return t;if(e instanceof Error)t.delete("stack");let n=Object.getPrototypeOf(e),r=n;while(r!==null&&r!==Object.prototype){let i=Reflect.ownKeys(r);for(let o=0;o<i.length;o++)t.add(i[o]);r=Object.getPrototypeOf(r)}if(t.has("constructor")&&typeof e.constructor==="function"&&n===e.constructor.prototype)t.delete("constructor");return t},ts,ns=(e)=>new Uint8Array(e.buffer,e.byteOffset,e.byteLength);var Bd=L(()=>{ts=new WeakSet});var Al=0,DS=()=>{Al++};function rs(e){return typeof e==="string"}function is(e){return typeof e==="number"}function FS(e){return typeof e==="boolean"}function LS(e){return typeof e==="symbol"}function US(e){return rs(e)||is(e)||LS(e)}function os(e){return typeof e==="function"}function $S(e){return e!=null}function jS(e){return!0}function Ml(e){return typeof e==="object"&&e!==null||os(e)}function BS(e){return we(e,Symbol.iterator)||rs(e)}var we;var $t=L(()=>{ln();we=Y(2,(e,t)=>Ml(e)&&(t in e))});var Qe="~effect/Hash",Ce=(e)=>{switch(typeof e){case"number":return ss(e);case"bigint":return jt(e.toString(10));case"string":return jt(e);case"function":case"object":if(e===null)break;else if(e instanceof Date){if(Number.isNaN(e.getTime()))return jt("Invalid Date");return jt(e.toISOString())}else if(e instanceof RegExp)return jt(e.toString());else{if(ts.has(e))return Nl(e);let t=qS.get(e);if(t!==void 0)return t;if(zd.has(e))return DS(),jt("[Circular]");zd.add(e);let n=Al,r;try{if(Qe in e)r=e[Qe]();else if(typeof e==="function")r=Nl(e);else if(e instanceof DataView)r=Dl(ns(e));else if(Array.isArray(e)||ArrayBuffer.isView(e))r=Dl(e);else if(e instanceof Map)r=lk(e);else if(e instanceof Set)r=uk(e);else r=Wd(e)}finally{zd.delete(e)}if(n===Al)qS.set(e,r);return r}}return ri(zS(jt(String(e))))},Nl=(e)=>{if(!qd.has(e))qd.set(e,ri(Math.random()*4294967296|0));return qd.get(e)},zS=(e)=>(e^=e>>>16,e=Math.imul(e,2246822507),e^=e>>>13,e=Math.imul(e,3266489909),e^e>>>16),pt,ri=(e)=>e&3221225471|e>>>1&1073741824,Vd,ss=(e)=>{let t=e|0;if(t===e)return ri(t);return Vd.setFloat64(0,e!==e?NaN:e),ri(pt(Vd.getInt32(0),Vd.getInt32(4)))},jt=(e)=>{let t=5381,n=e.length;while(n)t=t*33^e.charCodeAt(--n);return ri(t)},Jd=(e,t)=>{let n=12289;for(let r of t)n^=pt(Ce(r),Ce(e[r]));return ri(n)},Wd=(e)=>Jd(e,es(e)),JS=(e,t)=>(n)=>{let r=e;for(let i of n)r^=t(i);return ri(r)},Dl=(e)=>{let t=6151;for(let n of e)t=pt(t,Ce(n));return ri(t)},lk,VS,uk,qd,qS,zd;var ii=L(()=>{ln();Bd();pt=Y(2,(e,t)=>zS(Math.imul(e,2654435761)+Math.imul(t,2246822507))),Vd=new DataView(new ArrayBuffer(8)),lk=JS(jt("Map"),([e,t])=>pt(Ce(e),Ce(t))),VS=jt("Set"),uk=JS(VS,(e)=>pt(VS,Ce(e))),qd=new WeakMap,qS=new WeakMap,zd=new WeakSet});function mt(){if(arguments.length===1)return(e)=>$i(e,arguments[0]);return $i(arguments[0],arguments[1])}function $i(e,t){if(e===t)return!0;if(e==null||t==null)return!1;let n=typeof e;if(n!==typeof t)return!1;if(n==="number"&&e!==e&&t!==t)return!0;if(n!=="object"&&n!=="function")return!1;if(ts.has(e)||ts.has(t))return!1;return fk(e,t)}function fk(e,t){let n=Fl.length;for(let o=n;o-- >0;)if(Fl[o]===e&&Hd[o]===t)return!0;if(n)return WS(e,t);let r=HS.get(e);if(!r)HS.set(e,r=new WeakMap);let i=r.get(t);if(i===void 0)r.set(t,i=WS(e,t));return i}function WS(e,t){Fl.push(e),Hd.push(t);try{return dk(e,t)}finally{Fl.pop(),Hd.pop()}}function dk(e,t){if(Ce(e)!==Ce(t))return!1;else if(e instanceof Date){if(!(t instanceof Date))return!1;let r=e.getTime(),i=t.getTime();return r===i||Number.isNaN(r)&&Number.isNaN(i)}else if(e instanceof RegExp)return t instanceof RegExp&&e.toString()===t.toString();let n=YS(e);if(n!==YS(t)||typeof e==="function"&&!n)return!1;else if(n)return e[et](t);else if(Array.isArray(e)){if(!Array.isArray(t)||e.length!==t.length)return!1;return pk(e,t)}else if(ArrayBuffer.isView(e)){let r=e instanceof DataView;if(!ArrayBuffer.isView(t)||e.byteLength!==t.byteLength||r!==t instanceof DataView)return!1;if(r)return KS(ns(e),ns(t));return KS(e,t)}else if(e instanceof Map){if(!(t instanceof Map)||e.size!==t.size)return!1;return GS(e,t,gk,hk)}else if(e instanceof Set){if(!(t instanceof Set)||e.size!==t.size)return!1;return GS(e,t,Ce,$i)}return mk(e,t)}function pk(e,t){for(let n=0;n<e.length;n++)if(!$i(e[n],t[n]))return!1;return!0}function KS(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function mk(e,t){let n=es(e),r=es(t);if(n.size!==r.size)return!1;for(let i of n)if(!r.has(i)||!$i(e[i],t[i]))return!1;return!0}function GS(e,t,n,r){let i=new Map;for(let o of t){let a=n(o),s=i.get(a);if(s)s.push(o);else i.set(a,[o])}e:for(let o of e){let a=i.get(n(o));if(a){for(let s=0;s<a.length;s++)if(r(o,a[s])){a[s]=a[a.length-1],a.pop();continue e}}return!1}return!0}var et="~effect/Equal",Fl,Hd,HS,gk=(e)=>Ce(e[0]),hk=(e,t)=>$i(e[0],t[0])&&$i(e[1],t[1]),YS=(e)=>we(e,et);var ji=L(()=>{ii();Bd();$t();Fl=[],Hd=[],HS=new WeakMap});function Do(e){if(yk(e))return Kd(e);return e}function Kd(e){return e[cs](globalThis[Fo]?.context??Sk)}var cs,yk=(e)=>we(e,cs),Fo="~effect/Fiber/currentFiber",ZS,Sk;var Ll=L(()=>{Ir();$t();cs=Symbol.for("~effect/Redactable");ZS=new Map,Sk={"~effect/Context":{},base:ZS,depth:0,mapUnsafe:ZS,pipe(){return en(this,arguments)}}});function Te(e,t){let n=t?.space??0,r=new WeakSet,i=!n?"":typeof n==="number"?" ".repeat(n):n,o=(l)=>i.repeat(l),a=(l,u)=>{let g=l?.constructor;return g&&g!==Object.prototype.constructor&&g.name?`${g.name}(${u})`:u},s=(l)=>{try{return Reflect.ownKeys(l)}catch{return["[ownKeys threw]"]}};function c(l,u=0){try{return f(l,u)}catch{if(typeof l==="object"&&l!==null||typeof l==="function")r.delete(l);return"[inspection threw]"}}function f(l,u=0){if(typeof l==="string")return JSON.stringify(l);if(typeof l==="number"||l==null||typeof l==="boolean"||typeof l==="symbol")return String(l);if(typeof l==="bigint")return String(l)+"n";if(typeof l==="object"||typeof l==="function"){if(r.has(l))return xk;r.add(l);let g;if(cs in l)g=c(Kd(l),u);else if(Array.isArray(l))g=!i||l.length<=1?`[${l.map((h)=>c(h,u)).join(",")}]`:`[
4
+ ${o(u+1)}${l.map((h)=>c(h,u+1)).join(`,
5
+ `+o(u+1))}
6
+ ${o(u)}]`;else if(l instanceof Date)g=Ek(l);else if(!t?.ignoreToString&&we(l,"toString")&&typeof l.toString==="function"&&l.toString!==Object.prototype.toString&&l.toString!==Array.prototype.toString){let h=vk(l);g=l instanceof Error&&l.cause!==void 0?`${h} (cause: ${c(l.cause,u)})`:h}else if(Symbol.iterator in l)g=`${l.constructor.name}(${c(Array.from(l),u)})`;else{let h=s(l);if(!i||h.length<=1){let y=`{${h.map((S)=>`${Lo(S)}:${c(XS(l,S),u)}`).join(",")}}`;g=a(l,y)}else{let y=`{
7
+ ${h.map((S)=>`${o(u+1)}${Lo(S)}: ${c(XS(l,S),u+1)}`).join(`,
8
8
  `)}
9
- ${i(u)}}`;return a(l,p)}return String(l)}return c(e,0)}var me,Te=(e)=>{try{if(H(e,"toJSON")&&pi(e.toJSON)&&e.toJSON.length===0)return e.toJSON();else if(Array.isArray(e))return e.map(Te)}catch{return{}}return XR(e)},Ug="[Circular]",Ee=(e)=>JSON.stringify(e,null,2),SG,wo=(e,t=2)=>{if(typeof e==="string")return e;try{return typeof e==="object"?fp(e,t):String(e)}catch{return String(e)}},fp=(e,t)=>{let n=[],r=JSON.stringify(e,(o,i)=>typeof i==="object"&&i!==null?n.includes(i)?void 0:n.push(i)&&(xa.fiberRefs!==void 0&&YR(i)?i[$g](xa.fiberRefs):i):i,t);return n=void 0,r},$g,YR=(e)=>typeof e==="object"&&e!==null&&($g in e),xa,ZR=(e,t)=>{let n=xa.fiberRefs;xa.fiberRefs=e;try{return t()}finally{xa.fiberRefs=n}},XR=(e)=>{if(YR(e)&&xa.fiberRefs!==void 0)return e[$g](xa.fiberRefs);return e};var at=w(()=>{Ae();me=Symbol.for("nodejs.util.inspect.custom");SG={toJSON(){return Te(this)},[me](){return this.toJSON()},toString(){return Ee(this.toJSON())}},$g=Symbol.for("effect/Inspectable/Redactable"),xa=re("effect/Inspectable/redactableState",()=>({fiberRefs:void 0}))});var F=(e,t)=>{switch(t.length){case 0:return e;case 1:return t[0](e);case 2:return t[1](t[0](e));case 3:return t[2](t[1](t[0](e)));case 4:return t[3](t[2](t[1](t[0](e))));case 5:return t[4](t[3](t[2](t[1](t[0](e)))));case 6:return t[5](t[4](t[3](t[2](t[1](t[0](e))))));case 7:return t[6](t[5](t[4](t[3](t[2](t[1](t[0](e)))))));case 8:return t[7](t[6](t[5](t[4](t[3](t[2](t[1](t[0](e))))))));case 9:return t[8](t[7](t[6](t[5](t[4](t[3](t[2](t[1](t[0](e)))))))));default:{let n=e;for(let r=0,o=t.length;r<o;r++)n=t[r](n);return n}}};var Ne=()=>{};var ba="Async",wa="Commit",fn="Failure",Rl="OnFailure",As="OnSuccess",Ps="OnSuccessAndFailure",mn="Success",mp="Sync",QR="Tag",_a="UpdateRuntimeFlags",Ms="While",Ns="Iterator",hp="WithRuntime",Fs="Yield",Tl="RevertFlags";var tD="3.22.2",Cl=()=>tD;var tT,nT,rT,oT,mi,nD,rD,_o,Ol,hi,Hg,iT;var vo=w(()=>{Re();Ge();Ne();fi();tT=Symbol.for("effect/Effect"),nT=Symbol.for("effect/Stream"),rT=Symbol.for("effect/Sink"),oT=Symbol.for("effect/Channel"),mi={_R:(e)=>e,_E:(e)=>e,_A:(e)=>e,_V:Cl()},nD={_A:(e)=>e,_In:(e)=>e,_L:(e)=>e,_E:(e)=>e,_R:(e)=>e},rD={_Env:(e)=>e,_InErr:(e)=>e,_InElem:(e)=>e,_InDone:(e)=>e,_OutErr:(e)=>e,_OutElem:(e)=>e,_OutDone:(e)=>e},_o={[tT]:mi,[nT]:mi,[rT]:nD,[oT]:rD,[z](e){return this===e},[J](){return xe(this,bl(this))},[Symbol.iterator](){return new Is(new bo(this))},pipe(){return F(this,arguments)}},Ol={[J](){return xe(this,dp(this))},[z](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)&&j(this[r],e[r])))return!1;return!0}},hi={..._o,_op:wa},Hg={...hi,...Ol},iT=function(){function e(){}return e.prototype=hi,e}()});var sT,cT,oD,iD,aD,Bg=(e)=>H(e,sT),Vg=(e)=>e._tag==="None",Wg=(e)=>e._tag==="Some",gp,kl=(e)=>{let t=Object.create(oD);return t.value=e,t};var zg=w(()=>{Re();Ge();at();Ae();vo();sT=Symbol.for("effect/Option"),cT={..._o,[sT]:{_A:(e)=>e},[me](){return this.toJSON()},toString(){return Ee(this.toJSON())}},oD=Object.assign(Object.create(cT),{_tag:"Some",_op:"Some",[z](e){return Bg(e)&&Wg(e)&&j(this.value,e.value)},[J](){return xe(this,le(U(this._tag))(U(this.value)))},toJSON(){return{_id:"Option",_tag:this._tag,value:Te(this.value)}}}),iD=U("None"),aD=Object.assign(Object.create(cT),{_tag:"None",_op:"None",[z](e){return Bg(e)&&Vg(e)},[J](){return iD},toJSON(){return{_id:"Option",_tag:this._tag}}}),gp=Object.create(aD)});var Kg,uT,sD,cD,yp=(e)=>H(e,Kg),Jg=(e)=>e._tag==="Left",Gg=(e)=>e._tag==="Right",dT=(e)=>{let t=Object.create(cD);return t.left=e,t},pT=(e)=>{let t=Object.create(sD);return t.right=e,t};var fT=w(()=>{Re();Ge();at();Ae();vo();Kg=Symbol.for("effect/Either"),uT={..._o,[Kg]:{_R:(e)=>e},[me](){return this.toJSON()},toString(){return Ee(this.toJSON())}},sD=Object.assign(Object.create(uT),{_tag:"Right",_op:"Right",[z](e){return yp(e)&&Gg(e)&&j(this.right,e.right)},[J](){return le(U(this._tag))(U(this.right))},toJSON(){return{_id:"Either",_tag:this._tag,right:Te(this.right)}}}),cD=Object.assign(Object.create(uT),{_tag:"Left",_op:"Left",[z](e){return yp(e)&&Jg(e)&&j(this.left,e.left)},[J](){return le(U(this._tag))(U(this.left))},toJSON(){return{_id:"Either",_tag:this._tag,left:Te(this.left)}}})});var ue,ce,Yg,qe,Ct,xp,mT,El,hT,Zg,gT;var hn=w(()=>{ne();fT();ue=pT,ce=dT,Yg=yp,qe=Jg,Ct=Gg,xp=h(2,(e,t)=>qe(e)?ce(t(e.left)):ue(e.right)),mT=h(2,(e,t)=>Ct(e)?ue(t(e.right)):ce(e.left)),El=h(2,(e,{onLeft:t,onRight:n})=>qe(e)?t(e.left):n(e.right)),hT=El({onLeft:ve,onRight:ve}),Zg=h(2,(e,t)=>{if(Ct(e))return e.right;throw t(e.left)}),gT=Zg(()=>Error("getOrThrow called on a Left"))});var Xg=(e)=>e.length>0;var yT=(e)=>(t,n)=>t===n?0:e(t,n),xT,Sp,Qg=(e)=>h(2,(t,n)=>e(t,n)===1);var bp=w(()=>{ne();xT=yT((e,t)=>e<t?-1:1),Sp=h(2,(e,t)=>yT((n,r)=>e(t(n),t(r))))});var B=()=>gp,Y,Ye,$e,dt,Ue,pr,ST,Ro=(e)=>e==null?B():Y(e),gn,bT=(e)=>(...t)=>{try{return Y(e(...t))}catch{return B()}},fr,mr,wT,pD=(e)=>h(2,(t,n)=>Ye(t)?!1:e(t.value,n)),fD,_T,vT;var pt=w(()=>{Re();ne();zg();Y=kl,Ye=Vg,$e=Wg,dt=h(2,(e,{onNone:t,onSome:n})=>Ye(e)?t():n(e.value)),Ue=h(2,(e,t)=>Ye(e)?t():e.value),pr=h(2,(e,t)=>Ye(e)?t():e),ST=h(2,(e,t)=>Ye(e)?Y(t()):e),gn=Ue(ap),fr=h(2,(e,t)=>Ye(e)?B():Y(t(e.value))),mr=h(2,(e,t)=>Ye(e)?B():t(e.value)),wT=h(2,(e,t)=>Ye(e)?B():Ro(t(e.value))),fD=_l(),_T=pD(fD),vT=h(2,(e,t)=>Ye(e)?!1:t(e.value))});var RT=(...e)=>e;var TT=()=>{};var va=(e)=>Array(e),ty,je=(e)=>Array.isArray(e)?e:Array.from(e),ny=(e)=>Array.isArray(e)?e:[e],CT,Ls,OT,ry,oy,hD=(e)=>e.length===0,kT,gi,Fe,ET=(e,t)=>e<0||e>=t.length,gD=(e,t)=>Math.floor(Math.min(Math.max(0,e),t.length)),yD,iy,To,xt,IT=(e)=>Fe(e)?Y(ay(e)):B(),ay=(e)=>e[e.length-1],hr=(e)=>e.slice(1),xD=(e,t)=>{let n=0;for(let r of e){if(!t(r,n))break;n++}return n},AT,PT,sy=(e)=>Array.from(e).reverse(),Co,cy,MT,SD,bD,wD,Ds=(e)=>e.slice(),_D,yi,Oo=()=>[],Gt=(e)=>[e],gr,Il,wp,_p,qs,ly=(e,t)=>{let n=[],r=e,o;while($e(o=t(r))){let[i,a]=o.value;n.push(i),r=a}return n},xi,NT,uy=(e)=>NT(e,_l()),ko;var st=w(()=>{Re();gl();ne();pt();TT();ty=h(2,(e,t)=>{let n=Math.max(1,Math.floor(e)),r=Array(n);for(let o=0;o<n;o++)r[o]=t(o);return r}),CT=h(2,(e,{onEmpty:t,onNonEmpty:n})=>Fe(e)?n(xt(e),hr(e)):t()),Ls=h(2,(e,t)=>[t,...e]),OT=h(2,(e,t)=>[...e,t]),ry=h(2,(e,t)=>je(e).concat(je(t))),oy=Array.isArray,kT=hD,gi=Xg,Fe=Xg,yD=h(2,(e,t)=>{let n=Math.floor(t);return ET(n,e)?B():Y(e[n])}),iy=h(2,(e,t)=>{let n=Math.floor(t);if(ET(n,e))throw Error(`Index ${n} out of bounds`);return e[n]}),To=yD(0),xt=iy(0),AT=h(2,(e,t)=>bD(e,xD(e,t))),PT=h(2,(e,t)=>{let n=je(e);return n.slice(gD(t,n),n.length)}),Co=h(2,(e,t)=>{let n=Array.from(e);return n.sort(t),n}),cy=h(2,(e,t)=>MT(e,t,RT)),MT=h(3,(e,t,n)=>{let r=je(e),o=je(t);if(Fe(r)&&Fe(o)){let i=[n(xt(r),xt(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[]}),SD=_l(),bD=h(2,(e,t)=>{let n=Array.from(e),r=Math.floor(t);if(Fe(n)){if(r>=1)return wD(n,r);return[[],n]}return[n,[]]}),wD=h(2,(e,t)=>{let n=Math.max(1,Math.floor(t));return n>=e.length?[Ds(e),[]]:[Ls(e.slice(1,n),xt(e)),e.slice(n)]}),_D=h(3,(e,t,n)=>{let r=je(e),o=je(t);if(Fe(r)){if(Fe(o))return NT(n)(ry(r,o));return r}return o}),yi=h(2,(e,t)=>_D(e,t,SD)),gr=h(2,(e,t)=>e.map(t)),Il=h(2,(e,t)=>{if(kT(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}),wp=Il(ve),_p=h(2,(e,t)=>{let n=je(e),r=[];for(let o=0;o<n.length;o++){let i=t(n[o],o);if($e(i))r.push(i.value)}return r}),qs=h(3,(e,t,n)=>je(e).reduce((r,o,i)=>n(r,o,i),t)),xi=BR,NT=h(2,(e,t)=>{let n=je(e);if(Fe(n)){let r=[xt(n)],o=hr(n);for(let i of o)if(r.every((a)=>!t(i,a)))r.push(i);return r}return[]}),ko=h(2,(e,t)=>je(e).join(t))});function CD(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 LT,DT,OD=(e)=>hl((t,n)=>t.length===n.length&&Eo(t).every((r,o)=>e(r,Us(n,o)))),kD,ED,Ot=(e)=>{let t=Object.create(ED);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=Br,t.right=Br;break}case"ISingleton":{t.length=1,t.depth=0,t.left=Br,t.right=Br;break}case"ISlice":{t.length=e.length,t.depth=e.chunk.depth+1,t.left=Br,t.right=Br;break}}return t},qT=(e)=>H(e,LT),Br,Bn=()=>Br,Al=(...e)=>PD(e),St=(e)=>Ot({_tag:"ISingleton",a:e}),vp=(e)=>qT(e)?e:Pl(je(e)),dy=(e,t,n)=>{switch(e.backing._tag){case"IArray":{CD(e.backing.array,0,t,n,e.length);break}case"IConcat":{dy(e.left,t,n),dy(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]=Us(e,r),r+=1,o+=1;break}}},ID=(e)=>{switch(e.backing._tag){case"IEmpty":return DT;case"IArray":return e.backing.array;default:{let t=Array(e.length);return dy(e,t,0),e.backing={_tag:"IArray",array:t},e.left=Br,e.right=Br,e.depth=0,t}}},Eo,AD=(e)=>{switch(e.backing._tag){case"IEmpty":case"ISingleton":return e;case"IArray":return Ot({_tag:"IArray",array:sy(e.backing.array)});case"IConcat":return Ot({_tag:"IConcat",left:Si(e.backing.right),right:Si(e.backing.left)});case"ISlice":return Pl(sy(Eo(e)))}},Si,Pl=(e)=>e.length===0?Bn():e.length===1?St(e[0]):Ot({_tag:"IArray",array:e}),PD=(e)=>Pl(e),Us,UT,Yt,py,An,$T=(e)=>e.length===0,yr=(e)=>e.length>0,fy=(e)=>Us(e,0),xr,Sr=(e)=>py(e,1);var Vr=w(()=>{st();Re();gl();ne();Ge();at();Ne();Ae();LT=Symbol.for("effect/Chunk");DT=[],kD=OD(j),ED={[LT]:{_A:(e)=>e},toString(){return Ee(this.toJSON())},toJSON(){return{_id:"Chunk",values:Eo(this).map(Te)}},[me](){return this.toJSON()},[z](e){return qT(e)&&kD(this,e)},[J](){return xe(this,En(Eo(this)))},[Symbol.iterator](){switch(this.backing._tag){case"IArray":return this.backing.array[Symbol.iterator]();case"IEmpty":return DT[Symbol.iterator]();default:return Eo(this)[Symbol.iterator]()}},pipe(){return F(this,arguments)}},Br=Ot({_tag:"IEmpty"}),Eo=ID,Si=AD,Us=h(2,(e,t)=>{switch(e.backing._tag){case"IEmpty":throw Error("Index out of bounds");case"ISingleton":{if(t!==0)throw Error("Index out of bounds");return e.backing.a}case"IArray":{if(t>=e.length||t<0)throw Error("Index out of bounds");return e.backing.array[t]}case"IConcat":return t<e.left.length?Us(e.left,t):Us(e.right,t-e.left.length);case"ISlice":return Us(e.backing.chunk,t+e.backing.offset)}}),UT=h(2,(e,t)=>An(e,St(t))),Yt=h(2,(e,t)=>An(St(t),e)),py=h(2,(e,t)=>{if(t<=0)return e;else if(t>=e.length)return Br;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 py(e.right,t-e.left.length);return Ot({_tag:"IConcat",left:py(e.left,t),right:e.right})}default:return Ot({_tag:"ISlice",chunk:e,offset:t,length:e.length-t})}}),An=h(2,(e,t)=>{if(e.backing._tag==="IEmpty")return t;if(t.backing._tag==="IEmpty")return e;let n=t.depth-e.depth;if(Math.abs(n)<=1)return Ot({_tag:"IConcat",left:e,right:t});else if(n<-1)if(e.left.depth>=e.right.depth){let r=An(e.right,t);return Ot({_tag:"IConcat",left:e.left,right:r})}else{let r=An(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=An(e,t.left);return Ot({_tag:"IConcat",left:r,right:t.right})}else{let r=An(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})}}}),xr=fy});var bi=5,my,jT,HT,BT;var Rp=w(()=>{my=Math.pow(2,5),jT=my-1,HT=my/2,BT=my/4});function MD(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 wi(e,t){return t>>>e&jT}function _i(e){return 1<<e}function Tp(e,t){return MD(e&t-1)}var hy=w(()=>{Rp()});var VT=(e,t)=>({value:e,previous:t});function Ra(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 gy(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 WT(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 Ao{_tag="EmptyNode";modify(e,t,n,r,o,i){let a=n(B());if(Ye(a))return new Ao;return++i.value,new Ta(e,r,o,a)}}function Vn(e){return Sl(e,"EmptyNode")}function FD(e){return Vn(e)||e._tag==="LeafNode"||e._tag==="CollisionNode"}function Cp(e,t){return Vn(e)?!1:t===e.edit}class Ta{edit;hash;key;value;_tag="LeafNode";constructor(e,t,n,r){this.edit=e,this.hash=t,this.key=n,this.value=r}modify(e,t,n,r,o,i){if(j(o,this.key)){let s=n(this.value);if(s===this.value)return this;else if(Ye(s))return--i.value,new Ao;if(Cp(this,e))return this.value=s,this;return new Ta(e,r,o,s)}let a=n(B());if(Ye(a))return this;return++i.value,zT(e,t,this.hash,this,r,new Ta(e,r,o,a))}}class yy{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=Cp(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 yy(e,this.hash,c):c[0]}let a=n(B());if(Ye(a))return this;return++i.value,zT(e,t,this.hash,this,r,new Ta(e,r,o,a))}updateCollisionList(e,t,n,r,o,i,a){let s=r.length;for(let l=0;l<s;++l){let u=r[l];if("key"in u&&j(i,u.key)){let d=u.value,p=o(d);if(p===d)return r;if(Ye(p))return--a.value,gy(e,l,r);return Ra(e,l,new Ta(t,n,i,p),r)}}let c=o(B());if(Ye(c))return r;return++a.value,Ra(e,s,new Ta(t,n,i,c),r)}}class $s{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=wi(t,r),l=_i(c),u=Tp(a,l),d=a&l,p=Cp(this,e);if(!d){let x=new Ao().modify(e,t+bi,n,r,o,i);if(!x)return this;return s.length>=HT?DD(e,c,x,a,s):new $s(e,a|l,WT(p,u,x,s))}let m=s[u],f=m.modify(e,t+bi,n,r,o,i);if(m===f)return this;let y=a,g;if(Vn(f)){if(y&=~l,!y)return new Ao;if(s.length<=2&&FD(s[u^1]))return s[u^1];g=gy(p,u,s)}else g=Ra(p,u,f,s);if(p)return this.mask=y,this.children=g,this;return new $s(e,y,g)}}class xy{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=wi(t,r),l=s[c],u=(l||new Ao).modify(e,t+bi,n,r,o,i);if(l===u)return this;let d=Cp(this,e),p;if(Vn(l)&&!Vn(u))++a,p=Ra(d,c,u,s);else if(!Vn(l)&&Vn(u)){if(--a,a<=BT)return LD(e,a,c,s);p=Ra(d,c,new Ao,s)}else p=Ra(d,c,u,s);if(d)return this.size=a,this.children=p,this;return new xy(e,a,p)}}function LD(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&&!Vn(l))o[i++]=l,a|=1<<s}return new $s(e,a,o)}function DD(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 xy(e,s+1,i)}function qD(e,t,n,r,o,i){if(n===o)return new yy(e,n,[i,r]);let a=wi(t,n),s=wi(t,o);if(a===s)return(c)=>new $s(e,_i(a)|_i(s),[c]);else{let c=a<s?[r,i]:[i,r];return new $s(e,_i(a)|_i(s),c)}}function zT(e,t,n,r,o,i){let a=void 0,s=t;while(!0){let c=qD(e,s,n,r,o,i);if(typeof c==="function")a=VT(c,a),s=s+bi;else{let l=c;while(a!=null)l=a.value(l),a=a.previous;return l}}}var KT=w(()=>{Re();pt();Ae();hy();Rp()});var JT="effect/HashMap",Op,$D,Sy=(e,t,n,r)=>{let o=Object.create($D);return o._editable=e,o._edit=t,o._root=n,o._size=r,o},Ep,kp=(e)=>e?YT(e[0],e[1],e[2],e[3],e[4]):B(),GT=(e,t,n=void 0)=>{switch(e._tag){case"LeafNode":{if($e(e.value))return Y({value:t(e.key,e.value.value),cont:n});return kp(n)}case"CollisionNode":case"ArrayNode":case"IndexedNode":{let r=e.children;return YT(r.length,r,0,t,n)}default:return kp(n)}},YT=(e,t,n,r,o)=>{while(n<e){let i=t[n++];if(i&&!Vn(i))return GT(i,r,[e,t,n,r,o])}return kp(o)},jD,js=()=>jD,ZT=(e)=>{let t=Pp(js());for(let n of e)Ca(t,n[0],n[1]);return tC(t)},XT=(e)=>H(e,Op),QT=(e)=>e&&Vn(e._root),eC,Ip,by,Ca,HD,Ap=(e)=>new Ep(e,(t)=>t),Ml=(e)=>e._size,Pp=(e)=>Sy(!0,e._edit+1,e._root,e._size),tC=(e)=>(e._editable=!1,e),Mp,nC,Np,rC,wy,Hs;var _y=w(()=>{Re();ne();ne();Ge();at();pt();Ne();Ae();hy();Rp();KT();Op=Symbol.for(JT),$D={[Op]:Op,[Symbol.iterator](){return new Ep(this,(e,t)=>[e,t])},[J](){let e=U(JT);for(let t of this)e^=b(U(t[0]),le(U(t[1])));return xe(this,e)},[z](e){if(XT(e)){if(e._size!==this._size)return!1;for(let t of this){let n=b(e,Ip(t[0],U(t[0])));if(Ye(n))return!1;else if(!j(t[1],n.value))return!1}return!0}return!1},toString(){return Ee(this.toJSON())},toJSON(){return{_id:"HashMap",values:Array.from(this).map(Te)}},[me](){return this.toJSON()},pipe(){return F(this,arguments)}};Ep=class Ep{map;f;v;constructor(e,t){this.map=e,this.f=t,this.v=GT(this.map._root,this.f,void 0)}next(){if(Ye(this.v))return{done:!0,value:void 0};let e=this.v.value;return this.v=kp(e.cont),{done:!1,value:e.value}}[Symbol.iterator](){return new Ep(this.map,this.f)}};jD=Sy(!1,0,new Ao,0),eC=h(2,(e,t)=>Ip(e,t,U(t))),Ip=h(3,(e,t,n)=>{let r=e._root,o=0;while(!0)switch(r._tag){case"LeafNode":return j(t,r.key)?r.value:B();case"CollisionNode":{if(n===r.hash){let i=r.children;for(let a=0,s=i.length;a<s;++a){let c=i[a];if("key"in c&&j(t,c.key))return c.value}}return B()}case"IndexedNode":{let i=wi(o,n),a=_i(i);if(r.mask&a){r=r.children[Tp(r.mask,a)],o+=bi;break}return B()}case"ArrayNode":{if(r=r.children[wi(o,n)],r){o+=bi;break}return B()}default:return B()}}),by=h(2,(e,t)=>$e(Ip(e,t,U(t)))),Ca=h(3,(e,t,n)=>Mp(e,t,()=>Y(n))),HD=h(3,(e,t,n)=>{if(e._editable)return e._root=t,e._size=n,e;return t===e._root?e:Sy(e._editable,e._edit,t,n)}),Mp=h(3,(e,t,n)=>nC(e,t,U(t),n)),nC=h(4,(e,t,n,r)=>{let o={value:e._size},i=e._root.modify(e._editable?e._edit:NaN,0,r,n,t,o);return b(e,HD(i,o.value))}),Np=h(2,(e,t)=>Mp(e,t,B)),rC=h(2,(e,t)=>Hs(e,js(),(n,r,o)=>Ca(n,o,t(r,o)))),wy=h(2,(e,t)=>Hs(e,void 0,(n,r,o)=>t(r,o))),Hs=h(3,(e,t,n)=>{let r=e._root;if(r._tag==="LeafNode")return $e(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&&!Vn(c))if(c._tag==="LeafNode"){if($e(c.value))t=n(t,c.value.value,c.key)}else o.push(c.children)}return t})});var iC="effect/HashSet",Fp,BD,Lp=(e)=>{let t=Object.create(BD);return t._keyMap=e,t},aC=(e)=>H(e,Fp),VD,Nl=()=>VD,sC=(e)=>{let t=Dp(Nl());for(let n of e)Bs(t,n);return qp(t)},cC=(...e)=>{let t=Dp(Nl());for(let n of e)Bs(t,n);return qp(t)},lC,uC=(e)=>Ml(e._keyMap),Dp=(e)=>Lp(Pp(e._keyMap)),qp=(e)=>(e._keyMap._editable=!1,e),vy,Bs,Ry,dC,pC,fC,mC;var hC=w(()=>{Re();ne();Ge();at();Ne();Ae();_y();Fp=Symbol.for(iC),BD={[Fp]:Fp,[Symbol.iterator](){return Ap(this._keyMap)},[J](){return xe(this,le(U(this._keyMap))(U(iC)))},[z](e){if(aC(e))return Ml(this._keyMap)===Ml(e._keyMap)&&j(this._keyMap,e._keyMap);return!1},toString(){return Ee(this.toJSON())},toJSON(){return{_id:"HashSet",values:Array.from(this).map(Te)}},[me](){return this.toJSON()},pipe(){return F(this,arguments)}},VD=Lp(js()),lC=h(2,(e,t)=>by(e._keyMap,t)),vy=h(2,(e,t)=>{let n=Dp(e);return t(n),qp(n)}),Bs=h(2,(e,t)=>e._keyMap._editable?(Ca(t,!0)(e._keyMap),e):Lp(Ca(t,!0)(e._keyMap))),Ry=h(2,(e,t)=>e._keyMap._editable?(Np(t)(e._keyMap),e):Lp(Np(t)(e._keyMap))),dC=h(2,(e,t)=>vy(e,(n)=>{for(let r of t)Ry(n,r)})),pC=h(2,(e,t)=>vy(Nl(),(n)=>{fC(e,(r)=>Bs(n,r));for(let r of t)Bs(n,r)})),fC=h(2,(e,t)=>wy(e._keyMap,(n,r)=>t(r))),mC=h(3,(e,t,n)=>Hs(e._keyMap,t,(r,o,i)=>n(r,i)))});var Wr,gC,Oa,yC,Fl,ka,Ty,Cy,Po,Ea;var Ia=w(()=>{hC();Wr=Nl,gC=sC,Oa=cC,yC=lC,Fl=uC,ka=Bs,Ty=Ry,Cy=dC,Po=pC,Ea=mC});var Ws="Die",vi="Empty",Ri="Fail",Aa="Interrupt",Pa="Parallel",Ma="Sequential";var bC="effect/Cause",Ey,KD,zs,Mo,Ks=(e)=>{let t=Object.create(zs);return t._tag=Ri,t.error=e,t},Pn=(e)=>{let t=Object.create(zs);return t._tag=Ws,t.defect=e,t},br=(e)=>{let t=Object.create(zs);return t._tag=Aa,t.fiberId=e,t},La=(e,t)=>{let n=Object.create(zs);return n._tag=Pa,n.left=e,n.right=t,n},Zt=(e,t)=>{let n=Object.create(zs);return n._tag=Ma,n.left=e,n.right=t,n},wC=(e)=>H(e,Ey),Iy=(e)=>e._tag===vi,_C=(e)=>e._tag===Ri,Up=(e)=>{if(e._tag===vi)return!0;return Na(e,!0,(t,n)=>{switch(n._tag){case vi:return Y(t);case Ws:case Ri:case Aa:return Y(!1);default:return B()}})},$p=(e)=>$e(vC(e)),Js=(e)=>Bp(void 0,ZD)(e),Ay=(e)=>Si(Na(e,Bn(),(t,n)=>n._tag===Ri?Y(b(t,Yt(n.error))):B())),Py=(e)=>Si(Na(e,Bn(),(t,n)=>n._tag===Ws?Y(b(t,Yt(n.defect))):B())),My=(e)=>Na(e,Wr(),(t,n)=>n._tag===Aa?Y(b(t,ka(n.fiberId))):B()),Ny=(e)=>Fy(e,(t)=>t._tag===Ri?Y(t.error):B()),jp=(e)=>{let t=Ny(e);switch(t._tag){case"None":return ue(e);case"Some":return ce(t.value)}},vC=(e)=>Fy(e,(t)=>t._tag===Aa?Y(t.fiberId):B()),Hp=(e)=>Ly(e,{onEmpty:Mo,onFail:()=>Mo,onDie:Pn,onInterrupt:br,onSequential:Zt,onParallel:La}),RC=(e)=>Ly(e,{onEmpty:Mo,onFail:Pn,onDie:Pn,onInterrupt:br,onSequential:Zt,onParallel:La}),JD=(e,t)=>{let n=St(e),r=St(t);while(yr(n)&&yr(r)){let[o,i]=b(xr(n),Na([Wr(),Bn()],([c,l],u)=>{let[d,p]=Oy(u);return Y([b(c,Po(d)),b(l,An(p))])})),[a,s]=b(xr(r),Na([Wr(),Bn()],([c,l],u)=>{let[d,p]=Oy(u);return Y([b(c,Po(d)),b(l,An(p))])}));if(!j(o,a))return!1;n=i,r=s}return!0},GD=(e)=>YD(St(e),Bn()),YD=(e,t)=>{while(!0){let[n,r]=b(e,qs([Wr(),Bn()],([i,a],s)=>{let[c,l]=Oy(s);return[b(i,Po(c)),b(a,An(l))]})),o=Fl(n)>0?b(t,Yt(n)):t;if($T(r))return Si(o);e=r,t=o}throw Error(ya("Cause.flattenCauseLoop"))},Fy,Oy=(e)=>{let t=e,n=[],r=Wr(),o=Bn();while(t!==void 0)switch(t._tag){case vi:{if(n.length===0)return[r,o];t=n.pop();break}case Ri:{if(r=ka(r,Al(t._tag,t.error)),n.length===0)return[r,o];t=n.pop();break}case Ws:{if(r=ka(r,Al(t._tag,t.defect)),n.length===0)return[r,o];t=n.pop();break}case Aa:{if(r=ka(r,Al(t._tag,t.fiberId)),n.length===0)return[r,o];t=n.pop();break}case Ma:{switch(t.left._tag){case vi:{t=t.right;break}case Ma:{t=Zt(t.left.left,Zt(t.left.right,t.right));break}case Pa:{t=La(Zt(t.left.left,t.right),Zt(t.left.right,t.right));break}default:{o=Yt(o,t.right),t=t.left;break}}break}case Pa:{n.push(t.right),t=t.left;break}}throw Error(ya("Cause.evaluateCauseLoop"))},ZD,xC="SequentialCase",SC="ParallelCase",Ly,Na,Bp,wr=(e,t)=>{if(Js(e))return"All fibers interrupted without errors.";return Ll(e).map(function(n){if(t?.renderErrorCause!==!0||n.cause===void 0)return n.stack;return`${n.stack} {
10
- ${TC(n.cause," ")}
11
- }`}).join(`
12
- `)},TC=(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
- ${TC(e.cause,`${t} `)}
16
- ${t}}`;return r},ky=(e)=>{let t=typeof e==="object"&&e!==null,n=Error.stackTraceLimit;Error.stackTraceLimit=1;let r=Error(XD(e),t&&"cause"in e&&typeof e.cause<"u"?{cause:ky(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(Fa in e)r.span=e[Fa];Object.keys(e).forEach((o)=>{if(!(o in r))r[o]=e[o]})}return r.stack=tq(`${r.name}: ${r.message}`,e instanceof Error&&e.stack?e.stack:"",r.span),r},XD=(e)=>{if(typeof e==="string")return e;if(typeof e==="object"&&e!==null&&e instanceof Error)return e.message;try{if(H(e,"toString")&&pi(e.toString)&&e.toString!==Object.prototype.toString&&e.toString!==globalThis.Array.prototype.toString)return e.toString()}catch{}return fp(e)},QD,eq,tq=(e,t,n)=>{let r=[e],o=t.startsWith(e)?t.slice(e.length).split(`
17
- `):t.split(`
18
- `);for(let i=1;i<o.length;i++){if(o[i].includes(" at new BaseEffectError")||o[i].includes(" at new YieldableError")){i++;continue}if(o[i].includes("Generator.next"))break;if(o[i].includes("effect_internal_function"))break;r.push(o[i].replace(/at .*effect_instruction_i.*\((.*)\)/,"at $1").replace(/EffectPrimitive\.\w+/,"<anonymous>"))}if(n){let i=n,a=0;while(i&&i._tag==="Span"&&a<10){let s=eq.get(i);if(typeof s==="function"){let c=s();if(typeof c==="string"){let l=c.matchAll(QD),u=!1;for(let[,d]of l)u=!0,r.push(` at ${i.name} (${d})`);if(!u)r.push(` at ${i.name} (${c.replace(/^at /,"")})`)}else r.push(` at ${i.name}`)}else r.push(` at ${i.name}`);i=gn(i.parent),a++}}return r.join(`
19
- `)},Fa,Ll=(e)=>Bp(e,void 0,{emptyCase:()=>[],dieCase:(t,n)=>[ky(n)],failCase:(t,n)=>[ky(n)],interruptCase:()=>[],parallelCase:(t,n,r)=>[...n,...r],sequentialCase:(t,n,r)=>[...n,...r]});var Gs=w(()=>{st();Vr();hn();Re();ne();Ge();Ia();at();pt();Ne();Ae();Ey=Symbol.for(bC),KD={_E:(e)=>e},zs={[Ey]:KD,[J](){return b(U(bC),le(U(GD(this))),xe(this))},[z](e){return wC(e)&&JD(this,e)},pipe(){return F(this,arguments)},toJSON(){switch(this._tag){case"Empty":return{_id:"Cause",_tag:this._tag};case"Die":return{_id:"Cause",_tag:this._tag,defect:Te(this.defect)};case"Interrupt":return{_id:"Cause",_tag:this._tag,fiberId:this.fiberId.toJSON()};case"Fail":return{_id:"Cause",_tag:this._tag,failure:Te(this.error)};case"Sequential":case"Parallel":return{_id:"Cause",_tag:this._tag,left:Te(this.left),right:Te(this.right)}}},toString(){return wr(this)},[me](){return this.toJSON()}},Mo=(()=>{let e=Object.create(zs);return e._tag=vi,e})(),Fy=h(2,(e,t)=>{let n=[e];while(n.length>0){let r=n.pop(),o=t(r);switch(o._tag){case"None":{switch(r._tag){case Ma:case Pa:{n.push(r.right),n.push(r.left);break}}break}case"Some":return o}}return B()}),ZD={emptyCase:pl,failCase:ui,dieCase:ui,interruptCase:pl,sequentialCase:(e,t,n)=>t&&n,parallelCase:(e,t,n)=>t&&n},Ly=h(2,(e,{onDie:t,onEmpty:n,onFail:r,onInterrupt:o,onParallel:i,onSequential:a})=>Bp(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)})),Na=h(3,(e,t,n)=>{let r=t,o=e,i=[];while(o!==void 0){let a=n(r,o);switch(r=$e(a)?a.value:r,o._tag){case Ma:{i.push(o.right),o=o.left;break}case Pa:{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}),Bp=h(3,(e,t,n)=>{let r=[e],o=[];while(r.length>0){let a=r.pop();switch(a._tag){case vi:{o.push(ue(n.emptyCase(t)));break}case Ri:{o.push(ue(n.failCase(t,a.error)));break}case Ws:{o.push(ue(n.dieCase(t,a.defect)));break}case Aa:{o.push(ue(n.interruptCase(t,a.fiberId)));break}case Ma:{r.push(a.right),r.push(a.left),o.push(ce({_tag:xC}));break}case Pa:{r.push(a.right),r.push(a.left),o.push(ce({_tag:SC}));break}}}let i=[];while(o.length>0){let a=o.pop();switch(a._tag){case"Left":{switch(a.left._tag){case xC:{let s=i.pop(),c=i.pop(),l=n.sequentialCase(t,s,c);i.push(l);break}case SC:{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()}),QD=/\((.*)\)/g,eq=re("effect/Tracer/spanToTrace",()=>new WeakMap),Fa=Symbol.for("effect/SpanAnnotation")});var CC,ql,nq="effect/STM",rq,OC,oq,kC=(e)=>{let t=Error.stackTraceLimit;Error.stackTraceLimit=2;let n=Error();Error.stackTraceLimit=t;let r=Object.create(OC);return Object.defineProperty(r,"stack",{get(){return n.stack}}),r.key=e,r},EC=()=>(e,t)=>{let n=Error.stackTraceLimit;Error.stackTraceLimit=2;let r=Error();Error.stackTraceLimit=n;function o(){}return Object.setPrototypeOf(o,oq),o.key=e,o.defaultValue=t.defaultValue,Object.defineProperty(o,"stack",{get(){return r.stack}}),o},qy,iq,Ti=(e)=>{let t=Object.create(iq);return t.unsafeMap=e,t},aq=(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(`
9
+ ${o(u)}}`;g=a(l,y)}}return r.delete(l),g}return String(l)}return c(e,0)}function Lo(e){return typeof e==="string"?JSON.stringify(e):String(e)}function QS(e){return e.map((t)=>`[${Lo(t)}]`).join("")}function Ek(e){try{return e.toISOString()}catch{return"Invalid Date"}}function vk(e){try{let t=e.toString();return typeof t==="string"?t:String(t)}catch{return"[toString threw]"}}function XS(e,t){try{return e[t]}catch{return"[property access threw]"}}function ls(e,t){let n=[];return JSON.stringify(e,function(r,i){let o=Object.getOwnPropertyDescriptor(this,r)?.value,a=we(o,cs)?Do(o):Do(i);if(typeof a==="bigint")return Te(a);if(typeof a!=="object"||a===null)return a;let s=a instanceof Error&&!we(a,"toJSON")?{...a,name:a.name,message:a.message}:a;while(n.length>0&&n[n.length-1]!==this)n.pop();if(n.includes(a))return;if(n.push(a),s!==a)n.push(s);return s},t?.space)??"null"}var xk="[Circular]";var Pr=L(()=>{$t();Ll()});var Bi,oi=(e)=>{try{if(e=Do(e),we(e,"toJSON")&&os(e.toJSON)&&e.toJSON.length===0)return e.toJSON();else if(Array.isArray(e))return e.map(oi);return e}catch{return"[toJSON threw]"}},ex=(e,t=2)=>{if(typeof e==="string")return e;try{return typeof e==="object"?ls(e,{space:t}):Te(e,{space:t})}catch{return String(e)}},vL;var Uo=L(()=>{Pr();$t();Ll();Bi=Symbol.for("nodejs.util.inspect.custom"),vL={toJSON(){return oi(this)},[Bi](){return this.toJSON()},toString(){return Te(this.toJSON())}}});var bk=()=>{let e=Object.getOwnPropertyDescriptor(Error,"stackTraceLimit");if(e===void 0)return Object.isExtensible(Error);return Object.hasOwn(e,"writable")?e.writable===!0:e.set!==void 0},_k,$o=()=>Error.stackTraceLimit,jo=(e)=>{if(_k)Error.stackTraceLimit=e};var Ul=L(()=>{_k=bk()});class Vi{constructor(e){this.value=e,this.done=!1}next(e){if(this.done)return this.value=e,this;return this.done=!0,{value:this.value,done:!1}}}var wk=()=>{let t={["~effect/Utils/internal"]:(i)=>i()},n={["~effect/Utils/internal"]:(i)=>{try{return i()}finally{}}};return $o()!==0&&t["~effect/Utils/internal"](()=>Error().stack)?.includes("~effect/Utils/internal")===!0?t["~effect/Utils/internal"]:n["~effect/Utils/internal"]},us;var fs=L(()=>{Ul();us=wk()});function Or(e,t,n){if(t==="__proto__")Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0});else e[t]=n}function tx(e,t){for(let n of Reflect.ownKeys(t))if(Object.prototype.propertyIsEnumerable.call(t,n))Or(e,n,t[n])}function kk(e){return ar("Effect.evaluate: Not implemented")}var ai="~effect/Effect",qi="~effect/Exit",Ck,rx,ie,Be,tt,fn,zi,Ji,Wi,AL,Tk,ds=(e)=>we(e,ai),ix=(e)=>we(e,qi),jl="~effect/Cause",$l="~effect/Cause/Reason",ps=(e)=>we(e,jl),Ar,nx,ms,gs,hs,Bo=(e)=>new Ar(e),Zd,ox=(e)=>new Ar([new hs(e)]),Xd,Bl=(e)=>new Ar([new Xd(e)]),ys,si=(e)=>e._tag==="Fail",Qd=(e)=>e._tag==="Die",Vl=(e)=>e._tag==="Interrupt",dn=(e)=>({...Tk,[rx]:e.op,[Be]:e[Be]??kk,[tt]:e[tt],[fn]:e[fn],[zi]:e[zi]}),or=(e)=>{let t=dn(e),n=function(r){this[ie]=r};return n.prototype=t,function(r){return new n(r)}},ax=(e)=>{let t={[qi]:qi,_tag:e.op,get[e.prop](){return this[ie]},...dn(e),toString(){return`${e.op}(${Te(this[ie])})`},toJSON(){return{_id:"Exit",_tag:e.op,[e.prop]:this[ie]}},[et](r){return ix(r)&&r._tag===this._tag&&mt(this[ie],r[ie])},[Qe](){return pt(jt(e.op),Ce(this[ie]))}},n=function(r){this[ie]=r};return n.prototype=t,function(r){return new n(r)}},gt,ql,ep,$n,Vo=(e)=>$n(ox(e)),ar=(e)=>$n(Bl(e)),Bt,ML,Rk,sx,qo=(e)=>{class t extends sx{_tag=e}return t.prototype.name=e,t},Yd="~effect/Cause/Done",NL;var sr=L(()=>{ji();Pr();ln();ii();Uo();Ir();$t();fs();Ck={_A:Xe,_E:Xe,_R:Xe},rx=`${ai}/identifier`,ie=`${ai}/args`,Be=`${ai}/evaluate`,tt=`${ai}/successCont`,fn=`${ai}/failureCont`,zi=`${ai}/ensureCont`,Ji=Symbol.for("effect/Effect/Yield"),Wi={pipe(){return en(this,arguments)},toJSON(){return{...this}},toString(){return Te(this.toJSON(),{ignoreToString:!0,space:2})},[Bi](){return this.toJSON()}},AL={[Qe](){return Jd(this,Object.keys(this))},[et](e){let t=Object.keys(this),n=Object.keys(e);if(t.length!==n.length)return!1;for(let r=0;r<t.length;r++)if(t[r]!==n[r]||!mt(this[t[r]],e[t[r]]))return!1;return!0}},Tk={[ai]:Ck,...Wi,[Symbol.iterator](){return new Vi(this)},toJSON(){return{_id:"Effect",op:this[rx],...ie in this?{args:this[ie]}:void 0}}};Ar=class Ar{constructor(e){this[jl]=jl,this.reasons=e}pipe(){return en(this,arguments)}toJSON(){return{_id:"Cause",failures:this.reasons.map((e)=>e.toJSON())}}toString(){return`Cause(${Te(this.reasons)})`}[Bi](){return this.toJSON()}[et](e){return ps(e)&&this.reasons.length===e.reasons.length&&this.reasons.every((t,n)=>mt(t,e.reasons[n]))}[Qe](){return Dl(this.reasons)}};nx=new WeakMap;ms=class ms{[$l];annotations;_tag;constructor(e,t,n){if(this[$l]=$l,this._tag=e,t!==gs&&typeof n==="object"&&n!==null&&t.size>0){let r=nx.get(n);if(r)t=new Map([...r,...t]);nx.set(n,t)}this.annotations=t}annotate(e,t){if(e.mapUnsafe.size===0)return this;let n=new Map(this.annotations);e.mapUnsafe.forEach((i,o)=>{if(t?.overwrite!==!0&&n.has(o))return;n.set(o,i)});let r=Object.assign(Object.create(Object.getPrototypeOf(this)),this);return r.annotations=n,r}pipe(){return en(this,arguments)}toString(){return Te(this)}[Bi](){return this.toString()}};gs=new Map;hs=class hs extends ms{constructor(e,t=gs){super("Fail",t,e);this.error=e}toString(){return`Fail(${Te(this.error)})`}toJSON(){return{_tag:"Fail",error:this.error}}[et](e){return si(e)&&mt(this.error,e.error)&&mt(this.annotations,e.annotations)}[Qe](){return pt(jt(this._tag))(pt(Ce(this.error))(Ce(this.annotations)))}};Zd=new Ar([]);Xd=class Xd extends ms{constructor(e,t=gs){super("Die",t,e);this.defect=e}toString(){return`Die(${Te(this.defect)})`}toJSON(){return{_tag:"Die",defect:this.defect}}[et](e){return Qd(e)&&mt(this.defect,e.defect)&&mt(this.annotations,e.annotations)}[Qe](){return pt(jt(this._tag))(pt(Ce(this.defect))(Ce(this.annotations)))}};ys=Y((e)=>ps(e[0]),(e,t,n)=>{if(t.mapUnsafe.size===0)return e;return new Ar(e.reasons.map((r)=>r.annotate(t,n)))});gt=ax({op:"Success",prop:"value",[Be](e){let t=e.getCont(tt);return t?t[tt](this[ie],e,this):e.yieldWith(this)}}),ql={key:"effect/Cause/StackTrace"},ep={key:"effect/Cause/InterruptorStackTrace"},$n=ax({op:"Failure",prop:"cause",[Be](e){let t=this[ie],n=!1;if(e.cache.stackFrame)t=ys(t,{mapUnsafe:new Map([[ql.key,e.cache.stackFrame]])}),n=!0;let r=e.getCont(fn);while(e.interruptible&&e._interruptedCause&&r)r=e.getCont(fn);return r?r[fn](t,e,n?void 0:this):e.yieldWith(n?$n(t):this)}}),Bt=or({op:"WithFiber",[Be](e){return this[ie](e)}}),ML=or({op:"WithFiberSucceed",[Be](e){let t=this[ie](e),n=e.getCont(tt);return n?n[tt](t,e):e.yieldWith(gt(t))}}),Rk=function(){class e extends globalThis.Error{}let t=dn({op:"YieldableError",[Be](){return Vo(this)}});return delete t.toString,Object.assign(e.prototype,t),e}(),sx=function(){let e=Symbol.for("effect/Data/Error/plainArgs");return class extends Rk{constructor(n){super(n?.message,n?.cause?{cause:n.cause}:void 0);if(n)tx(this,n),Object.defineProperty(this,e,{value:n,enumerable:!1})}toJSON(){return{...this[e],...this}}}}(),NL={[Yd]:Yd,_tag:"Done",value:void 0}});var cx=(e)=>dn({op:e.label,[Be]:e.evaluate});var lx=L(()=>{sr()});var ux="~effect/Option",fx,Pk,Ok,Ak,np=(e)=>we(e,ux),rp=(e)=>e._tag==="None",dx=(e)=>e._tag==="Some",px,mx=function(e){this.value=e},gx=(e)=>new mx(e);var hx=L(()=>{ji();Pr();ii();Uo();$t();fs();sr();fx={[ux]:{_A:(e)=>e},...Wi,[Symbol.iterator](){return new Vi(this)}},Pk=Object.defineProperty(Object.assign(Object.create(fx),{_tag:"Some",_op:"Some",[et](e){return np(e)&&dx(e)&&mt(this.value,e.value)},[Qe](){return pt(Ce(this._tag))(Ce(this.value))},toString(){return`some(${Te(this.value)})`},toJSON(){return{_id:"Option",_tag:this._tag,value:oi(this.value)}}}),"valueOrUndefined",{get(){return this.value}}),Ok=Ce("None"),Ak=Object.assign(Object.create(fx),{_tag:"None",_op:"None",valueOrUndefined:void 0,[et](e){return np(e)&&rp(e)},[Qe](){return Ok},toString(){return"none()"},toJSON(){return{_id:"Option",_tag:this._tag}}}),px=Object.create(Ak);mx.prototype=Pk});var yx="~effect/Result",Sx,Nk,Dk,ip=(e)=>we(e,yx),op=(e)=>e._tag==="Failure",ap=(e)=>e._tag==="Success",xx=function(e){this.failure=e},Ex=(e)=>new xx(e),vx=function(e){this.success=e},bx=(e)=>new vx(e);var _x=L(()=>{ji();Pr();ii();Uo();$t();fs();sr();Sx={[yx]:{_A:(e)=>e,_E:(e)=>e},...Wi,[Symbol.iterator](){return new Vi(this)}},Nk=Object.assign(Object.create(Sx),{_tag:"Success",_op:"Success",[et](e){return ip(e)&&ap(e)&&mt(this.success,e.success)},[Qe](){return pt(Ce(this._tag))(Ce(this.success))},toString(){return`success(${Te(this.success)})`},toJSON(){return{_id:"Result",_tag:this._tag,value:oi(this.success)}}}),Dk=Object.assign(Object.create(Sx),{_tag:"Failure",_op:"Failure",[et](e){return ip(e)&&op(e)&&mt(this.failure,e.failure)},[Qe](){return pt(Ce(this._tag))(Ce(this.failure))},toString(){return`failure(${Te(this.failure)})`},toJSON(){return{_id:"Result",_tag:this._tag,failure:oi(this.failure)}}});xx.prototype=Dk;vx.prototype=Nk});function wx(e){return(t,n)=>t===n?0:e(t,n)}var zo,Cx,zl=(e)=>Y(2,(t,n)=>e(t,n)===1),Tx=(e)=>Y(2,(t,n)=>e(t,n)!==1),kx=(e)=>Y(2,(t,n)=>e(t,n)!==-1);var sp=L(()=>{ln();zo=wx((e,t)=>{if(globalThis.Number.isNaN(e)&&globalThis.Number.isNaN(t))return 0;if(globalThis.Number.isNaN(e))return-1;if(globalThis.Number.isNaN(t))return 1;return e<t?-1:1}),Cx=Y(2,(e,t)=>wx((n,r)=>e(t(n),t(r))))});var Jo=()=>px,Wo,Ix;var Jl=L(()=>{hx();Wo=gx,Ix=rp});var Px="~effect/Context/Service",Ox=function(){function e(){}let t=e;Object.setPrototypeOf(t,Lk);let n=(r,i)=>{if(t.key=r,i?.defaultValue)t[up]=up,t.defaultValue=i.defaultValue;if(i?.make)t.make=i.make;if(i?.fiberCached)Ax.add(r);return t};return arguments.length>0?n(arguments[0],arguments[1]):n},Lk,Ax,up="~effect/Context/Reference",Mx="~effect/Context",Uk=8,$k=8,fp=(e,t,n,r)=>{let i=Object.create(jk);return i.cacheRoot=e??i,i.base=t,i.overlay=n,i.depth=r,i._flat=void 0,i.baseHits=0,i},Nx=(e,t)=>{if(!t)return;Nx(e,t.parent),e.set(t.key,t.value)},Dx=(e)=>{if(e._flat)return e._flat;if(!e.overlay)return e._flat=e.base;let t=new Map(e.base);return Nx(t,e.overlay),e._flat=t},dp,Fx=(e,t)=>{let n=e;for(let i=n.overlay;i;i=i.parent)if(i.key===t)return i.value;let r=n.base.get(t);if(r===void 0&&!n.base.has(t))return dp;if(n.overlay&&++n.baseHits>=n.base.size&&n.baseHits>=$k)n.base=Dx(n),n.overlay=void 0,n.depth=0;return r},Wl=(e)=>fp(void 0,e,void 0,0),jk,Lx=(e,t)=>e.cacheRoot===t.cacheRoot,Bk=(e)=>we(e,Mx),Vk=(e)=>!!e[up],Ho=()=>qk,qk,pp=(e,t)=>Wl(new Map([[e.key,t]])),Ux,zk=(e,t,n)=>{let r=e,i=Ax.has(t)?void 0:r.cacheRoot;if(r.depth>=Uk){let o=new Map(r.mapUnsafe);return o.set(t,n),fp(i,o,void 0,0)}return fp(i,r.base,{key:t,value:n,parent:r.overlay},r.depth+1)},Hl=(e,t)=>{let n=Fx(e,t);return n===dp?void 0:n},$x,wn,lp="~effect/Context/defaultValue",Jk=(e)=>{if(lp in e)return e[lp];return e[lp]=e.defaultValue()},Wk=(e)=>{let t=Error(`Service not found${e.key?`: ${String(e.key)}`:""}`);if(t.stack){let n=t.stack.split(`
21
10
  `);n.splice(1,3),t.stack=n.join(`
22
- `)}return t},IC=(e)=>H(e,qy),AC=(e)=>H(e,ql),sq,PC=()=>sq,Uy=(e,t)=>Ti(new Map([[e.key,t]])),MC,Dy,$y=(e)=>{if(Dy.has(e.key))return Dy.get(e.key);let t=e.defaultValue();return Dy.set(e.key,t),t},NC=(e,t)=>e.unsafeMap.has(t.key)?e.unsafeMap.get(t.key):$y(t),jy,FC,LC,DC;var Vp=w(()=>{Re();ne();Ge();at();Ne();Ae();vo();zg();CC=Symbol.for("effect/Context/Tag"),ql=Symbol.for("effect/Context/Reference"),rq=Symbol.for(nq),OC={..._o,_op:"Tag",[rq]:mi,[CC]:{_Service:(e)=>e,_Identifier:(e)=>e},toString(){return Ee(this.toJSON())},toJSON(){return{_id:"Tag",key:this.key,stack:this.stack}},[me](){return this.toJSON()},of(e){return e},context(e){return Uy(this,e)}},oq={...OC,[ql]:ql},qy=Symbol.for("effect/Context"),iq={[qy]:{_Services:(e)=>e},[z](e){if(IC(e)){if(this.unsafeMap.size===e.unsafeMap.size){for(let t of this.unsafeMap.keys())if(!e.unsafeMap.has(t)||!j(this.unsafeMap.get(t),e.unsafeMap.get(t)))return!1;return!0}}return!1},[J](){return xe(this,up(this.unsafeMap.size))},pipe(){return F(this,arguments)},toString(){return Ee(this.toJSON())},toJSON(){return{_id:"Context",services:Array.from(this.unsafeMap).map(Te)}},[me](){return this.toJSON()}},sq=Ti(new Map),MC=h(3,(e,t,n)=>{let r=new Map(e.unsafeMap);return r.set(t.key,n),Ti(r)}),Dy=re("effect/Context/defaultValueCache",()=>new Map),jy=h(2,(e,t)=>{if(!e.unsafeMap.has(t.key)){if(ql in t)return $y(t);throw aq(t)}return e.unsafeMap.get(t.key)}),FC=jy,LC=h(2,(e,t)=>{if(!e.unsafeMap.has(t.key))return AC(t)?kl($y(t)):gp;return kl(e.unsafeMap.get(t.key))}),DC=h(2,(e,t)=>{let n=new Map(e.unsafeMap);for(let[r,o]of t.unsafeMap)n.set(r,o);return Ti(n)})});var yn,Ci,UC,zr,Ul,$l,Oi,jl,Hl;var Wn=w(()=>{Vp();yn=kC,Ci=PC,UC=Uy,zr=MC,Ul=FC,$l=jy,Oi=LC,jl=DC,Hl=EC});var By,VC,$C,Wp,Vy,jC,HC,cq,No=(e)=>{if(WC(e))return e;else if(kn(e))return zp(e);else if(di(e))return Hy(e);else if(Array.isArray(e)&&e.length===2&&e.every(kn)){if(e[0]===-1/0||e[1]===-1/0||Number.isNaN(e[0])||Number.isNaN(e[1]))return Wy;if(e[0]===1/0||e[1]===1/0)return pq;return Hy(BigInt(Math.round(e[0]*1e9))+BigInt(Math.round(e[1])))}else if(Ut(e)){let t=cq.exec(e);if(t){let[n,r,o]=t,i=Number(r);switch(o){case"nano":case"nanos":return Hy(BigInt(r));case"micro":case"micros":return fq(BigInt(r));case"milli":case"millis":return zp(i);case"second":case"seconds":return mq(i);case"minute":case"minutes":return hq(i);case"hour":case"hours":return gq(i);case"day":case"days":return yq(i);case"week":case"weeks":return xq(i)}}}throw Error("Invalid DurationInput")},BC,lq,uq,Kr=(e)=>{let t=Object.create(uq);if(kn(e))if(isNaN(e)||e<=0)t.value=BC;else if(!Number.isFinite(e))t.value=lq;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<=VC)t.value=BC;else t.value={_tag:"Nanos",nanos:e};return t},WC=(e)=>H(e,By),dq=(e)=>{switch(e.value._tag){case"Millis":return e.value.millis===0;case"Nanos":return e.value.nanos===VC;case"Infinity":return!1}},Wy,pq,Hy=(e)=>Kr(e),fq=(e)=>Kr(e*Vy),zp=(e)=>Kr(e),mq=(e)=>Kr(e*1000),hq=(e)=>Kr(e*60000),gq=(e)=>Kr(e*3600000),yq=(e)=>Kr(e*86400000),xq=(e)=>Kr(e*604800000),Kp=(e)=>wq(e,{onMillis:(t)=>t,onNanos:(t)=>Number(t)/1e6}),Sq=(e)=>{let t=No(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))}},bq=(e)=>{let t=No(e);switch(t.value._tag){case"Infinity":return[1/0,0];case"Nanos":return[Number(t.value.nanos/HC),Number(t.value.nanos%HC)];case"Millis":return[Math.floor(t.value.millis/1000),Math.round(t.value.millis%1000*1e6)]}},wq,zy,_q=(e,t)=>zy(e,t,{onMillis:(n,r)=>n===r,onNanos:(n,r)=>n===r}),zC,KC,vq,Rq=(e)=>{let t=No(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=Sq(t),r=n/jC,o=r/Vy,i=o/Wp,a=i/Wp,s=a/$C;return{days:Number(s),hours:Number(a%$C),minutes:Number(i%Wp),seconds:Number(o%Wp),millis:Number(r%Vy),nanos:Number(n%jC)}},Tq=(e)=>{let t=No(e);if(t.value._tag==="Infinity")return"Infinity";if(dq(t))return"0";let n=Rq(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 Ky=w(()=>{Re();ne();Ge();at();Ne();Ae();By=Symbol.for("effect/Duration"),VC=BigInt(0),$C=BigInt(24),Wp=BigInt(60),Vy=BigInt(1000),jC=BigInt(1e6),HC=BigInt(1e9),cq=/^(-?\d+(?:\.\d+)?)\s+(nanos?|micros?|millis?|seconds?|minutes?|hours?|days?|weeks?)$/,BC={_tag:"Millis",millis:0},lq={_tag:"Infinity"},uq={[By]:By,[J](){return xe(this,dp(this.value))},[z](e){return WC(e)&&vq(this,e)},toString(){return`Duration(${Tq(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:bq(this)};case"Infinity":return{_id:"Duration",_tag:"Infinity"}}},[me](){return this.toJSON()},pipe(){return F(this,arguments)}},Wy=Kr(0),pq=Kr(1/0),wq=h(2,(e,t)=>{let n=No(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)}}),zy=h(3,(e,t,n)=>{let r=No(e),o=No(t);if(r.value._tag==="Infinity"||o.value._tag==="Infinity")return n.onMillis(Kp(r),Kp(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)}),zC=h(2,(e,t)=>zy(e,t,{onMillis:(n,r)=>n<=r,onNanos:(n,r)=>n<=r})),KC=h(2,(e,t)=>zy(e,t,{onMillis:(n,r)=>n>=r,onNanos:(n,r)=>n>=r})),vq=h(2,(e,t)=>_q(No(e),No(t)))});var GC,Cq,Jp=(e)=>{let t=Object.create(Cq);return t.current=e,t},Ys=(e)=>e.current,Gp;var Jy=w(()=>{ne();at();Ne();GC=Symbol.for("effect/MutableRef"),Cq={[GC]:GC,toString(){return Ee(this.toJSON())},toJSON(){return{_id:"MutableRef",current:Te(this.current)}},[me](){return this.toJSON()},pipe(){return F(this,arguments)}},Gp=h(2,(e,t)=>(e.current=t,e))});var Yy="effect/FiberId",Zs,Yp="None",Gy="Runtime",Oq="Composite",kq,XC,QC,eO,Zy=(e)=>H(e,Zs),Zp=(e)=>{switch(e._tag){case Yp:return Wr();case Gy:return Oa(e.id);case Oq:return b(Zp(e.left),Po(Zp(e.right)))}},ZC,Xp=(e)=>Array.from(Zp(e)).map((n)=>`#${n}`).join(","),tO=()=>{let e=Ys(ZC);return b(ZC,Gp(e+1)),new QC(e,Date.now())};var Xy=w(()=>{Re();ne();Ge();Ia();at();Jy();Ae();Zs=Symbol.for(Yy),kq=ke(`${Yy}-${Yp}`);XC=class XC{[Zs]=Zs;_tag=Yp;id=-1;startTimeMillis=-1;[J](){return kq}[z](e){return Zy(e)&&e._tag===Yp}toString(){return Ee(this.toJSON())}toJSON(){return{_id:"FiberId",_tag:this._tag}}[me](){return this.toJSON()}};QC=class QC{id;startTimeMillis;[Zs]=Zs;_tag=Gy;constructor(e,t){this.id=e,this.startTimeMillis=t}[J](){return xe(this,ke(`${Yy}-${this._tag}-${this.id}-${this.startTimeMillis}`))}[z](e){return Zy(e)&&e._tag===Gy&&this.id===e.id&&this.startTimeMillis===e.startTimeMillis}toString(){return Ee(this.toJSON())}toJSON(){return{_id:"FiberId",_tag:this._tag,id:this.id,startTimeMillis:this.startTimeMillis}}[me](){return this.toJSON()}};eO=new XC,ZC=re(Symbol.for("effect/Fiber/Id/_fiberCounter"),()=>Jp(0))});var zn,rO,Qp;var Xs=w(()=>{Xy();zn=eO,rO=Xp,Qp=tO});var Qs,oO,iO,Qy,ex,tx,aO,sO,nx;var ef=w(()=>{_y();Qs=js,oO=ZT,iO=QT,Qy=eC,ex=Ca,tx=Ap,aO=Mp,sO=rC,nx=Hs});var Vl,ox=(e)=>je(e),Eq=(e)=>Pg(xi(e),ox),Iq,Aq,tf=(e,t)=>{let n=Object.create(Aq);return n.head=e,n.tail=t,n},Pq,Mq,cO,lO=(e)=>H(e,Vl),Jr=(e)=>e._tag==="Nil",ix=(e)=>e._tag==="Cons",Nq=()=>cO,Fo=(e,t)=>tf(e,t),ki,Wl=(e)=>tf(e,cO),uO,Fq,Lq,dO,pO=(e)=>{let t=ki(),n=e;while(!Jr(n))t=Fq(t,n.head),n=n.tail;return t};var nf=w(()=>{st();Re();gl();ne();Ge();at();Ne();Ae();Vl=Symbol.for("effect/List"),Iq=Eq(j),Aq={[Vl]:Vl,_tag:"Cons",toString(){return Ee(this.toJSON())},toJSON(){return{_id:"List",_tag:"Cons",values:ox(this).map(Te)}},[me](){return this.toJSON()},[z](e){return lO(e)&&this._tag===e._tag&&Iq(this,e)},[J](){return xe(this,En(ox(this)))},[Symbol.iterator](){let e=!1,t=this;return{next(){if(e)return this.return();if(t._tag==="Nil")return e=!0,this.return();let n=t.head;return t=t.tail,{done:e,value:n}},return(n){if(!e)e=!0;return{done:!0,value:n}}}},pipe(){return F(this,arguments)}},Pq=ke("Nil"),Mq={[Vl]:Vl,_tag:"Nil",toString(){return Ee(this.toJSON())},toJSON(){return{_id:"List",_tag:"Nil"}},[me](){return this.toJSON()},[J](){return Pq},[z](e){return lO(e)&&this._tag===e._tag},[Symbol.iterator](){return{next(){return{done:!0,value:void 0}}}},pipe(){return F(this,arguments)}},cO=Object.create(Mq),ki=Nq,uO=h(2,(e,t)=>Lq(t,e)),Fq=h(2,(e,t)=>Fo(t,e)),Lq=h(2,(e,t)=>{if(Jr(e))return t;else if(Jr(t))return e;else{let n=tf(t.head,e),r=n,o=t.tail;while(!Jr(o)){let i=tf(o.head,e);r.tail=i,r=i,o=o.tail}return n}}),dO=h(3,(e,t,n)=>{let r=t,o=e;while(!Jr(o))r=n(r,o.head),o=o.tail;return r})});var WY,ec;var rf=w(()=>{Re();Ge();vo();WY=Object.assign(Object.create(Array.prototype),{[J](){return xe(this,En(this))},[z](e){if(Array.isArray(e)&&this.length===e.length)return this.every((t,n)=>j(t,e[n]));else return!1}}),ec=function(){function e(t){if(t)Object.assign(this,t)}return e.prototype=Ol,e}()});function fO(e){return e}var qq,Kl,Uq,$q,sx=()=>$q,jq,Hq=(e,t)=>{let n=Object.create(jq);return n.first=e,n.second=t,n},Bq,Vq=(e,t)=>{let n=Object.create(Bq);return n.key=e,n.service=t,n},Wq,zq=(e)=>{let t=Object.create(Wq);return t.key=e,t},Kq,Jq=(e,t)=>{let n=Object.create(Kq);return n.key=e,n.update=t,n},mO=(e,t)=>{let n=new Map(e.unsafeMap),r=sx();for(let[o,i]of t.unsafeMap.entries())if(n.has(o)){let a=n.get(o);if(n.delete(o),!j(a,i))r=zl(Jq(o,()=>i))(r)}else n.delete(o),r=zl(Vq(o,i))(r);for(let[o]of n.entries())r=zl(zq(o))(r);return r},zl,hO;var gO=w(()=>{Vr();Re();ne();Vp();rf();qq=Symbol.for("effect/DifferContextPatch");Kl={...ec.prototype,[qq]:{_Value:fO,_Patch:fO}},Uq=Object.assign(Object.create(Kl),{_tag:"Empty"}),$q=Object.create(Uq),jq=Object.assign(Object.create(Kl),{_tag:"AndThen"}),Bq=Object.assign(Object.create(Kl),{_tag:"AddService"}),Wq=Object.assign(Object.create(Kl),{_tag:"RemoveService"}),Kq=Object.assign(Object.create(Kl),{_tag:"UpdateService"}),zl=h(2,(e,t)=>Hq(e,t)),hO=h(2,(e,t)=>{if(e._tag==="Empty")return t;let n=!1,r=St(e),o=new Map(t.unsafeMap);while(yr(r)){let a=xr(r),s=Sr(r);switch(a._tag){case"Empty":{r=s;break}case"AddService":{o.set(a.key,a.service),r=s;break}case"AndThen":{r=Yt(Yt(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 Ti(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 Ti(i)})});function cx(e){return e}var Yq,af,Zq,Xq,lx=()=>Xq,Qq,eU=(e,t)=>{let n=Object.create(Qq);return n.first=e,n.second=t,n},tU,nU=(e)=>{let t=Object.create(tU);return t.value=e,t},rU,oU=(e)=>{let t=Object.create(rU);return t.value=e,t},yO=(e,t)=>{let[n,r]=Ea([e,lx()],([o,i],a)=>{if(yC(a)(o))return[Ty(a)(o),i];return[o,of(nU(a))(i)]})(t);return Ea(r,(o,i)=>of(oU(i))(o))(n)},of,xO;var SO=w(()=>{Vr();ne();Ia();rf();Yq=Symbol.for("effect/DifferHashSetPatch");af={...ec.prototype,[Yq]:{_Value:cx,_Key:cx,_Patch:cx}},Zq=Object.assign(Object.create(af),{_tag:"Empty"}),Xq=Object.create(Zq),Qq=Object.assign(Object.create(af),{_tag:"AndThen"}),tU=Object.assign(Object.create(af),{_tag:"Add"}),rU=Object.assign(Object.create(af),{_tag:"Remove"}),of=h(2,(e,t)=>eU(e,t)),xO=h(2,(e,t)=>{if(e._tag==="Empty")return t;let n=t,r=St(e);while(yr(r)){let o=xr(r),i=Sr(r);switch(o._tag){case"Empty":{r=i;break}case"AndThen":{r=Yt(o.first)(Yt(o.second)(i));break}case"Add":{n=ka(o.value)(n),r=i;break}case"Remove":n=Ty(o.value)(n),r=i}}return n})});function bO(e){return e}var aU,Gl,sU,cU,ux=()=>cU,lU,uU=(e,t)=>{let n=Object.create(lU);return n.first=e,n.second=t,n},dU,pU=(e)=>{let t=Object.create(dU);return t.values=e,t},fU,mU=(e,t)=>{let n=Object.create(fU);return n.from=e,n.until=t,n},hU,gU=(e,t)=>{let n=Object.create(hU);return n.index=e,n.patch=t,n},wO=(e)=>{let t=0,n=ux();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(!j(i,e.differ.empty))n=Jl(n,gU(t,i));t=t+1}if(t<e.oldValue.length)n=Jl(n,mU(0,t));if(t<e.newValue.length)n=Jl(n,pU(PT(t)(e.newValue)));return n},Jl,_O;var vO=w(()=>{st();Re();ne();rf();aU=Symbol.for("effect/DifferReadonlyArrayPatch");Gl={...ec.prototype,[aU]:{_Value:bO,_Patch:bO}},sU=Object.assign(Object.create(Gl),{_tag:"Empty"}),cU=Object.create(sU),lU=Object.assign(Object.create(Gl),{_tag:"AndThen"}),dU=Object.assign(Object.create(Gl),{_tag:"Append"}),fU=Object.assign(Object.create(Gl),{_tag:"Slice"}),hU=Object.assign(Object.create(Gl),{_tag:"Update"}),Jl=h(2,(e,t)=>uU(e,t)),_O=h(3,(e,t,n)=>{if(e._tag==="Empty")return t;let r=t.slice(),o=Gt(e);while(gi(o)){let i=xt(o),a=hr(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 RO,xU,Ei=(e)=>{let t=Object.create(xU);return t.empty=e.empty,t.diff=e.diff,t.combine=e.combine,t.patch=e.patch,t},dx=()=>Ei({empty:sx(),combine:(e,t)=>zl(t)(e),diff:(e,t)=>mO(e,t),patch:(e,t)=>hO(t)(e)}),px=()=>Ei({empty:lx(),combine:(e,t)=>of(t)(e),diff:(e,t)=>yO(e,t),patch:(e,t)=>xO(t)(e)}),fx=(e)=>Ei({empty:ux(),combine:(t,n)=>Jl(t,n),diff:(t,n)=>wO({oldValue:t,newValue:n,differ:e}),patch:(t,n)=>_O(t,n,e)}),sf=()=>TO((e,t)=>t),TO=(e)=>Ei({empty:ve,combine:(t,n)=>{if(t===ve)return n;if(n===ve)return t;return(r)=>n(t(r))},diff:(t,n)=>{if(j(t,n))return ve;return dl(n)},patch:(t,n)=>e(n,t(n))});var cf=w(()=>{Re();ne();Ne();gO();SO();vO();RO=Symbol.for("effect/Differ"),xU={[RO]:{_P:ve,_V:ve},pipe(){return F(this,arguments)}}});var Yl=255,CO=8,lf=(e)=>e&Yl,uf=(e)=>e>>CO&Yl,Da=(e,t)=>(e&Yl)+((t&e&Yl)<<CO),hx,OO=(e)=>Da(e,e),kO=(e)=>Da(e,0),EO,gx,IO=(e)=>~e>>>0&Yl;var yx=w(()=>{ne();hx=Da(0,0),EO=h(2,(e,t)=>Da(lf(e)&~t,uf(e))),gx=h(2,(e,t)=>e|t)});var SU=0,Lo=1,PO=2,xx=4,df=16,Sx=32,MO=(e)=>pf(e,Sx),bx,Do=(e)=>wx(e)&&!bU(e),wx=(e)=>pf(e,Lo),pf,_x=(...e)=>e.reduce((t,n)=>t|n,0),NO,vx=(e)=>pf(e,xx),bU=(e)=>pf(e,df),Zl,Xl,Rx;var Ql=w(()=>{ne();cf();yx();bx=h(2,(e,t)=>e|t),pf=h(2,(e,t)=>(e&t)!==0),NO=_x(SU),Zl=h(2,(e,t)=>Da(e^t,t)),Xl=h(2,(e,t)=>e&(IO(lf(t))|uf(t))|lf(t)&uf(t)),Rx=Ei({empty:hx,diff:(e,t)=>Zl(e,t),combine:(e,t)=>gx(t)(e),patch:(e,t)=>Xl(t,e)})});var FO,Cx,Ox;var kx=w(()=>{yx();FO=OO,Cx=kO,Ox=EO});var Ix=(e,t)=>({_tag:"Par",left:e,right:t}),ff=(e,t)=>({_tag:"Seq",left:e,right:t}),DO=(e)=>{let t=Wl(e),n=ki();while(!0){let[r,o]=dO(t,[qO(),ki()],([i,a],s)=>{let[c,l]=wU(s);return[CU(i,c),uO(a,l)]});if(n=_U(n,r),Jr(o))return pO(n);t=o}throw Error("BUG: BlockedRequests.flatten - please report an issue at https://github.com/Effect-TS/effect/issues")},wU=(e)=>{let t=e,n=qO(),r=ki(),o=ki();while(!0)switch(t._tag){case"Empty":{if(Jr(r))return[n,o];t=r.head,r=r.tail;break}case"Par":{r=Fo(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=Ix(ff(s,a),ff(c,a));break}case"Seq":{let{left:s,right:c}=i;t=ff(s,ff(c,a));break}case"Single":{t=i,o=Fo(a,o);break}}break}case"Single":{if(n=TU(n,t),Jr(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")},_U=(e,t)=>{if(Jr(e))return Wl(Ex(t));if(OU(t))return e;let n=MU(e.head),r=kU(t);if(n.length===1&&r.length===1&&j(n[0],r[0]))return Fo(PU(e.head,Ex(t)),e.tail);return Fo(Ex(t),e)},vU,RU,mf,qO=()=>new mf(Qs()),TU=(e,t)=>new mf(aO(e.map,t.dataSource,(n)=>ST(fr(n,UT(t.blockedRequest)),()=>St(t.blockedRequest)))),CU=(e,t)=>new mf(nx(e.map,t.map,(n,r,o)=>ex(n,o,dt(Qy(n,o),{onNone:()=>r,onSome:(i)=>An(r,i)})))),OU=(e)=>iO(e.map),kU=(e)=>Array.from(tx(e.map)),Ex=(e)=>AU(sO(e.map,(t)=>St(t))),EU,IU,Ax,AU=(e)=>new Ax(e),PU=(e,t)=>new Ax(nx(t.map,e.map,(n,r,o)=>ex(n,o,dt(Qy(n,o),{onNone:()=>Bn(),onSome:(i)=>An(i,r)})))),MU=(e)=>Array.from(tx(e.map)),UO=(e)=>Array.from(e.map);var $O=w(()=>{Vr();Re();ef();nf();pt();vU=Symbol.for("effect/RequestBlock/RequestBlockParallel"),RU={_R:(e)=>e};mf=class mf{map;[vU]=RU;constructor(e){this.map=e}};EU=Symbol.for("effect/RequestBlock/RequestBlockSequential"),IU={_R:(e)=>e};Ax=class Ax{map;[EU]=IU;constructor(e){this.map=e}}});var tc="Pending",hf="Done";var FU="effect/Deferred",HO,BO,VO=(e)=>({_tag:tc,joiners:e}),WO=(e)=>({_tag:hf,effect:e});var zO=w(()=>{HO=Symbol.for(FU),BO={_E:(e)=>e,_A:(e)=>e}});var nc;var KO=w(()=>{nc=class nc{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 nc(this.self)}}});class Fx{patch;op;_op=Tl;constructor(e,t){this.patch=e,this.op=t}}var xf=(e,t)=>{let n=new Nt("Blocked");return n.effect_instruction_i0=e,n.effect_instruction_i1=t,n},Nx=(e)=>{let t=new Nt("RunBlocked");return t.effect_instruction_i0=e,t},Ii,Nt,Lx,Dx,rc=(e)=>H(e,Ii),jt=(e)=>{let t=new Nt(hp);return t.effect_instruction_i0=e,t},nk,qo,Uo=(e)=>qo(e,void 0),qx=function(){let e=new Nt(wa);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(ya("you're not supposed to end up here"))}return e},eu=(e,t=zn)=>{let n=new Nt(ba),r=void 0;return n.effect_instruction_i0=(o)=>{r=e(o)},n.effect_instruction_i1=t,ou(n,(o)=>rc(r)?r:bt)},rk=(e,t=zn)=>He(()=>eu(e,t)),Ai=(e,t=zn)=>qx(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 Nt(ba);i.effect_instruction_i0=(c)=>{if(n=c,r)c(r)},i.effect_instruction_i1=t;let a=void 0,s=void 0;if(this.effect_instruction_i0.length!==1)s=new AbortController,a=$t(()=>this.effect_instruction_i0(o,s.signal));else a=$t(()=>this.effect_instruction_i0(o));return a||s?ou(i,(c)=>{if(s)s.abort();return a??bt}):i}),tu,JO,Sf=(e,t)=>{if($e(t))return new Proxy(e,{has(n,r){return r===Fa||r===JO||r in n},get(n,r){if(r===Fa)return t.value;if(r===JO)return e;return n[r]}});return e},bf=(e)=>rn(e)&&!(Fa in e)?jt((t)=>Xt(Pn(Sf(e,Lf(t))))):Xt(Pn(e)),Ux=(e)=>ok(()=>Pn(new VU(e))),qa=(e)=>oc(e,{onFailure:(t)=>Ce(ce(t)),onSuccess:(t)=>Ce(ue(t))}),Pi=(e)=>ik(e,{onFailure:Le,onSuccess:Ke}),Ft=(e)=>rn(e)&&!(Fa in e)?jt((t)=>Xt(Ks(Sf(e,Lf(t))))):Xt(Ks(e)),$x=(e)=>oe(Q(e),Ft),Xt=(e)=>{let t=new Lx(fn);return t.effect_instruction_i0=e,t},ok=(e)=>oe(Q(e),Xt),jx,nu=(e)=>jt((t)=>e(t.id())),oe,Hx=(e)=>{let t=new Nt("OnStep");return t.effect_instruction_i0=e,t},ru=(e)=>oe(e,ve),ik,Kn,oc,Jn,Ua,wf=(e)=>{let t=new Nt(_a);return t.effect_instruction_i0=FO(Lo),t.effect_instruction_i1=()=>e,t},ct,_f,$a,ic,ou,Ce=(e)=>{let t=new Dx(mn);return t.effect_instruction_i0=e,t},He=(e)=>{let t=new Nt(wa);return t.commit=e,t},Q=(e)=>{let t=new Nt(mp);return t.effect_instruction_i0=e,t},vf,Bx=(e)=>jt((t)=>{let n=t.getFiberRef(yf),r=b(n,Ue(()=>t.scope()));return e(Fi(yf,Y(r)))}),Rf=(e)=>{let t=new Nt(_a);return t.effect_instruction_i0=Cx(Lo),t.effect_instruction_i1=()=>e,t},Mi=(e)=>qx(e,function(){let t=new Nt(_a);return t.effect_instruction_i0=Cx(Lo),t.effect_instruction_i1=(n)=>wx(n)?$t(()=>this.effect_instruction_i0(wf)):$t(()=>this.effect_instruction_i0(Rf)),t}),bt,Vx=(e)=>{let t=new Nt(_a);return t.effect_instruction_i0=e,t.effect_instruction_i1=void 0,t},iu=(e)=>{let t=new Nt(Ms);return t.effect_instruction_i0=e.while,t.effect_instruction_i1=e.body,t.effect_instruction_i2=e.step,t},au=(e)=>{let t=new Nt(Fs);return typeof e?.priority<"u"?gk(t,e.priority):t},Tf,Cf,Ni,su,ak=(e)=>oe(jx,(t)=>b(e,cu(t))),cu,sk,ck,lk,Wx,zx,Kx,uk,dk,UU="effect/FiberRef",$U,jU,Of=(e)=>jt((t)=>Ke(t.getFiberRef(e))),ja,Px,HU,Fi,Ht=(e,t)=>Ha(e,{differ:sf(),fork:t?.fork??ve,join:t?.join}),pk=(e)=>{let t=px();return Ha(e,{differ:t,fork:t.empty})},BU=(e)=>{let t=fx(sf());return Ha(e,{differ:t,fork:t.empty})},kf=(e)=>{let t=dx();return Ha(e,{differ:t,fork:t.empty})},Ha=(e,t)=>({...hi,[$U]:jU,initial:e,commit(){return Of(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)}),fk=(e)=>Ha(e,{differ:Rx,fork:Rx.empty}),Ba,ac,Jx,mk,Gx,hk,gk,yk,xk,Sk,bk,lu,yf,uu,Ef,If,Af=(e,t)=>e.addFinalizer(()=>Uo(t)),Yx=(e,t)=>e.close(t),sc=(e,t)=>e.fork(t),Pf,Va=(e,t)=>{class n extends Pf{_tag=t}return Object.assign(n.prototype,e),n.prototype.name=t,n},GO,VU,Mx,_3,wk=(e)=>H(e,Mx),YO,WU,ZO,du,XO,v3,QO,R3,ek,T3,tk,zU,cc=(e)=>rc(e)&&("_tag"in e)&&(e._tag==="Success"||e._tag==="Failure"),Zx=(e)=>e._tag==="Success",_k,pu=(e)=>_k(e,void 0),Wa=(e,t)=>KU(e,t?.parallel?La:Zt),Xx=(e)=>Le(Pn(e)),fu=(e)=>Le(Ks(e)),Le=(e)=>{let t=new Lx(fn);return t.effect_instruction_i0=e,t},Qx=(e)=>Le(br(e)),gf,Mf,Ke=(e)=>{let t=new Dx(mn);return t.effect_instruction_i0=e,t},Gn,eS,KU=(e,t)=>{let n=vp(e);if(!yr(n))return B();return b(Sr(n),qs(b(xr(n),gf(St)),(r,o)=>b(r,eS(o,{onSuccess:(i,a)=>b(i,Yt(a)),onFailure:t}))),gf(Si),gf((r)=>Eo(r)),Y)},vk=(e)=>({...hi,[HO]:BO,state:Jp(VO([])),commit(){return Nf(this)},blockingOn:e}),Nf=(e)=>rk((t)=>{let n=Ys(e.state);switch(n._tag){case hf:return t(n.effect);case tc:return n.joiners.push(t),JU(e,t)}},e.blockingOn),Ff=(e,t)=>{let n=Ys(e.state);if(n._tag===tc){Gp(e.state,WO(t));for(let r=0,o=n.joiners.length;r<o;r++)n.joiners[r](t)}},JU=(e,t)=>Q(()=>{let n=Ys(e.state);if(n._tag===tc){let r=n.joiners.indexOf(t);if(r>=0)n.joiners.splice(r,1)}}),GU,Rk=()=>GU,za=(e)=>oe(Rk(),e),YU,tS,Lf=(e)=>{let t=e.currentSpan;return t!==void 0&&t._tag==="Span"?Y(t):B()};var wt=w(()=>{st();Vr();Wn();hn();Re();Xs();ne();Ge();ef();at();nf();Jy();pt();Ne();Ae();kx();fi();Gs();zO();cf();vo();Ql();KO();Ii=Symbol.for("effect/Effect");Nt=class Nt{_op;effect_instruction_i0=void 0;effect_instruction_i1=void 0;effect_instruction_i2=void 0;trace=void 0;[Ii]=mi;constructor(e){this._op=e}[z](e){return this===e}[J](){return xe(this,bl(this))}pipe(){return F(this,arguments)}toJSON(){return{_id:"Effect",_op:this._op,effect_instruction_i0:Te(this.effect_instruction_i0),effect_instruction_i1:Te(this.effect_instruction_i1),effect_instruction_i2:Te(this.effect_instruction_i2)}}toString(){return Ee(this.toJSON())}[me](){return this.toJSON()}[Symbol.iterator](){return new nc(new bo(this))}};Lx=class Lx{_op;effect_instruction_i0=void 0;effect_instruction_i1=void 0;effect_instruction_i2=void 0;trace=void 0;[Ii]=mi;constructor(e){this._op=e,this._tag=e}[z](e){return cc(e)&&e._op==="Failure"&&j(this.effect_instruction_i0,e.effect_instruction_i0)}[J](){return b(ke(this._tag),le(U(this.effect_instruction_i0)),xe(this))}get cause(){return this.effect_instruction_i0}pipe(){return F(this,arguments)}toJSON(){return{_id:"Exit",_tag:this._op,cause:this.cause.toJSON()}}toString(){return Ee(this.toJSON())}[me](){return this.toJSON()}[Symbol.iterator](){return new nc(new bo(this))}};Dx=class Dx{_op;effect_instruction_i0=void 0;effect_instruction_i1=void 0;effect_instruction_i2=void 0;trace=void 0;[Ii]=mi;constructor(e){this._op=e,this._tag=e}[z](e){return cc(e)&&e._op==="Success"&&j(this.effect_instruction_i0,e.effect_instruction_i0)}[J](){return b(ke(this._tag),le(U(this.effect_instruction_i0)),xe(this))}get value(){return this.effect_instruction_i0}pipe(){return F(this,arguments)}toJSON(){return{_id:"Exit",_tag:this._op,value:Te(this.value)}}toString(){return Ee(this.toJSON())}[me](){return this.toJSON()}[Symbol.iterator](){return new nc(new bo(this))}};nk=h(3,(e,t,n)=>Mi((r)=>oe(e,(o)=>oe(Pi(He(()=>r(t(o)))),(i)=>He(()=>n(o,i)).pipe(Kn({onFailure:(a)=>{switch(i._tag){case fn:return Xt(Zt(i.effect_instruction_i0,a));case mn:return Xt(a)}},onSuccess:()=>i})))))),qo=h(2,(e,t)=>oe(e,()=>Ce(t))),tu=h(2,(e,t)=>oc(e,{onFailure:t,onSuccess:Ce})),JO=Symbol.for("effect/OriginalAnnotation"),jx=jt((e)=>Ce(e.id())),oe=h(2,(e,t)=>{let n=new Nt(As);return n.effect_instruction_i0=e,n.effect_instruction_i1=t,n}),ik=h(2,(e,t)=>Kn(e,{onFailure:(n)=>Ce(t.onFailure(n)),onSuccess:(n)=>Ce(t.onSuccess(n))})),Kn=h(2,(e,t)=>{let n=new Nt(Ps);return n.effect_instruction_i0=e,n.effect_instruction_i1=t.onFailure,n.effect_instruction_i2=t.onSuccess,n}),oc=h(2,(e,t)=>Kn(e,{onFailure:(n)=>{if(Py(n).length>0)return Xt(RC(n));let o=Ay(n);if(o.length>0)return t.onFailure(fy(o));return Xt(n)},onSuccess:t.onSuccess})),Jn=h(2,(e,t)=>He(()=>{let n=je(e),r=va(n.length),o=0;return qo(iu({while:()=>o<n.length,body:()=>t(n[o],o),step:(i)=>{r[o++]=i}}),r)})),Ua=h(2,(e,t)=>He(()=>{let n=je(e),r=0;return iu({while:()=>r<n.length,body:()=>t(n[r],r),step:()=>{r++}})})),ct=h(2,(e,t)=>oe(e,(n)=>Q(()=>t(n)))),_f=h(2,(e,t)=>oc(e,{onFailure:(n)=>$x(()=>t.onFailure(n)),onSuccess:(n)=>Q(()=>t.onSuccess(n))})),$a=h(2,(e,t)=>Kn(e,{onFailure:(n)=>{let r=jp(n);switch(r._tag){case"Left":return $x(()=>t(r.left));case"Right":return Xt(r.right)}},onSuccess:Ce})),ic=h(2,(e,t)=>Mi((n)=>Kn(n(e),{onFailure:(r)=>{let o=Le(r);return Kn(t(o),{onFailure:(i)=>Le(Zt(r,i)),onSuccess:()=>o})},onSuccess:(r)=>{let o=Ke(r);return Ni(t(o),o)}}))),ou=h(2,(e,t)=>ic(e,Mf({onFailure:(n)=>Js(n)?Uo(t(My(n))):bt,onSuccess:()=>bt}))),vf=h((e)=>e.length===3||e.length===2&&!(rn(e[1])&&("onlyEffect"in e[1])),(e,t)=>oe(e,(n)=>{let r=typeof t==="function"?t(n):t;if(rc(r))return qo(r,n);else if(KR(r))return eu((o)=>{r.then((i)=>o(Ce(n)),(i)=>o(Ft(new zU(i,"An unknown error occurred in Effect.tap"))))});return Ce(n)})),bt=Ce(void 0),Tf=h(2,(e,t)=>oe(e,(n)=>ct(t,(r)=>[n,r]))),Cf=h(2,(e,t)=>oe(e,(n)=>qo(t,n))),Ni=h(2,(e,t)=>oe(e,()=>t)),su=rk(()=>{let e=setInterval(()=>{},2147483647);return Q(()=>clearInterval(e))}),cu=h(2,(e,t)=>oe(e.interruptAsFork(t),()=>e.await)),sk={_tag:"All",syslog:0,label:"ALL",ordinal:Number.MIN_SAFE_INTEGER,pipe(){return F(this,arguments)}},ck={_tag:"Fatal",syslog:2,label:"FATAL",ordinal:50000,pipe(){return F(this,arguments)}},lk={_tag:"Error",syslog:3,label:"ERROR",ordinal:40000,pipe(){return F(this,arguments)}},Wx={_tag:"Warning",syslog:4,label:"WARN",ordinal:30000,pipe(){return F(this,arguments)}},zx={_tag:"Info",syslog:6,label:"INFO",ordinal:20000,pipe(){return F(this,arguments)}},Kx={_tag:"Debug",syslog:7,label:"DEBUG",ordinal:1e4,pipe(){return F(this,arguments)}},uk={_tag:"Trace",syslog:7,label:"TRACE",ordinal:0,pipe(){return F(this,arguments)}},dk={_tag:"None",syslog:7,label:"OFF",ordinal:Number.MAX_SAFE_INTEGER,pipe(){return F(this,arguments)}},$U=Symbol.for(UU),jU={_A:(e)=>e},ja=h(2,(e,t)=>oe(Of(e),t)),Px=h(2,(e,t)=>HU(e,()=>[void 0,t])),HU=h(2,(e,t)=>jt((n)=>{let[r,o]=t(n.getFiberRef(e));return n.setFiberRef(e,o),Ce(r)})),Fi=h(3,(e,t,n)=>nk(Cf(Of(t),Px(t,n)),()=>e,(r)=>Px(t,r))),Ba=re(Symbol.for("effect/FiberRef/currentContext"),()=>kf(Ci())),ac=re(Symbol.for("effect/FiberRef/currentSchedulingPriority"),()=>Ht(0)),Jx=re(Symbol.for("effect/FiberRef/currentMaxOpsBeforeYield"),()=>Ht(2048)),mk=re(Symbol.for("effect/FiberRef/currentLogAnnotation"),()=>Ht(Qs())),Gx=re(Symbol.for("effect/FiberRef/currentLogLevel"),()=>Ht(zx)),hk=re(Symbol.for("effect/FiberRef/currentLogSpan"),()=>Ht(ki())),gk=h(2,(e,t)=>Fi(e,ac,t)),yk=re(Symbol.for("effect/FiberRef/currentConcurrency"),()=>Ht("unbounded")),xk=re(Symbol.for("effect/FiberRef/currentRequestBatching"),()=>Ht(!0)),Sk=re(Symbol.for("effect/FiberRef/currentUnhandledErrorLogLevel"),()=>Ht(Y(Kx))),bk=re(Symbol.for("effect/FiberRef/versionMismatchErrorLogLevel"),()=>Ht(Y(Wx))),lu=re(Symbol.for("effect/FiberRef/currentMetricLabels"),()=>BU(Oo())),yf=re(Symbol.for("effect/FiberRef/currentForkScopeOverride"),()=>Ht(B(),{fork:()=>B(),join:(e,t)=>e})),uu=re(Symbol.for("effect/FiberRef/currentInterruptedCause"),()=>Ht(Mo,{fork:()=>Mo,join:(e,t)=>e})),Ef=Symbol.for("effect/Scope"),If=Symbol.for("effect/CloseableScope"),Pf=function(){class e extends globalThis.Error{commit(){return Ft(this)}toJSON(){let t={...this};if(this.message)t.message=this.message;if(this.cause)t.cause=this.cause;return t}[me](){if(this.toString!==globalThis.Error.prototype.toString)return this.stack?`${this.toString()}
23
- ${this.stack.split(`
24
- `).slice(1).join(`
25
- `)}`:this.toString();else if("Bun"in globalThis)return wr(Ks(this),{renderErrorCause:!0});return this}}return Object.assign(e.prototype,Hg),e}(),GO=Symbol.for("effect/Cause/errors/RuntimeException"),VU=Va({[GO]:GO},"RuntimeException"),Mx=Symbol.for("effect/Cause/errors/InterruptedException"),_3=Va({[Mx]:Mx},"InterruptedException"),YO=Symbol.for("effect/Cause/errors/IllegalArgument"),WU=Va({[YO]:YO},"IllegalArgumentException"),ZO=Symbol.for("effect/Cause/errors/NoSuchElement"),du=Va({[ZO]:ZO},"NoSuchElementException"),XO=Symbol.for("effect/Cause/errors/InvalidPubSubCapacityException"),v3=Va({[XO]:XO},"InvalidPubSubCapacityException"),QO=Symbol.for("effect/Cause/errors/ExceededCapacityException"),R3=Va({[QO]:QO},"ExceededCapacityException"),ek=Symbol.for("effect/Cause/errors/Timeout"),T3=Va({[ek]:ek},"TimeoutException"),tk=Symbol.for("effect/Cause/errors/UnknownException"),zU=function(){class e extends Pf{_tag="UnknownException";error;constructor(t,n){super(n??"An unknown error occurred",{cause:t});this.error=t}}return Object.assign(e.prototype,{[tk]:tk,name:"UnknownException"}),e}(),_k=h(2,(e,t)=>{switch(e._tag){case fn:return Le(e.effect_instruction_i0);case mn:return Ke(t)}}),gf=h(2,(e,t)=>{switch(e._tag){case fn:return Le(e.effect_instruction_i0);case mn:return Ke(t(e.effect_instruction_i0))}}),Mf=h(2,(e,{onFailure:t,onSuccess:n})=>{switch(e._tag){case fn:return t(e.effect_instruction_i0);case mn:return n(e.effect_instruction_i0)}}),Gn=Ke(void 0),eS=h(3,(e,t,{onFailure:n,onSuccess:r})=>{switch(e._tag){case fn:switch(t._tag){case mn:return Le(e.effect_instruction_i0);case fn:return Le(n(e.effect_instruction_i0,t.effect_instruction_i0))}case mn:switch(t._tag){case mn:return Ke(r(e.effect_instruction_i0,t.effect_instruction_i0));case fn:return Le(t.effect_instruction_i0)}}}),GU=jt((e)=>Ke(e.currentContext)),YU=h(2,(e,t)=>Fi(Ba,t)(e)),tS=h(2,(e,t)=>za((n)=>YU(e,t(n))))});var Tk,Ck;var Ok=w(()=>{Gs();Tk=_C,Ck=wr});var Df="And",qf="Or",Uf="InvalidData",$f="MissingData",jf="SourceUnavailable",Hf="Unsupported";var QU="effect/ConfigError",kk,lc,Bf=(e,t)=>{let n=Object.create(lc);return n._op=Df,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},Vf=(e,t)=>{let n=Object.create(lc);return n._op=qf,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},nS=(e,t,n={pathDelim:"."})=>{let r=Object.create(lc);return r._op=Uf,r.path=e,r.message=t,Object.defineProperty(r,"toString",{enumerable:!1,value(){return`(Invalid data at ${b(this.path,ko(n.pathDelim))}: "${this.message}")`}}),r},Gr=(e,t,n={pathDelim:"."})=>{let r=Object.create(lc);return r._op=$f,r.path=e,r.message=t,Object.defineProperty(r,"toString",{enumerable:!1,value(){return`(Missing data at ${b(this.path,ko(n.pathDelim))}: "${this.message}")`}}),r},rS=(e,t,n,r={pathDelim:"."})=>{let o=Object.create(lc);return o._op=jf,o.path=e,o.message=t,o.cause=n,Object.defineProperty(o,"toString",{enumerable:!1,value(){return`(Source unavailable at ${b(this.path,ko(r.pathDelim))}: "${this.message}")`}}),o},oS=(e,t,n={pathDelim:"."})=>{let r=Object.create(lc);return r._op=Hf,r.path=e,r.message=t,Object.defineProperty(r,"toString",{enumerable:!1,value(){return`(Unsupported operation at ${b(this.path,ko(n.pathDelim))}: "${this.message}")`}}),r},Li,Ek;var iS=w(()=>{st();hn();ne();kk=Symbol.for(QU),lc={_tag:"ConfigError",[kk]:kk},Li=h(2,(e,t)=>{switch(e._op){case Df:return Bf(Li(e.left,t),Li(e.right,t));case qf:return Vf(Li(e.left,t),Li(e.right,t));case Uf:return nS([...t,...e.path],e.message);case $f:return Gr([...t,...e.path],e.message);case jf:return rS([...t,...e.path],e.message,e.cause);case Hf:return oS([...t,...e.path],e.message)}}),Ek=h(3,(e,t,n)=>{let r=[e],o=[];while(r.length>0){let a=r.pop();switch(a._op){case Df:{r.push(a.right),r.push(a.left),o.push(ce({_op:"AndCase"}));break}case qf:{r.push(a.right),r.push(a.left),o.push(ce({_op:"OrCase"}));break}case Uf:{o.push(ue(n.invalidDataCase(t,a.path,a.message)));break}case $f:{o.push(ue(n.missingDataCase(t,a.path,a.message)));break}case jf:{o.push(ue(n.sourceUnavailableCase(t,a.path,a.message,a.cause)));break}case Hf:{o.push(ue(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 e$="effect/Clock",Ak,mu,t$=2147483647,Pk,Mk,n$,Nk,Fk=()=>new Nk;var aS=w(()=>{Wn();Ky();ne();wt();Ak=Symbol.for(e$),mu=yn("effect/Clock"),Pk={unsafeSchedule(e,t){let n=Kp(t);if(n>t$)return ui;let r=!1,o=setTimeout(()=>{r=!0,e()},n);return()=>(clearTimeout(o),!r)}},Mk=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))}}(),n$=function(){let e=typeof process==="object"&&"hrtime"in process&&typeof process.hrtime.bigint==="function"?process.hrtime:void 0;if(!e)return Mk;let t=Mk()-e.bigint();return()=>t+e.bigint()}();Nk=class Nk{[Ak]=Ak;unsafeCurrentTimeMillis(){return Date.now()}unsafeCurrentTimeNanos(){return n$()}currentTimeMillis=Q(()=>this.unsafeCurrentTimeMillis());currentTimeNanos=Q(()=>this.unsafeCurrentTimeNanos());scheduler(){return Ce(Pk)}sleep(e){return Ai((t)=>{let n=Pk.unsafeSchedule(()=>t(bt),e);return Uo(Q(n))})}}});var Yr;var hu=w(()=>{bp();Yr=xT});var uc=(e)=>e.replace(/[/\\^$*+?.()|[\]{}]/g,"\\$&");var sS=()=>{};var qk,zf;var Uk=w(()=>{st();hn();ne();nf();pt();iS();qk={_tag:"Empty"},zf=h(2,(e,t)=>{let n=Wl(t),r=e;while(ix(n)){let o=n.head;switch(o._tag){case"Empty":{n=n.tail;break}case"AndThen":{n=Fo(o.first,Fo(o.second,n.tail));break}case"MapName":{r=gr(r,o.f),n=n.tail;break}case"Nested":{r=Ls(r,o.name),n=n.tail;break}case"Unnested":{if(b(To(r),_T(o.name)))r=hr(r),n=n.tail;else return ce(Gr(r,`Expected ${o.name} to be in path in ConfigProvider#unnested`));break}}}return ue(r)})});var $k="Constant",jk="Fail",Hk="Fallback",Bk="Described",Vk="Lazy",Wk="MapOrFail",zk="Nested",Kk="Primitive",Jk="Redacted",Gk="Sequence",Yk="HashMap",Zk="ZipWith";var Kf=(e,t)=>[...e,...t],l$="effect/ConfigProvider",Xk,eE,u$="effect/ConfigProviderFlat",Qk,d$=(e)=>({[Xk]:Xk,pipe(){return F(this,arguments)},...e}),p$=(e)=>({[Qk]:Qk,patch:e.patch,load:(t,n,r=!0)=>e.load(t,n,r),enumerateChildren:e.enumerateChildren}),f$=(e)=>d$({load:(t)=>oe(Mn(e,Oo(),t,!1),(n)=>dt(To(n),{onNone:()=>Ft(Gr(Oo(),`Expected a single value having structure: ${t}`)),onSome:Ce})),flattened:e}),tE=(e)=>{let{pathDelim:t,seqDelim:n}=Object.assign({},{pathDelim:"_",seqDelim:","},e),r=(c)=>b(c,ko(t)),o=(c)=>c.split(t),i=()=>typeof process<"u"&&("env"in process)&&typeof process.env==="object"?process.env:{};return f$(p$({load:(c,l,u=!0)=>{let d=r(c),p=i(),m=d in p?Y(p[d]):B();return b(m,$a(()=>Gr(c,`Expected ${d} to exist in the process context`)),oe((f)=>b$(f,c,l,n,u)))},enumerateChildren:(c)=>Q(()=>{let l=i(),p=Object.keys(l).map((m)=>o(m.toUpperCase())).filter((m)=>{for(let f=0;f<c.length;f++){let y=b(c,iy(f)),g=m[f];if(g===void 0||y!==g)return!1}return!0}).flatMap((m)=>m.slice(c.length,c.length+1));return gC(p)}),patch:qk}))},m$=(e,t,n,r)=>{let o=ly(n.length,(c)=>c>=r.length?B():Y([e(c),c+1])),i=ly(r.length,(c)=>c>=n.length?B():Y([t(c),c+1])),a=Kf(n,o),s=Kf(r,i);return[a,s]},h$=(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},g$,y$=(e)=>Ek(e,void 0,g$),Mn=(e,t,n,r)=>{let o=n;switch(o._tag){case $k:return Ce(Gt(o.value));case Bk:return He(()=>Mn(e,t,o.config,r));case jk:return Ft(Gr(t,o.message));case Hk:return b(He(()=>Mn(e,t,o.first,r)),tu((i)=>{if(o.condition(i))return b(Mn(e,t,o.second,r),tu((a)=>Ft(Vf(i,a))));return Ft(i)}));case Vk:return He(()=>Mn(e,t,o.config(),r));case Wk:return He(()=>b(Mn(e,t,o.original,r),oe(Jn((i)=>b(o.mapOrFail(i),$a(Li(h$(t,o.original))))))));case zk:return He(()=>Mn(e,Kf(t,Gt(o.name)),o.config,r));case Kk:return b(zf(t,e.patch),oe((i)=>b(e.load(i,o,r),oe((a)=>{if(a.length===0){let s=b(IT(i),Ue(()=>"<n/a>"));return Ft(Gr([],`Expected ${o.description} with name ${s}`))}return Ce(a)}))));case Jk:return He(()=>b(Mn(e,t,o.original,r),$a(y$),ct(gr(o.redact))));case Gk:return b(zf(t,e.patch),oe((i)=>b(e.enumerateChildren(i),oe(_$),oe((a)=>{if(a.length===0)return He(()=>ct(Mn(e,t,o.config,!0),Gt));return b(Jn(a,(s)=>Mn(e,OT(t,`[${s}]`),o.config,!0)),ct((s)=>{let c=wp(s);if(c.length===0)return Gt(Oo());return Gt(c)}))}))));case Yk:return He(()=>b(zf(t,e.patch),oe((i)=>b(e.enumerateChildren(i),oe((a)=>b(a,Jn((s)=>Mn(e,Kf(i,Gt(s)),o.valueConfig,r)),ct((s)=>{if(s.length===0)return Gt(Qs());return b(w$(s),gr((c)=>oO(cy(je(a),c))))})))))));case Zk:return He(()=>b(Mn(e,t,o.left,r),qa,oe((i)=>b(Mn(e,t,o.right,r),qa,oe((a)=>{if(qe(i)&&qe(a))return Ft(Bf(i.left,a.left));if(qe(i)&&Ct(a))return Ft(i.left);if(Ct(i)&&qe(a))return Ft(a.left);if(Ct(i)&&Ct(a)){let s=b(t,ko(".")),c=x$(t,s),[l,u]=m$(c,c,b(i.right,gr(ue)),b(a.right,gr(ue)));return b(l,cy(u),Jn(([d,p])=>b(Tf(d,p),ct(([m,f])=>o.zip(m,f)))))}throw Error("BUG: ConfigProvider.fromFlatLoop - please report an issue at https://github.com/Effect-TS/effect/issues")})))))}},x$=(e,t)=>(n)=>ce(Gr(e,`The element at index ${n} in a sequence at path "${t}" was missing`)),S$=(e,t)=>e.split(new RegExp(`\\s*${uc(t)}\\s*`)),b$=(e,t,n,r,o)=>{if(!o)return b(n.parse(e),_f({onFailure:Li(t),onSuccess:Gt}));return b(S$(e,r),Jn((i)=>n.parse(i.trim())),$a(Li(t)))},w$=(e)=>Object.keys(e[0]).map((t)=>e.map((n)=>n[t])),_$=(e)=>b(Jn(e,R$),_f({onFailure:()=>Oo(),onSuccess:Co(Yr)}),qa,ct(hT)),v$,R$=(e)=>{let t=e.match(v$);if(t!==null){let n=t[2];return b(n!==void 0&&n.length>0?Y(n):B(),mr(T$))}return B()},T$=(e)=>{let t=Number.parseInt(e);return Number.isNaN(t)?B():Y(t)};var nE=w(()=>{st();Wn();hn();ne();ef();Ia();hu();pt();Ne();sS();iS();Uk();wt();Xk=Symbol.for(l$),eE=yn("effect/ConfigProvider"),Qk=Symbol.for(u$),g$={andCase:(e,t,n)=>Bf(t,n),orCase:(e,t,n)=>Vf(t,n),invalidDataCase:(e,t)=>nS(t,"<redacted>"),missingDataCase:(e,t)=>Gr(t,"<redacted>"),sourceUnavailableCase:(e,t,n,r)=>rS(t,"<redacted>",r),unsupportedCase:(e,t)=>oS(t,"<redacted>")},v$=/^(\[(\d+)\])$/});var rE,Jf,oE;var cS=w(()=>{Wn();wt();rE=Symbol.for("effect/Console"),Jf=yn("effect/Console"),oE={[rE]:rE,assert(e,...t){return Q(()=>{console.assert(e,...t)})},clear:Q(()=>{console.clear()}),count(e){return Q(()=>{console.count(e)})},countReset(e){return Q(()=>{console.countReset(e)})},debug(...e){return Q(()=>{console.debug(...e)})},dir(e,t){return Q(()=>{console.dir(e,t)})},dirxml(...e){return Q(()=>{console.dirxml(...e)})},error(...e){return Q(()=>{console.error(...e)})},group(e){return e?.collapsed?Q(()=>console.groupCollapsed(e?.label)):Q(()=>console.group(e?.label))},groupEnd:Q(()=>{console.groupEnd()}),info(...e){return Q(()=>{console.info(...e)})},log(...e){return Q(()=>{console.log(...e)})},table(e,t){return Q(()=>{console.table(e,t)})},time(e){return Q(()=>console.time(e))},timeEnd(e){return Q(()=>console.timeEnd(e))},timeLog(e,...t){return Q(()=>{console.timeLog(e,...t)})},trace(...e){return Q(()=>{console.trace(...e)})},warn(...e){return Q(()=>{console.warn(...e)})},unsafe:console}});var k$="effect/Random",iE,aE,sE,E$=(e,t)=>He(()=>b(Q(()=>Array.from(e)),oe((n)=>{let r=[];for(let o=n.length;o>=2;o=o-1)r.push(o);return b(r,Ua((o)=>b(t(o),ct((i)=>I$(n,o-1,i)))),qo(vp(n)))}))),I$=(e,t,n)=>{let r=e[t];return e[t]=e[n],e[n]=r,e},cE=(e)=>new sE(U(e));var lE=w(()=>{Vr();Wn();ne();Ge();fi();wt();iE=Symbol.for(k$),aE=yn("effect/Random");sE=class sE{seed;[iE]=iE;PRNG;constructor(e){this.seed=e,this.PRNG=new Lg(e)}get next(){return Q(()=>this.PRNG.number())}get nextBoolean(){return ct(this.next,(e)=>e>0.5)}get nextInt(){return Q(()=>this.PRNG.integer(Number.MAX_SAFE_INTEGER))}nextRange(e,t){return ct(this.next,(n)=>(t-e)*n+e)}nextIntBetween(e,t){return Q(()=>this.PRNG.integer(t-e)+e)}shuffle(e){return E$(e,(t)=>this.nextIntBetween(0,t))}}});class pE{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:dE(32),this.spanId=dE(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 uE,P$=(e)=>({[uE]:uE,...e}),gu,Gf,dE,fE,mE;var Yf=w(()=>{Wn();ne();uE=Symbol.for("effect/Tracer"),gu=yn("effect/Tracer"),Gf=yn("effect/ParentSpan"),dE=function(){return function(n){let r="";for(let o=0;o<n;o++)r+="abcdef0123456789".charAt(Math.floor(Math.random()*16));return r}}();fE=P$({span:(e,t,n,r,o,i)=>new pE(e,t,n,r,o,i),context:(e)=>e()}),mE=Hl()("effect/Tracer/DisablePropagation",{defaultValue:ui})});var F$,yu;var hE=w(()=>{Wn();ne();aS();nE();wt();cS();lE();Yf();F$=b(Ci(),zr(mu,Fk()),zr(Jf,oE),zr(aE,cE(Math.random())),zr(eE,tE()),zr(gu,fE)),yu=re(Symbol.for("effect/DefaultServices/currentServices"),()=>kf(F$))});var D$,gE=(e)=>{let t={BaseEffectError:class extends D${_tag=e}};return t.BaseEffectError.prototype.name=e,t.BaseEffectError};var yE=w(()=>{wt();D$=function(){let e=Symbol.for("effect/Data/Error/plainArgs");return{BaseEffectError:class extends Pf{constructor(n){super(n?.message,n?.cause?{cause:n.cause}:void 0);if(n)Object.assign(this,n),Object.defineProperty(this,e,{value:n,enumerable:!1})}toJSON(){return{...this[e],...this}}}}.BaseEffectError}()});var xE,q$,uS;var dS=w(()=>{vo();xE=_o,q$=iT;uS=class uS extends q${}});var bE="Sequential",wE="Parallel",U$="ParallelN",dc,_E,vE=(e)=>({_tag:U$,parallelism:e}),pS=(e)=>e._tag===bE,fS=(e)=>e._tag===wE;var Zf=w(()=>{dc={_tag:bE},_E={_tag:wE}});var Xf,Qf,em;var RE=w(()=>{Zf();Xf=dc,Qf=_E,em=vE});function TE(e){return new $o(e)}function CE(){return TE(new Map)}var hS,$o,j$=(e,t,n,r=!1)=>{let o=e,i=t,a=n,s=r,c=void 0;while(c===void 0)if(Fe(i)&&Fe(a)){let l=xt(i)[0],u=hr(i),d=xt(a)[0],p=xt(a)[1],m=hr(a);if(l.startTimeMillis<d.startTimeMillis)a=m,s=!0;else if(l.startTimeMillis>d.startTimeMillis)i=u;else if(l.id<d.id)a=m,s=!0;else if(l.id>d.id)i=u;else c=[p,s]}else c=[o.initial,!0];return c},yS,xS,OE=(e,t,n)=>{e.locals.forEach((r,o)=>{let i=r[0][1],a=o.patch(o.fork)(i);if(j(i,a))t.set(o,r);else t.set(o,[[n,a],...r])})},xu,SS,Di,pc,gS=(e,t,n,r)=>{let o=e.get(n)??[],i;if(Fe(o)){let[a,s]=xt(o);if(a[z](t))if(j(s,r))return;else i=[[t,r],...o.slice(1)];else i=[[t,r],...o]}else i=[[t,r]];e.set(n,i)},kE;var tm=w(()=>{st();Re();ne();pt();Ne();hS=Symbol.for("effect/FiberRefs");$o=class $o{locals;[hS]=hS;constructor(e){this.locals=e}pipe(){return F(this,arguments)}};yS=h(3,(e,t,n)=>{let r=new Map(e.locals);return n.locals.forEach((o,i)=>{let a=o[0][1];if(!o[0][0][z](t)){if(!r.has(i)){if(j(a,i.initial))return;r.set(i,[[t,i.join(i.initial,a)]]);return}let s=r.get(i),[c,l]=j$(i,s,o);if(l){let u=i.diff(c,a),d=s[0][1],p=i.join(d,i.patch(u)(d));if(!j(d,p)){let m,f=s[0][0];if(f[z](t))m=[[f,p],...s.slice(1)];else m=[[t,p],...s];r.set(i,m)}}}}),new $o(r)}),xS=h(2,(e,t)=>{let n=new Map;return OE(e,n,t),new $o(n)}),xu=h(2,(e,t)=>{let n=new Map(e.locals);return n.delete(t),new $o(n)}),SS=h(2,(e,t)=>{if(!e.locals.has(t))return B();return Y(xt(e.locals.get(t))[1])}),Di=h(2,(e,t)=>b(SS(e,t),Ue(()=>t.initial))),pc=h(2,(e,{fiberId:t,fiberRef:n,value:r})=>{if(e.locals.size===0)return new $o(new Map([[n,[[t,r]]]]));let o=new Map(e.locals);return gS(o,t,n,r),new $o(o)}),kE=h(2,(e,{entries:t,forkAs:n})=>{if(e.locals.size===0)return new $o(new Map(t));let r=new Map(e.locals);if(n!==void 0)OE(e,r,n);return t.forEach(([o,i])=>{if(i.length===1)gS(r,i[0][0],o,i[0][1]);else i.forEach(([a,s])=>{gS(r,a,o,s)})}),new $o(r)})});var EE,IE,AE;var wS=w(()=>{tm();EE=Di,IE=kE,AE=CE});var ME="Empty",NE="Add",FE="Remove",LE="Update",DE="AndThen",qE,UE=(e,t)=>{let n=new Map(e.locals),r=qE;for(let[o,i]of t.locals.entries()){let a=xt(i)[1],s=n.get(o);if(s!==void 0){let c=xt(s)[1];if(!j(c,a))r=nm({_tag:LE,fiberRef:o,patch:o.diff(c,a)})(r)}else r=nm({_tag:NE,fiberRef:o,value:a})(r);n.delete(o)}for(let[o]of n.entries())r=nm({_tag:FE,fiberRef:o})(r);return r},nm,$E;var jE=w(()=>{st();Re();ne();tm();qE={_tag:ME},nm=h(2,(e,t)=>({_tag:DE,first:e,second:t})),$E=h(3,(e,t,n)=>{let r=n,o=Gt(e);while(Fe(o)){let i=xt(o),a=hr(o);switch(i._tag){case ME:{o=a;break}case NE:{r=pc(r,{fiberId:t,fiberRef:i.fiberRef,value:i.value}),o=a;break}case FE:{r=xu(r,i.fiberRef),o=a;break}case LE:{let s=Di(r,i.fiberRef);r=pc(r,{fiberId:t,fiberRef:i.fiberRef,value:i.fiberRef.patch(i.patch)(s)}),o=a;break}case DE:{o=Ls(i.first)(Ls(i.second)(a));break}}}return r})});var HE,BE;var VE=w(()=>{jE();HE=UE,BE=$E});var om="effect/FiberStatus",qi,rm="Done",WE="Running",zE="Suspended",V$,KE,JE,GE,YE,ZE=(e)=>new JE(e),XE=(e,t)=>new GE(e,t),im=(e)=>H(e,qi),QE=(e)=>e._tag===rm;var eI=w(()=>{Re();ne();Ge();Ae();qi=Symbol.for(om),V$=ke(`${om}-${rm}`);KE=class KE{[qi]=qi;_tag=rm;[J](){return V$}[z](e){return im(e)&&e._tag===rm}};JE=class JE{runtimeFlags;[qi]=qi;_tag=WE;constructor(e){this.runtimeFlags=e}[J](){return b(U(om),le(U(this._tag)),le(U(this.runtimeFlags)),xe(this))}[z](e){return im(e)&&e._tag===WE&&this.runtimeFlags===e.runtimeFlags}};GE=class GE{runtimeFlags;blockingOn;[qi]=qi;_tag=zE;constructor(e,t){this.runtimeFlags=e,this.blockingOn=t}[J](){return b(U(om),le(U(this._tag)),le(U(this.runtimeFlags)),le(U(this.blockingOn)),xe(this))}[z](e){return im(e)&&e._tag===zE&&this.runtimeFlags===e.runtimeFlags&&j(this.blockingOn,e.blockingOn)}};YE=new KE});var tI,_S,nI,rI;var oI=w(()=>{eI();tI=YE,_S=ZE,nI=XE,rI=QE});var K$,J$,G$,Y$,Z$,X$,Q$,e2,t2,iI,aI=(e)=>{switch(e){case"All":return K$;case"Debug":return X$;case"Error":return G$;case"Fatal":return J$;case"Info":return Z$;case"Trace":return Q$;case"None":return e2;case"Warning":return Y$}};var sI=w(()=>{ne();wt();hu();bp();K$=sk,J$=ck,G$=lk,Y$=Wx,Z$=zx,X$=Kx,Q$=uk,e2=dk,t2=b(Yr,Sp((e)=>e.ordinal)),iI=Qg(t2)});function d2(e){return RS("Micro.evaluate: Not implemented")}class AS{tasks=[];running=!1;scheduleTask(e,t){if(this.tasks.push(e),!this.running)this.running=!0,x2(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(SI)}flush(){while(this.tasks.length>0)this.runTasks()}}var r2,sm,cI,o2,TS,dI,i2=(e,t=[])=>new dI(e,t),pI,a2=(e=[])=>new pI(e),s2=(e)=>e._tag==="Interrupt",lI,c2,fI,uI,mI,kt,vS,mc,fc,cm,am,l2,u2,um=(e)=>({...u2,[mI]:e.op,[vS]:e.eval??d2,[mc]:e.contA,[fc]:e.contE,[cm]:e.ensure}),CS=(e)=>{let t=um(e);return function(){let n=Object.create(t);return n[kt]=e.single===!1?arguments:arguments[0],n}},hI=(e)=>{let t={...um(e),[sm]:sm,_tag:e.op,get[e.prop](){return this[kt]},toJSON(){return{_id:"MicroExit",_tag:e.op,[e.prop]:this[kt]}},[z](n){return g2(n)&&n._tag===e.op&&j(this[kt],n[kt])},[J](){return xe(this,le(ke(e.op))(U(this[kt])))}};return function(n){let r=Object.create(t);return r[kt]=n,r[mc]=void 0,r[fc]=void 0,r[cm]=void 0,r}},OS,gI,p2,f2,m2,kS,lm,h2,g2=(e)=>H(e,sm),yI,ES,IS,RS=(e)=>ES(i2(e)),y2,x2,S2,xI,SI,dm,b2,w2,_2,bI,v2=(e)=>kS((t)=>{if(t.interruptible)return e;if(t.interruptible=!0,t._stack.push(bI(!1)),t._interrupted)return IS;return e}),R2=(e)=>kS((t)=>{if(!t.interruptible)return e(ve);return t.interruptible=!1,t._stack.push(bI(!0)),e(v2)}),wI=(e,t)=>{let n=new fI(dm.context(t?.scheduler??new AS));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 _I=w(()=>{Wn();dS();Re();ne();Ge();at();Vp();Ne();Ae();fi();r2=Symbol.for("effect/Micro"),sm=Symbol.for("effect/Micro/MicroExit"),cI=Symbol.for("effect/Micro/MicroCause"),o2={_E:ve};TS=class TS extends globalThis.Error{_tag;traces;[cI];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=wo(t,0),a=`${o}: ${i}`;if(n.length>0)a+=`
29
- ${n.join(`
30
- `)}`;super(i);this._tag=e,this.traces=n,this[cI]=o2,this.name=o,this.stack=a}pipe(){return F(this,arguments)}toString(){return this.stack}[me](){return this.stack}};dI=class dI extends TS{defect;constructor(e,t=[]){super("Die",e,t);this.defect=e}};pI=class pI extends TS{constructor(e=[]){super("Interrupt","interrupted",e)}};lI=Symbol.for("effect/Micro/MicroFiber"),c2={_A:ve,_E:ve};fI=class fI{context;interruptible;[lI];_stack=[];_observers=[];_exit;_children;currentOpCount=0;constructor(e,t=!0){this.context=e,this.interruptible=t,this[lI]=c2}getRef(e){return NC(this.context,e)}addObserver(e){if(this._exit)return e(this._exit),fl;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(IS)}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===am)return;let n=uI.interruptChildren&&uI.interruptChildren(this);if(n!==void 0)return this.evaluate(lm(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(dm).shouldYield(this)){t=!0;let r=n;n=lm(f2,()=>r)}if(n=n[vS](this),n===am){let r=this._yielded;if(sm in r)return this._yielded=void 0,r;return am}}}catch(r){if(!H(n,vS))return RS(`MicroFiber.runLoop: Not a valid effect: ${String(n)}`);return RS(r)}}getCont(e){while(!0){let t=this._stack.pop();if(!t)return;let n=t[cm]&&t[cm](this);if(n)return{[e]:n};if(t[e])return t}}_yielded=void 0;yieldWith(e){return this._yielded=e,am}children(){return this._children??=new Set}};uI=re("effect/Micro/fiberMiddleware",()=>({interruptChildren:void 0})),mI=Symbol.for("effect/Micro/identifier"),kt=Symbol.for("effect/Micro/args"),vS=Symbol.for("effect/Micro/evaluate"),mc=Symbol.for("effect/Micro/successCont"),fc=Symbol.for("effect/Micro/failureCont"),cm=Symbol.for("effect/Micro/ensureCont"),am=Symbol.for("effect/Micro/Yield"),l2={_A:ve,_E:ve,_R:ve},u2={...xE,_op:"Micro",[r2]:l2,pipe(){return F(this,arguments)},[Symbol.iterator](){return new Is(new bo(this))},toJSON(){return{_id:"Micro",op:this[mI],...kt in this?{args:this[kt]}:void 0}},toString(){return Ee(this)},[me](){return Ee(this)}};OS=hI({op:"Success",prop:"value",eval(e){let t=e.getCont(mc);return t?t[mc](this[kt],e):e.yieldWith(this)}}),gI=hI({op:"Failure",prop:"cause",eval(e){let t=e.getCont(fc);while(s2(this[kt])&&t&&e.interruptible)t=e.getCont(fc);return t?t[fc](this[kt],e):e.yieldWith(this)}}),p2=CS({op:"Yield",eval(e){let t=!1;return e.getRef(dm).scheduleTask(()=>{if(t)return;e.evaluate(y2)},this[kt]??0),e.yieldWith(()=>{t=!0})}}),f2=p2(0),m2=OS(void 0),kS=CS({op:"WithMicroFiber",eval(e){return this[kt](e)}}),lm=h(2,(e,t)=>{let n=Object.create(h2);return n[kt]=e,n[mc]=t,n}),h2=um({op:"OnSuccess",eval(e){return e._stack.push(this),this[kt]}}),yI=OS,ES=gI,IS=ES(a2()),y2=yI(void 0),x2="setImmediate"in globalThis?globalThis.setImmediate:(e)=>setTimeout(e,0);S2=h(2,(e,t)=>kS((n)=>{let r=n.context;return n.context=t(r),_2(e,()=>(n.context=r,m2))})),xI=h(2,(e,t)=>S2(e,jl(t)));SI=class SI extends Hl()("effect/Micro/currentMaxOpsBeforeYield",{defaultValue:()=>2048}){};dm=class dm extends Hl()("effect/Micro/currentScheduler",{defaultValue:()=>new AS}){};b2=h(2,(e,t)=>{let n=Object.create(w2);return n[kt]=e,n[mc]=t.onSuccess,n[fc]=t.onFailure,n}),w2=um({op:"OnSuccessAndFailure",eval(e){return e._stack.push(this),this[kt]}}),_2=h(2,(e,t)=>R2((n)=>b2(n(e),{onFailure:(r)=>lm(t(ES(r)),()=>gI(r)),onSuccess:(r)=>lm(t(yI(r)),()=>OS(r))}))),bI=CS({op:"SetInterruptible",ensure(e){if(e.interruptible=this[kt],e._interrupted&&e.interruptible)return()=>IS}})});class pm{scheduleDrain;running=!1;tasks=new PS;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 pm(e),n=new WeakMap;return(r)=>{if(r===void 0)return t;let o=n.get(r);if(o===void 0)o=new pm(e),n.set(r,o);return o}}}class PS{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 vI{maxNextTickBeforeTimer;getRunner=pm.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(Jx)?e.getFiberRef(ac):!1}scheduleTask(e,t,n){this.getRunner(n).scheduleTask(e,t)}}class Su{tasks=new PS;deferred=!1;scheduleTask(e,t,n){if(this.deferred)RI.scheduleTask(e,t,n);else this.tasks.scheduleTask(e,t)}shouldYield(e){return e.currentOpCount>e.getFiberRef(Jx)?e.getFiberRef(ac):!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 RI,fm;var mm=w(()=>{wt();RI=re(Symbol.for("effect/Scheduler/defaultScheduler"),()=>new vI(2048));fm=re(Symbol.for("effect/FiberRef/currentScheduler"),()=>Ht(RI))});var hm;var MS=w(()=>{wt();hm=re(Symbol.for("effect/FiberRef/currentRequestMap"),()=>Ht(new Map))});var NS=(e,t,n,r)=>{switch(e){case void 0:return t();case"unbounded":return n();case"inherit":return ja(yk,(o)=>o==="unbounded"?n():o>1?r(o):t());default:return e>1?r(e):t()}};var CI=w(()=>{wt()});var FS=(e)=>e.replace(/[\s="]/g,"_"),OI=(e)=>(t)=>`${FS(t.label)}=${e-t.startTime}ms`;var kI="effect/MetricLabel",LS,EI,II=(e,t)=>new EI(e,t),E2=(e)=>H(e,LS);var AI=w(()=>{Re();Ge();Ne();Ae();LS=Symbol.for(kI);EI=class EI{key;value;[LS]=LS;_hash;constructor(e,t){this.key=e,this.value=t,this._hash=ke(kI+this.key+this.value)}[J](){return this._hash}[z](e){return E2(e)&&this.key===e.key&&this.value===e.value}pipe(){return F(this,arguments)}}});var DS;var PI=w(()=>{Wn();pt();Yf();DS=mr((e)=>Ul(e.context,mE)?e._tag==="Span"?DS(e.parent):B():Y(e))});var MI;var NI=w(()=>{wt();MI=Zx});var qS="InterruptSignal",US="Stateful",$S="Resume",jS="YieldNow",gm=(e)=>({_tag:"InterruptSignal",cause:e}),hc=(e)=>({_tag:"Stateful",onFiber:e}),Ka=(e)=>({_tag:"Resume",effect:e}),FI=()=>({_tag:"YieldNow"});var F2="effect/FiberScope",ym,DI,qI,UI=(e)=>new qI(e.id(),e),bu;var HS=w(()=>{Xs();ym=Symbol.for(F2);DI=class DI{[ym]=ym;fiberId=zn;roots=new Set;add(e,t){this.roots.add(t),t.addObserver(()=>{this.roots.delete(t)})}};qI=class qI{fiberId;parent;[ym]=ym;constructor(e,t){this.fiberId=e,this.parent=t}add(e,t){this.parent.tell(hc((n)=>{n.addChild(t),t.addObserver(()=>{n.removeChild(t)})}))}};bu=re(Symbol.for("effect/FiberScope/Global"),()=>new DI)});var q2="effect/Fiber",BS,VS,U2,$2="effect/Fiber",jI,xm=(e)=>Cf(ru(e.await),e.inheritAll),a5,Ui="effect/FiberCurrent";var HI=w(()=>{Xs();pt();Ne();wt();vo();BS=Symbol.for(q2),VS={_E:(e)=>e,_A:(e)=>e},U2={[BS]:VS,pipe(){return F(this,arguments)}},jI=Symbol.for($2),a5={...hi,commit(){return xm(this)},...U2,id:()=>zn,await:su,children:Ce([]),inheritAll:su,poll:Ce(B()),interruptAsFork:()=>su}});var H2="effect/Logger",BI,VI,Sm=(e)=>({[BI]:VI,log:e,pipe(){return F(this,arguments)}}),l5,B2,V2=(e,t)=>({annotations:n,cause:r,date:o,fiberId:i,logLevel:a,message:s,spans:c})=>{let l=(f)=>f.match(B2)?f:e(f),u=(f,y)=>`${FS(f)}=${l(y)}`,d=(f,y)=>" "+u(f,y),p=u("timestamp",o.toISOString());p+=d("level",a.label),p+=d("fiber",Xp(i));let m=ny(s);for(let f=0;f<m.length;f++)p+=d("message",wo(m[f],t));if(!Iy(r))p+=d("cause",wr(r,{renderErrorCause:!0}));for(let f of c)p+=" "+OI(o.getTime())(f);for(let[f,y]of n)p+=d(f,wo(y,t));return p},W2=(e)=>`"${e.replace(/\\([\s\S])|(")/g,"\\$1$2")}"`,WI,Ja,u5,zI,d5,p5;var KI=w(()=>{st();ne();at();Ne();Gs();Xy();BI=Symbol.for(H2),VI={_Message:(e)=>e,_Output:(e)=>e},l5={[BI]:VI,log:fl,pipe(){return F(this,arguments)}},B2=/^[^\s"=]*$/,WI=Sm(V2(W2)),Ja={bold:"1",red:"31",green:"32",yellow:"33",blue:"34",cyan:"36",white:"37",gray:"90",black:"30",bgBrightRed:"101"},u5={None:[],All:[],Trace:[Ja.gray],Debug:[Ja.blue],Info:[Ja.green],Warning:[Ja.yellow],Error:[Ja.red],Fatal:[Ja.bgBrightRed,Ja.black]},zI=typeof process==="object"&&process!==null&&typeof process.stdout==="object"&&process.stdout!==null,d5=zI&&process.stdout.isTTY===!0,p5=zI||"Deno"in globalThis});var JI="effect/MetricBoundaries",WS,GI,K2=(e)=>H(e,WS),J2=(e)=>{let t=b(e,ry(St(Number.POSITIVE_INFINITY)),uy);return new GI(t)},YI=(e)=>b(ty(e.count-1,(t)=>e.start*Math.pow(e.factor,t)),Pl,J2);var ZI=w(()=>{st();Vr();Re();ne();Ge();Ne();Ae();WS=Symbol.for(JI);GI=class GI{values;[WS]=WS;constructor(e){this.values=e,this._hash=b(ke(JI),le(En(this.values)))}_hash;[J](){return this._hash}[z](e){return K2(e)&&j(this.values,e.values)}pipe(){return F(this,arguments)}}});var Y2="effect/MetricKeyType",XI,QI="effect/MetricKeyType/Counter",zS,Z2="effect/MetricKeyType/Frequency",X2,Q2="effect/MetricKeyType/Gauge",ej,eA="effect/MetricKeyType/Histogram",KS,tj="effect/MetricKeyType/Summary",nj,tA,nA,rA,oA=(e)=>new nA(e?.incremental??!1,e?.bigint??!1),iA=(e)=>new rA(e),JS=(e)=>H(e,zS),aA=(e)=>H(e,X2),sA=(e)=>H(e,ej),GS=(e)=>H(e,KS),cA=(e)=>H(e,nj);var YS=w(()=>{Re();ne();Ge();Ne();Ae();XI=Symbol.for(Y2),zS=Symbol.for(QI),X2=Symbol.for(Z2),ej=Symbol.for(Q2),KS=Symbol.for(eA),nj=Symbol.for(tj),tA={_In:(e)=>e,_Out:(e)=>e};nA=class nA{incremental;bigint;[XI]=tA;[zS]=zS;constructor(e,t){this.incremental=e,this.bigint=t,this._hash=ke(QI)}_hash;[J](){return this._hash}[z](e){return JS(e)}pipe(){return F(this,arguments)}};rA=class rA{boundaries;[XI]=tA;[KS]=KS;constructor(e){this.boundaries=e,this._hash=b(ke(eA),le(U(this.boundaries)))}_hash;[J](){return this._hash}[z](e){return GS(e)&&j(this.boundaries,e.boundaries)}pipe(){return F(this,arguments)}}});var rj="effect/MetricKey",uA,oj,ij,bm,aj=(e)=>H(e,uA),dA=(e,t)=>new bm(e,oA(t),Ro(t?.description)),pA=(e,t,n)=>new bm(e,iA(t),Ro(n)),fA;var mA=w(()=>{st();Re();ne();Ge();pt();Ne();Ae();YS();uA=Symbol.for(rj),oj={_Type:(e)=>e},ij=xi(j);bm=class bm{name;keyType;description;tags;[uA]=oj;constructor(e,t,n,r=[]){this.name=e,this.keyType=t,this.description=n,this.tags=r,this._hash=b(ke(this.name+this.description),le(U(this.keyType)),le(En(this.tags)))}_hash;[J](){return this._hash}[z](e){return aj(e)&&this.name===e.name&&j(this.keyType,e.keyType)&&j(this.description,e.description)&&ij(this.tags,e.tags)}pipe(){return F(this,arguments)}};fA=h(2,(e,t)=>t.length===0?e:new bm(e.name,e.keyType,e.description,yi(e.tags,t)))});class gA{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 hA,cj,ZS,yA=()=>{let e=Object.create(cj);return e.referential=new Map,e.buckets=new Map,e.bucketsSize=0,e},$i,lj=(e,t,n,r=!1)=>{for(let o=0,i=t.length;o<i;o++)if(n[z](t[o][0])){let a=t[o][1];if(r)t.splice(o,1),e.bucketsSize--;return Y(a)}return B()},gc,yc,uj=(e,t,n)=>{for(let r=0,o=t.length;r<o;r++)if(n[z](t[r][0])){t.splice(r,1),e.bucketsSize--;return}};var xA=w(()=>{Re();ne();Ge();at();pt();Ne();hA=Symbol.for("effect/MutableHashMap"),cj={[hA]:hA,[Symbol.iterator](){return new ZS(this)},toString(){return Ee(this.toJSON())},toJSON(){return{_id:"MutableHashMap",values:Array.from(this).map(Te)}},[me](){return this.toJSON()},pipe(){return F(this,arguments)}};ZS=class ZS{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 gA(this.self.buckets.values()),this.next();return e}[Symbol.iterator](){return new ZS(this.self)}};$i=h(2,(e,t)=>{if(wl(t)===!1)return e.referential.has(t)?Y(e.referential.get(t)):B();let n=t[J](),r=e.buckets.get(n);if(r===void 0)return B();return lj(e,r,t)}),gc=h(2,(e,t)=>$e($i(e,t))),yc=h(3,(e,t,n)=>{if(wl(t)===!1)return e.referential.set(t,n),e;let r=t[J](),o=e.buckets.get(r);if(o===void 0)return e.buckets.set(r,[[t,n]]),e.bucketsSize++,e;return uj(e,o,t),o.push([t,n]),e.bucketsSize++,e})});var pj="effect/MetricState",wu,SA="effect/MetricState/Counter",XS,bA="effect/MetricState/Frequency",QS,wA="effect/MetricState/Gauge",eb,_A="effect/MetricState/Histogram",tb,vA="effect/MetricState/Summary",nb,_u,RA,fj,TA,CA,OA,kA,EA=(e)=>new RA(e),IA=(e)=>new TA(e),AA=(e)=>new CA(e),PA=(e)=>new OA(e.buckets,e.count,e.min,e.max,e.sum),MA=(e)=>new kA(e.error,e.quantiles,e.count,e.min,e.max,e.sum),mj=(e)=>H(e,XS),hj=(e)=>H(e,QS),gj=(e)=>H(e,eb),yj=(e)=>H(e,tb),xj=(e)=>H(e,nb);var NA=w(()=>{st();Re();ne();Ge();Ne();Ae();wu=Symbol.for(pj),XS=Symbol.for(SA),QS=Symbol.for(bA),eb=Symbol.for(wA),tb=Symbol.for(_A),nb=Symbol.for(vA),_u={_A:(e)=>e};RA=class RA{count;[wu]=_u;[XS]=XS;constructor(e){this.count=e}[J](){return b(U(SA),le(U(this.count)),xe(this))}[z](e){return mj(e)&&this.count===e.count}pipe(){return F(this,arguments)}};fj=xi(j);TA=class TA{occurrences;[wu]=_u;[QS]=QS;constructor(e){this.occurrences=e}_hash;[J](){return b(ke(bA),le(En(je(this.occurrences.entries()))),xe(this))}[z](e){return hj(e)&&fj(je(this.occurrences.entries()),je(e.occurrences.entries()))}pipe(){return F(this,arguments)}};CA=class CA{value;[wu]=_u;[eb]=eb;constructor(e){this.value=e}[J](){return b(U(wA),le(U(this.value)),xe(this))}[z](e){return gj(e)&&this.value===e.value}pipe(){return F(this,arguments)}};OA=class OA{buckets;count;min;max;sum;[wu]=_u;[tb]=tb;constructor(e,t,n,r,o){this.buckets=e,this.count=t,this.min=n,this.max=r,this.sum=o}[J](){return b(U(_A),le(U(this.buckets)),le(U(this.count)),le(U(this.min)),le(U(this.max)),le(U(this.sum)),xe(this))}[z](e){return yj(e)&&j(this.buckets,e.buckets)&&this.count===e.count&&this.min===e.min&&this.max===e.max&&this.sum===e.sum}pipe(){return F(this,arguments)}};kA=class kA{error;quantiles;count;min;max;sum;[wu]=_u;[nb]=nb;constructor(e,t,n,r,o,i){this.error=e,this.quantiles=t,this.count=n,this.min=r,this.max=o,this.sum=i}[J](){return b(U(vA),le(U(this.error)),le(U(this.quantiles)),le(U(this.count)),le(U(this.min)),le(U(this.max)),le(U(this.sum)),xe(this))}[z](e){return xj(e)&&this.error===e.error&&j(this.quantiles,e.quantiles)&&this.count===e.count&&this.min===e.min&&this.max===e.max&&this.sum===e.sum}pipe(){return F(this,arguments)}}});var bj="effect/MetricHook",wj,_j,vu=(e)=>({[wj]:_j,pipe(){return F(this,arguments)},...e}),FA,DA=(e)=>{let t=e.keyType.bigint?FA:0,n=e.keyType.incremental?e.keyType.bigint?(o)=>o>=FA:(o)=>o>=0:(o)=>!0,r=(o)=>{if(n(o))t=t+o};return vu({get:()=>EA(t),update:r,modify:r})},qA=(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 vu({get:()=>IA(t),update:n,modify:n})},UA=(e,t)=>{let n=t;return vu({get:()=>AA(n),update:(r)=>{n=r},modify:(r)=>{n=n+r}})},$A=(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;b(t,Co(Yr),gr((d,p)=>{o[p]=d}));let l=(d)=>{let p=0,m=n;while(p!==m){let f=Math.floor(p+(m-p)/2),y=o[f];if(d<=y)m=f;else p=f;if(m===p+1)if(d<=o[p])m=p;else p=m}if(r[p]=r[p]+1,i=i+1,a=a+d,d<s)s=d;if(d>c)c=d},u=()=>{let d=va(n),p=0;for(let m=0;m<n;m++){let f=o[m],y=r[m];p=p+y,d[m]=[f,p]}return d};return vu({get:()=>PA({buckets:u(),count:i,min:s,max:c,sum:a}),update:l,modify:l})},jA=(e)=>{let{error:t,maxAge:n,maxSize:r,quantiles:o}=e.keyType,i=b(o,Co(Yr)),a=va(r),s=0,c=0,l=0,u=0,d=0,p=(f)=>{let y=[],g=0;while(g!==r-1){let x=a[g];if(x!=null){let[v,C]=x,M=zp(f-v);if(KC(M,Wy)&&zC(M,n))y.push(C)}g=g+1}return vj(t,i,Co(y,Yr))},m=(f,y)=>{if(r>0){s=s+1;let g=s%r;a[g]=[y,f]}u=c===0?f:Math.min(u,f),d=c===0?f:Math.max(d,f),c=c+1,l=l+f};return vu({get:()=>MA({error:t,quantiles:p(Date.now()),count:c,min:u,max:d,sum:l}),update:([f,y])=>m(f,y),modify:([f,y])=>m(f,y)})},vj=(e,t,n)=>{let r=n.length;if(!Fe(t))return Oo();let o=t[0],i=t.slice(1),a=LA(e,r,B(),0,o,n),s=Gt(a);return i.forEach((c)=>{s.push(LA(e,r,a.value,a.consumed,c,a.rest))}),gr(s,(c)=>[c.quantile,c.value])},LA=(e,t,n,r,o,i)=>{let a=e,s=t,c=n,l=r,u=o,d=i,p=e,m=t,f=n,y=r,g=o,x=i;while(!0){if(!Fe(d))return{quantile:u,value:B(),consumed:l,rest:[]};if(u===1)return{quantile:u,value:Y(ay(d)),consumed:l+d.length,rest:[]};let v=xt(d),C=AT(d,(I)=>I===v),M=u*s,N=a/2*M,O=l+C[0].length,k=Math.abs(O-M);if(O<M-N){p=a,m=s,f=To(d),y=O,g=u,x=C[1],a=p,s=m,c=f,l=y,u=g,d=x;continue}if(O>M+N){let I=Ye(c)?Y(v):c;return{quantile:u,value:I,consumed:l,rest:d}}switch(c._tag){case"None":{p=a,m=s,f=To(d),y=O,g=u,x=C[1],a=p,s=m,c=f,l=y,u=g,d=x;continue}case"Some":{let I=Math.abs(M-c.value);if(k<I){p=a,m=s,f=To(d),y=O,g=u,x=C[1],a=p,s=m,c=f,l=y,u=g,d=x;continue}return{quantile:u,value:Y(c.value),consumed:l,rest:d}}}}throw Error("BUG: MetricHook.resolveQuantiles - please report an issue at https://github.com/Effect-TS/effect/issues")};var HA=w(()=>{st();Ky();ne();hu();pt();Ne();NA();wj=Symbol.for(bj),_j={_In:(e)=>e,_Out:(e)=>e},FA=BigInt(0)});var Tj="effect/MetricPair",Cj,Oj,BA=(e,t)=>({[Cj]:Oj,metricKey:e,metricState:t,pipe(){return F(this,arguments)}});var VA=w(()=>{Ne();Cj=Symbol.for(Tj),Oj={_Type:(e)=>e}});var Ej="effect/MetricRegistry",WA,zA,KA=()=>new zA;var JA=w(()=>{ne();xA();pt();HA();YS();VA();WA=Symbol.for(Ej);zA=class zA{[WA]=WA;map=yA();snapshot(){let e=[];for(let[t,n]of this.map)e.push(BA(t,n.get()));return e}get(e){let t=b(this.map,$i(e),gn);if(t==null){if(JS(e.keyType))return this.getCounter(e);if(sA(e.keyType))return this.getGauge(e);if(aA(e.keyType))return this.getFrequency(e);if(GS(e.keyType))return this.getHistogram(e);if(cA(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=b(this.map,$i(e),gn);if(t==null){let n=DA(e);if(!b(this.map,gc(e)))b(this.map,yc(e,n));t=n}return t}getFrequency(e){let t=b(this.map,$i(e),gn);if(t==null){let n=qA(e);if(!b(this.map,gc(e)))b(this.map,yc(e,n));t=n}return t}getGauge(e){let t=b(this.map,$i(e),gn);if(t==null){let n=UA(e,e.keyType.bigint?BigInt(0):0);if(!b(this.map,gc(e)))b(this.map,yc(e,n));t=n}return t}getHistogram(e){let t=b(this.map,$i(e),gn);if(t==null){let n=$A(e);if(!b(this.map,gc(e)))b(this.map,yc(e,n));t=n}return t}getSummary(e){let t=b(this.map,$i(e),gn);if(t==null){let n=jA(e);if(!b(this.map,gc(e)))b(this.map,yc(e,n));t=n}return t}}});var Aj="effect/Metric",Pj,Mj,GA,YA=function(e,t,n,r){let o=Object.assign((i)=>vf(i,(a)=>Fj(o,a)),{[Pj]:Mj,keyType:e,unsafeUpdate:t,unsafeValue:n,unsafeModify:r,register(){return this.unsafeValue([]),this},pipe(){return F(this,arguments)}});return o},Ru=(e,t)=>ZA(dA(e,t)),ZA=(e)=>{let t,n=new WeakMap,r=(o)=>{if(o.length===0){if(t!==void 0)return t;return t=GA.get(e),t}let i=n.get(o);if(i!==void 0)return i;return i=GA.get(fA(e,o)),n.set(o,i),i};return YA(e.keyType,(o,i)=>r(i).update(o),(o)=>r(o).get(),(o,i)=>r(i).modify(o))},XA=(e,t,n)=>ZA(pA(e,t,n)),QA,Nj,Fj;var eP=w(()=>{st();ne();Ne();wt();mA();AI();JA();Pj=Symbol.for(Aj),Mj={_Type:(e)=>e,_In:(e)=>e,_Out:(e)=>e},GA=re(Symbol.for("effect/Metric/globalMetricRegistry"),()=>KA()),QA=h(3,(e,t,n)=>Nj(e,[II(t,n)])),Nj=h(2,(e,t)=>YA(e.keyType,(n,r)=>e.unsafeUpdate(n,yi(t,r)),(n)=>e.unsafeValue(yi(t,n)),(n,r)=>e.unsafeModify(n,yi(t,r)))),Fj=h(2,(e,t)=>ja(lu,(n)=>Q(()=>e.unsafeUpdate(t,n))))});var Dj="effect/Request",qj,Uj,B5,tP;var nP=w(()=>{ne();MS();wt();vo();qj=Symbol.for(Dj),Uj={_E:(e)=>e,_A:(e)=>e},B5={...Ol,[qj]:Uj},tP=h(2,(e,t)=>ja(hm,(n)=>Q(()=>{if(n.has(e)){let r=n.get(e);if(!r.state.completed)r.state.completed=!0,Ff(r.result,t)}})))});var $j="effect/Supervisor",wm,rb,_m,vm,ob=(e)=>H(e,wm)&&Sl(e,"Zip"),rP,jj=(e)=>new rP(e),Ga;var Rm=w(()=>{ne();Ae();wt();wm=Symbol.for($j),rb={_T:(e)=>e};_m=class _m{underlying;value0;[wm]=rb;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 _m(this,b(this.value,ct(e)))}zip(e){return new vm(this,e)}};vm=class vm{left;right;_tag="Zip";[wm]=rb;constructor(e,t){this.left=e,this.right=t}get value(){return Tf(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 _m(this,b(this.value,ct(e)))}zip(e){return new vm(this,e)}};rP=class rP{effect;[wm]=rb;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 _m(this,b(this.value,ct(e)))}zip(e){return new vm(this,e)}onRun(e,t){return e()}};Ga=re("effect/Supervisor/none",()=>jj(bt))});var oP;var iP=w(()=>{cf();oP=Ei});var aP="Empty",sP="AddSupervisor",cP="RemoveSupervisor",lP="AndThen",xc,Tm=(e,t)=>({_tag:lP,first:e,second:t}),Bj=(e,t)=>Vj(t,St(e)),Vj=(e,t)=>{let n=e,r=t;while(yr(r)){let o=xr(r);switch(o._tag){case aP:{r=Sr(r);break}case sP:{n=n.zip(o.supervisor),r=Sr(r);break}case cP:{n=ab(n,o.supervisor),r=Sr(r);break}case lP:{r=Yt(o.first)(Yt(o.second)(Sr(r)));break}}}return n},ab=(e,t)=>{if(j(e,t))return Ga;else if(ob(e))return ab(e.left,t).zip(ab(e.right,t));else return e},Cm=(e)=>{if(j(e,Ga))return Wr();else if(ob(e))return b(Cm(e.left),Po(Cm(e.right)));else return Oa(e)},Wj=(e,t)=>{if(j(e,t))return xc;let n=Cm(e),r=Cm(t),o=b(r,Cy(n),Ea(xc,(a,s)=>Tm(a,{_tag:sP,supervisor:s}))),i=b(n,Cy(r),Ea(xc,(a,s)=>Tm(a,{_tag:cP,supervisor:s})));return Tm(o,i)},uP;var dP=w(()=>{Vr();iP();Re();ne();Ia();Rm();xc={_tag:aP},uP=oP({empty:xc,patch:Bj,combine:Tm,diff:Wj})});var tH,pP,nH,rH,oH,Tu="Continue",iH="Done",fP="Yield",aH,Om=(e)=>{throw Error(`BUG: FiberRuntime - ${wo(e)} - please report an issue at https://github.com/Effect-TS/effect/issues`)},jo,Ho,Cu,sH,cH=(e)=>Ua(DO(e),(t)=>Ya(UO(t),([n,r])=>{let o=new Map,i=[];for(let s of r){i.push(Eo(s));for(let c of s)o.set(c.request,c)}let a=i.flat();return Fi(vH(n.runAll(i),a,()=>a.forEach((s)=>{s.listeners.interrupted=!0})),hm,o)},!1,!1)),lH,km,uH,dH=(e)=>Sm((t)=>{let n=EE(t.context,yu);Ul(n,Jf).unsafe.log(e.log(t))}),pH,fH,mH,gP,yP=(e,t,n)=>He(()=>{let r=je(e),o=Array(r.length);return Ni(Ya(r,(a,s)=>oe(t(a,s),(c)=>Q(()=>o[s]=c)),n,!1),Ce(o))}),Ya=(e,t,n,r,o)=>Mi((i)=>Bx((a)=>jt((s)=>{let c=Array.from(e).reverse(),l=c.length;if(l===0)return bt;let u=0,d=!1,p=o?Math.min(c.length,o):c.length,m=new Set,f=[],y=()=>m.forEach((I)=>{I.currentScheduler.scheduleTask(()=>{I.unsafeInterruptAsFork(s.id())},0,I)}),g=[],x=[],v=[],C=()=>{let I=f.filter(({exit:S})=>S._tag==="Failure").sort((S,D)=>S.index<D.index?-1:S.index===D.index?0:1).map(({exit:S})=>S);if(I.length===0)I.push(Gn);return I},M=(I,S=!1)=>{let D=Rf(a(I)),P=gH(D,s,s.currentRuntimeFlags,bu);return s.currentScheduler.scheduleTask(()=>{if(S)P.unsafeInterruptAsFork(s.id());P.resume(D)},0,P),P},N=()=>{if(!r)l-=c.length,c=[];d=!0,y()},O=n?Hx:Pi,k=M(Ai((I)=>{let S=(P,pe)=>{if(P._op==="Blocked")v.push(P);else if(f.push({index:pe,exit:P}),P._op==="Failure"&&!d)N()},D=()=>{if(c.length>0){let P=c.pop(),pe=u++,De=()=>{let Je=c.pop();return pe=u++,oe(au(),()=>oe(O(i(t(Je,pe))),Rt))},Rt=(Je)=>{if(c.length>0){if(S(Je,pe),c.length>0)return De()}return Ce(Je)},Tt=oe(O(i(t(P,pe))),Rt),et=M(Tt);if(g.push(et),m.add(et),d)et.currentScheduler.scheduleTask(()=>{et.unsafeInterruptAsFork(s.id())},0,et);et.addObserver((Je)=>{let it;if(Je._op==="Failure")it=Je;else it=Je.effect_instruction_i0;if(x.push(et),m.delete(et),S(it,pe),f.length===l)I(Ce(Ue(Wa(C(),{parallel:!0}),()=>Gn)));else if(v.length+f.length===l){let lr=C(),sa=v.map((si)=>si.effect_instruction_i0).reduce(Ix);I(Ce(xf(sa,Ya([Ue(Wa(lr,{parallel:!0}),()=>Gn),...v.map((si)=>si.effect_instruction_i1)],(si)=>si,n,!0,o))))}else D()})}};for(let P=0;P<p;P++)D()}));return Uo(ic(ru(i(xm(k))),Mf({onFailure:(I)=>{N();let S=v.length+1,D=Math.min(typeof o==="number"?o:v.length,v.length),P=Array.from(v);return Ai((pe)=>{let De=[],Rt=0,Tt=0,et=(it,lr)=>(sa)=>{if(De[it]=sa,Rt++,Rt===S)pe(Ke(Le(I)));if(P.length>0&&lr)Je()},Je=()=>{M(P.pop(),!0).addObserver(et(Tt,!0)),Tt++};k.addObserver(et(Tt,!1)),Tt++;for(let it=0;it<D;it++)Je()})},onSuccess:()=>Jn(x,(I)=>I.inheritAll)})))}))),sb=(e,t,n,r)=>He(()=>{let o=je(e),i=Array(o.length);return Ni(Ya(o,(s,c)=>ct(n(s,c),(l)=>i[c]=l),r,!1,t),Ce(i))}),ub=(e)=>yH(e,bu),hH=(e,t,n,r=null)=>{let o=xP(e,t,n,r);return o.resume(e),o},gH=(e,t,n,r=null)=>xP(e,t,n,r),xP=(e,t,n,r=null)=>{let o=Qp(),i=t.getFiberRefs(),a=xS(i,o),s=new km(o,a,n),c=Di(a,Ba),l=s.currentSupervisor;return l.onStart(c,e,Y(t),s),s.addObserver((d)=>l.onEnd(d,s)),(r!==null?r:b(t.getFiberRef(yf),Ue(()=>t.scope()))).add(n,s),s},yH=(e,t)=>jt((n,r)=>Ce(hH(e,n,r.runtimeFlags,t))),cb=(e)=>za((t)=>dt(Oi(t,Ou),{onNone:()=>e,onSome:(n)=>{switch(n.strategy._tag){case"Parallel":return e;case"Sequential":case"ParallelN":return oe(sc(n,Qf),(r)=>db(e,r))}}})),mP=(e)=>(t)=>za((n)=>dt(Oi(n,Ou),{onNone:()=>t,onSome:(r)=>{if(r.strategy._tag==="ParallelN"&&r.strategy.parallelism===e)return t;return oe(sc(r,em(e)),(o)=>db(t,o))}})),Sc=(e,t)=>(n)=>za((r)=>dt(Oi(r,Ou),{onNone:()=>n(ve),onSome:(o)=>{if(t===!0){let i=e._tag==="Parallel"?cb:e._tag==="Sequential"?lb:mP(e.parallelism);switch(o.strategy._tag){case"Parallel":return i(n(cb));case"Sequential":return i(n(lb));case"ParallelN":return i(n(mP(o.strategy.parallelism)))}}else return n(ve)}})),lb=(e)=>za((t)=>dt(Oi(t,Ou),{onNone:()=>e,onSome:(n)=>{switch(n.strategy._tag){case"Sequential":return e;case"Parallel":case"ParallelN":return oe(sc(n,Xf),(r)=>db(e,r))}}})),Ou,xH=(e,t)=>{if(e.state._tag==="Open")e.state.finalizers.set({},t)},SH,bH=(e=dc)=>{let t=Object.create(SH);return t.strategy=e,t.state={_tag:"Open",finalizers:new Map},t},db,wH=(e)=>Ha(e,{differ:uP,fork:xc}),hP,_H,SP,vH=(e,t,n)=>nu((r)=>SP(oe(ub(wf(e)),(o)=>Ai((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"&&cc(l.result.state.current.effect)&&l.result.state.current.effect._tag==="Failure"&&$p(l.result.state.current.effect.cause))return!0;else return!1}))c.forEach((l)=>l()),n?.(),i(ak(o))}};o.addObserver((l)=>{c.forEach((u)=>u()),i(l)});let c=t.map((l,u)=>{let d=(p)=>{a[u]=p,s()};return l.listeners.addObserver(d),()=>l.listeners.removeObserver(d)});return s(),Q(()=>{c.forEach((l)=>l())})})),He(()=>{let o=t.flatMap((i)=>{if(!i.state.completed)return[i];return[]});return Ua(o,(i)=>tP(i.request,Qx(r)))})));var pb=w(()=>{st();Vr();Wn();dS();RE();Xs();wS();VE();oI();ne();Ia();at();sI();_I();pt();Ne();Ae();kx();mm();fi();$O();Gs();aS();MS();CI();PI();wt();hE();cS();Zf();HI();tm();HS();KI();eP();ZI();nP();Ql();Ql();Rm();dP();Yf();tH=Ru("effect_fiber_started",{incremental:!0}),pP=Ru("effect_fiber_active"),nH=Ru("effect_fiber_successes",{incremental:!0}),rH=Ru("effect_fiber_failures",{incremental:!0}),oH=QA(XA("effect_fiber_lifetimes",YI({start:0.5,factor:2,count:35})),"time_unit","milliseconds"),aH={_E:(e)=>e,_A:(e)=>e},jo=Symbol.for("effect/internal/fiberRuntime/YieldedOp"),Ho=re("effect/internal/fiberRuntime/yieldedOpChannel",()=>({currentOp:null})),Cu={[As]:(e,t,n)=>$t(()=>t.effect_instruction_i1(n)),["OnStep"]:(e,t,n)=>Ke(Ke(n)),[Ps]:(e,t,n)=>$t(()=>t.effect_instruction_i2(n)),[Tl]:(e,t,n)=>{if(e.patchRuntimeFlags(e.currentRuntimeFlags,t.patch),Do(e.currentRuntimeFlags)&&e.isInterrupted())return Le(e.getInterruptedCause());else return Ke(n)},[Ms]:(e,t,n)=>{if($t(()=>t.effect_instruction_i2(n)),$t(()=>t.effect_instruction_i0()))return e.pushStack(t),$t(()=>t.effect_instruction_i1());else return bt},[Ns]:(e,t,n)=>{while(!0){let r=$t(()=>t.effect_instruction_i0.next(n));if(r.done)return Ke(r.value);let o=Dg(r.value);if(!cc(o))return e.pushStack(t),o;else if(o._tag==="Failure")return o;n=o.value}}},sH={[qS]:(e,t,n,r)=>(e.processNewInterruptSignal(r.cause),Do(t)?Le(r.cause):n),[$S]:(e,t,n,r)=>{throw Error("It is illegal to have multiple concurrent run loops in a single fiber")},[US]:(e,t,n,r)=>(r.onFiber(e,_S(t)),n),[jS]:(e,t,n,r)=>oe(au(),()=>n)},lH=Cl();km=class km extends uS{[BS]=VS;[jI]=aH;_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,vx(n)){let r=this.getFiberRef(lu);tH.unsafeUpdate(1,r),pP.unsafeUpdate(1,r)}this.refreshRefCache()}commit(){return xm(this)}id(){return this._fiberId}resume(e){this.tell(Ka(e))}get status(){return this.ask((e,t)=>t)}get runtimeFlags(){return this.ask((e,t)=>{if(rI(t))return e.currentRuntimeFlags;return t.runtimeFlags})}scope(){return UI(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(uu)}fiberRefs(){return this.ask((e)=>e.getFiberRefs())}ask(e){return He(()=>{let t=vk(this._fiberId);return this.tell(hc((n,r)=>{Ff(t,Q(()=>e(n,r)))})),Nf(t)})}tell(e){if(this._queue.push(e),!this._running)this._running=!0,this.drainQueueLaterOnExecutor()}get await(){return Ai((e)=>{let t=(n)=>e(Ce(n));if(this._exitValue!==null){t(this._exitValue);return}return this.tell(hc((n,r)=>{if(n._exitValue!==null)t(this._exitValue);else n.addObserver(t)})),Q(()=>this.tell(hc((n,r)=>{n.removeObserver(t)})))},this.id())}get inheritAll(){return jt((e,t)=>{let n=e.id(),r=e.getFiberRefs(),o=t.runtimeFlags,i=this.getFiberRefs(),a=yS(r,n,i);e.setFiberRefs(a);let s=e.getFiberRef(hP),c=b(Zl(o,s),Ox(Lo),Ox(df));return Vx(c)})}get poll(){return Q(()=>Ro(this._exitValue))}unsafePoll(){return this._exitValue}interruptAsFork(e){return Q(()=>this.tell(gm(br(e))))}unsafeInterruptAsFork(e){this.tell(gm(br(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(hP,this.currentRuntimeFlags),this._fiberRefs}unsafeDeleteFiberRef(e){this._fiberRefs=xu(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=pc(this._fiberRefs,{fiberId:this._fiberId,fiberRef:e,value:t}),this.refreshRefCache()}refreshRefCache(){this.currentDefaultServices=this.getFiberRef(yu),this.currentTracer=this.currentDefaultServices.unsafeMap.get(gu.key),this.currentSupervisor=this.getFiberRef(_H),this.currentScheduler=this.getFiberRef(fm),this.currentContext=this.getFiberRef(Ba),this.currentSpan=this.currentContext.unsafeMap.get(Gf.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=Tu,n=globalThis[Ui];globalThis[Ui]=this;try{while(t===Tu)t=this._queue.length===0?iH:this.evaluateMessageWhileSuspended(this._queue.splice(0,1)[0])}finally{this._running=!1,globalThis[Ui]=n}if(this._queue.length>0&&!this._running)if(this._running=!0,t===fP)this.drainQueueLaterOnExecutor(),e=!1;else e=!0;else e=!1}}drainQueueLaterOnExecutor(){this.currentScheduler.scheduleTask(this.run,this.getFiberRef(ac),this)}drainQueueWhileRunning(e,t){let n=t;while(this._queue.length>0){let r=this._queue.splice(0,1)[0];n=sH[r._tag](this,e,n,r)}return n}isInterrupted(){return!Up(this.getFiberRef(uu))}addInterruptedCause(e){let t=this.getFiberRef(uu);this.setFiberRef(uu,Zt(t,e))}processNewInterruptSignal(e){this.addInterruptedCause(e),this.sendInterruptSignalToAllChildren()}sendInterruptSignalToAllChildren(){if(this._children===null||this._children.size===0)return!1;let e=!1;for(let t of this._children)t.tell(gm(br(this.id()))),e=!0;return e}interruptAllChildren(){if(this.sendInterruptSignalToAllChildren()){let e=this._children.values();this._children=null;let t=!1;return iu({while:()=>!t,body:()=>{let r=e.next();if(!r.done)return Uo(r.value.await);else return Q(()=>{t=!0})},step:()=>{}})}return null}reportExitValue(e){if(vx(this.currentRuntimeFlags)){let t=this.getFiberRef(lu),n=this.id().startTimeMillis,r=Date.now();switch(oH.unsafeUpdate(r-n,t),pP.unsafeUpdate(-1,t),e._tag){case mn:{nH.unsafeUpdate(1,t);break}case fn:{rH.unsafeUpdate(1,t);break}}}if(e._tag==="Failure"){let t=this.getFiberRef(Sk);if(!Js(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(mH)}log(e,t,n){let r=$e(n)?n.value:this.getFiberRef(Gx),o=this.getFiberRef(uH);if(iI(o,r))return;let i=this.getFiberRef(hk),a=this.getFiberRef(mk),s=this.getLoggers(),c=this.getFiberRefs();if(Fl(s)>0){let l=Ul(this.getFiberRef(yu),mu),u=new Date(l.unsafeCurrentTimeMillis());ZR(c,()=>{for(let d of s)d.log({fiberId:this.id(),logLevel:r,message:e,cause:t,context:c,spans:i,annotations:a,date:u})})}}evaluateMessageWhileSuspended(e){switch(e._tag){case jS:return fP;case qS:{if(this.processNewInterruptSignal(e.cause),this._asyncInterruptor!==null)this._asyncInterruptor(Le(e.cause)),this._asyncInterruptor=null;return Tu}case $S:return this._asyncInterruptor=null,this._asyncBlockingOn=null,this.evaluateEffect(e.effect),Tu;case US:return e.onFiber(this,this._exitValue!==null?tI:nI(this.currentRuntimeFlags,this._asyncBlockingOn)),Tu;default:return Om(e)}}evaluateEffect(e){this.currentSupervisor.onResume(this);try{let t=Do(this.currentRuntimeFlags)&&this.isInterrupted()?Le(this.getInterruptedCause()):e;while(t!==null){let n=t,r=this.runLoop(n);if(r===jo){let o=Ho.currentOp;if(Ho.currentOp=null,o._op===Fs)if(MO(this.currentRuntimeFlags))this.tell(FI()),this.tell(Ka(Gn)),t=null;else t=Gn;else if(o._op===ba)t=null}else{this.currentRuntimeFlags=b(this.currentRuntimeFlags,bx(df));let o=this.interruptAllChildren();if(o!==null)t=oe(o,()=>r);else{if(this._queue.length===0)this.setExitValue(r);else this.tell(Ka(r));t=null}}}}finally{this.currentSupervisor.onSuspend(this)}}start(e){if(!this._running){this._running=!0;let t=globalThis[Ui];globalThis[Ui]=this;try{this.evaluateEffect(e)}finally{if(this._running=!1,globalThis[Ui]=t,this._queue.length>0)this.drainQueueLaterOnExecutor()}}else this.tell(Ka(e))}startFork(e){this.tell(Ka(e))}patchRuntimeFlags(e,t){let n=Xl(e,t);return globalThis[Ui]=this,this.currentRuntimeFlags=n,n}initiateAsync(e,t){let n=!1,r=(o)=>{if(!n)n=!0,this.tell(Ka(o))};if(Do(e))this._asyncInterruptor=r;try{t(r)}catch(o){r(Xt(Pn(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!==Rl)return e;e=this.popStack()}}getNextFailCont(){let e=this.popStack();while(e){if(e._op!==As&&e._op!==Ms&&e._op!==Ns)return e;e=this.popStack()}}[QR](e){return Q(()=>$l(this.currentContext,e))}["Left"](e){return Ft(e.left)}["None"](e){return Ft(new du)}["Right"](e){return Ke(e.right)}["Some"](e){return Ke(e.value)}["Micro"](e){return eu((t)=>{let n=t,r=wI(xI(e,this.currentContext));return r.addObserver((o)=>{if(o._tag==="Success")return n(Ke(o.value));switch(o.cause._tag){case"Interrupt":return n(Le(br(zn)));case"Fail":return n(Ft(o.cause.error));case"Die":return n(bf(o.cause.defect))}}),eu((o)=>{n=(i)=>{o(bt)},r.unsafeInterrupt()})})}[mp](e){let t=$t(()=>e.effect_instruction_i0()),n=this.getNextSuccessCont();if(n!==void 0){if(!(n._op in Cu))Om(n);return Cu[n._op](this,n,t)}else return Ho.currentOp=Ke(t),jo}[mn](e){let t=e,n=this.getNextSuccessCont();if(n!==void 0){if(!(n._op in Cu))Om(n);return Cu[n._op](this,n,t.effect_instruction_i0)}else return Ho.currentOp=t,jo}[fn](e){let t=e.effect_instruction_i0,n=this.getNextFailCont();if(n!==void 0)switch(n._op){case Rl:case Ps:if(!(Do(this.currentRuntimeFlags)&&this.isInterrupted()))return $t(()=>n.effect_instruction_i1(t));else return Le(Hp(t));case"OnStep":if(!(Do(this.currentRuntimeFlags)&&this.isInterrupted()))return Ke(Le(t));else return Le(Hp(t));case Tl:if(this.patchRuntimeFlags(this.currentRuntimeFlags,n.patch),Do(this.currentRuntimeFlags)&&this.isInterrupted())return Le(Zt(t,this.getInterruptedCause()));else return Le(t);default:Om(n)}else return Ho.currentOp=Le(t),jo}[hp](e){return $t(()=>e.effect_instruction_i0(this,_S(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=HE(o.refs,t),s=Zl(o.flags,n);return Ke(xf(e.effect_instruction_i0,jt((c)=>{while(r.length>0)c.pushStack(r.pop());return c.setFiberRefs(BE(c.id(),c.getFiberRefs())(a)),c.currentRuntimeFlags=Xl(s)(c.currentRuntimeFlags),e.effect_instruction_i1})))}return Mi((r)=>oe(ub(Nx(e.effect_instruction_i0)),()=>r(e.effect_instruction_i1)))}["RunBlocked"](e){return cH(e.effect_instruction_i0)}[_a](e){let t=e.effect_instruction_i0,n=this.currentRuntimeFlags,r=Xl(n,t);if(Do(r)&&this.isInterrupted())return Le(this.getInterruptedCause());else if(this.patchRuntimeFlags(this.currentRuntimeFlags,t),e.effect_instruction_i1){let o=Zl(r,n);return this.pushStack(new Fx(o,e)),$t(()=>e.effect_instruction_i1(n))}else return Gn}[As](e){return this.pushStack(e),e.effect_instruction_i0}["OnStep"](e){return this.pushStack(e),e.effect_instruction_i0}[Rl](e){return this.pushStack(e),e.effect_instruction_i0}[Ps](e){return this.pushStack(e),e.effect_instruction_i0}[ba](e){return this._asyncBlockingOn=e.effect_instruction_i1,this.initiateAsync(this.currentRuntimeFlags,e.effect_instruction_i0),Ho.currentOp=e,jo}[Fs](e){return this._isYielding=!1,Ho.currentOp=e,jo}[Ms](e){let{effect_instruction_i0:t,effect_instruction_i1:n}=e;if(t())return this.pushStack(e),n();else return Gn}[Ns](e){return Cu[Ns](this,e,void 0)}[wa](e){return $t(()=>e.commit())}runLoop(e){let t=e;this.currentOpCount=0;while(!0){if((this.currentRuntimeFlags&PO)!==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=oe(au({priority:n}),()=>r)}}try{if(t=this.currentTracer.context(()=>{if(lH!==t[Ii]._V){let n=this.getFiberRef(bk);if(n._tag==="Some"){let r=t[Ii]._V;this.log(`Executing an Effect versioned ${r} with a Runtime of version ${Cl()}, 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`,Mo,n)}}return this[t._op](t)},this),t===jo){let n=Ho.currentOp;if(n._op===Fs||n._op===ba)return jo;return Ho.currentOp=null,n._op===mn||n._op===fn?n:Le(Pn(n))}}catch(n){if(t!==jo&&!H(t,"_op")||!(t._op in this))t=Ux(`Not a valid effect: ${wo(t)}`);else if(wk(n))t=Le(Zt(Pn(n),br(zn)));else t=bf(n)}}}run=()=>{this.drainQueueOnCurrentThread()}};uH=re("effect/FiberRef/currentMinimumLogLevel",()=>Ht(aI("Info"))),pH=re(Symbol.for("effect/Logger/defaultLogger"),()=>dH(WI)),fH=re(Symbol.for("effect/Logger/tracerLogger"),()=>Sm(({annotations:e,cause:t,context:n,fiberId:r,logLevel:o,message:i})=>{let a=DS(Oi(Di(n,Ba),Gf));if(a._tag==="None"||a.value._tag==="ExternalSpan")return;let s=$l(Di(n,yu),mu),c={};for(let[l,u]of e)c[l]=u;if(c["effect.fiberId"]=rO(r),c["effect.logLevel"]=o.label,t!==null&&t._tag!=="Empty")c["effect.cause"]=wr(t,{renderErrorCause:!0});a.value.event(wo(Array.isArray(i)&&i.length===1?i[0]:i),s.unsafeCurrentTimeNanos(),c)})),mH=re(Symbol.for("effect/FiberRef/currentLoggers"),()=>pk(Oa(pH,fH))),gP=h((e)=>Mg(e[0]),(e,t,n)=>jt((r)=>{let o=n?.batching===!0||n?.batching==="inherit"&&r.getFiberRef(xk);if(n?.discard)return NS(n.concurrency,()=>Sc(Xf,n?.concurrentFinalizers)((i)=>o?Ya(e,(a,s)=>i(t(a,s)),!0,!1,1):Ua(e,(a,s)=>i(t(a,s)))),()=>Sc(Qf,n?.concurrentFinalizers)((i)=>Ya(e,(a,s)=>i(t(a,s)),o,!1)),(i)=>Sc(em(i),n?.concurrentFinalizers)((a)=>Ya(e,(s,c)=>a(t(s,c)),o,!1,i)));return NS(n?.concurrency,()=>Sc(Xf,n?.concurrentFinalizers)((i)=>o?sb(e,1,(a,s)=>i(t(a,s)),!0):Jn(e,(a,s)=>i(t(a,s)))),()=>Sc(Qf,n?.concurrentFinalizers)((i)=>yP(e,(a,s)=>i(t(a,s)),o)),(i)=>Sc(em(i),n?.concurrentFinalizers)((a)=>sb(e,i,(s,c)=>a(t(s,c)),o)))})),Ou=yn("effect/Scope"),SH={[Ef]:Ef,[If]:If,pipe(){return F(this,arguments)},fork(e){return Q(()=>{let t=bH(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),xH(t,(o)=>Q(()=>{if(this.state._tag==="Open")this.state.finalizers.delete(n)})),t})},close(e){return He(()=>{if(this.state._tag==="Closed")return bt;let t=Array.from(this.state.finalizers.values()).reverse();if(this.state={_tag:"Closed",exit:e},t.length===0)return bt;return pS(this.strategy)?b(Jn(t,(n)=>Pi(n(e))),oe((n)=>b(Wa(n),fr(pu),Ue(()=>Gn)))):fS(this.strategy)?b(yP(t,(n)=>Pi(n(e)),!1),oe((n)=>b(Wa(n,{parallel:!0}),fr(pu),Ue(()=>Gn)))):b(sb(t,this.strategy.parallelism,(n)=>Pi(n(e)),!1),oe((n)=>b(Wa(n,{parallel:!0}),fr(pu),Ue(()=>Gn))))})},addFinalizer(e){return He(()=>{if(this.state._tag==="Closed")return e(this.state.exit);return this.state.finalizers.set({},e),bt})}},db=h(2,(e,t)=>tS(e,jl(UC(Ou,t)))),hP=fk(NO),_H=wH(Ga),SP=h(2,(e,t)=>Mi((n)=>Kn(n(e),{onFailure:(r)=>Kn(t,{onFailure:(o)=>Xt(Zt(r,o)),onSuccess:()=>Xt(r)}),onSuccess:(r)=>qo(t,r)})))});var wP,_P;var vP=w(()=>{wt();wP=Yx,_P=sc});class OP{context;runtimeFlags;fiberRefs;constructor(e,t,n){this.context=e,this.runtimeFlags=t,this.fiberRefs=n}pipe(){return F(this,arguments)}}var mb=(e)=>function(){if(arguments.length===1){let t=arguments[0];return(n,...r)=>e(t,n,...r)}return e.apply(this,arguments)},RP,OH,TP,kH=(e)=>{let t=Error.stackTraceLimit;Error.stackTraceLimit=0;let n=new TP(e);return Error.stackTraceLimit=t,n},fb,Em,CP,EH=(e)=>{let t=Error.stackTraceLimit;Error.stackTraceLimit=0;let n=new CP(e);return Error.stackTraceLimit=t,n},IH=(e)=>{let t=e;switch(t._op){case"Failure":case"Success":return t;case"Left":return fu(t.left);case"Right":return Ke(t.right);case"Some":return Ke(t.value);case"None":return fu(new du)}},AH,PH=(e)=>new OP(e.context,e.runtimeFlags,e.fiberRefs),MH,kP,EP,IP;var AP=w(()=>{Wn();Re();Xs();wS();at();pt();Ne();mm();vP();Gs();wt();Zf();pb();HS();Ql();Rm();RP=mb((e,t,n)=>{let r=Qp(),o=[[Ba,[[r,e.context]]]];if(n?.scheduler)o.push([fm,[[r,n.scheduler]]]);let i=IE(e.fiberRefs,{entries:o,forkAs:r});if(n?.updateRefs)i=n.updateRefs(i,r);let a=new km(r,i,e.runtimeFlags),s=t;if(n?.scope)s=oe(_P(n.scope,dc),(l)=>Ni(Af(l,nu((u)=>j(u,a.id())?bt:cu(a,u))),ic(t,(u)=>wP(l,u))));let c=a.currentSupervisor;if(c!==Ga)c.onStart(e.context,s,B(),a),a.addObserver((l)=>c.onEnd(l,a));if(bu.add(e.runtimeFlags,a),n?.immediate===!1)a.resume(s);else a.start(s);return a}),OH=mb((e,t)=>{let n=AH(e)(t);if(n._tag==="Failure")throw EH(n.effect_instruction_i0);return n.effect_instruction_i0});TP=class TP 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}};fb=Symbol.for("effect/Runtime/FiberFailure"),Em=Symbol.for("effect/Runtime/FiberFailure/Cause");CP=class CP extends Error{[fb];[Em];constructor(e){let t=Ll(e)[0];super(t?.message||"An error has occurred");if(this[fb]=fb,this[Em]=e,this.name=t?`(FiberFailure) ${t.name}`:"FiberFailure",t?.stack)this.stack=t.stack}toJSON(){return{_id:"FiberFailure",cause:this[Em].toJSON()}}toString(){return"(FiberFailure) "+wr(this[Em],{renderErrorCause:!0})}[me](){return this.toString()}};AH=mb((e,t)=>{let n=IH(t);if(n)return n;let r=new Su,o=RP(e)(t,{scheduler:r});r.flush();let i=o.unsafePoll();if(i)return i;return Xx(Sf(kH(o),Lf(o)))});MH=_x(Lo,Sx,xx),kP=PH({context:Ci(),runtimeFlags:MH,fiberRefs:AE()}),EP=RP(kP),IP=OH(kP)});var PP,ku,Eu,Nn,MP,Im,NP,Za,vr,FP,LP;var DP=w(()=>{wt();pb();AP();PP=rc,ku=gP,Eu=He,Nn=bt,MP=tu,Im=ct,NP=$a,Za=qa,vr=oe,FP=EP,LP=IP});var hb=(e,t)=>{switch(t._tag){case"StringKeyword":case"TemplateLiteral":return Object.keys(e);case"SymbolKeyword":return Object.getOwnPropertySymbols(e);case"Refinement":return hb(e,t.from)}},Iu=(e)=>{let t=!1,n;return()=>{if(t)return n;return n=e(),t=!0,n}},gb=(e)=>Array.isArray(e),UP=(e)=>!Array.isArray(e),qP=(e)=>`[${vl(e)}]`,Am=(e)=>gb(e)?e.map(qP).join(""):qP(e);var Au=w(()=>{at()});var ji=(e,t,n,r)=>{let o=e;if(n&&Fe(n))o+=`
31
- at path: ${Am(n)}`;if(t!==void 0)o+=`
32
- details: ${t}`;if(r)o+=`
33
- schema (${r._tag}): ${r}`;return o},$P=(e)=>ji("Invalid Argument",e),jP=(e)=>ji("Unsupported key schema",void 0,void 0,e),HP=(e)=>ji("Unsupported literal",`literal value: ${Hr(e)}`),yb=(e)=>ji("Duplicate index signature",`${e} index signature`),BP,VP,xb=(e)=>ji("Duplicate property signature transformation",`Duplicate key ${Hr(e)}`),Sb=(e)=>ji("Duplicate property signature",`Duplicate key ${Hr(e)}`);var bb=w(()=>{st();at();Au();BP=ji("Unsupported index signature parameter","An index signature parameter type must be `string`, `symbol`, a template literal type or a refinement of the previous types"),VP=ji("Invalid element","A required element cannot follow an optional element. ts(1257)")});var zP,KP,JP,GP,YP,ZP,XP;var QP=w(()=>{zP=Symbol.for("effect/SchemaId/DateFromSelf"),KP=Symbol.for("effect/SchemaId/GreaterThan"),JP=Symbol.for("effect/SchemaId/GreaterThanOrEqualTo"),GP=Symbol.for("effect/SchemaId/Int"),YP=Symbol.for("effect/SchemaId/MinLength"),ZP=Symbol.for("effect/SchemaId/MaxLength"),XP=Symbol.for("effect/SchemaId/MinItems")});class bc{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 Ue(Xr(this),()=>"<declaration schema>")}toJSON(){return{_tag:this._tag,typeParameters:this.typeParameters.map((e)=>e.toJSON()),annotations:rt(this.annotations)}}}class Xa{literal;annotations;_tag="Literal";constructor(e,t={}){this.literal=e,this.annotations=t}toString(){return Ue(Xr(this),()=>Hr(this.literal))}toJSON(){return{_tag:this._tag,literal:di(this.literal)?String(this.literal):this.literal,annotations:rt(this.annotations)}}}class Dm{symbol;annotations;_tag="UniqueSymbol";constructor(e,t={}){this.symbol=e,this.annotations=t}toString(){return Ue(Xr(this),()=>Hr(this.symbol))}toJSON(){return{_tag:this._tag,symbol:String(this.symbol),annotations:rt(this.annotations)}}}class pM{annotations;_tag="UndefinedKeyword";constructor(e={}){this.annotations=e}toString(){return Rr(this)}toJSON(){return{_tag:this._tag,annotations:rt(this.annotations)}}}class fM{annotations;_tag="VoidKeyword";constructor(e={}){this.annotations=e}toString(){return Rr(this)}toJSON(){return{_tag:this._tag,annotations:rt(this.annotations)}}}class mM{annotations;_tag="NeverKeyword";constructor(e={}){this.annotations=e}toString(){return Rr(this)}toJSON(){return{_tag:this._tag,annotations:rt(this.annotations)}}}class hM{annotations;_tag="UnknownKeyword";constructor(e={}){this.annotations=e}toString(){return Rr(this)}toJSON(){return{_tag:this._tag,annotations:rt(this.annotations)}}}class gM{annotations;_tag="AnyKeyword";constructor(e={}){this.annotations=e}toString(){return Rr(this)}toJSON(){return{_tag:this._tag,annotations:rt(this.annotations)}}}class xM{annotations;_tag="StringKeyword";constructor(e={}){this.annotations=e}toString(){return Rr(this)}toJSON(){return{_tag:this._tag,annotations:rt(this.annotations)}}}class bM{annotations;_tag="NumberKeyword";constructor(e={}){this.annotations=e}toString(){return Rr(this)}toJSON(){return{_tag:this._tag,annotations:rt(this.annotations)}}}class _M{annotations;_tag="BooleanKeyword";constructor(e={}){this.annotations=e}toString(){return Rr(this)}toJSON(){return{_tag:this._tag,annotations:rt(this.annotations)}}}class RM{annotations;_tag="BigIntKeyword";constructor(e={}){this.annotations=e}toString(){return Rr(this)}toJSON(){return{_tag:this._tag,annotations:rt(this.annotations)}}}class TM{annotations;_tag="SymbolKeyword";constructor(e={}){this.annotations=e}toString(){return Rr(this)}toJSON(){return{_tag:this._tag,annotations:rt(this.annotations)}}}class OM{annotations;_tag="ObjectKeyword";constructor(e={}){this.annotations=e}toString(){return Rr(this)}toJSON(){return{_tag:this._tag,annotations:rt(this.annotations)}}}class wc{type;annotations;constructor(e,t={}){this.type=e,this.annotations=t}toJSON(){return{type:this.type.toJSON(),annotations:rt(this.annotations)}}toString(){return String(this.type)}}class Nu{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(VP)}toString(){return Ue(Xr(this),()=>VH(this))}toJSON(){return{_tag:this._tag,elements:this.elements.map((e)=>e.toJSON()),rest:this.rest.map((e)=>e.toJSON()),isReadonly:this.isReadonly,annotations:rt(this.annotations)}}}class _c{type;isReadonly;parameter;constructor(e,t,n){if(this.type=t,this.isReadonly=n,EM(e))this.parameter=e;else throw Error(BP)}toString(){return(this.isReadonly?"readonly ":"")+`[x: ${this.parameter}]: ${this.type}`}toJSON(){return{parameter:this.parameter.toJSON(),type:this.type.toJSON(),isReadonly:this.isReadonly}}}class Qr{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(Sb(a));r[a]=null}let o={string:!1,symbol:!1};for(let i=0;i<t.length;i++){let a=Xb(t[i].parameter);if($m(a)){if(o.string)throw Error(yb("string"));o.string=!0}else if(CM(a)){if(o.symbol)throw Error(yb("symbol"));o.symbol=!0}}this.propertySignatures=e,this.indexSignatures=t}toString(){return Ue(Xr(this),()=>WH(this))}toJSON(){return{_tag:this._tag,propertySignatures:this.propertySignatures.map((e)=>e.toJSON()),indexSignatures:this.indexSignatures.map((e)=>e.toJSON()),annotations:rt(this.annotations)}}}class on{types;annotations;static make=(e,t)=>jm(e)?new on(e,t):e.length===1?e[0]:Um;static unify=(e,t)=>on.make(JH(IM(e)),t);_tag="Union";constructor(e,t={}){this.types=e,this.annotations=t}toString(){return Ue(Xr(this),()=>this.types.map(String).join(" | "))}toJSON(){return{_tag:this._tag,types:this.types.map((e)=>e.toJSON()),annotations:rt(this.annotations)}}}class Hm{f;annotations;_tag="Suspend";constructor(e,t={}){this.f=e,this.annotations=t,this.f=Iu(e)}toString(){return Xr(this).pipe(pr(()=>mr(bT(this.f)(),(e)=>Xr(e))),Ue(()=>"<suspended schema>"))}toJSON(){let e=this.f(),t=wb.get(e);if(t)return t;return wb.set(e,{_tag:this._tag}),t={_tag:this._tag,ast:e.toJSON(),annotations:rt(this.annotations)},wb.set(e,t),t}}class Fu{from;filter;annotations;_tag="Refinement";constructor(e,t,n={}){this.from=e,this.filter=t,this.annotations=n}toString(){return Pu(this).pipe(Ue(()=>dt(FM(this),{onNone:()=>`{ ${this.from} | filter }`,onSome:(e)=>Lu(this.from)?String(this.from)+" & "+e:e})))}toJSON(){return{_tag:this._tag,from:this.from.toJSON(),annotations:rt(this.annotations)}}}class Kb{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 Ue(Xr(this),()=>`(${String(this.from)} <-> ${String(this.to)})`)}toJSON(){return{_tag:this._tag,from:this.from.toJSON(),to:this.to.toJSON(),annotations:rt(this.annotations)}}}class Jb{from;to;decode;encode;constructor(e,t,n,r){this.from=e,this.to=t,this.decode=n,this.encode=r}}class Gb{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(xb(o));t[o]=!0;let i=r.to;if(n[i])throw Error(xb(i));n[i]=!0}}}function Yn(e,t){let n=!1,r=va(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 QH(e){return dt(qb(e),{onNone:()=>"",onSome:(t)=>t.map((n)=>` & Brand<${Hr(n)}>`).join("")})}var tM,vb,nM,Rb,Mm,Nm,xn,Fm,Bo,Tb,Cb,Ob,kb,Eb,Ib,rM,Ab,Pb,Mb,Nb,Fb,Lb,Db,Qt,qb,oM,iM,Ub,$b,Pu,jb,aM,sM,cM,lM,uM,Hb,DH,Bb=(e)=>vT(DH(e),(t)=>t===!0),Vb,qH,UH=(e)=>pr(qH(e),()=>Pu(e)),Mu=(e)=>(t)=>t._tag===e,Lm,dM,qm,$H,Um,Wb,yM,SM,$m,wM,vM,jH,HH,CM,BH,Hi,kM=(e)=>e.map((t)=>t.type),VH=(e)=>{let t=e.elements.map(String).join(", ");return CT(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}>`}})},Et,EM=(e)=>{switch(e._tag){case"StringKeyword":case"SymbolKeyword":case"TemplateLiteral":return!0;case"Refinement":return EM(e.from)}return!1},eM=(e)=>e.map(String).join("; "),WH=(e)=>{if(e.propertySignatures.length>0){let t=e.propertySignatures.map(String).join("; ");if(e.indexSignatures.length>0)return`{ ${t}; ${eM(e.indexSignatures)} }`;else return`{ ${t} }`}else if(e.indexSignatures.length>0)return`{ ${eM(e.indexSignatures)} }`;else return"{}"},zH,KH,IM=(e)=>Il(e,(t)=>zb(t)?IM(t.types):[t]),JH=(e)=>{let t=zH(e),n=[],r={},o=[];for(let i of t)switch(i._tag){case"NeverKeyword":break;case"AnyKeyword":return[yM];case"UnknownKeyword":return[Wb];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=KH[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},AM=(e,t)=>e.map(t),jm=(e)=>e.length>1,zb,wb,Lu,Bm,Du=(e,t)=>{let n=Object.getOwnPropertyDescriptors(e),r={...e.annotations};delete r[Nm];let o={...r,...t},i=Hb(e);if($e(i))o[Lb]=Du(i.value,t);return n.annotations.value=o,Object.create(Object.getPrototypeOf(e),n)},GH="[\\s\\S]*?",YH="[+-]?\\d*\\.?\\d+(?:[Ee][+-]?\\d+)?",PM=(e,t)=>{switch(e._tag){case"Literal":return uc(String(e.literal));case"StringKeyword":return GH;case"NumberKeyword":return YH;case"TemplateLiteral":return MM(e,t,!1);case"Union":return e.types.map((n)=>PM(n,t)).join("|")}},ZH=(e,t,n,r)=>{if(zb(e)){if(n&&!r)return`(?:${t})`}else if(!n||!r)return t;return`(${t})`},MM=(e,t,n)=>{let r="";if(e.head!==""){let o=uc(e.head);r+=t&&n?`(${o})`:o}for(let o of e.spans){let i=PM(o.type,t);if(r+=ZH(o.type,i,t,n),o.literal!==""){let a=uc(o.literal);r+=t&&n?`(${a})`:a}}return r},NM=(e)=>new RegExp(`^${MM(e,!1,!0)}$`),Yb=(e,t)=>{let n=[],r=[],o=(i)=>{switch(i._tag){case"NeverKeyword":break;case"StringKeyword":case"SymbolKeyword":case"TemplateLiteral":case"Refinement":r.push(new _c(i,t,!0));break;case"Literal":if(Ut(i.literal)||kn(i.literal))n.push(new Et(i.literal,t,!1,!0));else throw Error(HP(i.literal));break;case"Enums":{for(let[a,s]of i.enums)n.push(new Et(s,t,!1,!0));break}case"UniqueSymbol":n.push(new Et(i.symbol,t,!1,!0));break;case"Union":i.types.forEach(o);break;default:throw Error(jP(i))}};return o(e),{propertySignatures:n,indexSignatures:r}},Zb=(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},XH,_t=(e)=>{switch(e._tag){case"Declaration":{let t=Yn(e.typeParameters,_t);return t===e.typeParameters?e:new bc(t,e.decodeUnknown,e.encodeUnknown,e.annotations)}case"TupleType":{let t=Yn(e.elements,(o)=>{let i=_t(o.type);return i===o.type?o:new Hi(i,o.isOptional)}),n=kM(e.rest),r=Yn(n,_t);return t===e.elements&&r===n?e:new Nu(t,r.map((o)=>new wc(o)),e.isReadonly,e.annotations)}case"TypeLiteral":{let t=Yn(e.propertySignatures,(r)=>{let o=_t(r.type);return o===r.type?r:new Et(r.name,o,r.isOptional,r.isReadonly)}),n=Yn(e.indexSignatures,(r)=>{let o=_t(r.type);return o===r.type?r:new _c(r.parameter,o,r.isReadonly)});return t===e.propertySignatures&&n===e.indexSignatures?e:new Qr(t,n,e.annotations)}case"Union":{let t=Yn(e.types,_t);return t===e.types?e:on.make(t,e.annotations)}case"Suspend":return new Hm(()=>_t(e.f()),e.annotations);case"Refinement":{let t=_t(e.from);return t===e.from?e:new Fu(t,e.filter,e.annotations)}case"Transformation":{let t=XH(e);return _t(t!==void 0?Du(e.to,t):e.to)}}return e},_b=(e)=>{switch(e._tag){case"Transformation":return e.from;case"Refinement":return _b(e.from);case"Suspend":return _b(e.f())}},Zr=(e,t)=>{switch(e._tag){case"Declaration":{let n=Yn(e.typeParameters,(r)=>Zr(r,t));return n===e.typeParameters?e:new bc(n,e.decodeUnknown,e.encodeUnknown)}case"TupleType":{let n=Yn(e.elements,(i)=>{let a=Zr(i.type,t);return a===i.type?i:new Hi(a,i.isOptional)}),r=kM(e.rest),o=Yn(r,(i)=>Zr(i,t));return n===e.elements&&o===r?e:new Nu(n,o.map((i)=>new wc(i)),e.isReadonly)}case"TypeLiteral":{let n=Yn(e.propertySignatures,(o)=>{let i=Zr(o.type,t);return i===o.type?o:new Et(o.name,i,o.isOptional,o.isReadonly)}),r=Yn(e.indexSignatures,(o)=>{let i=Zr(o.type,t);return i===o.type?o:new _c(o.parameter,i,o.isReadonly)});return n===e.propertySignatures&&r===e.indexSignatures?e:new Qr(n,r)}case"Union":{let n=Yn(e.types,(r)=>Zr(r,t));return n===e.types?e:on.make(n)}case"Suspend":{let n=void 0,r=UH(e);if($e(r)){let o=t?"Bound":"";n={[Vb]:`${r.value}Encoded${o}`}}return new Hm(()=>Zr(e.f(),t),n)}case"Refinement":{let n=Zr(e.from,t);if(t){if(n===e.from)return e;if(_b(e.from)===void 0&&Bb(e))return new Fu(n,e.filter,e.annotations);return n}else return n}case"Transformation":return Zr(e.from,t)}return e},Vm=(e)=>Zr(e,!1),rt=(e)=>{let t={};for(let n of Object.getOwnPropertySymbols(e))t[String(n)]=e[n];return t},Xb=(e)=>{switch(e._tag){case"StringKeyword":case"SymbolKeyword":case"TemplateLiteral":return e;case"Refinement":return Xb(e.from)}},Rr=(e)=>Ue(Xr(e),()=>e._tag),FM=(e)=>Ub(e).pipe(pr(()=>jb(e)),pr(()=>$b(e)),fr((t)=>t+QH(e))),Xr=(e)=>pr(Pu(e),()=>FM(e));var Qb=w(()=>{st();ne();at();bb();Au();hu();pt();bp();Ae();sS();tM=Symbol.for("effect/annotation/TypeConstructor"),vb=Symbol.for("effect/annotation/Brand"),nM=Symbol.for("effect/annotation/SchemaId"),Rb=Symbol.for("effect/annotation/Message"),Mm=Symbol.for("effect/annotation/MissingMessage"),Nm=Symbol.for("effect/annotation/Identifier"),xn=Symbol.for("effect/annotation/Title"),Fm=Symbol.for("effect/annotation/AutoTitle"),Bo=Symbol.for("effect/annotation/Description"),Tb=Symbol.for("effect/annotation/Examples"),Cb=Symbol.for("effect/annotation/Default"),Ob=Symbol.for("effect/annotation/JSONSchema"),kb=Symbol.for("effect/annotation/Arbitrary"),Eb=Symbol.for("effect/annotation/Pretty"),Ib=Symbol.for("effect/annotation/Equivalence"),rM=Symbol.for("effect/annotation/Documentation"),Ab=Symbol.for("effect/annotation/Concurrency"),Pb=Symbol.for("effect/annotation/Batching"),Mb=Symbol.for("effect/annotation/ParseIssueTitle"),Nb=Symbol.for("effect/annotation/ParseOptions"),Fb=Symbol.for("effect/annotation/DecodingFallback"),Lb=Symbol.for("effect/annotation/Surrogate"),Db=Symbol.for("effect/annotation/StableFilter"),Qt=h(2,(e,t)=>Object.prototype.hasOwnProperty.call(e.annotations,t)?Y(e.annotations[t]):B()),qb=Qt(vb),oM=Qt(Rb),iM=Qt(Mm),Ub=Qt(xn),$b=Qt(Fm),Pu=Qt(Nm),jb=Qt(Bo),aM=Qt(Ab),sM=Qt(Pb),cM=Qt(Mb),lM=Qt(Nb),uM=Qt(Fb),Hb=Qt(Lb),DH=Qt(Db),Vb=Symbol.for("effect/annotation/JSONIdentifier"),qH=Qt(Vb);Lm=Mu("Literal"),dM=new Xa(null);qm=new pM({[xn]:"undefined"});$H=new fM({[xn]:"void"});Um=new mM({[xn]:"never"});Wb=new hM({[xn]:"unknown"});yM=new gM({[xn]:"any"});SM=new xM({[xn]:"string",[Bo]:"a string"}),$m=Mu("StringKeyword");wM=new bM({[xn]:"number",[Bo]:"a number"});vM=new _M({[xn]:"boolean",[Bo]:"a boolean"});jH=new RM({[xn]:"bigint",[Bo]:"a bigint"});HH=new TM({[xn]:"symbol",[Bo]:"a symbol"}),CM=Mu("SymbolKeyword");BH=new OM({[xn]:"object",[Bo]:"an object in the TypeScript meaning, i.e. the `object` type"});Hi=class Hi extends wc{isOptional;constructor(e,t,n={}){super(e,n);this.isOptional=t}toJSON(){return{type:this.type.toJSON(),isOptional:this.isOptional,annotations:rt(this.annotations)}}toString(){return String(this.type)+(this.isOptional?"?":"")}};Et=class Et extends Hi{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:rt(this.annotations)}}};zH=Co(Sp(Yr,(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})),KH={string:"StringKeyword",number:"NumberKeyword",boolean:"BooleanKeyword",bigint:"BigIntKeyword"};zb=Mu("Union"),wb=re(Symbol.for("effect/Schema/AST/toJSONMemoMap"),()=>new WeakMap);Lu=Mu("Refinement"),Bm={};XH=Zb([Tb,Cb,Ob,kb,Eb,Ib])});class It{path;actual;issue;_tag="Pointer";constructor(e,t,n){this.path=e,this.actual=t,this.issue=n}}class nw{actual;message;_tag="Unexpected";constructor(e,t){this.actual=e,this.message=t}}class vc{ast;message;_tag="Missing";actual=void 0;constructor(e,t){this.ast=e,this.message=t}}class ot{ast;actual;issues;output;_tag="Composite";constructor(e,t,n,r){this.ast=e,this.actual=t,this.issues=n,this.output=r}}class zm{ast;actual;kind;issue;_tag="Refinement";constructor(e,t,n,r){this.ast=e,this.actual=t,this.kind=n,this.issue=r}}class Km{ast;actual;kind;issue;_tag="Transformation";constructor(e,t,n,r){this.ast=e,this.actual=t,this.kind=n,this.issue=r}}class Zn{ast;actual;message;_tag="Type";constructor(e,t,n){this.ast=e,this.actual=t,this.message=n}}class rw{ast;actual;message;_tag="Forbidden";constructor(e,t,n){this.ast=e,this.actual=t,this.message=n}}function Tr(e){return e.sort(o1).map((t)=>t[1])}function u1(e){return jb(e).pipe(pr(()=>Ub(e)),pr(()=>$b(e)),pr(()=>Pu(e)),Ue(()=>`{ ${e.from} | filter }`))}function d1(e){if(e.message!==void 0)return e.message;return`Expected ${Lu(e.ast)?u1(e.ast):String(e.ast)}, actual ${Hr(e.actual)}`}var DM,$M,iw=(e)=>new $M({issue:e}),jM,HM,bn,Vo,Cr,Jm,BM,aw=(e,t)=>{if(t===void 0||kn(t))return e;if(e===void 0)return t;return{...e,...t}},VM=(e,t,n)=>{let r=Bt(e,t);return(o,i)=>r(o,aw(n,i))},e1=(e,t,n)=>{let r=VM(e,t,n);return(o,i)=>Zg(r(o,i),iw)},WM=(e,t)=>VM(e.ast,!0,t),Hu=(e,t)=>e1(_t(e.ast),!0,t),Gm=(e,t)=>{let n=Bt(_t(e.ast),!0);return(r,o)=>Ct(n(r,{exact:!0,...aw(t,o)}))},t1,n1,Bt=(e,t)=>{let n=t?t1:n1,r=n.get(e);if(r)return r;let o=r1(e,t),i=lM(e),a=$e(i)?(l,u)=>o(l,aw(u,i.value)):o,s=uM(e),c=t&&$e(s)?(l,u)=>Uu(BM(a(l,u),s.value),e,l,u):a;return n.set(e,c),c},ew=(e)=>gn(aM(e)),tw=(e)=>gn(sM(e)),r1=(e,t)=>{switch(e._tag){case"Refinement":if(t){let n=Bt(e.from,!0);return(r,o)=>{o=o??Bm;let i=o?.errors==="all",a=Vo(BM(n(r,o),(s)=>{let c=new zm(e,r,"From",s);if(i&&Bb(e)&&YM(s))return dt(e.filter(r,o,e),{onNone:()=>ce(c),onSome:(l)=>ce(new ot(e,r,[c,new zm(e,r,"Predicate",l)]))});return ce(c)}),(s)=>dt(e.filter(s,o,e),{onNone:()=>ue(s),onSome:(c)=>ce(new zm(e,r,"Predicate",c))}));return Uu(a,e,r,o)}}else{let n=Bt(_t(e),!0),r=Bt(KM(e.from),!1);return(o,i)=>Uu(Vo(n(o,i),(a)=>r(a,i)),e,o,i)}case"Transformation":{let n=i1(e.transformation,t),r=t?Bt(e.from,!0):Bt(e.to,!1),o=t?Bt(e.to,!0):Bt(e.from,!1);return(i,a)=>Uu(Vo(Jm(r(i,a),(s)=>new Km(e,i,t?"Encoded":"Type",s)),(s)=>Vo(Jm(n(s,a??Bm,e,i),(c)=>new Km(e,i,"Transformation",c)),(c)=>Jm(o(c,a),(l)=>new Km(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)=>Uu(n(r,o??Bm,e),e,r,o)}case"Literal":return Sn(e,(n)=>n===e.literal);case"UniqueSymbol":return Sn(e,(n)=>n===e.symbol);case"UndefinedKeyword":return Sn(e,VR);case"NeverKeyword":return Sn(e,WR);case"UnknownKeyword":case"AnyKeyword":case"VoidKeyword":return ue;case"StringKeyword":return Sn(e,Ut);case"NumberKeyword":return Sn(e,kn);case"BooleanKeyword":return Sn(e,ma);case"BigIntKeyword":return Sn(e,di);case"SymbolKeyword":return Sn(e,ha);case"ObjectKeyword":return Sn(e,rn);case"Enums":return Sn(e,(n)=>e.enums.some(([r,o])=>o===n));case"TemplateLiteral":{if(e.spans.every((r)=>$m(r.type)))return Sn(e,(r)=>{if(!Ut(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=NM(e);return Sn(e,(r)=>Ut(r)&&n.test(r))}case"TupleType":{let n=e.elements.map((l)=>Bt(l.type,t)),r=e.rest.map((l)=>Bt(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=ew(e),c=tw(e);return(l,u)=>{if(!oy(l))return ce(new Zn(e,l));let d=u?.errors==="all",p=[],m=0,f=[],y=l.length;for(let C=y;C<=i-1;C++){let M=new It(C,l,new vc(o[C-y]));if(d){p.push([m++,M]);continue}else return ce(new ot(e,l,M,f))}if(e.rest.length===0)for(let C=e.elements.length;C<=y-1;C++){let M=new It(C,l,new nw(l[C],`is unexpected, expected: ${a}`));if(d){p.push([m++,M]);continue}else return ce(new ot(e,l,M,f))}let g=0,x=void 0;for(;g<n.length;g++)if(y<g+1){if(e.elements[g].isOptional)continue}else{let C=n[g],M=C(l[g],u);if(bn(M)){if(qe(M)){let N=new It(g,l,M.left);if(d){p.push([m++,N]);continue}else return ce(new ot(e,l,N,Tr(f)))}f.push([m++,M.right])}else{let N=m++,O=g;if(!x)x=[];x.push(({es:k,output:I})=>vr(Za(M),(S)=>{if(qe(S)){let D=new It(O,l,S.left);if(d)return k.push([N,D]),Nn;else return ce(new ot(e,l,D,Tr(I)))}return I.push([N,S.right]),Nn}))}}if(Fe(r)){let[C,...M]=r;for(;g<y-M.length;g++){let N=C(l[g],u);if(bn(N))if(qe(N)){let O=new It(g,l,N.left);if(d){p.push([m++,O]);continue}else return ce(new ot(e,l,O,Tr(f)))}else f.push([m++,N.right]);else{let O=m++,k=g;if(!x)x=[];x.push(({es:I,output:S})=>vr(Za(N),(D)=>{if(qe(D)){let P=new It(k,l,D.left);if(d)return I.push([O,P]),Nn;else return ce(new ot(e,l,P,Tr(S)))}else return S.push([O,D.right]),Nn}))}}for(let N=0;N<M.length;N++){let O=g+N;if(y<O+1)continue;else{let k=M[N](l[O],u);if(bn(k)){if(qe(k)){let I=new It(O,l,k.left);if(d){p.push([m++,I]);continue}else return ce(new ot(e,l,I,Tr(f)))}f.push([m++,k.right])}else{let I=m++;if(!x)x=[];x.push(({es:S,output:D})=>vr(Za(k),(P)=>{if(qe(P)){let pe=new It(O,l,P.left);if(d)return S.push([I,pe]),Nn;else return ce(new ot(e,l,pe,Tr(D)))}return D.push([I,P.right]),Nn}))}}}}let v=({es:C,output:M})=>gi(C)?ce(new ot(e,l,Tr(C),Tr(M))):ue(Tr(M));if(x&&x.length>0){let C=x;return Eu(()=>{let M={es:Ds(p),output:Ds(f)};return vr(ku(C,(N)=>N(M),{concurrency:s,batching:c,discard:!0}),()=>v(M))})}return v({output:f,es:p})}}case"TypeLiteral":{if(e.propertySignatures.length===0&&e.indexSignatures.length===0)return Sn(e,zR);let n=[],r={},o=[];for(let u of e.propertySignatures)n.push([Bt(u.type,t),u]),r[u.name]=null,o.push(u.name);let i=e.indexSignatures.map((u)=>[Bt(u.parameter,t),Bt(u.type,t),u.parameter]),a=on.make(e.indexSignatures.map((u)=>u.parameter).concat(o.map((u)=>ha(u)?new Dm(u):new Xa(u)))),s=Bt(a,t),c=ew(e),l=tw(e);return(u,d)=>{if(!Ng(u))return ce(new Zn(e,u));let p=d?.errors==="all",m=[],f=0,y=d?.onExcessProperty==="error",g=d?.onExcessProperty==="preserve",x={},v;if(y||g){v=Reflect.ownKeys(u);for(let O of v){let k=s(O,d);if(bn(k)&&qe(k))if(y){let I=new It(O,u,new nw(u[O],`is unexpected, expected: ${String(a)}`));if(p){m.push([f++,I]);continue}else return ce(new ot(e,u,I,x))}else x[O]=u[O]}}let C=void 0,M=d?.exact===!0;for(let O=0;O<n.length;O++){let k=n[O][1],I=k.name,S=Object.prototype.hasOwnProperty.call(u,I);if(!S){if(k.isOptional)continue;else if(M){let pe=new It(I,u,new vc(k));if(p){m.push([f++,pe]);continue}else return ce(new ot(e,u,pe,x))}}let D=n[O][0],P=D(u[I],d);if(bn(P)){if(qe(P)){let pe=new It(I,u,S?P.left:new vc(k));if(p){m.push([f++,pe]);continue}else return ce(new ot(e,u,pe,x))}x[I]=P.right}else{let pe=f++,De=I;if(!C)C=[];C.push(({es:Rt,output:Tt})=>vr(Za(P),(et)=>{if(qe(et)){let Je=new It(De,u,S?et.left:new vc(k));if(p)return Rt.push([pe,Je]),Nn;else return ce(new ot(e,u,Je,Tt))}return Tt[De]=et.right,Nn}))}}for(let O=0;O<i.length;O++){let k=i[O],I=k[0],S=k[1],D=hb(u,k[2]);for(let P of D){let pe=I(P,d);if(bn(pe)&&Ct(pe)){let De=S(u[P],d);if(bn(De)){if(qe(De)){let Rt=new It(P,u,De.left);if(p){m.push([f++,Rt]);continue}else return ce(new ot(e,u,Rt,x))}else if(!Object.prototype.hasOwnProperty.call(r,P))x[P]=De.right}else{let Rt=f++,Tt=P;if(!C)C=[];C.push(({es:et,output:Je})=>vr(Za(De),(it)=>{if(qe(it)){let lr=new It(Tt,u,it.left);if(p)return et.push([Rt,lr]),Nn;else return ce(new ot(e,u,lr,Je))}else{if(!Object.prototype.hasOwnProperty.call(r,P))Je[P]=it.right;return Nn}}))}}}}let N=({es:O,output:k})=>{if(gi(O))return ce(new ot(e,u,Tr(O),k));if(d?.propertyOrder==="original"){let I=v||Reflect.ownKeys(u);for(let D of o)if(I.indexOf(D)===-1)I.push(D);let S={};for(let D of I)if(Object.prototype.hasOwnProperty.call(k,D))S[D]=k[D];return ue(S)}return ue(k)};if(C&&C.length>0){let O=C;return Eu(()=>{let k={es:Ds(m),output:Object.assign({},x)};return vr(ku(O,(I)=>I(k),{concurrency:c,batching:l,discard:!0}),()=>N(k))})}return N({es:m,output:x})}}case"Union":{let n=zM(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],Bt(e.types[l],t));let s=ew(e)??1,c=tw(e);return(l,u)=>{let d=[],p=0,m=[];if(o>0)if(xl(l))for(let g=0;g<o;g++){let x=r[g],v=n.keys[x].buckets;if(Object.prototype.hasOwnProperty.call(l,x)){let C=String(l[x]);if(Object.prototype.hasOwnProperty.call(v,C))m=m.concat(v[C]);else{let{candidates:M,literals:N}=n.keys[x],O=on.make(N),k=M.length===i?new Qr([new Et(x,O,!1,!0)],[]):on.make(M);d.push([p++,new ot(k,l,new It(x,l,new Zn(O,l[x])))])}}else{let{candidates:C,literals:M}=n.keys[x],N=new Et(x,on.make(M),!1,!0),O=C.length===i?new Qr([N],[]):on.make(C);d.push([p++,new ot(O,l,new It(x,l,new vc(N)))])}}else{let g=n.candidates.length===i?e:on.make(n.candidates);d.push([p++,new Zn(g,l)])}if(n.otherwise.length>0)m=m.concat(n.otherwise);let f=void 0;for(let g=0;g<m.length;g++){let x=m[g],v=a.get(x)(l,u);if(bn(v)&&(!f||f.length===0))if(Ct(v))return v;else d.push([p++,v.left]);else{let C=p++;if(!f)f=[];f.push((M)=>Eu(()=>{if("finalResult"in M)return Nn;else return vr(Za(v),(N)=>{if(Ct(N))M.finalResult=N;else M.es.push([C,N.left]);return Nn})}))}}let y=(g)=>gi(g)?g.length===1&&g[0][1]._tag==="Type"?ce(g[0][1]):ce(new ot(e,l,Tr(g))):ce(new Zn(e,l));if(f&&f.length>0){let g=f;return Eu(()=>{let x={es:Ds(d)};return vr(ku(g,(v)=>v(x),{concurrency:s,batching:c,discard:!0}),()=>{if("finalResult"in x)return x.finalResult;return y(x.es)})})}return y(d)}}case"Suspend":{let n=Iu(()=>Bt(e.f(),t));return(r,o)=>n()(r,o)}}},Sn=(e,t)=>(n)=>t(n)?ue(n):ce(new Zn(e,n)),qu=(e,t)=>{switch(e._tag){case"Declaration":{let n=Hb(e);if($e(n))return qu(n.value,t);break}case"TypeLiteral":{let n=[];for(let r=0;r<e.propertySignatures.length;r++){let o=e.propertySignatures[r],i=t?Vm(o.type):_t(o.type);if(Lm(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?Vm(o.type):_t(o.type);if(Lm(i)&&!o.isOptional)n.push([r,i])}return n}case"Refinement":return qu(e.from,t);case"Suspend":return qu(e.f(),t);case"Transformation":return qu(t?e.from:e.to,t)}return[]},zM=(e,t)=>{let n={},r=[],o=[];for(let i=0;i<e.length;i++){let a=e[i],s=qu(a,t);if(s.length>0){o.push(a);for(let c=0;c<s.length;c++){let[l,u]=s[c],d=String(u.literal);n[l]=n[l]||{buckets:{},literals:[],candidates:[]};let p=n[l].buckets;if(Object.prototype.hasOwnProperty.call(p,d)){if(c<s.length-1)continue;p[d].push(a),n[l].literals.push(u),n[l].candidates.push(a)}else{p[d]=[a],n[l].literals.push(u),n[l].candidates.push(a);break}}}else r.push(a)}return{keys:n,otherwise:r,candidates:o}},KM=(e)=>Lu(e)?KM(e.from):e,Uu=(e,t,n,r)=>{if(r?.isEffectAllowed===!0)return e;if(bn(e))return e;let o=new Su,i=FP(e,{scheduler:o});o.flush();let a=i.unsafePoll();if(a){if(MI(a))return ue(a.value);let s=a.cause;if(Tk(s))return ce(s.error);return ce(new rw(t,n,Ck(s)))}return ce(new rw(t,n,"cannot be be resolved synchronously, this is caused by using runSync on an effect that performs async work"))},o1=([e],[t])=>e>t?1:e<t?-1:0,i1=(e,t)=>{switch(e._tag){case"FinalTransformation":return t?e.decode:e.encode;case"ComposeTransformation":return ue;case"TypeLiteralTransformation":return(n)=>{let r=ue(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=Cr(r,(l)=>{let u=s(Object.prototype.hasOwnProperty.call(l,i)?Y(l[i]):B());if(delete l[i],$e(u))l[a]=u.value;return l})}return r}}},an=(e,t=[])=>({value:e,forest:t}),$u,a1=(e)=>e.value+JM(`
34
- `,e.forest),JM=(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+=JM(e+(r>1&&!a?"\u2502 ":" "),o.forest)}return n},s1=(e)=>{switch(e){case"Encoded":return"Encoded side transformation failure";case"Transformation":return"Transformation process failure";case"Type":return"Type side transformation failure"}},c1=(e)=>{switch(e){case"From":return"From side refinement failure";case"Predicate":return"Predicate refinement failure"}},GM=(e)=>("ast"in e)?Y(e.ast):B(),ow,l1=(e)=>GM(e).pipe(mr(oM),dt({onNone:()=>ow,onSome:(t)=>{let n=t(e);if(Ut(n))return ue({message:n,override:!1});if(PP(n))return Im(n,(r)=>({message:r,override:!1}));if(Ut(n.message))return ue({message:n.message,override:n.override});return Im(n.message,(r)=>({message:r,override:n.override}))}})),sw=(e)=>(t)=>t._tag===e,YM,qM,UM,ju=(e)=>Vo(l1(e),(t)=>{if(t!==void 0)return!t.override&&(YM(e)||qM(e)&&e.kind==="From"||UM(e)&&e.kind!=="Transformation")?UM(e)||qM(e)?ju(e.issue):ow:ue(t.message);return ow}),ZM=(e)=>GM(e).pipe(mr(cM),wT((t)=>t(e)),gn),p1=(e)=>Cr(ju(e),(t)=>t??ZM(e)??d1(e)),Wm=(e)=>ZM(e)??String(e.ast),f1=(e)=>e.message??"is forbidden",m1=(e)=>e.message??"is unexpected",h1=(e)=>{let t=iM(e.ast);if($e(t)){let n=t.value();return Ut(n)?ue(n):n}return ue(e.message??"is missing")},Rc=(e)=>{switch(e._tag){case"Type":return Cr(p1(e),an);case"Forbidden":return ue(an(Wm(e),[an(f1(e))]));case"Unexpected":return ue(an(m1(e)));case"Missing":return Cr(h1(e),an);case"Transformation":return Vo(ju(e),(t)=>{if(t!==void 0)return ue(an(t));return Cr(Rc(e.issue),(n)=>an(Wm(e),[an(s1(e.kind),[n])]))});case"Refinement":return Vo(ju(e),(t)=>{if(t!==void 0)return ue(an(t));return Cr(Rc(e.issue),(n)=>an(Wm(e),[an(c1(e.kind),[n])]))});case"Pointer":return Cr(Rc(e.issue),(t)=>an(Am(e.path),[t]));case"Composite":return Vo(ju(e),(t)=>{if(t!==void 0)return ue(an(t));let n=Wm(e);return gb(e.issues)?Cr(ku(e.issues,Rc),(r)=>an(n,r)):Cr(Rc(e.issues),(r)=>an(n,[r]))})}};var cw=w(()=>{st();Ok();yE();DP();hn();NI();ne();at();Au();pt();Ae();mm();Qb();DM=Symbol.for("effect/Schema/ParseErrorTypeId");$M=class $M extends gE("ParseError"){[DM]=DM;get message(){return this.toString()}toString(){return $u.formatIssueSync(this.issue)}toJSON(){return{_id:"ParseError",message:this.toString()}}[me](){return this.toJSON()}};jM=ue,HM=ce,bn=Yg,Vo=h(2,(e,t)=>bn(e)?El(e,{onLeft:ce,onRight:t}):vr(e,t)),Cr=h(2,(e,t)=>bn(e)?mT(e,t):Im(e,t)),Jm=h(2,(e,t)=>bn(e)?xp(e,t):NP(e,t)),BM=h(2,(e,t)=>bn(e)?El(e,{onLeft:t,onRight:ue}):MP(e,t)),t1=re(Symbol.for("effect/ParseResult/decodeMemoMap"),()=>new WeakMap),n1=re(Symbol.for("effect/ParseResult/encodeMemoMap"),()=>new WeakMap);$u={formatIssue:(e)=>Cr(Rc(e),a1),formatIssueSync:(e)=>{let t=$u.formatIssue(e);return bn(t)?gT(t):LP(t)},formatError:(e)=>$u.formatIssue(e.issue),formatErrorSync:(e)=>$u.formatIssueSync(e.issue)},ow=ue(void 0),YM=sw("Composite"),qM=sw("Refinement"),UM=sw("Transformation")});var XM,QM;var eN=w(()=>{ne();Ae();XM=h((e)=>rn(e[0]),(e,...t)=>{let n={};for(let r of t)if(r in e)n[r]=e[r];return n}),QM=h((e)=>rn(e[0]),(e,...t)=>{let n={...e};for(let r of t)delete n[r];return n})});function Vt(e){return class{[Bu]=tN;static ast=e;static annotations(n){return Vt(eo(this.ast,n))}static pipe(){return F(this,arguments)}static toString(){return String(e)}static Type;static Encoded;static Context;static[Bu]=tN}}function x1(e){return jm(e)?on.make(AM(e,(t)=>new Xa(t))):new Xa(e[0])}function cN(e,t=x1(e)){return class extends Vt(t){static annotations(r){return cN(this.literals,eo(this.ast,r))}static literals=[...e]}}function E(...e){return Fe(e)?cN(e):dw}function uw(e,t){return class extends Vt(t){static annotations(r){return uw(this.typeParameters,eo(this.ast,r))}static typeParameters=[...e]}}function uN(e,t=w1(e)){return class extends Vt(t){static annotations(r){return uN(this.members,eo(this.ast,r))}static members=[...e]}}function Se(...e){return jm(e)?uN(e):Fe(e)?e[0]:dw}function Ym(e,t,n=v1(e,t)){return class extends Vt(n){static annotations(o){return Ym(this.elements,this.rest,eo(this.ast,o))}static elements=[...e];static rest=[...t]}}function dN(...e){return Array.isArray(e[0])?Ym(e[0],e.slice(1)):Ym(e,[])}function pN(e,t){return class extends Ym([],[e],t){static annotations(r){return pN(this.value,eo(this.ast,r))}static value=e}}class mN{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<${lw(this.to.isOptional)}, ${this.to.type}, ${R1(this.from.fromKey)}, ${lw(this.from.isOptional)}, ${this.from.type}>`}}function gw(e,t,n=C1(e,t)){return class extends Vt(n){static annotations(o){return gw(this.fields,this.records,eo(this.ast,o))}static fields={...e};static records=[...t];static make=(o,i)=>{let a=O1(e,{...o});return bw(i)?a:Hu(this)(a)};static pick(...o){return T(XM(e,...o))}static omit(...o){return T(QM(e,...o))}}}function T(e,...t){return gw(e,t)}function xN(e,t,n){return class extends gw({},[{key:e,value:t}],n){static annotations(o){return xN(e,t,eo(this.ast,o))}static key=e;static value=t}}function SN(e,t){return class extends Vt(t){static annotations(r){return SN(this.from,eo(this.ast,r))}static make=(r,o)=>bw(o)?r:Hu(this)(r);static from=e}}function bN(e,t,n){return class extends Vt(n){static annotations(o){return bN(this.from,this.filter,eo(this.ast,o))}static[k1]=e;static from=e;static filter=t;static make=(o,i)=>bw(i)?o:Hu(this)(o)}}function Ze(e,t){return(n)=>{function r(i,a,s){return E1(e(i,a,s),s,i)}let o=new Fu(n.ast,r,Qa(t));return bN(n,r,o)}}function bw(e){return ma(e)?e:e?.disableValidation??!1}var Bu,tN,nN,Qa=(e)=>{if(!e)return{};let t={...e};for(let n in nN)if(n in e){let r=nN[n];t[r]=e[n],delete t[n]}return t},eo=(e,t)=>Du(e,Qa(t)),Vu=(e,t)=>{let n=WM(e,t);return(r,o)=>xp(n(r,o),iw)},rN=(e)=>H(e,Bu)&&rn(e[Bu]),S1=(e,t,n)=>uw(e,new bc(e.map((r)=>r.ast),(...r)=>t.decode(...r.map(Vt)),(...r)=>t.encode(...r.map(Vt)),Qa(n))),b1=(e,t)=>{let n=()=>(o,i,a)=>e(o)?jM(o):HM(new Zn(a,o));return uw([],new bc([],n,n,Qa(t)))},ee=function(){if(Array.isArray(arguments[0])){let n=arguments[0],r=arguments[1],o=arguments[2];return S1(n,r,o)}let e=arguments[0],t=arguments[1];return b1(e,t)},lN,At,dw,pw,q,wn,V,w1=(e)=>on.make(e.map((t)=>t.ast)),_1=(e)=>Se(e,lN),v1=(e,t)=>new Nu(e.map((n)=>rN(n)?new Hi(n.ast,!1):n.ast),t.map((n)=>rN(n)?new wc(n.ast):n.ast),!0),K=(e)=>pN(e),lw=(e)=>e?'"?:"':'":"',fw,fN,R1=(e)=>{if(e===void 0)return"never";if(Ut(e))return JSON.stringify(e);return String(e)},hN=(e,t)=>{switch(e._tag){case"PropertySignatureDeclaration":return new fw(e.type,e.isOptional,e.isReadonly,{...e.annotations,...t},e.defaultValue);case"PropertySignatureTransformation":return new mN(e.from,new fN(e.to.type,e.to.isOptional,e.to.isReadonly,{...e.to.annotations,...t},e.to.defaultValue),e.decode,e.encode)}},gN,yN=(e)=>H(e,gN),mw,hw,R=(e)=>{let t=e.ast===qm||e.ast===Um?qm:_1(e).ast;return new hw(new fw(t,!0,!0,{},void 0),e)},T1,C1=(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(yN(u)){let d=u.ast;switch(d._tag){case"PropertySignatureDeclaration":{let{type:p,isOptional:m,annotations:f}=d;i.push(new Et(l,p,m,!0,T1(d))),a.push(new Et(l,_t(p),m,!0,f)),r.push(new Et(l,p,m,!0,f));break}case"PropertySignatureTransformation":{let p=d.from.fromKey??l;i.push(new Et(p,d.from.type,d.from.isOptional,!0,d.from.annotations)),a.push(new Et(l,d.to.type,d.to.isOptional,!0,d.to.annotations)),s.push(new Jb(p,l,d.decode,d.encode));break}}}else i.push(new Et(l,u.ast,!1,!0)),a.push(new Et(l,_t(u.ast),!1,!0)),r.push(new Et(l,u.ast,!1,!0))}if(Fe(s)){let c=[],l=[];for(let u of t){let{indexSignatures:d,propertySignatures:p}=Yb(u.key.ast,u.value.ast);p.forEach((m)=>{i.push(m),a.push(new Et(m.name,_t(m.type),m.isOptional,m.isReadonly,m.annotations))}),d.forEach((m)=>{c.push(m),l.push(new _c(m.parameter,_t(m.type),m.isReadonly))})}return new Kb(new Qr(i,c,{[Fm]:"Struct (Encoded side)"}),new Qr(a,l,{[Fm]:"Struct (Type side)"}),new Gb(s))}}let o=[];for(let i of t){let{indexSignatures:a,propertySignatures:s}=Yb(i.key.ast,i.value.ast);s.forEach((c)=>r.push(c)),a.forEach((c)=>o.push(c))}return new Qr(r,o)},O1=(e,t)=>{let n=Reflect.ownKeys(e);for(let r of n){let o=e[r];if(t[r]===void 0&&yN(o)){let i=o.ast,a=i._tag==="PropertySignatureDeclaration"?i.defaultValue:i.to.defaultValue;if(a!==void 0)t[r]=a()}}return t},Zm=(e)=>xN(e.key,e.value),Wu=(e,t)=>(n)=>{let r=dt(qb(n.ast),{onNone:()=>[e],onSome:(i)=>[...i,e]}),o=Du(n.ast,Qa({[vb]:r,...t}));return SN(n,o)},k1,oN=(e,t,n)=>{if(ma(e))return e?B():Y(new Zn(t,n));if(Ut(e))return Y(new Zn(t,n,e));if(e!==void 0){if("_tag"in e)return Y(e);let r=new Zn(t,n,e.message);return Y(Fe(e.path)?new It(e.path,n,r):r)}return B()},E1=(e,t,n)=>{if(UP(e))return oN(e,t,n);if(Fe(e)){let r=_p(e,(o)=>oN(o,t,n));if(Fe(r))return Y(r.length===1?r[0]:new ot(t,n,r))}return B()},I1,yw=(e,t)=>(n)=>n.pipe(Ze((r)=>r.length<=e,{schemaId:I1,title:`maxLength(${e})`,description:`a string at most ${e} character(s) long`,jsonSchema:{maxLength:e},...t})),A1,Tc=(e,t)=>(n)=>n.pipe(Ze((r)=>r.length>=e,{schemaId:A1,title:`minLength(${e})`,description:`a string at least ${e} character(s) long`,jsonSchema:{minLength:e},...t})),iN,we=(e,t)=>(n)=>{let r=e.source;return n.pipe(Ze((o)=>(e.lastIndex=0,e.test(o)),{schemaId:iN,[iN]:{regex:e},description:`a string matching the pattern ${r}`,jsonSchema:{pattern:r},...t}))},P1,aN,M1,N1,xw=(e,t)=>(n)=>n.pipe(Ze((r)=>r>e,{schemaId:N1,title:`greaterThan(${e})`,description:e===0?"a positive number":`a number greater than ${e}`,jsonSchema:{exclusiveMinimum:e},...t})),F1,wN=(e,t)=>(n)=>n.pipe(Ze((r)=>r>=e,{schemaId:F1,title:`greaterThanOrEqualTo(${e})`,description:e===0?"a non-negative number":`a number greater than or equal to ${e}`,jsonSchema:{minimum:e},...t})),L1,Xm=(e)=>(t)=>t.pipe(Ze((n)=>Number.isSafeInteger(n),{schemaId:L1,title:"int",description:"an integer",jsonSchema:{type:"integer"},...e})),Sw=(e)=>xw(0,{title:"positive",...e}),Qm,D1,to=(e,t)=>(n)=>{let r=Math.floor(e);if(r<1)throw Error($P(`Expected an integer greater than or equal to 1, actual ${e}`));return n.pipe(Ze((o)=>o.length>=r,{schemaId:D1,title:`minItems(${r})`,description:`an array of at least ${r} item(s)`,jsonSchema:{minItems:r},[Db]:!0,...t}))},sN,q1;var Dt=w(()=>{st();hn();gl();bb();QP();Au();pt();cw();Ne();Ae();Qb();eN();cw();Bu=Symbol.for("effect/Schema");tN={_A:(e)=>e,_I:(e)=>e,_R:(e)=>e},nN={typeConstructor:tM,schemaId:nM,message:Rb,missingMessage:Mm,identifier:Nm,title:xn,description:Bo,examples:Tb,default:Cb,documentation:rM,jsonSchema:Ob,arbitrary:kb,pretty:Eb,equivalence:Ib,concurrency:Ab,batching:Pb,parseIssueTitle:Mb,parseOptions:Nb,decodingFallback:Fb};lN=class lN extends Vt(qm){};At=class At extends Vt(dM){};dw=class dw extends Vt(Um){};pw=class pw extends Vt(Wb){};q=class q extends Vt(SM){};wn=class wn extends Vt(wM){};V=class V extends Vt(vM){};fw=class fw extends Hi{isReadonly;defaultValue;_tag="PropertySignatureDeclaration";constructor(e,t,n,r,o){super(e,t,r);this.isReadonly=n,this.defaultValue=o}toString(){let e=lw(this.isOptional),t=String(this.type);return`PropertySignature<${e}, ${t}, never, ${e}, ${t}>`}};fN=class fN extends Hi{isReadonly;defaultValue;constructor(e,t,n,r,o){super(e,t,r);this.isReadonly=n,this.defaultValue=o}};gN=Symbol.for("effect/PropertySignature");mw=class mw{ast;[Bu];[gN]=null;_TypeToken;_Key;_EncodedToken;_HasDefault;constructor(e){this.ast=e}pipe(){return F(this,arguments)}annotations(e){return new mw(hN(this.ast,Qa(e)))}toString(){return String(this.ast)}};hw=class hw extends mw{from;constructor(e,t){super(e);this.from=t}annotations(e){return new hw(hN(this.ast,Qa(e)),this.from)}};T1=Zb([Mm]);k1=Symbol.for("effect/SchemaId/Refine");I1=ZP,A1=YP,iN=Symbol.for("effect/SchemaId/Pattern"),P1=Symbol.for("effect/SchemaId/UUID"),aN=/^[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;M1=class M1 extends q.pipe(we(aN,{schemaId:P1,identifier:"UUID",jsonSchema:{format:"uuid",pattern:aN.source},description:"a Universally Unique Identifier",arbitrary:()=>(e)=>e.uuid()})){};N1=KP,F1=JP,L1=GP;Qm=class Qm extends wn.pipe(Xm({identifier:"Int"})){};D1=XP,sN=zP;q1=class q1 extends ee(cp,{typeConstructor:{_tag:"Date"},identifier:"DateFromSelf",schemaId:sN,[sN]:{noInvalidDate:!1},description:"a potentially invalid Date instance",pretty:()=>(e)=>`new Date(${JSON.stringify(e)})`,arbitrary:()=>(e)=>e.date({noInvalidDate:!1}),equivalence:()=>HR}){}});function Xn(e,t){return Vu(e,U1)(t)}var U1;var Cc=w(()=>{Dt();U1={onExcessProperty:"error"}});function CN(e){let t=Vu(Oc)(e);return Ct(t)?t.right:void 0}function ww(e){return CN(e)!==void 0}function ON(e){return ww(e)&&!e.includes("-")}function _N(e){if(e===void 0||e.length===0||e[0]==="0")return!1;for(let t of e)if(t<"0"||t>"9")return!1;return!0}function $1(e){let[t,n,r]=e.split("-");if(t===void 0||n===void 0||r!==void 0)return!1;if(!ON(t))return!1;let[o,i,a,s]=n.split(".");return o==="dev"&&s===void 0&&_N(i)&&_N(a)}function eh(e){let t=CN(e);if(t===void 0)throw Error(`The canonical version ${e} is invalid.`);let n=t.split("-",1)[0];if(n===void 0)throw Error(`The canonical version ${e} has no base version.`);return n}function Ec(e,t){let n=vN(e),r=vN(t),o=zu(n.minor,r.minor);if(o!==0)return o;let i=zu(n.patch,r.patch);if(i!==0)return i;return j1(n.suffix,r.suffix)}function vw(e,t){let n=eh(t);if(e!=="patch"&&e!=="minor"){if(!ww(e))throw Error("The version target is invalid.");return e}let[,r,o]=n.split(".");if(r===void 0||o===void 0)throw Error(`The canonical version ${t} has an invalid base version.`);let i=BigInt(r),a=BigInt(o);return e==="minor"?`0.${i+1n}.0`:`0.${i}.${a+1n}`}function vN(e){let[t,n]=e.split("-",2),r=t?.split("."),o=r?.[1],i=r?.[2];if(o===void 0||i===void 0)throw Error(`The release version ${e} has an invalid base version.`);if(n===void 0)return{minor:o,patch:i,suffix:{kind:"base"}};if(n.startsWith("dev.")){let[,a,s]=n.split(".");if(a===void 0||s===void 0)throw Error(`The development version ${e} has an invalid release suffix.`);return{minor:o,patch:i,suffix:{kind:"development",runNumber:a,runAttempt:s}}}return{minor:o,patch:i,suffix:{kind:"numeric",value:n}}}function zu(e,t){let n=BigInt(e),r=BigInt(t);if(n<r)return-1;if(n>r)return 1;return 0}function j1(e,t){let n=RN(e),r=RN(t);if(n<r)return-1;if(n>r)return 1;if(e.kind==="numeric"&&t.kind==="numeric")return zu(e.value,t.value);if(e.kind==="development"&&t.kind==="development"){let o=zu(e.runNumber,t.runNumber);return o===0?zu(e.runAttempt,t.runAttempt):o}return 0}function RN(e){if(e.kind==="development")return 0;if(e.kind==="base")return 1;return 2}var TN,Oc,_w,kN,kc;var EN=w(()=>{hn();Dt();TN=/^0\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)(?:-(?:0|[1-9]\d*))?$/u,Oc=q.pipe(we(TN));_w=q.pipe(Ze(ON));kN=q.pipe(Ze($1)),kc=Se(Oc,kN)});function Cw(e,t){if(typeof t!=="string")return;let n=e.lastIndexOf("@");if(n<=0)return;let r=e.slice(0,n),o=e.slice(n+1);if(r==="unified-computer-use"&&o==="openai-bundled"&&t===o)return{pluginName:"computer-use",marketplaceName:o,canonicalPluginId:"computer-use@openai-bundled"};if(r==="sites"&&o==="openai-curated-remote"&&t===o)return{pluginName:r,marketplaceName:o,canonicalPluginId:"sites@openai-bundled"};if(Tw.includes(r)&&o==="openai-bundled"&&t===o)return{pluginName:r,marketplaceName:o,canonicalPluginId:e};if(!PN(r)||!AN(o)||t!==o)return;return{pluginName:r,marketplaceName:o,canonicalPluginId:`${r}@openai-curated`}}function Qn(e){let t=e.lastIndexOf("@");if(t<=0)return;let n=e.slice(0,t),r=e.slice(t+1);if(n==="unified-computer-use"&&r==="openai-bundled")return"computer-use@openai-bundled";if(n==="sites"&&r==="openai-curated-remote")return"sites@openai-bundled";if(PN(n)&&AN(r))return`${n}@openai-curated`;if(Tw.includes(n)&&r==="openai-bundled")return`${n}@openai-bundled`;return}function Ic(e){let t=Qn(e);if(t===void 0)return[];if(t==="computer-use@openai-bundled")return Object.freeze(["unified-computer-use@openai-bundled",t]);if(t==="sites@openai-bundled")return Object.freeze([t,"sites@openai-curated-remote"]);if(t.endsWith("@openai-bundled"))return Object.freeze([t]);let n=t.slice(0,t.lastIndexOf("@"));return Object.freeze([t,`${n}@openai-curated-remote`])}function AN(e){return IN.includes(e)}function PN(e){return th.includes(e)}function Ow(e,t){let n=t??en;return{browser_use:e?.browser_use??n.browser_use,computer_use:e?.computer_use??n.computer_use,sites:e?.sites??n.sites}}function Ac(e,t=[]){let n=[...NN],r=new Set(n);for(let o of MN){if(!e[o])continue;for(let i of Wo[o].pluginIds)if(!r.has(i))r.add(i),n.push(i)}for(let o of t){if(o==="browser@openai-bundled")continue;if(!r.has(o))r.add(o),n.push(o)}return n}var Ku,Rw,H1,B1,IN,th,Tw,Pt,Bi,V1,W1,Wo,MN,z1,NN,K1,en;var kw=w(()=>{Dt();Ku=E("browser_use","computer_use","frontend","security","sites"),Rw=E("browser_use","computer_use","sites"),H1=E("installed","disabled","missing","uncertain"),B1=E("healthy","missing","disabled","uncertain"),IN=Object.freeze(["openai-curated","openai-curated-remote"]),th=Object.freeze(["build-web-apps","codex-security"]),Tw=Object.freeze(["browser","computer-use","sites"]);Pt=Object.freeze({coding:!0,computer_use:!1,browser_use:!0,sites:!0,frontend:!0,security:!0}),Bi=Object.freeze({frontend:Object.freeze([{skillId:"build-web-apps:frontend-app-builder",appliesWhen:"a new visually-driven UI or meaningful redesign"},{skillId:"build-web-apps:frontend-testing-debugging",appliesWhen:"a rendered UI or interaction defect"},{skillId:"build-web-apps:react-best-practices",appliesWhen:"a relevant React or Next implementation or review"}]),security:Object.freeze([]),computer_use:Object.freeze([]),browser_use:Object.freeze([]),sites:Object.freeze([])}),V1=Bi.frontend,W1={frontend:{name:"frontend",pluginIds:["build-web-apps@openai-curated"],defaultSelected:Pt.frontend,semanticSkillIds:Object.freeze(Bi.frontend.map(({skillId:e})=>e)),applicability:Bi.frontend,ownership:"shared-preserve"},security:{name:"security",pluginIds:["codex-security@openai-curated"],defaultSelected:Pt.security,semanticSkillIds:["codex-security:security-scan","codex-security:security-diff-scan","codex-security:threat-model"],applicability:Bi.security,ownership:"shared-preserve"},computer_use:{name:"computer_use",pluginIds:["computer-use@openai-bundled"],defaultSelected:Pt.computer_use,migrationKey:"computer_use",semanticSkillIds:["computer-use:computer-use"],applicability:Bi.computer_use,ownership:"shared-preserve"},browser_use:{name:"browser_use",pluginIds:[],defaultSelected:Pt.browser_use,migrationKey:"browser_use",semanticSkillIds:[],applicability:Bi.browser_use,ownership:"shared-preserve"},sites:{name:"sites",pluginIds:["sites@openai-bundled"],defaultSelected:Pt.sites,migrationKey:"sites",semanticSkillIds:[],applicability:Bi.sites,ownership:"shared-preserve"}},Wo=Object.freeze(W1),MN=Object.freeze(["browser_use","computer_use","sites"]),z1=Object.freeze(["frontend","security"]),NN=Object.freeze([...Wo.frontend.pluginIds,...Wo.security.pluginIds]),K1=Object.freeze(["writing-instructions","babysit-ci","dev-server","visual-loop"]),en=Object.freeze({browser_use:Pt.browser_use,computer_use:Pt.computer_use,sites:Pt.sites})});function no(e){return T({identifier:E(e),label:q,requiresRootApproval:V})}function FN(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 LN(e){return e.length===0?e:`${e[0]?.toUpperCase()??""}${e.slice(1)}`}var DN,J1,G1,Ew,Y1,qN,Z1,X1,Q1;var UN=w(()=>{Dt();DN=E("local.repository.edit","local.repository.check","local.repository.lint","local.repository.format","local.repository.commit","external.read","specialist.dispatch","vcs.server.mutation","vcs.server.ci-trigger","unknown.effect"),J1=T({identifier:DN,label:q,requiresRootApproval:V});G1=T({localRepositoryEdit:no("local.repository.edit"),localRepositoryCheck:no("local.repository.check"),localRepositoryLint:no("local.repository.lint"),localRepositoryFormat:no("local.repository.format"),localRepositoryCommit:no("local.repository.commit"),externalRead:no("external.read"),specialistDispatch:no("specialist.dispatch"),versionControlServerMutation:no("vcs.server.mutation"),versionControlServerCiTrigger:no("vcs.server.ci-trigger"),unknownEffect:no("unknown.effect")}),Ew={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}};jr(Ew);Y1=E("never","root"),qN=Object.values(Ew);Z1=qN.filter((e)=>!e.requiresRootApproval),X1=qN.filter((e)=>e.requiresRootApproval),Q1=Object.freeze({noRootApproval:`${LN(FN(Z1))} actions do not require Root approval.`,rootApproval:`${LN(FN(X1))} require Root approval.`})});function nh(e){let t=Xn(eB,e);if(qe(t))return fa(ul("sha256 digest",t.left));return Os(t.right)}var Or,Iw,GZ,YZ,ZZ,eB,tB,nB,rB,oB;var rh=w(()=>{hn();Dt();ks();Cc();Or=q.pipe(we(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u)),Iw=q.pipe(we(/^[0-9a-f]{64}$/u)),GZ=Or.pipe(Wu("RunId")),YZ=Or.pipe(Wu("ProjectId")),ZZ=Or.pipe(Wu("TrustId")),eB=Iw.pipe(Wu("Sha256Digest"));tB=T({run_id:Or,objective_lineage:Or,parent_run_id:R(Se(Or,At))}),nB=T({project_id:Or,trust_id:Or,trust_digest:Iw}),rB=T({project_id:Or,project_digest:Iw}),oB=q.pipe(we(/^state-[0-9]+\.[0-9]+$/u))});function ah(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 BN(e){return typeof e==="string"&&lB.has(e)}function dB(e){if(typeof e!=="object"||e===null||!("role"in e)||!("task"in e))return!1;let{role:t,task:n}=e;if(!BN(t)||typeof n!=="string")return!1;return Ju.get(t)?.tasks.some((r)=>r.name===n)===!0}function ch(e,t){return typeof t==="string"&&Ju.get(e)?.tasks.some((n)=>n.name===t)===!0}function VN(e){return typeof e==="string"&&uB.has(e)}function Nw(e){let t=`${e.role}.${e.task}`;if(!Pw.has(t))throw Error("Unknown native specialist agent type.");return t}function Fw(e){let t=Ju.get(e.role)?.tasks.find((n)=>n.name===e.task);if(t===void 0)throw Error("Unknown specialist task policy.");return e.role==="Librarian"?`${aB} ${t.instruction}`:t.instruction}function Lw(e){let t=Ju.get(e.role)?.tasks.find((n)=>n.name===e.task);if(t===void 0)throw Error("Unknown specialist task policy.");return t.description}function zN(e){let t=Ju.get(e);if(t===void 0)throw Error("Unknown specialist role.");return t}function Dw(e){let n=zN(e.role).tasks.find((o)=>o.name===e.task);if(n===void 0)throw Error("Unknown specialist task policy.");let r=e.role==="Worker"&&e.task==="operations"?"exact_ref_or_sha":n.permissions.network?"current_sources":"disabled";return Object.freeze({network:n.permissions.network,filesystem:n.permissions.filesystem,sourceMutation:n.permissions.sourceMutation,networkScope:r})}var ro,$N,kr,Ko,iB,sh="Satisfy the complete requested outcome correctly, elegantly, and mergeably; never weaken or reinterpret it to shrink the patch. Then make the smallest coherent patch within the authorized boundary. Prefer simple, cohesive, idiomatic solutions with appropriate abstraction and minimal accidental complexity. Avoid unrelated code, prose, configuration, documentation, instructions, tests, restructuring, formatting churn, files, and operations. Preserve unrelated work; return material scope expansion to Root.",oh="Treat unnecessary text, headings, subheadings, typography hierarchy, cards, pills, badges, decorative containers, labels, microcopy, repeated information, and grouping without information or interaction value as design defects. Use these primitives when they materially improve hierarchy, comprehension, composition, interaction, or content. Every visible item must be necessary or usefully complementary to the content and design.",zo="Do not modify repository source or the implementation under validation; observation, analysis, and proof artifacts only.",aB="For current library, framework, SDK, API, CLI, or cloud-service facts, resolve the library identity and query Context7 narrowly before model memory or web search. Return the typed context7 evidence state with version/source evidence. Use web search only when Context7 is unavailable, lacks relevant coverage or the required version, fails for authentication or quota, or a conflict remains after checking authoritative first-party documentation.",sB,jN,cB,Jo,Ju,lB,Aw,uB,HN,Pw,Mw,pB,fB,mB,hB,Gu,Yu,WN,Go,gB,lh,KN,ih,yB,xB,SB,qw,Zu,bB,Fn,wB,_B,W;var Xu=w(()=>{Dt();ro=E("low","default","high"),$N=E("go","Go","plus-low","plus","plus-high","pro-5x","pro-20x"),kr=Se(ro,$N);Ko=E("standard","fast","fast-all"),iB=E("low","medium","high","xhigh","max"),sB=E("none"),jN=Object.freeze(["implementation","review","validation","integration","vcs"]),cB=E("read-only","workspace-write"),Jo=[{role:"Explorer",tasks:[{name:"map",description:"Bounded repository structure mapping specialist.",instruction:`Map the assigned repository area: locate its relevant packages, entry points, ownership boundaries, and nearby tests or docs. Return a compact path map and identify where a follow-up lookup or trace should start; do not trace runtime behavior or resolve an unrelated fact. ${zo}`,permissions:{network:!0,filesystem:"read-only",sourceMutation:!1}},{name:"lookup",description:"Repository fact lookup specialist.",instruction:`Find the specific requested repository fact and cite its exact path or symbol; keep the search narrower than a structure map or execution trace. ${zo}`,permissions:{network:!0,filesystem:"read-only",sourceMutation:!1}},{name:"trace",description:"Repository execution and reference tracing specialist.",instruction:`Follow the assigned execution or reference path across callers, boundaries, and tests; explain the evidence-backed flow and stop at the assigned boundary. ${zo}`,permissions:{network:!0,filesystem:"read-only",sourceMutation:!1}}],capability:"repository-read",authority:"Read only the delegated Assignment repository scope; Git/VCS writes, Intent lifecycle, and material decisions remain Root-only.",evidence:"Return exact paths, symbols, callers, tests, and constraints.",completion:"Account for every in-scope caller and constraint.",permissions:{network:!0,filesystem:"read-only",sourceMutation:!1}},{role:"Librarian",tasks:[{name:"lookup",description:"Authoritative external fact lookup specialist.",instruction:`Answer the specific external fact with its current authoritative source. ${zo}`,permissions:{network:!0,filesystem:"read-only",sourceMutation:!1}},{name:"research",description:"Current authoritative-source research specialist.",instruction:`Compare and synthesize the assigned current sources with citations, noting conflicts and uncertainty. ${zo}`,permissions:{network:!0,filesystem:"read-only",sourceMutation:!1}}],capability:"current-research",authority:"Research only the delegated Assignment current sources without repository mutation; Git/VCS writes, Intent lifecycle, and material decisions remain Root-only.",evidence:"Return sourced facts, dates, and explicit uncertainty.",completion:"Resolve the assigned external fact or report the exact evidence gap.",permissions:{network:!0,filesystem:"read-only",sourceMutation:!1}},{role:"Worker",tasks:[{name:"mechanical",description:"Deterministic bounded-edit specialist.",instruction:"Apply the exact already-decided transformation within the assigned files and verify it.",permissions:{network:!0,filesystem:"workspace-write",sourceMutation:!0}},{name:"implementation",description:"Bounded behavior implementation specialist.",instruction:"Design and implement the assigned behavior within its bounded seam, then verify the changed behavior.",permissions:{network:!0,filesystem:"workspace-write",sourceMutation:!0}},{name:"visual",description:"Rendered visual implementation and interaction specialist.",instruction:`Produce mergeable visual implementation within the Assignment, including frontend, 3D, browser-driven UI, and interactive visualization. Inspect the actual rendered and interacted-with result against acceptance criteria and references; iterate on material discrepancies in visual quality, UI, UX, accessibility, responsiveness, interaction, task adherence, and reference adherence. Use the projected skills appropriate to this visual work. Return changed paths and observable rendered/interaction evidence for independent Reviewer.visual review. ${oh}`,permissions:{network:!0,filesystem:"workspace-write",sourceMutation:!0}},{name:"integration",description:"Decided seam integration specialist.",instruction:"Connect already-decided component seams, resolve interface mismatches within the assigned boundary, and verify their combined behavior.",permissions:{network:!0,filesystem:"workspace-write",sourceMutation:!0}},{name:"operations",description:"Exact-ref or SHA terminal operations observer.",instruction:`Use babysit-ci to observe the assigned CI or release gate for the Root-supplied exact ref or SHA until terminal; report the matching result and failure evidence. ${zo}`,permissions:{network:!0,filesystem:"read-only",sourceMutation:!1}},{name:"validation",description:"Independent local behavioral validation specialist.",instruction:`Independently exercise the assigned local behavior with the smallest relevant checks, classify failures, and report reproducible evidence; generated proof state is allowed, but do not repair the implementation or substitute for code review. ${zo}`,permissions:{network:!0,filesystem:"workspace-write",sourceMutation:!1}},{name:"debugging",description:"Reproducible bounded defect-repair specialist.",instruction:"Use the debugging skill to repair the assigned defect within its bounded seam.",permissions:{network:!0,filesystem:"workspace-write",sourceMutation:!0}}],capability:"task-scoped-assignment",authority:"Concrete task permissions govern observation, proof writes, or source repair within the delegated Assignment; no role-level source-mutation authority is granted. Intent lifecycle, Git/VCS writes, and material choices remain Root-only.",evidence:"Return changed files, verification results, and remaining risk.",completion:"Finish the delegated Assignment with proportional proof or an exact blocker and return a compact structured outcome.",permissions:{network:!0,filesystem:"read-only",sourceMutation:!1}},{role:"Reviewer",tasks:[{name:"code",description:"Adversarial implemented-code review specialist.",instruction:"Review and repair the implemented code to a fixed point. Batch relevant evidence, then follow up on concrete uncertainty. Check correctness, safety, compatibility, test quality, generated-artifact hygiene, and the canonical patch-quality rule.",permissions:{network:!0,filesystem:"workspace-write",sourceMutation:!0}},{name:"visual",description:"Independent rendered visual, UI, UX, and interaction review specialist.",instruction:`Independently inspect the implementation and actual rendered/interacted-with result against acceptance criteria and references. Review visual quality, UI, UX, accessibility, responsiveness, interactions, task adherence, and reference adherence. Do not implement repairs. Return concrete reproducible discrepancies or sufficient acceptance evidence to Root for its final independent visual pass. ${oh} ${zo}`,permissions:{network:!0,filesystem:"workspace-write",sourceMutation:!1}},{name:"artifact",description:"Adversarial produced-artifact review specialist.",instruction:"Inspect the assigned produced artifact against its requested content, usability, and delivery constraints; repair concrete defects within the artifact boundary and repeat inspection until no actionable findings remain.",permissions:{network:!0,filesystem:"workspace-write",sourceMutation:!0}}],capability:"task-scoped-review",authority:"Concrete task permissions govern observational review or bounded repair within the delegated Assignment; no role-level source-mutation authority is granted. Intent lifecycle, Git/VCS writes, and material choices remain Root-only.",evidence:"Return findings, repaired paths, verification, and residual risk.",completion:"Reach a fixed point or report each reproducible blocker as a compact structured outcome.",permissions:{network:!0,filesystem:"read-only",sourceMutation:!1}}];jr(Jo);Ju=new Map(Jo.map((e)=>[e.role,e])),lB=new Set(Jo.map((e)=>e.role)),Aw=Jo.flatMap((e)=>e.tasks.map((t)=>`${e.role}:${t.name}`)),uB=new Set(Aw),HN=Aw.map((e)=>e.replace(":",".")),Pw=new Set(HN);Mw=ee(BN),pB=ee((e)=>ch("Explorer",e)),fB=ee((e)=>ch("Librarian",e)),mB=ee((e)=>ch("Worker",e)),hB=ee((e)=>ch("Reviewer",e)),Gu=ee(dB),Yu=Object.freeze(Aw.filter((e)=>VN(e))),WN=ee(VN),Go=Object.freeze(HN.filter((e)=>Pw.has(e))),gB=ee((e)=>typeof e==="string"&&Pw.has(e)),lh=Object.freeze(["worker","explorer","reviewer","librarian"]);KN=T({profile:ro,service_tier:R(Ko)}),ih=Object.freeze(["user_interaction","intent","material_decisions","orchestration_lifecycle","integration_acceptance","completion","git_vcs","external_effects","visual_judgment","dev_server"]),yB=E(...ih),xB=E("delegated","root_direct","unavailable"),SB=E(...ih),qw=E("used","no_coverage","unavailable","auth_or_quota_failure","source_conflict"),Zu=Object.freeze({rule:"Prove success with the smallest meaningful validation proportionate to changed behavior, scope, risk, uncertainty, and acceptance criteria; preserve required repository gates. Reuse already-conclusive evidence. Do not manufacture proof work, add redundant tests, or test unrelated surfaces merely to increase confidence. Broaden or repeat validation only after relevant changes, failures, elevated risk, or unresolved material concerns. Avoid tests that mirror implementation for reversible low-impact changes.",avoidImplementationMirrorTestsForLowImpactReversibleChanges:!0,broadenOrRepeatOnlyAfter:Object.freeze(["source_change","proof_failure","unresolved_material_concern","change_breadth_or_risk"]),mandatoryRepositoryGatesRemainRequired:!0,reviewerCodeRemainsRequired:!0}),bB=Object.freeze({requiredFor:Object.freeze(["library","framework","sdk","api","cli","cloud_service"]),resolveIdentityBeforeQuery:!0,queryNarrowly:!0,evidenceStates:Object.freeze(["used","no_coverage","unavailable","auth_or_quota_failure","source_conflict"]),webFallbackEvidenceStates:Object.freeze(["no_coverage","unavailable","auth_or_quota_failure"]),missingRequiredVersionAllowsFallback:!0,successfulEvidenceAloneAllowsFallback:!1,checkFirstPartyDocsBeforeFallbackForConflict:!0,unresolvedConflictAfterFirstPartyAllowsFallback:!0,materialDecisionsRemainRootOwned:!0}),Fn=Object.freeze({repositoryAndUserRequirementsPrecedePluginDefaults:!0,specialistsOwnImplementationAndInteractionProof:!0,specialistVisualImplementationInstruction:"Assign material rendered implementation to Worker.visual, independent rendered review to Reviewer.visual, then perform Root's independent visual pass. Root remains final visual authority and actively looks for issues both specialists missed. Dispatch only bounded repairs for material discrepancies, repeat only affected review and judgment, and reuse unaffected evidence.",rootOwnsVisualJudgment:!0,designJudgment:oh,rootOwnsSharedDevServer:!0,rootAcceptsTerminalVisualEvidence:!0,sourceChangesInvalidateRenderEvidence:!0,specialistReportsIncludeObservableRenderedEvidence:!0,logicOnlyChangesRequireVisualAcceptance:!1,fixedPoint:Object.freeze(["worker_visual_implements_and_inspects","reviewer_visual_independently_reviews","root_independently_judges","root_assigns_bounded_visual_repair","repeat_affected_review_and_judgment"])}),wB=Object.freeze({interactiveCapabilitiesRemainSpecialistOwned:!0,rootMayInspectForVisualJudgment:!0,credentialEntryAndSubmissionRemainUserOwned:!0,specialistsMustNeverHandleCredentials:!0,missingAuthorizedPathIsCapabilityBlocker:!0}),_B=Object.freeze({threatModelForMaterialTrustBoundaryChanges:!0,securityDiffScanRequiredForSecuritySensitiveDiffs:!0,fullScanOnlyForAuditNewExposedSurfaceOrSystemicConcern:!0,validateSupportedFindingsBeforeBlocking:!0,introducedOrWorsenedValidatedVulnerabilityBlocksVcs:!0,preExistingUnrelatedFindingsDoNotExpandScope:!0,securityEditsInvalidateCodeReview:!0,securitySensitiveCodeReviewEditsInvalidateSecurityReview:!0,materialDecisionsRemainRootOwned:!0}),W=Object.freeze({requiresDelegation:!0,explicitUserDirectExecutionOverridesDelegation:!0,assignmentStartAndDispatchPrecedeDelegableExecution:!0,trivialWorkRequiresDelegation:!0,preparatoryAndExploratoryWorkRequiresDelegation:!0,genericDirectWorkFallback:!1,concreteSpecialistDispatchRequired:!0,registeredSpecialistAgentTypes:Go,roleFamiliesAreLabelsOnly:!0,forbiddenGenericAgentTypes:lh,missingConcreteRouteIsBlocker:!0,delegableActions:Object.freeze(["repository_discovery","file_source_test_doc_inspection","fact_finding","research","implementation","debugging","testing","validation","frontend_work","security_work","browser_use","computer_use","review","ci_release_observation"]),directExecutionExceptions:ih,rootOwnedAuthority:ih,requestUserInputGates:Object.freeze(["missing_authorization_for_consequential_effect","ambiguity_or_missing_material_input"]),surgicalMutationRule:sh,phaseOrder:jN,phaseGates:Object.freeze({implementedScopeStableBeforeReview:!0,reviewerCodeAndWorkerValidationMayOverlapOnNonConflictingScopes:!0,currentValidationBeforeRootIntegration:!0,rootIntegrationBeforeVcs:!0}),initialDispatch:Object.freeze({independentAssignments:!0,substantiveIndependentConcurrency:!0,routinePostdispatchSteering:!1,collectiveWaits:!0,evidenceReusedAcrossPhases:!0}),atomicLifecycleTransitions:Object.freeze({relatedAssignmentAndIntentWrites:!0,oneLockOneCommit:!0,staleRevisionChecksRetained:!0,repositoryDriftChecksRetained:!0}),supersession:Object.freeze({explicitOnly:!0,unfinishedPredecessorOnly:!0,validatedRelatedReplacement:!0,reasonAndProvenanceRequired:!0,supersededExcludedFromCompletionBlockers:!0}),specialistTerminalResultPersistence:Object.freeze({ownActiveInvocationCapabilityRequired:!0,ownAssignmentOnly:!0,terminalOutcomeOnly:!0,rootOwnedIntentLifecycle:!0,rootOwnedAcceptanceReviewAndCiGates:!0,rootOwnedVcsAndExternalEffects:!0,sharedRuntimeCallerIdentityUnavailable:!0,legacyResultCompatibilityPreserved:!0}),normalSpawnForkTurns:"none",normalSpawnRequiresExplicitForkTurns:!0,normalSpawnUsesConcreteRegisteredAgentType:!0,semanticStateBoundary:"Use holycodex-agent semantic operations for Intent and Assignment state. Do not edit TOON state. Resume the current Intent or create one for new work; record verification, acceptance, and readiness, and complete only when holycodex-agent confirms every completion predicate. There is no HolyCodex planning workflow or automatic Plan approval gate; preserve existing Plan state when resuming work that uses it.",routeConfigurationBeforeDispatch:"Use the active profile's registered Role.task configuration, including model, effort, tier, permissions, shell, and capabilities. Verify the registration once per configuration generation; recheck after configuration changes or when resuming an unverified thread. Pass fields required by the dispatch tool; registered settings need not be copied into Assignment prose. Never inherit Root settings, substitute a generic route, or override the selected route. Report a missing or incompatible route before dispatch.",assignmentInvocationLifecycle:"Before each specialist spawn, persist the bounded Assignment and call holycodex-agent assignment start. Keep the returned active_invocation_id and capability in Root; give the specialist only the bounded Assignment, never the capability. After a terminal report, record the result with that invocation ID and capability. Recover an interrupted invocation only after confirming it stopped, using the matching Root-held capability; never share that capability.",assignmentContextIsTaskSpecificOnly:!0,configuredRouteModelAndEffortPreserved:!0,normalProgressMessages:!1,normalHeartbeatMessages:!1,normalIntermediateEvidence:!1,userUpdatesUsefulOrImportantOnly:!0,routinePerToolOrSubagentNarrationForbidden:!0,routineStatusOnlyChatterForbidden:!0,fixedCadenceUserUpdatesForbidden:!0,materialUserUpdateKinds:Object.freeze(["significant_findings_or_decisions","consequential_blockers_or_input_needs","release_milestones"]),outOfBoundaryRequiresNewAssignment:!0,routineWaitTool:"collaboration.wait_agent",routineWaitMaximumTimeoutMs:600000,routineWaitUsesMaximumRuntimeTimeout:!0,earlySpecialistCompletionWakesWait:!0,collectiveMailboxIncludesRelevantAgents:!0,idleTimeoutRepeatsMaximumWait:!0,shortRoutineWaitsForbidden:!0,longestPracticalEventWait:!0,busyPollingForbidden:!0,statusOnlyCoordinationLoopsForbidden:!0,batchIndependentLifecycleActions:!0,releaseLeavesAfterAcceptedOutcome:!0,specialistOutcomes:Object.freeze(["completed","blocked","needs_root_input","failed"]),evidenceFirstConciseStructuredReports:!0,specialistReportFields:Object.freeze(["changed paths","checks","observable evidence","blockers","Root decisions needed","remaining risk"]),rootLargeReadsOnlyFor:Object.freeze(["material decisions","conflicts","failures","findings"]),stableFactsReused:!0,duplicatePolicyForbidden:!0,stableBoundedComponentScopesAreCanonical:!0,lifecycleWorkerOwnsDeterministicApi:!0,materialDecisionsRemainRootOwned:!0,lifecycleRemainsRootOwned:!0,integrationAndCompletionRemainRootOwned:!0,routineSafeReversibleInScopeDecisionsProceedAutonomously:!0,userInstructionsOverrideSkillGuidelinesExceptHardInvariants:!0,authorizedWorkContinuesThroughRequestedTerminalState:!0,testingPolicy:Zu,codeReviewRequiredForImplementation:!0,codeReviewRequiredBeforeVcs:!0,externalVerificationMustBeTerminal:!0,postVcsFlow:"discover_topology_observe_repair_repeat"})});function tn(e,t){return new gt("invalid_canonical_value",`Cannot canonicalize ${e}: ${t}.`,{path:e,reason:t})}function Uw(e,t,n){if(e===null)return"null";switch(typeof e){case"string":{let r=JSON.stringify(e);if(r===void 0)throw tn(t,"invalid string");return r}case"boolean":return e?"true":"false";case"number":{if(!Number.isFinite(e))throw tn(t,"non-finite number");let r=JSON.stringify(e);if(r===void 0)throw tn(t,"invalid number");return r}case"undefined":throw tn(t,"undefined is not JSON");case"bigint":throw tn(t,"bigint is not JSON");case"function":throw tn(t,"function is not JSON");case"symbol":throw tn(t,"symbol is not JSON");case"object":break}if(n.has(e))throw tn(t,"cyclic value");n.add(e);try{if(Array.isArray(e)){for(let s of Object.getOwnPropertySymbols(e))throw tn(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 tn(`${t}[${s}]`,"sparse or accessor array item");a.push(Uw(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 tn(t,`non-index array property ${s}`);let l=Object.getOwnPropertyDescriptor(i,s);if(!l||!l.enumerable||!("value"in l))throw tn(`${t}[${c}]`,"non-enumerable or accessor array item")}return`[${a.join(",")}]`}let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)throw tn(t,"only plain objects are supported");for(let i of Object.getOwnPropertySymbols(e))throw tn(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 tn(`${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 tn(`${t}.${i}`,"accessor property");o.push(`${JSON.stringify(i)}:${Uw(a.value,`${t}.${i}`,n)}`)}return`{${o.join(",")}}`}finally{n.delete(e)}}function Ln(e){return Uw(e,"$",new Set)}function Dn(e){return new TextEncoder().encode(Ln(e))}function JN(e,t){if(e.length===0||e.includes("\x00"))throw new gt("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 gt("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 RB(e){let t="";for(let n of e)t+=n.toString(16).padStart(2,"0");return t}async function qn(e,t){let n=globalThis.crypto?.subtle;if(!n)throw new gt("crypto_unavailable","The standards-based crypto API is unavailable.");let r=await n.digest("SHA-256",TB(JN(e,t)));return RB(new Uint8Array(r))}function TB(e){let t=new Uint8Array(e.byteLength);return t.set(e),t}var $w=w(()=>{ks();rh()});function ZN(e){try{return Ln(e)!==void 0}catch{return!1}}function dh(e){let t=Xn(o0,e);if(qe(t))return fa(ul("CLI envelope",t.left));return Os(t.right)}var GN,YN,XN,CB,OB,jw="holycodex-specialist-outcome-2",zt,Pc,Qu,kB,EB,IB,AB,PB,MB,uh,NB,FB,LB,DB,qB,QN,e0,t0,UB,n0,r0,o0;var Hw=w(()=>{hn();Dt();$w();kw();ks();rh();Xu();Cc();GN=E("blocked","completed","failed","partial"),YN=Se(E("high","max","xhigh"),At);XN=ee((e)=>ZN(e)),CB=ee((e)=>Ig(e)&&!Array.isArray(e)&&ZN(e)),OB=T({blocked:V,changed_files:K(q),confidence:wn,context_owner:Se(q,At),material_findings:K(q),needs_more_context:V,needs_root_decision:V,needs_verification:V,relevant_files:K(q),remaining_risk:K(q),reuse_recommended:V,status:GN,suggested_followup:Se(q,At),suggested_luna_effort:YN,suggested_specialist:Se(Mw,At),verification:K(q),verification_passed:V}),zt=q.pipe(Tc(1)),Pc=T({state:qw,evidence:K(zt).pipe(to(1)),library:R(zt),version:R(zt)}),Qu={protocol_version:E(jw),route:Gu,evidence:K(zt),context7:R(Pc)},kB=T(Qu),EB=T({...Qu,status:E("completed"),summary:zt}),IB=T({...Qu,status:E("blocked"),reason:zt,needs_root_decision:V}),AB=T({...Qu,status:E("partial"),summary:zt,completed:K(zt),remaining:K(zt),needs_root_decision:V}),PB=T({...Qu,status:E("failed"),error:zt}),MB=Se(EB,IB,AB,PB),uh={protocol_version:E(jw),capability:Ku,route:Se(Gu,At),evidence:K(zt),context7:R(Pc),data:XN},NB=T({...uh,status:E("completed"),summary:zt}),FB=T({...uh,status:E("blocked"),reason:zt,needs_root_decision:V}),LB=T({...uh,status:E("partial"),summary:zt,completed:K(zt),remaining:K(zt),needs_root_decision:V}),DB=T({...uh,status:E("failed"),error:zt}),qB=Se(NB,FB,LB,DB),QN=K(q),e0=q.pipe(we(/^[a-z][a-z0-9-]*(?: [a-z][a-z0-9-]*)*$/u)),t0=E(So),UB=T({code:Or,message:q,details:CB}),n0=T({schema_version:t0,ok:E(!0),command:e0,data:XN,warnings:QN}),r0=T({schema_version:t0,ok:E(!1),command:e0,error:UB,warnings:QN}),o0=Se(n0,r0)});function $B(e,t,n){return{key:`${e}:${t}`,role:e,task:t,model:ed,effort:n}}function BB(e){let t=HB.get(e);if(t===void 0)throw new gt("catalog_invalid","A profile has no route effort policy.",{profile:e});return Jo.flatMap((n)=>n.tasks.map((r)=>{let o=`${n.role}:${r.name}`,i=t.efforts[o];if(i===void 0)throw new gt("catalog_invalid","A route effort policy is incomplete.",{profile:e,route:o});return $B(n.role,r.name,i)}))}function Bw(e){return{name:e.name,root:{model:e.rootModel,effort:e.rootEffort},specialistModel:ed,defaultServiceTier:"standard",routes:BB(e.name)}}function VB(e){let t=["low","default","high"];if(e.length!==t.length)throw new gt("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 gt("catalog_invalid","The profile catalog order is invalid.",{index:n});let i=ph,a=o==="low"?"low":"medium";if(r.root.model!==i||r.root.effort!==a||r.specialistModel!==ed)throw new gt("catalog_invalid","A profile has an invalid model route.",{profile:r.name});if(r.routes.length!==Yu.length)throw new gt("catalog_invalid","A profile is incomplete.",{profile:r.name});let s=new Set;for(let c of r.routes){if(s.has(c.key)||!jB.has(c.key)||c.model!==ed||`${c.role}:${c.task}`!==c.key)throw new gt("catalog_invalid","A profile contains an invalid route.",{profile:r.name});s.add(c.key)}if(s.size!==Yu.length)throw new gt("catalog_invalid","A profile is missing a specialist route.",{profile:r.name})}}function oo(e){let t=Xn(ro,e);if(qe(t))return fa(new gt("invalid_profile","Unknown profile selection.",{field:"profile"},{cause:t.left}));let n=a0.get(t.right);if(!n)return fa(new gt("invalid_profile","Unknown profile selection.",{profile:t.right}));return Os(n)}var ph="gpt-6.1-sol",ed="gpt-6-luna",jB,Vw,HB,Ww,i0,a0,WB;var s0=w(()=>{hn();ks();Xu();Cc();jB=new Set(Yu),Vw=[{profile:"low",rationale:"Cheapest practical configuration without dropping Luna below its useful agentic threshold.",efforts:{"Explorer:map":"medium","Explorer:lookup":"medium","Explorer:trace":"high","Librarian:lookup":"medium","Librarian:research":"high","Worker:mechanical":"medium","Worker:implementation":"high","Worker:integration":"high","Worker:operations":"medium","Worker:validation":"medium","Worker:debugging":"high","Worker:visual":"high","Reviewer:code":"high","Reviewer:artifact":"high","Reviewer:visual":"high"}},{profile:"default",rationale:"Best general whole-task cost/performance: Sol medium orchestration and Luna medium/high execution.",efforts:{"Explorer:map":"medium","Explorer:lookup":"medium","Explorer:trace":"high","Librarian:lookup":"medium","Librarian:research":"high","Worker:mechanical":"medium","Worker:implementation":"high","Worker:integration":"high","Worker:operations":"medium","Worker:validation":"high","Worker:debugging":"high","Worker:visual":"high","Reviewer:code":"high","Reviewer:artifact":"high","Reviewer:visual":"high"}},{profile:"high",rationale:"Highest practical reliability without indiscriminate reasoning waste; reserve Luna max for difficult long-horizon work.",efforts:{"Explorer:map":"high","Explorer:lookup":"medium","Explorer:trace":"high","Librarian:lookup":"high","Librarian:research":"max","Worker:mechanical":"high","Worker:implementation":"max","Worker:integration":"max","Worker:operations":"high","Worker:validation":"high","Worker:debugging":"max","Worker:visual":"max","Reviewer:code":"high","Reviewer:artifact":"max","Reviewer:visual":"high"}}];jr(Vw);HB=new Map(Vw.map((e)=>[e.profile,e]));Ww=[Bw({name:"low",rootModel:ph,rootEffort:"low"}),Bw({name:"default",rootModel:ph,rootEffort:"medium"}),Bw({name:"high",rootModel:ph,rootEffort:"medium"})];VB(Ww);jr(Ww);i0=Ww,a0=new Map,WB=new Map;for(let e of i0){a0.set(e.name,e);let t=new Map;for(let n of e.routes)t.set(n.key,n);WB.set(e.name,t)}});import{execFile as KB}from"child_process";import{promisify as JB}from"util";var l0="holycodex-intent-1",u0="holycodex-plan-1",d0="holycodex-assignment-1",fh="toon-4",te,Er,mh,p0,Mc,er,mt,_X,zw,es,Kw,Jw,GB,c0,YB,ZB,Gw,f0,m0,Nc,Yw,XB,QB,vX,eV="holycodex-work-state-transaction-1",RX,TX,tV,nV,rV,oV,iV,aV,sV,cV,CX,lV,OX;var h0=w(()=>{Dt();Hw();Xu();Cc();te=q.pipe(Ze((e)=>e.trim().length>0)),Er=q.pipe(we(/^[a-z0-9][a-z0-9-]{0,95}$/u)),mh=q.pipe(we(/^[a-f0-9]{64}$/u)),p0=q.pipe(we(/^[a-f0-9]{40}$/u)),Mc=Qm.pipe(wN(1)),er=q.pipe(Ze((e)=>!Number.isNaN(Date.parse(e)))),mt=K(te),_X=T({pid:Qm.pipe(xw(0)),token:te}),zw=T({role:E("Explorer","Librarian","Worker","Reviewer"),task:te}).pipe(Ze((e)=>Jo.some((t)=>t.role===e.role&&t.tasks.some((n)=>n.name===e.task)))),es=T({kind:E("changed_path","check","repository_fact","ci","behavior","uncertainty"),value:te,result:R(E("passed","failed","observed","unknown"))}),Kw=T({root:te,git_common_dir:te,initial_head:te,expected_head:te,expected_changes:mt,expected_status_digest:mh,integrated_commit:R(p0),updated_at:er}),Jw=E("scoping","ready","executing","verifying","reviewing","blocked","needs_root_input","complete","abandoned"),GB=E("scoping","ready","executing","verifying","reviewing"),c0=T({required:V,status:E("not_required","missing","passed","failed","accepted","rejected"),evidence:K(es)}),YB=T({schema_version:E(l0),toon_compatibility:E(fh),id:Er,slug:Er,title:te,goal:te,acceptance_criteria:mt,state:Jw,revision:Mc,plan_required:V,active_plan_revision:R(Mc),active_plan_digest:R(mh),blockers:mt,resume_state:R(GB),verification:c0,review:c0,acceptance_met:V,root_readiness:V,evidence:K(es),baseline:Kw,created_at:er,updated_at:er}),ZB=T({schema_version:E(u0),toon_compatibility:E(fh),intent_id:Er,revision:Mc,predecessor_digest:R(mh),approach:te,scope:mt,exclusions:mt,assignments:mt,dependencies:mt,architecture:mt,risks:mt,assumptions:mt,open_questions:mt,verification:mt,recovery:mt,updated_at:er}),Gw=E("completed","blocked","needs_root_input","failed"),f0=E("pending","executing","completed","blocked","needs_root_input","failed","superseded"),m0=T({id:Er,outcome:Gw,started_at:er,finished_at:er,summary:te,evidence:K(es),context7:R(Pc),blocker:R(te),remaining_risk:mt}),Nc=mh,Yw={schema_version:E(d0),toon_compatibility:E(fh),intent_id:Er,id:Er,objective:te,owner:Se(zw,T({role:E("Reviewer"),task:E("plan")})),scope:mt,constraints:mt,exclusions:mt,dependencies:mt,acceptance_criteria:mt,status:f0,revision:Mc,invocations:K(m0),active_invocation_id:R(te),active_started_at:R(er),supersedes:R(Er),superseded_by:R(Er),supersession_reason:R(te),supersession_provenance:R(te),evidence:K(es),blocker:R(te),remaining_risk:mt,created_at:er,updated_at:er},XB=T(Yw),QB=T({...Yw,capability:Nc}),vX=T({...Yw,active_invocation_capability_verifier:R(Nc),active_invocation_capability:R(Nc)}),RX=T({schema_version:E(eV),state:E("prepared","committed"),files:K(T({path:te,previous:q,next:q})).pipe(to(1))}),TX=T({schema_version:E("holycodex-intent-0"),id:Er,slug:Er,title:te,goal:te,acceptance_criteria:mt,state:Jw,revision:Mc,baseline:Kw,created_at:er,updated_at:er}),tV=T({title:te,goal:te,acceptanceCriteria:K(te).pipe(to(1)),planRequired:R(V),verificationRequired:R(V),reviewRequired:R(V)}),nV=T({approach:te,scope:R(K(te)),exclusions:R(K(te)),assignments:R(K(te)),dependencies:R(K(te)),architecture:R(K(te)),risks:R(K(te)),assumptions:R(K(te)),openQuestions:R(K(te)),verification:R(K(te)),recovery:R(K(te))}),rV=T({id:R(te),objective:te,owner:zw,scope:K(te).pipe(to(1)),constraints:R(K(te)),exclusions:R(K(te)),dependencies:R(K(te)),acceptanceCriteria:K(te).pipe(to(1))}),oV=T({scope:K(te).pipe(to(1))}),iV=T({scope:R(K(te).pipe(to(1)))}),aV=T({replacementId:Er,replacementRevision:R(Mc),reason:te,provenance:te}),sV=T({commit:p0}),cV=T({invocationId:R(te),capability:R(Nc),outcome:Gw,startedAt:R(te),summary:te,scope:R(K(te).pipe(to(1))),evidence:R(K(es)),context7:R(Pc),blocker:R(te),remainingRisk:R(K(te))}),CX=T({invocationId:te,startedAt:er,capability:Nc,interruptionReason:te}),lV=T({evidence:R(K(es)),verification:R(E("passed","failed")),review:R(E("accepted","rejected")),acceptanceMet:R(V),rootReadiness:R(V),clearBlockers:R(V)}),OX=JB(KB)});var ht=w(()=>{jR();ks();Cc();EN();kw();UN();rh();Xu();Hw();s0();$w();h0()});function de(e){if(typeof e!=="object"||e===null||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function Xe(e){try{return Ln(e),!0}catch{return!1}}function pV(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 y0(e){return{ok:!1,error:e}}function x0(e){return{ok:!0,value:e}}function Un(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 ts(e,t=0){if(t>3)return"[truncated]";if(e===null||typeof e==="boolean")return e;if(typeof e==="string")return Un(e,256);if(typeof e==="number")return Number.isFinite(e)?e:null;if(Array.isArray(e))return e.slice(0,32).map((n)=>ts(n,t+1));if(de(e)){let n={};for(let[r,o]of Object.entries(e).slice(0,32)){let i=Un(r,96);if(i.length>0)n[i]=ts(o,t+1)}return n}return"[redacted]"}function S0(e){let t=ts(e);return de(t)?t:{value:t}}function Qe(e,t,n){return new ie("invalid_external_data",`Invalid ${e}.`,{field:e,received:ts(t)},n===void 0?void 0:{cause:n})}function Ve(e,t,n){let r=Xn(e,t);if(qe(r))throw Qe(n,t,String(r.left));return r.right}function b0(e,t){try{return Ve(e,t,"value"),!0}catch{return!1}}var Zw,td=1048576,Xw=65536,$n,Vi,SQ,Yo,dV,ie;var io=w(()=>{ht();hn();Dt();Zw=So;$n=ee((e)=>Xe(e)),Vi=ee((e)=>de(e)&&Xe(e)),SQ=q.pipe(we(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u)),Yo=q.pipe(Ze((e)=>e.length>0&&e.length<=4096)),dV=wn.pipe(Ze((e)=>Number.isFinite(e)&&e>=0));ie=class ie 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=pV(e),this.details=n,this.retryable=r?.retryable??!1,Object.freeze(this.details),Object.freeze(this)}}});var Qw,nd,rd,e_,t_,n_,r_="turn/completed";var hh=w(()=>{Qw=["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"],nd=["item/commandExecution/requestApproval","item/fileChange/requestApproval","applyPatchApproval","execCommandApproval"],rd=["item/permissions/requestApproval"],e_=["mcpServer/elicitation/request"],t_=["item/tool/call"],n_={method:"initialized"}});class yh{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??td,this.requestTimeoutMs=t.requestTimeoutMs,this.signal=t.signal,!Number.isSafeInteger(this.maxLineBytes)||this.maxLineBytes<1)throw new ie("invalid_external_data","The maximum line size is invalid.");if(this.requestTimeoutMs!==void 0&&(!Number.isSafeInteger(this.requestTimeoutMs)||this.requestTimeoutMs<1))throw new ie("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=fV){if(this.initializePromise)return this.initializePromise;if(this.initializeAttempted)throw new ie("invalid_external_data","The App Server initialize handshake was already attempted.");this.ensureOpen();let t=Ve(gh,e,"initialize parameters");return this.initializeAttempted=!0,this.initializePromise=this.performInitialize(t),this.initializePromise}async startThread(e={}){return this.action("thread/start",m_,e,ad)}async resumeThread(e){let t=typeof e==="string"?{threadId:e}:e;return this.action("thread/resume",h_,t,c_)}async readThread(e){let t=typeof e==="string"?{threadId:e}:e;return this.action("thread/read",g_,t,p_)}async listThreads(e={}){return this.action("thread/list",x_,e,f_)}async forkThread(e){let t=typeof e==="string"?{threadId:e}:e;return this.action("thread/fork",y_,t,l_)}async unsubscribeThread(e){let t=typeof e==="string"?{threadId:e}:e;return this.action("thread/unsubscribe",u_,t,d_)}async startTurn(e){return this.action("turn/start",S_,e,w_)}async steerTurn(e){return this.action("turn/steer",b_,e,__)}async interruptTurn(e,t){let n=typeof e==="string"?{threadId:e,turnId:t??""}:e;return this.action("turn/interrupt",v_,n,R_)}async listModels(e={}){return this.action("model/list",C_,e,O_)}async readModelProviderCapabilities(e={}){return this.action("modelProvider/capabilities/read",k_,e,E_)}async readConfig(e={}){return this.action("config/read",I_,e,A_)}async listPermissionProfiles(e={}){return this.action("permissionProfile/list",P_,e,M_)}async call(e,t={}){if(e==="initialize"){let r=await this.initialize(Ve(gh,t,"initialize parameters"));return Ve($n,r,"initialize result")}let n=Ve(id,{id:1,method:e,params:t},"App Server method");if(!mV.has(n.method))throw new ie("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 ie("closed","The App Server client is closed."))}async performInitialize(e){try{let t=await this.request("initialize",Ve($n,e,"initialize parameters")),n=Ve(a_,t,"initialize result"),r=Ve(s_,n_,"initialized notification");return await this.transport.writeLine(JSON.stringify(r)),this.initialized=!0,n}catch(t){let n=t instanceof ie?t:new ie("transport_failure","The initialize handshake failed.",{},{cause:t});throw await this.closeWithError(n),n}}async action(e,t,n,r){let o=Ve(t,n,`${e} parameters`),i=Ve($n,o,`${e} parameters`),a=await this.request(e,i);return Ve(r,a,`${e} result`)}async request(e,t){if(this.ensureOpen(),e!=="initialize"&&!this.initialized)throw new ie("invalid_external_data",`The ${e} action requires an initialized App Server client.`);this.startReader();let n=this.nextRequestId;this.nextRequestId+=1;let r=Ve(id,{id:n,method:e,params:t},`${e} request`);return new Promise((o,i)=>{let a=!1,s,c,l=(d)=>{if(a)return;if(a=!0,this.pending.delete(n),s!==void 0)clearTimeout(s);c?.(),i(d)};if(this.requestTimeoutMs!==void 0)s=setTimeout(()=>l(new ie("timeout",`The ${e} request timed out.`,{method:e})),this.requestTimeoutMs);if(this.signal){let d=()=>l(new ie("cancellation",`The ${e} request was cancelled.`,{method:e}));this.signal.addEventListener("abort",d,{once:!0}),c=()=>this.signal?.removeEventListener("abort",d)}let u={method:e,resolve:(d)=>{if(a)return;if(a=!0,s!==void 0)clearTimeout(s);c?.(),o(d)},reject:l,...s===void 0?{}:{timer:s},...c===void 0?{}:{removeAbortListener:c}};this.pending.set(n,u),this.transport.writeLine(JSON.stringify(r)).catch((d)=>{l(d instanceof ie?d:new ie("transport_failure","The App Server request could not be written.",{},{cause:d}))})})}startReader(){if(!this.readerPromise)this.readerPromise=this.readLoop().catch((e)=>this.handleReaderFailure(e)).catch(()=>{return})}async readLoop(){while(!this.closed){let e=await this.transport.readLine();if(e===null){if(!this.closed)throw new ie("transport_closed","The App Server transport closed.");return}if(new TextEncoder().encode(e).byteLength>this.maxLineBytes)throw new ie("invalid_transport_line","An App Server line exceeded the limit.");this.handleLine(e)}}async handleReaderFailure(e){let t=e instanceof ie?e:new ie("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 ie("invalid_transport_line","The App Server emitted invalid JSON.",{},{cause:i})}let n=this.tryDecode(od,t);if(n!==void 0){this.handleResponse(n);return}let r=this.tryDecode(id,t);if(r!==void 0){this.handleServerRequest(r);return}let o=this.tryDecode(i_,t);if(o!==void 0){this.handleNotification(o);return}throw Qe("JSON-RPC message",t)}tryDecode(e,t){try{return Ve(e,t,"JSON-RPC message")}catch{return}}handleResponse(e){let t=this.pending.get(e.id);if(!t)throw new ie("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=gV(t.method);t.reject(new ie(r,`The App Server rejected ${t.method}: ${Un(e.error.message)}.`,{method:t.method,serverCode:e.error.code,retryable:n,...e.error.data===void 0?{}:{data:ts(e.error.data)}},{retryable:n}));return}t.resolve(e.result)}handleServerRequest(e){let t=e.params??{},n=Ve(N_,{...e,params:t,category:w0(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,Un(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,Un(String(s))))));return}this.completeServerRequest(i,()=>this.writeValidatedServerResult(e.id,a))}writeValidatedServerResult(e,t){try{let n=Ve(F_,t,"server response");return this.writeServerResult(e,n)}catch(n){return this.writeServerError(e,-32000,Un(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=Ve(od,{id:e,result:t},"server response");await this.transport.writeLine(JSON.stringify(n))}async writeServerError(e,t,n){let r=Ve(od,{id:e,error:{code:t,message:hV(n)}},"server error response");await this.transport.writeLine(JSON.stringify(r))}handleNotification(e){let t=e.params;if(e.method===r_){let n=Ve(T_,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:S0({params:ts(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 ie("closed","The App Server client is closed.")}}function hV(e){let t=Un(e);return t.length>0?t:"server request failed"}function gV(e){if(rd.some((t)=>t===e))return"permission_denied";if(nd.some((t)=>t===e))return"approval_required";if(e==="turn/interrupt")return"cancellation";if(e.startsWith("turn/"))return"turn_failed";return"server_error"}var fV,mV;var o_=w(()=>{io();hh();L_();fV={clientInfo:{name:"holycodex",title:null,version:Zw},capabilities:null},mV=new Set(Qw)});import{isAbsolute as yV}from"path";function Wi(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 D_(e=process.env){return Object.freeze(Wi(e))}async function xh(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 ie("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 Sh(e,t){try{return new TextDecoder("utf-8",{fatal:!0}).decode(e)}catch(n){throw new ie("invalid_transport_line",`Invalid UTF-8 in ${t}.`,{},{cause:n})}}function zi(e){return Un(e.replace(/Bearer\s+[^\s]+/giu,"Bearer [redacted]").replace(/((?:api[_-]?key|authorization|cookie|password|secret|token)\s*[:=]\s*)[^\s,;]+/giu,"$1[redacted]"),512)}function sd(e){return e.split(/\r?\n/u).map((t)=>zi(t)).filter((t)=>t.length>0).slice(0,128)}class bh{process;stdin;stdoutReader;stderrStream;maxLineBytes;maxDiagnosticBytes;lineDecoder=new TextDecoder("utf-8",{fatal:!0});stderrDiagnostics=[];stdoutBuffer=new Uint8Array(0);stderrPromise;closed=!1;constructor(e){if(!yV(e.executablePath))throw new ie("discovery_failed","The Codex executable path must be absolute.");if(this.maxLineBytes=e.maxLineBytes??td,this.maxDiagnosticBytes=e.maxDiagnosticBytes??Xw,this.maxLineBytes<1||this.maxDiagnosticBytes<1)throw new ie("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:Wi(e.environment),stdin:"pipe",stdout:"pipe",stderr:"pipe"}),!(this.process.stdout instanceof ReadableStream)||!(this.process.stderr instanceof ReadableStream))throw new ie("transport_failure","The Codex App Server did not expose stdio pipes.");if(typeof this.process.stdin==="number"||this.process.stdin===void 0)throw new ie("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 ie("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 ie("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 ie("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 ie)throw t;throw new ie("transport_failure","The App Server stdout could not be read.",{},{cause:t})}finally{e.releaseLock()}}async writeLine(e){if(this.closed)throw new ie("closed","The App Server transport is closed.");if(new TextEncoder().encode(e).byteLength>this.maxLineBytes)throw new ie("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 ie("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 xh(this.stderrStream,this.maxDiagnosticBytes),t=Sh(e,"Codex stderr");for(let n of t.split(/\r?\n/u).slice(0,128)){let r=zi(n);if(r.length>0)this.stderrDiagnostics.push(r)}}catch{this.stderrDiagnostics.push("[stderr unavailable]")}}}var wh=w(()=>{io()});import{spawn as xV}from"child_process";import{lstat as Xo,mkdir as SV,mkdtemp as bV,readFile as wV,readdir as _V,realpath as U_,rename as vV,rm as RV,stat as AQ}from"fs/promises";import{dirname as v0,isAbsolute as V_,join as Ji,relative as R0,resolve as _h,sep as T0}from"path";async function O0(e){let t=G_(e.selectedPluginIds);if(t.length===0)return;if(A0(e.timeoutMs,e.pollIntervalMs),e.signal?.aborted)throw new he("cancelled","Official Codex marketplace bootstrap was cancelled.");let n=e.readSnapshot??((s)=>J_(s,e.selectedPluginIds)),r=await n(e.codexHome);if(r!==void 0&&Rh(r,t))return r;let o=e.initializeRuntime??(()=>UV(e)),i,a;try{i=await o()}catch(s){a=se("marketplace_unavailable","Codex runtime initialization could not start the official marketplace sync. Check that Codex is available and its network/policy settings permit the official marketplace.",s)}if(a===void 0)try{let s=e.timeoutMs??K_,c=e.pollIntervalMs??CV,l=Date.now();while(Date.now()-l<=s){if(e.signal?.aborted)throw new he("cancelled","Official Codex marketplace bootstrap was cancelled.");let u=await n(e.codexHome);if(u!==void 0&&Rh(u,t))return u;let d=s-(Date.now()-l);if(d<=0)break;await(e.sleep??P0)(Math.min(c,d))}a=se("marketplace_timeout","The official Codex marketplace did not become ready before the bounded wait expired. Check network access and Codex marketplace policy, then retry.")}catch(s){if(s instanceof he&&s.code==="cancelled")throw s;a=s instanceof he?s:se("marketplace_unavailable","The official Codex marketplace sync failed before its bounded wait completed.",s)}finally{await i?.()}if(e.gitFallback!==!1)try{return await k0({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 he)throw s;throw se("marketplace_unavailable",`The official marketplace could not be populated after runtime startup (${a?.code??"unavailable"}). Check network access and retry.`,s)}throw a??se("marketplace_timeout","The official Codex marketplace did not become ready before the bounded wait expired.")}async function k0(e){let t=G_(e.selectedPluginIds);if(t.length===0)throw se("marketplace_invalid","The official marketplace fallback requires at least one selected provider plugin.");if(A0(e.timeoutMs,void 0),!V_(e.codexHome))throw se("marketplace_invalid","The Codex home for official marketplace fallback must be absolute.");if(e.signal?.aborted)throw new he("cancelled","Official Codex marketplace fallback was cancelled.");let n=Wi(e.environment),r=e.gitRunner??F0("git",{environment:n,...e.timeoutMs===void 0?{}:{timeoutMs:e.timeoutMs}}),o=e.timeoutMs??K_,i;try{i=await PV(r,o,e.signal)}catch(u){if(u instanceof he)throw u;throw se("marketplace_unavailable","The official Codex marketplace remote HEAD could not be resolved. Check network access and retry.",u)}let a=Ji(e.codexHome,"plugins"),s=Ji(a,z_[1]);if(await NV(a,e.codexHome),await Xo(s).catch((u)=>{if(Fc(u))return;throw se("marketplace_invalid","The reserved official marketplace path could not be inspected safely.",u)})!==void 0)throw se("marketplace_invalid","The reserved official marketplace path appeared during bootstrap; refusing to overwrite it.");let l=await bV(Ji(a,".openai-plugins-stage-"));try{if(await j_(e.codexHome,l),e.cloneSnapshot!==void 0)try{await e.cloneSnapshot(rs,l)}catch(f){if($V(f))throw se("marketplace_invalid","The staged official marketplace could not be created as a safe file tree.",f);throw f}else{let f=await r.run(["-c","core.longpaths=true","clone","--depth=1","--no-tags",rs,l],{...e.signal===void 0?{}:{signal:e.signal},timeoutMs:o});if(f.exitCode!==0)throw se("marketplace_unavailable","The official Codex marketplace could not be downloaded. Check network access and retry.",f.stderr)}await vh(l);let u=await E0(l,e.codexHome,t);if(u===void 0||!Rh(u,t))throw se("marketplace_invalid","The downloaded official marketplace is missing the selected plugin entries or manifest.");if(await MV(r,l,o,e.signal)!==i)throw se("marketplace_invalid","The downloaded official marketplace did not match the verified remote HEAD.");if(await Xo(s).catch((f)=>{if(Fc(f))return;throw se("marketplace_invalid","The reserved official marketplace path could not be checked before publication.",f)})!==void 0)throw se("marketplace_invalid","The reserved official marketplace path appeared during staging; refusing to overwrite it.");await IV(l,s,e.renameSnapshot??vV);let m=await J_(e.codexHome,e.selectedPluginIds);if(m===void 0||!Rh(m,t))throw se("marketplace_invalid","The published official marketplace failed validation.");return m}catch(u){if(u instanceof he)throw u;throw se("marketplace_unavailable","The official Codex marketplace fallback failed safely. Check network access and retry.",u)}finally{await RV(l,{recursive:!0,force:!0}).catch(()=>{return})}}async function IV(e,t,n){for(let r=0;;r+=1)try{await n(e,t);return}catch(o){let i=OV[r];if(process.platform!=="win32"||i===void 0||!AV(o))throw o;if(await Xo(t).catch((s)=>{if(Fc(s))return;throw se("marketplace_invalid","The reserved official marketplace path could not be checked before retrying publication.",s)})!==void 0)throw se("marketplace_invalid","The reserved official marketplace path appeared during publication; refusing to overwrite it.");await P0(i)}}function AV(e){return e!==null&&typeof e==="object"&&"code"in e&&(e.code==="EPERM"||e.code==="EBUSY")}async function PV(e,t,n){let r=await e.run(["ls-remote",rs,"HEAD"],{...n===void 0?{}:{signal:n},timeoutMs:t});if(r.exitCode!==0)throw se("marketplace_unavailable","The official Codex marketplace remote HEAD could not be resolved. Check network access and retry.",r.stderr);let o=r.stdout.trim().split(/\r?\n/u).map((a)=>a.trim()).filter((a)=>a.length>0),i=o.length===1?/^([0-9a-f]{40}|[0-9a-f]{64})\s+HEAD$/iu.exec(o[0]??""):null;if(i?.[1]===void 0)throw se("marketplace_invalid","The official Codex marketplace remote HEAD response was malformed.");return i[1].toLowerCase()}async function MV(e,t,n,r){let o=await e.run(["rev-parse","HEAD"],{timeoutMs:n,cwd:t,...r===void 0?{}:{signal:r}}),i=o.stdout.trim().toLowerCase();if(o.exitCode!==0||!/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/u.test(i))throw se("marketplace_invalid","The downloaded official marketplace checkout did not expose a valid HEAD.",o.stderr);return i}async function NV(e,t){await $_(t,e),await SV(e,{recursive:!0}),await $_(t,e)}async function $_(e,t){let n=_h(e),r=_h(t);while(!0){if((await Xo(r).catch((a)=>{if(Fc(a))return;throw a}))?.isSymbolicLink())throw se("marketplace_invalid","The official marketplace path cannot contain symlinks.");if(r===n)return;let i=v0(r);if(i===r||i!==n&&!FV(n,i))throw se("marketplace_invalid","The official marketplace path escaped CODEX_HOME.");r=i}}function FV(e,t){let n=R0(e,t);return n.length>0&&n!==".."&&!n.startsWith(`..${T0}`)&&!V_(n)}async function vh(e){let t=await Xo(e);if(t.isSymbolicLink())throw se("marketplace_invalid","The official marketplace snapshot cannot contain symlinks.");if(!t.isDirectory())throw se("marketplace_invalid","The official marketplace snapshot is not a directory.");let n=await _V(e,{withFileTypes:!0});for(let r of n){let o=Ji(e,r.name),i=await Xo(o);if(i.isSymbolicLink())throw se("marketplace_invalid","The official marketplace snapshot cannot contain symlinks.");if(i.isDirectory())await vh(o)}}async function J_(e,t=[]){return await E0(Ji(e,...z_),e,G_(t))}async function E0(e,t,n=[]){if(t!==void 0)await $_(t,e);let r=await Xo(e).catch((l)=>{if(Fc(l))return;throw se("marketplace_invalid","The reserved openai-curated marketplace path could not be read safely.",l)});if(r===void 0)return;if(r.isSymbolicLink()||!r.isDirectory())throw se("marketplace_invalid","The reserved openai-curated marketplace path is not a real directory.");if(t!==void 0)await j_(t,e);else await vh(e);if(t!==void 0)await vh(e);let o=await U_(e),i=[Ji(o,".agents","plugins","marketplace.json"),Ji(o,".codex-plugin","marketplace.json"),Ji(o,"marketplace.json")],a,s;for(let l of i){let u=await Xo(l).catch((d)=>{if(Fc(d))return;throw se("marketplace_invalid","The official marketplace manifest could not be read safely.",d)});if(u===void 0)continue;if(u.isSymbolicLink()||!u.isFile())throw se("marketplace_invalid","The official marketplace manifest is not a regular file.");if(await j_(o,l),a!==void 0)throw se("marketplace_invalid","The reserved official marketplace contains more than one manifest.");a=l;try{s=new TextDecoder("utf-8",{fatal:!0}).decode(await wV(l))}catch(d){throw se("marketplace_invalid","The official marketplace manifest is not valid UTF-8.",d)}}if(a===void 0||s===void 0)return;let c;try{c=JSON.parse(s)}catch(l){throw se("marketplace_invalid","The official marketplace manifest is not valid JSON.",l)}return I0(c,o,a,n)}function I0(e,t=`${z_.join("/")}`,n=`${t}/marketplace.json`,r=[]){if(!de(e)||e.name!==ld)throw se("marketplace_invalid","The reserved official marketplace manifest has an unexpected name.");LV(e);let o=e.plugins;if(!Array.isArray(o)||o.length===0)throw se("marketplace_invalid","The official marketplace manifest has no plugin entries.");let i=[],a=new Set;for(let s of o){if(!de(s)||typeof s.name!=="string"){if(r.length>0)continue;throw se("marketplace_invalid","The official marketplace contains a malformed plugin entry.")}let c=s.name;if(!/^[a-z][a-z0-9._-]{1,63}$/u.test(c)){if(r.length>0)continue;throw se("marketplace_invalid","The official marketplace contains an invalid plugin name.")}if(a.has(c)){if(r.length>0&&!r.includes(c))continue;throw se("marketplace_invalid","The official marketplace contains a duplicate plugin name.")}if(a.add(c),r.length>0&&!r.includes(c))continue;let l=DV(s);if(!qV(l))throw se("marketplace_invalid",`The official marketplace source for ${c} is unsafe.`);i.push({name:c,source:l})}if(r.some((s)=>!i.some((c)=>c.name===s)))throw se("marketplace_invalid","The official marketplace is missing a selected plugin entry.");return{name:ld,source:rs,rootPath:t,manifestPath:n,plugins:i}}function LV(e){for(let t of["source","repository","repo","url"]){let n=e[t];if(n===void 0)continue;if((typeof n==="string"?n:de(n)&&typeof n.url==="string"?n.url:void 0)!==rs)throw se("marketplace_invalid","The reserved official marketplace source is not the approved OpenAI repository.")}}function DV(e){let t=e.source;if(typeof t==="string")return t;if(de(t)&&typeof t.path==="string")return t.path;if(typeof e.path==="string")return e.path;return}function qV(e){if(e===void 0||e.length===0||V_(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 G_(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!==ld&&i!=="openai-curated-remote")continue;let a=r.slice(0,o);if(!/^[a-z][a-z0-9._-]{1,63}$/u.test(a))throw se("marketplace_invalid","A selected official marketplace plugin id is invalid.");if(!M0(a))continue;if(!n.has(a))n.add(a),t.push(a)}return t}function Rh(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 UV(e){let t=Wi(e.environment),n;try{n=new bh({executablePath:e.executablePath,environment:t,...e.signal===void 0?{}:{signal:e.signal}});let r=new yh(n,{requestTimeoutMs:Math.min(e.timeoutMs??K_,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 A0(e,t){if(e!==void 0&&(!Number.isSafeInteger(e)||e<1||e>300000))throw se("marketplace_invalid","The official marketplace timeout is invalid.");if(t!==void 0&&(!Number.isSafeInteger(t)||t<0||t>60000))throw se("marketplace_invalid","The official marketplace poll interval is invalid.")}async function j_(e,t){let n=await U_(e),r=await U_(t),o=R0(n,r);if(o===""||o===".."||o.startsWith(`..${T0}`))throw se("marketplace_invalid","The reserved official marketplace is outside CODEX_HOME.");let i=_h(e),a=_h(t);while(!0){if((await Xo(a)).isSymbolicLink())throw se("marketplace_invalid","The reserved official marketplace path cannot contain symlinks.");if(a===i)break;let c=v0(a);if(c===a)throw se("marketplace_invalid","The reserved official marketplace path is outside CODEX_HOME.");a=c}}function Fc(e){return typeof e==="object"&&e!==null&&"code"in e&&e.code==="ENOENT"}function $V(e){return typeof e==="object"&&e!==null&&"code"in e&&(e.code==="EPERM"||e.code==="EACCES")}async function P0(e){await new Promise((t)=>setTimeout(t,e))}function se(e,t,n){return new he(e,t,n instanceof Error?{cause:zi(n.message)}:{})}function ao(e,t){let n=Qn(t);if(n===void 0||n!==t)return;let o=[...e.installed,...e.available].flatMap((i)=>{let a=Cw(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 M0(e){return th.includes(e)}function N0(e){if(!b0(B_,e))return y0(Qe("live official plugin list",e));return x0(Ve(B_,e,"live official plugin list"))}function Th(e){let t=e.runner??F0(e.executable,{environment:e.environment??Wi(),...e.timeoutMs===void 0?{}:{timeoutMs:e.timeoutMs},...e.stdoutLimit===void 0?{}:{stdoutLimit:e.stdoutLimit},...e.stderrLimit===void 0?{}:{stderrLimit:e.stderrLimit}}),n=async()=>{let o=await t.run(["plugin","list","--json"]);if(o.exitCode!==0)throw Ki("list",o);let i;try{i=JSON.parse(o.stdout)}catch{throw new he("command_failed","Codex returned invalid plugin data.")}let a=N0(i);if(!a.ok)throw new he("command_failed","Codex returned an invalid official plugin list.");return a.value},r=async()=>{let o=await t.run(["plugin","marketplace","list","--json"]);if(o.exitCode!==0)throw Ki("marketplace list",o);let i;try{i=JSON.parse(o.stdout)}catch{throw new he("command_failed","Codex returned invalid marketplace data.")}if(!de(i)||!Array.isArray(i.marketplaces))throw new he("command_failed","Codex returned an invalid marketplace list.");return i.marketplaces.map((a)=>{if(!de(a)||typeof a.name!=="string"||typeof a.root!=="string")throw new he("command_failed","Codex returned an invalid marketplace entry.");let s=a.marketplaceSource;if(s===void 0)return{name:a.name,root:a.root};if(!de(s)||typeof s.sourceType!=="string"||typeof s.source!=="string")throw new he("command_failed",`Codex returned an invalid source for marketplace ${a.name}.`);return{name:a.name,root:a.root,marketplaceSource:{sourceType:s.sourceType,source:s.source}}})};return{list:n,ensureOfficialMarketplace:async(o)=>{if(e.codexHome===void 0)throw new he("marketplace_unavailable","Codex home is unavailable; the official marketplace cannot be bootstrapped safely.");await O0({codexHome:e.codexHome,executablePath:e.executable,selectedPluginIds:o,...e.environment===void 0?{}:{environment:e.environment},...e.timeoutMs===void 0?{}:{timeoutMs:e.timeoutMs},...e.officialMarketplaceFallback===void 0?{}:{gitFallback:e.officialMarketplaceFallback}})},addMarketplace:async(o,i)=>{let a=Ve(ns,o,"plugin marketplace source");if(a===ld||a===rs)throw new he("marketplace_invalid","The reserved openai-curated marketplace must be populated by Codex runtime startup; it cannot be added manually.");if(a!==W_)throw new he("marketplace_invalid",`Unsupported managed marketplace source: ${a}.`);let s,c=!1;try{s=await r()}catch(x){if(!BV(x))throw x;e.onMarketplaceConflict?.("The registered HolyCodex marketplace cache is incomplete; Codex will rebuild it from the canonical source.");let v=await t.run(["plugin","marketplace","add",a],i===void 0?void 0:{signal:i});if(v.exitCode!==0)throw Ki("marketplace add",v,a);s=await r(),c=!0}let l=q_(s,Zo),u=VV(s,Zo);if(l!==void 0&&u.length>0){e.onMarketplaceConflict?.(`${l} HolyCodex will remove the conflicting registration and restore its required source.`);for(let x of u){let v=await t.run(["plugin","marketplace","remove",x],i===void 0?void 0:{signal:i});if(v.exitCode!==0)throw Ki("marketplace remove",v,x)}}let d=u.length===0?s:await r(),p=q_(d,Zo);if(p!==void 0)throw new he("marketplace_invalid",p);if(d.find((x)=>x.name===Zo)===void 0){let x=await t.run(["plugin","marketplace","add",a],i===void 0?void 0:{signal:i});if(x.exitCode!==0)throw Ki("marketplace add",x,a)}else if(!c){let x=await t.run(["plugin","marketplace","upgrade",Zo],i===void 0?void 0:{signal:i});if(x.exitCode!==0)throw Ki("marketplace upgrade",x,Zo)}let f=await r(),y=q_(f,Zo);if(y!==void 0)throw new he("marketplace_invalid",y);let g=f.find((x)=>x.name===Zo);if(g===void 0||!ud(g.marketplaceSource))throw new he("readback_mismatch","Codex did not report the canonical HolyCodex marketplace after installation or refresh.")},add:async(o,i)=>{let a=Ve(ns,o,"official plugin id"),s=Ic(a),c=Qn(a)==="computer-use@openai-bundled"?s:s.includes(a)?[a,...s.filter((y)=>y!==a)]:[a],l=!1;for(let[y,g]of c.entries()){let x=await t.run(["plugin","add",g,"--json"],i===void 0?void 0:{signal:i});if(x.exitCode===0){l=!0;break}if(y<c.length-1&&HV(x.stderr))continue;throw Ki("add",x,g)}if(!l)throw new he("command_failed",`Codex could not install ${a} from its recognized marketplace sources.`);let u=await n(),d=ao(u,a),p=Qn(a),m=[...u.installed,...u.available].filter((y)=>y.pluginId===a&&(p===void 0||y.marketplaceName==null)),f=d?.entry??m.find((y)=>y.installed)??m[0];if(!f)throw new he("readback_mismatch",`Codex did not report ${a} after installation.`,{plugin_id:a});if(!f.installed)throw new he("plugin_missing",`Codex reported ${a} as unavailable after installation.`,{plugin_id:a});if(!f.enabled)throw new he("plugin_disabled",`Codex installed ${a} but it is disabled; enable it in Codex and retry.`,{plugin_id:a})},remove:async(o,i)=>{let a=Ve(ns,o,"official plugin id"),s=a;if(Qn(a)===a){let d=await n(),p=ao(d,a);if(p?.entry.installed)s=p.entry.pluginId}let c=await t.run(["plugin","remove",s,"--json"],i===void 0?void 0:{signal:i});if(c.exitCode!==0&&!/not (?:installed|found)|missing/iu.test(c.stderr))throw Ki("remove",c,s);let l=await n(),u=[...l.installed,...l.available].find((d)=>d.pluginId===s);if(u?.installed)throw new he("readback_mismatch",`Codex still reports ${a} after removal.`,{plugin_id:a,observed_plugin_id:u.pluginId})}}}function Ki(e,t,n){let r=zi(t.stderr).trim().slice(0,512),o=r.length>0?`: ${r}`:"";return new he("command_failed",`Codex plugin ${e} failed${n===void 0?"":` for ${n}`}${o}`,{exit_code:t.exitCode})}function HV(e){return/plugin\b.+\bnot found in marketplace\b/iu.test(zi(e))}function BV(e){if(!(e instanceof he)||e.code!=="command_failed")return!1;return/(?:^|[\n:])\s*-\s*`([^`]+)`\s+at\s+[^\r\n]*:\s*marketplace root does not contain a supported manifest/iu.exec(e.message)?.[1]===Zo}function q_(e,t){let n=e.filter((o)=>o.name===t);if(n.length>1)return`Multiple Codex marketplaces use the reserved name ${t}; resolve the duplicate configuration before installing HolyCodex.`;if(n[0]!==void 0&&!ud(n[0].marketplaceSource)){let o=n[0].marketplaceSource?.source??"an unknown source";return`Codex marketplace ${t} points to ${o}, not the canonical HolyCodex source ${W_}; resolve the conflict before installing.`}let r=e.find((o)=>o.name!==t&&ud(o.marketplaceSource));if(r!==void 0)return`The canonical HolyCodex source is already registered as Codex marketplace ${r.name}; resolve the noncanonical marketplace name before installing.`;return}function VV(e,t){let r=e.filter((o)=>o.name===t).length>1;return[...new Set(e.filter((o)=>o.name===t&&(r||!ud(o.marketplaceSource))||o.name!==t&&ud(o.marketplaceSource)).map((o)=>o.name))]}function ud(e){if(e?.sourceType!=="git")return!1;return Ch(e.source)}function Ch(e){return TV.some((t)=>t===e)}function F0(e,t){let n=t.timeoutMs??30000,r=t.stdoutLimit??131072,o=t.stderrLimit??16384;return{run:(i,a)=>WV(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 WV(e,t,n){if(n.signal?.aborted)throw new he("cancelled","The Codex plugin command was cancelled.");let r=xV(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=_0(r.stdout,n.stdoutLimit),i=_0(r.stderr,n.stderrLimit),a=new Promise((d,p)=>{r.once("error",p),r.once("close",(m)=>d(m??-1))}),s,c,l=new Promise((d,p)=>{c=()=>{try{r.kill()}catch{}p(new he("cancelled","The Codex plugin command was cancelled."))},n.signal?.addEventListener("abort",c,{once:!0})}),u=new Promise((d,p)=>{s=setTimeout(()=>{try{r.kill()}catch{}p(new he("timeout","The Codex plugin command timed out."))},n.timeoutMs)});try{let[d,p,m]=await Promise.race([Promise.all([o,i,a]),l,u]);return{stdout:d,stderr:p,exitCode:m}}catch(d){try{r.kill()}catch{}if(d instanceof he)throw d;throw new he("command_failed","The Codex plugin command failed.")}finally{if(s!==void 0)clearTimeout(s);if(c!==void 0)n.signal?.removeEventListener("abort",c)}}function _0(e,t){if(e===null)return Promise.reject(new he("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 he("command_failed","Codex plugin output was invalid."));return}if(i+=s.byteLength,i>t){r(new he("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 ld="openai-curated",rs="https://github.com/openai/plugins.git",Zo="holycodex",W_="davidbasilefilho/holycodex",TV,z_,K_=30000,CV=100,OV,C0,kV,cd,ns,EV,jV,H_,B_,he;var Oh=w(()=>{ht();Dt();o_();io();wh();TV=[W_,"https://github.com/davidbasilefilho/holycodex.git","https://github.com/davidbasilefilho/holycodex","https://github.com/davidbasilefilho/holycodex.git/","https://github.com/davidbasilefilho/holycodex/","git@github.com:davidbasilefilho/holycodex.git","git@github.com:davidbasilefilho/holycodex","ssh://git@github.com/davidbasilefilho/holycodex.git","ssh://git@github.com/davidbasilefilho/holycodex"],z_=["plugins","openai-plugins"],OV=[25,50,100,200],C0=q.pipe(we(/^[a-z][a-z0-9._-]{1,63}$/u)),kV=q.pipe(we(/^[0-9]+\.[0-9]+\.[0-9]+(?:[-+][A-Za-z0-9.-]+)?$/u)),cd=K(q),ns=q.pipe(we(/^[A-Za-z0-9][A-Za-z0-9._:@/-]{0,255}$/u)),EV=T({name:C0,version:kV,description:Yo,author:R($n),license:R(Yo),homepage:R(Yo),repository:R(Yo),keywords:R(cd),skills:R(cd),commands:R(cd),hooks:R(cd),assets:R(cd),official:R(V)});jV=T({id:C0,selected:E(!0)}),H_=T({pluginId:ns,installed:V,enabled:V,name:R(Se(q,At)),marketplaceName:R(Se(q,At)),version:R(Se(q,At))},Zm({key:q,value:pw})),B_=T({installed:K(H_),available:K(H_)});he=class he extends Error{code;details;constructor(e,t,n={}){super(t);this.name="OfficialPluginAdapterError",this.code=e,this.details=n}}});function Lc(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)=>Lc(n,t));return de(e)&&Object.values(e).every((n)=>Lc(n,t))}finally{t.delete(e)}}function Ir(e){return de(e)&&Lc(e)}function Z_(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('"')?KV(s):s,l=s.startsWith('"'),u=l&&t.length===1&&t[0]==="plugins"&&Gm(ns)(c),d=l&&t.length===1&&t[0]==="agents"&&Y_.includes(c);if(l?!u&&!d:!/^[A-Za-z][A-Za-z0-9_-]*$/u.test(c)&&!Y_.includes(c))throw Qe("TOML key path",e);if(c==="__proto__"||(c==="constructor"||c==="prototype")&&!u)throw Qe("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 Qe("TOML key path",e);return t}function KV(e){try{let t=JSON.parse(e);if(typeof t==="string")return t}catch{}throw Qe("TOML quoted key",e)}function fe(e,t){if(!Ir(e))throw Qe("TOML document",e);let n=e,r=Z_(t);for(let o=0;o<r.length;o+=1){let i=r[o];if(!Ir(n)||!Object.prototype.hasOwnProperty.call(n,i))return;if(n=n[i],o===1&&r[0]==="features"&&i==="context_management"&&typeof n==="boolean"&&r[2]==="experimental_mode")return n}return n}function kh(e){if(Array.isArray(e))return e.map(kh);if(de(e))return Object.fromEntries(Object.entries(e).map(([t,n])=>[t,kh(n)]));return e}function Eh(e){return kh(e)}function so(e,t,n){if(!Ir(e)||!Lc(n))throw Qe("TOML write",{keyPath:t});let r=Z_(t),o={...Eh(e)},i=o;for(let a of r.slice(0,-1)){let s=Object.prototype.hasOwnProperty.call(i,a)?i[a]:void 0;if(s!==void 0&&!Ir(s)){if(a!=="context_management"||typeof s!=="boolean"||i!==o.features)throw Qe("TOML table path",t);if(r.at(-1)==="experimental_mode"&&s===n)return o;i[a]={experimental_mode:s}}let c=s===void 0?{}:Ir(i[a])?{...i[a]}:{};i[a]=c,i=c}return i[r.at(-1)]=kh(n),o}function tr(e,t){if(!Ir(e))throw Qe("TOML document",e);let n=Z_(t),r={...Eh(e)},o=[],i=r;for(let s of n.slice(0,-1)){let c=i[s];if(!Ir(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(Ir(l)&&Object.keys(l).length===0)delete c.table[c.key];else break}return r}function is(e){if(typeof e!=="string")return!1;if(D0.includes(e))return!0;if(/^agents\.(?:explorer|librarian|worker|reviewer)\.config_file$/u.test(e))return!0;return Y_.some((t)=>e===`agents."${t}".config_file`)}function Ih(e){return is(e)||Zi.includes(e)}function Gi(e){return typeof e==="string"&&GV.test(e)}function X_(e){return e==="gpt-6-astra"||e==="gpt-6.1-sol"||e==="gpt-6-sol"||e==="gpt-6-luna"||e==="gpt-5.6-terra"||e==="gpt-5.6-sol"||e==="gpt-5.6-luna"||e==="low"||e==="medium"||e==="high"||e==="xhigh"||e==="max"||e==="default"||e==="fast"||e==="live"||e==="cached"||e==="indexed"||e==="disabled"}function YV(e){return typeof e==="string"&&/^[a-f0-9]{64}$/u.test(e)}function Q_(e){return typeof e==="number"&&Number.isSafeInteger(e)&&e>=0}function ev(e,t){let n=new Set(t);return Object.keys(e).every((r)=>n.has(r))}function tv(e){if(!de(e)||!ev(e,["kind","value"])||typeof e.kind!=="string")return!1;switch(e.kind){case"enum":return X_(e.value);case"number":return Q_(e.value);case"boolean":return typeof e.value==="boolean";case"relative_path":return typeof e.value==="string"&&Mh(e.value);case"digest":return YV(e.value);default:return!1}}function L0(e,t){switch(rv(e)){case"number":return t.kind==="number";case"boolean":return t.kind==="boolean";case"relative_path":return t.kind==="relative_path";case"digest":return t.kind==="digest";case"enum":if(t.kind!=="enum")return!1;if(e==="model")return t.value==="gpt-6-astra"||t.value==="gpt-6.1-sol"||t.value==="gpt-6-sol"||t.value==="gpt-6-luna"||t.value==="gpt-5.6-terra"||t.value==="gpt-5.6-sol"||t.value==="gpt-5.6-luna";if(e==="model_reasoning_effort")return t.value==="low"||t.value==="medium"||t.value==="high"||t.value==="xhigh"||t.value==="max";if(e==="service_tier")return t.value==="default"||t.value==="fast";if(e==="web_search")return t.value==="live"||t.value==="cached"||t.value==="indexed"||t.value==="disabled";return t.value==="low"||t.value==="medium"||t.value==="high"}}function j0(e){return de(e)&&e.kind==="absent"?Object.keys(e).length===1:tv(e)}function H0(e){return de(e)&&ev(e,["owner","schema","installId","keyPath","originalValue","lastManagedValue"])&&e.owner==="holycodex"&&typeof e.schema==="string"&&Gi(e.schema)&&Gi(e.installId)&&Ih(e.keyPath)&&j0(e.originalValue)&&tv(e.lastManagedValue)&&L0(e.keyPath,e.lastManagedValue)&&(e.originalValue.kind==="absent"||L0(e.keyPath,e.originalValue))}function Yi(e){if(!de(e)||!ev(e,["owner","schema","installId","managed"])||e.owner!=="holycodex"||!Gi(e.schema)||!Gi(e.installId)||!de(e.managed))return!1;return Object.entries(e.managed).every(([t,n])=>Ih(t)&&H0(n)&&n.keyPath===t)}function Ph(e){if(!Gi(e.schema)||!Gi(e.installId))throw Qe("managed runtime config metadata",{schema:e.schema});return{owner:"holycodex",schema:e.schema,installId:e.installId,managed:{}}}function Mh(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 nv(e){if(!Mh(e))throw Qe("relative config path","[redacted]");return e.replaceAll("\\","/").split("/").filter((t)=>t!==".").join("/")}function as(e,t){let n=nv(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 rv(e){if(e==="developer_instructions")return"digest";if(e.endsWith(".config_file"))return"relative_path";if(e==="agents.max_concurrent_threads_per_session")return"number";if(e==="model_auto_compact_token_limit")return"number";if(e==="suppress_unstable_features_warning"||e==="features.multi_agent"||e==="features.default_mode_request_user_input"||e==="features.multi_agent_v2"||e==="features.agent_message_board"||e==="features.context_management.experimental_mode"||Zi.includes(e)||e==="sandbox_workspace_write.network_access")return"boolean";return"enum"}function ZV(e,t){let n=rv(e);if(n==="number")return Q_(t);if(n==="boolean")return typeof t==="boolean";if(n==="relative_path")return typeof t==="string"&&Mh(t);if(n==="digest")return typeof t==="string";if(e==="model")return t==="gpt-6-astra"||t==="gpt-6.1-sol"||t==="gpt-6-luna";return typeof t==="string"&&X_(t)}async function _n(e,t){if(!Ih(e)||!Lc(t))throw Qe("managed config value",{keyPath:e});let n=rv(e);if(n==="number"&&Q_(t))return{kind:n,value:t};if(n==="boolean"&&typeof t==="boolean")return{kind:n,value:t};if(n==="relative_path"&&typeof t==="string"&&Mh(t))return{kind:n,value:nv(t)};if(n==="enum"&&typeof t==="string"&&X_(t))return{kind:n,value:t};return{kind:"digest",value:await qn("holycodex-managed-config-value",[Dn({keyPath:e,value:t})])}}function XV(e){if(e.kind==="enum"||e.kind==="number"||e.kind==="boolean"||e.kind==="relative_path")return e.value;return}async function Dc(e,t,n,r){if(!Ir(e)||!Yi(t)||!Gi(r.schema)||!Gi(r.installId))throw Qe("managed runtime config",{});let o={...t.managed},i=Eh(e),a=[];for(let[c,l]of Object.entries(n)){if(!is(c)||typeof l!=="string"&&typeof l!=="number"&&typeof l!=="boolean")throw Qe("managed config key",c);let u=c,d=t.managed[u],p=fe(i,u);if(d&&(d.schema!==r.schema||d.installId!==r.installId)){a.push(u);continue}if(d&&d.owner==="holycodex"){let f=p===void 0?void 0:await _n(u,p);if(f===void 0||JSON.stringify(f)!==JSON.stringify(d.lastManagedValue)){a.push(u);continue}}let m=d?.originalValue??(p===void 0?{kind:"absent"}:await _n(u,p));if(!ZV(u,l))throw Qe("managed config value",{keyPath:u});i=so(i,u,l),o[u]={owner:"holycodex",schema:r.schema,installId:r.installId,keyPath:u,originalValue:m,lastManagedValue:await _n(u,l)}}let s={owner:"holycodex",schema:r.schema,installId:r.installId,managed:o};if(!Yi(s))throw Qe("managed runtime config state",{});return{document:i,state:s,driftedKeys:a}}async function Ar(e,t,n){if(!Ir(e)||!Yi(t))throw Qe("managed runtime config",{});let r=Eh(e),o={...t.managed},i=[],a=[],s=[];for(let[c,l]of Object.entries(t.managed)){if(!Ih(c))throw Qe("managed config key",c);let u=c;if(l.owner!=="holycodex"||l.schema!==n.schema||l.installId!==n.installId){if(l.schema!==n.schema||l.installId!==n.installId)s.push(u);continue}let d=fe(r,u);if(!(d!==void 0&&JSON.stringify(await _n(u,d))===JSON.stringify(l.lastManagedValue))){a.push(u);continue}if(l.originalValue.kind==="absent")r=tr(r,u),i.push(u),delete o[u];else{let m=XV(l.originalValue);if(m===void 0){s.push(u),a.push(u);continue}r=so(r,u,m),i.push(u),delete o[u]}}return{document:r,state:{...t,managed:o},restoredKeys:i,preservedKeys:a,unresolvedKeys:s}}async function ss(e,t,n){if(!is(n)||!Yi(t))throw Qe("managed config key",n);let r=t.managed[n],o=fe(e,n),i=o===void 0?void 0:await _n(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 Y_,zV,os,D0,Zi,JV,q0,U0,$0,Ah,GV;var Nh=w(()=>{ht();ht();Dt();io();Oh();Y_=[...Go,"Reviewer.plan"];zV=ee((e)=>Lc(e)),os=ee((e)=>Ir(e));D0=["model","model_reasoning_effort","service_tier","agents.max_concurrent_threads_per_session","web_search","sandbox_workspace_write.network_access","model_verbosity","developer_instructions","suppress_unstable_features_warning","features.multi_agent","features.default_mode_request_user_input","features.multi_agent_v2","features.agent_message_board","features.context_management.experimental_mode"],Zi=["model_auto_compact_token_limit","features.context_management"],JV=ee((e)=>is(e));q0=ee((e)=>tv(e)),U0=ee((e)=>j0(e)),$0=ee((e)=>H0(e)),Ah=ee((e)=>Yi(e)),GV=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u});function eW(e){return typeof e==="number"&&Number.isFinite(e)&&e>=0}function B0(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)=>eW(e[i]))}function z0(e){if(!de(e)||!Xe(e))return!1;return B0(e,["inputTokens","cachedInputTokens","outputTokens","reasoningOutputTokens"],"totalTokens")||B0(e,["input_tokens","cached_input_tokens","output_tokens","reasoning_output_tokens"],"total_tokens")}function Fh(e){return de(e)&&Xe(e)&&typeof e.id==="string"&&/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u.test(e.id)}function K0(e){return de(e)&&Xe(e)&&Fh(e.thread)}function rW(e){return de(e)&&Xe(e)&&typeof e.id==="string"}function Xi(e){return de(e)&&Xe(e)&&typeof e.threadId==="string"&&e.threadId.length>0}function J0(e){return de(e)&&Xe(e)&&typeof e.id==="string"&&e.id.length>0&&(e.usage===void 0||z0(e.usage))}function oW(e){return de(e)&&Xe(e)&&typeof e.id==="string"&&typeof e.model==="string"&&(e.supportedReasoningEfforts===void 0||Array.isArray(e.supportedReasoningEfforts)&&e.supportedReasoningEfforts.every((t)=>de(t)&&typeof t.reasoningEffort==="string"))&&(e.serviceTiers===void 0||Array.isArray(e.serviceTiers)&&e.serviceTiers.every((t)=>de(t)&&typeof t.id==="string"))&&(e.defaultServiceTier===void 0||e.defaultServiceTier===null||typeof e.defaultServiceTier==="string")&&(e.multiAgentVersion===void 0||e.multiAgentVersion===null||e.multiAgentVersion==="disabled"||e.multiAgentVersion==="v1"||e.multiAgentVersion==="v2")}function w0(e){if(rd.some((t)=>t===e))return"permissions";if(nd.some((t)=>t===e))return"approval";if(e_.some((t)=>t===e))return"elicitation";if(t_.some((t)=>t===e))return"dynamic_tool";return"other"}var V0,dd,W0,od,QV,i_,id,tW,gh,a_,s_,nW,ad,c_,l_,u_,d_,p_,f_,m_,h_,g_,y_,x_,S_,b_,w_,__,v_,R_,T_,C_,O_,k_,E_,I_,A_,P_,M_,N_,F_,zQ,iW,KQ;var L_=w(()=>{Dt();io();hh();Nh();V0=q.pipe(we(/^[A-Za-z][A-Za-z0-9_./:-]{0,127}$/u)),dd=Se(q.pipe(Tc(1)),wn.pipe(Ze((e)=>Number.isSafeInteger(e)))),W0=T({code:wn.pipe(Ze((e)=>Number.isSafeInteger(e))),message:q,data:R($n)}),od=Se(T({id:dd,result:$n}),T({id:dd,error:W0})),QV=T({id:dd,error:W0}),i_=T({method:V0,params:R($n)}),id=T({id:dd,method:V0,params:R($n),trace:R($n)});tW=ee(z0),gh=T({clientInfo:T({name:Yo,version:Yo,title:Se(Yo,At)}),capabilities:Se(T({experimentalApi:V,requestAttestation:V,mcpServerOpenaiFormElicitation:R(V),optOutNotificationMethods:R(Se(K(q),At)),extensions:R(Vi)}),At)}),a_=ee((e)=>de(e)&&Xe(e)&&typeof e.userAgent==="string"&&typeof e.codexHome==="string"&&typeof e.platformFamily==="string"&&typeof e.platformOs==="string"),s_=T({method:E("initialized")});nW=ee(Fh);ad=ee((e)=>K0(e)||rW(e)),c_=ad,l_=ad,u_=ee(Xi),d_=ee((e)=>de(e)&&Xe(e)&&(e.status==="notLoaded"||e.status==="notSubscribed"||e.status==="unsubscribed")),p_=ee((e)=>K0(e)),f_=ee((e)=>{if(!de(e)||!Xe(e))return!1;let t=Array.isArray(e.data)&&e.data.every((r)=>Fh(r)),n=Array.isArray(e.threads)&&e.threads.every((r)=>Fh(r));return t&&e.threads===void 0||n&&e.data===void 0}),m_=ee((e)=>de(e)&&Xe(e));h_=ee(Xi),g_=ee(Xi),y_=ee(Xi),x_=ee((e)=>de(e)&&Xe(e));S_=ee((e)=>Xi(e)&&(Array.isArray(e.input)&&e.input.every((t)=>Xe(t))||typeof e.prompt==="string"&&e.prompt.length>0)),b_=ee((e)=>Xi(e)&&typeof e.expectedTurnId==="string"&&Array.isArray(e.input)&&e.input.every((t)=>Xe(t))),w_=ee((e)=>de(e)&&Xe(e)&&(e.turn!==void 0&&J0(e.turn)||typeof e.turnId==="string"&&e.turnId.length>0||typeof e.id==="string"&&e.id.length>0)),__=ee((e)=>de(e)&&Xe(e)&&typeof e.turnId==="string"&&e.turnId.length>0),v_=ee((e)=>Xi(e)&&typeof e.turnId==="string"&&e.turnId.length>0),R_=ee((e)=>de(e)&&Xe(e)),T_=ee((e)=>Xi(e)&&(e.turn!==void 0&&J0(e.turn)||typeof e.turnId==="string"&&e.turnId.length>0)),C_=ee((e)=>de(e)&&Xe(e));O_=ee((e)=>de(e)&&Xe(e)&&Array.isArray(e.data)&&e.data.every((t)=>oW(t))),k_=Vi,E_=Vi,I_=T({includeLayers:R(V),cwd:R(Se(q,At))}),A_=T({config:os,origins:Vi,layers:Se(K(Vi),At)}),P_=Vi,M_=Vi,N_=ee((e)=>de(e)&&Xe(e)&&(typeof e.id==="string"||typeof e.id==="number"&&Number.isSafeInteger(e.id))&&typeof e.method==="string"&&de(e.params)&&(e.category==="approval"||e.category==="dynamic_tool"||e.category==="elicitation"||e.category==="other"||e.category==="permissions")),F_=$n,zQ=ee((e)=>de(e)&&Xe(e)&&typeof e.kind==="string"&&typeof e.method==="string");iW=Se(E("stable","experimental","disabled"),V),KQ=Zm({key:q,value:iW})});import{lstat as YQ,mkdir as ZQ,readFile as aW,readdir as XQ,realpath as sW,stat as cW}from"fs/promises";import{delimiter as lW,isAbsolute as eee,join as tee,relative as nee,resolve as G0}from"path";async function dW(e){let t=[];if(e.executablePath!==void 0)t.push(G0(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(lW).filter((i)=>i.length>0))for(let i of r)t.push(G0(o,i))}for(let n of t)try{let r=await cW(n);if(!r.isFile())continue;if(process.platform!=="win32"&&(r.mode&73)===0)continue;return await sW(n)}catch{if(e.executablePath!==void 0)throw new ie("discovery_failed","The explicit Codex executable was not found.",{path:n})}throw new ie("discovery_failed","No Codex executable was found on the allowlisted PATH.")}async function pW(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 ie("discovery_failed","The Codex version command did not expose output pipes.");try{let[r,o,i]=await mW(Promise.all([xh(n.stdout,16384),xh(n.stderr,16384),n.exited]),()=>n.kill(),"The Codex version command timed out."),a=Un(Sh(r,"Codex version output"));if(i!==0||a.length===0){let s=zi(Sh(o,"Codex version diagnostics"));throw new ie("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 ie)throw r;throw new ie("discovery_failed","The Codex version command failed.",{},{cause:r})}}async function fW(e){let t=await aW(e),n=await crypto.subtle.digest("SHA-256",t),r=[...new Uint8Array(n)].map((i)=>i.toString(16).padStart(2,"0")).join(""),o=nh(r);if(!o.ok)throw new ie("discovery_failed","The Codex executable digest was invalid.");return o.value}async function ov(e={}){let t=await dW(e),n=Wi(e.environment),r=e.versionRunner?Un(await e.versionRunner(t,n)):await pW(t,n);if(r.length===0)throw new ie("discovery_failed","The Codex version output was empty.");return{path:t,version:r,sha256:await fW(t)}}async function mW(e,t,n){let r;try{return await Promise.race([e,new Promise((o,i)=>{r=setTimeout(()=>{try{t()}catch{}i(new ie("timeout",n))},uW)})])}finally{if(r!==void 0)clearTimeout(r)}}var uW=30000,aee;var Y0=w(()=>{ht();Dt();io();wh();aee=T({exitCode:wn.pipe(Ze((e)=>Number.isSafeInteger(e))),stdout:q.pipe(yw(1048576)),stderr:q.pipe(yw(1048576))})});var hW="packages/codex/generated",gW,yW,iv,uee,dee;var Z0=w(()=>{ht();Dt();io();gW=/^codex-cli \d+\.\d+\.\d+$/u,yW=/^codex-app-server-\d+\.\d+\.\d+$/u,iv=q.pipe(we(/^[a-f0-9]{64}$/u)),uee=T({schema_version:E("holycodex-generated-v2"),artifact_root:E(hW),codex_cli_version:q.pipe(we(gW)),codex_cli_digest:iv,protocol_epoch:q.pipe(we(yW)),generator:T({command:dN(E("app-server"),E("generate-ts")),supported_surface:E("codex app-server generators")}),typescript_root:E("typescript"),files:T({count:wn.pipe(Xm(),Sw()),digest:iv})}),dee=T({path:q.pipe(Tc(1)),size:wn.pipe(Xm(),Sw()),sha256:iv})});var xW;var X0=w(()=>{Dt();Nh();xW=T({owner:E("holycodex"),schema:q.pipe(we(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u)),installId:q.pipe(we(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u))})});var cs=w(()=>{io();io();hh();L_();o_();wh();Y0();Z0();X0();Nh();Oh();Oh()});function sn(e){if(!qc(e))throw Error("The value is not JSON serializable.");return Ln(e),e}function qc(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)=>qc(n,t));return Object.getPrototypeOf(e)===Object.prototype&&Object.values(e).every((n)=>qc(n,t))}finally{t.delete(e)}}var hd=w(()=>{ht()});function Ie(e,t){let n=Xn(e,t);return Ct(n)?n.right:void 0}function cF(e){return Ie(gd,e)!==void 0}var gd,nte,kW,EW,yd,IW,ea,AW,PW,MW,tF,xd,qh,nF,Sd,rF,nn,lv,NW,FW,LW,DW,qW,UW,$W,jW,HW,Dh,BW,eF,VW,Uh,Uc,WW,uv,zW,dv,KW,oF,pv,fv,ta,iF,JW,aF,GW,sF;var ls=w(()=>{cs();ht();hn();Dt();hd();gd=ee((e)=>typeof e==="object"&&e!==null&&!Array.isArray(e)&&qc(e)),nte=ee(qc),kW=kc,EW=q.pipe(we(/^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/u)),yd=q.pipe(we(/^[0-9a-f]{64}$/u)),IW=q.pipe(we(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u)),ea=q.pipe(we(/^[A-Za-z0-9][A-Za-z0-9._:@/-]{0,255}$/u)),AW=q.pipe(Ze((e)=>!Number.isNaN(Date.parse(e)))),PW=T({path:q.pipe(we(/^[A-Za-z0-9][A-Za-z0-9._/-]{0,255}$/u)),digest:yd}),MW=T({browser_use:V,computer_use:V,sites:V,coding:E(!0)}),tF=T({browser_use:R(V),computer_use:R(V),sites:R(V)}),xd=T({profile:R(ro),tier:R(Ko),optional:R(tF),officialPlugins:R(K(ea))}),qh=xd,nF=E("keep","remove","replace","cancel"),Sd=T({schema_version:E(1),profile:ro,tier:Ko,capabilities:K(Rw),additional_plugins:K(ea)}),rF=T({schema_version:E(1),profile:ro,tier:Ko,capabilities:K(Ku),additional_plugins:K(ea)}),nn=T({selected:V,status:E("disabled","pending","healthy","missing","provider_disabled","uncertain","unavailable"),plugin_ids:K(ea),reason:R(q)}),lv=T({browser_use:nn,computer_use:nn,frontend:nn,security:nn,sites:nn}),NW=T({browser_use:R(V),computer_use:V,frontend:V,security:V,sites:R(V),coding:E(!0),work:V}),FW=T({browser_use:R(V),computer_use:R(V),frontend:R(V),security:R(V),sites:R(V),work:R(V)}),LW=T({browser_use:R(nn),computer_use:nn,frontend:nn,security:nn,sites:R(nn),work:nn}),DW=T({computer_use:V,frontend:V,security:V,coding:E(!0)}),qW=T({computer_use:R(V),frontend:R(V),security:R(V)}),UW=T({computer_use:nn,frontend:nn,security:nn}),$W=Se(T({status:E("not_applicable")}),T({status:E("missing")}),T({status:E("healthy"),path:q,installed:V})),jW=T({manager:E("bun","npm","pnpm"),launcher:E("bunx","npx","pnpm dlx"),version:EW,executable:q,ownership:E("user","holycodex"),identity:R(yd)}),HW=T({git_bash:R($W),context7:R(jW)}),Dh=T({presence:E("absent","present"),digest:yd,safe_value:R(Se(T({kind:E("boolean"),value:V}),T({kind:E("marketplace"),source_type:E("git"),source:E("https://github.com/davidbasilefilho/holycodex.git")})))}),BW=T({plugin_id:E("holycodex@holycodex"),before:T({preference:Dh,marketplace:Dh}),after:T({preference:Dh,marketplace:Dh})}),eF=T({presence:E("absent","present"),digest:yd,safe_value:R(T({kind:E("boolean"),value:V}))}),VW=T({plugin_id:ea,before:eF,after:eF}),Uh={owner:E("holycodex"),schema_epoch:E(On),install_id:IW,version:kW,digest:yd,profile:ro,tier:Ko,optional_selections:MW,explicit_optional_selections:tF,official_plugins:R(K(ea)),capability_state:R(lv),managed_artifacts:K(PW),installed_at:AW,status:R(E("active")),step:R(E("active")),managed_config:R(Ah),plugin_snapshot:R(K(T({plugin_id:ea,status:E("installed","available","missing","disabled","uncertain","unknown")}))),plugin_config:R(BW),provider_config:R(K(VW)),owned_plugins:R(K(ea)),tooling:R(HW)},Uc=T(Uh),WW=(({profile:e,...t})=>t)(Uh),uv={...Uh,optional_selections:NW,explicit_optional_selections:FW,capability_state:R(LW)},zW=(({profile:e,...t})=>t)(uv),dv={...Uh,optional_selections:DW,explicit_optional_selections:qW,capability_state:R(UW)},KW=(({profile:e,...t})=>t)(dv),oF=Se(T({...uv,profile:kr}),T({...zW,plan:kr}),T({...WW,plan:kr}),T({...dv,profile:kr}),T({...KW,plan:kr})),pv=E("preparing","conflicted"),fv=E("validated","plugins_snapshotted","roles_prepared","plugins_installed","config_published","verified","conflicted"),ta=T({...Uc.fields,status:pv,step:fv}),iF={...uv,status:pv,step:fv},JW=(({profile:e,...t})=>t)(iF),aF={...dv,status:pv,step:fv},GW=(({profile:e,...t})=>t)(aF),sF=Se(ta,T({...iF,profile:kr}),T({...JW,plan:kr}),T({...aF,profile:kr}),T({...GW,plan:kr}))});import{lstat as YW,mkdir as ZW}from"fs/promises";import{homedir as XW}from"os";import{dirname as QW,join as na,posix as lF,resolve as ez,sep as uF,win32 as dF}from"path";function Pr(e={},t=process.env){let n=XW(),r=e.paths?.codexHome??t.CODEX_HOME??na(n,".codex"),o=hv(r,"CODEX_HOME"),i=na(o,tz);return{codexHome:o,stateRoot:i,activeRecord:na(i,nz),preparingRecord:na(i,rz),conflictedRecord:na(i,oz),installOptions:na(i,iz),roleRoot:na(i,"agents"),configFile:na(o,"config.toml")}}function hv(e,t,n=process.platform==="win32"?"win32":"posix"){if(typeof e!=="string"||sz(e))throw new nr("invalid_path",`${t} contains invalid characters.`);let r=n==="win32"?dF:lF,o=mv(e,n);if(typeof o!=="string"||o.length===0||!r.isAbsolute(o))throw new nr("invalid_path",`${t} must be an absolute path.`);let i=r.normalize(o);if(i.split(n==="win32"?"\\":uF).filter((s)=>s.length>0).length===0||i===r.dirname(i))throw new nr("broad_path",`${t} is too broad.`);if(o.split(/[\\/]/u).some((s)=>s===".."))throw new nr("invalid_path",`${t} cannot contain traversal.`);return r.resolve(i)}function sz(e){for(let t of e){let n=t.codePointAt(0)??0;if(n<=31||n===127)return!0}return!1}async function $c(e){hv(e,"owned path"),await co(e),await ZW(e,{recursive:!0}),await co(e)}async function co(e){let n=ez(e);while(!0){try{if((await YW(n)).isSymbolicLink())throw new nr("path_symlink","A managed path cannot contain a symlink.")}catch(o){if(o instanceof nr)throw o;if(!We(o,"ENOENT"))throw o}let r=QW(n);if(r===n)break;n=r}}async function us(e){await co(e)}function rr(e,t,n=process.platform==="win32"?"win32":"posix"){let r=n==="win32"?dF:lF,o=r.resolve(mv(e,n)),i=r.resolve(mv(t,n)),a=r.relative(o,i);return a.length>0&&!a.startsWith(`..${n==="win32"?"\\":uF}`)&&a!==".."&&!r.isAbsolute(a)}function mv(e,t){if(t==="win32"&&/^\/[A-Za-z](?:\/|$)/u.test(e))return`${e[1]?.toUpperCase()??""}:${e.slice(2).replaceAll("/","\\")}`;return e}function We(e,t){return typeof e==="object"&&e!==null&&"code"in e&&e.code===t}var tz="holycodex",nz="active.toml",rz="preparing.toml",oz="conflicted.toml",iz="install.toml",az,nr;var ds=w(()=>{ht();az=On;nr=class nr extends Error{code;constructor(e,t){super(t);this.name="PathBoundaryError",this.code=e}}});function bd(e){let t={},n=[];for(let r of e.split(/\r?\n/u)){let o=lz(r).trim();if(o.length===0)continue;if(o.startsWith("[["))throw Error("Array-of-tables are not supported by the validated fallback.");if(o.startsWith("[")&&o.endsWith("]")){n=gv(o.slice(1,-1).trim()),cz(t,n);continue}let i=mF(o);if(i<1)throw Error("TOML assignment is invalid.");let a=gv(o.slice(0,i).trim()),s=$h(o.slice(i+1).trim());fF(t,[...n,...a],s)}return t}function wd(e){let t=[];return pF(e,[],t),t.join(`
36
- `)}function pF(e,t,n){let r=[],o=[];for(let[i,a]of Object.entries(e))if(bv(a))o.push([i,a]);else r.push([i,a]);if(t.length>0){if(n.length>0)n.push("");n.push(`[${t.map(xv).join(".")}]`)}for(let[i,a]of r)n.push(`${xv(i)} = ${Sv(a)}`);for(let[i,a]of o)pF(a,[...t,i],n)}function $h(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?[]:yv(t,",").map((n)=>$h(n.trim()))}if(e.startsWith("{")){if(!e.endsWith("}"))throw Error("TOML inline table is invalid.");let t=e.slice(1,-1).trim(),n={};if(t.length===0)return n;for(let r of yv(t,",")){let o=mF(r);if(o<1)throw Error("TOML inline table entry is invalid.");fF(n,gv(r.slice(0,o).trim()),$h(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 gv(e){let t=yv(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("'")?$h(n):n)}function fF(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(bv(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 cz(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(bv(o))n=o;else throw Error("TOML table conflicts with a scalar.")}}function yv(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 mF(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 lz(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 bv(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function xv(e){return/^[A-Za-z0-9_-]+$/u.test(e)?e:JSON.stringify(e)}function Sv(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(Sv).join(", ")}]`;if(e===null)throw Error("TOML null is not serializable.");return`{ ${Object.entries(e).map(([t,n])=>`${xv(t)} = ${Sv(n)}`).join(", ")} }`}import{lstat as hF,open as uz,readFile as gF,rename as dz,unlink as yF,writeFile as pz}from"fs/promises";import{dirname as fz}from"path";async function xF(e){let t;try{t=await uz(e,"r"),await t.sync()}catch(n){if(!bF(n))throw n}finally{await t?.close().catch(()=>{return})}}async function hz(e){await xF(e).catch((t)=>{if(!bF(t))throw t})}async function SF(e,t){await vt(e,`${Ln(t)}
37
- `)}async function jc(e,t){let n=[];function r(i,a){if(i===null)return n.push(a),"";if(Array.isArray(i))return i.map((s,c)=>r(s,[...a,String(c)]));if(typeof i==="object")return Object.fromEntries(Object.entries(i).map(([s,c])=>[s,r(c,[...a,s])]));return i}let o={format_version:1,null_paths:n,record:r(t,[])};await vt(e,wd(o))}async function wv(e,t){let n=await ye(e);if(n===void 0){let r=e.replace(/\.toml$/u,".json");return await xz(r,t)}return gz(n,t)}async function _d(e,t){if(await ye(e)!==void 0)return;let n=e.replace(/\.toml$/u,".json"),r=await ye(n);if(r===void 0)return;if(await jc(e,t),await ye(n)!==r)throw new lo("state_corrupt","Legacy state changed during migration.");await yF(n)}function gz(e,t){let n;try{if(e.trimStart().startsWith("{"))n=JSON.parse(e);else{let o=bd(e);if(o.format_version!==1||!Array.isArray(o.null_paths))throw Error("Invalid state format");n=o.record;for(let i of o.null_paths){if(!Array.isArray(i)||i.length===0||i.some((c)=>typeof c!=="string"||["__proto__","constructor","prototype"].includes(c)))throw Error("Invalid null path");let a=n;for(let c of i.slice(0,-1)){if(typeof a!=="object"||a===null||!Object.hasOwn(a,c))throw Error("Invalid null path");a=a[c]}let s=i.at(-1);if(typeof a!=="object"||a===null||!Object.hasOwn(a,s)||a[s]!=="")throw Error("Invalid null placeholder");a[s]=null}}}catch(o){throw new lo("state_corrupt","A persisted state file is not valid TOML.",o)}let r=Ie(t,n);if(r===void 0)throw new lo("state_corrupt","A persisted file failed schema validation.");return r}async function vt(e,t){let n=fz(e);await $c(n),await co(e);let r=`${e}.tmp-${process.pid}-${crypto.randomUUID()}`;try{await pz(r,t,{encoding:"utf8",mode:384}),await xF(r),await dz(r,e),await hz(n)}catch(o){throw await yF(r).catch(()=>{return}),o}}async function yz(e,t){let n=await hF(e);if(!n.isFile()||n.isSymbolicLink())throw new lo("state_corrupt","A persisted file is not a regular file.");let r;try{r=JSON.parse(await gF(e,"utf8"))}catch(i){throw new lo("state_corrupt","A persisted file is not valid JSON.",i)}let o=Ie(t,r);if(o===void 0)throw new lo("state_corrupt","A persisted file failed schema validation.");return o}async function ye(e){try{let t=await hF(e);if(!t.isFile()||t.isSymbolicLink())throw new lo("state_corrupt","A persisted file is not a regular file.");return await gF(e,"utf8")}catch(t){if(We(t,"ENOENT"))return;throw t}}async function xz(e,t){try{return await yz(e,t)}catch(n){if(We(n,"ENOENT"))return;throw n}}function bF(e){if(typeof e==="object"&&e!==null&&"code"in e&&typeof e.code==="string")return mz.has(e.code)||process.platform==="win32"&&e.code==="EPERM";return!1}var mz,lo;var Hc=w(()=>{ht();ds();ls();mz=new Set(["EBADF","EINVAL","ENOSYS","ENOTSUP","EISDIR"]);lo=class lo extends Error{code;causeValue;constructor(e,t,n){super(t);this.name="StorageError",this.code=e,this.causeValue=n}}});import{readFile as Sz}from"fs/promises";import{dirname as bz,resolve as wz}from"path";import{fileURLToPath as _z}from"url";async function wF(e=ps){let t=JSON.parse(await Sz(e,"utf8")),n=Ie(vz,t);if(n===void 0)throw new Qo("manifest_invalid","The public package manifest is invalid.");return n}async function Bc(e=ps){let t=(await wF(e)).version,n=Ie(kc,t);if(n===void 0)throw new Qo("manifest_invalid","The public package manifest version is invalid.");return n}async function _F(e=ps){let t=await Bc(e),n=Ie(Oc,t);if(n===void 0)throw new Qo("manifest_invalid","The public package manifest must use a canonical stable release version.");return n}async function Rz(e=ps){let n=(await Bc(e)).split("-",1)[0],r=Ie(_w,n);if(r===void 0)throw new Qo("manifest_invalid","The public package manifest must use a canonical release base version.");return r}async function vd(e=ps){return await Bc(e)}async function _v(e,t,n=ps){let r=await wF(n),o=await _F(n),i=Tz(e,o);if(!t)await SF(n,{...r,version:i});return{previous:o,next:i}}function Tz(e,t){if(e!=="patch"&&e!=="minor"){if(Ie(Oc,e)===void 0)throw new Qo("version_invalid","The version target is invalid.");return e}try{return vw(e,t)}catch(n){throw new Qo("version_invalid",n instanceof Error?n.message:"The current version is invalid.")}}var vz,ps,Qo;var Rd=w(()=>{ht();Dt();ls();Hc();vz=ee((e)=>cF(e)&&e.name==="holycodex"&&Ie(kc,e.version)!==void 0),ps=wz(bz(_z(import.meta.url)),"../package.json");Qo=class Qo extends Error{code;constructor(e,t){super(t);this.name="ManifestError",this.code=e}}});import{createHash as Cz}from"crypto";import{lstat as vv,readFile as Rv,rm as jh,rmdir as Oz}from"fs/promises";import{dirname as vF,join as Mt,relative as RF}from"path";async function Bh(e,t,n=[],r="standard",o={}){let i=fs(t,r,o),a=Mt(e,"holycodex","agents",i),s=ei(t,r).map((u)=>({path:Mt(a,`${u.name}.toml`),contents:Vc(u,o)})),c=new Map(n.map((u)=>[Mt(e,u.path),u])),l=[];for(let u of s){let d=await ra(u.path),p=c.get(u.path),m=d===void 0?void 0:await PF(u,d,p);if(m!==void 0)l.push(m)}return l}async function CF(e,t){let n=Mt(e,"agents"),r=Mt(e,"holycodex","agents"),o=[];for(let i of t){let a=Mt(e,i.path);if(!rr(e,a)||!rr(n,a)&&!rr(r,a)&&a!==Mt(e,"config.toml"))continue;let s=await ra(a);if(s!==void 0&&await jn(s)!==i.digest)o.push({...AF(a,"remove",{present:!0,digest:await jn(s)},{present:!1},"The managed native artifact changed outside HolyCodex and would be removed."),action:"remove"})}return o}async function OF(e,t){let n=Mt(e,"agents"),r=Mt(e,"holycodex","agents"),o=[];for(let[i,a]of t){if(!rr(e,i)||!rr(n,i)&&!rr(r,i)){o.push(i);continue}let s=await ra(i);if(s!==void 0&&await jn(s)!==a)o.push(i)}return o}function ei(e,t="standard"){let n=oo(e);if(!n.ok)return[];return n.value.routes.map((r)=>{let o={role:r.role,task:r.task};return{name:Nw(o),description:Lw(o),taskInstruction:Fw(o),permissions:Dw(o),model:r.model,effort:r.effort,serviceTier:t==="standard"?"default":"fast"}})}function fs(e,t="standard",n={}){let r=ei(e,t).map((o)=>`${o.name}\x00${Vc(o,n)}`).join("\x00");return Cz("sha256").update(r).digest("hex").slice(0,20)}function Td(e,t){if(!/^[a-f0-9]{20}$/u.test(t))throw Error("Invalid native-agent generation identifier.");return`holycodex/agents/${t}/${e}.toml`}function Tv(e,t="standard"){let n=oo(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 Cv(e=!1){let t=typeof e==="boolean"?{computerUse:e,frontend:!0,security:!0}:e;if(!W.requiresDelegation||!W.assignmentStartAndDispatchPrecedeDelegableExecution||!W.trivialWorkRequiresDelegation||!W.preparatoryAndExploratoryWorkRequiresDelegation||W.genericDirectWorkFallback||W.directExecutionExceptions!==W.rootOwnedAuthority||!W.codeReviewRequiredForImplementation||!W.codeReviewRequiredBeforeVcs||!W.externalVerificationMustBeTerminal||!W.concreteSpecialistDispatchRequired||!W.roleFamiliesAreLabelsOnly||!W.missingConcreteRouteIsBlocker||!W.normalSpawnRequiresExplicitForkTurns||W.normalSpawnForkTurns!=="none"||!W.normalSpawnUsesConcreteRegisteredAgentType||!W.assignmentContextIsTaskSpecificOnly||!W.configuredRouteModelAndEffortPreserved||W.normalProgressMessages||W.normalHeartbeatMessages||W.normalIntermediateEvidence||!W.userUpdatesUsefulOrImportantOnly||!W.routinePerToolOrSubagentNarrationForbidden||!W.routineStatusOnlyChatterForbidden||!W.fixedCadenceUserUpdatesForbidden||!W.materialUserUpdateKinds.includes("significant_findings_or_decisions")||!W.materialUserUpdateKinds.includes("consequential_blockers_or_input_needs")||!W.materialUserUpdateKinds.includes("release_milestones")||!W.outOfBoundaryRequiresNewAssignment||!W.longestPracticalEventWait||!W.busyPollingForbidden||!W.statusOnlyCoordinationLoopsForbidden||!W.batchIndependentLifecycleActions||!W.releaseLeavesAfterAcceptedOutcome||W.routineWaitTool!=="collaboration.wait_agent"||!Number.isSafeInteger(W.routineWaitMaximumTimeoutMs)||W.routineWaitMaximumTimeoutMs<=0||!W.routineWaitUsesMaximumRuntimeTimeout||!W.earlySpecialistCompletionWakesWait||!W.collectiveMailboxIncludesRelevantAgents||!W.idleTimeoutRepeatsMaximumWait||!W.shortRoutineWaitsForbidden||!W.evidenceFirstConciseStructuredReports||W.specialistReportFields.length===0||W.rootLargeReadsOnlyFor.length===0||!W.stableFactsReused||!W.duplicatePolicyForbidden||!W.stableBoundedComponentScopesAreCanonical||!W.lifecycleWorkerOwnsDeterministicApi||W.registeredSpecialistAgentTypes!==Go||W.forbiddenGenericAgentTypes!==lh)throw Error("The Root orchestration policy is incomplete.");let n=[`You are the HolyCodex Root/session orchestrator. Never perform delegable work yourself unless the user explicitly requests direct execution or forbids delegation. Root owns ${W.rootOwnedAuthority.map((r)=>Ez[r]).join("; ")}, within authorization and capability boundaries.`,`Delegate ${W.delegableActions.filter((r)=>(r!=="browser_use"||t.browserUse)&&(r!=="computer_use"||t.computerUse)).map((r)=>Iz[r]).join("; ")} through bounded Assignments. Bundle related trivial and preparatory steps into a coherent Assignment rather than spawning per action.`,W.routeConfigurationBeforeDispatch,W.assignmentInvocationLifecycle,`For normal specialist spawns, set fork_turns: "${W.normalSpawnForkTurns}". Give each specialist a self-contained Assignment with objective, bounded scope, constraints, dependencies, acceptance criteria, and evidence needed for acceptance.`,`Dispatch each Assignment to its exact concrete registered Role.task agent_type. Registered targets: ${W.registeredSpecialistAgentTypes.join(", ")}. Explorer, Librarian, Worker, and Reviewer are labels only; generic built-in agent_type values ${W.forbiddenGenericAgentTypes.join(", ")} are forbidden.`,W.semanticStateBoundary,"User instructions take precedence over skill guidelines. Treat later user steering as current when it changes scope, ownership, or delegation; do not carry forward earlier conflicting constraints. Infer intent from the request and session; carry authorized work through its requested terminal state. Routine omissions get safe defaults. For a blocking material user decision, Root alone uses grill-me, which must ask through request_user_input; ask only what remains unresolved, never turn clarification into planning. Specialists return material input needs to Root as needs_root_input and never ask the user. Dispatch immediately when no decision blocks the next step, and continue independent work while an answer is pending. Check existing authorization before asking again; prepare the concrete reviewable result before requesting approval for a consequential effect. Credential entry remains user-owned.","Dispatch independent non-conflicting Assignments concurrently as soon as their inputs are ready, including across workflow phases. Give each overlapping write or shared-mutable seam one specialist owner and send follow-ups to that owner instead of spawning competing writers; start dependent review or validation once its source is stable. Reuse accepted findings instead of repeating discovery. Batch independent tool reads and lifecycle work where supported; keep revisions and dependent writes ordered. Resolve material contradictions before acceptance.","For visual tasks, Root uses visual-loop: Worker.visual implementation, Reviewer.visual independent review, then Root independent visual pass; use dev-server when a shared background server is needed. Honor active-surface tool precedence. Report a capability blocker without inventing a provider or widening authority.",kF(t),Fn.designJudgment,"Use writing-instructions for model-facing contracts. Keep each meaning with one authoritative owner and add only the missing semantic delta for the receiver.","Give the user useful updates for significant findings, decisions, blockers, input needs, and release milestones; avoid per-tool, status-only, heartbeat, or fixed-cadence messages.",Pz,`${Zu.rule} ${Az}`,"After integration, Root owns approved VCS writes. For PR or release gates use babysit-ci and dispatch Worker.operations for exact-ref terminal evidence. Pending gates are not complete."];if(t.frontend??!0)n.push(Mz());if(t.security??!0)n.push("For security-sensitive changes, use the relevant security review skills before VCS. Validate supported findings; repair introduced or worsened vulnerabilities before VCS unless explicitly risk-accepted. Keep security review current after relevant repairs.");return n.join(`
38
- `)}function kF(e,t="Root"){let n=e.browserUse?`Inspect and interact with rendered visual work using Browser Use / the in-app browser (IAB). ${e.computerUse?"Use Computer Use when Browser Use cannot perform the required interaction. ":""}Use other available rendered evidence for remaining inspection gaps.`:e.computerUse?"Inspect and interact with rendered visual work using Computer Use, then other available rendered evidence for remaining inspection gaps.":"Inspect rendered visual work using other available rendered evidence such as screenshots or image tools.",r=e.browserUse?`For web-visualize, open and inspect the standalone temporary HTML with Browser Use / IAB.${e.computerUse?" Use Computer Use for HTML interactions Browser Use cannot perform.":""}`:e.computerUse?"For web-visualize, open and inspect the standalone temporary HTML with Computer Use.":"For web-visualize, give the standalone temporary HTML file to the user.";return`For ${t==="Root"?"Root visual judgment":"visual implementation and review"}, ${n} ${r} Honor higher-priority active-surface tool rules.`}function Mz(){if(!Fn.repositoryAndUserRequirementsPrecedePluginDefaults||!Fn.specialistsOwnImplementationAndInteractionProof||Fn.specialistVisualImplementationInstruction.length===0||!Fn.rootOwnsVisualJudgment||!Fn.rootOwnsSharedDevServer||!Fn.rootAcceptsTerminalVisualEvidence||!Fn.sourceChangesInvalidateRenderEvidence||!Fn.specialistReportsIncludeObservableRenderedEvidence||Fn.logicOnlyChangesRequireVisualAcceptance)throw Error("The Frontend workflow policy is incomplete.");return`${EF()} Follow the repository stack, design system, and user requirements. ${Fn.specialistVisualImplementationInstruction} Refresh affected visual evidence after relevant changes. Logic-only changes do not require a visual loop. Check responsive layout, accessibility, and interactions in proportion to the change.`}function EF(){return`Use Build Web Apps for applicable web-app construction and Frontend App Builder for applicable frontend work. For frontend work, ${Wo.frontend.applicability.map(({skillId:t,appliesWhen:n})=>`${n} uses ${t}`).join("; ")}.`}async function Ov(e,t,n=[],r="standard",o,i=[],a={}){let s=fs(t,r,a),c=Mt(e,"holycodex","agents",s),l=[],u=[],d=ei(t,r).map((v)=>({path:Mt(c,`${v.name}.toml`),contents:Vc(v,a)})),p=new Map(n.map((v)=>[Mt(e,v.path),v])),m=new Map,f=new Set,y=new Set,g=new Map;for(let v of d){let C=await ra(v.path);m.set(v.path,C);let M=i.find((O)=>O.path===v.path&&O.action==="replace"&&O.key===void 0);if(M!==void 0){let O=TF(M);if(O===void 0||C===void 0||await jn(C)!==O)throw Error(`The native role conflict changed after review; review the latest file and retry: ${v.path}`);if(g.set(v.path,O),M.decision==="keep")y.add(v.path);else f.add(v.path)}let N=p.get(v.path);if(C!==void 0&&M===void 0){let O=await PF(v,C,N);if(O!==void 0){let k=await o?.(O);if(k==="cancel")throw Error(`Native-agent conflict resolution was cancelled: ${v.path}`);if(k===void 0)y.add(v.path);else{let I=TF(O),S=await ra(v.path);if(I===void 0||S===void 0||await jn(S)!==I)throw Error(`The native role conflict changed after review; review the latest file and retry: ${v.path}`);if(g.set(v.path,I),k==="accept")f.add(v.path);else y.add(v.path)}}}}let x=[];try{for(let N of d){let O=m.get(N.path),k=p.get(N.path),I=g.get(N.path);if(I!==void 0){let S=await ra(N.path);if(S===void 0||await jn(S)!==I)throw Error(`The native role conflict changed after review; review the latest file and retry: ${N.path}`)}if(y.has(N.path)){if(l.push(N.path),k!==void 0)x.push(k);continue}if(O!==void 0&&k!==void 0){if(await jn(O)!==k.digest&&O!==N.contents&&!f.has(N.path)){l.push(N.path),x.push({path:RF(e,N.path).replaceAll("\\","/"),digest:k.digest});continue}}if(O===void 0||O!==N.contents)await vt(N.path,N.contents),u.push({path:N.path,previous:O,installedDigest:await jn(N.contents)});x.push({path:RF(e,N.path).replaceAll("\\","/"),digest:await jn(N.contents)})}let v=Mt(e,"agents","root.toml"),C=await ra(v),M=await IF(v);if(M==="preserved")l.push(v);if(M==="removed"&&C!==void 0)u.push({path:v,previous:C,installedDigest:void 0});for(let N of n){let O=Mt(e,N.path);if(!d.some((k)=>k.path===O))x.push(N)}return{managed_artifacts:x,preserved:l,rollback:u}}catch(v){throw await Vh(u).catch(()=>{return}),v}}async function Vh(e){let t=[],n=[];for(let r of[...e].reverse()){let o=await ra(r.path);if(!(r.installedDigest===void 0?o===void 0:o!==void 0&&await jn(o)===r.installedDigest)){n.push(r.path);continue}if(r.previous===void 0)await jh(r.path,{force:!1}).catch((a)=>{if(!We(a,"ENOENT"))throw a}),t.push(r.path);else await vt(r.path,r.previous)}return{removed:t,preserved:n}}async function Wh(e,t,n=new Map){let r=[],o=[],i=Mt(e,"agents"),a=Mt(e,"holycodex","agents");for(let u of t){let d=Mt(e,u.path);if(!rr(e,d)||!rr(i,d)&&!rr(a,d)&&d!==Mt(e,"config.toml")){o.push(d);continue}try{await co(d);let p=await vv(d);if(p.isSymbolicLink()||!p.isFile()){o.push(d);continue}let m=await Rv(d),f=await jn(m);if(f!==u.digest){let y=n.get(d);if(y!==void 0&&f===y){await jh(d,{force:!1}),r.push(d);continue}o.push(d);continue}await jh(d,{force:!1}),r.push(d)}catch(p){if(!We(p,"ENOENT"))o.push(d)}}let s=Mt(e,"agents","root.toml"),c=await IF(s);if(c==="removed")r.push(s);if(c==="preserved")o.push(s);let l=r.slice();for(let u of l){let d=vF(u);while(d!==a&&rr(a,d)){try{await co(d),await Oz(d),r.push(d)}catch(p){if(!We(p,"ENOENT"))break}d=vF(d)}}return{removed:r,preserved:o}}function Vc(e,t={}){let n=[kz,e.taskInstruction,...e.name==="Worker.visual"||e.name==="Reviewer.visual"?[kF(t,"specialist"),...t.frontend??!0?[EF()]:[]]:[],...e.permissions.sourceMutation?[`Patch quality: ${sh}`]:[],...t.browserUse?["Use Browser Use only for this Assignment, following active-surface tool rules. Return tool failures that prevent required evidence as a blocker. Tool availability does not grant authority, and consequential external effects remain Root-owned."]:[],...t.computerUse?["Use Computer Use only for this Assignment, following active-surface tool rules and platform restrictions. External actions require explicit task authority. Return tool failures that prevent required evidence as a blocker. Tool availability does not grant authority. Credential entry and submission remain user-owned; never request, enter, retrieve, expose, or store credentials."]:[]].join(`
39
- `);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(Hh(e))}`,'approval_policy = "never"','web_search = "live"',`developer_instructions = ${JSON.stringify(n)}`,"","[agents]","enabled = false","interrupt_message = false","","[features]","multi_agent = false","multi_agent_v2 = false","agent_message_board = false","[features.context_management]","experimental_mode = true","",...Hh(e)==="workspace-write"?["[sandbox_workspace_write]","network_access = true"]:[],""].join(`
40
- `)}function Hh(e){return e.permissions.filesystem}function zh(e,t){return t.sandbox_mode===Hh(e)&&t.default_permissions===void 0&&(Hh(e)==="workspace-write"?fe(t,"sandbox_workspace_write.network_access")===!0:fe(t,"sandbox_workspace_write.network_access")===void 0)}function Nz(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(`
41
- `)}function Wc(e){return Fz.has(e)}async function IF(e){try{await co(e);let t=await vv(e);if(!t.isFile()||t.isSymbolicLink())return"preserved";let n=await Rv(e,"utf8");if(!Wc(n))return"preserved";return await jh(e,{force:!1}),"removed"}catch(t){if(We(t,"ENOENT"))return"absent";throw t}}async function ra(e){try{await co(e);let t=await vv(e);if(t.isSymbolicLink()||!t.isFile())throw Error(`Invalid managed path: ${e}`);return new TextDecoder("utf-8",{fatal:!0}).decode(await Rv(e))}catch(t){if(We(t,"ENOENT"))return;throw t}}async function jn(e){let t=typeof e==="string"?new TextEncoder().encode(e):e,n=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(n),(r)=>r.toString(16).padStart(2,"0")).join("")}function AF(e,t,n,r,o){return{identity:`role-asset:${e}:${t}`,category:"role-asset",target:e,existing:n,desired:r,defaultDecision:"replace",validDecisions:["keep","replace","cancel"],explanation:o,path:e,action:t}}async function PF(e,t,n){if(t===e.contents)return;let r=await jn(t);if(n!==void 0&&r===n.digest)return;return{...AF(e.path,"replace",{present:!0,digest:r},{present:!0,digest:await jn(e.contents)},n===void 0?"A pre-existing generated native role file is not recorded as managed by this installation.":"The managed native role file changed outside the previous HolyCodex transaction."),validDecisions:["replace","cancel"]}}function TF(e){if(typeof e.existing!=="object"||e.existing===null)return;let t=e.existing.digest;return typeof t==="string"?t:void 0}var kz,Ez,Iz,Az="Before acceptance or VCS writes, require a Reviewer.code fixed point and current relevant validation. Review and validation may overlap on non-conflicting scopes; serialize repairs against checks of the same source. Reuse worker proof and assign Worker.validation only for independent proof or an evidence gap. Repairs invalidate only affected evidence.",Pz,Fz;var Kh=w(()=>{cs();ht();ds();Hc();kz=[`Execute the bounded Assignment through its acceptance criteria; make routine in-scope choices without asking. ${Zu.rule} Return material decisions, scope expansion, or required user input to Root; never ask the user. Do not message Root or peers during execution, delegate, change Intent lifecycle, or perform external effects. Read-only Git/VCS, CI, and PR-comment inspection is allowed when relevant and within the Assignment; Git/VCS writes remain Root-only. Source mutation requires permission from the concrete task; proof and cache writes do not grant it. Preserve others' work in the shared tree and adapt to their changes. Root owns the shared background dev server and final visual acceptance. Do not run dev-server or visual-loop.`,"Do not recover an Assignment or mutate another Assignment's lifecycle. Root keeps active invocation capabilities and records terminal results; never request or use those capabilities.",`Return only one compact, evidence-first terminal outcome (${W.specialistOutcomes.map((e)=>`\`${e}\``).join(", ")}) with ${W.specialistReportFields.join(", ")}.`].join(" "),Ez={user_interaction:"user interaction",intent:"Intent",material_decisions:"material decisions",orchestration_lifecycle:"orchestration and lifecycle",integration_acceptance:"integration acceptance",completion:"completion",git_vcs:"Git/VCS writes",external_effects:"external effects",visual_judgment:"visual judgment and its browser inspection",dev_server:"the shared background dev server"},Iz={repository_discovery:"repository discovery",file_source_test_doc_inspection:"file, source, test, and documentation inspection",fact_finding:"fact finding",research:"research",implementation:"implementation",debugging:"debugging",testing:"testing",validation:"validation",frontend_work:"frontend work",security_work:"security work",browser_use:"authorized Browser Use",computer_use:"authorized Computer Use",review:"review",ci_release_observation:"CI or release observation"},Pz=`After dispatching useful independent work, wait collectively for specialist results with ${W.routineWaitTool} at timeout_ms=${W.routineWaitMaximumTimeoutMs}, subject to mandatory active tool/runtime limits. Do not create unnecessary work to avoid waiting, busy-poll, or repeatedly use short waits when a longer event wait is appropriate. A long-running specialist is not stalled merely because others finished; inspect only bounded evidence when a material stall or failure is plausible, then repair, restart, or redispatch only the necessary scope. Batch specialist completion updates rather than reporting each completion separately. Continue useful independent work or wait again while live dependencies remain. Release specialist leaves after accepting terminal outcomes.`;Fz=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)=>Nz(e,t,n))))});import{access as Lz,readFile as Dz,readdir as qz}from"fs/promises";import{join as kv}from"path";class ti{adapter;observedIdentities={};constructor(e){if("run"in e){let t=Th({executable:"codex",runner:e});this.adapter=t}else this.adapter=e}static async discover(e=process.env){let t=await ov({environment:e}),n=Th({executable:t.path,environment:D_(e),onMarketplaceConflict:(r)=>{console.warn(`HolyCodex warning: ${r}`)},...e.CODEX_HOME===void 0?{}:{codexHome:e.CODEX_HOME}});return new ti(n)}async list(){try{return await this.adapter.list()}catch(e){throw Cd("list",e)}}async add(e){try{await this.adapter.add(e)}catch(t){throw Cd("add",t,e)}}async ensureOfficialMarketplace(e){if(this.adapter.ensureOfficialMarketplace===void 0)return;try{await this.adapter.ensureOfficialMarketplace(e)}catch(t){throw Cd("bootstrap",t)}}async remove(e){try{await this.adapter.remove(e)}catch(t){throw Cd("remove",t,e)}}async addMarketplace(e){try{await this.adapter.addMarketplace(e)}catch(t){throw Cd("add",t,e)}}async status(e){let t=await this.list(),n={},r=new Map;for(let i of[...t.installed,...t.available])if(!r.has(i.pluginId)||i.installed)r.set(i.pluginId,i);let o=Object.fromEntries(await Promise.all(e.map(async(i)=>{let a=ao(t,i),s=Qn(i),c=r.get(i),l=a?.entry??(s===void 0||c?.marketplaceName==null?c:void 0),u=a;if(l!==void 0)n[i]=u?.entry.pluginId??l.pluginId;let d=l===void 0?"missing":l.installed&&l.enabled?"installed":l.installed?"disabled":"missing";return[i,d]})));return this.observedIdentities=Object.freeze(n),o}getObservedIdentities(){return this.observedIdentities}}class Jh{codexHome;observedIdentities={};constructor(e){this.codexHome=e}async status(e){let t;try{t=await Dz(kv(this.codexHome,"config.toml"),"utf8")}catch(c){if(Ev(c))return this.observedIdentities=Object.freeze({}),Object.fromEntries(e.map((l)=>[l,"missing"]));throw c}let n=globalThis.Bun;if(!n?.TOML?.parse)throw Error("A TOML parser is unavailable.");let r=Ie(os,n.TOML.parse(t));if(r===void 0)throw Error("Codex configuration is invalid.");let o=r.plugins,i=typeof o==="object"&&o!==null&&!Array.isArray(o)?o:void 0,a={},s=Object.fromEntries(await Promise.all(e.map(async(c)=>{let l=Ic(c),d=(l.length>0?l:[c]).flatMap((g)=>{if(i===void 0||!Object.hasOwn(i,g))return[];let x=i?.[g],v=typeof x==="object"&&x!==null&&!Array.isArray(x)?x.enabled:void 0;return[{id:g,enabled:v}]});if(d.length===0)return[c,"missing"];let p=d.filter((g)=>g.enabled===!0),f=(await Promise.all(p.map(async(g)=>{let x=Ic(g.id),v=[g.id,...x.filter((C)=>C!==g.id)];return{...g,cachedIdentity:await Uz(this.codexHome,v)}}))).find((g)=>g.cachedIdentity!==void 0),y=f?.cachedIdentity??p[0]?.id??d[0]?.id;if(y!==void 0)a[c]=y;if(f!==void 0)return[c,"installed"];if(p.length>0)return[c,"missing"];if(d.every((g)=>g.enabled===!1))return[c,"disabled"];return[c,"unknown"]})));return this.observedIdentities=Object.freeze(a),s}getObservedIdentities(){return this.observedIdentities}}async function Uz(e,t){for(let n of t){let r=n.lastIndexOf("@");if(r<=0||r===n.length-1)continue;let o=kv(e,"plugins","cache",n.slice(r+1),n.slice(0,r));try{let i=await qz(o,{withFileTypes:!0,encoding:"utf8"});for(let a of i){if(!a.isDirectory())continue;try{return await Lz(kv(o,a.name,".codex-plugin","plugin.json")),n}catch(s){if(!Ev(s))throw s}}}catch(i){if(Ev(i))continue;throw i}}return}function Ev(e){return typeof e==="object"&&e!==null&&"code"in e&&e.code==="ENOENT"}function Cd(e,t,n){if(t instanceof uo)return t;let o=(t instanceof he?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 uo(i,a,t,n===void 0?{}:{plugin_id:n})}var uo;var Od=w(()=>{cs();ht();ls();uo=class uo extends Error{code;causeValue;details;constructor(e,t,n,r={}){super(t);this.name="OfficialPluginManagerError",this.code=e,this.causeValue=n,this.details=r}}});import{execFile as $z}from"child_process";import{access as jz,readFile as Hz,realpath as Bz}from"fs/promises";import{posix as Vz,win32 as Wz}from"path";import{promisify as zz}from"util";function ys(e=process.env){return{platform:process.platform,environment:e,processPath:process.execPath,files:Kc,run:async(t,n)=>{try{let r=await Kz(t,[...n],{encoding:"utf8",windowsHide:!0,env:{...process.env,...e},timeout:120000,maxBuffer:4194304});return{exitCode:0,stdout:r.stdout,stderr:r.stderr}}catch(r){let o=r;return{exitCode:typeof o.code==="number"?o.code:1,stdout:typeof o.stdout==="string"?o.stdout:"",stderr:typeof o.stderr==="string"?o.stderr:r instanceof Error?r.message:"process failed"}}}}}function hs(e){let t=ir(e.npm_execpath??""),n=(e.npm_command??"").toLowerCase(),r=(e.npm_config_user_agent??"").toLowerCase();if(t.includes("yarn")||t.includes("corepack")||r.startsWith("yarn/"))return;if(kd(t,"pnpm")&&n==="dlx")return{launcher:"pnpm dlx",family:"pnpm",executable:"pnpm"};if(kd(t,"bunx")||kd(t,"bun")&&n==="exec")return{launcher:"bunx",family:"bun",executable:"bun"};if(kd(t,"npx")||t.endsWith("/npx-cli.js")||kd(t,"npm")&&n==="exec"||t.endsWith("/npm-cli.js")&&n==="exec")return{launcher:"npx",family:"npm",executable:"npm"};return}async function Gh(e,t,n){let r=await Av(e);if(r!==void 0){let o=hs(e.environment)??{launcher:"bunx",family:"bun",executable:"bun"},i=n?.ownership==="holycodex"&&typeof n.identity==="string"&&await Jc(e,n.executable,r.executable);return{manager:o.family,launcher:o.launcher,version:r.version,executable:r.executable,ownership:i?"holycodex":"user",...i?{identity:n.identity}:{}}}if(zc(e))return Zz(e,t,n);return Yz(e,t,n)}async function Iv(e,t){let n=await Av(e);if(n!==void 0){let i=hs(e.environment)??{launcher:"bunx",family:"bun",executable:"bun"},a=t?.ownership==="holycodex"&&typeof t.identity==="string"&&await Jc(e,t.executable,n.executable);return{manager:i.family,launcher:i.launcher,version:n.version,executable:n.executable,ownership:a?"holycodex":"user",...a?{identity:t.identity}:{}}}let r=zc(e)?{launcher:"bunx",family:"bun",executable:"bun"}:hs(e.environment);if(r===void 0)throw new be("context7_manager_unknown","No usable PATH Context7 executable or supported package manager is available.");let o=r.family==="bun"&&zc(e)?await Ed(e):await Id(e,r);if(o===void 0)throw new be("context7_unavailable","No usable managed Context7 executable is available.");return{manager:r.family,launcher:r.launcher,version:o.version,executable:o.executable,ownership:Pv(t,r,o),identity:o.identity}}async function Av(e){let t=await FF(e.environment,e.platform,e.files??Kc);if(t===void 0)return;let n=await e.run(t,["--version"]),r=n.exitCode===0?gs(n.stdout):void 0;return r===void 0?void 0:{version:r,executable:t}}async function Jz(e){if(await Av(e)!==void 0)return;if(zc(e)){await Gz(e);return}let t=hs(e.environment);if(t===void 0)throw new be("context7_manager_unknown","HolyCodex must be launched with bunx, npx, or pnpm dlx so Context7 can use the same package manager.");let n=await e.run(t.executable,t.family==="npm"?["prefix","--global"]:t.family==="pnpm"?["bin","--global"]:["pm","bin","-g"]);if(n.exitCode!==0||n.stdout.trim().length===0)throw new be("context7_unavailable",`The ${t.family} global installation could not be inspected before managed changes.`,{stderr:n.stderr.slice(0,512)})}async function Gz(e){let t=e.files??Kc,n=await e.run(e.processPath,["pm","bin","-g"]);if(n.exitCode!==0||n.stdout.trim().length===0){if(oK(n.stderr))return;throw new be("context7_unavailable","Bun's managed global installation could not be located before managed changes.",{stderr:n.stderr.slice(0,512)})}let r=cn(e.platform),o=n.stdout.trim(),i=r.join(r.dirname(o),"install","global"),a=r.join(i,"node_modules","ctx7"),s=r.join(a,"package.json"),c=r.join(o,e.platform==="win32"?"ctx7.exe":"ctx7");try{await t.access(o),await t.access(i)}catch(g){throw new be("context7_unavailable","Bun's managed global location or project is unavailable before managed changes.",{reason:ms(g)})}let l;try{await t.access(a)}catch(g){if(rK(g))return;throw new be("context7_unavailable","Bun's managed ctx7 package could not be inspected before managed changes.",{reason:ms(g)})}try{l=await t.readText(s)}catch(g){throw new be("context7_unavailable","Bun's managed ctx7 package metadata could not be inspected before managed changes.",{reason:ms(g)})}let u;try{u=JSON.parse(l)}catch(g){throw new be("context7_unavailable","Bun's managed ctx7 package metadata is invalid before managed changes.",{reason:ms(g)})}if(typeof u.version!=="string"||gs(u.version)!==u.version)throw new be("context7_unavailable","Bun's managed ctx7 package has no exact semver version before managed changes.");let d=LF(u);if(d===void 0)throw new be("context7_unavailable","Bun's managed ctx7 package does not declare its executable before managed changes.");let p=r.resolve(a,d),m,f;try{await t.access(p),m=await t.realpath(a),f=await t.realpath(p)}catch(g){throw new be("context7_unavailable","Bun's managed ctx7 executable is unavailable before managed changes.",{reason:ms(g)})}if(!Ad(m,a,e.platform)||!ir(f).startsWith(`${ir(m)}/`))throw new be("context7_unavailable","Bun's managed ctx7 executable is outside its package before managed changes.");try{await t.access(c),await t.realpath(c)}catch(g){throw new be("context7_unavailable","Bun's managed ctx7 shim is unavailable before managed changes.",{reason:ms(g)})}let y=await e.run(c,["--version"]);if(y.exitCode!==0||gs(y.stdout)!==u.version)throw new be("context7_unavailable","Bun's managed ctx7 shim does not report the package version before managed changes.",{stderr:y.stderr.slice(0,512)})}async function Yz(e,t,n){let r=hs(e.environment);if(r===void 0)throw new be("context7_manager_unknown","HolyCodex must be launched with bunx, npx, or pnpm dlx so Context7 can use the same package manager.");let o=await Id(e,r),i=await DF(e,r);if(i===void 0)throw new be("context7_verification_failed",`${r.family} could not resolve the latest ctx7 version.`);let a=Pv(n,r,o);if(t&&o?.version!==i&&a==="holycodex"){let l=r.family==="bun"?{executable:"bun",args:Yh(e,"add",or)}:MF(r.family),u=await e.run(l.executable,l.args);if(u.exitCode!==0)throw new be("context7_install_failed",`${r.family} could not install ${or}.`,{stderr:u.stderr.slice(0,512)})}else if(!t&&o===void 0)throw new be("context7_unavailable",`${or} is not owned by the ${r.family} global installation.`);let s=await Id(e,r);if(s===void 0)throw new be("context7_verification_failed",`${or} could not be verified in the ${r.family} global installation.`);if(s.version!==i)throw new be("context7_outdated",`The ${r.family} global ctx7 is ${s.version}; ${i} is required.`,{installed:s.version,latest:i});return{manager:r.family,launcher:r.launcher,version:s.version,executable:s.executable,ownership:a,identity:s.identity}}async function Zz(e,t,n){let r={launcher:"bunx",family:"bun",executable:"bun"},o=await Ed(e),i=await DF(e,r);if(i===void 0)throw new be("context7_verification_failed","Bun could not resolve the latest ctx7 version.");let a=Pv(n,r,o);if(t&&o?.version!==i&&a==="holycodex"){let l=await e.run(e.processPath,Yh(e,"add",or));if(l.exitCode!==0)throw new be("context7_install_failed",`Bun could not install ${or} in its global installation.`,{stderr:l.stderr.slice(0,512)})}else if(o===void 0)throw new be("context7_unavailable",`${or} is not present in Bun's exact global installation.`);let s=await Ed(e);if(s===void 0)throw new be("context7_verification_failed",`${or} could not be verified in Bun's exact global installation.`);if(s.version!==i)throw new be("context7_outdated",`Bun's global ctx7 is ${s.version}; ${i} is required.`,{installed:s.version,latest:i});return{manager:"bun",launcher:"bunx",version:s.version,executable:s.executable,ownership:a,identity:s.identity}}async function Ed(e){let t=e.files??Kc,n=await e.run(e.processPath,["pm","bin","-g"]);if(n.exitCode!==0)return;let r=n.stdout.trim();if(r.length===0)return;let o=cn(e.platform),i=o.join(o.dirname(r),"install","global","node_modules","ctx7"),a;try{a=JSON.parse(await t.readText(o.join(i,"package.json")))}catch{return}if(typeof a.version!=="string"||gs(a.version)!==a.version)return;let s=LF(a);if(s===void 0)return;let c=o.resolve(i,s),l=o.join(r,e.platform==="win32"?"ctx7.exe":"ctx7"),u,d,p;try{await t.access(i),await t.access(c),await t.access(l),u=await t.realpath(i),d=await t.realpath(c),p=await t.realpath(l)}catch{return}if(!Ad(u,i,e.platform)||!ir(d).startsWith(`${ir(u)}/`))return;let m=await e.run(l,["--version"]);if(m.exitCode!==0||gs(m.stdout)!==a.version)return;return{version:a.version,executable:l,identity:await NF({launcher:"bunx",family:"bun",executable:"bun"},u,d,p,a)}}function zc(e){let t=cn(e.platform).basename(e.processPath).toLowerCase();return t==="bun"||t==="bun.exe"}function Pv(e,t,n){if(n===void 0)return"holycodex";if(e?.ownership!=="holycodex")return"user";if(e.manager!==t.family)return"user";let r=e.identity;if(!Mv(r)||r!==n.identity)return"user";return"holycodex"}async function Pd(e,t){if(zc(e))return Xz(e,t);return Qz(e,t)}async function Xz(e,t){if(t?.ownership!=="holycodex"||t.manager!=="bun")return!1;let n;try{n=await Ed(e)}catch{return!1}if(n===void 0||n.version!==t.version||!await Jc(e,n.executable,t.executable)||!Mv(t.identity)||n.identity!==t.identity)return!1;let r=await e.run(e.processPath,Yh(e,"remove","ctx7"));if(r.exitCode!==0)throw new be("context7_remove_failed","Bun could not remove ctx7.",{stderr:r.stderr.slice(0,512)});if(await Ed(e)!==void 0)throw new be("context7_remove_failed","Bun reported success, but the recorded ctx7 installation is still present.");return!0}async function Qz(e,t){if(t?.ownership!=="holycodex")return!1;let n=hs(e.environment);if(n===void 0||n.family!==t.manager)return!1;let r;try{r=await Id(e,n)}catch(a){if(a instanceof be&&a.code==="context7_shadowed")return!1;throw a}if(r===void 0||r.version!==t.version||!await Jc(e,r.executable,t.executable)||!Mv(t.identity)||r.identity!==t.identity)return!1;let o=n.family==="bun"?{executable:"bun",args:Yh(e,"remove","ctx7")}:eK(n.family),i=await e.run(o.executable,o.args);if(i.exitCode!==0)throw new be("context7_remove_failed",`${n.family} could not remove ctx7.`,{stderr:i.stderr.slice(0,512)});try{if(await Id(e,n)!==void 0)throw new be("context7_remove_failed",`${n.family} reported success, but the recorded ctx7 installation is still present.`)}catch(a){if(a instanceof be&&a.code==="context7_remove_failed")throw a;throw new be("context7_remove_failed",`${n.family} removed ctx7, but its final state could not be verified.`)}return!0}function MF(e){switch(e){case"bun":return{executable:"bun",args:["add","--global",or]};case"npm":return{executable:"npm",args:["install","--global",or]};case"pnpm":return{executable:"pnpm",args:["add","--global",or]}}}function Yh(e,t,n){let r=cn(e.platform),o=r.dirname(e.processPath),i=r.isAbsolute(o)?o:e.platform==="win32"?"C:\\":"/";return[t,"--global",`--cwd=${i}`,n]}function eK(e){switch(e){case"bun":return{executable:"bun",args:["remove","--global","ctx7"]};case"npm":return{executable:"npm",args:["uninstall","--global","ctx7"]};case"pnpm":return{executable:"pnpm",args:["remove","--global","ctx7"]}}}async function Id(e,t){let n=e.files??Kc,r=await e.run(t.executable,t.family==="npm"?["prefix","--global"]:t.family==="pnpm"?["bin","--global"]:["pm","bin","-g"]);if(r.exitCode!==0)return;let o=r.stdout.trim();if(o.length===0)return;let i=t.family==="npm"?cn(e.platform).join(o,"node_modules","ctx7"):t.family==="pnpm"?await iK(e,t):cn(e.platform).join(cn(e.platform).dirname(o),"install","global","node_modules","ctx7");if(i===void 0)return;let a;try{a=JSON.parse(await n.readText(cn(e.platform).join(i,"package.json")))}catch{return}if(typeof a.version!=="string")return;let s=typeof a.bin==="string"?a.bin:Nv(a.bin)&&typeof a.bin.ctx7==="string"?a.bin.ctx7:void 0;if(s===void 0)return;let c=cn(e.platform).resolve(i,s),l,u;try{if(await n.access(c),l=await n.realpath(i),u=await n.realpath(c),!ir(u).startsWith(`${ir(l)}/`))return}catch{return}let d=tK(o,t.family,e.platform),p;try{await n.access(d),p=await n.realpath(d)}catch{return}let m=await FF(e.environment,e.platform,n);if(m!==void 0&&!Ad(await nK(n,m),p,e.platform))throw new be("context7_shadowed","A different ctx7 executable shadows the managed global installation.",{resolved:m,expected:d});let f=await e.run(d,["--version"]);if(f.exitCode!==0||gs(f.stdout)!==a.version)return;return{version:a.version,executable:d,identity:await NF(t,l,u,p,a)}}async function NF(e,t,n,r,o){return await qn("context7-installation",[Dn({manager:e.family,package_root:ir(t),package_executable:ir(n),shim:ir(r),package:o})])}function Mv(e){return e!==void 0&&/^[0-9a-f]{64}$/u.test(e)}async function FF(e,t,n){let r=e.PATH;if(r===void 0)return;let o=t==="win32"?(e.PATHEXT??".COM;.EXE;.BAT;.CMD").split(";").filter((i)=>i.length>0).map((i)=>`ctx7${i.toLowerCase()}`):["ctx7"];for(let i of r.split(t==="win32"?";":":")){if(i.length===0)continue;for(let a of o){let s=cn(t).join(i,a);try{return await n.access(s),s}catch{}}}return}function tK(e,t,n){if(n==="win32")return cn(n).join(e,t==="bun"?"ctx7.exe":"ctx7.cmd");return t==="npm"?cn(n).join(e,"bin","ctx7"):cn(n).join(e,"ctx7")}async function nK(e,t){try{return await e.realpath(t)}catch{return t}}function gs(e){return e.match(/\b(\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?)\b/u)?.[1]}function LF(e){return typeof e.bin==="string"?e.bin:Nv(e.bin)&&typeof e.bin.ctx7==="string"?e.bin.ctx7:void 0}function ms(e){if(e instanceof Error)return e.message.slice(0,512);if(typeof e==="string")return e.slice(0,512);return"unknown error"}function rK(e){return Nv(e)&&e.code==="ENOENT"||/\b(?:e?noent|not found|does not exist|missing)\b/iu.test(ms(e))}function oK(e){return/(?:no package\.json(?: was)? found|couldn['\u2019]?t find (?:a )?package\.json|could not find (?:a )?package\.json|package\.json (?:is )?missing)/iu.test(e)}async function iK(e,t){let n=await e.run(t.executable,["root","--global"]),r=n.stdout.trim();return n.exitCode===0&&r.length>0?cn(e.platform).join(r,"ctx7"):void 0}async function DF(e,t){let n=await e.run(t.family==="bun"&&zc(e)?e.processPath:t.executable,t.family==="bun"?["pm","view","ctx7","version"]:["view","ctx7","version"]);if(n.exitCode!==0)return;return gs(n.stdout)}function kd(e,t){return[t,`${t}.exe`,`${t}.cmd`,`${t}.js`,`${t}.cjs`].some((n)=>e.endsWith(`/${n}`))}function Ad(e,t,n){let r=cn(n),o=r.resolve(e),i=r.resolve(t);return n==="win32"?ir(o)===ir(i):o===i}async function Jc(e,t,n){if(Ad(t,n,e.platform))return!0;let r=e.files??Kc;try{let[o,i]=await Promise.all([r.realpath(t),r.realpath(n)]);return Ad(o,i,e.platform)}catch{return!1}}function cn(e){return e==="win32"?Wz:Vz}function ir(e){return e.replaceAll("\\","/").toLowerCase().replace(/\/$/u,"")}function Nv(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}var or="ctx7@latest",Kz,Kc,be;var Zh=w(()=>{ht();Kz=zz($z),Kc={access:jz,readText:(e)=>Hz(e,"utf8"),realpath:Bz};be=class be extends Error{code;details;constructor(e,t,n={}){super(t);this.code=e;this.details=n;this.name="ToolingError"}}});import{rm as Qh,rmdir as Dv}from"fs/promises";import{join as aK}from"path";async function Uv(e={},t=process.env){let n=Pr(e,t),r={};try{await us(n.codexHome),await us(n.stateRoot),r.paths=Gc({state_root:n.stateRoot})}catch(u){r.paths=Kt(["path_symlink"],{error:ar(u)})}let o=await oa(n).catch((u)=>{r.configuration=Kt(["state_corrupt"],{error:ar(u)});return}),[i,a]=await Promise.all([Nr(n.preparingRecord,o).catch((u)=>{r.transaction=Kt(["state_corrupt"],{path:n.preparingRecord,error:ar(u)});return}),Nr(n.conflictedRecord,o).catch((u)=>{r.transaction=Kt(["state_corrupt"],{path:n.conflictedRecord,error:ar(u)});return})]);if(r.transaction?.status!=="failed"&&(i!==void 0||a!==void 0)){let u=rg(o,i,a),d=[...new Set(u.map((p)=>{if(p.relation==="stale")return"stale_transaction_state";if(p.relation==="incompatible")return"incompatible_transaction_state";return p.status==="preparing"?"incomplete_install_state":"conflicted_state"}))];r.transaction=Kt(d,{recovery:u.map((p)=>p.recovery).join(","),transactions:u.map((p)=>`${p.status}:${p.relation}:${p.install_id}:${p.digest}`).join(","),active:o===void 0?"absent":`${o.install_id}:${o.digest}`})}if(!r.configuration)if(!o)r.configuration=Kt(["configuration_missing"]);else if(await bs(o))r.configuration=Gc({profile:o.profile,tier:o.tier,install_id:o.install_id});else r.configuration=Kt(["configuration_changed"],{path:n.activeRecord});if(o){r.runtime_config=await gK(n,o),r.native_roles=await yK(n,o.profile,o.tier,{browserUse:o.capability_state?.browser_use.status==="healthy"&&o.capability_state.browser_use.selected,computerUse:o.capability_state?.computer_use.status==="healthy"&&o.capability_state.computer_use.selected});let u=Object.entries(o.capability_state??{}).find(([d,p])=>d!=="browser_use"&&p.selected&&p.status!=="healthy");if(u)r.capabilities=Kt(["selected_capability_not_healthy"],{capability:u[0],status:u[1].status});if(o.optional_selections.browser_use)r.browser_use={status:"unsupported",reasons:["surface_managed_by_codex_desktop"],details:{selected:!0,owner:"Codex Desktop/runtime",availability:"Available only on Codex surfaces that provide Browser Use.",cli_provisioning:"HolyCodex CLI does not install, configure, or verify Browser."}}}let s=e.runtime??ys(t);try{let u=await Iv(s,o?.tooling?.context7);r.context7=Gc({manager:u.manager,version:u.version,executable:u.executable,ownership:u.ownership})}catch(u){r.context7={status:"warning",reasons:["context7_unavailable"],details:{error:ar(u)}}}try{let u=await ye(`${n.codexHome}/agents/root.toml`);if(u!==void 0&&Wc(u)){let d=r.native_roles;r.native_roles={status:"failed",reasons:[...d?.reasons??[],"stale_legacy_root"],details:{...d?.details,path:`${n.codexHome}/agents/root.toml`}}}}catch(u){r.native_roles=Kt(["native_role_invalid"],{error:ar(u)})}let c=e.officialPluginManager;if(o&&c?.status){let u=[...new Set([un,...Ac({browser_use:o.optional_selections.browser_use,computer_use:o.optional_selections.computer_use,sites:o.optional_selections.sites},o.official_plugins),...(o.owned_plugins??[]).filter((d)=>d!==ln)])].filter((d)=>d!==ln);try{let d=await c.status(u),p=Object.entries(d).filter(([,f])=>f!=="installed").map(([f])=>f),m=c.getObservedIdentities?.()??{};r.native_plugins=p.length===0?Gc({status:d,observed_identities:m}):Kt(["native_plugin_disagreement"],{missing:p,status:d,observed_identities:m})}catch(d){r.native_plugins=Kt(["native_plugin_status_failed"],{error:ar(d)})}}else r.native_plugins=Kt(["native_plugin_status_unavailable"],{reason:"No read-only live official plugin status source is available."});let l=Object.values(r).flatMap((u)=>u.reasons);return{healthy:Object.values(r).every((u)=>u.status!=="failed"),checks:r,reasons:[...new Set(l)]}}async function $v(e={},t=process.env){let n=Pr(e,t);await us(n.codexHome),await us(n.stateRoot);let r=await oa(n);if(r!==void 0&&!await bs(r))throw new _("state_corrupt","The HolyCodex ownership record has an invalid digest and cannot authorize removal.",void 0,{path:n.activeRecord});let[o,i]=await Promise.all([Nr(n.preparingRecord,r),Nr(n.conflictedRecord,r)]);Bv(r,o,i);let a=BF(r,o,i);if(a===void 0)return[];let s=Jt(await ye(n.configFile)),c=[];if(a.managed_config!==void 0){let l=await Ar(s,a.managed_config,{schema:a.managed_config.schema,installId:a.managed_config.installId});for(let u of[...l.preservedKeys,...l.unresolvedKeys])c.push(await Lv(n.configFile,u,s,"config-key","This managed Codex setting changed after installation."))}if(a.plugin_config!==void 0){let l=await Yc(s,a.plugin_config,{allowBeforeState:!0});for(let u of l.preserved){let d=u==="preference"?'plugins."holycodex@holycodex"':"marketplaces.holycodex";c.push(await Lv(n.configFile,d,s,"plugin-config","This HolyCodex plugin setting differs from the recorded install state."))}}if(a.provider_config!==void 0){let l=await Zc(s,eg(a.provider_config),new Set(jv(a)),{allowBeforeState:!0});for(let u of l.preserved){let d=`plugins.${JSON.stringify(u)}`;c.push(await Lv(n.configFile,d,s,"plugin-config",`The ${u} plugin setting differs from the recorded install state.`))}}return c.push(...await CF(n.codexHome,a.managed_artifacts)),[...new Map(c.map((l)=>[po(l),l])).values()]}async function Md(e={},t=process.env){let n=Pr(e,t);await us(n.codexHome),await us(n.stateRoot);let r=await oa(n);if(r&&!await bs(r))throw new _("state_corrupt","The HolyCodex ownership record has an invalid digest and cannot authorize removal.",void 0,{path:n.activeRecord});let[o,i]=await Promise.all([Nr(n.preparingRecord,r),Nr(n.conflictedRecord,r)]);Bv(r,o,i);let a=BF(r,o,i);Xh(e,{stage:"removal",status:"started",message:"Removing HolyCodex-owned state"});let s=new Set(jv(a)),c=[],l=[],u=[],d=!1,p=()=>(Xh(e,{stage:"removal",status:"completed",message:"HolyCodex removal preserved state for review"}),{removed:c,preserved:l,reasons:u});if(a===void 0)return Xh(e,{stage:"removal",status:"completed",message:"Nothing to remove"}),{removed:c,preserved:l,reasons:u};let m=await $v(e,t),f=await mK(e,m),y=await ye(n.configFile),g=Jt(y),x=m.filter((S)=>S.key!==void 0&&f.has(po(S))),v=new Map;for(let S of m){if(S.key!==void 0||!f.has(po(S)))continue;let D=jF(S);if(D!==void 0)v.set(S.path,D)}await hK(n,g,x,v);let C=a?.managed_config;if(C){let S=await Ar(g,C,{schema:C.schema,installId:C.installId});if(S.preservedKeys.length>0||S.unresolvedKeys.length>0){let P=[...S.preservedKeys,...S.unresolvedKeys].map((pe)=>({path:n.configFile,key:pe,action:"remove"}));for(let pe of P)if(f.has(po(pe)))g=tr(g,pe.key)}}if(a?.plugin_config){let S=await Yc(g,a.plugin_config,{allowBeforeState:!0});if(S.preserved.length>0){let D=S.preserved.map((P)=>({path:n.configFile,key:P==="preference"?'plugins."holycodex@holycodex"':"marketplaces.holycodex",action:"remove"}));for(let P of S.preserved){let pe=D.find((De)=>De.key===(P==="preference"?'plugins."holycodex@holycodex"':"marketplaces.holycodex"));if(pe===void 0||!f.has(po(pe)))continue;g=tr(g,P==="preference"?'plugins."holycodex@holycodex"':"marketplaces.holycodex")}}}if(a?.provider_config){let S=await Zc(g,eg(a.provider_config),s,{allowBeforeState:!0});if(S.preserved.length>0){let D=S.preserved.map((P)=>({path:n.configFile,key:`plugins."${P}"`,action:"remove"}));for(let P of S.preserved){let pe=D.find((De)=>De.key===`plugins."${P}"`);if(pe===void 0||!f.has(po(pe)))continue;g=tr(g,`plugins."${P}"`)}}}let M,N;if(s.size>0){try{M=e.officialPluginManager??await ti.discover({...t,CODEX_HOME:n.codexHome})}catch(S){throw new _("capability_denied","Native Codex plugin removal is unavailable.",S,{operation:"discover Codex",plugins:[...s].join(","),recovery:"Install or expose Codex, then retry."})}if(M===void 0||!M.remove||!M.list)throw new _("capability_denied","Native Codex plugin removal and readback are unavailable.",void 0,{operation:"prepare plugin removal",plugins:[...s].join(",")});try{N=await M.list()}catch(S){throw new _("capability_denied","Codex plugin state could not be read before removing HolyCodex-owned plugins.",S,{operation:"read Codex plugin state",plugins:[...s].join(","),recovery:"Repair or expose Codex, then retry removal."})}}let O,k=a;try{let S=g,D=C;if(D){let P=await Ar(S,D,{schema:D.schema,installId:D.installId}),pe=[...P.preservedKeys,...P.unresolvedKeys];if(pe.filter((Rt)=>!f.has(po({path:n.configFile,key:Rt,action:"remove"}))).length>0)return l.push(n.configFile),u.push("managed_config_changed"),await Mr(n,a??xs()),p();if(S=P.document,pe.length>0){let Rt=new Set(pe);D={...P.state,managed:Object.fromEntries(Object.entries(P.state.managed).filter(([Tt])=>!Rt.has(Tt)))}}else D=P.state}if(a?.plugin_config){let P=await Yc(S,a.plugin_config,{allowBeforeState:!0});if(P.preserved.length>0)return l.push(n.configFile),u.push("plugin_config_changed"),await Mr(n,a),p();S=P.document}if(a?.provider_config){let P=await Zc(S,eg(a.provider_config),s,{allowBeforeState:!0});if(P.preserved.length>0)return l.push(n.configFile),u.push("provider_config_changed"),await Mr(n,a),p();S=P.document}if(a?.managed_config||a?.plugin_config||a?.provider_config)O=D===void 0?{document:S}:{document:S,state:D};if(O!==void 0){if(Object.keys(O.document).length===0&&y===void 0)await qF(n.configFile,y),await Qh(n.configFile,{force:!1});else await qF(n.configFile,y),await vt(n.configFile,fo(O.document));k={...a,managed_config:O.state},await Mr(n,k),d=!0}}catch(S){if(S instanceof _)throw await Mr(n,k??xs()),S;return l.push(n.configFile),u.push("managed_config_write_failed"),await Mr(n,k??xs()),p()}let I=await Wh(n.codexHome,a?.managed_artifacts??[],v);if(c.push(...I.removed),l.push(...I.preserved),I.preserved.length>0)return u.push("managed_artifact_changed"),await Mr(n,k??a??xs()),p();c.push(...await lK(n.roleRoot,a?.managed_artifacts??[]));for(let S of s)try{if(M?.list===void 0||M.remove===void 0||N===void 0)throw new _("capability_denied","Codex plugin state is unavailable for a HolyCodex-owned plugin.",void 0,{operation:"remove Codex plugin",plugin_id:S});let P=xK(N,S);if(P?.entry.installed!==!0)continue;let pe=P.entry.pluginId;await M.remove(pe);let De=await M.list();if(N=De,ao(De,S)?.entry?.installed===!0||[...De.installed,...De.available].some((et)=>et.pluginId===S&&et.installed))throw new _("capability_denied",`Codex still reports ${S} after removal.`);if(O!==void 0)await cK(n,O.document,S);c.push(S)}catch(D){throw u.push("native_plugin_remove_failed"),await Mr(n,k??xs()),new _("capability_denied",`Codex native plugin removal did not converge for ${S}: ${ar(D)}`,D)}try{if(await Pd(e.runtime??ys(t),a.tooling?.context7))c.push("ctx7")}catch(S){throw u.push("context7_remove_failed"),await Mr(n,k??xs()),new _("capability_denied",`Context7 removal did not converge: ${ar(S)}`,S)}if(r)try{await Qh(n.activeRecord,{force:!1}),c.push(n.activeRecord)}catch(S){if(!We(S,"ENOENT"))return l.push(n.activeRecord),u.push("state_remove_failed"),await Mr(n,a??r),p()}if(l.length===0)try{await Qh(n.installOptions,{force:!1}),c.push(n.installOptions)}catch(S){if(!We(S,"ENOENT"))l.push(n.installOptions),u.push("state_remove_failed"),await Mr(n,a??r??xs())}if(l.length===0)for(let[S,D]of[[n.preparingRecord,o!==void 0],[n.conflictedRecord,i!==void 0||d]]){if(!D)continue;try{await SK(S),c.push(S)}catch{l.push(S),u.push("state_remove_failed")}}if(l.length===0)try{await Dv(n.roleRoot),c.push(n.roleRoot)}catch(S){if(!We(S,"ENOENT"))l.push(n.roleRoot),u.push("role_directory_not_empty")}if(l.length===0)try{await Dv(n.stateRoot),c.push(n.stateRoot)}catch(S){if(We(S,"ENOENT"))c.push(n.stateRoot);else l.push(n.stateRoot),u.push("state_directory_not_empty")}return Xh(e,{stage:"removal",status:"completed",message:l.length===0&&u.length===0?"HolyCodex removal complete":"HolyCodex removal preserved state for review"}),{removed:c,preserved:l,reasons:u}}async function cK(e,t,n){let r=await ye(e.configFile);if(r===void 0)return;let o=Jt(r,e.configFile),i=o.plugins;if(!Fv(i))return;let a=i[n];if(!Fv(a)||Object.keys(a).length!==1||a.enabled!==!1)return;let s=t.plugins,c=Fv(s)?s[n]:void 0,l={...i};if(c===void 0)delete l[n];else l[n]=c;let u={...o};if(Object.keys(l).length===0)delete u.plugins;else u.plugins=l;await vt(e.configFile,fo(u))}function Fv(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}async function lK(e,t){let n=new Set;for(let o of t){let i=o.path.split("/");if(i.length===4&&i[0]==="holycodex"&&i[1]==="agents"&&/^[a-f0-9]{20}$/u.test(i[2]??"")&&i[3]?.endsWith(".toml"))n.add(i[2])}let r=[];for(let o of n){let i=aK(e,o);try{await Dv(i),r.push(i)}catch(a){if(!We(a,"ENOENT")&&!We(a,"ENOTEMPTY")&&!We(a,"EEXIST"))throw a}}return r}async function uK(e={},t=process.env,n={}){let r=Pr(e,t),o=await oa(r),[i,a]=await Promise.all([Nr(r.preparingRecord,o),Nr(r.conflictedRecord,o)]);if(o!==void 0&&!await bs(o))throw new _("state_corrupt","The existing HolyCodex configuration has changed and cannot be upgraded safely.",void 0,{path:r.activeRecord});Hv(o,i,a);let s=HF(o,i,a),c=s??o;if(c===void 0)throw new _("not_installed","HolyCodex is not installed in the selected Codex home.",void 0,{recovery:"Run `holycodex install --yes` first."});let l=await ng(r),u=l===void 0?{profile:c.profile,tier:c.tier,optional:{browser_use:c.optional_selections.browser_use,computer_use:c.optional_selections.computer_use,sites:c.optional_selections.sites},officialPlugins:dK(c)}:pK(Nd(l)),d=n.options===void 0?u:dn(n.options),p={profile:d.profile??u.profile,tier:d.tier??u.tier,optional:{...u.optional,...d.optional},officialPlugins:d.officialPlugins??u.officialPlugins},m=!fK(p,u),f;try{f=await vd()}catch(k){throw new _("upgrade_failed","The running HolyCodex version is unavailable.",k)}let y=f.split("-",1)[0]===c.version.split("-",1)[0]&&f.includes("-dev.")!==c.version.includes("-dev."),g=y?0:Ec(f,c.version);if(g<0)throw new _("upgrade_downgrade",`The running HolyCodex version ${f} is older than the installed version ${c.version}.`,void 0,{installed_version:c.version,running_version:f});let x=c.managed_config?.managed["features.context_management"]!==void 0,v=c.managed_config?.managed[Zi[0]]!==void 0,C=[];if(n.dryRun===!0){let k=Jt(await ye(r.configFile));if(c.managed_config!==void 0)for(let S of Object.keys(c.managed_config.managed)){if(!is(S))continue;if((await ss(k,c.managed_config,S)).status!=="unchanged")C.push({path:r.configFile,key:S,action:"replace"})}if(c.plugin_config!==void 0){let S=await Yc(k,c.plugin_config);for(let D of S.preserved){let P=D==="preference"?'plugins."holycodex@holycodex"':"marketplaces.holycodex";C.push({path:r.configFile,key:P,action:"replace"})}}if(c.provider_config!==void 0){let S=await Zc(k,eg(c.provider_config),new Set(jv(c)));for(let D of S.preserved)C.push({path:r.configFile,key:`plugins."${D}"`,action:"replace"})}let I=await Bh(r.codexHome,c.profile,c.managed_artifacts,c.tier,{browserUse:c.optional_selections.browser_use,computerUse:c.optional_selections.computer_use});for(let S of I)C.push(S)}let M=!1,N=[];try{let k=e.runtime??ys(t),I;try{I=await Iv(k,c.tooling?.context7)}catch(D){if(c.tooling?.context7!==void 0||!bK(D))throw D}let S=c.tooling?.context7;if(S?.manager!==I?.manager)N.push("Context7 manager changed");if(S?.version!==I?.version)N.push("Context7 version changed");if(S?.executable===void 0?I?.executable!==void 0:I?.executable===void 0||!await Jc(k,S.executable,I.executable))N.push("Context7 executable changed");M||=N.length>0}catch(k){M=!0;let I=typeof k==="object"&&k!==null&&"code"in k&&typeof k.code==="string"?k.code:k instanceof Error?k.name:"inspection failed";N.push(`inspection failed (${I})`)}let O=[...g>0||y?["version"]:[],...m?["installation options"]:[],...l===void 0?["installation options migration"]:[],...x?["context-management configuration migration"]:[],...v?["auto-compaction configuration cleanup"]:[],...g>0||x||v?["Root/session configuration","specialist role definitions"]:[],...s?["interrupted transaction recovery"]:[],...M?[`shared tooling reconciliation (${N.join(", ")})`]:[],...C.map((k)=>`conflict: ${k.path}${k.key===void 0?"":` (${k.key})`} -> ${k.action}`)];if(O.length===0)return{status:n.dryRun===!0?"dry_run":"current",from_version:c.version,to_version:f,changes:[],record:o,preserved:[],warnings:[],conflicts:C};if(n.dryRun===!0)return{status:"dry_run",from_version:c.version,to_version:f,changes:O,record:o,preserved:[],warnings:[],conflicts:C};try{let k=await Ss(p,e,t);return{status:"upgraded",from_version:c.version,to_version:f,changes:O,record:k.record,preserved:k.preserved,warnings:k.warnings}}catch(k){if(k instanceof _)throw k;throw new _("upgrade_failed",`HolyCodex upgrade failed: ${ar(k)}`,k)}}function dK(e){let t=new Set(Ac(e.optional_selections));return(e.official_plugins??[]).filter((n)=>n!==ln&&!UF(n)&&!t.has(n))}function eg(e){return e.filter((t)=>t.plugin_id!==ln)}function pK(e){return{...e,...e.officialPlugins===void 0?{}:{officialPlugins:e.officialPlugins.filter((t)=>!UF(t))}}}function UF(e){let t=e.slice(0,e.lastIndexOf("@"));return sK.has(t)}function fK(e,t){let n=e.optional??{},r=t.optional??{},o=[...new Set(e.officialPlugins??[])],i=[...new Set(t.officialPlugins??[])];return e.profile===t.profile&&e.tier===t.tier&&n.browser_use===r.browser_use&&n.computer_use===r.computer_use&&n.sites===r.sites&&o.length===i.length&&o.every((a,s)=>a===i[s])}async function mK(e,t){let n=new Set;if(e.resolveConflicts!==void 0&&t.length>0){let r=t.map((i)=>({...i,identity:`remove:${i.path}:${i.key??""}`,category:i.key===void 0?"role-asset":"config-key",target:i.key??i.path,explanation:"HolyCodex can remove this managed value after reviewing the change.",validDecisions:["keep","remove","cancel"],defaultDecision:"keep"})),o=await e.resolveConflicts(r);for(let i=0;i<r.length;i+=1){let a=r[i],s=o[a.identity];if(s==="remove")n.add(po(t[i]));else if(s==="keep")continue;else if(s==="cancel")throw new _("confirmation_required","Conflict resolution was cancelled.",void 0,{identity:a.identity,path:a.path,...a.key===void 0?{}:{key:a.key}});else throw new _("confirmation_required",`The removal conflict at ${a.target} requires a keep, remove, or cancel decision.`,void 0,{identity:a.identity,path:a.path,...a.key===void 0?{}:{key:a.key},decision:s??"unavailable"})}return n}for(let r of t){let o=await e.resolveConflict?.(r);if(o==="accept"){n.add(po(r));continue}if(o==="decline")continue;throw new _("confirmation_required",o==="cancel"?"Conflict resolution was cancelled.":"Modified HolyCodex-owned state requires confirmation before removal.",void 0,{path:r.path,...r.key===void 0?{}:{key:r.key},action:r.action,resolution:o??"unavailable"})}return n}function po(e){return`${e.action}\x00${e.path}\x00${e.key??""}`}async function Lv(e,t,n,r,o){let i=fe(n,t),a=await $F(n,t);return{identity:po({path:e,key:t,action:"remove"}),category:r,target:t,existing:{present:i!==void 0,digest:a},desired:{present:!1},explanation:o,validDecisions:["keep","remove","cancel"],defaultDecision:"keep",path:e,key:t,action:"remove"}}async function $F(e,t){let n=fe(e,t);return await qn("holycodex-removal-config-review-v1",[Dn(sn(n===void 0?{present:!1}:{present:!0,value:n}))])}function jF(e){if(typeof e.existing!=="object"||e.existing===null)return;let t=e.existing.digest;return typeof t==="string"?t:void 0}async function hK(e,t,n,r){for(let i of n){if(i.key===void 0)continue;let a=jF(i);if(a===void 0||await $F(t,i.key)!==a)throw qv(i.path,i.key)}let o;try{o=await OF(e.codexHome,r)}catch(i){let a=r.keys().next().value;throw new _("confirmation_required","A reviewed HolyCodex file could not be checked safely, so removal did not continue.",i,{operation:"verify removal review",...a===void 0?{}:{path:a},recovery:"Check file access, then run remove again to review current state."})}if(o.length>0)throw qv(o[0])}function qv(e,t){return new _("confirmation_required","A reviewed HolyCodex item changed before removal. No reviewed changes were applied; run remove again to review the current state.",void 0,{operation:"remove HolyCodex",path:e,...t===void 0?{}:{key:t},recovery:"Run remove again to review the current state."})}async function qF(e,t){if(await ye(e)!==t)throw qv(e)}async function gK(e,t){if(!t.managed_config)return Kt(["incomplete_install_state"]);try{let n=Jt(await ye(e.configFile)),r=Ld(t.profile,t.tier,{browserUse:t.capability_state?.browser_use.status==="healthy"&&t.capability_state.browser_use.selected,computerUse:t.optional_selections.computer_use,frontend:Pt.frontend,security:Pt.security}),o=[];for(let i of Object.keys(r))if((await ss(n,t.managed_config,i)).status!=="unchanged")o.push(i);return o.length===0?Gc({managed_keys:Object.keys(r).length}):Kt(["changed_holycodex_config"],{keys:o})}catch(n){return Kt(["config_unreadable"],{error:ar(n)})}}async function yK(e,t,n,r={browserUse:!1,computerUse:!1}){try{let o=Jt(await ye(e.configFile)),i=[],a=fs(t,n,r);for(let c of ei(t,n)){let l=fe(o,`agents."${c.name}".config_file`),u=as(e.configFile,Td(c.name,a)).replaceAll("\\","/");if(typeof l!=="string"||as(e.configFile,l).replaceAll("\\","/")!==u){i.push(`${c.name}:registration`);continue}let d=await ye(u);if(d===void 0){i.push(`${c.name}:missing`);continue}if(d!==Vc(c,r)){i.push(`${c.name}:changed`);continue}let p=Jt(d);if(p.name!==c.name||typeof p.description!=="string"||typeof p.developer_instructions!=="string"||p.model!==c.model||p.model_reasoning_effort!==c.effort||p.model_reasoning_summary!=="none"||p.model_verbosity!=="low"||p.tool_output_token_limit!==void 0||p.service_tier!==(n==="standard"?"default":"fast")||!zh(c,p)||p.approval_policy!=="never"||p.web_search!==(c.permissions.network?"live":"disabled")||fe(p,"agents.enabled")!==!1||fe(p,"features.multi_agent")!==!1||fe(p,"features.multi_agent_v2")!==!1||fe(p,"features.agent_message_board")!==!1||fe(p,"features.context_management.experimental_mode")!==!0||Object.keys(p.features??{}).some((m)=>!["multi_agent","multi_agent_v2","agent_message_board","context_management"].includes(m)))i.push(`${c.name}:malformed`)}let s=await ye(`${e.codexHome}/agents/root.toml`);if(s!==void 0&&Wc(s))i.push("root:stale");return i.length===0?Gc({role_root:e.roleRoot,agent_types:ei(t,n).map((c)=>c.name)}):Kt(["native_role_disagreement"],{roles:i})}catch(o){return Kt(["native_role_invalid"],{error:ar(o)})}}async function Mr(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(Ie(ta,n)!==void 0)await jc(e.conflictedRecord,sn(n))}function HF(e,t,n){return[n,t].find((r)=>r!==void 0&&(e===void 0||Fd(r,e)))}function BF(e,t,n){return HF(e,t,n)??e}function xs(){return{owner:"holycodex",schema_epoch:"state-0.16",install_id:"remove-conflict",version:"0.0.0",digest:"0".repeat(64),profile:"default",tier:"standard",optional_selections:{browser_use:!1,computer_use:!1,sites:!1,coding:!0},explicit_optional_selections:{},managed_artifacts:[],installed_at:new Date(0).toISOString()}}function jv(e){if(e?.owned_plugins!==void 0)return[...new Set(e.owned_plugins)].filter((o)=>o!==ln);let t=(e?.plugin_snapshot??[]).filter((o)=>o.plugin_id!==ln&&(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"?[un]:[],r=(e?.provider_config??[]).filter((o)=>o.plugin_id!==ln&&o.before.presence==="absent"&&o.after.presence==="present").map((o)=>o.plugin_id);return[...new Set([...t,...n,...r])]}function xK(e,t){let n=ao(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 Gc(e){return{status:"healthy",reasons:[],details:e}}function Kt(e,t={}){return{status:"failed",reasons:e,details:t}}async function SK(e){await Qh(e,{force:!1}).catch((t)=>{if(!We(t,"ENOENT"))throw t})}function bK(e){return typeof e==="object"&&e!==null&&"code"in e&&(e.code==="context7_unavailable"||e.code==="context7_manager_unknown")}function ar(e){return e instanceof Error?e.message.slice(0,256):"operation failed"}function Xh(e,t){try{e.onProgress?.(t)}catch{}}var sK;var tg=w(()=>{cs();ht();Dd();hd();Rd();Kh();Od();ds();ls();Hc();Zh();sK=new Set(["documents","pdf","presentations","spreadsheets","template-creator"])});import{lstat as YF,open as wK,rm as $d}from"fs/promises";import{dirname as _K}from"path";function dn(e){let t=Ie(qh,e);if(t===void 0)throw new _("install_failed","The installation options are invalid.");let n=t;return XF(n),n}function XF(e){if(e.officialPlugins?.includes(ln)!==!0)return;throw new _("install_failed","Browser Use is provided by Codex Desktop/runtime and cannot be installed by the HolyCodex CLI. Select the Browser Use capability instead; it is available only on supporting Codex surfaces.",void 0,{plugin_id:ln})}async function ng(e){let t=await ye(e.installOptions);return QF(t,e.installOptions)}function QF(e,t){if(e===void 0)return;let n;try{n=bd(e)}catch(i){throw new _("state_corrupt","The HolyCodex install options are not valid TOML.",i,{path:t})}let r=Ie(Sd,n);if(r!==void 0)return r;let o=Ie(rF,n);if(o!==void 0)return{schema_version:1,profile:o.profile,tier:o.tier,capabilities:o.capabilities.filter((i)=>i==="browser_use"||i==="computer_use"||i==="sites").concat(...["browser_use","sites"].filter((i)=>!o.capabilities.includes(i))),additional_plugins:o.additional_plugins};if(r===void 0)throw new _("state_corrupt","The HolyCodex install options are invalid.",void 0,{path:t});return r}async function eL(e,t){if(Ie(Sd,t)===void 0)throw new _("state_corrupt","The HolyCodex install options are invalid.");await vt(e.installOptions,wd(t))}function Nd(e){return{profile:e.profile,tier:e.tier,optional:{browser_use:e.capabilities.includes("browser_use"),computer_use:e.capabilities.includes("computer_use"),sites:e.capabilities.includes("sites")},officialPlugins:e.additional_plugins.filter((t)=>t!==ln)}}async function tL(e={},t=process.env){let n=Pr(e,t),r=await ng(n);if(r!==void 0)return Nd(r);let o=await oa(n);if(o===void 0)return{};return{profile:o.profile,tier:o.tier,optional:o.optional_selections,officialPlugins:Zv(o)}}function nL(e,t,n,r){let o=["browser_use","computer_use","sites"].filter((i)=>n[i]);return{schema_version:1,profile:e,tier:t,capabilities:o,additional_plugins:[...new Set(r)].filter((i)=>i!==ln)}}function Fd(e,t){return e.install_id===t.install_id&&e.digest===t.digest}function rg(e,t,n){let r=[{status:"conflicted",record:n},{status:"preparing",record:t}].filter((a)=>a.record!==void 0),o=r.length>1,i=o&&r.every(({record:a})=>Fd(a,r[0].record));return r.map(({status:a,record:s})=>{let c=e===void 0?o&&!i?"incompatible":"orphaned":Fd(s,e)?o&&!i?"incompatible":"bound":"stale";return{status:a,relation:c,install_id:s.install_id,digest:s.digest,recovery:c==="stale"||c==="incompatible"?"inspect":"reconcile",...e===void 0?{}:{active_install_id:e.install_id,active_digest:e.digest}}})}function Hv(e,t,n){let r=rg(e,t,n);if(r.filter((i)=>i.relation==="stale"||i.relation==="incompatible").length>0)throw new _("state_corrupt","HolyCodex has stale or incompatible transaction state and cannot recover safely.",void 0,rL(r));return r}function Bv(e,t,n){let r=rg(e,t,n);if(e===void 0&&r.some((o)=>o.relation==="incompatible"))throw new _("state_corrupt","HolyCodex has ambiguous transaction state and cannot recover safely.",void 0,rL(r));return r}function rL(e){return{recovery:e.map((t)=>t.recovery).join(","),transactions:e.map((t)=>`${t.status}:${t.relation}:${t.install_id}:${t.digest}`).join(","),active:e[0]?.active_install_id===void 0?"absent":`${e[0].active_install_id}:${e[0].active_digest}`}}async function Ss(e={},t={},n=process.env){let r=Ie(xd,e);if(r===void 0)throw new _("install_failed","The installation options are invalid.");XF(r);let o=Pr(t,n),i=await ye(o.installOptions),a=QF(i,o.installOptions),s=a===void 0?void 0:Nd(a);Fr(t,{stage:"validation",status:"started",message:"Validating Codex target"});let c=await oa(o),l=await ye(o.activeRecord);if(c!==void 0&&!await bs(c))throw new _("state_corrupt","The existing HolyCodex configuration has changed and cannot be replaced.",void 0,{path:o.activeRecord});let u=await Nr(o.preparingRecord,c),d=await Nr(o.conflictedRecord,c);Hv(c,u,d);let p=[d,u].find((A)=>A!==void 0&&(c===void 0||Fd(A,c)));if(p!==void 0){await Promise.resolve().then(() => tg());let L=await Md(t,n);if(L.preserved.length>0||L.reasons.length>0)throw new _("state_corrupt","The interrupted HolyCodex installation could not be reconciled safely.",void 0,{preserved:L.preserved.join(","),reasons:L.reasons.join(",")});return await Ss({profile:e.profile??s?.profile??p.profile,tier:e.tier??s?.tier??p.tier,optional:{browser_use:e.optional?.browser_use??s?.optional?.browser_use??p.optional_selections.browser_use,computer_use:e.optional?.computer_use??s?.optional?.computer_use??p.optional_selections.computer_use,sites:e.optional?.sites??s?.optional?.sites??p.optional_selections.sites},officialPlugins:e.officialPlugins??s?.officialPlugins??Zv(p)},t,n)}let m=GK(e.profile??s?.profile,c?.profile),f=YK(e.tier??s?.tier,c?.tier),y=s?.optional,g=Gv(y,e.optional),x=ZK(g,c?.optional_selections),v=Gv(Gv(c?.explicit_optional_selections,y),e.optional),C=e.officialPlugins??s?.officialPlugins??Zv(c),M=t.runtime??ys(n),N=await Gh(M,!1,c?.tooling?.context7).then(()=>!0,()=>!1),O,k,I=[...new Set(Ac(oL(x),C).map((A)=>Qn(A)??A))],S;try{S=t.officialPluginManager??await ti.discover({...n,CODEX_HOME:o.codexHome})}catch(A){throw new _("capability_denied","Native Codex plugin installation is unavailable.",A,{recovery:"Install or expose Codex, then retry."})}if(!S.addMarketplace||!S.add||!S.list)throw new _("install_failed","Native Codex plugin installation and verification are unavailable.");let D=c?.install_id??crypto.randomUUID().replaceAll("-",""),P=await vd(),pe=c!==void 0&&c.version!==P&&c.owned_plugins?.includes(un)===!0?new Set([un]):new Set,De=new Set((c?.owned_plugins??[]).filter((A)=>A!==ln)),Rt=new Set([un,...I]),Tt=[...De].filter((A)=>!Rt.has(A));if(Tt.length>0&&S.remove===void 0)throw new _("install_failed","Native Codex cannot remove previously managed plugins omitted from the new selection.",void 0,{plugins:Tt.join(",")});let et=(t.now?.()??new Date).toISOString(),Je=Ld(m,f,{browserUse:x.browser_use,computerUse:x.computer_use,frontend:Pt.frontend,security:Pt.security}),it=await ye(o.configFile),lr;try{lr=Jt(it,o.configFile)}catch(A){if(A instanceof _&&A.code==="state_corrupt")await MK(t,A,o.configFile);throw A}let sa=c?.managed_config??Ph({schema:On,installId:D}),si=await ag(lr,sa),gg=await EK(t,o.configFile,si.document,['plugins."holycodex@holycodex"',"marketplaces.holycodex",...Object.keys(Je)]),{document:tl,conflicts:Hn,decisions:Gd}=gg,yg=Hn.length===0?lr:Xc(lr,Hn,Gd),Rn;if(Hn.length>0){if(await ye(o.configFile)!==it)throw new _("confirmation_required","Codex configuration changed after the invalid-table review; review the latest configuration and retry.",void 0,{path:o.configFile});Rn=fo(yg),await vt(o.configFile,Rn)}let Yd,hR=!1,Zd,gR=new Map;try{Yd=await S.list()}catch(A){if(Rn!==void 0)await zv(o.configFile,it,Rn),Rn=void 0;if(!XK(A))throw new _("capability_denied","Native Codex plugin state could not be read safely.",A);if(await ye(o.configFile)!==it)throw new _("confirmation_required","Codex configuration changed before the required marketplace repair; review the current marketplace source and retry.",A,{path:o.configFile,key:"marketplaces.holycodex"});let L=fe(tl,"marketplaces.holycodex"),G=Hn.some((Be)=>Be.key==="marketplaces"&&Gd.get(Be.identity)==="remove");if(L===void 0&&!G)throw new _("confirmation_required","Codex reported an incomplete marketplace named holycodex, but config.toml does not contain a reviewable marketplace source. Review the source before retrying; no automatic replacement was attempted.",A,{path:o.configFile,key:"marketplaces.holycodex"});if(L!==void 0&&!QK(L))Zd=cr({path:o.configFile,key:"marketplaces.holycodex",action:"replace",category:"config-key",target:"marketplaces.holycodex",existing:L,desired:{source_type:"git",source:ni},explanation:"The existing HolyCodex marketplace source must be reviewed before rebuilding its incomplete cache from the required canonical source.",defaultDecision:"replace",validDecisions:["replace","cancel"]}),gR=(await jd(t,[Zd],!0)).decisions;if(!(ii(L)&&Object.keys(L).length===2&&L.source_type==="git"&&L.source===ni)){if(await ye(o.configFile)!==it)throw new _("confirmation_required","Codex configuration changed before marketplace repair; review the current source and retry.",A,{path:o.configFile,key:"marketplaces.holycodex"});let Be=mo(tl,"marketplaces",_s,{source_type:"git",source:ni});Rn=fo(Be),await vt(o.configFile,Rn)}if(S.addMarketplace===void 0)throw new _("capability_denied","Native Codex plugin state could not be read safely.",A);try{await S.addMarketplace(VF),Yd=await S.list(),hR=!0}catch(Be){if(Rn!==void 0)try{await zv(o.configFile,it,Rn),Rn=void 0}catch(ze){throw new _("confirmation_required","The marketplace repair failed and the reviewed temporary Codex configuration could not be restored safely; review config.toml before retrying.",ze,{path:o.configFile,key:"marketplaces.holycodex"})}throw new _("capability_denied","The required HolyCodex marketplace could not be repaired before plugin validation.",Be)}}if(Rn!==void 0)await zv(o.configFile,it,Rn),Rn=void 0;let yR=I.filter((A)=>{if(!A.endsWith("@openai-curated"))return!1;let L=Lr(Yd,A);return!(L?.installed&&L.enabled)});Fr(t,{stage:"validation",status:"completed",message:"Codex target validated"});let ca=await og(tl),xg=c?.plugin_config?.before??ca,ho=xg,Ts=t.resolveConflicts!==void 0,Cs=[],nl=[],rl=[];if(nl=["preference","marketplace"].filter((L)=>{let G=ca[L].digest,Z=ca[L],Be=L==="preference"?{kind:"boolean",value:!0}:{kind:"marketplace",source_type:"git",source:ni},ze=Z.presence==="present"&&JSON.stringify(Z.safe_value)!==JSON.stringify(Be),ut=c?.plugin_config!==void 0&&G!==c.plugin_config.after[L].digest&&G!==c.plugin_config.before[L].digest;return ze||ut}).map((L)=>{let G=L==="preference"?'plugins."holycodex@holycodex"':"marketplaces.holycodex",Z=ca[L],Be=L==="preference"?{kind:"boolean",value:!0}:{kind:"marketplace",source_type:"git",source:ni};return cr({path:o.configFile,key:G,action:"replace",category:"config-key",target:G,existing:Z.safe_value??{presence:Z.presence},desired:Be,explanation:`The existing ${G} entry does not match the HolyCodex plugin configuration.`,validDecisions:["replace","cancel"],defaultDecision:"replace"})}),Ts)Cs.push(...nl);let Sg=[...new Set([...I,...(c?.provider_config??[]).map((A)=>A.plugin_id),...c?.owned_plugins??[]])].filter((A)=>A!==un&&A!==ln),la=await ig(tl,Sg);{let A=new Set(c?.owned_plugins??[]);if(rl=la.filter((G)=>{let Z=c?.provider_config?.find((ut)=>ut.plugin_id===G.plugin_id),Be=A.has(G.plugin_id)&&Z!==void 0&&G.before.digest!==Z.after.digest&&G.before.digest!==Z.before.digest,ze=I.includes(G.plugin_id)&&G.before.presence==="present"&&G.before.safe_value?.value!==!0;return Be||ze}).map((G)=>{let Z=`plugins."${G.plugin_id}"`;return cr({path:o.configFile,key:Z,action:"replace",category:"config-key",target:Z,existing:G.before.safe_value??{presence:G.before.presence},desired:{kind:"boolean",value:!0},explanation:`The existing provider plugin entry ${G.plugin_id} does not match the selected plugin configuration.`,...I.includes(G.plugin_id)?{validDecisions:["replace","cancel"],defaultDecision:"replace"}:{}})}),Ts)Cs.push(...rl)}let bg=la.map((A)=>{let L=c?.provider_config?.find((G)=>G.plugin_id===A.plugin_id);return L===void 0?A:{plugin_id:A.plugin_id,before:L.before,after:L.before}}),Xd=bg,xR=si.state,SR=await Kv(tl,xR,c),bR=await ag(SR.document,SR.state),wR=await Jv(bR.document,bR.state),{document:Dr,state:ur}=wR;qK(Dr,ur);let ua;if(c!==void 0){ua=Ld(c.profile,c.tier,{browserUse:c.optional_selections.browser_use,computerUse:c.optional_selections.computer_use,frontend:Pt.frontend,security:Pt.security});let A=eh(c.version.split("-",1)[0]);for(let L of Go){let G=c.managed_artifacts.find(({path:Z})=>Z.endsWith(`/${L}.toml`));ua[`agents."${L}".config_file`]=G?.path??`holycodex/agents/${L}.toml`}if(Ec(A,vK)<=0)ua.model="gpt-6-astra",ua.model_reasoning_effort=c.profile==="low"?"low":c.profile==="default"?"medium":"high";else if(c.profile==="high"&&Ec(A,RK)<=0)ua.model_reasoning_effort="high";delete ua.developer_instructions}let wg=await DK(Dr,ur,Je,ua),go;try{go=await Dc(Dr,ur,wg,{schema:On,installId:D})}catch(A){if(A instanceof _)throw A;throw new _("state_corrupt","The existing Codex configuration has an incompatible shape for HolyCodex settings.",A,{recovery:"Converge the conflicting Codex setting, then retry."})}let ci=[];if(go.driftedKeys.length>0)ci=go.driftedKeys.map((A)=>{let L=ur.managed[A],G=fe(Dr,A),Z=Je[A];return cr({path:o.configFile,key:A,action:"replace",category:"config-key",target:A,existing:G??L?.lastManagedValue,desired:Z,explanation:`The managed Codex setting ${A} changed outside the previous transaction.`})});let da=Object.entries(Je).flatMap(([A,L])=>{let G=A;if(ur.managed[G]!==void 0)return[];let Z=fe(Dr,G);if(Z===void 0||JSON.stringify(Z)===JSON.stringify(L))return[];return[cr({path:o.configFile,key:G,action:"replace",category:"config-key",target:G,existing:Z,desired:L,explanation:`The existing Codex setting ${G} is user-owned and differs from the HolyCodex install value.`,defaultDecision:"replace",validDecisions:["keep","replace","cancel"]})]});if(Ts)Cs.push(...da);if(Ts)Cs.push(...ci);let ol;try{ol=await Bh(o.codexHome,m,c?.managed_artifacts,f,{browserUse:x.browser_use,computerUse:x.computer_use})}catch(A){throw new _("install_failed",Ud(A),A)}if(Ts)Cs.push(...ol.map(cr));let Qd=[...Hn,...nl,...rl,...da,...ci,...ol.map(cr)],EL={...go.state.managed},IL=new Set([...Hn.map((A)=>A.identity),...Zd===void 0?[]:[Zd.identity]]),AL=(Ts?Cs:Qd).filter((A)=>!IL.has(A.identity)),_R=await jd(t,AL,!0),qr={..._R,decisions:new Map([...Gd,...gR,..._R.decisions])},vR=[],il={...wg},al=ur.managed,RR=async()=>{vR=ol.map((ze)=>{let ut=cr(ze),tt=qr.decisions.get(ut.identity);return tt===void 0?ut:{...ut,decision:tt}});let A=await zF(Dr,Dr,xg,bg,ca,la,nl,rl,qr.decisions,I),L=Xc(A.document,Hn,qr.decisions);ho=A.pluginConfigBefore,Xd=A.providerConfigBefore;let G={...ur.managed},Z={...wg};for(let ze of[...da,...ci]){let ut=ze.key;if(ut===void 0)continue;let tt=ut,pa=qr.decisions.get(ze.identity);if(pa!=="keep"&&pa!=="replace")throw new _("confirmation_required","Managed conflict resolution is incomplete.",void 0,{key:ut});let qt=G[tt],li=Je[tt];if(li===void 0)throw new _("state_corrupt","The managed conflict cannot be verified.",void 0,{path:o.configFile,key:ut});let dr=fe(Dr,tt);if(pa==="replace")if(L=so(L,tt,li),qt!==void 0)G[tt]={...qt,lastManagedValue:await _n(tt,li)};else{let $r=EL[tt];if($r!==void 0)G[tt]=$r}else{if(delete Z[tt],qt===void 0)continue;if(dr===void 0){delete G[tt];continue}let $r={...qt,lastManagedValue:await _n(tt,dr)},np={...ur,managed:{...G,[tt]:$r}};if(Yi(np))G[tt]=$r;else delete G[tt]}}if(go=await Dc(L,{...ur,managed:G},Z,{schema:On,installId:D}),go.driftedKeys.length>0)throw new _("state_corrupt","The accepted managed conflicts did not converge.");il=Z;let Be={...ur.managed};for(let ze of[...da,...ci]){let ut=ze.key;if(ut===void 0)continue;delete Be[ut]}al=Be};await RR();let TR=()=>Qd.map((A)=>{let L=cr(A),G=qr.decisions.get(L.identity);return G===void 0?L:{...L,decision:G}}),CR=(A)=>Object.fromEntries(["config-key","invalid-config","native-plugin","role-asset"].flatMap((L)=>{let G=A.filter((Z)=>Z.category===L).length;return G===0?[]:[[L,G]]})),ep=TR(),OR=CR(ep),PL=eJ(N,Yd,I);if(t.reviewInstall!==void 0)while(!0){let A=await t.reviewInstall({operation:c===void 0?"install":"upgrade",...c===void 0?{}:{fromVersion:c.version},toVersion:P,profile:m,tier:f,capabilities:{browser_use:x.browser_use,computer_use:x.computer_use,sites:x.sites},additionalPlugins:[...C],conflicts:ep,conflictCounts:OR,tools:PL});if(A.action==="cancel")throw new _("confirmation_required","Install review was cancelled.");if(A.action==="resolve"){if(Qd.length===0)throw new _("confirmation_required","There are no managed conflicts to resolve.");qr=await jd(t,Qd,!0),await RR(),ep=TR(),OR=CR(ep);continue}if(A.action==="change"){if(A.request===void 0)throw new _("confirmation_required","Changing install options requires a revised request.");return await Ss(A.request,t,n)}if(A.action==="apply")break;throw new _("confirmation_required","Unknown install review action.")}let _g={owner:"holycodex",schema_epoch:On,install_id:D,version:P,digest:c?.digest??"0".repeat(64),profile:m,tier:f,optional_selections:x,explicit_optional_selections:v,official_plugins:I,capability_state:cg(x),managed_artifacts:c?.managed_artifacts??[],installed_at:et,status:"preparing",step:"validated",managed_config:xR,plugin_snapshot:[],plugin_config:{plugin_id:un,before:ho,after:ho},provider_config:Xd,owned_plugins:[...De],...c?.tooling?.context7===void 0?{}:{tooling:{context7:c.tooling.context7}}};await $c(o.stateRoot),await sr(o.preparingRecord,_g);let sl=[],yo,vg=!1,kR=!1,ER=new Set,Rg=new Set,tp=new Set,Tn=new Set(De),Tg=new Set([...De,...I]),Cg=new Set,ge=_g,IR=!1,Ur,Og,cl=go.state,AR=!1,PR=!1;try{if(Hn.length>0){let X=await ye(o.configFile);if(yg=Xc(Jt(X,o.configFile),Hn,Gd),await ye(o.configFile)!==X)throw new _("confirmation_required","Codex configuration changed during conflict resolution; review the latest configuration and retry.",void 0,{path:o.configFile});await vt(o.configFile,fo(yg)),kR=!0}try{O=await Gh(M,!0,c?.tooling?.context7)}catch(X){k=`Optional ctx7 is unavailable: ${Ud(X)}`}let A=O??c?.tooling?.context7,L=A===void 0?void 0:{context7:A},G={..._g,...L===void 0?{}:{tooling:L}};if(ge=G,await sr(o.preparingRecord,ge),S.ensureOfficialMarketplace!==void 0&&yR.length>0)try{await S.ensureOfficialMarketplace(yR)}catch(X){throw new _("capability_denied",`The selected official Codex provider marketplace is unavailable: ${Ud(X)}`,X,{recovery:"Check Codex network and marketplace policy, then retry."})}try{sl=await UK({list:()=>S.list()},[...new Set([un,...I,...De])])}catch(X){throw new _("capability_denied","Native Codex plugin state could not be read safely.",X)}G={...G,plugin_snapshot:sl},ge=G,await sr(o.preparingRecord,ge);let Z=await ye(o.configFile),Be=Jt(Z,o.configFile),ze=Xc(Be,Hn,qr.decisions);await LK(ze,ca,la);let ut=await Kv(ze,sa,c),tt=await ag(ut.document,ut.state);Ur=(await Jv(tt.document,tt.state)).document,await JF(Ur,Dr,{...ur,managed:al},il),Fr(t,{stage:"roles",status:"started",message:"Installing subagent roles"}),await $c(o.roleRoot),yo=await Ov(o.codexHome,m,c?.managed_artifacts,f,ol.length===0?t.resolveConflict:void 0,vR,{browserUse:x.browser_use,computerUse:x.computer_use}),ge={...G,step:"roles_prepared",managed_artifacts:yo.managed_artifacts},await sr(o.preparingRecord,ge),Fr(t,{stage:"roles",status:"completed",message:"Subagent roles installed"}),Fr(t,{stage:"plugins",status:"started",message:"Installing selected capabilities"}),IR=!0;let qt=Ur;if(qt===void 0)throw new _("state_corrupt","The pre-mutation configuration baseline is missing.");qt=mo(qt,"plugins",ws,{enabled:!0}),qt=mo(qt,"marketplaces",_s,{source_type:"git",source:ni});for(let X of I)qt=mo(qt,"plugins",X,{enabled:!0});let li=await og(qt),$r=(await ig(qt,Sg)).map((X)=>({plugin_id:X.plugin_id,before:la.find((Pe)=>Pe.plugin_id===X.plugin_id)?.before??X.before,after:X.before}));if(ge={...ge,plugin_config:{plugin_id:un,before:ho,after:li},provider_config:$r},await sr(o.preparingRecord,ge),it===void 0)try{Og=await VK(o.configFile);let X=await ye(o.configFile);if(Og===void 0||X!=="")throw new _("confirmation_required","Codex config.toml appeared during installation; review the latest configuration and retry.",void 0,{operation:"initialize Codex configuration",path:o.configFile});Z=""}catch(X){if(X instanceof _)throw X;throw new _("permission_denied","Codex config.toml could not be initialized before plugin setup.",X,{operation:"initialize Codex configuration",path:o.configFile,recovery:"Check CODEX_HOME permissions, then retry."})}if(await ye(o.configFile)!==Z)throw new _("confirmation_required","Codex configuration changed during plugin setup; review the latest configuration and retry.",void 0,{path:o.configFile});if(await vt(o.configFile,fo(qt)),vg=!0,!hR)await S.addMarketplace(VF);await zK({list:()=>S.list(),add:(X)=>S.add(X)},[un,...I],pe,async(X,Pe)=>{if(Pe==="new")ER.add(X),Tn.add(X),Tg.add(X),ge={...ge,owned_plugins:[...Tn]};else Cg.add(X),Tn.add(X),Tg.add(X),ge={...ge,owned_plugins:[...Tn]};await sr(o.preparingRecord,ge)}),ge={...ge,step:"plugins_installed"},await sr(o.preparingRecord,ge),Fr(t,{stage:"plugins",status:"completed",message:"Selected capabilities installed"});let MR=await ye(o.configFile),ML=Jt(MR,o.configFile),NL=Xc(ML,Hn,qr.decisions),NR=await Kv(NL,sa,c),FR=await ag(NR.document,NR.state),FL=await Jv(FR.document,FR.state);if(Ur===void 0)throw new _("state_corrupt","The pre-mutation configuration baseline is missing.");let kg=await zF(FL.document,Ur,xg,bg,ca,la,nl,rl,qr.decisions,I),xo=kg.document;for(let X of Object.keys(al)){let Pe=X,Cn=fe(Ur,Pe);xo=Cn===void 0?tr(xo,Pe):so(xo,Pe,Cn)}ho=kg.pluginConfigBefore,Xd=kg.providerConfigBefore;let rp=await og(xo),LR=await ig(xo,Sg),DR=LR.map((X)=>({plugin_id:X.plugin_id,before:Xd.find((Pe)=>Pe.plugin_id===X.plugin_id)?.before??X.before,after:X.before})),qR=LR.map((X)=>({plugin_id:X.plugin_id,before:la.find((Pe)=>Pe.plugin_id===X.plugin_id)?.before??X.before,after:X.before}));ge={...ge,plugin_config:{plugin_id:un,before:ho,after:rp},provider_config:qR};let LL=new Set([...da,...ci].flatMap((X)=>X.key===void 0?[]:[X.key])),op={...al};for(let X of[...da,...ci]){let Pe=X.key;if(Pe===void 0)continue;let Cn=go.state.managed[Pe];if(Cn!==void 0)op[Pe]=Cn}for(let[X,Pe]of Object.entries(op)){if(LL.has(X))continue;let Cn=X,ll=fe(Ur,Cn);op[Cn]={...Pe,...ll===void 0?{}:{lastManagedValue:await _n(Cn,ll)}}}let UR={...go.state,managed:op};await JF(xo,Ur,{...UR,managed:al},il);for(let X of[...da,...ci]){let Pe=X.key;if(Pe===void 0)continue;let ll=qr.decisions.get(X.identity)==="replace"?Je[Pe]:fe(Dr,Pe);if(ll!==void 0)xo=so(xo,Pe,ll)}let ip=await Dc(xo,UR,il,{schema:On,installId:D});if(ip.driftedKeys.length>0)throw new _("state_corrupt","HolyCodex-owned Codex settings changed during native plugin setup.",void 0,{keys:ip.driftedKeys.join(",")});if(Fr(t,{stage:"config",status:"started",message:"Configuring Root"}),cl=ip.state,ge={...ge,managed_config:cl,plugin_config:{plugin_id:un,before:ho,after:rp},provider_config:qR},await ye(o.configFile)!==MR)throw new _("confirmation_required","Codex configuration changed during plugin setup; review the latest configuration and retry.",void 0,{path:o.configFile});if(await vt(o.configFile,fo(ip.document)),vg=!0,ge={...ge,step:"config_published"},await sr(o.preparingRecord,ge),Tt.length>0)await KK({list:()=>S.list(),remove:(Pe)=>S.remove(Pe)},Tt,async(Pe,Cn)=>{if(Cn==="removed")Rg.add(Pe),Tn.delete(Pe);else if(Cn==="absent")Tn.delete(Pe);else tp.add(Pe);ge={...ge,owned_plugins:[...Tn]},await sr(o.preparingRecord,ge)});Fr(t,{stage:"config",status:"completed",message:"Root configuration published"}),Fr(t,{stage:"verification",status:"started",message:"Verifying installation"}),await jK(o,m,f,{browserUse:x.browser_use,computerUse:x.computer_use,frontend:Pt.frontend,security:Pt.security},cl,yo.preserved,il),Fr(t,{stage:"verification",status:"completed",message:"Installation verified"});let $R=cg(x),DL=await lg({owner:"holycodex",install_id:D,version:P,profile:m,tier:f,optional_selections:x,explicit_optional_selections:v,official_plugins:I,capability_state:$R,managed_artifacts:yo.managed_artifacts,managed_config:cl,plugin_config:{plugin_id:un,before:ho,after:rp},provider_config:DR,plugin_snapshot:sl,owned_plugins:[...Tn],...L===void 0?{}:{tooling:L}}),Eg={owner:"holycodex",schema_epoch:On,install_id:D,version:P,digest:DL,profile:m,tier:f,optional_selections:x,explicit_optional_selections:v,official_plugins:I,capability_state:$R,managed_artifacts:yo.managed_artifacts,installed_at:et,status:"active",step:"active",managed_config:cl,plugin_snapshot:sl,plugin_config:{plugin_id:un,before:ho,after:rp},provider_config:DR,owned_plugins:[...Tn],...L===void 0?{}:{tooling:L}};if(Ie(Uc,Eg)===void 0)throw new _("state_corrupt","The HolyCodex configuration is invalid.");return AR=!0,await jc(o.activeRecord,sn(Eg)),PR=!0,await eL(o,nL(m,f,x,C)),await sg(o.preparingRecord),await sg(o.conflictedRecord),Fr(t,{stage:"complete",status:"completed",message:"HolyCodex installation complete"}),{record:Eg,optional_plugins:I,preserved:yo.preserved,warnings:[...yo.preserved.length===0?[]:["modified managed files were preserved"],...k===void 0?[]:[k]]}}catch(A){let L=[],G;if(AR)try{if(l===void 0)await $d(o.activeRecord,{force:!1}).catch((Z)=>{if(!We(Z,"ENOENT"))throw Z});else await vt(o.activeRecord,l)}catch{L.push("active_record")}if(PR)try{if(i===void 0)await $d(o.installOptions,{force:!1}).catch((Z)=>{if(!We(Z,"ENOENT"))throw Z});else await vt(o.installOptions,i)}catch{L.push("install_options")}if(IR||vg)try{if(Ur!==void 0)G=await $K(o.configFile,ge,Ur,Tg)}catch{L.push("config")}if(kR)try{await IK(o.configFile,Hn)}catch{L.push("invalid_config")}if(yo!==void 0)try{if((await Vh(yo.rollback)).preserved.length>0)L.push("roles")}catch{L.push("roles")}if(Cg.size>0)L.push(...[...Cg].map((Z)=>`plugin:${Z}`));for(let Z of ER)try{await S.remove?.(Z)}catch{L.push(`plugin:${Z}`)}for(let Z of new Set([...Rg,...tp]))try{await JK({list:()=>S.list(),add:(Be)=>S.add(Be)},Z,sl.find((Be)=>Be.plugin_id===Z)?.status),Rg.delete(Z),tp.delete(Z),Tn.add(Z),ge={...ge,owned_plugins:[...Tn]},await sr(o.preparingRecord,ge)}catch{Tn.add(Z),tp.add(Z),ge={...ge,owned_plugins:[...Tn]},await sr(o.preparingRecord,ge).catch(()=>{return}),L.push(`plugin:${Z}`)}if(O?.ownership==="holycodex"&&c?.tooling?.context7?.ownership!=="holycodex")try{if(!await Pd(M,O))L.push("context7")}catch{L.push("context7")}if(L.length===0&&it===void 0)try{if((await ye(o.configFile))?.trim().length===0&&await WK(o.configFile,G??Og))await $d(o.configFile,{force:!1})}catch{L.push("config_initialization")}if(L.length>0){try{let Be=Jt(await ye(o.configFile),o.configFile),ze=ge.plugin_config,ut=await og(Be),tt=ze===void 0?void 0:{...ze,after:{preference:ut.preference.digest===ze.before.preference.digest?ze.before.preference:ze.after.preference,marketplace:ut.marketplace.digest===ze.before.marketplace.digest?ze.before.marketplace:ze.after.marketplace}},pa=ge.provider_config,qt=await ig(Be,pa?.map((dr)=>dr.plugin_id)??[]),li=pa?.map((dr)=>{let $r=qt.find((np)=>np.plugin_id===dr.plugin_id);return $r!==void 0&&$r.before.digest===dr.before.digest?{...dr,after:dr.before}:dr});ge={...ge,...tt===void 0?{}:{plugin_config:tt},...li===void 0?{}:{provider_config:li}}}catch{}let Z=!1;try{await sr(o.conflictedRecord,{...ge,step:"conflicted",status:"conflicted"}),Z=!0}catch{}if(Z)await sg(o.preparingRecord).catch(()=>{return})}else await sg(o.preparingRecord).catch(()=>{return});if(A instanceof nr)throw A;if(A instanceof _)throw A;throw new _(A instanceof uo||A instanceof oi?"capability_denied":"install_failed",Ud(A),A,L.length>0?{recovery:"Resolve conflicted state before retrying."}:{})}}async function oa(e){let t=await wv(e.activeRecord,gd);if(t===void 0)return;let n=t.optional_selections,o=typeof n==="object"&&n!==null&&!Array.isArray(n)&&Object.prototype.hasOwnProperty.call(n,"work")?void 0:Ie(Uc,t);if(o!==void 0){if(!await bs(o))throw new _("state_corrupt","The existing HolyCodex configuration has an invalid digest.");return await _d(e.activeRecord,t),o}let i=Ie(oF,t);if(i===void 0)throw new _("state_corrupt","The HolyCodex configuration is invalid.");if(!await iL(i))throw new _("state_corrupt","The existing HolyCodex configuration has an invalid digest.",void 0,{path:e.activeRecord});let a="profile"in i&&i.profile!==void 0?i.profile:("plan"in i)?i.plan:void 0;if(a===void 0)throw new _("state_corrupt","The persisted installation has neither profile nor legacy plan state.",void 0,{path:e.activeRecord});let s;try{s=ah(a)}catch(P){throw new _("state_corrupt",`The persisted profile ${a} was removed and requires an explicit replacement.`,P,{path:e.activeRecord,profile:a})}let c="plan"in i?Object.fromEntries(Object.entries(i).filter(([P])=>P!=="plan")):i,{optional_selections:l,explicit_optional_selections:u}=i,d={browser_use:l.browser_use??en.browser_use,computer_use:l.computer_use,sites:l.sites??en.sites,coding:!0},p={...u.computer_use===void 0?{}:{computer_use:u.computer_use},...u.browser_use===void 0?{}:{browser_use:u.browser_use},...u.sites===void 0?{}:{sites:u.sites}},m=i.capability_state===void 0?void 0:cg(d,new Map([["browser_use","missing"],["sites","missing"]])),f=(i.official_plugins??[]).filter((P)=>!qd(P)),y=i.owned_plugins?.filter((P)=>!qd(P)),g=i.provider_config?.filter((P)=>!qd(P.plugin_id)),x=i.plugin_snapshot?.filter((P)=>!qd(P.plugin_id)),{optional_selections:v,explicit_optional_selections:C,capability_state:M,official_plugins:N,owned_plugins:O,provider_config:k,plugin_snapshot:I,...S}=c,D={...S,profile:s,optional_selections:d,explicit_optional_selections:p,official_plugins:f,...m===void 0?{}:{capability_state:m},...y===void 0?{}:{owned_plugins:y},...g===void 0?{}:{provider_config:g},...x===void 0?{}:{plugin_snapshot:x},digest:await lg({owner:i.owner,install_id:i.install_id,version:i.version,profile:s,tier:i.tier,optional_selections:d,explicit_optional_selections:p,official_plugins:f,capability_state:m??null,managed_artifacts:i.managed_artifacts,...i.managed_config===void 0?{}:{managed_config:i.managed_config},...i.plugin_config===void 0?{}:{plugin_config:i.plugin_config},...g===void 0?{}:{provider_config:g},...x===void 0?{}:{plugin_snapshot:x},...y===void 0?{}:{owned_plugins:y},...i.tooling===void 0?{}:{tooling:i.tooling}})};return ZF.set(D,i.digest),await _d(e.activeRecord,t),D}async function Nr(e,t){let n=await wv(e,gd);if(n===void 0)return;let r=Ie(ta,n);if(r!==void 0)return await _d(e,n),r;let o=Ie(sF,n);if(o===void 0)throw new _("state_corrupt","The HolyCodex transaction state is invalid.",void 0,{path:e});let i=o,a=i.profile??i.plan;if(typeof a!=="string")throw new _("state_corrupt","The HolyCodex transaction has no profile.",void 0,{path:e});let s;try{s=ah(a)}catch(S){throw new _("state_corrupt","The persisted transaction profile requires an explicit replacement.",S,{path:e,profile:a})}let{optional_selections:c,explicit_optional_selections:l}=i,u={browser_use:c.browser_use??en.browser_use,computer_use:c.computer_use??!1,sites:c.sites??en.sites,coding:!0},d={...l.browser_use===void 0?{}:{browser_use:l.browser_use},...l.computer_use===void 0?{}:{computer_use:l.computer_use},...l.sites===void 0?{}:{sites:l.sites}},m=i.capability_state===void 0?void 0:cg(u,new Map([["browser_use","missing"],["sites","missing"]])),{plan:f,profile:y,optional_selections:g,explicit_optional_selections:x,capability_state:v,...C}=i,M=typeof C.digest==="string"?C.digest:void 0,N=t===void 0?void 0:ZF.get(t),O=t!==void 0&&C.install_id===t.install_id&&(M===t.digest||N!==void 0&&M===N)?t.digest:M,k={...C,profile:s,optional_selections:u,explicit_optional_selections:d,...m===void 0?{}:{capability_state:m},...O===void 0?{}:{digest:O}},I=Ie(ta,k);if(I===void 0)throw new _("state_corrupt","The migrated transaction state is invalid.",void 0,{path:e});return await _d(e,n),I}function oL(e){return{browser_use:e.browser_use,computer_use:e.computer_use,sites:e.sites}}function Jt(e,t="config.toml"){if(e===void 0||e.trim().length===0)return{};try{let n=globalThis.Bun,r=n?.TOML?.parse?n.TOML.parse(e):bd(e),o=Ie(os,r);if(o===void 0){let i=Yv(r),a=i===void 0?"an unsupported TOML value":`the TOML value ${i}`;throw new _("state_corrupt",`${t} contains ${a} that HolyCodex cannot preserve. Convert it to a string, number, boolean, table, or array, then retry.`,void 0,{path:t,...i===void 0?{}:{key:i},reason:"unsupported_toml_value"})}return o}catch(n){if(n instanceof _)throw n;let r=Ud(n),o=AK(e,r),i=o===void 0?`${t} contains invalid TOML: ${r}. Fix the TOML syntax and retry; HolyCodex cannot safely rewrite malformed TOML.`:`${t} contains invalid TOML at line ${o.line}, column ${o.column} (offset ${o.offset}): ${r}. Fix the syntax at that location and retry; HolyCodex cannot safely rewrite malformed TOML.`;throw new _("state_corrupt",i,n,{path:t,parser_message:r,...o===void 0?{}:o,reason:"invalid_toml_syntax"})}}function Yv(e,t=[]){if(e===null||typeof e==="string"||typeof e==="boolean")return;if(typeof e==="number")return Number.isFinite(e)?void 0:Wv(t);if(Array.isArray(e)){for(let[n,r]of e.entries()){let o=Yv(r,[...t,"["+n+"]"]);if(o!==void 0)return o}return}if(typeof e==="object"&&e!==null){let n=Object.getPrototypeOf(e);if(n!==Object.prototype&&n!==null)return Wv(t);for(let[r,o]of Object.entries(e)){let i=Yv(o,[...t,r]);if(i!==void 0)return i}return}return Wv(t)}function Wv(e){return e.length===0?"<root>":e.join(".")}function CK(e,t){let n=new Map;for(let r of t)for(let o of OK(r)){let i=fe(e,o);if(i!==void 0&&!ii(i))n.set(o,i)}return[...n].map(([r,o])=>({key:r,value:o}))}function OK(e){let t=[],n=!1,r=!1;for(let o=0;o<e.length;o+=1){let i=e[o];if(n){if(r)r=!1;else if(i==="\\")r=!0;else if(i==='"')n=!1;continue}if(i==='"')n=!0;else if(i===".")t.push(e.slice(0,o))}return t}function kK(e,t){let n=JSON.stringify(t.value);return new _("state_corrupt",`${e} has the non-table value ${n} at ${t.key}, but the HolyCodex installer needs that path to be a table. Remove it after review or convert it to a table and retry; replacing it automatically could discard user configuration.`,void 0,{path:e,key:t.key,existing:n,reason:"expected_table"})}async function EK(e,t,n,r){let o=CK(n,r).map((a)=>{let s=kK(t,a);return cr({identity:`invalid-config:${t}:${a.key}`,category:"invalid-config",target:a.key,existing:a.value,desired:`Remove the conflicting value at ${a.key} so HolyCodex can create the required table.`,explanation:`${s.message} Choose remove to continue or cancel to repair it manually.`,path:t,key:a.key,action:"remove",defaultDecision:"remove",validDecisions:["remove","cancel"]})});if(o.length===0)return{document:n,conflicts:o,decisions:new Map};let i=await jd(e,o,!0);return{document:Xc(n,o,i.decisions),conflicts:o,decisions:i.decisions}}function Xc(e,t,n){let r=e;for(let o of t){if(n.get(o.identity)!=="remove"||o.key===void 0)throw new _("confirmation_required",`Invalid configuration at ${o.target} can only be removed after review or cancelled.`,void 0,{path:o.path,...o.key===void 0?{}:{key:o.key},existing:JSON.stringify(o.existing),valid_decisions:o.validDecisions??["remove","cancel"]});let a=fe(r,o.key);if(a===void 0)continue;if(JSON.stringify(a)!==JSON.stringify(o.existing))throw new _("confirmation_required",`Invalid configuration at ${o.key} changed after review; review the current value and retry.`,void 0,{path:o.path,key:o.key,reviewed:JSON.stringify(o.existing),current:JSON.stringify(a)});r=tr(r,o.key)}return r}async function zv(e,t,n){if(await ye(e)!==n)throw new _("confirmation_required","Codex configuration changed during preflight validation; review the latest configuration and retry.",void 0,{path:e});if(t===void 0){await $d(e,{force:!1}).catch((r)=>{if(!We(r,"ENOENT"))throw r});return}await vt(e,t)}async function IK(e,t){let n=await ye(e),r=Jt(n,e),o=r;for(let i of t){if(i.key===void 0||i.existing===void 0)continue;let a=fe(o,i.key);if(a!==void 0){if(JSON.stringify(a)===JSON.stringify(i.existing))continue;if(!(typeof a==="object"&&a!==null&&!Array.isArray(a)&&Object.keys(a).length===0))throw new _("confirmation_required",`Codex configuration at ${i.key} changed during rollback; preserve it and review the current value.`,void 0,{path:e,key:i.key});o=tr(o,i.key)}o=so(o,i.key,i.existing)}if(o===r)return;if(await ye(e)!==n)throw new _("confirmation_required","Codex configuration changed during rollback; preserve it and review the current value.",void 0,{path:e});await vt(e,fo(o))}function AK(e,t){let n,r=/found \(0x([0-9a-f]{2})\)/iu.exec(t),o=/found '((?:\\.|[^'])*)'/u.exec(t),i=r===null?o?.[1]?.replaceAll("\\'","'").replaceAll("\\\"",'"'):String.fromCharCode(Number.parseInt(r[1],16));if(i!==void 0)n=PK(e,i);else if(/end of file|unterminated/iu.test(t))n=e.length;else if(/missing value after/iu.test(t)){let c=e.lastIndexOf("="),l=c<0?-1:e.indexOf(`
42
- `,c+1);n=l<0?e.length:l}if(n===void 0)return;let a=e.slice(0,n).split(`
11
+ `)}return t},kt;var Kl=L(()=>{lx();ji();ln();ii();sr();$t();Lk={[Px]:Px,...cx({label:"Service",evaluate(e){return gt(wn(e.context,this))}}),toJSON(){return{_id:"Service",key:this.key}},of(e){return e},context(e){return pp(this,e)},use(e){return Bt((t)=>e(wn(t.context,this)))},useSync(e){return Bt((t)=>gt(e(wn(t.context,this))))}},Ax=new Set,dp=Symbol(),jk={get mapUnsafe(){return Dx(this)},...Wi,[Mx]:{_Services:(e)=>e},toJSON(){return{_id:"Context",services:Array.from(this.mapUnsafe).map(([e,t])=>({key:e,value:t}))}},[et](e){if(!Bk(e))return!1;let t=this.mapUnsafe,n=e.mapUnsafe;if(t.size!==n.size)return!1;for(let[r,i]of t)if(!n.has(r)||!mt(i,n.get(r)))return!1;return!0},[Qe](){return ss(this.mapUnsafe.size)}},qk=Wl(new Map),Ux=Y(3,(e,t,n)=>zk(e,t.key,n)),$x=Y(2,(e,t)=>{let n=Fx(e,t.key);if(n===dp){if(Vk(t))return Jk(t);throw Wk(t)}return n}),wn=$x,kt=Ox});var Zl="~effect/Duration",Ko,Hx,Hk,Kk,jx,Gl,gp,Bx,Xl=(e)=>BigInt(e<0?Math.ceil(e-0.5):Math.floor(e+0.5)),Kx=(e)=>Xl(e*1e6),Vx=(e,t)=>{let n=e.indexOf(".");if(n===-1)return BigInt(e)*t;let r=e[0]==="-",i=e.slice(n+1),o=Kk**BigInt(i.length),a=(BigInt(e.slice(r?1:0,n))*o+BigInt(i))*t,s=a/o+(a%o*Hk>=o?Hx:Ko);return r?-s:s},Gk,Ss=(e)=>{switch(typeof e){case"number":return Wx(e);case"bigint":return Yl(e);case"string":{if(e==="Infinity")return hp;if(e==="-Infinity")return Jx;let t=Gk.exec(e);if(!t)break;let[n,r,i]=t;if(i==="nano"||i==="nanos")return Yl(Vx(r,Hx));if(i==="micro"||i==="micros")return Yl(Vx(r,gp));let o=Number(r);switch(i){case"milli":case"millis":return Wx(o);case"second":case"seconds":return iR(o);case"minute":case"minutes":return oR(o);case"hour":case"hours":return aR(o);case"day":case"days":return sR(o);case"week":case"weeks":return cR(o)}break}case"object":{if(e===null)break;if(Zl in e)return e;if(Array.isArray(e)){if(e.length!==2||!e.every(is))return qx(e);if(Number.isNaN(e[0])||Number.isNaN(e[1]))return rR;if(e[0]===-1/0||e[1]===-1/0)return Jx;if(e[0]===1/0||e[1]===1/0)return hp;return Vt(Xl(e[0]*1e9+e[1]))}let t=e,n=0;if(t.weeks)n+=t.weeks*604800000;if(t.days)n+=t.days*86400000;if(t.hours)n+=t.hours*3600000;if(t.minutes)n+=t.minutes*60000;if(t.seconds)n+=t.seconds*1000;if(t.milliseconds)n+=t.milliseconds;if(!t.microseconds&&!t.nanoseconds)return Vt(n);return Vt(Xl(n*1e6+(t.microseconds??0)*1000+(t.nanoseconds??0)))}}return qx(e)},qx=(e)=>{throw Error(`Invalid Input: ${e}`)},zx,Yk,Zk,Xk,Vt=(e)=>{let t=Object.create(Xk);if(typeof e==="number")if(isNaN(e)||e===0||Object.is(e,-0))t.value=zx;else if(!Number.isFinite(e))t.value=e>0?Yk:Zk;else if(!Number.isInteger(e))t.value={_tag:"Nanos",nanos:Kx(e)};else t.value={_tag:"Millis",millis:e};else if(e===Ko)t.value=zx;else t.value={_tag:"Nanos",nanos:e};return t},Qk=(e)=>we(e,Zl),eR=(e)=>{switch(e.value._tag){case"Millis":return e.value.millis===0;case"Nanos":return e.value.nanos===Ko;case"Infinity":case"NegativeInfinity":return!1}},tR=(e)=>{switch(e.value._tag){case"Millis":return e.value.millis<0;case"Nanos":return e.value.nanos<Ko;case"NegativeInfinity":return!0;case"Infinity":return!1}},nR=(e)=>{switch(e.value._tag){case"Infinity":case"NegativeInfinity":return hp;case"Millis":return e.value.millis<0?Vt(-e.value.millis):e;case"Nanos":return e.value.nanos<Ko?Vt(-e.value.nanos):e}},rR,hp,Jx,Yl=(e)=>Vt(e),Wx=(e)=>Vt(e),iR=(e)=>Vt(e*1000),oR=(e)=>Vt(e*60000),aR=(e)=>Vt(e*3600000),sR=(e)=>Vt(e*86400000),cR=(e)=>Vt(e*604800000),Gx=(e)=>lR(Ss(e),{onMillis:Xe,onNanos:(t)=>Number(t)/1e6,onInfinity:()=>1/0,onNegativeInfinity:()=>-1/0}),yp=(e)=>{let t=Ss(e);switch(t.value._tag){case"Infinity":case"NegativeInfinity":throw Error("Cannot convert infinite duration to nanos");case"Nanos":return t.value.nanos;case"Millis":return Kx(t.value.millis)}},lR,uR,fR=(e,t)=>uR(e,t,{onMillis:(n,r)=>n===r,onNanos:(n,r)=>n===r,onInfinity:(n,r)=>n.value._tag===r.value._tag}),dR,pR=(e)=>{if(e.value._tag==="Infinity")return{days:1/0,hours:1/0,minutes:1/0,seconds:1/0,millis:1/0,nanos:1/0};if(e.value._tag==="NegativeInfinity")return{days:-1/0,hours:-1/0,minutes:-1/0,seconds:-1/0,millis:-1/0,nanos:-1/0};let t=yp(e),n=t<Ko,r=n?-t:t,i=r/Bx,o=i/gp,a=o/Gl,s=a/Gl,c=s/jx,f=n?-1:1;return{days:f*Number(c),hours:f*Number(s%jx),minutes:f*Number(a%Gl),seconds:f*Number(o%Gl),millis:f*Number(i%gp),nanos:f*Number(r%Bx)}},Sp=(e)=>{if(e.value._tag==="Infinity")return"Infinity";if(e.value._tag==="NegativeInfinity")return"-Infinity";if(eR(e))return"0";if(tR(e))return"-"+Sp(nR(e));let t=pR(e),n=[];if(t.days!==0)n.push(`${t.days}d`);if(t.hours!==0)n.push(`${t.hours}h`);if(t.minutes!==0)n.push(`${t.minutes}m`);if(t.seconds!==0)n.push(`${t.seconds}s`);if(t.millis!==0)n.push(`${t.millis}ms`);if(t.nanos!==0)n.push(`${t.nanos}ns`);return n.join(" ")};var Yx=L(()=>{ji();ln();ii();Uo();Ir();$t();Ko=BigInt(0),Hx=BigInt(1),Hk=BigInt(2),Kk=BigInt(10),jx=BigInt(24),Gl=BigInt(60),gp=BigInt(1000),Bx=BigInt(1e6),Gk=/^(-?\d+(?:\.\d+)?)\s+(nanos?|micros?|millis?|seconds?|minutes?|hours?|days?|weeks?)$/,zx={_tag:"Millis",millis:0},Yk={_tag:"Infinity"},Zk={_tag:"NegativeInfinity"},Xk={[Zl]:Zl,[Qe](){switch(this.value._tag){case"Millis":{let e=this.value.millis*1e6;return Number.isFinite(e)?Ce(Xl(e)):ss(this.value.millis)}case"Nanos":return Ce(this.value.nanos);default:return Wd(this.value)}},[et](e){return Qk(e)&&dR(this,e)},toString(){switch(this.value._tag){case"Infinity":return"Infinity";case"NegativeInfinity":return"-Infinity";case"Nanos":return`${this.value.nanos} nanos`;case"Millis":return`${this.value.millis} millis`}},toJSON(){switch(this.value._tag){case"Millis":return{_id:"Duration",_tag:"Millis",millis:this.value.millis};case"Nanos":return{_id:"Duration",_tag:"Nanos",nanos:String(this.value.nanos)};case"Infinity":return{_id:"Duration",_tag:"Infinity"};case"NegativeInfinity":return{_id:"Duration",_tag:"NegativeInfinity"}}},[Bi](){return this.toJSON()},pipe(){return en(this,arguments)}},rR=Vt(0),hp=Vt(1/0),Jx=Vt(-1/0),lR=Y(2,(e,t)=>{switch(e.value._tag){case"Millis":return t.onMillis(e.value.millis);case"Nanos":return t.onNanos(e.value.nanos);case"Infinity":return t.onInfinity();case"NegativeInfinity":return(t.onNegativeInfinity??t.onInfinity)()}}),uR=Y(3,(e,t,n)=>{if(e.value._tag==="Infinity"||e.value._tag==="NegativeInfinity"||t.value._tag==="Infinity"||t.value._tag==="NegativeInfinity")return n.onInfinity(e,t);if(e.value._tag==="Millis")return t.value._tag==="Millis"?n.onMillis(e.value.millis,t.value.millis):n.onNanos(yp(e),t.value.nanos);else return n.onNanos(e.value.nanos,yp(t))}),dR=Y(2,(e,t)=>fR(e,t))});var xp=(e)=>e.length>0;var cr,pn,Me,Ve,Zx,Ql;var bt=L(()=>{ln();_x();cr=bx,pn=Ex,Me=op,Ve=ap,Zx=Y(2,(e,t)=>Me(e)?pn(t(e.failure)):e),Ql=Y(2,(e,{onFailure:t,onSuccess:n})=>Me(e)?t(e.failure):n(e.success))});var Ep,vp=(e)=>Ep.isArray(e)?e:Ep.from(e),bp,aU,_p,Xx,eu=()=>[],Qx;var tu=L(()=>{ln();Ep=globalThis.Array,bp=Y(2,(e,t)=>[...e,t]),aU=Ep.isArray,_p=xp,Xx=xp,Qx=Y(2,(e,t)=>e.map(t))});class nE{buckets=[];scheduleTask(e,t){let n=this.buckets,r=n.length,i,o=0;for(;o<r;o++){if(n[o][0]>t)break;i=n[o]}if(i&&i[0]===t)i[1].push(e);else if(o===r)n.push([t,[e]]);else n.splice(o,0,[t,[e]])}drain(){let e=this.buckets;return this.buckets=[],e}}class nu{executionMode;setImmediate;constructor(e="async",t){this.executionMode=e,this.setImmediate=t??(e==="sync"?eE:tE)}shouldYield(e){return e.currentOpCount>=e.cache.maxOpsBeforeYield}makeDispatcher(){return new rE(this.setImmediate)}}class rE{tasks=new nE;running=void 0;setImmediate;constructor(e=tE){this.setImmediate=e}scheduleTask(e,t){if(this.tasks.scheduleTask(e,t),this.running===void 0)this.running=this.setImmediate(this.afterScheduled)}afterScheduled=()=>{this.running=void 0,this.runTasks()};runTasks(){let e=this.tasks.drain();for(let t=0;t<e.length;t++){let n=e[t][1];for(let r=0;r<n.length;r++)n[r]()}}flush(){while(this.tasks.buckets.length>0){if(this.running!==void 0)this.running(),this.running=void 0;this.runTasks()}}}var Cp,eE=(e)=>{let t=!1;return Promise.resolve().then(()=>{if(!t)e()}),()=>{t=!0}},hR,tE=(e)=>{try{return hR(e)}catch{return eE(e)}},iE,oE;var aE=L(()=>{Kl();Cp=kt("effect/Scheduler",{fiberCached:!0,defaultValue:()=>new nu}),hR="setImmediate"in globalThis?(e)=>{let t=globalThis.setImmediate(e);return()=>globalThis.clearImmediate(t)}:(e)=>{let t=setTimeout(e,0);return()=>clearTimeout(t)};iE=kt("effect/Scheduler/MaxOpsBeforeYield",{fiberCached:!0,defaultValue:()=>2048}),oE=kt("effect/Scheduler/PreventSchedulerYield",{fiberCached:!0,defaultValue:()=>!1})});var ru;var Tp=L(()=>{sr();ru=qo});var cE="~effect/encoding/EncodingError",xs;var lE=L(()=>{Tp();xs=class xs extends ru("EncodingError"){[cE]=cE}});var uE="effect/Tracer/ParentSpan",fE="effect/Tracer";var dE=()=>{};var pE="effect/Metric/FiberRuntimeMetrics";var mE,gE,kp,hE,yE,SE;var xE=L(()=>{Kl();ln();mE=kt("effect/References/CurrentStackFrame",{fiberCached:!0,defaultValue:Xa}),gE=kt("effect/References/TracerEnabled",{fiberCached:!0,defaultValue:$d}),kp=kt("effect/References/CurrentLogAnnotations",{defaultValue:()=>({})}),hE=kt("effect/References/CurrentLogLevel",{fiberCached:!0,defaultValue:()=>"Info"}),yE=kt("effect/References/MinimumLogLevel",{fiberCached:!0,defaultValue:()=>"Info"}),SE=kt("effect/References/CurrentLogSpans",{defaultValue:()=>[]})});class Lv{waiters=[];scheduled=void 0;_isOpen;constructor(e){this._isOpen=e}scheduleUnsafe(e){if(this.waiters.length===0)return bE;if(this.scheduled===void 0)this.scheduled=this.waiters,e.currentDispatcher.scheduleTask(this.flushScheduled,0);else for(let t=0;t<this.waiters.length;t++)this.scheduled.push(this.waiters[t]);return this.waiters=[],bE}flushScheduled=()=>{if(this.scheduled===void 0)return;let e=this.scheduled;this.scheduled=void 0;for(let t=0;t<e.length;t++)e[t](jn)};flushWaiters(){let e=this.waiters;this.waiters=[],this.flushScheduled();for(let t=0;t<e.length;t++)e[t](jn)}open=Bt((e)=>{if(this._isOpen)return _E;return this._isOpen=!0,this.scheduleUnsafe(e)});release=Bt((e)=>this._isOpen?_E:this.scheduleUnsafe(e));openUnsafe(){if(this._isOpen)return!1;return this._isOpen=!0,this.flushWaiters(),!0}await=lr((e)=>{if(this._isOpen)return e(It);return this.waiters.push(e),Cn(()=>{let t=this.waiters.indexOf(e);if(t!==-1)this.waiters.splice(t,1);else if(this.scheduled!==void 0){if(t=this.scheduled.indexOf(e),t!==-1)this.scheduled.splice(t,1)}})});closeUnsafe(){if(!this._isOpen)return!1;return this._isOpen=!1,!0}close=Cn(()=>this.closeUnsafe());whenOpen=(e)=>_t(this.await,()=>e);isOpen(){return this._isOpen}}class Uv{currentTimeMillisUnsafe(){return Date.now()}currentTimeMillis=Cn(()=>this.currentTimeMillisUnsafe());currentTimeNanosUnsafe(){return GR()}currentTimeNanos=Cn(()=>this.currentTimeNanosUnsafe());monotonicTimeNanosUnsafe(){return jv()}monotonicTimeNanos=Cn(()=>this.monotonicTimeNanosUnsafe());sleep(e){return this.sleepMillis(Gx(e))}sleepMillis(e){if(e<=0)return Dp;else if(!Number.isFinite(e))return Fp;return lr((t)=>{let n=e>Rp?this.sleepMillis(e-Rp):It,r=setTimeout(()=>t(n),Math.min(e,Rp));return Cn(()=>clearTimeout(r))})}}var wE,CE=(e)=>new Ar([new wE(e)]),TE=(e)=>{let t=e.reasons.find(si);return t?cr(t):pn(e)},bs=(e)=>{for(let t=0;t<e.reasons.length;t++){let n=e.reasons[t];if(n._tag==="Fail")return cr(n.error)}return pn(e)},kE=(e)=>e.reasons.some(Vl),bR=(e,t)=>{let n=new Map,r=[];for(let i of e.concat(t)){let o=Ce(i),a=n.get(o);if(a===void 0)n.set(o,[i]);else if(a.some((s)=>mt(s,i)))continue;else a.push(i);r.push(i)}return r},ou,RE,au=(e)=>{let t;for(let n of e.reasons){if(n._tag==="Fail")return n.error;if(n._tag==="Die")t??=n}if(t!==void 0)return t.defect;if(e.reasons.length>0)return new globalThis.Error("All fibers interrupted without error");return new globalThis.Error("Empty cause")},IE=(e,t)=>{let n=[],r=[];if(e.reasons.length===0)return n;let i=$o();if(i!==0)jo(1);try{for(let o of e.reasons){if(o._tag==="Interrupt"){r.push(o);continue}n.push(Ip(o._tag==="Die"?o.defect:o.error,o.annotations,t))}if(n.length===0){let o=Error("The fiber was interrupted by:");o.name="InterruptCause",o.stack=TR(o,r);let a=new globalThis.Error("All fibers interrupted without error",{cause:o});a.name="InterruptError",a.stack=`${a.name}: ${a.message}`,n.push(Ip(a,r[0].annotations,t))}}finally{if(i!==0)jo(i)}return n},Ip=(e,t,n)=>{let r=typeof e,i;if(e&&r==="object"){if(i=new globalThis.Error(_R(e),{cause:e.cause?Ip(e.cause):void 0}),typeof e.name==="string")i.name=e.name;if(typeof e.stack==="string")i.stack=CR(e.stack,i,t);else{let o=`${i.name}: ${i.message}`;i.stack=t?PE(o,t):o}if(n?.includeCauseInStack)i.stack=AE(i);for(let o of Object.keys(e))if(!(o in i))i[o]=e[o]}else i=new globalThis.Error(!e?`Unknown error: ${e}`:r==="string"?e:ls(e));return i},_R=(e)=>{if(typeof e.message==="string")return e.message;else if(typeof e.toString==="function"&&e.toString!==Object.prototype.toString&&e.toString!==Array.prototype.toString)try{return e.toString()}catch{}return ls(e)},wR,CR=(e,t,n)=>{let r=`${t.name}: ${t.message}`,i=(e.startsWith(r)?e.slice(r.length):e).split(`
12
+ `),o=[r];for(let a=1;a<i.length;a++){if(/Generator\.next|~effect\/(?:Effect|Utils)/.test(i[a]))break;o.push(i[a])}return n?PE(o.join(`
13
+ `),n):o.join(`
14
+ `)},PE=(e,t)=>{let n=t?.get(ql.key);if(n)e=`${e}
15
+ ${OE(n)}`;return e},TR=(e,t)=>{let n=[`${e.name}: ${e.message}`];for(let r of t){let i=r.fiberId!==void 0?`#${r.fiberId}`:"unknown",o=r.annotations.get(ep.key);if(n.push(` at fiber (${i})`),o)n.push(OE(o))}return n.join(`
16
+ `)},OE=(e)=>{let t=[],n=e,r=0;while(n&&r<10){let i=n.stack();if(i){let o=i.matchAll(wR),a=!1;for(let[,s]of o)a=!0,t.push(` at ${n.name} (${s})`);if(!a)t.push(` at ${n.name} (${i.replace(/^at /,"")})`)}else t.push(` at ${n.name}`);n=n.parent,r++}return t.join(`
17
+ `)},Mp=(e)=>IE(e).map(AE).join(`
18
+ `),AE=(e)=>e.cause?`${e.stack} {
19
+ ${ME(e.cause," ")}
20
+ }`:e.stack,ME=(e,t)=>{let n=e.stack.split(`
21
+ `),r=`${t}[cause]: ${n[0]}`;for(let i=1,o=n.length;i<o;i++)r+=`
22
+ ${t}${n[i]}`;if(e.cause)r+=` {
23
+ ${ME(e.cause,`${t} `)}
24
+ ${t}}`;return r},NE="~effect/Fiber",kR,RR,DE=()=>globalThis[Fo],Np,IR=(e)=>{let t=Hl(e,fE);return{scheduler:wn(e,Cp),tracer:t,tracerContext:t?t.context:void 0,tracerEnabled:wn(e,gE),span:Hl(e,uE),logLevel:wn(e,hE),minimumLogLevel:wn(e,yE),stackFrame:wn(e,mE),runtimeMetrics:Hl(e,pE),maxOpsBeforeYield:wn(e,iE),preventYield:wn(e,oE)}},PR,OR=32,EE,FE=(e)=>{if(!e.cache.stackFrame)return;let t=new Map;return t.set(ep.key,e.cache.stackFrame),Wl(t)},LE=(e)=>{let t=e;if(t._exit)return ht(t._exit);return lr((n)=>{if(t._exit)return n(ht(t._exit));return Cn(e.addObserver((r)=>n(ht(r))))})},UE=(e)=>lr((t)=>{let n=e[Symbol.iterator](),r=[],i=void 0;function o(){let a=n.next();while(!a.done){if(a.value._exit){r.push(a.value._exit),a=n.next();continue}i=a.value.addObserver((s)=>{r.push(s),o()});return}t(ht(r))}return o(),Cn(()=>i?.())}),vs=(e)=>Bt((t)=>{let n=FE(t),r=eu();for(let i of e)i.interruptUnsafe(t.id,n),r.push(i);return Up(UE(r))}),ht,yt,Ki,Cn,tn,$E,jE,Dp,BE=(e)=>tn(()=>yt(e())),_s=(e)=>ar(e),VE=(e)=>tn(()=>Ki(e())),It,qE=(e)=>{let t=typeof e==="function"?e:e.try,n=typeof e==="function"?(r)=>new pu(r,"An error occurred in Effect.try"):e.catch;return tn(()=>{try{return ht(t())}catch(r){return Ki(n(r))}})},zE=(e)=>{let t=typeof e==="function"?e:e.try,n=typeof e==="function"?(r)=>new pu(r,"An error occurred in Effect.tryPromise"):e.catch;return JE(function(r,i){let o=(a)=>{try{r(Ki(us(()=>n(a))))}catch(s){r(_s(s))}};try{t(i).then((a)=>r(ht(a)),o)}catch(a){o(a)}},t.length!==0)},JE,AR,lr=(e)=>JE(e,e.length>=2),Fp,WE=(...e)=>{if(e.length===1){let r=e[0];return tn(()=>iu(r()))}let[t,n]=e;return tn(()=>iu(n.call(t.self)))},MR=(e,t)=>Object.defineProperty(t,"length",{value:e,configurable:!0}),HE=(e,...t)=>MR(e.length,t.length===0?function(){return vE(()=>e.apply(this,arguments))}:function(){let n=vE(()=>e.apply(this,arguments));for(let r of t)n=r(n,...arguments);return n}),vE=(e)=>{try{let t=e(),n=void 0;while(!0){let r=t.next(n);if(r.done)return ht(r.value);let i=r.value;if(i&&i._tag==="Success"){n=i.value;continue}else if(i&&i._tag==="Failure")return r.value;else{let o=!0;return tn(()=>{if(o)return o=!1,_t(r.value,(a)=>iu(t,a));else return tn(()=>iu(e()))})}}}catch(t){return _s(t)}},iu,Yo,su=function(e){return e._stack.push(this),this[ie]},NR,ws=function(e,t,n){this[ie]=e,this[tt]=t,this.payload=n},KE=function(){return this.payload},Lp,DR=function(e,t){let n=this.payload;return t.succeedWith(Lp?n(e):us(()=>n(e)))},FR=function(e){let t=this.payload;return t(e)},GE=(e)=>Cs(e,Wo),Up=(e)=>new ws(e,KE,jn),YE=(e,t)=>Bt((n)=>{let r=new Set;return Hp(n,()=>r.size===0?void 0:vs(r)),lr((i)=>{let o=vp(e),a=o.length,s=0,c=!1,f=[],l=(u,g,h)=>{if(s++,u._tag==="Failure"){if(f.push(...u.cause.reasons),s>=a)i(yt(Bo(f)));return}let y=!c;if(c=!0,i(u),y&&t?.onWinner)t.onWinner({fiber:g,index:h,parentFiber:n})};for(let u=0;u<a;u++){let g=Yp(n,o[u],!0,!0,!1);if(r.add(g),g.addObserver((h)=>{r.delete(g),l(h,g,u)}),c)break}})}),ZE=(e,t)=>Bt((n)=>{let r=new Set;return Hp(n,()=>r.size===0?void 0:vs(r)),lr((i)=>{let o=!1,a=0;for(let s of e){if(o)break;let c=a++,f=Yp(n,s,!0,!0,!1);r.add(f),f.addObserver((l)=>{r.delete(f);let u=!o;if(o=!0,i(l),u&&t?.onWinner)t.onWinner({fiber:f,index:c,parentFiber:n})})}})}),XE,$p,_t,Ne=(e)=>e[qi]!==void 0,QE,ev=(e)=>_t(e,Xe),Cs,tv,nv,jp=(e)=>e._tag==="Success",rv=(e)=>e._tag==="Failure",iv=(e)=>e._tag==="Failure"?cr(e.cause):pn(e),jn,ov,av,Ts,LR,sv=function(e,t){this[ie]=e,this[fn]=t},cv,cu,lv,Bp,uv=(e)=>cu(e,_s),fv,Es=(e)=>pv(e,{onFailure:pn,onSuccess:cr}),Vp,UR,dv=function(e,t,n){this[ie]=e,this[tt]=t,this[fn]=n},$R=function(e,t){let n=this.payload;return t.succeedWith(Lp?n.onSuccess(e):us(()=>n.onSuccess(e)))},jR=(e,t)=>{let n=dn({op:e,[Be]:su,[tt]:$R,[fn]:t}),r=function(i,o){this[ie]=i,this.payload=o};return r.prototype=n,r},BR,qp,zp,pv,Jp=(e)=>Ne(e)?gt(e):VR(e),VR,mv,qR=(e)=>new em(`Operation timed out after '${Sp(e)}'`),gv,hv,yv=(e,t)=>jp(e)?t:Ts(t,(n)=>yt(ou(e.cause,n))),Sv,Wp=(e,t,n)=>new Sv(e,t,n),Hp=(e,t)=>{e._stack.push(new Sv(void 0,t,void 0))},Kp,xv,Ev,vv,bv=(e,t,n)=>Tv((r)=>_t(e,(i)=>Wp(tn(()=>r(t(i))),(o)=>n(i,o),!0))),_v=(e)=>Cn(()=>{let t=KR(!1),n=!1,r,i=_t(t.await,()=>r);return Bt((o)=>{if(r!==void 0)return r;if(n)return i;return n=!0,Hp(o,(a)=>Cn(()=>{r=a,t.openUnsafe()})),e})}),Gp=(e)=>Bt((t)=>{if(!t.interruptible)return e;return t.interruptible=!1,t._stack.push(lu),e}),wv,lu,zR,JR=(e)=>{if(e.interruptible=!0,e._stack.push(zR),e._interruptedCause)return yt(e._interruptedCause)},Cv=(e)=>Bt((t)=>{if(t.interruptible)return e;return JR(t)??e}),Tv=(e)=>Bt((t)=>{if(!t.interruptible)return e(Xe);return t.interruptible=!1,t._stack.push(lu),e(Cv)}),kv=(e,t)=>{if(BS(e))return t?.mode==="result"?Go(e,Es,t):Go(e,Xe,t);else if(t?.discard)return t.mode==="result"?Go(Object.values(e),Es,t):Go(Object.values(e),Xe,t);return tn(()=>{let n={};return Yo(Go(Object.entries(e),([r,i])=>Cs(t?.mode==="result"?Es(i):i,(o)=>{Or(n,r,o)}),{discard:!0,concurrency:t?.concurrency}),n)})},Rv,Go,WR=(e,t,n)=>tn(()=>{let r=n?.discard?void 0:[],i=e[Symbol.iterator](),o=i.next(),a=0;return Yo(Rv({while:()=>!o.done,body:()=>t(o.value,a++),step:(s)=>{if(r)r.push(s);o=i.next()}}),r)}),ks=(e)=>e==="unbounded"?Number.POSITIVE_INFINITY:Math.max(1,e??1),uu=()=>(e)=>{let{onItem:t,step:n}=e,r=(o,a,s,c,f)=>_t(Jp(f),(l)=>n(o,a[s],l,s)??i(o,a,s+1,c)??It),i=(o,a,s=0,c=a.length)=>{for(;s<c;s++){let f=a[s],l=t(o,f,s);if(!Ne(l))return r(o,a,s,c,l);let u=n(o,f,l,s);if(u)return u._tag==="Failure"?u:void 0}};return i},Iv=(e)=>{let{onItem:t,step:n}=e;return(r,i,o)=>{let a=0,s=o.end??i.length,c=o.concurrency,f=!1,l,u,g,h,y,S=(x)=>{let E=ar(x);return h=E,f=!0,u&&u.size>0?_t(Gp(vs(Array.from(u))),()=>h??E):E},m=()=>{let x=!1;for(;!h&&a<s;a++){let E=i[a],_=y??t(r,E,a);if(Ne(_)){if(h=n(r,E,_,a),h)break}else if(!l)return lr((C)=>{l=DE(),u=new Set,y=_,g=C;let N;try{N=m()}catch(D){return C(S(D))}if(N)return C(N);return tn(()=>(h??=jn,_t(u?vs(u):It,()=>h?._tag==="Failure"?h:It)))});else{y=void 0;let C=Yp(l,_,!0,!0,"inherit");if(C._exit){if(h=n(r,E,C._exit,a),h)break;continue}u.add(C);let N=a;if(C.addObserver((D)=>{u.delete(C);try{if(h){if(D._tag==="Failure"){let F=D.cause.reasons.filter((K)=>K._tag!=="Interrupt");if(F.length>0){let K=Bo(F);h=$n(h._tag==="Failure"?ou(h.cause,K):K)}}}else{let F=n(r,E,D,N);if(F)h=F,m()}if(x){let F=m();if(F)g(F)}else if(f&&u.size===0)g(h??It)}catch(F){g(S(F))}}),u.size<c)continue;x=!0,a++;return}}if(f=!0,h){if(u&&u.size>0){let E=FE(l);u.forEach((_)=>_.interruptUnsafe(l.id,E));return}if(g||h._tag==="Failure")return h}else if(g){if(!u)return jn;else if(u.size===0)g(It)}};return m()}},fu=()=>(e)=>Iv(e),HR,Yp=(e,t,n=!1,r=!1,i=!1)=>{let o=e,a=i==="inherit"?o.interruptible:!i,s=new Np(o.context,a);if(n)s.evaluate(t);else o.currentDispatcher.scheduleTask(()=>s.evaluate(t),0);if(!r&&!s._exit)o.children().add(s),s._parent=o;return s},du=(e)=>(t,n)=>{let r=new Np(n?.scheduler?Ux(e,Cp,n.scheduler):e,n?.uninterruptible!==!0);if(r.evaluate(t),r._exit)return r;if(n?.signal)if(n.signal.aborted)r.interruptUnsafe();else{let i=()=>r.interruptUnsafe();n.signal.addEventListener("abort",i,{once:!0}),r.addObserver(()=>n.signal.removeEventListener("abort",i))}if(n?.onFiberStart)n.onFiberStart(r);return r},Pv,Ov=(e)=>{let t=du(e);return(n,r)=>{let i=t(n,r);return new Promise((o)=>{i.addObserver((a)=>o(a))})}},Av=(e)=>{let t=Ov(e);return(n,r)=>t(n,r).then((i)=>{if(i._tag==="Failure")throw au(i.cause);return i.value})},Mv,Zp=(e)=>{let t=du(e);return(n)=>{if(Ne(n))return n;let r=new nu("sync"),i=t(n,{scheduler:r});return i._dispatcher?.flush(),i._exit??ar(new tm(i))}},Nv,Dv=(e)=>{let t=Zp(e);return(n)=>{let r=t(n);if(r._tag==="Failure")throw au(r.cause);return r.value}},Fv,bE,_E,KR=(e)=>new Lv(e??!1),Xp,Rp=2147483647,$v,jv,GR,Bv=(e)=>Bt((t)=>e(t.getRef(Xp))),Qp=(e)=>Bv((t)=>t.sleep(Ss(e))),Pp="~effect/Cause/TimeoutError",em,Op="~effect/Cause/AsyncFiberError",tm,Ap="~effect/Cause/UnknownError",pu,YR,ZR=(e)=>{switch(e){case"All":return Number.MIN_SAFE_INTEGER;case"Fatal":return 50000;case"Error":return 40000;case"Warn":return 30000;case"Info":return 20000;case"Debug":return 1e4;case"Trace":return 0;case"None":return Number.MAX_SAFE_INTEGER}},XR,QR,Vv,eI,tI="~effect/Logger",nI,qv=(e)=>{let t=Object.create(nI);return t.log=e,t},rI=(e)=>e.replace(/[\s="]/g,"_"),iI=(e,t)=>`${rI(e[0])}=${t-e[1]}ms`,zv=(e)=>(...t)=>{let n=void 0;for(let r=0,i=t.length;r<i;r++){let o=t[r];if(ps(o)){if(n)t.splice(r,1);else t=t.slice(0,r).concat(t.slice(r+1));n=n?Bo(n.reasons.concat(o.reasons)):o,r--}}if(n===void 0)n=Zd;return Bt((r)=>{let i=e??r.cache.logLevel;if(QR(r.cache.minimumLogLevel,i))return It;let o=r.getRef(Xp),a=r.getRef(Vv);if(a.size>0){let s=new Date(o.currentTimeMillisUnsafe());for(let c of a)c.log({cause:n,fiber:r,date:s,logLevel:i,message:t})}return It})},Hi,LU,oI=(e)=>`${e.getHours().toString().padStart(2,"0")}:${e.getMinutes().toString().padStart(2,"0")}:${e.getSeconds().toString().padStart(2,"0")}.${e.getMilliseconds().toString().padStart(3,"0")}`,aI,sI;var Mr=L(()=>{tu();Kl();Yx();ji();Pr();ln();ii();Uo();Jl();sp();Ir();$t();Ll();bt();aE();dE();fs();sr();xE();Ul();wE=class wE extends ms{constructor(e,t=gs){super("Interrupt",t,"Interrupted");this.fiberId=e}toString(){return`Interrupt(${this.fiberId})`}toJSON(){return{_tag:"Interrupt",fiberId:this.fiberId}}[et](e){return Vl(e)&&this.fiberId===e.fiberId&&this.annotations===e.annotations}[Qe](){return pt(jt(`${this._tag}:${this.fiberId}`))(Nl(this.annotations))}};ou=Y(2,(e,t)=>{if(e.reasons.length===0)return t;else if(t.reasons.length===0)return e;let n=new Ar(bR(e.reasons,t.reasons));return mt(e,n)?e:n}),RE=Y(2,(e,t)=>{let n=!1,r=e.reasons.map((i)=>{if(si(i))return n=!0,new hs(t(i.error),i.annotations);return i});return n?Bo(r):e}),wR=/\((.*)\)/g,kR={_A:Xe,_E:Xe},RR={id:0};Np=class Np{constructor(e,t=!0){this.setContext(e),this.id=++RR.id,this.currentOpCount=0,this.interruptible=t,this._stack=[],this._observers=void 0,this._exit=void 0,this._children=void 0,this._interruptedCause=void 0,this._yielded=void 0,this._running=!1,this._deferredInterrupt=!1,this._parent=void 0,this.cache.runtimeMetrics?.recordFiberStart(this.context)}get[NE](){return kR}get currentDispatcher(){return this._dispatcher??=this.cache.scheduler.makeDispatcher()}getRef(e){return wn(this.context,e)}addObserver(e){if(this._exit)return e(this._exit),jd;if(this._observers===void 0)this._observers=[e];else this._observers.push(e);return()=>this.removeObserver(e)}removeObserver(e){if(this._exit||this._observers===void 0)return;let t=this._observers.indexOf(e);if(t>=0)this._observers.splice(t,1)}interruptUnsafe(e,t){if(this._exit)return;let n=CE(e);if(this.cache.stackFrame)n=ys(n,pp(ql,this.cache.stackFrame));if(t)n=ys(n,t);if(this._interruptedCause=this._interruptedCause?ou(this._interruptedCause,n):n,this.interruptible)if(this._running)this._deferredInterrupt=!0;else this.evaluate(yt(this._interruptedCause))}pollUnsafe(){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===Ji)return;let n=EE.interruptChildren&&EE.interruptChildren(this);if(n!==void 0)return this.evaluate(_t(n,()=>t));if(this._exit=t,this.cache.runtimeMetrics?.recordFiberEnd(this.context,this._exit),this._parent)this._parent._children?.delete(this),this._parent=void 0;if(this._observers!==void 0){let r=this._observers;this._observers=void 0;for(let i=0;i<r.length;i++)r[i](t)}this._stack.length=0,this._children=void 0,this.context=Ho()}runLoop(e){let t=globalThis[Fo];globalThis[Fo]=this;let n=this._running;this._running=!0;let r=!1,i=e;this.currentOpCount=0;try{while(!0){if(this._deferredInterrupt)this._deferredInterrupt=!1,i=yt(this._interruptedCause);this.currentOpCount++;let o=this.cache;if(!r&&!o.preventYield&&o.scheduler.shouldYield(this)){r=!0;let a=i;i=_t(Dp,()=>a)}if(i=o.tracerContext?o.tracerContext(i,this):i[Be](this),i===Ji){let a=this._yielded;if(qi in a)return this._deferredInterrupt=!1,this._yielded=void 0,a;else if(this._deferredInterrupt){this._yielded=void 0,a();continue}return Ji}}}catch(o){if(!we(i,Be))return ar(`Fiber.runLoop: Not a valid effect: ${String(i)}`);return this.runLoop(ar(o))}finally{this._running=n,globalThis[Fo]=t}}getCont(e){if(this._deferredInterrupt)return this._deferredInterrupt=!1,PR;while(!0){let t=this._stack.pop();if(!t)return;let n=t[zi];if(n!==void 0){let r=n.call(t,this);if(r)return r[e]=r,r}if(t[e])return t}}succeedWith(e){if((++this.currentOpCount&OR-1)===0)return gt(e);let t=this.getCont(tt);return t?t[tt](e,this):this.yieldWith(gt(e))}yieldWith(e){return this._yielded=e,Ji}children(){return this._children??=new Set}pipe(){return en(this,arguments)}setContext(e){let t=this.context;if(this.context=e,t!==void 0&&Lx(t,e))return;let n=e.cacheRoot,r=n._fiberCache??=IR(e);if(this.cache?.scheduler!==r.scheduler)this._dispatcher=void 0;this.cache=r}get currentSpanLocal(){let e=this.cache.span;return e?._tag==="Span"?e:void 0}};PR={[tt](e,t){return yt(t._interruptedCause)},[fn](e,t){return yt(t._interruptedCause)}},EE={interruptChildren:void 0},ht=gt,yt=$n,Ki=Vo,Cn=or({op:"Sync",[Be](e){let t=this[ie](),n=e.getCont(tt);return n?n[tt](t,e):e.yieldWith(gt(t))}}),tn=or({op:"Suspend",[Be](e){return this[ie]()}}),$E=Ql({onFailure:Ki,onSuccess:ht}),jE=or({op:"Yield",[Be](e){let t=!1;return e.currentDispatcher.scheduleTask(()=>{if(t)return;e.evaluate(jn)},this[ie]??0),e.yieldWith(()=>{t=!0})}}),Dp=jE(0),It=ht(void 0),JE=function(){let e=dn({op:"Async",[Be](n){let r=!1,i=!1,o=this.withSignal?new AbortController:void 0,a=this.register.call(n.cache.scheduler,(s)=>{if(r)return;if(r=!0,i)n.evaluate(s);else i=s},o?.signal);if(i!==!1)return i;if(i=!0,n._yielded=()=>{r=!0},o===void 0&&a===void 0)return Ji;return n._stack.push(AR(()=>(r=!0,o?.abort(),a??jn))),Ji}}),t=function(n,r){this.register=n,this.withSignal=r};return t.prototype=e,function(n,r){return new t(n,r)}}(),AR=or({op:"AsyncFinalizer",[zi](e){if(e.interruptible)e.interruptible=!1,e._stack.push(lu)},[fn](e,t){return kE(e)?_t(yv($n(e),this[ie]()),()=>yt(e)):yt(e)}}),Fp=lr(jd),iu=function(){let e=dn({op:"Iterator",[tt](n,r){let i=this.iterator;while(!0){let o=i.next(n);if(o.done)return ht(o.value);if(!Ne(o.value))return r._stack.push(this),o.value;else if(o.value._tag==="Failure")return o.value;n=o.value.value}},[Be](n){return this[tt](this.initial,n)}}),t=function(n,r){this.iterator=n,this.initial=r};return t.prototype=e,function(n,r){return new t(n,r)}}(),Yo=Y(2,(e,t)=>new ws(e,KE,ht(t))),NR=dn({op:"OnSuccess",[Be]:su});ws.prototype=NR;Lp=(()=>({["~effect/Effect/stackProbe"]:function(){return Error().stack}})["~effect/Effect/stackProbe"]()?.includes("[as ~effect/Effect/stackProbe]")===!0)(),XE=Y((e)=>ds(e[1]),(e,t,n)=>YE([e,t],n)),$p=Y((e)=>ds(e[1]),(e,t,n)=>ZE([e,t],n)),_t=Y(2,(e,t)=>new ws(e,FR,t)),QE=Y(2,(e,t)=>{if(Ne(e))return e._tag==="Success"?t(e.value):e;return _t(e,t)}),Cs=Y(2,(e,t)=>new ws(e,DR,t)),tv=Y(2,(e,t)=>Ne(e)?ov(e,t):Cs(e,t)),nv=Y(2,(e,t)=>Ne(e)?av(e,t):Bp(e,t)),jn=gt(void 0),ov=Y(2,(e,t)=>e._tag==="Success"?gt(t(e.value)):e),av=Y(2,(e,t)=>{if(e._tag==="Success")return e;let n=bs(e.cause);if(Me(n))return e;return Vo(t(n.success))}),Ts=Y(2,(e,t)=>new sv(e,t.length!==1?(n)=>t(n):t)),LR=dn({op:"OnFailure",[Be]:su});sv.prototype=LR;cv=Y(3,(e,t,n)=>Ts(e,(r)=>{let i=t(r);return Me(i)?yt(i.failure):n(i.success,r)})),cu=Y(2,(e,t)=>cv(e,bs,(n)=>t(n))),lv=Y((e)=>ds(e[0]),(e,t,n,r)=>Ts(e,(i)=>{let o=bs(i);if(Me(o))return yt(o.failure);if(!t(o.success))return r?r(o.success):yt(i);return n(o.success)})),Bp=Y(2,(e,t)=>cu(e,(n)=>VE(()=>t(n)))),fv=Y((e)=>ds(e[0]),(e,t)=>{if(!t?.log)return qp(e,{onFailure:(r)=>It,onSuccess:(r)=>It});let n=zv(t.log===!0?void 0:t.log);return Vp(e,{onFailure(r){let i=TE(r);return Me(i)?yt(i.failure):t.message===void 0?n(r):n(t.message,r)},onSuccess:(r)=>It})}),Vp=Y(2,(e,t)=>new dv(e,t.onSuccess.length!==1?(n)=>t.onSuccess(n):t.onSuccess,t.onFailure.length!==1?(n)=>t.onFailure(n):t.onFailure)),UR=dn({op:"OnSuccessAndFailure",[Be]:su});dv.prototype=UR;BR=jR("Match",function(e,t){let n=e.reasons.find(si);if(n===void 0)return yt(e);let r=this.payload;return t.succeedWith(Lp?r.onFailure(n.error):us(()=>r.onFailure(n.error)))}),qp=Y(2,(e,t)=>Vp(e,{onFailure:(n)=>{let r=n.reasons.find(si);return r?t.onFailure(r.error):yt(n)},onSuccess:t.onSuccess})),zp=Y(2,(e,t)=>new BR(e,t)),pv=Y(2,(e,t)=>{if(Ne(e)){if(e._tag==="Success")return gt(t.onSuccess(e.value));let n=bs(e.cause);if(Me(n))return e;return gt(t.onFailure(n.success))}return zp(e,t)}),VR=or({op:"Exit",[Be](e){return e._stack.push(this),this[ie]},[tt](e,t,n){return t.succeedWith(n??gt(e))},[fn](e,t,n){return t.succeedWith(n??$n(e))}}),mv=Y(2,(e,t)=>_t(hv(e,t.duration),(n)=>Ix(n)?t.orElse():ht(n.value))),gv=Y(2,(e,t)=>{let n=Ss(t);return mv(e,{duration:n,orElse:()=>Ki(qR(n))})}),hv=Y(2,(e,t)=>$p(GE(e),Yo(Qp(t),Jo()))),Sv=function(){let e=dn({op:"OnExit",[Be](n){return n._stack.push(this),this.effect},[zi](n){if(n.interruptible&&this.interruptible!==!0)n._stack.push(lu),n.interruptible=!1},[tt](n,r,i){i??=gt(n);let o;try{o=this.onExit(i)}catch(a){o=ar(a)}return o?_t(o,(a)=>i):i},[fn](n,r,i){i??=$n(n);let o;try{o=this.onExit(i)}catch(a){o=ar(a)}return o?_t(yv(i,o),(a)=>i):i}}),t=function(n,r,i){this.effect=n,this.onExit=r,this.interruptible=i};return t.prototype=e,t}(),Kp=Y(2,Wp),xv=Y(2,(e,t)=>Kp(e,(n)=>t)),Ev=Y(3,(e,t,n)=>Kp(e,(r)=>{let i=t(r);return Me(i)?It:n(i.success,r)})),vv=Y(2,(e,t)=>Ev(e,iv,t)),wv=or({op:"SetInterruptible",[zi](e){if(e.interruptible=this[ie],e._interruptedCause&&e.interruptible)return()=>yt(e._interruptedCause)}}),lu=wv(!0),zR=wv(!1),Rv=or({op:"While",[tt](e,t){if(this[ie].step(e),this[ie].while())return t._stack.push(this),this[ie].body();return jn},[Be](e){if(this[ie].while())return e._stack.push(this),this[ie].body();return jn}}),Go=Y((e)=>typeof e[1]==="function",(e,t,n)=>tn(()=>{let r=ks(n?.concurrency);if(r===1)return WR(e,t,n);let i=vp(e),o=i.length;if(o===0)return n?.discard?It:ht([]);let a=n?.discard?void 0:Array(o),s=HR({f:t,out:a},i,{concurrency:r});return s?Yo(s,a):ht(a)})),HR=Iv({onItem(e,t,n){return e.f(t,n)},step(e,t,n,r){if(n._tag==="Failure")return n;else if(e.out)e.out[r]=n.value}}),Pv=du(Ho()),Mv=Av(Ho()),Nv=Zp(Ho()),Fv=Dv(Ho()),bE=ht(!0),_E=ht(!1);Xp=kt("effect/Clock",{defaultValue:()=>new Uv});$v=BigInt(1e6),jv=function(){let e=globalThis.process?.hrtime;if(typeof e?.bigint==="function")return()=>e.bigint();if(typeof performance<"u"&&typeof performance.now==="function")return()=>BigInt(Math.round(performance.now()*1e6));let t=BigInt(0);return()=>{let n=BigInt(Date.now())*$v;if(n>t)t=n;return t}}(),GR=function(){let e=BigInt(1e9),t;return()=>{let n=jv(),r=BigInt(Date.now())*$v;if(t===void 0)t=r-n;else{let i=t+n;if((r>i?r-i:i-r)>e)t=r-n}return t+n}}();em=class em extends qo("TimeoutError"){[Pp]=Pp;constructor(e){super({message:e})}};tm=class tm extends qo("AsyncFiberError"){[Op]=Op;constructor(e){super({message:"An asynchronous Effect was executed with Effect.runSync",fiber:e})}};pu=class pu extends qo("UnknownError"){[Ap]=Ap;constructor(e,t){super({message:t,cause:e})}};YR=kt("effect/Console",{defaultValue:()=>globalThis.console}),XR=Cx(zo,ZR),QR=zl(XR),Vv=kt("effect/Logger/CurrentLoggers",{defaultValue:()=>new Set([aI,sI])}),eI=kt("effect/Logger/LogToStderr",{defaultValue:NS}),nI={[tI]:{_Message:Xe,_Output:Xe},pipe(){return en(this,arguments)}},Hi={bold:"1",red:"31",green:"32",yellow:"33",blue:"34",cyan:"36",white:"37",gray:"90",black:"30",bgBrightRed:"101"},LU={None:[],All:[],Trace:[Hi.gray],Debug:[Hi.blue],Info:[Hi.green],Warn:[Hi.yellow],Error:[Hi.red],Fatal:[Hi.bgBrightRed,Hi.black]},aI=qv(({cause:e,date:t,fiber:n,logLevel:r,message:i})=>{let o=Array.isArray(i)?i.slice():[i];if(e.reasons.length>0)o.push(Mp(e));let a=t.getTime(),s=n.getRef(SE),c="";for(let g of s)c+=` ${iI(g,a)}`;let f=n.getRef(kp);if(Object.keys(f).length>0)o.push(f);let l=n.getRef(YR);(n.getRef(eI)?l.error:l.log)(`[${oI(t)}] ${r.toUpperCase()} (#${n.id})${c}:`,...o)}),sI=qv(({cause:e,fiber:t,logLevel:n,message:r})=>{let i=t.getRef(Xp),o=t.getRef(kp),a=t.cache.span;if(a===void 0||a._tag==="ExternalSpan")return;let s={};for(let[c,f]of Object.entries(o))Or(s,c,f);if(s["effect.fiberId"]=t.id,s["effect.logLevel"]=n.toUpperCase(),e.reasons.length>0)s["effect.cause"]=Mp(e);a.event(ex(Array.isArray(r)&&r.length===1?r[0]:r),i.currentTimeNanosUnsafe(),s)})});var nm,Rs,Zo,Xo,Nr,rm;var Qo=L(()=>{sr();Mr();nm=gt,Rs=$n,Zo=Vo,Xo=jn,Nr=jp,rm=rv});var gu,im,Gi,om;var Yi=L(()=>{sr();Mr();gu=si,im=Bl,Gi=RE,om=au});var Tn,d,M,Jv,nt,rt,ci,Wv,v,p,hu,Ps,V,Hv,Re,yu,Le,Zi,de,Kv,Gv,Pt,Dr,me,St,Yv,Je,Su,Os,Zv,Xv,le,Qv,Fr,Xi,As,Ms,eb,ta,A,Oe,Qi,am,sm,qt,tb;var De=L(()=>{Mr();Tn=kv,d=zE,M=ht,Jv=tn,nt=Cn,rt=It,ci=lr,Wv=Fp,v=WE,p=Ki,hu=BE,Ps=_s,V=qE,Hv=$E,Re=_t,yu=ev,Le=Es,Zi=Jp,de=Cs,Kv=Yo,Gv=Up,Pt=cu,Dr=Ts,me=lv,St=Bp,Yv=uv,Je=fv,Su=gv,Os=Qp,Zv=XE,Xv=$p,le=zp,Qv=qp,Fr=bv,Xi=xv,As=vv,Ms=_v,eb=Gp,ta=Pv,A=Mv,Oe=Fv,Qi=Nv,am=tv,sm=nv,qt=QE,tb=HE});function ur(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&&cI(r.value))ur(r.value,t)}Object.freeze(e)}function cI(e){return typeof e==="object"&&e!==null}var Lr="0.15",mn="state-0.16";var nb=()=>{};function na(e){return{ok:!0,value:e}}function eo(e){return{ok:!1,error:e}}function Ns(e,t){return new it("invalid_input",`Invalid ${e}.`,{field:e},t===void 0?void 0:{cause:t})}var it;var ra=L(()=>{it=class it extends Error{code;details;constructor(e,t,n={},r){super(t,r);this.name="CoreError",this.code=e,this.details=n,ur(this.details),Object.freeze(this)}}});var Eu=(e)=>lI(typeof e==="string"?uI.encode(e):e),vu=(e)=>{let t=fI(e),n=t.length;if(n%4!==0)return pn(new xs({kind:"Decode",module:"Base64",input:t,message:`Length must be a multiple of 4, but is ${n}`}));let r=t.indexOf("=");if(r!==-1&&(r<n-2||r===n-2&&t[n-1]!=="="))return pn(new xs({kind:"Decode",module:"Base64",input:t,message:"Found a '=' character, but it is not at the end"}));try{let i=t.endsWith("==")?2:t.endsWith("=")?1:0,o=new Uint8Array(3*(n/4)-i);for(let a=0,s=0;a<n;a+=4,s+=3){let c=xu(t.charCodeAt(a))<<18|xu(t.charCodeAt(a+1))<<12|xu(t.charCodeAt(a+2))<<6|xu(t.charCodeAt(a+3));o[s]=c>>16,o[s+1]=c>>8&255,o[s+2]=c&255}return cr(o)}catch(i){return pn(new xs({kind:"Decode",module:"Base64",input:t,message:i instanceof Error?i.message:"Invalid input"}))}},lI=(e)=>{let t=e.length,n="",r;for(r=2;r<t;r+=3)n+=Bn[e[r-2]>>2],n+=Bn[(e[r-2]&3)<<4|e[r-1]>>4],n+=Bn[(e[r-1]&15)<<2|e[r]>>6],n+=Bn[e[r]&63];if(r===t+1)n+=Bn[e[r-2]>>2],n+=Bn[(e[r-2]&3)<<4],n+="==";if(r===t)n+=Bn[e[r-2]>>2],n+=Bn[(e[r-2]&3)<<4|e[r-1]>>4],n+=Bn[(e[r-1]&15)<<2],n+="=";return n},uI,fI=(e)=>e.replace(/[\n\r]/g,""),Bn="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Ds,xu=(e)=>{if(e>=Ds.length||Ds[e]===255)throw TypeError(`Invalid character ${String.fromCharCode(e)}`);return Ds[e]};var cm=L(()=>{bt();lE();uI=new TextEncoder,Ds=new Uint8Array(123).fill(255);for(let e=0;e<Bn.length;e++)Ds[Bn.charCodeAt(e)]=e;Ds[61]=0});function lm(e){return e.checks?e.checks[e.checks.length-1].annotations:e.annotations}var Fs="~structural",um="~sentinels",fm="~constructor",bu;var _u=L(()=>{ln();bu=Qa((e)=>{let t=lm(e)?.identifier;if(typeof t==="string")return t;return e.getExpected(bu)})});var ae,wt,kn,Ie,Ls=(e)=>e===ae?Jo():Wo(e),pm=(e)=>e._tag==="None"?kn:wt(e.value);var ia=L(()=>{Qo();Jl();sr();ae=Symbol(),wt=nm,kn=wt(ae),Ie=wt(ae)});function gm(e){return we(e,js)&&e[js]===js}function dI(e){return Object.hasOwn(e,"input")}function mm(e,t,n){if(gm(e))return e;if(typeof e==="string")return new Ot({message:e},t,n);let r=typeof e.issue==="string"?new Ot({message:e.issue},t,n):e.issue;return new Ur(e.path,r)}function sb(e,t,n){if(e===void 0)return;if(typeof e==="boolean")return e?void 0:new Ot(void 0,t,n);return mm(e,t,n)}function cb(e,t,n,r){if(Array.isArray(t)){if(!Xx(t))return;return t.length===1?mm(t[0],n,r):new At(e,Qx(t,(i)=>mm(i,n,r)),n,r)}return sb(t,n,r)}function wu(e){return dI(e)?Te(e.input):void 0}function lb(e){let t=e.annotations?.expected;return typeof t==="string"?t:void 0}function Bs(e,t){let n=wu(t);return n===void 0?`Expected ${e}`:`Expected ${e}, got ${n}`}function ub(e){let t=e.annotations?.expected;if(typeof t==="string")return t;switch(e._tag){case"Filter":return"<filter>";case"FilterGroup":return e.checks.map((n)=>ub(n)).join(" & ")}}function gI(){return(e)=>$s(e,"")}function $s(e,t){let n;switch(e._tag){case"Filter":{let r=mI(e);if(r!==void 0)n=r;else{if(e.issue._tag!=="InvalidValue")return $s(e.issue,t);let i=lb(e.issue);n=i===void 0?Bs(ub(e.filter),e):Bs(i,e.issue)}break}case"Encoding":return $s(e.issue,t);case"Pointer":return $s(e.issue,t+QS(e.path));case"Composite":case"AnyOf":{if(e._tag==="Composite"||e.issues.length>0)return e.issues.map((r)=>$s(r,t)).join(`
25
+ `);n=Vs(e)??Bs(bu(e.ast),e);break}default:n=pI(e);break}return t?`${n}
26
+ at ${t}`:n}function Vs(e){if(e._tag==="Pointer")return;if(e._tag==="Encoding")return Vs(e.issue);let n=(e._tag==="Filter"?e.filter.annotations:("annotations"in e)?e.annotations:e.ast.annotations)?.[e._tag==="MissingKey"?"messageMissingKey":e._tag==="UnexpectedKey"?"messageUnexpectedKey":"message"];if(typeof n==="string")return n}var js="~effect/SchemaIssue/Issue",Vn,ib,ob,Ur,qs,hm,At,fr,Ot,zs,ab,pI=(e)=>{let t=Vs(e);if(t!==void 0)return t;switch(e._tag){case"InvalidType":return Bs(bu(e.ast),e);case"InvalidValue":{let n=lb(e);if(n!==void 0)return Bs(n,e);let r=wu(e);return r===void 0?"Expected a valid value":`Invalid data ${r}`}case"MissingKey":return"Missing key";case"UnexpectedKey":{let n=wu(e);return n===void 0?"Expected no excess property":`Unexpected key with value ${n}`}case"Forbidden":return"Forbidden operation";case"OneOf":{let n=wu(e);return n===void 0?"Expected exactly one member to match":`Expected exactly one member to match the input ${n}`}}},mI=(e)=>Vs(e.issue)??Vs(e),fb;var li=L(()=>{tu();Pr();_u();ia();$t();Vn=class Vn{[js]=js;constructor(e,t){if(t?.reportInput===!0&&e!==ae)this.input=e}};ib=class extends Vn{_tag="Filter";filter;issue;constructor(e,t,n,r){super(n,r);this.filter=e,this.issue=t}},ob=class extends Vn{_tag="Encoding";ast;issue;constructor(e,t,n,r){super(n,r);this.ast=e,this.issue=t}},Ur=class extends Vn{_tag="Pointer";path;issue;constructor(e,t){super();this.path=e,this.issue=t}},qs=class extends Vn{_tag="MissingKey";annotations;constructor(e){super();this.annotations=e}},hm=class extends Vn{_tag="UnexpectedKey";ast;constructor(e,t,n){super(t,n);this.ast=e}},At=class extends Vn{_tag="Composite";ast;issues;constructor(e,t,n,r){super(n,r);this.ast=e,this.issues=t}},fr=class extends Vn{_tag="InvalidType";ast;constructor(e,t,n){super(t,n);this.ast=e}},Ot=class extends Vn{_tag="InvalidValue";annotations;constructor(e,t,n){super(t,n);this.annotations=e}},zs=class extends Vn{_tag="AnyOf";ast;issues;constructor(e,t,n,r){super(n,r);this.ast=e,this.issues=t}},ab=class extends Vn{_tag="OneOf";ast;successes;constructor(e,t,n,r){super(n,r);this.ast=e,this.successes=t}};fb=gI()});function Js(e){let t;for(let n of e.reasons){if(!gu(n)||!gm(n.error))return;t??=n.error}return t}function ui(e,t){let n=Js(e);if(n===void 0)throw Error(t,{cause:e});return n}var ym=L(()=>{Yi();li()});function Cu(){return SI}function zt(e){return Sm({_tag:"Transform",transform:e})}function fi(e){return Sm({_tag:"TransformEffect",transform:e})}function xm(){return zt(globalThis.String)}function Tu(){return zt(globalThis.Number)}function pb(e){return fi((t,n)=>V({try:()=>JSON.parse(t,e?.reviver),catch:()=>new Ot({expected:"a valid JSON string"},t,n)}))}function mb(e){return fi((t,n)=>V({try:()=>{let r=JSON.stringify(t,e?.replacer,e?.space);if(r===void 0)throw TypeError("Value cannot be represented as JSON");return r},catch:()=>new Ot({expected:"a JSON-serializable value"},t,n)}))}function gb(){return zt(Eu)}function hb(){return fi((e,t)=>sm(Hv(vu(e)),()=>new Ot({expected:"a valid Base64 string"},e,t)))}var Sm=(e)=>Object.assign(Object.create(Ud),e),SI;var ku=L(()=>{De();cm();Ir();li();SI=Sm({_tag:"Passthrough"})});function vI(e){return we(e,Ws)&&e[Ws]===Ws}function Hs(e){return new gn(fi(e.decode),fi(e.encode))}function yb(e){return new gn(zt(e.decode),zt(e.encode))}function Ru(){return bI}function Pu(e){return new gn(pb(e??{}),mb(e))}var Ws="~effect/SchemaTransformation/Transformation",gn,vm=(e)=>{if(vI(e))return e;return new gn(e.decode,e.encode)},bI,Iu,Sb,xb;var Ou=L(()=>{De();Ir();$t();ku();li();gn=class extends Za{[Ws]=Ws;_tag="Transformation";decode;encode;constructor(e,t){super();this.decode=e,this.encode=t}flip(){return new gn(this.encode,this.decode)}};bI=new gn(Cu(),Cu());Iu=new gn(Tu(),xm()),Sb=Hs({decode:(e,t)=>URL.canParse(e)?M(new URL(e)):p(new Ot({expected:"a valid URL string"},e,t)),encode:(e)=>M(e.href)}),xb=new gn(hb(),gb())});function io(e){return(t)=>t._tag===e}function vb(e){let t=globalThis.String(e.literal);return qn(e,[new Rn(new aa(t),new gn(zt(()=>e.literal),zt(()=>t)))])}function Cm(e,t){return e.some((n)=>n.annotations?.representation?.id===t||n._tag==="FilterGroup"&&Cm(n.checks,t))}function DI(e,t,n,r){if(n._tag==="Failure")return Nu(e,e.ast,r,n);let i=n===Ie?t:n[ie];if(i!==ae)e.output[r]=i;else{let o=e.getParser(e.tailThreshold,r);if(ro(o.ast))return;let a=new Ur([r],new qs(o.ast.context?.annotations));if(e.options.errors==="all")if(e.issues)e.issues.push(a);else e.issues=[a];else return Zo(new At(e.ast,[a],e.input,e.options))}}function _m(e,t,n=oo){let r,i;function o(a){switch(a._tag){case"String":case"TemplateLiteral":return(r??=Object.keys(e)).filter((s)=>a.matchPart(s,n)!==void 0);case"Number":return(r??=Object.keys(e)).filter((s)=>a.matchKey(s,n)!==void 0);case"Symbol":return(i??=Object.getOwnPropertySymbols(e)).filter((s)=>Object.prototype.propertyIsEnumerable.call(e,s)&&a.matchKey(s,n)!==void 0);case"Union":return[...new Set(a.types.flatMap(o))];default:return[]}}return o(qm(Bm(t)))}function Ab(e){switch(e._tag){case"String":case"Number":case"Symbol":case"TemplateLiteral":return!0;case"Union":return e.types.every(Ab);default:return!1}}function Mb(e){let t=Bb(e);switch(t._tag){case"String":case"Number":case"Symbol":case"TemplateLiteral":return!0;case"Union":return t.types.every(Mb);default:return!1}}function UI(e){return Ab(e)&&Mb(e)}function Tm(e,t,n){if(n._tag==="Failure")return Nu(e,e.ast,t.name,n);if(n===Ie)return;let r=n[ie];if(r!==ae){Or(e.out,t.name,r);return}if(delete e.out[t.name],!ro(t.type)){let i=new Ur([t.name],new qs(t.type.context?.annotations));if(e.options.errors==="all"){if(e.issues)e.issues.push(i);else e.issues=[i];return}else return Zo(new At(e.ast,[i],e.input,e.options))}}function Nm(e,t){if(!e)return t;if(!t)return e;return[...e,...t]}function Dm(e,t,n){return new Uu(Reflect.ownKeys(e).map((r)=>new Mm(r,e[r].ast)),[],n,t)}function $u(e){return e.ast}function Fm(e,t=void 0){return new Lu(!1,e.map((n)=>n.ast),[],void 0,t)}function ju(e,t,n){return new ua(e.map($u),t,void 0,n)}function Fb(e,t){if(e.encoding||t.some((o)=>o.encoding))throw Error("StructWithRest does not support encodings");let{propertySignatures:n,indexSignatures:r,checks:i}=e;for(let o of t){for(let a of o.propertySignatures)if(n.some((s)=>s.name===a.name))throw Error(`Duplicate identifier: ${JSON.stringify(a.name)}. ts(2300)`);n=n.concat(o.propertySignatures),r=r.concat(o.indexSignatures),i=Nm(i,o.checks)}return new Uu(n,r,void 0,i)}function Lb(e){switch(e._tag){case"Null":return["null"];case"Undefined":return["undefined"];case"String":case"TemplateLiteral":return["string"];case"Number":return["number"];case"Boolean":return["boolean"];case"Symbol":case"UniqueSymbol":return["symbol"];case"BigInt":return["bigint"];case"Arrays":return["array"];case"ObjectKeyword":return["object","array","function"];case"Objects":return e.propertySignatures.length||e.indexSignatures.length?["object"]:["string","number","boolean","symbol","bigint","object","array","function"];case"Enum":return Array.from(new Set(e.enums.map(([,t])=>typeof t)));case"Literal":return[typeof e.literal];case"Union":return Array.from(new Set(e.types.flatMap(Lb)));default:return["null","undefined","string","number","boolean","symbol","bigint","object","array","function"]}}function Du(e){switch(e._tag){default:return[];case"Declaration":{let t=e.annotations?.[um];return Array.isArray(t)?t:[]}case"Objects":return e.propertySignatures.flatMap((t)=>{let n=t.type;if(!ro(n)){if(sa(n))return[{key:t.name,literal:n.literal}];if(wm(n))return[{key:t.name,literal:n.symbol}]}return[]});case"Arrays":return e.elements.flatMap((t,n)=>{if(!ro(t)){if(sa(t))return[{key:n,literal:t.literal}];if(wm(t))return[{key:n,literal:t.symbol}]}return[]});case"Union":{if(e.types.length===0)return[];let t=e.types.map((n)=>Du(Lm(n)));return t[0].filter((n)=>t.every((r)=>r.some((i)=>i.key===n.key&&i.literal===n.literal)))}case"Suspend":return Du(e.thunk())}}function jI(e){let t=_b.get(e);if(t)return t;let n,r=0,i,o,a=!0,s=[];for(let l=0;l<e.length;l++){let u=e[l],g=Lm(u);if(CI(g))continue;if(sa(g)||wm(g)){o??=new Map;let y=sa(g)?g.literal:g.symbol;s[l]=y;let S=o.get(y);if(!S)o.set(y,S=[]);S.push(l)}else a=!1;let h=Du(g);if(h.length){n??=new Map,r++;for(let{key:y,literal:S}of h){let m=n.get(y);if(!m)n.set(y,m=[new Map,new Set]);m[1].add(l);let x=m[0].get(S);if(!x)m[0].set(S,x=new Set);x.add(l)}}else{i??={};let y=Lb(g);for(let S of y)(i[S]??=[]).push(l)}}let c={},f=(l)=>c[l]??=Object.freeze(i?.[l]??Au);if(a&&o)o.forEach(Object.freeze),t=(l)=>o.get(l)??Au;else if(n?.size===1&&!i){let[l,[u]]=n.entries().next().value,g=new Map;for(let[y,S]of u)g.set(y,Object.freeze(Array.from(S)));let h=Object.freeze(e.map((y,S)=>S));t=(y,S)=>{if(Ml(y)){let m=oa(y,l)?y[l]:void 0;if(m!==void 0)return g.get(m)??Au;if(S)return h}return Au}}else if(n){let l;for(let u of n)if((!l||u[1][0].size>l[1][0].size)&&u[1][1].size===r)l=u;t=(u,g)=>{let h=wb(u);if(!Ml(u))return f(h);let y=new Set(i?.[h]),S;if(l){let[m,[x]]=l,E=oa(u,m),_=E?u[m]:void 0;if(E&&(!g||_!==void 0)){let C=x.get(_);if(!C)return f(h);for(let N of C)y.add(N);S=m}}if(S===void 0)for(let[m,[x,E]]of n){let _=oa(u,m),C=_?u[m]:void 0;if(_&&(!g||C!==void 0)){let N=x.get(C);if(N)for(let D of N)y.add(D)}else if(g)for(let N of E)y.add(N)}for(let[m,[x,E]]of n){if(m===S)continue;let _=oa(u,m),C=_?u[m]:void 0;if(_&&(!g||C!==void 0)){let N=x.get(C);for(let D of y)if(E.has(D)&&!N?.has(D))y.delete(D)}}return Array.from(y).sort((m,x)=>m-x)}}else t=(l)=>{let u=f(wb(l));return o?u.filter((g)=>s[g]===void 0||s[g]===l):u};return _b.set(e,t),t}function Ub(e,t,n,r){let i=Js(t);if(!i)return Rs(t);return Zo(new zs(e,[i],n,r))}function BI(e,t,n,r){return Dr(t,(i)=>Ub(e,i,n,r))}function VI(e,t,n,r,i){let o={ast:e,parser:t,input:r,out:void 0,successes:e.options?.mode==="oneOf"?[]:void 0,issues:void 0,options:i},a=zI(o,n);if(!a){if(o.out)return o.out;return p(new zs(e,o.issues??[],r,i))}return qI(a,o)}function qI(e,t){return qt(e,(n)=>{if(t.out===Ie)return M(t.input);if(t.out)return t.out;return p(new zs(t.ast,t.issues??[],t.input,t.options))})}function Cb(e){return e?"":"readonly "}function Tb(e){return e?"?":""}function Bu(e,t,n=!1){return new km((r,i,o)=>cb(i,e(r,i,o),r,o),t,n)}function Um(e){return Bu((t)=>globalThis.Number.isFinite(t),{expected:"a finite number",representation:{id:"effect/schema/isFinite",payload:null},toJsonSchema:()=>({type:"number"}),toCode:()=>({runtime:"Schema.isFinite()"}),arbitraryConstraint:{number:"finite"},...e})}function $m(e,t){let n=new globalThis.RegExp(e),r={source:n.source,flags:n.flags};return Bu((i)=>(n.lastIndex=0,n.test(i)),{expected:`a string matching the RegExp ${r.source}`,representation:{id:"effect/schema/isPattern",payload:r},toJsonSchema:()=>[{},!0],arbitraryConstraint:{patterns:[r]},...t})}function Gs(e,t){let n=Object.assign(Object.create(Object.getPrototypeOf(e)),e,t);if(Reflect.ownKeys(t).every((r)=>r==="context"||r==="encoding"))Rm.set(n,Vu(e));return n}function Vu(e){let t=Rm.get(e);if(t!==void 0)return t;if(e.encoding===void 0)return e;let n=Object.assign(Object.create(Object.getPrototypeOf(e)),e,{encoding:void 0});return Rm.set(e,n),n}function qn(e,t){return e.encoding===t?e:Gs(e,{encoding:t})}function Ys(e,t){if(e.context===t)return e;let n=Vu(e);if(n.context===t&&n.encoding===e.encoding)return n;return Gs(e,{context:t})}function Bb(e){return e.encoding?Bb(e.encoding[e.encoding.length-1].to):e}function qu(e,t){if(e.checks){let n=e.checks[e.checks.length-1];return Vb(e,bp(e.checks.slice(0,-1),n.annotate(t)))}return Gs(e,{annotations:{...e.annotations,...t}})}function Vb(e,t){if(e._tag==="Suspend"&&t)throw Error("Cannot add checks to Suspend");if(e.checks===t)return e;return Gs(e,{checks:t})}function Zs(e,t){return Vb(e,Nm(e.checks,t))}function WI(e,t){let n=t(e.to);return n===e.to?e:new Rn(n,e.transformation)}function qb(e,t){let n=e,r=n[n.length-1],i=WI(r,t);return i===r?e:bp(e.slice(0,e.length-1),i)}function HI(e){return(t)=>t.encoding?qn(t,qb(t.encoding,e)):t}function KI(e,t){function n(r){if(r.encoding){let i=r.encoding[r.encoding.length-1];return t?.stopAt?.(i)?r:qn(r,qb(r.encoding,n))}return e(r)}return Mo(n)}function GI(e,t,n){let r=new Rn(e,t);return qn(n,n.encoding?[...n.encoding,r]:[r])}function la(e,t){let n;for(let r=0;r<e.length;r++){let i=e[r],o=t(i);if(n)n[r]=o;else if(o!==i){n=Array(e.length);for(let a=0;a<r;a++)n[a]=e[a];n[r]=o}}return n??e}function jm(e,t){let n=e.context?new ca(e.context.isOptional,e.context.isMutable,e.context.constructorDefault,{...e.context.annotations,...t}):new ca(!1,!1,void 0,t);return Ys(e,n)}function Jb(e,t){let n=e.context?new ca(e.context.isOptional,e.context.isMutable,t,e.context.annotations):new ca(!1,!1,t);return Ys(e,n)}function Wb(e,t,n){return GI(e,n,t)}function ZI(e){let t=[],n=[];function r(i){switch(i._tag){case"Literal":if(US(i.literal)&&!t.includes(i.literal))t.push(i.literal);return;case"UniqueSymbol":if(!t.includes(i.symbol))t.push(i.symbol);return;case"Never":return;case"Union":for(let o=0;o<i.types.length;o++)r(i.types[o]);return;default:n.push(i)}}return r(e),{literals:t,parameters:n}}function Hb(e,t){let{literals:n,parameters:r}=ZI(e);return new Uu(n.map((i)=>new Mm(i,t)),r.map((i)=>new Nb(i,t)))}function ro(e){return e.context?.isOptional??!1}function Kb(e){return e.annotations?.[Fs]===!0||e._tag==="FilterGroup"&&e.checks.every(Kb)}function XI(e){function t(r){if(Kb(r))return[r];return r._tag==="FilterGroup"?r.checks.flatMap(t):[]}let n=e.flatMap(t);return _p(n)?n:void 0}function QI(e){let t=!0;function n(r){if(t=t&&!r.encoding&&!Rb(r),t&&"recur"in r)r.recur(n);return r}if("recur"in e)e.recur(n);return t}function eP(e,t){let n=t,r=n.length,i=n[r-1],o=[new Rn($r(qn(e,void 0)),n[0].transformation.flip())];for(let s=1;s<r;s++)o.unshift(new Rn($r(n[s-1].to),n[s].transformation.flip()));let a=$r(i.to);if(a.encoding)return qn(a,[...a.encoding,...o]);else return qn(a,o)}function Gb(e){switch(e._tag){case"Undefined":return!0;case"Union":return e.types.some(Gb);default:return!1}}function Vm(e,t){let n=t===0?Ie:wt(t);return(r,i)=>{if(r===ae)return kn;if(r===t)return n;return p(new fr(e,r,i))}}function Xs(e,t){return(n,r)=>{if(n===ae)return kn;if(t(n))return Ie;return p(new fr(e,n,r))}}function Yb(e){return $m(Im,{expected:"a string representing a finite number",representation:{id:"effect/schema/isStringFinite",payload:null},toJsonSchema:()=>({pattern:Im.source}),...e})}function pi(e,t,n,r,i){for(let o=0;o<e.length;o++){let a=e[o];if(a._tag==="FilterGroup"){if(n=pi(a.checks,t,n,r,i),n&&(i.errors!=="all"||n[n.length-1].filter.aborted))return n}else{let s=a.run(t,r,i);if(s){let c=new ib(a,s,t,i);if(n)n.push(c);else n=[c];if(i.errors!=="all"||a.aborted)return n}}}return n}function Xb(e){if(!kb(e))return;let t=e.annotations?.[fm];return os(t)?t(e.typeParameters):void 0}function aP(e){return e===null||typeof e==="string"||typeof e==="boolean"||typeof e==="number"&&globalThis.Number.isFinite(e)}function sP(e){return e===void 0||typeof e==="string"}function Qb(e,t){let n=new WeakMap,r=[];e:while(!0){if(typeof e!=="object"||e===null){if(!t(e))return!1}else{let i=e,o=n.get(i);if(o===!1)return!1;if(o===void 0){let a=Array.isArray(i);if(!a){let s=Object.getPrototypeOf(i);if(s!==null&&s!==Object.prototype&&Object.getPrototypeOf(s)!==null)return!1}n.set(i,!1),r.push({value:i,keys:a?i.length:Object.keys(i),index:0})}}while(r.length>0){let i=r[r.length-1],o=i.keys;if(typeof o==="number"){if(i.index<o){e=i.value[i.index++];continue e}}else if(i.index<o.length){e=i.value[o[i.index++]];continue e}n.set(i.value,!0),r.pop()}return!0}}function cP(e){return Qb(e,aP)}function lP(e){return Qb(e,sP)}var kb,CI,sa,wm,TI,kI,Rb,Rn=class{to;transformation;constructor(e,t){this.to=e,this.transformation=t}},oo,ca=class{isOptional;isMutable;constructorDefault;annotations;constructor(e,t,n=void 0,r=void 0){this.isOptional=e,this.isMutable=t,this.constructorDefault=n,this.annotations=r}},Eb="~effect/Schema",In,Ks,RI,Pm,II,PI,Om,OI,Mu,aa,AI,no,MI,Am,NI,Ib,Lu,Pb,FI,LI,Nu=(e,t,n,r)=>{if(r.cause.reasons.length===0)return r;let i=Js(r.cause);if(i===void 0)return Rs(Gi(r.cause,(a)=>new At(t,[new Ur([n],a)],e.input,e.options)));let o=new Ur([n],i);if(e.options.errors==="all")if(e.issues)e.issues.push(o);else e.issues=[o];else return Zo(new At(t,[o],e.input,e.options))},Ob="[+-]?\\d*\\.?\\d+(?:[Ee][+-]?\\d+)?",Mm=class{name;type;constructor(e,t){this.name=e,this.type=t}},Nb=class{parameter;type;constructor(e,t){if(!UI(e))throw Error(`Invalid index signature parameter ${e._tag}`);if(this.parameter=e,this.type=t,ro(t)&&!Gb(t))throw Error("Cannot use `Schema.optionalKey` with index signatures, use `Schema.optional` instead.")}},Uu,Db,bb,$I,Lm,_b,Au,wb=(e)=>e===null?"null":Array.isArray(e)?"array":typeof e,oa=(e,t)=>t==="__proto__"?Object.hasOwn(e,t):(t in e),ua,zI,$b,km,Fu,jb,JI,Rm,zu,YI,zb,di,Bm,$r,qm,Im,tP,Zb,nP,rP,iP="-?\\d+",V1,oP="Symbol\\(([\\s\\S]*)\\)",q1,e_,uP,fP;var Qs=L(()=>{tu();Yi();De();Qo();Pr();ln();Mr();_u();ym();ia();Ir();$t();ku();li();Ou();kb=io("Declaration"),CI=io("Never"),sa=io("Literal"),wm=io("UniqueSymbol"),TI=io("Arrays"),kI=io("Objects"),Rb=io("Suspend"),oo={};In=class In{[Eb]=Eb;annotations;checks;encoding;context;constructor(e=void 0,t=void 0,n=void 0,r=void 0){this.annotations=e,this.checks=t,this.encoding=n,this.context=r}toString(){return`<${this._tag}>`}};Ks=class extends In{_tag="Declaration";typeParameters;run;encodingChecks;encodingRun;constructor(e,t,n,r,i,o,a,s){super(n,r,i,o);this.typeParameters=e,this.run=t,this.encodingChecks=a,this.encodingRun=s}getParser(){let e;return(t,n)=>{if(t===ae)return kn;return(e??=this.run(this.typeParameters))(t,this,n)}}_rebuild(e,t,n,r,i){let o=la(this.typeParameters,e);return o===this.typeParameters&&t===this.checks&&n===this.encodingChecks&&r===this.run&&i===this.encodingRun?this:new Ks(o,r,this.annotations,t,void 0,this.context,n,i)}recur(e){return this._rebuild(e,this.checks,this.encodingChecks,this.run,this.encodingRun)}flip(e){return this._rebuild(e,this.encodingChecks,this.checks,this.encodingRun??this.run,this.run)}getExpected(){let e=this.annotations?.expected;if(typeof e==="string")return e;return"<Declaration>"}},RI=class extends In{_tag="Null";getParser(){return Vm(this,null)}getExpected(){return"null"}},Pm=new RI,II=class extends In{_tag="Undefined";getParser(){return Vm(this,void 0)}toCodecJson(){return qn(this,[PI])}getExpected(){return"undefined"}},PI=new Rn(Pm,new gn(zt(()=>{return}),zt(()=>null))),Om=new II,OI=class extends In{_tag="Unknown";getParser(){return Xs(this,jS)}getExpected(){return"unknown"}},Mu=new OI,aa=class extends In{_tag="Literal";literal;constructor(e,t,n,r,i){super(t,n,r,i);if(typeof e==="number"&&!globalThis.Number.isFinite(e))throw Error(`A numeric literal must be finite, got ${Te(e)}`);this.literal=e}getParser(){return Vm(this,this.literal)}matchPart(e,t){return e===globalThis.String(this.literal)?this.literal:void 0}toCodecJson(){return typeof this.literal==="bigint"?vb(this):this}toCodecStringTree(){return typeof this.literal==="string"?this:vb(this)}getExpected(){return typeof this.literal==="string"?JSON.stringify(this.literal):globalThis.String(this.literal)}};AI=class extends In{_tag="String";getParser(){return Xs(this,rs)}matchPart(e,t){let n=this.checks;return n&&!t.disableChecks&&pi(n,e,void 0,this,t)?void 0:e}getExpected(){return"string"}},no=new AI,MI=class extends In{_tag="Number";getParser(){return Xs(this,is)}matchKey(e,t){return this._match(tP,e,t)}matchPart(e,t){return this._match(Im,e,t)}_match(e,t,n){if(!e.test(t))return;let r=globalThis.Number(t);if(n.disableChecks||!this.checks)return r;return pi(this.checks,r,void 0,this,n)?void 0:r}toCodecJson(){if(this.checks&&(Cm(this.checks,"effect/schema/isFinite")||Cm(this.checks,"effect/schema/isInt")))return this;return qn(this,[JI])}toCodecStringTree(){if(this.toCodecJson()===this)return qn(this,[nP]);return qn(this,[rP])}getExpected(){return"number"}};Am=new MI,NI=class extends In{_tag="Boolean";getParser(){return Xs(this,FS)}getExpected(){return"boolean"}},Ib=new NI,Lu=class extends In{_tag="Arrays";isMutable;elements;rest;encodingChecks;constructor(e,t,n,r,i,o,a,s){super(r,i,o,a);this.isMutable=e,this.elements=t,this.rest=n,this.encodingChecks=s;let c=!1;for(let f=0;f<t.length;f++)if(ro(t[f]))c=!0;else if(c)throw Error("A required element cannot follow an optional element. ts(1257)");if(c&&n.length>1)throw Error("A required element cannot follow an optional element. ts(1257)");for(let f=1;f<n.length;f++)if(ro(n[f]))throw Error("An optional element cannot follow a rest element. ts(1266)")}getParser(e,t=e){let n=this,r,i,o=n.elements.length,a=Math.max(0,n.rest.length-1);function s(l,u){if(u<o)return r[u];else if(u>=l)return i[u-l+1];return i[0]}let c=(l)=>{let{input:u,len:g,options:h}=l;if(n.rest.length===0&&g>o)for(let y=o;y<g;y++){let S=new hm(n,u[y],h),m=new Ur([y],S);if(h.errors==="all")if(l.issues)l.issues.push(m);else l.issues=[m];else return p(new At(n,[m],u,h))}if(l.issues)return p(new At(n,l.issues,u,h));return wt(l.output)},f=(l,u)=>{let g=l.length,h={ast:n,getParser:s,input:l,len:g,tailThreshold:Math.max(o,g-a),output:new globalThis.Array(g),issues:void 0,options:u},y=n.rest.length===0?o:Math.max(g,o+a),S=u.concurrency===void 0?1:ks(u.concurrency),m=S===1?FI(h,l,0,y):LI(h,l,{concurrency:S,end:y});if(!m)return c(h);if(Ne(m))return qt(m,()=>c(h));let x=!0;return Jv(()=>{if(!x)return f(l,u);return x=!1,Re(m,()=>c(h))})};return(l,u)=>{if(l===ae)return kn;try{if(!Array.isArray(l))return p(new fr(n,l,u));if(!r)r=n.elements.map((g)=>({ast:g,parser:t(g)})),i=n.rest.map((g)=>({ast:g,parser:t(g)}));return f(l,u)}catch(g){return Ps(g)}}}_rebuild(e,t,n){let r=la(this.elements,e),i=la(this.rest,e);return r===this.elements&&i===this.rest&&t===this.checks&&n===this.encodingChecks?this:new Lu(this.isMutable,r,i,this.annotations,t,void 0,this.context,n)}recur(e){return this._rebuild(e,this.checks,this.encodingChecks)}flip(e){return this._rebuild(e,this.encodingChecks,this.checks)}getExpected(){return"array"}};Pb={onItem(e,t,n){let r=n<e.len?t:ae;return e.getParser(e.tailThreshold,n).parser(r,e.options)},step:DI},FI=uu()(Pb),LI=fu()(Pb);Uu=class extends In{_tag="Objects";propertySignatures;indexSignatures;encodingChecks;constructor(e,t,n,r,i,o,a){super(n,r,i,o);this.propertySignatures=e,this.indexSignatures=t,this.encodingChecks=a}getParser(e,t=e){let n=this,r=n.propertySignatures.length,i=n.indexSignatures.length;if(!r&&!i)return Xs(n,$S);let o,a,s=()=>{if(!o)o=n.propertySignatures.map((u)=>({parser:t(u.type),name:u.name,type:u.type})),a=i?n.indexSignatures.map((u)=>({is:u,parserKey:e(qm(u.parameter)),parserValue:t(u.type)})):void 0;return o},c=()=>{let u=new Set(n.propertySignatures.map((m)=>typeof m.name==="number"?globalThis.String(m.name):m.name)),g=(m,x,E,_,C)=>{if(C._tag==="Failure")return Nu(m,n,x,C)??Xo;let N=C===Ie?_:C[ie];if(E!==ae&&N!==ae){if(r&&(u.has(x)||u.has(typeof E==="number"?globalThis.String(E):E)))return Xo;Or(m.out,E,N)}return Xo},h=(m,x,E,_)=>{if(!_){let F=E.parserKey(x,m.options);if(!Ne(F))return Re(Zi(F),(K)=>h(m,x,E,K));_=F}if(_._tag==="Failure")return Nu(m,n,x,_)??Xo;let C=_===Ie?x:_[ie],N=m.input[x],D=E.parserValue(N,m.options);return Ne(D)?g(m,x,C,N,D):Re(Zi(D),(F)=>g(m,x,C,N,F))},y=(m,x,E)=>{let _=m.input[x],C=E.parserValue(_,m.options);return Ne(C)?g(m,x,x,_,C):Re(Zi(C),(N)=>g(m,x,x,_,N))},S=i?fu()({onItem:(m,[x,E])=>E.is.parameter===no?y(m,x,E):h(m,x,E),step:(m,x,E)=>E._tag==="Failure"?E:void 0}):void 0;return tb(function*(m,x){if(m===ae)return ae;if(!(typeof m==="object"&&m!==null&&!Array.isArray(m)))return yield*p(new fr(n,m,x));s();let E=m,_={},C={ast:n,input:E,out:_,issues:void 0,options:x},N=x.errors==="all",D=x.onExcessProperty==="error",F=x.concurrency===void 0?1:ks(x.concurrency),K=i&&D?n.indexSignatures.map((O)=>_m(E,O.parameter,x)):void 0;if(D){let O=K?new Set(u):u;if(K)for(let oe of K)for(let I of oe)O.add(I);let ce=Reflect.ownKeys(E);for(let oe=0;oe<ce.length;oe++){let I=ce[oe];if(!O.has(I)&&Object.prototype.propertyIsEnumerable.call(E,I)){let J=new hm(n,E[I],x),ve=new Ur([I],J);if(N){if(C.issues)C.issues.push(ve);else C.issues=[ve];continue}else return yield*p(new At(n,[ve],m,x))}}}if(r){let O=F===1?bb(C,o):$I(C,o,{concurrency:F});if(O)yield*O}if(i&&F===1)for(let O=0;O<i;O++){let ce=a[O],oe=ce.is.parameter===no?y:h,I=K?.[O]??(ce.is.parameter===no?Object.keys(E):_m(E,ce.is.parameter,x));for(let J=0;J<I.length;J++){let ve=oe(C,I[J],ce);if(!Ne(ve))yield*ve;else if(ve._tag==="Failure")return yield*ve}}else if(S){let O=eu();for(let oe=0;oe<i;oe++){let I=a[oe],J=K?.[oe]??(I.is.parameter===no?Object.keys(E):_m(E,I.is.parameter,x));for(let ve=0;ve<J.length;ve++)O.push([J[ve],I])}let ce=S(C,O,{concurrency:F});if(ce)yield*ce}if(C.issues)return yield*p(new At(n,C.issues,m,x));return _})};if(i)return c();let f,l=(u,g,h)=>{let y=o[g];return Re(Zi(h),(S)=>{let m=Tm(u,y,S);if(m)return m;let x=()=>wt(u.out),E=bb(u,o.slice(g+1));return E?qt(E,x):x()})};return(u,g)=>{if(u===ae)return kn;if(g.errors==="all"||g.onExcessProperty!==void 0||g.concurrency!==void 0&&ks(g.concurrency)!==1)return(f??=c())(u,g);if(!(typeof u==="object"&&u!==null&&!Array.isArray(u)))return p(new fr(n,u,g));let h=s(),y=u,S={},m={ast:n,input:y,out:S,issues:void 0,options:g};try{for(let x=0;x<h.length;x++){let E=h[x],_=E.name,C=oa(y,_),N=C?y[_]:ae,D=E.parser(N,g);if(!Ne(D))return l(m,x,D);if(D===Ie){if(C)Or(S,_,N);continue}let F=Tm(m,E,D);if(F)return F}}catch(x){return Ps(x)}return wt(S)}}_rebuild(e,t,n,r){let i=la(this.propertySignatures,(a)=>{let s=e(a.type);return s===a.type?a:new Mm(a.name,s)}),o=la(this.indexSignatures,(a)=>{let s=t(a.parameter),c=e(a.type);return s===a.parameter&&c===a.type?a:new Nb(s,c)});return i===this.propertySignatures&&o===this.indexSignatures&&n===this.checks&&r===this.encodingChecks?this:new Uu(i,o,this.annotations,n,void 0,this.context,r)}flip(e){return this._rebuild(e,e,this.encodingChecks,this.checks)}recur(e,t=e){return this._rebuild(e,t,this.checks,this.encodingChecks)}getExpected(){if(this.propertySignatures.length===0&&this.indexSignatures.length===0)return"object | array";return"object"}};Db={onItem(e,t){if(!oa(e.input,t.name))return t.parser(ae,e.options);let n=e.input[t.name];return Or(e.out,t.name,n),t.parser(n,e.options)},step:Tm},bb=uu()(Db),$I=fu()(Db);Lm=Mo((e)=>{while(!0){if(Rb(e))return Mu;let t=e.encoding;if(!t)return e.recur?.(Lm,Xe)??e;if(t.some((n)=>n.transformation._tag==="Middleware"&&n.transformation.decode!==Xe))return Mu;e=t[t.length-1].to}});_b=new WeakMap,Au=Object.freeze([]);ua=class extends In{_tag="Union";types;options;encodingChecks;constructor(e,t,n,r,i,o,a){super(n,r,i,o);this.types=e,this.options=t,this.encodingChecks=a}getParser(e,t){let n=this,r=t!==void 0,i=[],o=(s)=>i[s]??=e(n.types[s]),a;return(s,c)=>{if(s===ae)return kn;let f=(a??=jI(n.types))(s,r);if(f.length===0)return p(new zs(n,[],s,c));if(f.length===1){let l=o(f[0])(s,c);if(l._tag==="Success")return l;return Ne(l)?Ub(n,l.cause,s,c):BI(n,l,s,c)}return VI(n,o,f,s,c)}}_rebuild(e,t,n){let r=la(this.types,e);return r===this.types&&t===this.checks&&n===this.encodingChecks?this:new ua(r,this.options,this.annotations,t,void 0,this.context,n)}recur(e){return this._rebuild(e,this.checks,this.encodingChecks)}flip(e){return this._rebuild(e,this.encodingChecks,this.checks)}matchPart(e,t){for(let n of this.types){let r=n.matchPart(e,t);if(r!==void 0)return r}return}getExpected(e){let t=this.annotations?.expected;if(typeof t==="string")return t;if(this.types.length===0)return"never";let n=this.types.map((r)=>{let i=Bm(r);switch(i._tag){case"Arrays":{let o=i.elements.filter(sa);if(o.length>0)return`${Cb(i.isMutable)}[ ${o.map((a)=>e(a)+Tb(a.context?.isOptional)).join(", ")}, ... ]`;break}case"Objects":{let o=i.propertySignatures.filter((a)=>sa(a.type));if(o.length>0)return`{ ${o.map((a)=>`${Cb(a.type.context?.isMutable)}${Lo(a.name)}${Tb(a.type.context?.isOptional)}: ${e(a.type)}`).join(", ")}, ... }`;break}}return e(i)});return Array.from(new Set(n)).join(" | ")}};zI=uu()({onItem(e,t){return e.parser(t)(e.input,e.options)},step(e,t,n){if(n._tag==="Failure"){let r=Js(n.cause);if(r===void 0)return n;if(e.issues)e.issues.push(r);else e.issues=[r]}else{if(e.out&&e.successes)return e.successes.push(e.ast.types[t]),Zo(new ab(e.ast,e.successes,e.input,e.options));if(e.out=n,e.successes)e.successes.push(e.ast.types[t]);else return Xo}}}),$b=new ua([new aa("Infinity"),new aa("-Infinity"),new aa("NaN")]);km=class extends Za{_tag="Filter";run;annotations;aborted;constructor(e,t=void 0,n=!1){super();this.run=e,this.annotations=t,this.aborted=n}annotate(e){return new km(this.run,{...this.annotations,...e},this.aborted)}abort(){return new km(this.run,this.annotations,!0)}and(e,t){return new Fu([this,e],t)}},Fu=class extends Za{_tag="FilterGroup";checks;annotations;constructor(e,t=void 0){super();this.checks=e,this.annotations=t}annotate(e){return new Fu(this.checks,{...this.annotations,...e})}and(e,t){return new Fu([this,e],t)}};jb=Zs(Am,[Um()]),JI=new Rn(new ua([jb,$b]),new gn(Tu(),zt((e)=>globalThis.Number.isFinite(e)?e:globalThis.String(e))));Rm=new WeakMap;zu=Mo((e)=>{let t=e.context?e.context.isOptional===!1?new ca(!0,e.context.isMutable,e.context.constructorDefault,e.context.annotations):e.context:new ca(!0,!1);return YI(Ys(e,t))}),YI=HI(zu),zb=Qa((e)=>zu(new ua([e,Om])));di=Mo((e)=>{let t=Vu(e);if(t!==e){let r=di(t);return r===t&&e.encoding===void 0?e:Ys(r,e.context)}let n="recur"in e?e.recur(di):e;if("encodingChecks"in n&&n.encodingChecks){let r=QI(e)?n.encodingChecks:TI(n)||kI(n)||kb(n)&&n.typeParameters.length>0?XI(n.encodingChecks):void 0;return Gs(n,{encodingChecks:void 0,checks:Nm(n.checks,r)})}return n}),Bm=Mo((e)=>di($r(e)));$r=Qa((e)=>{if(e.encoding)return eP(e,e.encoding);let t=Vu(e);if(t!==e){let n=$r(t);return n===t?e:Ys(n,e.context)}return"flip"in e?e.flip($r):("recur"in e)?e.recur($r):e});qm=KI((e)=>{switch(e._tag){default:return e;case"Number":return e.toCodecStringTree();case"Union":return e.recur(qm)}}),Im=new globalThis.RegExp(`^${Ob}$`),tP=new globalThis.RegExp(`^(?:${Ob}|Infinity|-Infinity|NaN)$`);Zb=Zs(no,[Yb()]),nP=new Rn(Zb,Iu),rP=new Rn(new ua([Zb,$b]),Iu),V1=new globalThis.RegExp(`^${iP}$`),q1=new globalThis.RegExp(`^${oP}$`);e_=new Ks([],()=>(e,t,n)=>cP(e)?Ie:p(new fr(t,e,n)),{representation:{id:"effect/schema/Json",payload:null},expected:"JSON value",toCodecJson:()=>{return},toCodecStringTree:()=>fP});uP=new Ks([],()=>(e,t,n)=>lP(e)?Ie:p(new fr(t,e,n)),{expected:"StringTree",toCodecStringTree:()=>{return}}),fP=new Rn(uP,Ru())});function n_(e){if(e._tag==="Middleware")return(n,r,i)=>{let o=n===Ie?e.decode(wt(Ls(r)),i):e.decode(am(n,Ls),i);return t_(o)};let t=e.decode;switch(t._tag){case"Passthrough":return(n,r)=>n===Ie?wt(r):n;case"Transform":{let n=(r)=>r===ae?kn:wt(t.transform(r));return(r,i)=>Wu(r,i,n)}case"TransformOptional":{let n=(r)=>pm(t.transform(Ls(r)));return(r,i)=>Wu(r,i,n)}case"TransformEffect":return(n,r,i)=>Wu(n,r,(o)=>o===ae?kn:t.transform(o,i));case"TransformOptionalEffect":return(n,r,i)=>Wu(n,r,(o)=>t_(t.transform(Ls(o),i)))}}function dP(e,t){let n=n_(e.link.transformation),r;return(i,o)=>{if(i===ae)return kn;if(e.isConstructed(i))return Ie;let a=(r??=t(e.link.to))(i,o);return n(a,i,o)}}function pP(e,t){let n=e.context.constructorDefault;return(r,i)=>{if(r!==ae&&r!==void 0)return t(r,i);let o=n;if(Ne(o)&&o._tag==="Success"){let a=t(o[ie],i);return a===Ie?o:a}return qt(r_(e,r,i,o),(a)=>{let s=t(a,i);return s===Ie?wt(a):s})}}function zm(e,t){let n=t(e);return e.context?.constructorDefault===void 0?n:pP(e,n)}function ec(e,t,n,r,i){if(e._tag==="Declaration")for(let y of e.typeParameters)t(y);let o=n?Xb(e):void 0,a=o?dP(o,t):r??e.getParser(t,n),{checks:s,encoding:c}=e,f=c?.map((y)=>n_(y.transformation)),l=e.encodingChecks;if(!c&&!s&&!l)return a;let u,g=(y,S)=>{let m=a(y,S);if(l&&!S.disableChecks)if(Ne(m)){if(m._tag==="Success"){let x=m===Ie?y:m[ie];if(y!==ae&&x!==ae){let E=pi(l,y,void 0,e,S);if(E)m=p(new At(e,E,y,S))}}}else m=Re(m,(x)=>{if(y!==ae&&x!==ae){let E=pi(l,y,void 0,e,S);if(E)return p(new At(e,E,y,S))}return M(x)});if(s&&!S.disableChecks)if(Ne(m)){if(m._tag==="Success"){let x=m===Ie?y:m[ie];if(x===ae)return m;let E=pi(s,x,void 0,e,S);if(E)m=p(new At(e,E,x,S))}}else m=Re(m,(x)=>{if(x!==ae){let E=pi(s,x,void 0,e,S);if(E)return p(new At(e,E,x,S))}return M(x)});return m},h=i===void 0?g:i(g);if(!c)return h;return(y,S)=>{let m=u??=c.map((_)=>t(_.to)),x=y,E=m[m.length-1](y,S);for(let _=c.length-1;_>=0;_--)if(E=f[_](E,x,S),_!==0){let C=m[_-1];if(E._tag==="Success")x=E[ie],E=C(x,S);else E=qt(E,(N)=>{let D=C(N,S);return D===Ie?wt(N):D})}if(E._tag==="Success"){let _=E[ie],C=h(_,S);return C===Ie?E:C}return E=r_(e,y,S,E),qt(E,(_)=>{let C=h(_,S);return C===Ie?wt(_):C})}}var Wu=(e,t,n)=>e===Ie?n(t):qt(e,n),t_=(e)=>qt(e,pm),r_=(e,t,n,r)=>Dr(r,(i)=>hu(()=>Gi(i,(o)=>new ob(e,o,t,n))));var i_=L(()=>{Yi();De();Qs();li();Mr();ia()});class Wm{ast;constructor(e){this.ast=e}get decodeEffect(){return this.cachedDecodeEffect??=ec(this.ast,gP)}get parser(){return this.decodeEffect}get makeEffect(){return this.cachedMakeEffect??=ec(this.ast,s_,hP)}}function yP(e,t){let n;return(r,i)=>{if(r!==ae)try{let o=e(r,i);if(o!==Jm)return o===r?Ie:wt(o)}catch(o){return Ps(o)}return(n??=t())(r,i)}}function Hu(e,t,n){let r=e(t);if(r.compiled===void 0||Object.hasOwn(r,n))return r[n];let i;return(o,a)=>(i??=r[n])(o,a)}function zn(e){let t=o_.get(e);if(t!==void 0)return t;let n=a_===void 0?new Wm(e):new c_(e,a_(e,zn),zn);return o_.set(e,n),n}var Jm,o_,a_,Ku=!1,gP=(e)=>Ku?Hu(zn,e,"parser"):zn(e).parser,s_=(e)=>Ku?Hu(zn,e,"makeEffect"):zn(e).makeEffect,hP=(e)=>zm(e,s_),c_;var l_=L(()=>{De();i_();ia();Jm=Symbol(),o_=new WeakMap;c_=class c_ extends Wm{compiled;resolve;constructor(e,t,n){super(e);this.compiled=t,this.resolve=n}save(e,t){return Object.defineProperty(this,e,{value:t}),t}operation(e){let t=this.compiled;return typeof t==="function"?t(this.ast,this.resolve,e):t?.[e]}get is(){return this.save("is",this.operation("is"))}get decode(){return this.save("decode",this.operation("decode"))}get make(){return this.save("make",this.operation("make"))}get decodeEffect(){return this.save("decodeEffect",this.operation("decodeEffect")??ec(this.ast,(e)=>Hu(this.resolve,e,"parser")))}get parser(){let e=this.decode;return e===void 0?this.decodeEffect:this.save("parser",yP(e,()=>this.decodeEffect))}get makeEffect(){let e=this.operation("makeEffect");if(e!==void 0)return this.save("makeEffect",e);let t=(n)=>Hu(this.resolve,n,"makeEffect");return this.save("makeEffect",ec(this.ast,t,(n)=>zm(n,t)))}}});function Hm(e){let t=e.ast,n;return(r,i)=>(n??=m_(kP,di(t)))(r,i?.disableChecks?i?.parseOptions?{...i.parseOptions,disableChecks:!0}:{disableChecks:!0}:i?.parseOptions)}function Km(e){let t=Hm(e);return(n,r)=>{let i=Qi(t(n,r));if(Nr(i))return Wo(i.value);return ui(i.cause,"Option adapter can only return none for schema issues"),Jo()}}function Gm(e){return CP(di(e.ast))}function u_(e){return vP(e.ast)}function EP(e){if(!Ku){let i=g_(d_(e));return(o)=>{let a=i(o,oo);if(Nr(a))return!0;return ui(a.cause,"Type guard adapter can only return false for schema issues"),!1}}let t=zn(e),n=t.is;if(n!==void 0)return(i)=>{try{return n(i,oo)}catch(o){return ui(im(o),"Type guard adapter can only return false for schema issues"),!1}};let r=t.parser;return(i)=>{let o=Qi(p_(r(i,oo),i));if(Nr(o))return!0;return ui(o.cause,"Type guard adapter can only return false for schema issues"),!1}}function vP(e){let t=di(e),n=(r)=>(n=EP(t),n(r));return(r)=>n(r)}function Ym(e,t){let n=d_(e.ast);return t===void 0?n:(r,i)=>n(r,bP(t,i))}function f_(e,t){return _P(Ym(e,t))}function d_(e){return m_(TP,e)}function p_(e,t){if(e===Ie)return M(t);if(!Ne(e))return qt(e,Gu);return e[ie]===ae?Gu(ae):e}function m_(e,t){let n;return(r,i)=>{let o=(n??=e(t))(r,i??oo);if(o===Ie)return M(r);if(!Ne(o))return qt(o,Gu);return o[ie]===ae?Gu(ae):o}}function g_(e){return(t,n)=>Qi(e(t,n))}function _P(e){let t=g_(e);return(n,r)=>{let i=t(n,r);if(Nr(i))return cr(i.value);return pn(ui(i.cause,"Result adapter can only return schema issues"))}}function wP(e,t){let n=Qi(e);if(Nr(n))return n.value;let r=ui(n.cause,t);throw Error("Schema validation failed",{cause:r})}function CP(e){let t,n;return(r,i)=>{t??=zn(e);let o=i?.disableChecks?i.parseOptions?{...i.parseOptions,disableChecks:!0}:{disableChecks:!0}:i?.parseOptions??oo,a=t.make;if(a!==void 0&&r!==ae){let c;try{c=a(r,o)}catch(f){throw ui(im(f),"Constructor adapter can only throw schema issues"),f}if(c!==Jm&&c!==ae)return c}let s=(n??=t.makeEffect)(r,o);return wP(p_(s,r),"Constructor adapter can only throw schema issues")}}var bP=(e,t)=>t?{...e,...t}:e,Gu=(e)=>{if(e===ae)return p(new Ot);return M(e)},TP=(e)=>zn(e).parser,kP=(e)=>zn(e).makeEffect;var Zm=L(()=>{Yi();De();Qo();Mr();ym();l_();ia();Jl();bt();Qs();li()});function Qm(e,t){function n(){}let r=Object.setPrototypeOf(n,RP);if(t&&(Object.hasOwn(t,"name")||Object.hasOwn(t,"length")||Object.hasOwn(t,"__proto__")))Object.defineProperties(r,Object.getOwnPropertyDescriptors({...t}));else Object.assign(r,t);return r[y_]=t,r.ast=e,r}var Xm="~effect/Schema/Schema",y_,RP;var S_=L(()=>{Ir();Qs();Zm();y_=Symbol(),RP={[Xm]:Xm,get make(){let e=Gm(this);return Object.defineProperty(this,"make",{value:e,enumerable:!0}),e},get makeEffect(){let e=Hm(this);return Object.defineProperty(this,"makeEffect",{value:e,enumerable:!0}),e},get makeOption(){let e=Km(this);return Object.defineProperty(this,"makeOption",{value:e,enumerable:!0}),e},pipe(){return en(this,arguments)},annotate(e){return this.rebuild(qu(this.ast,e))},annotateKey(e){return this.rebuild(jm(this.ast,e))},check(...e){return this.rebuild(Zs(this.ast,e))},rebuild(e){return Qm(e,this[y_])}}});var tc=(e)=>e;var x_=()=>{};function E_(e){return we(e,fa)&&e[fa]===fa}var fa="~effect/Schema/SchemaError";var v_=L(()=>{$t()});function OP(){return(e,t,n)=>Ge(new Ks(e.map($u),(r)=>t(r.map((i)=>Ge(i))),n))}function AP(e,t){return OP()([],()=>(n,r,i)=>e(n)?M(n):p(new fr(r,n,i)),t)}function MP(e){return E_(e)}function NP(e){if(Ne(e))return DP(e);return Dr(e,(t)=>hu(()=>Gi(t,(n)=>new Yu(n))))}function DP(e){return Nr(e)?e:Rs(Gi(e.cause,(t)=>new Yu(t)))}function FP(e,t){let n;for(let r of e.reasons){if(!gu(r)||!MP(r.error))throw new globalThis.Error(t,{cause:e});n??=r.error}if(n===void 0)throw new globalThis.Error(t,{cause:e});return n}function LP(e){let t=Qi(e);if(Nr(t))return t.value;throw FP(t.cause,"Sync adapter can only throw schema errors")}function UP(e,t){let n=Ym(e,t);return(r,i)=>NP(n(r,i))}function Pe(e,t){let n=f_(e,t);return(r,i)=>Zx(n(r,i),(o)=>new Yu(o))}function dr(e,t){let n=UP(e,t);return(r,i)=>LP(n(r,i))}function eg(e){let t=Ge(new aa(e),{literal:e,transform(n){return t.pipe(Zu(eg(n),{decode:zt(()=>n),encode:zt(()=>e)}))}});return t}function __(e,t){return Ge(e,{fields:t,mapFields(n,r){let i=n(this.fields);return __(Dm(i,r?.unsafePreserveChecks?this.ast.checks:void 0),i)}})}function b(e){return __(Dm(e,void 0),e)}function We(e,t){return Ge(Hb(e.ast,t.ast),{key:e,value:t})}function ke(e,t){return Ge(Fb(e.ast,t.map($u)),{schema:e,records:t})}function w_(e,t){return Ge(e,{elements:t,mapElements(n,r){let i=n(this.elements);return w_(Fm(i,r?.unsafePreserveChecks?this.ast.checks:void 0),i)}})}function tg(e){return w_(Fm(e),e)}function C_(e,t){return Ge(e,{members:t,mapMembers(n,r){let i=n(this.members);return C_(ju(i,this.ast.options,r?.unsafePreserveChecks?this.ast.checks:void 0),i)}})}function Z(e,t){return C_(ju(e,t,void 0),e)}function T(e){let t=e.map(eg);return Ge(ju(t,void 0,void 0),{literals:e,members:t,mapMembers(n){return Z(n(this.members))},pick(n){return T(n)},transform(n){return Z(t.map((r,i)=>r.transform(n[i])))}})}function ao(e){return(t)=>Ge(t.ast,{schema:t,identifier:e})}function Zu(e,t){return(n)=>Ge(Wb(n.ast,e.ast,t?vm(t):Ru()),{from:n,to:e})}function BP(e){return(t)=>Ge(Jb(t.ast,e),{schema:t})}function b_(e){return eg(e).pipe(BP(M(e)))}function da(e,t){return AP((n)=>n instanceof e,t)}function pa(){return(e,t)=>new Rn(e.ast,vm(t))}function ue(e,t){let{source:n,flags:r}=e,i=/^[dg]*uy?$/.test(r),o=r===""?`new RegExp(${Te(n)})`:`new RegExp(${Te(n)}, ${Te(r)})`;return $m(e,{toJsonSchema:()=>i?{pattern:r.endsWith("y")?`^(?:${n})`:n}:[{},!0],toCode:()=>({runtime:`Schema.isPattern(${o})`}),...t})}function VP(e){let t=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;return ue(t,{expected:"a base64 encoded string",representation:{id:"effect/schema/isBase64",payload:null},toJsonSchema:()=>({pattern:t.source}),toCode:()=>({runtime:"Schema.isBase64()"}),...e})}function qP(e){let t=zl(e.order),n=e.formatter??Te;return(r,i)=>ee((o)=>t(o,r),{expected:`a value greater than ${n(r)}`,arbitraryConstraint:{order:e.order,minimum:r,exclusiveMinimum:!0},...e.annotate?.(r),...i})}function zP(e){let t=kx(e.order),n=e.formatter??Te;return(r,i)=>ee((o)=>t(o,r),{expected:`a value greater than or equal to ${n(r)}`,arbitraryConstraint:{order:e.order,minimum:r},...e.annotate?.(r),...i})}function JP(e){let t=Tx(e.order),n=e.formatter??Te;return(r,i)=>ee((o)=>t(o,r),{expected:`a value less than or equal to ${n(r)}`,arbitraryConstraint:{order:e.order,maximum:r},...e.annotate?.(r),...i})}function ng(e){if(!globalThis.Number.isFinite(e))throw new globalThis.RangeError(`Expected a finite number, got ${Te(e)}`);return e}function Qu(e){return ee((t)=>globalThis.Number.isSafeInteger(t),{expected:"an integer",representation:{id:"effect/schema/isInt",payload:null},toJsonSchema:()=>[{type:"integer"},!0],toCode:()=>({runtime:"Schema.isInt()"}),arbitraryConstraint:{number:"integer"},...e})}function at(e,t){return e=R_(e),WP(e,Math.ceil(e/2),t)}function WP(e,t,n){return ee((r)=>r.length>=e,{expected:`a value with a length of at least ${e}`,representation:{id:"effect/schema/isMinLength",payload:{minLength:e}},toJsonSchema:({type:r})=>r==="string"?e<=1?{minLength:t}:[{minLength:t},!0]:r==="array"?{minItems:e}:r===void 0?[{minLength:t,minItems:e},!0]:[{},!0],toCode:()=>({runtime:`Schema.isMinLength(${e})`}),[Fs]:!0,arbitraryConstraint:{minLength:e},...n})}function rg(e,t){return e=R_(e),ee((n)=>n.length<=e,{expected:`a value with a length of at most ${e}`,representation:{id:"effect/schema/isMaxLength",payload:{maxLength:e}},toJsonSchema:({type:n})=>n==="string"?e===0?{maxLength:e}:[{maxLength:e},!0]:n==="array"?{maxItems:e}:n===void 0?[{maxLength:e,maxItems:e},!0]:[{},!0],toCode:()=>({runtime:`Schema.isMaxLength(${e})`}),[Fs]:!0,arbitraryConstraint:{maxLength:e},...t})}function R_(e){if(!globalThis.Number.isFinite(e))throw new globalThis.RangeError(`Expected a finite number, got ${e}`);return Math.max(0,Math.floor(e))}function tf(e,t){return KP.pipe(Zu(e,Pu(t)))}var Yu,be,Ge,qe,k,lt,ot,$P,w,xt,W,j,jP,ee,T_,nc,Xu,k_,ef,Fq,HP,Lq,KP,GP,Uq,$q,YP,jq,ZP=-8640000000000000,XP=8640000000000000,Bq,Vq,nn,mi;var Fe=L(()=>{Yi();Tp();De();cm();Qo();Pr();Mr();_u();S_();v_();Ul();sp();bt();Qs();ku();li();Zm();Ou();x_();Yu=class Yu extends ru("SchemaError"){[fa]=fa;constructor(e){let t=$o();jo(0);try{super({issue:e})}finally{jo(t)}}get message(){return fb(this.issue)}toString(){return`SchemaError(${this.message})`}};be=u_;Ge=Qm,qe=tc((e)=>Ge(zu(e.ast),{schema:e})),k=tc((e)=>{let t=jP(e);return Ge(zb(e.ast),{schema:t})});lt=Ge(Mu),ot=Ge(Pm),$P=Ge(Om),w=Ge(no),xt=Ge(Am),W=Ge(Ib);j=tc((e)=>Ge(new Lu(!1,[],[e.ast]),{value:e}));jP=tc((e)=>Z([e,$P]));ee=Bu;T_=Um;nc=qP({order:zo,annotate:(e)=>({representation:{id:"effect/schema/isGreaterThan",payload:{exclusiveMinimum:ng(e)}},toJsonSchema:()=>({exclusiveMinimum:e}),toCode:()=>({runtime:`Schema.isGreaterThan(${Te(e)})`})})}),Xu=zP({order:zo,annotate:(e)=>({representation:{id:"effect/schema/isGreaterThanOrEqualTo",payload:{minimum:ng(e)}},toJsonSchema:()=>({minimum:e}),toCode:()=>({runtime:`Schema.isGreaterThanOrEqualTo(${Te(e)})`})})}),k_=JP({order:zo,annotate:(e)=>({representation:{id:"effect/schema/isLessThanOrEqualTo",payload:{maximum:ng(e)}},toJsonSchema:()=>({maximum:e}),toCode:()=>({runtime:`Schema.isLessThanOrEqualTo(${Te(e)})`})})});ef=xt.check(Qu());Fq=da(globalThis.RegExp,{representation:{id:"effect/schema/RegExp",payload:null},toCode:()=>({runtime:"Schema.RegExp",Type:"globalThis.RegExp"}),expected:"RegExp",toCodecJson:()=>pa()(b({source:w,flags:w}),Hs({decode:(e,t)=>V({try:()=>new globalThis.RegExp(e.source,e.flags),catch:()=>new Ot({expected:"valid RegExp source and flags"},e,t)}),encode:(e)=>M({source:e.source,flags:e.flags})}))}),HP=w.annotate({expected:"a string that will be decoded as a URL"}),Lq=da(globalThis.URL,{representation:{id:"effect/schema/URL",payload:null},toCode:()=>({runtime:"Schema.URL",Type:"globalThis.URL"}),expected:"URL",toCodecJson:()=>pa()(HP,Sb)}),KP=w.annotate({expected:"a string that will be decoded as JSON",contentMediaType:"application/json"});GP=da(globalThis.File,{representation:{id:"effect/schema/File",payload:null},toCode:()=>({runtime:"Schema.File",Type:"globalThis.File"}),expected:"File",toCodecJson:()=>pa()(b({data:w.check(VP()),type:w,name:w,lastModified:ef}),Hs({decode:(e,t)=>Ql(vu(e.data),{onFailure:()=>p(new Ot({expected:"a valid Base64 string"},e.data,t)),onSuccess:(n)=>{let r=new globalThis.Uint8Array(n);return M(new globalThis.File([r],e.name,{type:e.type,lastModified:e.lastModified}))}}),encode:(e,t)=>d({try:async()=>{let n=new globalThis.Uint8Array(await e.arrayBuffer());return{data:Eu(n),type:e.type,name:e.name,lastModified:e.lastModified}},catch:()=>new Ot({expected:"a readable File"},e,t)})}))}),Uq=da(globalThis.FormData,{representation:{id:"effect/schema/FormData",payload:null},toCode:()=>({runtime:"Schema.FormData",Type:"globalThis.FormData"}),expected:"FormData",toCodecJson:()=>pa()(j(tg([w,Z([b({_tag:b_("String"),value:w}),b({_tag:b_("File"),value:GP})])])),Hs({decode:(e)=>{let t=new globalThis.FormData;for(let[n,r]of e)t.append(n,r.value);return M(t)},encode:(e)=>M(globalThis.Array.from(e.entries()).map(([t,n])=>{if(typeof n==="string")return[t,{_tag:"String",value:n}];else return[t,{_tag:"File",value:n}]}))}))}),$q=da(globalThis.URLSearchParams,{representation:{id:"effect/schema/URLSearchParams",payload:null},toCode:()=>({runtime:"Schema.URLSearchParams",Type:"globalThis.URLSearchParams"}),expected:"URLSearchParams",toCodecJson:()=>pa()(w.annotate({expected:"a query string that will be decoded as URLSearchParams"}),yb({decode:(e)=>new globalThis.URLSearchParams(e),encode:(e)=>e.toString()}))}),YP=w.annotate({expected:"a base64 encoded string that will be decoded as Uint8Array",format:"byte",contentEncoding:"base64"}),jq=da(globalThis.Uint8Array,{representation:{id:"effect/schema/Uint8Array",payload:null},toCode:()=>({runtime:"Schema.Uint8Array",Type:"globalThis.Uint8Array"}),expected:"Uint8Array",toCodecJson:()=>pa()(YP,xb)}),Bq=ZP+50400000,Vq=XP-50400000,nn=Ge(qu(e_,{toCode:()=>({runtime:"Schema.Json",Type:"Schema.Json"})})),mi=We(w,nn)});function hn(e,t){return Pe(e,QP)(t)}var QP;var ma=L(()=>{Fe();QP={onExcessProperty:"error"}});function M_(e){let t=Pe(ga)(e);return Ve(t)?t.success:void 0}function ig(e){return M_(e)!==void 0}function N_(e){return ig(e)&&!e.includes("-")}function I_(e){if(e===void 0||e.length===0||e[0]==="0")return!1;for(let t of e)if(t<"0"||t>"9")return!1;return!0}function eO(e){let[t,n,r]=e.split("-");if(t===void 0||n===void 0||r!==void 0)return!1;if(!N_(t))return!1;let[i,o,a,s]=n.split(".");return i==="dev"&&s===void 0&&I_(o)&&I_(a)}function nf(e){let t=M_(e);if(t===void 0)throw Error(`The canonical version ${e} is invalid.`);let n=t.split("-",1)[0];if(n===void 0)throw Error(`The canonical version ${e} has no base version.`);return n}function ha(e,t){let n=P_(e),r=P_(t),i=rc(n.minor,r.minor);if(i!==0)return i;let o=rc(n.patch,r.patch);if(o!==0)return o;return tO(n.suffix,r.suffix)}function ag(e,t){let n=nf(t);if(e!=="patch"&&e!=="minor"){if(!ig(e))throw Error("The version target is invalid.");return e}let[,r,i]=n.split(".");if(r===void 0||i===void 0)throw Error(`The canonical version ${t} has an invalid base version.`);let o=BigInt(r),a=BigInt(i);return e==="minor"?`0.${o+1n}.0`:`0.${o}.${a+1n}`}function P_(e){let[t,n]=e.split("-",2),r=t?.split("."),i=r?.[1],o=r?.[2];if(i===void 0||o===void 0)throw Error(`The release version ${e} has an invalid base version.`);if(n===void 0)return{minor:i,patch:o,suffix:{kind:"base"}};if(n.startsWith("dev.")){let[,a,s]=n.split(".");if(a===void 0||s===void 0)throw Error(`The development version ${e} has an invalid release suffix.`);return{minor:i,patch:o,suffix:{kind:"development",runNumber:a,runAttempt:s}}}return{minor:i,patch:o,suffix:{kind:"numeric",value:n}}}function rc(e,t){let n=BigInt(e),r=BigInt(t);if(n<r)return-1;if(n>r)return 1;return 0}function tO(e,t){let n=O_(e),r=O_(t);if(n<r)return-1;if(n>r)return 1;if(e.kind==="numeric"&&t.kind==="numeric")return rc(e.value,t.value);if(e.kind==="development"&&t.kind==="development"){let i=rc(e.runNumber,t.runNumber);return i===0?rc(e.runAttempt,t.runAttempt):i}return 0}function O_(e){if(e.kind==="development")return 0;if(e.kind==="base")return 1;return 2}var A_,ga,og,D_,ic;var F_=L(()=>{bt();Fe();A_=/^0\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)(?:-(?:0|[1-9]\d*))?$/u,ga=w.check(ue(A_));og=w.check(ee(N_));D_=w.check(ee(eO)),ic=Z([ga,D_])});function cg(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(r==="unified-computer-use"&&i==="openai-bundled"&&t===i)return{pluginName:"computer-use",marketplaceName:i,canonicalPluginId:"computer-use@openai-bundled"};if(r==="sites"&&i==="openai-curated-remote"&&t===i)return{pluginName:r,marketplaceName:i,canonicalPluginId:"sites@openai-bundled"};if(B_(r)&&i==="openai-bundled"&&t===i)return{pluginName:r,marketplaceName:i,canonicalPluginId:e};if(!j_(r)||!$_(i)||t!==i)return;return{pluginName:r,marketplaceName:i,canonicalPluginId:`${r}@openai-curated`}}function Pn(e){let t=e.lastIndexOf("@");if(t<=0)return;let n=e.slice(0,t),r=e.slice(t+1);if(n==="unified-computer-use"&&r==="openai-bundled")return"computer-use@openai-bundled";if(n==="sites"&&r==="openai-curated-remote")return"sites@openai-bundled";if(j_(n)&&$_(r))return`${n}@openai-curated`;if(B_(n)&&r==="openai-bundled")return`${n}@openai-bundled`;return}function ya(e){let t=Pn(e);if(t===void 0)return[];if(t==="computer-use@openai-bundled")return Object.freeze(["unified-computer-use@openai-bundled",t]);if(t==="sites@openai-bundled")return Object.freeze([t,"sites@openai-curated-remote"]);if(t.endsWith("@openai-bundled"))return Object.freeze([t]);let n=t.slice(0,t.lastIndexOf("@"));return Object.freeze([t,`${n}@openai-curated-remote`])}function $_(e){return be(iO)(e)}function j_(e){return be(oO)(e)}function B_(e){return be(aO)(e)}function lg(e,t){let n=t??Mt;return{browser_use:e?.browser_use??n.browser_use,computer_use:e?.computer_use??n.computer_use,sites:e?.sites??n.sites}}function Sa(e,t=[]){let n=[...q_],r=new Set(n);for(let i of V_){if(!e[i])continue;for(let o of jr[i].pluginIds)if(!r.has(o))r.add(o),n.push(o)}for(let i of t){if(i==="browser@openai-bundled")continue;if(!r.has(i))r.add(i),n.push(i)}return n}var oc,sg,nO,rO,L_,iO,rf,oO,U_,aO,ut,gi,sO,cO,jr,V_,lO,q_,uO,Mt;var ug=L(()=>{Fe();oc=T(["browser_use","computer_use","frontend","security","sites"]),sg=T(["browser_use","computer_use","sites"]),nO=T(["installed","disabled","missing","uncertain"]),rO=T(["healthy","missing","disabled","uncertain"]),L_=Object.freeze(["openai-curated","openai-curated-remote"]),iO=T(L_),rf=Object.freeze(["build-web-apps","codex-security"]),oO=T(rf),U_=Object.freeze(["browser","computer-use","sites"]),aO=T(U_);ut=Object.freeze({coding:!0,computer_use:!1,browser_use:!0,sites:!0,frontend:!0,security:!0}),gi=Object.freeze({frontend:Object.freeze([{skillId:"build-web-apps:frontend-app-builder",appliesWhen:"a new visually-driven UI or meaningful redesign"},{skillId:"build-web-apps:frontend-testing-debugging",appliesWhen:"a rendered UI or interaction defect"},{skillId:"build-web-apps:react-best-practices",appliesWhen:"a relevant React or Next implementation or review"}]),security:Object.freeze([]),computer_use:Object.freeze([]),browser_use:Object.freeze([]),sites:Object.freeze([])}),sO=gi.frontend,cO={frontend:{name:"frontend",pluginIds:["build-web-apps@openai-curated"],defaultSelected:ut.frontend,semanticSkillIds:Object.freeze(gi.frontend.map(({skillId:e})=>e)),applicability:gi.frontend,ownership:"shared-preserve"},security:{name:"security",pluginIds:["codex-security@openai-curated"],defaultSelected:ut.security,semanticSkillIds:["codex-security:security-scan","codex-security:security-diff-scan","codex-security:threat-model"],applicability:gi.security,ownership:"shared-preserve"},computer_use:{name:"computer_use",pluginIds:["computer-use@openai-bundled"],defaultSelected:ut.computer_use,migrationKey:"computer_use",semanticSkillIds:["computer-use:computer-use"],applicability:gi.computer_use,ownership:"shared-preserve"},browser_use:{name:"browser_use",pluginIds:[],defaultSelected:ut.browser_use,migrationKey:"browser_use",semanticSkillIds:[],applicability:gi.browser_use,ownership:"shared-preserve"},sites:{name:"sites",pluginIds:["sites@openai-bundled"],defaultSelected:ut.sites,migrationKey:"sites",semanticSkillIds:[],applicability:gi.sites,ownership:"shared-preserve"}},jr=Object.freeze(cO),V_=Object.freeze(["browser_use","computer_use","sites"]),lO=Object.freeze(["frontend","security"]),q_=Object.freeze([...jr.frontend.pluginIds,...jr.security.pluginIds]),uO=Object.freeze(["writing-instructions","babysit-ci","dev-server","visual-loop"]),Mt=Object.freeze({browser_use:ut.browser_use,computer_use:ut.computer_use,sites:ut.sites})});function pr(e){return b({identifier:T([e]),label:w,requiresRootApproval:W})}function z_(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 J_(e){return e.length===0?e:`${e[0]?.toUpperCase()??""}${e.slice(1)}`}var W_,fO,dO,fg,pO,H_,mO,gO,hO;var K_=L(()=>{Fe();W_=T(["local.repository.edit","local.repository.check","local.repository.lint","local.repository.format","local.repository.commit","external.read","specialist.dispatch","vcs.server.mutation","vcs.server.ci-trigger","unknown.effect"]),fO=b({identifier:W_,label:w,requiresRootApproval:W});dO=b({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")}),fg={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}};ur(fg);pO=T(["never","root"]),H_=Object.values(fg);mO=H_.filter((e)=>!e.requiresRootApproval),gO=H_.filter((e)=>e.requiresRootApproval),hO=Object.freeze({noRootApproval:`${J_(z_(mO))} actions do not require Root approval.`,rootApproval:`${J_(z_(gO))} require Root approval.`})});function pg(e){let t=hn(yO,e);if(Me(t))return eo(Ns("sha256 digest",t.failure));return na(t.success)}var Jn,dg,Yq,Zq,Xq,yO,SO,xO,EO,vO;var of=L(()=>{bt();Fe();ra();ma();Jn=w.check(ue(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u)),dg=w.check(ue(/^[0-9a-f]{64}$/u)),Yq=Jn.pipe(ao("RunId")),Zq=Jn.pipe(ao("ProjectId")),Xq=Jn.pipe(ao("TrustId")),yO=dg.pipe(ao("Sha256Digest"));SO=b({run_id:Jn,objective_lineage:Jn,parent_run_id:k(Z([Jn,ot]))}),xO=b({project_id:Jn,trust_id:Jn,trust_digest:dg}),EO=b({project_id:Jn,project_digest:dg}),vO=w.check(ue(/^state-[0-9]+\.[0-9]+$/u))});function cf(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 Sg(e){let t=`${e.role}.${e.task}`;return dr(yg)(t)}function xg(e){let t=mg.get(e.role);if(t===void 0)throw Error("Unknown specialist task policy.");let n=t.tasks.find((r)=>r.name===e.task);if(n===void 0)throw Error("Unknown specialist task policy.");return`${n.instruction} ${t.sharedInstruction}`}function Eg(e){let t=mg.get(e.role)?.tasks.find((n)=>n.name===e.task);if(t===void 0)throw Error("Unknown specialist task policy.");return t.description}function nw(e){let t=mg.get(e);if(t===void 0)throw Error("Unknown specialist role.");return t}function vg(e){let n=nw(e.role).tasks.find((i)=>i.name===e.task);if(n===void 0)throw Error("Unknown specialist task policy.");let r=e.role==="Worker"&&e.task==="operations"?"exact_ref_or_sha":n.permissions.network?"current_sources":"disabled";return Object.freeze({network:n.permissions.network,filesystem:n.permissions.filesystem,sourceMutation:n.permissions.sourceMutation,networkScope:r})}var rn,G_,Wn,yn,bO,lf="Satisfy the complete requested outcome correctly, elegantly, and mergeably; never weaken or reinterpret it to shrink the patch. Then make the smallest coherent patch within the authorized boundary. Prefer simple, cohesive, idiomatic solutions with appropriate abstraction and minimal accidental complexity. Avoid unrelated code, prose, configuration, documentation, instructions, tests, restructuring, formatting churn, files, and operations. Preserve unrelated work; return material scope expansion to Root.",af="Treat unnecessary text, headings, subheadings, typography hierarchy, cards, pills, badges, decorative containers, labels, microcopy, repeated information, and grouping without information or interaction value as design defects. Use these primitives when they materially improve hierarchy, comprehension, composition, interaction, or content. Every visible item must be necessary or usefully complementary to the content and design.",xa="Do not modify repository source or the implementation under validation; observation, analysis, and proof artifacts only.",_O="For current library, framework, SDK, API, CLI, or cloud-service facts, resolve the library identity and query Context7 narrowly before model memory or web search. Return the typed context7 evidence state with version/source evidence. Use web search only when Context7 is unavailable, lacks relevant coverage or the required version, fails for authentication or quota, or a conflict remains after checking authoritative first-party documentation.",wO,Y_,CO,hi,mg,Z_,TO,gg,X_,Q_,ew,tw,ac,hg,yg,sc,Br,uf,rw,sf,kO,RO,IO,bg,cc,PO,Sn,OO,AO,B,_g="Minimize model decision boundaries across every tool. Group and parallelize safe operations according to information dependencies, reorder safe known work to expose batching, and continue known work before returning to the model; return only when an intermediate result must be interpreted to choose the next action. Fuse deterministic capability or backend discovery with its operation where practical. Minimize unnecessary tool calls and specialist model calls while preserving correctness, mergeability, required evidence, testing, security, and review. Make tool output decision-relevant and allow all output needed for evidence; impose no arbitrary hard output caps. Do not send progress messages to Root or peers. Finish complete mergeable work and provide necessary proof within the Assignment.";var lc=L(()=>{Fe();rn=T(["low","default","high"]),G_=T(["go","Go","plus-low","plus","plus-high","pro-5x","pro-20x"]),Wn=Z([rn,G_]);yn=T(["standard","fast","fast-all"]),bO=T(["low","medium","high","xhigh"]),wO=T(["none"]),Y_=Object.freeze(["implementation","review","validation","integration","vcs"]),CO=T(["read-only","workspace-write"]),hi=[{role:"Explorer",sharedInstruction:`Keep discovery within the assigned repository scope and return exact paths, symbols, callers, tests, and constraints. ${xa}`,tasks:[{name:"map",description:"Bounded repository structure mapping specialist.",instruction:"Map the assigned repository area: locate its relevant packages, entry points, ownership boundaries, and nearby tests or docs. Return a compact path map and identify where a follow-up lookup or trace should start; do not trace runtime behavior or resolve an unrelated fact.",permissions:{network:!0,filesystem:"read-only",sourceMutation:!1}},{name:"lookup",description:"Repository fact lookup specialist.",instruction:"Find the specific requested repository fact and cite its exact path or symbol; keep the search narrower than a structure map or execution trace.",permissions:{network:!0,filesystem:"read-only",sourceMutation:!1}},{name:"trace",description:"Repository execution and reference tracing specialist.",instruction:"Follow the assigned execution or reference path across callers, boundaries, and tests; explain the evidence-backed flow and stop at the assigned boundary.",permissions:{network:!0,filesystem:"read-only",sourceMutation:!1}}],capability:"repository-read",authority:"Read only the delegated Assignment repository scope; Git/VCS writes, Intent lifecycle, and material decisions remain Root-only.",evidence:"Return exact paths, symbols, callers, tests, and constraints.",completion:"Account for every in-scope caller and constraint.",permissions:{network:!0,filesystem:"read-only",sourceMutation:!1}},{role:"Librarian",sharedInstruction:`${_O} ${xa}`,tasks:[{name:"lookup",description:"Authoritative external fact lookup specialist.",instruction:"Answer the specific external fact with its current authoritative source.",permissions:{network:!0,filesystem:"read-only",sourceMutation:!1}},{name:"research",description:"Current authoritative-source research specialist.",instruction:"Compare and synthesize the assigned current sources with citations, noting conflicts and uncertainty.",permissions:{network:!0,filesystem:"read-only",sourceMutation:!1}}],capability:"current-research",authority:"Research only the delegated Assignment current sources without repository mutation; Git/VCS writes, Intent lifecycle, and material decisions remain Root-only.",evidence:"Return sourced facts, dates, and explicit uncertainty.",completion:"Resolve the assigned external fact or report the exact evidence gap.",permissions:{network:!0,filesystem:"read-only",sourceMutation:!1}},{role:"Worker",sharedInstruction:"Keep all implementation, repair, or proof within the assigned scope and return concise evidence proportionate to the work.",tasks:[{name:"mechanical",description:"Deterministic bounded-edit specialist.",instruction:"Apply the exact already-decided transformation within the assigned files and verify it.",permissions:{network:!0,filesystem:"workspace-write",sourceMutation:!0}},{name:"implementation",description:"Bounded behavior implementation specialist.",instruction:"Design and implement the assigned behavior within its bounded seam, then verify the changed behavior.",permissions:{network:!0,filesystem:"workspace-write",sourceMutation:!0}},{name:"visual",description:"Rendered visual implementation and interaction specialist.",instruction:`Produce mergeable visual implementation within the Assignment, including frontend, 3D, browser-driven UI, and interactive visualization. Inspect the actual rendered and interacted-with result against acceptance criteria and references; iterate on material discrepancies in visual quality, UI, UX, accessibility, responsiveness, interaction, task adherence, and reference adherence. Use the projected skills appropriate to this visual work. Return changed paths and observable rendered/interaction evidence for independent Reviewer.visual review. ${af}`,permissions:{network:!0,filesystem:"workspace-write",sourceMutation:!0}},{name:"integration",description:"Decided seam integration specialist.",instruction:"Connect already-decided component seams, resolve interface mismatches within the assigned boundary, and verify their combined behavior.",permissions:{network:!0,filesystem:"workspace-write",sourceMutation:!0}},{name:"operations",description:"Exact-ref or SHA terminal operations observer.",instruction:`Use babysit-ci to observe the assigned CI or release gate for the Root-supplied exact ref or SHA until terminal; report the matching result and failure evidence. ${xa}`,permissions:{network:!0,filesystem:"read-only",sourceMutation:!1}},{name:"validation",description:"Independent local behavioral validation specialist.",instruction:`Independently exercise the assigned local behavior with the smallest relevant checks, classify failures, and report reproducible evidence; generated proof state is allowed, but do not repair the implementation or substitute for code review. ${xa}`,permissions:{network:!0,filesystem:"workspace-write",sourceMutation:!1}},{name:"debugging",description:"Reproducible bounded defect-repair specialist.",instruction:"Use the debugging skill to repair the assigned defect within its bounded seam.",permissions:{network:!0,filesystem:"workspace-write",sourceMutation:!0}}],capability:"task-scoped-assignment",authority:"Concrete task permissions govern observation, proof writes, or source repair within the delegated Assignment; no role-level source-mutation authority is granted. Intent lifecycle, Git/VCS writes, and material choices remain Root-only.",evidence:"Return changed files, verification results, and remaining risk.",completion:"Finish the delegated Assignment with proportional proof or an exact blocker and return a compact structured outcome.",permissions:{network:!0,filesystem:"read-only",sourceMutation:!1}},{role:"Reviewer",sharedInstruction:"Challenge the assigned target against its acceptance criteria and return reproducible evidence. Repair concrete defects to a fixed point when the concrete task permits source mutation; review-only tasks remain observational.",tasks:[{name:"code",description:"Adversarial implemented-code review specialist.",instruction:"Review and repair the implemented code to a fixed point. Batch relevant evidence, then follow up on concrete uncertainty. Check correctness, safety, compatibility, test quality, generated-artifact hygiene, and the canonical patch-quality rule.",permissions:{network:!0,filesystem:"workspace-write",sourceMutation:!0}},{name:"testing",description:"Broad test review, repair, and proof specialist.",instruction:"Review testing across the assigned scope, repair concrete test or behavior defects within the Assignment, and prove the affected behavior. Return material testing strategy or architecture decisions to Root.",permissions:{network:!0,filesystem:"workspace-write",sourceMutation:!0}},{name:"visual",description:"Independent rendered visual, UI, UX, and interaction review specialist.",instruction:`Independently inspect the implementation and actual rendered/interacted-with result against acceptance criteria and references. Review visual quality, UI, UX, accessibility, responsiveness, interactions, task adherence, and reference adherence. Do not implement repairs. Return concrete reproducible discrepancies or sufficient acceptance evidence to Root for its final independent visual pass. ${af} ${xa}`,permissions:{network:!0,filesystem:"workspace-write",sourceMutation:!1}},{name:"artifact",description:"Adversarial produced-artifact review specialist.",instruction:"Inspect the assigned produced artifact against its requested content, usability, and delivery constraints; repair concrete defects within the artifact boundary and repeat inspection until no actionable findings remain.",permissions:{network:!0,filesystem:"workspace-write",sourceMutation:!0}},{name:"audit",description:"Bounded audit and repair specialist.",instruction:"Review the assigned code for the requested concerns, repair concrete findings within the Assignment to a fixed point, and verify affected behavior.",permissions:{network:!0,filesystem:"workspace-write",sourceMutation:!0}},{name:"security",description:"Codex Security review and bounded repair specialist.",instruction:"Use the installed `codex-security:security-diff-scan` skill for an assigned change or `codex-security:security-scan` for an assigned repository scope, then follow applicable `codex-security:validation` and `codex-security:fix-finding` guidance rather than repeating their procedures. Repair validated vulnerabilities within the Assignment and verify affected behavior. Return material security risk, product, and architecture decisions to Root.",permissions:{network:!0,filesystem:"workspace-write",sourceMutation:!0}}],capability:"task-scoped-review",authority:"Concrete task permissions govern observational review or bounded repair within the delegated Assignment; no role-level source-mutation authority is granted. Intent lifecycle, Git/VCS writes, and material choices remain Root-only.",evidence:"Return findings, repaired paths, verification, and residual risk.",completion:"Reach a fixed point or report each reproducible blocker as a compact structured outcome.",permissions:{network:!0,filesystem:"read-only",sourceMutation:!1}}];ur(hi);mg=new Map(hi.map((e)=>[e.role,e])),Z_=hi.flatMap((e)=>e.tasks.map((t)=>`${e.role}:${t.name}`)),TO=Z_.map((e)=>e.replace(":",".")),gg=T(["Explorer","Librarian","Worker","Reviewer"]),X_=T(["map","lookup","trace"]),Q_=T(["lookup","research"]),ew=T(["mechanical","implementation","visual","integration","operations","validation","debugging"]),tw=T(["code","testing","visual","artifact","audit","security"]),ac=Z([b({role:T(["Explorer"]),task:X_}),b({role:T(["Librarian"]),task:Q_}),b({role:T(["Worker"]),task:ew}),b({role:T(["Reviewer"]),task:tw})]),hg=T(["Explorer:map","Explorer:lookup","Explorer:trace","Librarian:lookup","Librarian:research","Worker:mechanical","Worker:implementation","Worker:visual","Worker:integration","Worker:operations","Worker:validation","Worker:debugging","Reviewer:code","Reviewer:testing","Reviewer:visual","Reviewer:artifact","Reviewer:audit","Reviewer:security"]),yg=T(["Explorer.map","Explorer.lookup","Explorer.trace","Librarian.lookup","Librarian.research","Worker.mechanical","Worker.implementation","Worker.visual","Worker.integration","Worker.operations","Worker.validation","Worker.debugging","Reviewer.code","Reviewer.testing","Reviewer.visual","Reviewer.artifact","Reviewer.audit","Reviewer.security"]),sc=Object.freeze(Z_.map((e)=>dr(hg)(e))),Br=Object.freeze(TO.map((e)=>dr(yg)(e))),uf=Object.freeze(["worker","explorer","reviewer","librarian"]);rw=b({profile:rn,service_tier:k(yn)}),sf=Object.freeze(["user_interaction","intent","material_decisions","orchestration_lifecycle","integration_acceptance","completion","git_vcs","external_effects","visual_judgment","dev_server"]),kO=T([...sf]),RO=T(["delegated","root_direct","unavailable"]),IO=T([...sf]),bg=T(["used","no_coverage","unavailable","auth_or_quota_failure","source_conflict"]),cc=Object.freeze({rule:"Prove success with the smallest meaningful validation proportionate to changed behavior, scope, risk, uncertainty, and acceptance criteria; preserve required repository gates. Reuse already-conclusive evidence. Do not manufacture proof work, add redundant tests, or test unrelated surfaces merely to increase confidence. Broaden or repeat validation only after relevant changes, failures, elevated risk, or unresolved material concerns. Avoid tests that mirror implementation for reversible low-impact changes.",avoidImplementationMirrorTestsForLowImpactReversibleChanges:!0,broadenOrRepeatOnlyAfter:Object.freeze(["source_change","proof_failure","unresolved_material_concern","change_breadth_or_risk"]),mandatoryRepositoryGatesRemainRequired:!0,reviewerCodeRemainsRequired:!0}),PO=Object.freeze({requiredFor:Object.freeze(["library","framework","sdk","api","cli","cloud_service"]),resolveIdentityBeforeQuery:!0,queryNarrowly:!0,evidenceStates:Object.freeze(["used","no_coverage","unavailable","auth_or_quota_failure","source_conflict"]),webFallbackEvidenceStates:Object.freeze(["no_coverage","unavailable","auth_or_quota_failure"]),missingRequiredVersionAllowsFallback:!0,successfulEvidenceAloneAllowsFallback:!1,checkFirstPartyDocsBeforeFallbackForConflict:!0,unresolvedConflictAfterFirstPartyAllowsFallback:!0,materialDecisionsRemainRootOwned:!0}),Sn=Object.freeze({repositoryAndUserRequirementsPrecedePluginDefaults:!0,specialistsOwnImplementationAndInteractionProof:!0,specialistVisualImplementationInstruction:"Assign material rendered implementation to Worker.visual, independent rendered review to Reviewer.visual, then perform Root's independent visual pass. Root remains final visual authority and actively looks for issues both specialists missed. Dispatch only bounded repairs for material discrepancies, repeat only affected review and judgment, and reuse unaffected evidence.",rootOwnsVisualJudgment:!0,designJudgment:af,rootOwnsSharedDevServer:!0,rootAcceptsTerminalVisualEvidence:!0,sourceChangesInvalidateRenderEvidence:!0,specialistReportsIncludeObservableRenderedEvidence:!0,logicOnlyChangesRequireVisualAcceptance:!1,fixedPoint:Object.freeze(["worker_visual_implements_and_inspects","reviewer_visual_independently_reviews","root_independently_judges","root_assigns_bounded_visual_repair","repeat_affected_review_and_judgment"])}),OO=Object.freeze({interactiveCapabilitiesRemainSpecialistOwned:!0,rootMayInspectForVisualJudgment:!0,credentialEntryAndSubmissionRemainUserOwned:!0,specialistsMustNeverHandleCredentials:!0,missingAuthorizedPathIsCapabilityBlocker:!0}),AO=Object.freeze({threatModelForMaterialTrustBoundaryChanges:!0,securityDiffScanRequiredForSecuritySensitiveDiffs:!0,fullScanOnlyForAuditNewExposedSurfaceOrSystemicConcern:!0,validateSupportedFindingsBeforeBlocking:!0,introducedOrWorsenedValidatedVulnerabilityBlocksVcs:!0,preExistingUnrelatedFindingsDoNotExpandScope:!0,securityEditsInvalidateCodeReview:!0,securitySensitiveCodeReviewEditsInvalidateSecurityReview:!0,materialDecisionsRemainRootOwned:!0}),B=Object.freeze({requiresDelegation:!0,explicitUserDirectExecutionOverridesDelegation:!0,assignmentStartAndDispatchPrecedeDelegableExecution:!0,trivialWorkRequiresDelegation:!0,preparatoryAndExploratoryWorkRequiresDelegation:!0,genericDirectWorkFallback:!1,concreteSpecialistDispatchRequired:!0,registeredSpecialistAgentTypes:Br,roleFamiliesAreLabelsOnly:!0,forbiddenGenericAgentTypes:uf,missingConcreteRouteIsBlocker:!0,delegableActions:Object.freeze(["repository_discovery","file_source_test_doc_inspection","fact_finding","research","implementation","debugging","testing","validation","frontend_work","security_work","browser_use","computer_use","review","ci_release_observation"]),directExecutionExceptions:sf,rootOwnedAuthority:sf,requestUserInputGates:Object.freeze(["missing_authorization_for_consequential_effect","ambiguity_or_missing_material_input"]),surgicalMutationRule:lf,phaseOrder:Y_,phaseGates:Object.freeze({implementedScopeStableBeforeReview:!0,reviewerCodeAndWorkerValidationMayOverlapOnNonConflictingScopes:!0,currentValidationBeforeRootIntegration:!0,rootIntegrationBeforeVcs:!0}),initialDispatch:Object.freeze({independentAssignments:!0,substantiveIndependentConcurrency:!0,routinePostdispatchSteering:!1,collectiveWaits:!0,evidenceReusedAcrossPhases:!0}),atomicLifecycleTransitions:Object.freeze({relatedAssignmentAndIntentWrites:!0,oneLockOneCommit:!0,staleRevisionChecksRetained:!0,repositoryDriftChecksRetained:!0}),supersession:Object.freeze({explicitOnly:!0,unfinishedPredecessorOnly:!0,validatedRelatedReplacement:!0,reasonAndProvenanceRequired:!0,supersededExcludedFromCompletionBlockers:!0}),specialistTerminalResultPersistence:Object.freeze({ownActiveInvocationCapabilityRequired:!0,ownAssignmentOnly:!0,terminalOutcomeOnly:!0,rootOwnedIntentLifecycle:!0,rootOwnedAcceptanceReviewAndCiGates:!0,rootOwnedVcsAndExternalEffects:!0,sharedRuntimeCallerIdentityUnavailable:!0,legacyResultCompatibilityPreserved:!0}),normalSpawnForkTurns:"none",normalSpawnRequiresExplicitForkTurns:!0,normalSpawnUsesConcreteRegisteredAgentType:!0,semanticStateBoundary:"Use holycodex-agent semantic operations for Intent and Assignment state. Do not edit TOON state. Resume the current Intent or create one for new work; record verification, acceptance, and readiness, and complete only when holycodex-agent confirms every completion predicate. There is no HolyCodex planning workflow or automatic Plan approval gate; preserve existing Plan state when resuming work that uses it.",routeConfigurationBeforeDispatch:"Use the active profile's registered Role.task configuration, including model, effort, tier, permissions, shell, and capabilities. Verify the registration once per configuration generation; recheck after configuration changes or when resuming an unverified thread. Pass fields required by the dispatch tool; registered settings need not be copied into Assignment prose. Never inherit Root settings, substitute a generic route, or override the selected route. Report a missing or incompatible route before dispatch.",assignmentInvocationLifecycle:"Before each specialist spawn, persist the bounded Assignment and call holycodex-agent assignment start. Keep the returned active_invocation_id and capability in Root; give the specialist only the bounded Assignment, never the capability. After a terminal report, record the result with that invocation ID and capability. Recover an interrupted invocation only after confirming it stopped, using the matching Root-held capability; never share that capability.",assignmentContextIsTaskSpecificOnly:!0,configuredRouteModelAndEffortPreserved:!0,normalProgressMessages:!1,normalHeartbeatMessages:!1,normalIntermediateEvidence:!1,userUpdatesUsefulOrImportantOnly:!0,routinePerToolOrSubagentNarrationForbidden:!0,routineStatusOnlyChatterForbidden:!0,fixedCadenceUserUpdatesForbidden:!0,materialUserUpdateKinds:Object.freeze(["significant_findings_or_decisions","consequential_blockers_or_input_needs","release_milestones"]),outOfBoundaryRequiresNewAssignment:!0,rootWaitTool:"collaboration.wait_agent",rootWaitTimeoutMs:600000,specialistCoordinationInstruction:"Coordinate through terminal reports, not conversation. After dispatch, do not inspect a running specialist. Do not message, poll, request status from, or follow up with a running specialist. The only exception is a genuine lifecycle interruption or supersession caused by materially changed user intent, cancellation, or Assignment invalidation that makes continuation incorrect; use the lifecycle mechanism without normal steering. Do not use Root sleep for specialist coordination or create polling/status loops. Wait with the exact required timeout and let specialist completion wake the collective wait. Dispatch already-known independent Assignments before waiting. After a specialist reports, judge its evidence; when compatible follow-up work remains, prefer the same warm specialist if its concrete task fits, its context is useful, independent review and parallelism remain sound, and write ownership does not conflict. Reuse relevant warm context rather than discarding it without reason. Minimize Root model turns: return to judgment for decisions, orchestration boundaries, integration, contradictions, and completion, not for polling, heartbeat traffic, or incremental steering.",rootWaitRequiresExactTimeout:!0,earlySpecialistCompletionWakesWait:!0,collectiveMailboxIncludesRelevantAgents:!0,idleRootWaitRepeatsRequiredTimeout:!0,shortRootWaitsForbidden:!0,busyPollingForbidden:!0,statusOnlyCoordinationLoopsForbidden:!0,batchIndependentLifecycleActions:!0,releaseLeavesAfterAcceptedOutcome:!0,specialistOutcomes:Object.freeze(["completed","blocked","needs_root_input","failed"]),evidenceFirstConciseStructuredReports:!0,specialistReportFields:Object.freeze(["changed paths","checks","observable evidence","blockers","Root decisions needed","remaining risk"]),rootLargeReadsOnlyFor:Object.freeze(["material decisions","conflicts","failures","findings"]),stableFactsReused:!0,reportDrivenSpecialistCoordination:!0,runningSpecialistMessagesForbidden:!0,runningSpecialistInspectionForbidden:!0,runningSpecialistFollowupForbidden:!0,followupRequiresTerminalReport:!0,rootSleepForSpecialistCoordinationForbidden:!0,pollingAndStatusLoopsForbidden:!0,warmSpecialistReusePreferred:!0,warmReuseRequiresContextAndOwnershipFit:!0,independentAssignmentsDispatchedBeforeWait:!0,rootDecisionBoundariesMinimized:!0,duplicatePolicyForbidden:!0,stableBoundedComponentScopesAreCanonical:!0,lifecycleWorkerOwnsDeterministicApi:!0,materialDecisionsRemainRootOwned:!0,lifecycleRemainsRootOwned:!0,integrationAndCompletionRemainRootOwned:!0,routineSafeReversibleInScopeDecisionsProceedAutonomously:!0,userInstructionsOverrideSkillGuidelinesExceptHardInvariants:!0,authorizedWorkContinuesThroughRequestedTerminalState:!0,testingPolicy:cc,codeReviewRequiredForImplementation:!0,codeReviewRequiredBeforeVcs:!0,externalVerificationMustBeTerminal:!0,postVcsFlow:"discover_topology_observe_repair_repeat"})});function df(e){let t=hn(dw,e);if(Me(t))return eo(Ns("CLI envelope",t.failure));return na(t.success)}var iw,ow,aw,MO,NO,wg="holycodex-specialist-outcome-2",Ct,Ea,uc,DO,FO,LO,UO,$O,jO,ff,BO,VO,qO,zO,JO,sw,cw,lw,WO,uw,fw,dw;var Cg=L(()=>{bt();Fe();ug();ra();of();lc();ma();iw=T(["blocked","completed","failed","partial"]),ow=Z([T(["high","max","xhigh"]),ot]),aw=nn,MO=mi,NO=b({blocked:W,changed_files:j(w),confidence:xt,context_owner:Z([w,ot]),material_findings:j(w),needs_more_context:W,needs_root_decision:W,needs_verification:W,relevant_files:j(w),remaining_risk:j(w),reuse_recommended:W,status:iw,suggested_followup:Z([w,ot]),suggested_luna_effort:ow,suggested_specialist:Z([gg,ot]),verification:j(w),verification_passed:W}),Ct=w.check(at(1)),Ea=b({state:bg,evidence:j(Ct).check(at(1)),library:k(Ct),version:k(Ct)}),uc={protocol_version:T([wg]),route:ac,evidence:j(Ct),context7:k(Ea)},DO=b(uc),FO=b({...uc,status:T(["completed"]),summary:Ct}),LO=b({...uc,status:T(["blocked"]),reason:Ct,needs_root_decision:W}),UO=b({...uc,status:T(["partial"]),summary:Ct,completed:j(Ct),remaining:j(Ct),needs_root_decision:W}),$O=b({...uc,status:T(["failed"]),error:Ct}),jO=Z([FO,LO,UO,$O]),ff={protocol_version:T([wg]),capability:oc,route:Z([ac,ot]),evidence:j(Ct),context7:k(Ea),data:aw},BO=b({...ff,status:T(["completed"]),summary:Ct}),VO=b({...ff,status:T(["blocked"]),reason:Ct,needs_root_decision:W}),qO=b({...ff,status:T(["partial"]),summary:Ct,completed:j(Ct),remaining:j(Ct),needs_root_decision:W}),zO=b({...ff,status:T(["failed"]),error:Ct}),JO=Z([BO,VO,qO,zO]),sw=j(w),cw=w.check(ue(/^[a-z][a-z0-9-]*(?: [a-z][a-z0-9-]*)*$/u)),lw=T([Lr]),WO=b({code:Jn,message:w,details:MO}),uw=b({schema_version:lw,ok:T([!0]),command:cw,data:aw,warnings:sw}),fw=b({schema_version:lw,ok:T([!1]),command:cw,error:WO,warnings:sw}),dw=Z([uw,fw])});function HO(e,t,n){return{key:`${e}:${t}`,role:e,task:t,model:fc,effort:n}}function YO(e){let t=GO.get(e);if(t===void 0)throw new it("catalog_invalid","A profile has no route effort policy.",{profile:e});return hi.flatMap((n)=>n.tasks.map((r)=>{let i=`${n.role}:${r.name}`,o=t.efforts[i];if(o===void 0)throw new it("catalog_invalid","A route effort policy is incomplete.",{profile:e,route:i});return HO(n.role,r.name,o)}))}function Tg(e){return{name:e.name,root:{model:e.rootModel,effort:e.rootEffort},specialistModel:fc,defaultServiceTier:"standard",routes:YO(e.name)}}function ZO(e){let t=["low","default","high"];if(e.length!==t.length)throw new it("catalog_invalid","The profile 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 it("catalog_invalid","The profile catalog order is invalid.",{index:n});let o=pf,a=i==="low"?"low":"medium";if(r.root.model!==o||r.root.effort!==a||r.specialistModel!==fc)throw new it("catalog_invalid","A profile has an invalid model route.",{profile:r.name});if(r.routes.length!==sc.length)throw new it("catalog_invalid","A profile is incomplete.",{profile:r.name});let s=new Set;for(let c of r.routes){if(s.has(c.key)||!KO.has(c.key)||c.model!==fc||`${c.role}:${c.task}`!==c.key)throw new it("catalog_invalid","A profile contains an invalid route.",{profile:r.name});s.add(c.key)}if(s.size!==sc.length)throw new it("catalog_invalid","A profile is missing a specialist route.",{profile:r.name})}}function va(e){let t=hn(rn,e);if(Me(t))return eo(new it("invalid_profile","Unknown profile selection.",{field:"profile"},{cause:t.failure}));let n=mw.get(t.success);if(!n)return eo(new it("invalid_profile","Unknown profile selection.",{profile:t.success}));return na(n)}var pf="gpt-6.1-sol",fc="gpt-6-luna",KO,kg,GO,Rg,pw,mw,XO;var gw=L(()=>{bt();ra();lc();ma();KO=new Set(sc),kg=[{profile:"low",rationale:"Cheapest practical configuration without dropping Luna below its useful agentic threshold.",efforts:{"Explorer:map":"medium","Explorer:lookup":"medium","Explorer:trace":"high","Librarian:lookup":"medium","Librarian:research":"high","Worker:mechanical":"medium","Worker:implementation":"high","Worker:integration":"high","Worker:operations":"medium","Worker:validation":"medium","Worker:debugging":"high","Worker:visual":"high","Reviewer:code":"high","Reviewer:testing":"medium","Reviewer:audit":"medium","Reviewer:security":"high","Reviewer:artifact":"high","Reviewer:visual":"high"}},{profile:"default",rationale:"Best general whole-task cost/performance: Sol medium orchestration and Luna medium/high execution.",efforts:{"Explorer:map":"medium","Explorer:lookup":"medium","Explorer:trace":"high","Librarian:lookup":"medium","Librarian:research":"high","Worker:mechanical":"medium","Worker:implementation":"high","Worker:integration":"high","Worker:operations":"medium","Worker:validation":"high","Worker:debugging":"high","Worker:visual":"high","Reviewer:code":"high","Reviewer:testing":"high","Reviewer:audit":"high","Reviewer:security":"high","Reviewer:artifact":"high","Reviewer:visual":"high"}},{profile:"high",rationale:"Highest practical reliability without indiscriminate reasoning waste; use high effort consistently across all live routes.",efforts:{"Explorer:map":"high","Explorer:lookup":"medium","Explorer:trace":"high","Librarian:lookup":"high","Librarian:research":"high","Worker:mechanical":"high","Worker:implementation":"high","Worker:integration":"high","Worker:operations":"high","Worker:validation":"high","Worker:debugging":"high","Worker:visual":"high","Reviewer:code":"high","Reviewer:testing":"high","Reviewer:audit":"high","Reviewer:security":"high","Reviewer:artifact":"high","Reviewer:visual":"high"}}];ur(kg);GO=new Map(kg.map((e)=>[e.profile,e]));Rg=[Tg({name:"low",rootModel:pf,rootEffort:"low"}),Tg({name:"default",rootModel:pf,rootEffort:"medium"}),Tg({name:"high",rootModel:pf,rootEffort:"medium"})];ZO(Rg);ur(Rg);pw=Rg,mw=new Map,XO=new Map;for(let e of pw){mw.set(e.name,e);let t=new Map;for(let n of e.routes)t.set(n.key,n);XO.set(e.name,t)}});function eA(e,t){return new it("invalid_canonical_value",`Cannot canonicalize ${e}: ${t}.`,{path:e,reason:t})}function Ig(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;let n=new Set(t);if(n.add(e),Array.isArray(e)){if(Object.getOwnPropertySymbols(e).length>0)return!1;for(let r=0;r<e.length;r+=1){let i=Object.getOwnPropertyDescriptor(e,String(r));if(!i||!i.enumerable||!("value"in i)||!Ig(i.value,n))return!1}return Object.getOwnPropertyNames(e).every((r)=>{if(r==="length")return!0;let i=Number(r),o=Object.getOwnPropertyDescriptor(e,r);return Number.isInteger(i)&&i>=0&&i<e.length&&String(i)===r&&o!==void 0&&o.enumerable&&"value"in o})}if(Object.getPrototypeOf(e)!==Object.prototype&&Object.getPrototypeOf(e)!==null||Object.getOwnPropertySymbols(e).length>0)return!1;return Object.getOwnPropertyNames(e).every((r)=>{let i=Object.getOwnPropertyDescriptor(e,r);return i!==void 0&&i.enumerable&&"value"in i&&Ig(i.value,n)})}function Pg(e){if(e===null)return"null";switch(typeof e){case"string":return JSON.stringify(e);case"boolean":return e?"true":"false";case"number":return JSON.stringify(e);case"object":break}if(Array.isArray(e))return`[${e.map(Pg).join(",")}]`;let t=e;return`{${Object.keys(t).sort().map((r)=>`${JSON.stringify(r)}:${Pg(t[r])}`).join(",")}}`}function Vr(e){let t=Pe(tA)(e);if(Me(t))throw eA("$",`invalid JSON value: ${String(t.failure)}`);return Pg(t.success)}function xn(e){return new TextEncoder().encode(Vr(e))}function hw(e,t){let n=Pe(nA)(e);if(Me(n))throw new it("invalid_digest_domain","Digest domains must be non-empty and NUL-free.",{field:"domain"});let r=new TextEncoder().encode("holycodex-sha256\x00"),i=new TextEncoder().encode(n.success),o=r.byteLength+8+i.byteLength;for(let f of t){if(f.byteLength>4294967295||o>4294967291-f.byteLength)throw new it("invalid_digest_domain","Digest input is too large.");o+=4+f.byteLength}let a=new Uint8Array(o),s=new DataView(a.buffer);a.set(r,0);let c=r.byteLength;s.setUint32(c,i.byteLength,!1),c+=4,a.set(i,c),c+=i.byteLength,s.setUint32(c,t.length,!1),c+=4;for(let f of t)s.setUint32(c,f.byteLength,!1),c+=4,a.set(f,c),c+=f.byteLength;return a}function rA(e){let t="";for(let n of e)t+=n.toString(16).padStart(2,"0");return t}function En(e,t){let n=globalThis.crypto?.subtle;if(!n)throw new it("crypto_unavailable","The standards-based crypto API is unavailable.");return A(de(d(()=>n.digest("SHA-256",iA(hw(e,t)).buffer)),(r)=>rA(new Uint8Array(r))))}function iA(e){let t=new Uint8Array(e.byteLength);return t.set(e),t}var tA,nA;var yw=L(()=>{De();bt();Fe();ra();of();tA=nn.check(ee((e)=>Ig(e))),nA=w.check(at(1),ue(/^[^\0]+$/u))});import{execFile as aA}from"child_process";import{promisify as sA}from"util";var xw="holycodex-intent-1",Ew="holycodex-plan-1",vw="holycodex-assignment-1",mf="toon-4",X,Hn,gf,bw,ba,On,Ze,b2,Og,so,Ag,Mg,cA,Sw,lA,uA,Ng,_w,ww,_a,Dg,fA,dA,_2,pA="holycodex-work-state-transaction-1",w2,C2,mA,gA,hA,yA,SA,xA,EA,vA,T2,bA,k2;var Cw=L(()=>{Fe();Cg();lc();ma();X=w.check(ee((e)=>e.trim().length>0)),Hn=w.check(ue(/^[a-z0-9][a-z0-9-]{0,95}$/u)),gf=w.check(ue(/^[a-f0-9]{64}$/u)),bw=w.check(ue(/^[a-f0-9]{40}$/u)),ba=ef.check(Xu(1)),On=w.check(ee((e)=>!Number.isNaN(Date.parse(e)))),Ze=j(X),b2=b({pid:ef.check(nc(0)),token:X}),Og=b({role:T(["Explorer","Librarian","Worker","Reviewer"]),task:X}).check(ee((e)=>hi.some((t)=>t.role===e.role&&t.tasks.some((n)=>n.name===e.task)))),so=b({kind:T(["changed_path","check","repository_fact","ci","behavior","uncertainty"]),value:X,result:k(T(["passed","failed","observed","unknown"]))}),Ag=b({root:X,git_common_dir:X,initial_head:X,expected_head:X,expected_changes:Ze,expected_status_digest:gf,integrated_commit:k(bw),updated_at:On}),Mg=T(["scoping","ready","executing","verifying","reviewing","blocked","needs_root_input","complete","abandoned"]),cA=T(["scoping","ready","executing","verifying","reviewing"]),Sw=b({required:W,status:T(["not_required","missing","passed","failed","accepted","rejected"]),evidence:j(so)}),lA=b({schema_version:T([xw]),toon_compatibility:T([mf]),id:Hn,slug:Hn,title:X,goal:X,acceptance_criteria:Ze,state:Mg,revision:ba,plan_required:W,active_plan_revision:k(ba),active_plan_digest:k(gf),blockers:Ze,resume_state:k(cA),verification:Sw,review:Sw,acceptance_met:W,root_readiness:W,evidence:j(so),baseline:Ag,created_at:On,updated_at:On}),uA=b({schema_version:T([Ew]),toon_compatibility:T([mf]),intent_id:Hn,revision:ba,predecessor_digest:k(gf),approach:X,scope:Ze,exclusions:Ze,assignments:Ze,dependencies:Ze,architecture:Ze,risks:Ze,assumptions:Ze,open_questions:Ze,verification:Ze,recovery:Ze,updated_at:On}),Ng=T(["completed","blocked","needs_root_input","failed"]),_w=T(["pending","executing","completed","blocked","needs_root_input","failed","superseded"]),ww=b({id:Hn,outcome:Ng,started_at:On,finished_at:On,summary:X,evidence:j(so),context7:k(Ea),blocker:k(X),remaining_risk:Ze}),_a=gf,Dg={schema_version:T([vw]),toon_compatibility:T([mf]),intent_id:Hn,id:Hn,objective:X,owner:Z([Og,b({role:T(["Reviewer"]),task:T(["plan"])})]),scope:Ze,constraints:Ze,exclusions:Ze,dependencies:Ze,acceptance_criteria:Ze,status:_w,revision:ba,invocations:j(ww),active_invocation_id:k(X),active_started_at:k(On),supersedes:k(Hn),superseded_by:k(Hn),supersession_reason:k(X),supersession_provenance:k(X),evidence:j(so),blocker:k(X),remaining_risk:Ze,created_at:On,updated_at:On},fA=b(Dg),dA=b({...Dg,capability:_a}),_2=b({...Dg,active_invocation_capability_verifier:k(_a),active_invocation_capability:k(_a)}),w2=b({schema_version:T([pA]),state:T(["prepared","committed"]),files:j(b({path:X,previous:w,next:w})).check(at(1))}),C2=b({schema_version:T(["holycodex-intent-0"]),id:Hn,slug:Hn,title:X,goal:X,acceptance_criteria:Ze,state:Mg,revision:ba,baseline:Ag,created_at:On,updated_at:On}),mA=b({title:X,goal:X,acceptanceCriteria:j(X).check(at(1)),planRequired:k(W),verificationRequired:k(W),reviewRequired:k(W)}),gA=b({approach:X,scope:k(j(X)),exclusions:k(j(X)),assignments:k(j(X)),dependencies:k(j(X)),architecture:k(j(X)),risks:k(j(X)),assumptions:k(j(X)),openQuestions:k(j(X)),verification:k(j(X)),recovery:k(j(X))}),hA=b({id:k(X),objective:X,owner:Og,scope:j(X).check(at(1)),constraints:k(j(X)),exclusions:k(j(X)),dependencies:k(j(X)),acceptanceCriteria:j(X).check(at(1))}),yA=b({scope:j(X).check(at(1))}),SA=b({scope:k(j(X).check(at(1)))}),xA=b({replacementId:Hn,replacementRevision:k(ba),reason:X,provenance:X}),EA=b({commit:bw}),vA=b({invocationId:k(X),capability:k(_a),outcome:Ng,startedAt:k(X),summary:X,scope:k(j(X).check(at(1))),evidence:k(j(so)),context7:k(Ea),blocker:k(X),remainingRisk:k(j(X))}),T2=b({invocationId:X,startedAt:On,capability:_a,interruptionReason:X}),bA=b({evidence:k(j(so)),verification:k(T(["passed","failed"])),review:k(T(["accepted","rejected"])),acceptanceMet:k(W),rootReadiness:k(W),clearBlockers:k(W)}),k2=sA(aA)});var st=L(()=>{nb();ra();ma();F_();ug();K_();of();lc();Cg();gw();yw();Cw()});function pc(e){if(typeof e!=="object"||e===null||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function CA(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 kw(e){return{ok:!1,error:e}}function Rw(e){return{ok:!0,value:e}}function Kn(e,t=512){let n="";for(let r of e){let i=r.codePointAt(0)??0;n+=i<=8||i===11||i===12||i>=14&&i<=31||i===127?" ":r}return n.replace(/\s+/gu," ").trim().slice(0,t)}function co(e,t=0){if(t>3)return"[truncated]";if(e===null||typeof e==="boolean")return e;if(typeof e==="string")return Kn(e,256);if(typeof e==="number")return Number.isFinite(e)?e:null;if(Array.isArray(e))return e.slice(0,32).map((n)=>co(n,t+1));if(pc(e)){let n={};for(let[r,i]of Object.entries(e).slice(0,32)){let o=Kn(r,96);if(o.length>0)n[o]=co(i,t+1)}return n}return"[redacted]"}function Iw(e){let t=co(e);return pc(t)?t:{value:t}}function je(e,t,n){return new G("invalid_external_data",`Invalid ${e}.`,{field:e,received:co(t)},n===void 0?void 0:{cause:n})}function Nt(e,t,n){let r=hn(e,t);if(Me(r))throw je(n,t,String(r.failure));return r.success}function mc(e,t){return Ve(hn(e,t))}var Fg,dc=1048576,Lg=65536,Et,He,xz,qr,wA,G;var mr=L(()=>{st();bt();Fe();Fg=Lr;Et=nn,He=mi,xz=w.check(ue(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u)),qr=w.check(ee((e)=>e.length>0&&e.length<=4096)),wA=xt.check(ee((e)=>Number.isFinite(e)&&e>=0));G=class G extends Error{code;kind;details;retryable;constructor(e,t,n={},r){super(t,r?.cause===void 0?void 0:{cause:r.cause});this.name="CodexError",this.code=e,this.kind=CA(e),this.details=n,this.retryable=r?.retryable??!1,Object.freeze(this.details),Object.freeze(this)}}});var Ug,gc,hc,$g,jg,Bg,Vg="turn/completed";var hf=L(()=>{Ug=["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"],gc=["item/commandExecution/requestApproval","item/fileChange/requestApproval","applyPatchApproval","execCommandApproval"],hc=["item/permissions/requestApproval"],$g=["mcpServer/elicitation/request"],jg=["item/tool/call"],Bg={method:"initialized"}});class Sf{transport;maxLineBytes;requestTimeoutMs;signal;notificationListeners=new Set;serverRequestHandlers=new Set;pending=new Map;serverRequestWork=new Set;serverRequestTasks=new Set;nextRequestId=1;readerFiber;initializeEffect;transportCloseEffect;initializeAttempted=!1;initialized=!1;closed=!1;constructor(e,t={}){if(this.transport=e,this.maxLineBytes=t.maxLineBytes??dc,this.requestTimeoutMs=t.requestTimeoutMs,this.signal=t.signal,!Number.isSafeInteger(this.maxLineBytes)||this.maxLineBytes<1)throw new G("invalid_external_data","The maximum line size is invalid.");if(this.requestTimeoutMs!==void 0&&(!Number.isSafeInteger(this.requestTimeoutMs)||this.requestTimeoutMs<1))throw new G("invalid_external_data","The request timeout is invalid.");if(t.onNotification)this.notificationListeners.add(t.onNotification);if(t.onServerRequest)this.serverRequestHandlers.add(t.onServerRequest);if(this.signal?.aborted)this.close();else if(this.signal)this.signal.addEventListener("abort",()=>void this.close(),{once:!0})}get isInitialized(){return this.initialized}onNotification(e){return this.notificationListeners.add(e),()=>this.notificationListeners.delete(e)}onServerRequest(e){return this.serverRequestHandlers.add(e),()=>this.serverRequestHandlers.delete(e)}initialize(e=TA){if(this.initializeEffect)return A(this.initializeEffect);if(this.initializeAttempted)return A(p(new G("invalid_external_data","The App Server initialize handshake was already attempted.")));let t=V({try:()=>{this.ensureOpen();let n=Nt(xc,e,"initialize parameters");return this.initializeAttempted=!0,this.performInitializeEffect(n)},catch:(n)=>zr(n,"The initialize handshake failed.")}).pipe(yu);return this.initializeEffect=Oe(Ms(t)),A(this.initializeEffect)}startThread(e={}){return this.action("thread/start",Qg,e,Ec)}resumeThread(e){let t=typeof e==="string"?{threadId:e}:e;return this.action("thread/resume",vc,t,Hg)}readThread(e){let t=typeof e==="string"?{threadId:e}:e;return this.action("thread/read",eh,t,Zg)}listThreads(e={}){return this.action("thread/list",nh,e,Xg)}forkThread(e){let t=typeof e==="string"?{threadId:e}:e;return this.action("thread/fork",th,t,Kg)}unsubscribeThread(e){let t=typeof e==="string"?{threadId:e}:e;return this.action("thread/unsubscribe",Gg,t,Yg)}startTurn(e){return this.action("turn/start",rh,e,oh)}steerTurn(e){return this.action("turn/steer",ih,e,ah)}interruptTurn(e,t){let n=typeof e==="string"?{threadId:e,turnId:t??""}:e;return this.action("turn/interrupt",sh,n,ch)}listModels(e={}){return this.action("model/list",uh,e,fh)}readModelProviderCapabilities(e={}){return this.action("modelProvider/capabilities/read",dh,e,ph)}readConfig(e={}){return this.action("config/read",mh,e,gh)}listPermissionProfiles(e={}){return this.action("permissionProfile/list",hh,e,yh)}call(e,t={}){return A(V({try:()=>this.callEffect(e,t),catch:(n)=>zr(n,"The App Server method failed.")}).pipe(yu))}callEffect(e,t){if(e==="initialize")return de(d({try:()=>this.initialize(Nt(xc,t,"initialize parameters")),catch:(r)=>zr(r,"The initialize handshake failed.")}),(r)=>Nt(Et,r,"initialize result"));let n=Nt(Sc,{id:1,method:e,params:t},"App Server method");if(!kA.has(n.method))throw new G("method_unsupported",`Unsupported App Server method: ${e}.`,{method:e});return this.requestEffect(n.method,n.params===void 0?{}:n.params)}close(){return A(this.closeWithErrorEffect(new G("closed","The App Server client is closed.")))}performInitializeEffect(e){let t=v({self:this},function*(){let n=yield*this.decodeEffect(xc,e,"initialize parameters"),r=yield*this.decodeEffect(Et,n,"initialize parameters"),i=yield*this.requestEffect("initialize",r),o=yield*this.decodeEffect(Jg,i,"initialize result"),a=yield*this.decodeEffect(Wg,Bg,"initialized notification");return yield*this.transportWriteEffect(JSON.stringify(a)),this.initialized=!0,o});return me(t,()=>!0,(n)=>v({self:this},function*(){let r=zr(n,"The initialize handshake failed.");return yield*this.closeWithErrorEffect(r),yield*p(r)}))}action(e,t,n,r){return A(V({try:()=>this.actionEffect(e,t,n,r),catch:(i)=>zr(i,`The ${e} action failed.`)}).pipe(yu))}actionEffect(e,t,n,r){return v({self:this},function*(){let i=yield*this.decodeEffect(t,n,`${e} parameters`),o=yield*this.decodeEffect(Et,i,`${e} parameters`),a=yield*this.requestEffect(e,o);return yield*this.decodeEffect(r,a,`${e} result`)})}decodeEffect(e,t,n){return V({try:()=>Nt(e,t,n),catch:(r)=>zr(r,`Invalid ${n}.`)})}requestEffect(e,t){if(this.closed)return p(new G("closed","The App Server client is closed."));if(e!=="initialize"&&!this.initialized)return p(new G("invalid_external_data",`The ${e} action requires an initialized App Server client.`));this.startReader();let n=this.nextRequestId;return this.nextRequestId+=1,Re(this.decodeEffect(Sc,{id:n,method:e,params:t},`${e} request`),(r)=>ci((i,o)=>{let a=!1,s,c,f=()=>l(new G("cancellation",`The ${e} request was cancelled.`,{method:e})),l=(h)=>{if(a)return;if(a=!0,this.pending.delete(n),s!==void 0)clearTimeout(s);c?.(),i(p(h))};if(this.requestTimeoutMs!==void 0)s=setTimeout(()=>l(new G("timeout",`The ${e} request timed out.`,{method:e})),this.requestTimeoutMs);if(this.signal){if(this.signal.addEventListener("abort",f,{once:!0}),c=()=>this.signal?.removeEventListener("abort",f),this.signal.aborted)f()}let u={method:e,resume:i,...s===void 0?{}:{timer:s},...c===void 0?{}:{removeAbortListener:c}};this.pending.set(n,u),o.addEventListener("abort",f,{once:!0});let g=this.transportWriteEffect(JSON.stringify(r)).pipe(me(()=>!0,(h)=>nt(()=>l(h))));return ta(g),nt(()=>{if(s!==void 0)clearTimeout(s);c?.(),o.removeEventListener("abort",f),this.pending.delete(n)})}))}transportWriteEffect(e){return d({try:()=>this.transport.writeLine(e),catch:(t)=>zr(t,"The App Server request could not be written.")})}startReader(){if(!this.readerFiber){let e=this.readLoopEffect().pipe(me(()=>!0,(t)=>this.handleReaderFailureEffect(t)));this.readerFiber=ta(e)}}readLoopEffect(){return v({self:this},function*(){while(!this.closed){let e=yield*d({try:()=>this.transport.readLine(),catch:(t)=>zr(t,"The App Server stdout could not be read.")});if(e===null){if(!this.closed)return yield*p(new G("transport_closed","The App Server transport closed."));return}if(new TextEncoder().encode(e).byteLength>this.maxLineBytes)return yield*p(new G("invalid_transport_line","An App Server line exceeded the limit."));yield*V({try:()=>this.handleLine(e),catch:(t)=>zr(t,"The App Server emitted an invalid message.")})}})}handleReaderFailureEffect(e){let t=e instanceof G?e:new G("transport_failure","The App Server transport failed.",{},{cause:e});return this.closeWithErrorEffect(t)}handleLine(e){let t=Oe(V({try:()=>JSON.parse(e),catch:(o)=>new G("invalid_transport_line","The App Server emitted invalid JSON.",{},{cause:o})})),n=this.tryDecode(yc,t);if(n!==void 0){this.handleResponse(n);return}let r=this.tryDecode(Sc,t);if(r!==void 0){this.handleServerRequest(r);return}let i=this.tryDecode(zg,t);if(i!==void 0){this.handleNotification(i);return}throw je("JSON-RPC message",t)}tryDecode(e,t){return mc(e,t)?Nt(e,t,"JSON-RPC message"):void 0}handleResponse(e){let t=this.pending.get(e.id);if(!t)throw new G("unexpected_response","The App Server returned an unknown request id.",{id:e.id});if(this.pending.delete(e.id),"error"in e){let n=e.error.code===-32001,r=IA(t.method);this.resumePending(t,p(new G(r,`The App Server rejected ${t.method}: ${Kn(e.error.message)}.`,{method:t.method,serverCode:e.error.code,retryable:n,...e.error.data===void 0?{}:{data:co(e.error.data)}},{retryable:n})));return}this.resumePending(t,M(e.result))}resumePending(e,t){if(e.timer!==void 0)clearTimeout(e.timer);e.removeAbortListener?.(),e.resume(t)}handleServerRequest(e){let t=e.params??{},n=Nt(Sh,{...e,params:t,category:Pw(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.writeServerErrorEffect(e.id,-32601,`No handler for ${e.method}.`));return}let i=r[0];if(i===void 0){this.trackServerRequestTask(this.writeServerErrorEffect(e.id,-32601,`No handler for ${e.method}.`));return}let o={active:!0};this.serverRequestWork.add(o);let a=Qv({onFailure:(s)=>this.writeServerErrorEffect(e.id,-32000,Kn(String(s))),onSuccess:(s)=>this.writeValidatedServerResultEffect(e.id,s)})(d({try:()=>Promise.resolve(i(n)),catch:(s)=>s}));this.completeServerRequest(o,a)}writeValidatedServerResultEffect(e,t){return mc(yf,t)?this.writeServerResultEffect(e,Nt(yf,t,"server response")):this.writeServerErrorEffect(e,-32000,"Invalid server response.")}completeServerRequest(e,t){if(!e.active)return;e.active=!1,this.serverRequestWork.delete(e),this.trackServerRequestTask(t)}trackServerRequestTask(e){let t=Je(e);this.serverRequestTasks.add(t),ta(Xi(t,nt(()=>this.serverRequestTasks.delete(t))))}writeServerResultEffect(e,t){return Re(this.decodeEffect(yc,{id:e,result:t},"server response"),(n)=>this.transportWriteEffect(JSON.stringify(n)))}writeServerErrorEffect(e,t,n){return Re(this.decodeEffect(yc,{id:e,error:{code:t,message:RA(n)}},"server error response"),(r)=>this.transportWriteEffect(JSON.stringify(r)))}handleNotification(e){let t=e.params;if(e.method===Vg){let n=Nt(lh,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:Iw({params:co(t)})})}emitNotification(e){for(let t of this.notificationListeners)Oe(Je(V({try:()=>t(e),catch:()=>{return}})))}rejectPending(e){for(let t of this.pending.values())this.resumePending(t,p(e));this.pending.clear()}closeWithErrorEffect(e){if(this.transportCloseEffect===void 0){this.closed=!0,this.rejectPending(e);for(let t of this.serverRequestWork)t.active=!1;this.serverRequestWork.clear(),this.serverRequestTasks.clear(),this.transportCloseEffect=Oe(Ms(Je(d({try:()=>this.transport.close(),catch:()=>{return}}))))}return this.transportCloseEffect}ensureOpen(){if(this.closed)throw new G("closed","The App Server client is closed.")}}function RA(e){let t=Kn(e);return t.length>0?t:"server request failed"}function zr(e,t){return e instanceof G?e:new G("transport_failure",t,{},{cause:e})}function IA(e){if(hc.some((t)=>t===e))return"permission_denied";if(gc.some((t)=>t===e))return"approval_required";if(e==="turn/interrupt")return"cancellation";if(e.startsWith("turn/"))return"turn_failed";return"server_error"}var TA,kA;var qg=L(()=>{De();mr();hf();xh();TA={clientInfo:{name:"holycodex",title:null,version:Fg},capabilities:null},kA=new Set(Ug)});var Ow;var Aw=L(()=>{Mr();Ow=LE});import{isAbsolute as OA}from"path";function yi(e=process.env){let t=["PATH","HOME","USER","CODEX_HOME","TMPDIR","TEMP","TMP","LANG","LC_ALL"],n={};for(let r of t){let i=e[r];if(i!==void 0&&i.length>0)n[r]=i}return n}function Eh(e=process.env){return Object.freeze(yi(e))}function vh(e,t){return A(Nw(e,t))}function Nw(e,t){return v(function*(){let n=yield*V({try:()=>e.getReader(),catch:(a)=>new G("transport_failure","A subprocess stream could not be read.",{},{cause:a})}),r=[],i=0,o=v(function*(){while(!0){let c=yield*d({try:()=>n.read(),catch:(f)=>new G("transport_failure","A subprocess stream could not be read.",{},{cause:f})});if(c.done)break;if(i+=c.value.byteLength,i>t)return yield*p(new G("invalid_transport_line","A subprocess stream exceeded its limit."));r.push(c.value)}let a=new Uint8Array(i),s=0;for(let c of r)a.set(c,s),s+=c.byteLength;return a});return yield*Xi(o,nt(()=>n.releaseLock()))})}function xf(e,t){return Oe(V({try:()=>new TextDecoder("utf-8",{fatal:!0}).decode(e),catch:(n)=>new G("invalid_transport_line",`Invalid UTF-8 in ${t}.`,{},{cause:n})}))}function Si(e){return Kn(e.replace(/Bearer\s+[^\s]+/giu,"Bearer [redacted]").replace(/((?:api[_-]?key|authorization|cookie|password|secret|token)\s*[:=]\s*)[^\s,;]+/giu,"$1[redacted]"),512)}function bc(e){return e.split(/\r?\n/u).map((t)=>Si(t)).filter((t)=>t.length>0).slice(0,128)}class Ef{process;stdin;stdoutReader;stderrStream;maxLineBytes;maxDiagnosticBytes;lineDecoder=new TextDecoder("utf-8",{fatal:!0});stderrDiagnostics=[];stdoutBuffer=new Uint8Array(0);stderrFiber;closeEffect;closed=!1;constructor(e){if(!OA(e.executablePath))throw new G("discovery_failed","The Codex executable path must be absolute.");if(this.maxLineBytes=e.maxLineBytes??dc,this.maxDiagnosticBytes=e.maxDiagnosticBytes??Lg,this.maxLineBytes<1||this.maxDiagnosticBytes<1)throw new G("invalid_external_data","The transport bounds are invalid.");if(this.process=Bun.spawn([e.executablePath,"app-server"],{...e.cwd===void 0?{}:{cwd:e.cwd},env:yi(e.environment),stdin:"pipe",stdout:"pipe",stderr:"pipe"}),!(this.process.stdout instanceof ReadableStream)||!(this.process.stderr instanceof ReadableStream))throw new G("transport_failure","The Codex App Server did not expose stdio pipes.");if(typeof this.process.stdin==="number"||this.process.stdin===void 0)throw new G("transport_failure","The Codex App Server did not expose stdin.");if(this.stdin=this.process.stdin,this.stdoutReader=this.process.stdout,this.stderrStream=this.process.stderr,this.stderrFiber=ta(this.collectStderrEffect()),e.signal)if(e.signal.aborted)this.close();else e.signal.addEventListener("abort",()=>void this.close(),{once:!0})}get diagnostics(){return[...this.stderrDiagnostics]}readLine(){return A(this.readLineEffect())}readLineEffect(){if(this.closed&&this.stdoutBuffer.byteLength===0)return M(null);return v({self:this},function*(){let e=yield*V({try:()=>this.stdoutReader.getReader(),catch:(n)=>new G("transport_failure","The App Server stdout could not be read.",{},{cause:n})}),t=v({self:this},function*(){while(!0){let n=this.stdoutBuffer.indexOf(10);if(n>=0){if(n>this.maxLineBytes)return yield*Je(d({try:()=>this.close(),catch:()=>{return}})),yield*p(new G("invalid_transport_line","The App Server emitted an overlong line."));let o=this.stdoutBuffer.slice(0,n);this.stdoutBuffer=this.stdoutBuffer.slice(n+1);let a=o.at(-1)===13?o.slice(0,-1):o;return yield*Mw(a,this.lineDecoder)}if(this.stdoutBuffer.byteLength>this.maxLineBytes)return yield*Je(d({try:()=>this.close(),catch:()=>{return}})),yield*p(new G("invalid_transport_line","The App Server emitted an overlong line."));let r=yield*d({try:()=>e.read(),catch:(o)=>new G("transport_failure","The App Server stdout could not be read.",{},{cause:o})});if(r.done){if(this.stdoutBuffer.byteLength===0)return null;if(this.stdoutBuffer.byteLength>this.maxLineBytes)return yield*Je(d({try:()=>this.close(),catch:()=>{return}})),yield*p(new G("invalid_transport_line","The App Server emitted an overlong line."));let o=this.stdoutBuffer;return this.stdoutBuffer=new Uint8Array(0),yield*Mw(o,this.lineDecoder)}let i=new Uint8Array(this.stdoutBuffer.byteLength+r.value.byteLength);i.set(this.stdoutBuffer,0),i.set(r.value,this.stdoutBuffer.byteLength),this.stdoutBuffer=i}});return yield*Xi(t,nt(()=>e.releaseLock()))})}writeLine(e){return A(this.writeLineEffect(e))}writeLineEffect(e){if(this.closed)return p(new G("closed","The App Server transport is closed."));if(new TextEncoder().encode(e).byteLength>this.maxLineBytes)return p(new G("invalid_transport_line","The App Server request exceeded the line limit."));return v({self:this},function*(){yield*d({try:()=>Promise.resolve(this.stdin.write(`${e}
27
+ `)),catch:(t)=>new G("transport_failure","The App Server stdin could not be written.",{},{cause:t})}),yield*d({try:()=>Promise.resolve(this.stdin.flush()),catch:(t)=>new G("transport_failure","The App Server stdin could not be written.",{},{cause:t})})})}close(){if(this.closeEffect===void 0){if(this.closed)return Promise.resolve();this.closed=!0,this.closeEffect=Oe(Ms(this.closeTransportEffect()))}return A(this.closeEffect)}closeTransportEffect(){return v({self:this},function*(){yield*Je(d({try:()=>Promise.resolve(this.stdin.end()),catch:()=>{return}})),yield*Je(V({try:()=>this.process.kill(),catch:()=>{return}})),yield*Zv(Je(d({try:()=>this.process.exited,catch:()=>{return}})),Os(1000)),yield*Je(Ow(this.stderrFiber))})}collectStderrEffect(){return v({self:this},function*(){let e=yield*Zi(Nw(this.stderrStream,this.maxDiagnosticBytes));if(rm(e)){this.stderrDiagnostics.push("[stderr unavailable]");return}let t=yield*V({try:()=>xf(e.value,"Codex stderr"),catch:(n)=>n instanceof G?n:new G("transport_failure","Codex stderr could not be decoded.",{},{cause:n})});for(let n of t.split(/\r?\n/u).slice(0,128)){let r=Si(n);if(r.length>0)this.stderrDiagnostics.push(r)}}).pipe(Yv)}}function Mw(e,t){return V({try:()=>t.decode(e),catch:(n)=>new G("invalid_transport_line","The App Server emitted invalid UTF-8.",{},{cause:n})})}var vf=L(()=>{De();Qo();Aw();mr()});import{spawn as AA}from"child_process";import{lstat as Wr,mkdir as MA,mkdtemp as NA,readFile as DA,readdir as FA,realpath as _h,rename as LA,rm as UA,stat as Lz}from"fs/promises";import{dirname as Fw,isAbsolute as Rh,join as gr,relative as Lw,resolve as _f,sep as Uw}from"path";function GA(e){return v(function*(){let t=Bw(e.selectedPluginIds);if(t.length===0)return;if(yield*Vw(e.timeoutMs,e.pollIntervalMs),e.signal?.aborted)return yield*p(new se("cancelled","Official Codex marketplace bootstrap was cancelled."));let n=yield*e.readSnapshot===void 0?Cf(gr(e.codexHome,...wc),e.codexHome,t):d({try:()=>e.readSnapshot(e.codexHome),catch:(a)=>a});if(n!==void 0&&Tf(n,t))return n;let r=e.initializeRuntime===void 0?oM(e):d({try:()=>e.initializeRuntime(),catch:(a)=>a}),i,o=yield*r.pipe(de((a)=>({closeRuntime:a})),me(()=>!0,(a)=>M({error:a})));if("error"in o)i=ne("marketplace_unavailable","Codex runtime initialization could not start the official marketplace sync. Check that Codex is available and its network/policy settings permit the official marketplace.",o.error);else if(o.closeRuntime!==void 0){let a=v(function*(){let c=e.timeoutMs??Ph,f=e.pollIntervalMs??jA,l=Date.now();while(Date.now()-l<=c){if(e.signal?.aborted)return yield*p(new se("cancelled","Official Codex marketplace bootstrap was cancelled."));let u=yield*e.readSnapshot===void 0?Cf(gr(e.codexHome,...wc),e.codexHome,t):d({try:()=>e.readSnapshot(e.codexHome),catch:(y)=>y});if(u!==void 0&&Tf(u,t))return u;let g=c-(Date.now()-l);if(g<=0)break;let h=Math.min(f,g);yield*e.sleep===void 0?Os(h):d({try:()=>e.sleep(h),catch:(y)=>y})}return yield*p(ne("marketplace_timeout","The official Codex marketplace did not become ready before the bounded wait expired. Check network access and Codex marketplace policy, then retry."))}),s=yield*Fr(M(o.closeRuntime),()=>a.pipe(de((c)=>({snapshot:c})),me(()=>!0,(c)=>M({error:c}))),(c)=>d({try:()=>c(),catch:()=>{return}}));if("snapshot"in s)return s.snapshot;if(s.error instanceof se&&s.error.code==="cancelled")return yield*p(s.error);i=s.error instanceof se?s.error:ne("marketplace_unavailable","The official marketplace sync failed before its bounded wait completed.",s.error)}if(e.gitFallback!==!1)return yield*d({try:()=>$w({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:(a)=>a}).pipe(St((a)=>a instanceof se?a:ne("marketplace_unavailable",`The official marketplace could not be populated after runtime startup (${i?.code??"unavailable"}). Check network access and retry.`,a)));return yield*p(i??ne("marketplace_timeout","The official Codex marketplace did not become ready before the bounded wait expired."))})}function $w(e){return A(YA(e))}function YA(e){return v(function*(){let t=Bw(e.selectedPluginIds);if(t.length===0)return yield*p(ne("marketplace_invalid","The official marketplace fallback requires at least one selected provider plugin."));if(yield*Vw(e.timeoutMs,void 0),!Rh(e.codexHome))return yield*p(ne("marketplace_invalid","The Codex home for official marketplace fallback must be absolute."));if(e.signal?.aborted)return yield*p(new se("cancelled","Official Codex marketplace fallback was cancelled."));let n=yi(e.environment),r=e.gitRunner??Jw("git",{environment:n,...e.timeoutMs===void 0?{}:{timeoutMs:e.timeoutMs}}),i=e.timeoutMs??Ph,o=yield*QA(r,i,e.signal).pipe(St((l)=>l instanceof se?l:ne("marketplace_unavailable","The official Codex marketplace remote HEAD could not be resolved. Check network access and retry.",l))),a=gr(e.codexHome,"plugins"),s=gr(a,wc[1]);if(yield*tM(a,e.codexHome),(yield*me(d({try:()=>Wr(s),catch:(l)=>l}),wa,()=>M(void 0)).pipe(St((l)=>ne("marketplace_invalid","The reserved official marketplace path could not be inspected safely.",l))))!==void 0)return yield*p(ne("marketplace_invalid","The reserved official marketplace path appeared during bootstrap; refusing to overwrite it."));let f=yield*d({try:()=>NA(gr(a,".openai-plugins-stage-")),catch:(l)=>l});return yield*Fr(M(f),(l)=>v(function*(){if(yield*Ch(e.codexHome,l),e.cloneSnapshot!==void 0)yield*d({try:()=>e.cloneSnapshot(Ei,l),catch:(S)=>S}).pipe(St((S)=>sM(S)?ne("marketplace_invalid","The staged official marketplace could not be created as a safe file tree.",S):S));else{let S=yield*d({try:()=>r.run(["-c","core.longpaths=true","clone","--depth=1","--no-tags",Ei,l],{...e.signal===void 0?{}:{signal:e.signal},timeoutMs:i}),catch:(m)=>m});if(S.exitCode!==0)return yield*p(ne("marketplace_unavailable","The official Codex marketplace could not be downloaded. Check network access and retry.",S.stderr))}yield*wf(l);let u=yield*Cf(l,e.codexHome,t);if(u===void 0||!Tf(u,t))return yield*p(ne("marketplace_invalid","The downloaded official marketplace is missing the selected plugin entries or manifest."));if((yield*eM(r,l,i,e.signal))!==o)return yield*p(ne("marketplace_invalid","The downloaded official marketplace did not match the verified remote HEAD."));if((yield*me(d({try:()=>Wr(s),catch:(S)=>S}),wa,()=>M(void 0)).pipe(St((S)=>ne("marketplace_invalid","The reserved official marketplace path could not be checked before publication.",S))))!==void 0)return yield*p(ne("marketplace_invalid","The reserved official marketplace path appeared during staging; refusing to overwrite it."));yield*ZA(l,s,e.renameSnapshot??LA);let y=yield*Cf(gr(e.codexHome,...wc),e.codexHome,t);if(y===void 0||!Tf(y,t))return yield*p(ne("marketplace_invalid","The published official marketplace failed validation."));return y}).pipe(St((u)=>u instanceof se?u:ne("marketplace_unavailable","The official Codex marketplace fallback failed safely. Check network access and retry.",u))),(l)=>d({try:()=>UA(l,{recursive:!0,force:!0}),catch:()=>{return}}))})}function ZA(e,t,n){return v(function*(){for(let r=0;;r+=1){let i=yield*d({try:()=>n(e,t),catch:(c)=>c}).pipe(de(()=>({ok:!0})),me(()=>!0,(c)=>M({ok:!1,error:c})));if(i.ok)return;let o=i.error,a=BA[r];if(process.platform!=="win32"||a===void 0||!XA(o))return yield*p(o);if((yield*me(d({try:()=>Wr(t),catch:(c)=>c}),wa,()=>M(void 0)).pipe(St((c)=>ne("marketplace_invalid","The reserved official marketplace path could not be checked before retrying publication.",c))))!==void 0)return yield*p(ne("marketplace_invalid","The reserved official marketplace path appeared during publication; refusing to overwrite it."));yield*Os(a)}})}function XA(e){return e!==null&&typeof e==="object"&&"code"in e&&(e.code==="EPERM"||e.code==="EBUSY")}function QA(e,t,n){return v(function*(){let r=yield*d({try:()=>e.run(["ls-remote",Ei,"HEAD"],{...n===void 0?{}:{signal:n},timeoutMs:t}),catch:(a)=>a});if(r.exitCode!==0)return yield*p(ne("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((a)=>a.trim()).filter((a)=>a.length>0),o=i.length===1?/^([0-9a-f]{40}|[0-9a-f]{64})\s+HEAD$/iu.exec(i[0]??""):null;if(o?.[1]===void 0)return yield*p(ne("marketplace_invalid","The official Codex marketplace remote HEAD response was malformed."));return o[1].toLowerCase()})}function eM(e,t,n,r){return v(function*(){let i=yield*d({try:()=>e.run(["rev-parse","HEAD"],{timeoutMs:n,cwd:t,...r===void 0?{}:{signal:r}}),catch:(a)=>a}),o=i.stdout.trim().toLowerCase();if(i.exitCode!==0||!/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/u.test(o))return yield*p(ne("marketplace_invalid","The downloaded official marketplace checkout did not expose a valid HEAD.",i.stderr));return o})}function tM(e,t){return v(function*(){yield*wh(t,e),yield*d({try:()=>MA(e,{recursive:!0}),catch:(n)=>n}),yield*wh(t,e)})}function wh(e,t){return v(function*(){let n=_f(e),r=_f(t);while(!0){if((yield*me(d({try:()=>Wr(r),catch:(a)=>a}),wa,()=>M(void 0)))?.isSymbolicLink())return yield*p(ne("marketplace_invalid","The official marketplace path cannot contain symlinks."));if(r===n)return;let o=Fw(r);if(o===r||o!==n&&!nM(n,o))return yield*p(ne("marketplace_invalid","The official marketplace path escaped CODEX_HOME."));r=o}})}function nM(e,t){let n=Lw(e,t);return n.length>0&&n!==".."&&!n.startsWith(`..${Uw}`)&&!Rh(n)}function wf(e){return v(function*(){let t=yield*d({try:()=>Wr(e),catch:(r)=>r});if(t.isSymbolicLink())return yield*p(ne("marketplace_invalid","The official marketplace snapshot cannot contain symlinks."));if(!t.isDirectory())return yield*p(ne("marketplace_invalid","The official marketplace snapshot is not a directory."));let n=yield*d({try:()=>FA(e,{withFileTypes:!0}),catch:(r)=>r});for(let r of n){let i=gr(e,r.name),o=yield*d({try:()=>Wr(i),catch:(a)=>a});if(o.isSymbolicLink())return yield*p(ne("marketplace_invalid","The official marketplace snapshot cannot contain symlinks."));if(o.isDirectory())yield*wf(i)}})}function Cf(e,t,n=[]){return v(function*(){if(t!==void 0)yield*wh(t,e);let r=yield*me(d({try:()=>Wr(e),catch:(f)=>f}),wa,()=>M(void 0)).pipe(St((f)=>ne("marketplace_invalid","The reserved openai-curated marketplace path could not be read safely.",f)));if(r===void 0)return;if(r.isSymbolicLink()||!r.isDirectory())return yield*p(ne("marketplace_invalid","The reserved openai-curated marketplace path is not a real directory."));if(t!==void 0)yield*Ch(t,e);else yield*wf(e);if(t!==void 0)yield*wf(e);let i=yield*d({try:()=>_h(e),catch:(f)=>f}),o=[gr(i,".agents","plugins","marketplace.json"),gr(i,".codex-plugin","marketplace.json"),gr(i,"marketplace.json")],a,s;for(let f of o){let l=yield*me(d({try:()=>Wr(f),catch:(g)=>g}),wa,()=>M(void 0)).pipe(St((g)=>ne("marketplace_invalid","The official marketplace manifest could not be read safely.",g)));if(l===void 0)continue;if(l.isSymbolicLink()||!l.isFile())return yield*p(ne("marketplace_invalid","The official marketplace manifest is not a regular file."));if(yield*Ch(i,f),a!==void 0)return yield*p(ne("marketplace_invalid","The reserved official marketplace contains more than one manifest."));a=f;let u=yield*d({try:()=>DA(f),catch:(g)=>g});s=yield*V({try:()=>new TextDecoder("utf-8",{fatal:!0}).decode(u),catch:(g)=>ne("marketplace_invalid","The official marketplace manifest is not valid UTF-8.",g)})}if(a===void 0||s===void 0)return;let c=yield*V({try:()=>JSON.parse(s),catch:(f)=>ne("marketplace_invalid","The official marketplace manifest is not valid JSON.",f)});return yield*V({try:()=>jw(c,i,a,n),catch:(f)=>f})})}function jw(e,t=`${wc.join("/")}`,n=`${t}/marketplace.json`,r=[]){let i=Pe(qA)(e);if(Me(i))throw ne("marketplace_invalid","The reserved official marketplace manifest is malformed or has an unexpected name.");let o=i.success;if(!rM(o))throw ne("marketplace_invalid","The reserved official marketplace source is not the approved OpenAI repository.");if(o.plugins.length===0)throw ne("marketplace_invalid","The official marketplace manifest has no plugin entries.");let a=[],s=new Set;for(let c of o.plugins){let f=Pe(WA)(c);if(Me(f)){if(r.length>0)continue;throw ne("marketplace_invalid","The official marketplace contains a malformed plugin entry.")}let l=f.success,u=l.name;if(s.has(u)){if(r.length>0&&!r.includes(u))continue;throw ne("marketplace_invalid","The official marketplace contains a duplicate plugin name.")}if(s.add(u),r.length>0&&!r.includes(u))continue;let g=iM(l),h=g===void 0?void 0:Pe(zA)(g);if(h===void 0||Me(h))throw ne("marketplace_invalid",`The official marketplace source for ${u} is unsafe.`);a.push({name:u,source:h.success})}if(r.some((c)=>!a.some((f)=>f.name===c)))throw ne("marketplace_invalid","The official marketplace is missing a selected plugin entry.");return{name:Tc,source:Ei,rootPath:t,manifestPath:n,plugins:a}}function rM(e){return[e.source,e.repository,e.repo,e.url].every((t)=>t===void 0||Ve(Pe(VA)(t)))}function iM(e){let t=e.source;if(typeof t==="string")return t;if(t?.path!==void 0)return t.path;if(e.path!==void 0)return e.path;return}function Bw(e){let t=[],n=new Set;for(let r of e){let i=r.lastIndexOf("@");if(i<1)continue;let o=r.slice(i+1);if(o!==Tc&&o!=="openai-curated-remote")continue;let a=r.slice(0,i);if(Me(Pe(kf)(a)))throw ne("marketplace_invalid","A selected official marketplace plugin id is invalid.");if(!qw(a))continue;if(!n.has(a))n.add(a),t.push(a)}return t}function Tf(e,t){return t.every((n)=>{let r=e.plugins.find((o)=>o.name===n);if(r===void 0)return!1;return r.source.replaceAll("\\","/").replace(/\/+$/u,"").split("/").at(-1)===n})}function oM(e){return v(function*(){let t=yi(e.environment),n=new Ef({executablePath:e.executablePath,environment:t,...e.signal===void 0?{}:{signal:e.signal}}),r=new Sf(n,{requestTimeoutMs:Math.min(e.timeoutMs??Ph,1e4),...e.signal===void 0?{}:{signal:e.signal}});return yield*d({try:()=>r.initialize(),catch:(i)=>i}).pipe(As(()=>d({try:()=>n.close(),catch:(i)=>i}).pipe(Je))),()=>aM(r)})}function aM(e){return A(d({try:()=>e.close(),catch:(t)=>t}).pipe(Je))}function Vw(e,t){if(e!==void 0&&(!Number.isSafeInteger(e)||e<1||e>300000))return p(ne("marketplace_invalid","The official marketplace timeout is invalid."));if(t!==void 0&&(!Number.isSafeInteger(t)||t<0||t>60000))return p(ne("marketplace_invalid","The official marketplace poll interval is invalid."));return rt}function Ch(e,t){return v(function*(){let n=yield*d({try:()=>_h(e),catch:(s)=>s}),r=yield*d({try:()=>_h(t),catch:(s)=>s}),i=Lw(n,r);if(i===""||i===".."||i.startsWith(`..${Uw}`))return yield*p(ne("marketplace_invalid","The reserved official marketplace is outside CODEX_HOME."));let o=_f(e),a=_f(t);while(!0){if((yield*d({try:()=>Wr(a),catch:(f)=>f})).isSymbolicLink())return yield*p(ne("marketplace_invalid","The reserved official marketplace path cannot contain symlinks."));if(a===o)break;let c=Fw(a);if(c===a)throw ne("marketplace_invalid","The reserved official marketplace path is outside CODEX_HOME.");a=c}})}function wa(e){return typeof e==="object"&&e!==null&&"code"in e&&e.code==="ENOENT"}function sM(e){return typeof e==="object"&&e!==null&&"code"in e&&(e.code==="EPERM"||e.code==="EACCES")}function ne(e,t,n){return new se(e,t,n instanceof Error?{cause:Si(n.message)}:{})}function hr(e,t){let n=Pn(t);if(n===void 0||n!==t)return;let i=[...e.installed,...e.available].flatMap((o)=>{let a=cg(o.pluginId,o.marketplaceName);return a?.canonicalPluginId===n?[{identity:a,entry:o}]:[]});return i.find((o)=>o.entry.pluginId===n&&o.entry.installed)??i.find((o)=>o.entry.installed)??i.find((o)=>o.entry.pluginId===n)??i[0]}function qw(e){return rf.includes(e)}function zw(e){if(!mc(kh,e))return kw(je("live official plugin list",e));return Rw(Nt(kh,e,"live official plugin list"))}function Rf(e){let t=e.runner??Jw(e.executable,{environment:e.environment??yi(),...e.timeoutMs===void 0?{}:{timeoutMs:e.timeoutMs},...e.stdoutLimit===void 0?{}:{stdoutLimit:e.stdoutLimit},...e.stderrLimit===void 0?{}:{stderrLimit:e.stderrLimit}}),n=v(function*(){let o=yield*d({try:()=>t.run(["plugin","list","--json"]),catch:(c)=>c});if(o.exitCode!==0)return yield*p(xi("list",o));let a=yield*V({try:()=>JSON.parse(o.stdout),catch:()=>new se("command_failed","Codex returned invalid plugin data.")}),s=zw(a);if(!s.ok)return yield*p(new se("command_failed","Codex returned an invalid official plugin list."));return s.value}),r=()=>A(n),i=v(function*(){let o=yield*d({try:()=>t.run(["plugin","marketplace","list","--json"]),catch:(c)=>c});if(o.exitCode!==0)return yield*p(xi("marketplace list",o));let a=yield*V({try:()=>JSON.parse(o.stdout),catch:()=>new se("command_failed","Codex returned invalid marketplace data.")}),s=Pe(fM)(a);if(Me(s))return yield*p(new se("command_failed","Codex returned an invalid marketplace list."));return s.success.marketplaces.map((c)=>({name:c.name,root:c.root,...c.marketplaceSource===void 0?{}:{marketplaceSource:{sourceType:c.marketplaceSource.sourceType,source:c.marketplaceSource.source}}}))});return{list:r,ensureOfficialMarketplace:(o)=>A(v(function*(){if(e.codexHome===void 0)return yield*p(new se("marketplace_unavailable","Codex home is unavailable; the official marketplace cannot be bootstrapped safely."));yield*GA({codexHome:e.codexHome,executablePath:e.executable,selectedPluginIds:o,...e.environment===void 0?{}:{environment:e.environment},...e.timeoutMs===void 0?{}:{timeoutMs:e.timeoutMs},...e.officialMarketplaceFallback===void 0?{}:{gitFallback:e.officialMarketplaceFallback}})})),addMarketplace:(o,a)=>A(v(function*(){let s=Nt(lo,o,"plugin marketplace source");if(s===Tc||s===Ei)return yield*p(new se("marketplace_invalid","The reserved openai-curated marketplace must be populated by Codex runtime startup; it cannot be added manually."));if(s!==Ih)return yield*p(new se("marketplace_invalid",`Unsupported managed marketplace source: ${s}.`));let c,f=!1,l=yield*i.pipe(de((_)=>({value:_})),me(pM,(_)=>M({error:_})));if("error"in l){e.onMarketplaceConflict?.("The registered HolyCodex marketplace cache is incomplete; Codex will rebuild it from the canonical source.");let _=yield*d({try:()=>t.run(["plugin","marketplace","add",s],a===void 0?void 0:{signal:a}),catch:(C)=>C});if(_.exitCode!==0)return yield*p(xi("marketplace add",_,s));c=yield*i,f=!0}else c=l.value;let u=bh(c,Jr),g=mM(c,Jr);if(u!==void 0&&g.length>0){e.onMarketplaceConflict?.(`${u} HolyCodex will remove the conflicting registration and restore its required source.`);for(let _ of g){let C=yield*d({try:()=>t.run(["plugin","marketplace","remove",_],a===void 0?void 0:{signal:a}),catch:(N)=>N});if(C.exitCode!==0)return yield*p(xi("marketplace remove",C,_))}}let h=g.length===0?c:yield*i,y=bh(h,Jr);if(y!==void 0)return yield*p(new se("marketplace_invalid",y));if(h.find((_)=>_.name===Jr)===void 0){let _=yield*d({try:()=>t.run(["plugin","marketplace","add",s],a===void 0?void 0:{signal:a}),catch:(C)=>C});if(_.exitCode!==0)return yield*p(xi("marketplace add",_,s))}else if(!f){let _=yield*d({try:()=>t.run(["plugin","marketplace","upgrade",Jr],a===void 0?void 0:{signal:a}),catch:(C)=>C});if(_.exitCode!==0)return yield*p(xi("marketplace upgrade",_,Jr))}let m=yield*i,x=bh(m,Jr);if(x!==void 0)return yield*p(new se("marketplace_invalid",x));let E=m.find((_)=>_.name===Jr);if(E===void 0||!Cc(E.marketplaceSource))return yield*p(new se("readback_mismatch","Codex did not report the canonical HolyCodex marketplace after installation or refresh."))})),add:(o,a)=>A(v(function*(){let s=yield*V({try:()=>Nt(lo,o,"official plugin id"),catch:(m)=>m}),c=ya(s),f=Pn(s)==="computer-use@openai-bundled"?c:c.includes(s)?[s,...c.filter((m)=>m!==s)]:[s],l=!1;for(let[m,x]of f.entries()){let E=yield*d({try:()=>t.run(["plugin","add",x,"--json"],a===void 0?void 0:{signal:a}),catch:(_)=>_});if(E.exitCode===0){l=!0;break}if(m<f.length-1&&dM(E.stderr))continue;return yield*p(xi("add",E,x))}if(!l)return yield*p(new se("command_failed",`Codex could not install ${s} from its recognized marketplace sources.`));let u=yield*n,g=hr(u,s),h=Pn(s),y=[...u.installed,...u.available].filter((m)=>m.pluginId===s&&(h===void 0||m.marketplaceName==null)),S=g?.entry??y.find((m)=>m.installed)??y[0];if(!S)return yield*p(new se("readback_mismatch",`Codex did not report ${s} after installation.`,{plugin_id:s}));if(!S.installed)return yield*p(new se("plugin_missing",`Codex reported ${s} as unavailable after installation.`,{plugin_id:s}));if(!S.enabled)return yield*p(new se("plugin_disabled",`Codex installed ${s} but it is disabled; enable it in Codex and retry.`,{plugin_id:s}))})),remove:(o,a)=>A(v(function*(){let s=yield*V({try:()=>Nt(lo,o,"official plugin id"),catch:(g)=>g}),c=s;if(Pn(s)===s){let g=yield*n,h=hr(g,s);if(h?.entry.installed)c=h.entry.pluginId}let f=yield*d({try:()=>t.run(["plugin","remove",c,"--json"],a===void 0?void 0:{signal:a}),catch:(g)=>g});if(f.exitCode!==0&&!/not (?:installed|found)|missing/iu.test(f.stderr))return yield*p(xi("remove",f,c));let l=yield*n,u=[...l.installed,...l.available].find((g)=>g.pluginId===c);if(u?.installed)return yield*p(new se("readback_mismatch",`Codex still reports ${s} after removal.`,{plugin_id:s,observed_plugin_id:u.pluginId}))}))}}function xi(e,t,n){let r=Si(t.stderr).trim().slice(0,512),i=r.length>0?`: ${r}`:"";return new se("command_failed",`Codex plugin ${e} failed${n===void 0?"":` for ${n}`}${i}`,{exit_code:t.exitCode})}function dM(e){return/plugin\b.+\bnot found in marketplace\b/iu.test(Si(e))}function pM(e){if(!(e instanceof se)||e.code!=="command_failed")return!1;return/(?:^|[\n:])\s*-\s*`([^`]+)`\s+at\s+[^\r\n]*:\s*marketplace root does not contain a supported manifest/iu.exec(e.message)?.[1]===Jr}function bh(e,t){let n=e.filter((i)=>i.name===t);if(n.length>1)return`Multiple Codex marketplaces use the reserved name ${t}; resolve the duplicate configuration before installing HolyCodex.`;if(n[0]!==void 0&&!Cc(n[0].marketplaceSource)){let i=n[0].marketplaceSource?.source??"an unknown source";return`Codex marketplace ${t} points to ${i}, not the canonical HolyCodex source ${Ih}; resolve the conflict before installing.`}let r=e.find((i)=>i.name!==t&&Cc(i.marketplaceSource));if(r!==void 0)return`The canonical HolyCodex source is already registered as Codex marketplace ${r.name}; resolve the noncanonical marketplace name before installing.`;return}function mM(e,t){let r=e.filter((i)=>i.name===t).length>1;return[...new Set(e.filter((i)=>i.name===t&&(r||!Cc(i.marketplaceSource))||i.name!==t&&Cc(i.marketplaceSource)).map((i)=>i.name))]}function Cc(e){if(e?.sourceType!=="git")return!1;return If(e.source)}function If(e){return $A.some((t)=>t===e)}function Jw(e,t){let n=t.timeoutMs??30000,r=t.stdoutLimit??131072,i=t.stderrLimit??16384;return{run:(o,a)=>gM(e,o,{...t.environment===void 0?{}:{environment:t.environment},timeoutMs:a?.timeoutMs??n,stdoutLimit:r,stderrLimit:i,...a?.cwd===void 0?{}:{cwd:a.cwd},...a?.signal===void 0?{}:{signal:a.signal}})}}function gM(e,t,n){return A(hM(e,t,n))}function hM(e,t,n){return v(function*(){if(n.signal?.aborted)return yield*p(new se("cancelled","The Codex plugin command was cancelled."));let r=AA(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=ci((l)=>{r.once("error",()=>l(p(new se("command_failed","The Codex plugin command failed.")))),r.once("close",(u)=>l(M(u??-1)))}),o=n.signal===void 0?Wv:ci((l)=>{let u=()=>l(p(new se("cancelled","The Codex plugin command was cancelled.")));return n.signal.addEventListener("abort",u,{once:!0}),nt(()=>n.signal.removeEventListener("abort",u))}),a=Tn([Dw(r.stdout,n.stdoutLimit),Dw(r.stderr,n.stderrLimit),i],{concurrency:"unbounded"}).pipe(Su(n.timeoutMs),St((l)=>l instanceof se?l:l!==null&&typeof l==="object"&&("_tag"in l)&&l._tag==="TimeoutError"?new se("timeout","The Codex plugin command timed out."):new se("command_failed","The Codex plugin command failed."))),[s,c,f]=yield*Xv(a,o).pipe(As(()=>nt(()=>r.kill())));return{stdout:s,stderr:c,exitCode:f}})}function Dw(e,t){if(e===null)return p(new se("command_failed","Codex plugin command output is unavailable."));return ci((n)=>{let r=[],i=0;e.on("data",(o)=>{let a=typeof o==="string"?new TextEncoder().encode(o):o instanceof Uint8Array?o:void 0;if(a===void 0){n(p(new se("command_failed","Codex plugin output was invalid.")));return}if(i+=a.byteLength,i>t){n(p(new se("output_limit","Codex plugin output exceeded its limit.")));return}r.push(a)}),e.once("end",()=>{let o=new Uint8Array(i),a=0;for(let s of r)o.set(s,a),a+=s.byteLength;n(V({try:()=>new TextDecoder("utf-8",{fatal:!0}).decode(o),catch:()=>new se("command_failed","Codex plugin output was not valid UTF-8.")}))}),e.once("error",()=>n(p(new se("command_failed","Codex plugin output could not be read."))))})}var Tc="openai-curated",Ei="https://github.com/openai/plugins.git",Jr="holycodex",Ih="davidbasilefilho/holycodex",$A,wc,Ph=30000,jA=100,BA,kf,bf,VA,qA,zA,JA,WA,HA,_c,lo,KA,cM,Th,kh,lM,uM,fM,se;var Pf=L(()=>{st();De();bt();Fe();qg();mr();vf();$A=[Ih,"https://github.com/davidbasilefilho/holycodex.git","https://github.com/davidbasilefilho/holycodex","https://github.com/davidbasilefilho/holycodex.git/","https://github.com/davidbasilefilho/holycodex/","git@github.com:davidbasilefilho/holycodex.git","git@github.com:davidbasilefilho/holycodex","ssh://git@github.com/davidbasilefilho/holycodex.git","ssh://git@github.com/davidbasilefilho/holycodex"],wc=["plugins","openai-plugins"],BA=[25,50,100,200],kf=w.check(ue(/^[a-z][a-z0-9._-]{1,63}$/u)),bf=Z([w,ke(b({url:w}),[We(w,lt)])]),VA=Z([T([Ei]),ke(b({url:T([Ei])}),[We(w,lt)])]),qA=ke(b({name:T([Tc]),plugins:j(lt),source:k(bf),repository:k(bf),repo:k(bf),url:k(bf)}),[We(w,lt)]),zA=w.check(ee((e)=>{if(e.length===0||Rh(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)&&t.split("/").every((n)=>n.length===0||n==="."||n!=="..")})),JA=Z([w,ke(b({path:k(w)}),[We(w,lt)])]),WA=ke(b({name:kf,source:k(JA),path:k(w)}),[We(w,lt)]),HA=w.check(ue(/^[0-9]+\.[0-9]+\.[0-9]+(?:[-+][A-Za-z0-9.-]+)?$/u)),_c=j(w),lo=w.check(ue(/^[A-Za-z0-9][A-Za-z0-9._:@/-]{0,255}$/u)),KA=b({name:kf,version:HA,description:qr,author:k(Et),license:k(qr),homepage:k(qr),repository:k(qr),keywords:k(_c),skills:k(_c),commands:k(_c),hooks:k(_c),assets:k(_c),official:k(W)});cM=b({id:kf,selected:T([!0])}),Th=ke(b({pluginId:lo,installed:W,enabled:W,name:k(Z([w,ot])),marketplaceName:k(Z([w,ot])),version:k(Z([w,ot]))}),[We(w,lt)]),kh=b({installed:j(Th),available:j(Th)});lM=ke(b({sourceType:w,source:w}),[We(w,lt)]),uM=ke(b({name:w,root:w,marketplaceSource:k(lM)}),[We(w,lt)]),fM=ke(b({marketplaces:j(uM)}),[We(w,lt)]);se=class se extends Error{code;details;constructor(e,t,n={}){super(t);this.name="OfficialPluginAdapterError",this.code=e,this.details=n}}});function Kw(e){return be(Hw)(e)}function yr(e){return be(vi)(e)}function Ah(e){let t=[],n=0,r=!1,i=!1;for(let o=0;o<=e.length;o+=1){let a=e[o];if(o===e.length||a==="."&&!r){let s=e.slice(n,o),c=s.startsWith('"')?yM(s):s,f=s.startsWith('"'),l=f&&t.length===1&&t[0]==="plugins"&&be(lo)(c),u=f&&t.length===1&&t[0]==="agents"&&Oh.includes(c);if(f?!l&&!u:!/^[A-Za-z][A-Za-z0-9_-]*$/u.test(c)&&!Oh.includes(c))throw je("TOML key path",e);if(c==="__proto__"||(c==="constructor"||c==="prototype")&&!l)throw je("TOML key path",e);t.push(c),n=o+1;continue}if(r){if(i)i=!1;else if(a==="\\")i=!0;else if(a==='"')r=!1}else if(a==='"')r=!0}if(r||i||t.length===0)throw je("TOML key path",e);return t}function yM(e){let t=Pe(tf(w))(e);if(Ve(t))return t.success;throw je("TOML quoted key",e)}function pe(e,t){if(!yr(e))throw je("TOML document",e);let n=e,r=Ah(t);for(let i=0;i<r.length;i+=1){let o=r[i];if(!yr(n)||!Object.prototype.hasOwnProperty.call(n,o))return;if(n=n[o],i===1&&r[0]==="features"&&o==="context_management"&&typeof n==="boolean"&&r[2]==="experimental_mode")return n}return n}function Of(e){if(Array.isArray(e))return e.map(Of);if(pc(e))return Object.fromEntries(Object.entries(e).map(([t,n])=>[t,Of(n)]));return e}function Af(e){return Of(e)}function Gn(e,t,n){if(!yr(e)||!Kw(n))throw je("TOML write",{keyPath:t});let r=Ah(t),i={...Af(e)},o=i;for(let a of r.slice(0,-1)){let s=Object.prototype.hasOwnProperty.call(o,a)?o[a]:void 0;if(s!==void 0&&!yr(s)){if(a!=="context_management"||typeof s!=="boolean"||o!==i.features)throw je("TOML table path",t);if(r.at(-1)==="experimental_mode"&&s===n)return i;o[a]={experimental_mode:s}}let c=s===void 0?{}:yr(o[a])?{...o[a]}:{};o[a]=c,o=c}return o[r.at(-1)]=Of(n),i}function vn(e,t){if(!yr(e))throw je("TOML document",e);let n=Ah(t),r={...Af(e)},i=[],o=r;for(let s of n.slice(0,-1)){let c=o[s];if(!yr(c))return r;let f={...c};i.push({table:o,key:s}),o[s]=f,o=f}let a=n.at(-1);if(!Object.prototype.hasOwnProperty.call(o,a))return r;delete o[a];for(let s=i.length-1;s>=0;s-=1){let c=i[s],f=c.table[c.key];if(yr(f)&&Object.keys(f).length===0)delete c.table[c.key];else break}return r}function Rc(e){return be(Mh)(e)}function SM(e){if(Gw.includes(e))return!0;if(/^agents\.(?:explorer|librarian|worker|reviewer)\.config_file$/u.test(e))return!0;return Oh.some((t)=>e===`agents."${t}".config_file`)}function Yw(e){return be(Nh)(e)}function kc(e){return be(Ca)(e)}function Qw(e){return be(Zw)(e)}function eC(e){return be(Xw)(e)}function Lh(e,t){let n=new Set(t);return Object.keys(e).every((r)=>n.has(r))}function Ww(e,t){switch($h(e)){case"number":return t.kind==="number";case"boolean":return t.kind==="boolean";case"relative_path":return t.kind==="relative_path";case"digest":return t.kind==="digest";case"enum":if(t.kind!=="enum")return!1;if(e==="model")return t.value==="gpt-6-astra"||t.value==="gpt-6.1-sol"||t.value==="gpt-6-sol"||t.value==="gpt-6-luna"||t.value==="gpt-5.6-terra"||t.value==="gpt-5.6-sol"||t.value==="gpt-5.6-luna";if(e==="model_reasoning_effort")return t.value==="low"||t.value==="medium"||t.value==="high"||t.value==="xhigh"||t.value==="max";if(e==="service_tier")return t.value==="default"||t.value==="fast";if(e==="approval_policy")return t.value==="on-request"||t.value==="never";if(e==="approvals_reviewer")return t.value==="auto_review"||t.value==="user";if(e==="permissions.holycodex.extends")return t.value===":workspace"||t.value===":read-only"||kc(t.value);if(e==="web_search")return t.value==="live"||t.value==="cached"||t.value==="indexed"||t.value==="disabled";return t.value==="low"||t.value==="medium"||t.value==="high"}}function uo(e){return be(Ic)(e)}function Nf(e){if(!kc(e.schema)||!kc(e.installId))throw je("managed runtime config metadata",{schema:e.schema});return{owner:"holycodex",schema:e.schema,installId:e.installId,managed:{}}}function Df(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 Uh(e){if(!Df(e))throw je("relative config path","[redacted]");return e.replaceAll("\\","/").split("/").filter((t)=>t!==".").join("/")}function fo(e,t){let n=Uh(t),r=e.replaceAll("\\","/").split("/");r.pop();let i=[...r,...n.split("/")].join("/"),o=[];for(let c of i.split("/")){if(c.length===0||c===".")continue;if(c==="..")o.pop();else o.push(c)}let a=e.replaceAll("\\","/");return`${a.startsWith("//")?"//":a.startsWith("/")?"/":""}${o.join("/")}`}function $h(e){if(e==="developer_instructions")return"digest";if(e.endsWith(".config_file"))return"relative_path";if(e==="agents.max_concurrent_threads_per_session")return"number";if(e==="model_auto_compact_token_limit")return"number";if(e==="suppress_unstable_features_warning"||e==="features.multi_agent"||e==="features.default_mode_request_user_input"||e==="features.multi_agent_v2"||e==="features.agent_message_board"||e==="features.context_management.experimental_mode"||e==="permissions.holycodex.network.enabled"||bi.includes(e))return"boolean";return"enum"}function CM(e,t){let n=$h(e);if(n==="number")return eC(t);if(n==="boolean")return typeof t==="boolean";if(n==="relative_path")return typeof t==="string"&&Df(t);if(n==="digest")return typeof t==="string";if(e==="model")return t==="gpt-6-astra"||t==="gpt-6.1-sol"||t==="gpt-6-luna";return typeof t==="string"&&Qw(t)}function on(e,t){if(!Yw(e)||!Kw(t))return p(je("managed config value",{keyPath:e}));let n=$h(e);if(n==="number"&&eC(t))return M({kind:n,value:t});if(n==="boolean"&&typeof t==="boolean")return M({kind:n,value:t});if(n==="relative_path"&&typeof t==="string"&&Df(t))return M({kind:n,value:Uh(t)});if(n==="enum"&&typeof t==="string"&&Qw(t))return M({kind:n,value:t});return de(d({try:()=>En("holycodex-managed-config-value",[xn({keyPath:e,value:t})]),catch:(r)=>je("managed config value digest",{keyPath:e},r)}),(r)=>({kind:"digest",value:r}))}function TM(e){if(e.kind==="enum"||e.kind==="number"||e.kind==="boolean"||e.kind==="relative_path")return e.value;return}function Pc(e,t,n,r){return v(function*(){if(!yr(e)||!uo(t)||!kc(r.schema)||!kc(r.installId))return yield*p(je("managed runtime config",{}));let i={...t.managed},o=Af(e),a=[];for(let[c,f]of Object.entries(n)){if(!Rc(c)||typeof f!=="string"&&typeof f!=="number"&&typeof f!=="boolean")return yield*p(je("managed config key",c));let l=c,u=t.managed[l],g=pe(o,l);if(u&&(u.schema!==r.schema||u.installId!==r.installId)){a.push(l);continue}if(u&&u.owner==="holycodex"){let y=g===void 0?void 0:yield*on(l,g);if(y===void 0||JSON.stringify(y)!==JSON.stringify(u.lastManagedValue)){a.push(l);continue}}let h=u?.originalValue??(g===void 0?{kind:"absent"}:yield*on(l,g));if(!CM(l,f))return yield*p(je("managed config value",{keyPath:l}));o=Gn(o,l,f),i[l]={owner:"holycodex",schema:r.schema,installId:r.installId,keyPath:l,originalValue:h,lastManagedValue:yield*on(l,f)}}let s={owner:"holycodex",schema:r.schema,installId:r.installId,managed:i};if(!uo(s))return yield*p(je("managed runtime config state",{}));return{document:o,state:s,driftedKeys:a}})}function Ta(e,t,n){return A(po(e,t,n))}function po(e,t,n){return v(function*(){if(!yr(e)||!uo(t))return yield*p(je("managed runtime config",{}));let r=Af(e),i={...t.managed},o=[],a=[],s=[];for(let[c,f]of Object.entries(t.managed)){if(!Yw(c))return yield*p(je("managed config key",c));let l=c;if(f.owner!=="holycodex"||f.schema!==n.schema||f.installId!==n.installId){if(f.schema!==n.schema||f.installId!==n.installId)s.push(l);continue}let u=pe(r,l),g=u===void 0?void 0:yield*on(l,u);if(!(g!==void 0&&JSON.stringify(g)===JSON.stringify(f.lastManagedValue))){a.push(l);continue}if(f.originalValue.kind==="absent")r=vn(r,l),o.push(l),delete i[l];else{let y=TM(f.originalValue);if(y===void 0){s.push(l),a.push(l);continue}r=Gn(r,l,y),o.push(l),delete i[l]}}return{document:r,state:{...t,managed:i},restoredKeys:o,preservedKeys:a,unresolvedKeys:s}})}function Ff(e,t,n){return A(Oc(e,t,n))}function Oc(e,t,n){return v(function*(){if(!Rc(n)||!uo(t))return yield*p(je("managed config key",n));let r=t.managed[n],i=pe(e,n),o=i===void 0?void 0:yield*on(n,i);if(!r)return o===void 0?{keyPath:n,status:"unmanaged"}:{keyPath:n,status:"unmanaged",current:o};return{keyPath:n,status:o!==void 0&&JSON.stringify(o)===JSON.stringify(r.lastManagedValue)?"unchanged":"drifted",expected:r.lastManagedValue,...o===void 0?{}:{current:o}}})}var Oh,Hw,vi,Gw,bi,Mh,Nh,xM,Ca,Zw,Xw,EM,vM,bM,Mf,Dh,_M,Fh,wM,Ic;var Lf=L(()=>{st();st();De();bt();Fe();mr();Pf();Oh=[...Br,"Reviewer.plan"],Hw=nn,vi=mi;Gw=["model","model_reasoning_effort","service_tier","agents.max_concurrent_threads_per_session","web_search","approval_policy","approvals_reviewer","permissions.holycodex.extends","permissions.holycodex.network.enabled","model_verbosity","developer_instructions","suppress_unstable_features_warning","features.multi_agent","features.default_mode_request_user_input","features.multi_agent_v2","features.agent_message_board","features.context_management.experimental_mode"],bi=["model_auto_compact_token_limit","features.context_management","sandbox_workspace_write.network_access"],Mh=w.check(ee(SM));Nh=Z([Mh,T(bi)]);xM=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u,Ca=w.check(ue(xM)),Zw=Z([Ca,T([":workspace",":read-only"])]),Xw=xt.check(ee((e)=>Number.isSafeInteger(e)&&e>=0)),EM=w.check(ue(/^[a-f0-9]{64}$/u)),vM=w.check(ee(Df)),bM=Z([b({kind:T(["enum"]),value:Zw}),b({kind:T(["number"]),value:Xw}),b({kind:T(["boolean"]),value:W}),b({kind:T(["relative_path"]),value:vM}),b({kind:T(["digest"]),value:EM})]),Mf=bM.check(ee((e)=>Lh(e,["kind","value"]))),Dh=Z([Mf,b({kind:T(["absent"])})]),_M=b({owner:T(["holycodex"]),schema:Ca,installId:Ca,keyPath:Nh,originalValue:Dh,lastManagedValue:Mf}),Fh=_M.check(ee((e)=>Lh(e,["owner","schema","installId","keyPath","originalValue","lastManagedValue"])&&Ww(e.keyPath,e.lastManagedValue)&&(e.originalValue.kind==="absent"||Ww(e.keyPath,e.originalValue)))),wM=b({owner:T(["holycodex"]),schema:Ca,installId:Ca,managed:We(w,Fh)}),Ic=wM.check(ee((e)=>Lh(e,["owner","schema","installId","managed"])&&Object.entries(e.managed).every(([t,n])=>be(Nh)(t)&&n.keyPath===t)))});function Pw(e){if(hc.some((t)=>t===e))return"permissions";if(gc.some((t)=>t===e))return"approval";if($g.some((t)=>t===e))return"elicitation";if(jg.some((t)=>t===e))return"dynamic_tool";return"other"}var tC,Jt,kM,jh,ka,nC,yc,RM,zg,Sc,Sr,IM,PM,rC,xc,Jg,Wg,Ac,Ec,Hg,Kg,Gg,Yg,Zg,Xg,Qg,vc,eh,th,nh,iC,rh,ih,oh,ah,sh,ch,lh,uh,OM,AM,MM,fh,dh,ph,mh,gh,hh,yh,Sh,yf,Qz,NM,eJ;var xh=L(()=>{Fe();mr();hf();Lf();tC=w.check(ue(/^[A-Za-z][A-Za-z0-9_./:-]{0,127}$/u)),Jt=[We(w,Et)],kM=w.check(ue(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u)),jh=w.check(at(1)),ka=Z([w.check(at(1)),xt.check(ee((e)=>Number.isSafeInteger(e)))]),nC=b({code:xt.check(ee((e)=>Number.isSafeInteger(e))),message:w,data:k(Et)}),yc=Z([b({id:ka,result:Et}),b({id:ka,error:nC})]),RM=b({id:ka,error:nC}),zg=b({method:tC,params:k(Et)}),Sc=b({id:ka,method:tC,params:k(Et),trace:k(Et)}),Sr=xt.check(T_(),Xu(0)),IM=b({inputTokens:qe(Sr),cachedInputTokens:qe(Sr),outputTokens:qe(Sr),reasoningOutputTokens:qe(Sr),totalTokens:qe(Sr)}).check(ee((e)=>Object.values(e).some((t)=>t!==void 0))),PM=b({input_tokens:qe(Sr),cached_input_tokens:qe(Sr),output_tokens:qe(Sr),reasoning_output_tokens:qe(Sr),total_tokens:qe(Sr)}).check(ee((e)=>Object.values(e).some((t)=>t!==void 0))),rC=Z([IM,PM]),xc=b({clientInfo:b({name:qr,version:qr,title:Z([qr,ot])}),capabilities:Z([b({experimentalApi:W,requestAttestation:W,mcpServerOpenaiFormElicitation:k(W),optOutNotificationMethods:k(Z([j(w),ot])),extensions:k(He)}),ot])}),Jg=ke(b({userAgent:w,codexHome:w,platformFamily:w,platformOs:w,serverInfo:qe(He),capabilities:qe(He),protocolVersion:qe(w)}),Jt),Wg=b({method:T(["initialized"])}),Ac=ke(b({id:kM}),Jt),Ec=Z([ke(b({thread:Ac,id:qe(w)}),Jt),ke(b({id:w}),Jt)]),Hg=Ec,Kg=Ec,Gg=ke(b({threadId:jh}),Jt),Yg=ke(b({status:T(["notLoaded","notSubscribed","unsubscribed"])}),Jt),Zg=ke(b({thread:Ac}),Jt),Xg=He.check(ee((e)=>Array.isArray(e.data)&&e.threads===void 0&&be(j(Ac))(e.data)||Array.isArray(e.threads)&&e.data===void 0&&be(j(Ac))(e.threads))),Qg=He,vc=ke(b({threadId:jh}),Jt),eh=vc,th=vc,nh=He,iC=ke(b({id:jh,status:qe(w),usage:qe(rC),error:qe(Et)}),Jt),rh=He.check(ee((e)=>typeof e.threadId==="string"&&e.threadId.length>0&&(Array.isArray(e.input)&&be(j(Et))(e.input)||typeof e.prompt==="string"&&e.prompt.length>0))),ih=He.check(ee((e)=>typeof e.threadId==="string"&&e.threadId.length>0&&typeof e.expectedTurnId==="string"&&e.expectedTurnId.length>0&&Array.isArray(e.input)&&be(j(Et))(e.input))),oh=He.check(ee((e)=>e.turn!==void 0&&be(iC)(e.turn)||typeof e.turnId==="string"&&e.turnId.length>0||typeof e.id==="string"&&e.id.length>0)),ah=He.check(ee((e)=>typeof e.turnId==="string"&&e.turnId.length>0)),sh=He.check(ee((e)=>typeof e.threadId==="string"&&e.threadId.length>0&&typeof e.turnId==="string"&&e.turnId.length>0)),ch=He,lh=He.check(ee((e)=>typeof e.threadId==="string"&&e.threadId.length>0&&(e.turn!==void 0&&be(iC)(e.turn)||typeof e.turnId==="string"&&e.turnId.length>0))),uh=He,OM=ke(b({reasoningEffort:w}),Jt),AM=ke(b({id:w}),Jt),MM=ke(b({id:w,model:w,supportedReasoningEfforts:qe(j(OM)),serviceTiers:qe(j(AM)),defaultServiceTier:qe(Z([w,ot])),multiAgentVersion:qe(Z([T(["disabled","v1","v2"]),ot]))}),Jt),fh=ke(b({data:j(MM)}),Jt),dh=He,ph=He,mh=b({includeLayers:k(W),cwd:k(Z([w,ot]))}),gh=b({config:vi,origins:He,layers:Z([j(He),ot])}),hh=He,yh=He,Sh=ke(b({id:ka,method:w,params:He,category:T(["approval","dynamic_tool","elicitation","other","permissions"])}),Jt),yf=Et,Qz=ke(b({kind:T(["multi_agent","turn_completed","server_request","unknown"]),method:w,params:qe(Et),metadata:qe(He)}),Jt);NM=Z([T(["stable","experimental","disabled"]),W]),eJ=We(w,NM)});import{lstat as rJ,mkdir as iJ,readFile as DM,readdir as oJ,realpath as FM,stat as LM}from"fs/promises";import{delimiter as UM,isAbsolute as sJ,join as cJ,relative as lJ,resolve as oC}from"path";function jM(e){return v(function*(){let t=[];if(e.executablePath!==void 0)t.push(oC(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 i of n.split(UM).filter((o)=>o.length>0))for(let o of r)t.push(oC(i,o))}for(let n of t){let r=yield*me(d({try:()=>LM(n),catch:(i)=>i}),()=>!0,(i)=>e.executablePath!==void 0?p(new G("discovery_failed","The explicit Codex executable was not found.",{path:n},{cause:i})):M(void 0));if(r===void 0)continue;if(!r.isFile())continue;if(process.platform!=="win32"&&(r.mode&73)===0)continue;return yield*d({try:()=>FM(n),catch:(i)=>new G("discovery_failed","The explicit Codex executable could not be resolved.",{path:n},{cause:i})})}return yield*p(new G("discovery_failed","No Codex executable was found on the allowlisted PATH."))})}function BM(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))return p(new G("discovery_failed","The Codex version command did not expose output pipes."));return v(function*(){let[r,i,o]=yield*qM(Tn([d({try:()=>vh(n.stdout,16384),catch:(s)=>s}),d({try:()=>vh(n.stderr,16384),catch:(s)=>s}),d({try:()=>n.exited,catch:(s)=>s})],{concurrency:"unbounded"}),()=>n.kill(),"The Codex version command timed out."),a=Kn(xf(r,"Codex version output"));if(o!==0||a.length===0){let s=Si(xf(i,"Codex version diagnostics"));return yield*p(new G("discovery_failed","The Codex executable did not provide a version.",{exitCode:o,diagnostics:s}))}return a}).pipe(St((r)=>r instanceof G?r:new G("discovery_failed","The Codex version command failed.",{},{cause:r})),Xi(nt(()=>n.kill())))}function VM(e){return v(function*(){let t=yield*d({try:()=>DM(e),catch:(o)=>o}),n=yield*d({try:()=>crypto.subtle.digest("SHA-256",t),catch:(o)=>o}),r=[...new Uint8Array(n)].map((o)=>o.toString(16).padStart(2,"0")).join(""),i=pg(r);if(!i.ok)return yield*p(new G("discovery_failed","The Codex executable digest was invalid."));return i.value})}function Bh(e={}){return A(v(function*(){let t=yield*jM(e),n=yi(e.environment),r=e.versionRunner?yield*d({try:()=>e.versionRunner(t,n),catch:(i)=>i}).pipe(de(Kn)):yield*BM(t,n);if(r.length===0)return yield*p(new G("discovery_failed","The Codex version output was empty."));return{path:t,version:r,sha256:yield*VM(t)}}))}function qM(e,t,n){return e.pipe(Su($M),St((r)=>r instanceof G?r:r!==null&&typeof r==="object"&&("_tag"in r)&&r._tag==="TimeoutError"?new G("timeout",n):r),As(()=>nt(t)))}var $M=30000,pJ;var aC=L(()=>{st();De();Fe();mr();vf();pJ=b({exitCode:xt.check(ee((e)=>Number.isSafeInteger(e))),stdout:w.check(rg(1048576)),stderr:w.check(rg(1048576))})});var zM="packages/codex/generated",JM,WM,HM=4194304,Vh,KM,yJ,SJ,xJ;var sC=L(()=>{st();Fe();Ou();mr();JM=/^codex-cli \d+\.\d+\.\d+$/u,WM=/^codex-app-server-\d+\.\d+\.\d+$/u,Vh=w.check(ue(/^[a-f0-9]{64}$/u)).pipe(ao("Sha256Digest")),KM=xt.check(Qu(),nc(0),k_(HM)),yJ=b({schema_version:T(["holycodex-generated-v2"]),artifact_root:T([zM]),codex_cli_version:w.check(ue(JM)),codex_cli_digest:Vh,protocol_epoch:w.check(ue(WM)),generator:b({command:tg([T(["app-server"]),T(["generate-ts"])]),supported_surface:T(["codex app-server generators"])}),typescript_root:T(["typescript"]),files:b({count:xt.check(Qu(),nc(0)),digest:Vh})}),SJ=b({path:w.check(at(1)),size:KM,sha256:Vh}),xJ=w.pipe(Zu(lt,Pu()))});var YM;var cC=L(()=>{Fe();Lf();YM=b({owner:T(["holycodex"]),schema:w.check(ue(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u)),installId:w.check(ue(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u))})});var mo=L(()=>{mr();mr();hf();xh();qg();vf();aC();sC();cC();Lf();Pf();Pf()});function Wt(e){return Oe(V({try:()=>(dr(a0)(e),Vr(e),e),catch:()=>Error("The value is not JSON serializable.")}))}var a0;var $f=L(()=>{st();De();Fe();a0=nn});import{lstat as s0,mkdir as c0}from"fs/promises";import{homedir as l0}from"os";import{dirname as u0,join as wi,posix as uC,resolve as f0,sep as d0,win32 as fC}from"path";function Yn(e={},t=process.env){let n=l0(),r=e.paths?.codexHome??t.CODEX_HOME??wi(n,".codex"),i=Hh(r,"CODEX_HOME"),o=wi(i,p0);return{codexHome:i,stateRoot:o,activeRecord:wi(o,m0),preparingRecord:wi(o,g0),conflictedRecord:wi(o,h0),installOptions:wi(o,y0),roleRoot:wi(o,"agents"),configFile:wi(i,"config.toml")}}function Hh(e,t,n=process.platform==="win32"?"win32":"posix"){let r=jf(w.check(ee((s)=>!x0(s))),e,"invalid_path",`${t} contains invalid characters.`),i=n==="win32"?fC:uC,o=Wh(r,n);jf(w.check(ee((s)=>s.length>0&&i.isAbsolute(s))),o,"invalid_path",`${t} must be an absolute path.`);let a=i.normalize(o);return jf(w.check(ee((s)=>s!==i.dirname(s))),a,"broad_path",`${t} is too broad.`),jf(w.check(ee((s)=>!s.split(/[\\/]/u).some((c)=>c===".."))),o,"invalid_path",`${t} cannot contain traversal.`),i.resolve(a)}function jf(e,t,n,r){let i=Pe(e)(t);if(Ve(i))return i.success;throw new Ci(n,r)}function x0(e){for(let t of e){let n=t.codePointAt(0)??0;if(n<=31||n===127)return!0}return!1}function Ra(e){return v(function*(){Hh(e,"owned path"),yield*Fc(e),yield*d({try:()=>c0(e,{recursive:!0}),catch:(t)=>t}),yield*Fc(e)})}function Fc(e){return v(function*(){let t=f0(e);while(!0){if((yield*me(d({try:()=>s0(t),catch:(i)=>i}),(i)=>ze(i,"ENOENT"),()=>M(void 0)))?.isSymbolicLink())return yield*p(new Ci("path_symlink","A managed path cannot contain a symlink."));let r=u0(t);if(r===t)return;t=r}})}function Ia(e){return A(Fc(e))}function go(e){return Ia(e)}function An(e,t,n=process.platform==="win32"?"win32":"posix"){let r=n==="win32"?fC:uC,i=r.resolve(Wh(e,n)),o=r.resolve(Wh(t,n)),a=r.relative(i,o);return a.length>0&&!a.startsWith(`..${n==="win32"?"\\":d0}`)&&a!==".."&&!r.isAbsolute(a)}function Wh(e,t){if(t==="win32"&&/^\/[A-Za-z](?:\/|$)/u.test(e))return`${e[1]?.toUpperCase()??""}:${e.slice(2).replaceAll("/","\\")}`;return e}function ze(e,t){return typeof e==="object"&&e!==null&&"code"in e&&e.code===t}var p0="holycodex",m0="active.toml",g0="preparing.toml",h0="conflicted.toml",y0="install.toml",S0,Ci;var ho=L(()=>{st();De();bt();Fe();S0=mn;Ci=class Ci extends Error{code;constructor(e,t){super(t);this.name="PathBoundaryError",this.code=e}}});function Ye(e,t){let n=hn(e,t);return Ve(n)?n.success:void 0}var Vf,E0,v0,Lc,b0,Ti,_0,w0,C0,pC,Uc,qf,mC,$c,gC,Dt,Kh,T0,k0,R0,I0,P0,O0,A0,M0,N0,Bf,D0,dC,F0,zf,Pa,L0,Gh,U0,Yh,$0,hC,Zh,Xh,ki,yC,j0,SC,B0,xC;var jc=L(()=>{mo();st();bt();Fe();Vf=mi,E0=ic,v0=w.check(ue(/^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/u)),Lc=w.check(ue(/^[0-9a-f]{64}$/u)),b0=w.check(ue(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u)),Ti=w.check(ue(/^[A-Za-z0-9][A-Za-z0-9._:@/-]{0,255}$/u)),_0=w.check(ee((e)=>!Number.isNaN(Date.parse(e)))),w0=b({path:w.check(ue(/^[A-Za-z0-9][A-Za-z0-9._/-]{0,255}$/u)),digest:Lc}),C0=b({browser_use:W,computer_use:W,sites:W,coding:T([!0])}),pC=b({browser_use:k(W),computer_use:k(W),sites:k(W)}),Uc=b({profile:k(rn),tier:k(yn),optional:k(pC),officialPlugins:k(j(Ti))}),qf=Uc,mC=T(["keep","remove","replace","cancel"]),$c=b({schema_version:T([1]),profile:rn,tier:yn,capabilities:j(sg),additional_plugins:j(Ti)}),gC=b({schema_version:T([1]),profile:rn,tier:yn,capabilities:j(oc),additional_plugins:j(Ti)}),Dt=b({selected:W,status:T(["disabled","pending","healthy","missing","provider_disabled","uncertain","unavailable"]),plugin_ids:j(Ti),reason:k(w)}),Kh=b({browser_use:Dt,computer_use:Dt,frontend:Dt,security:Dt,sites:Dt}),T0=b({browser_use:k(W),computer_use:W,frontend:W,security:W,sites:k(W),coding:T([!0]),work:W}),k0=b({browser_use:k(W),computer_use:k(W),frontend:k(W),security:k(W),sites:k(W),work:k(W)}),R0=b({browser_use:k(Dt),computer_use:Dt,frontend:Dt,security:Dt,sites:k(Dt),work:Dt}),I0=b({computer_use:W,frontend:W,security:W,coding:T([!0])}),P0=b({computer_use:k(W),frontend:k(W),security:k(W)}),O0=b({computer_use:Dt,frontend:Dt,security:Dt}),A0=Z([b({status:T(["not_applicable"])}),b({status:T(["missing"])}),b({status:T(["healthy"]),path:w,installed:W})]),M0=b({manager:T(["bun","npm","pnpm"]),launcher:T(["bunx","npx","pnpm dlx"]),version:v0,executable:w,ownership:T(["user","holycodex"]),identity:k(Lc)}),N0=b({git_bash:k(A0),context7:k(M0)}),Bf=b({presence:T(["absent","present"]),digest:Lc,safe_value:k(Z([b({kind:T(["boolean"]),value:W}),b({kind:T(["marketplace"]),source_type:T(["git"]),source:T(["https://github.com/davidbasilefilho/holycodex.git"])})]))}),D0=b({plugin_id:T(["holycodex@holycodex"]),before:b({preference:Bf,marketplace:Bf}),after:b({preference:Bf,marketplace:Bf})}),dC=b({presence:T(["absent","present"]),digest:Lc,safe_value:k(b({kind:T(["boolean"]),value:W}))}),F0=b({plugin_id:Ti,before:dC,after:dC}),zf={owner:T(["holycodex"]),schema_epoch:T([mn]),install_id:b0,version:E0,digest:Lc,profile:rn,tier:yn,optional_selections:C0,explicit_optional_selections:pC,official_plugins:k(j(Ti)),capability_state:k(Kh),managed_artifacts:j(w0),installed_at:_0,status:k(T(["active"])),step:k(T(["active"])),managed_config:k(Ic),plugin_snapshot:k(j(b({plugin_id:Ti,status:T(["installed","available","missing","disabled","uncertain","unknown"])}))),plugin_config:k(D0),provider_config:k(j(F0)),owned_plugins:k(j(Ti)),tooling:k(N0)},Pa=b(zf),L0=(({profile:e,...t})=>t)(zf),Gh={...zf,optional_selections:T0,explicit_optional_selections:k0,capability_state:k(R0)},U0=(({profile:e,...t})=>t)(Gh),Yh={...zf,optional_selections:I0,explicit_optional_selections:P0,capability_state:k(O0)},$0=(({profile:e,...t})=>t)(Yh),hC=Z([b({...Gh,profile:Wn}),b({...U0,plan:Wn}),b({...L0,plan:Wn}),b({...Yh,profile:Wn}),b({...$0,plan:Wn})]),Zh=T(["preparing","conflicted"]),Xh=T(["validated","plugins_snapshotted","roles_prepared","plugins_installed","config_published","verified","conflicted"]),ki=b({...Pa.fields,status:Zh,step:Xh}),yC={...Gh,status:Zh,step:Xh},j0=(({profile:e,...t})=>t)(yC),SC={...Yh,status:Zh,step:Xh},B0=(({profile:e,...t})=>t)(SC),xC=Z([ki,b({...yC,profile:Wn}),b({...j0,plan:Wn}),b({...SC,profile:Wn}),b({...B0,plan:Wn})])});function Bc(e){let t={},n=[];for(let r of e.split(/\r?\n/u)){let i=q0(r).trim();if(i.length===0)continue;if(i.startsWith("[["))throw Error("Array-of-tables are not supported by the validated fallback.");if(i.startsWith("[")&&i.endsWith("]")){n=Qh(i.slice(1,-1).trim()),V0(t,n);continue}let o=bC(i);if(o<1)throw Error("TOML assignment is invalid.");let a=Qh(i.slice(0,o).trim()),s=Jf(i.slice(o+1).trim());vC(t,[...n,...a],s)}return t}function Vc(e){let t=[];return EC(e,[],t),t.join(`
28
+ `)}function EC(e,t,n){let r=[],i=[];for(let[o,a]of Object.entries(e))if(ry(a))i.push([o,a]);else r.push([o,a]);if(t.length>0){if(n.length>0)n.push("");n.push(`[${t.map(ty).join(".")}]`)}for(let[o,a]of r)n.push(`${ty(o)} = ${ny(a)}`);for(let[o,a]of i)EC(a,[...t,o],n)}function Jf(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?[]:ey(t,",").map((n)=>Jf(n.trim()))}if(e.startsWith("{")){if(!e.endsWith("}"))throw Error("TOML inline table is invalid.");let t=e.slice(1,-1).trim(),n={};if(t.length===0)return n;for(let r of ey(t,",")){let i=bC(r);if(i<1)throw Error("TOML inline table entry is invalid.");vC(n,Qh(r.slice(0,i).trim()),Jf(r.slice(i+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 Qh(e){let t=ey(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("'")?Jf(n):n)}function vC(e,t,n){if(t.length===0)throw Error("TOML key is missing.");let r=e;for(let o of t.slice(0,-1)){let a=r[o];if(a===void 0){let s={};r[o]=s,r=s}else if(ry(a))r=a;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 V0(e,t){let n=e;for(let r of t){let i=n[r];if(i===void 0){let o={};n[r]=o,n=o}else if(ry(i))n=i;else throw Error("TOML table conflicts with a scalar.")}}function ey(e,t){let n=[],r=0,i=0,o,a=!1;for(let s=0;s<e.length;s+=1){let c=e[s];if(o!==void 0){if(o==='"'&&a)a=!1;else if(o==='"'&&c==="\\")a=!0;else if(c===o)o=void 0;continue}if(c==='"'||c==="'")o=c;else if(c==="["||c==="{")i+=1;else if(c==="]"||c==="}")i-=1;else if(c===t&&i===0)n.push(e.slice(r,s)),r=s+1}if(o!==void 0||i!==0)throw Error("TOML value is unbalanced.");return n.push(e.slice(r)),n}function bC(e){let t,n=!1,r=0;for(let i=0;i<e.length;i+=1){let o=e[i];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==="["||o==="{")r+=1;else if(o==="]"||o==="}")r-=1;else if(o==="="&&r===0)return i}return-1}function q0(e){let t,n=!1;for(let r=0;r<e.length;r+=1){let i=e[r];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==="#")return e.slice(0,r)}return e}function ry(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function ty(e){return/^[A-Za-z0-9_-]+$/u.test(e)?e:JSON.stringify(e)}function ny(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(ny).join(", ")}]`;if(e===null)throw Error("TOML null is not serializable.");return`{ ${Object.entries(e).map(([t,n])=>`${ty(t)} = ${ny(n)}`).join(", ")} }`}import{lstat as _C,open as z0,readFile as wC,rename as J0,unlink as CC,writeFile as W0}from"fs/promises";import{dirname as H0}from"path";function TC(e){let t=Fr(d({try:()=>z0(e,"r"),catch:(n)=>n}),(n)=>d({try:()=>n.sync(),catch:(r)=>r}),(n)=>d({try:()=>n.close(),catch:(r)=>r}).pipe(me(()=>!0,()=>rt)));return me(t,PC,()=>rt)}function Z0(e){return me(TC(e),PC,()=>rt)}function kC(e,t){return ft(e,`${Vr(t)}
29
+ `)}function RC(e,t){let n=[];function r(o,a){if(o===null)return n.push(a),"";if(Array.isArray(o))return o.map((s,c)=>r(s,[...a,String(c)]));if(typeof o==="object")return Object.fromEntries(Object.entries(o).map(([s,c])=>[s,r(c,[...a,s])]));return o}let i={format_version:1,null_paths:n,record:r(t,[])};return IC(e,Vc(i))}function zc(e,t){return A(RC(e,t))}function X0(e,t){return v(function*(){let n=yield*qc(e);if(n===void 0){let r=e.replace(/\.toml$/u,".json");return yield*nN(r,t)}return eN(n,t)})}function iy(e,t){return A(X0(e,t))}function Q0(e,t){return v(function*(){if((yield*qc(e))!==void 0)return;let n=e.replace(/\.toml$/u,".json"),r=yield*qc(n);if(r===void 0)return;if(yield*RC(e,t),(yield*qc(n))!==r)return yield*p(new xr("state_corrupt","Legacy state changed during migration."));yield*d({try:()=>CC(n),catch:(o)=>o})})}function Jc(e,t){return A(Q0(e,t))}function eN(e,t){let n=Oe(V({try:()=>{if(e.trimStart().startsWith("{"))return JSON.parse(e);let i=Ye(Y0,Bc(e));if(i===void 0)throw Error("Invalid state document");let o=i.record;for(let a of i.null_paths){let s=o;for(let f of a.slice(0,-1)){if(typeof s!=="object"||s===null||!Object.hasOwn(s,f))throw Error("Invalid null path");s=s[f]}let c=a.at(-1);if(c===void 0||typeof s!=="object"||s===null||!Object.hasOwn(s,c)||s[c]!=="")throw Error("Invalid null placeholder");s[c]=null}return o},catch:(i)=>new xr("state_corrupt","A persisted state file is not valid TOML.",i)})),r=Ye(t,n);if(r===void 0)throw new xr("state_corrupt","A persisted file failed schema validation.");return r}function IC(e,t){let n=H0(e),r=`${e}.tmp-${process.pid}-${crypto.randomUUID()}`;return v(function*(){yield*Ra(n),yield*Fc(e),yield*d({try:()=>W0(r,t,{encoding:"utf8",mode:384}),catch:(o)=>o}),yield*TC(r),yield*d({try:()=>J0(r,e),catch:(o)=>o}),yield*Z0(n)}).pipe(me(()=>!0,(o)=>Re(d({try:()=>CC(r),catch:()=>{return}}),()=>p(o))))}function ft(e,t){return A(IC(e,t))}function tN(e,t){return A(v(function*(){let n=yield*d({try:()=>_C(e),catch:(a)=>a});if(!n.isFile()||n.isSymbolicLink())return yield*p(new xr("state_corrupt","A persisted file is not a regular file."));let r=yield*d({try:()=>wC(e,"utf8"),catch:(a)=>a}),i=yield*V({try:()=>JSON.parse(r),catch:(a)=>new xr("state_corrupt","A persisted file is not valid JSON.",a)}),o=Ye(t,i);if(o===void 0)return yield*p(new xr("state_corrupt","A persisted file failed schema validation."));return o}))}function qc(e){return v(function*(){let t=yield*me(d({try:()=>_C(e),catch:(n)=>n}),(n)=>ze(n,"ENOENT"),()=>M(void 0));if(t===void 0)return;if(!t.isFile()||t.isSymbolicLink())return yield*p(new xr("state_corrupt","A persisted file is not a regular file."));return yield*d({try:()=>wC(e,"utf8"),catch:(n)=>n})})}function Ee(e){return A(qc(e))}function nN(e,t){return me(d({try:()=>tN(e,t),catch:(n)=>n}),(n)=>ze(n,"ENOENT"),()=>M(void 0))}function PC(e){if(typeof e==="object"&&e!==null&&"code"in e&&typeof e.code==="string")return K0.has(e.code)||process.platform==="win32"&&e.code==="EPERM";return!1}var K0,G0,Y0,xr;var Oa=L(()=>{st();De();Fe();ho();jc();K0=new Set(["EBADF","EINVAL","ENOSYS","ENOTSUP","EISDIR"]),G0=j(w.check(ee((e)=>!["__proto__","constructor","prototype"].includes(e)))).check(at(1)),Y0=b({format_version:T([1]),null_paths:j(G0),record:lt});xr=class xr extends Error{code;causeValue;constructor(e,t,n){super(t);this.name="StorageError",this.code=e,this.causeValue=n}}});import{readFile as rN}from"fs/promises";import{dirname as iN,resolve as oN}from"path";import{fileURLToPath as aN}from"url";function OC(e=Mn){return v(function*(){let t=yield*d({try:()=>rN(e,"utf8"),catch:(n)=>n});return yield*V({try:()=>dr(tf(sN))(t),catch:()=>new Ri("manifest_invalid","The public package manifest is invalid.")})})}function oy(e=Mn){return A(Wf(e))}function Wf(e=Mn){return de(OC(e),(t)=>t.version)}function cN(e=Mn){return A(AC(e))}function AC(e=Mn){return Re(Wf(e),(t)=>be(ga)(t)?M(t):p(new Ri("manifest_invalid","The public package manifest must use a canonical stable release version.")))}function lN(e=Mn){return A(uN(e))}function uN(e=Mn){return Re(Wf(e),(t)=>{let n=t.split("-",1)[0];return be(og)(n)?M(n):p(new Ri("manifest_invalid","The public package manifest must use a canonical release base version."))})}function ay(e=Mn){return A(sy(e))}function sy(e=Mn){return Wf(e)}function cy(e,t,n=Mn){return A(fN(e,t,n))}function fN(e,t,n=Mn){return v(function*(){let r=yield*OC(n),i=yield*AC(n),o=yield*dN(e,i);if(!t)yield*d({try:()=>kC(n,{...r,version:o}),catch:(a)=>a});return{previous:i,next:o}})}function dN(e,t){if(e!=="patch"&&e!=="minor")return be(ga)(e)?M(e):p(new Ri("version_invalid","The version target is invalid."));return V({try:()=>ag(e,t),catch:(n)=>new Ri("version_invalid",n instanceof Error?n.message:"The current version is invalid.")})}var sN,Mn,Ri;var Wc=L(()=>{st();De();Fe();Oa();sN=ke(b({name:T(["holycodex"]),version:ic}),[We(w,nn)]),Mn=oN(iN(aN(import.meta.url)),"../package.json");Ri=class Ri extends Error{code;constructor(e,t){super(t);this.name="ManifestError",this.code=e}}});import{createHash as pN}from"crypto";import{lstat as ly,readFile as uy,rm as fy,rmdir as mN}from"fs/promises";import{dirname as MC,join as dt,relative as NC}from"path";function Hf(e,t,n=[],r="standard",i={}){return A(EN(e,t,n,r,i))}function EN(e,t,n,r,i){return v(function*(){let o=yo(t,r,i),a=dt(e,"holycodex","agents",o),s=Hr(t,r).map((l)=>({path:dt(a,`${l.name}.toml`),contents:Aa(l,i)})),c=new Map(n.map((l)=>[dt(e,l.path),l])),f=[];for(let l of s){let u=yield*d({try:()=>Ii(l.path),catch:(y)=>y}),g=c.get(l.path),h=u===void 0?void 0:yield*qC(l,u,g);if(h!==void 0)f.push(h)}return f})}function FC(e,t){return A(vN(e,t))}function vN(e,t){return v(function*(){let n=dt(e,"agents"),r=dt(e,"holycodex","agents"),i=[];for(let o of t){let a=dt(e,o.path);if(!An(e,a)||!An(n,a)&&!An(r,a)&&a!==dt(e,"config.toml"))continue;let s=yield*d({try:()=>Ii(a),catch:(c)=>c});if(s!==void 0&&(yield*d({try:()=>bn(s),catch:(c)=>c}))!==o.digest){let c=yield*d({try:()=>bn(s),catch:(f)=>f});i.push({...VC(a,"remove",{present:!0,digest:c},{present:!1},"The managed native artifact changed outside HolyCodex and would be removed."),action:"remove"})}}return i})}function LC(e,t){return A(bN(e,t))}function bN(e,t){return v(function*(){let n=dt(e,"agents"),r=dt(e,"holycodex","agents"),i=[];for(let[o,a]of t){if(!An(e,o)||!An(n,o)&&!An(r,o)){i.push(o);continue}let s=yield*d({try:()=>Ii(o),catch:(c)=>c});if(s!==void 0&&(yield*d({try:()=>bn(s),catch:(c)=>c}))!==a)i.push(o)}return i})}function Hr(e,t="standard"){let n=va(e);if(!n.ok)return[];return n.value.routes.map((r)=>{let i={role:r.role,task:r.task};return{name:Sg(i),description:Eg(i),taskInstruction:xg(i),permissions:vg(i),model:r.model,effort:r.effort,serviceTier:t==="standard"?"default":"fast"}})}function yo(e,t="standard",n={}){let r=Hr(e,t).map((i)=>`${i.name}\x00${Aa(i,n)}`).join("\x00");return pN("sha256").update(r).digest("hex").slice(0,20)}function Hc(e,t){if(!/^[a-f0-9]{20}$/u.test(t))throw Error("Invalid native-agent generation identifier.");return`holycodex/agents/${t}/${e}.toml`}function dy(e,t="standard"){let n=va(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 py(e=!1){let t=typeof e==="boolean"?{computerUse:e,frontend:!0,security:!0}:e;if(!B.requiresDelegation||!B.assignmentStartAndDispatchPrecedeDelegableExecution||!B.trivialWorkRequiresDelegation||!B.preparatoryAndExploratoryWorkRequiresDelegation||B.genericDirectWorkFallback||B.directExecutionExceptions!==B.rootOwnedAuthority||!B.codeReviewRequiredForImplementation||!B.codeReviewRequiredBeforeVcs||!B.externalVerificationMustBeTerminal||!B.concreteSpecialistDispatchRequired||!B.roleFamiliesAreLabelsOnly||!B.missingConcreteRouteIsBlocker||!B.normalSpawnRequiresExplicitForkTurns||B.normalSpawnForkTurns!=="none"||!B.normalSpawnUsesConcreteRegisteredAgentType||!B.assignmentContextIsTaskSpecificOnly||!B.configuredRouteModelAndEffortPreserved||B.normalProgressMessages||B.normalHeartbeatMessages||B.normalIntermediateEvidence||!B.userUpdatesUsefulOrImportantOnly||!B.routinePerToolOrSubagentNarrationForbidden||!B.routineStatusOnlyChatterForbidden||!B.fixedCadenceUserUpdatesForbidden||!B.materialUserUpdateKinds.includes("significant_findings_or_decisions")||!B.materialUserUpdateKinds.includes("consequential_blockers_or_input_needs")||!B.materialUserUpdateKinds.includes("release_milestones")||!B.outOfBoundaryRequiresNewAssignment||!B.busyPollingForbidden||!B.statusOnlyCoordinationLoopsForbidden||!B.batchIndependentLifecycleActions||!B.releaseLeavesAfterAcceptedOutcome||B.rootWaitTool!=="collaboration.wait_agent"||B.rootWaitTimeoutMs!==600000||!B.rootWaitRequiresExactTimeout||!B.earlySpecialistCompletionWakesWait||!B.collectiveMailboxIncludesRelevantAgents||!B.idleRootWaitRepeatsRequiredTimeout||!B.shortRootWaitsForbidden||!B.reportDrivenSpecialistCoordination||!B.runningSpecialistMessagesForbidden||!B.runningSpecialistInspectionForbidden||!B.runningSpecialistFollowupForbidden||!B.followupRequiresTerminalReport||!B.rootSleepForSpecialistCoordinationForbidden||!B.pollingAndStatusLoopsForbidden||!B.warmSpecialistReusePreferred||!B.warmReuseRequiresContextAndOwnershipFit||!B.independentAssignmentsDispatchedBeforeWait||!B.rootDecisionBoundariesMinimized||!B.evidenceFirstConciseStructuredReports||B.specialistReportFields.length===0||B.rootLargeReadsOnlyFor.length===0||!B.stableFactsReused||!B.duplicatePolicyForbidden||!B.stableBoundedComponentScopesAreCanonical||!B.lifecycleWorkerOwnsDeterministicApi||B.registeredSpecialistAgentTypes!==Br||B.forbiddenGenericAgentTypes!==uf)throw Error("The Root orchestration policy is incomplete.");let n=[`You are the HolyCodex Root/session orchestrator. Never perform delegable work yourself unless the user explicitly requests direct execution or forbids delegation. Root owns ${B.rootOwnedAuthority.map((r)=>hN[r]).join("; ")}, within authorization and capability boundaries.`,`Delegate ${B.delegableActions.filter((r)=>(r!=="browser_use"||t.browserUse)&&(r!=="computer_use"||t.computerUse)).map((r)=>yN[r]).join("; ")} through bounded Assignments. Bundle related trivial and preparatory steps into a coherent Assignment rather than spawning per action.`,B.routeConfigurationBeforeDispatch,B.assignmentInvocationLifecycle,`For normal specialist spawns, set fork_turns: "${B.normalSpawnForkTurns}". Give each specialist a self-contained Assignment with objective, bounded scope, constraints, dependencies, acceptance criteria, and evidence needed for acceptance.`,`Dispatch each Assignment to its exact concrete registered Role.task agent_type. Registered targets: ${B.registeredSpecialistAgentTypes.join(", ")}. Explorer, Librarian, Worker, and Reviewer are labels only; generic built-in agent_type values ${B.forbiddenGenericAgentTypes.join(", ")} are forbidden.`,B.semanticStateBoundary,"User instructions take precedence over skill guidelines. Treat later user steering as current when it changes scope, ownership, or delegation; do not carry forward earlier conflicting constraints. Infer intent from the request and session; carry authorized work through its requested terminal state. Routine omissions get safe defaults. Root routes every user-facing question or doubt through the supported input tools, never prose. Prefer request_user_input_async for clarifications and approvals; use request_user_input only when async would harm the situation or cause unnecessary work, and only when the synchronous tool contract permits that question. Never use a tool for permission requests when its contract forbids them. Invoke grill-me only when uncertainty about intent, implementation, or findings requires the user's project decision; when the request is clear enough, proceed without asking. Ask only what remains unresolved, never turn clarification into planning. While a question is pending, do only work independent of its answer; never do dependent or speculative work that must be redone after the answer. Required answers remain pending until an actual response; elapsed time is not an answer or approval. Specialists return material input needs to Root as needs_root_input and never ask the user. Dispatch immediately when no decision blocks the next step, and continue independent work while an answer is pending. Check existing authorization before asking again; prepare the concrete reviewable result before requesting approval for a consequential effect. Credential entry remains user-owned.","Dispatch independent non-conflicting Assignments concurrently as soon as their inputs are ready, including across workflow phases. Give each overlapping write or shared-mutable seam one specialist owner and send follow-ups to that owner instead of spawning competing writers; start dependent review or validation once its source is stable. Reuse accepted findings instead of repeating discovery. Batch independent tool reads and lifecycle work where supported; keep revisions and dependent writes ordered. Resolve material contradictions before acceptance.","For visual tasks, Root uses visual-loop: Worker.visual implementation, Reviewer.visual independent review, then Root independent visual pass; use dev-server when a shared background server is needed. Honor active-surface tool precedence. Report a capability blocker without inventing a provider or widening authority.",UC(t),Sn.designJudgment,"Use writing-instructions for model-facing contracts. Keep each meaning with one authoritative owner and add only the missing semantic delta for the receiver.","Give the user useful updates for significant findings, decisions, blockers, input needs, and release milestones; avoid per-tool, status-only, heartbeat, or fixed-cadence messages.",xN,B.specialistCoordinationInstruction,`${cc.rule} ${SN}`,"After integration, Root owns approved VCS writes. For PR or release gates use babysit-ci and dispatch Worker.operations for exact-ref terminal evidence. Pending gates are not complete."];if(t.frontend??!0)n.push(_N());if(t.security??!0)n.push("For security-sensitive changes, use the relevant security review skills before VCS. Validate supported findings; repair introduced or worsened vulnerabilities before VCS unless explicitly risk-accepted. Keep security review current after relevant repairs.");return n.join(`
30
+ `)}function UC(e,t="Root"){let n=e.browserUse?`Inspect and interact with rendered visual work using Browser Use / the in-app browser (IAB). ${e.computerUse?"Use Computer Use when Browser Use cannot perform the required interaction. ":""}Use other available rendered evidence for remaining inspection gaps.`:e.computerUse?"Inspect and interact with rendered visual work using Computer Use, then other available rendered evidence for remaining inspection gaps.":"Inspect rendered visual work using other available rendered evidence such as screenshots or image tools.",r=e.browserUse?`For web-visualize, open and inspect the standalone temporary HTML with Browser Use / IAB.${e.computerUse?" Use Computer Use for HTML interactions Browser Use cannot perform.":""}`:e.computerUse?"For web-visualize, open and inspect the standalone temporary HTML with Computer Use.":"For web-visualize, give the standalone temporary HTML file to the user.";return`For ${t==="Root"?"Root visual judgment":"visual implementation and review"}, ${n} ${r} Honor higher-priority active-surface tool rules.`}function _N(){if(!Sn.repositoryAndUserRequirementsPrecedePluginDefaults||!Sn.specialistsOwnImplementationAndInteractionProof||Sn.specialistVisualImplementationInstruction.length===0||!Sn.rootOwnsVisualJudgment||!Sn.rootOwnsSharedDevServer||!Sn.rootAcceptsTerminalVisualEvidence||!Sn.sourceChangesInvalidateRenderEvidence||!Sn.specialistReportsIncludeObservableRenderedEvidence||Sn.logicOnlyChangesRequireVisualAcceptance)throw Error("The Frontend workflow policy is incomplete.");return`${$C()} Follow the repository stack, design system, and user requirements. ${Sn.specialistVisualImplementationInstruction} Refresh affected visual evidence after relevant changes. Logic-only changes do not require a visual loop. Check responsive layout, accessibility, and interactions in proportion to the change.`}function $C(){return`Use Build Web Apps for applicable web-app construction and Frontend App Builder for applicable frontend work. For frontend work, ${jr.frontend.applicability.map(({skillId:t,appliesWhen:n})=>`${n} uses ${t}`).join("; ")}.`}function my(e,t,n=[],r="standard",i,o=[],a={}){let s=[],c=v(function*(){let f=yo(t,r,a),l=dt(e,"holycodex","agents",f),u=[],g=Hr(t,r).map((C)=>({path:dt(l,`${C.name}.toml`),contents:Aa(C,a)})),h=new Map(n.map((C)=>[dt(e,C.path),C])),y=new Map,S=new Set,m=new Set,x=new Map;for(let C of g){let N=yield*d({try:()=>Ii(C.path),catch:(K)=>K});y.set(C.path,N);let D=o.find((K)=>K.path===C.path&&K.action==="replace"&&K.key===void 0);if(D!==void 0){let K=DC(D);if(K===void 0||N===void 0||(yield*d({try:()=>bn(N),catch:(O)=>O}))!==K)return yield*p(Error(`The native role conflict changed after review; review the latest file and retry: ${C.path}`));if(x.set(C.path,K),D.decision==="keep")m.add(C.path);else S.add(C.path)}let F=h.get(C.path);if(N!==void 0&&D===void 0){let K=yield*qC(C,N,F);if(K!==void 0){let O=i===void 0?void 0:yield*i(K);if(O==="cancel")return yield*p(Error(`Native-agent conflict resolution was cancelled: ${C.path}`));if(O===void 0)m.add(C.path);else{let ce=DC(K),oe=yield*d({try:()=>Ii(C.path),catch:(I)=>I});if(ce===void 0||oe===void 0||(yield*d({try:()=>bn(oe),catch:(I)=>I}))!==ce)return yield*p(Error(`The native role conflict changed after review; review the latest file and retry: ${C.path}`));if(x.set(C.path,ce),O==="accept")S.add(C.path);else m.add(C.path)}}}}let E=[],_=yield*Le(v(function*(){for(let F of g){let K=y.get(F.path),O=h.get(F.path),ce=x.get(F.path);if(ce!==void 0){let oe=yield*d({try:()=>Ii(F.path),catch:(I)=>I});if(oe===void 0||(yield*d({try:()=>bn(oe),catch:(I)=>I}))!==ce)return yield*p(Error(`The native role conflict changed after review; review the latest file and retry: ${F.path}`))}if(m.has(F.path)){if(u.push(F.path),O!==void 0)E.push(O);continue}if(K!==void 0&&O!==void 0){if((yield*d({try:()=>bn(K),catch:(I)=>I}))!==O.digest&&K!==F.contents&&!S.has(F.path)){u.push(F.path),E.push({path:NC(e,F.path).replaceAll("\\","/"),digest:O.digest});continue}}if(K===void 0||K!==F.contents)yield*d({try:()=>ft(F.path,F.contents),catch:(oe)=>oe}),s.push({path:F.path,previous:K,installedDigest:yield*d({try:()=>bn(F.contents),catch:(oe)=>oe})});E.push({path:NC(e,F.path).replaceAll("\\","/"),digest:yield*d({try:()=>bn(F.contents),catch:(oe)=>oe})})}let C=dt(e,"agents","root.toml"),N=yield*d({try:()=>Ii(C),catch:(F)=>F}),D=yield*d({try:()=>BC(C),catch:(F)=>F});if(D==="preserved")u.push(C);if(D==="removed"&&N!==void 0)s.push({path:C,previous:N,installedDigest:void 0});for(let F of n){let K=dt(e,F.path);if(!g.some((O)=>O.path===K))E.push(F)}return{managed_artifacts:E,preserved:u,rollback:s}}));if(_._tag==="Failure")return yield*d({try:()=>Kf(s),catch:()=>{return}}),yield*p(_.failure);return _.success});return A(c)}function Kf(e){return A(wN(e))}function wN(e){return v(function*(){let t=[],n=[];for(let r of[...e].reverse()){let i=yield*d({try:()=>Ii(r.path),catch:(a)=>a});if(!(r.installedDigest===void 0?i===void 0:i!==void 0&&(yield*d({try:()=>bn(i),catch:(a)=>a}))===r.installedDigest)){n.push(r.path);continue}if(r.previous===void 0)yield*me(d({try:()=>fy(r.path,{force:!1}),catch:(a)=>a}),(a)=>ze(a,"ENOENT"),()=>rt),t.push(r.path);else yield*d({try:()=>ft(r.path,r.previous),catch:(a)=>a})}return{removed:t,preserved:n}})}function Gf(e,t,n=new Map){return A(CN(e,t,n))}function CN(e,t,n){return v(function*(){let r=[],i=[],o=dt(e,"agents"),a=dt(e,"holycodex","agents");for(let l of t){let u=dt(e,l.path);if(!An(e,u)||!An(o,u)&&!An(a,u)&&u!==dt(e,"config.toml")){i.push(u);continue}let g=yield*Le(v(function*(){yield*d({try:()=>Ia(u),catch:(x)=>x});let h=yield*d({try:()=>ly(u),catch:(x)=>x});if(h.isSymbolicLink()||!h.isFile())return"preserved";let y=yield*d({try:()=>uy(u),catch:(x)=>x}),S=yield*d({try:()=>bn(y),catch:(x)=>x}),m=n.get(u);if(S!==l.digest&&S!==m)return"preserved";return yield*d({try:()=>fy(u,{force:!1}),catch:(x)=>x}),"removed"}));if(g._tag==="Success")if(g.success==="removed")r.push(u);else i.push(u);else if(!ze(g.failure,"ENOENT"))i.push(u)}let s=dt(e,"agents","root.toml"),c=yield*d({try:()=>BC(s),catch:(l)=>l});if(c==="removed")r.push(s);if(c==="preserved")i.push(s);let f=r.slice();for(let l of f){let u=MC(l);while(u!==a&&An(a,u)){let g=yield*Le(v(function*(){yield*d({try:()=>Ia(u),catch:(h)=>h}),yield*d({try:()=>mN(u),catch:(h)=>h})}));if(g._tag==="Failure"){if(!ze(g.failure,"ENOENT"))break}else r.push(u);u=MC(u)}}return{removed:r,preserved:i}})}function Aa(e,t={}){let n=[gN,e.taskInstruction,...e.name==="Worker.visual"||e.name==="Reviewer.visual"?[UC(t,"specialist"),...t.frontend??!0?[$C()]:[]]:[],...e.permissions.sourceMutation?[`Patch quality: ${lf}`]:[],...t.browserUse?["Use Browser Use only for this Assignment, following active-surface tool rules. Return tool failures that prevent required evidence as a blocker. Tool availability does not grant authority, and consequential external effects remain Root-owned."]:[],...t.computerUse?["Use Computer Use only for this Assignment, following active-surface tool rules and platform restrictions. External actions require explicit task authority. Return tool failures that prevent required evidence as a blocker. Tool availability does not grant authority. Credential entry and submission remain user-owned; never request, enter, retrieve, expose, or store credentials."]:[]].join(`
31
+ `);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"',`developer_instructions = ${JSON.stringify(n)}`,"","[agents]","enabled = false","interrupt_message = false","","[features]","multi_agent = false","multi_agent_v2 = false","agent_message_board = false","[features.context_management]","experimental_mode = true",""].join(`
32
+ `)}function jC(e,t){return t.sandbox_mode===void 0&&t.approval_policy===void 0&&t.approvals_reviewer===void 0&&t.web_search===void 0&&t.default_permissions===void 0&&pe(t,"sandbox_workspace_write.network_access")===void 0}function TN(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(`
33
+ `)}function Ma(e){return kN.has(e)}function BC(e){return A(me(v(function*(){yield*d({try:()=>Ia(e),catch:(r)=>r});let t=yield*d({try:()=>ly(e),catch:(r)=>r});if(!t.isFile()||t.isSymbolicLink())return"preserved";let n=yield*d({try:()=>uy(e,"utf8"),catch:(r)=>r});if(!Ma(n))return"preserved";return yield*d({try:()=>fy(e,{force:!1}),catch:(r)=>r}),"removed"}),(t)=>ze(t,"ENOENT"),()=>M("absent")))}function Ii(e){return A(me(v(function*(){yield*d({try:()=>Ia(e),catch:(r)=>r});let t=yield*d({try:()=>ly(e),catch:(r)=>r});if(t.isSymbolicLink()||!t.isFile())return yield*p(Error(`Invalid managed path: ${e}`));let n=yield*d({try:()=>uy(e),catch:(r)=>r});return yield*V({try:()=>new TextDecoder("utf-8",{fatal:!0}).decode(n),catch:(r)=>r})}),(t)=>ze(t,"ENOENT"),()=>M(void 0)))}function bn(e){let t=typeof e==="string"?new TextEncoder().encode(e):e;return A(de(d({try:()=>crypto.subtle.digest("SHA-256",t),catch:(n)=>n}),(n)=>Array.from(new Uint8Array(n),(r)=>r.toString(16).padStart(2,"0")).join("")))}function VC(e,t,n,r,i){return{identity:`role-asset:${e}:${t}`,category:"role-asset",target:e,existing:n,desired:r,defaultDecision:"replace",validDecisions:["keep","replace","cancel"],explanation:i,path:e,action:t}}function qC(e,t,n){if(t===e.contents)return M(void 0);return v(function*(){let r=yield*d({try:()=>bn(t),catch:(a)=>a});if(n!==void 0&&r===n.digest)return;let i=yield*d({try:()=>bn(e.contents),catch:(a)=>a});return{...VC(e.path,"replace",{present:!0,digest:r},{present:!0,digest:i},n===void 0?"A pre-existing generated native role file is not recorded as managed by this installation.":"The managed native role file changed outside the previous HolyCodex transaction."),validDecisions:["replace","cancel"]}})}function DC(e){if(typeof e.existing!=="object"||e.existing===null)return;let t=e.existing.digest;return typeof t==="string"?t:void 0}var gN,hN,yN,SN="Before acceptance or VCS writes, require a Reviewer.code fixed point and current relevant validation. Review and validation may overlap on non-conflicting scopes; serialize repairs against checks of the same source. Reuse worker proof and assign Worker.validation only for independent proof or an evidence gap. Repairs invalidate only affected evidence.",xN,kN;var Yf=L(()=>{mo();st();De();ho();Oa();gN=[_g,`Execute the bounded Assignment through its acceptance criteria; make routine in-scope choices without asking. ${cc.rule} Return material decisions, scope expansion, or required user input to Root; never ask the user. Do not message Root or peers during execution, delegate, change Intent lifecycle, or perform external effects. Read-only Git/VCS, CI, and PR-comment inspection is allowed when relevant and within the Assignment; Git/VCS writes remain Root-only. Source mutation requires permission from the concrete task; proof and cache writes do not grant it. Preserve others' work in the shared tree and adapt to their changes. Root owns the shared background dev server and final visual acceptance. Do not run dev-server or visual-loop.`,"Do not recover an Assignment or mutate another Assignment's lifecycle. Root keeps active invocation capabilities and records terminal results; never request or use those capabilities.",`Return only one compact, evidence-first terminal outcome (${B.specialistOutcomes.map((e)=>`\`${e}\``).join(", ")}) with ${B.specialistReportFields.join(", ")}.`].join(" "),hN={user_interaction:"user interaction",intent:"Intent",material_decisions:"material decisions",orchestration_lifecycle:"orchestration and lifecycle",integration_acceptance:"integration acceptance",completion:"completion",git_vcs:"Git/VCS writes",external_effects:"external effects",visual_judgment:"visual judgment and its browser inspection",dev_server:"the shared background dev server"},yN={repository_discovery:"repository discovery",file_source_test_doc_inspection:"file, source, test, and documentation inspection",fact_finding:"fact finding",research:"research",implementation:"implementation",debugging:"debugging",testing:"testing",validation:"validation",frontend_work:"frontend work",security_work:"security work",browser_use:"authorized Browser Use",computer_use:"authorized Computer Use",review:"review",ci_release_observation:"CI or release observation"},xN=`Always call ${B.rootWaitTool} with timeout_ms=${B.rootWaitTimeoutMs} for every Root wait. Never use a 10-second timeout or any other duration, regardless of the situation. Specialist completion wakes the call early. On timeout, use ${B.rootWaitTimeoutMs} again while any specialist result remains a live dependency; continue independent work between waits. Do not busy-poll or create unnecessary work to avoid waiting. Batch specialist completion updates rather than reporting each completion separately. Continue useful independent work while live dependencies remain. Release specialist leaves after accepting terminal outcomes.`;kN=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)=>TN(e,t,n))))});import{access as RN,readFile as IN,readdir as PN}from"fs/promises";import{join as gy}from"path";class Er{adapter;observedIdentities={};constructor(e){if("run"in e){let t=Rf({executable:"codex",runner:e});this.adapter=t}else this.adapter=e}static discover(e=process.env){return A(Er.discoverEffect(e))}static discoverEffect(e=process.env){return de(d({try:()=>Bh({environment:e}),catch:(t)=>t}),(t)=>{let n=Rf({executable:t.path,environment:Eh(e),onMarketplaceConflict:(r)=>{console.warn(`HolyCodex warning: ${r}`)},...e.CODEX_HOME===void 0?{}:{codexHome:e.CODEX_HOME}});return new Er(n)})}list(){return A(this.listEffect())}listEffect(){return d({try:()=>this.adapter.list(),catch:(e)=>Na("list",e)})}add(e){return A(this.addEffect(e))}addEffect(e){return d({try:()=>this.adapter.add(e),catch:(t)=>Na("add",t,e)})}ensureOfficialMarketplace(e){return A(this.ensureOfficialMarketplaceEffect(e))}ensureOfficialMarketplaceEffect(e){let t=this.adapter.ensureOfficialMarketplace;if(t===void 0)return rt;return d({try:()=>t(e),catch:(n)=>Na("bootstrap",n)})}remove(e){return A(this.removeEffect(e))}removeEffect(e){return d({try:()=>this.adapter.remove(e),catch:(t)=>Na("remove",t,e)})}addMarketplace(e){return A(this.addMarketplaceEffect(e))}addMarketplaceEffect(e){return d({try:()=>this.adapter.addMarketplace(e),catch:(t)=>Na("add",t,e)})}status(e){return A(this.statusEffect(e))}statusEffect(e){let t=this.adapter,n=v(function*(){let r=yield*d({try:()=>t.list(),catch:(s)=>Na("list",s)}),i={},o=new Map;for(let s of[...r.installed,...r.available])if(!o.has(s.pluginId)||s.installed)o.set(s.pluginId,s);let a=yield*Tn(e.map((s)=>nt(()=>{let c=hr(r,s),f=Pn(s),l=o.get(s),u=c?.entry??(f===void 0||l?.marketplaceName==null?l:void 0);if(u!==void 0)i[s]=c?.entry.pluginId??u.pluginId;let g=u===void 0?"missing":u.installed&&u.enabled?"installed":u.installed?"disabled":"missing";return[s,g]})));return{observed:i,statuses:Object.fromEntries(a)}});return de(n,({observed:r,statuses:i})=>(this.observedIdentities=Object.freeze(r),i))}getObservedIdentities(){return this.observedIdentities}}class Zf{codexHome;observedIdentities={};constructor(e){this.codexHome=e}status(e){return A(this.statusEffect(e))}statusEffect(e){let t=this.codexHome,n=v(function*(){let r=yield*me(d({try:()=>IN(gy(t,"config.toml"),"utf8"),catch:(h)=>h}),hy,()=>M(void 0));if(r===void 0)return{identities:{},statuses:Object.fromEntries(e.map((h)=>[h,"missing"]))};let i=globalThis.Bun;if(i?.TOML?.parse===void 0)return yield*p(Error("A TOML parser is unavailable."));let o=i.TOML,a=yield*V({try:()=>o.parse(r),catch:(h)=>h}),s=yield*V({try:()=>dr(vi)(a),catch:()=>Error("Codex configuration is invalid.")}),c=We(w,lt),f=b({enabled:k(W)}),l=be(c)(s.plugins)?s.plugins:void 0,u={},g=yield*Tn(e.map((h)=>v(function*(){let y=ya(h),m=(y.length>0?y:[h]).flatMap((N)=>{if(l===void 0||!Object.hasOwn(l,N))return[];let D=l[N];return[{id:N,enabled:be(f)(D)?D.enabled:void 0}]});if(m.length===0)return[h,"missing"];let x=m.filter((N)=>N.enabled===!0),_=(yield*Tn(x.map((N)=>{let D=ya(N.id),F=[N.id,...D.filter((K)=>K!==N.id)];return de(ON(t,F),(K)=>({...N,cachedIdentity:K}))}))).find((N)=>N.cachedIdentity!==void 0),C=_?.cachedIdentity??x[0]?.id??m[0]?.id;if(C!==void 0)u[h]=C;if(_!==void 0)return[h,"installed"];if(x.length>0)return[h,"missing"];if(m.every((N)=>N.enabled===!1))return[h,"disabled"];return[h,"unknown"]})));return{identities:u,statuses:Object.fromEntries(g)}});return de(n,({identities:r,statuses:i})=>(this.observedIdentities=Object.freeze(r),i))}getObservedIdentities(){return this.observedIdentities}}function ON(e,t){return v(function*(){for(let n of t){let r=n.lastIndexOf("@");if(r<=0||r===n.length-1)continue;let i=gy(e,"plugins","cache",n.slice(r+1),n.slice(0,r)),o=yield*me(d({try:()=>PN(i,{withFileTypes:!0,encoding:"utf8"}),catch:(a)=>a}),hy,()=>M(void 0));if(o===void 0)continue;for(let a of o){if(!a.isDirectory())continue;if(yield*me(Kv(d({try:()=>RN(gy(i,a.name,".codex-plugin","plugin.json")),catch:(c)=>c}),!0),hy,()=>M(!1)))return n}}return})}function hy(e){return be(AN)(e)}function Na(e,t,n){if(t instanceof vr)return t;let i=(t instanceof se?t:void 0)?.code,o=i==="timeout"||i==="output_limit"||i==="cancelled"||i==="readback_mismatch"||i==="plugin_disabled"||i==="plugin_missing"||i==="marketplace_invalid"||i==="marketplace_timeout"||i==="marketplace_unavailable"?i:i==="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 vr(o,a,t,n===void 0?{}:{plugin_id:n})}var AN,vr;var Kc=L(()=>{mo();st();De();Fe();AN=b({code:T(["ENOENT"])});vr=class vr extends Error{code;causeValue;details;constructor(e,t,n,r={}){super(t);this.name="OfficialPluginManagerError",this.code=e,this.causeValue=n,this.details=r}}});import{execFile as MN}from"child_process";import{access as NN,readFile as DN,realpath as FN}from"fs/promises";import{posix as LN,win32 as UN}from"path";import{promisify as $N}from"util";function vo(e=process.env){return{platform:process.platform,environment:e,processPath:process.execPath,files:Fa,run:(t,n)=>A(v(function*(){let r=yield*Le(d({try:()=>jN(t,[...n],{encoding:"utf8",windowsHide:!0,env:{...process.env,...e},timeout:120000,maxBuffer:4194304}),catch:(a)=>a}));if(r._tag==="Success")return{exitCode:0,stdout:r.success.stdout,stderr:r.success.stderr};let i=Pe(VN)(r.failure),o=Ve(i)?i.success:{};return{exitCode:typeof o.code==="number"?o.code:1,stdout:o.stdout??"",stderr:o.stderr??(r.failure instanceof Error?r.failure.message:"process failed")}}))}}function xo(e){let t=Dn(e.npm_execpath??""),n=(e.npm_command??"").toLowerCase(),r=(e.npm_config_user_agent??"").toLowerCase();if(t.includes("yarn")||t.includes("corepack")||r.startsWith("yarn/"))return;if(Gc(t,"pnpm")&&n==="dlx")return{launcher:"pnpm dlx",family:"pnpm",executable:"pnpm"};if(Gc(t,"bunx")||Gc(t,"bun")&&n==="exec")return{launcher:"bunx",family:"bun",executable:"bun"};if(Gc(t,"npx")||t.endsWith("/npx-cli.js")||Gc(t,"npm")&&n==="exec"||t.endsWith("/npm-cli.js")&&n==="exec")return{launcher:"npx",family:"npm",executable:"npm"};return}function Xf(e,t,n){return A(zN(e,t,n))}function zN(e,t,n){return v(function*(){let r=yield*Sy(e);if(r!==void 0){let i=xo(e.environment)??{launcher:"bunx",family:"bun",executable:"bun"},o=n?.ownership==="holycodex"&&typeof n.identity==="string"&&(yield*el(e,n.executable,r.executable));return{manager:i.family,launcher:i.launcher,version:r.version,executable:r.executable,ownership:o?"holycodex":"user",...o?{identity:n.identity}:{}}}if(Da(e))return yield*YN(e,t,n);return yield*GN(e,t,n)})}function yy(e,t){return A(JN(e,t))}function JN(e,t){return v(function*(){let n=yield*Sy(e);if(n!==void 0){let o=xo(e.environment)??{launcher:"bunx",family:"bun",executable:"bun"},a=t?.ownership==="holycodex"&&typeof t.identity==="string"&&(yield*el(e,t.executable,n.executable));return{manager:o.family,launcher:o.launcher,version:n.version,executable:n.executable,ownership:a?"holycodex":"user",...a?{identity:t.identity}:{}}}let r=Da(e)?{launcher:"bunx",family:"bun",executable:"bun"}:xo(e.environment);if(r===void 0)throw new xe("context7_manager_unknown","No usable PATH Context7 executable or supported package manager is available.");let i=r.family==="bun"&&Da(e)?yield*Yc(e):yield*Zc(e,r);if(i===void 0)throw new xe("context7_unavailable","No usable managed Context7 executable is available.");return{manager:r.family,launcher:r.launcher,version:i.version,executable:i.executable,ownership:xy(t,r,i),identity:i.identity}})}function Sy(e){return v(function*(){let t=yield*WC(e.environment,e.platform,e.files??Fa);if(t===void 0)return;let n=yield*sn(e,t,["--version"]),r=n.exitCode===0?Eo(n.stdout):void 0;return r===void 0?void 0:{version:r,executable:t}})}function WN(e){return A(HN(e))}function HN(e){return v(function*(){if((yield*Sy(e))!==void 0)return;if(Da(e)){yield*KN(e);return}let t=xo(e.environment);if(t===void 0)throw new xe("context7_manager_unknown","HolyCodex must be launched with bunx, npx, or pnpm dlx so Context7 can use the same package manager.");let n=yield*sn(e,t.executable,t.family==="npm"?["prefix","--global"]:t.family==="pnpm"?["bin","--global"]:["pm","bin","-g"]);if(n.exitCode!==0||n.stdout.trim().length===0)throw new xe("context7_unavailable",`The ${t.family} global installation could not be inspected before managed changes.`,{stderr:n.stderr.slice(0,512)})})}function KN(e){return v(function*(){let t=e.files??Fa,n=yield*sn(e,e.processPath,["pm","bin","-g"]);if(n.exitCode!==0||n.stdout.trim().length===0){if(iD(n.stderr))return;throw new xe("context7_unavailable","Bun's managed global installation could not be located before managed changes.",{stderr:n.stderr.slice(0,512)})}let r=Ht(e.platform),i=n.stdout.trim(),o=r.join(r.dirname(i),"install","global"),a=r.join(o,"node_modules","ctx7"),s=r.join(a,"package.json"),c=r.join(i,e.platform==="win32"?"ctx7.exe":"ctx7"),f=yield*Le(v(function*(){yield*d({try:()=>t.access(i),catch:(C)=>C}),yield*d({try:()=>t.access(o),catch:(C)=>C})}));if(f._tag==="Failure")throw new xe("context7_unavailable","Bun's managed global location or project is unavailable before managed changes.",{reason:So(f.failure)});let l=yield*Le(d({try:()=>t.access(a),catch:(C)=>C}));if(l._tag==="Failure"){if(rD(l.failure))return;throw new xe("context7_unavailable","Bun's managed ctx7 package could not be inspected before managed changes.",{reason:So(l.failure)})}let u=yield*Le(d({try:()=>t.readText(s),catch:(C)=>C}));if(u._tag==="Failure")throw new xe("context7_unavailable","Bun's managed ctx7 package metadata could not be inspected before managed changes.",{reason:So(u.failure)});let g=yield*Le(vy(u.success));if(g._tag==="Failure")throw new xe("context7_unavailable","Bun's managed ctx7 package metadata is invalid before managed changes.",{reason:So(g.failure)});if(g.success.version===void 0||Eo(g.success.version)!==g.success.version)throw new xe("context7_unavailable","Bun's managed ctx7 package has no exact semver version before managed changes.");let h=HC(g.success);if(h===void 0)throw new xe("context7_unavailable","Bun's managed ctx7 package does not declare its executable before managed changes.");let y=r.resolve(a,h),S=yield*Le(v(function*(){yield*d({try:()=>t.access(y),catch:(D)=>D});let C=yield*d({try:()=>t.realpath(a),catch:(D)=>D}),N=yield*d({try:()=>t.realpath(y),catch:(D)=>D});return{canonicalPackageRoot:C,canonicalExecutable:N}}));if(S._tag==="Failure")throw new xe("context7_unavailable","Bun's managed ctx7 executable is unavailable before managed changes.",{reason:So(S.failure)});let{canonicalPackageRoot:m,canonicalExecutable:x}=S.success;if(!Xc(m,a,e.platform)||!Dn(x).startsWith(`${Dn(m)}/`))throw new xe("context7_unavailable","Bun's managed ctx7 executable is outside its package before managed changes.");let E=yield*Le(v(function*(){return yield*d({try:()=>t.access(c),catch:(C)=>C}),yield*d({try:()=>t.realpath(c),catch:(C)=>C})}));if(E._tag==="Failure")throw new xe("context7_unavailable","Bun's managed ctx7 shim is unavailable before managed changes.",{reason:So(E.failure)});let _=yield*sn(e,c,["--version"]);if(_.exitCode!==0||Eo(_.stdout)!==g.success.version)throw new xe("context7_unavailable","Bun's managed ctx7 shim does not report the package version before managed changes.",{stderr:_.stderr.slice(0,512)})})}function GN(e,t,n){return v(function*(){let r=xo(e.environment);if(r===void 0)throw new xe("context7_manager_unknown","HolyCodex must be launched with bunx, npx, or pnpm dlx so Context7 can use the same package manager.");let i=yield*Zc(e,r),o=yield*KC(e,r);if(o===void 0)throw new xe("context7_verification_failed",`${r.family} could not resolve the latest ctx7 version.`);let a=xy(n,r,i);if(t&&i?.version!==o&&a==="holycodex"){let f=r.family==="bun"?{executable:"bun",args:Qf(e,"add",Nn)}:zC(r.family),l=yield*sn(e,f.executable,f.args);if(l.exitCode!==0)throw new xe("context7_install_failed",`${r.family} could not install ${Nn}.`,{stderr:l.stderr.slice(0,512)})}else if(!t&&i===void 0)throw new xe("context7_unavailable",`${Nn} is not owned by the ${r.family} global installation.`);let s=yield*Zc(e,r);if(s===void 0)throw new xe("context7_verification_failed",`${Nn} could not be verified in the ${r.family} global installation.`);if(s.version!==o)throw new xe("context7_outdated",`The ${r.family} global ctx7 is ${s.version}; ${o} is required.`,{installed:s.version,latest:o});return{manager:r.family,launcher:r.launcher,version:s.version,executable:s.executable,ownership:a,identity:s.identity}})}function YN(e,t,n){return v(function*(){let r={launcher:"bunx",family:"bun",executable:"bun"},i=yield*Yc(e),o=yield*KC(e,r);if(o===void 0)throw new xe("context7_verification_failed","Bun could not resolve the latest ctx7 version.");let a=xy(n,r,i);if(t&&i?.version!==o&&a==="holycodex"){let f=yield*sn(e,e.processPath,Qf(e,"add",Nn));if(f.exitCode!==0)throw new xe("context7_install_failed",`Bun could not install ${Nn} in its global installation.`,{stderr:f.stderr.slice(0,512)})}else if(i===void 0)throw new xe("context7_unavailable",`${Nn} is not present in Bun's exact global installation.`);let s=yield*Yc(e);if(s===void 0)throw new xe("context7_verification_failed",`${Nn} could not be verified in Bun's exact global installation.`);if(s.version!==o)throw new xe("context7_outdated",`Bun's global ctx7 is ${s.version}; ${o} is required.`,{installed:s.version,latest:o});return{manager:"bun",launcher:"bunx",version:s.version,executable:s.executable,ownership:a,identity:s.identity}})}function Yc(e){return v(function*(){let t=e.files??Fa,n=yield*sn(e,e.processPath,["pm","bin","-g"]);if(n.exitCode!==0)return;let r=n.stdout.trim();if(r.length===0)return;let i=Ht(e.platform),o=i.join(i.dirname(r),"install","global","node_modules","ctx7"),a=yield*Le(v(function*(){let m=yield*d({try:()=>t.readText(i.join(o,"package.json")),catch:(x)=>x});return yield*vy(m)}));if(a._tag==="Failure")return;let s=a.success;if(typeof s.version!=="string"||Eo(s.version)!==s.version)return;let c=HC(s);if(c===void 0)return;let f=i.resolve(o,c),l=i.join(r,e.platform==="win32"?"ctx7.exe":"ctx7"),u=yield*Le(v(function*(){yield*d({try:()=>t.access(o),catch:(_)=>_}),yield*d({try:()=>t.access(f),catch:(_)=>_}),yield*d({try:()=>t.access(l),catch:(_)=>_});let m=yield*d({try:()=>t.realpath(o),catch:(_)=>_}),x=yield*d({try:()=>t.realpath(f),catch:(_)=>_}),E=yield*d({try:()=>t.realpath(l),catch:(_)=>_});return{canonicalPackageRoot:m,canonicalExecutable:x,canonicalShim:E}}));if(u._tag==="Failure")return;let{canonicalPackageRoot:g,canonicalExecutable:h,canonicalShim:y}=u.success;if(!Xc(g,o,e.platform)||!Dn(h).startsWith(`${Dn(g)}/`))return;let S=yield*sn(e,l,["--version"]);if(S.exitCode!==0||Eo(S.stdout)!==s.version)return;return{version:s.version,executable:l,identity:yield*JC({launcher:"bunx",family:"bun",executable:"bun"},g,h,y,s)}})}function Da(e){let t=Ht(e.platform).basename(e.processPath).toLowerCase();return t==="bun"||t==="bun.exe"}function xy(e,t,n){if(n===void 0)return"holycodex";if(e?.ownership!=="holycodex")return"user";if(e.manager!==t.family)return"user";let r=e.identity;if(!Ey(r)||r!==n.identity)return"user";return"holycodex"}function Qc(e,t){return A(ZN(e,t))}function ZN(e,t){return Da(e)?XN(e,t):QN(e,t)}function XN(e,t){return v(function*(){if(t?.ownership!=="holycodex"||t.manager!=="bun")return!1;let n=yield*Le(Yc(e));if(n._tag==="Failure")return!1;let r=n.success;if(r===void 0||r.version!==t.version||!(yield*el(e,r.executable,t.executable))||!Ey(t.identity)||r.identity!==t.identity)return!1;let i=yield*sn(e,e.processPath,Qf(e,"remove","ctx7"));if(i.exitCode!==0)throw new xe("context7_remove_failed","Bun could not remove ctx7.",{stderr:i.stderr.slice(0,512)});if((yield*Yc(e))!==void 0)throw new xe("context7_remove_failed","Bun reported success, but the recorded ctx7 installation is still present.");return!0})}function QN(e,t){return v(function*(){if(t?.ownership!=="holycodex")return!1;let n=xo(e.environment);if(n===void 0||n.family!==t.manager)return!1;let r=yield*Le(Zc(e,n));if(r._tag==="Failure"){if(r.failure instanceof xe&&r.failure.code==="context7_shadowed")return!1;throw r.failure}let i=r.success;if(i===void 0||i.version!==t.version||!(yield*el(e,i.executable,t.executable))||!Ey(t.identity)||i.identity!==t.identity)return!1;let o=n.family==="bun"?{executable:"bun",args:Qf(e,"remove","ctx7")}:eD(n.family),a=yield*sn(e,o.executable,o.args);if(a.exitCode!==0)throw new xe("context7_remove_failed",`${n.family} could not remove ctx7.`,{stderr:a.stderr.slice(0,512)});let s=yield*Le(v(function*(){if((yield*Zc(e,n))!==void 0)return yield*p(new xe("context7_remove_failed",`${n.family} reported success, but the recorded ctx7 installation is still present.`))}));if(s._tag==="Failure"){if(s.failure instanceof xe&&s.failure.code==="context7_remove_failed")throw s.failure;throw new xe("context7_remove_failed",`${n.family} removed ctx7, but its final state could not be verified.`)}return!0})}function zC(e){switch(e){case"bun":return{executable:"bun",args:["add","--global",Nn]};case"npm":return{executable:"npm",args:["install","--global",Nn]};case"pnpm":return{executable:"pnpm",args:["add","--global",Nn]}}}function Qf(e,t,n){let r=Ht(e.platform),i=r.dirname(e.processPath),o=r.isAbsolute(i)?i:e.platform==="win32"?"C:\\":"/";return[t,"--global",`--cwd=${o}`,n]}function eD(e){switch(e){case"bun":return{executable:"bun",args:["remove","--global","ctx7"]};case"npm":return{executable:"npm",args:["uninstall","--global","ctx7"]};case"pnpm":return{executable:"pnpm",args:["remove","--global","ctx7"]}}}function Zc(e,t){return v(function*(){let n=e.files??Fa,r=yield*sn(e,t.executable,t.family==="npm"?["prefix","--global"]:t.family==="pnpm"?["bin","--global"]:["pm","bin","-g"]);if(r.exitCode!==0)return;let i=r.stdout.trim();if(i.length===0)return;let o=t.family==="npm"?Ht(e.platform).join(i,"node_modules","ctx7"):t.family==="pnpm"?yield*oD(e,t):Ht(e.platform).join(Ht(e.platform).dirname(i),"install","global","node_modules","ctx7");if(o===void 0)return;let a=yield*Le(v(function*(){let E=yield*d({try:()=>n.readText(Ht(e.platform).join(o,"package.json")),catch:(_)=>_});return yield*vy(E)}));if(a._tag==="Failure")return;let s=a.success;if(typeof s.version!=="string")return;let c=typeof s.bin==="string"?s.bin:YC(s.bin)&&typeof s.bin.ctx7==="string"?s.bin.ctx7:void 0;if(c===void 0)return;let f=Ht(e.platform).resolve(o,c),l=yield*Le(v(function*(){yield*d({try:()=>n.access(f),catch:(C)=>C});let E=yield*d({try:()=>n.realpath(o),catch:(C)=>C}),_=yield*d({try:()=>n.realpath(f),catch:(C)=>C});return{canonicalPackageRoot:E,canonicalExecutable:_}}));if(l._tag==="Failure")return;let{canonicalPackageRoot:u,canonicalExecutable:g}=l.success;if(!Dn(g).startsWith(`${Dn(u)}/`))return;let h=tD(i,t.family,e.platform),y=yield*Le(v(function*(){return yield*d({try:()=>n.access(h),catch:(E)=>E}),yield*d({try:()=>n.realpath(h),catch:(E)=>E})}));if(y._tag==="Failure")return;let S=y.success,m=yield*WC(e.environment,e.platform,n);if(m!==void 0&&!Xc(yield*nD(n,m),S,e.platform))return yield*p(new xe("context7_shadowed","A different ctx7 executable shadows the managed global installation.",{resolved:m,expected:h}));let x=yield*sn(e,h,["--version"]);if(x.exitCode!==0||Eo(x.stdout)!==s.version)return;return{version:s.version,executable:h,identity:yield*JC(t,u,g,S,s)}})}function JC(e,t,n,r,i){return BN(()=>En("context7-installation",[xn({manager:e.family,package_root:Dn(t),package_executable:Dn(n),shim:Dn(r),package:i})]))}function Ey(e){return e!==void 0&&/^[0-9a-f]{64}$/u.test(e)}function WC(e,t,n){let r=e.PATH;if(r===void 0)return M(void 0);let i=t==="win32"?(e.PATHEXT??".COM;.EXE;.BAT;.CMD").split(";").filter((a)=>a.length>0).map((a)=>`ctx7${a.toLowerCase()}`):["ctx7"],o=r.split(t==="win32"?";":":").filter((a)=>a.length>0).flatMap((a)=>i.map((s)=>Ht(t).join(a,s)));return v(function*(){for(let a of o)if((yield*Le(d({try:()=>n.access(a),catch:(c)=>c})))._tag==="Success")return a;return})}function tD(e,t,n){if(n==="win32")return Ht(n).join(e,t==="bun"?"ctx7.exe":"ctx7.cmd");return t==="npm"?Ht(n).join(e,"bin","ctx7"):Ht(n).join(e,"ctx7")}function nD(e,t){return d({try:()=>e.realpath(t),catch:()=>t}).pipe(Pt((n)=>M(n)))}function Eo(e){return e.match(/\b(\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?)\b/u)?.[1]}function vy(e){return V({try:()=>{let t=Pe(qN)(JSON.parse(e));if(Ve(t))return t.success;throw t.failure},catch:(t)=>t})}function HC(e){return typeof e.bin==="string"?e.bin:e.bin?.ctx7}function So(e){if(e instanceof Error)return e.message.slice(0,512);if(typeof e==="string")return e.slice(0,512);return"unknown error"}function rD(e){return YC(e)&&e.code==="ENOENT"||/\b(?:e?noent|not found|does not exist|missing)\b/iu.test(So(e))}function iD(e){return/(?:no package\.json(?: was)? found|couldn['\u2019]?t find (?:a )?package\.json|could not find (?:a )?package\.json|package\.json (?:is )?missing)/iu.test(e)}function oD(e,t){return de(sn(e,t.executable,["root","--global"]),(n)=>{let r=n.stdout.trim();return n.exitCode===0&&r.length>0?Ht(e.platform).join(r,"ctx7"):void 0})}function KC(e,t){return de(sn(e,t.family==="bun"&&Da(e)?e.processPath:t.executable,t.family==="bun"?["pm","view","ctx7","version"]:["view","ctx7","version"]),(n)=>n.exitCode!==0?void 0:Eo(n.stdout))}function Gc(e,t){return[t,`${t}.exe`,`${t}.cmd`,`${t}.js`,`${t}.cjs`].some((n)=>e.endsWith(`/${n}`))}function Xc(e,t,n){let r=Ht(n),i=r.resolve(e),o=r.resolve(t);return n==="win32"?Dn(i)===Dn(o):i===o}function GC(e,t,n){return A(el(e,t,n))}function el(e,t,n){if(Xc(t,n,e.platform))return M(!0);let r=e.files??Fa;return Tn([d({try:()=>r.realpath(t),catch:(i)=>i}),d({try:()=>r.realpath(n),catch:(i)=>i})]).pipe(de(([i,o])=>Xc(i,o,e.platform)),Pt(()=>M(!1)))}function Ht(e){return e==="win32"?UN:LN}function Dn(e){return e.replaceAll("\\","/").toLowerCase().replace(/\/$/u,"")}function YC(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}var Nn="ctx7@latest",jN,BN=(e)=>d({try:e,catch:(t)=>t}),sn=(e,t,n)=>d({try:()=>e.run(t,n),catch:(r)=>r}),VN,qN,Fa,xe;var ed=L(()=>{st();De();bt();Fe();jN=$N(MN),VN=b({code:k(Z([xt,w])),stdout:k(w),stderr:k(w)}),qN=ke(b({version:k(w),bin:k(Z([w,We(w,w)]))}),[We(w,lt)]),Fa={access:NN,readText:(e)=>DN(e,"utf8"),realpath:FN};xe=class xe extends Error{code;details;constructor(e,t,n={}){super(t);this.code=e;this.details=n;this.name="ToolingError"}}});var sT={};ck(sT,{doctorHolyCodex:()=>XC,doctorHolyCodexEffect:()=>id,inspectRemovalConflicts:()=>cD,inspectRemovalConflictsEffect:()=>rl,removeHolyCodex:()=>QC,removeHolyCodexEffect:()=>od,upgradeHolyCodex:()=>eT,upgradeHolyCodexEffect:()=>tT});import{rm as nd,rmdir as wy}from"fs/promises";import{join as aD}from"path";function XC(e={},t=process.env){return A(id(e,t))}function id(e,t){return v(function*(){let n=Yn(e,t),r={},i=yield*z(()=>go(n.codexHome)).pipe(Re(()=>z(()=>go(n.stateRoot))),le({onFailure:(m)=>({error:m}),onSuccess:()=>({error:void 0})}));r.paths=i.error===void 0?La({state_root:n.stateRoot}):Ft(["path_symlink"],{error:Xn(i.error)});let o=yield*z(()=>Ua(n)).pipe(le({onFailure:(m)=>({error:m}),onSuccess:(m)=>({active:m})})),a="active"in o?o.active:void 0;if("error"in o)r.configuration=Ft(["state_corrupt"],{error:Xn(o.error)});let s=yield*z(()=>Kr(n.preparingRecord,a)).pipe(le({onFailure:(m)=>({error:m}),onSuccess:(m)=>({preparing:m})})),c=yield*z(()=>Kr(n.conflictedRecord,a)).pipe(le({onFailure:(m)=>({error:m}),onSuccess:(m)=>({conflicted:m})})),f="preparing"in s?s.preparing:void 0,l="conflicted"in c?c.conflicted:void 0;for(let[m,x]of[[s,n.preparingRecord],[c,n.conflictedRecord]])if("error"in m)r.transaction=Ft(["state_corrupt"],{path:x,error:Xn(m.error)});if(r.transaction?.status!=="failed"&&(f!==void 0||l!==void 0)){let m=sd(a,f,l),x=[...new Set(m.map((E)=>{if(E.relation==="stale")return"stale_transaction_state";if(E.relation==="incompatible")return"incompatible_transaction_state";return E.status==="preparing"?"incomplete_install_state":"conflicted_state"}))];r.transaction=Ft(x,{recovery:m.map((E)=>E.recovery).join(","),transactions:m.map((E)=>`${E.status}:${E.relation}:${E.install_id}:${E.digest}`).join(","),active:a===void 0?"absent":`${a.install_id}:${a.digest}`})}if(!r.configuration)if(!a)r.configuration=Ft(["configuration_missing"]);else if(yield*z(()=>sl(a)))r.configuration=La({profile:a.profile,tier:a.tier,install_id:a.install_id});else r.configuration=Ft(["configuration_changed"],{path:n.activeRecord});if(a){r.runtime_config=yield*hD(n,a),r.native_roles=yield*yD(n,a.profile,a.tier,{browserUse:a.capability_state?.browser_use.status==="healthy"&&a.capability_state.browser_use.selected,computerUse:a.capability_state?.computer_use.status==="healthy"&&a.capability_state.computer_use.selected});let m=Object.entries(a.capability_state??{}).find(([x,E])=>x!=="browser_use"&&E.selected&&E.status!=="healthy");if(m)r.capabilities=Ft(["selected_capability_not_healthy"],{capability:m[0],status:m[1].status});if(a.optional_selections.browser_use)r.browser_use={status:"unsupported",reasons:["surface_managed_by_codex_desktop"],details:{selected:!0,owner:"Codex Desktop/runtime",availability:"Available only on Codex surfaces that provide Browser Use.",cli_provisioning:"HolyCodex CLI does not install, configure, or verify Browser."}}}let u=e.runtime??vo(t),g=yield*z(()=>yy(u,a?.tooling?.context7)).pipe(le({onFailure:(m)=>({error:m}),onSuccess:(m)=>({context7:m})}));if("context7"in g)r.context7=La({manager:g.context7.manager,version:g.context7.version,executable:g.context7.executable,ownership:g.context7.ownership});else r.context7={status:"warning",reasons:["context7_unavailable"],details:{error:Xn(g.error)}};let h=yield*z(()=>Ee(`${n.codexHome}/agents/root.toml`)).pipe(le({onFailure:(m)=>({error:m}),onSuccess:(m)=>({legacyRoot:m})}));if("legacyRoot"in h){let m=h.legacyRoot;if(m!==void 0&&Ma(m)){let x=r.native_roles;r.native_roles={status:"failed",reasons:[...x?.reasons??[],"stale_legacy_root"],details:{...x?.details,path:`${n.codexHome}/agents/root.toml`}}}}else r.native_roles=Ft(["native_role_invalid"],{error:Xn(h.error)});let y=e.officialPluginManager;if(a&&y?.status){let m=[...new Set([Gt,...Sa({browser_use:a.optional_selections.browser_use,computer_use:a.optional_selections.computer_use,sites:a.optional_selections.sites},a.official_plugins),...(a.owned_plugins??[]).filter((E)=>E!==Kt)])].filter((E)=>E!==Kt),x=yield*z(()=>y.status(m)).pipe(le({onFailure:(E)=>({error:E}),onSuccess:(E)=>({status:E})}));if("status"in x){let E=x.status,_=Object.entries(E).filter(([,N])=>N!=="installed").map(([N])=>N),C=y.getObservedIdentities?.()??{};r.native_plugins=_.length===0?La({status:E,observed_identities:C}):Ft(["native_plugin_disagreement"],{missing:_,status:E,observed_identities:C})}else r.native_plugins=Ft(["native_plugin_status_failed"],{error:Xn(x.error)})}else r.native_plugins=Ft(["native_plugin_status_unavailable"],{reason:"No read-only live official plugin status source is available."});let S=Object.values(r).flatMap((m)=>m.reasons);return{healthy:Object.values(r).every((m)=>m.status!=="failed"),checks:r,reasons:[...new Set(S)]}})}function cD(e={},t=process.env){return A(rl(e,t))}function rl(e,t){return v(function*(){let n=Yn(e,t);yield*z(()=>go(n.codexHome)),yield*z(()=>go(n.stateRoot));let r=yield*z(()=>Ua(n));if(r!==void 0&&!(yield*z(()=>sl(r))))return yield*p(new R("state_corrupt","The HolyCodex ownership record has an invalid digest and cannot authorize removal.",void 0,{path:n.activeRecord}));let i=yield*z(()=>Kr(n.preparingRecord,r)),o=yield*z(()=>Kr(n.conflictedRecord,r));yield*V({try:()=>Iy(r,i,o),catch:(g)=>g});let a=aT(r,i,o);if(a===void 0)return[];let s=yield*z(()=>Ee(n.configFile)),c=yield*V({try:()=>Lt(s),catch:(g)=>g}),f=[],l=a.managed_config;if(l!==void 0){let g=yield*z(()=>Ta(c,l,{schema:l.schema,installId:l.installId}));for(let h of[...g.preservedKeys,...g.unresolvedKeys])f.push(yield*_y(n.configFile,h,c,"config-key","This managed Codex setting changed after installation."))}if(a.plugin_config!==void 0){let g=yield*z(()=>tl(c,a.plugin_config,{allowBeforeState:!0}));for(let h of g.preserved){let y=h==="preference"?'plugins."holycodex@holycodex"':"marketplaces.holycodex";f.push(yield*_y(n.configFile,y,c,"plugin-config","This HolyCodex plugin setting differs from the recorded install state."))}}let u=a.provider_config;if(u!==void 0){let g=yield*z(()=>nl(c,rd(u),new Set(Ty(a)),{allowBeforeState:!0}));for(let h of g.preserved){let y=`plugins.${JSON.stringify(h)}`;f.push(yield*_y(n.configFile,y,c,"plugin-config",`The ${h} plugin setting differs from the recorded install state.`))}}return f.push(...yield*z(()=>FC(n.codexHome,a.managed_artifacts))),[...new Map(f.map((g)=>[br(g),g])).values()]})}function QC(e={},t=process.env){return A(od(e,t))}function od(e,t){return v(function*(){let n=Yn(e,t);yield*z(()=>go(n.codexHome)),yield*z(()=>go(n.stateRoot));let r=yield*z(()=>Ua(n));if(r&&!(yield*z(()=>sl(r))))return yield*p(new R("state_corrupt","The HolyCodex ownership record has an invalid digest and cannot authorize removal.",void 0,{path:n.activeRecord}));let i=yield*z(()=>Kr(n.preparingRecord,r)),o=yield*z(()=>Kr(n.conflictedRecord,r));yield*V({try:()=>Iy(r,i,o),catch:(I)=>I});let a=aT(r,i,o);td(e,{stage:"removal",status:"started",message:"Removing HolyCodex-owned state"});let s=new Set(Ty(a)),c=[],f=[],l=[],u=!1,g=()=>(td(e,{stage:"removal",status:"completed",message:"HolyCodex removal preserved state for review"}),{removed:c,preserved:f,reasons:l});if(a===void 0)return td(e,{stage:"removal",status:"completed",message:"Nothing to remove"}),{removed:c,preserved:f,reasons:l};let h=yield*rl(e,t),y=yield*mD(e,h),S=yield*z(()=>Ee(n.configFile)),m=yield*V({try:()=>Lt(S),catch:(I)=>I}),x=h.filter((I)=>I.key!==void 0&&y.has(br(I))),E=new Map;for(let I of h){if(I.key!==void 0||!y.has(br(I)))continue;let J=iT(I);if(J!==void 0)E.set(I.path,J)}yield*gD(n,m,x,E);let _=a?.managed_config;if(_){let I=yield*z(()=>Ta(m,_,{schema:_.schema,installId:_.installId}));if(I.preservedKeys.length>0||I.unresolvedKeys.length>0){let ve=[...I.preservedKeys,...I.unresolvedKeys].map((ge)=>({path:n.configFile,key:ge,action:"remove"}));for(let ge of ve)if(y.has(br(ge)))m=vn(m,ge.key)}}if(a?.plugin_config){let I=a.plugin_config,J=yield*z(()=>tl(m,I,{allowBeforeState:!0}));if(J.preserved.length>0){let ve=J.preserved.map((ge)=>({path:n.configFile,key:ge==="preference"?'plugins."holycodex@holycodex"':"marketplaces.holycodex",action:"remove"}));for(let ge of J.preserved){let Zt=ve.find((Tt)=>Tt.key===(ge==="preference"?'plugins."holycodex@holycodex"':"marketplaces.holycodex"));if(Zt===void 0||!y.has(br(Zt)))continue;m=vn(m,ge==="preference"?'plugins."holycodex@holycodex"':"marketplaces.holycodex")}}}if(a?.provider_config){let I=a.provider_config,J=yield*z(()=>nl(m,rd(I),s,{allowBeforeState:!0}));if(J.preserved.length>0){let ve=J.preserved.map((ge)=>({path:n.configFile,key:`plugins."${ge}"`,action:"remove"}));for(let ge of J.preserved){let Zt=ve.find((Tt)=>Tt.key===`plugins."${ge}"`);if(Zt===void 0||!y.has(br(Zt)))continue;m=vn(m,`plugins."${ge}"`)}}}let C,N;if(s.size>0){if(C=e.officialPluginManager,C===void 0)C=yield*z(()=>Er.discover({...t,CODEX_HOME:n.codexHome})).pipe(Pt((J)=>p(new R("capability_denied","Native Codex plugin removal is unavailable.",J,{operation:"discover Codex",plugins:[...s].join(","),recovery:"Install or expose Codex, then retry."}))));if(C===void 0||!C.remove||!C.list)return yield*p(new R("capability_denied","Native Codex plugin removal and readback are unavailable.",void 0,{operation:"prepare plugin removal",plugins:[...s].join(",")}));let I=C;N=yield*z(()=>I.list()).pipe(Pt((J)=>p(new R("capability_denied","Codex plugin state could not be read before removing HolyCodex-owned plugins.",J,{operation:"read Codex plugin state",plugins:[...s].join(","),recovery:"Repair or expose Codex, then retry removal."}))))}let D,F=a,O=yield*v(function*(){let I=m,J=_;if(J){let ge=yield*z(()=>Ta(I,J,{schema:J.schema,installId:J.installId})),Zt=[...ge.preservedKeys,...ge.unresolvedKeys];if(Zt.filter((Xt)=>!y.has(br({path:n.configFile,key:Xt,action:"remove"}))).length>0)return f.push(n.configFile),l.push("managed_config_changed"),yield*Zn(n,a??bo()),{preserved:g()};if(I=ge.document,Zt.length>0){let Xt=new Set(Zt);J={...ge.state,managed:Object.fromEntries(Object.entries(ge.state.managed).filter(([ko])=>!Xt.has(ko)))}}else J=ge.state}if(a?.plugin_config){let ge=yield*z(()=>tl(I,a.plugin_config,{allowBeforeState:!0}));if(ge.preserved.length>0)return f.push(n.configFile),l.push("plugin_config_changed"),yield*Zn(n,a),{preserved:g()};I=ge.document}if(a?.provider_config){let ge=yield*z(()=>nl(I,rd(a.provider_config),s,{allowBeforeState:!0}));if(ge.preserved.length>0)return f.push(n.configFile),l.push("provider_config_changed"),yield*Zn(n,a),{preserved:g()};I=ge.document}let ve=pe(I,"default_permissions")==="holycodex"&&pe(I,"permissions.holycodex")===void 0;if(ve)I=vn(I,"default_permissions");if(a?.managed_config||a?.plugin_config||a?.provider_config||ve)D=J===void 0?{document:I}:{document:I,state:J};if(D!==void 0){if(Object.keys(D.document).length===0&&S===void 0)yield*ZC(n.configFile,S),yield*z(()=>nd(n.configFile,{force:!1}));else yield*ZC(n.configFile,S),yield*z(()=>ft(n.configFile,_r(D.document)));F={...a,managed_config:D.state},yield*Zn(n,F),u=!0}return{complete:!0}}).pipe(le({onFailure:(I)=>({error:I}),onSuccess:(I)=>({result:I})}));if("result"in O&&"preserved"in O.result)return O.result.preserved;if("error"in O){let I=O.error;if(I instanceof R)return yield*Zn(n,F??bo()),yield*p(I);return f.push(n.configFile),l.push("managed_config_write_failed"),yield*Zn(n,F??bo()),g()}let ce=yield*z(()=>Gf(n.codexHome,a?.managed_artifacts??[],E));if(c.push(...ce.removed),f.push(...ce.preserved),ce.preserved.length>0)return l.push("managed_artifact_changed"),yield*Zn(n,F??a??bo()),g();c.push(...yield*uD(n.roleRoot,a?.managed_artifacts??[]));for(let I of s){let J=yield*v(function*(){if(C?.list===void 0||C.remove===void 0||N===void 0)return yield*p(new R("capability_denied","Codex plugin state is unavailable for a HolyCodex-owned plugin.",void 0,{operation:"remove Codex plugin",plugin_id:I}));let ge=SD(N,I);if(ge?.entry.installed!==!0)return;let Zt=ge.entry.pluginId;yield*z(()=>C.remove(Zt));let Tt=yield*z(()=>C.list());if(N=Tt,hr(Tt,I)?.entry?.installed===!0||[...Tt.installed,...Tt.available].some((Ro)=>Ro.pluginId===I&&Ro.installed))return yield*p(new R("capability_denied",`Codex still reports ${I} after removal.`));if(D!==void 0)yield*lD(n,D.document,I);c.push(I)}).pipe(le({onFailure:(ve)=>({error:ve}),onSuccess:()=>({success:!0})}));if("error"in J){let ve=J.error;return l.push("native_plugin_remove_failed"),yield*Zn(n,F??bo()),yield*p(new R("capability_denied",`Codex native plugin removal did not converge for ${I}: ${Xn(ve)}`,ve))}}let oe=yield*z(()=>Qc(e.runtime??vo(t),a.tooling?.context7)).pipe(le({onFailure:(I)=>({error:I}),onSuccess:(I)=>({removedContext7:I})}));if("error"in oe){let I=oe.error;return l.push("context7_remove_failed"),yield*Zn(n,F??bo()),yield*p(new R("capability_denied",`Context7 removal did not converge: ${Xn(I)}`,I))}if(oe.removedContext7)c.push("ctx7");if(r){let I=yield*z(()=>nd(n.activeRecord,{force:!1})).pipe(le({onFailure:(J)=>({error:J}),onSuccess:()=>({success:!0})}));if("success"in I)c.push(n.activeRecord);else{let J=I.error;if(!ze(J,"ENOENT"))return f.push(n.activeRecord),l.push("state_remove_failed"),yield*Zn(n,a??r),g()}}if(f.length===0){let I=yield*z(()=>nd(n.installOptions,{force:!1})).pipe(le({onFailure:(J)=>({error:J}),onSuccess:()=>({success:!0})}));if("success"in I)c.push(n.installOptions);else{let J=I.error;if(!ze(J,"ENOENT"))f.push(n.installOptions),l.push("state_remove_failed"),yield*Zn(n,a??r??bo())}}if(f.length===0)for(let[I,J]of[[n.preparingRecord,i!==void 0],[n.conflictedRecord,o!==void 0||u]]){if(!J)continue;if("success"in(yield*xD(I).pipe(le({onFailure:(ge)=>({error:ge}),onSuccess:()=>({success:!0})}))))c.push(I);else f.push(I),l.push("state_remove_failed")}if(f.length===0){let I=yield*z(()=>wy(n.roleRoot)).pipe(le({onFailure:(J)=>({error:J}),onSuccess:()=>({success:!0})}));if("success"in I)c.push(n.roleRoot);else{let J=I.error;if(!ze(J,"ENOENT"))f.push(n.roleRoot),l.push("role_directory_not_empty")}}if(f.length===0){let I=yield*z(()=>wy(n.stateRoot)).pipe(le({onFailure:(J)=>({error:J}),onSuccess:()=>({success:!0})}));if("success"in I)c.push(n.stateRoot);else{let J=I.error;if(ze(J,"ENOENT"))c.push(n.stateRoot);else f.push(n.stateRoot),l.push("state_directory_not_empty")}}return td(e,{stage:"removal",status:"completed",message:f.length===0&&l.length===0?"HolyCodex removal complete":"HolyCodex removal preserved state for review"}),{removed:c,preserved:f,reasons:l}})}function lD(e,t,n){return v(function*(){let r=yield*z(()=>Ee(e.configFile));if(r===void 0)return;let i=yield*V({try:()=>Lt(r,e.configFile),catch:(u)=>u}),o=i.plugins;if(!by(o))return;let a=o[n];if(!by(a)||Object.keys(a).length!==1||a.enabled!==!1)return;let s=t.plugins,c=by(s)?s[n]:void 0,f={...o};if(c===void 0)delete f[n];else f[n]=c;let l={...i};if(Object.keys(f).length===0)delete l.plugins;else l.plugins=f;yield*z(()=>ft(e.configFile,_r(l)))})}function by(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function uD(e,t){return v(function*(){let n=new Set;for(let i of t){let o=i.path.split("/");if(o.length===4&&o[0]==="holycodex"&&o[1]==="agents"&&/^[a-f0-9]{20}$/u.test(o[2]??"")&&o[3]?.endsWith(".toml"))n.add(o[2])}let r=[];for(let i of n){let o=aD(e,i),a=yield*z(()=>wy(o)).pipe(le({onFailure:(s)=>({error:s}),onSuccess:()=>({removed:!0})}));if("removed"in a)r.push(o);else{let s=a.error;if(!ze(s,"ENOENT")&&!ze(s,"ENOTEMPTY")&&!ze(s,"EEXIST"))return yield*p(s)}}return r})}function eT(e={},t=process.env,n={}){return A(tT(e,t,n))}function tT(e,t,n){return v(function*(){let r=Yn(e,t),i=yield*z(()=>Ua(r)),o=yield*z(()=>Kr(r.preparingRecord,i)),a=yield*z(()=>Kr(r.conflictedRecord,i));if(i!==void 0&&!(yield*z(()=>sl(i))))return yield*p(new R("state_corrupt","The existing HolyCodex configuration has changed and cannot be upgraded safely.",void 0,{path:r.activeRecord}));yield*V({try:()=>Ry(i,o,a),catch:(O)=>O});let s=oT(i,o,a),c=s??i;if(c===void 0)return yield*p(new R("not_installed","HolyCodex is not installed in the selected Codex home.",void 0,{recovery:"Run `holycodex install --yes` first."}));let f=yield*z(()=>ky(r)),l=f===void 0?{profile:c.profile,tier:c.tier,optional:{browser_use:c.optional_selections.browser_use,computer_use:c.optional_selections.computer_use,sites:c.optional_selections.sites},officialPlugins:fD(c)}:dD(il(f)),u=n.options===void 0?l:yield*V({try:()=>Yt(n.options),catch:(O)=>O}),g={profile:u.profile??l.profile,tier:u.tier??l.tier,optional:{...l.optional,...u.optional},officialPlugins:u.officialPlugins??l.officialPlugins},h=!pD(g,l),y=yield*z(()=>ay()).pipe(Pt((O)=>p(new R("upgrade_failed","The running HolyCodex version is unavailable.",O)))),S=y.split("-",1)[0]===c.version.split("-",1)[0]&&y.includes("-dev.")!==c.version.includes("-dev."),m=S?0:ha(y,c.version);if(m<0)return yield*p(new R("upgrade_downgrade",`The running HolyCodex version ${y} is older than the installed version ${c.version}.`,void 0,{installed_version:c.version,running_version:y}));let x=c.managed_config?.managed["features.context_management"]!==void 0,E=c.managed_config?.managed[bi[0]]!==void 0,_=[];if(n.dryRun===!0){let O=yield*z(()=>Ee(r.configFile)),ce=yield*V({try:()=>Lt(O),catch:(I)=>I});if(c.managed_config!==void 0)for(let I of Object.keys(c.managed_config.managed)){if(!Rc(I))continue;if((yield*z(()=>Ff(ce,c.managed_config,I))).status!=="unchanged")_.push({path:r.configFile,key:I,action:"replace"})}if(c.plugin_config!==void 0){let I=yield*z(()=>tl(ce,c.plugin_config));for(let J of I.preserved){let ve=J==="preference"?'plugins."holycodex@holycodex"':"marketplaces.holycodex";_.push({path:r.configFile,key:ve,action:"replace"})}}if(c.provider_config!==void 0){let I=c.provider_config,J=yield*z(()=>nl(ce,rd(I),new Set(Ty(c))));for(let ve of J.preserved)_.push({path:r.configFile,key:`plugins."${ve}"`,action:"replace"})}let oe=yield*z(()=>Hf(r.codexHome,c.profile,c.managed_artifacts,c.tier,{browserUse:c.optional_selections.browser_use,computerUse:c.optional_selections.computer_use}));for(let I of oe)_.push(I)}let C=!1,N=[],D=yield*v(function*(){let O=e.runtime??vo(t),ce=yield*z(()=>yy(O,c.tooling?.context7)).pipe(le({onFailure:(J)=>({error:J}),onSuccess:(J)=>({context7:J})})),oe;if("error"in ce){if(c.tooling?.context7!==void 0||!ED(ce.error))return yield*p(ce.error)}else oe=ce.context7;let I=c.tooling?.context7;if(I?.manager!==oe?.manager)N.push("Context7 manager changed");if(I?.version!==oe?.version)N.push("Context7 version changed");if(I?.executable===void 0?oe?.executable!==void 0:oe?.executable===void 0||!(yield*z(()=>GC(O,I.executable,oe.executable))))N.push("Context7 executable changed");return C||=N.length>0,{driftReasons:N}}).pipe(le({onFailure:(O)=>({error:O}),onSuccess:(O)=>O}));if("error"in D){let O=D.error;C=!0;let ce=typeof O==="object"&&O!==null&&"code"in O&&typeof O.code==="string"?O.code:O instanceof Error?O.name:"inspection failed";N.push(`inspection failed (${ce})`)}else N.push(...D.driftReasons),C||=N.length>0;let F=[...m>0||S?["version"]:[],...h?["installation options"]:[],...f===void 0?["installation options migration"]:[],...x?["context-management configuration migration"]:[],...E?["auto-compaction configuration cleanup"]:[],...m>0||x||E?["Root/session configuration","specialist role definitions"]:[],...s?["interrupted transaction recovery"]:[],...C?[`shared tooling reconciliation (${N.join(", ")})`]:[],..._.map((O)=>`conflict: ${O.path}${O.key===void 0?"":` (${O.key})`} -> ${O.action}`)];if(F.length===0)return{status:n.dryRun===!0?"dry_run":"current",from_version:c.version,to_version:y,changes:[],record:i,preserved:[],warnings:[],conflicts:_};if(n.dryRun===!0)return{status:"dry_run",from_version:c.version,to_version:y,changes:F,record:i,preserved:[],warnings:[],conflicts:_};let K=yield*z(()=>Py(g,e,t)).pipe(Pt((O)=>p(O instanceof R?O:new R("upgrade_failed",`HolyCodex upgrade failed: ${Xn(O)}`,O))));return{status:"upgraded",from_version:c.version,to_version:y,changes:F,record:K.record,preserved:K.preserved,warnings:K.warnings}})}function fD(e){let t=new Set(Sa(e.optional_selections));return(e.official_plugins??[]).filter((n)=>n!==Kt&&!nT(n)&&!t.has(n))}function rd(e){return e.filter((t)=>t.plugin_id!==Kt)}function dD(e){return{...e,...e.officialPlugins===void 0?{}:{officialPlugins:e.officialPlugins.filter((t)=>!nT(t))}}}function nT(e){let t=e.slice(0,e.lastIndexOf("@"));return sD.has(t)}function pD(e,t){let n=e.optional??{},r=t.optional??{},i=[...new Set(e.officialPlugins??[])],o=[...new Set(t.officialPlugins??[])];return e.profile===t.profile&&e.tier===t.tier&&n.browser_use===r.browser_use&&n.computer_use===r.computer_use&&n.sites===r.sites&&i.length===o.length&&i.every((a,s)=>a===o[s])}function mD(e,t){return v(function*(){let n=new Set;if(e.resolveConflicts!==void 0&&t.length>0){let r=t.map((o)=>({...o,identity:`remove:${o.path}:${o.key??""}`,category:o.key===void 0?"role-asset":"config-key",target:o.key??o.path,explanation:"HolyCodex can remove this managed value after reviewing the change.",validDecisions:["keep","remove","cancel"],defaultDecision:"keep"})),i=yield*e.resolveConflicts(r);for(let o=0;o<r.length;o+=1){let a=r[o],s=i[a.identity];if(s==="remove")n.add(br(t[o]));else if(s==="keep")continue;else if(s==="cancel")return yield*p(new R("confirmation_required","Conflict resolution was cancelled.",void 0,{identity:a.identity,path:a.path,...a.key===void 0?{}:{key:a.key}}));else return yield*p(new R("confirmation_required",`The removal conflict at ${a.target} requires a keep, remove, or cancel decision.`,void 0,{identity:a.identity,path:a.path,...a.key===void 0?{}:{key:a.key},decision:s??"unavailable"}))}return n}for(let r of t){let i=e.resolveConflict===void 0?void 0:yield*e.resolveConflict(r);if(i==="accept"){n.add(br(r));continue}if(i==="decline")continue;return yield*p(new R("confirmation_required",i==="cancel"?"Conflict resolution was cancelled.":"Modified HolyCodex-owned state requires confirmation before removal.",void 0,{path:r.path,...r.key===void 0?{}:{key:r.key},action:r.action,resolution:i??"unavailable"}))}return n})}function br(e){return`${e.action}\x00${e.path}\x00${e.key??""}`}function _y(e,t,n,r,i){let o=pe(n,t);return rT(n,t).pipe(de((a)=>({identity:br({path:e,key:t,action:"remove"}),category:r,target:t,existing:{present:o!==void 0,digest:a},desired:{present:!1},explanation:i,validDecisions:["keep","remove","cancel"],defaultDecision:"keep",path:e,key:t,action:"remove"})))}function rT(e,t){let n=pe(e,t),r=n===void 0?{present:!1}:{present:!0,value:n};return z(()=>En("holycodex-removal-config-review-v1",[xn(Wt(r))]))}function iT(e){if(typeof e.existing!=="object"||e.existing===null)return;let t=e.existing.digest;return typeof t==="string"?t:void 0}function gD(e,t,n,r){return v(function*(){for(let o of n){if(o.key===void 0)continue;let a=iT(o);if(a===void 0||(yield*rT(t,o.key))!==a)return yield*p(Cy(o.path,o.key))}let i=yield*z(()=>LC(e.codexHome,r)).pipe(le({onFailure:(o)=>({error:o}),onSuccess:(o)=>({changedNativePaths:o})}));if("error"in i){let o=r.keys().next().value;return yield*p(new R("confirmation_required","A reviewed HolyCodex file could not be checked safely, so removal did not continue.",i.error,{operation:"verify removal review",...o===void 0?{}:{path:o},recovery:"Check file access, then run remove again to review current state."}))}if(i.changedNativePaths.length>0)return yield*p(Cy(i.changedNativePaths[0]))})}function Cy(e,t){return new R("confirmation_required","A reviewed HolyCodex item changed before removal. No reviewed changes were applied; run remove again to review the current state.",void 0,{operation:"remove HolyCodex",path:e,...t===void 0?{}:{key:t},recovery:"Run remove again to review the current state."})}function ZC(e,t){return z(()=>Ee(e)).pipe(Re((n)=>n===t?rt:p(Cy(e))))}function hD(e,t){if(!t.managed_config)return M(Ft(["incomplete_install_state"]));return v(function*(){let n=yield*z(()=>Ee(e.configFile)),r=yield*V({try:()=>Lt(n),catch:(a)=>a}),i=al(t.profile,t.tier,{browserUse:t.capability_state?.browser_use.status==="healthy"&&t.capability_state.browser_use.selected,computerUse:t.optional_selections.computer_use,frontend:ut.frontend,security:ut.security}),o=[];for(let a of Object.keys(i))if((yield*z(()=>Ff(r,t.managed_config,a))).status!=="unchanged")o.push(a);return o.length===0?La({managed_keys:Object.keys(i).length}):Ft(["changed_holycodex_config"],{keys:o})}).pipe(Pt((n)=>M(Ft(["config_unreadable"],{error:Xn(n)}))))}function yD(e,t,n,r={browserUse:!1,computerUse:!1}){return v(function*(){let i=yield*z(()=>Ee(e.configFile)),o=yield*V({try:()=>Lt(i),catch:(f)=>f}),a=[],s=yo(t,n,r);for(let f of Hr(t,n)){let l=pe(o,`agents."${f.name}".config_file`),u=fo(e.configFile,Hc(f.name,s)).replaceAll("\\","/");if(typeof l!=="string"||fo(e.configFile,l).replaceAll("\\","/")!==u){a.push(`${f.name}:registration`);continue}let g=yield*z(()=>Ee(u));if(g===void 0){a.push(`${f.name}:missing`);continue}if(g!==Aa(f,r)){a.push(`${f.name}:changed`);continue}}let c=yield*z(()=>Ee(`${e.codexHome}/agents/root.toml`));if(c!==void 0&&Ma(c))a.push("root:stale");return a.length===0?La({role_root:e.roleRoot,agent_types:Hr(t,n).map((f)=>f.name)}):Ft(["native_role_disagreement"],{roles:a})}).pipe(Pt((i)=>M(Ft(["native_role_invalid"],{error:Xn(i)}))))}function Zn(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(Ye(ki,n)!==void 0)return z(()=>zc(e.conflictedRecord,Wt(n)));return rt}function oT(e,t,n){return[n,t].find((r)=>r!==void 0&&(e===void 0||ol(r,e)))}function aT(e,t,n){return oT(e,t,n)??e}function bo(){return{owner:"holycodex",schema_epoch:"state-0.16",install_id:"remove-conflict",version:"0.0.0",digest:"0".repeat(64),profile:"default",tier:"standard",optional_selections:{browser_use:!1,computer_use:!1,sites:!1,coding:!0},explicit_optional_selections:{},managed_artifacts:[],installed_at:new Date(0).toISOString()}}function Ty(e){if(e?.owned_plugins!==void 0)return[...new Set(e.owned_plugins)].filter((i)=>i!==Kt);let t=(e?.plugin_snapshot??[]).filter((i)=>i.plugin_id!==Kt&&(i.status==="missing"||i.status==="available")).map((i)=>i.plugin_id),n=e?.plugin_config?.before.preference.presence==="absent"&&e.plugin_config.after.preference.presence==="present"?[Gt]:[],r=(e?.provider_config??[]).filter((i)=>i.plugin_id!==Kt&&i.before.presence==="absent"&&i.after.presence==="present").map((i)=>i.plugin_id);return[...new Set([...t,...n,...r])]}function SD(e,t){let n=hr(e,t);if(n!==void 0)return n;let r=[...e.installed,...e.available].find((i)=>i.pluginId===t);return r===void 0?void 0:{entry:r}}function La(e){return{status:"healthy",reasons:[],details:e}}function Ft(e,t={}){return{status:"failed",reasons:e,details:t}}function xD(e){return z(()=>nd(e,{force:!1})).pipe(me((t)=>ze(t,"ENOENT"),()=>rt),Gv)}function ED(e){return typeof e==="object"&&e!==null&&"code"in e&&(e.code==="context7_unavailable"||e.code==="context7_manager_unknown")}function Xn(e){return e instanceof Error?e.message.slice(0,256):"operation failed"}function z(e){return d({try:e,catch:(t)=>t})}function td(e,t){Oe(Je(V({try:()=>e.onProgress?.(t),catch:(n)=>n})))}var sD;var ad=L(()=>{mo();st();De();cl();$f();Wc();Yf();Kc();ho();jc();Oa();ed();sD=new Set(["documents","pdf","presentations","spreadsheets","template-creator"])});import{lstat as mT,open as vD,rm as By}from"fs/promises";import{dirname as bD}from"path";function Yt(e){let t=Ye(qf,e);if(t===void 0)throw new R("install_failed","The installation options are invalid.");let n=t;return hT(n),n}function hT(e){if(e.officialPlugins?.includes(Kt)!==!0)return;throw new R("install_failed","Browser Use is provided by Codex Desktop/runtime and cannot be installed by the HolyCodex CLI. Select the Browser Use capability instead; it is available only on supporting Codex surfaces.",void 0,{plugin_id:Kt})}function ky(e){return A(yT(e))}function yT(e){return v(function*(){let t=yield*d({try:()=>Ee(e.installOptions),catch:(n)=>n});return ST(t,e.installOptions)})}function ST(e,t){if(e===void 0)return;let n=Oe(V({try:()=>Bc(e),catch:(o)=>new R("state_corrupt","The HolyCodex install options are not valid TOML.",o,{path:t})})),r=Ye($c,n);if(r!==void 0)return r;let i=Ye(gC,n);if(i!==void 0)return{schema_version:1,profile:i.profile,tier:i.tier,capabilities:i.capabilities.filter((o)=>o==="browser_use"||o==="computer_use"||o==="sites").concat(...["browser_use","sites"].filter((o)=>!i.capabilities.includes(o))),additional_plugins:i.additional_plugins};if(r===void 0)throw new R("state_corrupt","The HolyCodex install options are invalid.",void 0,{path:t});return r}function CD(e,t){return A(xT(e,t))}function xT(e,t){if(Ye($c,t)===void 0)return p(new R("state_corrupt","The HolyCodex install options are invalid."));return d({try:()=>ft(e.installOptions,Vc(t)),catch:(n)=>n})}function il(e){return{profile:e.profile,tier:e.tier,optional:{browser_use:e.capabilities.includes("browser_use"),computer_use:e.capabilities.includes("computer_use"),sites:e.capabilities.includes("sites")},officialPlugins:e.additional_plugins.filter((t)=>t!==Kt)}}function ET(e={},t=process.env){return v(function*(){let n=Yn(e,t),r=yield*yT(n);if(r!==void 0)return il(r);let i=yield*Vy(n);if(i===void 0)return{};return{profile:i.profile,tier:i.tier,optional:i.optional_selections,officialPlugins:jy(i)}})}function vT(e,t,n,r){let i=["browser_use","computer_use","sites"].filter((o)=>n[o]);return{schema_version:1,profile:e,tier:t,capabilities:i,additional_plugins:[...new Set(r)].filter((o)=>o!==Kt)}}function ol(e,t){return e.install_id===t.install_id&&e.digest===t.digest}function sd(e,t,n){let r=[{status:"conflicted",record:n},{status:"preparing",record:t}].filter((a)=>a.record!==void 0),i=r.length>1,o=i&&r.every(({record:a})=>ol(a,r[0].record));return r.map(({status:a,record:s})=>{let c=e===void 0?i&&!o?"incompatible":"orphaned":ol(s,e)?i&&!o?"incompatible":"bound":"stale";return{status:a,relation:c,install_id:s.install_id,digest:s.digest,recovery:c==="stale"||c==="incompatible"?"inspect":"reconcile",...e===void 0?{}:{active_install_id:e.install_id,active_digest:e.digest}}})}function Ry(e,t,n){let r=sd(e,t,n);if(r.filter((o)=>o.relation==="stale"||o.relation==="incompatible").length>0)throw new R("state_corrupt","HolyCodex has stale or incompatible transaction state and cannot recover safely.",void 0,bT(r));return r}function Iy(e,t,n){let r=sd(e,t,n);if(e===void 0&&r.some((i)=>i.relation==="incompatible"))throw new R("state_corrupt","HolyCodex has ambiguous transaction state and cannot recover safely.",void 0,bT(r));return r}function bT(e){return{recovery:e.map((t)=>t.recovery).join(","),transactions:e.map((t)=>`${t.status}:${t.relation}:${t.install_id}:${t.digest}`).join(","),active:e[0]?.active_install_id===void 0?"absent":`${e[0].active_install_id}:${e[0].active_digest}`}}function dl(e={},t={},n=process.env){return v(function*(){let r=Ye(Uc,e);if(r===void 0)return yield*p(new R("install_failed","The installation options are invalid."));hT(r);let i=Yn(t,n),o=yield*d({try:()=>Ee(i.installOptions),catch:(P)=>P}),a=ST(o,i.installOptions),s=a===void 0?void 0:il(a);er(t,{stage:"validation",status:"started",message:"Validating Codex target"});let c=yield*Vy(i),f=yield*d({try:()=>Ee(i.activeRecord),catch:(P)=>P});if(c!==void 0&&!(yield*pd(c)))return yield*p(new R("state_corrupt","The existing HolyCodex configuration has changed and cannot be replaced.",void 0,{path:i.activeRecord}));let l=yield*Ly(i.preparingRecord,c),u=yield*Ly(i.conflictedRecord,c);Ry(c,l,u);let g=[u,l].find((P)=>P!==void 0&&(c===void 0||ol(P,c)));if(g!==void 0){let{removeHolyCodex:P}=yield*d({try:()=>Promise.resolve().then(() => (ad(),sT)),catch:(q)=>q}),H=yield*d({try:()=>P(t,n),catch:(q)=>q});if(H.preserved.length>0||H.reasons.length>0)return yield*p(new R("state_corrupt","The interrupted HolyCodex installation could not be reconciled safely.",void 0,{preserved:H.preserved.join(","),reasons:H.reasons.join(",")}));return yield*dl({profile:e.profile??s?.profile??g.profile,tier:e.tier??s?.tier??g.tier,optional:{browser_use:e.optional?.browser_use??s?.optional?.browser_use??g.optional_selections.browser_use,computer_use:e.optional?.computer_use??s?.optional?.computer_use??g.optional_selections.computer_use,sites:e.optional?.sites??s?.optional?.sites??g.optional_selections.sites},officialPlugins:e.officialPlugins??s?.officialPlugins??jy(g)},t,n)}let h=YD(e.profile??s?.profile,c?.profile),y=ZD(e.tier??s?.tier,c?.tier),S=s?.optional,m=Fy(S,e.optional),x=XD(m,c?.optional_selections),E=Fy(Fy(c?.explicit_optional_selections,S),e.optional),_=e.officialPlugins??s?.officialPlugins??jy(c),C=t.runtime??vo(n),N=yield*d({try:()=>Xf(C,!1,c?.tooling?.context7),catch:(P)=>P}).pipe(le({onFailure:()=>!1,onSuccess:()=>!0})),D,F,K=[...new Set(Sa(_T(x),_).map((P)=>Pn(P)??P))],O=t.officialPluginManager??(yield*d({try:()=>Er.discover({...n,CODEX_HOME:i.codexHome}),catch:(P)=>new R("capability_denied","Native Codex plugin installation is unavailable.",P,{recovery:"Install or expose Codex, then retry."})}));if(!O.addMarketplace||!O.add||!O.list)return yield*p(new R("install_failed","Native Codex plugin installation and verification are unavailable."));let ce=c?.install_id??crypto.randomUUID().replaceAll("-",""),oe=yield*sy(),I=c!==void 0&&c.version!==oe&&c.owned_plugins?.includes(Gt)===!0?new Set([Gt]):new Set,J=new Set((c?.owned_plugins??[]).filter((P)=>P!==Kt)),ve=new Set([Gt,...K]),ge=[...J].filter((P)=>!ve.has(P));if(ge.length>0&&O.remove===void 0)return yield*p(new R("install_failed","Native Codex cannot remove previously managed plugins omitted from the new selection.",void 0,{plugins:ge.join(",")}));let Zt=(t.now?.()??new Date).toISOString(),Tt=al(h,y,{browserUse:x.browser_use,computerUse:x.computer_use,frontend:ut.frontend,security:ut.security}),Xt=yield*d({try:()=>Ee(i.configFile),catch:(P)=>P}),ko=Oe(V({try:()=>Lt(Xt,i.configFile),catch:(P)=>P}).pipe(le({onFailure:(P)=>({error:P}),onSuccess:(P)=>({document:P})})));if("error"in ko){let P=ko.error;if(P instanceof R&&P.code==="state_corrupt")yield*ND(t,P,i.configFile);return yield*p(P)}let Ro=ko.document,vd=c?.managed_config??Nf({schema:mn,installId:ce}),sS=yield*ud(Ro,vd),bd=yield*PD(t,i.configFile,sS.document,['plugins."holycodex@holycodex"',"marketplaces.holycodex",...Object.keys(Tt)]),{document:Va,conflicts:_n,decisions:El}=bd,_d=_n.length===0?Ro:$a(Ro,_n,El),cn;if(_n.length>0){if((yield*d({try:()=>Ee(i.configFile),catch:(H)=>H}))!==Xt)return yield*p(new R("confirmation_required","Codex configuration changed after the invalid-table review; review the latest configuration and retry.",void 0,{path:i.configFile}));cn=_r(_d),yield*d({try:()=>ft(i.configFile,cn),catch:(H)=>H})}let vl,cS=!1,bl,lS=new Map,wd=yield*d({try:()=>O.list(),catch:(P)=>P}).pipe(le({onFailure:(P)=>({error:P}),onSuccess:(P)=>({live:P})}));if("live"in wd)vl=wd.live;else{let P=wd.error;if(cn!==void 0)yield*My(i.configFile,Xt,cn),cn=void 0;if(!eF(P))return yield*p(new R("capability_denied","Native Codex plugin state could not be read safely.",P));if((yield*d({try:()=>Ee(i.configFile),catch:(te)=>te}))!==Xt)return yield*p(new R("confirmation_required","Codex configuration changed before the required marketplace repair; review the current marketplace source and retry.",P,{path:i.configFile,key:"marketplaces.holycodex"}));let H=pe(Va,"marketplaces.holycodex"),q=_n.some((te)=>te.key==="marketplaces"&&El.get(te.identity)==="remove");if(H===void 0&&!q)return yield*p(new R("confirmation_required","Codex reported an incomplete marketplace named holycodex, but config.toml does not contain a reviewable marketplace source. Review the source before retrying; no automatic replacement was attempted.",P,{path:i.configFile,key:"marketplaces.holycodex"}));if(H!==void 0&&!tF(H))bl=Ln({path:i.configFile,key:"marketplaces.holycodex",action:"replace",category:"config-key",target:"marketplaces.holycodex",existing:H,desired:{source_type:"git",source:Gr},explanation:"The existing HolyCodex marketplace source must be reviewed before rebuilding its incomplete cache from the required canonical source.",defaultDecision:"replace",validDecisions:["replace","cancel"]}),lS=(yield*fl(t,[bl],!0)).decisions;if(!(Zr(H)&&Object.keys(H).length===2&&H.source_type==="git"&&H.source===Gr)){if((yield*d({try:()=>Ee(i.configFile),catch:(he)=>he}))!==Xt)return yield*p(new R("confirmation_required","Codex configuration changed before marketplace repair; review the current source and retry.",P,{path:i.configFile,key:"marketplaces.holycodex"}));let te=wr(Va,"marketplaces",wo,{source_type:"git",source:Gr});cn=_r(te),yield*d({try:()=>ft(i.configFile,cn),catch:(he)=>he})}if(O.addMarketplace===void 0)return yield*p(new R("capability_denied","Native Codex plugin state could not be read safely.",P));let re=yield*d({try:()=>O.addMarketplace(cT),catch:(te)=>te}).pipe(Re(()=>d({try:()=>O.list(),catch:(te)=>te}))).pipe(le({onFailure:(te)=>({error:te}),onSuccess:(te)=>({live:te})}));if("error"in re){let te=re.error;if(cn!==void 0){let he=cn,Ae=yield*My(i.configFile,Xt,he).pipe(le({onFailure:(ct)=>({error:ct}),onSuccess:()=>({restored:!0})}));if("error"in Ae){let ct=Ae.error;return yield*p(new R("confirmation_required","The marketplace repair failed and the reviewed temporary Codex configuration could not be restored safely; review config.toml before retrying.",ct,{path:i.configFile,key:"marketplaces.holycodex"}))}cn=void 0}return yield*p(new R("capability_denied","The required HolyCodex marketplace could not be repaired before plugin validation.",te))}vl=re.live,cS=!0}if(cn!==void 0)yield*My(i.configFile,Xt,cn),cn=void 0;let uS=K.filter((P)=>{if(!P.endsWith("@openai-curated"))return!1;let H=tr(vl,P);return!(H?.installed&&H.enabled)});er(t,{stage:"validation",status:"completed",message:"Codex target validated"});let Mi=yield*cd(Va),Cd=c?.plugin_config?.before??Mi,Cr=Cd,Io=t.resolveConflicts!==void 0,Po=[],qa=[],za=[];if(qa=["preference","marketplace"].filter((H)=>{let q=Mi[H].digest,Se=Mi[H],re=H==="preference"?{kind:"boolean",value:!0}:{kind:"marketplace",source_type:"git",source:Gr},te=Se.presence==="present"&&JSON.stringify(Se.safe_value)!==JSON.stringify(re),he=c?.plugin_config!==void 0&&q!==c.plugin_config.after[H].digest&&q!==c.plugin_config.before[H].digest;return te||he}).map((H)=>{let q=H==="preference"?'plugins."holycodex@holycodex"':"marketplaces.holycodex",Se=Mi[H],re=H==="preference"?{kind:"boolean",value:!0}:{kind:"marketplace",source_type:"git",source:Gr};return Ln({path:i.configFile,key:q,action:"replace",category:"config-key",target:q,existing:Se.safe_value??{presence:Se.presence},desired:re,explanation:`The existing ${q} entry does not match the HolyCodex plugin configuration.`,validDecisions:["replace","cancel"],defaultDecision:"replace"})}),Io)Po.push(...qa);let Td=[...new Set([...K,...(c?.provider_config??[]).map((P)=>P.plugin_id),...c?.owned_plugins??[]])].filter((P)=>P!==Gt&&P!==Kt),Ni=yield*ld(Va,Td);{let P=new Set(c?.owned_plugins??[]);if(za=Ni.filter((q)=>{let Se=c?.provider_config?.find((he)=>he.plugin_id===q.plugin_id),re=P.has(q.plugin_id)&&Se!==void 0&&q.before.digest!==Se.after.digest&&q.before.digest!==Se.before.digest,te=K.includes(q.plugin_id)&&q.before.presence==="present"&&q.before.safe_value?.value!==!0;return re||te}).map((q)=>{let Se=`plugins."${q.plugin_id}"`;return Ln({path:i.configFile,key:Se,action:"replace",category:"config-key",target:Se,existing:q.before.safe_value??{presence:q.before.presence},desired:{kind:"boolean",value:!0},explanation:`The existing provider plugin entry ${q.plugin_id} does not match the selected plugin configuration.`,...K.includes(q.plugin_id)?{validDecisions:["replace","cancel"],defaultDecision:"replace"}:{}})}),Io)Po.push(...za)}let kd=Ni.map((P)=>{let H=c?.provider_config?.find((q)=>q.plugin_id===P.plugin_id);return H===void 0?P:{plugin_id:P.plugin_id,before:H.before,after:H.before}}),_l=kd,fS=sS.state,dS=yield*Ny(Va,fS,c),pS=yield*ud(dS.document,dS.state),mS=yield*Dy(pS.document,pS.state),{document:nr,state:Un}=mS;$D(nr,Un);let Di;if(c!==void 0){Di=al(c.profile,c.tier,{browserUse:c.optional_selections.browser_use,computerUse:c.optional_selections.computer_use,frontend:ut.frontend,security:ut.security});let P=nf(c.version.split("-",1)[0]);for(let H of Br){let q=c.managed_artifacts.find(({path:Se})=>Se.endsWith(`/${H}.toml`));Di[`agents."${H}".config_file`]=q?.path??`holycodex/agents/${H}.toml`}if(ha(P,_D)<=0)Di.model="gpt-6-astra",Di.model_reasoning_effort=c.profile==="low"?"low":c.profile==="default"?"medium":"high";else if(c.profile==="high"&&ha(P,wD)<=0)Di.model_reasoning_effort="high";delete Di.developer_instructions}let Rd=yield*UD(nr,Un,Tt,Di),Id=yield*Pc(nr,Un,Rd,{schema:mn,installId:ce}).pipe(St((P)=>P instanceof R?P:new R("state_corrupt","The existing Codex configuration has an incompatible shape for HolyCodex settings.",P,{recovery:"Converge the conflicting Codex setting, then retry."}))).pipe(le({onFailure:(P)=>({error:P}),onSuccess:(P)=>({value:P})}));if("error"in Id)return yield*p(Id.error);let Qr=Id.value,ei=[];if(Qr.driftedKeys.length>0)ei=Qr.driftedKeys.map((P)=>{let H=Un.managed[P],q=pe(nr,P),Se=Tt[P];return Ln({path:i.configFile,key:P,action:"replace",category:"config-key",target:P,existing:q??H?.lastManagedValue,desired:Se,explanation:`The managed Codex setting ${P} changed outside the previous transaction.`})});let Fi=Object.entries(Tt).flatMap(([P,H])=>{let q=P;if(Un.managed[q]!==void 0)return[];let Se=pe(nr,q);if(Se===void 0||JSON.stringify(Se)===JSON.stringify(H))return[];return[Ln({path:i.configFile,key:q,action:"replace",category:"config-key",target:q,existing:Se,desired:H,explanation:`The existing Codex setting ${q} is user-owned and differs from the HolyCodex install value.`,defaultDecision:"replace",validDecisions:["keep","replace","cancel"]})]});if(Io)Po.push(...Fi);if(Io)Po.push(...ei);let wl=yield*d({try:()=>Hf(i.codexHome,h,c?.managed_artifacts,y,{browserUse:x.browser_use,computerUse:x.computer_use}),catch:(P)=>new R("install_failed",ul(P),P)});if(Io)Po.push(...wl.map(Ln));let Cl=[..._n,...qa,...za,...Fi,...ei,...wl.map(Ln)],YT={...Qr.state.managed},ZT=new Set([..._n.map((P)=>P.identity),...bl===void 0?[]:[bl.identity]]),XT=(Io?Po:Cl).filter((P)=>!ZT.has(P.identity)),gS=yield*fl(t,XT,!0),rr={...gS,decisions:new Map([...El,...lS,...gS.decisions])},hS=[],Ja={...Rd},Wa=Un.managed,yS=()=>v(function*(){hS=wl.map((te)=>{let he=Ln(te),Ae=rr.decisions.get(he.identity);return Ae===void 0?he:{...he,decision:Ae}});let P=yield*uT(nr,nr,Cd,kd,Mi,Ni,qa,za,rr.decisions,K),H=$a(P.document,_n,rr.decisions);Cr=P.pluginConfigBefore,_l=P.providerConfigBefore;let q={...Un.managed},Se={...Rd};for(let te of[...Fi,...ei]){let he=te.key;if(he===void 0)continue;let Ae=he,ct=rr.decisions.get(te.identity);if(ct!=="keep"&&ct!=="replace")return yield*p(new R("confirmation_required","Managed conflict resolution is incomplete.",void 0,{key:he}));let ti=q[Ae],vt=Tt[Ae];if(vt===void 0)return yield*p(new R("state_corrupt","The managed conflict cannot be verified.",void 0,{path:i.configFile,key:he}));let Li=pe(nr,Ae);if(ct==="replace")if(H=Gn(H,Ae,vt),ti!==void 0)q[Ae]={...ti,lastManagedValue:yield*on(Ae,vt)};else{let ni=YT[Ae];if(ni!==void 0)q[Ae]=ni}else{if(delete Se[Ae],ti===void 0)continue;if(Li===void 0){delete q[Ae];continue}let ni={...ti,lastManagedValue:yield*on(Ae,Li)},Oo={...Un,managed:{...q,[Ae]:ni}};if(uo(Oo))q[Ae]=ni;else delete q[Ae]}}if(Qr=yield*Pc(H,{...Un,managed:q},Se,{schema:mn,installId:ce}),Qr.driftedKeys.length>0)return yield*p(new R("state_corrupt","The accepted managed conflicts did not converge."));Ja=Se;let re={...Un.managed};for(let te of[...Fi,...ei]){let he=te.key;if(he===void 0)continue;delete re[he]}Wa=re});yield*yS();let SS=()=>Cl.map((P)=>{let H=Ln(P),q=rr.decisions.get(H.identity);return q===void 0?H:{...H,decision:q}}),xS=(P)=>Object.fromEntries(["config-key","invalid-config","native-plugin","role-asset"].flatMap((H)=>{let q=P.filter((Se)=>Se.category===H).length;return q===0?[]:[[H,q]]})),Tl=SS(),ES=xS(Tl),QT=nF(N,vl,K);if(t.reviewInstall!==void 0)while(!0){let P=yield*t.reviewInstall({operation:c===void 0?"install":"upgrade",...c===void 0?{}:{fromVersion:c.version},toVersion:oe,profile:h,tier:y,capabilities:{browser_use:x.browser_use,computer_use:x.computer_use,sites:x.sites},additionalPlugins:[..._],conflicts:Tl,conflictCounts:ES,tools:QT});if(P.action==="cancel")return yield*p(new R("confirmation_required","Install review was cancelled."));if(P.action==="resolve"){if(Cl.length===0)return yield*p(new R("confirmation_required","There are no managed conflicts to resolve."));rr=yield*fl(t,Cl,!0),yield*yS(),Tl=SS(),ES=xS(Tl);continue}if(P.action==="change"){if(P.request===void 0)return yield*p(new R("confirmation_required","Changing install options requires a revised request."));return yield*dl(P.request,t,n)}if(P.action==="apply")break;return yield*p(new R("confirmation_required","Unknown install review action."))}let Pd={owner:"holycodex",schema_epoch:mn,install_id:ce,version:oe,digest:c?.digest??"0".repeat(64),profile:h,tier:y,optional_selections:x,explicit_optional_selections:E,official_plugins:K,capability_state:dd(x),managed_artifacts:c?.managed_artifacts??[],installed_at:Zt,status:"preparing",step:"validated",managed_config:fS,plugin_snapshot:[],plugin_config:{plugin_id:Gt,before:Cr,after:Cr},provider_config:_l,owned_plugins:[...J],...c?.tooling?.context7===void 0?{}:{tooling:{context7:c.tooling.context7}}};yield*Ra(i.stateRoot),yield*Fn(i.preparingRecord,Pd);let Ha=[],Tr,Od=!1,vS=!1,bS=new Set,Ad=new Set,kl=new Set,Qt=new Set(J),Md=new Set([...J,...K]),Nd=new Set,fe=Pd,_S=!1,kr,wS,Ka=Qr.state,CS=!1,TS=!1;return yield*v(function*(){if(_n.length>0){let U=yield*d({try:()=>Ee(i.configFile),catch:(ye)=>ye});if(_d=$a(Lt(U,i.configFile),_n,El),(yield*d({try:()=>Ee(i.configFile),catch:(ye)=>ye}))!==U)return yield*p(new R("confirmation_required","Codex configuration changed during conflict resolution; review the latest configuration and retry.",void 0,{path:i.configFile}));yield*d({try:()=>ft(i.configFile,_r(_d)),catch:(ye)=>ye}),vS=!0}let P=yield*d({try:()=>Xf(C,!0,c?.tooling?.context7),catch:(U)=>U}).pipe(le({onFailure:(U)=>({error:U}),onSuccess:(U)=>({value:U})}));if("error"in P)F=`Optional ctx7 is unavailable: ${ul(P.error)}`;else D=P.value;let H=D??c?.tooling?.context7,q=H===void 0?void 0:{context7:H},Se={...Pd,...q===void 0?{}:{tooling:q}};if(fe=Se,yield*Fn(i.preparingRecord,fe),O.ensureOfficialMarketplace!==void 0&&uS.length>0)yield*d({try:()=>O.ensureOfficialMarketplace(uS),catch:(U)=>new R("capability_denied",`The selected official Codex provider marketplace is unavailable: ${ul(U)}`,U,{recovery:"Check Codex network and marketplace policy, then retry."})});Ha=yield*jD({list:()=>O.list()},[...new Set([Gt,...K,...J])]).pipe(St((U)=>new R("capability_denied","Native Codex plugin state could not be read safely.",U))),Se={...Se,plugin_snapshot:Ha},fe=Se,yield*Fn(i.preparingRecord,fe);let re=yield*d({try:()=>Ee(i.configFile),catch:(U)=>U}),te=Lt(re,i.configFile),he=$a(te,_n,rr.decisions);yield*LD(he,Mi,Ni);let Ae=yield*Ny(he,vd,c),ct=yield*ud(Ae.document,Ae.state);kr=(yield*Dy(ct.document,ct.state)).document,yield*dT(kr,nr,{...Un,managed:Wa},Ja),er(t,{stage:"roles",status:"started",message:"Installing subagent roles"}),yield*Ra(i.roleRoot),Tr=yield*d({try:()=>my(i.codexHome,h,c?.managed_artifacts,y,wl.length===0?t.resolveConflict:void 0,hS,{browserUse:x.browser_use,computerUse:x.computer_use}),catch:(U)=>U}),fe={...Se,step:"roles_prepared",managed_artifacts:Tr.managed_artifacts},yield*Fn(i.preparingRecord,fe),er(t,{stage:"roles",status:"completed",message:"Subagent roles installed"}),er(t,{stage:"plugins",status:"started",message:"Installing selected capabilities"}),_S=!0;let vt=kr;if(vt===void 0)return yield*p(new R("state_corrupt","The pre-mutation configuration baseline is missing."));vt=wr(vt,"plugins",_o,{enabled:!0}),vt=wr(vt,"marketplaces",wo,{source_type:"git",source:Gr});for(let U of K)vt=wr(vt,"plugins",U,{enabled:!0});let Li=yield*cd(vt),Oo=(yield*ld(vt,Td)).map((U)=>({plugin_id:U.plugin_id,before:Ni.find((ye)=>ye.plugin_id===U.plugin_id)?.before??U.before,after:U.before}));if(fe={...fe,plugin_config:{plugin_id:Gt,before:Cr,after:Li},provider_config:Oo},yield*Fn(i.preparingRecord,fe),Xt===void 0)wS=yield*v(function*(){let U=yield*JD(i.configFile),ye=yield*d({try:()=>Ee(i.configFile),catch:(Ut)=>Ut});if(U===void 0||ye!=="")return yield*p(new R("confirmation_required","Codex config.toml appeared during installation; review the latest configuration and retry.",void 0,{operation:"initialize Codex configuration",path:i.configFile}));return U}).pipe(St((U)=>U instanceof R?U:new R("permission_denied","Codex config.toml could not be initialized before plugin setup.",U,{operation:"initialize Codex configuration",path:i.configFile,recovery:"Check CODEX_HOME permissions, then retry."}))),re="";if((yield*d({try:()=>Ee(i.configFile),catch:(U)=>U}))!==re)return yield*p(new R("confirmation_required","Codex configuration changed during plugin setup; review the latest configuration and retry.",void 0,{path:i.configFile}));if(yield*d({try:()=>ft(i.configFile,_r(vt)),catch:(U)=>U}),Od=!0,!cS)yield*d({try:()=>O.addMarketplace(cT),catch:(U)=>U});yield*HD({list:()=>O.list(),add:(U)=>O.add(U)},[Gt,...K],I,(U,ye)=>v(function*(){if(ye==="new")bS.add(U),Qt.add(U),Md.add(U),fe={...fe,owned_plugins:[...Qt]};else Nd.add(U),Qt.add(U),Md.add(U),fe={...fe,owned_plugins:[...Qt]};yield*Fn(i.preparingRecord,fe)})),fe={...fe,step:"plugins_installed"},yield*Fn(i.preparingRecord,fe),er(t,{stage:"plugins",status:"completed",message:"Selected capabilities installed"});let Ga=yield*d({try:()=>Ee(i.configFile),catch:(U)=>U}),Dd=Lt(Ga,i.configFile),ek=$a(Dd,_n,rr.decisions),kS=yield*Ny(ek,vd,c),RS=yield*ud(kS.document,kS.state),tk=yield*Dy(RS.document,RS.state);if(kr===void 0)return yield*p(new R("state_corrupt","The pre-mutation configuration baseline is missing."));let Fd=yield*uT(tk.document,kr,Cd,kd,Mi,Ni,qa,za,rr.decisions,K),Rr=Fd.document;for(let U of Object.keys(Wa)){let ye=U,Ut=pe(kr,ye);Rr=Ut===void 0?vn(Rr,ye):Gn(Rr,ye,Ut)}Cr=Fd.pluginConfigBefore,_l=Fd.providerConfigBefore;let Rl=yield*cd(Rr),IS=yield*ld(Rr,Td),PS=IS.map((U)=>({plugin_id:U.plugin_id,before:_l.find((ye)=>ye.plugin_id===U.plugin_id)?.before??U.before,after:U.before})),OS=IS.map((U)=>({plugin_id:U.plugin_id,before:Ni.find((ye)=>ye.plugin_id===U.plugin_id)?.before??U.before,after:U.before}));fe={...fe,plugin_config:{plugin_id:Gt,before:Cr,after:Rl},provider_config:OS};let nk=new Set([...Fi,...ei].flatMap((U)=>U.key===void 0?[]:[U.key])),Il={...Wa};for(let U of[...Fi,...ei]){let ye=U.key;if(ye===void 0)continue;let Ut=Qr.state.managed[ye];if(Ut!==void 0)Il[ye]=Ut}for(let[U,ye]of Object.entries(Il)){if(nk.has(U))continue;let Ut=U,Ya=pe(kr,Ut);Il[Ut]={...ye,...Ya===void 0?{}:{lastManagedValue:yield*on(Ut,Ya)}}}let AS={...Qr.state,managed:Il};yield*dT(Rr,kr,{...AS,managed:Wa},Ja);for(let U of[...Fi,...ei]){let ye=U.key;if(ye===void 0)continue;let Ya=rr.decisions.get(U.identity)==="replace"?Tt[ye]:pe(nr,ye);if(Ya!==void 0)Rr=Gn(Rr,ye,Ya)}let Ao=yield*Pc(Rr,AS,Ja,{schema:mn,installId:ce});if(Ao.driftedKeys.length>0)return yield*p(new R("state_corrupt","HolyCodex-owned Codex settings changed during native plugin setup.",void 0,{keys:Ao.driftedKeys.join(",")}));if(er(t,{stage:"config",status:"started",message:"Configuring Root"}),Ka=Ao.state,fe={...fe,managed_config:Ka,plugin_config:{plugin_id:Gt,before:Cr,after:Rl},provider_config:OS},(yield*d({try:()=>Ee(i.configFile),catch:(U)=>U}))!==Ga)return yield*p(new R("confirmation_required","Codex configuration changed during plugin setup; review the latest configuration and retry.",void 0,{path:i.configFile}));let rk=c===void 0||c.managed_config?.managed["permissions.holycodex.extends"]===void 0&&pe(Ao.document,"default_permissions")===void 0?Gn(Ao.document,"default_permissions","holycodex"):Ao.document;if(yield*d({try:()=>ft(i.configFile,_r(rk)),catch:(U)=>U}),Od=!0,fe={...fe,step:"config_published"},yield*Fn(i.preparingRecord,fe),ge.length>0)yield*KD({list:()=>O.list(),remove:(ye)=>O.remove(ye)},ge,(ye,Ut)=>v(function*(){if(Ut==="removed")Ad.add(ye),Qt.delete(ye);else if(Ut==="absent")Qt.delete(ye);else kl.add(ye);fe={...fe,owned_plugins:[...Qt]},yield*Fn(i.preparingRecord,fe)}));er(t,{stage:"config",status:"completed",message:"Root configuration published"}),er(t,{stage:"verification",status:"started",message:"Verifying installation"}),yield*VD(i,h,y,{browserUse:x.browser_use,computerUse:x.computer_use,frontend:ut.frontend,security:ut.security},Ka,Tr.preserved,Ja),er(t,{stage:"verification",status:"completed",message:"Installation verified"});let MS=dd(x),ik=yield*md({owner:"holycodex",install_id:ce,version:oe,profile:h,tier:y,optional_selections:x,explicit_optional_selections:E,official_plugins:K,capability_state:MS,managed_artifacts:Tr.managed_artifacts,managed_config:Ka,plugin_config:{plugin_id:Gt,before:Cr,after:Rl},provider_config:PS,plugin_snapshot:Ha,owned_plugins:[...Qt],...q===void 0?{}:{tooling:q}}),Ld={owner:"holycodex",schema_epoch:mn,install_id:ce,version:oe,digest:ik,profile:h,tier:y,optional_selections:x,explicit_optional_selections:E,official_plugins:K,capability_state:MS,managed_artifacts:Tr.managed_artifacts,installed_at:Zt,status:"active",step:"active",managed_config:Ka,plugin_snapshot:Ha,plugin_config:{plugin_id:Gt,before:Cr,after:Rl},provider_config:PS,owned_plugins:[...Qt],...q===void 0?{}:{tooling:q}};if(Ye(Pa,Ld)===void 0)return yield*p(new R("state_corrupt","The HolyCodex configuration is invalid."));return CS=!0,yield*d({try:()=>zc(i.activeRecord,Wt(Ld)),catch:(U)=>U}),TS=!0,yield*xT(i,vT(h,y,x,_)),yield*fd(i.preparingRecord),yield*fd(i.conflictedRecord),er(t,{stage:"complete",status:"completed",message:"HolyCodex installation complete"}),{record:Ld,optional_plugins:K,preserved:Tr.preserved,warnings:[...Tr.preserved.length===0?[]:["modified managed files were preserved"],...F===void 0?[]:[F]]}}).pipe(Dr((P)=>v(function*(){let H=om(P),q=[],Se;if(CS){if(!(yield*Qn(f===void 0?$y(i.activeRecord):d({try:()=>ft(i.activeRecord,f),catch:(te)=>te}))).ok)q.push("active_record")}if(TS){if(!(yield*Qn(o===void 0?$y(i.installOptions):d({try:()=>ft(i.installOptions,o),catch:(te)=>te}))).ok)q.push("install_options")}if(_S||Od){let re=kr,te=yield*Qn(re===void 0?M(void 0):BD(i.configFile,fe,re,Md));if(te.ok)Se=te.value;else q.push("config")}if(vS){if(!(yield*Qn(OD(i.configFile,_n))).ok)q.push("invalid_config")}if(Tr!==void 0){let re=Tr.rollback,te=yield*Qn(d({try:()=>Kf(re),catch:(he)=>he}));if(!te.ok||te.value.preserved.length>0)q.push("roles")}if(Nd.size>0)q.push(...[...Nd].map((re)=>`plugin:${re}`));for(let re of bS)if(!(yield*Qn(O.remove===void 0?M(void 0):d({try:()=>O.remove(re),catch:(he)=>he}))).ok)q.push(`plugin:${re}`);for(let re of new Set([...Ad,...kl]))if((yield*Qn(v(function*(){yield*GD({list:()=>O.list(),add:(he)=>O.add(he)},re,Ha.find((he)=>he.plugin_id===re)?.status),yield*Fn(i.preparingRecord,{...fe,owned_plugins:[...Qt,re]})}))).ok)Ad.delete(re),kl.delete(re),Qt.add(re),fe={...fe,owned_plugins:[...Qt]};else Qt.add(re),kl.add(re),fe={...fe,owned_plugins:[...Qt]},yield*Je(Fn(i.preparingRecord,fe)),q.push(`plugin:${re}`);if(D?.ownership==="holycodex"&&c?.tooling?.context7?.ownership!=="holycodex"){let re=yield*Qn(d({try:()=>Qc(C,D),catch:(te)=>te}));if(!re.ok||!re.value)q.push("context7")}if(q.length===0&&Xt===void 0){if(!(yield*Qn(v(function*(){if((yield*d({try:()=>Ee(i.configFile),catch:(he)=>he}))?.trim().length===0&&(yield*WD(i.configFile,Se??wS)))yield*d({try:()=>By(i.configFile,{force:!1}),catch:(he)=>he})}))).ok)q.push("config_initialization")}if(q.length>0){let re=yield*Qn(v(function*(){let Ae=Lt(yield*d({try:()=>Ee(i.configFile),catch:(ir)=>ir}),i.configFile),ct=fe.plugin_config,ti=yield*cd(Ae),vt=ct===void 0?void 0:{...ct,after:{preference:ti.preference.digest===ct.before.preference.digest?ct.before.preference:ct.after.preference,marketplace:ti.marketplace.digest===ct.before.marketplace.digest?ct.before.marketplace:ct.after.marketplace}},Li=fe.provider_config,ni=yield*ld(Ae,Li?.map((ir)=>ir.plugin_id)??[]),Oo=Li?.map((ir)=>{let Ga=ni.find((Dd)=>Dd.plugin_id===ir.plugin_id);return Ga!==void 0&&Ga.before.digest===ir.before.digest?{...ir,after:ir.before}:ir});fe={...fe,...vt===void 0?{}:{plugin_config:vt},...Oo===void 0?{}:{provider_config:Oo}}})),te=!1;if(te=(yield*Qn(Fn(i.conflictedRecord,{...fe,step:"conflicted",status:"conflicted"}))).ok,te)yield*Je(fd(i.preparingRecord))}else yield*Je(fd(i.preparingRecord));if(H instanceof Ci)return yield*p(H);if(H instanceof R)return yield*p(H);return yield*p(new R(H instanceof vr||H instanceof Yr?"capability_denied":"install_failed",ul(H),H,q.length>0?{recovery:"Resolve conflicted state before retrying."}:{}))}).pipe(eb)))})}function Vy(e){return v(function*(){let t=yield*d({try:()=>iy(e.activeRecord,Vf),catch:(O)=>O});if(t===void 0)return;let n=Ye(Pa,t);if(n!==void 0){if(!(yield*pd(n)))return yield*p(new R("state_corrupt","The existing HolyCodex configuration has an invalid digest."));return yield*d({try:()=>Jc(e.activeRecord,t),catch:(O)=>O}),n}let r=Ye(hC,t);if(r===void 0)return yield*p(new R("state_corrupt","The HolyCodex configuration is invalid."));if(!(yield*pd(r)))return yield*p(new R("state_corrupt","The existing HolyCodex configuration has an invalid digest.",void 0,{path:e.activeRecord}));let i="profile"in r&&r.profile!==void 0?r.profile:("plan"in r)?r.plan:void 0;if(i===void 0)return yield*p(new R("state_corrupt","The persisted installation has neither profile nor legacy plan state.",void 0,{path:e.activeRecord}));let o=Oe(V({try:()=>cf(i),catch:(O)=>new R("state_corrupt",`The persisted profile ${i} was removed and requires an explicit replacement.`,O,{path:e.activeRecord,profile:i})})),a="plan"in r?Object.fromEntries(Object.entries(r).filter(([O])=>O!=="plan")):r,{optional_selections:s,explicit_optional_selections:c}=r,f={browser_use:("browser_use"in s?s.browser_use:void 0)??Mt.browser_use,computer_use:s.computer_use,sites:("sites"in s?s.sites:void 0)??Mt.sites,coding:!0},l={...c.computer_use===void 0?{}:{computer_use:c.computer_use},...!("browser_use"in c)||c.browser_use===void 0?{}:{browser_use:c.browser_use},...!("sites"in c)||c.sites===void 0?{}:{sites:c.sites}},u=r.capability_state===void 0?void 0:dd(f,new Map([["browser_use","missing"],["sites","missing"]])),g=(r.official_plugins??[]).filter((O)=>!ll(O)),h=r.owned_plugins?.filter((O)=>!ll(O)),y=r.provider_config?.filter((O)=>!ll(O.plugin_id)),S=r.plugin_snapshot?.filter((O)=>!ll(O.plugin_id)),{optional_selections:m,explicit_optional_selections:x,capability_state:E,official_plugins:_,owned_plugins:C,provider_config:N,plugin_snapshot:D,...F}=a,K={...F,profile:o,optional_selections:f,explicit_optional_selections:l,official_plugins:g,...u===void 0?{}:{capability_state:u},...h===void 0?{}:{owned_plugins:h},...y===void 0?{}:{provider_config:y},...S===void 0?{}:{plugin_snapshot:S},digest:yield*md({owner:r.owner,install_id:r.install_id,version:r.version,profile:o,tier:r.tier,optional_selections:f,explicit_optional_selections:l,official_plugins:g,capability_state:u??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},...y===void 0?{}:{provider_config:y},...S===void 0?{}:{plugin_snapshot:S},...h===void 0?{}:{owned_plugins:h},...r.tooling===void 0?{}:{tooling:r.tooling}})};return gT.set(K,r.digest),yield*d({try:()=>Jc(e.activeRecord,t),catch:(O)=>O}),K})}function Ly(e,t){return v(function*(){let n=yield*d({try:()=>iy(e,Vf),catch:(_)=>_});if(n===void 0)return;let r=Ye(ki,n);if(r!==void 0)return yield*d({try:()=>Jc(e,n),catch:(_)=>_}),r;let i=Ye(xC,n);if(i===void 0)return yield*p(new R("state_corrupt","The HolyCodex transaction state is invalid.",void 0,{path:e}));let o=("profile"in i?i.profile:void 0)??("plan"in i?i.plan:void 0);if(o===void 0)return yield*p(new R("state_corrupt","The HolyCodex transaction has no profile.",void 0,{path:e}));let a=Oe(V({try:()=>cf(o),catch:(_)=>new R("state_corrupt","The persisted transaction profile requires an explicit replacement.",_,{path:e,profile:o})})),{optional_selections:s,explicit_optional_selections:c}=i,f={browser_use:("browser_use"in s?s.browser_use:void 0)??Mt.browser_use,computer_use:s.computer_use??!1,sites:("sites"in s?s.sites:void 0)??Mt.sites,coding:!0},l={...!("browser_use"in c)||c.browser_use===void 0?{}:{browser_use:c.browser_use},...c.computer_use===void 0?{}:{computer_use:c.computer_use},...!("sites"in c)||c.sites===void 0?{}:{sites:c.sites}},g=i.capability_state===void 0?void 0:dd(f,new Map([["browser_use","missing"],["sites","missing"]])),h="profile"in i?(({profile:_,...C})=>C)(i):("plan"in i)?(({plan:_,...C})=>C)(i):i,y=h.digest,S=t===void 0?void 0:gT.get(t),m=t!==void 0&&h.install_id===t.install_id&&(y===t.digest||S!==void 0&&y===S)?t.digest:y,x={...h,profile:a,optional_selections:f,explicit_optional_selections:l,...g===void 0?{}:{capability_state:g},...m===void 0?{}:{digest:m}},E=Ye(ki,x);if(E===void 0)return yield*p(new R("state_corrupt","The migrated transaction state is invalid.",void 0,{path:e}));return yield*d({try:()=>Jc(e,n),catch:(_)=>_}),E})}function _T(e){return{browser_use:e.browser_use,computer_use:e.computer_use,sites:e.sites}}function Lt(e,t="config.toml"){if(e===void 0||e.trim().length===0)return{};return Oe(V({try:()=>{let n=globalThis.Bun,r=n?.TOML?.parse?n.TOML.parse(e):Bc(e),i=Ye(vi,r);if(i===void 0){let o=Uy(r),a=o===void 0?"an unsupported TOML value":`the TOML value ${o}`;throw new R("state_corrupt",`${t} contains ${a} that HolyCodex cannot preserve. Convert it to a string, number, boolean, table, or array, then retry.`,void 0,{path:t,...o===void 0?{}:{key:o},reason:"unsupported_toml_value"})}return i},catch:(n)=>{if(n instanceof R)return n;let r=ul(n),i=AD(e,r),o=i===void 0?`${t} contains invalid TOML: ${r}. Fix the TOML syntax and retry; HolyCodex cannot safely rewrite malformed TOML.`:`${t} contains invalid TOML at line ${i.line}, column ${i.column} (offset ${i.offset}): ${r}. Fix the syntax at that location and retry; HolyCodex cannot safely rewrite malformed TOML.`;return new R("state_corrupt",o,n,{path:t,parser_message:r,...i===void 0?{}:i,reason:"invalid_toml_syntax"})}}))}function Uy(e,t=[]){if(e===null||typeof e==="string"||typeof e==="boolean")return;if(typeof e==="number")return Number.isFinite(e)?void 0:Ay(t);if(Array.isArray(e)){for(let[n,r]of e.entries()){let i=Uy(r,[...t,"["+n+"]"]);if(i!==void 0)return i}return}if(typeof e==="object"&&e!==null){let n=Object.getPrototypeOf(e);if(n!==Object.prototype&&n!==null)return Ay(t);for(let[r,i]of Object.entries(e)){let o=Uy(i,[...t,r]);if(o!==void 0)return o}return}return Ay(t)}function Ay(e){return e.length===0?"<root>":e.join(".")}function kD(e,t){let n=new Map;for(let r of t)for(let i of RD(r)){let o=pe(e,i);if(o!==void 0&&!Zr(o))n.set(i,o)}return[...n].map(([r,i])=>({key:r,value:i}))}function RD(e){let t=[],n=!1,r=!1;for(let i=0;i<e.length;i+=1){let o=e[i];if(n){if(r)r=!1;else if(o==="\\")r=!0;else if(o==='"')n=!1;continue}if(o==='"')n=!0;else if(o===".")t.push(e.slice(0,i))}return t}function ID(e,t){let n=JSON.stringify(t.value);return new R("state_corrupt",`${e} has the non-table value ${n} at ${t.key}, but the HolyCodex installer needs that path to be a table. Remove it after review or convert it to a table and retry; replacing it automatically could discard user configuration.`,void 0,{path:e,key:t.key,existing:n,reason:"expected_table"})}function PD(e,t,n,r){return v(function*(){let i=kD(n,r).map((a)=>{let s=ID(t,a);return Ln({identity:`invalid-config:${t}:${a.key}`,category:"invalid-config",target:a.key,existing:a.value,desired:`Remove the conflicting value at ${a.key} so HolyCodex can create the required table.`,explanation:`${s.message} Choose remove to continue or cancel to repair it manually.`,path:t,key:a.key,action:"remove",defaultDecision:"remove",validDecisions:["remove","cancel"]})});if(i.length===0)return{document:n,conflicts:i,decisions:new Map};let o=yield*fl(e,i,!0);return{document:$a(n,i,o.decisions),conflicts:i,decisions:o.decisions}})}function $a(e,t,n){let r=e;for(let i of t){if(n.get(i.identity)!=="remove"||i.key===void 0)throw new R("confirmation_required",`Invalid configuration at ${i.target} can only be removed after review or cancelled.`,void 0,{path:i.path,...i.key===void 0?{}:{key:i.key},existing:JSON.stringify(i.existing),valid_decisions:i.validDecisions??["remove","cancel"]});let a=pe(r,i.key);if(a===void 0)continue;if(JSON.stringify(a)!==JSON.stringify(i.existing))throw new R("confirmation_required",`Invalid configuration at ${i.key} changed after review; review the current value and retry.`,void 0,{path:i.path,key:i.key,reviewed:JSON.stringify(i.existing),current:JSON.stringify(a)});r=vn(r,i.key)}return r}function My(e,t,n){return v(function*(){if((yield*d({try:()=>Ee(e),catch:(r)=>r}))!==n)return yield*p(new R("confirmation_required","Codex configuration changed during preflight validation; review the latest configuration and retry.",void 0,{path:e}));if(t===void 0){yield*$y(e);return}yield*d({try:()=>ft(e,t),catch:(r)=>r})})}function OD(e,t){return v(function*(){let n=yield*d({try:()=>Ee(e),catch:(o)=>o}),r=Lt(n,e),i=r;for(let o of t){if(o.key===void 0||o.existing===void 0)continue;let a=pe(i,o.key);if(a!==void 0){if(JSON.stringify(a)===JSON.stringify(o.existing))continue;if(!(typeof a==="object"&&a!==null&&!Array.isArray(a)&&Object.keys(a).length===0))return yield*p(new R("confirmation_required",`Codex configuration at ${o.key} changed during rollback; preserve it and review the current value.`,void 0,{path:e,key:o.key}));i=vn(i,o.key)}i=Gn(i,o.key,o.existing)}if(i===r)return;if((yield*d({try:()=>Ee(e),catch:(o)=>o}))!==n)return yield*p(new R("confirmation_required","Codex configuration changed during rollback; preserve it and review the current value.",void 0,{path:e}));yield*d({try:()=>ft(e,_r(i)),catch:(o)=>o})})}function AD(e,t){let n,r=/found \(0x([0-9a-f]{2})\)/iu.exec(t),i=/found '((?:\\.|[^'])*)'/u.exec(t),o=r===null?i?.[1]?.replaceAll("\\'","'").replaceAll("\\\"",'"'):String.fromCharCode(Number.parseInt(r[1],16));if(o!==void 0)n=MD(e,o);else if(/end of file|unterminated/iu.test(t))n=e.length;else if(/missing value after/iu.test(t)){let c=e.lastIndexOf("="),f=c<0?-1:e.indexOf(`
34
+ `,c+1);n=f<0?e.length:f}if(n===void 0)return;let a=e.slice(0,n).split(`
43
35
  `).length,s=e.lastIndexOf(`
44
- `,Math.max(0,n-1));return{offset:n,line:a,column:n-s}}function PK(e,t){let n,r=!1,o=!1;for(let i=0;i<e.length;i+=1){let a=e[i];if(o){if(a===`
45
- `)o=!1;continue}if(n!==void 0){if(n==='"'&&r)r=!1;else if(n==='"'&&a==="\\")r=!0;else if(a===n)n=void 0;continue}if(a==="#"){o=!0;continue}if(e.startsWith(t,i))return i;if(a==='"'||a==="'")n=a}return}async function MK(e,t,n){let r=typeof t.details.key==="string"?t.details.key:void 0,o=typeof t.details.offset==="number"?String(t.details.offset):void 0,i=cr({identity:"invalid-config:"+n+":"+(o??r??"unsupported"),category:"invalid-config",target:r===void 0?n+" syntax":n+" value "+r,existing:t.details,desired:"Repair the TOML value before installing HolyCodex.",explanation:t.message,path:n,...r===void 0?{}:{key:r},action:"replace",defaultDecision:"cancel",validDecisions:["cancel"]});try{await jd(e,[i],!0)}catch{}}function fo(e){try{let t=globalThis.Bun;return`${((t?.TOML?.stringify)?t.TOML.stringify(e):wd(e)).trimEnd()}
46
- `}catch(t){throw new _("install_failed","The merged Codex configuration is not writable.",t)}}async function og(e){return{preference:await vs(e,"plugins",ws),marketplace:await vs(e,"marketplaces",_s)}}async function ig(e,t){return await Promise.all(t.map(async(n)=>{let r=await vs(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 Yc(e,t,n={}){let r=e,o=[],i=[],a=[];for(let[s,c,l]of[["preference","plugins",ws],["marketplace","marketplaces",_s]]){let u=t.before[s],d=t.after[s],p=await vs(e,c,l);if(n.allowBeforeState===!0&&p.digest===u.digest)continue;if(p.digest!==d.digest){a.push(s);continue}if(u.presence==="absent"){if(p.presence==="present")r=Xv(r,c,l),i.push(s);continue}if(u.safe_value===void 0){a.push(s);continue}r=mo(r,c,l,FK(u.safe_value)),o.push(s)}return{document:r,restored:o,removed:i,preserved:a}}async function Zc(e,t,n,r={}){let o=e,i=[],a=[],s=[];for(let c of t){if(!n.has(c.plugin_id))continue;let{before:l,after:u}=c,d=await vs(e,"plugins",c.plugin_id);if(r.allowBeforeState===!0&&d.digest===l.digest)continue;if(d.digest!==u.digest){s.push(c.plugin_id);continue}if(l.presence==="absent"){if(d.presence==="present")o=Xv(o,"plugins",c.plugin_id),a.push(c.plugin_id);continue}if(l.safe_value===void 0){s.push(c.plugin_id);continue}o=mo(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 WF(e,t,n,r,o,i){if(o.presence!=="present"||o.safe_value!==void 0)return{document:e,restored:!1};let a=await vs(e,n,r);if(a.digest===o.digest||a.digest!==i.digest)return{document:e,restored:!1};let s=Hd(t,n,r);if(s===void 0)return{document:e,restored:!1};return{document:mo(e,n,r,s),restored:!0}}async function vs(e,t,n){let r=Hd(e,t,n),o=await qn("holycodex-plugin-config",[Dn(sn({key:`${t}.${n}`,value:r===void 0?{presence:"absent"}:r}))]),i=NK(t,r);return{presence:r===void 0?"absent":"present",digest:o,...i===void 0?{}:{safe_value:i}}}function Hd(e,t,n){let r=e[t];if(!ii(r)||!Object.hasOwn(r,n))return;return r[n]}function NK(e,t){if(!ii(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!==ni)return;return{kind:"marketplace",source_type:"git",source:ni}}function FK(e){if(e.kind==="boolean")return{enabled:e.value};return{source_type:e.source_type,source:e.source}}function mo(e,t,n,r){let o={...e},i=o[t];if(i!==void 0&&!ii(i))throw new _("state_corrupt",`The ${t} Codex config table is invalid.`);return o[t]={...i,[n]:r},o}function Xv(e,t,n){let r=e[t];if(!ii(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 ii(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}async function LK(e,t,n){let r=[{parent:"plugins",key:ws,expected:t.preference},{parent:"marketplaces",key:_s,expected:t.marketplace},...n.map(({plugin_id:o,before:i})=>({parent:"plugins",key:o,expected:i}))];for(let{parent:o,key:i,expected:a}of r)if((await vs(e,o,i)).digest!==a.digest)throw new _("confirmation_required","Plugin configuration changed after preflight; review the latest configuration and retry.",void 0,{key:`${o}.${i}`})}async function zF(e,t,n,r,o,i,a,s,c,l){let u=e,d=n,p=r;for(let m of a){let f=m.identity;if(f===void 0)throw new _("state_corrupt","A plugin configuration conflict has no identity.");let y=c.get(f);if(y!=="keep"&&y!=="replace")throw new _("confirmation_required",`Plugin configuration conflict resolution is incomplete for ${m.key??f}.`);let g=m.key==='plugins."holycodex@holycodex"'?"preference":"marketplace",x=o[g];if(y==="keep"){let v=Hd(t,"plugins",ws);if(g==="preference"&&ii(v)&&v.enabled===!1)throw new _("confirmation_required","Keeping disabled HolyCodex config would disable the selected plugin.");u=KF(u,t,m.key),d={...d,[g]:x};continue}u=mo(u,g==="preference"?"plugins":"marketplaces",g==="preference"?ws:_s,g==="preference"?{enabled:!0}:{source_type:"git",source:ni})}for(let m of s){let{identity:f,key:y}=m;if(f===void 0||y===void 0)throw new _("state_corrupt","A provider configuration conflict has no identity.");let g=y.startsWith('plugins."')&&y.endsWith('"')?y.slice(9,-1):void 0;if(g===void 0)throw new _("state_corrupt",`The provider configuration conflict key ${y} is invalid.`);let x=c.get(f);if(x!=="keep"&&x!=="replace")throw new _("confirmation_required",`Provider configuration conflict resolution is incomplete for ${y}.`);let v=i.find((C)=>C.plugin_id===g);if(v===void 0)throw new _("state_corrupt",`The provider configuration entry ${g} is missing.`);if(x==="keep"){let C=Hd(t,"plugins",g);if(l.includes(g)&&ii(C)&&C.enabled===!1)throw new _("confirmation_required",`Keeping disabled config would disable selected plugin ${g}.`);u=KF(u,t,y),p=p.map((M)=>M.plugin_id===g?{plugin_id:g,before:v.before,after:v.before}:M);continue}u=mo(u,"plugins",g,{enabled:!0})}return{document:u,pluginConfigBefore:d,providerConfigBefore:p}}function KF(e,t,n){if(n===void 0)throw new _("state_corrupt","A configuration conflict has no key.");if(n.startsWith('plugins."')&&n.endsWith('"')){let o=n.slice(9,-1),i=Hd(t,"plugins",o);return i===void 0?Xv(e,"plugins",o):mo(e,"plugins",o,i)}let r=fe(t,n);return r===void 0?tr(e,n):so(e,n,r)}async function DK(e,t,n,r){let o={...n};if(r===void 0)return o;for(let i of Object.keys(n)){let a=i,s=t.managed[a],c=r[a];if(s===void 0||c===void 0)continue;let l=await _n(a,c);if(JSON.stringify(l)===JSON.stringify(s.lastManagedValue))continue;let u=fe(e,a);if(typeof u!=="string"&&typeof u!=="number"&&typeof u!=="boolean")continue;let d=await _n(a,u);if(JSON.stringify(d)===JSON.stringify(s.lastManagedValue))delete o[a]}return o}function Ld(e,t,n=!1){let r=Tv(e,t),o=typeof n==="boolean"?{}:n,i={browserUse:o.browserUse??en.browser_use,computerUse:typeof n==="boolean"?n:o.computerUse??en.computer_use},a=fs(e,t,i),s={model:r.model,model_reasoning_effort:r.effort,service_tier:r.serviceTier,"agents.max_concurrent_threads_per_session":21,web_search:"live","sandbox_workspace_write.network_access":!0,model_verbosity:"low",developer_instructions:Cv({...typeof n==="boolean"?{computerUse:n}:n,rootModel:r.model}),suppress_unstable_features_warning:!0,"features.multi_agent":!0,"features.default_mode_request_user_input":!0,"features.multi_agent_v2":!1,"features.agent_message_board":!1,"features.context_management.experimental_mode":!0};for(let c of Go)s[`agents."${c}".config_file`]=Td(c,a);return s}async function JF(e,t,n,r){let o=[];for(let i of Object.keys(r)){let a=i;if(n.managed[a]!==void 0){if((await ss(e,n,a)).status==="drifted")o.push(a);continue}let c=fe(t,a),l=fe(e,a),u=sn(c===void 0?null:c),d=sn(l===void 0?null:l);if(Ln(u)!==Ln(d))o.push(a)}if(o.length>0)throw new _("state_corrupt","Codex settings changed during native plugin setup.",void 0,{keys:o.join(",")})}async function Kv(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 Ar(e,{...t,managed:o},{schema:t.schema,installId:t.installId});if(c.preservedKeys.length>0||c.unresolvedKeys.length>0)throw new _("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((m)=>m.startsWith(`agents/${c[0]?.toUpperCase()}${c.slice(1)}.`)||m===`holycodex/agents/${c}.toml`))continue;let u=`agents.${c}.config_file`,d=fe(i,u);if(typeof d!=="string")continue;let p=d.replaceAll("\\","/").replace(/^\.\//u,"");if(p===`agents/${c}.toml`||p===`holycodex/agents/${c}.toml`)i=tr(i,u)}return{document:i,state:a}}async function Jv(e,t){let n=t.managed[Vv];if(n===void 0)return{document:e,state:t};let r=await Ar(e,{...t,managed:{[Vv]:n}},{schema:t.schema,installId:t.installId}),o=Object.fromEntries(Object.entries(t.managed).filter(([i])=>i!==Vv));return{document:r.document,state:{...t,managed:o}}}async function ag(e,t){let n=Object.fromEntries(Object.entries(t.managed).filter(([i])=>Zi.includes(i)));if(Object.keys(n).length===0)return{document:e,state:t};let r=await Ar(e,{...t,managed:n},{schema:t.schema,installId:t.installId}),o=Object.fromEntries(Object.entries(t.managed).filter(([i])=>!(i in n)));return{document:r.document,state:{...t,managed:o}}}function qK(e,t){if(fe(e,"developer_instructions")!==void 0&&t.managed.developer_instructions===void 0)throw new _("state_corrupt","Existing developer_instructions cannot be displaced safely; remove it or converge managed state first.")}async function UK(e,t){let n=await e.list();return t.map((r)=>{let o=Lr(n,r),i=o===void 0?"missing":o.installed&&o.enabled?"installed":o.installed?"disabled":"available";return{plugin_id:r,status:i}})}async function sr(e,t){if(Ie(ta,t)===void 0)throw new _("state_corrupt","The HolyCodex transaction state is invalid.");await jc(e,sn(t))}async function sg(e){await $d(e,{force:!1}).catch((t)=>{if(!We(t,"ENOENT"))throw t})}async function $K(e,t,n,r){let o=await ye(e);if(o===void 0)return;let i=Jt(o,e),a={},s=0;for(let[m,f]of Object.entries(t.managed_config.managed)){let y=m,g=fe(n,y),x=g===void 0?void 0:await _n(y,g);if(JSON.stringify(x??null)===JSON.stringify(f.lastManagedValue))continue;if(g!==void 0&&x?.kind==="digest"){let v=fe(i,y);if(v!==void 0&&JSON.stringify(await _n(y,v))===JSON.stringify(f.lastManagedValue))i=so(i,y,g),s+=1;continue}a[m]={...f,originalValue:x??{kind:"absent"}}}let c=await Ar(i,{...t.managed_config,managed:a},{schema:On,installId:t.install_id});i=c.document;let l=t.plugin_config===void 0?void 0:await Yc(i,t.plugin_config,{allowBeforeState:!0});if(l!==void 0)i=l.document;let u=t.provider_config===void 0?void 0:await Zc(i,t.provider_config,r,{allowBeforeState:!0});if(u!==void 0)i=u.document;if(t.plugin_config!==void 0)for(let[m,f,y]of[["preference","plugins",ws],["marketplace","marketplaces",_s]]){let g=await WF(i,n,f,y,t.plugin_config.before[m],t.plugin_config.after[m]);if(i=g.document,g.restored)s+=1}if(t.provider_config!==void 0)for(let m of t.provider_config){if(!r.has(m.plugin_id))continue;let f=await WF(i,n,"plugins",m.plugin_id,m.before,m.after);if(i=f.document,f.restored)s+=1}if(!(c.restoredKeys.length>0||l!==void 0&&(l.restored.length>0||l.removed.length>0)||u!==void 0&&(u.restored.length>0||u.removed.length>0)||s>0))return;await vt(e,fo(i));let p=await YF(e);return p.isFile()&&!p.isSymbolicLink()?{dev:p.dev,ino:p.ino}:void 0}async function jK(e,t,n,r,o,i=[],a=Ld(t,n,r)){let s=await ye(e.configFile),c=Jt(s,e.configFile),l=a;for(let[f,y]of Object.entries(l)){let g=fe(c,f);if(f==="developer_instructions"){if(typeof g!=="string"||g!==y||await HK(f,g)!==o.managed[f]?.lastManagedValue.value)throw new _("install_failed","The effective Root instructions did not converge.")}else if(g!==y)throw new _("install_failed",`The effective Codex setting ${f} did not converge.`)}let u={browserUse:r.browserUse??en.browser_use,computerUse:r.computerUse},d=fs(t,n,u),p=ei(t,n);for(let f of p){let y=`agents."${f.name}".config_file`,g=fe(c,y);if(typeof g!=="string")throw new _("install_failed",`The ${f.name} registration is missing.`);let x=Td(f.name,d),v=as(e.configFile,x),C=v.replaceAll("\\","/");if(as(e.configFile,g).replaceAll("\\","/")!==C)throw new _("install_failed",`The ${f.name} registration is stale (expected ${x}; received ${g}).`);let N=await ye(v);if(N===void 0)throw new _("install_failed",`The ${f.name} role file is missing.`);if(i.some((k)=>k.replaceAll("\\","/")===C))throw new _("install_failed",`The ${f.name} role file was kept after a conflict and cannot be activated.`);let O=Jt(N,v);if(O.name!==f.name||typeof O.description!=="string"||typeof O.model!=="string"||typeof O.model_reasoning_effort!=="string"||typeof O.service_tier!=="string"||typeof O.developer_instructions!=="string"||!zh(f,O)||O.approval_policy!=="never"||O.web_search!==(f.permissions.network?"live":"disabled")||O.tool_output_token_limit!==void 0||fe(O,"agents.enabled")!==!1||fe(O,"features.multi_agent")!==!1||fe(O,"features.multi_agent_v2")!==!1||fe(O,"features.agent_message_board")!==!1||fe(O,"features.context_management.experimental_mode")!==!0||Object.keys(O.features??{}).some((k)=>!["multi_agent","multi_agent_v2","agent_message_board","context_management"].includes(k)))throw new _("install_failed",`The ${f.name} role file is malformed.`)}let m=await ye(`${e.codexHome}/agents/root.toml`);if(m!==void 0&&Wc(m))throw new _("install_failed","A stale HolyCodex Root role remains installed.")}async function HK(e,t){return await qn("holycodex-managed-config-value",[Dn({keyPath:e,value:t})])}function Gv(e,t){let n={};for(let r of["browser_use","computer_use","sites"]){let o=t?.[r]??e?.[r];if(o!==void 0)n[r]=o}return n}function BK(e){return["browser_use","computer_use","sites"].find((t)=>Wo[t].pluginIds.includes(e))}function Zv(e){return(e?.official_plugins??[]).filter((t)=>{if(t===ln)return!1;if(qd(t))return!1;let n=BK(t);return n===void 0||e?.optional_selections[n]!==!0})}async function VK(e){await $c(_K(e));let t;try{t=await wK(e,"wx",384)}catch(n){if(We(n,"EEXIST"))return;throw n}try{let n=await t.stat();return await t.sync(),{dev:n.dev,ino:n.ino}}finally{await t.close()}}async function WK(e,t){if(t===void 0)return!1;try{let n=await YF(e);return n.isFile()&&!n.isSymbolicLink()&&n.dev===t.dev&&n.ino===t.ino}catch(n){if(We(n,"ENOENT"))return!1;throw n}}function qd(e){let t=e.slice(0,e.lastIndexOf("@"));return TK.has(t)}async function zK(e,t,n=new Set,r){for(let o of t){let i=n.has(o),a;try{a=Lr(await e.list(),o)}catch(l){throw ri("list",l,o)}if(a?.installed&&!a.enabled)throw new oi("uncertain",`${o} is disabled`);let s=i||!(a?.installed&&a.enabled);if(s)try{await e.add(o)}catch(l){try{let u=Lr(await e.list(),o);if(i||!GF(a,u))await r?.(o,"uncertain")}catch{await r?.(o,"uncertain")}throw ri("add",l,o)}let c;try{c=Lr(await e.list(),o)}catch(l){if(s)await r?.(o,"uncertain");throw ri("list",l,o)}if(!c?.installed){if(s&&(i||!GF(a,c)))await r?.(o,"uncertain");throw new oi("missing",`${o} is not installed after add`)}if(s&&c.enabled)await r?.(o,i?"uncertain":"new");if(!c.enabled){if(s)await r?.(o,i?"uncertain":"new");throw new oi("uncertain",`${o} is disabled after add`)}}}async function KK(e,t,n){for(let r of t){let o;try{o=Lr(await e.list(),r)}catch(a){throw await n?.(r,"uncertain"),ri("list",a,r)}if(!(o?.installed??!1)){await n?.(r,"absent");continue}try{await e.remove(r)}catch(a){try{if(!(Lr(await e.list(),r)?.installed??!1))await n?.(r,"removed");else await n?.(r,"uncertain")}catch{await n?.(r,"uncertain")}throw ri("remove",a,r)}let i;try{i=Lr(await e.list(),r)}catch(a){throw await n?.(r,"uncertain"),ri("list",a,r)}if(i?.installed)throw await n?.(r,"uncertain"),new oi("uncertain",`${r} is still installed after remove`);await n?.(r,"removed")}}async function JK(e,t,n){if(n!=="installed"&&n!=="disabled")throw new oi("uncertain",`${t} has no proven prior installed state`);let r=n==="installed",o;try{o=Lr(await e.list(),t)}catch(a){throw ri("list",a,t)}if(o?.installed&&o.enabled===r)return;try{await e.add(t)}catch(a){throw ri("add",a,t)}let i;try{i=Lr(await e.list(),t)}catch(a){throw ri("list",a,t)}if(!i?.installed)throw new oi("missing",`${t} is not installed after restore`);if(i.enabled!==r)throw new oi("uncertain",`${t} did not regain its prior ${r?"enabled":"disabled"} state`)}function GF(e,t){return e?.pluginId===t?.pluginId&&e?.installed===t?.installed&&e?.enabled===t?.enabled&&e?.marketplaceName===t?.marketplaceName}function ri(e,t,n){if(t instanceof uo)return t;return new uo(e==="list"?"list_failed":e==="remove"?"remove_failed":"add_failed",e==="list"?`Codex could not read the status of ${n}.`:e==="remove"?`Codex could not remove ${n}.`:`Codex could not add ${n}.`,t,{plugin_id:n})}function Lr(e,t){let n=ao(e,t);if(n!==void 0)return n.entry;let r=Qn(t);return[...e.installed,...e.available].find((o)=>o.pluginId===t&&(r===void 0||o.marketplaceName==null))}function GK(e,t){let n=e??t??"default";if(!oo(n).ok)throw new _("install_failed","Unknown profile.");return n}function YK(e,t){let n=e??t??"standard";if(Ie(Ko,n)===void 0)throw new _("install_failed","The tier is not supported.");return n}function ZK(e,t){let n=t?oL(t):en,r=Ow(e,n);return{browser_use:r.browser_use,computer_use:r.computer_use,sites:r.sites,coding:!0}}function cg(e,t=new Map){return Object.fromEntries(["browser_use","computer_use","frontend","security","sites"].map((r)=>{let o=r==="frontend"||r==="security"?!0:e[r],i=r==="frontend"||r==="security"?void 0:t.get(r),a={selected:o,status:o?i??"healthy":"disabled",plugin_ids:[...Wo[r].pluginIds]};return[r,a]}))}async function lg(e){let{profile:t,plan:n,...r}=e,o=Object.fromEntries(Object.entries(n===void 0?{...r,profile:t}:{...r,plan:n}).filter(([,i])=>i!==void 0));return await qn("install-record",[Dn(sn(o))])}async function bs(e){return await iL(e)}async function iL(e){return await lg({owner:e.owner,install_id:e.install_id,version:e.version,...e.profile===void 0?{}:{profile:e.profile},...e.plan===void 0?{}:{plan:e.plan},tier:e.tier,optional_selections:e.optional_selections,explicit_optional_selections:e.explicit_optional_selections,official_plugins:e.official_plugins??[],capability_state:e.capability_state??null,managed_artifacts:e.managed_artifacts,...e.managed_config===void 0?{}:{managed_config:e.managed_config},...e.plugin_config===void 0?{}:{plugin_config:e.plugin_config},...e.provider_config===void 0?{}:{provider_config:e.provider_config},...e.plugin_snapshot===void 0?{}:{plugin_snapshot:e.plugin_snapshot},...e.owned_plugins===void 0?{}:{owned_plugins:e.owned_plugins},...e.tooling===void 0?{}:{tooling:e.tooling}})===e.digest}function Ud(e){return e instanceof Error?e.message.slice(0,256):"operation failed"}function XK(e){if(!(e instanceof Error))return!1;return/(?:^|[\n:])\s*-\s*`([^`]+)`\s+at\s+[^\r\n]*:\s*marketplace root does not contain a supported manifest/iu.exec(e.message)?.[1]==="holycodex"}function QK(e){return ii(e)&&Object.keys(e).length===2&&e.source_type==="git"&&typeof e.source==="string"&&Ch(e.source)}function eJ(e,t,n){let r=[{name:"context7",status:e?"ready":"unavailable"}];for(let o of n){let i=Lr(t,o),a=i===void 0?"missing":i.installed?i.enabled?"installed":"disabled":"available";r.push({name:`official-plugin:${o}`,status:a,...typeof i?.version==="string"?{detail:i.version}:{}})}return r}function cr(e){let t=e.category??(e.key===void 0?"role-asset":"config-key"),n=e.target??e.key??e.path,r=e.identity??`${t}:${e.path}:${e.key??""}:${e.action}`,o=e.action==="remove"?["keep","remove","cancel"]:["keep","replace","cancel"],i=e.action==="remove"&&e.validDecisions?.includes("replace")===!0&&e.validDecisions.includes("remove")===!1?o:e.validDecisions??o,a=e.defaultDecision!==void 0&&i.includes(e.defaultDecision)?e.defaultDecision:i.includes(e.action)?e.action:i[0]??e.action;return{...e,identity:r,category:t,target:n,defaultDecision:a,validDecisions:i,explanation:e.explanation??(e.action==="remove"?`HolyCodex can remove the managed ${n} after reviewing this change.`:`HolyCodex can replace the managed ${n} after reviewing this change.`)}}async function jd(e,t,n=!1){let r=t.map(cr),o=new Map;if(r.length===0)return{accepted:[],decisions:o};if(e.resolveConflicts!==void 0){let a;try{a=await e.resolveConflicts(r)}catch(s){if(!(s instanceof _)||s.code!=="confirmation_required")throw s;let c=r.map((l)=>{let u=l.category==="invalid-config"&&l.key!==void 0&&l.existing!==void 0?` = ${JSON.stringify(l.existing)}`:"";return`${l.target} at ${l.path}${u}`}).join("; ");throw new _("confirmation_required",`${s.message} Conflicts: ${c}.`,s,{conflicts:c})}for(let s of r){let c=s.identity,l=Ie(nF,a[c]);if(l===void 0||s.validDecisions?.includes(l)===!1){let u=s.validDecisions?.join(", ")??"keep, replace, cancel";throw new _("confirmation_required",`The conflict at ${s.target} requires one of these decisions: ${u}.`,void 0,{identity:c,path:s.path,...s.key===void 0?{}:{key:s.key}})}if(l==="cancel")throw new _("confirmation_required",`Conflict resolution was cancelled for ${s.target} at ${s.path}.`,void 0,{identity:c,path:s.path,...s.key===void 0?{}:{key:s.key}});o.set(c,l)}return{accepted:r.filter((s)=>o.get(s.identity)===(s.action==="remove"?"remove":"replace")),decisions:o}}let i=[];for(let a of r){let s=await e.resolveConflict?.(a);if(s==="accept"){let c=a.action==="remove"?"remove":"replace";if(a.validDecisions?.includes(c)===!1)throw new _("confirmation_required",`The conflict at ${a.target} cannot be ${c}d; choose ${a.validDecisions?.join(", ")}.`,void 0,{identity:a.identity,path:a.path,...a.key===void 0?{}:{key:a.key}});i.push(a),o.set(a.identity,c);continue}if(s==="decline"&&n){if(a.validDecisions?.includes("keep")===!1)throw new _("confirmation_required",`The conflict at ${a.target} cannot be kept; choose ${a.validDecisions?.join(", ")}.`,void 0,{identity:a.identity,path:a.path,...a.key===void 0?{}:{key:a.key}});o.set(a.identity,"keep");continue}throw new _("confirmation_required",s==="cancel"?`Conflict resolution was cancelled for ${a.target} at ${a.path}.`:`Conflict resolution is required for ${a.target} at ${a.path}: ${a.explanation}.`,void 0,{path:a.path,...a.key===void 0?{}:{key:a.key},action:a.action,resolution:s??"unavailable"})}return{accepted:i,decisions:o}}function Fr(e,t){try{e.onProgress?.(t)}catch{}}var VF="davidbasilefilho/holycodex",un="holycodex@holycodex",ln="browser@openai-bundled",vK="0.16.8",RK="0.16.9",ZF,ni="https://github.com/davidbasilefilho/holycodex.git",ws="holycodex@holycodex",_s="holycodex",TK,Vv,oi,_;var Dd=w(()=>{cs();ht();hd();Rd();Kh();Od();ds();ls();Hc();Zh();ls();ZF=new WeakMap;TK=new Set(["documents","pdf","presentations","spreadsheets","template-creator"]),Vv=Zi[0];oi=class oi extends Error{status;constructor(e,t){super(t);this.name="PluginVerificationError",this.status=e}};_=class _ 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 YJ}from"readline/promises";cs();ht();ht();ht();var av=Object.freeze([{name:"yes",kind:"boolean",usage:"--yes",description:"Confirm installation."},{name:"profile",kind:"value",usage:"--profile <low|default|high>",description:"Select routing (default: default)."},{name:"tier",kind:"value",usage:"--tier <standard|fast|fast-all>",description:"Select service handling (default: standard)."},{name:"sites",kind:"boolean",usage:"--sites / --no-sites",description:"ChatGPT Sites (default: true)."},{name:"browser-use",kind:"boolean",usage:"--browser-use / --no-browser-use",description:"Browser Use (default: true)."},{name:"computer-use",kind:"boolean",usage:"--computer-use / --no-computer-use",description:"Computer Use plugins (default: false)."},{name:"add-plugin",kind:"value",usage:"--add-plugin <id>",description:"Add a Codex plugin; repeatable."},{name:"json",kind:"boolean",usage:"--json",description:"Emit one JSON envelope."}]),Q0=new Set(["codex-home","profile","tier","add-plugin"]),SW=new Set(["yes","json","verbose","dry-run","computer-use","no-computer-use","sites","no-sites","browser-use","no-browser-use"]);class lt extends Error{code;details;constructor(e,t,n={}){super(t);this.name="ArgumentError",this.code=e,this.details=n}}function Lh(e){if(e.length===0)throw new lt("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 Lh(["version",...e.slice(1)]);let t=e[0];if(t!=="install"&&t!=="doctor"&&t!=="remove"&&t!=="version")throw new lt("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 lt("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 lt("invalid_argument","The --plan option was removed; use --profile <low|default|high>.",{option:"--plan",replacement:"--profile"});if(!Q0.has(u)&&!SW.has(u))throw new lt("invalid_argument","Unknown option.",{option:`--${c}`});if(Q0.has(u)){let d=l??e[o+1];if(d===void 0||d.length===0||d.startsWith("-"))throw new lt("invalid_argument",`Option --${c} requires a value.`,{option:`--${c}`});if(l===void 0)o+=1;if(u==="add-plugin"){let p=r[u];r[u]=Array.isArray(p)?[...p,d]:[d]}else{if(r[u]!==void 0)throw new lt("invalid_argument",`Option --${c} may only be supplied once.`,{option:`--${c}`});r[u]=d}continue}if(l!==void 0&&l!=="true"&&l!=="false")throw new lt("invalid_argument",`Option --${c} is boolean.`,{option:`--${c}`});if(r[u]!==void 0)throw new lt("invalid_argument",`Option --${c} may only be supplied once.`,{option:`--${c}`});r[u]=l==="false"?!1:!0}return bW(t,n,r),{command:t,positionals:n,options:r}}function bW(e,t,n){let r=_W(e);for(let s of Object.keys(n))if(!r.has(s))throw new lt("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 lt("invalid_argument",`Invalid positional arguments for ${e}.`);let i=n.profile;if(typeof i==="string"&&!oo(i).ok){let s=wW[i];if(s!==void 0)throw new lt("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 lt("invalid_argument",`Legacy profile ${i} was removed and requires an explicit replacement using --profile <low|default|high>.`,{profile:i});throw new lt("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 lt("invalid_argument","The tier is not supported.",{tier:a});for(let[s,c]of[["computer-use","no-computer-use"],["sites","no-sites"],["browser-use","no-browser-use"]])if(n[s]!==void 0&&n[c]!==void 0)throw new lt("invalid_argument",`Conflicting --${s} and --${c} options.`);if(["install","remove"].includes(e)&&n.yes===!1)throw new lt("invalid_argument","--yes cannot be false.");if(e!=="install"&&Object.keys(n).some((s)=>["profile","tier","sites","no-sites","browser-use","no-browser-use","computer-use","no-computer-use","add-plugin"].includes(s)))throw new lt("invalid_argument",`Installation options are not valid for ${e}.`)}var wW={"plus-low":"low",plus:"default","plus-high":"high"};function _W(e){switch(e){case"install":return new Set([...av.map((t)=>t.name),"no-sites","no-browser-use","no-computer-use","codex-home","verbose"]);case"doctor":return new Set(["json","verbose","codex-home"]);case"remove":return new Set(["yes","json","verbose","codex-home"]);case"version":return new Set(["json","verbose","dry-run"]);default:return new Set}}var vW=`HolyCodex
36
+ `,Math.max(0,n-1));return{offset:n,line:a,column:n-s}}function MD(e,t){let n,r=!1,i=!1;for(let o=0;o<e.length;o+=1){let a=e[o];if(i){if(a===`
37
+ `)i=!1;continue}if(n!==void 0){if(n==='"'&&r)r=!1;else if(n==='"'&&a==="\\")r=!0;else if(a===n)n=void 0;continue}if(a==="#"){i=!0;continue}if(e.startsWith(t,o))return o;if(a==='"'||a==="'")n=a}return}function ND(e,t,n){return v(function*(){let r=typeof t.details.key==="string"?t.details.key:void 0,i=typeof t.details.offset==="number"?String(t.details.offset):void 0,o=Ln({identity:"invalid-config:"+n+":"+(i??r??"unsupported"),category:"invalid-config",target:r===void 0?n+" syntax":n+" value "+r,existing:t.details,desired:"Repair the TOML value before installing HolyCodex.",explanation:t.message,path:n,...r===void 0?{}:{key:r},action:"replace",defaultDecision:"cancel",validDecisions:["cancel"]});yield*Je(fl(e,[o],!0))})}function _r(e){return Oe(V({try:()=>{let t=globalThis.Bun;return`${((t?.TOML?.stringify)?t.TOML.stringify(e):Vc(e)).trimEnd()}
38
+ `},catch:(t)=>new R("install_failed","The merged Codex configuration is not writable.",t)}))}function cd(e){return v(function*(){return{preference:yield*Co(e,"plugins",_o),marketplace:yield*Co(e,"marketplaces",wo)}})}function ld(e,t){return Tn(t.map((n)=>Co(e,"plugins",n).pipe(de((r)=>{let i={presence:r.presence,digest:r.digest,...r.safe_value?.kind==="boolean"?{safe_value:r.safe_value}:{}};return{plugin_id:n,before:i,after:i}}))),{concurrency:"unbounded"})}function wT(e,t,n={}){return v(function*(){let r=e,i=[],o=[],a=[];for(let[s,c,f]of[["preference","plugins",_o],["marketplace","marketplaces",wo]]){let l=t.before[s],u=t.after[s],g=yield*Co(e,c,f);if(n.allowBeforeState===!0&&g.digest===l.digest)continue;if(g.digest!==u.digest){a.push(s);continue}if(l.presence==="absent"){if(g.presence==="present")r=qy(r,c,f),o.push(s);continue}if(l.safe_value===void 0){a.push(s);continue}r=wr(r,c,f,FD(l.safe_value)),i.push(s)}return{document:r,restored:i,removed:o,preserved:a}})}function CT(e,t,n,r={}){return v(function*(){let i=e,o=[],a=[],s=[];for(let c of t){if(!n.has(c.plugin_id))continue;let{before:f,after:l}=c,u=yield*Co(e,"plugins",c.plugin_id);if(r.allowBeforeState===!0&&u.digest===f.digest)continue;if(u.digest!==l.digest){s.push(c.plugin_id);continue}if(f.presence==="absent"){if(u.presence==="present")i=qy(i,"plugins",c.plugin_id),a.push(c.plugin_id);continue}if(f.safe_value===void 0){s.push(c.plugin_id);continue}i=wr(i,"plugins",c.plugin_id,{enabled:f.safe_value.value}),o.push(c.plugin_id)}return{document:i,restored:o,removed:a,preserved:s}})}function lT(e,t,n,r,i,o){return v(function*(){if(i.presence!=="present"||i.safe_value!==void 0)return{document:e,restored:!1};let a=yield*Co(e,n,r);if(a.digest===i.digest||a.digest!==o.digest)return{document:e,restored:!1};let s=pl(t,n,r);if(s===void 0)return{document:e,restored:!1};return{document:wr(e,n,r,s),restored:!0}})}function Co(e,t,n){return v(function*(){let r=pl(e,t,n),i=yield*d({try:()=>En("holycodex-plugin-config",[xn(Wt({key:`${t}.${n}`,value:r===void 0?{presence:"absent"}:r}))]),catch:(a)=>a}),o=DD(t,r);return{presence:r===void 0?"absent":"present",digest:i,...o===void 0?{}:{safe_value:o}}})}function pl(e,t,n){let r=e[t];if(!Zr(r)||!Object.hasOwn(r,n))return;return r[n]}function DD(e,t){if(!Zr(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!==Gr)return;return{kind:"marketplace",source_type:"git",source:Gr}}function FD(e){if(e.kind==="boolean")return{enabled:e.value};return{source_type:e.source_type,source:e.source}}function wr(e,t,n,r){let i={...e},o=i[t];if(o!==void 0&&!Zr(o))throw new R("state_corrupt",`The ${t} Codex config table is invalid.`);return i[t]={...o,[n]:r},i}function qy(e,t,n){let r=e[t];if(!Zr(r)||!Object.prototype.hasOwnProperty.call(r,n))return e;let i={...e},o={...r};if(delete o[n],Object.keys(o).length===0)delete i[t];else i[t]=o;return i}function Zr(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function LD(e,t,n){return v(function*(){let r=[{parent:"plugins",key:_o,expected:t.preference},{parent:"marketplaces",key:wo,expected:t.marketplace},...n.map(({plugin_id:i,before:o})=>({parent:"plugins",key:i,expected:o}))];for(let{parent:i,key:o,expected:a}of r)if((yield*Co(e,i,o)).digest!==a.digest)return yield*p(new R("confirmation_required","Plugin configuration changed after preflight; review the latest configuration and retry.",void 0,{key:`${i}.${o}`}))})}function uT(e,t,n,r,i,o,a,s,c,f){return v(function*(){let l=e,u=n,g=r;for(let h of a){let y=h.identity;if(y===void 0)return yield*p(new R("state_corrupt","A plugin configuration conflict has no identity."));let S=c.get(y);if(S!=="keep"&&S!=="replace")return yield*p(new R("confirmation_required",`Plugin configuration conflict resolution is incomplete for ${h.key??y}.`));let m=h.key==='plugins."holycodex@holycodex"'?"preference":"marketplace",x=i[m];if(S==="keep"){let E=pl(t,"plugins",_o);if(m==="preference"&&Zr(E)&&E.enabled===!1)return yield*p(new R("confirmation_required","Keeping disabled HolyCodex config would disable the selected plugin."));l=fT(l,t,h.key),u={...u,[m]:x};continue}l=wr(l,m==="preference"?"plugins":"marketplaces",m==="preference"?_o:wo,m==="preference"?{enabled:!0}:{source_type:"git",source:Gr})}for(let h of s){let{identity:y,key:S}=h;if(y===void 0||S===void 0)return yield*p(new R("state_corrupt","A provider configuration conflict has no identity."));let m=S.startsWith('plugins."')&&S.endsWith('"')?S.slice(9,-1):void 0;if(m===void 0)return yield*p(new R("state_corrupt",`The provider configuration conflict key ${S} is invalid.`));let x=c.get(y);if(x!=="keep"&&x!=="replace")return yield*p(new R("confirmation_required",`Provider configuration conflict resolution is incomplete for ${S}.`));let E=o.find((_)=>_.plugin_id===m);if(E===void 0)return yield*p(new R("state_corrupt",`The provider configuration entry ${m} is missing.`));if(x==="keep"){let _=pl(t,"plugins",m);if(f.includes(m)&&Zr(_)&&_.enabled===!1)return yield*p(new R("confirmation_required",`Keeping disabled config would disable selected plugin ${m}.`));l=fT(l,t,S),g=g.map((C)=>C.plugin_id===m?{plugin_id:m,before:E.before,after:E.before}:C);continue}l=wr(l,"plugins",m,{enabled:!0})}return{document:l,pluginConfigBefore:u,providerConfigBefore:g}})}function fT(e,t,n){if(n===void 0)throw new R("state_corrupt","A configuration conflict has no key.");if(n.startsWith('plugins."')&&n.endsWith('"')){let i=n.slice(9,-1),o=pl(t,"plugins",i);return o===void 0?qy(e,"plugins",i):wr(e,"plugins",i,o)}let r=pe(t,n);return r===void 0?vn(e,n):Gn(e,n,r)}function UD(e,t,n,r){return v(function*(){let i={...n};if(r===void 0)return i;for(let o of Object.keys(n)){let a=o,s=t.managed[a],c=r[a];if(s===void 0||c===void 0)continue;let f=yield*on(a,c);if(JSON.stringify(f)===JSON.stringify(s.lastManagedValue))continue;let l=pe(e,a);if(typeof l!=="string"&&typeof l!=="number"&&typeof l!=="boolean")continue;let u=yield*on(a,l);if(JSON.stringify(u)===JSON.stringify(s.lastManagedValue))delete i[a]}return i})}function al(e,t,n=!1){let r=dy(e,t),i=typeof n==="boolean"?{}:n,o={browserUse:i.browserUse??Mt.browser_use,computerUse:typeof n==="boolean"?n:i.computerUse??Mt.computer_use},a=yo(e,t,o),s={model:r.model,model_reasoning_effort:r.effort,service_tier:r.serviceTier,"agents.max_concurrent_threads_per_session":21,web_search:"live",approval_policy:"on-request",approvals_reviewer:"auto_review","permissions.holycodex.extends":":workspace","permissions.holycodex.network.enabled":!0,model_verbosity:"low",developer_instructions:py({...typeof n==="boolean"?{computerUse:n}:n,rootModel:r.model}),suppress_unstable_features_warning:!0,"features.multi_agent":!0,"features.default_mode_request_user_input":!0,"features.multi_agent_v2":!1,"features.agent_message_board":!1,"features.context_management.experimental_mode":!0};for(let c of Br)s[`agents."${c}".config_file`]=Hc(c,a);return s}function dT(e,t,n,r){return v(function*(){let i=[];for(let o of Object.keys(r)){let a=o;if(n.managed[a]!==void 0){if((yield*Oc(e,n,a)).status==="drifted")i.push(a);continue}let c=pe(t,a),f=pe(e,a),l=Wt(c===void 0?null:c),u=Wt(f===void 0?null:f);if(Vr(l)!==Vr(u))i.push(a)}if(i.length>0)return yield*p(new R("state_corrupt","Codex settings changed during native plugin setup.",void 0,{keys:i.join(",")}))})}function Ny(e,t,n){return v(function*(){let r=["agents.explorer.config_file","agents.librarian.config_file","agents.worker.config_file","agents.reviewer.config_file"],i=Object.fromEntries(r.flatMap((c)=>{let f=t.managed[c];return f===void 0?[]:[[c,f]]})),o=e,a=t;if(Object.keys(i).length>0){let c=yield*po(e,{...t,managed:i},{schema:t.schema,installId:t.installId});if(c.preservedKeys.length>0||c.unresolvedKeys.length>0)return yield*p(new R("state_corrupt","Legacy HolyCodex agent registrations changed and cannot be migrated safely.",void 0,{keys:[...new Set([...c.preservedKeys,...c.unresolvedKeys])].join(",")}));o=c.document,a={...t,managed:Object.fromEntries(Object.entries(t.managed).filter(([f])=>!r.includes(f)))}}if(!n)return{document:o,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 l=`agents.${c}.config_file`,u=pe(o,l);if(typeof u!=="string")continue;let g=u.replaceAll("\\","/").replace(/^\.\//u,"");if(g===`agents/${c}.toml`||g===`holycodex/agents/${c}.toml`)o=vn(o,l)}return{document:o,state:a}})}function Dy(e,t){return v(function*(){let n=t.managed[Oy];if(n===void 0)return{document:e,state:t};let r=yield*po(e,{...t,managed:{[Oy]:n}},{schema:t.schema,installId:t.installId}),i=Object.fromEntries(Object.entries(t.managed).filter(([o])=>o!==Oy));return{document:r.document,state:{...t,managed:i}}})}function ud(e,t){return v(function*(){let n=Object.fromEntries(Object.entries(t.managed).filter(([o])=>bi.includes(o)));if(Object.keys(n).length===0)return{document:e,state:t};let r=yield*po(e,{...t,managed:n},{schema:t.schema,installId:t.installId}),i=Object.fromEntries(Object.entries(t.managed).filter(([o])=>!(o in n)));return{document:r.document,state:{...t,managed:i}}})}function $D(e,t){if(pe(e,"developer_instructions")!==void 0&&t.managed.developer_instructions===void 0)throw new R("state_corrupt","Existing developer_instructions cannot be displaced safely; remove it or converge managed state first.")}function jD(e,t){return v(function*(){let n=yield*d({try:()=>e.list(),catch:(r)=>Pi("list",r,"selected plugins")});return t.map((r)=>{let i=tr(n,r),o=i===void 0?"missing":i.installed&&i.enabled?"installed":i.installed?"disabled":"available";return{plugin_id:r,status:o}})})}function Fn(e,t){return v(function*(){let n=Ye(ki,t);if(n===void 0)return yield*p(new R("state_corrupt","The HolyCodex transaction state is invalid."));yield*d({try:()=>zc(e,Wt(n)),catch:(r)=>r})})}function fd(e){return d({try:()=>By(e,{force:!1}),catch:(t)=>t}).pipe(Pt((t)=>ze(t,"ENOENT")?M(void 0):p(t)))}function $y(e){return d({try:()=>By(e,{force:!1}),catch:(t)=>t}).pipe(Pt((t)=>ze(t,"ENOENT")?M(void 0):p(t)))}function Qn(e){return e.pipe(Dr((t)=>p(om(t))),le({onFailure:(t)=>({ok:!1,error:t}),onSuccess:(t)=>({ok:!0,value:t})}))}function BD(e,t,n,r){return v(function*(){let i=yield*d({try:()=>Ee(e),catch:(h)=>h});if(i===void 0)return;let o=Lt(i,e),a={},s=0;for(let[h,y]of Object.entries(t.managed_config.managed)){let S=h,m=pe(n,S),x=m===void 0?void 0:yield*on(S,m);if(JSON.stringify(x??null)===JSON.stringify(y.lastManagedValue))continue;if(m!==void 0&&x?.kind==="digest"){let E=pe(o,S);if(E!==void 0&&JSON.stringify(yield*on(S,E))===JSON.stringify(y.lastManagedValue))o=Gn(o,S,m),s+=1;continue}a[h]={...y,originalValue:x??{kind:"absent"}}}let c=yield*po(o,{...t.managed_config,managed:a},{schema:mn,installId:t.install_id});o=c.document;let f=t.plugin_config===void 0?void 0:yield*wT(o,t.plugin_config,{allowBeforeState:!0});if(f!==void 0)o=f.document;let l=t.provider_config===void 0?void 0:yield*CT(o,t.provider_config,r,{allowBeforeState:!0});if(l!==void 0)o=l.document;if(t.plugin_config!==void 0)for(let[h,y,S]of[["preference","plugins",_o],["marketplace","marketplaces",wo]]){let m=yield*lT(o,n,y,S,t.plugin_config.before[h],t.plugin_config.after[h]);if(o=m.document,m.restored)s+=1}if(t.provider_config!==void 0)for(let h of t.provider_config){if(!r.has(h.plugin_id))continue;let y=yield*lT(o,n,"plugins",h.plugin_id,h.before,h.after);if(o=y.document,y.restored)s+=1}if(!(c.restoredKeys.length>0||f!==void 0&&(f.restored.length>0||f.removed.length>0)||l!==void 0&&(l.restored.length>0||l.removed.length>0)||s>0))return;yield*d({try:()=>ft(e,_r(o)),catch:(h)=>h});let g=yield*d({try:()=>mT(e),catch:(h)=>h});return g.isFile()&&!g.isSymbolicLink()?{dev:g.dev,ino:g.ino}:void 0})}function VD(e,t,n,r,i,o=[],a=al(t,n,r)){return v(function*(){let s=yield*d({try:()=>Ee(e.configFile),catch:(y)=>y}),c=Lt(s,e.configFile),f=a;for(let[y,S]of Object.entries(f)){let m=pe(c,y);if(y==="developer_instructions"){if(typeof m!=="string"||m!==S||(yield*qD(y,m))!==i.managed[y]?.lastManagedValue.value)return yield*p(new R("install_failed","The effective Root instructions did not converge."))}else if(m!==S)return yield*p(new R("install_failed",`The effective Codex setting ${y} did not converge.`))}let l={browserUse:r.browserUse??Mt.browser_use,computerUse:r.computerUse},u=yo(t,n,l),g=Hr(t,n);for(let y of g){let S=`agents."${y.name}".config_file`,m=pe(c,S);if(typeof m!=="string")return yield*p(new R("install_failed",`The ${y.name} registration is missing.`));let x=Hc(y.name,u),E=fo(e.configFile,x),_=E.replaceAll("\\","/");if(fo(e.configFile,m).replaceAll("\\","/")!==_)return yield*p(new R("install_failed",`The ${y.name} registration is stale (expected ${x}; received ${m}).`));let N=yield*d({try:()=>Ee(E),catch:(F)=>F});if(N===void 0)return yield*p(new R("install_failed",`The ${y.name} role file is missing.`));if(o.some((F)=>F.replaceAll("\\","/")===_))return yield*p(new R("install_failed",`The ${y.name} role file was kept after a conflict and cannot be activated.`));let D=Lt(N,E);if(D.name!==y.name||typeof D.description!=="string"||typeof D.model!=="string"||typeof D.model_reasoning_effort!=="string"||typeof D.service_tier!=="string"||typeof D.developer_instructions!=="string"||!jC(y,D)||D.tool_output_token_limit!==void 0||pe(D,"agents.enabled")!==!1||pe(D,"features.multi_agent")!==!1||pe(D,"features.multi_agent_v2")!==!1||pe(D,"features.agent_message_board")!==!1||pe(D,"features.context_management.experimental_mode")!==!0||Object.keys(D.features??{}).some((F)=>!["multi_agent","multi_agent_v2","agent_message_board","context_management"].includes(F)))return yield*p(new R("install_failed",`The ${y.name} role file is malformed.`))}let h=yield*d({try:()=>Ee(`${e.codexHome}/agents/root.toml`),catch:(y)=>y});if(h!==void 0&&Ma(h))return yield*p(new R("install_failed","A stale HolyCodex Root role remains installed."))})}function qD(e,t){return v(function*(){return yield*d({try:()=>En("holycodex-managed-config-value",[xn({keyPath:e,value:t})]),catch:(n)=>n})})}function Fy(e,t){let n={};for(let r of["browser_use","computer_use","sites"]){let i=t?.[r]??e?.[r];if(i!==void 0)n[r]=i}return n}function zD(e){return["browser_use","computer_use","sites"].find((t)=>jr[t].pluginIds.includes(e))}function jy(e){return(e?.official_plugins??[]).filter((t)=>{if(t===Kt)return!1;if(ll(t))return!1;let n=zD(t);return n===void 0||e?.optional_selections[n]!==!0})}function JD(e){return v(function*(){yield*Ra(bD(e));let t=yield*d({try:()=>vD(e,"wx",384),catch:(r)=>r}).pipe(le({onFailure:(r)=>({error:r}),onSuccess:(r)=>({handle:r})}));if("error"in t){if(ze(t.error,"EEXIST"))return;return yield*p(t.error)}let n=t.handle;return yield*Fr(M(n),(r)=>v(function*(){let i=yield*d({try:()=>r.stat(),catch:(o)=>o});return yield*d({try:()=>r.sync(),catch:(o)=>o}),{dev:i.dev,ino:i.ino}}),(r)=>d({try:()=>r.close(),catch:(i)=>i}))})}function WD(e,t){return v(function*(){if(t===void 0)return!1;let n=yield*d({try:()=>mT(e),catch:(i)=>i}).pipe(le({onFailure:(i)=>({error:i}),onSuccess:(i)=>({stat:i})}));if("error"in n){if(ze(n.error,"ENOENT"))return!1;return yield*p(n.error)}let r=n.stat;return r.isFile()&&!r.isSymbolicLink()&&r.dev===t.dev&&r.ino===t.ino})}function ll(e){let t=e.slice(0,e.lastIndexOf("@"));return TD.has(t)}function HD(e,t,n,r){return v(function*(){let i=(s)=>d({try:()=>e.list(),catch:(c)=>Pi("list",c,s)}),o=(s)=>d({try:()=>e.add(s),catch:(c)=>Pi("add",c,s)}),a=(s,c)=>r?.(s,c)??rt;for(let s of t){let c=n.has(s),f=yield*i(s).pipe(le({onFailure:(y)=>({error:y}),onSuccess:(y)=>({before:tr(y,s)})}));if("error"in f)return yield*p(f.error);let l=f.before;if(l?.installed&&!l.enabled)return yield*p(new Yr("uncertain",`${s} is disabled`));let u=c||!(l?.installed&&l.enabled);if(u){let y=yield*o(s).pipe(le({onFailure:(S)=>({error:S}),onSuccess:()=>({added:!0})}));if("error"in y){let S=yield*i(s).pipe(le({onFailure:(m)=>({error:m}),onSuccess:(m)=>({afterFailure:tr(m,s)})}));if("error"in S||c||!pT(l,S.afterFailure))yield*a(s,"uncertain");return yield*p(y.error)}}let g=yield*i(s).pipe(le({onFailure:(y)=>({error:y}),onSuccess:(y)=>({after:tr(y,s)})}));if("error"in g){if(u)yield*a(s,"uncertain");return yield*p(g.error)}let h=g.after;if(!h?.installed){if(u&&(c||!pT(l,h)))yield*a(s,"uncertain");return yield*p(new Yr("missing",`${s} is not installed after add`))}if(u&&h.enabled)yield*a(s,c?"uncertain":"new");if(!h.enabled){if(u)yield*a(s,c?"uncertain":"new");return yield*p(new Yr("uncertain",`${s} is disabled after add`))}}})}function KD(e,t,n){return v(function*(){let r=(a)=>d({try:()=>e.list(),catch:(s)=>Pi("list",s,a)}),i=(a)=>d({try:()=>e.remove(a),catch:(s)=>Pi("remove",s,a)}),o=(a,s)=>n?.(a,s)??rt;for(let a of t){let s=yield*r(a).pipe(le({onFailure:(u)=>({error:u}),onSuccess:(u)=>({before:tr(u,a)})}));if("error"in s)return yield*o(a,"uncertain"),yield*p(s.error);if(!(s.before?.installed??!1)){yield*o(a,"absent");continue}let f=yield*i(a).pipe(le({onFailure:(u)=>({error:u}),onSuccess:()=>({removed:!0})}));if("error"in f){let u=yield*r(a).pipe(le({onFailure:(g)=>({error:g}),onSuccess:(g)=>({afterFailure:tr(g,a)})}));return yield*o(a,"error"in u||u.afterFailure?.installed?"uncertain":"removed"),yield*p(f.error)}let l=yield*r(a).pipe(le({onFailure:(u)=>({error:u}),onSuccess:(u)=>({after:tr(u,a)})}));if("error"in l)return yield*o(a,"uncertain"),yield*p(l.error);if(l.after?.installed)return yield*o(a,"uncertain"),yield*p(new Yr("uncertain",`${a} is still installed after remove`));yield*o(a,"removed")}})}function GD(e,t,n){return v(function*(){if(n!=="installed"&&n!=="disabled")return yield*p(new Yr("uncertain",`${t} has no proven prior installed state`));let r=n==="installed",i=yield*d({try:()=>e.list(),catch:(c)=>Pi("list",c,t)}),o=tr(i,t);if(o?.installed&&o.enabled===r)return;yield*d({try:()=>e.add(t),catch:(c)=>Pi("add",c,t)});let a=yield*d({try:()=>e.list(),catch:(c)=>Pi("list",c,t)}),s=tr(a,t);if(!s?.installed)return yield*p(new Yr("missing",`${t} is not installed after restore`));if(s.enabled!==r)return yield*p(new Yr("uncertain",`${t} did not regain its prior ${r?"enabled":"disabled"} state`))})}function pT(e,t){return e?.pluginId===t?.pluginId&&e?.installed===t?.installed&&e?.enabled===t?.enabled&&e?.marketplaceName===t?.marketplaceName}function Pi(e,t,n){if(t instanceof vr)return t;return new vr(e==="list"?"list_failed":e==="remove"?"remove_failed":"add_failed",e==="list"?`Codex could not read the status of ${n}.`:e==="remove"?`Codex could not remove ${n}.`:`Codex could not add ${n}.`,t,{plugin_id:n})}function tr(e,t){let n=hr(e,t);if(n!==void 0)return n.entry;let r=Pn(t);return[...e.installed,...e.available].find((i)=>i.pluginId===t&&(r===void 0||i.marketplaceName==null))}function YD(e,t){let n=e??t??"default";if(!va(n).ok)throw new R("install_failed","Unknown profile.");return n}function ZD(e,t){let n=e??t??"standard";if(Ye(yn,n)===void 0)throw new R("install_failed","The tier is not supported.");return n}function XD(e,t){let n=t?_T(t):Mt,r=lg(e,n);return{browser_use:r.browser_use,computer_use:r.computer_use,sites:r.sites,coding:!0}}function dd(e,t=new Map){return Object.fromEntries(["browser_use","computer_use","frontend","security","sites"].map((r)=>{let i=r==="frontend"||r==="security"?!0:e[r],o=r==="frontend"||r==="security"?void 0:t.get(r),a={selected:i,status:i?o??"healthy":"disabled",plugin_ids:[...jr[r].pluginIds]};return[r,a]}))}function QD(e){return A(md(e))}function md(e){let{profile:t,plan:n,...r}=e,i=Object.fromEntries(Object.entries(n===void 0?{...r,profile:t}:{...r,plan:n}).filter(([,o])=>o!==void 0));return d({try:()=>En("install-record",[xn(Wt(i))]),catch:(o)=>o})}function sl(e){return A(pd(e))}function pd(e){return v(function*(){return(yield*md({owner:e.owner,install_id:e.install_id,version:e.version,...e.profile===void 0?{}:{profile:e.profile},...e.plan===void 0?{}:{plan:e.plan},tier:e.tier,optional_selections:e.optional_selections,explicit_optional_selections:e.explicit_optional_selections,official_plugins:e.official_plugins??[],capability_state:e.capability_state??null,managed_artifacts:e.managed_artifacts,...e.managed_config===void 0?{}:{managed_config:e.managed_config},...e.plugin_config===void 0?{}:{plugin_config:e.plugin_config},...e.provider_config===void 0?{}:{provider_config:e.provider_config},...e.plugin_snapshot===void 0?{}:{plugin_snapshot:e.plugin_snapshot},...e.owned_plugins===void 0?{}:{owned_plugins:e.owned_plugins},...e.tooling===void 0?{}:{tooling:e.tooling}}))===e.digest})}function ul(e){return e instanceof Error?e.message.slice(0,256):"operation failed"}function eF(e){if(!(e instanceof Error))return!1;return/(?:^|[\n:])\s*-\s*`([^`]+)`\s+at\s+[^\r\n]*:\s*marketplace root does not contain a supported manifest/iu.exec(e.message)?.[1]==="holycodex"}function tF(e){return Zr(e)&&Object.keys(e).length===2&&e.source_type==="git"&&typeof e.source==="string"&&If(e.source)}function nF(e,t,n){let r=[{name:"context7",status:e?"ready":"unavailable"}];for(let i of n){let o=tr(t,i),a=o===void 0?"missing":o.installed?o.enabled?"installed":"disabled":"available";r.push({name:`official-plugin:${i}`,status:a,...typeof o?.version==="string"?{detail:o.version}:{}})}return r}function Ln(e){let t=e.category??(e.key===void 0?"role-asset":"config-key"),n=e.target??e.key??e.path,r=e.identity??`${t}:${e.path}:${e.key??""}:${e.action}`,i=e.action==="remove"?["keep","remove","cancel"]:["keep","replace","cancel"],o=e.action==="remove"&&e.validDecisions?.includes("replace")===!0&&e.validDecisions.includes("remove")===!1?i:e.validDecisions??i,a=e.defaultDecision!==void 0&&o.includes(e.defaultDecision)?e.defaultDecision:o.includes(e.action)?e.action:o[0]??e.action;return{...e,identity:r,category:t,target:n,defaultDecision:a,validDecisions:o,explanation:e.explanation??(e.action==="remove"?`HolyCodex can remove the managed ${n} after reviewing this change.`:`HolyCodex can replace the managed ${n} after reviewing this change.`)}}function fl(e,t,n=!1){return v(function*(){let r=t.map(Ln),i=new Map;if(r.length===0)return{accepted:[],decisions:i};if(e.resolveConflicts!==void 0){let a=yield*e.resolveConflicts(r).pipe(le({onFailure:(c)=>({error:c}),onSuccess:(c)=>({selected:c})}));if("error"in a){let c=a.error;if(!(c instanceof R)||c.code!=="confirmation_required")return yield*p(c);let f=r.map((l)=>{let u=l.category==="invalid-config"&&l.key!==void 0&&l.existing!==void 0?` = ${JSON.stringify(l.existing)}`:"";return`${l.target} at ${l.path}${u}`}).join("; ");return yield*p(new R("confirmation_required",`${c.message} Conflicts: ${f}.`,c,{conflicts:f}))}let s=a.selected;for(let c of r){let f=c.identity,l=Ye(mC,s[f]);if(l===void 0||c.validDecisions?.includes(l)===!1){let u=c.validDecisions?.join(", ")??"keep, replace, cancel";return yield*p(new R("confirmation_required",`The conflict at ${c.target} requires one of these decisions: ${u}.`,void 0,{identity:f,path:c.path,...c.key===void 0?{}:{key:c.key}}))}if(l==="cancel")return yield*p(new R("confirmation_required",`Conflict resolution was cancelled for ${c.target} at ${c.path}.`,void 0,{identity:f,path:c.path,...c.key===void 0?{}:{key:c.key}}));i.set(f,l)}return{accepted:r.filter((c)=>i.get(c.identity)===(c.action==="remove"?"remove":"replace")),decisions:i}}let o=[];for(let a of r){let s=yield*e.resolveConflict===void 0?M(void 0):e.resolveConflict(a);if(s==="accept"){let c=a.action==="remove"?"remove":"replace";if(a.validDecisions?.includes(c)===!1)return yield*p(new R("confirmation_required",`The conflict at ${a.target} cannot be ${c}d; choose ${a.validDecisions?.join(", ")}.`,void 0,{identity:a.identity,path:a.path,...a.key===void 0?{}:{key:a.key}}));o.push(a),i.set(a.identity,c);continue}if(s==="decline"&&n){if(a.validDecisions?.includes("keep")===!1)return yield*p(new R("confirmation_required",`The conflict at ${a.target} cannot be kept; choose ${a.validDecisions?.join(", ")}.`,void 0,{identity:a.identity,path:a.path,...a.key===void 0?{}:{key:a.key}}));i.set(a.identity,"keep");continue}return yield*p(new R("confirmation_required",s==="cancel"?`Conflict resolution was cancelled for ${a.target} at ${a.path}.`:`Conflict resolution is required for ${a.target} at ${a.path}: ${a.explanation}.`,void 0,{path:a.path,...a.key===void 0?{}:{key:a.key},action:a.action,resolution:s??"unavailable"}))}return{accepted:o,decisions:i}})}function er(e,t){Oe(Je(V({try:()=>e.onProgress?.(t),catch:(n)=>n})))}function Py(e={},t={},n=process.env){return A(dl(e,t,n))}function Ua(e){return A(Vy(e))}function Kr(e,t){return A(Ly(e,t))}function tl(e,t,n={}){return A(wT(e,t,n))}function nl(e,t,n,r={}){return A(CT(e,t,n,r))}var cT="davidbasilefilho/holycodex",Gt="holycodex@holycodex",Kt="browser@openai-bundled",_D="0.16.8",wD="0.16.9",gT,Gr="https://github.com/davidbasilefilho/holycodex.git",_o="holycodex@holycodex",wo="holycodex",TD,Oy,Yr,R;var cl=L(()=>{mo();st();Yi();De();$f();Wc();Yf();Kc();ho();jc();Oa();ed();jc();gT=new WeakMap;TD=new Set(["documents","pdf","presentations","spreadsheets","template-creator"]),Oy=bi[0];Yr=class Yr extends Error{status;constructor(e,t){super(t);this.name="PluginVerificationError",this.status=e}};R=class R 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}}});De();import{createInterface as XF}from"readline/promises";mo();st();De();bt();Fe();st();Fe();var qh=Object.freeze([{name:"yes",kind:"boolean",usage:"--yes",description:"Confirm installation."},{name:"profile",kind:"value",usage:"--profile <low|default|high>",description:"Select routing (default: default)."},{name:"tier",kind:"value",usage:"--tier <standard|fast|fast-all>",description:"Select service handling (default: standard)."},{name:"sites",kind:"boolean",usage:"--sites / --no-sites",description:"ChatGPT Sites (default: true)."},{name:"browser-use",kind:"boolean",usage:"--browser-use / --no-browser-use",description:"Browser Use (default: true)."},{name:"computer-use",kind:"boolean",usage:"--computer-use / --no-computer-use",description:"Computer Use plugins (default: false)."},{name:"add-plugin",kind:"value",usage:"--add-plugin <id>",description:"Add a Codex plugin; repeatable."},{name:"json",kind:"boolean",usage:"--json",description:"Emit one JSON envelope."}]),lC=new Set(["codex-home","profile","tier","add-plugin"]),ZM=new Set(["yes","json","verbose","dry-run","computer-use","no-computer-use","sites","no-sites","browser-use","no-browser-use"]);class Ke extends Error{code;details;constructor(e,t,n={}){super(t);this.name="ArgumentError",this.code=e,this.details=n}}function Uf(e){if(e.length===0)throw new Ke("unknown_command","A command is required.");if(e.includes("-h")||e.includes("--help")||e.includes("--help=true"))return{command:"help",positionals:[],options:{}};if(e[0]==="help")return{command:"help",positionals:e.slice(1),options:{}};if(e[0]==="-v"||e[0]==="--version"||e[0]==="--version=true")return Uf(["version",...e.slice(1)]);let t=e[0];if(t!=="install"&&t!=="doctor"&&t!=="remove"&&t!=="version")throw new Ke("unknown_command","Unknown command.",{command:t??""});let n=[],r={};for(let i=1;i<e.length;i+=1){let o=e[i];if(o===void 0)continue;if(o==="-"||!o.startsWith("-")){n.push(o);continue}if(!o.startsWith("--")||o==="--")throw new Ke("invalid_argument","Short options are not supported.",{option:o});let a=o.slice(2),s=a.indexOf("="),c=s>=0?a.slice(0,s):a,f=s>=0?a.slice(s+1):void 0,l=c.replaceAll("_","-");if(l==="plan")throw new Ke("invalid_argument","The --plan option was removed; use --profile <low|default|high>.",{option:"--plan",replacement:"--profile"});if(!lC.has(l)&&!ZM.has(l))throw new Ke("invalid_argument","Unknown option.",{option:`--${c}`});if(lC.has(l)){let u=f??e[i+1];if(u===void 0||u.length===0||u.startsWith("-"))throw new Ke("invalid_argument",`Option --${c} requires a value.`,{option:`--${c}`});if(f===void 0)i+=1;if(l==="add-plugin"){let g=r[l];r[l]=Array.isArray(g)?[...g,u]:[u]}else{if(r[l]!==void 0)throw new Ke("invalid_argument",`Option --${c} may only be supplied once.`,{option:`--${c}`});r[l]=u}continue}if(f!==void 0&&f!=="true"&&f!=="false")throw new Ke("invalid_argument",`Option --${c} is boolean.`,{option:`--${c}`});if(r[l]!==void 0)throw new Ke("invalid_argument",`Option --${c} may only be supplied once.`,{option:`--${c}`});r[l]=f==="false"?!1:!0}return XM(t,n,r),{command:t,positionals:n,options:r}}function XM(e,t,n){let r=e0(e);for(let s of Object.keys(n))if(!r.has(s))throw new Ke("invalid_argument",`Option --${s} is not valid for ${e}.`,{option:`--${s}`});let i=e==="version"?{min:0,max:1}:{min:0,max:0};if(t.length<i.min||t.length>i.max)throw new Ke("invalid_argument",`Invalid positional arguments for ${e}.`);let o=n.profile;if(o!==void 0&&!be(rn)(o)){if(typeof o!=="string")throw new Ke("invalid_argument","The profile is not supported.");let s=QM[o];if(s!==void 0)throw new Ke("invalid_argument",`Legacy profile ${o} was removed; use --profile ${s}.`,{profile:o,replacement:s});if(o==="go"||o==="Go"||o==="pro-5x"||o==="pro-20x")throw new Ke("invalid_argument",`Legacy profile ${o} was removed and requires an explicit replacement using --profile <low|default|high>.`,{profile:o});throw new Ke("invalid_argument","The profile is not supported.",{profile:o})}let a=n.tier;if(a!==void 0&&!be(yn)(a))throw new Ke("invalid_argument","The tier is not supported.",{tier:a});for(let[s,c]of[["computer-use","no-computer-use"],["sites","no-sites"],["browser-use","no-browser-use"]])if(n[s]!==void 0&&n[c]!==void 0)throw new Ke("invalid_argument",`Conflicting --${s} and --${c} options.`);if(["install","remove"].includes(e)&&n.yes===!1)throw new Ke("invalid_argument","--yes cannot be false.");if(e!=="install"&&Object.keys(n).some((s)=>["profile","tier","sites","no-sites","browser-use","no-browser-use","computer-use","no-computer-use","add-plugin"].includes(s)))throw new Ke("invalid_argument",`Installation options are not valid for ${e}.`)}var QM={"plus-low":"low",plus:"default","plus-high":"high"};function e0(e){switch(e){case"install":return new Set([...qh.map((t)=>t.name),"no-sites","no-browser-use","no-computer-use","codex-home","verbose"]);case"doctor":return new Set(["json","verbose","codex-home"]);case"remove":return new Set(["yes","json","verbose","codex-home"]);case"version":return new Set(["json","verbose","dry-run"]);default:return new Set}}var t0=`HolyCodex
47
39
 
48
40
  Usage:
49
41
  holycodex install [options]
@@ -57,7 +49,7 @@ Options:
57
49
  --json Emit one validated JSON envelope.
58
50
 
59
51
  Use --json for scripts. Install and remove use native Codex plugin management.
60
- `,RW=`Install HolyCodex through Codex native plugin management.
52
+ `,n0=`Install HolyCodex through Codex native plugin management.
61
53
 
62
54
  Usage:
63
55
  holycodex install [options]
@@ -74,7 +66,7 @@ Tier is independent service handling (CLI values are lowercase only):
74
66
  fast-all Fast service handling for Root and leaves.
75
67
 
76
68
  Options:
77
- ${av.map((e)=>` ${e.usage.padEnd(48)} ${e.description}`).join(`
69
+ ${qh.map((e)=>` ${e.usage.padEnd(48)} ${e.description}`).join(`
78
70
  `)}
79
71
  --no-sites / --no-browser-use / --no-computer-use
80
72
  Disable the corresponding plugin.
@@ -86,48 +78,48 @@ On an interactive TTY, install opens one wizard and final review with Install,
86
78
  Change options / Redo, and Cancel. The wizard never asks for CODEX_HOME.
87
79
  Additional plugin IDs in the wizard are separated by whitespace; --add-plugin
88
80
  remains repeatable on the command line.
89
- `,TW=`Remove HolyCodex-owned state through Codex native plugin management.
81
+ `,r0=`Remove HolyCodex-owned state through Codex native plugin management.
90
82
 
91
83
  Usage:
92
84
  holycodex remove [--yes] [--json] [--codex-home <absolute-path>]
93
85
 
94
86
  Only HolyCodex-owned state is removed. Shared and unrelated Codex plugins and
95
87
  configuration are preserved; changed owned files are preserved for review.
96
- `,CW=`Inspect HolyCodex-owned configuration and native plugin state without mutating it.
88
+ `,i0=`Inspect HolyCodex-owned configuration and native plugin state without mutating it.
97
89
 
98
90
  Usage:
99
91
  holycodex doctor [--json] [--codex-home <absolute-path>]
100
- `,OW=`Read or update the canonical public package version.
92
+ `,o0=`Read or update the canonical public package version.
101
93
 
102
94
  Usage:
103
95
  holycodex version [<0.x.y[-n]|patch|minor>] [--dry-run] [--json]
104
96
  holycodex --version
105
97
  holycodex -v
106
- `;function pd(e){switch(e){case"install":return RW;case"remove":return TW;case"doctor":return CW;case"version":return OW;default:return vW}}function sv(e,t={}){let n=Qi({...t,stream:"stdout"});return pd(e).split(`
107
- `).map((r)=>{if(r==="HolyCodex")return vn(r,"heading",n);if(/^(?:Usage|Options|Profiles control routing only|Tier is independent service handling|Capability defaults).*:$/u.test(r))return vn(r,"heading",n);return r.replace(/--[a-z][a-z0-9-]*/gu,(o)=>vn(o,"option",n)).replace(/<[^>]+>/gu,(o)=>vn(o,"argument",n))}).join(`
108
- `)}function fd(e){return e.some((t)=>t==="-h"||t==="--help"||t==="--help=true")}function md(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 Qi(e){let t=e.env??{};if(t.NO_COLOR!==void 0||t.TERM==="dumb")return!1;if(t.FORCE_COLOR!==void 0&&t.FORCE_COLOR!=="0")return!0;if(t.CI!==void 0&&t.CI!=="false")return!1;return(e.stream==="stderr"?e.stderrIsTTY:e.stdoutIsTTY)===!0}var cv={heading:"#7aa2f7",option:"#7dcfff",argument:"#a9b1d6",focus:"#7dcfff",enabled:"#9ece6a",disabled:"#a9b1d6",success:"#73daca",warning:"#e0af68",error:"#f7768e",hint:"#737aa2"};function vn(e,t,n){if(!n)return e;let r=t==="heading"||t==="focus"?"1;":"",o=cv[t],i=Number.parseInt(o.slice(1,3),16),a=Number.parseInt(o.slice(3,5),16),s=Number.parseInt(o.slice(5,7),16);return`\x1B[${r}38;2;${i};${a};${s}m${e}\x1B[0m`}ht();Dd();var tJ=["low","default","high"],nJ=["standard","fast","fast-all"],ia=["sites","browser_use","computer_use"];function Qv(e){return{...e.stdin===void 0?{}:{stdin:e.stdin},...e.stdout===void 0?{}:{stdout:e.stdout},...e.width===void 0?{}:{width:e.width},...e.height===void 0?{}:{height:e.height}}}function eR(e){let t=e.stdoutIsTTY??(e.stdout===void 0?process.stdout.isTTY===!0:e.stdout.isTTY===!0);return Qi({stdoutIsTTY:t,env:e.env??process.env,stream:"stdout"})}function Rs(...e){return e}function ae(e,t){return Rs({text:e,...t===void 0?{}:{tone:t}})}function rJ(e,t,n){let r=e.fg(cv[n])(t);return n==="heading"||n==="focus"?e.bold(r):r}function ug(e,t,n){let r=[];return t.forEach((o,i)=>{for(let a of o){if(a.text.length===0)continue;if(!n||a.tone===void 0)r.push(...e.stringToStyledText(a.text).chunks);else r.push(rJ(e,a.text,a.tone))}if(i<t.length-1)r.push(...e.stringToStyledText(`
98
+ `;function Mc(e){switch(e){case"install":return n0;case"remove":return r0;case"doctor":return i0;case"version":return o0;default:return t0}}function zh(e,t={}){let n=_i({...t,stream:"stdout"});return Mc(e).split(`
99
+ `).map((r)=>{if(r==="HolyCodex")return an(r,"heading",n);if(/^(?:Usage|Options|Profiles control routing only|Tier is independent service handling|Capability defaults).*:$/u.test(r))return an(r,"heading",n);return r.replace(/--[a-z][a-z0-9-]*/gu,(i)=>an(i,"option",n)).replace(/<[^>]+>/gu,(i)=>an(i,"argument",n))}).join(`
100
+ `)}function Nc(e){return e.some((t)=>t==="-h"||t==="--help"||t==="--help=true")}function Dc(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 _i(e){let t=e.env??{};if(t.NO_COLOR!==void 0||t.TERM==="dumb")return!1;if(t.FORCE_COLOR!==void 0&&t.FORCE_COLOR!=="0")return!0;if(t.CI!==void 0&&t.CI!=="false")return!1;return(e.stream==="stderr"?e.stderrIsTTY:e.stdoutIsTTY)===!0}var Jh={heading:"#7aa2f7",option:"#7dcfff",argument:"#a9b1d6",focus:"#7dcfff",enabled:"#9ece6a",disabled:"#a9b1d6",success:"#73daca",warning:"#e0af68",error:"#f7768e",hint:"#737aa2"};function an(e,t,n){if(!n)return e;let r=t==="heading"||t==="focus"?"1;":"",i=Jh[t],o=Number.parseInt(i.slice(1,3),16),a=Number.parseInt(i.slice(3,5),16),s=Number.parseInt(i.slice(5,7),16);return`\x1B[${r}38;2;${o};${a};${s}m${e}\x1B[0m`}st();De();cl();var rF=["low","default","high"],iF=["standard","fast","fast-all"],Oi=["sites","browser_use","computer_use"];function zy(e,t){return A(ci((n)=>{let r=!1,i=(c)=>{let f=Oe(Le(V({try:()=>t(c),catch:(l)=>l})));if(f._tag==="Failure")a(p(f.failure));else if(f.success!==void 0)a(M(f.success))},o=()=>{e.keyInput.off("keypress",i),e.destroy()},a=(c)=>{if(r)return;r=!0,o(),n(c)};e.keyInput.on("keypress",i);let s=Oe(Le(V({try:()=>e.start(),catch:(c)=>c})));if(s._tag==="Failure")a(p(s.failure));return nt(o)}))}function Jy(e){return{...e.stdin===void 0?{}:{stdin:e.stdin},...e.stdout===void 0?{}:{stdout:e.stdout},...e.width===void 0?{}:{width:e.width},...e.height===void 0?{}:{height:e.height}}}function Wy(e){let t=e.stdoutIsTTY??(e.stdout===void 0?process.stdout.isTTY===!0:e.stdout.isTTY===!0);return _i({stdoutIsTTY:t,env:e.env??process.env,stream:"stdout"})}function To(...e){return e}function Q(e,t){return To({text:e,...t===void 0?{}:{tone:t}})}function oF(e,t,n){let r=e.fg(Jh[n])(t);return n==="heading"||n==="focus"?e.bold(r):r}function gd(e,t,n){let r=[];return t.forEach((i,o)=>{for(let a of i){if(a.text.length===0)continue;if(!n||a.tone===void 0)r.push(...e.stringToStyledText(a.text).chunks);else r.push(oF(e,a.text,a.tone))}if(o<t.length-1)r.push(...e.stringToStyledText(`
109
101
  `).chunks)}),r.push(...e.stringToStyledText(`
110
- `).chunks),new e.StyledText(r)}async function dg(e={},t={}){let n=dn(e),r=await import("@opentui/core"),o=oR(n),i=await r.createCliRenderer({...Qv(t),exitOnCtrlC:!0,clearOnShutdown:!0}),a=eR(t),s=new r.TextRenderable(i,{content:fL(r,o,0,a)});return i.root.add(s),await new Promise((c,l)=>{let u=0,d=!1,p=0,m=!1,f=(v)=>{if(m)return;m=!0,i.keyInput.off("keypress",x),i.destroy(),c(v)},y=(v)=>{if(m)return;m=!0,i.keyInput.off("keypress",x),i.destroy(),l(v)},g=()=>{s.content=d?yJ(r,o,p,a):fL(r,o,u,a),i.requestRender()},x=(v)=>{try{let C=v.name.toLowerCase();if(v.ctrl===!0&&C==="c"){f({action:"cancel"});return}if(d){if(C==="escape"){d=!1,g();return}if(C==="up"||C==="k")p=(p+2)%3;else if(C==="down"||C==="j")p=(p+1)%3;else if(C==="return"||C==="enter"||C==="linefeed"){if(p===0)f({action:"install",request:wL(o)});else if(p===1)d=!1,u=0;else f({action:"cancel"});return}g();return}let M=bL(o,u,v);if(u=M.cursor,M.action==="cancel"){f({action:"cancel"});return}if(M.action==="review")d=!0,p=0;g()}catch(C){y(C)}};i.keyInput.on("keypress",x);try{i.start()}catch(v){y(v)}})}function tR(e,t={}){let n={};for(let r of e){let o=fg(r),i=Qc(r),a=t[o],s=i.includes(a??"cancel")?a:rR(r,i);n[o]=i.includes(s)?s:i[0]??"cancel"}return{conflicts:e,decisions:n}}function yL(e,t,n){let r=n.name,o=r.toLowerCase(),i=n.shift===!0||r.length===1&&r!==r.toLowerCase();if(o==="escape")return{cursor:t,action:"back"};if(n.ctrl===!0&&o==="c")return{cursor:t,action:"cancel"};if(o==="up"||o==="k"&&!i)return{cursor:Math.max(0,t-1),action:"render"};if(o==="down"||o==="j")return{cursor:Math.min(Math.max(0,e.conflicts.length-1),t+1),action:"render"};if(o==="return"||o==="enter"||o==="linefeed")return{cursor:t,action:e.conflicts.some((a)=>Qc(a).length===0)?"cancel":"continue"};if(o==="a"&&n.ctrl!==!0)return aL(e,"replace"),{cursor:t,action:"render"};if((o==="k"||r==="K")&&n.ctrl!==!0){if(o==="k"&&!i)return{cursor:Math.max(0,t-1),action:"render"};return aL(e,"keep"),{cursor:t,action:"render"}}if(o==="left"||o==="right")cJ(e,t,o==="left"?-1:1);return{cursor:t,action:"render"}}function oJ(e,t=tR(e).decisions,n=0,r={}){let o=Qi({...r,stream:"stdout"}),i=process.stdout.columns??80,a=process.stdout.rows??24;return`${SL(e,t,n,i,a).map((s)=>s.map((c)=>c.tone===void 0?c.text:vn(c.text,c.tone,o)).join("")).join(`
102
+ `).chunks),new e.StyledText(r)}function hd(e={},t={}){return A(v(function*(){let n=Yt(e),r=yield*d({try:()=>import("@opentui/core"),catch:(u)=>u}),i=Yy(n),o=yield*d({try:()=>r.createCliRenderer({...Jy(t),exitOnCtrlC:!0,clearOnShutdown:!0}),catch:(u)=>u}),a=Wy(t),s=new r.TextRenderable(o,{content:MT(r,i,0,a)});o.root.add(s);let c=0,f=!1,l=0;return yield*d({try:()=>zy(o,(u)=>{let g=()=>{s.content=f?xF(r,i,l,a):MT(r,i,c,a),o.requestRender()},h=u.name.toLowerCase();if(u.ctrl===!0&&h==="c")return{action:"cancel"};if(f){if(h==="escape"){f=!1,g();return}if(h==="up"||h==="k")l=(l+2)%3;else if(h==="down"||h==="j")l=(l+1)%3;else if(h==="return"||h==="enter"||h==="linefeed"){if(l===0)return{action:"install",request:BT(i)};if(l===1)f=!1,c=0;else return{action:"cancel"}}g();return}let y=jT(i,c,u);if(c=y.cursor,y.action==="cancel")return{action:"cancel"};if(y.action==="review")f=!0,l=0;g();return}),catch:(u)=>u})}))}function Hy(e,t={}){let n={};for(let r of e){let i=Sd(r),o=ja(r),a=t[i],s=o.includes(a??"cancel")?a:Gy(r,o);n[i]=o.includes(s)?s:o[0]??"cancel"}return{conflicts:e,decisions:n}}function LT(e,t,n){let r=n.name,i=r.toLowerCase(),o=n.shift===!0||r.length===1&&r!==r.toLowerCase();if(i==="escape")return{cursor:t,action:"back"};if(n.ctrl===!0&&i==="c")return{cursor:t,action:"cancel"};if(i==="up"||i==="k"&&!o)return{cursor:Math.max(0,t-1),action:"render"};if(i==="down"||i==="j")return{cursor:Math.min(Math.max(0,e.conflicts.length-1),t+1),action:"render"};if(i==="return"||i==="enter"||i==="linefeed")return{cursor:t,action:e.conflicts.some((a)=>ja(a).length===0)?"cancel":"continue"};if(i==="a"&&n.ctrl!==!0)return TT(e,"replace"),{cursor:t,action:"render"};if((i==="k"||r==="K")&&n.ctrl!==!0){if(i==="k"&&!o)return{cursor:Math.max(0,t-1),action:"render"};return TT(e,"keep"),{cursor:t,action:"render"}}if(i==="left"||i==="right")uF(e,t,i==="left"?-1:1);return{cursor:t,action:"render"}}function aF(e,t=Hy(e).decisions,n=0,r={}){let i=_i({...r,stream:"stdout"}),o=process.stdout.columns??80,a=process.stdout.rows??24;return`${$T(e,t,n,o,a).map((s)=>s.map((c)=>c.tone===void 0?c.text:an(c.text,c.tone,i)).join("")).join(`
111
103
  `)}
112
- `}async function pg(e,t={},n={}){let r=await import("@opentui/core"),o=tR(e,n),i=await r.createCliRenderer({...Qv(t),exitOnCtrlC:!0,clearOnShutdown:!0}),a=eR(t),s=new r.TextRenderable(i,{content:hL(r,o.conflicts,o.decisions,0,a,t.width??process.stdout.columns??80,t.height??process.stdout.rows??24)});return i.root.add(s),await new Promise((c,l)=>{let u=0,d=!1,p=(g)=>{if(d)return;d=!0,i.keyInput.off("keypress",y),i.destroy(),c(g)},m=(g)=>{if(d)return;d=!0,i.keyInput.off("keypress",y),i.destroy(),l(g)},f=()=>{s.content=hL(r,o.conflicts,o.decisions,u,a,t.width??process.stdout.columns??80,t.height??process.stdout.rows??24),i.requestRender()},y=(g)=>{try{let x=yL(o,u,g);if(u=x.cursor,x.action==="continue")p({action:"continue",decisions:{...o.decisions}});else if(x.action==="back"||x.action==="cancel")p({action:x.action});else f()}catch(x){m(x)}};i.keyInput.on("keypress",y);try{i.start()}catch(g){m(g)}})}function iJ(e){let t=0,n=0;for(let r of e.conflicts)if(r.decision==="keep")t+=1;else if(r.decision==="replace")n+=1;return{keep:t,replace:n}}function aJ(e,t){let n=nR(e.review),r=t.name.toLowerCase();if(r==="escape")return{selected:e.selected,action:"back"};if(t.ctrl===!0&&r==="c")return{selected:e.selected,action:"cancel"};if(r==="up"||r==="k")return{selected:(e.selected+n.length-1)%n.length,action:"render"};if(r==="down"||r==="j")return{selected:(e.selected+1)%n.length,action:"render"};if(r==="return"||r==="enter"||r==="linefeed")return{selected:e.selected,action:"choose"};return{selected:e.selected,action:"render"}}async function xL(e,t={}){let n=await import("@opentui/core"),r={review:e,selected:0},o=await n.createCliRenderer({...Qv(t),exitOnCtrlC:!0,clearOnShutdown:!0}),i=eR(t),a=new n.TextRenderable(o,{content:gL(n,e,r.selected,i)});return o.root.add(a),await new Promise((s,c)=>{let l=r.selected,u=!1,d=(y)=>{if(u)return;u=!0,o.keyInput.off("keypress",f),o.destroy(),s(y)},p=(y)=>{if(u)return;u=!0,o.keyInput.off("keypress",f),o.destroy(),c(y)},m=()=>{a.content=gL(n,e,l,i),o.requestRender()},f=(y)=>{try{let g=aJ({review:e,selected:l},y);if(l=g.selected,g.action==="cancel")d({action:"cancel"});else if(g.action==="back")d({action:"change"});else if(g.action==="choose"){let x=nR(e)[l];d({action:x})}else m()}catch(g){p(g)}};o.keyInput.on("keypress",f);try{o.start()}catch(y){p(y)}})}function nR(e){return e.conflicts.length>0?["apply","change","resolve","cancel"]:["apply","change","cancel"]}function sJ(e,t){switch(e){case"apply":return t==="upgrade"?"Upgrade":"Install";case"change":return"Change options";case"resolve":return"Resolve conflicts";case"cancel":return"Cancel"}}function aL(e,t){for(let n of e.conflicts){let r=Qc(n),o=t==="replace"&&n.category==="invalid-config"&&!r.includes("replace")&&r.includes("remove")?"remove":t;if(r.includes(o))e.decisions[fg(n)]=o}}function cJ(e,t,n){let r=e.conflicts[t];if(r===void 0)return;let o=fg(r),i=Qc(r);if(i.length===0)return;let a=e.decisions[o]??rR(r,i),s=i.indexOf(a),c=s<0?0:s;e.decisions[o]=i[(c+n+i.length)%i.length]??i[0]}function lJ(e){return e.validDecisions??(e.action==="remove"?["keep","remove","cancel"]:["keep","replace","cancel"])}function Qc(e){return lJ(e).filter((t)=>t!=="cancel")}function rR(e,t){let n=e.category==="invalid-config"?"remove":e.action==="remove"?"remove":"replace";return t.includes(n)?n:t[0]??"cancel"}function sL(e,t){let n=Qc(e),r=t[fg(e)];return n.includes(r??"cancel")?r:rR(e,n)}function SL(e,t,n,r,o){let i=Math.min(Math.max(n,0),Math.max(0,e.length-1)),a=e.length+11>o,s=[ae("HolyCodex \xB7 resolve conflicts","heading"),ae(`${e.length} conflict${e.length===1?"":"s"}`,"hint"),ae("\u2191/\u2193 navigate \u2190/\u2192 change action A replace all K keep all","hint"),ae("Enter continue Esc back Ctrl-C cancel","hint")];if(!a)s.push(ae(""));s.push(ae(" ACTION CONFIG","heading"));let c=Math.max(1,o-(a?9:12)),l=Math.max(0,Math.min(i-c+1,e.length-c));if(e.slice(l,l+c).forEach((y,g)=>{let x=l+g,v=Qc(y),C=sL(y,t),M=x===i?">":" ",N=v.length===0?"blocked":C==="remove"?"replace":C,O=v.length===0?"error":C==="replace"?"warning":C==="keep"?"disabled":"error",k=Bd(y.target??y.key??y.path,r-12);s.push(Rs({text:`${M} ${N.padEnd(7)} `,tone:O},{text:k,tone:x===i?"focus":"argument"}))}),e.length===0)return s.push(ae("No conflicts require a decision.","success")),s;if(!a)s.push(ae(""));let u=e[i],d=sL(u,t),p=Bd(cL(u.existing),r-10),m=u.desired===void 0&&u.action==="remove"?pJ(u):cL(u.desired),f=Bd(m,r-10);return s.push(ae(Bd(u.target??u.key??u.path,r),"focus")),s.push(Rs({text:"current ",tone:"hint"},{text:p})),s.push(Rs({text:"install ",tone:"hint"},{text:f})),s.push(ae(Bd(dJ(u,d),r),"hint")),s}function Bd(e,t){let n=e.replace(/[\r\n\t]+/gu," ").replace(/\s+/gu," ").trim(),r=Math.max(1,t);return n.length<=r?n:`${n.slice(0,Math.max(0,r-1))}\u2026`}function uJ(e){return e.split(/[-_]/u).map((t)=>t.length===0?t:`${t[0].toUpperCase()}${t.slice(1)}`).join(" ")}function cL(e){if(e===void 0)return"(unknown)";if(typeof e==="string")return e;try{return JSON.stringify(e)}catch{return"(unavailable)"}}function dJ(e,t){if(t==="keep")return"Keep the current value.";if(t==="remove")return e.category==="invalid-config"?"Remove the invalid value so HolyCodex can create the required table.":"Remove the managed item.";if(t==="cancel")return"No available action can continue this operation.";return"Replace the current value with the HolyCodex value."}function pJ(e){return e.category==="invalid-config"?"remove this conflicting user-owned value":"remove this managed item"}function fg(e){return e.identity??`${e.path}:${e.key??""}:${e.action}`}function bL(e,t,n){let r=n.name.toLowerCase(),o=ia.length+2;if(r==="escape"||n.ctrl===!0&&r==="c")return{cursor:t,action:"cancel"};if(r==="up"||r==="k")return{cursor:Math.max(0,t-1),action:"render"};if(r==="down"||r==="j")return{cursor:Math.min(o,t+1),action:"render"};if(r==="return"||r==="enter"||r==="linefeed")return e.plugins=_L(e.pluginInput),{cursor:t,action:"review"};if(t===o){if(r==="backspace")dL(e,-1);else if(r==="delete")dL(e,1);else if(r==="left")e.pluginCursor=Math.max(0,e.pluginCursor-1);else if(r==="right")e.pluginCursor=Math.min(e.pluginInput.length,e.pluginCursor+1);else if(r==="home")e.pluginCursor=0;else if(r==="end")e.pluginCursor=e.pluginInput.length;else if(r==="space")uL(e," ");else if(!n.ctrl&&!n.meta&&n.name.length===1&&!wJ(n.name))uL(e,n.name);return{cursor:t,action:"render"}}if(r==="space"&&t>=2)mJ(e,t-2);else if(r==="left")lL(e,t,-1);else if(r==="right")lL(e,t,1);return{cursor:t,action:"render"}}function wL(e){let t={profile:e.profile,tier:e.tier,optional:{...e.optional},officialPlugins:[...e.plugins]};return dn(t)}function fJ(e,t="install",n={}){let r=oR(dn(e));return hJ(r,t==="install"?0:t==="change"?1:2,Qi({...n,stream:"stdout"}))}function oR(e){let t={...en,...e.optional};return{profile:e.profile??"default",tier:e.tier??"standard",optional:{browser_use:t.browser_use??en.browser_use,computer_use:t.computer_use??en.computer_use,sites:t.sites??en.sites},plugins:[...e.officialPlugins??[]],pluginInput:(e.officialPlugins??[]).join(" "),pluginCursor:(e.officialPlugins??[]).join(" ").length}}function lL(e,t,n){if(t===0)e.profile=pL(tJ,e.profile,n);else if(t===1)e.tier=pL(nJ,e.tier,n)}function mJ(e,t){let n=ia[t];if(n!==void 0)e.optional[n]=!e.optional[n]}function uL(e,t){e.pluginInput=`${e.pluginInput.slice(0,e.pluginCursor)}${t}${e.pluginInput.slice(e.pluginCursor)}`,e.pluginCursor+=t.length}function dL(e,t){if(t===-1){if(e.pluginCursor===0)return;e.pluginInput=`${e.pluginInput.slice(0,e.pluginCursor-1)}${e.pluginInput.slice(e.pluginCursor)}`,e.pluginCursor-=1;return}if(e.pluginCursor>=e.pluginInput.length)return;e.pluginInput=`${e.pluginInput.slice(0,e.pluginCursor)}${e.pluginInput.slice(e.pluginCursor+1)}`}function pL(e,t,n){let r=e.indexOf(t);return e[(r+n+e.length)%e.length]??e[0]}function _L(e){let t=[...new Set(e.split(/\s+/u).map((n)=>n.trim()).filter(Boolean))];if(t.length===0)return[];return dn({officialPlugins:t}),t}function hJ(e,t,n=!1){let r=["Install","Change options / Redo","Cancel"];return`${[vn("HolyCodex \xB7 review","heading",n),vn("Review configuration","heading",n),vn("\u2191/\u2193 choose Enter confirm Esc back","hint",n),"",`Profile: ${e.profile}`,`Service tier: ${e.tier}`,"",vn("CAPABILITIES","heading",n),...ia.map((i)=>` ${mg(i)}: ${vn(aR(e.optional[i]),e.optional[i]?"enabled":"disabled",n)}`),...iR(` Additional plugins: ${e.plugins.length===0?"none":e.plugins.join(" ")}`),"",...r.map((i,a)=>vn(`${a===t?"\u203A":" "} ${i}`,a===t?"focus":a===0?"success":a===1?"warning":"error",n))].join(`
104
+ `}function yd(e,t={},n={}){return A(v(function*(){let r=yield*d({try:()=>import("@opentui/core"),catch:(f)=>f}),i=Hy(e,n),o=yield*d({try:()=>r.createCliRenderer({...Jy(t),exitOnCtrlC:!0,clearOnShutdown:!0}),catch:(f)=>f}),a=Wy(t),s=new r.TextRenderable(o,{content:DT(r,i.conflicts,i.decisions,0,a,t.width??process.stdout.columns??80,t.height??process.stdout.rows??24)});o.root.add(s);let c=0;return yield*d({try:()=>zy(o,(f)=>{let l=()=>{s.content=DT(r,i.conflicts,i.decisions,c,a,t.width??process.stdout.columns??80,t.height??process.stdout.rows??24),o.requestRender()},u=LT(i,c,f);if(c=u.cursor,u.action==="continue")return{action:"continue",decisions:{...i.decisions}};if(u.action==="back"||u.action==="cancel")return{action:u.action};l();return}),catch:(f)=>f})}))}function sF(e){let t=0,n=0;for(let r of e.conflicts)if(r.decision==="keep")t+=1;else if(r.decision==="replace")n+=1;return{keep:t,replace:n}}function cF(e,t){let n=Ky(e.review),r=t.name.toLowerCase();if(r==="escape")return{selected:e.selected,action:"back"};if(t.ctrl===!0&&r==="c")return{selected:e.selected,action:"cancel"};if(r==="up"||r==="k")return{selected:(e.selected+n.length-1)%n.length,action:"render"};if(r==="down"||r==="j")return{selected:(e.selected+1)%n.length,action:"render"};if(r==="return"||r==="enter"||r==="linefeed")return{selected:e.selected,action:"choose"};return{selected:e.selected,action:"render"}}function UT(e,t={}){return A(v(function*(){let n=yield*d({try:()=>import("@opentui/core"),catch:(c)=>c}),r={review:e,selected:0},i=yield*d({try:()=>n.createCliRenderer({...Jy(t),exitOnCtrlC:!0,clearOnShutdown:!0}),catch:(c)=>c}),o=Wy(t),a=new n.TextRenderable(i,{content:FT(n,e,r.selected,o)});i.root.add(a);let s=r.selected;return yield*d({try:()=>zy(i,(c)=>{let f=()=>{a.content=FT(n,e,s,o),i.requestRender()},l=cF({review:e,selected:s},c);if(s=l.selected,l.action==="cancel")return{action:"cancel"};if(l.action==="back")return{action:"change"};if(l.action==="choose")return{action:Ky(e)[s]};f();return}),catch:(c)=>c})}))}function Ky(e){return e.conflicts.length>0?["apply","change","resolve","cancel"]:["apply","change","cancel"]}function lF(e,t){switch(e){case"apply":return t==="upgrade"?"Upgrade":"Install";case"change":return"Change options";case"resolve":return"Resolve conflicts";case"cancel":return"Cancel"}}function TT(e,t){for(let n of e.conflicts){let r=ja(n),i=t==="replace"&&n.category==="invalid-config"&&!r.includes("replace")&&r.includes("remove")?"remove":t;if(r.includes(i))e.decisions[Sd(n)]=i}}function uF(e,t,n){let r=e.conflicts[t];if(r===void 0)return;let i=Sd(r),o=ja(r);if(o.length===0)return;let a=e.decisions[i]??Gy(r,o),s=o.indexOf(a),c=s<0?0:s;e.decisions[i]=o[(c+n+o.length)%o.length]??o[0]}function fF(e){return e.validDecisions??(e.action==="remove"?["keep","remove","cancel"]:["keep","replace","cancel"])}function ja(e){return fF(e).filter((t)=>t!=="cancel")}function Gy(e,t){let n=e.category==="invalid-config"?"remove":e.action==="remove"?"remove":"replace";return t.includes(n)?n:t[0]??"cancel"}function kT(e,t){let n=ja(e),r=t[Sd(e)];return n.includes(r??"cancel")?r:Gy(e,n)}function $T(e,t,n,r,i){let o=Math.min(Math.max(n,0),Math.max(0,e.length-1)),a=e.length+11>i,s=[Q("HolyCodex \xB7 resolve conflicts","heading"),Q(`${e.length} conflict${e.length===1?"":"s"}`,"hint"),Q("\u2191/\u2193 navigate \u2190/\u2192 change action A replace all K keep all","hint"),Q("Enter continue Esc back Ctrl-C cancel","hint")];if(!a)s.push(Q(""));s.push(Q(" ACTION CONFIG","heading"));let c=Math.max(1,i-(a?9:12)),f=Math.max(0,Math.min(o-c+1,e.length-c));if(e.slice(f,f+c).forEach((S,m)=>{let x=f+m,E=ja(S),_=kT(S,t),C=x===o?">":" ",N=E.length===0?"blocked":_==="remove"?"replace":_,D=E.length===0?"error":_==="replace"?"warning":_==="keep"?"disabled":"error",F=ml(S.target??S.key??S.path,r-12);s.push(To({text:`${C} ${N.padEnd(7)} `,tone:D},{text:F,tone:x===o?"focus":"argument"}))}),e.length===0)return s.push(Q("No conflicts require a decision.","success")),s;if(!a)s.push(Q(""));let l=e[o],u=kT(l,t),g=ml(RT(l.existing),r-10),h=l.desired===void 0&&l.action==="remove"?mF(l):RT(l.desired),y=ml(h,r-10);return s.push(Q(ml(l.target??l.key??l.path,r),"focus")),s.push(To({text:"current ",tone:"hint"},{text:g})),s.push(To({text:"install ",tone:"hint"},{text:y})),s.push(Q(ml(pF(l,u),r),"hint")),s}function ml(e,t){let n=e.replace(/[\r\n\t]+/gu," ").replace(/\s+/gu," ").trim(),r=Math.max(1,t);return n.length<=r?n:`${n.slice(0,Math.max(0,r-1))}\u2026`}function dF(e){return e.split(/[-_]/u).map((t)=>t.length===0?t:`${t[0].toUpperCase()}${t.slice(1)}`).join(" ")}function RT(e){if(e===void 0)return"(unknown)";if(typeof e==="string")return e;let t=Oe(Le(V({try:()=>JSON.stringify(e),catch:(n)=>n})));return t._tag==="Success"?t.success:"(unavailable)"}function pF(e,t){if(t==="keep")return"Keep the current value.";if(t==="remove")return e.category==="invalid-config"?"Remove the invalid value so HolyCodex can create the required table.":"Remove the managed item.";if(t==="cancel")return"No available action can continue this operation.";return"Replace the current value with the HolyCodex value."}function mF(e){return e.category==="invalid-config"?"remove this conflicting user-owned value":"remove this managed item"}function Sd(e){return e.identity??`${e.path}:${e.key??""}:${e.action}`}function jT(e,t,n){let r=n.name.toLowerCase(),i=Oi.length+2;if(r==="escape"||n.ctrl===!0&&r==="c")return{cursor:t,action:"cancel"};if(r==="up"||r==="k")return{cursor:Math.max(0,t-1),action:"render"};if(r==="down"||r==="j")return{cursor:Math.min(i,t+1),action:"render"};if(r==="return"||r==="enter"||r==="linefeed")return e.plugins=VT(e.pluginInput),{cursor:t,action:"review"};if(t===i){if(r==="backspace")OT(e,-1);else if(r==="delete")OT(e,1);else if(r==="left")e.pluginCursor=Math.max(0,e.pluginCursor-1);else if(r==="right")e.pluginCursor=Math.min(e.pluginInput.length,e.pluginCursor+1);else if(r==="home")e.pluginCursor=0;else if(r==="end")e.pluginCursor=e.pluginInput.length;else if(r==="space")PT(e," ");else if(!n.ctrl&&!n.meta&&n.name.length===1&&!_F(n.name))PT(e,n.name);return{cursor:t,action:"render"}}if(r==="space"&&t>=2)hF(e,t-2);else if(r==="left")IT(e,t,-1);else if(r==="right")IT(e,t,1);return{cursor:t,action:"render"}}function BT(e){let t={profile:e.profile,tier:e.tier,optional:{...e.optional},officialPlugins:[...e.plugins]};return Yt(t)}function gF(e,t="install",n={}){let r=Yy(Yt(e));return yF(r,t==="install"?0:t==="change"?1:2,_i({...n,stream:"stdout"}))}function Yy(e){let t={...Mt,...e.optional};return{profile:e.profile??"default",tier:e.tier??"standard",optional:{browser_use:t.browser_use??Mt.browser_use,computer_use:t.computer_use??Mt.computer_use,sites:t.sites??Mt.sites},plugins:[...e.officialPlugins??[]],pluginInput:(e.officialPlugins??[]).join(" "),pluginCursor:(e.officialPlugins??[]).join(" ").length}}function IT(e,t,n){if(t===0)e.profile=AT(rF,e.profile,n);else if(t===1)e.tier=AT(iF,e.tier,n)}function hF(e,t){let n=Oi[t];if(n!==void 0)e.optional[n]=!e.optional[n]}function PT(e,t){e.pluginInput=`${e.pluginInput.slice(0,e.pluginCursor)}${t}${e.pluginInput.slice(e.pluginCursor)}`,e.pluginCursor+=t.length}function OT(e,t){if(t===-1){if(e.pluginCursor===0)return;e.pluginInput=`${e.pluginInput.slice(0,e.pluginCursor-1)}${e.pluginInput.slice(e.pluginCursor)}`,e.pluginCursor-=1;return}if(e.pluginCursor>=e.pluginInput.length)return;e.pluginInput=`${e.pluginInput.slice(0,e.pluginCursor)}${e.pluginInput.slice(e.pluginCursor+1)}`}function AT(e,t,n){let r=e.indexOf(t);return e[(r+n+e.length)%e.length]??e[0]}function VT(e){let t=[...new Set(e.split(/\s+/u).map((n)=>n.trim()).filter(Boolean))];if(t.length===0)return[];return Yt({officialPlugins:t}),t}function yF(e,t,n=!1){let r=["Install","Change options / Redo","Cancel"];return`${[an("HolyCodex \xB7 review","heading",n),an("Review configuration","heading",n),an("\u2191/\u2193 choose Enter confirm Esc back","hint",n),"",`Profile: ${e.profile}`,`Service tier: ${e.tier}`,"",an("CAPABILITIES","heading",n),...Oi.map((o)=>` ${xd(o)}: ${an(Xy(e.optional[o]),e.optional[o]?"enabled":"disabled",n)}`),...Zy(` Additional plugins: ${e.plugins.length===0?"none":e.plugins.join(" ")}`),"",...r.map((o,a)=>an(`${a===t?"\u203A":" "} ${o}`,a===t?"focus":a===0?"success":a===1?"warning":"error",n))].join(`
113
105
  `)}
114
- `}function fL(e,t,n,r){let o=ia.length+2,i=n<2?n===0?"Choose the routing profile for the Root session.":"Choose how quickly services handle work.":n<o?bJ(ia[n-2]):"Optional plugin IDs separated by spaces. Enter continues to review.",a=[ae("HolyCodex \xB7 install","heading"),ae("\u2191/\u2193 focus \u2190/\u2192 change choice Space toggle Enter review Esc cancel","hint"),ae(""),ae("PROFILE","heading"),mL("Profile",t.profile,n===0),mL("Service tier",t.tier,n===1),ae(""),ae("OPTIONAL CAPABILITIES","heading"),...ia.map((s,c)=>gJ(s,t.optional[s],n===c+2)),ae(""),ae("ADDITIONAL PLUGINS","heading"),...iR(`${n===o?"\u276F":" "} ${t.pluginInput||"(none)"}`).map((s)=>ae(s,n===o?"focus":"argument")),ae(""),ae(i,"hint")];return ug(e,a,r)}function mL(e,t,n){return ae(`${n?"\u276F":" "} ${e.padEnd(13)} ${t}`,n?"focus":"argument")}function gJ(e,t,n){let r=t?"[x] enabled":"[ ] disabled";return ae(`${n?"\u276F":" "} ${mg(e).padEnd(14)} ${r}`,n?"focus":t?"enabled":"disabled")}function yJ(e,t,n,r){let o=["Install","Change options / Redo","Cancel"],i=[ae("HolyCodex \xB7 review","heading"),ae("Review configuration","heading"),ae("\u2191/\u2193 choose Enter confirm Esc back","hint"),ae(""),ae(`Profile: ${t.profile}`),ae(`Service tier: ${t.tier}`),ae(""),ae("CAPABILITIES","heading"),...ia.map((a)=>Rs({text:` ${mg(a)}: `},{text:aR(t.optional[a]),tone:t.optional[a]?"enabled":"disabled"})),...iR(` Additional plugins: ${t.plugins.length===0?"none":t.plugins.join(" ")}`).map((a)=>ae(a,"argument")),ae(""),...o.map((a,s)=>ae(`${s===n?"\u203A":" "} ${a}`,s===n?"focus":s===0?"success":s===1?"warning":"error"))];return ug(e,i,r)}function hL(e,t,n,r,o,i,a){return ug(e,SL(t,n,r,i,a),o)}function gL(e,t,n,r){let o=t.operation==="upgrade"?"upgrade":"install",i=t.operation==="upgrade"&&t.fromVersion!==void 0?`${t.fromVersion} \u2192 ${t.toVersion}`:t.toVersion,a=Object.values(t.conflictCounts).reduce((u,d)=>u+d,0),s=iJ(t),c=s.keep+s.replace,l=[ae(`HolyCodex \xB7 ${o} review`,"heading"),ae("Review the complete preflight plan before applying changes.","hint"),ae(`Version: ${i}`),ae(`Profile: ${t.profile}`),ae(`Service tier: ${t.tier}`),ae("CAPABILITIES","heading"),...ia.map((u)=>Rs({text:` ${mg(u)}: `},{text:aR(t.capabilities[u]),tone:t.capabilities[u]?"enabled":"disabled"})),ae(` Additional plugins: ${t.additionalPlugins.length===0?"none":t.additionalPlugins.join(" ")}`,"argument"),ae(`CONFLICTS (${a})`,"heading"),...a===0?[ae(" none")]:Object.entries(t.conflictCounts).map(([u,d])=>ae(` ${uJ(u)}: ${d}`)),...a===0?[]:[ae(`DECISIONS (${c})`,"heading"),ae(` Keep: ${s.keep}`),ae(` Replace: ${s.replace}`)],ae("PREREQUISITES","heading"),...t.tools.length===0?[ae(" none")]:t.tools.map((u)=>xJ(u)),ae("\u2191/\u2193 or j/k choose Enter select Esc back Ctrl-C cancel","hint"),...nR(t).map((u,d)=>ae(`${d===n?"\u203A":" "} ${sJ(u,t.operation)}`,d===n?"focus":u==="apply"?"success":u==="change"||u==="resolve"?"warning":"error"))];return ug(e,l,r)}function xJ(e){let t=e.name.toLowerCase()==="context7",n=t?SJ(e.status):e.status,r=e.status==="ready"||e.status==="healthy"?"success":"warning",o=t||e.detail===void 0?"":` (${e.detail})`;return Rs({text:` ${e.name}: `},{text:n,tone:r},...o.length===0?[]:[{text:o}])}function SJ(e){return e==="ready"?"Use available ctx7":"Attempt optional managed ctx7 install"}function bJ(e){switch(e){case"sites":return"ChatGPT Sites may depend on your account, region, workspace policy, or supported Codex surface.";case"browser_use":return"Browser Use depends on the Codex surface and runtime; it may be unavailable where unsupported.";case"computer_use":return"Computer Use has stronger platform and surface restrictions and can take external actions."}}function iR(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 mg(e){switch(e){case"sites":return"ChatGPT Sites";case"browser_use":return"Browser Use";case"computer_use":return"Computer Use"}}function aR(e){return e?"enabled":"disabled"}function wJ(e){let t=e.codePointAt(0)??0;return t<=31||t===127}Dd();hd();tg();Rd();Od();ds();Hc();async function dR(e,t={}){if(e.length===0||fd(e)||e[0]==="help"){let r=e[0]==="help"?e.slice(1).filter((o)=>!o.startsWith("-"))[0]:md(e);return{envelope:RL(r===void 0?"help":`${r} help`,{help:pd(r)}),exitCode:0}}let n;try{n=Lh(e);let r=await TL(n,t);return{envelope:RL(n.command,r),exitCode:qJ(n.command,r)}}catch(r){return DJ(n?.command??jJ(e),r)}}async function TL(e,t){switch(e.command){case"install":return sn(await RJ(e,t));case"doctor":{let n=Jd(e,t),r=Pr(n,t.env);return sn(await Uv({...n,officialPluginManager:n.officialPluginManager??await _J(r.codexHome,t.env)},t.env))}case"remove":return sn(await OJ(e,t));case"version":return sn(await kJ(e,t));case"help":return{help:pd(e.positionals[0])};default:throw new el("invalid_argument","Unknown command.")}}async function _J(e,t){try{return await ti.discover(t)}catch(n){if(vJ(n))return new Jh(e);throw n}}function vJ(e){return e instanceof Error&&"code"in e&&e.code==="discovery_failed"&&e.message.startsWith("No Codex executable was found")}async function RJ(e,t){let n=CJ(e),r=await TJ(e,t,n);if("cancelled"in r)return r;return await Ss(r,Jd(e,t),t.env)}async function TJ(e,t,n){if(e.options.json!==!0&&e.options.yes!==!0&&t.io?.stdoutIsTTY===!0&&t.io?.stderrIsTTY===!0){let i=await tL(Jd(e,t),t.env),a=await(t.io?.installWizard??dg)({...i,...n,...i.optional===void 0&&n.optional===void 0?{}:{optional:{...i.optional,...n.optional}}});if(a.action==="cancel")return{cancelled:!0};return dn(a.request)}let o=await CL(e,t,"Install HolyCodex into the selected Codex home?");if(o==="cancelled")return{cancelled:!0};if(o==="unavailable")throw new el("non_tty_confirmation_required","Install requires --yes in non-interactive mode.");return dn(n)}function CJ(e){let t=AJ(e),n=PJ(e),r=IJ(e),o=e.options["add-plugin"]===void 0?void 0:MJ(e,"add-plugin");return dn({...t===void 0?{}:{profile:t},...n===void 0?{}:{tier:n},...r===void 0?{}:{optional:r},...o===void 0?{}:{officialPlugins:o}})}async function OJ(e,t){let n=await CL(e,t,"Remove HolyCodex-owned Codex state?");if(n==="cancelled")return{cancelled:!0,removed:[],preserved:[],reasons:["cancelled"]};if(n==="unavailable"){let o=(await $v(Jd(e,t),t.env))[0];if(o!==void 0)throw new _("confirmation_required","Modified HolyCodex-owned state requires confirmation before removal.",void 0,{path:o.path,...o.key===void 0?{}:{key:o.key},action:o.action});throw new el("non_tty_confirmation_required","Remove requires --yes in non-interactive mode.")}return await Md(Jd(e,t),t.env)}async function kJ(e,t){let n=e.positionals[0];if(!n)return{version:await Bc()};return await _v(n,e.options["dry-run"]===!0)}async function CL(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 EJ(t,n)}async function EJ(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 IJ(e){let t={};for(let n of["browser_use","computer_use","sites"]){let r=n.replaceAll("_","-");if(e.options[r]===!0)t[n]=!0;else if(e.options[r]===!1)t[n]=!1;else if(e.options[`no-${r}`]===!0)t[n]=!1}return Object.keys(t).length===0?void 0:t}function AJ(e){let t=e.options.profile;if(typeof t!=="string")return;let n=oo(t);return n.ok?n.value.name:void 0}function PJ(e){let t=e.options.tier;return t==="standard"||t==="fast"||t==="fast-all"?t:void 0}function MJ(e,t){let n=e.options[t];return Array.isArray(n)?n.filter((r)=>typeof r==="string"):[]}function Jd(e,t){let n=t.installer??{},r=e.options.json===!0,o=!r&&e.options.yes!==!0&&t.io?.stdoutIsTTY===!0&&t.io?.stderrIsTTY===!0,i=(y)=>{n.onProgress?.(y),t.onProgress?.(y),HJ(t,r,y.message)},a=new Map,s=(y,g)=>{for(let x of y){let v=Vd(x),C=g[v];if(C!==void 0)a.set(v,C)}return g},c=n.resolveConflict??(async(y)=>{if(e.options.yes===!0){let C=lR(y);return vL(t,[y]),C==="keep"?"decline":C==="cancel"?"cancel":"accept"}if(e.options.json===!0||t.io?.stdoutIsTTY!==!0||t.io?.stderrIsTTY!==!0)throw new _("confirmation_required",`Review the modified HolyCodex-owned state at ${y.key===void 0?y.path:`${y.path} (${y.key})`} in an interactive terminal; --yes preserves user changes.`,void 0,{path:y.path,...y.key===void 0?{}:{key:y.key}});let g=Vd(y),x=await pg([y],{},Object.fromEntries(a));if(x.action==="back")return"decline";if(x.action!=="continue")return"cancel";let v=x.decisions[g];if(v!==void 0)a.set(g,v);if(v==="replace"||v==="remove")return"accept";if(v==="keep")return"decline";return"cancel"}),l=n.resolveConflicts??(e.options.yes===!0?async(y)=>{let g=Object.fromEntries(y.map((x)=>[Vd(x),lR(x)]));return vL(t,y),g}:async(y)=>{if(e.options.json===!0||t.io?.stdoutIsTTY!==!0||t.io?.stderrIsTTY!==!0)throw new _("confirmation_required","Managed conflicts require an interactive review or --yes.");let g=await pg(y,{},Object.fromEntries(a));if(g.action==="back"){let x=Object.fromEntries(y.map((v)=>{let C=v.validDecisions??(v.action==="remove"?["keep","remove","cancel"]:["keep","replace","cancel"]);return[Vd(v),C.includes("keep")?"keep":"cancel"]}));return s(y,x)}if(g.action==="cancel")throw new _("confirmation_required","Conflict review was cancelled.");if(g.action==="continue")return g.decisions;throw new _("confirmation_required","Conflict review was reopened.")}),u=async(y)=>s(y,await l(y)),p=n.reviewInstall??t.io?.installReview??(e.options.yes===!0?async()=>({action:"apply"}):o?async(y)=>await xL(y):void 0),m=p===void 0?void 0:async(y)=>{let g=FJ(y,a),x=await p(LJ(g));if(x.action!=="change")return x;if(x.request!==void 0)return{action:"change",request:dn(x.request)};if(!o)throw new _("confirmation_required","Changing install options requires an interactive review.");let v=await(t.io?.installWizard??dg)(NJ(g));if(v.action==="cancel")return{action:"cancel"};return{action:"change",request:dn(v.request)}},f=e.options["codex-home"];if(typeof f!=="string")return{...n,onProgress:i,resolveConflict:c,resolveConflicts:u,...m===void 0?{}:{reviewInstall:m},...t.now?{now:t.now}:{}};return{...n,paths:{...n.paths,codexHome:f},onProgress:i,resolveConflict:c,resolveConflicts:u,...m===void 0?{}:{reviewInstall:m},...t.now?{now:t.now}:{}}}function lR(e){let t=e.validDecisions??(e.action==="remove"?["keep","remove","cancel"]:["keep","replace","cancel"]),n=e.action==="remove"?"remove":"replace",r=t.includes(n)?n:void 0;if(r===void 0)throw new _("confirmation_required",`--yes cannot resolve ${e.target??e.key??e.path}; choose ${t.join(", ")}.`,void 0,{path:e.path,...e.key===void 0?{}:{key:e.key}});return r}function vL(e,t){if(t.length===0)return;let n=t.map((r)=>{let o=lR(r),i=r.key===void 0?r.path:`${r.path} (${r.key})`;return o==="keep"?void 0:`${o} ${i}`}).filter((r)=>r!==void 0);if(n.length===0)return;e.io?.writeStderr?.(`Warning: --yes will apply these conflict decisions: ${n.join("; ")}. This may overwrite existing Codex configuration.
115
- `)}function NJ(e){return dn({profile:e.profile,tier:e.tier,optional:e.capabilities,officialPlugins:e.additionalPlugins})}function Vd(e){return e.identity??e.path}function FJ(e,t){if(t.size===0||e.conflicts.length===0)return e;return{...e,conflicts:e.conflicts.map((n)=>{let r=t.get(Vd(n));return r===void 0?n:{...n,decision:r}})}}function LJ(e){let{fromVersion:t,...n}=e;return{...n,operation:"install"}}function RL(e,t){let n=dh({schema_version:So,ok:!0,command:e,data:t,warnings:[]});if(!n.ok)throw new el("internal_error","The success envelope failed validation.");return n.value}function DJ(e,t){let n=UJ(t,e),r=dh({schema_version:So,ok:!1,command:e,error:{code:n.code,message:n.message,details:n.details},warnings:[]});if(!r.ok)return{envelope:{schema_version:So,ok:!1,command:"internal-error",error:{code:"internal_error",message:"The CLI failure envelope was invalid.",details:{}},warnings:[]},exitCode:5};return{envelope:r.value,exitCode:n.exitCode}}function qJ(e,t){if(e==="doctor"&&ai(t)&&t.healthy===!1)return 4;if(e==="remove"&&ai(t)){if(t.cancelled===!0)return 1;if(aa(t,"preserved").length>0||aa(t,"reasons").length>0)return 4}return 0}function UJ(e,t){if(e instanceof lt)return{code:e.code,message:Wd(e.message),details:e.details,exitCode:1};if(e instanceof el)return{code:e.code,message:Wd(e.message),details:{},exitCode:e.code==="internal_error"?5:1};if(e instanceof nr)return{code:"trust_boundary_failed",message:Wd(e.message),details:{},exitCode:4};if(e instanceof _){let n=e,r=n.code==="confirmation_required"?1:n.code==="capability_denied"?2:n.code==="state_corrupt"?4:3;return{code:n.code,message:cR(n.message),details:sR(n.details,n.causeValue,t),exitCode:r}}if(e instanceof uo){let n=["timeout","output_limit","cancelled","readback_mismatch"].includes(e.code),r=e.code==="plugin_disabled"||e.code==="plugin_missing"||e.code==="command_failed";return{code:n?"effect_uncertain":r?"capability_denied":"install_failed",message:cR(e.message),details:sR(e.details,e.causeValue,t),exitCode:n?4:r?2:3}}if(e instanceof lo)return{code:e.code,message:cR(e.message),details:sR({},e.causeValue,t),exitCode:4};if(e instanceof Qo)return{code:e.code,message:Wd(e.message),details:{},exitCode:1};if(e instanceof Error)return{code:"internal_error",message:`The ${t} command failed unexpectedly.`,details:{operation:t,cause:sd(`${e.name}: ${e.message}`).join(" ").slice(0,512)},exitCode:5};return{code:"internal_error",message:`The ${t} command failed unexpectedly.`,details:{operation:t,cause:"A non-Error value was thrown."},exitCode:5}}function sR(e,t,n){let r={...e};if(t!==void 0){if(typeof r.operation!=="string")r.operation=n;r.cause=sd($J(t)).join(" ").slice(0,512)}return r}function $J(e){if(e instanceof Error)return`${e.name}: ${e.message}`;if(typeof e==="string")return e;return"The operation failed with a non-Error cause."}function cR(e){return Wd(sd(e).join(" "))}function jJ(e){return e.find((t)=>!t.startsWith("-"))??"unknown"}function Wd(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 ai(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function HJ(e,t,n){if(t||e.io?.stderrIsTTY===!1)return;e.io?.writeStderr?.(`${OL(n,{stderrIsTTY:e.io?.stderrIsTTY,env:e.env})}
116
- `)}function hg(e,t={}){let n=Qi(t);if(e.envelope.ok){if(e.envelope.command==="version")return BJ(e.envelope.data);if(e.envelope.command==="install")return VJ(e.envelope.data,n);if(e.envelope.command==="remove")return WJ(e.envelope.data,n);if(e.envelope.command==="doctor")return zJ(e.envelope.data,n);return`${_e("\u2714","green",n)} ${_e(e.envelope.command,"heading",n)}
117
- ${KJ(e.envelope.data,n)}`}let r=e.envelope.error,o=GJ(r.code,e.envelope.command);return[`${_e("\u2716","red",n)} ${_e(e.envelope.command,"heading",n)}`,` ${_e(r.code,"red",n)}: ${r.message}`,...JJ(r.details,n),...o===void 0?[]:[` hint: ${o}`],""].join(`
118
- `)}function OL(e,t={}){return`${_e("\u2022","cyan",Qi({...t,stream:"stderr"}))} ${e}`}function BJ(e){if(ai(e)&&typeof e.version==="string")return`holycodex ${e.version}
119
- `;if(ai(e)&&typeof e.next==="string"){let t=typeof e.previous==="string"?` (from ${e.previous})`:"";return`holycodex version updated to ${e.next}${t}
106
+ `}function MT(e,t,n,r){let i=Oi.length+2,o=n<2?n===0?"Choose the routing profile for the Root session.":"Choose how quickly services handle work.":n<i?bF(Oi[n-2]):"Optional plugin IDs separated by spaces. Enter continues to review.",a=[Q("HolyCodex \xB7 install","heading"),Q("\u2191/\u2193 focus \u2190/\u2192 change choice Space toggle Enter review Esc cancel","hint"),Q(""),Q("PROFILE","heading"),NT("Profile",t.profile,n===0),NT("Service tier",t.tier,n===1),Q(""),Q("OPTIONAL CAPABILITIES","heading"),...Oi.map((s,c)=>SF(s,t.optional[s],n===c+2)),Q(""),Q("ADDITIONAL PLUGINS","heading"),...Zy(`${n===i?"\u276F":" "} ${t.pluginInput||"(none)"}`).map((s)=>Q(s,n===i?"focus":"argument")),Q(""),Q(o,"hint")];return gd(e,a,r)}function NT(e,t,n){return Q(`${n?"\u276F":" "} ${e.padEnd(13)} ${t}`,n?"focus":"argument")}function SF(e,t,n){let r=t?"[x] enabled":"[ ] disabled";return Q(`${n?"\u276F":" "} ${xd(e).padEnd(14)} ${r}`,n?"focus":t?"enabled":"disabled")}function xF(e,t,n,r){let i=["Install","Change options / Redo","Cancel"],o=[Q("HolyCodex \xB7 review","heading"),Q("Review configuration","heading"),Q("\u2191/\u2193 choose Enter confirm Esc back","hint"),Q(""),Q(`Profile: ${t.profile}`),Q(`Service tier: ${t.tier}`),Q(""),Q("CAPABILITIES","heading"),...Oi.map((a)=>To({text:` ${xd(a)}: `},{text:Xy(t.optional[a]),tone:t.optional[a]?"enabled":"disabled"})),...Zy(` Additional plugins: ${t.plugins.length===0?"none":t.plugins.join(" ")}`).map((a)=>Q(a,"argument")),Q(""),...i.map((a,s)=>Q(`${s===n?"\u203A":" "} ${a}`,s===n?"focus":s===0?"success":s===1?"warning":"error"))];return gd(e,o,r)}function DT(e,t,n,r,i,o,a){return gd(e,$T(t,n,r,o,a),i)}function FT(e,t,n,r){let i=t.operation==="upgrade"?"upgrade":"install",o=t.operation==="upgrade"&&t.fromVersion!==void 0?`${t.fromVersion} \u2192 ${t.toVersion}`:t.toVersion,a=Object.values(t.conflictCounts).reduce((l,u)=>l+u,0),s=sF(t),c=s.keep+s.replace,f=[Q(`HolyCodex \xB7 ${i} review`,"heading"),Q("Review the complete preflight plan before applying changes.","hint"),Q(`Version: ${o}`),Q(`Profile: ${t.profile}`),Q(`Service tier: ${t.tier}`),Q("CAPABILITIES","heading"),...Oi.map((l)=>To({text:` ${xd(l)}: `},{text:Xy(t.capabilities[l]),tone:t.capabilities[l]?"enabled":"disabled"})),Q(` Additional plugins: ${t.additionalPlugins.length===0?"none":t.additionalPlugins.join(" ")}`,"argument"),Q(`CONFLICTS (${a})`,"heading"),...a===0?[Q(" none")]:Object.entries(t.conflictCounts).map(([l,u])=>Q(` ${dF(l)}: ${u}`)),...a===0?[]:[Q(`DECISIONS (${c})`,"heading"),Q(` Keep: ${s.keep}`),Q(` Replace: ${s.replace}`)],Q("PREREQUISITES","heading"),...t.tools.length===0?[Q(" none")]:t.tools.map((l)=>EF(l)),Q("\u2191/\u2193 or j/k choose Enter select Esc back Ctrl-C cancel","hint"),...Ky(t).map((l,u)=>Q(`${u===n?"\u203A":" "} ${lF(l,t.operation)}`,u===n?"focus":l==="apply"?"success":l==="change"||l==="resolve"?"warning":"error"))];return gd(e,f,r)}function EF(e){let t=e.name.toLowerCase()==="context7",n=t?vF(e.status):e.status,r=e.status==="ready"||e.status==="healthy"?"success":"warning",i=t||e.detail===void 0?"":` (${e.detail})`;return To({text:` ${e.name}: `},{text:n,tone:r},...i.length===0?[]:[{text:i}])}function vF(e){return e==="ready"?"Use available ctx7":"Attempt optional managed ctx7 install"}function bF(e){switch(e){case"sites":return"ChatGPT Sites may depend on your account, region, workspace policy, or supported Codex surface.";case"browser_use":return"Browser Use depends on the Codex surface and runtime; it may be unavailable where unsupported.";case"computer_use":return"Computer Use has stronger platform and surface restrictions and can take external actions."}}function Zy(e,t=76){if(e.length<=t)return[e];let n=[],r=e;while(r.length>t){let i=r.lastIndexOf(" ",t),o=i>0?i:t;n.push(r.slice(0,o)),r=r.slice(i>0?o+1:o)}if(r.length>0)n.push(r);return n}function xd(e){switch(e){case"sites":return"ChatGPT Sites";case"browser_use":return"Browser Use";case"computer_use":return"Computer Use"}}function Xy(e){return e?"enabled":"disabled"}function _F(e){let t=e.codePointAt(0)??0;return t<=31||t===127}cl();$f();ad();Wc();Kc();ho();Oa();function rS(e,t={}){let n=t.env===void 0?{...t,env:process.env}:t;if(e.length===0||Nc(e)||e[0]==="help"){let i=e[0]==="help"?e.slice(1).filter((o)=>!o.startsWith("-"))[0]:Dc(e);return A(zT(i===void 0?"help":`${i} help`,{help:Mc(i)}).pipe(de((o)=>({envelope:o,exitCode:0}))))}let r=V({try:()=>Uf(e),catch:(i)=>i}).pipe(Re((i)=>WT(i,n).pipe(Re((o)=>zT(i.command,o).pipe(de((a)=>({envelope:a,exitCode:jF(i.command,o)})))),Pt((o)=>M(JT(i.command,o))))),Pt((i)=>M(JT(qF(e),i))));return A(r)}function wF(e,t){let n=t.env===void 0?{...t,env:process.env}:t;return A(WT(e,n))}function WT(e,t){let n=t.env??{};return v(function*(){switch(e.command){case"install":return Wt(yield*kF(e,t));case"doctor":{let r=xl(e,t),i=Yn(r,n),o=r.officialPluginManager??(yield*CF(i.codexHome,n));return Wt(yield*id({...r,officialPluginManager:o},n))}case"remove":return Wt(yield*PF(e,t));case"version":return Wt(yield*OF(e));case"help":return{help:Mc(e.positionals[0])};default:return yield*p(new Ba("invalid_argument","Unknown command."))}})}function CF(e,t){return d({try:()=>Er.discover(t),catch:(n)=>n}).pipe(me(TF,()=>M(new Zf(e))))}function TF(e){return e instanceof Error&&"code"in e&&e.code==="discovery_failed"&&e.message.startsWith("No Codex executable was found")}function kF(e,t){return v(function*(){let n=yield*V({try:()=>IF(e),catch:(i)=>i}),r=yield*RF(e,t,n);if("cancelled"in r)return r;return yield*dl(r,xl(e,t),t.env)})}function RF(e,t,n){if(e.options.json!==!0&&e.options.yes!==!0&&t.io?.stdoutIsTTY===!0&&t.io?.stderrIsTTY===!0)return v(function*(){let i=yield*ET(xl(e,t),t.env??{}),o=yield*d({try:()=>(t.io?.installWizard??hd)({...i,...n,...i.optional===void 0&&n.optional===void 0?{}:{optional:{...i.optional,...n.optional}}}),catch:(a)=>a});if(o.action==="cancel")return{cancelled:!0};return yield*V({try:()=>Yt(o.request),catch:(a)=>a})});return v(function*(){let i=yield*HT(e,t,"Install HolyCodex into the selected Codex home?");if(i==="cancelled")return{cancelled:!0};if(i==="unavailable")return yield*p(new Ba("non_tty_confirmation_required","Install requires --yes in non-interactive mode."));return yield*V({try:()=>Yt(n),catch:(o)=>o})})}function IF(e){let t=NF(e),n=DF(e),r=MF(e),i=e.options["add-plugin"]===void 0?void 0:FF(e,"add-plugin");return Yt({...t===void 0?{}:{profile:t},...n===void 0?{}:{tier:n},...r===void 0?{}:{optional:r},...i===void 0?{}:{officialPlugins:i}})}function PF(e,t){return v(function*(){let n=yield*HT(e,t,"Remove HolyCodex-owned Codex state?");if(n==="cancelled")return{cancelled:!0,removed:[],preserved:[],reasons:["cancelled"]};if(n==="unavailable"){let i=(yield*rl(xl(e,t),t.env??{}))[0];if(i!==void 0)return yield*p(new R("confirmation_required","Modified HolyCodex-owned state requires confirmation before removal.",void 0,{path:i.path,...i.key===void 0?{}:{key:i.key},action:i.action}));return yield*p(new Ba("non_tty_confirmation_required","Remove requires --yes in non-interactive mode."))}return yield*od(xl(e,t),t.env??{})})}function OF(e){let t=e.positionals[0];if(!t)return d({try:()=>oy(),catch:(n)=>n}).pipe(de((n)=>({version:n})));return d({try:()=>cy(t,e.options["dry-run"]===!0),catch:(n)=>n})}function HT(e,t,n){if(e.options.yes===!0)return M("confirmed");if(e.options.json===!0||t.io?.stdoutIsTTY!==!0||t.io?.stderrIsTTY!==!0)return M("unavailable");return AF(t,n)}function AF(e,t){if(e.io?.confirm===void 0)return M("unavailable");return d({try:()=>e.io.confirm(t),catch:(n)=>n}).pipe(de((n)=>n==="confirmed"||n==="cancelled"||n==="unavailable"?n:n?"confirmed":"cancelled"))}function MF(e){let t={};for(let n of["browser_use","computer_use","sites"]){let r=n.replaceAll("_","-");if(e.options[r]===!0)t[n]=!0;else if(e.options[r]===!1)t[n]=!1;else if(e.options[`no-${r}`]===!0)t[n]=!1}return Object.keys(t).length===0?void 0:t}function NF(e){let t=Pe(rn)(e.options.profile);return Ve(t)?t.success:void 0}function DF(e){let t=Pe(yn)(e.options.tier);return Ve(t)?t.success:void 0}function FF(e,t){let n=Pe(j(w))(e.options[t]);return Ve(n)?n.success:[]}function xl(e,t){let n=t.installer??{},r=e.options.json===!0,i=!r&&e.options.yes!==!0&&t.io?.stdoutIsTTY===!0&&t.io?.stderrIsTTY===!0,o=(S)=>{n.onProgress?.(S),t.onProgress?.(S),zF(t,r,S.message)},a=new Map,s=(S,m)=>{for(let x of S){let E=gl(x),_=m[E];if(_!==void 0)a.set(E,_)}return m},c=n.resolveConflict??((S)=>v(function*(){if(e.options.yes===!0){let _=yield*tS(S);return yield*qT(t,[S]),_==="keep"?"decline":_==="cancel"?"cancel":"accept"}if(e.options.json===!0||t.io?.stdoutIsTTY!==!0||t.io?.stderrIsTTY!==!0)return yield*p(new R("confirmation_required",`Review the modified HolyCodex-owned state at ${S.key===void 0?S.path:`${S.path} (${S.key})`} in an interactive terminal; --yes preserves user changes.`,void 0,{path:S.path,...S.key===void 0?{}:{key:S.key}}));let m=gl(S),x=yield*d({try:()=>yd([S],{},Object.fromEntries(a)),catch:(_)=>_});if(x.action==="back")return"decline";if(x.action!=="continue")return"cancel";let E=x.decisions[m];if(E!==void 0)a.set(m,E);if(E==="replace"||E==="remove")return"accept";if(E==="keep")return"decline";return"cancel"})),f=n.resolveConflicts??(e.options.yes===!0?(S)=>v(function*(){let m={};for(let x of S)m[gl(x)]=yield*tS(x);return yield*qT(t,S),m}):(S)=>v(function*(){if(e.options.json===!0||t.io?.stdoutIsTTY!==!0||t.io?.stderrIsTTY!==!0)return yield*p(new R("confirmation_required","Managed conflicts require an interactive review or --yes."));let m=yield*d({try:()=>yd(S,{},Object.fromEntries(a)),catch:(x)=>x});if(m.action==="back"){let x=Object.fromEntries(S.map((E)=>{let _=E.validDecisions??(E.action==="remove"?["keep","remove","cancel"]:["keep","replace","cancel"]);return[gl(E),_.includes("keep")?"keep":"cancel"]}));return s(S,x)}if(m.action==="cancel")return yield*p(new R("confirmation_required","Conflict review was cancelled."));if(m.action==="continue")return m.decisions;return yield*p(new R("confirmation_required","Conflict review was reopened."))})),l=(S)=>f(S).pipe(de((m)=>s(S,m))),g=n.reviewInstall??(t.io?.installReview===void 0?void 0:(S)=>d({try:()=>t.io.installReview(S),catch:(m)=>m}))??(e.options.yes===!0?()=>M({action:"apply"}):i?(S)=>d({try:()=>UT(S),catch:(m)=>m}):void 0),h=g===void 0?void 0:(S)=>v(function*(){let m=UF(S,a),x=yield*g($F(m));if(x.action!=="change")return x;if(x.request!==void 0)return yield*V({try:()=>({action:"change",request:Yt(x.request)}),catch:(_)=>_});if(!i)return yield*p(new R("confirmation_required","Changing install options requires an interactive review."));let E=yield*d({try:()=>(t.io?.installWizard??hd)(LF(m)),catch:(_)=>_});if(E.action==="cancel")return{action:"cancel"};return yield*V({try:()=>({action:"change",request:Yt(E.request)}),catch:(_)=>_})}),y=e.options["codex-home"];if(typeof y!=="string")return{...n,onProgress:o,resolveConflict:c,resolveConflicts:l,...h===void 0?{}:{reviewInstall:h},...t.now?{now:t.now}:{}};return{...n,paths:{...n.paths,codexHome:y},onProgress:o,resolveConflict:c,resolveConflicts:l,...h===void 0?{}:{reviewInstall:h},...t.now?{now:t.now}:{}}}function tS(e){let t=e.validDecisions??(e.action==="remove"?["keep","remove","cancel"]:["keep","replace","cancel"]),n=e.action==="remove"?"remove":"replace",r=t.includes(n)?n:void 0;if(r===void 0)return p(new R("confirmation_required",`--yes cannot resolve ${e.target??e.key??e.path}; choose ${t.join(", ")}.`,void 0,{path:e.path,...e.key===void 0?{}:{key:e.key}}));return M(r)}function qT(e,t){if(t.length===0)return rt;return v(function*(){let n=[];for(let r of t){let i=yield*tS(r),o=r.key===void 0?r.path:`${r.path} (${r.key})`;if(i!=="keep")n.push(`${i} ${o}`)}if(n.length===0)return;e.io?.writeStderr?.(`Warning: --yes will apply these conflict decisions: ${n.join("; ")}. This may overwrite existing Codex configuration.
107
+ `)})}function LF(e){return Yt({profile:e.profile,tier:e.tier,optional:e.capabilities,officialPlugins:e.additionalPlugins})}function gl(e){return e.identity??e.path}function UF(e,t){if(t.size===0||e.conflicts.length===0)return e;return{...e,conflicts:e.conflicts.map((n)=>{let r=t.get(gl(n));return r===void 0?n:{...n,decision:r}})}}function $F(e){let{fromVersion:t,...n}=e;return{...n,operation:"install"}}function zT(e,t){let n=df({schema_version:Lr,ok:!0,command:e,data:t,warnings:[]});if(!n.ok)return p(new Ba("internal_error","The success envelope failed validation."));return M(n.value)}function JT(e,t){let n=BF(t,e),r=df({schema_version:Lr,ok:!1,command:e,error:{code:n.code,message:n.message,details:n.details},warnings:[]});if(!r.ok)return{envelope:{schema_version:Lr,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 jF(e,t){if(e==="doctor"&&Xr(t)&&t.healthy===!1)return 4;if(e==="remove"&&Xr(t)){if(t.cancelled===!0)return 1;if(Ai(t,"preserved").length>0||Ai(t,"reasons").length>0)return 4}return 0}function BF(e,t){if(e instanceof Ke)return{code:e.code,message:hl(e.message),details:e.details,exitCode:1};if(e instanceof Ba)return{code:e.code,message:hl(e.message),details:{},exitCode:e.code==="internal_error"?5:1};if(e instanceof Ci)return{code:"trust_boundary_failed",message:hl(e.message),details:{},exitCode:4};if(e instanceof R){let n=e,r=n.code==="confirmation_required"?1:n.code==="capability_denied"?2:n.code==="state_corrupt"?4:3;return{code:n.code,message:eS(n.message),details:Qy(n.details,n.causeValue,t),exitCode:r}}if(e instanceof vr){let n=["timeout","output_limit","cancelled","readback_mismatch"].includes(e.code),r=e.code==="plugin_disabled"||e.code==="plugin_missing"||e.code==="command_failed";return{code:n?"effect_uncertain":r?"capability_denied":"install_failed",message:eS(e.message),details:Qy(e.details,e.causeValue,t),exitCode:n?4:r?2:3}}if(e instanceof xr)return{code:e.code,message:eS(e.message),details:Qy({},e.causeValue,t),exitCode:4};if(e instanceof Ri)return{code:e.code,message:hl(e.message),details:{},exitCode:1};if(e instanceof Error)return{code:"internal_error",message:`The ${t} command failed unexpectedly.`,details:{operation:t,cause:bc(`${e.name}: ${e.message}`).join(" ").slice(0,512)},exitCode:5};return{code:"internal_error",message:`The ${t} command failed unexpectedly.`,details:{operation:t,cause:"A non-Error value was thrown."},exitCode:5}}function Qy(e,t,n){let r={...e};if(t!==void 0){if(typeof r.operation!=="string")r.operation=n;r.cause=bc(VF(t)).join(" ").slice(0,512)}return r}function VF(e){if(e instanceof Error)return`${e.name}: ${e.message}`;if(typeof e==="string")return e;return"The operation failed with a non-Error cause."}function eS(e){return hl(bc(e).join(" "))}function qF(e){return e.find((t)=>!t.startsWith("-"))??"unknown"}function hl(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 Xr(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function zF(e,t,n){if(t||e.io?.stderrIsTTY===!1)return;e.io?.writeStderr?.(`${KT(n,{stderrIsTTY:e.io?.stderrIsTTY,env:e.env})}
108
+ `)}function Ed(e,t={}){let n=_i(t);if(e.envelope.ok){if(e.envelope.command==="version")return JF(e.envelope.data);if(e.envelope.command==="install")return WF(e.envelope.data,n);if(e.envelope.command==="remove")return HF(e.envelope.data,n);if(e.envelope.command==="doctor")return KF(e.envelope.data,n);return`${_e("\u2714","green",n)} ${_e(e.envelope.command,"heading",n)}
109
+ ${GF(e.envelope.data,n)}`}let r=e.envelope.error,i=ZF(r.code,e.envelope.command);return[`${_e("\u2716","red",n)} ${_e(e.envelope.command,"heading",n)}`,` ${_e(r.code,"red",n)}: ${r.message}`,...YF(r.details,n),...i===void 0?[]:[` hint: ${i}`],""].join(`
110
+ `)}function KT(e,t={}){return`${_e("\u2022","cyan",_i({...t,stream:"stderr"}))} ${e}`}function JF(e){if(Xr(e)&&typeof e.version==="string")return`holycodex ${e.version}
111
+ `;if(Xr(e)&&typeof e.next==="string"){let t=typeof e.previous==="string"?` (from ${e.previous})`:"";return`holycodex version updated to ${e.next}${t}
120
112
  `}return`holycodex version completed
121
- `}function VJ(e,t){if(pR(e,"cancelled")===!0)return`${_e("\u21A9","cyan",t)} ${_e("install","heading",t)} cancelled
122
- `;let n=zd(e,"record"),r=Kd(n,"version")??"unknown",o=Kd(n,"profile")??"unknown",i=Kd(n,"tier")??"unknown",a=zd(n,"capability_state"),s=["frontend","security","sites","browser_use","computer_use"].filter((m)=>zd(a,m)?.selected===!0).map((m)=>{let f=Kd(zd(a,m),"status");return f===void 0||f==="healthy"?m:`${m} (${f})`}),c=aa(e,"preserved"),l=aa(e,"warnings"),u=s.length===0?"none":s.join(", "),d=c.length===0?"none":`${c.length} managed item${c.length===1?"":"s"} (review before retrying)`;return`${[`${_e("\u2714","green",t)} ${_e("install","heading",t)}`,` ${_e("version","option",t)}: ${r}`,` ${_e("profile","option",t)}: ${o}`,` ${_e("tier","option",t)}: ${i}`,` ${_e("capabilities","option",t)}: ${u}`,` ${_e("preserved","option",t)}: ${d}`,...l.map((m)=>` ${_e("warning","warning",t)}: ${fR(m)}`)].join(`
113
+ `}function WF(e,t){if(iS(e,"cancelled")===!0)return`${_e("\u21A9","cyan",t)} ${_e("install","heading",t)} cancelled
114
+ `;let n=yl(e,"record"),r=Sl(n,"version")??"unknown",i=Sl(n,"profile")??"unknown",o=Sl(n,"tier")??"unknown",a=yl(n,"capability_state"),s=["frontend","security","sites","browser_use","computer_use"].filter((h)=>yl(a,h)?.selected===!0).map((h)=>{let y=Sl(yl(a,h),"status");return y===void 0||y==="healthy"?h:`${h} (${y})`}),c=Ai(e,"preserved"),f=Ai(e,"warnings"),l=s.length===0?"none":s.join(", "),u=c.length===0?"none":`${c.length} managed item${c.length===1?"":"s"} (review before retrying)`;return`${[`${_e("\u2714","green",t)} ${_e("install","heading",t)}`,` ${_e("version","option",t)}: ${r}`,` ${_e("profile","option",t)}: ${i}`,` ${_e("tier","option",t)}: ${o}`,` ${_e("capabilities","option",t)}: ${l}`,` ${_e("preserved","option",t)}: ${u}`,...f.map((h)=>` ${_e("warning","warning",t)}: ${oS(h)}`)].join(`
123
115
  `)}
124
- `}function WJ(e,t){if(pR(e,"cancelled")===!0)return`${_e("\u21A9","cyan",t)} ${_e("remove","heading",t)} cancelled
125
- `;let n=aa(e,"removed"),r=aa(e,"preserved"),o=aa(e,"reasons"),i=r.length===0?"none":`${r.length} item${r.length===1?"":"s"} (review before retrying)`,a=r.length>0||o.length>0,s=a?"remove incomplete":"remove";return`${[`${_e(a?"!":"\u2714",a?"warning":"green",t)} ${_e(s,a?"warning":"heading",t)}`,` ${_e("removed","option",t)}: ${n.length} owned item${n.length===1?"":"s"}`,` ${_e("preserved","option",t)}: ${i}`,...o.map((l)=>` ${_e("reason","option",t)}: ${fR(l)}`)].join(`
116
+ `}function HF(e,t){if(iS(e,"cancelled")===!0)return`${_e("\u21A9","cyan",t)} ${_e("remove","heading",t)} cancelled
117
+ `;let n=Ai(e,"removed"),r=Ai(e,"preserved"),i=Ai(e,"reasons"),o=r.length===0?"none":`${r.length} item${r.length===1?"":"s"} (review before retrying)`,a=r.length>0||i.length>0,s=a?"remove incomplete":"remove";return`${[`${_e(a?"!":"\u2714",a?"warning":"green",t)} ${_e(s,a?"warning":"heading",t)}`,` ${_e("removed","option",t)}: ${n.length} owned item${n.length===1?"":"s"}`,` ${_e("preserved","option",t)}: ${o}`,...i.map((f)=>` ${_e("reason","option",t)}: ${oS(f)}`)].join(`
126
118
  `)}
127
- `}function zJ(e,t){let n=pR(e,"healthy")===!0,r=zd(e,"checks"),o=r===void 0?[]:Object.entries(r),i=o.flatMap(([c,l])=>{let u=ai(l)?l:void 0,d=Kd(u,"status");if(d===void 0||d==="healthy")return[];let p=aa(u,"reasons");return[` ${_e(c,"option",t)}: ${p.length===0?d:p.map(fR).join(", ")}`]});return`${[`${n?_e("\u2714","green",t):_e("\u2716","red",t)} ${_e("doctor","heading",t)}`,` ${_e("status","option",t)}: ${n?"healthy":"needs attention"}`,` ${_e("checks","option",t)}: ${o.length}`,...i.length===0?[]:[` ${_e("issues","option",t)}:`,...i]].join(`
119
+ `}function KF(e,t){let n=iS(e,"healthy")===!0,r=yl(e,"checks"),i=r===void 0?[]:Object.entries(r),o=i.flatMap(([c,f])=>{let l=Xr(f)?f:void 0,u=Sl(l,"status");if(u===void 0||u==="healthy")return[];let g=Ai(l,"reasons");return[` ${_e(c,"option",t)}: ${g.length===0?u:g.map(oS).join(", ")}`]});return`${[`${n?_e("\u2714","green",t):_e("\u2716","red",t)} ${_e("doctor","heading",t)}`,` ${_e("status","option",t)}: ${n?"healthy":"needs attention"}`,` ${_e("checks","option",t)}: ${i.length}`,...o.length===0?[]:[` ${_e("issues","option",t)}:`,...o]].join(`
128
120
  `)}
129
- `}function zd(e,t){if(!ai(e))return;return ai(e[t])?e[t]:void 0}function pR(e,t){return ai(e)?e[t]:void 0}function Kd(e,t){let n=e?.[t];return typeof n==="string"?n:void 0}function aa(e,t){if(!ai(e)||!Array.isArray(e[t]))return[];return e[t]}function fR(e){if(typeof e!=="string")return"operation requires review";return e.replaceAll("_"," ")}function KJ(e,t){if(typeof e!=="object"||e===null||Array.isArray(e))return` ${_e(uR(e),"dim",t)}
130
- `;let n=Object.entries(e);if(n.length===0)return"";let r=Math.max(...n.map(([o])=>o.length));return`${n.map(([o,i])=>` ${_e(o.padEnd(r),"option",t)}: ${uR(i)}`).join(`
121
+ `}function yl(e,t){if(!Xr(e))return;return Xr(e[t])?e[t]:void 0}function iS(e,t){return Xr(e)?e[t]:void 0}function Sl(e,t){let n=e?.[t];return typeof n==="string"?n:void 0}function Ai(e,t){if(!Xr(e)||!Array.isArray(e[t]))return[];return e[t]}function oS(e){if(typeof e!=="string")return"operation requires review";return e.replaceAll("_"," ")}function GF(e,t){if(typeof e!=="object"||e===null||Array.isArray(e))return` ${_e(nS(e),"dim",t)}
122
+ `;let n=Object.entries(e);if(n.length===0)return"";let r=Math.max(...n.map(([i])=>i.length));return`${n.map(([i,o])=>` ${_e(i.padEnd(r),"option",t)}: ${nS(o)}`).join(`
131
123
  `)}
132
- `}function JJ(e,t){return Object.entries(e).map(([n,r])=>` ${_e(n,"option",t)}: ${_e(uR(r),"dim",t)}`)}function uR(e){if(typeof e==="string")return e;if(e===null||typeof e==="number"||typeof e==="boolean")return String(e);return JSON.stringify(e)}function GJ(e,t){if(e==="unknown_command")return"run `holycodex --help` to list supported commands";if(e==="invalid_argument")return`holycodex ${t} --help`;if(e==="non_tty_confirmation_required")return"rerun with --yes or use an interactive terminal";if(e==="capability_denied")return"run `holycodex doctor` to inspect capability availability";return}function _e(e,t,n){return vn(e,{red:"error",green:"success",cyan:"focus",dim:"hint",warning:"warning",heading:"heading",option:"option"}[t],n)}class el extends Error{code;constructor(e,t){super(t);this.name="CliCommandError",this.code=e}}async function mR(e=Bun.argv.slice(2),t=ZJ()){let n={env:process.env,cwd:process.cwd(),io:{stdin:t.stdin??XJ(),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 dR(e,n);if((e.length===0||fd(e)||e[0]==="help")&&!kL(e))n.io?.writeStdout?.(sv(md(e),{stdoutIsTTY:n.io?.stdoutIsTTY,stderrIsTTY:n.io?.stderrIsTTY,env:n.env,stream:"stdout"}));else if(kL(e))n.io?.writeStdout?.(`${JSON.stringify(r.envelope)}
133
- `);else if(r.envelope.ok)n.io?.writeStdout?.(hg(r,{stdoutIsTTY:n.io?.stdoutIsTTY,stderrIsTTY:n.io?.stderrIsTTY,env:n.env,stream:"stdout"}));else n.io?.writeStderr?.(hg(r,{stdoutIsTTY:n.io?.stderrIsTTY,stderrIsTTY:n.io?.stderrIsTTY,env:n.env,stream:"stderr"}));return r.exitCode}function ZJ(){return{stdoutIsTTY:process.stdout.isTTY===!0,stderrIsTTY:process.stderr.isTTY===!0,writeStdout:(e)=>process.stdout.write(e),writeStderr:(e)=>process.stderr.write(e),confirm:async(e)=>{let t=YJ({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 kL(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*XJ(){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}Dd();tg();Rd();ds();Od();Zh();Kh();var Hne="holycodex";if(import.meta.main)process.exitCode=await mR();export{lt as ArgumentError,or as CONTEXT7_SPEC,nn as CapabilityInstallStateSchema,lv as CapabilityStateRecordSchema,ti as CodexOfficialPluginManager,qh as InstallOptionsSchema,Uc as InstallRecordSchema,xd as InstallRequestSchema,_ as InstallerError,uo as OfficialPluginManagerError,nr as PathBoundaryError,Sd as PersistedInstallOptionsSchema,Jh as ReadOnlyCodexPluginStatus,az as STATE_SCHEMA,be as ToolingError,yL as applyConflictScreenKey,bL as applyWizardConfigurationKey,hv as assertRootText,MF as context7InstallCommand,ys as createInstallerRuntime,hs as detectContext7Manager,Uv as doctorHolyCodex,Gh as ensureContext7,TL as executeCommand,fd as helpRequested,pd as helpText,md as helpTopic,Ss as installHolyCodex,Ov as installNativeAgents,lg as installRecordDigest,Nd as installRequestFromPersistedOptions,Hne as packageName,Lh as parseArgv,_L as parsePluginInput,rr as pathWithin,nL as persistedOptionsForInstall,Jz as preflightContext7,ei as projectNativeAgents,Tv as projectRootAgent,ps as publicManifestPath,oa as readActiveInstallRecord,Rz as readCanonicalBaseVersion,_F as readCanonicalVersion,ng as readInstallOptions,vd as readInstallationVersion,Bc as readPublicVersion,Md as removeHolyCodex,Wh as removeManagedNativeAgents,Pd as removeOwnedContext7,oJ as renderConflictScreen,sv as renderHelp,hg as renderHuman,fJ as renderInstallWizardReview,Vc as renderNativeAgent,OL as renderProgress,Pr as resolveInstallerPaths,Vh as rollbackNativeAgentInstall,Cv as rootDeveloperInstructions,mR as runBinary,dR as runCli,pg as runOpenTuiConflictResolver,dg as runOpenTuiInstallWizard,tR as stateFromConflicts,oR as stateFromRequest,wL as toInstallOptions,_v as updateCanonicalVersion,uK as upgradeHolyCodex,dn as validateInstallOptions,eL as writeInstallOptions};
124
+ `}function YF(e,t){return Object.entries(e).map(([n,r])=>` ${_e(n,"option",t)}: ${_e(nS(r),"dim",t)}`)}function nS(e){if(typeof e==="string")return e;if(e===null||typeof e==="number"||typeof e==="boolean")return String(e);return JSON.stringify(e)}function ZF(e,t){if(e==="unknown_command")return"run `holycodex --help` to list supported commands";if(e==="invalid_argument")return`holycodex ${t} --help`;if(e==="non_tty_confirmation_required")return"rerun with --yes or use an interactive terminal";if(e==="capability_denied")return"run `holycodex doctor` to inspect capability availability";return}function _e(e,t,n){return an(e,{red:"error",green:"success",cyan:"focus",dim:"hint",warning:"warning",heading:"heading",option:"option"}[t],n)}class Ba extends Error{code;constructor(e,t){super(t);this.name="CliCommandError",this.code=e}}function aS(e=Bun.argv.slice(2),t=eL()){return A(QF(e,t))}function QF(e,t){return v(function*(){let n={env:process.env,cwd:process.cwd(),io:{stdin:t.stdin??tL(),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=yield*d({try:()=>rS(e,n),catch:(i)=>i});if((e.length===0||Nc(e)||e[0]==="help")&&!GT(e))n.io?.writeStdout?.(zh(Dc(e),{stdoutIsTTY:n.io?.stdoutIsTTY,stderrIsTTY:n.io?.stderrIsTTY,env:n.env,stream:"stdout"}));else if(GT(e))n.io?.writeStdout?.(`${JSON.stringify(r.envelope)}
125
+ `);else if(r.envelope.ok)n.io?.writeStdout?.(Ed(r,{stdoutIsTTY:n.io?.stdoutIsTTY,stderrIsTTY:n.io?.stderrIsTTY,env:n.env,stream:"stdout"}));else n.io?.writeStderr?.(Ed(r,{stdoutIsTTY:n.io?.stderrIsTTY,stderrIsTTY:n.io?.stderrIsTTY,env:n.env,stream:"stderr"}));return r.exitCode})}function eL(){return{stdoutIsTTY:process.stdout.isTTY===!0,stderrIsTTY:process.stderr.isTTY===!0,writeStdout:(e)=>process.stdout.write(e),writeStderr:(e)=>process.stderr.write(e),confirm:(e)=>A(Fr(nt(()=>XF({input:process.stdin,output:process.stderr})),(t)=>d({try:()=>t.question(`${e} [y/N] `),catch:(n)=>n}).pipe(de((n)=>/^(?:y|yes)$/iu.test(n.trim()))),(t)=>nt(()=>t.close())))}}function GT(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}function tL(){let e=new TextDecoder,t=process.stdin[Symbol.asyncIterator](),n=!1;return{[Symbol.asyncIterator](){return{next:()=>A(v(function*(){while(!n){let r=yield*d({try:()=>t.next(),catch:(a)=>a});if(r.done){n=!0;let a=e.decode();return a.length>0?{done:!1,value:a}:{done:!0,value:void 0}}let i=r.value,o=typeof i==="string"?i:e.decode(i,{stream:!0});if(o.length>0)return{done:!1,value:o}}return{done:!0,value:void 0}}))}}}}cl();ad();Wc();ho();Kc();ed();Yf();var HH="holycodex";if(import.meta.main)process.exitCode=await aS();export{Ke as ArgumentError,Nn as CONTEXT7_SPEC,Dt as CapabilityInstallStateSchema,Kh as CapabilityStateRecordSchema,Er as CodexOfficialPluginManager,qf as InstallOptionsSchema,Pa as InstallRecordSchema,Uc as InstallRequestSchema,R as InstallerError,vr as OfficialPluginManagerError,Ci as PathBoundaryError,$c as PersistedInstallOptionsSchema,Zf as ReadOnlyCodexPluginStatus,S0 as STATE_SCHEMA,xe as ToolingError,LT as applyConflictScreenKey,jT as applyWizardConfigurationKey,Hh as assertRootText,zC as context7InstallCommand,vo as createInstallerRuntime,xo as detectContext7Manager,XC as doctorHolyCodex,Xf as ensureContext7,wF as executeCommand,Nc as helpRequested,Mc as helpText,Dc as helpTopic,Py as installHolyCodex,my as installNativeAgents,QD as installRecordDigest,il as installRequestFromPersistedOptions,HH as packageName,Uf as parseArgv,VT as parsePluginInput,An as pathWithin,vT as persistedOptionsForInstall,WN as preflightContext7,Hr as projectNativeAgents,dy as projectRootAgent,Mn as publicManifestPath,Ua as readActiveInstallRecord,lN as readCanonicalBaseVersion,cN as readCanonicalVersion,ky as readInstallOptions,ay as readInstallationVersion,oy as readPublicVersion,QC as removeHolyCodex,Gf as removeManagedNativeAgents,Qc as removeOwnedContext7,aF as renderConflictScreen,zh as renderHelp,Ed as renderHuman,gF as renderInstallWizardReview,Aa as renderNativeAgent,KT as renderProgress,Yn as resolveInstallerPaths,Kf as rollbackNativeAgentInstall,py as rootDeveloperInstructions,aS as runBinary,rS as runCli,yd as runOpenTuiConflictResolver,hd as runOpenTuiInstallWizard,Hy as stateFromConflicts,Yy as stateFromRequest,BT as toInstallOptions,cy as updateCanonicalVersion,eT as upgradeHolyCodex,Yt as validateInstallOptions,CD as writeInstallOptions};