@cortexkit/opencode-openai-auth 0.7.0 → 0.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{J as C,K as E,L as X,r as $,y as q,z as B}from"./index-n2s7s3h6.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:
2
+ import{J as C,K as E,L as X,r as $,y as q,z as B}from"./index-zf3axndm.js";import{ua as Y}from"./index-8f1200qx.js";import"./index-nrvjr97q.js";import{Ka as Z}from"./index-zxqb5ydj.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>
package/dist/config.d.ts CHANGED
@@ -29,7 +29,19 @@ export interface ResolvedSettings {
29
29
  }
30
30
  export declare function getConfigDir(): string;
31
31
  export declare function getConfigPath(): string;
32
- /** Resolved settings, computed once per process (env + config are process-static). */
32
+ /**
33
+ * Resolved settings, memoized per process.
34
+ *
35
+ * Env and the config file are read once because neither changes under a running
36
+ * process — except through a command that writes the config itself. Those
37
+ * commands must call `refreshSettings()`, or the process keeps serving the
38
+ * values it read at startup while the file on disk says otherwise.
39
+ */
33
40
  export declare function getSettings(): ResolvedSettings;
41
+ /**
42
+ * Drop the memoized settings after a command writes the config file, so the
43
+ * running process picks the change up without a restart.
44
+ */
45
+ export declare function refreshSettings(): ResolvedSettings;
34
46
  /** Test-only: drop the memoized settings so a later getSettings() re-reads env + config. */
35
47
  export declare function resetSettingsForTest(): void;
@@ -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.7.0";
5
+ export declare const USER_AGENT = "cortexkit-opencode-openai-auth/0.7.1";
6
6
  export declare const RESERVED_ACCOUNT_ID = "main";
7
7
  export declare const RESERVED_ACCOUNT_ID_ERROR = "\"main\" is a reserved account id; choose a different label.";
