@cortexkit/opencode-openai-auth 0.6.2 → 0.6.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.
- package/dist/cli.js +7 -7
- package/dist/core/account-paths.d.ts +25 -0
- package/dist/core/accounts.d.ts +31 -5
- package/dist/core/oauth.d.ts +1 -1
- package/dist/core/refresh-file-lock.d.ts +1 -5
- package/dist/{index-e08r33g5.js → index-00rp531h.js} +2 -2
- package/dist/{index-dz9a4xwy.js → index-4agbg1ec.js} +1 -1
- package/dist/{index-nwy7ec7p.js → index-7tsnfb8g.js} +1 -1
- package/dist/{index-hxpv25e8.js → index-80gqxa1f.js} +1 -1
- package/dist/index-8f1200qx.js +6 -0
- package/dist/index-ng315c61.js +89 -0
- package/dist/{index-s2vhsb2v.js → index-x55z0b3y.js} +1 -1
- package/dist/{index-meg0ng0z.js → index-zbpt7v1a.js} +1 -1
- package/dist/index.js +91 -91
- package/dist/{quota-normalize-vf2pj6n7.js → quota-normalize-s27mex1w.js} +1 -1
- package/dist/rpc/port-file.js +1 -1
- package/dist/rpc/rpc-client.js +1 -1
- package/dist/rpc/rpc-dir.js +1 -1
- package/dist/sidebar-state.js +1 -1
- package/dist/{token-esc14v6e.js → token-tag90anp.js} +1 -1
- package/dist/token-util-by7nbdh3.js +1 -0
- package/dist/tui-preferences.js +1 -1
- package/dist/version.d.ts +1 -1
- package/package.json +2 -1
- package/src/core/account-paths.ts +103 -0
- package/src/core/refresh-file-lock.ts +217 -145
- package/src/tui-compiled/core/account-paths.ts +103 -0
- package/src/tui-compiled/core/refresh-file-lock.ts +217 -145
- package/dist/index-n00ybbbq.js +0 -6
- package/dist/index-srgn00yp.js +0 -89
- package/dist/token-util-qkpkvy5t.js +0 -1
package/dist/cli.js
CHANGED
|
@@ -1,15 +1,15 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{
|
|
2
|
+
import{J as C,K as E,L as X,r as $,y as q,z as B}from"./index-ng315c61.js";import{ua as Y}from"./index-8f1200qx.js";import"./index-80gqxa1f.js";import{Ja as Z}from"./index-x55z0b3y.js";import{execFileSync as U}from"node:child_process";function V(z,K=process.platform,H=U){try{if(K==="win32"){H("cmd",["/c","start","",z],{stdio:"ignore",timeout:3000});return}H(K==="darwin"?"open":"xdg-open",[z],{stdio:"ignore",timeout:3000})}catch{}}function W(){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>
|
|
6
6
|
|
|
7
7
|
Fallback accounts are stored in:
|
|
8
|
-
${
|
|
9
|
-
Error: ${
|
|
8
|
+
${Y()}`)}function P(z){let K=[],H={};for(let N=0;N<z.length;N++){let j=z[N];if(!j)continue;if(j.startsWith("--")){let J=j.slice(2),D=z[N+1];if(D&&!D.startsWith("--"))H[J]=D,N++;else H[J]=!0}else K.push(j)}return{positional:K,flags:H}}async function R(){let{positional:z,flags:K}=P(process.argv.slice(2)),[H,...N]=z;if(!H||H==="help")W(),process.exit(0);switch(H){case"login":{let j=typeof K.label==="string"?K.label:void 0,J=Boolean(K.headless);try{$(j)}catch(G){console.error(`
|
|
9
|
+
Error: ${G instanceof Error?G.message:String(G)}`),process.exit(1)}let{url:D,instructions:M,completion:T}=await B({label:j,headless:J});if(console.log(`
|
|
10
10
|
Open this URL in your browser and complete sign-in:
|
|
11
|
-
`),console.log(`${
|
|
12
|
-
`),
|
|
13
|
-
`);
|
|
11
|
+
`),console.log(`${D}
|
|
12
|
+
`),M)console.log(`${M}
|
|
13
|
+
`);V(D);let O=await T,Q=!1;if(await X((G)=>{if(O.accountId&&G.mainAccountId&&O.accountId===G.mainAccountId)return Q=!0,G;return q(G.accounts,O),G}),Q)console.error(`
|
|
14
14
|
Error: that account is already your main (same ChatGPT account).`),console.error("A self-fallback would retry on the account that just returned 429."),process.exit(1);if(console.log(`
|
|
15
|
-
✓ Added account ${
|
|
15
|
+
✓ Added account ${O.id}`),O.label)console.log(` Label: ${O.label}`);break}case"list":{let j=await E();if(!j||j.accounts.length===0)console.log("No fallback accounts configured.");else for(let J of j.accounts){let D=J.label,M=[` ${J.id}`];if(D)M.push(`(${D})`);M.push(J.enabled!==!1?"[enabled]":"[disabled]"),console.log(M.join(" "))}break}case"remove":{let j=N[0];if(!j)console.error("Error: remove requires an account ID."),W(),process.exit(1);let J=Y(),D=await C(J),M=D?D.has(j):!1,T=!1;if(await X((Q)=>{let G=Q.accounts.findIndex((L)=>L.id===j);if(G===-1)return Q;return Q.accounts.splice(G,1),T=!0,Q},J,{allowDrop:[j]}),!(T||M))console.error(`No account with id "${j}".`),process.exit(1);console.log(`Removed account ${j}.`);break}default:console.error(`Unknown command: ${H}`),W(),process.exit(1)}}if(Z.main==Z.module)R().catch((z)=>{console.error(z instanceof Error?z.message:String(z)),process.exit(1)});export{V as openBrowserForLogin};
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Where the account store lives.
|
|
3
|
+
*
|
|
4
|
+
* This is the ONLY definition. It used to be duplicated verbatim in both
|
|
5
|
+
* `accounts.ts` and `refresh-file-lock.ts`, because `accounts.ts` imports the
|
|
6
|
+
* lock and the reverse import would have been a cycle. Two copies of a path
|
|
7
|
+
* resolver is a bad trade for that: the lock and the write must agree on the
|
|
8
|
+
* exact file, and if the copies ever drifted, a writer would take a lock on one
|
|
9
|
+
* path while writing another — mutual exclusion silently lost on a file holding
|
|
10
|
+
* credentials. Nothing would fail a test, since each copy works on its own.
|
|
11
|
+
*
|
|
12
|
+
* This module imports nothing from either side, so both can depend on it.
|
|
13
|
+
*/
|
|
14
|
+
export declare const ACCOUNT_FILE_NAME = "openai-auth.json";
|
|
15
|
+
export declare const ACCOUNT_STATE_FILE_NAME = "openai-auth-state.json";
|
|
16
|
+
export declare function getAccountStoragePath(): string;
|
|
17
|
+
/** Derive the state-file path from the config path without reading env vars. */
|
|
18
|
+
export declare function deriveStatePath(configPath: string): string;
|
|
19
|
+
/**
|
|
20
|
+
* Detect path aliases without requiring either file to exist. This is defense
|
|
21
|
+
* in depth: hardlinks and bind mounts can still make distinct paths share a
|
|
22
|
+
* file, because neither is distinguishable through pathname identity.
|
|
23
|
+
*/
|
|
24
|
+
export declare function accountPathsCollide(configPath: string, statePath: string, platform?: NodeJS.Platform): boolean;
|
|
25
|
+
export declare function getAccountStatePath(configPath?: string): string;
|
package/dist/core/accounts.d.ts
CHANGED
|
@@ -1,9 +1,7 @@
|
|
|
1
|
+
import { ACCOUNT_FILE_NAME, ACCOUNT_STATE_FILE_NAME, deriveStatePath, getAccountStatePath, getAccountStoragePath } from './account-paths';
|
|
1
2
|
import type { ProviderQuotaFn, ProviderRefreshFn, QuotaWindowName } from './provider.ts';
|
|
2
3
|
import { PRIMARY, SECONDARY } from './provider.ts';
|
|
3
|
-
export
|
|
4
|
-
export declare const ACCOUNT_STATE_FILE_NAME = "openai-auth-state.json";
|
|
5
|
-
export declare function getAccountStoragePath(): string;
|
|
6
|
-
export declare function getAccountStatePath(configPath?: string): string;
|
|
4
|
+
export { ACCOUNT_FILE_NAME, ACCOUNT_STATE_FILE_NAME, deriveStatePath, getAccountStatePath, getAccountStoragePath, };
|
|
7
5
|
export type { QuotaWindowName };
|
|
8
6
|
export { PRIMARY, SECONDARY };
|
|
9
7
|
export type AccountQuotaWindow = {
|
|
@@ -184,6 +182,17 @@ export declare const DEFAULT_KILLSWITCH_THRESHOLDS: {
|
|
|
184
182
|
secondary: number;
|
|
185
183
|
};
|
|
186
184
|
export declare function isSafeResetAccountKey(accountKey: string): boolean;
|
|
185
|
+
/**
|
|
186
|
+
* The set of account ids present in the CONFIG file (the authoritative account
|
|
187
|
+
* roster). Returns null when the config is absent or unreadable/malformed, so
|
|
188
|
+
* callers can fall back to non-pruning behavior rather than risk wiping live
|
|
189
|
+
* state. The config never holds secrets (see accountConfig), so reading it here
|
|
190
|
+
* is safe. Reads are lock-free but the file is written atomically, so a
|
|
191
|
+
* concurrent write is seen as either the complete old or complete new file.
|
|
192
|
+
*
|
|
193
|
+
* Trims and skips blank ids per the rule in collectConfigRosterIds above.
|
|
194
|
+
*/
|
|
195
|
+
export declare function readConfigRosterIds(path: string): Promise<Set<string> | null>;
|
|
187
196
|
export declare function loadAccounts(path?: string): Promise<AccountStorage | null>;
|
|
188
197
|
export declare function saveAccounts(storage: AccountStorage, path?: string): Promise<void>;
|
|
189
198
|
/**
|
|
@@ -201,8 +210,25 @@ export declare function saveAccounts(storage: AccountStorage, path?: string): Pr
|
|
|
201
210
|
* The mutator may edit `current` in place and return it, or return a new
|
|
202
211
|
* storage object. Returning undefined means "no change" and still rewrites the
|
|
203
212
|
* freshly-read state (a harmless idempotent write).
|
|
213
|
+
*
|
|
214
|
+
* Load-time drop preservation: if normalizeAccount (called inside
|
|
215
|
+
* normalizeStorage) rejects an account whose id IS in the raw config roster,
|
|
216
|
+
* the previous behavior would erase that id silently on the next write. This
|
|
217
|
+
* function now carries the dropped raw entry through to the written config
|
|
218
|
+
* verbatim, so the on-disk state always matches the operator's intent (an
|
|
219
|
+
* account they added, even if temporarily un-loadable, stays in their list
|
|
220
|
+
* until they deliberately remove it).
|
|
221
|
+
*
|
|
222
|
+
* Removal seam: when the caller knows they are removing an id (e.g. the CLI
|
|
223
|
+
* `remove` command) and that id may be load-dropped — in which case the
|
|
224
|
+
* mutator cannot find it in `current.accounts` to splice it — the caller can
|
|
225
|
+
* pass `options.allowDrop: [id]`. Ids in `allowDrop` are NOT preserved; the
|
|
226
|
+
* mutator's splice still no-ops on a dropped id, but the absence of
|
|
227
|
+
* preservation completes the removal end-to-end.
|
|
204
228
|
*/
|
|
205
|
-
export declare function mutateAccounts(mutate: (current: AccountStorage) => AccountStorage | undefined, path?: string
|
|
229
|
+
export declare function mutateAccounts(mutate: (current: AccountStorage) => AccountStorage | undefined, path?: string, options?: {
|
|
230
|
+
allowDrop?: readonly string[];
|
|
231
|
+
}): Promise<AccountStorage>;
|
|
206
232
|
export declare function saveAccountState(storage: AccountStorage, path?: string, scope?: AccountStateSaveScope): Promise<void>;
|
|
207
233
|
export declare function shouldFallbackStatus(status: number, storage: AccountStorage | null): boolean;
|
|
208
234
|
export declare function quotaSnapshotPassesPolicy(quota: OAuthQuotaSnapshot | undefined, storage: AccountStorage | null, now?: number): boolean;
|
package/dist/core/oauth.d.ts
CHANGED
|
@@ -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.6.
|
|
5
|
+
export declare const USER_AGENT = "cortexkit-opencode-openai-auth/0.6.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 {
|
|
@@ -1,8 +1,4 @@
|
|
|
1
|
-
export declare const ACCOUNT_FILE_NAME = "openai-auth.json";
|
|
2
|
-
export declare const ACCOUNT_STATE_FILE_NAME = "openai-auth-state.json";
|
|
3
1
|
export declare function isLostMarkerRaceError(error: unknown): boolean;
|
|
4
|
-
export declare function getAccountStoragePath(): string;
|
|
5
|
-
export declare function getAccountStatePath(configPath?: string): string;
|
|
6
2
|
export declare function acquireRefreshFileLock(options: {
|
|
7
3
|
name: string;
|
|
8
4
|
ttlMs: number;
|
|
@@ -10,7 +6,7 @@ export declare function acquireRefreshFileLock(options: {
|
|
|
10
6
|
now?: () => number;
|
|
11
7
|
renew?: boolean;
|
|
12
8
|
renewIntervalMs?: number;
|
|
13
|
-
onStep?: (step: 'stale-marker-stat' | 'stale-marker-claimed' | 'stale-lock-confirmed' | 'eviction-marker-acquired') => void | Promise<void>;
|
|
9
|
+
onStep?: (step: 'stale-marker-stat' | 'stale-marker-claimed' | 'stale-lock-confirmed' | 'eviction-marker-acquired' | 'renewal-owner-confirmed' | 'renewal-marker-unavailable' | 'renewal-write-fenced' | 'renewal-write-ready' | 'relinquish-read' | 'renewal-finished' | 'release-owner-confirmed') => void | Promise<void>;
|
|
14
10
|
}): Promise<{
|
|
15
11
|
release: () => Promise<void>;
|
|
16
12
|
} | null>;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
2
|
-
export{w as
|
|
1
|
+
import{Ca as _}from"./index-80gqxa1f.js";import{chmod as L,mkdir as M,readdir as W,readFile as $,rename as R,rmdir as S,unlink as X,writeFile as U}from"node:fs/promises";import{join as N,resolve as Y}from"node:path";var A=_("rpc");function E(q){try{return process.kill(q,0),!0}catch(H){return H.code==="EPERM"}}function C(q){return/^(?:openai-auth-)?[0-9a-f]{16}$/.test(q)}function O(q){return q!==null&&typeof q==="object"&&!Array.isArray(q)&&typeof q.pid==="number"&&Number.isFinite(q.pid)&&typeof q.port==="number"&&Number.isFinite(q.port)}async function Z(q){A.debug("rpc corrupt port file",{pid:process.pid,portFile:q}),await X(q).catch(()=>{})}async function w(q,H,I={}){let J=async()=>{if(await M(q,{recursive:!0,mode:I.secureDir?448:void 0}),I.secureDir)await L(q,448);await I.beforeWrite?.();let z={...H,startedAt:Date.now()},K=N(q,`port-${H.pid}.json`),B=`${K}.${process.pid}.tmp`;return await U(B,JSON.stringify(z),{encoding:"utf8",mode:384}),await R(B,K),K};try{return await J()}catch(z){if(z.code==="ENOENT")return await J();throw z}}async function x(q,H){let I;try{I=await W(q,{withFileTypes:!0})}catch(z){if(z.code==="ENOENT")return;throw z}let J=Y(H);for(let z of I){if(!z.isDirectory()||!C(z.name))continue;let K=N(q,z.name),B;try{B=await W(K)}catch(G){if(G.code==="ENOENT")continue;throw G}for(let G of B){if(!G.startsWith("port-")||!G.endsWith(".json"))continue;let Q=N(K,G),T;try{T=await $(Q,"utf8")}catch{continue}if(T===void 0)continue;let V;try{V=JSON.parse(T)}catch{await Z(Q);continue}if(!O(V)){await Z(Q);continue}if(!E(V.pid))await X(Q).catch(()=>{})}if(Y(K)!==J)await S(K).catch(()=>{})}}async function y(q,H){let I;try{I=await W(q)}catch{return null}let J=[];for(let B of I){if(!B.startsWith("port-")||!B.endsWith(".json"))continue;try{let G=JSON.parse(await $(N(q,B),"utf8"));if(Number.isFinite(G.port))if(E(G.pid))J.push(G);else X(N(q,B)).catch(()=>{})}catch{}}if(J.length===0)return null;let z=H!==void 0&&H>=1?J.filter((B)=>B.pid===H):[];return(z.length>0?z:J).sort((B,G)=>G.startedAt-B.startedAt)[0]??null}
|
|
2
|
+
export{w as xa,x as ya,y as za};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createHash as B}from"node:crypto";import{homedir as F,tmpdir as Q}from"node:os";import{dirname as G,join as w,resolve as z}from"node:path";var A="OPENCODE_OPENAI_AUTH_RPC_DIR";function J(k){return B("sha256").update(k).digest("hex").slice(0,16)}function K(){let k=process.env.XDG_STATE_HOME||w(F(),".local","state");return w(k,"cortexkit","openai-auth","rpc")}function L(k){let q=process.env[A]?.trim();if(q)return z(k,q);return w(K(),`openai-auth-${J(k)}`)}async function T(k){let q=process.env[A]?.trim();if(q)return{dir:z(k,q),secureDir:!1};let x=L(k);return{dir:x,secureDir:!0,sweepRoot:G(x)}}export{Q as
|
|
1
|
+
import{createHash as B}from"node:crypto";import{homedir as F,tmpdir as Q}from"node:os";import{dirname as G,join as w,resolve as z}from"node:path";var A="OPENCODE_OPENAI_AUTH_RPC_DIR";function J(k){return B("sha256").update(k).digest("hex").slice(0,16)}function K(){let k=process.env.XDG_STATE_HOME||w(F(),".local","state");return w(k,"cortexkit","openai-auth","rpc")}function L(k){let q=process.env[A]?.trim();if(q)return z(k,q);return w(K(),`openai-auth-${J(k)}`)}async function T(k){let q=process.env[A]?.trim();if(q)return{dir:z(k,q),secureDir:!1};let x=L(k);return{dir:x,secureDir:!0,sweepRoot:G(x)}}export{Q as Da,L as Ea,T as Fa};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Ha as Z,Ja as W}from"./index-x55z0b3y.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};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
import{appendFileSync as Y,chmodSync as w,existsSync as B,renameSync as N,statSync as C}from"node:fs";import{tmpdir as F}from"node:os";import{join as x}from"node:path";var $={error:0,warn:1,info:2,debug:3,trace:4},A=!1,D=5242880;function X(){return process.env.OPENCODE_OPENAI_AUTH_LOG_FILE??x(F(),"opencode-openai-auth.log")}var G;function k(q){if(q===void 0||q in $)G=q}function I(){if(G)return G;let q=process.env.OPENCODE_OPENAI_AUTH_LOG_LEVEL;if(q&&q in $)return q;return"info"}var K=/^(authorization|x-api-key|cookie|set-cookie|refresh|access|token)$/i;function b(q){if(K.test(q))return!0;let H=q.toLowerCase().replace(/[-_]/g,"");if(H==="chatgptaccountid")return!0;if(H.includes("apikey"))return!0;if(H.endsWith("secret")||H.endsWith("password"))return!0;if(H.endsWith("token")&&!H.endsWith("tokens"))return!0;return!1}var L=/\b(Bearer\s+[\w.-]+|sk-[\w-]+|eyJ[\w.-]+)\b/g;function P(q){return M(q,new WeakSet)}function M(q,H){if(typeof q==="string")return q.replace(L,"***REDACTED***");if(Array.isArray(q)){if(H.has(q))return"[Circular]";H.add(q);let J=q.map((Q)=>M(Q,H));return H.delete(q),J}if(q&&typeof q==="object"){if(H.has(q))return"[Circular]";H.add(q);let J={};for(let[Q,j]of Object.entries(q))J[Q]=b(Q)?"***REDACTED***":M(j,H);return H.delete(q),J}return q}var Z=[],z,_=3;function U(q){try{w(q,384)}catch{}}function g(){try{let q=X();if(!(B(q)&&C(q).size>D))return;for(let J=_-1;J>=1;J--)if(B(`${q}.${J}`)){let Q=`${q}.${J+1}`;N(`${q}.${J}`,Q),U(Q)}let H=`${q}.1`;N(q,H),U(H)}catch{}}function V(){if(!Z.length)return;let q=Z.join("");Z=[];try{g();let H=X();if(B(H))U(H);Y(H,q,{encoding:"utf8",mode:384})}catch{}}function O(){if(!z)z=setTimeout(()=>{z=void 0,V()},500)}if(!A)process.on("exit",V);function p(q){try{return` ${JSON.stringify(P(q))}`}catch{return" [unserializable]"}}function W(q,H,J,Q){if($[H]>$[I()])return;let j=`[${new Date().toISOString()}] ${H.toUpperCase()} [${q}] ${J}`+(Q===void 0?"":p(Q))+`
|
|
2
2
|
`;if(Z.push(j),Z.length>=50)V();else O()}function y(q){return{error:(H,J)=>W(q,"error",H,J),warn:(H,J)=>W(q,"warn",H,J),info:(H,J)=>W(q,"info",H,J),debug:(H,J)=>W(q,"debug",H,J),trace:(H,J)=>W(q,"trace",H,J)}}
|
|
3
|
-
export{k as
|
|
3
|
+
export{k as Aa,P as Ba,y as Ca};
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import{realpathSync as k}from"node:fs";import{homedir as i}from"node:os";import{basename as P,dirname as m,join as D,resolve as w}from"node:path";var d="openai-auth.json",r="openai-auth-state.json";function t(){if(process.env.OPENCODE_CONFIG_DIR?.trim())return process.env.OPENCODE_CONFIG_DIR.trim();return D(process.env.XDG_CONFIG_HOME||D(i(),".config"),"opencode")}function C(){return process.env.OPENCODE_OPENAI_AUTH_FILE?.trim()||D(t(),d)}function e(B){return P(B)===d?D(m(B),r):`${B}.state.json`}function q(B,Q){let J=w(B);return Q==="win32"||Q==="darwin"?J.toLowerCase():J}function f(B){try{return k.native(B)}catch{try{return D(k.native(m(B)),P(B))}catch{return}}}function o(B,Q,J=process.platform){if(q(B,J)===q(Q,J))return!0;let j=f(B),W=f(Q);return j!==void 0&&W!==void 0&&q(j,J)===q(W,J)}function ZB(B=C()){let Q=process.env.OPENCODE_OPENAI_AUTH_STATE_FILE?.trim();if(Q){if(o(B,Q))throw Error(`OPENCODE_OPENAI_AUTH_STATE_FILE resolves to the config path (${w(B)}). Set OPENCODE_OPENAI_AUTH_STATE_FILE to a different file.`);return Q}return e(B)}import{randomUUID as y}from"node:crypto";import{mkdir as h,readFile as F,rename as BB,rm as x,stat as l,writeFile as L}from"node:fs/promises";import{dirname as GB,join as p}from"node:path";var HB=globalThis.setTimeout.bind(globalThis),JB=globalThis.clearTimeout.bind(globalThis);function KB(B){let Q=B?.code;return Q==="ENOENT"||Q==="EINVAL"||Q==="ENOTDIR"}async function DB(B){let J=`${B.path??C()}.${B.name}.lock`,j=p(J,"owner.json"),W=y(),Z=B.now??Date.now,X=null,$=!1,N=null,z=`${J}.evicting`,A=p(z,"owner.json"),I=y(),c=5000,O=8;async function b(){try{return JSON.parse(await F(J,"utf8"))}catch(G){if(G.code!=="EISDIR")throw G;return JSON.parse(await F(j,"utf8"))}}async function s(){await L(J,`${JSON.stringify({ownerId:W,expiresAt:Z()+B.ttlMs})}
|
|
2
|
+
`,{encoding:"utf8",mode:384})}async function _(){try{return await L(J,`${JSON.stringify({ownerId:W,expiresAt:Z()+B.ttlMs})}
|
|
3
|
+
`,{encoding:"utf8",mode:384,flag:"wx"}),!0}catch(G){let H=G.code;if(H==="EEXIST"||H==="EISDIR")return!1;if(H==="ENOENT"){await h(GB(J),{recursive:!0});try{return await L(J,`${JSON.stringify({ownerId:W,expiresAt:Z()+B.ttlMs})}
|
|
4
|
+
`,{encoding:"utf8",mode:384,flag:"wx"}),!0}catch(K){let R=K.code;if(R==="EEXIST"||R==="EISDIR")return!1;throw K}}throw G}}async function U(){await new Promise((G)=>setTimeout(G,Math.floor(Math.random()*4)))}async function T(){try{let G=await b();return Number(G?.expiresAt)>Z()}catch{try{return(await l(J)).mtimeMs+B.ttlMs>Z()}catch{return!1}}}async function Y(){try{return JSON.parse(await F(A,"utf8"))?.ownerId===I}catch{return!1}}async function S(){if(await Y())await x(z,{recursive:!0,force:!0}).catch(()=>{})}async function M(){await h(z);try{await L(A,`${JSON.stringify({ownerId:I,createdAt:Z()})}
|
|
5
|
+
`,{encoding:"utf8",mode:384,flag:"wx"})}catch(G){if(KB(G))return!1;throw await S(),G}if(B.onStep)await B.onStep("eviction-marker-acquired");return!0}async function g(){let G;try{G=await l(z)}catch(K){if(K.code==="ENOENT")return"missing";throw K}if(G.mtimeMs+c>Z())return"fresh";if(B.onStep)await B.onStep("stale-marker-stat");let H=`${z}.${y()}`;try{await BB(z,H)}catch(K){if(K.code==="ENOENT")return"missing";throw K}if(B.onStep)await B.onStep("stale-marker-claimed");return await x(H,{recursive:!0,force:!0}).catch(()=>{}),"recovered"}async function E(G){try{if(!await M())return!1}catch(H){if(H.code==="EEXIST")return!1;throw H}try{await G()}finally{await S()}return!0}async function a(){for(let G=0;G<O;G++){if(B.onStep)await B.onStep("relinquish-read");let H;try{H=await b()}catch{return}if(H?.ownerId!==W)return;try{await x(J,{recursive:!0,force:!0});return}catch{await U()}}}function u(){if(!B.renew||$)return;let G=B.renewIntervalMs??Math.max(1000,Math.floor(B.ttlMs/3));if(X=HB(()=>{let H=(async()=>{let K=!$;try{if(!await E(async()=>{let v=await b(),n=Z();if($||v?.ownerId!==W){K=!1;return}if(Number(v?.expiresAt)<=n){K=!1;return}if(B.onStep)await B.onStep("renewal-owner-confirmed");if($){K=!1;return}if(!await Y())return;if(B.onStep)await B.onStep("renewal-write-fenced");if($){K=!1;return}if(!await Y())return;if(B.onStep)await B.onStep("renewal-write-ready");if(await s(),!await Y()){K=!1,await a();return}})&&B.onStep)await B.onStep("renewal-marker-unavailable")}catch{}finally{if(B.onStep)try{await B.onStep("renewal-finished")}catch{}if(K&&!$)u()}})();N=H,H.finally(()=>{if(N===H)N=null})},G),"unref"in X)X.unref()}let V=await _();if(!V)for(let G=0;G<O;G++){if(V=await _(),V)break;if(await T())return null;try{if(!await M()){await U();continue}}catch(H){if(H.code!=="EEXIST")throw H;if(await g()==="fresh")return null;await U();continue}try{if(await T())return null;if(!await Y())return null;if(B.onStep)await B.onStep("stale-lock-confirmed");if(!await Y())return null;if(await x(J,{recursive:!0,force:!0}).catch(()=>{}),!await Y())return null;if(V=await _(),!V)return null;if(!await Y())return await x(J,{recursive:!0,force:!0}).catch(()=>{}),V=!1,null;break}finally{await S()}}if(!V)return null;return u(),{release:async()=>{if($=!0,X)JB(X),X=null;await N;for(let G=0;G<O;G++){try{if(await E(async()=>{if((await b())?.ownerId!==W)return;if(B.onStep)await B.onStep("release-owner-confirmed");if(!await Y())return;await x(J,{recursive:!0,force:!0}).catch(()=>{})}))return;await g()}catch{return}await U()}}}}
|
|
6
|
+
export{C as ua,ZB as va,DB as wa};
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import{ua as I,va as u,wa as A}from"./index-8f1200qx.js";import{Ca as v}from"./index-80gqxa1f.js";import{Ja as Q3}from"./index-x55z0b3y.js";import{createHash as i0}from"node:crypto";var u0=86400000,s0=300000,r0=3600000,n0=60000,c0=900000,o0=300000;function $0(B){return B instanceof Error?B.message:String(B)}function a0(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 W0(B){let Z=$0(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 L0(B){return i0("sha256").update(B).digest("hex")}function F0(B){let Z=L0(B.refreshToken),W=(B.previous?.tokenHash===Z?B.previous.retryCount??0:0)+1,X,z=B.error?.retryAfter;if(typeof z==="number"&&z>0)X=z*1000;else if(a0(B.error))X=Math.min(r0,s0*2**Math.min(W-1,6));else X=u0;return{message:$0(B.error),checkedAt:B.now,nextRetryAt:B.now+X,retryCount:W,tokenHash:Z}}function _(B,Z,$){if(!B?.nextRetryAt||B.nextRetryAt<=$)return!1;if(!Z)return!0;return B.tokenHash===L0(Z)}function r(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 m(B){let $=(B.previous?.retryCount??0)+1,W,X=B.error?.retryAfter;if(typeof X==="number"&&X>0)W=X*1000;else if(W0(B.error))W=Math.min(c0,n0*2**Math.min($-1,6));else W=o0;return{message:$0(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 X0(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 t0}from"node:http";import{setTimeout as e0}from"node:timers/promises";var O0="0.6.3";var o="app_EMoamEEZ73f0CkXaXp7hrann",S="https://auth.openai.com",k=1455,B3=3000,D0=`cortexkit-opencode-openai-auth/${O0}`,U0="main",Z3=`"${U0}" is a reserved account id; choose a different label.`;function M0(B){let Z=new Uint8Array(B),$=String.fromCharCode(...Z);return btoa($).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function $3(){let Z=Array.from(crypto.getRandomValues(new Uint8Array(43))).map((W)=>"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~"[W%66]).join(""),$=M0(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 b0(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 X=W[0];if(X&&typeof X==="object"&&!Array.isArray(X)&&typeof X.id==="string"&&X.id.length>0)return X.id}return}function c(B){if(B.id_token){let Z=V0(B.id_token),$=Z&&b0(Z);if($)return $}if(B.access_token){let Z=V0(B.access_token);return Z?b0(Z):void 0}return}function W3(B){return typeof B==="string"&&B.toLowerCase()===U0}function G0(B){if(W3(B))throw Error(Z3);return B}function X3(B,Z,$){let W=new URLSearchParams({response_type:"code",client_id:o,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`${S}/oauth/authorize?${W.toString()}`}async function G3(B,Z,$){let W=await fetch(`${S}/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:o,code_verifier:$.verifier}).toString()});if(!W.ok)throw Error(`Token exchange failed: ${W.status}`);return await W.json()}function z3(B){return B.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}var K3=`<!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>`,n=(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">${z3(B)}</div>
|
|
85
|
+
</div>
|
|
86
|
+
</body>
|
|
87
|
+
</html>`,w,h,V=new Map;function q(){return V.size}function E(B){if(V.delete(B),q()===0)C()}async function Y3(){let B=`http://localhost:${k}/auth/callback`;if(w)return{port:k,redirectUri:B};if(h)return h;h=(async()=>{let Z=t0(($,W)=>{let X=new URL($.url||"/",`http://127.0.0.1:${k}`);if(X.pathname==="/auth/callback"){let z=X.searchParams.get("code"),G=X.searchParams.get("state"),K=X.searchParams.get("error"),Y=X.searchParams.get("error_description");if(K){let H=Y||K;if(G){let Q=V.get(G);if(Q)Q.reject(Error(H)),E(G);else if(q()===0)C()}else if(q()===0)C();W.writeHead(200,{"Content-Type":"text/html"}),W.end(n(H));return}if(!G){if(q()===0)C();W.writeHead(400,{"Content-Type":"text/html"}),W.end(n("Missing state parameter"));return}if(!z){if(q()===0)C();W.writeHead(400,{"Content-Type":"text/html"}),W.end(n("Missing authorization code"));return}let j=V.get(G);if(!j){if(q()===0)C();W.writeHead(400,{"Content-Type":"text/html"}),W.end(n("Unknown state — authorization may have expired"));return}E(G),G3(z,B,j.pkce).then((H)=>j.resolve(H)).catch((H)=>j.reject(H)),W.writeHead(200,{"Content-Type":"text/html"}),W.end(K3);return}if(X.pathname==="/cancel"){let z=X.searchParams.get("state"),G=z?[z]:[...V.keys()];W.writeHead(200),W.end("Login cancelled");for(let K of G){let Y=V.get(K);if(!Y)continue;Y.reject(Error("Login cancelled")),E(K)}if(q()===0)C();return}W.writeHead(404),W.end("Not found")});return await new Promise(($,W)=>{Z.once("error",W),Z.listen(k,"127.0.0.1",()=>{Z.off("error",W),$()})}),w=Z,{port:k,redirectUri:B}})();try{return await h}finally{h=void 0}}function C(){if(w){let B=w;w=void 0,B.close(()=>{}),B.closeIdleConnections?.(),setTimeout(()=>{B.closeAllConnections?.()},25).unref?.()}}function j3(B,Z,$=300000,W){return new Promise((X,z)=>{if(W?.aborted){E(Z),z(Error("Login cancelled"));return}let G=setTimeout(()=>{if(V.get(Z))E(Z),z(Error("OAuth callback timeout — authorization took too long"))},$),K=()=>{if(clearTimeout(G),V.get(Z))E(Z),z(Error("Login cancelled"))};if(W)W.addEventListener("abort",K);V.set(Z,{pkce:B,state:Z,resolve:(Y)=>{if(clearTimeout(G),W)W.removeEventListener("abort",K);X(Y)},reject:(Y)=>{if(clearTimeout(G),W)W.removeEventListener("abort",K);z(Y)}})})}async function J3(){let B=await fetch(`${S}/api/accounts/deviceauth/usercode`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":D0},body:JSON.stringify({client_id:o})});if(!B.ok)throw Error("Failed to initiate device authorization");let Z=await B.json();return{deviceData:Z,url:`${S}/codex/device`,instructions:`Enter code: ${Z.user_code}`}}async function H3(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),X=!Number.isNaN(W)&&W>0?W*1000:900000,z=Date.now();while(!0){if(Z?.aborted)throw Error("Device authorization cancelled");if(Date.now()-z>X)throw Error("Device authorization expired");let G=await fetch(`${S}/api/accounts/deviceauth/token`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":D0},body:JSON.stringify({device_auth_id:B.device_auth_id,user_code:B.user_code})});if(G.ok){let j=await G.json(),H=await fetch(`${S}/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:`${S}/deviceauth/callback`,client_id:o,code_verifier:j.code_verifier}).toString()});if(!H.ok)throw Error(`Token exchange failed: ${H.status}`);return await H.json()}if(G.status!==403&&G.status!==404)throw Error(`Device authorization failed: ${G.status}`);let K=X-(Date.now()-z);if(K<=0)throw Error("Device authorization expired");let Y=Math.min($+B3,K);try{await e0(Y,void 0,{signal:Z})}catch(j){if(j instanceof Error&&j.name==="AbortError")throw Error("Device authorization cancelled");throw j}}}function x6(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 A6(B={}){let{label:Z,headless:$=!1,signal:W}=B;if(G0(Z),$){let{deviceData:j,url:H,instructions:Q}=await J3(),b=(async()=>{let N=await H3(j,W),F=Date.now(),s=c(N);return{id:G0(Z||s||crypto.randomUUID()),label:Z||void 0,type:"oauth",access:N.access_token,refresh:N.refresh_token,expires:F+(N.expires_in??3600)*1000,enabled:!0,addedAt:F,lastUsed:F,lastRefreshedAt:F,accountId:s}})();return{url:H,instructions:Q,completion:b}}let{redirectUri:X}=await Y3(),z=await $3(),G=M0(crypto.getRandomValues(new Uint8Array(32)).buffer),K=X3(X,z,G),Y=(async()=>{try{if(W?.aborted)throw Error("Login cancelled");let j=await j3(z,G,void 0,W),H=Date.now(),Q=c(j);return{id:G0(Z||Q||crypto.randomUUID()),label:Z||void 0,type:"oauth",access:j.access_token,refresh:j.refresh_token,expires:H+(j.expires_in??3600)*1000,enabled:!0,addedAt:H,lastUsed:H,lastRefreshedAt:H,accountId:Q}}finally{E(G)}})();return{url:K,instructions:"Complete authorization in your browser. This window will close automatically.",completion:Y}}function _0(B){if(B instanceof Error)return B.message;if(typeof B==="string")return B;try{return JSON.stringify(B)}catch{return String(B)}}var N3=v("quota"),z0="primary",K0="secondary",P3="app_EMoamEEZ73f0CkXaXp7hrann",L3="https://auth.openai.com";async function w6(B){let Z=await B.fetchImpl(`${L3}/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:P3}).toString()});if(!Z.ok){let X=X0(Z.headers.get("retry-after"));throw Object.assign(Error(`Token refresh failed: ${Z.status}`),{status:Z.status,retryAfter:X,isRefreshError:!0})}let $=await Z.json();if(!$||typeof $.access_token!=="string"||!$.access_token||typeof $.expires_in!=="number")throw Object.assign(Error("Token refresh failed: malformed response"),{status:Z.status,isRefreshError:!0});if($.refresh_token!==void 0&&typeof $.refresh_token!=="string")throw Object.assign(Error("Token refresh failed: malformed response"),{status:Z.status,isRefreshError:!0});let W=typeof $.refresh_token==="string"&&$.refresh_token?$.refresh_token:B.refreshToken;return{access:$.access_token,refresh:W,expires:B.now()+$.expires_in*1000,expiresIn:$.expires_in}}var F3="https://chatgpt.com/backend-api/wham/usage";async function v6(B){let Z=B.logger??N3,$=B.accountKey??"unknown",W=Date.now();Z.debug("wham usage fetch started",{pid:process.pid,accountId:$});try{let X=await B.fetchImpl(F3,{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(!X.ok){let K=X0(X.headers.get("retry-after"));throw Object.assign(Error(`wham usage check failed: ${X.status}`),{status:X.status,retryAfter:K})}let{normalizeWham:z}=await import("./quota-normalize-s27mex1w.js"),G=z(await X.json());return Z.debug("wham usage fetch succeeded",{pid:process.pid,accountId:$,status:X.status,elapsedMs:Date.now()-W}),G}catch(X){throw Z.warn("wham usage fetch failed",{pid:process.pid,accountId:$,status:typeof X?.status==="number"?X.status:"error",elapsedMs:Date.now()-W,error:_0(X)}),X}}import{createHash as O3}from"node:crypto";var V3=globalThis.setTimeout,b3=5;function p(B){let Z=B?.quota?.checkIntervalMinutes??b3;return Math.max(1,Z)*60000}function D3(B){return B?.quota?.enabled!==!1}function a(B,Z){if(!B?.resetsAt)return!1;let $=Date.parse(B.resetsAt);return Number.isFinite($)&&$<=Z}function u6(B,Z,$,W,X){if(X!==void 0&&Number.isFinite(X)&&X>$)return X;let z=Z===z0?B?.primary:Z===K0?B?.secondary:void 0,G=z?.resetsAt?Date.parse(z.resetsAt):NaN;if(Number.isFinite(G)&&G>$)return G;return $+W}function U3(B){let Z=B?.quota?.minimumRemaining||{};return{primary:Z.primary??Z["5h"]??15,secondary:Z.secondary??Z["1w"]??10}}function q0(B,Z,$){if(!D3(Z))return $+p(Z);let W=U3(Z),X=[];for(let z of["primary","secondary"]){let G=B?.[z];if(!G)continue;if(G.remainingPercent>=W[z])continue;let K=G.resetsAt?Date.parse(G.resetsAt):Number.NaN;if(!Number.isFinite(K)||K<=$)return $+p(Z);X.push(K)}if(!X.length)return $+p(Z);return Math.min(...X)+60000}function M3(B){if(!B?.quota?.mainQuota||!B.quota.mainQuotaCheckedAt)return null;return{quota:B.quota.mainQuota,checkedAt:B.quota.mainQuotaCheckedAt,tokenFingerprint:B.quota.mainQuotaToken}}function _3(B){let Z=B?.quota?.refreshEveryNRequests;return typeof Z==="number"&&Number.isFinite(Z)&&Z>0?Math.floor(Z):0}function L(B){return O3("sha256").update(B).digest("hex").slice(0,16)}class D{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!==L(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)!==L(Z))return this.fallbacks.delete(B),this.fallbackTokenFps.delete(B),null;return $}getAllFallbacks(){return this.fallbacks}setMain(B,Z,$,W=!1){if(!W&&!C0(Z.quota))return;if(this.mainTokenFp=L(B),$&&this.mainQuotaAccountId&&this.mainQuotaAccountId!==$)this.clearRateLimited("main");if($)this.mainQuotaAccountId=$;if(this.main=Z,Y0(Z.quota))this.clearRateLimited("main")}peekMainForPolicy(B){if(B&&this.mainQuotaAccountId&&this.mainQuotaAccountId!==B)return null;return this.main}peekFallbackForPolicy(B,Z){let $=this.fallbacks.get(B)??null;if(Z&&$?.accountId&&$.accountId!==Z)return null;return $}setFallback(B,Z,$,W=!1,X){if(!W&&!C0(Z.quota))return;let z=this.fallbacks.get(B)?.accountId;if(X&&z&&X!==z)this.clearRateLimited(B);let G=X??z;if(this.fallbacks.set(B,{...Z,accountId:G}),$)this.fallbackTokenFps.set(B,L($));else this.fallbackTokenFps.delete(B);if(Y0(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=L(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 $=D.fallbackInflightKey(B,Z),W=this.inflightFallbacks.get($);if(W)return W;if(this.isFallbackBackedOff(B,Z)){let z=this.getFallback(B,Z);if(z)return z.quota;throw Error("Quota API rate-limited — try again later")}let X=this._fetchFallback(B,Z);return this.inflightFallbacks.set($,X),X}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=L(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=_3(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 $=M3(B);if(!$)return;let W=Z?L(Z):null;if(W&&$.tokenFingerprint&&$.tokenFingerprint!==W)return;let X={quota:$.quota,refreshAfter:q0($.quota,B,$.checkedAt),checkedAt:$.checkedAt};if(this.main&&this.main.checkedAt>=X.checkedAt&&(!W||!this.mainTokenFp||this.mainTokenFp===W))return;if(this.main=X,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=p(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 X=this.getFallback($.id,$.access);if(X&&X.checkedAt>=W)continue;this.setFallback($.id,{quota:$.quota,refreshAfter:W+Z,checkedAt:W},$.access,!1,$.accountId)}}isBackedOff(){return x(this.mainLastApiError,this.now())}isFallbackBackedOff(B,Z){if(Z){if(this.fallbackErrorTokenFps.get(B)!==L(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,L(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<D.API_CALL_GAP_MS)await new Promise((X)=>{let z=V3(X,D.API_CALL_GAP_MS-W);if(typeof z==="object"&&"unref"in z)z.unref()});return this.lastApiCallAt=this.now(),B()},$=this.apiGate.then(Z,Z);return this.apiGate=$.catch(()=>{}),$}async _fetchMain(B){let Z=L(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 A({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(),X=await this._fetchQuota(B),z=this.now();if(this.mainTokenFp=L(B),this.main={quota:X,refreshAfter:q0(X,this.storage,z),checkedAt:z},Y0(X))this.clearRateLimited("main");return this.mainLastApiError=void 0,this.onMainQuotaFetched?.(X,z,this.mainTokenFp,W),X}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 A({name:D.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),X=this.now();return this.setFallback(B,{quota:W,refreshAfter:X+p(this.storage),checkedAt:X},Z,!0),this.fallbackApiErrors.delete(B),this.fallbackErrorTokenFps.delete(B),W}finally{await $.release()}}catch($){throw this._handleFallbackFetchError(B,Z,$),$}finally{this.inflightFallbacks.delete(D.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(D.isAuthError(B))return;this.mainLastApiError=m({error:B,now:this.now(),previous:this.mainLastApiError}),this.onApiError?.(this.mainLastApiError)}_handleFallbackFetchError(B,Z,$){if(D.isAuthError($))return;let W=L(Z),X=this.fallbackErrorTokenFps.get(B)===W?this.fallbackApiErrors.get(B):void 0;this.fallbackApiErrors.set(B,m({error:$,now:this.now(),previous:X})),this.fallbackErrorTokenFps.set(B,W)}}function C0(B){return Boolean(B.primary||B.secondary)}function Y0(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 T3,randomUUID as x3}from"node:crypto";import{setTimeout as A3}from"node:timers/promises";import{randomUUID as q3}from"node:crypto";import{mkdir as C3,rename as S3,rm as E3,writeFile as R3}from"node:fs/promises";import{dirname as y3}from"node:path";async function f(B,Z){await C3(y3(B),{recursive:!0});let $=`${B}.${q3()}.tmp`;await R3($,`${JSON.stringify(Z,null,2)}
|
|
88
|
+
`,{encoding:"utf8",mode:384});try{await S3($,B)}catch(W){throw await E3($,{force:!0}).catch(()=>{}),W}}import{readFile as i3}from"node:fs/promises";var R=v("refresh"),t=v("accounts"),f3=1e4,I3=15000,j0=50;function U(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 JB(B){return B.costZeroing?.enabled!==!1}class e extends Error{code="ACCOUNT_REMOVED_DURING_REFRESH";constructor(B){super(`Fallback account ${B} was removed before refresh`);this.name="AccountRemovedDuringRefreshError"}}var k3=[401,403,429],S0={primary:0,secondary:0},h3=!1,H0={primary:5,secondary:10};function J(B){return B!=null&&typeof B==="object"&&!Array.isArray(B)}var w3=new Set(["__proto__","constructor","prototype"]);function v3(B){return B.length>0&&!w3.has(B)}function p3(B){return B instanceof e||J(B)&&B.name==="AccountRemovedDuringRefreshError"&&B.code==="ACCOUNT_REMOVED_DURING_REFRESH"}function E0(B){return{id:typeof B.id==="string"&&B.id.trim()?B.id.trim():x3(),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 R0(B){if(!J(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 l3(B){if(!J(B))return;let Z={};for(let $ of["primary","secondary"]){let W=B[$];if(!J(W))continue;let X=Number(W.usedPercent),z=Number(W.remainingPercent),G=Number(W.checkedAt);if(!Number.isFinite(X)||!Number.isFinite(z)||!Number.isFinite(G))continue;let K=typeof W.windowMinutes==="number"?W.windowMinutes:Number.NaN;Z[$]={usedPercent:X,remainingPercent:z,checkedAt:G,resetsAt:typeof W.resetsAt==="string"?W.resetsAt:void 0,...Number.isFinite(K)&&K>0?{windowMinutes:K}:{}}}for(let $ of["resetCreditsAvailable","resetCreditsApplicable"]){let W=typeof B[$]==="number"?B[$]:Number.NaN;if(Number.isFinite(W)&&W>=0)Z[$]=W}return Object.keys(Z).length?Z:void 0}function g3(B){if(!J(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{...E0(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{...E0(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:R0(B.lastRefreshError),lastQuotaRefreshError:R0(B.lastQuotaRefreshError),quota:l3(B.quota)}}function d3(B){if(!J(B))return;let Z=Object.create(null);for(let[$,W]of Object.entries(B)){if(!v3($)||!J(W))continue;let X={};if(J(W.inFlight))X.inFlight={...W.inFlight};if(J(W.lastOutcome)&&typeof W.lastOutcome.code==="string"&&W.lastOutcome.code.length>0&&typeof W.lastOutcome.at==="number"&&Number.isFinite(W.lastOutcome.at))X.lastOutcome={code:W.lastOutcome.code,at:W.lastOutcome.at,...J(W.lastOutcome.previousOutcome)&&typeof W.lastOutcome.previousOutcome.code==="string"&&W.lastOutcome.previousOutcome.code.length>0&&typeof W.lastOutcome.previousOutcome.at==="number"&&Number.isFinite(W.lastOutcome.previousOutcome.at)?{previousOutcome:{code:W.lastOutcome.previousOutcome.code,at:W.lastOutcome.previousOutcome.at}}:{}};if(typeof W.cooldownUntil==="number"&&Number.isFinite(W.cooldownUntil))X.cooldownUntil=W.cooldownUntil;if(Object.keys(X).length>0)Z[$]=X}return Object.keys(Z).length>0?Z:void 0}var y0=new Set;function f0(B){if(B.length===0)return;let Z=JSON.stringify([...B].sort());if(y0.has(Z))return;y0.add(Z),t.warn("account load-dropped, preserved on disk",{droppedIds:B})}function I0(B){if(!J(B)||!Array.isArray(B.accounts))return null;let Z=B.accounts,$=Z.map(g3).filter((W)=>W!=null);if($.length<Z.length){let W=new Set;for(let G of Z)if(J(G)&&typeof G.id==="string"&&G.id.trim())W.add(G.id.trim());let X=new Set($.map((G)=>G.id)),z=[];for(let G of W)if(!X.has(G))z.push(G);f0(z)}return{version:1,main:{type:"opencode",provider:"openai"},routing:J(B.routing)?B.routing:void 0,fallbackOn:Array.isArray(B.fallbackOn)?B.fallbackOn.filter((W)=>Number.isInteger(W)):void 0,refresh:J(B.refresh)?B.refresh:void 0,quota:J(B.quota)?B.quota:void 0,reset:d3(B.reset),dump:J(B.dump)?B.dump:void 0,costZeroing:J(B.costZeroing)?B.costZeroing:void 0,killswitch:J(B.killswitch)?B.killswitch:void 0,logging:J(B.logging)?B.logging:void 0,cachekeep:J(B.cachekeep)?B.cachekeep:void 0,mainAccountId:typeof B.mainAccountId==="string"?B.mainAccountId:void 0,accounts:$}}async function T(B){try{return{exists:!0,value:JSON.parse(await i3(B,"utf8"))}}catch(Z){if(Z.code==="ENOENT")return{exists:!1,value:null};throw Z}}function M(B){return Object.fromEntries(Object.entries(B).filter(([,Z])=>Z!==void 0))}async function u3(B){let Z;try{Z=(await T(B)).value}catch{return null}if(!J(Z)||!Array.isArray(Z.accounts))return null;let $=new Set;for(let W of Z.accounts){if(!J(W))continue;if(typeof W.id!=="string")continue;let X=W.id.trim();if(!X)continue;$.add(X)}return $}function m0(B,Z){if(!J(B))return B;let $=J(Z)?Z:{},W=J($.main)?$.main:void 0,X=J($.accounts)?$.accounts:{},z=J(B.quota)?B.quota:{},G=J(B.refresh)?B.refresh:{},K=W??z,Y=W??G,H=Array.isArray(B.accounts)?B.accounts.map((Q)=>{if(!J(Q))return Q;let b=typeof Q.id==="string"&&J(X[Q.id])?X[Q.id]:{};return{...Q,...b}}):void 0;return k0({...B,refresh:M({...G,mainLastRefreshError:Y.lastRefreshError,mainRefreshLeaseId:Y.refreshLeaseId,mainRefreshLeaseUntil:Y.refreshLeaseUntil,mainRefreshLeaseTokenHash:Y.refreshLeaseTokenHash}),quota:M({...z,mainQuota:K.quota,mainQuotaCheckedAt:K.quotaCheckedAt,mainQuotaToken:K.quotaToken,mainLastQuotaApiError:K.lastQuotaApiError}),accounts:H})}async function s3(B=I()){let Z=await T(B);if(!Z.exists)return null;let $=await T(u(B));return I0(m0(Z.value,$.value))}function k0(B){return Object.fromEntries(Object.entries(B).filter(([,Z])=>Z!==void 0))}function r3(B){return M({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 h0(B){if(B.type==="api")return M({apiKey:B.apiKey,lastUsed:B.lastUsed});return M({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 B0(B){return Math.max(B?.primary?.checkedAt??0,B?.secondary?.checkedAt??0)}function l(B,Z,$){if($ in Z)B[$]=Z[$];else delete B[$]}function n3(B,Z){return B.access===Z.access&&B.refresh===Z.refresh&&B.expires===Z.expires&&B.lastRefreshedAt===Z.lastRefreshedAt}function c3(B,Z){if(!n3(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 o3(B,Z,$){let W=Z.lastRefreshedAt??0,X=$.lastRefreshedAt??0,z=Z.expires??0,G=$.expires??0,K=X>W?$:W>X?Z:G>z?$:z>G?Z:c3(Z,$);l(B,K,"access"),l(B,K,"refresh"),l(B,K,"expires"),l(B,K,"lastRefreshedAt"),l(B,K,"lastRefreshError")}function a3(B,Z){if(!J(B))return Z;let $=B,W=B0($.quota),X=B0(Z.quota),z=W>X,G=z?{...$,...Z,quota:$.quota,lastQuotaRefreshError:$.lastQuotaRefreshError}:{...$,...Z};if(!z&&!("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 o3(G,$,Z),G}function w0(B){let Z=B.refresh?M({enabled:B.refresh.enabled,intervalMinutes:B.refresh.intervalMinutes,refreshBeforeExpiryMinutes:B.refresh.refreshBeforeExpiryMinutes}):void 0,$=B.quota?M({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 k0({version:1,main:B.main,routing:B.routing,fallbackOn:B.fallbackOn,refresh:Z,quota:$,reset:B.reset,dump:B.dump,costZeroing:B.costZeroing,killswitch:B.killswitch,logging:B.logging,cachekeep:B.cachekeep,mainAccountId:B.mainAccountId,accounts:B.accounts.map(r3)})}async function d(B){let Z=Date.now(),$=Z+I3,W=0;while(Date.now()<=$){W++;let G=await A({name:"save",ttlMs:f3,path:B});if(G)return G;let K=$-Date.now();if(K<=0)break;await A3(Math.min(j0+d0(j0),K))}let X=Date.now()-Z,z=Math.round(X/Math.max(1,W));throw Error(`Timed out after ${X}ms waiting for the account store lock on ${B} (${W} attempts, ~${z}ms apart; retry interval is ${j0}ms). A gap near the retry interval means lock contention; a much larger one means this process's event loop was saturated and the wait expired without getting scheduled.`)}function v0(B){let Z=Object.fromEntries(B.accounts.map(($)=>[$.id,h0($)]));return{version:1,main:M({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}}function t3(B){if(!J(B)||!Array.isArray(B.accounts))return null;let Z=new Set;for(let $ of B.accounts){if(!J($))continue;if(typeof $.id!=="string")continue;let W=$.id.trim();if(!W)continue;Z.add(W)}return Z}function e3(B,Z,$,W){if(!J(B)||!Array.isArray(B.accounts))return{preservedRawEntries:[],preservedIds:[]};let X=[],z=[];for(let G of Z){if($.has(G))continue;if(W.has(G))continue;let K=B.accounts.find((Y)=>J(Y)&&typeof Y.id==="string"&&Y.id.trim()===G);if(!K)continue;X.push(K),z.push(G)}return{preservedRawEntries:X,preservedIds:z}}function B6(B){if(!Array.isArray(B))return[];let Z=[];for(let $ of B){if(!J($))continue;if(typeof $.id!=="string")continue;Z.push($.id)}return Z}function Z6(B,Z,$){let W=t3(B);if(W===null)return[];let{preservedRawEntries:X,preservedIds:z}=e3(B,W,Z,$);return f0(z),X}async function QB(B,Z=I(),$={}){let W=u(Z),X=await d(Z);try{let z=await d(W);try{let G=await T(Z),K=await T(W),Y=(G.exists?I0(m0(G.value,K.value)):null)??$6(),j=new Set(Y.accounts.map((O)=>O.id)),H=B(Y)??Y,Q=new Set($.allowDrop??[]),b=Z6(G.value,j,Q),N=w0(H),F=new Set((Array.isArray(N.accounts)?N.accounts:[]).map((O)=>J(O)&&typeof O.id==="string"?O.id.trim():"").filter(Boolean)),s=b.filter((O)=>{if(!J(O))return!1;if(typeof O.id!=="string")return!1;return!F.has(O.id.trim())}),Z0={...J(G.value)?G.value:{},...N,accounts:[...Array.isArray(N.accounts)?N.accounts:[],...s]};return await f(Z,Z0),await f(W,v0(H)),t.debug("account config written",{accountCount:Z0.accounts.length,accountIds:B6(Z0.accounts)}),H}finally{await z.release()}}finally{await X.release()}}function $6(){return{version:1,main:{type:"opencode",provider:"openai"},accounts:[]}}function W6(B,Z){B.main=B.main??{};let $=typeof B.main.quotaCheckedAt==="number"?B.main.quotaCheckedAt:B0(B.main.quota),W=typeof Z.quota?.mainQuotaCheckedAt==="number"?Z.quota.mainQuotaCheckedAt:B0(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 X6(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 Q0(B){if(Array.isArray(B))return B.map(Q0);if(!J(B))return B;return Object.fromEntries(Object.entries(B).filter(([,Z])=>Z!==void 0).map(([Z,$])=>[Z,Q0($)]))}async function G6(B,Z=I(),$={mainQuota:!0,mainRefresh:!0,accounts:!0}){let W=u(Z),X=await d(W);try{let z=(await T(W)).value,G=J(z)?{...z,version:1}:{version:1};if($.mainQuota)W6(G,B);if($.mainRefresh)X6(G,B);if($.accounts){let K=$.accounts===!0?null:new Set($.accounts),Y=await u3(Z);G.accounts={...J(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]=a3(G.accounts[j.id],h0(j))}if(K){for(let j of K)if(!B.accounts.some((H)=>H.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 f(W,Q0(G))}finally{await X.release()}}function z6(B){return B?.fallbackOn?.length?B.fallbackOn:k3}function NB(B,Z){return z6(Z).includes(B)}function K6(B){let Z=B?.quota?.minimumRemaining||{};return{primary:Z.primary??Z["5h"]??S0.primary,secondary:Z.secondary??Z["1w"]??S0.secondary}}function N0(B){return B?.quota?.enabled!==!1}function i(B){return B?.quota?.failClosedOnUnknownQuota??h3}function p0(B,Z,$=Date.now()){if(!N0(Z))return!0;if(!B)return!i(Z);let W=K6(Z),X=i(Z);for(let z of["primary","secondary"]){let G=B[z];if(!G)continue;if(a(G,$)){if(X)return!1;continue}if(G.remainingPercent<W[z])return!1}return!0}function l0(B){return B?.killswitch?.enabled===!0}function T0(B){return{primary:B?.primary??B?.["5h"]??H0.primary,secondary:B?.secondary??B?.["1w"]??H0.secondary}}function g0(B,Z){if(!B?.killswitch)return H0;if(Z&&B.killswitch.accounts?.[Z])return T0(B.killswitch.accounts[Z]);return T0(B.killswitch.main)}function PB(B,Z,$,W=Date.now()){if(!l0(Z))return!0;if(!B)return!i(Z);let X=g0(Z,$),z=i(Z);for(let G of["primary","secondary"]){let K=B[G];if(!K)continue;if(a(K,W)){if(z)return!1;continue}if(K.remainingPercent<X[G])return!1}return!0}function LB(B,Z,$,W){if(!l0(W))return 300;let X=[],z=[{accountId:void 0,quota:B},...Z];for(let{accountId:K,quota:Y}of z){if(!Y)continue;let j=g0(W,K),H=[],Q=!1;for(let b of["primary","secondary"]){let N=Y[b];if(!N||a(N,$))continue;if(N.remainingPercent>=j[b])continue;let F=N.resetsAt?Date.parse(N.resetsAt):NaN;if(!Number.isFinite(F)||F<=$){Q=!0;break}H.push(F)}if(Q||H.length===0)continue;X.push(Math.max(...H))}if(X.length===0)return 300;let G=Math.min(...X);return Math.max(1,Math.ceil((G-$)/1000))}function Y6(B){return typeof B.version==="number"&&Array.isArray(B.accounts)}async function FB(B,Z=I()){let $=u(Z),W=await d(Z);try{let X=await d($);try{let z=await T(Z);if(z.exists&&J(z.value)){if(Y6(z.value))return}if(!B)return;let G={version:1,main:{type:"opencode",provider:"openai"},accounts:[]};if(B.access){let j=c({id_token:"",access_token:B.access,refresh_token:B.refresh});if(j)G.mainAccountId=j}let Y={...z.exists&&J(z.value)?z.value:{},...w0(G)};await f(Z,Y),await f($,v0(G))}finally{await X.release()}}finally{await W.release()}}function j6(B){return B?.refresh?.enabled!==!1}function J6(B){return(B?.refresh?.refreshBeforeExpiryMinutes??240)*60000}function d0(B){return Math.floor(Math.random()*(B+1))}function y(B,Z,$){return!B.access||!B.expires||B.expires-$<=J6(Z)}function H6(B,Z){return Boolean(B.access&&typeof B.expires==="number"&&B.expires>Z)}function Q6(B,Z){return Boolean(B.mainAccountId&&Z.accountId&&Z.accountId===B.mainAccountId)}function P(B,Z){let $=B.accounts.findIndex((W)=>W.id===Z.id);if($!==-1)B.accounts[$]=Z}function g(B){return B instanceof Error?B.message:String(B)}function P0(B,Z,$){B.lastRefreshError=F0({error:Z,now:$,refreshToken:B.refresh,previous:B.lastRefreshError})}function J0(B,Z,$){if(B.lastQuotaRefreshError=m({error:Z,now:$,previous:B.lastQuotaRefreshError}),Z?.isRefreshError===!0)P0(B,Z,$)}function N6(B){return`fallback-oauth-refresh-${T3("sha256").update(B).digest("base64url").slice(0,16)}`}function x0(B,Z){if(!B)return!1;if(!B.resetsAt)return!0;let $=Date.parse(B.resetsAt);return Number.isFinite($)?$>Z:!0}function P6(B,Z){if(!B)return!1;return x0(B.primary,Z)||x0(B.secondary,Z)}function L6(B,Z,$){if(!B)return!1;let W=Z?.quota?.checkIntervalMinutes??5,X=Math.max(1,W)*60000,z=Math.max(B.primary?.checkedAt??0,B.secondary?.checkedAt??0);return $-z<X}function A0(B,Z,$){return!L6(B.quota,Z,$)}function F6(B,Z,$,W){return W0($)&&p0(B.quota,Z,W)&&P6(B.quota,W)}function O6(B){let Z=B?.quota?.checkIntervalMinutes??5;return Math.max(1,Z)*60000}var V6=60000,b6=60000,D6=600000,U6=1e4,M6=100;var OB=globalThis.setTimeout.bind(globalThis),VB=globalThis.clearTimeout.bind(globalThis);class _6{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??I(),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:$+O6(Z),checkedAt:$},B.access,!1,B.accountId)}async load(){return s3(this.configPath)}async save(B,Z){await G6(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(()=>{})},V6+d0(b6)),"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 X of Z.accounts){if(X.enabled===!1||!U(X))continue;if(Q6(Z,X))continue;let z=!1,G=X;try{if(y(G,Z,this.now())){let K=G.lastRefreshError;if(K&&_(K,G.refresh,this.now()))throw z=!0,Error(r(K,this.now()));try{G=await this.refreshAccount(G,Z),W=!0}catch(Y){if(p3(Y))continue;z=!0;let j=Z.accounts.find((H)=>H.id===X.id&&U(H));if(j&&!_(j.lastRefreshError,j.refresh,this.now()))P0(j,Y,this.now()),P(Z,j),W=!0;throw Y}}if(this.seedFallbackQuota(G,Z),this.accountPassesQuotaPolicy(this.quotaPolicyAccount(G),Z))$.push(G)}catch(K){let Y=H6(G,this.now());if(z){if(!Y)continue}else if(!Y)continue;if(F6(G,Z,K,this.now()))R.debug("fallback quota using cached quota after refresh error",{pid:process.pid,accountId:G.id,error:g(K)}),$.push(G);else if(!i(Z))$.push(G)}}if(W)try{await this.save(Z)}catch(X){t.warn("fallback selection bookkeeping not persisted",{pid:process.pid,error:g(X)})}return $}async markUsed(B){try{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,[$.id])}catch(Z){t.warn("lastUsed stamp not persisted",{pid:process.pid,accountId:B.id,error:g(Z)})}}accountPassesQuotaPolicy(B,Z){return p0(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||!j6(B))return;let Z=!1;for(let $ of B.accounts){if($.enabled===!1||!U($))continue;if(!y($,B,this.now()))continue;if(_($.lastRefreshError,$.refresh,this.now()))continue;try{R.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){R.warn("fallback oauth background failed",{pid:process.pid,accountId:$.id,error:g(W)}),P0($,W,this.now()),P(B,$),Z=!0}}if(Z)await this.save(B)}async refreshQuotaForDueAccounts(){let B=await this.load();if(!B||!N0(B))return;if(!this.options.fetchQuotaFn)return;let Z=!1;for(let $ of B.accounts){if($.enabled===!1||!U($))continue;let W=$;try{if(y(W,B,this.now())){if(_(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):A0(W,B,this.now())))continue;await this.refreshAccountQuota(W,B),Z=!0}catch(X){J0($,X,this.now()),P(B,$),Z=!0}}if(Z)await this.save(B),this.onFallbackStorageChanged?.()}async refreshQuotaForAllAccounts(B={}){let Z=await this.load(),$=[];if(!Z||!N0(Z))return{storage:Z,errors:$};if(!this.options.fetchQuotaFn)return{storage:Z,errors:$};let W=B.force??!1,X=!1;for(let z of Z.accounts){if(z.enabled===!1||!U(z))continue;let G=z;try{if(y(G,Z,this.now())){let K=G.lastRefreshError;if(K&&_(K,G.refresh,this.now()))throw Error(r(K,this.now()));G=await this.refreshAccount(G,Z),X=!0}if(!W&&!A0(G,Z,this.now())){if(G.lastQuotaRefreshError)G.lastQuotaRefreshError=void 0,P(Z,G),X=!0;continue}await this.refreshAccountQuota(G,Z),X=!0}catch(K){J0(z,K,this.now()),P(Z,z),X=!0,$.push({accountId:z.id,message:g(K)})}}if(X)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 P(Z,G),G}let X=this.refreshAccountNow(B,Z,$).finally(()=>{this.refreshPromises.delete(B.id)});this.refreshPromises.set(B.id,X);let z=await X;return P(Z,z),z}async waitForConcurrentFallbackRefresh(B,Z,$,W){let X=Date.now()+U6;while(Date.now()<X){await new Promise((j)=>setTimeout(j,M6));let z=await this.load(),G=z?.accounts.find((j)=>j.id===B.id&&U(j));if(!G)continue;if((G.access!==$.access||G.refresh!==$.refresh||(G.expires??0)>($.expires??0)+60000)&&(W.force||!y(G,z,this.now())))return P(Z,G),R.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&&_(Y,G.refresh,this.now()))throw P(Z,G),Error(r(Y,this.now()))}return null}async refreshAccountNow(B,Z,$){let W=await this.load(),X=W?.accounts.find((K)=>K.id===B.id&&U(K));if(X&&!$.force&&!y(X,W,this.now()))return P(Z,X),X;let z=X??B,G=await A({name:N6(z.id),ttlMs:D6,path:this.configPath,now:this.now,renew:!0});if(!G){R.debug("fallback oauth refresh skipped file lock",{pid:process.pid,accountId:z.id});let K=await this.waitForConcurrentFallbackRefresh(B,Z,z,$);if(K)return K;throw Error("Fallback OAuth refresh is already in progress")}try{if(W=await this.load(),X=W?.accounts.find((H)=>H.id===B.id&&U(H)),X&&!$.force&&!y(X,W,this.now()))return P(Z,X),X;if(!X)throw new e(B.id);z=X;let K=this.options.refreshFn??(async()=>{throw Error("No refreshFn injected into FallbackAccountManager")});R.debug("fallback oauth refresh request start",{pid:process.pid,accountId:z.id,force:$.force===!0,expiresInMs:z.expires?z.expires-this.now():void 0});let Y=await K({refreshToken:z.refresh,fetchImpl:this.fetchImpl,now:this.now});if(z.access=Y.access,z.refresh=Y.refresh,z.expires=Y.expires,z.lastRefreshedAt=Y.expires-Y.expiresIn*1000,z.lastRefreshError=void 0,P(Z,z),await this.save(Z),!(await this.load())?.accounts.some((H)=>H.id===B.id))throw new e(B.id);return R.debug("fallback oauth refresh succeeded",{pid:process.pid,accountId:z.id,expiresInMs:z.expires?z.expires-this.now():void 0}),z}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")}),X=(z)=>this.quotaManager?this.quotaManager.refreshFallback($.id,z):W({accessToken:z,fetchImpl:this.fetchImpl,now:this.now});try{if(!$.access)throw Error(`Fallback account ${B.id} has no access token`);let z=await X($.access);$.quota=z,$.lastQuotaRefreshError=void 0,P(Z,$),await this.save(Z)}catch(z){throw J0(B,z,this.now()),P(Z,B),z}}}
|
|
89
|
+
export{L0 as h,F0 as i,_ as j,r as k,D0 as l,M0 as m,$3 as n,V0 as o,b0 as p,c as q,G0 as r,X3 as s,E as t,Y3 as u,j3 as v,J3 as w,H3 as x,x6 as y,A6 as z,_0 as A,w6 as B,v6 as C,u6 as D,D as E,U as F,JB as G,H0 as H,v3 as I,u3 as J,s3 as K,QB as L,NB as M,l0 as N,g0 as O,PB as P,LB as Q,FB as R,_6 as S};
|
|
@@ -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
|
|
2
|
+
export{t as Ga,u as Ha,v as Ia,x as Ja};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{ua as l}from"./index-n00ybbbq.js";import{Aa as d}from"./index-hxpv25e8.js";import{createHash as $j,randomUUID as Vj}from"node:crypto";import{chmod as Xj,mkdir as Kj,readFile as c,rename as Yj,rm as Gj,writeFile as Lj}from"node:fs/promises";import{tmpdir as zj}from"node:os";import{dirname as Dj,join as o}from"node:path";var r=["primary","secondary"],u={primary:300,secondary:10080};function E(j){return Number.isInteger(j)?String(j):String(Math.round(j*10)/10)}function Jj(j,J){let Z=j!==void 0&&Number.isFinite(j)&&j>0?j:u[J];if(Z<60)return`${E(Z)}m`;if(Z<1440)return`${E(Z/60)}h`;return`${E(Z/1440)}d`}function Zj(j){if(!j)return[];let J=[];for(let Z of r){let $=j[Z];if(!$)continue;let V=$.windowMinutes,X=V!==void 0&&Number.isFinite(V)&&V>0?V:u[Z];J.push({key:Z,label:Jj(X,Z),window:$,windowMs:X*60000})}return J}var M=d("sidebar"),Oj="OPENCODE_OPENAI_AUTH_SIDEBAR_STATE_FILE",Bj=o(zj(),"opencode-openai-auth"),a=o(Bj,"sidebar-state.json"),Tj=/^[a-f0-9]{64}$/,b=604800000,Uj=256,i=3600000;function R(j){return $j("sha256").update(j).digest("hex")}function Qj(j){return typeof j==="number"&&Number.isFinite(j)&&j>=0?j:void 0}function y(j){let J=Qj(j);return J!==void 0?{resetCredits:J}:{}}function Nj(j){if(j===null||typeof j!=="object"||Array.isArray(j))return;let J={};for(let[Z,$]of Object.entries(j)){if($===null||typeof $!=="object"||Array.isArray($))continue;let V=$;if(typeof V.activeId!=="string"||typeof V.route!=="string"||typeof V.updatedAt!=="number"||!Number.isFinite(V.updatedAt))continue;J[Z]={activeId:V.activeId,route:V.route,updatedAt:V.updatedAt}}return Object.keys(J).length>0?J:void 0}function _j(j){if(j===null||typeof j!=="object"||Array.isArray(j))return;let J={};for(let[Z,$]of Object.entries(j)){if(!Tj.test(Z)||$===null||typeof $!=="object"||Array.isArray($))continue;let V=$;if(typeof V.accountId!=="string"||V.accountId.length===0||typeof V.assignedAt!=="number"||!Number.isFinite(V.assignedAt)||V.assignedAt<0||typeof V.lastSeenAt!=="number"||!Number.isFinite(V.lastSeenAt)||V.lastSeenAt<0||typeof V.inputBytes!=="number"||!Number.isFinite(V.inputBytes)||V.inputBytes<0)continue;let X=V.quotaCheckedAt;if(X!==void 0&&(typeof X!=="number"||!Number.isFinite(X)||X<0))continue;let K=V.wireAccountId;J[Z]={accountId:V.accountId,assignedAt:V.assignedAt,lastSeenAt:V.lastSeenAt,inputBytes:V.inputBytes,...X===void 0?{}:{quotaCheckedAt:X},...typeof K==="string"?{wireAccountId:K}:{}}}return Object.keys(J).length>0?J:void 0}function T(){return process.env[Oj]||a}var Q={main:{quota:null,killed:!1},fallbacks:[],activeId:void 0,route:"main",lastUpdated:0};function x(j){if(j===null||typeof j!=="object"||Array.isArray(j))return Q;let J=j,Z=J.main,$;if(Z!==null&&typeof Z==="object"&&!Array.isArray(Z)){let Y=Z;$={quota:"quota"in Y?Y.quota:null,killed:typeof Y.killed==="boolean"?Y.killed:!1,...typeof Y.mainAccountId==="string"?{mainAccountId:Y.mainAccountId}:{},...typeof Y.quotaBackedOff==="boolean"?{quotaBackedOff:Y.quotaBackedOff}:{},...typeof Y.quotaBackoffUntil==="number"?{quotaBackoffUntil:Y.quotaBackoffUntil}:{},...typeof Y.refreshBackedOff==="boolean"?{refreshBackedOff:Y.refreshBackedOff}:{},...typeof Y.refreshBackoffUntil==="number"?{refreshBackoffUntil:Y.refreshBackoffUntil}:{},...y(Y.resetCredits)}}else $={quota:null,killed:!1};let V=J.fallbacks,X=Array.isArray(V)?V.filter((Y)=>Y!==null&&typeof Y==="object"&&!Array.isArray(Y)&&typeof Y.id==="string").map((Y)=>({id:Y.id,label:typeof Y.label==="string"?Y.label:void 0,...typeof Y.accountId==="string"?{accountId:Y.accountId}:{},quota:"quota"in Y?Y.quota:null,killed:typeof Y.killed==="boolean"?Y.killed:!1,enabled:typeof Y.enabled==="boolean"?Y.enabled:!0,...y(Y.resetCredits)})):[],K=typeof J.activeId==="string"?J.activeId:void 0,G=typeof J.route==="string"?J.route:Q.route,L=typeof J.lastUpdated==="number"?J.lastUpdated:0,z=typeof J.planType==="string"?J.planType:void 0,O=typeof J.credits==="number"?J.credits:void 0,D=Nj(J.activeRouting),B=_j(J.stickyAssignments);return{main:$,fallbacks:X,activeId:K,route:G,lastUpdated:L,...D!==void 0?{activeRouting:D}:{},...B!==void 0?{stickyAssignments:B}:{},...z!==void 0?{planType:z}:{},...O!==void 0?{credits:O}:{}}}async function wj(j=T()){try{let J=await c(j,"utf8");return x(JSON.parse(J))}catch{return Q}}var Pj=3600000,f=128;function s(j,J,Z=Date.now()){if(!(j.updatedAt>=Z-Pj&&j.updatedAt<=Z))return!1;if(J===void 0)return!0;return j.activeId==="main"||J.some((V)=>V.enabled!==!1&&V.killed!==!0&&V.id===j.activeId)}function Fj(j,J=Date.now()){let Z;for(let $ of r){let V=j?.[$];if(typeof V?.resetsAt!=="string"||!Number.isFinite(V.usedPercent)||V.usedPercent<100)continue;let X=Date.parse(V.resetsAt);if(!Number.isFinite(X)||X<=J)continue;if(!Z||X<Z.resetAtMs)Z={resetsAt:V.resetsAt,resetAtMs:X}}return Z}function _(j,J=Date.now()){return Fj(j,J)!==void 0}function Rj(j,J,Z=Date.now()){if(!J||j.route!=="sticky-balanced")return;let $=j.stickyAssignments?.[R(J)];if(!$||$.lastSeenAt<Z-b)return;if($.accountId==="main")return j.main?.killed||_(j.main?.quota,Z)?void 0:"main";let V=j.fallbacks?.find((X)=>X.id===$.accountId);if(!V||V.enabled===!1||V.killed===!0||_(V.quota,Z))return;return V.id}function mj(j,J,Z=Date.now()){if(!J)return{activeId:j.activeId??"main",route:j.route};let $=J?j.activeRouting?.[J]:void 0,V=$?.activeId==="main"?j.main.quota:j.fallbacks.find((L)=>L.id===$?.activeId)?.quota;if($&&s($,j.fallbacks,Z)&&!_(V,Z))return{activeId:$.activeId,route:$.route};let X=Rj(j,J,Z);if(X)return{activeId:X,route:j.route};let K=j.fallbacks.filter((L)=>L.enabled&&!L.killed),G=K.find((L)=>!_(L.quota,Z))??K[0];return{activeId:j.route==="fallback-first"&&G?G.id:"main",route:j.route}}function n(j,J,Z=Date.now(),$){if(!j)return;let V=Object.entries(j).filter(([K,G])=>K!==$&&s(G,J,Z)),X=V.length<=f?V:V.sort((K,G)=>G[1].updatedAt-K[1].updatedAt).slice(0,f);return X.length>0?Object.fromEntries(X):void 0}function W(j,J,Z=Date.now(),$){if(!j)return;let V=0,X=0,K=0,G=[];for(let[z,O]of Object.entries(j)){if(z===$){K+=1;continue}if(O.lastSeenAt<Z-b){X+=1;continue}if(J!==void 0&&!J.has(O.accountId)){V+=1;continue}G.push([z,O])}let L=V+X+K;if(L>0)M.debug("pruned sticky assignments",{pid:process.pid,removed:L,reasons:{"account-not-in-roster":V,expired:X,"explicit-removal":K}});return G.length>0?Object.fromEntries(G):void 0}function Wj(j,J){let Z=Object.keys(j).length-Uj;if(Z<=0)return j;let $=new Set(Object.entries(j).filter(([V])=>V!==J).sort(([V,X],[K,G])=>X.lastSeenAt-G.lastSeenAt||V.localeCompare(K)).slice(0,Z).map(([V])=>V));return Object.fromEntries(Object.entries(j).filter(([V])=>!$.has(V)))}function Ej(j,J){if(j===J)return!0;if(!j||!J)return!1;let Z=Object.entries(j);if(Z.length!==Object.keys(J).length)return!1;return Z.every(([$,V])=>Object.is(J[$],V))}function k(j,J,Z,$){return j!==void 0&&J.has(j.accountId)&&!Z.has(j.accountId)&&j.lastSeenAt>=$-b}function A(j,J,Z,$){return J>j.inputBytes||Z-j.lastSeenAt>=i||j.wireAccountId===void 0&&$!==void 0}function p(j,J){return typeof j.wireAccountId==="string"&&typeof J==="string"&&j.wireAccountId!==J}function Cj(j){let J=new Map(j),Z={get size(){return J.size},has:($)=>J.has($),get:($)=>J.get($),entries:()=>J.entries(),keys:()=>J.keys(),values:()=>J.values(),forEach:($,V)=>{J.forEach((X,K)=>{$.call(V,X,K,Z)})},[Symbol.iterator]:()=>J[Symbol.iterator]()};return Object.freeze(Z)}function Hj(j,J,Z){let $=new Map;for(let[V,X]of Object.entries(j??{})){if(V===Z)continue;if(X.quotaCheckedAt!==J[X.accountId])continue;$.set(X.accountId,($.get(X.accountId)??0)+X.inputBytes)}return Cj($)}function v(j){if(j===void 0)return;return new Set(["main",...j.filter((J)=>J.enabled!==!1&&J.killed!==!0).map((J)=>J.id)])}var C=Promise.resolve(),qj=3,Mj=1e4,bj=15000;function U(j){let J=C.then(j);return C=J.catch(()=>{}),J}function gj(j,J=T()){return U(()=>q(j,J))}async function t(j){try{return e(await H(j))}catch{return Q}}async function H(j){try{return await c(j,"utf8")}catch(J){if(J.code==="ENOENT")return"";throw J}}function e(j){if(j==="")return Q;try{return x(JSON.parse(j))}catch{return Q}}async function xj(j){await jj(j);let J=Date.now()+bj;while(Date.now()<=J){let Z=await l({name:"sidebar-write",path:j,ttlMs:Mj,renew:!0});if(Z)return Z;await new Promise(($)=>setTimeout($,10))}throw Error("Timed out waiting for the sidebar state write lock")}async function jj(j){let J=Dj(j);if(await Kj(J,{recursive:!0,mode:448}),j!==a)return;await Xj(J,448).catch((Z)=>{M.warn("sidebar directory permission remediation failed",{pid:process.pid,error:Z instanceof Error?Z.message:String(Z)})})}async function N(j,J,Z){let $=await xj(j);try{for(let K=0;K<qj;K+=1){let G=await H(j),L=J(e(G));if(!L)return;if(K===0)await Z?.beforeRecheck?.();if(await H(j)!==G)continue;await q(L,j);return}let V=await t(j),X=J(V);if(X)await q(X,j)}finally{await $.release()}}function P(j){let J;for(let Z of[j?.primary?.checkedAt,j?.secondary?.checkedAt,j?.checkedAt])if(typeof Z==="number"&&Number.isFinite(Z))J=J===void 0?Z:Math.max(J,Z);return J}function h(j,J){let Z=P(j),$=P(J);if($!==void 0&&(Z===void 0||$>Z))return J;return j}function w(j,J){return j!==void 0&&J!==void 0&&j===J}function F(j,J){let Z=j?.checkedAt;if(typeof Z==="number"&&Number.isFinite(Z))return Z;if(typeof J==="number"&&Number.isFinite(J))return J;return}function m(j,J,Z,$,V){if(j&&J){let X=F(j,$),K=F(J,V);if(K!==void 0&&(X===void 0||K>X))return J;return j}return Z?J:j}function g(j,J){if(!j)return J;if(!J)return j;let Z=P(j),$=P(J),V=$!==void 0&&(Z===void 0||$>Z),X=m(j.primary,J.primary,V,j.checkedAt,J.checkedAt),K=m(j.secondary,J.secondary,V,j.checkedAt,J.checkedAt),G;for(let L of[F(X),F(K)])if(L!==void 0)G=G===void 0?L:Math.max(G,L);return{...j,primary:X,secondary:K,checkedAt:G??j.checkedAt}}function dj(j,J=T(),Z){return U(async()=>{await N(J,($)=>{let V=new Map($.fallbacks.map((z)=>[z.id,z])),X=w(j.main.mainAccountId,$.main.mainAccountId),K=X?g(j.main.quota,$.main.quota):h(j.main.quota,$.main.quota),G=Date.now(),L=W($.stickyAssignments,v(j.fallbacks),G);return{...$,...j,main:{...j.main,quota:K,mainAccountId:X?j.main.mainAccountId:K===$.main.quota&&K!==j.main.quota?$.main.mainAccountId:j.main.mainAccountId},fallbacks:j.fallbacks.map((z)=>{let O=V.get(z.id),D=w(z.accountId,O?.accountId),B=D?g(z.quota,O?.quota??null):h(z.quota,O?.quota??null);return{...z,quota:B,accountId:D?z.accountId:B===O?.quota&&B!==z.quota?O?.accountId:z.accountId}}),activeId:$.activeId,activeRouting:$.activeRouting,stickyAssignments:L,lastUpdated:Math.max(G,$.lastUpdated+1)}},Z)})}function lj(j,J,Z=T(),$){return U(async()=>{await N(Z,(V)=>{let X=n({...V.activeRouting,[j.sessionId]:{activeId:j.activeId,route:j.route,updatedAt:j.updatedAt}},J,Date.now()),K=W(V.stickyAssignments,v(J),Date.now());return{...V,activeId:j.activeId,route:j.route,activeRouting:X,stickyAssignments:K,lastUpdated:Math.max(Date.now(),V.lastUpdated+1)}},$)})}function rj(j,J=T()){return U(async()=>{await N(J,(Z)=>({...Z,activeId:j.activeId,route:j.route,lastUpdated:Math.max(Date.now(),Z.lastUpdated+1)}))})}function uj(j,J,Z=T(),$){return U(async()=>{await N(Z,(V)=>{let X=Date.now(),K=n(V.activeRouting,J,X,j),G=W(V.stickyAssignments,v(J),X,R(j));return{...V,activeRouting:K,stickyAssignments:G,lastUpdated:Math.max(Date.now(),V.lastUpdated+1)}},$)})}async function cj(j,J=T(),Z){let $=R(j.sessionId),V=new Set(j.validPinnedAccountIds),X=new Set(j.excludeAccountIds),K=(await t(J)).stickyAssignments?.[$];if(k(K,V,X,j.now)&&!p(K,j.wireAccountIdByAccount?.[K.accountId])&&!A(K,j.requestBytes,j.now,j.wireAccountIdByAccount?.[K.accountId]))return K;let G;return await U(async()=>{await N(J,(L)=>{let z=W(L.stickyAssignments,V,j.now),O=!Ej(L.stickyAssignments,z),D=z?.[$],B=D!==void 0&&p(D,j.wireAccountIdByAccount?.[D.accountId]);if(k(D,V,X,j.now)&&!B){let I=A(D,j.requestBytes,j.now,j.wireAccountIdByAccount?.[D.accountId]),S=I?{...D,inputBytes:Math.max(D.inputBytes,j.requestBytes),...D.wireAccountId===void 0&&j.wireAccountIdByAccount?.[D.accountId]!==void 0?{wireAccountId:j.wireAccountIdByAccount?.[D.accountId]}:{},...j.now-D.lastSeenAt>=i?{lastSeenAt:j.now}:{}}:D;if(G=S,!O&&!I)return;return{...L,stickyAssignments:{...z,[$]:S},lastUpdated:Math.max(j.now,L.lastUpdated+1)}}let Y=j.choose(Hj(z,j.quotaCheckedAtByAccount,B?$:void 0));if(!Y){if(G=void 0,!O)return;return{...L,stickyAssignments:z,lastUpdated:Math.max(j.now,L.lastUpdated+1)}}return G={accountId:Y.accountId,assignedAt:j.now,lastSeenAt:j.now,inputBytes:j.requestBytes,...Y.quotaCheckedAt===void 0?{}:{quotaCheckedAt:Y.quotaCheckedAt},...j.wireAccountIdByAccount?.[Y.accountId]===void 0?{}:{wireAccountId:j.wireAccountIdByAccount?.[Y.accountId]}},{...L,stickyAssignments:Wj({...z,[$]:G},$),lastUpdated:Math.max(j.now,L.lastUpdated+1)}},Z)}),G}async function oj(j,J=T()){let Z=R(j),$=!1;return await U(async()=>{await N(J,(V)=>{let X=V.stickyAssignments;if(X?.[Z]===void 0){$=!1;return}$=!0;let{[Z]:K,...G}=X;return{...V,...Object.keys(G).length>0?{stickyAssignments:G}:{stickyAssignments:void 0},lastUpdated:Math.max(Date.now(),V.lastUpdated+1)}})}),$}async function q(j,J){let Z=`${J}.${Vj()}.tmp`;try{await jj(J),await Lj(Z,JSON.stringify(x(j)),{encoding:"utf8",mode:384}),await Yj(Z,J)}catch($){throw await Gj(Z,{force:!0}).catch(()=>{}),M.warn("sidebar write failed",{pid:process.pid,error:$ instanceof Error?$.message:String($)}),$}}function aj(){return C}function ij(j){let J=j.activeId;if(J&&J!=="main"){let Z=j.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:j.main.quota,killed:j.main.killed}}function sj(j){let J=j?.primary?.usedPercent??null,Z=j?.secondary?.usedPercent??null,$=Zj(j);return{primaryUsedPercent:J,secondaryUsedPercent:Z,text:$.length===0?null:$.map(({label:V,window:X})=>`${V}: ${Math.round(X.usedPercent)}%`).join(" ")}}var vj=300000,Ij=0.01,Sj=1;function nj(j,J,Z){if(!j.resetsAt)return null;let $=new Date(j.resetsAt).getTime();if(!Number.isFinite($))return null;let V=$-J,X=Z-V;if(X<vj)return null;if(X<J*Ij)return null;if(X>=J)return null;let K=j.usedPercent,G=Math.min(Math.max(X/J*100,0),100),L=K-G,z=Math.abs(L)<Sj?"on-pace":L>0?"deficit":"reserve",O=null;if(K>0){let D=X*100/K,B=V+D;if(B<$)O=new Date(B).toISOString()}return{pacePercent:G,deltaPercent:L,state:z,runsOutAt:O}}
|
|
1
|
+
import{wa as l}from"./index-8f1200qx.js";import{Ca as d}from"./index-80gqxa1f.js";import{createHash as $j,randomUUID as Vj}from"node:crypto";import{chmod as Xj,mkdir as Kj,readFile as c,rename as Yj,rm as Gj,writeFile as Lj}from"node:fs/promises";import{tmpdir as zj}from"node:os";import{dirname as Dj,join as o}from"node:path";var r=["primary","secondary"],u={primary:300,secondary:10080};function E(j){return Number.isInteger(j)?String(j):String(Math.round(j*10)/10)}function Jj(j,J){let Z=j!==void 0&&Number.isFinite(j)&&j>0?j:u[J];if(Z<60)return`${E(Z)}m`;if(Z<1440)return`${E(Z/60)}h`;return`${E(Z/1440)}d`}function Zj(j){if(!j)return[];let J=[];for(let Z of r){let $=j[Z];if(!$)continue;let V=$.windowMinutes,X=V!==void 0&&Number.isFinite(V)&&V>0?V:u[Z];J.push({key:Z,label:Jj(X,Z),window:$,windowMs:X*60000})}return J}var M=d("sidebar"),Oj="OPENCODE_OPENAI_AUTH_SIDEBAR_STATE_FILE",Bj=o(zj(),"opencode-openai-auth"),a=o(Bj,"sidebar-state.json"),Tj=/^[a-f0-9]{64}$/,b=604800000,Uj=256,i=3600000;function R(j){return $j("sha256").update(j).digest("hex")}function Qj(j){return typeof j==="number"&&Number.isFinite(j)&&j>=0?j:void 0}function y(j){let J=Qj(j);return J!==void 0?{resetCredits:J}:{}}function Nj(j){if(j===null||typeof j!=="object"||Array.isArray(j))return;let J={};for(let[Z,$]of Object.entries(j)){if($===null||typeof $!=="object"||Array.isArray($))continue;let V=$;if(typeof V.activeId!=="string"||typeof V.route!=="string"||typeof V.updatedAt!=="number"||!Number.isFinite(V.updatedAt))continue;J[Z]={activeId:V.activeId,route:V.route,updatedAt:V.updatedAt}}return Object.keys(J).length>0?J:void 0}function _j(j){if(j===null||typeof j!=="object"||Array.isArray(j))return;let J={};for(let[Z,$]of Object.entries(j)){if(!Tj.test(Z)||$===null||typeof $!=="object"||Array.isArray($))continue;let V=$;if(typeof V.accountId!=="string"||V.accountId.length===0||typeof V.assignedAt!=="number"||!Number.isFinite(V.assignedAt)||V.assignedAt<0||typeof V.lastSeenAt!=="number"||!Number.isFinite(V.lastSeenAt)||V.lastSeenAt<0||typeof V.inputBytes!=="number"||!Number.isFinite(V.inputBytes)||V.inputBytes<0)continue;let X=V.quotaCheckedAt;if(X!==void 0&&(typeof X!=="number"||!Number.isFinite(X)||X<0))continue;let K=V.wireAccountId;J[Z]={accountId:V.accountId,assignedAt:V.assignedAt,lastSeenAt:V.lastSeenAt,inputBytes:V.inputBytes,...X===void 0?{}:{quotaCheckedAt:X},...typeof K==="string"?{wireAccountId:K}:{}}}return Object.keys(J).length>0?J:void 0}function T(){return process.env[Oj]||a}var Q={main:{quota:null,killed:!1},fallbacks:[],activeId:void 0,route:"main",lastUpdated:0};function x(j){if(j===null||typeof j!=="object"||Array.isArray(j))return Q;let J=j,Z=J.main,$;if(Z!==null&&typeof Z==="object"&&!Array.isArray(Z)){let Y=Z;$={quota:"quota"in Y?Y.quota:null,killed:typeof Y.killed==="boolean"?Y.killed:!1,...typeof Y.mainAccountId==="string"?{mainAccountId:Y.mainAccountId}:{},...typeof Y.quotaBackedOff==="boolean"?{quotaBackedOff:Y.quotaBackedOff}:{},...typeof Y.quotaBackoffUntil==="number"?{quotaBackoffUntil:Y.quotaBackoffUntil}:{},...typeof Y.refreshBackedOff==="boolean"?{refreshBackedOff:Y.refreshBackedOff}:{},...typeof Y.refreshBackoffUntil==="number"?{refreshBackoffUntil:Y.refreshBackoffUntil}:{},...y(Y.resetCredits)}}else $={quota:null,killed:!1};let V=J.fallbacks,X=Array.isArray(V)?V.filter((Y)=>Y!==null&&typeof Y==="object"&&!Array.isArray(Y)&&typeof Y.id==="string").map((Y)=>({id:Y.id,label:typeof Y.label==="string"?Y.label:void 0,...typeof Y.accountId==="string"?{accountId:Y.accountId}:{},quota:"quota"in Y?Y.quota:null,killed:typeof Y.killed==="boolean"?Y.killed:!1,enabled:typeof Y.enabled==="boolean"?Y.enabled:!0,...y(Y.resetCredits)})):[],K=typeof J.activeId==="string"?J.activeId:void 0,G=typeof J.route==="string"?J.route:Q.route,L=typeof J.lastUpdated==="number"?J.lastUpdated:0,z=typeof J.planType==="string"?J.planType:void 0,O=typeof J.credits==="number"?J.credits:void 0,D=Nj(J.activeRouting),B=_j(J.stickyAssignments);return{main:$,fallbacks:X,activeId:K,route:G,lastUpdated:L,...D!==void 0?{activeRouting:D}:{},...B!==void 0?{stickyAssignments:B}:{},...z!==void 0?{planType:z}:{},...O!==void 0?{credits:O}:{}}}async function wj(j=T()){try{let J=await c(j,"utf8");return x(JSON.parse(J))}catch{return Q}}var Pj=3600000,f=128;function s(j,J,Z=Date.now()){if(!(j.updatedAt>=Z-Pj&&j.updatedAt<=Z))return!1;if(J===void 0)return!0;return j.activeId==="main"||J.some((V)=>V.enabled!==!1&&V.killed!==!0&&V.id===j.activeId)}function Fj(j,J=Date.now()){let Z;for(let $ of r){let V=j?.[$];if(typeof V?.resetsAt!=="string"||!Number.isFinite(V.usedPercent)||V.usedPercent<100)continue;let X=Date.parse(V.resetsAt);if(!Number.isFinite(X)||X<=J)continue;if(!Z||X<Z.resetAtMs)Z={resetsAt:V.resetsAt,resetAtMs:X}}return Z}function _(j,J=Date.now()){return Fj(j,J)!==void 0}function Rj(j,J,Z=Date.now()){if(!J||j.route!=="sticky-balanced")return;let $=j.stickyAssignments?.[R(J)];if(!$||$.lastSeenAt<Z-b)return;if($.accountId==="main")return j.main?.killed||_(j.main?.quota,Z)?void 0:"main";let V=j.fallbacks?.find((X)=>X.id===$.accountId);if(!V||V.enabled===!1||V.killed===!0||_(V.quota,Z))return;return V.id}function mj(j,J,Z=Date.now()){if(!J)return{activeId:j.activeId??"main",route:j.route};let $=J?j.activeRouting?.[J]:void 0,V=$?.activeId==="main"?j.main.quota:j.fallbacks.find((L)=>L.id===$?.activeId)?.quota;if($&&s($,j.fallbacks,Z)&&!_(V,Z))return{activeId:$.activeId,route:$.route};let X=Rj(j,J,Z);if(X)return{activeId:X,route:j.route};let K=j.fallbacks.filter((L)=>L.enabled&&!L.killed),G=K.find((L)=>!_(L.quota,Z))??K[0];return{activeId:j.route==="fallback-first"&&G?G.id:"main",route:j.route}}function n(j,J,Z=Date.now(),$){if(!j)return;let V=Object.entries(j).filter(([K,G])=>K!==$&&s(G,J,Z)),X=V.length<=f?V:V.sort((K,G)=>G[1].updatedAt-K[1].updatedAt).slice(0,f);return X.length>0?Object.fromEntries(X):void 0}function W(j,J,Z=Date.now(),$){if(!j)return;let V=0,X=0,K=0,G=[];for(let[z,O]of Object.entries(j)){if(z===$){K+=1;continue}if(O.lastSeenAt<Z-b){X+=1;continue}if(J!==void 0&&!J.has(O.accountId)){V+=1;continue}G.push([z,O])}let L=V+X+K;if(L>0)M.debug("pruned sticky assignments",{pid:process.pid,removed:L,reasons:{"account-not-in-roster":V,expired:X,"explicit-removal":K}});return G.length>0?Object.fromEntries(G):void 0}function Wj(j,J){let Z=Object.keys(j).length-Uj;if(Z<=0)return j;let $=new Set(Object.entries(j).filter(([V])=>V!==J).sort(([V,X],[K,G])=>X.lastSeenAt-G.lastSeenAt||V.localeCompare(K)).slice(0,Z).map(([V])=>V));return Object.fromEntries(Object.entries(j).filter(([V])=>!$.has(V)))}function Ej(j,J){if(j===J)return!0;if(!j||!J)return!1;let Z=Object.entries(j);if(Z.length!==Object.keys(J).length)return!1;return Z.every(([$,V])=>Object.is(J[$],V))}function k(j,J,Z,$){return j!==void 0&&J.has(j.accountId)&&!Z.has(j.accountId)&&j.lastSeenAt>=$-b}function A(j,J,Z,$){return J>j.inputBytes||Z-j.lastSeenAt>=i||j.wireAccountId===void 0&&$!==void 0}function p(j,J){return typeof j.wireAccountId==="string"&&typeof J==="string"&&j.wireAccountId!==J}function Cj(j){let J=new Map(j),Z={get size(){return J.size},has:($)=>J.has($),get:($)=>J.get($),entries:()=>J.entries(),keys:()=>J.keys(),values:()=>J.values(),forEach:($,V)=>{J.forEach((X,K)=>{$.call(V,X,K,Z)})},[Symbol.iterator]:()=>J[Symbol.iterator]()};return Object.freeze(Z)}function Hj(j,J,Z){let $=new Map;for(let[V,X]of Object.entries(j??{})){if(V===Z)continue;if(X.quotaCheckedAt!==J[X.accountId])continue;$.set(X.accountId,($.get(X.accountId)??0)+X.inputBytes)}return Cj($)}function v(j){if(j===void 0)return;return new Set(["main",...j.filter((J)=>J.enabled!==!1&&J.killed!==!0).map((J)=>J.id)])}var C=Promise.resolve(),qj=3,Mj=1e4,bj=15000;function U(j){let J=C.then(j);return C=J.catch(()=>{}),J}function gj(j,J=T()){return U(()=>q(j,J))}async function t(j){try{return e(await H(j))}catch{return Q}}async function H(j){try{return await c(j,"utf8")}catch(J){if(J.code==="ENOENT")return"";throw J}}function e(j){if(j==="")return Q;try{return x(JSON.parse(j))}catch{return Q}}async function xj(j){await jj(j);let J=Date.now()+bj;while(Date.now()<=J){let Z=await l({name:"sidebar-write",path:j,ttlMs:Mj,renew:!0});if(Z)return Z;await new Promise(($)=>setTimeout($,10))}throw Error("Timed out waiting for the sidebar state write lock")}async function jj(j){let J=Dj(j);if(await Kj(J,{recursive:!0,mode:448}),j!==a)return;await Xj(J,448).catch((Z)=>{M.warn("sidebar directory permission remediation failed",{pid:process.pid,error:Z instanceof Error?Z.message:String(Z)})})}async function N(j,J,Z){let $=await xj(j);try{for(let K=0;K<qj;K+=1){let G=await H(j),L=J(e(G));if(!L)return;if(K===0)await Z?.beforeRecheck?.();if(await H(j)!==G)continue;await q(L,j);return}let V=await t(j),X=J(V);if(X)await q(X,j)}finally{await $.release()}}function P(j){let J;for(let Z of[j?.primary?.checkedAt,j?.secondary?.checkedAt,j?.checkedAt])if(typeof Z==="number"&&Number.isFinite(Z))J=J===void 0?Z:Math.max(J,Z);return J}function h(j,J){let Z=P(j),$=P(J);if($!==void 0&&(Z===void 0||$>Z))return J;return j}function w(j,J){return j!==void 0&&J!==void 0&&j===J}function F(j,J){let Z=j?.checkedAt;if(typeof Z==="number"&&Number.isFinite(Z))return Z;if(typeof J==="number"&&Number.isFinite(J))return J;return}function m(j,J,Z,$,V){if(j&&J){let X=F(j,$),K=F(J,V);if(K!==void 0&&(X===void 0||K>X))return J;return j}return Z?J:j}function g(j,J){if(!j)return J;if(!J)return j;let Z=P(j),$=P(J),V=$!==void 0&&(Z===void 0||$>Z),X=m(j.primary,J.primary,V,j.checkedAt,J.checkedAt),K=m(j.secondary,J.secondary,V,j.checkedAt,J.checkedAt),G;for(let L of[F(X),F(K)])if(L!==void 0)G=G===void 0?L:Math.max(G,L);return{...j,primary:X,secondary:K,checkedAt:G??j.checkedAt}}function dj(j,J=T(),Z){return U(async()=>{await N(J,($)=>{let V=new Map($.fallbacks.map((z)=>[z.id,z])),X=w(j.main.mainAccountId,$.main.mainAccountId),K=X?g(j.main.quota,$.main.quota):h(j.main.quota,$.main.quota),G=Date.now(),L=W($.stickyAssignments,v(j.fallbacks),G);return{...$,...j,main:{...j.main,quota:K,mainAccountId:X?j.main.mainAccountId:K===$.main.quota&&K!==j.main.quota?$.main.mainAccountId:j.main.mainAccountId},fallbacks:j.fallbacks.map((z)=>{let O=V.get(z.id),D=w(z.accountId,O?.accountId),B=D?g(z.quota,O?.quota??null):h(z.quota,O?.quota??null);return{...z,quota:B,accountId:D?z.accountId:B===O?.quota&&B!==z.quota?O?.accountId:z.accountId}}),activeId:$.activeId,activeRouting:$.activeRouting,stickyAssignments:L,lastUpdated:Math.max(G,$.lastUpdated+1)}},Z)})}function lj(j,J,Z=T(),$){return U(async()=>{await N(Z,(V)=>{let X=n({...V.activeRouting,[j.sessionId]:{activeId:j.activeId,route:j.route,updatedAt:j.updatedAt}},J,Date.now()),K=W(V.stickyAssignments,v(J),Date.now());return{...V,activeId:j.activeId,route:j.route,activeRouting:X,stickyAssignments:K,lastUpdated:Math.max(Date.now(),V.lastUpdated+1)}},$)})}function rj(j,J=T()){return U(async()=>{await N(J,(Z)=>({...Z,activeId:j.activeId,route:j.route,lastUpdated:Math.max(Date.now(),Z.lastUpdated+1)}))})}function uj(j,J,Z=T(),$){return U(async()=>{await N(Z,(V)=>{let X=Date.now(),K=n(V.activeRouting,J,X,j),G=W(V.stickyAssignments,v(J),X,R(j));return{...V,activeRouting:K,stickyAssignments:G,lastUpdated:Math.max(Date.now(),V.lastUpdated+1)}},$)})}async function cj(j,J=T(),Z){let $=R(j.sessionId),V=new Set(j.validPinnedAccountIds),X=new Set(j.excludeAccountIds),K=(await t(J)).stickyAssignments?.[$];if(k(K,V,X,j.now)&&!p(K,j.wireAccountIdByAccount?.[K.accountId])&&!A(K,j.requestBytes,j.now,j.wireAccountIdByAccount?.[K.accountId]))return K;let G;return await U(async()=>{await N(J,(L)=>{let z=W(L.stickyAssignments,V,j.now),O=!Ej(L.stickyAssignments,z),D=z?.[$],B=D!==void 0&&p(D,j.wireAccountIdByAccount?.[D.accountId]);if(k(D,V,X,j.now)&&!B){let I=A(D,j.requestBytes,j.now,j.wireAccountIdByAccount?.[D.accountId]),S=I?{...D,inputBytes:Math.max(D.inputBytes,j.requestBytes),...D.wireAccountId===void 0&&j.wireAccountIdByAccount?.[D.accountId]!==void 0?{wireAccountId:j.wireAccountIdByAccount?.[D.accountId]}:{},...j.now-D.lastSeenAt>=i?{lastSeenAt:j.now}:{}}:D;if(G=S,!O&&!I)return;return{...L,stickyAssignments:{...z,[$]:S},lastUpdated:Math.max(j.now,L.lastUpdated+1)}}let Y=j.choose(Hj(z,j.quotaCheckedAtByAccount,B?$:void 0));if(!Y){if(G=void 0,!O)return;return{...L,stickyAssignments:z,lastUpdated:Math.max(j.now,L.lastUpdated+1)}}return G={accountId:Y.accountId,assignedAt:j.now,lastSeenAt:j.now,inputBytes:j.requestBytes,...Y.quotaCheckedAt===void 0?{}:{quotaCheckedAt:Y.quotaCheckedAt},...j.wireAccountIdByAccount?.[Y.accountId]===void 0?{}:{wireAccountId:j.wireAccountIdByAccount?.[Y.accountId]}},{...L,stickyAssignments:Wj({...z,[$]:G},$),lastUpdated:Math.max(j.now,L.lastUpdated+1)}},Z)}),G}async function oj(j,J=T()){let Z=R(j),$=!1;return await U(async()=>{await N(J,(V)=>{let X=V.stickyAssignments;if(X?.[Z]===void 0){$=!1;return}$=!0;let{[Z]:K,...G}=X;return{...V,...Object.keys(G).length>0?{stickyAssignments:G}:{stickyAssignments:void 0},lastUpdated:Math.max(Date.now(),V.lastUpdated+1)}})}),$}async function q(j,J){let Z=`${J}.${Vj()}.tmp`;try{await jj(J),await Lj(Z,JSON.stringify(x(j)),{encoding:"utf8",mode:384}),await Yj(Z,J)}catch($){throw await Gj(Z,{force:!0}).catch(()=>{}),M.warn("sidebar write failed",{pid:process.pid,error:$ instanceof Error?$.message:String($)}),$}}function aj(){return C}function ij(j){let J=j.activeId;if(J&&J!=="main"){let Z=j.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:j.main.quota,killed:j.main.killed}}function sj(j){let J=j?.primary?.usedPercent??null,Z=j?.secondary?.usedPercent??null,$=Zj(j);return{primaryUsedPercent:J,secondaryUsedPercent:Z,text:$.length===0?null:$.map(({label:V,window:X})=>`${V}: ${Math.round(X.usedPercent)}%`).join(" ")}}var vj=300000,Ij=0.01,Sj=1;function nj(j,J,Z){if(!j.resetsAt)return null;let $=new Date(j.resetsAt).getTime();if(!Number.isFinite($))return null;let V=$-J,X=Z-V;if(X<vj)return null;if(X<J*Ij)return null;if(X>=J)return null;let K=j.usedPercent,G=Math.min(Math.max(X/J*100,0),100),L=K-G,z=Math.abs(L)<Sj?"on-pace":L>0?"deficit":"reserve",O=null;if(K>0){let D=X*100/K,B=V+D;if(B<$)O=new Date(B).toISOString()}return{pacePercent:G,deltaPercent:L,state:z,runsOutAt:O}}
|
|
2
2
|
export{Jj as T,Zj as U,b as V,Uj as W,R as X,T as Y,Q as Z,x as _,wj as $,Pj as aa,f as ba,s as ca,Fj as da,_ as ea,Rj as fa,mj as ga,n as ha,W as ia,gj as ja,dj as ka,lj as la,rj as ma,uj as na,cj as oa,oj as pa,aj as qa,ij as ra,sj as sa,nj as ta};
|