@cortexkit/opencode-openai-auth 0.7.1 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +9 -5
- package/dist/{index-9jpc8yct.js → index-02h7g5f9.js} +1 -1
- package/dist/index-2xppkvkx.js +2 -0
- package/dist/index-3w4vmckx.js +2 -0
- package/dist/{index-zxqb5ydj.js → index-507jh8bv.js} +1 -1
- package/dist/{index-zg1x8sty.js → index-944gsj1s.js} +1 -1
- package/dist/index-nshbgkz1.js +198 -0
- package/dist/{index-87145jkw.js → index-xyg86jgt.js} +1 -1
- package/dist/index.d.ts +381 -35
- package/dist/index.js +66 -161
- package/dist/protocol-Cv9ZmU0p.d.ts +24 -0
- package/dist/quota-normalize-wap0rne8.js +1 -0
- package/dist/rpc/port-file.d.ts +11 -9
- package/dist/rpc/port-file.js +1 -1
- package/dist/rpc/protocol.d.ts +2 -21
- package/dist/rpc/rpc-client.d.ts +6 -4
- package/dist/rpc/rpc-client.js +1 -1
- package/dist/rpc/rpc-dir.d.ts +7 -5
- package/dist/rpc/rpc-dir.js +1 -1
- package/dist/sidebar-state.d.ts +84 -83
- package/dist/sidebar-state.js +1 -1
- package/dist/{token-bvp0y166.js → token-jdvpwk60.js} +1 -1
- package/dist/token-util-zzm7paz9.js +1 -0
- package/dist/tui-preferences.d.ts +27 -26
- package/dist/tui-preferences.js +1 -1
- package/dist/tui.d.ts +18 -17
- package/package.json +10 -17
- package/src/tui/entry.mjs +2 -2
- package/src/tui-compiled/{core/account-paths.ts → raw/core-account-paths.ts} +29 -18
- package/src/tui-compiled/raw/logger.ts +53 -0
- package/src/tui-compiled/{rpc/port-file.ts → raw/rpc-port-file.ts} +1 -1
- package/src/tui-compiled/raw/rpc-protocol.ts +12 -0
- package/src/{rpc/rpc-client.ts → tui-compiled/raw/rpc-rpc-client.ts} +2 -2
- package/src/{sidebar-state.ts → tui-compiled/raw/sidebar-state.ts} +2 -2
- package/src/{tui/command-dialogs.tsx → tui-compiled/raw/tui-command-dialogs.tsx} +5 -5
- package/src/{tui.tsx → tui-compiled/raw/tui.tsx} +11 -10
- package/src/{core/account-paths.ts → tui-compiled/runtime/core-account-paths.ts} +29 -18
- package/src/tui-compiled/runtime/logger.ts +53 -0
- package/src/{rpc/port-file.ts → tui-compiled/runtime/rpc-port-file.ts} +1 -1
- package/src/tui-compiled/runtime/rpc-protocol.ts +12 -0
- package/src/tui-compiled/{rpc/rpc-client.ts → runtime/rpc-rpc-client.ts} +2 -2
- package/src/tui-compiled/{sidebar-state.ts → runtime/sidebar-state.ts} +2 -2
- package/src/tui-compiled/{tui/command-dialogs.tsx → runtime/tui-command-dialogs.tsx} +3 -4
- package/src/tui-compiled/{tui.tsx → runtime/tui.tsx} +10 -10
- package/src/tui-compiled/shared/internal.ts +6 -0
- package/src/{logger.ts → tui-compiled/shared/logger.ts} +82 -21
- package/src/tui-compiled/shared/paths.ts +33 -0
- package/src/{core → tui-compiled/shared}/refresh-file-lock.ts +7 -4
- package/dist/cli.d.ts +0 -2
- package/dist/cli.js +0 -15
- package/dist/codex-http.d.ts +0 -3
- package/dist/commands.d.ts +0 -88
- package/dist/config.d.ts +0 -47
- package/dist/core/account-paths.d.ts +0 -25
- package/dist/core/accounts.d.ts +0 -330
- package/dist/core/atomic-write.d.ts +0 -1
- package/dist/core/background-quota-refresh.d.ts +0 -46
- package/dist/core/backoff.d.ts +0 -53
- package/dist/core/cachekeep.d.ts +0 -118
- package/dist/core/oauth.d.ts +0 -138
- package/dist/core/provider.d.ts +0 -70
- package/dist/core/quota-manager.d.ts +0 -192
- package/dist/core/refresh-all-quota.d.ts +0 -86
- package/dist/core/refresh-file-lock.d.ts +0 -12
- package/dist/core/reset-credits.d.ts +0 -116
- package/dist/core/sticky-routing.d.ts +0 -43
- package/dist/dump.d.ts +0 -20
- package/dist/hosted-web-search.d.ts +0 -5
- package/dist/index-8f1200qx.js +0 -6
- package/dist/index-nrvjr97q.js +0 -3
- package/dist/index-qaggaze1.js +0 -2
- package/dist/index-sdcpzbnk.js +0 -2
- package/dist/index-zf3axndm.js +0 -89
- package/dist/logger.d.ts +0 -22
- package/dist/model-costs.d.ts +0 -29
- package/dist/prompt-context.d.ts +0 -19
- package/dist/quota-normalize-dvwtmy7f.js +0 -1
- package/dist/quota-normalize.d.ts +0 -43
- package/dist/raw-ws-bun.d.ts +0 -40
- package/dist/raw-ws-node.d.ts +0 -37
- package/dist/raw-ws-upgrade.d.ts +0 -2
- package/dist/raw-ws.d.ts +0 -3
- package/dist/response-stream-error.d.ts +0 -12
- package/dist/rpc/notifications.d.ts +0 -5
- package/dist/rpc/rpc-server.d.ts +0 -17
- package/dist/token-util-jcj7k7pa.js +0 -1
- package/dist/tui/command-dialogs.d.ts +0 -21
- package/dist/util/error.d.ts +0 -1
- package/dist/util/open-url.d.ts +0 -6
- package/dist/util/proxy-env.d.ts +0 -4
- package/dist/util/record.d.ts +0 -1
- package/dist/util/stable-json.d.ts +0 -1
- package/dist/util/uuid-v7.d.ts +0 -1
- package/dist/version.d.ts +0 -1
- package/dist/ws-pool.d.ts +0 -57
- package/dist/ws.d.ts +0 -53
- package/src/rpc/notifications.ts +0 -54
- package/src/rpc/protocol.ts +0 -33
- package/src/rpc/rpc-server.ts +0 -172
- package/src/tui-compiled/core/refresh-file-lock.ts +0 -381
- package/src/tui-compiled/logger.ts +0 -196
- package/src/tui-compiled/rpc/protocol.ts +0 -33
- package/src/util/error.ts +0 -9
- package/src/util/open-url.ts +0 -30
- package/src/util/proxy-env.ts +0 -42
- package/src/util/record.ts +0 -3
- package/src/util/stable-json.ts +0 -15
- package/src/util/uuid-v7.ts +0 -18
- /package/src/{rpc/rpc-dir.ts → tui-compiled/raw/rpc-rpc-dir.ts} +0 -0
- /package/src/tui-compiled/{tui-preferences.ts → raw/tui-preferences.ts} +0 -0
- /package/src/tui-compiled/{rpc/rpc-dir.ts → runtime/rpc-rpc-dir.ts} +0 -0
- /package/src/{tui-preferences.ts → tui-compiled/runtime/tui-preferences.ts} +0 -0
- /package/src/tui-compiled/{util → shared/util}/error.ts +0 -0
- /package/src/tui-compiled/{util → shared/util}/open-url.ts +0 -0
package/README.md
CHANGED
|
@@ -30,7 +30,7 @@ Restart OpenCode after changing plugin config, then authenticate:
|
|
|
30
30
|
- Per-turn quota tracking (5-hour + weekly windows) on both transports, with a sidebar readout and an explicit all-accounts refresh.
|
|
31
31
|
- Idle prompt-cache keep-warm, with an optional subagent mode and main-only sustain mode.
|
|
32
32
|
- Leveled, secret-redacting, rotating log file.
|
|
33
|
-
- Interactive in-TUI control surfaces for every command,
|
|
33
|
+
- Interactive in-TUI control surfaces for every command, including fallback account management and headless device-code authentication.
|
|
34
34
|
- Optional OpenAI Responses WebSocket transport (HTTP is the default).
|
|
35
35
|
|
|
36
36
|
## Commands
|
|
@@ -48,14 +48,18 @@ Each opens an interactive dialog in the TUI. Commands with listed arguments also
|
|
|
48
48
|
| `/openai-logging` | `<level>` | Set log level live. |
|
|
49
49
|
| `/openai-dump` | `on` · `off` | Toggle transport request dumps. |
|
|
50
50
|
|
|
51
|
-
|
|
51
|
+
Account management (fallback accounts; the main account comes from `/login openai`):
|
|
52
52
|
|
|
53
53
|
```text
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
54
|
+
/openai-account add [--headless] [label]
|
|
55
|
+
/openai-account
|
|
56
|
+
/openai-account remove <id>
|
|
57
57
|
```
|
|
58
58
|
|
|
59
|
+
All account operations can also be performed interactively via the `/openai-account` TUI dialog.
|
|
60
|
+
|
|
61
|
+
On a headless machine, where the slash commands are out of reach, `opencode auth login` offers the same account actions — add, re-authenticate the main account, force a quota check, diagnose and repair the stored credentials, or delete every fallback. It prints `Failed to authorize` on return even when the action succeeded, because the menu writes its own changes and reports none of them as a sign-in; confirm with `/openai-account`.
|
|
62
|
+
|
|
59
63
|
## Configuration
|
|
60
64
|
|
|
61
65
|
Settings resolve as environment variable → config file (`~/.config/opencode/openai-auth.json`) → default.
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Ta as Z,Va as W}from"./index-507jh8bv.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,2 @@
|
|
|
1
|
+
import{Q as d,ia as l}from"./index-nshbgkz1.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
|
+
export{Jj as c,Zj as d,b as e,Uj as f,R as g,T as h,Q as i,x as j,wj as k,Pj as l,f as m,s as n,Fj as o,_ as p,Rj as q,mj as r,n as s,W as t,gj as u,dj as v,lj as w,rj as x,uj as y,cj as z,oj as A,aj as B,ij as C,sj as D,nj as E};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{Q as _}from"./index-nshbgkz1.js";import{chmod as L,mkdir as M,readdir as W,readFile as $,rename as R,rmdir as S,unlink as X,writeFile as U}from"node:fs/promises";import{join as N,resolve as Y}from"node:path";var A=_("rpc");function E(q){try{return process.kill(q,0),!0}catch(H){return H.code==="EPERM"}}function C(q){return/^(?:openai-auth-)?[0-9a-f]{16}$/.test(q)}function O(q){return q!==null&&typeof q==="object"&&!Array.isArray(q)&&typeof q.pid==="number"&&Number.isFinite(q.pid)&&typeof q.port==="number"&&Number.isFinite(q.port)}async function Z(q){A.debug("rpc corrupt port file",{pid:process.pid,portFile:q}),await X(q).catch(()=>{})}async function w(q,H,I={}){let J=async()=>{if(await M(q,{recursive:!0,mode:I.secureDir?448:void 0}),I.secureDir)await L(q,448);await I.beforeWrite?.();let z={...H,startedAt:Date.now()},K=N(q,`port-${H.pid}.json`),B=`${K}.${process.pid}.tmp`;return await U(B,JSON.stringify(z),{encoding:"utf8",mode:384}),await R(B,K),K};try{return await J()}catch(z){if(z.code==="ENOENT")return await J();throw z}}async function x(q,H){let I;try{I=await W(q,{withFileTypes:!0})}catch(z){if(z.code==="ENOENT")return;throw z}let J=Y(H);for(let z of I){if(!z.isDirectory()||!C(z.name))continue;let K=N(q,z.name),B;try{B=await W(K)}catch(G){if(G.code==="ENOENT")continue;throw G}for(let G of B){if(!G.startsWith("port-")||!G.endsWith(".json"))continue;let Q=N(K,G),T;try{T=await $(Q,"utf8")}catch{continue}if(T===void 0)continue;let V;try{V=JSON.parse(T)}catch{await Z(Q);continue}if(!O(V)){await Z(Q);continue}if(!E(V.pid))await X(Q).catch(()=>{})}if(Y(K)!==J)await S(K).catch(()=>{})}}async function y(q,H){let I;try{I=await W(q)}catch{return null}let J=[];for(let B of I){if(!B.startsWith("port-")||!B.endsWith(".json"))continue;try{let G=JSON.parse(await $(N(q,B),"utf8"));if(Number.isFinite(G.port))if(E(G.pid))J.push(G);else X(N(q,B)).catch(()=>{})}catch{}}if(J.length===0)return null;let z=H!==void 0&&H>=1?J.filter((B)=>B.pid===H):[];return(z.length>0?z:J).sort((B,G)=>G.startedAt-B.startedAt)[0]??null}
|
|
2
|
+
export{w as F,x as G,y as H};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import{createRequire as s}from"node:module";var j=Object.create;var{getPrototypeOf:k,defineProperty:f,getOwnPropertyNames:l}=Object;var m=Object.prototype.hasOwnProperty;function n(a){return this[a]}var o,p,t=(a,b,c)=>{var g=a!=null&&typeof a==="object";if(g){var h=b?o??=new WeakMap:p??=new WeakMap,i=h.get(a);if(i)return i}c=a!=null?j(k(a)):{};let d=b||!a||!a.__esModule?f(c,"default",{value:a,enumerable:!0}):c;for(let e of l(a))if(!m.call(d,e))f(d,e,{get:n.bind(a,e),enumerable:!0});if(g)h.set(a,d);return d};var u=(a,b)=>()=>(b||a((b={exports:{}}).exports,b),b.exports);var q=(a)=>a;function r(a,b){this[a]=q.bind(null,b)}var v=(a,b)=>{for(var c in b)f(a,c,{get:b[c],enumerable:!0,configurable:!0,set:r.bind(b,c)})};var x=s(import.meta.url);
|
|
2
|
-
export{t as
|
|
2
|
+
export{t as Sa,u as Ta,v as Ua,x as Va};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createHash as B}from"node:crypto";import{homedir as F,tmpdir as Q}from"node:os";import{dirname as G,join as w,resolve as z}from"node:path";var A="OPENCODE_OPENAI_AUTH_RPC_DIR";function J(k){return B("sha256").update(k).digest("hex").slice(0,16)}function K(){let k=process.env.XDG_STATE_HOME||w(F(),".local","state");return w(k,"cortexkit","openai-auth","rpc")}function L(k){let q=process.env[A]?.trim();if(q)return z(k,q);return w(K(),`openai-auth-${J(k)}`)}async function T(k){let q=process.env[A]?.trim();if(q)return{dir:z(k,q),secureDir:!1};let x=L(k);return{dir:x,secureDir:!0,sweepRoot:G(x)}}export{Q as
|
|
1
|
+
import{createHash as B}from"node:crypto";import{homedir as F,tmpdir as Q}from"node:os";import{dirname as G,join as w,resolve as z}from"node:path";var A="OPENCODE_OPENAI_AUTH_RPC_DIR";function J(k){return B("sha256").update(k).digest("hex").slice(0,16)}function K(){let k=process.env.XDG_STATE_HOME||w(F(),".local","state");return w(k,"cortexkit","openai-auth","rpc")}function L(k){let q=process.env[A]?.trim();if(q)return z(k,q);return w(K(),`openai-auth-${J(k)}`)}async function T(k){let q=process.env[A]?.trim();if(q)return{dir:z(k,q),secureDir:!1};let x=L(k);return{dir:x,secureDir:!0,sweepRoot:G(x)}}export{Q as Ka,L as La,T as Ma};
|
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
import{Va as W2}from"./index-507jh8bv.js";import{createHash as F1}from"node:crypto";var K1=86400000,M1=300000,b1=3600000,C1=60000,S1=900000,T1=300000;function IZ(Z){return Z instanceof Error?Z.message:String(Z)}function E1(Z){let $=Z?.status;if(typeof $==="number")return $===429||$>=500;if(!(Z instanceof Error))return!1;return Z.name==="AbortError"||Z.name==="TimeoutError"||Z.message.includes("fetch failed")||"code"in Z&&(Z.code==="ECONNRESET"||Z.code==="ECONNREFUSED"||Z.code==="ETIMEDOUT"||Z.code==="UND_ERR_CONNECT_TIMEOUT")}function AZ(Z){let $=IZ(Z),G=Z?.status;if(typeof G==="number")return G===429||G>=500;if(!(Z instanceof Error))return!1;let X=Z.code;return Z.name==="AbortError"||Z.name==="TimeoutError"||$.includes("fetch failed")||X==="ECONNRESET"||X==="ECONNREFUSED"||X==="ETIMEDOUT"||X==="UND_ERR_CONNECT_TIMEOUT"}function V0(Z){return F1("sha256").update(Z).digest("hex")}function N0(Z){let $=V0(Z.refreshToken),X=(Z.previous?.tokenHash===$?Z.previous.retryCount??0:0)+1,W,B=Z.error?.retryAfter;if(typeof B==="number"&&B>0)W=B*1000;else if(E1(Z.error))W=Math.min(b1,M1*2**Math.min(X-1,6));else W=K1;return{message:IZ(Z.error),checkedAt:Z.now,nextRetryAt:Z.now+W,retryCount:X,tokenHash:$}}function I(Z,$,G){if(!Z?.nextRetryAt||Z.nextRetryAt<=G)return!1;if(!$)return!0;return Z.tokenHash===V0($)}function n(Z,$){return`Codex OAuth refresh is backed off for ${Math.max(1,Math.ceil(((Z.nextRetryAt??$)-$)/1000))}s after: ${Z.message}`}function GZ(Z){let G=(Z.previous?.retryCount??0)+1,X,W=Z.error?.retryAfter;if(typeof W==="number"&&W>0)X=W*1000;else if(AZ(Z.error))X=Math.min(S1,C1*2**Math.min(G-1,6));else X=T1;return{message:IZ(Z.error),checkedAt:Z.now,nextRetryAt:Z.now+X,retryCount:G}}function c(Z,$){if(!Z?.nextRetryAt||Z.nextRetryAt<=$)return!1;return!0}function yZ(Z){if(!Z)return;let $=Number(Z);if(Number.isFinite($)&&$>0)return Math.ceil($);let G=Date.parse(Z);if(Number.isFinite(G)){let X=Math.ceil((G-Date.now())/1000);return X>0?X:void 0}return}import{appendFileSync as R1,chmodSync as x1,existsSync as kZ,renameSync as D0,statSync as I1}from"node:fs";var OZ={error:0,warn:1,info:2,debug:3,trace:4},A1=5242880,r,UZ,mZ;function L0(Z){r=Z.file,UZ=Z.level}function y1(Z){if(Z===void 0||Z in OZ)mZ=Z}function f1(){if(r===void 0)return;return(typeof r==="function"?r():r)||void 0}function k1(){if(mZ)return mZ;let Z=typeof UZ==="function"?UZ():UZ;if(Z&&Z in OZ)return Z;return"info"}var m1=/^(authorization|x-api-key|cookie|set-cookie|refresh|access|token)$/i;function w1(Z){if(m1.test(Z))return!0;let $=Z.toLowerCase().replace(/[-_]/g,"");if($==="chatgptaccountid")return!0;if($.includes("apikey"))return!0;if($.endsWith("secret")||$.endsWith("password"))return!0;if($.endsWith("token")&&!$.endsWith("tokens"))return!0;return!1}var U0=/\b(Bearer\s+[\w.-]+|sk-[\w-]+|eyJ[\w.-]+)\b/g;function O0(Z){return hZ(Z,new WeakSet)}function h1(Z){return wZ(Z,new WeakSet)}function wZ(Z,$){if(typeof Z==="string")return Z.replace(U0,"***REDACTED***");if(Array.isArray(Z)){if($.has(Z))return"[Circular]";$.add(Z);let G=Z.map((X)=>wZ(X,$));return $.delete(Z),G}if(Z&&typeof Z==="object"){if($.has(Z))return"[Circular]";$.add(Z);let G={};for(let[X,W]of Object.entries(Z))G[X]=wZ(W,$);return $.delete(Z),G}return Z}function hZ(Z,$){if(typeof Z==="string")return Z.replace(U0,"***REDACTED***");if(Array.isArray(Z)){if($.has(Z))return"[Circular]";$.add(Z);let G=Z.map((X)=>hZ(X,$));return $.delete(Z),G}if(Z&&typeof Z==="object"){if($.has(Z))return"[Circular]";$.add(Z);let G={};for(let[X,W]of Object.entries(Z))G[X]=w1(X)?"***REDACTED***":hZ(W,$);return $.delete(Z),G}return Z}var WZ=[],fZ,v1=3;function vZ(Z){try{x1(Z,384)}catch{}}function p1(Z){try{if(!(kZ(Z)&&I1(Z).size>A1))return;for(let G=v1-1;G>=1;G--)if(kZ(`${Z}.${G}`)){let X=`${Z}.${G+1}`;D0(`${Z}.${G}`,X),vZ(X)}let $=`${Z}.1`;D0(Z,$),vZ($)}catch{}}function BZ(){if(!WZ.length)return;let Z=f1(),$=WZ.join("");if(WZ=[],!Z)return;try{if(p1(Z),kZ(Z))vZ(Z);R1(Z,$,{encoding:"utf8",mode:384})}catch{}}function g1(){if(!fZ)fZ=setTimeout(()=>{fZ=void 0,BZ()},500)}function l1(Z){try{return` ${JSON.stringify(O0(Z))}`}catch{return" [unserializable]"}}function XZ(Z,$,G,X){if(r===void 0)return;if(OZ[$]>OZ[k1()])return;let W=`[${new Date().toISOString()}] ${$.toUpperCase()} [${Z}] ${G}`+(X===void 0?"":l1(X))+`
|
|
2
|
+
`;if(WZ.push(W),WZ.length>=50)BZ();else g1()}function x(Z){return{error:($,G)=>XZ(Z,"error",$,G),warn:($,G)=>XZ(Z,"warn",$,G),info:($,G)=>XZ(Z,"info",$,G),debug:($,G)=>XZ(Z,"debug",$,G),trace:($,G)=>XZ(Z,"trace",$,G)}}import{createServer as d1}from"node:http";import{setTimeout as i1}from"node:timers/promises";var _Z="app_EMoamEEZ73f0CkXaXp7hrann",p="https://auth.openai.com",JZ=1455,u1=3000,s1="cortexkit-opencode-openai-auth";function _0(Z){return`${s1}/${Z}`}var F0="main",n1=`"${F0}" is a reserved account id; choose a different label.`;function K0(Z){let $=new Uint8Array(Z),G=String.fromCharCode(...$);return btoa(G).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function c1(){let $=Array.from(crypto.getRandomValues(new Uint8Array(43))).map((X)=>"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~"[X%66]).join(""),G=K0(await crypto.subtle.digest("SHA-256",new TextEncoder().encode($)));return{verifier:$,challenge:G}}function q0(Z){if(Z.length>16384)return;let $=Z.split(".");if($.length!==3)return;let G=$[1];if(!G||G.length>8192)return;try{return JSON.parse(Buffer.from(G,"base64url").toString())}catch{return}}function P0(Z){let $=Z.chatgpt_account_id;if(typeof $==="string"&&$.length>0)return $;let G=Z["https://api.openai.com/auth"];if(G&&typeof G==="object"&&!Array.isArray(G)&&typeof G.chatgpt_account_id==="string"&&G.chatgpt_account_id.length>0)return G.chatgpt_account_id;let X=Z.organizations;if(Array.isArray(X)){let W=X[0];if(W&&typeof W==="object"&&!Array.isArray(W)&&typeof W.id==="string"&&W.id.length>0)return W.id}return}function PZ(Z){if(Z.id_token){let $=q0(Z.id_token),G=$&&P0($);if(G)return G}if(Z.access_token){let $=q0(Z.access_token);return $?P0($):void 0}return}function r1(Z){return typeof Z==="string"&&Z.toLowerCase()===F0}function pZ(Z){if(r1(Z))throw Error(n1);return Z}function a1(Z,$,G){let X=new URLSearchParams({response_type:"code",client_id:_Z,redirect_uri:Z,scope:"openid profile email offline_access",code_challenge:$.challenge,code_challenge_method:"S256",id_token_add_organizations:"true",codex_cli_simplified_flow:"true",state:G,originator:"opencode"});return`${p}/oauth/authorize?${X.toString()}`}async function o1(Z,$,G){let X=await fetch(`${p}/oauth/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",code:Z,redirect_uri:$,client_id:_Z,code_verifier:G.verifier}).toString()});if(!X.ok)throw Error(`Token exchange failed: ${X.status}`);return await X.json()}function t1(Z){return Z.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}var e1=`<!doctype html>
|
|
3
|
+
<html>
|
|
4
|
+
<head>
|
|
5
|
+
<title>CortexKit OpenAI Auth - Authorization Successful</title>
|
|
6
|
+
<style>
|
|
7
|
+
body {
|
|
8
|
+
font-family:
|
|
9
|
+
system-ui,
|
|
10
|
+
-apple-system,
|
|
11
|
+
sans-serif;
|
|
12
|
+
display: flex;
|
|
13
|
+
justify-content: center;
|
|
14
|
+
align-items: center;
|
|
15
|
+
height: 100vh;
|
|
16
|
+
margin: 0;
|
|
17
|
+
background: #131010;
|
|
18
|
+
color: #f1ecec;
|
|
19
|
+
}
|
|
20
|
+
.container {
|
|
21
|
+
text-align: center;
|
|
22
|
+
padding: 2rem;
|
|
23
|
+
}
|
|
24
|
+
h1 {
|
|
25
|
+
color: #f1ecec;
|
|
26
|
+
margin-bottom: 1rem;
|
|
27
|
+
}
|
|
28
|
+
p {
|
|
29
|
+
color: #b7b1b1;
|
|
30
|
+
}
|
|
31
|
+
</style>
|
|
32
|
+
</head>
|
|
33
|
+
<body>
|
|
34
|
+
<div class="container">
|
|
35
|
+
<h1>Authorization Successful</h1>
|
|
36
|
+
<p>You can close this window and return to OpenCode.</p>
|
|
37
|
+
</div>
|
|
38
|
+
<script>
|
|
39
|
+
setTimeout(() => window.close(), 2000)
|
|
40
|
+
</script>
|
|
41
|
+
</body>
|
|
42
|
+
</html>`,qZ=(Z)=>`<!doctype html>
|
|
43
|
+
<html>
|
|
44
|
+
<head>
|
|
45
|
+
<title>CortexKit OpenAI Auth - Authorization Failed</title>
|
|
46
|
+
<style>
|
|
47
|
+
body {
|
|
48
|
+
font-family:
|
|
49
|
+
system-ui,
|
|
50
|
+
-apple-system,
|
|
51
|
+
sans-serif;
|
|
52
|
+
display: flex;
|
|
53
|
+
justify-content: center;
|
|
54
|
+
align-items: center;
|
|
55
|
+
height: 100vh;
|
|
56
|
+
margin: 0;
|
|
57
|
+
background: #131010;
|
|
58
|
+
color: #f1ecec;
|
|
59
|
+
}
|
|
60
|
+
.container {
|
|
61
|
+
text-align: center;
|
|
62
|
+
padding: 2rem;
|
|
63
|
+
}
|
|
64
|
+
h1 {
|
|
65
|
+
color: #fc533a;
|
|
66
|
+
margin-bottom: 1rem;
|
|
67
|
+
}
|
|
68
|
+
p {
|
|
69
|
+
color: #b7b1b1;
|
|
70
|
+
}
|
|
71
|
+
.error {
|
|
72
|
+
color: #ff917b;
|
|
73
|
+
font-family: monospace;
|
|
74
|
+
margin-top: 1rem;
|
|
75
|
+
padding: 1rem;
|
|
76
|
+
background: #3c140d;
|
|
77
|
+
border-radius: 0.5rem;
|
|
78
|
+
}
|
|
79
|
+
</style>
|
|
80
|
+
</head>
|
|
81
|
+
<body>
|
|
82
|
+
<div class="container">
|
|
83
|
+
<h1>Authorization Failed</h1>
|
|
84
|
+
<p>An error occurred during authorization.</p>
|
|
85
|
+
<div class="error">${t1(Z)}</div>
|
|
86
|
+
</div>
|
|
87
|
+
</body>
|
|
88
|
+
</html>`,zZ,YZ,A=new Map;function h(){return A.size}function g(Z){if(A.delete(Z),h()===0)v()}async function Z2(){let Z=`http://localhost:${JZ}/auth/callback`;if(zZ)return{port:JZ,redirectUri:Z};if(YZ)return YZ;YZ=(async()=>{let $=d1((G,X)=>{let W=new URL(G.url||"/",`http://127.0.0.1:${JZ}`);if(W.pathname==="/auth/callback"){let B=W.searchParams.get("code"),J=W.searchParams.get("state"),Y=W.searchParams.get("error"),z=W.searchParams.get("error_description");if(Y){let Q=z||Y;if(J){let V=A.get(J);if(V)V.reject(Error(Q)),g(J);else if(h()===0)v()}else if(h()===0)v();X.writeHead(200,{"Content-Type":"text/html"}),X.end(qZ(Q));return}if(!J){if(h()===0)v();X.writeHead(400,{"Content-Type":"text/html"}),X.end(qZ("Missing state parameter"));return}if(!B){if(h()===0)v();X.writeHead(400,{"Content-Type":"text/html"}),X.end(qZ("Missing authorization code"));return}let j=A.get(J);if(!j){if(h()===0)v();X.writeHead(400,{"Content-Type":"text/html"}),X.end(qZ("Unknown state — authorization may have expired"));return}g(J),o1(B,Z,j.pkce).then((Q)=>j.resolve(Q)).catch((Q)=>j.reject(Q)),X.writeHead(200,{"Content-Type":"text/html"}),X.end(e1);return}if(W.pathname==="/cancel"){let B=W.searchParams.get("state"),J=B?[B]:[...A.keys()];X.writeHead(200),X.end("Login cancelled");for(let Y of J){let z=A.get(Y);if(!z)continue;z.reject(Error("Login cancelled")),g(Y)}if(h()===0)v();return}X.writeHead(404),X.end("Not found")});return await new Promise((G,X)=>{$.once("error",X),$.listen(JZ,"127.0.0.1",()=>{$.off("error",X),G()})}),zZ=$,{port:JZ,redirectUri:Z}})();try{return await YZ}finally{YZ=void 0}}function v(){if(zZ){let Z=zZ;zZ=void 0,Z.close(()=>{}),Z.closeIdleConnections?.(),setTimeout(()=>{Z.closeAllConnections?.()},25).unref?.()}}function $2(Z,$,G=300000,X){return new Promise((W,B)=>{if(X?.aborted){g($),B(Error("Login cancelled"));return}let J=setTimeout(()=>{if(A.get($))g($),B(Error("OAuth callback timeout — authorization took too long"))},G),Y=()=>{if(clearTimeout(J),A.get($))g($),B(Error("Login cancelled"))};if(X)X.addEventListener("abort",Y);A.set($,{pkce:Z,state:$,resolve:(z)=>{if(clearTimeout(J),X)X.removeEventListener("abort",Y);W(z)},reject:(z)=>{if(clearTimeout(J),X)X.removeEventListener("abort",Y);B(z)}})})}async function G2(Z){let $=await fetch(`${p}/api/accounts/deviceauth/usercode`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":_0(Z)},body:JSON.stringify({client_id:_Z})});if(!$.ok)throw Error("Failed to initiate device authorization");let G=await $.json();return{deviceData:G,url:`${p}/codex/device`,instructions:`Enter code: ${G.user_code}`}}async function X2(Z,$,G){let X=Math.max(parseInt(Z.interval,10)||5,1)*1000,W=typeof Z.expires_in==="number"?Z.expires_in:parseInt(Z.expires_in||"",10),B=!Number.isNaN(W)&&W>0?W*1000:900000,J=Date.now();while(!0){if(G?.aborted)throw Error("Device authorization cancelled");if(Date.now()-J>B)throw Error("Device authorization expired");let Y=await fetch(`${p}/api/accounts/deviceauth/token`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":_0($)},body:JSON.stringify({device_auth_id:Z.device_auth_id,user_code:Z.user_code})});if(Y.ok){let Q=await Y.json(),V=await fetch(`${p}/oauth/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",code:Q.authorization_code,redirect_uri:`${p}/deviceauth/callback`,client_id:_Z,code_verifier:Q.code_verifier}).toString()});if(!V.ok)throw Error(`Token exchange failed: ${V.status}`);return await V.json()}if(Y.status!==403&&Y.status!==404)throw Error(`Device authorization failed: ${Y.status}`);let z=B-(Date.now()-J);if(z<=0)throw Error("Device authorization expired");let j=Math.min(X+u1,z);try{await i1(j,void 0,{signal:G})}catch(Q){if(Q instanceof Error&&Q.name==="AbortError")throw Error("Device authorization cancelled");throw Q}}}function M0(Z,$){let G=-1;if($.accountId)G=Z.findIndex((X)=>X.accountId&&X.accountId===$.accountId);if(G<0)G=Z.findIndex((X)=>X.id===$.id);if(G<0&&$.label&&!$.accountId)G=Z.findIndex((X)=>X.label===$.label);if(G>=0)return Z[G]={...Z[G],...$,addedAt:Z[G]?.addedAt??$.addedAt},G;return Z.push($),Z.length-1}async function b0(Z){let{label:$,headless:G=!1,signal:X,version:W}=Z;if(pZ($),G){let{deviceData:Q,url:V,instructions:L}=await G2(W),H=(async()=>{let D=await X2(Q,W,X),O=Date.now(),_=PZ(D);return{id:pZ($||_||crypto.randomUUID()),label:$||void 0,type:"oauth",access:D.access_token,refresh:D.refresh_token,expires:O+(D.expires_in??3600)*1000,enabled:!0,addedAt:O,lastUsed:O,lastRefreshedAt:O,accountId:_}})();return{url:V,instructions:L,completion:H}}let{redirectUri:B}=await Z2(),J=await c1(),Y=K0(crypto.getRandomValues(new Uint8Array(32)).buffer),z=a1(B,J,Y),j=(async()=>{try{if(X?.aborted)throw Error("Login cancelled");let Q=await $2(J,Y,void 0,X),V=Date.now(),L=PZ(Q);return{id:pZ($||L||crypto.randomUUID()),label:$||void 0,type:"oauth",access:Q.access_token,refresh:Q.refresh_token,expires:V+(Q.expires_in??3600)*1000,enabled:!0,addedAt:V,lastUsed:V,lastRefreshedAt:V,accountId:L}}finally{g(Y)}})();return{url:z,instructions:"Complete authorization in your browser. This window will close automatically.",completion:j}}function a(Z){if(Z instanceof Error)return Z.message;if(typeof Z==="string")return Z;try{return JSON.stringify(Z)}catch{return String(Z)}}var B2=x("quota"),gZ="primary",lZ="secondary",J2="app_EMoamEEZ73f0CkXaXp7hrann",Y2="https://auth.openai.com";async function H4(Z){let $=await Z.fetchImpl(`${Y2}/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:Z.refreshToken,client_id:J2}).toString()});if(!$.ok){let W=yZ($.headers.get("retry-after"));throw Object.assign(Error(`Token refresh failed: ${$.status}`),{status:$.status,retryAfter:W,isRefreshError:!0})}let G=await $.json();if(!G||typeof G.access_token!=="string"||!G.access_token||typeof G.expires_in!=="number")throw Object.assign(Error("Token refresh failed: malformed response"),{status:$.status,isRefreshError:!0});if(G.refresh_token!==void 0&&typeof G.refresh_token!=="string")throw Object.assign(Error("Token refresh failed: malformed response"),{status:$.status,isRefreshError:!0});let X=typeof G.refresh_token==="string"&&G.refresh_token?G.refresh_token:Z.refreshToken;return{access:G.access_token,refresh:X,expires:Z.now()+G.expires_in*1000,expiresIn:G.expires_in}}var z2="https://chatgpt.com/backend-api/wham/usage";async function dZ(Z){let $=Z.logger??B2,G=Z.accountKey??"unknown",X=Date.now();$.debug("wham usage fetch started",{pid:process.pid,accountId:G});try{let W=await Z.fetchImpl(z2,{signal:AbortSignal.timeout(15000),headers:{authorization:`Bearer ${Z.accessToken}`,"chatgpt-account-id":Z.accountId??"","oai-client-platform":"web","oai-client-version":"0","x-openai-target-path":"/backend-api/wham/usage"}});if(!W.ok){let Y=yZ(W.headers.get("retry-after"));throw Object.assign(Error(`wham usage check failed: ${W.status}`),{status:W.status,retryAfter:Y})}let{normalizeWham:B}=await import("./quota-normalize-wap0rne8.js"),J=B(await W.json());return $.debug("wham usage fetch succeeded",{pid:process.pid,accountId:G,status:W.status,elapsedMs:Date.now()-X}),J}catch(W){throw $.warn("wham usage fetch failed",{pid:process.pid,accountId:G,status:typeof W?.status==="number"?W.status:"error",elapsedMs:Date.now()-X,error:a(W)}),W}}import{randomUUID as iZ}from"node:crypto";import{mkdir as C0,readFile as uZ,rename as j2,rm as o,stat as S0,writeFile as FZ}from"node:fs/promises";import{dirname as H2,join as T0}from"node:path";var Q2=globalThis.setTimeout.bind(globalThis),V2=globalThis.clearTimeout.bind(globalThis);function N2(Z){let $=Z?.code;return $==="ENOENT"||$==="EINVAL"||$==="ENOTDIR"}async function t(Z){let $=`${Z.path}.${Z.name}.lock`,G=T0($,"owner.json"),X=iZ(),W=Z.now??Date.now,B=null,J=!1,Y=null,z=`${$}.evicting`,j=T0(z,"owner.json"),Q=iZ(),V=5000,L=8;async function H(){try{return JSON.parse(await uZ($,"utf8"))}catch(U){if(U.code!=="EISDIR")throw U;return JSON.parse(await uZ(G,"utf8"))}}async function D(){await FZ($,`${JSON.stringify({ownerId:X,expiresAt:W()+Z.ttlMs})}
|
|
89
|
+
`,{encoding:"utf8",mode:384})}async function O(){try{return await FZ($,`${JSON.stringify({ownerId:X,expiresAt:W()+Z.ttlMs})}
|
|
90
|
+
`,{encoding:"utf8",mode:384,flag:"wx"}),!0}catch(U){let P=U.code;if(P==="EEXIST"||P==="EISDIR")return!1;if(P==="ENOENT"){await C0(H2($),{recursive:!0});try{return await FZ($,`${JSON.stringify({ownerId:X,expiresAt:W()+Z.ttlMs})}
|
|
91
|
+
`,{encoding:"utf8",mode:384,flag:"wx"}),!0}catch(M){let LZ=M.code;if(LZ==="EEXIST"||LZ==="EISDIR")return!1;throw M}}throw U}}async function _(){await new Promise((U)=>setTimeout(U,Math.floor(Math.random()*4)))}async function m(){try{let U=await H();return Number(U?.expiresAt)>W()}catch{try{return(await S0($)).mtimeMs+Z.ttlMs>W()}catch{return!1}}}async function q(){try{return JSON.parse(await uZ(j,"utf8"))?.ownerId===Q}catch{return!1}}async function T(){if(await q())await o(z,{recursive:!0,force:!0}).catch(()=>{})}async function K(){await C0(z);try{await FZ(j,`${JSON.stringify({ownerId:Q,createdAt:W()})}
|
|
92
|
+
`,{encoding:"utf8",mode:384,flag:"wx"})}catch(U){if(N2(U))return!1;throw await T(),U}if(Z.onStep)await Z.onStep("eviction-marker-acquired");return!0}async function z0(){let U;try{U=await S0(z)}catch(M){if(M.code==="ENOENT")return"missing";throw M}if(U.mtimeMs+V>W())return"fresh";if(Z.onStep)await Z.onStep("stale-marker-stat");let P=`${z}.${iZ()}`;try{await j2(z,P)}catch(M){if(M.code==="ENOENT")return"missing";throw M}if(Z.onStep)await Z.onStep("stale-marker-claimed");return await o(P,{recursive:!0,force:!0}).catch(()=>{}),"recovered"}async function j0(U){try{if(!await K())return!1}catch(P){if(P.code==="EEXIST")return!1;throw P}try{await U()}finally{await T()}return!0}async function P1(){for(let U=0;U<L;U++){if(Z.onStep)await Z.onStep("relinquish-read");let P;try{P=await H()}catch{return}if(P?.ownerId!==X)return;try{await o($,{recursive:!0,force:!0});return}catch{await _()}}}function H0(){if(!Z.renew||J)return;let U=Z.renewIntervalMs??Math.max(1000,Math.floor(Z.ttlMs/3));if(B=Q2(()=>{let P=(async()=>{let M=!J;try{if(!await j0(async()=>{let Q0=await H(),_1=W();if(J||Q0?.ownerId!==X){M=!1;return}if(Number(Q0?.expiresAt)<=_1){M=!1;return}if(Z.onStep)await Z.onStep("renewal-owner-confirmed");if(J){M=!1;return}if(!await q())return;if(Z.onStep)await Z.onStep("renewal-write-fenced");if(J){M=!1;return}if(!await q())return;if(Z.onStep)await Z.onStep("renewal-write-ready");if(await D(),!await q()){M=!1,await P1();return}})&&Z.onStep)await Z.onStep("renewal-marker-unavailable")}catch{}finally{if(Z.onStep)try{await Z.onStep("renewal-finished")}catch{}if(M&&!J)H0()}})();Y=P,P.finally(()=>{if(Y===P)Y=null})},U),"unref"in B)B.unref()}let w=await O();if(!w)for(let U=0;U<L;U++){if(w=await O(),w)break;if(await m())return null;try{if(!await K()){await _();continue}}catch(P){if(P.code!=="EEXIST")throw P;if(await z0()==="fresh")return null;await _();continue}try{if(await m())return null;if(!await q())return null;if(Z.onStep)await Z.onStep("stale-lock-confirmed");if(!await q())return null;if(await o($,{recursive:!0,force:!0}).catch(()=>{}),!await q())return null;if(w=await O(),!w)return null;if(!await q())return await o($,{recursive:!0,force:!0}).catch(()=>{}),w=!1,null;break}finally{await T()}}if(!w)return null;return H0(),{release:async()=>{if(J=!0,B)V2(B),B=null;await Y;for(let U=0;U<L;U++){try{if(await j0(async()=>{if((await H())?.ownerId!==X)return;if(Z.onStep)await Z.onStep("release-owner-confirmed");if(!await q())return;await o($,{recursive:!0,force:!0}).catch(()=>{})}))return;await z0()}catch{return}await _()}}}}import{createHash as D2}from"node:crypto";var L2=globalThis.setTimeout,U2=5;function jZ(Z){let $=Z?.quota?.checkIntervalMinutes??U2;return Math.max(1,$)*60000}function O2(Z){return Z?.quota?.enabled!==!1}function KZ(Z,$){if(!Z?.resetsAt)return!1;let G=Date.parse(Z.resetsAt);return Number.isFinite(G)&&G<=$}function _4(Z,$,G,X,W){if(W!==void 0&&Number.isFinite(W)&&W>G)return W;let B=$===gZ?Z?.primary:$===lZ?Z?.secondary:void 0,J=B?.resetsAt?Date.parse(B.resetsAt):NaN;if(Number.isFinite(J)&&J>G)return J;return G+X}function q2(Z){let $=Z?.quota?.minimumRemaining||{};return{primary:$.primary??$["5h"]??15,secondary:$.secondary??$["1w"]??10}}function E0(Z,$,G){if(!O2($))return G+jZ($);let X=q2($),W=[];for(let B of["primary","secondary"]){let J=Z?.[B];if(!J)continue;if(J.remainingPercent>=X[B])continue;let Y=J.resetsAt?Date.parse(J.resetsAt):Number.NaN;if(!Number.isFinite(Y)||Y<=G)return G+jZ($);W.push(Y)}if(!W.length)return G+jZ($);return Math.min(...W)+60000}function P2(Z){if(!Z?.quota?.mainQuota||!Z.quota.mainQuotaCheckedAt)return null;return{quota:Z.quota.mainQuota,checkedAt:Z.quota.mainQuotaCheckedAt,tokenFingerprint:Z.quota.mainQuotaToken}}function _2(Z){let $=Z?.quota?.refreshEveryNRequests;return typeof $==="number"&&Number.isFinite($)&&$>0?Math.floor($):0}function S(Z){return D2("sha256").update(Z).digest("hex").slice(0,16)}class y{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;configPath;constructor(Z){this.storage=Z.storage,this.fetchImpl=Z.fetchImpl??fetch,this.configPath=Z.configPath,this.now=Z.now??Date.now,this.fetchQuotaFn=Z.fetchQuotaFn,this.onMainQuotaFetched=Z.onMainQuotaFetched,this.onApiError=Z.onApiError,this.seedMainFromStorage(Z.storage),this.seedMainBackoffFromStorage(Z.storage)}getMain(Z){if(Z&&this.main&&this.mainTokenFp&&this.mainTokenFp!==S(Z))this.main=null,this.mainTokenFp=null;return this.main}getFallback(Z,$){let G=this.fallbacks.get(Z)??null;if(!$||!G)return G;if(this.fallbackTokenFps.get(Z)!==S($))return this.fallbacks.delete(Z),this.fallbackTokenFps.delete(Z),null;return G}getAllFallbacks(){return this.fallbacks}setMain(Z,$,G,X=!1){if(!X&&!R0($.quota))return;if(this.mainTokenFp=S(Z),G&&this.mainQuotaAccountId&&this.mainQuotaAccountId!==G)this.clearRateLimited("main");if(G)this.mainQuotaAccountId=G;if(this.main=$,sZ($.quota))this.clearRateLimited("main")}peekMainForPolicy(Z){if(Z&&this.mainQuotaAccountId&&this.mainQuotaAccountId!==Z)return null;return this.main}peekFallbackForPolicy(Z,$){let G=this.fallbacks.get(Z)??null;if($&&G?.accountId&&G.accountId!==$)return null;return G}setFallback(Z,$,G,X=!1,W){if(!X&&!R0($.quota))return;let B=this.fallbacks.get(Z)?.accountId;if(W&&B&&W!==B)this.clearRateLimited(Z);let J=W??B;if(this.fallbacks.set(Z,{...$,accountId:J}),G)this.fallbackTokenFps.set(Z,S(G));else this.fallbackTokenFps.delete(Z);if(sZ($.quota))this.clearRateLimited(Z)}markRateLimited(Z,$){let G=this.rateLimitedUntilMap.get(Z);if(G!==void 0&&G>$)return;this.rateLimitedUntilMap.set(Z,$)}isRateLimited(Z){let $=this.rateLimitedUntilMap.get(Z);return $!==void 0&&this.now()<$}rateLimitedUntil(Z){return this.rateLimitedUntilMap.get(Z)}clearRateLimited(Z){this.rateLimitedUntilMap.delete(Z)}async refreshMain(Z){let $=S(Z);if(this.mainTokenFp&&this.mainTokenFp!==$)this.main=null,this.mainTokenFp=null;if(this.inflightMain&&this.inflightMainFp===$)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=$,this.inflightMain=this._fetchMain(Z),this.inflightMain}async refreshFallback(Z,$){let G=y.fallbackInflightKey(Z,$),X=this.inflightFallbacks.get(G);if(X)return X;if(this.isFallbackBackedOff(Z,$)){let B=this.getFallback(Z,$);if(B)return B.quota;throw Error("Quota API rate-limited — try again later")}let W=this._fetchFallback(Z,$);return this.inflightFallbacks.set(G,W),W}async refreshAllFallbacks(Z){let $=this.now();for(let G of Z){if(G.enabled===!1)continue;if(!G.access)continue;let X=this.getFallback(G.id,G.access);if(X&&$<X.refreshAfter)continue;try{await this.refreshFallback(G.id,G.access)}catch{}}}refreshMainInBackground(Z){let $=S(Z);if(this.inflightMain&&this.inflightMainFp===$)return;if(this.isBackedOff())return;this.refreshMain(Z).catch(()=>{})}isMainStale(){if(!this.main)return!0;return this.now()>=this.main.refreshAfter}isFallbackStale(Z,$){let G=this.getFallback(Z,$);if(!G)return!0;return this.now()>=G.refreshAfter}shouldRefreshOnRequestCount(Z){let $=_2(this.storage);if($<=0)return!1;return Z>0&&Z%$===0}needsRefresh(Z){return this.isMainStale()||this.shouldRefreshOnRequestCount(Z)}updateStorage(Z){this.storage=Z,this.seedMainFromStorage(Z),this.seedMainBackoffFromStorage(Z)}seedMainFromStorage(Z,$){let G=P2(Z);if(!G)return;let X=$?S($):null;if(X&&G.tokenFingerprint&&G.tokenFingerprint!==X)return;let W={quota:G.quota,refreshAfter:E0(G.quota,Z,G.checkedAt),checkedAt:G.checkedAt};if(this.main&&this.main.checkedAt>=W.checkedAt&&(!X||!this.mainTokenFp||this.mainTokenFp===X))return;if(this.main=W,this.mainTokenFp=G.tokenFingerprint??null,Z?.mainAccountId){if(this.mainQuotaAccountId&&this.mainQuotaAccountId!==Z.mainAccountId)this.clearRateLimited("main");this.mainQuotaAccountId=Z.mainAccountId}}seedMainBackoffFromStorage(Z){let $=Z?.quota?.mainLastQuotaApiError;this.mainLastApiError=$&&c($,this.now())?$:void 0}seedFallbacksFromAccounts(Z){let $=jZ(this.storage);for(let G of Z){if(G.enabled===!1)continue;if(!G.quota)continue;let X=Math.max(G.quota.primary?.checkedAt??0,G.quota.secondary?.checkedAt??0);if(X<=0)continue;let W=this.getFallback(G.id,G.access);if(W&&W.checkedAt>=X)continue;this.setFallback(G.id,{quota:G.quota,refreshAfter:X+$,checkedAt:X},G.access,!1,G.accountId)}}isBackedOff(){return c(this.mainLastApiError,this.now())}isFallbackBackedOff(Z,$){if($){if(this.fallbackErrorTokenFps.get(Z)!==S($))return!1}return c(this.fallbackApiErrors.get(Z),this.now())}getLastApiError(){return this.mainLastApiError}static API_CALL_GAP_MS=1000;static fallbackInflightKey(Z,$){return JSON.stringify([Z,S($)])}static quotaLockName(Z){return`opencode-fallback-quota-refresh-${Z.replace(/[^a-zA-Z0-9._-]+/g,"-")||"account"}`}_enqueueApiFetch(Z){let $=async()=>{let X=this.now()-this.lastApiCallAt;if(X<y.API_CALL_GAP_MS)await new Promise((W)=>{let B=L2(W,y.API_CALL_GAP_MS-X);if(typeof B==="object"&&"unref"in B)B.unref()});return this.lastApiCallAt=this.now(),Z()},G=this.apiGate.then($,$);return this.apiGate=G.catch(()=>{}),G}async _fetchMain(Z){let $=S(Z);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 G=await t({name:"opencode-main-quota-refresh",ttlMs:30000,path:this.configPath});if(!G){let X=this.main;if(X&&this.now()<X.refreshAfter)return X.quota;throw Error("Quota refresh is already in progress")}try{let X=this.now(),W=await this._fetchQuota(Z),B=this.now();if(this.mainTokenFp=S(Z),this.main={quota:W,refreshAfter:E0(W,this.storage,B),checkedAt:B},sZ(W))this.clearRateLimited("main");return this.mainLastApiError=void 0,this.onMainQuotaFetched?.(W,B,this.mainTokenFp,X),W}catch(X){throw this._handleMainFetchError(X),X}finally{await G.release()}}finally{if(this.inflightMainFp===$)this.inflightMain=null,this.inflightMainFp=null}})}async _fetchFallback(Z,$){return this._enqueueApiFetch(async()=>{try{if(this.isFallbackBackedOff(Z,$)){let X=this.getFallback(Z,$);if(X)return X.quota;throw Error("Quota API rate-limited — try again later")}let G=await t({name:y.quotaLockName(Z),ttlMs:30000,path:this.configPath});if(!G){let X=this.getFallback(Z,$);if(X&&this.now()<X.refreshAfter)return X.quota;throw Error("Quota refresh is already in progress")}try{let X=await this._fetchQuota($),W=this.now();return this.setFallback(Z,{quota:X,refreshAfter:W+jZ(this.storage),checkedAt:W},$,!0),this.fallbackApiErrors.delete(Z),this.fallbackErrorTokenFps.delete(Z),X}finally{await G.release()}}catch(G){throw this._handleFallbackFetchError(Z,$,G),G}finally{this.inflightFallbacks.delete(y.fallbackInflightKey(Z,$))}})}async _fetchQuota(Z){if(!this.fetchQuotaFn)throw Error("Quota fetch not available — no fetchQuotaFn injected (push-only mode)");return this.fetchQuotaFn({accessToken:Z,fetchImpl:this.fetchImpl,now:this.now})}static isAuthError(Z){return Z?.status===401}_handleMainFetchError(Z){if(y.isAuthError(Z))return;this.mainLastApiError=GZ({error:Z,now:this.now(),previous:this.mainLastApiError}),this.onApiError?.(this.mainLastApiError)}_handleFallbackFetchError(Z,$,G){if(y.isAuthError(G))return;let X=S($),W=this.fallbackErrorTokenFps.get(Z)===X?this.fallbackApiErrors.get(Z):void 0;this.fallbackApiErrors.set(Z,GZ({error:G,now:this.now(),previous:W})),this.fallbackErrorTokenFps.set(Z,X)}}function R0(Z){return Boolean(Z.primary||Z.secondary)}function sZ(Z){let{primary:$,secondary:G}=Z;if(!$&&!G)return!1;if($&&$.usedPercent>=100)return!1;if(G&&G.usedPercent>=100)return!1;return!0}import{createHash as I2,randomUUID as A2}from"node:crypto";import{setTimeout as y2}from"node:timers/promises";import{randomUUID as F2}from"node:crypto";import{mkdir as K2,rename as M2,rm as b2,writeFile as C2}from"node:fs/promises";import{dirname as S2}from"node:path";async function e(Z,$){await K2(S2(Z),{recursive:!0});let G=`${Z}.${F2()}.tmp`;await C2(G,`${JSON.stringify($,null,2)}
|
|
93
|
+
`,{encoding:"utf8",mode:384});try{await M2(G,Z)}catch(X){throw await b2(G,{force:!0}).catch(()=>{}),X}}import{basename as T2,dirname as E2,join as R2}from"node:path";var x0="openai-auth.json",I0="openai-auth-state.json";function x2(Z){return T2(Z)===x0?R2(E2(Z),I0):`${Z}.state.json`}import{readFile as i2}from"node:fs/promises";var l=x("refresh"),MZ=x("accounts"),f2=1e4,k2=15000,nZ=50;function f(Z){return Z.type==="oauth"}function m2(Z){let $=Z?.trim();if(!$)return!1;try{let G=new URL($);return(G.protocol==="http:"||G.protocol==="https:")&&!G.username&&!G.password}catch{return!1}}function h4(Z){return Z.costZeroing?.enabled!==!1}class bZ extends Error{code="ACCOUNT_REMOVED_DURING_REFRESH";constructor(Z){super(`Fallback account ${Z} was removed before refresh`);this.name="AccountRemovedDuringRefreshError"}}var w2=[401,403,429],A0={primary:0,secondary:0},h2=!1,rZ={primary:5,secondary:10};function N(Z){return Z!=null&&typeof Z==="object"&&!Array.isArray(Z)}var v2=new Set(["__proto__","constructor","prototype"]);function E(Z){return Z.length>0&&!v2.has(Z)}function p2(Z){return Z instanceof bZ||N(Z)&&Z.name==="AccountRemovedDuringRefreshError"&&Z.code==="ACCOUNT_REMOVED_DURING_REFRESH"}function y0(Z){return{id:typeof Z.id==="string"&&Z.id.trim()?Z.id.trim():A2(),label:typeof Z.label==="string"?Z.label:void 0,enabled:typeof Z.enabled==="boolean"?Z.enabled:void 0,addedAt:typeof Z.addedAt==="number"?Z.addedAt:void 0,lastUsed:typeof Z.lastUsed==="number"?Z.lastUsed:void 0,accountId:typeof Z.accountId==="string"?Z.accountId:void 0}}function f0(Z){if(!N(Z))return;if(typeof Z.message!=="string")return;let $=Number(Z.checkedAt);if(!Number.isFinite($))return;let G=Number(Z.nextRetryAt),X=Number(Z.retryCount);return{message:Z.message,checkedAt:$,nextRetryAt:Number.isFinite(G)?G:void 0,retryCount:Number.isFinite(X)?X:void 0,tokenHash:typeof Z.tokenHash==="string"?Z.tokenHash:void 0}}function g2(Z){if(!N(Z))return;let $={};for(let G of["primary","secondary"]){let X=Z[G];if(!N(X))continue;let W=Number(X.usedPercent),B=Number(X.remainingPercent),J=Number(X.checkedAt);if(!Number.isFinite(W)||!Number.isFinite(B)||!Number.isFinite(J))continue;let Y=typeof X.windowMinutes==="number"?X.windowMinutes:Number.NaN;$[G]={usedPercent:W,remainingPercent:B,checkedAt:J,resetsAt:typeof X.resetsAt==="string"?X.resetsAt:void 0,...Number.isFinite(Y)&&Y>0?{windowMinutes:Y}:{}}}for(let G of["resetCreditsAvailable","resetCreditsApplicable"]){let X=typeof Z[G]==="number"?Z[G]:Number.NaN;if(Number.isFinite(X)&&X>=0)$[G]=X}return Object.keys($).length?$:void 0}function l2(Z){if(!N(Z))return null;if(Z.type==="api"){let $=typeof Z.baseURL==="string"?Z.baseURL.trim():"",G=typeof Z.apiKey==="string"?Z.apiKey.trim():"";if(!m2($))return null;let X=Z.authHeader==="x-api-key"?"x-api-key":"authorization-bearer";return{...y0(Z),type:"api",apiKey:G||void 0,baseURL:$,authHeader:X}}if(Z.type!=="oauth")return null;if(typeof Z.refresh!=="string"||!Z.refresh.trim())return null;return{...y0(Z),type:"oauth",access:typeof Z.access==="string"?Z.access:void 0,refresh:Z.refresh,expires:typeof Z.expires==="number"?Z.expires:void 0,lastRefreshedAt:typeof Z.lastRefreshedAt==="number"?Z.lastRefreshedAt:void 0,lastRefreshError:f0(Z.lastRefreshError),lastQuotaRefreshError:f0(Z.lastQuotaRefreshError),quota:g2(Z.quota)}}function d2(Z){if(!N(Z))return;let $=Object.create(null);for(let[G,X]of Object.entries(Z)){if(!E(G)||!N(X))continue;let W={};if(N(X.inFlight))W.inFlight={...X.inFlight};if(N(X.lastOutcome)&&typeof X.lastOutcome.code==="string"&&X.lastOutcome.code.length>0&&typeof X.lastOutcome.at==="number"&&Number.isFinite(X.lastOutcome.at))W.lastOutcome={code:X.lastOutcome.code,at:X.lastOutcome.at,...N(X.lastOutcome.previousOutcome)&&typeof X.lastOutcome.previousOutcome.code==="string"&&X.lastOutcome.previousOutcome.code.length>0&&typeof X.lastOutcome.previousOutcome.at==="number"&&Number.isFinite(X.lastOutcome.previousOutcome.at)?{previousOutcome:{code:X.lastOutcome.previousOutcome.code,at:X.lastOutcome.previousOutcome.at}}:{}};if(typeof X.cooldownUntil==="number"&&Number.isFinite(X.cooldownUntil))W.cooldownUntil=X.cooldownUntil;if(Object.keys(W).length>0)$[G]=W}return Object.keys($).length>0?$:void 0}var k0=new Set;function v0(Z){if(Z.length===0)return;let $=JSON.stringify([...Z].sort());if(k0.has($))return;k0.add($),MZ.warn("account load-dropped, preserved on disk",{droppedIds:Z})}function p0(Z){if(!N(Z)||!Array.isArray(Z.accounts))return null;let $=Z.accounts,G=$.map(l2).filter((X)=>X!=null);if(G.length<$.length){let X=new Set;for(let J of $)if(N(J)&&typeof J.id==="string"&&J.id.trim())X.add(J.id.trim());let W=new Set(G.map((J)=>J.id)),B=[];for(let J of X)if(!W.has(J))B.push(J);v0(B)}return{version:1,main:{type:"opencode",provider:"openai"},routing:N(Z.routing)?Z.routing:void 0,fallbackOn:Array.isArray(Z.fallbackOn)?Z.fallbackOn.filter((X)=>Number.isInteger(X)):void 0,refresh:N(Z.refresh)?Z.refresh:void 0,quota:N(Z.quota)?Z.quota:void 0,reset:d2(Z.reset),dump:N(Z.dump)?Z.dump:void 0,costZeroing:N(Z.costZeroing)?Z.costZeroing:void 0,killswitch:N(Z.killswitch)?Z.killswitch:void 0,logging:N(Z.logging)?Z.logging:void 0,cachekeep:N(Z.cachekeep)?Z.cachekeep:void 0,mainAccountId:typeof Z.mainAccountId==="string"?Z.mainAccountId:void 0,accounts:G}}async function i(Z){try{return{exists:!0,value:JSON.parse(await i2(Z,"utf8"))}}catch($){if($.code==="ENOENT")return{exists:!1,value:null};throw $}}function k(Z){return Object.fromEntries(Object.entries(Z).filter(([,$])=>$!==void 0))}async function eZ(Z){let $;try{$=(await i(Z)).value}catch{return null}if(!N($)||!Array.isArray($.accounts))return null;let G=new Set;for(let X of $.accounts){if(!N(X))continue;if(typeof X.id!=="string")continue;let W=X.id.trim();if(!W)continue;G.add(W)}return G}function g0(Z,$){if(!N(Z))return Z;let G=N($)?$:{},X=N(G.main)?G.main:void 0,W=N(G.accounts)?G.accounts:{},B=N(Z.quota)?Z.quota:{},J=N(Z.refresh)?Z.refresh:{},Y=X??B,z=X??J,Q=Array.isArray(Z.accounts)?Z.accounts.map((V)=>{if(!N(V))return V;let L=typeof V.id==="string"&&N(W[V.id])?W[V.id]:{};return{...V,...L}}):void 0;return l0({...Z,refresh:k({...J,mainLastRefreshError:z.lastRefreshError,mainRefreshLeaseId:z.refreshLeaseId,mainRefreshLeaseUntil:z.refreshLeaseUntil,mainRefreshLeaseTokenHash:z.refreshLeaseTokenHash}),quota:k({...B,mainQuota:Y.quota,mainQuotaCheckedAt:Y.quotaCheckedAt,mainQuotaToken:Y.quotaToken,mainLastQuotaApiError:Y.lastQuotaApiError}),accounts:Q})}async function u2(Z){let $=await i(Z.configPath);if(!$.exists)return null;let G=await i(Z.statePath);return p0(g0($.value,G.value))}function l0(Z){return Object.fromEntries(Object.entries(Z).filter(([,$])=>$!==void 0))}function s2(Z){return k({id:Z.id,label:Z.label,type:Z.type,enabled:Z.enabled,addedAt:Z.addedAt,accountId:Z.accountId,baseURL:Z.type==="api"?Z.baseURL:void 0,authHeader:Z.type==="api"?Z.authHeader:void 0})}function d0(Z){if(Z.type==="api")return k({apiKey:Z.apiKey,lastUsed:Z.lastUsed});return k({access:Z.access,refresh:Z.refresh,expires:Z.expires,lastUsed:Z.lastUsed,lastRefreshedAt:Z.lastRefreshedAt,lastRefreshError:Z.lastRefreshError,lastQuotaRefreshError:Z.lastQuotaRefreshError,quota:Z.quota})}function CZ(Z){return Math.max(Z?.primary?.checkedAt??0,Z?.secondary?.checkedAt??0)}function HZ(Z,$,G){if(G in $)Z[G]=$[G];else delete Z[G]}function n2(Z,$){return Z.access===$.access&&Z.refresh===$.refresh&&Z.expires===$.expires&&Z.lastRefreshedAt===$.lastRefreshedAt}function c2(Z,$){if(!n2(Z,$))return $;if(!("lastRefreshError"in $))return Z;if(!("lastRefreshError"in Z))return $;return($.lastRefreshError?.checkedAt??0)>(Z.lastRefreshError?.checkedAt??0)?$:Z}function r2(Z,$,G){let X=$.lastRefreshedAt??0,W=G.lastRefreshedAt??0,B=$.expires??0,J=G.expires??0,Y=W>X?G:X>W?$:J>B?G:B>J?$:c2($,G);HZ(Z,Y,"access"),HZ(Z,Y,"refresh"),HZ(Z,Y,"expires"),HZ(Z,Y,"lastRefreshedAt"),HZ(Z,Y,"lastRefreshError")}function a2(Z,$){if(!N(Z))return $;let G=Z,X=CZ(G.quota),W=CZ($.quota),B=X>W,J=B?{...G,...$,quota:G.quota,lastQuotaRefreshError:G.lastQuotaRefreshError}:{...G,...$};if(!B&&!("lastQuotaRefreshError"in $))delete J.lastQuotaRefreshError;if(!("lastRefreshError"in $))delete J.lastRefreshError;if(typeof G.lastUsed==="number"&&(typeof $.lastUsed!=="number"||G.lastUsed>$.lastUsed))J.lastUsed=G.lastUsed;return r2(J,G,$),J}function i0(Z){let $=Z.refresh?k({enabled:Z.refresh.enabled,intervalMinutes:Z.refresh.intervalMinutes,refreshBeforeExpiryMinutes:Z.refresh.refreshBeforeExpiryMinutes}):void 0,G=Z.quota?k({enabled:Z.quota.enabled,checkIntervalMinutes:Z.quota.checkIntervalMinutes,refreshEveryNRequests:Z.quota.refreshEveryNRequests,minimumRemaining:Z.quota.minimumRemaining,failClosedOnUnknownQuota:Z.quota.failClosedOnUnknownQuota,showToasts:Z.quota.showToasts}):void 0;return l0({version:1,main:Z.main,routing:Z.routing,fallbackOn:Z.fallbackOn,refresh:$,quota:G,reset:Z.reset,dump:Z.dump,costZeroing:Z.costZeroing,killswitch:Z.killswitch,logging:Z.logging,cachekeep:Z.cachekeep,mainAccountId:Z.mainAccountId,accounts:Z.accounts.map(s2)})}async function VZ(Z){let $=Date.now(),G=$+k2,X=0;while(Date.now()<=G){X++;let J=await t({name:"save",ttlMs:f2,path:Z});if(J)return J;let Y=G-Date.now();if(Y<=0)break;await y2(Math.min(nZ+a0(nZ),Y))}let W=Date.now()-$,B=Math.round(W/Math.max(1,X));throw Error(`Timed out after ${W}ms waiting for the account store lock on ${Z} (${X} attempts, ~${B}ms apart; retry interval is ${nZ}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 u0(Z){let $=Object.fromEntries(Z.accounts.map((G)=>[G.id,d0(G)]));return{version:1,main:k({quota:Z.quota?.mainQuota,quotaCheckedAt:Z.quota?.mainQuotaCheckedAt,quotaToken:Z.quota?.mainQuotaToken,lastQuotaApiError:Z.quota?.mainLastQuotaApiError,lastRefreshError:Z.refresh?.mainLastRefreshError,refreshLeaseId:Z.refresh?.mainRefreshLeaseId,refreshLeaseUntil:Z.refresh?.mainRefreshLeaseUntil,refreshLeaseTokenHash:Z.refresh?.mainRefreshLeaseTokenHash}),accounts:$}}function s0(Z){if(!N(Z)||!Array.isArray(Z.accounts))return null;let $=new Set;for(let G of Z.accounts){if(!N(G))continue;if(typeof G.id!=="string")continue;let X=G.id.trim();if(!X)continue;$.add(X)}return $}function o2(Z,$,G,X){if(!N(Z)||!Array.isArray(Z.accounts))return{preservedRawEntries:[],preservedIds:[]};let W=[],B=[];for(let J of $){if(G.has(J))continue;if(X.has(J))continue;let Y=Z.accounts.find((z)=>N(z)&&typeof z.id==="string"&&z.id.trim()===J);if(!Y)continue;W.push(Y),B.push(J)}return{preservedRawEntries:W,preservedIds:B}}function t2(Z){if(!Array.isArray(Z))return[];let $=[];for(let G of Z){if(!N(G))continue;if(typeof G.id!=="string")continue;$.push(G.id)}return $}function e2(Z,$,G){let X=s0(Z);if(X===null)return[];let{preservedRawEntries:W,preservedIds:B}=o2(Z,X,$,G);return v0(B),W}async function ZZ(Z,$,G={}){let{configPath:X,statePath:W}=$,B=await VZ(X);try{let J=await VZ(W);try{let Y=await i(X),z=await i(W),j=(Y.exists?p0(g0(Y.value,z.value)):null)??Z3(),Q=new Set(j.accounts.map((K)=>K.id)),V=s0(Y.value)??new Set,L=Z(j,{rawRosterIds:[...V],loadedRosterIds:[...Q]})??j,H=new Set(G.allowDrop??[]),D=e2(Y.value,Q,H),O=i0(L),_=new Set((Array.isArray(O.accounts)?O.accounts:[]).map((K)=>N(K)&&typeof K.id==="string"?K.id.trim():"").filter(Boolean)),m=D.filter((K)=>{if(!N(K))return!1;if(typeof K.id!=="string")return!1;return!_.has(K.id.trim())}),T={...N(Y.value)?Y.value:{},...O,accounts:[...Array.isArray(O.accounts)?O.accounts:[],...m]};return await e(X,T),await e(W,u0(L)),MZ.debug("account config written",{accountCount:T.accounts.length,accountIds:t2(T.accounts)}),L}finally{await J.release()}}finally{await B.release()}}function Z3(){return{version:1,main:{type:"opencode",provider:"openai"},accounts:[]}}function $3(Z,$){Z.main=Z.main??{};let G=typeof Z.main.quotaCheckedAt==="number"?Z.main.quotaCheckedAt:CZ(Z.main.quota),X=typeof $.quota?.mainQuotaCheckedAt==="number"?$.quota.mainQuotaCheckedAt:CZ($.quota?.mainQuota);if(G>X)return;Z.main.quota=$.quota?.mainQuota,Z.main.quotaCheckedAt=$.quota?.mainQuotaCheckedAt,Z.main.quotaToken=$.quota?.mainQuotaToken,Z.main.lastQuotaApiError=$.quota?.mainLastQuotaApiError}function G3(Z,$){Z.main=Z.main??{},Z.main.lastRefreshError=$.refresh?.mainLastRefreshError,Z.main.refreshLeaseId=$.refresh?.mainRefreshLeaseId,Z.main.refreshLeaseUntil=$.refresh?.mainRefreshLeaseUntil,Z.main.refreshLeaseTokenHash=$.refresh?.mainRefreshLeaseTokenHash}function aZ(Z){if(Array.isArray(Z))return Z.map(aZ);if(!N(Z))return Z;return Object.fromEntries(Object.entries(Z).filter(([,$])=>$!==void 0).map(([$,G])=>[$,aZ(G)]))}async function X3(Z,$,G={mainQuota:!0,mainRefresh:!0,accounts:!0}){let X=$.statePath,W=await VZ(X);try{let B=(await i(X)).value,J=N(B)?{...B,version:1}:{version:1};if(G.mainQuota)$3(J,Z);if(G.mainRefresh)G3(J,Z);if(G.accounts){let Y=G.accounts===!0?null:new Set(G.accounts),z=await eZ($.configPath);J.accounts={...N(J.accounts)?J.accounts:{}};for(let j of Z.accounts){if(Y&&!Y.has(j.id))continue;if(z&&!z.has(j.id))continue;J.accounts[j.id]=a2(J.accounts[j.id],d0(j))}if(Y){for(let j of Y)if(!Z.accounts.some((Q)=>Q.id===j))delete J.accounts[j]}if(z){for(let j of Object.keys(J.accounts))if(!z.has(j))delete J.accounts[j]}}await e(X,aZ(J))}finally{await W.release()}}function W3(Z){return Z?.fallbackOn?.length?Z.fallbackOn:w2}function p4(Z,$){return W3($).includes(Z)}function B3(Z){let $=Z?.quota?.minimumRemaining||{};return{primary:$.primary??$["5h"]??A0.primary,secondary:$.secondary??$["1w"]??A0.secondary}}function oZ(Z){return Z?.quota?.enabled!==!1}function NZ(Z){return Z?.quota?.failClosedOnUnknownQuota??h2}function n0(Z,$,G=Date.now()){if(!oZ($))return!0;if(!Z)return!NZ($);let X=B3($),W=NZ($);for(let B of["primary","secondary"]){let J=Z[B];if(!J)continue;if(KZ(J,G)){if(W)return!1;continue}if(J.remainingPercent<X[B])return!1}return!0}function c0(Z){return Z?.killswitch?.enabled===!0}function m0(Z){return{primary:Z?.primary??Z?.["5h"]??rZ.primary,secondary:Z?.secondary??Z?.["1w"]??rZ.secondary}}function r0(Z,$){if(!Z?.killswitch)return rZ;if($&&Z.killswitch.accounts?.[$])return m0(Z.killswitch.accounts[$]);return m0(Z.killswitch.main)}function g4(Z,$,G,X=Date.now()){if(!c0($))return!0;if(!Z)return!NZ($);let W=r0($,G),B=NZ($);for(let J of["primary","secondary"]){let Y=Z[J];if(!Y)continue;if(KZ(Y,X)){if(B)return!1;continue}if(Y.remainingPercent<W[J])return!1}return!0}function l4(Z,$,G,X){if(!c0(X))return 300;let W=[],B=[{accountId:void 0,quota:Z},...$];for(let{accountId:Y,quota:z}of B){if(!z)continue;let j=r0(X,Y),Q=[],V=!1;for(let L of["primary","secondary"]){let H=z[L];if(!H||KZ(H,G))continue;if(H.remainingPercent>=j[L])continue;let D=H.resetsAt?Date.parse(H.resetsAt):NaN;if(!Number.isFinite(D)||D<=G){V=!0;break}Q.push(D)}if(V||Q.length===0)continue;W.push(Math.max(...Q))}if(W.length===0)return 300;let J=Math.min(...W);return Math.max(1,Math.ceil((J-G)/1000))}function J3(Z){return typeof Z.version==="number"&&Array.isArray(Z.accounts)}async function d4(Z,$){let{configPath:G,statePath:X}=$,W=await VZ(G);try{let B=await VZ(X);try{let J=await i(G);if(J.exists&&N(J.value)){if(J3(J.value))return}if(!Z)return;let Y={version:1,main:{type:"opencode",provider:"openai"},accounts:[]};if(Z.access){let Q=PZ({id_token:"",access_token:Z.access,refresh_token:Z.refresh});if(Q)Y.mainAccountId=Q}let j={...J.exists&&N(J.value)?J.value:{},...i0(Y)};await e(G,j),await e(X,u0(Y))}finally{await B.release()}}finally{await W.release()}}function Y3(Z){return Z?.refresh?.enabled!==!1}function z3(Z){return(Z?.refresh?.refreshBeforeExpiryMinutes??240)*60000}function a0(Z){return Math.floor(Math.random()*(Z+1))}function d(Z,$,G){return!Z.access||!Z.expires||Z.expires-G<=z3($)}function j3(Z,$){return Boolean(Z.access&&typeof Z.expires==="number"&&Z.expires>$)}function H3(Z,$){return Boolean(Z.mainAccountId&&$.accountId&&$.accountId===Z.mainAccountId)}function b(Z,$){let G=Z.accounts.findIndex((X)=>X.id===$.id);if(G!==-1)Z.accounts[G]=$}function QZ(Z){return Z instanceof Error?Z.message:String(Z)}function tZ(Z,$,G){Z.lastRefreshError=N0({error:$,now:G,refreshToken:Z.refresh,previous:Z.lastRefreshError})}function cZ(Z,$,G){if(Z.lastQuotaRefreshError=GZ({error:$,now:G,previous:Z.lastQuotaRefreshError}),$?.isRefreshError===!0)tZ(Z,$,G)}function Q3(Z){return`fallback-oauth-refresh-${I2("sha256").update(Z).digest("base64url").slice(0,16)}`}function w0(Z,$){if(!Z)return!1;if(!Z.resetsAt)return!0;let G=Date.parse(Z.resetsAt);return Number.isFinite(G)?G>$:!0}function V3(Z,$){if(!Z)return!1;return w0(Z.primary,$)||w0(Z.secondary,$)}function N3(Z,$,G){if(!Z)return!1;let X=$?.quota?.checkIntervalMinutes??5,W=Math.max(1,X)*60000,B=Math.max(Z.primary?.checkedAt??0,Z.secondary?.checkedAt??0);return G-B<W}function h0(Z,$,G){return!N3(Z.quota,$,G)}function D3(Z,$,G,X){return AZ(G)&&n0(Z.quota,$,X)&&V3(Z.quota,X)}function L3(Z){let $=Z?.quota?.checkIntervalMinutes??5;return Math.max(1,$)*60000}var U3=60000,O3=60000,q3=600000,P3=1e4,_3=100;var i4=globalThis.setTimeout.bind(globalThis),u4=globalThis.clearTimeout.bind(globalThis);class F3{now;fetchImpl;paths;refreshPromises=new Map;refreshTimer=null;quotaTimer=null;quotaManager;onFallbackStorageChanged;options;constructor(Z){this.options=Z,this.now=Z.now??Date.now,this.fetchImpl=Z.fetchImpl??fetch,this.paths=Z.paths,this.quotaManager=Z.quotaManager??null,this.onFallbackStorageChanged=Z.onFallbackStorageChanged}seedFallbackQuota(Z,$){if(!this.quotaManager)return;if(!Z.quota)return;let G=Math.max(Z.quota.primary?.checkedAt??0,Z.quota.secondary?.checkedAt??0);if(G<=0)return;let X=this.quotaManager.getFallback(Z.id,Z.access);if(X&&X.checkedAt>=G)return;this.quotaManager.setFallback(Z.id,{quota:Z.quota,refreshAfter:G+L3($),checkedAt:G},Z.access,!1,Z.accountId)}async load(){return u2(this.paths)}async save(Z,$){await X3(Z,this.paths,{accounts:$??!0})}startBackgroundRefresh(){let Z=async()=>{if(await this.refreshDueAccounts(),this.options.fetchQuotaFn)await this.refreshQuotaForDueAccounts()};if(Z().catch(()=>{}),!this.refreshTimer){if(this.refreshTimer=setInterval(()=>{Z().catch(()=>{})},U3+a0(O3)),"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(Z){let $=Z!==void 0?Z:await this.load();if(!$)return[];let G=[],X=!1;for(let W of $.accounts){if(W.enabled===!1||!f(W))continue;if(H3($,W))continue;let B=!1,J=W;try{if(d(J,$,this.now())){let Y=J.lastRefreshError;if(Y&&I(Y,J.refresh,this.now()))throw B=!0,Error(n(Y,this.now()));try{J=await this.refreshAccount(J,$),X=!0}catch(z){if(p2(z))continue;B=!0;let j=$.accounts.find((Q)=>Q.id===W.id&&f(Q));if(j&&!I(j.lastRefreshError,j.refresh,this.now()))tZ(j,z,this.now()),b($,j),X=!0;throw z}}if(this.seedFallbackQuota(J,$),this.accountPassesQuotaPolicy(this.quotaPolicyAccount(J),$))G.push(J)}catch(Y){let z=j3(J,this.now());if(B){if(!z)continue}else if(!z)continue;if(D3(J,$,Y,this.now()))l.debug("fallback quota using cached quota after refresh error",{pid:process.pid,accountId:J.id,error:QZ(Y)}),G.push(J);else if(!NZ($))G.push(J)}}if(X)try{await this.save($)}catch(W){MZ.warn("fallback selection bookkeeping not persisted",{pid:process.pid,error:QZ(W)})}return G}async markUsed(Z){try{let $=await this.load();if(!$)return;let G=$.accounts.find((X)=>X.id===Z.id);if(!G)return;G.lastUsed=this.now(),await this.save($,[G.id])}catch($){MZ.warn("lastUsed stamp not persisted",{pid:process.pid,accountId:Z.id,error:QZ($)})}}accountPassesQuotaPolicy(Z,$){return n0(Z.quota,$,this.now())}quotaPolicyAccount(Z){if(!this.quotaManager)return Z;let $=this.quotaManager.getFallback(Z.id,Z.access)?.quota;return $?{...Z,quota:$}:Z}async refreshDueAccounts(){let Z=await this.load();if(!Z||!Y3(Z))return;let $=!1;for(let G of Z.accounts){if(G.enabled===!1||!f(G))continue;if(!d(G,Z,this.now()))continue;if(I(G.lastRefreshError,G.refresh,this.now()))continue;try{l.debug("fallback oauth background due",{pid:process.pid,accountId:G.id,expiresInMs:G.expires?G.expires-this.now():void 0}),await this.refreshAccount(G,Z),$=!0}catch(X){l.warn("fallback oauth background failed",{pid:process.pid,accountId:G.id,error:QZ(X)}),tZ(G,X,this.now()),b(Z,G),$=!0}}if($)await this.save(Z)}async refreshQuotaForDueAccounts(){let Z=await this.load();if(!Z||!oZ(Z))return;if(!this.options.fetchQuotaFn)return;let $=!1;for(let G of Z.accounts){if(G.enabled===!1||!f(G))continue;let X=G;try{if(d(X,Z,this.now())){if(I(X.lastRefreshError,X.refresh,this.now()))continue;X=await this.refreshAccount(X,Z),$=!0}if(c(X.lastQuotaRefreshError,this.now()))continue;if(this.seedFallbackQuota(X,Z),!(this.quotaManager?this.quotaManager.isFallbackStale(X.id,X.access):h0(X,Z,this.now())))continue;await this.refreshAccountQuota(X,Z),$=!0}catch(W){cZ(G,W,this.now()),b(Z,G),$=!0}}if($)await this.save(Z),this.onFallbackStorageChanged?.()}async refreshQuotaForAllAccounts(Z={}){let $=await this.load(),G=[];if(!$||!oZ($))return{storage:$,errors:G};if(!this.options.fetchQuotaFn)return{storage:$,errors:G};let X=Z.force??!1,W=!1;for(let B of $.accounts){if(B.enabled===!1||!f(B))continue;let J=B;try{if(d(J,$,this.now())){let Y=J.lastRefreshError;if(Y&&I(Y,J.refresh,this.now()))throw Error(n(Y,this.now()));J=await this.refreshAccount(J,$),W=!0}if(!X&&!h0(J,$,this.now())){if(J.lastQuotaRefreshError)J.lastQuotaRefreshError=void 0,b($,J),W=!0;continue}await this.refreshAccountQuota(J,$),W=!0}catch(Y){cZ(B,Y,this.now()),b($,B),W=!0,G.push({accountId:B.id,message:QZ(Y)})}}if(W)await this.save($);return{storage:$,errors:G}}async refreshAccount(Z,$,G={}){let X=this.refreshPromises.get(Z.id);if(X){let J=await X;return b($,J),J}let W=this.refreshAccountNow(Z,$,G).finally(()=>{this.refreshPromises.delete(Z.id)});this.refreshPromises.set(Z.id,W);let B=await W;return b($,B),B}async waitForConcurrentFallbackRefresh(Z,$,G,X){let W=Date.now()+P3;while(Date.now()<W){await new Promise((j)=>setTimeout(j,_3));let B=await this.load(),J=B?.accounts.find((j)=>j.id===Z.id&&f(j));if(!J)continue;if((J.access!==G.access||J.refresh!==G.refresh||(J.expires??0)>(G.expires??0)+60000)&&(X.force||!d(J,B,this.now())))return b($,J),l.debug("fallback oauth joined concurrent refresh",{pid:process.pid,accountId:J.id,expiresInMs:J.expires?J.expires-this.now():void 0}),J;let z=J.lastRefreshError;if(z&&I(z,J.refresh,this.now()))throw b($,J),Error(n(z,this.now()))}return null}async refreshAccountNow(Z,$,G){let X=await this.load(),W=X?.accounts.find((Y)=>Y.id===Z.id&&f(Y));if(W&&!G.force&&!d(W,X,this.now()))return b($,W),W;let B=W??Z,J=await t({name:Q3(B.id),ttlMs:q3,path:this.paths.configPath,now:this.now,renew:!0});if(!J){l.debug("fallback oauth refresh skipped file lock",{pid:process.pid,accountId:B.id});let Y=await this.waitForConcurrentFallbackRefresh(Z,$,B,G);if(Y)return Y;throw Error("Fallback OAuth refresh is already in progress")}try{if(X=await this.load(),W=X?.accounts.find((Q)=>Q.id===Z.id&&f(Q)),W&&!G.force&&!d(W,X,this.now()))return b($,W),W;if(!W)throw new bZ(Z.id);B=W;let Y=this.options.refreshFn??(async()=>{throw Error("No refreshFn injected into FallbackAccountManager")});l.debug("fallback oauth refresh request start",{pid:process.pid,accountId:B.id,force:G.force===!0,expiresInMs:B.expires?B.expires-this.now():void 0});let z=await Y({refreshToken:B.refresh,fetchImpl:this.fetchImpl,now:this.now});if(B.access=z.access,B.refresh=z.refresh,B.expires=z.expires,B.lastRefreshedAt=z.expires-z.expiresIn*1000,B.lastRefreshError=void 0,b($,B),await this.save($),!(await this.load())?.accounts.some((Q)=>Q.id===Z.id))throw new bZ(Z.id);return l.debug("fallback oauth refresh succeeded",{pid:process.pid,accountId:B.id,expiresInMs:B.expires?B.expires-this.now():void 0}),B}finally{await J.release()}}async refreshAccountQuota(Z,$){let G=Z;if(!G.access)throw Error(`Fallback account ${Z.id} has no access token`);if(!this.options.fetchQuotaFn)throw Error("No fetchQuotaFn injected — wham/usage supplement is disabled");let X=this.options.fetchQuotaFn??(async()=>{throw Error("No fetchQuotaFn injected — wham/usage supplement is disabled")}),W=(B)=>this.quotaManager?this.quotaManager.refreshFallback(G.id,B):X({accessToken:B,fetchImpl:this.fetchImpl,now:this.now});try{if(!G.access)throw Error(`Fallback account ${Z.id} has no access token`);let B=await W(G.access);G.quota=B,G.lastQuotaRefreshError=void 0,b($,G),await this.save($)}catch(B){throw cZ(Z,B,this.now()),b($,Z),B}}}function o0(Z){return typeof Z==="object"&&Z!==null&&!Array.isArray(Z)}var Z0="/backend-api/wham/rate-limit-reset-credits",K3=`https://chatgpt.com${Z0}`,G1=`${Z0}/consume`,M3=`https://chatgpt.com${G1}`,b3=300000,C3=60000,S3=15000,T3=60000;function SZ(Z){return{configPath:Z.configPath,statePath:Z.statePath}}class R extends Error{kind;cooldownUntil;constructor(Z,$,G){super($);this.name="ResetRedemptionError",this.kind=Z,this.cooldownUntil=G}}class u extends Error{kind;status;constructor(Z,$,G){super($);this.name="ResetCreditError",this.kind=Z,this.status=G}}function X1(Z,$,G){return{authorization:`Bearer ${Z}`,...G?{"chatgpt-account-id":G}:{},"oai-client-platform":"web","oai-client-version":"0","x-openai-target-path":$}}function TZ(Z){return typeof Z==="object"&&Z!==null&&!Array.isArray(Z)}function W1(Z){if(!Z)return;return{...Z.inFlight?{inFlight:{...Z.inFlight}}:{},...Z.lastOutcome?{lastOutcome:{...Z.lastOutcome}}:{},...Z.cooldownUntil!==void 0?{cooldownUntil:Z.cooldownUntil}:{}}}function $0(Z){if(!TZ(Z)||typeof Z.redeemRequestId!=="string"||Z.redeemRequestId.length===0||typeof Z.creditId!=="string"||Z.creditId.length===0||typeof Z.startedAt!=="number"||!Number.isFinite(Z.startedAt))return;return{redeemRequestId:Z.redeemRequestId,creditId:Z.creditId,startedAt:Z.startedAt}}function B1(Z){return Boolean(Z&&Object.hasOwn(Z,"inFlight"))}function J1(Z,$){return $-Z.startedAt<b3}function EZ(Z,$){if(!E($))return;return Z.reset?.[$]}function Y1(Z){if(!Z.reset)Z.reset=Object.create(null);return Z.reset}function z1(Z,$,G){if(!E($))return;let X=Y1(Z),W=X[$]??{},B=W.lastOutcome;delete W.inFlight,W.lastOutcome={code:"ambiguous_local",at:G,...B?{previousOutcome:{code:B.code,at:B.at}}:{}},X[$]=W}function j1(Z,$){let G=W1(Z),X=$0(Z?.inFlight);if(B1(Z)&&!X)return{kind:"corrupt",beforeState:G};if(Z?.cooldownUntil!==void 0&&Z.cooldownUntil>$)return{kind:"cooldown",beforeState:G,cooldownUntil:Z.cooldownUntil};if(X&&J1(X,$))return{kind:"claim",beforeState:G,claim:{inFlight:X,selectedCredit:{id:X.creditId}}};if(X)return{kind:"expired_unreconciled",beforeState:G,claim:{inFlight:X,selectedCredit:{id:X.creditId}}};return{kind:"fresh",beforeState:G}}async function E3(Z,$){if(!E($))return{kind:"fresh",beforeState:void 0};let G=await Z.loadAccountsFn(SZ(Z));return j1(G?EZ(G,$):void 0,Z.now())}async function R3(Z,$){let G;if(await Z.mutateAccountsFn((X)=>{let W=Z.now(),B=EZ(X,$);if(G=j1(B,W),G.kind==="corrupt")z1(X,$,W);return X},SZ(Z)),!G)throw Error("corrupt reset state mutation did not run");return G}async function x3(Z,$,G){if(!E($))return{kind:"fresh",beforeState:void 0};let X;if(await Z.mutateAccountsFn((W)=>{let B=Z.now(),J=EZ(W,$),Y=W1(J),z=$0(J?.inFlight);if(B1(J)&&!z)return z1(W,$,B),X={kind:"corrupt",beforeState:Y},W;if(J?.cooldownUntil!==void 0&&J.cooldownUntil>B)return X={kind:"cooldown",beforeState:Y,cooldownUntil:J.cooldownUntil},W;if(z&&J1(z,B))return X={kind:"claim",beforeState:Y,claim:{inFlight:z,selectedCredit:{id:z.creditId}}},W;if(z)return X={kind:"expired_unreconciled",beforeState:Y,claim:{inFlight:z,selectedCredit:{id:z.creditId}}},W;let j=RZ(G);if(!j)return X={kind:"fresh",beforeState:Y},W;let Q={redeemRequestId:Z.randomUUID(),creditId:j.id,startedAt:B},V=Y1(W);return V[$]={...J,inFlight:Q},X={kind:"claim",beforeState:Y,claim:{inFlight:Q,selectedCredit:j}},W},SZ(Z)),!X)throw Error("reset claim mutation did not run");return X}async function I3(Z,$,G,X){if(!E($))return;if(!W0(X.kind))return;await Z.mutateAccountsFn((W)=>{let B=EZ(W,$),J=$0(B?.inFlight);if(!B||!J||J.redeemRequestId!==G.redeemRequestId||J.creditId!==G.creditId)return W;let Y=Z.now();if(delete B.inFlight,B.lastOutcome={code:X.kind,at:Y},X.kind==="reset"||X.kind==="already_redeemed")B.cooldownUntil=Y+T3;else delete B.cooldownUntil;return W},SZ(Z))}function DZ(Z,$){if(!Z||Z.usedPercent<100)return!1;if(!Z.resetsAt)return!0;let G=Date.parse(Z.resetsAt);return!Number.isFinite(G)||G>$}function G0(Z,$,G){if(!($||DZ(Z.primary,G)||DZ(Z.secondary,G)))return{ok:!1,reason:"not exhausted"};return{ok:!0}}function t0(Z,$){let G=Z[$];if(G===void 0||G===null)return;return typeof G==="string"?G:null}function A3(Z){if(!TZ(Z))return;let $=t0(Z,"granted_at"),G=t0(Z,"reset_type");if(typeof Z.id!=="string"||typeof Z.status!=="string"||typeof Z.expires_at!=="string"||Number.isNaN(Date.parse(Z.expires_at))||typeof Z.is_supported_by_plan!=="boolean"||$===null||G===null)return;return{id:Z.id,status:Z.status,...$===void 0?{}:{grantedAt:$},expiresAt:Z.expires_at,...G===void 0?{}:{resetType:G},isSupportedByPlan:Z.is_supported_by_plan}}async function X0(Z,$,G){let X;try{X=await Z(K3,{method:"GET",headers:X1($,Z0,G),signal:AbortSignal.timeout(S3)})}catch{throw new u("http_error","reset credit list request failed")}if(!X.ok)throw new u("http_error",`reset credit list request failed: ${X.status}`,X.status);let W;try{W=await X.json()}catch{throw new u("invalid_response","reset credit list response was not valid JSON",X.status)}if(!TZ(W))throw new u("invalid_response","reset credit list response was not an object",X.status);return{credits:(Array.isArray(W.credits)?W.credits:[]).flatMap((J)=>{let Y=A3(J);return Y===void 0?[]:[Y]}),availableCount:typeof W.available_count==="number"&&Number.isFinite(W.available_count)?W.available_count:void 0}}function RZ(Z){return[...Z].filter(H1).sort(($,G)=>Date.parse($.expiresAt)-Date.parse(G.expiresAt))[0]}function H1(Z){return Z.status==="available"&&Z.isSupportedByPlan&&Z.resetType==="codex_rate_limits"}function Q1(Z){return Z.filter(H1).length}function W0(Z){return Z==="reset"||Z==="already_redeemed"||Z==="nothing_to_reset"||Z==="no_credit"}async function y3(Z,$,G,X,W){let B;try{B=await Z(M3,{method:"POST",headers:{...X1($,G1,G),"content-type":"application/json"},body:JSON.stringify({redeem_request_id:W,credit_id:X}),signal:AbortSignal.timeout(C3)})}catch(j){return{kind:"ambiguous",raw:j}}let J;try{J=await B.text()}catch(j){return B.ok?{kind:"ambiguous",raw:j}:{kind:"http_error",raw:j,status:B.status}}let Y=J,z=!1;try{Y=JSON.parse(J),z=!0}catch{}if(!B.ok)return{kind:"http_error",raw:Y,status:B.status};if(!z||!TZ(Y)||!W0(Y.code))return{kind:"ambiguous",raw:Y};return{kind:Y.code,raw:Y}}function e0(Z){if(Z.kind==="cooldown")throw new R("cooldown_active","reset credit redemption is cooling down",Z.cooldownUntil);throw Error(`unexpected reset state decision: ${Z.kind}`)}function Z1(){throw new R("expired_unreconciled","the previous reset attempt outcome is unknown")}function $1(Z,$){return{target:Z,selectedCredit:void 0,beforeState:$,outcome:{kind:"ambiguous_local",raw:{reason:"corrupt_in_flight"}},retrySafety:"No request was sent because the saved redemption identity was incomplete."}}function f3(Z){if(Z.kind==="reset"||Z.kind==="already_redeemed")return"The server returned a terminal result; cooldown blocks an immediate new redemption.";if(Z.kind==="nothing_to_reset"||Z.kind==="no_credit")return"The server returned a terminal no-op. No cooldown was set; a new attempt starts fresh and remains gated by fresh preconditions.";return"The outcome is uncertain. A retry within five minutes reuses the same request and credit identifiers; this does not prove the server did nothing."}async function V1(Z,$){if(!E($.accountKey))throw new R("invalid_account_key","the reset account key is reserved");let G=await Z.resolveTarget($.accountKey);if(G.chatgptAccountId!==$.expectedChatgptAccountId)throw new R("identity_mismatch","the resolved ChatGPT account identity changed before redemption");let X=G.accountKey==="main"?void 0:G.chatgptAccountId,W=await E3(Z,$.accountKey);if(W.kind==="corrupt"){if(W=await R3(Z,$.accountKey),W.kind==="corrupt")return $1(G,W.beforeState)}if(W.kind==="cooldown")e0(W);let B;if(W.kind==="claim")B=W.claim;else if(W.kind==="expired_unreconciled"){if(!$.retry)Z1();B=W.claim}else{if($.retry)throw new R("retry_without_inflight","there is no active reset credit redemption to retry");let[z,j]=await Promise.all([Z.fetchUsage(G),X0(Z.fetchImpl,G.accessToken,X)]),Q=G0(z,Z.hasActiveRateLimitMark($.accountKey),Z.now());if(!Q.ok)throw new R("not_exhausted",Q.reason);if(!RZ(j.credits))throw new R("no_eligible_credit","no eligible reset credit was returned");let V=await x3(Z,$.accountKey,j.credits);if(V.kind==="corrupt")return $1(G,V.beforeState);if(V.kind==="cooldown")e0(V);if(V.kind==="expired_unreconciled")Z1();if(V.kind!=="claim")throw new R("no_eligible_credit","no eligible reset credit was available while claiming");B=V.claim}let J=await y3(Z.fetchImpl,G.accessToken,X,B.inFlight.creditId,B.inFlight.redeemRequestId),Y=!1;try{await I3(Z,$.accountKey,B.inFlight,J)}catch{Y=W0(J.kind)}return{target:G,selectedCredit:B.selectedCredit,beforeState:W.beforeState,outcome:J,retrySafety:Y?"The server returned a terminal result, but the state write failed. A retry within five minutes reuses the same request and credit identifiers.":f3(J),...Y?{finalizeStateWriteFailed:!0}:{}}}var G6="openai-quota",X6="openai-account",W6="openai-routing",B6="openai-killswitch",J6="openai-dump",Y6="openai-logging",z6="openai-cachekeep",xZ="openai-reset",j6=["openai-quota","openai-account","openai-routing","openai-killswitch","openai-dump","openai-logging","openai-cachekeep","openai-reset"],F=x("commands");function s(Z){return{configPath:Z.accountStoragePath,statePath:Z.accountStatePath}}function N1(Z){if(Z==="fallback-first")return"Try usable fallback accounts before the main account.";if(Z==="sticky-balanced")return"Keep each session on its assigned account while balancing new sessions.";return"Try the main account first. Use fallback accounts only when required."}var k3=900000;function D1(Z,$){if(typeof Z!=="number"||!Number.isFinite(Z))return" (age unknown)";let G=$-Z;if(G<k3)return"";let X=Math.floor(G/3600000);if(X>=24)return` (${Math.floor(X/24)}d old)`;if(X>=1)return` (${X}h old)`;return` (${Math.floor(G/60000)}m old)`}async function m3(Z){let $=await Z.refreshAllQuota?.(),G=Z.quotaManager.getMain(),X=Date.now(),W=["## OpenAI Quota",""];if(G?.quota){let Y=G.quota;W.push("### Main account");for(let z of["primary","secondary"]){let j=Y[z];if(j){let Q=Math.round(j.usedPercent),V="█".repeat(Math.max(0,Math.min(Math.round(Q/10),10)))+"░".repeat(Math.max(0,10-Math.min(Math.round(Q/10),10)));W.push(`- ${z}: ${V} ${Q}% used (${Math.round(j.remainingPercent)}% remaining)${D1(j.checkedAt??G.checkedAt,X)}`)}}if(Y.resetCreditsAvailable!==void 0)W.push(`- resets: ${Y.resetCreditsAvailable}`)}else W.push("No main quota snapshot available. Send a request first.");let J=[...Z.quotaManager.getAllFallbacks().entries()].filter(([,Y])=>Y);if(J.length>0){W.push(""),W.push("### Fallback accounts");for(let[Y,z]of J){if(!z?.quota)continue;W.push(`**${Y}**`);for(let j of["primary","secondary"]){let Q=z.quota[j];if(Q){let V=Math.round(Q.usedPercent);W.push(` - ${j}: ${V}% used (${Math.round(Q.remainingPercent)}% remaining)${D1(Q.checkedAt??z.checkedAt,X)}`)}}if(z.quota.resetCreditsAvailable!==void 0)W.push(` - resets: ${z.quota.resetCreditsAvailable}`)}}if($?.length){let Y=$.filter((z)=>!z.ok);if(Y.length>0){W.push("");for(let z of Y)W.push(z.permanent?`- ${z.account}: sign-in no longer accepted — remove and add this account again`:`- ${z.account}: fetch failed — Refresh to retry`)}}return{command:"openai-quota",text:W.join(`
|
|
94
|
+
`),knobs:{}}}function $Z(Z){return{id:Z.id,type:Z.type??"oauth",enabled:Z.enabled,label:Z.label}}async function w3(Z,$){let G=Z.trim().split(/\s+/).filter(Boolean),X=await $.loadAccounts(s($))??{version:1,accounts:[]},W=X.accounts??[];if(G.length===0||G.length===1&&G[0]==="list"){let B=["## OpenAI Accounts",""];if(W.length===0)B.push("No accounts configured. Use `/login openai` to add your main account, or `/openai-account add` to add a fallback account.");else{let J=X.routing?.mode??"main-first";B.push(`Routing: \`${J}\` (set with \`/openai-routing\`). Modes: main-first, fallback-first, or sticky-balanced. \`/openai-routing reset\` clears this session's pin.`),B.push("");for(let Y of W){let z=Y.type??"oauth";B.push(`- \`${Y.id}\` (${z})`)}}return B.push(""),B.push("Commands: `/openai-account add [label]` | `/openai-account remove <id>`"),{command:"openai-account",text:B.join(`
|
|
95
|
+
`),knobs:{accounts:W.map($Z)}}}if(G[0]==="remove"&&G[1]){let B=G[1],J=await eZ($.accountStoragePath),Y=J?J.has(B):!1,z=!1,j=await ZZ((V)=>{let L=V.accounts.findIndex((H)=>H.id===B);if(L===-1)return V;return V.accounts.splice(L,1),z=!0,V},s($),{allowDrop:[B]});if(!(z||Y))return{command:"openai-account",text:`## Account Not Found
|
|
96
|
+
|
|
97
|
+
No account with id \`${B}\` exists.`,knobs:{accounts:j.accounts.map($Z)}};return F.info("account removed",{id:B}),$.refreshSidebar?.().catch(()=>{}),{command:"openai-account",text:`## Account Removed
|
|
98
|
+
|
|
99
|
+
Removed account \`${B}\`.`,knobs:{accounts:j.accounts.map($Z)}}}if(G[0]==="order"&&G.length>=3){let B=!1,J=await ZZ((Y)=>{let z=Y.accounts.findIndex((V)=>V.id===G[1]),j=Y.accounts.findIndex((V)=>V.id===G[2]);if(z===-1||j===-1)return Y;B=!0;let Q=Y.accounts[z];return Y.accounts[z]=Y.accounts[j],Y.accounts[j]=Q,Y},s($));if(!B)return{command:"openai-account",text:`## Invalid Order
|
|
100
|
+
|
|
101
|
+
Both account IDs must exist.`,knobs:{accounts:J.accounts.map($Z)}};return F.info("accounts reordered",{a:G[1],b:G[2]}),$.refreshSidebar?.().catch(()=>{}),{command:"openai-account",text:`## Accounts Reordered
|
|
102
|
+
|
|
103
|
+
Swapped positions of \`${G[1]}\` and \`${G[2]}\`.`,knobs:{accounts:J.accounts.map($Z)}}}if(G[0]==="add"){let B=G.includes("--headless"),J=G.filter((H)=>H!=="add"&&H!=="--headless"),Y=J.length>0?J.join(" "):void 0,{url:z,instructions:j,completion:Q}=await($.beginAccountLogin??b0)({label:Y,headless:B,version:$.packageVersion}),V=$.notify,L=$.sessionId;if(Q.then(async(H)=>{let D=!1;if(await ZZ((O)=>{if(H.accountId&&O.mainAccountId&&H.accountId===O.mainAccountId)return D=!0,O;return M0(O.accounts,H),O},s($)),D){F.warn("account add rejected (main identity)",{id:H.id,sessionId:L}),V?.({command:"openai-account",text:`## Add Failed
|
|
104
|
+
|
|
105
|
+
${"That account is already your main account — not added as a fallback."}`,knobs:{}});return}F.info("account added",{id:H.id,label:H.label}),$.refreshSidebar?.().catch(()=>{}),V?.({command:"openai-account",text:`## Account Added
|
|
106
|
+
|
|
107
|
+
Added account \`${H.id}\`${H.label?` ("${H.label}")`:""}.
|
|
108
|
+
|
|
109
|
+
Run \`/openai-account\` to confirm.`,knobs:{}})}).catch((H)=>{let D=H instanceof Error?H.message:String(H??"unknown error");F.warn("account add failed",{error:D,sessionId:L}),V?.({command:"openai-account",text:`## Add Failed
|
|
110
|
+
|
|
111
|
+
Account add failed: ${D}`,knobs:{}})}),B){let H=j.match(/Enter code: (.+)/)?.[1]??j;return{command:"openai-account",text:`## Device Code
|
|
112
|
+
|
|
113
|
+
1. Open this verification URL:
|
|
114
|
+
|
|
115
|
+
${z}
|
|
116
|
+
|
|
117
|
+
2. Enter the code: **${H}**
|
|
118
|
+
|
|
119
|
+
${j}
|
|
120
|
+
|
|
121
|
+
The account will be added automatically — run \`/openai-account\` to confirm.`,knobs:{verificationUrl:z,userCode:H,instructions:j}}}return{command:"openai-account",text:`## Add OpenAI Account
|
|
122
|
+
|
|
123
|
+
Open this URL and complete sign-in:
|
|
124
|
+
|
|
125
|
+
${z}
|
|
126
|
+
|
|
127
|
+
${j}
|
|
128
|
+
|
|
129
|
+
The account will be added automatically — run \`/openai-account\` to confirm.`,knobs:{url:z,instructions:j}}}return{command:"openai-account",text:"## Account Commands\n\n- `/openai-account` — show accounts\n- `/openai-account add [label]` — add a new account\n- `/openai-account remove <id>` — remove\n- `/openai-account order <a> <b>` — swap fallback positions\n\nRouting modes are `main-first`, `fallback-first`, and `sticky-balanced`. `/openai-routing reset` clears the current session pin.",knobs:{accounts:W.map($Z)}}}async function h3(Z,$){let G=Z.trim().toLowerCase().split(/\s+/).filter(Boolean),W=(await $.loadAccounts(s($))??{version:1,accounts:[]}).routing?.mode??"main-first";if(G.length===1&&G[0]==="reset"){if(!$.sessionId)return{command:"openai-routing",text:`## OpenAI Routing Reset
|
|
130
|
+
|
|
131
|
+
No current session is available, so no pin was changed.`,knobs:{mode:W}};if(!$.clearStickyRouting)return{command:"openai-routing",text:`## OpenAI Routing Reset
|
|
132
|
+
|
|
133
|
+
This runtime cannot clear the current session pin.`,knobs:{mode:W}};return await $.clearStickyRouting($.sessionId),F.info("routing session pin cleared"),{command:"openai-routing",text:`## OpenAI Routing Reset
|
|
134
|
+
|
|
135
|
+
This session's pin was cleared. The next request may choose the same account if it remains the best selection.`,knobs:{mode:W}}}if(G.length===1&&(G[0]==="main-first"||G[0]==="fallback-first"||G[0]==="sticky-balanced")){let Y=G[0];return await ZZ((z)=>{return z.routing={...z.routing??{},mode:Y},z},s($)),F.info("routing mode changed",{mode:Y}),{command:"openai-routing",text:`## OpenAI Routing Updated
|
|
136
|
+
|
|
137
|
+
Mode: \`${Y}\`
|
|
138
|
+
- ${N1(Y)}
|
|
139
|
+
|
|
140
|
+
Usage: \`/openai-routing\`, \`/openai-routing main-first\`, \`/openai-routing fallback-first\`, or \`/openai-routing sticky-balanced\`.`,knobs:{mode:Y}}}let B=W==="sticky-balanced"&&$.sessionId?await $.getStickyRouting?.($.sessionId):void 0,J=W==="sticky-balanced"?B?`
|
|
141
|
+
- Session pin: \`${B}\`. Use \`/openai-routing reset\` to clear it.`:`
|
|
142
|
+
- Session pin: none yet. A request will choose one when a usable account is available.`:"";return{command:"openai-routing",text:`## OpenAI Routing
|
|
143
|
+
|
|
144
|
+
- Mode: \`${W}\`
|
|
145
|
+
- ${N1(W)}${J}
|
|
146
|
+
|
|
147
|
+
Usage: \`/openai-routing\`, \`/openai-routing main-first\`, \`/openai-routing fallback-first\`, or \`/openai-routing sticky-balanced\`.`,knobs:{mode:W}}}function O1(Z){let $=[Z.primary?.usedPercent,Z.secondary?.usedPercent].filter((G)=>G!==void 0);return $.length>0?Math.max(...$):void 0}function v3(Z,$){let G=[Z.primary,Z.secondary].filter((W)=>W!==void 0),X=G.filter((W)=>DZ(W,$));return(X.length>0?X:G).sort((W,B)=>B.usedPercent-W.usedPercent)[0]?.resetsAt}function p3(Z,$){if(!Z)return!1;let G=[Z.primary,Z.secondary].filter((X)=>X!==void 0);if(G.length===0)return!1;return G.every((X)=>!DZ(X,$))}function B0(Z){if(!Z)return;try{return decodeURIComponent(Z)}catch{return}}async function L1(Z,$){try{let G=await $.resolveResetTarget(Z),X=G.accountKey==="main"?void 0:G.chatgptAccountId,[W,B]=await Promise.all([dZ({accessToken:G.accessToken,fetchImpl:$.fetchImpl,now:$.now,accountId:G.chatgptAccountId}),X0($.fetchImpl,G.accessToken,X)]),J=RZ(B.credits),Y=Q1(B.credits),z=B.availableCount??W.resetCreditsAvailable??(Y>0?Y:void 0),j=W.resetCreditsApplicable,Q=G0(W,$.quotaManager.isRateLimited(Z),$.now()),V;if(!G.chatgptAccountId)V="stable ChatGPT account identity unavailable";else if(!Q.ok)V=Q.reason;else if(!J)V="no eligible credit";return{accountKey:G.accountKey,label:G.label,chatgptAccountId:G.chatgptAccountId,usedPercent:O1(W),resetTime:v3(W,$.now()),availableCount:z,applicableAvailableCount:j,eligible:V===void 0,reason:V,selectedCreditId:J?.id,selectedCreditExpiresAt:J?.expiresAt}}catch(G){return F.warn("reset preview row failed",{accountKey:Z,error:G?.message??String(G)}),{accountKey:Z,label:Z==="main"?"Main account":Z,eligible:!1,reason:G?.message??String(G)}}}function g3(Z){let $=["## Reset credits","","Select an account to fetch a fresh confirmation preview:",""];for(let G of Z){let X=G.usedPercent===void 0?"quota unavailable":`${G.usedPercent}% used`,W=G.availableCount===void 0?"credits unavailable":`${G.applicableAvailableCount===void 0?"?":G.applicableAvailableCount}/${G.availableCount} applicable/available`,B=G.eligible?`eligible · credit ${G.selectedCreditId} expires ${G.selectedCreditExpiresAt}`:G.reason;$.push(`- **${G.label}** (\`${G.accountKey}\`) — ${X}; ${W}; ${B}`)}return $.push(""),$.push("Command: `/openai-reset select <encodedAccountKey>`"),$.join(`
|
|
148
|
+
`)}function U1(Z){let $=["## Confirm reset credit","",`Account: **${Z.label}** (\`${Z.accountKey}\`)`,`Current quota: **${Z.usedPercent??"unknown"}% used**`,`Credit: **Spend 1 of ${Z.availableCount??"unknown"}**`,`Credit expires: **${Z.selectedCreditExpiresAt??"unavailable"}**`,`Quota resets: **${Z.resetTime??"unavailable"}**`,""];if((Z.availableCount??0)>0&&Z.applicableAvailableCount===0)$.push("The server does not currently count this credit as applicable; redemption may return a no-op, and a no-op does not spend the credit."),$.push("");if(Z.eligible&&Z.chatgptAccountId)$.push(`Confirm: \`/openai-reset confirm ${encodeURIComponent(Z.accountKey)} ${encodeURIComponent(Z.chatgptAccountId)}\``);else $.push(`Cannot reset: **${Z.reason??"not eligible"}**`);return $.join(`
|
|
149
|
+
`)}function C(Z,$,G,X={}){return{command:xZ,text:G,knobs:{stage:"result",accountKey:Z,code:$,...X}}}function l3(Z,$,G){if($ instanceof R){let W={identity_mismatch:"The account identity changed before redemption. Reopen the reset account list.",invalid_account_key:"The selected account key is reserved. Reopen the reset account list.",cooldown_active:"This account just reset — re-checking quota. Wait for the cooldown before another redemption.",expired_unreconciled:"The previous attempt outcome is unknown — retry replays the same identifiers, or wait until quota reflects the earlier attempt.",retry_without_inflight:"There is no active reset redemption to retry. Reopen the account list.",not_exhausted:"No credit was spent: the fresh account state is not exhausted.",no_eligible_credit:"No credit was spent: no eligible credit was returned."};return C(Z,$.kind,`## Reset credit
|
|
150
|
+
|
|
151
|
+
${W[$.kind]}
|
|
152
|
+
|
|
153
|
+
Code: \`${$.kind}\``,{cooldownUntil:$.cooldownUntil,...$.kind==="expired_unreconciled"?{chatgptAccountId:G,retryGuidance:"Retry replays the same request and credit identifiers from the previous attempt."}:{}})}let X=$?.code;if(X==="unknown_account"||X==="disabled_account"||X==="non_oauth_account"||X==="token_unavailable")return C(Z,X,`## Reset credit
|
|
154
|
+
|
|
155
|
+
${{unknown_account:"Account unavailable: the selected account no longer exists. Reopen the reset account list.",disabled_account:"Account unavailable: the selected account is disabled. Reopen the reset account list.",non_oauth_account:"Account unavailable: the selected account is not authenticated with OAuth. Reopen the reset account list.",token_unavailable:"Authentication problem: the selected account token is unavailable. Reauthenticate the account before retrying."}[X]}
|
|
156
|
+
|
|
157
|
+
Code: \`${X}\``);if($ instanceof u)return C(Z,$.kind,`## Reset credit
|
|
158
|
+
|
|
159
|
+
No redemption was attempted: reset credit availability could not be loaded.
|
|
160
|
+
|
|
161
|
+
Code: \`${$.kind}\``);return F.warn("reset command failed before a known result",{accountKey:Z,error:$?.message??String($)}),C(Z,"error",`## Reset credit
|
|
162
|
+
|
|
163
|
+
The reset request failed before a known result: internal command failure — see plugin log.`)}async function q1(Z,$,G){let{accountKey:X}=Z.target,W=Z.outcome.kind;if(Z.finalizeStateWriteFailed)return C(X,W,`## Reset credit result
|
|
164
|
+
|
|
165
|
+
Account: **${Z.target.label}** (\`${X}\`)
|
|
166
|
+
|
|
167
|
+
The server outcome recorded as \`${W}\`, but the state write failed. A retry within five minutes reuses the same request and credit identifiers; this does not prove the server did nothing.`,{stateWriteFailed:!0,retryGuidance:Z.retrySafety,chatgptAccountId:G});if(W==="reset"||W==="already_redeemed"){let J={account:X,ok:!1,error:"targeted quota refresh did not complete"};try{J=await $.refreshResetTargetQuota(X)}catch(H){J.error=H?.message??String(H)}let Y=!J.ok&&J.error!==void 0;if(Y)F.warn("reset quota re-check failed",{accountKey:X,error:J.error});let z=X==="main"?$.quotaManager.getMain():$.quotaManager.getFallback(X),j=J.ok&&p3(z?.quota,$.now()),Q=z?.quota.resetCreditsApplicable,V=j?"Post-verification: **window fresh**.":`Post-verification: **window not yet refreshed** (server code \`${W}\`).`,L=Y?`
|
|
168
|
+
|
|
169
|
+
quota re-check failed — see log.`:"";return C(X,W,`## Reset credit result
|
|
170
|
+
|
|
171
|
+
Account: **${Z.target.label}** (\`${X}\`)
|
|
172
|
+
|
|
173
|
+
Code: \`${W}\`
|
|
174
|
+
|
|
175
|
+
${V}${L}${Q===void 0?"":`
|
|
176
|
+
|
|
177
|
+
Remaining applicable credits: **${Q}**`}`,{verifiedFresh:j,afterUsedPercent:O1(z?.quota??{}),remainingCredits:Q})}if(W==="ambiguous_local")return C(X,W,`## Reset credit result
|
|
178
|
+
|
|
179
|
+
Account: **${Z.target.label}** (\`${X}\`)
|
|
180
|
+
|
|
181
|
+
Code: \`${W}\`
|
|
182
|
+
|
|
183
|
+
${Z.retrySafety}`,{retryGuidance:Z.retrySafety});if(W==="ambiguous"||W==="http_error"){let J=G?`/openai-reset retry ${encodeURIComponent(X)} ${encodeURIComponent(G)}`:"/openai-reset";return C(X,W,`## Reset credit result
|
|
184
|
+
|
|
185
|
+
Account: **${Z.target.label}** (\`${X}\`)
|
|
186
|
+
|
|
187
|
+
The redemption outcome is unknown (\`${W}\`).
|
|
188
|
+
|
|
189
|
+
Retry with \`${J}\`. A retry within five minutes reuses the same request and credit identifiers; this does not prove the server did nothing.`,{retryGuidance:Z.retrySafety,chatgptAccountId:G})}let B={nothing_to_reset:"The server found no exhausted quota window to reset. No reset was confirmed. A new attempt starts fresh and must pass the current preconditions.",no_credit:"The server found no usable reset credit. No reset was confirmed. A new attempt starts fresh and must pass the current preconditions."};return C(X,W,`## Reset credit result
|
|
190
|
+
|
|
191
|
+
Account: **${Z.target.label}** (\`${X}\`)
|
|
192
|
+
|
|
193
|
+
Code: \`${W}\`
|
|
194
|
+
|
|
195
|
+
${B[W]??"The server returned a no-op result. No reset was confirmed."}`)}async function d3(Z,$){let G=[$.resolveResetTarget?void 0:"resolveResetTarget",$.fetchImpl?void 0:"fetchImpl",$.now?void 0:"now",$.randomUUID?void 0:"randomUUID",$.refreshResetTargetQuota?void 0:"refreshResetTargetQuota"].filter((J)=>J!==void 0);if(G.length>0)return F.warn("reset command dependencies unwired",{missingDeps:G}),{command:xZ,text:`## Reset credit
|
|
196
|
+
|
|
197
|
+
Unavailable: reset command runtime dependencies are not wired.`,knobs:{}};let X=$,W=Z.trim().split(/\s+/).filter(Boolean),B=W[0];if(!B||B==="refresh"){let Y=["main",...((await $.loadAccounts(s($)))?.accounts??[]).filter((j)=>j.enabled!==!1&&j.type==="oauth").map((j)=>j.id)];F.debug("reset accounts stage requested",{accountKeys:Y});let z=await Promise.all(Y.map((j)=>L1(j,X)));return F.debug("reset accounts stage built",{rows:z.map((j)=>({accountKey:j.accountKey,eligible:j.eligible,reason:j.reason,usedPercent:j.usedPercent,availableCount:j.availableCount,applicableAvailableCount:j.applicableAvailableCount}))}),{command:xZ,text:g3(z),knobs:{stage:"accounts",accounts:z}}}if(B==="select"){let J=B0(W[1]);if(!J||!E(J)||W.length!==2)return C("","invalid_command","Usage: `/openai-reset select <encodedAccountKey>`");let Y=await L1(J,X);if(!Y.eligible)return C(J,"not_eligible",U1(Y));return{command:xZ,text:U1(Y),knobs:{stage:"confirm",preview:Y}}}if(B==="confirm"||B==="retry"){let J=B0(W[1]),Y=B0(W[2]);if(!J||!E(J)||!Y||W.length!==3)return C(J??"","invalid_command",`Usage: \`/openai-reset ${B} <encodedAccountKey> <encodedChatgptAccountId>\``);F.info("reset redemption decision",{accountKey:J,action:B}),F.debug("reset redemption identity binding",{accountKey:J,expectedChatgptAccountId:Y});try{let z=await V1({configPath:$.accountStoragePath,statePath:$.accountStatePath,mutateAccountsFn:ZZ,loadAccountsFn:$.loadAccounts,now:X.now,randomUUID:X.randomUUID,fetchImpl:X.fetchImpl,resolveTarget:X.resolveResetTarget,fetchUsage:(j)=>dZ({accessToken:j.accessToken,fetchImpl:X.fetchImpl,now:X.now,accountId:j.chatgptAccountId}),hasActiveRateLimitMark:(j)=>$.quotaManager.isRateLimited(j)},{accountKey:J,expectedChatgptAccountId:Y,retry:B==="retry"});return F.info("reset redemption outcome",{accountKey:J,code:z.outcome.kind}),q1(z,X,Y)}catch(z){let j=l3(J,z,Y);return F.info("reset redemption outcome",{accountKey:J,code:j.knobs.code}),j}}return C("","invalid_command","Usage: `/openai-reset` | `/openai-reset select <encodedAccountKey>` | `/openai-reset confirm <encodedAccountKey> <encodedChatgptAccountId>` | `/openai-reset retry <encodedAccountKey> <encodedChatgptAccountId>` | `/openai-reset refresh`")}var i3=new Set(["access","refresh","apikey","authheader","password","secret"]);function u3(Z){let $=Z.toLowerCase().replace(/[-_]/g,"");if(i3.has($))return!0;return $.endsWith("token")}function J0(Z,$,G){if(Array.isArray(Z))return Z.map((W,B)=>J0(W,`${$}[${B}]`,G));if(!o0(Z))return Z;let X={};for(let[W,B]of Object.entries(Z)){if(u3(W)){G.push(`${$}.${W}`);continue}X[W]=J0(B,`${$}.${W}`,G)}return X}async function H6(Z,$,G,X={}){let W=await s3(Z,$,G,X),B=[],J=J0(W.knobs,"knobs",B);if(B.length>0)return F.warn("credential-shaped knob stripped before RPC",{command:Z,fields:B}),{...W,knobs:J};return W}async function s3(Z,$,G,X){switch(Z){case"openai-quota":return m3(G);case"openai-account":return w3($,G);case"openai-routing":return h3($,G);case"openai-reset":return d3($,G);default:{let W=X[Z];if(!W)throw Error(`unhandled command: ${Z}`);return W($,G)}}}var Y0=x("quota");function n3(Z){return Z?.status===401}async function L6(Z,$={}){let G=Z.whamFn;if(!G)throw Error("whamFn is required for refreshAllQuota");let X=[],W=Z.logger??Y0,B=(H)=>{X.push(H);let D={pid:process.pid,accountId:H.account,status:H.ok?"ok":"error",...H.error?{error:H.error}:{}};if(H.ok)W.debug("quota refresh succeeded",D);else W.warn("quota refresh failed",D)},J=Z.skipFresherThanMs,Y=!1,z;if(J!==void 0)try{z=await Z.readSidebarState()}catch{}let j=new Map(z?.fallbacks.map((H)=>[H.id,H])??[]),Q=(...H)=>J!==void 0&&H.some((D)=>typeof D==="number"&&Number.isFinite(D)&&D<=Z.now()&&Z.now()-D<J),V=await Z.loadAccounts(Z.paths).catch(()=>{return}),L=V?.mainAccountId??Z.storageMainAccountId;if(!$.accountKey||$.accountKey==="main")try{let H=await Z.getAuth();if(H.type==="oauth"){let D=z&&L!==void 0&&z.main.mainAccountId===L?z.main.quota:void 0;if(Q(Z.quotaManager.peekMainForPolicy(L)?.checkedAt,D?.primary?.checkedAt,D?.secondary?.checkedAt,D?.checkedAt))B({account:"main",ok:!0});else{if(!H.access||(H.expires??0)<Z.now()){let _=await Z.refreshMainWithLease();H={...H,access:_.access,expires:_.expires}}if(H.access)if(Z.respectBackoff&&Z.quotaManager.isBackedOff())B({account:"main",ok:!0});else{let _=await G({accessToken:H.access,fetchImpl:Z.fetchImpl,now:Z.now,accountId:L,accountKey:"main"});Z.quotaManager.setMain(H.access,{quota:_,refreshAfter:Z.now()+300000,checkedAt:Z.now()},L,!0),Y=!0,B({account:"main",ok:!0})}else B({account:"main",ok:!1,error:"no access token"})}}else B({account:"main",ok:!1,error:"auth type is not oauth"})}catch(H){B({account:"main",ok:!1,error:a(H)})}if(V)for(let H of V.accounts){if($.accountKey&&($.accountKey==="main"||H.id!==$.accountKey))continue;if(H.enabled===!1||!Z.isOAuthAccountFn(H)){if($.accountKey)B({account:H.id,ok:!1,error:"account is not an enabled OAuth fallback"});continue}try{let D=j.get(H.id),O=H.accountId,_=D&&O!==void 0&&D.accountId===O?D.quota:void 0;if(Q(Z.quotaManager.peekFallbackForPolicy(H.id,O)?.checkedAt,_?.primary?.checkedAt,_?.secondary?.checkedAt,_?.checkedAt)){B({account:H.id,ok:!0});continue}if(Z.respectBackoff&&Z.quotaManager.isFallbackBackedOff(H.id,H.access)){B({account:H.id,ok:!0});continue}let m=H.lastRefreshError;if(I(m,H.refresh,Z.now())){B({account:H.id,ok:!1,error:n(m,Z.now()),permanent:!0});continue}let q;try{q=await Z.fallbackManager.refreshAccount(H,V)}catch(K){Y0.warn("fallback token refresh failed during quota poll",{pid:process.pid,accountId:H.id,error:a(K)}),q=H}if(!q.access||(q.expires??0)<Z.now()){B({account:H.id,ok:!1,error:"no usable access token"});continue}let T;try{T=await G({accessToken:q.access,fetchImpl:Z.fetchImpl,now:Z.now,accountId:q.accountId,accountKey:H.id})}catch(K){if(!n3(K))throw K;if(Y0.warn("quota endpoint rejected the token; forcing a refresh",{pid:process.pid,accountId:H.id}),q=await Z.fallbackManager.refreshAccount(H,V,{force:!0}),!q.access){B({account:H.id,ok:!1,error:"no usable access token after forced refresh"});continue}T=await G({accessToken:q.access,fetchImpl:Z.fetchImpl,now:Z.now,accountId:q.accountId,accountKey:H.id})}Z.quotaManager.setFallback(H.id,{quota:T,refreshAfter:Z.now()+300000,checkedAt:Z.now()},q.access,!0,q.accountId),Y=!0,B({account:H.id,ok:!0})}catch(D){B({account:H.id,ok:!1,error:a(D)})}}if($.accountKey&&$.accountKey!=="main"&&!X.some((H)=>H.account===$.accountKey))X.push({account:$.accountKey,ok:!1,error:"account not found"});if(J===void 0||Y){let H=await Z.loadAccounts(Z.paths);await Z.writeSidebarState(Z.quotaManager,H)}return X}import{tmpdir as c3}from"node:os";import{join as r3}from"node:path";var a3=["error","warn","info","debug","trace"];function o3(){return process.env.OPENCODE_OPENAI_AUTH_LOG_FILE??r3(c3(),"opencode-openai-auth.log")}function t3(){let Z=process.env.OPENCODE_OPENAI_AUTH_LOG_LEVEL;return Z&&a3.includes(Z)?Z:void 0}L0({file:o3,level:t3});process.on("exit",BZ);
|
|
198
|
+
export{K1 as I,V0 as J,N0 as K,I as L,n as M,y1 as N,O0 as O,h1 as P,x as Q,_0 as R,K0 as S,c1 as T,q0 as U,P0 as V,PZ as W,a1 as X,g as Y,Z2 as Z,$2 as _,G2 as $,X2 as aa,M0 as ba,b0 as ca,x0 as da,x2 as ea,a as fa,H4 as ga,dZ as ha,t as ia,_4 as ja,y as ka,f as la,h4 as ma,rZ as na,eZ as oa,u2 as pa,ZZ as qa,p4 as ra,c0 as sa,r0 as ta,g4 as ua,l4 as va,d4 as wa,F3 as xa,o0 as ya,G6 as za,X6 as Aa,W6 as Ba,B6 as Ca,J6 as Da,Y6 as Ea,z6 as Fa,xZ as Ga,j6 as Ha,H6 as Ia,L6 as Ja};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
function K(k){if(k==null||k==="")return;let q=typeof k==="number"?k:Number(k);if(Number.isFinite(q)){let B=q<100000000000?q*1000:q,G=new Date(B);return Number.isNaN(G.getTime())?void 0:G.toISOString()}let z=new Date(k);return Number.isNaN(z.getTime())?void 0:z.toISOString()}function L(k){let q=Number(k);return Number.isFinite(q)&&q>0?q:void 0}function X(k){return typeof k==="number"&&Number.isFinite(k)&&k>=0?k:void 0}function Y(k,q){let z=k.get(q);if(z===null||z.trim()==="")return;let B=Number(z);if(!Number.isFinite(B)||B<0||B>100)return;let G=q.slice(0,-13),J=L(k.get(`${G}-window-minutes`)),V=K(k.get(`${G}-reset-at`)??void 0);if(B===0&&k.get(`${G}-window-minutes`)==="0"&&!V)return;return{usedPercent:B,remainingPercent:100-B,resetsAt:V,checkedAt:Date.now(),...J!==void 0?{windowMinutes:J}:{}}}var O=["x-codex-primary-used-percent","x-codex-secondary-used-percent"];function Q(k,q){let z=k.get(q);if(z===null)return"absent";if(z.trim()==="")return"invalid";let B=Number(z);return Number.isFinite(B)&&B>=0&&B<=100?"valid":"invalid"}function g(k){if(O.some((G)=>Q(k,G)==="invalid"))return{};let q={},z=Y(k,"x-codex-primary-used-percent");if(z)q.primary=z;let B=Y(k,"x-codex-secondary-used-percent");if(B)q.secondary=B;return q}function I(k){let q=O.map((z)=>Q(k,z));return q.includes("valid")&&!q.includes("invalid")}function Z(k){if(!k)return;if(!Number.isFinite(k.used_percent)||k.used_percent<0||k.used_percent>100)return;let q=L(k.window_minutes),z=K(k.reset_at);if(k.used_percent===0&&q===void 0&&!z)return;return{usedPercent:k.used_percent,remainingPercent:100-k.used_percent,resetsAt:z,checkedAt:Date.now(),...q!==void 0?{windowMinutes:q}:{}}}function f(k){let q={},z=Z(k.rate_limits?.primary);if(z)q.primary=z;let B=Z(k.rate_limits?.secondary);if(B)q.secondary=B;return q}function $(k){if(!k)return;if(!Number.isFinite(k.used_percent)||k.used_percent<0||k.used_percent>100)return;let q=L(k.limit_window_seconds),z=K(k.reset_at);if(k.used_percent===0&&q===void 0&&!z)return;return{usedPercent:k.used_percent,remainingPercent:100-k.used_percent,resetsAt:z,checkedAt:Date.now(),...q!==void 0?{windowMinutes:q/60}:{}}}function x(k){let q={},z=$(k.rate_limit?.primary_window);if(z)q.primary=z;let B=$(k.rate_limit?.secondary_window);if(B)q.secondary=B;let G=X(k.rate_limit_reset_credits?.available_count);if(G!==void 0)q.resetCreditsAvailable=G;let J=X(k.rate_limit_reset_credits?.applicable_available_count);if(J!==void 0)q.resetCreditsApplicable=J;return q}
|
|
2
|
-
export{K as
|
|
2
|
+
export{K as Na,g as Oa,I as Pa,f as Qa,x as Ra};
|