holycodex 0.16.11-dev.121.1 → 0.16.12-dev.124.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/agent.js +73 -35
- package/dist/assets/plugin/plugin.json +1 -1
- package/dist/assets/plugin/skills/auto-reset/SKILL.md +14 -0
- package/dist/assets/plugin/skills/auto-reset/agents/openai.yaml +6 -0
- package/dist/assets/plugin/skills/session-audit/SKILL.md +12 -0
- package/dist/assets/plugin/skills/session-audit/agents/openai.yaml +6 -0
- package/dist/index.js +101 -55
- package/package.json +2 -2
package/dist/index.js
CHANGED
|
@@ -1,41 +1,87 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
2
|
// @bun
|
|
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
|
|
4
|
-
${o(
|
|
5
|
-
`+o(
|
|
6
|
-
${o(
|
|
7
|
-
${
|
|
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 rn=(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}}},hp,ds;var Ur=L(()=>{hp={pipe(){return rn(this,arguments)}},ds=function(){function e(){}return e.prototype=hp,e}()});function ps(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 zo(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 Z=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)}}}},at=(e)=>e,Ql=(e)=>()=>e,gp,Ex,qo,yp;var on=L(()=>{gp=Ql(!0),Ex=Ql(!1),qo=Ql(void 0),yp=qo});var ms=(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},hs,gs=(e)=>new Uint8Array(e.buffer,e.byteOffset,e.byteLength);var Sp=L(()=>{hs=new WeakSet});var eu=0,vx=()=>{eu++};function Wo(e){return typeof e==="string"}function ys(e){return typeof e==="number"}function bx(e){return typeof e==="boolean"}function _x(e){return typeof e==="symbol"}function wx(e){return Wo(e)||ys(e)||_x(e)}function Ss(e){return typeof e==="function"}function xp(e){return e!==void 0}function Cx(e){return e!=null}function Rx(e){return!0}function tu(e){return typeof e==="object"&&e!==null||Ss(e)}function Tx(e){return Re(e,Symbol.iterator)||Wo(e)}var Re;var Dt=L(()=>{on();Re=Z(2,(e,t)=>tu(e)&&(t in e))});var lt="~effect/Hash",Te=(e)=>{switch(typeof e){case"number":return xs(e);case"bigint":return zt(e.toString(10));case"string":return zt(e);case"function":case"object":if(e===null)break;else if(e instanceof Date){if(Number.isNaN(e.getTime()))return zt("Invalid Date");return zt(e.toISOString())}else if(e instanceof RegExp)return zt(e.toString());else{if(hs.has(e))return nu(e);let t=Ix.get(e);if(t!==void 0)return t;if(bp.has(e))return vx(),zt("[Circular]");bp.add(e);let n=eu,r;try{if(lt in e)r=e[lt]();else if(typeof e==="function")r=nu(e);else if(e instanceof DataView)r=ru(gs(e));else if(Array.isArray(e)||ArrayBuffer.isView(e))r=ru(e);else if(e instanceof Map)r=lk(e);else if(e instanceof Set)r=uk(e);else r=wp(e)}finally{bp.delete(e)}if(n===eu)Ix.set(e,r);return r}}return fi(Px(zt(String(e))))},nu=(e)=>{if(!vp.has(e))vp.set(e,fi(Math.random()*4294967296|0));return vp.get(e)},Px=(e)=>(e^=e>>>16,e=Math.imul(e,2246822507),e^=e>>>13,e=Math.imul(e,3266489909),e^e>>>16),xt,fi=(e)=>e&3221225471|e>>>1&1073741824,Ep,xs=(e)=>{let t=e|0;if(t===e)return fi(t);return Ep.setFloat64(0,e!==e?NaN:e),fi(xt(Ep.getInt32(0),Ep.getInt32(4)))},zt=(e)=>{let t=5381,n=e.length;while(n)t=t*33^e.charCodeAt(--n);return fi(t)},_p=(e,t)=>{let n=12289;for(let r of t)n^=xt(Te(r),Te(e[r]));return fi(n)},wp=(e)=>_p(e,ms(e)),Ox=(e,t)=>(n)=>{let r=e;for(let i of n)r^=t(i);return fi(r)},ru=(e)=>{let t=6151;for(let n of e)t=xt(t,Te(n));return fi(t)},lk,kx,uk,vp,Ix,bp;var di=L(()=>{on();Sp();xt=Z(2,(e,t)=>Px(Math.imul(e,2654435761)+Math.imul(t,2246822507))),Ep=new DataView(new ArrayBuffer(8)),lk=Ox(zt("Map"),([e,t])=>xt(Te(e),Te(t))),kx=zt("Set"),uk=Ox(kx,(e)=>xt(kx,Te(e))),vp=new WeakMap,Ix=new WeakMap,bp=new WeakSet});function Et(){if(arguments.length===1)return(e)=>Gi(e,arguments[0]);return Gi(arguments[0],arguments[1])}function Gi(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(hs.has(e)||hs.has(t))return!1;return fk(e,t)}function fk(e,t){let n=iu.length;for(let o=n;o-- >0;)if(iu[o]===e&&Cp[o]===t)return!0;if(n)return Ax(e,t);let r=Nx.get(e);if(!r)Nx.set(e,r=new WeakMap);let i=r.get(t);if(i===void 0)r.set(t,i=Ax(e,t));return i}function Ax(e,t){iu.push(e),Cp.push(t);try{return dk(e,t)}finally{iu.pop(),Cp.pop()}}function dk(e,t){if(Te(e)!==Te(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=Lx(e);if(n!==Lx(t)||typeof e==="function"&&!n)return!1;else if(n)return e[ut](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 Mx(gs(e),gs(t));return Mx(e,t)}else if(e instanceof Map){if(!(t instanceof Map)||e.size!==t.size)return!1;return Dx(e,t,hk,gk)}else if(e instanceof Set){if(!(t instanceof Set)||e.size!==t.size)return!1;return Dx(e,t,Te,Gi)}return mk(e,t)}function pk(e,t){for(let n=0;n<e.length;n++)if(!Gi(e[n],t[n]))return!1;return!0}function Mx(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=ms(e),r=ms(t);if(n.size!==r.size)return!1;for(let i of n)if(!r.has(i)||!Gi(e[i],t[i]))return!1;return!0}function Dx(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 ut="~effect/Equal",iu,Cp,Nx,hk=(e)=>Te(e[0]),gk=(e,t)=>Gi(e[0],t[0])&&Gi(e[1],t[1]),Lx=(e)=>Re(e,ut);var Yi=L(()=>{di();Sp();Dt();iu=[],Cp=[],Nx=new WeakMap});function Ko(e){if(yk(e))return Rp(e);return e}function Rp(e){return e[Es](globalThis[Go]?.context??Sk)}var Es,yk=(e)=>Re(e,Es),Go="~effect/Fiber/currentFiber",Fx,Sk;var ou=L(()=>{Ur();Dt();Es=Symbol.for("~effect/Redactable");Fx=new Map,Sk={"~effect/Context":{},base:Fx,depth:0,mapUnsafe:Fx,pipe(){return rn(this,arguments)}}});function ke(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,f)=>{let h=l?.constructor;return h&&h!==Object.prototype.constructor&&h.name?`${h.name}(${f})`:f},s=(l)=>{try{return Reflect.ownKeys(l)}catch{return["[ownKeys threw]"]}};function c(l,f=0){try{return u(l,f)}catch{if(typeof l==="object"&&l!==null||typeof l==="function")r.delete(l);return"[inspection threw]"}}function u(l,f=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 h;if(Es in l)h=c(Rp(l),f);else if(Array.isArray(l))h=!i||l.length<=1?`[${l.map((g)=>c(g,f)).join(",")}]`:`[
|
|
4
|
+
${o(f+1)}${l.map((g)=>c(g,f+1)).join(`,
|
|
5
|
+
`+o(f+1))}
|
|
6
|
+
${o(f)}]`;else if(l instanceof Date)h=Ek(l);else if(!t?.ignoreToString&&Re(l,"toString")&&typeof l.toString==="function"&&l.toString!==Object.prototype.toString&&l.toString!==Array.prototype.toString){let g=vk(l);h=l instanceof Error&&l.cause!==void 0?`${g} (cause: ${c(l.cause,f)})`:g}else if(Symbol.iterator in l)h=`${l.constructor.name}(${c(Array.from(l),f)})`;else{let g=s(l);if(!i||g.length<=1){let y=`{${g.map((v)=>`${Yo(v)}:${c(Ux(l,v),f)}`).join(",")}}`;h=a(l,y)}else{let y=`{
|
|
7
|
+
${g.map((v)=>`${o(f+1)}${Yo(v)}: ${c(Ux(l,v),f+1)}`).join(`,
|
|
8
8
|
`)}
|
|
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(`
|
|
9
|
+
${o(f)}}`;h=a(l,y)}}return r.delete(l),h}return String(l)}return c(e,0)}function Yo(e){return typeof e==="string"?JSON.stringify(e):String(e)}function $x(e){return e.map((t)=>`[${Yo(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 Ux(e,t){try{return e[t]}catch{return"[property access threw]"}}function vs(e,t){let n=[];return JSON.stringify(e,function(r,i){let o=Object.getOwnPropertyDescriptor(this,r)?.value,a=Re(o,Es)?Ko(o):Ko(i);if(typeof a==="bigint")return ke(a);if(typeof a!=="object"||a===null)return a;let s=a instanceof Error&&!Re(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 $r=L(()=>{Dt();ou()});var Zi,pi=(e)=>{try{if(e=Ko(e),Re(e,"toJSON")&&Ss(e.toJSON)&&e.toJSON.length===0)return e.toJSON();else if(Array.isArray(e))return e.map(pi);return e}catch{return"[toJSON threw]"}},jx=(e,t=2)=>{if(typeof e==="string")return e;try{return typeof e==="object"?vs(e,{space:t}):ke(e,{space:t})}catch{return String(e)}},GU;var Zo=L(()=>{$r();Dt();ou();Zi=Symbol.for("nodejs.util.inspect.custom"),GU={toJSON(){return pi(this)},[Zi](){return this.toJSON()},toString(){return ke(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,Xo=()=>Error.stackTraceLimit,Qo=(e)=>{if(_k)Error.stackTraceLimit=e};var au=L(()=>{_k=bk()});class Xi{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 Xo()!==0&&t["~effect/Utils/internal"](()=>Error().stack)?.includes("~effect/Utils/internal")===!0?t["~effect/Utils/internal"]:n["~effect/Utils/internal"]},bs;var _s=L(()=>{au();bs=wk()});function jr(e,t,n){if(t==="__proto__")Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0});else e[t]=n}function Bx(e,t){for(let n of Reflect.ownKeys(t))if(Object.prototype.propertyIsEnumerable.call(t,n))jr(e,n,t[n])}function Tk(e){return dr("Effect.evaluate: Not implemented")}var mi="~effect/Effect",Qi="~effect/Exit",Ck,qx,oe,Je,ft,mn,eo,to,no,a$,Rk,ws=(e)=>Re(e,mi),zx=(e)=>Re(e,Qi),cu="~effect/Cause",su="~effect/Cause/Reason",Cs=(e)=>Re(e,cu),Br,Vx,Rs,Ts,ks,ea=(e)=>new Br(e),Ip,Wx=(e)=>new Br([new ks(e)]),Pp,lu=(e)=>new Br([new Pp(e)]),Is,hi=(e)=>e._tag==="Fail",Op=(e)=>e._tag==="Die",uu=(e)=>e._tag==="Interrupt",hn=(e)=>({...Rk,[qx]:e.op,[Je]:e[Je]??Tk,[ft]:e[ft],[mn]:e[mn],[eo]:e[eo]}),fr=(e)=>{let t=hn(e),n=function(r){this[oe]=r};return n.prototype=t,function(r){return new n(r)}},Hx=(e)=>{let t={[Qi]:Qi,_tag:e.op,get[e.prop](){return this[oe]},...hn(e),toString(){return`${e.op}(${ke(this[oe])})`},toJSON(){return{_id:"Exit",_tag:e.op,[e.prop]:this[oe]}},[ut](r){return zx(r)&&r._tag===this._tag&&Et(this[oe],r[oe])},[lt](){return xt(zt(e.op),Te(this[oe]))}},n=function(r){this[oe]=r};return n.prototype=t,function(r){return new n(r)}},vt,fu,Ap,Hn,ta=(e)=>Hn(Wx(e)),dr=(e)=>Hn(lu(e)),Wt,s$,kk,Jx,na=(e)=>{class t extends Jx{_tag=e}return t.prototype.name=e,t},kp="~effect/Cause/Done",c$;var pr=L(()=>{Yi();$r();on();di();Zo();Ur();Dt();_s();Ck={_A:at,_E:at,_R:at},qx=`${mi}/identifier`,oe=`${mi}/args`,Je=`${mi}/evaluate`,ft=`${mi}/successCont`,mn=`${mi}/failureCont`,eo=`${mi}/ensureCont`,to=Symbol.for("effect/Effect/Yield"),no={pipe(){return rn(this,arguments)},toJSON(){return{...this}},toString(){return ke(this.toJSON(),{ignoreToString:!0,space:2})},[Zi](){return this.toJSON()}},a$={[lt](){return _p(this,Object.keys(this))},[ut](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]||!Et(this[t[r]],e[t[r]]))return!1;return!0}},Rk={[mi]:Ck,...no,[Symbol.iterator](){return new Xi(this)},toJSON(){return{_id:"Effect",op:this[qx],...oe in this?{args:this[oe]}:void 0}}};Br=class Br{constructor(e){this[cu]=cu,this.reasons=e}pipe(){return rn(this,arguments)}toJSON(){return{_id:"Cause",failures:this.reasons.map((e)=>e.toJSON())}}toString(){return`Cause(${ke(this.reasons)})`}[Zi](){return this.toJSON()}[ut](e){return Cs(e)&&this.reasons.length===e.reasons.length&&this.reasons.every((t,n)=>Et(t,e.reasons[n]))}[lt](){return ru(this.reasons)}};Vx=new WeakMap;Rs=class Rs{[su];annotations;_tag;constructor(e,t,n){if(this[su]=su,this._tag=e,t!==Ts&&typeof n==="object"&&n!==null&&t.size>0){let r=Vx.get(n);if(r)t=new Map([...r,...t]);Vx.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 rn(this,arguments)}toString(){return ke(this)}[Zi](){return this.toString()}};Ts=new Map;ks=class ks extends Rs{constructor(e,t=Ts){super("Fail",t,e);this.error=e}toString(){return`Fail(${ke(this.error)})`}toJSON(){return{_tag:"Fail",error:this.error}}[ut](e){return hi(e)&&Et(this.error,e.error)&&Et(this.annotations,e.annotations)}[lt](){return xt(zt(this._tag))(xt(Te(this.error))(Te(this.annotations)))}};Ip=new Br([]);Pp=class Pp extends Rs{constructor(e,t=Ts){super("Die",t,e);this.defect=e}toString(){return`Die(${ke(this.defect)})`}toJSON(){return{_tag:"Die",defect:this.defect}}[ut](e){return Op(e)&&Et(this.defect,e.defect)&&Et(this.annotations,e.annotations)}[lt](){return xt(zt(this._tag))(xt(Te(this.defect))(Te(this.annotations)))}};Is=Z((e)=>Cs(e[0]),(e,t,n)=>{if(t.mapUnsafe.size===0)return e;return new Br(e.reasons.map((r)=>r.annotate(t,n)))});vt=Hx({op:"Success",prop:"value",[Je](e){let t=e.getCont(ft);return t?t[ft](this[oe],e,this):e.yieldWith(this)}}),fu={key:"effect/Cause/StackTrace"},Ap={key:"effect/Cause/InterruptorStackTrace"},Hn=Hx({op:"Failure",prop:"cause",[Je](e){let t=this[oe],n=!1;if(e.cache.stackFrame)t=Is(t,{mapUnsafe:new Map([[fu.key,e.cache.stackFrame]])}),n=!0;let r=e.getCont(mn);while(e.interruptible&&e._interruptedCause&&r)r=e.getCont(mn);return r?r[mn](t,e,n?void 0:this):e.yieldWith(n?Hn(t):this)}}),Wt=fr({op:"WithFiber",[Je](e){return this[oe](e)}}),s$=fr({op:"WithFiberSucceed",[Je](e){let t=this[oe](e),n=e.getCont(ft);return n?n[ft](t,e):e.yieldWith(vt(t))}}),kk=function(){class e extends globalThis.Error{}let t=hn({op:"YieldableError",[Je](){return ta(this)}});return delete t.toString,Object.assign(e.prototype,t),e}(),Jx=function(){let e=Symbol.for("effect/Data/Error/plainArgs");return class extends kk{constructor(n){super(n?.message,n?.cause?{cause:n.cause}:void 0);if(n)Bx(this,n),Object.defineProperty(this,e,{value:n,enumerable:!1})}toJSON(){return{...this[e],...this}}}}(),c$={[kp]:kp,_tag:"Done",value:void 0}});var Kx=(e)=>hn({op:e.label,[Je]:e.evaluate});var Gx=L(()=>{pr()});var Yx="~effect/Option",Zx,Pk,Ok,Ak,Mp=(e)=>Re(e,Yx),Dp=(e)=>e._tag==="None",Lp=(e)=>e._tag==="Some",Xx,Qx=function(e){this.value=e},eE=(e)=>new Qx(e);var tE=L(()=>{Yi();$r();di();Zo();Dt();_s();pr();Zx={[Yx]:{_A:(e)=>e},...no,[Symbol.iterator](){return new Xi(this)}},Pk=Object.defineProperty(Object.assign(Object.create(Zx),{_tag:"Some",_op:"Some",[ut](e){return Mp(e)&&Lp(e)&&Et(this.value,e.value)},[lt](){return xt(Te(this._tag))(Te(this.value))},toString(){return`some(${ke(this.value)})`},toJSON(){return{_id:"Option",_tag:this._tag,value:pi(this.value)}}}),"valueOrUndefined",{get(){return this.value}}),Ok=Te("None"),Ak=Object.assign(Object.create(Zx),{_tag:"None",_op:"None",valueOrUndefined:void 0,[ut](e){return Mp(e)&&Dp(e)},[lt](){return Ok},toString(){return"none()"},toJSON(){return{_id:"Option",_tag:this._tag}}}),Xx=Object.create(Ak);Qx.prototype=Pk});var nE="~effect/Result",rE,Mk,Dk,Fp=(e)=>Re(e,nE),Up=(e)=>e._tag==="Failure",$p=(e)=>e._tag==="Success",iE=function(e){this.failure=e},oE=(e)=>new iE(e),aE=function(e){this.success=e},sE=(e)=>new aE(e);var cE=L(()=>{Yi();$r();di();Zo();Dt();_s();pr();rE={[nE]:{_A:(e)=>e,_E:(e)=>e},...no,[Symbol.iterator](){return new Xi(this)}},Mk=Object.assign(Object.create(rE),{_tag:"Success",_op:"Success",[ut](e){return Fp(e)&&$p(e)&&Et(this.success,e.success)},[lt](){return xt(Te(this._tag))(Te(this.success))},toString(){return`success(${ke(this.success)})`},toJSON(){return{_id:"Result",_tag:this._tag,value:pi(this.success)}}}),Dk=Object.assign(Object.create(rE),{_tag:"Failure",_op:"Failure",[ut](e){return Fp(e)&&Up(e)&&Et(this.failure,e.failure)},[lt](){return xt(Te(this._tag))(Te(this.failure))},toString(){return`failure(${ke(this.failure)})`},toJSON(){return{_id:"Result",_tag:this._tag,failure:pi(this.failure)}}});iE.prototype=Dk;aE.prototype=Mk});function lE(e){return(t,n)=>t===n?0:e(t,n)}var ra,uE,du=(e)=>Z(2,(t,n)=>e(t,n)===1),fE=(e)=>Z(2,(t,n)=>e(t,n)!==1),dE=(e)=>Z(2,(t,n)=>e(t,n)!==-1);var jp=L(()=>{on();ra=lE((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}),uE=Z(2,(e,t)=>lE((n,r)=>e(t(n),t(r))))});var mr=()=>Xx,Vr,pu,Bp,mE;var Ps=L(()=>{on();tE();Vr=eE,pu=Dp,Bp=Lp,mE=Z(2,(e,t)=>pu(e)?mr():t(e.value)?Vr(e.value):mr())});var hE="~effect/Context/Service",gE=function(){function e(){}let t=e;Object.setPrototypeOf(t,Uk);let n=(r,i)=>{if(t.key=r,i?.defaultValue)t[qp]=qp,t.defaultValue=i.defaultValue;if(i?.make)t.make=i.make;if(i?.fiberCached)yE.add(r);return t};return arguments.length>0?n(arguments[0],arguments[1]):n},Uk,yE,qp="~effect/Context/Reference",SE="~effect/Context",$k=8,jk=8,zp=(e,t,n,r)=>{let i=Object.create(Bk);return i.cacheRoot=e??i,i.base=t,i.overlay=n,i.depth=r,i._flat=void 0,i.baseHits=0,i},xE=(e,t)=>{if(!t)return;xE(e,t.parent),e.set(t.key,t.value)},EE=(e)=>{if(e._flat)return e._flat;if(!e.overlay)return e._flat=e.base;let t=new Map(e.base);return xE(t,e.overlay),e._flat=t},Wp,vE=(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 Wp;if(n.overlay&&++n.baseHits>=n.base.size&&n.baseHits>=jk)n.base=EE(n),n.overlay=void 0,n.depth=0;return r},hu=(e)=>zp(void 0,e,void 0,0),Bk,bE=(e,t)=>e.cacheRoot===t.cacheRoot,Vk=(e)=>Re(e,SE),qk=(e)=>!!e[qp],ia=()=>zk,zk,Hp=(e,t)=>hu(new Map([[e.key,t]])),_E,Wk=(e,t,n)=>{let r=e,i=yE.has(t)?void 0:r.cacheRoot;if(r.depth>=$k){let o=new Map(r.mapUnsafe);return o.set(t,n),zp(i,o,void 0,0)}return zp(i,r.base,{key:t,value:n,parent:r.overlay},r.depth+1)},gu=(e,t)=>{let n=vE(e,t);return n===Wp?void 0:n},wE,kn,Vp="~effect/Context/defaultValue",Hk=(e)=>{if(Vp in e)return e[Vp];return e[Vp]=e.defaultValue()},Jk=(e)=>{let t=Error(`Service not found${e.key?`: ${String(e.key)}`:""}`);if(t.stack){let n=t.stack.split(`
|
|
10
10
|
`);n.splice(1,3),t.stack=n.join(`
|
|
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?
|
|
11
|
+
`)}return t},Lt;var yu=L(()=>{Gx();Yi();on();di();pr();Dt();Uk={[hE]:hE,...Kx({label:"Service",evaluate(e){return vt(kn(e.context,this))}}),toJSON(){return{_id:"Service",key:this.key}},of(e){return e},context(e){return Hp(this,e)},use(e){return Wt((t)=>e(kn(t.context,this)))},useSync(e){return Wt((t)=>vt(e(kn(t.context,this))))}},yE=new Set,Wp=Symbol(),Bk={get mapUnsafe(){return EE(this)},...no,[SE]:{_Services:(e)=>e},toJSON(){return{_id:"Context",services:Array.from(this.mapUnsafe).map(([e,t])=>({key:e,value:t}))}},[ut](e){if(!Vk(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)||!Et(i,n.get(r)))return!1;return!0},[lt](){return xs(this.mapUnsafe.size)}},zk=hu(new Map),_E=Z(3,(e,t,n)=>Wk(e,t.key,n)),wE=Z(2,(e,t)=>{let n=vE(e,t.key);if(n===Wp){if(qk(t))return Hk(t);throw Jk(t)}return n}),kn=wE,Lt=gE});var Eu="~effect/Duration",oa,AE,Kk,Gk,CE,Su,Kp,RE,vu=(e)=>BigInt(e<0?Math.ceil(e-0.5):Math.floor(e+0.5)),NE=(e)=>vu(e*1e6),TE=(e,t)=>{let n=e.indexOf(".");if(n===-1)return BigInt(e)*t;let r=e[0]==="-",i=e.slice(n+1),o=Gk**BigInt(i.length),a=(BigInt(e.slice(r?1:0,n))*o+BigInt(i))*t,s=a/o+(a%o*Kk>=o?AE:oa);return r?-s:s},Yk,Os=(e)=>{switch(typeof e){case"number":return OE(e);case"bigint":return xu(e);case"string":{if(e==="Infinity")return Gp;if(e==="-Infinity")return PE;let t=Yk.exec(e);if(!t)break;let[n,r,i]=t;if(i==="nano"||i==="nanos")return xu(TE(r,AE));if(i==="micro"||i==="micros")return xu(TE(r,Kp));let o=Number(r);switch(i){case"milli":case"millis":return OE(o);case"second":case"seconds":return oI(o);case"minute":case"minutes":return aI(o);case"hour":case"hours":return sI(o);case"day":case"days":return cI(o);case"week":case"weeks":return lI(o)}break}case"object":{if(e===null)break;if(Eu in e)return e;if(Array.isArray(e)){if(e.length!==2||!e.every(ys))return kE(e);if(Number.isNaN(e[0])||Number.isNaN(e[1]))return iI;if(e[0]===-1/0||e[1]===-1/0)return PE;if(e[0]===1/0||e[1]===1/0)return Gp;return Ht(vu(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 Ht(n);return Ht(vu(n*1e6+(t.microseconds??0)*1000+(t.nanoseconds??0)))}}return kE(e)},kE=(e)=>{throw Error(`Invalid Input: ${e}`)},IE,Zk,Xk,Qk,Ht=(e)=>{let t=Object.create(Qk);if(typeof e==="number")if(isNaN(e)||e===0||Object.is(e,-0))t.value=IE;else if(!Number.isFinite(e))t.value=e>0?Zk:Xk;else if(!Number.isInteger(e))t.value={_tag:"Nanos",nanos:NE(e)};else t.value={_tag:"Millis",millis:e};else if(e===oa)t.value=IE;else t.value={_tag:"Nanos",nanos:e};return t},eI=(e)=>Re(e,Eu),tI=(e)=>{switch(e.value._tag){case"Millis":return e.value.millis===0;case"Nanos":return e.value.nanos===oa;case"Infinity":case"NegativeInfinity":return!1}},nI=(e)=>{switch(e.value._tag){case"Millis":return e.value.millis<0;case"Nanos":return e.value.nanos<oa;case"NegativeInfinity":return!0;case"Infinity":return!1}},rI=(e)=>{switch(e.value._tag){case"Infinity":case"NegativeInfinity":return Gp;case"Millis":return e.value.millis<0?Ht(-e.value.millis):e;case"Nanos":return e.value.nanos<oa?Ht(-e.value.nanos):e}},iI,Gp,PE,xu=(e)=>Ht(e),OE=(e)=>Ht(e),oI=(e)=>Ht(e*1000),aI=(e)=>Ht(e*60000),sI=(e)=>Ht(e*3600000),cI=(e)=>Ht(e*86400000),lI=(e)=>Ht(e*604800000),ME=(e)=>uI(Os(e),{onMillis:at,onNanos:(t)=>Number(t)/1e6,onInfinity:()=>1/0,onNegativeInfinity:()=>-1/0}),Yp=(e)=>{let t=Os(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 NE(t.value.millis)}},uI,fI,dI=(e,t)=>fI(e,t,{onMillis:(n,r)=>n===r,onNanos:(n,r)=>n===r,onInfinity:(n,r)=>n.value._tag===r.value._tag}),pI,mI=(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<oa,r=n?-t:t,i=r/RE,o=i/Kp,a=o/Su,s=a/Su,c=s/CE,u=n?-1:1;return{days:u*Number(c),hours:u*Number(s%CE),minutes:u*Number(a%Su),seconds:u*Number(o%Su),millis:u*Number(i%Kp),nanos:u*Number(r%RE)}},Zp=(e)=>{if(e.value._tag==="Infinity")return"Infinity";if(e.value._tag==="NegativeInfinity")return"-Infinity";if(tI(e))return"0";if(nI(e))return"-"+Zp(rI(e));let t=mI(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 DE=L(()=>{Yi();on();di();Zo();Ur();Dt();oa=BigInt(0),AE=BigInt(1),Kk=BigInt(2),Gk=BigInt(10),CE=BigInt(24),Su=BigInt(60),Kp=BigInt(1000),RE=BigInt(1e6),Yk=/^(-?\d+(?:\.\d+)?)\s+(nanos?|micros?|millis?|seconds?|minutes?|hours?|days?|weeks?)$/,IE={_tag:"Millis",millis:0},Zk={_tag:"Infinity"},Xk={_tag:"NegativeInfinity"},Qk={[Eu]:Eu,[lt](){switch(this.value._tag){case"Millis":{let e=this.value.millis*1e6;return Number.isFinite(e)?Te(vu(e)):xs(this.value.millis)}case"Nanos":return Te(this.value.nanos);default:return wp(this.value)}},[ut](e){return eI(e)&&pI(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"}}},[Zi](){return this.toJSON()},pipe(){return rn(this,arguments)}},iI=Ht(0),Gp=Ht(1/0),PE=Ht(-1/0),uI=Z(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)()}}),fI=Z(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))}),pI=Z(2,(e,t)=>dI(e,t))});var Xp=(e)=>e.length>0;var hr,gn,Be,Ke,LE,bu;var It=L(()=>{on();cE();hr=sE,gn=oE,Be=Up,Ke=$p,LE=Z(2,(e,t)=>Be(e)?gn(t(e.failure)):e),bu=Z(2,(e,{onFailure:t,onSuccess:n})=>Be(e)?t(e.failure):n(e.success))});var Qp,em=(e)=>Qp.isArray(e)?e:Qp.from(e),tm,M$,nm,FE,_u=()=>[],UE;var wu=L(()=>{on();Qp=globalThis.Array,tm=Z(2,(e,t)=>[...e,t]),M$=Qp.isArray,nm=Xp,FE=Xp,UE=Z(2,(e,t)=>e.map(t))});class BE{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 Cu{executionMode;setImmediate;constructor(e="async",t){this.executionMode=e,this.setImmediate=t??(e==="sync"?$E:jE)}shouldYield(e){return e.currentOpCount>=e.cache.maxOpsBeforeYield}makeDispatcher(){return new VE(this.setImmediate)}}class VE{tasks=new BE;running=void 0;setImmediate;constructor(e=jE){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 im,$E=(e)=>{let t=!1;return Promise.resolve().then(()=>{if(!t)e()}),()=>{t=!0}},yI,jE=(e)=>{try{return yI(e)}catch{return $E(e)}},qE,zE;var WE=L(()=>{yu();im=Lt("effect/Scheduler",{fiberCached:!0,defaultValue:()=>new Cu}),yI="setImmediate"in globalThis?(e)=>{let t=globalThis.setImmediate(e);return()=>globalThis.clearImmediate(t)}:(e)=>{let t=setTimeout(e,0);return()=>clearTimeout(t)};qE=Lt("effect/Scheduler/MaxOpsBeforeYield",{fiberCached:!0,defaultValue:()=>2048}),zE=Lt("effect/Scheduler/PreventSchedulerYield",{fiberCached:!0,defaultValue:()=>!1})});var Ru;var om=L(()=>{pr();Ru=na});var JE="~effect/encoding/EncodingError",As;var KE=L(()=>{om();As=class As extends Ru("EncodingError"){[JE]=JE}});var GE="effect/Tracer/ParentSpan",YE="effect/Tracer";var ZE=()=>{};var XE="effect/Metric/FiberRuntimeMetrics";var QE,ev,am,tv,nv,rv;var iv=L(()=>{yu();on();QE=Lt("effect/References/CurrentStackFrame",{fiberCached:!0,defaultValue:qo}),ev=Lt("effect/References/TracerEnabled",{fiberCached:!0,defaultValue:gp}),am=Lt("effect/References/CurrentLogAnnotations",{defaultValue:()=>({})}),tv=Lt("effect/References/CurrentLogLevel",{fiberCached:!0,defaultValue:()=>"Info"}),nv=Lt("effect/References/MinimumLogLevel",{fiberCached:!0,defaultValue:()=>"Info"}),rv=Lt("effect/References/CurrentLogSpans",{defaultValue:()=>[]})});class bb{waiters=[];scheduled=void 0;_isOpen;constructor(e){this._isOpen=e}scheduleUnsafe(e){if(this.waiters.length===0)return sv;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=[],sv}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=Wt((e)=>{if(this._isOpen)return cv;return this._isOpen=!0,this.scheduleUnsafe(e)});release=Wt((e)=>this._isOpen?cv:this.scheduleUnsafe(e));openUnsafe(){if(this._isOpen)return!1;return this._isOpen=!0,this.flushWaiters(),!0}await=gr((e)=>{if(this._isOpen)return e(Ut);return this.waiters.push(e),In(()=>{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=In(()=>this.closeUnsafe());whenOpen=(e)=>Pt(this.await,()=>e);isOpen(){return this._isOpen}}class _b{currentTimeMillisUnsafe(){return Date.now()}currentTimeMillis=In(()=>this.currentTimeMillisUnsafe());currentTimeNanosUnsafe(){return YI()}currentTimeNanos=In(()=>this.currentTimeNanosUnsafe());monotonicTimeNanosUnsafe(){return Cb()}monotonicTimeNanos=In(()=>this.monotonicTimeNanosUnsafe());sleep(e){return this.sleepMillis(ME(e))}sleepMillis(e){if(e<=0)return mm;else if(!Number.isFinite(e))return hm;return gr((t)=>{let n=e>sm?this.sleepMillis(e-sm):Ut,r=setTimeout(()=>t(n),Math.min(e,sm));return In(()=>clearTimeout(r))})}}var lv,uv=(e)=>new Br([new lv(e)]),fv=(e)=>{let t=e.reasons.find(hi);return t?hr(t):gn(e)},Ds=(e)=>{for(let t=0;t<e.reasons.length;t++){let n=e.reasons[t];if(n._tag==="Fail")return hr(n.error)}return gn(e)},dv=(e)=>e.reasons.some(uu),_I=(e,t)=>{let n=new Map,r=[];for(let i of e.concat(t)){let o=Te(i),a=n.get(o);if(a===void 0)n.set(o,[i]);else if(a.some((s)=>Et(s,i)))continue;else a.push(i);r.push(i)}return r},ku,pv,Iu=(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")},mv=(e,t)=>{let n=[],r=[];if(e.reasons.length===0)return n;let i=Xo();if(i!==0)Qo(1);try{for(let o of e.reasons){if(o._tag==="Interrupt"){r.push(o);continue}n.push(cm(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=TI(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(cm(a,r[0].annotations,t))}}finally{if(i!==0)Qo(i)}return n},cm=(e,t,n)=>{let r=typeof e,i;if(e&&r==="object"){if(i=new globalThis.Error(wI(e),{cause:e.cause?cm(e.cause):void 0}),typeof e.name==="string")i.name=e.name;if(typeof e.stack==="string")i.stack=RI(e.stack,i,t);else{let o=`${i.name}: ${i.message}`;i.stack=t?hv(o,t):o}if(n?.includeCauseInStack)i.stack=yv(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:vs(e));return i},wI=(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 vs(e)},CI,RI=(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?hv(o.join(`
|
|
13
13
|
`),n):o.join(`
|
|
14
|
-
`)},
|
|
15
|
-
${
|
|
16
|
-
`)},
|
|
17
|
-
`)},
|
|
18
|
-
`),
|
|
19
|
-
${
|
|
20
|
-
}`:e.stack,
|
|
14
|
+
`)},hv=(e,t)=>{let n=t?.get(fu.key);if(n)e=`${e}
|
|
15
|
+
${gv(n)}`;return e},TI=(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(Ap.key);if(n.push(` at fiber (${i})`),o)n.push(gv(o))}return n.join(`
|
|
16
|
+
`)},gv=(e)=>{let t=[],n=e,r=0;while(n&&r<10){let i=n.stack();if(i){let o=i.matchAll(CI),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
|
+
`)},dm=(e)=>mv(e).map(yv).join(`
|
|
18
|
+
`),yv=(e)=>e.cause?`${e.stack} {
|
|
19
|
+
${Sv(e.cause," ")}
|
|
20
|
+
}`:e.stack,Sv=(e,t)=>{let n=e.stack.split(`
|
|
21
21
|
`),r=`${t}[cause]: ${n[0]}`;for(let i=1,o=n.length;i<o;i++)r+=`
|
|
22
22
|
${t}${n[i]}`;if(e.cause)r+=` {
|
|
23
|
-
${
|
|
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=
|
|
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
|
|
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
|
-
|
|
31
|
-
|
|
32
|
-
|
|
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
|
-
|
|
23
|
+
${Sv(e.cause,`${t} `)}
|
|
24
|
+
${t}}`;return r},xv="~effect/Fiber",kI,II,Ev=()=>globalThis[Go],pm,PI=(e)=>{let t=gu(e,YE);return{scheduler:kn(e,im),tracer:t,tracerContext:t?t.context:void 0,tracerEnabled:kn(e,ev),span:gu(e,GE),logLevel:kn(e,tv),minimumLogLevel:kn(e,nv),stackFrame:kn(e,QE),runtimeMetrics:gu(e,XE),maxOpsBeforeYield:kn(e,qE),preventYield:kn(e,zE)}},OI,AI=32,ov,vv=(e)=>{if(!e.cache.stackFrame)return;let t=new Map;return t.set(Ap.key,e.cache.stackFrame),hu(t)},bv=(e)=>{let t=e;if(t._exit)return bt(t._exit);return gr((n)=>{if(t._exit)return n(bt(t._exit));return In(e.addObserver((r)=>n(bt(r))))})},_v=(e)=>gr((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(bt(r))}return o(),In(()=>i?.())}),Ms=(e)=>Wt((t)=>{let n=vv(t),r=_u();for(let i of e)i.interruptUnsafe(t.id,n),r.push(i);return ym(_v(r))}),bt,_t,io,In,an,wv,Cv,mm,Rv=(e)=>an(()=>_t(e())),Ls=(e)=>dr(e),Tv=(e)=>an(()=>io(e())),Ut,kv=(e)=>{let t=typeof e==="function"?e:e.try,n=typeof e==="function"?(r)=>new Lu(r,"An error occurred in Effect.try"):e.catch;return an(()=>{try{return bt(t())}catch(r){return io(n(r))}})},Iv=(e)=>{let t=typeof e==="function"?e:e.try,n=typeof e==="function"?(r)=>new Lu(r,"An error occurred in Effect.tryPromise"):e.catch;return Pv(function(r,i){let o=(a)=>{try{r(io(bs(()=>n(a))))}catch(s){r(Ls(s))}};try{t(i).then((a)=>r(bt(a)),o)}catch(a){o(a)}},t.length!==0)},Pv,NI,gr=(e)=>Pv(e,e.length>=2),hm,Ov=(...e)=>{if(e.length===1){let r=e[0];return an(()=>Tu(r()))}let[t,n]=e;return an(()=>Tu(n.call(t.self)))},MI=(e,t)=>Object.defineProperty(t,"length",{value:e,configurable:!0}),Av=(e,...t)=>MI(e.length,t.length===0?function(){return av(()=>e.apply(this,arguments))}:function(){let n=av(()=>e.apply(this,arguments));for(let r of t)n=r(n,...arguments);return n}),av=(e)=>{try{let t=e(),n=void 0;while(!0){let r=t.next(n);if(r.done)return bt(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 an(()=>{if(o)return o=!1,Pt(r.value,(a)=>Tu(t,a));else return an(()=>Tu(e()))})}}}catch(t){return Ls(t)}},Tu,sa,Pu=function(e){return e._stack.push(this),this[oe]},DI,Fs=function(e,t,n){this[oe]=e,this[ft]=t,this.payload=n},Nv=function(){return this.payload},gm,LI=function(e,t){let n=this.payload;return t.succeedWith(gm?n(e):bs(()=>n(e)))},FI=function(e){let t=this.payload;return t(e)},Mv=(e)=>Us(e,Vr),ym=(e)=>new Fs(e,Nv,Jn),Dv=(e,t)=>Wt((n)=>{let r=new Set;return Rm(n,()=>r.size===0?void 0:Ms(r)),gr((i)=>{let o=em(e),a=o.length,s=0,c=!1,u=[],l=(f,h,g)=>{if(s++,f._tag==="Failure"){if(u.push(...f.cause.reasons),s>=a)i(_t(ea(u)));return}let y=!c;if(c=!0,i(f),y&&t?.onWinner)t.onWinner({fiber:h,index:g,parentFiber:n})};for(let f=0;f<a;f++){let h=Im(n,o[f],!0,!0,!1);if(r.add(h),h.addObserver((g)=>{r.delete(h),l(g,h,f)}),c)break}})}),Lv=(e,t)=>Wt((n)=>{let r=new Set;return Rm(n,()=>r.size===0?void 0:Ms(r)),gr((i)=>{let o=!1,a=0;for(let s of e){if(o)break;let c=a++,u=Im(n,s,!0,!0,!1);r.add(u),u.addObserver((l)=>{r.delete(u);let f=!o;if(o=!0,i(l),f&&t?.onWinner)t.onWinner({fiber:u,index:c,parentFiber:n})})}})}),Fv,Sm,Pt,Ve=(e)=>e[Qi]!==void 0,Uv,$v=(e)=>Pt(e,at),Us,jv,Bv,xm=(e)=>e._tag==="Success",Vv=(e)=>e._tag==="Failure",qv=(e)=>e._tag==="Failure"?hr(e.cause):gn(e),Jn,zv,Wv,$s,UI,Hv=function(e,t){this[oe]=e,this[mn]=t},Jv,Ou,Kv,Em,Gv=(e)=>Ou(e,Ls),Yv,Ns=(e)=>Xv(e,{onFailure:gn,onSuccess:hr}),vm,$I,Zv=function(e,t,n){this[oe]=e,this[ft]=t,this[mn]=n},jI=function(e,t){let n=this.payload;return t.succeedWith(gm?n.onSuccess(e):bs(()=>n.onSuccess(e)))},BI=(e,t)=>{let n=hn({op:e,[Je]:Pu,[ft]:jI,[mn]:t}),r=function(i,o){this[oe]=i,this.payload=o};return r.prototype=n,r},VI,bm,_m,Xv,wm=(e)=>Ve(e)?vt(e):qI(e),qI,Qv,zI=(e)=>new Nm(`Operation timed out after '${Zp(e)}'`),eb,tb,nb=(e,t)=>xm(e)?t:$s(t,(n)=>_t(ku(e.cause,n))),rb,Cm=(e,t,n)=>new rb(e,t,n),Rm=(e,t)=>{e._stack.push(new rb(void 0,t,void 0))},Tm,ib,ob,ab,sb=(e,t,n)=>fb((r)=>Pt(e,(i)=>Cm(an(()=>r(t(i))),(o)=>n(i,o),!0))),cb=(e)=>In(()=>{let t=GI(!1),n=!1,r,i=Pt(t.await,()=>r);return Wt((o)=>{if(r!==void 0)return r;if(n)return i;return n=!0,Rm(o,(a)=>In(()=>{r=a,t.openUnsafe()})),e})}),km=(e)=>Wt((t)=>{if(!t.interruptible)return e;return t.interruptible=!1,t._stack.push(Au),e}),lb,Au,WI,HI=(e)=>{if(e.interruptible=!0,e._stack.push(WI),e._interruptedCause)return _t(e._interruptedCause)},ub=(e)=>Wt((t)=>{if(t.interruptible)return e;return HI(t)??e}),fb=(e)=>Wt((t)=>{if(!t.interruptible)return e(at);return t.interruptible=!1,t._stack.push(Au),e(ub)}),db=(e,t)=>{if(Tx(e))return t?.mode==="result"?aa(e,Ns,t):aa(e,at,t);else if(t?.discard)return t.mode==="result"?aa(Object.values(e),Ns,t):aa(Object.values(e),at,t);return an(()=>{let n={};return sa(aa(Object.entries(e),([r,i])=>Us(t?.mode==="result"?Ns(i):i,(o)=>{jr(n,r,o)}),{discard:!0,concurrency:t?.concurrency}),n)})},pb,aa,JI=(e,t,n)=>an(()=>{let r=n?.discard?void 0:[],i=e[Symbol.iterator](),o=i.next(),a=0;return sa(pb({while:()=>!o.done,body:()=>t(o.value,a++),step:(s)=>{if(r)r.push(s);o=i.next()}}),r)}),js=(e)=>e==="unbounded"?Number.POSITIVE_INFINITY:Math.max(1,e??1),Nu=()=>(e)=>{let{onItem:t,step:n}=e,r=(o,a,s,c,u)=>Pt(wm(u),(l)=>n(o,a[s],l,s)??i(o,a,s+1,c)??Ut),i=(o,a,s=0,c=a.length)=>{for(;s<c;s++){let u=a[s],l=t(o,u,s);if(!Ve(l))return r(o,a,s,c,l);let f=n(o,u,l,s);if(f)return f._tag==="Failure"?f:void 0}};return i},mb=(e)=>{let{onItem:t,step:n}=e;return(r,i,o)=>{let a=0,s=o.end??i.length,c=o.concurrency,u=!1,l,f,h,g,y,v=(x)=>{let S=dr(x);return g=S,u=!0,f&&f.size>0?Pt(km(Ms(Array.from(f))),()=>g??S):S},d=()=>{let x=!1;for(;!g&&a<s;a++){let S=i[a],C=y??t(r,S,a);if(Ve(C)){if(g=n(r,S,C,a),g)break}else if(!l)return gr((T)=>{l=Ev(),f=new Set,y=C,h=T;let F;try{F=d()}catch(J){return T(v(J))}if(F)return T(F);return an(()=>(g??=Jn,Pt(f?Ms(f):Ut,()=>g?._tag==="Failure"?g:Ut)))});else{y=void 0;let T=Im(l,C,!0,!0,"inherit");if(T._exit){if(g=n(r,S,T._exit,a),g)break;continue}f.add(T);let F=a;if(T.addObserver((J)=>{f.delete(T);try{if(g){if(J._tag==="Failure"){let j=J.cause.reasons.filter((z)=>z._tag!=="Interrupt");if(j.length>0){let z=ea(j);g=Hn(g._tag==="Failure"?ku(g.cause,z):z)}}}else{let j=n(r,S,J,F);if(j)g=j,d()}if(x){let j=d();if(j)h(j)}else if(u&&f.size===0)h(g??Ut)}catch(j){h(v(j))}}),f.size<c)continue;x=!0,a++;return}}if(u=!0,g){if(f&&f.size>0){let S=vv(l);f.forEach((C)=>C.interruptUnsafe(l.id,S));return}if(h||g._tag==="Failure")return g}else if(h){if(!f)return Jn;else if(f.size===0)h(Ut)}};return d()}},Mu=()=>(e)=>mb(e),KI,Im=(e,t,n=!1,r=!1,i=!1)=>{let o=e,a=i==="inherit"?o.interruptible:!i,s=new pm(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 pm(n?.scheduler?_E(e,im,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},hb,gb=(e)=>{let t=Du(e);return(n,r)=>{let i=t(n,r);return new Promise((o)=>{i.addObserver((a)=>o(a))})}},yb=(e)=>{let t=gb(e);return(n,r)=>t(n,r).then((i)=>{if(i._tag==="Failure")throw Iu(i.cause);return i.value})},Sb,Pm=(e)=>{let t=Du(e);return(n)=>{if(Ve(n))return n;let r=new Cu("sync"),i=t(n,{scheduler:r});return i._dispatcher?.flush(),i._exit??dr(new Mm(i))}},xb,Eb=(e)=>{let t=Pm(e);return(n)=>{let r=t(n);if(r._tag==="Failure")throw Iu(r.cause);return r.value}},vb,sv,cv,GI=(e)=>new bb(e??!1),Om,sm=2147483647,wb,Cb,YI,Rb=(e)=>Wt((t)=>e(t.getRef(Om))),Am=(e)=>Rb((t)=>t.sleep(Os(e))),lm="~effect/Cause/TimeoutError",Nm,um="~effect/Cause/AsyncFiberError",Mm,fm="~effect/Cause/UnknownError",Lu,ZI,XI=(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}},QI,eP,Tb,tP,nP="~effect/Logger",rP,kb=(e)=>{let t=Object.create(rP);return t.log=e,t},iP=(e)=>e.replace(/[\s="]/g,"_"),oP=(e,t)=>`${iP(e[0])}=${t-e[1]}ms`,Ib=(e)=>(...t)=>{let n=void 0;for(let r=0,i=t.length;r<i;r++){let o=t[r];if(Cs(o)){if(n)t.splice(r,1);else t=t.slice(0,r).concat(t.slice(r+1));n=n?ea(n.reasons.concat(o.reasons)):o,r--}}if(n===void 0)n=Ip;return Wt((r)=>{let i=e??r.cache.logLevel;if(eP(r.cache.minimumLogLevel,i))return Ut;let o=r.getRef(Om),a=r.getRef(Tb);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 Ut})},ro,uj,aP=(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")}`,sP,cP;var qr=L(()=>{wu();yu();DE();Yi();$r();on();di();Zo();Ps();jp();Ur();Dt();ou();It();WE();ZE();_s();pr();iv();au();lv=class lv extends Rs{constructor(e,t=Ts){super("Interrupt",t,"Interrupted");this.fiberId=e}toString(){return`Interrupt(${this.fiberId})`}toJSON(){return{_tag:"Interrupt",fiberId:this.fiberId}}[ut](e){return uu(e)&&this.fiberId===e.fiberId&&this.annotations===e.annotations}[lt](){return xt(zt(`${this._tag}:${this.fiberId}`))(nu(this.annotations))}};ku=Z(2,(e,t)=>{if(e.reasons.length===0)return t;else if(t.reasons.length===0)return e;let n=new Br(_I(e.reasons,t.reasons));return Et(e,n)?e:n}),pv=Z(2,(e,t)=>{let n=!1,r=e.reasons.map((i)=>{if(hi(i))return n=!0,new ks(t(i.error),i.annotations);return i});return n?ea(r):e}),CI=/\((.*)\)/g,kI={_A:at,_E:at},II={id:0};pm=class pm{constructor(e,t=!0){this.setContext(e),this.id=++II.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[xv](){return kI}get currentDispatcher(){return this._dispatcher??=this.cache.scheduler.makeDispatcher()}getRef(e){return kn(this.context,e)}addObserver(e){if(this._exit)return e(this._exit),yp;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=uv(e);if(this.cache.stackFrame)n=Is(n,Hp(fu,this.cache.stackFrame));if(t)n=Is(n,t);if(this._interruptedCause=this._interruptedCause?ku(this._interruptedCause,n):n,this.interruptible)if(this._running)this._deferredInterrupt=!0;else this.evaluate(_t(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===to)return;let n=ov.interruptChildren&&ov.interruptChildren(this);if(n!==void 0)return this.evaluate(Pt(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=ia()}runLoop(e){let t=globalThis[Go];globalThis[Go]=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=_t(this._interruptedCause);this.currentOpCount++;let o=this.cache;if(!r&&!o.preventYield&&o.scheduler.shouldYield(this)){r=!0;let a=i;i=Pt(mm,()=>a)}if(i=o.tracerContext?o.tracerContext(i,this):i[Je](this),i===to){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 to}}}catch(o){if(!Re(i,Je))return dr(`Fiber.runLoop: Not a valid effect: ${String(i)}`);return this.runLoop(dr(o))}finally{this._running=n,globalThis[Go]=t}}getCont(e){if(this._deferredInterrupt)return this._deferredInterrupt=!1,OI;while(!0){let t=this._stack.pop();if(!t)return;let n=t[eo];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&AI-1)===0)return vt(e);let t=this.getCont(ft);return t?t[ft](e,this):this.yieldWith(vt(e))}yieldWith(e){return this._yielded=e,to}children(){return this._children??=new Set}pipe(){return rn(this,arguments)}setContext(e){let t=this.context;if(this.context=e,t!==void 0&&bE(t,e))return;let n=e.cacheRoot,r=n._fiberCache??=PI(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}};OI={[ft](e,t){return _t(t._interruptedCause)},[mn](e,t){return _t(t._interruptedCause)}},ov={interruptChildren:void 0},bt=vt,_t=Hn,io=ta,In=fr({op:"Sync",[Je](e){let t=this[oe](),n=e.getCont(ft);return n?n[ft](t,e):e.yieldWith(vt(t))}}),an=fr({op:"Suspend",[Je](e){return this[oe]()}}),wv=bu({onFailure:io,onSuccess:bt}),Cv=fr({op:"Yield",[Je](e){let t=!1;return e.currentDispatcher.scheduleTask(()=>{if(t)return;e.evaluate(Jn)},this[oe]??0),e.yieldWith(()=>{t=!0})}}),mm=Cv(0),Ut=bt(void 0),Pv=function(){let e=hn({op:"Async",[Je](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 to;return n._stack.push(NI(()=>(r=!0,o?.abort(),a??Jn))),to}}),t=function(n,r){this.register=n,this.withSignal=r};return t.prototype=e,function(n,r){return new t(n,r)}}(),NI=fr({op:"AsyncFinalizer",[eo](e){if(e.interruptible)e.interruptible=!1,e._stack.push(Au)},[mn](e,t){return dv(e)?Pt(nb(Hn(e),this[oe]()),()=>_t(e)):_t(e)}}),hm=gr(yp),Tu=function(){let e=hn({op:"Iterator",[ft](n,r){let i=this.iterator;while(!0){let o=i.next(n);if(o.done)return bt(o.value);if(!Ve(o.value))return r._stack.push(this),o.value;else if(o.value._tag==="Failure")return o.value;n=o.value.value}},[Je](n){return this[ft](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)}}(),sa=Z(2,(e,t)=>new Fs(e,Nv,bt(t))),DI=hn({op:"OnSuccess",[Je]:Pu});Fs.prototype=DI;gm=(()=>({["~effect/Effect/stackProbe"]:function(){return Error().stack}})["~effect/Effect/stackProbe"]()?.includes("[as ~effect/Effect/stackProbe]")===!0)(),Fv=Z((e)=>ws(e[1]),(e,t,n)=>Dv([e,t],n)),Sm=Z((e)=>ws(e[1]),(e,t,n)=>Lv([e,t],n)),Pt=Z(2,(e,t)=>new Fs(e,FI,t)),Uv=Z(2,(e,t)=>{if(Ve(e))return e._tag==="Success"?t(e.value):e;return Pt(e,t)}),Us=Z(2,(e,t)=>new Fs(e,LI,t)),jv=Z(2,(e,t)=>Ve(e)?zv(e,t):Us(e,t)),Bv=Z(2,(e,t)=>Ve(e)?Wv(e,t):Em(e,t)),Jn=vt(void 0),zv=Z(2,(e,t)=>e._tag==="Success"?vt(t(e.value)):e),Wv=Z(2,(e,t)=>{if(e._tag==="Success")return e;let n=Ds(e.cause);if(Be(n))return e;return ta(t(n.success))}),$s=Z(2,(e,t)=>new Hv(e,t.length!==1?(n)=>t(n):t)),UI=hn({op:"OnFailure",[Je]:Pu});Hv.prototype=UI;Jv=Z(3,(e,t,n)=>$s(e,(r)=>{let i=t(r);return Be(i)?_t(i.failure):n(i.success,r)})),Ou=Z(2,(e,t)=>Jv(e,Ds,(n)=>t(n))),Kv=Z((e)=>ws(e[0]),(e,t,n,r)=>$s(e,(i)=>{let o=Ds(i);if(Be(o))return _t(o.failure);if(!t(o.success))return r?r(o.success):_t(i);return n(o.success)})),Em=Z(2,(e,t)=>Ou(e,(n)=>Tv(()=>t(n)))),Yv=Z((e)=>ws(e[0]),(e,t)=>{if(!t?.log)return bm(e,{onFailure:(r)=>Ut,onSuccess:(r)=>Ut});let n=Ib(t.log===!0?void 0:t.log);return vm(e,{onFailure(r){let i=fv(r);return Be(i)?_t(i.failure):t.message===void 0?n(r):n(t.message,r)},onSuccess:(r)=>Ut})}),vm=Z(2,(e,t)=>new Zv(e,t.onSuccess.length!==1?(n)=>t.onSuccess(n):t.onSuccess,t.onFailure.length!==1?(n)=>t.onFailure(n):t.onFailure)),$I=hn({op:"OnSuccessAndFailure",[Je]:Pu});Zv.prototype=$I;VI=BI("Match",function(e,t){let n=e.reasons.find(hi);if(n===void 0)return _t(e);let r=this.payload;return t.succeedWith(gm?r.onFailure(n.error):bs(()=>r.onFailure(n.error)))}),bm=Z(2,(e,t)=>vm(e,{onFailure:(n)=>{let r=n.reasons.find(hi);return r?t.onFailure(r.error):_t(n)},onSuccess:t.onSuccess})),_m=Z(2,(e,t)=>new VI(e,t)),Xv=Z(2,(e,t)=>{if(Ve(e)){if(e._tag==="Success")return vt(t.onSuccess(e.value));let n=Ds(e.cause);if(Be(n))return e;return vt(t.onFailure(n.success))}return _m(e,t)}),qI=fr({op:"Exit",[Je](e){return e._stack.push(this),this[oe]},[ft](e,t,n){return t.succeedWith(n??vt(e))},[mn](e,t,n){return t.succeedWith(n??Hn(e))}}),Qv=Z(2,(e,t)=>Pt(tb(e,t.duration),(n)=>pu(n)?t.orElse():bt(n.value))),eb=Z(2,(e,t)=>{let n=Os(t);return Qv(e,{duration:n,orElse:()=>io(zI(n))})}),tb=Z(2,(e,t)=>Sm(Mv(e),sa(Am(t),mr()))),rb=function(){let e=hn({op:"OnExit",[Je](n){return n._stack.push(this),this.effect},[eo](n){if(n.interruptible&&this.interruptible!==!0)n._stack.push(Au),n.interruptible=!1},[ft](n,r,i){i??=vt(n);let o;try{o=this.onExit(i)}catch(a){o=dr(a)}return o?Pt(o,(a)=>i):i},[mn](n,r,i){i??=Hn(n);let o;try{o=this.onExit(i)}catch(a){o=dr(a)}return o?Pt(nb(i,o),(a)=>i):i}}),t=function(n,r,i){this.effect=n,this.onExit=r,this.interruptible=i};return t.prototype=e,t}(),Tm=Z(2,Cm),ib=Z(2,(e,t)=>Tm(e,(n)=>t)),ob=Z(3,(e,t,n)=>Tm(e,(r)=>{let i=t(r);return Be(i)?Ut:n(i.success,r)})),ab=Z(2,(e,t)=>ob(e,qv,t)),lb=fr({op:"SetInterruptible",[eo](e){if(e.interruptible=this[oe],e._interruptedCause&&e.interruptible)return()=>_t(e._interruptedCause)}}),Au=lb(!0),WI=lb(!1),pb=fr({op:"While",[ft](e,t){if(this[oe].step(e),this[oe].while())return t._stack.push(this),this[oe].body();return Jn},[Je](e){if(this[oe].while())return e._stack.push(this),this[oe].body();return Jn}}),aa=Z((e)=>typeof e[1]==="function",(e,t,n)=>an(()=>{let r=js(n?.concurrency);if(r===1)return JI(e,t,n);let i=em(e),o=i.length;if(o===0)return n?.discard?Ut:bt([]);let a=n?.discard?void 0:Array(o),s=KI({f:t,out:a},i,{concurrency:r});return s?sa(s,a):bt(a)})),KI=mb({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}}),hb=Du(ia()),Sb=yb(ia()),xb=Pm(ia()),vb=Eb(ia()),sv=bt(!0),cv=bt(!1);Om=Lt("effect/Clock",{defaultValue:()=>new _b});wb=BigInt(1e6),Cb=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())*wb;if(n>t)t=n;return t}}(),YI=function(){let e=BigInt(1e9),t;return()=>{let n=Cb(),r=BigInt(Date.now())*wb;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}}();Nm=class Nm extends na("TimeoutError"){[lm]=lm;constructor(e){super({message:e})}};Mm=class Mm extends na("AsyncFiberError"){[um]=um;constructor(e){super({message:"An asynchronous Effect was executed with Effect.runSync",fiber:e})}};Lu=class Lu extends na("UnknownError"){[fm]=fm;constructor(e,t){super({message:t,cause:e})}};ZI=Lt("effect/Console",{defaultValue:()=>globalThis.console}),QI=uE(ra,XI),eP=du(QI),Tb=Lt("effect/Logger/CurrentLoggers",{defaultValue:()=>new Set([sP,cP])}),tP=Lt("effect/Logger/LogToStderr",{defaultValue:Ex}),rP={[nP]:{_Message:at,_Output:at},pipe(){return rn(this,arguments)}},ro={bold:"1",red:"31",green:"32",yellow:"33",blue:"34",cyan:"36",white:"37",gray:"90",black:"30",bgBrightRed:"101"},uj={None:[],All:[],Trace:[ro.gray],Debug:[ro.blue],Info:[ro.green],Warn:[ro.yellow],Error:[ro.red],Fatal:[ro.bgBrightRed,ro.black]},sP=kb(({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(dm(e));let a=t.getTime(),s=n.getRef(rv),c="";for(let h of s)c+=` ${oP(h,a)}`;let u=n.getRef(am);if(Object.keys(u).length>0)o.push(u);let l=n.getRef(ZI);(n.getRef(tP)?l.error:l.log)(`[${aP(t)}] ${r.toUpperCase()} (#${n.id})${c}:`,...o)}),cP=kb(({cause:e,fiber:t,logLevel:n,message:r})=>{let i=t.getRef(Om),o=t.getRef(am),a=t.cache.span;if(a===void 0||a._tag==="ExternalSpan")return;let s={};for(let[c,u]of Object.entries(o))jr(s,c,u);if(s["effect.fiberId"]=t.id,s["effect.logLevel"]=n.toUpperCase(),e.reasons.length>0)s["effect.cause"]=dm(e);a.event(jx(Array.isArray(r)&&r.length===1?r[0]:r),i.currentTimeNanosUnsafe(),s)})});var Dm,Bs,ca,la,zr,Lm;var ua=L(()=>{pr();qr();Dm=vt,Bs=Hn,ca=ta,la=Jn,zr=xm,Lm=Vv});var Uu,Fm,gi,Um;var oo=L(()=>{pr();qr();Uu=hi,Fm=lu,gi=pv,Um=Iu});var Pn,p,O,Pb,dt,pt,yi,Ob,b,m,qs,zs,U,Ab,Ae,$u,We,ao,me,Nb,Mb,$t,yr,ge,wt,Db,Qe,ju,Ws,Lb,Fb,de,Ub,Wr,so,Hs,Js,$b,da,A,Le,co,Bu,$m,Jt,jb;var Fe=L(()=>{qr();Pn=db,p=Iv,O=bt,Pb=an,dt=In,pt=Ut,yi=gr,Ob=hm,b=Ov,m=io,qs=Rv,zs=Ls,U=kv,Ab=wv,Ae=Pt,$u=$v,We=Ns,ao=wm,me=Us,Nb=sa,Mb=ym,$t=Ou,yr=$s,ge=Kv,wt=Em,Db=Gv,Qe=Yv,ju=eb,Ws=Am,Lb=Fv,Fb=Sm,de=_m,Ub=bm,Wr=sb,so=ib,Hs=ab,Js=cb,$b=km,da=hb,A=Sb,Le=vb,co=xb,Bu=jv,$m=Bv,Jt=Uv,jb=Av});function Sr(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&&lP(r.value))Sr(r.value,t)}Object.freeze(e)}function lP(e){return typeof e==="object"&&e!==null}var Hr="0.15",yn="state-0.16";var Bb=()=>{};function pa(e){return{ok:!0,value:e}}function lo(e){return{ok:!1,error:e}}function Ks(e,t){return new mt("invalid_input",`Invalid ${e}.`,{field:e},t===void 0?void 0:{cause:t})}var mt;var ma=L(()=>{mt=class mt extends Error{code;details;constructor(e,t,n={},r){super(t,r);this.name="CoreError",this.code=e,this.details=n,Sr(this.details),Object.freeze(this)}}});var qu=(e)=>uP(typeof e==="string"?fP.encode(e):e),zu=(e)=>{let t=dP(e),n=t.length;if(n%4!==0)return gn(new As({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 gn(new As({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=Vu(t.charCodeAt(a))<<18|Vu(t.charCodeAt(a+1))<<12|Vu(t.charCodeAt(a+2))<<6|Vu(t.charCodeAt(a+3));o[s]=c>>16,o[s+1]=c>>8&255,o[s+2]=c&255}return hr(o)}catch(i){return gn(new As({kind:"Decode",module:"Base64",input:t,message:i instanceof Error?i.message:"Invalid input"}))}},uP=(e)=>{let t=e.length,n="",r;for(r=2;r<t;r+=3)n+=Kn[e[r-2]>>2],n+=Kn[(e[r-2]&3)<<4|e[r-1]>>4],n+=Kn[(e[r-1]&15)<<2|e[r]>>6],n+=Kn[e[r]&63];if(r===t+1)n+=Kn[e[r-2]>>2],n+=Kn[(e[r-2]&3)<<4],n+="==";if(r===t)n+=Kn[e[r-2]>>2],n+=Kn[(e[r-2]&3)<<4|e[r-1]>>4],n+=Kn[(e[r-1]&15)<<2],n+="=";return n},fP,dP=(e)=>e.replace(/[\n\r]/g,""),Kn="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Gs,Vu=(e)=>{if(e>=Gs.length||Gs[e]===255)throw TypeError(`Invalid character ${String.fromCharCode(e)}`);return Gs[e]};var jm=L(()=>{It();KE();fP=new TextEncoder,Gs=new Uint8Array(123).fill(255);for(let e=0;e<Kn.length;e++)Gs[Kn.charCodeAt(e)]=e;Gs[61]=0});function Bm(e){return e.checks?e.checks[e.checks.length-1].annotations:e.annotations}var Ys="~structural",Vm="~sentinels",qm="~constructor",Wu;var Hu=L(()=>{on();Wu=ps((e)=>{let t=Bm(e)?.identifier;if(typeof t==="string")return t;return e.getExpected(Wu)})});var se,Ot,On,Ne,Zs=(e)=>e===se?mr():Vr(e),Wm=(e)=>e._tag==="None"?On:Ot(e.value);var ha=L(()=>{ua();Ps();pr();se=Symbol(),Ot=Dm,On=Ot(se),Ne=Ot(se)});function Jm(e){return Re(e,ec)&&e[ec]===ec}function pP(e){return Object.hasOwn(e,"input")}function Hm(e,t,n){if(Jm(e))return e;if(typeof e==="string")return new jt({message:e},t,n);let r=typeof e.issue==="string"?new jt({message:e.issue},t,n):e.issue;return new Jr(e.path,r)}function Hb(e,t,n){if(e===void 0)return;if(typeof e==="boolean")return e?void 0:new jt(void 0,t,n);return Hm(e,t,n)}function Jb(e,t,n,r){if(Array.isArray(t)){if(!FE(t))return;return t.length===1?Hm(t[0],n,r):new Bt(e,UE(t,(i)=>Hm(i,n,r)),n,r)}return Hb(t,n,r)}function Ju(e){return pP(e)?ke(e.input):void 0}function Kb(e){let t=e.annotations?.expected;return typeof t==="string"?t:void 0}function tc(e,t){let n=Ju(t);return n===void 0?`Expected ${e}`:`Expected ${e}, got ${n}`}function Gb(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)=>Gb(n)).join(" & ")}}function gP(){return(e)=>Qs(e,"")}function Qs(e,t){let n;switch(e._tag){case"Filter":{let r=hP(e);if(r!==void 0)n=r;else{if(e.issue._tag!=="InvalidValue")return Qs(e.issue,t);let i=Kb(e.issue);n=i===void 0?tc(Gb(e.filter),e):tc(i,e.issue)}break}case"Encoding":return Qs(e.issue,t);case"Pointer":return Qs(e.issue,t+$x(e.path));case"Composite":case"AnyOf":{if(e._tag==="Composite"||e.issues.length>0)return e.issues.map((r)=>Qs(r,t)).join(`
|
|
25
|
+
`);n=nc(e)??tc(Wu(e.ast),e);break}default:n=mP(e);break}return t?`${n}
|
|
26
|
+
at ${t}`:n}function nc(e){if(e._tag==="Pointer")return;if(e._tag==="Encoding")return nc(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 ec="~effect/SchemaIssue/Issue",Gn,qb,zb,Jr,rc,Km,Bt,xr,jt,ic,Wb,mP=(e)=>{let t=nc(e);if(t!==void 0)return t;switch(e._tag){case"InvalidType":return tc(Wu(e.ast),e);case"InvalidValue":{let n=Kb(e);if(n!==void 0)return tc(n,e);let r=Ju(e);return r===void 0?"Expected a valid value":`Invalid data ${r}`}case"MissingKey":return"Missing key";case"UnexpectedKey":{let n=Ju(e);return n===void 0?"Expected no excess property":`Unexpected key with value ${n}`}case"Forbidden":return"Forbidden operation";case"OneOf":{let n=Ju(e);return n===void 0?"Expected exactly one member to match":`Expected exactly one member to match the input ${n}`}}},hP=(e)=>nc(e.issue)??nc(e),Yb;var Si=L(()=>{wu();$r();Hu();ha();Dt();Gn=class Gn{[ec]=ec;constructor(e,t){if(t?.reportInput===!0&&e!==se)this.input=e}};qb=class extends Gn{_tag="Filter";filter;issue;constructor(e,t,n,r){super(n,r);this.filter=e,this.issue=t}},zb=class extends Gn{_tag="Encoding";ast;issue;constructor(e,t,n,r){super(n,r);this.ast=e,this.issue=t}},Jr=class extends Gn{_tag="Pointer";path;issue;constructor(e,t){super();this.path=e,this.issue=t}},rc=class extends Gn{_tag="MissingKey";annotations;constructor(e){super();this.annotations=e}},Km=class extends Gn{_tag="UnexpectedKey";ast;constructor(e,t,n){super(t,n);this.ast=e}},Bt=class extends Gn{_tag="Composite";ast;issues;constructor(e,t,n,r){super(n,r);this.ast=e,this.issues=t}},xr=class extends Gn{_tag="InvalidType";ast;constructor(e,t,n){super(t,n);this.ast=e}},jt=class extends Gn{_tag="InvalidValue";annotations;constructor(e,t,n){super(t,n);this.annotations=e}},ic=class extends Gn{_tag="AnyOf";ast;issues;constructor(e,t,n,r){super(n,r);this.ast=e,this.issues=t}},Wb=class extends Gn{_tag="OneOf";ast;successes;constructor(e,t,n,r){super(n,r);this.ast=e,this.successes=t}};Yb=gP()});function oc(e){let t;for(let n of e.reasons){if(!Uu(n)||!Jm(n.error))return;t??=n.error}return t}function xi(e,t){let n=oc(e);if(n===void 0)throw Error(t,{cause:e});return n}var Gm=L(()=>{oo();Si()});function sc(){return xP}function Kt(e){return ac({_tag:"Transform",transform:e})}function Ei(e){return ac({_tag:"TransformEffect",transform:e})}function Xb(e){return ac({_tag:"TransformOptional",transform:e})}function EP(e){return ac({_tag:"TransformOptionalEffect",transform:e})}function Qb(){return Xb(()=>mr())}function e_(e){return EP((t)=>{let n=mE(t,xp);return Bp(n)?O(n):Bu(e,Vr)})}function Ym(){return Kt(globalThis.String)}function Ku(){return Kt(globalThis.Number)}function t_(e){return Ei((t,n)=>U({try:()=>JSON.parse(t,e?.reviver),catch:()=>new jt({expected:"a valid JSON string"},t,n)}))}function n_(e){return Ei((t,n)=>U({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 jt({expected:"a JSON-serializable value"},t,n)}))}function r_(){return Kt(qu)}function i_(){return Ei((e,t)=>$m(Ab(zu(e)),()=>new jt({expected:"a valid Base64 string"},e,t)))}var ac=(e)=>Object.assign(Object.create(hp),e),xP;var Gu=L(()=>{Fe();jm();Ps();Ur();Dt();Si();xP=ac({_tag:"Passthrough"})});function _P(e){return Re(e,cc)&&e[cc]===cc}function lc(e){return new Sn(Ei(e.decode),Ei(e.encode))}function o_(e){return new Sn(Kt(e.decode),Kt(e.encode))}function Yu(){return wP}function Xu(e){return new Sn(t_(e??{}),n_(e))}var cc="~effect/SchemaTransformation/Transformation",Sn,Xm=(e)=>{if(_P(e))return e;return new Sn(e.decode,e.encode)},wP,Zu,a_,s_;var Qu=L(()=>{Fe();Ur();Dt();Gu();Si();Sn=class extends ds{[cc]=cc;_tag="Transformation";decode;encode;constructor(e,t){super();this.decode=e,this.encode=t}flip(){return new Sn(this.encode,this.decode)}};wP=new Sn(sc(),sc());Zu=new Sn(Ku(),Ym()),a_=lc({decode:(e,t)=>URL.canParse(e)?O(new URL(e)):m(new jt({expected:"a valid URL string"},e,t)),encode:(e)=>O(e.href)}),s_=new Sn(i_(),r_())});function mo(e){return(t)=>t._tag===e}function l_(e){let t=globalThis.String(e.literal);return Yn(e,[new An(new ya(t),new Sn(Kt(()=>e.literal),Kt(()=>t)))])}function nh(e,t){return e.some((n)=>n.annotations?.representation?.id===t||n._tag==="FilterGroup"&&nh(n.checks,t))}function FP(e,t,n,r){if(n._tag==="Failure")return nf(e,e.ast,r,n);let i=n===Ne?t:n[oe];if(i!==se)e.output[r]=i;else{let o=e.getParser(e.tailThreshold,r);if(po(o.ast))return;let a=new Jr([r],new rc(o.ast.context?.annotations));if(e.options.errors==="all")if(e.issues)e.issues.push(a);else e.issues=[a];else return ca(new Bt(e.ast,[a],e.input,e.options))}}function eh(e,t,n=ho){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(xh(mf(t)))}function E_(e){switch(e._tag){case"String":case"Number":case"Symbol":case"TemplateLiteral":return!0;case"Union":return e.types.every(E_);default:return!1}}function v_(e){let t=I_(e);switch(t._tag){case"String":case"Number":case"Symbol":case"TemplateLiteral":return!0;case"Union":return t.types.every(v_);default:return!1}}function jP(e){return E_(e)&&v_(e)}function rh(e,t,n){if(n._tag==="Failure")return nf(e,e.ast,t.name,n);if(n===Ne)return;let r=n[oe];if(r!==se){jr(e.out,t.name,r);return}if(delete e.out[t.name],!po(t.type)){let i=new Jr([t.name],new rc(t.type.context?.annotations));if(e.options.errors==="all"){if(e.issues)e.issues.push(i);else e.issues=[i];return}else return ca(new Bt(e.ast,[i],e.input,e.options))}}function fh(e,t){if(!e)return t;if(!t)return e;return[...e,...t]}function dh(e,t,n){return new sf(Reflect.ownKeys(e).map((r)=>new uh(r,e[r].ast)),[],n,t)}function cf(e){return e.ast}function ph(e,t=void 0){return new af(!1,e.map((n)=>n.ast),[],void 0,t)}function lf(e,t,n){return new va(e.map(cf),t,void 0,n)}function w_(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=fh(i,o.checks)}return new sf(n,r,void 0,i)}function C_(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(C_)));default:return["null","undefined","string","number","boolean","symbol","bigint","object","array","function"]}}function rf(e){switch(e._tag){default:return[];case"Declaration":{let t=e.annotations?.[Vm];return Array.isArray(t)?t:[]}case"Objects":return e.propertySignatures.flatMap((t)=>{let n=t.type;if(!po(n)){if(Sa(n))return[{key:t.name,literal:n.literal}];if(th(n))return[{key:t.name,literal:n.symbol}]}return[]});case"Arrays":return e.elements.flatMap((t,n)=>{if(!po(t)){if(Sa(t))return[{key:n,literal:t.literal}];if(th(t))return[{key:n,literal:t.symbol}]}return[]});case"Union":{if(e.types.length===0)return[];let t=e.types.map((n)=>rf(mh(n)));return t[0].filter((n)=>t.every((r)=>r.some((i)=>i.key===n.key&&i.literal===n.literal)))}case"Suspend":return rf(e.thunk())}}function VP(e){let t=f_.get(e);if(t)return t;let n,r=0,i,o,a=!0,s=[];for(let l=0;l<e.length;l++){let f=e[l],h=mh(f);if(TP(h))continue;if(Sa(h)||th(h)){o??=new Map;let y=Sa(h)?h.literal:h.symbol;s[l]=y;let v=o.get(y);if(!v)o.set(y,v=[]);v.push(l)}else a=!1;let g=rf(h);if(g.length){n??=new Map,r++;for(let{key:y,literal:v}of g){let d=n.get(y);if(!d)n.set(y,d=[new Map,new Set]);d[1].add(l);let x=d[0].get(v);if(!x)d[0].set(v,x=new Set);x.add(l)}}else{i??={};let y=C_(h);for(let v of y)(i[v]??=[]).push(l)}}let c={},u=(l)=>c[l]??=Object.freeze(i?.[l]??ef);if(a&&o)o.forEach(Object.freeze),t=(l)=>o.get(l)??ef;else if(n?.size===1&&!i){let[l,[f]]=n.entries().next().value,h=new Map;for(let[y,v]of f)h.set(y,Object.freeze(Array.from(v)));let g=Object.freeze(e.map((y,v)=>v));t=(y,v)=>{if(tu(y)){let d=ga(y,l)?y[l]:void 0;if(d!==void 0)return h.get(d)??ef;if(v)return g}return ef}}else if(n){let l;for(let f of n)if((!l||f[1][0].size>l[1][0].size)&&f[1][1].size===r)l=f;t=(f,h)=>{let g=d_(f);if(!tu(f))return u(g);let y=new Set(i?.[g]),v;if(l){let[d,[x]]=l,S=ga(f,d),C=S?f[d]:void 0;if(S&&(!h||C!==void 0)){let T=x.get(C);if(!T)return u(g);for(let F of T)y.add(F);v=d}}if(v===void 0)for(let[d,[x,S]]of n){let C=ga(f,d),T=C?f[d]:void 0;if(C&&(!h||T!==void 0)){let F=x.get(T);if(F)for(let J of F)y.add(J)}else if(h)for(let F of S)y.add(F)}for(let[d,[x,S]]of n){if(d===v)continue;let C=ga(f,d),T=C?f[d]:void 0;if(C&&(!h||T!==void 0)){let F=x.get(T);for(let J of y)if(S.has(J)&&!F?.has(J))y.delete(J)}}return Array.from(y).sort((d,x)=>d-x)}}else t=(l)=>{let f=u(d_(l));return o?f.filter((h)=>s[h]===void 0||s[h]===l):f};return f_.set(e,t),t}function R_(e,t,n,r){let i=oc(t);if(!i)return Bs(t);return ca(new ic(e,[i],n,r))}function qP(e,t,n,r){return yr(t,(i)=>R_(e,i,n,r))}function zP(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=HP(o,n);if(!a){if(o.out)return o.out;return m(new ic(e,o.issues??[],r,i))}return WP(a,o)}function WP(e,t){return Jt(e,(n)=>{if(t.out===Ne)return O(t.input);if(t.out)return t.out;return m(new ic(t.ast,t.issues??[],t.input,t.options))})}function p_(e){return e?"":"readonly "}function m_(e){return e?"?":""}function uf(e,t,n=!1){return new ih((r,i,o)=>Jb(i,e(r,i,o),r,o),t,n)}function hh(e){return uf((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 gh(e,t){let n=new globalThis.RegExp(e),r={source:n.source,flags:n.flags};return uf((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 fc(e,t){let n=Object.assign(Object.create(Object.getPrototypeOf(e)),e,t);if(Reflect.ownKeys(t).every((r)=>r==="context"||r==="encoding"))oh.set(n,ff(e));return n}function ff(e){let t=oh.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 oh.set(e,n),n}function Yn(e,t){return e.encoding===t?e:fc(e,{encoding:t})}function dc(e,t){if(e.context===t)return e;let n=ff(e);if(n.context===t&&n.encoding===e.encoding)return n;return fc(e,{context:t})}function I_(e){return e.encoding?I_(e.encoding[e.encoding.length-1].to):e}function df(e,t){if(e.checks){let n=e.checks[e.checks.length-1];return P_(e,tm(e.checks.slice(0,-1),n.annotate(t)))}return fc(e,{annotations:{...e.annotations,...t}})}function P_(e,t){if(e._tag==="Suspend"&&t)throw Error("Cannot add checks to Suspend");if(e.checks===t)return e;return fc(e,{checks:t})}function pc(e,t){return P_(e,fh(e.checks,t))}function KP(e,t){let n=t(e.to);return n===e.to?e:new An(n,e.transformation)}function O_(e,t){let n=e,r=n[n.length-1],i=KP(r,t);return i===r?e:tm(e.slice(0,e.length-1),i)}function GP(e){return(t)=>t.encoding?Yn(t,O_(t.encoding,e)):t}function YP(e,t){function n(r){if(r.encoding){let i=r.encoding[r.encoding.length-1];return t?.stopAt?.(i)?r:Yn(r,O_(r.encoding,n))}return e(r)}return zo(n)}function ZP(e,t,n){let r=new An(e,t);return Yn(n,n.encoding?[...n.encoding,r]:[r])}function Ea(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 yh(e,t){let n=e.context?new xa(e.context.isOptional,e.context.isMutable,e.context.constructorDefault,{...e.context.annotations,...t}):new xa(!1,!1,void 0,t);return dc(e,n)}function N_(e,t){let n=e.context?new xa(e.context.isOptional,e.context.isMutable,t,e.context.annotations):new xa(!1,!1,t);return dc(e,n)}function M_(e,t,n){return ZP(e,n,t)}function QP(e){let t=[],n=[];function r(i){switch(i._tag){case"Literal":if(wx(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 D_(e,t){let{literals:n,parameters:r}=QP(e);return new sf(n.map((i)=>new uh(i,t)),r.map((i)=>new b_(i,t)))}function po(e){return e.context?.isOptional??!1}function L_(e){return e.annotations?.[Ys]===!0||e._tag==="FilterGroup"&&e.checks.every(L_)}function eO(e){function t(r){if(L_(r))return[r];return r._tag==="FilterGroup"?r.checks.flatMap(t):[]}let n=e.flatMap(t);return nm(n)?n:void 0}function tO(e){let t=!0;function n(r){if(t=t&&!r.encoding&&!g_(r),t&&"recur"in r)r.recur(n);return r}if("recur"in e)e.recur(n);return t}function nO(e,t){let n=t,r=n.length,i=n[r-1],o=[new An(Kr(Yn(e,void 0)),n[0].transformation.flip())];for(let s=1;s<r;s++)o.unshift(new An(Kr(n[s-1].to),n[s].transformation.flip()));let a=Kr(i.to);if(a.encoding)return Yn(a,[...a.encoding,...o]);else return Yn(a,o)}function F_(e){switch(e._tag){case"Undefined":return!0;case"Union":return e.types.some(F_);default:return!1}}function Sh(e,t){let n=t===0?Ne:Ot(t);return(r,i)=>{if(r===se)return On;if(r===t)return n;return m(new xr(e,r,i))}}function mc(e,t){return(n,r)=>{if(n===se)return On;if(t(n))return Ne;return m(new xr(e,n,r))}}function U_(e){return gh(ah,{expected:"a string representing a finite number",representation:{id:"effect/schema/isStringFinite",payload:null},toJsonSchema:()=>({pattern:ah.source}),...e})}function bi(e,t,n,r,i){for(let o=0;o<e.length;o++){let a=e[o];if(a._tag==="FilterGroup"){if(n=bi(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 qb(a,s,t,i);if(n)n.push(c);else n=[c];if(i.errors!=="all"||a.aborted)return n}}}return n}function j_(e){if(!h_(e))return;let t=e.annotations?.[qm];return Ss(t)?t(e.typeParameters):void 0}function cO(e){return e===null||typeof e==="string"||typeof e==="boolean"||typeof e==="number"&&globalThis.Number.isFinite(e)}function lO(e){return e===void 0||typeof e==="string"}function B_(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 uO(e){return B_(e,cO)}function fO(e){return B_(e,lO)}var h_,TP,Sa,th,kP,IP,g_,An=class{to;transformation;constructor(e,t){this.to=e,this.transformation=t}},ho,xa=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}},c_="~effect/Schema",Nn,uc,PP,sh,OP,AP,ch,NP,tf,ya,MP,fo,DP,lh,LP,y_,af,S_,UP,$P,nf=(e,t,n,r)=>{if(r.cause.reasons.length===0)return r;let i=oc(r.cause);if(i===void 0)return Bs(gi(r.cause,(a)=>new Bt(t,[new Jr([n],a)],e.input,e.options)));let o=new Jr([n],i);if(e.options.errors==="all")if(e.issues)e.issues.push(o);else e.issues=[o];else return ca(new Bt(t,[o],e.input,e.options))},x_="[+-]?\\d*\\.?\\d+(?:[Ee][+-]?\\d+)?",uh=class{name;type;constructor(e,t){this.name=e,this.type=t}},b_=class{parameter;type;constructor(e,t){if(!jP(e))throw Error(`Invalid index signature parameter ${e._tag}`);if(this.parameter=e,this.type=t,po(t)&&!F_(t))throw Error("Cannot use `Schema.optionalKey` with index signatures, use `Schema.optional` instead.")}},sf,__,u_,BP,mh,f_,ef,d_=(e)=>e===null?"null":Array.isArray(e)?"array":typeof e,ga=(e,t)=>t==="__proto__"?Object.hasOwn(e,t):(t in e),va,HP,T_,ih,of,k_,JP,oh,pf,XP,A_,vi,mf,Kr,xh,ah,rO,$_,iO,oO,aO="-?\\d+",hq,sO="Symbol\\(([\\s\\S]*)\\)",gq,V_,dO,pO;var hc=L(()=>{wu();oo();Fe();ua();$r();on();qr();Hu();Gm();ha();Ur();Dt();Gu();Si();Qu();h_=mo("Declaration"),TP=mo("Never"),Sa=mo("Literal"),th=mo("UniqueSymbol"),kP=mo("Arrays"),IP=mo("Objects"),g_=mo("Suspend"),ho={};Nn=class Nn{[c_]=c_;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}>`}};uc=class extends Nn{_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===se)return On;return(e??=this.run(this.typeParameters))(t,this,n)}}_rebuild(e,t,n,r,i){let o=Ea(this.typeParameters,e);return o===this.typeParameters&&t===this.checks&&n===this.encodingChecks&&r===this.run&&i===this.encodingRun?this:new uc(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>"}},PP=class extends Nn{_tag="Null";getParser(){return Sh(this,null)}getExpected(){return"null"}},sh=new PP,OP=class extends Nn{_tag="Undefined";getParser(){return Sh(this,void 0)}toCodecJson(){return Yn(this,[AP])}getExpected(){return"undefined"}},AP=new An(sh,new Sn(Kt(()=>{return}),Kt(()=>null))),ch=new OP,NP=class extends Nn{_tag="Unknown";getParser(){return mc(this,Rx)}getExpected(){return"unknown"}},tf=new NP,ya=class extends Nn{_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 ${ke(e)}`);this.literal=e}getParser(){return Sh(this,this.literal)}matchPart(e,t){return e===globalThis.String(this.literal)?this.literal:void 0}toCodecJson(){return typeof this.literal==="bigint"?l_(this):this}toCodecStringTree(){return typeof this.literal==="string"?this:l_(this)}getExpected(){return typeof this.literal==="string"?JSON.stringify(this.literal):globalThis.String(this.literal)}};MP=class extends Nn{_tag="String";getParser(){return mc(this,Wo)}matchPart(e,t){let n=this.checks;return n&&!t.disableChecks&&bi(n,e,void 0,this,t)?void 0:e}getExpected(){return"string"}},fo=new MP,DP=class extends Nn{_tag="Number";getParser(){return mc(this,ys)}matchKey(e,t){return this._match(rO,e,t)}matchPart(e,t){return this._match(ah,e,t)}_match(e,t,n){if(!e.test(t))return;let r=globalThis.Number(t);if(n.disableChecks||!this.checks)return r;return bi(this.checks,r,void 0,this,n)?void 0:r}toCodecJson(){if(this.checks&&(nh(this.checks,"effect/schema/isFinite")||nh(this.checks,"effect/schema/isInt")))return this;return Yn(this,[JP])}toCodecStringTree(){if(this.toCodecJson()===this)return Yn(this,[iO]);return Yn(this,[oO])}getExpected(){return"number"}};lh=new DP,LP=class extends Nn{_tag="Boolean";getParser(){return mc(this,bx)}getExpected(){return"boolean"}},y_=new LP,af=class extends Nn{_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 u=0;u<t.length;u++)if(po(t[u]))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 u=1;u<n.length;u++)if(po(n[u]))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,f){if(f<o)return r[f];else if(f>=l)return i[f-l+1];return i[0]}let c=(l)=>{let{input:f,len:h,options:g}=l;if(n.rest.length===0&&h>o)for(let y=o;y<h;y++){let v=new Km(n,f[y],g),d=new Jr([y],v);if(g.errors==="all")if(l.issues)l.issues.push(d);else l.issues=[d];else return m(new Bt(n,[d],f,g))}if(l.issues)return m(new Bt(n,l.issues,f,g));return Ot(l.output)},u=(l,f)=>{let h=l.length,g={ast:n,getParser:s,input:l,len:h,tailThreshold:Math.max(o,h-a),output:new globalThis.Array(h),issues:void 0,options:f},y=n.rest.length===0?o:Math.max(h,o+a),v=f.concurrency===void 0?1:js(f.concurrency),d=v===1?UP(g,l,0,y):$P(g,l,{concurrency:v,end:y});if(!d)return c(g);if(Ve(d))return Jt(d,()=>c(g));let x=!0;return Pb(()=>{if(!x)return u(l,f);return x=!1,Ae(d,()=>c(g))})};return(l,f)=>{if(l===se)return On;try{if(!Array.isArray(l))return m(new xr(n,l,f));if(!r)r=n.elements.map((h)=>({ast:h,parser:t(h)})),i=n.rest.map((h)=>({ast:h,parser:t(h)}));return u(l,f)}catch(h){return zs(h)}}}_rebuild(e,t,n){let r=Ea(this.elements,e),i=Ea(this.rest,e);return r===this.elements&&i===this.rest&&t===this.checks&&n===this.encodingChecks?this:new af(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"}};S_={onItem(e,t,n){let r=n<e.len?t:se;return e.getParser(e.tailThreshold,n).parser(r,e.options)},step:FP},UP=Nu()(S_),$P=Mu()(S_);sf=class extends Nn{_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 mc(n,Cx);let o,a,s=()=>{if(!o)o=n.propertySignatures.map((f)=>({parser:t(f.type),name:f.name,type:f.type})),a=i?n.indexSignatures.map((f)=>({is:f,parserKey:e(xh(f.parameter)),parserValue:t(f.type)})):void 0;return o},c=()=>{let f=new Set(n.propertySignatures.map((d)=>typeof d.name==="number"?globalThis.String(d.name):d.name)),h=(d,x,S,C,T)=>{if(T._tag==="Failure")return nf(d,n,x,T)??la;let F=T===Ne?C:T[oe];if(S!==se&&F!==se){if(r&&(f.has(x)||f.has(typeof S==="number"?globalThis.String(S):S)))return la;jr(d.out,S,F)}return la},g=(d,x,S,C)=>{if(!C){let j=S.parserKey(x,d.options);if(!Ve(j))return Ae(ao(j),(z)=>g(d,x,S,z));C=j}if(C._tag==="Failure")return nf(d,n,x,C)??la;let T=C===Ne?x:C[oe],F=d.input[x],J=S.parserValue(F,d.options);return Ve(J)?h(d,x,T,F,J):Ae(ao(J),(j)=>h(d,x,T,F,j))},y=(d,x,S)=>{let C=d.input[x],T=S.parserValue(C,d.options);return Ve(T)?h(d,x,x,C,T):Ae(ao(T),(F)=>h(d,x,x,C,F))},v=i?Mu()({onItem:(d,[x,S])=>S.is.parameter===fo?y(d,x,S):g(d,x,S),step:(d,x,S)=>S._tag==="Failure"?S:void 0}):void 0;return jb(function*(d,x){if(d===se)return se;if(!(typeof d==="object"&&d!==null&&!Array.isArray(d)))return yield*m(new xr(n,d,x));s();let S=d,C={},T={ast:n,input:S,out:C,issues:void 0,options:x},F=x.errors==="all",J=x.onExcessProperty==="error",j=x.concurrency===void 0?1:js(x.concurrency),z=i&&J?n.indexSignatures.map((K)=>eh(S,K.parameter,x)):void 0;if(J){let K=z?new Set(f):f;if(z)for(let Y of z)for(let I of Y)K.add(I);let Ce=Reflect.ownKeys(S);for(let Y=0;Y<Ce.length;Y++){let I=Ce[Y];if(!K.has(I)&&Object.prototype.propertyIsEnumerable.call(S,I)){let B=new Km(n,S[I],x),be=new Jr([I],B);if(F){if(T.issues)T.issues.push(be);else T.issues=[be];continue}else return yield*m(new Bt(n,[be],d,x))}}}if(r){let K=j===1?u_(T,o):BP(T,o,{concurrency:j});if(K)yield*K}if(i&&j===1)for(let K=0;K<i;K++){let Ce=a[K],Y=Ce.is.parameter===fo?y:g,I=z?.[K]??(Ce.is.parameter===fo?Object.keys(S):eh(S,Ce.is.parameter,x));for(let B=0;B<I.length;B++){let be=Y(T,I[B],Ce);if(!Ve(be))yield*be;else if(be._tag==="Failure")return yield*be}}else if(v){let K=_u();for(let Y=0;Y<i;Y++){let I=a[Y],B=z?.[Y]??(I.is.parameter===fo?Object.keys(S):eh(S,I.is.parameter,x));for(let be=0;be<B.length;be++)K.push([B[be],I])}let Ce=v(T,K,{concurrency:j});if(Ce)yield*Ce}if(T.issues)return yield*m(new Bt(n,T.issues,d,x));return C})};if(i)return c();let u,l=(f,h,g)=>{let y=o[h];return Ae(ao(g),(v)=>{let d=rh(f,y,v);if(d)return d;let x=()=>Ot(f.out),S=u_(f,o.slice(h+1));return S?Jt(S,x):x()})};return(f,h)=>{if(f===se)return On;if(h.errors==="all"||h.onExcessProperty!==void 0||h.concurrency!==void 0&&js(h.concurrency)!==1)return(u??=c())(f,h);if(!(typeof f==="object"&&f!==null&&!Array.isArray(f)))return m(new xr(n,f,h));let g=s(),y=f,v={},d={ast:n,input:y,out:v,issues:void 0,options:h};try{for(let x=0;x<g.length;x++){let S=g[x],C=S.name,T=ga(y,C),F=T?y[C]:se,J=S.parser(F,h);if(!Ve(J))return l(d,x,J);if(J===Ne){if(T)jr(v,C,F);continue}let j=rh(d,S,J);if(j)return j}}catch(x){return zs(x)}return Ot(v)}}_rebuild(e,t,n,r){let i=Ea(this.propertySignatures,(a)=>{let s=e(a.type);return s===a.type?a:new uh(a.name,s)}),o=Ea(this.indexSignatures,(a)=>{let s=t(a.parameter),c=e(a.type);return s===a.parameter&&c===a.type?a:new b_(s,c)});return i===this.propertySignatures&&o===this.indexSignatures&&n===this.checks&&r===this.encodingChecks?this:new sf(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"}};__={onItem(e,t){if(!ga(e.input,t.name))return t.parser(se,e.options);let n=e.input[t.name];return jr(e.out,t.name,n),t.parser(n,e.options)},step:rh},u_=Nu()(__),BP=Mu()(__);mh=zo((e)=>{while(!0){if(g_(e))return tf;let t=e.encoding;if(!t)return e.recur?.(mh,at)??e;if(t.some((n)=>n.transformation._tag==="Middleware"&&n.transformation.decode!==at))return tf;e=t[t.length-1].to}});f_=new WeakMap,ef=Object.freeze([]);va=class extends Nn{_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===se)return On;let u=(a??=VP(n.types))(s,r);if(u.length===0)return m(new ic(n,[],s,c));if(u.length===1){let l=o(u[0])(s,c);if(l._tag==="Success")return l;return Ve(l)?R_(n,l.cause,s,c):qP(n,l,s,c)}return zP(n,o,u,s,c)}}_rebuild(e,t,n){let r=Ea(this.types,e);return r===this.types&&t===this.checks&&n===this.encodingChecks?this:new va(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=mf(r);switch(i._tag){case"Arrays":{let o=i.elements.filter(Sa);if(o.length>0)return`${p_(i.isMutable)}[ ${o.map((a)=>e(a)+m_(a.context?.isOptional)).join(", ")}, ... ]`;break}case"Objects":{let o=i.propertySignatures.filter((a)=>Sa(a.type));if(o.length>0)return`{ ${o.map((a)=>`${p_(a.type.context?.isMutable)}${Yo(a.name)}${m_(a.type.context?.isOptional)}: ${e(a.type)}`).join(", ")}, ... }`;break}}return e(i)});return Array.from(new Set(n)).join(" | ")}};HP=Nu()({onItem(e,t){return e.parser(t)(e.input,e.options)},step(e,t,n){if(n._tag==="Failure"){let r=oc(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]),ca(new Wb(e.ast,e.successes,e.input,e.options));if(e.out=n,e.successes)e.successes.push(e.ast.types[t]);else return la}}}),T_=new va([new ya("Infinity"),new ya("-Infinity"),new ya("NaN")]);ih=class extends ds{_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 ih(this.run,{...this.annotations,...e},this.aborted)}abort(){return new ih(this.run,this.annotations,!0)}and(e,t){return new of([this,e],t)}},of=class extends ds{_tag="FilterGroup";checks;annotations;constructor(e,t=void 0){super();this.checks=e,this.annotations=t}annotate(e){return new of(this.checks,{...this.annotations,...e})}and(e,t){return new of([this,e],t)}};k_=pc(lh,[hh()]),JP=new An(new va([k_,T_]),new Sn(Ku(),Kt((e)=>globalThis.Number.isFinite(e)?e:globalThis.String(e))));oh=new WeakMap;pf=zo((e)=>{let t=e.context?e.context.isOptional===!1?new xa(!0,e.context.isMutable,e.context.constructorDefault,e.context.annotations):e.context:new xa(!0,!1);return XP(dc(e,t))}),XP=GP(pf),A_=ps((e)=>pf(new va([e,ch])));vi=zo((e)=>{let t=ff(e);if(t!==e){let r=vi(t);return r===t&&e.encoding===void 0?e:dc(r,e.context)}let n="recur"in e?e.recur(vi):e;if("encodingChecks"in n&&n.encodingChecks){let r=tO(e)?n.encodingChecks:kP(n)||IP(n)||h_(n)&&n.typeParameters.length>0?eO(n.encodingChecks):void 0;return fc(n,{encodingChecks:void 0,checks:fh(n.checks,r)})}return n}),mf=zo((e)=>vi(Kr(e)));Kr=ps((e)=>{if(e.encoding)return nO(e,e.encoding);let t=ff(e);if(t!==e){let n=Kr(t);return n===t?e:dc(n,e.context)}return"flip"in e?e.flip(Kr):("recur"in e)?e.recur(Kr):e});xh=YP((e)=>{switch(e._tag){default:return e;case"Number":return e.toCodecStringTree();case"Union":return e.recur(xh)}}),ah=new globalThis.RegExp(`^${x_}$`),rO=new globalThis.RegExp(`^(?:${x_}|Infinity|-Infinity|NaN)$`);$_=pc(fo,[U_()]),iO=new An($_,Zu),oO=new An(new va([$_,T_]),Zu),hq=new globalThis.RegExp(`^${aO}$`),gq=new globalThis.RegExp(`^${sO}$`);V_=new uc([],()=>(e,t,n)=>uO(e)?Ne:m(new xr(t,e,n)),{representation:{id:"effect/schema/Json",payload:null},expected:"JSON value",toCodecJson:()=>{return},toCodecStringTree:()=>pO});dO=new uc([],()=>(e,t,n)=>fO(e)?Ne:m(new xr(t,e,n)),{expected:"StringTree",toCodecStringTree:()=>{return}}),pO=new An(dO,Yu())});function z_(e){if(e._tag==="Middleware")return(n,r,i)=>{let o=n===Ne?e.decode(Ot(Zs(r)),i):e.decode(Bu(n,Zs),i);return q_(o)};let t=e.decode;switch(t._tag){case"Passthrough":return(n,r)=>n===Ne?Ot(r):n;case"Transform":{let n=(r)=>r===se?On:Ot(t.transform(r));return(r,i)=>gf(r,i,n)}case"TransformOptional":{let n=(r)=>Wm(t.transform(Zs(r)));return(r,i)=>gf(r,i,n)}case"TransformEffect":return(n,r,i)=>gf(n,r,(o)=>o===se?On:t.transform(o,i));case"TransformOptionalEffect":return(n,r,i)=>gf(n,r,(o)=>q_(t.transform(Zs(o),i)))}}function mO(e,t){let n=z_(e.link.transformation),r;return(i,o)=>{if(i===se)return On;if(e.isConstructed(i))return Ne;let a=(r??=t(e.link.to))(i,o);return n(a,i,o)}}function hO(e,t){let n=e.context.constructorDefault;return(r,i)=>{if(r!==se&&r!==void 0)return t(r,i);let o=n;if(Ve(o)&&o._tag==="Success"){let a=t(o[oe],i);return a===Ne?o:a}return Jt(W_(e,r,i,o),(a)=>{let s=t(a,i);return s===Ne?Ot(a):s})}}function Eh(e,t){let n=t(e);return e.context?.constructorDefault===void 0?n:hO(e,n)}function gc(e,t,n,r,i){if(e._tag==="Declaration")for(let y of e.typeParameters)t(y);let o=n?j_(e):void 0,a=o?mO(o,t):r??e.getParser(t,n),{checks:s,encoding:c}=e,u=c?.map((y)=>z_(y.transformation)),l=e.encodingChecks;if(!c&&!s&&!l)return a;let f,h=(y,v)=>{let d=a(y,v);if(l&&!v.disableChecks)if(Ve(d)){if(d._tag==="Success"){let x=d===Ne?y:d[oe];if(y!==se&&x!==se){let S=bi(l,y,void 0,e,v);if(S)d=m(new Bt(e,S,y,v))}}}else d=Ae(d,(x)=>{if(y!==se&&x!==se){let S=bi(l,y,void 0,e,v);if(S)return m(new Bt(e,S,y,v))}return O(x)});if(s&&!v.disableChecks)if(Ve(d)){if(d._tag==="Success"){let x=d===Ne?y:d[oe];if(x===se)return d;let S=bi(s,x,void 0,e,v);if(S)d=m(new Bt(e,S,x,v))}}else d=Ae(d,(x)=>{if(x!==se){let S=bi(s,x,void 0,e,v);if(S)return m(new Bt(e,S,x,v))}return O(x)});return d},g=i===void 0?h:i(h);if(!c)return g;return(y,v)=>{let d=f??=c.map((C)=>t(C.to)),x=y,S=d[d.length-1](y,v);for(let C=c.length-1;C>=0;C--)if(S=u[C](S,x,v),C!==0){let T=d[C-1];if(S._tag==="Success")x=S[oe],S=T(x,v);else S=Jt(S,(F)=>{let J=T(F,v);return J===Ne?Ot(F):J})}if(S._tag==="Success"){let C=S[oe],T=g(C,v);return T===Ne?S:T}return S=W_(e,y,v,S),Jt(S,(C)=>{let T=g(C,v);return T===Ne?Ot(C):T})}}var gf=(e,t,n)=>e===Ne?n(t):Jt(e,n),q_=(e)=>Jt(e,Wm),W_=(e,t,n,r)=>yr(r,(i)=>qs(()=>gi(i,(o)=>new zb(e,o,t,n))));var H_=L(()=>{oo();Fe();hc();Si();qr();ha()});class bh{ast;constructor(e){this.ast=e}get decodeEffect(){return this.cachedDecodeEffect??=gc(this.ast,yO)}get parser(){return this.decodeEffect}get makeEffect(){return this.cachedMakeEffect??=gc(this.ast,G_,SO)}}function xO(e,t){let n;return(r,i)=>{if(r!==se)try{let o=e(r,i);if(o!==vh)return o===r?Ne:Ot(o)}catch(o){return zs(o)}return(n??=t())(r,i)}}function yf(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=J_.get(e);if(t!==void 0)return t;let n=K_===void 0?new bh(e):new Y_(e,K_(e,Zn),Zn);return J_.set(e,n),n}var vh,J_,K_,Sf=!1,yO=(e)=>Sf?yf(Zn,e,"parser"):Zn(e).parser,G_=(e)=>Sf?yf(Zn,e,"makeEffect"):Zn(e).makeEffect,SO=(e)=>Eh(e,G_),Y_;var Z_=L(()=>{Fe();H_();ha();vh=Symbol(),J_=new WeakMap;Y_=class Y_ extends bh{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")??gc(this.ast,(e)=>yf(this.resolve,e,"parser")))}get parser(){let e=this.decode;return e===void 0?this.decodeEffect:this.save("parser",xO(e,()=>this.decodeEffect))}get makeEffect(){let e=this.operation("makeEffect");if(e!==void 0)return this.save("makeEffect",e);let t=(n)=>yf(this.resolve,n,"makeEffect");return this.save("makeEffect",gc(this.ast,t,(n)=>Eh(n,t)))}}});function _h(e){let t=e.ast,n;return(r,i)=>(n??=nw(IO,vi(t)))(r,i?.disableChecks?i?.parseOptions?{...i.parseOptions,disableChecks:!0}:{disableChecks:!0}:i?.parseOptions)}function wh(e){let t=_h(e);return(n,r)=>{let i=co(t(n,r));if(zr(i))return Vr(i.value);return xi(i.cause,"Option adapter can only return none for schema issues"),mr()}}function Ch(e){return TO(vi(e.ast))}function X_(e){return _O(e.ast)}function bO(e){if(!Sf){let i=rw(ew(e));return(o)=>{let a=i(o,ho);if(zr(a))return!0;return xi(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,ho)}catch(o){return xi(Fm(o),"Type guard adapter can only return false for schema issues"),!1}};let r=t.parser;return(i)=>{let o=co(tw(r(i,ho),i));if(zr(o))return!0;return xi(o.cause,"Type guard adapter can only return false for schema issues"),!1}}function _O(e){let t=vi(e),n=(r)=>(n=bO(t),n(r));return(r)=>n(r)}function Rh(e,t){let n=ew(e.ast);return t===void 0?n:(r,i)=>n(r,wO(t,i))}function Q_(e,t){return CO(Rh(e,t))}function ew(e){return nw(kO,e)}function tw(e,t){if(e===Ne)return O(t);if(!Ve(e))return Jt(e,xf);return e[oe]===se?xf(se):e}function nw(e,t){let n;return(r,i)=>{let o=(n??=e(t))(r,i??ho);if(o===Ne)return O(r);if(!Ve(o))return Jt(o,xf);return o[oe]===se?xf(se):o}}function rw(e){return(t,n)=>co(e(t,n))}function CO(e){let t=rw(e);return(n,r)=>{let i=t(n,r);if(zr(i))return hr(i.value);return gn(xi(i.cause,"Result adapter can only return schema issues"))}}function RO(e,t){let n=co(e);if(zr(n))return n.value;let r=xi(n.cause,t);throw Error("Schema validation failed",{cause:r})}function TO(e){let t,n;return(r,i)=>{t??=Zn(e);let o=i?.disableChecks?i.parseOptions?{...i.parseOptions,disableChecks:!0}:{disableChecks:!0}:i?.parseOptions??ho,a=t.make;if(a!==void 0&&r!==se){let c;try{c=a(r,o)}catch(u){throw xi(Fm(u),"Constructor adapter can only throw schema issues"),u}if(c!==vh&&c!==se)return c}let s=(n??=t.makeEffect)(r,o);return RO(tw(s,r),"Constructor adapter can only throw schema issues")}}var wO=(e,t)=>t?{...e,...t}:e,xf=(e)=>{if(e===se)return m(new jt);return O(e)},kO=(e)=>Zn(e).parser,IO=(e)=>Zn(e).makeEffect;var Th=L(()=>{oo();Fe();ua();qr();Gm();Z_();ha();Ps();It();hc();Si()});function Ih(e,t){function n(){}let r=Object.setPrototypeOf(n,PO);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[ow]=t,r.ast=e,r}var kh="~effect/Schema/Schema",ow,PO;var aw=L(()=>{Ur();hc();Th();ow=Symbol(),PO={[kh]:kh,get make(){let e=Ch(this);return Object.defineProperty(this,"make",{value:e,enumerable:!0}),e},get makeEffect(){let e=_h(this);return Object.defineProperty(this,"makeEffect",{value:e,enumerable:!0}),e},get makeOption(){let e=wh(this);return Object.defineProperty(this,"makeOption",{value:e,enumerable:!0}),e},pipe(){return rn(this,arguments)},annotate(e){return this.rebuild(df(this.ast,e))},annotateKey(e){return this.rebuild(yh(this.ast,e))},check(...e){return this.rebuild(pc(this.ast,e))},rebuild(e){return Ih(e,this[ow])}}});var ba=(e)=>e;var sw=()=>{};function cw(e){return Re(e,_a)&&e[_a]===_a}var _a="~effect/Schema/SchemaError";var lw=L(()=>{Dt()});function NO(){return(e,t,n)=>et(new uc(e.map(cf),(r)=>t(r.map((i)=>et(i))),n))}function MO(e,t){return NO()([],()=>(n,r,i)=>e(n)?O(n):m(new xr(r,n,i)),t)}function DO(e){return cw(e)}function LO(e){if(Ve(e))return FO(e);return yr(e,(t)=>qs(()=>gi(t,(n)=>new Ef(n))))}function FO(e){return zr(e)?e:Bs(gi(e.cause,(t)=>new Ef(t)))}function UO(e,t){let n;for(let r of e.reasons){if(!Uu(r)||!DO(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 $O(e){let t=co(e);if(zr(t))return t.value;throw UO(t.cause,"Sync adapter can only throw schema errors")}function jO(e,t){let n=Rh(e,t);return(r,i)=>LO(n(r,i))}function Me(e,t){let n=Q_(e,t);return(r,i)=>LE(n(r,i),(o)=>new Ef(o))}function Gt(e,t){let n=jO(e,t);return(r,i)=>$O(n(r,i))}function Ph(e){let t=et(new ya(e),{literal:e,transform(n){return t.pipe(yc(Ph(n),{decode:Kt(()=>n),encode:Kt(()=>e)}))}});return t}function fw(e,t){return et(e,{fields:t,mapFields(n,r){let i=n(this.fields);return fw(dh(i,r?.unsafePreserveChecks?this.ast.checks:void 0),i)}})}function E(e){return fw(dh(e,void 0),e)}function Pe(e,t){return et(D_(e.ast,t.ast),{key:e,value:t})}function ye(e,t){return et(w_(e.ast,t.map(cf)),{schema:e,records:t})}function dw(e,t){return et(e,{elements:t,mapElements(n,r){let i=n(this.elements);return dw(ph(i,r?.unsafePreserveChecks?this.ast.checks:void 0),i)}})}function Oh(e){return dw(ph(e),e)}function pw(e,t){return et(e,{members:t,mapMembers(n,r){let i=n(this.members);return pw(lf(i,this.ast.options,r?.unsafePreserveChecks?this.ast.checks:void 0),i)}})}function H(e,t){return pw(lf(e,t,void 0),e)}function R(e){let t=e.map(Ph);return et(lf(t,void 0,void 0),{literals:e,members:t,mapMembers(n){return H(n(this.members))},pick(n){return R(n)},transform(n){return H(t.map((r,i)=>r.transform(n[i])))}})}function go(e){return(t)=>et(t.ast,{schema:t,identifier:e})}function yc(e,t){return(n)=>et(M_(n.ast,e.ast,t?Xm(t):Yu()),{from:n,to:e})}function zO(e){return(t)=>et(N_(t.ast,e),{schema:t})}function WO(e){return yr(e,(t)=>qs(()=>gi(t,(n)=>n.issue)))}function Ah(e,t){let n=t?.encodingStrategy==="omit"?Qb():sc();return(r)=>De(BO(r)).pipe(yc(r,{decode:e_(WO(e)),encode:n}))}function uw(e){return Ph(e).pipe(zO(O(e)))}function wa(e,t){return MO((n)=>n instanceof e,t)}function Ca(){return(e,t)=>new An(e.ast,Xm(t))}function ce(e,t){let{source:n,flags:r}=e,i=/^[dg]*uy?$/.test(r),o=r===""?`new RegExp(${ke(n)})`:`new RegExp(${ke(n)}, ${ke(r)})`;return gh(e,{toJsonSchema:()=>i?{pattern:r.endsWith("y")?`^(?:${n})`:n}:[{},!0],toCode:()=>({runtime:`Schema.isPattern(${o})`}),...t})}function HO(e){let t=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;return ce(t,{expected:"a base64 encoded string",representation:{id:"effect/schema/isBase64",payload:null},toJsonSchema:()=>({pattern:t.source}),toCode:()=>({runtime:"Schema.isBase64()"}),...e})}function JO(e){let t=du(e.order),n=e.formatter??ke;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 KO(e){let t=dE(e.order),n=e.formatter??ke;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 GO(e){let t=fE(e.order),n=e.formatter??ke;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 Nh(e){if(!globalThis.Number.isFinite(e))throw new globalThis.RangeError(`Expected a finite number, got ${ke(e)}`);return e}function Ta(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 tt(e,t){return e=mw(e),YO(e,Math.ceil(e/2),t)}function YO(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})`}),[Ys]:!0,arbitraryConstraint:{minLength:e},...n})}function Mh(e,t){return e=mw(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})`}),[Ys]:!0,arbitraryConstraint:{maxLength:e},...t})}function mw(e){if(!globalThis.Number.isFinite(e))throw new globalThis.RangeError(`Expected a finite number, got ${e}`);return Math.max(0,Math.floor(e))}function _f(e,t){return XO.pipe(yc(e,Xu(t)))}var Ef,le,et,De,w,BO,Ge,_e,VO,_,Ye,N,M,qO,ee,yo,So,Ra,vf,bf,sz,ZO,cz,XO,QO,lz,uz,eA,fz,tA=-8640000000000000,nA=8640000000000000,dz,pz,sn,_i;var Ue=L(()=>{oo();om();Fe();jm();ua();$r();qr();Hu();aw();lw();au();jp();It();hc();Gu();Si();Th();Qu();sw();Ef=class Ef extends Ru("SchemaError"){[_a]=_a;constructor(e){let t=Xo();Qo(0);try{super({issue:e})}finally{Qo(t)}}get message(){return Yb(this.issue)}toString(){return`SchemaError(${this.message})`}};le=X_;et=Ih,De=ba((e)=>et(pf(e.ast),{schema:e})),w=ba((e)=>{let t=qO(e);return et(A_(e.ast),{schema:t})}),BO=ba((e)=>et(mf(e.ast),{schema:e}));Ge=et(tf),_e=et(sh),VO=et(ch),_=et(fo),Ye=et(lh),N=et(y_);M=ba((e)=>et(new af(!1,[],[e.ast]),{value:e}));qO=ba((e)=>H([e,VO]));ee=uf;yo=hh;So=JO({order:ra,annotate:(e)=>({representation:{id:"effect/schema/isGreaterThan",payload:{exclusiveMinimum:Nh(e)}},toJsonSchema:()=>({exclusiveMinimum:e}),toCode:()=>({runtime:`Schema.isGreaterThan(${ke(e)})`})})}),Ra=KO({order:ra,annotate:(e)=>({representation:{id:"effect/schema/isGreaterThanOrEqualTo",payload:{minimum:Nh(e)}},toJsonSchema:()=>({minimum:e}),toCode:()=>({runtime:`Schema.isGreaterThanOrEqualTo(${ke(e)})`})})}),vf=GO({order:ra,annotate:(e)=>({representation:{id:"effect/schema/isLessThanOrEqualTo",payload:{maximum:Nh(e)}},toJsonSchema:()=>({maximum:e}),toCode:()=>({runtime:`Schema.isLessThanOrEqualTo(${ke(e)})`})})});bf=Ye.check(Ta());sz=wa(globalThis.RegExp,{representation:{id:"effect/schema/RegExp",payload:null},toCode:()=>({runtime:"Schema.RegExp",Type:"globalThis.RegExp"}),expected:"RegExp",toCodecJson:()=>Ca()(E({source:_,flags:_}),lc({decode:(e,t)=>U({try:()=>new globalThis.RegExp(e.source,e.flags),catch:()=>new jt({expected:"valid RegExp source and flags"},e,t)}),encode:(e)=>O({source:e.source,flags:e.flags})}))}),ZO=_.annotate({expected:"a string that will be decoded as a URL"}),cz=wa(globalThis.URL,{representation:{id:"effect/schema/URL",payload:null},toCode:()=>({runtime:"Schema.URL",Type:"globalThis.URL"}),expected:"URL",toCodecJson:()=>Ca()(ZO,a_)}),XO=_.annotate({expected:"a string that will be decoded as JSON",contentMediaType:"application/json"});QO=wa(globalThis.File,{representation:{id:"effect/schema/File",payload:null},toCode:()=>({runtime:"Schema.File",Type:"globalThis.File"}),expected:"File",toCodecJson:()=>Ca()(E({data:_.check(HO()),type:_,name:_,lastModified:bf}),lc({decode:(e,t)=>bu(zu(e.data),{onFailure:()=>m(new jt({expected:"a valid Base64 string"},e.data,t)),onSuccess:(n)=>{let r=new globalThis.Uint8Array(n);return O(new globalThis.File([r],e.name,{type:e.type,lastModified:e.lastModified}))}}),encode:(e,t)=>p({try:async()=>{let n=new globalThis.Uint8Array(await e.arrayBuffer());return{data:qu(n),type:e.type,name:e.name,lastModified:e.lastModified}},catch:()=>new jt({expected:"a readable File"},e,t)})}))}),lz=wa(globalThis.FormData,{representation:{id:"effect/schema/FormData",payload:null},toCode:()=>({runtime:"Schema.FormData",Type:"globalThis.FormData"}),expected:"FormData",toCodecJson:()=>Ca()(M(Oh([_,H([E({_tag:uw("String"),value:_}),E({_tag:uw("File"),value:QO})])])),lc({decode:(e)=>{let t=new globalThis.FormData;for(let[n,r]of e)t.append(n,r.value);return O(t)},encode:(e)=>O(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}]}))}))}),uz=wa(globalThis.URLSearchParams,{representation:{id:"effect/schema/URLSearchParams",payload:null},toCode:()=>({runtime:"Schema.URLSearchParams",Type:"globalThis.URLSearchParams"}),expected:"URLSearchParams",toCodecJson:()=>Ca()(_.annotate({expected:"a query string that will be decoded as URLSearchParams"}),o_({decode:(e)=>new globalThis.URLSearchParams(e),encode:(e)=>e.toString()}))}),eA=_.annotate({expected:"a base64 encoded string that will be decoded as Uint8Array",format:"byte",contentEncoding:"base64"}),fz=wa(globalThis.Uint8Array,{representation:{id:"effect/schema/Uint8Array",payload:null},toCode:()=>({runtime:"Schema.Uint8Array",Type:"globalThis.Uint8Array"}),expected:"Uint8Array",toCodecJson:()=>Ca()(eA,s_)}),dz=tA+50400000,pz=nA-50400000,sn=et(df(V_,{toCode:()=>({runtime:"Schema.Json",Type:"Schema.Json"})})),_i=Pe(_,sn)});function xn(e,t){return Me(e,rA)(t)}var rA;var ka=L(()=>{Ue();rA={onExcessProperty:"error"}});function xw(e){let t=Me(xc)(e);return Ke(t)?t.success:void 0}function Dh(e){return xw(e)!==void 0}function Ew(e){return typeof e==="string"&&Dh(e)&&!e.includes("-")}function hw(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 oA(e){if(typeof e!=="string")return!1;let[t,n,r]=e.split("-");if(t===void 0||n===void 0||r!==void 0)return!1;if(!Ew(t))return!1;let[i,o,a,s]=n.split(".");return i==="dev"&&s===void 0&&hw(o)&&hw(a)}function wf(e){let t=xw(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 Ia(e,t){let n=gw(e),r=gw(t),i=Sc(n.minor,r.minor);if(i!==0)return i;let o=Sc(n.patch,r.patch);if(o!==0)return o;return sA(n.suffix,r.suffix)}function Fh(e,t){let n=wf(t);if(e!=="patch"&&e!=="minor"){if(!Dh(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 gw(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 Sc(e,t){let n=BigInt(e),r=BigInt(t);if(n<r)return-1;if(n>r)return 1;return 0}function sA(e,t){let n=yw(e),r=yw(t);if(n<r)return-1;if(n>r)return 1;if(e.kind==="numeric"&&t.kind==="numeric")return Sc(e.value,t.value);if(e.kind==="development"&&t.kind==="development"){let i=Sc(e.runNumber,t.runNumber);return i===0?Sc(e.runAttempt,t.runAttempt):i}return 0}function yw(e){if(e.kind==="development")return 0;if(e.kind==="base")return 1;return 2}var Sw,iA,xc,Lh,aA,Ec;var vw=L(()=>{It();Ue();Sw=/^0\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)(?:-(?:0|[1-9]\d*))?$/u,iA=/^0\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)(?:-(?:(?:0|[1-9]\d*)|dev\.[1-9]\d*\.[1-9]\d*))?$/u,xc=_.check(ce(Sw));Lh=_.check(ee((e)=>Ew(e)?void 0:"Expected a canonical base version"));aA=_.check(ee((e)=>oA(e)?void 0:"Expected a development release version")),Ec=_.check(ce(iA))});function $h(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(Rw(r)&&i==="openai-bundled"&&t===i)return{pluginName:r,marketplaceName:i,canonicalPluginId:e};if(!Cw(r)||!ww(i)||t!==i)return;return{pluginName:r,marketplaceName:i,canonicalPluginId:`${r}@openai-curated`}}function Mn(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(Cw(n)&&ww(r))return`${n}@openai-curated`;if(Rw(n)&&r==="openai-bundled")return`${n}@openai-bundled`;return}function Pa(e){let t=Mn(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 ww(e){return le(uA)(e)}function Cw(e){return le(fA)(e)}function Rw(e){return le(dA)(e)}function jh(e,t){let n=t??Ct;return{browser_use:e?.browser_use??n.browser_use,computer_use:e?.computer_use??n.computer_use,sites:e?.sites??n.sites,"session-audit":e?.["session-audit"]??n["session-audit"],"auto-reset":e?.["auto-reset"]??n["auto-reset"]}}function Oa(e,t=[]){let n=[...kw],r=new Set(n);for(let i of Tw){if(!e[i])continue;for(let o of Er[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 vc,Uh,bc,cA,lA,bw,uA,Cf,fA,_w,dA,nt,En,pA,mA,Er,Tw,hA,kw,gA,Ct;var Bh=L(()=>{Fe();Ue();vc=R(["auto-reset","browser_use","computer_use","frontend","session-audit","security","sites"]),Uh=R(["browser_use","computer_use","sites","session-audit","auto-reset"]),bc=E({browser_use:N,computer_use:N,sites:N,"session-audit":N.pipe(De,Ah(O(!1))),"auto-reset":N.pipe(De,Ah(O(!1)))}),cA=R(["installed","disabled","missing","uncertain"]),lA=R(["healthy","missing","disabled","uncertain"]),bw=Object.freeze(["openai-curated","openai-curated-remote"]),uA=R(bw),Cf=Object.freeze(["build-web-apps","codex-security"]),fA=R(Cf),_w=Object.freeze(["browser","computer-use","sites"]),dA=R(_w);nt=Object.freeze({coding:!0,computer_use:!1,browser_use:!0,sites:!0,frontend:!0,"session-audit":!1,"auto-reset":!1,security:!0}),En=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([{skillId:"codex-security:security-diff-scan",appliesWhen:"a bounded implemented change is ready for security review"},{skillId:"codex-security:security-scan",appliesWhen:"a repository or scoped path needs a broader security review"},{skillId:"codex-security:threat-model",appliesWhen:"security architecture or trust boundaries need analysis"}]),computer_use:Object.freeze([]),browser_use:Object.freeze([]),sites:Object.freeze([]),"session-audit":Object.freeze([{skillId:"session-audit",appliesWhen:"the session-audit capability is enabled for the current task"}]),"auto-reset":Object.freeze([{skillId:"auto-reset",appliesWhen:"the auto-reset capability is enabled and quota monitoring detects a threshold"}])}),pA=En.frontend,mA={frontend:{name:"frontend",pluginIds:["build-web-apps@openai-curated"],defaultSelected:nt.frontend,semanticSkillIds:Object.freeze(En.frontend.map(({skillId:e})=>e)),applicability:En.frontend,ownership:"shared-preserve"},security:{name:"security",pluginIds:["codex-security@openai-curated"],defaultSelected:nt.security,semanticSkillIds:En.security.map(({skillId:e})=>e),applicability:En.security,ownership:"shared-preserve"},"session-audit":{name:"session-audit",pluginIds:[],defaultSelected:nt["session-audit"],semanticSkillIds:En["session-audit"].map(({skillId:e})=>e),applicability:En["session-audit"],ownership:"shared-preserve"},"auto-reset":{name:"auto-reset",pluginIds:[],defaultSelected:nt["auto-reset"],semanticSkillIds:En["auto-reset"].map(({skillId:e})=>e),applicability:En["auto-reset"],ownership:"shared-preserve"},computer_use:{name:"computer_use",pluginIds:["computer-use@openai-bundled"],defaultSelected:nt.computer_use,migrationKey:"computer_use",semanticSkillIds:["computer-use:computer-use"],applicability:En.computer_use,ownership:"shared-preserve"},browser_use:{name:"browser_use",pluginIds:[],defaultSelected:nt.browser_use,migrationKey:"browser_use",semanticSkillIds:[],applicability:En.browser_use,ownership:"shared-preserve"},sites:{name:"sites",pluginIds:["sites@openai-bundled"],defaultSelected:nt.sites,migrationKey:"sites",semanticSkillIds:[],applicability:En.sites,ownership:"shared-preserve"}},Er=Object.freeze(mA),Tw=Object.freeze(["browser_use","computer_use","sites","session-audit","auto-reset"]),hA=Object.freeze(["frontend","security"]),kw=Object.freeze([...Er.frontend.pluginIds,...Er.security.pluginIds]),gA=Object.freeze(["writing-instructions","babysit-ci","dev-server","visual-loop"]),Ct=Object.freeze({browser_use:nt.browser_use,computer_use:nt.computer_use,sites:nt.sites,"session-audit":nt["session-audit"],"auto-reset":nt["auto-reset"]})});function vr(e){return E({identifier:R([e]),label:_,requiresRootApproval:N})}function Iw(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 Pw(e){return e.length===0?e:`${e[0]?.toUpperCase()??""}${e.slice(1)}`}var Ow,yA,SA,Vh,xA,Aw,EA,vA,bA;var Nw=L(()=>{Ue();Ow=R(["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"]),yA=E({identifier:Ow,label:_,requiresRootApproval:N});SA=E({localRepositoryEdit:vr("local.repository.edit"),localRepositoryCheck:vr("local.repository.check"),localRepositoryLint:vr("local.repository.lint"),localRepositoryFormat:vr("local.repository.format"),localRepositoryCommit:vr("local.repository.commit"),externalRead:vr("external.read"),specialistDispatch:vr("specialist.dispatch"),versionControlServerMutation:vr("vcs.server.mutation"),versionControlServerCiTrigger:vr("vcs.server.ci-trigger"),unknownEffect:vr("unknown.effect")}),Vh={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}};Sr(Vh);xA=R(["never","root"]),Aw=Object.values(Vh);EA=Aw.filter((e)=>!e.requiresRootApproval),vA=Aw.filter((e)=>e.requiresRootApproval),bA=Object.freeze({noRootApproval:`${Pw(Iw(EA))} actions do not require Root approval.`,rootApproval:`${Pw(Iw(vA))} require Root approval.`})});function zh(e){let t=xn(_A,e);if(Be(t))return lo(Ks("sha256 digest",t.failure));return pa(t.success)}var Xn,qh,vz,bz,_z,_A,wA,CA,RA,TA;var Rf=L(()=>{It();Ue();ma();ka();Xn=_.check(ce(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u)),qh=_.check(ce(/^[0-9a-f]{64}$/u)),vz=Xn.pipe(go("RunId")),bz=Xn.pipe(go("ProjectId")),_z=Xn.pipe(go("TrustId")),_A=qh.pipe(go("Sha256Digest"));wA=E({run_id:Xn,objective_lineage:Xn,parent_run_id:w(H([Xn,_e]))}),CA=E({project_id:Xn,trust_id:Xn,trust_digest:qh}),RA=E({project_id:Xn,project_digest:qh}),TA=_.check(ce(/^state-[0-9]+\.[0-9]+$/u))});function If(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 Yh(e){let t=`${e.role}.${e.task}`;return Gt(Gh)(t)}function Zh(e){let t=Hh.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,Of,Mf,Af].join(" ")}function Xh(e){let t=Hh.get(e.role)?.tasks.find((n)=>n.name===e.task);if(t===void 0)throw Error("Unknown specialist task policy.");return t.description}function Bw(e){let t=Hh.get(e);if(t===void 0)throw Error("Unknown specialist role.");return t}function Qh(e){let n=Bw(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 cn,Mw,Qn,vn,kA,Pf="Satisfy the complete requested outcome and acceptance criteria correctly; preserve repository and runtime constraints; 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.",Tf="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.",Aa="Do not modify repository source or the implementation under validation; observation, analysis, and proof artifacts only.",br,Wh,IA="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.",PA,Dw,OA,wi,Hh,Lw,AA,Jh,Fw,Uw,$w,jw,_c,Kh,Gh,wc,Gr,Of,Af="Return exactly one compact, evidence-first terminal outcome to Root. Include agent_id, concrete Role.task, owned seam and write scope, terminal outcome, reusable status, changed paths, checks, observable evidence, blockers, Root decisions needed, and remaining risk. If acceptance is blocked by missing input, name the exact missing input and the work it blocks. Reuse is eligible only under the compatible warm reuse definition. Do not report progress before the terminal result.",Ci,Vw,kf,NA,MA,DA,eg,Nf,LA,bn,FA,UA,Ie,Mf="Batch scheduling-independent operations and parallelize only when information dependencies allow it. Continue deterministic known work before returning to model reasoning; return only when an intermediate result must be interpreted before the next action. Combine deterministic capability discovery with the operation when safe. Avoid duplicate reads, tool calls, and model boundaries. Retain every unique fact needed for correctness, failure diagnosis, acceptance, changed behavior, or a Root decision; remove repetitive and irrelevant output without truncating required evidence.";var Cc=L(()=>{Ue();cn=R(["low","default","high"]),Mw=R(["go","Go","plus-low","plus","plus-high","pro-5x","pro-20x"]),Qn=H([cn,Mw]);vn=R(["standard","fast","fast-all"]),kA=R(["low","medium","high"]),br=Object.freeze({materialDecision:"A choice that changes requirements/accepted behavior, user-facing behavior, architecture/trust boundaries, security posture, persistent/data/API contracts, dependency/toolchain strategy, deployment/external effects, Assignment ownership/scope, or whose reversal would invalidate substantial accepted work.",routineDecision:"A safe reversible choice inside the Assignment that changes none of the material-decision categories.",stableSource:"Every currently planned writer for the seam/revision is terminal and no running Assignment owns an overlapping write that can invalidate dependent evidence.",schedulingIndependent:"Neither action needs the other's output to choose or execute its next action.",writeIndependent:"Write ownership does not overlap and neither Assignment depends on transient mutable state produced by the other.",independentReview:"The reviewer is not the agent whose work is being independently reviewed and does not share ownership that compromises that review.",evidenceInvalidation:"Evidence becomes stale only when a later mutation changes behavior, source/configuration, generated artifact, runtime state, or a dependency assumption established by that evidence.",compatibleWarmReuse:"Reuse is allowed only when the previous specialist is terminal; the same concrete Role.task remains valid; the follow-up fits the same or compatible ownership seam; retained context remains relevant; reuse does not violate independent review; and no conflicting writer is active.",materialVisualDiscrepancy:"A rendered discrepancy affecting acceptance criteria, hierarchy/composition, legibility, accessibility, responsiveness, interaction correctness, reference adherence, or obvious production quality."}),Wh=[["Material decision",br.materialDecision],["Routine decision",br.routineDecision],["Stable source",br.stableSource],["Scheduling-independent",br.schedulingIndependent],["Write-independent",br.writeIndependent],["Independent review",br.independentReview],["Evidence invalidation",br.evidenceInvalidation],["Compatible warm reuse",br.compatibleWarmReuse],["Material visual discrepancy",br.materialVisualDiscrepancy]].map(([e,t])=>`${e}: ${t}`).join(" "),PA=R([!1]),Dw=Object.freeze(["implementation","review","validation","integration","vcs"]),OA=R(["read-only","workspace-write"]),wi=[{role:"Explorer",sharedInstruction:`Keep discovery within the assigned repository scope and return exact paths, symbols, callers, tests, and constraints. ${Aa}`,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:`${IA} ${Aa}`,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 projected skills appropriate to the work and keep image_generation enabled. Prefer a suitable existing project or user asset, then an online asset legally reusable for the intended use with its required attribution/license provenance, then a generated asset when no reusable asset fits or a generated asset better satisfies the design. Do not search indefinitely when generation is the better implementation choice. Return changed paths and observable rendered/interaction evidence for independent Reviewer.visual review. ${Tf}`,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. ${Aa}`,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. ${Aa}`,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:"Own reproduction, regression hunting, benchmark methodology and results, missing or ineffective behavioral tests, flaky tests, test architecture, and testing-related behavior defects. Repair concrete in-scope defects and prove the affected behavior. Return material test-strategy and architecture decisions to Root. Add no redundant tests; behavior expectations must come from externally meaningful contracts rather than implementation internals.",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. ${Tf} ${Aa}`,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:"Own cross-cutting repository, process, configuration, and integration concerns that have no narrower specialist owner or span multiple categories. Route testing, reproduction, and benchmarks to Reviewer.testing; security and trust-boundary work to Reviewer.security; rendered UI/UX to Reviewer.visual; and implementation correctness to Reviewer.code. Repair concrete in-scope findings 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:"For an implemented change, use `codex-security:security-diff-scan`; for a broader repository scope, use `codex-security:security-scan`; for architecture or trust-boundary analysis, use `codex-security:threat-model`. Apply first-party validation and fix procedures when relevant instead of duplicating them. Hypothetical modeled threats are allowed in threat-model work but are not validated vulnerabilities. Repair validated vulnerabilities within the Assignment and prove the affected behavior. A validated introduced or worsened vulnerability blocks VCS. Return material security, product, architecture, and risk 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}}];Sr(wi);Hh=new Map(wi.map((e)=>[e.role,e])),Lw=wi.flatMap((e)=>e.tasks.map((t)=>`${e.role}:${t.name}`)),AA=Lw.map((e)=>e.replace(":",".")),Jh=R(["Explorer","Librarian","Worker","Reviewer"]),Fw=R(["map","lookup","trace"]),Uw=R(["lookup","research"]),$w=R(["mechanical","implementation","visual","integration","operations","validation","debugging"]),jw=R(["code","testing","visual","artifact","audit","security"]),_c=H([E({role:R(["Explorer"]),task:Fw}),E({role:R(["Librarian"]),task:Uw}),E({role:R(["Worker"]),task:$w}),E({role:R(["Reviewer"]),task:jw})]),Kh=R(["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"]),Gh=R(["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"]),wc=Object.freeze(Lw.map((e)=>Gt(Kh)(e))),Gr=Object.freeze(AA.map((e)=>Gt(Gh)(e))),Of=`Execute only the bounded Assignment using its objective, scope, constraints, dependencies, permissions, ownership, and acceptance criteria; make routine in-scope choices autonomously. Return material decisions, scope expansion, or required user input to Root; never ask or message the user. Do not delegate, mutate Intent or Assignment lifecycle, perform Git/VCS writes, or cause consequential external effects unless the Assignment explicitly grants an allowed effect. Stay within the owned mutable seam, preserve unrelated and concurrent work, and adapt to shared-tree changes. Root owns user interaction, lifecycle, material decisions, integration acceptance, completion, Git/VCS writes, consequential external effects, final visual judgment, and the shared development server. ${Wh}`,Ci=Object.freeze(["default","worker","explorer","reviewer","librarian"]);Vw=E({profile:cn,service_tier:w(vn)}),kf=Object.freeze(["user_interaction","intent","material_decisions","orchestration_lifecycle","integration_acceptance","completion","git_vcs","external_effects","visual_judgment","dev_server"]),NA=R([...kf]),MA=R(["delegated","root_direct","unavailable"]),DA=R([...kf]),eg=R(["used","no_coverage","unavailable","auth_or_quota_failure","source_conflict"]),Nf=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}),LA=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}),bn=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:Tf,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"])}),FA=Object.freeze({interactiveCapabilitiesRemainSpecialistOwned:!0,rootMayInspectForVisualJudgment:!0,credentialEntryAndSubmissionRemainUserOwned:!0,specialistsMustNeverHandleCredentials:!0,missingAuthorizedPathIsCapabilityBlocker:!0}),UA=Object.freeze({threatModelForMaterialTrustBoundaryChanges:!0,securityDiffScanRequiredForSecuritySensitiveDiffs:!0,fullScanOnlyForAuditNewExposedSurfaceOrSystemicConcern:!0,validateSupportedFindingsBeforeBlocking:!0,introducedOrWorsenedValidatedVulnerabilityBlocksVcs:!0,preExistingUnrelatedFindingsDoNotExpandScope:!0,securityEditsInvalidateCodeReview:!0,securitySensitiveCodeReviewEditsInvalidateSecurityReview:!0,materialDecisionsRemainRootOwned:!0}),Ie=Object.freeze({requiresDelegation:!0,explicitUserDirectExecutionOverridesDelegation:!1,assignmentStartAndDispatchPrecedeDelegableExecution:!0,trivialWorkRequiresDelegation:!0,preparatoryAndExploratoryWorkRequiresDelegation:!0,genericDirectWorkFallback:!1,concreteSpecialistDispatchRequired:!0,registeredSpecialistAgentTypes:Gr,roleFamiliesAreLabelsOnly:!0,forbiddenGenericAgentTypes:Ci,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:kf,rootOwnedAuthority:kf,requestUserInputGates:Object.freeze(["missing_authorization_for_consequential_effect","missing_or_ambiguous_correctness_input_unresolvable_from_authorized_context"]),dependencyAwareAmbiguityInstruction:"When required information is missing, continue actions whose correctness is independent of it and do not perform speculative work whose validity depends on the answer. Ask only when missing or ambiguous information affects correctness and cannot be resolved from authorized context, or authorization for a consequential external effect is missing.",surgicalMutationRule:Pf,phaseOrder:Dw,phaseGates:Object.freeze({implementedScopeStableBeforeReview:!0,reviewerCodeAndWorkerValidationMayOverlapOnNonConflictingScopes:!0,currentValidationBeforeRootIntegration:!0,rootIntegrationBeforeVcs:!0}),initialDispatch:Object.freeze({independentAssignments:!0,substantiveIndependentConcurrency:!0,routinePostdispatchSteering:!1,waitIncludesEveryLiveBlockingSpecialist:!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,terminalReuseStateIncludes:Object.freeze(["agent_id","concrete Role.task","owned seam and write scope","terminal outcome","reusable status"])}),normalSpawnForkContext:!1,normalSpawnRequiresExplicitRegisteredAgentType:!0,normalSpawnUsesConcreteRegisteredAgentType:!0,normalSpawnModelOverride:!1,normalSpawnEffortOverride:!1,orchestrationToolNamespace:"multi_agent_v1",orchestrationToolOperations:Object.freeze(["spawn_agent","send_input","wait_agent","resume_agent","close_agent"]),orchestrationToolsDirectOnly:!0,toolSearchRemainsAvailableForDeferredCapabilities:!0,v1UsageHintText:"HolyCodex Root delegates all delegable work to exact registered HolyCodex Role.task agent types. For normal spawns use fork_context=false; do not override the selected route's model or effort. Dispatch all ready independent Assignments before waiting. Follow the HolyCodex exact wait contract. Root does not perform delegable fallback work.",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,semanticDefinitionsInstruction:Wh,normalProgressMessages:!1,normalHeartbeatMessages:!1,normalIntermediateEvidence:!1,userUpdatesUsefulOrImportantOnly:!0,routinePerToolOrSubagentNarrationForbidden:!0,routineStatusOnlyChatterForbidden:!0,fixedCadenceUserUpdatesForbidden:!0,materialUserUpdateKinds:Object.freeze(["changes_a_root_decision","changes_the_expected_user_visible_outcome","user_input_is_required","authorized_progress_is_blocked","user_relevant_release_or_completion_milestone"]),outOfBoundaryRequiresNewAssignment:!0,rootWaitTool:"multi_agent_v1.wait_agent",rootWaitTimeoutMs:600000,specialistCoordinationInstruction:"Coordinate through terminal reports, not conversation. After dispatch, do not inspect, message, poll, request status from, or follow up with a running specialist. Interrupt or supersede only when changed user intent, cancellation, or Assignment invalidation makes continued work incorrect. Never sleep or busy-poll for specialist coordination. Dispatch every ready scheduling-independent Assignment before waiting. Each multi_agent_v1.wait_agent call must include every live specialist whose result blocks the next required Root decision or action and use timeout_ms=600000 exactly; terminal completion may wake it early. If the timeout expires while a blocking dependency remains live, perform ready independent work and then wait again with timeout_ms=600000. After a terminal result, prefer compatible warm reuse only when the exact predicate allows it: send_input for immediate follow-up on an open agent, close_agent with no near-term follow-up, or resume_agent then send_input for later reuse after closure. Keep Root turns for judgment, decisions, orchestration boundaries, integration, contradictions, and completion.",rootWaitRequiresExactTimeout:!0,earlySpecialistCompletionWakesWait:!0,waitIncludesEveryLiveBlockingSpecialist:!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(["agent_id","concrete Role.task","owned seam and write scope","terminal outcome","reusable status","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:Nf,codeReviewRequiredForImplementation:!0,codeReviewRequiredBeforeVcs:!0,externalVerificationMustBeTerminal:!0,postVcsFlow:"discover_topology_observe_repair_repeat"})});function Lf(e){let t=xn(Yw,e);if(Be(t))return lo(Ks("CLI envelope",t.failure));return pa(t.success)}var qw,$A,jA,zw,BA,VA,tg="holycodex-specialist-outcome-2",At,Na,Rc,qA,zA,WA,HA,JA,KA,Df,GA,YA,ZA,XA,QA,Ww,Hw,Jw,eN,Kw,Gw,Yw;var ng=L(()=>{It();Ue();Bh();ma();Rf();Cc();ka();qw=R(["blocked","completed","failed","partial"]),$A=H([R(["high"]),_e]),jA=H([R(["high","max","xhigh"]),_e]),zw=sn,BA=_i,VA=E({blocked:N,changed_files:M(_),confidence:Ye,context_owner:H([_,_e]),material_findings:M(_),needs_more_context:N,needs_root_decision:N,needs_verification:N,relevant_files:M(_),remaining_risk:M(_),reuse_recommended:N,status:qw,suggested_followup:H([_,_e]),suggested_luna_effort:jA,suggested_specialist:H([Jh,_e]),verification:M(_),verification_passed:N}),At=_.check(tt(1)),Na=E({state:eg,evidence:M(At).check(tt(1)),library:w(At),version:w(At)}),Rc={protocol_version:R([tg]),route:_c,evidence:M(At),context7:w(Na)},qA=E(Rc),zA=E({...Rc,status:R(["completed"]),summary:At}),WA=E({...Rc,status:R(["blocked"]),reason:At,needs_root_decision:N}),HA=E({...Rc,status:R(["partial"]),summary:At,completed:M(At),remaining:M(At),needs_root_decision:N}),JA=E({...Rc,status:R(["failed"]),error:At}),KA=H([zA,WA,HA,JA]),Df={protocol_version:R([tg]),capability:vc,route:H([_c,_e]),evidence:M(At),context7:w(Na),data:zw},GA=E({...Df,status:R(["completed"]),summary:At}),YA=E({...Df,status:R(["blocked"]),reason:At,needs_root_decision:N}),ZA=E({...Df,status:R(["partial"]),summary:At,completed:M(At),remaining:M(At),needs_root_decision:N}),XA=E({...Df,status:R(["failed"]),error:At}),QA=H([GA,YA,ZA,XA]),Ww=M(_),Hw=_.check(ce(/^[a-z][a-z0-9-]*(?: [a-z][a-z0-9-]*)*$/u)),Jw=R([Hr]),eN=E({code:Xn,message:_,details:BA}),Kw=E({schema_version:Jw,ok:R([!0]),command:Hw,data:zw,warnings:Ww}),Gw=E({schema_version:Jw,ok:R([!1]),command:Hw,error:eN,warnings:Ww}),Yw=H([Kw,Gw])});function tN(e,t,n){return{key:`${e}:${t}`,role:e,task:t,model:Tc,effort:n}}function iN(e){let t=rN.get(e);if(t===void 0)throw new mt("catalog_invalid","A profile has no route effort policy.",{profile:e});return wi.flatMap((n)=>n.tasks.map((r)=>{let i=`${n.role}:${r.name}`,o=t.efforts[i];if(o===void 0)throw new mt("catalog_invalid","A route effort policy is incomplete.",{profile:e,route:i});return tN(n.role,r.name,o)}))}function rg(e){return{name:e.name,root:{model:e.rootModel,effort:e.rootEffort},specialistModel:Tc,defaultServiceTier:"standard",routes:iN(e.name)}}function oN(e){let t=["low","default","high"];if(e.length!==t.length)throw new mt("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 mt("catalog_invalid","The profile catalog order is invalid.",{index:n});let o=Ff,a=i==="low"?"low":"medium";if(r.root.model!==o||r.root.effort!==a||r.specialistModel!==Tc)throw new mt("catalog_invalid","A profile has an invalid model route.",{profile:r.name});if(r.routes.length!==wc.length)throw new mt("catalog_invalid","A profile is incomplete.",{profile:r.name});let s=new Set;for(let c of r.routes){if(s.has(c.key)||!nN.has(c.key)||c.model!==Tc||`${c.role}:${c.task}`!==c.key)throw new mt("catalog_invalid","A profile contains an invalid route.",{profile:r.name});s.add(c.key)}if(s.size!==wc.length)throw new mt("catalog_invalid","A profile is missing a specialist route.",{profile:r.name})}}function Ma(e){let t=xn(cn,e);if(Be(t))return lo(new mt("invalid_profile","Unknown profile selection.",{field:"profile"},{cause:t.failure}));let n=Xw.get(t.success);if(!n)return lo(new mt("invalid_profile","Unknown profile selection.",{profile:t.success}));return pa(n)}var Ff="gpt-6.1-sol",Tc="gpt-6-luna",nN,ig,rN,og,Zw,Xw,aN;var Qw=L(()=>{It();ma();Cc();ka();nN=new Set(wc),ig=[{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"}}];Sr(ig);rN=new Map(ig.map((e)=>[e.profile,e]));og=[rg({name:"low",rootModel:Ff,rootEffort:"low"}),rg({name:"default",rootModel:Ff,rootEffort:"medium"}),rg({name:"high",rootModel:Ff,rootEffort:"medium"})];oN(og);Sr(og);Zw=og,Xw=new Map,aN=new Map;for(let e of Zw){Xw.set(e.name,e);let t=new Map;for(let n of e.routes)t.set(n.key,n);aN.set(e.name,t)}});function cN(e,t){return new mt("invalid_canonical_value",`Cannot canonicalize ${e}: ${t}.`,{path:e,reason:t})}function ag(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)||!ag(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&&ag(i.value,n)})}function sg(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(sg).join(",")}]`;let t=e;return`{${Object.keys(t).sort().map((r)=>`${JSON.stringify(r)}:${sg(t[r])}`).join(",")}}`}function er(e){let t=Me(lN)(e);if(Be(t))throw cN("$",`invalid JSON value: ${String(t.failure)}`);return sg(t.success)}function _n(e){return new TextEncoder().encode(er(e))}function eC(e,t){let n=Me(uN)(e);if(Be(n))throw new mt("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 u of t){if(u.byteLength>4294967295||o>4294967291-u.byteLength)throw new mt("invalid_digest_domain","Digest input is too large.");o+=4+u.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 u of t)s.setUint32(c,u.byteLength,!1),c+=4,a.set(u,c),c+=u.byteLength;return a}function fN(e){let t="";for(let n of e)t+=n.toString(16).padStart(2,"0");return t}function wn(e,t){let n=globalThis.crypto?.subtle;if(!n)throw new mt("crypto_unavailable","The standards-based crypto API is unavailable.");return A(me(p(()=>n.digest("SHA-256",dN(eC(e,t)).buffer)),(r)=>fN(new Uint8Array(r))))}function dN(e){let t=new Uint8Array(e.byteLength);return t.set(e),t}var lN,uN;var tC=L(()=>{Fe();It();Ue();ma();Rf();lN=sn.check(ee((e)=>ag(e))),uN=_.check(tt(1),ce(/^[^\0]+$/u))});import{execFile as mN}from"child_process";import{promisify as hN}from"util";var rC="holycodex-intent-1",iC="holycodex-plan-1",oC="holycodex-assignment-1",Uf="toon-4",Q,tr,$f,aC,Da,Dn,st,Jz,cg,xo,lg,ug,gN,nC,yN,SN,fg,sC,cC,La,dg,xN,EN,Kz,vN="holycodex-work-state-transaction-1",Gz,Yz,bN,_N,wN,CN,RN,TN,kN,IN,Zz,PN,Xz;var lC=L(()=>{Ue();ng();Cc();ka();Q=_.check(ee((e)=>e.trim().length>0)),tr=_.check(ce(/^[a-z0-9][a-z0-9-]{0,95}$/u)),$f=_.check(ce(/^[a-f0-9]{64}$/u)),aC=_.check(ce(/^[a-f0-9]{40}$/u)),Da=bf.check(Ra(1)),Dn=_.check(ee((e)=>!Number.isNaN(Date.parse(e)))),st=M(Q),Jz=E({pid:bf.check(So(0)),token:Q}),cg=E({role:R(["Explorer","Librarian","Worker","Reviewer"]),task:Q}).check(ee((e)=>wi.some((t)=>t.role===e.role&&t.tasks.some((n)=>n.name===e.task)))),xo=E({kind:R(["changed_path","check","repository_fact","ci","behavior","uncertainty"]),value:Q,result:w(R(["passed","failed","observed","unknown"]))}),lg=E({root:Q,git_common_dir:Q,initial_head:Q,expected_head:Q,expected_changes:st,expected_status_digest:$f,integrated_commit:w(aC),updated_at:Dn}),ug=R(["scoping","ready","executing","verifying","reviewing","blocked","needs_root_input","complete","abandoned"]),gN=R(["scoping","ready","executing","verifying","reviewing"]),nC=E({required:N,status:R(["not_required","missing","passed","failed","accepted","rejected"]),evidence:M(xo)}),yN=E({schema_version:R([rC]),toon_compatibility:R([Uf]),id:tr,slug:tr,title:Q,goal:Q,acceptance_criteria:st,state:ug,revision:Da,plan_required:N,active_plan_revision:w(Da),active_plan_digest:w($f),blockers:st,resume_state:w(gN),verification:nC,review:nC,acceptance_met:N,root_readiness:N,evidence:M(xo),baseline:lg,created_at:Dn,updated_at:Dn}),SN=E({schema_version:R([iC]),toon_compatibility:R([Uf]),intent_id:tr,revision:Da,predecessor_digest:w($f),approach:Q,scope:st,exclusions:st,assignments:st,dependencies:st,architecture:st,risks:st,assumptions:st,open_questions:st,verification:st,recovery:st,updated_at:Dn}),fg=R(["completed","blocked","needs_root_input","failed"]),sC=R(["pending","executing","completed","blocked","needs_root_input","failed","superseded"]),cC=E({id:tr,outcome:fg,started_at:Dn,finished_at:Dn,summary:Q,evidence:M(xo),context7:w(Na),blocker:w(Q),remaining_risk:st}),La=$f,dg={schema_version:R([oC]),toon_compatibility:R([Uf]),intent_id:tr,id:tr,objective:Q,owner:H([cg,E({role:R(["Reviewer"]),task:R(["plan"])})]),scope:st,constraints:st,exclusions:st,dependencies:st,acceptance_criteria:st,status:sC,revision:Da,invocations:M(cC),active_invocation_id:w(Q),active_started_at:w(Dn),supersedes:w(tr),superseded_by:w(tr),supersession_reason:w(Q),supersession_provenance:w(Q),evidence:M(xo),blocker:w(Q),remaining_risk:st,created_at:Dn,updated_at:Dn},xN=E(dg),EN=E({...dg,capability:La}),Kz=E({...dg,active_invocation_capability_verifier:w(La),active_invocation_capability:w(La)}),Gz=E({schema_version:R([vN]),state:R(["prepared","committed"]),files:M(E({path:Q,previous:_,next:_})).check(tt(1))}),Yz=E({schema_version:R(["holycodex-intent-0"]),id:tr,slug:tr,title:Q,goal:Q,acceptance_criteria:st,state:ug,revision:Da,baseline:lg,created_at:Dn,updated_at:Dn}),bN=E({title:Q,goal:Q,acceptanceCriteria:M(Q).check(tt(1)),planRequired:w(N),verificationRequired:w(N),reviewRequired:w(N)}),_N=E({approach:Q,scope:w(M(Q)),exclusions:w(M(Q)),assignments:w(M(Q)),dependencies:w(M(Q)),architecture:w(M(Q)),risks:w(M(Q)),assumptions:w(M(Q)),openQuestions:w(M(Q)),verification:w(M(Q)),recovery:w(M(Q))}),wN=E({id:w(Q),objective:Q,owner:cg,scope:M(Q).check(tt(1)),constraints:w(M(Q)),exclusions:w(M(Q)),dependencies:w(M(Q)),acceptanceCriteria:M(Q).check(tt(1))}),CN=E({scope:M(Q).check(tt(1))}),RN=E({scope:w(M(Q).check(tt(1)))}),TN=E({replacementId:tr,replacementRevision:w(Da),reason:Q,provenance:Q}),kN=E({commit:aC}),IN=E({invocationId:w(Q),capability:w(La),outcome:fg,startedAt:w(Q),summary:Q,scope:w(M(Q).check(tt(1))),evidence:w(M(xo)),context7:w(Na),blocker:w(Q),remainingRisk:w(M(Q))}),Zz=E({invocationId:Q,startedAt:Dn,capability:La,interruptionReason:Q}),PN=E({evidence:w(M(xo)),verification:w(R(["passed","failed"])),review:w(R(["accepted","rejected"])),acceptanceMet:w(N),rootReadiness:w(N),clearBlockers:w(N)}),Xz=hN(mN)});var ht=L(()=>{Bb();ma();ka();vw();Bh();Nw();Rf();Cc();ng();Qw();tC();lC()});function Ic(e){if(typeof e!=="object"||e===null||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function NN(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 fC(e){return{ok:!1,error:e}}function dC(e){return{ok:!0,value:e}}function nr(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 Eo(e,t=0){if(t>3)return"[truncated]";if(e===null||typeof e==="boolean")return e;if(typeof e==="string")return nr(e,256);if(typeof e==="number")return Number.isFinite(e)?e:null;if(Array.isArray(e))return e.slice(0,32).map((n)=>Eo(n,t+1));if(Ic(e)){let n={};for(let[r,i]of Object.entries(e).slice(0,32)){let o=nr(r,96);if(o.length>0)n[o]=Eo(i,t+1)}return n}return"[redacted]"}function pC(e){let t=Eo(e);return Ic(t)?t:{value:t}}function He(e,t,n){return new G("invalid_external_data",`Invalid ${e}.`,{field:e,received:Eo(t)},n===void 0?void 0:{cause:n})}function Vt(e,t,n){let r=xn(e,t);if(Be(r))throw He(n,t,String(r.failure));return r.success}function Pc(e,t){return Ke(xn(e,t))}var pg,kc=1048576,mg=65536,Rt,rt,zW,Yr,AN,G;var _r=L(()=>{ht();It();Ue();pg=Hr;Rt=sn,rt=_i,zW=_.check(ce(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u)),Yr=_.check(ee((e)=>e.length>0&&e.length<=4096)),AN=Ye.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=NN(e),this.details=n,this.retryable=r?.retryable??!1,Object.freeze(this.details),Object.freeze(this)}}});var hg,Oc,Ac,gg,yg,Sg,xg="turn/completed";var jf=L(()=>{hg=["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","account/rateLimits/read","account/rateLimitResetCredit/consume"],Oc=["item/commandExecution/requestApproval","item/fileChange/requestApproval","applyPatchApproval","execCommandApproval"],Ac=["item/permissions/requestApproval"],gg=["mcpServer/elicitation/request"],yg=["item/tool/call"],Sg={method:"initialized"}});class Vf{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??kc,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=MN){if(this.initializeEffect)return A(this.initializeEffect);if(this.initializeAttempted)return A(m(new G("invalid_external_data","The App Server initialize handshake was already attempted.")));let t=U({try:()=>{this.ensureOpen();let n=Vt(Dc,e,"initialize parameters");return this.initializeAttempted=!0,this.performInitializeEffect(n)},catch:(n)=>Zr(n,"The initialize handshake failed.")}).pipe($u);return this.initializeEffect=Le(Js(t)),A(this.initializeEffect)}startThread(e={}){return this.action("thread/start",Pg,e,Lc)}resumeThread(e){let t=typeof e==="string"?{threadId:e}:e;return this.action("thread/resume",Fc,t,wg)}readThread(e){let t=typeof e==="string"?{threadId:e}:e;return this.action("thread/read",Og,t,kg)}listThreads(e={}){return this.action("thread/list",Ng,e,Ig)}forkThread(e){let t=typeof e==="string"?{threadId:e}:e;return this.action("thread/fork",Ag,t,Cg)}unsubscribeThread(e){let t=typeof e==="string"?{threadId:e}:e;return this.action("thread/unsubscribe",Rg,t,Tg)}startTurn(e){return this.action("turn/start",Mg,e,Lg)}steerTurn(e){return this.action("turn/steer",Dg,e,Fg)}interruptTurn(e,t){let n=typeof e==="string"?{threadId:e,turnId:t??""}:e;return this.action("turn/interrupt",Ug,n,$g)}listModels(e={}){return this.action("model/list",Bg,e,Vg)}readModelProviderCapabilities(e={}){return this.action("modelProvider/capabilities/read",qg,e,zg)}readConfig(e={}){return this.action("config/read",Gg,e,Yg)}listPermissionProfiles(e={}){return this.action("permissionProfile/list",Zg,e,Xg)}readAccountRateLimits(e={}){return this.action("account/rateLimits/read",Wg,e,Hg)}consumeAccountRateLimitResetCredit(e){return this.action("account/rateLimitResetCredit/consume",Jg,e,Kg)}call(e,t={}){return A(U({try:()=>this.callEffect(e,t),catch:(n)=>Zr(n,"The App Server method failed.")}).pipe($u))}callEffect(e,t){if(e==="initialize")return me(p({try:()=>this.initialize(Vt(Dc,t,"initialize parameters")),catch:(r)=>Zr(r,"The initialize handshake failed.")}),(r)=>Vt(Rt,r,"initialize result"));let n=Vt(Mc,{id:1,method:e,params:t},"App Server method");if(!DN.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=b({self:this},function*(){let n=yield*this.decodeEffect(Dc,e,"initialize parameters"),r=yield*this.decodeEffect(Rt,n,"initialize parameters"),i=yield*this.requestEffect("initialize",r),o=yield*this.decodeEffect(bg,i,"initialize result"),a=yield*this.decodeEffect(_g,Sg,"initialized notification");return yield*this.transportWriteEffect(JSON.stringify(a)),this.initialized=!0,o});return ge(t,()=>!0,(n)=>b({self:this},function*(){let r=Zr(n,"The initialize handshake failed.");return yield*this.closeWithErrorEffect(r),yield*m(r)}))}action(e,t,n,r){return A(U({try:()=>this.actionEffect(e,t,n,r),catch:(i)=>Zr(i,`The ${e} action failed.`)}).pipe($u))}actionEffect(e,t,n,r){return b({self:this},function*(){let i=yield*this.decodeEffect(t,n,`${e} parameters`),o=yield*this.decodeEffect(Rt,i,`${e} parameters`),a=yield*this.requestEffect(e,o);return yield*this.decodeEffect(r,a,`${e} result`)})}decodeEffect(e,t,n){return U({try:()=>Vt(e,t,n),catch:(r)=>Zr(r,`Invalid ${n}.`)})}requestEffect(e,t){if(this.closed)return m(new G("closed","The App Server client is closed."));if(e!=="initialize"&&!this.initialized)return m(new G("invalid_external_data",`The ${e} action requires an initialized App Server client.`));this.startReader();let n=this.nextRequestId;return this.nextRequestId+=1,Ae(this.decodeEffect(Mc,{id:n,method:e,params:t},`${e} request`),(r)=>yi((i,o)=>{let a=!1,s,c,u=()=>l(new G("cancellation",`The ${e} request was cancelled.`,{method:e})),l=(g)=>{if(a)return;if(a=!0,this.pending.delete(n),s!==void 0)clearTimeout(s);c?.(),i(m(g))};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",u,{once:!0}),c=()=>this.signal?.removeEventListener("abort",u),this.signal.aborted)u()}let f={method:e,resume:i,...s===void 0?{}:{timer:s},...c===void 0?{}:{removeAbortListener:c}};this.pending.set(n,f),o.addEventListener("abort",u,{once:!0});let h=this.transportWriteEffect(JSON.stringify(r)).pipe(ge(()=>!0,(g)=>dt(()=>l(g))));return da(h),dt(()=>{if(s!==void 0)clearTimeout(s);c?.(),o.removeEventListener("abort",u),this.pending.delete(n)})}))}transportWriteEffect(e){return p({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(ge(()=>!0,(t)=>this.handleReaderFailureEffect(t)));this.readerFiber=da(e)}}readLoopEffect(){return b({self:this},function*(){while(!this.closed){let e=yield*p({try:()=>this.transport.readLine(),catch:(t)=>Zr(t,"The App Server stdout could not be read.")});if(e===null){if(!this.closed)return yield*m(new G("transport_closed","The App Server transport closed."));return}if(new TextEncoder().encode(e).byteLength>this.maxLineBytes)return yield*m(new G("invalid_transport_line","An App Server line exceeded the limit."));yield*U({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=Le(U({try:()=>JSON.parse(e),catch:(o)=>new G("invalid_transport_line","The App Server emitted invalid JSON.",{},{cause:o})})),n=this.tryDecode(Nc,t);if(n!==void 0){this.handleResponse(n);return}let r=this.tryDecode(Mc,t);if(r!==void 0){this.handleServerRequest(r);return}let i=this.tryDecode(vg,t);if(i!==void 0){this.handleNotification(i);return}throw He("JSON-RPC message",t)}tryDecode(e,t){return Pc(e,t)?Vt(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=FN(t.method);this.resumePending(t,m(new G(r,`The App Server rejected ${t.method}: ${nr(e.error.message)}.`,{method:t.method,serverCode:e.error.code,retryable:n,...e.error.data===void 0?{}:{data:Eo(e.error.data)}},{retryable:n})));return}this.resumePending(t,O(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=Vt(Qg,{...e,params:t,category:mC(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=Ub({onFailure:(s)=>this.writeServerErrorEffect(e.id,-32000,nr(String(s))),onSuccess:(s)=>this.writeValidatedServerResultEffect(e.id,s)})(p({try:()=>Promise.resolve(i(n)),catch:(s)=>s}));this.completeServerRequest(o,a)}writeValidatedServerResultEffect(e,t){return Pc(Bf,t)?this.writeServerResultEffect(e,Vt(Bf,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=Qe(e);this.serverRequestTasks.add(t),da(so(t,dt(()=>this.serverRequestTasks.delete(t))))}writeServerResultEffect(e,t){return Ae(this.decodeEffect(Nc,{id:e,result:t},"server response"),(n)=>this.transportWriteEffect(JSON.stringify(n)))}writeServerErrorEffect(e,t,n){return Ae(this.decodeEffect(Nc,{id:e,error:{code:t,message:LN(n)}},"server error response"),(r)=>this.transportWriteEffect(JSON.stringify(r)))}handleNotification(e){let t=e.params;if(e.method===xg){let n=Vt(jg,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:pC({params:Eo(t)})})}emitNotification(e){for(let t of this.notificationListeners)Le(Qe(U({try:()=>t(e),catch:()=>{return}})))}rejectPending(e){for(let t of this.pending.values())this.resumePending(t,m(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=Le(Js(Qe(p({try:()=>this.transport.close(),catch:()=>{return}}))))}return this.transportCloseEffect}ensureOpen(){if(this.closed)throw new G("closed","The App Server client is closed.")}}function LN(e){let t=nr(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 FN(e){if(Ac.some((t)=>t===e))return"permission_denied";if(Oc.some((t)=>t===e))return"approval_required";if(e==="turn/interrupt")return"cancellation";if(e.startsWith("turn/"))return"turn_failed";return"server_error"}var MN,DN;var Eg=L(()=>{Fe();_r();jf();ey();MN={clientInfo:{name:"holycodex",title:null,version:pg},capabilities:null},DN=new Set(hg)});var hC;var gC=L(()=>{qr();hC=bv});import{isAbsolute as $N}from"path";function Ri(e=process.env){let t=["PATH","HOME","USER","CODEX_HOME","TMPDIR","TEMP","TMP","LANG","LC_ALL"],n={};for(let r of t){let i=e[r];if(i!==void 0&&i.length>0)n[r]=i}return n}function ty(e=process.env){return Object.freeze(Ri(e))}function ny(e,t){return A(SC(e,t))}function SC(e,t){return b(function*(){let n=yield*U({try:()=>e.getReader(),catch:(a)=>new G("transport_failure","A subprocess stream could not be read.",{},{cause:a})}),r=[],i=0,o=b(function*(){while(!0){let c=yield*p({try:()=>n.read(),catch:(u)=>new G("transport_failure","A subprocess stream could not be read.",{},{cause:u})});if(c.done)break;if(i+=c.value.byteLength,i>t)return yield*m(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*so(o,dt(()=>n.releaseLock()))})}function qf(e,t){return Le(U({try:()=>new TextDecoder("utf-8",{fatal:!0}).decode(e),catch:(n)=>new G("invalid_transport_line",`Invalid UTF-8 in ${t}.`,{},{cause:n})}))}function Ti(e){return nr(e.replace(/Bearer\s+[^\s]+/giu,"Bearer [redacted]").replace(/((?:api[_-]?key|authorization|cookie|password|secret|token)\s*[:=]\s*)[^\s,;]+/giu,"$1[redacted]"),512)}function Uc(e){return e.split(/\r?\n/u).map((t)=>Ti(t)).filter((t)=>t.length>0).slice(0,128)}class zf{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(!$N(e.executablePath))throw new G("discovery_failed","The Codex executable path must be absolute.");if(this.maxLineBytes=e.maxLineBytes??kc,this.maxDiagnosticBytes=e.maxDiagnosticBytes??mg,this.maxLineBytes<1||this.maxDiagnosticBytes<1)throw new G("invalid_external_data","The transport bounds are invalid.");if(this.process=Bun.spawn([e.executablePath,"app-server"],{...e.cwd===void 0?{}:{cwd:e.cwd},env:Ri(e.environment),stdin:"pipe",stdout:"pipe",stderr:"pipe"}),!(this.process.stdout instanceof ReadableStream)||!(this.process.stderr instanceof ReadableStream))throw new G("transport_failure","The Codex App Server did not expose stdio pipes.");if(typeof this.process.stdin==="number"||this.process.stdin===void 0)throw new G("transport_failure","The Codex App Server did not expose stdin.");if(this.stdin=this.process.stdin,this.stdoutReader=this.process.stdout,this.stderrStream=this.process.stderr,this.stderrFiber=da(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 O(null);return b({self:this},function*(){let e=yield*U({try:()=>this.stdoutReader.getReader(),catch:(n)=>new G("transport_failure","The App Server stdout could not be read.",{},{cause:n})}),t=b({self:this},function*(){while(!0){let n=this.stdoutBuffer.indexOf(10);if(n>=0){if(n>this.maxLineBytes)return yield*Qe(p({try:()=>this.close(),catch:()=>{return}})),yield*m(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*yC(a,this.lineDecoder)}if(this.stdoutBuffer.byteLength>this.maxLineBytes)return yield*Qe(p({try:()=>this.close(),catch:()=>{return}})),yield*m(new G("invalid_transport_line","The App Server emitted an overlong line."));let r=yield*p({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*Qe(p({try:()=>this.close(),catch:()=>{return}})),yield*m(new G("invalid_transport_line","The App Server emitted an overlong line."));let o=this.stdoutBuffer;return this.stdoutBuffer=new Uint8Array(0),yield*yC(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*so(t,dt(()=>e.releaseLock()))})}writeLine(e){return A(this.writeLineEffect(e))}writeLineEffect(e){if(this.closed)return m(new G("closed","The App Server transport is closed."));if(new TextEncoder().encode(e).byteLength>this.maxLineBytes)return m(new G("invalid_transport_line","The App Server request exceeded the line limit."));return b({self:this},function*(){yield*p({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*p({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=Le(Js(this.closeTransportEffect()))}return A(this.closeEffect)}closeTransportEffect(){return b({self:this},function*(){yield*Qe(p({try:()=>Promise.resolve(this.stdin.end()),catch:()=>{return}})),yield*Qe(U({try:()=>this.process.kill(),catch:()=>{return}})),yield*Lb(Qe(p({try:()=>this.process.exited,catch:()=>{return}})),Ws(1000)),yield*Qe(hC(this.stderrFiber))})}collectStderrEffect(){return b({self:this},function*(){let e=yield*ao(SC(this.stderrStream,this.maxDiagnosticBytes));if(Lm(e)){this.stderrDiagnostics.push("[stderr unavailable]");return}let t=yield*U({try:()=>qf(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=Ti(n);if(r.length>0)this.stderrDiagnostics.push(r)}}).pipe(Db)}}function yC(e,t){return U({try:()=>t.decode(e),catch:(n)=>new G("invalid_transport_line","The App Server emitted invalid UTF-8.",{},{cause:n})})}var Wf=L(()=>{Fe();ua();gC();_r()});import{spawn as jN}from"child_process";import{lstat as Qr,mkdir as BN,mkdtemp as VN,readFile as qN,readdir as zN,realpath as iy,rename as WN,rm as HN,stat as cH}from"fs/promises";import{dirname as EC,isAbsolute as ly,join as wr,relative as vC,resolve as Jf,sep as bC}from"path";function r0(e){return b(function*(){let t=CC(e.selectedPluginIds);if(t.length===0)return;if(yield*RC(e.timeoutMs,e.pollIntervalMs),e.signal?.aborted)return yield*m(new ue("cancelled","Official Codex marketplace bootstrap was cancelled."));let n=yield*e.readSnapshot===void 0?Gf(wr(e.codexHome,...jc),e.codexHome,t):p({try:()=>e.readSnapshot(e.codexHome),catch:(a)=>a});if(n!==void 0&&Yf(n,t))return n;let r=e.initializeRuntime===void 0?p0(e):p({try:()=>e.initializeRuntime(),catch:(a)=>a}),i,o=yield*r.pipe(me((a)=>({closeRuntime:a})),ge(()=>!0,(a)=>O({error:a})));if("error"in o)i=re("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=b(function*(){let c=e.timeoutMs??fy,u=e.pollIntervalMs??KN,l=Date.now();while(Date.now()-l<=c){if(e.signal?.aborted)return yield*m(new ue("cancelled","Official Codex marketplace bootstrap was cancelled."));let f=yield*e.readSnapshot===void 0?Gf(wr(e.codexHome,...jc),e.codexHome,t):p({try:()=>e.readSnapshot(e.codexHome),catch:(y)=>y});if(f!==void 0&&Yf(f,t))return f;let h=c-(Date.now()-l);if(h<=0)break;let g=Math.min(u,h);yield*e.sleep===void 0?Ws(g):p({try:()=>e.sleep(g),catch:(y)=>y})}return yield*m(re("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*Wr(O(o.closeRuntime),()=>a.pipe(me((c)=>({snapshot:c})),ge(()=>!0,(c)=>O({error:c}))),(c)=>p({try:()=>c(),catch:()=>{return}}));if("snapshot"in s)return s.snapshot;if(s.error instanceof ue&&s.error.code==="cancelled")return yield*m(s.error);i=s.error instanceof ue?s.error:re("marketplace_unavailable","The official marketplace sync failed before its bounded wait completed.",s.error)}if(e.gitFallback!==!1)return yield*p({try:()=>_C({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(wt((a)=>a instanceof ue?a:re("marketplace_unavailable",`The official marketplace could not be populated after runtime startup (${i?.code??"unavailable"}). Check network access and retry.`,a)));return yield*m(i??re("marketplace_timeout","The official Codex marketplace did not become ready before the bounded wait expired."))})}function _C(e){return A(i0(e))}function i0(e){return b(function*(){let t=CC(e.selectedPluginIds);if(t.length===0)return yield*m(re("marketplace_invalid","The official marketplace fallback requires at least one selected provider plugin."));if(yield*RC(e.timeoutMs,void 0),!ly(e.codexHome))return yield*m(re("marketplace_invalid","The Codex home for official marketplace fallback must be absolute."));if(e.signal?.aborted)return yield*m(new ue("cancelled","Official Codex marketplace fallback was cancelled."));let n=Ri(e.environment),r=e.gitRunner??IC("git",{environment:n,...e.timeoutMs===void 0?{}:{timeoutMs:e.timeoutMs}}),i=e.timeoutMs??fy,o=yield*s0(r,i,e.signal).pipe(wt((l)=>l instanceof ue?l:re("marketplace_unavailable","The official Codex marketplace remote HEAD could not be resolved. Check network access and retry.",l))),a=wr(e.codexHome,"plugins"),s=wr(a,jc[1]);if(yield*l0(a,e.codexHome),(yield*ge(p({try:()=>Qr(s),catch:(l)=>l}),Fa,()=>O(void 0)).pipe(wt((l)=>re("marketplace_invalid","The reserved official marketplace path could not be inspected safely.",l))))!==void 0)return yield*m(re("marketplace_invalid","The reserved official marketplace path appeared during bootstrap; refusing to overwrite it."));let u=yield*p({try:()=>VN(wr(a,".openai-plugins-stage-")),catch:(l)=>l});return yield*Wr(O(u),(l)=>b(function*(){if(yield*ay(e.codexHome,l),e.cloneSnapshot!==void 0)yield*p({try:()=>e.cloneSnapshot(Ii,l),catch:(v)=>v}).pipe(wt((v)=>h0(v)?re("marketplace_invalid","The staged official marketplace could not be created as a safe file tree.",v):v));else{let v=yield*p({try:()=>r.run(["-c","core.longpaths=true","clone","--depth=1","--no-tags",Ii,l],{...e.signal===void 0?{}:{signal:e.signal},timeoutMs:i}),catch:(d)=>d});if(v.exitCode!==0)return yield*m(re("marketplace_unavailable","The official Codex marketplace could not be downloaded. Check network access and retry.",v.stderr))}yield*Kf(l);let f=yield*Gf(l,e.codexHome,t);if(f===void 0||!Yf(f,t))return yield*m(re("marketplace_invalid","The downloaded official marketplace is missing the selected plugin entries or manifest."));if((yield*c0(r,l,i,e.signal))!==o)return yield*m(re("marketplace_invalid","The downloaded official marketplace did not match the verified remote HEAD."));if((yield*ge(p({try:()=>Qr(s),catch:(v)=>v}),Fa,()=>O(void 0)).pipe(wt((v)=>re("marketplace_invalid","The reserved official marketplace path could not be checked before publication.",v))))!==void 0)return yield*m(re("marketplace_invalid","The reserved official marketplace path appeared during staging; refusing to overwrite it."));yield*o0(l,s,e.renameSnapshot??WN);let y=yield*Gf(wr(e.codexHome,...jc),e.codexHome,t);if(y===void 0||!Yf(y,t))return yield*m(re("marketplace_invalid","The published official marketplace failed validation."));return y}).pipe(wt((f)=>f instanceof ue?f:re("marketplace_unavailable","The official Codex marketplace fallback failed safely. Check network access and retry.",f))),(l)=>p({try:()=>HN(l,{recursive:!0,force:!0}),catch:()=>{return}}))})}function o0(e,t,n){return b(function*(){for(let r=0;;r+=1){let i=yield*p({try:()=>n(e,t),catch:(c)=>c}).pipe(me(()=>({ok:!0})),ge(()=>!0,(c)=>O({ok:!1,error:c})));if(i.ok)return;let o=i.error,a=GN[r];if(process.platform!=="win32"||a===void 0||!a0(o))return yield*m(o);if((yield*ge(p({try:()=>Qr(t),catch:(c)=>c}),Fa,()=>O(void 0)).pipe(wt((c)=>re("marketplace_invalid","The reserved official marketplace path could not be checked before retrying publication.",c))))!==void 0)return yield*m(re("marketplace_invalid","The reserved official marketplace path appeared during publication; refusing to overwrite it."));yield*Ws(a)}})}function a0(e){return e!==null&&typeof e==="object"&&"code"in e&&(e.code==="EPERM"||e.code==="EBUSY")}function s0(e,t,n){return b(function*(){let r=yield*p({try:()=>e.run(["ls-remote",Ii,"HEAD"],{...n===void 0?{}:{signal:n},timeoutMs:t}),catch:(a)=>a});if(r.exitCode!==0)return yield*m(re("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*m(re("marketplace_invalid","The official Codex marketplace remote HEAD response was malformed."));return o[1].toLowerCase()})}function c0(e,t,n,r){return b(function*(){let i=yield*p({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*m(re("marketplace_invalid","The downloaded official marketplace checkout did not expose a valid HEAD.",i.stderr));return o})}function l0(e,t){return b(function*(){yield*oy(t,e),yield*p({try:()=>BN(e,{recursive:!0}),catch:(n)=>n}),yield*oy(t,e)})}function oy(e,t){return b(function*(){let n=Jf(e),r=Jf(t);while(!0){if((yield*ge(p({try:()=>Qr(r),catch:(a)=>a}),Fa,()=>O(void 0)))?.isSymbolicLink())return yield*m(re("marketplace_invalid","The official marketplace path cannot contain symlinks."));if(r===n)return;let o=EC(r);if(o===r||o!==n&&!u0(n,o))return yield*m(re("marketplace_invalid","The official marketplace path escaped CODEX_HOME."));r=o}})}function u0(e,t){let n=vC(e,t);return n.length>0&&n!==".."&&!n.startsWith(`..${bC}`)&&!ly(n)}function Kf(e){return b(function*(){let t=yield*p({try:()=>Qr(e),catch:(r)=>r});if(t.isSymbolicLink())return yield*m(re("marketplace_invalid","The official marketplace snapshot cannot contain symlinks."));if(!t.isDirectory())return yield*m(re("marketplace_invalid","The official marketplace snapshot is not a directory."));let n=yield*p({try:()=>zN(e,{withFileTypes:!0}),catch:(r)=>r});for(let r of n){let i=wr(e,r.name),o=yield*p({try:()=>Qr(i),catch:(a)=>a});if(o.isSymbolicLink())return yield*m(re("marketplace_invalid","The official marketplace snapshot cannot contain symlinks."));if(o.isDirectory())yield*Kf(i)}})}function Gf(e,t,n=[]){return b(function*(){if(t!==void 0)yield*oy(t,e);let r=yield*ge(p({try:()=>Qr(e),catch:(u)=>u}),Fa,()=>O(void 0)).pipe(wt((u)=>re("marketplace_invalid","The reserved openai-curated marketplace path could not be read safely.",u)));if(r===void 0)return;if(r.isSymbolicLink()||!r.isDirectory())return yield*m(re("marketplace_invalid","The reserved openai-curated marketplace path is not a real directory."));if(t!==void 0)yield*ay(t,e);else yield*Kf(e);if(t!==void 0)yield*Kf(e);let i=yield*p({try:()=>iy(e),catch:(u)=>u}),o=[wr(i,".agents","plugins","marketplace.json"),wr(i,".codex-plugin","marketplace.json"),wr(i,"marketplace.json")],a,s;for(let u of o){let l=yield*ge(p({try:()=>Qr(u),catch:(h)=>h}),Fa,()=>O(void 0)).pipe(wt((h)=>re("marketplace_invalid","The official marketplace manifest could not be read safely.",h)));if(l===void 0)continue;if(l.isSymbolicLink()||!l.isFile())return yield*m(re("marketplace_invalid","The official marketplace manifest is not a regular file."));if(yield*ay(i,u),a!==void 0)return yield*m(re("marketplace_invalid","The reserved official marketplace contains more than one manifest."));a=u;let f=yield*p({try:()=>qN(u),catch:(h)=>h});s=yield*U({try:()=>new TextDecoder("utf-8",{fatal:!0}).decode(f),catch:(h)=>re("marketplace_invalid","The official marketplace manifest is not valid UTF-8.",h)})}if(a===void 0||s===void 0)return;let c=yield*U({try:()=>JSON.parse(s),catch:(u)=>re("marketplace_invalid","The official marketplace manifest is not valid JSON.",u)});return yield*U({try:()=>wC(c,i,a,n),catch:(u)=>u})})}function wC(e,t=`${jc.join("/")}`,n=`${t}/marketplace.json`,r=[]){let i=Me(ZN)(e);if(Be(i))throw re("marketplace_invalid","The reserved official marketplace manifest is malformed or has an unexpected name.");let o=i.success;if(!f0(o))throw re("marketplace_invalid","The reserved official marketplace source is not the approved OpenAI repository.");if(o.plugins.length===0)throw re("marketplace_invalid","The official marketplace manifest has no plugin entries.");let a=[],s=new Set;for(let c of o.plugins){let u=Me(e0)(c);if(Be(u)){if(r.length>0)continue;throw re("marketplace_invalid","The official marketplace contains a malformed plugin entry.")}let l=u.success,f=l.name;if(s.has(f)){if(r.length>0&&!r.includes(f))continue;throw re("marketplace_invalid","The official marketplace contains a duplicate plugin name.")}if(s.add(f),r.length>0&&!r.includes(f))continue;let h=d0(l),g=h===void 0?void 0:Me(XN)(h);if(g===void 0||Be(g))throw re("marketplace_invalid",`The official marketplace source for ${f} is unsafe.`);a.push({name:f,source:g.success})}if(r.some((c)=>!a.some((u)=>u.name===c)))throw re("marketplace_invalid","The official marketplace is missing a selected plugin entry.");return{name:Vc,source:Ii,rootPath:t,manifestPath:n,plugins:a}}function f0(e){return[e.source,e.repository,e.repo,e.url].every((t)=>t===void 0||Ke(Me(YN)(t)))}function d0(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 CC(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!==Vc&&o!=="openai-curated-remote")continue;let a=r.slice(0,i);if(Be(Me(Zf)(a)))throw re("marketplace_invalid","A selected official marketplace plugin id is invalid.");if(!TC(a))continue;if(!n.has(a))n.add(a),t.push(a)}return t}function Yf(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 p0(e){return b(function*(){let t=Ri(e.environment),n=new zf({executablePath:e.executablePath,environment:t,...e.signal===void 0?{}:{signal:e.signal}}),r=new Vf(n,{requestTimeoutMs:Math.min(e.timeoutMs??fy,1e4),...e.signal===void 0?{}:{signal:e.signal}});return yield*p({try:()=>r.initialize(),catch:(i)=>i}).pipe(Hs(()=>p({try:()=>n.close(),catch:(i)=>i}).pipe(Qe))),()=>m0(r)})}function m0(e){return A(p({try:()=>e.close(),catch:(t)=>t}).pipe(Qe))}function RC(e,t){if(e!==void 0&&(!Number.isSafeInteger(e)||e<1||e>300000))return m(re("marketplace_invalid","The official marketplace timeout is invalid."));if(t!==void 0&&(!Number.isSafeInteger(t)||t<0||t>60000))return m(re("marketplace_invalid","The official marketplace poll interval is invalid."));return pt}function ay(e,t){return b(function*(){let n=yield*p({try:()=>iy(e),catch:(s)=>s}),r=yield*p({try:()=>iy(t),catch:(s)=>s}),i=vC(n,r);if(i===""||i===".."||i.startsWith(`..${bC}`))return yield*m(re("marketplace_invalid","The reserved official marketplace is outside CODEX_HOME."));let o=Jf(e),a=Jf(t);while(!0){if((yield*p({try:()=>Qr(a),catch:(u)=>u})).isSymbolicLink())return yield*m(re("marketplace_invalid","The reserved official marketplace path cannot contain symlinks."));if(a===o)break;let c=EC(a);if(c===a)throw re("marketplace_invalid","The reserved official marketplace path is outside CODEX_HOME.");a=c}})}function Fa(e){return typeof e==="object"&&e!==null&&"code"in e&&e.code==="ENOENT"}function h0(e){return typeof e==="object"&&e!==null&&"code"in e&&(e.code==="EPERM"||e.code==="EACCES")}function re(e,t,n){return new ue(e,t,n instanceof Error?{cause:Ti(n.message)}:{})}function Cr(e,t){let n=Mn(t);if(n===void 0||n!==t)return;let i=[...e.installed,...e.available].flatMap((o)=>{let a=$h(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 TC(e){return Cf.includes(e)}function kC(e){if(!Pc(cy,e))return fC(He("live official plugin list",e));return dC(Vt(cy,e,"live official plugin list"))}function Xf(e){let t=e.runner??IC(e.executable,{environment:e.environment??Ri(),...e.timeoutMs===void 0?{}:{timeoutMs:e.timeoutMs},...e.stdoutLimit===void 0?{}:{stdoutLimit:e.stdoutLimit},...e.stderrLimit===void 0?{}:{stderrLimit:e.stderrLimit}}),n=b(function*(){let o=yield*p({try:()=>t.run(["plugin","list","--json"]),catch:(c)=>c});if(o.exitCode!==0)return yield*m(ki("list",o));let a=yield*U({try:()=>JSON.parse(o.stdout),catch:()=>new ue("command_failed","Codex returned invalid plugin data.")}),s=kC(a);if(!s.ok)return yield*m(new ue("command_failed","Codex returned an invalid official plugin list."));return s.value}),r=()=>A(n),i=b(function*(){let o=yield*p({try:()=>t.run(["plugin","marketplace","list","--json"]),catch:(c)=>c});if(o.exitCode!==0)return yield*m(ki("marketplace list",o));let a=yield*U({try:()=>JSON.parse(o.stdout),catch:()=>new ue("command_failed","Codex returned invalid marketplace data.")}),s=Me(x0)(a);if(Be(s))return yield*m(new ue("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(b(function*(){if(e.codexHome===void 0)return yield*m(new ue("marketplace_unavailable","Codex home is unavailable; the official marketplace cannot be bootstrapped safely."));yield*r0({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(b(function*(){let s=Vt(vo,o,"plugin marketplace source");if(s===Vc||s===Ii)return yield*m(new ue("marketplace_invalid","The reserved openai-curated marketplace must be populated by Codex runtime startup; it cannot be added manually."));if(s!==uy)return yield*m(new ue("marketplace_invalid",`Unsupported managed marketplace source: ${s}.`));let c,u=!1,l=yield*i.pipe(me((C)=>({value:C})),ge(v0,(C)=>O({error:C})));if("error"in l){e.onMarketplaceConflict?.("The registered HolyCodex marketplace cache is incomplete; Codex will rebuild it from the canonical source.");let C=yield*p({try:()=>t.run(["plugin","marketplace","add",s],a===void 0?void 0:{signal:a}),catch:(T)=>T});if(C.exitCode!==0)return yield*m(ki("marketplace add",C,s));c=yield*i,u=!0}else c=l.value;let f=ry(c,Xr),h=b0(c,Xr);if(f!==void 0&&h.length>0){e.onMarketplaceConflict?.(`${f} HolyCodex will remove the conflicting registration and restore its required source.`);for(let C of h){let T=yield*p({try:()=>t.run(["plugin","marketplace","remove",C],a===void 0?void 0:{signal:a}),catch:(F)=>F});if(T.exitCode!==0)return yield*m(ki("marketplace remove",T,C))}}let g=h.length===0?c:yield*i,y=ry(g,Xr);if(y!==void 0)return yield*m(new ue("marketplace_invalid",y));if(g.find((C)=>C.name===Xr)===void 0){let C=yield*p({try:()=>t.run(["plugin","marketplace","add",s],a===void 0?void 0:{signal:a}),catch:(T)=>T});if(C.exitCode!==0)return yield*m(ki("marketplace add",C,s))}else if(!u){let C=yield*p({try:()=>t.run(["plugin","marketplace","upgrade",Xr],a===void 0?void 0:{signal:a}),catch:(T)=>T});if(C.exitCode!==0)return yield*m(ki("marketplace upgrade",C,Xr))}let d=yield*i,x=ry(d,Xr);if(x!==void 0)return yield*m(new ue("marketplace_invalid",x));let S=d.find((C)=>C.name===Xr);if(S===void 0||!Bc(S.marketplaceSource))return yield*m(new ue("readback_mismatch","Codex did not report the canonical HolyCodex marketplace after installation or refresh."))})),add:(o,a)=>A(b(function*(){let s=yield*U({try:()=>Vt(vo,o,"official plugin id"),catch:(d)=>d}),c=Pa(s),u=Mn(s)==="computer-use@openai-bundled"?c:c.includes(s)?[s,...c.filter((d)=>d!==s)]:[s],l=!1;for(let[d,x]of u.entries()){let S=yield*p({try:()=>t.run(["plugin","add",x,"--json"],a===void 0?void 0:{signal:a}),catch:(C)=>C});if(S.exitCode===0){l=!0;break}if(d<u.length-1&&E0(S.stderr))continue;return yield*m(ki("add",S,x))}if(!l)return yield*m(new ue("command_failed",`Codex could not install ${s} from its recognized marketplace sources.`));let f=yield*n,h=Cr(f,s),g=Mn(s),y=[...f.installed,...f.available].filter((d)=>d.pluginId===s&&(g===void 0||d.marketplaceName==null)),v=h?.entry??y.find((d)=>d.installed)??y[0];if(!v)return yield*m(new ue("readback_mismatch",`Codex did not report ${s} after installation.`,{plugin_id:s}));if(!v.installed)return yield*m(new ue("plugin_missing",`Codex reported ${s} as unavailable after installation.`,{plugin_id:s}));if(!v.enabled)return yield*m(new ue("plugin_disabled",`Codex installed ${s} but it is disabled; enable it in Codex and retry.`,{plugin_id:s}))})),remove:(o,a)=>A(b(function*(){let s=yield*U({try:()=>Vt(vo,o,"official plugin id"),catch:(h)=>h}),c=s;if(Mn(s)===s){let h=yield*n,g=Cr(h,s);if(g?.entry.installed)c=g.entry.pluginId}let u=yield*p({try:()=>t.run(["plugin","remove",c,"--json"],a===void 0?void 0:{signal:a}),catch:(h)=>h});if(u.exitCode!==0&&!/not (?:installed|found)|missing/iu.test(u.stderr))return yield*m(ki("remove",u,c));let l=yield*n,f=[...l.installed,...l.available].find((h)=>h.pluginId===c);if(f?.installed)return yield*m(new ue("readback_mismatch",`Codex still reports ${s} after removal.`,{plugin_id:s,observed_plugin_id:f.pluginId}))}))}}function ki(e,t,n){let r=Ti(t.stderr).trim().slice(0,512),i=r.length>0?`: ${r}`:"";return new ue("command_failed",`Codex plugin ${e} failed${n===void 0?"":` for ${n}`}${i}`,{exit_code:t.exitCode})}function E0(e){return/plugin\b.+\bnot found in marketplace\b/iu.test(Ti(e))}function v0(e){if(!(e instanceof ue)||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]===Xr}function ry(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&&!Bc(n[0].marketplaceSource)){let i=n[0].marketplaceSource?.source??"an unknown source";return`Codex marketplace ${t} points to ${i}, not the canonical HolyCodex source ${uy}; resolve the conflict before installing.`}let r=e.find((i)=>i.name!==t&&Bc(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 b0(e,t){let r=e.filter((i)=>i.name===t).length>1;return[...new Set(e.filter((i)=>i.name===t&&(r||!Bc(i.marketplaceSource))||i.name!==t&&Bc(i.marketplaceSource)).map((i)=>i.name))]}function Bc(e){if(e?.sourceType!=="git")return!1;return Qf(e.source)}function Qf(e){return JN.some((t)=>t===e)}function IC(e,t){let n=t.timeoutMs??30000,r=t.stdoutLimit??131072,i=t.stderrLimit??16384;return{run:(o,a)=>_0(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 _0(e,t,n){return A(w0(e,t,n))}function w0(e,t,n){return b(function*(){if(n.signal?.aborted)return yield*m(new ue("cancelled","The Codex plugin command was cancelled."));let r=jN(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=yi((l)=>{r.once("error",()=>l(m(new ue("command_failed","The Codex plugin command failed.")))),r.once("close",(f)=>l(O(f??-1)))}),o=n.signal===void 0?Ob:yi((l)=>{let f=()=>l(m(new ue("cancelled","The Codex plugin command was cancelled.")));return n.signal.addEventListener("abort",f,{once:!0}),dt(()=>n.signal.removeEventListener("abort",f))}),a=Pn([xC(r.stdout,n.stdoutLimit),xC(r.stderr,n.stderrLimit),i],{concurrency:"unbounded"}).pipe(ju(n.timeoutMs),wt((l)=>l instanceof ue?l:l!==null&&typeof l==="object"&&("_tag"in l)&&l._tag==="TimeoutError"?new ue("timeout","The Codex plugin command timed out."):new ue("command_failed","The Codex plugin command failed."))),[s,c,u]=yield*Fb(a,o).pipe(Hs(()=>dt(()=>r.kill())));return{stdout:s,stderr:c,exitCode:u}})}function xC(e,t){if(e===null)return m(new ue("command_failed","Codex plugin command output is unavailable."));return yi((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(m(new ue("command_failed","Codex plugin output was invalid.")));return}if(i+=a.byteLength,i>t){n(m(new ue("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(U({try:()=>new TextDecoder("utf-8",{fatal:!0}).decode(o),catch:()=>new ue("command_failed","Codex plugin output was not valid UTF-8.")}))}),e.once("error",()=>n(m(new ue("command_failed","Codex plugin output could not be read."))))})}var Vc="openai-curated",Ii="https://github.com/openai/plugins.git",Xr="holycodex",uy="davidbasilefilho/holycodex",JN,jc,fy=30000,KN=100,GN,Zf,Hf,YN,ZN,XN,QN,e0,t0,$c,vo,n0,g0,sy,cy,y0,S0,x0,ue;var ed=L(()=>{ht();Fe();It();Ue();Eg();_r();Wf();JN=[uy,"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"],jc=["plugins","openai-plugins"],GN=[25,50,100,200],Zf=_.check(ce(/^[a-z][a-z0-9._-]{1,63}$/u)),Hf=H([_,ye(E({url:_}),[Pe(_,Ge)])]),YN=H([R([Ii]),ye(E({url:R([Ii])}),[Pe(_,Ge)])]),ZN=ye(E({name:R([Vc]),plugins:M(Ge),source:w(Hf),repository:w(Hf),repo:w(Hf),url:w(Hf)}),[Pe(_,Ge)]),XN=_.check(ee((e)=>{if(e.length===0||ly(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!=="..")})),QN=H([_,ye(E({path:w(_)}),[Pe(_,Ge)])]),e0=ye(E({name:Zf,source:w(QN),path:w(_)}),[Pe(_,Ge)]),t0=_.check(ce(/^[0-9]+\.[0-9]+\.[0-9]+(?:[-+][A-Za-z0-9.-]+)?$/u)),$c=M(_),vo=_.check(ce(/^[A-Za-z0-9][A-Za-z0-9._:@/-]{0,255}$/u)),n0=E({name:Zf,version:t0,description:Yr,author:w(Rt),license:w(Yr),homepage:w(Yr),repository:w(Yr),keywords:w($c),skills:w($c),commands:w($c),hooks:w($c),assets:w($c),official:w(N)});g0=E({id:Zf,selected:R([!0])}),sy=ye(E({pluginId:vo,installed:N,enabled:N,name:w(H([_,_e])),marketplaceName:w(H([_,_e])),version:w(H([_,_e]))}),[Pe(_,Ge)]),cy=E({installed:M(sy),available:M(sy)});y0=ye(E({sourceType:_,source:_}),[Pe(_,Ge)]),S0=ye(E({name:_,root:_,marketplaceSource:w(y0)}),[Pe(_,Ge)]),x0=ye(E({marketplaces:M(S0)}),[Pe(_,Ge)]);ue=class ue extends Error{code;details;constructor(e,t,n={}){super(t);this.name="OfficialPluginAdapterError",this.code=e,this.details=n}}});function AC(e){return le(OC)(e)}function Rr(e){return le(Pi)(e)}function py(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('"')?C0(s):s,u=s.startsWith('"'),l=u&&t.length===1&&t[0]==="plugins"&&le(vo)(c),f=u&&t.length===1&&t[0]==="agents"&&dy.includes(c);if(u?!l&&!f:!/^[A-Za-z][A-Za-z0-9_-]*$/u.test(c)&&!dy.includes(c))throw He("TOML key path",e);if(c==="__proto__"||(c==="constructor"||c==="prototype")&&!l)throw He("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 He("TOML key path",e);return t}function C0(e){let t=Me(_f(_))(e);if(Ke(t))return t.success;throw He("TOML quoted key",e)}function fe(e,t){if(!Rr(e))throw He("TOML document",e);let n=e,r=py(t);for(let i=0;i<r.length;i+=1){let o=r[i];if(!Rr(n)||!Object.prototype.hasOwnProperty.call(n,o))return;if(n=n[o],i===1&&r[0]==="features"&&typeof n==="boolean"){if(o==="context_management"&&r[2]==="experimental_mode")return n;if(o==="multi_agent_v2"&&r[2]==="enabled")return n}}return n}function td(e){if(Array.isArray(e))return e.map(td);if(Ic(e))return Object.fromEntries(Object.entries(e).map(([t,n])=>[t,td(n)]));return e}function nd(e){return td(e)}function Tr(e,t,n){if(!Rr(e)||!AC(n))throw He("TOML write",{keyPath:t});let r=py(t),i={...nd(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&&!Rr(s)){if(typeof s!=="boolean"||o!==i.features||!["context_management","multi_agent_v2"].includes(a))throw He("TOML table path",t);if((a==="context_management"&&r.at(-1)==="experimental_mode"||a==="multi_agent_v2"&&r.at(-1)==="enabled")&&s===n)return i;o[a]=a==="context_management"?{experimental_mode:s}:{enabled:s}}let c=s===void 0?{}:Rr(o[a])?{...o[a]}:{};o[a]=c,o=c}return o[r.at(-1)]=td(n),i}function Cn(e,t){if(!Rr(e))throw He("TOML document",e);let n=py(t),r={...nd(e)},i=[],o=r;for(let s of n.slice(0,-1)){let c=o[s];if(!Rr(c))return r;let u={...c};i.push({table:o,key:s}),o[s]=u,o=u}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],u=c.table[c.key];if(Rr(u)&&Object.keys(u).length===0)delete c.table[c.key];else break}return r}function zc(e){return le(my)(e)}function R0(e){if(NC.includes(e))return!0;if(/^agents\.(?:explorer|librarian|worker|reviewer)\.config_file$/u.test(e))return!0;return dy.some((t)=>e===`agents."${t}".config_file`)}function MC(e){return le(hy)(e)}function qc(e){return le(Ua)(e)}function UC(e){return le(DC)(e)}function $C(e){return le(LC)(e)}function Sy(e,t){let n=new Set(t);return Object.keys(e).every((r)=>n.has(r))}function PC(e,t){switch(vy(e)){case"number":return t.kind==="number";case"boolean":return t.kind==="boolean";case"relative_path":return t.kind==="relative_path";case"absolute_path":return t.kind==="absolute_path"&&le(FC)(t.value);case"digest":return t.kind==="digest";case"string_array":return t.kind==="string_array"&&le(id)(t.value);case"text":return t.kind==="text"&&le(rd)(t.value);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==="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==="default_permissions")return t.value===":danger-full-access"||t.value===":workspace"||t.value===":read-only"||t.value==="holycodex";if(e==="permissions.holycodex.extends")return t.value===":workspace"||t.value===":read-only"||qc(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 bo(e){return le(Wc)(e)}function ad(e){if(!qc(e.schema)||!qc(e.installId))throw He("managed runtime config metadata",{schema:e.schema});return{owner:"holycodex",schema:e.schema,installId:e.installId,managed:{}}}function sd(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 xy(e){return e.length>0&&e.length<=1024&&!e.includes("\x00")&&/^(?:[A-Za-z]:[\\/]|\\\\|\/)/u.test(e)}function Ey(e){if(!sd(e))throw He("relative config path","[redacted]");return e.replaceAll("\\","/").split("/").filter((t)=>t!==".").join("/")}function _o(e,t){let n=Ey(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 vy(e){if(e==="developer_instructions")return"digest";if(e==="model_catalog_json")return"absolute_path";if(e.endsWith(".config_file"))return"relative_path";if(e==="agents.max_concurrent_threads_per_session"||e==="agents.max_depth")return"number";if(e==="permissions.holycodex.extends")return"enum";if(e==="features.multi_agent_v2.usage_hint_text")return"text";if(e==="features.code_mode.direct_only_tool_namespaces")return"string_array";if(e==="model_auto_compact_token_limit")return"number";if(e==="suppress_unstable_features_warning"||e==="include_collaboration_mode_instructions"||e==="tools.experimental_request_user_input.enabled"||e==="tools.update_plan.enabled"||e==="agents.enabled"||e==="features.multi_agent"||e==="features.default_mode_request_user_input"||e==="features.goals"||e==="features.image_generation"||e==="features.memories"||e==="features.request_permissions_tool"||e==="features.skill_search"||e==="features.sleep_tool"||e==="features.multi_agent_v2.enabled"||e==="features.agent_message_board"||e==="features.code_mode.enabled"||e==="features.context_management.experimental_mode"||e==="permissions.holycodex.network.enabled"||Oi.includes(e))return"boolean";return"enum"}function M0(e,t){let n=vy(e);if(n==="number")return $C(t);if(n==="boolean")return typeof t==="boolean";if(n==="string_array")return le(id)(t);if(n==="text")return le(rd)(t);if(n==="relative_path")return typeof t==="string"&&sd(t);if(n==="absolute_path")return typeof t==="string"&&xy(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"&&UC(t)}function ln(e,t){if(!MC(e)||!AC(t))return m(He("managed config value",{keyPath:e}));let n=vy(e);if(n==="number"&&$C(t))return O({kind:n,value:t});if(n==="boolean"&&typeof t==="boolean")return O({kind:n,value:t});if(n==="string_array"&&le(id)(t))return O({kind:n,value:t});if(n==="text"&&le(rd)(t))return O({kind:n,value:t});if(n==="relative_path"&&typeof t==="string"&&sd(t))return O({kind:n,value:Ey(t)});if(n==="absolute_path"&&typeof t==="string"&&xy(t))return O({kind:n,value:t});if(n==="enum"&&typeof t==="string"&&UC(t))return O({kind:n,value:t});return me(p({try:()=>wn("holycodex-managed-config-value",[_n({keyPath:e,value:t})]),catch:(r)=>He("managed config value digest",{keyPath:e},r)}),(r)=>({kind:"digest",value:r}))}function D0(e){if(e.kind==="enum"||e.kind==="text"||e.kind==="number"||e.kind==="boolean"||e.kind==="relative_path"||e.kind==="absolute_path")return e.value;if(e.kind==="string_array")return e.value;return}function Hc(e,t,n,r){return b(function*(){if(!Rr(e)||!bo(t)||!qc(r.schema)||!qc(r.installId))return yield*m(He("managed runtime config",{}));let i={...t.managed},o=nd(e),a=[];for(let[c,u]of Object.entries(n)){if(!zc(c)||typeof u!=="string"&&typeof u!=="number"&&typeof u!=="boolean"&&!Array.isArray(u))return yield*m(He("managed config key",c));let l=c,f=t.managed[l],h=fe(o,l);if(f&&(f.schema!==r.schema||f.installId!==r.installId)){a.push(l);continue}if(f&&f.owner==="holycodex"){let y=h===void 0?void 0:yield*ln(l,h);if(y===void 0||JSON.stringify(y)!==JSON.stringify(f.lastManagedValue)){a.push(l);continue}}let g=f?.originalValue??(h===void 0?{kind:"absent"}:yield*ln(l,h));if(!M0(l,u))return yield*m(He("managed config value",{keyPath:l}));o=Tr(o,l,u),i[l]={owner:"holycodex",schema:r.schema,installId:r.installId,keyPath:l,originalValue:g,lastManagedValue:yield*ln(l,u)}}let s={owner:"holycodex",schema:r.schema,installId:r.installId,managed:i};if(!bo(s))return yield*m(He("managed runtime config state",{}));return{document:o,state:s,driftedKeys:a}})}function $a(e,t,n){return A(Ai(e,t,n))}function Ai(e,t,n){return b(function*(){if(!Rr(e)||!bo(t))return yield*m(He("managed runtime config",{}));let r=nd(e),i={...t.managed},o=[],a=[],s=[];for(let[c,u]of Object.entries(t.managed)){if(!MC(c))return yield*m(He("managed config key",c));let l=c;if(u.owner!=="holycodex"||u.schema!==n.schema||u.installId!==n.installId){if(u.schema!==n.schema||u.installId!==n.installId)s.push(l);continue}let f=fe(r,l),h=f===void 0?void 0:yield*ln(l,f);if(!(h!==void 0&&JSON.stringify(h)===JSON.stringify(u.lastManagedValue))){a.push(l);continue}if(u.originalValue.kind==="absent")r=Cn(r,l),o.push(l),delete i[l];else{let y=D0(u.originalValue);if(y===void 0){s.push(l),a.push(l);continue}r=Tr(r,l,y),o.push(l),delete i[l]}}return{document:r,state:{...t,managed:i},restoredKeys:o,preservedKeys:a,unresolvedKeys:s}})}function cd(e,t,n){return A(Jc(e,t,n))}function Jc(e,t,n){return b(function*(){if(!zc(n)||!bo(t))return yield*m(He("managed config key",n));let r=t.managed[n],i=fe(e,n),o=i===void 0?void 0:yield*ln(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 dy,OC,Pi,NC,Oi,my,hy,T0,Ua,DC,LC,k0,I0,FC,rd,P0,id,O0,od,gy,A0,yy,N0,Wc;var ld=L(()=>{ht();ht();Fe();It();Ue();_r();ed();dy=[...Gr,"Reviewer.plan"],OC=sn,Pi=_i;NC=["model","model_catalog_json","model_reasoning_effort","service_tier","agents.enabled","agents.default.config_file","agents.worker.config_file","agents.explorer.config_file","agents.librarian.config_file","agents.reviewer.config_file","agents.max_concurrent_threads_per_session","agents.max_depth","web_search","approval_policy","approvals_reviewer","default_permissions","model_verbosity","developer_instructions","include_collaboration_mode_instructions","tools.experimental_request_user_input.enabled","tools.update_plan.enabled","suppress_unstable_features_warning","features.multi_agent","features.default_mode_request_user_input","features.goals","features.image_generation","features.memories","features.request_permissions_tool","features.skill_search","features.sleep_tool","features.multi_agent_v2.enabled","features.multi_agent_v2.usage_hint_text","features.agent_message_board","features.code_mode.enabled","features.code_mode.direct_only_tool_namespaces","features.context_management.experimental_mode"],Oi=["model_auto_compact_token_limit","features.context_management","features.multi_agent_v2","sandbox_workspace_write.network_access","permissions.holycodex.extends","permissions.holycodex.network.enabled"],my=_.check(ee(R0));hy=H([my,R(Oi)]);T0=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u,Ua=_.check(ce(T0)),DC=H([Ua,R([":workspace",":read-only",":danger-full-access"])]),LC=Ye.check(ee((e)=>Number.isSafeInteger(e)&&e>=0)),k0=_.check(ce(/^[a-f0-9]{64}$/u)),I0=_.check(ee(sd)),FC=_.check(ee(xy)),rd=_.check(ee((e)=>e.length>0&&e.length<=2000)),P0=_.check(ce(/^[A-Za-z0-9_-]{1,64}$/u)),id=M(P0),O0=H([E({kind:R(["enum"]),value:DC}),E({kind:R(["text"]),value:rd}),E({kind:R(["string_array"]),value:id}),E({kind:R(["number"]),value:LC}),E({kind:R(["boolean"]),value:N}),E({kind:R(["relative_path"]),value:I0}),E({kind:R(["absolute_path"]),value:FC}),E({kind:R(["digest"]),value:k0})]),od=O0.check(ee((e)=>Sy(e,["kind","value"]))),gy=H([od,E({kind:R(["absent"])})]),A0=E({owner:R(["holycodex"]),schema:Ua,installId:Ua,keyPath:hy,originalValue:gy,lastManagedValue:od}),yy=A0.check(ee((e)=>Sy(e,["owner","schema","installId","keyPath","originalValue","lastManagedValue"])&&PC(e.keyPath,e.lastManagedValue)&&(e.originalValue.kind==="absent"||PC(e.keyPath,e.originalValue)))),N0=E({owner:R(["holycodex"]),schema:Ua,installId:Ua,managed:Pe(_,yy)}),Wc=N0.check(ee((e)=>Sy(e,["owner","schema","installId","managed"])&&Object.entries(e.managed).every(([t,n])=>le(hy)(t)&&n.keyPath===t)))});function mC(e){if(Ac.some((t)=>t===e))return"permissions";if(Oc.some((t)=>t===e))return"approval";if(gg.some((t)=>t===e))return"elicitation";if(yg.some((t)=>t===e))return"dynamic_tool";return"other"}var jC,Tt,L0,wy,ja,BC,Nc,F0,vg,Mc,kr,U0,$0,VC,Dc,bg,_g,Kc,Lc,wg,Cg,Rg,Tg,kg,Ig,Pg,Fc,Og,Ag,Ng,qC,Mg,Dg,Lg,Fg,Ug,$g,jg,Bg,j0,B0,V0,Vg,qg,zg,Wg,by,_y,zC,Hg,Jg,Kg,Gg,Yg,Zg,Xg,Qg,Bf,wH,q0,CH;var ey=L(()=>{Ue();_r();jf();ld();jC=_.check(ce(/^[A-Za-z][A-Za-z0-9_./:-]{0,127}$/u)),Tt=[Pe(_,Rt)],L0=_.check(ce(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u)),wy=_.check(tt(1)),ja=H([_.check(tt(1)),Ye.check(ee((e)=>Number.isSafeInteger(e)))]),BC=E({code:Ye.check(ee((e)=>Number.isSafeInteger(e))),message:_,data:w(Rt)}),Nc=H([E({id:ja,result:Rt}),E({id:ja,error:BC})]),F0=E({id:ja,error:BC}),vg=E({method:jC,params:w(Rt)}),Mc=E({id:ja,method:jC,params:w(Rt),trace:w(Rt)}),kr=Ye.check(yo(),Ra(0)),U0=E({inputTokens:De(kr),cachedInputTokens:De(kr),outputTokens:De(kr),reasoningOutputTokens:De(kr),totalTokens:De(kr)}).check(ee((e)=>Object.values(e).some((t)=>t!==void 0))),$0=E({input_tokens:De(kr),cached_input_tokens:De(kr),output_tokens:De(kr),reasoning_output_tokens:De(kr),total_tokens:De(kr)}).check(ee((e)=>Object.values(e).some((t)=>t!==void 0))),VC=H([U0,$0]),Dc=E({clientInfo:E({name:Yr,version:Yr,title:H([Yr,_e])}),capabilities:H([E({experimentalApi:N,requestAttestation:N,mcpServerOpenaiFormElicitation:w(N),optOutNotificationMethods:w(H([M(_),_e])),extensions:w(rt)}),_e])}),bg=ye(E({userAgent:_,codexHome:_,platformFamily:_,platformOs:_,serverInfo:De(rt),capabilities:De(rt),protocolVersion:De(_)}),Tt),_g=E({method:R(["initialized"])}),Kc=ye(E({id:L0}),Tt),Lc=H([ye(E({thread:Kc,id:De(_)}),Tt),ye(E({id:_}),Tt)]),wg=Lc,Cg=Lc,Rg=ye(E({threadId:wy}),Tt),Tg=ye(E({status:R(["notLoaded","notSubscribed","unsubscribed"])}),Tt),kg=ye(E({thread:Kc}),Tt),Ig=rt.check(ee((e)=>Array.isArray(e.data)&&e.threads===void 0&&le(M(Kc))(e.data)||Array.isArray(e.threads)&&e.data===void 0&&le(M(Kc))(e.threads))),Pg=rt,Fc=ye(E({threadId:wy}),Tt),Og=Fc,Ag=Fc,Ng=rt,qC=ye(E({id:wy,status:De(_),usage:De(VC),error:De(Rt)}),Tt),Mg=rt.check(ee((e)=>typeof e.threadId==="string"&&e.threadId.length>0&&(Array.isArray(e.input)&&le(M(Rt))(e.input)||typeof e.prompt==="string"&&e.prompt.length>0))),Dg=rt.check(ee((e)=>typeof e.threadId==="string"&&e.threadId.length>0&&typeof e.expectedTurnId==="string"&&e.expectedTurnId.length>0&&Array.isArray(e.input)&&le(M(Rt))(e.input))),Lg=rt.check(ee((e)=>e.turn!==void 0&&le(qC)(e.turn)||typeof e.turnId==="string"&&e.turnId.length>0||typeof e.id==="string"&&e.id.length>0)),Fg=rt.check(ee((e)=>typeof e.turnId==="string"&&e.turnId.length>0)),Ug=rt.check(ee((e)=>typeof e.threadId==="string"&&e.threadId.length>0&&typeof e.turnId==="string"&&e.turnId.length>0)),$g=rt,jg=rt.check(ee((e)=>typeof e.threadId==="string"&&e.threadId.length>0&&(e.turn!==void 0&&le(qC)(e.turn)||typeof e.turnId==="string"&&e.turnId.length>0))),Bg=rt,j0=ye(E({reasoningEffort:_}),Tt),B0=ye(E({id:_}),Tt),V0=ye(E({id:_,model:_,supportedReasoningEfforts:De(M(j0)),serviceTiers:De(M(B0)),defaultServiceTier:De(H([_,_e])),multiAgentVersion:De(H([R(["disabled","v1","v2"]),_e]))}),Tt),Vg=ye(E({data:M(V0)}),Tt),qg=rt,zg=rt,Wg=E({supportsLunaReserve:w(N),excludeResetCreditDetails:w(N)}),by=E({usedPercent:Ye.check(yo(),Ra(0),vf(100)),windowDurationMins:H([Ye.check(yo(),So(0)),_e]),resetsAt:H([Ye.check(yo()),_e])}),_y=ye(E({primary:H([by,_e]),secondary:H([by,_e])}),Tt),zC=E({id:_.check(tt(1)),resetType:R(["codexRateLimits","unknown"]),status:R(["available","redeeming","redeemed","unknown"]),grantedAt:Ye.check(yo()),expiresAt:H([Ye.check(yo()),_e]),title:H([_,_e]),description:H([_,_e])}),Hg=ye(E({rateLimits:_y,rateLimitsByLimitId:H([Pe(_,_y),_e]),rateLimitResetCredits:H([ye(E({availableCount:Ye.check(Ta(),Ra(0)),credits:H([M(zC),_e])}),Tt),_e])}),Tt),Jg=E({idempotencyKey:_.check(tt(1)),creditId:w(H([_.check(tt(1)),_e]))}),Kg=E({outcome:R(["reset","nothingToReset","noCredit","alreadyRedeemed"])}),Gg=E({includeLayers:w(N),cwd:w(H([_,_e]))}),Yg=E({config:Pi,origins:rt,layers:H([M(rt),_e])}),Zg=rt,Xg=rt,Qg=ye(E({id:ja,method:_,params:rt,category:R(["approval","dynamic_tool","elicitation","other","permissions"])}),Tt),Bf=Rt,wH=ye(E({kind:R(["multi_agent","turn_completed","server_request","unknown"]),method:_,params:De(Rt),metadata:De(rt)}),Tt);q0=H([R(["stable","experimental","disabled"]),N]),CH=Pe(_,q0)});import{lstat as kH,mkdir as IH,readFile as z0,readdir as PH,realpath as W0,stat as H0}from"fs/promises";import{delimiter as J0,isAbsolute as AH,join as NH,relative as MH,resolve as WC}from"path";function G0(e){return b(function*(){let t=[];if(e.executablePath!==void 0)t.push(WC(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(J0).filter((o)=>o.length>0))for(let o of r)t.push(WC(i,o))}for(let n of t){let r=yield*ge(p({try:()=>H0(n),catch:(i)=>i}),()=>!0,(i)=>e.executablePath!==void 0?m(new G("discovery_failed","The explicit Codex executable was not found.",{path:n},{cause:i})):O(void 0));if(r===void 0)continue;if(!r.isFile())continue;if(process.platform!=="win32"&&(r.mode&73)===0)continue;return yield*p({try:()=>W0(n),catch:(i)=>new G("discovery_failed","The explicit Codex executable could not be resolved.",{path:n},{cause:i})})}return yield*m(new G("discovery_failed","No Codex executable was found on the allowlisted PATH."))})}function Y0(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 m(new G("discovery_failed","The Codex version command did not expose output pipes."));return b(function*(){let[r,i,o]=yield*X0(Pn([p({try:()=>ny(n.stdout,16384),catch:(s)=>s}),p({try:()=>ny(n.stderr,16384),catch:(s)=>s}),p({try:()=>n.exited,catch:(s)=>s})],{concurrency:"unbounded"}),()=>n.kill(),"The Codex version command timed out."),a=nr(qf(r,"Codex version output"));if(o!==0||a.length===0){let s=Ti(qf(i,"Codex version diagnostics"));return yield*m(new G("discovery_failed","The Codex executable did not provide a version.",{exitCode:o,diagnostics:s}))}return a}).pipe(wt((r)=>r instanceof G?r:new G("discovery_failed","The Codex version command failed.",{},{cause:r})),so(dt(()=>n.kill())))}function Z0(e){return b(function*(){let t=yield*p({try:()=>z0(e),catch:(o)=>o}),n=yield*p({try:()=>crypto.subtle.digest("SHA-256",t),catch:(o)=>o}),r=[...new Uint8Array(n)].map((o)=>o.toString(16).padStart(2,"0")).join(""),i=zh(r);if(!i.ok)return yield*m(new G("discovery_failed","The Codex executable digest was invalid."));return i.value})}function Cy(e={}){return A(b(function*(){let t=yield*G0(e),n=Ri(e.environment),r=e.versionRunner?yield*p({try:()=>e.versionRunner(t,n),catch:(i)=>i}).pipe(me(nr)):yield*Y0(t,n);if(r.length===0)return yield*m(new G("discovery_failed","The Codex version output was empty."));return{path:t,version:r,sha256:yield*Z0(t)}}))}function X0(e,t,n){return e.pipe(ju(K0),wt((r)=>r instanceof G?r:r!==null&&typeof r==="object"&&("_tag"in r)&&r._tag==="TimeoutError"?new G("timeout",n):r),Hs(()=>dt(t)))}var K0=30000,UH;var HC=L(()=>{ht();Fe();Ue();_r();Wf();UH=E({exitCode:Ye.check(ee((e)=>Number.isSafeInteger(e))),stdout:_.check(Mh(1048576)),stderr:_.check(Mh(1048576))})});var Q0="packages/codex/generated",eM,tM,nM=4194304,Ry,rM,VH,qH,zH;var JC=L(()=>{ht();Ue();Qu();_r();eM=/^codex-cli \d+\.\d+\.\d+$/u,tM=/^codex-app-server-\d+\.\d+\.\d+$/u,Ry=_.check(ce(/^[a-f0-9]{64}$/u)).pipe(go("Sha256Digest")),rM=Ye.check(Ta(),So(0),vf(nM)),VH=E({schema_version:R(["holycodex-generated-v2"]),artifact_root:R([Q0]),codex_cli_version:_.check(ce(eM)),codex_cli_digest:Ry,protocol_epoch:_.check(ce(tM)),generator:E({command:Oh([R(["app-server"]),R(["generate-ts"])]),supported_surface:R(["codex app-server generators"])}),typescript_root:R(["typescript"]),files:E({count:Ye.check(Ta(),So(0)),digest:Ry})}),qH=E({path:_.check(tt(1)),size:rM,sha256:Ry}),zH=_.pipe(yc(Ge,Xu()))});var oM;var KC=L(()=>{Ue();ld();oM=E({owner:R(["holycodex"]),schema:_.check(ce(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u)),installId:_.check(ce(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u))})});var wo=L(()=>{_r();_r();jf();ey();Eg();Wf();HC();JC();KC();ld();ed();ed()});function Yt(e){return Le(U({try:()=>(Gt(hM)(e),er(e),e),catch:()=>Error("The value is not JSON serializable.")}))}var hM;var fd=L(()=>{ht();Fe();Ue();hM=sn});import{lstat as gM,mkdir as yM}from"fs/promises";import{homedir as SM}from"os";import{dirname as xM,join as Mi,posix as YC,resolve as EM,sep as vM,win32 as ZC}from"path";function rr(e={},t=process.env){let n=SM(),r=e.paths?.codexHome??t.CODEX_HOME??Mi(n,".codex"),i=Oy(r,"CODEX_HOME"),o=Mi(i,bM);return{codexHome:i,stateRoot:o,activeRecord:Mi(o,_M),preparingRecord:Mi(o,wM),conflictedRecord:Mi(o,CM),installOptions:Mi(o,RM),roleRoot:Mi(o,"agents"),configFile:Mi(i,"config.toml")}}function Oy(e,t,n=process.platform==="win32"?"win32":"posix"){let r=dd(_.check(ee((s)=>!kM(s))),e,"invalid_path",`${t} contains invalid characters.`),i=n==="win32"?ZC:YC,o=Py(r,n);dd(_.check(ee((s)=>s.length>0&&i.isAbsolute(s))),o,"invalid_path",`${t} must be an absolute path.`);let a=i.normalize(o);return dd(_.check(ee((s)=>s!==i.dirname(s))),a,"broad_path",`${t} is too broad.`),dd(_.check(ee((s)=>!s.split(/[\\/]/u).some((c)=>c===".."))),o,"invalid_path",`${t} cannot contain traversal.`),i.resolve(a)}function dd(e,t,n,r){let i=Me(e)(t);if(Ke(i))return i.success;throw new Di(n,r)}function kM(e){for(let t of e){let n=t.codePointAt(0)??0;if(n<=31||n===127)return!0}return!1}function Ba(e){return b(function*(){Oy(e,"owned path"),yield*Xc(e),yield*p({try:()=>yM(e,{recursive:!0}),catch:(t)=>t}),yield*Xc(e)})}function Xc(e){return b(function*(){let t=EM(e);while(!0){if((yield*ge(p({try:()=>gM(t),catch:(i)=>i}),(i)=>Ze(i,"ENOENT"),()=>O(void 0)))?.isSymbolicLink())return yield*m(new Di("path_symlink","A managed path cannot contain a symlink."));let r=xM(t);if(r===t)return;t=r}})}function Va(e){return A(Xc(e))}function Co(e){return Va(e)}function Ln(e,t,n=process.platform==="win32"?"win32":"posix"){let r=n==="win32"?ZC:YC,i=r.resolve(Py(e,n)),o=r.resolve(Py(t,n)),a=r.relative(i,o);return a.length>0&&!a.startsWith(`..${n==="win32"?"\\":vM}`)&&a!==".."&&!r.isAbsolute(a)}function Py(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 bM="holycodex",_M="active.toml",wM="preparing.toml",CM="conflicted.toml",RM="install.toml",TM,Di;var Ro=L(()=>{ht();Fe();It();Ue();TM=yn;Di=class Di extends Error{code;constructor(e,t){super(t);this.name="PathBoundaryError",this.code=e}}});function ot(e,t){let n=xn(e,t);return Ke(n)?n.success:void 0}var md,IM,PM,Qc,OM,Li,AM,NM,MM,QC,el,hd,eR,tl,tR,$e,Ay,DM,LM,FM,UM,$M,jM,nR,rR,iR,BM,VM,qM,pd,zM,XC,WM,qa,za,HM,Ny,JM,My,KM,Dy,gd,yd,Fi,oR,GM,aR,YM,sR;var nl=L(()=>{wo();ht();It();Ue();md=_i,IM=Ec,PM=_.check(ce(/^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/u)),Qc=_.check(ce(/^[0-9a-f]{64}$/u)),OM=_.check(ce(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u)),Li=_.check(ce(/^[A-Za-z0-9][A-Za-z0-9._:@/-]{0,255}$/u)),AM=_.check(ee((e)=>!Number.isNaN(Date.parse(e)))),NM=E({path:_.check(ce(/^[A-Za-z0-9][A-Za-z0-9._/-]{0,255}$/u)),digest:Qc}),MM=E({...bc.fields,coding:R([!0])}),QC=E({browser_use:w(N),computer_use:w(N),sites:w(N),"session-audit":w(N),"auto-reset":w(N)}),el=E({profile:w(cn),tier:w(vn),optional:w(QC),officialPlugins:w(M(Li))}),hd=el,eR=R(["keep","remove","replace","cancel"]),tl=E({schema_version:R([1]),profile:cn,tier:vn,capabilities:M(Uh),additional_plugins:M(Li)}),tR=E({schema_version:R([1]),profile:cn,tier:vn,capabilities:M(vc),additional_plugins:M(Li)}),$e=E({selected:N,status:R(["disabled","pending","healthy","missing","provider_disabled","uncertain","unavailable"]),plugin_ids:M(Li),reason:w(_)}),Ay=E({browser_use:$e,computer_use:$e,frontend:$e,security:$e,sites:$e,"session-audit":$e,"auto-reset":$e}),DM=E({browser_use:w(N),computer_use:N,frontend:N,security:N,sites:w(N),"session-audit":bc.fields["session-audit"],"auto-reset":bc.fields["auto-reset"],coding:R([!0]),work:N}),LM=E({browser_use:w(N),computer_use:w(N),frontend:w(N),security:w(N),sites:w(N),"session-audit":w(N),"auto-reset":w(N),work:w(N)}),FM=E({browser_use:w($e),computer_use:$e,frontend:$e,security:$e,sites:w($e),"session-audit":w($e),"auto-reset":w($e),work:$e}),UM=E({computer_use:N,frontend:N,security:N,coding:R([!0])}),$M=E({computer_use:w(N),frontend:w(N),security:w(N)}),jM=E({computer_use:$e,frontend:$e,security:$e}),nR=E({browser_use:$e,computer_use:$e,frontend:$e,security:$e,sites:$e,"session-audit":w($e),"auto-reset":w($e)}),rR=E({browser_use:N,computer_use:N,sites:N,"session-audit":w(N),"auto-reset":w(N),coding:R([!0])}),iR=E({browser_use:w(N),computer_use:w(N),sites:w(N),"session-audit":w(N),"auto-reset":w(N)}),BM=H([E({status:R(["not_applicable"])}),E({status:R(["missing"])}),E({status:R(["healthy"]),path:_,installed:N})]),VM=E({manager:R(["bun","npm","pnpm"]),launcher:R(["bunx","npx","pnpm dlx"]),version:PM,executable:_,ownership:R(["user","holycodex"]),identity:w(Qc)}),qM=E({git_bash:w(BM),context7:w(VM)}),pd=E({presence:R(["absent","present"]),digest:Qc,safe_value:w(H([E({kind:R(["boolean"]),value:N}),E({kind:R(["marketplace"]),source_type:R(["git"]),source:R(["https://github.com/davidbasilefilho/holycodex.git"])})]))}),zM=E({plugin_id:R(["holycodex@holycodex"]),before:E({preference:pd,marketplace:pd}),after:E({preference:pd,marketplace:pd})}),XC=E({presence:R(["absent","present"]),digest:Qc,safe_value:w(E({kind:R(["boolean"]),value:N}))}),WM=E({plugin_id:Li,before:XC,after:XC}),qa={owner:R(["holycodex"]),schema_epoch:R([yn]),install_id:OM,version:IM,digest:Qc,profile:cn,tier:vn,optional_selections:MM,explicit_optional_selections:QC,official_plugins:w(M(Li)),capability_state:w(Ay),managed_artifacts:M(NM),installed_at:AM,status:w(R(["active"])),step:w(R(["active"])),managed_config:w(Wc),plugin_snapshot:w(M(E({plugin_id:Li,status:R(["installed","available","missing","disabled","uncertain","unknown"])}))),plugin_config:w(zM),provider_config:w(M(WM)),owned_plugins:w(M(Li)),tooling:w(qM)},za=E(qa),HM=(({profile:e,...t})=>t)(qa),Ny={...qa,optional_selections:DM,explicit_optional_selections:LM,capability_state:w(FM)},JM=(({profile:e,...t})=>t)(Ny),My={...qa,optional_selections:UM,explicit_optional_selections:$M,capability_state:w(jM)},KM=(({profile:e,...t})=>t)(My),Dy=H([E({...qa,optional_selections:rR,explicit_optional_selections:iR,capability_state:w(nR)}),E({...Ny,profile:Qn}),E({...JM,plan:Qn}),E({...HM,plan:Qn}),E({...My,profile:Qn}),E({...KM,plan:Qn})]),gd=R(["preparing","conflicted"]),yd=R(["validated","plugins_snapshotted","roles_prepared","plugins_installed","config_published","verified","conflicted"]),Fi=E({...za.fields,status:gd,step:yd}),oR={...Ny,status:gd,step:yd},GM=(({profile:e,...t})=>t)(oR),aR={...My,status:gd,step:yd},YM=(({profile:e,...t})=>t)(aR),sR=H([Fi,E({...qa,optional_selections:rR,explicit_optional_selections:iR,capability_state:w(nR),status:gd,step:yd}),E({...oR,profile:Qn}),E({...GM,plan:Qn}),E({...aR,profile:Qn}),E({...YM,plan:Qn})])});function rl(e){let t={},n=[];for(let r of e.split(/\r?\n/u)){let i=XM(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=Ly(i.slice(1,-1).trim()),ZM(t,n);continue}let o=uR(i);if(o<1)throw Error("TOML assignment is invalid.");let a=Ly(i.slice(0,o).trim()),s=Sd(i.slice(o+1).trim());lR(t,[...n,...a],s)}return t}function il(e){let t=[];return cR(e,[],t),t.join(`
|
|
28
|
+
`)}function cR(e,t,n){let r=[],i=[];for(let[o,a]of Object.entries(e))if(jy(a))i.push([o,a]);else r.push([o,a]);if(t.length>0){if(n.length>0)n.push("");n.push(`[${t.map(Uy).join(".")}]`)}for(let[o,a]of r)n.push(`${Uy(o)} = ${$y(a)}`);for(let[o,a]of i)cR(a,[...t,o],n)}function Sd(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?[]:Fy(t,",").map((n)=>Sd(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 Fy(t,",")){let i=uR(r);if(i<1)throw Error("TOML inline table entry is invalid.");lR(n,Ly(r.slice(0,i).trim()),Sd(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 Ly(e){let t=Fy(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("'")?Sd(n):n)}function lR(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(jy(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 ZM(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(jy(i))n=i;else throw Error("TOML table conflicts with a scalar.")}}function Fy(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 uR(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 XM(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 jy(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function Uy(e){return/^[A-Za-z0-9_-]+$/u.test(e)?e:JSON.stringify(e)}function $y(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($y).join(", ")}]`;if(e===null)throw Error("TOML null is not serializable.");return`{ ${Object.entries(e).map(([t,n])=>`${Uy(t)} = ${$y(n)}`).join(", ")} }`}import{lstat as fR,open as QM,readFile as dR,rename as eD,unlink as pR,writeFile as tD}from"fs/promises";import{dirname as nD}from"path";function mR(e){let t=Wr(p({try:()=>QM(e,"r"),catch:(n)=>n}),(n)=>p({try:()=>n.sync(),catch:(r)=>r}),(n)=>p({try:()=>n.close(),catch:(r)=>r}).pipe(ge(()=>!0,()=>pt)));return ge(t,SR,()=>pt)}function aD(e){return ge(mR(e),SR,()=>pt)}function hR(e,t){return yt(e,`${er(t)}
|
|
29
|
+
`)}function gR(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 yR(e,il(i))}function al(e,t){return A(gR(e,t))}function sD(e,t){return b(function*(){let n=yield*ol(e);if(n===void 0){let r=e.replace(/\.toml$/u,".json");return yield*fD(r,t)}return lD(n,t)})}function By(e,t){return A(sD(e,t))}function cD(e,t){return b(function*(){if((yield*ol(e))!==void 0)return;let n=e.replace(/\.toml$/u,".json"),r=yield*ol(n);if(r===void 0)return;if(yield*gR(e,t),(yield*ol(n))!==r)return yield*m(new Ir("state_corrupt","Legacy state changed during migration."));yield*p({try:()=>pR(n),catch:(o)=>o})})}function sl(e,t){return A(cD(e,t))}function lD(e,t){let n=Le(U({try:()=>{if(e.trimStart().startsWith("{"))return JSON.parse(e);let i=ot(oD,rl(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 u of a.slice(0,-1)){if(typeof s!=="object"||s===null||!Object.hasOwn(s,u))throw Error("Invalid null path");s=s[u]}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 Ir("state_corrupt","A persisted state file is not valid TOML.",i)})),r=ot(t,n);if(r===void 0)throw new Ir("state_corrupt","A persisted file failed schema validation.");return r}function yR(e,t){let n=nD(e),r=`${e}.tmp-${process.pid}-${crypto.randomUUID()}`;return b(function*(){yield*Ba(n),yield*Xc(e),yield*p({try:()=>tD(r,t,{encoding:"utf8",mode:384}),catch:(o)=>o}),yield*mR(r),yield*p({try:()=>eD(r,e),catch:(o)=>o}),yield*aD(n)}).pipe(ge(()=>!0,(o)=>Ae(p({try:()=>pR(r),catch:()=>{return}}),()=>m(o))))}function yt(e,t){return A(yR(e,t))}function uD(e,t){return A(b(function*(){let n=yield*p({try:()=>fR(e),catch:(a)=>a});if(!n.isFile()||n.isSymbolicLink())return yield*m(new Ir("state_corrupt","A persisted file is not a regular file."));let r=yield*p({try:()=>dR(e,"utf8"),catch:(a)=>a}),i=yield*U({try:()=>JSON.parse(r),catch:(a)=>new Ir("state_corrupt","A persisted file is not valid JSON.",a)}),o=ot(t,i);if(o===void 0)return yield*m(new Ir("state_corrupt","A persisted file failed schema validation."));return o}))}function ol(e){return b(function*(){let t=yield*ge(p({try:()=>fR(e),catch:(n)=>n}),(n)=>Ze(n,"ENOENT"),()=>O(void 0));if(t===void 0)return;if(!t.isFile()||t.isSymbolicLink())return yield*m(new Ir("state_corrupt","A persisted file is not a regular file."));return yield*p({try:()=>dR(e,"utf8"),catch:(n)=>n})})}function xe(e){return A(ol(e))}function fD(e,t){return ge(p({try:()=>uD(e,t),catch:(n)=>n}),(n)=>Ze(n,"ENOENT"),()=>O(void 0))}function SR(e){if(typeof e==="object"&&e!==null&&"code"in e&&typeof e.code==="string")return rD.has(e.code)||process.platform==="win32"&&e.code==="EPERM";return!1}var rD,iD,oD,Ir;var Wa=L(()=>{ht();Fe();Ue();Ro();nl();rD=new Set(["EBADF","EINVAL","ENOSYS","ENOTSUP","EISDIR"]),iD=M(_.check(ee((e)=>!["__proto__","constructor","prototype"].includes(e)))).check(tt(1)),oD=E({format_version:R([1]),null_paths:M(iD),record:Ge});Ir=class Ir extends Error{code;causeValue;constructor(e,t,n){super(t);this.name="StorageError",this.code=e,this.causeValue=n}}});import{readFile as dD}from"fs/promises";import{dirname as pD,resolve as mD}from"path";import{fileURLToPath as hD}from"url";function xR(e=Fn){return b(function*(){let t=yield*p({try:()=>dD(e,"utf8"),catch:(n)=>n});return yield*U({try:()=>Gt(_f(gD))(t),catch:()=>new Ui("manifest_invalid","The public package manifest is invalid.")})})}function Vy(e=Fn){return A(xd(e))}function xd(e=Fn){return me(xR(e),(t)=>t.version)}function yD(e=Fn){return A(ER(e))}function ER(e=Fn){return Ae(xd(e),(t)=>le(xc)(t)?O(t):m(new Ui("manifest_invalid","The public package manifest must use a canonical stable release version.")))}function SD(e=Fn){return A(xD(e))}function xD(e=Fn){return Ae(xd(e),(t)=>{let n=t.split("-",1)[0];return le(Lh)(n)?O(n):m(new Ui("manifest_invalid","The public package manifest must use a canonical release base version."))})}function qy(e=Fn){return A(zy(e))}function zy(e=Fn){return xd(e)}function Wy(e,t,n=Fn){return A(ED(e,t,n))}function ED(e,t,n=Fn){return b(function*(){let r=yield*xR(n),i=yield*ER(n),o=yield*vD(e,i);if(!t)yield*p({try:()=>hR(n,{...r,version:o}),catch:(a)=>a});return{previous:i,next:o}})}function vD(e,t){if(e!=="patch"&&e!=="minor")return le(xc)(e)?O(e):m(new Ui("version_invalid","The version target is invalid."));return U({try:()=>Fh(e,t),catch:(n)=>new Ui("version_invalid",n instanceof Error?n.message:"The current version is invalid.")})}var gD,Fn,Ui;var cl=L(()=>{ht();Fe();Ue();Wa();gD=ye(E({name:R(["holycodex"]),version:Ec}),[Pe(_,sn)]),Fn=mD(pD(hD(import.meta.url)),"../package.json");Ui=class Ui extends Error{code;constructor(e,t){super(t);this.name="ManifestError",this.code=e}}});import{createHash as bD}from"crypto";function Jy(e,t){let r=Gt(TR)(e).models.filter((i)=>i.slug===t);if(r.length!==1)throw Error(`The current Codex catalog must contain exactly one ${t} entry.`);return r[0]?.supports_experimental_context===!0}function vd(e){let t=Gt(TR)(e),n=t.models.filter((u)=>CR(u)&&u.slug==="gpt-6.1-sol"),r=t.models.filter((u)=>CR(u)&&u.slug==="gpt-6-luna");if(n.length!==1||r.length!==1)throw Error("The current Codex catalog must contain exactly one Sol and Luna model entry.");let i=Gt(vR)(n[0]),o=Gt(vR)(r[0]),a=FD(i.model_messages.instructions_template),s=$D(o.model_messages.instructions_template),c=t.models.map((u)=>{if(u.slug==="gpt-6.1-sol")return{...i,multi_agent_version:"v1",model_messages:{...i.model_messages,instructions_template:a}};if(u.slug==="gpt-6-luna")return{...o,model_messages:{...o.model_messages,instructions_template:s}};return u});return{catalog:{...t,models:c},rootInstructions:a,specialistInstructions:s}}function CR(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function FD(e){let t=UD(e),n=Pr(t,_D),r=Pr(t,wD,n),i=Pr(t,ID,r),o=Pr(t,wR,i),a=o,s=Pr(t,PD,a),c=ll(t.slice(a,s),Hy,"Codex Root wait prohibition"),u=t.slice(0,n).concat(`# When to ask the user for permission
|
|
30
|
+
Ask only when a consequential external effect lacks authorization or correctness depends on information that cannot be resolved from authorized context. Continue independent work while an answer is pending.
|
|
31
|
+
|
|
32
|
+
`,t.slice(r,i),`# Working with the user
|
|
33
|
+
Root owns user interaction. Send an intermediate update only when it changes a Root decision or expected outcome, input is required, authorized work is blocked, or a release/completion milestone occurs.
|
|
34
|
+
|
|
35
|
+
`,t.slice(o,a),`# Rules for getting work done
|
|
36
|
+
Root delegates all delegable execution and discovery through bounded Assignments; Root owns user interaction, material decisions, orchestration, integration acceptance, completion, Git/VCS writes, consequential external effects, and final visual judgment. Dispatch every ready independent Assignment before waiting and coordinate only through terminal specialist reports. Use a tool only for Root-owned decisions, integration, or evidence that cannot be assigned; batch scheduling-independent tool calls. Quote shell inputs safely, avoid chained commands, preserve unrelated user configuration and concurrent work, and use the smallest meaningful proof required for acceptance.
|
|
37
|
+
|
|
38
|
+
`,c.slice(wR.length),t.slice(s));if(u.includes(Hy))throw Error("The Root model prompt retained a conflicting long-wait prohibition.");return ll(u,kR,"Codex skill-announcement guidance")}function UD(e){let t=e.indexOf(Ed);if(t<0||e.indexOf(Ed,t+Ed.length)>=0)throw Error("The expected Codex direct-execution guidance changed; update the managed model-prompt patch.");let n=t+Ed.length,r=e.slice(n),i=` ${Ha}`,o=r.startsWith(i)?i:r.startsWith(`
|
|
39
|
+
|
|
40
|
+
${Ha}`)?`
|
|
41
|
+
|
|
42
|
+
${Ha}`:r.startsWith(`
|
|
43
|
+
${Ha}`)?`
|
|
44
|
+
${Ha}`:void 0;if(r===""||RR(r))return`${e.slice(0,t)}${_R}${r}`;if(o===void 0||!RR(r.slice(o.length)))throw Error("The expected Codex direct-execution guidance changed; update the managed model-prompt patch.");let s=`${_R} ${Ha}`;return`${e.slice(0,t)}${s}${r.slice(o.length)}`}function RR(e){if(e.startsWith(`
|
|
45
|
+
${bR}`)||e.startsWith(`
|
|
46
|
+
|
|
47
|
+
${bR}`)||e.startsWith(TD))return!0;let n=e.indexOf(kD);if(n<0)return!1;let r=e.slice(0,n);return bD("sha256").update(r).digest("hex")===RD}function $D(e){let t=Pr(e,OD),n=Pr(e,AD,t),r=Pr(e,ND,n),i=Pr(e,MD,r),o=Pr(e,DD,i),a=e.slice(0,n).concat(`# Specialist authority
|
|
48
|
+
Execute only the one bounded Assignment, make routine in-scope choices, and return one terminal evidence report to Root. Do not ask or message the user, delegate, mutate HolyCodex lifecycle, perform Git/VCS writes, or perform external effects unless explicitly authorized by the Assignment.
|
|
49
|
+
|
|
50
|
+
`,e.slice(r,i),`# Working with Root
|
|
51
|
+
Root owns user interaction and coordination. Return material decisions, scope expansion, required input, blockers, or terminal evidence to Root; do not message the user or peers.
|
|
52
|
+
|
|
53
|
+
`,e.slice(o)),s=ll(a,Hy,"Codex specialist wait prohibition"),c=ll(s,LD,"Codex specialist test restriction"),u=ll(c,kR,"Codex specialist skill-announcement guidance");if(u.includes("functions.send_user_message_async")||u.includes("request_user_input_async"))throw Error("The Luna-derived specialist prompt still contains user-interaction machinery.");return u}function ll(e,t,n){let r=e.indexOf(t);if(r<0||e.indexOf(t,r+t.length)>=0)throw Error(`The expected ${n} changed; update the managed model-prompt patch.`);return`${e.slice(0,r)}${e.slice(r+t.length)}`}function Pr(e,t,n=0){let r=e.indexOf(t,n);if(r<0||e.indexOf(t,r+t.length)>=0)throw Error(`The expected Codex instruction patch anchor changed: ${t.trim()}`);return r}var vR,TR,_D=`# When to ask the user for permission
|
|
54
|
+
`,wD=`# Autonomy and persistence
|
|
55
|
+
`,Ed=`When the user's prompt indicates a request for action, such as "can you...", "I want to...", "help me..." and similar expressions, treat these as instructions to do the work and take action. Do not stop at acknowledging capability (e.g. "Yes\u2026"), proposing a plan, or offering to continue. Do not settle for a partial or "helpful enough" solution that does not fully satisfy the user's task to save time, effort or tokens.`,Ha="If a task requires sustained work, complete all the necessary work until the intended outcome is fulfilled.",bR=`# Working with the user
|
|
56
|
+
`,CD="If the user's intent or task scope is unclear, progress towards the user's goal with the information available and then ask the user for clarification while continuing independent work.",RD="5d19834e9e9c5e608a8174525b11b31c4438bbfcb55af81101c695724a9e634b",TD,kD=`# Personality
|
|
57
|
+
`,_R="When a user requests action, carry the objective through to completion. Root delegates every delegable action through bounded Assignments and directly performs Root-owned work, decisions, integration, and proof. Do not stop after acknowledging the request, proposing a plan, or completing only part of the authorized objective.",ID=`# Working with the user
|
|
58
|
+
`,wR=`# Rules for getting work done
|
|
59
|
+
`,PD=`# Using skills
|
|
60
|
+
`,OD=`# Personality
|
|
61
|
+
`,AD=`# When to ask the user for permission
|
|
62
|
+
`,ND=`# Autonomy and persistence
|
|
63
|
+
`,MD=`# Working with the user
|
|
64
|
+
`,DD=`# Rules for getting work done
|
|
65
|
+
`,kR="The first time in a conversation that you decide to apply a skill, inform the user in the commentary channel.",Hy=`- Avoid performing blocking sleep or wait calls longer than 60 seconds, as they may prevent you from communicating with the user for their duration.
|
|
66
|
+
`,LD=`- Do not add or run tests unless the user asks you to test or verify implementation.
|
|
67
|
+
`;var Ky=L(()=>{Ue();vR=ye(E({slug:R(["gpt-6.1-sol","gpt-6-luna"]),multi_agent_version:w(H([_,_e])),model_messages:ye(E({instructions_template:_}),[Pe(_,Ge)])}),[Pe(_,Ge)]),TR=ye(E({models:M(ye(E({slug:_,supports_experimental_context:w(N)}),[Pe(_,Ge)]))}),[Pe(_,Ge)]),TD=`
|
|
68
|
+
|
|
69
|
+
${CD}
|
|
70
|
+
|
|
71
|
+
# Working with the user
|
|
72
|
+
`});import{createHash as jD}from"crypto";import{lstat as Gy,readFile as Yy,rm as Zy,rmdir as BD}from"fs/promises";import{dirname as IR,join as Xe,relative as PR}from"path";function To(e){return e==="none"}function bd(e,t,n=[],r="standard",i={},o){return A(WD(e,t,n,r,i,o))}function WD(e,t,n,r,i,o){return b(function*(){let a=ko(t,r,i),s=DR(e,t,r,i,a);if(o!==void 0)s.push({path:Xe(e,"holycodex","model-catalog.json"),contents:o});let c=new Map(n.map((l)=>[Xe(e,l.path),l])),u=[];for(let l of s){let f=yield*p({try:()=>$i(l.path),catch:(y)=>y}),h=c.get(l.path),g=f===void 0?void 0:yield*qR(l,f,h);if(g!==void 0)u.push(g)}return u})}function NR(e,t){return A(HD(e,t))}function HD(e,t){return b(function*(){let n=Xe(e,"agents"),r=Xe(e,"holycodex","agents"),i=Xe(e,"holycodex","model-catalog.json"),o=[];for(let a of t){let s=Xe(e,a.path);if(!Ln(e,s)||!Ln(n,s)&&!Ln(r,s)&&s!==Xe(e,"config.toml")&&s!==i)continue;let c=yield*p({try:()=>$i(s),catch:(u)=>u});if(c!==void 0&&(yield*p({try:()=>Rn(c),catch:(u)=>u}))!==a.digest){let u=yield*p({try:()=>Rn(c),catch:(l)=>l});o.push({...VR(s,"remove",{present:!0,digest:u},{present:!1},"The managed native artifact changed outside HolyCodex and would be removed."),action:"remove"})}}return o})}function MR(e,t){return A(JD(e,t))}function JD(e,t){return b(function*(){let n=Xe(e,"agents"),r=Xe(e,"holycodex","agents"),i=Xe(e,"holycodex","model-catalog.json"),o=[];for(let[a,s]of t){if(!Ln(e,a)||!Ln(n,a)&&!Ln(r,a)&&a!==i){o.push(a);continue}let c=yield*p({try:()=>$i(a),catch:(u)=>u});if(c!==void 0&&(yield*p({try:()=>Rn(c),catch:(u)=>u}))!==s)o.push(a)}return o})}function ji(e,t="standard"){let n=Ma(e);if(!n.ok)return[];return n.value.routes.map((r)=>{let i={role:r.role,task:r.task};return{name:Yh(i),description:Xh(i),taskInstruction:Zh(i),permissions:Qh(i),model:r.model,effort:r.effort,serviceTier:t==="standard"?"default":"fast"}})}function DR(e,t,n,r,i){let o=Xe(e,"holycodex","agents",i);return[...ji(t,n).map((a)=>({path:Xe(o,`${a.name}.toml`),contents:dl(a,r)})),...Ci.map((a)=>({path:Xe(o,`sentinel-${a}.toml`),contents:FR(a,r.parentPersonalityNone===!0)}))]}function ko(e,t="standard",n={}){let r=[...ji(e,t).map((i)=>`${i.name}\x00${dl(i,n)}`),...Ci.map((i)=>`${i}\x00${FR(i,n.parentPersonalityNone)}`)].join("\x00");return jD("sha256").update(r).digest("hex").slice(0,20)}function ul(e,t){if(!/^[a-f0-9]{20}$/u.test(t))throw Error("Invalid native-agent generation identifier.");return`holycodex/agents/${t}/${e}.toml`}function LR(e,t){if(!/^[a-f0-9]{20}$/u.test(t))throw Error("Invalid native-agent generation identifier.");return`holycodex/agents/${t}/sentinel-${e}.toml`}function FR(e,t=!1){let n=`This is HolyCodex's fail-closed sentinel for the generic \`${e}\` route. Do not perform work, inspect files, use tools, or delegate. Immediately return to the parent that the generic route is disabled and that it must use an exact registered Role.task route or report the missing route to Root.`;return[`name = ${JSON.stringify(e)}`,`description = ${JSON.stringify(`Fail-closed sentinel for generic ${e} assignments.`)}`,'model = "gpt-6-luna"','model_reasoning_effort = "low"','service_tier = "default"','model_reasoning_summary = "none"','model_verbosity = "low"',`personality = ${JSON.stringify(t?"friendly":"none")}`,`developer_instructions = ${JSON.stringify(n)}`,""].join(`
|
|
73
|
+
`)}function fl(e){return Xe(e,"holycodex","model-catalog.json")}function _d(e,t="standard"){let n=Ma(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 Xy(e=!1){let t=typeof e==="boolean"?{computerUse:e,frontend:!0,security:!0}:e;if(!Ie.requiresDelegation||Ie.normalSpawnForkContext!==!1||Ie.normalSpawnModelOverride!==!1||Ie.normalSpawnEffortOverride!==!1||Ie.orchestrationToolNamespace!=="multi_agent_v1"||!Ie.orchestrationToolsDirectOnly||!Ie.assignmentContextIsTaskSpecificOnly||!Ie.configuredRouteModelAndEffortPreserved||Ie.rootWaitTool!=="multi_agent_v1.wait_agent"||Ie.rootWaitTimeoutMs!==600000||!Ie.waitIncludesEveryLiveBlockingSpecialist||!Ie.v1UsageHintText.includes("fork_context=false")||Ie.registeredSpecialistAgentTypes!==Gr||Ie.forbiddenGenericAgentTypes!==Ci)throw Error("The Root orchestration policy is incomplete.");let n=[`You are the HolyCodex Root/session orchestrator. Delegate all delegable work. Root owns ${Ie.rootOwnedAuthority.map((r)=>VD[r]).join("; ")}, within authorization and capability boundaries.`,`Delegate ${Ie.delegableActions.filter((r)=>(r!=="browser_use"||t.browserUse)&&(r!=="computer_use"||t.computerUse)).map((r)=>qD[r]).join("; ")} through bounded Assignments. Bundle related trivial and preparatory steps into a coherent Assignment rather than spawning per action.`,Ie.routeConfigurationBeforeDispatch,Ie.assignmentInvocationLifecycle,`For normal specialist spawns, set fork_context: ${Ie.normalSpawnForkContext}; do not override the selected route's model or effort. 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: ${Ie.registeredSpecialistAgentTypes.join(", ")}. Explorer, Librarian, Worker, and Reviewer are labels only; generic built-in agent_type values ${Ie.forbiddenGenericAgentTypes.join(", ")} are forbidden.`,Ie.semanticDefinitionsInstruction,Ie.semanticStateBoundary,Ie.dependencyAwareAmbiguityInstruction,`Root owns user interaction. Continue independent work while input is pending; prepare the concrete reviewable result before requesting approval for a consequential effect. Credential entry remains user-owned. ${Ie.dependencyAwareAmbiguityInstruction}`,"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.",UR(t),bn.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.",Ie.specialistCoordinationInstruction,`${Nf.rule} ${zD}`,"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(KD());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.");if(t.sessionAudit)n.push(OR("session-audit"));if(t.autoReset)n.push(OR("auto-reset"));return n.join(`
|
|
74
|
+
`)}function OR(e){return Er[e].applicability.map(({appliesWhen:t,skillId:n})=>`When ${t}, use $${n}.`).join(" ")}function UR(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 KD(){if(!bn.repositoryAndUserRequirementsPrecedePluginDefaults||!bn.specialistsOwnImplementationAndInteractionProof||bn.specialistVisualImplementationInstruction.length===0||!bn.rootOwnsVisualJudgment||!bn.rootOwnsSharedDevServer||!bn.rootAcceptsTerminalVisualEvidence||!bn.sourceChangesInvalidateRenderEvidence||!bn.specialistReportsIncludeObservableRenderedEvidence||bn.logicOnlyChangesRequireVisualAcceptance)throw Error("The Frontend workflow policy is incomplete.");return`${$R()} Follow the repository stack, design system, and user requirements. ${bn.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 $R(){return`Use Build Web Apps for applicable web-app construction and Frontend App Builder for applicable frontend work. For frontend work, ${Er.frontend.applicability.map(({skillId:t,appliesWhen:n})=>`${n} uses ${t}`).join("; ")}.`}function Qy(e,t,n=[],r="standard",i,o=[],a={},s){let c=[],u=b(function*(){let l=ko(t,r,a),f=[],h=DR(e,t,r,a,l);if(s!==void 0)h.push({path:Xe(e,"holycodex","model-catalog.json"),contents:s});let g=new Map(n.map((T)=>[Xe(e,T.path),T])),y=new Map,v=new Set,d=new Set,x=new Map;for(let T of h){let F=yield*p({try:()=>$i(T.path),catch:(z)=>z});y.set(T.path,F);let J=o.find((z)=>z.path===T.path&&z.action==="replace"&&z.key===void 0);if(J!==void 0){let z=AR(J);if(z===void 0||F===void 0||(yield*p({try:()=>Rn(F),catch:(K)=>K}))!==z)return yield*m(Error(`The native role conflict changed after review; review the latest file and retry: ${T.path}`));if(x.set(T.path,z),J.decision==="keep")d.add(T.path);else v.add(T.path)}let j=g.get(T.path);if(F!==void 0&&J===void 0){let z=yield*qR(T,F,j);if(z!==void 0){let K=i===void 0?void 0:yield*i(z);if(K==="cancel")return yield*m(Error(`Native-agent conflict resolution was cancelled: ${T.path}`));if(K===void 0)d.add(T.path);else{let Ce=AR(z),Y=yield*p({try:()=>$i(T.path),catch:(I)=>I});if(Ce===void 0||Y===void 0||(yield*p({try:()=>Rn(Y),catch:(I)=>I}))!==Ce)return yield*m(Error(`The native role conflict changed after review; review the latest file and retry: ${T.path}`));if(x.set(T.path,Ce),K==="accept")v.add(T.path);else d.add(T.path)}}}}let S=[],C=yield*We(b(function*(){for(let j of h){let z=y.get(j.path),K=g.get(j.path),Ce=x.get(j.path);if(Ce!==void 0){let Y=yield*p({try:()=>$i(j.path),catch:(I)=>I});if(Y===void 0||(yield*p({try:()=>Rn(Y),catch:(I)=>I}))!==Ce)return yield*m(Error(`The native role conflict changed after review; review the latest file and retry: ${j.path}`))}if(d.has(j.path)){if(f.push(j.path),K!==void 0)S.push(K);continue}if(z!==void 0&&K!==void 0){if((yield*p({try:()=>Rn(z),catch:(I)=>I}))!==K.digest&&z!==j.contents&&!v.has(j.path)){f.push(j.path),S.push({path:PR(e,j.path).replaceAll("\\","/"),digest:K.digest});continue}}if(z===void 0||z!==j.contents)yield*p({try:()=>yt(j.path,j.contents),catch:(Y)=>Y}),c.push({path:j.path,previous:z,installedDigest:yield*p({try:()=>Rn(j.contents),catch:(Y)=>Y})});S.push({path:PR(e,j.path).replaceAll("\\","/"),digest:yield*p({try:()=>Rn(j.contents),catch:(Y)=>Y})})}let T=Xe(e,"agents","root.toml"),F=yield*p({try:()=>$i(T),catch:(j)=>j}),J=yield*p({try:()=>BR(T),catch:(j)=>j});if(J==="preserved")f.push(T);if(J==="removed"&&F!==void 0)c.push({path:T,previous:F,installedDigest:void 0});for(let j of n){let z=Xe(e,j.path);if(!h.some((K)=>K.path===z))S.push(j)}return{managed_artifacts:S,preserved:f,rollback:c}}));if(C._tag==="Failure")return yield*p({try:()=>wd(c),catch:()=>{return}}),yield*m(C.failure);return C.success});return A(u)}function wd(e){return A(GD(e))}function GD(e){return b(function*(){let t=[],n=[];for(let r of[...e].reverse()){let i=yield*p({try:()=>$i(r.path),catch:(a)=>a});if(!(r.installedDigest===void 0?i===void 0:i!==void 0&&(yield*p({try:()=>Rn(i),catch:(a)=>a}))===r.installedDigest)){n.push(r.path);continue}if(r.previous===void 0)yield*ge(p({try:()=>Zy(r.path,{force:!1}),catch:(a)=>a}),(a)=>Ze(a,"ENOENT"),()=>pt),t.push(r.path);else yield*p({try:()=>yt(r.path,r.previous),catch:(a)=>a})}return{removed:t,preserved:n}})}function Cd(e,t,n=new Map){return A(YD(e,t,n))}function YD(e,t,n){return b(function*(){let r=[],i=[],o=Xe(e,"agents"),a=Xe(e,"holycodex","agents"),s=Xe(e,"holycodex","model-catalog.json");for(let f of t){let h=Xe(e,f.path);if(!Ln(e,h)||!Ln(o,h)&&!Ln(a,h)&&h!==s&&h!==Xe(e,"config.toml")){i.push(h);continue}let g=yield*We(b(function*(){yield*p({try:()=>Va(h),catch:(S)=>S});let y=yield*p({try:()=>Gy(h),catch:(S)=>S});if(y.isSymbolicLink()||!y.isFile())return"preserved";let v=yield*p({try:()=>Yy(h),catch:(S)=>S}),d=yield*p({try:()=>Rn(v),catch:(S)=>S}),x=n.get(h);if(d!==f.digest&&d!==x)return"preserved";return yield*p({try:()=>Zy(h,{force:!1}),catch:(S)=>S}),"removed"}));if(g._tag==="Success")if(g.success==="removed")r.push(h);else i.push(h);else if(!Ze(g.failure,"ENOENT"))i.push(h)}let c=Xe(e,"agents","root.toml"),u=yield*p({try:()=>BR(c),catch:(f)=>f});if(u==="removed")r.push(c);if(u==="preserved")i.push(c);let l=r.slice();for(let f of l){let h=IR(f);while(h!==a&&Ln(a,h)){let g=yield*We(b(function*(){yield*p({try:()=>Va(h),catch:(y)=>y}),yield*p({try:()=>BD(h),catch:(y)=>y})}));if(g._tag==="Failure"){if(!Ze(g.failure,"ENOENT"))break}else r.push(h);h=IR(h)}}return{removed:r,preserved:i}})}function dl(e,t={}){let n=e.taskInstruction.indexOf(Of),r=e.taskInstruction.indexOf(Mf,n),i=e.taskInstruction.indexOf(Af,r);if(n<0||r<n||i<r)throw Error(`The ${e.name} task instruction has no canonical specialist policy order.`);let o=e.taskInstruction.slice(0,n).trim(),a=[...e.name==="Worker.visual"||e.name==="Reviewer.visual"?[UR(t,"specialist"),...t.frontend??!0?[$R()]:[]]:[],...e.permissions.sourceMutation?[`Patch quality: ${Pf}`]:[],...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."]:[]],s=[o,e.taskInstruction.slice(n,r).trim(),e.taskInstruction.slice(r,i).trim(),...a,e.taskInstruction.slice(i).trim()].join(`
|
|
75
|
+
`);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"',`personality = ${JSON.stringify(t.parentPersonalityNone===!0?"friendly":"none")}`,`developer_instructions = ${JSON.stringify(s)}`,""].join(`
|
|
76
|
+
`)}function jR(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&&fe(t,"sandbox_workspace_write.network_access")===void 0}function ZD(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(`
|
|
77
|
+
`)}function Ja(e){return XD.has(e)}function BR(e){return A(ge(b(function*(){yield*p({try:()=>Va(e),catch:(r)=>r});let t=yield*p({try:()=>Gy(e),catch:(r)=>r});if(!t.isFile()||t.isSymbolicLink())return"preserved";let n=yield*p({try:()=>Yy(e,"utf8"),catch:(r)=>r});if(!Ja(n))return"preserved";return yield*p({try:()=>Zy(e,{force:!1}),catch:(r)=>r}),"removed"}),(t)=>Ze(t,"ENOENT"),()=>O("absent")))}function $i(e){return A(ge(b(function*(){yield*p({try:()=>Va(e),catch:(r)=>r});let t=yield*p({try:()=>Gy(e),catch:(r)=>r});if(t.isSymbolicLink()||!t.isFile())return yield*m(Error(`Invalid managed path: ${e}`));let n=yield*p({try:()=>Yy(e),catch:(r)=>r});return yield*U({try:()=>new TextDecoder("utf-8",{fatal:!0}).decode(n),catch:(r)=>r})}),(t)=>Ze(t,"ENOENT"),()=>O(void 0)))}function Rn(e){let t=typeof e==="string"?new TextEncoder().encode(e):e;return A(me(p({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 VR(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 qR(e,t,n){if(t===e.contents)return O(void 0);return b(function*(){let r=yield*p({try:()=>Rn(t),catch:(a)=>a});if(n!==void 0&&r===n.digest)return;let i=yield*p({try:()=>Rn(e.contents),catch:(a)=>a});return{...VR(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 AR(e){if(typeof e.existing!=="object"||e.existing===null)return;let t=e.existing.digest;return typeof t==="string"?t:void 0}var VD,qD,zD="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.",XD;var Rd=L(()=>{wo();ht();Fe();Ro();Wa();VD={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"},qD={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"};XD=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)=>ZD(e,t,n))))});import{access as QD,readFile as eL,readdir as tL}from"fs/promises";import{join as eS}from"path";class Or{adapter;observedIdentities={};constructor(e){if("run"in e){let t=Xf({executable:"codex",runner:e});this.adapter=t}else this.adapter=e}static discover(e=process.env){return A(Or.discoverEffect(e))}static discoverEffect(e=process.env){return me(p({try:()=>Cy({environment:e}),catch:(t)=>t}),(t)=>{let n=Xf({executable:t.path,environment:ty(e),onMarketplaceConflict:(r)=>{console.warn(`HolyCodex warning: ${r}`)},...e.CODEX_HOME===void 0?{}:{codexHome:e.CODEX_HOME}});return new Or(n)})}list(){return A(this.listEffect())}listEffect(){return p({try:()=>this.adapter.list(),catch:(e)=>Ka("list",e)})}add(e){return A(this.addEffect(e))}addEffect(e){return p({try:()=>this.adapter.add(e),catch:(t)=>Ka("add",t,e)})}ensureOfficialMarketplace(e){return A(this.ensureOfficialMarketplaceEffect(e))}ensureOfficialMarketplaceEffect(e){let t=this.adapter.ensureOfficialMarketplace;if(t===void 0)return pt;return p({try:()=>t(e),catch:(n)=>Ka("bootstrap",n)})}remove(e){return A(this.removeEffect(e))}removeEffect(e){return p({try:()=>this.adapter.remove(e),catch:(t)=>Ka("remove",t,e)})}addMarketplace(e){return A(this.addMarketplaceEffect(e))}addMarketplaceEffect(e){return p({try:()=>this.adapter.addMarketplace(e),catch:(t)=>Ka("add",t,e)})}status(e){return A(this.statusEffect(e))}statusEffect(e){let t=this.adapter,n=b(function*(){let r=yield*p({try:()=>t.list(),catch:(s)=>Ka("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*Pn(e.map((s)=>dt(()=>{let c=Cr(r,s),u=Mn(s),l=o.get(s),f=c?.entry??(u===void 0||l?.marketplaceName==null?l:void 0);if(f!==void 0)i[s]=c?.entry.pluginId??f.pluginId;let h=f===void 0?"missing":f.installed&&f.enabled?"installed":f.installed?"disabled":"missing";return[s,h]})));return{observed:i,statuses:Object.fromEntries(a)}});return me(n,({observed:r,statuses:i})=>(this.observedIdentities=Object.freeze(r),i))}getObservedIdentities(){return this.observedIdentities}}class Td{codexHome;observedIdentities={};constructor(e){this.codexHome=e}status(e){return A(this.statusEffect(e))}statusEffect(e){let t=this.codexHome,n=b(function*(){let r=yield*ge(p({try:()=>eL(eS(t,"config.toml"),"utf8"),catch:(g)=>g}),tS,()=>O(void 0));if(r===void 0)return{identities:{},statuses:Object.fromEntries(e.map((g)=>[g,"missing"]))};let i=globalThis.Bun;if(i?.TOML?.parse===void 0)return yield*m(Error("A TOML parser is unavailable."));let o=i.TOML,a=yield*U({try:()=>o.parse(r),catch:(g)=>g}),s=yield*U({try:()=>Gt(Pi)(a),catch:()=>Error("Codex configuration is invalid.")}),c=Pe(_,Ge),u=E({enabled:w(N)}),l=le(c)(s.plugins)?s.plugins:void 0,f={},h=yield*Pn(e.map((g)=>b(function*(){let y=Pa(g),d=(y.length>0?y:[g]).flatMap((F)=>{if(l===void 0||!Object.hasOwn(l,F))return[];let J=l[F];return[{id:F,enabled:le(u)(J)?J.enabled:void 0}]});if(d.length===0)return[g,"missing"];let x=d.filter((F)=>F.enabled===!0),C=(yield*Pn(x.map((F)=>{let J=Pa(F.id),j=[F.id,...J.filter((z)=>z!==F.id)];return me(nL(t,j),(z)=>({...F,cachedIdentity:z}))}))).find((F)=>F.cachedIdentity!==void 0),T=C?.cachedIdentity??x[0]?.id??d[0]?.id;if(T!==void 0)f[g]=T;if(C!==void 0)return[g,"installed"];if(x.length>0)return[g,"missing"];if(d.every((F)=>F.enabled===!1))return[g,"disabled"];return[g,"unknown"]})));return{identities:f,statuses:Object.fromEntries(h)}});return me(n,({identities:r,statuses:i})=>(this.observedIdentities=Object.freeze(r),i))}getObservedIdentities(){return this.observedIdentities}}function nL(e,t){return b(function*(){for(let n of t){let r=n.lastIndexOf("@");if(r<=0||r===n.length-1)continue;let i=eS(e,"plugins","cache",n.slice(r+1),n.slice(0,r)),o=yield*ge(p({try:()=>tL(i,{withFileTypes:!0,encoding:"utf8"}),catch:(a)=>a}),tS,()=>O(void 0));if(o===void 0)continue;for(let a of o){if(!a.isDirectory())continue;if(yield*ge(Nb(p({try:()=>QD(eS(i,a.name,".codex-plugin","plugin.json")),catch:(c)=>c}),!0),tS,()=>O(!1)))return n}}return})}function tS(e){return le(rL)(e)}function Ka(e,t,n){if(t instanceof Ar)return t;let i=(t instanceof ue?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 Ar(o,a,t,n===void 0?{}:{plugin_id:n})}var rL,Ar;var pl=L(()=>{wo();ht();Fe();Ue();rL=E({code:R(["ENOENT"])});Ar=class Ar 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 iL}from"child_process";import{access as oL,readFile as aL,realpath as sL}from"fs/promises";import{posix as cL,win32 as lL}from"path";import{promisify as uL}from"util";function Ao(e=process.env){return{platform:process.platform,environment:e,processPath:process.execPath,files:Ya,run:(t,n)=>A(b(function*(){let r=yield*We(p({try:()=>fL(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=Me(pL)(r.failure),o=Ke(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 Po(e){let t=$n(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(ml(t,"pnpm")&&n==="dlx")return{launcher:"pnpm dlx",family:"pnpm",executable:"pnpm"};if(ml(t,"bunx")||ml(t,"bun")&&n==="exec")return{launcher:"bunx",family:"bun",executable:"bun"};if(ml(t,"npx")||t.endsWith("/npx-cli.js")||ml(t,"npm")&&n==="exec"||t.endsWith("/npm-cli.js")&&n==="exec")return{launcher:"npx",family:"npm",executable:"npm"};return}function kd(e,t,n){return A(hL(e,t,n))}function hL(e,t,n){return b(function*(){let r=yield*rS(e);if(r!==void 0){let i=Po(e.environment)??{launcher:"bunx",family:"bun",executable:"bun"},o=n?.ownership==="holycodex"&&typeof n.identity==="string"&&(yield*xl(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(Ga(e))return yield*vL(e,t,n);return yield*EL(e,t,n)})}function nS(e,t){return A(gL(e,t))}function gL(e,t){return b(function*(){let n=yield*rS(e);if(n!==void 0){let o=Po(e.environment)??{launcher:"bunx",family:"bun",executable:"bun"},a=t?.ownership==="holycodex"&&typeof t.identity==="string"&&(yield*xl(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=Ga(e)?{launcher:"bunx",family:"bun",executable:"bun"}:Po(e.environment);if(r===void 0)throw new ve("context7_manager_unknown","No usable PATH Context7 executable or supported package manager is available.");let i=r.family==="bun"&&Ga(e)?yield*hl(e):yield*gl(e,r);if(i===void 0)throw new ve("context7_unavailable","No usable managed Context7 executable is available.");return{manager:r.family,launcher:r.launcher,version:i.version,executable:i.executable,ownership:iS(t,r,i),identity:i.identity}})}function rS(e){return b(function*(){let t=yield*HR(e.environment,e.platform,e.files??Ya);if(t===void 0)return;let n=yield*fn(e,t,["--version"]),r=n.exitCode===0?Oo(n.stdout):void 0;return r===void 0?void 0:{version:r,executable:t}})}function yL(e){return A(SL(e))}function SL(e){return b(function*(){if((yield*rS(e))!==void 0)return;if(Ga(e)){yield*xL(e);return}let t=Po(e.environment);if(t===void 0)throw new ve("context7_manager_unknown","HolyCodex must be launched with bunx, npx, or pnpm dlx so Context7 can use the same package manager.");let n=yield*fn(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 ve("context7_unavailable",`The ${t.family} global installation could not be inspected before managed changes.`,{stderr:n.stderr.slice(0,512)})})}function xL(e){return b(function*(){let t=e.files??Ya,n=yield*fn(e,e.processPath,["pm","bin","-g"]);if(n.exitCode!==0||n.stdout.trim().length===0){if(IL(n.stderr))return;throw new ve("context7_unavailable","Bun's managed global installation could not be located before managed changes.",{stderr:n.stderr.slice(0,512)})}let r=Zt(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"),u=yield*We(b(function*(){yield*p({try:()=>t.access(i),catch:(T)=>T}),yield*p({try:()=>t.access(o),catch:(T)=>T})}));if(u._tag==="Failure")throw new ve("context7_unavailable","Bun's managed global location or project is unavailable before managed changes.",{reason:Io(u.failure)});let l=yield*We(p({try:()=>t.access(a),catch:(T)=>T}));if(l._tag==="Failure"){if(kL(l.failure))return;throw new ve("context7_unavailable","Bun's managed ctx7 package could not be inspected before managed changes.",{reason:Io(l.failure)})}let f=yield*We(p({try:()=>t.readText(s),catch:(T)=>T}));if(f._tag==="Failure")throw new ve("context7_unavailable","Bun's managed ctx7 package metadata could not be inspected before managed changes.",{reason:Io(f.failure)});let h=yield*We(aS(f.success));if(h._tag==="Failure")throw new ve("context7_unavailable","Bun's managed ctx7 package metadata is invalid before managed changes.",{reason:Io(h.failure)});if(h.success.version===void 0||Oo(h.success.version)!==h.success.version)throw new ve("context7_unavailable","Bun's managed ctx7 package has no exact semver version before managed changes.");let g=JR(h.success);if(g===void 0)throw new ve("context7_unavailable","Bun's managed ctx7 package does not declare its executable before managed changes.");let y=r.resolve(a,g),v=yield*We(b(function*(){yield*p({try:()=>t.access(y),catch:(J)=>J});let T=yield*p({try:()=>t.realpath(a),catch:(J)=>J}),F=yield*p({try:()=>t.realpath(y),catch:(J)=>J});return{canonicalPackageRoot:T,canonicalExecutable:F}}));if(v._tag==="Failure")throw new ve("context7_unavailable","Bun's managed ctx7 executable is unavailable before managed changes.",{reason:Io(v.failure)});let{canonicalPackageRoot:d,canonicalExecutable:x}=v.success;if(!yl(d,a,e.platform)||!$n(x).startsWith(`${$n(d)}/`))throw new ve("context7_unavailable","Bun's managed ctx7 executable is outside its package before managed changes.");let S=yield*We(b(function*(){return yield*p({try:()=>t.access(c),catch:(T)=>T}),yield*p({try:()=>t.realpath(c),catch:(T)=>T})}));if(S._tag==="Failure")throw new ve("context7_unavailable","Bun's managed ctx7 shim is unavailable before managed changes.",{reason:Io(S.failure)});let C=yield*fn(e,c,["--version"]);if(C.exitCode!==0||Oo(C.stdout)!==h.success.version)throw new ve("context7_unavailable","Bun's managed ctx7 shim does not report the package version before managed changes.",{stderr:C.stderr.slice(0,512)})})}function EL(e,t,n){return b(function*(){let r=Po(e.environment);if(r===void 0)throw new ve("context7_manager_unknown","HolyCodex must be launched with bunx, npx, or pnpm dlx so Context7 can use the same package manager.");let i=yield*gl(e,r),o=yield*KR(e,r);if(o===void 0)throw new ve("context7_verification_failed",`${r.family} could not resolve the latest ctx7 version.`);let a=iS(n,r,i);if(t&&i?.version!==o&&a==="holycodex"){let u=r.family==="bun"?{executable:"bun",args:Id(e,"add",Un)}:zR(r.family),l=yield*fn(e,u.executable,u.args);if(l.exitCode!==0)throw new ve("context7_install_failed",`${r.family} could not install ${Un}.`,{stderr:l.stderr.slice(0,512)})}else if(!t&&i===void 0)throw new ve("context7_unavailable",`${Un} is not owned by the ${r.family} global installation.`);let s=yield*gl(e,r);if(s===void 0)throw new ve("context7_verification_failed",`${Un} could not be verified in the ${r.family} global installation.`);if(s.version!==o)throw new ve("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 vL(e,t,n){return b(function*(){let r={launcher:"bunx",family:"bun",executable:"bun"},i=yield*hl(e),o=yield*KR(e,r);if(o===void 0)throw new ve("context7_verification_failed","Bun could not resolve the latest ctx7 version.");let a=iS(n,r,i);if(t&&i?.version!==o&&a==="holycodex"){let u=yield*fn(e,e.processPath,Id(e,"add",Un));if(u.exitCode!==0)throw new ve("context7_install_failed",`Bun could not install ${Un} in its global installation.`,{stderr:u.stderr.slice(0,512)})}else if(i===void 0)throw new ve("context7_unavailable",`${Un} is not present in Bun's exact global installation.`);let s=yield*hl(e);if(s===void 0)throw new ve("context7_verification_failed",`${Un} could not be verified in Bun's exact global installation.`);if(s.version!==o)throw new ve("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 hl(e){return b(function*(){let t=e.files??Ya,n=yield*fn(e,e.processPath,["pm","bin","-g"]);if(n.exitCode!==0)return;let r=n.stdout.trim();if(r.length===0)return;let i=Zt(e.platform),o=i.join(i.dirname(r),"install","global","node_modules","ctx7"),a=yield*We(b(function*(){let d=yield*p({try:()=>t.readText(i.join(o,"package.json")),catch:(x)=>x});return yield*aS(d)}));if(a._tag==="Failure")return;let s=a.success;if(typeof s.version!=="string"||Oo(s.version)!==s.version)return;let c=JR(s);if(c===void 0)return;let u=i.resolve(o,c),l=i.join(r,e.platform==="win32"?"ctx7.exe":"ctx7"),f=yield*We(b(function*(){yield*p({try:()=>t.access(o),catch:(C)=>C}),yield*p({try:()=>t.access(u),catch:(C)=>C}),yield*p({try:()=>t.access(l),catch:(C)=>C});let d=yield*p({try:()=>t.realpath(o),catch:(C)=>C}),x=yield*p({try:()=>t.realpath(u),catch:(C)=>C}),S=yield*p({try:()=>t.realpath(l),catch:(C)=>C});return{canonicalPackageRoot:d,canonicalExecutable:x,canonicalShim:S}}));if(f._tag==="Failure")return;let{canonicalPackageRoot:h,canonicalExecutable:g,canonicalShim:y}=f.success;if(!yl(h,o,e.platform)||!$n(g).startsWith(`${$n(h)}/`))return;let v=yield*fn(e,l,["--version"]);if(v.exitCode!==0||Oo(v.stdout)!==s.version)return;return{version:s.version,executable:l,identity:yield*WR({launcher:"bunx",family:"bun",executable:"bun"},h,g,y,s)}})}function Ga(e){let t=Zt(e.platform).basename(e.processPath).toLowerCase();return t==="bun"||t==="bun.exe"}function iS(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(!oS(r)||r!==n.identity)return"user";return"holycodex"}function Sl(e,t){return A(bL(e,t))}function bL(e,t){return Ga(e)?_L(e,t):wL(e,t)}function _L(e,t){return b(function*(){if(t?.ownership!=="holycodex"||t.manager!=="bun")return!1;let n=yield*We(hl(e));if(n._tag==="Failure")return!1;let r=n.success;if(r===void 0||r.version!==t.version||!(yield*xl(e,r.executable,t.executable))||!oS(t.identity)||r.identity!==t.identity)return!1;let i=yield*fn(e,e.processPath,Id(e,"remove","ctx7"));if(i.exitCode!==0)throw new ve("context7_remove_failed","Bun could not remove ctx7.",{stderr:i.stderr.slice(0,512)});if((yield*hl(e))!==void 0)throw new ve("context7_remove_failed","Bun reported success, but the recorded ctx7 installation is still present.");return!0})}function wL(e,t){return b(function*(){if(t?.ownership!=="holycodex")return!1;let n=Po(e.environment);if(n===void 0||n.family!==t.manager)return!1;let r=yield*We(gl(e,n));if(r._tag==="Failure"){if(r.failure instanceof ve&&r.failure.code==="context7_shadowed")return!1;throw r.failure}let i=r.success;if(i===void 0||i.version!==t.version||!(yield*xl(e,i.executable,t.executable))||!oS(t.identity)||i.identity!==t.identity)return!1;let o=n.family==="bun"?{executable:"bun",args:Id(e,"remove","ctx7")}:CL(n.family),a=yield*fn(e,o.executable,o.args);if(a.exitCode!==0)throw new ve("context7_remove_failed",`${n.family} could not remove ctx7.`,{stderr:a.stderr.slice(0,512)});let s=yield*We(b(function*(){if((yield*gl(e,n))!==void 0)return yield*m(new ve("context7_remove_failed",`${n.family} reported success, but the recorded ctx7 installation is still present.`))}));if(s._tag==="Failure"){if(s.failure instanceof ve&&s.failure.code==="context7_remove_failed")throw s.failure;throw new ve("context7_remove_failed",`${n.family} removed ctx7, but its final state could not be verified.`)}return!0})}function zR(e){switch(e){case"bun":return{executable:"bun",args:["add","--global",Un]};case"npm":return{executable:"npm",args:["install","--global",Un]};case"pnpm":return{executable:"pnpm",args:["add","--global",Un]}}}function Id(e,t,n){let r=Zt(e.platform),i=r.dirname(e.processPath),o=r.isAbsolute(i)?i:e.platform==="win32"?"C:\\":"/";return[t,"--global",`--cwd=${o}`,n]}function CL(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 gl(e,t){return b(function*(){let n=e.files??Ya,r=yield*fn(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"?Zt(e.platform).join(i,"node_modules","ctx7"):t.family==="pnpm"?yield*PL(e,t):Zt(e.platform).join(Zt(e.platform).dirname(i),"install","global","node_modules","ctx7");if(o===void 0)return;let a=yield*We(b(function*(){let S=yield*p({try:()=>n.readText(Zt(e.platform).join(o,"package.json")),catch:(C)=>C});return yield*aS(S)}));if(a._tag==="Failure")return;let s=a.success;if(typeof s.version!=="string")return;let c=typeof s.bin==="string"?s.bin:YR(s.bin)&&typeof s.bin.ctx7==="string"?s.bin.ctx7:void 0;if(c===void 0)return;let u=Zt(e.platform).resolve(o,c),l=yield*We(b(function*(){yield*p({try:()=>n.access(u),catch:(T)=>T});let S=yield*p({try:()=>n.realpath(o),catch:(T)=>T}),C=yield*p({try:()=>n.realpath(u),catch:(T)=>T});return{canonicalPackageRoot:S,canonicalExecutable:C}}));if(l._tag==="Failure")return;let{canonicalPackageRoot:f,canonicalExecutable:h}=l.success;if(!$n(h).startsWith(`${$n(f)}/`))return;let g=RL(i,t.family,e.platform),y=yield*We(b(function*(){return yield*p({try:()=>n.access(g),catch:(S)=>S}),yield*p({try:()=>n.realpath(g),catch:(S)=>S})}));if(y._tag==="Failure")return;let v=y.success,d=yield*HR(e.environment,e.platform,n);if(d!==void 0&&!yl(yield*TL(n,d),v,e.platform))return yield*m(new ve("context7_shadowed","A different ctx7 executable shadows the managed global installation.",{resolved:d,expected:g}));let x=yield*fn(e,g,["--version"]);if(x.exitCode!==0||Oo(x.stdout)!==s.version)return;return{version:s.version,executable:g,identity:yield*WR(t,f,h,v,s)}})}function WR(e,t,n,r,i){return dL(()=>wn("context7-installation",[_n({manager:e.family,package_root:$n(t),package_executable:$n(n),shim:$n(r),package:i})]))}function oS(e){return e!==void 0&&/^[0-9a-f]{64}$/u.test(e)}function HR(e,t,n){let r=e.PATH;if(r===void 0)return O(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)=>Zt(t).join(a,s)));return b(function*(){for(let a of o)if((yield*We(p({try:()=>n.access(a),catch:(c)=>c})))._tag==="Success")return a;return})}function RL(e,t,n){if(n==="win32")return Zt(n).join(e,t==="bun"?"ctx7.exe":"ctx7.cmd");return t==="npm"?Zt(n).join(e,"bin","ctx7"):Zt(n).join(e,"ctx7")}function TL(e,t){return p({try:()=>e.realpath(t),catch:()=>t}).pipe($t((n)=>O(n)))}function Oo(e){return e.match(/\b(\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?)\b/u)?.[1]}function aS(e){return U({try:()=>{let t=Me(mL)(JSON.parse(e));if(Ke(t))return t.success;throw t.failure},catch:(t)=>t})}function JR(e){return typeof e.bin==="string"?e.bin:e.bin?.ctx7}function Io(e){if(e instanceof Error)return e.message.slice(0,512);if(typeof e==="string")return e.slice(0,512);return"unknown error"}function kL(e){return YR(e)&&e.code==="ENOENT"||/\b(?:e?noent|not found|does not exist|missing)\b/iu.test(Io(e))}function IL(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 PL(e,t){return me(fn(e,t.executable,["root","--global"]),(n)=>{let r=n.stdout.trim();return n.exitCode===0&&r.length>0?Zt(e.platform).join(r,"ctx7"):void 0})}function KR(e,t){return me(fn(e,t.family==="bun"&&Ga(e)?e.processPath:t.executable,t.family==="bun"?["pm","view","ctx7","version"]:["view","ctx7","version"]),(n)=>n.exitCode!==0?void 0:Oo(n.stdout))}function ml(e,t){return[t,`${t}.exe`,`${t}.cmd`,`${t}.js`,`${t}.cjs`].some((n)=>e.endsWith(`/${n}`))}function yl(e,t,n){let r=Zt(n),i=r.resolve(e),o=r.resolve(t);return n==="win32"?$n(i)===$n(o):i===o}function GR(e,t,n){return A(xl(e,t,n))}function xl(e,t,n){if(yl(t,n,e.platform))return O(!0);let r=e.files??Ya;return Pn([p({try:()=>r.realpath(t),catch:(i)=>i}),p({try:()=>r.realpath(n),catch:(i)=>i})]).pipe(me(([i,o])=>yl(i,o,e.platform)),$t(()=>O(!1)))}function Zt(e){return e==="win32"?lL:cL}function $n(e){return e.replaceAll("\\","/").toLowerCase().replace(/\/$/u,"")}function YR(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}var Un="ctx7@latest",fL,dL=(e)=>p({try:e,catch:(t)=>t}),fn=(e,t,n)=>p({try:()=>e.run(t,n),catch:(r)=>r}),pL,mL,Ya,ve;var Pd=L(()=>{ht();Fe();It();Ue();fL=uL(iL),pL=E({code:w(H([Ye,_])),stdout:w(_),stderr:w(_)}),mL=ye(E({version:w(_),bin:w(H([_,Pe(_,_)]))}),[Pe(_,Ge)]),Ya={access:oL,readText:(e)=>aL(e,"utf8"),realpath:sL};ve=class ve extends Error{code;details;constructor(e,t,n={}){super(t);this.code=e;this.details=n;this.name="ToolingError"}}});var cT={};ck(cT,{doctorHolyCodex:()=>QR,doctorHolyCodexEffect:()=>Md,inspectRemovalConflicts:()=>ML,inspectRemovalConflictsEffect:()=>bl,removeHolyCodex:()=>eT,removeHolyCodexEffect:()=>Dd,upgradeHolyCodex:()=>tT,upgradeHolyCodexEffect:()=>nT});import{createHash as XR}from"crypto";import{rm as Ad,rmdir as lS}from"fs/promises";import{join as OL,relative as AL}from"path";function QR(e={},t=process.env){return A(Md(e,t))}function Md(e,t){return b(function*(){let n=rr(e,t),r={},i=yield*q(()=>Co(n.codexHome)).pipe(Ae(()=>q(()=>Co(n.stateRoot))),de({onFailure:(d)=>({error:d}),onSuccess:()=>({error:void 0})}));r.paths=i.error===void 0?Za({state_root:n.stateRoot}):Nt(["path_symlink"],{error:or(i.error)});let o=yield*q(()=>Xa(n)).pipe(de({onFailure:(d)=>({error:d}),onSuccess:(d)=>({active:d})})),a="active"in o?o.active:void 0;if("error"in o)r.configuration=Nt(["state_corrupt"],{error:or(o.error)});let s=yield*q(()=>ei(n.preparingRecord,a)).pipe(de({onFailure:(d)=>({error:d}),onSuccess:(d)=>({preparing:d})})),c=yield*q(()=>ei(n.conflictedRecord,a)).pipe(de({onFailure:(d)=>({error:d}),onSuccess:(d)=>({conflicted:d})})),u="preparing"in s?s.preparing:void 0,l="conflicted"in c?c.conflicted:void 0;for(let[d,x]of[[s,n.preparingRecord],[c,n.conflictedRecord]])if("error"in d)r.transaction=Nt(["state_corrupt"],{path:x,error:or(d.error)});if(r.transaction?.status!=="failed"&&(u!==void 0||l!==void 0)){let d=Fd(a,u,l),x=[...new Set(d.map((S)=>{if(S.relation==="stale")return"stale_transaction_state";if(S.relation==="incompatible")return"incompatible_transaction_state";return S.status==="preparing"?"incomplete_install_state":"conflicted_state"}))];r.transaction=Nt(x,{recovery:d.map((S)=>S.recovery).join(","),transactions:d.map((S)=>`${S.status}:${S.relation}:${S.install_id}:${S.digest}`).join(","),active:a===void 0?"absent":`${a.install_id}:${a.digest}`})}if(!r.configuration)if(!a)r.configuration=Nt(["configuration_missing"]);else if(yield*q(()=>Rl(a)))r.configuration=Za({profile:a.profile,tier:a.tier,install_id:a.install_id});else r.configuration=Nt(["configuration_changed"],{path:n.activeRecord});if(a){r.runtime_config=yield*VL(n,a),r.native_roles=yield*qL(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},a.managed_artifacts);let d=Object.entries(a.capability_state??{}).find(([x,S])=>x!=="browser_use"&&S.selected&&S.status!=="healthy");if(d)r.capabilities=Nt(["selected_capability_not_healthy"],{capability:d[0],status:d[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 f=e.runtime??Ao(t),h=yield*q(()=>nS(f,a?.tooling?.context7)).pipe(de({onFailure:(d)=>({error:d}),onSuccess:(d)=>({context7:d})}));if("context7"in h)r.context7=Za({manager:h.context7.manager,version:h.context7.version,executable:h.context7.executable,ownership:h.context7.ownership});else r.context7={status:"warning",reasons:["context7_unavailable"],details:{error:or(h.error)}};let g=yield*q(()=>xe(`${n.codexHome}/agents/root.toml`)).pipe(de({onFailure:(d)=>({error:d}),onSuccess:(d)=>({legacyRoot:d})}));if("legacyRoot"in g){let d=g.legacyRoot;if(d!==void 0&&Ja(d)){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=Nt(["native_role_invalid"],{error:or(g.error)});let y=e.officialPluginManager;if(a&&y?.status){let d=[...new Set([Qt,...Oa({browser_use:a.optional_selections.browser_use,computer_use:a.optional_selections.computer_use,sites:a.optional_selections.sites,"session-audit":a.optional_selections["session-audit"],"auto-reset":a.optional_selections["auto-reset"]},a.official_plugins),...(a.owned_plugins??[]).filter((S)=>S!==Xt)])].filter((S)=>S!==Xt),x=yield*q(()=>y.status(d)).pipe(de({onFailure:(S)=>({error:S}),onSuccess:(S)=>({status:S})}));if("status"in x){let S=x.status,C=Object.entries(S).filter(([,F])=>F!=="installed").map(([F])=>F),T=y.getObservedIdentities?.()??{};r.native_plugins=C.length===0?Za({status:S,observed_identities:T}):Nt(["native_plugin_disagreement"],{missing:C,status:S,observed_identities:T})}else r.native_plugins=Nt(["native_plugin_status_failed"],{error:or(x.error)})}else r.native_plugins=Nt(["native_plugin_status_unavailable"],{reason:"No read-only live official plugin status source is available."});let v=Object.values(r).flatMap((d)=>d.reasons);return{healthy:Object.values(r).every((d)=>d.status!=="failed"),checks:r,reasons:[...new Set(v)]}})}function ML(e={},t=process.env){return A(bl(e,t))}function bl(e,t){return b(function*(){let n=rr(e,t);yield*q(()=>Co(n.codexHome)),yield*q(()=>Co(n.stateRoot));let r=yield*q(()=>Xa(n));if(r!==void 0&&!(yield*q(()=>Rl(r))))return yield*m(new k("state_corrupt","The HolyCodex ownership record has an invalid digest and cannot authorize removal.",void 0,{path:n.activeRecord}));let i=yield*q(()=>ei(n.preparingRecord,r)),o=yield*q(()=>ei(n.conflictedRecord,r));yield*U({try:()=>mS(r,i,o),catch:(h)=>h});let a=sT(r,i,o);if(a===void 0)return[];let s=yield*q(()=>xe(n.configFile)),c=yield*U({try:()=>Mt(s),catch:(h)=>h}),u=[],l=a.managed_config;if(l!==void 0){let h=yield*q(()=>$a(c,l,{schema:l.schema,installId:l.installId}));for(let g of[...h.preservedKeys,...h.unresolvedKeys])u.push(yield*cS(n.configFile,g,c,"config-key","This managed Codex setting changed after installation."))}if(a.plugin_config!==void 0){let h=yield*q(()=>El(c,a.plugin_config,{allowBeforeState:!0}));for(let g of h.preserved){let y=g==="preference"?'plugins."holycodex@holycodex"':"marketplaces.holycodex";u.push(yield*cS(n.configFile,y,c,"plugin-config","This HolyCodex plugin setting differs from the recorded install state."))}}let f=a.provider_config;if(f!==void 0){let h=yield*q(()=>vl(c,Nd(f),new Set(fS(a)),{allowBeforeState:!0}));for(let g of h.preserved){let y=`plugins.${JSON.stringify(g)}`;u.push(yield*cS(n.configFile,y,c,"plugin-config",`The ${g} plugin setting differs from the recorded install state.`))}}return u.push(...yield*q(()=>NR(n.codexHome,a.managed_artifacts))),[...new Map(u.map((h)=>[Nr(h),h])).values()]})}function eT(e={},t=process.env){return A(Dd(e,t))}function Dd(e,t){return b(function*(){let n=rr(e,t);yield*q(()=>Co(n.codexHome)),yield*q(()=>Co(n.stateRoot));let r=yield*q(()=>Xa(n));if(r&&!(yield*q(()=>Rl(r))))return yield*m(new k("state_corrupt","The HolyCodex ownership record has an invalid digest and cannot authorize removal.",void 0,{path:n.activeRecord}));let i=yield*q(()=>ei(n.preparingRecord,r)),o=yield*q(()=>ei(n.conflictedRecord,r));yield*U({try:()=>mS(r,i,o),catch:(I)=>I});let a=sT(r,i,o);Od(e,{stage:"removal",status:"started",message:"Removing HolyCodex-owned state"});let s=new Set(fS(a)),c=[],u=[],l=[],f=!1,h=()=>(Od(e,{stage:"removal",status:"completed",message:"HolyCodex removal preserved state for review"}),{removed:c,preserved:u,reasons:l});if(a===void 0)return Od(e,{stage:"removal",status:"completed",message:"Nothing to remove"}),{removed:c,preserved:u,reasons:l};let g=yield*bl(e,t),y=yield*jL(e,g),v=yield*q(()=>xe(n.configFile)),d=yield*U({try:()=>Mt(v),catch:(I)=>I}),x=g.filter((I)=>I.key!==void 0&&y.has(Nr(I))),S=new Map;for(let I of g){if(I.key!==void 0||!y.has(Nr(I)))continue;let B=oT(I);if(B!==void 0)S.set(I.path,B)}yield*BL(n,d,x,S);let C=a?.managed_config;if(C){let I=yield*q(()=>$a(d,C,{schema:C.schema,installId:C.installId}));if(I.preservedKeys.length>0||I.unresolvedKeys.length>0){let be=[...I.preservedKeys,...I.unresolvedKeys].map((ae)=>({path:n.configFile,key:ae,action:"remove"}));for(let ae of be)if(y.has(Nr(ae)))d=Cn(d,ae.key)}}if(a?.plugin_config){let I=a.plugin_config,B=yield*q(()=>El(d,I,{allowBeforeState:!0}));if(B.preserved.length>0){let be=B.preserved.map((ae)=>({path:n.configFile,key:ae==="preference"?'plugins."holycodex@holycodex"':"marketplaces.holycodex",action:"remove"}));for(let ae of B.preserved){let St=be.find((X)=>X.key===(ae==="preference"?'plugins."holycodex@holycodex"':"marketplaces.holycodex"));if(St===void 0||!y.has(Nr(St)))continue;d=Cn(d,ae==="preference"?'plugins."holycodex@holycodex"':"marketplaces.holycodex")}}}if(a?.provider_config){let I=a.provider_config,B=yield*q(()=>vl(d,Nd(I),s,{allowBeforeState:!0}));if(B.preserved.length>0){let be=B.preserved.map((ae)=>({path:n.configFile,key:`plugins."${ae}"`,action:"remove"}));for(let ae of B.preserved){let St=be.find((X)=>X.key===`plugins."${ae}"`);if(St===void 0||!y.has(Nr(St)))continue;d=Cn(d,`plugins."${ae}"`)}}}let T,F;if(s.size>0){if(T=e.officialPluginManager,T===void 0)T=yield*q(()=>Or.discover({...t,CODEX_HOME:n.codexHome})).pipe($t((B)=>m(new k("capability_denied","Native Codex plugin removal is unavailable.",B,{operation:"discover Codex",plugins:[...s].join(","),recovery:"Install or expose Codex, then retry."}))));if(T===void 0||!T.remove||!T.list)return yield*m(new k("capability_denied","Native Codex plugin removal and readback are unavailable.",void 0,{operation:"prepare plugin removal",plugins:[...s].join(",")}));let I=T;F=yield*q(()=>I.list()).pipe($t((B)=>m(new k("capability_denied","Codex plugin state could not be read before removing HolyCodex-owned plugins.",B,{operation:"read Codex plugin state",plugins:[...s].join(","),recovery:"Repair or expose Codex, then retry removal."}))))}let J,j=a,K=yield*b(function*(){let I=d,B=C;if(B){let ae=yield*q(()=>$a(I,B,{schema:B.schema,installId:B.installId})),St=[...ae.preservedKeys,...ae.unresolvedKeys];if(St.filter((ct)=>!y.has(Nr({path:n.configFile,key:ct,action:"remove"}))).length>0)return u.push(n.configFile),l.push("managed_config_changed"),yield*ir(n,a??No()),{preserved:h()};if(I=ae.document,St.length>0){let ct=new Set(St);B={...ae.state,managed:Object.fromEntries(Object.entries(ae.state.managed).filter(([Vn])=>!ct.has(Vn)))}}else B=ae.state}if(a?.plugin_config){let ae=yield*q(()=>El(I,a.plugin_config,{allowBeforeState:!0}));if(ae.preserved.length>0)return u.push(n.configFile),l.push("plugin_config_changed"),yield*ir(n,a),{preserved:h()};I=ae.document}if(a?.provider_config){let ae=yield*q(()=>vl(I,Nd(a.provider_config),s,{allowBeforeState:!0}));if(ae.preserved.length>0)return u.push(n.configFile),l.push("provider_config_changed"),yield*ir(n,a),{preserved:h()};I=ae.document}let be=fe(I,"default_permissions")==="holycodex"&&fe(I,"permissions.holycodex")===void 0;if(be)I=Cn(I,"default_permissions");if(a?.managed_config||a?.plugin_config||a?.provider_config||be)J=B===void 0?{document:I}:{document:I,state:B};if(J!==void 0){if(Object.keys(J.document).length===0&&v===void 0)yield*ZR(n.configFile,v),yield*q(()=>Ad(n.configFile,{force:!1}));else yield*ZR(n.configFile,v),yield*q(()=>yt(n.configFile,Mr(J.document)));j={...a,managed_config:J.state},yield*ir(n,j),f=!0}return{complete:!0}}).pipe(de({onFailure:(I)=>({error:I}),onSuccess:(I)=>({result:I})}));if("result"in K&&"preserved"in K.result)return K.result.preserved;if("error"in K){let I=K.error;if(I instanceof k)return yield*ir(n,j??No()),yield*m(I);return u.push(n.configFile),l.push("managed_config_write_failed"),yield*ir(n,j??No()),h()}let Ce=yield*q(()=>Cd(n.codexHome,a?.managed_artifacts??[],S));if(c.push(...Ce.removed),u.push(...Ce.preserved),Ce.preserved.length>0)return l.push("managed_artifact_changed"),yield*ir(n,j??a??No()),h();c.push(...yield*LL(n.roleRoot,a?.managed_artifacts??[]));for(let I of s){let B=yield*b(function*(){if(T?.list===void 0||T.remove===void 0||F===void 0)return yield*m(new k("capability_denied","Codex plugin state is unavailable for a HolyCodex-owned plugin.",void 0,{operation:"remove Codex plugin",plugin_id:I}));let ae=zL(F,I);if(ae?.entry.installed!==!0)return;let St=ae.entry.pluginId;yield*q(()=>T.remove(St));let X=yield*q(()=>T.list());if(F=X,Cr(X,I)?.entry?.installed===!0||[...X.installed,...X.available].some((Oe)=>Oe.pluginId===I&&Oe.installed))return yield*m(new k("capability_denied",`Codex still reports ${I} after removal.`));if(J!==void 0)yield*DL(n,J.document,I);c.push(I)}).pipe(de({onFailure:(be)=>({error:be}),onSuccess:()=>({success:!0})}));if("error"in B){let be=B.error;return l.push("native_plugin_remove_failed"),yield*ir(n,j??No()),yield*m(new k("capability_denied",`Codex native plugin removal did not converge for ${I}: ${or(be)}`,be))}}let Y=yield*q(()=>Sl(e.runtime??Ao(t),a.tooling?.context7)).pipe(de({onFailure:(I)=>({error:I}),onSuccess:(I)=>({removedContext7:I})}));if("error"in Y){let I=Y.error;return l.push("context7_remove_failed"),yield*ir(n,j??No()),yield*m(new k("capability_denied",`Context7 removal did not converge: ${or(I)}`,I))}if(Y.removedContext7)c.push("ctx7");if(r){let I=yield*q(()=>Ad(n.activeRecord,{force:!1})).pipe(de({onFailure:(B)=>({error:B}),onSuccess:()=>({success:!0})}));if("success"in I)c.push(n.activeRecord);else{let B=I.error;if(!Ze(B,"ENOENT"))return u.push(n.activeRecord),l.push("state_remove_failed"),yield*ir(n,a??r),h()}}if(u.length===0){let I=yield*q(()=>Ad(n.installOptions,{force:!1})).pipe(de({onFailure:(B)=>({error:B}),onSuccess:()=>({success:!0})}));if("success"in I)c.push(n.installOptions);else{let B=I.error;if(!Ze(B,"ENOENT"))u.push(n.installOptions),l.push("state_remove_failed"),yield*ir(n,a??r??No())}}if(u.length===0)for(let[I,B]of[[n.preparingRecord,i!==void 0],[n.conflictedRecord,o!==void 0||f]]){if(!B)continue;if("success"in(yield*WL(I).pipe(de({onFailure:(ae)=>({error:ae}),onSuccess:()=>({success:!0})}))))c.push(I);else u.push(I),l.push("state_remove_failed")}if(u.length===0){let I=yield*q(()=>lS(n.roleRoot)).pipe(de({onFailure:(B)=>({error:B}),onSuccess:()=>({success:!0})}));if("success"in I)c.push(n.roleRoot);else{let B=I.error;if(!Ze(B,"ENOENT"))u.push(n.roleRoot),l.push("role_directory_not_empty")}}if(u.length===0){let I=yield*q(()=>lS(n.stateRoot)).pipe(de({onFailure:(B)=>({error:B}),onSuccess:()=>({success:!0})}));if("success"in I)c.push(n.stateRoot);else{let B=I.error;if(Ze(B,"ENOENT"))c.push(n.stateRoot);else u.push(n.stateRoot),l.push("state_directory_not_empty")}}return Od(e,{stage:"removal",status:"completed",message:u.length===0&&l.length===0?"HolyCodex removal complete":"HolyCodex removal preserved state for review"}),{removed:c,preserved:u,reasons:l}})}function DL(e,t,n){return b(function*(){let r=yield*q(()=>xe(e.configFile));if(r===void 0)return;let i=yield*U({try:()=>Mt(r,e.configFile),catch:(f)=>f}),o=i.plugins;if(!sS(o))return;let a=o[n];if(!sS(a)||Object.keys(a).length!==1||a.enabled!==!1)return;let s=t.plugins,c=sS(s)?s[n]:void 0,u={...o};if(c===void 0)delete u[n];else u[n]=c;let l={...i};if(Object.keys(u).length===0)delete l.plugins;else l.plugins=u;yield*q(()=>yt(e.configFile,Mr(l)))})}function sS(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function LL(e,t){return b(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=OL(e,i),a=yield*q(()=>lS(o)).pipe(de({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*m(s)}}return r})}function tT(e={},t=process.env,n={}){return A(nT(e,t,n))}function nT(e,t,n){return b(function*(){let r=rr(e,t),i=yield*q(()=>Xa(r)),o=yield*q(()=>ei(r.preparingRecord,i)),a=yield*q(()=>ei(r.conflictedRecord,i));if(i!==void 0&&!(yield*q(()=>Rl(i))))return yield*m(new k("state_corrupt","The existing HolyCodex configuration has changed and cannot be upgraded safely.",void 0,{path:r.activeRecord}));yield*U({try:()=>pS(i,o,a),catch:(X)=>X});let s=aT(i,o,a),c=s??i;if(c===void 0)return yield*m(new k("not_installed","HolyCodex is not installed in the selected Codex home.",void 0,{recovery:"Run `holycodex install --yes` first."}));let u=yield*q(()=>dS(r)),l=u===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,"session-audit":c.optional_selections["session-audit"],"auto-reset":c.optional_selections["auto-reset"]},officialPlugins:FL(c)}:UL(_l(u)),f=n.options===void 0?l:yield*U({try:()=>en(n.options),catch:(X)=>X}),h={profile:f.profile??l.profile,tier:f.tier??l.tier,optional:{...l.optional,...f.optional},officialPlugins:f.officialPlugins??l.officialPlugins},g=!$L(h,l),y=yield*q(()=>qy()).pipe($t((X)=>m(new k("upgrade_failed","The running HolyCodex version is unavailable.",X)))),v=y.split("-",1)[0]===c.version.split("-",1)[0]&&y.includes("-dev.")!==c.version.includes("-dev."),d=v?0:Ia(y,c.version);if(d<0)return yield*m(new k("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,S=c.managed_config?.managed[Oi[0]]!==void 0,C=[];if(n.dryRun===!0){let X=yield*q(()=>xe(r.configFile)),ct=yield*U({try:()=>Mt(X),catch:(Oe)=>Oe});if(c.managed_config!==void 0)for(let Oe of Object.keys(c.managed_config.managed)){if(!zc(Oe))continue;if((yield*q(()=>cd(ct,c.managed_config,Oe))).status!=="unchanged")C.push({path:r.configFile,key:Oe,action:"replace"})}if(c.plugin_config!==void 0){let Oe=yield*q(()=>El(ct,c.plugin_config));for(let oi of Oe.preserved){let ai=oi==="preference"?'plugins."holycodex@holycodex"':"marketplaces.holycodex";C.push({path:r.configFile,key:ai,action:"replace"})}}if(c.provider_config!==void 0){let Oe=c.provider_config,oi=yield*q(()=>vl(ct,Nd(Oe),new Set(fS(c))));for(let ai of oi.preserved)C.push({path:r.configFile,key:`plugins."${ai}"`,action:"replace"})}let Vn=yield*q(()=>bd(r.codexHome,c.profile,c.managed_artifacts,c.tier,{browserUse:c.optional_selections.browser_use,computerUse:c.optional_selections.computer_use}));for(let Oe of Vn)C.push(Oe)}let T=e.runtime??Ao(t),F=yield*q(()=>T.run("codex",["debug","models","--bundled"]));if(F.exitCode!==0)return yield*m(new k("upgrade_failed",`The current Codex model catalog could not be read: ${F.stderr||"Codex debug models failed."}`));let J=yield*U({try:()=>JSON.parse(F.stdout),catch:(X)=>X}),j=yield*U({try:()=>vd(J),catch:(X)=>X}),z=`${JSON.stringify(j.catalog,null,2)}
|
|
78
|
+
`,K=XR("sha256").update(z).digest("hex"),Y=c.managed_artifacts.find((X)=>X.path==="holycodex/model-catalog.json")?.digest!==K,I=!1,B=[],be=yield*b(function*(){let X=yield*q(()=>nS(T,c.tooling?.context7)).pipe(de({onFailure:(Oe)=>({error:Oe}),onSuccess:(Oe)=>({context7:Oe})})),ct;if("error"in X){if(c.tooling?.context7!==void 0||!HL(X.error))return yield*m(X.error)}else ct=X.context7;let Vn=c.tooling?.context7;if(Vn?.manager!==ct?.manager)B.push("Context7 manager changed");if(Vn?.version!==ct?.version)B.push("Context7 version changed");if(Vn?.executable===void 0?ct?.executable!==void 0:ct?.executable===void 0||!(yield*q(()=>GR(T,Vn.executable,ct.executable))))B.push("Context7 executable changed");return I||=B.length>0,{driftReasons:B}}).pipe(de({onFailure:(X)=>({error:X}),onSuccess:(X)=>X}));if("error"in be){let X=be.error;I=!0;let ct=typeof X==="object"&&X!==null&&"code"in X&&typeof X.code==="string"?X.code:X instanceof Error?X.name:"inspection failed";B.push(`inspection failed (${ct})`)}else B.push(...be.driftReasons),I||=B.length>0;let ae=[...d>0||v?["version"]:[],...g?["installation options"]:[],...u===void 0?["installation options migration"]:[],...x?["context-management configuration migration"]:[],...S?["auto-compaction configuration cleanup"]:[],...d>0||x||S?["Root/session configuration","specialist role definitions"]:[],...s?["interrupted transaction recovery"]:[],...Y?["current Codex model catalog changed"]:[],...I?[`shared tooling reconciliation (${B.join(", ")})`]:[],...C.map((X)=>`conflict: ${X.path}${X.key===void 0?"":` (${X.key})`} -> ${X.action}`)];if(ae.length===0)return{status:n.dryRun===!0?"dry_run":"current",from_version:c.version,to_version:y,changes:[],record:i,preserved:[],warnings:[],conflicts:C};if(n.dryRun===!0)return{status:"dry_run",from_version:c.version,to_version:y,changes:ae,record:i,preserved:[],warnings:[],conflicts:C};let St=yield*q(()=>hS(h,e,t)).pipe($t((X)=>m(X instanceof k?X:new k("upgrade_failed",`HolyCodex upgrade failed: ${or(X)}`,X))));return{status:"upgraded",from_version:c.version,to_version:y,changes:ae,record:St.record,preserved:St.preserved,warnings:St.warnings}})}function FL(e){let t=new Set(Oa(e.optional_selections));return(e.official_plugins??[]).filter((n)=>n!==Xt&&!rT(n)&&!t.has(n))}function Nd(e){return e.filter((t)=>t.plugin_id!==Xt)}function UL(e){return{...e,...e.officialPlugins===void 0?{}:{officialPlugins:e.officialPlugins.filter((t)=>!rT(t))}}}function rT(e){let t=e.slice(0,e.lastIndexOf("@"));return NL.has(t)}function $L(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 jL(e,t){return b(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(Nr(t[o]));else if(s==="keep")continue;else if(s==="cancel")return yield*m(new k("confirmation_required","Conflict resolution was cancelled.",void 0,{identity:a.identity,path:a.path,...a.key===void 0?{}:{key:a.key}}));else return yield*m(new k("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(Nr(r));continue}if(i==="decline")continue;return yield*m(new k("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 Nr(e){return`${e.action}\x00${e.path}\x00${e.key??""}`}function cS(e,t,n,r,i){let o=fe(n,t);return iT(n,t).pipe(me((a)=>({identity:Nr({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 iT(e,t){let n=fe(e,t),r=n===void 0?{present:!1}:{present:!0,value:n};return q(()=>wn("holycodex-removal-config-review-v1",[_n(Yt(r))]))}function oT(e){if(typeof e.existing!=="object"||e.existing===null)return;let t=e.existing.digest;return typeof t==="string"?t:void 0}function BL(e,t,n,r){return b(function*(){for(let o of n){if(o.key===void 0)continue;let a=oT(o);if(a===void 0||(yield*iT(t,o.key))!==a)return yield*m(uS(o.path,o.key))}let i=yield*q(()=>MR(e.codexHome,r)).pipe(de({onFailure:(o)=>({error:o}),onSuccess:(o)=>({changedNativePaths:o})}));if("error"in i){let o=r.keys().next().value;return yield*m(new k("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*m(uS(i.changedNativePaths[0]))})}function uS(e,t){return new k("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 ZR(e,t){return q(()=>xe(e)).pipe(Ae((n)=>n===t?pt:m(uS(e))))}function VL(e,t){if(!t.managed_config)return O(Nt(["incomplete_install_state"]));return b(function*(){let n=yield*q(()=>xe(e.configFile)),r=yield*U({try:()=>Mt(n),catch:(c)=>c}),i=yield*q(()=>xe(fl(e.codexHome)));if(i===void 0)return Nt(["model_catalog_missing"],{path:fl(e.codexHome)});let o=yield*U({try:()=>JSON.parse(i),catch:(c)=>c}),a=Cl(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:nt.frontend,security:nt.security,sessionAudit:t.optional_selections["session-audit"],autoReset:t.optional_selections["auto-reset"],parentPersonalityNone:To(fe(r,"personality"))},e.codexHome,o),s=[];for(let c of Object.keys(a))if((yield*q(()=>cd(r,t.managed_config,c))).status!=="unchanged")s.push(c);return s.length===0?Za({managed_keys:Object.keys(a).length}):Nt(["changed_holycodex_config"],{keys:s})}).pipe($t((n)=>O(Nt(["config_unreadable"],{error:or(n)}))))}function qL(e,t,n,r={browserUse:!1,computerUse:!1},i=[]){return b(function*(){let o=yield*q(()=>xe(e.configFile)),a=yield*U({try:()=>Mt(o),catch:(h)=>h}),s=[],c=new Map(i.map((h)=>[h.path,h])),u={...r,parentPersonalityNone:To(fe(a,"personality"))},l=ko(t,n,u);for(let h of ji(t,n)){let g=fe(a,`agents."${h.name}".config_file`),y=_o(e.configFile,ul(h.name,l)).replaceAll("\\","/");if(typeof g!=="string"||_o(e.configFile,g).replaceAll("\\","/")!==y){s.push(`${h.name}:registration`);continue}let v=yield*q(()=>xe(y));if(v===void 0){s.push(`${h.name}:missing`);continue}let d=Mt(v,y),x=AL(e.codexHome,y).replaceAll("\\","/"),S=c.get(x);if(S===void 0||XR("sha256").update(v).digest("hex")!==S.digest){s.push(`${h.name}:changed`);continue}if(d.personality!==(u.parentPersonalityNone?"friendly":"none")){s.push(`${h.name}:personality_changed`);continue}if(v!==dl(h,u)){s.push(`${h.name}:changed`);continue}}let f=yield*q(()=>xe(`${e.codexHome}/agents/root.toml`));if(f!==void 0&&Ja(f))s.push("root:stale");return s.length===0?Za({role_root:e.roleRoot,agent_types:ji(t,n).map((h)=>h.name)}):Nt(["native_role_disagreement"],{roles:s})}).pipe($t((o)=>O(Nt(["native_role_invalid"],{error:or(o)}))))}function ir(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(ot(Fi,n)!==void 0)return q(()=>al(e.conflictedRecord,Yt(n)));return pt}function aT(e,t,n){return[n,t].find((r)=>r!==void 0&&(e===void 0||wl(r,e)))}function sT(e,t,n){return aT(e,t,n)??e}function No(){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,"session-audit":!1,"auto-reset":!1,coding:!0},explicit_optional_selections:{},managed_artifacts:[],installed_at:new Date(0).toISOString()}}function fS(e){if(e?.owned_plugins!==void 0)return[...new Set(e.owned_plugins)].filter((i)=>i!==Xt);let t=(e?.plugin_snapshot??[]).filter((i)=>i.plugin_id!==Xt&&(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"?[Qt]:[],r=(e?.provider_config??[]).filter((i)=>i.plugin_id!==Xt&&i.before.presence==="absent"&&i.after.presence==="present").map((i)=>i.plugin_id);return[...new Set([...t,...n,...r])]}function zL(e,t){let n=Cr(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 Za(e){return{status:"healthy",reasons:[],details:e}}function Nt(e,t={}){return{status:"failed",reasons:e,details:t}}function WL(e){return q(()=>Ad(e,{force:!1})).pipe(ge((t)=>Ze(t,"ENOENT"),()=>pt),Mb)}function HL(e){return typeof e==="object"&&e!==null&&"code"in e&&(e.code==="context7_unavailable"||e.code==="context7_manager_unknown")}function or(e){return e instanceof Error?e.message.slice(0,256):"operation failed"}function q(e){return p({try:e,catch:(t)=>t})}function Od(e,t){Le(Qe(U({try:()=>e.onProgress?.(t),catch:(n)=>n})))}var NL;var Ld=L(()=>{wo();ht();Fe();Tl();fd();cl();Ky();Rd();pl();Ro();nl();Wa();Pd();NL=new Set(["documents","pdf","presentations","spreadsheets","template-creator"])});import{lstat as hT,open as JL,rm as RS}from"fs/promises";import{homedir as KL}from"os";import{dirname as GL,join as YL}from"path";function en(e){let t=ot(hd,e);if(t===void 0)throw new k("install_failed","The installation options are invalid.");let n=t;return gT(n),n}function gT(e){if(e.officialPlugins?.includes(Xt)!==!0)return;throw new k("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:Xt})}function dS(e){return A(yT(e))}function yT(e){return b(function*(){let t=yield*p({try:()=>xe(e.installOptions),catch:(n)=>n});return ST(t,e.installOptions)})}function ST(e,t){if(e===void 0)return;let n=Le(U({try:()=>rl(e),catch:(o)=>new k("state_corrupt","The HolyCodex install options are not valid TOML.",o,{path:t})})),r=ot(tl,n);if(r!==void 0)return r;let i=ot(tR,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"||o==="session-audit"||o==="auto-reset").concat(...["browser_use","sites"].filter((o)=>!i.capabilities.includes(o))),additional_plugins:i.additional_plugins};if(r===void 0)throw new k("state_corrupt","The HolyCodex install options are invalid.",void 0,{path:t});return r}function QL(e,t){return A(xT(e,t))}function xT(e,t){if(ot(tl,t)===void 0)return m(new k("state_corrupt","The HolyCodex install options are invalid."));return p({try:()=>yt(e.installOptions,il(t)),catch:(n)=>n})}function _l(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"),"session-audit":e.capabilities.includes("session-audit"),"auto-reset":e.capabilities.includes("auto-reset")},officialPlugins:e.additional_plugins.filter((t)=>t!==Xt)}}function ET(e={},t=process.env){return b(function*(){let n=rr(e,t),r=yield*yT(n);if(r!==void 0)return _l(r);let i=yield*TS(n);if(i===void 0)return{};return{profile:i.profile,tier:i.tier,optional:i.optional_selections,officialPlugins:CS(i)}})}function vT(e,t,n,r){let i=["browser_use","computer_use","sites","session-audit","auto-reset"].filter((o)=>n[o]);return{schema_version:1,profile:e,tier:t,capabilities:i,additional_plugins:[...new Set(r)].filter((o)=>o!==Xt)}}function wl(e,t){return e.install_id===t.install_id&&e.digest===t.digest}function Fd(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})=>wl(a,r[0].record));return r.map(({status:a,record:s})=>{let c=e===void 0?i&&!o?"incompatible":"orphaned":wl(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 pS(e,t,n){let r=Fd(e,t,n);if(r.filter((o)=>o.relation==="stale"||o.relation==="incompatible").length>0)throw new k("state_corrupt","HolyCodex has stale or incompatible transaction state and cannot recover safely.",void 0,bT(r));return r}function mS(e,t,n){let r=Fd(e,t,n);if(e===void 0&&r.some((i)=>i.relation==="incompatible"))throw new k("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 Al(e={},t={},n=process.env){return b(function*(){let r=ot(el,e);if(r===void 0)return yield*m(new k("install_failed","The installation options are invalid."));gT(r);let i=rr(t,n),o=yield*p({try:()=>xe(i.installOptions),catch:(P)=>P}),a=ST(o,i.installOptions),s=a===void 0?void 0:_l(a);sr(t,{stage:"validation",status:"started",message:"Validating Codex target"});let c=yield*TS(i),u=yield*p({try:()=>xe(i.activeRecord),catch:(P)=>P});if(c!==void 0&&!(yield*Pl(c)))return yield*m(new k("state_corrupt","The existing HolyCodex configuration has changed and cannot be replaced.",void 0,{path:i.activeRecord}));let l=yield*bS(i.preparingRecord,c),f=yield*bS(i.conflictedRecord,c);pS(c,l,f);let h=[f,l].find((P)=>P!==void 0&&(c===void 0||wl(P,c)));if(h!==void 0){let{removeHolyCodex:P}=yield*p({try:()=>Promise.resolve().then(() => (Ld(),cT)),catch:(V)=>V}),W=yield*p({try:()=>P(t,n),catch:(V)=>V});if(W.preserved.length>0||W.reasons.length>0)return yield*m(new k("state_corrupt","The interrupted HolyCodex installation could not be reconciled safely.",void 0,{preserved:W.preserved.join(","),reasons:W.reasons.join(",")}));return yield*Al({profile:e.profile??s?.profile??h.profile,tier:e.tier??s?.tier??h.tier,optional:{browser_use:e.optional?.browser_use??s?.optional?.browser_use??h.optional_selections.browser_use,computer_use:e.optional?.computer_use??s?.optional?.computer_use??h.optional_selections.computer_use,sites:e.optional?.sites??s?.optional?.sites??h.optional_selections.sites},officialPlugins:e.officialPlugins??s?.officialPlugins??CS(h)},t,n)}let g=CF(e.profile??s?.profile,c?.profile),y=RF(e.tier??s?.tier,c?.tier),v=s?.optional,d=vS(v,e.optional),x=TF(d,c?.optional_selections),S=vS(vS(c?.explicit_optional_selections,v),e.optional),C=e.officialPlugins??s?.officialPlugins??CS(c),T=t.runtime??Ao(n),F=yield*p({try:()=>kd(T,!1,c?.tooling?.context7),catch:(P)=>P}).pipe(de({onFailure:()=>!1,onSuccess:()=>!0})),J,j,z=[...new Set(Oa(_T(x),C).map((P)=>Mn(P)??P))],K=t.officialPluginManager??(yield*p({try:()=>Or.discover({...n,CODEX_HOME:i.codexHome}),catch:(P)=>new k("capability_denied","Native Codex plugin installation is unavailable.",P,{recovery:"Install or expose Codex, then retry."})}));if(!K.addMarketplace||!K.add||!K.list)return yield*m(new k("install_failed","Native Codex plugin installation and verification are unavailable."));let Ce=c?.install_id??crypto.randomUUID().replaceAll("-",""),Y=yield*zy(),I=c!==void 0&&c.version!==Y&&c.owned_plugins?.includes(Qt)===!0?new Set([Qt]):new Set,B=new Set((c?.owned_plugins??[]).filter((P)=>P!==Xt)),be=new Set([Qt,...z]),ae=[...B].filter((P)=>!be.has(P));if(ae.length>0&&K.remove===void 0)return yield*m(new k("install_failed","Native Codex cannot remove previously managed plugins omitted from the new selection.",void 0,{plugins:ae.join(",")}));let St=(t.now?.()??new Date).toISOString(),X=yield*pF(T),ct=X.json,Vn=Jy(X.catalog,_d(g,y).model),Oe=yield*p({try:()=>xe(i.configFile),catch:(P)=>P}),oi=Le(U({try:()=>Mt(Oe,i.configFile),catch:(P)=>P}).pipe(de({onFailure:(P)=>({error:P}),onSuccess:(P)=>({document:P})})));if("error"in oi){let P=oi.error;if(P instanceof k&&P.code==="state_corrupt")yield*cF(t,P,i.configFile);return yield*m(P)}let ai=oi.document,Yd=To(fe(ai,"personality")),Uo=Cl(g,y,{browserUse:x.browser_use,computerUse:x.computer_use,frontend:nt.frontend,security:nt.security,sessionAudit:x["session-audit"],autoReset:x["auto-reset"],parentPersonalityNone:Yd},i.codexHome,X.catalog),Zd=c?.managed_config??ad({schema:yn,installId:Ce}),HS=yield*jd(ai,Zd),Xd=yield*iF(t,i.configFile,HS.document,['plugins."holycodex@holycodex"',"marketplaces.holycodex",...Object.keys(Uo)]),{document:ns,conflicts:Tn,decisions:Bl}=Xd,Qd=Tn.length===0?ai:Qa(ai,Tn,Bl),dn;if(Tn.length>0){if((yield*p({try:()=>xe(i.configFile),catch:(W)=>W}))!==Oe)return yield*m(new k("confirmation_required","Codex configuration changed after the invalid-table review; review the latest configuration and retry.",void 0,{path:i.configFile}));dn=Mr(Qd),yield*p({try:()=>yt(i.configFile,dn),catch:(W)=>W})}let Vl,JS=!1,ql,KS=new Map,ep=yield*p({try:()=>K.list(),catch:(P)=>P}).pipe(de({onFailure:(P)=>({error:P}),onSuccess:(P)=>({live:P})}));if("live"in ep)Vl=ep.live;else{let P=ep.error;if(dn!==void 0)yield*SS(i.configFile,Oe,dn),dn=void 0;if(!IF(P))return yield*m(new k("capability_denied","Native Codex plugin state could not be read safely.",P));if((yield*p({try:()=>xe(i.configFile),catch:(ne)=>ne}))!==Oe)return yield*m(new k("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 W=fe(ns,"marketplaces.holycodex"),V=Tn.some((ne)=>ne.key==="marketplaces"&&Bl.get(ne.identity)==="remove");if(W===void 0&&!V)return yield*m(new k("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(W!==void 0&&!PF(W))ql=Bn({path:i.configFile,key:"marketplaces.holycodex",action:"replace",category:"config-key",target:"marketplaces.holycodex",existing:W,desired:{source_type:"git",source:ti},explanation:"The existing HolyCodex marketplace source must be reviewed before rebuilding its incomplete cache from the required canonical source.",defaultDecision:"replace",validDecisions:["replace","cancel"]}),KS=(yield*Ol(t,[ql],!0)).decisions;if(!(ri(W)&&Object.keys(W).length===2&&W.source_type==="git"&&W.source===ti)){if((yield*p({try:()=>xe(i.configFile),catch:(he)=>he}))!==Oe)return yield*m(new k("confirmation_required","Codex configuration changed before marketplace repair; review the current source and retry.",P,{path:i.configFile,key:"marketplaces.holycodex"}));let ne=Dr(ns,"marketplaces",Do,{source_type:"git",source:ti});dn=Mr(ne),yield*p({try:()=>yt(i.configFile,dn),catch:(he)=>he})}if(K.addMarketplace===void 0)return yield*m(new k("capability_denied","Native Codex plugin state could not be read safely.",P));let ie=yield*p({try:()=>K.addMarketplace(lT),catch:(ne)=>ne}).pipe(Ae(()=>p({try:()=>K.list(),catch:(ne)=>ne}))).pipe(de({onFailure:(ne)=>({error:ne}),onSuccess:(ne)=>({live:ne})}));if("error"in ie){let ne=ie.error;if(dn!==void 0){let he=dn,je=yield*SS(i.configFile,Oe,he).pipe(de({onFailure:(gt)=>({error:gt}),onSuccess:()=>({restored:!0})}));if("error"in je){let gt=je.error;return yield*m(new k("confirmation_required","The marketplace repair failed and the reviewed temporary Codex configuration could not be restored safely; review config.toml before retrying.",gt,{path:i.configFile,key:"marketplaces.holycodex"}))}dn=void 0}return yield*m(new k("capability_denied","The required HolyCodex marketplace could not be repaired before plugin validation.",ne))}Vl=ie.live,JS=!0}if(dn!==void 0)yield*SS(i.configFile,Oe,dn),dn=void 0;let GS=z.filter((P)=>{if(!P.endsWith("@openai-curated"))return!1;let W=cr(Vl,P);return!(W?.installed&&W.enabled)});sr(t,{stage:"validation",status:"completed",message:"Codex target validated"});let qn=yield*Ud(ns),tp=c?.plugin_config?.before??qn,rs=tp,$o=t.resolveConflicts!==void 0,jo=[],is=[],os=[];if(is=["preference","marketplace"].filter((W)=>{let V=qn[W].digest,Ee=qn[W],ie=W==="preference"?{kind:"boolean",value:!0}:{kind:"marketplace",source_type:"git",source:ti},ne=Ee.presence==="present"&&JSON.stringify(Ee.safe_value)!==JSON.stringify(ie),he=c?.plugin_config!==void 0&&V!==c.plugin_config.after[W].digest&&V!==c.plugin_config.before[W].digest;return ne||he}).map((W)=>{let V=W==="preference"?'plugins."holycodex@holycodex"':"marketplaces.holycodex",Ee=qn[W],ie=W==="preference"?{kind:"boolean",value:!0}:{kind:"marketplace",source_type:"git",source:ti};return Bn({path:i.configFile,key:V,action:"replace",category:"config-key",target:V,existing:Ee.safe_value??{presence:Ee.presence},desired:ie,explanation:`The existing ${V} entry does not match the HolyCodex plugin configuration.`,validDecisions:["replace","cancel"],defaultDecision:"replace"})}),$o)jo.push(...is);let np=[...new Set([...z,...(c?.provider_config??[]).map((P)=>P.plugin_id),...c?.owned_plugins??[]])].filter((P)=>P!==Qt&&P!==Xt),zi=yield*$d(ns,np);{let P=new Set(c?.owned_plugins??[]);if(os=zi.filter((V)=>{let Ee=c?.provider_config?.find((he)=>he.plugin_id===V.plugin_id),ie=P.has(V.plugin_id)&&Ee!==void 0&&V.before.digest!==Ee.after.digest&&V.before.digest!==Ee.before.digest,ne=z.includes(V.plugin_id)&&V.before.presence==="present"&&V.before.safe_value?.value!==!0;return ie||ne}).map((V)=>{let Ee=`plugins."${V.plugin_id}"`;return Bn({path:i.configFile,key:Ee,action:"replace",category:"config-key",target:Ee,existing:V.before.safe_value??{presence:V.before.presence},desired:{kind:"boolean",value:!0},explanation:`The existing provider plugin entry ${V.plugin_id} does not match the selected plugin configuration.`,...z.includes(V.plugin_id)?{validDecisions:["replace","cancel"],defaultDecision:"replace"}:{}})}),$o)jo.push(...os)}let rp=zi.map((P)=>{let W=c?.provider_config?.find((V)=>V.plugin_id===P.plugin_id);return W===void 0?P:{plugin_id:P.plugin_id,before:W.before,after:W.before}}),zl=rp,YS=HS.state,ZS=yield*xS(ns,YS,c),XS=yield*jd(ZS.document,ZS.state),QS=yield*ES(XS.document,XS.state),{document:zn,state:tn}=QS;mF(zn,tn);let si;if(c!==void 0){if(si=Cl(c.profile,c.tier,{browserUse:c.optional_selections.browser_use,computerUse:c.optional_selections.computer_use,frontend:nt.frontend,security:nt.security,sessionAudit:c.optional_selections["session-audit"],autoReset:c.optional_selections["auto-reset"]},i.codexHome,X.catalog),(c.managed_config?.managed["permissions.holycodex.extends"]!==void 0||c.managed_config?.managed["permissions.holycodex.network.enabled"]!==void 0)&&fe(zn,"default_permissions")==="holycodex")si.default_permissions="holycodex";let P=wf(c.version.split("-",1)[0]);for(let W of Gr){let V=c.managed_artifacts.find(({path:Ee})=>Ee.endsWith(`/${W}.toml`));si[`agents."${W}".config_file`]=V?.path??`holycodex/agents/${W}.toml`}if(Ia(P,ZL)<=0)si.model="gpt-6-astra",si.model_reasoning_effort=c.profile==="low"?"low":c.profile==="default"?"medium":"high";else if(c.profile==="high"&&Ia(P,XL)<=0)si.model_reasoning_effort="high";delete si.developer_instructions}let ip=yield*dF(zn,tn,Uo,si),op=yield*Hc(zn,tn,ip,{schema:yn,installId:Ce}).pipe(wt((P)=>P instanceof k?P:new k("state_corrupt","The existing Codex configuration has an incompatible shape for HolyCodex settings.",P,{recovery:"Converge the conflicting Codex setting, then retry."}))).pipe(de({onFailure:(P)=>({error:P}),onSuccess:(P)=>({value:P})}));if("error"in op)return yield*m(op.error);let ci=op.value,li=[];if(ci.driftedKeys.length>0)li=ci.driftedKeys.map((P)=>{let W=tn.managed[P],V=fe(zn,P),Ee=Uo[P];return Bn({path:i.configFile,key:P,action:"replace",category:"config-key",target:P,existing:V??W?.lastManagedValue,desired:Ee,explanation:`The managed Codex setting ${P} changed outside the previous transaction.`})});let Wi=Object.entries(Uo).flatMap(([P,W])=>{let V=P;if(tn.managed[V]!==void 0)return[];let Ee=fe(zn,V);if(Ee===void 0||JSON.stringify(Ee)===JSON.stringify(W))return[];return[Bn({path:i.configFile,key:V,action:"replace",category:"config-key",target:V,existing:Ee,desired:W,explanation:`The existing Codex setting ${V} is user-owned and differs from the HolyCodex install value.`,defaultDecision:"replace",validDecisions:["keep","replace","cancel"]})]});if($o)jo.push(...Wi);if($o)jo.push(...li);let Wl=yield*p({try:()=>bd(i.codexHome,g,c?.managed_artifacts,y,{browserUse:x.browser_use,computerUse:x.computer_use,parentPersonalityNone:Yd},ct),catch:(P)=>new k("install_failed",Il(P),P)});if($o)jo.push(...Wl.map(Bn));let Hl=[...Tn,...is,...os,...Wi,...li,...Wl.map(Bn)],ZT={...ci.state.managed},XT=new Set([...Tn.map((P)=>P.identity),...ql===void 0?[]:[ql.identity]]),QT=($o?jo:Hl).filter((P)=>!XT.has(P.identity)),ex=yield*Ol(t,QT,!0),lr={...ex,decisions:new Map([...Bl,...KS,...ex.decisions])},tx=[],as={...ip},Hi={...tn.managed},nx=()=>b(function*(){tx=Wl.map((ne)=>{let he=Bn(ne),je=lr.decisions.get(he.identity);return je===void 0?he:{...he,decision:je}});let P=yield*fT(zn,zn,tp,rp,qn,zi,is,os,lr.decisions,z),W=Qa(P.document,Tn,lr.decisions);rs=P.pluginConfigBefore,zl=P.providerConfigBefore;let V={...tn.managed},Ee={...ip};for(let ne of[...Wi,...li]){let he=ne.key;if(he===void 0)continue;let je=he,gt=lr.decisions.get(ne.identity);if(gt!=="keep"&>!=="replace")return yield*m(new k("confirmation_required","Managed conflict resolution is incomplete.",void 0,{key:he}));let Fr=V[je],kt=Uo[je];if(kt===void 0)return yield*m(new k("state_corrupt","The managed conflict cannot be verified.",void 0,{path:i.configFile,key:he}));let Ji=fe(zn,je);if(gt==="replace")if(W=Tr(W,je,kt),Fr!==void 0)V[je]={...Fr,lastManagedValue:yield*ln(je,kt)};else{let ui=ZT[je];if(ui!==void 0)V[je]=ui}else{if(delete Ee[je],Fr===void 0)continue;if(Ji===void 0){delete V[je];continue}let ui={...Fr,lastManagedValue:yield*ln(je,Ji)},Vo={...tn,managed:{...V,[je]:ui}};if(bo(Vo))V[je]=ui;else delete V[je]}}if(ci=yield*Hc(W,{...tn,managed:V},Ee,{schema:yn,installId:Ce}),ci.driftedKeys.length>0)return yield*m(new k("state_corrupt","The accepted managed conflicts did not converge."));as=Ee;let ie={...tn.managed};for(let ne of[...Wi,...li]){let he=ne.key;if(he===void 0)continue;delete ie[he]}Hi=ie});yield*nx();let rx=()=>Hl.map((P)=>{let W=Bn(P),V=lr.decisions.get(W.identity);return V===void 0?W:{...W,decision:V}}),ix=(P)=>Object.fromEntries(["config-key","invalid-config","native-plugin","role-asset"].flatMap((W)=>{let V=P.filter((Ee)=>Ee.category===W).length;return V===0?[]:[[W,V]]})),Jl=rx(),ox=ix(Jl),ek=OF(F,Vl,z);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:Y,profile:g,tier:y,capabilities:{browser_use:x.browser_use,computer_use:x.computer_use,sites:x.sites,"session-audit":x["session-audit"],"auto-reset":x["auto-reset"]},additionalPlugins:[...C],conflicts:Jl,conflictCounts:ox,tools:ek});if(P.action==="cancel")return yield*m(new k("confirmation_required","Install review was cancelled."));if(P.action==="resolve"){if(Hl.length===0)return yield*m(new k("confirmation_required","There are no managed conflicts to resolve."));lr=yield*Ol(t,Hl,!0),yield*nx(),Jl=rx(),ox=ix(Jl);continue}if(P.action==="change"){if(P.request===void 0)return yield*m(new k("confirmation_required","Changing install options requires a revised request."));return yield*Al(P.request,t,n)}if(P.action==="apply")break;return yield*m(new k("confirmation_required","Unknown install review action."))}let ap={owner:"holycodex",schema_epoch:yn,install_id:Ce,version:Y,digest:c?.digest??"0".repeat(64),profile:g,tier:y,optional_selections:x,explicit_optional_selections:S,official_plugins:z,capability_state:qd(x),managed_artifacts:c?.managed_artifacts??[],installed_at:St,status:"preparing",step:"validated",managed_config:YS,plugin_snapshot:[],plugin_config:{plugin_id:Qt,before:qn,after:qn},provider_config:zl,owned_plugins:[...B],...c?.tooling?.context7===void 0?{}:{tooling:{context7:c.tooling.context7}}};yield*Ba(i.stateRoot),yield*jn(i.preparingRecord,ap);let ss=[],Lr,sp=!1,ax=!1,sx=new Set,cp=new Set,Kl=new Set,nn=new Set(B),lp=new Set([...B,...z]),up=new Set,pe=ap,cx=!1,cs,Bo,lx,ls=ci.state,ux=!1,fx=!1;return yield*b(function*(){if(Tn.length>0){let D=yield*p({try:()=>xe(i.configFile),catch:(Se)=>Se});if(Qd=Qa(Mt(D,i.configFile),Tn,Bl),(yield*p({try:()=>xe(i.configFile),catch:(Se)=>Se}))!==D)return yield*m(new k("confirmation_required","Codex configuration changed during conflict resolution; review the latest configuration and retry.",void 0,{path:i.configFile}));yield*p({try:()=>yt(i.configFile,Mr(Qd)),catch:(Se)=>Se}),ax=!0}let P=yield*p({try:()=>kd(T,!0,c?.tooling?.context7),catch:(D)=>D}).pipe(de({onFailure:(D)=>({error:D}),onSuccess:(D)=>({value:D})}));if("error"in P)j=`Optional ctx7 is unavailable: ${Il(P.error)}`;else J=P.value;let W=J??c?.tooling?.context7,V=W===void 0?void 0:{context7:W},Ee={...ap,...V===void 0?{}:{tooling:V}};if(pe=Ee,yield*jn(i.preparingRecord,pe),K.ensureOfficialMarketplace!==void 0&&GS.length>0)yield*p({try:()=>K.ensureOfficialMarketplace(GS),catch:(D)=>new k("capability_denied",`The selected official Codex provider marketplace is unavailable: ${Il(D)}`,D,{recovery:"Check Codex network and marketplace policy, then retry."})});ss=yield*hF({list:()=>K.list()},[...new Set([Qt,...z,...B])]).pipe(wt((D)=>new k("capability_denied","Native Codex plugin state could not be read safely.",D))),Ee={...Ee,plugin_snapshot:ss},pe=Ee,yield*jn(i.preparingRecord,pe);let ie=yield*p({try:()=>xe(i.configFile),catch:(D)=>D}),ne=Mt(ie,i.configFile),he=Qa(ne,Tn,lr.decisions);yield*fF(he,qn,zi);let je=yield*xS(he,Zd,c),gt=yield*jd(je.document,je.state),Fr=yield*ES(gt.document,gt.state);cs=he,Bo=Fr.document,yield*pT(Bo,zn,{...tn,managed:Hi},as),sr(t,{stage:"roles",status:"started",message:"Installing subagent roles"}),yield*Ba(i.roleRoot),Lr=yield*p({try:()=>Qy(i.codexHome,g,c?.managed_artifacts,y,Wl.length===0?t.resolveConflict:void 0,tx,{browserUse:x.browser_use,computerUse:x.computer_use,parentPersonalityNone:Yd},ct),catch:(D)=>D}),pe={...Ee,step:"roles_prepared",managed_artifacts:Lr.managed_artifacts},yield*jn(i.preparingRecord,pe),sr(t,{stage:"roles",status:"completed",message:"Subagent roles installed"}),sr(t,{stage:"plugins",status:"started",message:"Installing selected capabilities"}),cx=!0;let kt=cs;if(kt===void 0)return yield*m(new k("state_corrupt","The pre-mutation configuration baseline is missing."));kt=Dr(kt,"plugins",Mo,{enabled:!0}),kt=Dr(kt,"marketplaces",Do,{source_type:"git",source:ti});for(let D of z)kt=Dr(kt,"plugins",D,{enabled:!0});let Ji=yield*Ud(kt),Vo=(yield*$d(kt,np)).map((D)=>({plugin_id:D.plugin_id,before:zi.find((Se)=>Se.plugin_id===D.plugin_id)?.before??D.before,after:D.before}));if(pe={...pe,plugin_config:{plugin_id:Qt,before:qn,after:Ji},provider_config:Vo},yield*jn(i.preparingRecord,pe),Oe===void 0)lx=yield*b(function*(){let D=yield*EF(i.configFile),Se=yield*p({try:()=>xe(i.configFile),catch:(qt)=>qt});if(D===void 0||Se!=="")return yield*m(new k("confirmation_required","Codex config.toml appeared during installation; review the latest configuration and retry.",void 0,{operation:"initialize Codex configuration",path:i.configFile}));return D}).pipe(wt((D)=>D instanceof k?D:new k("permission_denied","Codex config.toml could not be initialized before plugin setup.",D,{operation:"initialize Codex configuration",path:i.configFile,recovery:"Check CODEX_HOME permissions, then retry."}))),ie="";if((yield*p({try:()=>xe(i.configFile),catch:(D)=>D}))!==ie)return yield*m(new k("confirmation_required","Codex configuration changed during plugin setup; review the latest configuration and retry.",void 0,{path:i.configFile}));if(yield*p({try:()=>yt(i.configFile,Mr(kt)),catch:(D)=>D}),sp=!0,!JS)yield*p({try:()=>K.addMarketplace(lT),catch:(D)=>D});yield*bF({list:()=>K.list(),add:(D)=>K.add(D)},[Qt,...z],I,(D,Se)=>b(function*(){if(Se==="new")sx.add(D),nn.add(D),lp.add(D),pe={...pe,owned_plugins:[...nn]};else up.add(D),nn.add(D),lp.add(D),pe={...pe,owned_plugins:[...nn]};yield*jn(i.preparingRecord,pe)})),pe={...pe,step:"plugins_installed"},yield*jn(i.preparingRecord,pe),sr(t,{stage:"plugins",status:"completed",message:"Selected capabilities installed"});let us=yield*p({try:()=>xe(i.configFile),catch:(D)=>D}),fp=Mt(us,i.configFile),tk=Qa(fp,Tn,lr.decisions),dx=yield*xS(tk,Zd,c),px=yield*jd(dx.document,dx.state),nk=yield*ES(px.document,px.state);if(cs===void 0||Bo===void 0)return yield*m(new k("state_corrupt","The pre-mutation configuration baseline is missing."));let dp=yield*fT(nk.document,cs,tp,rp,qn,zi,is,os,lr.decisions,z),Wn=dp.document;for(let D of Object.keys(Hi)){let Se=D,qt=fe(Bo,Se);Wn=qt===void 0?Cn(Wn,Se):Tr(Wn,Se,qt)}let pp="features.context_management.experimental_mode",mx=Hi[pp];if(!Vn&&mx!==void 0){let D=yield*Ai(Wn,{...tn,managed:{[pp]:mx}},{schema:tn.schema,installId:tn.installId});if(D.unresolvedKeys.length>0)return yield*m(new k("state_corrupt","The unsupported context setting cannot be safely released."));Wn=D.document,delete Hi[pp]}rs=dp.pluginConfigBefore,zl=dp.providerConfigBefore;let Gl=yield*Ud(Wn),hx=yield*$d(Wn,np),gx=hx.map((D)=>({plugin_id:D.plugin_id,before:zl.find((Se)=>Se.plugin_id===D.plugin_id)?.before??D.before,after:D.before})),yx=hx.map((D)=>({plugin_id:D.plugin_id,before:zi.find((Se)=>Se.plugin_id===D.plugin_id)?.before??D.before,after:D.before}));pe={...pe,plugin_config:{plugin_id:Qt,before:qn,after:Gl},provider_config:yx};let rk=new Set([...Wi,...li].flatMap((D)=>D.key===void 0?[]:[D.key])),Yl={...Hi};for(let D of[...Wi,...li]){let Se=D.key;if(Se===void 0)continue;let qt=ci.state.managed[Se];if(qt!==void 0)Yl[Se]=qt}for(let[D,Se]of Object.entries(Yl)){if(rk.has(D))continue;let qt=D,fs=fe(Bo,qt);Yl[qt]={...Se,...fs===void 0?{}:{lastManagedValue:yield*ln(qt,fs)}}}let Sx={...ci.state,managed:Yl};yield*pT(Wn,Bo,{...Sx,managed:Hi},as);for(let D of[...Wi,...li]){let Se=D.key;if(Se===void 0)continue;let fs=lr.decisions.get(D.identity)==="replace"?Uo[Se]:fe(zn,Se);if(fs!==void 0)Wn=Tr(Wn,Se,fs)}let Zl=yield*Hc(Wn,Sx,as,{schema:yn,installId:Ce});if(Zl.driftedKeys.length>0)return yield*m(new k("state_corrupt","HolyCodex-owned Codex settings changed during native plugin setup.",void 0,{keys:Zl.driftedKeys.join(",")}));if(sr(t,{stage:"config",status:"started",message:"Configuring Root"}),ls=Zl.state,pe={...pe,managed_config:ls,plugin_config:{plugin_id:Qt,before:rs,after:Gl},provider_config:yx},(yield*p({try:()=>xe(i.configFile),catch:(D)=>D}))!==us)return yield*m(new k("confirmation_required","Codex configuration changed during plugin setup; review the latest configuration and retry.",void 0,{path:i.configFile}));if(yield*p({try:()=>yt(i.configFile,Mr(Zl.document)),catch:(D)=>D}),sp=!0,pe={...pe,step:"config_published"},yield*jn(i.preparingRecord,pe),ae.length>0)yield*_F({list:()=>K.list(),remove:(Se)=>K.remove(Se)},ae,(Se,qt)=>b(function*(){if(qt==="removed")cp.add(Se),nn.delete(Se);else if(qt==="absent")nn.delete(Se);else Kl.add(Se);pe={...pe,owned_plugins:[...nn]},yield*jn(i.preparingRecord,pe)}));sr(t,{stage:"config",status:"completed",message:"Root configuration published"}),sr(t,{stage:"verification",status:"started",message:"Verifying installation"}),yield*yF(i,g,y,{browserUse:x.browser_use,computerUse:x.computer_use,frontend:nt.frontend,security:nt.security,sessionAudit:x["session-audit"],autoReset:x["auto-reset"]},ls,Lr.preserved,as),sr(t,{stage:"verification",status:"completed",message:"Installation verified"});let xx=qd(x),ik=yield*Ml({owner:"holycodex",install_id:Ce,version:Y,profile:g,tier:y,optional_selections:x,explicit_optional_selections:S,official_plugins:z,capability_state:xx,managed_artifacts:Lr.managed_artifacts,managed_config:ls,plugin_config:{plugin_id:Qt,before:rs,after:Gl},provider_config:gx,plugin_snapshot:ss,owned_plugins:[...nn],...V===void 0?{}:{tooling:V}}),mp={owner:"holycodex",schema_epoch:yn,install_id:Ce,version:Y,digest:ik,profile:g,tier:y,optional_selections:x,explicit_optional_selections:S,official_plugins:z,capability_state:xx,managed_artifacts:Lr.managed_artifacts,installed_at:St,status:"active",step:"active",managed_config:ls,plugin_snapshot:ss,plugin_config:{plugin_id:Qt,before:rs,after:Gl},provider_config:gx,owned_plugins:[...nn],...V===void 0?{}:{tooling:V}};if(ot(za,mp)===void 0)return yield*m(new k("state_corrupt","The HolyCodex configuration is invalid."));return ux=!0,yield*p({try:()=>al(i.activeRecord,Yt(mp)),catch:(D)=>D}),fx=!0,yield*xT(i,vT(g,y,x,C)),yield*Bd(i.preparingRecord),yield*Bd(i.conflictedRecord),sr(t,{stage:"complete",status:"completed",message:"HolyCodex installation complete"}),{record:mp,optional_plugins:z,preserved:Lr.preserved,warnings:[...Lr.preserved.length===0?[]:["modified managed files were preserved"],...j===void 0?[]:[j]]}}).pipe(yr((P)=>b(function*(){let W=Um(P),V=[],Ee;if(ux){if(!(yield*ar(u===void 0?wS(i.activeRecord):p({try:()=>yt(i.activeRecord,u),catch:(ne)=>ne}))).ok)V.push("active_record")}if(fx){if(!(yield*ar(o===void 0?wS(i.installOptions):p({try:()=>yt(i.installOptions,o),catch:(ne)=>ne}))).ok)V.push("install_options")}if(cx||sp){let ie=cs,ne=yield*ar(ie===void 0?O(void 0):gF(i.configFile,pe,ie,lp));if(ne.ok)Ee=ne.value;else V.push("config")}if(ax){if(!(yield*ar(oF(i.configFile,Tn))).ok)V.push("invalid_config")}if(Lr!==void 0){let ie=Lr.rollback,ne=yield*ar(p({try:()=>wd(ie),catch:(he)=>he}));if(!ne.ok||ne.value.preserved.length>0)V.push("roles")}if(up.size>0)V.push(...[...up].map((ie)=>`plugin:${ie}`));for(let ie of sx)if(!(yield*ar(K.remove===void 0?O(void 0):p({try:()=>K.remove(ie),catch:(he)=>he}))).ok)V.push(`plugin:${ie}`);for(let ie of new Set([...cp,...Kl]))if((yield*ar(b(function*(){yield*wF({list:()=>K.list(),add:(he)=>K.add(he)},ie,ss.find((he)=>he.plugin_id===ie)?.status),yield*jn(i.preparingRecord,{...pe,owned_plugins:[...nn,ie]})}))).ok)cp.delete(ie),Kl.delete(ie),nn.add(ie),pe={...pe,owned_plugins:[...nn]};else nn.add(ie),Kl.add(ie),pe={...pe,owned_plugins:[...nn]},yield*Qe(jn(i.preparingRecord,pe)),V.push(`plugin:${ie}`);if(J?.ownership==="holycodex"&&c?.tooling?.context7?.ownership!=="holycodex"){let ie=yield*ar(p({try:()=>Sl(T,J),catch:(ne)=>ne}));if(!ie.ok||!ie.value)V.push("context7")}if(V.length===0&&Oe===void 0){if(!(yield*ar(b(function*(){if((yield*p({try:()=>xe(i.configFile),catch:(he)=>he}))?.trim().length===0&&(yield*vF(i.configFile,Ee??lx)))yield*p({try:()=>RS(i.configFile,{force:!1}),catch:(he)=>he})}))).ok)V.push("config_initialization")}if(V.length>0){let ie=yield*ar(b(function*(){let je=Mt(yield*p({try:()=>xe(i.configFile),catch:(ur)=>ur}),i.configFile),gt=pe.plugin_config,Fr=yield*Ud(je),kt=gt===void 0?void 0:{...gt,after:{preference:Fr.preference.digest===gt.before.preference.digest?gt.before.preference:gt.after.preference,marketplace:Fr.marketplace.digest===gt.before.marketplace.digest?gt.before.marketplace:gt.after.marketplace}},Ji=pe.provider_config,ui=yield*$d(je,Ji?.map((ur)=>ur.plugin_id)??[]),Vo=Ji?.map((ur)=>{let us=ui.find((fp)=>fp.plugin_id===ur.plugin_id);return us!==void 0&&us.before.digest===ur.before.digest?{...ur,after:ur.before}:ur});pe={...pe,...kt===void 0?{}:{plugin_config:kt},...Vo===void 0?{}:{provider_config:Vo}}})),ne=!1;if(ne=(yield*ar(jn(i.conflictedRecord,{...pe,step:"conflicted",status:"conflicted"}))).ok,ne)yield*Qe(Bd(i.preparingRecord))}else yield*Qe(Bd(i.preparingRecord));if(W instanceof Di)return yield*m(W);if(W instanceof k)return yield*m(W);return yield*m(new k(W instanceof Ar||W instanceof ni?"capability_denied":"install_failed",Il(W),W,V.length>0?{recovery:"Resolve conflicted state before retrying."}:{}))}).pipe($b)))})}function TS(e){return b(function*(){let t=yield*p({try:()=>By(e.activeRecord,md),catch:(Y)=>Y});if(t===void 0)return;let n=ot(za,t);if(n!==void 0){let Y=n;if(!(yield*Pl(n))){let I=RT(t)?ot(Dy,t):void 0,B=I===void 0?void 0:{...I,optional_selections:t.optional_selections};if(!(B!==void 0&&(yield*Pl(B))))return yield*m(new k("state_corrupt","The existing HolyCodex configuration has an invalid digest."));let ae=yield*Ml({owner:n.owner,install_id:n.install_id,version:n.version,profile:n.profile,tier:n.tier,optional_selections:n.optional_selections,explicit_optional_selections:n.explicit_optional_selections,official_plugins:n.official_plugins??[],capability_state:n.capability_state??null,managed_artifacts:n.managed_artifacts,...n.managed_config===void 0?{}:{managed_config:n.managed_config},...n.plugin_config===void 0?{}:{plugin_config:n.plugin_config},...n.provider_config===void 0?{}:{provider_config:n.provider_config},...n.plugin_snapshot===void 0?{}:{plugin_snapshot:n.plugin_snapshot},...n.owned_plugins===void 0?{}:{owned_plugins:n.owned_plugins},...n.tooling===void 0?{}:{tooling:n.tooling}});Y={...n,digest:ae},Vd.set(Y,B.digest)}return yield*p({try:()=>sl(e.activeRecord,t),catch:(I)=>I}),Y}let r=ot(Dy,t);if(r===void 0)return yield*m(new k("state_corrupt","The HolyCodex configuration is invalid."));let i={...r,optional_selections:t.optional_selections};if(!(yield*Pl(i)))return yield*m(new k("state_corrupt","The existing HolyCodex configuration has an invalid digest.",void 0,{path:e.activeRecord}));let a="profile"in r&&r.profile!==void 0?r.profile:("plan"in r)?r.plan:void 0;if(a===void 0)return yield*m(new k("state_corrupt","The persisted installation has neither profile nor legacy plan state.",void 0,{path:e.activeRecord}));let s=Le(U({try:()=>If(a),catch:(Y)=>new k("state_corrupt",`The persisted profile ${a} was removed and requires an explicit replacement.`,Y,{path:e.activeRecord,profile:a})})),c="plan"in r?Object.fromEntries(Object.entries(r).filter(([Y])=>Y!=="plan")):r,{optional_selections:u,explicit_optional_selections:l}=r,f={browser_use:u.browser_use??Ct.browser_use,computer_use:u.computer_use??!1,sites:u.sites??Ct.sites,"session-audit":u["session-audit"]??!1,"auto-reset":u["auto-reset"]??!1,coding:!0},h={...l.computer_use===void 0?{}:{computer_use:l.computer_use},...!("browser_use"in l)||l.browser_use===void 0?{}:{browser_use:l.browser_use},...!("sites"in l)||l.sites===void 0?{}:{sites:l.sites},...l["session-audit"]===void 0?{}:{"session-audit":l["session-audit"]},...l["auto-reset"]===void 0?{}:{"auto-reset":l["auto-reset"]}},g=r.capability_state===void 0?void 0:qd(f,new Map([["browser_use","missing"],["sites","missing"]])),y=(r.official_plugins??[]).filter((Y)=>!kl(Y)),v=r.owned_plugins?.filter((Y)=>!kl(Y)),d=r.provider_config?.filter((Y)=>!kl(Y.plugin_id)),x=r.plugin_snapshot?.filter((Y)=>!kl(Y.plugin_id)),{optional_selections:S,explicit_optional_selections:C,capability_state:T,official_plugins:F,owned_plugins:J,provider_config:j,plugin_snapshot:z,...K}=c,Ce={...K,profile:s,optional_selections:f,explicit_optional_selections:h,official_plugins:y,...g===void 0?{}:{capability_state:g},...v===void 0?{}:{owned_plugins:v},...d===void 0?{}:{provider_config:d},...x===void 0?{}:{plugin_snapshot:x},digest:yield*Ml({owner:r.owner,install_id:r.install_id,version:r.version,profile:s,tier:r.tier,optional_selections:f,explicit_optional_selections:h,official_plugins:y,capability_state:g??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},...d===void 0?{}:{provider_config:d},...x===void 0?{}:{plugin_snapshot:x},...v===void 0?{}:{owned_plugins:v},...r.tooling===void 0?{}:{tooling:r.tooling}})};return Vd.set(Ce,r.digest),yield*p({try:()=>sl(e.activeRecord,t),catch:(Y)=>Y}),Ce})}function bS(e,t){return b(function*(){let n=yield*p({try:()=>By(e,md),catch:(C)=>C});if(n===void 0)return;let r=ot(Fi,n);if(r!==void 0){yield*p({try:()=>sl(e,n),catch:(T)=>T});let C=t===void 0?void 0:Vd.get(t);if(t!==void 0&&C!==void 0&&RT(n)&&r.install_id===t.install_id&&r.digest===C)return{...r,digest:t.digest};return r}let i=ot(sR,n);if(i===void 0)return yield*m(new k("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*m(new k("state_corrupt","The HolyCodex transaction has no profile.",void 0,{path:e}));let a=Le(U({try:()=>If(o),catch:(C)=>new k("state_corrupt","The persisted transaction profile requires an explicit replacement.",C,{path:e,profile:o})})),{optional_selections:s,explicit_optional_selections:c}=i,u={browser_use:s.browser_use??Ct.browser_use,computer_use:s.computer_use??!1,sites:s.sites??Ct.sites,"session-audit":s["session-audit"]??!1,"auto-reset":s["auto-reset"]??!1,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},...c["session-audit"]===void 0?{}:{"session-audit":c["session-audit"]},...c["auto-reset"]===void 0?{}:{"auto-reset":c["auto-reset"]}},h=i.capability_state===void 0?void 0:qd(u,new Map([["browser_use","missing"],["sites","missing"]])),g="profile"in i?(({profile:C,...T})=>T)(i):("plan"in i)?(({plan:C,...T})=>T)(i):i,y=g.digest,v=t===void 0?void 0:Vd.get(t),d=t!==void 0&&g.install_id===t.install_id&&(y===t.digest||v!==void 0&&y===v)?t.digest:y,x={...g,profile:a,optional_selections:u,explicit_optional_selections:l,...h===void 0?{}:{capability_state:h},...d===void 0?{}:{digest:d}},S=ot(Fi,x);if(S===void 0)return yield*m(new k("state_corrupt","The migrated transaction state is invalid.",void 0,{path:e}));return yield*p({try:()=>sl(e,n),catch:(C)=>C}),S})}function _T(e){return{browser_use:e.browser_use,computer_use:e.computer_use,sites:e.sites,"session-audit":e["session-audit"],"auto-reset":e["auto-reset"]}}function Mt(e,t="config.toml"){if(e===void 0||e.trim().length===0)return{};return Le(U({try:()=>{let n=globalThis.Bun,r=n?.TOML?.parse?n.TOML.parse(e):rl(e),i=ot(Pi,r);if(i===void 0){let o=_S(r),a=o===void 0?"an unsupported TOML value":`the TOML value ${o}`;throw new k("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 k)return n;let r=Il(n),i=aF(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 k("state_corrupt",o,n,{path:t,parser_message:r,...i===void 0?{}:i,reason:"invalid_toml_syntax"})}}))}function _S(e,t=[]){if(e===null||typeof e==="string"||typeof e==="boolean")return;if(typeof e==="number")return Number.isFinite(e)?void 0:yS(t);if(Array.isArray(e)){for(let[n,r]of e.entries()){let i=_S(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 yS(t);for(let[r,i]of Object.entries(e)){let o=_S(i,[...t,r]);if(o!==void 0)return o}return}return yS(t)}function yS(e){return e.length===0?"<root>":e.join(".")}function tF(e,t){let n=new Map;for(let r of t)for(let i of nF(r)){let o=fe(e,i);if(o!==void 0&&!ri(o))n.set(i,o)}return[...n].map(([r,i])=>({key:r,value:i}))}function nF(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 rF(e,t){let n=JSON.stringify(t.value);return new k("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 iF(e,t,n,r){return b(function*(){let i=tF(n,r).map((a)=>{let s=rF(t,a);return Bn({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*Ol(e,i,!0);return{document:Qa(n,i,o.decisions),conflicts:i,decisions:o.decisions}})}function Qa(e,t,n){let r=e;for(let i of t){if(n.get(i.identity)!=="remove"||i.key===void 0)throw new k("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=fe(r,i.key);if(a===void 0)continue;if(JSON.stringify(a)!==JSON.stringify(i.existing))throw new k("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=Cn(r,i.key)}return r}function SS(e,t,n){return b(function*(){if((yield*p({try:()=>xe(e),catch:(r)=>r}))!==n)return yield*m(new k("confirmation_required","Codex configuration changed during preflight validation; review the latest configuration and retry.",void 0,{path:e}));if(t===void 0){yield*wS(e);return}yield*p({try:()=>yt(e,t),catch:(r)=>r})})}function oF(e,t){return b(function*(){let n=yield*p({try:()=>xe(e),catch:(o)=>o}),r=Mt(n,e),i=r;for(let o of t){if(o.key===void 0||o.existing===void 0)continue;let a=fe(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*m(new k("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=Cn(i,o.key)}i=Tr(i,o.key,o.existing)}if(i===r)return;if((yield*p({try:()=>xe(e),catch:(o)=>o}))!==n)return yield*m(new k("confirmation_required","Codex configuration changed during rollback; preserve it and review the current value.",void 0,{path:e}));yield*p({try:()=>yt(e,Mr(i)),catch:(o)=>o})})}function aF(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=sF(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("="),u=c<0?-1:e.indexOf(`
|
|
79
|
+
`,c+1);n=u<0?e.length:u}if(n===void 0)return;let a=e.slice(0,n).split(`
|
|
35
80
|
`).length,s=e.lastIndexOf(`
|
|
36
|
-
`,Math.max(0,n-1));return{offset:n,line:a,column:n-s}}function
|
|
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
|
|
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
|
|
81
|
+
`,Math.max(0,n-1));return{offset:n,line:a,column:n-s}}function sF(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===`
|
|
82
|
+
`)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 cF(e,t,n){return b(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=Bn({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*Qe(Ol(e,[o],!0))})}function Mr(e){return Le(U({try:()=>{let t=globalThis.Bun;return`${((t?.TOML?.stringify)?t.TOML.stringify(e):il(e)).trimEnd()}
|
|
83
|
+
`},catch:(t)=>new k("install_failed","The merged Codex configuration is not writable.",t)}))}function Ud(e){return b(function*(){return{preference:yield*Lo(e,"plugins",Mo),marketplace:yield*Lo(e,"marketplaces",Do)}})}function $d(e,t){return Pn(t.map((n)=>Lo(e,"plugins",n).pipe(me((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 b(function*(){let r=e,i=[],o=[],a=[];for(let[s,c,u]of[["preference","plugins",Mo],["marketplace","marketplaces",Do]]){let l=t.before[s],f=t.after[s],h=yield*Lo(e,c,u);if(n.allowBeforeState===!0&&h.digest===l.digest)continue;if(h.digest!==f.digest){a.push(s);continue}if(l.presence==="absent"){if(h.presence==="present")r=kS(r,c,u),o.push(s);continue}if(l.safe_value===void 0){a.push(s);continue}r=Dr(r,c,u,uF(l.safe_value)),i.push(s)}return{document:r,restored:i,removed:o,preserved:a}})}function CT(e,t,n,r={}){return b(function*(){let i=e,o=[],a=[],s=[];for(let c of t){if(!n.has(c.plugin_id))continue;let{before:u,after:l}=c,f=yield*Lo(e,"plugins",c.plugin_id);if(r.allowBeforeState===!0&&f.digest===u.digest)continue;if(f.digest!==l.digest){s.push(c.plugin_id);continue}if(u.presence==="absent"){if(f.presence==="present")i=kS(i,"plugins",c.plugin_id),a.push(c.plugin_id);continue}if(u.safe_value===void 0){s.push(c.plugin_id);continue}i=Dr(i,"plugins",c.plugin_id,{enabled:u.safe_value.value}),o.push(c.plugin_id)}return{document:i,restored:o,removed:a,preserved:s}})}function uT(e,t,n,r,i,o){return b(function*(){if(i.presence!=="present"||i.safe_value!==void 0)return{document:e,restored:!1};let a=yield*Lo(e,n,r);if(a.digest===i.digest||a.digest!==o.digest)return{document:e,restored:!1};let s=Nl(t,n,r);if(s===void 0)return{document:e,restored:!1};return{document:Dr(e,n,r,s),restored:!0}})}function Lo(e,t,n){return b(function*(){let r=Nl(e,t,n),i=yield*p({try:()=>wn("holycodex-plugin-config",[_n(Yt({key:`${t}.${n}`,value:r===void 0?{presence:"absent"}:r}))]),catch:(a)=>a}),o=lF(t,r);return{presence:r===void 0?"absent":"present",digest:i,...o===void 0?{}:{safe_value:o}}})}function Nl(e,t,n){let r=e[t];if(!ri(r)||!Object.hasOwn(r,n))return;return r[n]}function lF(e,t){if(!ri(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!==ti)return;return{kind:"marketplace",source_type:"git",source:ti}}function uF(e){if(e.kind==="boolean")return{enabled:e.value};return{source_type:e.source_type,source:e.source}}function Dr(e,t,n,r){let i={...e},o=i[t];if(o!==void 0&&!ri(o))throw new k("state_corrupt",`The ${t} Codex config table is invalid.`);return i[t]={...o,[n]:r},i}function kS(e,t,n){let r=e[t];if(!ri(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 ri(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function fF(e,t,n){return b(function*(){let r=[{parent:"plugins",key:Mo,expected:t.preference},{parent:"marketplaces",key:Do,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*Lo(e,i,o)).digest!==a.digest)return yield*m(new k("confirmation_required","Plugin configuration changed after preflight; review the latest configuration and retry.",void 0,{key:`${i}.${o}`}))})}function fT(e,t,n,r,i,o,a,s,c,u){return b(function*(){let l=e,f=n,h=r;for(let g of a){let y=g.identity;if(y===void 0)return yield*m(new k("state_corrupt","A plugin configuration conflict has no identity."));let v=c.get(y);if(v!=="keep"&&v!=="replace")return yield*m(new k("confirmation_required",`Plugin configuration conflict resolution is incomplete for ${g.key??y}.`));let d=g.key==='plugins."holycodex@holycodex"'?"preference":"marketplace",x=i[d];if(v==="keep"){let S=Nl(t,"plugins",Mo);if(d==="preference"&&ri(S)&&S.enabled===!1)return yield*m(new k("confirmation_required","Keeping disabled HolyCodex config would disable the selected plugin."));l=dT(l,t,g.key),f={...f,[d]:x};continue}l=Dr(l,d==="preference"?"plugins":"marketplaces",d==="preference"?Mo:Do,d==="preference"?{enabled:!0}:{source_type:"git",source:ti})}for(let g of s){let{identity:y,key:v}=g;if(y===void 0||v===void 0)return yield*m(new k("state_corrupt","A provider configuration conflict has no identity."));let d=v.startsWith('plugins."')&&v.endsWith('"')?v.slice(9,-1):void 0;if(d===void 0)return yield*m(new k("state_corrupt",`The provider configuration conflict key ${v} is invalid.`));let x=c.get(y);if(x!=="keep"&&x!=="replace")return yield*m(new k("confirmation_required",`Provider configuration conflict resolution is incomplete for ${v}.`));let S=o.find((C)=>C.plugin_id===d);if(S===void 0)return yield*m(new k("state_corrupt",`The provider configuration entry ${d} is missing.`));if(x==="keep"){let C=Nl(t,"plugins",d);if(u.includes(d)&&ri(C)&&C.enabled===!1)return yield*m(new k("confirmation_required",`Keeping disabled config would disable selected plugin ${d}.`));l=dT(l,t,v),h=h.map((T)=>T.plugin_id===d?{plugin_id:d,before:S.before,after:S.before}:T);continue}l=Dr(l,"plugins",d,{enabled:!0})}return{document:l,pluginConfigBefore:f,providerConfigBefore:h}})}function dT(e,t,n){if(n===void 0)throw new k("state_corrupt","A configuration conflict has no key.");if(n.startsWith('plugins."')&&n.endsWith('"')){let i=n.slice(9,-1),o=Nl(t,"plugins",i);return o===void 0?kS(e,"plugins",i):Dr(e,"plugins",i,o)}let r=fe(t,n);return r===void 0?Cn(e,n):Tr(e,n,r)}function dF(e,t,n,r){return b(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 u=yield*ln(a,c);if(JSON.stringify(u)===JSON.stringify(s.lastManagedValue))continue;let l=fe(e,a);if(typeof l!=="string"&&typeof l!=="number"&&typeof l!=="boolean")continue;let f=yield*ln(a,l);if(JSON.stringify(f)===JSON.stringify(s.lastManagedValue))delete i[a]}return i})}function Cl(e,t,n=!1,r=process.env.CODEX_HOME??YL(KL(),".codex"),i){let o=_d(e,t),a=typeof n==="boolean"?{}:n,s={browserUse:a.browserUse??Ct.browser_use,computerUse:typeof n==="boolean"?n:a.computerUse??Ct.computer_use,...a.parentPersonalityNone===void 0?{}:{parentPersonalityNone:a.parentPersonalityNone}},c=ko(e,t,s),u={model:o.model,model_catalog_json:fl(r),model_reasoning_effort:o.effort,service_tier:o.serviceTier,"agents.enabled":!0,"agents.max_concurrent_threads_per_session":21,"agents.max_depth":1,web_search:"live",approval_policy:"on-request",approvals_reviewer:"auto_review",default_permissions:":danger-full-access",include_collaboration_mode_instructions:!1,model_verbosity:"low",developer_instructions:Xy({...typeof n==="boolean"?{computerUse:n}:n,rootModel:o.model}),suppress_unstable_features_warning:!0,"features.multi_agent":!0,"features.default_mode_request_user_input":!0,"features.goals":!1,"features.image_generation":!0,"features.memories":!1,"features.request_permissions_tool":!1,"features.skill_search":!0,"features.sleep_tool":!1,"features.multi_agent_v2.enabled":!1,"features.multi_agent_v2.usage_hint_text":Ie.v1UsageHintText,"features.agent_message_board":!1,"features.code_mode.enabled":!0,"features.code_mode.direct_only_tool_namespaces":["multi_agent_v1"],"tools.experimental_request_user_input.enabled":!1,"tools.update_plan.enabled":!1,...i!==void 0&&Jy(i,o.model)?{"features.context_management.experimental_mode":!0}:{}};for(let l of Gr)u[`agents."${l}".config_file`]=ul(l,c);for(let l of Ci)u[`agents.${l}.config_file`]=LR(l,c);return u}function pF(e){return b(function*(){let t=yield*p({try:()=>e.run("codex",["debug","models","--bundled"]),catch:(i)=>i});if(t.exitCode!==0)return yield*m(new k("install_failed",`The current Codex model catalog could not be read: ${t.stderr||"Codex debug models failed."}`));let n=yield*U({try:()=>JSON.parse(t.stdout),catch:(i)=>i}),r=yield*U({try:()=>vd(n),catch:(i)=>i});return{catalog:r.catalog,json:`${JSON.stringify(r.catalog,null,2)}
|
|
84
|
+
`}})}function pT(e,t,n,r){return b(function*(){let i=[];for(let o of Object.keys(r)){let a=o;if(n.managed[a]!==void 0){if((yield*Jc(e,n,a)).status==="drifted")i.push(a);continue}let c=fe(t,a),u=fe(e,a),l=Yt(c===void 0?null:c),f=Yt(u===void 0?null:u);if(er(l)!==er(f))i.push(a)}if(i.length>0)return yield*m(new k("state_corrupt","Codex settings changed during native plugin setup.",void 0,{keys:i.join(",")}))})}function xS(e,t,n){return b(function*(){if(!n)return{document:e,state:t};let r=n.managed_artifacts.map((l)=>l.path),o=["explorer","librarian","worker","reviewer"].filter((l)=>r.some((f)=>f.startsWith(`agents/${l[0]?.toUpperCase()}${l.slice(1)}.`)||f===`holycodex/agents/${l}.toml`)),a=o.map((l)=>`agents.${l}.config_file`),s=Object.fromEntries(a.flatMap((l)=>{let f=t.managed[l];return f===void 0?[]:[[l,f]]})),c=e,u=t;if(Object.keys(s).length>0){let l=yield*Ai(e,{...t,managed:s},{schema:t.schema,installId:t.installId});if(l.preservedKeys.length>0||l.unresolvedKeys.length>0)return yield*m(new k("state_corrupt","Legacy HolyCodex agent registrations changed and cannot be migrated safely.",void 0,{keys:[...new Set([...l.preservedKeys,...l.unresolvedKeys])].join(",")}));c=l.document,u={...t,managed:Object.fromEntries(Object.entries(t.managed).filter(([f])=>!a.includes(f)))}}for(let l of o){let f=`agents.${l}.config_file`,h=fe(c,f);if(typeof h!=="string")continue;let g=h.replaceAll("\\","/").replace(/^\.\//u,"");if(g===`agents/${l}.toml`||g===`holycodex/agents/${l}.toml`)c=Cn(c,f)}return{document:c,state:u}})}function ES(e,t){return b(function*(){let n=t.managed[gS];if(n===void 0)return{document:e,state:t};let r=yield*Ai(e,{...t,managed:{[gS]:n}},{schema:t.schema,installId:t.installId}),i=Object.fromEntries(Object.entries(t.managed).filter(([o])=>o!==gS));return{document:r.document,state:{...t,managed:i}}})}function jd(e,t){return b(function*(){let n=t.managed["permissions.holycodex.extends"]!==void 0||t.managed["permissions.holycodex.network.enabled"]!==void 0,r=Object.fromEntries(Object.entries(t.managed).filter(([s])=>Oi.includes(s)));if(Object.keys(r).length===0)return{document:e,state:t};let i=yield*Ai(e,{...t,managed:r},{schema:t.schema,installId:t.installId}),o=Object.fromEntries(Object.entries(t.managed).filter(([s])=>!(s in r)));if(n&&fe(e,"default_permissions")==="holycodex")o.default_permissions={owner:"holycodex",schema:t.schema,installId:t.installId,keyPath:"default_permissions",originalValue:{kind:"absent"},lastManagedValue:{kind:"enum",value:"holycodex"}};return{document:i.document,state:{...t,managed:o}}})}function mF(e,t){if(fe(e,"developer_instructions")!==void 0&&t.managed.developer_instructions===void 0)throw new k("state_corrupt","Existing developer_instructions cannot be displaced safely; remove it or converge managed state first.")}function hF(e,t){return b(function*(){let n=yield*p({try:()=>e.list(),catch:(r)=>Bi("list",r,"selected plugins")});return t.map((r)=>{let i=cr(n,r),o=i===void 0?"missing":i.installed&&i.enabled?"installed":i.installed?"disabled":"available";return{plugin_id:r,status:o}})})}function jn(e,t){return b(function*(){let n=ot(Fi,t);if(n===void 0)return yield*m(new k("state_corrupt","The HolyCodex transaction state is invalid."));yield*p({try:()=>al(e,Yt(n)),catch:(r)=>r})})}function Bd(e){return p({try:()=>RS(e,{force:!1}),catch:(t)=>t}).pipe($t((t)=>Ze(t,"ENOENT")?O(void 0):m(t)))}function wS(e){return p({try:()=>RS(e,{force:!1}),catch:(t)=>t}).pipe($t((t)=>Ze(t,"ENOENT")?O(void 0):m(t)))}function ar(e){return e.pipe(yr((t)=>m(Um(t))),de({onFailure:(t)=>({ok:!1,error:t}),onSuccess:(t)=>({ok:!0,value:t})}))}function gF(e,t,n,r){return b(function*(){let i=yield*p({try:()=>xe(e),catch:(g)=>g});if(i===void 0)return;let o=Mt(i,e),a={},s=0;for(let[g,y]of Object.entries(t.managed_config.managed)){let v=g,d=fe(n,v),x=d===void 0?void 0:yield*ln(v,d);if(JSON.stringify(x??null)===JSON.stringify(y.lastManagedValue))continue;if(d!==void 0&&x?.kind==="digest"){let S=fe(o,v);if(S!==void 0&&JSON.stringify(yield*ln(v,S))===JSON.stringify(y.lastManagedValue))o=Tr(o,v,d),s+=1;continue}a[g]={...y,originalValue:x??{kind:"absent"}}}let c=yield*Ai(o,{...t.managed_config,managed:a},{schema:yn,installId:t.install_id});o=c.document;let u=t.plugin_config===void 0?void 0:yield*wT(o,t.plugin_config,{allowBeforeState:!0});if(u!==void 0)o=u.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[g,y,v]of[["preference","plugins",Mo],["marketplace","marketplaces",Do]]){let d=yield*uT(o,n,y,v,t.plugin_config.before[g],t.plugin_config.after[g]);if(o=d.document,d.restored)s+=1}if(t.provider_config!==void 0)for(let g of t.provider_config){if(!r.has(g.plugin_id))continue;let y=yield*uT(o,n,"plugins",g.plugin_id,g.before,g.after);if(o=y.document,y.restored)s+=1}if(!(c.restoredKeys.length>0||u!==void 0&&(u.restored.length>0||u.removed.length>0)||l!==void 0&&(l.restored.length>0||l.removed.length>0)||s>0))return;yield*p({try:()=>yt(e,Mr(o)),catch:(g)=>g});let h=yield*p({try:()=>hT(e),catch:(g)=>g});return h.isFile()&&!h.isSymbolicLink()?{dev:h.dev,ino:h.ino}:void 0})}function yF(e,t,n,r,i,o=[],a=Cl(t,n,r,e.codexHome)){return b(function*(){let s=yield*p({try:()=>xe(e.configFile),catch:(d)=>d}),c=Mt(s,e.configFile),u=fe(c,"model_catalog_json");if(typeof u!=="string")return yield*m(new k("install_failed","The managed model catalog path is missing."));if((yield*p({try:()=>xe(u),catch:(d)=>d}))===void 0)return yield*m(new k("install_failed","The managed model catalog is missing."));let f=a;for(let[d,x]of Object.entries(f)){let S=fe(c,d);if(d==="developer_instructions"){if(typeof S!=="string"||S!==x||(yield*SF(d,S))!==i.managed[d]?.lastManagedValue.value)return yield*m(new k("install_failed","The effective Root instructions did not converge."))}else if(typeof x==="object"?er(S)!==er(x):S!==x)return yield*m(new k("install_failed",`The effective Codex setting ${d} did not converge.`))}let h={browserUse:r.browserUse??Ct.browser_use,computerUse:r.computerUse,parentPersonalityNone:To(fe(c,"personality"))},g=ko(t,n,h),y=ji(t,n);for(let d of y){let x=`agents."${d.name}".config_file`,S=fe(c,x);if(typeof S!=="string")return yield*m(new k("install_failed",`The ${d.name} registration is missing.`));let C=ul(d.name,g),T=_o(e.configFile,C),F=T.replaceAll("\\","/");if(_o(e.configFile,S).replaceAll("\\","/")!==F)return yield*m(new k("install_failed",`The ${d.name} registration is stale (expected ${C}; received ${S}).`));let j=yield*p({try:()=>xe(T),catch:(K)=>K});if(j===void 0)return yield*m(new k("install_failed",`The ${d.name} role file is missing.`));if(o.some((K)=>K.replaceAll("\\","/")===F))return yield*m(new k("install_failed",`The ${d.name} role file was kept after a conflict and cannot be activated.`));let z=Mt(j,T);if(z.name!==d.name||typeof z.description!=="string"||typeof z.model!=="string"||typeof z.model_reasoning_effort!=="string"||typeof z.service_tier!=="string"||typeof z.developer_instructions!=="string"||z.personality!==(To(fe(c,"personality"))?"friendly":"none")||!jR(d,z)||z.tool_output_token_limit!==void 0||z.agents!==void 0||z.features!==void 0)return yield*m(new k("install_failed",`The ${d.name} role file is malformed.`))}let v=yield*p({try:()=>xe(`${e.codexHome}/agents/root.toml`),catch:(d)=>d});if(v!==void 0&&Ja(v))return yield*m(new k("install_failed","A stale HolyCodex Root role remains installed."))})}function SF(e,t){return b(function*(){return yield*p({try:()=>wn("holycodex-managed-config-value",[_n({keyPath:e,value:t})]),catch:(n)=>n})})}function vS(e,t){let n={};for(let r of["browser_use","computer_use","sites","session-audit","auto-reset"]){let i=t?.[r]??e?.[r];if(i!==void 0)n[r]=i}return n}function xF(e){return["browser_use","computer_use","sites"].find((t)=>Er[t].pluginIds.includes(e))}function CS(e){return(e?.official_plugins??[]).filter((t)=>{if(t===Xt)return!1;if(kl(t))return!1;let n=xF(t);return n===void 0||e?.optional_selections[n]!==!0})}function EF(e){return b(function*(){yield*Ba(GL(e));let t=yield*p({try:()=>JL(e,"wx",384),catch:(r)=>r}).pipe(de({onFailure:(r)=>({error:r}),onSuccess:(r)=>({handle:r})}));if("error"in t){if(Ze(t.error,"EEXIST"))return;return yield*m(t.error)}let n=t.handle;return yield*Wr(O(n),(r)=>b(function*(){let i=yield*p({try:()=>r.stat(),catch:(o)=>o});return yield*p({try:()=>r.sync(),catch:(o)=>o}),{dev:i.dev,ino:i.ino}}),(r)=>p({try:()=>r.close(),catch:(i)=>i}))})}function vF(e,t){return b(function*(){if(t===void 0)return!1;let n=yield*p({try:()=>hT(e),catch:(i)=>i}).pipe(de({onFailure:(i)=>({error:i}),onSuccess:(i)=>({stat:i})}));if("error"in n){if(Ze(n.error,"ENOENT"))return!1;return yield*m(n.error)}let r=n.stat;return r.isFile()&&!r.isSymbolicLink()&&r.dev===t.dev&&r.ino===t.ino})}function kl(e){let t=e.slice(0,e.lastIndexOf("@"));return eF.has(t)}function bF(e,t,n,r){return b(function*(){let i=(s)=>p({try:()=>e.list(),catch:(c)=>Bi("list",c,s)}),o=(s)=>p({try:()=>e.add(s),catch:(c)=>Bi("add",c,s)}),a=(s,c)=>r?.(s,c)??pt;for(let s of t){let c=n.has(s),u=yield*i(s).pipe(de({onFailure:(y)=>({error:y}),onSuccess:(y)=>({before:cr(y,s)})}));if("error"in u)return yield*m(u.error);let l=u.before;if(l?.installed&&!l.enabled)return yield*m(new ni("uncertain",`${s} is disabled`));let f=c||!(l?.installed&&l.enabled);if(f){let y=yield*o(s).pipe(de({onFailure:(v)=>({error:v}),onSuccess:()=>({added:!0})}));if("error"in y){let v=yield*i(s).pipe(de({onFailure:(d)=>({error:d}),onSuccess:(d)=>({afterFailure:cr(d,s)})}));if("error"in v||c||!mT(l,v.afterFailure))yield*a(s,"uncertain");return yield*m(y.error)}}let h=yield*i(s).pipe(de({onFailure:(y)=>({error:y}),onSuccess:(y)=>({after:cr(y,s)})}));if("error"in h){if(f)yield*a(s,"uncertain");return yield*m(h.error)}let g=h.after;if(!g?.installed){if(f&&(c||!mT(l,g)))yield*a(s,"uncertain");return yield*m(new ni("missing",`${s} is not installed after add`))}if(f&&g.enabled)yield*a(s,c?"uncertain":"new");if(!g.enabled){if(f)yield*a(s,c?"uncertain":"new");return yield*m(new ni("uncertain",`${s} is disabled after add`))}}})}function _F(e,t,n){return b(function*(){let r=(a)=>p({try:()=>e.list(),catch:(s)=>Bi("list",s,a)}),i=(a)=>p({try:()=>e.remove(a),catch:(s)=>Bi("remove",s,a)}),o=(a,s)=>n?.(a,s)??pt;for(let a of t){let s=yield*r(a).pipe(de({onFailure:(f)=>({error:f}),onSuccess:(f)=>({before:cr(f,a)})}));if("error"in s)return yield*o(a,"uncertain"),yield*m(s.error);if(!(s.before?.installed??!1)){yield*o(a,"absent");continue}let u=yield*i(a).pipe(de({onFailure:(f)=>({error:f}),onSuccess:()=>({removed:!0})}));if("error"in u){let f=yield*r(a).pipe(de({onFailure:(h)=>({error:h}),onSuccess:(h)=>({afterFailure:cr(h,a)})}));return yield*o(a,"error"in f||f.afterFailure?.installed?"uncertain":"removed"),yield*m(u.error)}let l=yield*r(a).pipe(de({onFailure:(f)=>({error:f}),onSuccess:(f)=>({after:cr(f,a)})}));if("error"in l)return yield*o(a,"uncertain"),yield*m(l.error);if(l.after?.installed)return yield*o(a,"uncertain"),yield*m(new ni("uncertain",`${a} is still installed after remove`));yield*o(a,"removed")}})}function wF(e,t,n){return b(function*(){if(n!=="installed"&&n!=="disabled")return yield*m(new ni("uncertain",`${t} has no proven prior installed state`));let r=n==="installed",i=yield*p({try:()=>e.list(),catch:(c)=>Bi("list",c,t)}),o=cr(i,t);if(o?.installed&&o.enabled===r)return;yield*p({try:()=>e.add(t),catch:(c)=>Bi("add",c,t)});let a=yield*p({try:()=>e.list(),catch:(c)=>Bi("list",c,t)}),s=cr(a,t);if(!s?.installed)return yield*m(new ni("missing",`${t} is not installed after restore`));if(s.enabled!==r)return yield*m(new ni("uncertain",`${t} did not regain its prior ${r?"enabled":"disabled"} state`))})}function mT(e,t){return e?.pluginId===t?.pluginId&&e?.installed===t?.installed&&e?.enabled===t?.enabled&&e?.marketplaceName===t?.marketplaceName}function Bi(e,t,n){if(t instanceof Ar)return t;return new Ar(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 cr(e,t){let n=Cr(e,t);if(n!==void 0)return n.entry;let r=Mn(t);return[...e.installed,...e.available].find((i)=>i.pluginId===t&&(r===void 0||i.marketplaceName==null))}function CF(e,t){let n=e??t??"default";if(!Ma(n).ok)throw new k("install_failed","Unknown profile.");return n}function RF(e,t){let n=e??t??"standard";if(ot(vn,n)===void 0)throw new k("install_failed","The tier is not supported.");return n}function TF(e,t){let n=t?_T(t):Ct,r=jh(e,n);return{browser_use:r.browser_use,computer_use:r.computer_use,sites:r.sites,"session-audit":r["session-audit"],"auto-reset":r["auto-reset"],coding:!0}}function qd(e,t=new Map){return Object.fromEntries(["browser_use","computer_use","frontend","security","sites","session-audit","auto-reset"].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:[...Er[r].pluginIds]};return[r,a]}))}function kF(e){return A(Ml(e))}function Ml(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 p({try:()=>wn("install-record",[_n(Yt(i))]),catch:(o)=>o})}function RT(e){let t=e.optional_selections;if(typeof t!=="object"||t===null||Array.isArray(t))return!1;return!Object.hasOwn(t,"session-audit")||!Object.hasOwn(t,"auto-reset")}function Rl(e){return A(Pl(e))}function Pl(e){return b(function*(){return(yield*Ml({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 Il(e){return e instanceof Error?e.message.slice(0,256):"operation failed"}function IF(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 PF(e){return ri(e)&&Object.keys(e).length===2&&e.source_type==="git"&&typeof e.source==="string"&&Qf(e.source)}function OF(e,t,n){let r=[{name:"context7",status:e?"ready":"unavailable"}];for(let i of n){let o=cr(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 Bn(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 Ol(e,t,n=!1){return b(function*(){let r=t.map(Bn),i=new Map;if(r.length===0)return{accepted:[],decisions:i};if(e.resolveConflicts!==void 0){let a=yield*e.resolveConflicts(r).pipe(de({onFailure:(c)=>({error:c}),onSuccess:(c)=>({selected:c})}));if("error"in a){let c=a.error;if(!(c instanceof k)||c.code!=="confirmation_required")return yield*m(c);let u=r.map((l)=>{let f=l.category==="invalid-config"&&l.key!==void 0&&l.existing!==void 0?` = ${JSON.stringify(l.existing)}`:"";return`${l.target} at ${l.path}${f}`}).join("; ");return yield*m(new k("confirmation_required",`${c.message} Conflicts: ${u}.`,c,{conflicts:u}))}let s=a.selected;for(let c of r){let u=c.identity,l=ot(eR,s[u]);if(l===void 0||c.validDecisions?.includes(l)===!1){let f=c.validDecisions?.join(", ")??"keep, replace, cancel";return yield*m(new k("confirmation_required",`The conflict at ${c.target} requires one of these decisions: ${f}.`,void 0,{identity:u,path:c.path,...c.key===void 0?{}:{key:c.key}}))}if(l==="cancel")return yield*m(new k("confirmation_required",`Conflict resolution was cancelled for ${c.target} at ${c.path}.`,void 0,{identity:u,path:c.path,...c.key===void 0?{}:{key:c.key}}));i.set(u,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?O(void 0):e.resolveConflict(a);if(s==="accept"){let c=a.action==="remove"?"remove":"replace";if(a.validDecisions?.includes(c)===!1)return yield*m(new k("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*m(new k("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*m(new k("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 sr(e,t){Le(Qe(U({try:()=>e.onProgress?.(t),catch:(n)=>n})))}function hS(e={},t={},n=process.env){return A(Al(e,t,n))}function Xa(e){return A(TS(e))}function ei(e,t){return A(bS(e,t))}function El(e,t,n={}){return A(wT(e,t,n))}function vl(e,t,n,r={}){return A(CT(e,t,n,r))}var lT="davidbasilefilho/holycodex",Qt="holycodex@holycodex",Xt="browser@openai-bundled",ZL="0.16.8",XL="0.16.9",Vd,ti="https://github.com/davidbasilefilho/holycodex.git",Mo="holycodex@holycodex",Do="holycodex",eF,gS,ni,k;var Tl=L(()=>{wo();ht();oo();Fe();fd();cl();Ky();Rd();pl();Ro();nl();Wa();Pd();nl();Vd=new WeakMap;eF=new Set(["documents","pdf","presentations","spreadsheets","template-creator"]),gS=Oi[0];ni=class ni extends Error{status;constructor(e,t){super(t);this.name="PluginVerificationError",this.status=e}};k=class k 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}}});Fe();import{createInterface as TU}from"readline/promises";wo();ht();Fe();It();Ue();ht();Ue();var Ty=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."}]),GC=new Set(["codex-home","profile","tier","add-plugin"]),aM=new Set(["yes","json","verbose","dry-run","computer-use","no-computer-use","sites","no-sites","browser-use","no-browser-use"]);class it extends Error{code;details;constructor(e,t,n={}){super(t);this.name="ArgumentError",this.code=e,this.details=n}}function ud(e){if(e.length===0)throw new it("unknown_command","A command is required.");if(e.includes("-h")||e.includes("--help")||e.includes("--help=true"))return{command:"help",positionals:[],options:{}};if(e[0]==="help")return{command:"help",positionals:e.slice(1),options:{}};if(e[0]==="-v"||e[0]==="--version"||e[0]==="--version=true")return ud(["version",...e.slice(1)]);let t=e[0];if(t!=="install"&&t!=="doctor"&&t!=="remove"&&t!=="version")throw new it("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 it("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,u=s>=0?a.slice(s+1):void 0,l=c.replaceAll("_","-");if(l==="plan")throw new it("invalid_argument","The --plan option was removed; use --profile <low|default|high>.",{option:"--plan",replacement:"--profile"});if(!GC.has(l)&&!aM.has(l))throw new it("invalid_argument","Unknown option.",{option:`--${c}`});if(GC.has(l)){let f=u??e[i+1];if(f===void 0||f.length===0||f.startsWith("-"))throw new it("invalid_argument",`Option --${c} requires a value.`,{option:`--${c}`});if(u===void 0)i+=1;if(l==="add-plugin"){let h=r[l];r[l]=Array.isArray(h)?[...h,f]:[f]}else{if(r[l]!==void 0)throw new it("invalid_argument",`Option --${c} may only be supplied once.`,{option:`--${c}`});r[l]=f}continue}if(u!==void 0&&u!=="true"&&u!=="false")throw new it("invalid_argument",`Option --${c} is boolean.`,{option:`--${c}`});if(r[l]!==void 0)throw new it("invalid_argument",`Option --${c} may only be supplied once.`,{option:`--${c}`});r[l]=u==="false"?!1:!0}return sM(t,n,r),{command:t,positionals:n,options:r}}function sM(e,t,n){let r=lM(e);for(let s of Object.keys(n))if(!r.has(s))throw new it("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 it("invalid_argument",`Invalid positional arguments for ${e}.`);let o=n.profile;if(o!==void 0&&!le(cn)(o)){if(typeof o!=="string")throw new it("invalid_argument","The profile is not supported.");let s=cM[o];if(s!==void 0)throw new it("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 it("invalid_argument",`Legacy profile ${o} was removed and requires an explicit replacement using --profile <low|default|high>.`,{profile:o});throw new it("invalid_argument","The profile is not supported.",{profile:o})}let a=n.tier;if(a!==void 0&&!le(vn)(a))throw new it("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 it("invalid_argument",`Conflicting --${s} and --${c} options.`);if(["install","remove"].includes(e)&&n.yes===!1)throw new it("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 it("invalid_argument",`Installation options are not valid for ${e}.`)}var cM={"plus-low":"low",plus:"default","plus-high":"high"};function lM(e){switch(e){case"install":return new Set([...Ty.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 uM=`HolyCodex
|
|
39
85
|
|
|
40
86
|
Usage:
|
|
41
87
|
holycodex install [options]
|
|
@@ -49,7 +95,7 @@ Options:
|
|
|
49
95
|
--json Emit one validated JSON envelope.
|
|
50
96
|
|
|
51
97
|
Use --json for scripts. Install and remove use native Codex plugin management.
|
|
52
|
-
`,
|
|
98
|
+
`,fM=`Install HolyCodex through Codex native plugin management.
|
|
53
99
|
|
|
54
100
|
Usage:
|
|
55
101
|
holycodex install [options]
|
|
@@ -66,7 +112,7 @@ Tier is independent service handling (CLI values are lowercase only):
|
|
|
66
112
|
fast-all Fast service handling for Root and leaves.
|
|
67
113
|
|
|
68
114
|
Options:
|
|
69
|
-
${
|
|
115
|
+
${Ty.map((e)=>` ${e.usage.padEnd(48)} ${e.description}`).join(`
|
|
70
116
|
`)}
|
|
71
117
|
--no-sites / --no-browser-use / --no-computer-use
|
|
72
118
|
Disable the corresponding plugin.
|
|
@@ -78,48 +124,48 @@ On an interactive TTY, install opens one wizard and final review with Install,
|
|
|
78
124
|
Change options / Redo, and Cancel. The wizard never asks for CODEX_HOME.
|
|
79
125
|
Additional plugin IDs in the wizard are separated by whitespace; --add-plugin
|
|
80
126
|
remains repeatable on the command line.
|
|
81
|
-
`,
|
|
127
|
+
`,dM=`Remove HolyCodex-owned state through Codex native plugin management.
|
|
82
128
|
|
|
83
129
|
Usage:
|
|
84
130
|
holycodex remove [--yes] [--json] [--codex-home <absolute-path>]
|
|
85
131
|
|
|
86
132
|
Only HolyCodex-owned state is removed. Shared and unrelated Codex plugins and
|
|
87
133
|
configuration are preserved; changed owned files are preserved for review.
|
|
88
|
-
`,
|
|
134
|
+
`,pM=`Inspect HolyCodex-owned configuration and native plugin state without mutating it.
|
|
89
135
|
|
|
90
136
|
Usage:
|
|
91
137
|
holycodex doctor [--json] [--codex-home <absolute-path>]
|
|
92
|
-
`,
|
|
138
|
+
`,mM=`Read or update the canonical public package version.
|
|
93
139
|
|
|
94
140
|
Usage:
|
|
95
141
|
holycodex version [<0.x.y[-n]|patch|minor>] [--dry-run] [--json]
|
|
96
142
|
holycodex --version
|
|
97
143
|
holycodex -v
|
|
98
|
-
`;function
|
|
99
|
-
`).map((r)=>{if(r==="HolyCodex")return
|
|
100
|
-
`)}function
|
|
144
|
+
`;function Gc(e){switch(e){case"install":return fM;case"remove":return dM;case"doctor":return pM;case"version":return mM;default:return uM}}function ky(e,t={}){let n=Ni({...t,stream:"stdout"});return Gc(e).split(`
|
|
145
|
+
`).map((r)=>{if(r==="HolyCodex")return un(r,"heading",n);if(/^(?:Usage|Options|Profiles control routing only|Tier is independent service handling|Capability defaults).*:$/u.test(r))return un(r,"heading",n);return r.replace(/--[a-z][a-z0-9-]*/gu,(i)=>un(i,"option",n)).replace(/<[^>]+>/gu,(i)=>un(i,"argument",n))}).join(`
|
|
146
|
+
`)}function Yc(e){return e.some((t)=>t==="-h"||t==="--help"||t==="--help=true")}function Zc(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 Ni(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 Iy={heading:"#7aa2f7",option:"#7dcfff",argument:"#a9b1d6",focus:"#7dcfff",enabled:"#9ece6a",disabled:"#a9b1d6",success:"#73daca",warning:"#e0af68",error:"#f7768e",hint:"#737aa2"};function un(e,t,n){if(!n)return e;let r=t==="heading"||t==="focus"?"1;":"",i=Iy[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`}ht();Fe();Tl();var AF=["low","default","high"],NF=["standard","fast","fast-all"],Vi=["sites","browser_use","computer_use","session-audit","auto-reset"];function IS(e,t){return A(yi((n)=>{let r=!1,i=(c)=>{let u=Le(We(U({try:()=>t(c),catch:(l)=>l})));if(u._tag==="Failure")a(m(u.failure));else if(u.success!==void 0)a(O(u.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=Le(We(U({try:()=>e.start(),catch:(c)=>c})));if(s._tag==="Failure")a(m(s.failure));return dt(o)}))}function PS(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 OS(e){let t=e.stdoutIsTTY??(e.stdout===void 0?process.stdout.isTTY===!0:e.stdout.isTTY===!0);return Ni({stdoutIsTTY:t,env:e.env??process.env,stream:"stdout"})}function Fo(...e){return e}function te(e,t){return Fo({text:e,...t===void 0?{}:{tone:t}})}function MF(e,t,n){let r=e.fg(Iy[n])(t);return n==="heading"||n==="focus"?e.bold(r):r}function zd(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(MF(e,a.text,a.tone))}if(o<t.length-1)r.push(...e.stringToStyledText(`
|
|
101
147
|
`).chunks)}),r.push(...e.stringToStyledText(`
|
|
102
|
-
`).chunks),new e.StyledText(r)}function
|
|
148
|
+
`).chunks),new e.StyledText(r)}function Wd(e={},t={}){return A(b(function*(){let n=en(e),r=yield*p({try:()=>import("@opentui/core"),catch:(f)=>f}),i=DS(n),o=yield*p({try:()=>r.createCliRenderer({...PS(t),exitOnCtrlC:!0,clearOnShutdown:!0}),catch:(f)=>f}),a=OS(t),s=new r.TextRenderable(o,{content:MT(r,i,0,a)});o.root.add(s);let c=0,u=!1,l=0;return yield*p({try:()=>IS(o,(f)=>{let h=()=>{s.content=u?KF(r,i,l,a):MT(r,i,c,a),o.requestRender()},g=f.name.toLowerCase();if(f.ctrl===!0&&g==="c")return{action:"cancel"};if(u){if(g==="escape"){u=!1,h();return}if(g==="up"||g==="k")l=(l+2)%3;else if(g==="down"||g==="j")l=(l+1)%3;else if(g==="return"||g==="enter"||g==="linefeed"){if(l===0)return{action:"install",request:VT(i)};if(l===1)u=!1,c=0;else return{action:"cancel"}}h();return}let y=BT(i,c,f);if(c=y.cursor,y.action==="cancel")return{action:"cancel"};if(y.action==="review")u=!0,l=0;h();return}),catch:(f)=>f})}))}function AS(e,t={}){let n={};for(let r of e){let i=Jd(r),o=es(r),a=t[i],s=o.includes(a??"cancel")?a:MS(r,o);n[i]=o.includes(s)?s:o[0]??"cancel"}return{conflicts:e,decisions:n}}function UT(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)=>es(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")$F(e,t,i==="left"?-1:1);return{cursor:t,action:"render"}}function DF(e,t=AS(e).decisions,n=0,r={}){let i=Ni({...r,stream:"stdout"}),o=process.stdout.columns??80,a=process.stdout.rows??24;return`${jT(e,t,n,o,a).map((s)=>s.map((c)=>c.tone===void 0?c.text:un(c.text,c.tone,i)).join("")).join(`
|
|
103
149
|
`)}
|
|
104
|
-
`}function
|
|
150
|
+
`}function Hd(e,t={},n={}){return A(b(function*(){let r=yield*p({try:()=>import("@opentui/core"),catch:(u)=>u}),i=AS(e,n),o=yield*p({try:()=>r.createCliRenderer({...PS(t),exitOnCtrlC:!0,clearOnShutdown:!0}),catch:(u)=>u}),a=OS(t),s=new r.TextRenderable(o,{content:LT(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*p({try:()=>IS(o,(u)=>{let l=()=>{s.content=LT(r,i.conflicts,i.decisions,c,a,t.width??process.stdout.columns??80,t.height??process.stdout.rows??24),o.requestRender()},f=UT(i,c,u);if(c=f.cursor,f.action==="continue")return{action:"continue",decisions:{...i.decisions}};if(f.action==="back"||f.action==="cancel")return{action:f.action};l();return}),catch:(u)=>u})}))}function LF(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 FF(e,t){let n=NS(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 $T(e,t={}){return A(b(function*(){let n=yield*p({try:()=>import("@opentui/core"),catch:(c)=>c}),r={review:e,selected:0},i=yield*p({try:()=>n.createCliRenderer({...PS(t),exitOnCtrlC:!0,clearOnShutdown:!0}),catch:(c)=>c}),o=OS(t),a=new n.TextRenderable(i,{content:FT(n,e,r.selected,o)});i.root.add(a);let s=r.selected;return yield*p({try:()=>IS(i,(c)=>{let u=()=>{a.content=FT(n,e,s,o),i.requestRender()},l=FF({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:NS(e)[s]};u();return}),catch:(c)=>c})}))}function NS(e){return e.conflicts.length>0?["apply","change","resolve","cancel"]:["apply","change","cancel"]}function UF(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=es(n),i=t==="replace"&&n.category==="invalid-config"&&!r.includes("replace")&&r.includes("remove")?"remove":t;if(r.includes(i))e.decisions[Jd(n)]=i}}function $F(e,t,n){let r=e.conflicts[t];if(r===void 0)return;let i=Jd(r),o=es(r);if(o.length===0)return;let a=e.decisions[i]??MS(r,o),s=o.indexOf(a),c=s<0?0:s;e.decisions[i]=o[(c+n+o.length)%o.length]??o[0]}function jF(e){return e.validDecisions??(e.action==="remove"?["keep","remove","cancel"]:["keep","replace","cancel"])}function es(e){return jF(e).filter((t)=>t!=="cancel")}function MS(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=es(e),r=t[Jd(e)];return n.includes(r??"cancel")?r:MS(e,n)}function jT(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=[te("HolyCodex \xB7 resolve conflicts","heading"),te(`${e.length} conflict${e.length===1?"":"s"}`,"hint"),te("\u2191/\u2193 navigate \u2190/\u2192 change action A replace all K keep all","hint"),te("Enter continue Esc back Ctrl-C cancel","hint")];if(!a)s.push(te(""));s.push(te(" ACTION CONFIG","heading"));let c=Math.max(1,i-(a?9:12)),u=Math.max(0,Math.min(o-c+1,e.length-c));if(e.slice(u,u+c).forEach((v,d)=>{let x=u+d,S=es(v),C=kT(v,t),T=x===o?">":" ",F=S.length===0?"blocked":C==="remove"?"replace":C,J=S.length===0?"error":C==="replace"?"warning":C==="keep"?"disabled":"error",j=Dl(v.target??v.key??v.path,r-12);s.push(Fo({text:`${T} ${F.padEnd(7)} `,tone:J},{text:j,tone:x===o?"focus":"argument"}))}),e.length===0)return s.push(te("No conflicts require a decision.","success")),s;if(!a)s.push(te(""));let l=e[o],f=kT(l,t),h=Dl(IT(l.existing),r-10),g=l.desired===void 0&&l.action==="remove"?qF(l):IT(l.desired),y=Dl(g,r-10);return s.push(te(Dl(l.target??l.key??l.path,r),"focus")),s.push(Fo({text:"current ",tone:"hint"},{text:h})),s.push(Fo({text:"install ",tone:"hint"},{text:y})),s.push(te(Dl(VF(l,f),r),"hint")),s}function Dl(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 BF(e){return e.split(/[-_]/u).map((t)=>t.length===0?t:`${t[0].toUpperCase()}${t.slice(1)}`).join(" ")}function IT(e){if(e===void 0)return"(unknown)";if(typeof e==="string")return e;let t=Le(We(U({try:()=>JSON.stringify(e),catch:(n)=>n})));return t._tag==="Success"?t.success:"(unavailable)"}function VF(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 qF(e){return e.category==="invalid-config"?"remove this conflicting user-owned value":"remove this managed item"}function Jd(e){return e.identity??`${e.path}:${e.key??""}:${e.action}`}function BT(e,t,n){let r=n.name.toLowerCase(),i=Vi.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=qT(e.pluginInput),{cursor:t,action:"review"};if(t===i){if(r==="backspace")AT(e,-1);else if(r==="delete")AT(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")OT(e," ");else if(!n.ctrl&&!n.meta&&n.name.length===1&&!XF(n.name))OT(e,n.name);return{cursor:t,action:"render"}}if(r==="space"&&t>=2)WF(e,t-2);else if(r==="left")PT(e,t,-1);else if(r==="right")PT(e,t,1);return{cursor:t,action:"render"}}function VT(e){let t={profile:e.profile,tier:e.tier,optional:{...e.optional},officialPlugins:[...e.plugins]};return en(t)}function zF(e,t="install",n={}){let r=DS(en(e));return HF(r,t==="install"?0:t==="change"?1:2,Ni({...n,stream:"stdout"}))}function DS(e){let t={...Ct,...e.optional};return{profile:e.profile??"default",tier:e.tier??"standard",optional:{browser_use:t.browser_use??Ct.browser_use,computer_use:t.computer_use??Ct.computer_use,sites:t.sites??Ct.sites,"session-audit":t["session-audit"]??Ct["session-audit"],"auto-reset":t["auto-reset"]??Ct["auto-reset"]},plugins:[...e.officialPlugins??[]],pluginInput:(e.officialPlugins??[]).join(" "),pluginCursor:(e.officialPlugins??[]).join(" ").length}}function PT(e,t,n){if(t===0)e.profile=NT(AF,e.profile,n);else if(t===1)e.tier=NT(NF,e.tier,n)}function WF(e,t){let n=Vi[t];if(n!==void 0)e.optional[n]=!e.optional[n]}function OT(e,t){e.pluginInput=`${e.pluginInput.slice(0,e.pluginCursor)}${t}${e.pluginInput.slice(e.pluginCursor)}`,e.pluginCursor+=t.length}function AT(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 NT(e,t,n){let r=e.indexOf(t);return e[(r+n+e.length)%e.length]??e[0]}function qT(e){let t=[...new Set(e.split(/\s+/u).map((n)=>n.trim()).filter(Boolean))];if(t.length===0)return[];return en({officialPlugins:t}),t}function HF(e,t,n=!1){let r=["Install","Change options / Redo","Cancel"];return`${[un("HolyCodex \xB7 review","heading",n),un("Review configuration","heading",n),un("\u2191/\u2193 choose Enter confirm Esc back","hint",n),"",`Profile: ${e.profile}`,`Service tier: ${e.tier}`,"",un("CAPABILITIES","heading",n),...Vi.map((o)=>` ${Kd(o)}: ${un(FS(e.optional[o]),e.optional[o]?"enabled":"disabled",n)}`),...LS(` Additional plugins: ${e.plugins.length===0?"none":e.plugins.join(" ")}`),"",...r.map((o,a)=>un(`${a===t?"\u203A":" "} ${o}`,a===t?"focus":a===0?"success":a===1?"warning":"error",n))].join(`
|
|
105
151
|
`)}
|
|
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
|
|
108
|
-
`)}function
|
|
109
|
-
${
|
|
110
|
-
`)}function
|
|
111
|
-
`;if(
|
|
152
|
+
`}function MT(e,t,n,r){let i=Vi.length+2,o=n<2?n===0?"Choose the routing profile for the Root session.":"Choose how quickly services handle work.":n<i?ZF(Vi[n-2]):"Optional plugin IDs separated by spaces. Enter continues to review.",a=[te("HolyCodex \xB7 install","heading"),te("\u2191/\u2193 focus \u2190/\u2192 change choice Space toggle Enter review Esc cancel","hint"),te(""),te("PROFILE","heading"),DT("Profile",t.profile,n===0),DT("Service tier",t.tier,n===1),te(""),te("OPTIONAL CAPABILITIES","heading"),...Vi.map((s,c)=>JF(s,t.optional[s],n===c+2)),te(""),te("ADDITIONAL PLUGINS","heading"),...LS(`${n===i?"\u276F":" "} ${t.pluginInput||"(none)"}`).map((s)=>te(s,n===i?"focus":"argument")),te(""),te(o,"hint")];return zd(e,a,r)}function DT(e,t,n){return te(`${n?"\u276F":" "} ${e.padEnd(13)} ${t}`,n?"focus":"argument")}function JF(e,t,n){let r=t?"[x] enabled":"[ ] disabled";return te(`${n?"\u276F":" "} ${Kd(e).padEnd(14)} ${r}`,n?"focus":t?"enabled":"disabled")}function KF(e,t,n,r){let i=["Install","Change options / Redo","Cancel"],o=[te("HolyCodex \xB7 review","heading"),te("Review configuration","heading"),te("\u2191/\u2193 choose Enter confirm Esc back","hint"),te(""),te(`Profile: ${t.profile}`),te(`Service tier: ${t.tier}`),te(""),te("CAPABILITIES","heading"),...Vi.map((a)=>Fo({text:` ${Kd(a)}: `},{text:FS(t.optional[a]),tone:t.optional[a]?"enabled":"disabled"})),...LS(` Additional plugins: ${t.plugins.length===0?"none":t.plugins.join(" ")}`).map((a)=>te(a,"argument")),te(""),...i.map((a,s)=>te(`${s===n?"\u203A":" "} ${a}`,s===n?"focus":s===0?"success":s===1?"warning":"error"))];return zd(e,o,r)}function LT(e,t,n,r,i,o,a){return zd(e,jT(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,f)=>l+f,0),s=LF(t),c=s.keep+s.replace,u=[te(`HolyCodex \xB7 ${i} review`,"heading"),te("Review the complete preflight plan before applying changes.","hint"),te(`Version: ${o}`),te(`Profile: ${t.profile}`),te(`Service tier: ${t.tier}`),te("CAPABILITIES","heading"),...Vi.map((l)=>Fo({text:` ${Kd(l)}: `},{text:FS(t.capabilities[l]),tone:t.capabilities[l]?"enabled":"disabled"})),te(` Additional plugins: ${t.additionalPlugins.length===0?"none":t.additionalPlugins.join(" ")}`,"argument"),te(`CONFLICTS (${a})`,"heading"),...a===0?[te(" none")]:Object.entries(t.conflictCounts).map(([l,f])=>te(` ${BF(l)}: ${f}`)),...a===0?[]:[te(`DECISIONS (${c})`,"heading"),te(` Keep: ${s.keep}`),te(` Replace: ${s.replace}`)],te("PREREQUISITES","heading"),...t.tools.length===0?[te(" none")]:t.tools.map((l)=>GF(l)),te("\u2191/\u2193 or j/k choose Enter select Esc back Ctrl-C cancel","hint"),...NS(t).map((l,f)=>te(`${f===n?"\u203A":" "} ${UF(l,t.operation)}`,f===n?"focus":l==="apply"?"success":l==="change"||l==="resolve"?"warning":"error"))];return zd(e,u,r)}function GF(e){let t=e.name.toLowerCase()==="context7",n=t?YF(e.status):e.status,r=e.status==="ready"||e.status==="healthy"?"success":"warning",i=t||e.detail===void 0?"":` (${e.detail})`;return Fo({text:` ${e.name}: `},{text:n,tone:r},...i.length===0?[]:[{text:i}])}function YF(e){return e==="ready"?"Use available ctx7":"Attempt optional managed ctx7 install"}function ZF(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.";case"session-audit":return"Review available session evidence for avoidable cost and concrete coordination improvements.";case"auto-reset":return"Monitor quota thresholds and use available banked resets only after the required permission checks."}}function LS(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 Kd(e){switch(e){case"sites":return"ChatGPT Sites";case"browser_use":return"Browser Use";case"computer_use":return"Computer Use";case"session-audit":return"Session audit";case"auto-reset":return"Auto reset"}}function FS(e){return e?"enabled":"disabled"}function XF(e){let t=e.codePointAt(0)??0;return t<=31||t===127}Tl();fd();Ld();cl();pl();Ro();Wa();function VS(e,t={}){let n=t.env===void 0?{...t,env:process.env}:t;if(e.length===0||Yc(e)||e[0]==="help"){let i=e[0]==="help"?e.slice(1).filter((o)=>!o.startsWith("-"))[0]:Zc(e);return A(WT(i===void 0?"help":`${i} help`,{help:Gc(i)}).pipe(me((o)=>({envelope:o,exitCode:0}))))}let r=U({try:()=>ud(e),catch:(i)=>i}).pipe(Ae((i)=>JT(i,n).pipe(Ae((o)=>WT(i.command,o).pipe(me((a)=>({envelope:a,exitCode:hU(i.command,o)})))),$t((o)=>O(HT(i.command,o))))),$t((i)=>O(HT(SU(e),i))));return A(r)}function QF(e,t){let n=t.env===void 0?{...t,env:process.env}:t;return A(JT(e,n))}function JT(e,t){let n=t.env??{};return b(function*(){switch(e.command){case"install":return Yt(yield*nU(e,t));case"doctor":{let r=jl(e,t),i=rr(r,n),o=r.officialPluginManager??(yield*eU(i.codexHome,n));return Yt(yield*Md({...r,officialPluginManager:o},n))}case"remove":return Yt(yield*oU(e,t));case"version":return Yt(yield*aU(e));case"help":return{help:Gc(e.positionals[0])};default:return yield*m(new ts("invalid_argument","Unknown command."))}})}function eU(e,t){return p({try:()=>Or.discover(t),catch:(n)=>n}).pipe(ge(tU,()=>O(new Td(e))))}function tU(e){return e instanceof Error&&"code"in e&&e.code==="discovery_failed"&&e.message.startsWith("No Codex executable was found")}function nU(e,t){return b(function*(){let n=yield*U({try:()=>iU(e),catch:(i)=>i}),r=yield*rU(e,t,n);if("cancelled"in r)return r;return yield*Al(r,jl(e,t),t.env)})}function rU(e,t,n){if(e.options.json!==!0&&e.options.yes!==!0&&t.io?.stdoutIsTTY===!0&&t.io?.stderrIsTTY===!0)return b(function*(){let i=yield*ET(jl(e,t),t.env??{}),o=yield*p({try:()=>(t.io?.installWizard??Wd)({...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*U({try:()=>en(o.request),catch:(a)=>a})});return b(function*(){let i=yield*KT(e,t,"Install HolyCodex into the selected Codex home?");if(i==="cancelled")return{cancelled:!0};if(i==="unavailable")return yield*m(new ts("non_tty_confirmation_required","Install requires --yes in non-interactive mode."));return yield*U({try:()=>en(n),catch:(o)=>o})})}function iU(e){let t=lU(e),n=uU(e),r=cU(e),i=e.options["add-plugin"]===void 0?void 0:fU(e,"add-plugin");return en({...t===void 0?{}:{profile:t},...n===void 0?{}:{tier:n},...r===void 0?{}:{optional:r},...i===void 0?{}:{officialPlugins:i}})}function oU(e,t){return b(function*(){let n=yield*KT(e,t,"Remove HolyCodex-owned Codex state?");if(n==="cancelled")return{cancelled:!0,removed:[],preserved:[],reasons:["cancelled"]};if(n==="unavailable"){let i=(yield*bl(jl(e,t),t.env??{}))[0];if(i!==void 0)return yield*m(new k("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*m(new ts("non_tty_confirmation_required","Remove requires --yes in non-interactive mode."))}return yield*Dd(jl(e,t),t.env??{})})}function aU(e){let t=e.positionals[0];if(!t)return p({try:()=>Vy(),catch:(n)=>n}).pipe(me((n)=>({version:n})));return p({try:()=>Wy(t,e.options["dry-run"]===!0),catch:(n)=>n})}function KT(e,t,n){if(e.options.yes===!0)return O("confirmed");if(e.options.json===!0||t.io?.stdoutIsTTY!==!0||t.io?.stderrIsTTY!==!0)return O("unavailable");return sU(t,n)}function sU(e,t){if(e.io?.confirm===void 0)return O("unavailable");return p({try:()=>e.io.confirm(t),catch:(n)=>n}).pipe(me((n)=>n==="confirmed"||n==="cancelled"||n==="unavailable"?n:n?"confirmed":"cancelled"))}function cU(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 lU(e){let t=Me(cn)(e.options.profile);return Ke(t)?t.success:void 0}function uU(e){let t=Me(vn)(e.options.tier);return Ke(t)?t.success:void 0}function fU(e,t){let n=Me(M(_))(e.options[t]);return Ke(n)?n.success:[]}function jl(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=(v)=>{n.onProgress?.(v),t.onProgress?.(v),xU(t,r,v.message)},a=new Map,s=(v,d)=>{for(let x of v){let S=Ll(x),C=d[S];if(C!==void 0)a.set(S,C)}return d},c=n.resolveConflict??((v)=>b(function*(){if(e.options.yes===!0){let C=yield*jS(v);return yield*zT(t,[v]),C==="keep"?"decline":C==="cancel"?"cancel":"accept"}if(e.options.json===!0||t.io?.stdoutIsTTY!==!0||t.io?.stderrIsTTY!==!0)return yield*m(new k("confirmation_required",`Review the modified HolyCodex-owned state at ${v.key===void 0?v.path:`${v.path} (${v.key})`} in an interactive terminal; --yes preserves user changes.`,void 0,{path:v.path,...v.key===void 0?{}:{key:v.key}}));let d=Ll(v),x=yield*p({try:()=>Hd([v],{},Object.fromEntries(a)),catch:(C)=>C});if(x.action==="back")return"decline";if(x.action!=="continue")return"cancel";let S=x.decisions[d];if(S!==void 0)a.set(d,S);if(S==="replace"||S==="remove")return"accept";if(S==="keep")return"decline";return"cancel"})),u=n.resolveConflicts??(e.options.yes===!0?(v)=>b(function*(){let d={};for(let x of v)d[Ll(x)]=yield*jS(x);return yield*zT(t,v),d}):(v)=>b(function*(){if(e.options.json===!0||t.io?.stdoutIsTTY!==!0||t.io?.stderrIsTTY!==!0)return yield*m(new k("confirmation_required","Managed conflicts require an interactive review or --yes."));let d=yield*p({try:()=>Hd(v,{},Object.fromEntries(a)),catch:(x)=>x});if(d.action==="back"){let x=Object.fromEntries(v.map((S)=>{let C=S.validDecisions??(S.action==="remove"?["keep","remove","cancel"]:["keep","replace","cancel"]);return[Ll(S),C.includes("keep")?"keep":"cancel"]}));return s(v,x)}if(d.action==="cancel")return yield*m(new k("confirmation_required","Conflict review was cancelled."));if(d.action==="continue")return d.decisions;return yield*m(new k("confirmation_required","Conflict review was reopened."))})),l=(v)=>u(v).pipe(me((d)=>s(v,d))),h=n.reviewInstall??(t.io?.installReview===void 0?void 0:(v)=>p({try:()=>t.io.installReview(v),catch:(d)=>d}))??(e.options.yes===!0?()=>O({action:"apply"}):i?(v)=>p({try:()=>$T(v),catch:(d)=>d}):void 0),g=h===void 0?void 0:(v)=>b(function*(){let d=pU(v,a),x=yield*h(mU(d));if(x.action!=="change")return x;if(x.request!==void 0)return yield*U({try:()=>({action:"change",request:en(x.request)}),catch:(C)=>C});if(!i)return yield*m(new k("confirmation_required","Changing install options requires an interactive review."));let S=yield*p({try:()=>(t.io?.installWizard??Wd)(dU(d)),catch:(C)=>C});if(S.action==="cancel")return{action:"cancel"};return yield*U({try:()=>({action:"change",request:en(S.request)}),catch:(C)=>C})}),y=e.options["codex-home"];if(typeof y!=="string")return{...n,onProgress:o,resolveConflict:c,resolveConflicts:l,...g===void 0?{}:{reviewInstall:g},...t.now?{now:t.now}:{}};return{...n,paths:{...n.paths,codexHome:y},onProgress:o,resolveConflict:c,resolveConflicts:l,...g===void 0?{}:{reviewInstall:g},...t.now?{now:t.now}:{}}}function jS(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 m(new k("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 O(r)}function zT(e,t){if(t.length===0)return pt;return b(function*(){let n=[];for(let r of t){let i=yield*jS(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.
|
|
153
|
+
`)})}function dU(e){return en({profile:e.profile,tier:e.tier,optional:e.capabilities,officialPlugins:e.additionalPlugins})}function Ll(e){return e.identity??e.path}function pU(e,t){if(t.size===0||e.conflicts.length===0)return e;return{...e,conflicts:e.conflicts.map((n)=>{let r=t.get(Ll(n));return r===void 0?n:{...n,decision:r}})}}function mU(e){let{fromVersion:t,...n}=e;return{...n,operation:"install"}}function WT(e,t){let n=Lf({schema_version:Hr,ok:!0,command:e,data:t,warnings:[]});if(!n.ok)return m(new ts("internal_error","The success envelope failed validation."));return O(n.value)}function HT(e,t){let n=gU(t,e),r=Lf({schema_version:Hr,ok:!1,command:e,error:{code:n.code,message:n.message,details:n.details},warnings:[]});if(!r.ok)return{envelope:{schema_version:Hr,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 hU(e,t){if(e==="doctor"&&ii(t)&&t.healthy===!1)return 4;if(e==="remove"&&ii(t)){if(t.cancelled===!0)return 1;if(qi(t,"preserved").length>0||qi(t,"reasons").length>0)return 4}return 0}function gU(e,t){if(e instanceof it)return{code:e.code,message:Fl(e.message),details:e.details,exitCode:1};if(e instanceof ts)return{code:e.code,message:Fl(e.message),details:{},exitCode:e.code==="internal_error"?5:1};if(e instanceof Di)return{code:"trust_boundary_failed",message:Fl(e.message),details:{},exitCode:4};if(e instanceof k){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:$S(n.message),details:US(n.details,n.causeValue,t),exitCode:r}}if(e instanceof Ar){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:$S(e.message),details:US(e.details,e.causeValue,t),exitCode:n?4:r?2:3}}if(e instanceof Ir)return{code:e.code,message:$S(e.message),details:US({},e.causeValue,t),exitCode:4};if(e instanceof Ui)return{code:e.code,message:Fl(e.message),details:{},exitCode:1};if(e instanceof Error)return{code:"internal_error",message:`The ${t} command failed unexpectedly.`,details:{operation:t,cause:Uc(`${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 US(e,t,n){let r={...e};if(t!==void 0){if(typeof r.operation!=="string")r.operation=n;r.cause=Uc(yU(t)).join(" ").slice(0,512)}return r}function yU(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 $S(e){return Fl(Uc(e).join(" "))}function SU(e){return e.find((t)=>!t.startsWith("-"))??"unknown"}function Fl(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 ii(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function xU(e,t,n){if(t||e.io?.stderrIsTTY===!1)return;e.io?.writeStderr?.(`${GT(n,{stderrIsTTY:e.io?.stderrIsTTY,env:e.env})}
|
|
154
|
+
`)}function Gd(e,t={}){let n=Ni(t);if(e.envelope.ok){if(e.envelope.command==="version")return EU(e.envelope.data);if(e.envelope.command==="install")return vU(e.envelope.data,n);if(e.envelope.command==="remove")return bU(e.envelope.data,n);if(e.envelope.command==="doctor")return _U(e.envelope.data,n);return`${we("\u2714","green",n)} ${we(e.envelope.command,"heading",n)}
|
|
155
|
+
${wU(e.envelope.data,n)}`}let r=e.envelope.error,i=RU(r.code,e.envelope.command);return[`${we("\u2716","red",n)} ${we(e.envelope.command,"heading",n)}`,` ${we(r.code,"red",n)}: ${r.message}`,...CU(r.details,n),...i===void 0?[]:[` hint: ${i}`],""].join(`
|
|
156
|
+
`)}function GT(e,t={}){return`${we("\u2022","cyan",Ni({...t,stream:"stderr"}))} ${e}`}function EU(e){if(ii(e)&&typeof e.version==="string")return`holycodex ${e.version}
|
|
157
|
+
`;if(ii(e)&&typeof e.next==="string"){let t=typeof e.previous==="string"?` (from ${e.previous})`:"";return`holycodex version updated to ${e.next}${t}
|
|
112
158
|
`}return`holycodex version completed
|
|
113
|
-
`}function
|
|
114
|
-
`;let n=
|
|
159
|
+
`}function vU(e,t){if(qS(e,"cancelled")===!0)return`${we("\u21A9","cyan",t)} ${we("install","heading",t)} cancelled
|
|
160
|
+
`;let n=Ul(e,"record"),r=$l(n,"version")??"unknown",i=$l(n,"profile")??"unknown",o=$l(n,"tier")??"unknown",a=Ul(n,"capability_state"),s=["frontend","security","sites","browser_use","computer_use","session-audit","auto-reset"].filter((g)=>Ul(a,g)?.selected===!0).map((g)=>{let y=$l(Ul(a,g),"status");return y===void 0||y==="healthy"?g:`${g} (${y})`}),c=qi(e,"preserved"),u=qi(e,"warnings"),l=s.length===0?"none":s.join(", "),f=c.length===0?"none":`${c.length} managed item${c.length===1?"":"s"} (review before retrying)`;return`${[`${we("\u2714","green",t)} ${we("install","heading",t)}`,` ${we("version","option",t)}: ${r}`,` ${we("profile","option",t)}: ${i}`,` ${we("tier","option",t)}: ${o}`,` ${we("capabilities","option",t)}: ${l}`,` ${we("preserved","option",t)}: ${f}`,...u.map((g)=>` ${we("warning","warning",t)}: ${zS(g)}`)].join(`
|
|
115
161
|
`)}
|
|
116
|
-
`}function
|
|
117
|
-
`;let n=
|
|
162
|
+
`}function bU(e,t){if(qS(e,"cancelled")===!0)return`${we("\u21A9","cyan",t)} ${we("remove","heading",t)} cancelled
|
|
163
|
+
`;let n=qi(e,"removed"),r=qi(e,"preserved"),i=qi(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`${[`${we(a?"!":"\u2714",a?"warning":"green",t)} ${we(s,a?"warning":"heading",t)}`,` ${we("removed","option",t)}: ${n.length} owned item${n.length===1?"":"s"}`,` ${we("preserved","option",t)}: ${o}`,...i.map((u)=>` ${we("reason","option",t)}: ${zS(u)}`)].join(`
|
|
118
164
|
`)}
|
|
119
|
-
`}function
|
|
165
|
+
`}function _U(e,t){let n=qS(e,"healthy")===!0,r=Ul(e,"checks"),i=r===void 0?[]:Object.entries(r),o=i.flatMap(([c,u])=>{let l=ii(u)?u:void 0,f=$l(l,"status");if(f===void 0||f==="healthy")return[];let h=qi(l,"reasons");return[` ${we(c,"option",t)}: ${h.length===0?f:h.map(zS).join(", ")}`]});return`${[`${n?we("\u2714","green",t):we("\u2716","red",t)} ${we("doctor","heading",t)}`,` ${we("status","option",t)}: ${n?"healthy":"needs attention"}`,` ${we("checks","option",t)}: ${i.length}`,...o.length===0?[]:[` ${we("issues","option",t)}:`,...o]].join(`
|
|
120
166
|
`)}
|
|
121
|
-
`}function
|
|
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])=>` ${
|
|
167
|
+
`}function Ul(e,t){if(!ii(e))return;return ii(e[t])?e[t]:void 0}function qS(e,t){return ii(e)?e[t]:void 0}function $l(e,t){let n=e?.[t];return typeof n==="string"?n:void 0}function qi(e,t){if(!ii(e)||!Array.isArray(e[t]))return[];return e[t]}function zS(e){if(typeof e!=="string")return"operation requires review";return e.replaceAll("_"," ")}function wU(e,t){if(typeof e!=="object"||e===null||Array.isArray(e))return` ${we(BS(e),"dim",t)}
|
|
168
|
+
`;let n=Object.entries(e);if(n.length===0)return"";let r=Math.max(...n.map(([i])=>i.length));return`${n.map(([i,o])=>` ${we(i.padEnd(r),"option",t)}: ${BS(o)}`).join(`
|
|
123
169
|
`)}
|
|
124
|
-
`}function
|
|
125
|
-
`);else if(r.envelope.ok)n.io?.writeStdout?.(
|
|
170
|
+
`}function CU(e,t){return Object.entries(e).map(([n,r])=>` ${we(n,"option",t)}: ${we(BS(r),"dim",t)}`)}function BS(e){if(typeof e==="string")return e;if(e===null||typeof e==="number"||typeof e==="boolean")return String(e);return JSON.stringify(e)}function RU(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 we(e,t,n){return un(e,{red:"error",green:"success",cyan:"focus",dim:"hint",warning:"warning",heading:"heading",option:"option"}[t],n)}class ts extends Error{code;constructor(e,t){super(t);this.name="CliCommandError",this.code=e}}function WS(e=Bun.argv.slice(2),t=IU()){return A(kU(e,t))}function kU(e,t){return b(function*(){let n={env:process.env,cwd:process.cwd(),io:{stdin:t.stdin??PU(),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*p({try:()=>VS(e,n),catch:(i)=>i});if((e.length===0||Yc(e)||e[0]==="help")&&!YT(e))n.io?.writeStdout?.(ky(Zc(e),{stdoutIsTTY:n.io?.stdoutIsTTY,stderrIsTTY:n.io?.stderrIsTTY,env:n.env,stream:"stdout"}));else if(YT(e))n.io?.writeStdout?.(`${JSON.stringify(r.envelope)}
|
|
171
|
+
`);else if(r.envelope.ok)n.io?.writeStdout?.(Gd(r,{stdoutIsTTY:n.io?.stdoutIsTTY,stderrIsTTY:n.io?.stderrIsTTY,env:n.env,stream:"stdout"}));else n.io?.writeStderr?.(Gd(r,{stdoutIsTTY:n.io?.stderrIsTTY,stderrIsTTY:n.io?.stderrIsTTY,env:n.env,stream:"stderr"}));return r.exitCode})}function IU(){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(Wr(dt(()=>TU({input:process.stdin,output:process.stderr})),(t)=>p({try:()=>t.question(`${e} [y/N] `),catch:(n)=>n}).pipe(me((n)=>/^(?:y|yes)$/iu.test(n.trim()))),(t)=>dt(()=>t.close())))}}function YT(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 PU(){let e=new TextDecoder,t=process.stdin[Symbol.asyncIterator](),n=!1;return{[Symbol.asyncIterator](){return{next:()=>A(b(function*(){while(!n){let r=yield*p({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}}))}}}}Tl();Ld();cl();Ro();pl();Pd();Rd();var wG="holycodex";if(import.meta.main)process.exitCode=await WS();export{it as ArgumentError,Un as CONTEXT7_SPEC,$e as CapabilityInstallStateSchema,Ay as CapabilityStateRecordSchema,Or as CodexOfficialPluginManager,hd as InstallOptionsSchema,za as InstallRecordSchema,el as InstallRequestSchema,k as InstallerError,Ar as OfficialPluginManagerError,Di as PathBoundaryError,tl as PersistedInstallOptionsSchema,Td as ReadOnlyCodexPluginStatus,TM as STATE_SCHEMA,ve as ToolingError,UT as applyConflictScreenKey,BT as applyWizardConfigurationKey,Oy as assertRootText,zR as context7InstallCommand,Ao as createInstallerRuntime,Po as detectContext7Manager,QR as doctorHolyCodex,kd as ensureContext7,QF as executeCommand,Yc as helpRequested,Gc as helpText,Zc as helpTopic,hS as installHolyCodex,Qy as installNativeAgents,kF as installRecordDigest,_l as installRequestFromPersistedOptions,wG as packageName,ud as parseArgv,qT as parsePluginInput,Ln as pathWithin,vT as persistedOptionsForInstall,yL as preflightContext7,ji as projectNativeAgents,_d as projectRootAgent,Fn as publicManifestPath,Xa as readActiveInstallRecord,SD as readCanonicalBaseVersion,yD as readCanonicalVersion,dS as readInstallOptions,qy as readInstallationVersion,Vy as readPublicVersion,eT as removeHolyCodex,Cd as removeManagedNativeAgents,Sl as removeOwnedContext7,DF as renderConflictScreen,ky as renderHelp,Gd as renderHuman,zF as renderInstallWizardReview,dl as renderNativeAgent,GT as renderProgress,rr as resolveInstallerPaths,wd as rollbackNativeAgentInstall,Xy as rootDeveloperInstructions,WS as runBinary,VS as runCli,Hd as runOpenTuiConflictResolver,Wd as runOpenTuiInstallWizard,AS as stateFromConflicts,DS as stateFromRequest,VT as toInstallOptions,Wy as updateCanonicalVersion,tT as upgradeHolyCodex,en as validateInstallOptions,QL as writeInstallOptions};
|