@cortexkit/opencode-openai-auth 0.4.1 → 0.4.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/dist/cli.js +1 -1
  2. package/dist/core/oauth.d.ts +1 -1
  3. package/dist/core/provider.d.ts +11 -0
  4. package/dist/core/quota-manager.d.ts +7 -11
  5. package/dist/core/refresh-all-quota.d.ts +10 -0
  6. package/dist/index-9k2gxqc1.js +89 -0
  7. package/dist/{index-1anzb8jh.js → index-ptsh66z7.js} +1 -1
  8. package/dist/{index-b6kp9ydc.js → index-rckqt97a.js} +1 -1
  9. package/dist/index-reagbdg3.js +2 -0
  10. package/dist/{index-6y6ss1kc.js → index-xbq3aq6f.js} +1 -1
  11. package/dist/{index-y67qn95a.js → index-xcf8tm40.js} +1 -1
  12. package/dist/index-ya6hw803.js +7 -0
  13. package/dist/index.js +69 -64
  14. package/dist/{quota-normalize-8yzxqy78.js → quota-normalize-754rewnb.js} +1 -1
  15. package/dist/raw-ws-bun.d.ts +2 -0
  16. package/dist/raw-ws-node.d.ts +2 -0
  17. package/dist/raw-ws-upgrade.d.ts +2 -0
  18. package/dist/rpc/port-file.js +1 -1
  19. package/dist/rpc/rpc-client.js +1 -1
  20. package/dist/rpc/rpc-dir.js +1 -1
  21. package/dist/sidebar-state.d.ts +2 -0
  22. package/dist/sidebar-state.js +1 -1
  23. package/dist/token-util-xzavn760.js +1 -0
  24. package/dist/{token-yzcb1p3e.js → token-xsc39hv8.js} +1 -1
  25. package/dist/tui-preferences.js +1 -1
  26. package/dist/version.d.ts +1 -1
  27. package/dist/ws-pool.d.ts +2 -11
  28. package/dist/ws.d.ts +7 -2
  29. package/package.json +4 -4
  30. package/src/core/refresh-file-lock.ts +16 -0
  31. package/src/sidebar-state.ts +34 -3
  32. package/src/tui-compiled/core/refresh-file-lock.ts +309 -0
  33. package/src/tui-compiled/sidebar-state.ts +34 -3
  34. package/dist/index-0gccjqxr.js +0 -89
  35. package/dist/index-1r02s323.js +0 -6
  36. package/dist/index-fbfpefx6.js +0 -2
  37. package/dist/token-util-h46jb3eg.js +0 -1
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-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:
2
+ import{F as q,J as B,K as V,r as Y,y as Z,z as $}from"./index-9k2gxqc1.js";import"./index-ya6hw803.js";import{va as X}from"./index-xbq3aq6f.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.1";
5
+ export declare const USER_AGENT = "cortexkit-opencode-openai-auth/0.4.3";
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 {
@@ -6,6 +6,14 @@
6
6
  * directly.
7
7
  */
8
8
  import type { OAuthQuotaSnapshot } from './accounts.ts';
9
+ declare const log: {
10
+ error: (m: string, d?: unknown) => void;
11
+ warn: (m: string, d?: unknown) => void;
12
+ info: (m: string, d?: unknown) => void;
13
+ debug: (m: string, d?: unknown) => void;
14
+ trace: (m: string, d?: unknown) => void;
15
+ };
16
+ type QuotaLogger = Pick<typeof log, 'debug' | 'warn'>;
9
17
  export type QuotaWindowName = string;
10
18
  export declare const PRIMARY: QuotaWindowName;
11
19
  export declare const SECONDARY: QuotaWindowName;
@@ -56,4 +64,7 @@ export declare function whamUsageFn(input: {
56
64
  fetchImpl: typeof fetch;
57
65
  now: () => number;
58
66
  accountId?: string;
67
+ accountKey?: string;
68
+ logger?: QuotaLogger;
59
69
  }): Promise<OAuthQuotaSnapshot>;
70
+ export {};
@@ -13,18 +13,14 @@ import { type ProviderQuotaFn } from './provider.ts';
13
13
  export type { ProviderQuotaFn };
14
14
  export declare function quotaWindowResetIsPast(window: AccountQuotaWindow | undefined, now: number): boolean;
15
15
  /**
16
- * Resolve when a mid-stream-exhausted account's window actually resets, from
17
- * its own last-known cached quota snapshot (a response.failed frame carries no
18
- * reset time itself). The frame always names the exhausted window (primary or
19
- * secondary), so use only THAT window's cached reset; if it's unknown, fall
20
- * back to a conservative bounded default rather than borrowing the OTHER
21
- * window's reset — an unrelated window can reset far in the future and would
22
- * blackhole the account long past its actual rate-limit. The default is
23
- * self-correcting: if the account is still exhausted, the next response.failed
24
- * frame re-marks it. Pure — single source of truth shared by the fetch-override
25
- * reroute and its unit tests.
16
+ * Resolve when a WS-exhausted account becomes usable. Admission errors can
17
+ * carry the provider's authoritative reset; response.failed frames do not, so
18
+ * those fall back to the named window in the last-known quota snapshot. Never
19
+ * borrow the other window's reset — an unrelated window can blackhole the
20
+ * account long past its actual limit. The bounded default self-corrects when a
21
+ * later request reports exhaustion again.
26
22
  */
27
- export declare function resolveMidStreamRateLimitResetAt(quota: OAuthQuotaSnapshot | undefined, window: string, now: number, defaultMs: number): number;
23
+ export declare function resolveMidStreamRateLimitResetAt(quota: OAuthQuotaSnapshot | undefined, window: string, now: number, defaultMs: number, explicitResetAt?: number): number;
28
24
  /**
29
25
  * Stable, non-reversible fingerprint of an access token. Used to detect a
30
26
  * main-account switch so a different account's persisted/cached quota is never
@@ -1,6 +1,14 @@
1
1
  import type { FallbackAccountManager, isOAuthAccount, loadAccounts } from './accounts';
2
2
  import type { whamUsageFn } from './provider';
3
3
  import type { QuotaManager } from './quota-manager';
4
+ declare const log: {
5
+ error: (m: string, d?: unknown) => void;
6
+ warn: (m: string, d?: unknown) => void;
7
+ info: (m: string, d?: unknown) => void;
8
+ debug: (m: string, d?: unknown) => void;
9
+ trace: (m: string, d?: unknown) => void;
10
+ };
11
+ type QuotaLogger = Pick<typeof log, 'debug' | 'warn'>;
4
12
  export interface RefreshAllQuotaDeps {
5
13
  getAuth: () => Promise<{
6
14
  type: string;
@@ -43,6 +51,7 @@ export interface RefreshAllQuotaDeps {
43
51
  isOAuthAccountFn: typeof isOAuthAccount;
44
52
  whamFn?: typeof whamUsageFn;
45
53
  respectBackoff?: boolean;
54
+ logger?: QuotaLogger;
46
55
  }
47
56
  export interface RefreshAllQuotaResult {
48
57
  account: string;
@@ -50,3 +59,4 @@ export interface RefreshAllQuotaResult {
50
59
  error?: string;
51
60
  }
52
61
  export declare function refreshAllQuota(deps: RefreshAllQuotaDeps): Promise<RefreshAllQuotaResult[]>;
62
+ export {};
@@ -0,0 +1,89 @@
1
+ import{ma as s,na as x}from"./index-ya6hw803.js";import{va as Y3}from"./index-xbq3aq6f.js";import{createHash as p0}from"node:crypto";var l0=86400000,d0=300000,g0=3600000,i0=60000,u0=900000,s0=300000;function t(B){return B instanceof Error?B.message:String(B)}function r0(B){let Z=B?.status;if(typeof Z==="number")return Z===429||Z>=500;if(!(B instanceof Error))return!1;return B.name==="AbortError"||B.name==="TimeoutError"||B.message.includes("fetch failed")||"code"in B&&(B.code==="ECONNRESET"||B.code==="ECONNREFUSED"||B.code==="ETIMEDOUT"||B.code==="UND_ERR_CONNECT_TIMEOUT")}function e(B){let Z=t(B),$=B?.status;if(typeof $==="number")return $===429||$>=500;if(!(B instanceof Error))return!1;let W=B.code;return B.name==="AbortError"||B.name==="TimeoutError"||Z.includes("fetch failed")||W==="ECONNRESET"||W==="ECONNREFUSED"||W==="ETIMEDOUT"||W==="UND_ERR_CONNECT_TIMEOUT"}function Q0(B){return p0("sha256").update(B).digest("hex")}function N0(B){let Z=Q0(B.refreshToken),W=(B.previous?.tokenHash===Z?B.previous.retryCount??0:0)+1,z,G=B.error?.retryAfter;if(typeof G==="number"&&G>0)z=G*1000;else if(r0(B.error))z=Math.min(g0,d0*2**Math.min(W-1,6));else z=l0;return{message:t(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===Q0(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 A(B){let $=(B.previous?.retryCount??0)+1,W,z=B.error?.retryAfter;if(typeof z==="number"&&z>0)W=z*1000;else if(e(B.error))W=Math.min(u0,i0*2**Math.min($-1,6));else W=s0;return{message:t(B.error),checkedAt:B.now,nextRetryAt:B.now+W,retryCount:$}}function I(B,Z){if(!B?.nextRetryAt||B.nextRetryAt<=Z)return!1;return!0}function B0(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 n0}from"node:http";import{setTimeout as c0}from"node:timers/promises";var P0="0.4.3";var u="app_EMoamEEZ73f0CkXaXp7hrann",q="https://auth.openai.com",m=1455,a0=3000,F0=`cortexkit-opencode-openai-auth/${P0}`,O0="main",o0=`"${O0}" is a reserved account id; choose a different label.`;function b0(B){let Z=new Uint8Array(B),$=String.fromCharCode(...Z);return btoa($).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function t0(){let Z=Array.from(crypto.getRandomValues(new Uint8Array(43))).map((W)=>"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~"[W%66]).join(""),$=b0(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(Z)));return{verifier:Z,challenge:$}}function V0(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 L0(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=V0(B.id_token),$=Z&&L0(Z);if($)return $}if(B.access_token){let Z=V0(B.access_token);return Z?L0(Z):void 0}return}function e0(B){return typeof B==="string"&&B.toLowerCase()===O0}function Z0(B){if(e0(B))throw Error(o0);return B}function B3(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 Z3(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 $3(B){return B.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&#39;")}var W3=`<!doctype html>
2
+ <html>
3
+ <head>
4
+ <title>CortexKit OpenAI Auth - Authorization Successful</title>
5
+ <style>
6
+ body {
7
+ font-family:
8
+ system-ui,
9
+ -apple-system,
10
+ sans-serif;
11
+ display: flex;
12
+ justify-content: center;
13
+ align-items: center;
14
+ height: 100vh;
15
+ margin: 0;
16
+ background: #131010;
17
+ color: #f1ecec;
18
+ }
19
+ .container {
20
+ text-align: center;
21
+ padding: 2rem;
22
+ }
23
+ h1 {
24
+ color: #f1ecec;
25
+ margin-bottom: 1rem;
26
+ }
27
+ p {
28
+ color: #b7b1b1;
29
+ }
30
+ </style>
31
+ </head>
32
+ <body>
33
+ <div class="container">
34
+ <h1>Authorization Successful</h1>
35
+ <p>You can close this window and return to OpenCode.</p>
36
+ </div>
37
+ <script>
38
+ setTimeout(() => window.close(), 2000)
39
+ </script>
40
+ </body>
41
+ </html>`,g=(B)=>`<!doctype html>
42
+ <html>
43
+ <head>
44
+ <title>CortexKit OpenAI Auth - Authorization Failed</title>
45
+ <style>
46
+ body {
47
+ font-family:
48
+ system-ui,
49
+ -apple-system,
50
+ sans-serif;
51
+ display: flex;
52
+ justify-content: center;
53
+ align-items: center;
54
+ height: 100vh;
55
+ margin: 0;
56
+ background: #131010;
57
+ color: #f1ecec;
58
+ }
59
+ .container {
60
+ text-align: center;
61
+ padding: 2rem;
62
+ }
63
+ h1 {
64
+ color: #fc533a;
65
+ margin-bottom: 1rem;
66
+ }
67
+ p {
68
+ color: #b7b1b1;
69
+ }
70
+ .error {
71
+ color: #ff917b;
72
+ font-family: monospace;
73
+ margin-top: 1rem;
74
+ padding: 1rem;
75
+ background: #3c140d;
76
+ border-radius: 0.5rem;
77
+ }
78
+ </style>
79
+ </head>
80
+ <body>
81
+ <div class="container">
82
+ <h1>Authorization Failed</h1>
83
+ <p>An error occurred during authorization.</p>
84
+ <div class="error">${$3(B)}</div>
85
+ </div>
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 z3(){let B=`http://localhost:${m}/auth/callback`;if(k)return{port:m,redirectUri:B};if(w)return w;w=(async()=>{let Z=n0(($,W)=>{let z=new URL($.url||"/",`http://127.0.0.1:${m}`);if(z.pathname==="/auth/callback"){let G=z.searchParams.get("code"),X=z.searchParams.get("state"),K=z.searchParams.get("error"),Y=z.searchParams.get("error_description");if(K){let j=Y||K;if(X){let Q=L.get(X);if(Q)Q.reject(Error(j)),C(X);else if(M()===0)_()}else if(M()===0)_();W.writeHead(200,{"Content-Type":"text/html"}),W.end(g(j));return}if(!X){if(M()===0)_();W.writeHead(400,{"Content-Type":"text/html"}),W.end(g("Missing state parameter"));return}if(!G){if(M()===0)_();W.writeHead(400,{"Content-Type":"text/html"}),W.end(g("Missing authorization code"));return}let J=L.get(X);if(!J){if(M()===0)_();W.writeHead(400,{"Content-Type":"text/html"}),W.end(g("Unknown state — authorization may have expired"));return}C(X),Z3(G,B,J.pkce).then((j)=>J.resolve(j)).catch((j)=>J.reject(j)),W.writeHead(200,{"Content-Type":"text/html"}),W.end(W3);return}if(z.pathname==="/cancel"){let G=z.searchParams.get("state"),X=G?[G]:[...L.keys()];W.writeHead(200),W.end("Login cancelled");for(let K of X){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 X3(B,Z,$=300000,W){return new Promise((z,G)=>{if(W?.aborted){C(Z),G(Error("Login cancelled"));return}let X=setTimeout(()=>{if(L.get(Z))C(Z),G(Error("OAuth callback timeout — authorization took too long"))},$),K=()=>{if(clearTimeout(X),L.get(Z))C(Z),G(Error("Login cancelled"))};if(W)W.addEventListener("abort",K);L.set(Z,{pkce:B,state:Z,resolve:(Y)=>{if(clearTimeout(X),W)W.removeEventListener("abort",K);z(Y)},reject:(Y)=>{if(clearTimeout(X),W)W.removeEventListener("abort",K);G(Y)}})})}async function G3(){let B=await fetch(`${q}/api/accounts/deviceauth/usercode`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":F0},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 K3(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,G=Date.now();while(!0){if(Z?.aborted)throw Error("Device authorization cancelled");if(Date.now()-G>z)throw Error("Device authorization expired");let X=await fetch(`${q}/api/accounts/deviceauth/token`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":F0},body:JSON.stringify({device_auth_id:B.device_auth_id,user_code:B.user_code})});if(X.ok){let J=await X.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(X.status!==403&&X.status!==404)throw Error(`Device authorization failed: ${X.status}`);let K=z-(Date.now()-G);if(K<=0)throw Error("Device authorization expired");let Y=Math.min($+a0,K);try{await c0(Y,void 0,{signal:Z})}catch(J){if(J instanceof Error&&J.name==="AbortError")throw Error("Device authorization cancelled");throw J}}}function q4(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 C4(B={}){let{label:Z,headless:$=!1,signal:W}=B;if(Z0(Z),$){let{deviceData:J,url:j,instructions:Q}=await G3(),y=(async()=>{let V=await K3(J,W),F=Date.now(),H0=i(V);return{id:Z0(Z||H0||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:H0}})();return{url:j,instructions:Q,completion:y}}let{redirectUri:z}=await z3(),G=await t0(),X=b0(crypto.getRandomValues(new Uint8Array(32)).buffer),K=B3(z,G,X),Y=(async()=>{try{if(W?.aborted)throw Error("Login cancelled");let J=await X3(G,X,void 0,W),j=Date.now(),Q=i(J);return{id:Z0(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(X)}})();return{url:K,instructions:"Complete authorization in your browser. This window will close automatically.",completion:Y}}function D0(B){if(B instanceof Error)return B.message;if(typeof B==="string")return B;try{return JSON.stringify(B)}catch{return String(B)}}var J3=s("quota"),$0="primary",W0="secondary",j3="app_EMoamEEZ73f0CkXaXp7hrann",H3="https://auth.openai.com";async function x4(B){let Z=await B.fetchImpl(`${H3}/oauth/token`,{method:"POST",signal:AbortSignal.timeout(15000),headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"refresh_token",refresh_token:B.refreshToken,client_id:j3}).toString()});if(!Z.ok){let W=B0(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 Q3="https://chatgpt.com/backend-api/wham/usage";async function T4(B){let Z=B.logger??J3,$=B.accountKey??"unknown",W=Date.now();Z.debug("wham usage fetch started",{pid:process.pid,accountId:$});try{let z=await B.fetchImpl(Q3,{signal:AbortSignal.timeout(15000),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 K=B0(z.headers.get("retry-after"));throw Object.assign(Error(`wham usage check failed: ${z.status}`),{status:z.status,retryAfter:K})}let{normalizeWham:G}=await import("./quota-normalize-754rewnb.js"),X=G(await z.json());return Z.debug("wham usage fetch succeeded",{pid:process.pid,accountId:$,status:z.status,elapsedMs:Date.now()-W}),X}catch(z){throw Z.warn("wham usage fetch failed",{pid:process.pid,accountId:$,status:typeof z?.status==="number"?z.status:"error",elapsedMs:Date.now()-W,error:D0(z)}),z}}import{createHash as N3}from"node:crypto";var P3=globalThis.setTimeout,V3=5;function h(B){let Z=B?.quota?.checkIntervalMinutes??V3;return Math.max(1,Z)*60000}function L3(B){return B?.quota?.enabled!==!1}function r(B,Z){if(!B?.resetsAt)return!1;let $=Date.parse(B.resetsAt);return Number.isFinite($)&&$<=Z}function h4(B,Z,$,W,z){if(z!==void 0&&Number.isFinite(z)&&z>$)return z;let G=Z===$0?B?.primary:Z===W0?B?.secondary:void 0,X=G?.resetsAt?Date.parse(G.resetsAt):NaN;if(Number.isFinite(X)&&X>$)return X;return $+W}function F3(B){let Z=B?.quota?.minimumRemaining||{};return{primary:Z.primary??Z["5h"]??15,secondary:Z.secondary??Z["1w"]??10}}function U0(B,Z,$){if(!L3(Z))return $+h(Z);let W=F3(Z),z=[];for(let G of["primary","secondary"]){let X=B?.[G];if(!X)continue;if(X.remainingPercent>=W[G])continue;let K=X.resetsAt?Date.parse(X.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 O3(B){if(!B?.quota?.mainQuota||!B.quota.mainQuotaCheckedAt)return null;return{quota:B.quota.mainQuota,checkedAt:B.quota.mainQuotaCheckedAt,tokenFingerprint:B.quota.mainQuotaToken}}function b3(B){let Z=B?.quota?.refreshEveryNRequests;return typeof Z==="number"&&Number.isFinite(Z)&&Z>0?Math.floor(Z):0}function P(B){return N3("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&&!M0(Z.quota))return;if(this.mainTokenFp=P(B),$&&this.mainQuotaAccountId&&this.mainQuotaAccountId!==$)this.clearRateLimited("main");if($)this.mainQuotaAccountId=$;if(this.main=Z,z0(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&&!M0(Z.quota))return;if(this.fallbacks.set(B,Z),$)this.fallbackTokenFps.set(B,P($));else this.fallbackTokenFps.delete(B);if(z0(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 G=this.getFallback(B,Z);if(G)return G.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=b3(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 $=O3(B);if(!$)return;let W=Z?P(Z):null;if(W&&$.tokenFingerprint&&$.tokenFingerprint!==W)return;let z={quota:$.quota,refreshAfter:U0($.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&&I(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 I(this.mainLastApiError,this.now())}isFallbackBackedOff(B,Z){if(Z){if(this.fallbackErrorTokenFps.get(B)!==P(Z))return!1}return I(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 G=P3(z,O.API_CALL_GAP_MS-W);if(typeof G==="object"&&"unref"in G)G.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 x({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),G=this.now();if(this.mainTokenFp=P(B),this.main={quota:z,refreshAfter:U0(z,this.storage,G),checkedAt:G},z0(z))this.clearRateLimited("main");return this.mainLastApiError=void 0,this.onMainQuotaFetched?.(z,G,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 x({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=A({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,A({error:$,now:this.now(),previous:z})),this.fallbackErrorTokenFps.set(B,W)}}function M0(B){return Boolean(B.primary||B.secondary)}function z0(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 E3,randomUUID as S3}from"node:crypto";import{homedir as R3}from"node:os";import{dirname as y3,join as n}from"node:path";import{setTimeout as I3}from"node:timers/promises";import{randomUUID as D3}from"node:crypto";import{mkdir as U3,rename as M3,rm as _3,writeFile as q3}from"node:fs/promises";import{dirname as C3}from"node:path";async function T(B,Z){await U3(C3(B),{recursive:!0});let $=`${B}.${D3()}.tmp`;await q3($,`${JSON.stringify(Z,null,2)}
88
+ `,{encoding:"utf8",mode:384});try{await M3($,B)}catch(W){throw await _3($,{force:!0}).catch(()=>{}),W}}import{readFile as l3}from"node:fs/promises";var E=s("refresh"),_0=1e4,x3=50,I0="openai-auth.json",T3="openai-auth-state.json";function f3(){if(process.env.OPENCODE_CONFIG_DIR?.trim())return process.env.OPENCODE_CONFIG_DIR.trim();return n(process.env.XDG_CONFIG_HOME||n(R3(),".config"),"opencode")}function f(){return process.env.OPENCODE_OPENAI_AUTH_FILE?.trim()||n(f3(),I0)}function o(B=f()){let Z=process.env.OPENCODE_OPENAI_AUTH_STATE_FILE?.trim();if(Z)return Z;return A3(B)}function A3(B){return B.endsWith(I0)?n(y3(B),T3):`${B}.state.json`}function b(B){return B.type==="oauth"}function m3(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 ZB(B){return B.costZeroing?.enabled!==!1}class c extends Error{code="ACCOUNT_REMOVED_DURING_REFRESH";constructor(B){super(`Fallback account ${B} was removed before refresh`);this.name="AccountRemovedDuringRefreshError"}}var w3=[401,403,429],q0={primary:0,secondary:0},k3=!1,K0={primary:5,secondary:10};function H(B){return B!=null&&typeof B==="object"&&!Array.isArray(B)}function h3(B){return B instanceof c||H(B)&&B.name==="AccountRemovedDuringRefreshError"&&B.code==="ACCOUNT_REMOVED_DURING_REFRESH"}function C0(B){return{id:typeof B.id==="string"&&B.id.trim()?B.id.trim():S3(),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 E0(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 v3(B){if(!H(B))return;let Z={};for(let W of["primary","secondary"]){let z=B[W];if(!H(z))continue;let G=Number(z.usedPercent),X=Number(z.remainingPercent),K=Number(z.checkedAt);if(!Number.isFinite(G)||!Number.isFinite(X)||!Number.isFinite(K))continue;let Y=typeof z.windowMinutes==="number"?z.windowMinutes:Number.NaN;Z[W]={usedPercent:G,remainingPercent:X,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 p3(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(!m3(Z))return null;let W=B.authHeader==="x-api-key"?"x-api-key":"authorization-bearer";return{...C0(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{...C0(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:E0(B.lastRefreshError),lastQuotaRefreshError:E0(B.lastQuotaRefreshError),quota:v3(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(p3).filter((Z)=>Z!=null)}}async function R(B){try{return{exists:!0,value:JSON.parse(await l3(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 d3(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 T0(B,Z){if(!H(B))return B;let $=H(Z)?Z:{},W=H($.main)?$.main:void 0,z=H($.accounts)?$.accounts:{},G=H(B.quota)?B.quota:{},X=H(B.refresh)?B.refresh:{},K=W??G,Y=W??X,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 f0({...B,refresh:D({...X,mainLastRefreshError:Y.lastRefreshError,mainRefreshLeaseId:Y.refreshLeaseId,mainRefreshLeaseUntil:Y.refreshLeaseUntil,mainRefreshLeaseTokenHash:Y.refreshLeaseTokenHash}),quota:D({...G,mainQuota:K.quota,mainQuotaCheckedAt:K.quotaCheckedAt,mainQuotaToken:K.quotaToken,mainLastQuotaApiError:K.lastQuotaApiError}),accounts:j})}async function g3(B=f()){let Z=await R(B);if(!Z.exists)return null;let $=await R(o(B));return x0(T0(Z.value,$.value))}function f0(B){return Object.fromEntries(Object.entries(B).filter(([,Z])=>Z!==void 0))}function i3(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 A0(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 a(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 u3(B,Z){return B.access===Z.access&&B.refresh===Z.refresh&&B.expires===Z.expires&&B.lastRefreshedAt===Z.lastRefreshedAt}function s3(B,Z){if(!u3(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 r3(B,Z,$){let W=Z.lastRefreshedAt??0,z=$.lastRefreshedAt??0,G=Z.expires??0,X=$.expires??0,K=z>W?$:W>z?Z:X>G?$:G>X?Z:s3(Z,$);v(B,K,"access"),v(B,K,"refresh"),v(B,K,"expires"),v(B,K,"lastRefreshedAt"),v(B,K,"lastRefreshError")}function n3(B,Z){if(!H(B))return Z;let $=B,W=a($.quota),z=a(Z.quota),G=W>z,X=G?{...$,...Z,quota:$.quota,lastQuotaRefreshError:$.lastQuotaRefreshError}:{...$,...Z};if(!G&&!("lastQuotaRefreshError"in Z))delete X.lastQuotaRefreshError;if(!("lastRefreshError"in Z))delete X.lastRefreshError;if(typeof $.lastUsed==="number"&&(typeof Z.lastUsed!=="number"||$.lastUsed>Z.lastUsed))X.lastUsed=$.lastUsed;return r3(X,$,Z),X}function m0(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 f0({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(i3)})}async function p(B){let Z=Date.now()+_0;while(Date.now()<=Z){let $=await x({name:"save",ttlMs:_0,path:B});if($)return $;let W=Z-Date.now();if(W<=0)break;await I3(Math.min(x3,W))}throw Error(`Timed out acquiring account store lock for ${B}; refusing to overwrite newer account data`)}function w0(B){let Z=Object.fromEntries(B.accounts.map(($)=>[$.id,A0($)]));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 WB(B,Z=f()){let $=o(Z),W=await p(Z);try{let z=await p($);try{let G=await R(Z),X=await R($),K=(G.exists?x0(T0(G.value,X.value)):null)??c3(),Y=B(K)??K,j={...H(G.value)?G.value:{},...m0(Y)};return await T(Z,j),await T($,w0(Y)),Y}finally{await z.release()}}finally{await W.release()}}function c3(){return{version:1,main:{type:"opencode",provider:"openai"},accounts:[]}}function a3(B,Z){B.main=B.main??{};let $=typeof B.main.quotaCheckedAt==="number"?B.main.quotaCheckedAt:a(B.main.quota),W=typeof Z.quota?.mainQuotaCheckedAt==="number"?Z.quota.mainQuotaCheckedAt:a(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 o3(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 Y0(B){if(Array.isArray(B))return B.map(Y0);if(!H(B))return B;return Object.fromEntries(Object.entries(B).filter(([,Z])=>Z!==void 0).map(([Z,$])=>[Z,Y0($)]))}async function t3(B,Z=f(),$={mainQuota:!0,mainRefresh:!0,accounts:!0}){let W=o(Z),z=await p(W);try{let G=(await R(W)).value,X=H(G)?{...G,version:1}:{version:1};if($.mainQuota)a3(X,B);if($.mainRefresh)o3(X,B);if($.accounts){let K=$.accounts===!0?null:new Set($.accounts),Y=await d3(Z);X.accounts={...H(X.accounts)?X.accounts:{}};for(let J of B.accounts){if(K&&!K.has(J.id))continue;if(Y&&!Y.has(J.id))continue;X.accounts[J.id]=n3(X.accounts[J.id],A0(J))}if(K){for(let J of K)if(!B.accounts.some((j)=>j.id===J))delete X.accounts[J]}if(Y){for(let J of Object.keys(X.accounts))if(!Y.has(J))delete X.accounts[J]}}await T(W,Y0(X))}finally{await z.release()}}function e3(B){return B?.fallbackOn?.length?B.fallbackOn:w3}function zB(B,Z){return e3(Z).includes(B)}function B4(B){let Z=B?.quota?.minimumRemaining||{};return{primary:Z.primary??Z["5h"]??q0.primary,secondary:Z.secondary??Z["1w"]??q0.secondary}}function J0(B){return B?.quota?.enabled!==!1}function l(B){return B?.quota?.failClosedOnUnknownQuota??k3}function k0(B,Z,$=Date.now()){if(!J0(Z))return!0;if(!B)return!l(Z);let W=B4(Z),z=l(Z);for(let G of["primary","secondary"]){let X=B[G];if(!X)continue;if(r(X,$)){if(z)return!1;continue}if(X.remainingPercent<W[G])return!1}return!0}function h0(B){return B?.killswitch?.enabled===!0}function S0(B){return{primary:B?.primary??B?.["5h"]??K0.primary,secondary:B?.secondary??B?.["1w"]??K0.secondary}}function v0(B,Z){if(!B?.killswitch)return K0;if(Z&&B.killswitch.accounts?.[Z])return S0(B.killswitch.accounts[Z]);return S0(B.killswitch.main)}function XB(B,Z,$,W=Date.now()){if(!h0(Z))return!0;if(!B)return!l(Z);let z=v0(Z,$),G=l(Z);for(let X of["primary","secondary"]){let K=B[X];if(!K)continue;if(r(K,W)){if(G)return!1;continue}if(K.remainingPercent<z[X])return!1}return!0}function GB(B,Z,$,W){if(!h0(W))return 300;let z=[],G=[{accountId:void 0,quota:B},...Z];for(let{accountId:K,quota:Y}of G){if(!Y)continue;let J=v0(W,K),j=[],Q=!1;for(let y of["primary","secondary"]){let V=Y[y];if(!V||r(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 X=Math.min(...z);return Math.max(1,Math.ceil((X-$)/1000))}function Z4(B){return typeof B.version==="number"&&Array.isArray(B.accounts)}async function KB(B,Z=f()){let $=o(Z),W=await p(Z);try{let z=await p($);try{let G=await R(Z);if(G.exists&&H(G.value)){if(Z4(G.value))return}if(!B)return;let X={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)X.mainAccountId=J}let Y={...G.exists&&H(G.value)?G.value:{},...m0(X)};await T(Z,Y),await T($,w0(X))}finally{await z.release()}}finally{await W.release()}}function $4(B){return B?.refresh?.enabled!==!1}function W4(B){return(B?.refresh?.refreshBeforeExpiryMinutes??240)*60000}function z4(B){return Math.floor(Math.random()*(B+1))}function S(B,Z,$){return!B.access||!B.expires||B.expires-$<=W4(Z)}function X4(B,Z){return Boolean(B.access&&typeof B.expires==="number"&&B.expires>Z)}function G4(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 X0(B){return B instanceof Error?B.message:String(B)}function j0(B,Z,$){B.lastRefreshError=N0({error:Z,now:$,refreshToken:B.refresh,previous:B.lastRefreshError})}function G0(B,Z,$){if(B.lastQuotaRefreshError=A({error:Z,now:$,previous:B.lastQuotaRefreshError}),Z?.isRefreshError===!0)j0(B,Z,$)}function K4(B){return`fallback-oauth-refresh-${E3("sha256").update(B).digest("base64url").slice(0,16)}`}function R0(B,Z){if(!B)return!1;if(!B.resetsAt)return!0;let $=Date.parse(B.resetsAt);return Number.isFinite($)?$>Z:!0}function Y4(B,Z){if(!B)return!1;return R0(B.primary,Z)||R0(B.secondary,Z)}function J4(B,Z,$){if(!B)return!1;let W=Z?.quota?.checkIntervalMinutes??5,z=Math.max(1,W)*60000,G=Math.max(B.primary?.checkedAt??0,B.secondary?.checkedAt??0);return $-G<z}function y0(B,Z,$){return!J4(B.quota,Z,$)}function j4(B,Z,$,W){return e($)&&k0(B.quota,Z,W)&&Y4(B.quota,W)}function H4(B){let Z=B?.quota?.checkIntervalMinutes??5;return Math.max(1,Z)*60000}var Q4=60000,N4=60000,P4=600000,V4=1e4,L4=100;var YB=globalThis.setTimeout.bind(globalThis),JB=globalThis.clearTimeout.bind(globalThis);class F4{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??f(),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:$+H4(Z),checkedAt:$},B.access)}async load(){return g3(this.configPath)}async save(B,Z){await t3(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(()=>{})},Q4+z4(N4)),"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(G4(Z,z))continue;let G=!1,X=z;try{if(S(X,Z,this.now())){let K=X.lastRefreshError;if(K&&U(K,X.refresh,this.now()))throw G=!0,Error(d(K,this.now()));try{X=await this.refreshAccount(X,Z),W=!0}catch(Y){if(h3(Y))continue;G=!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(X,Z),this.accountPassesQuotaPolicy(this.quotaPolicyAccount(X),Z))$.push(X)}catch(K){let Y=X4(X,this.now());if(G){if(!Y)continue}else if(!Y)continue;if(j4(X,Z,K,this.now()))E.debug("fallback quota using cached quota after refresh error",{pid:process.pid,accountId:X.id,error:X0(K)}),$.push(X);else if(!l(Z))$.push(X)}}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 k0(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||!$4(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:X0(W)}),j0($,W,this.now()),N(B,$),Z=!0}}if(Z)await this.save(B)}async refreshQuotaForDueAccounts(){let B=await this.load();if(!B||!J0(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(I(W.lastQuotaRefreshError,this.now()))continue;if(this.seedFallbackQuota(W,B),!(this.quotaManager?this.quotaManager.isFallbackStale(W.id,W.access):y0(W,B,this.now())))continue;await this.refreshAccountQuota(W,B),Z=!0}catch(z){G0($,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||!J0(Z))return{storage:Z,errors:$};if(!this.options.fetchQuotaFn)return{storage:Z,errors:$};let W=B.force??!1,z=!1;for(let G of Z.accounts){if(G.enabled===!1||!b(G))continue;let X=G;try{if(S(X,Z,this.now())){let K=X.lastRefreshError;if(K&&U(K,X.refresh,this.now()))throw Error(d(K,this.now()));X=await this.refreshAccount(X,Z),z=!0}if(!W&&!y0(X,Z,this.now())){if(X.lastQuotaRefreshError)X.lastQuotaRefreshError=void 0,N(Z,X),z=!0;continue}await this.refreshAccountQuota(X,Z),z=!0}catch(K){G0(G,K,this.now()),N(Z,G),z=!0,$.push({accountId:G.id,message:X0(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 X=await W;return N(Z,X),X}let z=this.refreshAccountNow(B,Z,$).finally(()=>{this.refreshPromises.delete(B.id)});this.refreshPromises.set(B.id,z);let G=await z;return N(Z,G),G}async waitForConcurrentFallbackRefresh(B,Z,$,W){let z=Date.now()+V4;while(Date.now()<z){await new Promise((J)=>setTimeout(J,L4));let G=await this.load(),X=G?.accounts.find((J)=>J.id===B.id&&b(J));if(!X)continue;if((X.access!==$.access||X.refresh!==$.refresh||(X.expires??0)>($.expires??0)+60000)&&(W.force||!S(X,G,this.now())))return N(Z,X),E.debug("fallback oauth joined concurrent refresh",{pid:process.pid,accountId:X.id,expiresInMs:X.expires?X.expires-this.now():void 0}),X;let Y=X.lastRefreshError;if(Y&&U(Y,X.refresh,this.now()))throw N(Z,X),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 G=z??B,X=await x({name:K4(G.id),ttlMs:P4,path:this.configPath,now:this.now,renew:!0});if(!X){E.debug("fallback oauth refresh skipped file lock",{pid:process.pid,accountId:G.id});let K=await this.waitForConcurrentFallbackRefresh(B,Z,G,$);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 c(B.id);G=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:G.id,force:$.force===!0,expiresInMs:G.expires?G.expires-this.now():void 0});let Y=await K({refreshToken:G.refresh,fetchImpl:this.fetchImpl,now:this.now});if(G.access=Y.access,G.refresh=Y.refresh,G.expires=Y.expires,G.lastRefreshedAt=Y.expires-Y.expiresIn*1000,G.lastRefreshError=void 0,N(Z,G),await this.save(Z),!(await this.load())?.accounts.some((j)=>j.id===B.id))throw new c(B.id);return E.debug("fallback oauth refresh succeeded",{pid:process.pid,accountId:G.id,expiresInMs:G.expires?G.expires-this.now():void 0}),G}finally{await X.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=(G)=>this.quotaManager?this.quotaManager.refreshFallback($.id,G):W({accessToken:G,fetchImpl:this.fetchImpl,now:this.now});try{if(!$.access)throw Error(`Fallback account ${B.id} has no access token`);let G=await z($.access);$.quota=G,$.lastQuotaRefreshError=void 0,N(Z,$),await this.save(Z)}catch(G){throw G0(B,G,this.now()),N(Z,B),G}}}
89
+ export{Q0 as h,N0 as i,U as j,d as k,F0 as l,b0 as m,t0 as n,V0 as o,L0 as p,i as q,Z0 as r,B3 as s,C as t,z3 as u,X3 as v,G3 as w,K3 as x,q4 as y,C4 as z,D0 as A,x4 as B,T4 as C,h4 as D,O as E,f as F,b as G,ZB as H,K0 as I,g3 as J,WB as K,zB as L,h0 as M,XB as N,GB as O,KB as P,F4 as Q};
@@ -1,2 +1,2 @@
1
1
  import{mkdir as u,readdir as l,readFile as c,rename as p,unlink as m,writeFile as d}from"node:fs/promises";import{join as a}from"node:path";function f(t){try{return process.kill(t,0),!0}catch(r){return r.code==="EPERM"}}async function b(t,r){await u(t,{recursive:!0});let s={...r,startedAt:Date.now()},e=a(t,`port-${r.pid}.json`),i=`${e}.${process.pid}.tmp`;return await d(i,JSON.stringify(s),{encoding:"utf8",mode:384}),await p(i,e),e}async function h(t,r){let s;try{s=await l(t)}catch{return null}let e=[];for(let n of s){if(!n.startsWith("port-")||!n.endsWith(".json"))continue;try{let o=JSON.parse(await c(a(t,n),"utf8"));if(Number.isFinite(o.port))if(f(o.pid))e.push(o);else m(a(t,n)).catch(()=>{})}catch{}}if(e.length===0)return null;let i=r!==void 0&&r>=1?e.filter((n)=>n.pid===r):[];return(i.length>0?i:e).sort((n,o)=>o.startedAt-n.startedAt)[0]??null}
2
- export{b as ma,h as na};
2
+ export{b as oa,h as pa};
@@ -1 +1 @@
1
- import{createHash as z}from"node:crypto";import{homedir as A,tmpdir as K}from"node:os";import{join as q,resolve as B}from"node:path";var F="OPENCODE_OPENAI_AUTH_RPC_DIR";function M(f){let k=process.env[F]?.trim();if(k)return B(f,k);let w=z("sha256").update(f).digest("hex").slice(0,16),x=process.env.XDG_STATE_HOME||q(A(),".local","state");return q(x,"cortexkit","openai-auth","rpc",w)}export{K as oa,M as pa};
1
+ import{createHash as z}from"node:crypto";import{homedir as A,tmpdir as K}from"node:os";import{join as q,resolve as B}from"node:path";var F="OPENCODE_OPENAI_AUTH_RPC_DIR";function M(f){let k=process.env[F]?.trim();if(k)return B(f,k);let w=z("sha256").update(f).digest("hex").slice(0,16),x=process.env.XDG_STATE_HOME||q(A(),".local","state");return q(x,"cortexkit","openai-auth","rpc",w)}export{K as qa,M as ra};
@@ -0,0 +1,2 @@
1
+ import{ma as F,na as R}from"./index-ya6hw803.js";import{randomUUID as f}from"node:crypto";import{mkdir as g,readFile as v,rename as m,rm as S,writeFile as c}from"node:fs/promises";import{tmpdir as w}from"node:os";import{dirname as M,join as y}from"node:path";var A=["primary","secondary"],k={primary:300,secondary:10080};function P(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`${P(Z)}m`;if(Z<1440)return`${P(Z/60)}h`;return`${P(Z/1440)}d`}function E(H){if(!H)return[];let J=[];for(let Z of A){let $=H[Z];if(!$)continue;let j=$.windowMinutes,Y=j!==void 0&&Number.isFinite(j)&&j>0?j:k[Z];J.push({key:Z,label:p(Y,Z),window:$,windowMs:Y*60000})}return J}var d=F("sidebar"),u="OPENCODE_OPENAI_AUTH_SIDEBAR_STATE_FILE",l=y(w(),"opencode-openai-auth"),o=y(l,"sidebar-state.json");function s(H){return typeof H==="number"&&Number.isFinite(H)&&H>=0?H:void 0}function h(H){let J=s(H);return J!==void 0?{resetCredits:J}:{}}function r(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 j=$;if(typeof j.activeId!=="string"||typeof j.route!=="string"||typeof j.updatedAt!=="number"||!Number.isFinite(j.updatedAt))continue;J[Z]={activeId:j.activeId,route:j.route,updatedAt:j.updatedAt}}return Object.keys(J).length>0?J:void 0}function z(){return process.env[u]||o}var Q={main:{quota:null,killed:!1},fallbacks:[],activeId:void 0,route:"main",lastUpdated:0};function I(H){if(H===null||typeof H!=="object"||Array.isArray(H))return Q;let J=H,Z=J.main,$;if(Z!==null&&typeof Z==="object"&&!Array.isArray(Z)){let x=Z;$={quota:"quota"in x?x.quota:null,killed:typeof x.killed==="boolean"?x.killed:!1,...typeof x.quotaBackedOff==="boolean"?{quotaBackedOff:x.quotaBackedOff}:{},...typeof x.quotaBackoffUntil==="number"?{quotaBackoffUntil:x.quotaBackoffUntil}:{},...typeof x.refreshBackedOff==="boolean"?{refreshBackedOff:x.refreshBackedOff}:{},...typeof x.refreshBackoffUntil==="number"?{refreshBackoffUntil:x.refreshBackoffUntil}:{},...h(x.resetCredits)}}else $={quota:null,killed:!1};let j=J.fallbacks,Y=Array.isArray(j)?j.filter((x)=>x!==null&&typeof x==="object"&&!Array.isArray(x)&&typeof x.id==="string").map((x)=>({id:x.id,label:typeof x.label==="string"?x.label:void 0,quota:"quota"in x?x.quota:null,killed:typeof x.killed==="boolean"?x.killed:!1,enabled:typeof x.enabled==="boolean"?x.enabled:!0,...h(x.resetCredits)})):[],V=typeof J.activeId==="string"?J.activeId:void 0,X=typeof J.route==="string"?J.route:Q.route,K=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,C=r(J.activeRouting);return{main:$,fallbacks:Y,activeId:V,route:X,lastUpdated:K,...C!==void 0?{activeRouting:C}:{},...O!==void 0?{planType:O}:{},...G!==void 0?{credits:G}:{}}}async function QH(){try{let H=await v(z(),"utf8");return I(JSON.parse(H))}catch{return Q}}var n=3600000,D=128;function T(H,J,Z=Date.now()){if(!(H.updatedAt>=Z-n&&H.updatedAt<=Z))return!1;return H.activeId==="main"||J.some((j)=>j.enabled!==!1&&j.killed!==!0&&j.id===H.activeId)}function U(H,J=Date.now()){let Z=H?.primary;if(typeof Z?.resetsAt!=="string"||!Number.isFinite(Z.usedPercent)||Z.usedPercent<100)return!1;let $=Date.parse(Z.resetsAt);return Number.isFinite($)&&$>J}function zH(H,J,Z=Date.now()){if(!J)return{activeId:H.activeId??"main",route:H.route};let $=J?H.activeRouting?.[J]:void 0,j=$?.activeId==="main"?H.main.quota:H.fallbacks.find((X)=>X.id===$?.activeId)?.quota;if($&&T($,H.fallbacks,Z)&&!U(j,Z))return{activeId:$.activeId,route:$.route};let Y=H.fallbacks.filter((X)=>X.enabled&&!X.killed),V=Y.find((X)=>!U(X.quota,Z))??Y[0];return{activeId:H.route==="fallback-first"&&V?V.id:"main",route:H.route}}function _(H,J,Z=Date.now(),$){if(!H)return;let j=Object.entries(H).filter(([V,X])=>V!==$&&T(X,J,Z)),Y=j.length<=D?j:j.sort((V,X)=>X[1].updatedAt-V[1].updatedAt).slice(0,D);return Y.length>0?Object.fromEntries(Y):void 0}var q=Promise.resolve(),i=3,a=1e4,t=15000;function B(H){let J=q.then(H);return q=J.catch(()=>{}),J}function GH(H,J=z()){return B(()=>W(H,J))}async function e(H){try{return b(await L(H))}catch{return Q}}async function L(H){try{return await v(H,"utf8")}catch(J){if(J.code==="ENOENT")return"";throw J}}function b(H){if(H==="")return Q;try{return I(JSON.parse(H))}catch{return Q}}async function HH(H){await g(M(H),{recursive:!0});let J=Date.now()+t;while(Date.now()<=J){let Z=await R({name:"sidebar-write",path:H,ttlMs:a,renew:!0});if(Z)return Z;await new Promise(($)=>setTimeout($,10))}throw Error("Timed out waiting for the sidebar state write lock")}async function N(H,J,Z){let $=await HH(H);try{for(let Y=0;Y<i;Y+=1){let V=await L(H),X=J(b(V));if(Y===0)await Z?.beforeRecheck?.();if(await L(H)!==V)continue;await W(X,H);return}let j=await e(H);await W(J(j),H)}finally{await $.release()}}function BH(H,J=z(),Z){return B(async()=>{await N(J,($)=>({...$,...H,activeId:$.activeId,activeRouting:$.activeRouting,lastUpdated:Math.max(Date.now(),$.lastUpdated+1)}),Z)})}function OH(H,J,Z=z(),$){return B(async()=>{await N(Z,(j)=>{let Y=_({...j.activeRouting,[H.sessionId]:{activeId:H.activeId,route:H.route,updatedAt:H.updatedAt}},J,Date.now());return{...j,activeId:H.activeId,route:H.route,activeRouting:Y,lastUpdated:Math.max(Date.now(),j.lastUpdated+1)}},$)})}function CH(H,J=z()){return B(async()=>{await N(J,(Z)=>({...Z,activeId:H.activeId,route:H.route,lastUpdated:Math.max(Date.now(),Z.lastUpdated+1)}))})}function NH(H,J,Z=z(),$){return B(async()=>{await N(Z,(j)=>{let Y=Date.now(),V=_(j.activeRouting,J,Y,H);return{...j,activeRouting:V,lastUpdated:Math.max(Date.now(),j.lastUpdated+1)}},$)})}async function W(H,J){let Z=`${J}.${f()}.tmp`;try{await g(M(J),{recursive:!0}),await c(Z,JSON.stringify(H),"utf8"),await m(Z,J)}catch($){throw await S(Z,{force:!0}).catch(()=>{}),d.warn("sidebar write failed",{pid:process.pid,error:$ instanceof Error?$.message:String($)}),$}}function PH(){return q}function qH(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 LH(H){let J=H?.primary?.usedPercent??null,Z=H?.secondary?.usedPercent??null,$=E(H);return{primaryUsedPercent:J,secondaryUsedPercent:Z,text:$.length===0?null:$.map(({label:j,window:Y})=>`${j}: ${Math.round(Y.usedPercent)}%`).join(" ")}}var JH=300000,ZH=0.01,$H=1;function WH(H,J,Z){if(!H.resetsAt)return null;let $=new Date(H.resetsAt).getTime();if(!Number.isFinite($))return null;let j=$-J,Y=Z-j;if(Y<JH)return null;if(Y<J*ZH)return null;if(Y>=J)return null;let V=H.usedPercent,X=Math.min(Math.max(Y/J*100,0),100),K=V-X,O=Math.abs(K)<$H?"on-pace":K>0?"deficit":"reserve",G=null;if(V>0){let C=Y*100/V,x=j+C;if(x<$)G=new Date(x).toISOString()}return{pacePercent:X,deltaPercent:K,state:O,runsOutAt:G}}
2
+ export{p as R,E as S,z as T,Q as U,I as V,QH as W,n as X,D as Y,T as Z,U as _,zH as $,_ as aa,GH as ba,BH as ca,OH as da,CH as ea,NH as fa,PH as ga,qH as ha,LH as ia,WH as ja};
@@ -1,2 +1,2 @@
1
1
  import{createRequire as s}from"node:module";var j=Object.create;var{getPrototypeOf:k,defineProperty:f,getOwnPropertyNames:l}=Object;var m=Object.prototype.hasOwnProperty;function n(a){return this[a]}var o,p,t=(a,b,c)=>{var g=a!=null&&typeof a==="object";if(g){var h=b?o??=new WeakMap:p??=new WeakMap,i=h.get(a);if(i)return i}c=a!=null?j(k(a)):{};let d=b||!a||!a.__esModule?f(c,"default",{value:a,enumerable:!0}):c;for(let e of l(a))if(!m.call(d,e))f(d,e,{get:n.bind(a,e),enumerable:!0});if(g)h.set(a,d);return d};var u=(a,b)=>()=>(b||a((b={exports:{}}).exports,b),b.exports);var q=(a)=>a;function r(a,b){this[a]=q.bind(null,b)}var v=(a,b)=>{for(var c in b)f(a,c,{get:b[c],enumerable:!0,configurable:!0,set:r.bind(b,c)})};var x=s(import.meta.url);
2
- export{t as qa,u as ra,v as sa,x as ta};
2
+ export{t as sa,u as ta,v as ua,x as va};
@@ -1,2 +1,2 @@
1
- import{ra as Z,ta as W}from"./index-6y6ss1kc.js";var R=Z(($G,E)=>{var{defineProperty:N,getOwnPropertyDescriptor:Kz,getOwnPropertyNames:Qz}=Object,Wz=Object.prototype.hasOwnProperty,Xz=(z,G)=>{for(var H in G)N(z,H,{get:G[H],enumerable:!0})},Yz=(z,G,H,Q)=>{if(G&&typeof G==="object"||typeof G==="function"){for(let K of Qz(G))if(!Wz.call(z,K)&&K!==H)N(z,K,{get:()=>G[K],enumerable:!(Q=Kz(G,K))||Q.enumerable})}return z},Zz=(z)=>Yz(N({},"__esModule",{value:!0}),z),O={};Xz(O,{VercelOidcTokenError:()=>S});E.exports=Zz(O);class S extends Error{constructor(z,G){super(z);this.name="VercelOidcTokenError",this.cause=G}toString(){if(this.cause)return`${this.name}: ${this.message}: ${this.cause}`;return`${this.name}: ${this.message}`}}});var P=Z((qG,y)=>{var{create:$z,defineProperty:L,getOwnPropertyDescriptor:qz,getOwnPropertyNames:vz,getPrototypeOf:Bz}=Object,Fz=Object.prototype.hasOwnProperty,Uz=(z,G)=>{for(var H in G)L(z,H,{get:G[H],enumerable:!0})},C=(z,G,H,Q)=>{if(G&&typeof G==="object"||typeof G==="function"){for(let K of vz(G))if(!Fz.call(z,K)&&K!==H)L(z,K,{get:()=>G[K],enumerable:!(Q=qz(G,K))||Q.enumerable})}return z},I=(z,G,H)=>(H=z!=null?$z(Bz(z)):{},C(G||!z||!z.__esModule?L(H,"default",{value:z,enumerable:!0}):H,z)),Lz=(z)=>C(L({},"__esModule",{value:!0}),z),x={};Uz(x,{findRootDir:()=>Jz,getUserDataDir:()=>Nz});y.exports=Lz(x);var B=I(W("path")),bz=I(W("fs")),A=I(W("os")),Vz=R();function Jz(){try{let z=process.cwd();while(z!==B.default.dirname(z)){let G=B.default.join(z,".vercel");if(bz.default.existsSync(G))return z;z=B.default.dirname(z)}}catch(z){throw new Vz.VercelOidcTokenError("Token refresh only supported in node server environments")}return null}function Nz(){if(process.env.XDG_DATA_HOME)return process.env.XDG_DATA_HOME;switch(A.default.platform()){case"darwin":return B.default.join(A.default.homedir(),"Library/Application Support");case"linux":return B.default.join(A.default.homedir(),".local/share");case"win32":if(process.env.LOCALAPPDATA)return process.env.LOCALAPPDATA;return null;default:return null}}});var i=Z((vG,c)=>{var{create:Rz,defineProperty:b,getOwnPropertyDescriptor:Az,getOwnPropertyNames:Iz,getPrototypeOf:Dz}=Object,wz=Object.prototype.hasOwnProperty,Tz=(z,G)=>{for(var H in G)b(z,H,{get:G[H],enumerable:!0})},u=(z,G,H,Q)=>{if(G&&typeof G==="object"||typeof G==="function"){for(let K of Iz(G))if(!wz.call(z,K)&&K!==H)b(z,K,{get:()=>G[K],enumerable:!(Q=Az(G,K))||Q.enumerable})}return z},l=(z,G,H)=>(H=z!=null?Rz(Dz(z)):{},u(G||!z||!z.__esModule?b(H,"default",{value:z,enumerable:!0}):H,z)),jz=(z)=>u(b({},"__esModule",{value:!0}),z),g={};Tz(g,{isValidAccessToken:()=>Ez,readAuthConfig:()=>Oz,writeAuthConfig:()=>Sz});c.exports=jz(g);var F=l(W("fs")),h=l(W("path")),Mz=f();function k(){let z=(0,Mz.getVercelDataDir)();if(!z)throw Error(`Unable to find Vercel CLI data directory. Your platform: ${process.platform}. Supported: darwin, linux, win32.`);return h.join(z,"auth.json")}function Oz(){try{let z=k();if(!F.existsSync(z))return null;let G=F.readFileSync(z,"utf8");if(!G)return null;return JSON.parse(G)}catch(z){return null}}function Sz(z){let G=k(),H=h.dirname(G);if(!F.existsSync(H))F.mkdirSync(H,{mode:504,recursive:!0});F.writeFileSync(G,JSON.stringify(z,null,2),{mode:384})}function Ez(z,G=0){if(!z.token)return!1;if(typeof z.expiresAt!=="number")return!0;let H=Math.floor(Date.now()/1000),Q=G/1000;return z.expiresAt>=H+Q}});var a=Z((BG,s)=>{var{defineProperty:T,getOwnPropertyDescriptor:Cz,getOwnPropertyNames:xz}=Object,yz=Object.prototype.hasOwnProperty,Pz=(z,G)=>{for(var H in G)T(z,H,{get:G[H],enumerable:!0})},uz=(z,G,H,Q)=>{if(G&&typeof G==="object"||typeof G==="function"){for(let K of xz(G))if(!yz.call(z,K)&&K!==H)T(z,K,{get:()=>G[K],enumerable:!(Q=Cz(G,K))||Q.enumerable})}return z},lz=(z)=>uz(T({},"__esModule",{value:!0}),z),d={};Pz(d,{processTokenResponse:()=>iz,refreshTokenRequest:()=>cz});s.exports=lz(d);var D=W("os"),gz="https://vercel.com",hz="cl_HYyOPBNtFMfHhaUn9L4QPfTZz6TP47bp",p=`@vercel/oidc node-${process.version} ${(0,D.platform)()} (${(0,D.arch)()}) ${(0,D.hostname)()}`,w=null;async function kz(){if(w)return w;let z=`${gz}/.well-known/openid-configuration`,G=await fetch(z,{headers:{"user-agent":p}});if(!G.ok)throw Error("Failed to discover OAuth endpoints");let H=await G.json();if(!H||typeof H.token_endpoint!=="string")throw Error("Invalid OAuth discovery response");let Q=H.token_endpoint;return w=Q,Q}async function cz(z){let G=await kz();return await fetch(G,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded","user-agent":p},body:new URLSearchParams({client_id:hz,grant_type:"refresh_token",...z})})}async function iz(z){let G=await z.json();if(!z.ok){let H=typeof G==="object"&&G&&"error"in G?String(G.error):"Token refresh failed";return[Error(H)]}if(typeof G!=="object"||G===null)return[Error("Invalid token response")];if(typeof G.access_token!=="string")return[Error("Missing access_token in response")];if(G.token_type!=="Bearer")return[Error("Invalid token_type in response")];if(typeof G.expires_in!=="number")return[Error("Missing expires_in in response")];return[null,G]}});var t=Z((FG,r)=>{var{defineProperty:j,getOwnPropertyDescriptor:fz,getOwnPropertyNames:dz}=Object,pz=Object.prototype.hasOwnProperty,sz=(z,G)=>{for(var H in G)j(z,H,{get:G[H],enumerable:!0})},az=(z,G,H,Q)=>{if(G&&typeof G==="object"||typeof G==="function"){for(let K of dz(G))if(!pz.call(z,K)&&K!==H)j(z,K,{get:()=>G[K],enumerable:!(Q=fz(G,K))||Q.enumerable})}return z},_z=(z)=>az(j({},"__esModule",{value:!0}),z),_={};sz(_,{AccessTokenMissingError:()=>m,RefreshAccessTokenFailedError:()=>n});r.exports=_z(_);class m extends Error{constructor(){super("No authentication found. Please log in with the Vercel CLI (vercel login).");this.name="AccessTokenMissingError"}}class n extends Error{constructor(z){super("Failed to refresh authentication token.",{cause:z});this.name="RefreshAccessTokenFailedError"}}});var f=Z((UG,Hz)=>{var{create:mz,defineProperty:V,getOwnPropertyDescriptor:nz,getOwnPropertyNames:rz,getPrototypeOf:tz}=Object,ez=Object.prototype.hasOwnProperty,oz=(z,G)=>{for(var H in G)V(z,H,{get:G[H],enumerable:!0})},o=(z,G,H,Q)=>{if(G&&typeof G==="object"||typeof G==="function"){for(let K of rz(G))if(!ez.call(z,K)&&K!==H)V(z,K,{get:()=>G[K],enumerable:!(Q=nz(G,K))||Q.enumerable})}return z},zz=(z,G,H)=>(H=z!=null?mz(tz(z)):{},o(G||!z||!z.__esModule?V(H,"default",{value:z,enumerable:!0}):H,z)),zG=(z)=>o(V({},"__esModule",{value:!0}),z),Gz={};oz(Gz,{assertVercelOidcTokenResponse:()=>M,findProjectInfo:()=>QG,getTokenPayload:()=>YG,getVercelDataDir:()=>GG,getVercelOidcToken:()=>KG,getVercelToken:()=>HG,isExpired:()=>ZG,loadToken:()=>XG,saveToken:()=>WG});Hz.exports=zG(Gz);var U=zz(W("path")),X=zz(W("fs")),v=R(),J=P(),$=i(),e=a(),q=t();function GG(){let G=(0,J.getUserDataDir)();if(!G)return null;return U.join(G,"com.vercel.cli")}async function HG(z){let G=(0,$.readAuthConfig)();if(!G?.token)throw new q.AccessTokenMissingError;if((0,$.isValidAccessToken)(G,z?.expirationBufferMs))return G.token;if(!G.refreshToken)throw(0,$.writeAuthConfig)({}),new q.RefreshAccessTokenFailedError("No refresh token available");try{let H=await(0,e.refreshTokenRequest)({refresh_token:G.refreshToken}),[Q,K]=await(0,e.processTokenResponse)(H);if(Q||!K)throw(0,$.writeAuthConfig)({}),new q.RefreshAccessTokenFailedError(Q);let Y={token:K.access_token,expiresAt:Math.floor(Date.now()/1000)+K.expires_in};if(K.refresh_token)Y.refreshToken=K.refresh_token;return(0,$.writeAuthConfig)(Y),Y.token}catch(H){if((0,$.writeAuthConfig)({}),H instanceof q.AccessTokenMissingError||H instanceof q.RefreshAccessTokenFailedError)throw H;throw new q.RefreshAccessTokenFailedError(H)}}async function KG(z,G,H){let Q=`https://api.vercel.com/v1/projects/${G}/token?source=vercel-oidc-refresh${H?`&teamId=${H}`:""}`,K=await fetch(Q,{method:"POST",headers:{Authorization:`Bearer ${z}`}});if(!K.ok)throw new v.VercelOidcTokenError(`Failed to refresh OIDC token: ${K.statusText}`);let Y=await K.json();return M(Y),Y}function M(z){if(!z||typeof z!=="object")throw TypeError("Vercel OIDC token is malformed. Expected an object. Please run `vc env pull` and try again");if(!("token"in z)||typeof z.token!=="string")throw TypeError("Vercel OIDC token is malformed. Expected a string-valued token property. Please run `vc env pull` and try again")}function QG(){let z=(0,J.findRootDir)();if(!z)throw new v.VercelOidcTokenError("Unable to find project root directory. Have you linked your project with `vc link?`");let G=U.join(z,".vercel","project.json");if(!X.existsSync(G))throw new v.VercelOidcTokenError("project.json not found, have you linked your project with `vc link?`");let H=JSON.parse(X.readFileSync(G,"utf8"));if(typeof H.projectId!=="string"&&typeof H.orgId!=="string")throw TypeError("Expected a string-valued projectId property. Try running `vc link` to re-link your project.");return{projectId:H.projectId,teamId:H.orgId}}function WG(z,G){let H=(0,J.getUserDataDir)();if(!H)throw new v.VercelOidcTokenError("Unable to find user data directory. Please reach out to Vercel support.");let Q=U.join(H,"com.vercel.token",`${G}.json`),K=JSON.stringify(z);X.mkdirSync(U.dirname(Q),{mode:504,recursive:!0}),X.writeFileSync(Q,K),X.chmodSync(Q,432);return}function XG(z){let G=(0,J.getUserDataDir)();if(!G)throw new v.VercelOidcTokenError("Unable to find user data directory. Please reach out to Vercel support.");let H=U.join(G,"com.vercel.token",`${z}.json`);if(!X.existsSync(H))return null;let Q=JSON.parse(X.readFileSync(H,"utf8"));return M(Q),Q}function YG(z){let G=z.split(".");if(G.length!==3)throw new v.VercelOidcTokenError("Invalid token. Please run `vc env pull` and try again");let H=G[1].replace(/-/g,"+").replace(/_/g,"/"),Q=H.padEnd(H.length+(4-H.length%4)%4,"=");return JSON.parse(Buffer.from(Q,"base64").toString("utf8"))}function ZG(z,G=0){return z.exp*1000<Date.now()+G}});
1
+ import{ta as Z,va as W}from"./index-xbq3aq6f.js";var R=Z(($G,E)=>{var{defineProperty:N,getOwnPropertyDescriptor:Kz,getOwnPropertyNames:Qz}=Object,Wz=Object.prototype.hasOwnProperty,Xz=(z,G)=>{for(var H in G)N(z,H,{get:G[H],enumerable:!0})},Yz=(z,G,H,Q)=>{if(G&&typeof G==="object"||typeof G==="function"){for(let K of Qz(G))if(!Wz.call(z,K)&&K!==H)N(z,K,{get:()=>G[K],enumerable:!(Q=Kz(G,K))||Q.enumerable})}return z},Zz=(z)=>Yz(N({},"__esModule",{value:!0}),z),O={};Xz(O,{VercelOidcTokenError:()=>S});E.exports=Zz(O);class S extends Error{constructor(z,G){super(z);this.name="VercelOidcTokenError",this.cause=G}toString(){if(this.cause)return`${this.name}: ${this.message}: ${this.cause}`;return`${this.name}: ${this.message}`}}});var P=Z((qG,y)=>{var{create:$z,defineProperty:L,getOwnPropertyDescriptor:qz,getOwnPropertyNames:vz,getPrototypeOf:Bz}=Object,Fz=Object.prototype.hasOwnProperty,Uz=(z,G)=>{for(var H in G)L(z,H,{get:G[H],enumerable:!0})},C=(z,G,H,Q)=>{if(G&&typeof G==="object"||typeof G==="function"){for(let K of vz(G))if(!Fz.call(z,K)&&K!==H)L(z,K,{get:()=>G[K],enumerable:!(Q=qz(G,K))||Q.enumerable})}return z},I=(z,G,H)=>(H=z!=null?$z(Bz(z)):{},C(G||!z||!z.__esModule?L(H,"default",{value:z,enumerable:!0}):H,z)),Lz=(z)=>C(L({},"__esModule",{value:!0}),z),x={};Uz(x,{findRootDir:()=>Jz,getUserDataDir:()=>Nz});y.exports=Lz(x);var B=I(W("path")),bz=I(W("fs")),A=I(W("os")),Vz=R();function Jz(){try{let z=process.cwd();while(z!==B.default.dirname(z)){let G=B.default.join(z,".vercel");if(bz.default.existsSync(G))return z;z=B.default.dirname(z)}}catch(z){throw new Vz.VercelOidcTokenError("Token refresh only supported in node server environments")}return null}function Nz(){if(process.env.XDG_DATA_HOME)return process.env.XDG_DATA_HOME;switch(A.default.platform()){case"darwin":return B.default.join(A.default.homedir(),"Library/Application Support");case"linux":return B.default.join(A.default.homedir(),".local/share");case"win32":if(process.env.LOCALAPPDATA)return process.env.LOCALAPPDATA;return null;default:return null}}});var i=Z((vG,c)=>{var{create:Rz,defineProperty:b,getOwnPropertyDescriptor:Az,getOwnPropertyNames:Iz,getPrototypeOf:Dz}=Object,wz=Object.prototype.hasOwnProperty,Tz=(z,G)=>{for(var H in G)b(z,H,{get:G[H],enumerable:!0})},u=(z,G,H,Q)=>{if(G&&typeof G==="object"||typeof G==="function"){for(let K of Iz(G))if(!wz.call(z,K)&&K!==H)b(z,K,{get:()=>G[K],enumerable:!(Q=Az(G,K))||Q.enumerable})}return z},l=(z,G,H)=>(H=z!=null?Rz(Dz(z)):{},u(G||!z||!z.__esModule?b(H,"default",{value:z,enumerable:!0}):H,z)),jz=(z)=>u(b({},"__esModule",{value:!0}),z),g={};Tz(g,{isValidAccessToken:()=>Ez,readAuthConfig:()=>Oz,writeAuthConfig:()=>Sz});c.exports=jz(g);var F=l(W("fs")),h=l(W("path")),Mz=f();function k(){let z=(0,Mz.getVercelDataDir)();if(!z)throw Error(`Unable to find Vercel CLI data directory. Your platform: ${process.platform}. Supported: darwin, linux, win32.`);return h.join(z,"auth.json")}function Oz(){try{let z=k();if(!F.existsSync(z))return null;let G=F.readFileSync(z,"utf8");if(!G)return null;return JSON.parse(G)}catch(z){return null}}function Sz(z){let G=k(),H=h.dirname(G);if(!F.existsSync(H))F.mkdirSync(H,{mode:504,recursive:!0});F.writeFileSync(G,JSON.stringify(z,null,2),{mode:384})}function Ez(z,G=0){if(!z.token)return!1;if(typeof z.expiresAt!=="number")return!0;let H=Math.floor(Date.now()/1000),Q=G/1000;return z.expiresAt>=H+Q}});var a=Z((BG,s)=>{var{defineProperty:T,getOwnPropertyDescriptor:Cz,getOwnPropertyNames:xz}=Object,yz=Object.prototype.hasOwnProperty,Pz=(z,G)=>{for(var H in G)T(z,H,{get:G[H],enumerable:!0})},uz=(z,G,H,Q)=>{if(G&&typeof G==="object"||typeof G==="function"){for(let K of xz(G))if(!yz.call(z,K)&&K!==H)T(z,K,{get:()=>G[K],enumerable:!(Q=Cz(G,K))||Q.enumerable})}return z},lz=(z)=>uz(T({},"__esModule",{value:!0}),z),d={};Pz(d,{processTokenResponse:()=>iz,refreshTokenRequest:()=>cz});s.exports=lz(d);var D=W("os"),gz="https://vercel.com",hz="cl_HYyOPBNtFMfHhaUn9L4QPfTZz6TP47bp",p=`@vercel/oidc node-${process.version} ${(0,D.platform)()} (${(0,D.arch)()}) ${(0,D.hostname)()}`,w=null;async function kz(){if(w)return w;let z=`${gz}/.well-known/openid-configuration`,G=await fetch(z,{headers:{"user-agent":p}});if(!G.ok)throw Error("Failed to discover OAuth endpoints");let H=await G.json();if(!H||typeof H.token_endpoint!=="string")throw Error("Invalid OAuth discovery response");let Q=H.token_endpoint;return w=Q,Q}async function cz(z){let G=await kz();return await fetch(G,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded","user-agent":p},body:new URLSearchParams({client_id:hz,grant_type:"refresh_token",...z})})}async function iz(z){let G=await z.json();if(!z.ok){let H=typeof G==="object"&&G&&"error"in G?String(G.error):"Token refresh failed";return[Error(H)]}if(typeof G!=="object"||G===null)return[Error("Invalid token response")];if(typeof G.access_token!=="string")return[Error("Missing access_token in response")];if(G.token_type!=="Bearer")return[Error("Invalid token_type in response")];if(typeof G.expires_in!=="number")return[Error("Missing expires_in in response")];return[null,G]}});var t=Z((FG,r)=>{var{defineProperty:j,getOwnPropertyDescriptor:fz,getOwnPropertyNames:dz}=Object,pz=Object.prototype.hasOwnProperty,sz=(z,G)=>{for(var H in G)j(z,H,{get:G[H],enumerable:!0})},az=(z,G,H,Q)=>{if(G&&typeof G==="object"||typeof G==="function"){for(let K of dz(G))if(!pz.call(z,K)&&K!==H)j(z,K,{get:()=>G[K],enumerable:!(Q=fz(G,K))||Q.enumerable})}return z},_z=(z)=>az(j({},"__esModule",{value:!0}),z),_={};sz(_,{AccessTokenMissingError:()=>m,RefreshAccessTokenFailedError:()=>n});r.exports=_z(_);class m extends Error{constructor(){super("No authentication found. Please log in with the Vercel CLI (vercel login).");this.name="AccessTokenMissingError"}}class n extends Error{constructor(z){super("Failed to refresh authentication token.",{cause:z});this.name="RefreshAccessTokenFailedError"}}});var f=Z((UG,Hz)=>{var{create:mz,defineProperty:V,getOwnPropertyDescriptor:nz,getOwnPropertyNames:rz,getPrototypeOf:tz}=Object,ez=Object.prototype.hasOwnProperty,oz=(z,G)=>{for(var H in G)V(z,H,{get:G[H],enumerable:!0})},o=(z,G,H,Q)=>{if(G&&typeof G==="object"||typeof G==="function"){for(let K of rz(G))if(!ez.call(z,K)&&K!==H)V(z,K,{get:()=>G[K],enumerable:!(Q=nz(G,K))||Q.enumerable})}return z},zz=(z,G,H)=>(H=z!=null?mz(tz(z)):{},o(G||!z||!z.__esModule?V(H,"default",{value:z,enumerable:!0}):H,z)),zG=(z)=>o(V({},"__esModule",{value:!0}),z),Gz={};oz(Gz,{assertVercelOidcTokenResponse:()=>M,findProjectInfo:()=>QG,getTokenPayload:()=>YG,getVercelDataDir:()=>GG,getVercelOidcToken:()=>KG,getVercelToken:()=>HG,isExpired:()=>ZG,loadToken:()=>XG,saveToken:()=>WG});Hz.exports=zG(Gz);var U=zz(W("path")),X=zz(W("fs")),v=R(),J=P(),$=i(),e=a(),q=t();function GG(){let G=(0,J.getUserDataDir)();if(!G)return null;return U.join(G,"com.vercel.cli")}async function HG(z){let G=(0,$.readAuthConfig)();if(!G?.token)throw new q.AccessTokenMissingError;if((0,$.isValidAccessToken)(G,z?.expirationBufferMs))return G.token;if(!G.refreshToken)throw(0,$.writeAuthConfig)({}),new q.RefreshAccessTokenFailedError("No refresh token available");try{let H=await(0,e.refreshTokenRequest)({refresh_token:G.refreshToken}),[Q,K]=await(0,e.processTokenResponse)(H);if(Q||!K)throw(0,$.writeAuthConfig)({}),new q.RefreshAccessTokenFailedError(Q);let Y={token:K.access_token,expiresAt:Math.floor(Date.now()/1000)+K.expires_in};if(K.refresh_token)Y.refreshToken=K.refresh_token;return(0,$.writeAuthConfig)(Y),Y.token}catch(H){if((0,$.writeAuthConfig)({}),H instanceof q.AccessTokenMissingError||H instanceof q.RefreshAccessTokenFailedError)throw H;throw new q.RefreshAccessTokenFailedError(H)}}async function KG(z,G,H){let Q=`https://api.vercel.com/v1/projects/${G}/token?source=vercel-oidc-refresh${H?`&teamId=${H}`:""}`,K=await fetch(Q,{method:"POST",headers:{Authorization:`Bearer ${z}`}});if(!K.ok)throw new v.VercelOidcTokenError(`Failed to refresh OIDC token: ${K.statusText}`);let Y=await K.json();return M(Y),Y}function M(z){if(!z||typeof z!=="object")throw TypeError("Vercel OIDC token is malformed. Expected an object. Please run `vc env pull` and try again");if(!("token"in z)||typeof z.token!=="string")throw TypeError("Vercel OIDC token is malformed. Expected a string-valued token property. Please run `vc env pull` and try again")}function QG(){let z=(0,J.findRootDir)();if(!z)throw new v.VercelOidcTokenError("Unable to find project root directory. Have you linked your project with `vc link?`");let G=U.join(z,".vercel","project.json");if(!X.existsSync(G))throw new v.VercelOidcTokenError("project.json not found, have you linked your project with `vc link?`");let H=JSON.parse(X.readFileSync(G,"utf8"));if(typeof H.projectId!=="string"&&typeof H.orgId!=="string")throw TypeError("Expected a string-valued projectId property. Try running `vc link` to re-link your project.");return{projectId:H.projectId,teamId:H.orgId}}function WG(z,G){let H=(0,J.getUserDataDir)();if(!H)throw new v.VercelOidcTokenError("Unable to find user data directory. Please reach out to Vercel support.");let Q=U.join(H,"com.vercel.token",`${G}.json`),K=JSON.stringify(z);X.mkdirSync(U.dirname(Q),{mode:504,recursive:!0}),X.writeFileSync(Q,K),X.chmodSync(Q,432);return}function XG(z){let G=(0,J.getUserDataDir)();if(!G)throw new v.VercelOidcTokenError("Unable to find user data directory. Please reach out to Vercel support.");let H=U.join(G,"com.vercel.token",`${z}.json`);if(!X.existsSync(H))return null;let Q=JSON.parse(X.readFileSync(H,"utf8"));return M(Q),Q}function YG(z){let G=z.split(".");if(G.length!==3)throw new v.VercelOidcTokenError("Invalid token. Please run `vc env pull` and try again");let H=G[1].replace(/-/g,"+").replace(/_/g,"/"),Q=H.padEnd(H.length+(4-H.length%4)%4,"=");return JSON.parse(Buffer.from(Q,"base64").toString("utf8"))}function ZG(z,G=0){return z.exp*1000<Date.now()+G}});
2
2
  export{R as a,f as b};
@@ -0,0 +1,7 @@
1
+ import{appendFileSync as c,chmodSync as l,existsSync as R,renameSync as m,statSync as i}from"node:fs";import{tmpdir as a}from"node:os";import{join as n}from"node:path";var q={error:0,warn:1,info:2,debug:3,trace:4},t=!1,o=5242880;function h(){return process.env.OPENCODE_OPENAI_AUTH_LOG_FILE??n(a(),"opencode-openai-auth.log")}var S;function _H(H){if(H===void 0||H in q)S=H}function r(){if(S)return S;let H=process.env.OPENCODE_OPENAI_AUTH_LOG_LEVEL;if(H&&H in q)return H;return"info"}var e=/^(authorization|x-api-key|cookie|set-cookie|refresh|access|token)$/i;function HH(H){if(e.test(H))return!0;let J=H.toLowerCase().replace(/[-_]/g,"");if(J==="chatgptaccountid")return!0;if(J.includes("apikey"))return!0;if(J.endsWith("secret")||J.endsWith("password"))return!0;if(J.endsWith("token")&&!J.endsWith("tokens"))return!0;return!1}var JH=/\b(Bearer\s+[\w.-]+|sk-[\w-]+|eyJ[\w.-]+)\b/g;function QH(H){return g(H,new WeakSet)}function g(H,J){if(typeof H==="string")return H.replace(JH,"***REDACTED***");if(Array.isArray(H)){if(J.has(H))return"[Circular]";J.add(H);let Q=H.map((Z)=>g(Z,J));return J.delete(H),Q}if(H&&typeof H==="object"){if(J.has(H))return"[Circular]";J.add(H);let Q={};for(let[Z,B]of Object.entries(H))Q[Z]=HH(Z)?"***REDACTED***":g(B,J);return J.delete(H),Q}return H}var D=[],A,WH=3;function I(H){try{l(H,384)}catch{}}function ZH(){try{let H=h();if(!(R(H)&&i(H).size>o))return;for(let Q=WH-1;Q>=1;Q--)if(R(`${H}.${Q}`)){let Z=`${H}.${Q+1}`;m(`${H}.${Q}`,Z),I(Z)}let J=`${H}.1`;m(H,J),I(J)}catch{}}function O(){if(!D.length)return;let H=D.join("");D=[];try{ZH();let J=h();if(R(J))I(J);c(J,H,{encoding:"utf8",mode:384})}catch{}}function $H(){if(!A)A=setTimeout(()=>{A=void 0,O()},500)}if(!t)process.on("exit",O);function zH(H){try{return` ${JSON.stringify(QH(H))}`}catch{return" [unserializable]"}}function j(H,J,Q,Z){if(q[J]>q[r()])return;let B=`[${new Date().toISOString()}] ${J.toUpperCase()} [${H}] ${Q}`+(Z===void 0?"":zH(Z))+`
2
+ `;if(D.push(B),D.length>=50)O();else $H()}function FH(H){return{error:(J,Q)=>j(H,"error",J,Q),warn:(J,Q)=>j(H,"warn",J,Q),info:(J,Q)=>j(H,"info",J,Q),debug:(J,Q)=>j(H,"debug",J,Q),trace:(J,Q)=>j(H,"trace",J,Q)}}import{randomUUID as T}from"node:crypto";import{mkdir as u,readFile as y,rename as BH,rm as b,stat as v,writeFile as C}from"node:fs/promises";import{homedir as GH}from"node:os";import{dirname as VH,join as N}from"node:path";var XH=globalThis.setTimeout.bind(globalThis),YH=globalThis.clearTimeout.bind(globalThis),KH="openai-auth.json";function xH(){if(process.env.OPENCODE_CONFIG_DIR?.trim())return process.env.OPENCODE_CONFIG_DIR.trim();return N(process.env.XDG_CONFIG_HOME||N(GH(),".config"),"opencode")}function jH(H){let J=H?.code;return J==="ENOENT"||J==="EINVAL"||J==="ENOTDIR"}function DH(){return process.env.OPENCODE_OPENAI_AUTH_FILE?.trim()||N(xH(),KH)}async function gH(H){let Q=`${H.path??DH()}.${H.name}.lock`,Z=N(Q,"owner.json"),B=T(),G=H.now??Date.now,Y=null,_=!1;async function F(){try{return JSON.parse(await y(Q,"utf8"))}catch(W){if(W.code!=="EISDIR")throw W;return JSON.parse(await y(Z,"utf8"))}}async function d(){await C(Q,`${JSON.stringify({ownerId:B,expiresAt:G()+H.ttlMs})}
3
+ `,{encoding:"utf8",mode:384})}async function L(){try{return await C(Q,`${JSON.stringify({ownerId:B,expiresAt:G()+H.ttlMs})}
4
+ `,{encoding:"utf8",mode:384,flag:"wx"}),!0}catch(W){let z=W.code;if(z==="EEXIST"||z==="EISDIR")return!1;if(z==="ENOENT"){await u(VH(Q),{recursive:!0});try{return await C(Q,`${JSON.stringify({ownerId:B,expiresAt:G()+H.ttlMs})}
5
+ `,{encoding:"utf8",mode:384,flag:"wx"}),!0}catch(X){let M=X.code;if(M==="EEXIST"||M==="EISDIR")return!1;throw X}}throw W}}function P(){if(!H.renew||_)return;let W=H.renewIntervalMs??Math.max(1000,Math.floor(H.ttlMs/3));if(Y=XH(()=>{(async()=>{try{let z=await F(),X=G();if(_||z?.ownerId!==B||Number(z?.expiresAt)<=X)return;await d(),P()}catch{}})()},W),"unref"in Y)Y.unref()}let V=await L();if(!V){let W=`${Q}.evicting`,z=N(W,"owner.json"),X=T(),M=5000,bH=8;async function U(){await new Promise(($)=>setTimeout($,Math.floor(Math.random()*4)))}async function E(){try{let $=await F();return Number($?.expiresAt)>G()}catch{try{return(await v(Q)).mtimeMs+H.ttlMs>G()}catch{return!1}}}async function K(){try{return JSON.parse(await y(z,"utf8"))?.ownerId===X}catch{return!1}}async function s(){await u(W);try{await C(z,`${JSON.stringify({ownerId:X,createdAt:G()})}
6
+ `,{encoding:"utf8",mode:384,flag:"wx"})}catch($){if(jH($))return!1;throw await p(),$}return await H.onStep?.("eviction-marker-acquired"),!0}async function p(){if(await K())await b(W,{recursive:!0,force:!0}).catch(()=>{})}for(let $=0;$<8;$++){if(V=await L(),V)break;if(await E())return null;try{if(!await s()){await U();continue}}catch(k){if(k.code!=="EEXIST")throw k;let f;try{f=await v(W)}catch(x){if(x.code==="ENOENT"){await U();continue}throw x}if(f.mtimeMs+5000>G())return null;await H.onStep?.("stale-marker-stat");let w=`${W}.${T()}`;try{await BH(W,w)}catch(x){if(x.code==="ENOENT"){await U();continue}throw x}await H.onStep?.("stale-marker-claimed"),await b(w,{recursive:!0,force:!0}).catch(()=>{}),await U();continue}try{if(await E())return null;if(!await K())return null;if(await H.onStep?.("stale-lock-confirmed"),!await K())return null;if(await b(Q,{recursive:!0,force:!0}).catch(()=>{}),!await K())return null;if(V=await L(),!V)return null;if(!await K())return await b(Q,{recursive:!0,force:!0}).catch(()=>{}),V=!1,null;break}finally{await p()}}}if(!V)return null;return P(),{release:async()=>{if(_=!0,Y)YH(Y),Y=null;try{if((await F())?.ownerId!==B)return}catch{return}await b(Q,{recursive:!0,force:!0}).catch(()=>{})}}}
7
+ export{_H as ka,QH as la,FH as ma,gH as na};