@cortexkit/opencode-openai-auth 0.4.0 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{E as q,I as B,J as V,r as Y,y as Z,z as $}from"./index-dzg88nw2.js";import"./index-1r02s323.js";import{ta as X}from"./index-6y6ss1kc.js";import{execFileSync as E}from"node:child_process";function Q(C,H=process.platform,D=E){try{if(H==="win32"){D("cmd",["/c","start","",C],{stdio:"ignore",timeout:3000});return}D(H==="darwin"?"open":"xdg-open",[C],{stdio:"ignore",timeout:3000})}catch{}}function T(){console.log(`Usage:
2
+ import{E as q,I as B,J as V,r as Y,y as Z,z as $}from"./index-0gccjqxr.js";import"./index-1r02s323.js";import{ta as X}from"./index-6y6ss1kc.js";import{execFileSync as E}from"node:child_process";function Q(C,H=process.platform,D=E){try{if(H==="win32"){D("cmd",["/c","start","",C],{stdio:"ignore",timeout:3000});return}D(H==="darwin"?"open":"xdg-open",[C],{stdio:"ignore",timeout:3000})}catch{}}function T(){console.log(`Usage:
3
3
  npx @cortexkit/opencode-openai-auth login [--label <name>] [--headless]
4
4
  npx @cortexkit/opencode-openai-auth list
5
5
  npx @cortexkit/opencode-openai-auth remove <id>
@@ -2,7 +2,7 @@ export declare const CLIENT_ID = "app_EMoamEEZ73f0CkXaXp7hrann";
2
2
  export declare const ISSUER = "https://auth.openai.com";
3
3
  export declare const OAUTH_PORT = 1455;
4
4
  export declare const OAUTH_POLLING_SAFETY_MARGIN_MS = 3000;
5
- export declare const USER_AGENT = "cortexkit-opencode-openai-auth/0.4.0";
5
+ export declare const USER_AGENT = "cortexkit-opencode-openai-auth/0.4.1";
6
6
  export declare const RESERVED_ACCOUNT_ID = "main";
7
7
  export declare const RESERVED_ACCOUNT_ID_ERROR = "\"main\" is a reserved account id; choose a different label.";
8
8
  export interface PkceCodes {
@@ -1,4 +1,4 @@
1
- import{ka as R0,la as I}from"./index-1r02s323.js";import{ta as K4}from"./index-6y6ss1kc.js";import{createHash as v0}from"node:crypto";var p0=86400000,l0=300000,d0=3600000,g0=60000,i0=900000,u0=300000;function o(B){return B instanceof Error?B.message:String(B)}function s0(B){let Z=B?.status;if(typeof Z==="number")return Z===429||Z>=500;if(!(B instanceof Error))return!1;return B.message.includes("fetch failed")||"code"in B&&(B.code==="ECONNRESET"||B.code==="ECONNREFUSED"||B.code==="ETIMEDOUT"||B.code==="UND_ERR_CONNECT_TIMEOUT")}function t(B){let Z=o(B),$=B?.status;if(typeof $==="number")return $===429||$>=500;if(!(B instanceof Error))return!1;let W=B.code;return Z.includes("fetch failed")||W==="ECONNRESET"||W==="ECONNREFUSED"||W==="ETIMEDOUT"||W==="UND_ERR_CONNECT_TIMEOUT"}function H0(B){return v0("sha256").update(B).digest("hex")}function Q0(B){let Z=H0(B.refreshToken),W=(B.previous?.tokenHash===Z?B.previous.retryCount??0:0)+1,z,X=B.error?.retryAfter;if(typeof X==="number"&&X>0)z=X*1000;else if(s0(B.error))z=Math.min(d0,l0*2**Math.min(W-1,6));else z=p0;return{message:o(B.error),checkedAt:B.now,nextRetryAt:B.now+z,retryCount:W,tokenHash:Z}}function U(B,Z,$){if(!B?.nextRetryAt||B.nextRetryAt<=$)return!1;if(!Z)return!0;return B.tokenHash===H0(Z)}function d(B,Z){return`Codex OAuth refresh is backed off for ${Math.max(1,Math.ceil(((B.nextRetryAt??Z)-Z)/1000))}s after: ${B.message}`}function f(B){let $=(B.previous?.retryCount??0)+1,W,z=B.error?.retryAfter;if(typeof z==="number"&&z>0)W=z*1000;else if(t(B.error))W=Math.min(i0,g0*2**Math.min($-1,6));else W=u0;return{message:o(B.error),checkedAt:B.now,nextRetryAt:B.now+W,retryCount:$}}function x(B,Z){if(!B?.nextRetryAt||B.nextRetryAt<=Z)return!1;return!0}function e(B){if(!B)return;let Z=Number(B);if(Number.isFinite(Z)&&Z>0)return Math.ceil(Z);let $=Date.parse(B);if(Number.isFinite($)){let W=Math.ceil(($-Date.now())/1000);return W>0?W:void 0}return}import{createServer as r0}from"node:http";import{setTimeout as n0}from"node:timers/promises";var N0="0.4.0";var u="app_EMoamEEZ73f0CkXaXp7hrann",q="https://auth.openai.com",m=1455,c0=3000,L0=`cortexkit-opencode-openai-auth/${N0}`,F0="main",a0=`"${F0}" is a reserved account id; choose a different label.`;function O0(B){let Z=new Uint8Array(B),$=String.fromCharCode(...Z);return btoa($).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function o0(){let Z=Array.from(crypto.getRandomValues(new Uint8Array(43))).map((W)=>"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~"[W%66]).join(""),$=O0(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(Z)));return{verifier:Z,challenge:$}}function P0(B){if(B.length>16384)return;let Z=B.split(".");if(Z.length!==3)return;let $=Z[1];if(!$||$.length>8192)return;try{return JSON.parse(Buffer.from($,"base64url").toString())}catch{return}}function V0(B){let Z=B.chatgpt_account_id;if(typeof Z==="string"&&Z.length>0)return Z;let $=B["https://api.openai.com/auth"];if($&&typeof $==="object"&&!Array.isArray($)&&typeof $.chatgpt_account_id==="string"&&$.chatgpt_account_id.length>0)return $.chatgpt_account_id;let W=B.organizations;if(Array.isArray(W)){let z=W[0];if(z&&typeof z==="object"&&!Array.isArray(z)&&typeof z.id==="string"&&z.id.length>0)return z.id}return}function i(B){if(B.id_token){let Z=P0(B.id_token),$=Z&&V0(Z);if($)return $}if(B.access_token){let Z=P0(B.access_token);return Z?V0(Z):void 0}return}function t0(B){return typeof B==="string"&&B.toLowerCase()===F0}function B0(B){if(t0(B))throw Error(a0);return B}function e0(B,Z,$){let W=new URLSearchParams({response_type:"code",client_id:u,redirect_uri:B,scope:"openid profile email offline_access",code_challenge:Z.challenge,code_challenge_method:"S256",id_token_add_organizations:"true",codex_cli_simplified_flow:"true",state:$,originator:"opencode"});return`${q}/oauth/authorize?${W.toString()}`}async function B4(B,Z,$){let W=await fetch(`${q}/oauth/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",code:B,redirect_uri:Z,client_id:u,code_verifier:$.verifier}).toString()});if(!W.ok)throw Error(`Token exchange failed: ${W.status}`);return await W.json()}function Z4(B){return B.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&#39;")}var $4=`<!doctype html>
1
+ import{ka as R0,la as I}from"./index-1r02s323.js";import{ta as K1}from"./index-6y6ss1kc.js";import{createHash as v0}from"node:crypto";var p0=86400000,l0=300000,d0=3600000,g0=60000,i0=900000,u0=300000;function o(B){return B instanceof Error?B.message:String(B)}function s0(B){let Z=B?.status;if(typeof Z==="number")return Z===429||Z>=500;if(!(B instanceof Error))return!1;return B.message.includes("fetch failed")||"code"in B&&(B.code==="ECONNRESET"||B.code==="ECONNREFUSED"||B.code==="ETIMEDOUT"||B.code==="UND_ERR_CONNECT_TIMEOUT")}function t(B){let Z=o(B),$=B?.status;if(typeof $==="number")return $===429||$>=500;if(!(B instanceof Error))return!1;let W=B.code;return Z.includes("fetch failed")||W==="ECONNRESET"||W==="ECONNREFUSED"||W==="ETIMEDOUT"||W==="UND_ERR_CONNECT_TIMEOUT"}function H0(B){return v0("sha256").update(B).digest("hex")}function Q0(B){let Z=H0(B.refreshToken),W=(B.previous?.tokenHash===Z?B.previous.retryCount??0:0)+1,z,X=B.error?.retryAfter;if(typeof X==="number"&&X>0)z=X*1000;else if(s0(B.error))z=Math.min(d0,l0*2**Math.min(W-1,6));else z=p0;return{message:o(B.error),checkedAt:B.now,nextRetryAt:B.now+z,retryCount:W,tokenHash:Z}}function U(B,Z,$){if(!B?.nextRetryAt||B.nextRetryAt<=$)return!1;if(!Z)return!0;return B.tokenHash===H0(Z)}function d(B,Z){return`Codex OAuth refresh is backed off for ${Math.max(1,Math.ceil(((B.nextRetryAt??Z)-Z)/1000))}s after: ${B.message}`}function f(B){let $=(B.previous?.retryCount??0)+1,W,z=B.error?.retryAfter;if(typeof z==="number"&&z>0)W=z*1000;else if(t(B.error))W=Math.min(i0,g0*2**Math.min($-1,6));else W=u0;return{message:o(B.error),checkedAt:B.now,nextRetryAt:B.now+W,retryCount:$}}function x(B,Z){if(!B?.nextRetryAt||B.nextRetryAt<=Z)return!1;return!0}function e(B){if(!B)return;let Z=Number(B);if(Number.isFinite(Z)&&Z>0)return Math.ceil(Z);let $=Date.parse(B);if(Number.isFinite($)){let W=Math.ceil(($-Date.now())/1000);return W>0?W:void 0}return}import{createServer as r0}from"node:http";import{setTimeout as n0}from"node:timers/promises";var N0="0.4.1";var u="app_EMoamEEZ73f0CkXaXp7hrann",q="https://auth.openai.com",m=1455,c0=3000,L0=`cortexkit-opencode-openai-auth/${N0}`,F0="main",a0=`"${F0}" is a reserved account id; choose a different label.`;function O0(B){let Z=new Uint8Array(B),$=String.fromCharCode(...Z);return btoa($).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function o0(){let Z=Array.from(crypto.getRandomValues(new Uint8Array(43))).map((W)=>"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~"[W%66]).join(""),$=O0(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(Z)));return{verifier:Z,challenge:$}}function P0(B){if(B.length>16384)return;let Z=B.split(".");if(Z.length!==3)return;let $=Z[1];if(!$||$.length>8192)return;try{return JSON.parse(Buffer.from($,"base64url").toString())}catch{return}}function V0(B){let Z=B.chatgpt_account_id;if(typeof Z==="string"&&Z.length>0)return Z;let $=B["https://api.openai.com/auth"];if($&&typeof $==="object"&&!Array.isArray($)&&typeof $.chatgpt_account_id==="string"&&$.chatgpt_account_id.length>0)return $.chatgpt_account_id;let W=B.organizations;if(Array.isArray(W)){let z=W[0];if(z&&typeof z==="object"&&!Array.isArray(z)&&typeof z.id==="string"&&z.id.length>0)return z.id}return}function i(B){if(B.id_token){let Z=P0(B.id_token),$=Z&&V0(Z);if($)return $}if(B.access_token){let Z=P0(B.access_token);return Z?V0(Z):void 0}return}function t0(B){return typeof B==="string"&&B.toLowerCase()===F0}function B0(B){if(t0(B))throw Error(a0);return B}function e0(B,Z,$){let W=new URLSearchParams({response_type:"code",client_id:u,redirect_uri:B,scope:"openid profile email offline_access",code_challenge:Z.challenge,code_challenge_method:"S256",id_token_add_organizations:"true",codex_cli_simplified_flow:"true",state:$,originator:"opencode"});return`${q}/oauth/authorize?${W.toString()}`}async function B1(B,Z,$){let W=await fetch(`${q}/oauth/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",code:B,redirect_uri:Z,client_id:u,code_verifier:$.verifier}).toString()});if(!W.ok)throw Error(`Token exchange failed: ${W.status}`);return await W.json()}function Z1(B){return B.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&#39;")}var $1=`<!doctype html>
2
2
  <html>
3
3
  <head>
4
4
  <title>CortexKit OpenAI Auth - Authorization Successful</title>
@@ -81,9 +81,9 @@ import{ka as R0,la as I}from"./index-1r02s323.js";import{ta as K4}from"./index-6
81
81
  <div class="container">
82
82
  <h1>Authorization Failed</h1>
83
83
  <p>An error occurred during authorization.</p>
84
- <div class="error">${Z4(B)}</div>
84
+ <div class="error">${Z1(B)}</div>
85
85
  </div>
86
86
  </body>
87
- </html>`,k,w,L=new Map;function M(){return L.size}function C(B){if(L.delete(B),M()===0)_()}async function W4(){let B=`http://localhost:${m}/auth/callback`;if(k)return{port:m,redirectUri:B};if(w)return w;w=(async()=>{let Z=r0(($,W)=>{let z=new URL($.url||"/",`http://127.0.0.1:${m}`);if(z.pathname==="/auth/callback"){let X=z.searchParams.get("code"),G=z.searchParams.get("state"),K=z.searchParams.get("error"),Y=z.searchParams.get("error_description");if(K){let J=Y||K;if(G){let Q=L.get(G);if(Q)Q.reject(Error(J)),C(G);else if(M()===0)_()}else if(M()===0)_();W.writeHead(200,{"Content-Type":"text/html"}),W.end(g(J));return}if(!G){if(M()===0)_();W.writeHead(400,{"Content-Type":"text/html"}),W.end(g("Missing state parameter"));return}if(!X){if(M()===0)_();W.writeHead(400,{"Content-Type":"text/html"}),W.end(g("Missing authorization code"));return}let j=L.get(G);if(!j){if(M()===0)_();W.writeHead(400,{"Content-Type":"text/html"}),W.end(g("Unknown state — authorization may have expired"));return}C(G),B4(X,B,j.pkce).then((J)=>j.resolve(J)).catch((J)=>j.reject(J)),W.writeHead(200,{"Content-Type":"text/html"}),W.end($4);return}if(z.pathname==="/cancel"){let X=z.searchParams.get("state"),G=X?[X]:[...L.keys()];W.writeHead(200),W.end("Login cancelled");for(let K of G){let Y=L.get(K);if(!Y)continue;Y.reject(Error("Login cancelled")),C(K)}if(M()===0)_();return}W.writeHead(404),W.end("Not found")});return await new Promise(($,W)=>{Z.once("error",W),Z.listen(m,"127.0.0.1",()=>{Z.off("error",W),$()})}),k=Z,{port:m,redirectUri:B}})();try{return await w}finally{w=void 0}}function _(){if(k){let B=k;k=void 0,B.close(()=>{}),B.closeIdleConnections?.(),setTimeout(()=>{B.closeAllConnections?.()},25).unref?.()}}function z4(B,Z,$=300000,W){return new Promise((z,X)=>{if(W?.aborted){C(Z),X(Error("Login cancelled"));return}let G=setTimeout(()=>{if(L.get(Z))C(Z),X(Error("OAuth callback timeout — authorization took too long"))},$),K=()=>{if(clearTimeout(G),L.get(Z))C(Z),X(Error("Login cancelled"))};if(W)W.addEventListener("abort",K);L.set(Z,{pkce:B,state:Z,resolve:(Y)=>{if(clearTimeout(G),W)W.removeEventListener("abort",K);z(Y)},reject:(Y)=>{if(clearTimeout(G),W)W.removeEventListener("abort",K);X(Y)}})})}async function X4(){let B=await fetch(`${q}/api/accounts/deviceauth/usercode`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":L0},body:JSON.stringify({client_id:u})});if(!B.ok)throw Error("Failed to initiate device authorization");let Z=await B.json();return{deviceData:Z,url:`${q}/codex/device`,instructions:`Enter code: ${Z.user_code}`}}async function G4(B,Z){let $=Math.max(parseInt(B.interval,10)||5,1)*1000,W=typeof B.expires_in==="number"?B.expires_in:parseInt(B.expires_in||"",10),z=!Number.isNaN(W)&&W>0?W*1000:900000,X=Date.now();while(!0){if(Z?.aborted)throw Error("Device authorization cancelled");if(Date.now()-X>z)throw Error("Device authorization expired");let G=await fetch(`${q}/api/accounts/deviceauth/token`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":L0},body:JSON.stringify({device_auth_id:B.device_auth_id,user_code:B.user_code})});if(G.ok){let j=await G.json(),J=await fetch(`${q}/oauth/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",code:j.authorization_code,redirect_uri:`${q}/deviceauth/callback`,client_id:u,code_verifier:j.code_verifier}).toString()});if(!J.ok)throw Error(`Token exchange failed: ${J.status}`);return await J.json()}if(G.status!==403&&G.status!==404)throw Error(`Device authorization failed: ${G.status}`);let K=z-(Date.now()-X);if(K<=0)throw Error("Device authorization expired");let Y=Math.min($+c0,K);try{await n0(Y,void 0,{signal:Z})}catch(j){if(j instanceof Error&&j.name==="AbortError")throw Error("Device authorization cancelled");throw j}}}function MB(B,Z){let $=-1;if(Z.accountId)$=B.findIndex((W)=>W.accountId&&W.accountId===Z.accountId);if($<0)$=B.findIndex((W)=>W.id===Z.id);if($<0&&Z.label&&!Z.accountId)$=B.findIndex((W)=>W.label===Z.label);if($>=0)return B[$]={...B[$],...Z,addedAt:B[$]?.addedAt??Z.addedAt},$;return B.push(Z),B.length-1}async function _B(B={}){let{label:Z,headless:$=!1,signal:W}=B;if(B0(Z),$){let{deviceData:j,url:J,instructions:Q}=await X4(),y=(async()=>{let V=await G4(j,W),F=Date.now(),J0=i(V);return{id:B0(Z||J0||crypto.randomUUID()),label:Z||void 0,type:"oauth",access:V.access_token,refresh:V.refresh_token,expires:F+(V.expires_in??3600)*1000,enabled:!0,addedAt:F,lastUsed:F,lastRefreshedAt:F,accountId:J0}})();return{url:J,instructions:Q,completion:y}}let{redirectUri:z}=await W4(),X=await o0(),G=O0(crypto.getRandomValues(new Uint8Array(32)).buffer),K=e0(z,X,G),Y=(async()=>{try{if(W?.aborted)throw Error("Login cancelled");let j=await z4(X,G,void 0,W),J=Date.now(),Q=i(j);return{id:B0(Z||Q||crypto.randomUUID()),label:Z||void 0,type:"oauth",access:j.access_token,refresh:j.refresh_token,expires:J+(j.expires_in??3600)*1000,enabled:!0,addedAt:J,lastUsed:J,lastRefreshedAt:J,accountId:Q}}finally{C(G)}})();return{url:K,instructions:"Complete authorization in your browser. This window will close automatically.",completion:Y}}var Z0="primary",$0="secondary",Y4="app_EMoamEEZ73f0CkXaXp7hrann",j4="https://auth.openai.com";async function EB(B){let Z=await B.fetchImpl(`${j4}/oauth/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"refresh_token",refresh_token:B.refreshToken,client_id:Y4}).toString()});if(!Z.ok){let W=e(Z.headers.get("retry-after"));throw Object.assign(Error(`Token refresh failed: ${Z.status}`),{status:Z.status,retryAfter:W,isRefreshError:!0})}let $=await Z.json();if(!$||typeof $.access_token!=="string"||!$.access_token||typeof $.refresh_token!=="string"||!$.refresh_token||typeof $.expires_in!=="number")throw Object.assign(Error("Token refresh failed: malformed response"),{status:Z.status,isRefreshError:!0});return{access:$.access_token,refresh:$.refresh_token,expires:B.now()+$.expires_in*1000,expiresIn:$.expires_in}}var J4="https://chatgpt.com/backend-api/wham/usage";async function SB(B){let Z=await B.fetchImpl(J4,{headers:{authorization:`Bearer ${B.accessToken}`,"chatgpt-account-id":B.accountId??"","oai-client-platform":"web","oai-client-version":"0","x-openai-target-path":"/backend-api/wham/usage"}});if(!Z.ok){let W=e(Z.headers.get("retry-after"));throw Object.assign(Error(`wham usage check failed: ${Z.status}`),{status:Z.status,retryAfter:W})}let{normalizeWham:$}=await import("./quota-normalize-8yzxqy78.js");return $(await Z.json())}import{createHash as H4}from"node:crypto";var Q4=globalThis.setTimeout,N4=5;function h(B){let Z=B?.quota?.checkIntervalMinutes??N4;return Math.max(1,Z)*60000}function P4(B){return B?.quota?.enabled!==!1}function s(B,Z){if(!B?.resetsAt)return!1;let $=Date.parse(B.resetsAt);return Number.isFinite($)&&$<=Z}function TB(B,Z,$,W){let z=Z===Z0?B?.primary:Z===$0?B?.secondary:void 0,X=z?.resetsAt?Date.parse(z.resetsAt):NaN;if(Number.isFinite(X)&&X>$)return X;return $+W}function V4(B){let Z=B?.quota?.minimumRemaining||{};return{primary:Z.primary??Z["5h"]??15,secondary:Z.secondary??Z["1w"]??10}}function b0(B,Z,$){if(!P4(Z))return $+h(Z);let W=V4(Z),z=[];for(let X of["primary","secondary"]){let G=B?.[X];if(!G)continue;if(G.remainingPercent>=W[X])continue;let K=G.resetsAt?Date.parse(G.resetsAt):Number.NaN;if(!Number.isFinite(K)||K<=$)return $+h(Z);z.push(K)}if(!z.length)return $+h(Z);return Math.min(...z)+60000}function L4(B){if(!B?.quota?.mainQuota||!B.quota.mainQuotaCheckedAt)return null;return{quota:B.quota.mainQuota,checkedAt:B.quota.mainQuotaCheckedAt,tokenFingerprint:B.quota.mainQuotaToken}}function F4(B){let Z=B?.quota?.refreshEveryNRequests;return typeof Z==="number"&&Number.isFinite(Z)&&Z>0?Math.floor(Z):0}function P(B){return H4("sha256").update(B).digest("hex").slice(0,16)}class O{main=null;mainTokenFp=null;mainQuotaAccountId=null;fallbacks=new Map;fallbackTokenFps=new Map;inflightMain=null;inflightMainFp=null;inflightFallbacks=new Map;mainLastApiError=void 0;fallbackApiErrors=new Map;fallbackErrorTokenFps=new Map;rateLimitedUntilMap=new Map;apiGate=Promise.resolve();lastApiCallAt=0;storage;fetchImpl;now;fetchQuotaFn;onMainQuotaFetched;onApiError;constructor(B){this.storage=B.storage,this.fetchImpl=B.fetchImpl??fetch,this.now=B.now??Date.now,this.fetchQuotaFn=B.fetchQuotaFn,this.onMainQuotaFetched=B.onMainQuotaFetched,this.onApiError=B.onApiError,this.seedMainFromStorage(B.storage),this.seedMainBackoffFromStorage(B.storage)}getMain(B){if(B&&this.main&&this.mainTokenFp&&this.mainTokenFp!==P(B))this.main=null,this.mainTokenFp=null;return this.main}getFallback(B,Z){let $=this.fallbacks.get(B)??null;if(!Z||!$)return $;if(this.fallbackTokenFps.get(B)!==P(Z))return this.fallbacks.delete(B),this.fallbackTokenFps.delete(B),null;return $}getAllFallbacks(){return this.fallbacks}setMain(B,Z,$,W=!1){if(!W&&!D0(Z.quota))return;if(this.mainTokenFp=P(B),$&&this.mainQuotaAccountId&&this.mainQuotaAccountId!==$)this.clearRateLimited("main");if($)this.mainQuotaAccountId=$;if(this.main=Z,W0(Z.quota))this.clearRateLimited("main")}peekMainForPolicy(B){if(B&&this.mainQuotaAccountId&&this.mainQuotaAccountId!==B)return null;return this.main}peekFallbackForPolicy(B){return this.fallbacks.get(B)??null}setFallback(B,Z,$,W=!1){if(!W&&!D0(Z.quota))return;if(this.fallbacks.set(B,Z),$)this.fallbackTokenFps.set(B,P($));else this.fallbackTokenFps.delete(B);if(W0(Z.quota))this.clearRateLimited(B)}markRateLimited(B,Z){let $=this.rateLimitedUntilMap.get(B);if($!==void 0&&$>Z)return;this.rateLimitedUntilMap.set(B,Z)}isRateLimited(B){let Z=this.rateLimitedUntilMap.get(B);return Z!==void 0&&this.now()<Z}rateLimitedUntil(B){return this.rateLimitedUntilMap.get(B)}clearRateLimited(B){this.rateLimitedUntilMap.delete(B)}async refreshMain(B){let Z=P(B);if(this.mainTokenFp&&this.mainTokenFp!==Z)this.main=null,this.mainTokenFp=null;if(this.inflightMain&&this.inflightMainFp===Z)return this.inflightMain;if(this.isBackedOff()){if(this.main)return this.main.quota;throw Error("Quota API rate-limited — try again later")}return this.inflightMainFp=Z,this.inflightMain=this._fetchMain(B),this.inflightMain}async refreshFallback(B,Z){let $=O.fallbackInflightKey(B,Z),W=this.inflightFallbacks.get($);if(W)return W;if(this.isFallbackBackedOff(B,Z)){let X=this.getFallback(B,Z);if(X)return X.quota;throw Error("Quota API rate-limited — try again later")}let z=this._fetchFallback(B,Z);return this.inflightFallbacks.set($,z),z}async refreshAllFallbacks(B){let Z=this.now();for(let $ of B){if($.enabled===!1)continue;if(!$.access)continue;let W=this.getFallback($.id,$.access);if(W&&Z<W.refreshAfter)continue;try{await this.refreshFallback($.id,$.access)}catch{}}}refreshMainInBackground(B){let Z=P(B);if(this.inflightMain&&this.inflightMainFp===Z)return;if(this.isBackedOff())return;this.refreshMain(B).catch(()=>{})}isMainStale(){if(!this.main)return!0;return this.now()>=this.main.refreshAfter}isFallbackStale(B,Z){let $=this.getFallback(B,Z);if(!$)return!0;return this.now()>=$.refreshAfter}shouldRefreshOnRequestCount(B){let Z=F4(this.storage);if(Z<=0)return!1;return B>0&&B%Z===0}needsRefresh(B){return this.isMainStale()||this.shouldRefreshOnRequestCount(B)}updateStorage(B){this.storage=B,this.seedMainFromStorage(B),this.seedMainBackoffFromStorage(B)}seedMainFromStorage(B,Z){let $=L4(B);if(!$)return;let W=Z?P(Z):null;if(W&&$.tokenFingerprint&&$.tokenFingerprint!==W)return;let z={quota:$.quota,refreshAfter:b0($.quota,B,$.checkedAt),checkedAt:$.checkedAt};if(this.main&&this.main.checkedAt>=z.checkedAt&&(!W||!this.mainTokenFp||this.mainTokenFp===W))return;if(this.main=z,this.mainTokenFp=$.tokenFingerprint??null,B?.mainAccountId){if(this.mainQuotaAccountId&&this.mainQuotaAccountId!==B.mainAccountId)this.clearRateLimited("main");this.mainQuotaAccountId=B.mainAccountId}}seedMainBackoffFromStorage(B){let Z=B?.quota?.mainLastQuotaApiError;this.mainLastApiError=Z&&x(Z,this.now())?Z:void 0}seedFallbacksFromAccounts(B){let Z=h(this.storage);for(let $ of B){if($.enabled===!1)continue;if(!$.quota)continue;let W=Math.max($.quota.primary?.checkedAt??0,$.quota.secondary?.checkedAt??0);if(W<=0)continue;let z=this.getFallback($.id,$.access);if(z&&z.checkedAt>=W)continue;this.setFallback($.id,{quota:$.quota,refreshAfter:W+Z,checkedAt:W},$.access)}}isBackedOff(){return x(this.mainLastApiError,this.now())}isFallbackBackedOff(B,Z){if(Z){if(this.fallbackErrorTokenFps.get(B)!==P(Z))return!1}return x(this.fallbackApiErrors.get(B),this.now())}getLastApiError(){return this.mainLastApiError}static API_CALL_GAP_MS=1000;static fallbackInflightKey(B,Z){return JSON.stringify([B,P(Z)])}static quotaLockName(B){return`opencode-fallback-quota-refresh-${B.replace(/[^a-zA-Z0-9._-]+/g,"-")||"account"}`}_enqueueApiFetch(B){let Z=async()=>{let W=this.now()-this.lastApiCallAt;if(W<O.API_CALL_GAP_MS)await new Promise((z)=>{let X=Q4(z,O.API_CALL_GAP_MS-W);if(typeof X==="object"&&"unref"in X)X.unref()});return this.lastApiCallAt=this.now(),B()},$=this.apiGate.then(Z,Z);return this.apiGate=$.catch(()=>{}),$}async _fetchMain(B){let Z=P(B);return this._enqueueApiFetch(async()=>{try{if(this.isBackedOff()){if(this.main)return this.main.quota;throw Error("Quota API rate-limited — try again later")}let $=await I({name:"opencode-main-quota-refresh",ttlMs:30000});if(!$){let W=this.main;if(W&&this.now()<W.refreshAfter)return W.quota;throw Error("Quota refresh is already in progress")}try{let W=this.now(),z=await this._fetchQuota(B),X=this.now();if(this.mainTokenFp=P(B),this.main={quota:z,refreshAfter:b0(z,this.storage,X),checkedAt:X},W0(z))this.clearRateLimited("main");return this.mainLastApiError=void 0,this.onMainQuotaFetched?.(z,X,this.mainTokenFp,W),z}catch(W){throw this._handleMainFetchError(W),W}finally{await $.release()}}finally{if(this.inflightMainFp===Z)this.inflightMain=null,this.inflightMainFp=null}})}async _fetchFallback(B,Z){return this._enqueueApiFetch(async()=>{try{if(this.isFallbackBackedOff(B,Z)){let W=this.getFallback(B,Z);if(W)return W.quota;throw Error("Quota API rate-limited — try again later")}let $=await I({name:O.quotaLockName(B),ttlMs:30000});if(!$){let W=this.getFallback(B,Z);if(W&&this.now()<W.refreshAfter)return W.quota;throw Error("Quota refresh is already in progress")}try{let W=await this._fetchQuota(Z),z=this.now();return this.setFallback(B,{quota:W,refreshAfter:z+h(this.storage),checkedAt:z},Z,!0),this.fallbackApiErrors.delete(B),this.fallbackErrorTokenFps.delete(B),W}finally{await $.release()}}catch($){throw this._handleFallbackFetchError(B,Z,$),$}finally{this.inflightFallbacks.delete(O.fallbackInflightKey(B,Z))}})}async _fetchQuota(B){if(!this.fetchQuotaFn)throw Error("Quota fetch not available — no fetchQuotaFn injected (push-only mode)");return this.fetchQuotaFn({accessToken:B,fetchImpl:this.fetchImpl,now:this.now})}static isAuthError(B){return B?.status===401}_handleMainFetchError(B){if(O.isAuthError(B))return;this.mainLastApiError=f({error:B,now:this.now(),previous:this.mainLastApiError}),this.onApiError?.(this.mainLastApiError)}_handleFallbackFetchError(B,Z,$){if(O.isAuthError($))return;let W=P(Z),z=this.fallbackErrorTokenFps.get(B)===W?this.fallbackApiErrors.get(B):void 0;this.fallbackApiErrors.set(B,f({error:$,now:this.now(),previous:z})),this.fallbackErrorTokenFps.set(B,W)}}function D0(B){return Boolean(B.primary||B.secondary)}function W0(B){let{primary:Z,secondary:$}=B;if(!Z&&!$)return!1;if(Z&&Z.usedPercent>=100)return!1;if($&&$.usedPercent>=100)return!1;return!0}import{createHash as q4,randomUUID as C4}from"node:crypto";import{homedir as E4}from"node:os";import{dirname as S4,join as r}from"node:path";import{setTimeout as R4}from"node:timers/promises";import{randomUUID as O4}from"node:crypto";import{mkdir as b4,rename as D4,rm as U4,writeFile as M4}from"node:fs/promises";import{dirname as _4}from"node:path";async function A(B,Z){await b4(_4(B),{recursive:!0});let $=`${B}.${O4()}.tmp`;await M4($,`${JSON.stringify(Z,null,2)}
88
- `,{encoding:"utf8",mode:384});try{await D4($,B)}catch(W){throw await U4($,{force:!0}).catch(()=>{}),W}}import{readFile as v4}from"node:fs/promises";var E=R0("refresh"),U0=1e4,y4=50,y0="openai-auth.json",x4="openai-auth-state.json";function I4(){if(process.env.OPENCODE_CONFIG_DIR?.trim())return process.env.OPENCODE_CONFIG_DIR.trim();return r(process.env.XDG_CONFIG_HOME||r(E4(),".config"),"opencode")}function T(){return process.env.OPENCODE_OPENAI_AUTH_FILE?.trim()||r(I4(),y0)}function a(B=T()){let Z=process.env.OPENCODE_OPENAI_AUTH_STATE_FILE?.trim();if(Z)return Z;return A4(B)}function A4(B){return B.endsWith(y0)?r(S4(B),x4):`${B}.state.json`}function b(B){return B.type==="oauth"}function T4(B){let Z=B?.trim();if(!Z)return!1;try{let $=new URL(Z);return($.protocol==="http:"||$.protocol==="https:")&&!$.username&&!$.password}catch{return!1}}function aB(B){return B.costZeroing?.enabled!==!1}class n extends Error{code="ACCOUNT_REMOVED_DURING_REFRESH";constructor(B){super(`Fallback account ${B} was removed before refresh`);this.name="AccountRemovedDuringRefreshError"}}var f4=[401,403,429],M0={primary:0,secondary:0},m4=!1,G0={primary:5,secondary:10};function H(B){return B!=null&&typeof B==="object"&&!Array.isArray(B)}function w4(B){return B instanceof n||H(B)&&B.name==="AccountRemovedDuringRefreshError"&&B.code==="ACCOUNT_REMOVED_DURING_REFRESH"}function _0(B){return{id:typeof B.id==="string"&&B.id.trim()?B.id.trim():C4(),label:typeof B.label==="string"?B.label:void 0,enabled:typeof B.enabled==="boolean"?B.enabled:void 0,addedAt:typeof B.addedAt==="number"?B.addedAt:void 0,lastUsed:typeof B.lastUsed==="number"?B.lastUsed:void 0,accountId:typeof B.accountId==="string"?B.accountId:void 0}}function q0(B){if(!H(B))return;if(typeof B.message!=="string")return;let Z=Number(B.checkedAt);if(!Number.isFinite(Z))return;let $=Number(B.nextRetryAt),W=Number(B.retryCount);return{message:B.message,checkedAt:Z,nextRetryAt:Number.isFinite($)?$:void 0,retryCount:Number.isFinite(W)?W:void 0,tokenHash:typeof B.tokenHash==="string"?B.tokenHash:void 0}}function k4(B){if(!H(B))return;let Z={};for(let W of["primary","secondary"]){let z=B[W];if(!H(z))continue;let X=Number(z.usedPercent),G=Number(z.remainingPercent),K=Number(z.checkedAt);if(!Number.isFinite(X)||!Number.isFinite(G)||!Number.isFinite(K))continue;let Y=typeof z.windowMinutes==="number"?z.windowMinutes:Number.NaN;Z[W]={usedPercent:X,remainingPercent:G,checkedAt:K,resetsAt:typeof z.resetsAt==="string"?z.resetsAt:void 0,...Number.isFinite(Y)&&Y>0?{windowMinutes:Y}:{}}}let $=typeof B.resetCreditsAvailable==="number"?B.resetCreditsAvailable:Number.NaN;if(Number.isFinite($)&&$>=0)Z.resetCreditsAvailable=$;return Object.keys(Z).length?Z:void 0}function h4(B){if(!H(B))return null;if(B.type==="api"){let Z=typeof B.baseURL==="string"?B.baseURL.trim():"",$=typeof B.apiKey==="string"?B.apiKey.trim():"";if(!T4(Z))return null;let W=B.authHeader==="x-api-key"?"x-api-key":"authorization-bearer";return{..._0(B),type:"api",apiKey:$||void 0,baseURL:Z,authHeader:W}}if(B.type!=="oauth")return null;if(typeof B.refresh!=="string"||!B.refresh.trim())return null;return{..._0(B),type:"oauth",access:typeof B.access==="string"?B.access:void 0,refresh:B.refresh,expires:typeof B.expires==="number"?B.expires:void 0,lastRefreshedAt:typeof B.lastRefreshedAt==="number"?B.lastRefreshedAt:void 0,lastRefreshError:q0(B.lastRefreshError),lastQuotaRefreshError:q0(B.lastQuotaRefreshError),quota:k4(B.quota)}}function x0(B){if(!H(B)||!Array.isArray(B.accounts))return null;return{version:1,main:{type:"opencode",provider:"openai"},routing:H(B.routing)?B.routing:void 0,fallbackOn:Array.isArray(B.fallbackOn)?B.fallbackOn.filter((Z)=>Number.isInteger(Z)):void 0,refresh:H(B.refresh)?B.refresh:void 0,quota:H(B.quota)?B.quota:void 0,dump:H(B.dump)?B.dump:void 0,costZeroing:H(B.costZeroing)?B.costZeroing:void 0,killswitch:H(B.killswitch)?B.killswitch:void 0,logging:H(B.logging)?B.logging:void 0,cachekeep:H(B.cachekeep)?B.cachekeep:void 0,mainAccountId:typeof B.mainAccountId==="string"?B.mainAccountId:void 0,accounts:B.accounts.map(h4).filter((Z)=>Z!=null)}}async function R(B){try{return{exists:!0,value:JSON.parse(await v4(B,"utf8"))}}catch(Z){if(Z.code==="ENOENT")return{exists:!1,value:null};throw Z}}function D(B){return Object.fromEntries(Object.entries(B).filter(([,Z])=>Z!==void 0))}async function p4(B){let Z;try{Z=(await R(B)).value}catch{return null}if(!H(Z)||!Array.isArray(Z.accounts))return null;let $=new Set;for(let W of Z.accounts)if(H(W)&&typeof W.id==="string")$.add(W.id);return $}function I0(B,Z){if(!H(B))return B;let $=H(Z)?Z:{},W=H($.main)?$.main:void 0,z=H($.accounts)?$.accounts:{},X=H(B.quota)?B.quota:{},G=H(B.refresh)?B.refresh:{},K=W??X,Y=W??G,J=Array.isArray(B.accounts)?B.accounts.map((Q)=>{if(!H(Q))return Q;let y=typeof Q.id==="string"&&H(z[Q.id])?z[Q.id]:{};return{...Q,...y}}):void 0;return A0({...B,refresh:D({...G,mainLastRefreshError:Y.lastRefreshError,mainRefreshLeaseId:Y.refreshLeaseId,mainRefreshLeaseUntil:Y.refreshLeaseUntil,mainRefreshLeaseTokenHash:Y.refreshLeaseTokenHash}),quota:D({...X,mainQuota:K.quota,mainQuotaCheckedAt:K.quotaCheckedAt,mainQuotaToken:K.quotaToken,mainLastQuotaApiError:K.lastQuotaApiError}),accounts:J})}async function l4(B=T()){let Z=await R(B);if(!Z.exists)return null;let $=await R(a(B));return x0(I0(Z.value,$.value))}function A0(B){return Object.fromEntries(Object.entries(B).filter(([,Z])=>Z!==void 0))}function d4(B){return D({id:B.id,label:B.label,type:B.type,enabled:B.enabled,addedAt:B.addedAt,accountId:B.accountId,baseURL:B.type==="api"?B.baseURL:void 0,authHeader:B.type==="api"?B.authHeader:void 0})}function T0(B){if(B.type==="api")return D({apiKey:B.apiKey,lastUsed:B.lastUsed});return D({access:B.access,refresh:B.refresh,expires:B.expires,lastUsed:B.lastUsed,lastRefreshedAt:B.lastRefreshedAt,lastRefreshError:B.lastRefreshError,lastQuotaRefreshError:B.lastQuotaRefreshError,quota:B.quota})}function c(B){return Math.max(B?.primary?.checkedAt??0,B?.secondary?.checkedAt??0)}function v(B,Z,$){if($ in Z)B[$]=Z[$];else delete B[$]}function g4(B,Z){return B.access===Z.access&&B.refresh===Z.refresh&&B.expires===Z.expires&&B.lastRefreshedAt===Z.lastRefreshedAt}function i4(B,Z){if(!g4(B,Z))return Z;if(!("lastRefreshError"in Z))return B;if(!("lastRefreshError"in B))return Z;return(Z.lastRefreshError?.checkedAt??0)>(B.lastRefreshError?.checkedAt??0)?Z:B}function u4(B,Z,$){let W=Z.lastRefreshedAt??0,z=$.lastRefreshedAt??0,X=Z.expires??0,G=$.expires??0,K=z>W?$:W>z?Z:G>X?$:X>G?Z:i4(Z,$);v(B,K,"access"),v(B,K,"refresh"),v(B,K,"expires"),v(B,K,"lastRefreshedAt"),v(B,K,"lastRefreshError")}function s4(B,Z){if(!H(B))return Z;let $=B,W=c($.quota),z=c(Z.quota),X=W>z,G=X?{...$,...Z,quota:$.quota,lastQuotaRefreshError:$.lastQuotaRefreshError}:{...$,...Z};if(!X&&!("lastQuotaRefreshError"in Z))delete G.lastQuotaRefreshError;if(!("lastRefreshError"in Z))delete G.lastRefreshError;if(typeof $.lastUsed==="number"&&(typeof Z.lastUsed!=="number"||$.lastUsed>Z.lastUsed))G.lastUsed=$.lastUsed;return u4(G,$,Z),G}function f0(B){let Z=B.refresh?D({enabled:B.refresh.enabled,intervalMinutes:B.refresh.intervalMinutes,refreshBeforeExpiryMinutes:B.refresh.refreshBeforeExpiryMinutes}):void 0,$=B.quota?D({enabled:B.quota.enabled,checkIntervalMinutes:B.quota.checkIntervalMinutes,refreshEveryNRequests:B.quota.refreshEveryNRequests,minimumRemaining:B.quota.minimumRemaining,failClosedOnUnknownQuota:B.quota.failClosedOnUnknownQuota,showToasts:B.quota.showToasts}):void 0;return A0({version:1,main:B.main,routing:B.routing,fallbackOn:B.fallbackOn,refresh:Z,quota:$,dump:B.dump,costZeroing:B.costZeroing,killswitch:B.killswitch,logging:B.logging,cachekeep:B.cachekeep,mainAccountId:B.mainAccountId,accounts:B.accounts.map(d4)})}async function p(B){let Z=Date.now()+U0;while(Date.now()<=Z){let $=await I({name:"save",ttlMs:U0,path:B});if($)return $;let W=Z-Date.now();if(W<=0)break;await R4(Math.min(y4,W))}throw Error(`Timed out acquiring account store lock for ${B}; refusing to overwrite newer account data`)}function m0(B){let Z=Object.fromEntries(B.accounts.map(($)=>[$.id,T0($)]));return{version:1,main:D({quota:B.quota?.mainQuota,quotaCheckedAt:B.quota?.mainQuotaCheckedAt,quotaToken:B.quota?.mainQuotaToken,lastQuotaApiError:B.quota?.mainLastQuotaApiError,lastRefreshError:B.refresh?.mainLastRefreshError,refreshLeaseId:B.refresh?.mainRefreshLeaseId,refreshLeaseUntil:B.refresh?.mainRefreshLeaseUntil,refreshLeaseTokenHash:B.refresh?.mainRefreshLeaseTokenHash}),accounts:Z}}async function tB(B,Z=T()){let $=a(Z),W=await p(Z);try{let z=await p($);try{let X=await R(Z),G=await R($),K=(X.exists?x0(I0(X.value,G.value)):null)??r4(),Y=B(K)??K,J={...H(X.value)?X.value:{},...f0(Y)};return await A(Z,J),await A($,m0(Y)),Y}finally{await z.release()}}finally{await W.release()}}function r4(){return{version:1,main:{type:"opencode",provider:"openai"},accounts:[]}}function n4(B,Z){B.main=B.main??{};let $=typeof B.main.quotaCheckedAt==="number"?B.main.quotaCheckedAt:c(B.main.quota),W=typeof Z.quota?.mainQuotaCheckedAt==="number"?Z.quota.mainQuotaCheckedAt:c(Z.quota?.mainQuota);if($>W)return;B.main.quota=Z.quota?.mainQuota,B.main.quotaCheckedAt=Z.quota?.mainQuotaCheckedAt,B.main.quotaToken=Z.quota?.mainQuotaToken,B.main.lastQuotaApiError=Z.quota?.mainLastQuotaApiError}function c4(B,Z){B.main=B.main??{},B.main.lastRefreshError=Z.refresh?.mainLastRefreshError,B.main.refreshLeaseId=Z.refresh?.mainRefreshLeaseId,B.main.refreshLeaseUntil=Z.refresh?.mainRefreshLeaseUntil,B.main.refreshLeaseTokenHash=Z.refresh?.mainRefreshLeaseTokenHash}function K0(B){if(Array.isArray(B))return B.map(K0);if(!H(B))return B;return Object.fromEntries(Object.entries(B).filter(([,Z])=>Z!==void 0).map(([Z,$])=>[Z,K0($)]))}async function a4(B,Z=T(),$={mainQuota:!0,mainRefresh:!0,accounts:!0}){let W=a(Z),z=await p(W);try{let X=(await R(W)).value,G=H(X)?{...X,version:1}:{version:1};if($.mainQuota)n4(G,B);if($.mainRefresh)c4(G,B);if($.accounts){let K=$.accounts===!0?null:new Set($.accounts),Y=await p4(Z);G.accounts={...H(G.accounts)?G.accounts:{}};for(let j of B.accounts){if(K&&!K.has(j.id))continue;if(Y&&!Y.has(j.id))continue;G.accounts[j.id]=s4(G.accounts[j.id],T0(j))}if(K){for(let j of K)if(!B.accounts.some((J)=>J.id===j))delete G.accounts[j]}if(Y){for(let j of Object.keys(G.accounts))if(!Y.has(j))delete G.accounts[j]}}await A(W,K0(G))}finally{await z.release()}}function o4(B){return B?.fallbackOn?.length?B.fallbackOn:f4}function eB(B,Z){return o4(Z).includes(B)}function t4(B){let Z=B?.quota?.minimumRemaining||{};return{primary:Z.primary??Z["5h"]??M0.primary,secondary:Z.secondary??Z["1w"]??M0.secondary}}function Y0(B){return B?.quota?.enabled!==!1}function l(B){return B?.quota?.failClosedOnUnknownQuota??m4}function w0(B,Z,$=Date.now()){if(!Y0(Z))return!0;if(!B)return!l(Z);let W=t4(Z),z=l(Z);for(let X of["primary","secondary"]){let G=B[X];if(!G)continue;if(s(G,$)){if(z)return!1;continue}if(G.remainingPercent<W[X])return!1}return!0}function k0(B){return B?.killswitch?.enabled===!0}function C0(B){return{primary:B?.primary??B?.["5h"]??G0.primary,secondary:B?.secondary??B?.["1w"]??G0.secondary}}function h0(B,Z){if(!B?.killswitch)return G0;if(Z&&B.killswitch.accounts?.[Z])return C0(B.killswitch.accounts[Z]);return C0(B.killswitch.main)}function BZ(B,Z,$,W=Date.now()){if(!k0(Z))return!0;if(!B)return!l(Z);let z=h0(Z,$),X=l(Z);for(let G of["primary","secondary"]){let K=B[G];if(!K)continue;if(s(K,W)){if(X)return!1;continue}if(K.remainingPercent<z[G])return!1}return!0}function ZZ(B,Z,$,W){if(!k0(W))return 300;let z=[],X=[{accountId:void 0,quota:B},...Z];for(let{accountId:K,quota:Y}of X){if(!Y)continue;let j=h0(W,K),J=[],Q=!1;for(let y of["primary","secondary"]){let V=Y[y];if(!V||s(V,$))continue;if(V.remainingPercent>=j[y])continue;let F=V.resetsAt?Date.parse(V.resetsAt):NaN;if(!Number.isFinite(F)||F<=$){Q=!0;break}J.push(F)}if(Q||J.length===0)continue;z.push(Math.max(...J))}if(z.length===0)return 300;let G=Math.min(...z);return Math.max(1,Math.ceil((G-$)/1000))}function e4(B){return typeof B.version==="number"&&Array.isArray(B.accounts)}async function $Z(B,Z=T()){let $=a(Z),W=await p(Z);try{let z=await p($);try{let X=await R(Z);if(X.exists&&H(X.value)){if(e4(X.value))return}if(!B)return;let G={version:1,main:{type:"opencode",provider:"openai"},accounts:[]};if(B.access){let j=i({id_token:"",access_token:B.access,refresh_token:B.refresh});if(j)G.mainAccountId=j}let Y={...X.exists&&H(X.value)?X.value:{},...f0(G)};await A(Z,Y),await A($,m0(G))}finally{await z.release()}}finally{await W.release()}}function BB(B){return B?.refresh?.enabled!==!1}function ZB(B){return(B?.refresh?.refreshBeforeExpiryMinutes??240)*60000}function $B(B){return Math.floor(Math.random()*(B+1))}function S(B,Z,$){return!B.access||!B.expires||B.expires-$<=ZB(Z)}function WB(B,Z){return Boolean(B.access&&typeof B.expires==="number"&&B.expires>Z)}function zB(B,Z){return Boolean(B.mainAccountId&&Z.accountId&&Z.accountId===B.mainAccountId)}function N(B,Z){let $=B.accounts.findIndex((W)=>W.id===Z.id);if($!==-1)B.accounts[$]=Z}function z0(B){return B instanceof Error?B.message:String(B)}function j0(B,Z,$){B.lastRefreshError=Q0({error:Z,now:$,refreshToken:B.refresh,previous:B.lastRefreshError})}function X0(B,Z,$){if(B.lastQuotaRefreshError=f({error:Z,now:$,previous:B.lastQuotaRefreshError}),Z?.isRefreshError===!0)j0(B,Z,$)}function XB(B){return`fallback-oauth-refresh-${q4("sha256").update(B).digest("base64url").slice(0,16)}`}function E0(B,Z){if(!B)return!1;if(!B.resetsAt)return!0;let $=Date.parse(B.resetsAt);return Number.isFinite($)?$>Z:!0}function GB(B,Z){if(!B)return!1;return E0(B.primary,Z)||E0(B.secondary,Z)}function KB(B,Z,$){if(!B)return!1;let W=Z?.quota?.checkIntervalMinutes??5,z=Math.max(1,W)*60000,X=Math.max(B.primary?.checkedAt??0,B.secondary?.checkedAt??0);return $-X<z}function S0(B,Z,$){return!KB(B.quota,Z,$)}function YB(B,Z,$,W){return t($)&&w0(B.quota,Z,W)&&GB(B.quota,W)}function jB(B){let Z=B?.quota?.checkIntervalMinutes??5;return Math.max(1,Z)*60000}var JB=60000,HB=60000,QB=600000,NB=1e4,PB=100;var WZ=globalThis.setTimeout.bind(globalThis),zZ=globalThis.clearTimeout.bind(globalThis);class VB{now;fetchImpl;configPath;refreshPromises=new Map;refreshTimer=null;quotaTimer=null;quotaManager;onFallbackStorageChanged;options;constructor(B={}){this.options=B,this.now=B.now??Date.now,this.fetchImpl=B.fetchImpl??fetch,this.configPath=B.configPath??T(),this.quotaManager=B.quotaManager??null,this.onFallbackStorageChanged=B.onFallbackStorageChanged}seedFallbackQuota(B,Z){if(!this.quotaManager)return;if(!B.quota)return;let $=Math.max(B.quota.primary?.checkedAt??0,B.quota.secondary?.checkedAt??0);if($<=0)return;let W=this.quotaManager.getFallback(B.id,B.access);if(W&&W.checkedAt>=$)return;this.quotaManager.setFallback(B.id,{quota:B.quota,refreshAfter:$+jB(Z),checkedAt:$},B.access)}async load(){return l4(this.configPath)}async save(B,Z){await a4(B,this.configPath,{accounts:Z??!0})}startBackgroundRefresh(){let B=async()=>{if(await this.refreshDueAccounts(),this.options.fetchQuotaFn)await this.refreshQuotaForDueAccounts()};if(B().catch(()=>{}),!this.refreshTimer){if(this.refreshTimer=setInterval(()=>{B().catch(()=>{})},JB+$B(HB)),"unref"in this.refreshTimer)this.refreshTimer.unref()}}stopBackgroundRefresh(){if(this.refreshTimer)clearInterval(this.refreshTimer);if(this.quotaTimer)clearInterval(this.quotaTimer);this.refreshTimer=null,this.quotaTimer=null}async getUsableFallbackAccounts(B){let Z=B!==void 0?B:await this.load();if(!Z)return[];let $=[],W=!1;for(let z of Z.accounts){if(z.enabled===!1||!b(z))continue;if(zB(Z,z))continue;let X=!1,G=z;try{if(S(G,Z,this.now())){let K=G.lastRefreshError;if(K&&U(K,G.refresh,this.now()))throw X=!0,Error(d(K,this.now()));try{G=await this.refreshAccount(G,Z),W=!0}catch(Y){if(w4(Y))continue;X=!0;let j=Z.accounts.find((J)=>J.id===z.id&&b(J));if(j&&!U(j.lastRefreshError,j.refresh,this.now()))j0(j,Y,this.now()),N(Z,j),W=!0;throw Y}}if(this.seedFallbackQuota(G,Z),this.accountPassesQuotaPolicy(this.quotaPolicyAccount(G),Z))$.push(G)}catch(K){let Y=WB(G,this.now());if(X){if(!Y)continue}else if(!Y)continue;if(YB(G,Z,K,this.now()))E.debug("fallback quota using cached quota after refresh error",{pid:process.pid,accountId:G.id,error:z0(K)}),$.push(G);else if(!l(Z))$.push(G)}}if(W)await this.save(Z);return $}async markUsed(B){let Z=await this.load();if(!Z)return;let $=Z.accounts.find((W)=>W.id===B.id);if(!$)return;$.lastUsed=this.now(),await this.save(Z)}accountPassesQuotaPolicy(B,Z){return w0(B.quota,Z,this.now())}quotaPolicyAccount(B){if(!this.quotaManager)return B;let Z=this.quotaManager.getFallback(B.id,B.access)?.quota;return Z?{...B,quota:Z}:B}async refreshDueAccounts(){let B=await this.load();if(!B||!BB(B))return;let Z=!1;for(let $ of B.accounts){if($.enabled===!1||!b($))continue;if(!S($,B,this.now()))continue;if(U($.lastRefreshError,$.refresh,this.now()))continue;try{E.debug("fallback oauth background due",{pid:process.pid,accountId:$.id,expiresInMs:$.expires?$.expires-this.now():void 0}),await this.refreshAccount($,B),Z=!0}catch(W){E.warn("fallback oauth background failed",{pid:process.pid,accountId:$.id,error:z0(W)}),j0($,W,this.now()),N(B,$),Z=!0}}if(Z)await this.save(B)}async refreshQuotaForDueAccounts(){let B=await this.load();if(!B||!Y0(B))return;if(!this.options.fetchQuotaFn)return;let Z=!1;for(let $ of B.accounts){if($.enabled===!1||!b($))continue;let W=$;try{if(S(W,B,this.now())){if(U(W.lastRefreshError,W.refresh,this.now()))continue;W=await this.refreshAccount(W,B),Z=!0}if(x(W.lastQuotaRefreshError,this.now()))continue;if(this.seedFallbackQuota(W,B),!(this.quotaManager?this.quotaManager.isFallbackStale(W.id,W.access):S0(W,B,this.now())))continue;await this.refreshAccountQuota(W,B),Z=!0}catch(z){X0($,z,this.now()),N(B,$),Z=!0}}if(Z)await this.save(B),this.onFallbackStorageChanged?.()}async refreshQuotaForAllAccounts(B={}){let Z=await this.load(),$=[];if(!Z||!Y0(Z))return{storage:Z,errors:$};if(!this.options.fetchQuotaFn)return{storage:Z,errors:$};let W=B.force??!1,z=!1;for(let X of Z.accounts){if(X.enabled===!1||!b(X))continue;let G=X;try{if(S(G,Z,this.now())){let K=G.lastRefreshError;if(K&&U(K,G.refresh,this.now()))throw Error(d(K,this.now()));G=await this.refreshAccount(G,Z),z=!0}if(!W&&!S0(G,Z,this.now())){if(G.lastQuotaRefreshError)G.lastQuotaRefreshError=void 0,N(Z,G),z=!0;continue}await this.refreshAccountQuota(G,Z),z=!0}catch(K){X0(X,K,this.now()),N(Z,X),z=!0,$.push({accountId:X.id,message:z0(K)})}}if(z)await this.save(Z);return{storage:Z,errors:$}}async refreshAccount(B,Z,$={}){let W=this.refreshPromises.get(B.id);if(W){let G=await W;return N(Z,G),G}let z=this.refreshAccountNow(B,Z,$).finally(()=>{this.refreshPromises.delete(B.id)});this.refreshPromises.set(B.id,z);let X=await z;return N(Z,X),X}async waitForConcurrentFallbackRefresh(B,Z,$,W){let z=Date.now()+NB;while(Date.now()<z){await new Promise((j)=>setTimeout(j,PB));let X=await this.load(),G=X?.accounts.find((j)=>j.id===B.id&&b(j));if(!G)continue;if((G.access!==$.access||G.refresh!==$.refresh||(G.expires??0)>($.expires??0)+60000)&&(W.force||!S(G,X,this.now())))return N(Z,G),E.debug("fallback oauth joined concurrent refresh",{pid:process.pid,accountId:G.id,expiresInMs:G.expires?G.expires-this.now():void 0}),G;let Y=G.lastRefreshError;if(Y&&U(Y,G.refresh,this.now()))throw N(Z,G),Error(d(Y,this.now()))}return null}async refreshAccountNow(B,Z,$){let W=await this.load(),z=W?.accounts.find((K)=>K.id===B.id&&b(K));if(z&&!$.force&&!S(z,W,this.now()))return N(Z,z),z;let X=z??B,G=await I({name:XB(X.id),ttlMs:QB,path:this.configPath,now:this.now,renew:!0});if(!G){E.debug("fallback oauth refresh skipped file lock",{pid:process.pid,accountId:X.id});let K=await this.waitForConcurrentFallbackRefresh(B,Z,X,$);if(K)return K;throw Error("Fallback OAuth refresh is already in progress")}try{if(W=await this.load(),z=W?.accounts.find((J)=>J.id===B.id&&b(J)),z&&!$.force&&!S(z,W,this.now()))return N(Z,z),z;if(!z)throw new n(B.id);X=z;let K=this.options.refreshFn??(async()=>{throw Error("No refreshFn injected into FallbackAccountManager")});E.debug("fallback oauth refresh request start",{pid:process.pid,accountId:X.id,force:$.force===!0,expiresInMs:X.expires?X.expires-this.now():void 0});let Y=await K({refreshToken:X.refresh,fetchImpl:this.fetchImpl,now:this.now});if(X.access=Y.access,X.refresh=Y.refresh,X.expires=Y.expires,X.lastRefreshedAt=Y.expires-Y.expiresIn*1000,X.lastRefreshError=void 0,N(Z,X),await this.save(Z),!(await this.load())?.accounts.some((J)=>J.id===B.id))throw new n(B.id);return E.debug("fallback oauth refresh succeeded",{pid:process.pid,accountId:X.id,expiresInMs:X.expires?X.expires-this.now():void 0}),X}finally{await G.release()}}async refreshAccountQuota(B,Z){let $=B;if(!$.access)throw Error(`Fallback account ${B.id} has no access token`);if(!this.options.fetchQuotaFn)throw Error("No fetchQuotaFn injected — wham/usage supplement is disabled");let W=this.options.fetchQuotaFn??(async()=>{throw Error("No fetchQuotaFn injected — wham/usage supplement is disabled")}),z=(X)=>this.quotaManager?this.quotaManager.refreshFallback($.id,X):W({accessToken:X,fetchImpl:this.fetchImpl,now:this.now});try{if(!$.access)throw Error(`Fallback account ${B.id} has no access token`);let X=await z($.access);$.quota=X,$.lastQuotaRefreshError=void 0,N(Z,$),await this.save(Z)}catch(X){throw X0(B,X,this.now()),N(Z,B),X}}}
89
- export{H0 as h,Q0 as i,U as j,d as k,L0 as l,O0 as m,o0 as n,P0 as o,V0 as p,i as q,B0 as r,e0 as s,C as t,W4 as u,z4 as v,X4 as w,G4 as x,MB as y,_B as z,EB as A,SB as B,TB as C,O as D,T as E,b as F,aB as G,G0 as H,l4 as I,tB as J,eB as K,k0 as L,BZ as M,ZZ as N,$Z as O,VB as P};
87
+ </html>`,k,w,L=new Map;function M(){return L.size}function C(B){if(L.delete(B),M()===0)_()}async function W1(){let B=`http://localhost:${m}/auth/callback`;if(k)return{port:m,redirectUri:B};if(w)return w;w=(async()=>{let Z=r0(($,W)=>{let z=new URL($.url||"/",`http://127.0.0.1:${m}`);if(z.pathname==="/auth/callback"){let X=z.searchParams.get("code"),G=z.searchParams.get("state"),K=z.searchParams.get("error"),Y=z.searchParams.get("error_description");if(K){let J=Y||K;if(G){let Q=L.get(G);if(Q)Q.reject(Error(J)),C(G);else if(M()===0)_()}else if(M()===0)_();W.writeHead(200,{"Content-Type":"text/html"}),W.end(g(J));return}if(!G){if(M()===0)_();W.writeHead(400,{"Content-Type":"text/html"}),W.end(g("Missing state parameter"));return}if(!X){if(M()===0)_();W.writeHead(400,{"Content-Type":"text/html"}),W.end(g("Missing authorization code"));return}let j=L.get(G);if(!j){if(M()===0)_();W.writeHead(400,{"Content-Type":"text/html"}),W.end(g("Unknown state — authorization may have expired"));return}C(G),B1(X,B,j.pkce).then((J)=>j.resolve(J)).catch((J)=>j.reject(J)),W.writeHead(200,{"Content-Type":"text/html"}),W.end($1);return}if(z.pathname==="/cancel"){let X=z.searchParams.get("state"),G=X?[X]:[...L.keys()];W.writeHead(200),W.end("Login cancelled");for(let K of G){let Y=L.get(K);if(!Y)continue;Y.reject(Error("Login cancelled")),C(K)}if(M()===0)_();return}W.writeHead(404),W.end("Not found")});return await new Promise(($,W)=>{Z.once("error",W),Z.listen(m,"127.0.0.1",()=>{Z.off("error",W),$()})}),k=Z,{port:m,redirectUri:B}})();try{return await w}finally{w=void 0}}function _(){if(k){let B=k;k=void 0,B.close(()=>{}),B.closeIdleConnections?.(),setTimeout(()=>{B.closeAllConnections?.()},25).unref?.()}}function z1(B,Z,$=300000,W){return new Promise((z,X)=>{if(W?.aborted){C(Z),X(Error("Login cancelled"));return}let G=setTimeout(()=>{if(L.get(Z))C(Z),X(Error("OAuth callback timeout — authorization took too long"))},$),K=()=>{if(clearTimeout(G),L.get(Z))C(Z),X(Error("Login cancelled"))};if(W)W.addEventListener("abort",K);L.set(Z,{pkce:B,state:Z,resolve:(Y)=>{if(clearTimeout(G),W)W.removeEventListener("abort",K);z(Y)},reject:(Y)=>{if(clearTimeout(G),W)W.removeEventListener("abort",K);X(Y)}})})}async function X1(){let B=await fetch(`${q}/api/accounts/deviceauth/usercode`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":L0},body:JSON.stringify({client_id:u})});if(!B.ok)throw Error("Failed to initiate device authorization");let Z=await B.json();return{deviceData:Z,url:`${q}/codex/device`,instructions:`Enter code: ${Z.user_code}`}}async function G1(B,Z){let $=Math.max(parseInt(B.interval,10)||5,1)*1000,W=typeof B.expires_in==="number"?B.expires_in:parseInt(B.expires_in||"",10),z=!Number.isNaN(W)&&W>0?W*1000:900000,X=Date.now();while(!0){if(Z?.aborted)throw Error("Device authorization cancelled");if(Date.now()-X>z)throw Error("Device authorization expired");let G=await fetch(`${q}/api/accounts/deviceauth/token`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":L0},body:JSON.stringify({device_auth_id:B.device_auth_id,user_code:B.user_code})});if(G.ok){let j=await G.json(),J=await fetch(`${q}/oauth/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",code:j.authorization_code,redirect_uri:`${q}/deviceauth/callback`,client_id:u,code_verifier:j.code_verifier}).toString()});if(!J.ok)throw Error(`Token exchange failed: ${J.status}`);return await J.json()}if(G.status!==403&&G.status!==404)throw Error(`Device authorization failed: ${G.status}`);let K=z-(Date.now()-X);if(K<=0)throw Error("Device authorization expired");let Y=Math.min($+c0,K);try{await n0(Y,void 0,{signal:Z})}catch(j){if(j instanceof Error&&j.name==="AbortError")throw Error("Device authorization cancelled");throw j}}}function M4(B,Z){let $=-1;if(Z.accountId)$=B.findIndex((W)=>W.accountId&&W.accountId===Z.accountId);if($<0)$=B.findIndex((W)=>W.id===Z.id);if($<0&&Z.label&&!Z.accountId)$=B.findIndex((W)=>W.label===Z.label);if($>=0)return B[$]={...B[$],...Z,addedAt:B[$]?.addedAt??Z.addedAt},$;return B.push(Z),B.length-1}async function _4(B={}){let{label:Z,headless:$=!1,signal:W}=B;if(B0(Z),$){let{deviceData:j,url:J,instructions:Q}=await X1(),y=(async()=>{let V=await G1(j,W),F=Date.now(),J0=i(V);return{id:B0(Z||J0||crypto.randomUUID()),label:Z||void 0,type:"oauth",access:V.access_token,refresh:V.refresh_token,expires:F+(V.expires_in??3600)*1000,enabled:!0,addedAt:F,lastUsed:F,lastRefreshedAt:F,accountId:J0}})();return{url:J,instructions:Q,completion:y}}let{redirectUri:z}=await W1(),X=await o0(),G=O0(crypto.getRandomValues(new Uint8Array(32)).buffer),K=e0(z,X,G),Y=(async()=>{try{if(W?.aborted)throw Error("Login cancelled");let j=await z1(X,G,void 0,W),J=Date.now(),Q=i(j);return{id:B0(Z||Q||crypto.randomUUID()),label:Z||void 0,type:"oauth",access:j.access_token,refresh:j.refresh_token,expires:J+(j.expires_in??3600)*1000,enabled:!0,addedAt:J,lastUsed:J,lastRefreshedAt:J,accountId:Q}}finally{C(G)}})();return{url:K,instructions:"Complete authorization in your browser. This window will close automatically.",completion:Y}}var Z0="primary",$0="secondary",Y1="app_EMoamEEZ73f0CkXaXp7hrann",j1="https://auth.openai.com";async function E4(B){let Z=await B.fetchImpl(`${j1}/oauth/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"refresh_token",refresh_token:B.refreshToken,client_id:Y1}).toString()});if(!Z.ok){let W=e(Z.headers.get("retry-after"));throw Object.assign(Error(`Token refresh failed: ${Z.status}`),{status:Z.status,retryAfter:W,isRefreshError:!0})}let $=await Z.json();if(!$||typeof $.access_token!=="string"||!$.access_token||typeof $.refresh_token!=="string"||!$.refresh_token||typeof $.expires_in!=="number")throw Object.assign(Error("Token refresh failed: malformed response"),{status:Z.status,isRefreshError:!0});return{access:$.access_token,refresh:$.refresh_token,expires:B.now()+$.expires_in*1000,expiresIn:$.expires_in}}var J1="https://chatgpt.com/backend-api/wham/usage";async function S4(B){let Z=await B.fetchImpl(J1,{headers:{authorization:`Bearer ${B.accessToken}`,"chatgpt-account-id":B.accountId??"","oai-client-platform":"web","oai-client-version":"0","x-openai-target-path":"/backend-api/wham/usage"}});if(!Z.ok){let W=e(Z.headers.get("retry-after"));throw Object.assign(Error(`wham usage check failed: ${Z.status}`),{status:Z.status,retryAfter:W})}let{normalizeWham:$}=await import("./quota-normalize-8yzxqy78.js");return $(await Z.json())}import{createHash as H1}from"node:crypto";var Q1=globalThis.setTimeout,N1=5;function h(B){let Z=B?.quota?.checkIntervalMinutes??N1;return Math.max(1,Z)*60000}function P1(B){return B?.quota?.enabled!==!1}function s(B,Z){if(!B?.resetsAt)return!1;let $=Date.parse(B.resetsAt);return Number.isFinite($)&&$<=Z}function T4(B,Z,$,W){let z=Z===Z0?B?.primary:Z===$0?B?.secondary:void 0,X=z?.resetsAt?Date.parse(z.resetsAt):NaN;if(Number.isFinite(X)&&X>$)return X;return $+W}function V1(B){let Z=B?.quota?.minimumRemaining||{};return{primary:Z.primary??Z["5h"]??15,secondary:Z.secondary??Z["1w"]??10}}function b0(B,Z,$){if(!P1(Z))return $+h(Z);let W=V1(Z),z=[];for(let X of["primary","secondary"]){let G=B?.[X];if(!G)continue;if(G.remainingPercent>=W[X])continue;let K=G.resetsAt?Date.parse(G.resetsAt):Number.NaN;if(!Number.isFinite(K)||K<=$)return $+h(Z);z.push(K)}if(!z.length)return $+h(Z);return Math.min(...z)+60000}function L1(B){if(!B?.quota?.mainQuota||!B.quota.mainQuotaCheckedAt)return null;return{quota:B.quota.mainQuota,checkedAt:B.quota.mainQuotaCheckedAt,tokenFingerprint:B.quota.mainQuotaToken}}function F1(B){let Z=B?.quota?.refreshEveryNRequests;return typeof Z==="number"&&Number.isFinite(Z)&&Z>0?Math.floor(Z):0}function P(B){return H1("sha256").update(B).digest("hex").slice(0,16)}class O{main=null;mainTokenFp=null;mainQuotaAccountId=null;fallbacks=new Map;fallbackTokenFps=new Map;inflightMain=null;inflightMainFp=null;inflightFallbacks=new Map;mainLastApiError=void 0;fallbackApiErrors=new Map;fallbackErrorTokenFps=new Map;rateLimitedUntilMap=new Map;apiGate=Promise.resolve();lastApiCallAt=0;storage;fetchImpl;now;fetchQuotaFn;onMainQuotaFetched;onApiError;constructor(B){this.storage=B.storage,this.fetchImpl=B.fetchImpl??fetch,this.now=B.now??Date.now,this.fetchQuotaFn=B.fetchQuotaFn,this.onMainQuotaFetched=B.onMainQuotaFetched,this.onApiError=B.onApiError,this.seedMainFromStorage(B.storage),this.seedMainBackoffFromStorage(B.storage)}getMain(B){if(B&&this.main&&this.mainTokenFp&&this.mainTokenFp!==P(B))this.main=null,this.mainTokenFp=null;return this.main}getFallback(B,Z){let $=this.fallbacks.get(B)??null;if(!Z||!$)return $;if(this.fallbackTokenFps.get(B)!==P(Z))return this.fallbacks.delete(B),this.fallbackTokenFps.delete(B),null;return $}getAllFallbacks(){return this.fallbacks}setMain(B,Z,$,W=!1){if(!W&&!D0(Z.quota))return;if(this.mainTokenFp=P(B),$&&this.mainQuotaAccountId&&this.mainQuotaAccountId!==$)this.clearRateLimited("main");if($)this.mainQuotaAccountId=$;if(this.main=Z,W0(Z.quota))this.clearRateLimited("main")}peekMainForPolicy(B){if(B&&this.mainQuotaAccountId&&this.mainQuotaAccountId!==B)return null;return this.main}peekFallbackForPolicy(B){return this.fallbacks.get(B)??null}setFallback(B,Z,$,W=!1){if(!W&&!D0(Z.quota))return;if(this.fallbacks.set(B,Z),$)this.fallbackTokenFps.set(B,P($));else this.fallbackTokenFps.delete(B);if(W0(Z.quota))this.clearRateLimited(B)}markRateLimited(B,Z){let $=this.rateLimitedUntilMap.get(B);if($!==void 0&&$>Z)return;this.rateLimitedUntilMap.set(B,Z)}isRateLimited(B){let Z=this.rateLimitedUntilMap.get(B);return Z!==void 0&&this.now()<Z}rateLimitedUntil(B){return this.rateLimitedUntilMap.get(B)}clearRateLimited(B){this.rateLimitedUntilMap.delete(B)}async refreshMain(B){let Z=P(B);if(this.mainTokenFp&&this.mainTokenFp!==Z)this.main=null,this.mainTokenFp=null;if(this.inflightMain&&this.inflightMainFp===Z)return this.inflightMain;if(this.isBackedOff()){if(this.main)return this.main.quota;throw Error("Quota API rate-limited — try again later")}return this.inflightMainFp=Z,this.inflightMain=this._fetchMain(B),this.inflightMain}async refreshFallback(B,Z){let $=O.fallbackInflightKey(B,Z),W=this.inflightFallbacks.get($);if(W)return W;if(this.isFallbackBackedOff(B,Z)){let X=this.getFallback(B,Z);if(X)return X.quota;throw Error("Quota API rate-limited — try again later")}let z=this._fetchFallback(B,Z);return this.inflightFallbacks.set($,z),z}async refreshAllFallbacks(B){let Z=this.now();for(let $ of B){if($.enabled===!1)continue;if(!$.access)continue;let W=this.getFallback($.id,$.access);if(W&&Z<W.refreshAfter)continue;try{await this.refreshFallback($.id,$.access)}catch{}}}refreshMainInBackground(B){let Z=P(B);if(this.inflightMain&&this.inflightMainFp===Z)return;if(this.isBackedOff())return;this.refreshMain(B).catch(()=>{})}isMainStale(){if(!this.main)return!0;return this.now()>=this.main.refreshAfter}isFallbackStale(B,Z){let $=this.getFallback(B,Z);if(!$)return!0;return this.now()>=$.refreshAfter}shouldRefreshOnRequestCount(B){let Z=F1(this.storage);if(Z<=0)return!1;return B>0&&B%Z===0}needsRefresh(B){return this.isMainStale()||this.shouldRefreshOnRequestCount(B)}updateStorage(B){this.storage=B,this.seedMainFromStorage(B),this.seedMainBackoffFromStorage(B)}seedMainFromStorage(B,Z){let $=L1(B);if(!$)return;let W=Z?P(Z):null;if(W&&$.tokenFingerprint&&$.tokenFingerprint!==W)return;let z={quota:$.quota,refreshAfter:b0($.quota,B,$.checkedAt),checkedAt:$.checkedAt};if(this.main&&this.main.checkedAt>=z.checkedAt&&(!W||!this.mainTokenFp||this.mainTokenFp===W))return;if(this.main=z,this.mainTokenFp=$.tokenFingerprint??null,B?.mainAccountId){if(this.mainQuotaAccountId&&this.mainQuotaAccountId!==B.mainAccountId)this.clearRateLimited("main");this.mainQuotaAccountId=B.mainAccountId}}seedMainBackoffFromStorage(B){let Z=B?.quota?.mainLastQuotaApiError;this.mainLastApiError=Z&&x(Z,this.now())?Z:void 0}seedFallbacksFromAccounts(B){let Z=h(this.storage);for(let $ of B){if($.enabled===!1)continue;if(!$.quota)continue;let W=Math.max($.quota.primary?.checkedAt??0,$.quota.secondary?.checkedAt??0);if(W<=0)continue;let z=this.getFallback($.id,$.access);if(z&&z.checkedAt>=W)continue;this.setFallback($.id,{quota:$.quota,refreshAfter:W+Z,checkedAt:W},$.access)}}isBackedOff(){return x(this.mainLastApiError,this.now())}isFallbackBackedOff(B,Z){if(Z){if(this.fallbackErrorTokenFps.get(B)!==P(Z))return!1}return x(this.fallbackApiErrors.get(B),this.now())}getLastApiError(){return this.mainLastApiError}static API_CALL_GAP_MS=1000;static fallbackInflightKey(B,Z){return JSON.stringify([B,P(Z)])}static quotaLockName(B){return`opencode-fallback-quota-refresh-${B.replace(/[^a-zA-Z0-9._-]+/g,"-")||"account"}`}_enqueueApiFetch(B){let Z=async()=>{let W=this.now()-this.lastApiCallAt;if(W<O.API_CALL_GAP_MS)await new Promise((z)=>{let X=Q1(z,O.API_CALL_GAP_MS-W);if(typeof X==="object"&&"unref"in X)X.unref()});return this.lastApiCallAt=this.now(),B()},$=this.apiGate.then(Z,Z);return this.apiGate=$.catch(()=>{}),$}async _fetchMain(B){let Z=P(B);return this._enqueueApiFetch(async()=>{try{if(this.isBackedOff()){if(this.main)return this.main.quota;throw Error("Quota API rate-limited — try again later")}let $=await I({name:"opencode-main-quota-refresh",ttlMs:30000});if(!$){let W=this.main;if(W&&this.now()<W.refreshAfter)return W.quota;throw Error("Quota refresh is already in progress")}try{let W=this.now(),z=await this._fetchQuota(B),X=this.now();if(this.mainTokenFp=P(B),this.main={quota:z,refreshAfter:b0(z,this.storage,X),checkedAt:X},W0(z))this.clearRateLimited("main");return this.mainLastApiError=void 0,this.onMainQuotaFetched?.(z,X,this.mainTokenFp,W),z}catch(W){throw this._handleMainFetchError(W),W}finally{await $.release()}}finally{if(this.inflightMainFp===Z)this.inflightMain=null,this.inflightMainFp=null}})}async _fetchFallback(B,Z){return this._enqueueApiFetch(async()=>{try{if(this.isFallbackBackedOff(B,Z)){let W=this.getFallback(B,Z);if(W)return W.quota;throw Error("Quota API rate-limited — try again later")}let $=await I({name:O.quotaLockName(B),ttlMs:30000});if(!$){let W=this.getFallback(B,Z);if(W&&this.now()<W.refreshAfter)return W.quota;throw Error("Quota refresh is already in progress")}try{let W=await this._fetchQuota(Z),z=this.now();return this.setFallback(B,{quota:W,refreshAfter:z+h(this.storage),checkedAt:z},Z,!0),this.fallbackApiErrors.delete(B),this.fallbackErrorTokenFps.delete(B),W}finally{await $.release()}}catch($){throw this._handleFallbackFetchError(B,Z,$),$}finally{this.inflightFallbacks.delete(O.fallbackInflightKey(B,Z))}})}async _fetchQuota(B){if(!this.fetchQuotaFn)throw Error("Quota fetch not available — no fetchQuotaFn injected (push-only mode)");return this.fetchQuotaFn({accessToken:B,fetchImpl:this.fetchImpl,now:this.now})}static isAuthError(B){return B?.status===401}_handleMainFetchError(B){if(O.isAuthError(B))return;this.mainLastApiError=f({error:B,now:this.now(),previous:this.mainLastApiError}),this.onApiError?.(this.mainLastApiError)}_handleFallbackFetchError(B,Z,$){if(O.isAuthError($))return;let W=P(Z),z=this.fallbackErrorTokenFps.get(B)===W?this.fallbackApiErrors.get(B):void 0;this.fallbackApiErrors.set(B,f({error:$,now:this.now(),previous:z})),this.fallbackErrorTokenFps.set(B,W)}}function D0(B){return Boolean(B.primary||B.secondary)}function W0(B){let{primary:Z,secondary:$}=B;if(!Z&&!$)return!1;if(Z&&Z.usedPercent>=100)return!1;if($&&$.usedPercent>=100)return!1;return!0}import{createHash as q1,randomUUID as C1}from"node:crypto";import{homedir as E1}from"node:os";import{dirname as S1,join as r}from"node:path";import{setTimeout as R1}from"node:timers/promises";import{randomUUID as O1}from"node:crypto";import{mkdir as b1,rename as D1,rm as U1,writeFile as M1}from"node:fs/promises";import{dirname as _1}from"node:path";async function A(B,Z){await b1(_1(B),{recursive:!0});let $=`${B}.${O1()}.tmp`;await M1($,`${JSON.stringify(Z,null,2)}
88
+ `,{encoding:"utf8",mode:384});try{await D1($,B)}catch(W){throw await U1($,{force:!0}).catch(()=>{}),W}}import{readFile as v1}from"node:fs/promises";var E=R0("refresh"),U0=1e4,y1=50,y0="openai-auth.json",x1="openai-auth-state.json";function I1(){if(process.env.OPENCODE_CONFIG_DIR?.trim())return process.env.OPENCODE_CONFIG_DIR.trim();return r(process.env.XDG_CONFIG_HOME||r(E1(),".config"),"opencode")}function T(){return process.env.OPENCODE_OPENAI_AUTH_FILE?.trim()||r(I1(),y0)}function a(B=T()){let Z=process.env.OPENCODE_OPENAI_AUTH_STATE_FILE?.trim();if(Z)return Z;return A1(B)}function A1(B){return B.endsWith(y0)?r(S1(B),x1):`${B}.state.json`}function b(B){return B.type==="oauth"}function T1(B){let Z=B?.trim();if(!Z)return!1;try{let $=new URL(Z);return($.protocol==="http:"||$.protocol==="https:")&&!$.username&&!$.password}catch{return!1}}function a4(B){return B.costZeroing?.enabled!==!1}class n extends Error{code="ACCOUNT_REMOVED_DURING_REFRESH";constructor(B){super(`Fallback account ${B} was removed before refresh`);this.name="AccountRemovedDuringRefreshError"}}var f1=[401,403,429],M0={primary:0,secondary:0},m1=!1,G0={primary:5,secondary:10};function H(B){return B!=null&&typeof B==="object"&&!Array.isArray(B)}function w1(B){return B instanceof n||H(B)&&B.name==="AccountRemovedDuringRefreshError"&&B.code==="ACCOUNT_REMOVED_DURING_REFRESH"}function _0(B){return{id:typeof B.id==="string"&&B.id.trim()?B.id.trim():C1(),label:typeof B.label==="string"?B.label:void 0,enabled:typeof B.enabled==="boolean"?B.enabled:void 0,addedAt:typeof B.addedAt==="number"?B.addedAt:void 0,lastUsed:typeof B.lastUsed==="number"?B.lastUsed:void 0,accountId:typeof B.accountId==="string"?B.accountId:void 0}}function q0(B){if(!H(B))return;if(typeof B.message!=="string")return;let Z=Number(B.checkedAt);if(!Number.isFinite(Z))return;let $=Number(B.nextRetryAt),W=Number(B.retryCount);return{message:B.message,checkedAt:Z,nextRetryAt:Number.isFinite($)?$:void 0,retryCount:Number.isFinite(W)?W:void 0,tokenHash:typeof B.tokenHash==="string"?B.tokenHash:void 0}}function k1(B){if(!H(B))return;let Z={};for(let W of["primary","secondary"]){let z=B[W];if(!H(z))continue;let X=Number(z.usedPercent),G=Number(z.remainingPercent),K=Number(z.checkedAt);if(!Number.isFinite(X)||!Number.isFinite(G)||!Number.isFinite(K))continue;let Y=typeof z.windowMinutes==="number"?z.windowMinutes:Number.NaN;Z[W]={usedPercent:X,remainingPercent:G,checkedAt:K,resetsAt:typeof z.resetsAt==="string"?z.resetsAt:void 0,...Number.isFinite(Y)&&Y>0?{windowMinutes:Y}:{}}}let $=typeof B.resetCreditsAvailable==="number"?B.resetCreditsAvailable:Number.NaN;if(Number.isFinite($)&&$>=0)Z.resetCreditsAvailable=$;return Object.keys(Z).length?Z:void 0}function h1(B){if(!H(B))return null;if(B.type==="api"){let Z=typeof B.baseURL==="string"?B.baseURL.trim():"",$=typeof B.apiKey==="string"?B.apiKey.trim():"";if(!T1(Z))return null;let W=B.authHeader==="x-api-key"?"x-api-key":"authorization-bearer";return{..._0(B),type:"api",apiKey:$||void 0,baseURL:Z,authHeader:W}}if(B.type!=="oauth")return null;if(typeof B.refresh!=="string"||!B.refresh.trim())return null;return{..._0(B),type:"oauth",access:typeof B.access==="string"?B.access:void 0,refresh:B.refresh,expires:typeof B.expires==="number"?B.expires:void 0,lastRefreshedAt:typeof B.lastRefreshedAt==="number"?B.lastRefreshedAt:void 0,lastRefreshError:q0(B.lastRefreshError),lastQuotaRefreshError:q0(B.lastQuotaRefreshError),quota:k1(B.quota)}}function x0(B){if(!H(B)||!Array.isArray(B.accounts))return null;return{version:1,main:{type:"opencode",provider:"openai"},routing:H(B.routing)?B.routing:void 0,fallbackOn:Array.isArray(B.fallbackOn)?B.fallbackOn.filter((Z)=>Number.isInteger(Z)):void 0,refresh:H(B.refresh)?B.refresh:void 0,quota:H(B.quota)?B.quota:void 0,dump:H(B.dump)?B.dump:void 0,costZeroing:H(B.costZeroing)?B.costZeroing:void 0,killswitch:H(B.killswitch)?B.killswitch:void 0,logging:H(B.logging)?B.logging:void 0,cachekeep:H(B.cachekeep)?B.cachekeep:void 0,mainAccountId:typeof B.mainAccountId==="string"?B.mainAccountId:void 0,accounts:B.accounts.map(h1).filter((Z)=>Z!=null)}}async function R(B){try{return{exists:!0,value:JSON.parse(await v1(B,"utf8"))}}catch(Z){if(Z.code==="ENOENT")return{exists:!1,value:null};throw Z}}function D(B){return Object.fromEntries(Object.entries(B).filter(([,Z])=>Z!==void 0))}async function p1(B){let Z;try{Z=(await R(B)).value}catch{return null}if(!H(Z)||!Array.isArray(Z.accounts))return null;let $=new Set;for(let W of Z.accounts)if(H(W)&&typeof W.id==="string")$.add(W.id);return $}function I0(B,Z){if(!H(B))return B;let $=H(Z)?Z:{},W=H($.main)?$.main:void 0,z=H($.accounts)?$.accounts:{},X=H(B.quota)?B.quota:{},G=H(B.refresh)?B.refresh:{},K=W??X,Y=W??G,J=Array.isArray(B.accounts)?B.accounts.map((Q)=>{if(!H(Q))return Q;let y=typeof Q.id==="string"&&H(z[Q.id])?z[Q.id]:{};return{...Q,...y}}):void 0;return A0({...B,refresh:D({...G,mainLastRefreshError:Y.lastRefreshError,mainRefreshLeaseId:Y.refreshLeaseId,mainRefreshLeaseUntil:Y.refreshLeaseUntil,mainRefreshLeaseTokenHash:Y.refreshLeaseTokenHash}),quota:D({...X,mainQuota:K.quota,mainQuotaCheckedAt:K.quotaCheckedAt,mainQuotaToken:K.quotaToken,mainLastQuotaApiError:K.lastQuotaApiError}),accounts:J})}async function l1(B=T()){let Z=await R(B);if(!Z.exists)return null;let $=await R(a(B));return x0(I0(Z.value,$.value))}function A0(B){return Object.fromEntries(Object.entries(B).filter(([,Z])=>Z!==void 0))}function d1(B){return D({id:B.id,label:B.label,type:B.type,enabled:B.enabled,addedAt:B.addedAt,accountId:B.accountId,baseURL:B.type==="api"?B.baseURL:void 0,authHeader:B.type==="api"?B.authHeader:void 0})}function T0(B){if(B.type==="api")return D({apiKey:B.apiKey,lastUsed:B.lastUsed});return D({access:B.access,refresh:B.refresh,expires:B.expires,lastUsed:B.lastUsed,lastRefreshedAt:B.lastRefreshedAt,lastRefreshError:B.lastRefreshError,lastQuotaRefreshError:B.lastQuotaRefreshError,quota:B.quota})}function c(B){return Math.max(B?.primary?.checkedAt??0,B?.secondary?.checkedAt??0)}function v(B,Z,$){if($ in Z)B[$]=Z[$];else delete B[$]}function g1(B,Z){return B.access===Z.access&&B.refresh===Z.refresh&&B.expires===Z.expires&&B.lastRefreshedAt===Z.lastRefreshedAt}function i1(B,Z){if(!g1(B,Z))return Z;if(!("lastRefreshError"in Z))return B;if(!("lastRefreshError"in B))return Z;return(Z.lastRefreshError?.checkedAt??0)>(B.lastRefreshError?.checkedAt??0)?Z:B}function u1(B,Z,$){let W=Z.lastRefreshedAt??0,z=$.lastRefreshedAt??0,X=Z.expires??0,G=$.expires??0,K=z>W?$:W>z?Z:G>X?$:X>G?Z:i1(Z,$);v(B,K,"access"),v(B,K,"refresh"),v(B,K,"expires"),v(B,K,"lastRefreshedAt"),v(B,K,"lastRefreshError")}function s1(B,Z){if(!H(B))return Z;let $=B,W=c($.quota),z=c(Z.quota),X=W>z,G=X?{...$,...Z,quota:$.quota,lastQuotaRefreshError:$.lastQuotaRefreshError}:{...$,...Z};if(!X&&!("lastQuotaRefreshError"in Z))delete G.lastQuotaRefreshError;if(!("lastRefreshError"in Z))delete G.lastRefreshError;if(typeof $.lastUsed==="number"&&(typeof Z.lastUsed!=="number"||$.lastUsed>Z.lastUsed))G.lastUsed=$.lastUsed;return u1(G,$,Z),G}function f0(B){let Z=B.refresh?D({enabled:B.refresh.enabled,intervalMinutes:B.refresh.intervalMinutes,refreshBeforeExpiryMinutes:B.refresh.refreshBeforeExpiryMinutes}):void 0,$=B.quota?D({enabled:B.quota.enabled,checkIntervalMinutes:B.quota.checkIntervalMinutes,refreshEveryNRequests:B.quota.refreshEveryNRequests,minimumRemaining:B.quota.minimumRemaining,failClosedOnUnknownQuota:B.quota.failClosedOnUnknownQuota,showToasts:B.quota.showToasts}):void 0;return A0({version:1,main:B.main,routing:B.routing,fallbackOn:B.fallbackOn,refresh:Z,quota:$,dump:B.dump,costZeroing:B.costZeroing,killswitch:B.killswitch,logging:B.logging,cachekeep:B.cachekeep,mainAccountId:B.mainAccountId,accounts:B.accounts.map(d1)})}async function p(B){let Z=Date.now()+U0;while(Date.now()<=Z){let $=await I({name:"save",ttlMs:U0,path:B});if($)return $;let W=Z-Date.now();if(W<=0)break;await R1(Math.min(y1,W))}throw Error(`Timed out acquiring account store lock for ${B}; refusing to overwrite newer account data`)}function m0(B){let Z=Object.fromEntries(B.accounts.map(($)=>[$.id,T0($)]));return{version:1,main:D({quota:B.quota?.mainQuota,quotaCheckedAt:B.quota?.mainQuotaCheckedAt,quotaToken:B.quota?.mainQuotaToken,lastQuotaApiError:B.quota?.mainLastQuotaApiError,lastRefreshError:B.refresh?.mainLastRefreshError,refreshLeaseId:B.refresh?.mainRefreshLeaseId,refreshLeaseUntil:B.refresh?.mainRefreshLeaseUntil,refreshLeaseTokenHash:B.refresh?.mainRefreshLeaseTokenHash}),accounts:Z}}async function t4(B,Z=T()){let $=a(Z),W=await p(Z);try{let z=await p($);try{let X=await R(Z),G=await R($),K=(X.exists?x0(I0(X.value,G.value)):null)??r1(),Y=B(K)??K,J={...H(X.value)?X.value:{},...f0(Y)};return await A(Z,J),await A($,m0(Y)),Y}finally{await z.release()}}finally{await W.release()}}function r1(){return{version:1,main:{type:"opencode",provider:"openai"},accounts:[]}}function n1(B,Z){B.main=B.main??{};let $=typeof B.main.quotaCheckedAt==="number"?B.main.quotaCheckedAt:c(B.main.quota),W=typeof Z.quota?.mainQuotaCheckedAt==="number"?Z.quota.mainQuotaCheckedAt:c(Z.quota?.mainQuota);if($>W)return;B.main.quota=Z.quota?.mainQuota,B.main.quotaCheckedAt=Z.quota?.mainQuotaCheckedAt,B.main.quotaToken=Z.quota?.mainQuotaToken,B.main.lastQuotaApiError=Z.quota?.mainLastQuotaApiError}function c1(B,Z){B.main=B.main??{},B.main.lastRefreshError=Z.refresh?.mainLastRefreshError,B.main.refreshLeaseId=Z.refresh?.mainRefreshLeaseId,B.main.refreshLeaseUntil=Z.refresh?.mainRefreshLeaseUntil,B.main.refreshLeaseTokenHash=Z.refresh?.mainRefreshLeaseTokenHash}function K0(B){if(Array.isArray(B))return B.map(K0);if(!H(B))return B;return Object.fromEntries(Object.entries(B).filter(([,Z])=>Z!==void 0).map(([Z,$])=>[Z,K0($)]))}async function a1(B,Z=T(),$={mainQuota:!0,mainRefresh:!0,accounts:!0}){let W=a(Z),z=await p(W);try{let X=(await R(W)).value,G=H(X)?{...X,version:1}:{version:1};if($.mainQuota)n1(G,B);if($.mainRefresh)c1(G,B);if($.accounts){let K=$.accounts===!0?null:new Set($.accounts),Y=await p1(Z);G.accounts={...H(G.accounts)?G.accounts:{}};for(let j of B.accounts){if(K&&!K.has(j.id))continue;if(Y&&!Y.has(j.id))continue;G.accounts[j.id]=s1(G.accounts[j.id],T0(j))}if(K){for(let j of K)if(!B.accounts.some((J)=>J.id===j))delete G.accounts[j]}if(Y){for(let j of Object.keys(G.accounts))if(!Y.has(j))delete G.accounts[j]}}await A(W,K0(G))}finally{await z.release()}}function o1(B){return B?.fallbackOn?.length?B.fallbackOn:f1}function e4(B,Z){return o1(Z).includes(B)}function t1(B){let Z=B?.quota?.minimumRemaining||{};return{primary:Z.primary??Z["5h"]??M0.primary,secondary:Z.secondary??Z["1w"]??M0.secondary}}function Y0(B){return B?.quota?.enabled!==!1}function l(B){return B?.quota?.failClosedOnUnknownQuota??m1}function w0(B,Z,$=Date.now()){if(!Y0(Z))return!0;if(!B)return!l(Z);let W=t1(Z),z=l(Z);for(let X of["primary","secondary"]){let G=B[X];if(!G)continue;if(s(G,$)){if(z)return!1;continue}if(G.remainingPercent<W[X])return!1}return!0}function k0(B){return B?.killswitch?.enabled===!0}function C0(B){return{primary:B?.primary??B?.["5h"]??G0.primary,secondary:B?.secondary??B?.["1w"]??G0.secondary}}function h0(B,Z){if(!B?.killswitch)return G0;if(Z&&B.killswitch.accounts?.[Z])return C0(B.killswitch.accounts[Z]);return C0(B.killswitch.main)}function BB(B,Z,$,W=Date.now()){if(!k0(Z))return!0;if(!B)return!l(Z);let z=h0(Z,$),X=l(Z);for(let G of["primary","secondary"]){let K=B[G];if(!K)continue;if(s(K,W)){if(X)return!1;continue}if(K.remainingPercent<z[G])return!1}return!0}function ZB(B,Z,$,W){if(!k0(W))return 300;let z=[],X=[{accountId:void 0,quota:B},...Z];for(let{accountId:K,quota:Y}of X){if(!Y)continue;let j=h0(W,K),J=[],Q=!1;for(let y of["primary","secondary"]){let V=Y[y];if(!V||s(V,$))continue;if(V.remainingPercent>=j[y])continue;let F=V.resetsAt?Date.parse(V.resetsAt):NaN;if(!Number.isFinite(F)||F<=$){Q=!0;break}J.push(F)}if(Q||J.length===0)continue;z.push(Math.max(...J))}if(z.length===0)return 300;let G=Math.min(...z);return Math.max(1,Math.ceil((G-$)/1000))}function e1(B){return typeof B.version==="number"&&Array.isArray(B.accounts)}async function $B(B,Z=T()){let $=a(Z),W=await p(Z);try{let z=await p($);try{let X=await R(Z);if(X.exists&&H(X.value)){if(e1(X.value))return}if(!B)return;let G={version:1,main:{type:"opencode",provider:"openai"},accounts:[]};if(B.access){let j=i({id_token:"",access_token:B.access,refresh_token:B.refresh});if(j)G.mainAccountId=j}let Y={...X.exists&&H(X.value)?X.value:{},...f0(G)};await A(Z,Y),await A($,m0(G))}finally{await z.release()}}finally{await W.release()}}function B4(B){return B?.refresh?.enabled!==!1}function Z4(B){return(B?.refresh?.refreshBeforeExpiryMinutes??240)*60000}function $4(B){return Math.floor(Math.random()*(B+1))}function S(B,Z,$){return!B.access||!B.expires||B.expires-$<=Z4(Z)}function W4(B,Z){return Boolean(B.access&&typeof B.expires==="number"&&B.expires>Z)}function z4(B,Z){return Boolean(B.mainAccountId&&Z.accountId&&Z.accountId===B.mainAccountId)}function N(B,Z){let $=B.accounts.findIndex((W)=>W.id===Z.id);if($!==-1)B.accounts[$]=Z}function z0(B){return B instanceof Error?B.message:String(B)}function j0(B,Z,$){B.lastRefreshError=Q0({error:Z,now:$,refreshToken:B.refresh,previous:B.lastRefreshError})}function X0(B,Z,$){if(B.lastQuotaRefreshError=f({error:Z,now:$,previous:B.lastQuotaRefreshError}),Z?.isRefreshError===!0)j0(B,Z,$)}function X4(B){return`fallback-oauth-refresh-${q1("sha256").update(B).digest("base64url").slice(0,16)}`}function E0(B,Z){if(!B)return!1;if(!B.resetsAt)return!0;let $=Date.parse(B.resetsAt);return Number.isFinite($)?$>Z:!0}function G4(B,Z){if(!B)return!1;return E0(B.primary,Z)||E0(B.secondary,Z)}function K4(B,Z,$){if(!B)return!1;let W=Z?.quota?.checkIntervalMinutes??5,z=Math.max(1,W)*60000,X=Math.max(B.primary?.checkedAt??0,B.secondary?.checkedAt??0);return $-X<z}function S0(B,Z,$){return!K4(B.quota,Z,$)}function Y4(B,Z,$,W){return t($)&&w0(B.quota,Z,W)&&G4(B.quota,W)}function j4(B){let Z=B?.quota?.checkIntervalMinutes??5;return Math.max(1,Z)*60000}var J4=60000,H4=60000,Q4=600000,N4=1e4,P4=100;var WB=globalThis.setTimeout.bind(globalThis),zB=globalThis.clearTimeout.bind(globalThis);class V4{now;fetchImpl;configPath;refreshPromises=new Map;refreshTimer=null;quotaTimer=null;quotaManager;onFallbackStorageChanged;options;constructor(B={}){this.options=B,this.now=B.now??Date.now,this.fetchImpl=B.fetchImpl??fetch,this.configPath=B.configPath??T(),this.quotaManager=B.quotaManager??null,this.onFallbackStorageChanged=B.onFallbackStorageChanged}seedFallbackQuota(B,Z){if(!this.quotaManager)return;if(!B.quota)return;let $=Math.max(B.quota.primary?.checkedAt??0,B.quota.secondary?.checkedAt??0);if($<=0)return;let W=this.quotaManager.getFallback(B.id,B.access);if(W&&W.checkedAt>=$)return;this.quotaManager.setFallback(B.id,{quota:B.quota,refreshAfter:$+j4(Z),checkedAt:$},B.access)}async load(){return l1(this.configPath)}async save(B,Z){await a1(B,this.configPath,{accounts:Z??!0})}startBackgroundRefresh(){let B=async()=>{if(await this.refreshDueAccounts(),this.options.fetchQuotaFn)await this.refreshQuotaForDueAccounts()};if(B().catch(()=>{}),!this.refreshTimer){if(this.refreshTimer=setInterval(()=>{B().catch(()=>{})},J4+$4(H4)),"unref"in this.refreshTimer)this.refreshTimer.unref()}}stopBackgroundRefresh(){if(this.refreshTimer)clearInterval(this.refreshTimer);if(this.quotaTimer)clearInterval(this.quotaTimer);this.refreshTimer=null,this.quotaTimer=null}async getUsableFallbackAccounts(B){let Z=B!==void 0?B:await this.load();if(!Z)return[];let $=[],W=!1;for(let z of Z.accounts){if(z.enabled===!1||!b(z))continue;if(z4(Z,z))continue;let X=!1,G=z;try{if(S(G,Z,this.now())){let K=G.lastRefreshError;if(K&&U(K,G.refresh,this.now()))throw X=!0,Error(d(K,this.now()));try{G=await this.refreshAccount(G,Z),W=!0}catch(Y){if(w1(Y))continue;X=!0;let j=Z.accounts.find((J)=>J.id===z.id&&b(J));if(j&&!U(j.lastRefreshError,j.refresh,this.now()))j0(j,Y,this.now()),N(Z,j),W=!0;throw Y}}if(this.seedFallbackQuota(G,Z),this.accountPassesQuotaPolicy(this.quotaPolicyAccount(G),Z))$.push(G)}catch(K){let Y=W4(G,this.now());if(X){if(!Y)continue}else if(!Y)continue;if(Y4(G,Z,K,this.now()))E.debug("fallback quota using cached quota after refresh error",{pid:process.pid,accountId:G.id,error:z0(K)}),$.push(G);else if(!l(Z))$.push(G)}}if(W)await this.save(Z);return $}async markUsed(B){let Z=await this.load();if(!Z)return;let $=Z.accounts.find((W)=>W.id===B.id);if(!$)return;$.lastUsed=this.now(),await this.save(Z)}accountPassesQuotaPolicy(B,Z){return w0(B.quota,Z,this.now())}quotaPolicyAccount(B){if(!this.quotaManager)return B;let Z=this.quotaManager.getFallback(B.id,B.access)?.quota;return Z?{...B,quota:Z}:B}async refreshDueAccounts(){let B=await this.load();if(!B||!B4(B))return;let Z=!1;for(let $ of B.accounts){if($.enabled===!1||!b($))continue;if(!S($,B,this.now()))continue;if(U($.lastRefreshError,$.refresh,this.now()))continue;try{E.debug("fallback oauth background due",{pid:process.pid,accountId:$.id,expiresInMs:$.expires?$.expires-this.now():void 0}),await this.refreshAccount($,B),Z=!0}catch(W){E.warn("fallback oauth background failed",{pid:process.pid,accountId:$.id,error:z0(W)}),j0($,W,this.now()),N(B,$),Z=!0}}if(Z)await this.save(B)}async refreshQuotaForDueAccounts(){let B=await this.load();if(!B||!Y0(B))return;if(!this.options.fetchQuotaFn)return;let Z=!1;for(let $ of B.accounts){if($.enabled===!1||!b($))continue;let W=$;try{if(S(W,B,this.now())){if(U(W.lastRefreshError,W.refresh,this.now()))continue;W=await this.refreshAccount(W,B),Z=!0}if(x(W.lastQuotaRefreshError,this.now()))continue;if(this.seedFallbackQuota(W,B),!(this.quotaManager?this.quotaManager.isFallbackStale(W.id,W.access):S0(W,B,this.now())))continue;await this.refreshAccountQuota(W,B),Z=!0}catch(z){X0($,z,this.now()),N(B,$),Z=!0}}if(Z)await this.save(B),this.onFallbackStorageChanged?.()}async refreshQuotaForAllAccounts(B={}){let Z=await this.load(),$=[];if(!Z||!Y0(Z))return{storage:Z,errors:$};if(!this.options.fetchQuotaFn)return{storage:Z,errors:$};let W=B.force??!1,z=!1;for(let X of Z.accounts){if(X.enabled===!1||!b(X))continue;let G=X;try{if(S(G,Z,this.now())){let K=G.lastRefreshError;if(K&&U(K,G.refresh,this.now()))throw Error(d(K,this.now()));G=await this.refreshAccount(G,Z),z=!0}if(!W&&!S0(G,Z,this.now())){if(G.lastQuotaRefreshError)G.lastQuotaRefreshError=void 0,N(Z,G),z=!0;continue}await this.refreshAccountQuota(G,Z),z=!0}catch(K){X0(X,K,this.now()),N(Z,X),z=!0,$.push({accountId:X.id,message:z0(K)})}}if(z)await this.save(Z);return{storage:Z,errors:$}}async refreshAccount(B,Z,$={}){let W=this.refreshPromises.get(B.id);if(W){let G=await W;return N(Z,G),G}let z=this.refreshAccountNow(B,Z,$).finally(()=>{this.refreshPromises.delete(B.id)});this.refreshPromises.set(B.id,z);let X=await z;return N(Z,X),X}async waitForConcurrentFallbackRefresh(B,Z,$,W){let z=Date.now()+N4;while(Date.now()<z){await new Promise((j)=>setTimeout(j,P4));let X=await this.load(),G=X?.accounts.find((j)=>j.id===B.id&&b(j));if(!G)continue;if((G.access!==$.access||G.refresh!==$.refresh||(G.expires??0)>($.expires??0)+60000)&&(W.force||!S(G,X,this.now())))return N(Z,G),E.debug("fallback oauth joined concurrent refresh",{pid:process.pid,accountId:G.id,expiresInMs:G.expires?G.expires-this.now():void 0}),G;let Y=G.lastRefreshError;if(Y&&U(Y,G.refresh,this.now()))throw N(Z,G),Error(d(Y,this.now()))}return null}async refreshAccountNow(B,Z,$){let W=await this.load(),z=W?.accounts.find((K)=>K.id===B.id&&b(K));if(z&&!$.force&&!S(z,W,this.now()))return N(Z,z),z;let X=z??B,G=await I({name:X4(X.id),ttlMs:Q4,path:this.configPath,now:this.now,renew:!0});if(!G){E.debug("fallback oauth refresh skipped file lock",{pid:process.pid,accountId:X.id});let K=await this.waitForConcurrentFallbackRefresh(B,Z,X,$);if(K)return K;throw Error("Fallback OAuth refresh is already in progress")}try{if(W=await this.load(),z=W?.accounts.find((J)=>J.id===B.id&&b(J)),z&&!$.force&&!S(z,W,this.now()))return N(Z,z),z;if(!z)throw new n(B.id);X=z;let K=this.options.refreshFn??(async()=>{throw Error("No refreshFn injected into FallbackAccountManager")});E.debug("fallback oauth refresh request start",{pid:process.pid,accountId:X.id,force:$.force===!0,expiresInMs:X.expires?X.expires-this.now():void 0});let Y=await K({refreshToken:X.refresh,fetchImpl:this.fetchImpl,now:this.now});if(X.access=Y.access,X.refresh=Y.refresh,X.expires=Y.expires,X.lastRefreshedAt=Y.expires-Y.expiresIn*1000,X.lastRefreshError=void 0,N(Z,X),await this.save(Z),!(await this.load())?.accounts.some((J)=>J.id===B.id))throw new n(B.id);return E.debug("fallback oauth refresh succeeded",{pid:process.pid,accountId:X.id,expiresInMs:X.expires?X.expires-this.now():void 0}),X}finally{await G.release()}}async refreshAccountQuota(B,Z){let $=B;if(!$.access)throw Error(`Fallback account ${B.id} has no access token`);if(!this.options.fetchQuotaFn)throw Error("No fetchQuotaFn injected — wham/usage supplement is disabled");let W=this.options.fetchQuotaFn??(async()=>{throw Error("No fetchQuotaFn injected — wham/usage supplement is disabled")}),z=(X)=>this.quotaManager?this.quotaManager.refreshFallback($.id,X):W({accessToken:X,fetchImpl:this.fetchImpl,now:this.now});try{if(!$.access)throw Error(`Fallback account ${B.id} has no access token`);let X=await z($.access);$.quota=X,$.lastQuotaRefreshError=void 0,N(Z,$),await this.save(Z)}catch(X){throw X0(B,X,this.now()),N(Z,B),X}}}
89
+ export{H0 as h,Q0 as i,U as j,d as k,L0 as l,O0 as m,o0 as n,P0 as o,V0 as p,i as q,B0 as r,e0 as s,C as t,W1 as u,z1 as v,X1 as w,G1 as x,M4 as y,_4 as z,E4 as A,S4 as B,T4 as C,O as D,T as E,b as F,a4 as G,G0 as H,l1 as I,t4 as J,e4 as K,k0 as L,BB as M,ZB as N,$B as O,V4 as P};
@@ -0,0 +1,2 @@
1
+ import{ka as U,la as F}from"./index-1r02s323.js";import{randomUUID as E}from"node:crypto";import{mkdir as R,readFile as g,rename as f,rm as m,writeFile as S}from"node:fs/promises";import{tmpdir as c}from"node:os";import{dirname as y,join as v}from"node:path";var _=["primary","secondary"],k={primary:300,secondary:10080};function N(H){return Number.isInteger(H)?String(H):String(Math.round(H*10)/10)}function p(H,J){let Z=H!==void 0&&Number.isFinite(H)&&H>0?H:k[J];if(Z<60)return`${N(Z)}m`;if(Z<1440)return`${N(Z/60)}h`;return`${N(Z/1440)}d`}function A(H){if(!H)return[];let J=[];for(let Z of _){let $=H[Z];if(!$)continue;let x=$.windowMinutes,Q=x!==void 0&&Number.isFinite(x)&&x>0?x:k[Z];J.push({key:Z,label:p(Q,Z),window:$,windowMs:Q*60000})}return J}var w=U("sidebar"),u="OPENCODE_OPENAI_AUTH_SIDEBAR_STATE_FILE",d=v(c(),"opencode-openai-auth"),l=v(d,"sidebar-state.json");function o(H){return typeof H==="number"&&Number.isFinite(H)&&H>=0?H:void 0}function W(H){let J=o(H);return J!==void 0?{resetCredits:J}:{}}function s(H){if(H===null||typeof H!=="object"||Array.isArray(H))return;let J={};for(let[Z,$]of Object.entries(H)){if($===null||typeof $!=="object"||Array.isArray($))continue;let x=$;if(typeof x.activeId!=="string"||typeof x.route!=="string"||typeof x.updatedAt!=="number"||!Number.isFinite(x.updatedAt))continue;J[Z]={activeId:x.activeId,route:x.route,updatedAt:x.updatedAt}}return Object.keys(J).length>0?J:void 0}function z(){return process.env[u]||l}var K={main:{quota:null,killed:!1},fallbacks:[],activeId:void 0,route:"main",lastUpdated:0};function M(H){if(H===null||typeof H!=="object"||Array.isArray(H))return K;let J=H,Z=J.main,$;if(Z!==null&&typeof Z==="object"&&!Array.isArray(Z)){let j=Z;$={quota:"quota"in j?j.quota:null,killed:typeof j.killed==="boolean"?j.killed:!1,...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}:{},...W(j.resetCredits)}}else $={quota:null,killed:!1};let x=J.fallbacks,Q=Array.isArray(x)?x.filter((j)=>j!==null&&typeof j==="object"&&!Array.isArray(j)&&typeof j.id==="string").map((j)=>({id:j.id,label:typeof j.label==="string"?j.label:void 0,quota:"quota"in j?j.quota:null,killed:typeof j.killed==="boolean"?j.killed:!1,enabled:typeof j.enabled==="boolean"?j.enabled:!0,...W(j.resetCredits)})):[],Y=typeof J.activeId==="string"?J.activeId:void 0,V=typeof J.route==="string"?J.route:K.route,X=typeof J.lastUpdated==="number"?J.lastUpdated:0,O=typeof J.planType==="string"?J.planType:void 0,G=typeof J.credits==="number"?J.credits:void 0,q=s(J.activeRouting);return{main:$,fallbacks:Q,activeId:Y,route:V,lastUpdated:X,...q!==void 0?{activeRouting:q}:{},...O!==void 0?{planType:O}:{},...G!==void 0?{credits:G}:{}}}async function XH(){try{let H=await g(z(),"utf8");return M(JSON.parse(H))}catch{return K}}var r=3600000,D=128;function I(H,J,Z=Date.now()){if(!(H.updatedAt>=Z-r&&H.updatedAt<=Z))return!1;return H.activeId==="main"||J.some((x)=>x.enabled!==!1&&x.id===H.activeId)}function KH(H,J,Z=Date.now()){if(!J)return{activeId:H.activeId??"main",route:H.route};let $=J?H.activeRouting?.[J]:void 0;if($&&I($,H.fallbacks,Z))return{activeId:$.activeId,route:$.route};let x=H.fallbacks.find((Q)=>Q.enabled&&!Q.killed);return{activeId:H.route==="fallback-first"&&x?x.id:"main",route:H.route}}function T(H,J,Z=Date.now(),$){if(!H)return;let x=Object.entries(H).filter(([Y,V])=>Y!==$&&I(V,J,Z)),Q=x.length<=D?x:x.sort((Y,V)=>V[1].updatedAt-Y[1].updatedAt).slice(0,D);return Q.length>0?Object.fromEntries(Q):void 0}var P=Promise.resolve(),n=3,i=1e4,a=15000;function B(H){let J=P.then(H);return P=J.catch(()=>{}),J}function zH(H,J=z()){return B(()=>L(H,J))}async function t(H){try{return b(await h(H))}catch{return K}}async function h(H){try{return await g(H,"utf8")}catch(J){if(J.code==="ENOENT")return"";throw J}}function b(H){if(H==="")return K;try{return M(JSON.parse(H))}catch{return K}}async function e(H){await R(y(H),{recursive:!0});let J=Date.now()+a;while(Date.now()<=J){let Z=await F({name:"sidebar-write",path:H,ttlMs:i,renew:!0});if(Z)return Z;await new Promise(($)=>setTimeout($,10))}throw Error("Timed out waiting for the sidebar state write lock")}async function C(H,J,Z){let $=await e(H);try{for(let Q=0;Q<n;Q+=1){let Y=await h(H),V=J(b(Y));if(Q===0)await Z?.beforeRecheck?.();if(await h(H)!==Y)continue;await L(V,H);return}let x=await t(H);await L(J(x),H)}finally{await $.release()}}function GH(H,J=z(),Z){return B(async()=>{await C(J,($)=>({...$,...H,activeId:$.activeId,activeRouting:$.activeRouting,lastUpdated:Math.max(Date.now(),$.lastUpdated+1)}),Z)})}function BH(H,J,Z=z(),$){return B(async()=>{await C(Z,(x)=>{let Q=T({...x.activeRouting,[H.sessionId]:{activeId:H.activeId,route:H.route,updatedAt:H.updatedAt}},J,Date.now());return{...x,activeId:H.activeId,route:H.route,activeRouting:Q,lastUpdated:Math.max(Date.now(),x.lastUpdated+1)}},$)})}function OH(H,J=z()){return B(async()=>{await C(J,(Z)=>({...Z,activeId:H.activeId,route:H.route,lastUpdated:Math.max(Date.now(),Z.lastUpdated+1)}))})}function qH(H,J,Z=z(),$){return B(async()=>{await C(Z,(x)=>{let Q=Date.now(),Y=T(x.activeRouting,J,Q,H);return{...x,activeRouting:Y,lastUpdated:Math.max(Date.now(),x.lastUpdated+1)}},$)})}async function L(H,J){let Z=`${J}.${E()}.tmp`;try{await R(y(J),{recursive:!0}),await S(Z,JSON.stringify(H),"utf8"),await f(Z,J)}catch($){throw await m(Z,{force:!0}).catch(()=>{}),w.warn("sidebar write failed",{pid:process.pid,error:$ instanceof Error?$.message:String($)}),$}}function CH(){return P}function NH(H){let J=H.activeId;if(J&&J!=="main"){let Z=H.fallbacks.find(($)=>$.enabled&&$.id===J);if(Z)return{id:Z.id,name:Z.label??Z.id,quota:Z.quota,killed:Z.killed}}return{id:"main",name:"main",quota:H.main.quota,killed:H.main.killed}}function PH(H){let J=H?.primary?.usedPercent??null,Z=H?.secondary?.usedPercent??null,$=A(H);return{primaryUsedPercent:J,secondaryUsedPercent:Z,text:$.length===0?null:$.map(({label:x,window:Q})=>`${x}: ${Math.round(Q.usedPercent)}%`).join(" ")}}var HH=300000,JH=0.01,ZH=1;function hH(H,J,Z){if(!H.resetsAt)return null;let $=new Date(H.resetsAt).getTime();if(!Number.isFinite($))return null;let x=$-J,Q=Z-x;if(Q<HH)return null;if(Q<J*JH)return null;if(Q>=J)return null;let Y=H.usedPercent,V=Math.min(Math.max(Q/J*100,0),100),X=Y-V,O=Math.abs(X)<ZH?"on-pace":X>0?"deficit":"reserve",G=null;if(Y>0){let q=Q*100/Y,j=x+q;if(j<$)G=new Date(j).toISOString()}return{pacePercent:V,deltaPercent:X,state:O,runsOutAt:G}}
2
+ export{p as Q,A as R,z as S,K as T,M as U,XH as V,r as W,D as X,I as Y,KH as Z,T as _,zH as $,GH as aa,BH as ba,OH as ca,qH as da,CH as ea,NH as fa,PH as ga,hH as ha};
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import{d as S4,e as F0,f as LW}from"./index-2ng03cby.js";import{A as m1,B as HN,C as $2,D as U2,F as M4,G as z2,H as c6,I as m$,J as L$,K as P0,L as VN,M as LN,N as J2,O as X2,P as j2,h as cW,i as mW,j as uW,k as iW,l as lW,m as nW,n as rW,o as A0,p as E0,q as _0,s as pW,t as dW,u as oW,v as tW,w as aW,x as sW,y as EN,z as bN}from"./index-dzg88nw2.js";import{S as N2,aa as O2,ba as W2,ca as G2,da as Q2}from"./index-cz1bkmjz.js";import{ia as d1,ja as hN,ka as _$,la as eW}from"./index-1r02s323.js";import{ma as XO}from"./index-1anzb8jh.js";import{pa as Y2}from"./index-b6kp9ydc.js";import{sa as N6}from"./index-6y6ss1kc.js";import{mkdirSync as BD,readFileSync as DD,renameSync as KD,statSync as qD,writeFileSync as vD}from"node:fs";import QN from"node:os";import{join as _D}from"node:path";import{readFileSync as D2}from"node:fs";import{homedir as K2,tmpdir as q2}from"node:os";import{join as r1}from"node:path";var v2="https://chatgpt.com/backend-api/codex/responses",_2="openai-auth.json",X6={noWebSearch:"CORTEXKIT_OPENAI_AUTH_NO_WEB_SEARCH",webSockets:"CORTEXKIT_OPENAI_AUTH_WEBSOCKETS",rawWebSocket:"CORTEXKIT_OPENAI_AUTH_RAW_WS",responsesLite:"CORTEXKIT_OPENAI_AUTH_RESPONSES_LITE",dump:"CORTEXKIT_OPENAI_AUTH_DUMP",dumpDir:"OPENCODE_OPENAI_AUTH_DUMP_DIR",codexApiEndpoint:"CORTEXKIT_OPENAI_AUTH_CODEX_ENDPOINT",configFile:"OPENCODE_OPENAI_AUTH_FILE",stateFile:"OPENCODE_OPENAI_AUTH_STATE_FILE",configDir:"OPENCODE_CONFIG_DIR"};function p1(){let $=process.env[X6.configDir]?.trim();if($)return $;return r1(process.env.XDG_CONFIG_HOME||r1(K2(),".config"),"opencode")}function K$(){return process.env[X6.configFile]?.trim()||r1(p1(),_2)}function F2(){try{let $=JSON.parse(D2(K$(),"utf8"));return $!=null&&typeof $==="object"&&!Array.isArray($)?$:{}}catch{return{}}}function PN($){let U=process.env[$];if(U===void 0)return;let J=U.trim().toLowerCase();if(J==="1"||J==="true"||J==="yes"||J==="on")return!0;if(J===""||J==="0"||J==="false"||J==="no"||J==="off")return!1;return}function n1($,U,J){let X=PN($);if(X!==void 0)return X;if(typeof U==="boolean")return U;return J}function P2(){let $=F2(),U=PN(X6.noWebSearch),J=U!==void 0?!U:typeof $.webSearch==="boolean"?$.webSearch:!0,X;if($.dump!==void 0&&$.dump!==null){if(typeof $.dump==="object")X=$.dump.enabled;else if(typeof $.dump==="boolean")X=$.dump}return{webSearch:J,webSockets:n1(X6.webSockets,$.webSockets,!1),rawWebSocket:n1(X6.rawWebSocket,$.rawWebSocket,!1),responsesLite:n1(X6.responsesLite,$.responsesLite,!1),dump:n1(X6.dump,X,!1),dumpDir:process.env[X6.dumpDir]?.trim()||(typeof $.dumpDir==="string"&&$.dumpDir.trim()?$.dumpDir.trim():r1(q2(),"opencode-openai-auth-dumps")),codexApiEndpoint:process.env[X6.codexApiEndpoint]?.trim()||(typeof $.codexApiEndpoint==="string"&&$.codexApiEndpoint.trim()?$.codexApiEndpoint.trim():v2)}}var I0;function k$(){if(!I0)I0=P2();return I0}var S0="openai-quota",k0="openai-account",C0="openai-routing",Z0="openai-killswitch",T0="openai-dump",g0="openai-logging",x0="openai-cachekeep",MN=["openai-quota","openai-account","openai-routing","openai-killswitch","openai-dump","openai-logging","openai-cachekeep"],q$=_$("commands");function AN($){return $==="fallback-first"?"Try usable fallback accounts before the main account.":"Try the main account first. Use fallback accounts only when required."}async function A2($){let U=await $.refreshAllQuota?.(),J=$.quotaManager.getMain(),X=["## OpenAI Quota",""];if(J?.quota){let Y=J.quota;X.push("### Main account");for(let N of["primary","secondary"]){let W=Y[N];if(W){let G=Math.round(W.usedPercent),Q="█".repeat(Math.max(0,Math.min(Math.round(G/10),10)))+"░".repeat(Math.max(0,10-Math.min(Math.round(G/10),10)));X.push(`- ${N}: ${Q} ${G}% used (${Math.round(W.remainingPercent)}% remaining)`)}}if(Y.resetCreditsAvailable!==void 0)X.push(`- resets: ${Y.resetCreditsAvailable}`)}else X.push("No main quota snapshot available. Send a request first.");let j=[...$.quotaManager.getAllFallbacks().entries()].filter(([,Y])=>Y);if(j.length>0){X.push(""),X.push("### Fallback accounts");for(let[Y,N]of j){if(!N?.quota)continue;X.push(`**${Y}**`);for(let W of["primary","secondary"]){let G=N.quota[W];if(G){let Q=Math.round(G.usedPercent);X.push(` - ${W}: ${Q}% used (${Math.round(G.remainingPercent)}% remaining)`)}}if(N.quota.resetCreditsAvailable!==void 0)X.push(` - resets: ${N.quota.resetCreditsAvailable}`)}}if(U?.length){let Y=U.filter((N)=>!N.ok);if(Y.length>0){X.push("");for(let N of Y)X.push(`⚠ ${N.account}: could not fetch (${N.error??"unknown error"})`)}}return{command:"openai-quota",text:X.join(`
1
+ import{d as S4,e as F0,f as LW}from"./index-2ng03cby.js";import{A as m1,B as HN,C as $2,D as U2,F as M4,G as z2,H as c6,I as m$,J as L$,K as P0,L as VN,M as LN,N as J2,O as X2,P as j2,h as cW,i as mW,j as uW,k as iW,l as lW,m as nW,n as rW,o as A0,p as E0,q as _0,s as pW,t as dW,u as oW,v as tW,w as aW,x as sW,y as EN,z as bN}from"./index-0gccjqxr.js";import{S as N2,aa as O2,ba as W2,ca as G2,da as Q2}from"./index-fbfpefx6.js";import{ia as d1,ja as hN,ka as _$,la as eW}from"./index-1r02s323.js";import{ma as XO}from"./index-1anzb8jh.js";import{pa as Y2}from"./index-b6kp9ydc.js";import{sa as N6}from"./index-6y6ss1kc.js";import{mkdirSync as BD,readFileSync as DD,renameSync as KD,statSync as qD,writeFileSync as vD}from"node:fs";import QN from"node:os";import{join as _D}from"node:path";import{readFileSync as D2}from"node:fs";import{homedir as K2,tmpdir as q2}from"node:os";import{join as r1}from"node:path";var v2="https://chatgpt.com/backend-api/codex/responses",_2="openai-auth.json",X6={noWebSearch:"CORTEXKIT_OPENAI_AUTH_NO_WEB_SEARCH",webSockets:"CORTEXKIT_OPENAI_AUTH_WEBSOCKETS",rawWebSocket:"CORTEXKIT_OPENAI_AUTH_RAW_WS",responsesLite:"CORTEXKIT_OPENAI_AUTH_RESPONSES_LITE",dump:"CORTEXKIT_OPENAI_AUTH_DUMP",dumpDir:"OPENCODE_OPENAI_AUTH_DUMP_DIR",codexApiEndpoint:"CORTEXKIT_OPENAI_AUTH_CODEX_ENDPOINT",configFile:"OPENCODE_OPENAI_AUTH_FILE",stateFile:"OPENCODE_OPENAI_AUTH_STATE_FILE",configDir:"OPENCODE_CONFIG_DIR"};function p1(){let $=process.env[X6.configDir]?.trim();if($)return $;return r1(process.env.XDG_CONFIG_HOME||r1(K2(),".config"),"opencode")}function K$(){return process.env[X6.configFile]?.trim()||r1(p1(),_2)}function F2(){try{let $=JSON.parse(D2(K$(),"utf8"));return $!=null&&typeof $==="object"&&!Array.isArray($)?$:{}}catch{return{}}}function PN($){let U=process.env[$];if(U===void 0)return;let J=U.trim().toLowerCase();if(J==="1"||J==="true"||J==="yes"||J==="on")return!0;if(J===""||J==="0"||J==="false"||J==="no"||J==="off")return!1;return}function n1($,U,J){let X=PN($);if(X!==void 0)return X;if(typeof U==="boolean")return U;return J}function P2(){let $=F2(),U=PN(X6.noWebSearch),J=U!==void 0?!U:typeof $.webSearch==="boolean"?$.webSearch:!0,X;if($.dump!==void 0&&$.dump!==null){if(typeof $.dump==="object")X=$.dump.enabled;else if(typeof $.dump==="boolean")X=$.dump}return{webSearch:J,webSockets:n1(X6.webSockets,$.webSockets,!1),rawWebSocket:n1(X6.rawWebSocket,$.rawWebSocket,!1),responsesLite:n1(X6.responsesLite,$.responsesLite,!1),dump:n1(X6.dump,X,!1),dumpDir:process.env[X6.dumpDir]?.trim()||(typeof $.dumpDir==="string"&&$.dumpDir.trim()?$.dumpDir.trim():r1(q2(),"opencode-openai-auth-dumps")),codexApiEndpoint:process.env[X6.codexApiEndpoint]?.trim()||(typeof $.codexApiEndpoint==="string"&&$.codexApiEndpoint.trim()?$.codexApiEndpoint.trim():v2)}}var I0;function k$(){if(!I0)I0=P2();return I0}var S0="openai-quota",k0="openai-account",C0="openai-routing",Z0="openai-killswitch",T0="openai-dump",g0="openai-logging",x0="openai-cachekeep",MN=["openai-quota","openai-account","openai-routing","openai-killswitch","openai-dump","openai-logging","openai-cachekeep"],q$=_$("commands");function AN($){return $==="fallback-first"?"Try usable fallback accounts before the main account.":"Try the main account first. Use fallback accounts only when required."}async function A2($){let U=await $.refreshAllQuota?.(),J=$.quotaManager.getMain(),X=["## OpenAI Quota",""];if(J?.quota){let Y=J.quota;X.push("### Main account");for(let N of["primary","secondary"]){let W=Y[N];if(W){let G=Math.round(W.usedPercent),Q="█".repeat(Math.max(0,Math.min(Math.round(G/10),10)))+"░".repeat(Math.max(0,10-Math.min(Math.round(G/10),10)));X.push(`- ${N}: ${Q} ${G}% used (${Math.round(W.remainingPercent)}% remaining)`)}}if(Y.resetCreditsAvailable!==void 0)X.push(`- resets: ${Y.resetCreditsAvailable}`)}else X.push("No main quota snapshot available. Send a request first.");let j=[...$.quotaManager.getAllFallbacks().entries()].filter(([,Y])=>Y);if(j.length>0){X.push(""),X.push("### Fallback accounts");for(let[Y,N]of j){if(!N?.quota)continue;X.push(`**${Y}**`);for(let W of["primary","secondary"]){let G=N.quota[W];if(G){let Q=Math.round(G.usedPercent);X.push(` - ${W}: ${Q}% used (${Math.round(G.remainingPercent)}% remaining)`)}}if(N.quota.resetCreditsAvailable!==void 0)X.push(` - resets: ${N.quota.resetCreditsAvailable}`)}}if(U?.length){let Y=U.filter((N)=>!N.ok);if(Y.length>0){X.push("");for(let N of Y)X.push(`⚠ ${N.account}: could not fetch (${N.error??"unknown error"})`)}}return{command:"openai-quota",text:X.join(`
2
2
  `),knobs:{}}}async function E2($,U){let J=$.trim().split(/\s+/).filter(Boolean),X=await U.loadAccounts(U.accountStoragePath)??{version:1,accounts:[]},z=X.accounts??[];if(J.length===0){let j=["## OpenAI Accounts",""];if(z.length===0)j.push("No accounts configured. Use `/login openai` to add your main account, or `/openai-account add` to add a fallback account.");else{let Y=X.routing?.mode??"main-first";j.push(`Routing: \`${Y}\` (set with \`/openai-routing\`).`),j.push("");for(let N of z){let W=N.type??"oauth";j.push(`- \`${N.id}\` (${W})`)}}return j.push(""),j.push("Commands: `/openai-account add [label]` | `/openai-account remove <id>`"),{command:"openai-account",text:j.join(`
3
3
  `),knobs:{accounts:z}}}if(J[0]==="remove"&&J[1]){let j=J[1],Y=!1,N=await L$((W)=>{let G=W.accounts.findIndex((Q)=>Q.id===j);if(G===-1)return W;return Y=!0,W.accounts.splice(G,1),W},U.accountStoragePath);if(!Y)return{command:"openai-account",text:`## Account Not Found
4
4
 
@@ -1 +1 @@
1
- import{$ as l,Q as a,R as b,S as c,T as d,U as e,V as f,W as g,X as h,Y as i,Z as j,_ as k,aa as m,ba as n,ca as o,da as p,ea as q,fa as r,ga as s,ha as t}from"./index-cz1bkmjz.js";import"./index-1r02s323.js";import"./index-6y6ss1kc.js";export{n as upsertSidebarActiveRouting,l as setSidebarState,m as setSidebarMachineState,o as setSidebarLegacyRouting,j as resolveSessionSidebarRouting,r as resolveActiveAccount,p as removeSidebarActiveRouting,k as pruneActiveRouting,e as normalizeSidebarState,i as isUsableRoutingEntry,c as getSidebarStateFile,f as getSidebarState,b as getPresentQuotaWindows,s as getCollapsedQuotaSummary,a as formatWindowLabel,q as drainSidebarWrites,t as computeQuotaPacing,d as DEFAULT_SIDEBAR_STATE,h as ACTIVE_ROUTING_MAX_ENTRIES,g as ACTIVE_ROUTING_MAX_AGE_MS};
1
+ import{$ as l,Q as a,R as b,S as c,T as d,U as e,V as f,W as g,X as h,Y as i,Z as j,_ as k,aa as m,ba as n,ca as o,da as p,ea as q,fa as r,ga as s,ha as t}from"./index-fbfpefx6.js";import"./index-1r02s323.js";import"./index-6y6ss1kc.js";export{n as upsertSidebarActiveRouting,l as setSidebarState,m as setSidebarMachineState,o as setSidebarLegacyRouting,j as resolveSessionSidebarRouting,r as resolveActiveAccount,p as removeSidebarActiveRouting,k as pruneActiveRouting,e as normalizeSidebarState,i as isUsableRoutingEntry,c as getSidebarStateFile,f as getSidebarState,b as getPresentQuotaWindows,s as getCollapsedQuotaSummary,a as formatWindowLabel,q as drainSidebarWrites,t as computeQuotaPacing,d as DEFAULT_SIDEBAR_STATE,h as ACTIVE_ROUTING_MAX_ENTRIES,g as ACTIVE_ROUTING_MAX_AGE_MS};
package/dist/version.d.ts CHANGED
@@ -1 +1 @@
1
- export declare const PackageVersion = "0.4.0";
1
+ export declare const PackageVersion = "0.4.1";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cortexkit/opencode-openai-auth",
3
- "version": "0.4.0",
3
+ "version": "0.4.1",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "repository": {
@@ -419,6 +419,7 @@ function parseSidebarState(raw: string): SidebarState {
419
419
  }
420
420
 
421
421
  async function acquireSidebarWriteLock(file: string) {
422
+ await mkdir(dirname(file), { recursive: true })
422
423
  const deadline = Date.now() + SIDEBAR_WRITE_LOCK_WAIT_MS
423
424
  while (Date.now() <= deadline) {
424
425
  const lock = await acquireRefreshFileLock({
@@ -419,6 +419,7 @@ function parseSidebarState(raw: string): SidebarState {
419
419
  }
420
420
 
421
421
  async function acquireSidebarWriteLock(file: string) {
422
+ await mkdir(dirname(file), { recursive: true })
422
423
  const deadline = Date.now() + SIDEBAR_WRITE_LOCK_WAIT_MS
423
424
  while (Date.now() <= deadline) {
424
425
  const lock = await acquireRefreshFileLock({
@@ -1,2 +0,0 @@
1
- import{ka as U,la as F}from"./index-1r02s323.js";import{randomUUID as p}from"node:crypto";import{mkdir as A,readFile as R,rename as E,rm as f,writeFile as m}from"node:fs/promises";import{tmpdir as S}from"node:os";import{dirname as c,join as g}from"node:path";var T=["primary","secondary"],k={primary:300,secondary:10080};function N(H){return Number.isInteger(H)?String(H):String(Math.round(H*10)/10)}function b(H,J){let Z=H!==void 0&&Number.isFinite(H)&&H>0?H:k[J];if(Z<60)return`${N(Z)}m`;if(Z<1440)return`${N(Z/60)}h`;return`${N(Z/1440)}d`}function _(H){if(!H)return[];let J=[];for(let Z of T){let $=H[Z];if(!$)continue;let x=$.windowMinutes,Q=x!==void 0&&Number.isFinite(x)&&x>0?x:k[Z];J.push({key:Z,label:b(Q,Z),window:$,windowMs:Q*60000})}return J}var w=U("sidebar"),u="OPENCODE_OPENAI_AUTH_SIDEBAR_STATE_FILE",d=g(S(),"opencode-openai-auth"),l=g(d,"sidebar-state.json");function o(H){return typeof H==="number"&&Number.isFinite(H)&&H>=0?H:void 0}function W(H){let J=o(H);return J!==void 0?{resetCredits:J}:{}}function s(H){if(H===null||typeof H!=="object"||Array.isArray(H))return;let J={};for(let[Z,$]of Object.entries(H)){if($===null||typeof $!=="object"||Array.isArray($))continue;let x=$;if(typeof x.activeId!=="string"||typeof x.route!=="string"||typeof x.updatedAt!=="number"||!Number.isFinite(x.updatedAt))continue;J[Z]={activeId:x.activeId,route:x.route,updatedAt:x.updatedAt}}return Object.keys(J).length>0?J:void 0}function z(){return process.env[u]||l}var K={main:{quota:null,killed:!1},fallbacks:[],activeId:void 0,route:"main",lastUpdated:0};function y(H){if(H===null||typeof H!=="object"||Array.isArray(H))return K;let J=H,Z=J.main,$;if(Z!==null&&typeof Z==="object"&&!Array.isArray(Z)){let j=Z;$={quota:"quota"in j?j.quota:null,killed:typeof j.killed==="boolean"?j.killed:!1,...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}:{},...W(j.resetCredits)}}else $={quota:null,killed:!1};let x=J.fallbacks,Q=Array.isArray(x)?x.filter((j)=>j!==null&&typeof j==="object"&&!Array.isArray(j)&&typeof j.id==="string").map((j)=>({id:j.id,label:typeof j.label==="string"?j.label:void 0,quota:"quota"in j?j.quota:null,killed:typeof j.killed==="boolean"?j.killed:!1,enabled:typeof j.enabled==="boolean"?j.enabled:!0,...W(j.resetCredits)})):[],Y=typeof J.activeId==="string"?J.activeId:void 0,V=typeof J.route==="string"?J.route:K.route,X=typeof J.lastUpdated==="number"?J.lastUpdated:0,O=typeof J.planType==="string"?J.planType:void 0,G=typeof J.credits==="number"?J.credits:void 0,q=s(J.activeRouting);return{main:$,fallbacks:Q,activeId:Y,route:V,lastUpdated:X,...q!==void 0?{activeRouting:q}:{},...O!==void 0?{planType:O}:{},...G!==void 0?{credits:G}:{}}}async function XH(){try{let H=await R(z(),"utf8");return y(JSON.parse(H))}catch{return K}}var r=3600000,D=128;function v(H,J,Z=Date.now()){if(!(H.updatedAt>=Z-r&&H.updatedAt<=Z))return!1;return H.activeId==="main"||J.some((x)=>x.enabled!==!1&&x.id===H.activeId)}function KH(H,J,Z=Date.now()){if(!J)return{activeId:H.activeId??"main",route:H.route};let $=J?H.activeRouting?.[J]:void 0;if($&&v($,H.fallbacks,Z))return{activeId:$.activeId,route:$.route};let x=H.fallbacks.find((Q)=>Q.enabled&&!Q.killed);return{activeId:H.route==="fallback-first"&&x?x.id:"main",route:H.route}}function M(H,J,Z=Date.now(),$){if(!H)return;let x=Object.entries(H).filter(([Y,V])=>Y!==$&&v(V,J,Z)),Q=x.length<=D?x:x.sort((Y,V)=>V[1].updatedAt-Y[1].updatedAt).slice(0,D);return Q.length>0?Object.fromEntries(Q):void 0}var P=Promise.resolve(),n=3,i=1e4,a=15000;function B(H){let J=P.then(H);return P=J.catch(()=>{}),J}function zH(H,J=z()){return B(()=>L(H,J))}async function t(H){try{return I(await h(H))}catch{return K}}async function h(H){try{return await R(H,"utf8")}catch(J){if(J.code==="ENOENT")return"";throw J}}function I(H){if(H==="")return K;try{return y(JSON.parse(H))}catch{return K}}async function e(H){let J=Date.now()+a;while(Date.now()<=J){let Z=await F({name:"sidebar-write",path:H,ttlMs:i,renew:!0});if(Z)return Z;await new Promise(($)=>setTimeout($,10))}throw Error("Timed out waiting for the sidebar state write lock")}async function C(H,J,Z){let $=await e(H);try{for(let Q=0;Q<n;Q+=1){let Y=await h(H),V=J(I(Y));if(Q===0)await Z?.beforeRecheck?.();if(await h(H)!==Y)continue;await L(V,H);return}let x=await t(H);await L(J(x),H)}finally{await $.release()}}function GH(H,J=z(),Z){return B(async()=>{await C(J,($)=>({...$,...H,activeId:$.activeId,activeRouting:$.activeRouting,lastUpdated:Math.max(Date.now(),$.lastUpdated+1)}),Z)})}function BH(H,J,Z=z(),$){return B(async()=>{await C(Z,(x)=>{let Q=M({...x.activeRouting,[H.sessionId]:{activeId:H.activeId,route:H.route,updatedAt:H.updatedAt}},J,Date.now());return{...x,activeId:H.activeId,route:H.route,activeRouting:Q,lastUpdated:Math.max(Date.now(),x.lastUpdated+1)}},$)})}function OH(H,J=z()){return B(async()=>{await C(J,(Z)=>({...Z,activeId:H.activeId,route:H.route,lastUpdated:Math.max(Date.now(),Z.lastUpdated+1)}))})}function qH(H,J,Z=z(),$){return B(async()=>{await C(Z,(x)=>{let Q=Date.now(),Y=M(x.activeRouting,J,Q,H);return{...x,activeRouting:Y,lastUpdated:Math.max(Date.now(),x.lastUpdated+1)}},$)})}async function L(H,J){let Z=`${J}.${p()}.tmp`;try{await A(c(J),{recursive:!0}),await m(Z,JSON.stringify(H),"utf8"),await E(Z,J)}catch($){throw await f(Z,{force:!0}).catch(()=>{}),w.warn("sidebar write failed",{pid:process.pid,error:$ instanceof Error?$.message:String($)}),$}}function CH(){return P}function NH(H){let J=H.activeId;if(J&&J!=="main"){let Z=H.fallbacks.find(($)=>$.enabled&&$.id===J);if(Z)return{id:Z.id,name:Z.label??Z.id,quota:Z.quota,killed:Z.killed}}return{id:"main",name:"main",quota:H.main.quota,killed:H.main.killed}}function PH(H){let J=H?.primary?.usedPercent??null,Z=H?.secondary?.usedPercent??null,$=_(H);return{primaryUsedPercent:J,secondaryUsedPercent:Z,text:$.length===0?null:$.map(({label:x,window:Q})=>`${x}: ${Math.round(Q.usedPercent)}%`).join(" ")}}var HH=300000,JH=0.01,ZH=1;function hH(H,J,Z){if(!H.resetsAt)return null;let $=new Date(H.resetsAt).getTime();if(!Number.isFinite($))return null;let x=$-J,Q=Z-x;if(Q<HH)return null;if(Q<J*JH)return null;if(Q>=J)return null;let Y=H.usedPercent,V=Math.min(Math.max(Q/J*100,0),100),X=Y-V,O=Math.abs(X)<ZH?"on-pace":X>0?"deficit":"reserve",G=null;if(Y>0){let q=Q*100/Y,j=x+q;if(j<$)G=new Date(j).toISOString()}return{pacePercent:V,deltaPercent:X,state:O,runsOutAt:G}}
2
- export{b as Q,_ as R,z as S,K as T,y as U,XH as V,r as W,D as X,v as Y,KH as Z,M as _,zH as $,GH as aa,BH as ba,OH as ca,qH as da,CH as ea,NH as fa,PH as ga,hH as ha};