@cortexkit/opencode-openai-auth 1.8.0 → 1.8.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.
Files changed (49) hide show
  1. package/dist/bin.js +2 -2
  2. package/dist/{codex-request-DohnbsFR.d.ts → codex-request-GJkvxv4S.d.ts} +3 -57
  3. package/dist/{index-th47aqez.js → index-21yxzeet.js} +2 -2
  4. package/dist/index-4rf3rkdm.js +2 -0
  5. package/dist/{index-8pk9savd.js → index-73z9ftrg.js} +2 -2
  6. package/dist/{index-g3d50jz0.js → index-97cz7kyq.js} +10 -10
  7. package/dist/index-b7p76qqa.js +91 -0
  8. package/dist/{index-dtwgf694.js → index-c50p5mem.js} +1 -1
  9. package/dist/{index-cxstwq02.js → index-fhcnxrtz.js} +1 -1
  10. package/dist/{index-5d4y47h8.js → index-h1r8cbet.js} +2 -2
  11. package/dist/{index-x7jzcvqy.js → index-hpnj460b.js} +1 -1
  12. package/dist/{index-5dxpsa3t.js → index-mg4w434p.js} +2 -2
  13. package/dist/{index-cbcka7sa.js → index-p8m4yh73.js} +1 -1
  14. package/dist/index-vh1sr50d.js +63 -0
  15. package/dist/{index-dzaqj248.js → index-ww8w9edq.js} +2 -2
  16. package/dist/index.d.ts +2 -12
  17. package/dist/index.js +1 -1
  18. package/dist/{port-file-DQ7-ItDK.d.ts → port-file-DXCxv8tU.d.ts} +0 -2
  19. package/dist/{protocol-CVQK-d3j.d.ts → protocol-BZZtDn5h.d.ts} +0 -4
  20. package/dist/rpc/port-file.d.ts +1 -3
  21. package/dist/rpc/port-file.js +1 -1
  22. package/dist/rpc/protocol.d.ts +1 -1
  23. package/dist/rpc/protocol.js +1 -1
  24. package/dist/rpc/rpc-client.d.ts +1 -1
  25. package/dist/rpc/rpc-client.js +1 -1
  26. package/dist/rpc/rpc-dir.d.ts +0 -2
  27. package/dist/rpc/rpc-dir.js +1 -1
  28. package/dist/{rpc-client-BQfIKrXI.d.ts → rpc-client-CmaZW1by.d.ts} +2 -6
  29. package/dist/{sidebar-state-B1cq68UB.d.ts → sidebar-state-DkNebAiC.d.ts} +3 -11
  30. package/dist/sidebar-state.d.ts +1 -1
  31. package/dist/sidebar-state.js +1 -1
  32. package/dist/{token-gy442bba.js → token-3vtr29vt.js} +1 -1
  33. package/dist/token-util-erhrf24m.js +1 -0
  34. package/dist/tui-preferences.d.ts +0 -2
  35. package/dist/tui-preferences.js +1 -1
  36. package/dist/tui.d.ts +3 -7
  37. package/dist/v2/server.d.ts +2 -18
  38. package/dist/v2/server.js +2 -2
  39. package/package.json +5 -5
  40. package/src/tui-compiled/raw/shared/dbc61cd405941828-accounts.js +42 -0
  41. package/src/tui-compiled/raw/sidebar-state.js +4 -2
  42. package/src/tui-compiled/raw/tui.tsx +7 -1
  43. package/src/tui-compiled/runtime/shared/dbc61cd405941828-accounts.js +42 -0
  44. package/src/tui-compiled/runtime/sidebar-state.js +4 -2
  45. package/src/tui-compiled/runtime/tui.js +4 -1
  46. package/dist/index-3v868rnp.js +0 -63
  47. package/dist/index-n7fxqgfb.js +0 -2
  48. package/dist/index-tvban5vp.js +0 -91
  49. package/dist/token-util-rxy0p234.js +0 -1