8
8
  export interface PkceCodes {
@@ -1,2 +1,2 @@
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}});
1
+ import{Ia as Z,Ka as W}from"./index-zxqb5ydj.js";var R=Z(($G,E)=>{var{defineProperty:N,getOwnPropertyDescriptor:Kz,getOwnPropertyNames:Qz}=Object,Wz=Object.prototype.hasOwnProperty,Xz=(z,G)=>{for(var H in G)N(z,H,{get:G[H],enumerable:!0})},Yz=(z,G,H,Q)=>{if(G&&typeof G==="object"||typeof G==="function"){for(let K of Qz(G))if(!Wz.call(z,K)&&K!==H)N(z,K,{get:()=>G[K],enumerable:!(Q=Kz(G,K))||Q.enumerable})}return z},Zz=(z)=>Yz(N({},"__esModule",{value:!0}),z),O={};Xz(O,{VercelOidcTokenError:()=>S});E.exports=Zz(O);class S extends Error{constructor(z,G){super(z);this.name="VercelOidcTokenError",this.cause=G}toString(){if(this.cause)return`${this.name}: ${this.message}: ${this.cause}`;return`${this.name}: ${this.message}`}}});var P=Z((qG,y)=>{var{create:$z,defineProperty:L,getOwnPropertyDescriptor:qz,getOwnPropertyNames:vz,getPrototypeOf:Bz}=Object,Fz=Object.prototype.hasOwnProperty,Uz=(z,G)=>{for(var H in G)L(z,H,{get:G[H],enumerable:!0})},C=(z,G,H,Q)=>{if(G&&typeof G==="object"||typeof G==="function"){for(let K of vz(G))if(!Fz.call(z,K)&&K!==H)L(z,K,{get:()=>G[K],enumerable:!(Q=qz(G,K))||Q.enumerable})}return z},I=(z,G,H)=>(H=z!=null?$z(Bz(z)):{},C(G||!z||!z.__esModule?L(H,"default",{value:z,enumerable:!0}):H,z)),Lz=(z)=>C(L({},"__esModule",{value:!0}),z),x={};Uz(x,{findRootDir:()=>Jz,getUserDataDir:()=>Nz});y.exports=Lz(x);var B=I(W("path")),bz=I(W("fs")),A=I(W("os")),Vz=R();function Jz(){try{let z=process.cwd();while(z!==B.default.dirname(z)){let G=B.default.join(z,".vercel");if(bz.default.existsSync(G))return z;z=B.default.dirname(z)}}catch(z){throw new Vz.VercelOidcTokenError("Token refresh only supported in node server environments")}return null}function Nz(){if(process.env.XDG_DATA_HOME)return process.env.XDG_DATA_HOME;switch(A.default.platform()){case"darwin":return B.default.join(A.default.homedir(),"Library/Application Support");case"linux":return B.default.join(A.default.homedir(),".local/share");case"win32":if(process.env.LOCALAPPDATA)return process.env.LOCALAPPDATA;return null;default:return null}}});var i=Z((vG,c)=>{var{create:Rz,defineProperty:b,getOwnPropertyDescriptor:Az,getOwnPropertyNames:Iz,getPrototypeOf:Dz}=Object,wz=Object.prototype.hasOwnProperty,Tz=(z,G)=>{for(var H in G)b(z,H,{get:G[H],enumerable:!0})},u=(z,G,H,Q)=>{if(G&&typeof G==="object"||typeof G==="function"){for(let K of Iz(G))if(!wz.call(z,K)&&K!==H)b(z,K,{get:()=>G[K],enumerable:!(Q=Az(G,K))||Q.enumerable})}return z},l=(z,G,H)=>(H=z!=null?Rz(Dz(z)):{},u(G||!z||!z.__esModule?b(H,"default",{value:z,enumerable:!0}):H,z)),jz=(z)=>u(b({},"__esModule",{value:!0}),z),g={};Tz(g,{isValidAccessToken:()=>Ez,readAuthConfig:()=>Oz,writeAuthConfig:()=>Sz});c.exports=jz(g);var F=l(W("fs")),h=l(W("path")),Mz=f();function k(){let z=(0,Mz.getVercelDataDir)();if(!z)throw Error(`Unable to find Vercel CLI data directory. Your platform: ${process.platform}. Supported: darwin, linux, win32.`);return h.join(z,"auth.json")}function Oz(){try{let z=k();if(!F.existsSync(z))return null;let G=F.readFileSync(z,"utf8");if(!G)return null;return JSON.parse(G)}catch(z){return null}}function Sz(z){let G=k(),H=h.dirname(G);if(!F.existsSync(H))F.mkdirSync(H,{mode:504,recursive:!0});F.writeFileSync(G,JSON.stringify(z,null,2),{mode:384})}function Ez(z,G=0){if(!z.token)return!1;if(typeof z.expiresAt!=="number")return!0;let H=Math.floor(Date.now()/1000),Q=G/1000;return z.expiresAt>=H+Q}});var a=Z((BG,s)=>{var{defineProperty:T,getOwnPropertyDescriptor:Cz,getOwnPropertyNames:xz}=Object,yz=Object.prototype.hasOwnProperty,Pz=(z,G)=>{for(var H in G)T(z,H,{get:G[H],enumerable:!0})},uz=(z,G,H,Q)=>{if(G&&typeof G==="object"||typeof G==="function"){for(let K of xz(G))if(!yz.call(z,K)&&K!==H)T(z,K,{get:()=>G[K],enumerable:!(Q=Cz(G,K))||Q.enumerable})}return z},lz=(z)=>uz(T({},"__esModule",{value:!0}),z),d={};Pz(d,{processTokenResponse:()=>iz,refreshTokenRequest:()=>cz});s.exports=lz(d);var D=W("os"),gz="https://vercel.com",hz="cl_HYyOPBNtFMfHhaUn9L4QPfTZz6TP47bp",p=`@vercel/oidc node-${process.version} ${(0,D.platform)()} (${(0,D.arch)()}) ${(0,D.hostname)()}`,w=null;async function kz(){if(w)return w;let z=`${gz}/.well-known/openid-configuration`,G=await fetch(z,{headers:{"user-agent":p}});if(!G.ok)throw Error("Failed to discover OAuth endpoints");let H=await G.json();if(!H||typeof H.token_endpoint!=="string")throw Error("Invalid OAuth discovery response");let Q=H.token_endpoint;return w=Q,Q}async function cz(z){let G=await kz();return await fetch(G,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded","user-agent":p},body:new URLSearchParams({client_id:hz,grant_type:"refresh_token",...z})})}async function iz(z){let G=await z.json();if(!z.ok){let H=typeof G==="object"&&G&&"error"in G?String(G.error):"Token refresh failed";return[Error(H)]}if(typeof G!=="object"||G===null)return[Error("Invalid token response")];if(typeof G.access_token!=="string")return[Error("Missing access_token in response")];if(G.token_type!=="Bearer")return[Error("Invalid token_type in response")];if(typeof G.expires_in!=="number")return[Error("Missing expires_in in response")];return[null,G]}});var t=Z((FG,r)=>{var{defineProperty:j,getOwnPropertyDescriptor:fz,getOwnPropertyNames:dz}=Object,pz=Object.prototype.hasOwnProperty,sz=(z,G)=>{for(var H in G)j(z,H,{get:G[H],enumerable:!0})},az=(z,G,H,Q)=>{if(G&&typeof G==="object"||typeof G==="function"){for(let K of dz(G))if(!pz.call(z,K)&&K!==H)j(z,K,{get:()=>G[K],enumerable:!(Q=fz(G,K))||Q.enumerable})}return z},_z=(z)=>az(j({},"__esModule",{value:!0}),z),_={};sz(_,{AccessTokenMissingError:()=>m,RefreshAccessTokenFailedError:()=>n});r.exports=_z(_);class m extends Error{constructor(){super("No authentication found. Please log in with the Vercel CLI (vercel login).");this.name="AccessTokenMissingError"}}class n extends Error{constructor(z){super("Failed to refresh authentication token.",{cause:z});this.name="RefreshAccessTokenFailedError"}}});var f=Z((UG,Hz)=>{var{create:mz,defineProperty:V,getOwnPropertyDescriptor:nz,getOwnPropertyNames:rz,getPrototypeOf:tz}=Object,ez=Object.prototype.hasOwnProperty,oz=(z,G)=>{for(var H in G)V(z,H,{get:G[H],enumerable:!0})},o=(z,G,H,Q)=>{if(G&&typeof G==="object"||typeof G==="function"){for(let K of rz(G))if(!ez.call(z,K)&&K!==H)V(z,K,{get:()=>G[K],enumerable:!(Q=nz(G,K))||Q.enumerable})}return z},zz=(z,G,H)=>(H=z!=null?mz(tz(z)):{},o(G||!z||!z.__esModule?V(H,"default",{value:z,enumerable:!0}):H,z)),zG=(z)=>o(V({},"__esModule",{value:!0}),z),Gz={};oz(Gz,{assertVercelOidcTokenResponse:()=>M,findProjectInfo:()=>QG,getTokenPayload:()=>YG,getVercelDataDir:()=>GG,getVercelOidcToken:()=>KG,getVercelToken:()=>HG,isExpired:()=>ZG,loadToken:()=>XG,saveToken:()=>WG});Hz.exports=zG(Gz);var U=zz(W("path")),X=zz(W("fs")),v=R(),J=P(),$=i(),e=a(),q=t();function GG(){let G=(0,J.getUserDataDir)();if(!G)return null;return U.join(G,"com.vercel.cli")}async function HG(z){let G=(0,$.readAuthConfig)();if(!G?.token)throw new q.AccessTokenMissingError;if((0,$.isValidAccessToken)(G,z?.expirationBufferMs))return G.token;if(!G.refreshToken)throw(0,$.writeAuthConfig)({}),new q.RefreshAccessTokenFailedError("No refresh token available");try{let H=await(0,e.refreshTokenRequest)({refresh_token:G.refreshToken}),[Q,K]=await(0,e.processTokenResponse)(H);if(Q||!K)throw(0,$.writeAuthConfig)({}),new q.RefreshAccessTokenFailedError(Q);let Y={token:K.access_token,expiresAt:Math.floor(Date.now()/1000)+K.expires_in};if(K.refresh_token)Y.refreshToken=K.refresh_token;return(0,$.writeAuthConfig)(Y),Y.token}catch(H){if((0,$.writeAuthConfig)({}),H instanceof q.AccessTokenMissingError||H instanceof q.RefreshAccessTokenFailedError)throw H;throw new q.RefreshAccessTokenFailedError(H)}}async function KG(z,G,H){let Q=`https://api.vercel.com/v1/projects/${G}/token?source=vercel-oidc-refresh${H?`&teamId=${H}`:""}`,K=await fetch(Q,{method:"POST",headers:{Authorization:`Bearer ${z}`}});if(!K.ok)throw new v.VercelOidcTokenError(`Failed to refresh OIDC token: ${K.statusText}`);let Y=await K.json();return M(Y),Y}function M(z){if(!z||typeof z!=="object")throw TypeError("Vercel OIDC token is malformed. Expected an object. Please run `vc env pull` and try again");if(!("token"in z)||typeof z.token!=="string")throw TypeError("Vercel OIDC token is malformed. Expected a string-valued token property. Please run `vc env pull` and try again")}function QG(){let z=(0,J.findRootDir)();if(!z)throw new v.VercelOidcTokenError("Unable to find project root directory. Have you linked your project with `vc link?`");let G=U.join(z,".vercel","project.json");if(!X.existsSync(G))throw new v.VercelOidcTokenError("project.json not found, have you linked your project with `vc link?`");let H=JSON.parse(X.readFileSync(G,"utf8"));if(typeof H.projectId!=="string"&&typeof H.orgId!=="string")throw TypeError("Expected a string-valued projectId property. Try running `vc link` to re-link your project.");return{projectId:H.projectId,teamId:H.orgId}}function WG(z,G){let H=(0,J.getUserDataDir)();if(!H)throw new v.VercelOidcTokenError("Unable to find user data directory. Please reach out to Vercel support.");let Q=U.join(H,"com.vercel.token",`${G}.json`),K=JSON.stringify(z);X.mkdirSync(U.dirname(Q),{mode:504,recursive:!0}),X.writeFileSync(Q,K),X.chmodSync(Q,432);return}function XG(z){let G=(0,J.getUserDataDir)();if(!G)throw new v.VercelOidcTokenError("Unable to find user data directory. Please reach out to Vercel support.");let H=U.join(G,"com.vercel.token",`${z}.json`);if(!X.existsSync(H))return null;let Q=JSON.parse(X.readFileSync(H,"utf8"));return M(Q),Q}function YG(z){let G=z.split(".");if(G.length!==3)throw new v.VercelOidcTokenError("Invalid token. Please run `vc env pull` and try again");let H=G[1].replace(/-/g,"+").replace(/_/g,"/"),Q=H.padEnd(H.length+(4-H.length%4)%4,"=");return JSON.parse(Buffer.from(Q,"base64").toString("utf8"))}function ZG(z,G=0){return z.exp*1000<Date.now()+G}});
2
2
  export{R as a,f as b};
@@ -0,0 +1,3 @@
1
+ import{appendFileSync as D,chmodSync as F,existsSync as B,renameSync as X,statSync as N}from"node:fs";import{tmpdir as P}from"node:os";import{join as K}from"node:path";var j={error:0,warn:1,info:2,debug:3,trace:4},w=!1,A=5242880;function Y(){return process.env.OPENCODE_OPENAI_AUTH_LOG_FILE??K(P(),"opencode-openai-auth.log")}var J;function S(q){if(q===void 0||q in j)J=q}function L(){if(J)return J;let q=process.env.OPENCODE_OPENAI_AUTH_LOG_LEVEL;if(q&&q in j)return q;return"info"}var I=/^(authorization|x-api-key|cookie|set-cookie|refresh|access|token)$/i;function _(q){if(I.test(q))return!0;let G=q.toLowerCase().replace(/[-_]/g,"");if(G==="chatgptaccountid")return!0;if(G.includes("apikey"))return!0;if(G.endsWith("secret")||G.endsWith("password"))return!0;if(G.endsWith("token")&&!G.endsWith("tokens"))return!0;return!1}var x=/\b(Bearer\s+[\w.-]+|sk-[\w-]+|eyJ[\w.-]+)\b/g;function O(q){return C(q,new WeakSet)}function y(q){return M(q,new WeakSet)}function M(q,G){if(typeof q==="string")return q.replace(x,"***REDACTED***");if(Array.isArray(q)){if(G.has(q))return"[Circular]";G.add(q);let H=q.map((Q)=>M(Q,G));return G.delete(q),H}if(q&&typeof q==="object"){if(G.has(q))return"[Circular]";G.add(q);let H={};for(let[Q,W]of Object.entries(q))H[Q]=M(W,G);return G.delete(q),H}return q}function C(q,G){if(typeof q==="string")return q.replace(x,"***REDACTED***");if(Array.isArray(q)){if(G.has(q))return"[Circular]";G.add(q);let H=q.map((Q)=>C(Q,G));return G.delete(q),H}if(q&&typeof q==="object"){if(G.has(q))return"[Circular]";G.add(q);let H={};for(let[Q,W]of Object.entries(q))H[Q]=_(Q)?"***REDACTED***":C(W,G);return G.delete(q),H}return q}var $=[],z,T=3;function U(q){try{F(q,384)}catch{}}function b(){try{let q=Y();if(!(B(q)&&N(q).size>A))return;for(let H=T-1;H>=1;H--)if(B(`${q}.${H}`)){let Q=`${q}.${H+1}`;X(`${q}.${H}`,Q),U(Q)}let G=`${q}.1`;X(q,G),U(G)}catch{}}function V(){if(!$.length)return;let q=$.join("");$=[];try{b();let G=Y();if(B(G))U(G);D(G,q,{encoding:"utf8",mode:384})}catch{}}function R(){if(!z)z=setTimeout(()=>{z=void 0,V()},500)}if(!w)process.on("exit",V);function p(q){try{return` ${JSON.stringify(O(q))}`}catch{return" [unserializable]"}}function Z(q,G,H,Q){if(j[G]>j[L()])return;let W=`[${new Date().toISOString()}] ${G.toUpperCase()} [${q}] ${H}`+(Q===void 0?"":p(Q))+`
2
+ `;if($.push(W),$.length>=50)V();else R()}function f(q){return{error:(G,H)=>Z(q,"error",G,H),warn:(G,H)=>Z(q,"warn",G,H),info:(G,H)=>Z(q,"info",G,H),debug:(G,H)=>Z(q,"debug",G,H),trace:(G,H)=>Z(q,"trace",G,H)}}
3
+ export{S as Aa,O as Ba,y as Ca,f as Da};
@@ -1,2 +1,2 @@
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}
1
+ import{Da as _}from"./index-nrvjr97q.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
2
  export{w as xa,x as ya,y as za};
@@ -1,2 +1,2 @@
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}}
1
+ import{wa as l}from"./index-8f1200qx.js";import{Da as d}from"./index-nrvjr97q.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};
@@ -1,4 +1,4 @@
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 QB}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.7.0";var o="app_EMoamEEZ73f0CkXaXp7hrann",S="https://auth.openai.com",k=1455,BB=3000,D0=`cortexkit-opencode-openai-auth/${O0}`,U0="main",ZB=`"${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 $B(){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 WB(B){return typeof B==="string"&&B.toLowerCase()===U0}function G0(B){if(WB(B))throw Error(ZB);return B}function XB(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 GB(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 zB(B){return B.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&#39;")}var KB=`<!doctype html>
1
+ import{ua as I,va as u,wa as A}from"./index-8f1200qx.js";import{Da as v}from"./index-nrvjr97q.js";import{Ka as Q1}from"./index-zxqb5ydj.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.7.1";var o="app_EMoamEEZ73f0CkXaXp7hrann",S="https://auth.openai.com",k=1455,B1=3000,D0=`cortexkit-opencode-openai-auth/${O0}`,U0="main",Z1=`"${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 $1(){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 W1(B){return typeof B==="string"&&B.toLowerCase()===U0}function G0(B){if(W1(B))throw Error(Z1);return B}function X1(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 G1(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 z1(B){return B.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&#39;")}var K1=`<!doctype html>
2
2
  <html>
