@cortexkit/opencode-openai-auth 0.2.0 → 0.2.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/README.md CHANGED
@@ -40,19 +40,19 @@ Each opens an interactive dialog in the TUI and also accepts explicit arguments:
40
40
  | Command | Arguments | Purpose |
41
41
  | --- | --- | --- |
42
42
  | `/openai-quota` | — | Show 5h + weekly quota for all accounts. |
43
- | `/openai-account` | `add [label]` · `switch <id>` · `remove <id>` · `order <a> <b>` | Manage main + fallback accounts (non-destructive switch). |
44
- | `/openai-routing` | `main-first` · `fallback-first` | Account preference order. |
43
+ | `/openai-account` | `add [label]` · `remove <id>` · `order <a> <b>` | Manage main + fallback accounts. |
44
+ | `/openai-routing` | `main-first` · `fallback-first` | Routing mode: which account is tried first. |
45
45
  | `/openai-killswitch` | `on` · `off` · `set <acct>:<5h>,<1w> ...` | Hard-block accounts below quota thresholds. |
46
46
  | `/openai-cachekeep` | `on` · `off` · `subagents on` · `subagents off` | Idle prompt-cache keep-warm. |
47
47
  | `/openai-logging` | `<level>` | Set log level live. |
48
48
  | `/openai-dump` | `on` · `off` | Toggle transport request dumps. |
49
49
 
50
- CLI (fallback accounts only; the main account comes from `/login openai`):
50
+ CLI (fallback accounts only; the main account comes from `/login openai`). Run via `npx` — no global install needed:
51
51
 
52
52
  ```text
53
- openai-auth login [--label <name>] [--headless]
54
- openai-auth list
55
- openai-auth remove <id>
53
+ npx @cortexkit/opencode-openai-auth login [--label <name>] [--headless]
54
+ npx @cortexkit/opencode-openai-auth list
55
+ npx @cortexkit/opencode-openai-auth remove <id>
56
56
  ```
57
57
 
58
58
  ## Configuration
package/dist/cli.js CHANGED
@@ -1,8 +1,8 @@
1
1
  #!/usr/bin/env node
