@cortexkit/opencode-openai-auth 1.9.3 → 1.9.4

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/bin.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{c as s0}from"./index-2dwy4yab.js";import{Aa as y0,Ba as f,Ca as F,Da as E,Hb as i0,Tb as n0,na as p0,oa as S,pa as g,pb as a0,qa as m0}from"./index-3sda8acd.js";import{Bd as O0,Dd as d,Ed as w,Fd as u0,Gd as u,Hd as M0,vd as c0}from"./index-6xz3n4qh.js";import"./index-81yvwra9.js";import"./index-ezwfbnx5.js";import"./index-2esezxst.js";import{ff as q0,lf as Q0,nf as K0,qf as l0}from"./index-cmybrjbd.js";import"./index-hz6f9gpq.js";import"./index-g3gbp1m4.js";import"./index-v1ztg103.js";import{spawn as t0}from"node:child_process";var N=4096,e0=1048576;class b0{buffer=Buffer.alloc(N);start=0;length=0;truncated=!1;get didTruncate(){return this.truncated}push(z){if(z.length>=N){if(z.length>N||this.length>0)this.truncated=!0;z.copy(this.buffer,0,z.length-N),this.start=0,this.length=N;return}let J=Math.max(0,this.length+z.length-N);if(J>0)this.truncated=!0;this.start=(this.start+J)%N,this.length-=J;let Z=(this.start+this.length)%N,$=Math.min(z.length,N-Z);if(z.copy(this.buffer,Z,0,$),$<z.length)z.copy(this.buffer,0,$);this.length+=z.length}toString(){let z=Buffer.alloc(this.length),J=Math.min(this.length,N-this.start);if(this.buffer.copy(z,0,this.start,this.start+J),J<this.length)this.buffer.copy(z,J,0,this.length-J);let Z=0;while(Z<z.length){let $=z[Z];if($===void 0||($&192)!==128)break;Z++}return z.subarray(Z).toString("utf8")}}var _={run(z,J,Z={}){return new Promise(($)=>{let G=performance.now(),Q=Z.timeoutMs??15000,K=new b0,W=[],V=0,q=!1,j=!1,D=!1,Y;try{Y=t0(z,[...J],{env:Z.env??process.env,windowsHide:!0,windowsVerbatimArguments:Z.windowsVerbatimArguments,stdio:["ignore","pipe","pipe"]})}catch{$({exitCode:1,stdout:"",stderr:"",spawnError:!0,signal:null,timedOut:!1,durationMs:performance.now()-G});return}let X=Q>0?setTimeout(()=>{D=!0,Y.kill("SIGTERM")},Q):void 0;Y.stdout?.on("data",(U)=>{let C=e0-V,b=Math.min(C,U.length);if(b>0)W.push(U.subarray(0,b)),V+=b;if(U.length>C)q=!0,Y.kill("SIGTERM")}),Y.stderr?.on("data",(U)=>K.push(U));let B=!1,x=(U,C)=>{if(B)return;if(B=!0,X)clearTimeout(X);$({exitCode:j?1:q?1:U??1,stdout:Buffer.concat(W,V).toString("utf8"),stderr:K.toString(),stderrTruncated:K.didTruncate,...j?{spawnError:!0}:{},signal:C??null,timedOut:D,durationMs:performance.now()-G})};Y.once("error",()=>{if(j=!0,Y.pid===void 0)x(null,null)}),Y.once("close",(U,C)=>x(U,C))})}};function m(z,J,Z,$,G,Q=15000){if(J==="win32"&&/\.(cmd|bat)$/i.test(Z)){if(/["%!\r\n]/.test(Z)||$.some((K)=>!/^[a-zA-Z0-9@:/._+-]+$/.test(K)))throw Error("Unsafe batch launcher or argument; use an executable instead.");return z.run("cmd.exe",["/d","/s","/c",`""${Z}" ${$.join(" ")}"`],{env:G,timeoutMs:Q,windowsVerbatimArguments:!0})}return z.run(Z,$,{env:G,timeoutMs:Q})}var z2="Pi install failed; run pi install after checking your npm connection.";function J2(z){let J=Buffer.from(z,"utf8");if(J.length<=N)return z;let Z=J.length-N;while(Z<J.length){let $=J[Z];if($===void 0||($&192)!==128)break;Z++}return J.subarray(Z).toString("utf8")}function Z2(z){let J=z.indexOf(`
2
+ import{c as s0}from"./index-jej9cfk7.js";import{Aa as y0,Ba as f,Ca as F,Da as E,Hb as i0,Tb as n0,na as p0,oa as S,pa as g,pb as a0,qa as m0}from"./index-xx3k2qbv.js";import{Bd as O0,Dd as d,Ed as w,Fd as u0,Gd as u,Hd as M0,vd as c0}from"./index-6xz3n4qh.js";import"./index-81yvwra9.js";import"./index-rrtsaz80.js";import"./index-2esezxst.js";import{ff as q0,lf as Q0,nf as K0,qf as l0}from"./index-cmybrjbd.js";import"./index-hz6f9gpq.js";import"./index-g3gbp1m4.js";import"./index-v1ztg103.js";import{spawn as t0}from"node:child_process";var N=4096,e0=1048576;class b0{buffer=Buffer.alloc(N);start=0;length=0;truncated=!1;get didTruncate(){return this.truncated}push(z){if(z.length>=N){if(z.length>N||this.length>0)this.truncated=!0;z.copy(this.buffer,0,z.length-N),this.start=0,this.length=N;return}let J=Math.max(0,this.length+z.length-N);if(J>0)this.truncated=!0;this.start=(this.start+J)%N,this.length-=J;let Z=(this.start+this.length)%N,$=Math.min(z.length,N-Z);if(z.copy(this.buffer,Z,0,$),$<z.length)z.copy(this.buffer,0,$);this.length+=z.length}toString(){let z=Buffer.alloc(this.length),J=Math.min(this.length,N-this.start);if(this.buffer.copy(z,0,this.start,this.start+J),J<this.length)this.buffer.copy(z,J,0,this.length-J);let Z=0;while(Z<z.length){let $=z[Z];if($===void 0||($&192)!==128)break;Z++}return z.subarray(Z).toString("utf8")}}var _={run(z,J,Z={}){return new Promise(($)=>{let G=performance.now(),Q=Z.timeoutMs??15000,K=new b0,W=[],V=0,q=!1,j=!1,D=!1,Y;try{Y=t0(z,[...J],{env:Z.env??process.env,windowsHide:!0,windowsVerbatimArguments:Z.windowsVerbatimArguments,stdio:["ignore","pipe","pipe"]})}catch{$({exitCode:1,stdout:"",stderr:"",spawnError:!0,signal:null,timedOut:!1,durationMs:performance.now()-G});return}let X=Q>0?setTimeout(()=>{D=!0,Y.kill("SIGTERM")},Q):void 0;Y.stdout?.on("data",(U)=>{let C=e0-V,b=Math.min(C,U.length);if(b>0)W.push(U.subarray(0,b)),V+=b;if(U.length>C)q=!0,Y.kill("SIGTERM")}),Y.stderr?.on("data",(U)=>K.push(U));let B=!1,x=(U,C)=>{if(B)return;if(B=!0,X)clearTimeout(X);$({exitCode:j?1:q?1:U??1,stdout:Buffer.concat(W,V).toString("utf8"),stderr:K.toString(),stderrTruncated:K.didTruncate,...j?{spawnError:!0}:{},signal:C??null,timedOut:D,durationMs:performance.now()-G})};Y.once("error",()=>{if(j=!0,Y.pid===void 0)x(null,null)}),Y.once("close",(U,C)=>x(U,C))})}};function m(z,J,Z,$,G,Q=15000){if(J==="win32"&&/\.(cmd|bat)$/i.test(Z)){if(/["%!\r\n]/.test(Z)||$.some((K)=>!/^[a-zA-Z0-9@:/._+-]+$/.test(K)))throw Error("Unsafe batch launcher or argument; use an executable instead.");return z.run("cmd.exe",["/d","/s","/c",`""${Z}" ${$.join(" ")}"`],{env:G,timeoutMs:Q,windowsVerbatimArguments:!0})}return z.run(Z,$,{env:G,timeoutMs:Q})}var z2="Pi install failed; run pi install after checking your npm connection.";function J2(z){let J=Buffer.from(z,"utf8");if(J.length<=N)return z;let Z=J.length-N;while(Z<J.length){let $=J[Z];if($===void 0||($&192)!==128)break;Z++}return J.subarray(Z).toString("utf8")}function Z2(z){let J=z.indexOf(`
3
3
  `);return J<0?"":z.slice(J+1)}class h extends Error{step="pi-install";exitCode;signal;stderrTail;constructor(z){super(z2);this.name="SetupCommandError",this.exitCode=z.exitCode,this.signal=z.signal;let J=z.stderrTruncated?Z2(z.stderrTail):z.stderrTail,Z=q0(J);this.stderrTail=J2(typeof Z==="string"?Z:"")}}var $2={opencode:"OpenCode",pi:"Pi"},G2={enrolled:"connected to the vault","not-enrolled":"not connected",unknown:"unknown, check with ck auth status"};function X0({host:z,outcome:J}){return`${$2[z]}: ${G2[J]}`}var Q2=new WeakMap;function W0(z,J){if(typeof z!=="object"&&typeof z!=="function"||!z)return;Q2.set(z,Object.freeze(J.map((Z)=>Object.freeze({...Z}))))}import{accessSync as W2,constants as V2,existsSync as D2,readFileSync as j2,realpathSync as Y2,statSync as B2}from"node:fs";import{mkdtemp as U2,rm as F2}from"node:fs/promises";import{tmpdir as x2}from"node:os";import{join as H2}from"node:path";import{parse as O2}from"jsonc-parser";import{homedir as K2}from"node:os";import{posix as b2,win32 as q2}from"node:path";import{fileURLToPath as X2}from"node:url";function k(z={}){let J=z.env??process.env,Z=z.platform??process.platform,$=Z==="win32"?q2:b2,G=z.home??(Z==="win32"?J.USERPROFILE:J.HOME)??K2(),Q=z.cwd??process.cwd(),K=(j)=>$.resolve(Q,j),W=J.OPENCODE_CONFIG_DIR?.trim(),V=J.XDG_CONFIG_HOME?.trim(),q=J.PI_CODING_AGENT_DIR?.trim()||$.join(G,".pi","agent");if(q==="~")q=G;else if(/^~[/\\]/.test(q))q=$.join(G,q.slice(2));if(q.startsWith("file://"))q=X2(q);return{env:J,platform:Z,path:$,home:G,cwd:Q,opencode:W?K(W):V?$.join(K(V),"opencode"):$.join(G,".config","opencode"),pi:K(q)}}function i(z,J){try{return B2(z)[J]()}catch{return!1}}var T={exists:D2,isFile:(z)=>i(z,"isFile"),isDirectory:(z)=>i(z,"isDirectory"),isExecutable(z){try{return W2(z,V2.X_OK),i(z,"isFile")}catch{return!1}},readText:(z)=>j2(z,"utf8"),realpath:Y2};function A(z,J={}){let{env:Z,platform:$,path:G,cwd:Q}=k(J),K=J.fs??T,W=Object.entries(Z).find(([q])=>$==="win32"?q.toUpperCase()==="PATH":q==="PATH")?.[1]??"",V=$==="win32"?[".exe",".cmd",".bat",""]:[""];for(let q of W.split($==="win32"?";":":")){let j=q.trim().replace(/^"|"$/g,"");if(!j)continue;for(let D of V){let Y=G.resolve(Q,j,z+D);if($==="win32"?K.isFile(Y):K.isExecutable(Y))return Y}}return null}function V0(z={}){let{platform:J,home:Z,env:$,path:G}=k(z);if(J==="darwin")return["/Applications/OpenCode.app","/Applications/OpenCode Beta.app",G.join(Z,"Applications","OpenCode.app"),G.join(Z,"Applications","OpenCode Beta.app")];if(J==="win32"){let Q=$.LOCALAPPDATA||G.join(Z,"AppData","Local");return[G.join(Q,"Programs","opencode"),G.join(Q,"opencode")]}return["/opt/OpenCode","/usr/lib/opencode",G.join(Z,".local","share","applications","opencode.desktop")]}function s(z,J){let Z=J.fs??T,{path:$}=k(J);try{let G=Z.readText(z);if(G.length>65536)return z;let Q=[...G.matchAll(/"%~?dp0%?\\([^"%\r\n]+)"/g)];if(!Q.length)Q.push(...G.matchAll(/"\$basedir\/([^"$\r\n]+)"/g));let K=Q.at(-1)?.[1];if(K){let W=$.join($.dirname(z),...K.split(/[/\\]+/));if(Z.isFile(W))return Z.realpath(W)}return Z.realpath(z)}catch{return z}}function M2(z,J){let Z=J.fs??T,{path:$}=k(J),G=$.dirname(s(z,J));for(;;){try{let K=JSON.parse(Z.readText($.join(G,"package.json")));if(["@opencode/cli","@opencode-ai/cli"].includes(K.name))return"2";if(K.name==="opencode-ai")return/^(?:[2-9]\d*|1\d+)\.|^0\.0\.0-(?:beta|dev)-/.test(K.version??"")?"2":"1"}catch{}let Q=$.dirname(G);if(Q===G)return null;G=Q}}function D0(z={}){let J=A("opencode",z),Z=A("opencode2",z),$=J&&Z&&s(J,z)===s(Z,z),G=z.fs??T,{path:Q,opencode:K}=k(z),W="1";for(let q of["jsonc","json"]){let j=Q.join(K,`opencode.${q}`);if(!G.exists(j))continue;try{if(Object.hasOwn(O2(G.readText(j))??{},"plugins"))W="2"}catch{}break}let V=J?M2(J,z)??($?"2":W):null;if(Z&&V==="1"&&!$)return"ambiguous";return Z||$?"2":V??W}async function r(z,J={}){let Z=J.fs??T,{env:$,platform:G,opencode:Q,pi:K}=k(J),W=J.runner??_,V=A("opencode",J)??A("opencode2",J),q=A("pi",J),j=A("ck",J),D=async(x)=>{if(!x)return null;let U;try{U=await U2(H2(x2(),"common-auth-setup-version-"));let C={...$,HOME:U,USERPROFILE:U,XDG_CONFIG_HOME:U,XDG_DATA_HOME:U,XDG_STATE_HOME:U,XDG_CACHE_HOME:U,OPENCODE_CONFIG_DIR:U,OPENCODE_CONFIG:void 0,OPENCODE_CONFIG_CONTENT:void 0,OPENCODE_AUTH_CONTENT:void 0,PI_CODING_AGENT_DIR:U},b=await m(W,G,x,["--version"],C,2000);return b.exitCode===0?/\b\d+\.\d+\.\d+(?:-[\w.-]+)?/.exec(b.stdout)?.[0]??null:null}catch{return null}finally{if(U)await F2(U,{recursive:!0,force:!0}).catch(()=>{})}},Y=!1;if(j&&Z.exists(z.vault.connectionFile))try{(await(J.connect??d)({connectionFile:z.vault.connectionFile,handshakeTimeoutMs:2000})).close(),Y=!0}catch{Y=!1}let[X,B]=await Promise.all([D(V),D(q)]);return{opencode:{installed:Z.isDirectory(Q)||V0(J).some((x)=>Z.exists(x))||V!==null,executable:V,version:X,directory:Q,generation:D0(J)},pi:{installed:q!==null||Z.isDirectory(K),executable:q,version:B,directory:K},claustrum:{available:Y,executable:j}}}import{setTimeout as T2}from"node:timers/promises";import{writeEnrollmentTokenFile as w2}from"@cortexkit/claustrum-client";var j0=45000,n=new Set(["opencode","litecode","opencode2","pi"]),B0=new Set(["node","bun"]),C2=[...n,...B0].map((z)=>`Name LIKE '${z}%'`).join(" OR "),R2=`$ErrorActionPreference = 'Stop'; $rows = @(Get-CimInstance Win32_Process -Filter "${C2}" | Select-Object Name,ProcessId,CommandLine); ConvertTo-Json -Compress -Depth 3 -InputObject @{ complete = $true; processes = $rows }`,N2=/(?:^|[/\\])pi-coding-agent[/\\]dist[/\\](?:(?:bundle|bun)[/\\])?cli\.m?js$/i;function k2(z){return[...z.matchAll(/"([^"]*)"|(\S+)/g)].map((J)=>J[1]??J[2]??"")}function Y0(z){return(z.split(/[/\\]/).pop()??"").toLowerCase().replace(/\.(?:exe|cmd|bat|m?js)$/,"")}var I2=new Set(["-r","--require","--import","--loader","--experimental-loader","-C","--conditions","--env-file","--title","--input-type","--preload","--cwd","-c","--config","--tsconfig-override","-d","--define","-l","--main-fields"]),A2=new Set(["-e","--eval","-p","--print"]);function _2(z,J){for(let Z=0;Z<J.length;Z++){let $=J[Z]??"";if($==="--")return J[Z+1];if(A2.has($))return;if($.startsWith("-")){if(!$.includes("=")&&I2.has($))Z++;continue}if(z==="bun"&&$==="run")continue;return $}return}function U0(z){let[J,...Z]=k2(z);if(J===void 0)return null;let $=Y0(J);if(n.has($))return $;if(!B0.has($))return null;let G=_2($,Z);if(G===void 0)return null;let Q=Y0(G);if(n.has(Q))return Q;return N2.test(G)?"pi":null}class M extends Error{code="process-inspection-failed";step;exitCode;signal;timedOut;durationMs;constructor(z){super("Process inspection failed; setup cannot prove hosts are stopped.");this.name="ProcessInspectionError",this.step=z.step,this.exitCode=z.exitCode,this.signal=z.signal,this.timedOut=z.timedOut,this.durationMs=z.durationMs}get refusalText(){let z=this.timedOut?"timed out":this.signal?`signal ${this.signal}`:this.exitCode===null?"could not start or complete":this.exitCode===0?"invalid output (exit code 0)":`exit code ${this.exitCode}`;return`${this.message} ${this.step}: ${z} after ${Math.round(this.durationMs)} ms.`}}class P extends Error{activeHosts;constructor(z){let J=z.map((Z)=>({pid:Z.pid,command:U0(Z.command)??"host"}));super(`OpenCode or Pi processes are currently running:
4
4
  ${J.map((Z)=>` - PID ${Z.pid}: ${Z.command}`).join(`
5
5
  `)}
@@ -9,6 +9,6 @@ Please quit all OpenCode, LiteCode, and Pi processes before running setup.`);thi
9
9
  `:`
10
10
  `}},K=z,W=G[J],V=Array.isArray(W)?[...W]:[],q=V.flatMap((Y,X)=>z0(Y)===Z?[X]:[]),j=`${Z}@${$}`;if(!q.length)K=e(K,T0(K,W===void 0?[J]:[J,V.length],W===void 0?[j]:j,Q));else{let Y=q[0],X=V[Y],B=Array.isArray(X)?[j,...X.slice(1)]:X&&typeof X==="object"?{...X,package:j}:j;if(JSON.stringify(X)!==JSON.stringify(B))K=e(K,T0(K,[J,Y],B,Q));for(let x of q.slice(1).reverse())K=w0(K,J,x)}let D=J==="plugin"?"plugins":"plugin";if(Array.isArray(G[D])){let Y=G[D];for(let X=Y.length-1;X>=0;X--)if(z0(Y[X])===Z)K=w0(K,D,X)}return K}function J0(z,J,Z={}){let $=Z.fs??T,{path:G,opencode:Q}=k(Z),K=J==="2"?"plugins":"plugin";return(J==="2"?["opencode"]:["opencode","tui"]).map((V)=>{let q=G.join(Q,`${V}.jsonc`),j=G.join(Q,`${V}.json`),D=$.exists(q)?q:$.exists(j)?j:q,Y=$.exists(D),X=Y?$.readText(D):`${JSON.stringify({$schema:`https://opencode.ai/${V==="tui"?"tui":"config"}.json`},null,2)}
11
11
  `,B=P0(X,K),x=[],U=[];for(let b of["plugin","plugins"]){if(!Array.isArray(B[b]))continue;for(let H of B[b]){let O=L0(H);if(O===null)continue;if(r2(O,D,Z)===z.packages.opencode)x.push(JSON.stringify(H));else if(z0(H)===z.packages.opencode)U.push(JSON.stringify(H))}}if(x.length>0)return{path:D,content:X,changed:!1,existingLocalEntries:x,existingNpmEntries:U};let C=S0(X,K,z.packages.opencode,z.version);return{path:D,content:C,changed:!Y||C!==X}})}async function Z0(z,J){for(let Z of z){if(!Z.changed)continue;await J?.(),await _0(Z.path,Z.content,{beforeRename:J})}}async function $0(z,J,Z={}){let{platform:$,env:G}=k(Z),Q=await m(Z.runner??_,$,J,["install",`npm:${z.packages.pi}@${z.version}`],G);if(Q.exitCode!==0||Q.timedOut)throw new h({exitCode:Q.spawnError?null:Q.exitCode,signal:Q.signal??null,stderrTail:Q.stderr,stderrTruncated:Q.stderrTruncated??!1})}var v0="Multiple OpenCode generations found. Choose --opencode=1|2|both before running noninteractive setup.";function n2(z){for(let J of Object.values(z.packages))if(!/^(?:@[a-z0-9._-]+\/)?[a-z0-9._-]+$/.test(J))throw Error("Setup requires npm package names.");if(!/^\d+\.\d+\.\d+(?:-[a-zA-Z0-9.-]+)?(?:\+[a-zA-Z0-9.-]+)?$/.test(z.version))throw Error("Setup requires a concrete package version.");for(let J of Object.values(z.vault.hosts))if(!/^[a-z0-9][a-z0-9-]*$/.test(J.name))throw Error("Setup requires lowercase vault names containing only letters, digits and dashes.")}async function o2(z,J,Z){let $=[];for(let G of J){let Q=Z.get(G)??"not-enrolled";if(Q==="unknown"){let{name:K,paths:W}=z.vault.hosts[G],V=await u(w(W),K).catch(()=>"unreadable");if(V==="vault")Q="enrolled";else if(V==="local")Q="not-enrolled"}$.push({host:G,outcome:Q})}return $}async function G0(z,J=[],Z={}){let $=I0(J);n2(z);let G=Z.terminal??y0(),Q=await r(z,Z);F(G,`${z.displayName} setup`);for(let[b,H]of[["OpenCode",Q.opencode],["Pi",Q.pi]])F(G,`${b}: ${H.installed?`found (version ${H.version??"unknown"})`:"not found"} — ${H.directory}`);F(G,`Claustrum: ${Q.claustrum.available?"available":"not available"}`);let K=Q.pi.installed&&!Q.pi.executable;if(K)F(G,"Pi: skipped, because its folder exists but pi is not on PATH. Install the Pi CLI and rerun setup to add it.");let W=["opencode","pi"].filter((b)=>Q[b].installed&&!(b==="pi"&&K));if($.hosts.some((b)=>!W.includes(b)))throw Error(k0);let V=$.yes||$.dryRun&&!f(G);if(!V&&!f(G))throw Error("Setup requires a TTY or --yes.");let q=$.hosts.length?W.filter((b)=>$.hosts.includes(b)):V?W:await A0(G,W)??[],j=$.opencode??(Q.opencode.generation==="ambiguous"?"1":Q.opencode.generation);if(q.includes("opencode")&&!$.opencode&&Q.opencode.generation==="ambiguous"){if(V||!f(G))throw Error(v0);let b=await E(G,[{value:"1",label:"OpenCode 1"},{value:"2",label:"OpenCode 2"},{value:"both",label:"Both (one compatible registration)"}],{message:"Which OpenCode generation should be registered?"});if(b===null)return{hosts:[],dryRun:$.dryRun,mode:"local",detection:Q};j=b}if(!q.length)return F(G,"No hosts selected. Install OpenCode or Pi and rerun setup."),{hosts:q,dryRun:$.dryRun,mode:"local",detection:Q};let{env:D,platform:Y}=k(Z),X=Z.fence??y(Z.runner??_,{platform:Y}),B=async()=>{try{await v(X,D)}catch(b){if(b instanceof M)F(G,b.refusalText);throw b}};if(F(G,"Checking that OpenCode and Pi are not running…"),$.dryRun)try{let b=X.previewRunningHosts?await X.previewRunningHosts(D):{hosts:await X.listRunningHosts(D),uncheckedRuntimes:0},H=b.hosts;if(b.uncheckedRuntimes>0)F(G,"Node or Bun programs are running; a real run checks whether any of them is OpenCode or Pi.");let O=new Set(new P(H).activeHosts.map((R)=>R.command.toLowerCase()==="pi"?"Pi":"OpenCode"));for(let R of O)F(G,`${R} is running; setup will ask you to quit it.`)}catch(b){if(F(G,"Process inspection failed; real setup will require successful inspection and stopped OpenCode/Pi hosts."),b instanceof M)F(G,b.refusalText)}else await B();if(($.claustrum||$.enrollOnly)&&!Q.claustrum.available)throw Error("Claustrum is not available. Start ck, or omit vault-only flags and use --no-claustrum for local sign-in.");let x=$.claustrum||$.enrollOnly;if(!x&&!$.login&&!$.noClaustrum&&!V&&Q.claustrum.available&&f(G)){let b=await E(G,[{label:"No",value:!1},{label:"Yes",value:!0}],{message:"Connect these hosts to the Claustrum vault?"});if(b===null)return F(G,"Setup cancelled. Nothing was changed."),{hosts:[],dryRun:$.dryRun,mode:"local",detection:Q};x=b===!0}let U=x?"claustrum":"local",C=!$.enrollOnly&&q.includes("opencode")?J0(z,j,Z):[];for(let b of C){for(let O of b.existingLocalEntries??[])F(G,`OpenCode: already registered from ${O} in ${b.path}.`);let H=[...b.existingLocalEntries??[],...b.existingNpmEntries??[]];if(H.length>1)F(G,`Warning: ${z.displayName} may load twice in ${b.path}: ${H.join(", ")}. Entries were left unchanged.`)}if($.dryRun){F(G,"Dry run: no registrations, enrollment, sign-in or migration will be performed.");for(let b of q){if(z.beforeSignIn)F(G,`Would run beforeSignIn(${b}, ${U}).`);if(x){let H=w(z.vault.hosts[b].paths);F(G,`Would Connect ${b}: write ${H.statePath} and ${H.tokenPath}; wait for ck auth enroll approve.`)}else F(G,`Would sign in locally for ${b}.`);if(!$.enrollOnly&&z.beforeRegister)F(G,`Would run beforeRegister(${b}, ${U}).`)}for(let b of C)F(G,`${b.changed?"Would write":"Unchanged"} ${b.path}:
12
- ${b.content}`);if(!$.enrollOnly&&q.includes("pi"))F(G,`Would run ${Q.pi.executable} install npm:${z.packages.pi}@${z.version}`);if(!$.enrollOnly&&z.migrate)for(let b of q)F(G,`Would migrate ${b} using the plugin callback (provider-specific writes).`)}else{let b={opencodeGeneration:j,mode:U,hosts:Object.freeze([...q]),piAgentDir:Q.pi.directory},H=new Map;try{for(let O of q){if(await B(),await z.beforeSignIn?.(O,b),await B(),x){H.set(O,"unknown");try{await N0(z,O,Z,G,B)}catch(R){if(R instanceof I)H.set(O,"not-enrolled");throw R}H.set(O,"enrolled")}else await z.signInLocal(O,b);if(await B(),$.enrollOnly)continue;if(await z.beforeRegister?.(O,U,b),await B(),O==="opencode")await Z0(C,B);else await $0(z,Q.pi.executable,Z);await B(),await z.migrate?.(O,b)}}catch(O){if(H.size===0)throw O;try{let R=await o2(z,q,H);W0(O,R);for(let o0 of R)F(G,X0(o0))}catch{}throw O}}if(F(G,`${$.dryRun?"Planned":$.enrollOnly?"Enrolled":"Configured"} ${z.displayName} for ${q.join(", ")} (${U}).`),$.enrollOnly)F(G,`Enroll-only: no host config or plugin registration ${$.dryRun?"will be":"was"} written.`),F(G,"Next: register the plugin yourself in each selected host and enable vault access as required by the plugin.");else F(G,`Next: ${q.includes("opencode")?"start OpenCode":"start Pi"} and run ${z.slashCommand}.`);return{hosts:q,dryRun:$.dryRun,mode:U,detection:Q}}var L={name:"@cortexkit/opencode-openai-auth",version:"1.9.3",license:"MIT",type:"module",repository:{type:"git",url:"git+https://github.com/cortexkit/openai-auth.git",directory:"packages/opencode"},main:"./dist/index.js",types:"./dist/index.d.ts",bin:{"opencode-openai-auth":"./dist/bin.js"},exports:{".":{import:"./dist/index.js",types:"./dist/index.d.ts"},"./tui":{types:"./dist/tui.d.ts",import:"./src/tui/entry.mjs"},"./tui-prefs":{types:"./dist/tui-preferences.d.ts",import:"./dist/tui-preferences.js"},"./server":{types:"./dist/v2/server.d.ts",import:"./dist/v2/server.js"}},"oc-plugin":["server","tui"],engines:{bun:"1.3.14"},files:["dist","src/tui/entry.mjs","src/tui-compiled","README.md","LICENSE"],scripts:{build:"rm -rf dist && bun build src/index.ts src/v2/server.ts src/sidebar-state.ts src/tui-preferences.ts src/rpc/rpc-client.ts src/rpc/port-file.ts src/rpc/protocol.ts src/rpc/rpc-dir.ts src/bin.ts --root src --outdir dist --target node --format esm --splitting --external @opencode-ai/plugin --external @opencode/plugin --external @cortexkit/private-files --external jsonc-parser --external @cortexkit/claustrum-client --external @cortexkit/subc-client --minify && bun run build:types && bun run build:tui","build:tui":"bun scripts/build-tui.ts","build:types":"cd ../core && bun run build && cd ../opencode && tsdown --config tsdown.config.ts --config-loader native","build:dev":"rm -rf dist && tsc -p tsconfig.build.json",test:"bun test src/tests",typecheck:"tsc",types:"tsc",prepublishOnly:"bun run build"},peerDependencies:{"@opencode-ai/plugin":"*","@opencode/plugin":">=2.0.21"},peerDependenciesMeta:{"@opencode/plugin":{optional:!0}},devDependencies:{"@ai-sdk/openai":"3.0.88","@cortexkit/common-auth":"^0.33.0","@cortexkit/openai-auth-core":"workspace:*","@opencode/plugin":"2.2.0"},dependencies:{"@cortexkit/claustrum-client":"^0.13.0","@cortexkit/private-files":"^0.2.2","@cortexkit/subc-client":"^0.22.0","@opentui/core":">=0.7.0","@opentui/solid":">=0.7.0",ai:"^7.0.155","jsonc-parser":"^3.3.1","solid-js":"1.9.12"}};import{basename as $1}from"node:path";import{resolveClaustrumConnectionPath as G1}from"@cortexkit/claustrum-client";var E0={name:"@cortexkit/pi-openai-auth",version:"1.9.3",license:"MIT",type:"module",repository:{type:"git",url:"git+https://github.com/cortexkit/openai-auth.git",directory:"packages/pi"},main:"./dist/index.js",types:"./dist/index.d.ts",exports:{".":{import:"./dist/index.js",types:"./dist/index.d.ts"}},files:["dist","README.md","LICENSE"],keywords:["pi-package"],pi:{extensions:["./dist/index.js"]},scripts:{build:"rm -rf dist && bun build src/index.ts --outdir dist --target node --format esm --external '@earendil-works/pi-ai' --external '@earendil-works/pi-ai/*' --external '@earendil-works/pi-coding-agent' --external '@earendil-works/pi-coding-agent/*' --external '@earendil-works/pi-tui' --external '@earendil-works/pi-tui/*' --external @cortexkit/private-files --external @cortexkit/claustrum-client --external @cortexkit/subc-client --minify && bun run build:types","build:types":"cd ../core && bun run build && cd ../pi && tsdown --config tsdown.config.ts --config-loader native",test:"bun test src/tests",typecheck:"tsc",types:"tsc",prepublishOnly:"bun run build"},devDependencies:{"@cortexkit/common-auth":"^0.33.0","@cortexkit/openai-auth-core":"workspace:*"},dependencies:{"@cortexkit/claustrum-client":"^0.13.0","@cortexkit/private-files":"^0.2.2","@cortexkit/subc-client":"^0.22.0"},peerDependencies:{"@earendil-works/pi-ai":">=1.0.1","@earendil-works/pi-coding-agent":">=1.0.1","@earendil-works/pi-tui":">=1.0.1"}};import{existsSync as p}from"node:fs";import{homedir as l}from"node:os";import{join as a,resolve as f0}from"node:path";import{fileURLToPath as z1}from"node:url";var g0=new Set;function J1(){let z=process.env.PI_CODING_AGENT_DIR;if(!z)return a(l(),".pi","agent");if(process.platform==="win32"&&z.startsWith("/")&&!z.startsWith("//")&&!z.includes("\\")){let J=z.match(/^\/(?:mnt\/|cygdrive\/)?([a-z])(?:\/(.*))?$/i);if(J?.[1])z=`${J[1].toUpperCase()}:\\${J[2]?.replaceAll("/","\\")??""}`}if(z==="~")return l();if(z.startsWith("~/")||process.platform==="win32"&&z.startsWith("~\\"))return a(l(),z.slice(2));return z.startsWith("file://")?z1(z):z}function h0(z=J1()){let J=process.env.PI_OPENAI_AUTH_FILE?.trim();if(J)return J;let Z=a(z,Q0),$=a(l(),".pi","agent",Q0),G=(K)=>{let W=K0(K),V=m0(g(W),"pi");return p(K)||p(W)||p(V.tokenPath)||p(V.statePath)};if(f0(Z)===f0($)||G(Z)||!G($))return Z;let Q=`${Z}\x00${$}`;if(!g0.has(Q))g0.add(Q),console.warn(`openai-auth is using its store in the legacy Pi agent directory: ${$} (${Z} has no store). Credentials were not copied or moved. Set PI_OPENAI_AUTH_FILE to choose a store explicitly.`);return $}function Z1(z=h0()){return process.env.PI_OPENAI_AUTH_STATE_FILE?.trim()||K0(z)}function d0(z=h0()){return{configPath:z,statePath:Z1(z)}}function r0(z={}){let J=z.print??console.log,Z=z.fence??y(),$={opencode:{stateDir:g(a0().statePath),host:"opencode"},pi:{stateDir:g(d0().statePath),host:"pi"}},G=async(Q)=>{if(await u(w($[Q]),S(Q))!=="local")throw Error(`${Q} is enrolled in Claustrum or its enrollment is unreadable. Disconnect it from the vault before using local sign-in.`)};return{packages:{opencode:L.name,pi:E0.name},version:L.version,displayName:"OpenAI Auth",slashCommand:"/openai",vault:{connectionFile:G1(),hosts:{opencode:{name:S("opencode"),paths:$.opencode},pi:{name:S("pi"),paths:$.pi}}},async beforeRegister(Q,K){if(K==="claustrum"){let W=await u0(w($[Q]),S(Q)),V=W.state==="approved"?W.approvedName:void 0,q=V??("proposedName"in W?W.proposedName:S(Q));if(!V)J("The enrollment state does not record an approved name. The command below uses the proposed name; if the vault approved a different name, substitute it.");if(J(`Allow this host to read OpenAI accounts with:
12
+ ${b.content}`);if(!$.enrollOnly&&q.includes("pi"))F(G,`Would run ${Q.pi.executable} install npm:${z.packages.pi}@${z.version}`);if(!$.enrollOnly&&z.migrate)for(let b of q)F(G,`Would migrate ${b} using the plugin callback (provider-specific writes).`)}else{let b={opencodeGeneration:j,mode:U,hosts:Object.freeze([...q]),piAgentDir:Q.pi.directory},H=new Map;try{for(let O of q){if(await B(),await z.beforeSignIn?.(O,b),await B(),x){H.set(O,"unknown");try{await N0(z,O,Z,G,B)}catch(R){if(R instanceof I)H.set(O,"not-enrolled");throw R}H.set(O,"enrolled")}else await z.signInLocal(O,b);if(await B(),$.enrollOnly)continue;if(await z.beforeRegister?.(O,U,b),await B(),O==="opencode")await Z0(C,B);else await $0(z,Q.pi.executable,Z);await B(),await z.migrate?.(O,b)}}catch(O){if(H.size===0)throw O;try{let R=await o2(z,q,H);W0(O,R);for(let o0 of R)F(G,X0(o0))}catch{}throw O}}if(F(G,`${$.dryRun?"Planned":$.enrollOnly?"Enrolled":"Configured"} ${z.displayName} for ${q.join(", ")} (${U}).`),$.enrollOnly)F(G,`Enroll-only: no host config or plugin registration ${$.dryRun?"will be":"was"} written.`),F(G,"Next: register the plugin yourself in each selected host and enable vault access as required by the plugin.");else F(G,`Next: ${q.includes("opencode")?"start OpenCode":"start Pi"} and run ${z.slashCommand}.`);return{hosts:q,dryRun:$.dryRun,mode:U,detection:Q}}var L={name:"@cortexkit/opencode-openai-auth",version:"1.9.4",license:"MIT",type:"module",repository:{type:"git",url:"git+https://github.com/cortexkit/openai-auth.git",directory:"packages/opencode"},main:"./dist/index.js",types:"./dist/index.d.ts",bin:{"opencode-openai-auth":"./dist/bin.js"},exports:{".":{import:"./dist/index.js",types:"./dist/index.d.ts"},"./tui":{types:"./dist/tui.d.ts",import:"./src/tui/entry.mjs"},"./tui-prefs":{types:"./dist/tui-preferences.d.ts",import:"./dist/tui-preferences.js"},"./server":{types:"./dist/v2/server.d.ts",import:"./dist/v2/server.js"}},"oc-plugin":["server","tui"],engines:{bun:"1.3.14"},files:["dist","src/tui/entry.mjs","src/tui-compiled","README.md","LICENSE"],scripts:{build:"rm -rf dist && bun build src/index.ts src/v2/server.ts src/sidebar-state.ts src/tui-preferences.ts src/rpc/rpc-client.ts src/rpc/port-file.ts src/rpc/protocol.ts src/rpc/rpc-dir.ts src/bin.ts --root src --outdir dist --target node --format esm --splitting --external @opencode-ai/plugin --external @opencode/plugin --external @cortexkit/private-files --external jsonc-parser --external @cortexkit/claustrum-client --external @cortexkit/subc-client --minify && bun run build:types && bun run build:tui","build:tui":"bun scripts/build-tui.ts","build:types":"cd ../core && bun run build && cd ../opencode && tsdown --config tsdown.config.ts --config-loader native","build:dev":"rm -rf dist && tsc -p tsconfig.build.json",test:"bun test src/tests",typecheck:"tsc",types:"tsc",prepublishOnly:"bun run build"},peerDependencies:{"@opencode-ai/plugin":"*","@opencode/plugin":">=2.0.21"},peerDependenciesMeta:{"@opencode/plugin":{optional:!0}},devDependencies:{"@ai-sdk/openai":"3.0.88","@cortexkit/common-auth":"^0.33.0","@cortexkit/openai-auth-core":"workspace:*","@opencode/plugin":"2.2.0"},dependencies:{"@cortexkit/claustrum-client":"^0.13.0","@cortexkit/private-files":"^0.2.2","@cortexkit/subc-client":"^0.22.0","@opentui/core":">=0.7.0","@opentui/solid":">=0.7.0",ai:"^7.0.155","jsonc-parser":"^3.3.1","solid-js":"1.9.12"}};import{basename as $1}from"node:path";import{resolveClaustrumConnectionPath as G1}from"@cortexkit/claustrum-client";var E0={name:"@cortexkit/pi-openai-auth",version:"1.9.4",license:"MIT",type:"module",repository:{type:"git",url:"git+https://github.com/cortexkit/openai-auth.git",directory:"packages/pi"},main:"./dist/index.js",types:"./dist/index.d.ts",exports:{".":{import:"./dist/index.js",types:"./dist/index.d.ts"}},files:["dist","README.md","LICENSE"],keywords:["pi-package"],pi:{extensions:["./dist/index.js"]},scripts:{build:"rm -rf dist && bun build src/index.ts --outdir dist --target node --format esm --external '@earendil-works/pi-ai' --external '@earendil-works/pi-ai/*' --external '@earendil-works/pi-coding-agent' --external '@earendil-works/pi-coding-agent/*' --external '@earendil-works/pi-tui' --external '@earendil-works/pi-tui/*' --external @cortexkit/private-files --external @cortexkit/claustrum-client --external @cortexkit/subc-client --minify && bun run build:types","build:types":"cd ../core && bun run build && cd ../pi && tsdown --config tsdown.config.ts --config-loader native",test:"bun test src/tests",typecheck:"tsc",types:"tsc",prepublishOnly:"bun run build"},devDependencies:{"@cortexkit/common-auth":"^0.33.0","@cortexkit/openai-auth-core":"workspace:*"},dependencies:{"@cortexkit/claustrum-client":"^0.13.0","@cortexkit/private-files":"^0.2.2","@cortexkit/subc-client":"^0.22.0"},peerDependencies:{"@earendil-works/pi-ai":">=1.0.1","@earendil-works/pi-coding-agent":">=1.0.1","@earendil-works/pi-tui":">=1.0.1"}};import{existsSync as p}from"node:fs";import{homedir as l}from"node:os";import{join as a,resolve as f0}from"node:path";import{fileURLToPath as z1}from"node:url";var g0=new Set;function J1(){let z=process.env.PI_CODING_AGENT_DIR;if(!z)return a(l(),".pi","agent");if(process.platform==="win32"&&z.startsWith("/")&&!z.startsWith("//")&&!z.includes("\\")){let J=z.match(/^\/(?:mnt\/|cygdrive\/)?([a-z])(?:\/(.*))?$/i);if(J?.[1])z=`${J[1].toUpperCase()}:\\${J[2]?.replaceAll("/","\\")??""}`}if(z==="~")return l();if(z.startsWith("~/")||process.platform==="win32"&&z.startsWith("~\\"))return a(l(),z.slice(2));return z.startsWith("file://")?z1(z):z}function h0(z=J1()){let J=process.env.PI_OPENAI_AUTH_FILE?.trim();if(J)return J;let Z=a(z,Q0),$=a(l(),".pi","agent",Q0),G=(K)=>{let W=K0(K),V=m0(g(W),"pi");return p(K)||p(W)||p(V.tokenPath)||p(V.statePath)};if(f0(Z)===f0($)||G(Z)||!G($))return Z;let Q=`${Z}\x00${$}`;if(!g0.has(Q))g0.add(Q),console.warn(`openai-auth is using its store in the legacy Pi agent directory: ${$} (${Z} has no store). Credentials were not copied or moved. Set PI_OPENAI_AUTH_FILE to choose a store explicitly.`);return $}function Z1(z=h0()){return process.env.PI_OPENAI_AUTH_STATE_FILE?.trim()||K0(z)}function d0(z=h0()){return{configPath:z,statePath:Z1(z)}}function r0(z={}){let J=z.print??console.log,Z=z.fence??y(),$={opencode:{stateDir:g(a0().statePath),host:"opencode"},pi:{stateDir:g(d0().statePath),host:"pi"}},G=async(Q)=>{if(await u(w($[Q]),S(Q))!=="local")throw Error(`${Q} is enrolled in Claustrum or its enrollment is unreadable. Disconnect it from the vault before using local sign-in.`)};return{packages:{opencode:L.name,pi:E0.name},version:L.version,displayName:"OpenAI Auth",slashCommand:"/openai",vault:{connectionFile:G1(),hosts:{opencode:{name:S("opencode"),paths:$.opencode},pi:{name:S("pi"),paths:$.pi}}},async beforeRegister(Q,K){if(K==="claustrum"){let W=await u0(w($[Q]),S(Q)),V=W.state==="approved"?W.approvedName:void 0,q=V??("proposedName"in W?W.proposedName:S(Q));if(!V)J("The enrollment state does not record an approved name. The command below uses the proposed name; if the vault approved a different name, substitute it.");if(J(`Allow this host to read OpenAI accounts with:
13
13
  ck auth grant --principal enrolled:${q} --selector-kind category --selector ${p0.category} --operation read`),Q==="opencode")J("Then run opencode auth login and choose ChatGPT accounts in the vault to activate vault routing without local sign-in.");return}await G(Q)},async signInLocal(Q,K){if(await G(Q),Q==="pi"){J("Start Pi and run /login openai-codex to sign in with Pi itself.");return}if(K.opencodeGeneration!=="1"){let U=$1(A("opencode2",z.io)??A("opencode",z.io)??"opencode");J(`In OpenCode 2, run ${U} auth login openai and choose "ChatGPT (openai-auth pool, browser)" or "ChatGPT (openai-auth pool, headless)" to sign in to the account pool and activate it.`)}if(K.opencodeGeneration==="2")return;if(i0(process.env))throw Error("Unset OPENCODE_AUTH_CONTENT before local setup sign-in.");let W=s0(),V={path:{id:"openai"}};if(await W.get(V)!==void 0){J("OpenCode already has an OpenAI login. Use opencode auth login to change it.");return}let q=z.beginLogin??c0,j=new AbortController,D=Boolean(process.env.SSH_CONNECTION||process.env.SSH_TTY||process.platform==="linux"&&!process.env.DISPLAY&&!process.env.WAYLAND_DISPLAY),Y={version:L.version,signal:j.signal},X,B=!D;try{X=await q({...Y,headless:D})}catch(U){if(D)throw U;B=!1,J("Browser callback unavailable; using device-code sign-in."),X=await q({version:L.version,headless:!0})}if(B){if(!(z.openBrowser??l0)(X.url))j.abort(),await X.completion.catch(()=>{}),J("Browser unavailable; using device-code sign-in."),X=await q({version:L.version,headless:!0})}J(`${X.url}
14
14
  ${X.instructions}`);let x=await X.completion;await v(Z),await G(Q),await W.set({...V,body:{type:"oauth",access:x.access,refresh:x.refresh,expires:x.expires,...x.accountId?{accountId:x.accountId}:{}}}),J("Signed in to OpenCode. The first plugin start adopts this login into the account pool.")},async migrate(Q){J(`${Q}: account migration runs on first plugin start; setup leaves existing credentials unchanged.`)}}}if(process.argv[2]!=="setup")console.log("Usage: opencode-openai-auth setup [options]");else try{await n0({version:L.version}),await G0(r0(),process.argv.slice(3))}catch(z){console.error(z instanceof Error?z.message:String(z)),process.exitCode=1}
@@ -1,4 +1,4 @@
1
- import{$a as V3,Ab as K9,Bb as U9,Cb as O6,Db as B3,Ea as zX,Eb as Y8,Fa as HX,Fb as t4,Ga as KX,Gb as LX,Ha as UX,Ia as FG,Ja as q6,Jb as v$,Ka as i8,Kb as J6,La as x1,Ma as JY,Na as n1,Oa as XY,Ob as y$,Pa as QY,Qa as GY,Qb as g$,Ra as $Y,Rb as t$,Sa as WY,Sb as e$,Tb as YW,Ua as IY,Ub as qG,Va as bY,Wa as S6,Xa as H3,Ya as K3,Za as U3,_a as Z3,ab as w6,cb as v1,eb as Q6,gb as S$,hb as h4,ja as D6,ka as uX,la as L$,lb as LG,ma as r,mb as M6,nb as b$,ob as k$,pa as A$,pb as G0,ra as $G,rb as VX,sa as WG,sb as uJ,ta as T$,tb as pJ,ua as R$,ub as BX,va as PG,vb as x$,wa as GX,wb as a4,xa as KY,xb as h$,ya as $X,yb as e6,za as WX,zb as m9}from"./index-3sda8acd.js";import{Ac as z9,Bc as H9,Cc as r$,Dc as s$,Ec as Z6,Fc as a$,Yb as g4,_b as eX,ac as j1,bc as f$,ec as m$,ic as wG,jc as c$,kc as u$,lc as p$,qc as c9,rc as u9,sc as l$,tc as d$,wc as i$,xc as n$,yc as o$}from"./index-7bjgmbx4.js";import{$d as o8,Ad as tX,Ae as KG,Ce as w$,De as UG,Ee as I4,Fe as ZG,Gd as QX,Ge as VG,He as BG,Md as c0,Nc as y1,Nd as D$,Od as w8,Pc as F6,Pd as J8,Qd as O$,Sd as _$,Td as s0,Vc as W9,Vd as P$,Yd as cJ,Zc as XG,Zd as C0,_d as m6,be as QG,ce as S8,dd as mJ,de as x4,ee as I8,fd as U8,fe as X9,gd as j$,ge as T8,hd as M1,he as V6,id as s4,ie as q$,jd as F$,je as E$,kd as rJ,ke as z3,ld as sJ,le as GG,md as J1,me as B1,nd as X1,ne as r0,od as a1,oe as r1,pd as aJ,pe as HY,qd as tJ,rd as eJ,sd as YX,se as M$,td as JX,te as E6,ud as XX,ue as S1,vd as n8,ve as I1,wd as X6,we as zG,xd as f6,xe as R8,yd as lQ,ye as C$,ze as HG}from"./index-6xz3n4qh.js";import{Me as Q9}from"./index-81yvwra9.js";import{Se as vX,Te as yX,Ue as gX,Ve as mG,We as N$,Xe as A1,Ye as cG,Ze as uG}from"./index-ezwfbnx5.js";import{ef as AX,gf as J9,if as H0,of as h6,qf as ZX}from"./index-cmybrjbd.js";import{Bf as MX,rf as L1,sf as Q8,vf as PX,wf as qX,xf as LY,yf as EX}from"./index-hz6f9gpq.js";import{Df as fX,Ff as I$}from"./index-g3gbp1m4.js";import{Hf as gY}from"./index-v1ztg103.js";import{createHash as MB,randomUUID as AB}from"node:crypto";import{statSync as TB}from"node:fs";import d4 from"node:os";import{readFile as bW}from"node:fs/promises";import{readFileSync as NW,statSync as jW}from"node:fs";import{homedir as FW,tmpdir as DW}from"node:os";import{join as u8}from"node:path";var OW="https://chatgpt.com/backend-api/codex/responses",bJ=536870912,_W=H0("config"),kJ=!1,PW="openai-auth.json",Y1={webSockets:"CORTEXKIT_OPENAI_AUTH_WEBSOCKETS",rawWebSocket:"CORTEXKIT_OPENAI_AUTH_RAW_WS",responsesLite:"CORTEXKIT_OPENAI_AUTH_RESPONSES_LITE",dump:"CORTEXKIT_OPENAI_AUTH_DUMP",dumpDir:"OPENCODE_OPENAI_AUTH_DUMP_DIR",dumpMaxBytes:"OPENCODE_OPENAI_AUTH_DUMP_MAX_BYTES",codexApiEndpoint:"CORTEXKIT_OPENAI_AUTH_CODEX_ENDPOINT",configFile:"OPENCODE_OPENAI_AUTH_FILE",stateFile:"OPENCODE_OPENAI_AUTH_STATE_FILE",configDir:"OPENCODE_CONFIG_DIR"};function qW(){let Y=process.env[Y1.configDir]?.trim();if(Y)return Y;return u8(process.env.XDG_CONFIG_HOME||u8(FW(),".config"),"opencode")}function Y0(){return process.env[Y1.configFile]?.trim()||u8(qW(),PW)}function xJ(){try{let Y=JSON.parse(NW(Y0(),"utf8"));return Y!=null&&typeof Y==="object"&&!Array.isArray(Y)?Y:{}}catch{return{}}}function hJ(Y){let J=process.env[Y];if(J===void 0)return;let X=J.trim().toLowerCase();if(X==="1"||X==="true"||X==="yes"||X==="on")return!0;if(X===""||X==="0"||X==="false"||X==="no"||X==="off")return!1;return}function a6(Y,J,X){let Q=hJ(Y);if(Q!==void 0)return Q;if(typeof J==="boolean")return J;return X}function EW(Y){let J=process.env[Y1.dumpMaxBytes],X=J??Y;if(X===void 0)return bJ;let Q=J?.trim()?Number(J):X;if(typeof Q==="number"&&Number.isSafeInteger(Q)&&Q>=0)return Q;if(!kJ)kJ=!0,_W.warn("Invalid dumpMaxBytes; using the default 512 MiB cap",{env:Y1.dumpMaxBytes});return bJ}function vJ(Y){if(typeof Y.dump==="boolean")return Y.dump;if(Y.dump&&typeof Y.dump==="object")return Y.dump.enabled;return}var o1;function t6(){let Y=hJ(Y1.dump);if(Y!==void 0)return Y;let J=Y0(),X;try{X=jW(J)}catch{}if(o1?.path===J&&o1.mtimeMs===X?.mtimeMs&&o1.ctimeMs===X?.ctimeMs&&o1.size===X?.size)return o1.enabled;let Q=a6(Y1.dump,vJ(xJ()),!1);return o1={path:J,mtimeMs:X?.mtimeMs,ctimeMs:X?.ctimeMs,size:X?.size,enabled:Q},Q}function MW(){let Y=xJ();return{webSockets:a6(Y1.webSockets,Y.webSockets,!1),rawWebSocket:a6(Y1.rawWebSocket,Y.rawWebSocket,!1),responsesLite:a6(Y1.responsesLite,Y.responsesLite,!1),dump:a6(Y1.dump,vJ(Y),!1),dumpDir:process.env[Y1.dumpDir]?.trim()||(typeof Y.dumpDir==="string"&&Y.dumpDir.trim()?Y.dumpDir.trim():u8(DW(),"opencode-openai-auth-dumps")),dumpMaxBytes:EW(Y.dumpMaxBytes),codexApiEndpoint:process.env[Y1.codexApiEndpoint]?.trim()||(typeof Y.codexApiEndpoint==="string"&&Y.codexApiEndpoint.trim()?Y.codexApiEndpoint.trim():OW)}}var c8;function o0(){if(!c8)c8=MW();return c8}function yJ(){return c8=void 0,o1=void 0,o0()}import{readFileSync as AW}from"node:fs";var TW="The `main` account holds the login OpenCode signs in with (its login slot only points at it), so it cannot be removed. Sign in with another account through `opencode auth login` to replace it.";function RW(Y){return`The account-pool migration is moving OpenCode's login into \`${Y}\` right now, so it cannot be removed yet. Try again once the migration has finished.`}function _6(Y,J={}){return D6({provider:"openai",configPath:Y.configPath,statePath:Y.statePath,quota:F6,...J})}function zY(Y){try{let J=JSON.parse(AW(Y,"utf8"));if(!J||typeof J!=="object"||Array.isArray(J))return!1;return e6(J).migratedAt!==void 0}catch{return!1}}async function p8(Y,J){if(!zY(Y.configPath))return;let X=await J.read();return X.status==="ready"?X.rows:void 0}function l8(Y,J){if(Y===B1)return TW;if(e6(J.config).pending?.rowId===Y)return RW(Y);return}function CW(Y,J){return O6(Y,B1,J.legacyLocks).filter((X)=>X.name===Y8)}function E1(Y,J={}){return CW(Y,J)}var P6="This setup has no OpenAI login in its account store. Sign in for this setup with opencode auth login, or point OPENCODE_OPENAI_AUTH_FILE and OPENCODE_OPENAI_AUTH_STATE_FILE at the store that holds the login.";class s1 extends Error{constructor(){super("The main OpenAI account lives in the account pool");this.name="MainAccountInPoolError"}}async function gJ(Y){let J=Y.storage,X=r1(J);if(!J||!X||c0(X))return;let Q=X,G=Y.now(),$=(J.refresh?.refreshBeforeExpiryMinutes??240)*60000;if((!Q.access||!Q.expires||Q.expires-G<=$)&&!M1(Q.lastRefreshError,Q.refresh,G))try{Q=await Y.refreshAccount(Q,J)}catch(K){Y.warn?.("pool main row refresh failed",{error:K instanceof Error?K.message:String(K)})}let H=Q.access?.trim();if(!H)return;if(typeof Q.expires!=="number"||Q.expires<=Y.now())return;return{account:Q,token:H}}import{readFile as lJ}from"node:fs/promises";function d8(Y){return typeof Y==="object"&&Y!==null&&!Array.isArray(Y)}async function dJ(Y){let J=await cJ(Y.configPath),X=[];try{let G=JSON.parse(await lJ(Y.statePath,"utf8"));if(d8(G)){let $=G.accounts;if(d8($))X=Object.keys($)}}catch(G){if(G.code!=="ENOENT")throw G}return{rosterIds:J?[...J]:[],stateIds:X,orphanStateIds:J?X.filter((G)=>!J.has(G)):[]}}async function wW(Y){try{let J=JSON.parse(await lJ(Y.configPath,"utf8"));return d8(J)&&d8(J.claustrum)&&J.claustrum.mode==="claustrum"}catch{return!1}}var fJ="Connect this host to the Claustrum vault (`opencode auth login` > Connect to the Claustrum vault, or the Vault section of `/openai`) if the vault holds the account, or sign in to the account again.";function iJ(Y){if(!Y)return;let J=Y.accounts.find((X)=>X.id==="main"&&s0(X));if(J)return J;if(!Y.mainAccountId)return;return Y.accounts.find((X)=>s0(X)&&X.accountId===Y.mainAccountId)}function SW(Y,J){let X=Y.lastRefreshError;return M1(X,Y.refresh,J)&&X!==void 0&&X.nextRetryAt!==void 0&&X.nextRetryAt-X.checkedAt>=mJ}function IW(Y){let J=[],X=[],Q=Y.now??Date.now(),G=iJ(Y.storage),$=!1;if(c0(Y.auth))J.push({code:"tombstoned-host-slot",message:`OpenCode's OpenAI slot holds a tombstone left by the vault custody of an older version, not a credential; it is never sent. ${fJ}`});else if(r0(Y.auth)){if(!r1(Y.storage))J.push({code:"main-pool-row-missing",message:"The main account was moved into the account pool, but the pool has no usable `main` row."})}else if(!Y.auth)J.push({code:"auth-slot-missing",message:"OpenCode's OpenAI auth slot is missing."}),$=!0;else if(Y.auth.type!=="oauth")J.push({code:"auth-slot-not-oauth",message:"OpenCode's OpenAI auth slot is not OAuth."}),$=!0;else if(G&&(!Y.auth.refresh||G.refresh!==Y.auth.refresh))J.push({code:"main-refresh-not-in-store",message:"OpenCode's main credential does not match the copy in the account store."}),$=!0;if($&&G){let K={type:"restore-main-credential"};X.push(K);let U=J.find((V)=>V.code==="auth-slot-missing"||V.code==="auth-slot-not-oauth"||V.code==="main-refresh-not-in-store");if(U)U.repair=K}let W=Y.storage?.accounts??[];if(W.length===0)J.push({code:"no-accounts",message:"The account store has no accounts."});else if(!W.some((K)=>K.enabled!==!1))J.push({code:"no-enabled-accounts",message:"The account store has no enabled accounts."});for(let K of W){if(!s0(K)||!c0(K))continue;J.push({code:"tombstoned-account",accountId:K.id,message:`Account ${K.id} holds a tombstone left by the vault custody of an older version, not a credential; it is never sent. ${fJ}`})}if(Y.retiredCustodyMode)J.push({code:"retired-custody-mode",message:"The config still selects the vault custody mode of an older version (`claustrum.mode`). It is ignored, and dropped at the next settings write; vault accounts are served once this host is connected to the Claustrum vault."});for(let K of W){if(!s0(K))continue;if(!SW(K,Q))continue;let U={type:"clear-refresh-backoff",accountId:K.id};X.push(U),J.push({code:"armed-non-transient-refresh-backoff",accountId:K.id,message:`Account ${K.id} has an armed non-transient refresh backoff.`,repair:U})}let H=[...Y.orphanStateIds??[]];if(H.length>0){let K={type:"prune-orphan-state-ids",ids:H};X.push(K),J.push({code:"orphan-state-ids",message:`State contains ids absent from the config roster: ${H.join(", ")}.`,repair:K})}return{findings:J,repairs:X}}function nJ(Y){let J=(X)=>{if(X.type==="restore-main-credential")return{label:"Copy the stored main credential back into OpenCode's slot",apply:async()=>{if(r0(await Y.readAuth()))return;let Q=iJ(await Y.loadAccounts(Y.paths));if(!Q)return;await Y.setMainAuth({refresh:Q.refresh,access:Q.access??"",expires:Q.expires??0})}};if(Y.migrated)return;if(X.type==="prune-orphan-state-ids")return{label:`Drop the state entries of ${X.ids.join(", ")}`,apply:async()=>{await Y.mutateAccounts((Q)=>Q,Y.paths)}};return{label:`Clear the refresh backoff of ${X.accountId}`,apply:async()=>{await Y.mutateAccounts((Q)=>{let G=Q.accounts.find(($)=>$.id===X.accountId&&s0($));if(G)G.lastRefreshError=void 0;return Q},Y.paths)}}};return[{id:"openai-auth",run:async()=>{let[X,Q,G,$]=await Promise.all([Y.loadAccounts(Y.paths),Y.readStoreIds(Y.paths),Y.readAuth(),wW(Y.paths)]),W=IW({auth:G.type==="missing"?void 0:G,storage:X,orphanStateIds:Q.orphanStateIds,retiredCustodyMode:$,now:Y.now()}),H=await D6({provider:"openai",quota:F6,configPath:Y.paths.configPath,statePath:Y.paths.statePath}).read();if(H.status==="ready")for(let K of H.rows){if(K.disabledReason!==uJ)continue;W.findings.push({code:"slot-transfer-origin-unknown",accountId:K.id,message:`Account ${K.id} was preserved disabled after an interrupted transfer with an untagged placeholder; sole ownership could not be established. ${pJ}`})}return W.findings.map((K)=>{let U=K.repair?J(K.repair):void 0;return{code:K.code,message:K.message,...K.accountId!==void 0?{accountId:K.accountId}:{},...U?{repair:U}:{}}})}}]}var kW=ZX,oJ="OpenAI accounts",xW="ChatGPT accounts in the vault",hW="Uses the ChatGPT accounts in the Claustrum vault, with no sign-in. This works only while this host is connected to the vault and OpenCode has no OpenAI login stored; otherwise it fails and changes nothing.";async function vW(){let{redirectUri:Y}=await eJ(),J=await sJ(),X=rJ(crypto.getRandomValues(new Uint8Array(32)).buffer),Q=aJ(Y,J,X),G=YX(J,X);return{url:Q,instructions:"Complete authorization in your browser. This window will close automatically.",method:"auto",callback:async()=>{try{let $=await G;return{type:"success",refresh:$.refresh_token,access:$.access_token,expires:Date.now()+($.expires_in??3600)*1000,accountId:a1($)}}finally{tJ(X)}}}}async function yW(Y){let{deviceData:J,url:X,instructions:Q}=await JX(Y);return{url:X,instructions:Q,method:"auto",async callback(){try{let G=await XX(J,Y);return{type:"success",refresh:G.refresh_token,access:G.access_token,expires:Date.now()+(G.expires_in??3600)*1000,accountId:a1(G)}}catch{return{type:"failed"}}}}}function NX({client:Y,getAuth:J,getPaths:X=()=>G0(Y0()),fetchImpl:Q=fetch,packageVersion:G=A1,dependencies:$,onMainSlotWritten:W,vault:H}){let K={authorizeBrowser:$?.authorizeBrowser??vW,authorizeHeadless:$?.authorizeHeadless??(()=>yW(G)),beginAccountLogin:$?.beginAccountLogin??n8,loadAccounts:$?.loadAccounts??C0,mutateAccounts:$?.mutateAccounts??o8,readStoreIds:$?.readStoreIds??dJ,openBrowser:$?.openBrowser??kW,now:$?.now??Date.now,openAccountPool:$?.openAccountPool??_6,migrationBlockers:$?.migrationBlockers??(async()=>{let j=await M6({currentVersion:G});return j.open?[]:j.blockers.map((C)=>({pid:C.pid,version:C.version}))}),...$?.terminal?{terminal:$.terminal}:{},...$?.vaultWait?{vaultWait:$.vaultWait}:{}},U=async()=>await J?.().catch(()=>{return})??{type:"missing"},V=async()=>{if(H&&await H.authority()!=="local")return!0;if((await U()).type!=="missing")return!0;let j=X(),C=K.openAccountPool(j);if((await C.read()).status==="ready")return HX(C);return((await K.loadAccounts(j))?.accounts.length??0)>0},O=async(j)=>{if(await BX(X().configPath,async()=>{if(H&&await H.authority()!=="local")return!1;if(r0(await U()))return!1;return await Y.auth.set({path:{id:"openai"},body:{type:"oauth",...j}}),!0}))await W?.().catch(()=>{})},L=(j)=>({begin:async({headless:C,signal:u})=>{if(H&&await H.authority()!=="local")throw Error(q6);let E=await K.beginAccountLogin({version:G,headless:C,...u?{signal:u}:{}});return{url:E.url,instructions:E.instructions,completion:E.completion.then(async(h)=>{if(H&&await H.authority()!=="local")throw Error(q6);let y=await j.read(),n=y.status==="ready"?y.rows.find((B0)=>B0.id===B1)?.identity:void 0;if(h.accountId&&n&&h.accountId===n)throw Error("that account is already the OpenCode main credential");return{id:h.id,credential:{type:"oauth",refresh:h.refresh,...h.access!==void 0?{access:h.access}:{},...h.expires!==void 0?{expires:h.expires}:{}},...h.accountId!==void 0?{identity:h.accountId}:{},...h.label!==void 0?{label:h.label}:{}}})}},openBrowser:(C)=>K.openBrowser(C)}),B=async(j)=>{if(H&&await H.authority()!=="local")throw Error(q6);let C=j.credential;if(C?.type!=="oauth"||!C.access)throw Error("no usable access token for a quota check");let u=await J8({accessToken:C.access,fetchImpl:Q,now:K.now,...j.identity?{accountId:j.identity}:{},accountKey:j.id});return E6(u,K.now(),!0)},D=(j)=>nJ({paths:X(),migrated:j,readAuth:U,loadAccounts:K.loadAccounts,readStoreIds:K.readStoreIds,mutateAccounts:K.mutateAccounts,setMainAuth:O,now:K.now}),P=(j,C)=>({title:oJ,store:JY(C,{rowLocks:(u)=>O6(j,u)}),...K.terminal?{terminal:K.terminal}:{},login:L(C),protect:(u,E)=>l8(u,E),extraLocks:E1(j),pollQuota:B,doctor:D(!0),status:async()=>{let u=await H?.status();if(H&&await H.authority()!=="local"&&u)return[KY(H.host,H.name,u.enrollment)];return[`Routing: ${(await K.loadAccounts(j))?.routing?.mode??"main-first"}`,...H?[KY(H.host,H.name,(await H.status()).enrollment)]:[]]},...H?{extraActions:[M(H)]}:{}}),M=(j)=>{let C=j.enrolled();return{id:C?"vault-disconnect":"vault-connect",label:C?"Disconnect from the Claustrum vault":"Connect to the Claustrum vault",hint:"serve OpenAI accounts held in the vault",run:async(u)=>{let E=await j.authority();if(C){if(E!=="local")await j.disconnect();u.print("Disconnected from the Claustrum vault.");return}if(E!=="local"){u.print("Nothing was changed: this host is already connected or its enrollment is unreadable. Reopen the menu to disconnect.");return}u.print(`Asking the Claustrum vault to enroll ${j.name}…`);let h,y=await j.waitForApproval({...K.vaultWait,onPending:(n)=>{let V0=n.state==="pending"?n.requestId??n.retryCode??"":n.state;if(V0===h)return;h=V0;for(let B0 of GX(j.name,n))u.print(B0);u.print("Waiting for the approval… (stop with Ctrl-C; Connect picks the request up again)")}});u.print($X(j,y).text)}}},w=async()=>{let j=await K.migrationBlockers();return zX({title:oJ,status:["Accounts move to the new account layout once every OpenCode process on this machine runs this version of OpenAI auth. Account management opens after the move.",...j.length>0?["These processes still hold the move back:",...j.map((C)=>` ${C.pid==="unknown"?"processes that could not be read":`pid ${C.pid}`}: version ${C.version}`)]:[]],actions:[WX({checks:D(!1)})],...K.terminal?{terminal:K.terminal}:{}})},b=async(j)=>{let C=X(),u=K.openAccountPool(C);if(H&&await H.authority()!=="local")return i8(P(C,u),H);if(await p8(C,u)===void 0)return w();let E=P(C,u);return H?i8(E,H):KX(E)},k=(j)=>async()=>{if(H&&await H.authority()!=="local")throw Error(q6);let C=await j();if(C.method!=="auto")return C;return{...C,callback:async()=>{let u=await C.callback();if(H&&await H.authority()!=="local")return{type:"failed"};return u}}};return[{label:"ChatGPT Pro/Plus (browser)",type:"oauth",authorize:UX({hasCredential:V,openMenu:b,login:k(()=>K.authorizeBrowser())})},{label:"ChatGPT Pro/Plus (headless)",type:"oauth",authorize:k(()=>K.authorizeHeadless())},{label:"Manually enter API Key",type:"api"},...H?.enrolled()?[{label:xW,type:"oauth",authorize:async()=>({url:"",instructions:hW,method:"auto",callback:async()=>{if(await QX(H.paths,H.name)!=="vault")return{type:"failed"};try{let j=JSON.parse(await bW(LX(),"utf8"));if(!j||typeof j!=="object"||Array.isArray(j)||Object.hasOwn(j,"openai"))return{type:"failed"}}catch(j){if(j.code!=="ENOENT")return{type:"failed"}}return{...VX,type:"success"}}})}]:[]]}var UY=["type","model","instructions","previous_response_id","input","tools","tool_choice","parallel_tool_calls","reasoning","store","stream","include","prompt_cache_key","text","generate","client_metadata"];function t1(Y){let J={};for(let X of UY)if(X in Y)J[X]=Y[X];for(let X of Object.keys(Y))if(!(X in J))J[X]=Y[X];return J}import{createHash as Xz}from"node:crypto";import{createHash as gW,randomBytes as jX}from"node:crypto";import{chmod as fW,lstat as FX,mkdir as mW,open as cW,readdir as TX,rename as uW,unlink as NY,writeFile as pW}from"node:fs/promises";import{join as r8,resolve as ZY}from"node:path";var lW=100,VY="session-unknown",dW=300000,iW=60000,nW=600000,oW=/\.(body|meta|request|response)\.json$/,rW=/^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}-\d{3}Z-\d+-\d{6,}-[a-zA-Z0-9._-]+$/,sW=/\.[a-f0-9]{24}\.partial$/;function RX(Y){let J=Y.replace(oW,"");if(J===Y||!rW.test(J))return;return J}function aW(Y){let J=Y.replace(sW,"");return J!==Y&&RX(J)!==void 0}async function DX(Y){let{dir:J,maxBytes:X}=Y,Q=Y.now??Date.now(),G=Y.minAgeMs??iW,$=Y.partialStaleMs??nW,W={removed:0,freedBytes:0};if(!(X>0))return W;try{if(L1)await PX(J,"directory");if((await FX(J)).isSymbolicLink())return W;let H=new Set((Y.protectedPaths??[]).map((M)=>ZY(M))),K=await TX(J,{withFileTypes:!0}),U=[];await Promise.all(K.map(async(M)=>{if(!M.isFile())return;let w=aW(M.name),b=w?void 0:RX(M.name);if(!w&&b===void 0)return;let k=r8(J,M.name);try{let j=await FX(k);if(!j.isFile())return;U.push({path:k,size:j.size,mtimeMs:j.mtimeMs,group:b})}catch{}}));let V=U.reduce((M,w)=>M+w.size,0),O=0,L=0,B=async(M)=>{try{await NY(M.path),V-=M.size,L+=M.size,O+=1}catch{}};for(let M of U){if(M.group!==void 0)continue;if(H.has(ZY(M.path)))continue;if(Q-M.mtimeMs<$)continue;await B(M)}let D=new Map;for(let M of U){if(M.group===void 0)continue;let w=D.get(M.group)??{files:[],newest:0};w.files.push(M),w.newest=Math.max(w.newest,M.mtimeMs),D.set(M.group,w)}let P=[...D.entries()].sort(([M,w],[b,k])=>w.newest-k.newest||M.localeCompare(b));for(let[,M]of P){if(V<=X)break;if(Q-M.newest<G)continue;if(M.files.some((w)=>H.has(ZY(w.path))))continue;for(let w of M.files)await B(w)}if(O>0)Y.logger?.debug("removed old dump files",{removed:O,freedBytes:L});return{removed:O,freedBytes:L}}catch(H){if(H instanceof Q8&&H.code==="ERR_PRIVATE_FILES_SECURITY")throw H;return W}}async function tW(Y,J,X){if(L1)return MX(Y,J,{stagePath:`${Y}.${X?X():jX(12).toString("hex")}.partial`});for(let Q=0;;Q+=1){let G=`${Y}.${X?X():jX(12).toString("hex")}.partial`,$=!1,W;try{W=await cW(G,"wx",384),$=!0,await W.writeFile(J,"utf8"),await W.chmod(384),await W.close(),W=void 0,await uW(G,Y);return}catch(H){if(await W?.close().catch(()=>{}),$)await NY(G).catch(()=>{});if(H.code==="EEXIST"&&Q===0)continue;throw H}}}function BY(Y){return Y.length<=16?Y:`${Y.slice(0,12)}…`}function X8(Y,J){let X=Y.trim().replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"");if(!X)return J;return X.slice(0,80)}function OX(Y){return gW("sha256").update(Y).digest("hex")}function eW(Y){return Y.toLowerCase().replace(/[-_]/g,"")}function _X(Y){return Y!==null&&typeof Y==="object"&&!Array.isArray(Y)}function Yz(Y,J){if(Y===void 0)return null;if(Y===J)return{changed:!1,firstByte:-1,lastPreviousByte:-1,lastCurrentByte:-1,previousBytes:Y.length,currentBytes:J.length};let X=0;while(X<Y.length&&X<J.length&&Y[X]===J[X])X++;let Q=Y.length-1,G=J.length-1;while(Q>=X&&G>=X&&Y[Q]===J[G])Q--,G--;return{changed:!0,firstByte:X,lastPreviousByte:Q,lastCurrentByte:G,changedPreviousBytes:Q-X+1,changedCurrentBytes:G-X+1,previousBytes:Y.length,currentBytes:J.length}}var Jz=0;function CX(Y){let J=Y.enabled===!0,X=Y.pid??process.pid,Q=Y.now??Date.now,G=Y.logger,$=new Set((Y.secretKeys??[]).map(eW)),W=AX({extraSecretKeys:(E)=>$.has(E),extraValuePatterns:[...Y.secretPatterns??[]]}),H=new Set(Y.schemaKeys??["tools"]),K=new Map,U=()=>typeof Y.dir==="function"?Y.dir():Y.dir;function V(E){let h=W.redact({[E]:null})[E];return h===null?void 0:h}function O(E){if(Array.isArray(E))return E.map(O);if(_X(E)){let h={};for(let[y,n]of Object.entries(E)){let V0=V(y);if(H.has(y))h[y]=W.redactStrings(n);else if(V0!==void 0)h[y]=V0;else h[y]=O(n)}return h}return W.redactStrings(E)}function L(E){let h;try{h=JSON.parse(E)}catch{return{text:W.redactStrings(E),parsed:void 0}}let y=O(h),n=JSON.stringify(y);return{text:JSON.stringify(h)===n?E:n,parsed:_X(y)?y:void 0}}async function B(E,h,y,n){let V0=`-${X8(h,VY)}-${X8(y,"channel")}`,B0;try{B0=await TX(E)}catch{return}let l=B0.filter((t)=>t.endsWith(".meta.json")&&t.includes(V0)).sort().reverse();for(let t of l)try{if(JSON.parse(await LY(r8(E,t),L1))?.baselineKey!==n)continue;return await LY(r8(E,t.replace(/\.meta\.json$/,".body.json")),L1)}catch(L0){if(L0 instanceof Q8&&(L1||L0.code==="ERR_PRIVATE_FILES_SECURITY"))throw L0}return}function D(E,h){if(!K.has(E))while(K.size>=lW){let y=K.keys().next().value;if(y===void 0)break;K.delete(y)}K.set(E,h)}async function P(E){if(!J)return;let h=++Jz,y=E.session?.trim()||VY,n=U(),V0=new Date(Q()).toISOString(),B0=[V0.replace(/[:.]/g,"-"),String(X),String(h).padStart(6,"0"),X8(y,VY),X8(E.channel,"channel"),...E.phase?[X8(E.phase,"phase")]:[]].join("-"),l=r8(n,B0),t={body:`${l}.body.json`,metadata:`${l}.meta.json`,request:`${l}.request.json`},L0=OX(`${E.channel}\x00${y}`);try{if(L1)await qX(n);else await mW(n,{recursive:!0,mode:448}),await fW(n,448);let v=K.get(L0),x0=v===void 0?void 0:"memory";if(v===void 0){if(v=await B(n,y,E.channel,L0),v!==void 0)x0="disk"}let R0=L(E.bodyText),U0={id:B0,createdAt:V0,pid:X,session:BY(y),channel:E.channel,...E.phase?{phase:E.phase}:{},accountId:E.accountId,status:E.status,error:E.error===void 0?void 0:W.redactStrings(E.error),baselineKey:L0,bodyBytes:Buffer.byteLength(E.bodyText,"utf8"),bodyHash:OX(E.bodyText),diff:Yz(v,R0.text),baselineSource:x0,body:R0.parsed?{parseable:!0,...Y.summarize?.(R0.parsed)}:{parseable:!1},...E.meta?{extra:O(E.meta)}:{},files:t},s=O({url:E.url,method:E.method,accountId:E.accountId,headers:E.headers===void 0?void 0:Object.fromEntries(new Headers(E.headers).entries())}),E0=(i,g)=>L1?EX(i,g):pW(i,g,{encoding:"utf8",mode:384,flag:"wx"}),d=[[t.body,R0.text],[t.metadata,`${JSON.stringify(U0,null,2)}
1
+ import{$a as V3,Ab as K9,Bb as U9,Cb as O6,Db as B3,Ea as zX,Eb as Y8,Fa as HX,Fb as t4,Ga as KX,Gb as LX,Ha as UX,Ia as FG,Ja as q6,Jb as v$,Ka as i8,Kb as J6,La as x1,Ma as JY,Na as n1,Oa as XY,Ob as y$,Pa as QY,Qa as GY,Qb as g$,Ra as $Y,Rb as t$,Sa as WY,Sb as e$,Tb as YW,Ua as IY,Ub as qG,Va as bY,Wa as S6,Xa as H3,Ya as K3,Za as U3,_a as Z3,ab as w6,cb as v1,eb as Q6,gb as S$,hb as h4,ja as D6,ka as uX,la as L$,lb as LG,ma as r,mb as M6,nb as b$,ob as k$,pa as A$,pb as G0,ra as $G,rb as VX,sa as WG,sb as uJ,ta as T$,tb as pJ,ua as R$,ub as BX,va as PG,vb as x$,wa as GX,wb as a4,xa as KY,xb as h$,ya as $X,yb as e6,za as WX,zb as m9}from"./index-xx3k2qbv.js";import{Ac as z9,Bc as H9,Cc as r$,Dc as s$,Ec as Z6,Fc as a$,Yb as g4,_b as eX,ac as j1,bc as f$,ec as m$,ic as wG,jc as c$,kc as u$,lc as p$,qc as c9,rc as u9,sc as l$,tc as d$,wc as i$,xc as n$,yc as o$}from"./index-7bjgmbx4.js";import{$d as o8,Ad as tX,Ae as KG,Ce as w$,De as UG,Ee as I4,Fe as ZG,Gd as QX,Ge as VG,He as BG,Md as c0,Nc as y1,Nd as D$,Od as w8,Pc as F6,Pd as J8,Qd as O$,Sd as _$,Td as s0,Vc as W9,Vd as P$,Yd as cJ,Zc as XG,Zd as C0,_d as m6,be as QG,ce as S8,dd as mJ,de as x4,ee as I8,fd as U8,fe as X9,gd as j$,ge as T8,hd as M1,he as V6,id as s4,ie as q$,jd as F$,je as E$,kd as rJ,ke as z3,ld as sJ,le as GG,md as J1,me as B1,nd as X1,ne as r0,od as a1,oe as r1,pd as aJ,pe as HY,qd as tJ,rd as eJ,sd as YX,se as M$,td as JX,te as E6,ud as XX,ue as S1,vd as n8,ve as I1,wd as X6,we as zG,xd as f6,xe as R8,yd as lQ,ye as C$,ze as HG}from"./index-6xz3n4qh.js";import{Me as Q9}from"./index-81yvwra9.js";import{Se as vX,Te as yX,Ue as gX,Ve as mG,We as N$,Xe as A1,Ye as cG,Ze as uG}from"./index-rrtsaz80.js";import{ef as AX,gf as J9,if as H0,of as h6,qf as ZX}from"./index-cmybrjbd.js";import{Bf as MX,rf as L1,sf as Q8,vf as PX,wf as qX,xf as LY,yf as EX}from"./index-hz6f9gpq.js";import{Df as fX,Ff as I$}from"./index-g3gbp1m4.js";import{Hf as gY}from"./index-v1ztg103.js";import{createHash as MB,randomUUID as AB}from"node:crypto";import{statSync as TB}from"node:fs";import d4 from"node:os";import{readFile as bW}from"node:fs/promises";import{readFileSync as NW,statSync as jW}from"node:fs";import{homedir as FW,tmpdir as DW}from"node:os";import{join as u8}from"node:path";var OW="https://chatgpt.com/backend-api/codex/responses",bJ=536870912,_W=H0("config"),kJ=!1,PW="openai-auth.json",Y1={webSockets:"CORTEXKIT_OPENAI_AUTH_WEBSOCKETS",rawWebSocket:"CORTEXKIT_OPENAI_AUTH_RAW_WS",responsesLite:"CORTEXKIT_OPENAI_AUTH_RESPONSES_LITE",dump:"CORTEXKIT_OPENAI_AUTH_DUMP",dumpDir:"OPENCODE_OPENAI_AUTH_DUMP_DIR",dumpMaxBytes:"OPENCODE_OPENAI_AUTH_DUMP_MAX_BYTES",codexApiEndpoint:"CORTEXKIT_OPENAI_AUTH_CODEX_ENDPOINT",configFile:"OPENCODE_OPENAI_AUTH_FILE",stateFile:"OPENCODE_OPENAI_AUTH_STATE_FILE",configDir:"OPENCODE_CONFIG_DIR"};function qW(){let Y=process.env[Y1.configDir]?.trim();if(Y)return Y;return u8(process.env.XDG_CONFIG_HOME||u8(FW(),".config"),"opencode")}function Y0(){return process.env[Y1.configFile]?.trim()||u8(qW(),PW)}function xJ(){try{let Y=JSON.parse(NW(Y0(),"utf8"));return Y!=null&&typeof Y==="object"&&!Array.isArray(Y)?Y:{}}catch{return{}}}function hJ(Y){let J=process.env[Y];if(J===void 0)return;let X=J.trim().toLowerCase();if(X==="1"||X==="true"||X==="yes"||X==="on")return!0;if(X===""||X==="0"||X==="false"||X==="no"||X==="off")return!1;return}function a6(Y,J,X){let Q=hJ(Y);if(Q!==void 0)return Q;if(typeof J==="boolean")return J;return X}function EW(Y){let J=process.env[Y1.dumpMaxBytes],X=J??Y;if(X===void 0)return bJ;let Q=J?.trim()?Number(J):X;if(typeof Q==="number"&&Number.isSafeInteger(Q)&&Q>=0)return Q;if(!kJ)kJ=!0,_W.warn("Invalid dumpMaxBytes; using the default 512 MiB cap",{env:Y1.dumpMaxBytes});return bJ}function vJ(Y){if(typeof Y.dump==="boolean")return Y.dump;if(Y.dump&&typeof Y.dump==="object")return Y.dump.enabled;return}var o1;function t6(){let Y=hJ(Y1.dump);if(Y!==void 0)return Y;let J=Y0(),X;try{X=jW(J)}catch{}if(o1?.path===J&&o1.mtimeMs===X?.mtimeMs&&o1.ctimeMs===X?.ctimeMs&&o1.size===X?.size)return o1.enabled;let Q=a6(Y1.dump,vJ(xJ()),!1);return o1={path:J,mtimeMs:X?.mtimeMs,ctimeMs:X?.ctimeMs,size:X?.size,enabled:Q},Q}function MW(){let Y=xJ();return{webSockets:a6(Y1.webSockets,Y.webSockets,!1),rawWebSocket:a6(Y1.rawWebSocket,Y.rawWebSocket,!1),responsesLite:a6(Y1.responsesLite,Y.responsesLite,!1),dump:a6(Y1.dump,vJ(Y),!1),dumpDir:process.env[Y1.dumpDir]?.trim()||(typeof Y.dumpDir==="string"&&Y.dumpDir.trim()?Y.dumpDir.trim():u8(DW(),"opencode-openai-auth-dumps")),dumpMaxBytes:EW(Y.dumpMaxBytes),codexApiEndpoint:process.env[Y1.codexApiEndpoint]?.trim()||(typeof Y.codexApiEndpoint==="string"&&Y.codexApiEndpoint.trim()?Y.codexApiEndpoint.trim():OW)}}var c8;function o0(){if(!c8)c8=MW();return c8}function yJ(){return c8=void 0,o1=void 0,o0()}import{readFileSync as AW}from"node:fs";var TW="The `main` account holds the login OpenCode signs in with (its login slot only points at it), so it cannot be removed. Sign in with another account through `opencode auth login` to replace it.";function RW(Y){return`The account-pool migration is moving OpenCode's login into \`${Y}\` right now, so it cannot be removed yet. Try again once the migration has finished.`}function _6(Y,J={}){return D6({provider:"openai",configPath:Y.configPath,statePath:Y.statePath,quota:F6,...J})}function zY(Y){try{let J=JSON.parse(AW(Y,"utf8"));if(!J||typeof J!=="object"||Array.isArray(J))return!1;return e6(J).migratedAt!==void 0}catch{return!1}}async function p8(Y,J){if(!zY(Y.configPath))return;let X=await J.read();return X.status==="ready"?X.rows:void 0}function l8(Y,J){if(Y===B1)return TW;if(e6(J.config).pending?.rowId===Y)return RW(Y);return}function CW(Y,J){return O6(Y,B1,J.legacyLocks).filter((X)=>X.name===Y8)}function E1(Y,J={}){return CW(Y,J)}var P6="This setup has no OpenAI login in its account store. Sign in for this setup with opencode auth login, or point OPENCODE_OPENAI_AUTH_FILE and OPENCODE_OPENAI_AUTH_STATE_FILE at the store that holds the login.";class s1 extends Error{constructor(){super("The main OpenAI account lives in the account pool");this.name="MainAccountInPoolError"}}async function gJ(Y){let J=Y.storage,X=r1(J);if(!J||!X||c0(X))return;let Q=X,G=Y.now(),$=(J.refresh?.refreshBeforeExpiryMinutes??240)*60000;if((!Q.access||!Q.expires||Q.expires-G<=$)&&!M1(Q.lastRefreshError,Q.refresh,G))try{Q=await Y.refreshAccount(Q,J)}catch(K){Y.warn?.("pool main row refresh failed",{error:K instanceof Error?K.message:String(K)})}let H=Q.access?.trim();if(!H)return;if(typeof Q.expires!=="number"||Q.expires<=Y.now())return;return{account:Q,token:H}}import{readFile as lJ}from"node:fs/promises";function d8(Y){return typeof Y==="object"&&Y!==null&&!Array.isArray(Y)}async function dJ(Y){let J=await cJ(Y.configPath),X=[];try{let G=JSON.parse(await lJ(Y.statePath,"utf8"));if(d8(G)){let $=G.accounts;if(d8($))X=Object.keys($)}}catch(G){if(G.code!=="ENOENT")throw G}return{rosterIds:J?[...J]:[],stateIds:X,orphanStateIds:J?X.filter((G)=>!J.has(G)):[]}}async function wW(Y){try{let J=JSON.parse(await lJ(Y.configPath,"utf8"));return d8(J)&&d8(J.claustrum)&&J.claustrum.mode==="claustrum"}catch{return!1}}var fJ="Connect this host to the Claustrum vault (`opencode auth login` > Connect to the Claustrum vault, or the Vault section of `/openai`) if the vault holds the account, or sign in to the account again.";function iJ(Y){if(!Y)return;let J=Y.accounts.find((X)=>X.id==="main"&&s0(X));if(J)return J;if(!Y.mainAccountId)return;return Y.accounts.find((X)=>s0(X)&&X.accountId===Y.mainAccountId)}function SW(Y,J){let X=Y.lastRefreshError;return M1(X,Y.refresh,J)&&X!==void 0&&X.nextRetryAt!==void 0&&X.nextRetryAt-X.checkedAt>=mJ}function IW(Y){let J=[],X=[],Q=Y.now??Date.now(),G=iJ(Y.storage),$=!1;if(c0(Y.auth))J.push({code:"tombstoned-host-slot",message:`OpenCode's OpenAI slot holds a tombstone left by the vault custody of an older version, not a credential; it is never sent. ${fJ}`});else if(r0(Y.auth)){if(!r1(Y.storage))J.push({code:"main-pool-row-missing",message:"The main account was moved into the account pool, but the pool has no usable `main` row."})}else if(!Y.auth)J.push({code:"auth-slot-missing",message:"OpenCode's OpenAI auth slot is missing."}),$=!0;else if(Y.auth.type!=="oauth")J.push({code:"auth-slot-not-oauth",message:"OpenCode's OpenAI auth slot is not OAuth."}),$=!0;else if(G&&(!Y.auth.refresh||G.refresh!==Y.auth.refresh))J.push({code:"main-refresh-not-in-store",message:"OpenCode's main credential does not match the copy in the account store."}),$=!0;if($&&G){let K={type:"restore-main-credential"};X.push(K);let U=J.find((V)=>V.code==="auth-slot-missing"||V.code==="auth-slot-not-oauth"||V.code==="main-refresh-not-in-store");if(U)U.repair=K}let W=Y.storage?.accounts??[];if(W.length===0)J.push({code:"no-accounts",message:"The account store has no accounts."});else if(!W.some((K)=>K.enabled!==!1))J.push({code:"no-enabled-accounts",message:"The account store has no enabled accounts."});for(let K of W){if(!s0(K)||!c0(K))continue;J.push({code:"tombstoned-account",accountId:K.id,message:`Account ${K.id} holds a tombstone left by the vault custody of an older version, not a credential; it is never sent. ${fJ}`})}if(Y.retiredCustodyMode)J.push({code:"retired-custody-mode",message:"The config still selects the vault custody mode of an older version (`claustrum.mode`). It is ignored, and dropped at the next settings write; vault accounts are served once this host is connected to the Claustrum vault."});for(let K of W){if(!s0(K))continue;if(!SW(K,Q))continue;let U={type:"clear-refresh-backoff",accountId:K.id};X.push(U),J.push({code:"armed-non-transient-refresh-backoff",accountId:K.id,message:`Account ${K.id} has an armed non-transient refresh backoff.`,repair:U})}let H=[...Y.orphanStateIds??[]];if(H.length>0){let K={type:"prune-orphan-state-ids",ids:H};X.push(K),J.push({code:"orphan-state-ids",message:`State contains ids absent from the config roster: ${H.join(", ")}.`,repair:K})}return{findings:J,repairs:X}}function nJ(Y){let J=(X)=>{if(X.type==="restore-main-credential")return{label:"Copy the stored main credential back into OpenCode's slot",apply:async()=>{if(r0(await Y.readAuth()))return;let Q=iJ(await Y.loadAccounts(Y.paths));if(!Q)return;await Y.setMainAuth({refresh:Q.refresh,access:Q.access??"",expires:Q.expires??0})}};if(Y.migrated)return;if(X.type==="prune-orphan-state-ids")return{label:`Drop the state entries of ${X.ids.join(", ")}`,apply:async()=>{await Y.mutateAccounts((Q)=>Q,Y.paths)}};return{label:`Clear the refresh backoff of ${X.accountId}`,apply:async()=>{await Y.mutateAccounts((Q)=>{let G=Q.accounts.find(($)=>$.id===X.accountId&&s0($));if(G)G.lastRefreshError=void 0;return Q},Y.paths)}}};return[{id:"openai-auth",run:async()=>{let[X,Q,G,$]=await Promise.all([Y.loadAccounts(Y.paths),Y.readStoreIds(Y.paths),Y.readAuth(),wW(Y.paths)]),W=IW({auth:G.type==="missing"?void 0:G,storage:X,orphanStateIds:Q.orphanStateIds,retiredCustodyMode:$,now:Y.now()}),H=await D6({provider:"openai",quota:F6,configPath:Y.paths.configPath,statePath:Y.paths.statePath}).read();if(H.status==="ready")for(let K of H.rows){if(K.disabledReason!==uJ)continue;W.findings.push({code:"slot-transfer-origin-unknown",accountId:K.id,message:`Account ${K.id} was preserved disabled after an interrupted transfer with an untagged placeholder; sole ownership could not be established. ${pJ}`})}return W.findings.map((K)=>{let U=K.repair?J(K.repair):void 0;return{code:K.code,message:K.message,...K.accountId!==void 0?{accountId:K.accountId}:{},...U?{repair:U}:{}}})}}]}var kW=ZX,oJ="OpenAI accounts",xW="ChatGPT accounts in the vault",hW="Uses the ChatGPT accounts in the Claustrum vault, with no sign-in. This works only while this host is connected to the vault and OpenCode has no OpenAI login stored; otherwise it fails and changes nothing.";async function vW(){let{redirectUri:Y}=await eJ(),J=await sJ(),X=rJ(crypto.getRandomValues(new Uint8Array(32)).buffer),Q=aJ(Y,J,X),G=YX(J,X);return{url:Q,instructions:"Complete authorization in your browser. This window will close automatically.",method:"auto",callback:async()=>{try{let $=await G;return{type:"success",refresh:$.refresh_token,access:$.access_token,expires:Date.now()+($.expires_in??3600)*1000,accountId:a1($)}}finally{tJ(X)}}}}async function yW(Y){let{deviceData:J,url:X,instructions:Q}=await JX(Y);return{url:X,instructions:Q,method:"auto",async callback(){try{let G=await XX(J,Y);return{type:"success",refresh:G.refresh_token,access:G.access_token,expires:Date.now()+(G.expires_in??3600)*1000,accountId:a1(G)}}catch{return{type:"failed"}}}}}function NX({client:Y,getAuth:J,getPaths:X=()=>G0(Y0()),fetchImpl:Q=fetch,packageVersion:G=A1,dependencies:$,onMainSlotWritten:W,vault:H}){let K={authorizeBrowser:$?.authorizeBrowser??vW,authorizeHeadless:$?.authorizeHeadless??(()=>yW(G)),beginAccountLogin:$?.beginAccountLogin??n8,loadAccounts:$?.loadAccounts??C0,mutateAccounts:$?.mutateAccounts??o8,readStoreIds:$?.readStoreIds??dJ,openBrowser:$?.openBrowser??kW,now:$?.now??Date.now,openAccountPool:$?.openAccountPool??_6,migrationBlockers:$?.migrationBlockers??(async()=>{let j=await M6({currentVersion:G});return j.open?[]:j.blockers.map((C)=>({pid:C.pid,version:C.version}))}),...$?.terminal?{terminal:$.terminal}:{},...$?.vaultWait?{vaultWait:$.vaultWait}:{}},U=async()=>await J?.().catch(()=>{return})??{type:"missing"},V=async()=>{if(H&&await H.authority()!=="local")return!0;if((await U()).type!=="missing")return!0;let j=X(),C=K.openAccountPool(j);if((await C.read()).status==="ready")return HX(C);return((await K.loadAccounts(j))?.accounts.length??0)>0},O=async(j)=>{if(await BX(X().configPath,async()=>{if(H&&await H.authority()!=="local")return!1;if(r0(await U()))return!1;return await Y.auth.set({path:{id:"openai"},body:{type:"oauth",...j}}),!0}))await W?.().catch(()=>{})},L=(j)=>({begin:async({headless:C,signal:u})=>{if(H&&await H.authority()!=="local")throw Error(q6);let E=await K.beginAccountLogin({version:G,headless:C,...u?{signal:u}:{}});return{url:E.url,instructions:E.instructions,completion:E.completion.then(async(h)=>{if(H&&await H.authority()!=="local")throw Error(q6);let y=await j.read(),n=y.status==="ready"?y.rows.find((B0)=>B0.id===B1)?.identity:void 0;if(h.accountId&&n&&h.accountId===n)throw Error("that account is already the OpenCode main credential");return{id:h.id,credential:{type:"oauth",refresh:h.refresh,...h.access!==void 0?{access:h.access}:{},...h.expires!==void 0?{expires:h.expires}:{}},...h.accountId!==void 0?{identity:h.accountId}:{},...h.label!==void 0?{label:h.label}:{}}})}},openBrowser:(C)=>K.openBrowser(C)}),B=async(j)=>{if(H&&await H.authority()!=="local")throw Error(q6);let C=j.credential;if(C?.type!=="oauth"||!C.access)throw Error("no usable access token for a quota check");let u=await J8({accessToken:C.access,fetchImpl:Q,now:K.now,...j.identity?{accountId:j.identity}:{},accountKey:j.id});return E6(u,K.now(),!0)},D=(j)=>nJ({paths:X(),migrated:j,readAuth:U,loadAccounts:K.loadAccounts,readStoreIds:K.readStoreIds,mutateAccounts:K.mutateAccounts,setMainAuth:O,now:K.now}),P=(j,C)=>({title:oJ,store:JY(C,{rowLocks:(u)=>O6(j,u)}),...K.terminal?{terminal:K.terminal}:{},login:L(C),protect:(u,E)=>l8(u,E),extraLocks:E1(j),pollQuota:B,doctor:D(!0),status:async()=>{let u=await H?.status();if(H&&await H.authority()!=="local"&&u)return[KY(H.host,H.name,u.enrollment)];return[`Routing: ${(await K.loadAccounts(j))?.routing?.mode??"main-first"}`,...H?[KY(H.host,H.name,(await H.status()).enrollment)]:[]]},...H?{extraActions:[M(H)]}:{}}),M=(j)=>{let C=j.enrolled();return{id:C?"vault-disconnect":"vault-connect",label:C?"Disconnect from the Claustrum vault":"Connect to the Claustrum vault",hint:"serve OpenAI accounts held in the vault",run:async(u)=>{let E=await j.authority();if(C){if(E!=="local")await j.disconnect();u.print("Disconnected from the Claustrum vault.");return}if(E!=="local"){u.print("Nothing was changed: this host is already connected or its enrollment is unreadable. Reopen the menu to disconnect.");return}u.print(`Asking the Claustrum vault to enroll ${j.name}…`);let h,y=await j.waitForApproval({...K.vaultWait,onPending:(n)=>{let V0=n.state==="pending"?n.requestId??n.retryCode??"":n.state;if(V0===h)return;h=V0;for(let B0 of GX(j.name,n))u.print(B0);u.print("Waiting for the approval… (stop with Ctrl-C; Connect picks the request up again)")}});u.print($X(j,y).text)}}},w=async()=>{let j=await K.migrationBlockers();return zX({title:oJ,status:["Accounts move to the new account layout once every OpenCode process on this machine runs this version of OpenAI auth. Account management opens after the move.",...j.length>0?["These processes still hold the move back:",...j.map((C)=>` ${C.pid==="unknown"?"processes that could not be read":`pid ${C.pid}`}: version ${C.version}`)]:[]],actions:[WX({checks:D(!1)})],...K.terminal?{terminal:K.terminal}:{}})},b=async(j)=>{let C=X(),u=K.openAccountPool(C);if(H&&await H.authority()!=="local")return i8(P(C,u),H);if(await p8(C,u)===void 0)return w();let E=P(C,u);return H?i8(E,H):KX(E)},k=(j)=>async()=>{if(H&&await H.authority()!=="local")throw Error(q6);let C=await j();if(C.method!=="auto")return C;return{...C,callback:async()=>{let u=await C.callback();if(H&&await H.authority()!=="local")return{type:"failed"};return u}}};return[{label:"ChatGPT Pro/Plus (browser)",type:"oauth",authorize:UX({hasCredential:V,openMenu:b,login:k(()=>K.authorizeBrowser())})},{label:"ChatGPT Pro/Plus (headless)",type:"oauth",authorize:k(()=>K.authorizeHeadless())},{label:"Manually enter API Key",type:"api"},...H?.enrolled()?[{label:xW,type:"oauth",authorize:async()=>({url:"",instructions:hW,method:"auto",callback:async()=>{if(await QX(H.paths,H.name)!=="vault")return{type:"failed"};try{let j=JSON.parse(await bW(LX(),"utf8"));if(!j||typeof j!=="object"||Array.isArray(j)||Object.hasOwn(j,"openai"))return{type:"failed"}}catch(j){if(j.code!=="ENOENT")return{type:"failed"}}return{...VX,type:"success"}}})}]:[]]}var UY=["type","model","instructions","previous_response_id","input","tools","tool_choice","parallel_tool_calls","reasoning","store","stream","include","prompt_cache_key","text","generate","client_metadata"];function t1(Y){let J={};for(let X of UY)if(X in Y)J[X]=Y[X];for(let X of Object.keys(Y))if(!(X in J))J[X]=Y[X];return J}import{createHash as Xz}from"node:crypto";import{createHash as gW,randomBytes as jX}from"node:crypto";import{chmod as fW,lstat as FX,mkdir as mW,open as cW,readdir as TX,rename as uW,unlink as NY,writeFile as pW}from"node:fs/promises";import{join as r8,resolve as ZY}from"node:path";var lW=100,VY="session-unknown",dW=300000,iW=60000,nW=600000,oW=/\.(body|meta|request|response)\.json$/,rW=/^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}-\d{3}Z-\d+-\d{6,}-[a-zA-Z0-9._-]+$/,sW=/\.[a-f0-9]{24}\.partial$/;function RX(Y){let J=Y.replace(oW,"");if(J===Y||!rW.test(J))return;return J}function aW(Y){let J=Y.replace(sW,"");return J!==Y&&RX(J)!==void 0}async function DX(Y){let{dir:J,maxBytes:X}=Y,Q=Y.now??Date.now(),G=Y.minAgeMs??iW,$=Y.partialStaleMs??nW,W={removed:0,freedBytes:0};if(!(X>0))return W;try{if(L1)await PX(J,"directory");if((await FX(J)).isSymbolicLink())return W;let H=new Set((Y.protectedPaths??[]).map((M)=>ZY(M))),K=await TX(J,{withFileTypes:!0}),U=[];await Promise.all(K.map(async(M)=>{if(!M.isFile())return;let w=aW(M.name),b=w?void 0:RX(M.name);if(!w&&b===void 0)return;let k=r8(J,M.name);try{let j=await FX(k);if(!j.isFile())return;U.push({path:k,size:j.size,mtimeMs:j.mtimeMs,group:b})}catch{}}));let V=U.reduce((M,w)=>M+w.size,0),O=0,L=0,B=async(M)=>{try{await NY(M.path),V-=M.size,L+=M.size,O+=1}catch{}};for(let M of U){if(M.group!==void 0)continue;if(H.has(ZY(M.path)))continue;if(Q-M.mtimeMs<$)continue;await B(M)}let D=new Map;for(let M of U){if(M.group===void 0)continue;let w=D.get(M.group)??{files:[],newest:0};w.files.push(M),w.newest=Math.max(w.newest,M.mtimeMs),D.set(M.group,w)}let P=[...D.entries()].sort(([M,w],[b,k])=>w.newest-k.newest||M.localeCompare(b));for(let[,M]of P){if(V<=X)break;if(Q-M.newest<G)continue;if(M.files.some((w)=>H.has(ZY(w.path))))continue;for(let w of M.files)await B(w)}if(O>0)Y.logger?.debug("removed old dump files",{removed:O,freedBytes:L});return{removed:O,freedBytes:L}}catch(H){if(H instanceof Q8&&H.code==="ERR_PRIVATE_FILES_SECURITY")throw H;return W}}async function tW(Y,J,X){if(L1)return MX(Y,J,{stagePath:`${Y}.${X?X():jX(12).toString("hex")}.partial`});for(let Q=0;;Q+=1){let G=`${Y}.${X?X():jX(12).toString("hex")}.partial`,$=!1,W;try{W=await cW(G,"wx",384),$=!0,await W.writeFile(J,"utf8"),await W.chmod(384),await W.close(),W=void 0,await uW(G,Y);return}catch(H){if(await W?.close().catch(()=>{}),$)await NY(G).catch(()=>{});if(H.code==="EEXIST"&&Q===0)continue;throw H}}}function BY(Y){return Y.length<=16?Y:`${Y.slice(0,12)}…`}function X8(Y,J){let X=Y.trim().replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"");if(!X)return J;return X.slice(0,80)}function OX(Y){return gW("sha256").update(Y).digest("hex")}function eW(Y){return Y.toLowerCase().replace(/[-_]/g,"")}function _X(Y){return Y!==null&&typeof Y==="object"&&!Array.isArray(Y)}function Yz(Y,J){if(Y===void 0)return null;if(Y===J)return{changed:!1,firstByte:-1,lastPreviousByte:-1,lastCurrentByte:-1,previousBytes:Y.length,currentBytes:J.length};let X=0;while(X<Y.length&&X<J.length&&Y[X]===J[X])X++;let Q=Y.length-1,G=J.length-1;while(Q>=X&&G>=X&&Y[Q]===J[G])Q--,G--;return{changed:!0,firstByte:X,lastPreviousByte:Q,lastCurrentByte:G,changedPreviousBytes:Q-X+1,changedCurrentBytes:G-X+1,previousBytes:Y.length,currentBytes:J.length}}var Jz=0;function CX(Y){let J=Y.enabled===!0,X=Y.pid??process.pid,Q=Y.now??Date.now,G=Y.logger,$=new Set((Y.secretKeys??[]).map(eW)),W=AX({extraSecretKeys:(E)=>$.has(E),extraValuePatterns:[...Y.secretPatterns??[]]}),H=new Set(Y.schemaKeys??["tools"]),K=new Map,U=()=>typeof Y.dir==="function"?Y.dir():Y.dir;function V(E){let h=W.redact({[E]:null})[E];return h===null?void 0:h}function O(E){if(Array.isArray(E))return E.map(O);if(_X(E)){let h={};for(let[y,n]of Object.entries(E)){let V0=V(y);if(H.has(y))h[y]=W.redactStrings(n);else if(V0!==void 0)h[y]=V0;else h[y]=O(n)}return h}return W.redactStrings(E)}function L(E){let h;try{h=JSON.parse(E)}catch{return{text:W.redactStrings(E),parsed:void 0}}let y=O(h),n=JSON.stringify(y);return{text:JSON.stringify(h)===n?E:n,parsed:_X(y)?y:void 0}}async function B(E,h,y,n){let V0=`-${X8(h,VY)}-${X8(y,"channel")}`,B0;try{B0=await TX(E)}catch{return}let l=B0.filter((t)=>t.endsWith(".meta.json")&&t.includes(V0)).sort().reverse();for(let t of l)try{if(JSON.parse(await LY(r8(E,t),L1))?.baselineKey!==n)continue;return await LY(r8(E,t.replace(/\.meta\.json$/,".body.json")),L1)}catch(L0){if(L0 instanceof Q8&&(L1||L0.code==="ERR_PRIVATE_FILES_SECURITY"))throw L0}return}function D(E,h){if(!K.has(E))while(K.size>=lW){let y=K.keys().next().value;if(y===void 0)break;K.delete(y)}K.set(E,h)}async function P(E){if(!J)return;let h=++Jz,y=E.session?.trim()||VY,n=U(),V0=new Date(Q()).toISOString(),B0=[V0.replace(/[:.]/g,"-"),String(X),String(h).padStart(6,"0"),X8(y,VY),X8(E.channel,"channel"),...E.phase?[X8(E.phase,"phase")]:[]].join("-"),l=r8(n,B0),t={body:`${l}.body.json`,metadata:`${l}.meta.json`,request:`${l}.request.json`},L0=OX(`${E.channel}\x00${y}`);try{if(L1)await qX(n);else await mW(n,{recursive:!0,mode:448}),await fW(n,448);let v=K.get(L0),x0=v===void 0?void 0:"memory";if(v===void 0){if(v=await B(n,y,E.channel,L0),v!==void 0)x0="disk"}let R0=L(E.bodyText),U0={id:B0,createdAt:V0,pid:X,session:BY(y),channel:E.channel,...E.phase?{phase:E.phase}:{},accountId:E.accountId,status:E.status,error:E.error===void 0?void 0:W.redactStrings(E.error),baselineKey:L0,bodyBytes:Buffer.byteLength(E.bodyText,"utf8"),bodyHash:OX(E.bodyText),diff:Yz(v,R0.text),baselineSource:x0,body:R0.parsed?{parseable:!0,...Y.summarize?.(R0.parsed)}:{parseable:!1},...E.meta?{extra:O(E.meta)}:{},files:t},s=O({url:E.url,method:E.method,accountId:E.accountId,headers:E.headers===void 0?void 0:Object.fromEntries(new Headers(E.headers).entries())}),E0=(i,g)=>L1?EX(i,g):pW(i,g,{encoding:"utf8",mode:384,flag:"wx"}),d=[[t.body,R0.text],[t.metadata,`${JSON.stringify(U0,null,2)}
2
2
  `],[t.request,`${JSON.stringify(s,null,2)}
3
3
  `]],S=await Promise.allSettled(d.map(([i,g])=>E0(i,g))),p=S.find((i)=>i.status==="rejected");if(p){if(Y.cleanupFailedDumps)await M(d,S);throw p.reason}return D(L0,R0.text),G?.debug("dumped request",{id:B0,session:BY(y),body:t.body}),C(n,Object.values(t)),{id:B0,files:t,responseFile:`${l}.response.json`}}catch(v){if(v instanceof Q8&&(L1||v.code==="ERR_PRIVATE_FILES_SECURITY"))throw v;G?.warn("request dump failed",{session:BY(y),error:v instanceof Error?v.message:String(v)});return}}async function M(E,h){await Promise.all(E.map(async([y],n)=>{let V0=h[n];if(V0?.status==="rejected"&&V0.reason?.code==="EEXIST")return;await NY(y).catch(()=>{})}))}let w=Y.maxBytes??0,b=Y.sweepIntervalMs??dW,k=0;function j(E,h){return{dir:E,maxBytes:w,protectedPaths:h,now:Q(),minAgeMs:Y.sweepMinAgeMs,partialStaleMs:Y.partialStaleMs,logger:G}}function C(E,h){if(!(w>0))return;let y=Q();if(y-k<b)return;k=y,DX(j(E,h))}async function u(E,h){if(!E)return;let y=O({status:h.status,requestId:h.requestId,usage:h.usage,...h.fields,complete:h.complete??!0});try{return await tW(E.responseFile,`${JSON.stringify(y,null,2)}
4
4
  `,Y.stageName),E.responseFile}catch(n){if(n instanceof Q8&&(L1||n.code==="ERR_PRIVATE_FILES_SECURITY"))throw n;G?.warn("response dump failed",{id:E.id,error:n instanceof Error?n.message:String(n)});return}}return{isEnabled:()=>J,setEnabled:(E)=>{J=E},dump:P,dumpResponse:u,sweep:(E)=>DX(j(U(),E))}}var wX=H0("dump"),h1="x-cortexkit-openai-auth-dump-session",Qz=["chatgpt-account-id","email","org_name","organization_name"],Gz=["tools"];function jY(Y){return Xz("sha256").update(JSON.stringify(Y)).digest("hex")}function $z(Y){return Y!=null&&typeof Y==="object"&&"type"in Y&&typeof Y.type==="string"?Y.type:"unknown"}function Wz(Y){let J=Array.isArray(Y.input)?Y.input:[],X=Array.isArray(Y.tools)?Y.tools:[],Q=Y.client_metadata!=null&&typeof Y.client_metadata==="object"&&!Array.isArray(Y.client_metadata)?Y.client_metadata:void 0;return{model:typeof Y.model==="string"?Y.model:void 0,stream:Y.stream,generate:Y.generate,store:Y.store,previousResponseID:typeof Y.previous_response_id==="string"?Y.previous_response_id:void 0,promptCacheKey:typeof Y.prompt_cache_key==="string"?Y.prompt_cache_key:void 0,reasoning:Y.reasoning,inputCount:J.length,inputHash:jY(J),inputBytes:JSON.stringify(J).length,firstInputHash:J[0]===void 0?null:jY(J[0]),toolsCount:X.length,toolTypes:X.map($z),toolsHash:jY(X),clientMetadataKeys:Q?Object.keys(Q).sort():[]}}var FY;function SX(){return FY=o0().dumpMaxBytes,CX({dir:()=>o0().dumpDir,maxBytes:FY,logger:wX,secretKeys:Qz,schemaKeys:Gz,summarize:Wz})}var s8=SX();async function A6(Y){if(!t6()){s8.setEnabled(!1);return}if(o0().dumpMaxBytes!==FY)s8=SX();s8.setEnabled(!0);let J=typeof Y.bodyText==="function"?Y.bodyText():Y.bodyText;await s8.dump({session:Y.sessionID,channel:Y.transport,phase:Y.phase,bodyText:J,accountId:Y.accountId,url:Y.url,method:Y.method,headers:Y.headers,status:Y.status,error:Y.error})}async function e1(Y){if(!t6())return;wX.debug("diagnostic",Y)}function T6(Y){return JSON.stringify(DY(Y))??"undefined"}function DY(Y){if(Array.isArray(Y))return Y.map(DY);if(!r(Y))return Y;return Object.fromEntries(Object.keys(Y).sort().map((J)=>[J,DY(Y[J])]))}var zz=512,Hz=2097152;function OY(Y,J){if(typeof Y==="function"||typeof J==="function")return!1;if(J!==null&&typeof J==="object"&&Object.hasOwn(J,"toJSON")&&typeof J.toJSON==="function")return!1;if(Y===J)return!0;if(Array.isArray(Y))return Array.isArray(J)&&Y.length===J.length&&Y.every(($,W)=>OY($,J[W]));if(Y===null||J===null||typeof Y!=="object"||typeof J!=="object"||Array.isArray(J))return!1;let X=Y,Q=J,G=Object.keys(X);return G.length===Object.keys(Q).length&&G.every(($)=>Object.prototype.propertyIsEnumerable.call(Q,$)&&OY(X[$],Q[$]))}function Y6(Y,J){let X=[],Q=[],G=0;for(let $=0;$<Y.length;$++){let W=J?.texts[$],H=W!==void 0&&OY(J?.snapshots[$],Y[$]),K=H?W:T6(Y[$]);X.push(K),Q.push(H?J?.snapshots[$]:K==="undefined"?void 0:JSON.parse(K)),G+=K.length}return{texts:X,snapshots:Q,retainable:Y.length<=zz&&G<=Hz}}function G8(Y){return Y.retainable?Y:void 0}function $8(Y,J){if(Y.texts.length>J.texts.length)return;for(let X=0;X<Y.texts.length;X++)if(Y.texts[X]!==J.texts[X])return;return Y.texts.length}var IX=new Set(["gpt-5.6-sol","gpt-5.6-terra","gpt-5.6-luna","gpt-6-astra","gpt-6-sol","gpt-6-luna","gpt-6.1-sol","gpt-6.1-terra"]),Kz="terminal_resize_reflow",a8="0.159.0",bX=`codex_exec/${a8} (Debian 12.0.0; aarch64) unknown (codex_exec; ${a8})`,Uz="seccomp",R6="x-openai-auth-agent";function Zz(Y){if(typeof Y!=="string")return;try{let J=JSON.parse(Y);return typeof J==="object"&&J!==null&&!Array.isArray(J)?J:void 0}catch{return}}function W8(Y,J){return r(Y)&&(Y.type==="message"||("role"in Y))&&Y.role===J}function Vz(Y,J,X){if(!Y.input)return J.length>0;let Q=Y.canonicalInput??Y6(Y.input);if($8(Q,X)===void 0)return!0;return J.slice(Y.input.length).some(($)=>W8($,"user")||W8($,"developer"))}function Bz(Y,J,X){let Q=Array.isArray(J?.input)?J.input:void 0,G=Q?Y6(Q,Y.canonicalInput):void 0;if(Q&&G&&(Vz(Y,Q,G)||!Y.turnID))Y.turnID=(X?.uuid??J6)(),Y.turnStartedAt=(X?.now??Date.now)();else if(!Y.turnStartedAt)Y.turnStartedAt=(X?.now??Date.now)();if(Q&&G)Y.input=Q.slice(),Y.canonicalInput=G8(G)}function kX(Y){let J=Y.headers.get(R6);if(Y.headers.delete(R6),!Y.metadata)return{init:Y.init};let X=Zz(Y.init?.body),Q=Y.runtime?.now??Date.now;if(!Y.skipTurnUpdate){if(!Y.websocket)Bz(Y.metadata,X,Y.runtime);else if(!Y.metadata.turnStartedAt)Y.metadata.turnStartedAt=Q();if(!Y.metadata.turnStartedAt)Y.metadata.turnStartedAt=Q()}let G=JSON.stringify({session_id:Y.metadata.threadID,thread_id:Y.metadata.threadID,thread_source:"user",turn_id:Y.metadata.turnID,sandbox:Uz,turn_started_at_unix_ms:Y.metadata.turnStartedAt,request_kind:"turn",window_id:Y.metadata.windowID});if(Y.headers.set("originator","codex_exec"),Y.websocket)Y.headers.delete("accept"),Y.headers.delete("content-type");else Y.headers.set("accept","text/event-stream");if(Y.headers.set("session-id",Y.metadata.threadID),Y.headers.delete("x-session-id"),Y.headers.delete("x-session-affinity"),Y.headers.set("thread-id",Y.metadata.threadID),Y.headers.set("x-codex-window-id",Y.metadata.windowID),Y.headers.set("x-client-request-id",Y.metadata.threadID),Y.headers.set("x-codex-beta-features",Kz),Y.headers.set("x-codex-turn-metadata",G),Y.headers.set("user-agent",bX),Y.headers.set("version",a8),Y.dumpSessionID)Y.headers.set(h1,Y.dumpSessionID);let $=X;if(!$)return{init:Y.init};let W=Y.responsesLite&&typeof $.model==="string"&&IX.has($.model);if(W&&!Y.websocket)Y.headers.set("x-openai-internal-codex-responses-lite","true");if($.prompt_cache_key=Y.metadata.threadID,$.parallel_tool_calls??=!0,Array.isArray($.tools))$.tools=$.tools.map(Lz);if(Y.applyEffort?.($,Y.metadata,J),W)Y.rewriteLite($);let H={...typeof $.client_metadata==="object"&&$.client_metadata!==null?$.client_metadata:{},"x-codex-installation-id":Y.installationID,"x-codex-window-id":Y.metadata.windowID};if(Y.websocket){if(H["x-codex-turn-metadata"]=G,H["x-codex-ws-stream-request-start-ms"]=String(Q()),W)H.ws_request_header_x_openai_internal_codex_responses_lite="true"}return $.client_metadata=H,Y.headers.delete("content-length"),Y.headers.delete("Content-Length"),{init:{...Y.init,body:JSON.stringify(t1($))}}}function Lz(Y){if(!r(Y)||Y.type!=="function")return Y;let J=r(Y.parameters)&&"$schema"in Y.parameters?(()=>{let{$schema:K,...U}=Y.parameters;return U})():Y.parameters,{type:X,name:Q,description:G,strict:$,parameters:W,...H}=Y;return{type:X,name:Q,description:G,strict:$??!1,parameters:J,...H}}import{lstat as xX,opendir as Nz}from"node:fs/promises";import{join as jz}from"node:path";async function hX(Y){try{if(!(await xX(Y)).isDirectory())return;let J=0,X=!1,Q=[],G=async($)=>{try{let W=await xX(jz(Y,$));if(W.isFile())J+=W.size}catch(W){if(W.code!=="ENOENT")X=!0}};for await(let $ of await Nz(Y)){if(!$.isFile())continue;if(Q.push(G($.name)),Q.length===32)await Promise.all(Q),Q=[]}return await Promise.all(Q),X?void 0:J}catch(J){return J.code==="ENOENT"?0:void 0}}function _Y(Y){let J=["B","KiB","MiB","GiB","TiB","PiB"],X=0,Q=Y;while(Q>=1024&&X<J.length-1)Q/=1024,X++;return`${Number(Q.toFixed(1))} ${J[X]}`}var PY={rpcRoot:"openai-auth",directoryPrefix:fX,registrationSessionId:"process"},t8=new Map;function hN(Y,J){if(J?.aborted)return Promise.resolve(!1);if(qY(Y))return Promise.resolve(!0);return new Promise((X)=>{let Q=(H)=>{if(clearTimeout($),J?.removeEventListener("abort",G),W.delete(Q),W.size===0)t8.delete(Y);X(H)},G=()=>Q(!1),$=setTimeout(()=>Q(!1),2000),W=t8.get(Y)??new Set;t8.set(Y,W),W.add(Q),J?.addEventListener("abort",G,{once:!0})})}function e8(Y,J){vX(PY,Y,J)}function mX(Y=0,J){let X=yX(PY,Y,J);if(J!==void 0)for(let Q of t8.get(J)??[])Q(!0);return X}function qY(Y){return gX(PY,Y)}var Y9=H0("commands");function C6(Y){return{configPath:Y.accountStoragePath,statePath:Y.accountStatePath}}function EY(Y){return`${String(Y.startHour).padStart(2,"0")}-${String(Y.endHour).padStart(2,"0")}`}function Fz(Y){let J=/^(\d{1,2})-(\d{1,2})$/.exec(Y.trim());if(!J)return{ok:!1,reason:"expected HH-HH, e.g. 9-18 or 22-6"};let X=Number(J[1]),Q=Number(J[2]);if(X>23||Q>23||X===Q)return{ok:!1,reason:"hours must be integers 0-23 and start ≠ end"};return{ok:!0,startHour:X,endHour:Q}}var Dz="Sustain keeps main-agent sessions warming past the idle cap for this process. Clock windows still apply.\n\nBefore enabling sustain with Magic Context, set a non-expiring `cache_ttl` for models used by main sessions; elapsed-time cold-cache assumptions are no longer valid.";function Oz(Y){let J=(X)=>n1(Y.store(),E1(C6(Y)),(Q)=>{let G={...Q.cacheKeep??{}};X(G),Q.cacheKeep=G});return{title:"Cache",build:async()=>{let X=Y.cacheKeepManager;if(!X)return{lines:["Keep-warm unavailable"]};let Q=X9(await Y.loadAccounts(C6(Y))),G=Q?.enabled===!0,$=Q?.subagents===!0,W=X.status(),H=W.window?EY(W.window):"always (no window)";return{lines:[`Keep-warm ${G?"on":"off"} · ${W.tracked===0?"no sessions":`${W.tracked} session${W.tracked===1?"":"s"}`}`,`Timer ${W.running?"armed":"idle"} · subagents ${$?"on":"off"} · sustain ${W.sustain?"on":"off"}`,`Window ${H}`,...Y.cacheKeepNotice?[Y.cacheKeepNotice]:[],`TTL ${Math.round(W.ttlMs/1000)}s · lead ${Math.round(W.leadMs/1000)}s · idle cap ${Math.round(W.maxIdleWarmMs/60000)}min (subagents ${Math.round(W.maxSubagentIdleMs/60000)}min)`],items:W.targets.map((K)=>({id:K.sessionKey,label:K.sessionKey,group:"Sessions",detail:[K.accountId??"main",`expires in ${Math.ceil((K.cacheExpiresAt-W.generatedAt)/1000)}s`,...K.lastWarmedAt?[`last warm ${Math.ceil((W.generatedAt-K.lastWarmedAt)/1000)}s ago`]:[],...K.backoffUntil&&K.backoffUntil>W.generatedAt?[`backoff ${Math.ceil((K.backoffUntil-W.generatedAt)/1000)}s`]:[]].join(" · ")})),actions:[{id:"enabled",label:G?"Turn keep-warm off":"Turn keep-warm on",knobs:[{kind:"toggle",id:"enabled",label:"Keep-warm",value:!G}],run:async({values:K})=>{let U=K.enabled===!0;if(await J((V)=>{V.enabled=U}),Y.setCacheKeepEnabled?.(U),U)X.start();else X.stop();return Y9.info(U?"cachekeep enabled":"cachekeep disabled"),U?`Keep-warm is on. TTL ${Math.round(W.ttlMs/1000)}s, idle cap ${Math.round(W.maxIdleWarmMs/60000)}min.`:"Keep-warm is off."}},{id:"subagents",label:$?"Stop warming subagent sessions":"Warm subagent sessions too",knobs:[{kind:"toggle",id:"subagents",label:"Subagent warming",value:!$}],run:async({values:K})=>{let U=K.subagents===!0;return await J((V)=>{V.subagents=U}),Y.setCacheKeepSubagents?.(U),`Subagent warming is ${U?"on":"off"}.`}},{id:"sustain",label:W.sustain?"Stop sustaining main sessions":"Sustain main sessions past the idle cap",knobs:[{kind:"toggle",id:"sustain",label:"Sustain",value:!W.sustain}],run:async({values:K})=>{let U=K.sustain===!0;return await J((V)=>{V.sustain=U}),Y.setCacheKeepSustain?.(U),U?Dz:"Main-agent sessions again stop warming at the configured idle cap."}},{id:"window",label:"Set the warm window",description:"Warm only between these local hours, e.g. 9-18 or 22-6. Leave it empty to warm at any hour.",knobs:[{kind:"text",id:"window",label:"Window (HH-HH)",placeholder:"9-18",...W.window?{value:EY(W.window)}:{}}],run:async({values:K})=>{let U=K.window;if(typeof U!=="string"||U.trim()==="")return await J((B)=>{delete B.startHour,delete B.endHour}),Y.setCacheKeepWindow?.(void 0),"Warm window cleared: keep-warm warms at any hour (within idle caps).";let V=Fz(U);if(!V.ok)return{ok:!1,text:`Invalid window: ${V.reason}`};let{startHour:O,endHour:L}=V;return await J((B)=>{B.startHour=O,B.endHour=L}),Y.setCacheKeepWindow?.({startHour:O,endHour:L}),`Warming limited to ${EY(V)} local hours.`}}]}}}}var cX=["error","warn","info","debug","trace"];function _z(Y){return{title:"Diagnostics",build:async()=>{let J=o0(),X=t6(),G=(await Y.loadAccounts(C6(Y)))?.logging?.level??"info",$=X?await hX(J.dumpDir):void 0,W=$===void 0?"size unavailable":_Y($),H=J.dumpMaxBytes===0?"no cap":`${_Y(J.dumpMaxBytes)} cap`,K=Y.layoutNotice?.();return{lines:[X?`Dumps on (${W} / ${H})`:"Dumps off",`Dump directory: ${J.dumpDir}`,`Log level: ${G}`,...K?[K]:[]],actions:[{id:"dump",label:X?"Turn request dumps off":"Turn request dumps on",knobs:[{kind:"toggle",id:"enabled",label:"Request dumps",value:!X}],run:async({values:U})=>{let V=U.enabled===!0;await n1(Y.store(),E1(C6(Y)),(L)=>{L.dump={...L.dump??{},enabled:V}});let O=yJ();return Y9.info(V?"request dump enabled":"request dump disabled"),V?`Request dumps are on, written to ${O.dumpDir}.
@@ -1,3 +1,3 @@
1
- import{Gb as X,Ib as V}from"./index-3sda8acd.js";import{randomUUID as Z}from"node:crypto";import{chmod as $,mkdir as G,readFile as H,rename as L,rm as T,stat as f,writeFile as g}from"node:fs/promises";import{dirname as k,resolve as w}from"node:path";var x="(no OpenCode 1 logins on this machine)";function C(b=process.env){return X(b)}async function Q(b){let z;try{z=await H(b,"utf8")}catch(q){if(q.code==="ENOENT")return;throw q}let j=JSON.parse(z);if(!j||typeof j!=="object"||Array.isArray(j))throw Error(`${b} does not hold a JSON object`);return j}function R(b){return b===void 0?void 0:JSON.stringify(b)}async function D(b){try{return(await f(b)).mode&511}catch(z){if(z.code==="ENOENT")return;throw z}}function _(b=C()){let z=new Map;return{path:w(b),async get(j){let q=(await Q(b))?.[j.path.id];return z.set(j.path.id,R(q)),q},async set(j){let q=j.path.id,W=await D(b),J=await Q(b)??{};if(!z.has(q)||z.get(q)!==R(J[q]))throw new V;J[q]=j.body,await G(k(b),{recursive:!0});let B=`${b}.${Z()}.tmp`;try{await g(B,`${JSON.stringify(J,null,2)}
1
+ import{Gb as X,Ib as V}from"./index-xx3k2qbv.js";import{randomUUID as Z}from"node:crypto";import{chmod as $,mkdir as G,readFile as H,rename as L,rm as T,stat as f,writeFile as g}from"node:fs/promises";import{dirname as k,resolve as w}from"node:path";var x="(no OpenCode 1 logins on this machine)";function C(b=process.env){return X(b)}async function Q(b){let z;try{z=await H(b,"utf8")}catch(q){if(q.code==="ENOENT")return;throw q}let j=JSON.parse(z);if(!j||typeof j!=="object"||Array.isArray(j))throw Error(`${b} does not hold a JSON object`);return j}function R(b){return b===void 0?void 0:JSON.stringify(b)}async function D(b){try{return(await f(b)).mode&511}catch(z){if(z.code==="ENOENT")return;throw z}}function _(b=C()){let z=new Map;return{path:w(b),async get(j){let q=(await Q(b))?.[j.path.id];return z.set(j.path.id,R(q)),q},async set(j){let q=j.path.id,W=await D(b),J=await Q(b)??{};if(!z.has(q)||z.get(q)!==R(J[q]))throw new V;J[q]=j.body,await G(k(b),{recursive:!0});let B=`${b}.${Z()}.tmp`;try{await g(B,`${JSON.stringify(J,null,2)}
2
2
  `,{mode:W??384}),await $(B,W??384),await L(B,b)}catch(Y){throw await T(B,{force:!0}).catch(()=>{}),Y}return z.set(q,R(j.body)),!0},async all(){let j=await Q(b);if(!j||Object.keys(j).length===0)return{[x]:!0};return j}}}
3
3
  export{_ as c};
@@ -1,2 +1,2 @@
1
- import{$e as O,_e as w,af as k}from"./index-2esezxst.js";import{sf as h,xf as D}from"./index-hz6f9gpq.js";import{Df as j}from"./index-g3gbp1m4.js";class g extends Error{operation;constructor(f){super(`a ${f} on a strict notification scope needs a session id`);this.name="RpcSessionRequiredError",this.operation=f}}function M(f){return typeof f==="string"&&f.length>0}var U=new Map;function y(f){let x=JSON.stringify([f.rpcRoot,f.directoryPrefix,f.registrationSessionId,...f.requireSession===!0?["strict"]:[]]),z=U.get(x);if(!z)z={queue:[],nextId:1,lastDrainAtBySession:new Map,lastDrainAtAny:0},U.set(x,z);return z}var m=100,t=3000;function i(f,x,z){if(f.requireSession===!0&&!M(z))throw new g("push");let H=y(f);if(H.queue.push({id:H.nextId++,type:"open-dialog",payload:x,sessionId:z}),H.queue.length>m)H.queue=H.queue.slice(-m)}function n(f,x=0,z){if(f.requireSession===!0&&!M(z))throw new g("drain");let H=y(f),Y=Date.now();if(H.lastDrainAtAny=Y,z!==void 0)H.lastDrainAtBySession.set(z,Y);let Z=f.sessionlessDrain==="broadcast-only",L=(B)=>z===void 0?!Z||B.sessionId===void 0:B.sessionId===void 0||B.sessionId===z;if(x>0)H.queue=H.queue.filter((B)=>{if(B.id>x)return!0;if(z===void 0)return!Z||B.sessionId!==void 0;return B.sessionId!==z});return H.queue.filter((B)=>B.id>x&&L(B))}function a(f,x){let z=Date.now(),H=y(f),Y=x!==void 0?H.lastDrainAtBySession.get(x)??0:f.sessionlessDrain==="broadcast-only"?H.lastDrainAtAny:0;return Y>0&&z-Y<t}import{randomBytes as v,timingSafeEqual as q}from"node:crypto";import{unlink as u}from"node:fs/promises";import{createServer as I}from"node:http";import{join as l}from"node:path";class N extends Error{status;constructor(f,x){if(!Number.isInteger(f)||f<400||f>499)throw RangeError(`RpcRequestError status must be 4xx, got ${f}`);super(x);this.name="RpcRequestError",this.status=f}}var E=1e6;class _ extends Error{declaredOversize;constructor(f){super("body too large");this.declaredOversize=f}}function p(f){return new Promise((x,z)=>{let H=(B=!1)=>{f.removeAllListeners("data"),f.on("data",()=>{}),f.resume(),z(new _(B))},Y=Number(f.headers["content-length"]);if(Number.isFinite(Y)&&Y>E){H(!0);return}let Z=[],L=0;f.on("data",(B)=>{if(L+=B.length,L>E){H();return}Z.push(B)}),f.on("end",()=>x(Buffer.concat(Z).toString("utf8"))),f.on("error",z)})}class S extends Error{}async function c(f,x){let z,H=new Promise((Y,Z)=>{z=setTimeout(()=>Z(new S("apply deadline exceeded")),x),z.unref?.()});f.catch(()=>{});try{return await Promise.race([f,H])}finally{clearTimeout(z)}}function d(f,x){if(!f?.startsWith("Bearer "))return!1;let z=Buffer.from(f.slice(7)),H=Buffer.from(x);return z.length===H.length&&q(z,H)}async function Bf(f){if(typeof f.drain==="function"===(typeof f.drainAsync==="function"))throw TypeError("exactly one of drain or drainAsync must be provided");let x=f.log??{warn(){},debug(){}},z=v(32).toString("hex"),H=f.timeoutMs??90000,Y=f.receiptTimeoutMs??2000,Z=!1,L=new Set,B=I((V,J)=>{V.setTimeout(H,()=>{V.socket.destroy()}),T(V,J)});B.on("connection",(V)=>{L.add(V),V.once("close",()=>L.delete(V))}),B.requestTimeout=Y,B.headersTimeout=Y;async function T(V,J){let G=(X,b,C={})=>{if(J.headersSent||J.writableEnded||J.destroyed)return;J.writeHead(X,{"content-type":"application/json",...C}),J.end(JSON.stringify(b))};try{let X=new URL(V.url??"/","http://127.0.0.1").pathname;if(V.method==="GET"&&X==="/health")return G(200,{ok:!0});if(V.method!=="POST"||!X.startsWith("/rpc/"))return G(404,{error:"not found"});if(!d(V.headers.authorization,z))return G(401,{error:"unauthorized"});let b=X.slice(5),C;try{C=await p(V)}catch($){if(!($ instanceof _))throw $;let P=V.socket;if(J.once("finish",()=>{P.end();let A=setTimeout(()=>P.destroy(),2000);if(A.unref(),V.once("end",()=>P.destroy()),P.once("close",()=>clearTimeout(A)),V.complete)P.destroy()}),!$.declaredOversize&&!V.complete){if(J.headersSent||J.writableEnded||J.destroyed)return;let A=JSON.stringify({error:"body too large"});J.writeHead(413,{"content-type":"application/json","content-length":Buffer.byteLength(A),connection:"close"}),J.write(A),V.once("end",()=>J.end());return}return G(413,{error:"body too large"},{connection:"close"})}let F;try{F=JSON.parse(C||"{}")}catch{return G(400,{error:"invalid json"})}if(b==="pending-notifications"){let $;try{if(f.parsePending)$=f.parsePending(F);else{if(!F||typeof F!=="object"||Array.isArray(F))throw Error("invalid params");let K=F;if(f.requireSession===!0&&!M(K.sessionId))return G(400,{error:"session required"});if("lastReceivedId"in K&&(typeof K.lastReceivedId!=="number"||!Number.isSafeInteger(K.lastReceivedId)||K.lastReceivedId<0)||"sessionId"in K&&typeof K.sessionId!=="string")throw Error("invalid params");$={lastReceivedId:Number(K.lastReceivedId??0),sessionId:typeof K.sessionId==="string"?K.sessionId:void 0}}}catch(K){if(K instanceof N)throw K;return G(400,{error:"invalid params"})}let{lastReceivedId:P,sessionId:A}=$;if(f.requireSession===!0&&!M(A))return G(400,{error:"session required"});if(A===void 0&&!Z)Z=!0,x.warn("rpc notification drain missing session id",{pid:process.pid});let W;if(f.drainAsync)try{W=await f.drainAsync(P,A)}catch(K){return x.warn("rpc notification drain failed",{pid:process.pid,error:K instanceof Error?K.message:String(K)}),G(500,{error:"drain failed"})}else W=f.drain?.(P,A);return G(200,{messages:W})}if(b==="apply"){let $=Promise.resolve(f.apply(F)),P=f.applyDeadlineMs===void 0?await $:await c($,f.applyDeadlineMs);return G(200,P)}return G(404,{error:"unknown method"})}catch(X){if(X instanceof N)return x.debug("rpc request refused",{pid:process.pid,status:X.status}),G(X.status,{error:X.message});if(X instanceof S)return x.warn("rpc apply deadline exceeded",{pid:process.pid,deadlineMs:f.applyDeadlineMs}),G(504,{error:"handler deadline exceeded"});x.warn("rpc request failed",{pid:process.pid,error:X instanceof Error?X.message:String(X)}),G(500,{error:"internal error"})}}let Q=await new Promise((V,J)=>{B.on("error",J),B.listen(0,"127.0.0.1",()=>{let G=B.address();if(G&&typeof G==="object")V(G.port);else J(Error("no port"))})});if(B.unref(),f.sweepRoot)try{await k(f.sweepRoot,f.dir,f.isManagedDir,x)}catch(V){x.warn("rpc state sweep failed",{pid:process.pid,error:V instanceof Error?V.message:String(V)})}try{await O(f.dir,{port:Q,token:z,pid:process.pid},{secureDir:f.secureDir}),x.debug("rpc server pid",{pid:process.pid,rpcPort:Q})}catch(V){throw await new Promise((J)=>B.close(()=>J())),V}return{port:Q,token:z,async stop(){await new Promise((G)=>{B.closeAllConnections?.(),B.close(()=>G());for(let X of L)X.destroy()});let V=l(f.dir,`port-${process.pid}.json`),J=await D(V).then((G)=>JSON.parse(G)).catch((G)=>{if(G instanceof h&&G.code!=="ENOENT")throw G;return});if(J?.port===Q&&J.token===z)await u(V).catch(()=>{})}}}async function Hf(f,x,z){let H=globalThis,Y=Symbol.for(f),Z=H[Y]??{servers:new Map,pending:new Map};H[Y]=Z;let{servers:L,pending:B}=Z,T=B.get(x)??Promise.resolve(),Q,V=T.catch(()=>{}).then(async()=>{let G=L.get(x);if(G){if(await G.stop(),L.get(x)===G)L.delete(x)}Q=await z(),L.set(x,Q)});B.set(x,V);try{await V}finally{if(B.get(x)===V)B.delete(x)}let J=Q;if(!J)throw Error("RPC server failed to start");return{server:J,release:async()=>{if(L.get(x)!==J)return;if(await J.stop(),L.get(x)===J)L.delete(x)}}}var R="1.9.3";function bf(f,x,z){let H={...x,version:R};return O(f,H,z)}var Cf=w(j);
1
+ import{$e as O,_e as w,af as k}from"./index-2esezxst.js";import{sf as h,xf as D}from"./index-hz6f9gpq.js";import{Df as j}from"./index-g3gbp1m4.js";class g extends Error{operation;constructor(f){super(`a ${f} on a strict notification scope needs a session id`);this.name="RpcSessionRequiredError",this.operation=f}}function M(f){return typeof f==="string"&&f.length>0}var U=new Map;function y(f){let x=JSON.stringify([f.rpcRoot,f.directoryPrefix,f.registrationSessionId,...f.requireSession===!0?["strict"]:[]]),z=U.get(x);if(!z)z={queue:[],nextId:1,lastDrainAtBySession:new Map,lastDrainAtAny:0},U.set(x,z);return z}var m=100,t=3000;function i(f,x,z){if(f.requireSession===!0&&!M(z))throw new g("push");let H=y(f);if(H.queue.push({id:H.nextId++,type:"open-dialog",payload:x,sessionId:z}),H.queue.length>m)H.queue=H.queue.slice(-m)}function n(f,x=0,z){if(f.requireSession===!0&&!M(z))throw new g("drain");let H=y(f),Y=Date.now();if(H.lastDrainAtAny=Y,z!==void 0)H.lastDrainAtBySession.set(z,Y);let Z=f.sessionlessDrain==="broadcast-only",L=(B)=>z===void 0?!Z||B.sessionId===void 0:B.sessionId===void 0||B.sessionId===z;if(x>0)H.queue=H.queue.filter((B)=>{if(B.id>x)return!0;if(z===void 0)return!Z||B.sessionId!==void 0;return B.sessionId!==z});return H.queue.filter((B)=>B.id>x&&L(B))}function a(f,x){let z=Date.now(),H=y(f),Y=x!==void 0?H.lastDrainAtBySession.get(x)??0:f.sessionlessDrain==="broadcast-only"?H.lastDrainAtAny:0;return Y>0&&z-Y<t}import{randomBytes as v,timingSafeEqual as q}from"node:crypto";import{unlink as u}from"node:fs/promises";import{createServer as I}from"node:http";import{join as l}from"node:path";class N extends Error{status;constructor(f,x){if(!Number.isInteger(f)||f<400||f>499)throw RangeError(`RpcRequestError status must be 4xx, got ${f}`);super(x);this.name="RpcRequestError",this.status=f}}var E=1e6;class _ extends Error{declaredOversize;constructor(f){super("body too large");this.declaredOversize=f}}function p(f){return new Promise((x,z)=>{let H=(B=!1)=>{f.removeAllListeners("data"),f.on("data",()=>{}),f.resume(),z(new _(B))},Y=Number(f.headers["content-length"]);if(Number.isFinite(Y)&&Y>E){H(!0);return}let Z=[],L=0;f.on("data",(B)=>{if(L+=B.length,L>E){H();return}Z.push(B)}),f.on("end",()=>x(Buffer.concat(Z).toString("utf8"))),f.on("error",z)})}class S extends Error{}async function c(f,x){let z,H=new Promise((Y,Z)=>{z=setTimeout(()=>Z(new S("apply deadline exceeded")),x),z.unref?.()});f.catch(()=>{});try{return await Promise.race([f,H])}finally{clearTimeout(z)}}function d(f,x){if(!f?.startsWith("Bearer "))return!1;let z=Buffer.from(f.slice(7)),H=Buffer.from(x);return z.length===H.length&&q(z,H)}async function Bf(f){if(typeof f.drain==="function"===(typeof f.drainAsync==="function"))throw TypeError("exactly one of drain or drainAsync must be provided");let x=f.log??{warn(){},debug(){}},z=v(32).toString("hex"),H=f.timeoutMs??90000,Y=f.receiptTimeoutMs??2000,Z=!1,L=new Set,B=I((V,J)=>{V.setTimeout(H,()=>{V.socket.destroy()}),T(V,J)});B.on("connection",(V)=>{L.add(V),V.once("close",()=>L.delete(V))}),B.requestTimeout=Y,B.headersTimeout=Y;async function T(V,J){let G=(X,b,C={})=>{if(J.headersSent||J.writableEnded||J.destroyed)return;J.writeHead(X,{"content-type":"application/json",...C}),J.end(JSON.stringify(b))};try{let X=new URL(V.url??"/","http://127.0.0.1").pathname;if(V.method==="GET"&&X==="/health")return G(200,{ok:!0});if(V.method!=="POST"||!X.startsWith("/rpc/"))return G(404,{error:"not found"});if(!d(V.headers.authorization,z))return G(401,{error:"unauthorized"});let b=X.slice(5),C;try{C=await p(V)}catch($){if(!($ instanceof _))throw $;let P=V.socket;if(J.once("finish",()=>{P.end();let A=setTimeout(()=>P.destroy(),2000);if(A.unref(),V.once("end",()=>P.destroy()),P.once("close",()=>clearTimeout(A)),V.complete)P.destroy()}),!$.declaredOversize&&!V.complete){if(J.headersSent||J.writableEnded||J.destroyed)return;let A=JSON.stringify({error:"body too large"});J.writeHead(413,{"content-type":"application/json","content-length":Buffer.byteLength(A),connection:"close"}),J.write(A),V.once("end",()=>J.end());return}return G(413,{error:"body too large"},{connection:"close"})}let F;try{F=JSON.parse(C||"{}")}catch{return G(400,{error:"invalid json"})}if(b==="pending-notifications"){let $;try{if(f.parsePending)$=f.parsePending(F);else{if(!F||typeof F!=="object"||Array.isArray(F))throw Error("invalid params");let K=F;if(f.requireSession===!0&&!M(K.sessionId))return G(400,{error:"session required"});if("lastReceivedId"in K&&(typeof K.lastReceivedId!=="number"||!Number.isSafeInteger(K.lastReceivedId)||K.lastReceivedId<0)||"sessionId"in K&&typeof K.sessionId!=="string")throw Error("invalid params");$={lastReceivedId:Number(K.lastReceivedId??0),sessionId:typeof K.sessionId==="string"?K.sessionId:void 0}}}catch(K){if(K instanceof N)throw K;return G(400,{error:"invalid params"})}let{lastReceivedId:P,sessionId:A}=$;if(f.requireSession===!0&&!M(A))return G(400,{error:"session required"});if(A===void 0&&!Z)Z=!0,x.warn("rpc notification drain missing session id",{pid:process.pid});let W;if(f.drainAsync)try{W=await f.drainAsync(P,A)}catch(K){return x.warn("rpc notification drain failed",{pid:process.pid,error:K instanceof Error?K.message:String(K)}),G(500,{error:"drain failed"})}else W=f.drain?.(P,A);return G(200,{messages:W})}if(b==="apply"){let $=Promise.resolve(f.apply(F)),P=f.applyDeadlineMs===void 0?await $:await c($,f.applyDeadlineMs);return G(200,P)}return G(404,{error:"unknown method"})}catch(X){if(X instanceof N)return x.debug("rpc request refused",{pid:process.pid,status:X.status}),G(X.status,{error:X.message});if(X instanceof S)return x.warn("rpc apply deadline exceeded",{pid:process.pid,deadlineMs:f.applyDeadlineMs}),G(504,{error:"handler deadline exceeded"});x.warn("rpc request failed",{pid:process.pid,error:X instanceof Error?X.message:String(X)}),G(500,{error:"internal error"})}}let Q=await new Promise((V,J)=>{B.on("error",J),B.listen(0,"127.0.0.1",()=>{let G=B.address();if(G&&typeof G==="object")V(G.port);else J(Error("no port"))})});if(B.unref(),f.sweepRoot)try{await k(f.sweepRoot,f.dir,f.isManagedDir,x)}catch(V){x.warn("rpc state sweep failed",{pid:process.pid,error:V instanceof Error?V.message:String(V)})}try{await O(f.dir,{port:Q,token:z,pid:process.pid},{secureDir:f.secureDir}),x.debug("rpc server pid",{pid:process.pid,rpcPort:Q})}catch(V){throw await new Promise((J)=>B.close(()=>J())),V}return{port:Q,token:z,async stop(){await new Promise((G)=>{B.closeAllConnections?.(),B.close(()=>G());for(let X of L)X.destroy()});let V=l(f.dir,`port-${process.pid}.json`),J=await D(V).then((G)=>JSON.parse(G)).catch((G)=>{if(G instanceof h&&G.code!=="ENOENT")throw G;return});if(J?.port===Q&&J.token===z)await u(V).catch(()=>{})}}}async function Hf(f,x,z){let H=globalThis,Y=Symbol.for(f),Z=H[Y]??{servers:new Map,pending:new Map};H[Y]=Z;let{servers:L,pending:B}=Z,T=B.get(x)??Promise.resolve(),Q,V=T.catch(()=>{}).then(async()=>{let G=L.get(x);if(G){if(await G.stop(),L.get(x)===G)L.delete(x)}Q=await z(),L.set(x,Q)});B.set(x,V);try{await V}finally{if(B.get(x)===V)B.delete(x)}let J=Q;if(!J)throw Error("RPC server failed to start");return{server:J,release:async()=>{if(L.get(x)!==J)return;if(await J.stop(),L.get(x)===J)L.delete(x)}}}var R="1.9.4";function bf(f,x,z){let H={...x,version:R};return O(f,H,z)}var Cf=w(j);
2
2
  export{i as Se,n as Te,a as Ue,Bf as Ve,Hf as We,R as Xe,bf as Ye,Cf as Ze};