@cortexkit/opencode-openai-auth 1.5.0 → 1.6.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin.js +8 -8
- package/dist/{codex-request-BjGT9yWg.d.ts → codex-request-D_In8uaR.d.ts} +43 -26
- package/dist/{index-gmmakhbt.js → index-1qxz4s8a.js} +2 -2
- package/dist/{index-2rw81dtm.js → index-79y7w9bz.js} +1 -1
- package/dist/{index-2yszc75z.js → index-7nmdsmpp.js} +2 -2
- package/dist/{index-3y453wg4.js → index-8xq099qf.js} +2 -2
- package/dist/{index-mhfja8yr.js → index-b0ty9qam.js} +2 -2
- package/dist/index-cv6aqcvk.js +65 -0
- package/dist/index-ge60xry3.js +90 -0
- package/dist/{index-krcqvyqf.js → index-jkpg9d1p.js} +1 -1
- package/dist/index-k5anexvs.js +69 -0
- package/dist/{index-e416r885.js → index-rf0ht3gc.js} +2 -2
- package/dist/{index-4w0nsq5s.js → index-x9nffaye.js} +1 -1
- package/dist/{index-7vkn2e46.js → index-ya9c5e4m.js} +1 -1
- package/dist/{index-djnfq652.js → index-z8bptbrk.js} +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/{model-BMq5SCUB.d.ts → model-D22uj0OB.d.ts} +1 -1
- package/dist/{port-file-CjMFUWcX.d.ts → port-file-8ElfwDcq.d.ts} +1 -1
- package/dist/{protocol-BC3ndToM.d.ts → protocol-CK9guiFy.d.ts} +1 -1
- package/dist/rpc/port-file.d.ts +1 -1
- 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 +3 -3
- package/dist/rpc/rpc-client.js +1 -1
- package/dist/rpc/rpc-dir.js +1 -1
- package/dist/{sidebar-state-DfYyqiOH.d.ts → sidebar-state-Bb9L9oPq.d.ts} +4 -4
- package/dist/sidebar-state.d.ts +1 -1
- package/dist/sidebar-state.js +1 -1
- package/dist/token-util-nyvn9866.js +1 -0
- package/dist/{token-ycw7dyev.js → token-xtq3457d.js} +1 -1
- package/dist/tui-preferences.js +1 -1
- package/dist/tui.d.ts +22 -3
- package/dist/v2/server.d.ts +2 -2
- package/dist/v2/server.js +2 -2
- package/package.json +2 -2
- package/src/tui-compiled/raw/shared/81dddd203f1b92a3-quota-writer.js +4 -54
- package/src/tui-compiled/raw/shared/a62a27a204266acd-attribution.js +39 -25
- package/src/tui-compiled/raw/shared/a910277ac43a8626-pull.js +3 -1
- package/src/tui-compiled/raw/shared/c852a15cfe489d12-pool.js +18 -3
- package/src/tui-compiled/raw/shared/c911dbb64c9d85c7-quota-writer.js +298 -0
- package/src/tui-compiled/raw/shared/e1c5e56df0ba4053-pending.js +48 -0
- package/src/tui-compiled/raw/tui.tsx +47 -1
- package/src/tui-compiled/runtime/shared/81dddd203f1b92a3-quota-writer.js +4 -54
- package/src/tui-compiled/runtime/shared/a62a27a204266acd-attribution.js +39 -25
- package/src/tui-compiled/runtime/shared/a910277ac43a8626-pull.js +3 -1
- package/src/tui-compiled/runtime/shared/c852a15cfe489d12-pool.js +18 -3
- package/src/tui-compiled/runtime/shared/c911dbb64c9d85c7-quota-writer.js +298 -0
- package/src/tui-compiled/runtime/shared/e1c5e56df0ba4053-pending.js +48 -0
- package/src/tui-compiled/runtime/tui.js +19 -1
- package/dist/index-2p3gcjsa.js +0 -69
- package/dist/index-6fdmqk6p.js +0 -90
- package/dist/index-fztcacjr.js +0 -65
- package/dist/token-util-ed4az5gg.js +0 -1
package/dist/bin.js
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{c as
|
|
3
|
-
`);return b<0?"":G.slice(b+1)}class m extends Error{step="pi-install";exitCode;signal;stderrTail;constructor(G){super(
|
|
2
|
+
import{c as f1}from"./index-79y7w9bz.js";import{Db as E1,Ga as N1,Ha as E,Ia as Y,Ja as v,lb as v1,ua as S1,va as f,wa as e}from"./index-k5anexvs.js";import{dd as y1,jd as j1,ld as h,md as L,od as d,pd as D1}from"./index-ge60xry3.js";import"./index-8xq099qf.js";import{Le as b1,Re as w1,Se as I1,Ve as P1}from"./index-b0ty9qam.js";import"./index-7nmdsmpp.js";import"./index-ya9c5e4m.js";import{spawn as h1}from"node:child_process";var N=4096,d1=1048576;class G1{buffer=Buffer.alloc(N);start=0;length=0;truncated=!1;get didTruncate(){return this.truncated}push(G){if(G.length>=N){if(G.length>N||this.length>0)this.truncated=!0;G.copy(this.buffer,0,G.length-N),this.start=0,this.length=N;return}let b=Math.max(0,this.length+G.length-N);if(b>0)this.truncated=!0;this.start=(this.start+b)%N,this.length-=b;let z=(this.start+this.length)%N,Z=Math.min(G.length,N-z);if(G.copy(this.buffer,z,0,Z),Z<G.length)G.copy(this.buffer,0,Z);this.length+=G.length}toString(){let G=Buffer.alloc(this.length),b=Math.min(this.length,N-this.start);if(this.buffer.copy(G,0,this.start,this.start+b),b<this.length)this.buffer.copy(G,b,0,this.length-b);let z=0;while(z<G.length){let Z=G[z];if(Z===void 0||(Z&192)!==128)break;z++}return G.subarray(z).toString("utf8")}}var I={run(G,b,z={}){return new Promise((Z)=>{let J=performance.now(),$=z.timeoutMs??15000,K=new G1,W=[],j=0,Q=!1,D=!1,U=!1,V;try{V=h1(G,[...b],{env:z.env??process.env,windowsHide:!0,windowsVerbatimArguments:z.windowsVerbatimArguments,stdio:["ignore","pipe","pipe"]})}catch{Z({exitCode:1,stdout:"",stderr:"",spawnError:!0,signal:null,timedOut:!1,durationMs:performance.now()-J});return}let x=$>0?setTimeout(()=>{U=!0,V.kill("SIGTERM")},$):void 0;V.stdout?.on("data",(F)=>{let k=d1-j,q=Math.min(k,F.length);if(q>0)W.push(F.subarray(0,q)),j+=q;if(F.length>k)Q=!0,V.kill("SIGTERM")}),V.stderr?.on("data",(F)=>K.push(F));let X=!1,B=(F,k)=>{if(X)return;if(X=!0,x)clearTimeout(x);Z({exitCode:D?1:Q?1:F??1,stdout:Buffer.concat(W,j).toString("utf8"),stderr:K.toString(),stderrTruncated:K.didTruncate,...D?{spawnError:!0}:{},signal:k??null,timedOut:U,durationMs:performance.now()-J})};V.once("error",()=>{if(D=!0,V.pid===void 0)B(null,null)}),V.once("close",(F,k)=>B(F,k))})}};function g(G,b,z,Z,J,$=15000){if(b==="win32"&&/\.(cmd|bat)$/i.test(z)){if(/["%!\r\n]/.test(z)||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",`""${z}" ${Z.join(" ")}"`],{env:J,timeoutMs:$,windowsVerbatimArguments:!0})}return G.run(z,Z,{env:J,timeoutMs:$})}var c1="Pi install failed; run pi install after checking your npm connection.";function u1(G){let b=Buffer.from(G,"utf8");if(b.length<=N)return G;let z=b.length-N;while(z<b.length){let Z=b[z];if(Z===void 0||(Z&192)!==128)break;z++}return b.subarray(z).toString("utf8")}function p1(G){let b=G.indexOf(`
|
|
3
|
+
`);return b<0?"":G.slice(b+1)}class m extends Error{step="pi-install";exitCode;signal;stderrTail;constructor(G){super(c1);this.name="SetupCommandError",this.exitCode=G.exitCode,this.signal=G.signal;let b=G.stderrTruncated?p1(G.stderrTail):G.stderrTail,z=b1(b);this.stderrTail=u1(typeof z==="string"?z:"")}}var l1={opencode:"OpenCode",pi:"Pi"},a1={enrolled:"connected to the vault","not-enrolled":"not connected",unknown:"unknown, check with ck auth status"};function z1({host:G,outcome:b}){return`${l1[G]}: ${a1[b]}`}var i1=new WeakMap;function J1(G,b){if(typeof G!=="object"&&typeof G!=="function"||!G)return;i1.set(G,Object.freeze(b.map((z)=>Object.freeze({...z}))))}import{accessSync as t1,constants as e1,existsSync as G0,readFileSync as b0,realpathSync as z0,statSync as J0}from"node:fs";import{mkdtemp as Z0,rm as $0}from"node:fs/promises";import{tmpdir as Q0}from"node:os";import{join as K0}from"node:path";import{parse as q0}from"jsonc-parser";import{homedir as s1}from"node:os";import{posix as r1,win32 as n1}from"node:path";import{fileURLToPath as o1}from"node:url";function R(G={}){let b=G.env??process.env,z=G.platform??process.platform,Z=z==="win32"?n1:r1,J=G.home??(z==="win32"?b.USERPROFILE:b.HOME)??s1(),$=G.cwd??process.cwd(),K=(D)=>Z.resolve($,D),W=b.OPENCODE_CONFIG_DIR?.trim(),j=b.XDG_CONFIG_HOME?.trim(),Q=b.PI_CODING_AGENT_DIR?.trim()||Z.join(J,".pi","agent");if(Q==="~")Q=J;else if(/^~[/\\]/.test(Q))Q=Z.join(J,Q.slice(2));if(Q.startsWith("file://"))Q=o1(Q);return{env:b,platform:z,path:Z,home:J,cwd:$,opencode:W?K(W):j?Z.join(K(j),"opencode"):Z.join(J,".config","opencode"),pi:K(Q)}}function c(G,b){try{return J0(G)[b]()}catch{return!1}}var _={exists:G0,isFile:(G)=>c(G,"isFile"),isDirectory:(G)=>c(G,"isDirectory"),isExecutable(G){try{return t1(G,e1.X_OK),c(G,"isFile")}catch{return!1}},readText:(G)=>b0(G,"utf8"),realpath:z0};function w(G,b={}){let{env:z,platform:Z,path:J,cwd:$}=R(b),K=b.fs??_,W=Object.entries(z).find(([Q])=>Z==="win32"?Q.toUpperCase()==="PATH":Q==="PATH")?.[1]??"",j=Z==="win32"?[".exe",".cmd",".bat",""]:[""];for(let Q of W.split(Z==="win32"?";":":")){let D=Q.trim().replace(/^"|"$/g,"");if(!D)continue;for(let U of j){let V=J.resolve($,D,G+U);if(Z==="win32"?K.isFile(V):K.isExecutable(V))return V}}return null}function Z1(G={}){let{platform:b,home:z,env:Z,path:J}=R(G);if(b==="darwin")return["/Applications/OpenCode.app","/Applications/OpenCode Beta.app",J.join(z,"Applications","OpenCode.app"),J.join(z,"Applications","OpenCode Beta.app")];if(b==="win32"){let $=Z.LOCALAPPDATA||J.join(z,"AppData","Local");return[J.join($,"Programs","opencode"),J.join($,"opencode")]}return["/opt/OpenCode","/usr/lib/opencode",J.join(z,".local","share","applications","opencode.desktop")]}function u(G,b){let z=b.fs??_,{path:Z}=R(b);try{let J=z.readText(G);if(J.length>65536)return G;let $=[...J.matchAll(/"%~?dp0%?\\([^"%\r\n]+)"/g)];if(!$.length)$.push(...J.matchAll(/"\$basedir\/([^"$\r\n]+)"/g));let K=$.at(-1)?.[1];if(K){let W=Z.join(Z.dirname(G),...K.split(/[/\\]+/));if(z.isFile(W))return z.realpath(W)}return z.realpath(G)}catch{return G}}function x0(G,b){let z=b.fs??_,{path:Z}=R(b),J=Z.dirname(u(G,b));for(;;){try{let K=JSON.parse(z.readText(Z.join(J,"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 $=Z.dirname(J);if($===J)return null;J=$}}function $1(G={}){let b=w("opencode",G),z=w("opencode2",G),Z=b&&z&&u(b,G)===u(z,G),J=G.fs??_,{path:$,opencode:K}=R(G),W="1";for(let Q of["jsonc","json"]){let D=$.join(K,`opencode.${Q}`);if(!J.exists(D))continue;try{if(Object.hasOwn(q0(J.readText(D))??{},"plugins"))W="2"}catch{}break}let j=b?x0(b,G)??(Z?"2":W):null;if(z&&j==="1"&&!Z)return"ambiguous";return z||Z?"2":j??W}async function p(G,b={}){let z=b.fs??_,{env:Z,platform:J,opencode:$,pi:K}=R(b),W=b.runner??I,j=w("opencode",b)??w("opencode2",b),Q=w("pi",b),D=w("ck",b),U=async(B)=>{if(!B)return null;let F;try{F=await Z0(K0(Q0(),"common-auth-setup-version-"));let k={...Z,HOME:F,USERPROFILE:F,XDG_CONFIG_HOME:F,XDG_DATA_HOME:F,XDG_STATE_HOME:F,XDG_CACHE_HOME:F,OPENCODE_CONFIG_DIR:F,OPENCODE_CONFIG:void 0,OPENCODE_CONFIG_CONTENT:void 0,OPENCODE_AUTH_CONTENT:void 0,PI_CODING_AGENT_DIR:F},q=await g(W,J,B,["--version"],k,2000);return q.exitCode===0?/\b\d+\.\d+\.\d+(?:-[\w.-]+)?/.exec(q.stdout)?.[0]??null:null}catch{return null}finally{if(F)await $0(F,{recursive:!0,force:!0}).catch(()=>{})}},V=!1;if(D&&z.exists(G.vault.connectionFile))try{(await(b.connect??h)({connectionFile:G.vault.connectionFile,handshakeTimeoutMs:2000})).close(),V=!0}catch{V=!1}let[x,X]=await Promise.all([U(j),U(Q)]);return{opencode:{installed:z.isDirectory($)||Z1(b).some((B)=>z.exists(B))||j!==null,executable:j,version:x,directory:$,generation:$1(b)},pi:{installed:Q!==null||z.isDirectory(K),executable:Q,version:X,directory:K},claustrum:{available:V,executable:D}}}import{setTimeout as Y0}from"node:timers/promises";import{writeEnrollmentTokenFile as B0}from"@cortexkit/claustrum-client";var Q1=45000,l=new Set(["opencode","litecode","opencode2","pi"]),q1=new Set(["node","bun"]),U0=[...l,...q1].map((G)=>`Name LIKE '${G}%'`).join(" OR "),W0=`$ErrorActionPreference = 'Stop'; $rows = @(Get-CimInstance Win32_Process -Filter "${U0}" | Select-Object Name,ProcessId,CommandLine); ConvertTo-Json -Compress -Depth 3 -InputObject @{ complete = $true; processes = $rows }`,X0=/(?:^|[/\\])pi-coding-agent[/\\]dist[/\\](?:(?:bundle|bun)[/\\])?cli\.m?js$/i;function j0(G){return[...G.matchAll(/"([^"]*)"|(\S+)/g)].map((b)=>b[1]??b[2]??"")}function K1(G){return(G.split(/[/\\]/).pop()??"").toLowerCase().replace(/\.(?:exe|cmd|bat|m?js)$/,"")}var D0=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"]),V0=new Set(["-e","--eval","-p","--print"]);function F0(G,b){for(let z=0;z<b.length;z++){let Z=b[z]??"";if(Z==="--")return b[z+1];if(V0.has(Z))return;if(Z.startsWith("-")){if(!Z.includes("=")&&D0.has(Z))z++;continue}if(G==="bun"&&Z==="run")continue;return Z}return}function x1(G){let[b,...z]=j0(G);if(b===void 0)return null;let Z=K1(b);if(l.has(Z))return Z;if(!q1.has(Z))return null;let J=F0(Z,z);if(J===void 0)return null;let $=K1(J);if(l.has($))return $;return X0.test(J)?"pi":null}class H 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 T extends Error{activeHosts;constructor(G){let b=G.map((z)=>({pid:z.pid,command:x1(z.command)??"host"}));super(`OpenCode or Pi processes are currently running:
|
|
4
4
|
${b.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=b,this.name="ProcessFenceViolationError"}}async function a(G=I,b={}){let z=(b.platform??process.platform)==="win32",Z=b.selfPid??process.pid,J={step:z?"tasklist":"ps",exitCode:null,signal:null,timedOut:!1,durationMs:0},$=async(K,W,j,Q)=>{let D=performance.now();J={step:K,exitCode:null,signal:null,timedOut:!1,durationMs:0};try{let U=await G.run(W,j,{env:b.env,timeoutMs:Q});return J={step:K,exitCode:U.exitCode,signal:U.signal??null,timedOut:U.timedOut??!1,durationMs:U.durationMs??performance.now()-D},U}finally{if(J.exitCode===null)J.durationMs=performance.now()-D;b.onStep?.({...J})}};try{if(z&&b.hostImagesOnly){let Q=await $("CIM","powershell.exe",["-NoProfile","-NonInteractive","-Command",
|
|
7
|
+
Please quit all OpenCode, LiteCode, and Pi processes before running setup.`);this.activeHosts=b,this.name="ProcessFenceViolationError"}}async function a(G=I,b={}){let z=(b.platform??process.platform)==="win32",Z=b.selfPid??process.pid,J={step:z?"tasklist":"ps",exitCode:null,signal:null,timedOut:!1,durationMs:0},$=async(K,W,j,Q)=>{let D=performance.now();J={step:K,exitCode:null,signal:null,timedOut:!1,durationMs:0};try{let U=await G.run(W,j,{env:b.env,timeoutMs:Q});return J={step:K,exitCode:U.exitCode,signal:U.signal??null,timedOut:U.timedOut??!1,durationMs:U.durationMs??performance.now()-D},U}finally{if(J.exitCode===null)J.durationMs=performance.now()-D;b.onStep?.({...J})}};try{if(z&&b.hostImagesOnly){let Q=await $("CIM","powershell.exe",["-NoProfile","-NonInteractive","-Command",W0],Q1);if(Q.exitCode!==0)throw new H(J);let D=JSON.parse(Q.stdout);if(!D||typeof D!=="object"||!("complete"in D)||D.complete!==!0||!("processes"in D))throw new H(J);let U=D.processes,V=U===null?[]:Array.isArray(U)?U:[U],x=[];for(let X of V){if(!X||typeof X!=="object"||!("Name"in X)||typeof X.Name!=="string"||!("ProcessId"in X)||!Number.isSafeInteger(X.ProcessId)||X.ProcessId<0||!("CommandLine"in X))throw new H(J);let B=X.ProcessId;if(!/^(?:node|bun)\.exe$/i.test(X.Name))x.push({pid:B,command:X.Name});else if(typeof X.CommandLine==="string")x.push({pid:B,command:X.CommandLine});else if(B!==Z)throw new H(J)}return x}let K=await $(z?"tasklist":"ps",z?"tasklist.exe":"ps",z?["/fo","csv","/nh"]:["-eo","pid,command"]);if(K.exitCode!==0)throw new H(J);let W=[];for(let Q of K.stdout.split(/\r?\n/)){let D=Q.trim();if(!D)continue;let U,V;if(z){let x=/^"([^"]+)","(\d+)"(?:,|$)/.exec(D);if(!x)throw new H(J);V=x[1]??"",U=Number(x[2])}else{let x=/^(\d+)\s+(.+)$/.exec(D);if(!x){if(/^PID\s+COMMAND$/i.test(D))continue;throw new H(J)}U=Number(x[1]),V=x[2]??""}if(!Number.isSafeInteger(U)||U<0)throw new H(J);W.push({pid:U,command:V})}if(!W.length)throw new H(J);let j=W.filter((Q)=>Q.pid!==Z&&/^(?:node|bun)\.exe$/i.test(Q.command));if(z&&j.length&&b.inspectRuntimes!==!1){let Q=await $("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`],Q1);if(Q.exitCode!==0)throw new H(J);let D=JSON.parse(Q.stdout||"null"),U=D===null?[]:Array.isArray(D)?D:[D],V=new Map;for(let x of U){if(!x||typeof x!=="object"||!("ProcessId"in x)||!("CommandLine"in x)||!Number.isSafeInteger(x.ProcessId))throw new H(J);if(typeof x.CommandLine==="string")V.set(Number(x.ProcessId),x.CommandLine);else if(j.some((X)=>X.pid===x.ProcessId))throw new H(J)}for(let x of j)x.command=V.get(x.pid)??""}return W}catch(K){if(K instanceof H)throw K;throw new H(J)}}function S(G=I,b={}){let z=b.selfPid??process.pid,Z=(J)=>J.pid!==z&&x1(J.command)!==null;return{async listRunningHosts(J){return(await a(G,{...b,env:J,hostImagesOnly:!0})).filter(Z)},async previewRunningHosts(J){let $=await a(G,{...b,env:J,inspectRuntimes:!1}),K=(b.platform??process.platform)==="win32";return{hosts:$.filter(Z),uncheckedRuntimes:K?$.filter((W)=>W.pid!==z&&/^(?:node|bun)\.exe$/i.test(W.command)).length:0}}}}async function P(G,b){let z=await G.listRunningHosts(b);if(z.length)throw new T(z)}var H0="Claustrum enrollment did not complete. Inspect and approve with ck, then rerun setup.",V1='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.',F1=300000,U1=1000,W1=[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,b){super(G);if(this.name="HostNotEnrolledError",this.reason=b.reason,b.lastErrorCode!==void 0)this.lastErrorCode=i(b.lastErrorCode)}}function X1(G,b){return`ck auth enroll approve --request-id ${G} --name ${b}`}async function Y1(G,b,z,Z,J){let{name:$,paths:K}=G.vault.hosts[b],W=L(K);await J();let j=await(z.connect??h)({connectionFile:G.vault.connectionFile,handshakeTimeoutMs:2000}).catch(()=>{throw new A("Claustrum connection failed; start ck and rerun setup.",{reason:"connection-failed"})}),Q=z.now??(()=>performance.now()),D=z.wait??Y0;try{let U=new D1({proposedName:$,paths:W,client:j,writeTokenFile:async(q,O)=>{await J(),await B0(q,O)}});Y(Z,`Asking the vault to connect ${$}…`);let V=Q()+F1,x,X,B,F=0;for(;;){await J();let q=await U.reconcile();if(q.state==="approved"){Y(Z,`Connected ${b} to Claustrum.`);return}if(q.state==="unavailable"&&q.code===j1)throw new A(V1,{reason:"unsupported-vault",lastErrorCode:q.code});if(q.state!=="pending"&&q.state!=="busy")throw new A("Claustrum enrollment refused; inspect its status with ck before rerunning setup.",{reason:"refused",..."code"in q&&{lastErrorCode:q.code}});let O=U1;if(q.state==="busy")X="busy";else if(q.retryCode)X=q.retryCode;if(q.state==="pending"&&q.requestId){if(F=0,q.requestId!==x){if(!/^[a-zA-Z0-9_-]+$/.test(q.requestId))throw new A("Invalid enrollment request id.",{reason:"invalid-request"});x=q.requestId,Y(Z,"Waiting for approval. In another terminal, run:"),Y(Z,` ${X1(q.requestId,$)}`),Y(Z,`Enrollment files: ${W.statePath}, ${W.tokenPath}`)}}else if(q.state==="pending"&&q.retryCode){O=W1[Math.min(F,W1.length-1)]??U1,F++;let C=i(q.retryCode);if(C!==B)B=C,Y(Z,`The vault has not created the request yet (${C}); retrying.`)}let M=V-Q();if(M<=0)break;await D(Math.min(O,M))}if(x)throw new A(`Claustrum approval is still pending. In another terminal, run: ${X1(x,$)} and then rerun setup.`,{reason:"approval-pending",...X!==void 0&&{lastErrorCode:X}});let k=i(X);throw new A(`The vault never created the enrollment request (last error: ${k}). Check that ck is running, then rerun setup.`,{reason:"request-not-created",lastErrorCode:k})}catch(U){if(U instanceof T||U instanceof H||U instanceof A)throw U;let V=U?.code;throw new A(H0,{reason:"incomplete",...typeof V==="string"&&{lastErrorCode:V}})}finally{j.close()}}async function B1(G,b){let z=new Set(b);for(;;){let Z=await v(G,[...["opencode","pi"].map((J)=>({value:J,label:`[${z.has(J)?"x":" "}] ${J==="opencode"?"OpenCode":"Pi"}`,hint:b.includes(J)?"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[...z];if(z.has(Z))z.delete(Z);else z.add(Z)}}import{applyEdits as s,createScanner as T0,findNodeAtLocation as L0,modify as O1,parse as y0,parseTree as S0}from"jsonc-parser";import{randomUUID as O0}from"node:crypto";import{mkdir as M0,open as k0,rename as C0,stat as N0,unlink as R0}from"node:fs/promises";import{basename as A0,dirname as w0,join as I0}from"node:path";import{setTimeout as _0}from"node:timers/promises";async function H1(G,b,z={}){let Z=(z.platform??process.platform)==="win32",J=w0(G);await M0(J,{recursive:!0});let $;if(!Z)try{$=(await N0(G)).mode&4095}catch(j){if(j.code!=="ENOENT")throw j}let K=I0(J,`.${A0(G)}.${(z.stageName??O0)()}.tmp`),W=!1;try{let j=await k0(K,"wx",$??438);W=!0;try{if(await j.writeFile(b,"utf8"),$!==void 0)await j.chmod($)}finally{await j.close()}let Q=z.now??(()=>performance.now()),D=Q();for(let U=0;;U++){await z.beforeRename?.();try{await(z.rename??C0)(K,G),W=!1;return}catch(V){let x=V.code,X=2000-(Q()-D);if(!Z||!["EPERM","EBUSY","EACCES"].includes(x??"")||X<=0||U>=40)throw Error(`Unable to replace host config ${G}. Close editors or other programs using the file, then rerun setup.`);await(z.wait??_0)(Math.min(X,25*2**Math.min(U,2)))}}}finally{if(W)await R0(K).catch(()=>{})}}function M1(G){let b=typeof G==="string"?G:Array.isArray(G)?G[0]:G&&typeof G==="object"&&("package"in G)?G.package:null;if(typeof b!=="string")return null;let z=b.indexOf("@",b.startsWith("@")?1:0);return z<0?b:b.slice(0,z)}function k1(G,b,z){let Z=S0(G),J=Z&&L0(Z,[b]),$=J?.children??[],K=$[z];if(!K||!J)throw Error("Invalid plugin array edit.");let W=[{offset:K.offset,length:K.length,content:""}],j=(Q,D)=>{let U=T0(G.slice(Q,D),!0);if(U.scan(),G[Q+U.getTokenOffset()]===",")W.push({offset:Q+U.getTokenOffset(),length:1,content:""})};if(z===$.length-1){let Q=$[z-1];if(Q)j(Q.offset+Q.length,K.offset);j(K.offset+K.length,J.offset+J.length-1)}else j(K.offset+K.length,$[z+1]?.offset??K.offset+K.length);return s(G,W)}function C1(G,b,z,Z){let J=[],$=y0(G,J,{allowTrailingComma:!0});if(J.length||!$||typeof $!=="object"||Array.isArray($))throw Error("Invalid OpenCode config; refusing to overwrite it.");let K={formattingOptions:{insertSpaces:!/^\t+/m.test(G),tabSize:/^([ ]+)"/m.exec(G)?.[1]?.length??2,eol:G.includes(`\r
|
|
8
8
|
`)?`\r
|
|
9
9
|
`:`
|
|
10
|
-
`}},W=G,j=$[b];if(j!==void 0&&!Array.isArray(j))throw Error(`OpenCode ${b} must be an array.`);let Q=Array.isArray(j)?[...j]:[],D=Q.flatMap((x,X)=>
|
|
11
|
-
`,X=
|
|
12
|
-
${q.content}`);if(Q.includes("pi"))Y(J,`Would run ${$.pi.executable} install npm:${G.packages.pi}@${G.version}`);for(let q of Q)Y(J,`Would migrate ${q} using the plugin callback (provider-specific writes).`)}else{let q={opencodeGeneration:D,mode:F,hosts:Object.freeze([...Q]),piAgentDir:$.pi.directory},O=new Map;try{for(let M of Q){if(await X(),await G.beforeSignIn?.(M,q),await X(),B){O.set(M,"unknown");try{await
|
|
13
|
-
ck auth grant --principal enrolled:${f($)} --selector-kind category --selector ${
|
|
14
|
-
${x.instructions}`);let B=await x.completion;await P(z),await J($),await W.set({...j,body:{type:"oauth",access:B.access,refresh:B.refresh,expires:B.expires,...B.accountId?{accountId:B.accountId}:{}}}),b("Signed in to OpenCode. The first plugin start adopts this login into the account pool.")},async migrate($){b(`${$}: 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 t(
|
|
10
|
+
`}},W=G,j=$[b];if(j!==void 0&&!Array.isArray(j))throw Error(`OpenCode ${b} must be an array.`);let Q=Array.isArray(j)?[...j]:[],D=Q.flatMap((x,X)=>M1(x)===z?[X]:[]),U=`${z}@${Z}`;if(!D.length)W=s(W,O1(W,j===void 0?[b]:[b,Q.length],j===void 0?[U]:U,K));else{let x=D[0],X=Q[x],B=Array.isArray(X)?[U,...X.slice(1)]:X&&typeof X==="object"?{...X,package:U}:U;if(JSON.stringify(X)!==JSON.stringify(B))W=s(W,O1(W,[b,x],B,K));for(let F of D.slice(1).reverse())W=k1(W,b,F)}let V=b==="plugin"?"plugins":"plugin";if(Array.isArray($[V])){let x=$[V];for(let X=x.length-1;X>=0;X--)if(M1(x[X])===z)W=k1(W,V,X)}return W}function r(G,b,z={}){let Z=z.fs??_,{path:J,opencode:$}=R(z),K=b==="2"?"plugins":"plugin";return(b==="2"?["opencode"]:["opencode","tui"]).map((j)=>{let Q=J.join($,`${j}.jsonc`),D=J.join($,`${j}.json`),U=Z.exists(Q)?Q:Z.exists(D)?D:Q,V=Z.exists(U),x=V?Z.readText(U):`${JSON.stringify({$schema:`https://opencode.ai/${j==="tui"?"tui":"config"}.json`},null,2)}
|
|
11
|
+
`,X=C1(x,K,G.packages.opencode,G.version);return{path:U,content:X,changed:!V||X!==x}})}async function n(G,b){for(let z of G){if(!z.changed)continue;await b?.(),await H1(z.path,z.content,{beforeRename:b})}}async function o(G,b,z={}){let{platform:Z,env:J}=R(z),$=await g(z.runner??I,Z,b,["install",`npm:${G.packages.pi}@${G.version}`],J);if($.exitCode!==0||$.timedOut)throw new m({exitCode:$.spawnError?null:$.exitCode,signal:$.signal??null,stderrTail:$.stderr,stderrTruncated:$.stderrTruncated??!1})}var R1="Multiple OpenCode generations found. Choose --opencode=1|2|both before running noninteractive setup.";function P0(G){let b={yes:!1,dryRun:!1,claustrum:!1,noClaustrum:!1,login:!1,opencode:void 0};for(let z of G)if(z==="--yes")b.yes=!0;else if(z==="--dry-run")b.dryRun=!0;else if(z==="--claustrum")b.claustrum=!0;else if(z==="--no-claustrum")b.noClaustrum=!0;else if(z==="--login")b.login=!0;else if(/^--opencode=(1|2|both)$/.test(z))b.opencode=z.slice(11);else throw Error(`Unknown setup argument: ${z}`);if(b.claustrum&&b.noClaustrum)throw Error("--claustrum and --no-claustrum cannot be used together.");if(b.login&&b.claustrum)throw Error("--login and --claustrum cannot be used together.");return b}function v0(G){for(let b of Object.values(G.packages))if(!/^(?:@[a-z0-9._-]+\/)?[a-z0-9._-]+$/.test(b))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 b of Object.values(G.vault.hosts))if(!/^[a-z0-9][a-z0-9-]*$/.test(b.name))throw Error("Setup requires lowercase vault names containing only letters, digits and dashes.")}async function E0(G,b,z){let Z=[];for(let J of b){let $=z.get(J)??"not-enrolled";if($==="unknown"){let{name:K,paths:W}=G.vault.hosts[J],j=await d(L(W),K).catch(()=>"unreadable");if(j==="vault")$="enrolled";else if(j==="local")$="not-enrolled"}Z.push({host:J,outcome:$})}return Z}async function t(G,b=[],z={}){let Z=P0(b);v0(G);let J=z.terminal??N1(),$=await p(G,z);Y(J,`${G.displayName} setup`);for(let[q,O]of[["OpenCode",$.opencode],["Pi",$.pi]])Y(J,`${q}: ${O.installed?`found (version ${O.version??"unknown"})`:"not found"} — ${O.directory}`);Y(J,`Claustrum: ${$.claustrum.available?"available":"not available"}`);let K=$.pi.installed&&!$.pi.executable;if(K)Y(J,"Pi: skipped, because its folder exists but pi is not on PATH. Install the Pi CLI and rerun setup to add it.");let W=["opencode","pi"].filter((q)=>$[q].installed&&!(q==="pi"&&K)),j=Z.yes||Z.dryRun&&!E(J);if(!j&&!E(J))throw Error("Setup requires a TTY or --yes.");let Q=j?W:await B1(J,W)??[],D=Z.opencode??($.opencode.generation==="ambiguous"?"1":$.opencode.generation);if(Q.includes("opencode")&&!Z.opencode&&$.opencode.generation==="ambiguous"){if(j||!E(J))throw Error(R1);let q=await v(J,[{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(q===null)return{hosts:[],dryRun:Z.dryRun,mode:"local",detection:$};D=q}if(!Q.length)return Y(J,"No hosts selected. Install OpenCode or Pi and rerun setup."),{hosts:Q,dryRun:Z.dryRun,mode:"local",detection:$};let{env:U,platform:V}=R(z),x=z.fence??S(z.runner??I,{platform:V}),X=async()=>{try{await P(x,U)}catch(q){if(q instanceof H)Y(J,q.refusalText);throw q}};if(Y(J,"Checking that OpenCode and Pi are not running…"),Z.dryRun)try{let q=x.previewRunningHosts?await x.previewRunningHosts(U):{hosts:await x.listRunningHosts(U),uncheckedRuntimes:0},O=q.hosts;if(q.uncheckedRuntimes>0)Y(J,"Node or Bun programs are running; a real run checks whether any of them is OpenCode or Pi.");let M=new Set(new T(O).activeHosts.map((C)=>C.command.toLowerCase()==="pi"?"Pi":"OpenCode"));for(let C of M)Y(J,`${C} is running; setup will ask you to quit it.`)}catch(q){if(Y(J,"Process inspection failed; real setup will require successful inspection and stopped OpenCode/Pi hosts."),q instanceof H)Y(J,q.refusalText)}else await X();if(Z.claustrum&&!$.claustrum.available)throw Error("Claustrum is not available. Start ck or use --no-claustrum for local sign-in.");let B=Boolean(Z.claustrum);if(!B&&!Z.login&&!Z.noClaustrum&&!j&&$.claustrum.available&&E(J)){let q=await v(J,[{label:"No",value:!1},{label:"Yes",value:!0}],{message:"Connect these hosts to the Claustrum vault?"});if(q===null)return Y(J,"Setup cancelled. Nothing was changed."),{hosts:[],dryRun:Z.dryRun,mode:"local",detection:$};B=q===!0}let F=B?"claustrum":"local",k=Q.includes("opencode")?r(G,D,z):[];if(Z.dryRun){Y(J,"Dry run: no registrations, enrollment, sign-in or migration will be performed.");for(let q of Q){if(G.beforeSignIn)Y(J,`Would run beforeSignIn(${q}, ${F}).`);if(B){let O=L(G.vault.hosts[q].paths);Y(J,`Would Connect ${q}: write ${O.statePath} and ${O.tokenPath}; wait for ck auth enroll approve.`)}else Y(J,`Would sign in locally for ${q}.`);if(G.beforeRegister)Y(J,`Would run beforeRegister(${q}, ${F}).`)}for(let q of k)Y(J,`${q.changed?"Would write":"Unchanged"} ${q.path}:
|
|
12
|
+
${q.content}`);if(Q.includes("pi"))Y(J,`Would run ${$.pi.executable} install npm:${G.packages.pi}@${G.version}`);for(let q of Q)Y(J,`Would migrate ${q} using the plugin callback (provider-specific writes).`)}else{let q={opencodeGeneration:D,mode:F,hosts:Object.freeze([...Q]),piAgentDir:$.pi.directory},O=new Map;try{for(let M of Q){if(await X(),await G.beforeSignIn?.(M,q),await X(),B){O.set(M,"unknown");try{await Y1(G,M,z,J,X)}catch(C){if(C instanceof A)O.set(M,"not-enrolled");throw C}O.set(M,"enrolled")}else await G.signInLocal(M,q);if(await X(),await G.beforeRegister?.(M,F,q),await X(),M==="opencode")await n(k,X);else await o(G,$.pi.executable,z);await X(),await G.migrate(M,q)}}catch(M){if(O.size===0)throw M;try{let C=await E0(G,Q,O);J1(M,C);for(let m1 of C)Y(J,z1(m1))}catch{}throw M}}return Y(J,`${Z.dryRun?"Planned":"Configured"} ${G.displayName} for ${Q.join(", ")} (${F}).`),Y(J,`Next: ${Q.includes("opencode")?"start OpenCode":"start Pi"} and run ${G.slashCommand}.`),{hosts:Q,dryRun:Z.dryRun,mode:F,detection:$}}import{basename as c0}from"node:path";import{resolveClaustrumConnectionPath as u0}from"@cortexkit/claustrum-client";var A1={name:"@cortexkit/pi-openai-auth",version:"1.6.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.26.0","@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 g0}from"node:os";import{join as _1}from"node:path";function m0(){return process.env.PI_AGENT_DIR?.trim()||_1(g0(),".pi","agent")}function T1(){return process.env.PI_OPENAI_AUTH_FILE?.trim()||_1(m0(),w1)}function h0(G=T1()){return process.env.PI_OPENAI_AUTH_STATE_FILE?.trim()||I1(G)}function L1(G=T1()){return{configPath:G,statePath:h0(G)}}var y={name:"@cortexkit/opencode-openai-auth",version:"1.6.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.26.0","@cortexkit/openai-auth-core":"workspace:*","@opencode/plugin":"2.0.32"},dependencies:{"@cortexkit/claustrum-client":"^0.13.0","@cortexkit/private-files":"^0.2.1","@cortexkit/subc-client":"^0.22.0","@opentui/core":">=0.6.1","@opentui/solid":">=0.6.1",ai:"^7.0.143","jsonc-parser":"^3.3.1","solid-js":"1.9.12"}};function g1(G={}){let b=G.print??console.log,z=G.fence??S(),Z={opencode:{stateDir:e(v1().statePath),host:"opencode"},pi:{stateDir:e(L1().statePath),host:"pi"}},J=async($)=>{if(await d(L(Z[$]),f($))!=="local")throw Error(`${$} is enrolled in Claustrum or its enrollment is unreadable. Disconnect it from the vault before using local sign-in.`)};return{packages:{opencode:y.name,pi:A1.name},version:y.version,displayName:"OpenAI Auth",slashCommand:"/openai",vault:{connectionFile:u0(),hosts:{opencode:{name:f("opencode"),paths:Z.opencode},pi:{name:f("pi"),paths:Z.pi}}},async beforeRegister($,K){if(K==="claustrum"){if(b(`Allow this host to read OpenAI accounts with:
|
|
13
|
+
ck auth grant --principal enrolled:${f($)} --selector-kind category --selector ${S1.category} --operation read`),$==="opencode")b("Then run opencode auth login and choose ChatGPT accounts in the vault to activate vault routing without local sign-in.");return}await J($)},async signInLocal($,K){if(await J($),$==="pi"){b("Start Pi and run /login openai-codex to sign in with Pi itself.");return}if(K.opencodeGeneration!=="1"){let F=c0(w("opencode2",G.io)??w("opencode",G.io)??"opencode");b(`In OpenCode 2, run ${F} 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(E1(process.env))throw Error("Unset OPENCODE_AUTH_CONTENT before local setup sign-in.");let W=f1(),j={path:{id:"openai"}};if(await W.get(j)!==void 0){b("OpenCode already has an OpenAI login. Use opencode auth login to change it.");return}let Q=G.beginLogin??y1,D=new AbortController,U=Boolean(process.env.SSH_CONNECTION||process.env.SSH_TTY||process.platform==="linux"&&!process.env.DISPLAY&&!process.env.WAYLAND_DISPLAY),V={version:y.version,signal:D.signal},x,X=!U;try{x=await Q({...V,headless:U})}catch(F){if(U)throw F;X=!1,b("Browser callback unavailable; using device-code sign-in."),x=await Q({version:y.version,headless:!0})}if(X){if(!(G.openBrowser??P1)(x.url))D.abort(),await x.completion.catch(()=>{}),b("Browser unavailable; using device-code sign-in."),x=await Q({version:y.version,headless:!0})}b(`${x.url}
|
|
14
|
+
${x.instructions}`);let B=await x.completion;await P(z),await J($),await W.set({...j,body:{type:"oauth",access:B.access,refresh:B.refresh,expires:B.expires,...B.accountId?{accountId:B.accountId}:{}}}),b("Signed in to OpenCode. The first plugin start adopts this login into the account pool.")},async migrate($){b(`${$}: 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 t(g1(),process.argv.slice(3))}catch(G){console.error(G instanceof Error?G.message:String(G)),process.exitCode=1}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { a as KnobValues, c as PluginExtraSection, i as CommandInvocation, l as PluginSection, o as MenuKnob, t as CommandApplyRequest } from "./model-
|
|
2
|
-
import { _t as QuotaMap } from "./sidebar-state-
|
|
1
|
+
import { a as KnobValues, c as PluginExtraSection, i as CommandInvocation, l as PluginSection, o as MenuKnob, t as CommandApplyRequest } from "./model-D22uj0OB.js";
|
|
2
|
+
import { _t as QuotaMap } from "./sidebar-state-Bb9L9oPq.js";
|
|
3
3
|
import { ClaustrumClient, EnrollmentPollOutcome } from "@cortexkit/claustrum-client";
|
|
4
4
|
import "@cortexkit/private-files";
|
|
5
|
-
//#region ../../node_modules/.bun/@cortexkit+common-auth@0.
|
|
5
|
+
//#region ../../node_modules/.bun/@cortexkit+common-auth@0.26.0+edd79cef82a5b402/node_modules/@cortexkit/common-auth/dist/store/schema.d.ts
|
|
6
6
|
type OAuthCredential = {
|
|
7
7
|
type: 'oauth';
|
|
8
8
|
access?: string;
|
|
@@ -191,7 +191,7 @@ interface PoolRow {
|
|
|
191
191
|
unbound?: true;
|
|
192
192
|
}
|
|
193
193
|
//#endregion
|
|
194
|
-
//#region ../../node_modules/.bun/@cortexkit+common-auth@0.
|
|
194
|
+
//#region ../../node_modules/.bun/@cortexkit+common-auth@0.26.0+edd79cef82a5b402/node_modules/@cortexkit/common-auth/dist/store/errors.d.ts
|
|
195
195
|
/** Every library operation that can fail, as named in the failure value. */
|
|
196
196
|
type PoolOperation = 'initialize' | 'add' | 'replace' | 'rotate' | 'disable' | 'enable' | 'remove' | 'reorder' | 'updateSettings' | 'recordIdentity' | 'updateProviderState' | 'refresh' | 'pull' | 'publishRoster';
|
|
197
197
|
/**
|
|
@@ -238,12 +238,12 @@ declare class PoolOperationError extends Error {
|
|
|
238
238
|
});
|
|
239
239
|
}
|
|
240
240
|
//#endregion
|
|
241
|
-
//#region ../../node_modules/.bun/@cortexkit+common-auth@0.
|
|
241
|
+
//#region ../../node_modules/.bun/@cortexkit+common-auth@0.26.0+edd79cef82a5b402/node_modules/@cortexkit/common-auth/dist/store/hooks.d.ts
|
|
242
242
|
interface PoolLogger {
|
|
243
243
|
warn(message: string, data?: unknown): void;
|
|
244
244
|
}
|
|
245
245
|
//#endregion
|
|
246
|
-
//#region ../../node_modules/.bun/@cortexkit+common-auth@0.
|
|
246
|
+
//#region ../../node_modules/.bun/@cortexkit+common-auth@0.26.0+edd79cef82a5b402/node_modules/@cortexkit/common-auth/dist/fs/refresh-file-lock.d.ts
|
|
247
247
|
interface LockLoss {
|
|
248
248
|
readonly reason: 'taken-over' | 'expired' | 'unreadable' | 'renewal-failed' | 'marker-lost';
|
|
249
249
|
readonly expectedOwnerId: string;
|
|
@@ -278,7 +278,7 @@ type RefreshFileLockOptions = {
|
|
|
278
278
|
/** Filesystem leases share wall time across all callers and processes. */
|
|
279
279
|
declare function acquireRefreshFileLock(options: RefreshFileLockOptions): Promise<RefreshFileLock | null>;
|
|
280
280
|
//#endregion
|
|
281
|
-
//#region ../../node_modules/.bun/@cortexkit+common-auth@0.
|
|
281
|
+
//#region ../../node_modules/.bun/@cortexkit+common-auth@0.26.0+edd79cef82a5b402/node_modules/@cortexkit/common-auth/dist/store/refresh-lock.d.ts
|
|
282
282
|
type LockStep = NonNullable<Parameters<typeof acquireRefreshFileLock>[0]['onStep']> extends ((step: infer S) => unknown) ? S : never;
|
|
283
283
|
/** Tuning shared by every lock the store takes; each field is overridable. */
|
|
284
284
|
interface PoolLockOptions {
|
|
@@ -310,7 +310,7 @@ interface LockEnvironment {
|
|
|
310
310
|
}, event: 'scheduled' | 'cancelled') => void;
|
|
311
311
|
}
|
|
312
312
|
//#endregion
|
|
313
|
-
//#region ../../node_modules/.bun/@cortexkit+common-auth@0.
|
|
313
|
+
//#region ../../node_modules/.bun/@cortexkit+common-auth@0.26.0+edd79cef82a5b402/node_modules/@cortexkit/common-auth/dist/store/mutate.d.ts
|
|
314
314
|
/** Named points on the write path, for crash and ownership injection. */
|
|
315
315
|
type WriteStep = 'before-config-write' | 'after-config-write' | 'before-state-write' | 'after-state-write';
|
|
316
316
|
/** Awaitable pause points on the pull and refresh paths. */
|
|
@@ -345,11 +345,11 @@ interface StoreContext {
|
|
|
345
345
|
/** What `initializePool` did. */
|
|
346
346
|
type InitializeOutcome = 'initialized' | 'already-ready';
|
|
347
347
|
//#endregion
|
|
348
|
-
//#region ../../node_modules/.bun/@cortexkit+common-auth@0.
|
|
348
|
+
//#region ../../node_modules/.bun/@cortexkit+common-auth@0.26.0+edd79cef82a5b402/node_modules/@cortexkit/common-auth/dist/store/runtime.d.ts
|
|
349
349
|
/** Where a pull was fired from; `load` fires at most once per process per row. */
|
|
350
350
|
type PullReason = 'load' | 'add' | 'replace' | 'admission';
|
|
351
351
|
//#endregion
|
|
352
|
-
//#region ../../node_modules/.bun/@cortexkit+common-auth@0.
|
|
352
|
+
//#region ../../node_modules/.bun/@cortexkit+common-auth@0.26.0+edd79cef82a5b402/node_modules/@cortexkit/common-auth/dist/store/attribution.d.ts
|
|
353
353
|
/**
|
|
354
354
|
* What a pull or refresh captured about its row (named by id alongside) when
|
|
355
355
|
* it was issued. A result applies only while the row with that id still has
|
|
@@ -372,7 +372,7 @@ interface Attribution {
|
|
|
372
372
|
identity?: string;
|
|
373
373
|
}
|
|
374
374
|
//#endregion
|
|
375
|
-
//#region ../../node_modules/.bun/@cortexkit+common-auth@0.
|
|
375
|
+
//#region ../../node_modules/.bun/@cortexkit+common-auth@0.26.0+edd79cef82a5b402/node_modules/@cortexkit/common-auth/dist/store/rows.d.ts
|
|
376
376
|
type FailureHook = (rowId: string, error: PoolOperationError) => void | Promise<void>;
|
|
377
377
|
interface RowOperationOptions {
|
|
378
378
|
/** Called once, awaited, on every non-success path, before locks release. */
|
|
@@ -588,7 +588,7 @@ interface RowTransitionResult {
|
|
|
588
588
|
providerState?: unknown;
|
|
589
589
|
}
|
|
590
590
|
//#endregion
|
|
591
|
-
//#region ../../node_modules/.bun/@cortexkit+common-auth@0.
|
|
591
|
+
//#region ../../node_modules/.bun/@cortexkit+common-auth@0.26.0+edd79cef82a5b402/node_modules/@cortexkit/common-auth/dist/store/provider-state.d.ts
|
|
592
592
|
/**
|
|
593
593
|
* Receives a private copy of the row's provider state (undefined when the row
|
|
594
594
|
* shows none) and the row as loaded under the locks, and returns the next
|
|
@@ -624,7 +624,7 @@ declare const DECLINE_TRANSITION: unique symbol;
|
|
|
624
624
|
*/
|
|
625
625
|
type RowTransitionMutator = (current: unknown | undefined, row: PoolRow) => unknown | typeof DECLINE_TRANSITION | Promise<unknown | typeof DECLINE_TRANSITION>;
|
|
626
626
|
//#endregion
|
|
627
|
-
//#region ../../node_modules/.bun/@cortexkit+common-auth@0.
|
|
627
|
+
//#region ../../node_modules/.bun/@cortexkit+common-auth@0.26.0+edd79cef82a5b402/node_modules/@cortexkit/common-auth/dist/store/publication.d.ts
|
|
628
628
|
interface PublishPlan {
|
|
629
629
|
operationId: string;
|
|
630
630
|
remove: Array<{
|
|
@@ -667,7 +667,7 @@ interface PublishResult {
|
|
|
667
667
|
receipt: PublicationReceipt;
|
|
668
668
|
}
|
|
669
669
|
//#endregion
|
|
670
|
-
//#region ../../node_modules/.bun/@cortexkit+common-auth@0.
|
|
670
|
+
//#region ../../node_modules/.bun/@cortexkit+common-auth@0.26.0+edd79cef82a5b402/node_modules/@cortexkit/common-auth/dist/store/pull.d.ts
|
|
671
671
|
/** What a pull is issued with: the credential and its attribution tuple. */
|
|
672
672
|
interface PullRequest {
|
|
673
673
|
id: string;
|
|
@@ -678,7 +678,7 @@ interface PullRequest {
|
|
|
678
678
|
}
|
|
679
679
|
type PullHook = (request: PullRequest) => Promise<unknown>;
|
|
680
680
|
//#endregion
|
|
681
|
-
//#region ../../node_modules/.bun/@cortexkit+common-auth@0.
|
|
681
|
+
//#region ../../node_modules/.bun/@cortexkit+common-auth@0.26.0+edd79cef82a5b402/node_modules/@cortexkit/common-auth/dist/store/refresh.d.ts
|
|
682
682
|
/** What the injected provider refresh function returns. */
|
|
683
683
|
interface ProviderRefreshResult {
|
|
684
684
|
access: string;
|
|
@@ -741,7 +741,7 @@ type RefreshOutcome = {
|
|
|
741
741
|
reason: string;
|
|
742
742
|
};
|
|
743
743
|
//#endregion
|
|
744
|
-
//#region ../../node_modules/.bun/@cortexkit+common-auth@0.
|
|
744
|
+
//#region ../../node_modules/.bun/@cortexkit+common-auth@0.26.0+edd79cef82a5b402/node_modules/@cortexkit/common-auth/dist/store/settings.d.ts
|
|
745
745
|
/** The plugin's settings: every top-level config key except the pool-owned ones. */
|
|
746
746
|
type PoolSettings = Record<string, unknown>;
|
|
747
747
|
type SettingsRead = {
|
|
@@ -785,13 +785,26 @@ type UpdateSettingsResult = {
|
|
|
785
785
|
outcome: 'updated' | 'unchanged';
|
|
786
786
|
};
|
|
787
787
|
//#endregion
|
|
788
|
-
//#region ../../node_modules/.bun/@cortexkit+common-auth@0.
|
|
788
|
+
//#region ../../node_modules/.bun/@cortexkit+common-auth@0.26.0+edd79cef82a5b402/node_modules/@cortexkit/common-auth/dist/store/pool.d.ts
|
|
789
789
|
interface OpenPoolStoreOptions {
|
|
790
790
|
/** The provider every row of this pool belongs to; keys the provider-wide lock. */
|
|
791
791
|
provider: string;
|
|
792
792
|
configPath: string;
|
|
793
793
|
statePath: string;
|
|
794
794
|
quota: QuotaCodec;
|
|
795
|
+
/**
|
|
796
|
+
* Opt in to detached, coalesced quota publication, with any `quota` codec.
|
|
797
|
+
* Each accepted observation is queued whole for its row and binding, and
|
|
798
|
+
* the queue is applied in arrival order through `quota.merge` under the
|
|
799
|
+
* store locks, so the codec's own merge decides which fields a newer or
|
|
800
|
+
* older reading replaces. Accepted readings appear in read/load
|
|
801
|
+
* immediately, merged the same way; the returned promise still rejects
|
|
802
|
+
* current-row refusals before queueing. Await dispose or close at shutdown
|
|
803
|
+
* to drain.
|
|
804
|
+
*/
|
|
805
|
+
coalesceQuota?: boolean;
|
|
806
|
+
/** Bounded quota drain on close/dispose, in milliseconds; defaults to 1,000. */
|
|
807
|
+
quotaDrainTimeoutMs?: number;
|
|
795
808
|
/**
|
|
796
809
|
* The codec of the provider state kept beside each row's credential (see
|
|
797
810
|
* `ProviderStateCodec`). Without it no row shows a provider state, and
|
|
@@ -965,19 +978,23 @@ interface PoolStore {
|
|
|
965
978
|
}>;
|
|
966
979
|
refresh(id: string, provider: ProviderRefresh, options?: RefreshOptions): Promise<RefreshOutcome>;
|
|
967
980
|
recordQuota(id: string, attribution: Attribution, observation: unknown): Promise<void>;
|
|
981
|
+
/** Drain opted-in quota publication; subsequent coalesced readings refuse. Idempotent. */
|
|
982
|
+
close(): Promise<void>;
|
|
983
|
+
/** Same bounded quota drain as close(). Does not wait for provider pull hooks. */
|
|
984
|
+
dispose(): Promise<void>;
|
|
968
985
|
/** Fires a pull for a row admission refused for want of a reading. */
|
|
969
986
|
requestReading(id: string): void;
|
|
970
987
|
/** Resolves once every pull fired so far has settled. */
|
|
971
988
|
pullsSettled(): Promise<void>;
|
|
972
989
|
}
|
|
973
990
|
//#endregion
|
|
974
|
-
//#region ../../node_modules/.bun/@cortexkit+common-auth@0.
|
|
991
|
+
//#region ../../node_modules/.bun/@cortexkit+common-auth@0.26.0+edd79cef82a5b402/node_modules/@cortexkit/common-auth/dist/commands/seam.d.ts
|
|
975
992
|
/** Where a dropped field is reported. Names only, never values. */
|
|
976
993
|
interface SeamLogger {
|
|
977
994
|
warn(message: string, data?: unknown): void;
|
|
978
995
|
}
|
|
979
996
|
//#endregion
|
|
980
|
-
//#region ../../node_modules/.bun/@cortexkit+common-auth@0.
|
|
997
|
+
//#region ../../node_modules/.bun/@cortexkit+common-auth@0.26.0+edd79cef82a5b402/node_modules/@cortexkit/common-auth/dist/commands/builtins.d.ts
|
|
981
998
|
/**
|
|
982
999
|
* What a plugin's login hands back. `ready` adds the account now. `pending`
|
|
983
1000
|
* means the user must finish somewhere else (a browser, a device code):
|
|
@@ -1097,7 +1114,7 @@ interface BeginAccountLoginResult {
|
|
|
1097
1114
|
*/
|
|
1098
1115
|
declare function beginAccountLogin(opts: BeginAccountLoginOptions): Promise<BeginAccountLoginResult>;
|
|
1099
1116
|
//#endregion
|
|
1100
|
-
//#region ../../node_modules/.bun/@cortexkit+common-auth@0.
|
|
1117
|
+
//#region ../../node_modules/.bun/@cortexkit+common-auth@0.26.0+edd79cef82a5b402/node_modules/@cortexkit/common-auth/dist/claustrum/watch.d.ts
|
|
1101
1118
|
/**
|
|
1102
1119
|
* How a host currently learns about changes, for logs and status displays.
|
|
1103
1120
|
* `watching`: a watch was accepted and is open, so polling is reduced to a
|
|
@@ -1151,7 +1168,7 @@ interface ScopedWatchSource {
|
|
|
1151
1168
|
}): ScopedWatchHandle;
|
|
1152
1169
|
}
|
|
1153
1170
|
//#endregion
|
|
1154
|
-
//#region ../../node_modules/.bun/@cortexkit+common-auth@0.
|
|
1171
|
+
//#region ../../node_modules/.bun/@cortexkit+common-auth@0.26.0+edd79cef82a5b402/node_modules/@cortexkit/common-auth/dist/claustrum/insula.d.ts
|
|
1155
1172
|
/**
|
|
1156
1173
|
* A held-open `usage.watch` stream. `closed` resolves when insula ends the
|
|
1157
1174
|
* stream (STREAM_END at shutdown, or a reply that ends it) or after `stop()`,
|
|
@@ -1175,7 +1192,7 @@ interface InsulaUsageTransport {
|
|
|
1175
1192
|
watchUsage?(onNotice: (body: Uint8Array) => void): InsulaUsageWatch;
|
|
1176
1193
|
}
|
|
1177
1194
|
//#endregion
|
|
1178
|
-
//#region ../../node_modules/.bun/@cortexkit+common-auth@0.
|
|
1195
|
+
//#region ../../node_modules/.bun/@cortexkit+common-auth@0.26.0+edd79cef82a5b402/node_modules/@cortexkit/common-auth/dist/claustrum/custody.d.ts
|
|
1179
1196
|
/**
|
|
1180
1197
|
* `watchScoped` is present from claustrum-client 0.12.0. Hosts detect it at
|
|
1181
1198
|
* run time and keep polling without it.
|
|
@@ -1280,7 +1297,7 @@ interface KeptReceiptState {
|
|
|
1280
1297
|
readonly since: number | null;
|
|
1281
1298
|
}
|
|
1282
1299
|
//#endregion
|
|
1283
|
-
//#region ../../node_modules/.bun/@cortexkit+common-auth@0.
|
|
1300
|
+
//#region ../../node_modules/.bun/@cortexkit+common-auth@0.26.0+edd79cef82a5b402/node_modules/@cortexkit/common-auth/dist/claustrum/interlock.d.ts
|
|
1284
1301
|
/**
|
|
1285
1302
|
* The declined-account interlock: the user's "do not use this vault account",
|
|
1286
1303
|
* kept on the consumer side because the vault has no notion of it.
|
|
@@ -1299,7 +1316,7 @@ interface DeclinedAccount {
|
|
|
1299
1316
|
readonly accountIdentity?: string;
|
|
1300
1317
|
}
|
|
1301
1318
|
//#endregion
|
|
1302
|
-
//#region ../../node_modules/.bun/@cortexkit+common-auth@0.
|
|
1319
|
+
//#region ../../node_modules/.bun/@cortexkit+common-auth@0.26.0+edd79cef82a5b402/node_modules/@cortexkit/common-auth/dist/claustrum/roster.d.ts
|
|
1303
1320
|
/**
|
|
1304
1321
|
* One vault account as the pool sees it. It carries no bearer material: the
|
|
1305
1322
|
* access token is fetched from the vault for every send. Several vault
|
|
@@ -1360,7 +1377,7 @@ interface ReorderVaultRosterResult {
|
|
|
1360
1377
|
*/
|
|
1361
1378
|
type QuotaReceipt = Pick<ClaustrumScopedAttempt, 'credentialId' | 'accountIdentity' | 'accountIdentitySource' | 'expectedAccountIdentity'>;
|
|
1362
1379
|
//#endregion
|
|
1363
|
-
//#region ../../node_modules/.bun/@cortexkit+common-auth@0.
|
|
1380
|
+
//#region ../../node_modules/.bun/@cortexkit+common-auth@0.26.0+edd79cef82a5b402/node_modules/@cortexkit/common-auth/dist/claustrum/consumer.d.ts
|
|
1364
1381
|
/**
|
|
1365
1382
|
* How a started consumer learns about changes, for logs and status displays.
|
|
1366
1383
|
* `insula` is present when the consumer was given an insula source. Never
|
|
@@ -1371,7 +1388,7 @@ interface ClaustrumWatchState {
|
|
|
1371
1388
|
readonly insula?: WatchMode;
|
|
1372
1389
|
}
|
|
1373
1390
|
//#endregion
|
|
1374
|
-
//#region ../../node_modules/.bun/@cortexkit+common-auth@0.
|
|
1391
|
+
//#region ../../node_modules/.bun/@cortexkit+common-auth@0.26.0+edd79cef82a5b402/node_modules/@cortexkit/common-auth/dist/claustrum/enrollment.d.ts
|
|
1375
1392
|
interface ClaustrumEnrollmentClient {
|
|
1376
1393
|
enrollPropose(input: {
|
|
1377
1394
|
name: string;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{Ac as NZ,Bc as PZ,Dc as g,Ec as WZ,Fc as HZ,Ic as d,ce as _Z,fe as TZ,he as RZ}from"./index-6fdmqk6p.js";import{pe as XZ,te as VZ,ue as YZ,ve as y,we as x}from"./index-3y453wg4.js";import{Ne as OZ}from"./index-mhfja8yr.js";import{$e as JZ,Ve as b,We as $Z,_e as A}from"./index-2yszc75z.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 S0(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 f0(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,m.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(!m.has($))m.add($),z0($,FZ);return $}var m=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 f(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}:{}}}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 f(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 SZ(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 fZ(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 p=Promise.resolve();function _(Z){let $=p.then(Z);return p=$.catch(()=>{}),$}var KZ=new Map;function a(Z){let $=KZ.get(Z);if(!$)$=k({path:Z,defaultValue:q,normalize:f,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(f(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 f(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 S(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=S(Z,J),G=S($,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[S(Y),S(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}},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 mZ(Z,$){let V=T($.sessionId),J=new Set($.validPinnedAccountIds),X=new Set($.excludeAccountIds),Y=I(Z.stickyAssignments,J,$.now),G=!fZ(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:SZ({...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=mZ(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 mZ(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(fZ(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:SZ({...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 p}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 pZ(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=pZ(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=pZ(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
|
|
1
|
+
import{Bc as NZ,Cc as PZ,Ec as g,Fc as WZ,Gc as HZ,Jc as d,de as _Z,ge as TZ,ie as RZ}from"./index-ge60xry3.js";import{qe as XZ,ue as VZ,ve as YZ,we as y,xe as x}from"./index-8xq099qf.js";import{Oe as OZ}from"./index-b0ty9qam.js";import{$e as A,We as b,Xe as $Z,af as JZ}from"./index-7nmdsmpp.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 S0(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 f0(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,m.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(!m.has($))m.add($),z0($,FZ);return $}var m=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 f(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}:{}}}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 f(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 SZ(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 fZ(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 p=Promise.resolve();function _(Z){let $=p.then(Z);return p=$.catch(()=>{}),$}var KZ=new Map;function a(Z){let $=KZ.get(Z);if(!$)$=k({path:Z,defaultValue:q,normalize:f,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(f(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 f(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 S(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=S(Z,J),G=S($,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[S(Y),S(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}},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 mZ(Z,$){let V=T($.sessionId),J=new Set($.validPinnedAccountIds),X=new Set($.excludeAccountIds),Y=I(Z.stickyAssignments,J,$.now),G=!fZ(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:SZ({...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=mZ(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 mZ(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(fZ(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:SZ({...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 p}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 pZ(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=pZ(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=pZ(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 Gb,S0 as Hb,rZ as Ib,f0 as Jb,g0 as Kb,u as Lb,MZ as Mb,T as Nb,O as Ob,q as Pb,f as Qb,G0 as Rb,K0 as Sb,GZ as Tb,IZ as Ub,bZ as Vb,xZ as Wb,E as Xb,j0 as Yb,d0 as Zb,vZ as _b,I as $b,l0 as ac,u0 as bc,r0 as cc,c0 as dc,o0 as ec,mZ as fc,a0 as gc,i0 as hc,s0 as ic,n0 as jc,e0 as kc,D0 as lc,N0 as mc,t0 as nc,Z1 as oc,$1 as pc,J1 as qc,P0 as rc,pZ as sc,X1 as tc,V1 as uc,DZ as vc,Y1 as wc,z1 as xc};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Cb as X,Eb as V}from"./index-k5anexvs.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};
|