@cortexkit/opencode-openai-auth 1.20.0 → 1.20.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/bin.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{c as q2}from"./index-z1hz7e5y.js";import{Aa as H0,Ba as a,Ca as $2,Gc as D2,Ma as t0,Na as l,Oa as F,Pa as u,ac as G2,sc as j2,ya as F0,za as s}from"./index-d5er9yht.js";import{Ge as W2,Zd as g,_d as e,ae as y0,ce as r0,de as n,ee as A,fe as n0,ge as i,he as C0,ie as f0}from"./index-3898z307.js";import"./index-7tkppvqd.js";import"./index-wy84wezx.js";import"./index-74mg470w.js";import{Bg as x0,Dg as U0,Gg as X2}from"./index-pdsqgqng.js";import{Ig as R0,Mg as A0}from"./index-xbh03w1v.js";import"./index-asjkhkty.js";import"./index-62xhtkv8.js";import"./index-r6k6hh93.js";import{spawn as B2}from"node:child_process";var N=4096,V2=1048576;class O0{buffer=Buffer.alloc(N);start=0;length=0;truncated=!1;get didTruncate(){return this.truncated}push(z){if(z.length>=N){if(z.length>N||this.length>0)this.truncated=!0;z.copy(this.buffer,0,z.length-N),this.start=0,this.length=N;return}let J=Math.max(0,this.length+z.length-N);if(J>0)this.truncated=!0;this.start=(this.start+J)%N,this.length-=J;let Z=(this.start+this.length)%N,$=Math.min(z.length,N-Z);if(z.copy(this.buffer,Z,0,$),$<z.length)z.copy(this.buffer,0,$);this.length+=z.length}toString(){let z=Buffer.alloc(this.length),J=Math.min(this.length,N-this.start);if(this.buffer.copy(z,0,this.start,this.start+J),J<this.length)this.buffer.copy(z,J,0,this.length-J);let Z=0;while(Z<z.length){let $=z[Z];if($===void 0||($&192)!==128)break;Z++}return z.subarray(Z).toString("utf8")}}var w={run(z,J,Z={}){return new Promise(($)=>{let K=performance.now(),Q=Z.timeoutMs??15000,W=new O0,G=[],V=0,X=!1,q=!1,b=!1,x;try{x=B2(z,[...J],{env:Z.env??process.env,windowsHide:!0,windowsVerbatimArguments:Z.windowsVerbatimArguments,stdio:["ignore","pipe","pipe"]})}catch{$({exitCode:1,stdout:"",stderr:"",spawnError:!0,signal:null,timedOut:!1,durationMs:performance.now()-K});return}let Y=Q>0?setTimeout(()=>{b=!0,x.kill("SIGTERM")},Q):void 0;x.stdout?.on("data",(j)=>{let U=V2-V,O=Math.min(U,j.length);if(O>0)G.push(j.subarray(0,O)),V+=O;if(j.length>U)X=!0,x.kill("SIGTERM")}),x.stderr?.on("data",(j)=>W.push(j));let H=!1,D=(j,U)=>{if(H)return;if(H=!0,Y)clearTimeout(Y);$({exitCode:q?1:X?1:j??1,stdout:Buffer.concat(G,V).toString("utf8"),stderr:W.toString(),stderrTruncated:W.didTruncate,...q?{spawnError:!0}:{},signal:U??null,timedOut:b,durationMs:performance.now()-K})};x.once("error",()=>{if(q=!0,x.pid===void 0)D(null,null)}),x.once("close",(j,U)=>D(j,U))})}};function o(z,J,Z,$,K,Q=15000){if(J==="win32"&&/\.(cmd|bat)$/i.test(Z)){if(/["%!\r\n]/.test(Z)||$.some((W)=>!/^[a-zA-Z0-9@:/._+-]+$/.test(W)))throw Error("Unsafe batch launcher or argument; use an executable instead.");return z.run("cmd.exe",["/d","/s","/c",`""${Z}" ${$.join(" ")}"`],{env:K,timeoutMs:Q,windowsVerbatimArguments:!0})}return z.run(Z,$,{env:K,timeoutMs:Q})}function I0(z){if(/^[a-zA-Z0-9_:@./-]+$/.test(z))return z;return process.platform==="win32"?`'${z.replaceAll("'","''")}'`:`'${z.replaceAll("'","'\\''")}'`}async function h(z,J,Z,$){let K=J.requestedGrants??$;if(!K)return;let Q=K.map((G)=>({grant:G,...J.approvedName!==void 0&&{grantCommand:`ck auth grant --principal ${I0(`enrolled:${J.approvedName}`)} --selector-kind ${G.selector.exact===void 0?"category":"exact"} --selector ${I0(G.selector.exact??G.selector.category)} --operation ${G.operation}`}})),W={grants:Q,...J.requestedGrantsStatus!==void 0&&{requestedGrantsStatus:J.requestedGrantsStatus}};if(J.requestedGrantsStatus==="dropped")return{...W,state:"older-vault"};try{if(!z.listScoped)return{...W,state:"unconfirmed"};let{token:G}=await C0(Z),V=await z.listScoped(G),X=Q.map((q)=>({...q,reachableLogins:V.rows.filter((b)=>b.operations.includes(q.grant.operation)&&(q.grant.selector.exact!==void 0?b.id===q.grant.selector.exact:b.categories.includes(q.grant.selector.category))).length}));return{...W,state:X.every((q)=>q.reachableLogins>0)?"reachable":X.some((q)=>q.reachableLogins>0)?"partial":"no-logins",grants:X.map((q)=>{if(q.reachableLogins===0)return q;let{grantCommand:b,...x}=q;return x})}}catch{return{...W,state:"unconfirmed"}}}function m(z,J="setup"){if(J==="plugin"&&z.requestedGrantsStatus!=="sent")return[];let Z=[],$=z.grants.some((K)=>K.grantCommand)?"run:":"check ck auth status for the approved name before granting access.";if(z.state==="older-vault")Z.push(`Approved. This vault is too old to grant access with the approval; ${$}`);else if(z.state==="no-logins")Z.push(`Approved, but no logins are reachable yet; ${$}`);else if(z.state==="partial")Z.push(`Approved, but some requested access has no reachable logins yet; ${$}`);else if(z.state==="unconfirmed")Z.push(`Approved, but access could not be confirmed; ${z.grants.some((K)=>K.grantCommand)?"check ck auth status or run:":$}`);for(let{grant:K,reachableLogins:Q,grantCommand:W}of z.grants){if(Q!==void 0&&Q>0){let G=K.selector.exact===void 0?`the vault's ${JSON.stringify(K.selector.category)} accounts`:`credential ${JSON.stringify(K.selector.exact)}`;Z.push(`Confirmed ${K.operation} access to ${G} (${Q} reachable ${Q===1?"login":"logins"}).`)}if(W)Z.push(` ${W}`)}return Z}var x2="Pi install failed; run pi install after checking your npm connection.";function U2(z){let J=Buffer.from(z,"utf8");if(J.length<=N)return z;let Z=J.length-N;while(Z<J.length){let $=J[Z];if($===void 0||($&192)!==128)break;Z++}return J.subarray(Z).toString("utf8")}function F2(z){let J=z.indexOf(`
2
+ import{c as q2}from"./index-38xyx9nd.js";import{Aa as s,Ba as H0,Ca as a,Da as $2,Jc as D2,Na as t0,Oa as l,Pa as F,Qa as u,dc as G2,vc as j2,za as F0}from"./index-rbc7cfbv.js";import{Je as W2,ae as g,be as e,de as y0,fe as r0,ge as n,he as A,ie as n0,je as i,ke as C0,le as f0}from"./index-x3q449sn.js";import"./index-z4tfv40j.js";import"./index-jky7c65x.js";import"./index-a1zh72v8.js";import{Eg as x0,Gg as U0,Jg as X2}from"./index-0mf78d7s.js";import{Lg as R0,Pg as A0}from"./index-xcsz00nr.js";import"./index-c4h4t3wg.js";import"./index-qtaqp1bf.js";import"./index-t15pb3n2.js";import{spawn as B2}from"node:child_process";var N=4096,V2=1048576;class O0{buffer=Buffer.alloc(N);start=0;length=0;truncated=!1;get didTruncate(){return this.truncated}push(z){if(z.length>=N){if(z.length>N||this.length>0)this.truncated=!0;z.copy(this.buffer,0,z.length-N),this.start=0,this.length=N;return}let J=Math.max(0,this.length+z.length-N);if(J>0)this.truncated=!0;this.start=(this.start+J)%N,this.length-=J;let Z=(this.start+this.length)%N,$=Math.min(z.length,N-Z);if(z.copy(this.buffer,Z,0,$),$<z.length)z.copy(this.buffer,0,$);this.length+=z.length}toString(){let z=Buffer.alloc(this.length),J=Math.min(this.length,N-this.start);if(this.buffer.copy(z,0,this.start,this.start+J),J<this.length)this.buffer.copy(z,J,0,this.length-J);let Z=0;while(Z<z.length){let $=z[Z];if($===void 0||($&192)!==128)break;Z++}return z.subarray(Z).toString("utf8")}}var w={run(z,J,Z={}){return new Promise(($)=>{let K=performance.now(),Q=Z.timeoutMs??15000,W=new O0,G=[],V=0,X=!1,q=!1,b=!1,x;try{x=B2(z,[...J],{env:Z.env??process.env,windowsHide:!0,windowsVerbatimArguments:Z.windowsVerbatimArguments,stdio:["ignore","pipe","pipe"]})}catch{$({exitCode:1,stdout:"",stderr:"",spawnError:!0,signal:null,timedOut:!1,durationMs:performance.now()-K});return}let Y=Q>0?setTimeout(()=>{b=!0,x.kill("SIGTERM")},Q):void 0;x.stdout?.on("data",(j)=>{let U=V2-V,O=Math.min(U,j.length);if(O>0)G.push(j.subarray(0,O)),V+=O;if(j.length>U)X=!0,x.kill("SIGTERM")}),x.stderr?.on("data",(j)=>W.push(j));let H=!1,D=(j,U)=>{if(H)return;if(H=!0,Y)clearTimeout(Y);$({exitCode:q?1:X?1:j??1,stdout:Buffer.concat(G,V).toString("utf8"),stderr:W.toString(),stderrTruncated:W.didTruncate,...q?{spawnError:!0}:{},signal:U??null,timedOut:b,durationMs:performance.now()-K})};x.once("error",()=>{if(q=!0,x.pid===void 0)D(null,null)}),x.once("close",(j,U)=>D(j,U))})}};function o(z,J,Z,$,K,Q=15000){if(J==="win32"&&/\.(cmd|bat)$/i.test(Z)){if(/["%!\r\n]/.test(Z)||$.some((W)=>!/^[a-zA-Z0-9@:/._+-]+$/.test(W)))throw Error("Unsafe batch launcher or argument; use an executable instead.");return z.run("cmd.exe",["/d","/s","/c",`""${Z}" ${$.join(" ")}"`],{env:K,timeoutMs:Q,windowsVerbatimArguments:!0})}return z.run(Z,$,{env:K,timeoutMs:Q})}function I0(z){if(/^[a-zA-Z0-9_:@./-]+$/.test(z))return z;return process.platform==="win32"?`'${z.replaceAll("'","''")}'`:`'${z.replaceAll("'","'\\''")}'`}async function h(z,J,Z,$){let K=J.requestedGrants??$;if(!K)return;let Q=K.map((G)=>({grant:G,...J.approvedName!==void 0&&{grantCommand:`ck auth grant --principal ${I0(`enrolled:${J.approvedName}`)} --selector-kind ${G.selector.exact===void 0?"category":"exact"} --selector ${I0(G.selector.exact??G.selector.category)} --operation ${G.operation}`}})),W={grants:Q,...J.requestedGrantsStatus!==void 0&&{requestedGrantsStatus:J.requestedGrantsStatus}};if(J.requestedGrantsStatus==="dropped")return{...W,state:"older-vault"};try{if(!z.listScoped)return{...W,state:"unconfirmed"};let{token:G}=await C0(Z),V=await z.listScoped(G),X=Q.map((q)=>({...q,reachableLogins:V.rows.filter((b)=>b.operations.includes(q.grant.operation)&&(q.grant.selector.exact!==void 0?b.id===q.grant.selector.exact:b.categories.includes(q.grant.selector.category))).length}));return{...W,state:X.every((q)=>q.reachableLogins>0)?"reachable":X.some((q)=>q.reachableLogins>0)?"partial":"no-logins",grants:X.map((q)=>{if(q.reachableLogins===0)return q;let{grantCommand:b,...x}=q;return x})}}catch{return{...W,state:"unconfirmed"}}}function m(z,J="setup"){if(J==="plugin"&&z.requestedGrantsStatus!=="sent")return[];let Z=[],$=z.grants.some((K)=>K.grantCommand)?"run:":"check ck auth status for the approved name before granting access.";if(z.state==="older-vault")Z.push(`Approved. This vault is too old to grant access with the approval; ${$}`);else if(z.state==="no-logins")Z.push(`Approved, but no logins are reachable yet; ${$}`);else if(z.state==="partial")Z.push(`Approved, but some requested access has no reachable logins yet; ${$}`);else if(z.state==="unconfirmed")Z.push(`Approved, but access could not be confirmed; ${z.grants.some((K)=>K.grantCommand)?"check ck auth status or run:":$}`);for(let{grant:K,reachableLogins:Q,grantCommand:W}of z.grants){if(Q!==void 0&&Q>0){let G=K.selector.exact===void 0?`the vault's ${JSON.stringify(K.selector.category)} accounts`:`credential ${JSON.stringify(K.selector.exact)}`;Z.push(`Confirmed ${K.operation} access to ${G} (${Q} reachable ${Q===1?"login":"logins"}).`)}if(W)Z.push(` ${W}`)}return Z}var x2="Pi install failed; run pi install after checking your npm connection.";function U2(z){let J=Buffer.from(z,"utf8");if(J.length<=N)return z;let Z=J.length-N;while(Z<J.length){let $=J[Z];if($===void 0||($&192)!==128)break;Z++}return J.subarray(Z).toString("utf8")}function F2(z){let J=z.indexOf(`
3
3
  `);return J<0?"":z.slice(J+1)}class r extends Error{step="pi-install";exitCode;signal;stderrTail;constructor(z){super(x2);this.name="SetupCommandError",this.exitCode=z.exitCode,this.signal=z.signal;let J=z.stderrTruncated?F2(z.stderrTail):z.stderrTail,Z=R0(J);this.stderrTail=U2(typeof Z==="string"?Z:"")}}var H2={opencode:"OpenCode",pi:"Pi"},M2={enrolled:"connected to the vault","not-enrolled":"not connected",unknown:"unknown, check with ck auth status"};function N0({host:z,outcome:J,access:Z},$="setup"){let K=Z?m(Z,$):[];return`${H2[z]}: ${M2[J]}${K.length?` — ${K.join(`
4
4
  `)}`:""}`}var O2=new WeakMap;function k0(z,J){if(typeof z!=="object"&&typeof z!=="function"||!z)return;O2.set(z,Object.freeze(J.map((Z)=>Object.freeze({...Z}))))}import{accessSync as k2,constants as _2,existsSync as T2,readFileSync as P2,realpathSync as A2,statSync as L2}from"node:fs";import{mkdtemp as w2,rm as S2}from"node:fs/promises";import{tmpdir as v2}from"node:os";import{join as E2}from"node:path";import{parse as y2}from"jsonc-parser";import{homedir as I2}from"node:os";import{posix as C2,win32 as R2}from"node:path";import{fileURLToPath as N2}from"node:url";function k(z={}){let J=z.env??process.env,Z=z.platform??process.platform,$=Z==="win32"?R2:C2,K=z.home??(Z==="win32"?J.USERPROFILE:J.HOME)??I2(),Q=z.cwd??process.cwd(),W=(q)=>$.resolve(Q,q),G=J.OPENCODE_CONFIG_DIR?.trim(),V=J.XDG_CONFIG_HOME?.trim(),X=J.PI_CODING_AGENT_DIR?.trim()||$.join(K,".pi","agent");if(X==="~")X=K;else if(/^~[/\\]/.test(X))X=$.join(K,X.slice(2));if(X.startsWith("file://"))X=N2(X);return{env:J,platform:Z,path:$,home:K,cwd:Q,opencode:G?W(G):V?$.join(W(V),"opencode"):$.join(K,".config","opencode"),pi:W(X)}}function K0(z,J){try{return L2(z)[J]()}catch{return!1}}var S={exists:T2,isFile:(z)=>K0(z,"isFile"),isDirectory:(z)=>K0(z,"isDirectory"),isExecutable(z){try{return k2(z,_2.X_OK),K0(z,"isFile")}catch{return!1}},readText:(z)=>P2(z,"utf8"),realpath:A2};function P(z,J={}){let{env:Z,platform:$,path:K,cwd:Q}=k(J),W=J.fs??S,G=Object.entries(Z).find(([X])=>$==="win32"?X.toUpperCase()==="PATH":X==="PATH")?.[1]??"",V=$==="win32"?[".exe",".cmd",".bat",""]:[""];for(let X of G.split($==="win32"?";":":")){let q=X.trim().replace(/^"|"$/g,"");if(!q)continue;for(let b of V){let x=K.resolve(Q,q,z+b);if($==="win32"?W.isFile(x):W.isExecutable(x))return x}}return null}function _0(z={}){let{platform:J,home:Z,env:$,path:K}=k(z);if(J==="darwin")return["/Applications/OpenCode.app","/Applications/OpenCode Beta.app",K.join(Z,"Applications","OpenCode.app"),K.join(Z,"Applications","OpenCode Beta.app")];if(J==="win32"){let Q=$.LOCALAPPDATA||K.join(Z,"AppData","Local");return[K.join(Q,"Programs","opencode"),K.join(Q,"opencode")]}return["/opt/OpenCode","/usr/lib/opencode",K.join(Z,".local","share","applications","opencode.desktop")]}function Q0(z,J){let Z=J.fs??S,{path:$}=k(J);try{let K=Z.readText(z);if(K.length>65536)return z;let Q=[...K.matchAll(/"%~?dp0%?\\([^"%\r\n]+)"/g)];if(!Q.length)Q.push(...K.matchAll(/"\$basedir\/([^"$\r\n]+)"/g));let W=Q.at(-1)?.[1];if(W){let G=$.join($.dirname(z),...W.split(/[/\\]+/));if(Z.isFile(G))return Z.realpath(G)}return Z.realpath(z)}catch{return z}}function f2(z,J){let Z=J.fs??S,{path:$}=k(J),K=$.dirname(Q0(z,J));for(;;){try{let W=JSON.parse(Z.readText($.join(K,"package.json")));if(["@opencode/cli","@opencode-ai/cli"].includes(W.name))return"2";if(W.name==="opencode-ai")return/^(?:[2-9]\d*|1\d+)\.|^0\.0\.0-(?:beta|dev)-/.test(W.version??"")?"2":"1"}catch{}let Q=$.dirname(K);if(Q===K)return null;K=Q}}function T0(z={}){let J=P("opencode",z),Z=P("opencode2",z),$=J&&Z&&Q0(J,z)===Q0(Z,z),K=z.fs??S,{path:Q,opencode:W}=k(z),G="1";for(let X of["jsonc","json"]){let q=Q.join(W,`opencode.${X}`);if(!K.exists(q))continue;try{if(Object.hasOwn(y2(K.readText(q))??{},"plugins"))G="2"}catch{}break}let V=J?f2(J,z)??($?"2":G):null;if(Z&&V==="1"&&!$)return"ambiguous";return Z||$?"2":V??G}async function W0(z,J={}){let Z=J.fs??S,{env:$,platform:K,opencode:Q,pi:W}=k(J),G=J.runner??w,V=P("opencode",J)??P("opencode2",J),X=P("pi",J),q=P("ck",J),b=async(D)=>{if(!D)return null;let j;try{j=await w2(E2(v2(),"common-auth-setup-version-"));let U={...$,HOME:j,USERPROFILE:j,XDG_CONFIG_HOME:j,XDG_DATA_HOME:j,XDG_STATE_HOME:j,XDG_CACHE_HOME:j,OPENCODE_CONFIG_DIR:j,OPENCODE_CONFIG:void 0,OPENCODE_CONFIG_CONTENT:void 0,OPENCODE_AUTH_CONTENT:void 0,PI_CODING_AGENT_DIR:j},O=await o(G,K,D,["--version"],U,2000);return O.exitCode===0?/\b\d+\.\d+\.\d+(?:-[\w.-]+)?/.exec(O.stdout)?.[0]??null:null}catch{return null}finally{if(j)await S2(j,{recursive:!0,force:!0}).catch(()=>{})}},x=!1;if(q&&Z.exists(z.vault.connectionFile))try{(await(J.connect??n)({connectionFile:z.vault.connectionFile,handshakeTimeoutMs:2000})).close(),x=!0}catch{x=!1}let[Y,H]=await Promise.all([b(V),b(X)]);return{opencode:{installed:Z.isDirectory(Q)||_0(J).some((D)=>Z.exists(D))||V!==null,executable:V,version:Y,directory:Q,generation:T0(J)},pi:{installed:X!==null||Z.isDirectory(W),executable:X,version:H,directory:W},claustrum:{available:x,executable:q}}}import{setTimeout as r2}from"node:timers/promises";import{writeEnrollmentTokenFile as n2}from"@cortexkit/claustrum-client";import{statSync as g2}from"node:fs";import{win32 as t}from"node:path";var h2=45000,m2=A0("setup-process-fence"),d2=90000;function p2(z){try{return g2(z).isFile()}catch{return!1}}function d(z,J){return Object.entries(z).find(([Z])=>Z.toUpperCase()===J.toUpperCase())?.[1]}var X0=new Set(["opencode","litecode","opencode2","pi"]),L0=new Set(["node","bun"]),c2=[...X0,...L0].map((z)=>`Name LIKE '${z}%'`).join(" OR "),u2=`$ErrorActionPreference = 'Stop'; $rows = @(Get-CimInstance Win32_Process -Filter "${c2}" | Select-Object Name,ProcessId,CommandLine); ConvertTo-Json -Compress -Depth 3 -InputObject @{ complete = $true; processes = $rows }`,l2=/(?:^|[/\\])pi-coding-agent[/\\]dist[/\\](?:(?:bundle|bun)[/\\])?cli\.m?js$/i;function i2(z){return[...z.matchAll(/"([^"]*)"|(\S+)/g)].map((J)=>J[1]??J[2]??"")}function P0(z){return(z.split(/[/\\]/).pop()??"").toLowerCase().replace(/\.(?:exe|cmd|bat|m?js)$/,"")}var a2=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"]),s2=new Set(["-e","--eval","-p","--print"]);function o2(z,J){for(let Z=0;Z<J.length;Z++){let $=J[Z]??"";if($==="--")return J[Z+1];if(s2.has($))return;if($.startsWith("-")){if(!$.includes("=")&&a2.has($))Z++;continue}if(z==="bun"&&$==="run")continue;return $}return}function w0(z){let[J,...Z]=i2(z);if(J===void 0)return null;let $=P0(J);if(X0.has($))return $;if(!L0.has($))return null;let K=o2($,Z);if(K===void 0)return null;let Q=P0(K);if(X0.has(Q))return Q;return l2.test(K)?"pi":null}class R extends Error{code="process-inspection-failed";step;program;exitCode;signal;timedOut;durationMs;constructor(z){super("Process inspection failed; setup cannot prove hosts are stopped.");this.name="ProcessInspectionError",this.step=z.step,this.program=z.program,this.exitCode=z.exitCode,this.signal=z.signal,this.timedOut=z.timedOut,this.durationMs=z.durationMs}get refusalText(){let z=this.timedOut?"timed out":this.signal?`signal ${this.signal}`:this.exitCode===null?"could not start or complete":this.exitCode===0?"invalid output (exit code 0)":`exit code ${this.exitCode}`;return`${this.message} ${this.step}: ${z} after ${Math.round(this.durationMs)} ms.`}}class y extends Error{activeHosts;constructor(z){let J=z.map((Z)=>({pid:Z.pid,command:w0(Z.command)??"host"}));super(`OpenCode or Pi processes are currently running:
5
5
  ${J.map((Z)=>` - PID ${Z.pid}: ${Z.command}`).join(`
@@ -10,5 +10,5 @@ Please quit all OpenCode, LiteCode, and Pi processes before running setup.`);thi
10
10
  `:`
11
11
  `}},W=z,G=K[J],V=Array.isArray(G)?[...G]:[],X=V.flatMap((x,Y)=>Y0(x)===Z?[Y]:[]),q=`${Z}@${$}`;if(!X.length)W=q0(W,l0(W,G===void 0?[J]:[J,V.length],G===void 0?[q]:q,Q));else{let x=X[0],Y=V[x],H=Array.isArray(Y)?[q,...Y.slice(1)]:Y&&typeof Y==="object"?{...Y,package:q}:q;if(JSON.stringify(Y)!==JSON.stringify(H))W=q0(W,l0(W,[J,x],H,Q));for(let D of X.slice(1).reverse())W=i0(W,J,D)}let b=J==="plugin"?"plugins":"plugin";if(Array.isArray(K[b])){let x=K[b];for(let Y=x.length-1;Y>=0;Y--)if(Y0(x[Y])===Z)W=i0(W,b,Y)}return W}function D0(z,J,Z={}){let $=Z.fs??S,{path:K,opencode:Q}=k(Z),W=J==="2"?"plugins":"plugin";return(J==="2"?["opencode"]:["opencode","tui"]).map((V)=>{let X=K.join(Q,`${V}.jsonc`),q=K.join(Q,`${V}.json`),b=$.exists(X)?X:$.exists(q)?q:X,x=$.exists(b),Y=x?$.readText(b):`${JSON.stringify({$schema:`https://opencode.ai/${V==="tui"?"tui":"config"}.json`},null,2)}
12
12
  `,H=s0(Y,W),D=[],j=[];for(let O of["plugin","plugins"]){if(!Array.isArray(H[O]))continue;for(let B of H[O]){let I=a0(B);if(I===null)continue;if(F1(I,b,Z)===z.packages.opencode)D.push(JSON.stringify(B));else if(Y0(B)===z.packages.opencode)j.push(JSON.stringify(B))}}if(D.length>0)return{path:b,content:Y,changed:!1,existingLocalEntries:D,existingNpmEntries:j};let U=o0(Y,W,z.packages.opencode,z.version);return{path:b,content:U,changed:!x||U!==Y}})}async function b0(z,J){let Z=typeof J==="function"?new f(J):J;for(let $ of z){if(!$.changed)continue;await u0($.path,$.content,{beforeRename:Z?()=>Z.check({reuse:!0}):void 0,rename:Z?(K,Q)=>Z.step(()=>q1(K,Q)):void 0,wait:Z?(K)=>Z.step(()=>Y1(K)):void 0})}}async function B0(z,J,Z={}){let{platform:$,env:K}=k(Z),Q=await o(Z.runner??w,$,J,["install",`npm:${z.packages.pi}@${z.version}`],K);if(Q.exitCode!==0||Q.timedOut)throw new r({exitCode:Q.spawnError?null:Q.exitCode,signal:Q.signal??null,stderrTail:Q.stderr,stderrTruncated:Q.stderrTruncated??!1})}var e0="Multiple OpenCode generations found. Choose --opencode=1|2|both before running noninteractive setup.";function H1(z){for(let J of Object.values(z.packages))if(!/^(?:@[a-z0-9._-]+\/)?[a-z0-9._-]+$/.test(J))throw Error("Setup requires npm package names.");if(!/^\d+\.\d+\.\d+(?:-[a-zA-Z0-9.-]+)?(?:\+[a-zA-Z0-9.-]+)?$/.test(z.version))throw Error("Setup requires a concrete package version.");for(let J of Object.values(z.vault.hosts)){if(!/^[a-z0-9][a-z0-9-]*$/.test(J.name))throw Error("Setup requires lowercase vault names containing only letters, digits and dashes.");if(J.requestedGrants!==void 0&&!r0(J.requestedGrants))throw Error("invalid Claustrum enrollment requested grants");if(J.grantFallback!==void 0&&J.grantFallback!=="setup"&&J.grantFallback!=="plugin")throw Error("invalid Claustrum enrollment grant fallback")}}async function M1(z,J,Z,$){let K=[];for(let Q of J){let W=Z.get(Q)??"not-enrolled",G=$.get(Q);if(W==="unknown"){let{name:V,paths:X}=z.vault.hosts[Q],q=await i(A(X),V).catch(()=>"unreadable");if(q==="vault"||q==="host")W="enrolled";else if(q==="local")W="not-enrolled";if(W==="enrolled"){let b=await n0(A(X),V).catch(()=>{return});if(b?.state==="approved")G=await h({},b,A(X).tokenPath,z.vault.hosts[Q].requestedGrants)}}K.push({host:Q,outcome:W,...G&&{access:G}})}return K}async function V0(z,J=[],Z={}){let $=p0(J);if(e())throw Error(g);H1(z);let K=Z.terminal??t0(),Q=await W0(z,Z);F(K,`${z.displayName} setup`);for(let[B,I]of[["OpenCode",Q.opencode],["Pi",Q.pi]])F(K,`${B}: ${I.installed?`found (version ${I.version??"unknown"})`:"not found"} — ${I.directory}`);F(K,`Claustrum: ${Q.claustrum.available?"available":"not available"}`);let W=Q.pi.installed&&!Q.pi.executable;if(W)F(K,"Pi: skipped, because its folder exists but pi is not on PATH. Install the Pi CLI and rerun setup to add it.");let G=["opencode","pi"].filter((B)=>Q[B].installed&&!(B==="pi"&&W));if($.hosts.some((B)=>!G.includes(B)))throw Error(d0);let V=$.yes||$.dryRun&&!l(K);if(!V&&!l(K))throw Error("Setup requires a TTY or --yes.");let X=$.hosts.length?G.filter((B)=>$.hosts.includes(B)):V?G:await c0(K,G)??[],q=$.opencode??(Q.opencode.generation==="ambiguous"?"1":Q.opencode.generation);if(X.includes("opencode")&&!$.opencode&&Q.opencode.generation==="ambiguous"){if(V||!l(K))throw Error(e0);let B=await u(K,[{value:"1",label:"OpenCode 1"},{value:"2",label:"OpenCode 2"},{value:"both",label:"Both (one compatible registration)"}],{message:"Which OpenCode generation should be registered?"});if(B===null)return{hosts:[],dryRun:$.dryRun,mode:"local",detection:Q};q=B}if(!X.length)return F(K,"No hosts selected. Install OpenCode or Pi and rerun setup."),{hosts:X,dryRun:$.dryRun,mode:"local",detection:Q};let{env:b,platform:x}=k(Z),Y=Z.fence??p(Z.runner??w,{platform:x,isFile:Z.fs?.isFile.bind(Z.fs),onProgress:(B)=>F(K,B)}),D=new f(async()=>{try{await c(Y,b)}catch(B){if(B instanceof R)F(K,B.refusalText);throw B}},Z.now);if(F(K,"Checking that OpenCode and Pi are not running…"),$.dryRun)try{let B=Y.previewRunningHosts?await Y.previewRunningHosts(b):{hosts:await Y.listRunningHosts(b),uncheckedRuntimes:0},I=B.hosts;if(B.uncheckedRuntimes>0)F(K,"Node or Bun programs are running; a real run checks whether any of them is OpenCode or Pi.");let T=new Set(new y(I).activeHosts.map((C)=>C.command.toLowerCase()==="pi"?"Pi":"OpenCode"));for(let C of T)F(K,`${C} is running; setup will ask you to quit it.`)}catch(B){if(F(K,"Process inspection failed; real setup will require successful inspection and stopped OpenCode/Pi hosts."),B instanceof R)F(K,B.refusalText)}else await D.check();if(($.claustrum||$.enrollOnly)&&!Q.claustrum.available)throw Error("Claustrum is not available. Start ck, or omit vault-only flags and use --no-claustrum for local sign-in.");let j=$.claustrum||$.enrollOnly;if(!j&&!$.login&&!$.noClaustrum&&!V&&Q.claustrum.available&&l(K)){let B=await D.step(()=>u(K,[{label:"No",value:!1},{label:"Yes",value:!0}],{message:"Connect these hosts to the Claustrum vault?"}));if(B===null)return F(K,"Setup cancelled. Nothing was changed."),{hosts:[],dryRun:$.dryRun,mode:"local",detection:Q};j=B===!0}let U=j?"claustrum":"local",O=!$.enrollOnly&&X.includes("opencode")?D0(z,q,Z):[];for(let B of O){for(let T of B.existingLocalEntries??[])F(K,`OpenCode: already registered from ${T} in ${B.path}.`);let I=[...B.existingLocalEntries??[],...B.existingNpmEntries??[]];if(I.length>1)F(K,`Warning: ${z.displayName} may load twice in ${B.path}: ${I.join(", ")}. Entries were left unchanged.`)}if($.dryRun){F(K,"Dry run: no registrations, enrollment, sign-in or migration will be performed.");for(let B of X){if(z.beforeSignIn)F(K,`Would run beforeSignIn(${B}, ${U}).`);if(j){let I=A(z.vault.hosts[B].paths);F(K,`Would Connect ${B}: write ${I.statePath} and ${I.tokenPath}; wait for ck auth enroll approve.`)}else F(K,`Would sign in locally for ${B}.`);if(!$.enrollOnly&&z.beforeRegister)F(K,`Would run beforeRegister(${B}, ${U}).`)}for(let B of O)F(K,`${B.changed?"Would write":"Unchanged"} ${B.path}:
13
- ${B.content}`);if(!$.enrollOnly&&X.includes("pi"))F(K,`Would run ${Q.pi.executable} install npm:${z.packages.pi}@${z.version}`);if(!$.enrollOnly&&z.migrate)for(let B of X)F(K,`Would migrate ${B} using the plugin callback (provider-specific writes).`)}else{let B={opencodeGeneration:q,mode:U,hosts:Object.freeze([...X]),piAgentDir:Q.pi.directory},I=new Map,T=new Map;try{for(let C of X){if(z.beforeSignIn)await D.check({reuse:!0}),await D.step(()=>z.beforeSignIn?.(C,B));if(j){I.set(C,"unknown");try{let M=await m0(z,C,Z,K,D);if(M)T.set(C,M)}catch(M){if(M instanceof _)I.set(C,"not-enrolled");throw M}I.set(C,"enrolled")}else await D.check({reuse:!0}),await D.step(()=>z.signInLocal(C,B));if($.enrollOnly)continue;if(z.beforeRegister)await D.check({reuse:!0}),await D.step(()=>z.beforeRegister?.(C,U,B));if(C==="opencode")await b0(O,D);else await D.check({reuse:!0}),await D.step(()=>B0(z,Q.pi.executable,Z));if(z.migrate)await D.check({reuse:!0}),await D.step(()=>z.migrate?.(C,B))}}catch(C){if(I.size===0)throw C;try{let M=await M1(z,X,I,T);k0(C,M);for(let L of M)F(K,N0(L,z.vault.hosts[L.host].grantFallback))}catch{}throw C}}if(F(K,`${$.dryRun?"Planned":$.enrollOnly?"Enrolled":"Configured"} ${z.displayName} for ${X.join(", ")} (${U}).`),$.enrollOnly)F(K,`Enroll-only: no host config or plugin registration ${$.dryRun?"will be":"was"} written.`),F(K,"Next: register the plugin yourself in each selected host and enable vault access as required by the plugin.");else F(K,`Next: ${X.includes("opencode")?"start OpenCode":"start Pi"} and run ${z.slashCommand}.`);return{hosts:X,dryRun:$.dryRun,mode:U,detection:Q}}var v={name:"@cortexkit/opencode-openai-auth",version:"1.20.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 && cp ../core/openai-auth.schema.json dist/openai-auth.schema.json","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.55.1","@cortexkit/openai-auth-core":"workspace:*","@cortexkit/opencode-sidebar":"0.3.0","@opencode/plugin":"2.3.0"},dependencies:{"@cortexkit/claustrum-client":"^0.20.0","@cortexkit/private-files":"^0.2.2","@cortexkit/subc-client":"^0.24.0","@opentui/core":">=0.9.0","@opentui/solid":">=0.9.0",ai:"^7.0.173","jsonc-parser":"^3.3.1","solid-js":"1.9.18"}};import{basename as k1}from"node:path";import{resolveClaustrumConnectionPath as _1}from"@cortexkit/claustrum-client";var z2={name:"@cortexkit/pi-openai-auth",version:"1.20.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 jsonc-parser --external @cortexkit/claustrum-client --external @cortexkit/subc-client --minify && bun run build:types && cp ../core/openai-auth.schema.json dist/openai-auth.schema.json","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.55.1","@cortexkit/openai-auth-core":"workspace:*"},dependencies:{"@cortexkit/claustrum-client":"^0.20.0","@cortexkit/private-files":"^0.2.2","@cortexkit/subc-client":"^0.24.0","jsonc-parser":"^3.3.1"},peerDependencies:{"@earendil-works/pi-ai":">=1.0.1","@earendil-works/pi-coding-agent":">=1.0.1","@earendil-works/pi-tui":">=1.0.1"}};import{existsSync as J0}from"node:fs";import{homedir as Z0}from"node:os";import{join as $0,resolve as J2}from"node:path";import{fileURLToPath as C1}from"node:url";var Z2=new Set;function R1(){let z=process.env.PI_CODING_AGENT_DIR;if(!z)return $0(Z0(),".pi","agent");if(process.platform==="win32"&&z.startsWith("/")&&!z.startsWith("//")&&!z.includes("\\")){let J=z.match(/^\/(?:mnt\/|cygdrive\/)?([a-z])(?:\/(.*))?$/i);if(J?.[1])z=`${J[1].toUpperCase()}:\\${J[2]?.replaceAll("/","\\")??""}`}if(z==="~")return Z0();if(z.startsWith("~/")||process.platform==="win32"&&z.startsWith("~\\"))return $0(Z0(),z.slice(2));return z.startsWith("file://")?C1(z):z}function K2(z=R1()){let J=process.env.PI_OPENAI_AUTH_FILE?.trim();if(J)return J;let Z=$0(z,x0),$=$0(Z0(),".pi","agent",x0),K=(W)=>{let G=U0(W),V=$2(a(G),"pi");return J0(W)||J0(G)||J0(V.tokenPath)||J0(V.statePath)};if(J2(Z)===J2($)||K(Z)||!K($))return Z;let Q=`${Z}\x00${$}`;if(!Z2.has(Q))Z2.add(Q),console.warn(`openai-auth is using its store in the legacy Pi agent directory: ${$} (${Z} has no store). Credentials were not copied or moved. Set PI_OPENAI_AUTH_FILE to choose a store explicitly.`);return $}function N1(z=K2()){return process.env.PI_OPENAI_AUTH_STATE_FILE?.trim()||U0(z)}function Q2(z=K2()){return{configPath:z,statePath:N1(z)}}function Y2(z={}){let J=z.print??console.log,Z=z.fence??(z.createFence??p)(void 0,{onProgress:J}),$={opencode:{stateDir:a(G2().statePath),host:"opencode"},pi:{stateDir:a(Q2().statePath),host:"pi"}},K=async(Q)=>{let W=await i(A($[Q]),s(Q));if(W==="host")throw Error(g);if(W!=="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:v.name,pi:z2.name},version:v.version,displayName:"OpenAI Auth",slashCommand:"/openai",vault:{connectionFile:_1(),hosts:{opencode:{name:s("opencode"),displayName:H0("opencode"),requestedGrants:F0,paths:$.opencode},pi:{name:s("pi"),displayName:H0("pi"),requestedGrants:F0,paths:$.pi}}},async beforeRegister(Q,W){if(await i(A($[Q]),s(Q))==="host")throw Error(g);if(W==="claustrum"){if(Q==="opencode")J("Then run opencode auth login and choose ChatGPT accounts in the vault to activate vault routing without local sign-in.");return}await K(Q)},async signInLocal(Q,W){if(await K(Q),Q==="pi"){J("Start Pi and run /login openai-codex to sign in with Pi itself.");return}if(W.opencodeGeneration!=="1"){let j=k1(P("opencode2",z.io)??P("opencode",z.io)??"opencode");J(`In OpenCode 2, run ${j} 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(W.opencodeGeneration==="2")return;if(j2(process.env))throw Error("Unset OPENCODE_AUTH_CONTENT before local setup sign-in.");let G=q2(),V={path:{id:"openai"}};if(await G.get(V)!==void 0){J("OpenCode already has an OpenAI login. Use opencode auth login to change it.");return}let X=z.beginLogin??W2,q=new AbortController,b=Boolean(process.env.SSH_CONNECTION||process.env.SSH_TTY||process.platform==="linux"&&!process.env.DISPLAY&&!process.env.WAYLAND_DISPLAY),x={version:v.version,signal:q.signal},Y,H=!b;try{Y=await X({...x,headless:b})}catch(j){if(b)throw j;H=!1,J("Browser callback unavailable; using device-code sign-in."),Y=await X({version:v.version,headless:!0})}if(H){if(!(z.openBrowser??X2)(Y.url))q.abort(),await Y.completion.catch(()=>{}),J("Browser unavailable; using device-code sign-in."),Y=await X({version:v.version,headless:!0})}J(`${Y.url}
13
+ ${B.content}`);if(!$.enrollOnly&&X.includes("pi"))F(K,`Would run ${Q.pi.executable} install npm:${z.packages.pi}@${z.version}`);if(!$.enrollOnly&&z.migrate)for(let B of X)F(K,`Would migrate ${B} using the plugin callback (provider-specific writes).`)}else{let B={opencodeGeneration:q,mode:U,hosts:Object.freeze([...X]),piAgentDir:Q.pi.directory},I=new Map,T=new Map;try{for(let C of X){if(z.beforeSignIn)await D.check({reuse:!0}),await D.step(()=>z.beforeSignIn?.(C,B));if(j){I.set(C,"unknown");try{let M=await m0(z,C,Z,K,D);if(M)T.set(C,M)}catch(M){if(M instanceof _)I.set(C,"not-enrolled");throw M}I.set(C,"enrolled")}else await D.check({reuse:!0}),await D.step(()=>z.signInLocal(C,B));if($.enrollOnly)continue;if(z.beforeRegister)await D.check({reuse:!0}),await D.step(()=>z.beforeRegister?.(C,U,B));if(C==="opencode")await b0(O,D);else await D.check({reuse:!0}),await D.step(()=>B0(z,Q.pi.executable,Z));if(z.migrate)await D.check({reuse:!0}),await D.step(()=>z.migrate?.(C,B))}}catch(C){if(I.size===0)throw C;try{let M=await M1(z,X,I,T);k0(C,M);for(let L of M)F(K,N0(L,z.vault.hosts[L.host].grantFallback))}catch{}throw C}}if(F(K,`${$.dryRun?"Planned":$.enrollOnly?"Enrolled":"Configured"} ${z.displayName} for ${X.join(", ")} (${U}).`),$.enrollOnly)F(K,`Enroll-only: no host config or plugin registration ${$.dryRun?"will be":"was"} written.`),F(K,"Next: register the plugin yourself in each selected host and enable vault access as required by the plugin.");else F(K,`Next: ${X.includes("opencode")?"start OpenCode":"start Pi"} and run ${z.slashCommand}.`);return{hosts:X,dryRun:$.dryRun,mode:U,detection:Q}}var v={name:"@cortexkit/opencode-openai-auth",version:"1.20.2",license:"MIT",type:"module",repository:{type:"git",url:"git+https://github.com/cortexkit/openai-auth.git",directory:"packages/opencode"},main:"./dist/index.js",types:"./dist/index.d.ts",bin:{"opencode-openai-auth":"./dist/bin.js"},exports:{".":{import:"./dist/index.js",types:"./dist/index.d.ts"},"./tui":{types:"./dist/tui.d.ts",import:"./src/tui/entry.mjs"},"./tui-prefs":{types:"./dist/tui-preferences.d.ts",import:"./dist/tui-preferences.js"},"./server":{types:"./dist/v2/server.d.ts",import:"./dist/v2/server.js"}},"oc-plugin":["server","tui"],engines:{bun:"1.3.14"},files:["dist","src/tui/entry.mjs","src/tui-compiled","README.md","LICENSE"],scripts:{build:"rm -rf dist && bun build src/index.ts src/v2/server.ts src/sidebar-state.ts src/tui-preferences.ts src/rpc/rpc-client.ts src/rpc/port-file.ts src/rpc/protocol.ts src/rpc/rpc-dir.ts src/bin.ts --root src --outdir dist --target node --format esm --splitting --external @opencode-ai/plugin --external @opencode/plugin --external @cortexkit/private-files --external jsonc-parser --external @cortexkit/claustrum-client --external @cortexkit/subc-client --minify && bun run build:types && bun run build:tui && cp ../core/openai-auth.schema.json dist/openai-auth.schema.json","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.55.1","@cortexkit/openai-auth-core":"workspace:*","@cortexkit/opencode-sidebar":"0.3.0","@opencode/plugin":"2.3.0"},dependencies:{"@cortexkit/claustrum-client":"^0.20.0","@cortexkit/private-files":"^0.2.2","@cortexkit/subc-client":"^0.24.0","@opentui/core":">=0.9.0","@opentui/solid":">=0.9.0",ai:"^7.0.173","jsonc-parser":"^3.3.1","solid-js":"1.9.18"}};import{basename as k1}from"node:path";import{resolveClaustrumConnectionPath as _1}from"@cortexkit/claustrum-client";var z2={name:"@cortexkit/pi-openai-auth",version:"1.20.2",license:"MIT",type:"module",repository:{type:"git",url:"git+https://github.com/cortexkit/openai-auth.git",directory:"packages/pi"},main:"./dist/index.js",types:"./dist/index.d.ts",exports:{".":{import:"./dist/index.js",types:"./dist/index.d.ts"}},files:["dist","README.md","LICENSE"],keywords:["pi-package"],pi:{extensions:["./dist/index.js"]},scripts:{build:"rm -rf dist && bun build src/index.ts --outdir dist --target node --format esm --external '@earendil-works/pi-ai' --external '@earendil-works/pi-ai/*' --external '@earendil-works/pi-coding-agent' --external '@earendil-works/pi-coding-agent/*' --external '@earendil-works/pi-tui' --external '@earendil-works/pi-tui/*' --external @cortexkit/private-files --external jsonc-parser --external @cortexkit/claustrum-client --external @cortexkit/subc-client --minify && bun run build:types && cp ../core/openai-auth.schema.json dist/openai-auth.schema.json","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.55.1","@cortexkit/openai-auth-core":"workspace:*"},dependencies:{"@cortexkit/claustrum-client":"^0.20.0","@cortexkit/private-files":"^0.2.2","@cortexkit/subc-client":"^0.24.0","jsonc-parser":"^3.3.1"},peerDependencies:{"@earendil-works/pi-ai":">=1.0.1","@earendil-works/pi-coding-agent":">=1.0.1","@earendil-works/pi-tui":">=1.0.1"}};import{existsSync as J0}from"node:fs";import{homedir as Z0}from"node:os";import{join as $0,resolve as J2}from"node:path";import{fileURLToPath as C1}from"node:url";var Z2=new Set;function R1(){let z=process.env.PI_CODING_AGENT_DIR;if(!z)return $0(Z0(),".pi","agent");if(process.platform==="win32"&&z.startsWith("/")&&!z.startsWith("//")&&!z.includes("\\")){let J=z.match(/^\/(?:mnt\/|cygdrive\/)?([a-z])(?:\/(.*))?$/i);if(J?.[1])z=`${J[1].toUpperCase()}:\\${J[2]?.replaceAll("/","\\")??""}`}if(z==="~")return Z0();if(z.startsWith("~/")||process.platform==="win32"&&z.startsWith("~\\"))return $0(Z0(),z.slice(2));return z.startsWith("file://")?C1(z):z}function K2(z=R1()){let J=process.env.PI_OPENAI_AUTH_FILE?.trim();if(J)return J;let Z=$0(z,x0),$=$0(Z0(),".pi","agent",x0),K=(W)=>{let G=U0(W),V=$2(a(G),"pi");return J0(W)||J0(G)||J0(V.tokenPath)||J0(V.statePath)};if(J2(Z)===J2($)||K(Z)||!K($))return Z;let Q=`${Z}\x00${$}`;if(!Z2.has(Q))Z2.add(Q),console.warn(`openai-auth is using its store in the legacy Pi agent directory: ${$} (${Z} has no store). Credentials were not copied or moved. Set PI_OPENAI_AUTH_FILE to choose a store explicitly.`);return $}function N1(z=K2()){return process.env.PI_OPENAI_AUTH_STATE_FILE?.trim()||U0(z)}function Q2(z=K2()){return{configPath:z,statePath:N1(z)}}function Y2(z={}){let J=z.print??console.log,Z=z.fence??(z.createFence??p)(void 0,{onProgress:J}),$={opencode:{stateDir:a(G2().statePath),host:"opencode"},pi:{stateDir:a(Q2().statePath),host:"pi"}},K=async(Q)=>{let W=await i(A($[Q]),s(Q));if(W==="host")throw Error(g);if(W!=="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:v.name,pi:z2.name},version:v.version,displayName:"OpenAI Auth",slashCommand:"/openai",vault:{connectionFile:_1(),hosts:{opencode:{name:s("opencode"),displayName:H0("opencode"),requestedGrants:F0,paths:$.opencode},pi:{name:s("pi"),displayName:H0("pi"),requestedGrants:F0,paths:$.pi}}},async beforeRegister(Q,W){if(await i(A($[Q]),s(Q))==="host")throw Error(g);if(W==="claustrum"){if(Q==="opencode")J("Then run opencode auth login and choose ChatGPT accounts in the vault to activate vault routing without local sign-in.");return}await K(Q)},async signInLocal(Q,W){if(await K(Q),Q==="pi"){J("Start Pi and run /login openai-codex to sign in with Pi itself.");return}if(W.opencodeGeneration!=="1"){let j=k1(P("opencode2",z.io)??P("opencode",z.io)??"opencode");J(`In OpenCode 2, run ${j} 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(W.opencodeGeneration==="2")return;if(j2(process.env))throw Error("Unset OPENCODE_AUTH_CONTENT before local setup sign-in.");let G=q2(),V={path:{id:"openai"}};if(await G.get(V)!==void 0){J("OpenCode already has an OpenAI login. Use opencode auth login to change it.");return}let X=z.beginLogin??W2,q=new AbortController,b=Boolean(process.env.SSH_CONNECTION||process.env.SSH_TTY||process.platform==="linux"&&!process.env.DISPLAY&&!process.env.WAYLAND_DISPLAY),x={version:v.version,signal:q.signal},Y,H=!b;try{Y=await X({...x,headless:b})}catch(j){if(b)throw j;H=!1,J("Browser callback unavailable; using device-code sign-in."),Y=await X({version:v.version,headless:!0})}if(H){if(!(z.openBrowser??X2)(Y.url))q.abort(),await Y.completion.catch(()=>{}),J("Browser unavailable; using device-code sign-in."),Y=await X({version:v.version,headless:!0})}J(`${Y.url}
14
14
  ${Y.instructions}`);let D=await Y.completion;await c(Z),await K(Q),await G.set({...V,body:{type:"oauth",access:D.access,refresh:D.refresh,expires:D.expires,...D.accountId?{accountId:D.accountId}:{}}}),J("Signed in to OpenCode. The first plugin start adopts this login into the account pool.")},async migrate(Q){J(`${Q}: account migration runs on first plugin start; setup leaves existing credentials unchanged.`)}}}if(process.argv[2]!=="setup")console.log("Usage: opencode-openai-auth setup [options]");else try{await D2({version:v.version}),await V0(Y2(),process.argv.slice(3))}catch(z){console.error(z instanceof Error?z.message:String(z)),process.exitCode=1}
@@ -1 +1 @@
1
- import{Hg as G,Jg as H}from"./index-xbh03w1v.js";function Q(x){return x==="chatgptaccountid"||x==="email"||x==="orgname"||x==="organizationname"}var S=G({extraSecretKeys:Q}),I=S.redact,N=S.redactStrings;function O(x){H({...x,extraSecretKeys:Q})}function C(x){if(x instanceof Error)return x.message;if(typeof x==="string")return x;try{return JSON.stringify(x)}catch{return String(x)}}function v(x){return"notify"in x}import{basename as X,dirname as Y,join as Z}from"node:path";var $="openai-auth.json",b="openai-auth-state.json";function p(x){return X(x)===$?Z(Y(x),b):`${x}.state.json`}import{spawn as j}from"node:child_process";function z(x,J=process.platform,q=j){try{if(J==="win32"){let U=`Start-Process '${x.replaceAll("'","''")}'`,V=Buffer.from(U,"utf16le").toString("base64"),T=q("powershell.exe",["-NoProfile","-NonInteractive","-WindowStyle","Hidden","-EncodedCommand",V],{stdio:"ignore",windowsHide:!0});return T.on("error",()=>{}),T.unref(),T.pid!==void 0}let u=q(J==="darwin"?"open":"xdg-open",[x],{stdio:"ignore"});return u.on("error",()=>{}),u.unref(),u.pid!==void 0}catch{return!1}}export{N as zg,O as Ag,$ as Bg,b as Cg,p as Dg,C as Eg,v as Fg,z as Gg};
1
+ import{Kg as G,Mg as H}from"./index-xcsz00nr.js";function Q(x){return x==="chatgptaccountid"||x==="email"||x==="orgname"||x==="organizationname"}var S=G({extraSecretKeys:Q}),I=S.redact,N=S.redactStrings;function O(x){H({...x,extraSecretKeys:Q})}function C(x){if(x instanceof Error)return x.message;if(typeof x==="string")return x;try{return JSON.stringify(x)}catch{return String(x)}}function v(x){return"notify"in x}import{basename as X,dirname as Y,join as Z}from"node:path";var $="openai-auth.json",b="openai-auth-state.json";function p(x){return X(x)===$?Z(Y(x),b):`${x}.state.json`}import{spawn as j}from"node:child_process";function z(x,J=process.platform,q=j){try{if(J==="win32"){let U=`Start-Process '${x.replaceAll("'","''")}'`,V=Buffer.from(U,"utf16le").toString("base64"),T=q("powershell.exe",["-NoProfile","-NonInteractive","-WindowStyle","Hidden","-EncodedCommand",V],{stdio:"ignore",windowsHide:!0});return T.on("error",()=>{}),T.unref(),T.pid!==void 0}let u=q(J==="darwin"?"open":"xdg-open",[x],{stdio:"ignore"});return u.on("error",()=>{}),u.unref(),u.pid!==void 0}catch{return!1}}export{N as Cg,O as Dg,$ as Eg,b as Fg,p as Gg,C as Hg,v as Ig,z as Jg};
@@ -1,3 +1,3 @@
1
- import{rc as X,tc as V}from"./index-d5er9yht.js";import{randomUUID as Z}from"node:crypto";import{chmod as $,mkdir as G,readFile as H,rename as L,rm as T,stat as f,writeFile as g}from"node:fs/promises";import{dirname as k,resolve as w}from"node:path";var x="(no OpenCode 1 logins on this machine)";function C(b=process.env){return X(b)}async function Q(b){let z;try{z=await H(b,"utf8")}catch(q){if(q.code==="ENOENT")return;throw q}let j=JSON.parse(z);if(!j||typeof j!=="object"||Array.isArray(j))throw Error(`${b} does not hold a JSON object`);return j}function R(b){return b===void 0?void 0:JSON.stringify(b)}async function D(b){try{return(await f(b)).mode&511}catch(z){if(z.code==="ENOENT")return;throw z}}function _(b=C()){let z=new Map;return{path:w(b),async get(j){let q=(await Q(b))?.[j.path.id];return z.set(j.path.id,R(q)),q},async set(j){let q=j.path.id,W=await D(b),J=await Q(b)??{};if(!z.has(q)||z.get(q)!==R(J[q]))throw new V;J[q]=j.body,await G(k(b),{recursive:!0});let B=`${b}.${Z()}.tmp`;try{await g(B,`${JSON.stringify(J,null,2)}
1
+ import{uc as X,wc as V}from"./index-rbc7cfbv.js";import{randomUUID as Z}from"node:crypto";import{chmod as $,mkdir as G,readFile as H,rename as L,rm as T,stat as f,writeFile as g}from"node:fs/promises";import{dirname as k,resolve as w}from"node:path";var x="(no OpenCode 1 logins on this machine)";function C(b=process.env){return X(b)}async function Q(b){let z;try{z=await H(b,"utf8")}catch(q){if(q.code==="ENOENT")return;throw q}let j=JSON.parse(z);if(!j||typeof j!=="object"||Array.isArray(j))throw Error(`${b} does not hold a JSON object`);return j}function R(b){return b===void 0?void 0:JSON.stringify(b)}async function D(b){try{return(await f(b)).mode&511}catch(z){if(z.code==="ENOENT")return;throw z}}function _(b=C()){let z=new Map;return{path:w(b),async get(j){let q=(await Q(b))?.[j.path.id];return z.set(j.path.id,R(q)),q},async set(j){let q=j.path.id,W=await D(b),J=await Q(b)??{};if(!z.has(q)||z.get(q)!==R(J[q]))throw new V;J[q]=j.body,await G(k(b),{recursive:!0});let B=`${b}.${Z()}.tmp`;try{await g(B,`${JSON.stringify(J,null,2)}
2
2
  `,{mode:W??384}),await $(B,W??384),await L(B,b)}catch(Y){throw await T(B,{force:!0}).catch(()=>{}),Y}return z.set(q,R(j.body)),!0},async all(){let j=await Q(b);if(!j||Object.keys(j).length===0)return{[x]:!0};return j}}}
3
3
  export{_ as c};
@@ -1,2 +1,2 @@
1
- import{Dd as NZ,Ed as PZ,Gd as g,Hd as WZ,Id as HZ,Kf as _Z,Md as d,Of as TZ,Qf as RZ}from"./index-3898z307.js";import{Zf as XZ,cg as VZ,dg as YZ,fg as y,hg as x}from"./index-7tkppvqd.js";import{Mg as OZ}from"./index-xbh03w1v.js";import{Ng as b,Og as $Z,Tg as A,Ug as JZ}from"./index-asjkhkty.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:X,normalize:J}=Z,V=Promise.resolve(),Y=(B)=>{if(B==="")return X;try{return J(JSON.parse(B))}catch{return X}},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 X}},L=(B,D)=>{let N=V.then(B).then((P)=>D?.onResult?.(P));return V=N.catch(()=>{}),N},U={...x.sidebar,name:Z.lockName??x.sidebar.name,timeoutMs:Z.timeoutMs??x.sidebar.timeoutMs},K=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($,U,async(W)=>{let H=B(await z(),D);if(H===void 0)return"skipped";return await K(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"}}},j=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($,U,async(F)=>{let s=async(C)=>({value:C,held:await K(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)=>L(()=>j(()=>B,D),D),update:(B,D)=>L(()=>j(B,D),D)}}function v0(Z){let $=Z?.credits;if($===null||typeof $!=="object")return;let{hasCredits:X,unlimited:J,balance:V}=$;if(typeof X!=="boolean"||typeof J!=="boolean")return;return WZ({hasCredits:X,unlimited:J,...typeof V==="number"?{balance:V}:{}})}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 X of l){let J=Z[X];if(!J)continue;let V=J.windowMinutes,Y=V!==void 0&&Number.isFinite(V)&&V>0?V:uZ[X];$.push({key:X,label:rZ(V,X),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[X,J]of Object.entries(Z)){if(J===null||typeof J!=="object"||Array.isArray(J))continue;let V=J;if(typeof V.activeId!=="string"||typeof V.route!=="string"||typeof V.updatedAt!=="number"||!Number.isFinite(V.updatedAt))continue;$[X]={activeId:V.activeId,route:V.route,updatedAt:V.updatedAt}}return Object.keys($).length>0?$:void 0}function Y0(Z){if(Z===null||typeof Z!=="object"||Array.isArray(Z))return;let $={};for(let[X,J]of Object.entries(Z)){if(!J0.test(X)||J===null||typeof J!=="object"||Array.isArray(J))continue;let V=J;if(typeof V.accountId!=="string"||V.accountId.length===0||typeof V.assignedAt!=="number"||!Number.isFinite(V.assignedAt)||V.assignedAt<0||typeof V.lastSeenAt!=="number"||!Number.isFinite(V.lastSeenAt)||V.lastSeenAt<0||typeof V.inputBytes!=="number"||!Number.isFinite(V.inputBytes)||V.inputBytes<0)continue;let Y=V.quotaCheckedAt;if(Y!==void 0&&(typeof Y!=="number"||!Number.isFinite(Y)||Y<0))continue;let G=V.wireAccountId;$[X]={accountId:V.accountId,assignedAt:V.assignedAt,lastSeenAt:V.lastSeenAt,inputBytes:V.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,X=$.main,J;if(X!==null&&typeof X==="object"&&!Array.isArray(X)){let j=X;J={quota:"quota"in j?j.quota:null,killed:typeof j.killed==="boolean"?j.killed:!1,...typeof j.mainAccountId==="string"?{mainAccountId:j.mainAccountId}:{},...typeof j.quotaBackedOff==="boolean"?{quotaBackedOff:j.quotaBackedOff}:{},...typeof j.quotaBackoffUntil==="number"?{quotaBackoffUntil:j.quotaBackoffUntil}:{},...typeof j.refreshBackedOff==="boolean"?{refreshBackedOff:j.refreshBackedOff}:{},...typeof j.refreshBackoffUntil==="number"?{refreshBackoffUntil:j.refreshBackoffUntil}:{},...qZ(j.resetCredits)}}else J={quota:null,killed:!1};let V=zZ($.fallbacks),Y=Array.isArray($.vaultAccounts)?zZ($.vaultAccounts):void 0,G=typeof $.activeId==="string"?$.activeId:void 0,z=typeof $.route==="string"?$.route:q.route,L=typeof $.lastUpdated==="number"?$.lastUpdated:0,U=typeof $.planType==="string"?$.planType:void 0,K=V0($.activeRouting),Q=Y0($.stickyAssignments);return{main:J,fallbacks:V,activeId:G,route:z,lastUpdated:L,...K!==void 0?{activeRouting:K}:{},...Q!==void 0?{stickyAssignments:Q}:{},...U!==void 0?{planType:U}:{},...$.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,$,X=Date.now()){if(!(Z.updatedAt>=X-K0&&Z.updatedAt<=X))return!1;if($===void 0)return!0;return Z.activeId==="main"||$.some((V)=>V.enabled!==!1&&V.routable!==!1&&V.killed!==!0&&V.id===Z.activeId)}function bZ(Z,$=Date.now()){let X=Z?.spendControl;if(X?.reached!==!0||typeof X.resetsAt!=="string")return;let J=Date.parse(X.resetsAt);if(!Number.isFinite(J)||J<=$)return;return{resetsAt:X.resetsAt,resetAtMs:J}}function xZ(Z,$=Date.now()){let X;for(let V of l){let Y=Z?.[V];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(!X||G<X.resetAtMs)X={resetsAt:Y.resetsAt,resetAtMs:G}}let J=bZ(Z,$);if(J&&(!X||J.resetAtMs<X.resetAtMs))X=J;return X}function E(Z,$=Date.now()){return xZ(Z,$)!==void 0}function j0(Z,$,X=Date.now()){if(!$||Z.route!=="sticky-balanced")return;let J=Z.stickyAssignments?.[T($)];if(!J||J.lastSeenAt<X-u)return;if(J.accountId==="main"&&Z.vaultAccounts===void 0)return Z.main?.killed||E(Z.main?.quota,X)?void 0:"main";let V=r(Z).find((Y)=>Y.id===J.accountId);if(!V||V.enabled===!1||V.routable===!1||V.killed===!0||E(V.quota,X))return;return V.id}function d0(Z,$,X=Date.now()){if(!$){if(Z.vaultAccounts===void 0)return{activeId:Z.activeId??"main",route:Z.route};let K=Z.vaultAccounts.find((Q)=>Q.id===Z.activeId&&Q.enabled&&Q.routable!==!1&&!Q.killed);if(K&&!E(K.quota,X))return{activeId:K.id,route:Z.route}}let J=$?Z.activeRouting?.[$]:void 0,V=r(Z),Y=J?.activeId==="main"?Z.main.quota:V.find((K)=>K.id===J?.activeId)?.quota;if(J&&(Z.vaultAccounts===void 0||J.activeId.startsWith("vault:"))&&IZ(J,V,X)&&!E(Y,X))return{activeId:J.activeId,route:J.route};let G=j0(Z,$,X);if(G)return{activeId:G,route:Z.route};let z=Z.vaultAccounts!==void 0,L=(z?c(Z):Z.fallbacks).filter((K)=>K.enabled&&K.routable!==!1&&!K.killed),U=L.find((K)=>!E(K.quota,X))??L[0];return{activeId:z?U?.id??"vault":Z.route==="fallback-first"&&U?U.id:"main",route:Z.route}}function c(Z){let $=Z.vaultAccounts??[],X=new Map($.map((J)=>[J.id,J]));return d($.map((J)=>J.id),gZ(Z),_Z($)??"").flatMap((J)=>{let V=X.get(J);return V?[V]:[]})}function vZ(Z,$,X=Date.now(),J){if(!Z)return;let V=Object.entries(Z).filter(([G,z])=>G!==J&&IZ(z,$,X)),Y=V.length<=GZ?V:V.sort((G,z)=>z[1].updatedAt-G[1].updatedAt).slice(0,GZ);return Y.length>0?Object.fromEntries(Y):void 0}function I(Z,$,X=Date.now(),J){if(!Z)return;let V=0,Y=0,G=0,z=[];for(let[U,K]of Object.entries(Z)){if(U===J){G+=1;continue}if(K.lastSeenAt<X-u){Y+=1;continue}if($!==void 0&&!$.has(K.accountId)){V+=1;continue}z.push([U,K])}let L=V+Y+G;if(L>0)M.debug("pruned sticky assignments",{pid:process.pid,removed:L,reasons:{"account-not-in-roster":V,expired:Y,"explicit-removal":G}});return z.length>0?Object.fromEntries(z):void 0}function fZ(Z,$){let X=Object.keys(Z).length-MZ;if(X<=0)return Z;let J=new Set(Object.entries(Z).filter(([V])=>V!==$).sort(([V,Y],[G,z])=>Y.lastSeenAt-z.lastSeenAt||V.localeCompare(G)).slice(0,X).map(([V])=>V));return Object.fromEntries(Object.entries(Z).filter(([V])=>!J.has(V)))}function SZ(Z,$){if(Z===$)return!0;if(!Z||!$)return!1;let X=Object.entries(Z);if(X.length!==Object.keys($).length)return!1;return X.every(([J,V])=>Object.is($[J],V))}function AZ(Z,$,X,J){return Z!==void 0&&$.has(Z.accountId)&&!X.has(Z.accountId)&&Z.lastSeenAt>=J-u}function yZ(Z,$,X,J){return $>Z.inputBytes||X-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),X={get size(){return $.size},has:(J)=>$.has(J),get:(J)=>$.get(J),entries:()=>$.entries(),keys:()=>$.keys(),values:()=>$.values(),forEach:(J,V)=>{$.forEach((Y,G)=>{J.call(V,Y,G,X)})},[Symbol.iterator]:()=>$[Symbol.iterator]()};return Object.freeze(X)}function B0(Z,$,X){let J=new Map;for(let[V,Y]of Object.entries(Z??{})){if(V===X)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(X){let J={pid:process.pid,error:X instanceof Error?X.message:String(X)};if(w.has(Z))M.debug("sidebar write failed again",J);else w.add(Z),M.warn("sidebar write failed",J);throw X}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,$,X){let J=Symbol("sidebar authority changed");return wZ(Z,a(Z).update((V)=>{if(X?.canWrite&&!X.canWrite())return;let Y=$(V);if(Y===void 0)return;if(X?.vaultMode===!1)Y.vaultAccounts=void 0,Y.vaultDiscovered=void 0;if(X?.vaultMode??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(...V)=>{if(await X?.beforeRecheck?.(...V),X?.canWrite&&!X.canWrite())throw J}}).catch((V)=>{if(V!==J)throw V}))}function v(Z){let $;for(let X of[Z?.primary?.checkedAt,Z?.secondary?.checkedAt,Z?.checkedAt])if(typeof X==="number"&&Number.isFinite(X))$=$===void 0?X:Math.max($,X);return $}function jZ(Z,$){let X=v(Z),J=v($);if(J!==void 0&&(X===void 0||J>X))return $;return Z}function LZ(Z,$){return Z!==void 0&&$!==void 0&&Z===$}function f(Z,$){let X=Z?.checkedAt;if(typeof X==="number"&&Number.isFinite(X))return X;if(typeof $==="number"&&Number.isFinite($))return $;return}function BZ(Z,$,X,J,V){if(Z&&$){let Y=f(Z,J),G=f($,V);if(G!==void 0&&(Y===void 0||G>Y))return $;return Z}return X?$: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 X=(J)=>typeof J.checkedAt==="number"&&Number.isFinite(J.checkedAt)?J.checkedAt:Number.NEGATIVE_INFINITY;return X($)>X(Z)?$:Z}function QZ(Z,$){if(!Z)return $;if(!$)return Z;let X=v(Z),J=v($),V=J!==void 0&&(X===void 0||J>X),Y=BZ(Z.primary,$.primary,V,Z.checkedAt,$.checkedAt),G=BZ(Z.secondary,$.secondary,V,Z.checkedAt,$.checkedAt),z=V?UZ($,Z):UZ(Z,$),L=z===void 0&&(Z.spendControlCleared===!0||$.spendControlCleared===!0),U=Q0(Z.credits,$.credits),K;for(let N of[f(Y),f(G)])if(N!==void 0)K=K===void 0?N:Math.max(K,N);let{spendControl:Q,spendControlCleared:j,credits:B,...D}=Z;return{...D,primary:Y,secondary:G,...z!==void 0?{spendControl:z}:{},...L?{spendControlCleared:!0}:{},...U!==void 0?{credits:U}:{},checkedAt:K??Z.checkedAt}}function u0(Z,$=O(),X){return _(async()=>{await R($,(J)=>{let V=new Map(J.fallbacks.map((K)=>[K.id,K])),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),L=Date.now(),U=I(J.stickyAssignments,Y?void 0:o(r(Z)),L);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((K)=>{let Q=V.get(K.id),j=LZ(K.accountId,Q?.accountId),B=j?QZ(K.quota,Q?.quota??null):jZ(K.quota,Q?.quota??null);return{...K,quota:B,accountId:j?K.accountId:B===Q?.quota&&B!==K.quota?Q?.accountId:K.accountId}}),activeId:J.activeId,activeRouting:J.activeRouting,stickyAssignments:U,lastUpdated:Math.max(L,J.lastUpdated+1),accountPool:Z.accountPool===!0?!0:void 0,vaultAccounts:Z.vaultAccounts,vaultDiscovered:Z.vaultDiscovered}},X)})}function r0(Z,$,X=O(),J){return _(async()=>{await R(X,(V)=>{let Y=vZ({...V.activeRouting,[Z.sessionId]:{activeId:Z.activeId,route:Z.route,updatedAt:Z.updatedAt}},$,Date.now()),G=I(V.stickyAssignments,J?.vaultMode??V.vaultAccounts!==void 0?void 0:o($),Date.now());return{...V,activeId:Z.activeId,route:Z.route,activeRouting:Y,stickyAssignments:G,lastUpdated:Math.max(Date.now(),V.lastUpdated+1)}},J)})}function c0(Z,$=O(),X){return _(async()=>{await R($,(J)=>({...J,activeId:Z.activeId,route:Z.route,lastUpdated:Math.max(Date.now(),J.lastUpdated+1)}),X)})}function o0(Z,$,X=O(),J){return _(async()=>{await R(X,(V)=>{let Y=Date.now(),G=vZ(V.activeRouting,$,Y,Z),z=I(V.stickyAssignments,J?.vaultMode??V.vaultAccounts!==void 0?void 0:o($),Y,T(Z));return{...V,activeRouting:G,stickyAssignments:z,lastUpdated:Math.max(Date.now(),V.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 X=T($.sessionId),J=new Set($.validPinnedAccountIds),V=new Set($.excludeAccountIds),Y=I(Z.stickyAssignments,J,$.now),G=!SZ(Z.stickyAssignments,Y),z=Y?.[X],L=z!==void 0&&kZ(z,$.wireAccountIdByAccount?.[z.accountId]);if(AZ(z,J,V,$.now)&&!L){let Q=yZ(z,$.requestBytes,$.now,$.wireAccountIdByAccount?.[z.accountId]),j=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:j,next:void 0};return{assignment:j,next:{...Z,stickyAssignments:{...Y,[X]:j},lastUpdated:Math.max($.now,Z.lastUpdated+1)}}}let U=$.choose(B0(Y,$.quotaCheckedAtByAccount,L?X:void 0));if(!U){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 K={accountId:U.accountId,assignedAt:$.now,lastSeenAt:$.now,inputBytes:$.requestBytes,...U.quotaCheckedAt===void 0?{}:{quotaCheckedAt:U.quotaCheckedAt},...$.wireAccountIdByAccount?.[U.accountId]===void 0?{}:{wireAccountId:$.wireAccountIdByAccount?.[U.accountId]}};return{assignment:K,next:{...Z,stickyAssignments:fZ({...Y,[X]:K},X),lastUpdated:Math.max($.now,Z.lastUpdated+1)}}}async function a0(Z,$=O(),X){let J=T(Z.sessionId),V=(await U0($)).stickyAssignments?.[J];if(hZ(V,Z))return V;let Y;return await _(async()=>{await R($,(G)=>{let z=pZ(G,Z);return Y=z.assignment,z.next},X)}),Y}function i0(Z,$){let X=Z.stickyAssignments?.[T($.sessionId)];if(hZ(X,$))return{assignment:X,next:void 0};return pZ(Z,$)}function s0(Z,$=O(),X){let J=T(Z.sessionId),V=new Set(Z.validPinnedAccountIds);return _(async()=>{await R($,(Y)=>{let G=Date.now(),z=I(Y.stickyAssignments,X?.vaultMode??Y.vaultAccounts!==void 0?void 0:V,G),L=z?.[J];if(L&&L.assignedAt>Z.assignment.assignedAt){if(SZ(Y.stickyAssignments,z))return;return{...Y,stickyAssignments:z,lastUpdated:Math.max(G,Y.lastUpdated+1)}}let K=L!==void 0&&L.accountId===Z.assignment.accountId&&L.assignedAt===Z.assignment.assignedAt?{...Z.assignment,inputBytes:Math.max(L.inputBytes,Z.assignment.inputBytes),lastSeenAt:Math.max(L.lastSeenAt,Z.assignment.lastSeenAt)}:Z.assignment;return{...Y,stickyAssignments:fZ({...z,[J]:K},J),lastUpdated:Math.max(G,Y.lastUpdated+1)}},X)})}async function n0(Z,$=O()){let X=T(Z),J=!1;return await _(async()=>{await R($,(V)=>{let Y=V.stickyAssignments;if(Y?.[X]===void 0){J=!1;return}J=!0;let{[X]:G,...z}=Y;return{...V,...Object.keys(z).length>0?{stickyAssignments:z}:{stickyAssignments:void 0},lastUpdated:Math.max(Date.now(),V.lastUpdated+1)}})}),J}function e0(){return m}var D0=500;function N0(Z,$,X){return new Promise((J,V)=>{let Y=setTimeout(()=>J(X()),$);Y.unref?.(),Z.then((G)=>{clearTimeout(Y),J(G)},(G)=>{clearTimeout(Y),V(G)})})}function t0(Z,$={}){let X=$.readBudgetMs??D0,J,V,Y=()=>{try{let z=sZ(Z);return`${z.ino}:${z.size}:${z.mtimeMs}`}catch{return}},G=(z)=>{if(V&&V.key===z)return V.promise;let L=Date.now(),U=G0(Z).then((j)=>{if(!J||J.readAt<=L)J={state:j,readAt:L,key:z};return{state:j,readAt:L}}),K={key:z,promise:U};V=K;let Q=()=>{if(V===K)V=void 0};return U.then(Q,Q),U};return{get(){let z=Y();if(J&&J.key===z)return Promise.resolve({state:J.state,readAt:J.readAt});return N0(G(z),X,()=>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,$,X){let J={assignment:X};Z.delete($),Z.set($,J);while(Z.size>MZ){let V=Z.keys().next().value;if(V===void 0)break;Z.delete(V)}return J}function $1(Z,$){if($.size===0)return Z.state;let X={...Z.state.stickyAssignments},J=!1;for(let[V,Y]of $){if(Y.persistedAt!==void 0&&Z.readAt>Y.persistedAt){$.delete(V);continue}X[V]=Y.assignment,J=!0}if(!J)return Z.state;return{...Z.state,stickyAssignments:X}}function J1(Z){let $=Z.retryDelayMs??500,X=Z.maxRetryDelayMs??30000,J=new Map,V=new Map,Y=new Set,G=0,z=$,L,U=!1,K=()=>{if(L||U||V.size===0)return;L=setTimeout(()=>{L=void 0;let j=[...V];V.clear(),z=Math.min(z*2,X);for(let[B,D]of j){let N=J.get(B);if(N!==void 0)Q(B,D.label,D.write,N)}},z),L.unref?.()},Q=(j,B,D,N)=>{let P;try{P=D()}catch(W){P=Promise.reject(W)}P.then(()=>{if(J.get(j)!==N)return;if(J.delete(j),Y.delete(j))Z.logger.info("sidebar bookkeeping write recovered",{pid:process.pid,write:B});if(Y.size===0)z=$;Z.onWritten?.()},(W)=>{if(J.get(j)!==N)return;let H={pid:process.pid,write:B,error:W instanceof Error?W.message:String(W)};if(U){J.delete(j),Z.logger.debug("sidebar bookkeeping write dropped",H);return}if(Y.has(j))Z.logger.debug("sidebar bookkeeping write failed again",H);else Y.add(j),Z.logger.warn("sidebar bookkeeping write failed; retrying in the background",H);V.set(j,{label:B,write:D}),K()})};return{enqueue(j,B,D){G+=1,J.set(j,G),V.delete(j),Q(j,B,D,G)},cancel(j){J.delete(j),V.delete(j),Y.delete(j)},stop(){if(U=!0,L)clearTimeout(L);L=void 0,V.clear()}}}function P0(Z){let $=Z.activeId;if(Z.vaultAccounts!==void 0){let X=c(Z).filter((V)=>V.enabled&&V.routable!==!1),J=X.find((V)=>V.id===$)??X[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 X=Z.fallbacks.find((J)=>J.enabled&&J.id===$);if(X)return{id:X.id,name:X.label??X.id,quota:X.quota,killed:X.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((X)=>{let J=Z[X];return J?[{kind:"reading",scope:"all",label:X,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 X=Z?.primary?.usedPercent??null,J=Z?.secondary?.usedPercent??null,V=mZ(Z,$);return{primaryUsedPercent:X,secondaryUsedPercent:J,text:!V||V.limits.length===0&&!V.budget?null:g(V,{now:$,form:"compact"})}}function gZ(Z){return Z.route==="sticky-balanced"?"roster":TZ(Z.route)}function V1(Z,$={}){let X=$.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,X),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:X}):!1,text:z?g(z,{now:X,form:"narrow"}):null}})}function W0(Z,$,X){let J=[{id:"main",name:"main",quota:Z.main.quota,killed:Z.main.killed},...Z.fallbacks.filter((Y)=>Y.enabled&&(X||Y.id===$)).map((Y)=>({id:Y.id,name:Y.label??Y.id,quota:Y.quota,killed:Y.killed}))],V=new Map(J.map((Y)=>[Y.id,Y]));return d(J.map((Y)=>Y.id),gZ(Z),"main").flatMap((Y)=>{let G=V.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 X="",J=0;for(let V of Z){let Y=DZ(V);if(J+Y>$-1)break;X+=V,J+=Y}return`${X}…`}var H0=300000,O0=0.01,_0=1;function z1(Z,$,X){if(!Z.resetsAt)return null;let J=new Date(Z.resetsAt).getTime();if(!Number.isFinite(J))return null;let V=J-$,Y=X-V;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),L=G-z,U=Math.abs(L)<_0?"on-pace":L>0?"deficit":"reserve",K=null;if(G>0){let Q=Y*100/G,j=V+Q;if(j<J)K=new Date(j).toISOString()}return{pacePercent:z,deltaPercent:L,state:U,runsOutAt:K}}
2
- export{v0 as Ic,f0 as Jc,rZ as Kc,S0 as Lc,g0 as Mc,u as Nc,MZ as Oc,T as Pc,O as Qc,q as Rc,S as Sc,G0 as Tc,K0 as Uc,GZ as Vc,IZ as Wc,bZ as Xc,xZ as Yc,E as Zc,j0 as _c,d0 as $c,vZ as ad,I as bd,l0 as cd,u0 as dd,r0 as ed,c0 as fd,o0 as gd,pZ as hd,a0 as id,i0 as jd,s0 as kd,n0 as ld,e0 as md,D0 as nd,N0 as od,t0 as pd,Z1 as qd,$1 as rd,J1 as sd,P0 as td,mZ as ud,X1 as vd,V1 as wd,DZ as xd,Y1 as yd,z1 as zd};
1
+ import{Gd as NZ,Hd as PZ,Jd as g,Kd as WZ,Ld as HZ,Nf as _Z,Pd as d,Rf as TZ,Tf as RZ}from"./index-x3q449sn.js";import{ag as XZ,fg as VZ,gg as YZ,ig as y,kg as x}from"./index-z4tfv40j.js";import{Pg as OZ}from"./index-xcsz00nr.js";import{Qg as b,Rg as $Z,Wg as A,Xg as JZ}from"./index-c4h4t3wg.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:X,normalize:J}=Z,V=Promise.resolve(),Y=(B)=>{if(B==="")return X;try{return J(JSON.parse(B))}catch{return X}},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 X}},L=(B,D)=>{let N=V.then(B).then((P)=>D?.onResult?.(P));return V=N.catch(()=>{}),N},U={...x.sidebar,name:Z.lockName??x.sidebar.name,timeoutMs:Z.timeoutMs??x.sidebar.timeoutMs},K=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($,U,async(W)=>{let H=B(await z(),D);if(H===void 0)return"skipped";return await K(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"}}},j=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($,U,async(F)=>{let s=async(C)=>({value:C,held:await K(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)=>L(()=>j(()=>B,D),D),update:(B,D)=>L(()=>j(B,D),D)}}function v0(Z){let $=Z?.credits;if($===null||typeof $!=="object")return;let{hasCredits:X,unlimited:J,balance:V}=$;if(typeof X!=="boolean"||typeof J!=="boolean")return;return WZ({hasCredits:X,unlimited:J,...typeof V==="number"?{balance:V}:{}})}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 X of l){let J=Z[X];if(!J)continue;let V=J.windowMinutes,Y=V!==void 0&&Number.isFinite(V)&&V>0?V:uZ[X];$.push({key:X,label:rZ(V,X),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[X,J]of Object.entries(Z)){if(J===null||typeof J!=="object"||Array.isArray(J))continue;let V=J;if(typeof V.activeId!=="string"||typeof V.route!=="string"||typeof V.updatedAt!=="number"||!Number.isFinite(V.updatedAt))continue;$[X]={activeId:V.activeId,route:V.route,updatedAt:V.updatedAt}}return Object.keys($).length>0?$:void 0}function Y0(Z){if(Z===null||typeof Z!=="object"||Array.isArray(Z))return;let $={};for(let[X,J]of Object.entries(Z)){if(!J0.test(X)||J===null||typeof J!=="object"||Array.isArray(J))continue;let V=J;if(typeof V.accountId!=="string"||V.accountId.length===0||typeof V.assignedAt!=="number"||!Number.isFinite(V.assignedAt)||V.assignedAt<0||typeof V.lastSeenAt!=="number"||!Number.isFinite(V.lastSeenAt)||V.lastSeenAt<0||typeof V.inputBytes!=="number"||!Number.isFinite(V.inputBytes)||V.inputBytes<0)continue;let Y=V.quotaCheckedAt;if(Y!==void 0&&(typeof Y!=="number"||!Number.isFinite(Y)||Y<0))continue;let G=V.wireAccountId;$[X]={accountId:V.accountId,assignedAt:V.assignedAt,lastSeenAt:V.lastSeenAt,inputBytes:V.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,X=$.main,J;if(X!==null&&typeof X==="object"&&!Array.isArray(X)){let j=X;J={quota:"quota"in j?j.quota:null,killed:typeof j.killed==="boolean"?j.killed:!1,...typeof j.mainAccountId==="string"?{mainAccountId:j.mainAccountId}:{},...typeof j.quotaBackedOff==="boolean"?{quotaBackedOff:j.quotaBackedOff}:{},...typeof j.quotaBackoffUntil==="number"?{quotaBackoffUntil:j.quotaBackoffUntil}:{},...typeof j.refreshBackedOff==="boolean"?{refreshBackedOff:j.refreshBackedOff}:{},...typeof j.refreshBackoffUntil==="number"?{refreshBackoffUntil:j.refreshBackoffUntil}:{},...qZ(j.resetCredits)}}else J={quota:null,killed:!1};let V=zZ($.fallbacks),Y=Array.isArray($.vaultAccounts)?zZ($.vaultAccounts):void 0,G=typeof $.activeId==="string"?$.activeId:void 0,z=typeof $.route==="string"?$.route:q.route,L=typeof $.lastUpdated==="number"?$.lastUpdated:0,U=typeof $.planType==="string"?$.planType:void 0,K=V0($.activeRouting),Q=Y0($.stickyAssignments);return{main:J,fallbacks:V,activeId:G,route:z,lastUpdated:L,...K!==void 0?{activeRouting:K}:{},...Q!==void 0?{stickyAssignments:Q}:{},...U!==void 0?{planType:U}:{},...$.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,$,X=Date.now()){if(!(Z.updatedAt>=X-K0&&Z.updatedAt<=X))return!1;if($===void 0)return!0;return Z.activeId==="main"||$.some((V)=>V.enabled!==!1&&V.routable!==!1&&V.killed!==!0&&V.id===Z.activeId)}function bZ(Z,$=Date.now()){let X=Z?.spendControl;if(X?.reached!==!0||typeof X.resetsAt!=="string")return;let J=Date.parse(X.resetsAt);if(!Number.isFinite(J)||J<=$)return;return{resetsAt:X.resetsAt,resetAtMs:J}}function xZ(Z,$=Date.now()){let X;for(let V of l){let Y=Z?.[V];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(!X||G<X.resetAtMs)X={resetsAt:Y.resetsAt,resetAtMs:G}}let J=bZ(Z,$);if(J&&(!X||J.resetAtMs<X.resetAtMs))X=J;return X}function E(Z,$=Date.now()){return xZ(Z,$)!==void 0}function j0(Z,$,X=Date.now()){if(!$||Z.route!=="sticky-balanced")return;let J=Z.stickyAssignments?.[T($)];if(!J||J.lastSeenAt<X-u)return;if(J.accountId==="main"&&Z.vaultAccounts===void 0)return Z.main?.killed||E(Z.main?.quota,X)?void 0:"main";let V=r(Z).find((Y)=>Y.id===J.accountId);if(!V||V.enabled===!1||V.routable===!1||V.killed===!0||E(V.quota,X))return;return V.id}function d0(Z,$,X=Date.now()){if(!$){if(Z.vaultAccounts===void 0)return{activeId:Z.activeId??"main",route:Z.route};let K=Z.vaultAccounts.find((Q)=>Q.id===Z.activeId&&Q.enabled&&Q.routable!==!1&&!Q.killed);if(K&&!E(K.quota,X))return{activeId:K.id,route:Z.route}}let J=$?Z.activeRouting?.[$]:void 0,V=r(Z),Y=J?.activeId==="main"?Z.main.quota:V.find((K)=>K.id===J?.activeId)?.quota;if(J&&(Z.vaultAccounts===void 0||J.activeId.startsWith("vault:"))&&IZ(J,V,X)&&!E(Y,X))return{activeId:J.activeId,route:J.route};let G=j0(Z,$,X);if(G)return{activeId:G,route:Z.route};let z=Z.vaultAccounts!==void 0,L=(z?c(Z):Z.fallbacks).filter((K)=>K.enabled&&K.routable!==!1&&!K.killed),U=L.find((K)=>!E(K.quota,X))??L[0];return{activeId:z?U?.id??"vault":Z.route==="fallback-first"&&U?U.id:"main",route:Z.route}}function c(Z){let $=Z.vaultAccounts??[],X=new Map($.map((J)=>[J.id,J]));return d($.map((J)=>J.id),gZ(Z),_Z($)??"").flatMap((J)=>{let V=X.get(J);return V?[V]:[]})}function vZ(Z,$,X=Date.now(),J){if(!Z)return;let V=Object.entries(Z).filter(([G,z])=>G!==J&&IZ(z,$,X)),Y=V.length<=GZ?V:V.sort((G,z)=>z[1].updatedAt-G[1].updatedAt).slice(0,GZ);return Y.length>0?Object.fromEntries(Y):void 0}function I(Z,$,X=Date.now(),J){if(!Z)return;let V=0,Y=0,G=0,z=[];for(let[U,K]of Object.entries(Z)){if(U===J){G+=1;continue}if(K.lastSeenAt<X-u){Y+=1;continue}if($!==void 0&&!$.has(K.accountId)){V+=1;continue}z.push([U,K])}let L=V+Y+G;if(L>0)M.debug("pruned sticky assignments",{pid:process.pid,removed:L,reasons:{"account-not-in-roster":V,expired:Y,"explicit-removal":G}});return z.length>0?Object.fromEntries(z):void 0}function fZ(Z,$){let X=Object.keys(Z).length-MZ;if(X<=0)return Z;let J=new Set(Object.entries(Z).filter(([V])=>V!==$).sort(([V,Y],[G,z])=>Y.lastSeenAt-z.lastSeenAt||V.localeCompare(G)).slice(0,X).map(([V])=>V));return Object.fromEntries(Object.entries(Z).filter(([V])=>!J.has(V)))}function SZ(Z,$){if(Z===$)return!0;if(!Z||!$)return!1;let X=Object.entries(Z);if(X.length!==Object.keys($).length)return!1;return X.every(([J,V])=>Object.is($[J],V))}function AZ(Z,$,X,J){return Z!==void 0&&$.has(Z.accountId)&&!X.has(Z.accountId)&&Z.lastSeenAt>=J-u}function yZ(Z,$,X,J){return $>Z.inputBytes||X-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),X={get size(){return $.size},has:(J)=>$.has(J),get:(J)=>$.get(J),entries:()=>$.entries(),keys:()=>$.keys(),values:()=>$.values(),forEach:(J,V)=>{$.forEach((Y,G)=>{J.call(V,Y,G,X)})},[Symbol.iterator]:()=>$[Symbol.iterator]()};return Object.freeze(X)}function B0(Z,$,X){let J=new Map;for(let[V,Y]of Object.entries(Z??{})){if(V===X)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(X){let J={pid:process.pid,error:X instanceof Error?X.message:String(X)};if(w.has(Z))M.debug("sidebar write failed again",J);else w.add(Z),M.warn("sidebar write failed",J);throw X}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,$,X){let J=Symbol("sidebar authority changed");return wZ(Z,a(Z).update((V)=>{if(X?.canWrite&&!X.canWrite())return;let Y=$(V);if(Y===void 0)return;if(X?.vaultMode===!1)Y.vaultAccounts=void 0,Y.vaultDiscovered=void 0;if(X?.vaultMode??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(...V)=>{if(await X?.beforeRecheck?.(...V),X?.canWrite&&!X.canWrite())throw J}}).catch((V)=>{if(V!==J)throw V}))}function v(Z){let $;for(let X of[Z?.primary?.checkedAt,Z?.secondary?.checkedAt,Z?.checkedAt])if(typeof X==="number"&&Number.isFinite(X))$=$===void 0?X:Math.max($,X);return $}function jZ(Z,$){let X=v(Z),J=v($);if(J!==void 0&&(X===void 0||J>X))return $;return Z}function LZ(Z,$){return Z!==void 0&&$!==void 0&&Z===$}function f(Z,$){let X=Z?.checkedAt;if(typeof X==="number"&&Number.isFinite(X))return X;if(typeof $==="number"&&Number.isFinite($))return $;return}function BZ(Z,$,X,J,V){if(Z&&$){let Y=f(Z,J),G=f($,V);if(G!==void 0&&(Y===void 0||G>Y))return $;return Z}return X?$: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 X=(J)=>typeof J.checkedAt==="number"&&Number.isFinite(J.checkedAt)?J.checkedAt:Number.NEGATIVE_INFINITY;return X($)>X(Z)?$:Z}function QZ(Z,$){if(!Z)return $;if(!$)return Z;let X=v(Z),J=v($),V=J!==void 0&&(X===void 0||J>X),Y=BZ(Z.primary,$.primary,V,Z.checkedAt,$.checkedAt),G=BZ(Z.secondary,$.secondary,V,Z.checkedAt,$.checkedAt),z=V?UZ($,Z):UZ(Z,$),L=z===void 0&&(Z.spendControlCleared===!0||$.spendControlCleared===!0),U=Q0(Z.credits,$.credits),K;for(let N of[f(Y),f(G)])if(N!==void 0)K=K===void 0?N:Math.max(K,N);let{spendControl:Q,spendControlCleared:j,credits:B,...D}=Z;return{...D,primary:Y,secondary:G,...z!==void 0?{spendControl:z}:{},...L?{spendControlCleared:!0}:{},...U!==void 0?{credits:U}:{},checkedAt:K??Z.checkedAt}}function u0(Z,$=O(),X){return _(async()=>{await R($,(J)=>{let V=new Map(J.fallbacks.map((K)=>[K.id,K])),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),L=Date.now(),U=I(J.stickyAssignments,Y?void 0:o(r(Z)),L);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((K)=>{let Q=V.get(K.id),j=LZ(K.accountId,Q?.accountId),B=j?QZ(K.quota,Q?.quota??null):jZ(K.quota,Q?.quota??null);return{...K,quota:B,accountId:j?K.accountId:B===Q?.quota&&B!==K.quota?Q?.accountId:K.accountId}}),activeId:J.activeId,activeRouting:J.activeRouting,stickyAssignments:U,lastUpdated:Math.max(L,J.lastUpdated+1),accountPool:Z.accountPool===!0?!0:void 0,vaultAccounts:Z.vaultAccounts,vaultDiscovered:Z.vaultDiscovered}},X)})}function r0(Z,$,X=O(),J){return _(async()=>{await R(X,(V)=>{let Y=vZ({...V.activeRouting,[Z.sessionId]:{activeId:Z.activeId,route:Z.route,updatedAt:Z.updatedAt}},$,Date.now()),G=I(V.stickyAssignments,J?.vaultMode??V.vaultAccounts!==void 0?void 0:o($),Date.now());return{...V,activeId:Z.activeId,route:Z.route,activeRouting:Y,stickyAssignments:G,lastUpdated:Math.max(Date.now(),V.lastUpdated+1)}},J)})}function c0(Z,$=O(),X){return _(async()=>{await R($,(J)=>({...J,activeId:Z.activeId,route:Z.route,lastUpdated:Math.max(Date.now(),J.lastUpdated+1)}),X)})}function o0(Z,$,X=O(),J){return _(async()=>{await R(X,(V)=>{let Y=Date.now(),G=vZ(V.activeRouting,$,Y,Z),z=I(V.stickyAssignments,J?.vaultMode??V.vaultAccounts!==void 0?void 0:o($),Y,T(Z));return{...V,activeRouting:G,stickyAssignments:z,lastUpdated:Math.max(Date.now(),V.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 X=T($.sessionId),J=new Set($.validPinnedAccountIds),V=new Set($.excludeAccountIds),Y=I(Z.stickyAssignments,J,$.now),G=!SZ(Z.stickyAssignments,Y),z=Y?.[X],L=z!==void 0&&kZ(z,$.wireAccountIdByAccount?.[z.accountId]);if(AZ(z,J,V,$.now)&&!L){let Q=yZ(z,$.requestBytes,$.now,$.wireAccountIdByAccount?.[z.accountId]),j=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:j,next:void 0};return{assignment:j,next:{...Z,stickyAssignments:{...Y,[X]:j},lastUpdated:Math.max($.now,Z.lastUpdated+1)}}}let U=$.choose(B0(Y,$.quotaCheckedAtByAccount,L?X:void 0));if(!U){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 K={accountId:U.accountId,assignedAt:$.now,lastSeenAt:$.now,inputBytes:$.requestBytes,...U.quotaCheckedAt===void 0?{}:{quotaCheckedAt:U.quotaCheckedAt},...$.wireAccountIdByAccount?.[U.accountId]===void 0?{}:{wireAccountId:$.wireAccountIdByAccount?.[U.accountId]}};return{assignment:K,next:{...Z,stickyAssignments:fZ({...Y,[X]:K},X),lastUpdated:Math.max($.now,Z.lastUpdated+1)}}}async function a0(Z,$=O(),X){let J=T(Z.sessionId),V=(await U0($)).stickyAssignments?.[J];if(hZ(V,Z))return V;let Y;return await _(async()=>{await R($,(G)=>{let z=pZ(G,Z);return Y=z.assignment,z.next},X)}),Y}function i0(Z,$){let X=Z.stickyAssignments?.[T($.sessionId)];if(hZ(X,$))return{assignment:X,next:void 0};return pZ(Z,$)}function s0(Z,$=O(),X){let J=T(Z.sessionId),V=new Set(Z.validPinnedAccountIds);return _(async()=>{await R($,(Y)=>{let G=Date.now(),z=I(Y.stickyAssignments,X?.vaultMode??Y.vaultAccounts!==void 0?void 0:V,G),L=z?.[J];if(L&&L.assignedAt>Z.assignment.assignedAt){if(SZ(Y.stickyAssignments,z))return;return{...Y,stickyAssignments:z,lastUpdated:Math.max(G,Y.lastUpdated+1)}}let K=L!==void 0&&L.accountId===Z.assignment.accountId&&L.assignedAt===Z.assignment.assignedAt?{...Z.assignment,inputBytes:Math.max(L.inputBytes,Z.assignment.inputBytes),lastSeenAt:Math.max(L.lastSeenAt,Z.assignment.lastSeenAt)}:Z.assignment;return{...Y,stickyAssignments:fZ({...z,[J]:K},J),lastUpdated:Math.max(G,Y.lastUpdated+1)}},X)})}async function n0(Z,$=O()){let X=T(Z),J=!1;return await _(async()=>{await R($,(V)=>{let Y=V.stickyAssignments;if(Y?.[X]===void 0){J=!1;return}J=!0;let{[X]:G,...z}=Y;return{...V,...Object.keys(z).length>0?{stickyAssignments:z}:{stickyAssignments:void 0},lastUpdated:Math.max(Date.now(),V.lastUpdated+1)}})}),J}function e0(){return m}var D0=500;function N0(Z,$,X){return new Promise((J,V)=>{let Y=setTimeout(()=>J(X()),$);Y.unref?.(),Z.then((G)=>{clearTimeout(Y),J(G)},(G)=>{clearTimeout(Y),V(G)})})}function t0(Z,$={}){let X=$.readBudgetMs??D0,J,V,Y=()=>{try{let z=sZ(Z);return`${z.ino}:${z.size}:${z.mtimeMs}`}catch{return}},G=(z)=>{if(V&&V.key===z)return V.promise;let L=Date.now(),U=G0(Z).then((j)=>{if(!J||J.readAt<=L)J={state:j,readAt:L,key:z};return{state:j,readAt:L}}),K={key:z,promise:U};V=K;let Q=()=>{if(V===K)V=void 0};return U.then(Q,Q),U};return{get(){let z=Y();if(J&&J.key===z)return Promise.resolve({state:J.state,readAt:J.readAt});return N0(G(z),X,()=>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,$,X){let J={assignment:X};Z.delete($),Z.set($,J);while(Z.size>MZ){let V=Z.keys().next().value;if(V===void 0)break;Z.delete(V)}return J}function $1(Z,$){if($.size===0)return Z.state;let X={...Z.state.stickyAssignments},J=!1;for(let[V,Y]of $){if(Y.persistedAt!==void 0&&Z.readAt>Y.persistedAt){$.delete(V);continue}X[V]=Y.assignment,J=!0}if(!J)return Z.state;return{...Z.state,stickyAssignments:X}}function J1(Z){let $=Z.retryDelayMs??500,X=Z.maxRetryDelayMs??30000,J=new Map,V=new Map,Y=new Set,G=0,z=$,L,U=!1,K=()=>{if(L||U||V.size===0)return;L=setTimeout(()=>{L=void 0;let j=[...V];V.clear(),z=Math.min(z*2,X);for(let[B,D]of j){let N=J.get(B);if(N!==void 0)Q(B,D.label,D.write,N)}},z),L.unref?.()},Q=(j,B,D,N)=>{let P;try{P=D()}catch(W){P=Promise.reject(W)}P.then(()=>{if(J.get(j)!==N)return;if(J.delete(j),Y.delete(j))Z.logger.info("sidebar bookkeeping write recovered",{pid:process.pid,write:B});if(Y.size===0)z=$;Z.onWritten?.()},(W)=>{if(J.get(j)!==N)return;let H={pid:process.pid,write:B,error:W instanceof Error?W.message:String(W)};if(U){J.delete(j),Z.logger.debug("sidebar bookkeeping write dropped",H);return}if(Y.has(j))Z.logger.debug("sidebar bookkeeping write failed again",H);else Y.add(j),Z.logger.warn("sidebar bookkeeping write failed; retrying in the background",H);V.set(j,{label:B,write:D}),K()})};return{enqueue(j,B,D){G+=1,J.set(j,G),V.delete(j),Q(j,B,D,G)},cancel(j){J.delete(j),V.delete(j),Y.delete(j)},stop(){if(U=!0,L)clearTimeout(L);L=void 0,V.clear()}}}function P0(Z){let $=Z.activeId;if(Z.vaultAccounts!==void 0){let X=c(Z).filter((V)=>V.enabled&&V.routable!==!1),J=X.find((V)=>V.id===$)??X[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 X=Z.fallbacks.find((J)=>J.enabled&&J.id===$);if(X)return{id:X.id,name:X.label??X.id,quota:X.quota,killed:X.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((X)=>{let J=Z[X];return J?[{kind:"reading",scope:"all",label:X,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 X=Z?.primary?.usedPercent??null,J=Z?.secondary?.usedPercent??null,V=mZ(Z,$);return{primaryUsedPercent:X,secondaryUsedPercent:J,text:!V||V.limits.length===0&&!V.budget?null:g(V,{now:$,form:"compact"})}}function gZ(Z){return Z.route==="sticky-balanced"?"roster":TZ(Z.route)}function V1(Z,$={}){let X=$.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,X),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:X}):!1,text:z?g(z,{now:X,form:"narrow"}):null}})}function W0(Z,$,X){let J=[{id:"main",name:"main",quota:Z.main.quota,killed:Z.main.killed},...Z.fallbacks.filter((Y)=>Y.enabled&&(X||Y.id===$)).map((Y)=>({id:Y.id,name:Y.label??Y.id,quota:Y.quota,killed:Y.killed}))],V=new Map(J.map((Y)=>[Y.id,Y]));return d(J.map((Y)=>Y.id),gZ(Z),"main").flatMap((Y)=>{let G=V.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 X="",J=0;for(let V of Z){let Y=DZ(V);if(J+Y>$-1)break;X+=V,J+=Y}return`${X}…`}var H0=300000,O0=0.01,_0=1;function z1(Z,$,X){if(!Z.resetsAt)return null;let J=new Date(Z.resetsAt).getTime();if(!Number.isFinite(J))return null;let V=J-$,Y=X-V;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),L=G-z,U=Math.abs(L)<_0?"on-pace":L>0?"deficit":"reserve",K=null;if(G>0){let Q=Y*100/G,j=V+Q;if(j<J)K=new Date(j).toISOString()}return{pacePercent:z,deltaPercent:L,state:U,runsOutAt:K}}
2
+ export{v0 as Lc,f0 as Mc,rZ as Nc,S0 as Oc,g0 as Pc,u as Qc,MZ as Rc,T as Sc,O as Tc,q as Uc,S as Vc,G0 as Wc,K0 as Xc,GZ as Yc,IZ as Zc,bZ as _c,xZ as $c,E as ad,j0 as bd,d0 as cd,vZ as dd,I as ed,l0 as fd,u0 as gd,r0 as hd,c0 as id,o0 as jd,pZ as kd,a0 as ld,i0 as md,s0 as nd,n0 as od,e0 as pd,D0 as qd,N0 as rd,t0 as sd,Z1 as td,$1 as ud,J1 as vd,P0 as wd,mZ as xd,X1 as yd,V1 as zd,DZ as Ad,Y1 as Bd,z1 as Cd};
@@ -1,4 +1,4 @@
1
- import{Ng as _,Og as U,Sg as g,Tg as p,Ug as E,Yg as c}from"./index-asjkhkty.js";import{createHash as Oz,randomUUID as y}from"node:crypto";import{chmod as zz,mkdir as Gz,open as Jz,readdir as F,rename as Kz,rmdir as Nz,stat as T,unlink as I}from"node:fs/promises";import{uptime as Qz}from"node:os";import{join as A,resolve as b}from"node:path";function S(z){return(z.now??Date.now)()-(z.uptime??Qz)()*1000-300000}function x(z,J,Q){let X=z.startedAt===void 0?J?.mtimeMs:z.startedAt;return typeof X==="number"&&Number.isFinite(X)&&X<Q}async function Vz(z,J,Q,X){if(!Q)return;await X?.(z);try{let K=await E(z),G=await T(z);if(K===J&&G.dev===Q.dev&&G.ino===Q.ino&&G.mtimeMs===Q.mtimeMs&&G.size===Q.size)await I(z).catch(()=>{})}catch(K){if(K instanceof U&&K.code!=="ENOENT")throw K}}function a(z){return typeof z==="number"&&Number.isSafeInteger(z)&&z>0}function k(z){if(!a(z))return!1;try{return process.kill(z,0),!0}catch(J){return J.code==="EPERM"}}function Ez(z){return(J)=>Wz(J,z)}function Wz(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 Xz(z){let J=/^port-(\d+)\.json$/.exec(z);return J?Number(J[1]):void 0}function s(z,J){if(z===null||typeof z!=="object"||Array.isArray(z))return!1;let{pid:Q,port:X,token:K}=z;return a(Q)&&Xz(J)===Q&&typeof X==="number"&&Number.isInteger(X)&&X>=1&&X<=65535&&typeof K==="string"&&K.length>0}async function l(z,J){J?.debug("rpc corrupt port file",{pid:process.pid,portFile:z}),await I(z).catch(()=>{})}async function Lz(z,J,Q={}){let X=async()=>{let K=A(z,`port-${J.pid}.json`);if(_)return await p(z,Q.secureDir??!1),await Q.beforeWrite?.(),await c(K,JSON.stringify({...J,startedAt:Date.now()}),{stagePath:`${K}.${(Q.stageName??y)()}.tmp`}),K;if(await Gz(z,{recursive:!0,mode:Q.secureDir?448:void 0}),Q.secureDir)await zz(z,448);await Q.beforeWrite?.();let G={...J,startedAt:Date.now()},Y=`${K}.${(Q.stageName??y)()}.tmp`,V,N=!1;try{V=await Jz(Y,"wx",384),N=!0,await V.writeFile(JSON.stringify(G),"utf8"),await V.chmod(384),await V.close(),V=void 0,await Kz(Y,K),N=!1}finally{if(await V?.close().catch(()=>{}),N)await I(Y).catch(()=>{})}return K};for(let K=1;;K+=1)try{return await X()}catch(G){if(G.code!=="ENOENT"||K===5)throw G;await new Promise((Y)=>setTimeout(Y,25))}}async function Iz(z,J,Q,X,K={}){let G=S(K),Y;try{Y=await F(z,{withFileTypes:!0})}catch(N){if(N.code==="ENOENT")return;throw N}let V=b(J);for(let N of Y){if(!N.isDirectory()||!Q(N.name))continue;let W=A(z,N.name);if(!await Yz(W,X,K,G))continue;if(b(W)!==V)await Nz(W).catch(()=>{})}}async function Yz(z,J,Q={},X=S(Q)){let K;try{K=await F(z)}catch(G){if(G.code==="ENOENT")return!1;throw G}for(let G of K){if(!G.startsWith("port-")||!G.endsWith(".json"))continue;let Y=A(z,G),V=await T(Y).catch(()=>{return}),N;try{N=await E(Y)}catch($){if($ instanceof U&&$.code!=="ENOENT")throw $;continue}if(N===void 0)continue;let W;try{W=JSON.parse(N)}catch{await l(Y,J);continue}if(!s(W,G)){await l(Y,J);continue}let Z=W;if(!k(Z.pid))await I(Y).catch(()=>{});else if(x(Z,V,X))await Vz(Y,N,V,Q.beforeRemove)}return!0}async function d(z,J,Q={}){let X=S(Q);if(!k(J.pid))return null;let K=A(b(z),`port-${J.pid}.json`);try{if(_)await g(K,"file");let G=await T(K);if(x(J,G,X))return null;return`${K}:${G.dev}:${G.ino}:${G.mtimeMs}:${G.size}`}catch(G){if(G instanceof U&&G.code!=="ENOENT")throw G;return null}}async function n(z,J,Q={}){let X=S(Q),K;try{if(_)await g(z,"directory");K=await F(z)}catch(W){if(W instanceof U&&W.code!=="ENOENT")throw W;return null}let G=[];for(let W of K){if(!W.startsWith("port-")||!W.endsWith(".json"))continue;try{let Z=JSON.parse(await E(A(z,W)));if(s(Z,W))if(k(Z.pid)){let $=Z.startedAt===void 0?await T(A(z,W)).catch(()=>{return}):void 0;if(!x(Z,$,X))G.push(Z)}else await I(A(z,W)).catch(()=>{})}catch(Z){if(Z instanceof U&&Z.code!=="ENOENT")throw Z}}if(G.length===0)return null;let Y=J!==void 0&&J>=1?G.filter((W)=>W.pid===J):[];if(Q.exactPid===!0&&Y.length===0)return null;let V=Y.length>0?Y:G,N=(W)=>typeof W.startedAt==="number"&&Number.isFinite(W.startedAt)?W.startedAt:-1/0;return V.sort((W,Z)=>N(Z)-N(W))[0]??null}import{open as Zz}from"node:fs/promises";import{connect as $z}from"node:net";import{join as Hz,resolve as t}from"node:path";var e=2000,q=new Map,B=new Map;async function qz(z,J){let Q=Hz(t(z),`port-${J.pid}.json`);if(_){let K=JSON.parse(await E(Q));if(K.pid!==J.pid||K.port!==J.port||K.token!==J.token)return null;return null}let X;try{X=await Zz(Q,"r");let K=await X.stat(),G=JSON.parse(await X.readFile("utf8"));if(G.pid!==J.pid||G.port!==J.port||G.token!==J.token)return null;return`${Q}:${K.dev}:${K.ino}:${K.mtimeMs}:${K.size}`}catch{return null}finally{await X?.close().catch(()=>{})}}async function i(z,J,Q,X){let K=q.get(z);if(!_&&K&&await d(J,K.entry)===K.identity)return K;q.delete(z);let G=B.get(z);if(G)return G;let Y=(async()=>{let V=await(X.discover??n)(J,Q,X);if(!V)return null;let N=await qz(J,V);if(!N)return{entry:V,identity:""};let W={entry:V,identity:N};return q.set(z,W),W})();B.set(z,Y);try{return await Y}finally{if(B.get(z)===Y)B.delete(z)}}async function o(z,J,Q,X=e){return new Promise((K)=>{let G,Y=!1,V=!1,N=(Z,$=!1)=>{if(Y)return;Y=!0,clearTimeout(W),G?.destroy(),K({value:Z,stale:$})},W=setTimeout(()=>N(null),X);try{let Z=JSON.stringify(Q);G=$z({host:"127.0.0.1",port:z.port}),G.on("connect",()=>{V=!0,G?.write(`POST /rpc/${J} HTTP/1.0\r
1
+ import{$g as c,Qg as _,Rg as U,Vg as g,Wg as p,Xg as E}from"./index-c4h4t3wg.js";import{createHash as Oz,randomUUID as y}from"node:crypto";import{chmod as zz,mkdir as Gz,open as Jz,readdir as F,rename as Kz,rmdir as Nz,stat as T,unlink as I}from"node:fs/promises";import{uptime as Qz}from"node:os";import{join as A,resolve as b}from"node:path";function S(z){return(z.now??Date.now)()-(z.uptime??Qz)()*1000-300000}function x(z,J,Q){let X=z.startedAt===void 0?J?.mtimeMs:z.startedAt;return typeof X==="number"&&Number.isFinite(X)&&X<Q}async function Vz(z,J,Q,X){if(!Q)return;await X?.(z);try{let K=await E(z),G=await T(z);if(K===J&&G.dev===Q.dev&&G.ino===Q.ino&&G.mtimeMs===Q.mtimeMs&&G.size===Q.size)await I(z).catch(()=>{})}catch(K){if(K instanceof U&&K.code!=="ENOENT")throw K}}function a(z){return typeof z==="number"&&Number.isSafeInteger(z)&&z>0}function k(z){if(!a(z))return!1;try{return process.kill(z,0),!0}catch(J){return J.code==="EPERM"}}function Ez(z){return(J)=>Wz(J,z)}function Wz(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 Xz(z){let J=/^port-(\d+)\.json$/.exec(z);return J?Number(J[1]):void 0}function s(z,J){if(z===null||typeof z!=="object"||Array.isArray(z))return!1;let{pid:Q,port:X,token:K}=z;return a(Q)&&Xz(J)===Q&&typeof X==="number"&&Number.isInteger(X)&&X>=1&&X<=65535&&typeof K==="string"&&K.length>0}async function l(z,J){J?.debug("rpc corrupt port file",{pid:process.pid,portFile:z}),await I(z).catch(()=>{})}async function Lz(z,J,Q={}){let X=async()=>{let K=A(z,`port-${J.pid}.json`);if(_)return await p(z,Q.secureDir??!1),await Q.beforeWrite?.(),await c(K,JSON.stringify({...J,startedAt:Date.now()}),{stagePath:`${K}.${(Q.stageName??y)()}.tmp`}),K;if(await Gz(z,{recursive:!0,mode:Q.secureDir?448:void 0}),Q.secureDir)await zz(z,448);await Q.beforeWrite?.();let G={...J,startedAt:Date.now()},Y=`${K}.${(Q.stageName??y)()}.tmp`,V,N=!1;try{V=await Jz(Y,"wx",384),N=!0,await V.writeFile(JSON.stringify(G),"utf8"),await V.chmod(384),await V.close(),V=void 0,await Kz(Y,K),N=!1}finally{if(await V?.close().catch(()=>{}),N)await I(Y).catch(()=>{})}return K};for(let K=1;;K+=1)try{return await X()}catch(G){if(G.code!=="ENOENT"||K===5)throw G;await new Promise((Y)=>setTimeout(Y,25))}}async function Iz(z,J,Q,X,K={}){let G=S(K),Y;try{Y=await F(z,{withFileTypes:!0})}catch(N){if(N.code==="ENOENT")return;throw N}let V=b(J);for(let N of Y){if(!N.isDirectory()||!Q(N.name))continue;let W=A(z,N.name);if(!await Yz(W,X,K,G))continue;if(b(W)!==V)await Nz(W).catch(()=>{})}}async function Yz(z,J,Q={},X=S(Q)){let K;try{K=await F(z)}catch(G){if(G.code==="ENOENT")return!1;throw G}for(let G of K){if(!G.startsWith("port-")||!G.endsWith(".json"))continue;let Y=A(z,G),V=await T(Y).catch(()=>{return}),N;try{N=await E(Y)}catch($){if($ instanceof U&&$.code!=="ENOENT")throw $;continue}if(N===void 0)continue;let W;try{W=JSON.parse(N)}catch{await l(Y,J);continue}if(!s(W,G)){await l(Y,J);continue}let Z=W;if(!k(Z.pid))await I(Y).catch(()=>{});else if(x(Z,V,X))await Vz(Y,N,V,Q.beforeRemove)}return!0}async function d(z,J,Q={}){let X=S(Q);if(!k(J.pid))return null;let K=A(b(z),`port-${J.pid}.json`);try{if(_)await g(K,"file");let G=await T(K);if(x(J,G,X))return null;return`${K}:${G.dev}:${G.ino}:${G.mtimeMs}:${G.size}`}catch(G){if(G instanceof U&&G.code!=="ENOENT")throw G;return null}}async function n(z,J,Q={}){let X=S(Q),K;try{if(_)await g(z,"directory");K=await F(z)}catch(W){if(W instanceof U&&W.code!=="ENOENT")throw W;return null}let G=[];for(let W of K){if(!W.startsWith("port-")||!W.endsWith(".json"))continue;try{let Z=JSON.parse(await E(A(z,W)));if(s(Z,W))if(k(Z.pid)){let $=Z.startedAt===void 0?await T(A(z,W)).catch(()=>{return}):void 0;if(!x(Z,$,X))G.push(Z)}else await I(A(z,W)).catch(()=>{})}catch(Z){if(Z instanceof U&&Z.code!=="ENOENT")throw Z}}if(G.length===0)return null;let Y=J!==void 0&&J>=1?G.filter((W)=>W.pid===J):[];if(Q.exactPid===!0&&Y.length===0)return null;let V=Y.length>0?Y:G,N=(W)=>typeof W.startedAt==="number"&&Number.isFinite(W.startedAt)?W.startedAt:-1/0;return V.sort((W,Z)=>N(Z)-N(W))[0]??null}import{open as Zz}from"node:fs/promises";import{connect as $z}from"node:net";import{join as Hz,resolve as t}from"node:path";var e=2000,q=new Map,B=new Map;async function qz(z,J){let Q=Hz(t(z),`port-${J.pid}.json`);if(_){let K=JSON.parse(await E(Q));if(K.pid!==J.pid||K.port!==J.port||K.token!==J.token)return null;return null}let X;try{X=await Zz(Q,"r");let K=await X.stat(),G=JSON.parse(await X.readFile("utf8"));if(G.pid!==J.pid||G.port!==J.port||G.token!==J.token)return null;return`${Q}:${K.dev}:${K.ino}:${K.mtimeMs}:${K.size}`}catch{return null}finally{await X?.close().catch(()=>{})}}async function i(z,J,Q,X){let K=q.get(z);if(!_&&K&&await d(J,K.entry)===K.identity)return K;q.delete(z);let G=B.get(z);if(G)return G;let Y=(async()=>{let V=await(X.discover??n)(J,Q,X);if(!V)return null;let N=await qz(J,V);if(!N)return{entry:V,identity:""};let W={entry:V,identity:N};return q.set(z,W),W})();B.set(z,Y);try{return await Y}finally{if(B.get(z)===Y)B.delete(z)}}async function o(z,J,Q,X=e){return new Promise((K)=>{let G,Y=!1,V=!1,N=(Z,$=!1)=>{if(Y)return;Y=!0,clearTimeout(W),G?.destroy(),K({value:Z,stale:$})},W=setTimeout(()=>N(null),X);try{let Z=JSON.stringify(Q);G=$z({host:"127.0.0.1",port:z.port}),G.on("connect",()=>{V=!0,G?.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(j>=0)C=j+4;if((C??R.length)>16384)return N(null);if(C!==void 0){let u=R.subarray(0,j).toString("latin1").split(`\r
11
11
  `),v=/^HTTP\/1\.[01] (\d{3})(?: |$)/.exec(u[0]??"");if(!v)return N(null);let w=Number(v[1]);if(w<200||w>=300)return N(null,[401,403,404,410].includes(w));for(let D of u.slice(1)){let f=D.indexOf(":"),h=D.slice(0,f).toLowerCase(),m=D.slice(f+1).trim();if(h==="transfer-encoding")return N(null);if(h==="content-length"){if(H!==void 0||!/^\d+$/.test(m))return N(null);if(H=Number(m),!Number.isSafeInteger(H)||H>8388608)return N(null)}}R=Buffer.alloc(0)}}let M=O-(C??O);if(M>8388608)return N(null);if(H!==void 0){if(M>H)return N(null);if(M===H)P()}}),G.on("end",()=>{if(H!==void 0&&O-(C??0)!==H)return N(null);P()}),G.on("error",()=>N(null,!V)),G.on("close",()=>N(null))}catch{N(null,!V)}})}async function r(z,J,Q,X,K,G,Y=e){let V=JSON.stringify([t(z),J??null,Q.exactPid===!0]),N=await i(V,z,J,Q);if(X(N?.entry??null),!N)return null;let W=Date.now()+Y,Z=await o(N.entry,K,G,Y);if(!Z.stale)return Z.value;if(q.get(V)===N)q.delete(V);let $=await i(V,z,J,Q);if(!$||Date.now()>=W)return null;if($.entry.port===N.entry.port&&$.entry.pid===N.entry.pid&&$.entry.token===N.entry.token){if(q.get(V)===$)q.delete(V);return null}let O=await o($.entry,K,G,W-Date.now());if(O.stale&&q.get(V)===$)q.delete(V);return O.value}function Dz(z,J,Q,X={}){let K={exactPid:X.exactPid,discover:X.discover},G=!1,Y=(V)=>{if(G)return;Q?.(V),G=!0};return{async pending(V,N,W){return(await r(z,J,K,Y,"pending-notifications",{lastReceivedId:V,sessionId:N},W))?.messages??[]},async apply(V,N){return await r(z,J,K,Y,"apply",{...V},N)??{text:"apply failed",knobs:{}}}}}
12
- export{Ez as sg,Lz as tg,Iz as ug,Yz as vg,n as wg,e as xg,Dz as yg};
12
+ export{Ez as vg,Lz as wg,Iz as xg,Yz as yg,n as zg,e as Ag,Dz as Bg};