@cortexkit/opencode-openai-auth 0.1.4 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -1,14 +1,14 @@
1
1
  #!/usr/bin/env node
2
- import{D as $,H as Q,I as W,y as Y,z as Z}from"./index-m9dtkj3q.js";import"./index-0s5tftne.js";import{ea as X}from"./index-hrg6bdgb.js";import{execFileSync as q}from"node:child_process";function T(D,J=process.platform,H=q){try{if(J==="win32"){H("cmd",["/c","start","",D],{stdio:"ignore",timeout:3000});return}H(J==="darwin"?"open":"xdg-open",[D],{stdio:"ignore",timeout:3000})}catch{}}function V(){console.log(`Usage:
2
+ import{D as $,H as q,J as V,y as Y,z as Z}from"./index-nzqvhshr.js";import"./index-garxs63s.js";import{ia as X}from"./index-2b5wejq3.js";import{execFileSync as B}from"node:child_process";function Q(C,H=process.platform,D=B){try{if(H==="win32"){D("cmd",["/c","start","",C],{stdio:"ignore",timeout:3000});return}D(H==="darwin"?"open":"xdg-open",[C],{stdio:"ignore",timeout:3000})}catch{}}function T(){console.log(`Usage:
3
3
  openai-auth login [--label <name>] [--headless]
4
4
  openai-auth list
5
5
  openai-auth remove <id>
6
6
 
7
7
  Fallback accounts are stored in:
8
- ${$()}`)}function B(D){let J=[],H={};for(let M=0;M<D.length;M++){let z=D[M];if(!z)continue;if(z.startsWith("--")){let C=z.slice(2),G=D[M+1];if(G&&!G.startsWith("--"))H[C]=G,M++;else H[C]=!0}else J.push(z)}return{positional:J,flags:H}}async function E(){let{positional:D,flags:J}=B(process.argv.slice(2)),[H,...M]=D;if(!H||H==="help")V(),process.exit(0);switch(H){case"login":{let z=typeof J.label==="string"?J.label:void 0,C=Boolean(J.headless),{url:G,instructions:K,completion:j}=await Z({label:z,headless:C});if(console.log(`
8
+ ${$()}`)}function E(C){let H=[],D={};for(let K=0;K<C.length;K++){let j=C[K];if(!j)continue;if(j.startsWith("--")){let G=j.slice(2),z=C[K+1];if(z&&!z.startsWith("--"))D[G]=z,K++;else D[G]=!0}else H.push(j)}return{positional:H,flags:D}}async function P(){let{positional:C,flags:H}=E(process.argv.slice(2)),[D,...K]=C;if(!D||D==="help")T(),process.exit(0);switch(D){case"login":{let j=typeof H.label==="string"?H.label:void 0,G=Boolean(H.headless),{url:z,instructions:J,completion:O}=await Z({label:j,headless:G});if(console.log(`
9
9
  Open this URL in your browser and complete sign-in:
10
- `),console.log(`${G}
11
- `),K)console.log(`${K}
12
- `);T(G);let N=await j,O=await Q()??{version:1,accounts:[]};if(N.accountId&&O.mainAccountId&&N.accountId===O.mainAccountId)console.error(`
13
- 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(Y(O.accounts,N),await W(O),console.log(`
14
- ✓ Added account ${N.id}`),N.label)console.log(` Label: ${N.label}`);break}case"list":{let z=await Q();if(!z||z.accounts.length===0)console.log("No fallback accounts configured.");else for(let C of z.accounts){let G=C.label,K=[` ${C.id}`];if(G)K.push(`(${G})`);K.push(C.enabled!==!1?"[enabled]":"[disabled]"),console.log(K.join(" "))}break}case"remove":{let z=M[0];if(!z)console.error("Error: remove requires an account ID."),V(),process.exit(1);let C=await Q();if(!C)console.error("No account store found."),process.exit(1);let G=C.accounts.findIndex((K)=>K.id===z);if(G===-1)console.error(`No account with id "${z}".`),process.exit(1);C.accounts.splice(G,1),await W(C),console.log(`Removed account ${z}.`);break}default:console.error(`Unknown command: ${H}`),V(),process.exit(1)}}if(X.main==X.module)E().catch((D)=>{console.error(D instanceof Error?D.message:String(D)),process.exit(1)});export{T as openBrowserForLogin};
10
+ `),console.log(`${z}
11
+ `),J)console.log(`${J}
12
+ `);Q(z);let M=await O,W=!1;if(await V((N)=>{if(M.accountId&&N.mainAccountId&&M.accountId===N.mainAccountId)return W=!0,N;return Y(N.accounts,M),N}),W)console.error(`
13
+ 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(`
14
+ ✓ Added account ${M.id}`),M.label)console.log(` Label: ${M.label}`);break}case"list":{let j=await q();if(!j||j.accounts.length===0)console.log("No fallback accounts configured.");else for(let G of j.accounts){let z=G.label,J=[` ${G.id}`];if(z)J.push(`(${z})`);J.push(G.enabled!==!1?"[enabled]":"[disabled]"),console.log(J.join(" "))}break}case"remove":{let j=K[0];if(!j)console.error("Error: remove requires an account ID."),T(),process.exit(1);let G=!1;if(await V((z)=>{let J=z.accounts.findIndex((O)=>O.id===j);if(J===-1)return z;return G=!0,z.accounts.splice(J,1),z}),!G)console.error(`No account with id "${j}".`),process.exit(1);console.log(`Removed account ${j}.`);break}default:console.error(`Unknown command: ${D}`),T(),process.exit(1)}}if(X.main==X.module)P().catch((C)=>{console.error(C instanceof Error?C.message:String(C)),process.exit(1)});export{Q as openBrowserForLogin};
package/dist/config.d.ts CHANGED
@@ -8,7 +8,9 @@ export interface OpenAIAuthConfig {
8
8
  /** Use the hand-rolled raw TCP/TLS WebSocket client (incremental streaming). Default false. */
9
9
  rawWebSocket?: boolean;
10
10
  /** Dump final Codex request bodies for cache debugging. Default false. */
11
- dump?: boolean;
11
+ dump?: boolean | {
12
+ enabled?: boolean;
13
+ };
12
14
  /** Directory for request dumps. Defaults to the OS temp directory. */
13
15
  dumpDir?: string;
14
16
  /** Codex-compatible Responses endpoint. Defaults to ChatGPT's Codex backend. */
@@ -149,6 +149,23 @@ export declare const DEFAULT_KILLSWITCH_THRESHOLDS: {
149
149
  };
150
150
  export declare function loadAccounts(path?: string): Promise<AccountStorage | null>;
151
151
  export declare function saveAccounts(storage: AccountStorage, path?: string): Promise<void>;
152
+ /**
153
+ * Read-modify-write the account store atomically under the save lock.
154
+ *
155
+ * Unlike saveAccounts (which UNION-merges the incoming accounts with the latest
156
+ * on-disk set so concurrent ADDS from another process are never lost), this
157
+ * reads the freshest state under the lock and writes the mutator's result
158
+ * AUTHORITATIVELY — no union. That is required for structural edits (remove,
159
+ * reorder): a union cannot express a deletion (the removed id reappears from
160
+ * `latest`) or a reordering (the union is seeded latest-first). Because the
161
+ * mutator runs against freshly-read state under the lock, an add committed by a
162
+ * concurrent process is still visible to it and preserved.
163
+ *
164
+ * The mutator may edit `current` in place and return it, or return a new
165
+ * storage object. Returning undefined means "no change" and still rewrites the
166
+ * freshly-read state (a harmless idempotent write).
167
+ */
168
+ export declare function mutateAccounts(mutate: (current: AccountStorage) => AccountStorage | undefined, path?: string): Promise<AccountStorage>;
152
169
  export declare function saveAccountState(storage: AccountStorage, path?: string, scope?: AccountStateSaveScope): Promise<void>;
153
170
  export declare function shouldFallbackStatus(status: number, storage: AccountStorage | null): boolean;
154
171
  export declare function quotaSnapshotPassesPolicy(quota: OAuthQuotaSnapshot | undefined, storage: AccountStorage | null): boolean;
@@ -83,12 +83,15 @@ export declare class CacheKeepManager {
83
83
  private startedAt;
84
84
  private totalBytes;
85
85
  private tickInFlight;
86
+ private disposed;
87
+ private abortController;
86
88
  private logPayload;
87
89
  constructor(options: CacheKeepManagerOptions);
88
90
  track(sessionKey: string, bodyText: string, accountId: string | undefined, chatgptAccountId?: string, replayHeaders?: Record<string, string>, isSubagent?: boolean): void;
89
91
  private pruneStale;
90
92
  start(): void;
91
93
  stop(): void;
94
+ remove(sessionKey: string): void;
92
95
  status(): CacheKeepStatus;
93
96
  tick(): Promise<void>;
94
97
  private prewarm;
@@ -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.1.4";
5
+ export declare const USER_AGENT = "cortexkit-opencode-openai-auth/0.2.0";
6
6
  export interface PkceCodes {
7
7
  verifier: string;
8
8
  challenge: string;
@@ -46,11 +46,12 @@ export declare function startOAuthServer(): Promise<{
46
46
  }>;
47
47
  export declare function stopOAuthServer(): void;
48
48
  export declare function resetOAuthStateForTest(): void;
49
- export declare function waitForOAuthCallback(pkce: PkceCodes, state: string, timeoutMs?: number): Promise<TokenResponse>;
49
+ export declare function waitForOAuthCallback(pkce: PkceCodes, state: string, timeoutMs?: number, signal?: AbortSignal): Promise<TokenResponse>;
50
50
  export interface DeviceAuthInit {
51
51
  device_auth_id: string;
52
52
  user_code: string;
53
53
  interval: string;
54
+ expires_in?: number | string;
54
55
  }
55
56
  export declare function beginDeviceAuth(): Promise<{
56
57
  deviceData: DeviceAuthInit;
@@ -73,6 +74,13 @@ export interface IngestAccount {
73
74
  enabled: boolean;
74
75
  addedAt: number;
75
76
  lastUsed: number;
77
+ /**
78
+ * When the token was obtained. Stamped at login so a freshly added account
79
+ * carries a refresh marker — without it, the runtime-state merge cannot tell a
80
+ * rotated token from a stale one (both default to 0) and a concurrent stale
81
+ * save could roll the token back.
82
+ */
83
+ lastRefreshedAt?: number;
76
84
  /** Stable ChatGPT account identifier from the OAuth token claims. */
77
85
  accountId?: string;
78
86
  }
@@ -34,6 +34,7 @@ export type QuotaManagerOptions = {
34
34
  export declare class QuotaManager {
35
35
  private main;
36
36
  private mainTokenFp;
37
+ private mainQuotaAccountId;
37
38
  private fallbacks;
38
39
  private fallbackTokenFps;
39
40
  private inflightMain;
@@ -66,7 +67,26 @@ export declare class QuotaManager {
66
67
  */
67
68
  getFallback(accountId: string, accessToken?: string): QuotaEntry | null;
68
69
  getAllFallbacks(): Map<string, QuotaEntry>;
69
- setMain(accessToken: string, entry: QuotaEntry): void;
70
+ setMain(accessToken: string, entry: QuotaEntry, accountId?: string): void;
71
+ /**
72
+ * Non-invalidating read of the cached main quota for POLICY decisions
73
+ * (killswitch). Unlike getMain(token), a token mismatch does NOT drop the
74
+ * cache — an access-token refresh is a same-account event and must not turn a
75
+ * known-exhausted account into "unknown" (which would fail open and spend).
76
+ *
77
+ * Pass the live ChatGPT accountId to still drop on a genuine account SWITCH:
78
+ * if the cached entry's account identity is known and differs, return null so
79
+ * the killswitch treats it as unknown rather than judging account A by account
80
+ * B's quota. When identity is unknown on either side, the cached snapshot is
81
+ * returned (best-effort) — the same fail-open-on-unknown stance as elsewhere.
82
+ */
83
+ peekMainForPolicy(accountId?: string): QuotaEntry | null;
84
+ /**
85
+ * Non-invalidating read of a cached fallback quota for POLICY decisions
86
+ * (killswitch). Keyed by the stable internal account id, so a token refresh
87
+ * for the same account does not drop it (getFallback(id, token) would).
88
+ */
89
+ peekFallbackForPolicy(accountId: string): QuotaEntry | null;
70
90
  setFallback(accountId: string, entry: QuotaEntry, accessToken?: string): void;
71
91
  refreshMain(accessToken: string): Promise<OAuthQuotaSnapshot>;
72
92
  refreshFallback(accountId: string, accessToken: string): Promise<OAuthQuotaSnapshot>;
@@ -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 ba,u as ca,v as da,x as ea};
2
+ export{t as fa,u as ga,v as ha,x as ia};
@@ -0,0 +1,2 @@
1
+ function A(b){if(b==null||b==="")return;let g=typeof b==="number"?b:Number(b);if(Number.isFinite(g)){let q=g<100000000000?g*1000:g,B=new Date(q);return Number.isNaN(B.getTime())?void 0:B.toISOString()}let z=new Date(b);return Number.isNaN(z.getTime())?void 0:z.toISOString()}function C(b,g){let z=b.get(g);if(z===null)return;let q=Number(z);if(!Number.isFinite(q)||q<0||q>100)return;return{usedPercent:q,remainingPercent:100-q,resetsAt:A(b.get(`${g.slice(0,-13)}-reset-at`)??void 0),checkedAt:Date.now()}}function G(b){let g={},z=C(b,"x-codex-primary-used-percent");if(z)g.primary=z;let q=C(b,"x-codex-secondary-used-percent");if(q)g.secondary=q;return g}function D(b){if(!b)return;if(!Number.isFinite(b.used_percent)||b.used_percent<0||b.used_percent>100)return;return{usedPercent:b.used_percent,remainingPercent:100-b.used_percent,resetsAt:A(b.reset_at),checkedAt:Date.now()}}function J(b){let g={},z=D(b.rate_limits?.primary);if(z)g.primary=z;let q=D(b.rate_limits?.secondary);if(q)g.secondary=q;return g}function E(b){if(!b)return;if(!Number.isFinite(b.used_percent)||b.used_percent<0||b.used_percent>100)return;return{usedPercent:b.used_percent,remainingPercent:100-b.used_percent,resetsAt:A(b.reset_at),checkedAt:Date.now()}}function K(b){let g={},z=E(b.rate_limit?.primary_window);if(z)g.primary=z;let q=E(b.rate_limit?.secondary_window);if(q)g.secondary=q;return g}
2
+ export{A as c,G as d,J as e,K as f};
@@ -0,0 +1,2 @@
1
+ import{aa as v}from"./index-garxs63s.js";import{randomUUID as O}from"node:crypto";import{mkdir as N,readFile as C,rename as g,rm as h,writeFile as k}from"node:fs/promises";import{tmpdir as L}from"node:os";import{dirname as D,join as R}from"node:path";var F=v("sidebar"),M="OPENCODE_OPENAI_AUTH_SIDEBAR_STATE_FILE",I=R(L(),"opencode-openai-auth"),f=R(I,"sidebar-state.json");function W(){return process.env[M]||f}var B={main:{quota:null,killed:!1},fallbacks:[],activeId:void 0,route:"main",lastUpdated:0};function b(K){if(K===null||typeof K!=="object"||Array.isArray(K))return B;let x=K,J=x.main,Q;if(J!==null&&typeof J==="object"&&!Array.isArray(J)){let H=J;Q={quota:"quota"in H?H.quota:null,killed:typeof H.killed==="boolean"?H.killed:!1,...typeof H.quotaBackedOff==="boolean"?{quotaBackedOff:H.quotaBackedOff}:{},...typeof H.quotaBackoffUntil==="number"?{quotaBackoffUntil:H.quotaBackoffUntil}:{},...typeof H.refreshBackedOff==="boolean"?{refreshBackedOff:H.refreshBackedOff}:{},...typeof H.refreshBackoffUntil==="number"?{refreshBackoffUntil:H.refreshBackoffUntil}:{}}}else Q={quota:null,killed:!1};let Y=x.fallbacks,X=Array.isArray(Y)?Y.filter((H)=>H!==null&&typeof H==="object"&&!Array.isArray(H)&&typeof H.id==="string").map((H)=>({id:H.id,label:typeof H.label==="string"?H.label:void 0,quota:"quota"in H?H.quota:null,killed:typeof H.killed==="boolean"?H.killed:!1,enabled:typeof H.enabled==="boolean"?H.enabled:!0})):[],Z=typeof x.activeId==="string"?x.activeId:void 0,V=typeof x.route==="string"?x.route:B.route,$=typeof x.lastUpdated==="number"?x.lastUpdated:0,j=typeof x.planType==="string"?x.planType:void 0,z=typeof x.credits==="number"?x.credits:void 0;return{main:Q,fallbacks:X,activeId:Z,route:V,lastUpdated:$,...j!==void 0?{planType:j}:{},...z!==void 0?{credits:z}:{}}}async function A(){try{let K=await C(W(),"utf8");return b(JSON.parse(K))}catch{return B}}var G=Promise.resolve();function m(K,x=W()){return G=G.then(()=>U(K,x)).catch(()=>{}),G}async function U(K,x){let J=`${x}.${O()}.tmp`;try{await N(D(x),{recursive:!0}),await k(J,JSON.stringify(K),"utf8"),await g(J,x)}catch(Q){await h(J,{force:!0}).catch(()=>{}),F.warn("sidebar write failed",{pid:process.pid,error:Q instanceof Error?Q.message:String(Q)})}}function w(){return G}function c(K){let x=K.activeId;if(x&&x!=="main"){let J=K.fallbacks.find((Q)=>Q.enabled&&Q.id===x);if(J)return{id:J.id,name:J.label??J.id,quota:J.quota,killed:J.killed}}return{id:"main",name:"main",quota:K.main.quota,killed:K.main.killed}}function l(K){let x=K?.primary?.usedPercent??null,J=K?.secondary?.usedPercent??null;if(x==null&&J==null)return{primaryUsedPercent:x,secondaryUsedPercent:J,text:null};return{primaryUsedPercent:x,secondaryUsedPercent:J,text:`5h: ${x==null?"—":`${Math.round(x)}%`} 7d: ${J==null?"—":`${Math.round(J)}%`}`}}var o=18000000,d=604800000,_=300000,y=0.01,S=1;function s(K,x,J){if(!K.resetsAt)return null;let Q=new Date(K.resetsAt).getTime();if(!Number.isFinite(Q))return null;let Y=Q-x,X=J-Y;if(X<_)return null;if(X<x*y)return null;if(X>=x)return null;let Z=K.usedPercent,V=Math.min(Math.max(X/x*100,0),100),$=Z-V,j=Math.abs($)<S?"on-pace":$>0?"deficit":"reserve",z=null;if(Z>0){let H=X*100/Z,q=Y+H;if(q<Q)z=new Date(q).toISOString()}return{pacePercent:V,deltaPercent:$,state:j,runsOutAt:z}}
2
+ export{W as Q,B as R,b as S,A as T,m as U,w as V,c as W,l as X,o as Y,d as Z,s as _};
@@ -1,2 +1,2 @@
1
- import{ca as Y,ea as K}from"./index-hrg6bdgb.js";var V=Y((rz,O)=>{var{defineProperty:J,getOwnPropertyDescriptor:r,getOwnPropertyNames:t}=Object,e=Object.prototype.hasOwnProperty,o=(z,B)=>{for(var F in B)J(z,F,{get:B[F],enumerable:!0})},zz=(z,B,F,H)=>{if(B&&typeof B==="object"||typeof B==="function"){for(let G of t(B))if(!e.call(z,G)&&G!==F)J(z,G,{get:()=>B[G],enumerable:!(H=r(B,G))||H.enumerable})}return z},Bz=(z)=>zz(J({},"__esModule",{value:!0}),z),M={};o(M,{VercelOidcTokenError:()=>j});O.exports=Bz(M);class j extends Error{constructor(z,B){super(z);this.name="VercelOidcTokenError",this.cause=B}toString(){if(this.cause)return`${this.name}: ${this.message}: ${this.cause}`;return`${this.name}: ${this.message}`}}});var C=Y((tz,x)=>{var{create:Fz,defineProperty:v,getOwnPropertyDescriptor:Gz,getOwnPropertyNames:Hz,getPrototypeOf:Kz}=Object,Qz=Object.prototype.hasOwnProperty,Wz=(z,B)=>{for(var F in B)v(z,F,{get:B[F],enumerable:!0})},S=(z,B,F,H)=>{if(B&&typeof B==="object"||typeof B==="function"){for(let G of Hz(B))if(!Qz.call(z,G)&&G!==F)v(z,G,{get:()=>B[G],enumerable:!(H=Gz(B,G))||H.enumerable})}return z},N=(z,B,F)=>(F=z!=null?Fz(Kz(z)):{},S(B||!z||!z.__esModule?v(F,"default",{value:z,enumerable:!0}):F,z)),Xz=(z)=>S(v({},"__esModule",{value:!0}),z),E={};Wz(E,{findRootDir:()=>$z,getUserDataDir:()=>qz});x.exports=Xz(E);var Z=N(K("path")),Yz=N(K("fs")),A=N(K("os")),Zz=V();function $z(){try{let z=process.cwd();while(z!==Z.default.dirname(z)){let B=Z.default.join(z,".vercel");if(Yz.default.existsSync(B))return z;z=Z.default.dirname(z)}}catch(z){throw new Zz.VercelOidcTokenError("Token refresh only supported in node server environments")}return null}function qz(){if(process.env.XDG_DATA_HOME)return process.env.XDG_DATA_HOME;switch(A.default.platform()){case"darwin":return Z.default.join(A.default.homedir(),"Library/Application Support");case"linux":return Z.default.join(A.default.homedir(),".local/share");case"win32":if(process.env.LOCALAPPDATA)return process.env.LOCALAPPDATA;return null;default:return null}}});var c=Y((ez,g)=>{var{create:vz,defineProperty:b,getOwnPropertyDescriptor:bz,getOwnPropertyNames:Uz,getPrototypeOf:Lz}=Object,Jz=Object.prototype.hasOwnProperty,Vz=(z,B)=>{for(var F in B)b(z,F,{get:B[F],enumerable:!0})},y=(z,B,F,H)=>{if(B&&typeof B==="object"||typeof B==="function"){for(let G of Uz(B))if(!Jz.call(z,G)&&G!==F)b(z,G,{get:()=>B[G],enumerable:!(H=bz(B,G))||H.enumerable})}return z},u=(z,B,F)=>(F=z!=null?vz(Lz(z)):{},y(B||!z||!z.__esModule?b(F,"default",{value:z,enumerable:!0}):F,z)),Az=(z)=>y(b({},"__esModule",{value:!0}),z),P={};Vz(P,{isValidAccessToken:()=>wz,readAuthConfig:()=>Rz,writeAuthConfig:()=>Iz});g.exports=Az(P);var $=u(K("fs")),l=u(K("path")),Nz=k();function h(){let z=(0,Nz.getVercelDataDir)();if(!z)throw Error(`Unable to find Vercel CLI data directory. Your platform: ${process.platform}. Supported: darwin, linux, win32.`);return l.join(z,"auth.json")}function Rz(){try{let z=h();if(!$.existsSync(z))return null;let B=$.readFileSync(z,"utf8");if(!B)return null;return JSON.parse(B)}catch(z){return null}}function Iz(z){let B=h(),F=l.dirname(B);if(!$.existsSync(F))$.mkdirSync(F,{mode:504,recursive:!0});$.writeFileSync(B,JSON.stringify(z,null,2),{mode:384})}function wz(z){if(!z.token)return!1;if(typeof z.expiresAt!=="number")return!0;let B=Math.floor(Date.now()/1000);return z.expiresAt>=B}});var p=Y((oz,d)=>{var{defineProperty:w,getOwnPropertyDescriptor:Dz,getOwnPropertyNames:Tz}=Object,Mz=Object.prototype.hasOwnProperty,jz=(z,B)=>{for(var F in B)w(z,F,{get:B[F],enumerable:!0})},Oz=(z,B,F,H)=>{if(B&&typeof B==="object"||typeof B==="function"){for(let G of Tz(B))if(!Mz.call(z,G)&&G!==F)w(z,G,{get:()=>B[G],enumerable:!(H=Dz(B,G))||H.enumerable})}return z},Sz=(z)=>Oz(w({},"__esModule",{value:!0}),z),i={};jz(i,{processTokenResponse:()=>uz,refreshTokenRequest:()=>yz});d.exports=Sz(i);var R=K("os"),Ez="https://vercel.com",xz="cl_HYyOPBNtFMfHhaUn9L4QPfTZz6TP47bp",f=`@vercel/oidc node-${process.version} ${(0,R.platform)()} (${(0,R.arch)()}) ${(0,R.hostname)()}`,I=null;async function Cz(){if(I)return I;let z=`${Ez}/.well-known/openid-configuration`,B=await fetch(z,{headers:{"user-agent":f}});if(!B.ok)throw Error("Failed to discover OAuth endpoints");let F=await B.json();if(!F||typeof F.token_endpoint!=="string")throw Error("Invalid OAuth discovery response");let H=F.token_endpoint;return I=H,H}async function yz(z){let B=await Cz();return await fetch(B,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded","user-agent":f},body:new URLSearchParams({client_id:xz,grant_type:"refresh_token",...z})})}async function uz(z){let B=await z.json();if(!z.ok){let F=typeof B==="object"&&B&&"error"in B?String(B.error):"Token refresh failed";return[Error(F)]}if(typeof B!=="object"||B===null)return[Error("Invalid token response")];if(typeof B.access_token!=="string")return[Error("Missing access_token in response")];if(B.token_type!=="Bearer")return[Error("Invalid token_type in response")];if(typeof B.expires_in!=="number")return[Error("Missing expires_in in response")];return[null,B]}});var k=Y((zB,n)=>{var{create:Pz,defineProperty:U,getOwnPropertyDescriptor:lz,getOwnPropertyNames:hz,getPrototypeOf:gz}=Object,cz=Object.prototype.hasOwnProperty,kz=(z,B)=>{for(var F in B)U(z,F,{get:B[F],enumerable:!0})},a=(z,B,F,H)=>{if(B&&typeof B==="object"||typeof B==="function"){for(let G of hz(B))if(!cz.call(z,G)&&G!==F)U(z,G,{get:()=>B[G],enumerable:!(H=lz(B,G))||H.enumerable})}return z},_=(z,B,F)=>(F=z!=null?Pz(gz(z)):{},a(B||!z||!z.__esModule?U(F,"default",{value:z,enumerable:!0}):F,z)),iz=(z)=>a(U({},"__esModule",{value:!0}),z),m={};kz(m,{assertVercelOidcTokenResponse:()=>D,findProjectInfo:()=>sz,getTokenPayload:()=>mz,getVercelCliToken:()=>dz,getVercelDataDir:()=>fz,getVercelOidcToken:()=>pz,isExpired:()=>nz,loadToken:()=>_z,saveToken:()=>az});n.exports=iz(m);var q=_(K("path")),Q=_(K("fs")),X=V(),L=C(),W=c(),s=p();function fz(){let B=(0,L.getUserDataDir)();if(!B)return null;return q.join(B,"com.vercel.cli")}async function dz(){let z=(0,W.readAuthConfig)();if(!z)return null;if((0,W.isValidAccessToken)(z))return z.token||null;if(!z.refreshToken)return(0,W.writeAuthConfig)({}),null;try{let B=await(0,s.refreshTokenRequest)({refresh_token:z.refreshToken}),[F,H]=await(0,s.processTokenResponse)(B);if(F||!H)return(0,W.writeAuthConfig)({}),null;let G={token:H.access_token,expiresAt:Math.floor(Date.now()/1000)+H.expires_in};if(H.refresh_token)G.refreshToken=H.refresh_token;return(0,W.writeAuthConfig)(G),G.token??null}catch(B){return(0,W.writeAuthConfig)({}),null}}async function pz(z,B,F){let H=`https://api.vercel.com/v1/projects/${B}/token?source=vercel-oidc-refresh${F?`&teamId=${F}`:""}`,G=await fetch(H,{method:"POST",headers:{Authorization:`Bearer ${z}`}});if(!G.ok)throw new X.VercelOidcTokenError(`Failed to refresh OIDC token: ${G.statusText}`);let T=await G.json();return D(T),T}function D(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 sz(){let z=(0,L.findRootDir)();if(!z)throw new X.VercelOidcTokenError("Unable to find project root directory. Have you linked your project with `vc link?`");let B=q.join(z,".vercel","project.json");if(!Q.existsSync(B))throw new X.VercelOidcTokenError("project.json not found, have you linked your project with `vc link?`");let F=JSON.parse(Q.readFileSync(B,"utf8"));if(typeof F.projectId!=="string"&&typeof F.orgId!=="string")throw TypeError("Expected a string-valued projectId property. Try running `vc link` to re-link your project.");return{projectId:F.projectId,teamId:F.orgId}}function az(z,B){let F=(0,L.getUserDataDir)();if(!F)throw new X.VercelOidcTokenError("Unable to find user data directory. Please reach out to Vercel support.");let H=q.join(F,"com.vercel.token",`${B}.json`),G=JSON.stringify(z);Q.mkdirSync(q.dirname(H),{mode:504,recursive:!0}),Q.writeFileSync(H,G),Q.chmodSync(H,432);return}function _z(z){let B=(0,L.getUserDataDir)();if(!B)throw new X.VercelOidcTokenError("Unable to find user data directory. Please reach out to Vercel support.");let F=q.join(B,"com.vercel.token",`${z}.json`);if(!Q.existsSync(F))return null;let H=JSON.parse(Q.readFileSync(F,"utf8"));return D(H),H}function mz(z){let B=z.split(".");if(B.length!==3)throw new X.VercelOidcTokenError("Invalid token. Please run `vc env pull` and try again");let F=B[1].replace(/-/g,"+").replace(/_/g,"/"),H=F.padEnd(F.length+(4-F.length%4)%4,"=");return JSON.parse(Buffer.from(H,"base64").toString("utf8"))}function nz(z){return z.exp*1000<Date.now()}});
1
+ import{ga as Y,ia as K}from"./index-2b5wejq3.js";var V=Y((rz,O)=>{var{defineProperty:J,getOwnPropertyDescriptor:r,getOwnPropertyNames:t}=Object,e=Object.prototype.hasOwnProperty,o=(z,B)=>{for(var F in B)J(z,F,{get:B[F],enumerable:!0})},zz=(z,B,F,H)=>{if(B&&typeof B==="object"||typeof B==="function"){for(let G of t(B))if(!e.call(z,G)&&G!==F)J(z,G,{get:()=>B[G],enumerable:!(H=r(B,G))||H.enumerable})}return z},Bz=(z)=>zz(J({},"__esModule",{value:!0}),z),M={};o(M,{VercelOidcTokenError:()=>j});O.exports=Bz(M);class j extends Error{constructor(z,B){super(z);this.name="VercelOidcTokenError",this.cause=B}toString(){if(this.cause)return`${this.name}: ${this.message}: ${this.cause}`;return`${this.name}: ${this.message}`}}});var C=Y((tz,x)=>{var{create:Fz,defineProperty:v,getOwnPropertyDescriptor:Gz,getOwnPropertyNames:Hz,getPrototypeOf:Kz}=Object,Qz=Object.prototype.hasOwnProperty,Wz=(z,B)=>{for(var F in B)v(z,F,{get:B[F],enumerable:!0})},S=(z,B,F,H)=>{if(B&&typeof B==="object"||typeof B==="function"){for(let G of Hz(B))if(!Qz.call(z,G)&&G!==F)v(z,G,{get:()=>B[G],enumerable:!(H=Gz(B,G))||H.enumerable})}return z},N=(z,B,F)=>(F=z!=null?Fz(Kz(z)):{},S(B||!z||!z.__esModule?v(F,"default",{value:z,enumerable:!0}):F,z)),Xz=(z)=>S(v({},"__esModule",{value:!0}),z),E={};Wz(E,{findRootDir:()=>$z,getUserDataDir:()=>qz});x.exports=Xz(E);var Z=N(K("path")),Yz=N(K("fs")),A=N(K("os")),Zz=V();function $z(){try{let z=process.cwd();while(z!==Z.default.dirname(z)){let B=Z.default.join(z,".vercel");if(Yz.default.existsSync(B))return z;z=Z.default.dirname(z)}}catch(z){throw new Zz.VercelOidcTokenError("Token refresh only supported in node server environments")}return null}function qz(){if(process.env.XDG_DATA_HOME)return process.env.XDG_DATA_HOME;switch(A.default.platform()){case"darwin":return Z.default.join(A.default.homedir(),"Library/Application Support");case"linux":return Z.default.join(A.default.homedir(),".local/share");case"win32":if(process.env.LOCALAPPDATA)return process.env.LOCALAPPDATA;return null;default:return null}}});var c=Y((ez,g)=>{var{create:vz,defineProperty:b,getOwnPropertyDescriptor:bz,getOwnPropertyNames:Uz,getPrototypeOf:Lz}=Object,Jz=Object.prototype.hasOwnProperty,Vz=(z,B)=>{for(var F in B)b(z,F,{get:B[F],enumerable:!0})},y=(z,B,F,H)=>{if(B&&typeof B==="object"||typeof B==="function"){for(let G of Uz(B))if(!Jz.call(z,G)&&G!==F)b(z,G,{get:()=>B[G],enumerable:!(H=bz(B,G))||H.enumerable})}return z},u=(z,B,F)=>(F=z!=null?vz(Lz(z)):{},y(B||!z||!z.__esModule?b(F,"default",{value:z,enumerable:!0}):F,z)),Az=(z)=>y(b({},"__esModule",{value:!0}),z),P={};Vz(P,{isValidAccessToken:()=>wz,readAuthConfig:()=>Rz,writeAuthConfig:()=>Iz});g.exports=Az(P);var $=u(K("fs")),l=u(K("path")),Nz=k();function h(){let z=(0,Nz.getVercelDataDir)();if(!z)throw Error(`Unable to find Vercel CLI data directory. Your platform: ${process.platform}. Supported: darwin, linux, win32.`);return l.join(z,"auth.json")}function Rz(){try{let z=h();if(!$.existsSync(z))return null;let B=$.readFileSync(z,"utf8");if(!B)return null;return JSON.parse(B)}catch(z){return null}}function Iz(z){let B=h(),F=l.dirname(B);if(!$.existsSync(F))$.mkdirSync(F,{mode:504,recursive:!0});$.writeFileSync(B,JSON.stringify(z,null,2),{mode:384})}function wz(z){if(!z.token)return!1;if(typeof z.expiresAt!=="number")return!0;let B=Math.floor(Date.now()/1000);return z.expiresAt>=B}});var p=Y((oz,d)=>{var{defineProperty:w,getOwnPropertyDescriptor:Dz,getOwnPropertyNames:Tz}=Object,Mz=Object.prototype.hasOwnProperty,jz=(z,B)=>{for(var F in B)w(z,F,{get:B[F],enumerable:!0})},Oz=(z,B,F,H)=>{if(B&&typeof B==="object"||typeof B==="function"){for(let G of Tz(B))if(!Mz.call(z,G)&&G!==F)w(z,G,{get:()=>B[G],enumerable:!(H=Dz(B,G))||H.enumerable})}return z},Sz=(z)=>Oz(w({},"__esModule",{value:!0}),z),i={};jz(i,{processTokenResponse:()=>uz,refreshTokenRequest:()=>yz});d.exports=Sz(i);var R=K("os"),Ez="https://vercel.com",xz="cl_HYyOPBNtFMfHhaUn9L4QPfTZz6TP47bp",f=`@vercel/oidc node-${process.version} ${(0,R.platform)()} (${(0,R.arch)()}) ${(0,R.hostname)()}`,I=null;async function Cz(){if(I)return I;let z=`${Ez}/.well-known/openid-configuration`,B=await fetch(z,{headers:{"user-agent":f}});if(!B.ok)throw Error("Failed to discover OAuth endpoints");let F=await B.json();if(!F||typeof F.token_endpoint!=="string")throw Error("Invalid OAuth discovery response");let H=F.token_endpoint;return I=H,H}async function yz(z){let B=await Cz();return await fetch(B,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded","user-agent":f},body:new URLSearchParams({client_id:xz,grant_type:"refresh_token",...z})})}async function uz(z){let B=await z.json();if(!z.ok){let F=typeof B==="object"&&B&&"error"in B?String(B.error):"Token refresh failed";return[Error(F)]}if(typeof B!=="object"||B===null)return[Error("Invalid token response")];if(typeof B.access_token!=="string")return[Error("Missing access_token in response")];if(B.token_type!=="Bearer")return[Error("Invalid token_type in response")];if(typeof B.expires_in!=="number")return[Error("Missing expires_in in response")];return[null,B]}});var k=Y((zB,n)=>{var{create:Pz,defineProperty:U,getOwnPropertyDescriptor:lz,getOwnPropertyNames:hz,getPrototypeOf:gz}=Object,cz=Object.prototype.hasOwnProperty,kz=(z,B)=>{for(var F in B)U(z,F,{get:B[F],enumerable:!0})},a=(z,B,F,H)=>{if(B&&typeof B==="object"||typeof B==="function"){for(let G of hz(B))if(!cz.call(z,G)&&G!==F)U(z,G,{get:()=>B[G],enumerable:!(H=lz(B,G))||H.enumerable})}return z},_=(z,B,F)=>(F=z!=null?Pz(gz(z)):{},a(B||!z||!z.__esModule?U(F,"default",{value:z,enumerable:!0}):F,z)),iz=(z)=>a(U({},"__esModule",{value:!0}),z),m={};kz(m,{assertVercelOidcTokenResponse:()=>D,findProjectInfo:()=>sz,getTokenPayload:()=>mz,getVercelCliToken:()=>dz,getVercelDataDir:()=>fz,getVercelOidcToken:()=>pz,isExpired:()=>nz,loadToken:()=>_z,saveToken:()=>az});n.exports=iz(m);var q=_(K("path")),Q=_(K("fs")),X=V(),L=C(),W=c(),s=p();function fz(){let B=(0,L.getUserDataDir)();if(!B)return null;return q.join(B,"com.vercel.cli")}async function dz(){let z=(0,W.readAuthConfig)();if(!z)return null;if((0,W.isValidAccessToken)(z))return z.token||null;if(!z.refreshToken)return(0,W.writeAuthConfig)({}),null;try{let B=await(0,s.refreshTokenRequest)({refresh_token:z.refreshToken}),[F,H]=await(0,s.processTokenResponse)(B);if(F||!H)return(0,W.writeAuthConfig)({}),null;let G={token:H.access_token,expiresAt:Math.floor(Date.now()/1000)+H.expires_in};if(H.refresh_token)G.refreshToken=H.refresh_token;return(0,W.writeAuthConfig)(G),G.token??null}catch(B){return(0,W.writeAuthConfig)({}),null}}async function pz(z,B,F){let H=`https://api.vercel.com/v1/projects/${B}/token?source=vercel-oidc-refresh${F?`&teamId=${F}`:""}`,G=await fetch(H,{method:"POST",headers:{Authorization:`Bearer ${z}`}});if(!G.ok)throw new X.VercelOidcTokenError(`Failed to refresh OIDC token: ${G.statusText}`);let T=await G.json();return D(T),T}function D(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 sz(){let z=(0,L.findRootDir)();if(!z)throw new X.VercelOidcTokenError("Unable to find project root directory. Have you linked your project with `vc link?`");let B=q.join(z,".vercel","project.json");if(!Q.existsSync(B))throw new X.VercelOidcTokenError("project.json not found, have you linked your project with `vc link?`");let F=JSON.parse(Q.readFileSync(B,"utf8"));if(typeof F.projectId!=="string"&&typeof F.orgId!=="string")throw TypeError("Expected a string-valued projectId property. Try running `vc link` to re-link your project.");return{projectId:F.projectId,teamId:F.orgId}}function az(z,B){let F=(0,L.getUserDataDir)();if(!F)throw new X.VercelOidcTokenError("Unable to find user data directory. Please reach out to Vercel support.");let H=q.join(F,"com.vercel.token",`${B}.json`),G=JSON.stringify(z);Q.mkdirSync(q.dirname(H),{mode:504,recursive:!0}),Q.writeFileSync(H,G),Q.chmodSync(H,432);return}function _z(z){let B=(0,L.getUserDataDir)();if(!B)throw new X.VercelOidcTokenError("Unable to find user data directory. Please reach out to Vercel support.");let F=q.join(B,"com.vercel.token",`${z}.json`);if(!Q.existsSync(F))return null;let H=JSON.parse(Q.readFileSync(F,"utf8"));return D(H),H}function mz(z){let B=z.split(".");if(B.length!==3)throw new X.VercelOidcTokenError("Invalid token. Please run `vc env pull` and try again");let F=B[1].replace(/-/g,"+").replace(/_/g,"/"),H=F.padEnd(F.length+(4-F.length%4)%4,"=");return JSON.parse(Buffer.from(H,"base64").toString("utf8"))}function nz(z){return z.exp*1000<Date.now()}});
2
2
  export{V as a,k as b};
@@ -0,0 +1,3 @@
1
+ import{appendFileSync as N,existsSync as U,renameSync as V,statSync as P}from"node:fs";import{tmpdir as X}from"node:os";import{join as Y}from"node:path";var $={error:0,warn:1,info:2,debug:3,trace:4},x=!1,C=5242880;function w(){return process.env.OPENCODE_OPENAI_AUTH_LOG_FILE??Y(X(),"opencode-openai-auth.log")}var B;function R(q){if(q===void 0||q in $)B=q}function F(){if(B)return B;let q=process.env.OPENCODE_OPENAI_AUTH_LOG_LEVEL;if(q&&q in $)return q;return"info"}var A=/^(authorization|x-api-key|cookie|set-cookie|refresh|access|token)$/i;function D(q){if(A.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 I=/\b(Bearer\s+[\w.-]+|sk-[\w-]+|eyJ[\w.-]+)\b/g;function K(q){return G(q,new WeakSet)}function G(q,H){if(typeof q==="string")return q.replace(I,"***REDACTED***");if(Array.isArray(q)){if(H.has(q))return"[Circular]";H.add(q);let J=q.map((Q)=>G(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]=D(Q)?"***REDACTED***":G(j,H);return H.delete(q),J}return q}var Z=[],z,b=3;function p(){try{let q=w();if(!(U(q)&&P(q).size>C))return;for(let H=b-1;H>=1;H--)if(U(`${q}.${H}`))V(`${q}.${H}`,`${q}.${H+1}`);V(q,`${q}.1`)}catch{}}function M(){if(!Z.length)return;let q=Z.join("");Z=[];try{p(),N(w(),q)}catch{}}function L(){if(!z)z=setTimeout(()=>{z=void 0,M()},500)}if(!x)process.on("exit",M);function _(q){try{return` ${JSON.stringify(K(q))}`}catch{return" [unserializable]"}}function W(q,H,J,Q){if($[H]>$[F()])return;let j=`[${new Date().toISOString()}] ${H.toUpperCase()} [${q}] ${J}`+(Q===void 0?"":_(Q))+`
2
+ `;if(Z.push(j),Z.length>=50)M();else L()}function S(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{R as $,S as aa};
@@ -1 +1 @@
1
- import{createHash as z}from"node:crypto";import{homedir as A,tmpdir as K}from"node:os";import{join as q,resolve as B}from"node:path";var F="OPENCODE_OPENAI_AUTH_RPC_DIR";function M(f){let k=process.env[F]?.trim();if(k)return B(f,k);let w=z("sha256").update(f).digest("hex").slice(0,16),x=process.env.XDG_STATE_HOME||q(A(),".local","state");return q(x,"cortexkit","openai-auth","rpc",w)}export{K as $,M as aa};
1
+ import{createHash as z}from"node:crypto";import{homedir as A,tmpdir as K}from"node:os";import{join as q,resolve as B}from"node:path";var F="OPENCODE_OPENAI_AUTH_RPC_DIR";function M(f){let k=process.env[F]?.trim();if(k)return B(f,k);let w=z("sha256").update(f).digest("hex").slice(0,16),x=process.env.XDG_STATE_HOME||q(A(),".local","state");return q(x,"cortexkit","openai-auth","rpc",w)}export{K as da,M as ea};
@@ -1,2 +1,2 @@
1
1
  import{mkdir as u,readdir as l,readFile as c,rename as p,unlink as m,writeFile as d}from"node:fs/promises";import{join as a}from"node:path";function f(t){try{return process.kill(t,0),!0}catch(r){return r.code==="EPERM"}}async function b(t,r){await u(t,{recursive:!0});let s={...r,startedAt:Date.now()},e=a(t,`port-${r.pid}.json`),i=`${e}.${process.pid}.tmp`;return await d(i,JSON.stringify(s),{encoding:"utf8",mode:384}),await p(i,e),e}async function h(t,r){let s;try{s=await l(t)}catch{return null}let e=[];for(let n of s){if(!n.startsWith("port-")||!n.endsWith(".json"))continue;try{let o=JSON.parse(await c(a(t,n),"utf8"));if(Number.isFinite(o.port))if(f(o.pid))e.push(o);else m(a(t,n)).catch(()=>{})}catch{}}if(e.length===0)return null;let i=r!==void 0&&r>=1?e.filter((n)=>n.pid===r):[];return(i.length>0?i:e).sort((n,o)=>o.startedAt-n.startedAt)[0]??null}
2
- export{b as Z,h as _};
2
+ export{b as ba,h as ca};
@@ -0,0 +1,92 @@
1
+ import{aa as m0}from"./index-garxs63s.js";import{ia as J2}from"./index-2b5wejq3.js";import{createHash as g0}from"node:crypto";var u0=86400000,i0=300000,s0=3600000,c0=60000,n0=900000,r0=300000;function o(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.message.includes("fetch failed")||"code"in B&&(B.code==="ECONNRESET"||B.code==="ECONNREFUSED"||B.code==="ETIMEDOUT"||B.code==="UND_ERR_CONNECT_TIMEOUT")}function t(B){let Z=o(B),$=B?.status;if(typeof $==="number")return $===429||$>=500;if(!(B instanceof Error))return!1;let z=B.code;return Z.includes("fetch failed")||z==="ECONNRESET"||z==="ECONNREFUSED"||z==="ETIMEDOUT"||z==="UND_ERR_CONNECT_TIMEOUT"}function M0(B){return g0("sha256").update(B).digest("hex")}function O0(B){let Z=M0(B.refreshToken),z=(B.previous?.tokenHash===Z?B.previous.retryCount??0:0)+1,K,G=B.error?.retryAfter;if(typeof G==="number"&&G>0)K=G*1000;else if(a0(B.error))K=Math.min(s0,i0*2**Math.min(z-1,6));else K=u0;return{message:o(B.error),checkedAt:B.now,nextRetryAt:B.now+K,retryCount:z,tokenHash:Z}}function P(B,Z,$){if(!B?.nextRetryAt||B.nextRetryAt<=$)return!1;if(!Z)return!0;return B.tokenHash===M0(Z)}function u(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 U0(B){let $=(B.previous?.retryCount??0)+1,z,K=B.error?.retryAfter;if(typeof K==="number"&&K>0)z=K*1000;else if(t(B.error))z=Math.min(n0,c0*2**Math.min($-1,6));else z=r0;return{message:o(B.error),checkedAt:B.now,nextRetryAt:B.now+z,retryCount:$}}function _0(B,Z){if(!B?.nextRetryAt||B.nextRetryAt<=Z)return!1;return!0}function e(B){if(!B)return;let Z=Number(B);if(Number.isFinite(Z)&&Z>0)return Math.ceil(Z);let $=Date.parse(B);if(Number.isFinite($)){let z=Math.ceil(($-Date.now())/1000);return z>0?z:void 0}return}import{createServer as o0}from"node:http";import{setTimeout as t0}from"node:timers/promises";var P0="0.2.0";var i="app_EMoamEEZ73f0CkXaXp7hrann",R="https://auth.openai.com",k=1455,e0=3000,R0=`cortexkit-opencode-openai-auth/${P0}`;function y0(B){let Z=new Uint8Array(B),$=String.fromCharCode(...Z);return btoa($).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function B2(){let Z=Array.from(crypto.getRandomValues(new Uint8Array(43))).map((z)=>"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~"[z%66]).join(""),$=y0(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(Z)));return{verifier:Z,challenge:$}}function C0(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 I0(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 z=B.organizations;if(Array.isArray(z)){let K=z[0];if(K&&typeof K==="object"&&!Array.isArray(K)&&typeof K.id==="string"&&K.id.length>0)return K.id}return}function S(B){if(B.id_token){let Z=C0(B.id_token),$=Z&&I0(Z);if($)return $}if(B.access_token){let Z=C0(B.access_token);return Z?I0(Z):void 0}return}function Z2(B,Z,$){let z=new URLSearchParams({response_type:"code",client_id:i,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`${R}/oauth/authorize?${z.toString()}`}async function $2(B,Z,$){let z=await fetch(`${R}/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:i,code_verifier:$.verifier}).toString()});if(!z.ok)throw Error(`Token exchange failed: ${z.status}`);return await z.json()}function z2(B){return B.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&#39;")}var X2=`<!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>`,B0=(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">${z2(B)}</div>
85
+ </div>
86
+ </body>
87
+ </html>`,f,w,D=new Map;function C(){return D.size}function q(B){if(D.delete(B),C()===0)I()}async function G2(){let B=`http://127.0.0.1:${k}/auth/callback`;if(f)return{port:k,redirectUri:B};if(w)return w;w=(async()=>{let Z=o0(($,z)=>{let K=new URL($.url||"/",`http://127.0.0.1:${k}`);if(K.pathname==="/auth/callback"){let G=K.searchParams.get("code"),X=K.searchParams.get("state"),W=K.searchParams.get("error"),Y=K.searchParams.get("error_description");if(W){let Q=Y||W;if(X){let V=D.get(X);if(V)V.reject(Error(Q)),q(X);else if(C()===0)I()}else if(C()===0)I();z.writeHead(200,{"Content-Type":"text/html"}),z.end(B0(Q));return}if(!G||!X){let Q=!G?"Missing authorization code":"Missing state parameter";if(X){let V=D.get(X);if(V)V.reject(Error(Q)),q(X);else if(C()===0)I()}else if(C()===0)I();z.writeHead(400,{"Content-Type":"text/html"}),z.end(B0(Q));return}let J=D.get(X);if(!J){if(C()===0)I();z.writeHead(400,{"Content-Type":"text/html"}),z.end(B0("Unknown state — authorization may have expired"));return}q(X),$2(G,B,J.pkce).then((Q)=>J.resolve(Q)).catch((Q)=>J.reject(Q)),z.writeHead(200,{"Content-Type":"text/html"}),z.end(X2);return}if(K.pathname==="/cancel"){let G=K.searchParams.get("state"),X=G?[G]:[...D.keys()];z.writeHead(200),z.end("Login cancelled");for(let W of X){let Y=D.get(W);if(!Y)continue;Y.reject(Error("Login cancelled")),q(W)}if(C()===0)I();return}z.writeHead(404),z.end("Not found")});return await new Promise(($,z)=>{Z.once("error",z),Z.listen(k,"127.0.0.1",()=>{Z.off("error",z),$()})}),f=Z,{port:k,redirectUri:B}})();try{return await w}finally{w=void 0}}function I(){if(f){let B=f;f=void 0,B.close(()=>{}),B.closeIdleConnections?.(),setTimeout(()=>{B.closeAllConnections?.()},25).unref?.()}}function K2(B,Z,$=300000,z){return new Promise((K,G)=>{if(z?.aborted){q(Z),G(Error("Login cancelled"));return}let X=setTimeout(()=>{if(D.get(Z))q(Z),G(Error("OAuth callback timeout — authorization took too long"))},$),W=()=>{if(clearTimeout(X),D.get(Z))q(Z),G(Error("Login cancelled"))};if(z)z.addEventListener("abort",W);D.set(Z,{pkce:B,state:Z,resolve:(Y)=>{if(clearTimeout(X),z)z.removeEventListener("abort",W);K(Y)},reject:(Y)=>{if(clearTimeout(X),z)z.removeEventListener("abort",W);G(Y)}})})}async function W2(){let B=await fetch(`${R}/api/accounts/deviceauth/usercode`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":R0},body:JSON.stringify({client_id:i})});if(!B.ok)throw Error("Failed to initiate device authorization");let Z=await B.json();return{deviceData:Z,url:`${R}/codex/device`,instructions:`Enter code: ${Z.user_code}`}}async function Y2(B,Z){let $=Math.max(parseInt(B.interval,10)||5,1)*1000,z=typeof B.expires_in==="number"?B.expires_in:parseInt(B.expires_in||"",10),K=!Number.isNaN(z)&&z>0?z*1000:900000,G=Date.now();while(!0){if(Z?.aborted)throw Error("Device authorization cancelled");if(Date.now()-G>K)throw Error("Device authorization expired");let X=await fetch(`${R}/api/accounts/deviceauth/token`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":R0},body:JSON.stringify({device_auth_id:B.device_auth_id,user_code:B.user_code})});if(X.ok){let J=await X.json(),Q=await fetch(`${R}/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:`${R}/deviceauth/callback`,client_id:i,code_verifier:J.code_verifier}).toString()});if(!Q.ok)throw Error(`Token exchange failed: ${Q.status}`);return await Q.json()}if(X.status!==403&&X.status!==404)throw Error(`Device authorization failed: ${X.status}`);let W=K-(Date.now()-G);if(W<=0)throw Error("Device authorization expired");let Y=Math.min($+e0,W);try{await t0(Y,void 0,{signal:Z})}catch(J){if(J instanceof Error&&J.name==="AbortError")throw Error("Device authorization cancelled");throw J}}}function TB(B,Z){let $=-1;if(Z.accountId)$=B.findIndex((z)=>z.accountId&&z.accountId===Z.accountId);if($<0)$=B.findIndex((z)=>z.id===Z.id);if($<0&&Z.label&&!Z.accountId)$=B.findIndex((z)=>z.label===Z.label);if($>=0)return B[$]={...B[$],...Z,addedAt:B[$]?.addedAt??Z.addedAt},$;return B.push(Z),B.length-1}async function EB(B={}){let{label:Z,headless:$=!1,signal:z}=B;if($){let{deviceData:J,url:Q,instructions:V}=await W2(),F=(async()=>{let N=await Y2(J,z),H=Date.now();return{id:Z||S(N)||crypto.randomUUID(),label:Z||void 0,type:"oauth",access:N.access_token,refresh:N.refresh_token,expires:H+(N.expires_in??3600)*1000,enabled:!0,addedAt:H,lastUsed:H,lastRefreshedAt:H,accountId:S(N)}})();return{url:Q,instructions:V,completion:F}}let{redirectUri:K}=await G2(),G=await B2(),X=y0(crypto.getRandomValues(new Uint8Array(32)).buffer),W=Z2(K,G,X),Y=(async()=>{try{if(z?.aborted)throw Error("Login cancelled");let J=await K2(G,X,void 0,z),Q=Date.now();return{id:Z||S(J)||crypto.randomUUID(),label:Z||void 0,type:"oauth",access:J.access_token,refresh:J.refresh_token,expires:Q+(J.expires_in??3600)*1000,enabled:!0,addedAt:Q,lastUsed:Q,lastRefreshedAt:Q,accountId:S(J)}}finally{q(X)}})();return{url:W,instructions:"Complete authorization in your browser. This window will close automatically.",completion:Y}}var s="primary",c="secondary",Q2="app_EMoamEEZ73f0CkXaXp7hrann",j2="https://auth.openai.com";async function xB(B){let Z=await B.fetchImpl(`${j2}/oauth/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"refresh_token",refresh_token:B.refreshToken,client_id:Q2}).toString()});if(!Z.ok){let z=e(Z.headers.get("retry-after"));throw Object.assign(Error(`Token refresh failed: ${Z.status}`),{status:Z.status,retryAfter:z,isRefreshError:!0})}let $=await Z.json();if(!$||typeof $.access_token!=="string"||!$.access_token||typeof $.refresh_token!=="string"||!$.refresh_token||typeof $.expires_in!=="number")throw Object.assign(Error("Token refresh failed: malformed response"),{status:Z.status,isRefreshError:!0});return{access:$.access_token,refresh:$.refresh_token,expires:B.now()+$.expires_in*1000,expiresIn:$.expires_in}}var N2="https://chatgpt.com/backend-api/wham/usage";async function kB(B){let Z=await B.fetchImpl(N2,{headers:{authorization:`Bearer ${B.accessToken}`,"chatgpt-account-id":B.accountId??"","oai-client-platform":"web","oai-client-version":"0","x-openai-target-path":"/backend-api/wham/usage"}});if(!Z.ok){let z=e(Z.headers.get("retry-after"));throw Object.assign(Error(`wham usage check failed: ${Z.status}`),{status:Z.status,retryAfter:z})}let{normalizeWham:$}=await import("./quota-normalize-dnaa90ct.js");return $(await Z.json())}import{randomUUID as Z0}from"node:crypto";import{mkdir as V2,readFile as $0,rename as H2,rm as m,stat as T0,writeFile as z0}from"node:fs/promises";import{homedir as b2}from"node:os";import{dirname as vB,join as h}from"node:path";var F2=globalThis.setTimeout.bind(globalThis),L2=globalThis.clearTimeout.bind(globalThis),D2="openai-auth.json";function q2(){if(process.env.OPENCODE_CONFIG_DIR?.trim())return process.env.OPENCODE_CONFIG_DIR.trim();return h(process.env.XDG_CONFIG_HOME||h(b2(),".config"),"opencode")}function M2(){return process.env.OPENCODE_OPENAI_AUTH_FILE?.trim()||h(q2(),D2)}async function n(B){let $=`${B.path??M2()}.${B.name}.lock`,z=h($,"owner.json"),K=Z0(),G=B.now??Date.now,X=null,W=!1;async function Y(){try{return JSON.parse(await $0($,"utf8"))}catch(N){if(N.code!=="EISDIR")throw N;return JSON.parse(await $0(z,"utf8"))}}async function J(){await z0($,`${JSON.stringify({ownerId:K,expiresAt:G()+B.ttlMs})}
88
+ `,{encoding:"utf8",mode:384})}async function Q(){try{return await z0($,`${JSON.stringify({ownerId:K,expiresAt:G()+B.ttlMs})}
89
+ `,{encoding:"utf8",mode:384,flag:"wx"}),!0}catch(N){let H=N.code;if(H==="EEXIST"||H==="EISDIR")return!1;throw N}}function V(){if(!B.renew||W)return;let N=B.renewIntervalMs??Math.max(1000,Math.floor(B.ttlMs/3));if(X=F2(()=>{(async()=>{try{let H=await Y(),l=G();if(W||H?.ownerId!==K||Number(H?.expiresAt)<=l)return;await J(),V()}catch{}})()},N),"unref"in X)X.unref()}let F=await Q();if(!F){let N=`${$}.evicting`,H=h(N,"owner.json"),l=Z0(),MB=5000,OB=8;async function g(){await new Promise((L)=>setTimeout(L,Math.floor(Math.random()*4)))}async function b0(){try{let L=await Y();return Number(L?.expiresAt)>G()}catch{try{return(await T0($)).mtimeMs+B.ttlMs>G()}catch{return!1}}}async function A(){try{return JSON.parse(await $0(H,"utf8"))?.ownerId===l}catch{return!1}}async function l0(){await V2(N);try{await z0(H,`${JSON.stringify({ownerId:l,createdAt:G()})}
90
+ `,{encoding:"utf8",mode:384,flag:"wx"})}catch(L){if(L.code==="ENOENT")return!1;throw await F0(),L}return await B.onStep?.("eviction-marker-acquired"),!0}async function F0(){if(await A())await m(N,{recursive:!0,force:!0}).catch(()=>{})}for(let L=0;L<8;L++){if(F=await Q(),F)break;if(await b0())return null;try{if(!await l0()){await g();continue}}catch(L0){if(L0.code!=="EEXIST")throw L0;let D0;try{D0=await T0(N)}catch(x){if(x.code==="ENOENT"){await g();continue}throw x}if(D0.mtimeMs+5000>G())return null;await B.onStep?.("stale-marker-stat");let q0=`${N}.${Z0()}`;try{await H2(N,q0)}catch(x){if(x.code==="ENOENT"){await g();continue}throw x}await B.onStep?.("stale-marker-claimed"),await m(q0,{recursive:!0,force:!0}).catch(()=>{}),await g();continue}try{if(await b0())return null;if(!await A())return null;if(await B.onStep?.("stale-lock-confirmed"),!await A())return null;if(await m($,{recursive:!0,force:!0}).catch(()=>{}),!await A())return null;if(F=await Q(),!F)return null;if(!await A())return await m($,{recursive:!0,force:!0}).catch(()=>{}),F=!1,null;break}finally{await F0()}}}if(!F)return null;return V(),{release:async()=>{if(W=!0,X)L2(X),X=null;try{if((await Y())?.ownerId!==K)return}catch{return}await m($,{recursive:!0,force:!0}).catch(()=>{})}}}import{createHash as R2,randomUUID as y2}from"node:crypto";import{homedir as T2}from"node:os";import{dirname as E2,join as r}from"node:path";import{setTimeout as S2}from"node:timers/promises";import{randomUUID as O2}from"node:crypto";import{mkdir as U2,rename as _2,rm as P2,writeFile as C2}from"node:fs/promises";import{dirname as I2}from"node:path";async function M(B,Z){await U2(I2(B),{recursive:!0});let $=`${B}.${O2()}.tmp`;await C2($,`${JSON.stringify(Z,null,2)}
91
+ `,{encoding:"utf8",mode:384});try{await _2($,B)}catch(z){throw await P2($,{force:!0}).catch(()=>{}),z}}import{readFile as d2}from"node:fs/promises";var y=m0("refresh"),E0=1e4,A2=50,h0="openai-auth.json",x2="openai-auth-state.json";function k2(){if(process.env.OPENCODE_CONFIG_DIR?.trim())return process.env.OPENCODE_CONFIG_DIR.trim();return r(process.env.XDG_CONFIG_HOME||r(T2(),".config"),"opencode")}function E(){return process.env.OPENCODE_OPENAI_AUTH_FILE?.trim()||r(k2(),h0)}function d(B=E()){let Z=process.env.OPENCODE_OPENAI_AUTH_STATE_FILE?.trim();if(Z)return Z;return w2(B)}function w2(B){return B.endsWith(h0)?r(E2(B),x2):`${B}.state.json`}function O(B){return B.type==="oauth"}function f2(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 $Z(B){return B.costZeroing?.enabled!==!1}var m2=[401,403,429],S0={primary:0,secondary:0},h2=!1,K0={primary:5,secondary:10};function j(B){return B!=null&&typeof B==="object"&&!Array.isArray(B)}function A0(B){return{id:typeof B.id==="string"&&B.id.trim()?B.id.trim():y2(),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 x0(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),z=Number(B.retryCount);return{message:B.message,checkedAt:Z,nextRetryAt:Number.isFinite($)?$:void 0,retryCount:Number.isFinite(z)?z:void 0,tokenHash:typeof B.tokenHash==="string"?B.tokenHash:void 0}}function p2(B){if(!j(B))return;let Z={};for(let $ of["primary","secondary"]){let z=B[$];if(!j(z))continue;let K=Number(z.usedPercent),G=Number(z.remainingPercent),X=Number(z.checkedAt);if(!Number.isFinite(K)||!Number.isFinite(G)||!Number.isFinite(X))continue;Z[$]={usedPercent:K,remainingPercent:G,checkedAt:X,resetsAt:typeof z.resetsAt==="string"?z.resetsAt:void 0}}return Object.keys(Z).length?Z:void 0}function v2(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(!f2(Z))return null;let z=B.authHeader==="x-api-key"?"x-api-key":"authorization-bearer";return{...A0(B),type:"api",apiKey:$||void 0,baseURL:Z,authHeader:z}}if(B.type!=="oauth")return null;if(typeof B.refresh!=="string"||!B.refresh.trim())return null;return{...A0(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:x0(B.lastRefreshError),lastQuotaRefreshError:x0(B.lastQuotaRefreshError),quota:p2(B.quota)}}function Q0(B){if(!j(B)||!Array.isArray(B.accounts))return null;return{version:1,main:{type:"opencode",provider:"openai"},routing:j(B.routing)?B.routing:void 0,fallbackOn:Array.isArray(B.fallbackOn)?B.fallbackOn.filter((Z)=>Number.isInteger(Z)):void 0,refresh:j(B.refresh)?B.refresh:void 0,quota:j(B.quota)?B.quota:void 0,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:B.accounts.map(v2).filter((Z)=>Z!=null)}}async function U(B){try{return{exists:!0,value:JSON.parse(await d2(B,"utf8"))}}catch(Z){if(Z.code==="ENOENT")return{exists:!1,value:null};throw Z}}function _(B){return Object.fromEntries(Object.entries(B).filter(([,Z])=>Z!==void 0))}function j0(B,Z){if(!j(B))return B;let $=j(Z)?Z:{},z=j($.main)?$.main:void 0,K=j($.accounts)?$.accounts:{},G=j(B.quota)?B.quota:{},X=j(B.refresh)?B.refresh:{},W=z??G,Y=z??X,Q=Array.isArray(B.accounts)?B.accounts.map((V)=>{if(!j(V))return V;let F=typeof V.id==="string"&&j(K[V.id])?K[V.id]:{};return{...V,...F}}):void 0;return p0({...B,refresh:_({...X,mainLastRefreshError:Y.lastRefreshError,mainRefreshLeaseId:Y.refreshLeaseId,mainRefreshLeaseUntil:Y.refreshLeaseUntil,mainRefreshLeaseTokenHash:Y.refreshLeaseTokenHash}),quota:_({...G,mainQuota:W.quota,mainQuotaCheckedAt:W.quotaCheckedAt,mainQuotaToken:W.quotaToken,mainLastQuotaApiError:W.lastQuotaApiError}),accounts:Q})}async function l2(B=E()){let Z=await U(B);if(!Z.exists)return null;let $=await U(d(B));return Q0(j0(Z.value,$.value))}function p0(B){return Object.fromEntries(Object.entries(B).filter(([,Z])=>Z!==void 0))}function g2(B){return _({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 v0(B){if(B.type==="api")return _({apiKey:B.apiKey,lastUsed:B.lastUsed});return _({access:B.access,refresh:B.refresh,expires:B.expires,lastUsed:B.lastUsed,lastRefreshedAt:B.lastRefreshedAt,lastRefreshError:B.lastRefreshError,lastQuotaRefreshError:B.lastQuotaRefreshError,quota:B.quota})}function a(B){return Math.max(B?.primary?.checkedAt??0,B?.secondary?.checkedAt??0)}function p(B,Z,$){if($ in Z)B[$]=Z[$];else delete B[$]}function u2(B,Z){return B.access===Z.access&&B.refresh===Z.refresh&&B.expires===Z.expires&&B.lastRefreshedAt===Z.lastRefreshedAt}function i2(B,Z){if(!u2(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 s2(B,Z,$){let z=Z.lastRefreshedAt??0,K=$.lastRefreshedAt??0,G=Z.expires??0,X=$.expires??0,W=K>z?$:z>K?Z:X>G?$:G>X?Z:i2(Z,$);p(B,W,"access"),p(B,W,"refresh"),p(B,W,"expires"),p(B,W,"lastRefreshedAt"),p(B,W,"lastRefreshError")}function c2(B,Z){if(!j(B))return Z;let $=B,z=a($.quota),K=a(Z.quota),G=z>K,X=G?{...$,...Z,quota:$.quota,lastQuotaRefreshError:$.lastQuotaRefreshError}:{...$,...Z};if(!G&&!("lastQuotaRefreshError"in Z))delete X.lastQuotaRefreshError;if(!("lastRefreshError"in Z))delete X.lastRefreshError;if(typeof $.lastUsed==="number"&&(typeof Z.lastUsed!=="number"||$.lastUsed>Z.lastUsed))X.lastUsed=$.lastUsed;return s2(X,$,Z),X}function N0(B){let Z=B.refresh?_({enabled:B.refresh.enabled,intervalMinutes:B.refresh.intervalMinutes,refreshBeforeExpiryMinutes:B.refresh.refreshBeforeExpiryMinutes}):void 0,$=B.quota?_({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 p0({version:1,main:B.main,routing:B.routing,fallbackOn:B.fallbackOn,refresh:Z,quota:$,dump:B.dump,costZeroing:B.costZeroing,killswitch:B.killswitch,logging:B.logging,cachekeep:B.cachekeep,mainAccountId:B.mainAccountId,accounts:B.accounts.map(g2)})}function n2(B,Z){if(!B)return Z;let $=new Map;for(let z of B.accounts)$.set(z.id,z);for(let z of Z.accounts)$.set(z.id,z);return{...B,...Z,accounts:[...$.values()]}}async function v(B){let Z=Date.now()+E0;while(Date.now()<=Z){let $=await n({name:"save",ttlMs:E0,path:B});if($)return $;let z=Z-Date.now();if(z<=0)break;await S2(Math.min(A2,z))}throw Error(`Timed out acquiring account store lock for ${B}; refusing to overwrite newer account data`)}function V0(B){let Z=Object.fromEntries(B.accounts.map(($)=>[$.id,v0($)]));return{version:1,main:_({quota:B.quota?.mainQuota,quotaCheckedAt:B.quota?.mainQuotaCheckedAt,quotaToken:B.quota?.mainQuotaToken,lastQuotaApiError:B.quota?.mainLastQuotaApiError,lastRefreshError:B.refresh?.mainLastRefreshError,refreshLeaseId:B.refresh?.mainRefreshLeaseId,refreshLeaseUntil:B.refresh?.mainRefreshLeaseUntil,refreshLeaseTokenHash:B.refresh?.mainRefreshLeaseTokenHash}),accounts:Z}}async function XZ(B,Z=E()){let $=d(Z),z=await v(Z);try{let K=await v($);try{let G=await U(Z),X=await U($),W=G.exists?Q0(j0(G.value,X.value)):null,Y=n2(W,B),Q={...j(G.value)?G.value:{},...N0(Y)};await M(Z,Q),await M($,V0(Y))}finally{await K.release()}}finally{await z.release()}}async function GZ(B,Z=E()){let $=d(Z),z=await v(Z);try{let K=await v($);try{let G=await U(Z),X=await U($),W=(G.exists?Q0(j0(G.value,X.value)):null)??r2(),Y=B(W)??W,Q={...j(G.value)?G.value:{},...N0(Y)};return await M(Z,Q),await M($,V0(Y)),Y}finally{await K.release()}}finally{await z.release()}}function r2(){return{version:1,main:{type:"opencode",provider:"openai"},accounts:[]}}function a2(B,Z){B.main=B.main??{};let $=typeof B.main.quotaCheckedAt==="number"?B.main.quotaCheckedAt:a(B.main.quota),z=typeof Z.quota?.mainQuotaCheckedAt==="number"?Z.quota.mainQuotaCheckedAt:a(Z.quota?.mainQuota);if($>z)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 o2(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 W0(B){if(Array.isArray(B))return B.map(W0);if(!j(B))return B;return Object.fromEntries(Object.entries(B).filter(([,Z])=>Z!==void 0).map(([Z,$])=>[Z,W0($)]))}async function t2(B,Z=E(),$={mainQuota:!0,mainRefresh:!0,accounts:!0}){let z=d(Z),K=await v(z);try{let G=(await U(z)).value,X=j(G)?{...G,version:1}:{version:1};if($.mainQuota)a2(X,B);if($.mainRefresh)o2(X,B);if($.accounts){let W=$.accounts===!0?null:new Set($.accounts);X.accounts={...j(X.accounts)?X.accounts:{}};for(let Y of B.accounts){if(W&&!W.has(Y.id))continue;X.accounts[Y.id]=c2(X.accounts[Y.id],v0(Y))}if(W){for(let Y of W)if(!B.accounts.some((J)=>J.id===Y))delete X.accounts[Y]}}await M(z,W0(X))}finally{await K.release()}}function e2(B){return B?.fallbackOn?.length?B.fallbackOn:m2}function KZ(B,Z){return e2(Z).includes(B)}function BB(B){let Z=B?.quota?.minimumRemaining||{};return{primary:Z.primary??Z["5h"]??S0.primary,secondary:Z.secondary??Z["1w"]??S0.secondary}}function Y0(B){return B?.quota?.enabled!==!1}function H0(B){return B?.quota?.failClosedOnUnknownQuota??h2}function d0(B,Z){if(!Y0(Z))return!0;let $=BB(Z);for(let z of["primary","secondary"]){let K=B?.[z];if(!K)return!H0(Z);if(K.remainingPercent<$[z])return!1}return!0}function ZB(B){return B?.killswitch?.enabled===!0}function k0(B){return{primary:B?.primary??B?.["5h"]??K0.primary,secondary:B?.secondary??B?.["1w"]??K0.secondary}}function $B(B,Z){if(!B?.killswitch)return K0;if(Z&&B.killswitch.accounts?.[Z])return k0(B.killswitch.accounts[Z]);return k0(B.killswitch.main)}function WZ(B,Z,$){if(!ZB(Z))return!0;let z=$B(Z,$),K=!1;for(let G of["primary","secondary"]){let X=B?.[G];if(!X){K=!0;continue}if(X.remainingPercent<z[G])return!1}if(K)return!H0(Z);return!0}function YZ(B,Z,$){let z=[],K=[B,...Z.map((X)=>X.quota)];for(let X of K)for(let W of["primary","secondary"]){let Y=X?.[W]?.resetsAt;if(!Y)continue;let J=Date.parse(Y);if(Number.isFinite(J)&&J>$)z.push(J)}if(z.length===0)return 300;let G=Math.min(...z);return Math.max(1,Math.ceil((G-$)/1000))}function zB(B){return typeof B.version==="number"&&Array.isArray(B.accounts)}async function JZ(B,Z=E()){let $=await n({name:"migrate",ttlMs:30000,path:Z});if(!$)return;try{let z=await U(Z);if(z.exists&&j(z.value)){if(zB(z.value))return}if(!B)return;let K={version:1,main:{type:"opencode",provider:"openai"},accounts:[]};if(B.access){let W=S({id_token:"",access_token:B.access,refresh_token:B.refresh});if(W)K.mainAccountId=W}let X={...z.exists&&j(z.value)?z.value:{},...N0(K)};await M(Z,X),await M(d(Z),V0(K))}finally{await $.release()}}function XB(B){return B?.refresh?.enabled!==!1}function GB(B){return(B?.refresh?.refreshBeforeExpiryMinutes??240)*60000}function KB(B){return Math.floor(Math.random()*(B+1))}function T(B,Z,$){return!B.access||!B.expires||B.expires-$<=GB(Z)}function WB(B,Z){return Boolean(B.access&&typeof B.expires==="number"&&B.expires>Z)}function YB(B,Z){return Boolean(B.mainAccountId&&Z.accountId&&Z.accountId===B.mainAccountId)}function b(B,Z){let $=B.accounts.findIndex((z)=>z.id===Z.id);if($!==-1)B.accounts[$]=Z}function X0(B){return B instanceof Error?B.message:String(B)}function J0(B,Z,$){B.lastRefreshError=O0({error:Z,now:$,refreshToken:B.refresh,previous:B.lastRefreshError})}function G0(B,Z,$){if(B.lastQuotaRefreshError=U0({error:Z,now:$,previous:B.lastQuotaRefreshError}),Z?.isRefreshError===!0)J0(B,Z,$)}function JB(B){return`fallback-oauth-refresh-${R2("sha256").update(B).digest("base64url").slice(0,16)}`}function w0(B,Z){if(!B)return!1;if(!B.resetsAt)return!0;let $=Date.parse(B.resetsAt);return Number.isFinite($)?$>Z:!0}function QB(B,Z){if(!B)return!1;return w0(B[s],Z)||w0(B[c],Z)}function jB(B,Z,$){if(!B)return!1;let z=Z?.quota?.checkIntervalMinutes??5,K=Math.max(1,z)*60000,G=Math.max(B[s]?.checkedAt??0,B[c]?.checkedAt??0);return $-G<K}function f0(B,Z,$){return!jB(B.quota,Z,$)}function NB(B,Z,$,z){return t($)&&d0(B.quota,Z)&&QB(B.quota,z)}function VB(B){let Z=B?.quota?.checkIntervalMinutes??5;return Math.max(1,Z)*60000}var HB=60000,bB=60000,FB=600000,LB=1e4,DB=100;var QZ=globalThis.setTimeout.bind(globalThis),jZ=globalThis.clearTimeout.bind(globalThis);class qB{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??E(),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[s]?.checkedAt??0,B.quota[c]?.checkedAt??0);if($<=0)return;let z=this.quotaManager.getFallback(B.id,B.access);if(z&&z.checkedAt>=$)return;this.quotaManager.setFallback(B.id,{quota:B.quota,refreshAfter:$+VB(Z),checkedAt:$},B.access)}async load(){return l2(this.configPath)}async save(B,Z){await t2(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(()=>{})},HB+KB(bB)),"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 $=[],z=!1;for(let K of Z.accounts){if(K.enabled===!1||!O(K))continue;if(YB(Z,K))continue;let G=!1,X=K;try{if(T(X,Z,this.now())){let W=X.lastRefreshError;if(W&&P(W,X.refresh,this.now()))throw G=!0,Error(u(W,this.now()));try{X=await this.refreshAccount(X,Z),z=!0}catch(Y){G=!0;let J=Z.accounts.find((Q)=>Q.id===K.id&&O(Q));if(J&&!P(J.lastRefreshError,J.refresh,this.now()))J0(J,Y,this.now()),b(Z,J),z=!0;throw Y}}if(this.seedFallbackQuota(X,Z),this.accountPassesQuotaPolicy(this.quotaPolicyAccount(X),Z))$.push(X)}catch(W){let Y=WB(X,this.now());if(G){if(!Y)continue}else if(!Y)continue;if(NB(X,Z,W,this.now()))y.debug("fallback quota using cached quota after refresh error",{pid:process.pid,accountId:X.id,error:X0(W)}),$.push(X);else if(!H0(Z))$.push(X)}}if(z)await this.save(Z);return $}async markUsed(B){let Z=await this.load();if(!Z)return;let $=Z.accounts.find((z)=>z.id===B.id);if(!$)return;$.lastUsed=this.now(),await this.save(Z)}accountPassesQuotaPolicy(B,Z){return d0(B.quota,Z)}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||!XB(B))return;let Z=!1;for(let $ of B.accounts){if($.enabled===!1||!O($))continue;if(!T($,B,this.now()))continue;if(P($.lastRefreshError,$.refresh,this.now()))continue;try{y.debug("fallback oauth background due",{pid:process.pid,accountId:$.id,expiresInMs:$.expires?$.expires-this.now():void 0}),await this.refreshAccount($,B),Z=!0}catch(z){y.warn("fallback oauth background failed",{pid:process.pid,accountId:$.id,error:X0(z)}),J0($,z,this.now()),b(B,$),Z=!0}}if(Z)await this.save(B)}async refreshQuotaForDueAccounts(){let B=await this.load();if(!B||!Y0(B))return;if(!this.options.fetchQuotaFn)return;let Z=!1;for(let $ of B.accounts){if($.enabled===!1||!O($))continue;let z=$;try{if(T(z,B,this.now())){if(P(z.lastRefreshError,z.refresh,this.now()))continue;z=await this.refreshAccount(z,B),Z=!0}if(_0(z.lastQuotaRefreshError,this.now()))continue;if(this.seedFallbackQuota(z,B),!(this.quotaManager?this.quotaManager.isFallbackStale(z.id,z.access):f0(z,B,this.now())))continue;await this.refreshAccountQuota(z,B),Z=!0}catch(K){G0($,K,this.now()),b(B,$),Z=!0}}if(Z)await this.save(B),this.onFallbackStorageChanged?.()}async refreshQuotaForAllAccounts(B={}){let Z=await this.load(),$=[];if(!Z||!Y0(Z))return{storage:Z,errors:$};if(!this.options.fetchQuotaFn)return{storage:Z,errors:$};let z=B.force??!1,K=!1;for(let G of Z.accounts){if(G.enabled===!1||!O(G))continue;let X=G;try{if(T(X,Z,this.now())){let W=X.lastRefreshError;if(W&&P(W,X.refresh,this.now()))throw Error(u(W,this.now()));X=await this.refreshAccount(X,Z),K=!0}if(!z&&!f0(X,Z,this.now())){if(X.lastQuotaRefreshError)X.lastQuotaRefreshError=void 0,b(Z,X),K=!0;continue}await this.refreshAccountQuota(X,Z),K=!0}catch(W){G0(G,W,this.now()),b(Z,G),K=!0,$.push({accountId:G.id,message:X0(W)})}}if(K)await this.save(Z);return{storage:Z,errors:$}}async refreshAccount(B,Z,$={}){let z=this.refreshPromises.get(B.id);if(z){let X=await z;return b(Z,X),X}let K=this.refreshAccountNow(B,Z,$).finally(()=>{this.refreshPromises.delete(B.id)});this.refreshPromises.set(B.id,K);let G=await K;return b(Z,G),G}async waitForConcurrentFallbackRefresh(B,Z,$,z){let K=Date.now()+LB;while(Date.now()<K){await new Promise((J)=>setTimeout(J,DB));let G=await this.load(),X=G?.accounts.find((J)=>J.id===B.id&&O(J));if(!X)continue;if((X.access!==$.access||X.refresh!==$.refresh||(X.expires??0)>($.expires??0)+60000)&&(z.force||!T(X,G,this.now())))return b(Z,X),y.debug("fallback oauth joined concurrent refresh",{pid:process.pid,accountId:X.id,expiresInMs:X.expires?X.expires-this.now():void 0}),X;let Y=X.lastRefreshError;if(Y&&P(Y,X.refresh,this.now()))throw b(Z,X),Error(u(Y,this.now()))}return null}async refreshAccountNow(B,Z,$){let z=await this.load(),K=z?.accounts.find((W)=>W.id===B.id&&O(W));if(K&&!$.force&&!T(K,z,this.now()))return b(Z,K),K;let G=K??B,X=await n({name:JB(G.id),ttlMs:FB,path:this.configPath,now:this.now,renew:!0});if(!X){y.debug("fallback oauth refresh skipped file lock",{pid:process.pid,accountId:G.id});let W=await this.waitForConcurrentFallbackRefresh(B,Z,G,$);if(W)return W;throw Error("Fallback OAuth refresh is already in progress")}try{if(z=await this.load(),K=z?.accounts.find((J)=>J.id===B.id&&O(J)),K&&!$.force&&!T(K,z,this.now()))return b(Z,K),K;G=K??G;let W=this.options.refreshFn??(async()=>{throw Error("No refreshFn injected into FallbackAccountManager")});y.debug("fallback oauth refresh request start",{pid:process.pid,accountId:G.id,force:$.force===!0,expiresInMs:G.expires?G.expires-this.now():void 0});let Y=await W({refreshToken:G.refresh,fetchImpl:this.fetchImpl,now:this.now});return G.access=Y.access,G.refresh=Y.refresh,G.expires=Y.expires,G.lastRefreshedAt=Y.expires-Y.expiresIn*1000,G.lastRefreshError=void 0,b(Z,G),await this.save(Z),y.debug("fallback oauth refresh succeeded",{pid:process.pid,accountId:G.id,expiresInMs:G.expires?G.expires-this.now():void 0}),G}finally{await X.release()}}async refreshAccountQuota(B,Z){let $=B;if(!$.access)throw Error(`Fallback account ${B.id} has no access token`);if(!this.options.fetchQuotaFn)throw Error("No fetchQuotaFn injected — wham/usage supplement is disabled");let z=this.options.fetchQuotaFn??(async()=>{throw Error("No fetchQuotaFn injected — wham/usage supplement is disabled")}),K=(G)=>this.quotaManager?this.quotaManager.refreshFallback($.id,G):z({accessToken:G,fetchImpl:this.fetchImpl,now:this.now});try{if(!$.access)throw Error(`Fallback account ${B.id} has no access token`);let G=await K($.access);$.quota=G,$.lastQuotaRefreshError=void 0,b(Z,$),await this.save(Z)}catch(G){throw G0(B,G,this.now()),b(Z,B),G}}}
92
+ export{M0 as g,O0 as h,P as i,u as j,U0 as k,_0 as l,R0 as m,y0 as n,B2 as o,C0 as p,I0 as q,S as r,Z2 as s,q as t,G2 as u,K2 as v,W2 as w,Y2 as x,TB as y,EB as z,xB as A,kB as B,n as C,E as D,O as E,$Z as F,K0 as G,l2 as H,XZ as I,GZ as J,KZ as K,ZB as L,WZ as M,YZ as N,JZ as O,qB as P};