@cortexkit/opencode-openai-auth 1.8.1 → 1.8.3

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,14 +1,14 @@
1
1
  #!/usr/bin/env node
2
- import{c as m0}from"./index-fhcnxrtz.js";import{Aa as f,Ba as B,Ca as E,Kb as u0,gb as h0,na as f0,oa as S,pa as G0,yb as d0,za as A0}from"./index-97cz7kyq.js";import{md as y0,sd as V0,ud as d,vd as w,wd as E0,xd as m,yd as U0}from"./index-b7p76qqa.js";import"./index-73z9ftrg.js";import"./index-ww8w9edq.js";import"./index-21yxzeet.js";import{Ye as J0,cf as w0,ef as L0,hf as g0}from"./index-h1r8cbet.js";import"./index-mg4w434p.js";import"./index-c50p5mem.js";import"./index-hpnj460b.js";import{spawn as l0}from"node:child_process";var k=4096,a0=1048576;class z0{buffer=Buffer.alloc(k);start=0;length=0;truncated=!1;get didTruncate(){return this.truncated}push(G){if(G.length>=k){if(G.length>k||this.length>0)this.truncated=!0;G.copy(this.buffer,0,G.length-k),this.start=0,this.length=k;return}let z=Math.max(0,this.length+G.length-k);if(z>0)this.truncated=!0;this.start=(this.start+z)%k,this.length-=z;let J=(this.start+this.length)%k,Z=Math.min(G.length,k-J);if(G.copy(this.buffer,J,0,Z),Z<G.length)G.copy(this.buffer,0,Z);this.length+=G.length}toString(){let G=Buffer.alloc(this.length),z=Math.min(this.length,k-this.start);if(this.buffer.copy(G,0,this.start,this.start+z),z<this.length)this.buffer.copy(G,z,0,this.length-z);let J=0;while(J<G.length){let Z=G[J];if(Z===void 0||(Z&192)!==128)break;J++}return G.subarray(J).toString("utf8")}}var T={run(G,z,J={}){return new Promise((Z)=>{let $=performance.now(),Q=J.timeoutMs??15000,K=new z0,D=[],j=0,q=!1,x=!1,X=!1,V;try{V=l0(G,[...z],{env:J.env??process.env,windowsHide:!0,windowsVerbatimArguments:J.windowsVerbatimArguments,stdio:["ignore","pipe","pipe"]})}catch{Z({exitCode:1,stdout:"",stderr:"",spawnError:!0,signal:null,timedOut:!1,durationMs:performance.now()-$});return}let W=Q>0?setTimeout(()=>{X=!0,V.kill("SIGTERM")},Q):void 0;V.stdout?.on("data",(Y)=>{let C=a0-j,b=Math.min(C,Y.length);if(b>0)D.push(Y.subarray(0,b)),j+=b;if(Y.length>C)q=!0,V.kill("SIGTERM")}),V.stderr?.on("data",(Y)=>K.push(Y));let U=!1,F=(Y,C)=>{if(U)return;if(U=!0,W)clearTimeout(W);Z({exitCode:x?1:q?1:Y??1,stdout:Buffer.concat(D,j).toString("utf8"),stderr:K.toString(),stderrTruncated:K.didTruncate,...x?{spawnError:!0}:{},signal:C??null,timedOut:X,durationMs:performance.now()-$})};V.once("error",()=>{if(x=!0,V.pid===void 0)F(null,null)}),V.once("close",(Y,C)=>F(Y,C))})}};function g(G,z,J,Z,$,Q=15000){if(z==="win32"&&/\.(cmd|bat)$/i.test(J)){if(/["%!\r\n]/.test(J)||Z.some((K)=>!/^[a-zA-Z0-9@:/._+-]+$/.test(K)))throw Error("Unsafe batch launcher or argument; use an executable instead.");return G.run("cmd.exe",["/d","/s","/c",`""${J}" ${Z.join(" ")}"`],{env:$,timeoutMs:Q,windowsVerbatimArguments:!0})}return G.run(J,Z,{env:$,timeoutMs:Q})}var i0="Pi install failed; run pi install after checking your npm connection.";function s0(G){let z=Buffer.from(G,"utf8");if(z.length<=k)return G;let J=z.length-k;while(J<z.length){let Z=z[J];if(Z===void 0||(Z&192)!==128)break;J++}return z.subarray(J).toString("utf8")}function r0(G){let z=G.indexOf(`
3
- `);return z<0?"":G.slice(z+1)}class h extends Error{step="pi-install";exitCode;signal;stderrTail;constructor(G){super(i0);this.name="SetupCommandError",this.exitCode=G.exitCode,this.signal=G.signal;let z=G.stderrTruncated?r0(G.stderrTail):G.stderrTail,J=J0(z);this.stderrTail=s0(typeof J==="string"?J:"")}}var n0={opencode:"OpenCode",pi:"Pi"},o0={enrolled:"connected to the vault","not-enrolled":"not connected",unknown:"unknown, check with ck auth status"};function Z0({host:G,outcome:z}){return`${n0[G]}: ${o0[z]}`}var t0=new WeakMap;function $0(G,z){if(typeof G!=="object"&&typeof G!=="function"||!G)return;t0.set(G,Object.freeze(z.map((J)=>Object.freeze({...J}))))}import{accessSync as Z1,constants as $1,existsSync as Q1,readFileSync as K1,realpathSync as b1,statSync as q1}from"node:fs";import{mkdtemp as W1,rm as X1}from"node:fs/promises";import{tmpdir as D1}from"node:os";import{join as j1}from"node:path";import{parse as x1}from"jsonc-parser";import{homedir as e0}from"node:os";import{posix as G1,win32 as z1}from"node:path";import{fileURLToPath as J1}from"node:url";function N(G={}){let z=G.env??process.env,J=G.platform??process.platform,Z=J==="win32"?z1:G1,$=G.home??(J==="win32"?z.USERPROFILE:z.HOME)??e0(),Q=G.cwd??process.cwd(),K=(x)=>Z.resolve(Q,x),D=z.OPENCODE_CONFIG_DIR?.trim(),j=z.XDG_CONFIG_HOME?.trim(),q=z.PI_CODING_AGENT_DIR?.trim()||Z.join($,".pi","agent");if(q==="~")q=$;else if(/^~[/\\]/.test(q))q=Z.join($,q.slice(2));if(q.startsWith("file://"))q=J1(q);return{env:z,platform:J,path:Z,home:$,cwd:Q,opencode:D?K(D):j?Z.join(K(j),"opencode"):Z.join($,".config","opencode"),pi:K(q)}}function c(G,z){try{return q1(G)[z]()}catch{return!1}}var _={exists:Q1,isFile:(G)=>c(G,"isFile"),isDirectory:(G)=>c(G,"isDirectory"),isExecutable(G){try{return Z1(G,$1.X_OK),c(G,"isFile")}catch{return!1}},readText:(G)=>K1(G,"utf8"),realpath:b1};function I(G,z={}){let{env:J,platform:Z,path:$,cwd:Q}=N(z),K=z.fs??_,D=Object.entries(J).find(([q])=>Z==="win32"?q.toUpperCase()==="PATH":q==="PATH")?.[1]??"",j=Z==="win32"?[".exe",".cmd",".bat",""]:[""];for(let q of D.split(Z==="win32"?";":":")){let x=q.trim().replace(/^"|"$/g,"");if(!x)continue;for(let X of j){let V=$.resolve(Q,x,G+X);if(Z==="win32"?K.isFile(V):K.isExecutable(V))return V}}return null}function Q0(G={}){let{platform:z,home:J,env:Z,path:$}=N(G);if(z==="darwin")return["/Applications/OpenCode.app","/Applications/OpenCode Beta.app",$.join(J,"Applications","OpenCode.app"),$.join(J,"Applications","OpenCode Beta.app")];if(z==="win32"){let Q=Z.LOCALAPPDATA||$.join(J,"AppData","Local");return[$.join(Q,"Programs","opencode"),$.join(Q,"opencode")]}return["/opt/OpenCode","/usr/lib/opencode",$.join(J,".local","share","applications","opencode.desktop")]}function u(G,z){let J=z.fs??_,{path:Z}=N(z);try{let $=J.readText(G);if($.length>65536)return G;let Q=[...$.matchAll(/"%~?dp0%?\\([^"%\r\n]+)"/g)];if(!Q.length)Q.push(...$.matchAll(/"\$basedir\/([^"$\r\n]+)"/g));let K=Q.at(-1)?.[1];if(K){let D=Z.join(Z.dirname(G),...K.split(/[/\\]+/));if(J.isFile(D))return J.realpath(D)}return J.realpath(G)}catch{return G}}function V1(G,z){let J=z.fs??_,{path:Z}=N(z),$=Z.dirname(u(G,z));for(;;){try{let K=JSON.parse(J.readText(Z.join($,"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=Z.dirname($);if(Q===$)return null;$=Q}}function K0(G={}){let z=I("opencode",G),J=I("opencode2",G),Z=z&&J&&u(z,G)===u(J,G),$=G.fs??_,{path:Q,opencode:K}=N(G),D="1";for(let q of["jsonc","json"]){let x=Q.join(K,`opencode.${q}`);if(!$.exists(x))continue;try{if(Object.hasOwn(x1($.readText(x))??{},"plugins"))D="2"}catch{}break}let j=z?V1(z,G)??(Z?"2":D):null;if(J&&j==="1"&&!Z)return"ambiguous";return J||Z?"2":j??D}async function p(G,z={}){let J=z.fs??_,{env:Z,platform:$,opencode:Q,pi:K}=N(z),D=z.runner??T,j=I("opencode",z)??I("opencode2",z),q=I("pi",z),x=I("ck",z),X=async(F)=>{if(!F)return null;let Y;try{Y=await W1(j1(D1(),"common-auth-setup-version-"));let C={...Z,HOME:Y,USERPROFILE:Y,XDG_CONFIG_HOME:Y,XDG_DATA_HOME:Y,XDG_STATE_HOME:Y,XDG_CACHE_HOME:Y,OPENCODE_CONFIG_DIR:Y,OPENCODE_CONFIG:void 0,OPENCODE_CONFIG_CONTENT:void 0,OPENCODE_AUTH_CONTENT:void 0,PI_CODING_AGENT_DIR:Y},b=await g(D,$,F,["--version"],C,2000);return b.exitCode===0?/\b\d+\.\d+\.\d+(?:-[\w.-]+)?/.exec(b.stdout)?.[0]??null:null}catch{return null}finally{if(Y)await X1(Y,{recursive:!0,force:!0}).catch(()=>{})}},V=!1;if(x&&J.exists(G.vault.connectionFile))try{(await(z.connect??d)({connectionFile:G.vault.connectionFile,handshakeTimeoutMs:2000})).close(),V=!0}catch{V=!1}let[W,U]=await Promise.all([X(j),X(q)]);return{opencode:{installed:J.isDirectory(Q)||Q0(z).some((F)=>J.exists(F))||j!==null,executable:j,version:W,directory:Q,generation:K0(z)},pi:{installed:q!==null||J.isDirectory(K),executable:q,version:U,directory:K},claustrum:{available:V,executable:x}}}import{setTimeout as C1}from"node:timers/promises";import{writeEnrollmentTokenFile as R1}from"@cortexkit/claustrum-client";var b0=45000,l=new Set(["opencode","litecode","opencode2","pi"]),W0=new Set(["node","bun"]),U1=[...l,...W0].map((G)=>`Name LIKE '${G}%'`).join(" OR "),Y1=`$ErrorActionPreference = 'Stop'; $rows = @(Get-CimInstance Win32_Process -Filter "${U1}" | Select-Object Name,ProcessId,CommandLine); ConvertTo-Json -Compress -Depth 3 -InputObject @{ complete = $true; processes = $rows }`,B1=/(?:^|[/\\])pi-coding-agent[/\\]dist[/\\](?:(?:bundle|bun)[/\\])?cli\.m?js$/i;function F1(G){return[...G.matchAll(/"([^"]*)"|(\S+)/g)].map((z)=>z[1]??z[2]??"")}function q0(G){return(G.split(/[/\\]/).pop()??"").toLowerCase().replace(/\.(?:exe|cmd|bat|m?js)$/,"")}var H1=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"]),O1=new Set(["-e","--eval","-p","--print"]);function M1(G,z){for(let J=0;J<z.length;J++){let Z=z[J]??"";if(Z==="--")return z[J+1];if(O1.has(Z))return;if(Z.startsWith("-")){if(!Z.includes("=")&&H1.has(Z))J++;continue}if(G==="bun"&&Z==="run")continue;return Z}return}function X0(G){let[z,...J]=F1(G);if(z===void 0)return null;let Z=q0(z);if(l.has(Z))return Z;if(!W0.has(Z))return null;let $=M1(Z,J);if($===void 0)return null;let Q=q0($);if(l.has(Q))return Q;return B1.test($)?"pi":null}class M extends Error{code="process-inspection-failed";step;exitCode;signal;timedOut;durationMs;constructor(G){super("Process inspection failed; setup cannot prove hosts are stopped.");this.name="ProcessInspectionError",this.step=G.step,this.exitCode=G.exitCode,this.signal=G.signal,this.timedOut=G.timedOut,this.durationMs=G.durationMs}get refusalText(){let G=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}: ${G} after ${Math.round(this.durationMs)} ms.`}}class P extends Error{activeHosts;constructor(G){let z=G.map((J)=>({pid:J.pid,command:X0(J.command)??"host"}));super(`OpenCode or Pi processes are currently running:
4
- ${z.map((J)=>` - PID ${J.pid}: ${J.command}`).join(`
2
+ import{c as u0}from"./index-0v7ar02e.js";import{Aa as f,Ba as x,Ca as E,Kb as l0,gb as d0,na as h0,oa as S,pa as J0,yb as c0,za as T0}from"./index-rw932qm9.js";import{md as f0,sd as Y0,ud as m,vd as w,wd as g0,xd as c,yd as B0}from"./index-b0s5cty6.js";import"./index-fyrgwfx3.js";import"./index-z81cged1.js";import"./index-yt52fztj.js";import{Ye as $0,cf as P0,ef as S0,hf as m0}from"./index-dw6yd976.js";import"./index-g556s1mz.js";import"./index-c50p5mem.js";import"./index-hpnj460b.js";import{spawn as i0}from"node:child_process";var N=4096,s0=1048576;class Z0{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 Z0,D=[],V=0,q=!1,j=!1,W=!1,U;try{U=i0(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(()=>{W=!0,U.kill("SIGTERM")},Q):void 0;U.stdout?.on("data",(B)=>{let C=s0-V,b=Math.min(C,B.length);if(b>0)D.push(B.subarray(0,b)),V+=b;if(B.length>C)q=!0,U.kill("SIGTERM")}),U.stderr?.on("data",(B)=>K.push(B));let Y=!1,F=(B,C)=>{if(Y)return;if(Y=!0,X)clearTimeout(X);$({exitCode:j?1:q?1:B??1,stdout:Buffer.concat(D,V).toString("utf8"),stderr:K.toString(),stderrTruncated:K.didTruncate,...j?{spawnError:!0}:{},signal:C??null,timedOut:W,durationMs:performance.now()-G})};U.once("error",()=>{if(j=!0,U.pid===void 0)F(null,null)}),U.once("close",(B,C)=>F(B,C))})}};function g(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 r0="Pi install failed; run pi install after checking your npm connection.";function n0(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 o0(z){let J=z.indexOf(`
3
+ `);return J<0?"":z.slice(J+1)}class h extends Error{step="pi-install";exitCode;signal;stderrTail;constructor(z){super(r0);this.name="SetupCommandError",this.exitCode=z.exitCode,this.signal=z.signal;let J=z.stderrTruncated?o0(z.stderrTail):z.stderrTail,Z=$0(J);this.stderrTail=n0(typeof Z==="string"?Z:"")}}var t0={opencode:"OpenCode",pi:"Pi"},e0={enrolled:"connected to the vault","not-enrolled":"not connected",unknown:"unknown, check with ck auth status"};function G0({host:z,outcome:J}){return`${t0[z]}: ${e0[J]}`}var z2=new WeakMap;function Q0(z,J){if(typeof z!=="object"&&typeof z!=="function"||!z)return;z2.set(z,Object.freeze(J.map((Z)=>Object.freeze({...Z}))))}import{accessSync as Q2,constants as K2,existsSync as b2,readFileSync as q2,realpathSync as X2,statSync as D2}from"node:fs";import{mkdtemp as W2,rm as V2}from"node:fs/promises";import{tmpdir as j2}from"node:os";import{join as U2}from"node:path";import{parse as Y2}from"jsonc-parser";import{homedir as J2}from"node:os";import{posix as Z2,win32 as $2}from"node:path";import{fileURLToPath as G2}from"node:url";function k(z={}){let J=z.env??process.env,Z=z.platform??process.platform,$=Z==="win32"?$2:Z2,G=z.home??(Z==="win32"?J.USERPROFILE:J.HOME)??J2(),Q=z.cwd??process.cwd(),K=(j)=>$.resolve(Q,j),D=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=G2(q);return{env:J,platform:Z,path:$,home:G,cwd:Q,opencode:D?K(D):V?$.join(K(V),"opencode"):$.join(G,".config","opencode"),pi:K(q)}}function u(z,J){try{return D2(z)[J]()}catch{return!1}}var T={exists:b2,isFile:(z)=>u(z,"isFile"),isDirectory:(z)=>u(z,"isDirectory"),isExecutable(z){try{return Q2(z,K2.X_OK),u(z,"isFile")}catch{return!1}},readText:(z)=>q2(z,"utf8"),realpath:X2};function I(z,J={}){let{env:Z,platform:$,path:G,cwd:Q}=k(J),K=J.fs??T,D=Object.entries(Z).find(([q])=>$==="win32"?q.toUpperCase()==="PATH":q==="PATH")?.[1]??"",V=$==="win32"?[".exe",".cmd",".bat",""]:[""];for(let q of D.split($==="win32"?";":":")){let j=q.trim().replace(/^"|"$/g,"");if(!j)continue;for(let W of V){let U=G.resolve(Q,j,z+W);if($==="win32"?K.isFile(U):K.isExecutable(U))return U}}return null}function K0(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 p(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 D=$.join($.dirname(z),...K.split(/[/\\]+/));if(Z.isFile(D))return Z.realpath(D)}return Z.realpath(z)}catch{return z}}function B2(z,J){let Z=J.fs??T,{path:$}=k(J),G=$.dirname(p(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 b0(z={}){let J=I("opencode",z),Z=I("opencode2",z),$=J&&Z&&p(J,z)===p(Z,z),G=z.fs??T,{path:Q,opencode:K}=k(z),D="1";for(let q of["jsonc","json"]){let j=Q.join(K,`opencode.${q}`);if(!G.exists(j))continue;try{if(Object.hasOwn(Y2(G.readText(j))??{},"plugins"))D="2"}catch{}break}let V=J?B2(J,z)??($?"2":D):null;if(Z&&V==="1"&&!$)return"ambiguous";return Z||$?"2":V??D}async function l(z,J={}){let Z=J.fs??T,{env:$,platform:G,opencode:Q,pi:K}=k(J),D=J.runner??_,V=I("opencode",J)??I("opencode2",J),q=I("pi",J),j=I("ck",J),W=async(F)=>{if(!F)return null;let B;try{B=await W2(U2(j2(),"common-auth-setup-version-"));let C={...$,HOME:B,USERPROFILE:B,XDG_CONFIG_HOME:B,XDG_DATA_HOME:B,XDG_STATE_HOME:B,XDG_CACHE_HOME:B,OPENCODE_CONFIG_DIR:B,OPENCODE_CONFIG:void 0,OPENCODE_CONFIG_CONTENT:void 0,OPENCODE_AUTH_CONTENT:void 0,PI_CODING_AGENT_DIR:B},b=await g(D,G,F,["--version"],C,2000);return b.exitCode===0?/\b\d+\.\d+\.\d+(?:-[\w.-]+)?/.exec(b.stdout)?.[0]??null:null}catch{return null}finally{if(B)await V2(B,{recursive:!0,force:!0}).catch(()=>{})}},U=!1;if(j&&Z.exists(z.vault.connectionFile))try{(await(J.connect??m)({connectionFile:z.vault.connectionFile,handshakeTimeoutMs:2000})).close(),U=!0}catch{U=!1}let[X,Y]=await Promise.all([W(V),W(q)]);return{opencode:{installed:Z.isDirectory(Q)||K0(J).some((F)=>Z.exists(F))||V!==null,executable:V,version:X,directory:Q,generation:b0(J)},pi:{installed:q!==null||Z.isDirectory(K),executable:q,version:Y,directory:K},claustrum:{available:U,executable:j}}}import{setTimeout as N2}from"node:timers/promises";import{writeEnrollmentTokenFile as k2}from"@cortexkit/claustrum-client";var q0=45000,a=new Set(["opencode","litecode","opencode2","pi"]),D0=new Set(["node","bun"]),x2=[...a,...D0].map((z)=>`Name LIKE '${z}%'`).join(" OR "),F2=`$ErrorActionPreference = 'Stop'; $rows = @(Get-CimInstance Win32_Process -Filter "${x2}" | Select-Object Name,ProcessId,CommandLine); ConvertTo-Json -Compress -Depth 3 -InputObject @{ complete = $true; processes = $rows }`,H2=/(?:^|[/\\])pi-coding-agent[/\\]dist[/\\](?:(?:bundle|bun)[/\\])?cli\.m?js$/i;function O2(z){return[...z.matchAll(/"([^"]*)"|(\S+)/g)].map((J)=>J[1]??J[2]??"")}function X0(z){return(z.split(/[/\\]/).pop()??"").toLowerCase().replace(/\.(?:exe|cmd|bat|m?js)$/,"")}var M2=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"]),C2=new Set(["-e","--eval","-p","--print"]);function R2(z,J){for(let Z=0;Z<J.length;Z++){let $=J[Z]??"";if($==="--")return J[Z+1];if(C2.has($))return;if($.startsWith("-")){if(!$.includes("=")&&M2.has($))Z++;continue}if(z==="bun"&&$==="run")continue;return $}return}function W0(z){let[J,...Z]=O2(z);if(J===void 0)return null;let $=X0(J);if(a.has($))return $;if(!D0.has($))return null;let G=R2($,Z);if(G===void 0)return null;let Q=X0(G);if(a.has(Q))return Q;return H2.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:W0(Z.command)??"host"}));super(`OpenCode or Pi processes are currently running:
4
+ ${J.map((Z)=>` - PID ${Z.pid}: ${Z.command}`).join(`
5
5
  `)}
6
6
 
7
- Please quit all OpenCode, LiteCode, and Pi processes before running setup.`);this.activeHosts=z,this.name="ProcessFenceViolationError"}}async function a(G=T,z={}){let J=(z.platform??process.platform)==="win32",Z=z.selfPid??process.pid,$={step:J?"tasklist":"ps",exitCode:null,signal:null,timedOut:!1,durationMs:0},Q=async(K,D,j,q)=>{let x=performance.now();$={step:K,exitCode:null,signal:null,timedOut:!1,durationMs:0};try{let X=await G.run(D,j,{env:z.env,timeoutMs:q});return $={step:K,exitCode:X.exitCode,signal:X.signal??null,timedOut:X.timedOut??!1,durationMs:X.durationMs??performance.now()-x},X}finally{if($.exitCode===null)$.durationMs=performance.now()-x;z.onStep?.({...$})}};try{if(J&&z.hostImagesOnly){let q=await Q("CIM","powershell.exe",["-NoProfile","-NonInteractive","-Command",Y1],b0);if(q.exitCode!==0)throw new M($);let x=JSON.parse(q.stdout);if(!x||typeof x!=="object"||!("complete"in x)||x.complete!==!0||!("processes"in x))throw new M($);let X=x.processes,V=X===null?[]:Array.isArray(X)?X:[X],W=[];for(let U of V){if(!U||typeof U!=="object"||!("Name"in U)||typeof U.Name!=="string"||!("ProcessId"in U)||!Number.isSafeInteger(U.ProcessId)||U.ProcessId<0||!("CommandLine"in U))throw new M($);let F=U.ProcessId;if(!/^(?:node|bun)\.exe$/i.test(U.Name))W.push({pid:F,command:U.Name});else if(typeof U.CommandLine==="string")W.push({pid:F,command:U.CommandLine});else if(F!==Z)throw new M($)}return W}let K=await Q(J?"tasklist":"ps",J?"tasklist.exe":"ps",J?["/fo","csv","/nh"]:["-eo","pid,command"]);if(K.exitCode!==0)throw new M($);let D=[];for(let q of K.stdout.split(/\r?\n/)){let x=q.trim();if(!x)continue;let X,V;if(J){let W=/^"([^"]+)","(\d+)"(?:,|$)/.exec(x);if(!W)throw new M($);V=W[1]??"",X=Number(W[2])}else{let W=/^(\d+)\s+(.+)$/.exec(x);if(!W){if(/^PID\s+COMMAND$/i.test(x))continue;throw new M($)}X=Number(W[1]),V=W[2]??""}if(!Number.isSafeInteger(X)||X<0)throw new M($);D.push({pid:X,command:V})}if(!D.length)throw new M($);let j=D.filter((q)=>q.pid!==Z&&/^(?:node|bun)\.exe$/i.test(q.command));if(J&&j.length&&z.inspectRuntimes!==!1){let q=await Q("CIM","powershell.exe",["-NoProfile","-NonInteractive","-Command",`$ErrorActionPreference = 'Stop'; Get-CimInstance Win32_Process -Filter "Name = 'node.exe' OR Name = 'bun.exe'" | Select-Object ProcessId,CommandLine | ConvertTo-Json -Compress`],b0);if(q.exitCode!==0)throw new M($);let x=JSON.parse(q.stdout||"null"),X=x===null?[]:Array.isArray(x)?x:[x],V=new Map;for(let W of X){if(!W||typeof W!=="object"||!("ProcessId"in W)||!("CommandLine"in W)||!Number.isSafeInteger(W.ProcessId))throw new M($);if(typeof W.CommandLine==="string")V.set(Number(W.ProcessId),W.CommandLine);else if(j.some((U)=>U.pid===W.ProcessId))throw new M($)}for(let W of j)W.command=V.get(W.pid)??""}return D}catch(K){if(K instanceof M)throw K;throw new M($)}}function v(G=T,z={}){let J=z.selfPid??process.pid,Z=($)=>$.pid!==J&&X0($.command)!==null;return{async listRunningHosts($){return(await a(G,{...z,env:$,hostImagesOnly:!0})).filter(Z)},async previewRunningHosts($){let Q=await a(G,{...z,env:$,inspectRuntimes:!1}),K=(z.platform??process.platform)==="win32";return{hosts:Q.filter(Z),uncheckedRuntimes:K?Q.filter((D)=>D.pid!==J&&/^(?:node|bun)\.exe$/i.test(D.command)).length:0}}}}async function y(G,z){let J=await G.listRunningHosts(z);if(J.length)throw new P(J)}var k1="Claustrum enrollment did not complete. Inspect and approve with ck, then rerun setup.",Y0='This Claustrum vault is too old to connect plugins. Run ck upgrade to move to Claustrum v0.2.0 or newer (read "Upgrading from v0.1.3" in its release notes first), or run setup without --claustrum to use local accounts.',B0=300000,D0=1000,j0=[1000,2000,4000,8000,16000,30000];function i(G){return G&&/^[a-z][a-z0-9_]{0,63}$/.test(G)?G:"unknown"}class A extends Error{reason;lastErrorCode;constructor(G,z){super(G);if(this.name="HostNotEnrolledError",this.reason=z.reason,z.lastErrorCode!==void 0)this.lastErrorCode=i(z.lastErrorCode)}}function x0(G,z){return`ck auth enroll approve --request-id ${G} --name ${z}`}async function F0(G,z,J,Z,$){let{name:Q,paths:K}=G.vault.hosts[z],D=w(K);await $();let j=await(J.connect??d)({connectionFile:G.vault.connectionFile,handshakeTimeoutMs:2000}).catch(()=>{throw new A("Claustrum connection failed; start ck and rerun setup.",{reason:"connection-failed"})}),q=J.now??(()=>performance.now()),x=J.wait??C1;try{let X=new U0({proposedName:Q,paths:D,client:j,writeTokenFile:async(b,H)=>{await $(),await R1(b,H)}});B(Z,`Asking the vault to connect ${Q}…`);let V=q()+B0,W,U,F,Y=0;for(;;){await $();let b=await X.reconcile();if(b.state==="approved"){B(Z,`Connected ${z} to Claustrum.`);return}if(b.state==="unavailable"&&b.code===V0)throw new A(Y0,{reason:"unsupported-vault",lastErrorCode:b.code});if(b.state!=="pending"&&b.state!=="busy")throw new A("Claustrum enrollment refused; inspect its status with ck before rerunning setup.",{reason:"refused",..."code"in b&&{lastErrorCode:b.code}});let H=D0;if(b.state==="busy")U="busy";else if(b.retryCode)U=b.retryCode;if(b.state==="pending"&&b.requestId){if(Y=0,b.requestId!==W){if(!/^[a-zA-Z0-9_-]+$/.test(b.requestId))throw new A("Invalid enrollment request id.",{reason:"invalid-request"});W=b.requestId,B(Z,"Waiting for approval. In another terminal, run:"),B(Z,` ${x0(b.requestId,Q)}`),B(Z,`Enrollment files: ${D.statePath}, ${D.tokenPath}`)}}else if(b.state==="pending"&&b.retryCode){H=j0[Math.min(Y,j0.length-1)]??D0,Y++;let R=i(b.retryCode);if(R!==F)F=R,B(Z,`The vault has not created the request yet (${R}); retrying.`)}let O=V-q();if(O<=0)break;await x(Math.min(H,O))}if(W)throw new A(`Claustrum approval is still pending. In another terminal, run: ${x0(W,Q)} and then rerun setup.`,{reason:"approval-pending",...U!==void 0&&{lastErrorCode:U}});let C=i(U);throw new A(`The vault never created the enrollment request (last error: ${C}). Check that ck is running, then rerun setup.`,{reason:"request-not-created",lastErrorCode:C})}catch(X){if(X instanceof P||X instanceof M||X instanceof A)throw X;let V=X?.code;throw new A(k1,{reason:"incomplete",...typeof V==="string"&&{lastErrorCode:V}})}finally{j.close()}}async function H0(G,z){let J=new Set(z);for(;;){let Z=await E(G,[...["opencode","pi"].map(($)=>({value:$,label:`[${J.has($)?"x":" "}] ${$==="opencode"?"OpenCode":"Pi"}`,hint:z.includes($)?"found":"not found"})),{value:"done",label:"Continue with selected hosts"}],{message:"Select hosts to set up",subtitle:"Enter toggles a host; choose Continue when ready."});if(Z===null)return null;if(Z==="done")return[...J];if(J.has(Z))J.delete(Z);else J.add(Z)}}import{domainToUnicode as y1}from"node:url";import{applyEdits as s,createScanner as E1,findNodeAtLocation as f1,modify as M0,parse as g1,parseTree as h1}from"jsonc-parser";import{randomUUID as N1}from"node:crypto";import{mkdir as A1,open as I1,rename as T1,stat as _1,unlink as w1}from"node:fs/promises";import{basename as L1,dirname as P1,join as S1}from"node:path";import{setTimeout as v1}from"node:timers/promises";async function O0(G,z,J={}){let Z=(J.platform??process.platform)==="win32",$=P1(G);await A1($,{recursive:!0});let Q;if(!Z)try{Q=(await _1(G)).mode&4095}catch(j){if(j.code!=="ENOENT")throw j}let K=S1($,`.${L1(G)}.${(J.stageName??N1)()}.tmp`),D=!1;try{let j=await I1(K,"wx",Q??438);D=!0;try{if(await j.writeFile(z,"utf8"),Q!==void 0)await j.chmod(Q)}finally{await j.close()}let q=J.now??(()=>performance.now()),x=q();for(let X=0;;X++){await J.beforeRename?.();try{await(J.rename??T1)(K,G),D=!1;return}catch(V){let W=V.code,U=2000-(q()-x);if(!Z||!["EPERM","EBUSY","EACCES"].includes(W??"")||U<=0||X>=40)throw Error(`Unable to replace host config ${G}. Close editors or other programs using the file, then rerun setup.`);await(J.wait??v1)(Math.min(U,25*2**Math.min(X,2)))}}}finally{if(D)await w1(K).catch(()=>{})}}function R0(G){let z=typeof G==="string"?G:Array.isArray(G)?G[0]:G&&typeof G==="object"&&("package"in G)?G.package:null;return typeof z==="string"?z:null}function r(G){let z=R0(G);if(z===null)return null;let J=z.indexOf("@",z.startsWith("@")?1:0);return J<0?z:z.slice(0,J)}function d1(G,z){let J=new URL(G);if(/%2f/i.test(J.pathname)||z&&/%5c/i.test(J.pathname))throw Error("Encoded path separators are not valid in a file URL.");let Z=decodeURIComponent(J.pathname);if(!z){if(J.hostname)throw Error("A POSIX file URL must be local.");return Z}let $=Z.replaceAll("/","\\");if(J.hostname)return`\\\\${y1(J.hostname)}${$}`;if(!/^\\[a-z]:/i.test($))throw Error("A Windows file URL must have an absolute drive path.");return $.slice(1)}function m1(G,z,J){let{path:Z,platform:$}=N(J);try{let Q=/^file:\/\//i.test(G)?d1(G,$==="win32"):Z.isAbsolute(G)||G.startsWith(".")?Z.resolve(Z.dirname(z),G):null;if(Q===null)return null;let K=JSON.parse((J.fs??_).readText(Z.join(Q,"package.json")));return K&&typeof K==="object"&&"name"in K&&typeof K.name==="string"?K.name:null}catch{return null}}function k0(G,z){let J=[],Z=g1(G,J,{allowTrailingComma:!0});if(J.length||!Z||typeof Z!=="object"||Array.isArray(Z))throw Error("Invalid OpenCode config; refusing to overwrite it.");if(Z[z]!==void 0&&!Array.isArray(Z[z]))throw Error(`OpenCode ${z} must be an array.`);return Z}function C0(G,z,J){let Z=h1(G),$=Z&&f1(Z,[z]),Q=$?.children??[],K=Q[J];if(!K||!$)throw Error("Invalid plugin array edit.");let D=[{offset:K.offset,length:K.length,content:""}],j=(q,x)=>{let X=E1(G.slice(q,x),!0);if(X.scan(),G[q+X.getTokenOffset()]===",")D.push({offset:q+X.getTokenOffset(),length:1,content:""})};if(J===Q.length-1){let q=Q[J-1];if(q)j(q.offset+q.length,K.offset);j(K.offset+K.length,$.offset+$.length-1)}else j(K.offset+K.length,Q[J+1]?.offset??K.offset+K.length);return s(G,D)}function N0(G,z,J,Z){let $=k0(G,z),Q={formattingOptions:{insertSpaces:!/^\t+/m.test(G),tabSize:/^([ ]+)"/m.exec(G)?.[1]?.length??2,eol:G.includes(`\r
7
+ Please quit all OpenCode, LiteCode, and Pi processes before running setup.`);this.activeHosts=J,this.name="ProcessFenceViolationError"}}async function i(z=_,J={}){let Z=(J.platform??process.platform)==="win32",$=J.selfPid??process.pid,G={step:Z?"tasklist":"ps",exitCode:null,signal:null,timedOut:!1,durationMs:0},Q=async(K,D,V,q)=>{let j=performance.now();G={step:K,exitCode:null,signal:null,timedOut:!1,durationMs:0};try{let W=await z.run(D,V,{env:J.env,timeoutMs:q});return G={step:K,exitCode:W.exitCode,signal:W.signal??null,timedOut:W.timedOut??!1,durationMs:W.durationMs??performance.now()-j},W}finally{if(G.exitCode===null)G.durationMs=performance.now()-j;J.onStep?.({...G})}};try{if(Z&&J.hostImagesOnly){let q=await Q("CIM","powershell.exe",["-NoProfile","-NonInteractive","-Command",F2],q0);if(q.exitCode!==0)throw new M(G);let j=JSON.parse(q.stdout);if(!j||typeof j!=="object"||!("complete"in j)||j.complete!==!0||!("processes"in j))throw new M(G);let W=j.processes,U=W===null?[]:Array.isArray(W)?W:[W],X=[];for(let Y of U){if(!Y||typeof Y!=="object"||!("Name"in Y)||typeof Y.Name!=="string"||!("ProcessId"in Y)||!Number.isSafeInteger(Y.ProcessId)||Y.ProcessId<0||!("CommandLine"in Y))throw new M(G);let F=Y.ProcessId;if(!/^(?:node|bun)\.exe$/i.test(Y.Name))X.push({pid:F,command:Y.Name});else if(typeof Y.CommandLine==="string")X.push({pid:F,command:Y.CommandLine});else if(F!==$)throw new M(G)}return X}let K=await Q(Z?"tasklist":"ps",Z?"tasklist.exe":"ps",Z?["/fo","csv","/nh"]:["-eo","pid,command"]);if(K.exitCode!==0)throw new M(G);let D=[];for(let q of K.stdout.split(/\r?\n/)){let j=q.trim();if(!j)continue;let W,U;if(Z){let X=/^"([^"]+)","(\d+)"(?:,|$)/.exec(j);if(!X)throw new M(G);U=X[1]??"",W=Number(X[2])}else{let X=/^(\d+)\s+(.+)$/.exec(j);if(!X){if(/^PID\s+COMMAND$/i.test(j))continue;throw new M(G)}W=Number(X[1]),U=X[2]??""}if(!Number.isSafeInteger(W)||W<0)throw new M(G);D.push({pid:W,command:U})}if(!D.length)throw new M(G);let V=D.filter((q)=>q.pid!==$&&/^(?:node|bun)\.exe$/i.test(q.command));if(Z&&V.length&&J.inspectRuntimes!==!1){let q=await Q("CIM","powershell.exe",["-NoProfile","-NonInteractive","-Command",`$ErrorActionPreference = 'Stop'; Get-CimInstance Win32_Process -Filter "Name = 'node.exe' OR Name = 'bun.exe'" | Select-Object ProcessId,CommandLine | ConvertTo-Json -Compress`],q0);if(q.exitCode!==0)throw new M(G);let j=JSON.parse(q.stdout||"null"),W=j===null?[]:Array.isArray(j)?j:[j],U=new Map;for(let X of W){if(!X||typeof X!=="object"||!("ProcessId"in X)||!("CommandLine"in X)||!Number.isSafeInteger(X.ProcessId))throw new M(G);if(typeof X.CommandLine==="string")U.set(Number(X.ProcessId),X.CommandLine);else if(V.some((Y)=>Y.pid===X.ProcessId))throw new M(G)}for(let X of V)X.command=U.get(X.pid)??""}return D}catch(K){if(K instanceof M)throw K;throw new M(G)}}function y(z=_,J={}){let Z=J.selfPid??process.pid,$=(G)=>G.pid!==Z&&W0(G.command)!==null;return{async listRunningHosts(G){return(await i(z,{...J,env:G,hostImagesOnly:!0})).filter($)},async previewRunningHosts(G){let Q=await i(z,{...J,env:G,inspectRuntimes:!1}),K=(J.platform??process.platform)==="win32";return{hosts:Q.filter($),uncheckedRuntimes:K?Q.filter((D)=>D.pid!==Z&&/^(?:node|bun)\.exe$/i.test(D.command)).length:0}}}}async function v(z,J){let Z=await z.listRunningHosts(J);if(Z.length)throw new P(Z)}var A2="Claustrum enrollment did not complete. Inspect and approve with ck, then rerun setup.",x0='This Claustrum vault is too old to connect plugins. Run ck upgrade to move to Claustrum v0.2.0 or newer (read "Upgrading from v0.1.3" in its release notes first), or run setup without --claustrum to use local accounts.',F0=300000,V0=1000,j0=[1000,2000,4000,8000,16000,30000];function s(z){return z&&/^[a-z][a-z0-9_]{0,63}$/.test(z)?z:"unknown"}class A extends Error{reason;lastErrorCode;constructor(z,J){super(z);if(this.name="HostNotEnrolledError",this.reason=J.reason,J.lastErrorCode!==void 0)this.lastErrorCode=s(J.lastErrorCode)}}function U0(z,J){return`ck auth enroll approve --request-id ${z} --name ${J}`}async function H0(z,J,Z,$,G){let{name:Q,paths:K}=z.vault.hosts[J],D=w(K);await G();let V=await(Z.connect??m)({connectionFile:z.vault.connectionFile,handshakeTimeoutMs:2000}).catch(()=>{throw new A("Claustrum connection failed; start ck and rerun setup.",{reason:"connection-failed"})}),q=Z.now??(()=>performance.now()),j=Z.wait??N2;try{let W=new B0({proposedName:Q,paths:D,client:V,writeTokenFile:async(b,H)=>{await G(),await k2(b,H)}});x($,`Asking the vault to connect ${Q}…`);let U=q()+F0,X,Y,F,B=0;for(;;){await G();let b=await W.reconcile();if(b.state==="approved"){x($,`Connected ${J} to Claustrum.`);return}if(b.state==="unavailable"&&b.code===Y0)throw new A(x0,{reason:"unsupported-vault",lastErrorCode:b.code});if(b.state!=="pending"&&b.state!=="busy")throw new A("Claustrum enrollment refused; inspect its status with ck before rerunning setup.",{reason:"refused",..."code"in b&&{lastErrorCode:b.code}});let H=V0;if(b.state==="busy")Y="busy";else if(b.retryCode)Y=b.retryCode;if(b.state==="pending"&&b.requestId){if(B=0,b.requestId!==X){if(!/^[a-zA-Z0-9_-]+$/.test(b.requestId))throw new A("Invalid enrollment request id.",{reason:"invalid-request"});X=b.requestId,x($,"Waiting for approval. In another terminal, run:"),x($,` ${U0(b.requestId,Q)}`),x($,`Enrollment files: ${D.statePath}, ${D.tokenPath}`)}}else if(b.state==="pending"&&b.retryCode){H=j0[Math.min(B,j0.length-1)]??V0,B++;let R=s(b.retryCode);if(R!==F)F=R,x($,`The vault has not created the request yet (${R}); retrying.`)}let O=U-q();if(O<=0)break;await j(Math.min(H,O))}if(X)throw new A(`Claustrum approval is still pending. In another terminal, run: ${U0(X,Q)} and then rerun setup.`,{reason:"approval-pending",...Y!==void 0&&{lastErrorCode:Y}});let C=s(Y);throw new A(`The vault never created the enrollment request (last error: ${C}). Check that ck is running, then rerun setup.`,{reason:"request-not-created",lastErrorCode:C})}catch(W){if(W instanceof P||W instanceof M||W instanceof A)throw W;let U=W?.code;throw new A(A2,{reason:"incomplete",...typeof U==="string"&&{lastErrorCode:U}})}finally{V.close()}}var O0="Requested setup host is unknown or unavailable. Use --host=opencode or --host=pi with a detected host.",I2=[{name:"--yes",key:"yes",description:"Run without questions and set up every found host. Does not choose the vault."},{name:"--dry-run",key:"dryRun",description:"Print what setup would do without changing anything."},{name:"--host",key:"hosts",values:["opencode","pi"],spaceForm:!0,invalid:"Requested setup host is unknown or unavailable. Use --host=opencode or --host=pi with a detected host.",description:"Set up only this host; repeat the flag for both. Also written --host=<host>."},{name:"--opencode",key:"opencode",values:["1","2","both"],description:"Register for this OpenCode generation."},{name:"--claustrum",key:"claustrum",description:"Connect the hosts to the Claustrum vault."},{name:"--no-claustrum",key:"noClaustrum",description:"Do not offer the Claustrum vault; sign in locally."},{name:"--login",key:"login",description:"Sign in locally instead of using the Claustrum vault."},{name:"--enroll-only",key:"enrollOnly",description:"Only connect the hosts to the Claustrum vault; register nothing and migrate nothing."}];function d(z){return Error(`Unknown setup argument: ${z}. Run the plugin's own setup --help to list the flags setup accepts.`)}function M0(z){let J={yes:!1,dryRun:!1,claustrum:!1,noClaustrum:!1,login:!1,enrollOnly:!1,hosts:[],opencode:void 0};for(let Z=0;Z<z.length;Z++){let $=z[Z],G=$.indexOf("="),Q=G===-1?$:$.slice(0,G),K=I2.find((V)=>V.name===Q);if(!K)throw d($);if(!("values"in K)){if(G!==-1)throw d($);J[K.key]=!0;continue}let D;if(G!==-1)D=$.slice(G+1);else if(K.spaceForm)D=z[++Z];else throw d($);if(D===void 0||!K.values.includes(D))throw K.invalid?Error(K.invalid):d($);if(K.key==="hosts")J.hosts.push(D);else J.opencode=D}if(J.claustrum&&J.noClaustrum)throw Error("--claustrum and --no-claustrum cannot be used together.");if(J.login&&J.claustrum)throw Error("--login and --claustrum cannot be used together.");if(J.enrollOnly&&J.login)throw Error("--enroll-only and --login cannot be used together.");if(J.enrollOnly&&J.noClaustrum)throw Error("--enroll-only and --no-claustrum cannot be used together.");return J}async function C0(z,J){let Z=new Set(J);for(;;){let $=await E(z,[...["opencode","pi"].map((G)=>({value:G,label:`[${Z.has(G)?"x":" "}] ${G==="opencode"?"OpenCode":"Pi"}`,hint:J.includes(G)?"found":"not found"})),{value:"done",label:"Continue with selected hosts"}],{message:"Select hosts to set up",subtitle:"Enter toggles a host; choose Continue when ready."});if($===null)return null;if($==="done")return[...Z];if(Z.has($))Z.delete($);else Z.add($)}}import{domainToUnicode as g2}from"node:url";import{applyEdits as r,createScanner as h2,findNodeAtLocation as m2,modify as N0,parse as d2,parseTree as c2}from"jsonc-parser";import{randomUUID as _2}from"node:crypto";import{mkdir as T2,open as w2,rename as L2,stat as P2,unlink as S2}from"node:fs/promises";import{basename as y2,dirname as v2,join as E2}from"node:path";import{setTimeout as f2}from"node:timers/promises";async function R0(z,J,Z={}){let $=(Z.platform??process.platform)==="win32",G=v2(z);await T2(G,{recursive:!0});let Q;if(!$)try{Q=(await P2(z)).mode&4095}catch(V){if(V.code!=="ENOENT")throw V}let K=E2(G,`.${y2(z)}.${(Z.stageName??_2)()}.tmp`),D=!1;try{let V=await w2(K,"wx",Q??438);D=!0;try{if(await V.writeFile(J,"utf8"),Q!==void 0)await V.chmod(Q)}finally{await V.close()}let q=Z.now??(()=>performance.now()),j=q();for(let W=0;;W++){await Z.beforeRename?.();try{await(Z.rename??L2)(K,z),D=!1;return}catch(U){let X=U.code,Y=2000-(q()-j);if(!$||!["EPERM","EBUSY","EACCES"].includes(X??"")||Y<=0||W>=40)throw Error(`Unable to replace host config ${z}. Close editors or other programs using the file, then rerun setup.`);await(Z.wait??f2)(Math.min(Y,25*2**Math.min(W,2)))}}}finally{if(D)await S2(K).catch(()=>{})}}function A0(z){let J=typeof z==="string"?z:Array.isArray(z)?z[0]:z&&typeof z==="object"&&("package"in z)?z.package:null;return typeof J==="string"?J:null}function n(z){let J=A0(z);if(J===null)return null;let Z=J.indexOf("@",J.startsWith("@")?1:0);return Z<0?J:J.slice(0,Z)}function u2(z,J){let Z=new URL(z);if(/%2f/i.test(Z.pathname)||J&&/%5c/i.test(Z.pathname))throw Error("Encoded path separators are not valid in a file URL.");let $=decodeURIComponent(Z.pathname);if(!J){if(Z.hostname)throw Error("A POSIX file URL must be local.");return $}let G=$.replaceAll("/","\\");if(Z.hostname)return`\\\\${g2(Z.hostname)}${G}`;if(!/^\\[a-z]:/i.test(G))throw Error("A Windows file URL must have an absolute drive path.");return G.slice(1)}function p2(z,J,Z){let{path:$,platform:G}=k(Z);try{let Q=/^file:\/\//i.test(z)?u2(z,G==="win32"):$.isAbsolute(z)||z.startsWith(".")?$.resolve($.dirname(J),z):null;if(Q===null)return null;let K=JSON.parse((Z.fs??T).readText($.join(Q,"package.json")));return K&&typeof K==="object"&&"name"in K&&typeof K.name==="string"?K.name:null}catch{return null}}function I0(z,J){let Z=[],$=d2(z,Z,{allowTrailingComma:!0});if(Z.length||!$||typeof $!=="object"||Array.isArray($))throw Error("Invalid OpenCode config; refusing to overwrite it.");if($[J]!==void 0&&!Array.isArray($[J]))throw Error(`OpenCode ${J} must be an array.`);return $}function k0(z,J,Z){let $=c2(z),G=$&&m2($,[J]),Q=G?.children??[],K=Q[Z];if(!K||!G)throw Error("Invalid plugin array edit.");let D=[{offset:K.offset,length:K.length,content:""}],V=(q,j)=>{let W=h2(z.slice(q,j),!0);if(W.scan(),z[q+W.getTokenOffset()]===",")D.push({offset:q+W.getTokenOffset(),length:1,content:""})};if(Z===Q.length-1){let q=Q[Z-1];if(q)V(q.offset+q.length,K.offset);V(K.offset+K.length,G.offset+G.length-1)}else V(K.offset+K.length,Q[Z+1]?.offset??K.offset+K.length);return r(z,D)}function _0(z,J,Z,$){let G=I0(z,J),Q={formattingOptions:{insertSpaces:!/^\t+/m.test(z),tabSize:/^([ ]+)"/m.exec(z)?.[1]?.length??2,eol:z.includes(`\r
8
8
  `)?`\r
9
9
  `:`
10
- `}},K=G,D=$[z],j=Array.isArray(D)?[...D]:[],q=j.flatMap((V,W)=>r(V)===J?[W]:[]),x=`${J}@${Z}`;if(!q.length)K=s(K,M0(K,D===void 0?[z]:[z,j.length],D===void 0?[x]:x,Q));else{let V=q[0],W=j[V],U=Array.isArray(W)?[x,...W.slice(1)]:W&&typeof W==="object"?{...W,package:x}:x;if(JSON.stringify(W)!==JSON.stringify(U))K=s(K,M0(K,[z,V],U,Q));for(let F of q.slice(1).reverse())K=C0(K,z,F)}let X=z==="plugin"?"plugins":"plugin";if(Array.isArray($[X])){let V=$[X];for(let W=V.length-1;W>=0;W--)if(r(V[W])===J)K=C0(K,X,W)}return K}function n(G,z,J={}){let Z=J.fs??_,{path:$,opencode:Q}=N(J),K=z==="2"?"plugins":"plugin";return(z==="2"?["opencode"]:["opencode","tui"]).map((j)=>{let q=$.join(Q,`${j}.jsonc`),x=$.join(Q,`${j}.json`),X=Z.exists(q)?q:Z.exists(x)?x:q,V=Z.exists(X),W=V?Z.readText(X):`${JSON.stringify({$schema:`https://opencode.ai/${j==="tui"?"tui":"config"}.json`},null,2)}
11
- `,U=k0(W,K),F=[],Y=[];for(let b of["plugin","plugins"]){if(!Array.isArray(U[b]))continue;for(let H of U[b]){let O=R0(H);if(O===null)continue;if(m1(O,X,J)===G.packages.opencode)F.push(JSON.stringify(H));else if(r(H)===G.packages.opencode)Y.push(JSON.stringify(H))}}if(F.length>0)return{path:X,content:W,changed:!1,existingLocalEntries:F,existingNpmEntries:Y};let C=N0(W,K,G.packages.opencode,G.version);return{path:X,content:C,changed:!V||C!==W}})}async function o(G,z){for(let J of G){if(!J.changed)continue;await z?.(),await O0(J.path,J.content,{beforeRename:z})}}async function t(G,z,J={}){let{platform:Z,env:$}=N(J),Q=await g(J.runner??T,Z,z,["install",`npm:${G.packages.pi}@${G.version}`],$);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 I0="Multiple OpenCode generations found. Choose --opencode=1|2|both before running noninteractive setup.",T0="Requested setup host is unknown or unavailable. Use --host=opencode or --host=pi with a detected host.";function c1(G){let z={yes:!1,dryRun:!1,claustrum:!1,noClaustrum:!1,login:!1,enrollOnly:!1,hosts:[],opencode:void 0};for(let J of G)if(J==="--yes")z.yes=!0;else if(J==="--dry-run")z.dryRun=!0;else if(J==="--claustrum")z.claustrum=!0;else if(J==="--no-claustrum")z.noClaustrum=!0;else if(J==="--login")z.login=!0;else if(J==="--enroll-only")z.enrollOnly=!0;else if(J.startsWith("--host=")){let Z=J.slice(7);if(Z!=="opencode"&&Z!=="pi")throw Error(T0);z.hosts.push(Z)}else if(/^--opencode=(1|2|both)$/.test(J))z.opencode=J.slice(11);else throw Error(`Unknown setup argument: ${J}`);if(z.claustrum&&z.noClaustrum)throw Error("--claustrum and --no-claustrum cannot be used together.");if(z.login&&z.claustrum)throw Error("--login and --claustrum cannot be used together.");if(z.enrollOnly&&z.login)throw Error("--enroll-only and --login cannot be used together.");if(z.enrollOnly&&z.noClaustrum)throw Error("--enroll-only and --no-claustrum cannot be used together.");return z}function u1(G){for(let z of Object.values(G.packages))if(!/^(?:@[a-z0-9._-]+\/)?[a-z0-9._-]+$/.test(z))throw Error("Setup requires npm package names.");if(!/^\d+\.\d+\.\d+(?:-[a-zA-Z0-9.-]+)?(?:\+[a-zA-Z0-9.-]+)?$/.test(G.version))throw Error("Setup requires a concrete package version.");for(let z of Object.values(G.vault.hosts))if(!/^[a-z0-9][a-z0-9-]*$/.test(z.name))throw Error("Setup requires lowercase vault names containing only letters, digits and dashes.")}async function p1(G,z,J){let Z=[];for(let $ of z){let Q=J.get($)??"not-enrolled";if(Q==="unknown"){let{name:K,paths:D}=G.vault.hosts[$],j=await m(w(D),K).catch(()=>"unreadable");if(j==="vault")Q="enrolled";else if(j==="local")Q="not-enrolled"}Z.push({host:$,outcome:Q})}return Z}async function e(G,z=[],J={}){let Z=c1(z);u1(G);let $=J.terminal??A0(),Q=await p(G,J);B($,`${G.displayName} setup`);for(let[b,H]of[["OpenCode",Q.opencode],["Pi",Q.pi]])B($,`${b}: ${H.installed?`found (version ${H.version??"unknown"})`:"not found"} — ${H.directory}`);B($,`Claustrum: ${Q.claustrum.available?"available":"not available"}`);let K=Q.pi.installed&&!Q.pi.executable;if(K)B($,"Pi: skipped, because its folder exists but pi is not on PATH. Install the Pi CLI and rerun setup to add it.");let D=["opencode","pi"].filter((b)=>Q[b].installed&&!(b==="pi"&&K));if(Z.hosts.some((b)=>!D.includes(b)))throw Error(T0);let j=Z.yes||Z.dryRun&&!f($);if(!j&&!f($))throw Error("Setup requires a TTY or --yes.");let q=Z.hosts.length?D.filter((b)=>Z.hosts.includes(b)):j?D:await H0($,D)??[],x=Z.opencode??(Q.opencode.generation==="ambiguous"?"1":Q.opencode.generation);if(q.includes("opencode")&&!Z.opencode&&Q.opencode.generation==="ambiguous"){if(j||!f($))throw Error(I0);let b=await E($,[{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:Z.dryRun,mode:"local",detection:Q};x=b}if(!q.length)return B($,"No hosts selected. Install OpenCode or Pi and rerun setup."),{hosts:q,dryRun:Z.dryRun,mode:"local",detection:Q};let{env:X,platform:V}=N(J),W=J.fence??v(J.runner??T,{platform:V}),U=async()=>{try{await y(W,X)}catch(b){if(b instanceof M)B($,b.refusalText);throw b}};if(B($,"Checking that OpenCode and Pi are not running…"),Z.dryRun)try{let b=W.previewRunningHosts?await W.previewRunningHosts(X):{hosts:await W.listRunningHosts(X),uncheckedRuntimes:0},H=b.hosts;if(b.uncheckedRuntimes>0)B($,"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)B($,`${R} is running; setup will ask you to quit it.`)}catch(b){if(B($,"Process inspection failed; real setup will require successful inspection and stopped OpenCode/Pi hosts."),b instanceof M)B($,b.refusalText)}else await U();if((Z.claustrum||Z.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 F=Z.claustrum||Z.enrollOnly;if(!F&&!Z.login&&!Z.noClaustrum&&!j&&Q.claustrum.available&&f($)){let b=await E($,[{label:"No",value:!1},{label:"Yes",value:!0}],{message:"Connect these hosts to the Claustrum vault?"});if(b===null)return B($,"Setup cancelled. Nothing was changed."),{hosts:[],dryRun:Z.dryRun,mode:"local",detection:Q};F=b===!0}let Y=F?"claustrum":"local",C=!Z.enrollOnly&&q.includes("opencode")?n(G,x,J):[];for(let b of C){for(let O of b.existingLocalEntries??[])B($,`OpenCode: already registered from ${O} in ${b.path}.`);let H=[...b.existingLocalEntries??[],...b.existingNpmEntries??[]];if(H.length>1)B($,`Warning: ${G.displayName} may load twice in ${b.path}: ${H.join(", ")}. Entries were left unchanged.`)}if(Z.dryRun){B($,"Dry run: no registrations, enrollment, sign-in or migration will be performed.");for(let b of q){if(G.beforeSignIn)B($,`Would run beforeSignIn(${b}, ${Y}).`);if(F){let H=w(G.vault.hosts[b].paths);B($,`Would Connect ${b}: write ${H.statePath} and ${H.tokenPath}; wait for ck auth enroll approve.`)}else B($,`Would sign in locally for ${b}.`);if(!Z.enrollOnly&&G.beforeRegister)B($,`Would run beforeRegister(${b}, ${Y}).`)}for(let b of C)B($,`${b.changed?"Would write":"Unchanged"} ${b.path}:
12
- ${b.content}`);if(!Z.enrollOnly&&q.includes("pi"))B($,`Would run ${Q.pi.executable} install npm:${G.packages.pi}@${G.version}`);if(!Z.enrollOnly)for(let b of q)B($,`Would migrate ${b} using the plugin callback (provider-specific writes).`)}else{let b={opencodeGeneration:x,mode:Y,hosts:Object.freeze([...q]),piAgentDir:Q.pi.directory},H=new Map;try{for(let O of q){if(await U(),await G.beforeSignIn?.(O,b),await U(),F){H.set(O,"unknown");try{await F0(G,O,J,$,U)}catch(R){if(R instanceof A)H.set(O,"not-enrolled");throw R}H.set(O,"enrolled")}else await G.signInLocal(O,b);if(await U(),Z.enrollOnly)continue;if(await G.beforeRegister?.(O,Y,b),await U(),O==="opencode")await o(C,U);else await t(G,Q.pi.executable,J);await U(),await G.migrate(O,b)}}catch(O){if(H.size===0)throw O;try{let R=await p1(G,q,H);$0(O,R);for(let p0 of R)B($,Z0(p0))}catch{}throw O}}if(B($,`${Z.dryRun?"Planned":Z.enrollOnly?"Enrolled":"Configured"} ${G.displayName} for ${q.join(", ")} (${Y}).`),Z.enrollOnly)B($,`Enroll-only: no host config or plugin registration ${Z.dryRun?"will be":"was"} written.`),B($,"Next: register the plugin yourself in each selected host and enable vault access as required by the plugin.");else B($,`Next: ${q.includes("opencode")?"start OpenCode":"start Pi"} and run ${G.slashCommand}.`);return{hosts:q,dryRun:Z.dryRun,mode:Y,detection:Q}}var L={name:"@cortexkit/opencode-openai-auth",version:"1.8.1",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.27.1","@cortexkit/openai-auth-core":"workspace:*","@opencode/plugin":"2.2.0"},dependencies:{"@cortexkit/claustrum-client":"^0.13.0","@cortexkit/private-files":"^0.2.1","@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 n1}from"node:path";import{resolveClaustrumConnectionPath as o1}from"@cortexkit/claustrum-client";var _0={name:"@cortexkit/pi-openai-auth",version:"1.8.1",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.27.1","@cortexkit/openai-auth-core":"workspace:*"},dependencies:{"@cortexkit/claustrum-client":"^0.13.0","@cortexkit/private-files":"^0.2.1","@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{homedir as i1}from"node:os";import{join as P0}from"node:path";function s1(){return process.env.PI_AGENT_DIR?.trim()||P0(i1(),".pi","agent")}function S0(){return process.env.PI_OPENAI_AUTH_FILE?.trim()||P0(s1(),w0)}function r1(G=S0()){return process.env.PI_OPENAI_AUTH_STATE_FILE?.trim()||L0(G)}function v0(G=S0()){return{configPath:G,statePath:r1(G)}}function c0(G={}){let z=G.print??console.log,J=G.fence??v(),Z={opencode:{stateDir:G0(h0().statePath),host:"opencode"},pi:{stateDir:G0(v0().statePath),host:"pi"}},$=async(Q)=>{if(await m(w(Z[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:_0.name},version:L.version,displayName:"OpenAI Auth",slashCommand:"/openai",vault:{connectionFile:o1(),hosts:{opencode:{name:S("opencode"),paths:Z.opencode},pi:{name:S("pi"),paths:Z.pi}}},async beforeRegister(Q,K){if(K==="claustrum"){let D=await E0(w(Z[Q]),S(Q)),j=D.state==="approved"?D.approvedName:void 0,q=j??("proposedName"in D?D.proposedName:S(Q));if(!j)z("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(z(`Allow this host to read OpenAI accounts with:
13
- ck auth grant --principal enrolled:${q} --selector-kind category --selector ${f0.category} --operation read`),Q==="opencode")z("Then run opencode auth login and choose ChatGPT accounts in the vault to activate vault routing without local sign-in.");return}await $(Q)},async signInLocal(Q,K){if(await $(Q),Q==="pi"){z("Start Pi and run /login openai-codex to sign in with Pi itself.");return}if(K.opencodeGeneration!=="1"){let Y=n1(I("opencode2",G.io)??I("opencode",G.io)??"opencode");z(`In OpenCode 2, run ${Y} 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(d0(process.env))throw Error("Unset OPENCODE_AUTH_CONTENT before local setup sign-in.");let D=m0(),j={path:{id:"openai"}};if(await D.get(j)!==void 0){z("OpenCode already has an OpenAI login. Use opencode auth login to change it.");return}let q=G.beginLogin??y0,x=new AbortController,X=Boolean(process.env.SSH_CONNECTION||process.env.SSH_TTY||process.platform==="linux"&&!process.env.DISPLAY&&!process.env.WAYLAND_DISPLAY),V={version:L.version,signal:x.signal},W,U=!X;try{W=await q({...V,headless:X})}catch(Y){if(X)throw Y;U=!1,z("Browser callback unavailable; using device-code sign-in."),W=await q({version:L.version,headless:!0})}if(U){if(!(G.openBrowser??g0)(W.url))x.abort(),await W.completion.catch(()=>{}),z("Browser unavailable; using device-code sign-in."),W=await q({version:L.version,headless:!0})}z(`${W.url}
14
- ${W.instructions}`);let F=await W.completion;await y(J),await $(Q),await D.set({...j,body:{type:"oauth",access:F.access,refresh:F.refresh,expires:F.expires,...F.accountId?{accountId:F.accountId}:{}}}),z("Signed in to OpenCode. The first plugin start adopts this login into the account pool.")},async migrate(Q){z(`${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 u0({version:L.version}),await e(c0(),process.argv.slice(3))}catch(G){console.error(G instanceof Error?G.message:String(G)),process.exitCode=1}
10
+ `}},K=z,D=G[J],V=Array.isArray(D)?[...D]:[],q=V.flatMap((U,X)=>n(U)===Z?[X]:[]),j=`${Z}@${$}`;if(!q.length)K=r(K,N0(K,D===void 0?[J]:[J,V.length],D===void 0?[j]:j,Q));else{let U=q[0],X=V[U],Y=Array.isArray(X)?[j,...X.slice(1)]:X&&typeof X==="object"?{...X,package:j}:j;if(JSON.stringify(X)!==JSON.stringify(Y))K=r(K,N0(K,[J,U],Y,Q));for(let F of q.slice(1).reverse())K=k0(K,J,F)}let W=J==="plugin"?"plugins":"plugin";if(Array.isArray(G[W])){let U=G[W];for(let X=U.length-1;X>=0;X--)if(n(U[X])===Z)K=k0(K,W,X)}return K}function o(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`),W=$.exists(q)?q:$.exists(j)?j:q,U=$.exists(W),X=U?$.readText(W):`${JSON.stringify({$schema:`https://opencode.ai/${V==="tui"?"tui":"config"}.json`},null,2)}
11
+ `,Y=I0(X,K),F=[],B=[];for(let b of["plugin","plugins"]){if(!Array.isArray(Y[b]))continue;for(let H of Y[b]){let O=A0(H);if(O===null)continue;if(p2(O,W,Z)===z.packages.opencode)F.push(JSON.stringify(H));else if(n(H)===z.packages.opencode)B.push(JSON.stringify(H))}}if(F.length>0)return{path:W,content:X,changed:!1,existingLocalEntries:F,existingNpmEntries:B};let C=_0(X,K,z.packages.opencode,z.version);return{path:W,content:C,changed:!U||C!==X}})}async function t(z,J){for(let Z of z){if(!Z.changed)continue;await J?.(),await R0(Z.path,Z.content,{beforeRename:J})}}async function e(z,J,Z={}){let{platform:$,env:G}=k(Z),Q=await g(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 w0="Multiple OpenCode generations found. Choose --opencode=1|2|both before running noninteractive setup.";function l2(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 a2(z,J,Z){let $=[];for(let G of J){let Q=Z.get(G)??"not-enrolled";if(Q==="unknown"){let{name:K,paths:D}=z.vault.hosts[G],V=await c(w(D),K).catch(()=>"unreadable");if(V==="vault")Q="enrolled";else if(V==="local")Q="not-enrolled"}$.push({host:G,outcome:Q})}return $}async function z0(z,J=[],Z={}){let $=M0(J);l2(z);let G=Z.terminal??T0(),Q=await l(z,Z);x(G,`${z.displayName} setup`);for(let[b,H]of[["OpenCode",Q.opencode],["Pi",Q.pi]])x(G,`${b}: ${H.installed?`found (version ${H.version??"unknown"})`:"not found"} — ${H.directory}`);x(G,`Claustrum: ${Q.claustrum.available?"available":"not available"}`);let K=Q.pi.installed&&!Q.pi.executable;if(K)x(G,"Pi: skipped, because its folder exists but pi is not on PATH. Install the Pi CLI and rerun setup to add it.");let D=["opencode","pi"].filter((b)=>Q[b].installed&&!(b==="pi"&&K));if($.hosts.some((b)=>!D.includes(b)))throw Error(O0);let V=$.yes||$.dryRun&&!f(G);if(!V&&!f(G))throw Error("Setup requires a TTY or --yes.");let q=$.hosts.length?D.filter((b)=>$.hosts.includes(b)):V?D:await C0(G,D)??[],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(w0);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 x(G,"No hosts selected. Install OpenCode or Pi and rerun setup."),{hosts:q,dryRun:$.dryRun,mode:"local",detection:Q};let{env:W,platform:U}=k(Z),X=Z.fence??y(Z.runner??_,{platform:U}),Y=async()=>{try{await v(X,W)}catch(b){if(b instanceof M)x(G,b.refusalText);throw b}};if(x(G,"Checking that OpenCode and Pi are not running…"),$.dryRun)try{let b=X.previewRunningHosts?await X.previewRunningHosts(W):{hosts:await X.listRunningHosts(W),uncheckedRuntimes:0},H=b.hosts;if(b.uncheckedRuntimes>0)x(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)x(G,`${R} is running; setup will ask you to quit it.`)}catch(b){if(x(G,"Process inspection failed; real setup will require successful inspection and stopped OpenCode/Pi hosts."),b instanceof M)x(G,b.refusalText)}else await Y();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 F=$.claustrum||$.enrollOnly;if(!F&&!$.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 x(G,"Setup cancelled. Nothing was changed."),{hosts:[],dryRun:$.dryRun,mode:"local",detection:Q};F=b===!0}let B=F?"claustrum":"local",C=!$.enrollOnly&&q.includes("opencode")?o(z,j,Z):[];for(let b of C){for(let O of b.existingLocalEntries??[])x(G,`OpenCode: already registered from ${O} in ${b.path}.`);let H=[...b.existingLocalEntries??[],...b.existingNpmEntries??[]];if(H.length>1)x(G,`Warning: ${z.displayName} may load twice in ${b.path}: ${H.join(", ")}. Entries were left unchanged.`)}if($.dryRun){x(G,"Dry run: no registrations, enrollment, sign-in or migration will be performed.");for(let b of q){if(z.beforeSignIn)x(G,`Would run beforeSignIn(${b}, ${B}).`);if(F){let H=w(z.vault.hosts[b].paths);x(G,`Would Connect ${b}: write ${H.statePath} and ${H.tokenPath}; wait for ck auth enroll approve.`)}else x(G,`Would sign in locally for ${b}.`);if(!$.enrollOnly&&z.beforeRegister)x(G,`Would run beforeRegister(${b}, ${B}).`)}for(let b of C)x(G,`${b.changed?"Would write":"Unchanged"} ${b.path}:
12
+ ${b.content}`);if(!$.enrollOnly&&q.includes("pi"))x(G,`Would run ${Q.pi.executable} install npm:${z.packages.pi}@${z.version}`);if(!$.enrollOnly&&z.migrate)for(let b of q)x(G,`Would migrate ${b} using the plugin callback (provider-specific writes).`)}else{let b={opencodeGeneration:j,mode:B,hosts:Object.freeze([...q]),piAgentDir:Q.pi.directory},H=new Map;try{for(let O of q){if(await Y(),await z.beforeSignIn?.(O,b),await Y(),F){H.set(O,"unknown");try{await H0(z,O,Z,G,Y)}catch(R){if(R instanceof A)H.set(O,"not-enrolled");throw R}H.set(O,"enrolled")}else await z.signInLocal(O,b);if(await Y(),$.enrollOnly)continue;if(await z.beforeRegister?.(O,B,b),await Y(),O==="opencode")await t(C,Y);else await e(z,Q.pi.executable,Z);await Y(),await z.migrate?.(O,b)}}catch(O){if(H.size===0)throw O;try{let R=await a2(z,q,H);Q0(O,R);for(let a0 of R)x(G,G0(a0))}catch{}throw O}}if(x(G,`${$.dryRun?"Planned":$.enrollOnly?"Enrolled":"Configured"} ${z.displayName} for ${q.join(", ")} (${B}).`),$.enrollOnly)x(G,`Enroll-only: no host config or plugin registration ${$.dryRun?"will be":"was"} written.`),x(G,"Next: register the plugin yourself in each selected host and enable vault access as required by the plugin.");else x(G,`Next: ${q.includes("opencode")?"start OpenCode":"start Pi"} and run ${z.slashCommand}.`);return{hosts:q,dryRun:$.dryRun,mode:B,detection:Q}}var L={name:"@cortexkit/opencode-openai-auth",version:"1.8.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.29.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 t2}from"node:path";import{resolveClaustrumConnectionPath as e2}from"@cortexkit/claustrum-client";var L0={name:"@cortexkit/pi-openai-auth",version:"1.8.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.29.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{homedir as r2}from"node:os";import{join as y0}from"node:path";function n2(){return process.env.PI_AGENT_DIR?.trim()||y0(r2(),".pi","agent")}function v0(){return process.env.PI_OPENAI_AUTH_FILE?.trim()||y0(n2(),P0)}function o2(z=v0()){return process.env.PI_OPENAI_AUTH_STATE_FILE?.trim()||S0(z)}function E0(z=v0()){return{configPath:z,statePath:o2(z)}}function p0(z={}){let J=z.print??console.log,Z=z.fence??y(),$={opencode:{stateDir:J0(d0().statePath),host:"opencode"},pi:{stateDir:J0(E0().statePath),host:"pi"}},G=async(Q)=>{if(await c(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:L0.name},version:L.version,displayName:"OpenAI Auth",slashCommand:"/openai",vault:{connectionFile:e2(),hosts:{opencode:{name:S("opencode"),paths:$.opencode},pi:{name:S("pi"),paths:$.pi}}},async beforeRegister(Q,K){if(K==="claustrum"){let D=await g0(w($[Q]),S(Q)),V=D.state==="approved"?D.approvedName:void 0,q=V??("proposedName"in D?D.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
+ ck auth grant --principal enrolled:${q} --selector-kind category --selector ${h0.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 B=t2(I("opencode2",z.io)??I("opencode",z.io)??"opencode");J(`In OpenCode 2, run ${B} 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(c0(process.env))throw Error("Unset OPENCODE_AUTH_CONTENT before local setup sign-in.");let D=u0(),V={path:{id:"openai"}};if(await D.get(V)!==void 0){J("OpenCode already has an OpenAI login. Use opencode auth login to change it.");return}let q=z.beginLogin??f0,j=new AbortController,W=Boolean(process.env.SSH_CONNECTION||process.env.SSH_TTY||process.platform==="linux"&&!process.env.DISPLAY&&!process.env.WAYLAND_DISPLAY),U={version:L.version,signal:j.signal},X,Y=!W;try{X=await q({...U,headless:W})}catch(B){if(W)throw B;Y=!1,J("Browser callback unavailable; using device-code sign-in."),X=await q({version:L.version,headless:!0})}if(Y){if(!(z.openBrowser??m0)(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
+ ${X.instructions}`);let F=await X.completion;await v(Z),await G(Q),await D.set({...V,body:{type:"oauth",access:F.access,refresh:F.refresh,expires:F.expires,...F.accountId?{accountId:F.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 l0({version:L.version}),await z0(p0(),process.argv.slice(3))}catch(z){console.error(z instanceof Error?z.message:String(z)),process.exitCode=1}
@@ -1,2 +1,2 @@
1
- import{Hc as NZ,Ic as PZ,Kc as g,Lc as WZ,Mc as HZ,Pc as d,ne as _Z,qe as TZ,se as RZ}from"./index-b7p76qqa.js";import{Ae as XZ,Fe as VZ,Ge as YZ,He as y,Ie as x}from"./index-73z9ftrg.js";import{$e as OZ}from"./index-h1r8cbet.js";import{if as b,jf as $Z,nf as A,of as JZ}from"./index-mg4w434p.js";import{createHash as cZ}from"node:crypto";import{constants as oZ,copyFileSync as aZ,mkdirSync as iZ,statSync as sZ}from"node:fs";import{readFile as nZ}from"node:fs/promises";import{homedir as eZ,tmpdir as tZ}from"node:os";import{dirname as Z0,join as h}from"node:path";import{chmod as dZ,mkdir as lZ}from"node:fs/promises";import{dirname as ZZ}from"node:path";function k(Z){let{path:$,defaultValue:V,normalize:J}=Z,X=Promise.resolve(),Y=(B)=>{if(B==="")return V;try{return J(JSON.parse(B))}catch{return V}},G=async()=>{try{if(b)await A(ZZ($),Z.secureDir??!0);return await JZ($,b)}catch(B){if(B.code==="ENOENT")return"";throw B}},z=async()=>{try{return Y(await G())}catch(B){if(B instanceof $Z)throw B;return V}},U=(B,D)=>{let N=X.then(B).then((P)=>D?.onResult?.(P));return X=N.catch(()=>{}),N},L={...x.sidebar,name:Z.lockName??x.sidebar.name,timeoutMs:Z.timeoutMs??x.sidebar.timeoutMs},j=async(B,D,N)=>{await XZ($,D,{serialize:JSON.stringify,beforeRename:async()=>{await N?.beforeCommit?.(),await B.assertOwned()}}),await N?.afterRename?.();try{return await B.assertOwned(),!0}catch(P){if(P instanceof YZ)return!1;throw P}},Q=async(B,D,N)=>{Z.logger?.warn("sidebar lock lost after rename; repairing write",{path:$});try{let P=await y($,L,async(W)=>{let H=B(await z(),D);if(H===void 0)return"skipped";return await j(W,H,N)?"written":"lost-again"});if(P==="lost-again")Z.logger?.warn("sidebar repair lost its lock after rename",{path:$});return{status:"lost-after-rename",repair:P}}catch(P){if(!(P instanceof VZ))throw P;return Z.logger?.warn("sidebar repair lock unavailable; repair skipped",{path:$}),{status:"lost-after-rename",repair:"lock-unavailable"}}},K=async(B,D)=>{let N=D,P=ZZ($),W=Z.secureDir??!0;if(b)await A(P,W);else if(await lZ(P,{recursive:!0,mode:448}),W)await dZ(P,448).catch((F)=>{Z.logger?.warn("sidebar directory permission remediation failed",{error:F instanceof Error?F.message:String(F)})});let H=await y($,L,async(F)=>{let s=async(C)=>({value:C,held:await j(F,C,N)});for(let C=0;C<3;C+=1){let e=await G(),t=B(Y(e));if(t===void 0)return;if(C===0)await N?.beforeRecheck?.();if(await G()!==e)continue;return await s(t)}let n=B(await z());return n===void 0?void 0:await s(n)});if(H===void 0)return{status:"skipped"};if(H.held)return{status:"written"};let i=D?.repair??Z.repair;if(!i)return Z.logger?.warn("sidebar lock lost after rename; write not repaired",{path:$}),{status:"lost-after-rename",repair:"none"};return await Q(i,H.value,N)};return{read:z,write:(B,D)=>U(()=>K(()=>B,D),D),update:(B,D)=>U(()=>K(B,D),D)}}function v0(Z){let $=Z?.credits;if($===null||typeof $!=="object")return;let{hasCredits:V,unlimited:J,balance:X}=$;if(typeof V!=="boolean"||typeof J!=="boolean")return;return WZ({hasCredits:V,unlimited:J,...typeof X==="number"?{balance:X}:{}})}function f0(Z,$=Date.now()){if(!xZ(Z,$))return!1;if(bZ(Z,$))return!1;return RZ(Z?.credits,$)}var l=["primary","secondary"],uZ={primary:300,secondary:10080};function rZ(Z,$){return NZ({scope:"all",label:$,windowMinutes:Z})}function S0(Z){if(!Z)return[];let $=[];for(let V of l){let J=Z[V];if(!J)continue;let X=J.windowMinutes,Y=X!==void 0&&Number.isFinite(X)&&X>0?X:uZ[V];$.push({key:V,label:rZ(X,V),window:J,windowMs:Y*60000})}return $}var M=OZ("sidebar"),$0="OPENCODE_OPENAI_AUTH_SIDEBAR_STATE_FILE";function CZ(){let Z=process.env.XDG_STATE_HOME||h(eZ(),".local","state");return h(Z,"cortexkit","openai-auth","sidebar-state.json")}var FZ=h(tZ(),"opencode-openai-auth","sidebar-state.json");function g0(Z){FZ=Z,p.clear()}var J0=/^[a-f0-9]{64}$/,u=604800000,MZ=256,EZ=3600000;function T(Z){return cZ("sha256").update(Z).digest("hex")}function X0(Z){return typeof Z==="number"&&Number.isFinite(Z)&&Z>=0?Z:void 0}function qZ(Z){let $=X0(Z);return $!==void 0?{resetCredits:$}:{}}function V0(Z){if(Z===null||typeof Z!=="object"||Array.isArray(Z))return;let $={};for(let[V,J]of Object.entries(Z)){if(J===null||typeof J!=="object"||Array.isArray(J))continue;let X=J;if(typeof X.activeId!=="string"||typeof X.route!=="string"||typeof X.updatedAt!=="number"||!Number.isFinite(X.updatedAt))continue;$[V]={activeId:X.activeId,route:X.route,updatedAt:X.updatedAt}}return Object.keys($).length>0?$:void 0}function Y0(Z){if(Z===null||typeof Z!=="object"||Array.isArray(Z))return;let $={};for(let[V,J]of Object.entries(Z)){if(!J0.test(V)||J===null||typeof J!=="object"||Array.isArray(J))continue;let X=J;if(typeof X.accountId!=="string"||X.accountId.length===0||typeof X.assignedAt!=="number"||!Number.isFinite(X.assignedAt)||X.assignedAt<0||typeof X.lastSeenAt!=="number"||!Number.isFinite(X.lastSeenAt)||X.lastSeenAt<0||typeof X.inputBytes!=="number"||!Number.isFinite(X.inputBytes)||X.inputBytes<0)continue;let Y=X.quotaCheckedAt;if(Y!==void 0&&(typeof Y!=="number"||!Number.isFinite(Y)||Y<0))continue;let G=X.wireAccountId;$[V]={accountId:X.accountId,assignedAt:X.assignedAt,lastSeenAt:X.lastSeenAt,inputBytes:X.inputBytes,...Y===void 0?{}:{quotaCheckedAt:Y},...typeof G==="string"?{wireAccountId:G}:{}}}return Object.keys($).length>0?$:void 0}function O(){let Z=process.env[$0];if(Z)return Z;let $=CZ();if(!p.has($))p.add($),z0($,FZ);return $}var p=new Set;function z0(Z,$){try{iZ(Z0(Z),{recursive:!0,mode:448}),aZ($,Z,oZ.COPYFILE_EXCL)}catch{}}var q={main:{quota:null,killed:!1},fallbacks:[],activeId:void 0,route:"main",lastUpdated:0};function S(Z){if(Z===null||typeof Z!=="object"||Array.isArray(Z))return q;let $=Z,V=$.main,J;if(V!==null&&typeof V==="object"&&!Array.isArray(V)){let K=V;J={quota:"quota"in K?K.quota:null,killed:typeof K.killed==="boolean"?K.killed:!1,...typeof K.mainAccountId==="string"?{mainAccountId:K.mainAccountId}:{},...typeof K.quotaBackedOff==="boolean"?{quotaBackedOff:K.quotaBackedOff}:{},...typeof K.quotaBackoffUntil==="number"?{quotaBackoffUntil:K.quotaBackoffUntil}:{},...typeof K.refreshBackedOff==="boolean"?{refreshBackedOff:K.refreshBackedOff}:{},...typeof K.refreshBackoffUntil==="number"?{refreshBackoffUntil:K.refreshBackoffUntil}:{},...qZ(K.resetCredits)}}else J={quota:null,killed:!1};let X=zZ($.fallbacks),Y=Array.isArray($.vaultAccounts)?zZ($.vaultAccounts):void 0,G=typeof $.activeId==="string"?$.activeId:void 0,z=typeof $.route==="string"?$.route:q.route,U=typeof $.lastUpdated==="number"?$.lastUpdated:0,L=typeof $.planType==="string"?$.planType:void 0,j=V0($.activeRouting),Q=Y0($.stickyAssignments);return{main:J,fallbacks:X,activeId:G,route:z,lastUpdated:U,...j!==void 0?{activeRouting:j}:{},...Q!==void 0?{stickyAssignments:Q}:{},...L!==void 0?{planType:L}:{},...$.accountPool===!0?{accountPool:!0}:{},...Y!==void 0?{vaultAccounts:Y}:{},...typeof $.vaultDiscovered==="boolean"?{vaultDiscovered:$.vaultDiscovered}:{}}}function zZ(Z){if(!Array.isArray(Z))return[];return Z.filter(($)=>$!==null&&typeof $==="object"&&!Array.isArray($)&&typeof $.id==="string").map(($)=>({id:$.id,...typeof $.credentialId==="string"?{credentialId:$.credentialId}:{},label:typeof $.label==="string"?$.label:void 0,...typeof $.accountId==="string"?{accountId:$.accountId}:{},quota:"quota"in $?$.quota:null,killed:typeof $.killed==="boolean"?$.killed:!1,enabled:typeof $.enabled==="boolean"?$.enabled:!0,...typeof $.routable==="boolean"?{routable:$.routable}:{},...["needs sign-in","turned off in vault","unavailable"].includes($.vaultState)?{vaultState:$.vaultState}:{},...qZ($.resetCredits)}))}function r(Z){return[...Z.fallbacks,...Z.vaultAccounts??[]]}async function G0(Z=O()){try{let $=await nZ(Z,"utf8");return S(JSON.parse($))}catch{return q}}var K0=3600000,GZ=128;function IZ(Z,$,V=Date.now()){if(!(Z.updatedAt>=V-K0&&Z.updatedAt<=V))return!1;if($===void 0)return!0;return Z.activeId==="main"||$.some((X)=>X.enabled!==!1&&X.routable!==!1&&X.killed!==!0&&X.id===Z.activeId)}function bZ(Z,$=Date.now()){let V=Z?.spendControl;if(V?.reached!==!0||typeof V.resetsAt!=="string")return;let J=Date.parse(V.resetsAt);if(!Number.isFinite(J)||J<=$)return;return{resetsAt:V.resetsAt,resetAtMs:J}}function xZ(Z,$=Date.now()){let V;for(let X of l){let Y=Z?.[X];if(typeof Y?.resetsAt!=="string"||!Number.isFinite(Y.usedPercent)||Y.usedPercent<100)continue;let G=Date.parse(Y.resetsAt);if(!Number.isFinite(G)||G<=$)continue;if(!V||G<V.resetAtMs)V={resetsAt:Y.resetsAt,resetAtMs:G}}let J=bZ(Z,$);if(J&&(!V||J.resetAtMs<V.resetAtMs))V=J;return V}function E(Z,$=Date.now()){return xZ(Z,$)!==void 0}function j0(Z,$,V=Date.now()){if(!$||Z.route!=="sticky-balanced")return;let J=Z.stickyAssignments?.[T($)];if(!J||J.lastSeenAt<V-u)return;if(J.accountId==="main"&&Z.vaultAccounts===void 0)return Z.main?.killed||E(Z.main?.quota,V)?void 0:"main";let X=r(Z).find((Y)=>Y.id===J.accountId);if(!X||X.enabled===!1||X.routable===!1||X.killed===!0||E(X.quota,V))return;return X.id}function d0(Z,$,V=Date.now()){if(!$){if(Z.vaultAccounts===void 0)return{activeId:Z.activeId??"main",route:Z.route};let j=Z.vaultAccounts.find((Q)=>Q.id===Z.activeId&&Q.enabled&&Q.routable!==!1&&!Q.killed);if(j&&!E(j.quota,V))return{activeId:j.id,route:Z.route}}let J=$?Z.activeRouting?.[$]:void 0,X=r(Z),Y=J?.activeId==="main"?Z.main.quota:X.find((j)=>j.id===J?.activeId)?.quota;if(J&&(Z.vaultAccounts===void 0||J.activeId.startsWith("vault:"))&&IZ(J,X,V)&&!E(Y,V))return{activeId:J.activeId,route:J.route};let G=j0(Z,$,V);if(G)return{activeId:G,route:Z.route};let z=Z.vaultAccounts!==void 0,U=(z?c(Z):Z.fallbacks).filter((j)=>j.enabled&&j.routable!==!1&&!j.killed),L=U.find((j)=>!E(j.quota,V))??U[0];return{activeId:z?L?.id??"vault":Z.route==="fallback-first"&&L?L.id:"main",route:Z.route}}function c(Z){let $=Z.vaultAccounts??[],V=new Map($.map((J)=>[J.id,J]));return d($.map((J)=>J.id),gZ(Z),_Z($)??"").flatMap((J)=>{let X=V.get(J);return X?[X]:[]})}function vZ(Z,$,V=Date.now(),J){if(!Z)return;let X=Object.entries(Z).filter(([G,z])=>G!==J&&IZ(z,$,V)),Y=X.length<=GZ?X:X.sort((G,z)=>z[1].updatedAt-G[1].updatedAt).slice(0,GZ);return Y.length>0?Object.fromEntries(Y):void 0}function I(Z,$,V=Date.now(),J){if(!Z)return;let X=0,Y=0,G=0,z=[];for(let[L,j]of Object.entries(Z)){if(L===J){G+=1;continue}if(j.lastSeenAt<V-u){Y+=1;continue}if($!==void 0&&!$.has(j.accountId)){X+=1;continue}z.push([L,j])}let U=X+Y+G;if(U>0)M.debug("pruned sticky assignments",{pid:process.pid,removed:U,reasons:{"account-not-in-roster":X,expired:Y,"explicit-removal":G}});return z.length>0?Object.fromEntries(z):void 0}function fZ(Z,$){let V=Object.keys(Z).length-MZ;if(V<=0)return Z;let J=new Set(Object.entries(Z).filter(([X])=>X!==$).sort(([X,Y],[G,z])=>Y.lastSeenAt-z.lastSeenAt||X.localeCompare(G)).slice(0,V).map(([X])=>X));return Object.fromEntries(Object.entries(Z).filter(([X])=>!J.has(X)))}function SZ(Z,$){if(Z===$)return!0;if(!Z||!$)return!1;let V=Object.entries(Z);if(V.length!==Object.keys($).length)return!1;return V.every(([J,X])=>Object.is($[J],X))}function AZ(Z,$,V,J){return Z!==void 0&&$.has(Z.accountId)&&!V.has(Z.accountId)&&Z.lastSeenAt>=J-u}function yZ(Z,$,V,J){return $>Z.inputBytes||V-Z.lastSeenAt>=EZ||Z.wireAccountId===void 0&&J!==void 0}function kZ(Z,$){return typeof Z.wireAccountId==="string"&&typeof $==="string"&&Z.wireAccountId!==$}function L0(Z){let $=new Map(Z),V={get size(){return $.size},has:(J)=>$.has(J),get:(J)=>$.get(J),entries:()=>$.entries(),keys:()=>$.keys(),values:()=>$.values(),forEach:(J,X)=>{$.forEach((Y,G)=>{J.call(X,Y,G,V)})},[Symbol.iterator]:()=>$[Symbol.iterator]()};return Object.freeze(V)}function B0(Z,$,V){let J=new Map;for(let[X,Y]of Object.entries(Z??{})){if(X===V)continue;if(Y.quotaCheckedAt!==$[Y.accountId])continue;J.set(Y.accountId,(J.get(Y.accountId)??0)+Y.inputBytes)}return L0(J)}function o(Z){if(Z===void 0)return;return new Set(["main",...Z.filter(($)=>$.enabled!==!1&&$.killed!==!0).map(($)=>$.id)])}var m=Promise.resolve();function _(Z){let $=m.then(Z);return m=$.catch(()=>{}),$}var KZ=new Map;function a(Z){let $=KZ.get(Z);if(!$)$=k({path:Z,defaultValue:q,normalize:S,secureDir:Z===CZ(),logger:M}),KZ.set(Z,$);return $}var w=new Set;async function wZ(Z,$){try{await $}catch(V){let J={pid:process.pid,error:V instanceof Error?V.message:String(V)};if(w.has(Z))M.debug("sidebar write failed again",J);else w.add(Z),M.warn("sidebar write failed",J);throw V}if(w.delete(Z))M.info("sidebar write recovered",{pid:process.pid})}function l0(Z,$=O()){return _(()=>wZ($,a($).write(S(Z))))}function U0(Z){return a(Z).read()}function R(Z,$,V){let J=Symbol("sidebar authority changed");return wZ(Z,a(Z).update((X)=>{if(V?.canWrite&&!V.canWrite())return;let Y=$(X);if(Y===void 0)return;if(Y.vaultAccounts!==void 0)Y.activeId=Y.activeId?.startsWith("vault:")?Y.activeId:void 0,Y.activeRouting=Object.fromEntries(Object.entries(Y.activeRouting??{}).filter(([,G])=>G.activeId.startsWith("vault:"))),Y.stickyAssignments=Object.fromEntries(Object.entries(Y.stickyAssignments??{}).filter(([,G])=>G.accountId.startsWith("vault:")&&!Y.vaultAccounts?.some((z)=>z.id===G.accountId&&z.killed)));return S(Y)},{beforeRecheck:async(...X)=>{if(await V?.beforeRecheck?.(...X),V?.canWrite&&!V.canWrite())throw J}}).catch((X)=>{if(X!==J)throw X}))}function v(Z){let $;for(let V of[Z?.primary?.checkedAt,Z?.secondary?.checkedAt,Z?.checkedAt])if(typeof V==="number"&&Number.isFinite(V))$=$===void 0?V:Math.max($,V);return $}function jZ(Z,$){let V=v(Z),J=v($);if(J!==void 0&&(V===void 0||J>V))return $;return Z}function LZ(Z,$){return Z!==void 0&&$!==void 0&&Z===$}function f(Z,$){let V=Z?.checkedAt;if(typeof V==="number"&&Number.isFinite(V))return V;if(typeof $==="number"&&Number.isFinite($))return $;return}function BZ(Z,$,V,J,X){if(Z&&$){let Y=f(Z,J),G=f($,X);if(G!==void 0&&(Y===void 0||G>Y))return $;return Z}return V?$:Z}function UZ(Z,$){if(Z.spendControl!==void 0)return Z.spendControl;if(Z.spendControlCleared===!0)return;return $.spendControl}function Q0(Z,$){if(!Z||!$)return Z??$;let V=(J)=>typeof J.checkedAt==="number"&&Number.isFinite(J.checkedAt)?J.checkedAt:Number.NEGATIVE_INFINITY;return V($)>V(Z)?$:Z}function QZ(Z,$){if(!Z)return $;if(!$)return Z;let V=v(Z),J=v($),X=J!==void 0&&(V===void 0||J>V),Y=BZ(Z.primary,$.primary,X,Z.checkedAt,$.checkedAt),G=BZ(Z.secondary,$.secondary,X,Z.checkedAt,$.checkedAt),z=X?UZ($,Z):UZ(Z,$),U=z===void 0&&(Z.spendControlCleared===!0||$.spendControlCleared===!0),L=Q0(Z.credits,$.credits),j;for(let N of[f(Y),f(G)])if(N!==void 0)j=j===void 0?N:Math.max(j,N);let{spendControl:Q,spendControlCleared:K,credits:B,...D}=Z;return{...D,primary:Y,secondary:G,...z!==void 0?{spendControl:z}:{},...U?{spendControlCleared:!0}:{},...L!==void 0?{credits:L}:{},checkedAt:j??Z.checkedAt}}function u0(Z,$=O(),V){return _(async()=>{await R($,(J)=>{let X=new Map(J.fallbacks.map((j)=>[j.id,j])),Y=Z.vaultAccounts!==void 0,G=LZ(Z.main.mainAccountId,J.main.mainAccountId),z=G?QZ(Z.main.quota,J.main.quota):jZ(Z.main.quota,J.main.quota),U=Date.now(),L=I(J.stickyAssignments,Y?void 0:o(r(Z)),U);return{...J,...Z,main:Y?Z.main:{...Z.main,quota:z,mainAccountId:G?Z.main.mainAccountId:z===J.main.quota&&z!==Z.main.quota?J.main.mainAccountId:Z.main.mainAccountId},fallbacks:Y?Z.fallbacks:Z.fallbacks.map((j)=>{let Q=X.get(j.id),K=LZ(j.accountId,Q?.accountId),B=K?QZ(j.quota,Q?.quota??null):jZ(j.quota,Q?.quota??null);return{...j,quota:B,accountId:K?j.accountId:B===Q?.quota&&B!==j.quota?Q?.accountId:j.accountId}}),activeId:J.activeId,activeRouting:J.activeRouting,stickyAssignments:L,lastUpdated:Math.max(U,J.lastUpdated+1),accountPool:Z.accountPool===!0?!0:void 0,vaultAccounts:Z.vaultAccounts,vaultDiscovered:Z.vaultDiscovered}},V)})}function r0(Z,$,V=O(),J){return _(async()=>{await R(V,(X)=>{let Y=vZ({...X.activeRouting,[Z.sessionId]:{activeId:Z.activeId,route:Z.route,updatedAt:Z.updatedAt}},$,Date.now()),G=I(X.stickyAssignments,X.vaultAccounts!==void 0?void 0:o($),Date.now());return{...X,activeId:Z.activeId,route:Z.route,activeRouting:Y,stickyAssignments:G,lastUpdated:Math.max(Date.now(),X.lastUpdated+1)}},J)})}function c0(Z,$=O(),V){return _(async()=>{await R($,(J)=>({...J,activeId:Z.activeId,route:Z.route,lastUpdated:Math.max(Date.now(),J.lastUpdated+1)}),V)})}function o0(Z,$,V=O(),J){return _(async()=>{await R(V,(X)=>{let Y=Date.now(),G=vZ(X.activeRouting,$,Y,Z),z=I(X.stickyAssignments,X.vaultAccounts!==void 0?void 0:o($),Y,T(Z));return{...X,activeRouting:G,stickyAssignments:z,lastUpdated:Math.max(Date.now(),X.lastUpdated+1)}},J)})}function hZ(Z,$){return AZ(Z,new Set($.validPinnedAccountIds),new Set($.excludeAccountIds),$.now)&&!kZ(Z,$.wireAccountIdByAccount?.[Z.accountId])&&!yZ(Z,$.requestBytes,$.now,$.wireAccountIdByAccount?.[Z.accountId])}function pZ(Z,$){let V=T($.sessionId),J=new Set($.validPinnedAccountIds),X=new Set($.excludeAccountIds),Y=I(Z.stickyAssignments,J,$.now),G=!SZ(Z.stickyAssignments,Y),z=Y?.[V],U=z!==void 0&&kZ(z,$.wireAccountIdByAccount?.[z.accountId]);if(AZ(z,J,X,$.now)&&!U){let Q=yZ(z,$.requestBytes,$.now,$.wireAccountIdByAccount?.[z.accountId]),K=Q?{...z,inputBytes:Math.max(z.inputBytes,$.requestBytes),...z.wireAccountId===void 0&&$.wireAccountIdByAccount?.[z.accountId]!==void 0?{wireAccountId:$.wireAccountIdByAccount?.[z.accountId]}:{},...$.now-z.lastSeenAt>=EZ?{lastSeenAt:$.now}:{}}:z;if(!G&&!Q)return{assignment:K,next:void 0};return{assignment:K,next:{...Z,stickyAssignments:{...Y,[V]:K},lastUpdated:Math.max($.now,Z.lastUpdated+1)}}}let L=$.choose(B0(Y,$.quotaCheckedAtByAccount,U?V:void 0));if(!L){if(!G)return{assignment:void 0,next:void 0};return{assignment:void 0,next:{...Z,stickyAssignments:Y,lastUpdated:Math.max($.now,Z.lastUpdated+1)}}}let j={accountId:L.accountId,assignedAt:$.now,lastSeenAt:$.now,inputBytes:$.requestBytes,...L.quotaCheckedAt===void 0?{}:{quotaCheckedAt:L.quotaCheckedAt},...$.wireAccountIdByAccount?.[L.accountId]===void 0?{}:{wireAccountId:$.wireAccountIdByAccount?.[L.accountId]}};return{assignment:j,next:{...Z,stickyAssignments:fZ({...Y,[V]:j},V),lastUpdated:Math.max($.now,Z.lastUpdated+1)}}}async function a0(Z,$=O(),V){let J=T(Z.sessionId),X=(await U0($)).stickyAssignments?.[J];if(hZ(X,Z))return X;let Y;return await _(async()=>{await R($,(G)=>{let z=pZ(G,Z);return Y=z.assignment,z.next},V)}),Y}function i0(Z,$){let V=Z.stickyAssignments?.[T($.sessionId)];if(hZ(V,$))return{assignment:V,next:void 0};return pZ(Z,$)}function s0(Z,$=O()){let V=T(Z.sessionId),J=new Set(Z.validPinnedAccountIds);return _(async()=>{await R($,(X)=>{let Y=Date.now(),G=I(X.stickyAssignments,X.vaultAccounts!==void 0?void 0:J,Y),z=G?.[V];if(z&&z.assignedAt>Z.assignment.assignedAt){if(SZ(X.stickyAssignments,G))return;return{...X,stickyAssignments:G,lastUpdated:Math.max(Y,X.lastUpdated+1)}}let L=z!==void 0&&z.accountId===Z.assignment.accountId&&z.assignedAt===Z.assignment.assignedAt?{...Z.assignment,inputBytes:Math.max(z.inputBytes,Z.assignment.inputBytes),lastSeenAt:Math.max(z.lastSeenAt,Z.assignment.lastSeenAt)}:Z.assignment;return{...X,stickyAssignments:fZ({...G,[V]:L},V),lastUpdated:Math.max(Y,X.lastUpdated+1)}})})}async function n0(Z,$=O()){let V=T(Z),J=!1;return await _(async()=>{await R($,(X)=>{let Y=X.stickyAssignments;if(Y?.[V]===void 0){J=!1;return}J=!0;let{[V]:G,...z}=Y;return{...X,...Object.keys(z).length>0?{stickyAssignments:z}:{stickyAssignments:void 0},lastUpdated:Math.max(Date.now(),X.lastUpdated+1)}})}),J}function e0(){return m}var D0=500;function N0(Z,$,V){return new Promise((J,X)=>{let Y=setTimeout(()=>J(V()),$);Y.unref?.(),Z.then((G)=>{clearTimeout(Y),J(G)},(G)=>{clearTimeout(Y),X(G)})})}function t0(Z,$={}){let V=$.readBudgetMs??D0,J,X,Y=()=>{try{let z=sZ(Z);return`${z.ino}:${z.size}:${z.mtimeMs}`}catch{return}},G=(z)=>{if(X&&X.key===z)return X.promise;let U=Date.now(),L=G0(Z).then((K)=>{if(!J||J.readAt<=U)J={state:K,readAt:U,key:z};return{state:K,readAt:U}}),j={key:z,promise:L};X=j;let Q=()=>{if(X===j)X=void 0};return L.then(Q,Q),L};return{get(){let z=Y();if(J&&J.key===z)return Promise.resolve({state:J.state,readAt:J.readAt});return N0(G(z),V,()=>J?{state:J.state,readAt:J.readAt}:{state:q,readAt:0})},read(){return G(Y())},refreshInBackground(){let z=Y();if(J?.key===z)return;G(z)}}}function Z1(Z,$,V){let J={assignment:V};Z.delete($),Z.set($,J);while(Z.size>MZ){let X=Z.keys().next().value;if(X===void 0)break;Z.delete(X)}return J}function $1(Z,$){if($.size===0)return Z.state;let V={...Z.state.stickyAssignments},J=!1;for(let[X,Y]of $){if(Y.persistedAt!==void 0&&Z.readAt>Y.persistedAt){$.delete(X);continue}V[X]=Y.assignment,J=!0}if(!J)return Z.state;return{...Z.state,stickyAssignments:V}}function J1(Z){let $=Z.retryDelayMs??500,V=Z.maxRetryDelayMs??30000,J=new Map,X=new Map,Y=new Set,G=0,z=$,U,L=!1,j=()=>{if(U||L||X.size===0)return;U=setTimeout(()=>{U=void 0;let K=[...X];X.clear(),z=Math.min(z*2,V);for(let[B,D]of K){let N=J.get(B);if(N!==void 0)Q(B,D.label,D.write,N)}},z),U.unref?.()},Q=(K,B,D,N)=>{let P;try{P=D()}catch(W){P=Promise.reject(W)}P.then(()=>{if(J.get(K)!==N)return;if(J.delete(K),Y.delete(K))Z.logger.info("sidebar bookkeeping write recovered",{pid:process.pid,write:B});if(Y.size===0)z=$;Z.onWritten?.()},(W)=>{if(J.get(K)!==N)return;let H={pid:process.pid,write:B,error:W instanceof Error?W.message:String(W)};if(L){J.delete(K),Z.logger.debug("sidebar bookkeeping write dropped",H);return}if(Y.has(K))Z.logger.debug("sidebar bookkeeping write failed again",H);else Y.add(K),Z.logger.warn("sidebar bookkeeping write failed; retrying in the background",H);X.set(K,{label:B,write:D}),j()})};return{enqueue(K,B,D){G+=1,J.set(K,G),X.delete(K),Q(K,B,D,G)},cancel(K){J.delete(K),X.delete(K),Y.delete(K)},stop(){if(L=!0,U)clearTimeout(U);U=void 0,X.clear()}}}function P0(Z){let $=Z.activeId;if(Z.vaultAccounts!==void 0){let V=c(Z).filter((X)=>X.enabled&&X.routable!==!1),J=V.find((X)=>X.id===$)??V[0];return J?{id:J.id,name:J.label??J.id,quota:J.quota,killed:J.killed}:{id:"vault",name:"vault",quota:null,killed:!1}}if($&&$!=="main"){let V=Z.fallbacks.find((J)=>J.enabled&&J.id===$);if(V)return{id:V.id,name:V.label??V.id,quota:V.quota,killed:V.killed}}return{id:"main",name:"main",quota:Z.main.quota,killed:Z.main.killed}}function mZ(Z,$=Date.now()){if(!Z)return;return HZ({limits:l.flatMap((V)=>{let J=Z[V];return J?[{kind:"reading",scope:"all",label:V,usedPercent:J.usedPercent,checkedAt:J.checkedAt??Z.checkedAt??$,windowMinutes:J.windowMinutes,resetsAt:J.resetsAt}]:[]}),...Z.spendControl?{budget:{...Z.spendControl,kind:"reading",checkedAt:Z.checkedAt??$}}:{}})}function X1(Z,$=Date.now()){let V=Z?.primary?.usedPercent??null,J=Z?.secondary?.usedPercent??null,X=mZ(Z,$);return{primaryUsedPercent:V,secondaryUsedPercent:J,text:!X||X.limits.length===0&&!X.budget?null:g(X,{now:$,form:"compact"})}}function gZ(Z){return Z.route==="sticky-balanced"?"roster":TZ(Z.route)}function V1(Z,$={}){let V=$.now??Date.now(),J=P0(Z).id;return(Z.vaultAccounts!==void 0?c(Z).map((Y)=>({id:Y.id,name:Y.label??Y.id,quota:Y.quota,killed:Y.killed})):W0(Z,J,$.showFallbacks??!0)).map((Y)=>{let G=mZ(Y.quota,V),z=G&&(G.limits.length>0||G.budget)?G:void 0;return{id:Y.id,name:Y.name,killed:Y.killed,active:Y.id===J,stale:z?PZ(z,{now:V}):!1,text:z?g(z,{now:V,form:"narrow"}):null}})}function W0(Z,$,V){let J=[{id:"main",name:"main",quota:Z.main.quota,killed:Z.main.killed},...Z.fallbacks.filter((Y)=>Y.enabled&&(V||Y.id===$)).map((Y)=>({id:Y.id,name:Y.label??Y.id,quota:Y.quota,killed:Y.killed}))],X=new Map(J.map((Y)=>[Y.id,Y]));return d(J.map((Y)=>Y.id),gZ(Z),"main").flatMap((Y)=>{let G=X.get(Y);return G?[G]:[]})}function DZ(Z){let $=globalThis.Bun;return $?.stringWidth?$.stringWidth(Z):Array.from(Z).length}function Y1(Z,$){if(DZ(Z)<=$)return Z;if($<1)return"";let V="",J=0;for(let X of Z){let Y=DZ(X);if(J+Y>$-1)break;V+=X,J+=Y}return`${V}…`}var H0=300000,O0=0.01,_0=1;function z1(Z,$,V){if(!Z.resetsAt)return null;let J=new Date(Z.resetsAt).getTime();if(!Number.isFinite(J))return null;let X=J-$,Y=V-X;if(Y<H0)return null;if(Y<$*O0)return null;if(Y>=$)return null;let G=Z.usedPercent,z=Math.min(Math.max(Y/$*100,0),100),U=G-z,L=Math.abs(U)<_0?"on-pace":U>0?"deficit":"reserve",j=null;if(G>0){let Q=Y*100/G,K=X+Q;if(K<J)j=new Date(K).toISOString()}return{pacePercent:z,deltaPercent:U,state:L,runsOutAt:j}}
1
+ import{Hc as NZ,Ic as PZ,Kc as g,Lc as WZ,Mc as HZ,Pc as d,ne as _Z,qe as TZ,se as RZ}from"./index-b0s5cty6.js";import{Ae as XZ,Fe as VZ,Ge as YZ,He as y,Ie as x}from"./index-fyrgwfx3.js";import{$e as OZ}from"./index-dw6yd976.js";import{if as b,jf as $Z,nf as A,of as JZ}from"./index-g556s1mz.js";import{createHash as cZ}from"node:crypto";import{constants as oZ,copyFileSync as aZ,mkdirSync as iZ,statSync as sZ}from"node:fs";import{readFile as nZ}from"node:fs/promises";import{homedir as eZ,tmpdir as tZ}from"node:os";import{dirname as Z0,join as h}from"node:path";import{chmod as dZ,mkdir as lZ}from"node:fs/promises";import{dirname as ZZ}from"node:path";function k(Z){let{path:$,defaultValue:V,normalize:J}=Z,X=Promise.resolve(),Y=(B)=>{if(B==="")return V;try{return J(JSON.parse(B))}catch{return V}},G=async()=>{try{if(b)await A(ZZ($),Z.secureDir??!0);return await JZ($,b)}catch(B){if(B.code==="ENOENT")return"";throw B}},z=async()=>{try{return Y(await G())}catch(B){if(B instanceof $Z)throw B;return V}},U=(B,D)=>{let N=X.then(B).then((P)=>D?.onResult?.(P));return X=N.catch(()=>{}),N},L={...x.sidebar,name:Z.lockName??x.sidebar.name,timeoutMs:Z.timeoutMs??x.sidebar.timeoutMs},j=async(B,D,N)=>{await XZ($,D,{serialize:JSON.stringify,beforeRename:async()=>{await N?.beforeCommit?.(),await B.assertOwned()}}),await N?.afterRename?.();try{return await B.assertOwned(),!0}catch(P){if(P instanceof YZ)return!1;throw P}},Q=async(B,D,N)=>{Z.logger?.warn("sidebar lock lost after rename; repairing write",{path:$});try{let P=await y($,L,async(W)=>{let H=B(await z(),D);if(H===void 0)return"skipped";return await j(W,H,N)?"written":"lost-again"});if(P==="lost-again")Z.logger?.warn("sidebar repair lost its lock after rename",{path:$});return{status:"lost-after-rename",repair:P}}catch(P){if(!(P instanceof VZ))throw P;return Z.logger?.warn("sidebar repair lock unavailable; repair skipped",{path:$}),{status:"lost-after-rename",repair:"lock-unavailable"}}},K=async(B,D)=>{let N=D,P=ZZ($),W=Z.secureDir??!0;if(b)await A(P,W);else if(await lZ(P,{recursive:!0,mode:448}),W)await dZ(P,448).catch((F)=>{Z.logger?.warn("sidebar directory permission remediation failed",{error:F instanceof Error?F.message:String(F)})});let H=await y($,L,async(F)=>{let s=async(C)=>({value:C,held:await j(F,C,N)});for(let C=0;C<3;C+=1){let e=await G(),t=B(Y(e));if(t===void 0)return;if(C===0)await N?.beforeRecheck?.();if(await G()!==e)continue;return await s(t)}let n=B(await z());return n===void 0?void 0:await s(n)});if(H===void 0)return{status:"skipped"};if(H.held)return{status:"written"};let i=D?.repair??Z.repair;if(!i)return Z.logger?.warn("sidebar lock lost after rename; write not repaired",{path:$}),{status:"lost-after-rename",repair:"none"};return await Q(i,H.value,N)};return{read:z,write:(B,D)=>U(()=>K(()=>B,D),D),update:(B,D)=>U(()=>K(B,D),D)}}function v0(Z){let $=Z?.credits;if($===null||typeof $!=="object")return;let{hasCredits:V,unlimited:J,balance:X}=$;if(typeof V!=="boolean"||typeof J!=="boolean")return;return WZ({hasCredits:V,unlimited:J,...typeof X==="number"?{balance:X}:{}})}function f0(Z,$=Date.now()){if(!xZ(Z,$))return!1;if(bZ(Z,$))return!1;return RZ(Z?.credits,$)}var l=["primary","secondary"],uZ={primary:300,secondary:10080};function rZ(Z,$){return NZ({scope:"all",label:$,windowMinutes:Z})}function S0(Z){if(!Z)return[];let $=[];for(let V of l){let J=Z[V];if(!J)continue;let X=J.windowMinutes,Y=X!==void 0&&Number.isFinite(X)&&X>0?X:uZ[V];$.push({key:V,label:rZ(X,V),window:J,windowMs:Y*60000})}return $}var M=OZ("sidebar"),$0="OPENCODE_OPENAI_AUTH_SIDEBAR_STATE_FILE";function CZ(){let Z=process.env.XDG_STATE_HOME||h(eZ(),".local","state");return h(Z,"cortexkit","openai-auth","sidebar-state.json")}var FZ=h(tZ(),"opencode-openai-auth","sidebar-state.json");function g0(Z){FZ=Z,p.clear()}var J0=/^[a-f0-9]{64}$/,u=604800000,MZ=256,EZ=3600000;function T(Z){return cZ("sha256").update(Z).digest("hex")}function X0(Z){return typeof Z==="number"&&Number.isFinite(Z)&&Z>=0?Z:void 0}function qZ(Z){let $=X0(Z);return $!==void 0?{resetCredits:$}:{}}function V0(Z){if(Z===null||typeof Z!=="object"||Array.isArray(Z))return;let $={};for(let[V,J]of Object.entries(Z)){if(J===null||typeof J!=="object"||Array.isArray(J))continue;let X=J;if(typeof X.activeId!=="string"||typeof X.route!=="string"||typeof X.updatedAt!=="number"||!Number.isFinite(X.updatedAt))continue;$[V]={activeId:X.activeId,route:X.route,updatedAt:X.updatedAt}}return Object.keys($).length>0?$:void 0}function Y0(Z){if(Z===null||typeof Z!=="object"||Array.isArray(Z))return;let $={};for(let[V,J]of Object.entries(Z)){if(!J0.test(V)||J===null||typeof J!=="object"||Array.isArray(J))continue;let X=J;if(typeof X.accountId!=="string"||X.accountId.length===0||typeof X.assignedAt!=="number"||!Number.isFinite(X.assignedAt)||X.assignedAt<0||typeof X.lastSeenAt!=="number"||!Number.isFinite(X.lastSeenAt)||X.lastSeenAt<0||typeof X.inputBytes!=="number"||!Number.isFinite(X.inputBytes)||X.inputBytes<0)continue;let Y=X.quotaCheckedAt;if(Y!==void 0&&(typeof Y!=="number"||!Number.isFinite(Y)||Y<0))continue;let G=X.wireAccountId;$[V]={accountId:X.accountId,assignedAt:X.assignedAt,lastSeenAt:X.lastSeenAt,inputBytes:X.inputBytes,...Y===void 0?{}:{quotaCheckedAt:Y},...typeof G==="string"?{wireAccountId:G}:{}}}return Object.keys($).length>0?$:void 0}function O(){let Z=process.env[$0];if(Z)return Z;let $=CZ();if(!p.has($))p.add($),z0($,FZ);return $}var p=new Set;function z0(Z,$){try{iZ(Z0(Z),{recursive:!0,mode:448}),aZ($,Z,oZ.COPYFILE_EXCL)}catch{}}var q={main:{quota:null,killed:!1},fallbacks:[],activeId:void 0,route:"main",lastUpdated:0};function S(Z){if(Z===null||typeof Z!=="object"||Array.isArray(Z))return q;let $=Z,V=$.main,J;if(V!==null&&typeof V==="object"&&!Array.isArray(V)){let K=V;J={quota:"quota"in K?K.quota:null,killed:typeof K.killed==="boolean"?K.killed:!1,...typeof K.mainAccountId==="string"?{mainAccountId:K.mainAccountId}:{},...typeof K.quotaBackedOff==="boolean"?{quotaBackedOff:K.quotaBackedOff}:{},...typeof K.quotaBackoffUntil==="number"?{quotaBackoffUntil:K.quotaBackoffUntil}:{},...typeof K.refreshBackedOff==="boolean"?{refreshBackedOff:K.refreshBackedOff}:{},...typeof K.refreshBackoffUntil==="number"?{refreshBackoffUntil:K.refreshBackoffUntil}:{},...qZ(K.resetCredits)}}else J={quota:null,killed:!1};let X=zZ($.fallbacks),Y=Array.isArray($.vaultAccounts)?zZ($.vaultAccounts):void 0,G=typeof $.activeId==="string"?$.activeId:void 0,z=typeof $.route==="string"?$.route:q.route,U=typeof $.lastUpdated==="number"?$.lastUpdated:0,L=typeof $.planType==="string"?$.planType:void 0,j=V0($.activeRouting),Q=Y0($.stickyAssignments);return{main:J,fallbacks:X,activeId:G,route:z,lastUpdated:U,...j!==void 0?{activeRouting:j}:{},...Q!==void 0?{stickyAssignments:Q}:{},...L!==void 0?{planType:L}:{},...$.accountPool===!0?{accountPool:!0}:{},...Y!==void 0?{vaultAccounts:Y}:{},...typeof $.vaultDiscovered==="boolean"?{vaultDiscovered:$.vaultDiscovered}:{}}}function zZ(Z){if(!Array.isArray(Z))return[];return Z.filter(($)=>$!==null&&typeof $==="object"&&!Array.isArray($)&&typeof $.id==="string").map(($)=>({id:$.id,...typeof $.credentialId==="string"?{credentialId:$.credentialId}:{},label:typeof $.label==="string"?$.label:void 0,...typeof $.accountId==="string"?{accountId:$.accountId}:{},quota:"quota"in $?$.quota:null,killed:typeof $.killed==="boolean"?$.killed:!1,enabled:typeof $.enabled==="boolean"?$.enabled:!0,...typeof $.routable==="boolean"?{routable:$.routable}:{},...["needs sign-in","turned off in vault","unavailable"].includes($.vaultState)?{vaultState:$.vaultState}:{},...qZ($.resetCredits)}))}function r(Z){return[...Z.fallbacks,...Z.vaultAccounts??[]]}async function G0(Z=O()){try{let $=await nZ(Z,"utf8");return S(JSON.parse($))}catch{return q}}var K0=3600000,GZ=128;function IZ(Z,$,V=Date.now()){if(!(Z.updatedAt>=V-K0&&Z.updatedAt<=V))return!1;if($===void 0)return!0;return Z.activeId==="main"||$.some((X)=>X.enabled!==!1&&X.routable!==!1&&X.killed!==!0&&X.id===Z.activeId)}function bZ(Z,$=Date.now()){let V=Z?.spendControl;if(V?.reached!==!0||typeof V.resetsAt!=="string")return;let J=Date.parse(V.resetsAt);if(!Number.isFinite(J)||J<=$)return;return{resetsAt:V.resetsAt,resetAtMs:J}}function xZ(Z,$=Date.now()){let V;for(let X of l){let Y=Z?.[X];if(typeof Y?.resetsAt!=="string"||!Number.isFinite(Y.usedPercent)||Y.usedPercent<100)continue;let G=Date.parse(Y.resetsAt);if(!Number.isFinite(G)||G<=$)continue;if(!V||G<V.resetAtMs)V={resetsAt:Y.resetsAt,resetAtMs:G}}let J=bZ(Z,$);if(J&&(!V||J.resetAtMs<V.resetAtMs))V=J;return V}function E(Z,$=Date.now()){return xZ(Z,$)!==void 0}function j0(Z,$,V=Date.now()){if(!$||Z.route!=="sticky-balanced")return;let J=Z.stickyAssignments?.[T($)];if(!J||J.lastSeenAt<V-u)return;if(J.accountId==="main"&&Z.vaultAccounts===void 0)return Z.main?.killed||E(Z.main?.quota,V)?void 0:"main";let X=r(Z).find((Y)=>Y.id===J.accountId);if(!X||X.enabled===!1||X.routable===!1||X.killed===!0||E(X.quota,V))return;return X.id}function d0(Z,$,V=Date.now()){if(!$){if(Z.vaultAccounts===void 0)return{activeId:Z.activeId??"main",route:Z.route};let j=Z.vaultAccounts.find((Q)=>Q.id===Z.activeId&&Q.enabled&&Q.routable!==!1&&!Q.killed);if(j&&!E(j.quota,V))return{activeId:j.id,route:Z.route}}let J=$?Z.activeRouting?.[$]:void 0,X=r(Z),Y=J?.activeId==="main"?Z.main.quota:X.find((j)=>j.id===J?.activeId)?.quota;if(J&&(Z.vaultAccounts===void 0||J.activeId.startsWith("vault:"))&&IZ(J,X,V)&&!E(Y,V))return{activeId:J.activeId,route:J.route};let G=j0(Z,$,V);if(G)return{activeId:G,route:Z.route};let z=Z.vaultAccounts!==void 0,U=(z?c(Z):Z.fallbacks).filter((j)=>j.enabled&&j.routable!==!1&&!j.killed),L=U.find((j)=>!E(j.quota,V))??U[0];return{activeId:z?L?.id??"vault":Z.route==="fallback-first"&&L?L.id:"main",route:Z.route}}function c(Z){let $=Z.vaultAccounts??[],V=new Map($.map((J)=>[J.id,J]));return d($.map((J)=>J.id),gZ(Z),_Z($)??"").flatMap((J)=>{let X=V.get(J);return X?[X]:[]})}function vZ(Z,$,V=Date.now(),J){if(!Z)return;let X=Object.entries(Z).filter(([G,z])=>G!==J&&IZ(z,$,V)),Y=X.length<=GZ?X:X.sort((G,z)=>z[1].updatedAt-G[1].updatedAt).slice(0,GZ);return Y.length>0?Object.fromEntries(Y):void 0}function I(Z,$,V=Date.now(),J){if(!Z)return;let X=0,Y=0,G=0,z=[];for(let[L,j]of Object.entries(Z)){if(L===J){G+=1;continue}if(j.lastSeenAt<V-u){Y+=1;continue}if($!==void 0&&!$.has(j.accountId)){X+=1;continue}z.push([L,j])}let U=X+Y+G;if(U>0)M.debug("pruned sticky assignments",{pid:process.pid,removed:U,reasons:{"account-not-in-roster":X,expired:Y,"explicit-removal":G}});return z.length>0?Object.fromEntries(z):void 0}function fZ(Z,$){let V=Object.keys(Z).length-MZ;if(V<=0)return Z;let J=new Set(Object.entries(Z).filter(([X])=>X!==$).sort(([X,Y],[G,z])=>Y.lastSeenAt-z.lastSeenAt||X.localeCompare(G)).slice(0,V).map(([X])=>X));return Object.fromEntries(Object.entries(Z).filter(([X])=>!J.has(X)))}function SZ(Z,$){if(Z===$)return!0;if(!Z||!$)return!1;let V=Object.entries(Z);if(V.length!==Object.keys($).length)return!1;return V.every(([J,X])=>Object.is($[J],X))}function AZ(Z,$,V,J){return Z!==void 0&&$.has(Z.accountId)&&!V.has(Z.accountId)&&Z.lastSeenAt>=J-u}function yZ(Z,$,V,J){return $>Z.inputBytes||V-Z.lastSeenAt>=EZ||Z.wireAccountId===void 0&&J!==void 0}function kZ(Z,$){return typeof Z.wireAccountId==="string"&&typeof $==="string"&&Z.wireAccountId!==$}function L0(Z){let $=new Map(Z),V={get size(){return $.size},has:(J)=>$.has(J),get:(J)=>$.get(J),entries:()=>$.entries(),keys:()=>$.keys(),values:()=>$.values(),forEach:(J,X)=>{$.forEach((Y,G)=>{J.call(X,Y,G,V)})},[Symbol.iterator]:()=>$[Symbol.iterator]()};return Object.freeze(V)}function B0(Z,$,V){let J=new Map;for(let[X,Y]of Object.entries(Z??{})){if(X===V)continue;if(Y.quotaCheckedAt!==$[Y.accountId])continue;J.set(Y.accountId,(J.get(Y.accountId)??0)+Y.inputBytes)}return L0(J)}function o(Z){if(Z===void 0)return;return new Set(["main",...Z.filter(($)=>$.enabled!==!1&&$.killed!==!0).map(($)=>$.id)])}var m=Promise.resolve();function _(Z){let $=m.then(Z);return m=$.catch(()=>{}),$}var KZ=new Map;function a(Z){let $=KZ.get(Z);if(!$)$=k({path:Z,defaultValue:q,normalize:S,secureDir:Z===CZ(),logger:M}),KZ.set(Z,$);return $}var w=new Set;async function wZ(Z,$){try{await $}catch(V){let J={pid:process.pid,error:V instanceof Error?V.message:String(V)};if(w.has(Z))M.debug("sidebar write failed again",J);else w.add(Z),M.warn("sidebar write failed",J);throw V}if(w.delete(Z))M.info("sidebar write recovered",{pid:process.pid})}function l0(Z,$=O()){return _(()=>wZ($,a($).write(S(Z))))}function U0(Z){return a(Z).read()}function R(Z,$,V){let J=Symbol("sidebar authority changed");return wZ(Z,a(Z).update((X)=>{if(V?.canWrite&&!V.canWrite())return;let Y=$(X);if(Y===void 0)return;if(Y.vaultAccounts!==void 0)Y.activeId=Y.activeId?.startsWith("vault:")?Y.activeId:void 0,Y.activeRouting=Object.fromEntries(Object.entries(Y.activeRouting??{}).filter(([,G])=>G.activeId.startsWith("vault:"))),Y.stickyAssignments=Object.fromEntries(Object.entries(Y.stickyAssignments??{}).filter(([,G])=>G.accountId.startsWith("vault:")&&!Y.vaultAccounts?.some((z)=>z.id===G.accountId&&z.killed)));return S(Y)},{beforeRecheck:async(...X)=>{if(await V?.beforeRecheck?.(...X),V?.canWrite&&!V.canWrite())throw J}}).catch((X)=>{if(X!==J)throw X}))}function v(Z){let $;for(let V of[Z?.primary?.checkedAt,Z?.secondary?.checkedAt,Z?.checkedAt])if(typeof V==="number"&&Number.isFinite(V))$=$===void 0?V:Math.max($,V);return $}function jZ(Z,$){let V=v(Z),J=v($);if(J!==void 0&&(V===void 0||J>V))return $;return Z}function LZ(Z,$){return Z!==void 0&&$!==void 0&&Z===$}function f(Z,$){let V=Z?.checkedAt;if(typeof V==="number"&&Number.isFinite(V))return V;if(typeof $==="number"&&Number.isFinite($))return $;return}function BZ(Z,$,V,J,X){if(Z&&$){let Y=f(Z,J),G=f($,X);if(G!==void 0&&(Y===void 0||G>Y))return $;return Z}return V?$:Z}function UZ(Z,$){if(Z.spendControl!==void 0)return Z.spendControl;if(Z.spendControlCleared===!0)return;return $.spendControl}function Q0(Z,$){if(!Z||!$)return Z??$;let V=(J)=>typeof J.checkedAt==="number"&&Number.isFinite(J.checkedAt)?J.checkedAt:Number.NEGATIVE_INFINITY;return V($)>V(Z)?$:Z}function QZ(Z,$){if(!Z)return $;if(!$)return Z;let V=v(Z),J=v($),X=J!==void 0&&(V===void 0||J>V),Y=BZ(Z.primary,$.primary,X,Z.checkedAt,$.checkedAt),G=BZ(Z.secondary,$.secondary,X,Z.checkedAt,$.checkedAt),z=X?UZ($,Z):UZ(Z,$),U=z===void 0&&(Z.spendControlCleared===!0||$.spendControlCleared===!0),L=Q0(Z.credits,$.credits),j;for(let N of[f(Y),f(G)])if(N!==void 0)j=j===void 0?N:Math.max(j,N);let{spendControl:Q,spendControlCleared:K,credits:B,...D}=Z;return{...D,primary:Y,secondary:G,...z!==void 0?{spendControl:z}:{},...U?{spendControlCleared:!0}:{},...L!==void 0?{credits:L}:{},checkedAt:j??Z.checkedAt}}function u0(Z,$=O(),V){return _(async()=>{await R($,(J)=>{let X=new Map(J.fallbacks.map((j)=>[j.id,j])),Y=Z.vaultAccounts!==void 0,G=LZ(Z.main.mainAccountId,J.main.mainAccountId),z=G?QZ(Z.main.quota,J.main.quota):jZ(Z.main.quota,J.main.quota),U=Date.now(),L=I(J.stickyAssignments,Y?void 0:o(r(Z)),U);return{...J,...Z,main:Y?Z.main:{...Z.main,quota:z,mainAccountId:G?Z.main.mainAccountId:z===J.main.quota&&z!==Z.main.quota?J.main.mainAccountId:Z.main.mainAccountId},fallbacks:Y?Z.fallbacks:Z.fallbacks.map((j)=>{let Q=X.get(j.id),K=LZ(j.accountId,Q?.accountId),B=K?QZ(j.quota,Q?.quota??null):jZ(j.quota,Q?.quota??null);return{...j,quota:B,accountId:K?j.accountId:B===Q?.quota&&B!==j.quota?Q?.accountId:j.accountId}}),activeId:J.activeId,activeRouting:J.activeRouting,stickyAssignments:L,lastUpdated:Math.max(U,J.lastUpdated+1),accountPool:Z.accountPool===!0?!0:void 0,vaultAccounts:Z.vaultAccounts,vaultDiscovered:Z.vaultDiscovered}},V)})}function r0(Z,$,V=O(),J){return _(async()=>{await R(V,(X)=>{let Y=vZ({...X.activeRouting,[Z.sessionId]:{activeId:Z.activeId,route:Z.route,updatedAt:Z.updatedAt}},$,Date.now()),G=I(X.stickyAssignments,X.vaultAccounts!==void 0?void 0:o($),Date.now());return{...X,activeId:Z.activeId,route:Z.route,activeRouting:Y,stickyAssignments:G,lastUpdated:Math.max(Date.now(),X.lastUpdated+1)}},J)})}function c0(Z,$=O(),V){return _(async()=>{await R($,(J)=>({...J,activeId:Z.activeId,route:Z.route,lastUpdated:Math.max(Date.now(),J.lastUpdated+1)}),V)})}function o0(Z,$,V=O(),J){return _(async()=>{await R(V,(X)=>{let Y=Date.now(),G=vZ(X.activeRouting,$,Y,Z),z=I(X.stickyAssignments,X.vaultAccounts!==void 0?void 0:o($),Y,T(Z));return{...X,activeRouting:G,stickyAssignments:z,lastUpdated:Math.max(Date.now(),X.lastUpdated+1)}},J)})}function hZ(Z,$){return AZ(Z,new Set($.validPinnedAccountIds),new Set($.excludeAccountIds),$.now)&&!kZ(Z,$.wireAccountIdByAccount?.[Z.accountId])&&!yZ(Z,$.requestBytes,$.now,$.wireAccountIdByAccount?.[Z.accountId])}function pZ(Z,$){let V=T($.sessionId),J=new Set($.validPinnedAccountIds),X=new Set($.excludeAccountIds),Y=I(Z.stickyAssignments,J,$.now),G=!SZ(Z.stickyAssignments,Y),z=Y?.[V],U=z!==void 0&&kZ(z,$.wireAccountIdByAccount?.[z.accountId]);if(AZ(z,J,X,$.now)&&!U){let Q=yZ(z,$.requestBytes,$.now,$.wireAccountIdByAccount?.[z.accountId]),K=Q?{...z,inputBytes:Math.max(z.inputBytes,$.requestBytes),...z.wireAccountId===void 0&&$.wireAccountIdByAccount?.[z.accountId]!==void 0?{wireAccountId:$.wireAccountIdByAccount?.[z.accountId]}:{},...$.now-z.lastSeenAt>=EZ?{lastSeenAt:$.now}:{}}:z;if(!G&&!Q)return{assignment:K,next:void 0};return{assignment:K,next:{...Z,stickyAssignments:{...Y,[V]:K},lastUpdated:Math.max($.now,Z.lastUpdated+1)}}}let L=$.choose(B0(Y,$.quotaCheckedAtByAccount,U?V:void 0));if(!L){if(!G)return{assignment:void 0,next:void 0};return{assignment:void 0,next:{...Z,stickyAssignments:Y,lastUpdated:Math.max($.now,Z.lastUpdated+1)}}}let j={accountId:L.accountId,assignedAt:$.now,lastSeenAt:$.now,inputBytes:$.requestBytes,...L.quotaCheckedAt===void 0?{}:{quotaCheckedAt:L.quotaCheckedAt},...$.wireAccountIdByAccount?.[L.accountId]===void 0?{}:{wireAccountId:$.wireAccountIdByAccount?.[L.accountId]}};return{assignment:j,next:{...Z,stickyAssignments:fZ({...Y,[V]:j},V),lastUpdated:Math.max($.now,Z.lastUpdated+1)}}}async function a0(Z,$=O(),V){let J=T(Z.sessionId),X=(await U0($)).stickyAssignments?.[J];if(hZ(X,Z))return X;let Y;return await _(async()=>{await R($,(G)=>{let z=pZ(G,Z);return Y=z.assignment,z.next},V)}),Y}function i0(Z,$){let V=Z.stickyAssignments?.[T($.sessionId)];if(hZ(V,$))return{assignment:V,next:void 0};return pZ(Z,$)}function s0(Z,$=O()){let V=T(Z.sessionId),J=new Set(Z.validPinnedAccountIds);return _(async()=>{await R($,(X)=>{let Y=Date.now(),G=I(X.stickyAssignments,X.vaultAccounts!==void 0?void 0:J,Y),z=G?.[V];if(z&&z.assignedAt>Z.assignment.assignedAt){if(SZ(X.stickyAssignments,G))return;return{...X,stickyAssignments:G,lastUpdated:Math.max(Y,X.lastUpdated+1)}}let L=z!==void 0&&z.accountId===Z.assignment.accountId&&z.assignedAt===Z.assignment.assignedAt?{...Z.assignment,inputBytes:Math.max(z.inputBytes,Z.assignment.inputBytes),lastSeenAt:Math.max(z.lastSeenAt,Z.assignment.lastSeenAt)}:Z.assignment;return{...X,stickyAssignments:fZ({...G,[V]:L},V),lastUpdated:Math.max(Y,X.lastUpdated+1)}})})}async function n0(Z,$=O()){let V=T(Z),J=!1;return await _(async()=>{await R($,(X)=>{let Y=X.stickyAssignments;if(Y?.[V]===void 0){J=!1;return}J=!0;let{[V]:G,...z}=Y;return{...X,...Object.keys(z).length>0?{stickyAssignments:z}:{stickyAssignments:void 0},lastUpdated:Math.max(Date.now(),X.lastUpdated+1)}})}),J}function e0(){return m}var D0=500;function N0(Z,$,V){return new Promise((J,X)=>{let Y=setTimeout(()=>J(V()),$);Y.unref?.(),Z.then((G)=>{clearTimeout(Y),J(G)},(G)=>{clearTimeout(Y),X(G)})})}function t0(Z,$={}){let V=$.readBudgetMs??D0,J,X,Y=()=>{try{let z=sZ(Z);return`${z.ino}:${z.size}:${z.mtimeMs}`}catch{return}},G=(z)=>{if(X&&X.key===z)return X.promise;let U=Date.now(),L=G0(Z).then((K)=>{if(!J||J.readAt<=U)J={state:K,readAt:U,key:z};return{state:K,readAt:U}}),j={key:z,promise:L};X=j;let Q=()=>{if(X===j)X=void 0};return L.then(Q,Q),L};return{get(){let z=Y();if(J&&J.key===z)return Promise.resolve({state:J.state,readAt:J.readAt});return N0(G(z),V,()=>J?{state:J.state,readAt:J.readAt}:{state:q,readAt:0})},read(){return G(Y())},refreshInBackground(){let z=Y();if(J?.key===z)return;G(z)}}}function Z1(Z,$,V){let J={assignment:V};Z.delete($),Z.set($,J);while(Z.size>MZ){let X=Z.keys().next().value;if(X===void 0)break;Z.delete(X)}return J}function $1(Z,$){if($.size===0)return Z.state;let V={...Z.state.stickyAssignments},J=!1;for(let[X,Y]of $){if(Y.persistedAt!==void 0&&Z.readAt>Y.persistedAt){$.delete(X);continue}V[X]=Y.assignment,J=!0}if(!J)return Z.state;return{...Z.state,stickyAssignments:V}}function J1(Z){let $=Z.retryDelayMs??500,V=Z.maxRetryDelayMs??30000,J=new Map,X=new Map,Y=new Set,G=0,z=$,U,L=!1,j=()=>{if(U||L||X.size===0)return;U=setTimeout(()=>{U=void 0;let K=[...X];X.clear(),z=Math.min(z*2,V);for(let[B,D]of K){let N=J.get(B);if(N!==void 0)Q(B,D.label,D.write,N)}},z),U.unref?.()},Q=(K,B,D,N)=>{let P;try{P=D()}catch(W){P=Promise.reject(W)}P.then(()=>{if(J.get(K)!==N)return;if(J.delete(K),Y.delete(K))Z.logger.info("sidebar bookkeeping write recovered",{pid:process.pid,write:B});if(Y.size===0)z=$;Z.onWritten?.()},(W)=>{if(J.get(K)!==N)return;let H={pid:process.pid,write:B,error:W instanceof Error?W.message:String(W)};if(L){J.delete(K),Z.logger.debug("sidebar bookkeeping write dropped",H);return}if(Y.has(K))Z.logger.debug("sidebar bookkeeping write failed again",H);else Y.add(K),Z.logger.warn("sidebar bookkeeping write failed; retrying in the background",H);X.set(K,{label:B,write:D}),j()})};return{enqueue(K,B,D){G+=1,J.set(K,G),X.delete(K),Q(K,B,D,G)},cancel(K){J.delete(K),X.delete(K),Y.delete(K)},stop(){if(L=!0,U)clearTimeout(U);U=void 0,X.clear()}}}function P0(Z){let $=Z.activeId;if(Z.vaultAccounts!==void 0){let V=c(Z).filter((X)=>X.enabled&&X.routable!==!1),J=V.find((X)=>X.id===$)??V[0];return J?{id:J.id,name:J.label??J.id,quota:J.quota,killed:J.killed}:{id:"vault",name:"vault",quota:null,killed:!1}}if($&&$!=="main"){let V=Z.fallbacks.find((J)=>J.enabled&&J.id===$);if(V)return{id:V.id,name:V.label??V.id,quota:V.quota,killed:V.killed}}return{id:"main",name:"main",quota:Z.main.quota,killed:Z.main.killed}}function mZ(Z,$=Date.now()){if(!Z)return;return HZ({limits:l.flatMap((V)=>{let J=Z[V];return J?[{kind:"reading",scope:"all",label:V,usedPercent:J.usedPercent,checkedAt:J.checkedAt??Z.checkedAt??$,windowMinutes:J.windowMinutes,resetsAt:J.resetsAt}]:[]}),...Z.spendControl?{budget:{...Z.spendControl,kind:"reading",checkedAt:Z.checkedAt??$}}:{}})}function X1(Z,$=Date.now()){let V=Z?.primary?.usedPercent??null,J=Z?.secondary?.usedPercent??null,X=mZ(Z,$);return{primaryUsedPercent:V,secondaryUsedPercent:J,text:!X||X.limits.length===0&&!X.budget?null:g(X,{now:$,form:"compact"})}}function gZ(Z){return Z.route==="sticky-balanced"?"roster":TZ(Z.route)}function V1(Z,$={}){let V=$.now??Date.now(),J=P0(Z).id;return(Z.vaultAccounts!==void 0?c(Z).map((Y)=>({id:Y.id,name:Y.label??Y.id,quota:Y.quota,killed:Y.killed})):W0(Z,J,$.showFallbacks??!0)).map((Y)=>{let G=mZ(Y.quota,V),z=G&&(G.limits.length>0||G.budget)?G:void 0;return{id:Y.id,name:Y.name,killed:Y.killed,active:Y.id===J,stale:z?PZ(z,{now:V}):!1,text:z?g(z,{now:V,form:"narrow"}):null}})}function W0(Z,$,V){let J=[{id:"main",name:"main",quota:Z.main.quota,killed:Z.main.killed},...Z.fallbacks.filter((Y)=>Y.enabled&&(V||Y.id===$)).map((Y)=>({id:Y.id,name:Y.label??Y.id,quota:Y.quota,killed:Y.killed}))],X=new Map(J.map((Y)=>[Y.id,Y]));return d(J.map((Y)=>Y.id),gZ(Z),"main").flatMap((Y)=>{let G=X.get(Y);return G?[G]:[]})}function DZ(Z){let $=globalThis.Bun;return $?.stringWidth?$.stringWidth(Z):Array.from(Z).length}function Y1(Z,$){if(DZ(Z)<=$)return Z;if($<1)return"";let V="",J=0;for(let X of Z){let Y=DZ(X);if(J+Y>$-1)break;V+=X,J+=Y}return`${V}…`}var H0=300000,O0=0.01,_0=1;function z1(Z,$,V){if(!Z.resetsAt)return null;let J=new Date(Z.resetsAt).getTime();if(!Number.isFinite(J))return null;let X=J-$,Y=V-X;if(Y<H0)return null;if(Y<$*O0)return null;if(Y>=$)return null;let G=Z.usedPercent,z=Math.min(Math.max(Y/$*100,0),100),U=G-z,L=Math.abs(U)<_0?"on-pace":U>0?"deficit":"reserve",j=null;if(G>0){let Q=Y*100/G,K=X+Q;if(K<J)j=new Date(K).toISOString()}return{pacePercent:z,deltaPercent:U,state:L,runsOutAt:j}}
2
2
  export{v0 as Mb,f0 as Nb,rZ as Ob,S0 as Pb,g0 as Qb,u as Rb,MZ as Sb,T as Tb,O as Ub,q as Vb,S as Wb,G0 as Xb,K0 as Yb,GZ as Zb,IZ as _b,bZ as $b,xZ as ac,E as bc,j0 as cc,d0 as dc,vZ as ec,I as fc,l0 as gc,u0 as hc,r0 as ic,c0 as jc,o0 as kc,pZ as lc,a0 as mc,i0 as nc,s0 as oc,n0 as pc,e0 as qc,D0 as rc,N0 as sc,t0 as tc,Z1 as uc,$1 as vc,J1 as wc,P0 as xc,mZ as yc,X1 as zc,V1 as Ac,DZ as Bc,Y1 as Cc,z1 as Dc};
@@ -1,3 +1,3 @@
1
- import{xb as X,zb as V}from"./index-97cz7kyq.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{xb as X,zb as V}from"./index-rw932qm9.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};