@cortexkit/opencode-openai-auth 1.8.0 → 1.8.2
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 +9 -9
- package/dist/{codex-request-DohnbsFR.d.ts → codex-request-GJkvxv4S.d.ts} +3 -57
- package/dist/index-03hs0rq7.js +2 -0
- package/dist/index-0dmg1yer.js +63 -0
- package/dist/{index-cxstwq02.js → index-7sa6ncxb.js} +1 -1
- package/dist/index-b0s5cty6.js +91 -0
- package/dist/{index-dtwgf694.js → index-c50p5mem.js} +1 -1
- package/dist/{index-g3d50jz0.js → index-ctch2vgj.js} +10 -10
- package/dist/{index-5d4y47h8.js → index-dw6yd976.js} +2 -2
- package/dist/index-fyrgwfx3.js +8 -0
- package/dist/{index-5dxpsa3t.js → index-g556s1mz.js} +2 -2
- package/dist/{index-x7jzcvqy.js → index-hpnj460b.js} +1 -1
- package/dist/{index-cbcka7sa.js → index-p8m4yh73.js} +1 -1
- package/dist/{index-th47aqez.js → index-yt52fztj.js} +2 -2
- package/dist/{index-dzaqj248.js → index-z36br4a0.js} +2 -2
- package/dist/index.d.ts +2 -12
- package/dist/index.js +1 -1
- package/dist/{port-file-DQ7-ItDK.d.ts → port-file-DXCxv8tU.d.ts} +0 -2
- package/dist/{protocol-CVQK-d3j.d.ts → protocol-BZZtDn5h.d.ts} +0 -4
- package/dist/rpc/port-file.d.ts +1 -3
- package/dist/rpc/port-file.js +1 -1
- package/dist/rpc/protocol.d.ts +1 -1
- package/dist/rpc/protocol.js +1 -1
- package/dist/rpc/rpc-client.d.ts +1 -1
- package/dist/rpc/rpc-client.js +1 -1
- package/dist/rpc/rpc-dir.d.ts +0 -2
- package/dist/rpc/rpc-dir.js +1 -1
- package/dist/{rpc-client-BQfIKrXI.d.ts → rpc-client-CmaZW1by.d.ts} +2 -6
- package/dist/{sidebar-state-B1cq68UB.d.ts → sidebar-state-DkNebAiC.d.ts} +3 -11
- package/dist/sidebar-state.d.ts +1 -1
- package/dist/sidebar-state.js +1 -1
- package/dist/{token-gy442bba.js → token-3vtr29vt.js} +1 -1
- package/dist/token-util-erhrf24m.js +1 -0
- package/dist/tui-preferences.d.ts +0 -2
- package/dist/tui-preferences.js +1 -1
- package/dist/tui.d.ts +3 -7
- package/dist/v2/server.d.ts +2 -18
- package/dist/v2/server.js +2 -2
- package/package.json +7 -7
- package/src/tui-compiled/raw/shared/352d228be2832bd4-hub.js +86 -42
- package/src/tui-compiled/raw/shared/b9588ad4725c1d10-enrollment.js +15 -8
- package/src/tui-compiled/raw/shared/dbc61cd405941828-accounts.js +42 -0
- package/src/tui-compiled/raw/shared/e8cd4929507508d8-refresh-file-lock.js +175 -10
- package/src/tui-compiled/raw/sidebar-state.js +4 -2
- package/src/tui-compiled/raw/tui.tsx +7 -1
- package/src/tui-compiled/runtime/shared/352d228be2832bd4-hub.js +86 -42
- package/src/tui-compiled/runtime/shared/b9588ad4725c1d10-enrollment.js +15 -8
- package/src/tui-compiled/runtime/shared/dbc61cd405941828-accounts.js +42 -0
- package/src/tui-compiled/runtime/shared/e8cd4929507508d8-refresh-file-lock.js +175 -10
- package/src/tui-compiled/runtime/sidebar-state.js +4 -2
- package/src/tui-compiled/runtime/tui.js +4 -1
- package/dist/index-3v868rnp.js +0 -63
- package/dist/index-8pk9savd.js +0 -8
- package/dist/index-n7fxqgfb.js +0 -2
- package/dist/index-tvban5vp.js +0 -91
- package/dist/token-util-rxy0p234.js +0 -1
package/dist/bin.js
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{c as
|
|
3
|
-
`);return
|
|
4
|
-
${
|
|
2
|
+
import{c as u0}from"./index-7sa6ncxb.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-ctch2vgj.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-z36br4a0.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=
|
|
11
|
-
`,
|
|
12
|
-
${b.content}`);if(
|
|
13
|
-
ck auth grant --principal enrolled:${q} --selector-kind category --selector ${
|
|
14
|
-
${
|
|
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.2",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.2",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,7 +1,6 @@
|
|
|
1
|
-
import { gt as QuotaMap } from "./sidebar-state-
|
|
1
|
+
import { gt as QuotaMap } from "./sidebar-state-DkNebAiC.js";
|
|
2
2
|
import { ClaustrumClient, EnrollmentPollOutcome } from "@cortexkit/claustrum-client";
|
|
3
3
|
import "@cortexkit/private-files";
|
|
4
|
-
//#region ../../node_modules/.bun/@cortexkit+common-auth@0.27.1+edd79cef82a5b402/node_modules/@cortexkit/common-auth/dist/store/schema.d.ts
|
|
5
4
|
type OAuthCredential = {
|
|
6
5
|
type: 'oauth';
|
|
7
6
|
access?: string;
|
|
@@ -76,8 +75,6 @@ interface ProviderStateCodec {
|
|
|
76
75
|
*/
|
|
77
76
|
onReplace?(previous: unknown | undefined, replacement: ProviderStateReplacement): unknown | undefined;
|
|
78
77
|
}
|
|
79
|
-
//#endregion
|
|
80
|
-
//#region ../../node_modules/.bun/@cortexkit+common-auth@0.27.1+edd79cef82a5b402/node_modules/@cortexkit/common-auth/dist/store/errors.d.ts
|
|
81
78
|
/** Every library operation that can fail, as named in the failure value. */
|
|
82
79
|
type PoolOperation = 'initialize' | 'add' | 'replace' | 'rotate' | 'disable' | 'enable' | 'remove' | 'reorder' | 'updateSettings' | 'recordIdentity' | 'updateProviderState' | 'refresh' | 'pull' | 'publishRoster';
|
|
83
80
|
/**
|
|
@@ -123,13 +120,9 @@ declare class PoolOperationError extends Error {
|
|
|
123
120
|
cause?: unknown;
|
|
124
121
|
});
|
|
125
122
|
}
|
|
126
|
-
//#endregion
|
|
127
|
-
//#region ../../node_modules/.bun/@cortexkit+common-auth@0.27.1+edd79cef82a5b402/node_modules/@cortexkit/common-auth/dist/store/hooks.d.ts
|
|
128
123
|
interface PoolLogger {
|
|
129
124
|
warn(message: string, data?: unknown): void;
|
|
130
125
|
}
|
|
131
|
-
//#endregion
|
|
132
|
-
//#region ../../node_modules/.bun/@cortexkit+common-auth@0.27.1+edd79cef82a5b402/node_modules/@cortexkit/common-auth/dist/fs/refresh-file-lock.d.ts
|
|
133
126
|
interface LockLoss {
|
|
134
127
|
readonly reason: 'taken-over' | 'expired' | 'unreadable' | 'renewal-failed' | 'marker-lost';
|
|
135
128
|
readonly expectedOwnerId: string;
|
|
@@ -163,8 +156,6 @@ type RefreshFileLockOptions = {
|
|
|
163
156
|
};
|
|
164
157
|
/** Filesystem leases share wall time across all callers and processes. */
|
|
165
158
|
declare function acquireRefreshFileLock(options: RefreshFileLockOptions): Promise<RefreshFileLock | null>;
|
|
166
|
-
//#endregion
|
|
167
|
-
//#region ../../node_modules/.bun/@cortexkit+common-auth@0.27.1+edd79cef82a5b402/node_modules/@cortexkit/common-auth/dist/store/refresh-lock.d.ts
|
|
168
159
|
type LockStep = NonNullable<Parameters<typeof acquireRefreshFileLock>[0]['onStep']> extends ((step: infer S) => unknown) ? S : never;
|
|
169
160
|
/** Tuning shared by every lock the store takes; each field is overridable. */
|
|
170
161
|
interface PoolLockOptions {
|
|
@@ -195,8 +186,6 @@ interface LockEnvironment {
|
|
|
195
186
|
path: string;
|
|
196
187
|
}, event: 'scheduled' | 'cancelled') => void;
|
|
197
188
|
}
|
|
198
|
-
//#endregion
|
|
199
|
-
//#region ../../node_modules/.bun/@cortexkit+common-auth@0.27.1+edd79cef82a5b402/node_modules/@cortexkit/common-auth/dist/store/mutate.d.ts
|
|
200
189
|
/** Named points on the write path, for crash and ownership injection. */
|
|
201
190
|
type WriteStep = 'before-config-write' | 'after-config-write' | 'before-state-write' | 'after-state-write';
|
|
202
191
|
/** Awaitable pause points on the pull and refresh paths. */
|
|
@@ -228,12 +217,8 @@ interface StoreContext {
|
|
|
228
217
|
requireCredentialStamps?: boolean;
|
|
229
218
|
requireRemovedFingerprint?: boolean;
|
|
230
219
|
}
|
|
231
|
-
//#endregion
|
|
232
|
-
//#region ../../node_modules/.bun/@cortexkit+common-auth@0.27.1+edd79cef82a5b402/node_modules/@cortexkit/common-auth/dist/store/runtime.d.ts
|
|
233
220
|
/** Where a pull was fired from; `load` fires at most once per process per row. */
|
|
234
221
|
type PullReason = 'load' | 'add' | 'replace' | 'admission';
|
|
235
|
-
//#endregion
|
|
236
|
-
//#region ../../node_modules/.bun/@cortexkit+common-auth@0.27.1+edd79cef82a5b402/node_modules/@cortexkit/common-auth/dist/quota/commit-interval.d.ts
|
|
237
222
|
interface QuotaCommitTimer {
|
|
238
223
|
now(): number;
|
|
239
224
|
schedule(delayMs: number, run: () => Promise<void>): {
|
|
@@ -241,8 +226,6 @@ interface QuotaCommitTimer {
|
|
|
241
226
|
unref?(): void;
|
|
242
227
|
};
|
|
243
228
|
}
|
|
244
|
-
//#endregion
|
|
245
|
-
//#region ../../node_modules/.bun/@cortexkit+common-auth@0.27.1+edd79cef82a5b402/node_modules/@cortexkit/common-auth/dist/store/pull.d.ts
|
|
246
229
|
/** What a pull is issued with: the credential and its attribution tuple. */
|
|
247
230
|
interface PullRequest {
|
|
248
231
|
id: string;
|
|
@@ -252,8 +235,6 @@ interface PullRequest {
|
|
|
252
235
|
reason: PullReason;
|
|
253
236
|
}
|
|
254
237
|
type PullHook = (request: PullRequest) => Promise<unknown>;
|
|
255
|
-
//#endregion
|
|
256
|
-
//#region ../../node_modules/.bun/@cortexkit+common-auth@0.27.1+edd79cef82a5b402/node_modules/@cortexkit/common-auth/dist/store/pool.d.ts
|
|
257
238
|
interface OpenPoolStoreOptions {
|
|
258
239
|
/** The provider every row of this pool belongs to; keys the provider-wide lock. */
|
|
259
240
|
provider: string;
|
|
@@ -329,8 +310,6 @@ interface OpenPoolStoreOptions {
|
|
|
329
310
|
onLockStep?: LockEnvironment['onLockStep'];
|
|
330
311
|
onRenewalTimer?: LockEnvironment['onRenewalTimer'];
|
|
331
312
|
}
|
|
332
|
-
//#endregion
|
|
333
|
-
//#region ../core/dist/paths.d.ts
|
|
334
313
|
/**
|
|
335
314
|
* The config file and the runtime-state file a store operation reads and writes.
|
|
336
315
|
*
|
|
@@ -342,8 +321,6 @@ interface AccountPaths {
|
|
|
342
321
|
configPath: string;
|
|
343
322
|
statePath: string;
|
|
344
323
|
}
|
|
345
|
-
//#endregion
|
|
346
|
-
//#region ../core/dist/oauth.d.ts
|
|
347
324
|
interface IdTokenClaims {
|
|
348
325
|
chatgpt_account_id?: string;
|
|
349
326
|
email?: string;
|
|
@@ -400,8 +377,6 @@ interface BeginAccountLoginResult {
|
|
|
400
377
|
/** Resolves after the user completes the OAuth flow with a ready-to-ingest account. */
|
|
401
378
|
completion: Promise<IngestAccount>;
|
|
402
379
|
}
|
|
403
|
-
//#endregion
|
|
404
|
-
//#region ../../node_modules/.bun/@cortexkit+common-auth@0.27.1+edd79cef82a5b402/node_modules/@cortexkit/common-auth/dist/claustrum/watch.d.ts
|
|
405
380
|
/**
|
|
406
381
|
* How a host currently learns about changes, for logs and status displays.
|
|
407
382
|
* `watching`: a watch was accepted and is open, so polling is reduced to a
|
|
@@ -454,8 +429,6 @@ interface ScopedWatchSource {
|
|
|
454
429
|
enrollmentToken?: string;
|
|
455
430
|
}): ScopedWatchHandle;
|
|
456
431
|
}
|
|
457
|
-
//#endregion
|
|
458
|
-
//#region ../../node_modules/.bun/@cortexkit+common-auth@0.27.1+edd79cef82a5b402/node_modules/@cortexkit/common-auth/dist/claustrum/insula.d.ts
|
|
459
432
|
/**
|
|
460
433
|
* A held-open `usage.watch` stream. `closed` resolves when insula ends the
|
|
461
434
|
* stream (STREAM_END at shutdown, or a reply that ends it) or after `stop()`,
|
|
@@ -478,8 +451,6 @@ interface InsulaUsageTransport {
|
|
|
478
451
|
*/
|
|
479
452
|
watchUsage?(onNotice: (body: Uint8Array) => void): InsulaUsageWatch;
|
|
480
453
|
}
|
|
481
|
-
//#endregion
|
|
482
|
-
//#region ../../node_modules/.bun/@cortexkit+common-auth@0.27.1+edd79cef82a5b402/node_modules/@cortexkit/common-auth/dist/claustrum/custody.d.ts
|
|
483
454
|
/**
|
|
484
455
|
* `watchScoped` is present from claustrum-client 0.12.0. Hosts detect it at
|
|
485
456
|
* run time and keep polling without it.
|
|
@@ -584,8 +555,6 @@ interface KeptReceiptState {
|
|
|
584
555
|
readonly active: boolean;
|
|
585
556
|
readonly since: number | null;
|
|
586
557
|
}
|
|
587
|
-
//#endregion
|
|
588
|
-
//#region ../../node_modules/.bun/@cortexkit+common-auth@0.27.1+edd79cef82a5b402/node_modules/@cortexkit/common-auth/dist/claustrum/interlock.d.ts
|
|
589
558
|
/**
|
|
590
559
|
* The declined-account interlock: the user's "do not use this vault account",
|
|
591
560
|
* kept on the consumer side because the vault has no notion of it.
|
|
@@ -603,8 +572,6 @@ interface DeclinedAccount {
|
|
|
603
572
|
readonly credentialId: string;
|
|
604
573
|
readonly accountIdentity?: string;
|
|
605
574
|
}
|
|
606
|
-
//#endregion
|
|
607
|
-
//#region ../../node_modules/.bun/@cortexkit+common-auth@0.27.1+edd79cef82a5b402/node_modules/@cortexkit/common-auth/dist/claustrum/roster.d.ts
|
|
608
575
|
/**
|
|
609
576
|
* One vault account as the pool sees it. It carries no bearer material: the
|
|
610
577
|
* access token is fetched from the vault for every send. Several vault
|
|
@@ -664,8 +631,6 @@ interface ReorderVaultRosterResult {
|
|
|
664
631
|
* `ClaustrumScopedAttempt` that send was authorized with.
|
|
665
632
|
*/
|
|
666
633
|
type QuotaReceipt = Pick<ClaustrumScopedAttempt, 'credentialId' | 'accountIdentity' | 'accountIdentitySource' | 'expectedAccountIdentity'>;
|
|
667
|
-
//#endregion
|
|
668
|
-
//#region ../../node_modules/.bun/@cortexkit+common-auth@0.27.1+edd79cef82a5b402/node_modules/@cortexkit/common-auth/dist/claustrum/consumer.d.ts
|
|
669
634
|
/**
|
|
670
635
|
* How a started consumer learns about changes, for logs and status displays.
|
|
671
636
|
* `insula` is present when the consumer was given an insula source. Never
|
|
@@ -675,8 +640,6 @@ interface ClaustrumWatchState {
|
|
|
675
640
|
readonly vault: WatchMode;
|
|
676
641
|
readonly insula?: WatchMode;
|
|
677
642
|
}
|
|
678
|
-
//#endregion
|
|
679
|
-
//#region ../../node_modules/.bun/@cortexkit+common-auth@0.27.1+edd79cef82a5b402/node_modules/@cortexkit/common-auth/dist/claustrum/enrollment.d.ts
|
|
680
643
|
interface ClaustrumEnrollmentClient {
|
|
681
644
|
enrollPropose(input: {
|
|
682
645
|
name: string;
|
|
@@ -722,12 +685,8 @@ interface ClaustrumEnrollmentPaths {
|
|
|
722
685
|
statePath: string;
|
|
723
686
|
tokenPath: string;
|
|
724
687
|
}
|
|
725
|
-
//#endregion
|
|
726
|
-
//#region ../core/dist/pool-routing.d.ts
|
|
727
688
|
/** Existing callbacks may return a promise for an in-progress quota poll. */
|
|
728
689
|
type QuotaReadingRequest = ((id: string) => void) | ((id: string) => Promise<unknown> | undefined);
|
|
729
|
-
//#endregion
|
|
730
|
-
//#region ../core/dist/vault.d.ts
|
|
731
690
|
type VaultHost = 'opencode' | 'pi';
|
|
732
691
|
interface VaultPaths extends ClaustrumEnrollmentPaths {
|
|
733
692
|
/** The roster: the vault accounts, their quota and the declined ones. Holds no token. */
|
|
@@ -748,6 +707,8 @@ interface VaultStatus {
|
|
|
748
707
|
/** The name this host enrolls as. */
|
|
749
708
|
name: string;
|
|
750
709
|
enrollment: ClaustrumEnrollmentStatus;
|
|
710
|
+
/** Whether a roster snapshot exists, including an answered empty list. */
|
|
711
|
+
discovered: boolean;
|
|
751
712
|
/** Every vault account this host can see, declined and cold ones included. */
|
|
752
713
|
accounts: readonly VaultRosterRow[];
|
|
753
714
|
lastError?: string;
|
|
@@ -960,8 +921,6 @@ declare class OpenAiVault {
|
|
|
960
921
|
assertHostSlot(auth: unknown): void;
|
|
961
922
|
close(): void;
|
|
962
923
|
}
|
|
963
|
-
//#endregion
|
|
964
|
-
//#region ../core/dist/commands.d.ts
|
|
965
924
|
interface ResetTargetIdentity {
|
|
966
925
|
accountKey: string;
|
|
967
926
|
label: string;
|
|
@@ -969,8 +928,6 @@ interface ResetTargetIdentity {
|
|
|
969
928
|
chatgptAccountId?: string;
|
|
970
929
|
onAuthFailure?: (status: number) => Promise<void>;
|
|
971
930
|
}
|
|
972
|
-
//#endregion
|
|
973
|
-
//#region src/core/version-fence.d.ts
|
|
974
931
|
/** One live process that keeps the fence shut. */
|
|
975
932
|
interface VersionFenceBlocker {
|
|
976
933
|
/** `'unknown'` when a whole directory could not be read. */
|
|
@@ -986,8 +943,6 @@ type VersionFenceResult = {
|
|
|
986
943
|
open: false;
|
|
987
944
|
blockers: VersionFenceBlocker[];
|
|
988
945
|
};
|
|
989
|
-
//#endregion
|
|
990
|
-
//#region src/core/pool-migration.d.ts
|
|
991
946
|
/** The host login slot, shaped like the plugin's `client.auth`. */
|
|
992
947
|
interface HostSlotAdapter {
|
|
993
948
|
/** The shared auth.json path, independent of a plugin's config root. */
|
|
@@ -1176,8 +1131,6 @@ declare function migrateToPool(deps: PoolMigrationDeps & PoolMigrationFenceDeps)
|
|
|
1176
1131
|
* and the placeholder goes back into the slot.
|
|
1177
1132
|
*/
|
|
1178
1133
|
declare function adoptHostSlotLogin(deps: PoolMigrationDeps): Promise<PoolTransferOutcome>;
|
|
1179
|
-
//#endregion
|
|
1180
|
-
//#region src/core/pool-lifecycle.d.ts
|
|
1181
1134
|
interface PoolLifecycleTimers {
|
|
1182
1135
|
set(run: () => void, ms: number): unknown;
|
|
1183
1136
|
clear(handle: unknown): void;
|
|
@@ -1203,8 +1156,6 @@ interface PoolLifecycleDeps {
|
|
|
1203
1156
|
*/
|
|
1204
1157
|
paused?: () => boolean | Promise<boolean>;
|
|
1205
1158
|
}
|
|
1206
|
-
//#endregion
|
|
1207
|
-
//#region src/core/runtime-layout.d.ts
|
|
1208
1159
|
interface RuntimeLayoutLogger {
|
|
1209
1160
|
info(message: string, meta?: Record<string, unknown>): unknown;
|
|
1210
1161
|
warn(message: string, meta?: Record<string, unknown>): unknown;
|
|
@@ -1232,15 +1183,11 @@ interface RuntimeLayoutOptions {
|
|
|
1232
1183
|
/** Test seam: how long to wait for the layout lock. */
|
|
1233
1184
|
layoutLockWaitMs?: number;
|
|
1234
1185
|
}
|
|
1235
|
-
//#endregion
|
|
1236
|
-
//#region src/util/canonical-input.d.ts
|
|
1237
1186
|
interface CanonicalInput {
|
|
1238
1187
|
texts: string[];
|
|
1239
1188
|
snapshots: unknown[];
|
|
1240
1189
|
retainable: boolean;
|
|
1241
1190
|
}
|
|
1242
|
-
//#endregion
|
|
1243
|
-
//#region src/codex-request.d.ts
|
|
1244
1191
|
declare const RESPONSES_LITE_MODELS: ReadonlySet<string>;
|
|
1245
1192
|
declare const CODEX_VERSION = "0.159.0";
|
|
1246
1193
|
declare const CODEX_USER_AGENT = "codex_exec/0.159.0 (Debian 12.0.0; aarch64) unknown (codex_exec; 0.159.0)";
|
|
@@ -1263,5 +1210,4 @@ interface CodexRequestRuntime {
|
|
|
1263
1210
|
now: () => number;
|
|
1264
1211
|
uuid: () => string;
|
|
1265
1212
|
}
|
|
1266
|
-
//#endregion
|
|
1267
1213
|
export { parseJwtClaims as _, RESPONSES_LITE_MODELS as a, HostSlotAdapter as c, OpenAiVaultOptions as d, BeginAccountLoginOptions as f, extractAccountIdFromClaims as g, TokenResponse as h, CodexSessionMetadata as i, ResetTargetIdentity as l, IdTokenClaims as m, CODEX_VERSION as n, RuntimeLayoutOptions as o, BeginAccountLoginResult as p, CodexRequestRuntime as r, PoolLifecycleDeps as s, CODEX_USER_AGENT as t, OpenAiVault as u, AccountPaths as v };
|
|
@@ -0,0 +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-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
|
+
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};
|