package/dist/bin.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{c as m0}from"./index-cxstwq02.js";import{Aa as f,Ba as B,Ca as E,Kb as u0,gb as h0,na as f0,oa as S,pa as G0,yb as d0,za as A0}from"./index-g3d50jz0.js";import{md as y0,sd as V0,ud as d,vd as w,wd as E0,xd as m,yd as U0}from"./index-tvban5vp.js";import"./index-8pk9savd.js";import"./index-dzaqj248.js";import"./index-th47aqez.js";import{Xe as J0,bf as w0,df as L0,gf as g0}from"./index-5d4y47h8.js";import"./index-5dxpsa3t.js";import"./index-dtwgf694.js";import"./index-x7jzcvqy.js";import{spawn as l0}from"node:child_process";var k=4096,a0=1048576;class z0{buffer=Buffer.alloc(k);start=0;length=0;truncated=!1;get didTruncate(){return this.truncated}push(G){if(G.length>=k){if(G.length>k||this.length>0)this.truncated=!0;G.copy(this.buffer,0,G.length-k),this.start=0,this.length=k;return}let z=Math.max(0,this.length+G.length-k);if(z>0)this.truncated=!0;this.start=(this.start+z)%k,this.length-=z;let J=(this.start+this.length)%k,Z=Math.min(G.length,k-J);if(G.copy(this.buffer,J,0,Z),Z<G.length)G.copy(this.buffer,0,Z);this.length+=G.length}toString(){let G=Buffer.alloc(this.length),z=Math.min(this.length,k-this.start);if(this.buffer.copy(G,0,this.start,this.start+z),z<this.length)this.buffer.copy(G,z,0,this.length-z);let J=0;while(J<G.length){let Z=G[J];if(Z===void 0||(Z&192)!==128)break;J++}return G.subarray(J).toString("utf8")}}var T={run(G,z,J={}){return new Promise((Z)=>{let $=performance.now(),Q=J.timeoutMs??15000,K=new z0,D=[],j=0,q=!1,x=!1,X=!1,V;try{V=l0(G,[...z],{env:J.env??process.env,windowsHide:!0,windowsVerbatimArguments:J.windowsVerbatimArguments,stdio:["ignore","pipe","pipe"]})}catch{Z({exitCode:1,stdout:"",stderr:"",spawnError:!0,signal:null,timedOut:!1,durationMs:performance.now()-$});return}let W=Q>0?setTimeout(()=>{X=!0,V.kill("SIGTERM")},Q):void 0;V.stdout?.on("data",(Y)=>{let C=a0-j,b=Math.min(C,Y.length);if(b>0)D.push(Y.subarray(0,b)),j+=b;if(Y.length>C)q=!0,V.kill("SIGTERM")}),V.stderr?.on("data",(Y)=>K.push(Y));let U=!1,F=(Y,C)=>{if(U)return;if(U=!0,W)clearTimeout(W);Z({exitCode:x?1:q?1:Y??1,stdout:Buffer.concat(D,j).toString("utf8"),stderr:K.toString(),stderrTruncated:K.didTruncate,...x?{spawnError:!0}:{},signal:C??null,timedOut:X,durationMs:performance.now()-$})};V.once("error",()=>{if(x=!0,V.pid===void 0)F(null,null)}),V.once("close",(Y,C)=>F(Y,C))})}};function g(G,z,J,Z,$,Q=15000){if(z==="win32"&&/\.(cmd|bat)$/i.test(J)){if(/["%!\r\n]/.test(J)||Z.some((K)=>!/^[a-zA-Z0-9@:/._+-]+$/.test(K)))throw Error("Unsafe batch launcher or argument; use an executable instead.");return G.run("cmd.exe",["/d","/s","/c",`""${J}" ${Z.join(" ")}"`],{env:$,timeoutMs:Q,windowsVerbatimArguments:!0})}return G.run(J,Z,{env:$,timeoutMs:Q})}var i0="Pi install failed; run pi install after checking your npm connection.";function s0(G){let z=Buffer.from(G,"utf8");if(z.length<=k)return G;let J=z.length-k;while(J<z.length){let Z=z[J];if(Z===void 0||(Z&192)!==128)break;J++}return z.subarray(J).toString("utf8")}function r0(G){let z=G.indexOf(`
2
+ import{c as m0}from"./index-fhcnxrtz.js";import{Aa as f,Ba as B,Ca as E,Kb as u0,gb as h0,na as f0,oa as S,pa as G0,yb as d0,za as A0}from"./index-97cz7kyq.js";import{md as y0,sd as V0,ud as d,vd as w,wd as E0,xd as m,yd as U0}from"./index-b7p76qqa.js";import"./index-73z9ftrg.js";import"./index-ww8w9edq.js";import"./index-21yxzeet.js";import{Ye as J0,cf as w0,ef as L0,hf as g0}from"./index-h1r8cbet.js";import"./index-mg4w434p.js";import"./index-c50p5mem.js";import"./index-hpnj460b.js";import{spawn as l0}from"node:child_process";var k=4096,a0=1048576;class z0{buffer=Buffer.alloc(k);start=0;length=0;truncated=!1;get didTruncate(){return this.truncated}push(G){if(G.length>=k){if(G.length>k||this.length>0)this.truncated=!0;G.copy(this.buffer,0,G.length-k),this.start=0,this.length=k;return}let z=Math.max(0,this.length+G.length-k);if(z>0)this.truncated=!0;this.start=(this.start+z)%k,this.length-=z;let J=(this.start+this.length)%k,Z=Math.min(G.length,k-J);if(G.copy(this.buffer,J,0,Z),Z<G.length)G.copy(this.buffer,0,Z);this.length+=G.length}toString(){let G=Buffer.alloc(this.length),z=Math.min(this.length,k-this.start);if(this.buffer.copy(G,0,this.start,this.start+z),z<this.length)this.buffer.copy(G,z,0,this.length-z);let J=0;while(J<G.length){let Z=G[J];if(Z===void 0||(Z&192)!==128)break;J++}return G.subarray(J).toString("utf8")}}var T={run(G,z,J={}){return new Promise((Z)=>{let $=performance.now(),Q=J.timeoutMs??15000,K=new z0,D=[],j=0,q=!1,x=!1,X=!1,V;try{V=l0(G,[...z],{env:J.env??process.env,windowsHide:!0,windowsVerbatimArguments:J.windowsVerbatimArguments,stdio:["ignore","pipe","pipe"]})}catch{Z({exitCode:1,stdout:"",stderr:"",spawnError:!0,signal:null,timedOut:!1,durationMs:performance.now()-$});return}let W=Q>0?setTimeout(()=>{X=!0,V.kill("SIGTERM")},Q):void 0;V.stdout?.on("data",(Y)=>{let C=a0-j,b=Math.min(C,Y.length);if(b>0)D.push(Y.subarray(0,b)),j+=b;if(Y.length>C)q=!0,V.kill("SIGTERM")}),V.stderr?.on("data",(Y)=>K.push(Y));let U=!1,F=(Y,C)=>{if(U)return;if(U=!0,W)clearTimeout(W);Z({exitCode:x?1:q?1:Y??1,stdout:Buffer.concat(D,j).toString("utf8"),stderr:K.toString(),stderrTruncated:K.didTruncate,...x?{spawnError:!0}:{},signal:C??null,timedOut:X,durationMs:performance.now()-$})};V.once("error",()=>{if(x=!0,V.pid===void 0)F(null,null)}),V.once("close",(Y,C)=>F(Y,C))})}};function g(G,z,J,Z,$,Q=15000){if(z==="win32"&&/\.(cmd|bat)$/i.test(J)){if(/["%!\r\n]/.test(J)||Z.some((K)=>!/^[a-zA-Z0-9@:/._+-]+$/.test(K)))throw Error("Unsafe batch launcher or argument; use an executable instead.");return G.run("cmd.exe",["/d","/s","/c",`""${J}" ${Z.join(" ")}"`],{env:$,timeoutMs:Q,windowsVerbatimArguments:!0})}return G.run(J,Z,{env:$,timeoutMs:Q})}var i0="Pi install failed; run pi install after checking your npm connection.";function s0(G){let z=Buffer.from(G,"utf8");if(z.length<=k)return G;let J=z.length-k;while(J<z.length){let Z=z[J];if(Z===void 0||(Z&192)!==128)break;J++}return z.subarray(J).toString("utf8")}function r0(G){let z=G.indexOf(`
3
3
  `);return z<0?"":G.slice(z+1)}class h extends Error{step="pi-install";exitCode;signal;stderrTail;constructor(G){super(i0);this.name="SetupCommandError",this.exitCode=G.exitCode,this.signal=G.signal;let z=G.stderrTruncated?r0(G.stderrTail):G.stderrTail,J=J0(z);this.stderrTail=s0(typeof J==="string"?J:"")}}var n0={opencode:"OpenCode",pi:"Pi"},o0={enrolled:"connected to the vault","not-enrolled":"not connected",unknown:"unknown, check with ck auth status"};function Z0({host:G,outcome:z}){return`${n0[G]}: ${o0[z]}`}var t0=new WeakMap;function $0(G,z){if(typeof G!=="object"&&typeof G!=="function"||!G)return;t0.set(G,Object.freeze(z.map((J)=>Object.freeze({...J}))))}import{accessSync as Z1,constants as $1,existsSync as Q1,readFileSync as K1,realpathSync as b1,statSync as q1}from"node:fs";import{mkdtemp as W1,rm as X1}from"node:fs/promises";import{tmpdir as D1}from"node:os";import{join as j1}from"node:path";import{parse as x1}from"jsonc-parser";import{homedir as e0}from"node:os";import{posix as G1,win32 as z1}from"node:path";import{fileURLToPath as J1}from"node:url";function N(G={}){let z=G.env??process.env,J=G.platform??process.platform,Z=J==="win32"?z1:G1,$=G.home??(J==="win32"?z.USERPROFILE:z.HOME)??e0(),Q=G.cwd??process.cwd(),K=(x)=>Z.resolve(Q,x),D=z.OPENCODE_CONFIG_DIR?.trim(),j=z.XDG_CONFIG_HOME?.trim(),q=z.PI_CODING_AGENT_DIR?.trim()||Z.join($,".pi","agent");if(q==="~")q=$;else if(/^~[/\\]/.test(q))q=Z.join($,q.slice(2));if(q.startsWith("file://"))q=J1(q);return{env:z,platform:J,path:Z,home:$,cwd:Q,opencode:D?K(D):j?Z.join(K(j),"opencode"):Z.join($,".config","opencode"),pi:K(q)}}function c(G,z){try{return q1(G)[z]()}catch{return!1}}var _={exists:Q1,isFile:(G)=>c(G,"isFile"),isDirectory:(G)=>c(G,"isDirectory"),isExecutable(G){try{return Z1(G,$1.X_OK),c(G,"isFile")}catch{return!1}},readText:(G)=>K1(G,"utf8"),realpath:b1};function I(G,z={}){let{env:J,platform:Z,path:$,cwd:Q}=N(z),K=z.fs??_,D=Object.entries(J).find(([q])=>Z==="win32"?q.toUpperCase()==="PATH":q==="PATH")?.[1]??"",j=Z==="win32"?[".exe",".cmd",".bat",""]:[""];for(let q of D.split(Z==="win32"?";":":")){let x=q.trim().replace(/^"|"$/g,"");if(!x)continue;for(let X of j){let V=$.resolve(Q,x,G+X);if(Z==="win32"?K.isFile(V):K.isExecutable(V))return V}}return null}function Q0(G={}){let{platform:z,home:J,env:Z,path:$}=N(G);if(z==="darwin")return["/Applications/OpenCode.app","/Applications/OpenCode Beta.app",$.join(J,"Applications","OpenCode.app"),$.join(J,"Applications","OpenCode Beta.app")];if(z==="win32"){let Q=Z.LOCALAPPDATA||$.join(J,"AppData","Local");return[$.join(Q,"Programs","opencode"),$.join(Q,"opencode")]}return["/opt/OpenCode","/usr/lib/opencode",$.join(J,".local","share","applications","opencode.desktop")]}function u(G,z){let J=z.fs??_,{path:Z}=N(z);try{let $=J.readText(G);if($.length>65536)return G;let Q=[...$.matchAll(/"%~?dp0%?\\([^"%\r\n]+)"/g)];if(!Q.length)Q.push(...$.matchAll(/"\$basedir\/([^"$\r\n]+)"/g));let K=Q.at(-1)?.[1];if(K){let D=Z.join(Z.dirname(G),...K.split(/[/\\]+/));if(J.isFile(D))return J.realpath(D)}return J.realpath(G)}catch{return G}}function V1(G,z){let J=z.fs??_,{path:Z}=N(z),$=Z.dirname(u(G,z));for(;;){try{let K=JSON.parse(J.readText(Z.join($,"package.json")));if(["@opencode/cli","@opencode-ai/cli"].includes(K.name))return"2";if(K.name==="opencode-ai")return/^(?:[2-9]\d*|1\d+)\.|^0\.0\.0-(?:beta|dev)-/.test(K.version??"")?"2":"1"}catch{}let Q=Z.dirname($);if(Q===$)return null;$=Q}}function K0(G={}){let z=I("opencode",G),J=I("opencode2",G),Z=z&&J&&u(z,G)===u(J,G),$=G.fs??_,{path:Q,opencode:K}=N(G),D="1";for(let q of["jsonc","json"]){let x=Q.join(K,`opencode.${q}`);if(!$.exists(x))continue;try{if(Object.hasOwn(x1($.readText(x))??{},"plugins"))D="2"}catch{}break}let j=z?V1(z,G)??(Z?"2":D):null;if(J&&j==="1"&&!Z)return"ambiguous";return J||Z?"2":j??D}async function p(G,z={}){let J=z.fs??_,{env:Z,platform:$,opencode:Q,pi:K}=N(z),D=z.runner??T,j=I("opencode",z)??I("opencode2",z),q=I("pi",z),x=I("ck",z),X=async(F)=>{if(!F)return null;let Y;try{Y=await W1(j1(D1(),"common-auth-setup-version-"));let C={...Z,HOME:Y,USERPROFILE:Y,XDG_CONFIG_HOME:Y,XDG_DATA_HOME:Y,XDG_STATE_HOME:Y,XDG_CACHE_HOME:Y,OPENCODE_CONFIG_DIR:Y,OPENCODE_CONFIG:void 0,OPENCODE_CONFIG_CONTENT:void 0,OPENCODE_AUTH_CONTENT:void 0,PI_CODING_AGENT_DIR:Y},b=await g(D,$,F,["--version"],C,2000);return b.exitCode===0?/\b\d+\.\d+\.\d+(?:-[\w.-]+)?/.exec(b.stdout)?.[0]??null:null}catch{return null}finally{if(Y)await X1(Y,{recursive:!0,force:!0}).catch(()=>{})}},V=!1;if(x&&J.exists(G.vault.connectionFile))try{(await(z.connect??d)({connectionFile:G.vault.connectionFile,handshakeTimeoutMs:2000})).close(),V=!0}catch{V=!1}let[W,U]=await Promise.all([X(j),X(q)]);return{opencode:{installed:J.isDirectory(Q)||Q0(z).some((F)=>J.exists(F))||j!==null,executable:j,version:W,directory:Q,generation:K0(z)},pi:{installed:q!==null||J.isDirectory(K),executable:q,version:U,directory:K},claustrum:{available:V,executable:x}}}import{setTimeout as C1}from"node:timers/promises";import{writeEnrollmentTokenFile as R1}from"@cortexkit/claustrum-client";var b0=45000,l=new Set(["opencode","litecode","opencode2","pi"]),W0=new Set(["node","bun"]),U1=[...l,...W0].map((G)=>`Name LIKE '${G}%'`).join(" OR "),Y1=`$ErrorActionPreference = 'Stop'; $rows = @(Get-CimInstance Win32_Process -Filter "${U1}" | Select-Object Name,ProcessId,CommandLine); ConvertTo-Json -Compress -Depth 3 -InputObject @{ complete = $true; processes = $rows }`,B1=/(?:^|[/\\])pi-coding-agent[/\\]dist[/\\](?:(?:bundle|bun)[/\\])?cli\.m?js$/i;function F1(G){return[...G.matchAll(/"([^"]*)"|(\S+)/g)].map((z)=>z[1]??z[2]??"")}function q0(G){return(G.split(/[/\\]/).pop()??"").toLowerCase().replace(/\.(?:exe|cmd|bat|m?js)$/,"")}var H1=new Set(["-r","--require","--import","--loader","--experimental-loader","-C","--conditions","--env-file","--title","--input-type","--preload","--cwd","-c","--config","--tsconfig-override","-d","--define","-l","--main-fields"]),O1=new Set(["-e","--eval","-p","--print"]);function M1(G,z){for(let J=0;J<z.length;J++){let Z=z[J]??"";if(Z==="--")return z[J+1];if(O1.has(Z))return;if(Z.startsWith("-")){if(!Z.includes("=")&&H1.has(Z))J++;continue}if(G==="bun"&&Z==="run")continue;return Z}return}function X0(G){let[z,...J]=F1(G);if(z===void 0)return null;let Z=q0(z);if(l.has(Z))return Z;if(!W0.has(Z))return null;let $=M1(Z,J);if($===void 0)return null;let Q=q0($);if(l.has(Q))return Q;return B1.test($)?"pi":null}class M extends Error{code="process-inspection-failed";step;exitCode;signal;timedOut;durationMs;constructor(G){super("Process inspection failed; setup cannot prove hosts are stopped.");this.name="ProcessInspectionError",this.step=G.step,this.exitCode=G.exitCode,this.signal=G.signal,this.timedOut=G.timedOut,this.durationMs=G.durationMs}get refusalText(){let G=this.timedOut?"timed out":this.signal?`signal ${this.signal}`:this.exitCode===null?"could not start or complete":this.exitCode===0?"invalid output (exit code 0)":`exit code ${this.exitCode}`;return`${this.message} ${this.step}: ${G} after ${Math.round(this.durationMs)} ms.`}}class P extends Error{activeHosts;constructor(G){let z=G.map((J)=>({pid:J.pid,command:X0(J.command)??"host"}));super(`OpenCode or Pi processes are currently running:
4
4
  ${z.map((J)=>` - PID ${J.pid}: ${J.command}`).join(`
5
5
  `)}
@@ -9,6 +9,6 @@ Please quit all OpenCode, LiteCode, and Pi processes before running setup.`);thi
9
9
  `:`
10
10
  `}},K=G,D=$[z],j=Array.isArray(D)?[...D]:[],q=j.flatMap((V,W)=>r(V)===J?[W]:[]),x=`${J}@${Z}`;if(!q.length)K=s(K,M0(K,D===void 0?[z]:[z,j.length],D===void 0?[x]:x,Q));else{let V=q[0],W=j[V],U=Array.isArray(W)?[x,...W.slice(1)]:W&&typeof W==="object"?{...W,package:x}:x;if(JSON.stringify(W)!==JSON.stringify(U))K=s(K,M0(K,[z,V],U,Q));for(let F of q.slice(1).reverse())K=C0(K,z,F)}let X=z==="plugin"?"plugins":"plugin";if(Array.isArray($[X])){let V=$[X];for(let W=V.length-1;W>=0;W--)if(r(V[W])===J)K=C0(K,X,W)}return K}function n(G,z,J={}){let Z=J.fs??_,{path:$,opencode:Q}=N(J),K=z==="2"?"plugins":"plugin";return(z==="2"?["opencode"]:["opencode","tui"]).map((j)=>{let q=$.join(Q,`${j}.jsonc`),x=$.join(Q,`${j}.json`),X=Z.exists(q)?q:Z.exists(x)?x:q,V=Z.exists(X),W=V?Z.readText(X):`${JSON.stringify({$schema:`https://opencode.ai/${j==="tui"?"tui":"config"}.json`},null,2)}
11
11
  `,U=k0(W,K),F=[],Y=[];for(let b of["plugin","plugins"]){if(!Array.isArray(U[b]))continue;for(let H of U[b]){let O=R0(H);if(O===null)continue;if(m1(O,X,J)===G.packages.opencode)F.push(JSON.stringify(H));else if(r(H)===G.packages.opencode)Y.push(JSON.stringify(H))}}if(F.length>0)return{path:X,content:W,changed:!1,existingLocalEntries:F,existingNpmEntries:Y};let C=N0(W,K,G.packages.opencode,G.version);return{path:X,content:C,changed:!V||C!==W}})}async function o(G,z){for(let J of G){if(!J.changed)continue;await z?.(),await O0(J.path,J.content,{beforeRename:z})}}async function t(G,z,J={}){let{platform:Z,env:$}=N(J),Q=await g(J.runner??T,Z,z,["install",`npm:${G.packages.pi}@${G.version}`],$);if(Q.exitCode!==0||Q.timedOut)throw new h({exitCode:Q.spawnError?null:Q.exitCode,signal:Q.signal??null,stderrTail:Q.stderr,stderrTruncated:Q.stderrTruncated??!1})}var I0="Multiple OpenCode generations found. Choose --opencode=1|2|both before running noninteractive setup.",T0="Requested setup host is unknown or unavailable. Use --host=opencode or --host=pi with a detected host.";function c1(G){let z={yes:!1,dryRun:!1,claustrum:!1,noClaustrum:!1,login:!1,enrollOnly:!1,hosts:[],opencode:void 0};for(let J of G)if(J==="--yes")z.yes=!0;else if(J==="--dry-run")z.dryRun=!0;else if(J==="--claustrum")z.claustrum=!0;else if(J==="--no-claustrum")z.noClaustrum=!0;else if(J==="--login")z.login=!0;else if(J==="--enroll-only")z.enrollOnly=!0;else if(J.startsWith("--host=")){let Z=J.slice(7);if(Z!=="opencode"&&Z!=="pi")throw Error(T0);z.hosts.push(Z)}else if(/^--opencode=(1|2|both)$/.test(J))z.opencode=J.slice(11);else throw Error(`Unknown setup argument: ${J}`);if(z.claustrum&&z.noClaustrum)throw Error("--claustrum and --no-claustrum cannot be used together.");if(z.login&&z.claustrum)throw Error("--login and --claustrum cannot be used together.");if(z.enrollOnly&&z.login)throw Error("--enroll-only and --login cannot be used together.");if(z.enrollOnly&&z.noClaustrum)throw Error("--enroll-only and --no-claustrum cannot be used together.");return z}function u1(G){for(let z of Object.values(G.packages))if(!/^(?:@[a-z0-9._-]+\/)?[a-z0-9._-]+$/.test(z))throw Error("Setup requires npm package names.");if(!/^\d+\.\d+\.\d+(?:-[a-zA-Z0-9.-]+)?(?:\+[a-zA-Z0-9.-]+)?$/.test(G.version))throw Error("Setup requires a concrete package version.");for(let z of Object.values(G.vault.hosts))if(!/^[a-z0-9][a-z0-9-]*$/.test(z.name))throw Error("Setup requires lowercase vault names containing only letters, digits and dashes.")}async function p1(G,z,J){let Z=[];for(let $ of z){let Q=J.get($)??"not-enrolled";if(Q==="unknown"){let{name:K,paths:D}=G.vault.hosts[$],j=await m(w(D),K).catch(()=>"unreadable");if(j==="vault")Q="enrolled";else if(j==="local")Q="not-enrolled"}Z.push({host:$,outcome:Q})}return Z}async function e(G,z=[],J={}){let Z=c1(z);u1(G);let $=J.terminal??A0(),Q=await p(G,J);B($,`${G.displayName} setup`);for(let[b,H]of[["OpenCode",Q.opencode],["Pi",Q.pi]])B($,`${b}: ${H.installed?`found (version ${H.version??"unknown"})`:"not found"} — ${H.directory}`);B($,`Claustrum: ${Q.claustrum.available?"available":"not available"}`);let K=Q.pi.installed&&!Q.pi.executable;if(K)B($,"Pi: skipped, because its folder exists but pi is not on PATH. Install the Pi CLI and rerun setup to add it.");let D=["opencode","pi"].filter((b)=>Q[b].installed&&!(b==="pi"&&K));if(Z.hosts.some((b)=>!D.includes(b)))throw Error(T0);let j=Z.yes||Z.dryRun&&!f($);if(!j&&!f($))throw Error("Setup requires a TTY or --yes.");let q=Z.hosts.length?D.filter((b)=>Z.hosts.includes(b)):j?D:await H0($,D)??[],x=Z.opencode??(Q.opencode.generation==="ambiguous"?"1":Q.opencode.generation);if(q.includes("opencode")&&!Z.opencode&&Q.opencode.generation==="ambiguous"){if(j||!f($))throw Error(I0);let b=await E($,[{value:"1",label:"OpenCode 1"},{value:"2",label:"OpenCode 2"},{value:"both",label:"Both (one compatible registration)"}],{message:"Which OpenCode generation should be registered?"});if(b===null)return{hosts:[],dryRun:Z.dryRun,mode:"local",detection:Q};x=b}if(!q.length)return B($,"No hosts selected. Install OpenCode or Pi and rerun setup."),{hosts:q,dryRun:Z.dryRun,mode:"local",detection:Q};let{env:X,platform:V}=N(J),W=J.fence??v(J.runner??T,{platform:V}),U=async()=>{try{await y(W,X)}catch(b){if(b instanceof M)B($,b.refusalText);throw b}};if(B($,"Checking that OpenCode and Pi are not running…"),Z.dryRun)try{let b=W.previewRunningHosts?await W.previewRunningHosts(X):{hosts:await W.listRunningHosts(X),uncheckedRuntimes:0},H=b.hosts;if(b.uncheckedRuntimes>0)B($,"Node or Bun programs are running; a real run checks whether any of them is OpenCode or Pi.");let O=new Set(new P(H).activeHosts.map((R)=>R.command.toLowerCase()==="pi"?"Pi":"OpenCode"));for(let R of O)B($,`${R} is running; setup will ask you to quit it.`)}catch(b){if(B($,"Process inspection failed; real setup will require successful inspection and stopped OpenCode/Pi hosts."),b instanceof M)B($,b.refusalText)}else await U();if((Z.claustrum||Z.enrollOnly)&&!Q.claustrum.available)throw Error("Claustrum is not available. Start ck, or omit vault-only flags and use --no-claustrum for local sign-in.");let F=Z.claustrum||Z.enrollOnly;if(!F&&!Z.login&&!Z.noClaustrum&&!j&&Q.claustrum.available&&f($)){let b=await E($,[{label:"No",value:!1},{label:"Yes",value:!0}],{message:"Connect these hosts to the Claustrum vault?"});if(b===null)return B($,"Setup cancelled. Nothing was changed."),{hosts:[],dryRun:Z.dryRun,mode:"local",detection:Q};F=b===!0}let Y=F?"claustrum":"local",C=!Z.enrollOnly&&q.includes("opencode")?n(G,x,J):[];for(let b of C){for(let O of b.existingLocalEntries??[])B($,`OpenCode: already registered from ${O} in ${b.path}.`);let H=[...b.existingLocalEntries??[],...b.existingNpmEntries??[]];if(H.length>1)B($,`Warning: ${G.displayName} may load twice in ${b.path}: ${H.join(", ")}. Entries were left unchanged.`)}if(Z.dryRun){B($,"Dry run: no registrations, enrollment, sign-in or migration will be performed.");for(let b of q){if(G.beforeSignIn)B($,`Would run beforeSignIn(${b}, ${Y}).`);if(F){let H=w(G.vault.hosts[b].paths);B($,`Would Connect ${b}: write ${H.statePath} and ${H.tokenPath}; wait for ck auth enroll approve.`)}else B($,`Would sign in locally for ${b}.`);if(!Z.enrollOnly&&G.beforeRegister)B($,`Would run beforeRegister(${b}, ${Y}).`)}for(let b of C)B($,`${b.changed?"Would write":"Unchanged"} ${b.path}:
12
- ${b.content}`);if(!Z.enrollOnly&&q.includes("pi"))B($,`Would run ${Q.pi.executable} install npm:${G.packages.pi}@${G.version}`);if(!Z.enrollOnly)for(let b of q)B($,`Would migrate ${b} using the plugin callback (provider-specific writes).`)}else{let b={opencodeGeneration:x,mode:Y,hosts:Object.freeze([...q]),piAgentDir:Q.pi.directory},H=new Map;try{for(let O of q){if(await U(),await G.beforeSignIn?.(O,b),await U(),F){H.set(O,"unknown");try{await F0(G,O,J,$,U)}catch(R){if(R instanceof A)H.set(O,"not-enrolled");throw R}H.set(O,"enrolled")}else await G.signInLocal(O,b);if(await U(),Z.enrollOnly)continue;if(await G.beforeRegister?.(O,Y,b),await U(),O==="opencode")await o(C,U);else await t(G,Q.pi.executable,J);await U(),await G.migrate(O,b)}}catch(O){if(H.size===0)throw O;try{let R=await p1(G,q,H);$0(O,R);for(let p0 of R)B($,Z0(p0))}catch{}throw O}}if(B($,`${Z.dryRun?"Planned":Z.enrollOnly?"Enrolled":"Configured"} ${G.displayName} for ${q.join(", ")} (${Y}).`),Z.enrollOnly)B($,`Enroll-only: no host config or plugin registration ${Z.dryRun?"will be":"was"} written.`),B($,"Next: register the plugin yourself in each selected host and enable vault access as required by the plugin.");else B($,`Next: ${q.includes("opencode")?"start OpenCode":"start Pi"} and run ${G.slashCommand}.`);return{hosts:q,dryRun:Z.dryRun,mode:Y,detection:Q}}var L={name:"@cortexkit/opencode-openai-auth",version:"1.8.0",license:"MIT",type:"module",repository:{type:"git",url:"git+https://github.com/cortexkit/openai-auth.git",directory:"packages/opencode"},main:"./dist/index.js",types:"./dist/index.d.ts",bin:{"opencode-openai-auth":"./dist/bin.js"},exports:{".":{import:"./dist/index.js",types:"./dist/index.d.ts"},"./tui":{types:"./dist/tui.d.ts",import:"./src/tui/entry.mjs"},"./tui-prefs":{types:"./dist/tui-preferences.d.ts",import:"./dist/tui-preferences.js"},"./server":{types:"./dist/v2/server.d.ts",import:"./dist/v2/server.js"}},"oc-plugin":["server","tui"],engines:{bun:"1.3.14"},files:["dist","src/tui/entry.mjs","src/tui-compiled","README.md","LICENSE"],scripts:{build:"rm -rf dist && bun build src/index.ts src/v2/server.ts src/sidebar-state.ts src/tui-preferences.ts src/rpc/rpc-client.ts src/rpc/port-file.ts src/rpc/protocol.ts src/rpc/rpc-dir.ts src/bin.ts --root src --outdir dist --target node --format esm --splitting --external @opencode-ai/plugin --external @opencode/plugin --external @cortexkit/private-files --external jsonc-parser --external @cortexkit/claustrum-client --external @cortexkit/subc-client --minify && bun run build:types && bun run build:tui","build:tui":"bun scripts/build-tui.ts","build:types":"cd ../core && bun run build && cd ../opencode && tsdown --config tsdown.config.ts --config-loader native","build:dev":"rm -rf dist && tsc -p tsconfig.build.json",test:"bun test src/tests",typecheck:"tsc",types:"tsc",prepublishOnly:"bun run build"},peerDependencies:{"@opencode-ai/plugin":"*","@opencode/plugin":">=2.0.21"},peerDependenciesMeta:{"@opencode/plugin":{optional:!0}},devDependencies:{"@ai-sdk/openai":"3.0.88","@cortexkit/common-auth":"^0.27.1","@cortexkit/openai-auth-core":"workspace:*","@opencode/plugin":"2.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"}};import{basename as n1}from"node:path";import{resolveClaustrumConnectionPath as o1}from"@cortexkit/claustrum-client";var _0={name:"@cortexkit/pi-openai-auth",version:"1.8.0",license:"MIT",type:"module",repository:{type:"git",url:"git+https://github.com/cortexkit/openai-auth.git",directory:"packages/pi"},main:"./dist/index.js",types:"./dist/index.d.ts",exports:{".":{import:"./dist/index.js",types:"./dist/index.d.ts"}},files:["dist","README.md","LICENSE"],keywords:["pi-package"],pi:{extensions:["./dist/index.js"]},scripts:{build:"rm -rf dist && bun build src/index.ts --outdir dist --target node --format esm --external '@earendil-works/pi-ai' --external '@earendil-works/pi-ai/*' --external '@earendil-works/pi-coding-agent' --external '@earendil-works/pi-coding-agent/*' --external '@earendil-works/pi-tui' --external '@earendil-works/pi-tui/*' --external @cortexkit/private-files --external @cortexkit/claustrum-client --external @cortexkit/subc-client --minify && bun run build:types","build:types":"cd ../core && bun run build && cd ../pi && tsdown --config tsdown.config.ts --config-loader native",test:"bun test src/tests",typecheck:"tsc",types:"tsc",prepublishOnly:"bun run build"},devDependencies:{"@cortexkit/common-auth":"^0.27.1","@cortexkit/openai-auth-core":"workspace:*"},dependencies:{"@cortexkit/claustrum-client":"^0.13.0","@cortexkit/private-files":"^0.2.1","@cortexkit/subc-client":"^0.22.0"},peerDependencies:{"@earendil-works/pi-ai":">=1.0.1","@earendil-works/pi-coding-agent":">=1.0.1","@earendil-works/pi-tui":">=1.0.1"}};import{homedir as i1}from"node:os";import{join as P0}from"node:path";function s1(){return process.env.PI_AGENT_DIR?.trim()||P0(i1(),".pi","agent")}function S0(){return process.env.PI_OPENAI_AUTH_FILE?.trim()||P0(s1(),w0)}function r1(G=S0()){return process.env.PI_OPENAI_AUTH_STATE_FILE?.trim()||L0(G)}function v0(G=S0()){return{configPath:G,statePath:r1(G)}}function c0(G={}){let z=G.print??console.log,J=G.fence??v(),Z={opencode:{stateDir:G0(h0().statePath),host:"opencode"},pi:{stateDir:G0(v0().statePath),host:"pi"}},$=async(Q)=>{if(await m(w(Z[Q]),S(Q))!=="local")throw Error(`${Q} is enrolled in Claustrum or its enrollment is unreadable. Disconnect it from the vault before using local sign-in.`)};return{packages:{opencode:L.name,pi:_0.name},version:L.version,displayName:"OpenAI Auth",slashCommand:"/openai",vault:{connectionFile:o1(),hosts:{opencode:{name:S("opencode"),paths:Z.opencode},pi:{name:S("pi"),paths:Z.pi}}},async beforeRegister(Q,K){if(K==="claustrum"){let D=await E0(w(Z[Q]),S(Q)),j=D.state==="approved"?D.approvedName:void 0,q=j??("proposedName"in D?D.proposedName:S(Q));if(!j)z("The enrollment state does not record an approved name. The command below uses the proposed name; if the vault approved a different name, substitute it.");if(z(`Allow this host to read OpenAI accounts with:
12
+ ${b.content}`);if(!Z.enrollOnly&&q.includes("pi"))B($,`Would run ${Q.pi.executable} install npm:${G.packages.pi}@${G.version}`);if(!Z.enrollOnly)for(let b of q)B($,`Would migrate ${b} using the plugin callback (provider-specific writes).`)}else{let b={opencodeGeneration:x,mode:Y,hosts:Object.freeze([...q]),piAgentDir:Q.pi.directory},H=new Map;try{for(let O of q){if(await U(),await G.beforeSignIn?.(O,b),await U(),F){H.set(O,"unknown");try{await F0(G,O,J,$,U)}catch(R){if(R instanceof A)H.set(O,"not-enrolled");throw R}H.set(O,"enrolled")}else await G.signInLocal(O,b);if(await U(),Z.enrollOnly)continue;if(await G.beforeRegister?.(O,Y,b),await U(),O==="opencode")await o(C,U);else await t(G,Q.pi.executable,J);await U(),await G.migrate(O,b)}}catch(O){if(H.size===0)throw O;try{let R=await p1(G,q,H);$0(O,R);for(let p0 of R)B($,Z0(p0))}catch{}throw O}}if(B($,`${Z.dryRun?"Planned":Z.enrollOnly?"Enrolled":"Configured"} ${G.displayName} for ${q.join(", ")} (${Y}).`),Z.enrollOnly)B($,`Enroll-only: no host config or plugin registration ${Z.dryRun?"will be":"was"} written.`),B($,"Next: register the plugin yourself in each selected host and enable vault access as required by the plugin.");else B($,`Next: ${q.includes("opencode")?"start OpenCode":"start Pi"} and run ${G.slashCommand}.`);return{hosts:q,dryRun:Z.dryRun,mode:Y,detection:Q}}var L={name:"@cortexkit/opencode-openai-auth",version:"1.8.1",license:"MIT",type:"module",repository:{type:"git",url:"git+https://github.com/cortexkit/openai-auth.git",directory:"packages/opencode"},main:"./dist/index.js",types:"./dist/index.d.ts",bin:{"opencode-openai-auth":"./dist/bin.js"},exports:{".":{import:"./dist/index.js",types:"./dist/index.d.ts"},"./tui":{types:"./dist/tui.d.ts",import:"./src/tui/entry.mjs"},"./tui-prefs":{types:"./dist/tui-preferences.d.ts",import:"./dist/tui-preferences.js"},"./server":{types:"./dist/v2/server.d.ts",import:"./dist/v2/server.js"}},"oc-plugin":["server","tui"],engines:{bun:"1.3.14"},files:["dist","src/tui/entry.mjs","src/tui-compiled","README.md","LICENSE"],scripts:{build:"rm -rf dist && bun build src/index.ts src/v2/server.ts src/sidebar-state.ts src/tui-preferences.ts src/rpc/rpc-client.ts src/rpc/port-file.ts src/rpc/protocol.ts src/rpc/rpc-dir.ts src/bin.ts --root src --outdir dist --target node --format esm --splitting --external @opencode-ai/plugin --external @opencode/plugin --external @cortexkit/private-files --external jsonc-parser --external @cortexkit/claustrum-client --external @cortexkit/subc-client --minify && bun run build:types && bun run build:tui","build:tui":"bun scripts/build-tui.ts","build:types":"cd ../core && bun run build && cd ../opencode && tsdown --config tsdown.config.ts --config-loader native","build:dev":"rm -rf dist && tsc -p tsconfig.build.json",test:"bun test src/tests",typecheck:"tsc",types:"tsc",prepublishOnly:"bun run build"},peerDependencies:{"@opencode-ai/plugin":"*","@opencode/plugin":">=2.0.21"},peerDependenciesMeta:{"@opencode/plugin":{optional:!0}},devDependencies:{"@ai-sdk/openai":"3.0.88","@cortexkit/common-auth":"^0.27.1","@cortexkit/openai-auth-core":"workspace:*","@opencode/plugin":"2.2.0"},dependencies:{"@cortexkit/claustrum-client":"^0.13.0","@cortexkit/private-files":"^0.2.1","@cortexkit/subc-client":"^0.22.0","@opentui/core":">=0.7.0","@opentui/solid":">=0.7.0",ai:"^7.0.155","jsonc-parser":"^3.3.1","solid-js":"1.9.12"}};import{basename as n1}from"node:path";import{resolveClaustrumConnectionPath as o1}from"@cortexkit/claustrum-client";var _0={name:"@cortexkit/pi-openai-auth",version:"1.8.1",license:"MIT",type:"module",repository:{type:"git",url:"git+https://github.com/cortexkit/openai-auth.git",directory:"packages/pi"},main:"./dist/index.js",types:"./dist/index.d.ts",exports:{".":{import:"./dist/index.js",types:"./dist/index.d.ts"}},files:["dist","README.md","LICENSE"],keywords:["pi-package"],pi:{extensions:["./dist/index.js"]},scripts:{build:"rm -rf dist && bun build src/index.ts --outdir dist --target node --format esm --external '@earendil-works/pi-ai' --external '@earendil-works/pi-ai/*' --external '@earendil-works/pi-coding-agent' --external '@earendil-works/pi-coding-agent/*' --external '@earendil-works/pi-tui' --external '@earendil-works/pi-tui/*' --external @cortexkit/private-files --external @cortexkit/claustrum-client --external @cortexkit/subc-client --minify && bun run build:types","build:types":"cd ../core && bun run build && cd ../pi && tsdown --config tsdown.config.ts --config-loader native",test:"bun test src/tests",typecheck:"tsc",types:"tsc",prepublishOnly:"bun run build"},devDependencies:{"@cortexkit/common-auth":"^0.27.1","@cortexkit/openai-auth-core":"workspace:*"},dependencies:{"@cortexkit/claustrum-client":"^0.13.0","@cortexkit/private-files":"^0.2.1","@cortexkit/subc-client":"^0.22.0"},peerDependencies:{"@earendil-works/pi-ai":">=1.0.1","@earendil-works/pi-coding-agent":">=1.0.1","@earendil-works/pi-tui":">=1.0.1"}};import{homedir as i1}from"node:os";import{join as P0}from"node:path";function s1(){return process.env.PI_AGENT_DIR?.trim()||P0(i1(),".pi","agent")}function S0(){return process.env.PI_OPENAI_AUTH_FILE?.trim()||P0(s1(),w0)}function r1(G=S0()){return process.env.PI_OPENAI_AUTH_STATE_FILE?.trim()||L0(G)}function v0(G=S0()){return{configPath:G,statePath:r1(G)}}function c0(G={}){let z=G.print??console.log,J=G.fence??v(),Z={opencode:{stateDir:G0(h0().statePath),host:"opencode"},pi:{stateDir:G0(v0().statePath),host:"pi"}},$=async(Q)=>{if(await m(w(Z[Q]),S(Q))!=="local")throw Error(`${Q} is enrolled in Claustrum or its enrollment is unreadable. Disconnect it from the vault before using local sign-in.`)};return{packages:{opencode:L.name,pi:_0.name},version:L.version,displayName:"OpenAI Auth",slashCommand:"/openai",vault:{connectionFile:o1(),hosts:{opencode:{name:S("opencode"),paths:Z.opencode},pi:{name:S("pi"),paths:Z.pi}}},async beforeRegister(Q,K){if(K==="claustrum"){let D=await E0(w(Z[Q]),S(Q)),j=D.state==="approved"?D.approvedName:void 0,q=j??("proposedName"in D?D.proposedName:S(Q));if(!j)z("The enrollment state does not record an approved name. The command below uses the proposed name; if the vault approved a different name, substitute it.");if(z(`Allow this host to read OpenAI accounts with:
13
13
  ck auth grant --principal enrolled:${q} --selector-kind category --selector ${f0.category} --operation read`),Q==="opencode")z("Then run opencode auth login and choose ChatGPT accounts in the vault to activate vault routing without local sign-in.");return}await $(Q)},async signInLocal(Q,K){if(await $(Q),Q==="pi"){z("Start Pi and run /login openai-codex to sign in with Pi itself.");return}if(K.opencodeGeneration!=="1"){let Y=n1(I("opencode2",G.io)??I("opencode",G.io)??"opencode");z(`In OpenCode 2, run ${Y} auth login openai and choose "ChatGPT (openai-auth pool, browser)" or "ChatGPT (openai-auth pool, headless)" to sign in to the account pool and activate it.`)}if(K.opencodeGeneration==="2")return;if(d0(process.env))throw Error("Unset OPENCODE_AUTH_CONTENT before local setup sign-in.");let D=m0(),j={path:{id:"openai"}};if(await D.get(j)!==void 0){z("OpenCode already has an OpenAI login. Use opencode auth login to change it.");return}let q=G.beginLogin??y0,x=new AbortController,X=Boolean(process.env.SSH_CONNECTION||process.env.SSH_TTY||process.platform==="linux"&&!process.env.DISPLAY&&!process.env.WAYLAND_DISPLAY),V={version:L.version,signal:x.signal},W,U=!X;try{W=await q({...V,headless:X})}catch(Y){if(X)throw Y;U=!1,z("Browser callback unavailable; using device-code sign-in."),W=await q({version:L.version,headless:!0})}if(U){if(!(G.openBrowser??g0)(W.url))x.abort(),await W.completion.catch(()=>{}),z("Browser unavailable; using device-code sign-in."),W=await q({version:L.version,headless:!0})}z(`${W.url}
14
14
  ${W.instructions}`);let F=await W.completion;await y(J),await $(Q),await D.set({...j,body:{type:"oauth",access:F.access,refresh:F.refresh,expires:F.expires,...F.accountId?{accountId:F.accountId}:{}}}),z("Signed in to OpenCode. The first plugin start adopts this login into the account pool.")},async migrate(Q){z(`${Q}: account migration runs on first plugin start; setup leaves existing credentials unchanged.`)}}}if(process.argv[2]!=="setup")console.log("Usage: opencode-openai-auth setup [options]");else try{await u0({version:L.version}),await e(c0(),process.argv.slice(3))}catch(G){console.error(G instanceof Error?G.message:String(G)),process.exitCode=1}
@@ -1,7 +1,6 @@
1
- import { gt as QuotaMap } from "./sidebar-state-B1cq68UB.js";
1
+ import { gt as QuotaMap } from "./sidebar-state-DkNebAiC.js";
2
2
  import { ClaustrumClient, EnrollmentPollOutcome } from "@cortexkit/claustrum-client";
3
3
  import "@cortexkit/private-files";
4
- //#region ../../node_modules/.bun/@cortexkit+common-auth@0.27.1+edd79cef82a5b402/node_modules/@cortexkit/common-auth/dist/store/schema.d.ts
5
4
  type OAuthCredential = {
6
5
  type: 'oauth';
7
6
  access?: string;
@@ -76,8 +75,6 @@ interface ProviderStateCodec {
76
75
  */
77
76
  onReplace?(previous: unknown | undefined, replacement: ProviderStateReplacement): unknown | undefined;
78
77
  }
79
- //#endregion
80
- //#region ../../node_modules/.bun/@cortexkit+common-auth@0.27.1+edd79cef82a5b402/node_modules/@cortexkit/common-auth/dist/store/errors.d.ts
81
78
  /** Every library operation that can fail, as named in the failure value. */
82
79
  type PoolOperation = 'initialize' | 'add' | 'replace' | 'rotate' | 'disable' | 'enable' | 'remove' | 'reorder' | 'updateSettings' | 'recordIdentity' | 'updateProviderState' | 'refresh' | 'pull' | 'publishRoster';
83
80
  /**
@@ -123,13 +120,9 @@ declare class PoolOperationError extends Error {
123
120
  cause?: unknown;
124
121
  });
125
122
  }
126
- //#endregion
127
- //#region ../../node_modules/.bun/@cortexkit+common-auth@0.27.1+edd79cef82a5b402/node_modules/@cortexkit/common-auth/dist/store/hooks.d.ts
128
123
  interface PoolLogger {
129
124
  warn(message: string, data?: unknown): void;
130
125
  }
131
- //#endregion
132
- //#region ../../node_modules/.bun/@cortexkit+common-auth@0.27.1+edd79cef82a5b402/node_modules/@cortexkit/common-auth/dist/fs/refresh-file-lock.d.ts
133
126
  interface LockLoss {
134
127
  readonly reason: 'taken-over' | 'expired' | 'unreadable' | 'renewal-failed' | 'marker-lost';
135
128
  readonly expectedOwnerId: string;
@@ -163,8 +156,6 @@ type RefreshFileLockOptions = {
163
156
  };
164
157
  /** Filesystem leases share wall time across all callers and processes. */
165
158
  declare function acquireRefreshFileLock(options: RefreshFileLockOptions): Promise<RefreshFileLock | null>;
166
- //#endregion
167
- //#region ../../node_modules/.bun/@cortexkit+common-auth@0.27.1+edd79cef82a5b402/node_modules/@cortexkit/common-auth/dist/store/refresh-lock.d.ts
168
159
  type LockStep = NonNullable<Parameters<typeof acquireRefreshFileLock>[0]['onStep']> extends ((step: infer S) => unknown) ? S : never;
169
160
  /** Tuning shared by every lock the store takes; each field is overridable. */
170
161
  interface PoolLockOptions {
@@ -195,8 +186,6 @@ interface LockEnvironment {
195
186
  path: string;
196
187
  }, event: 'scheduled' | 'cancelled') => void;
197
188
  }
198
- //#endregion
199
- //#region ../../node_modules/.bun/@cortexkit+common-auth@0.27.1+edd79cef82a5b402/node_modules/@cortexkit/common-auth/dist/store/mutate.d.ts
200
189
  /** Named points on the write path, for crash and ownership injection. */
201
190
  type WriteStep = 'before-config-write' | 'after-config-write' | 'before-state-write' | 'after-state-write';
202
191
  /** Awaitable pause points on the pull and refresh paths. */
@@ -228,12 +217,8 @@ interface StoreContext {
228
217
  requireCredentialStamps?: boolean;
229
218
  requireRemovedFingerprint?: boolean;
230
219
  }
231
- //#endregion
232
- //#region ../../node_modules/.bun/@cortexkit+common-auth@0.27.1+edd79cef82a5b402/node_modules/@cortexkit/common-auth/dist/store/runtime.d.ts
233
220
  /** Where a pull was fired from; `load` fires at most once per process per row. */
234
221
  type PullReason = 'load' | 'add' | 'replace' | 'admission';
235
- //#endregion
236
- //#region ../../node_modules/.bun/@cortexkit+common-auth@0.27.1+edd79cef82a5b402/node_modules/@cortexkit/common-auth/dist/quota/commit-interval.d.ts
237
222
  interface QuotaCommitTimer {
238
223
  now(): number;
239
224
  schedule(delayMs: number, run: () => Promise<void>): {
@@ -241,8 +226,6 @@ interface QuotaCommitTimer {
241
226
  unref?(): void;
242
227
  };
243
228
  }
244
- //#endregion
245
- //#region ../../node_modules/.bun/@cortexkit+common-auth@0.27.1+edd79cef82a5b402/node_modules/@cortexkit/common-auth/dist/store/pull.d.ts
246
229
  /** What a pull is issued with: the credential and its attribution tuple. */
247
230
  interface PullRequest {
248
231
  id: string;
@@ -252,8 +235,6 @@ interface PullRequest {
252
235
  reason: PullReason;
253
236
  }
254
237
  type PullHook = (request: PullRequest) => Promise<unknown>;
255
- //#endregion
256
- //#region ../../node_modules/.bun/@cortexkit+common-auth@0.27.1+edd79cef82a5b402/node_modules/@cortexkit/common-auth/dist/store/pool.d.ts
257
238
  interface OpenPoolStoreOptions {
258
239
  /** The provider every row of this pool belongs to; keys the provider-wide lock. */
259
240
  provider: string;
@@ -329,8 +310,6 @@ interface OpenPoolStoreOptions {
329
310
  onLockStep?: LockEnvironment['onLockStep'];
330
311
  onRenewalTimer?: LockEnvironment['onRenewalTimer'];
331
312
  }
332
- //#endregion
333
- //#region ../core/dist/paths.d.ts
334
313
  /**
335
314
  * The config file and the runtime-state file a store operation reads and writes.
336
315
  *
@@ -342,8 +321,6 @@ interface AccountPaths {
342
321
  configPath: string;
343
322
  statePath: string;
344
323
  }
345
- //#endregion
346
- //#region ../core/dist/oauth.d.ts
347
324
  interface IdTokenClaims {
348
325
  chatgpt_account_id?: string;
349
326
  email?: string;
@@ -400,8 +377,6 @@ interface BeginAccountLoginResult {
400
377
  /** Resolves after the user completes the OAuth flow with a ready-to-ingest account. */
401
378
  completion: Promise<IngestAccount>;
402
379
  }
403
- //#endregion
404
- //#region ../../node_modules/.bun/@cortexkit+common-auth@0.27.1+edd79cef82a5b402/node_modules/@cortexkit/common-auth/dist/claustrum/watch.d.ts
405
380
  /**
406
381
  * How a host currently learns about changes, for logs and status displays.
407
382
  * `watching`: a watch was accepted and is open, so polling is reduced to a
@@ -454,8 +429,6 @@ interface ScopedWatchSource {
454
429
  enrollmentToken?: string;
455
430
  }): ScopedWatchHandle;
456
431
  }
457
- //#endregion
458
- //#region ../../node_modules/.bun/@cortexkit+common-auth@0.27.1+edd79cef82a5b402/node_modules/@cortexkit/common-auth/dist/claustrum/insula.d.ts
459
432
  /**
460
433
  * A held-open `usage.watch` stream. `closed` resolves when insula ends the
461
434
  * stream (STREAM_END at shutdown, or a reply that ends it) or after `stop()`,
@@ -478,8 +451,6 @@ interface InsulaUsageTransport {
478
451
  */
479
452
  watchUsage?(onNotice: (body: Uint8Array) => void): InsulaUsageWatch;
480
453
  }
481
- //#endregion
482
- //#region ../../node_modules/.bun/@cortexkit+common-auth@0.27.1+edd79cef82a5b402/node_modules/@cortexkit/common-auth/dist/claustrum/custody.d.ts
483
454
  /**
484
455
  * `watchScoped` is present from claustrum-client 0.12.0. Hosts detect it at
485
456
  * run time and keep polling without it.
@@ -584,8 +555,6 @@ interface KeptReceiptState {
584
555
  readonly active: boolean;
585
556
  readonly since: number | null;
586
557
  }
587
- //#endregion
588
- //#region ../../node_modules/.bun/@cortexkit+common-auth@0.27.1+edd79cef82a5b402/node_modules/@cortexkit/common-auth/dist/claustrum/interlock.d.ts
589
558
  /**
590
559
  * The declined-account interlock: the user's "do not use this vault account",
591
560
  * kept on the consumer side because the vault has no notion of it.
@@ -603,8 +572,6 @@ interface DeclinedAccount {
603
572
  readonly credentialId: string;
604
573
  readonly accountIdentity?: string;
605
574
  }
606
- //#endregion
607
- //#region ../../node_modules/.bun/@cortexkit+common-auth@0.27.1+edd79cef82a5b402/node_modules/@cortexkit/common-auth/dist/claustrum/roster.d.ts
608
575
  /**
609
576
  * One vault account as the pool sees it. It carries no bearer material: the
610
577
  * access token is fetched from the vault for every send. Several vault
@@ -664,8 +631,6 @@ interface ReorderVaultRosterResult {
664
631
  * `ClaustrumScopedAttempt` that send was authorized with.
665
632
  */
666
633
  type QuotaReceipt = Pick<ClaustrumScopedAttempt, 'credentialId' | 'accountIdentity' | 'accountIdentitySource' | 'expectedAccountIdentity'>;
667
- //#endregion
668
- //#region ../../node_modules/.bun/@cortexkit+common-auth@0.27.1+edd79cef82a5b402/node_modules/@cortexkit/common-auth/dist/claustrum/consumer.d.ts
669
634
  /**
670
635
  * How a started consumer learns about changes, for logs and status displays.
671
636
  * `insula` is present when the consumer was given an insula source. Never
@@ -675,8 +640,6 @@ interface ClaustrumWatchState {
675
640
  readonly vault: WatchMode;
676
641
  readonly insula?: WatchMode;
677
642
  }
678
- //#endregion
679
- //#region ../../node_modules/.bun/@cortexkit+common-auth@0.27.1+edd79cef82a5b402/node_modules/@cortexkit/common-auth/dist/claustrum/enrollment.d.ts
680
643
  interface ClaustrumEnrollmentClient {
681
644
  enrollPropose(input: {
682
645
  name: string;
@@ -722,12 +685,8 @@ interface ClaustrumEnrollmentPaths {
722
685
  statePath: string;
723
686
  tokenPath: string;
724
687
  }
725
- //#endregion
726
- //#region ../core/dist/pool-routing.d.ts
727
688
  /** Existing callbacks may return a promise for an in-progress quota poll. */
728
689
  type QuotaReadingRequest = ((id: string) => void) | ((id: string) => Promise<unknown> | undefined);
729
- //#endregion
730
- //#region ../core/dist/vault.d.ts
731
690
  type VaultHost = 'opencode' | 'pi';
732
691
  interface VaultPaths extends ClaustrumEnrollmentPaths {
733
692
  /** The roster: the vault accounts, their quota and the declined ones. Holds no token. */
@@ -748,6 +707,8 @@ interface VaultStatus {
748
707
  /** The name this host enrolls as. */
749
708
  name: string;
750
709
  enrollment: ClaustrumEnrollmentStatus;
710
+ /** Whether a roster snapshot exists, including an answered empty list. */
711
+ discovered: boolean;
751
712
  /** Every vault account this host can see, declined and cold ones included. */
752
713
  accounts: readonly VaultRosterRow[];
753
714
  lastError?: string;
@@ -960,8 +921,6 @@ declare class OpenAiVault {
960
921
  assertHostSlot(auth: unknown): void;
961
922
  close(): void;
962
923
  }
963
- //#endregion
964
- //#region ../core/dist/commands.d.ts
965
924
  interface ResetTargetIdentity {
966
925
  accountKey: string;
967
926
  label: string;
@@ -969,8 +928,6 @@ interface ResetTargetIdentity {
969
928
  chatgptAccountId?: string;
970
929
  onAuthFailure?: (status: number) => Promise<void>;
971
930
  }
972
- //#endregion
973
- //#region src/core/version-fence.d.ts
974
931
  /** One live process that keeps the fence shut. */
975
932
  interface VersionFenceBlocker {
976
933
  /** `'unknown'` when a whole directory could not be read. */
@@ -986,8 +943,6 @@ type VersionFenceResult = {
986
943
  open: false;
987
944
  blockers: VersionFenceBlocker[];
988
945
  };
989
- //#endregion
990
- //#region src/core/pool-migration.d.ts
991
946
  /** The host login slot, shaped like the plugin's `client.auth`. */
992
947
  interface HostSlotAdapter {
993
948
  /** The shared auth.json path, independent of a plugin's config root. */
@@ -1176,8 +1131,6 @@ declare function migrateToPool(deps: PoolMigrationDeps & PoolMigrationFenceDeps)
1176
1131
  * and the placeholder goes back into the slot.
1177
1132
  */
1178
1133
  declare function adoptHostSlotLogin(deps: PoolMigrationDeps): Promise<PoolTransferOutcome>;
1179
- //#endregion
1180
- //#region src/core/pool-lifecycle.d.ts
1181
1134
  interface PoolLifecycleTimers {
1182
1135
  set(run: () => void, ms: number): unknown;
1183
1136
  clear(handle: unknown): void;
@@ -1203,8 +1156,6 @@ interface PoolLifecycleDeps {
1203
1156
  */
1204
1157
  paused?: () => boolean | Promise<boolean>;
1205
1158
  }
1206
- //#endregion
1207
- //#region src/core/runtime-layout.d.ts
1208
1159
  interface RuntimeLayoutLogger {
1209
1160
  info(message: string, meta?: Record<string, unknown>): unknown;
1210
1161
  warn(message: string, meta?: Record<string, unknown>): unknown;
@@ -1232,15 +1183,11 @@ interface RuntimeLayoutOptions {
1232
1183
  /** Test seam: how long to wait for the layout lock. */
1233
1184
  layoutLockWaitMs?: number;
1234
1185
  }
1235
- //#endregion
1236
- //#region src/util/canonical-input.d.ts
1237
1186
  interface CanonicalInput {
1238
1187
  texts: string[];
1239
1188
  snapshots: unknown[];
1240
1189
  retainable: boolean;
1241
1190
  }
1242
- //#endregion
1243
- //#region src/codex-request.d.ts
1244
1191
  declare const RESPONSES_LITE_MODELS: ReadonlySet<string>;
1245
1192
  declare const CODEX_VERSION = "0.159.0";
1246
1193
  declare const CODEX_USER_AGENT = "codex_exec/0.159.0 (Debian 12.0.0; aarch64) unknown (codex_exec; 0.159.0)";
@@ -1263,5 +1210,4 @@ interface CodexRequestRuntime {
1263
1210
  now: () => number;
1264
1211
  uuid: () => string;
1265
1212
  }
1266
- //#endregion
1267
1213
  export { parseJwtClaims as _, RESPONSES_LITE_MODELS as a, HostSlotAdapter as c, OpenAiVaultOptions as d, BeginAccountLoginOptions as f, extractAccountIdFromClaims as g, TokenResponse as h, CodexSessionMetadata as i, ResetTargetIdentity as l, IdTokenClaims as m, CODEX_VERSION as n, RuntimeLayoutOptions as o, BeginAccountLoginResult as p, CodexRequestRuntime as r, PoolLifecycleDeps as s, CODEX_USER_AGENT as t, OpenAiVault as u, AccountPaths as v };
@@ -1,4 +1,4 @@
1
- import{hf as O,if as U,lf as b,mf as m,nf as L,rf as y}from"./index-5dxpsa3t.js";import{createHash as Zz,randomUUID as v}from"node:crypto";import{chmod as t,mkdir as r,open as e,readdir as j,rename as zz,rmdir as Gz,stat as Jz,unlink as S}from"node:fs/promises";import{join as R,resolve as D}from"node:path";function l(z){return typeof z==="number"&&Number.isSafeInteger(z)&&z>0}function F(z){if(!l(z))return!1;try{return process.kill(z,0),!0}catch(J){return J.code==="EPERM"}}function Cz(z){return(J)=>Kz(J,z)}function Kz(z,J){if(/^[0-9a-f]{16}$/.test(z))return!0;return z.startsWith(J)&&/^[0-9a-f]{16}$/.test(z.slice(J.length))}function Nz(z){let J=/^port-(\d+)\.json$/.exec(z);return J?Number(J[1]):void 0}function p(z,J){if(z===null||typeof z!=="object"||Array.isArray(z))return!1;let{pid:V,port:Q,token:K}=z;return l(V)&&Nz(J)===V&&typeof Q==="number"&&Number.isInteger(Q)&&Q>=1&&Q<=65535&&typeof K==="string"&&K.length>0}async function h(z,J){J?.debug("rpc corrupt port file",{pid:process.pid,portFile:z}),await S(z).catch(()=>{})}async function Az(z,J,V={}){let Q=async()=>{let K=R(z,`port-${J.pid}.json`);if(O)return await m(z,V.secureDir??!1),await V.beforeWrite?.(),await y(K,JSON.stringify({...J,startedAt:Date.now()}),{stagePath:`${K}.${(V.stageName??v)()}.tmp`}),K;if(await r(z,{recursive:!0,mode:V.secureDir?448:void 0}),V.secureDir)await t(z,448);await V.beforeWrite?.();let W={...J,startedAt:Date.now()},Y=`${K}.${(V.stageName??v)()}.tmp`,N,G=!1;try{N=await e(Y,"wx",384),G=!0,await N.writeFile(JSON.stringify(W),"utf8"),await N.chmod(384),await N.close(),N=void 0,await zz(Y,K),G=!1}finally{if(await N?.close().catch(()=>{}),G)await S(Y).catch(()=>{})}return K};try{return await Q()}catch(K){if(K.code==="ENOENT")return await Q();throw K}}async function Oz(z,J,V,Q){let K;try{K=await j(z,{withFileTypes:!0})}catch(Y){if(Y.code==="ENOENT")return;throw Y}let W=D(J);for(let Y of K){if(!Y.isDirectory()||!V(Y.name))continue;let N=R(z,Y.name),G;try{G=await j(N)}catch(X){if(X.code==="ENOENT")continue;throw X}for(let X of G){if(!X.startsWith("port-")||!X.endsWith(".json"))continue;let $=R(N,X),Z;try{Z=await L($)}catch(H){if(H instanceof U&&H.code!=="ENOENT")throw H;continue}if(Z===void 0)continue;let q;try{q=JSON.parse(Z)}catch{await h($,Q);continue}if(!p(q,X)){await h($,Q);continue}if(!F(q.pid))await S($).catch(()=>{})}if(D(N)!==W)await Gz(N).catch(()=>{})}}async function c(z,J){if(!F(J.pid))return null;let V=R(D(z),`port-${J.pid}.json`);try{if(O)await b(V,"file");let Q=await Jz(V);return`${V}:${Q.dev}:${Q.ino}:${Q.mtimeMs}:${Q.size}`}catch(Q){if(Q instanceof U&&Q.code!=="ENOENT")throw Q;return null}}async function a(z,J,V={}){let Q;try{if(O)await b(z,"directory");Q=await j(z)}catch(G){if(G instanceof U&&G.code!=="ENOENT")throw G;return null}let K=[];for(let G of Q){if(!G.startsWith("port-")||!G.endsWith(".json"))continue;try{let X=JSON.parse(await L(R(z,G)));if(p(X,G))if(F(X.pid))K.push(X);else await S(R(z,G)).catch(()=>{})}catch(X){if(X instanceof U&&X.code!=="ENOENT")throw X}}if(K.length===0)return null;let W=J!==void 0&&J>=1?K.filter((G)=>G.pid===J):[];if(V.exactPid===!0&&W.length===0)return null;let Y=W.length>0?W:K,N=(G)=>typeof G.startedAt==="number"&&Number.isFinite(G.startedAt)?G.startedAt:-1/0;return Y.sort((G,X)=>N(X)-N(G))[0]??null}import{open as Qz}from"node:fs/promises";import{connect as Vz}from"node:net";import{join as Wz,resolve as o}from"node:path";var i=2000,A=new Map,T=new Map;async function Xz(z,J){let V=Wz(o(z),`port-${J.pid}.json`);if(O){let K=JSON.parse(await L(V));if(K.pid!==J.pid||K.port!==J.port||K.token!==J.token)return null;return null}let Q;try{Q=await Qz(V,"r");let K=await Q.stat(),W=JSON.parse(await Q.readFile("utf8"));if(W.pid!==J.pid||W.port!==J.port||W.token!==J.token)return null;return`${V}:${K.dev}:${K.ino}:${K.mtimeMs}:${K.size}`}catch{return null}finally{await Q?.close().catch(()=>{})}}async function s(z,J,V,Q){let K=A.get(z);if(!O&&K&&await c(J,K.entry)===K.identity)return K;A.delete(z);let W=T.get(z);if(W)return W;let Y=(async()=>{let N=await(Q.discover??a)(J,V,Q);if(!N)return null;let G=await Xz(J,N);if(!G)return{entry:N,identity:""};let X={entry:N,identity:G};return A.set(z,X),X})();T.set(z,Y);try{return await Y}finally{if(T.get(z)===Y)T.delete(z)}}async function d(z,J,V,Q=i){return new Promise((K)=>{let W,Y=!1,N=!1,G=($,Z=!1)=>{if(Y)return;Y=!0,clearTimeout(X),W?.destroy(),K({value:$,stale:Z})},X=setTimeout(()=>G(null),Q);try{let $=JSON.stringify(V);W=Vz({host:"127.0.0.1",port:z.port}),W.on("connect",()=>{N=!0,W?.write(`POST /rpc/${J} HTTP/1.0\r
1
+ import{if as O,jf as U,mf as b,nf as m,of as L,sf as y}from"./index-mg4w434p.js";import{createHash as Zz,randomUUID as v}from"node:crypto";import{chmod as t,mkdir as r,open as e,readdir as j,rename as zz,rmdir as Gz,stat as Jz,unlink as S}from"node:fs/promises";import{join as R,resolve as D}from"node:path";function l(z){return typeof z==="number"&&Number.isSafeInteger(z)&&z>0}function F(z){if(!l(z))return!1;try{return process.kill(z,0),!0}catch(J){return J.code==="EPERM"}}function Cz(z){return(J)=>Kz(J,z)}function Kz(z,J){if(/^[0-9a-f]{16}$/.test(z))return!0;return z.startsWith(J)&&/^[0-9a-f]{16}$/.test(z.slice(J.length))}function Nz(z){let J=/^port-(\d+)\.json$/.exec(z);return J?Number(J[1]):void 0}function p(z,J){if(z===null||typeof z!=="object"||Array.isArray(z))return!1;let{pid:V,port:Q,token:K}=z;return l(V)&&Nz(J)===V&&typeof Q==="number"&&Number.isInteger(Q)&&Q>=1&&Q<=65535&&typeof K==="string"&&K.length>0}async function h(z,J){J?.debug("rpc corrupt port file",{pid:process.pid,portFile:z}),await S(z).catch(()=>{})}async function Az(z,J,V={}){let Q=async()=>{let K=R(z,`port-${J.pid}.json`);if(O)return await m(z,V.secureDir??!1),await V.beforeWrite?.(),await y(K,JSON.stringify({...J,startedAt:Date.now()}),{stagePath:`${K}.${(V.stageName??v)()}.tmp`}),K;if(await r(z,{recursive:!0,mode:V.secureDir?448:void 0}),V.secureDir)await t(z,448);await V.beforeWrite?.();let W={...J,startedAt:Date.now()},Y=`${K}.${(V.stageName??v)()}.tmp`,N,G=!1;try{N=await e(Y,"wx",384),G=!0,await N.writeFile(JSON.stringify(W),"utf8"),await N.chmod(384),await N.close(),N=void 0,await zz(Y,K),G=!1}finally{if(await N?.close().catch(()=>{}),G)await S(Y).catch(()=>{})}return K};try{return await Q()}catch(K){if(K.code==="ENOENT")return await Q();throw K}}async function Oz(z,J,V,Q){let K;try{K=await j(z,{withFileTypes:!0})}catch(Y){if(Y.code==="ENOENT")return;throw Y}let W=D(J);for(let Y of K){if(!Y.isDirectory()||!V(Y.name))continue;let N=R(z,Y.name),G;try{G=await j(N)}catch(X){if(X.code==="ENOENT")continue;throw X}for(let X of G){if(!X.startsWith("port-")||!X.endsWith(".json"))continue;let $=R(N,X),Z;try{Z=await L($)}catch(H){if(H instanceof U&&H.code!=="ENOENT")throw H;continue}if(Z===void 0)continue;let q;try{q=JSON.parse(Z)}catch{await h($,Q);continue}if(!p(q,X)){await h($,Q);continue}if(!F(q.pid))await S($).catch(()=>{})}if(D(N)!==W)await Gz(N).catch(()=>{})}}async function c(z,J){if(!F(J.pid))return null;let V=R(D(z),`port-${J.pid}.json`);try{if(O)await b(V,"file");let Q=await Jz(V);return`${V}:${Q.dev}:${Q.ino}:${Q.mtimeMs}:${Q.size}`}catch(Q){if(Q instanceof U&&Q.code!=="ENOENT")throw Q;return null}}async function a(z,J,V={}){let Q;try{if(O)await b(z,"directory");Q=await j(z)}catch(G){if(G instanceof U&&G.code!=="ENOENT")throw G;return null}let K=[];for(let G of Q){if(!G.startsWith("port-")||!G.endsWith(".json"))continue;try{let X=JSON.parse(await L(R(z,G)));if(p(X,G))if(F(X.pid))K.push(X);else await S(R(z,G)).catch(()=>{})}catch(X){if(X instanceof U&&X.code!=="ENOENT")throw X}}if(K.length===0)return null;let W=J!==void 0&&J>=1?K.filter((G)=>G.pid===J):[];if(V.exactPid===!0&&W.length===0)return null;let Y=W.length>0?W:K,N=(G)=>typeof G.startedAt==="number"&&Number.isFinite(G.startedAt)?G.startedAt:-1/0;return Y.sort((G,X)=>N(X)-N(G))[0]??null}import{open as Qz}from"node:fs/promises";import{connect as Vz}from"node:net";import{join as Wz,resolve as o}from"node:path";var i=2000,A=new Map,T=new Map;async function Xz(z,J){let V=Wz(o(z),`port-${J.pid}.json`);if(O){let K=JSON.parse(await L(V));if(K.pid!==J.pid||K.port!==J.port||K.token!==J.token)return null;return null}let Q;try{Q=await Qz(V,"r");let K=await Q.stat(),W=JSON.parse(await Q.readFile("utf8"));if(W.pid!==J.pid||W.port!==J.port||W.token!==J.token)return null;return`${V}:${K.dev}:${K.ino}:${K.mtimeMs}:${K.size}`}catch{return null}finally{await Q?.close().catch(()=>{})}}async function s(z,J,V,Q){let K=A.get(z);if(!O&&K&&await c(J,K.entry)===K.identity)return K;A.delete(z);let W=T.get(z);if(W)return W;let Y=(async()=>{let N=await(Q.discover??a)(J,V,Q);if(!N)return null;let G=await Xz(J,N);if(!G)return{entry:N,identity:""};let X={entry:N,identity:G};return A.set(z,X),X})();T.set(z,Y);try{return await Y}finally{if(T.get(z)===Y)T.delete(z)}}async function d(z,J,V,Q=i){return new Promise((K)=>{let W,Y=!1,N=!1,G=($,Z=!1)=>{if(Y)return;Y=!0,clearTimeout(X),W?.destroy(),K({value:$,stale:Z})},X=setTimeout(()=>G(null),Q);try{let $=JSON.stringify(V);W=Vz({host:"127.0.0.1",port:z.port}),W.on("connect",()=>{N=!0,W?.write(`POST /rpc/${J} HTTP/1.0\r
2
2
  Host: 127.0.0.1:${z.port}\r
3
3
  Connection: close\r
4
4
  Content-Type: application/json\r
@@ -9,4 +9,4 @@ Authorization: Bearer ${z.token}\r
9
9
  \r
10
10
  `);if(B>=0)C=B+4;if((C??_.length)>16384)return G(null);if(C!==void 0){let x=_.subarray(0,B).toString("latin1").split(`\r
11
11
  `),f=/^HTTP\/1\.[01] (\d{3})(?: |$)/.exec(x[0]??"");if(!f)return G(null);let w=Number(f[1]);if(w<200||w>=300)return G(null,[401,403,404,410].includes(w));for(let M of x.slice(1)){let k=M.indexOf(":"),u=M.slice(0,k).toLowerCase(),P=M.slice(k+1).trim();if(u==="transfer-encoding")return G(null);if(u==="content-length"){if(H!==void 0||!/^\d+$/.test(P))return G(null);if(H=Number(P),!Number.isSafeInteger(H)||H>8388608)return G(null)}}_=Buffer.alloc(0)}}let I=q-(C??q);if(I>8388608)return G(null);if(H!==void 0){if(I>H)return G(null);if(I===H)g()}}),W.on("end",()=>{if(H!==void 0&&q-(C??0)!==H)return G(null);g()}),W.on("error",()=>G(null,!N)),W.on("close",()=>G(null))}catch{G(null,!N)}})}async function n(z,J,V,Q,K,W,Y=i){let N=JSON.stringify([o(z),J??null,V.exactPid===!0]),G=await s(N,z,J,V);if(Q(G?.entry??null),!G)return null;let X=Date.now()+Y,$=await d(G.entry,K,W,Y);if(!$.stale)return $.value;if(A.get(N)===G)A.delete(N);let Z=await s(N,z,J,V);if(!Z||Date.now()>=X)return null;if(Z.entry.port===G.entry.port&&Z.entry.pid===G.entry.pid&&Z.entry.token===G.entry.token){if(A.get(N)===Z)A.delete(N);return null}let q=await d(Z.entry,K,W,X-Date.now());if(q.stale&&A.get(N)===Z)A.delete(N);return q.value}function Tz(z,J,V,Q={}){let K={exactPid:Q.exactPid,discover:Q.discover},W=!1,Y=(N)=>{if(W)return;V?.(N),W=!0};return{async pending(N,G,X){return(await n(z,J,K,Y,"pending-notifications",{lastReceivedId:N,sessionId:G},X))?.messages??[]},async apply(N,G){return await n(z,J,K,Y,"apply",{...N},G)??{text:"apply failed",knobs:{}}}}}
12
- export{Cz as Qe,Az as Re,Oz as Se,a as Te,i as Ue,Tz as Ve};
12
+ export{Cz as Re,Az as Se,Oz as Te,a as Ue,i as Ve,Tz as We};
@@ -0,0 +1,2 @@
1
+ import{Hc as NZ,Ic as PZ,Kc as g,Lc as WZ,Mc as HZ,Pc as d,ne as _Z,qe as TZ,se as RZ}from"./index-b7p76qqa.js";import{Ae as XZ,Fe as VZ,Ge as YZ,He as y,Ie as x}from"./index-73z9ftrg.js";import{$e as OZ}from"./index-h1r8cbet.js";import{if as b,jf as $Z,nf as A,of as JZ}from"./index-mg4w434p.js";import{createHash as cZ}from"node:crypto";import{constants as oZ,copyFileSync as aZ,mkdirSync as iZ,statSync as sZ}from"node:fs";import{readFile as nZ}from"node:fs/promises";import{homedir as eZ,tmpdir as tZ}from"node:os";import{dirname as Z0,join as h}from"node:path";import{chmod as dZ,mkdir as lZ}from"node:fs/promises";import{dirname as ZZ}from"node:path";function k(Z){let{path:$,defaultValue:V,normalize:J}=Z,X=Promise.resolve(),Y=(B)=>{if(B==="")return V;try{return J(JSON.parse(B))}catch{return V}},G=async()=>{try{if(b)await A(ZZ($),Z.secureDir??!0);return await JZ($,b)}catch(B){if(B.code==="ENOENT")return"";throw B}},z=async()=>{try{return Y(await G())}catch(B){if(B instanceof $Z)throw B;return V}},U=(B,D)=>{let N=X.then(B).then((P)=>D?.onResult?.(P));return X=N.catch(()=>{}),N},L={...x.sidebar,name:Z.lockName??x.sidebar.name,timeoutMs:Z.timeoutMs??x.sidebar.timeoutMs},j=async(B,D,N)=>{await XZ($,D,{serialize:JSON.stringify,beforeRename:async()=>{await N?.beforeCommit?.(),await B.assertOwned()}}),await N?.afterRename?.();try{return await B.assertOwned(),!0}catch(P){if(P instanceof YZ)return!1;throw P}},Q=async(B,D,N)=>{Z.logger?.warn("sidebar lock lost after rename; repairing write",{path:$});try{let P=await y($,L,async(W)=>{let H=B(await z(),D);if(H===void 0)return"skipped";return await j(W,H,N)?"written":"lost-again"});if(P==="lost-again")Z.logger?.warn("sidebar repair lost its lock after rename",{path:$});return{status:"lost-after-rename",repair:P}}catch(P){if(!(P instanceof VZ))throw P;return Z.logger?.warn("sidebar repair lock unavailable; repair skipped",{path:$}),{status:"lost-after-rename",repair:"lock-unavailable"}}},K=async(B,D)=>{let N=D,P=ZZ($),W=Z.secureDir??!0;if(b)await A(P,W);else if(await lZ(P,{recursive:!0,mode:448}),W)await dZ(P,448).catch((F)=>{Z.logger?.warn("sidebar directory permission remediation failed",{error:F instanceof Error?F.message:String(F)})});let H=await y($,L,async(F)=>{let s=async(C)=>({value:C,held:await j(F,C,N)});for(let C=0;C<3;C+=1){let e=await G(),t=B(Y(e));if(t===void 0)return;if(C===0)await N?.beforeRecheck?.();if(await G()!==e)continue;return await s(t)}let n=B(await z());return n===void 0?void 0:await s(n)});if(H===void 0)return{status:"skipped"};if(H.held)return{status:"written"};let i=D?.repair??Z.repair;if(!i)return Z.logger?.warn("sidebar lock lost after rename; write not repaired",{path:$}),{status:"lost-after-rename",repair:"none"};return await Q(i,H.value,N)};return{read:z,write:(B,D)=>U(()=>K(()=>B,D),D),update:(B,D)=>U(()=>K(B,D),D)}}function v0(Z){let $=Z?.credits;if($===null||typeof $!=="object")return;let{hasCredits:V,unlimited:J,balance:X}=$;if(typeof V!=="boolean"||typeof J!=="boolean")return;return WZ({hasCredits:V,unlimited:J,...typeof X==="number"?{balance:X}:{}})}function f0(Z,$=Date.now()){if(!xZ(Z,$))return!1;if(bZ(Z,$))return!1;return RZ(Z?.credits,$)}var l=["primary","secondary"],uZ={primary:300,secondary:10080};function rZ(Z,$){return NZ({scope:"all",label:$,windowMinutes:Z})}function S0(Z){if(!Z)return[];let $=[];for(let V of l){let J=Z[V];if(!J)continue;let X=J.windowMinutes,Y=X!==void 0&&Number.isFinite(X)&&X>0?X:uZ[V];$.push({key:V,label:rZ(X,V),window:J,windowMs:Y*60000})}return $}var M=OZ("sidebar"),$0="OPENCODE_OPENAI_AUTH_SIDEBAR_STATE_FILE";function CZ(){let Z=process.env.XDG_STATE_HOME||h(eZ(),".local","state");return h(Z,"cortexkit","openai-auth","sidebar-state.json")}var FZ=h(tZ(),"opencode-openai-auth","sidebar-state.json");function g0(Z){FZ=Z,p.clear()}var J0=/^[a-f0-9]{64}$/,u=604800000,MZ=256,EZ=3600000;function T(Z){return cZ("sha256").update(Z).digest("hex")}function X0(Z){return typeof Z==="number"&&Number.isFinite(Z)&&Z>=0?Z:void 0}function qZ(Z){let $=X0(Z);return $!==void 0?{resetCredits:$}:{}}function V0(Z){if(Z===null||typeof Z!=="object"||Array.isArray(Z))return;let $={};for(let[V,J]of Object.entries(Z)){if(J===null||typeof J!=="object"||Array.isArray(J))continue;let X=J;if(typeof X.activeId!=="string"||typeof X.route!=="string"||typeof X.updatedAt!=="number"||!Number.isFinite(X.updatedAt))continue;$[V]={activeId:X.activeId,route:X.route,updatedAt:X.updatedAt}}return Object.keys($).length>0?$:void 0}function Y0(Z){if(Z===null||typeof Z!=="object"||Array.isArray(Z))return;let $={};for(let[V,J]of Object.entries(Z)){if(!J0.test(V)||J===null||typeof J!=="object"||Array.isArray(J))continue;let X=J;if(typeof X.accountId!=="string"||X.accountId.length===0||typeof X.assignedAt!=="number"||!Number.isFinite(X.assignedAt)||X.assignedAt<0||typeof X.lastSeenAt!=="number"||!Number.isFinite(X.lastSeenAt)||X.lastSeenAt<0||typeof X.inputBytes!=="number"||!Number.isFinite(X.inputBytes)||X.inputBytes<0)continue;let Y=X.quotaCheckedAt;if(Y!==void 0&&(typeof Y!=="number"||!Number.isFinite(Y)||Y<0))continue;let G=X.wireAccountId;$[V]={accountId:X.accountId,assignedAt:X.assignedAt,lastSeenAt:X.lastSeenAt,inputBytes:X.inputBytes,...Y===void 0?{}:{quotaCheckedAt:Y},...typeof G==="string"?{wireAccountId:G}:{}}}return Object.keys($).length>0?$:void 0}function O(){let Z=process.env[$0];if(Z)return Z;let $=CZ();if(!p.has($))p.add($),z0($,FZ);return $}var p=new Set;function z0(Z,$){try{iZ(Z0(Z),{recursive:!0,mode:448}),aZ($,Z,oZ.COPYFILE_EXCL)}catch{}}var q={main:{quota:null,killed:!1},fallbacks:[],activeId:void 0,route:"main",lastUpdated:0};function S(Z){if(Z===null||typeof Z!=="object"||Array.isArray(Z))return q;let $=Z,V=$.main,J;if(V!==null&&typeof V==="object"&&!Array.isArray(V)){let K=V;J={quota:"quota"in K?K.quota:null,killed:typeof K.killed==="boolean"?K.killed:!1,...typeof K.mainAccountId==="string"?{mainAccountId:K.mainAccountId}:{},...typeof K.quotaBackedOff==="boolean"?{quotaBackedOff:K.quotaBackedOff}:{},...typeof K.quotaBackoffUntil==="number"?{quotaBackoffUntil:K.quotaBackoffUntil}:{},...typeof K.refreshBackedOff==="boolean"?{refreshBackedOff:K.refreshBackedOff}:{},...typeof K.refreshBackoffUntil==="number"?{refreshBackoffUntil:K.refreshBackoffUntil}:{},...qZ(K.resetCredits)}}else J={quota:null,killed:!1};let X=zZ($.fallbacks),Y=Array.isArray($.vaultAccounts)?zZ($.vaultAccounts):void 0,G=typeof $.activeId==="string"?$.activeId:void 0,z=typeof $.route==="string"?$.route:q.route,U=typeof $.lastUpdated==="number"?$.lastUpdated:0,L=typeof $.planType==="string"?$.planType:void 0,j=V0($.activeRouting),Q=Y0($.stickyAssignments);return{main:J,fallbacks:X,activeId:G,route:z,lastUpdated:U,...j!==void 0?{activeRouting:j}:{},...Q!==void 0?{stickyAssignments:Q}:{},...L!==void 0?{planType:L}:{},...$.accountPool===!0?{accountPool:!0}:{},...Y!==void 0?{vaultAccounts:Y}:{},...typeof $.vaultDiscovered==="boolean"?{vaultDiscovered:$.vaultDiscovered}:{}}}function zZ(Z){if(!Array.isArray(Z))return[];return Z.filter(($)=>$!==null&&typeof $==="object"&&!Array.isArray($)&&typeof $.id==="string").map(($)=>({id:$.id,...typeof $.credentialId==="string"?{credentialId:$.credentialId}:{},label:typeof $.label==="string"?$.label:void 0,...typeof $.accountId==="string"?{accountId:$.accountId}:{},quota:"quota"in $?$.quota:null,killed:typeof $.killed==="boolean"?$.killed:!1,enabled:typeof $.enabled==="boolean"?$.enabled:!0,...typeof $.routable==="boolean"?{routable:$.routable}:{},...["needs sign-in","turned off in vault","unavailable"].includes($.vaultState)?{vaultState:$.vaultState}:{},...qZ($.resetCredits)}))}function r(Z){return[...Z.fallbacks,...Z.vaultAccounts??[]]}async function G0(Z=O()){try{let $=await nZ(Z,"utf8");return S(JSON.parse($))}catch{return q}}var K0=3600000,GZ=128;function IZ(Z,$,V=Date.now()){if(!(Z.updatedAt>=V-K0&&Z.updatedAt<=V))return!1;if($===void 0)return!0;return Z.activeId==="main"||$.some((X)=>X.enabled!==!1&&X.routable!==!1&&X.killed!==!0&&X.id===Z.activeId)}function bZ(Z,$=Date.now()){let V=Z?.spendControl;if(V?.reached!==!0||typeof V.resetsAt!=="string")return;let J=Date.parse(V.resetsAt);if(!Number.isFinite(J)||J<=$)return;return{resetsAt:V.resetsAt,resetAtMs:J}}function xZ(Z,$=Date.now()){let V;for(let X of l){let Y=Z?.[X];if(typeof Y?.resetsAt!=="string"||!Number.isFinite(Y.usedPercent)||Y.usedPercent<100)continue;let G=Date.parse(Y.resetsAt);if(!Number.isFinite(G)||G<=$)continue;if(!V||G<V.resetAtMs)V={resetsAt:Y.resetsAt,resetAtMs:G}}let J=bZ(Z,$);if(J&&(!V||J.resetAtMs<V.resetAtMs))V=J;return V}function E(Z,$=Date.now()){return xZ(Z,$)!==void 0}function j0(Z,$,V=Date.now()){if(!$||Z.route!=="sticky-balanced")return;let J=Z.stickyAssignments?.[T($)];if(!J||J.lastSeenAt<V-u)return;if(J.accountId==="main"&&Z.vaultAccounts===void 0)return Z.main?.killed||E(Z.main?.quota,V)?void 0:"main";let X=r(Z).find((Y)=>Y.id===J.accountId);if(!X||X.enabled===!1||X.routable===!1||X.killed===!0||E(X.quota,V))return;return X.id}function d0(Z,$,V=Date.now()){if(!$){if(Z.vaultAccounts===void 0)return{activeId:Z.activeId??"main",route:Z.route};let j=Z.vaultAccounts.find((Q)=>Q.id===Z.activeId&&Q.enabled&&Q.routable!==!1&&!Q.killed);if(j&&!E(j.quota,V))return{activeId:j.id,route:Z.route}}let J=$?Z.activeRouting?.[$]:void 0,X=r(Z),Y=J?.activeId==="main"?Z.main.quota:X.find((j)=>j.id===J?.activeId)?.quota;if(J&&(Z.vaultAccounts===void 0||J.activeId.startsWith("vault:"))&&IZ(J,X,V)&&!E(Y,V))return{activeId:J.activeId,route:J.route};let G=j0(Z,$,V);if(G)return{activeId:G,route:Z.route};let z=Z.vaultAccounts!==void 0,U=(z?c(Z):Z.fallbacks).filter((j)=>j.enabled&&j.routable!==!1&&!j.killed),L=U.find((j)=>!E(j.quota,V))??U[0];return{activeId:z?L?.id??"vault":Z.route==="fallback-first"&&L?L.id:"main",route:Z.route}}function c(Z){let $=Z.vaultAccounts??[],V=new Map($.map((J)=>[J.id,J]));return d($.map((J)=>J.id),gZ(Z),_Z($)??"").flatMap((J)=>{let X=V.get(J);return X?[X]:[]})}function vZ(Z,$,V=Date.now(),J){if(!Z)return;let X=Object.entries(Z).filter(([G,z])=>G!==J&&IZ(z,$,V)),Y=X.length<=GZ?X:X.sort((G,z)=>z[1].updatedAt-G[1].updatedAt).slice(0,GZ);return Y.length>0?Object.fromEntries(Y):void 0}function I(Z,$,V=Date.now(),J){if(!Z)return;let X=0,Y=0,G=0,z=[];for(let[L,j]of Object.entries(Z)){if(L===J){G+=1;continue}if(j.lastSeenAt<V-u){Y+=1;continue}if($!==void 0&&!$.has(j.accountId)){X+=1;continue}z.push([L,j])}let U=X+Y+G;if(U>0)M.debug("pruned sticky assignments",{pid:process.pid,removed:U,reasons:{"account-not-in-roster":X,expired:Y,"explicit-removal":G}});return z.length>0?Object.fromEntries(z):void 0}function fZ(Z,$){let V=Object.keys(Z).length-MZ;if(V<=0)return Z;let J=new Set(Object.entries(Z).filter(([X])=>X!==$).sort(([X,Y],[G,z])=>Y.lastSeenAt-z.lastSeenAt||X.localeCompare(G)).slice(0,V).map(([X])=>X));return Object.fromEntries(Object.entries(Z).filter(([X])=>!J.has(X)))}function SZ(Z,$){if(Z===$)return!0;if(!Z||!$)return!1;let V=Object.entries(Z);if(V.length!==Object.keys($).length)return!1;return V.every(([J,X])=>Object.is($[J],X))}function AZ(Z,$,V,J){return Z!==void 0&&$.has(Z.accountId)&&!V.has(Z.accountId)&&Z.lastSeenAt>=J-u}function yZ(Z,$,V,J){return $>Z.inputBytes||V-Z.lastSeenAt>=EZ||Z.wireAccountId===void 0&&J!==void 0}function kZ(Z,$){return typeof Z.wireAccountId==="string"&&typeof $==="string"&&Z.wireAccountId!==$}function L0(Z){let $=new Map(Z),V={get size(){return $.size},has:(J)=>$.has(J),get:(J)=>$.get(J),entries:()=>$.entries(),keys:()=>$.keys(),values:()=>$.values(),forEach:(J,X)=>{$.forEach((Y,G)=>{J.call(X,Y,G,V)})},[Symbol.iterator]:()=>$[Symbol.iterator]()};return Object.freeze(V)}function B0(Z,$,V){let J=new Map;for(let[X,Y]of Object.entries(Z??{})){if(X===V)continue;if(Y.quotaCheckedAt!==$[Y.accountId])continue;J.set(Y.accountId,(J.get(Y.accountId)??0)+Y.inputBytes)}return L0(J)}function o(Z){if(Z===void 0)return;return new Set(["main",...Z.filter(($)=>$.enabled!==!1&&$.killed!==!0).map(($)=>$.id)])}var m=Promise.resolve();function _(Z){let $=m.then(Z);return m=$.catch(()=>{}),$}var KZ=new Map;function a(Z){let $=KZ.get(Z);if(!$)$=k({path:Z,defaultValue:q,normalize:S,secureDir:Z===CZ(),logger:M}),KZ.set(Z,$);return $}var w=new Set;async function wZ(Z,$){try{await $}catch(V){let J={pid:process.pid,error:V instanceof Error?V.message:String(V)};if(w.has(Z))M.debug("sidebar write failed again",J);else w.add(Z),M.warn("sidebar write failed",J);throw V}if(w.delete(Z))M.info("sidebar write recovered",{pid:process.pid})}function l0(Z,$=O()){return _(()=>wZ($,a($).write(S(Z))))}function U0(Z){return a(Z).read()}function R(Z,$,V){let J=Symbol("sidebar authority changed");return wZ(Z,a(Z).update((X)=>{if(V?.canWrite&&!V.canWrite())return;let Y=$(X);if(Y===void 0)return;if(Y.vaultAccounts!==void 0)Y.activeId=Y.activeId?.startsWith("vault:")?Y.activeId:void 0,Y.activeRouting=Object.fromEntries(Object.entries(Y.activeRouting??{}).filter(([,G])=>G.activeId.startsWith("vault:"))),Y.stickyAssignments=Object.fromEntries(Object.entries(Y.stickyAssignments??{}).filter(([,G])=>G.accountId.startsWith("vault:")&&!Y.vaultAccounts?.some((z)=>z.id===G.accountId&&z.killed)));return S(Y)},{beforeRecheck:async(...X)=>{if(await V?.beforeRecheck?.(...X),V?.canWrite&&!V.canWrite())throw J}}).catch((X)=>{if(X!==J)throw X}))}function v(Z){let $;for(let V of[Z?.primary?.checkedAt,Z?.secondary?.checkedAt,Z?.checkedAt])if(typeof V==="number"&&Number.isFinite(V))$=$===void 0?V:Math.max($,V);return $}function jZ(Z,$){let V=v(Z),J=v($);if(J!==void 0&&(V===void 0||J>V))return $;return Z}function LZ(Z,$){return Z!==void 0&&$!==void 0&&Z===$}function f(Z,$){let V=Z?.checkedAt;if(typeof V==="number"&&Number.isFinite(V))return V;if(typeof $==="number"&&Number.isFinite($))return $;return}function BZ(Z,$,V,J,X){if(Z&&$){let Y=f(Z,J),G=f($,X);if(G!==void 0&&(Y===void 0||G>Y))return $;return Z}return V?$:Z}function UZ(Z,$){if(Z.spendControl!==void 0)return Z.spendControl;if(Z.spendControlCleared===!0)return;return $.spendControl}function Q0(Z,$){if(!Z||!$)return Z??$;let V=(J)=>typeof J.checkedAt==="number"&&Number.isFinite(J.checkedAt)?J.checkedAt:Number.NEGATIVE_INFINITY;return V($)>V(Z)?$:Z}function QZ(Z,$){if(!Z)return $;if(!$)return Z;let V=v(Z),J=v($),X=J!==void 0&&(V===void 0||J>V),Y=BZ(Z.primary,$.primary,X,Z.checkedAt,$.checkedAt),G=BZ(Z.secondary,$.secondary,X,Z.checkedAt,$.checkedAt),z=X?UZ($,Z):UZ(Z,$),U=z===void 0&&(Z.spendControlCleared===!0||$.spendControlCleared===!0),L=Q0(Z.credits,$.credits),j;for(let N of[f(Y),f(G)])if(N!==void 0)j=j===void 0?N:Math.max(j,N);let{spendControl:Q,spendControlCleared:K,credits:B,...D}=Z;return{...D,primary:Y,secondary:G,...z!==void 0?{spendControl:z}:{},...U?{spendControlCleared:!0}:{},...L!==void 0?{credits:L}:{},checkedAt:j??Z.checkedAt}}function u0(Z,$=O(),V){return _(async()=>{await R($,(J)=>{let X=new Map(J.fallbacks.map((j)=>[j.id,j])),Y=Z.vaultAccounts!==void 0,G=LZ(Z.main.mainAccountId,J.main.mainAccountId),z=G?QZ(Z.main.quota,J.main.quota):jZ(Z.main.quota,J.main.quota),U=Date.now(),L=I(J.stickyAssignments,Y?void 0:o(r(Z)),U);return{...J,...Z,main:Y?Z.main:{...Z.main,quota:z,mainAccountId:G?Z.main.mainAccountId:z===J.main.quota&&z!==Z.main.quota?J.main.mainAccountId:Z.main.mainAccountId},fallbacks:Y?Z.fallbacks:Z.fallbacks.map((j)=>{let Q=X.get(j.id),K=LZ(j.accountId,Q?.accountId),B=K?QZ(j.quota,Q?.quota??null):jZ(j.quota,Q?.quota??null);return{...j,quota:B,accountId:K?j.accountId:B===Q?.quota&&B!==j.quota?Q?.accountId:j.accountId}}),activeId:J.activeId,activeRouting:J.activeRouting,stickyAssignments:L,lastUpdated:Math.max(U,J.lastUpdated+1),accountPool:Z.accountPool===!0?!0:void 0,vaultAccounts:Z.vaultAccounts,vaultDiscovered:Z.vaultDiscovered}},V)})}function r0(Z,$,V=O(),J){return _(async()=>{await R(V,(X)=>{let Y=vZ({...X.activeRouting,[Z.sessionId]:{activeId:Z.activeId,route:Z.route,updatedAt:Z.updatedAt}},$,Date.now()),G=I(X.stickyAssignments,X.vaultAccounts!==void 0?void 0:o($),Date.now());return{...X,activeId:Z.activeId,route:Z.route,activeRouting:Y,stickyAssignments:G,lastUpdated:Math.max(Date.now(),X.lastUpdated+1)}},J)})}function c0(Z,$=O(),V){return _(async()=>{await R($,(J)=>({...J,activeId:Z.activeId,route:Z.route,lastUpdated:Math.max(Date.now(),J.lastUpdated+1)}),V)})}function o0(Z,$,V=O(),J){return _(async()=>{await R(V,(X)=>{let Y=Date.now(),G=vZ(X.activeRouting,$,Y,Z),z=I(X.stickyAssignments,X.vaultAccounts!==void 0?void 0:o($),Y,T(Z));return{...X,activeRouting:G,stickyAssignments:z,lastUpdated:Math.max(Date.now(),X.lastUpdated+1)}},J)})}function hZ(Z,$){return AZ(Z,new Set($.validPinnedAccountIds),new Set($.excludeAccountIds),$.now)&&!kZ(Z,$.wireAccountIdByAccount?.[Z.accountId])&&!yZ(Z,$.requestBytes,$.now,$.wireAccountIdByAccount?.[Z.accountId])}function pZ(Z,$){let V=T($.sessionId),J=new Set($.validPinnedAccountIds),X=new Set($.excludeAccountIds),Y=I(Z.stickyAssignments,J,$.now),G=!SZ(Z.stickyAssignments,Y),z=Y?.[V],U=z!==void 0&&kZ(z,$.wireAccountIdByAccount?.[z.accountId]);if(AZ(z,J,X,$.now)&&!U){let Q=yZ(z,$.requestBytes,$.now,$.wireAccountIdByAccount?.[z.accountId]),K=Q?{...z,inputBytes:Math.max(z.inputBytes,$.requestBytes),...z.wireAccountId===void 0&&$.wireAccountIdByAccount?.[z.accountId]!==void 0?{wireAccountId:$.wireAccountIdByAccount?.[z.accountId]}:{},...$.now-z.lastSeenAt>=EZ?{lastSeenAt:$.now}:{}}:z;if(!G&&!Q)return{assignment:K,next:void 0};return{assignment:K,next:{...Z,stickyAssignments:{...Y,[V]:K},lastUpdated:Math.max($.now,Z.lastUpdated+1)}}}let L=$.choose(B0(Y,$.quotaCheckedAtByAccount,U?V:void 0));if(!L){if(!G)return{assignment:void 0,next:void 0};return{assignment:void 0,next:{...Z,stickyAssignments:Y,lastUpdated:Math.max($.now,Z.lastUpdated+1)}}}let j={accountId:L.accountId,assignedAt:$.now,lastSeenAt:$.now,inputBytes:$.requestBytes,...L.quotaCheckedAt===void 0?{}:{quotaCheckedAt:L.quotaCheckedAt},...$.wireAccountIdByAccount?.[L.accountId]===void 0?{}:{wireAccountId:$.wireAccountIdByAccount?.[L.accountId]}};return{assignment:j,next:{...Z,stickyAssignments:fZ({...Y,[V]:j},V),lastUpdated:Math.max($.now,Z.lastUpdated+1)}}}async function a0(Z,$=O(),V){let J=T(Z.sessionId),X=(await U0($)).stickyAssignments?.[J];if(hZ(X,Z))return X;let Y;return await _(async()=>{await R($,(G)=>{let z=pZ(G,Z);return Y=z.assignment,z.next},V)}),Y}function i0(Z,$){let V=Z.stickyAssignments?.[T($.sessionId)];if(hZ(V,$))return{assignment:V,next:void 0};return pZ(Z,$)}function s0(Z,$=O()){let V=T(Z.sessionId),J=new Set(Z.validPinnedAccountIds);return _(async()=>{await R($,(X)=>{let Y=Date.now(),G=I(X.stickyAssignments,X.vaultAccounts!==void 0?void 0:J,Y),z=G?.[V];if(z&&z.assignedAt>Z.assignment.assignedAt){if(SZ(X.stickyAssignments,G))return;return{...X,stickyAssignments:G,lastUpdated:Math.max(Y,X.lastUpdated+1)}}let L=z!==void 0&&z.accountId===Z.assignment.accountId&&z.assignedAt===Z.assignment.assignedAt?{...Z.assignment,inputBytes:Math.max(z.inputBytes,Z.assignment.inputBytes),lastSeenAt:Math.max(z.lastSeenAt,Z.assignment.lastSeenAt)}:Z.assignment;return{...X,stickyAssignments:fZ({...G,[V]:L},V),lastUpdated:Math.max(Y,X.lastUpdated+1)}})})}async function n0(Z,$=O()){let V=T(Z),J=!1;return await _(async()=>{await R($,(X)=>{let Y=X.stickyAssignments;if(Y?.[V]===void 0){J=!1;return}J=!0;let{[V]:G,...z}=Y;return{...X,...Object.keys(z).length>0?{stickyAssignments:z}:{stickyAssignments:void 0},lastUpdated:Math.max(Date.now(),X.lastUpdated+1)}})}),J}function e0(){return m}var D0=500;function N0(Z,$,V){return new Promise((J,X)=>{let Y=setTimeout(()=>J(V()),$);Y.unref?.(),Z.then((G)=>{clearTimeout(Y),J(G)},(G)=>{clearTimeout(Y),X(G)})})}function t0(Z,$={}){let V=$.readBudgetMs??D0,J,X,Y=()=>{try{let z=sZ(Z);return`${z.ino}:${z.size}:${z.mtimeMs}`}catch{return}},G=(z)=>{if(X&&X.key===z)return X.promise;let U=Date.now(),L=G0(Z).then((K)=>{if(!J||J.readAt<=U)J={state:K,readAt:U,key:z};return{state:K,readAt:U}}),j={key:z,promise:L};X=j;let Q=()=>{if(X===j)X=void 0};return L.then(Q,Q),L};return{get(){let z=Y();if(J&&J.key===z)return Promise.resolve({state:J.state,readAt:J.readAt});return N0(G(z),V,()=>J?{state:J.state,readAt:J.readAt}:{state:q,readAt:0})},read(){return G(Y())},refreshInBackground(){let z=Y();if(J?.key===z)return;G(z)}}}function Z1(Z,$,V){let J={assignment:V};Z.delete($),Z.set($,J);while(Z.size>MZ){let X=Z.keys().next().value;if(X===void 0)break;Z.delete(X)}return J}function $1(Z,$){if($.size===0)return Z.state;let V={...Z.state.stickyAssignments},J=!1;for(let[X,Y]of $){if(Y.persistedAt!==void 0&&Z.readAt>Y.persistedAt){$.delete(X);continue}V[X]=Y.assignment,J=!0}if(!J)return Z.state;return{...Z.state,stickyAssignments:V}}function J1(Z){let $=Z.retryDelayMs??500,V=Z.maxRetryDelayMs??30000,J=new Map,X=new Map,Y=new Set,G=0,z=$,U,L=!1,j=()=>{if(U||L||X.size===0)return;U=setTimeout(()=>{U=void 0;let K=[...X];X.clear(),z=Math.min(z*2,V);for(let[B,D]of K){let N=J.get(B);if(N!==void 0)Q(B,D.label,D.write,N)}},z),U.unref?.()},Q=(K,B,D,N)=>{let P;try{P=D()}catch(W){P=Promise.reject(W)}P.then(()=>{if(J.get(K)!==N)return;if(J.delete(K),Y.delete(K))Z.logger.info("sidebar bookkeeping write recovered",{pid:process.pid,write:B});if(Y.size===0)z=$;Z.onWritten?.()},(W)=>{if(J.get(K)!==N)return;let H={pid:process.pid,write:B,error:W instanceof Error?W.message:String(W)};if(L){J.delete(K),Z.logger.debug("sidebar bookkeeping write dropped",H);return}if(Y.has(K))Z.logger.debug("sidebar bookkeeping write failed again",H);else Y.add(K),Z.logger.warn("sidebar bookkeeping write failed; retrying in the background",H);X.set(K,{label:B,write:D}),j()})};return{enqueue(K,B,D){G+=1,J.set(K,G),X.delete(K),Q(K,B,D,G)},cancel(K){J.delete(K),X.delete(K),Y.delete(K)},stop(){if(L=!0,U)clearTimeout(U);U=void 0,X.clear()}}}function P0(Z){let $=Z.activeId;if(Z.vaultAccounts!==void 0){let V=c(Z).filter((X)=>X.enabled&&X.routable!==!1),J=V.find((X)=>X.id===$)??V[0];return J?{id:J.id,name:J.label??J.id,quota:J.quota,killed:J.killed}:{id:"vault",name:"vault",quota:null,killed:!1}}if($&&$!=="main"){let V=Z.fallbacks.find((J)=>J.enabled&&J.id===$);if(V)return{id:V.id,name:V.label??V.id,quota:V.quota,killed:V.killed}}return{id:"main",name:"main",quota:Z.main.quota,killed:Z.main.killed}}function mZ(Z,$=Date.now()){if(!Z)return;return HZ({limits:l.flatMap((V)=>{let J=Z[V];return J?[{kind:"reading",scope:"all",label:V,usedPercent:J.usedPercent,checkedAt:J.checkedAt??Z.checkedAt??$,windowMinutes:J.windowMinutes,resetsAt:J.resetsAt}]:[]}),...Z.spendControl?{budget:{...Z.spendControl,kind:"reading",checkedAt:Z.checkedAt??$}}:{}})}function X1(Z,$=Date.now()){let V=Z?.primary?.usedPercent??null,J=Z?.secondary?.usedPercent??null,X=mZ(Z,$);return{primaryUsedPercent:V,secondaryUsedPercent:J,text:!X||X.limits.length===0&&!X.budget?null:g(X,{now:$,form:"compact"})}}function gZ(Z){return Z.route==="sticky-balanced"?"roster":TZ(Z.route)}function V1(Z,$={}){let V=$.now??Date.now(),J=P0(Z).id;return(Z.vaultAccounts!==void 0?c(Z).map((Y)=>({id:Y.id,name:Y.label??Y.id,quota:Y.quota,killed:Y.killed})):W0(Z,J,$.showFallbacks??!0)).map((Y)=>{let G=mZ(Y.quota,V),z=G&&(G.limits.length>0||G.budget)?G:void 0;return{id:Y.id,name:Y.name,killed:Y.killed,active:Y.id===J,stale:z?PZ(z,{now:V}):!1,text:z?g(z,{now:V,form:"narrow"}):null}})}function W0(Z,$,V){let J=[{id:"main",name:"main",quota:Z.main.quota,killed:Z.main.killed},...Z.fallbacks.filter((Y)=>Y.enabled&&(V||Y.id===$)).map((Y)=>({id:Y.id,name:Y.label??Y.id,quota:Y.quota,killed:Y.killed}))],X=new Map(J.map((Y)=>[Y.id,Y]));return d(J.map((Y)=>Y.id),gZ(Z),"main").flatMap((Y)=>{let G=X.get(Y);return G?[G]:[]})}function DZ(Z){let $=globalThis.Bun;return $?.stringWidth?$.stringWidth(Z):Array.from(Z).length}function Y1(Z,$){if(DZ(Z)<=$)return Z;if($<1)return"";let V="",J=0;for(let X of Z){let Y=DZ(X);if(J+Y>$-1)break;V+=X,J+=Y}return`${V}…`}var H0=300000,O0=0.01,_0=1;function z1(Z,$,V){if(!Z.resetsAt)return null;let J=new Date(Z.resetsAt).getTime();if(!Number.isFinite(J))return null;let X=J-$,Y=V-X;if(Y<H0)return null;if(Y<$*O0)return null;if(Y>=$)return null;let G=Z.usedPercent,z=Math.min(Math.max(Y/$*100,0),100),U=G-z,L=Math.abs(U)<_0?"on-pace":U>0?"deficit":"reserve",j=null;if(G>0){let Q=Y*100/G,K=X+Q;if(K<J)j=new Date(K).toISOString()}return{pacePercent:z,deltaPercent:U,state:L,runsOutAt:j}}
2
+ export{v0 as Mb,f0 as Nb,rZ as Ob,S0 as Pb,g0 as Qb,u as Rb,MZ as Sb,T as Tb,O as Ub,q as Vb,S as Wb,G0 as Xb,K0 as Yb,GZ as Zb,IZ as _b,bZ as $b,xZ as ac,E as bc,j0 as cc,d0 as dc,vZ as ec,I as fc,l0 as gc,u0 as hc,r0 as ic,c0 as jc,o0 as kc,pZ as lc,a0 as mc,i0 as nc,s0 as oc,n0 as pc,e0 as qc,D0 as rc,N0 as sc,t0 as tc,Z1 as uc,$1 as vc,J1 as wc,P0 as xc,mZ as yc,X1 as zc,V1 as Ac,DZ as Bc,Y1 as Cc,z1 as Dc};
@@ -1,8 +1,8 @@
1
- import{hf as H,if as q,jf as V0,lf as x,mf as h,nf as S,of as w,pf as _0,rf as b}from"./index-5dxpsa3t.js";import{randomUUID as T}from"node:crypto";import{mkdir as H0,open as B0,readFile as Q0,rename as W0,rm as L,stat as Y0}from"node:fs/promises";import{dirname as P,join as Z0}from"node:path";function N0($,G){return`${$}.${G}.lock`}class G0 extends Error{details;constructor($){super(`Timed out acquiring ${$.name} lock for ${$.target}`);this.name="LockContentionError",this.details=$}}class f extends Error{details;constructor($){super(`Lost ${$.name} lock for ${$.target}`);this.name="LockOwnershipError",this.details=$}}async function A0($,G,Q){let Y=performance.now();for(;;){G.signal?.throwIfAborted();let Z=await K0({path:$,name:G.name,ttlMs:G.ttlMs,renew:G.renew??!1,...G.onStep?{onStep:G.onStep}:{},...G.onRenewalTimer?{onRenewalTimer:G.onRenewalTimer}:{}});if(Z)try{return G.signal?.throwIfAborted(),await Q(Z)}finally{await Z.release()}let J=G.timeoutMs-(performance.now()-Y);if(J<=0)throw new G0({target:$,name:G.name,timeoutMs:G.timeoutMs});await new Promise((_)=>setTimeout(_,Math.min(25,Math.ceil(J))))}}async function J0($,G){let Q=await B0($,"wx",384);try{await Q.writeFile(G,"utf8")}finally{await Q.close()}}var D0=globalThis.setTimeout.bind(globalThis),U0=globalThis.clearTimeout.bind(globalThis);function q0($){let G=$?.code;return G==="ENOENT"||!H&&(G==="EINVAL"||G==="ENOTDIR")}function K0($){return x0({...$,now:Date.now})}async function x0($){let G=N0($.path,$.name),Q=Z0(G,"owner.json"),Y=T(),Z=$.now??Date.now,J=null,_=!1,D=!1,B,l,j0=new Promise((z)=>{l=z});function p(z){try{let K=$.onRenewalTimer?.(z);if(K&&(typeof K==="object"||typeof K==="function")&&"then"in K&&typeof K.then==="function")Promise.resolve(K).catch(()=>{})}catch{}}function d(){if(!J)return;U0(J),J=null,p("cancelled")}function g(z,K){if(B||_)return;B=Object.freeze({reason:z,expectedOwnerId:Y,...typeof K?.ownerId==="string"?{observedOwnerId:K.ownerId}:{},...typeof K?.expiresAt==="number"?{observedExpiresAt:K.expiresAt}:{}}),d(),l(B)}let E,R=null,C=`${G}.evicting`,M=Z0(C,"owner.json"),a=T(),g0=5000,y=8;async function j(){if(H)try{return JSON.parse(await S(G,!0))}catch(z){if(z.code!=="EISDIR"&&z.reason!=="wrong-kind")throw z;return await x(G,"directory",!0),JSON.parse(await S(Q,!0))}try{return JSON.parse(await Q0(G,"utf8"))}catch(z){if(z.code!=="EISDIR")throw z;return JSON.parse(await Q0(Q,"utf8"))}}async function C0(){if(H){let W=await j(),V=Number(W?.expiresAt)-Z();await b(G,`${JSON.stringify({ownerId:Y,expiresAt:Z()+$.ttlMs})}
1
+ import{if as H,jf as q,kf as V0,mf as x,nf as h,of as S,pf as w,qf as _0,sf as b}from"./index-mg4w434p.js";import{randomUUID as T}from"node:crypto";import{mkdir as H0,open as B0,readFile as Q0,rename as W0,rm as L,stat as Y0}from"node:fs/promises";import{dirname as P,join as Z0}from"node:path";function N0($,G){return`${$}.${G}.lock`}class G0 extends Error{details;constructor($){super(`Timed out acquiring ${$.name} lock for ${$.target}`);this.name="LockContentionError",this.details=$}}class f extends Error{details;constructor($){super(`Lost ${$.name} lock for ${$.target}`);this.name="LockOwnershipError",this.details=$}}async function A0($,G,Q){let Y=performance.now();for(;;){G.signal?.throwIfAborted();let Z=await K0({path:$,name:G.name,ttlMs:G.ttlMs,renew:G.renew??!1,...G.onStep?{onStep:G.onStep}:{},...G.onRenewalTimer?{onRenewalTimer:G.onRenewalTimer}:{}});if(Z)try{return G.signal?.throwIfAborted(),await Q(Z)}finally{await Z.release()}let J=G.timeoutMs-(performance.now()-Y);if(J<=0)throw new G0({target:$,name:G.name,timeoutMs:G.timeoutMs});await new Promise((_)=>setTimeout(_,Math.min(25,Math.ceil(J))))}}async function J0($,G){let Q=await B0($,"wx",384);try{await Q.writeFile(G,"utf8")}finally{await Q.close()}}var D0=globalThis.setTimeout.bind(globalThis),U0=globalThis.clearTimeout.bind(globalThis);function q0($){let G=$?.code;return G==="ENOENT"||!H&&(G==="EINVAL"||G==="ENOTDIR")}function K0($){return x0({...$,now:Date.now})}async function x0($){let G=N0($.path,$.name),Q=Z0(G,"owner.json"),Y=T(),Z=$.now??Date.now,J=null,_=!1,D=!1,B,l,j0=new Promise((z)=>{l=z});function p(z){try{let K=$.onRenewalTimer?.(z);if(K&&(typeof K==="object"||typeof K==="function")&&"then"in K&&typeof K.then==="function")Promise.resolve(K).catch(()=>{})}catch{}}function d(){if(!J)return;U0(J),J=null,p("cancelled")}function g(z,K){if(B||_)return;B=Object.freeze({reason:z,expectedOwnerId:Y,...typeof K?.ownerId==="string"?{observedOwnerId:K.ownerId}:{},...typeof K?.expiresAt==="number"?{observedExpiresAt:K.expiresAt}:{}}),d(),l(B)}let E,R=null,C=`${G}.evicting`,M=Z0(C,"owner.json"),a=T(),g0=5000,y=8;async function j(){if(H)try{return JSON.parse(await S(G,!0))}catch(z){if(z.code!=="EISDIR"&&z.reason!=="wrong-kind")throw z;return await x(G,"directory",!0),JSON.parse(await S(Q,!0))}try{return JSON.parse(await Q0(G,"utf8"))}catch(z){if(z.code!=="EISDIR")throw z;return JSON.parse(await Q0(Q,"utf8"))}}async function C0(){if(H){let W=await j(),V=Number(W?.expiresAt)-Z();await b(G,`${JSON.stringify({ownerId:Y,expiresAt:Z()+$.ttlMs})}
2
2
  `,{deadline:performance.now()+Math.max(0,V),beforeRename:async()=>{let I=await j();if(I?.ownerId!==Y||!(Number(I?.expiresAt)>Z())||!await X())throw new f({target:$.path,name:$.name})}});return}let z=`${G}.${T()}.tmp`,K,N=!1;try{K=await B0(z,"wx",384),N=!0,await K.writeFile(`${JSON.stringify({ownerId:Y,expiresAt:Z()+$.ttlMs})}
3
3
  `,"utf8"),await K.chmod(384),await K.close(),K=void 0;let W=await j();if(W?.ownerId!==Y||!(Number(W?.expiresAt)>Z())||!await X())throw new f({target:$.path,name:$.name});await W0(z,G),N=!1}finally{if(await K?.close().catch(()=>{}),N)await L(z,{force:!0}).catch(()=>{})}}async function s(){let z=`${JSON.stringify({ownerId:Y,expiresAt:Z()+$.ttlMs})}
4
4
  `;if(H)await w(G,z);else await J0(G,z)}async function n(z){let K=z.code;if(K!=="EEXIST"&&K!=="EISDIR")return!1;if(H){if($.onStep)await $.onStep("lease-contention-read-ready");try{if(K==="EISDIR")await x(G,"directory",!0),await S(Q,!0);else await j()}catch(N){if(N.code!=="ENOENT")throw N}}return!0}async function k(){if(H)await h(P(G));try{return await s(),!0}catch(z){let K=z.code;if(await n(z))return!1;if(K==="ENOENT"){if(H)await h(P(G));else await H0(P(G),{recursive:!0});try{return await s(),!0}catch(N){if(await n(N))return!1;throw N}}throw z}}async function O(){await new Promise((z)=>setTimeout(z,Math.floor(Math.random()*4)))}async function m(z=!0){if(z&&$.onStep)await $.onStep("lock-read-ready");let K;try{K=await j()}catch(W){if(H&&W.code!=="ENOENT")throw W}let N=Number(K?.expiresAt);if(Number.isFinite(N)&&N>Z())return{status:"live"};if(typeof K?.ownerId==="string"&&Number.isFinite(N))return{status:"stale",identity:{kind:"owner",ownerId:K.ownerId,expiresAt:N}};try{let W=await Y0(G),V=Number.isFinite(N)?N:W.mtimeMs+$.ttlMs;if(V>Z())return{status:"live"};return{status:"stale",identity:{kind:"stat",dev:W.dev,ino:W.ino,mtimeMs:W.mtimeMs,expiresAt:V}}}catch(W){if(W.code==="ENOENT"){if($.onStep)await $.onStep("lock-missing");return{status:"missing"}}throw W}}function i(z,K){if(K.status!=="stale")return!1;let N=K.identity;if(z.kind==="owner"&&N.kind==="owner")return z.ownerId===N.ownerId&&z.expiresAt===N.expiresAt;return z.kind==="stat"&&N.kind==="stat"&&z.dev===N.dev&&z.ino===N.ino&&z.mtimeMs===N.mtimeMs&&z.expiresAt===N.expiresAt}async function X(){try{return JSON.parse(await S(M,H))?.ownerId===a}catch(z){if(H&&z.code!=="ENOENT")throw z;return!1}}async function A(z){if(H)await V0(z,"remove",()=>L(z,{recursive:!0,force:!0}));else await L(z,{recursive:!0,force:!0}).catch(()=>{})}async function u(){if(await X())await A(C)}async function t(){if(H)await _0(C);else await H0(C);try{let z=`${JSON.stringify({ownerId:a,createdAt:Z()})}
5
5
  `;if(H)await w(M,z);else await J0(M,z)}catch(z){if(q0(z))return!1;throw await u(),z}if($.onStep)await $.onStep("eviction-marker-acquired");return!0}async function r(){let z;try{z=await Y0(C)}catch(N){if(N.code==="ENOENT")return"missing";throw N}if(H)await x(C,"directory",!0);if(z.mtimeMs+g0>Z())return"fresh";if($.onStep)await $.onStep("stale-marker-stat");let K=`${C}.${T()}`;try{await W0(C,K)}catch(N){if(N.code==="ENOENT")return"missing";throw N}if($.onStep)await $.onStep("stale-marker-claimed");return await A(K),"recovered"}async function o(z){try{if(!await t())return!1}catch(K){if(K.code==="EEXIST"){if(H){await x(C,"directory",!0);try{await S(M,!0)}catch(N){if(N.code!=="ENOENT")throw N}}return!1}throw K}try{await z()}finally{await u()}return!0}async function e(){for(let z=0;z<y;z++){if($.onStep)await $.onStep("relinquish-read");let K;try{K=await j()}catch(N){if(H)throw N;return}if(K?.ownerId!==Y)return;try{await L(G,{recursive:!0,force:!0});return}catch(N){if(H)throw N;await O()}}}function $0(){if(!$.renew||_||B)return;let z=$.renewIntervalMs??Math.max(1000,Math.floor($.ttlMs/3));if(J=D0(()=>{J=null;let K=(async()=>{let N=!_;try{if(!await o(async()=>{let V=await j(),I=Z();if(_||B){N=!1;return}if(V?.ownerId!==Y){g("taken-over",V),N=!1;return}if(!(Number(V?.expiresAt)>I)){g("expired",V),N=!1;return}if($.onStep)await $.onStep("renewal-owner-confirmed");if(_||B){N=!1;return}if(!await X())return;if($.onStep)await $.onStep("renewal-write-fenced");if(_||B){N=!1;return}if(!await X())return;if($.onStep)await $.onStep("renewal-write-ready");if(_||B){N=!1;return}if(await C0(),$.onStep)await $.onStep("renewal-write-finished");if(!await X()){g("marker-lost"),N=!1,await e();return}})&&$.onStep)await $.onStep("renewal-marker-unavailable")}catch(W){if(H&&W instanceof q)E=W,g("renewal-failed"),N=!1;try{let V=await j();if(V?.ownerId!==Y)g("taken-over",V);else if(!(Number(V?.expiresAt)>Z()))g("expired",V)}catch{g("renewal-failed")}}finally{if($.onStep)try{await $.onStep("renewal-finished")}catch{}if(N&&!_&&!B)$0()}})();R=K,K.finally(()=>{if(R===K)R=null})},z),"unref"in J)J.unref();p("scheduled")}function z0(){try{let z=$.onContended?.();if(z&&(typeof z==="object"||typeof z==="function")&&"then"in z&&typeof z.then==="function")Promise.resolve(z).catch(()=>{})}catch{}return null}let U=await k();if(!U)for(let z=0;z<y;z++){if(U=await k(),U)break;let K=await m();if(K.status==="live")return z0();if(K.status==="missing")continue;if($.onStep)await $.onStep("stale-lock-observed");try{if(!await t()){await O();continue}}catch(N){if(N.code!=="EEXIST")throw N;if(await r()==="fresh")return null;await O();continue}try{let N=await m();if(N.status==="live")return z0();if(!i(K.identity,N))continue;if(!await X())return null;if($.onStep)await $.onStep("stale-lock-confirmed");if(!await X())return null;let W=await m(!1);if(!i(K.identity,W))continue;if(await A(G),!await X())return null;if($.onStep)await $.onStep("stale-lock-removed");if(U=await k(),!U)return null;if($.onStep)await $.onStep("stale-lock-recreated");if(!await X())return await e(),U=!1,null;break}finally{await u()}}if(!U)return null;return $0(),{ownerId:Y,whenLost:()=>j0,hasLost:()=>B!==void 0,assertOwned:async()=>{if(E)throw E;let z;try{let K=await j();if(z=K,!_&&!B&&K?.ownerId===Y&&Number(K?.expiresAt)>Z())return;g(K?.ownerId!==Y?"taken-over":"expired",K)}catch(K){if(g("unreadable"),H&&K instanceof q)throw K}throw new f({target:$.path,name:$.name,expectedOwnerId:Y,...typeof z?.ownerId==="string"?{observedOwnerId:z.ownerId}:{},...typeof z?.expiresAt==="number"?{observedExpiresAt:z.expiresAt}:{}})},release:async()=>{if(H&&D)return;_=!0,d(),await R;for(let z=0;z<y;z++){try{let K=!1;if(await o(async()=>{let W;try{W=await j()}catch(V){if(H&&V.code==="ENOENT"){K=!0;return}throw V}if(W?.ownerId!==Y){K=!0;return}if($.onStep)await $.onStep("release-owner-confirmed");if(!await X())return;await A(G),K=!0})){if(H&&!K)throw new q(G,"release-not-confirmed",{code:"EIO"});D=K;return}await r()}catch(K){if(H)throw K;return}await O()}if(H)throw new q(G,"release-not-confirmed",{code:"ETIMEDOUT"})}}}import{randomUUID as X0}from"node:crypto";import{mkdir as S0,open as F,rename as f0,rm as R0}from"node:fs/promises";import{dirname as v}from"node:path";class c extends Error{constructor($){super("file or directory sync failed",{cause:$});this.name="AtomicSyncError"}}async function h0($,G,Q={}){await M0($,G,Q)}async function M0($,G,Q,Y){if(H)return b($,Q.serialize?Q.serialize(G):`${JSON.stringify(G,null,2)}
6
6
  `,{beforeRename:Q.beforeRename,stagePath:`${$}.${(Q.stageName??X0)()}.tmp`,onRenamed:Y,durable:Q.durable,durability:Q.durability,onOutcome:Q.onOutcome});await S0(v($),{recursive:!0});let Z=`${$}.${(Q.stageName??X0)()}.tmp`,J,_=!1;try{if(J=await F(Z,"wx",384),_=!0,await J.writeFile(Q.serialize?Q.serialize(G):`${JSON.stringify(G,null,2)}
7
7
  `,"utf8"),await J.chmod(384),Q.durable)try{await J.sync()}catch(D){throw new c(D)}if(await J.close(),J=void 0,await Q.beforeRename?.(),await f0(Z,$),_=!1,Y?.(),Q.durable){let D=await F(v($),"r");try{await D.sync()}catch(B){throw new c(B)}finally{await D.close()}}}finally{if(await J?.close().catch(()=>{}),_)await R0(Z,{force:!0}).catch(()=>{})}}async function w0($){if(H){await x($,"file");let Y=new q($,"directory-sync-unsupported",{code:"ENOTSUP"});throw Y.published=!0,Y}let G=await F($,"r");try{await G.sync()}finally{await G.close()}let Q=await F(v($),"r");try{await Q.sync()}finally{await Q.close()}}var c0=Object.freeze({sidebar:Object.freeze({name:"sidebar-write",ttlMs:1e4,timeoutMs:15000,renew:!0}),preferences:Object.freeze({name:"preferences",ttlMs:1e4,timeoutMs:2000,renew:!0})});
8
- export{c as ye,h0 as ze,M0 as Ae,w0 as Be,K0 as Ce,N0 as De,G0 as Ee,f as Fe,A0 as Ge,c0 as He};
8
+ export{c as ze,h0 as Ae,M0 as Be,w0 as Ce,K0 as De,N0 as Ee,G0 as Fe,f as Ge,A0 as He,c0 as Ie};