holycodex 0.16.10-dev.114.1 → 0.16.10-dev.116.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +1 -1
- package/package.json +2 -2
package/dist/index.js
CHANGED
|
@@ -35,7 +35,7 @@ schema (${r._tag}): ${r}`;return o},$P=(e)=>ji("Invalid Argument",e),jP=(e)=>ji(
|
|
|
35
35
|
`),await this.stdin.flush()}catch(t){throw new ie("transport_failure","The App Server stdin could not be written.",{},{cause:t})}}async close(){if(this.closed)return;this.closed=!0;try{await Promise.resolve(this.stdin.end())}catch{}try{this.process.kill()}catch{}await Promise.race([this.process.exited,new Promise((e)=>setTimeout(()=>e(-1),1000))]),await this.stderrPromise.catch(()=>{return})}async collectStderr(){try{let e=await xh(this.stderrStream,this.maxDiagnosticBytes),t=Sh(e,"Codex stderr");for(let n of t.split(/\r?\n/u).slice(0,128)){let r=zi(n);if(r.length>0)this.stderrDiagnostics.push(r)}}catch{this.stderrDiagnostics.push("[stderr unavailable]")}}}var wh=w(()=>{io()});import{spawn as xV}from"child_process";import{lstat as Xo,mkdir as SV,mkdtemp as bV,readFile as wV,readdir as _V,realpath as U_,rename as vV,rm as RV,stat as AQ}from"fs/promises";import{dirname as v0,isAbsolute as V_,join as Ji,relative as R0,resolve as _h,sep as T0}from"path";async function O0(e){let t=G_(e.selectedPluginIds);if(t.length===0)return;if(A0(e.timeoutMs,e.pollIntervalMs),e.signal?.aborted)throw new he("cancelled","Official Codex marketplace bootstrap was cancelled.");let n=e.readSnapshot??((s)=>J_(s,e.selectedPluginIds)),r=await n(e.codexHome);if(r!==void 0&&Rh(r,t))return r;let o=e.initializeRuntime??(()=>UV(e)),i,a;try{i=await o()}catch(s){a=se("marketplace_unavailable","Codex runtime initialization could not start the official marketplace sync. Check that Codex is available and its network/policy settings permit the official marketplace.",s)}if(a===void 0)try{let s=e.timeoutMs??K_,c=e.pollIntervalMs??CV,l=Date.now();while(Date.now()-l<=s){if(e.signal?.aborted)throw new he("cancelled","Official Codex marketplace bootstrap was cancelled.");let u=await n(e.codexHome);if(u!==void 0&&Rh(u,t))return u;let d=s-(Date.now()-l);if(d<=0)break;await(e.sleep??P0)(Math.min(c,d))}a=se("marketplace_timeout","The official Codex marketplace did not become ready before the bounded wait expired. Check network access and Codex marketplace policy, then retry.")}catch(s){if(s instanceof he&&s.code==="cancelled")throw s;a=s instanceof he?s:se("marketplace_unavailable","The official Codex marketplace sync failed before its bounded wait completed.",s)}finally{await i?.()}if(e.gitFallback!==!1)try{return await k0({codexHome:e.codexHome,selectedPluginIds:e.selectedPluginIds,...e.environment===void 0?{}:{environment:e.environment},...e.timeoutMs===void 0?{}:{timeoutMs:e.timeoutMs},...e.signal===void 0?{}:{signal:e.signal},...e.gitFallback===void 0?{}:e.gitFallback})}catch(s){if(s instanceof he)throw s;throw se("marketplace_unavailable",`The official marketplace could not be populated after runtime startup (${a?.code??"unavailable"}). Check network access and retry.`,s)}throw a??se("marketplace_timeout","The official Codex marketplace did not become ready before the bounded wait expired.")}async function k0(e){let t=G_(e.selectedPluginIds);if(t.length===0)throw se("marketplace_invalid","The official marketplace fallback requires at least one selected provider plugin.");if(A0(e.timeoutMs,void 0),!V_(e.codexHome))throw se("marketplace_invalid","The Codex home for official marketplace fallback must be absolute.");if(e.signal?.aborted)throw new he("cancelled","Official Codex marketplace fallback was cancelled.");let n=Wi(e.environment),r=e.gitRunner??F0("git",{environment:n,...e.timeoutMs===void 0?{}:{timeoutMs:e.timeoutMs}}),o=e.timeoutMs??K_,i;try{i=await PV(r,o,e.signal)}catch(u){if(u instanceof he)throw u;throw se("marketplace_unavailable","The official Codex marketplace remote HEAD could not be resolved. Check network access and retry.",u)}let a=Ji(e.codexHome,"plugins"),s=Ji(a,z_[1]);if(await NV(a,e.codexHome),await Xo(s).catch((u)=>{if(Fc(u))return;throw se("marketplace_invalid","The reserved official marketplace path could not be inspected safely.",u)})!==void 0)throw se("marketplace_invalid","The reserved official marketplace path appeared during bootstrap; refusing to overwrite it.");let l=await bV(Ji(a,".openai-plugins-stage-"));try{if(await j_(e.codexHome,l),e.cloneSnapshot!==void 0)try{await e.cloneSnapshot(rs,l)}catch(f){if($V(f))throw se("marketplace_invalid","The staged official marketplace could not be created as a safe file tree.",f);throw f}else{let f=await r.run(["-c","core.longpaths=true","clone","--depth=1","--no-tags",rs,l],{...e.signal===void 0?{}:{signal:e.signal},timeoutMs:o});if(f.exitCode!==0)throw se("marketplace_unavailable","The official Codex marketplace could not be downloaded. Check network access and retry.",f.stderr)}await vh(l);let u=await E0(l,e.codexHome,t);if(u===void 0||!Rh(u,t))throw se("marketplace_invalid","The downloaded official marketplace is missing the selected plugin entries or manifest.");if(await MV(r,l,o,e.signal)!==i)throw se("marketplace_invalid","The downloaded official marketplace did not match the verified remote HEAD.");if(await Xo(s).catch((f)=>{if(Fc(f))return;throw se("marketplace_invalid","The reserved official marketplace path could not be checked before publication.",f)})!==void 0)throw se("marketplace_invalid","The reserved official marketplace path appeared during staging; refusing to overwrite it.");await IV(l,s,e.renameSnapshot??vV);let m=await J_(e.codexHome,e.selectedPluginIds);if(m===void 0||!Rh(m,t))throw se("marketplace_invalid","The published official marketplace failed validation.");return m}catch(u){if(u instanceof he)throw u;throw se("marketplace_unavailable","The official Codex marketplace fallback failed safely. Check network access and retry.",u)}finally{await RV(l,{recursive:!0,force:!0}).catch(()=>{return})}}async function IV(e,t,n){for(let r=0;;r+=1)try{await n(e,t);return}catch(o){let i=OV[r];if(process.platform!=="win32"||i===void 0||!AV(o))throw o;if(await Xo(t).catch((s)=>{if(Fc(s))return;throw se("marketplace_invalid","The reserved official marketplace path could not be checked before retrying publication.",s)})!==void 0)throw se("marketplace_invalid","The reserved official marketplace path appeared during publication; refusing to overwrite it.");await P0(i)}}function AV(e){return e!==null&&typeof e==="object"&&"code"in e&&(e.code==="EPERM"||e.code==="EBUSY")}async function PV(e,t,n){let r=await e.run(["ls-remote",rs,"HEAD"],{...n===void 0?{}:{signal:n},timeoutMs:t});if(r.exitCode!==0)throw se("marketplace_unavailable","The official Codex marketplace remote HEAD could not be resolved. Check network access and retry.",r.stderr);let o=r.stdout.trim().split(/\r?\n/u).map((a)=>a.trim()).filter((a)=>a.length>0),i=o.length===1?/^([0-9a-f]{40}|[0-9a-f]{64})\s+HEAD$/iu.exec(o[0]??""):null;if(i?.[1]===void 0)throw se("marketplace_invalid","The official Codex marketplace remote HEAD response was malformed.");return i[1].toLowerCase()}async function MV(e,t,n,r){let o=await e.run(["rev-parse","HEAD"],{timeoutMs:n,cwd:t,...r===void 0?{}:{signal:r}}),i=o.stdout.trim().toLowerCase();if(o.exitCode!==0||!/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/u.test(i))throw se("marketplace_invalid","The downloaded official marketplace checkout did not expose a valid HEAD.",o.stderr);return i}async function NV(e,t){await $_(t,e),await SV(e,{recursive:!0}),await $_(t,e)}async function $_(e,t){let n=_h(e),r=_h(t);while(!0){if((await Xo(r).catch((a)=>{if(Fc(a))return;throw a}))?.isSymbolicLink())throw se("marketplace_invalid","The official marketplace path cannot contain symlinks.");if(r===n)return;let i=v0(r);if(i===r||i!==n&&!FV(n,i))throw se("marketplace_invalid","The official marketplace path escaped CODEX_HOME.");r=i}}function FV(e,t){let n=R0(e,t);return n.length>0&&n!==".."&&!n.startsWith(`..${T0}`)&&!V_(n)}async function vh(e){let t=await Xo(e);if(t.isSymbolicLink())throw se("marketplace_invalid","The official marketplace snapshot cannot contain symlinks.");if(!t.isDirectory())throw se("marketplace_invalid","The official marketplace snapshot is not a directory.");let n=await _V(e,{withFileTypes:!0});for(let r of n){let o=Ji(e,r.name),i=await Xo(o);if(i.isSymbolicLink())throw se("marketplace_invalid","The official marketplace snapshot cannot contain symlinks.");if(i.isDirectory())await vh(o)}}async function J_(e,t=[]){return await E0(Ji(e,...z_),e,G_(t))}async function E0(e,t,n=[]){if(t!==void 0)await $_(t,e);let r=await Xo(e).catch((l)=>{if(Fc(l))return;throw se("marketplace_invalid","The reserved openai-curated marketplace path could not be read safely.",l)});if(r===void 0)return;if(r.isSymbolicLink()||!r.isDirectory())throw se("marketplace_invalid","The reserved openai-curated marketplace path is not a real directory.");if(t!==void 0)await j_(t,e);else await vh(e);if(t!==void 0)await vh(e);let o=await U_(e),i=[Ji(o,".agents","plugins","marketplace.json"),Ji(o,".codex-plugin","marketplace.json"),Ji(o,"marketplace.json")],a,s;for(let l of i){let u=await Xo(l).catch((d)=>{if(Fc(d))return;throw se("marketplace_invalid","The official marketplace manifest could not be read safely.",d)});if(u===void 0)continue;if(u.isSymbolicLink()||!u.isFile())throw se("marketplace_invalid","The official marketplace manifest is not a regular file.");if(await j_(o,l),a!==void 0)throw se("marketplace_invalid","The reserved official marketplace contains more than one manifest.");a=l;try{s=new TextDecoder("utf-8",{fatal:!0}).decode(await wV(l))}catch(d){throw se("marketplace_invalid","The official marketplace manifest is not valid UTF-8.",d)}}if(a===void 0||s===void 0)return;let c;try{c=JSON.parse(s)}catch(l){throw se("marketplace_invalid","The official marketplace manifest is not valid JSON.",l)}return I0(c,o,a,n)}function I0(e,t=`${z_.join("/")}`,n=`${t}/marketplace.json`,r=[]){if(!de(e)||e.name!==ld)throw se("marketplace_invalid","The reserved official marketplace manifest has an unexpected name.");LV(e);let o=e.plugins;if(!Array.isArray(o)||o.length===0)throw se("marketplace_invalid","The official marketplace manifest has no plugin entries.");let i=[],a=new Set;for(let s of o){if(!de(s)||typeof s.name!=="string"){if(r.length>0)continue;throw se("marketplace_invalid","The official marketplace contains a malformed plugin entry.")}let c=s.name;if(!/^[a-z][a-z0-9._-]{1,63}$/u.test(c)){if(r.length>0)continue;throw se("marketplace_invalid","The official marketplace contains an invalid plugin name.")}if(a.has(c)){if(r.length>0&&!r.includes(c))continue;throw se("marketplace_invalid","The official marketplace contains a duplicate plugin name.")}if(a.add(c),r.length>0&&!r.includes(c))continue;let l=DV(s);if(!qV(l))throw se("marketplace_invalid",`The official marketplace source for ${c} is unsafe.`);i.push({name:c,source:l})}if(r.some((s)=>!i.some((c)=>c.name===s)))throw se("marketplace_invalid","The official marketplace is missing a selected plugin entry.");return{name:ld,source:rs,rootPath:t,manifestPath:n,plugins:i}}function LV(e){for(let t of["source","repository","repo","url"]){let n=e[t];if(n===void 0)continue;if((typeof n==="string"?n:de(n)&&typeof n.url==="string"?n.url:void 0)!==rs)throw se("marketplace_invalid","The reserved official marketplace source is not the approved OpenAI repository.")}}function DV(e){let t=e.source;if(typeof t==="string")return t;if(de(t)&&typeof t.path==="string")return t.path;if(typeof e.path==="string")return e.path;return}function qV(e){if(e===void 0||e.length===0||V_(e))return!1;if(/^[A-Za-z]:[\\/]/u.test(e))return!1;let t=e.replaceAll("\\","/");if(t.startsWith("/")||/^[A-Za-z][A-Za-z0-9+.-]*:/u.test(t))return!1;return t.split("/").every((n)=>n.length===0||n==="."||n!=="..")}function G_(e){let t=[],n=new Set;for(let r of e){let o=r.lastIndexOf("@");if(o<1)continue;let i=r.slice(o+1);if(i!==ld&&i!=="openai-curated-remote")continue;let a=r.slice(0,o);if(!/^[a-z][a-z0-9._-]{1,63}$/u.test(a))throw se("marketplace_invalid","A selected official marketplace plugin id is invalid.");if(!M0(a))continue;if(!n.has(a))n.add(a),t.push(a)}return t}function Rh(e,t){return t.every((n)=>{let r=e.plugins.find((i)=>i.name===n);if(r===void 0)return!1;return r.source.replaceAll("\\","/").replace(/\/+$/u,"").split("/").at(-1)===n})}async function UV(e){let t=Wi(e.environment),n;try{n=new bh({executablePath:e.executablePath,environment:t,...e.signal===void 0?{}:{signal:e.signal}});let r=new yh(n,{requestTimeoutMs:Math.min(e.timeoutMs??K_,1e4),...e.signal===void 0?{}:{signal:e.signal}});return await r.initialize(),async()=>{await r.close()}}catch(r){throw await n?.close().catch(()=>{return}),r}}function A0(e,t){if(e!==void 0&&(!Number.isSafeInteger(e)||e<1||e>300000))throw se("marketplace_invalid","The official marketplace timeout is invalid.");if(t!==void 0&&(!Number.isSafeInteger(t)||t<0||t>60000))throw se("marketplace_invalid","The official marketplace poll interval is invalid.")}async function j_(e,t){let n=await U_(e),r=await U_(t),o=R0(n,r);if(o===""||o===".."||o.startsWith(`..${T0}`))throw se("marketplace_invalid","The reserved official marketplace is outside CODEX_HOME.");let i=_h(e),a=_h(t);while(!0){if((await Xo(a)).isSymbolicLink())throw se("marketplace_invalid","The reserved official marketplace path cannot contain symlinks.");if(a===i)break;let c=v0(a);if(c===a)throw se("marketplace_invalid","The reserved official marketplace path is outside CODEX_HOME.");a=c}}function Fc(e){return typeof e==="object"&&e!==null&&"code"in e&&e.code==="ENOENT"}function $V(e){return typeof e==="object"&&e!==null&&"code"in e&&(e.code==="EPERM"||e.code==="EACCES")}async function P0(e){await new Promise((t)=>setTimeout(t,e))}function se(e,t,n){return new he(e,t,n instanceof Error?{cause:zi(n.message)}:{})}function ao(e,t){let n=Qn(t);if(n===void 0||n!==t)return;let o=[...e.installed,...e.available].flatMap((i)=>{let a=Cw(i.pluginId,i.marketplaceName);return a?.canonicalPluginId===n?[{identity:a,entry:i}]:[]});return o.find((i)=>i.entry.pluginId===n&&i.entry.installed)??o.find((i)=>i.entry.installed)??o.find((i)=>i.entry.pluginId===n)??o[0]}function M0(e){return th.includes(e)}function N0(e){if(!b0(B_,e))return y0(Qe("live official plugin list",e));return x0(Ve(B_,e,"live official plugin list"))}function Th(e){let t=e.runner??F0(e.executable,{environment:e.environment??Wi(),...e.timeoutMs===void 0?{}:{timeoutMs:e.timeoutMs},...e.stdoutLimit===void 0?{}:{stdoutLimit:e.stdoutLimit},...e.stderrLimit===void 0?{}:{stderrLimit:e.stderrLimit}}),n=async()=>{let o=await t.run(["plugin","list","--json"]);if(o.exitCode!==0)throw Ki("list",o);let i;try{i=JSON.parse(o.stdout)}catch{throw new he("command_failed","Codex returned invalid plugin data.")}let a=N0(i);if(!a.ok)throw new he("command_failed","Codex returned an invalid official plugin list.");return a.value},r=async()=>{let o=await t.run(["plugin","marketplace","list","--json"]);if(o.exitCode!==0)throw Ki("marketplace list",o);let i;try{i=JSON.parse(o.stdout)}catch{throw new he("command_failed","Codex returned invalid marketplace data.")}if(!de(i)||!Array.isArray(i.marketplaces))throw new he("command_failed","Codex returned an invalid marketplace list.");return i.marketplaces.map((a)=>{if(!de(a)||typeof a.name!=="string"||typeof a.root!=="string")throw new he("command_failed","Codex returned an invalid marketplace entry.");let s=a.marketplaceSource;if(s===void 0)return{name:a.name,root:a.root};if(!de(s)||typeof s.sourceType!=="string"||typeof s.source!=="string")throw new he("command_failed",`Codex returned an invalid source for marketplace ${a.name}.`);return{name:a.name,root:a.root,marketplaceSource:{sourceType:s.sourceType,source:s.source}}})};return{list:n,ensureOfficialMarketplace:async(o)=>{if(e.codexHome===void 0)throw new he("marketplace_unavailable","Codex home is unavailable; the official marketplace cannot be bootstrapped safely.");await O0({codexHome:e.codexHome,executablePath:e.executable,selectedPluginIds:o,...e.environment===void 0?{}:{environment:e.environment},...e.timeoutMs===void 0?{}:{timeoutMs:e.timeoutMs},...e.officialMarketplaceFallback===void 0?{}:{gitFallback:e.officialMarketplaceFallback}})},addMarketplace:async(o,i)=>{let a=Ve(ns,o,"plugin marketplace source");if(a===ld||a===rs)throw new he("marketplace_invalid","The reserved openai-curated marketplace must be populated by Codex runtime startup; it cannot be added manually.");if(a!==W_)throw new he("marketplace_invalid",`Unsupported managed marketplace source: ${a}.`);let s,c=!1;try{s=await r()}catch(x){if(!BV(x))throw x;e.onMarketplaceConflict?.("The registered HolyCodex marketplace cache is incomplete; Codex will rebuild it from the canonical source.");let v=await t.run(["plugin","marketplace","add",a],i===void 0?void 0:{signal:i});if(v.exitCode!==0)throw Ki("marketplace add",v,a);s=await r(),c=!0}let l=q_(s,Zo),u=VV(s,Zo);if(l!==void 0&&u.length>0){e.onMarketplaceConflict?.(`${l} HolyCodex will remove the conflicting registration and restore its required source.`);for(let x of u){let v=await t.run(["plugin","marketplace","remove",x],i===void 0?void 0:{signal:i});if(v.exitCode!==0)throw Ki("marketplace remove",v,x)}}let d=u.length===0?s:await r(),p=q_(d,Zo);if(p!==void 0)throw new he("marketplace_invalid",p);if(d.find((x)=>x.name===Zo)===void 0){let x=await t.run(["plugin","marketplace","add",a],i===void 0?void 0:{signal:i});if(x.exitCode!==0)throw Ki("marketplace add",x,a)}else if(!c){let x=await t.run(["plugin","marketplace","upgrade",Zo],i===void 0?void 0:{signal:i});if(x.exitCode!==0)throw Ki("marketplace upgrade",x,Zo)}let f=await r(),y=q_(f,Zo);if(y!==void 0)throw new he("marketplace_invalid",y);let g=f.find((x)=>x.name===Zo);if(g===void 0||!ud(g.marketplaceSource))throw new he("readback_mismatch","Codex did not report the canonical HolyCodex marketplace after installation or refresh.")},add:async(o,i)=>{let a=Ve(ns,o,"official plugin id"),s=Ic(a),c=Qn(a)==="computer-use@openai-bundled"?s:s.includes(a)?[a,...s.filter((y)=>y!==a)]:[a],l=!1;for(let[y,g]of c.entries()){let x=await t.run(["plugin","add",g,"--json"],i===void 0?void 0:{signal:i});if(x.exitCode===0){l=!0;break}if(y<c.length-1&&HV(x.stderr))continue;throw Ki("add",x,g)}if(!l)throw new he("command_failed",`Codex could not install ${a} from its recognized marketplace sources.`);let u=await n(),d=ao(u,a),p=Qn(a),m=[...u.installed,...u.available].filter((y)=>y.pluginId===a&&(p===void 0||y.marketplaceName==null)),f=d?.entry??m.find((y)=>y.installed)??m[0];if(!f)throw new he("readback_mismatch",`Codex did not report ${a} after installation.`,{plugin_id:a});if(!f.installed)throw new he("plugin_missing",`Codex reported ${a} as unavailable after installation.`,{plugin_id:a});if(!f.enabled)throw new he("plugin_disabled",`Codex installed ${a} but it is disabled; enable it in Codex and retry.`,{plugin_id:a})},remove:async(o,i)=>{let a=Ve(ns,o,"official plugin id"),s=a;if(Qn(a)===a){let d=await n(),p=ao(d,a);if(p?.entry.installed)s=p.entry.pluginId}let c=await t.run(["plugin","remove",s,"--json"],i===void 0?void 0:{signal:i});if(c.exitCode!==0&&!/not (?:installed|found)|missing/iu.test(c.stderr))throw Ki("remove",c,s);let l=await n(),u=[...l.installed,...l.available].find((d)=>d.pluginId===s);if(u?.installed)throw new he("readback_mismatch",`Codex still reports ${a} after removal.`,{plugin_id:a,observed_plugin_id:u.pluginId})}}}function Ki(e,t,n){let r=zi(t.stderr).trim().slice(0,512),o=r.length>0?`: ${r}`:"";return new he("command_failed",`Codex plugin ${e} failed${n===void 0?"":` for ${n}`}${o}`,{exit_code:t.exitCode})}function HV(e){return/plugin\b.+\bnot found in marketplace\b/iu.test(zi(e))}function BV(e){if(!(e instanceof he)||e.code!=="command_failed")return!1;return/(?:^|[\n:])\s*-\s*`([^`]+)`\s+at\s+[^\r\n]*:\s*marketplace root does not contain a supported manifest/iu.exec(e.message)?.[1]===Zo}function q_(e,t){let n=e.filter((o)=>o.name===t);if(n.length>1)return`Multiple Codex marketplaces use the reserved name ${t}; resolve the duplicate configuration before installing HolyCodex.`;if(n[0]!==void 0&&!ud(n[0].marketplaceSource)){let o=n[0].marketplaceSource?.source??"an unknown source";return`Codex marketplace ${t} points to ${o}, not the canonical HolyCodex source ${W_}; resolve the conflict before installing.`}let r=e.find((o)=>o.name!==t&&ud(o.marketplaceSource));if(r!==void 0)return`The canonical HolyCodex source is already registered as Codex marketplace ${r.name}; resolve the noncanonical marketplace name before installing.`;return}function VV(e,t){let r=e.filter((o)=>o.name===t).length>1;return[...new Set(e.filter((o)=>o.name===t&&(r||!ud(o.marketplaceSource))||o.name!==t&&ud(o.marketplaceSource)).map((o)=>o.name))]}function ud(e){if(e?.sourceType!=="git")return!1;return Ch(e.source)}function Ch(e){return TV.some((t)=>t===e)}function F0(e,t){let n=t.timeoutMs??30000,r=t.stdoutLimit??131072,o=t.stderrLimit??16384;return{run:(i,a)=>WV(e,i,{...t.environment===void 0?{}:{environment:t.environment},timeoutMs:a?.timeoutMs??n,stdoutLimit:r,stderrLimit:o,...a?.cwd===void 0?{}:{cwd:a.cwd},...a?.signal===void 0?{}:{signal:a.signal}})}}async function WV(e,t,n){if(n.signal?.aborted)throw new he("cancelled","The Codex plugin command was cancelled.");let r=xV(e,[...t],{env:n.environment===void 0?void 0:{...n.environment},...n.cwd===void 0?{}:{cwd:n.cwd},stdio:["ignore","pipe","pipe"],windowsHide:!0}),o=_0(r.stdout,n.stdoutLimit),i=_0(r.stderr,n.stderrLimit),a=new Promise((d,p)=>{r.once("error",p),r.once("close",(m)=>d(m??-1))}),s,c,l=new Promise((d,p)=>{c=()=>{try{r.kill()}catch{}p(new he("cancelled","The Codex plugin command was cancelled."))},n.signal?.addEventListener("abort",c,{once:!0})}),u=new Promise((d,p)=>{s=setTimeout(()=>{try{r.kill()}catch{}p(new he("timeout","The Codex plugin command timed out."))},n.timeoutMs)});try{let[d,p,m]=await Promise.race([Promise.all([o,i,a]),l,u]);return{stdout:d,stderr:p,exitCode:m}}catch(d){try{r.kill()}catch{}if(d instanceof he)throw d;throw new he("command_failed","The Codex plugin command failed.")}finally{if(s!==void 0)clearTimeout(s);if(c!==void 0)n.signal?.removeEventListener("abort",c)}}function _0(e,t){if(e===null)return Promise.reject(new he("command_failed","Codex plugin command output is unavailable."));return new Promise((n,r)=>{let o=[],i=0;e.on("data",(a)=>{let s=typeof a==="string"?new TextEncoder().encode(a):a instanceof Uint8Array?a:void 0;if(s===void 0){r(new he("command_failed","Codex plugin output was invalid."));return}if(i+=s.byteLength,i>t){r(new he("output_limit","Codex plugin output exceeded its limit."));return}o.push(s)}),e.once("end",()=>{let a=new Uint8Array(i),s=0;for(let c of o)a.set(c,s),s+=c.byteLength;try{n(new TextDecoder("utf-8",{fatal:!0}).decode(a))}catch(c){r(c)}}),e.once("error",(a)=>r(a))})}var ld="openai-curated",rs="https://github.com/openai/plugins.git",Zo="holycodex",W_="davidbasilefilho/holycodex",TV,z_,K_=30000,CV=100,OV,C0,kV,cd,ns,EV,jV,H_,B_,he;var Oh=w(()=>{ht();Dt();o_();io();wh();TV=[W_,"https://github.com/davidbasilefilho/holycodex.git","https://github.com/davidbasilefilho/holycodex","https://github.com/davidbasilefilho/holycodex.git/","https://github.com/davidbasilefilho/holycodex/","git@github.com:davidbasilefilho/holycodex.git","git@github.com:davidbasilefilho/holycodex","ssh://git@github.com/davidbasilefilho/holycodex.git","ssh://git@github.com/davidbasilefilho/holycodex"],z_=["plugins","openai-plugins"],OV=[25,50,100,200],C0=q.pipe(we(/^[a-z][a-z0-9._-]{1,63}$/u)),kV=q.pipe(we(/^[0-9]+\.[0-9]+\.[0-9]+(?:[-+][A-Za-z0-9.-]+)?$/u)),cd=K(q),ns=q.pipe(we(/^[A-Za-z0-9][A-Za-z0-9._:@/-]{0,255}$/u)),EV=T({name:C0,version:kV,description:Yo,author:R($n),license:R(Yo),homepage:R(Yo),repository:R(Yo),keywords:R(cd),skills:R(cd),commands:R(cd),hooks:R(cd),assets:R(cd),official:R(V)});jV=T({id:C0,selected:E(!0)}),H_=T({pluginId:ns,installed:V,enabled:V,name:R(Se(q,At)),marketplaceName:R(Se(q,At)),version:R(Se(q,At))},Zm({key:q,value:pw})),B_=T({installed:K(H_),available:K(H_)});he=class he extends Error{code;details;constructor(e,t,n={}){super(t);this.name="OfficialPluginAdapterError",this.code=e,this.details=n}}});function Lc(e,t=new Set){if(e===null||typeof e==="string"||typeof e==="boolean")return!0;if(typeof e==="number")return Number.isFinite(e);if(typeof e!=="object")return!1;if(t.has(e))return!1;t.add(e);try{if(Array.isArray(e))return e.every((n)=>Lc(n,t));return de(e)&&Object.values(e).every((n)=>Lc(n,t))}finally{t.delete(e)}}function Ir(e){return de(e)&&Lc(e)}function Z_(e){let t=[],n=0,r=!1,o=!1;for(let i=0;i<=e.length;i+=1){let a=e[i];if(i===e.length||a==="."&&!r){let s=e.slice(n,i),c=s.startsWith('"')?KV(s):s,l=s.startsWith('"'),u=l&&t.length===1&&t[0]==="plugins"&&Gm(ns)(c),d=l&&t.length===1&&t[0]==="agents"&&Y_.includes(c);if(l?!u&&!d:!/^[A-Za-z][A-Za-z0-9_-]*$/u.test(c)&&!Y_.includes(c))throw Qe("TOML key path",e);if(c==="__proto__"||(c==="constructor"||c==="prototype")&&!u)throw Qe("TOML key path",e);t.push(c),n=i+1;continue}if(r){if(o)o=!1;else if(a==="\\")o=!0;else if(a==='"')r=!1}else if(a==='"')r=!0}if(r||o||t.length===0)throw Qe("TOML key path",e);return t}function KV(e){try{let t=JSON.parse(e);if(typeof t==="string")return t}catch{}throw Qe("TOML quoted key",e)}function fe(e,t){if(!Ir(e))throw Qe("TOML document",e);let n=e,r=Z_(t);for(let o=0;o<r.length;o+=1){let i=r[o];if(!Ir(n)||!Object.prototype.hasOwnProperty.call(n,i))return;if(n=n[i],o===1&&r[0]==="features"&&i==="context_management"&&typeof n==="boolean"&&r[2]==="experimental_mode")return n}return n}function kh(e){if(Array.isArray(e))return e.map(kh);if(de(e))return Object.fromEntries(Object.entries(e).map(([t,n])=>[t,kh(n)]));return e}function Eh(e){return kh(e)}function so(e,t,n){if(!Ir(e)||!Lc(n))throw Qe("TOML write",{keyPath:t});let r=Z_(t),o={...Eh(e)},i=o;for(let a of r.slice(0,-1)){let s=Object.prototype.hasOwnProperty.call(i,a)?i[a]:void 0;if(s!==void 0&&!Ir(s)){if(a!=="context_management"||typeof s!=="boolean"||i!==o.features)throw Qe("TOML table path",t);if(r.at(-1)==="experimental_mode"&&s===n)return o;i[a]={experimental_mode:s}}let c=s===void 0?{}:Ir(i[a])?{...i[a]}:{};i[a]=c,i=c}return i[r.at(-1)]=kh(n),o}function tr(e,t){if(!Ir(e))throw Qe("TOML document",e);let n=Z_(t),r={...Eh(e)},o=[],i=r;for(let s of n.slice(0,-1)){let c=i[s];if(!Ir(c))return r;let l={...c};o.push({table:i,key:s}),i[s]=l,i=l}let a=n.at(-1);if(!Object.prototype.hasOwnProperty.call(i,a))return r;delete i[a];for(let s=o.length-1;s>=0;s-=1){let c=o[s],l=c.table[c.key];if(Ir(l)&&Object.keys(l).length===0)delete c.table[c.key];else break}return r}function is(e){if(typeof e!=="string")return!1;if(D0.includes(e))return!0;if(/^agents\.(?:explorer|librarian|worker|reviewer)\.config_file$/u.test(e))return!0;return Y_.some((t)=>e===`agents."${t}".config_file`)}function Ih(e){return is(e)||Zi.includes(e)}function Gi(e){return typeof e==="string"&&GV.test(e)}function X_(e){return e==="gpt-6-astra"||e==="gpt-6.1-sol"||e==="gpt-6-sol"||e==="gpt-6-luna"||e==="gpt-5.6-terra"||e==="gpt-5.6-sol"||e==="gpt-5.6-luna"||e==="low"||e==="medium"||e==="high"||e==="xhigh"||e==="max"||e==="default"||e==="fast"||e==="live"||e==="cached"||e==="indexed"||e==="disabled"}function YV(e){return typeof e==="string"&&/^[a-f0-9]{64}$/u.test(e)}function Q_(e){return typeof e==="number"&&Number.isSafeInteger(e)&&e>=0}function ev(e,t){let n=new Set(t);return Object.keys(e).every((r)=>n.has(r))}function tv(e){if(!de(e)||!ev(e,["kind","value"])||typeof e.kind!=="string")return!1;switch(e.kind){case"enum":return X_(e.value);case"number":return Q_(e.value);case"boolean":return typeof e.value==="boolean";case"relative_path":return typeof e.value==="string"&&Mh(e.value);case"digest":return YV(e.value);default:return!1}}function L0(e,t){switch(rv(e)){case"number":return t.kind==="number";case"boolean":return t.kind==="boolean";case"relative_path":return t.kind==="relative_path";case"digest":return t.kind==="digest";case"enum":if(t.kind!=="enum")return!1;if(e==="model")return t.value==="gpt-6-astra"||t.value==="gpt-6.1-sol"||t.value==="gpt-6-sol"||t.value==="gpt-6-luna"||t.value==="gpt-5.6-terra"||t.value==="gpt-5.6-sol"||t.value==="gpt-5.6-luna";if(e==="model_reasoning_effort")return t.value==="low"||t.value==="medium"||t.value==="high"||t.value==="xhigh"||t.value==="max";if(e==="service_tier")return t.value==="default"||t.value==="fast";if(e==="web_search")return t.value==="live"||t.value==="cached"||t.value==="indexed"||t.value==="disabled";return t.value==="low"||t.value==="medium"||t.value==="high"}}function j0(e){return de(e)&&e.kind==="absent"?Object.keys(e).length===1:tv(e)}function H0(e){return de(e)&&ev(e,["owner","schema","installId","keyPath","originalValue","lastManagedValue"])&&e.owner==="holycodex"&&typeof e.schema==="string"&&Gi(e.schema)&&Gi(e.installId)&&Ih(e.keyPath)&&j0(e.originalValue)&&tv(e.lastManagedValue)&&L0(e.keyPath,e.lastManagedValue)&&(e.originalValue.kind==="absent"||L0(e.keyPath,e.originalValue))}function Yi(e){if(!de(e)||!ev(e,["owner","schema","installId","managed"])||e.owner!=="holycodex"||!Gi(e.schema)||!Gi(e.installId)||!de(e.managed))return!1;return Object.entries(e.managed).every(([t,n])=>Ih(t)&&H0(n)&&n.keyPath===t)}function Ph(e){if(!Gi(e.schema)||!Gi(e.installId))throw Qe("managed runtime config metadata",{schema:e.schema});return{owner:"holycodex",schema:e.schema,installId:e.installId,managed:{}}}function Mh(e){if(e.length===0||e.includes("\x00")||/^[\\/]|^[A-Za-z]:[\\/]/u.test(e))return!1;let t=e.replaceAll("\\","/").split("/");return t.some((n)=>n!==".")&&t.every((n)=>n.length>0&&n!=="..")}function nv(e){if(!Mh(e))throw Qe("relative config path","[redacted]");return e.replaceAll("\\","/").split("/").filter((t)=>t!==".").join("/")}function as(e,t){let n=nv(t),r=e.replaceAll("\\","/").split("/");r.pop();let o=[...r,...n.split("/")].join("/"),i=[];for(let c of o.split("/")){if(c.length===0||c===".")continue;if(c==="..")i.pop();else i.push(c)}let a=e.replaceAll("\\","/");return`${a.startsWith("//")?"//":a.startsWith("/")?"/":""}${i.join("/")}`}function rv(e){if(e==="developer_instructions")return"digest";if(e.endsWith(".config_file"))return"relative_path";if(e==="agents.max_concurrent_threads_per_session")return"number";if(e==="model_auto_compact_token_limit")return"number";if(e==="suppress_unstable_features_warning"||e==="features.multi_agent"||e==="features.default_mode_request_user_input"||e==="features.multi_agent_v2"||e==="features.agent_message_board"||e==="features.context_management.experimental_mode"||Zi.includes(e)||e==="sandbox_workspace_write.network_access")return"boolean";return"enum"}function ZV(e,t){let n=rv(e);if(n==="number")return Q_(t);if(n==="boolean")return typeof t==="boolean";if(n==="relative_path")return typeof t==="string"&&Mh(t);if(n==="digest")return typeof t==="string";if(e==="model")return t==="gpt-6-astra"||t==="gpt-6.1-sol"||t==="gpt-6-luna";return typeof t==="string"&&X_(t)}async function _n(e,t){if(!Ih(e)||!Lc(t))throw Qe("managed config value",{keyPath:e});let n=rv(e);if(n==="number"&&Q_(t))return{kind:n,value:t};if(n==="boolean"&&typeof t==="boolean")return{kind:n,value:t};if(n==="relative_path"&&typeof t==="string"&&Mh(t))return{kind:n,value:nv(t)};if(n==="enum"&&typeof t==="string"&&X_(t))return{kind:n,value:t};return{kind:"digest",value:await qn("holycodex-managed-config-value",[Dn({keyPath:e,value:t})])}}function XV(e){if(e.kind==="enum"||e.kind==="number"||e.kind==="boolean"||e.kind==="relative_path")return e.value;return}async function Dc(e,t,n,r){if(!Ir(e)||!Yi(t)||!Gi(r.schema)||!Gi(r.installId))throw Qe("managed runtime config",{});let o={...t.managed},i=Eh(e),a=[];for(let[c,l]of Object.entries(n)){if(!is(c)||typeof l!=="string"&&typeof l!=="number"&&typeof l!=="boolean")throw Qe("managed config key",c);let u=c,d=t.managed[u],p=fe(i,u);if(d&&(d.schema!==r.schema||d.installId!==r.installId)){a.push(u);continue}if(d&&d.owner==="holycodex"){let f=p===void 0?void 0:await _n(u,p);if(f===void 0||JSON.stringify(f)!==JSON.stringify(d.lastManagedValue)){a.push(u);continue}}let m=d?.originalValue??(p===void 0?{kind:"absent"}:await _n(u,p));if(!ZV(u,l))throw Qe("managed config value",{keyPath:u});i=so(i,u,l),o[u]={owner:"holycodex",schema:r.schema,installId:r.installId,keyPath:u,originalValue:m,lastManagedValue:await _n(u,l)}}let s={owner:"holycodex",schema:r.schema,installId:r.installId,managed:o};if(!Yi(s))throw Qe("managed runtime config state",{});return{document:i,state:s,driftedKeys:a}}async function Ar(e,t,n){if(!Ir(e)||!Yi(t))throw Qe("managed runtime config",{});let r=Eh(e),o={...t.managed},i=[],a=[],s=[];for(let[c,l]of Object.entries(t.managed)){if(!Ih(c))throw Qe("managed config key",c);let u=c;if(l.owner!=="holycodex"||l.schema!==n.schema||l.installId!==n.installId){if(l.schema!==n.schema||l.installId!==n.installId)s.push(u);continue}let d=fe(r,u);if(!(d!==void 0&&JSON.stringify(await _n(u,d))===JSON.stringify(l.lastManagedValue))){a.push(u);continue}if(l.originalValue.kind==="absent")r=tr(r,u),i.push(u),delete o[u];else{let m=XV(l.originalValue);if(m===void 0){s.push(u),a.push(u);continue}r=so(r,u,m),i.push(u),delete o[u]}}return{document:r,state:{...t,managed:o},restoredKeys:i,preservedKeys:a,unresolvedKeys:s}}async function ss(e,t,n){if(!is(n)||!Yi(t))throw Qe("managed config key",n);let r=t.managed[n],o=fe(e,n),i=o===void 0?void 0:await _n(n,o);if(!r)return i===void 0?{keyPath:n,status:"unmanaged"}:{keyPath:n,status:"unmanaged",current:i};return{keyPath:n,status:i!==void 0&&JSON.stringify(i)===JSON.stringify(r.lastManagedValue)?"unchanged":"drifted",expected:r.lastManagedValue,...i===void 0?{}:{current:i}}}var Y_,zV,os,D0,Zi,JV,q0,U0,$0,Ah,GV;var Nh=w(()=>{ht();ht();Dt();io();Oh();Y_=[...Go,"Reviewer.plan"];zV=ee((e)=>Lc(e)),os=ee((e)=>Ir(e));D0=["model","model_reasoning_effort","service_tier","agents.max_concurrent_threads_per_session","web_search","sandbox_workspace_write.network_access","model_verbosity","developer_instructions","suppress_unstable_features_warning","features.multi_agent","features.default_mode_request_user_input","features.multi_agent_v2","features.agent_message_board","features.context_management.experimental_mode"],Zi=["model_auto_compact_token_limit","features.context_management"],JV=ee((e)=>is(e));q0=ee((e)=>tv(e)),U0=ee((e)=>j0(e)),$0=ee((e)=>H0(e)),Ah=ee((e)=>Yi(e)),GV=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u});function eW(e){return typeof e==="number"&&Number.isFinite(e)&&e>=0}function B0(e,t,n){let r=new Set([...t,n]),o=Object.keys(e);if(Object.keys(e).some((i)=>!r.has(i)))return!1;return o.length>0&&o.every((i)=>eW(e[i]))}function z0(e){if(!de(e)||!Xe(e))return!1;return B0(e,["inputTokens","cachedInputTokens","outputTokens","reasoningOutputTokens"],"totalTokens")||B0(e,["input_tokens","cached_input_tokens","output_tokens","reasoning_output_tokens"],"total_tokens")}function Fh(e){return de(e)&&Xe(e)&&typeof e.id==="string"&&/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u.test(e.id)}function K0(e){return de(e)&&Xe(e)&&Fh(e.thread)}function rW(e){return de(e)&&Xe(e)&&typeof e.id==="string"}function Xi(e){return de(e)&&Xe(e)&&typeof e.threadId==="string"&&e.threadId.length>0}function J0(e){return de(e)&&Xe(e)&&typeof e.id==="string"&&e.id.length>0&&(e.usage===void 0||z0(e.usage))}function oW(e){return de(e)&&Xe(e)&&typeof e.id==="string"&&typeof e.model==="string"&&(e.supportedReasoningEfforts===void 0||Array.isArray(e.supportedReasoningEfforts)&&e.supportedReasoningEfforts.every((t)=>de(t)&&typeof t.reasoningEffort==="string"))&&(e.serviceTiers===void 0||Array.isArray(e.serviceTiers)&&e.serviceTiers.every((t)=>de(t)&&typeof t.id==="string"))&&(e.defaultServiceTier===void 0||e.defaultServiceTier===null||typeof e.defaultServiceTier==="string")&&(e.multiAgentVersion===void 0||e.multiAgentVersion===null||e.multiAgentVersion==="disabled"||e.multiAgentVersion==="v1"||e.multiAgentVersion==="v2")}function w0(e){if(rd.some((t)=>t===e))return"permissions";if(nd.some((t)=>t===e))return"approval";if(e_.some((t)=>t===e))return"elicitation";if(t_.some((t)=>t===e))return"dynamic_tool";return"other"}var V0,dd,W0,od,QV,i_,id,tW,gh,a_,s_,nW,ad,c_,l_,u_,d_,p_,f_,m_,h_,g_,y_,x_,S_,b_,w_,__,v_,R_,T_,C_,O_,k_,E_,I_,A_,P_,M_,N_,F_,zQ,iW,KQ;var L_=w(()=>{Dt();io();hh();Nh();V0=q.pipe(we(/^[A-Za-z][A-Za-z0-9_./:-]{0,127}$/u)),dd=Se(q.pipe(Tc(1)),wn.pipe(Ze((e)=>Number.isSafeInteger(e)))),W0=T({code:wn.pipe(Ze((e)=>Number.isSafeInteger(e))),message:q,data:R($n)}),od=Se(T({id:dd,result:$n}),T({id:dd,error:W0})),QV=T({id:dd,error:W0}),i_=T({method:V0,params:R($n)}),id=T({id:dd,method:V0,params:R($n),trace:R($n)});tW=ee(z0),gh=T({clientInfo:T({name:Yo,version:Yo,title:Se(Yo,At)}),capabilities:Se(T({experimentalApi:V,requestAttestation:V,mcpServerOpenaiFormElicitation:R(V),optOutNotificationMethods:R(Se(K(q),At)),extensions:R(Vi)}),At)}),a_=ee((e)=>de(e)&&Xe(e)&&typeof e.userAgent==="string"&&typeof e.codexHome==="string"&&typeof e.platformFamily==="string"&&typeof e.platformOs==="string"),s_=T({method:E("initialized")});nW=ee(Fh);ad=ee((e)=>K0(e)||rW(e)),c_=ad,l_=ad,u_=ee(Xi),d_=ee((e)=>de(e)&&Xe(e)&&(e.status==="notLoaded"||e.status==="notSubscribed"||e.status==="unsubscribed")),p_=ee((e)=>K0(e)),f_=ee((e)=>{if(!de(e)||!Xe(e))return!1;let t=Array.isArray(e.data)&&e.data.every((r)=>Fh(r)),n=Array.isArray(e.threads)&&e.threads.every((r)=>Fh(r));return t&&e.threads===void 0||n&&e.data===void 0}),m_=ee((e)=>de(e)&&Xe(e));h_=ee(Xi),g_=ee(Xi),y_=ee(Xi),x_=ee((e)=>de(e)&&Xe(e));S_=ee((e)=>Xi(e)&&(Array.isArray(e.input)&&e.input.every((t)=>Xe(t))||typeof e.prompt==="string"&&e.prompt.length>0)),b_=ee((e)=>Xi(e)&&typeof e.expectedTurnId==="string"&&Array.isArray(e.input)&&e.input.every((t)=>Xe(t))),w_=ee((e)=>de(e)&&Xe(e)&&(e.turn!==void 0&&J0(e.turn)||typeof e.turnId==="string"&&e.turnId.length>0||typeof e.id==="string"&&e.id.length>0)),__=ee((e)=>de(e)&&Xe(e)&&typeof e.turnId==="string"&&e.turnId.length>0),v_=ee((e)=>Xi(e)&&typeof e.turnId==="string"&&e.turnId.length>0),R_=ee((e)=>de(e)&&Xe(e)),T_=ee((e)=>Xi(e)&&(e.turn!==void 0&&J0(e.turn)||typeof e.turnId==="string"&&e.turnId.length>0)),C_=ee((e)=>de(e)&&Xe(e));O_=ee((e)=>de(e)&&Xe(e)&&Array.isArray(e.data)&&e.data.every((t)=>oW(t))),k_=Vi,E_=Vi,I_=T({includeLayers:R(V),cwd:R(Se(q,At))}),A_=T({config:os,origins:Vi,layers:Se(K(Vi),At)}),P_=Vi,M_=Vi,N_=ee((e)=>de(e)&&Xe(e)&&(typeof e.id==="string"||typeof e.id==="number"&&Number.isSafeInteger(e.id))&&typeof e.method==="string"&&de(e.params)&&(e.category==="approval"||e.category==="dynamic_tool"||e.category==="elicitation"||e.category==="other"||e.category==="permissions")),F_=$n,zQ=ee((e)=>de(e)&&Xe(e)&&typeof e.kind==="string"&&typeof e.method==="string");iW=Se(E("stable","experimental","disabled"),V),KQ=Zm({key:q,value:iW})});import{lstat as YQ,mkdir as ZQ,readFile as aW,readdir as XQ,realpath as sW,stat as cW}from"fs/promises";import{delimiter as lW,isAbsolute as eee,join as tee,relative as nee,resolve as G0}from"path";async function dW(e){let t=[];if(e.executablePath!==void 0)t.push(G0(e.cwd??process.cwd(),e.executablePath));else{let n=e.pathValue??e.environment?.PATH??process.env.PATH??"",r=process.platform==="win32"?["codex.exe","codex.cmd","codex"]:["codex"];for(let o of n.split(lW).filter((i)=>i.length>0))for(let i of r)t.push(G0(o,i))}for(let n of t)try{let r=await cW(n);if(!r.isFile())continue;if(process.platform!=="win32"&&(r.mode&73)===0)continue;return await sW(n)}catch{if(e.executablePath!==void 0)throw new ie("discovery_failed","The explicit Codex executable was not found.",{path:n})}throw new ie("discovery_failed","No Codex executable was found on the allowlisted PATH.")}async function pW(e,t){let n=Bun.spawn([e,"--version"],{env:t,stdin:"ignore",stdout:"pipe",stderr:"pipe"});if(!(n.stdout instanceof ReadableStream)||!(n.stderr instanceof ReadableStream))throw new ie("discovery_failed","The Codex version command did not expose output pipes.");try{let[r,o,i]=await mW(Promise.all([xh(n.stdout,16384),xh(n.stderr,16384),n.exited]),()=>n.kill(),"The Codex version command timed out."),a=Un(Sh(r,"Codex version output"));if(i!==0||a.length===0){let s=zi(Sh(o,"Codex version diagnostics"));throw new ie("discovery_failed","The Codex executable did not provide a version.",{exitCode:i,diagnostics:s})}return a}catch(r){try{n.kill()}catch{}if(r instanceof ie)throw r;throw new ie("discovery_failed","The Codex version command failed.",{},{cause:r})}}async function fW(e){let t=await aW(e),n=await crypto.subtle.digest("SHA-256",t),r=[...new Uint8Array(n)].map((i)=>i.toString(16).padStart(2,"0")).join(""),o=nh(r);if(!o.ok)throw new ie("discovery_failed","The Codex executable digest was invalid.");return o.value}async function ov(e={}){let t=await dW(e),n=Wi(e.environment),r=e.versionRunner?Un(await e.versionRunner(t,n)):await pW(t,n);if(r.length===0)throw new ie("discovery_failed","The Codex version output was empty.");return{path:t,version:r,sha256:await fW(t)}}async function mW(e,t,n){let r;try{return await Promise.race([e,new Promise((o,i)=>{r=setTimeout(()=>{try{t()}catch{}i(new ie("timeout",n))},uW)})])}finally{if(r!==void 0)clearTimeout(r)}}var uW=30000,aee;var Y0=w(()=>{ht();Dt();io();wh();aee=T({exitCode:wn.pipe(Ze((e)=>Number.isSafeInteger(e))),stdout:q.pipe(yw(1048576)),stderr:q.pipe(yw(1048576))})});var hW="packages/codex/generated",gW,yW,iv,uee,dee;var Z0=w(()=>{ht();Dt();io();gW=/^codex-cli \d+\.\d+\.\d+$/u,yW=/^codex-app-server-\d+\.\d+\.\d+$/u,iv=q.pipe(we(/^[a-f0-9]{64}$/u)),uee=T({schema_version:E("holycodex-generated-v2"),artifact_root:E(hW),codex_cli_version:q.pipe(we(gW)),codex_cli_digest:iv,protocol_epoch:q.pipe(we(yW)),generator:T({command:dN(E("app-server"),E("generate-ts")),supported_surface:E("codex app-server generators")}),typescript_root:E("typescript"),files:T({count:wn.pipe(Xm(),Sw()),digest:iv})}),dee=T({path:q.pipe(Tc(1)),size:wn.pipe(Xm(),Sw()),sha256:iv})});var xW;var X0=w(()=>{Dt();Nh();xW=T({owner:E("holycodex"),schema:q.pipe(we(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u)),installId:q.pipe(we(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u))})});var cs=w(()=>{io();io();hh();L_();o_();wh();Y0();Z0();X0();Nh();Oh();Oh()});function sn(e){if(!qc(e))throw Error("The value is not JSON serializable.");return Ln(e),e}function qc(e,t=new Set){if(e===null||typeof e==="string"||typeof e==="boolean")return!0;if(typeof e==="number")return Number.isFinite(e);if(typeof e!=="object"||t.has(e))return!1;t.add(e);try{if(Array.isArray(e))return e.every((n)=>qc(n,t));return Object.getPrototypeOf(e)===Object.prototype&&Object.values(e).every((n)=>qc(n,t))}finally{t.delete(e)}}var hd=w(()=>{ht()});function Ie(e,t){let n=Xn(e,t);return Ct(n)?n.right:void 0}function cF(e){return Ie(gd,e)!==void 0}var gd,nte,kW,EW,yd,IW,ea,AW,PW,MW,tF,xd,qh,nF,Sd,rF,nn,lv,NW,FW,LW,DW,qW,UW,$W,jW,HW,Dh,BW,eF,VW,Uh,Uc,WW,uv,zW,dv,KW,oF,pv,fv,ta,iF,JW,aF,GW,sF;var ls=w(()=>{cs();ht();hn();Dt();hd();gd=ee((e)=>typeof e==="object"&&e!==null&&!Array.isArray(e)&&qc(e)),nte=ee(qc),kW=kc,EW=q.pipe(we(/^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/u)),yd=q.pipe(we(/^[0-9a-f]{64}$/u)),IW=q.pipe(we(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u)),ea=q.pipe(we(/^[A-Za-z0-9][A-Za-z0-9._:@/-]{0,255}$/u)),AW=q.pipe(Ze((e)=>!Number.isNaN(Date.parse(e)))),PW=T({path:q.pipe(we(/^[A-Za-z0-9][A-Za-z0-9._/-]{0,255}$/u)),digest:yd}),MW=T({browser_use:V,computer_use:V,sites:V,coding:E(!0)}),tF=T({browser_use:R(V),computer_use:R(V),sites:R(V)}),xd=T({profile:R(ro),tier:R(Ko),optional:R(tF),officialPlugins:R(K(ea))}),qh=xd,nF=E("keep","remove","replace","cancel"),Sd=T({schema_version:E(1),profile:ro,tier:Ko,capabilities:K(Rw),additional_plugins:K(ea)}),rF=T({schema_version:E(1),profile:ro,tier:Ko,capabilities:K(Ku),additional_plugins:K(ea)}),nn=T({selected:V,status:E("disabled","pending","healthy","missing","provider_disabled","uncertain","unavailable"),plugin_ids:K(ea),reason:R(q)}),lv=T({browser_use:nn,computer_use:nn,frontend:nn,security:nn,sites:nn}),NW=T({browser_use:R(V),computer_use:V,frontend:V,security:V,sites:R(V),coding:E(!0),work:V}),FW=T({browser_use:R(V),computer_use:R(V),frontend:R(V),security:R(V),sites:R(V),work:R(V)}),LW=T({browser_use:R(nn),computer_use:nn,frontend:nn,security:nn,sites:R(nn),work:nn}),DW=T({computer_use:V,frontend:V,security:V,coding:E(!0)}),qW=T({computer_use:R(V),frontend:R(V),security:R(V)}),UW=T({computer_use:nn,frontend:nn,security:nn}),$W=Se(T({status:E("not_applicable")}),T({status:E("missing")}),T({status:E("healthy"),path:q,installed:V})),jW=T({manager:E("bun","npm","pnpm"),launcher:E("bunx","npx","pnpm dlx"),version:EW,executable:q,ownership:E("user","holycodex"),identity:R(yd)}),HW=T({git_bash:R($W),context7:R(jW)}),Dh=T({presence:E("absent","present"),digest:yd,safe_value:R(Se(T({kind:E("boolean"),value:V}),T({kind:E("marketplace"),source_type:E("git"),source:E("https://github.com/davidbasilefilho/holycodex.git")})))}),BW=T({plugin_id:E("holycodex@holycodex"),before:T({preference:Dh,marketplace:Dh}),after:T({preference:Dh,marketplace:Dh})}),eF=T({presence:E("absent","present"),digest:yd,safe_value:R(T({kind:E("boolean"),value:V}))}),VW=T({plugin_id:ea,before:eF,after:eF}),Uh={owner:E("holycodex"),schema_epoch:E(On),install_id:IW,version:kW,digest:yd,profile:ro,tier:Ko,optional_selections:MW,explicit_optional_selections:tF,official_plugins:R(K(ea)),capability_state:R(lv),managed_artifacts:K(PW),installed_at:AW,status:R(E("active")),step:R(E("active")),managed_config:R(Ah),plugin_snapshot:R(K(T({plugin_id:ea,status:E("installed","available","missing","disabled","uncertain","unknown")}))),plugin_config:R(BW),provider_config:R(K(VW)),owned_plugins:R(K(ea)),tooling:R(HW)},Uc=T(Uh),WW=(({profile:e,...t})=>t)(Uh),uv={...Uh,optional_selections:NW,explicit_optional_selections:FW,capability_state:R(LW)},zW=(({profile:e,...t})=>t)(uv),dv={...Uh,optional_selections:DW,explicit_optional_selections:qW,capability_state:R(UW)},KW=(({profile:e,...t})=>t)(dv),oF=Se(T({...uv,profile:kr}),T({...zW,plan:kr}),T({...WW,plan:kr}),T({...dv,profile:kr}),T({...KW,plan:kr})),pv=E("preparing","conflicted"),fv=E("validated","plugins_snapshotted","roles_prepared","plugins_installed","config_published","verified","conflicted"),ta=T({...Uc.fields,status:pv,step:fv}),iF={...uv,status:pv,step:fv},JW=(({profile:e,...t})=>t)(iF),aF={...dv,status:pv,step:fv},GW=(({profile:e,...t})=>t)(aF),sF=Se(ta,T({...iF,profile:kr}),T({...JW,plan:kr}),T({...aF,profile:kr}),T({...GW,plan:kr}))});import{lstat as YW,mkdir as ZW}from"fs/promises";import{homedir as XW}from"os";import{dirname as QW,join as na,posix as lF,resolve as ez,sep as uF,win32 as dF}from"path";function Pr(e={},t=process.env){let n=XW(),r=e.paths?.codexHome??t.CODEX_HOME??na(n,".codex"),o=hv(r,"CODEX_HOME"),i=na(o,tz);return{codexHome:o,stateRoot:i,activeRecord:na(i,nz),preparingRecord:na(i,rz),conflictedRecord:na(i,oz),installOptions:na(i,iz),roleRoot:na(i,"agents"),configFile:na(o,"config.toml")}}function hv(e,t,n=process.platform==="win32"?"win32":"posix"){if(typeof e!=="string"||sz(e))throw new nr("invalid_path",`${t} contains invalid characters.`);let r=n==="win32"?dF:lF,o=mv(e,n);if(typeof o!=="string"||o.length===0||!r.isAbsolute(o))throw new nr("invalid_path",`${t} must be an absolute path.`);let i=r.normalize(o);if(i.split(n==="win32"?"\\":uF).filter((s)=>s.length>0).length===0||i===r.dirname(i))throw new nr("broad_path",`${t} is too broad.`);if(o.split(/[\\/]/u).some((s)=>s===".."))throw new nr("invalid_path",`${t} cannot contain traversal.`);return r.resolve(i)}function sz(e){for(let t of e){let n=t.codePointAt(0)??0;if(n<=31||n===127)return!0}return!1}async function $c(e){hv(e,"owned path"),await co(e),await ZW(e,{recursive:!0}),await co(e)}async function co(e){let n=ez(e);while(!0){try{if((await YW(n)).isSymbolicLink())throw new nr("path_symlink","A managed path cannot contain a symlink.")}catch(o){if(o instanceof nr)throw o;if(!We(o,"ENOENT"))throw o}let r=QW(n);if(r===n)break;n=r}}async function us(e){await co(e)}function rr(e,t,n=process.platform==="win32"?"win32":"posix"){let r=n==="win32"?dF:lF,o=r.resolve(mv(e,n)),i=r.resolve(mv(t,n)),a=r.relative(o,i);return a.length>0&&!a.startsWith(`..${n==="win32"?"\\":uF}`)&&a!==".."&&!r.isAbsolute(a)}function mv(e,t){if(t==="win32"&&/^\/[A-Za-z](?:\/|$)/u.test(e))return`${e[1]?.toUpperCase()??""}:${e.slice(2).replaceAll("/","\\")}`;return e}function We(e,t){return typeof e==="object"&&e!==null&&"code"in e&&e.code===t}var tz="holycodex",nz="active.toml",rz="preparing.toml",oz="conflicted.toml",iz="install.toml",az,nr;var ds=w(()=>{ht();az=On;nr=class nr extends Error{code;constructor(e,t){super(t);this.name="PathBoundaryError",this.code=e}}});function bd(e){let t={},n=[];for(let r of e.split(/\r?\n/u)){let o=lz(r).trim();if(o.length===0)continue;if(o.startsWith("[["))throw Error("Array-of-tables are not supported by the validated fallback.");if(o.startsWith("[")&&o.endsWith("]")){n=gv(o.slice(1,-1).trim()),cz(t,n);continue}let i=mF(o);if(i<1)throw Error("TOML assignment is invalid.");let a=gv(o.slice(0,i).trim()),s=$h(o.slice(i+1).trim());fF(t,[...n,...a],s)}return t}function wd(e){let t=[];return pF(e,[],t),t.join(`
|
|
36
36
|
`)}function pF(e,t,n){let r=[],o=[];for(let[i,a]of Object.entries(e))if(bv(a))o.push([i,a]);else r.push([i,a]);if(t.length>0){if(n.length>0)n.push("");n.push(`[${t.map(xv).join(".")}]`)}for(let[i,a]of r)n.push(`${xv(i)} = ${Sv(a)}`);for(let[i,a]of o)pF(a,[...t,i],n)}function $h(e){if(e.length===0)throw Error("TOML value is missing.");if(e.startsWith('"')){let t=JSON.parse(e);if(typeof t!=="string")throw Error("TOML string is invalid.");return t}if(e.startsWith("'")){if(!e.endsWith("'")||e.length<2)throw Error("TOML string is invalid.");return e.slice(1,-1)}if(e==="true")return!0;if(e==="false")return!1;if(e.startsWith("[")){if(!e.endsWith("]"))throw Error("TOML array is invalid.");let t=e.slice(1,-1).trim();return t.length===0?[]:yv(t,",").map((n)=>$h(n.trim()))}if(e.startsWith("{")){if(!e.endsWith("}"))throw Error("TOML inline table is invalid.");let t=e.slice(1,-1).trim(),n={};if(t.length===0)return n;for(let r of yv(t,",")){let o=mF(r);if(o<1)throw Error("TOML inline table entry is invalid.");fF(n,gv(r.slice(0,o).trim()),$h(r.slice(o+1).trim()))}return n}if(/^[+-]?(?:0|[1-9]\d*)(?:\.\d+)?$/u.test(e)){let t=Number(e);if(Number.isFinite(t))return t}throw Error("TOML value is unsupported.")}function gv(e){let t=yv(e,".").map((n)=>n.trim());if(t.length===0||t.some((n)=>!/^(?:[A-Za-z0-9_-]+|"(?:[^"\\]|\\.)*"|'[^']*')$/u.test(n)||n==="__proto__"||n==="constructor"||n==="prototype"))throw Error("TOML key is invalid.");return t.map((n)=>n.startsWith('"')||n.startsWith("'")?$h(n):n)}function fF(e,t,n){if(t.length===0)throw Error("TOML key is missing.");let r=e;for(let i of t.slice(0,-1)){let a=r[i];if(a===void 0){let s={};r[i]=s,r=s}else if(bv(a))r=a;else throw Error("TOML key conflicts with a scalar.")}let o=t.at(-1);if(Object.prototype.hasOwnProperty.call(r,o))throw Error("TOML key is duplicated.");r[o]=n}function cz(e,t){let n=e;for(let r of t){let o=n[r];if(o===void 0){let i={};n[r]=i,n=i}else if(bv(o))n=o;else throw Error("TOML table conflicts with a scalar.")}}function yv(e,t){let n=[],r=0,o=0,i,a=!1;for(let s=0;s<e.length;s+=1){let c=e[s];if(i!==void 0){if(i==='"'&&a)a=!1;else if(i==='"'&&c==="\\")a=!0;else if(c===i)i=void 0;continue}if(c==='"'||c==="'")i=c;else if(c==="["||c==="{")o+=1;else if(c==="]"||c==="}")o-=1;else if(c===t&&o===0)n.push(e.slice(r,s)),r=s+1}if(i!==void 0||o!==0)throw Error("TOML value is unbalanced.");return n.push(e.slice(r)),n}function mF(e){let t,n=!1,r=0;for(let o=0;o<e.length;o+=1){let i=e[o];if(t!==void 0){if(t==='"'&&n)n=!1;else if(t==='"'&&i==="\\")n=!0;else if(i===t)t=void 0}else if(i==='"'||i==="'")t=i;else if(i==="["||i==="{")r+=1;else if(i==="]"||i==="}")r-=1;else if(i==="="&&r===0)return o}return-1}function lz(e){let t,n=!1;for(let r=0;r<e.length;r+=1){let o=e[r];if(t!==void 0){if(t==='"'&&n)n=!1;else if(t==='"'&&o==="\\")n=!0;else if(o===t)t=void 0}else if(o==='"'||o==="'")t=o;else if(o==="#")return e.slice(0,r)}return e}function bv(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function xv(e){return/^[A-Za-z0-9_-]+$/u.test(e)?e:JSON.stringify(e)}function Sv(e){if(typeof e==="string")return JSON.stringify(e);if(typeof e==="boolean"||typeof e==="number"){if(typeof e==="number"&&!Number.isFinite(e))throw Error("TOML number is invalid.");return String(e)}if(Array.isArray(e))return`[${e.map(Sv).join(", ")}]`;if(e===null)throw Error("TOML null is not serializable.");return`{ ${Object.entries(e).map(([t,n])=>`${xv(t)} = ${Sv(n)}`).join(", ")} }`}import{lstat as hF,open as uz,readFile as gF,rename as dz,unlink as yF,writeFile as pz}from"fs/promises";import{dirname as fz}from"path";async function xF(e){let t;try{t=await uz(e,"r"),await t.sync()}catch(n){if(!bF(n))throw n}finally{await t?.close().catch(()=>{return})}}async function hz(e){await xF(e).catch((t)=>{if(!bF(t))throw t})}async function SF(e,t){await vt(e,`${Ln(t)}
|
|
37
37
|
`)}async function jc(e,t){let n=[];function r(i,a){if(i===null)return n.push(a),"";if(Array.isArray(i))return i.map((s,c)=>r(s,[...a,String(c)]));if(typeof i==="object")return Object.fromEntries(Object.entries(i).map(([s,c])=>[s,r(c,[...a,s])]));return i}let o={format_version:1,null_paths:n,record:r(t,[])};await vt(e,wd(o))}async function wv(e,t){let n=await ye(e);if(n===void 0){let r=e.replace(/\.toml$/u,".json");return await xz(r,t)}return gz(n,t)}async function _d(e,t){if(await ye(e)!==void 0)return;let n=e.replace(/\.toml$/u,".json"),r=await ye(n);if(r===void 0)return;if(await jc(e,t),await ye(n)!==r)throw new lo("state_corrupt","Legacy state changed during migration.");await yF(n)}function gz(e,t){let n;try{if(e.trimStart().startsWith("{"))n=JSON.parse(e);else{let o=bd(e);if(o.format_version!==1||!Array.isArray(o.null_paths))throw Error("Invalid state format");n=o.record;for(let i of o.null_paths){if(!Array.isArray(i)||i.length===0||i.some((c)=>typeof c!=="string"||["__proto__","constructor","prototype"].includes(c)))throw Error("Invalid null path");let a=n;for(let c of i.slice(0,-1)){if(typeof a!=="object"||a===null||!Object.hasOwn(a,c))throw Error("Invalid null path");a=a[c]}let s=i.at(-1);if(typeof a!=="object"||a===null||!Object.hasOwn(a,s)||a[s]!=="")throw Error("Invalid null placeholder");a[s]=null}}}catch(o){throw new lo("state_corrupt","A persisted state file is not valid TOML.",o)}let r=Ie(t,n);if(r===void 0)throw new lo("state_corrupt","A persisted file failed schema validation.");return r}async function vt(e,t){let n=fz(e);await $c(n),await co(e);let r=`${e}.tmp-${process.pid}-${crypto.randomUUID()}`;try{await pz(r,t,{encoding:"utf8",mode:384}),await xF(r),await dz(r,e),await hz(n)}catch(o){throw await yF(r).catch(()=>{return}),o}}async function yz(e,t){let n=await hF(e);if(!n.isFile()||n.isSymbolicLink())throw new lo("state_corrupt","A persisted file is not a regular file.");let r;try{r=JSON.parse(await gF(e,"utf8"))}catch(i){throw new lo("state_corrupt","A persisted file is not valid JSON.",i)}let o=Ie(t,r);if(o===void 0)throw new lo("state_corrupt","A persisted file failed schema validation.");return o}async function ye(e){try{let t=await hF(e);if(!t.isFile()||t.isSymbolicLink())throw new lo("state_corrupt","A persisted file is not a regular file.");return await gF(e,"utf8")}catch(t){if(We(t,"ENOENT"))return;throw t}}async function xz(e,t){try{return await yz(e,t)}catch(n){if(We(n,"ENOENT"))return;throw n}}function bF(e){if(typeof e==="object"&&e!==null&&"code"in e&&typeof e.code==="string")return mz.has(e.code)||process.platform==="win32"&&e.code==="EPERM";return!1}var mz,lo;var Hc=w(()=>{ht();ds();ls();mz=new Set(["EBADF","EINVAL","ENOSYS","ENOTSUP","EISDIR"]);lo=class lo extends Error{code;causeValue;constructor(e,t,n){super(t);this.name="StorageError",this.code=e,this.causeValue=n}}});import{readFile as Sz}from"fs/promises";import{dirname as bz,resolve as wz}from"path";import{fileURLToPath as _z}from"url";async function wF(e=ps){let t=JSON.parse(await Sz(e,"utf8")),n=Ie(vz,t);if(n===void 0)throw new Qo("manifest_invalid","The public package manifest is invalid.");return n}async function Bc(e=ps){let t=(await wF(e)).version,n=Ie(kc,t);if(n===void 0)throw new Qo("manifest_invalid","The public package manifest version is invalid.");return n}async function _F(e=ps){let t=await Bc(e),n=Ie(Oc,t);if(n===void 0)throw new Qo("manifest_invalid","The public package manifest must use a canonical stable release version.");return n}async function Rz(e=ps){let n=(await Bc(e)).split("-",1)[0],r=Ie(_w,n);if(r===void 0)throw new Qo("manifest_invalid","The public package manifest must use a canonical release base version.");return r}async function vd(e=ps){return await Bc(e)}async function _v(e,t,n=ps){let r=await wF(n),o=await _F(n),i=Tz(e,o);if(!t)await SF(n,{...r,version:i});return{previous:o,next:i}}function Tz(e,t){if(e!=="patch"&&e!=="minor"){if(Ie(Oc,e)===void 0)throw new Qo("version_invalid","The version target is invalid.");return e}try{return vw(e,t)}catch(n){throw new Qo("version_invalid",n instanceof Error?n.message:"The current version is invalid.")}}var vz,ps,Qo;var Rd=w(()=>{ht();Dt();ls();Hc();vz=ee((e)=>cF(e)&&e.name==="holycodex"&&Ie(kc,e.version)!==void 0),ps=wz(bz(_z(import.meta.url)),"../package.json");Qo=class Qo extends Error{code;constructor(e,t){super(t);this.name="ManifestError",this.code=e}}});import{createHash as Cz}from"crypto";import{lstat as vv,readFile as Rv,rm as jh,rmdir as Oz}from"fs/promises";import{dirname as vF,join as Mt,relative as RF}from"path";async function Bh(e,t,n=[],r="standard",o={}){let i=fs(t,r,o),a=Mt(e,"holycodex","agents",i),s=ei(t,r).map((u)=>({path:Mt(a,`${u.name}.toml`),contents:Vc(u,o)})),c=new Map(n.map((u)=>[Mt(e,u.path),u])),l=[];for(let u of s){let d=await ra(u.path),p=c.get(u.path),m=d===void 0?void 0:await PF(u,d,p);if(m!==void 0)l.push(m)}return l}async function CF(e,t){let n=Mt(e,"agents"),r=Mt(e,"holycodex","agents"),o=[];for(let i of t){let a=Mt(e,i.path);if(!rr(e,a)||!rr(n,a)&&!rr(r,a)&&a!==Mt(e,"config.toml"))continue;let s=await ra(a);if(s!==void 0&&await jn(s)!==i.digest)o.push({...AF(a,"remove",{present:!0,digest:await jn(s)},{present:!1},"The managed native artifact changed outside HolyCodex and would be removed."),action:"remove"})}return o}async function OF(e,t){let n=Mt(e,"agents"),r=Mt(e,"holycodex","agents"),o=[];for(let[i,a]of t){if(!rr(e,i)||!rr(n,i)&&!rr(r,i)){o.push(i);continue}let s=await ra(i);if(s!==void 0&&await jn(s)!==a)o.push(i)}return o}function ei(e,t="standard"){let n=oo(e);if(!n.ok)return[];return n.value.routes.map((r)=>{let o={role:r.role,task:r.task};return{name:Nw(o),description:Lw(o),taskInstruction:Fw(o),permissions:Dw(o),model:r.model,effort:r.effort,serviceTier:t==="standard"?"default":"fast"}})}function fs(e,t="standard",n={}){let r=ei(e,t).map((o)=>`${o.name}\x00${Vc(o,n)}`).join("\x00");return Cz("sha256").update(r).digest("hex").slice(0,20)}function Td(e,t){if(!/^[a-f0-9]{20}$/u.test(t))throw Error("Invalid native-agent generation identifier.");return`holycodex/agents/${t}/${e}.toml`}function Tv(e,t="standard"){let n=oo(e);if(!n.ok)throw Error("Unknown profile.");return{name:"root",description:"Root-directed HolyCodex control agent.",model:n.value.root.model,effort:n.value.root.effort,serviceTier:t==="fast-all"?"fast":"default"}}function Cv(e=!1){let t=typeof e==="boolean"?{computerUse:e,frontend:!0,security:!0}:e;if(!W.requiresDelegation||!W.assignmentStartAndDispatchPrecedeDelegableExecution||!W.trivialWorkRequiresDelegation||!W.preparatoryAndExploratoryWorkRequiresDelegation||W.genericDirectWorkFallback||W.directExecutionExceptions!==W.rootOwnedAuthority||!W.codeReviewRequiredForImplementation||!W.codeReviewRequiredBeforeVcs||!W.externalVerificationMustBeTerminal||!W.concreteSpecialistDispatchRequired||!W.roleFamiliesAreLabelsOnly||!W.missingConcreteRouteIsBlocker||!W.normalSpawnRequiresExplicitForkTurns||W.normalSpawnForkTurns!=="none"||!W.normalSpawnUsesConcreteRegisteredAgentType||!W.assignmentContextIsTaskSpecificOnly||!W.configuredRouteModelAndEffortPreserved||W.normalProgressMessages||W.normalHeartbeatMessages||W.normalIntermediateEvidence||!W.userUpdatesUsefulOrImportantOnly||!W.routinePerToolOrSubagentNarrationForbidden||!W.routineStatusOnlyChatterForbidden||!W.fixedCadenceUserUpdatesForbidden||!W.materialUserUpdateKinds.includes("significant_findings_or_decisions")||!W.materialUserUpdateKinds.includes("consequential_blockers_or_input_needs")||!W.materialUserUpdateKinds.includes("release_milestones")||!W.outOfBoundaryRequiresNewAssignment||!W.longestPracticalEventWait||!W.busyPollingForbidden||!W.statusOnlyCoordinationLoopsForbidden||!W.batchIndependentLifecycleActions||!W.releaseLeavesAfterAcceptedOutcome||W.routineWaitTool!=="collaboration.wait_agent"||!Number.isSafeInteger(W.routineWaitMaximumTimeoutMs)||W.routineWaitMaximumTimeoutMs<=0||!W.routineWaitUsesMaximumRuntimeTimeout||!W.earlySpecialistCompletionWakesWait||!W.collectiveMailboxIncludesRelevantAgents||!W.idleTimeoutRepeatsMaximumWait||!W.shortRoutineWaitsForbidden||!W.evidenceFirstConciseStructuredReports||W.specialistReportFields.length===0||W.rootLargeReadsOnlyFor.length===0||!W.stableFactsReused||!W.duplicatePolicyForbidden||!W.stableBoundedComponentScopesAreCanonical||!W.lifecycleWorkerOwnsDeterministicApi||W.registeredSpecialistAgentTypes!==Go||W.forbiddenGenericAgentTypes!==lh)throw Error("The Root orchestration policy is incomplete.");let n=[`You are the HolyCodex Root/session orchestrator. Never perform delegable work yourself unless the user explicitly requests direct execution or forbids delegation. Root owns ${W.rootOwnedAuthority.map((r)=>Ez[r]).join("; ")}, within authorization and capability boundaries.`,`Delegate ${W.delegableActions.filter((r)=>(r!=="browser_use"||t.browserUse)&&(r!=="computer_use"||t.computerUse)).map((r)=>Iz[r]).join("; ")} through bounded Assignments. Bundle related trivial and preparatory steps into a coherent Assignment rather than spawning per action.`,W.routeConfigurationBeforeDispatch,W.assignmentInvocationLifecycle,`For normal specialist spawns, set fork_turns: "${W.normalSpawnForkTurns}". Give each specialist a self-contained Assignment with objective, bounded scope, constraints, dependencies, acceptance criteria, and evidence needed for acceptance.`,`Dispatch each Assignment to its exact concrete registered Role.task agent_type. Registered targets: ${W.registeredSpecialistAgentTypes.join(", ")}. Explorer, Librarian, Worker, and Reviewer are labels only; generic built-in agent_type values ${W.forbiddenGenericAgentTypes.join(", ")} are forbidden.`,W.semanticStateBoundary,"User instructions take precedence over skill guidelines. Treat later user steering as current when it changes scope, ownership, or delegation; do not carry forward earlier conflicting constraints. Infer intent from the request and session; carry authorized work through its requested terminal state. Routine omissions get safe defaults. For a blocking material user decision, Root alone uses grill-me, which must ask through request_user_input; ask only what remains unresolved, never turn clarification into planning. Specialists return material input needs to Root as needs_root_input and never ask the user. Dispatch immediately when no decision blocks the next step, and continue independent work while an answer is pending. Check existing authorization before asking again; prepare the concrete reviewable result before requesting approval for a consequential effect. Credential entry remains user-owned.","Dispatch independent non-conflicting Assignments concurrently as soon as their inputs are ready, including across workflow phases. Give each overlapping write or shared-mutable seam one specialist owner and send follow-ups to that owner instead of spawning competing writers; start dependent review or validation once its source is stable. Reuse accepted findings instead of repeating discovery. Batch independent tool reads and lifecycle work where supported; keep revisions and dependent writes ordered. Resolve material contradictions before acceptance.","For visual tasks, Root uses visual-loop: Worker.visual implementation, Reviewer.visual independent review, then Root independent visual pass; use dev-server when a shared background server is needed. Honor active-surface tool precedence. Report a capability blocker without inventing a provider or widening authority.",kF(t),Fn.designJudgment,"Use writing-instructions for model-facing contracts. Keep each meaning with one authoritative owner and add only the missing semantic delta for the receiver.","Give the user useful updates for significant findings, decisions, blockers, input needs, and release milestones; avoid per-tool, status-only, heartbeat, or fixed-cadence messages.",Pz,`${Zu.rule} ${Az}`,"After integration, Root owns approved VCS writes. For PR or release gates use babysit-ci and dispatch Worker.operations for exact-ref terminal evidence. Pending gates are not complete."];if(t.frontend??!0)n.push(Mz());if(t.security??!0)n.push("For security-sensitive changes, use the relevant security review skills before VCS. Validate supported findings; repair introduced or worsened vulnerabilities before VCS unless explicitly risk-accepted. Keep security review current after relevant repairs.");return n.join(`
|
|
38
|
-
`)}function kF(e,t="Root"){let n=e.browserUse?`Inspect and interact with rendered visual work using Browser Use / the in-app browser (IAB). ${e.computerUse?"Use Computer Use when Browser Use cannot perform the required interaction. ":""}Use other available rendered evidence for remaining inspection gaps.`:e.computerUse?"Inspect and interact with rendered visual work using Computer Use, then other available rendered evidence for remaining inspection gaps.":"Inspect rendered visual work using other available rendered evidence such as screenshots or image tools.",r=e.browserUse?`For web-visualize, open and inspect the standalone temporary HTML with Browser Use / IAB.${e.computerUse?" Use Computer Use for HTML interactions Browser Use cannot perform.":""}`:e.computerUse?"For web-visualize, open and inspect the standalone temporary HTML with Computer Use.":"For web-visualize, give the standalone temporary HTML file to the user.";return`For ${t==="Root"?"Root visual judgment":"visual implementation and review"}, ${n} ${r} Honor higher-priority active-surface tool rules.`}function Mz(){if(!Fn.repositoryAndUserRequirementsPrecedePluginDefaults||!Fn.specialistsOwnImplementationAndInteractionProof||Fn.specialistVisualImplementationInstruction.length===0||!Fn.rootOwnsVisualJudgment||!Fn.rootOwnsSharedDevServer||!Fn.rootAcceptsTerminalVisualEvidence||!Fn.sourceChangesInvalidateRenderEvidence||!Fn.specialistReportsIncludeObservableRenderedEvidence||Fn.logicOnlyChangesRequireVisualAcceptance)throw Error("The Frontend workflow policy is incomplete.");return`${EF()} Follow the repository stack, design system, and user requirements. ${Fn.specialistVisualImplementationInstruction} Refresh affected visual evidence after relevant changes. Logic-only changes do not require a visual loop. Check responsive layout, accessibility, and interactions in proportion to the change.`}function EF(){return`Use Build Web Apps for applicable web-app construction and Frontend App Builder for applicable frontend work. For frontend work, ${Wo.frontend.applicability.map(({skillId:t,appliesWhen:n})=>`${n} uses ${t}`).join("; ")}.`}async function Ov(e,t,n=[],r="standard",o,i=[],a={}){let s=fs(t,r,a),c=Mt(e,"holycodex","agents",s),l=[],u=[],d=ei(t,r).map((v)=>({path:Mt(c,`${v.name}.toml`),contents:Vc(v,a)})),p=new Map(n.map((v)=>[Mt(e,v.path),v])),m=new Map,f=new Set,y=new Set,g=new Map;for(let v of d){let C=await ra(v.path);m.set(v.path,C);let M=i.find((O)=>O.path===v.path&&O.action==="replace"&&O.key===void 0);if(M!==void 0){let O=TF(M);if(O===void 0||C===void 0||await jn(C)!==O)throw Error(`The native role conflict changed after review; review the latest file and retry: ${v.path}`);if(g.set(v.path,O),M.decision==="keep")y.add(v.path);else f.add(v.path)}let N=p.get(v.path);if(C!==void 0&&M===void 0){let O=await PF(v,C,N);if(O!==void 0){let k=await o?.(O);if(k==="cancel")throw Error(`Native-agent conflict resolution was cancelled: ${v.path}`);if(k===void 0)y.add(v.path);else{let I=TF(O),S=await ra(v.path);if(I===void 0||S===void 0||await jn(S)!==I)throw Error(`The native role conflict changed after review; review the latest file and retry: ${v.path}`);if(g.set(v.path,I),k==="accept")f.add(v.path);else y.add(v.path)}}}}let x=[];try{for(let N of d){let O=m.get(N.path),k=p.get(N.path),I=g.get(N.path);if(I!==void 0){let S=await ra(N.path);if(S===void 0||await jn(S)!==I)throw Error(`The native role conflict changed after review; review the latest file and retry: ${N.path}`)}if(y.has(N.path)){if(l.push(N.path),k!==void 0)x.push(k);continue}if(O!==void 0&&k!==void 0){if(await jn(O)!==k.digest&&O!==N.contents&&!f.has(N.path)){l.push(N.path),x.push({path:RF(e,N.path).replaceAll("\\","/"),digest:k.digest});continue}}if(O===void 0||O!==N.contents)await vt(N.path,N.contents),u.push({path:N.path,previous:O,installedDigest:await jn(N.contents)});x.push({path:RF(e,N.path).replaceAll("\\","/"),digest:await jn(N.contents)})}let v=Mt(e,"agents","root.toml"),C=await ra(v),M=await IF(v);if(M==="preserved")l.push(v);if(M==="removed"&&C!==void 0)u.push({path:v,previous:C,installedDigest:void 0});for(let N of n){let O=Mt(e,N.path);if(!d.some((k)=>k.path===O))x.push(N)}return{managed_artifacts:x,preserved:l,rollback:u}}catch(v){throw await Vh(u).catch(()=>{return}),v}}async function Vh(e){let t=[],n=[];for(let r of[...e].reverse()){let o=await ra(r.path);if(!(r.installedDigest===void 0?o===void 0:o!==void 0&&await jn(o)===r.installedDigest)){n.push(r.path);continue}if(r.previous===void 0)await jh(r.path,{force:!1}).catch((a)=>{if(!We(a,"ENOENT"))throw a}),t.push(r.path);else await vt(r.path,r.previous)}return{removed:t,preserved:n}}async function Wh(e,t,n=new Map){let r=[],o=[],i=Mt(e,"agents"),a=Mt(e,"holycodex","agents");for(let u of t){let d=Mt(e,u.path);if(!rr(e,d)||!rr(i,d)&&!rr(a,d)&&d!==Mt(e,"config.toml")){o.push(d);continue}try{await co(d);let p=await vv(d);if(p.isSymbolicLink()||!p.isFile()){o.push(d);continue}let m=await Rv(d),f=await jn(m);if(f!==u.digest){let y=n.get(d);if(y!==void 0&&f===y){await jh(d,{force:!1}),r.push(d);continue}o.push(d);continue}await jh(d,{force:!1}),r.push(d)}catch(p){if(!We(p,"ENOENT"))o.push(d)}}let s=Mt(e,"agents","root.toml"),c=await IF(s);if(c==="removed")r.push(s);if(c==="preserved")o.push(s);let l=r.slice();for(let u of l){let d=vF(u);while(d!==a&&rr(a,d)){try{await co(d),await Oz(d),r.push(d)}catch(p){if(!We(p,"ENOENT"))break}d=vF(d)}}return{removed:r,preserved:o}}function Vc(e,t={}){let n=[kz,e.taskInstruction,...e.name==="Worker.visual"||e.name==="Reviewer.visual"?[kF(t,"specialist"),...t.frontend??!0?[EF()]:[]]:[],...e.permissions.sourceMutation?[`Patch quality: ${sh}`]:[],...t.browserUse?["Use Browser Use only for this Assignment
|
|
38
|
+
`)}function kF(e,t="Root"){let n=e.browserUse?`Inspect and interact with rendered visual work using Browser Use / the in-app browser (IAB). ${e.computerUse?"Use Computer Use when Browser Use cannot perform the required interaction. ":""}Use other available rendered evidence for remaining inspection gaps.`:e.computerUse?"Inspect and interact with rendered visual work using Computer Use, then other available rendered evidence for remaining inspection gaps.":"Inspect rendered visual work using other available rendered evidence such as screenshots or image tools.",r=e.browserUse?`For web-visualize, open and inspect the standalone temporary HTML with Browser Use / IAB.${e.computerUse?" Use Computer Use for HTML interactions Browser Use cannot perform.":""}`:e.computerUse?"For web-visualize, open and inspect the standalone temporary HTML with Computer Use.":"For web-visualize, give the standalone temporary HTML file to the user.";return`For ${t==="Root"?"Root visual judgment":"visual implementation and review"}, ${n} ${r} Honor higher-priority active-surface tool rules.`}function Mz(){if(!Fn.repositoryAndUserRequirementsPrecedePluginDefaults||!Fn.specialistsOwnImplementationAndInteractionProof||Fn.specialistVisualImplementationInstruction.length===0||!Fn.rootOwnsVisualJudgment||!Fn.rootOwnsSharedDevServer||!Fn.rootAcceptsTerminalVisualEvidence||!Fn.sourceChangesInvalidateRenderEvidence||!Fn.specialistReportsIncludeObservableRenderedEvidence||Fn.logicOnlyChangesRequireVisualAcceptance)throw Error("The Frontend workflow policy is incomplete.");return`${EF()} Follow the repository stack, design system, and user requirements. ${Fn.specialistVisualImplementationInstruction} Refresh affected visual evidence after relevant changes. Logic-only changes do not require a visual loop. Check responsive layout, accessibility, and interactions in proportion to the change.`}function EF(){return`Use Build Web Apps for applicable web-app construction and Frontend App Builder for applicable frontend work. For frontend work, ${Wo.frontend.applicability.map(({skillId:t,appliesWhen:n})=>`${n} uses ${t}`).join("; ")}.`}async function Ov(e,t,n=[],r="standard",o,i=[],a={}){let s=fs(t,r,a),c=Mt(e,"holycodex","agents",s),l=[],u=[],d=ei(t,r).map((v)=>({path:Mt(c,`${v.name}.toml`),contents:Vc(v,a)})),p=new Map(n.map((v)=>[Mt(e,v.path),v])),m=new Map,f=new Set,y=new Set,g=new Map;for(let v of d){let C=await ra(v.path);m.set(v.path,C);let M=i.find((O)=>O.path===v.path&&O.action==="replace"&&O.key===void 0);if(M!==void 0){let O=TF(M);if(O===void 0||C===void 0||await jn(C)!==O)throw Error(`The native role conflict changed after review; review the latest file and retry: ${v.path}`);if(g.set(v.path,O),M.decision==="keep")y.add(v.path);else f.add(v.path)}let N=p.get(v.path);if(C!==void 0&&M===void 0){let O=await PF(v,C,N);if(O!==void 0){let k=await o?.(O);if(k==="cancel")throw Error(`Native-agent conflict resolution was cancelled: ${v.path}`);if(k===void 0)y.add(v.path);else{let I=TF(O),S=await ra(v.path);if(I===void 0||S===void 0||await jn(S)!==I)throw Error(`The native role conflict changed after review; review the latest file and retry: ${v.path}`);if(g.set(v.path,I),k==="accept")f.add(v.path);else y.add(v.path)}}}}let x=[];try{for(let N of d){let O=m.get(N.path),k=p.get(N.path),I=g.get(N.path);if(I!==void 0){let S=await ra(N.path);if(S===void 0||await jn(S)!==I)throw Error(`The native role conflict changed after review; review the latest file and retry: ${N.path}`)}if(y.has(N.path)){if(l.push(N.path),k!==void 0)x.push(k);continue}if(O!==void 0&&k!==void 0){if(await jn(O)!==k.digest&&O!==N.contents&&!f.has(N.path)){l.push(N.path),x.push({path:RF(e,N.path).replaceAll("\\","/"),digest:k.digest});continue}}if(O===void 0||O!==N.contents)await vt(N.path,N.contents),u.push({path:N.path,previous:O,installedDigest:await jn(N.contents)});x.push({path:RF(e,N.path).replaceAll("\\","/"),digest:await jn(N.contents)})}let v=Mt(e,"agents","root.toml"),C=await ra(v),M=await IF(v);if(M==="preserved")l.push(v);if(M==="removed"&&C!==void 0)u.push({path:v,previous:C,installedDigest:void 0});for(let N of n){let O=Mt(e,N.path);if(!d.some((k)=>k.path===O))x.push(N)}return{managed_artifacts:x,preserved:l,rollback:u}}catch(v){throw await Vh(u).catch(()=>{return}),v}}async function Vh(e){let t=[],n=[];for(let r of[...e].reverse()){let o=await ra(r.path);if(!(r.installedDigest===void 0?o===void 0:o!==void 0&&await jn(o)===r.installedDigest)){n.push(r.path);continue}if(r.previous===void 0)await jh(r.path,{force:!1}).catch((a)=>{if(!We(a,"ENOENT"))throw a}),t.push(r.path);else await vt(r.path,r.previous)}return{removed:t,preserved:n}}async function Wh(e,t,n=new Map){let r=[],o=[],i=Mt(e,"agents"),a=Mt(e,"holycodex","agents");for(let u of t){let d=Mt(e,u.path);if(!rr(e,d)||!rr(i,d)&&!rr(a,d)&&d!==Mt(e,"config.toml")){o.push(d);continue}try{await co(d);let p=await vv(d);if(p.isSymbolicLink()||!p.isFile()){o.push(d);continue}let m=await Rv(d),f=await jn(m);if(f!==u.digest){let y=n.get(d);if(y!==void 0&&f===y){await jh(d,{force:!1}),r.push(d);continue}o.push(d);continue}await jh(d,{force:!1}),r.push(d)}catch(p){if(!We(p,"ENOENT"))o.push(d)}}let s=Mt(e,"agents","root.toml"),c=await IF(s);if(c==="removed")r.push(s);if(c==="preserved")o.push(s);let l=r.slice();for(let u of l){let d=vF(u);while(d!==a&&rr(a,d)){try{await co(d),await Oz(d),r.push(d)}catch(p){if(!We(p,"ENOENT"))break}d=vF(d)}}return{removed:r,preserved:o}}function Vc(e,t={}){let n=[kz,e.taskInstruction,...e.name==="Worker.visual"||e.name==="Reviewer.visual"?[kF(t,"specialist"),...t.frontend??!0?[EF()]:[]]:[],...e.permissions.sourceMutation?[`Patch quality: ${sh}`]:[],...t.browserUse?["Use Browser Use only for this Assignment, following active-surface tool rules. Return tool failures that prevent required evidence as a blocker. Tool availability does not grant authority, and consequential external effects remain Root-owned."]:[],...t.computerUse?["Use Computer Use only for this Assignment, following active-surface tool rules and platform restrictions. External actions require explicit task authority. Return tool failures that prevent required evidence as a blocker. Tool availability does not grant authority. Credential entry and submission remain user-owned; never request, enter, retrieve, expose, or store credentials."]:[]].join(`
|
|
39
39
|
`);return[`name = ${JSON.stringify(e.name)}`,`description = ${JSON.stringify(e.description)}`,`model = ${JSON.stringify(e.model)}`,`model_reasoning_effort = ${JSON.stringify(e.effort)}`,`service_tier = ${JSON.stringify(e.serviceTier)}`,'model_reasoning_summary = "none"','model_verbosity = "low"',`sandbox_mode = ${JSON.stringify(Hh(e))}`,'approval_policy = "never"','web_search = "live"',`developer_instructions = ${JSON.stringify(n)}`,"","[agents]","enabled = false","interrupt_message = false","","[features]","multi_agent = false","multi_agent_v2 = false","agent_message_board = false","[features.context_management]","experimental_mode = true","",...Hh(e)==="workspace-write"?["[sandbox_workspace_write]","network_access = true"]:[],""].join(`
|
|
40
40
|
`)}function Hh(e){return e.permissions.filesystem}function zh(e,t){return t.sandbox_mode===Hh(e)&&t.default_permissions===void 0&&(Hh(e)==="workspace-write"?fe(t,"sandbox_workspace_write.network_access")===!0:fe(t,"sandbox_workspace_write.network_access")===void 0)}function Nz(e,t,n){return['name = "root"','description = "Root-directed HolyCodex control agent."',`model = ${JSON.stringify(e)}`,`model_reasoning_effort = ${JSON.stringify(t)}`,`service_tier = ${JSON.stringify(n)}`,'model_verbosity = "low"',""].join(`
|
|
41
41
|
`)}function Wc(e){return Fz.has(e)}async function IF(e){try{await co(e);let t=await vv(e);if(!t.isFile()||t.isSymbolicLink())return"preserved";let n=await Rv(e,"utf8");if(!Wc(n))return"preserved";return await jh(e,{force:!1}),"removed"}catch(t){if(We(t,"ENOENT"))return"absent";throw t}}async function ra(e){try{await co(e);let t=await vv(e);if(t.isSymbolicLink()||!t.isFile())throw Error(`Invalid managed path: ${e}`);return new TextDecoder("utf-8",{fatal:!0}).decode(await Rv(e))}catch(t){if(We(t,"ENOENT"))return;throw t}}async function jn(e){let t=typeof e==="string"?new TextEncoder().encode(e):e,n=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(n),(r)=>r.toString(16).padStart(2,"0")).join("")}function AF(e,t,n,r,o){return{identity:`role-asset:${e}:${t}`,category:"role-asset",target:e,existing:n,desired:r,defaultDecision:"replace",validDecisions:["keep","replace","cancel"],explanation:o,path:e,action:t}}async function PF(e,t,n){if(t===e.contents)return;let r=await jn(t);if(n!==void 0&&r===n.digest)return;return{...AF(e.path,"replace",{present:!0,digest:r},{present:!0,digest:await jn(e.contents)},n===void 0?"A pre-existing generated native role file is not recorded as managed by this installation.":"The managed native role file changed outside the previous HolyCodex transaction."),validDecisions:["replace","cancel"]}}function TF(e){if(typeof e.existing!=="object"||e.existing===null)return;let t=e.existing.digest;return typeof t==="string"?t:void 0}var kz,Ez,Iz,Az="Before acceptance or VCS writes, require a Reviewer.code fixed point and current relevant validation. Review and validation may overlap on non-conflicting scopes; serialize repairs against checks of the same source. Reuse worker proof and assign Worker.validation only for independent proof or an evidence gap. Repairs invalidate only affected evidence.",Pz,Fz;var Kh=w(()=>{cs();ht();ds();Hc();kz=[`Execute the bounded Assignment through its acceptance criteria; make routine in-scope choices without asking. ${Zu.rule} Return material decisions, scope expansion, or required user input to Root; never ask the user. Do not message Root or peers during execution, delegate, change Intent lifecycle, or perform external effects. Read-only Git/VCS, CI, and PR-comment inspection is allowed when relevant and within the Assignment; Git/VCS writes remain Root-only. Source mutation requires permission from the concrete task; proof and cache writes do not grant it. Preserve others' work in the shared tree and adapt to their changes. Root owns the shared background dev server and final visual acceptance. Do not run dev-server or visual-loop.`,"Do not recover an Assignment or mutate another Assignment's lifecycle. Root keeps active invocation capabilities and records terminal results; never request or use those capabilities.",`Return only one compact, evidence-first terminal outcome (${W.specialistOutcomes.map((e)=>`\`${e}\``).join(", ")}) with ${W.specialistReportFields.join(", ")}.`].join(" "),Ez={user_interaction:"user interaction",intent:"Intent",material_decisions:"material decisions",orchestration_lifecycle:"orchestration and lifecycle",integration_acceptance:"integration acceptance",completion:"completion",git_vcs:"Git/VCS writes",external_effects:"external effects",visual_judgment:"visual judgment and its browser inspection",dev_server:"the shared background dev server"},Iz={repository_discovery:"repository discovery",file_source_test_doc_inspection:"file, source, test, and documentation inspection",fact_finding:"fact finding",research:"research",implementation:"implementation",debugging:"debugging",testing:"testing",validation:"validation",frontend_work:"frontend work",security_work:"security work",browser_use:"authorized Browser Use",computer_use:"authorized Computer Use",review:"review",ci_release_observation:"CI or release observation"},Pz=`After dispatching useful independent work, wait collectively for specialist results with ${W.routineWaitTool} at timeout_ms=${W.routineWaitMaximumTimeoutMs}, subject to mandatory active tool/runtime limits. Do not create unnecessary work to avoid waiting, busy-poll, or repeatedly use short waits when a longer event wait is appropriate. A long-running specialist is not stalled merely because others finished; inspect only bounded evidence when a material stall or failure is plausible, then repair, restart, or redispatch only the necessary scope. Batch specialist completion updates rather than reporting each completion separately. Continue useful independent work or wait again while live dependencies remain. Release specialist leaves after accepting terminal outcomes.`;Fz=new Set([{model:"gpt-5.6-terra",effort:"high"},{model:"gpt-5.6-sol",effort:"low"},{model:"gpt-5.6-sol",effort:"medium"},{model:"gpt-5.6-sol",effort:"high"}].flatMap(({model:e,effort:t})=>["default","fast"].map((n)=>Nz(e,t,n))))});import{access as Lz,readFile as Dz,readdir as qz}from"fs/promises";import{join as kv}from"path";class ti{adapter;observedIdentities={};constructor(e){if("run"in e){let t=Th({executable:"codex",runner:e});this.adapter=t}else this.adapter=e}static async discover(e=process.env){let t=await ov({environment:e}),n=Th({executable:t.path,environment:D_(e),onMarketplaceConflict:(r)=>{console.warn(`HolyCodex warning: ${r}`)},...e.CODEX_HOME===void 0?{}:{codexHome:e.CODEX_HOME}});return new ti(n)}async list(){try{return await this.adapter.list()}catch(e){throw Cd("list",e)}}async add(e){try{await this.adapter.add(e)}catch(t){throw Cd("add",t,e)}}async ensureOfficialMarketplace(e){if(this.adapter.ensureOfficialMarketplace===void 0)return;try{await this.adapter.ensureOfficialMarketplace(e)}catch(t){throw Cd("bootstrap",t)}}async remove(e){try{await this.adapter.remove(e)}catch(t){throw Cd("remove",t,e)}}async addMarketplace(e){try{await this.adapter.addMarketplace(e)}catch(t){throw Cd("add",t,e)}}async status(e){let t=await this.list(),n={},r=new Map;for(let i of[...t.installed,...t.available])if(!r.has(i.pluginId)||i.installed)r.set(i.pluginId,i);let o=Object.fromEntries(await Promise.all(e.map(async(i)=>{let a=ao(t,i),s=Qn(i),c=r.get(i),l=a?.entry??(s===void 0||c?.marketplaceName==null?c:void 0),u=a;if(l!==void 0)n[i]=u?.entry.pluginId??l.pluginId;let d=l===void 0?"missing":l.installed&&l.enabled?"installed":l.installed?"disabled":"missing";return[i,d]})));return this.observedIdentities=Object.freeze(n),o}getObservedIdentities(){return this.observedIdentities}}class Jh{codexHome;observedIdentities={};constructor(e){this.codexHome=e}async status(e){let t;try{t=await Dz(kv(this.codexHome,"config.toml"),"utf8")}catch(c){if(Ev(c))return this.observedIdentities=Object.freeze({}),Object.fromEntries(e.map((l)=>[l,"missing"]));throw c}let n=globalThis.Bun;if(!n?.TOML?.parse)throw Error("A TOML parser is unavailable.");let r=Ie(os,n.TOML.parse(t));if(r===void 0)throw Error("Codex configuration is invalid.");let o=r.plugins,i=typeof o==="object"&&o!==null&&!Array.isArray(o)?o:void 0,a={},s=Object.fromEntries(await Promise.all(e.map(async(c)=>{let l=Ic(c),d=(l.length>0?l:[c]).flatMap((g)=>{if(i===void 0||!Object.hasOwn(i,g))return[];let x=i?.[g],v=typeof x==="object"&&x!==null&&!Array.isArray(x)?x.enabled:void 0;return[{id:g,enabled:v}]});if(d.length===0)return[c,"missing"];let p=d.filter((g)=>g.enabled===!0),f=(await Promise.all(p.map(async(g)=>{let x=Ic(g.id),v=[g.id,...x.filter((C)=>C!==g.id)];return{...g,cachedIdentity:await Uz(this.codexHome,v)}}))).find((g)=>g.cachedIdentity!==void 0),y=f?.cachedIdentity??p[0]?.id??d[0]?.id;if(y!==void 0)a[c]=y;if(f!==void 0)return[c,"installed"];if(p.length>0)return[c,"missing"];if(d.every((g)=>g.enabled===!1))return[c,"disabled"];return[c,"unknown"]})));return this.observedIdentities=Object.freeze(a),s}getObservedIdentities(){return this.observedIdentities}}async function Uz(e,t){for(let n of t){let r=n.lastIndexOf("@");if(r<=0||r===n.length-1)continue;let o=kv(e,"plugins","cache",n.slice(r+1),n.slice(0,r));try{let i=await qz(o,{withFileTypes:!0,encoding:"utf8"});for(let a of i){if(!a.isDirectory())continue;try{return await Lz(kv(o,a.name,".codex-plugin","plugin.json")),n}catch(s){if(!Ev(s))throw s}}}catch(i){if(Ev(i))continue;throw i}}return}function Ev(e){return typeof e==="object"&&e!==null&&"code"in e&&e.code==="ENOENT"}function Cd(e,t,n){if(t instanceof uo)return t;let o=(t instanceof he?t:void 0)?.code,i=o==="timeout"||o==="output_limit"||o==="cancelled"||o==="readback_mismatch"||o==="plugin_disabled"||o==="plugin_missing"||o==="marketplace_invalid"||o==="marketplace_timeout"||o==="marketplace_unavailable"?o:o==="command_failed"?e==="list"?"list_failed":e==="remove"?"remove_failed":e==="bootstrap"?"marketplace_unavailable":"add_failed":e==="list"?"list_failed":e==="bootstrap"?"marketplace_unavailable":"add_failed",a=t instanceof Error?t.message:e==="list"?"Codex could not list official plugins.":e==="remove"?`Codex could not remove ${n??"the selected official plugin"}.`:e==="bootstrap"?"Codex could not initialize the official marketplace.":`Codex could not add ${n??"the selected official plugin"}.`;return new uo(i,a,t,n===void 0?{}:{plugin_id:n})}var uo;var Od=w(()=>{cs();ht();ls();uo=class uo extends Error{code;causeValue;details;constructor(e,t,n,r={}){super(t);this.name="OfficialPluginManagerError",this.code=e,this.causeValue=n,this.details=r}}});import{execFile as $z}from"child_process";import{access as jz,readFile as Hz,realpath as Bz}from"fs/promises";import{posix as Vz,win32 as Wz}from"path";import{promisify as zz}from"util";function ys(e=process.env){return{platform:process.platform,environment:e,processPath:process.execPath,files:Kc,run:async(t,n)=>{try{let r=await Kz(t,[...n],{encoding:"utf8",windowsHide:!0,env:{...process.env,...e},timeout:120000,maxBuffer:4194304});return{exitCode:0,stdout:r.stdout,stderr:r.stderr}}catch(r){let o=r;return{exitCode:typeof o.code==="number"?o.code:1,stdout:typeof o.stdout==="string"?o.stdout:"",stderr:typeof o.stderr==="string"?o.stderr:r instanceof Error?r.message:"process failed"}}}}}function hs(e){let t=ir(e.npm_execpath??""),n=(e.npm_command??"").toLowerCase(),r=(e.npm_config_user_agent??"").toLowerCase();if(t.includes("yarn")||t.includes("corepack")||r.startsWith("yarn/"))return;if(kd(t,"pnpm")&&n==="dlx")return{launcher:"pnpm dlx",family:"pnpm",executable:"pnpm"};if(kd(t,"bunx")||kd(t,"bun")&&n==="exec")return{launcher:"bunx",family:"bun",executable:"bun"};if(kd(t,"npx")||t.endsWith("/npx-cli.js")||kd(t,"npm")&&n==="exec"||t.endsWith("/npm-cli.js")&&n==="exec")return{launcher:"npx",family:"npm",executable:"npm"};return}async function Gh(e,t,n){let r=await Av(e);if(r!==void 0){let o=hs(e.environment)??{launcher:"bunx",family:"bun",executable:"bun"},i=n?.ownership==="holycodex"&&typeof n.identity==="string"&&await Jc(e,n.executable,r.executable);return{manager:o.family,launcher:o.launcher,version:r.version,executable:r.executable,ownership:i?"holycodex":"user",...i?{identity:n.identity}:{}}}if(zc(e))return Zz(e,t,n);return Yz(e,t,n)}async function Iv(e,t){let n=await Av(e);if(n!==void 0){let i=hs(e.environment)??{launcher:"bunx",family:"bun",executable:"bun"},a=t?.ownership==="holycodex"&&typeof t.identity==="string"&&await Jc(e,t.executable,n.executable);return{manager:i.family,launcher:i.launcher,version:n.version,executable:n.executable,ownership:a?"holycodex":"user",...a?{identity:t.identity}:{}}}let r=zc(e)?{launcher:"bunx",family:"bun",executable:"bun"}:hs(e.environment);if(r===void 0)throw new be("context7_manager_unknown","No usable PATH Context7 executable or supported package manager is available.");let o=r.family==="bun"&&zc(e)?await Ed(e):await Id(e,r);if(o===void 0)throw new be("context7_unavailable","No usable managed Context7 executable is available.");return{manager:r.family,launcher:r.launcher,version:o.version,executable:o.executable,ownership:Pv(t,r,o),identity:o.identity}}async function Av(e){let t=await FF(e.environment,e.platform,e.files??Kc);if(t===void 0)return;let n=await e.run(t,["--version"]),r=n.exitCode===0?gs(n.stdout):void 0;return r===void 0?void 0:{version:r,executable:t}}async function Jz(e){if(await Av(e)!==void 0)return;if(zc(e)){await Gz(e);return}let t=hs(e.environment);if(t===void 0)throw new be("context7_manager_unknown","HolyCodex must be launched with bunx, npx, or pnpm dlx so Context7 can use the same package manager.");let n=await e.run(t.executable,t.family==="npm"?["prefix","--global"]:t.family==="pnpm"?["bin","--global"]:["pm","bin","-g"]);if(n.exitCode!==0||n.stdout.trim().length===0)throw new be("context7_unavailable",`The ${t.family} global installation could not be inspected before managed changes.`,{stderr:n.stderr.slice(0,512)})}async function Gz(e){let t=e.files??Kc,n=await e.run(e.processPath,["pm","bin","-g"]);if(n.exitCode!==0||n.stdout.trim().length===0){if(oK(n.stderr))return;throw new be("context7_unavailable","Bun's managed global installation could not be located before managed changes.",{stderr:n.stderr.slice(0,512)})}let r=cn(e.platform),o=n.stdout.trim(),i=r.join(r.dirname(o),"install","global"),a=r.join(i,"node_modules","ctx7"),s=r.join(a,"package.json"),c=r.join(o,e.platform==="win32"?"ctx7.exe":"ctx7");try{await t.access(o),await t.access(i)}catch(g){throw new be("context7_unavailable","Bun's managed global location or project is unavailable before managed changes.",{reason:ms(g)})}let l;try{await t.access(a)}catch(g){if(rK(g))return;throw new be("context7_unavailable","Bun's managed ctx7 package could not be inspected before managed changes.",{reason:ms(g)})}try{l=await t.readText(s)}catch(g){throw new be("context7_unavailable","Bun's managed ctx7 package metadata could not be inspected before managed changes.",{reason:ms(g)})}let u;try{u=JSON.parse(l)}catch(g){throw new be("context7_unavailable","Bun's managed ctx7 package metadata is invalid before managed changes.",{reason:ms(g)})}if(typeof u.version!=="string"||gs(u.version)!==u.version)throw new be("context7_unavailable","Bun's managed ctx7 package has no exact semver version before managed changes.");let d=LF(u);if(d===void 0)throw new be("context7_unavailable","Bun's managed ctx7 package does not declare its executable before managed changes.");let p=r.resolve(a,d),m,f;try{await t.access(p),m=await t.realpath(a),f=await t.realpath(p)}catch(g){throw new be("context7_unavailable","Bun's managed ctx7 executable is unavailable before managed changes.",{reason:ms(g)})}if(!Ad(m,a,e.platform)||!ir(f).startsWith(`${ir(m)}/`))throw new be("context7_unavailable","Bun's managed ctx7 executable is outside its package before managed changes.");try{await t.access(c),await t.realpath(c)}catch(g){throw new be("context7_unavailable","Bun's managed ctx7 shim is unavailable before managed changes.",{reason:ms(g)})}let y=await e.run(c,["--version"]);if(y.exitCode!==0||gs(y.stdout)!==u.version)throw new be("context7_unavailable","Bun's managed ctx7 shim does not report the package version before managed changes.",{stderr:y.stderr.slice(0,512)})}async function Yz(e,t,n){let r=hs(e.environment);if(r===void 0)throw new be("context7_manager_unknown","HolyCodex must be launched with bunx, npx, or pnpm dlx so Context7 can use the same package manager.");let o=await Id(e,r),i=await DF(e,r);if(i===void 0)throw new be("context7_verification_failed",`${r.family} could not resolve the latest ctx7 version.`);let a=Pv(n,r,o);if(t&&o?.version!==i&&a==="holycodex"){let l=r.family==="bun"?{executable:"bun",args:Yh(e,"add",or)}:MF(r.family),u=await e.run(l.executable,l.args);if(u.exitCode!==0)throw new be("context7_install_failed",`${r.family} could not install ${or}.`,{stderr:u.stderr.slice(0,512)})}else if(!t&&o===void 0)throw new be("context7_unavailable",`${or} is not owned by the ${r.family} global installation.`);let s=await Id(e,r);if(s===void 0)throw new be("context7_verification_failed",`${or} could not be verified in the ${r.family} global installation.`);if(s.version!==i)throw new be("context7_outdated",`The ${r.family} global ctx7 is ${s.version}; ${i} is required.`,{installed:s.version,latest:i});return{manager:r.family,launcher:r.launcher,version:s.version,executable:s.executable,ownership:a,identity:s.identity}}async function Zz(e,t,n){let r={launcher:"bunx",family:"bun",executable:"bun"},o=await Ed(e),i=await DF(e,r);if(i===void 0)throw new be("context7_verification_failed","Bun could not resolve the latest ctx7 version.");let a=Pv(n,r,o);if(t&&o?.version!==i&&a==="holycodex"){let l=await e.run(e.processPath,Yh(e,"add",or));if(l.exitCode!==0)throw new be("context7_install_failed",`Bun could not install ${or} in its global installation.`,{stderr:l.stderr.slice(0,512)})}else if(o===void 0)throw new be("context7_unavailable",`${or} is not present in Bun's exact global installation.`);let s=await Ed(e);if(s===void 0)throw new be("context7_verification_failed",`${or} could not be verified in Bun's exact global installation.`);if(s.version!==i)throw new be("context7_outdated",`Bun's global ctx7 is ${s.version}; ${i} is required.`,{installed:s.version,latest:i});return{manager:"bun",launcher:"bunx",version:s.version,executable:s.executable,ownership:a,identity:s.identity}}async function Ed(e){let t=e.files??Kc,n=await e.run(e.processPath,["pm","bin","-g"]);if(n.exitCode!==0)return;let r=n.stdout.trim();if(r.length===0)return;let o=cn(e.platform),i=o.join(o.dirname(r),"install","global","node_modules","ctx7"),a;try{a=JSON.parse(await t.readText(o.join(i,"package.json")))}catch{return}if(typeof a.version!=="string"||gs(a.version)!==a.version)return;let s=LF(a);if(s===void 0)return;let c=o.resolve(i,s),l=o.join(r,e.platform==="win32"?"ctx7.exe":"ctx7"),u,d,p;try{await t.access(i),await t.access(c),await t.access(l),u=await t.realpath(i),d=await t.realpath(c),p=await t.realpath(l)}catch{return}if(!Ad(u,i,e.platform)||!ir(d).startsWith(`${ir(u)}/`))return;let m=await e.run(l,["--version"]);if(m.exitCode!==0||gs(m.stdout)!==a.version)return;return{version:a.version,executable:l,identity:await NF({launcher:"bunx",family:"bun",executable:"bun"},u,d,p,a)}}function zc(e){let t=cn(e.platform).basename(e.processPath).toLowerCase();return t==="bun"||t==="bun.exe"}function Pv(e,t,n){if(n===void 0)return"holycodex";if(e?.ownership!=="holycodex")return"user";if(e.manager!==t.family)return"user";let r=e.identity;if(!Mv(r)||r!==n.identity)return"user";return"holycodex"}async function Pd(e,t){if(zc(e))return Xz(e,t);return Qz(e,t)}async function Xz(e,t){if(t?.ownership!=="holycodex"||t.manager!=="bun")return!1;let n;try{n=await Ed(e)}catch{return!1}if(n===void 0||n.version!==t.version||!await Jc(e,n.executable,t.executable)||!Mv(t.identity)||n.identity!==t.identity)return!1;let r=await e.run(e.processPath,Yh(e,"remove","ctx7"));if(r.exitCode!==0)throw new be("context7_remove_failed","Bun could not remove ctx7.",{stderr:r.stderr.slice(0,512)});if(await Ed(e)!==void 0)throw new be("context7_remove_failed","Bun reported success, but the recorded ctx7 installation is still present.");return!0}async function Qz(e,t){if(t?.ownership!=="holycodex")return!1;let n=hs(e.environment);if(n===void 0||n.family!==t.manager)return!1;let r;try{r=await Id(e,n)}catch(a){if(a instanceof be&&a.code==="context7_shadowed")return!1;throw a}if(r===void 0||r.version!==t.version||!await Jc(e,r.executable,t.executable)||!Mv(t.identity)||r.identity!==t.identity)return!1;let o=n.family==="bun"?{executable:"bun",args:Yh(e,"remove","ctx7")}:eK(n.family),i=await e.run(o.executable,o.args);if(i.exitCode!==0)throw new be("context7_remove_failed",`${n.family} could not remove ctx7.`,{stderr:i.stderr.slice(0,512)});try{if(await Id(e,n)!==void 0)throw new be("context7_remove_failed",`${n.family} reported success, but the recorded ctx7 installation is still present.`)}catch(a){if(a instanceof be&&a.code==="context7_remove_failed")throw a;throw new be("context7_remove_failed",`${n.family} removed ctx7, but its final state could not be verified.`)}return!0}function MF(e){switch(e){case"bun":return{executable:"bun",args:["add","--global",or]};case"npm":return{executable:"npm",args:["install","--global",or]};case"pnpm":return{executable:"pnpm",args:["add","--global",or]}}}function Yh(e,t,n){let r=cn(e.platform),o=r.dirname(e.processPath),i=r.isAbsolute(o)?o:e.platform==="win32"?"C:\\":"/";return[t,"--global",`--cwd=${i}`,n]}function eK(e){switch(e){case"bun":return{executable:"bun",args:["remove","--global","ctx7"]};case"npm":return{executable:"npm",args:["uninstall","--global","ctx7"]};case"pnpm":return{executable:"pnpm",args:["remove","--global","ctx7"]}}}async function Id(e,t){let n=e.files??Kc,r=await e.run(t.executable,t.family==="npm"?["prefix","--global"]:t.family==="pnpm"?["bin","--global"]:["pm","bin","-g"]);if(r.exitCode!==0)return;let o=r.stdout.trim();if(o.length===0)return;let i=t.family==="npm"?cn(e.platform).join(o,"node_modules","ctx7"):t.family==="pnpm"?await iK(e,t):cn(e.platform).join(cn(e.platform).dirname(o),"install","global","node_modules","ctx7");if(i===void 0)return;let a;try{a=JSON.parse(await n.readText(cn(e.platform).join(i,"package.json")))}catch{return}if(typeof a.version!=="string")return;let s=typeof a.bin==="string"?a.bin:Nv(a.bin)&&typeof a.bin.ctx7==="string"?a.bin.ctx7:void 0;if(s===void 0)return;let c=cn(e.platform).resolve(i,s),l,u;try{if(await n.access(c),l=await n.realpath(i),u=await n.realpath(c),!ir(u).startsWith(`${ir(l)}/`))return}catch{return}let d=tK(o,t.family,e.platform),p;try{await n.access(d),p=await n.realpath(d)}catch{return}let m=await FF(e.environment,e.platform,n);if(m!==void 0&&!Ad(await nK(n,m),p,e.platform))throw new be("context7_shadowed","A different ctx7 executable shadows the managed global installation.",{resolved:m,expected:d});let f=await e.run(d,["--version"]);if(f.exitCode!==0||gs(f.stdout)!==a.version)return;return{version:a.version,executable:d,identity:await NF(t,l,u,p,a)}}async function NF(e,t,n,r,o){return await qn("context7-installation",[Dn({manager:e.family,package_root:ir(t),package_executable:ir(n),shim:ir(r),package:o})])}function Mv(e){return e!==void 0&&/^[0-9a-f]{64}$/u.test(e)}async function FF(e,t,n){let r=e.PATH;if(r===void 0)return;let o=t==="win32"?(e.PATHEXT??".COM;.EXE;.BAT;.CMD").split(";").filter((i)=>i.length>0).map((i)=>`ctx7${i.toLowerCase()}`):["ctx7"];for(let i of r.split(t==="win32"?";":":")){if(i.length===0)continue;for(let a of o){let s=cn(t).join(i,a);try{return await n.access(s),s}catch{}}}return}function tK(e,t,n){if(n==="win32")return cn(n).join(e,t==="bun"?"ctx7.exe":"ctx7.cmd");return t==="npm"?cn(n).join(e,"bin","ctx7"):cn(n).join(e,"ctx7")}async function nK(e,t){try{return await e.realpath(t)}catch{return t}}function gs(e){return e.match(/\b(\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?)\b/u)?.[1]}function LF(e){return typeof e.bin==="string"?e.bin:Nv(e.bin)&&typeof e.bin.ctx7==="string"?e.bin.ctx7:void 0}function ms(e){if(e instanceof Error)return e.message.slice(0,512);if(typeof e==="string")return e.slice(0,512);return"unknown error"}function rK(e){return Nv(e)&&e.code==="ENOENT"||/\b(?:e?noent|not found|does not exist|missing)\b/iu.test(ms(e))}function oK(e){return/(?:no package\.json(?: was)? found|couldn['\u2019]?t find (?:a )?package\.json|could not find (?:a )?package\.json|package\.json (?:is )?missing)/iu.test(e)}async function iK(e,t){let n=await e.run(t.executable,["root","--global"]),r=n.stdout.trim();return n.exitCode===0&&r.length>0?cn(e.platform).join(r,"ctx7"):void 0}async function DF(e,t){let n=await e.run(t.family==="bun"&&zc(e)?e.processPath:t.executable,t.family==="bun"?["pm","view","ctx7","version"]:["view","ctx7","version"]);if(n.exitCode!==0)return;return gs(n.stdout)}function kd(e,t){return[t,`${t}.exe`,`${t}.cmd`,`${t}.js`,`${t}.cjs`].some((n)=>e.endsWith(`/${n}`))}function Ad(e,t,n){let r=cn(n),o=r.resolve(e),i=r.resolve(t);return n==="win32"?ir(o)===ir(i):o===i}async function Jc(e,t,n){if(Ad(t,n,e.platform))return!0;let r=e.files??Kc;try{let[o,i]=await Promise.all([r.realpath(t),r.realpath(n)]);return Ad(o,i,e.platform)}catch{return!1}}function cn(e){return e==="win32"?Wz:Vz}function ir(e){return e.replaceAll("\\","/").toLowerCase().replace(/\/$/u,"")}function Nv(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}var or="ctx7@latest",Kz,Kc,be;var Zh=w(()=>{ht();Kz=zz($z),Kc={access:jz,readText:(e)=>Hz(e,"utf8"),realpath:Bz};be=class be extends Error{code;details;constructor(e,t,n={}){super(t);this.code=e;this.details=n;this.name="ToolingError"}}});import{rm as Qh,rmdir as Dv}from"fs/promises";import{join as aK}from"path";async function Uv(e={},t=process.env){let n=Pr(e,t),r={};try{await us(n.codexHome),await us(n.stateRoot),r.paths=Gc({state_root:n.stateRoot})}catch(u){r.paths=Kt(["path_symlink"],{error:ar(u)})}let o=await oa(n).catch((u)=>{r.configuration=Kt(["state_corrupt"],{error:ar(u)});return}),[i,a]=await Promise.all([Nr(n.preparingRecord,o).catch((u)=>{r.transaction=Kt(["state_corrupt"],{path:n.preparingRecord,error:ar(u)});return}),Nr(n.conflictedRecord,o).catch((u)=>{r.transaction=Kt(["state_corrupt"],{path:n.conflictedRecord,error:ar(u)});return})]);if(r.transaction?.status!=="failed"&&(i!==void 0||a!==void 0)){let u=rg(o,i,a),d=[...new Set(u.map((p)=>{if(p.relation==="stale")return"stale_transaction_state";if(p.relation==="incompatible")return"incompatible_transaction_state";return p.status==="preparing"?"incomplete_install_state":"conflicted_state"}))];r.transaction=Kt(d,{recovery:u.map((p)=>p.recovery).join(","),transactions:u.map((p)=>`${p.status}:${p.relation}:${p.install_id}:${p.digest}`).join(","),active:o===void 0?"absent":`${o.install_id}:${o.digest}`})}if(!r.configuration)if(!o)r.configuration=Kt(["configuration_missing"]);else if(await bs(o))r.configuration=Gc({profile:o.profile,tier:o.tier,install_id:o.install_id});else r.configuration=Kt(["configuration_changed"],{path:n.activeRecord});if(o){r.runtime_config=await gK(n,o),r.native_roles=await yK(n,o.profile,o.tier,{browserUse:o.capability_state?.browser_use.status==="healthy"&&o.capability_state.browser_use.selected,computerUse:o.capability_state?.computer_use.status==="healthy"&&o.capability_state.computer_use.selected});let u=Object.entries(o.capability_state??{}).find(([d,p])=>d!=="browser_use"&&p.selected&&p.status!=="healthy");if(u)r.capabilities=Kt(["selected_capability_not_healthy"],{capability:u[0],status:u[1].status});if(o.optional_selections.browser_use)r.browser_use={status:"unsupported",reasons:["surface_managed_by_codex_desktop"],details:{selected:!0,owner:"Codex Desktop/runtime",availability:"Available only on Codex surfaces that provide Browser Use.",cli_provisioning:"HolyCodex CLI does not install, configure, or verify Browser."}}}let s=e.runtime??ys(t);try{let u=await Iv(s,o?.tooling?.context7);r.context7=Gc({manager:u.manager,version:u.version,executable:u.executable,ownership:u.ownership})}catch(u){r.context7={status:"warning",reasons:["context7_unavailable"],details:{error:ar(u)}}}try{let u=await ye(`${n.codexHome}/agents/root.toml`);if(u!==void 0&&Wc(u)){let d=r.native_roles;r.native_roles={status:"failed",reasons:[...d?.reasons??[],"stale_legacy_root"],details:{...d?.details,path:`${n.codexHome}/agents/root.toml`}}}}catch(u){r.native_roles=Kt(["native_role_invalid"],{error:ar(u)})}let c=e.officialPluginManager;if(o&&c?.status){let u=[...new Set([un,...Ac({browser_use:o.optional_selections.browser_use,computer_use:o.optional_selections.computer_use,sites:o.optional_selections.sites},o.official_plugins),...(o.owned_plugins??[]).filter((d)=>d!==ln)])].filter((d)=>d!==ln);try{let d=await c.status(u),p=Object.entries(d).filter(([,f])=>f!=="installed").map(([f])=>f),m=c.getObservedIdentities?.()??{};r.native_plugins=p.length===0?Gc({status:d,observed_identities:m}):Kt(["native_plugin_disagreement"],{missing:p,status:d,observed_identities:m})}catch(d){r.native_plugins=Kt(["native_plugin_status_failed"],{error:ar(d)})}}else r.native_plugins=Kt(["native_plugin_status_unavailable"],{reason:"No read-only live official plugin status source is available."});let l=Object.values(r).flatMap((u)=>u.reasons);return{healthy:Object.values(r).every((u)=>u.status!=="failed"),checks:r,reasons:[...new Set(l)]}}async function $v(e={},t=process.env){let n=Pr(e,t);await us(n.codexHome),await us(n.stateRoot);let r=await oa(n);if(r!==void 0&&!await bs(r))throw new _("state_corrupt","The HolyCodex ownership record has an invalid digest and cannot authorize removal.",void 0,{path:n.activeRecord});let[o,i]=await Promise.all([Nr(n.preparingRecord,r),Nr(n.conflictedRecord,r)]);Bv(r,o,i);let a=BF(r,o,i);if(a===void 0)return[];let s=Jt(await ye(n.configFile)),c=[];if(a.managed_config!==void 0){let l=await Ar(s,a.managed_config,{schema:a.managed_config.schema,installId:a.managed_config.installId});for(let u of[...l.preservedKeys,...l.unresolvedKeys])c.push(await Lv(n.configFile,u,s,"config-key","This managed Codex setting changed after installation."))}if(a.plugin_config!==void 0){let l=await Yc(s,a.plugin_config,{allowBeforeState:!0});for(let u of l.preserved){let d=u==="preference"?'plugins."holycodex@holycodex"':"marketplaces.holycodex";c.push(await Lv(n.configFile,d,s,"plugin-config","This HolyCodex plugin setting differs from the recorded install state."))}}if(a.provider_config!==void 0){let l=await Zc(s,eg(a.provider_config),new Set(jv(a)),{allowBeforeState:!0});for(let u of l.preserved){let d=`plugins.${JSON.stringify(u)}`;c.push(await Lv(n.configFile,d,s,"plugin-config",`The ${u} plugin setting differs from the recorded install state.`))}}return c.push(...await CF(n.codexHome,a.managed_artifacts)),[...new Map(c.map((l)=>[po(l),l])).values()]}async function Md(e={},t=process.env){let n=Pr(e,t);await us(n.codexHome),await us(n.stateRoot);let r=await oa(n);if(r&&!await bs(r))throw new _("state_corrupt","The HolyCodex ownership record has an invalid digest and cannot authorize removal.",void 0,{path:n.activeRecord});let[o,i]=await Promise.all([Nr(n.preparingRecord,r),Nr(n.conflictedRecord,r)]);Bv(r,o,i);let a=BF(r,o,i);Xh(e,{stage:"removal",status:"started",message:"Removing HolyCodex-owned state"});let s=new Set(jv(a)),c=[],l=[],u=[],d=!1,p=()=>(Xh(e,{stage:"removal",status:"completed",message:"HolyCodex removal preserved state for review"}),{removed:c,preserved:l,reasons:u});if(a===void 0)return Xh(e,{stage:"removal",status:"completed",message:"Nothing to remove"}),{removed:c,preserved:l,reasons:u};let m=await $v(e,t),f=await mK(e,m),y=await ye(n.configFile),g=Jt(y),x=m.filter((S)=>S.key!==void 0&&f.has(po(S))),v=new Map;for(let S of m){if(S.key!==void 0||!f.has(po(S)))continue;let D=jF(S);if(D!==void 0)v.set(S.path,D)}await hK(n,g,x,v);let C=a?.managed_config;if(C){let S=await Ar(g,C,{schema:C.schema,installId:C.installId});if(S.preservedKeys.length>0||S.unresolvedKeys.length>0){let P=[...S.preservedKeys,...S.unresolvedKeys].map((pe)=>({path:n.configFile,key:pe,action:"remove"}));for(let pe of P)if(f.has(po(pe)))g=tr(g,pe.key)}}if(a?.plugin_config){let S=await Yc(g,a.plugin_config,{allowBeforeState:!0});if(S.preserved.length>0){let D=S.preserved.map((P)=>({path:n.configFile,key:P==="preference"?'plugins."holycodex@holycodex"':"marketplaces.holycodex",action:"remove"}));for(let P of S.preserved){let pe=D.find((De)=>De.key===(P==="preference"?'plugins."holycodex@holycodex"':"marketplaces.holycodex"));if(pe===void 0||!f.has(po(pe)))continue;g=tr(g,P==="preference"?'plugins."holycodex@holycodex"':"marketplaces.holycodex")}}}if(a?.provider_config){let S=await Zc(g,eg(a.provider_config),s,{allowBeforeState:!0});if(S.preserved.length>0){let D=S.preserved.map((P)=>({path:n.configFile,key:`plugins."${P}"`,action:"remove"}));for(let P of S.preserved){let pe=D.find((De)=>De.key===`plugins."${P}"`);if(pe===void 0||!f.has(po(pe)))continue;g=tr(g,`plugins."${P}"`)}}}let M,N;if(s.size>0){try{M=e.officialPluginManager??await ti.discover({...t,CODEX_HOME:n.codexHome})}catch(S){throw new _("capability_denied","Native Codex plugin removal is unavailable.",S,{operation:"discover Codex",plugins:[...s].join(","),recovery:"Install or expose Codex, then retry."})}if(M===void 0||!M.remove||!M.list)throw new _("capability_denied","Native Codex plugin removal and readback are unavailable.",void 0,{operation:"prepare plugin removal",plugins:[...s].join(",")});try{N=await M.list()}catch(S){throw new _("capability_denied","Codex plugin state could not be read before removing HolyCodex-owned plugins.",S,{operation:"read Codex plugin state",plugins:[...s].join(","),recovery:"Repair or expose Codex, then retry removal."})}}let O,k=a;try{let S=g,D=C;if(D){let P=await Ar(S,D,{schema:D.schema,installId:D.installId}),pe=[...P.preservedKeys,...P.unresolvedKeys];if(pe.filter((Rt)=>!f.has(po({path:n.configFile,key:Rt,action:"remove"}))).length>0)return l.push(n.configFile),u.push("managed_config_changed"),await Mr(n,a??xs()),p();if(S=P.document,pe.length>0){let Rt=new Set(pe);D={...P.state,managed:Object.fromEntries(Object.entries(P.state.managed).filter(([Tt])=>!Rt.has(Tt)))}}else D=P.state}if(a?.plugin_config){let P=await Yc(S,a.plugin_config,{allowBeforeState:!0});if(P.preserved.length>0)return l.push(n.configFile),u.push("plugin_config_changed"),await Mr(n,a),p();S=P.document}if(a?.provider_config){let P=await Zc(S,eg(a.provider_config),s,{allowBeforeState:!0});if(P.preserved.length>0)return l.push(n.configFile),u.push("provider_config_changed"),await Mr(n,a),p();S=P.document}if(a?.managed_config||a?.plugin_config||a?.provider_config)O=D===void 0?{document:S}:{document:S,state:D};if(O!==void 0){if(Object.keys(O.document).length===0&&y===void 0)await qF(n.configFile,y),await Qh(n.configFile,{force:!1});else await qF(n.configFile,y),await vt(n.configFile,fo(O.document));k={...a,managed_config:O.state},await Mr(n,k),d=!0}}catch(S){if(S instanceof _)throw await Mr(n,k??xs()),S;return l.push(n.configFile),u.push("managed_config_write_failed"),await Mr(n,k??xs()),p()}let I=await Wh(n.codexHome,a?.managed_artifacts??[],v);if(c.push(...I.removed),l.push(...I.preserved),I.preserved.length>0)return u.push("managed_artifact_changed"),await Mr(n,k??a??xs()),p();c.push(...await lK(n.roleRoot,a?.managed_artifacts??[]));for(let S of s)try{if(M?.list===void 0||M.remove===void 0||N===void 0)throw new _("capability_denied","Codex plugin state is unavailable for a HolyCodex-owned plugin.",void 0,{operation:"remove Codex plugin",plugin_id:S});let P=xK(N,S);if(P?.entry.installed!==!0)continue;let pe=P.entry.pluginId;await M.remove(pe);let De=await M.list();if(N=De,ao(De,S)?.entry?.installed===!0||[...De.installed,...De.available].some((et)=>et.pluginId===S&&et.installed))throw new _("capability_denied",`Codex still reports ${S} after removal.`);if(O!==void 0)await cK(n,O.document,S);c.push(S)}catch(D){throw u.push("native_plugin_remove_failed"),await Mr(n,k??xs()),new _("capability_denied",`Codex native plugin removal did not converge for ${S}: ${ar(D)}`,D)}try{if(await Pd(e.runtime??ys(t),a.tooling?.context7))c.push("ctx7")}catch(S){throw u.push("context7_remove_failed"),await Mr(n,k??xs()),new _("capability_denied",`Context7 removal did not converge: ${ar(S)}`,S)}if(r)try{await Qh(n.activeRecord,{force:!1}),c.push(n.activeRecord)}catch(S){if(!We(S,"ENOENT"))return l.push(n.activeRecord),u.push("state_remove_failed"),await Mr(n,a??r),p()}if(l.length===0)try{await Qh(n.installOptions,{force:!1}),c.push(n.installOptions)}catch(S){if(!We(S,"ENOENT"))l.push(n.installOptions),u.push("state_remove_failed"),await Mr(n,a??r??xs())}if(l.length===0)for(let[S,D]of[[n.preparingRecord,o!==void 0],[n.conflictedRecord,i!==void 0||d]]){if(!D)continue;try{await SK(S),c.push(S)}catch{l.push(S),u.push("state_remove_failed")}}if(l.length===0)try{await Dv(n.roleRoot),c.push(n.roleRoot)}catch(S){if(!We(S,"ENOENT"))l.push(n.roleRoot),u.push("role_directory_not_empty")}if(l.length===0)try{await Dv(n.stateRoot),c.push(n.stateRoot)}catch(S){if(We(S,"ENOENT"))c.push(n.stateRoot);else l.push(n.stateRoot),u.push("state_directory_not_empty")}return Xh(e,{stage:"removal",status:"completed",message:l.length===0&&u.length===0?"HolyCodex removal complete":"HolyCodex removal preserved state for review"}),{removed:c,preserved:l,reasons:u}}async function cK(e,t,n){let r=await ye(e.configFile);if(r===void 0)return;let o=Jt(r,e.configFile),i=o.plugins;if(!Fv(i))return;let a=i[n];if(!Fv(a)||Object.keys(a).length!==1||a.enabled!==!1)return;let s=t.plugins,c=Fv(s)?s[n]:void 0,l={...i};if(c===void 0)delete l[n];else l[n]=c;let u={...o};if(Object.keys(l).length===0)delete u.plugins;else u.plugins=l;await vt(e.configFile,fo(u))}function Fv(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}async function lK(e,t){let n=new Set;for(let o of t){let i=o.path.split("/");if(i.length===4&&i[0]==="holycodex"&&i[1]==="agents"&&/^[a-f0-9]{20}$/u.test(i[2]??"")&&i[3]?.endsWith(".toml"))n.add(i[2])}let r=[];for(let o of n){let i=aK(e,o);try{await Dv(i),r.push(i)}catch(a){if(!We(a,"ENOENT")&&!We(a,"ENOTEMPTY")&&!We(a,"EEXIST"))throw a}}return r}async function uK(e={},t=process.env,n={}){let r=Pr(e,t),o=await oa(r),[i,a]=await Promise.all([Nr(r.preparingRecord,o),Nr(r.conflictedRecord,o)]);if(o!==void 0&&!await bs(o))throw new _("state_corrupt","The existing HolyCodex configuration has changed and cannot be upgraded safely.",void 0,{path:r.activeRecord});Hv(o,i,a);let s=HF(o,i,a),c=s??o;if(c===void 0)throw new _("not_installed","HolyCodex is not installed in the selected Codex home.",void 0,{recovery:"Run `holycodex install --yes` first."});let l=await ng(r),u=l===void 0?{profile:c.profile,tier:c.tier,optional:{browser_use:c.optional_selections.browser_use,computer_use:c.optional_selections.computer_use,sites:c.optional_selections.sites},officialPlugins:dK(c)}:pK(Nd(l)),d=n.options===void 0?u:dn(n.options),p={profile:d.profile??u.profile,tier:d.tier??u.tier,optional:{...u.optional,...d.optional},officialPlugins:d.officialPlugins??u.officialPlugins},m=!fK(p,u),f;try{f=await vd()}catch(k){throw new _("upgrade_failed","The running HolyCodex version is unavailable.",k)}let y=f.split("-",1)[0]===c.version.split("-",1)[0]&&f.includes("-dev.")!==c.version.includes("-dev."),g=y?0:Ec(f,c.version);if(g<0)throw new _("upgrade_downgrade",`The running HolyCodex version ${f} is older than the installed version ${c.version}.`,void 0,{installed_version:c.version,running_version:f});let x=c.managed_config?.managed["features.context_management"]!==void 0,v=c.managed_config?.managed[Zi[0]]!==void 0,C=[];if(n.dryRun===!0){let k=Jt(await ye(r.configFile));if(c.managed_config!==void 0)for(let S of Object.keys(c.managed_config.managed)){if(!is(S))continue;if((await ss(k,c.managed_config,S)).status!=="unchanged")C.push({path:r.configFile,key:S,action:"replace"})}if(c.plugin_config!==void 0){let S=await Yc(k,c.plugin_config);for(let D of S.preserved){let P=D==="preference"?'plugins."holycodex@holycodex"':"marketplaces.holycodex";C.push({path:r.configFile,key:P,action:"replace"})}}if(c.provider_config!==void 0){let S=await Zc(k,eg(c.provider_config),new Set(jv(c)));for(let D of S.preserved)C.push({path:r.configFile,key:`plugins."${D}"`,action:"replace"})}let I=await Bh(r.codexHome,c.profile,c.managed_artifacts,c.tier,{browserUse:c.optional_selections.browser_use,computerUse:c.optional_selections.computer_use});for(let S of I)C.push(S)}let M=!1,N=[];try{let k=e.runtime??ys(t),I;try{I=await Iv(k,c.tooling?.context7)}catch(D){if(c.tooling?.context7!==void 0||!bK(D))throw D}let S=c.tooling?.context7;if(S?.manager!==I?.manager)N.push("Context7 manager changed");if(S?.version!==I?.version)N.push("Context7 version changed");if(S?.executable===void 0?I?.executable!==void 0:I?.executable===void 0||!await Jc(k,S.executable,I.executable))N.push("Context7 executable changed");M||=N.length>0}catch(k){M=!0;let I=typeof k==="object"&&k!==null&&"code"in k&&typeof k.code==="string"?k.code:k instanceof Error?k.name:"inspection failed";N.push(`inspection failed (${I})`)}let O=[...g>0||y?["version"]:[],...m?["installation options"]:[],...l===void 0?["installation options migration"]:[],...x?["context-management configuration migration"]:[],...v?["auto-compaction configuration cleanup"]:[],...g>0||x||v?["Root/session configuration","specialist role definitions"]:[],...s?["interrupted transaction recovery"]:[],...M?[`shared tooling reconciliation (${N.join(", ")})`]:[],...C.map((k)=>`conflict: ${k.path}${k.key===void 0?"":` (${k.key})`} -> ${k.action}`)];if(O.length===0)return{status:n.dryRun===!0?"dry_run":"current",from_version:c.version,to_version:f,changes:[],record:o,preserved:[],warnings:[],conflicts:C};if(n.dryRun===!0)return{status:"dry_run",from_version:c.version,to_version:f,changes:O,record:o,preserved:[],warnings:[],conflicts:C};try{let k=await Ss(p,e,t);return{status:"upgraded",from_version:c.version,to_version:f,changes:O,record:k.record,preserved:k.preserved,warnings:k.warnings}}catch(k){if(k instanceof _)throw k;throw new _("upgrade_failed",`HolyCodex upgrade failed: ${ar(k)}`,k)}}function dK(e){let t=new Set(Ac(e.optional_selections));return(e.official_plugins??[]).filter((n)=>n!==ln&&!UF(n)&&!t.has(n))}function eg(e){return e.filter((t)=>t.plugin_id!==ln)}function pK(e){return{...e,...e.officialPlugins===void 0?{}:{officialPlugins:e.officialPlugins.filter((t)=>!UF(t))}}}function UF(e){let t=e.slice(0,e.lastIndexOf("@"));return sK.has(t)}function fK(e,t){let n=e.optional??{},r=t.optional??{},o=[...new Set(e.officialPlugins??[])],i=[...new Set(t.officialPlugins??[])];return e.profile===t.profile&&e.tier===t.tier&&n.browser_use===r.browser_use&&n.computer_use===r.computer_use&&n.sites===r.sites&&o.length===i.length&&o.every((a,s)=>a===i[s])}async function mK(e,t){let n=new Set;if(e.resolveConflicts!==void 0&&t.length>0){let r=t.map((i)=>({...i,identity:`remove:${i.path}:${i.key??""}`,category:i.key===void 0?"role-asset":"config-key",target:i.key??i.path,explanation:"HolyCodex can remove this managed value after reviewing the change.",validDecisions:["keep","remove","cancel"],defaultDecision:"keep"})),o=await e.resolveConflicts(r);for(let i=0;i<r.length;i+=1){let a=r[i],s=o[a.identity];if(s==="remove")n.add(po(t[i]));else if(s==="keep")continue;else if(s==="cancel")throw new _("confirmation_required","Conflict resolution was cancelled.",void 0,{identity:a.identity,path:a.path,...a.key===void 0?{}:{key:a.key}});else throw new _("confirmation_required",`The removal conflict at ${a.target} requires a keep, remove, or cancel decision.`,void 0,{identity:a.identity,path:a.path,...a.key===void 0?{}:{key:a.key},decision:s??"unavailable"})}return n}for(let r of t){let o=await e.resolveConflict?.(r);if(o==="accept"){n.add(po(r));continue}if(o==="decline")continue;throw new _("confirmation_required",o==="cancel"?"Conflict resolution was cancelled.":"Modified HolyCodex-owned state requires confirmation before removal.",void 0,{path:r.path,...r.key===void 0?{}:{key:r.key},action:r.action,resolution:o??"unavailable"})}return n}function po(e){return`${e.action}\x00${e.path}\x00${e.key??""}`}async function Lv(e,t,n,r,o){let i=fe(n,t),a=await $F(n,t);return{identity:po({path:e,key:t,action:"remove"}),category:r,target:t,existing:{present:i!==void 0,digest:a},desired:{present:!1},explanation:o,validDecisions:["keep","remove","cancel"],defaultDecision:"keep",path:e,key:t,action:"remove"}}async function $F(e,t){let n=fe(e,t);return await qn("holycodex-removal-config-review-v1",[Dn(sn(n===void 0?{present:!1}:{present:!0,value:n}))])}function jF(e){if(typeof e.existing!=="object"||e.existing===null)return;let t=e.existing.digest;return typeof t==="string"?t:void 0}async function hK(e,t,n,r){for(let i of n){if(i.key===void 0)continue;let a=jF(i);if(a===void 0||await $F(t,i.key)!==a)throw qv(i.path,i.key)}let o;try{o=await OF(e.codexHome,r)}catch(i){let a=r.keys().next().value;throw new _("confirmation_required","A reviewed HolyCodex file could not be checked safely, so removal did not continue.",i,{operation:"verify removal review",...a===void 0?{}:{path:a},recovery:"Check file access, then run remove again to review current state."})}if(o.length>0)throw qv(o[0])}function qv(e,t){return new _("confirmation_required","A reviewed HolyCodex item changed before removal. No reviewed changes were applied; run remove again to review the current state.",void 0,{operation:"remove HolyCodex",path:e,...t===void 0?{}:{key:t},recovery:"Run remove again to review the current state."})}async function qF(e,t){if(await ye(e)!==t)throw qv(e)}async function gK(e,t){if(!t.managed_config)return Kt(["incomplete_install_state"]);try{let n=Jt(await ye(e.configFile)),r=Ld(t.profile,t.tier,{browserUse:t.capability_state?.browser_use.status==="healthy"&&t.capability_state.browser_use.selected,computerUse:t.optional_selections.computer_use,frontend:Pt.frontend,security:Pt.security}),o=[];for(let i of Object.keys(r))if((await ss(n,t.managed_config,i)).status!=="unchanged")o.push(i);return o.length===0?Gc({managed_keys:Object.keys(r).length}):Kt(["changed_holycodex_config"],{keys:o})}catch(n){return Kt(["config_unreadable"],{error:ar(n)})}}async function yK(e,t,n,r={browserUse:!1,computerUse:!1}){try{let o=Jt(await ye(e.configFile)),i=[],a=fs(t,n,r);for(let c of ei(t,n)){let l=fe(o,`agents."${c.name}".config_file`),u=as(e.configFile,Td(c.name,a)).replaceAll("\\","/");if(typeof l!=="string"||as(e.configFile,l).replaceAll("\\","/")!==u){i.push(`${c.name}:registration`);continue}let d=await ye(u);if(d===void 0){i.push(`${c.name}:missing`);continue}if(d!==Vc(c,r)){i.push(`${c.name}:changed`);continue}let p=Jt(d);if(p.name!==c.name||typeof p.description!=="string"||typeof p.developer_instructions!=="string"||p.model!==c.model||p.model_reasoning_effort!==c.effort||p.model_reasoning_summary!=="none"||p.model_verbosity!=="low"||p.tool_output_token_limit!==void 0||p.service_tier!==(n==="standard"?"default":"fast")||!zh(c,p)||p.approval_policy!=="never"||p.web_search!==(c.permissions.network?"live":"disabled")||fe(p,"agents.enabled")!==!1||fe(p,"features.multi_agent")!==!1||fe(p,"features.multi_agent_v2")!==!1||fe(p,"features.agent_message_board")!==!1||fe(p,"features.context_management.experimental_mode")!==!0||Object.keys(p.features??{}).some((m)=>!["multi_agent","multi_agent_v2","agent_message_board","context_management"].includes(m)))i.push(`${c.name}:malformed`)}let s=await ye(`${e.codexHome}/agents/root.toml`);if(s!==void 0&&Wc(s))i.push("root:stale");return i.length===0?Gc({role_root:e.roleRoot,agent_types:ei(t,n).map((c)=>c.name)}):Kt(["native_role_disagreement"],{roles:i})}catch(o){return Kt(["native_role_invalid"],{error:ar(o)})}}async function Mr(e,t){let n={...t,status:"conflicted",step:"conflicted",managed_config:t.managed_config??{owner:"holycodex",schema:t.schema_epoch,installId:t.install_id,managed:{}},plugin_snapshot:t.plugin_snapshot??[],owned_plugins:t.owned_plugins??[]};if(Ie(ta,n)!==void 0)await jc(e.conflictedRecord,sn(n))}function HF(e,t,n){return[n,t].find((r)=>r!==void 0&&(e===void 0||Fd(r,e)))}function BF(e,t,n){return HF(e,t,n)??e}function xs(){return{owner:"holycodex",schema_epoch:"state-0.16",install_id:"remove-conflict",version:"0.0.0",digest:"0".repeat(64),profile:"default",tier:"standard",optional_selections:{browser_use:!1,computer_use:!1,sites:!1,coding:!0},explicit_optional_selections:{},managed_artifacts:[],installed_at:new Date(0).toISOString()}}function jv(e){if(e?.owned_plugins!==void 0)return[...new Set(e.owned_plugins)].filter((o)=>o!==ln);let t=(e?.plugin_snapshot??[]).filter((o)=>o.plugin_id!==ln&&(o.status==="missing"||o.status==="available")).map((o)=>o.plugin_id),n=e?.plugin_config?.before.preference.presence==="absent"&&e.plugin_config.after.preference.presence==="present"?[un]:[],r=(e?.provider_config??[]).filter((o)=>o.plugin_id!==ln&&o.before.presence==="absent"&&o.after.presence==="present").map((o)=>o.plugin_id);return[...new Set([...t,...n,...r])]}function xK(e,t){let n=ao(e,t);if(n!==void 0)return n;let r=[...e.installed,...e.available].find((o)=>o.pluginId===t);return r===void 0?void 0:{entry:r}}function Gc(e){return{status:"healthy",reasons:[],details:e}}function Kt(e,t={}){return{status:"failed",reasons:e,details:t}}async function SK(e){await Qh(e,{force:!1}).catch((t)=>{if(!We(t,"ENOENT"))throw t})}function bK(e){return typeof e==="object"&&e!==null&&"code"in e&&(e.code==="context7_unavailable"||e.code==="context7_manager_unknown")}function ar(e){return e instanceof Error?e.message.slice(0,256):"operation failed"}function Xh(e,t){try{e.onProgress?.(t)}catch{}}var sK;var tg=w(()=>{cs();ht();Dd();hd();Rd();Kh();Od();ds();ls();Hc();Zh();sK=new Set(["documents","pdf","presentations","spreadsheets","template-creator"])});import{lstat as YF,open as wK,rm as $d}from"fs/promises";import{dirname as _K}from"path";function dn(e){let t=Ie(qh,e);if(t===void 0)throw new _("install_failed","The installation options are invalid.");let n=t;return XF(n),n}function XF(e){if(e.officialPlugins?.includes(ln)!==!0)return;throw new _("install_failed","Browser Use is provided by Codex Desktop/runtime and cannot be installed by the HolyCodex CLI. Select the Browser Use capability instead; it is available only on supporting Codex surfaces.",void 0,{plugin_id:ln})}async function ng(e){let t=await ye(e.installOptions);return QF(t,e.installOptions)}function QF(e,t){if(e===void 0)return;let n;try{n=bd(e)}catch(i){throw new _("state_corrupt","The HolyCodex install options are not valid TOML.",i,{path:t})}let r=Ie(Sd,n);if(r!==void 0)return r;let o=Ie(rF,n);if(o!==void 0)return{schema_version:1,profile:o.profile,tier:o.tier,capabilities:o.capabilities.filter((i)=>i==="browser_use"||i==="computer_use"||i==="sites").concat(...["browser_use","sites"].filter((i)=>!o.capabilities.includes(i))),additional_plugins:o.additional_plugins};if(r===void 0)throw new _("state_corrupt","The HolyCodex install options are invalid.",void 0,{path:t});return r}async function eL(e,t){if(Ie(Sd,t)===void 0)throw new _("state_corrupt","The HolyCodex install options are invalid.");await vt(e.installOptions,wd(t))}function Nd(e){return{profile:e.profile,tier:e.tier,optional:{browser_use:e.capabilities.includes("browser_use"),computer_use:e.capabilities.includes("computer_use"),sites:e.capabilities.includes("sites")},officialPlugins:e.additional_plugins.filter((t)=>t!==ln)}}async function tL(e={},t=process.env){let n=Pr(e,t),r=await ng(n);if(r!==void 0)return Nd(r);let o=await oa(n);if(o===void 0)return{};return{profile:o.profile,tier:o.tier,optional:o.optional_selections,officialPlugins:Zv(o)}}function nL(e,t,n,r){let o=["browser_use","computer_use","sites"].filter((i)=>n[i]);return{schema_version:1,profile:e,tier:t,capabilities:o,additional_plugins:[...new Set(r)].filter((i)=>i!==ln)}}function Fd(e,t){return e.install_id===t.install_id&&e.digest===t.digest}function rg(e,t,n){let r=[{status:"conflicted",record:n},{status:"preparing",record:t}].filter((a)=>a.record!==void 0),o=r.length>1,i=o&&r.every(({record:a})=>Fd(a,r[0].record));return r.map(({status:a,record:s})=>{let c=e===void 0?o&&!i?"incompatible":"orphaned":Fd(s,e)?o&&!i?"incompatible":"bound":"stale";return{status:a,relation:c,install_id:s.install_id,digest:s.digest,recovery:c==="stale"||c==="incompatible"?"inspect":"reconcile",...e===void 0?{}:{active_install_id:e.install_id,active_digest:e.digest}}})}function Hv(e,t,n){let r=rg(e,t,n);if(r.filter((i)=>i.relation==="stale"||i.relation==="incompatible").length>0)throw new _("state_corrupt","HolyCodex has stale or incompatible transaction state and cannot recover safely.",void 0,rL(r));return r}function Bv(e,t,n){let r=rg(e,t,n);if(e===void 0&&r.some((o)=>o.relation==="incompatible"))throw new _("state_corrupt","HolyCodex has ambiguous transaction state and cannot recover safely.",void 0,rL(r));return r}function rL(e){return{recovery:e.map((t)=>t.recovery).join(","),transactions:e.map((t)=>`${t.status}:${t.relation}:${t.install_id}:${t.digest}`).join(","),active:e[0]?.active_install_id===void 0?"absent":`${e[0].active_install_id}:${e[0].active_digest}`}}async function Ss(e={},t={},n=process.env){let r=Ie(xd,e);if(r===void 0)throw new _("install_failed","The installation options are invalid.");XF(r);let o=Pr(t,n),i=await ye(o.installOptions),a=QF(i,o.installOptions),s=a===void 0?void 0:Nd(a);Fr(t,{stage:"validation",status:"started",message:"Validating Codex target"});let c=await oa(o),l=await ye(o.activeRecord);if(c!==void 0&&!await bs(c))throw new _("state_corrupt","The existing HolyCodex configuration has changed and cannot be replaced.",void 0,{path:o.activeRecord});let u=await Nr(o.preparingRecord,c),d=await Nr(o.conflictedRecord,c);Hv(c,u,d);let p=[d,u].find((A)=>A!==void 0&&(c===void 0||Fd(A,c)));if(p!==void 0){await Promise.resolve().then(() => tg());let L=await Md(t,n);if(L.preserved.length>0||L.reasons.length>0)throw new _("state_corrupt","The interrupted HolyCodex installation could not be reconciled safely.",void 0,{preserved:L.preserved.join(","),reasons:L.reasons.join(",")});return await Ss({profile:e.profile??s?.profile??p.profile,tier:e.tier??s?.tier??p.tier,optional:{browser_use:e.optional?.browser_use??s?.optional?.browser_use??p.optional_selections.browser_use,computer_use:e.optional?.computer_use??s?.optional?.computer_use??p.optional_selections.computer_use,sites:e.optional?.sites??s?.optional?.sites??p.optional_selections.sites},officialPlugins:e.officialPlugins??s?.officialPlugins??Zv(p)},t,n)}let m=GK(e.profile??s?.profile,c?.profile),f=YK(e.tier??s?.tier,c?.tier),y=s?.optional,g=Gv(y,e.optional),x=ZK(g,c?.optional_selections),v=Gv(Gv(c?.explicit_optional_selections,y),e.optional),C=e.officialPlugins??s?.officialPlugins??Zv(c),M=t.runtime??ys(n),N=await Gh(M,!1,c?.tooling?.context7).then(()=>!0,()=>!1),O,k,I=[...new Set(Ac(oL(x),C).map((A)=>Qn(A)??A))],S;try{S=t.officialPluginManager??await ti.discover({...n,CODEX_HOME:o.codexHome})}catch(A){throw new _("capability_denied","Native Codex plugin installation is unavailable.",A,{recovery:"Install or expose Codex, then retry."})}if(!S.addMarketplace||!S.add||!S.list)throw new _("install_failed","Native Codex plugin installation and verification are unavailable.");let D=c?.install_id??crypto.randomUUID().replaceAll("-",""),P=await vd(),pe=c!==void 0&&c.version!==P&&c.owned_plugins?.includes(un)===!0?new Set([un]):new Set,De=new Set((c?.owned_plugins??[]).filter((A)=>A!==ln)),Rt=new Set([un,...I]),Tt=[...De].filter((A)=>!Rt.has(A));if(Tt.length>0&&S.remove===void 0)throw new _("install_failed","Native Codex cannot remove previously managed plugins omitted from the new selection.",void 0,{plugins:Tt.join(",")});let et=(t.now?.()??new Date).toISOString(),Je=Ld(m,f,{browserUse:x.browser_use,computerUse:x.computer_use,frontend:Pt.frontend,security:Pt.security}),it=await ye(o.configFile),lr;try{lr=Jt(it,o.configFile)}catch(A){if(A instanceof _&&A.code==="state_corrupt")await MK(t,A,o.configFile);throw A}let sa=c?.managed_config??Ph({schema:On,installId:D}),si=await ag(lr,sa),gg=await EK(t,o.configFile,si.document,['plugins."holycodex@holycodex"',"marketplaces.holycodex",...Object.keys(Je)]),{document:tl,conflicts:Hn,decisions:Gd}=gg,yg=Hn.length===0?lr:Xc(lr,Hn,Gd),Rn;if(Hn.length>0){if(await ye(o.configFile)!==it)throw new _("confirmation_required","Codex configuration changed after the invalid-table review; review the latest configuration and retry.",void 0,{path:o.configFile});Rn=fo(yg),await vt(o.configFile,Rn)}let Yd,hR=!1,Zd,gR=new Map;try{Yd=await S.list()}catch(A){if(Rn!==void 0)await zv(o.configFile,it,Rn),Rn=void 0;if(!XK(A))throw new _("capability_denied","Native Codex plugin state could not be read safely.",A);if(await ye(o.configFile)!==it)throw new _("confirmation_required","Codex configuration changed before the required marketplace repair; review the current marketplace source and retry.",A,{path:o.configFile,key:"marketplaces.holycodex"});let L=fe(tl,"marketplaces.holycodex"),G=Hn.some((Be)=>Be.key==="marketplaces"&&Gd.get(Be.identity)==="remove");if(L===void 0&&!G)throw new _("confirmation_required","Codex reported an incomplete marketplace named holycodex, but config.toml does not contain a reviewable marketplace source. Review the source before retrying; no automatic replacement was attempted.",A,{path:o.configFile,key:"marketplaces.holycodex"});if(L!==void 0&&!QK(L))Zd=cr({path:o.configFile,key:"marketplaces.holycodex",action:"replace",category:"config-key",target:"marketplaces.holycodex",existing:L,desired:{source_type:"git",source:ni},explanation:"The existing HolyCodex marketplace source must be reviewed before rebuilding its incomplete cache from the required canonical source.",defaultDecision:"replace",validDecisions:["replace","cancel"]}),gR=(await jd(t,[Zd],!0)).decisions;if(!(ii(L)&&Object.keys(L).length===2&&L.source_type==="git"&&L.source===ni)){if(await ye(o.configFile)!==it)throw new _("confirmation_required","Codex configuration changed before marketplace repair; review the current source and retry.",A,{path:o.configFile,key:"marketplaces.holycodex"});let Be=mo(tl,"marketplaces",_s,{source_type:"git",source:ni});Rn=fo(Be),await vt(o.configFile,Rn)}if(S.addMarketplace===void 0)throw new _("capability_denied","Native Codex plugin state could not be read safely.",A);try{await S.addMarketplace(VF),Yd=await S.list(),hR=!0}catch(Be){if(Rn!==void 0)try{await zv(o.configFile,it,Rn),Rn=void 0}catch(ze){throw new _("confirmation_required","The marketplace repair failed and the reviewed temporary Codex configuration could not be restored safely; review config.toml before retrying.",ze,{path:o.configFile,key:"marketplaces.holycodex"})}throw new _("capability_denied","The required HolyCodex marketplace could not be repaired before plugin validation.",Be)}}if(Rn!==void 0)await zv(o.configFile,it,Rn),Rn=void 0;let yR=I.filter((A)=>{if(!A.endsWith("@openai-curated"))return!1;let L=Lr(Yd,A);return!(L?.installed&&L.enabled)});Fr(t,{stage:"validation",status:"completed",message:"Codex target validated"});let ca=await og(tl),xg=c?.plugin_config?.before??ca,ho=xg,Ts=t.resolveConflicts!==void 0,Cs=[],nl=[],rl=[];if(nl=["preference","marketplace"].filter((L)=>{let G=ca[L].digest,Z=ca[L],Be=L==="preference"?{kind:"boolean",value:!0}:{kind:"marketplace",source_type:"git",source:ni},ze=Z.presence==="present"&&JSON.stringify(Z.safe_value)!==JSON.stringify(Be),ut=c?.plugin_config!==void 0&&G!==c.plugin_config.after[L].digest&&G!==c.plugin_config.before[L].digest;return ze||ut}).map((L)=>{let G=L==="preference"?'plugins."holycodex@holycodex"':"marketplaces.holycodex",Z=ca[L],Be=L==="preference"?{kind:"boolean",value:!0}:{kind:"marketplace",source_type:"git",source:ni};return cr({path:o.configFile,key:G,action:"replace",category:"config-key",target:G,existing:Z.safe_value??{presence:Z.presence},desired:Be,explanation:`The existing ${G} entry does not match the HolyCodex plugin configuration.`,validDecisions:["replace","cancel"],defaultDecision:"replace"})}),Ts)Cs.push(...nl);let Sg=[...new Set([...I,...(c?.provider_config??[]).map((A)=>A.plugin_id),...c?.owned_plugins??[]])].filter((A)=>A!==un&&A!==ln),la=await ig(tl,Sg);{let A=new Set(c?.owned_plugins??[]);if(rl=la.filter((G)=>{let Z=c?.provider_config?.find((ut)=>ut.plugin_id===G.plugin_id),Be=A.has(G.plugin_id)&&Z!==void 0&&G.before.digest!==Z.after.digest&&G.before.digest!==Z.before.digest,ze=I.includes(G.plugin_id)&&G.before.presence==="present"&&G.before.safe_value?.value!==!0;return Be||ze}).map((G)=>{let Z=`plugins."${G.plugin_id}"`;return cr({path:o.configFile,key:Z,action:"replace",category:"config-key",target:Z,existing:G.before.safe_value??{presence:G.before.presence},desired:{kind:"boolean",value:!0},explanation:`The existing provider plugin entry ${G.plugin_id} does not match the selected plugin configuration.`,...I.includes(G.plugin_id)?{validDecisions:["replace","cancel"],defaultDecision:"replace"}:{}})}),Ts)Cs.push(...rl)}let bg=la.map((A)=>{let L=c?.provider_config?.find((G)=>G.plugin_id===A.plugin_id);return L===void 0?A:{plugin_id:A.plugin_id,before:L.before,after:L.before}}),Xd=bg,xR=si.state,SR=await Kv(tl,xR,c),bR=await ag(SR.document,SR.state),wR=await Jv(bR.document,bR.state),{document:Dr,state:ur}=wR;qK(Dr,ur);let ua;if(c!==void 0){ua=Ld(c.profile,c.tier,{browserUse:c.optional_selections.browser_use,computerUse:c.optional_selections.computer_use,frontend:Pt.frontend,security:Pt.security});let A=eh(c.version.split("-",1)[0]);for(let L of Go){let G=c.managed_artifacts.find(({path:Z})=>Z.endsWith(`/${L}.toml`));ua[`agents."${L}".config_file`]=G?.path??`holycodex/agents/${L}.toml`}if(Ec(A,vK)<=0)ua.model="gpt-6-astra",ua.model_reasoning_effort=c.profile==="low"?"low":c.profile==="default"?"medium":"high";else if(c.profile==="high"&&Ec(A,RK)<=0)ua.model_reasoning_effort="high";delete ua.developer_instructions}let wg=await DK(Dr,ur,Je,ua),go;try{go=await Dc(Dr,ur,wg,{schema:On,installId:D})}catch(A){if(A instanceof _)throw A;throw new _("state_corrupt","The existing Codex configuration has an incompatible shape for HolyCodex settings.",A,{recovery:"Converge the conflicting Codex setting, then retry."})}let ci=[];if(go.driftedKeys.length>0)ci=go.driftedKeys.map((A)=>{let L=ur.managed[A],G=fe(Dr,A),Z=Je[A];return cr({path:o.configFile,key:A,action:"replace",category:"config-key",target:A,existing:G??L?.lastManagedValue,desired:Z,explanation:`The managed Codex setting ${A} changed outside the previous transaction.`})});let da=Object.entries(Je).flatMap(([A,L])=>{let G=A;if(ur.managed[G]!==void 0)return[];let Z=fe(Dr,G);if(Z===void 0||JSON.stringify(Z)===JSON.stringify(L))return[];return[cr({path:o.configFile,key:G,action:"replace",category:"config-key",target:G,existing:Z,desired:L,explanation:`The existing Codex setting ${G} is user-owned and differs from the HolyCodex install value.`,defaultDecision:"replace",validDecisions:["keep","replace","cancel"]})]});if(Ts)Cs.push(...da);if(Ts)Cs.push(...ci);let ol;try{ol=await Bh(o.codexHome,m,c?.managed_artifacts,f,{browserUse:x.browser_use,computerUse:x.computer_use})}catch(A){throw new _("install_failed",Ud(A),A)}if(Ts)Cs.push(...ol.map(cr));let Qd=[...Hn,...nl,...rl,...da,...ci,...ol.map(cr)],EL={...go.state.managed},IL=new Set([...Hn.map((A)=>A.identity),...Zd===void 0?[]:[Zd.identity]]),AL=(Ts?Cs:Qd).filter((A)=>!IL.has(A.identity)),_R=await jd(t,AL,!0),qr={..._R,decisions:new Map([...Gd,...gR,..._R.decisions])},vR=[],il={...wg},al=ur.managed,RR=async()=>{vR=ol.map((ze)=>{let ut=cr(ze),tt=qr.decisions.get(ut.identity);return tt===void 0?ut:{...ut,decision:tt}});let A=await zF(Dr,Dr,xg,bg,ca,la,nl,rl,qr.decisions,I),L=Xc(A.document,Hn,qr.decisions);ho=A.pluginConfigBefore,Xd=A.providerConfigBefore;let G={...ur.managed},Z={...wg};for(let ze of[...da,...ci]){let ut=ze.key;if(ut===void 0)continue;let tt=ut,pa=qr.decisions.get(ze.identity);if(pa!=="keep"&&pa!=="replace")throw new _("confirmation_required","Managed conflict resolution is incomplete.",void 0,{key:ut});let qt=G[tt],li=Je[tt];if(li===void 0)throw new _("state_corrupt","The managed conflict cannot be verified.",void 0,{path:o.configFile,key:ut});let dr=fe(Dr,tt);if(pa==="replace")if(L=so(L,tt,li),qt!==void 0)G[tt]={...qt,lastManagedValue:await _n(tt,li)};else{let $r=EL[tt];if($r!==void 0)G[tt]=$r}else{if(delete Z[tt],qt===void 0)continue;if(dr===void 0){delete G[tt];continue}let $r={...qt,lastManagedValue:await _n(tt,dr)},np={...ur,managed:{...G,[tt]:$r}};if(Yi(np))G[tt]=$r;else delete G[tt]}}if(go=await Dc(L,{...ur,managed:G},Z,{schema:On,installId:D}),go.driftedKeys.length>0)throw new _("state_corrupt","The accepted managed conflicts did not converge.");il=Z;let Be={...ur.managed};for(let ze of[...da,...ci]){let ut=ze.key;if(ut===void 0)continue;delete Be[ut]}al=Be};await RR();let TR=()=>Qd.map((A)=>{let L=cr(A),G=qr.decisions.get(L.identity);return G===void 0?L:{...L,decision:G}}),CR=(A)=>Object.fromEntries(["config-key","invalid-config","native-plugin","role-asset"].flatMap((L)=>{let G=A.filter((Z)=>Z.category===L).length;return G===0?[]:[[L,G]]})),ep=TR(),OR=CR(ep),PL=eJ(N,Yd,I);if(t.reviewInstall!==void 0)while(!0){let A=await t.reviewInstall({operation:c===void 0?"install":"upgrade",...c===void 0?{}:{fromVersion:c.version},toVersion:P,profile:m,tier:f,capabilities:{browser_use:x.browser_use,computer_use:x.computer_use,sites:x.sites},additionalPlugins:[...C],conflicts:ep,conflictCounts:OR,tools:PL});if(A.action==="cancel")throw new _("confirmation_required","Install review was cancelled.");if(A.action==="resolve"){if(Qd.length===0)throw new _("confirmation_required","There are no managed conflicts to resolve.");qr=await jd(t,Qd,!0),await RR(),ep=TR(),OR=CR(ep);continue}if(A.action==="change"){if(A.request===void 0)throw new _("confirmation_required","Changing install options requires a revised request.");return await Ss(A.request,t,n)}if(A.action==="apply")break;throw new _("confirmation_required","Unknown install review action.")}let _g={owner:"holycodex",schema_epoch:On,install_id:D,version:P,digest:c?.digest??"0".repeat(64),profile:m,tier:f,optional_selections:x,explicit_optional_selections:v,official_plugins:I,capability_state:cg(x),managed_artifacts:c?.managed_artifacts??[],installed_at:et,status:"preparing",step:"validated",managed_config:xR,plugin_snapshot:[],plugin_config:{plugin_id:un,before:ho,after:ho},provider_config:Xd,owned_plugins:[...De],...c?.tooling?.context7===void 0?{}:{tooling:{context7:c.tooling.context7}}};await $c(o.stateRoot),await sr(o.preparingRecord,_g);let sl=[],yo,vg=!1,kR=!1,ER=new Set,Rg=new Set,tp=new Set,Tn=new Set(De),Tg=new Set([...De,...I]),Cg=new Set,ge=_g,IR=!1,Ur,Og,cl=go.state,AR=!1,PR=!1;try{if(Hn.length>0){let X=await ye(o.configFile);if(yg=Xc(Jt(X,o.configFile),Hn,Gd),await ye(o.configFile)!==X)throw new _("confirmation_required","Codex configuration changed during conflict resolution; review the latest configuration and retry.",void 0,{path:o.configFile});await vt(o.configFile,fo(yg)),kR=!0}try{O=await Gh(M,!0,c?.tooling?.context7)}catch(X){k=`Optional ctx7 is unavailable: ${Ud(X)}`}let A=O??c?.tooling?.context7,L=A===void 0?void 0:{context7:A},G={..._g,...L===void 0?{}:{tooling:L}};if(ge=G,await sr(o.preparingRecord,ge),S.ensureOfficialMarketplace!==void 0&&yR.length>0)try{await S.ensureOfficialMarketplace(yR)}catch(X){throw new _("capability_denied",`The selected official Codex provider marketplace is unavailable: ${Ud(X)}`,X,{recovery:"Check Codex network and marketplace policy, then retry."})}try{sl=await UK({list:()=>S.list()},[...new Set([un,...I,...De])])}catch(X){throw new _("capability_denied","Native Codex plugin state could not be read safely.",X)}G={...G,plugin_snapshot:sl},ge=G,await sr(o.preparingRecord,ge);let Z=await ye(o.configFile),Be=Jt(Z,o.configFile),ze=Xc(Be,Hn,qr.decisions);await LK(ze,ca,la);let ut=await Kv(ze,sa,c),tt=await ag(ut.document,ut.state);Ur=(await Jv(tt.document,tt.state)).document,await JF(Ur,Dr,{...ur,managed:al},il),Fr(t,{stage:"roles",status:"started",message:"Installing subagent roles"}),await $c(o.roleRoot),yo=await Ov(o.codexHome,m,c?.managed_artifacts,f,ol.length===0?t.resolveConflict:void 0,vR,{browserUse:x.browser_use,computerUse:x.computer_use}),ge={...G,step:"roles_prepared",managed_artifacts:yo.managed_artifacts},await sr(o.preparingRecord,ge),Fr(t,{stage:"roles",status:"completed",message:"Subagent roles installed"}),Fr(t,{stage:"plugins",status:"started",message:"Installing selected capabilities"}),IR=!0;let qt=Ur;if(qt===void 0)throw new _("state_corrupt","The pre-mutation configuration baseline is missing.");qt=mo(qt,"plugins",ws,{enabled:!0}),qt=mo(qt,"marketplaces",_s,{source_type:"git",source:ni});for(let X of I)qt=mo(qt,"plugins",X,{enabled:!0});let li=await og(qt),$r=(await ig(qt,Sg)).map((X)=>({plugin_id:X.plugin_id,before:la.find((Pe)=>Pe.plugin_id===X.plugin_id)?.before??X.before,after:X.before}));if(ge={...ge,plugin_config:{plugin_id:un,before:ho,after:li},provider_config:$r},await sr(o.preparingRecord,ge),it===void 0)try{Og=await VK(o.configFile);let X=await ye(o.configFile);if(Og===void 0||X!=="")throw new _("confirmation_required","Codex config.toml appeared during installation; review the latest configuration and retry.",void 0,{operation:"initialize Codex configuration",path:o.configFile});Z=""}catch(X){if(X instanceof _)throw X;throw new _("permission_denied","Codex config.toml could not be initialized before plugin setup.",X,{operation:"initialize Codex configuration",path:o.configFile,recovery:"Check CODEX_HOME permissions, then retry."})}if(await ye(o.configFile)!==Z)throw new _("confirmation_required","Codex configuration changed during plugin setup; review the latest configuration and retry.",void 0,{path:o.configFile});if(await vt(o.configFile,fo(qt)),vg=!0,!hR)await S.addMarketplace(VF);await zK({list:()=>S.list(),add:(X)=>S.add(X)},[un,...I],pe,async(X,Pe)=>{if(Pe==="new")ER.add(X),Tn.add(X),Tg.add(X),ge={...ge,owned_plugins:[...Tn]};else Cg.add(X),Tn.add(X),Tg.add(X),ge={...ge,owned_plugins:[...Tn]};await sr(o.preparingRecord,ge)}),ge={...ge,step:"plugins_installed"},await sr(o.preparingRecord,ge),Fr(t,{stage:"plugins",status:"completed",message:"Selected capabilities installed"});let MR=await ye(o.configFile),ML=Jt(MR,o.configFile),NL=Xc(ML,Hn,qr.decisions),NR=await Kv(NL,sa,c),FR=await ag(NR.document,NR.state),FL=await Jv(FR.document,FR.state);if(Ur===void 0)throw new _("state_corrupt","The pre-mutation configuration baseline is missing.");let kg=await zF(FL.document,Ur,xg,bg,ca,la,nl,rl,qr.decisions,I),xo=kg.document;for(let X of Object.keys(al)){let Pe=X,Cn=fe(Ur,Pe);xo=Cn===void 0?tr(xo,Pe):so(xo,Pe,Cn)}ho=kg.pluginConfigBefore,Xd=kg.providerConfigBefore;let rp=await og(xo),LR=await ig(xo,Sg),DR=LR.map((X)=>({plugin_id:X.plugin_id,before:Xd.find((Pe)=>Pe.plugin_id===X.plugin_id)?.before??X.before,after:X.before})),qR=LR.map((X)=>({plugin_id:X.plugin_id,before:la.find((Pe)=>Pe.plugin_id===X.plugin_id)?.before??X.before,after:X.before}));ge={...ge,plugin_config:{plugin_id:un,before:ho,after:rp},provider_config:qR};let LL=new Set([...da,...ci].flatMap((X)=>X.key===void 0?[]:[X.key])),op={...al};for(let X of[...da,...ci]){let Pe=X.key;if(Pe===void 0)continue;let Cn=go.state.managed[Pe];if(Cn!==void 0)op[Pe]=Cn}for(let[X,Pe]of Object.entries(op)){if(LL.has(X))continue;let Cn=X,ll=fe(Ur,Cn);op[Cn]={...Pe,...ll===void 0?{}:{lastManagedValue:await _n(Cn,ll)}}}let UR={...go.state,managed:op};await JF(xo,Ur,{...UR,managed:al},il);for(let X of[...da,...ci]){let Pe=X.key;if(Pe===void 0)continue;let ll=qr.decisions.get(X.identity)==="replace"?Je[Pe]:fe(Dr,Pe);if(ll!==void 0)xo=so(xo,Pe,ll)}let ip=await Dc(xo,UR,il,{schema:On,installId:D});if(ip.driftedKeys.length>0)throw new _("state_corrupt","HolyCodex-owned Codex settings changed during native plugin setup.",void 0,{keys:ip.driftedKeys.join(",")});if(Fr(t,{stage:"config",status:"started",message:"Configuring Root"}),cl=ip.state,ge={...ge,managed_config:cl,plugin_config:{plugin_id:un,before:ho,after:rp},provider_config:qR},await ye(o.configFile)!==MR)throw new _("confirmation_required","Codex configuration changed during plugin setup; review the latest configuration and retry.",void 0,{path:o.configFile});if(await vt(o.configFile,fo(ip.document)),vg=!0,ge={...ge,step:"config_published"},await sr(o.preparingRecord,ge),Tt.length>0)await KK({list:()=>S.list(),remove:(Pe)=>S.remove(Pe)},Tt,async(Pe,Cn)=>{if(Cn==="removed")Rg.add(Pe),Tn.delete(Pe);else if(Cn==="absent")Tn.delete(Pe);else tp.add(Pe);ge={...ge,owned_plugins:[...Tn]},await sr(o.preparingRecord,ge)});Fr(t,{stage:"config",status:"completed",message:"Root configuration published"}),Fr(t,{stage:"verification",status:"started",message:"Verifying installation"}),await jK(o,m,f,{browserUse:x.browser_use,computerUse:x.computer_use,frontend:Pt.frontend,security:Pt.security},cl,yo.preserved,il),Fr(t,{stage:"verification",status:"completed",message:"Installation verified"});let $R=cg(x),DL=await lg({owner:"holycodex",install_id:D,version:P,profile:m,tier:f,optional_selections:x,explicit_optional_selections:v,official_plugins:I,capability_state:$R,managed_artifacts:yo.managed_artifacts,managed_config:cl,plugin_config:{plugin_id:un,before:ho,after:rp},provider_config:DR,plugin_snapshot:sl,owned_plugins:[...Tn],...L===void 0?{}:{tooling:L}}),Eg={owner:"holycodex",schema_epoch:On,install_id:D,version:P,digest:DL,profile:m,tier:f,optional_selections:x,explicit_optional_selections:v,official_plugins:I,capability_state:$R,managed_artifacts:yo.managed_artifacts,installed_at:et,status:"active",step:"active",managed_config:cl,plugin_snapshot:sl,plugin_config:{plugin_id:un,before:ho,after:rp},provider_config:DR,owned_plugins:[...Tn],...L===void 0?{}:{tooling:L}};if(Ie(Uc,Eg)===void 0)throw new _("state_corrupt","The HolyCodex configuration is invalid.");return AR=!0,await jc(o.activeRecord,sn(Eg)),PR=!0,await eL(o,nL(m,f,x,C)),await sg(o.preparingRecord),await sg(o.conflictedRecord),Fr(t,{stage:"complete",status:"completed",message:"HolyCodex installation complete"}),{record:Eg,optional_plugins:I,preserved:yo.preserved,warnings:[...yo.preserved.length===0?[]:["modified managed files were preserved"],...k===void 0?[]:[k]]}}catch(A){let L=[],G;if(AR)try{if(l===void 0)await $d(o.activeRecord,{force:!1}).catch((Z)=>{if(!We(Z,"ENOENT"))throw Z});else await vt(o.activeRecord,l)}catch{L.push("active_record")}if(PR)try{if(i===void 0)await $d(o.installOptions,{force:!1}).catch((Z)=>{if(!We(Z,"ENOENT"))throw Z});else await vt(o.installOptions,i)}catch{L.push("install_options")}if(IR||vg)try{if(Ur!==void 0)G=await $K(o.configFile,ge,Ur,Tg)}catch{L.push("config")}if(kR)try{await IK(o.configFile,Hn)}catch{L.push("invalid_config")}if(yo!==void 0)try{if((await Vh(yo.rollback)).preserved.length>0)L.push("roles")}catch{L.push("roles")}if(Cg.size>0)L.push(...[...Cg].map((Z)=>`plugin:${Z}`));for(let Z of ER)try{await S.remove?.(Z)}catch{L.push(`plugin:${Z}`)}for(let Z of new Set([...Rg,...tp]))try{await JK({list:()=>S.list(),add:(Be)=>S.add(Be)},Z,sl.find((Be)=>Be.plugin_id===Z)?.status),Rg.delete(Z),tp.delete(Z),Tn.add(Z),ge={...ge,owned_plugins:[...Tn]},await sr(o.preparingRecord,ge)}catch{Tn.add(Z),tp.add(Z),ge={...ge,owned_plugins:[...Tn]},await sr(o.preparingRecord,ge).catch(()=>{return}),L.push(`plugin:${Z}`)}if(O?.ownership==="holycodex"&&c?.tooling?.context7?.ownership!=="holycodex")try{if(!await Pd(M,O))L.push("context7")}catch{L.push("context7")}if(L.length===0&&it===void 0)try{if((await ye(o.configFile))?.trim().length===0&&await WK(o.configFile,G??Og))await $d(o.configFile,{force:!1})}catch{L.push("config_initialization")}if(L.length>0){try{let Be=Jt(await ye(o.configFile),o.configFile),ze=ge.plugin_config,ut=await og(Be),tt=ze===void 0?void 0:{...ze,after:{preference:ut.preference.digest===ze.before.preference.digest?ze.before.preference:ze.after.preference,marketplace:ut.marketplace.digest===ze.before.marketplace.digest?ze.before.marketplace:ze.after.marketplace}},pa=ge.provider_config,qt=await ig(Be,pa?.map((dr)=>dr.plugin_id)??[]),li=pa?.map((dr)=>{let $r=qt.find((np)=>np.plugin_id===dr.plugin_id);return $r!==void 0&&$r.before.digest===dr.before.digest?{...dr,after:dr.before}:dr});ge={...ge,...tt===void 0?{}:{plugin_config:tt},...li===void 0?{}:{provider_config:li}}}catch{}let Z=!1;try{await sr(o.conflictedRecord,{...ge,step:"conflicted",status:"conflicted"}),Z=!0}catch{}if(Z)await sg(o.preparingRecord).catch(()=>{return})}else await sg(o.preparingRecord).catch(()=>{return});if(A instanceof nr)throw A;if(A instanceof _)throw A;throw new _(A instanceof uo||A instanceof oi?"capability_denied":"install_failed",Ud(A),A,L.length>0?{recovery:"Resolve conflicted state before retrying."}:{})}}async function oa(e){let t=await wv(e.activeRecord,gd);if(t===void 0)return;let n=t.optional_selections,o=typeof n==="object"&&n!==null&&!Array.isArray(n)&&Object.prototype.hasOwnProperty.call(n,"work")?void 0:Ie(Uc,t);if(o!==void 0){if(!await bs(o))throw new _("state_corrupt","The existing HolyCodex configuration has an invalid digest.");return await _d(e.activeRecord,t),o}let i=Ie(oF,t);if(i===void 0)throw new _("state_corrupt","The HolyCodex configuration is invalid.");if(!await iL(i))throw new _("state_corrupt","The existing HolyCodex configuration has an invalid digest.",void 0,{path:e.activeRecord});let a="profile"in i&&i.profile!==void 0?i.profile:("plan"in i)?i.plan:void 0;if(a===void 0)throw new _("state_corrupt","The persisted installation has neither profile nor legacy plan state.",void 0,{path:e.activeRecord});let s;try{s=ah(a)}catch(P){throw new _("state_corrupt",`The persisted profile ${a} was removed and requires an explicit replacement.`,P,{path:e.activeRecord,profile:a})}let c="plan"in i?Object.fromEntries(Object.entries(i).filter(([P])=>P!=="plan")):i,{optional_selections:l,explicit_optional_selections:u}=i,d={browser_use:l.browser_use??en.browser_use,computer_use:l.computer_use,sites:l.sites??en.sites,coding:!0},p={...u.computer_use===void 0?{}:{computer_use:u.computer_use},...u.browser_use===void 0?{}:{browser_use:u.browser_use},...u.sites===void 0?{}:{sites:u.sites}},m=i.capability_state===void 0?void 0:cg(d,new Map([["browser_use","missing"],["sites","missing"]])),f=(i.official_plugins??[]).filter((P)=>!qd(P)),y=i.owned_plugins?.filter((P)=>!qd(P)),g=i.provider_config?.filter((P)=>!qd(P.plugin_id)),x=i.plugin_snapshot?.filter((P)=>!qd(P.plugin_id)),{optional_selections:v,explicit_optional_selections:C,capability_state:M,official_plugins:N,owned_plugins:O,provider_config:k,plugin_snapshot:I,...S}=c,D={...S,profile:s,optional_selections:d,explicit_optional_selections:p,official_plugins:f,...m===void 0?{}:{capability_state:m},...y===void 0?{}:{owned_plugins:y},...g===void 0?{}:{provider_config:g},...x===void 0?{}:{plugin_snapshot:x},digest:await lg({owner:i.owner,install_id:i.install_id,version:i.version,profile:s,tier:i.tier,optional_selections:d,explicit_optional_selections:p,official_plugins:f,capability_state:m??null,managed_artifacts:i.managed_artifacts,...i.managed_config===void 0?{}:{managed_config:i.managed_config},...i.plugin_config===void 0?{}:{plugin_config:i.plugin_config},...g===void 0?{}:{provider_config:g},...x===void 0?{}:{plugin_snapshot:x},...y===void 0?{}:{owned_plugins:y},...i.tooling===void 0?{}:{tooling:i.tooling}})};return ZF.set(D,i.digest),await _d(e.activeRecord,t),D}async function Nr(e,t){let n=await wv(e,gd);if(n===void 0)return;let r=Ie(ta,n);if(r!==void 0)return await _d(e,n),r;let o=Ie(sF,n);if(o===void 0)throw new _("state_corrupt","The HolyCodex transaction state is invalid.",void 0,{path:e});let i=o,a=i.profile??i.plan;if(typeof a!=="string")throw new _("state_corrupt","The HolyCodex transaction has no profile.",void 0,{path:e});let s;try{s=ah(a)}catch(S){throw new _("state_corrupt","The persisted transaction profile requires an explicit replacement.",S,{path:e,profile:a})}let{optional_selections:c,explicit_optional_selections:l}=i,u={browser_use:c.browser_use??en.browser_use,computer_use:c.computer_use??!1,sites:c.sites??en.sites,coding:!0},d={...l.browser_use===void 0?{}:{browser_use:l.browser_use},...l.computer_use===void 0?{}:{computer_use:l.computer_use},...l.sites===void 0?{}:{sites:l.sites}},m=i.capability_state===void 0?void 0:cg(u,new Map([["browser_use","missing"],["sites","missing"]])),{plan:f,profile:y,optional_selections:g,explicit_optional_selections:x,capability_state:v,...C}=i,M=typeof C.digest==="string"?C.digest:void 0,N=t===void 0?void 0:ZF.get(t),O=t!==void 0&&C.install_id===t.install_id&&(M===t.digest||N!==void 0&&M===N)?t.digest:M,k={...C,profile:s,optional_selections:u,explicit_optional_selections:d,...m===void 0?{}:{capability_state:m},...O===void 0?{}:{digest:O}},I=Ie(ta,k);if(I===void 0)throw new _("state_corrupt","The migrated transaction state is invalid.",void 0,{path:e});return await _d(e,n),I}function oL(e){return{browser_use:e.browser_use,computer_use:e.computer_use,sites:e.sites}}function Jt(e,t="config.toml"){if(e===void 0||e.trim().length===0)return{};try{let n=globalThis.Bun,r=n?.TOML?.parse?n.TOML.parse(e):bd(e),o=Ie(os,r);if(o===void 0){let i=Yv(r),a=i===void 0?"an unsupported TOML value":`the TOML value ${i}`;throw new _("state_corrupt",`${t} contains ${a} that HolyCodex cannot preserve. Convert it to a string, number, boolean, table, or array, then retry.`,void 0,{path:t,...i===void 0?{}:{key:i},reason:"unsupported_toml_value"})}return o}catch(n){if(n instanceof _)throw n;let r=Ud(n),o=AK(e,r),i=o===void 0?`${t} contains invalid TOML: ${r}. Fix the TOML syntax and retry; HolyCodex cannot safely rewrite malformed TOML.`:`${t} contains invalid TOML at line ${o.line}, column ${o.column} (offset ${o.offset}): ${r}. Fix the syntax at that location and retry; HolyCodex cannot safely rewrite malformed TOML.`;throw new _("state_corrupt",i,n,{path:t,parser_message:r,...o===void 0?{}:o,reason:"invalid_toml_syntax"})}}function Yv(e,t=[]){if(e===null||typeof e==="string"||typeof e==="boolean")return;if(typeof e==="number")return Number.isFinite(e)?void 0:Wv(t);if(Array.isArray(e)){for(let[n,r]of e.entries()){let o=Yv(r,[...t,"["+n+"]"]);if(o!==void 0)return o}return}if(typeof e==="object"&&e!==null){let n=Object.getPrototypeOf(e);if(n!==Object.prototype&&n!==null)return Wv(t);for(let[r,o]of Object.entries(e)){let i=Yv(o,[...t,r]);if(i!==void 0)return i}return}return Wv(t)}function Wv(e){return e.length===0?"<root>":e.join(".")}function CK(e,t){let n=new Map;for(let r of t)for(let o of OK(r)){let i=fe(e,o);if(i!==void 0&&!ii(i))n.set(o,i)}return[...n].map(([r,o])=>({key:r,value:o}))}function OK(e){let t=[],n=!1,r=!1;for(let o=0;o<e.length;o+=1){let i=e[o];if(n){if(r)r=!1;else if(i==="\\")r=!0;else if(i==='"')n=!1;continue}if(i==='"')n=!0;else if(i===".")t.push(e.slice(0,o))}return t}function kK(e,t){let n=JSON.stringify(t.value);return new _("state_corrupt",`${e} has the non-table value ${n} at ${t.key}, but the HolyCodex installer needs that path to be a table. Remove it after review or convert it to a table and retry; replacing it automatically could discard user configuration.`,void 0,{path:e,key:t.key,existing:n,reason:"expected_table"})}async function EK(e,t,n,r){let o=CK(n,r).map((a)=>{let s=kK(t,a);return cr({identity:`invalid-config:${t}:${a.key}`,category:"invalid-config",target:a.key,existing:a.value,desired:`Remove the conflicting value at ${a.key} so HolyCodex can create the required table.`,explanation:`${s.message} Choose remove to continue or cancel to repair it manually.`,path:t,key:a.key,action:"remove",defaultDecision:"remove",validDecisions:["remove","cancel"]})});if(o.length===0)return{document:n,conflicts:o,decisions:new Map};let i=await jd(e,o,!0);return{document:Xc(n,o,i.decisions),conflicts:o,decisions:i.decisions}}function Xc(e,t,n){let r=e;for(let o of t){if(n.get(o.identity)!=="remove"||o.key===void 0)throw new _("confirmation_required",`Invalid configuration at ${o.target} can only be removed after review or cancelled.`,void 0,{path:o.path,...o.key===void 0?{}:{key:o.key},existing:JSON.stringify(o.existing),valid_decisions:o.validDecisions??["remove","cancel"]});let a=fe(r,o.key);if(a===void 0)continue;if(JSON.stringify(a)!==JSON.stringify(o.existing))throw new _("confirmation_required",`Invalid configuration at ${o.key} changed after review; review the current value and retry.`,void 0,{path:o.path,key:o.key,reviewed:JSON.stringify(o.existing),current:JSON.stringify(a)});r=tr(r,o.key)}return r}async function zv(e,t,n){if(await ye(e)!==n)throw new _("confirmation_required","Codex configuration changed during preflight validation; review the latest configuration and retry.",void 0,{path:e});if(t===void 0){await $d(e,{force:!1}).catch((r)=>{if(!We(r,"ENOENT"))throw r});return}await vt(e,t)}async function IK(e,t){let n=await ye(e),r=Jt(n,e),o=r;for(let i of t){if(i.key===void 0||i.existing===void 0)continue;let a=fe(o,i.key);if(a!==void 0){if(JSON.stringify(a)===JSON.stringify(i.existing))continue;if(!(typeof a==="object"&&a!==null&&!Array.isArray(a)&&Object.keys(a).length===0))throw new _("confirmation_required",`Codex configuration at ${i.key} changed during rollback; preserve it and review the current value.`,void 0,{path:e,key:i.key});o=tr(o,i.key)}o=so(o,i.key,i.existing)}if(o===r)return;if(await ye(e)!==n)throw new _("confirmation_required","Codex configuration changed during rollback; preserve it and review the current value.",void 0,{path:e});await vt(e,fo(o))}function AK(e,t){let n,r=/found \(0x([0-9a-f]{2})\)/iu.exec(t),o=/found '((?:\\.|[^'])*)'/u.exec(t),i=r===null?o?.[1]?.replaceAll("\\'","'").replaceAll("\\\"",'"'):String.fromCharCode(Number.parseInt(r[1],16));if(i!==void 0)n=PK(e,i);else if(/end of file|unterminated/iu.test(t))n=e.length;else if(/missing value after/iu.test(t)){let c=e.lastIndexOf("="),l=c<0?-1:e.indexOf(`
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "holycodex",
|
|
3
|
-
"version": "0.16.10-dev.
|
|
3
|
+
"version": "0.16.10-dev.116.1",
|
|
4
4
|
"bin": {
|
|
5
5
|
"holycodex": "./dist/index.js",
|
|
6
6
|
"holycodex-agent": "./dist/agent.js"
|
|
@@ -25,6 +25,6 @@
|
|
|
25
25
|
"release": {
|
|
26
26
|
"schemaVersion": "holycodex-release-v1",
|
|
27
27
|
"channel": "dev",
|
|
28
|
-
"sourceSha": "
|
|
28
|
+
"sourceSha": "377022d05fb7db4a17ac630f27e87e09b71f465e"
|
|
29
29
|
}
|
|
30
30
|
}
|