@cortexkit/opencode-openai-auth 0.3.0 → 0.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +5 -4
- package/dist/core/accounts.d.ts +9 -4
- package/dist/core/oauth.d.ts +5 -1
- package/dist/core/quota-manager.d.ts +2 -1
- package/dist/core/refresh-file-lock.d.ts +1 -0
- package/dist/{index-vj00ztg7.js → index-53j7bdev.js} +1 -1
- package/dist/{index-nngfcx1x.js → index-7w467pz8.js} +1 -1
- package/dist/{index-r68prrfg.js → index-899gpxdd.js} +1 -1
- package/dist/index-d9hq0tmc.js +2 -0
- package/dist/{index-qqrj9za2.js → index-gwmhhrrc.js} +1 -1
- package/dist/index-jn8xd8fy.js +3 -0
- package/dist/index-n33dsxp3.js +92 -0
- package/dist/index-qp2nja20.js +2 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +58 -58
- package/dist/logger.d.ts +1 -0
- package/dist/quota-normalize-dxftsgep.js +1 -0
- package/dist/rpc/port-file.js +1 -1
- package/dist/rpc/rpc-client.js +1 -1
- package/dist/rpc/rpc-dir.js +1 -1
- package/dist/sidebar-state.js +1 -1
- package/dist/{token-c1q4pea2.js → token-28n5g707.js} +1 -1
- package/dist/token-util-gmr2b13z.js +1 -0
- package/dist/tui-preferences.js +1 -1
- package/dist/version.d.ts +1 -1
- package/dist/ws-pool.d.ts +7 -4
- package/package.json +1 -1
- package/src/logger.ts +26 -5
- package/dist/index-1gjhrsep.js +0 -2
- package/dist/index-5j7p33r8.js +0 -2
- package/dist/index-88b7ha2h.js +0 -3
- package/dist/index-pyyjg54f.js +0 -92
- package/dist/quota-normalize-s1bctr9a.js +0 -1
- package/dist/token-util-ff59e4fw.js +0 -1
package/dist/logger.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
type Level = 'error' | 'warn' | 'info' | 'debug' | 'trace';
|
|
2
2
|
export declare function setLogLevel(l: Level | undefined): void;
|
|
3
|
+
export declare function redact(value: unknown): unknown;
|
|
3
4
|
export declare function createLogger(channel: string): {
|
|
4
5
|
error: (m: string, d?: unknown) => void;
|
|
5
6
|
warn: (m: string, d?: unknown) => void;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{c as a,d as b,e as c,f as d}from"./index-d9hq0tmc.js";import"./index-53j7bdev.js";export{a as toResetIso,c as normalizeWsFrame,d as normalizeWham,b as normalizeQuotaHeaders};
|
package/dist/rpc/port-file.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{ca as a,da as b}from"../index-7w467pz8.js";import"../index-53j7bdev.js";export{a as writePortFile,b as discoverPortFile};
|
package/dist/rpc/rpc-client.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{da as c}from"../index-7w467pz8.js";import"../index-53j7bdev.js";async function p(n,r,l,o,i){let t=await c(n,r);if(l?.(t),!t)return null;let e=new AbortController,s=setTimeout(()=>e.abort(),2000);try{let a=await fetch(`http://127.0.0.1:${t.port}/rpc/${o}`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${t.token}`},body:JSON.stringify(i),signal:e.signal});if(!a.ok)return null;return await a.json()}catch{return null}finally{clearTimeout(s)}}function y(n,r,l){let o=!1,i=(t)=>{if(o)return;o=!0,l?.(t)};return{async pending(t,e){return(await p(n,r,i,"pending-notifications",{lastReceivedId:t,sessionId:e}))?.messages??[]},async apply(t){return await p(n,r,i,"apply",{...t})??{text:"apply failed",knobs:{}}}}}export{y as createRpcClient};
|
package/dist/rpc/rpc-dir.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{ea as a,fa as b}from"../index-gwmhhrrc.js";import"../index-53j7bdev.js";export{a as tmpdir,b as getRpcDir};
|
package/dist/sidebar-state.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Q as a,R as b,S as c,T as d,U as e,V as f,W as g,X as h,Y as i,Z as j,_ as k}from"./index-qp2nja20.js";import"./index-jn8xd8fy.js";import"./index-53j7bdev.js";export{e as setSidebarState,g as resolveActiveAccount,c as normalizeSidebarState,a as getSidebarStateFile,d as getSidebarState,h as getCollapsedQuotaSummary,f as drainSidebarWrites,k as computeQuotaPacing,j as SEVEN_DAY_MS,i as FIVE_HOUR_MS,b as DEFAULT_SIDEBAR_STATE};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as U,b as V}from"./index-
|
|
1
|
+
import{a as U,b as V}from"./index-899gpxdd.js";import{ha as R}from"./index-53j7bdev.js";var E=R((M,Q)=>{var{defineProperty:K,getOwnPropertyDescriptor:W,getOwnPropertyNames:X}=Object,Y=Object.prototype.hasOwnProperty,Z=(q,v)=>{for(var z in v)K(q,z,{get:v[z],enumerable:!0})},$=(q,v,z,F)=>{if(v&&typeof v==="object"||typeof v==="function"){for(let G of X(v))if(!Y.call(q,G)&&G!==z)K(q,G,{get:()=>v[G],enumerable:!(F=W(v,G))||F.enumerable})}return q},A=(q)=>$(K({},"__esModule",{value:!0}),q),L={};Z(L,{refreshToken:()=>D});Q.exports=A(L);var H=U(),B=V();async function D(){let{projectId:q,teamId:v}=(0,B.findProjectInfo)(),z=(0,B.loadToken)(q);if(!z||(0,B.isExpired)((0,B.getTokenPayload)(z.token))){let F=await(0,B.getVercelCliToken)();if(!F)throw new H.VercelOidcTokenError("Failed to refresh OIDC token: Log in to Vercel CLI and link your project with `vc link`");if(!q)throw new H.VercelOidcTokenError("Failed to refresh OIDC token: Try re-linking your project with `vc link`");if(z=await(0,B.getVercelOidcToken)(F,q,v),!z)throw new H.VercelOidcTokenError("Failed to refresh OIDC token");(0,B.saveToken)(z,q)}process.env.VERCEL_OIDC_TOKEN=z.token;return}});export default E();
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{b as a}from"./index-899gpxdd.js";import"./index-53j7bdev.js";export default a();
|
package/dist/tui-preferences.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{ga as P,ha as C,ja as _}from"./index-53j7bdev.js";var g=C((T,L)=>{(function(Q){if(typeof L==="object"&&typeof L.exports==="object"){var J=Q(_,T);if(J!==void 0)L.exports=J}else if(typeof define==="function"&&define.amd)define(["require","exports","./impl/format","./impl/edit","./impl/scanner","./impl/parser"],Q)})(function(Q,J){Object.defineProperty(J,"__esModule",{value:!0}),J.applyEdits=J.modify=J.format=J.printParseErrorCode=J.ParseErrorCode=J.stripComments=J.visit=J.getNodeValue=J.getNodePath=J.findNodeAtOffset=J.findNodeAtLocation=J.parseTree=J.parse=J.getLocation=J.SyntaxKind=J.ScanError=J.createScanner=void 0;let X=Q("./impl/format"),Z=Q("./impl/edit"),G=Q("./impl/scanner"),$=Q("./impl/parser");J.createScanner=G.createScanner;var W;(function(z){z[z.None=0]="None",z[z.UnexpectedEndOfComment=1]="UnexpectedEndOfComment",z[z.UnexpectedEndOfString=2]="UnexpectedEndOfString",z[z.UnexpectedEndOfNumber=3]="UnexpectedEndOfNumber",z[z.InvalidUnicode=4]="InvalidUnicode",z[z.InvalidEscapeCharacter=5]="InvalidEscapeCharacter",z[z.InvalidCharacter=6]="InvalidCharacter"})(W||(J.ScanError=W={}));var H;(function(z){z[z.OpenBraceToken=1]="OpenBraceToken",z[z.CloseBraceToken=2]="CloseBraceToken",z[z.OpenBracketToken=3]="OpenBracketToken",z[z.CloseBracketToken=4]="CloseBracketToken",z[z.CommaToken=5]="CommaToken",z[z.ColonToken=6]="ColonToken",z[z.NullKeyword=7]="NullKeyword",z[z.TrueKeyword=8]="TrueKeyword",z[z.FalseKeyword=9]="FalseKeyword",z[z.StringLiteral=10]="StringLiteral",z[z.NumericLiteral=11]="NumericLiteral",z[z.LineCommentTrivia=12]="LineCommentTrivia",z[z.BlockCommentTrivia=13]="BlockCommentTrivia",z[z.LineBreakTrivia=14]="LineBreakTrivia",z[z.Trivia=15]="Trivia",z[z.Unknown=16]="Unknown",z[z.EOF=17]="EOF"})(H||(J.SyntaxKind=H={})),J.getLocation=$.getLocation,J.parse=$.parse,J.parseTree=$.parseTree,J.findNodeAtLocation=$.findNodeAtLocation,J.findNodeAtOffset=$.findNodeAtOffset,J.getNodePath=$.getNodePath,J.getNodeValue=$.getNodeValue,J.visit=$.visit,J.stripComments=$.stripComments;var q;(function(z){z[z.InvalidSymbol=1]="InvalidSymbol",z[z.InvalidNumberFormat=2]="InvalidNumberFormat",z[z.PropertyNameExpected=3]="PropertyNameExpected",z[z.ValueExpected=4]="ValueExpected",z[z.ColonExpected=5]="ColonExpected",z[z.CommaExpected=6]="CommaExpected",z[z.CloseBraceExpected=7]="CloseBraceExpected",z[z.CloseBracketExpected=8]="CloseBracketExpected",z[z.EndOfFileExpected=9]="EndOfFileExpected",z[z.InvalidCommentToken=10]="InvalidCommentToken",z[z.UnexpectedEndOfComment=11]="UnexpectedEndOfComment",z[z.UnexpectedEndOfString=12]="UnexpectedEndOfString",z[z.UnexpectedEndOfNumber=13]="UnexpectedEndOfNumber",z[z.InvalidUnicode=14]="InvalidUnicode",z[z.InvalidEscapeCharacter=15]="InvalidEscapeCharacter",z[z.InvalidCharacter=16]="InvalidCharacter"})(q||(J.ParseErrorCode=q={}));function D(z){switch(z){case 1:return"InvalidSymbol";case 2:return"InvalidNumberFormat";case 3:return"PropertyNameExpected";case 4:return"ValueExpected";case 5:return"ColonExpected";case 6:return"CommaExpected";case 7:return"CloseBraceExpected";case 8:return"CloseBracketExpected";case 9:return"EndOfFileExpected";case 10:return"InvalidCommentToken";case 11:return"UnexpectedEndOfComment";case 12:return"UnexpectedEndOfString";case 13:return"UnexpectedEndOfNumber";case 14:return"InvalidUnicode";case 15:return"InvalidEscapeCharacter";case 16:return"InvalidCharacter"}return"<unknown ParseErrorCode>"}J.printParseErrorCode=D;function m(z,U,j){return X.format(z,U,j)}J.format=m;function f(z,U,j,A){return Z.setProperty(z,U,j,A)}J.modify=f;function u(z,U){let j=U.slice(0).sort((I,Y)=>{let F=I.offset-Y.offset;if(F===0)return I.length-Y.length;return F}),A=z.length;for(let I=j.length-1;I>=0;I--){let Y=j[I];if(Y.offset+Y.length<=A)z=Z.applyEdit(z,Y);else throw Error("Overlapping edit");A=Y.offset}return z}J.applyEdits=u})});var M=P(g(),1);import{watch as K}from"node:fs";import{mkdir as c,readFile as O,rename as y,writeFile as S}from"node:fs/promises";import{homedir as E}from"node:os";import{basename as l,dirname as v,join as k}from"node:path";var p="OPENCODE_TUI_PREFERENCES_FILE",x="tui-preferences.jsonc";function w(){let Q=process.env[p];if(Q)return Q;let J=process.env.OPENCODE_CONFIG_DIR||k(process.env.XDG_CONFIG_HOME||k(E(),".config"),"opencode");return k(J,x)}function N(Q){return typeof Q==="object"&&Q!==null&&!Array.isArray(Q)}async function Xz(){try{let Q=await O(w(),"utf8"),J=[],X=M.parse(Q,J,{allowTrailingComma:!0});if(J.length>0)return{};return N(X)?X:{}}catch{return{}}}var i="openai-auth",s=160,b={forceToTop:!1,order:s,startCollapsed:!1,rememberCollapsed:!0,collapsed:null,pollMs:1500,refreshDebounceMs:200,header:{label:"OPENAI",showVersion:!0},sections:{quota:!0,fallbackAccounts:!0,routing:!0,health:!0,pacing:!0},appearance:{barWidth:10,barFilledChar:"█",barEmptyChar:"░",warnThreshold:50,errorThreshold:80}};function V(Q,J){return typeof Q==="boolean"?Q:J}function B(Q,J,X,Z){if(typeof Q!=="number"||!Number.isFinite(Q))return J;return Math.min(Math.max(Math.round(Q),X),Z)}function d(Q,J,X){if(typeof Q!=="string"||Q.length===0)return J;return Q.slice(0,X)}function h(Q,J){if(typeof Q!=="string")return J;return[...Q][0]??J}function Zz(Q){let J=Q[i];if(!N(J))return structuredClone(b);let X=b,Z=N(J.header)?J.header:{},G=N(J.sections)?J.sections:{},$=N(J.appearance)?J.appearance:{},W=B($.warnThreshold,X.appearance.warnThreshold,0,99),H=Math.max(B($.errorThreshold,X.appearance.errorThreshold,0,100),Math.min(W+1,100));return{forceToTop:V(J.forceToTop,X.forceToTop),order:B(J.order,X.order,-1e4,1e4),startCollapsed:V(J.startCollapsed,X.startCollapsed),rememberCollapsed:V(J.rememberCollapsed,X.rememberCollapsed),collapsed:typeof J.collapsed==="boolean"?J.collapsed:null,pollMs:B(J.pollMs,X.pollMs,500,30000),refreshDebounceMs:B(J.refreshDebounceMs,X.refreshDebounceMs,50,5000),header:{label:d(Z.label,X.header.label,20),showVersion:V(Z.showVersion,X.header.showVersion)},sections:{quota:V(G.quota,X.sections.quota),fallbackAccounts:V(G.fallbackAccounts,X.sections.fallbackAccounts),routing:V(G.routing,X.sections.routing),health:V(G.health,X.sections.health),pacing:V(G.pacing,X.sections.pacing)},appearance:{barWidth:B($.barWidth,X.appearance.barWidth,4,40),barFilledChar:h($.barFilledChar,X.appearance.barFilledChar),barEmptyChar:h($.barEmptyChar,X.appearance.barEmptyChar),warnThreshold:W,errorThreshold:H}}}var n=-1e5;function $z(Q,J,X){let Z=Q[J];if(!N(Z))return X;if(Z.forceToTop===!0)return n+Object.keys(Q).indexOf(J);return B(Z.order,X,-1e4,1e4)}var t=`// Shared preferences for opencode TUI plugins.
|
|
2
2
|
// One top-level key per plugin (short name). See each plugin's README for
|
|
3
3
|
// its supported settings. This file is safe to hand-edit; plugins update
|
|
4
4
|
// individual keys in place and preserve comments.
|
package/dist/version.d.ts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export declare const PackageVersion = "0.3.
|
|
1
|
+
export declare const PackageVersion = "0.3.1";
|
package/dist/ws-pool.d.ts
CHANGED
|
@@ -14,11 +14,12 @@ export interface CreateWebSocketFetchOptions {
|
|
|
14
14
|
/**
|
|
15
15
|
* Push per-turn quota from a codex.rate_limits in-band frame.
|
|
16
16
|
*
|
|
17
|
-
* Receives the snapshot plus the per-request account identity (access token
|
|
18
|
-
*
|
|
19
|
-
* connection's own account, not a
|
|
17
|
+
* Receives the snapshot plus the per-request account identity (access token,
|
|
18
|
+
* internal quota account key, and served ChatGPT account id) captured at send
|
|
19
|
+
* time so the frame is attributed to the connection's own account, not a
|
|
20
|
+
* shared mutable global.
|
|
20
21
|
*/
|
|
21
|
-
onQuota?: (s: Record<string, unknown>, accessToken: string, accountId: string | undefined) => void;
|
|
22
|
+
onQuota?: (s: Record<string, unknown>, accessToken: string, accountId: string | undefined, servedChatgptAccountId: string | undefined) => void;
|
|
22
23
|
}
|
|
23
24
|
interface PoolEntry {
|
|
24
25
|
socket?: WebSocket;
|
|
@@ -43,6 +44,8 @@ export declare function createWebSocketFetch(options?: CreateWebSocketFetchOptio
|
|
|
43
44
|
close: () => void;
|
|
44
45
|
remove: (sessionID: string) => void;
|
|
45
46
|
};
|
|
47
|
+
export declare const CODEX_BODY_KEY_ORDER: string[];
|
|
48
|
+
export declare function orderCodexBody(body: Record<string, unknown>): Record<string, unknown>;
|
|
46
49
|
export declare function applyTurnId(entry: PoolEntry, body: Record<string, unknown>, fullBody?: Record<string, unknown>): Record<string, unknown>;
|
|
47
50
|
export declare function withoutInternalHeaders<T extends {
|
|
48
51
|
headers?: HeadersInit;
|
package/package.json
CHANGED
package/src/logger.ts
CHANGED
|
@@ -1,4 +1,10 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import {
|
|
2
|
+
appendFileSync,
|
|
3
|
+
chmodSync,
|
|
4
|
+
existsSync,
|
|
5
|
+
renameSync,
|
|
6
|
+
statSync,
|
|
7
|
+
} from 'node:fs'
|
|
2
8
|
import { tmpdir } from 'node:os'
|
|
3
9
|
import { join } from 'node:path'
|
|
4
10
|
|
|
@@ -47,7 +53,7 @@ function isSecretKey(key: string): boolean {
|
|
|
47
53
|
return false
|
|
48
54
|
}
|
|
49
55
|
const TOKEN_VALUE = /\b(Bearer\s+[\w.-]+|sk-[\w-]+|eyJ[\w.-]+)\b/g
|
|
50
|
-
function redact(value: unknown): unknown {
|
|
56
|
+
export function redact(value: unknown): unknown {
|
|
51
57
|
return redactInner(value, new WeakSet<object>())
|
|
52
58
|
}
|
|
53
59
|
function redactInner(value: unknown, seen: WeakSet<object>): unknown {
|
|
@@ -75,14 +81,27 @@ function redactInner(value: unknown, seen: WeakSet<object>): unknown {
|
|
|
75
81
|
let buffer: string[] = []
|
|
76
82
|
let timer: ReturnType<typeof setTimeout> | undefined
|
|
77
83
|
const ROTATE_KEEP = 3
|
|
84
|
+
function chmodPrivate(path: string) {
|
|
85
|
+
try {
|
|
86
|
+
chmodSync(path, 0o600)
|
|
87
|
+
} catch {
|
|
88
|
+
/* never throw */
|
|
89
|
+
}
|
|
90
|
+
}
|
|
78
91
|
function rotateIfNeeded() {
|
|
79
92
|
try {
|
|
80
93
|
const f = logFile()
|
|
81
94
|
if (!(existsSync(f) && statSync(f).size > MAX_BYTES)) return
|
|
82
95
|
for (let i = ROTATE_KEEP - 1; i >= 1; i--) {
|
|
83
|
-
if (existsSync(`${f}.${i}`))
|
|
96
|
+
if (existsSync(`${f}.${i}`)) {
|
|
97
|
+
const rotated = `${f}.${i + 1}`
|
|
98
|
+
renameSync(`${f}.${i}`, rotated)
|
|
99
|
+
chmodPrivate(rotated)
|
|
100
|
+
}
|
|
84
101
|
}
|
|
85
|
-
|
|
102
|
+
const rotated = `${f}.1`
|
|
103
|
+
renameSync(f, rotated)
|
|
104
|
+
chmodPrivate(rotated)
|
|
86
105
|
} catch {
|
|
87
106
|
/* never throw */
|
|
88
107
|
}
|
|
@@ -93,7 +112,9 @@ function flush() {
|
|
|
93
112
|
buffer = []
|
|
94
113
|
try {
|
|
95
114
|
rotateIfNeeded()
|
|
96
|
-
|
|
115
|
+
const file = logFile()
|
|
116
|
+
if (existsSync(file)) chmodPrivate(file)
|
|
117
|
+
appendFileSync(file, text, { encoding: 'utf8', mode: 0o600 })
|
|
97
118
|
} catch {
|
|
98
119
|
/* never throw */
|
|
99
120
|
}
|
package/dist/index-1gjhrsep.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{$ as v}from"./index-88b7ha2h.js";import{randomUUID as O}from"node:crypto";import{mkdir as N,readFile as C,rename as g,rm as h,writeFile as k}from"node:fs/promises";import{tmpdir as L}from"node:os";import{dirname as D,join as R}from"node:path";var F=v("sidebar"),M="OPENCODE_OPENAI_AUTH_SIDEBAR_STATE_FILE",I=R(L(),"opencode-openai-auth"),f=R(I,"sidebar-state.json");function W(){return process.env[M]||f}var B={main:{quota:null,killed:!1},fallbacks:[],activeId:void 0,route:"main",lastUpdated:0};function b(K){if(K===null||typeof K!=="object"||Array.isArray(K))return B;let x=K,J=x.main,Q;if(J!==null&&typeof J==="object"&&!Array.isArray(J)){let H=J;Q={quota:"quota"in H?H.quota:null,killed:typeof H.killed==="boolean"?H.killed:!1,...typeof H.quotaBackedOff==="boolean"?{quotaBackedOff:H.quotaBackedOff}:{},...typeof H.quotaBackoffUntil==="number"?{quotaBackoffUntil:H.quotaBackoffUntil}:{},...typeof H.refreshBackedOff==="boolean"?{refreshBackedOff:H.refreshBackedOff}:{},...typeof H.refreshBackoffUntil==="number"?{refreshBackoffUntil:H.refreshBackoffUntil}:{}}}else Q={quota:null,killed:!1};let Y=x.fallbacks,X=Array.isArray(Y)?Y.filter((H)=>H!==null&&typeof H==="object"&&!Array.isArray(H)&&typeof H.id==="string").map((H)=>({id:H.id,label:typeof H.label==="string"?H.label:void 0,quota:"quota"in H?H.quota:null,killed:typeof H.killed==="boolean"?H.killed:!1,enabled:typeof H.enabled==="boolean"?H.enabled:!0})):[],Z=typeof x.activeId==="string"?x.activeId:void 0,V=typeof x.route==="string"?x.route:B.route,$=typeof x.lastUpdated==="number"?x.lastUpdated:0,j=typeof x.planType==="string"?x.planType:void 0,z=typeof x.credits==="number"?x.credits:void 0;return{main:Q,fallbacks:X,activeId:Z,route:V,lastUpdated:$,...j!==void 0?{planType:j}:{},...z!==void 0?{credits:z}:{}}}async function A(){try{let K=await C(W(),"utf8");return b(JSON.parse(K))}catch{return B}}var G=Promise.resolve();function m(K,x=W()){return G=G.then(()=>U(K,x)).catch(()=>{}),G}async function U(K,x){let J=`${x}.${O()}.tmp`;try{await N(D(x),{recursive:!0}),await k(J,JSON.stringify(K),"utf8"),await g(J,x)}catch(Q){await h(J,{force:!0}).catch(()=>{}),F.warn("sidebar write failed",{pid:process.pid,error:Q instanceof Error?Q.message:String(Q)})}}function w(){return G}function c(K){let x=K.activeId;if(x&&x!=="main"){let J=K.fallbacks.find((Q)=>Q.enabled&&Q.id===x);if(J)return{id:J.id,name:J.label??J.id,quota:J.quota,killed:J.killed}}return{id:"main",name:"main",quota:K.main.quota,killed:K.main.killed}}function l(K){let x=K?.primary?.usedPercent??null,J=K?.secondary?.usedPercent??null;if(x==null&&J==null)return{primaryUsedPercent:x,secondaryUsedPercent:J,text:null};return{primaryUsedPercent:x,secondaryUsedPercent:J,text:`5h: ${x==null?"—":`${Math.round(x)}%`} 7d: ${J==null?"—":`${Math.round(J)}%`}`}}var o=18000000,d=604800000,_=300000,y=0.01,S=1;function s(K,x,J){if(!K.resetsAt)return null;let Q=new Date(K.resetsAt).getTime();if(!Number.isFinite(Q))return null;let Y=Q-x,X=J-Y;if(X<_)return null;if(X<x*y)return null;if(X>=x)return null;let Z=K.usedPercent,V=Math.min(Math.max(X/x*100,0),100),$=Z-V,j=Math.abs($)<S?"on-pace":$>0?"deficit":"reserve",z=null;if(Z>0){let H=X*100/Z,q=Y+H;if(q<Q)z=new Date(q).toISOString()}return{pacePercent:V,deltaPercent:$,state:j,runsOutAt:z}}
|
|
2
|
-
export{W as P,B as Q,b as R,A as S,m as T,w as U,c as V,l as W,o as X,d as Y,s as Z};
|
package/dist/index-5j7p33r8.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
function A(b){if(b==null||b==="")return;let g=typeof b==="number"?b:Number(b);if(Number.isFinite(g)){let q=g<100000000000?g*1000:g,B=new Date(q);return Number.isNaN(B.getTime())?void 0:B.toISOString()}let z=new Date(b);return Number.isNaN(z.getTime())?void 0:z.toISOString()}function C(b,g){let z=b.get(g);if(z===null)return;let q=Number(z);if(!Number.isFinite(q)||q<0||q>100)return;return{usedPercent:q,remainingPercent:100-q,resetsAt:A(b.get(`${g.slice(0,-13)}-reset-at`)??void 0),checkedAt:Date.now()}}function G(b){let g={},z=C(b,"x-codex-primary-used-percent");if(z)g.primary=z;let q=C(b,"x-codex-secondary-used-percent");if(q)g.secondary=q;return g}function D(b){if(!b)return;if(!Number.isFinite(b.used_percent)||b.used_percent<0||b.used_percent>100)return;return{usedPercent:b.used_percent,remainingPercent:100-b.used_percent,resetsAt:A(b.reset_at),checkedAt:Date.now()}}function J(b){let g={},z=D(b.rate_limits?.primary);if(z)g.primary=z;let q=D(b.rate_limits?.secondary);if(q)g.secondary=q;return g}function E(b){if(!b)return;if(!Number.isFinite(b.used_percent)||b.used_percent<0||b.used_percent>100)return;return{usedPercent:b.used_percent,remainingPercent:100-b.used_percent,resetsAt:A(b.reset_at),checkedAt:Date.now()}}function K(b){let g={},z=E(b.rate_limit?.primary_window);if(z)g.primary=z;let q=E(b.rate_limit?.secondary_window);if(q)g.secondary=q;return g}
|
|
2
|
-
export{A as c,G as d,J as e,K as f};
|
package/dist/index-88b7ha2h.js
DELETED
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
import{appendFileSync as N,existsSync as U,renameSync as V,statSync as P}from"node:fs";import{tmpdir as X}from"node:os";import{join as Y}from"node:path";var $={error:0,warn:1,info:2,debug:3,trace:4},x=!1,C=5242880;function w(){return process.env.OPENCODE_OPENAI_AUTH_LOG_FILE??Y(X(),"opencode-openai-auth.log")}var B;function R(q){if(q===void 0||q in $)B=q}function F(){if(B)return B;let q=process.env.OPENCODE_OPENAI_AUTH_LOG_LEVEL;if(q&&q in $)return q;return"info"}var A=/^(authorization|x-api-key|cookie|set-cookie|refresh|access|token)$/i;function D(q){if(A.test(q))return!0;let H=q.toLowerCase().replace(/[-_]/g,"");if(H==="chatgptaccountid")return!0;if(H.includes("apikey"))return!0;if(H.endsWith("secret")||H.endsWith("password"))return!0;if(H.endsWith("token")&&!H.endsWith("tokens"))return!0;return!1}var I=/\b(Bearer\s+[\w.-]+|sk-[\w-]+|eyJ[\w.-]+)\b/g;function K(q){return G(q,new WeakSet)}function G(q,H){if(typeof q==="string")return q.replace(I,"***REDACTED***");if(Array.isArray(q)){if(H.has(q))return"[Circular]";H.add(q);let J=q.map((Q)=>G(Q,H));return H.delete(q),J}if(q&&typeof q==="object"){if(H.has(q))return"[Circular]";H.add(q);let J={};for(let[Q,j]of Object.entries(q))J[Q]=D(Q)?"***REDACTED***":G(j,H);return H.delete(q),J}return q}var Z=[],z,b=3;function p(){try{let q=w();if(!(U(q)&&P(q).size>C))return;for(let H=b-1;H>=1;H--)if(U(`${q}.${H}`))V(`${q}.${H}`,`${q}.${H+1}`);V(q,`${q}.1`)}catch{}}function M(){if(!Z.length)return;let q=Z.join("");Z=[];try{p(),N(w(),q)}catch{}}function L(){if(!z)z=setTimeout(()=>{z=void 0,M()},500)}if(!x)process.on("exit",M);function _(q){try{return` ${JSON.stringify(K(q))}`}catch{return" [unserializable]"}}function W(q,H,J,Q){if($[H]>$[F()])return;let j=`[${new Date().toISOString()}] ${H.toUpperCase()} [${q}] ${J}`+(Q===void 0?"":_(Q))+`
|
|
2
|
-
`;if(Z.push(j),Z.length>=50)M();else L()}function S(q){return{error:(H,J)=>W(q,"error",H,J),warn:(H,J)=>W(q,"warn",H,J),info:(H,J)=>W(q,"info",H,J),debug:(H,J)=>W(q,"debug",H,J),trace:(H,J)=>W(q,"trace",H,J)}}
|
|
3
|
-
export{R as _,S as $};
|
package/dist/index-pyyjg54f.js
DELETED
|
@@ -1,92 +0,0 @@
|
|
|
1
|
-
import{$ as x0}from"./index-88b7ha2h.js";import{ha as J3}from"./index-vj00ztg7.js";import{createHash as g0}from"node:crypto";var u0=86400000,i0=300000,s0=3600000,c0=60000,n0=900000,r0=300000;function a(B){return B instanceof Error?B.message:String(B)}function a0(B){let Z=B?.status;if(typeof Z==="number")return Z===429||Z>=500;if(!(B instanceof Error))return!1;return B.message.includes("fetch failed")||"code"in B&&(B.code==="ECONNRESET"||B.code==="ECONNREFUSED"||B.code==="ETIMEDOUT"||B.code==="UND_ERR_CONNECT_TIMEOUT")}function o(B){let Z=a(B),$=B?.status;if(typeof $==="number")return $===429||$>=500;if(!(B instanceof Error))return!1;let z=B.code;return Z.includes("fetch failed")||z==="ECONNRESET"||z==="ECONNREFUSED"||z==="ETIMEDOUT"||z==="UND_ERR_CONNECT_TIMEOUT"}function F0(B){return g0("sha256").update(B).digest("hex")}function L0(B){let Z=F0(B.refreshToken),z=(B.previous?.tokenHash===Z?B.previous.retryCount??0:0)+1,K,G=B.error?.retryAfter;if(typeof G==="number"&&G>0)K=G*1000;else if(a0(B.error))K=Math.min(s0,i0*2**Math.min(z-1,6));else K=u0;return{message:a(B.error),checkedAt:B.now,nextRetryAt:B.now+K,retryCount:z,tokenHash:Z}}function U(B,Z,$){if(!B?.nextRetryAt||B.nextRetryAt<=$)return!1;if(!Z)return!0;return B.tokenHash===F0(Z)}function l(B,Z){return`Codex OAuth refresh is backed off for ${Math.max(1,Math.ceil(((B.nextRetryAt??Z)-Z)/1000))}s after: ${B.message}`}function D0(B){let $=(B.previous?.retryCount??0)+1,z,K=B.error?.retryAfter;if(typeof K==="number"&&K>0)z=K*1000;else if(o(B.error))z=Math.min(n0,c0*2**Math.min($-1,6));else z=r0;return{message:a(B.error),checkedAt:B.now,nextRetryAt:B.now+z,retryCount:$}}function q0(B,Z){if(!B?.nextRetryAt||B.nextRetryAt<=Z)return!1;return!0}function t(B){if(!B)return;let Z=Number(B);if(Number.isFinite(Z)&&Z>0)return Math.ceil(Z);let $=Date.parse(B);if(Number.isFinite($)){let z=Math.ceil(($-Date.now())/1000);return z>0?z:void 0}return}import{createServer as o0}from"node:http";import{setTimeout as t0}from"node:timers/promises";var M0="0.3.0";var g="app_EMoamEEZ73f0CkXaXp7hrann",C="https://auth.openai.com",k=1455,e0=3000,_0=`cortexkit-opencode-openai-auth/${M0}`;function P0(B){let Z=new Uint8Array(B),$=String.fromCharCode(...Z);return btoa($).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function B3(){let Z=Array.from(crypto.getRandomValues(new Uint8Array(43))).map((z)=>"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~"[z%66]).join(""),$=P0(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(Z)));return{verifier:Z,challenge:$}}function O0(B){if(B.length>16384)return;let Z=B.split(".");if(Z.length!==3)return;let $=Z[1];if(!$||$.length>8192)return;try{return JSON.parse(Buffer.from($,"base64url").toString())}catch{return}}function U0(B){let Z=B.chatgpt_account_id;if(typeof Z==="string"&&Z.length>0)return Z;let $=B["https://api.openai.com/auth"];if($&&typeof $==="object"&&!Array.isArray($)&&typeof $.chatgpt_account_id==="string"&&$.chatgpt_account_id.length>0)return $.chatgpt_account_id;let z=B.organizations;if(Array.isArray(z)){let K=z[0];if(K&&typeof K==="object"&&!Array.isArray(K)&&typeof K.id==="string"&&K.id.length>0)return K.id}return}function T(B){if(B.id_token){let Z=O0(B.id_token),$=Z&&U0(Z);if($)return $}if(B.access_token){let Z=O0(B.access_token);return Z?U0(Z):void 0}return}function Z3(B,Z,$){let z=new URLSearchParams({response_type:"code",client_id:g,redirect_uri:B,scope:"openid profile email offline_access",code_challenge:Z.challenge,code_challenge_method:"S256",id_token_add_organizations:"true",codex_cli_simplified_flow:"true",state:$,originator:"opencode"});return`${C}/oauth/authorize?${z.toString()}`}async function $3(B,Z,$){let z=await fetch(`${C}/oauth/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",code:B,redirect_uri:Z,client_id:g,code_verifier:$.verifier}).toString()});if(!z.ok)throw Error(`Token exchange failed: ${z.status}`);return await z.json()}function z3(B){return B.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}var X3=`<!doctype html>
|
|
2
|
-
<html>
|
|
3
|
-
<head>
|
|
4
|
-
<title>CortexKit OpenAI Auth - Authorization Successful</title>
|
|
5
|
-
<style>
|
|
6
|
-
body {
|
|
7
|
-
font-family:
|
|
8
|
-
system-ui,
|
|
9
|
-
-apple-system,
|
|
10
|
-
sans-serif;
|
|
11
|
-
display: flex;
|
|
12
|
-
justify-content: center;
|
|
13
|
-
align-items: center;
|
|
14
|
-
height: 100vh;
|
|
15
|
-
margin: 0;
|
|
16
|
-
background: #131010;
|
|
17
|
-
color: #f1ecec;
|
|
18
|
-
}
|
|
19
|
-
.container {
|
|
20
|
-
text-align: center;
|
|
21
|
-
padding: 2rem;
|
|
22
|
-
}
|
|
23
|
-
h1 {
|
|
24
|
-
color: #f1ecec;
|
|
25
|
-
margin-bottom: 1rem;
|
|
26
|
-
}
|
|
27
|
-
p {
|
|
28
|
-
color: #b7b1b1;
|
|
29
|
-
}
|
|
30
|
-
</style>
|
|
31
|
-
</head>
|
|
32
|
-
<body>
|
|
33
|
-
<div class="container">
|
|
34
|
-
<h1>Authorization Successful</h1>
|
|
35
|
-
<p>You can close this window and return to OpenCode.</p>
|
|
36
|
-
</div>
|
|
37
|
-
<script>
|
|
38
|
-
setTimeout(() => window.close(), 2000)
|
|
39
|
-
</script>
|
|
40
|
-
</body>
|
|
41
|
-
</html>`,e=(B)=>`<!doctype html>
|
|
42
|
-
<html>
|
|
43
|
-
<head>
|
|
44
|
-
<title>CortexKit OpenAI Auth - Authorization Failed</title>
|
|
45
|
-
<style>
|
|
46
|
-
body {
|
|
47
|
-
font-family:
|
|
48
|
-
system-ui,
|
|
49
|
-
-apple-system,
|
|
50
|
-
sans-serif;
|
|
51
|
-
display: flex;
|
|
52
|
-
justify-content: center;
|
|
53
|
-
align-items: center;
|
|
54
|
-
height: 100vh;
|
|
55
|
-
margin: 0;
|
|
56
|
-
background: #131010;
|
|
57
|
-
color: #f1ecec;
|
|
58
|
-
}
|
|
59
|
-
.container {
|
|
60
|
-
text-align: center;
|
|
61
|
-
padding: 2rem;
|
|
62
|
-
}
|
|
63
|
-
h1 {
|
|
64
|
-
color: #fc533a;
|
|
65
|
-
margin-bottom: 1rem;
|
|
66
|
-
}
|
|
67
|
-
p {
|
|
68
|
-
color: #b7b1b1;
|
|
69
|
-
}
|
|
70
|
-
.error {
|
|
71
|
-
color: #ff917b;
|
|
72
|
-
font-family: monospace;
|
|
73
|
-
margin-top: 1rem;
|
|
74
|
-
padding: 1rem;
|
|
75
|
-
background: #3c140d;
|
|
76
|
-
border-radius: 0.5rem;
|
|
77
|
-
}
|
|
78
|
-
</style>
|
|
79
|
-
</head>
|
|
80
|
-
<body>
|
|
81
|
-
<div class="container">
|
|
82
|
-
<h1>Authorization Failed</h1>
|
|
83
|
-
<p>An error occurred during authorization.</p>
|
|
84
|
-
<div class="error">${z3(B)}</div>
|
|
85
|
-
</div>
|
|
86
|
-
</body>
|
|
87
|
-
</html>`,f,w,D=new Map;function _(){return D.size}function q(B){if(D.delete(B),_()===0)P()}async function G3(){let B=`http://localhost:${k}/auth/callback`;if(f)return{port:k,redirectUri:B};if(w)return w;w=(async()=>{let Z=o0(($,z)=>{let K=new URL($.url||"/",`http://127.0.0.1:${k}`);if(K.pathname==="/auth/callback"){let G=K.searchParams.get("code"),X=K.searchParams.get("state"),W=K.searchParams.get("error"),J=K.searchParams.get("error_description");if(W){let Q=J||W;if(X){let V=D.get(X);if(V)V.reject(Error(Q)),q(X);else if(_()===0)P()}else if(_()===0)P();z.writeHead(200,{"Content-Type":"text/html"}),z.end(e(Q));return}if(!G||!X){let Q=!G?"Missing authorization code":"Missing state parameter";if(X){let V=D.get(X);if(V)V.reject(Error(Q)),q(X);else if(_()===0)P()}else if(_()===0)P();z.writeHead(400,{"Content-Type":"text/html"}),z.end(e(Q));return}let Y=D.get(X);if(!Y){if(_()===0)P();z.writeHead(400,{"Content-Type":"text/html"}),z.end(e("Unknown state — authorization may have expired"));return}q(X),$3(G,B,Y.pkce).then((Q)=>Y.resolve(Q)).catch((Q)=>Y.reject(Q)),z.writeHead(200,{"Content-Type":"text/html"}),z.end(X3);return}if(K.pathname==="/cancel"){let G=K.searchParams.get("state"),X=G?[G]:[...D.keys()];z.writeHead(200),z.end("Login cancelled");for(let W of X){let J=D.get(W);if(!J)continue;J.reject(Error("Login cancelled")),q(W)}if(_()===0)P();return}z.writeHead(404),z.end("Not found")});return await new Promise(($,z)=>{Z.once("error",z),Z.listen(k,"127.0.0.1",()=>{Z.off("error",z),$()})}),f=Z,{port:k,redirectUri:B}})();try{return await w}finally{w=void 0}}function P(){if(f){let B=f;f=void 0,B.close(()=>{}),B.closeIdleConnections?.(),setTimeout(()=>{B.closeAllConnections?.()},25).unref?.()}}function K3(B,Z,$=300000,z){return new Promise((K,G)=>{if(z?.aborted){q(Z),G(Error("Login cancelled"));return}let X=setTimeout(()=>{if(D.get(Z))q(Z),G(Error("OAuth callback timeout — authorization took too long"))},$),W=()=>{if(clearTimeout(X),D.get(Z))q(Z),G(Error("Login cancelled"))};if(z)z.addEventListener("abort",W);D.set(Z,{pkce:B,state:Z,resolve:(J)=>{if(clearTimeout(X),z)z.removeEventListener("abort",W);K(J)},reject:(J)=>{if(clearTimeout(X),z)z.removeEventListener("abort",W);G(J)}})})}async function W3(){let B=await fetch(`${C}/api/accounts/deviceauth/usercode`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":_0},body:JSON.stringify({client_id:g})});if(!B.ok)throw Error("Failed to initiate device authorization");let Z=await B.json();return{deviceData:Z,url:`${C}/codex/device`,instructions:`Enter code: ${Z.user_code}`}}async function Y3(B,Z){let $=Math.max(parseInt(B.interval,10)||5,1)*1000,z=typeof B.expires_in==="number"?B.expires_in:parseInt(B.expires_in||"",10),K=!Number.isNaN(z)&&z>0?z*1000:900000,G=Date.now();while(!0){if(Z?.aborted)throw Error("Device authorization cancelled");if(Date.now()-G>K)throw Error("Device authorization expired");let X=await fetch(`${C}/api/accounts/deviceauth/token`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":_0},body:JSON.stringify({device_auth_id:B.device_auth_id,user_code:B.user_code})});if(X.ok){let Y=await X.json(),Q=await fetch(`${C}/oauth/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",code:Y.authorization_code,redirect_uri:`${C}/deviceauth/callback`,client_id:g,code_verifier:Y.code_verifier}).toString()});if(!Q.ok)throw Error(`Token exchange failed: ${Q.status}`);return await Q.json()}if(X.status!==403&&X.status!==404)throw Error(`Device authorization failed: ${X.status}`);let W=K-(Date.now()-G);if(W<=0)throw Error("Device authorization expired");let J=Math.min($+e0,W);try{await t0(J,void 0,{signal:Z})}catch(Y){if(Y instanceof Error&&Y.name==="AbortError")throw Error("Device authorization cancelled");throw Y}}}function TB(B,Z){let $=-1;if(Z.accountId)$=B.findIndex((z)=>z.accountId&&z.accountId===Z.accountId);if($<0)$=B.findIndex((z)=>z.id===Z.id);if($<0&&Z.label&&!Z.accountId)$=B.findIndex((z)=>z.label===Z.label);if($>=0)return B[$]={...B[$],...Z,addedAt:B[$]?.addedAt??Z.addedAt},$;return B.push(Z),B.length-1}async function EB(B={}){let{label:Z,headless:$=!1,signal:z}=B;if($){let{deviceData:Y,url:Q,instructions:V}=await W3(),F=(async()=>{let N=await Y3(Y,z),H=Date.now();return{id:Z||T(N)||crypto.randomUUID(),label:Z||void 0,type:"oauth",access:N.access_token,refresh:N.refresh_token,expires:H+(N.expires_in??3600)*1000,enabled:!0,addedAt:H,lastUsed:H,lastRefreshedAt:H,accountId:T(N)}})();return{url:Q,instructions:V,completion:F}}let{redirectUri:K}=await G3(),G=await B3(),X=P0(crypto.getRandomValues(new Uint8Array(32)).buffer),W=Z3(K,G,X),J=(async()=>{try{if(z?.aborted)throw Error("Login cancelled");let Y=await K3(G,X,void 0,z),Q=Date.now();return{id:Z||T(Y)||crypto.randomUUID(),label:Z||void 0,type:"oauth",access:Y.access_token,refresh:Y.refresh_token,expires:Q+(Y.expires_in??3600)*1000,enabled:!0,addedAt:Q,lastUsed:Q,lastRefreshedAt:Q,accountId:T(Y)}}finally{q(X)}})();return{url:W,instructions:"Complete authorization in your browser. This window will close automatically.",completion:J}}var u="primary",i="secondary",Q3="app_EMoamEEZ73f0CkXaXp7hrann",j3="https://auth.openai.com";async function xB(B){let Z=await B.fetchImpl(`${j3}/oauth/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"refresh_token",refresh_token:B.refreshToken,client_id:Q3}).toString()});if(!Z.ok){let z=t(Z.headers.get("retry-after"));throw Object.assign(Error(`Token refresh failed: ${Z.status}`),{status:Z.status,retryAfter:z,isRefreshError:!0})}let $=await Z.json();if(!$||typeof $.access_token!=="string"||!$.access_token||typeof $.refresh_token!=="string"||!$.refresh_token||typeof $.expires_in!=="number")throw Object.assign(Error("Token refresh failed: malformed response"),{status:Z.status,isRefreshError:!0});return{access:$.access_token,refresh:$.refresh_token,expires:B.now()+$.expires_in*1000,expiresIn:$.expires_in}}var N3="https://chatgpt.com/backend-api/wham/usage";async function kB(B){let Z=await B.fetchImpl(N3,{headers:{authorization:`Bearer ${B.accessToken}`,"chatgpt-account-id":B.accountId??"","oai-client-platform":"web","oai-client-version":"0","x-openai-target-path":"/backend-api/wham/usage"}});if(!Z.ok){let z=t(Z.headers.get("retry-after"));throw Object.assign(Error(`wham usage check failed: ${Z.status}`),{status:Z.status,retryAfter:z})}let{normalizeWham:$}=await import("./quota-normalize-s1bctr9a.js");return $(await Z.json())}import{randomUUID as B0}from"node:crypto";import{mkdir as V3,readFile as Z0,rename as H3,rm as m,stat as C0,writeFile as $0}from"node:fs/promises";import{homedir as b3}from"node:os";import{dirname as vB,join as h}from"node:path";var F3=globalThis.setTimeout.bind(globalThis),L3=globalThis.clearTimeout.bind(globalThis),D3="openai-auth.json";function q3(){if(process.env.OPENCODE_CONFIG_DIR?.trim())return process.env.OPENCODE_CONFIG_DIR.trim();return h(process.env.XDG_CONFIG_HOME||h(b3(),".config"),"opencode")}function M3(){return process.env.OPENCODE_OPENAI_AUTH_FILE?.trim()||h(q3(),D3)}async function s(B){let $=`${B.path??M3()}.${B.name}.lock`,z=h($,"owner.json"),K=B0(),G=B.now??Date.now,X=null,W=!1;async function J(){try{return JSON.parse(await Z0($,"utf8"))}catch(N){if(N.code!=="EISDIR")throw N;return JSON.parse(await Z0(z,"utf8"))}}async function Y(){await $0($,`${JSON.stringify({ownerId:K,expiresAt:G()+B.ttlMs})}
|
|
88
|
-
`,{encoding:"utf8",mode:384})}async function Q(){try{return await $0($,`${JSON.stringify({ownerId:K,expiresAt:G()+B.ttlMs})}
|
|
89
|
-
`,{encoding:"utf8",mode:384,flag:"wx"}),!0}catch(N){let H=N.code;if(H==="EEXIST"||H==="EISDIR")return!1;throw N}}function V(){if(!B.renew||W)return;let N=B.renewIntervalMs??Math.max(1000,Math.floor(B.ttlMs/3));if(X=F3(()=>{(async()=>{try{let H=await J(),v=G();if(W||H?.ownerId!==K||Number(H?.expiresAt)<=v)return;await Y(),V()}catch{}})()},N),"unref"in X)X.unref()}let F=await Q();if(!F){let N=`${$}.evicting`,H=h(N,"owner.json"),v=B0(),MB=5000,OB=8;async function d(){await new Promise((L)=>setTimeout(L,Math.floor(Math.random()*4)))}async function j0(){try{let L=await J();return Number(L?.expiresAt)>G()}catch{try{return(await C0($)).mtimeMs+B.ttlMs>G()}catch{return!1}}}async function A(){try{return JSON.parse(await Z0(H,"utf8"))?.ownerId===v}catch{return!1}}async function l0(){await V3(N);try{await $0(H,`${JSON.stringify({ownerId:v,createdAt:G()})}
|
|
90
|
-
`,{encoding:"utf8",mode:384,flag:"wx"})}catch(L){if(L.code==="ENOENT")return!1;throw await N0(),L}return await B.onStep?.("eviction-marker-acquired"),!0}async function N0(){if(await A())await m(N,{recursive:!0,force:!0}).catch(()=>{})}for(let L=0;L<8;L++){if(F=await Q(),F)break;if(await j0())return null;try{if(!await l0()){await d();continue}}catch(V0){if(V0.code!=="EEXIST")throw V0;let H0;try{H0=await C0(N)}catch(x){if(x.code==="ENOENT"){await d();continue}throw x}if(H0.mtimeMs+5000>G())return null;await B.onStep?.("stale-marker-stat");let b0=`${N}.${B0()}`;try{await H3(N,b0)}catch(x){if(x.code==="ENOENT"){await d();continue}throw x}await B.onStep?.("stale-marker-claimed"),await m(b0,{recursive:!0,force:!0}).catch(()=>{}),await d();continue}try{if(await j0())return null;if(!await A())return null;if(await B.onStep?.("stale-lock-confirmed"),!await A())return null;if(await m($,{recursive:!0,force:!0}).catch(()=>{}),!await A())return null;if(F=await Q(),!F)return null;if(!await A())return await m($,{recursive:!0,force:!0}).catch(()=>{}),F=!1,null;break}finally{await N0()}}}if(!F)return null;return V(),{release:async()=>{if(W=!0,X)L3(X),X=null;try{if((await J())?.ownerId!==K)return}catch{return}await m($,{recursive:!0,force:!0}).catch(()=>{})}}}import{createHash as R3,randomUUID as y3}from"node:crypto";import{homedir as T3}from"node:os";import{dirname as E3,join as c}from"node:path";import{setTimeout as S3}from"node:timers/promises";import{randomUUID as O3}from"node:crypto";import{mkdir as U3,rename as _3,rm as P3,writeFile as C3}from"node:fs/promises";import{dirname as I3}from"node:path";async function E(B,Z){await U3(I3(B),{recursive:!0});let $=`${B}.${O3()}.tmp`;await C3($,`${JSON.stringify(Z,null,2)}
|
|
91
|
-
`,{encoding:"utf8",mode:384});try{await _3($,B)}catch(z){throw await P3($,{force:!0}).catch(()=>{}),z}}import{readFile as d3}from"node:fs/promises";var I=x0("refresh"),I0=1e4,A3=50,k0="openai-auth.json",x3="openai-auth-state.json";function k3(){if(process.env.OPENCODE_CONFIG_DIR?.trim())return process.env.OPENCODE_CONFIG_DIR.trim();return c(process.env.XDG_CONFIG_HOME||c(T3(),".config"),"opencode")}function S(){return process.env.OPENCODE_OPENAI_AUTH_FILE?.trim()||c(k3(),k0)}function r(B=S()){let Z=process.env.OPENCODE_OPENAI_AUTH_STATE_FILE?.trim();if(Z)return Z;return w3(B)}function w3(B){return B.endsWith(k0)?c(E3(B),x3):`${B}.state.json`}function M(B){return B.type==="oauth"}function f3(B){let Z=B?.trim();if(!Z)return!1;try{let $=new URL(Z);return($.protocol==="http:"||$.protocol==="https:")&&!$.username&&!$.password}catch{return!1}}function $Z(B){return B.costZeroing?.enabled!==!1}var m3=[401,403,429],R0={primary:0,secondary:0},h3=!1,G0={primary:5,secondary:10};function j(B){return B!=null&&typeof B==="object"&&!Array.isArray(B)}function y0(B){return{id:typeof B.id==="string"&&B.id.trim()?B.id.trim():y3(),label:typeof B.label==="string"?B.label:void 0,enabled:typeof B.enabled==="boolean"?B.enabled:void 0,addedAt:typeof B.addedAt==="number"?B.addedAt:void 0,lastUsed:typeof B.lastUsed==="number"?B.lastUsed:void 0,accountId:typeof B.accountId==="string"?B.accountId:void 0}}function T0(B){if(!j(B))return;if(typeof B.message!=="string")return;let Z=Number(B.checkedAt);if(!Number.isFinite(Z))return;let $=Number(B.nextRetryAt),z=Number(B.retryCount);return{message:B.message,checkedAt:Z,nextRetryAt:Number.isFinite($)?$:void 0,retryCount:Number.isFinite(z)?z:void 0,tokenHash:typeof B.tokenHash==="string"?B.tokenHash:void 0}}function p3(B){if(!j(B))return;let Z={};for(let $ of["primary","secondary"]){let z=B[$];if(!j(z))continue;let K=Number(z.usedPercent),G=Number(z.remainingPercent),X=Number(z.checkedAt);if(!Number.isFinite(K)||!Number.isFinite(G)||!Number.isFinite(X))continue;Z[$]={usedPercent:K,remainingPercent:G,checkedAt:X,resetsAt:typeof z.resetsAt==="string"?z.resetsAt:void 0}}return Object.keys(Z).length?Z:void 0}function v3(B){if(!j(B))return null;if(B.type==="api"){let Z=typeof B.baseURL==="string"?B.baseURL.trim():"",$=typeof B.apiKey==="string"?B.apiKey.trim():"";if(!f3(Z))return null;let z=B.authHeader==="x-api-key"?"x-api-key":"authorization-bearer";return{...y0(B),type:"api",apiKey:$||void 0,baseURL:Z,authHeader:z}}if(B.type!=="oauth")return null;if(typeof B.refresh!=="string"||!B.refresh.trim())return null;return{...y0(B),type:"oauth",access:typeof B.access==="string"?B.access:void 0,refresh:B.refresh,expires:typeof B.expires==="number"?B.expires:void 0,lastRefreshedAt:typeof B.lastRefreshedAt==="number"?B.lastRefreshedAt:void 0,lastRefreshError:T0(B.lastRefreshError),lastQuotaRefreshError:T0(B.lastQuotaRefreshError),quota:p3(B.quota)}}function w0(B){if(!j(B)||!Array.isArray(B.accounts))return null;return{version:1,main:{type:"opencode",provider:"openai"},routing:j(B.routing)?B.routing:void 0,fallbackOn:Array.isArray(B.fallbackOn)?B.fallbackOn.filter((Z)=>Number.isInteger(Z)):void 0,refresh:j(B.refresh)?B.refresh:void 0,quota:j(B.quota)?B.quota:void 0,dump:j(B.dump)?B.dump:void 0,costZeroing:j(B.costZeroing)?B.costZeroing:void 0,killswitch:j(B.killswitch)?B.killswitch:void 0,logging:j(B.logging)?B.logging:void 0,cachekeep:j(B.cachekeep)?B.cachekeep:void 0,mainAccountId:typeof B.mainAccountId==="string"?B.mainAccountId:void 0,accounts:B.accounts.map(v3).filter((Z)=>Z!=null)}}async function y(B){try{return{exists:!0,value:JSON.parse(await d3(B,"utf8"))}}catch(Z){if(Z.code==="ENOENT")return{exists:!1,value:null};throw Z}}function O(B){return Object.fromEntries(Object.entries(B).filter(([,Z])=>Z!==void 0))}async function l3(B){let Z;try{Z=(await y(B)).value}catch{return null}if(!j(Z)||!Array.isArray(Z.accounts))return null;let $=new Set;for(let z of Z.accounts)if(j(z)&&typeof z.id==="string")$.add(z.id);return $}function f0(B,Z){if(!j(B))return B;let $=j(Z)?Z:{},z=j($.main)?$.main:void 0,K=j($.accounts)?$.accounts:{},G=j(B.quota)?B.quota:{},X=j(B.refresh)?B.refresh:{},W=z??G,J=z??X,Q=Array.isArray(B.accounts)?B.accounts.map((V)=>{if(!j(V))return V;let F=typeof V.id==="string"&&j(K[V.id])?K[V.id]:{};return{...V,...F}}):void 0;return m0({...B,refresh:O({...X,mainLastRefreshError:J.lastRefreshError,mainRefreshLeaseId:J.refreshLeaseId,mainRefreshLeaseUntil:J.refreshLeaseUntil,mainRefreshLeaseTokenHash:J.refreshLeaseTokenHash}),quota:O({...G,mainQuota:W.quota,mainQuotaCheckedAt:W.quotaCheckedAt,mainQuotaToken:W.quotaToken,mainLastQuotaApiError:W.lastQuotaApiError}),accounts:Q})}async function g3(B=S()){let Z=await y(B);if(!Z.exists)return null;let $=await y(r(B));return w0(f0(Z.value,$.value))}function m0(B){return Object.fromEntries(Object.entries(B).filter(([,Z])=>Z!==void 0))}function u3(B){return O({id:B.id,label:B.label,type:B.type,enabled:B.enabled,addedAt:B.addedAt,accountId:B.accountId,baseURL:B.type==="api"?B.baseURL:void 0,authHeader:B.type==="api"?B.authHeader:void 0})}function h0(B){if(B.type==="api")return O({apiKey:B.apiKey,lastUsed:B.lastUsed});return O({access:B.access,refresh:B.refresh,expires:B.expires,lastUsed:B.lastUsed,lastRefreshedAt:B.lastRefreshedAt,lastRefreshError:B.lastRefreshError,lastQuotaRefreshError:B.lastQuotaRefreshError,quota:B.quota})}function n(B){return Math.max(B?.primary?.checkedAt??0,B?.secondary?.checkedAt??0)}function p(B,Z,$){if($ in Z)B[$]=Z[$];else delete B[$]}function i3(B,Z){return B.access===Z.access&&B.refresh===Z.refresh&&B.expires===Z.expires&&B.lastRefreshedAt===Z.lastRefreshedAt}function s3(B,Z){if(!i3(B,Z))return Z;if(!("lastRefreshError"in Z))return B;if(!("lastRefreshError"in B))return Z;return(Z.lastRefreshError?.checkedAt??0)>(B.lastRefreshError?.checkedAt??0)?Z:B}function c3(B,Z,$){let z=Z.lastRefreshedAt??0,K=$.lastRefreshedAt??0,G=Z.expires??0,X=$.expires??0,W=K>z?$:z>K?Z:X>G?$:G>X?Z:s3(Z,$);p(B,W,"access"),p(B,W,"refresh"),p(B,W,"expires"),p(B,W,"lastRefreshedAt"),p(B,W,"lastRefreshError")}function n3(B,Z){if(!j(B))return Z;let $=B,z=n($.quota),K=n(Z.quota),G=z>K,X=G?{...$,...Z,quota:$.quota,lastQuotaRefreshError:$.lastQuotaRefreshError}:{...$,...Z};if(!G&&!("lastQuotaRefreshError"in Z))delete X.lastQuotaRefreshError;if(!("lastRefreshError"in Z))delete X.lastRefreshError;if(typeof $.lastUsed==="number"&&(typeof Z.lastUsed!=="number"||$.lastUsed>Z.lastUsed))X.lastUsed=$.lastUsed;return c3(X,$,Z),X}function p0(B){let Z=B.refresh?O({enabled:B.refresh.enabled,intervalMinutes:B.refresh.intervalMinutes,refreshBeforeExpiryMinutes:B.refresh.refreshBeforeExpiryMinutes}):void 0,$=B.quota?O({enabled:B.quota.enabled,checkIntervalMinutes:B.quota.checkIntervalMinutes,refreshEveryNRequests:B.quota.refreshEveryNRequests,minimumRemaining:B.quota.minimumRemaining,failClosedOnUnknownQuota:B.quota.failClosedOnUnknownQuota,showToasts:B.quota.showToasts}):void 0;return m0({version:1,main:B.main,routing:B.routing,fallbackOn:B.fallbackOn,refresh:Z,quota:$,dump:B.dump,costZeroing:B.costZeroing,killswitch:B.killswitch,logging:B.logging,cachekeep:B.cachekeep,mainAccountId:B.mainAccountId,accounts:B.accounts.map(u3)})}async function K0(B){let Z=Date.now()+I0;while(Date.now()<=Z){let $=await s({name:"save",ttlMs:I0,path:B});if($)return $;let z=Z-Date.now();if(z<=0)break;await S3(Math.min(A3,z))}throw Error(`Timed out acquiring account store lock for ${B}; refusing to overwrite newer account data`)}function v0(B){let Z=Object.fromEntries(B.accounts.map(($)=>[$.id,h0($)]));return{version:1,main:O({quota:B.quota?.mainQuota,quotaCheckedAt:B.quota?.mainQuotaCheckedAt,quotaToken:B.quota?.mainQuotaToken,lastQuotaApiError:B.quota?.mainLastQuotaApiError,lastRefreshError:B.refresh?.mainLastRefreshError,refreshLeaseId:B.refresh?.mainRefreshLeaseId,refreshLeaseUntil:B.refresh?.mainRefreshLeaseUntil,refreshLeaseTokenHash:B.refresh?.mainRefreshLeaseTokenHash}),accounts:Z}}async function XZ(B,Z=S()){let $=r(Z),z=await K0(Z);try{let K=await K0($);try{let G=await y(Z),X=await y($),W=(G.exists?w0(f0(G.value,X.value)):null)??r3(),J=B(W)??W,Q={...j(G.value)?G.value:{},...p0(J)};return await E(Z,Q),await E($,v0(J)),J}finally{await K.release()}}finally{await z.release()}}function r3(){return{version:1,main:{type:"opencode",provider:"openai"},accounts:[]}}function a3(B,Z){B.main=B.main??{};let $=typeof B.main.quotaCheckedAt==="number"?B.main.quotaCheckedAt:n(B.main.quota),z=typeof Z.quota?.mainQuotaCheckedAt==="number"?Z.quota.mainQuotaCheckedAt:n(Z.quota?.mainQuota);if($>z)return;B.main.quota=Z.quota?.mainQuota,B.main.quotaCheckedAt=Z.quota?.mainQuotaCheckedAt,B.main.quotaToken=Z.quota?.mainQuotaToken,B.main.lastQuotaApiError=Z.quota?.mainLastQuotaApiError}function o3(B,Z){B.main=B.main??{},B.main.lastRefreshError=Z.refresh?.mainLastRefreshError,B.main.refreshLeaseId=Z.refresh?.mainRefreshLeaseId,B.main.refreshLeaseUntil=Z.refresh?.mainRefreshLeaseUntil,B.main.refreshLeaseTokenHash=Z.refresh?.mainRefreshLeaseTokenHash}function W0(B){if(Array.isArray(B))return B.map(W0);if(!j(B))return B;return Object.fromEntries(Object.entries(B).filter(([,Z])=>Z!==void 0).map(([Z,$])=>[Z,W0($)]))}async function t3(B,Z=S(),$={mainQuota:!0,mainRefresh:!0,accounts:!0}){let z=r(Z),K=await K0(z);try{let G=(await y(z)).value,X=j(G)?{...G,version:1}:{version:1};if($.mainQuota)a3(X,B);if($.mainRefresh)o3(X,B);if($.accounts){let W=$.accounts===!0?null:new Set($.accounts),J=await l3(Z);X.accounts={...j(X.accounts)?X.accounts:{}};for(let Y of B.accounts){if(W&&!W.has(Y.id))continue;if(J&&!J.has(Y.id))continue;X.accounts[Y.id]=n3(X.accounts[Y.id],h0(Y))}if(W){for(let Y of W)if(!B.accounts.some((Q)=>Q.id===Y))delete X.accounts[Y]}if(J){for(let Y of Object.keys(X.accounts))if(!J.has(Y))delete X.accounts[Y]}}await E(z,W0(X))}finally{await K.release()}}function e3(B){return B?.fallbackOn?.length?B.fallbackOn:m3}function GZ(B,Z){return e3(Z).includes(B)}function BB(B){let Z=B?.quota?.minimumRemaining||{};return{primary:Z.primary??Z["5h"]??R0.primary,secondary:Z.secondary??Z["1w"]??R0.secondary}}function Y0(B){return B?.quota?.enabled!==!1}function Q0(B){return B?.quota?.failClosedOnUnknownQuota??h3}function d0(B,Z){if(!Y0(Z))return!0;let $=BB(Z);for(let z of["primary","secondary"]){let K=B?.[z];if(!K)return!Q0(Z);if(K.remainingPercent<$[z])return!1}return!0}function ZB(B){return B?.killswitch?.enabled===!0}function E0(B){return{primary:B?.primary??B?.["5h"]??G0.primary,secondary:B?.secondary??B?.["1w"]??G0.secondary}}function $B(B,Z){if(!B?.killswitch)return G0;if(Z&&B.killswitch.accounts?.[Z])return E0(B.killswitch.accounts[Z]);return E0(B.killswitch.main)}function KZ(B,Z,$){if(!ZB(Z))return!0;let z=$B(Z,$),K=!1;for(let G of["primary","secondary"]){let X=B?.[G];if(!X){K=!0;continue}if(X.remainingPercent<z[G])return!1}if(K)return!Q0(Z);return!0}function WZ(B,Z,$){let z=[],K=[B,...Z.map((X)=>X.quota)];for(let X of K)for(let W of["primary","secondary"]){let J=X?.[W]?.resetsAt;if(!J)continue;let Y=Date.parse(J);if(Number.isFinite(Y)&&Y>$)z.push(Y)}if(z.length===0)return 300;let G=Math.min(...z);return Math.max(1,Math.ceil((G-$)/1000))}function zB(B){return typeof B.version==="number"&&Array.isArray(B.accounts)}async function YZ(B,Z=S()){let $=await s({name:"migrate",ttlMs:30000,path:Z});if(!$)return;try{let z=await y(Z);if(z.exists&&j(z.value)){if(zB(z.value))return}if(!B)return;let K={version:1,main:{type:"opencode",provider:"openai"},accounts:[]};if(B.access){let W=T({id_token:"",access_token:B.access,refresh_token:B.refresh});if(W)K.mainAccountId=W}let X={...z.exists&&j(z.value)?z.value:{},...p0(K)};await E(Z,X),await E(r(Z),v0(K))}finally{await $.release()}}function XB(B){return B?.refresh?.enabled!==!1}function GB(B){return(B?.refresh?.refreshBeforeExpiryMinutes??240)*60000}function KB(B){return Math.floor(Math.random()*(B+1))}function R(B,Z,$){return!B.access||!B.expires||B.expires-$<=GB(Z)}function WB(B,Z){return Boolean(B.access&&typeof B.expires==="number"&&B.expires>Z)}function YB(B,Z){return Boolean(B.mainAccountId&&Z.accountId&&Z.accountId===B.mainAccountId)}function b(B,Z){let $=B.accounts.findIndex((z)=>z.id===Z.id);if($!==-1)B.accounts[$]=Z}function z0(B){return B instanceof Error?B.message:String(B)}function J0(B,Z,$){B.lastRefreshError=L0({error:Z,now:$,refreshToken:B.refresh,previous:B.lastRefreshError})}function X0(B,Z,$){if(B.lastQuotaRefreshError=D0({error:Z,now:$,previous:B.lastQuotaRefreshError}),Z?.isRefreshError===!0)J0(B,Z,$)}function JB(B){return`fallback-oauth-refresh-${R3("sha256").update(B).digest("base64url").slice(0,16)}`}function S0(B,Z){if(!B)return!1;if(!B.resetsAt)return!0;let $=Date.parse(B.resetsAt);return Number.isFinite($)?$>Z:!0}function QB(B,Z){if(!B)return!1;return S0(B[u],Z)||S0(B[i],Z)}function jB(B,Z,$){if(!B)return!1;let z=Z?.quota?.checkIntervalMinutes??5,K=Math.max(1,z)*60000,G=Math.max(B[u]?.checkedAt??0,B[i]?.checkedAt??0);return $-G<K}function A0(B,Z,$){return!jB(B.quota,Z,$)}function NB(B,Z,$,z){return o($)&&d0(B.quota,Z)&&QB(B.quota,z)}function VB(B){let Z=B?.quota?.checkIntervalMinutes??5;return Math.max(1,Z)*60000}var HB=60000,bB=60000,FB=600000,LB=1e4,DB=100;var JZ=globalThis.setTimeout.bind(globalThis),QZ=globalThis.clearTimeout.bind(globalThis);class qB{now;fetchImpl;configPath;refreshPromises=new Map;refreshTimer=null;quotaTimer=null;quotaManager;onFallbackStorageChanged;options;constructor(B={}){this.options=B,this.now=B.now??Date.now,this.fetchImpl=B.fetchImpl??fetch,this.configPath=B.configPath??S(),this.quotaManager=B.quotaManager??null,this.onFallbackStorageChanged=B.onFallbackStorageChanged}seedFallbackQuota(B,Z){if(!this.quotaManager)return;if(!B.quota)return;let $=Math.max(B.quota[u]?.checkedAt??0,B.quota[i]?.checkedAt??0);if($<=0)return;let z=this.quotaManager.getFallback(B.id,B.access);if(z&&z.checkedAt>=$)return;this.quotaManager.setFallback(B.id,{quota:B.quota,refreshAfter:$+VB(Z),checkedAt:$},B.access)}async load(){return g3(this.configPath)}async save(B,Z){await t3(B,this.configPath,{accounts:Z??!0})}startBackgroundRefresh(){let B=async()=>{if(await this.refreshDueAccounts(),this.options.fetchQuotaFn)await this.refreshQuotaForDueAccounts()};if(B().catch(()=>{}),!this.refreshTimer){if(this.refreshTimer=setInterval(()=>{B().catch(()=>{})},HB+KB(bB)),"unref"in this.refreshTimer)this.refreshTimer.unref()}}stopBackgroundRefresh(){if(this.refreshTimer)clearInterval(this.refreshTimer);if(this.quotaTimer)clearInterval(this.quotaTimer);this.refreshTimer=null,this.quotaTimer=null}async getUsableFallbackAccounts(B){let Z=B!==void 0?B:await this.load();if(!Z)return[];let $=[],z=!1;for(let K of Z.accounts){if(K.enabled===!1||!M(K))continue;if(YB(Z,K))continue;let G=!1,X=K;try{if(R(X,Z,this.now())){let W=X.lastRefreshError;if(W&&U(W,X.refresh,this.now()))throw G=!0,Error(l(W,this.now()));try{X=await this.refreshAccount(X,Z),z=!0}catch(J){G=!0;let Y=Z.accounts.find((Q)=>Q.id===K.id&&M(Q));if(Y&&!U(Y.lastRefreshError,Y.refresh,this.now()))J0(Y,J,this.now()),b(Z,Y),z=!0;throw J}}if(this.seedFallbackQuota(X,Z),this.accountPassesQuotaPolicy(this.quotaPolicyAccount(X),Z))$.push(X)}catch(W){let J=WB(X,this.now());if(G){if(!J)continue}else if(!J)continue;if(NB(X,Z,W,this.now()))I.debug("fallback quota using cached quota after refresh error",{pid:process.pid,accountId:X.id,error:z0(W)}),$.push(X);else if(!Q0(Z))$.push(X)}}if(z)await this.save(Z);return $}async markUsed(B){let Z=await this.load();if(!Z)return;let $=Z.accounts.find((z)=>z.id===B.id);if(!$)return;$.lastUsed=this.now(),await this.save(Z)}accountPassesQuotaPolicy(B,Z){return d0(B.quota,Z)}quotaPolicyAccount(B){if(!this.quotaManager)return B;let Z=this.quotaManager.getFallback(B.id,B.access)?.quota;return Z?{...B,quota:Z}:B}async refreshDueAccounts(){let B=await this.load();if(!B||!XB(B))return;let Z=!1;for(let $ of B.accounts){if($.enabled===!1||!M($))continue;if(!R($,B,this.now()))continue;if(U($.lastRefreshError,$.refresh,this.now()))continue;try{I.debug("fallback oauth background due",{pid:process.pid,accountId:$.id,expiresInMs:$.expires?$.expires-this.now():void 0}),await this.refreshAccount($,B),Z=!0}catch(z){I.warn("fallback oauth background failed",{pid:process.pid,accountId:$.id,error:z0(z)}),J0($,z,this.now()),b(B,$),Z=!0}}if(Z)await this.save(B)}async refreshQuotaForDueAccounts(){let B=await this.load();if(!B||!Y0(B))return;if(!this.options.fetchQuotaFn)return;let Z=!1;for(let $ of B.accounts){if($.enabled===!1||!M($))continue;let z=$;try{if(R(z,B,this.now())){if(U(z.lastRefreshError,z.refresh,this.now()))continue;z=await this.refreshAccount(z,B),Z=!0}if(q0(z.lastQuotaRefreshError,this.now()))continue;if(this.seedFallbackQuota(z,B),!(this.quotaManager?this.quotaManager.isFallbackStale(z.id,z.access):A0(z,B,this.now())))continue;await this.refreshAccountQuota(z,B),Z=!0}catch(K){X0($,K,this.now()),b(B,$),Z=!0}}if(Z)await this.save(B),this.onFallbackStorageChanged?.()}async refreshQuotaForAllAccounts(B={}){let Z=await this.load(),$=[];if(!Z||!Y0(Z))return{storage:Z,errors:$};if(!this.options.fetchQuotaFn)return{storage:Z,errors:$};let z=B.force??!1,K=!1;for(let G of Z.accounts){if(G.enabled===!1||!M(G))continue;let X=G;try{if(R(X,Z,this.now())){let W=X.lastRefreshError;if(W&&U(W,X.refresh,this.now()))throw Error(l(W,this.now()));X=await this.refreshAccount(X,Z),K=!0}if(!z&&!A0(X,Z,this.now())){if(X.lastQuotaRefreshError)X.lastQuotaRefreshError=void 0,b(Z,X),K=!0;continue}await this.refreshAccountQuota(X,Z),K=!0}catch(W){X0(G,W,this.now()),b(Z,G),K=!0,$.push({accountId:G.id,message:z0(W)})}}if(K)await this.save(Z);return{storage:Z,errors:$}}async refreshAccount(B,Z,$={}){let z=this.refreshPromises.get(B.id);if(z){let X=await z;return b(Z,X),X}let K=this.refreshAccountNow(B,Z,$).finally(()=>{this.refreshPromises.delete(B.id)});this.refreshPromises.set(B.id,K);let G=await K;return b(Z,G),G}async waitForConcurrentFallbackRefresh(B,Z,$,z){let K=Date.now()+LB;while(Date.now()<K){await new Promise((Y)=>setTimeout(Y,DB));let G=await this.load(),X=G?.accounts.find((Y)=>Y.id===B.id&&M(Y));if(!X)continue;if((X.access!==$.access||X.refresh!==$.refresh||(X.expires??0)>($.expires??0)+60000)&&(z.force||!R(X,G,this.now())))return b(Z,X),I.debug("fallback oauth joined concurrent refresh",{pid:process.pid,accountId:X.id,expiresInMs:X.expires?X.expires-this.now():void 0}),X;let J=X.lastRefreshError;if(J&&U(J,X.refresh,this.now()))throw b(Z,X),Error(l(J,this.now()))}return null}async refreshAccountNow(B,Z,$){let z=await this.load(),K=z?.accounts.find((W)=>W.id===B.id&&M(W));if(K&&!$.force&&!R(K,z,this.now()))return b(Z,K),K;let G=K??B,X=await s({name:JB(G.id),ttlMs:FB,path:this.configPath,now:this.now,renew:!0});if(!X){I.debug("fallback oauth refresh skipped file lock",{pid:process.pid,accountId:G.id});let W=await this.waitForConcurrentFallbackRefresh(B,Z,G,$);if(W)return W;throw Error("Fallback OAuth refresh is already in progress")}try{if(z=await this.load(),K=z?.accounts.find((Y)=>Y.id===B.id&&M(Y)),K&&!$.force&&!R(K,z,this.now()))return b(Z,K),K;G=K??G;let W=this.options.refreshFn??(async()=>{throw Error("No refreshFn injected into FallbackAccountManager")});I.debug("fallback oauth refresh request start",{pid:process.pid,accountId:G.id,force:$.force===!0,expiresInMs:G.expires?G.expires-this.now():void 0});let J=await W({refreshToken:G.refresh,fetchImpl:this.fetchImpl,now:this.now});return G.access=J.access,G.refresh=J.refresh,G.expires=J.expires,G.lastRefreshedAt=J.expires-J.expiresIn*1000,G.lastRefreshError=void 0,b(Z,G),await this.save(Z),I.debug("fallback oauth refresh succeeded",{pid:process.pid,accountId:G.id,expiresInMs:G.expires?G.expires-this.now():void 0}),G}finally{await X.release()}}async refreshAccountQuota(B,Z){let $=B;if(!$.access)throw Error(`Fallback account ${B.id} has no access token`);if(!this.options.fetchQuotaFn)throw Error("No fetchQuotaFn injected — wham/usage supplement is disabled");let z=this.options.fetchQuotaFn??(async()=>{throw Error("No fetchQuotaFn injected — wham/usage supplement is disabled")}),K=(G)=>this.quotaManager?this.quotaManager.refreshFallback($.id,G):z({accessToken:G,fetchImpl:this.fetchImpl,now:this.now});try{if(!$.access)throw Error(`Fallback account ${B.id} has no access token`);let G=await K($.access);$.quota=G,$.lastQuotaRefreshError=void 0,b(Z,$),await this.save(Z)}catch(G){throw X0(B,G,this.now()),b(Z,B),G}}}
|
|
92
|
-
export{F0 as g,L0 as h,U as i,l as j,D0 as k,q0 as l,_0 as m,P0 as n,B3 as o,O0 as p,U0 as q,T as r,Z3 as s,q as t,G3 as u,K3 as v,W3 as w,Y3 as x,TB as y,EB as z,xB as A,kB as B,s as C,S as D,M as E,$Z as F,G0 as G,g3 as H,XZ as I,GZ as J,ZB as K,KZ as L,WZ as M,YZ as N,qB as O};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{c as a,d as b,e as c,f as d}from"./index-5j7p33r8.js";import"./index-vj00ztg7.js";export{a as toResetIso,c as normalizeWsFrame,d as normalizeWham,b as normalizeQuotaHeaders};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{b as a}from"./index-r68prrfg.js";import"./index-vj00ztg7.js";export default a();
|