3
3
  <head>
4
4
  <title>CortexKit OpenAI Auth - Authorization Successful</title>
@@ -81,9 +81,9 @@ import{ua as I,va as u,wa as A}from"./index-8f1200qx.js";import{Ca as v}from"./i
81
81
  <div class="container">
82
82
  <h1>Authorization Failed</h1>
83
83
  <p>An error occurred during authorization.</p>
84
- <div class="error">${zB(B)}</div>
84
+ <div class="error">${z1(B)}</div>
85
85
  </div>
86
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 YB(){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),GB(z,B,j.pkce).then((H)=>j.resolve(H)).catch((H)=>j.reject(H)),W.writeHead(200,{"Content-Type":"text/html"}),W.end(KB);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 jB(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 JB(){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 HB(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($+BB,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 xZ(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 AZ(B={}){let{label:Z,headless:$=!1,signal:W}=B;if(G0(Z),$){let{deviceData:j,url:H,instructions:Q}=await JB(),b=(async()=>{let N=await HB(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 YB(),z=await $B(),G=M0(crypto.getRandomValues(new Uint8Array(32)).buffer),K=XB(X,z,G),Y=(async()=>{try{if(W?.aborted)throw Error("Login cancelled");let j=await jB(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 NB=v("quota"),z0="primary",K0="secondary",PB="app_EMoamEEZ73f0CkXaXp7hrann",LB="https://auth.openai.com";async function wZ(B){let Z=await B.fetchImpl(`${LB}/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:PB}).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 FB="https://chatgpt.com/backend-api/wham/usage";async function vZ(B){let Z=B.logger??NB,$=B.accountKey??"unknown",W=Date.now();Z.debug("wham usage fetch started",{pid:process.pid,accountId:$});try{let X=await B.fetchImpl(FB,{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 OB}from"node:crypto";var VB=globalThis.setTimeout,bB=5;function p(B){let Z=B?.quota?.checkIntervalMinutes??bB;return Math.max(1,Z)*60000}function DB(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 uZ(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 UB(B){let Z=B?.quota?.minimumRemaining||{};return{primary:Z.primary??Z["5h"]??15,secondary:Z.secondary??Z["1w"]??10}}function q0(B,Z,$){if(!DB(Z))return $+p(Z);let W=UB(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 MB(B){if(!B?.quota?.mainQuota||!B.quota.mainQuotaCheckedAt)return null;return{quota:B.quota.mainQuota,checkedAt:B.quota.mainQuotaCheckedAt,tokenFingerprint:B.quota.mainQuotaToken}}function _B(B){let Z=B?.quota?.refreshEveryNRequests;return typeof Z==="number"&&Number.isFinite(Z)&&Z>0?Math.floor(Z):0}function L(B){return OB("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=_B(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 $=MB(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=VB(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 TB,randomUUID as xB}from"node:crypto";import{setTimeout as AB}from"node:timers/promises";import{randomUUID as qB}from"node:crypto";import{mkdir as CB,rename as SB,rm as EB,writeFile as RB}from"node:fs/promises";import{dirname as yB}from"node:path";async function f(B,Z){await CB(yB(B),{recursive:!0});let $=`${B}.${qB()}.tmp`;await RB($,`${JSON.stringify(Z,null,2)}
88
- `,{encoding:"utf8",mode:384});try{await SB($,B)}catch(W){throw await EB($,{force:!0}).catch(()=>{}),W}}import{readFile as iB}from"node:fs/promises";var R=v("refresh"),t=v("accounts"),fB=1e4,IB=15000,j0=50;function U(B){return B.type==="oauth"}function mB(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 J1(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 kB=[401,403,429],S0={primary:0,secondary:0},hB=!1,H0={primary:5,secondary:10};function J(B){return B!=null&&typeof B==="object"&&!Array.isArray(B)}var wB=new Set(["__proto__","constructor","prototype"]);function vB(B){return B.length>0&&!wB.has(B)}function pB(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():xB(),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 lB(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 gB(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(!mB(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:lB(B.quota)}}function dB(B){if(!J(B))return;let Z=Object.create(null);for(let[$,W]of Object.entries(B)){if(!vB($)||!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(gB).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:dB(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 iB(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 uB(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 sB(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 rB(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 nB(B,Z){return B.access===Z.access&&B.refresh===Z.refresh&&B.expires===Z.expires&&B.lastRefreshedAt===Z.lastRefreshedAt}function cB(B,Z){if(!nB(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 oB(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:cB(Z,$);l(B,K,"access"),l(B,K,"refresh"),l(B,K,"expires"),l(B,K,"lastRefreshedAt"),l(B,K,"lastRefreshError")}function aB(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 oB(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(rB)})}async function d(B){let Z=Date.now(),$=Z+IB,W=0;while(Date.now()<=$){W++;let G=await A({name:"save",ttlMs:fB,path:B});if(G)return G;let K=$-Date.now();if(K<=0)break;await AB(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 tB(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 eB(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 BZ(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 ZZ(B,Z,$){let W=tB(B);if(W===null)return[];let{preservedRawEntries:X,preservedIds:z}=eB(B,W,Z,$);return f0(z),X}async function Q1(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)??$Z(),j=new Set(Y.accounts.map((O)=>O.id)),H=B(Y)??Y,Q=new Set($.allowDrop??[]),b=ZZ(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:BZ(Z0.accounts)}),H}finally{await z.release()}}finally{await X.release()}}function $Z(){return{version:1,main:{type:"opencode",provider:"openai"},accounts:[]}}function WZ(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 XZ(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 GZ(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)WZ(G,B);if($.mainRefresh)XZ(G,B);if($.accounts){let K=$.accounts===!0?null:new Set($.accounts),Y=await uB(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]=aB(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 zZ(B){return B?.fallbackOn?.length?B.fallbackOn:kB}function N1(B,Z){return zZ(Z).includes(B)}function KZ(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??hB}function p0(B,Z,$=Date.now()){if(!N0(Z))return!0;if(!B)return!i(Z);let W=KZ(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 P1(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 L1(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 YZ(B){return typeof B.version==="number"&&Array.isArray(B.accounts)}async function F1(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(YZ(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 jZ(B){return B?.refresh?.enabled!==!1}function JZ(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-$<=JZ(Z)}function HZ(B,Z){return Boolean(B.access&&typeof B.expires==="number"&&B.expires>Z)}function QZ(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 NZ(B){return`fallback-oauth-refresh-${TB("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 PZ(B,Z){if(!B)return!1;return x0(B.primary,Z)||x0(B.secondary,Z)}function LZ(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!LZ(B.quota,Z,$)}function FZ(B,Z,$,W){return W0($)&&p0(B.quota,Z,W)&&PZ(B.quota,W)}function OZ(B){let Z=B?.quota?.checkIntervalMinutes??5;return Math.max(1,Z)*60000}var VZ=60000,bZ=60000,DZ=600000,UZ=1e4,MZ=100;var O1=globalThis.setTimeout.bind(globalThis),V1=globalThis.clearTimeout.bind(globalThis);class _Z{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:$+OZ(Z),checkedAt:$},B.access,!1,B.accountId)}async load(){return sB(this.configPath)}async save(B,Z){await GZ(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(()=>{})},VZ+d0(bZ)),"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(QZ(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(pB(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=HZ(G,this.now());if(z){if(!Y)continue}else if(!Y)continue;if(FZ(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||!jZ(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()+UZ;while(Date.now()<X){await new Promise((j)=>setTimeout(j,MZ));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:NZ(z.id),ttlMs:DZ,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,$B as n,V0 as o,b0 as p,c as q,G0 as r,XB as s,E as t,YB as u,jB as v,JB as w,HB as x,xZ as y,AZ as z,_0 as A,wZ as B,vZ as C,uZ as D,D as E,U as F,J1 as G,H0 as H,vB as I,uB as J,sB as K,Q1 as L,N1 as M,l0 as N,g0 as O,P1 as P,L1 as Q,F1 as R,_Z as S};
87
+ </html>`,w,h,V=new Map;function q(){return V.size}function E(B){if(V.delete(B),q()===0)C()}async function Y1(){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),G1(z,B,j.pkce).then((H)=>j.resolve(H)).catch((H)=>j.reject(H)),W.writeHead(200,{"Content-Type":"text/html"}),W.end(K1);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 j1(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 J1(){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 H1(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($+B1,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 xB(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 AB(B={}){let{label:Z,headless:$=!1,signal:W}=B;if(G0(Z),$){let{deviceData:j,url:H,instructions:Q}=await J1(),b=(async()=>{let N=await H1(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 Y1(),z=await $1(),G=M0(crypto.getRandomValues(new Uint8Array(32)).buffer),K=X1(X,z,G),Y=(async()=>{try{if(W?.aborted)throw Error("Login cancelled");let j=await j1(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 N1=v("quota"),z0="primary",K0="secondary",P1="app_EMoamEEZ73f0CkXaXp7hrann",L1="https://auth.openai.com";async function wB(B){let Z=await B.fetchImpl(`${L1}/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:P1}).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 F1="https://chatgpt.com/backend-api/wham/usage";async function vB(B){let Z=B.logger??N1,$=B.accountKey??"unknown",W=Date.now();Z.debug("wham usage fetch started",{pid:process.pid,accountId:$});try{let X=await B.fetchImpl(F1,{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-dvwtmy7f.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 O1}from"node:crypto";var V1=globalThis.setTimeout,b1=5;function p(B){let Z=B?.quota?.checkIntervalMinutes??b1;return Math.max(1,Z)*60000}function D1(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 uB(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 U1(B){let Z=B?.quota?.minimumRemaining||{};return{primary:Z.primary??Z["5h"]??15,secondary:Z.secondary??Z["1w"]??10}}function q0(B,Z,$){if(!D1(Z))return $+p(Z);let W=U1(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 M1(B){if(!B?.quota?.mainQuota||!B.quota.mainQuotaCheckedAt)return null;return{quota:B.quota.mainQuota,checkedAt:B.quota.mainQuotaCheckedAt,tokenFingerprint:B.quota.mainQuotaToken}}function _1(B){let Z=B?.quota?.refreshEveryNRequests;return typeof Z==="number"&&Number.isFinite(Z)&&Z>0?Math.floor(Z):0}function L(B){return O1("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=_1(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 $=M1(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=V1(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 T1,randomUUID as x1}from"node:crypto";import{setTimeout as A1}from"node:timers/promises";import{randomUUID as q1}from"node:crypto";import{mkdir as C1,rename as S1,rm as E1,writeFile as R1}from"node:fs/promises";import{dirname as y1}from"node:path";async function f(B,Z){await C1(y1(B),{recursive:!0});let $=`${B}.${q1()}.tmp`;await R1($,`${JSON.stringify(Z,null,2)}
88
+ `,{encoding:"utf8",mode:384});try{await S1($,B)}catch(W){throw await E1($,{force:!0}).catch(()=>{}),W}}import{readFile as i1}from"node:fs/promises";var R=v("refresh"),t=v("accounts"),f1=1e4,I1=15000,j0=50;function U(B){return B.type==="oauth"}function m1(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 JZ(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 k1=[401,403,429],S0={primary:0,secondary:0},h1=!1,H0={primary:5,secondary:10};function J(B){return B!=null&&typeof B==="object"&&!Array.isArray(B)}var w1=new Set(["__proto__","constructor","prototype"]);function v1(B){return B.length>0&&!w1.has(B)}function p1(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():x1(),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 l1(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 g1(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(!m1(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:l1(B.quota)}}function d1(B){if(!J(B))return;let Z=Object.create(null);for(let[$,W]of Object.entries(B)){if(!v1($)||!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(g1).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:d1(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 i1(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 u1(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 s1(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 r1(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 n1(B,Z){return B.access===Z.access&&B.refresh===Z.refresh&&B.expires===Z.expires&&B.lastRefreshedAt===Z.lastRefreshedAt}function c1(B,Z){if(!n1(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 o1(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:c1(Z,$);l(B,K,"access"),l(B,K,"refresh"),l(B,K,"expires"),l(B,K,"lastRefreshedAt"),l(B,K,"lastRefreshError")}function a1(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 o1(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(r1)})}async function d(B){let Z=Date.now(),$=Z+I1,W=0;while(Date.now()<=$){W++;let G=await A({name:"save",ttlMs:f1,path:B});if(G)return G;let K=$-Date.now();if(K<=0)break;await A1(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 t1(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 e1(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 BB(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 ZB(B,Z,$){let W=t1(B);if(W===null)return[];let{preservedRawEntries:X,preservedIds:z}=e1(B,W,Z,$);return f0(z),X}async function QZ(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)??$B(),j=new Set(Y.accounts.map((O)=>O.id)),H=B(Y)??Y,Q=new Set($.allowDrop??[]),b=ZB(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:BB(Z0.accounts)}),H}finally{await z.release()}}finally{await X.release()}}function $B(){return{version:1,main:{type:"opencode",provider:"openai"},accounts:[]}}function WB(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 XB(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 GB(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)WB(G,B);if($.mainRefresh)XB(G,B);if($.accounts){let K=$.accounts===!0?null:new Set($.accounts),Y=await u1(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]=a1(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 zB(B){return B?.fallbackOn?.length?B.fallbackOn:k1}function NZ(B,Z){return zB(Z).includes(B)}function KB(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??h1}function p0(B,Z,$=Date.now()){if(!N0(Z))return!0;if(!B)return!i(Z);let W=KB(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 PZ(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 LZ(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 YB(B){return typeof B.version==="number"&&Array.isArray(B.accounts)}async function FZ(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(YB(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 jB(B){return B?.refresh?.enabled!==!1}function JB(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-$<=JB(Z)}function HB(B,Z){return Boolean(B.access&&typeof B.expires==="number"&&B.expires>Z)}function QB(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 NB(B){return`fallback-oauth-refresh-${T1("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 PB(B,Z){if(!B)return!1;return x0(B.primary,Z)||x0(B.secondary,Z)}function LB(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!LB(B.quota,Z,$)}function FB(B,Z,$,W){return W0($)&&p0(B.quota,Z,W)&&PB(B.quota,W)}function OB(B){let Z=B?.quota?.checkIntervalMinutes??5;return Math.max(1,Z)*60000}var VB=60000,bB=60000,DB=600000,UB=1e4,MB=100;var OZ=globalThis.setTimeout.bind(globalThis),VZ=globalThis.clearTimeout.bind(globalThis);class _B{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:$+OB(Z),checkedAt:$},B.access,!1,B.accountId)}async load(){return s1(this.configPath)}async save(B,Z){await GB(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(()=>{})},VB+d0(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 $=[],W=!1;for(let X of Z.accounts){if(X.enabled===!1||!U(X))continue;if(QB(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(p1(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=HB(G,this.now());if(z){if(!Y)continue}else if(!Y)continue;if(FB(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||!jB(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()+UB;while(Date.now()<X){await new Promise((j)=>setTimeout(j,MB));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:NB(z.id),ttlMs:DB,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,$1 as n,V0 as o,b0 as p,c as q,G0 as r,X1 as s,E as t,Y1 as u,j1 as v,J1 as w,H1 as x,xB as y,AB as z,_0 as A,wB as B,vB as C,uB as D,D as E,U as F,JZ as G,H0 as H,v1 as I,u1 as J,s1 as K,QZ as L,NZ as M,l0 as N,g0 as O,PZ as P,LZ as Q,FZ as R,_B as S};
@@ -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 Da,L as Ea,T as Fa};
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 Ea,L as Fa,T as Ga};
@@ -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 Ga,u as Ha,v as Ia,x as Ja};
2
+ export{t as Ha,u as Ia,v as Ja,x as Ka};