2
- import{D as $,H as q,J as V,y as Y,z as Z}from"./index-nzqvhshr.js";import"./index-garxs63s.js";import{ia as X}from"./index-2b5wejq3.js";import{execFileSync as B}from"node:child_process";function Q(C,H=process.platform,D=B){try{if(H==="win32"){D("cmd",["/c","start","",C],{stdio:"ignore",timeout:3000});return}D(H==="darwin"?"open":"xdg-open",[C],{stdio:"ignore",timeout:3000})}catch{}}function T(){console.log(`Usage:
3
- openai-auth login [--label <name>] [--headless]
4
- openai-auth list
5
- openai-auth remove <id>
2
+ import{D as $,H as q,I as V,y as Y,z as Z}from"./index-xftpnva2.js";import"./index-88b7ha2h.js";import{ha as X}from"./index-vj00ztg7.js";import{execFileSync as B}from"node:child_process";function Q(C,H=process.platform,D=B){try{if(H==="win32"){D("cmd",["/c","start","",C],{stdio:"ignore",timeout:3000});return}D(H==="darwin"?"open":"xdg-open",[C],{stdio:"ignore",timeout:3000})}catch{}}function T(){console.log(`Usage:
3
+ npx @cortexkit/opencode-openai-auth login [--label <name>] [--headless]
4
+ npx @cortexkit/opencode-openai-auth list
5
+ npx @cortexkit/opencode-openai-auth remove <id>
6
6
 
7
7
  Fallback accounts are stored in:
8
8
  ${$()}`)}function E(C){let H=[],D={};for(let K=0;K<C.length;K++){let j=C[K];if(!j)continue;if(j.startsWith("--")){let G=j.slice(2),z=C[K+1];if(z&&!z.startsWith("--"))D[G]=z,K++;else D[G]=!0}else H.push(j)}return{positional:H,flags:D}}async function P(){let{positional:C,flags:H}=E(process.argv.slice(2)),[D,...K]=C;if(!D||D==="help")T(),process.exit(0);switch(D){case"login":{let j=typeof H.label==="string"?H.label:void 0,G=Boolean(H.headless),{url:z,instructions:J,completion:O}=await Z({label:j,headless:G});if(console.log(`
@@ -64,7 +64,6 @@ export type AccountStorage = {
64
64
  };
65
65
  routing?: {
66
66
  mode?: RoutingMode;
67
- activeId?: string;
68
67
  };
69
68
  fallbackOn?: number[];
70
69
  refresh?: {
@@ -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.2.0";
5
+ export declare const USER_AGENT = "cortexkit-opencode-openai-auth/0.2.1";
6
6
  export interface PkceCodes {
7
7
  verifier: string;
8
8
  challenge: string;
@@ -0,0 +1,2 @@
1
+ import{$ as v}from"./index-88b7ha2h.js";import{randomUUID as O}from"node:crypto";import{mkdir as N,readFile as C,rename as g,rm as h,writeFile as k}from"node:fs/promises";import{tmpdir as L}from"node:os";import{dirname as D,join as R}from"node:path";var F=v("sidebar"),M="OPENCODE_OPENAI_AUTH_SIDEBAR_STATE_FILE",I=R(L(),"opencode-openai-auth"),f=R(I,"sidebar-state.json");function W(){return process.env[M]||f}var B={main:{quota:null,killed:!1},fallbacks:[],activeId:void 0,route:"main",lastUpdated:0};function b(K){if(K===null||typeof K!=="object"||Array.isArray(K))return B;let x=K,J=x.main,Q;if(J!==null&&typeof J==="object"&&!Array.isArray(J)){let H=J;Q={quota:"quota"in H?H.quota:null,killed:typeof H.killed==="boolean"?H.killed:!1,...typeof H.quotaBackedOff==="boolean"?{quotaBackedOff:H.quotaBackedOff}:{},...typeof H.quotaBackoffUntil==="number"?{quotaBackoffUntil:H.quotaBackoffUntil}:{},...typeof H.refreshBackedOff==="boolean"?{refreshBackedOff:H.refreshBackedOff}:{},...typeof H.refreshBackoffUntil==="number"?{refreshBackoffUntil:H.refreshBackoffUntil}:{}}}else Q={quota:null,killed:!1};let Y=x.fallbacks,X=Array.isArray(Y)?Y.filter((H)=>H!==null&&typeof H==="object"&&!Array.isArray(H)&&typeof H.id==="string").map((H)=>({id:H.id,label:typeof H.label==="string"?H.label:void 0,quota:"quota"in H?H.quota:null,killed:typeof H.killed==="boolean"?H.killed:!1,enabled:typeof H.enabled==="boolean"?H.enabled:!0})):[],Z=typeof x.activeId==="string"?x.activeId:void 0,V=typeof x.route==="string"?x.route:B.route,$=typeof x.lastUpdated==="number"?x.lastUpdated:0,j=typeof x.planType==="string"?x.planType:void 0,z=typeof x.credits==="number"?x.credits:void 0;return{main:Q,fallbacks:X,activeId:Z,route:V,lastUpdated:$,...j!==void 0?{planType:j}:{},...z!==void 0?{credits:z}:{}}}async function A(){try{let K=await C(W(),"utf8");return b(JSON.parse(K))}catch{return B}}var G=Promise.resolve();function m(K,x=W()){return G=G.then(()=>U(K,x)).catch(()=>{}),G}async function U(K,x){let J=`${x}.${O()}.tmp`;try{await N(D(x),{recursive:!0}),await k(J,JSON.stringify(K),"utf8"),await g(J,x)}catch(Q){await h(J,{force:!0}).catch(()=>{}),F.warn("sidebar write failed",{pid:process.pid,error:Q instanceof Error?Q.message:String(Q)})}}function w(){return G}function c(K){let x=K.activeId;if(x&&x!=="main"){let J=K.fallbacks.find((Q)=>Q.enabled&&Q.id===x);if(J)return{id:J.id,name:J.label??J.id,quota:J.quota,killed:J.killed}}return{id:"main",name:"main",quota:K.main.quota,killed:K.main.killed}}function l(K){let x=K?.primary?.usedPercent??null,J=K?.secondary?.usedPercent??null;if(x==null&&J==null)return{primaryUsedPercent:x,secondaryUsedPercent:J,text:null};return{primaryUsedPercent:x,secondaryUsedPercent:J,text:`5h: ${x==null?"—":`${Math.round(x)}%`} 7d: ${J==null?"—":`${Math.round(J)}%`}`}}var o=18000000,d=604800000,_=300000,y=0.01,S=1;function s(K,x,J){if(!K.resetsAt)return null;let Q=new Date(K.resetsAt).getTime();if(!Number.isFinite(Q))return null;let Y=Q-x,X=J-Y;if(X<_)return null;if(X<x*y)return null;if(X>=x)return null;let Z=K.usedPercent,V=Math.min(Math.max(X/x*100,0),100),$=Z-V,j=Math.abs($)<S?"on-pace":$>0?"deficit":"reserve",z=null;if(Z>0){let H=X*100/Z,q=Y+H;if(q<Q)z=new Date(q).toISOString()}return{pacePercent:V,deltaPercent:$,state:j,runsOutAt:z}}
2
+ export{W as P,B as Q,b as R,A as S,m as T,w as U,c as V,l as W,o as X,d as Y,s as Z};
@@ -1,3 +1,3 @@
1
1
  import{appendFileSync as N,existsSync as U,renameSync as V,statSync as P}from"node:fs";import{tmpdir as X}from"node:os";import{join as Y}from"node:path";var $={error:0,warn:1,info:2,debug:3,trace:4},x=!1,C=5242880;function w(){return process.env.OPENCODE_OPENAI_AUTH_LOG_FILE??Y(X(),"opencode-openai-auth.log")}var B;function R(q){if(q===void 0||q in $)B=q}function F(){if(B)return B;let q=process.env.OPENCODE_OPENAI_AUTH_LOG_LEVEL;if(q&&q in $)return q;return"info"}var A=/^(authorization|x-api-key|cookie|set-cookie|refresh|access|token)$/i;function D(q){if(A.test(q))return!0;let H=q.toLowerCase().replace(/[-_]/g,"");if(H==="chatgptaccountid")return!0;if(H.includes("apikey"))return!0;if(H.endsWith("secret")||H.endsWith("password"))return!0;if(H.endsWith("token")&&!H.endsWith("tokens"))return!0;return!1}var I=/\b(Bearer\s+[\w.-]+|sk-[\w-]+|eyJ[\w.-]+)\b/g;function K(q){return G(q,new WeakSet)}function G(q,H){if(typeof q==="string")return q.replace(I,"***REDACTED***");if(Array.isArray(q)){if(H.has(q))return"[Circular]";H.add(q);let J=q.map((Q)=>G(Q,H));return H.delete(q),J}if(q&&typeof q==="object"){if(H.has(q))return"[Circular]";H.add(q);let J={};for(let[Q,j]of Object.entries(q))J[Q]=D(Q)?"***REDACTED***":G(j,H);return H.delete(q),J}return q}var Z=[],z,b=3;function p(){try{let q=w();if(!(U(q)&&P(q).size>C))return;for(let H=b-1;H>=1;H--)if(U(`${q}.${H}`))V(`${q}.${H}`,`${q}.${H+1}`);V(q,`${q}.1`)}catch{}}function M(){if(!Z.length)return;let q=Z.join("");Z=[];try{p(),N(w(),q)}catch{}}function L(){if(!z)z=setTimeout(()=>{z=void 0,M()},500)}if(!x)process.on("exit",M);function _(q){try{return` ${JSON.stringify(K(q))}`}catch{return" [unserializable]"}}function W(q,H,J,Q){if($[H]>$[F()])return;let j=`[${new Date().toISOString()}] ${H.toUpperCase()} [${q}] ${J}`+(Q===void 0?"":_(Q))+`
2
2
  `;if(Z.push(j),Z.length>=50)M();else L()}function S(q){return{error:(H,J)=>W(q,"error",H,J),warn:(H,J)=>W(q,"warn",H,J),info:(H,J)=>W(q,"info",H,J),debug:(H,J)=>W(q,"debug",H,J),trace:(H,J)=>W(q,"trace",H,J)}}
3
- export{R as $,S as aa};
3
+ export{R as _,S as $};
@@ -1,2 +1,2 @@
1
1
  import{mkdir as u,readdir as l,readFile as c,rename as p,unlink as m,writeFile as d}from"node:fs/promises";import{join as a}from"node:path";function f(t){try{return process.kill(t,0),!0}catch(r){return r.code==="EPERM"}}async function b(t,r){await u(t,{recursive:!0});let s={...r,startedAt:Date.now()},e=a(t,`port-${r.pid}.json`),i=`${e}.${process.pid}.tmp`;return await d(i,JSON.stringify(s),{encoding:"utf8",mode:384}),await p(i,e),e}async function h(t,r){let s;try{s=await l(t)}catch{return null}let e=[];for(let n of s){if(!n.startsWith("port-")||!n.endsWith(".json"))continue;try{let o=JSON.parse(await c(a(t,n),"utf8"));if(Number.isFinite(o.port))if(f(o.pid))e.push(o);else m(a(t,n)).catch(()=>{})}catch{}}if(e.length===0)return null;let i=r!==void 0&&r>=1?e.filter((n)=>n.pid===r):[];return(i.length>0?i:e).sort((n,o)=>o.startedAt-n.startedAt)[0]??null}
2
- export{b as ba,h as ca};
2
+ export{b as aa,h as ba};
@@ -1 +1 @@
1
- import{createHash as z}from"node:crypto";import{homedir as A,tmpdir as K}from"node:os";import{join as q,resolve as B}from"node:path";var F="OPENCODE_OPENAI_AUTH_RPC_DIR";function M(f){let k=process.env[F]?.trim();if(k)return B(f,k);let w=z("sha256").update(f).digest("hex").slice(0,16),x=process.env.XDG_STATE_HOME||q(A(),".local","state");return q(x,"cortexkit","openai-auth","rpc",w)}export{K as da,M as ea};
1
+ import{createHash as z}from"node:crypto";import{homedir as A,tmpdir as K}from"node:os";import{join as q,resolve as B}from"node:path";var F="OPENCODE_OPENAI_AUTH_RPC_DIR";function M(f){let k=process.env[F]?.trim();if(k)return B(f,k);let w=z("sha256").update(f).digest("hex").slice(0,16),x=process.env.XDG_STATE_HOME||q(A(),".local","state");return q(x,"cortexkit","openai-auth","rpc",w)}export{K as ca,M as da};
@@ -1,2 +1,2 @@
1
- import{ga as Y,ia as K}from"./index-2b5wejq3.js";var V=Y((rz,O)=>{var{defineProperty:J,getOwnPropertyDescriptor:r,getOwnPropertyNames:t}=Object,e=Object.prototype.hasOwnProperty,o=(z,B)=>{for(var F in B)J(z,F,{get:B[F],enumerable:!0})},zz=(z,B,F,H)=>{if(B&&typeof B==="object"||typeof B==="function"){for(let G of t(B))if(!e.call(z,G)&&G!==F)J(z,G,{get:()=>B[G],enumerable:!(H=r(B,G))||H.enumerable})}return z},Bz=(z)=>zz(J({},"__esModule",{value:!0}),z),M={};o(M,{VercelOidcTokenError:()=>j});O.exports=Bz(M);class j extends Error{constructor(z,B){super(z);this.name="VercelOidcTokenError",this.cause=B}toString(){if(this.cause)return`${this.name}: ${this.message}: ${this.cause}`;return`${this.name}: ${this.message}`}}});var C=Y((tz,x)=>{var{create:Fz,defineProperty:v,getOwnPropertyDescriptor:Gz,getOwnPropertyNames:Hz,getPrototypeOf:Kz}=Object,Qz=Object.prototype.hasOwnProperty,Wz=(z,B)=>{for(var F in B)v(z,F,{get:B[F],enumerable:!0})},S=(z,B,F,H)=>{if(B&&typeof B==="object"||typeof B==="function"){for(let G of Hz(B))if(!Qz.call(z,G)&&G!==F)v(z,G,{get:()=>B[G],enumerable:!(H=Gz(B,G))||H.enumerable})}return z},N=(z,B,F)=>(F=z!=null?Fz(Kz(z)):{},S(B||!z||!z.__esModule?v(F,"default",{value:z,enumerable:!0}):F,z)),Xz=(z)=>S(v({},"__esModule",{value:!0}),z),E={};Wz(E,{findRootDir:()=>$z,getUserDataDir:()=>qz});x.exports=Xz(E);var Z=N(K("path")),Yz=N(K("fs")),A=N(K("os")),Zz=V();function $z(){try{let z=process.cwd();while(z!==Z.default.dirname(z)){let B=Z.default.join(z,".vercel");if(Yz.default.existsSync(B))return z;z=Z.default.dirname(z)}}catch(z){throw new Zz.VercelOidcTokenError("Token refresh only supported in node server environments")}return null}function qz(){if(process.env.XDG_DATA_HOME)return process.env.XDG_DATA_HOME;switch(A.default.platform()){case"darwin":return Z.default.join(A.default.homedir(),"Library/Application Support");case"linux":return Z.default.join(A.default.homedir(),".local/share");case"win32":if(process.env.LOCALAPPDATA)return process.env.LOCALAPPDATA;return null;default:return null}}});var c=Y((ez,g)=>{var{create:vz,defineProperty:b,getOwnPropertyDescriptor:bz,getOwnPropertyNames:Uz,getPrototypeOf:Lz}=Object,Jz=Object.prototype.hasOwnProperty,Vz=(z,B)=>{for(var F in B)b(z,F,{get:B[F],enumerable:!0})},y=(z,B,F,H)=>{if(B&&typeof B==="object"||typeof B==="function"){for(let G of Uz(B))if(!Jz.call(z,G)&&G!==F)b(z,G,{get:()=>B[G],enumerable:!(H=bz(B,G))||H.enumerable})}return z},u=(z,B,F)=>(F=z!=null?vz(Lz(z)):{},y(B||!z||!z.__esModule?b(F,"default",{value:z,enumerable:!0}):F,z)),Az=(z)=>y(b({},"__esModule",{value:!0}),z),P={};Vz(P,{isValidAccessToken:()=>wz,readAuthConfig:()=>Rz,writeAuthConfig:()=>Iz});g.exports=Az(P);var $=u(K("fs")),l=u(K("path")),Nz=k();function h(){let z=(0,Nz.getVercelDataDir)();if(!z)throw Error(`Unable to find Vercel CLI data directory. Your platform: ${process.platform}. Supported: darwin, linux, win32.`);return l.join(z,"auth.json")}function Rz(){try{let z=h();if(!$.existsSync(z))return null;let B=$.readFileSync(z,"utf8");if(!B)return null;return JSON.parse(B)}catch(z){return null}}function Iz(z){let B=h(),F=l.dirname(B);if(!$.existsSync(F))$.mkdirSync(F,{mode:504,recursive:!0});$.writeFileSync(B,JSON.stringify(z,null,2),{mode:384})}function wz(z){if(!z.token)return!1;if(typeof z.expiresAt!=="number")return!0;let B=Math.floor(Date.now()/1000);return z.expiresAt>=B}});var p=Y((oz,d)=>{var{defineProperty:w,getOwnPropertyDescriptor:Dz,getOwnPropertyNames:Tz}=Object,Mz=Object.prototype.hasOwnProperty,jz=(z,B)=>{for(var F in B)w(z,F,{get:B[F],enumerable:!0})},Oz=(z,B,F,H)=>{if(B&&typeof B==="object"||typeof B==="function"){for(let G of Tz(B))if(!Mz.call(z,G)&&G!==F)w(z,G,{get:()=>B[G],enumerable:!(H=Dz(B,G))||H.enumerable})}return z},Sz=(z)=>Oz(w({},"__esModule",{value:!0}),z),i={};jz(i,{processTokenResponse:()=>uz,refreshTokenRequest:()=>yz});d.exports=Sz(i);var R=K("os"),Ez="https://vercel.com",xz="cl_HYyOPBNtFMfHhaUn9L4QPfTZz6TP47bp",f=`@vercel/oidc node-${process.version} ${(0,R.platform)()} (${(0,R.arch)()}) ${(0,R.hostname)()}`,I=null;async function Cz(){if(I)return I;let z=`${Ez}/.well-known/openid-configuration`,B=await fetch(z,{headers:{"user-agent":f}});if(!B.ok)throw Error("Failed to discover OAuth endpoints");let F=await B.json();if(!F||typeof F.token_endpoint!=="string")throw Error("Invalid OAuth discovery response");let H=F.token_endpoint;return I=H,H}async function yz(z){let B=await Cz();return await fetch(B,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded","user-agent":f},body:new URLSearchParams({client_id:xz,grant_type:"refresh_token",...z})})}async function uz(z){let B=await z.json();if(!z.ok){let F=typeof B==="object"&&B&&"error"in B?String(B.error):"Token refresh failed";return[Error(F)]}if(typeof B!=="object"||B===null)return[Error("Invalid token response")];if(typeof B.access_token!=="string")return[Error("Missing access_token in response")];if(B.token_type!=="Bearer")return[Error("Invalid token_type in response")];if(typeof B.expires_in!=="number")return[Error("Missing expires_in in response")];return[null,B]}});var k=Y((zB,n)=>{var{create:Pz,defineProperty:U,getOwnPropertyDescriptor:lz,getOwnPropertyNames:hz,getPrototypeOf:gz}=Object,cz=Object.prototype.hasOwnProperty,kz=(z,B)=>{for(var F in B)U(z,F,{get:B[F],enumerable:!0})},a=(z,B,F,H)=>{if(B&&typeof B==="object"||typeof B==="function"){for(let G of hz(B))if(!cz.call(z,G)&&G!==F)U(z,G,{get:()=>B[G],enumerable:!(H=lz(B,G))||H.enumerable})}return z},_=(z,B,F)=>(F=z!=null?Pz(gz(z)):{},a(B||!z||!z.__esModule?U(F,"default",{value:z,enumerable:!0}):F,z)),iz=(z)=>a(U({},"__esModule",{value:!0}),z),m={};kz(m,{assertVercelOidcTokenResponse:()=>D,findProjectInfo:()=>sz,getTokenPayload:()=>mz,getVercelCliToken:()=>dz,getVercelDataDir:()=>fz,getVercelOidcToken:()=>pz,isExpired:()=>nz,loadToken:()=>_z,saveToken:()=>az});n.exports=iz(m);var q=_(K("path")),Q=_(K("fs")),X=V(),L=C(),W=c(),s=p();function fz(){let B=(0,L.getUserDataDir)();if(!B)return null;return q.join(B,"com.vercel.cli")}async function dz(){let z=(0,W.readAuthConfig)();if(!z)return null;if((0,W.isValidAccessToken)(z))return z.token||null;if(!z.refreshToken)return(0,W.writeAuthConfig)({}),null;try{let B=await(0,s.refreshTokenRequest)({refresh_token:z.refreshToken}),[F,H]=await(0,s.processTokenResponse)(B);if(F||!H)return(0,W.writeAuthConfig)({}),null;let G={token:H.access_token,expiresAt:Math.floor(Date.now()/1000)+H.expires_in};if(H.refresh_token)G.refreshToken=H.refresh_token;return(0,W.writeAuthConfig)(G),G.token??null}catch(B){return(0,W.writeAuthConfig)({}),null}}async function pz(z,B,F){let H=`https://api.vercel.com/v1/projects/${B}/token?source=vercel-oidc-refresh${F?`&teamId=${F}`:""}`,G=await fetch(H,{method:"POST",headers:{Authorization:`Bearer ${z}`}});if(!G.ok)throw new X.VercelOidcTokenError(`Failed to refresh OIDC token: ${G.statusText}`);let T=await G.json();return D(T),T}function D(z){if(!z||typeof z!=="object")throw TypeError("Vercel OIDC token is malformed. Expected an object. Please run `vc env pull` and try again");if(!("token"in z)||typeof z.token!=="string")throw TypeError("Vercel OIDC token is malformed. Expected a string-valued token property. Please run `vc env pull` and try again")}function sz(){let z=(0,L.findRootDir)();if(!z)throw new X.VercelOidcTokenError("Unable to find project root directory. Have you linked your project with `vc link?`");let B=q.join(z,".vercel","project.json");if(!Q.existsSync(B))throw new X.VercelOidcTokenError("project.json not found, have you linked your project with `vc link?`");let F=JSON.parse(Q.readFileSync(B,"utf8"));if(typeof F.projectId!=="string"&&typeof F.orgId!=="string")throw TypeError("Expected a string-valued projectId property. Try running `vc link` to re-link your project.");return{projectId:F.projectId,teamId:F.orgId}}function az(z,B){let F=(0,L.getUserDataDir)();if(!F)throw new X.VercelOidcTokenError("Unable to find user data directory. Please reach out to Vercel support.");let H=q.join(F,"com.vercel.token",`${B}.json`),G=JSON.stringify(z);Q.mkdirSync(q.dirname(H),{mode:504,recursive:!0}),Q.writeFileSync(H,G),Q.chmodSync(H,432);return}function _z(z){let B=(0,L.getUserDataDir)();if(!B)throw new X.VercelOidcTokenError("Unable to find user data directory. Please reach out to Vercel support.");let F=q.join(B,"com.vercel.token",`${z}.json`);if(!Q.existsSync(F))return null;let H=JSON.parse(Q.readFileSync(F,"utf8"));return D(H),H}function mz(z){let B=z.split(".");if(B.length!==3)throw new X.VercelOidcTokenError("Invalid token. Please run `vc env pull` and try again");let F=B[1].replace(/-/g,"+").replace(/_/g,"/"),H=F.padEnd(F.length+(4-F.length%4)%4,"=");return JSON.parse(Buffer.from(H,"base64").toString("utf8"))}function nz(z){return z.exp*1000<Date.now()}});
1
+ import{fa as Y,ha as K}from"./index-vj00ztg7.js";var V=Y((rz,O)=>{var{defineProperty:J,getOwnPropertyDescriptor:r,getOwnPropertyNames:t}=Object,e=Object.prototype.hasOwnProperty,o=(z,B)=>{for(var F in B)J(z,F,{get:B[F],enumerable:!0})},zz=(z,B,F,H)=>{if(B&&typeof B==="object"||typeof B==="function"){for(let G of t(B))if(!e.call(z,G)&&G!==F)J(z,G,{get:()=>B[G],enumerable:!(H=r(B,G))||H.enumerable})}return z},Bz=(z)=>zz(J({},"__esModule",{value:!0}),z),M={};o(M,{VercelOidcTokenError:()=>j});O.exports=Bz(M);class j extends Error{constructor(z,B){super(z);this.name="VercelOidcTokenError",this.cause=B}toString(){if(this.cause)return`${this.name}: ${this.message}: ${this.cause}`;return`${this.name}: ${this.message}`}}});var C=Y((tz,x)=>{var{create:Fz,defineProperty:v,getOwnPropertyDescriptor:Gz,getOwnPropertyNames:Hz,getPrototypeOf:Kz}=Object,Qz=Object.prototype.hasOwnProperty,Wz=(z,B)=>{for(var F in B)v(z,F,{get:B[F],enumerable:!0})},S=(z,B,F,H)=>{if(B&&typeof B==="object"||typeof B==="function"){for(let G of Hz(B))if(!Qz.call(z,G)&&G!==F)v(z,G,{get:()=>B[G],enumerable:!(H=Gz(B,G))||H.enumerable})}return z},N=(z,B,F)=>(F=z!=null?Fz(Kz(z)):{},S(B||!z||!z.__esModule?v(F,"default",{value:z,enumerable:!0}):F,z)),Xz=(z)=>S(v({},"__esModule",{value:!0}),z),E={};Wz(E,{findRootDir:()=>$z,getUserDataDir:()=>qz});x.exports=Xz(E);var Z=N(K("path")),Yz=N(K("fs")),A=N(K("os")),Zz=V();function $z(){try{let z=process.cwd();while(z!==Z.default.dirname(z)){let B=Z.default.join(z,".vercel");if(Yz.default.existsSync(B))return z;z=Z.default.dirname(z)}}catch(z){throw new Zz.VercelOidcTokenError("Token refresh only supported in node server environments")}return null}function qz(){if(process.env.XDG_DATA_HOME)return process.env.XDG_DATA_HOME;switch(A.default.platform()){case"darwin":return Z.default.join(A.default.homedir(),"Library/Application Support");case"linux":return Z.default.join(A.default.homedir(),".local/share");case"win32":if(process.env.LOCALAPPDATA)return process.env.LOCALAPPDATA;return null;default:return null}}});var c=Y((ez,g)=>{var{create:vz,defineProperty:b,getOwnPropertyDescriptor:bz,getOwnPropertyNames:Uz,getPrototypeOf:Lz}=Object,Jz=Object.prototype.hasOwnProperty,Vz=(z,B)=>{for(var F in B)b(z,F,{get:B[F],enumerable:!0})},y=(z,B,F,H)=>{if(B&&typeof B==="object"||typeof B==="function"){for(let G of Uz(B))if(!Jz.call(z,G)&&G!==F)b(z,G,{get:()=>B[G],enumerable:!(H=bz(B,G))||H.enumerable})}return z},u=(z,B,F)=>(F=z!=null?vz(Lz(z)):{},y(B||!z||!z.__esModule?b(F,"default",{value:z,enumerable:!0}):F,z)),Az=(z)=>y(b({},"__esModule",{value:!0}),z),P={};Vz(P,{isValidAccessToken:()=>wz,readAuthConfig:()=>Rz,writeAuthConfig:()=>Iz});g.exports=Az(P);var $=u(K("fs")),l=u(K("path")),Nz=k();function h(){let z=(0,Nz.getVercelDataDir)();if(!z)throw Error(`Unable to find Vercel CLI data directory. Your platform: ${process.platform}. Supported: darwin, linux, win32.`);return l.join(z,"auth.json")}function Rz(){try{let z=h();if(!$.existsSync(z))return null;let B=$.readFileSync(z,"utf8");if(!B)return null;return JSON.parse(B)}catch(z){return null}}function Iz(z){let B=h(),F=l.dirname(B);if(!$.existsSync(F))$.mkdirSync(F,{mode:504,recursive:!0});$.writeFileSync(B,JSON.stringify(z,null,2),{mode:384})}function wz(z){if(!z.token)return!1;if(typeof z.expiresAt!=="number")return!0;let B=Math.floor(Date.now()/1000);return z.expiresAt>=B}});var p=Y((oz,d)=>{var{defineProperty:w,getOwnPropertyDescriptor:Dz,getOwnPropertyNames:Tz}=Object,Mz=Object.prototype.hasOwnProperty,jz=(z,B)=>{for(var F in B)w(z,F,{get:B[F],enumerable:!0})},Oz=(z,B,F,H)=>{if(B&&typeof B==="object"||typeof B==="function"){for(let G of Tz(B))if(!Mz.call(z,G)&&G!==F)w(z,G,{get:()=>B[G],enumerable:!(H=Dz(B,G))||H.enumerable})}return z},Sz=(z)=>Oz(w({},"__esModule",{value:!0}),z),i={};jz(i,{processTokenResponse:()=>uz,refreshTokenRequest:()=>yz});d.exports=Sz(i);var R=K("os"),Ez="https://vercel.com",xz="cl_HYyOPBNtFMfHhaUn9L4QPfTZz6TP47bp",f=`@vercel/oidc node-${process.version} ${(0,R.platform)()} (${(0,R.arch)()}) ${(0,R.hostname)()}`,I=null;async function Cz(){if(I)return I;let z=`${Ez}/.well-known/openid-configuration`,B=await fetch(z,{headers:{"user-agent":f}});if(!B.ok)throw Error("Failed to discover OAuth endpoints");let F=await B.json();if(!F||typeof F.token_endpoint!=="string")throw Error("Invalid OAuth discovery response");let H=F.token_endpoint;return I=H,H}async function yz(z){let B=await Cz();return await fetch(B,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded","user-agent":f},body:new URLSearchParams({client_id:xz,grant_type:"refresh_token",...z})})}async function uz(z){let B=await z.json();if(!z.ok){let F=typeof B==="object"&&B&&"error"in B?String(B.error):"Token refresh failed";return[Error(F)]}if(typeof B!=="object"||B===null)return[Error("Invalid token response")];if(typeof B.access_token!=="string")return[Error("Missing access_token in response")];if(B.token_type!=="Bearer")return[Error("Invalid token_type in response")];if(typeof B.expires_in!=="number")return[Error("Missing expires_in in response")];return[null,B]}});var k=Y((zB,n)=>{var{create:Pz,defineProperty:U,getOwnPropertyDescriptor:lz,getOwnPropertyNames:hz,getPrototypeOf:gz}=Object,cz=Object.prototype.hasOwnProperty,kz=(z,B)=>{for(var F in B)U(z,F,{get:B[F],enumerable:!0})},a=(z,B,F,H)=>{if(B&&typeof B==="object"||typeof B==="function"){for(let G of hz(B))if(!cz.call(z,G)&&G!==F)U(z,G,{get:()=>B[G],enumerable:!(H=lz(B,G))||H.enumerable})}return z},_=(z,B,F)=>(F=z!=null?Pz(gz(z)):{},a(B||!z||!z.__esModule?U(F,"default",{value:z,enumerable:!0}):F,z)),iz=(z)=>a(U({},"__esModule",{value:!0}),z),m={};kz(m,{assertVercelOidcTokenResponse:()=>D,findProjectInfo:()=>sz,getTokenPayload:()=>mz,getVercelCliToken:()=>dz,getVercelDataDir:()=>fz,getVercelOidcToken:()=>pz,isExpired:()=>nz,loadToken:()=>_z,saveToken:()=>az});n.exports=iz(m);var q=_(K("path")),Q=_(K("fs")),X=V(),L=C(),W=c(),s=p();function fz(){let B=(0,L.getUserDataDir)();if(!B)return null;return q.join(B,"com.vercel.cli")}async function dz(){let z=(0,W.readAuthConfig)();if(!z)return null;if((0,W.isValidAccessToken)(z))return z.token||null;if(!z.refreshToken)return(0,W.writeAuthConfig)({}),null;try{let B=await(0,s.refreshTokenRequest)({refresh_token:z.refreshToken}),[F,H]=await(0,s.processTokenResponse)(B);if(F||!H)return(0,W.writeAuthConfig)({}),null;let G={token:H.access_token,expiresAt:Math.floor(Date.now()/1000)+H.expires_in};if(H.refresh_token)G.refreshToken=H.refresh_token;return(0,W.writeAuthConfig)(G),G.token??null}catch(B){return(0,W.writeAuthConfig)({}),null}}async function pz(z,B,F){let H=`https://api.vercel.com/v1/projects/${B}/token?source=vercel-oidc-refresh${F?`&teamId=${F}`:""}`,G=await fetch(H,{method:"POST",headers:{Authorization:`Bearer ${z}`}});if(!G.ok)throw new X.VercelOidcTokenError(`Failed to refresh OIDC token: ${G.statusText}`);let T=await G.json();return D(T),T}function D(z){if(!z||typeof z!=="object")throw TypeError("Vercel OIDC token is malformed. Expected an object. Please run `vc env pull` and try again");if(!("token"in z)||typeof z.token!=="string")throw TypeError("Vercel OIDC token is malformed. Expected a string-valued token property. Please run `vc env pull` and try again")}function sz(){let z=(0,L.findRootDir)();if(!z)throw new X.VercelOidcTokenError("Unable to find project root directory. Have you linked your project with `vc link?`");let B=q.join(z,".vercel","project.json");if(!Q.existsSync(B))throw new X.VercelOidcTokenError("project.json not found, have you linked your project with `vc link?`");let F=JSON.parse(Q.readFileSync(B,"utf8"));if(typeof F.projectId!=="string"&&typeof F.orgId!=="string")throw TypeError("Expected a string-valued projectId property. Try running `vc link` to re-link your project.");return{projectId:F.projectId,teamId:F.orgId}}function az(z,B){let F=(0,L.getUserDataDir)();if(!F)throw new X.VercelOidcTokenError("Unable to find user data directory. Please reach out to Vercel support.");let H=q.join(F,"com.vercel.token",`${B}.json`),G=JSON.stringify(z);Q.mkdirSync(q.dirname(H),{mode:504,recursive:!0}),Q.writeFileSync(H,G),Q.chmodSync(H,432);return}function _z(z){let B=(0,L.getUserDataDir)();if(!B)throw new X.VercelOidcTokenError("Unable to find user data directory. Please reach out to Vercel support.");let F=q.join(B,"com.vercel.token",`${z}.json`);if(!Q.existsSync(F))return null;let H=JSON.parse(Q.readFileSync(F,"utf8"));return D(H),H}function mz(z){let B=z.split(".");if(B.length!==3)throw new X.VercelOidcTokenError("Invalid token. Please run `vc env pull` and try again");let F=B[1].replace(/-/g,"+").replace(/_/g,"/"),H=F.padEnd(F.length+(4-F.length%4)%4,"=");return JSON.parse(Buffer.from(H,"base64").toString("utf8"))}function nz(z){return z.exp*1000<Date.now()}});
2
2
  export{V as a,k as b};
@@ -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 fa,u as ga,v as ha,x as ia};
2
+ export{t as ea,u as fa,v as ga,x as ha};
@@ -0,0 +1,92 @@
1
+ import{$ as x0}from"./index-88b7ha2h.js";import{ha as J1}from"./index-vj00ztg7.js";import{createHash as g0}from"node:crypto";var u0=86400000,i0=300000,s0=3600000,c0=60000,n0=900000,r0=300000;function a(B){return B instanceof Error?B.message:String(B)}function a0(B){let Z=B?.status;if(typeof Z==="number")return Z===429||Z>=500;if(!(B instanceof Error))return!1;return B.message.includes("fetch failed")||"code"in B&&(B.code==="ECONNRESET"||B.code==="ECONNREFUSED"||B.code==="ETIMEDOUT"||B.code==="UND_ERR_CONNECT_TIMEOUT")}function o(B){let Z=a(B),$=B?.status;if(typeof $==="number")return $===429||$>=500;if(!(B instanceof Error))return!1;let z=B.code;return Z.includes("fetch failed")||z==="ECONNRESET"||z==="ECONNREFUSED"||z==="ETIMEDOUT"||z==="UND_ERR_CONNECT_TIMEOUT"}function F0(B){return g0("sha256").update(B).digest("hex")}function L0(B){let Z=F0(B.refreshToken),z=(B.previous?.tokenHash===Z?B.previous.retryCount??0:0)+1,K,G=B.error?.retryAfter;if(typeof G==="number"&&G>0)K=G*1000;else if(a0(B.error))K=Math.min(s0,i0*2**Math.min(z-1,6));else K=u0;return{message:a(B.error),checkedAt:B.now,nextRetryAt:B.now+K,retryCount:z,tokenHash:Z}}function U(B,Z,$){if(!B?.nextRetryAt||B.nextRetryAt<=$)return!1;if(!Z)return!0;return B.tokenHash===F0(Z)}function l(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 D0(B){let $=(B.previous?.retryCount??0)+1,z,K=B.error?.retryAfter;if(typeof K==="number"&&K>0)z=K*1000;else if(o(B.error))z=Math.min(n0,c0*2**Math.min($-1,6));else z=r0;return{message:a(B.error),checkedAt:B.now,nextRetryAt:B.now+z,retryCount:$}}function q0(B,Z){if(!B?.nextRetryAt||B.nextRetryAt<=Z)return!1;return!0}function t(B){if(!B)return;let Z=Number(B);if(Number.isFinite(Z)&&Z>0)return Math.ceil(Z);let $=Date.parse(B);if(Number.isFinite($)){let z=Math.ceil(($-Date.now())/1000);return z>0?z:void 0}return}import{createServer as o0}from"node:http";import{setTimeout as t0}from"node:timers/promises";var M0="0.2.1";var g="app_EMoamEEZ73f0CkXaXp7hrann",C="https://auth.openai.com",k=1455,e0=3000,_0=`cortexkit-opencode-openai-auth/${M0}`;function P0(B){let Z=new Uint8Array(B),$=String.fromCharCode(...Z);return btoa($).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function B1(){let Z=Array.from(crypto.getRandomValues(new Uint8Array(43))).map((z)=>"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~"[z%66]).join(""),$=P0(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(Z)));return{verifier:Z,challenge:$}}function O0(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 U0(B){let Z=B.chatgpt_account_id;if(typeof Z==="string"&&Z.length>0)return Z;let $=B["https://api.openai.com/auth"];if($&&typeof $==="object"&&!Array.isArray($)&&typeof $.chatgpt_account_id==="string"&&$.chatgpt_account_id.length>0)return $.chatgpt_account_id;let z=B.organizations;if(Array.isArray(z)){let K=z[0];if(K&&typeof K==="object"&&!Array.isArray(K)&&typeof K.id==="string"&&K.id.length>0)return K.id}return}function T(B){if(B.id_token){let Z=O0(B.id_token),$=Z&&U0(Z);if($)return $}if(B.access_token){let Z=O0(B.access_token);return Z?U0(Z):void 0}return}function Z1(B,Z,$){let z=new URLSearchParams({response_type:"code",client_id:g,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`${C}/oauth/authorize?${z.toString()}`}async function $1(B,Z,$){let z=await fetch(`${C}/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:g,code_verifier:$.verifier}).toString()});if(!z.ok)throw Error(`Token exchange failed: ${z.status}`);return await z.json()}function z1(B){return B.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&#39;")}var X1=`<!doctype html>
2
+ <html>
3
+ <head>
4
+ <title>CortexKit OpenAI Auth - Authorization Successful</title>
5
+ <style>
6
+ body {
7
+ font-family:
8
+ system-ui,
9
+ -apple-system,
10
+ sans-serif;
11
+ display: flex;
12
+ justify-content: center;
13
+ align-items: center;
14
+ height: 100vh;
15
+ margin: 0;
16
+ background: #131010;
17
+ color: #f1ecec;
18
+ }
19
+ .container {
20
+ text-align: center;
21
+ padding: 2rem;
22
+ }
23
+ h1 {
24
+ color: #f1ecec;
25
+ margin-bottom: 1rem;
26
+ }
27
+ p {
28
+ color: #b7b1b1;
29
+ }
30
+ </style>
31
+ </head>
32
+ <body>
33
+ <div class="container">
34
+ <h1>Authorization Successful</h1>
35
+ <p>You can close this window and return to OpenCode.</p>
36
+ </div>
37
+ <script>
38
+ setTimeout(() => window.close(), 2000)
39
+ </script>
40
+ </body>
41
+ </html>`,e=(B)=>`<!doctype html>
42
+ <html>
43
+ <head>
44
+ <title>CortexKit OpenAI Auth - Authorization Failed</title>
45
+ <style>
46
+ body {
47
+ font-family:
48
+ system-ui,
49
+ -apple-system,
50
+ sans-serif;
51
+ display: flex;
52
+ justify-content: center;
53
+ align-items: center;
54
+ height: 100vh;
55
+ margin: 0;
56
+ background: #131010;
57
+ color: #f1ecec;
58
+ }
59
+ .container {
60
+ text-align: center;
61
+ padding: 2rem;
62
+ }
63
+ h1 {
64
+ color: #fc533a;
65
+ margin-bottom: 1rem;
66
+ }
67
+ p {
68
+ color: #b7b1b1;
69
+ }
70
+ .error {
71
+ color: #ff917b;
72
+ font-family: monospace;
73
+ margin-top: 1rem;
74
+ padding: 1rem;
75
+ background: #3c140d;
76
+ border-radius: 0.5rem;
77
+ }
78
+ </style>
79
+ </head>
80
+ <body>
81
+ <div class="container">
82
+ <h1>Authorization Failed</h1>
83
+ <p>An error occurred during authorization.</p>
84
+ <div class="error">${z1(B)}</div>
85
+ </div>
86
+ </body>
87
+ </html>`,f,w,D=new Map;function _(){return D.size}function q(B){if(D.delete(B),_()===0)P()}async function G1(){let B=`http://localhost:${k}/auth/callback`;if(f)return{port:k,redirectUri:B};if(w)return w;w=(async()=>{let Z=o0(($,z)=>{let K=new URL($.url||"/",`http://127.0.0.1:${k}`);if(K.pathname==="/auth/callback"){let G=K.searchParams.get("code"),X=K.searchParams.get("state"),W=K.searchParams.get("error"),J=K.searchParams.get("error_description");if(W){let Q=J||W;if(X){let V=D.get(X);if(V)V.reject(Error(Q)),q(X);else if(_()===0)P()}else if(_()===0)P();z.writeHead(200,{"Content-Type":"text/html"}),z.end(e(Q));return}if(!G||!X){let Q=!G?"Missing authorization code":"Missing state parameter";if(X){let V=D.get(X);if(V)V.reject(Error(Q)),q(X);else if(_()===0)P()}else if(_()===0)P();z.writeHead(400,{"Content-Type":"text/html"}),z.end(e(Q));return}let Y=D.get(X);if(!Y){if(_()===0)P();z.writeHead(400,{"Content-Type":"text/html"}),z.end(e("Unknown state — authorization may have expired"));return}q(X),$1(G,B,Y.pkce).then((Q)=>Y.resolve(Q)).catch((Q)=>Y.reject(Q)),z.writeHead(200,{"Content-Type":"text/html"}),z.end(X1);return}if(K.pathname==="/cancel"){let G=K.searchParams.get("state"),X=G?[G]:[...D.keys()];z.writeHead(200),z.end("Login cancelled");for(let W of X){let J=D.get(W);if(!J)continue;J.reject(Error("Login cancelled")),q(W)}if(_()===0)P();return}z.writeHead(404),z.end("Not found")});return await new Promise(($,z)=>{Z.once("error",z),Z.listen(k,"127.0.0.1",()=>{Z.off("error",z),$()})}),f=Z,{port:k,redirectUri:B}})();try{return await w}finally{w=void 0}}function P(){if(f){let B=f;f=void 0,B.close(()=>{}),B.closeIdleConnections?.(),setTimeout(()=>{B.closeAllConnections?.()},25).unref?.()}}function K1(B,Z,$=300000,z){return new Promise((K,G)=>{if(z?.aborted){q(Z),G(Error("Login cancelled"));return}let X=setTimeout(()=>{if(D.get(Z))q(Z),G(Error("OAuth callback timeout — authorization took too long"))},$),W=()=>{if(clearTimeout(X),D.get(Z))q(Z),G(Error("Login cancelled"))};if(z)z.addEventListener("abort",W);D.set(Z,{pkce:B,state:Z,resolve:(J)=>{if(clearTimeout(X),z)z.removeEventListener("abort",W);K(J)},reject:(J)=>{if(clearTimeout(X),z)z.removeEventListener("abort",W);G(J)}})})}async function W1(){let B=await fetch(`${C}/api/accounts/deviceauth/usercode`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":_0},body:JSON.stringify({client_id:g})});if(!B.ok)throw Error("Failed to initiate device authorization");let Z=await B.json();return{deviceData:Z,url:`${C}/codex/device`,instructions:`Enter code: ${Z.user_code}`}}async function Y1(B,Z){let $=Math.max(parseInt(B.interval,10)||5,1)*1000,z=typeof B.expires_in==="number"?B.expires_in:parseInt(B.expires_in||"",10),K=!Number.isNaN(z)&&z>0?z*1000:900000,G=Date.now();while(!0){if(Z?.aborted)throw Error("Device authorization cancelled");if(Date.now()-G>K)throw Error("Device authorization expired");let X=await fetch(`${C}/api/accounts/deviceauth/token`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":_0},body:JSON.stringify({device_auth_id:B.device_auth_id,user_code:B.user_code})});if(X.ok){let Y=await X.json(),Q=await fetch(`${C}/oauth/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",code:Y.authorization_code,redirect_uri:`${C}/deviceauth/callback`,client_id:g,code_verifier:Y.code_verifier}).toString()});if(!Q.ok)throw Error(`Token exchange failed: ${Q.status}`);return await Q.json()}if(X.status!==403&&X.status!==404)throw Error(`Device authorization failed: ${X.status}`);let W=K-(Date.now()-G);if(W<=0)throw Error("Device authorization expired");let J=Math.min($+e0,W);try{await t0(J,void 0,{signal:Z})}catch(Y){if(Y instanceof Error&&Y.name==="AbortError")throw Error("Device authorization cancelled");throw Y}}}function T2(B,Z){let $=-1;if(Z.accountId)$=B.findIndex((z)=>z.accountId&&z.accountId===Z.accountId);if($<0)$=B.findIndex((z)=>z.id===Z.id);if($<0&&Z.label&&!Z.accountId)$=B.findIndex((z)=>z.label===Z.label);if($>=0)return B[$]={...B[$],...Z,addedAt:B[$]?.addedAt??Z.addedAt},$;return B.push(Z),B.length-1}async function E2(B={}){let{label:Z,headless:$=!1,signal:z}=B;if($){let{deviceData:Y,url:Q,instructions:V}=await W1(),F=(async()=>{let N=await Y1(Y,z),H=Date.now();return{id:Z||T(N)||crypto.randomUUID(),label:Z||void 0,type:"oauth",access:N.access_token,refresh:N.refresh_token,expires:H+(N.expires_in??3600)*1000,enabled:!0,addedAt:H,lastUsed:H,lastRefreshedAt:H,accountId:T(N)}})();return{url:Q,instructions:V,completion:F}}let{redirectUri:K}=await G1(),G=await B1(),X=P0(crypto.getRandomValues(new Uint8Array(32)).buffer),W=Z1(K,G,X),J=(async()=>{try{if(z?.aborted)throw Error("Login cancelled");let Y=await K1(G,X,void 0,z),Q=Date.now();return{id:Z||T(Y)||crypto.randomUUID(),label:Z||void 0,type:"oauth",access:Y.access_token,refresh:Y.refresh_token,expires:Q+(Y.expires_in??3600)*1000,enabled:!0,addedAt:Q,lastUsed:Q,lastRefreshedAt:Q,accountId:T(Y)}}finally{q(X)}})();return{url:W,instructions:"Complete authorization in your browser. This window will close automatically.",completion:J}}var u="primary",i="secondary",Q1="app_EMoamEEZ73f0CkXaXp7hrann",j1="https://auth.openai.com";async function x2(B){let Z=await B.fetchImpl(`${j1}/oauth/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"refresh_token",refresh_token:B.refreshToken,client_id:Q1}).toString()});if(!Z.ok){let z=t(Z.headers.get("retry-after"));throw Object.assign(Error(`Token refresh failed: ${Z.status}`),{status:Z.status,retryAfter:z,isRefreshError:!0})}let $=await Z.json();if(!$||typeof $.access_token!=="string"||!$.access_token||typeof $.refresh_token!=="string"||!$.refresh_token||typeof $.expires_in!=="number")throw Object.assign(Error("Token refresh failed: malformed response"),{status:Z.status,isRefreshError:!0});return{access:$.access_token,refresh:$.refresh_token,expires:B.now()+$.expires_in*1000,expiresIn:$.expires_in}}var N1="https://chatgpt.com/backend-api/wham/usage";async function k2(B){let Z=await B.fetchImpl(N1,{headers:{authorization:`Bearer ${B.accessToken}`,"chatgpt-account-id":B.accountId??"","oai-client-platform":"web","oai-client-version":"0","x-openai-target-path":"/backend-api/wham/usage"}});if(!Z.ok){let z=t(Z.headers.get("retry-after"));throw Object.assign(Error(`wham usage check failed: ${Z.status}`),{status:Z.status,retryAfter:z})}let{normalizeWham:$}=await import("./quota-normalize-s1bctr9a.js");return $(await Z.json())}import{randomUUID as B0}from"node:crypto";import{mkdir as V1,readFile as Z0,rename as H1,rm as m,stat as C0,writeFile as $0}from"node:fs/promises";import{homedir as b1}from"node:os";import{dirname as v2,join as h}from"node:path";var F1=globalThis.setTimeout.bind(globalThis),L1=globalThis.clearTimeout.bind(globalThis),D1="openai-auth.json";function q1(){if(process.env.OPENCODE_CONFIG_DIR?.trim())return process.env.OPENCODE_CONFIG_DIR.trim();return h(process.env.XDG_CONFIG_HOME||h(b1(),".config"),"opencode")}function M1(){return process.env.OPENCODE_OPENAI_AUTH_FILE?.trim()||h(q1(),D1)}async function s(B){let $=`${B.path??M1()}.${B.name}.lock`,z=h($,"owner.json"),K=B0(),G=B.now??Date.now,X=null,W=!1;async function J(){try{return JSON.parse(await Z0($,"utf8"))}catch(N){if(N.code!=="EISDIR")throw N;return JSON.parse(await Z0(z,"utf8"))}}async function Y(){await $0($,`${JSON.stringify({ownerId:K,expiresAt:G()+B.ttlMs})}
88
+ `,{encoding:"utf8",mode:384})}async function Q(){try{return await $0($,`${JSON.stringify({ownerId:K,expiresAt:G()+B.ttlMs})}
89
+ `,{encoding:"utf8",mode:384,flag:"wx"}),!0}catch(N){let H=N.code;if(H==="EEXIST"||H==="EISDIR")return!1;throw N}}function V(){if(!B.renew||W)return;let N=B.renewIntervalMs??Math.max(1000,Math.floor(B.ttlMs/3));if(X=F1(()=>{(async()=>{try{let H=await J(),v=G();if(W||H?.ownerId!==K||Number(H?.expiresAt)<=v)return;await Y(),V()}catch{}})()},N),"unref"in X)X.unref()}let F=await Q();if(!F){let N=`${$}.evicting`,H=h(N,"owner.json"),v=B0(),M2=5000,O2=8;async function d(){await new Promise((L)=>setTimeout(L,Math.floor(Math.random()*4)))}async function j0(){try{let L=await J();return Number(L?.expiresAt)>G()}catch{try{return(await C0($)).mtimeMs+B.ttlMs>G()}catch{return!1}}}async function A(){try{return JSON.parse(await Z0(H,"utf8"))?.ownerId===v}catch{return!1}}async function l0(){await V1(N);try{await $0(H,`${JSON.stringify({ownerId:v,createdAt:G()})}
90
+ `,{encoding:"utf8",mode:384,flag:"wx"})}catch(L){if(L.code==="ENOENT")return!1;throw await N0(),L}return await B.onStep?.("eviction-marker-acquired"),!0}async function N0(){if(await A())await m(N,{recursive:!0,force:!0}).catch(()=>{})}for(let L=0;L<8;L++){if(F=await Q(),F)break;if(await j0())return null;try{if(!await l0()){await d();continue}}catch(V0){if(V0.code!=="EEXIST")throw V0;let H0;try{H0=await C0(N)}catch(x){if(x.code==="ENOENT"){await d();continue}throw x}if(H0.mtimeMs+5000>G())return null;await B.onStep?.("stale-marker-stat");let b0=`${N}.${B0()}`;try{await H1(N,b0)}catch(x){if(x.code==="ENOENT"){await d();continue}throw x}await B.onStep?.("stale-marker-claimed"),await m(b0,{recursive:!0,force:!0}).catch(()=>{}),await d();continue}try{if(await j0())return null;if(!await A())return null;if(await B.onStep?.("stale-lock-confirmed"),!await A())return null;if(await m($,{recursive:!0,force:!0}).catch(()=>{}),!await A())return null;if(F=await Q(),!F)return null;if(!await A())return await m($,{recursive:!0,force:!0}).catch(()=>{}),F=!1,null;break}finally{await N0()}}}if(!F)return null;return V(),{release:async()=>{if(W=!0,X)L1(X),X=null;try{if((await J())?.ownerId!==K)return}catch{return}await m($,{recursive:!0,force:!0}).catch(()=>{})}}}import{createHash as R1,randomUUID as y1}from"node:crypto";import{homedir as T1}from"node:os";import{dirname as E1,join as c}from"node:path";import{setTimeout as S1}from"node:timers/promises";import{randomUUID as O1}from"node:crypto";import{mkdir as U1,rename as _1,rm as P1,writeFile as C1}from"node:fs/promises";import{dirname as I1}from"node:path";async function E(B,Z){await U1(I1(B),{recursive:!0});let $=`${B}.${O1()}.tmp`;await C1($,`${JSON.stringify(Z,null,2)}
91
+ `,{encoding:"utf8",mode:384});try{await _1($,B)}catch(z){throw await P1($,{force:!0}).catch(()=>{}),z}}import{readFile as d1}from"node:fs/promises";var I=x0("refresh"),I0=1e4,A1=50,k0="openai-auth.json",x1="openai-auth-state.json";function k1(){if(process.env.OPENCODE_CONFIG_DIR?.trim())return process.env.OPENCODE_CONFIG_DIR.trim();return c(process.env.XDG_CONFIG_HOME||c(T1(),".config"),"opencode")}function S(){return process.env.OPENCODE_OPENAI_AUTH_FILE?.trim()||c(k1(),k0)}function r(B=S()){let Z=process.env.OPENCODE_OPENAI_AUTH_STATE_FILE?.trim();if(Z)return Z;return w1(B)}function w1(B){return B.endsWith(k0)?c(E1(B),x1):`${B}.state.json`}function M(B){return B.type==="oauth"}function f1(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 $B(B){return B.costZeroing?.enabled!==!1}var m1=[401,403,429],R0={primary:0,secondary:0},h1=!1,G0={primary:5,secondary:10};function j(B){return B!=null&&typeof B==="object"&&!Array.isArray(B)}function y0(B){return{id:typeof B.id==="string"&&B.id.trim()?B.id.trim():y1(),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 T0(B){if(!j(B))return;if(typeof B.message!=="string")return;let Z=Number(B.checkedAt);if(!Number.isFinite(Z))return;let $=Number(B.nextRetryAt),z=Number(B.retryCount);return{message:B.message,checkedAt:Z,nextRetryAt:Number.isFinite($)?$:void 0,retryCount:Number.isFinite(z)?z:void 0,tokenHash:typeof B.tokenHash==="string"?B.tokenHash:void 0}}function p1(B){if(!j(B))return;let Z={};for(let $ of["primary","secondary"]){let z=B[$];if(!j(z))continue;let K=Number(z.usedPercent),G=Number(z.remainingPercent),X=Number(z.checkedAt);if(!Number.isFinite(K)||!Number.isFinite(G)||!Number.isFinite(X))continue;Z[$]={usedPercent:K,remainingPercent:G,checkedAt:X,resetsAt:typeof z.resetsAt==="string"?z.resetsAt:void 0}}return Object.keys(Z).length?Z:void 0}function v1(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(!f1(Z))return null;let z=B.authHeader==="x-api-key"?"x-api-key":"authorization-bearer";return{...y0(B),type:"api",apiKey:$||void 0,baseURL:Z,authHeader:z}}if(B.type!=="oauth")return null;if(typeof B.refresh!=="string"||!B.refresh.trim())return null;return{...y0(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:T0(B.lastRefreshError),lastQuotaRefreshError:T0(B.lastQuotaRefreshError),quota:p1(B.quota)}}function w0(B){if(!j(B)||!Array.isArray(B.accounts))return null;return{version:1,main:{type:"opencode",provider:"openai"},routing:j(B.routing)?B.routing:void 0,fallbackOn:Array.isArray(B.fallbackOn)?B.fallbackOn.filter((Z)=>Number.isInteger(Z)):void 0,refresh:j(B.refresh)?B.refresh:void 0,quota:j(B.quota)?B.quota:void 0,dump:j(B.dump)?B.dump:void 0,costZeroing:j(B.costZeroing)?B.costZeroing:void 0,killswitch:j(B.killswitch)?B.killswitch:void 0,logging:j(B.logging)?B.logging:void 0,cachekeep:j(B.cachekeep)?B.cachekeep:void 0,mainAccountId:typeof B.mainAccountId==="string"?B.mainAccountId:void 0,accounts:B.accounts.map(v1).filter((Z)=>Z!=null)}}async function y(B){try{return{exists:!0,value:JSON.parse(await d1(B,"utf8"))}}catch(Z){if(Z.code==="ENOENT")return{exists:!1,value:null};throw Z}}function O(B){return Object.fromEntries(Object.entries(B).filter(([,Z])=>Z!==void 0))}async function l1(B){let Z;try{Z=(await y(B)).value}catch{return null}if(!j(Z)||!Array.isArray(Z.accounts))return null;let $=new Set;for(let z of Z.accounts)if(j(z)&&typeof z.id==="string")$.add(z.id);return $}function f0(B,Z){if(!j(B))return B;let $=j(Z)?Z:{},z=j($.main)?$.main:void 0,K=j($.accounts)?$.accounts:{},G=j(B.quota)?B.quota:{},X=j(B.refresh)?B.refresh:{},W=z??G,J=z??X,Q=Array.isArray(B.accounts)?B.accounts.map((V)=>{if(!j(V))return V;let F=typeof V.id==="string"&&j(K[V.id])?K[V.id]:{};return{...V,...F}}):void 0;return m0({...B,refresh:O({...X,mainLastRefreshError:J.lastRefreshError,mainRefreshLeaseId:J.refreshLeaseId,mainRefreshLeaseUntil:J.refreshLeaseUntil,mainRefreshLeaseTokenHash:J.refreshLeaseTokenHash}),quota:O({...G,mainQuota:W.quota,mainQuotaCheckedAt:W.quotaCheckedAt,mainQuotaToken:W.quotaToken,mainLastQuotaApiError:W.lastQuotaApiError}),accounts:Q})}async function g1(B=S()){let Z=await y(B);if(!Z.exists)return null;let $=await y(r(B));return w0(f0(Z.value,$.value))}function m0(B){return Object.fromEntries(Object.entries(B).filter(([,Z])=>Z!==void 0))}function u1(B){return O({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 O({apiKey:B.apiKey,lastUsed:B.lastUsed});return O({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 n(B){return Math.max(B?.primary?.checkedAt??0,B?.secondary?.checkedAt??0)}function p(B,Z,$){if($ in Z)B[$]=Z[$];else delete B[$]}function i1(B,Z){return B.access===Z.access&&B.refresh===Z.refresh&&B.expires===Z.expires&&B.lastRefreshedAt===Z.lastRefreshedAt}function s1(B,Z){if(!i1(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 c1(B,Z,$){let z=Z.lastRefreshedAt??0,K=$.lastRefreshedAt??0,G=Z.expires??0,X=$.expires??0,W=K>z?$:z>K?Z:X>G?$:G>X?Z:s1(Z,$);p(B,W,"access"),p(B,W,"refresh"),p(B,W,"expires"),p(B,W,"lastRefreshedAt"),p(B,W,"lastRefreshError")}function n1(B,Z){if(!j(B))return Z;let $=B,z=n($.quota),K=n(Z.quota),G=z>K,X=G?{...$,...Z,quota:$.quota,lastQuotaRefreshError:$.lastQuotaRefreshError}:{...$,...Z};if(!G&&!("lastQuotaRefreshError"in Z))delete X.lastQuotaRefreshError;if(!("lastRefreshError"in Z))delete X.lastRefreshError;if(typeof $.lastUsed==="number"&&(typeof Z.lastUsed!=="number"||$.lastUsed>Z.lastUsed))X.lastUsed=$.lastUsed;return c1(X,$,Z),X}function p0(B){let Z=B.refresh?O({enabled:B.refresh.enabled,intervalMinutes:B.refresh.intervalMinutes,refreshBeforeExpiryMinutes:B.refresh.refreshBeforeExpiryMinutes}):void 0,$=B.quota?O({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 m0({version:1,main:B.main,routing:B.routing,fallbackOn:B.fallbackOn,refresh:Z,quota:$,dump:B.dump,costZeroing:B.costZeroing,killswitch:B.killswitch,logging:B.logging,cachekeep:B.cachekeep,mainAccountId:B.mainAccountId,accounts:B.accounts.map(u1)})}async function K0(B){let Z=Date.now()+I0;while(Date.now()<=Z){let $=await s({name:"save",ttlMs:I0,path:B});if($)return $;let z=Z-Date.now();if(z<=0)break;await S1(Math.min(A1,z))}throw Error(`Timed out acquiring account store lock for ${B}; refusing to overwrite newer account data`)}function v0(B){let Z=Object.fromEntries(B.accounts.map(($)=>[$.id,h0($)]));return{version:1,main:O({quota:B.quota?.mainQuota,quotaCheckedAt:B.quota?.mainQuotaCheckedAt,quotaToken:B.quota?.mainQuotaToken,lastQuotaApiError:B.quota?.mainLastQuotaApiError,lastRefreshError:B.refresh?.mainLastRefreshError,refreshLeaseId:B.refresh?.mainRefreshLeaseId,refreshLeaseUntil:B.refresh?.mainRefreshLeaseUntil,refreshLeaseTokenHash:B.refresh?.mainRefreshLeaseTokenHash}),accounts:Z}}async function XB(B,Z=S()){let $=r(Z),z=await K0(Z);try{let K=await K0($);try{let G=await y(Z),X=await y($),W=(G.exists?w0(f0(G.value,X.value)):null)??r1(),J=B(W)??W,Q={...j(G.value)?G.value:{},...p0(J)};return await E(Z,Q),await E($,v0(J)),J}finally{await K.release()}}finally{await z.release()}}function r1(){return{version:1,main:{type:"opencode",provider:"openai"},accounts:[]}}function a1(B,Z){B.main=B.main??{};let $=typeof B.main.quotaCheckedAt==="number"?B.main.quotaCheckedAt:n(B.main.quota),z=typeof Z.quota?.mainQuotaCheckedAt==="number"?Z.quota.mainQuotaCheckedAt:n(Z.quota?.mainQuota);if($>z)return;B.main.quota=Z.quota?.mainQuota,B.main.quotaCheckedAt=Z.quota?.mainQuotaCheckedAt,B.main.quotaToken=Z.quota?.mainQuotaToken,B.main.lastQuotaApiError=Z.quota?.mainLastQuotaApiError}function o1(B,Z){B.main=B.main??{},B.main.lastRefreshError=Z.refresh?.mainLastRefreshError,B.main.refreshLeaseId=Z.refresh?.mainRefreshLeaseId,B.main.refreshLeaseUntil=Z.refresh?.mainRefreshLeaseUntil,B.main.refreshLeaseTokenHash=Z.refresh?.mainRefreshLeaseTokenHash}function W0(B){if(Array.isArray(B))return B.map(W0);if(!j(B))return B;return Object.fromEntries(Object.entries(B).filter(([,Z])=>Z!==void 0).map(([Z,$])=>[Z,W0($)]))}async function t1(B,Z=S(),$={mainQuota:!0,mainRefresh:!0,accounts:!0}){let z=r(Z),K=await K0(z);try{let G=(await y(z)).value,X=j(G)?{...G,version:1}:{version:1};if($.mainQuota)a1(X,B);if($.mainRefresh)o1(X,B);if($.accounts){let W=$.accounts===!0?null:new Set($.accounts),J=await l1(Z);X.accounts={...j(X.accounts)?X.accounts:{}};for(let Y of B.accounts){if(W&&!W.has(Y.id))continue;if(J&&!J.has(Y.id))continue;X.accounts[Y.id]=n1(X.accounts[Y.id],h0(Y))}if(W){for(let Y of W)if(!B.accounts.some((Q)=>Q.id===Y))delete X.accounts[Y]}if(J){for(let Y of Object.keys(X.accounts))if(!J.has(Y))delete X.accounts[Y]}}await E(z,W0(X))}finally{await K.release()}}function e1(B){return B?.fallbackOn?.length?B.fallbackOn:m1}function GB(B,Z){return e1(Z).includes(B)}function B2(B){let Z=B?.quota?.minimumRemaining||{};return{primary:Z.primary??Z["5h"]??R0.primary,secondary:Z.secondary??Z["1w"]??R0.secondary}}function Y0(B){return B?.quota?.enabled!==!1}function Q0(B){return B?.quota?.failClosedOnUnknownQuota??h1}function d0(B,Z){if(!Y0(Z))return!0;let $=B2(Z);for(let z of["primary","secondary"]){let K=B?.[z];if(!K)return!Q0(Z);if(K.remainingPercent<$[z])return!1}return!0}function Z2(B){return B?.killswitch?.enabled===!0}function E0(B){return{primary:B?.primary??B?.["5h"]??G0.primary,secondary:B?.secondary??B?.["1w"]??G0.secondary}}function $2(B,Z){if(!B?.killswitch)return G0;if(Z&&B.killswitch.accounts?.[Z])return E0(B.killswitch.accounts[Z]);return E0(B.killswitch.main)}function KB(B,Z,$){if(!Z2(Z))return!0;let z=$2(Z,$),K=!1;for(let G of["primary","secondary"]){let X=B?.[G];if(!X){K=!0;continue}if(X.remainingPercent<z[G])return!1}if(K)return!Q0(Z);return!0}function WB(B,Z,$){let z=[],K=[B,...Z.map((X)=>X.quota)];for(let X of K)for(let W of["primary","secondary"]){let J=X?.[W]?.resetsAt;if(!J)continue;let Y=Date.parse(J);if(Number.isFinite(Y)&&Y>$)z.push(Y)}if(z.length===0)return 300;let G=Math.min(...z);return Math.max(1,Math.ceil((G-$)/1000))}function z2(B){return typeof B.version==="number"&&Array.isArray(B.accounts)}async function YB(B,Z=S()){let $=await s({name:"migrate",ttlMs:30000,path:Z});if(!$)return;try{let z=await y(Z);if(z.exists&&j(z.value)){if(z2(z.value))return}if(!B)return;let K={version:1,main:{type:"opencode",provider:"openai"},accounts:[]};if(B.access){let W=T({id_token:"",access_token:B.access,refresh_token:B.refresh});if(W)K.mainAccountId=W}let X={...z.exists&&j(z.value)?z.value:{},...p0(K)};await E(Z,X),await E(r(Z),v0(K))}finally{await $.release()}}function X2(B){return B?.refresh?.enabled!==!1}function G2(B){return(B?.refresh?.refreshBeforeExpiryMinutes??240)*60000}function K2(B){return Math.floor(Math.random()*(B+1))}function R(B,Z,$){return!B.access||!B.expires||B.expires-$<=G2(Z)}function W2(B,Z){return Boolean(B.access&&typeof B.expires==="number"&&B.expires>Z)}function Y2(B,Z){return Boolean(B.mainAccountId&&Z.accountId&&Z.accountId===B.mainAccountId)}function b(B,Z){let $=B.accounts.findIndex((z)=>z.id===Z.id);if($!==-1)B.accounts[$]=Z}function z0(B){return B instanceof Error?B.message:String(B)}function J0(B,Z,$){B.lastRefreshError=L0({error:Z,now:$,refreshToken:B.refresh,previous:B.lastRefreshError})}function X0(B,Z,$){if(B.lastQuotaRefreshError=D0({error:Z,now:$,previous:B.lastQuotaRefreshError}),Z?.isRefreshError===!0)J0(B,Z,$)}function J2(B){return`fallback-oauth-refresh-${R1("sha256").update(B).digest("base64url").slice(0,16)}`}function S0(B,Z){if(!B)return!1;if(!B.resetsAt)return!0;let $=Date.parse(B.resetsAt);return Number.isFinite($)?$>Z:!0}function Q2(B,Z){if(!B)return!1;return S0(B[u],Z)||S0(B[i],Z)}function j2(B,Z,$){if(!B)return!1;let z=Z?.quota?.checkIntervalMinutes??5,K=Math.max(1,z)*60000,G=Math.max(B[u]?.checkedAt??0,B[i]?.checkedAt??0);return $-G<K}function A0(B,Z,$){return!j2(B.quota,Z,$)}function N2(B,Z,$,z){return o($)&&d0(B.quota,Z)&&Q2(B.quota,z)}function V2(B){let Z=B?.quota?.checkIntervalMinutes??5;return Math.max(1,Z)*60000}var H2=60000,b2=60000,F2=600000,L2=1e4,D2=100;var JB=globalThis.setTimeout.bind(globalThis),QB=globalThis.clearTimeout.bind(globalThis);class q2{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??S(),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[u]?.checkedAt??0,B.quota[i]?.checkedAt??0);if($<=0)return;let z=this.quotaManager.getFallback(B.id,B.access);if(z&&z.checkedAt>=$)return;this.quotaManager.setFallback(B.id,{quota:B.quota,refreshAfter:$+V2(Z),checkedAt:$},B.access)}async load(){return g1(this.configPath)}async save(B,Z){await t1(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(()=>{})},H2+K2(b2)),"unref"in this.refreshTimer)this.refreshTimer.unref()}}stopBackgroundRefresh(){if(this.refreshTimer)clearInterval(this.refreshTimer);if(this.quotaTimer)clearInterval(this.quotaTimer);this.refreshTimer=null,this.quotaTimer=null}async getUsableFallbackAccounts(B){let Z=B!==void 0?B:await this.load();if(!Z)return[];let $=[],z=!1;for(let K of Z.accounts){if(K.enabled===!1||!M(K))continue;if(Y2(Z,K))continue;let G=!1,X=K;try{if(R(X,Z,this.now())){let W=X.lastRefreshError;if(W&&U(W,X.refresh,this.now()))throw G=!0,Error(l(W,this.now()));try{X=await this.refreshAccount(X,Z),z=!0}catch(J){G=!0;let Y=Z.accounts.find((Q)=>Q.id===K.id&&M(Q));if(Y&&!U(Y.lastRefreshError,Y.refresh,this.now()))J0(Y,J,this.now()),b(Z,Y),z=!0;throw J}}if(this.seedFallbackQuota(X,Z),this.accountPassesQuotaPolicy(this.quotaPolicyAccount(X),Z))$.push(X)}catch(W){let J=W2(X,this.now());if(G){if(!J)continue}else if(!J)continue;if(N2(X,Z,W,this.now()))I.debug("fallback quota using cached quota after refresh error",{pid:process.pid,accountId:X.id,error:z0(W)}),$.push(X);else if(!Q0(Z))$.push(X)}}if(z)await this.save(Z);return $}async markUsed(B){let Z=await this.load();if(!Z)return;let $=Z.accounts.find((z)=>z.id===B.id);if(!$)return;$.lastUsed=this.now(),await this.save(Z)}accountPassesQuotaPolicy(B,Z){return d0(B.quota,Z)}quotaPolicyAccount(B){if(!this.quotaManager)return B;let Z=this.quotaManager.getFallback(B.id,B.access)?.quota;return Z?{...B,quota:Z}:B}async refreshDueAccounts(){let B=await this.load();if(!B||!X2(B))return;let Z=!1;for(let $ of B.accounts){if($.enabled===!1||!M($))continue;if(!R($,B,this.now()))continue;if(U($.lastRefreshError,$.refresh,this.now()))continue;try{I.debug("fallback oauth background due",{pid:process.pid,accountId:$.id,expiresInMs:$.expires?$.expires-this.now():void 0}),await this.refreshAccount($,B),Z=!0}catch(z){I.warn("fallback oauth background failed",{pid:process.pid,accountId:$.id,error:z0(z)}),J0($,z,this.now()),b(B,$),Z=!0}}if(Z)await this.save(B)}async refreshQuotaForDueAccounts(){let B=await this.load();if(!B||!Y0(B))return;if(!this.options.fetchQuotaFn)return;let Z=!1;for(let $ of B.accounts){if($.enabled===!1||!M($))continue;let z=$;try{if(R(z,B,this.now())){if(U(z.lastRefreshError,z.refresh,this.now()))continue;z=await this.refreshAccount(z,B),Z=!0}if(q0(z.lastQuotaRefreshError,this.now()))continue;if(this.seedFallbackQuota(z,B),!(this.quotaManager?this.quotaManager.isFallbackStale(z.id,z.access):A0(z,B,this.now())))continue;await this.refreshAccountQuota(z,B),Z=!0}catch(K){X0($,K,this.now()),b(B,$),Z=!0}}if(Z)await this.save(B),this.onFallbackStorageChanged?.()}async refreshQuotaForAllAccounts(B={}){let Z=await this.load(),$=[];if(!Z||!Y0(Z))return{storage:Z,errors:$};if(!this.options.fetchQuotaFn)return{storage:Z,errors:$};let z=B.force??!1,K=!1;for(let G of Z.accounts){if(G.enabled===!1||!M(G))continue;let X=G;try{if(R(X,Z,this.now())){let W=X.lastRefreshError;if(W&&U(W,X.refresh,this.now()))throw Error(l(W,this.now()));X=await this.refreshAccount(X,Z),K=!0}if(!z&&!A0(X,Z,this.now())){if(X.lastQuotaRefreshError)X.lastQuotaRefreshError=void 0,b(Z,X),K=!0;continue}await this.refreshAccountQuota(X,Z),K=!0}catch(W){X0(G,W,this.now()),b(Z,G),K=!0,$.push({accountId:G.id,message:z0(W)})}}if(K)await this.save(Z);return{storage:Z,errors:$}}async refreshAccount(B,Z,$={}){let z=this.refreshPromises.get(B.id);if(z){let X=await z;return b(Z,X),X}let K=this.refreshAccountNow(B,Z,$).finally(()=>{this.refreshPromises.delete(B.id)});this.refreshPromises.set(B.id,K);let G=await K;return b(Z,G),G}async waitForConcurrentFallbackRefresh(B,Z,$,z){let K=Date.now()+L2;while(Date.now()<K){await new Promise((Y)=>setTimeout(Y,D2));let G=await this.load(),X=G?.accounts.find((Y)=>Y.id===B.id&&M(Y));if(!X)continue;if((X.access!==$.access||X.refresh!==$.refresh||(X.expires??0)>($.expires??0)+60000)&&(z.force||!R(X,G,this.now())))return b(Z,X),I.debug("fallback oauth joined concurrent refresh",{pid:process.pid,accountId:X.id,expiresInMs:X.expires?X.expires-this.now():void 0}),X;let J=X.lastRefreshError;if(J&&U(J,X.refresh,this.now()))throw b(Z,X),Error(l(J,this.now()))}return null}async refreshAccountNow(B,Z,$){let z=await this.load(),K=z?.accounts.find((W)=>W.id===B.id&&M(W));if(K&&!$.force&&!R(K,z,this.now()))return b(Z,K),K;let G=K??B,X=await s({name:J2(G.id),ttlMs:F2,path:this.configPath,now:this.now,renew:!0});if(!X){I.debug("fallback oauth refresh skipped file lock",{pid:process.pid,accountId:G.id});let W=await this.waitForConcurrentFallbackRefresh(B,Z,G,$);if(W)return W;throw Error("Fallback OAuth refresh is already in progress")}try{if(z=await this.load(),K=z?.accounts.find((Y)=>Y.id===B.id&&M(Y)),K&&!$.force&&!R(K,z,this.now()))return b(Z,K),K;G=K??G;let W=this.options.refreshFn??(async()=>{throw Error("No refreshFn injected into FallbackAccountManager")});I.debug("fallback oauth refresh request start",{pid:process.pid,accountId:G.id,force:$.force===!0,expiresInMs:G.expires?G.expires-this.now():void 0});let J=await W({refreshToken:G.refresh,fetchImpl:this.fetchImpl,now:this.now});return G.access=J.access,G.refresh=J.refresh,G.expires=J.expires,G.lastRefreshedAt=J.expires-J.expiresIn*1000,G.lastRefreshError=void 0,b(Z,G),await this.save(Z),I.debug("fallback oauth refresh succeeded",{pid:process.pid,accountId:G.id,expiresInMs:G.expires?G.expires-this.now():void 0}),G}finally{await X.release()}}async refreshAccountQuota(B,Z){let $=B;if(!$.access)throw Error(`Fallback account ${B.id} has no access token`);if(!this.options.fetchQuotaFn)throw Error("No fetchQuotaFn injected — wham/usage supplement is disabled");let z=this.options.fetchQuotaFn??(async()=>{throw Error("No fetchQuotaFn injected — wham/usage supplement is disabled")}),K=(G)=>this.quotaManager?this.quotaManager.refreshFallback($.id,G):z({accessToken:G,fetchImpl:this.fetchImpl,now:this.now});try{if(!$.access)throw Error(`Fallback account ${B.id} has no access token`);let G=await K($.access);$.quota=G,$.lastQuotaRefreshError=void 0,b(Z,$),await this.save(Z)}catch(G){throw X0(B,G,this.now()),b(Z,B),G}}}
92
+ export{F0 as g,L0 as h,U as i,l as j,D0 as k,q0 as l,_0 as m,P0 as n,B1 as o,O0 as p,U0 as q,T as r,Z1 as s,q as t,G1 as u,K1 as v,W1 as w,Y1 as x,T2 as y,E2 as z,x2 as A,k2 as B,s as C,S as D,M as E,$B as F,G0 as G,g1 as H,XB as I,GB as J,Z2 as K,KB as L,WB as M,YB as N,q2 as O};