@cortexkit/opencode-openai-auth 0.1.4 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +7 -7
- package/dist/config.d.ts +3 -1
- package/dist/core/accounts.d.ts +17 -0
- package/dist/core/cachekeep.d.ts +3 -0
- package/dist/core/oauth.d.ts +10 -2
- package/dist/core/quota-manager.d.ts +21 -1
- package/dist/{index-hrg6bdgb.js → index-2b5wejq3.js} +1 -1
- package/dist/index-5j7p33r8.js +2 -0
- package/dist/index-8bx5ex97.js +2 -0
- package/dist/{index-6qjg8qfw.js → index-8xgff91h.js} +1 -1
- package/dist/index-garxs63s.js +3 -0
- package/dist/{index-eks9xm6s.js → index-mma66jx7.js} +1 -1
- package/dist/{index-dz7tcrxb.js → index-mxts9rp6.js} +1 -1
- package/dist/index-nzqvhshr.js +92 -0
- package/dist/index.js +65 -65
- package/dist/quota-normalize-dnaa90ct.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/rpc/rpc-server.d.ts +1 -0
- package/dist/sidebar-state.js +1 -1
- package/dist/token-util-xkawvxxx.js +1 -0
- package/dist/{token-zzzp7w2y.js → token-vyj9bxy1.js} +1 -1
- package/dist/tui-preferences.js +1 -1
- package/dist/version.d.ts +1 -1
- package/dist/ws-pool.d.ts +5 -1
- package/dist/ws.d.ts +9 -1
- package/package.json +1 -1
- package/src/rpc/rpc-server.ts +7 -0
- package/src/sidebar-state.ts +6 -2
- package/dist/index-0s5tftne.js +0 -3
- package/dist/index-jshhys8t.js +0 -2
- package/dist/index-m9dtkj3q.js +0 -92
- package/dist/index-sgfft5d3.js +0 -2
- package/dist/quota-normalize-qh5n0p7v.js +0 -1
- package/dist/token-util-sqwtzxz0.js +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{c as a,d as b,e as c,f as d}from"./index-5j7p33r8.js";import"./index-2b5wejq3.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{ba as a,ca as b}from"../index-mxts9rp6.js";import"../index-2b5wejq3.js";export{a as writePortFile,b as discoverPortFile};
|
package/dist/rpc/rpc-client.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{ca as c}from"../index-mxts9rp6.js";import"../index-2b5wejq3.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{da as a,ea as b}from"../index-mma66jx7.js";import"../index-2b5wejq3.js";export{a as tmpdir,b as getRpcDir};
|
package/dist/rpc/rpc-server.d.ts
CHANGED
|
@@ -9,5 +9,6 @@ export interface RpcServerOptions {
|
|
|
9
9
|
dir: string;
|
|
10
10
|
drain: typeof drainNotifications;
|
|
11
11
|
apply: (request: ApplyRequest) => Promise<ApplyResult>;
|
|
12
|
+
timeoutMs?: number;
|
|
12
13
|
}
|
|
13
14
|
export declare function startRpcServer(options: RpcServerOptions): Promise<RpcServerHandle>;
|
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-8bx5ex97.js";import"./index-garxs63s.js";import"./index-2b5wejq3.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};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{b as a}from"./index-8xgff91h.js";import"./index-2b5wejq3.js";export default a();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as U,b as V}from"./index-
|
|
1
|
+
import{a as U,b as V}from"./index-8xgff91h.js";import{ga as R}from"./index-2b5wejq3.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();
|
package/dist/tui-preferences.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{fa as P,ga as C,ia as _}from"./index-2b5wejq3.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.
|
|
1
|
+
export declare const PackageVersion = "0.2.0";
|
package/dist/ws-pool.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
export declare const TITLE_HEADER = "x-opencode-title";
|
|
2
|
+
export declare const QUOTA_ACCOUNT_HEADER = "x-openai-auth-quota-account";
|
|
2
3
|
export interface CreateWebSocketFetchOptions {
|
|
3
4
|
httpFetch?: typeof globalThis.fetch;
|
|
4
5
|
url?: string;
|
|
@@ -29,17 +30,20 @@ interface PoolEntry {
|
|
|
29
30
|
continuation?: ContinuationState;
|
|
30
31
|
turnID?: string;
|
|
31
32
|
turnStartedAt?: number;
|
|
33
|
+
turnInput?: unknown[];
|
|
34
|
+
turnSignature?: string;
|
|
32
35
|
}
|
|
33
36
|
interface ContinuationState {
|
|
34
37
|
responseID: string;
|
|
35
38
|
input: unknown[];
|
|
36
39
|
signature: string;
|
|
40
|
+
finalizedCallIds: Set<string>;
|
|
37
41
|
}
|
|
38
42
|
export declare function createWebSocketFetch(options?: CreateWebSocketFetchOptions): ((input: RequestInfo | URL, init?: RequestInit) => Promise<Response>) & {
|
|
39
43
|
close: () => void;
|
|
40
44
|
remove: (sessionID: string) => void;
|
|
41
45
|
};
|
|
42
|
-
export declare function applyTurnId(entry: PoolEntry, body: Record<string, unknown>): Record<string, unknown>;
|
|
46
|
+
export declare function applyTurnId(entry: PoolEntry, body: Record<string, unknown>, fullBody?: Record<string, unknown>): Record<string, unknown>;
|
|
43
47
|
export declare function withoutInternalHeaders<T extends {
|
|
44
48
|
headers?: HeadersInit;
|
|
45
49
|
}>(init: T | undefined): T | undefined;
|
package/dist/ws.d.ts
CHANGED
|
@@ -15,7 +15,15 @@ export interface StreamResponsesWebSocketOptions {
|
|
|
15
15
|
idleTimeout?: number;
|
|
16
16
|
signal?: AbortSignal;
|
|
17
17
|
onFirstEvent?: (error?: WrappedError) => void;
|
|
18
|
-
|
|
18
|
+
/**
|
|
19
|
+
* Fires on response.completed/response.done. `finalizedFunctionCallIds` is the
|
|
20
|
+
* set of function/custom tool call ids the response actually finalized (emitted
|
|
21
|
+
* a response.output_item.done for). The pool uses it to decide which suffix
|
|
22
|
+
* function_call items are safe to trim from a continuation: only those present
|
|
23
|
+
* in the chained response may be dropped — an unfinalized call (e.g. an aborted
|
|
24
|
+
* partial) must be kept inline or its function_call_output orphans → 400.
|
|
25
|
+
*/
|
|
26
|
+
onComplete?: (event: Record<string, unknown>, finalizedFunctionCallIds: Set<string>) => void;
|
|
19
27
|
onTerminal?: (event: Record<string, unknown>) => void;
|
|
20
28
|
onRetryableTerminal?: (event: Record<string, unknown>) => Promise<WebSocket | undefined>;
|
|
21
29
|
onConnectionInvalid?: (error: ResponseStreamError) => void;
|
package/package.json
CHANGED
package/src/rpc/rpc-server.ts
CHANGED
|
@@ -23,6 +23,7 @@ export interface RpcServerOptions {
|
|
|
23
23
|
dir: string
|
|
24
24
|
drain: typeof drainNotifications
|
|
25
25
|
apply: (request: ApplyRequest) => Promise<ApplyResult>
|
|
26
|
+
timeoutMs?: number
|
|
26
27
|
}
|
|
27
28
|
|
|
28
29
|
function readBody(req: IncomingMessage): Promise<string> {
|
|
@@ -54,9 +55,15 @@ export async function startRpcServer(
|
|
|
54
55
|
options: RpcServerOptions,
|
|
55
56
|
): Promise<RpcServerHandle> {
|
|
56
57
|
const token = randomBytes(32).toString('hex')
|
|
58
|
+
const timeoutMs = options.timeoutMs ?? 2000
|
|
57
59
|
const server = createServer((req, res) => {
|
|
60
|
+
req.setTimeout(timeoutMs, () => {
|
|
61
|
+
req.socket.destroy()
|
|
62
|
+
})
|
|
58
63
|
void dispatch(req, res)
|
|
59
64
|
})
|
|
65
|
+
server.requestTimeout = timeoutMs
|
|
66
|
+
server.headersTimeout = timeoutMs
|
|
60
67
|
|
|
61
68
|
async function dispatch(req: IncomingMessage, res: ServerResponse) {
|
|
62
69
|
const json = (status: number, value: unknown) => {
|
package/src/sidebar-state.ts
CHANGED
|
@@ -34,7 +34,8 @@ export interface SidebarState {
|
|
|
34
34
|
lastUpdated: number
|
|
35
35
|
}
|
|
36
36
|
|
|
37
|
-
import {
|
|
37
|
+
import { randomUUID } from 'node:crypto'
|
|
38
|
+
import { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises'
|
|
38
39
|
import { tmpdir } from 'node:os'
|
|
39
40
|
import { dirname, join } from 'node:path'
|
|
40
41
|
import { createLogger } from './logger'
|
|
@@ -188,10 +189,13 @@ async function doWriteSidebarState(
|
|
|
188
189
|
state: SidebarState,
|
|
189
190
|
file: string,
|
|
190
191
|
): Promise<void> {
|
|
192
|
+
const tempPath = `${file}.${randomUUID()}.tmp`
|
|
191
193
|
try {
|
|
192
194
|
await mkdir(dirname(file), { recursive: true })
|
|
193
|
-
await writeFile(
|
|
195
|
+
await writeFile(tempPath, JSON.stringify(state), 'utf8')
|
|
196
|
+
await rename(tempPath, file)
|
|
194
197
|
} catch (e) {
|
|
198
|
+
await rm(tempPath, { force: true }).catch(() => {})
|
|
195
199
|
logSb.warn('sidebar write failed', {
|
|
196
200
|
pid: process.pid,
|
|
197
201
|
error: e instanceof Error ? e.message : String(e),
|
package/dist/index-0s5tftne.js
DELETED
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
import{appendFileSync as k,existsSync as g,renameSync as p,statSync as w}from"node:fs";import{tmpdir as y}from"node:os";import{join as L}from"node:path";var s={error:0,warn:1,info:2,debug:3,trace:4},l=!1,m=5242880;function E(){return process.env.OPENCODE_OPENAI_AUTH_LOG_FILE??L(y(),"opencode-openai-auth.log")}var f;function x(n){if(n===void 0||n in s)f=n}function O(){if(f)return f;let n=process.env.OPENCODE_OPENAI_AUTH_LOG_LEVEL;if(n&&n in s)return n;return"info"}var T=/^(authorization|x-api-key|cookie|set-cookie|refresh|access|token)$/i;function _(n){if(T.test(n))return!0;let e=n.toLowerCase().replace(/[-_]/g,"");if(e.includes("apikey"))return!0;if(e.endsWith("secret")||e.endsWith("password"))return!0;if(e.endsWith("token")&&!e.endsWith("tokens"))return!0;return!1}var b=/\b(Bearer\s+[\w.-]+|sk-[\w-]+|eyJ[\w.-]+)\b/g;function h(n){return d(n,new WeakSet)}function d(n,e){if(typeof n==="string")return n.replace(b,"***REDACTED***");if(Array.isArray(n)){if(e.has(n))return"[Circular]";e.add(n);let t=n.map((r)=>d(r,e));return e.delete(n),t}if(n&&typeof n==="object"){if(e.has(n))return"[Circular]";e.add(n);let t={};for(let[r,u]of Object.entries(n))t[r]=_(r)?"***REDACTED***":d(u,e);return e.delete(n),t}return n}var o=[],c,S=3;function $(){try{let n=E();if(!(g(n)&&w(n).size>m))return;for(let e=S-1;e>=1;e--)if(g(`${n}.${e}`))p(`${n}.${e}`,`${n}.${e+1}`);p(n,`${n}.1`)}catch{}}function a(){if(!o.length)return;let n=o.join("");o=[];try{$(),k(E(),n)}catch{}}function A(){if(!c)c=setTimeout(()=>{c=void 0,a()},500)}if(!l)process.on("exit",a);function C(n){try{return` ${JSON.stringify(h(n))}`}catch{return" [unserializable]"}}function i(n,e,t,r){if(s[e]>s[O()])return;let u=`[${new Date().toISOString()}] ${e.toUpperCase()} [${n}] ${t}`+(r===void 0?"":C(r))+`
|
|
2
|
-
`;if(o.push(u),o.length>=50)a();else A()}function j(n){return{error:(e,t)=>i(n,"error",e,t),warn:(e,t)=>i(n,"warn",e,t),info:(e,t)=>i(n,"info",e,t),debug:(e,t)=>i(n,"debug",e,t),trace:(e,t)=>i(n,"trace",e,t)}}
|
|
3
|
-
export{x as X,j as Y};
|
package/dist/index-jshhys8t.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{Y as v}from"./index-0s5tftne.js";import{mkdir as h,readFile as O,writeFile as N}from"node:fs/promises";import{tmpdir as C}from"node:os";import{dirname as g,join as R}from"node:path";var k=v("sidebar"),L="OPENCODE_OPENAI_AUTH_SIDEBAR_STATE_FILE",D=R(C(),"opencode-openai-auth"),f=R(D,"sidebar-state.json");function W(){return process.env[L]||f}var B={main:{quota:null,killed:!1},fallbacks:[],activeId:void 0,route:"main",lastUpdated:0};function F(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 p(){try{let K=await O(W(),"utf8");return F(JSON.parse(K))}catch{return B}}var G=Promise.resolve();function u(K,x=W()){return G=G.then(()=>I(K,x)).catch(()=>{}),G}async function I(K,x){try{await h(g(x),{recursive:!0}),await N(x,JSON.stringify(K),"utf8")}catch(J){k.warn("sidebar write failed",{pid:process.pid,error:J instanceof Error?J.message:String(J)})}}function T(){return G}function E(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 A(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 m=18000000,c=604800000,M=300000,U=0.01,b=1;function w(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<M)return null;if(X<x*U)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($)<b?"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 M,B as N,F as O,p as P,u as Q,T as R,E as S,A as T,m as U,c as V,w as W};
|
package/dist/index-m9dtkj3q.js
DELETED
|
@@ -1,92 +0,0 @@
|
|
|
1
|
-
import{Y as y0}from"./index-0s5tftne.js";import{ea as K1}from"./index-hrg6bdgb.js";import{createHash as v0}from"node:crypto";var d0=86400000,l0=300000,g0=3600000,i0=60000,u0=900000,s0=300000;function r(B){return B instanceof Error?B.message:String(B)}function c0(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 a(B){let Z=r(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 N0(B){return v0("sha256").update(B).digest("hex")}function V0(B){let Z=N0(B.refreshToken),z=(B.previous?.tokenHash===Z?B.previous.retryCount??0:0)+1,G,X=B.error?.retryAfter;if(typeof X==="number"&&X>0)G=X*1000;else if(c0(B.error))G=Math.min(g0,l0*2**Math.min(z-1,6));else G=d0;return{message:r(B.error),checkedAt:B.now,nextRetryAt:B.now+G,retryCount:z,tokenHash:Z}}function I(B,Z,$){if(!B?.nextRetryAt||B.nextRetryAt<=$)return!1;if(!Z)return!0;return B.tokenHash===N0(Z)}function d(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 H0(B){let $=(B.previous?.retryCount??0)+1,z=a(B.error)?Math.min(u0,i0*2**Math.min($-1,6)):s0;return{message:r(B.error),checkedAt:B.now,nextRetryAt:B.now+z,retryCount:$}}function b0(B,Z){if(!B?.nextRetryAt||B.nextRetryAt<=Z)return!1;return!0}function o(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 n0}from"node:http";import{setTimeout as r0}from"node:timers/promises";var F0="0.1.4";var l="app_EMoamEEZ73f0CkXaXp7hrann",_="https://auth.openai.com",k=1455,a0=3000,M0=`cortexkit-opencode-openai-auth/${F0}`;function q0(B){let Z=new Uint8Array(B),$=String.fromCharCode(...Z);return btoa($).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function o0(){let Z=Array.from(crypto.getRandomValues(new Uint8Array(43))).map((z)=>"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~"[z%66]).join(""),$=q0(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(Z)));return{verifier:Z,challenge:$}}function D0(B){let Z=B.split(".");if(Z.length!==3)return;let $=Z[1];if(!$)return;try{return JSON.parse(Buffer.from($,"base64url").toString())}catch{return}}function L0(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 G=z[0];if(G&&typeof G==="object"&&!Array.isArray(G)&&typeof G.id==="string"&&G.id.length>0)return G.id}return}function R(B){if(B.id_token){let Z=D0(B.id_token),$=Z&&L0(Z);if($)return $}if(B.access_token){let Z=D0(B.access_token);return Z?L0(Z):void 0}return}function t0(B,Z,$){let z=new URLSearchParams({response_type:"code",client_id:l,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`${_}/oauth/authorize?${z.toString()}`}async function e0(B,Z,$){let z=await fetch(`${_}/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:l,code_verifier:$.verifier}).toString()});if(!z.ok)throw Error(`Token exchange failed: ${z.status}`);return await z.json()}function B1(B){return B.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}var Z1=`<!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>`,t=(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">${B1(B)}</div>
|
|
85
|
-
</div>
|
|
86
|
-
</body>
|
|
87
|
-
</html>`,f,m,L=new Map;function q(){return L.size}function y(B){if(L.delete(B),q()===0)O()}async function $1(){let B=`http://localhost:${k}/auth/callback`;if(f)return{port:k,redirectUri:B};if(m)return m;m=(async()=>{let Z=n0(($,z)=>{let G=new URL($.url||"/",`http://localhost:${k}`);if(G.pathname==="/auth/callback"){let X=G.searchParams.get("code"),K=G.searchParams.get("state"),J=G.searchParams.get("error"),W=G.searchParams.get("error_description");if(J){let Q=W||J;if(K){let V=L.get(K);if(V)V.reject(Error(Q)),y(K);else if(q()===0)O()}else if(q()===0)O();z.writeHead(200,{"Content-Type":"text/html"}),z.end(t(Q));return}if(!X||!K){let Q=!X?"Missing authorization code":"Missing state parameter";if(K){let V=L.get(K);if(V)V.reject(Error(Q)),y(K);else if(q()===0)O()}else if(q()===0)O();z.writeHead(400,{"Content-Type":"text/html"}),z.end(t(Q));return}let Y=L.get(K);if(!Y){if(q()===0)O();z.writeHead(400,{"Content-Type":"text/html"}),z.end(t("Unknown state — authorization may have expired"));return}y(K),e0(X,B,Y.pkce).then((Q)=>Y.resolve(Q)).catch((Q)=>Y.reject(Q)),z.writeHead(200,{"Content-Type":"text/html"}),z.end(Z1);return}if(G.pathname==="/cancel"){let X=G.searchParams.get("state"),K=X?[X]:[...L.keys()];z.writeHead(200),z.end("Login cancelled");for(let J of K){let W=L.get(J);if(!W)continue;W.reject(Error("Login cancelled")),y(J)}if(q()===0)O();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 m}finally{m=void 0}}function O(){if(f){let B=f;f=void 0,B.close(()=>{}),B.closeIdleConnections?.(),setTimeout(()=>{B.closeAllConnections?.()},25).unref?.()}}function z1(B,Z,$=300000){return new Promise((z,G)=>{let X=setTimeout(()=>{if(L.get(Z))y(Z),G(Error("OAuth callback timeout — authorization took too long"))},$);L.set(Z,{pkce:B,state:Z,resolve:(K)=>{clearTimeout(X),z(K)},reject:(K)=>{clearTimeout(X),G(K)}})})}async function X1(){let B=await fetch(`${_}/api/accounts/deviceauth/usercode`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":M0},body:JSON.stringify({client_id:l})});if(!B.ok)throw Error("Failed to initiate device authorization");let Z=await B.json();return{deviceData:Z,url:`${_}/codex/device`,instructions:`Enter code: ${Z.user_code}`}}async function G1(B,Z){let $=Math.max(parseInt(B.interval,10)||5,1)*1000;while(!0){if(Z?.aborted)throw Error("Device authorization cancelled");let z=await fetch(`${_}/api/accounts/deviceauth/token`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":M0},body:JSON.stringify({device_auth_id:B.device_auth_id,user_code:B.user_code})});if(z.ok){let G=await z.json(),X=await fetch(`${_}/oauth/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",code:G.authorization_code,redirect_uri:`${_}/deviceauth/callback`,client_id:l,code_verifier:G.code_verifier}).toString()});if(!X.ok)throw Error(`Token exchange failed: ${X.status}`);return await X.json()}if(z.status!==403&&z.status!==404)throw Error(`Device authorization failed: ${z.status}`);await r0($+a0)}}function L4(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 M4(B={}){let{label:Z,headless:$=!1,signal:z}=B;if($){let{deviceData:Y,url:Q,instructions:V}=await X1(),F=(async()=>{let N=await G1(Y,z),H=Date.now();return{id:Z||R(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,accountId:R(N)}})();return{url:Q,instructions:V,completion:F}}let{redirectUri:G}=await $1(),X=await o0(),K=q0(crypto.getRandomValues(new Uint8Array(32)).buffer),J=t0(G,X,K),W=(async()=>{try{if(z?.aborted)throw Error("Login cancelled");let Y=await z1(X,K),Q=Date.now();return{id:Z||R(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,accountId:R(Y)}}finally{y(K)}})();return{url:J,instructions:"Complete authorization in your browser. This window will close automatically.",completion:W}}var g="primary",i="secondary",J1="app_EMoamEEZ73f0CkXaXp7hrann",W1="https://auth.openai.com";async function _4(B){let Z=await B.fetchImpl(`${W1}/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:J1}).toString()});if(!Z.ok){let z=o(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();return{access:$.access_token,refresh:$.refresh_token,expires:$.expires_in?B.now()+$.expires_in*1000:0,expiresIn:$.expires_in??3600}}var Y1="https://chatgpt.com/backend-api/wham/usage";async function U4(B){let Z=await B.fetchImpl(Y1,{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=o(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-qh5n0p7v.js");return $(await Z.json())}import{randomUUID as e}from"node:crypto";import{mkdir as j1,readFile as B0,rename as Q1,rm as w,stat as O0,writeFile as Z0}from"node:fs/promises";import{homedir as N1}from"node:os";import{dirname as T4,join as h}from"node:path";var V1=globalThis.setTimeout.bind(globalThis),H1=globalThis.clearTimeout.bind(globalThis),b1="openai-auth.json";function F1(){if(process.env.OPENCODE_CONFIG_DIR?.trim())return process.env.OPENCODE_CONFIG_DIR.trim();return h(process.env.XDG_CONFIG_HOME||h(N1(),".config"),"opencode")}function D1(){return process.env.OPENCODE_OPENAI_AUTH_FILE?.trim()||h(F1(),b1)}async function u(B){let $=`${B.path??D1()}.${B.name}.lock`,z=h($,"owner.json"),G=e(),X=B.now??Date.now,K=null,J=!1;async function W(){try{return JSON.parse(await B0($,"utf8"))}catch(N){if(N.code!=="EISDIR")throw N;return JSON.parse(await B0(z,"utf8"))}}async function Y(){await Z0($,`${JSON.stringify({ownerId:G,expiresAt:X()+B.ttlMs})}
|
|
88
|
-
`,{encoding:"utf8",mode:384})}async function Q(){try{return await Z0($,`${JSON.stringify({ownerId:G,expiresAt:X()+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||J)return;let N=B.renewIntervalMs??Math.max(1000,Math.floor(B.ttlMs/3));if(K=V1(()=>{(async()=>{try{let H=await W(),p=X();if(J||H?.ownerId!==G||Number(H?.expiresAt)<=p)return;await Y(),V()}catch{}})()},N),"unref"in K)K.unref()}let F=await Q();if(!F){let N=`${$}.evicting`,H=h(N,"owner.json"),p=e(),Y4=5000,j4=8;async function v(){await new Promise((D)=>setTimeout(D,Math.floor(Math.random()*4)))}async function J0(){try{let D=await W();return Number(D?.expiresAt)>X()}catch{try{return(await O0($)).mtimeMs+B.ttlMs>X()}catch{return!1}}}async function x(){try{return JSON.parse(await B0(H,"utf8"))?.ownerId===p}catch{return!1}}async function p0(){await j1(N);try{await Z0(H,`${JSON.stringify({ownerId:p,createdAt:X()})}
|
|
90
|
-
`,{encoding:"utf8",mode:384,flag:"wx"})}catch(D){if(D.code==="ENOENT")return!1;throw await W0(),D}return await B.onStep?.("eviction-marker-acquired"),!0}async function W0(){if(await x())await w(N,{recursive:!0,force:!0}).catch(()=>{})}for(let D=0;D<8;D++){if(F=await Q(),F)break;if(await J0())return null;try{if(!await p0()){await v();continue}}catch(Y0){if(Y0.code!=="EEXIST")throw Y0;let j0;try{j0=await O0(N)}catch(A){if(A.code==="ENOENT"){await v();continue}throw A}if(j0.mtimeMs+5000>X())return null;await B.onStep?.("stale-marker-stat");let Q0=`${N}.${e()}`;try{await Q1(N,Q0)}catch(A){if(A.code==="ENOENT"){await v();continue}throw A}await B.onStep?.("stale-marker-claimed"),await w(Q0,{recursive:!0,force:!0}).catch(()=>{}),await v();continue}try{if(await J0())return null;if(!await x())return null;if(await B.onStep?.("stale-lock-confirmed"),!await x())return null;if(await w($,{recursive:!0,force:!0}).catch(()=>{}),!await x())return null;if(F=await Q(),!F)return null;if(!await x())return await w($,{recursive:!0,force:!0}).catch(()=>{}),F=!1,null;break}finally{await W0()}}}if(!F)return null;return V(),{release:async()=>{if(J=!0,K)H1(K),K=null;try{if((await W())?.ownerId!==G)return}catch{return}await w($,{recursive:!0,force:!0}).catch(()=>{})}}}import{createHash as C1,randomUUID as P1}from"node:crypto";import{homedir as I1}from"node:os";import{dirname as R1,join as s}from"node:path";import{setTimeout as y1}from"node:timers/promises";import{randomUUID as L1}from"node:crypto";import{mkdir as M1,rename as q1,rm as O1,writeFile as _1}from"node:fs/promises";import{dirname as U1}from"node:path";async function T(B,Z){await M1(U1(B),{recursive:!0});let $=`${B}.${L1()}.tmp`;await _1($,`${JSON.stringify(Z,null,2)}
|
|
91
|
-
`,{encoding:"utf8",mode:384});try{await q1($,B)}catch(z){throw await O1($,{force:!0}).catch(()=>{}),z}}import{readFile as h1}from"node:fs/promises";var U=y0("refresh"),_0=1e4,T1=50,T0="openai-auth.json",E1="openai-auth-state.json";function S1(){if(process.env.OPENCODE_CONFIG_DIR?.trim())return process.env.OPENCODE_CONFIG_DIR.trim();return s(process.env.XDG_CONFIG_HOME||s(I1(),".config"),"opencode")}function S(){return process.env.OPENCODE_OPENAI_AUTH_FILE?.trim()||s(S1(),T0)}function n(B=S()){let Z=process.env.OPENCODE_OPENAI_AUTH_STATE_FILE?.trim();if(Z)return Z;return x1(B)}function x1(B){return B.endsWith(T0)?s(R1(B),E1):`${B}.state.json`}function C(B){return B.type==="oauth"}function A1(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 u4(B){return B.costZeroing?.enabled!==!1}var k1=[401,403,429],U0={primary:0,secondary:0},m1=!1,s4={primary:5,secondary:10};function j(B){return B!=null&&typeof B==="object"&&!Array.isArray(B)}function C0(B){return{id:typeof B.id==="string"&&B.id.trim()?B.id.trim():P1(),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 P0(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 f1(B){if(!j(B))return;let Z={};for(let $ of["primary","secondary"]){let z=B[$];if(!j(z))continue;let G=Number(z.usedPercent),X=Number(z.remainingPercent),K=Number(z.checkedAt);if(!Number.isFinite(G)||!Number.isFinite(X)||!Number.isFinite(K))continue;Z[$]={usedPercent:G,remainingPercent:X,checkedAt:K,resetsAt:typeof z.resetsAt==="string"?z.resetsAt:void 0}}return Object.keys(Z).length?Z:void 0}function w1(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(!A1(Z))return null;let z=B.authHeader==="x-api-key"?"x-api-key":"authorization-bearer";return{...C0(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{...C0(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:P0(B.lastRefreshError),lastQuotaRefreshError:P0(B.lastQuotaRefreshError),quota:f1(B.quota)}}function E0(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(w1).filter((Z)=>Z!=null)}}async function E(B){try{return{exists:!0,value:JSON.parse(await h1(B,"utf8"))}}catch(Z){if(Z.code==="ENOENT")return{exists:!1,value:null};throw Z}}function M(B){return Object.fromEntries(Object.entries(B).filter(([,Z])=>Z!==void 0))}function S0(B,Z){if(!j(B))return B;let $=j(Z)?Z:{},z=j($.main)?$.main:void 0,G=j($.accounts)?$.accounts:{},X=j(B.quota)?B.quota:{},K=j(B.refresh)?B.refresh:{},J=z??X,W=z??K,Q=Array.isArray(B.accounts)?B.accounts.map((V)=>{if(!j(V))return V;let F=typeof V.id==="string"&&j(G[V.id])?G[V.id]:{};return{...V,...F}}):void 0;return x0({...B,refresh:M({...K,mainLastRefreshError:W.lastRefreshError,mainRefreshLeaseId:W.refreshLeaseId,mainRefreshLeaseUntil:W.refreshLeaseUntil,mainRefreshLeaseTokenHash:W.refreshLeaseTokenHash}),quota:M({...X,mainQuota:J.quota,mainQuotaCheckedAt:J.quotaCheckedAt,mainQuotaToken:J.quotaToken,mainLastQuotaApiError:J.lastQuotaApiError}),accounts:Q})}async function p1(B=S()){let Z=await E(B);if(!Z.exists)return null;let $=await E(n(B));return E0(S0(Z.value,$.value))}function x0(B){return Object.fromEntries(Object.entries(B).filter(([,Z])=>Z!==void 0))}function v1(B){return M({id:B.id,label:B.label,type:B.type,enabled:B.enabled,addedAt:B.addedAt,accountId:B.accountId,baseURL:B.type==="api"?B.baseURL:void 0,authHeader:B.type==="api"?B.authHeader:void 0})}function A0(B){if(B.type==="api")return M({apiKey:B.apiKey,lastUsed:B.lastUsed});return M({access:B.access,refresh:B.refresh,expires:B.expires,lastUsed:B.lastUsed,lastRefreshedAt:B.lastRefreshedAt,lastRefreshError:B.lastRefreshError,lastQuotaRefreshError:B.lastQuotaRefreshError,quota:B.quota})}function c(B){return Math.max(B?.primary?.checkedAt??0,B?.secondary?.checkedAt??0)}function d1(B,Z){if(!j(B))return Z;let $=B,z=c($.quota),G=c(Z.quota);if(z>G){let K=Boolean($.access&&Z.access&&$.access!==Z.access),J=$.lastRefreshedAt??0,W=Z.lastRefreshedAt??0;if(K&&W<=J){let Y={...$};if(typeof Z.lastUsed==="number"&&(typeof $.lastUsed!=="number"||Z.lastUsed>$.lastUsed))Y.lastUsed=Z.lastUsed;return Y}return{...$,...Z,quota:$.quota,lastQuotaRefreshError:$.lastQuotaRefreshError}}let X={...$,...Z};if(!("lastQuotaRefreshError"in Z))delete X.lastQuotaRefreshError;if(!("lastRefreshError"in Z))delete X.lastRefreshError;return X}function k0(B){let Z=B.refresh?M({enabled:B.refresh.enabled,intervalMinutes:B.refresh.intervalMinutes,refreshBeforeExpiryMinutes:B.refresh.refreshBeforeExpiryMinutes}):void 0,$=B.quota?M({enabled:B.quota.enabled,checkIntervalMinutes:B.quota.checkIntervalMinutes,refreshEveryNRequests:B.quota.refreshEveryNRequests,minimumRemaining:B.quota.minimumRemaining,failClosedOnUnknownQuota:B.quota.failClosedOnUnknownQuota,showToasts:B.quota.showToasts}):void 0;return x0({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(v1)})}function l1(B,Z){if(!B)return Z;let $=new Map;for(let z of B.accounts)$.set(z.id,z);for(let z of Z.accounts)$.set(z.id,z);return{...B,...Z,accounts:[...$.values()]}}async function X0(B){let Z=Date.now()+_0;while(Date.now()<=Z){let $=await u({name:"save",ttlMs:_0,path:B});if($)return $;let z=Z-Date.now();if(z<=0)break;await y1(Math.min(T1,z))}throw Error(`Timed out acquiring account store lock for ${B}; refusing to overwrite newer account data`)}function m0(B){let Z=Object.fromEntries(B.accounts.map(($)=>[$.id,A0($)]));return{version:1,main:M({quota:B.quota?.mainQuota,quotaCheckedAt:B.quota?.mainQuotaCheckedAt,quotaToken:B.quota?.mainQuotaToken,lastQuotaApiError:B.quota?.mainLastQuotaApiError,lastRefreshError:B.refresh?.mainLastRefreshError,refreshLeaseId:B.refresh?.mainRefreshLeaseId,refreshLeaseUntil:B.refresh?.mainRefreshLeaseUntil,refreshLeaseTokenHash:B.refresh?.mainRefreshLeaseTokenHash}),accounts:Z}}async function n4(B,Z=S()){let $=n(Z),z=await X0(Z);try{let G=await X0($);try{let X=await E(Z),K=await E($),J=X.exists?E0(S0(X.value,K.value)):null,W=l1(J,B),Q={...j(X.value)?X.value:{},...k0(W)};await T(Z,Q),await T($,m0(W))}finally{await G.release()}}finally{await z.release()}}function g1(B,Z){B.main=B.main??{};let $=typeof B.main.quotaCheckedAt==="number"?B.main.quotaCheckedAt:c(B.main.quota),z=typeof Z.quota?.mainQuotaCheckedAt==="number"?Z.quota.mainQuotaCheckedAt:c(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 i1(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 G0(B){if(Array.isArray(B))return B.map(G0);if(!j(B))return B;return Object.fromEntries(Object.entries(B).filter(([,Z])=>Z!==void 0).map(([Z,$])=>[Z,G0($)]))}async function u1(B,Z=S(),$={mainQuota:!0,mainRefresh:!0,accounts:!0}){let z=n(Z),G=await X0(z);try{let X=(await E(z)).value,K=j(X)?{...X,version:1}:{version:1};if($.mainQuota)g1(K,B);if($.mainRefresh)i1(K,B);if($.accounts){let J=$.accounts===!0?null:new Set($.accounts);K.accounts={...j(K.accounts)?K.accounts:{}};for(let W of B.accounts){if(J&&!J.has(W.id))continue;K.accounts[W.id]=d1(K.accounts[W.id],A0(W))}if(J){for(let W of J)if(!B.accounts.some((Y)=>Y.id===W))delete K.accounts[W]}}await T(z,G0(K))}finally{await G.release()}}function s1(B){return B?.fallbackOn?.length?B.fallbackOn:k1}function r4(B,Z){return s1(Z).includes(B)}function c1(B){let Z=B?.quota?.minimumRemaining||{};return{primary:Z.primary??Z["5h"]??U0.primary,secondary:Z.secondary??Z["1w"]??U0.secondary}}function K0(B){return B?.quota?.enabled!==!1}function f0(B){return B?.quota?.failClosedOnUnknownQuota??m1}function w0(B,Z){if(!K0(Z))return!0;let $=c1(Z);for(let z of["primary","secondary"]){let G=B?.[z];if(!G)return!f0(Z);if(G.remainingPercent<$[z])return!1}return!0}function n1(B){return typeof B.version==="number"&&Array.isArray(B.accounts)}async function a4(B,Z=S()){let $=await u({name:"migrate",ttlMs:30000,path:Z});if(!$)return;try{let z=await E(Z);if(z.exists&&j(z.value)){if(n1(z.value))return}if(!B)return;let G={version:1,main:{type:"opencode",provider:"openai"},accounts:[]};if(B.access){let J=R({id_token:"",access_token:B.access,refresh_token:B.refresh});if(J)G.mainAccountId=J}let K={...z.exists&&j(z.value)?z.value:{},...k0(G)};await T(Z,K),await T(n(Z),m0(G))}finally{await $.release()}}function r1(B){return B?.refresh?.enabled!==!1}function a1(B){return(B?.refresh?.refreshBeforeExpiryMinutes??240)*60000}function o1(B){return Math.floor(Math.random()*(B+1))}function P(B,Z,$){return!B.access||!B.expires||B.expires-$<=a1(Z)}function b(B,Z){let $=B.accounts.findIndex((z)=>z.id===Z.id);if($!==-1)B.accounts[$]=Z}function $0(B){return B instanceof Error?B.message:String(B)}function h0(B,Z,$){B.lastRefreshError=V0({error:Z,now:$,refreshToken:B.refresh,previous:B.lastRefreshError})}function z0(B,Z,$){if(B.lastQuotaRefreshError=H0({error:Z,now:$,previous:B.lastQuotaRefreshError}),Z?.isRefreshError===!0)h0(B,Z,$)}function t1(B){return`fallback-oauth-refresh-${C1("sha256").update(B).digest("base64url").slice(0,16)}`}function I0(B,Z){if(!B)return!1;if(!B.resetsAt)return!0;let $=Date.parse(B.resetsAt);return Number.isFinite($)?$>Z:!0}function e1(B,Z){if(!B)return!1;return I0(B[g],Z)||I0(B[i],Z)}function B4(B,Z,$){if(!B)return!1;let z=Z?.quota?.checkIntervalMinutes??5,G=Math.max(1,z)*60000,X=Math.max(B[g]?.checkedAt??0,B[i]?.checkedAt??0);return $-X<G}function R0(B,Z,$){return!B4(B.quota,Z,$)}function Z4(B,Z,$,z){return a($)&&w0(B.quota,Z)&&e1(B.quota,z)}function $4(B){let Z=B?.quota?.checkIntervalMinutes??5;return Math.max(1,Z)*60000}var z4=60000,X4=60000,G4=600000,K4=1e4,J4=100;var o4=globalThis.setTimeout.bind(globalThis),t4=globalThis.clearTimeout.bind(globalThis);class W4{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[g]?.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:$+$4(Z),checkedAt:$},B.access)}async load(){return p1(this.configPath)}async save(B,Z){await u1(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(()=>{})},z4+o1(X4)),"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 G of Z.accounts){if(G.enabled===!1||!C(G))continue;try{let X=G;if(P(X,Z,this.now())){let K=X.lastRefreshError;if(K&&I(K,X.refresh,this.now()))throw Error(d(K,this.now()));X=await this.refreshAccount(X,Z),z=!0}if(this.seedFallbackQuota(X,Z),this.accountPassesQuotaPolicy(this.quotaPolicyAccount(X),Z))$.push(X)}catch(X){if(Z4(G,Z,X,this.now()))U.debug("fallback quota using cached quota after refresh error",{pid:process.pid,accountId:G.id,error:$0(X)}),$.push(G);else if(!f0(Z))$.push(G)}}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 w0(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||!r1(B))return;let Z=!1;for(let $ of B.accounts){if($.enabled===!1||!C($))continue;if(!P($,B,this.now()))continue;if(I($.lastRefreshError,$.refresh,this.now()))continue;try{U.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){U.warn("fallback oauth background failed",{pid:process.pid,accountId:$.id,error:$0(z)}),h0($,z,this.now()),b(B,$),Z=!0}}if(Z)await this.save(B)}async refreshQuotaForDueAccounts(){let B=await this.load();if(!B||!K0(B))return;if(!this.options.fetchQuotaFn)return;let Z=!1;for(let $ of B.accounts){if($.enabled===!1||!C($))continue;let z=$;try{if(P(z,B,this.now())){if(I(z.lastRefreshError,z.refresh,this.now()))continue;z=await this.refreshAccount(z,B),Z=!0}if(b0(z.lastQuotaRefreshError,this.now()))continue;if(this.seedFallbackQuota(z,B),!(this.quotaManager?this.quotaManager.isFallbackStale(z.id,z.access):R0(z,B,this.now())))continue;await this.refreshAccountQuota(z,B),Z=!0}catch(G){z0($,G,this.now()),b(B,$),Z=!0}}if(Z)await this.save(B),this.onFallbackStorageChanged?.()}async refreshQuotaForAllAccounts(B={}){let Z=await this.load(),$=[];if(!Z||!K0(Z))return{storage:Z,errors:$};if(!this.options.fetchQuotaFn)return{storage:Z,errors:$};let z=B.force??!1,G=!1;for(let X of Z.accounts){if(X.enabled===!1||!C(X))continue;let K=X;try{if(P(K,Z,this.now())){let J=K.lastRefreshError;if(J&&I(J,K.refresh,this.now()))throw Error(d(J,this.now()));K=await this.refreshAccount(K,Z),G=!0}if(!z&&!R0(K,Z,this.now())){if(K.lastQuotaRefreshError)K.lastQuotaRefreshError=void 0,b(Z,K),G=!0;continue}await this.refreshAccountQuota(K,Z),G=!0}catch(J){z0(X,J,this.now()),b(Z,X),G=!0,$.push({accountId:X.id,message:$0(J)})}}if(G)await this.save(Z);return{storage:Z,errors:$}}async refreshAccount(B,Z,$={}){let z=this.refreshPromises.get(B.id);if(z){let K=await z;return b(Z,K),K}let G=this.refreshAccountNow(B,Z,$).finally(()=>{this.refreshPromises.delete(B.id)});this.refreshPromises.set(B.id,G);let X=await G;return b(Z,X),X}async waitForConcurrentFallbackRefresh(B,Z,$,z){let G=Date.now()+K4;while(Date.now()<G){await new Promise((Y)=>setTimeout(Y,J4));let X=await this.load(),K=X?.accounts.find((Y)=>Y.id===B.id&&C(Y));if(!K)continue;if((K.access!==$.access||K.refresh!==$.refresh||(K.expires??0)>($.expires??0)+60000)&&(z.force||!P(K,X,this.now())))return b(Z,K),U.debug("fallback oauth joined concurrent refresh",{pid:process.pid,accountId:K.id,expiresInMs:K.expires?K.expires-this.now():void 0}),K;let W=K.lastRefreshError;if(W&&I(W,K.refresh,this.now()))throw b(Z,K),Error(d(W,this.now()))}return null}async refreshAccountNow(B,Z,$){let z=await this.load(),G=z?.accounts.find((J)=>J.id===B.id&&C(J));if(G&&!$.force&&!P(G,z,this.now()))return b(Z,G),G;let X=G??B,K=await u({name:t1(X.id),ttlMs:G4,path:this.configPath,now:this.now,renew:!0});if(!K){U.debug("fallback oauth refresh skipped file lock",{pid:process.pid,accountId:X.id});let J=await this.waitForConcurrentFallbackRefresh(B,Z,X,$);if(J)return J;throw Error("Fallback OAuth refresh is already in progress")}try{if(z=await this.load(),G=z?.accounts.find((Y)=>Y.id===B.id&&C(Y)),G&&!$.force&&!P(G,z,this.now()))return b(Z,G),G;X=G??X;let J=this.options.refreshFn??(async()=>{throw Error("No refreshFn injected into FallbackAccountManager")});U.debug("fallback oauth refresh request start",{pid:process.pid,accountId:X.id,force:$.force===!0,expiresInMs:X.expires?X.expires-this.now():void 0});let W=await J({refreshToken:X.refresh,fetchImpl:this.fetchImpl,now:this.now});return X.access=W.access,X.refresh=W.refresh,X.expires=W.expires,X.lastRefreshedAt=W.expires-W.expiresIn*1000,X.lastRefreshError=void 0,b(Z,X),await this.save(Z),U.debug("fallback oauth refresh succeeded",{pid:process.pid,accountId:X.id,expiresInMs:X.expires?X.expires-this.now():void 0}),X}finally{await K.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")}),G=(X)=>this.quotaManager?this.quotaManager.refreshFallback($.id,X):z({accessToken:X,fetchImpl:this.fetchImpl,now:this.now});try{if(!$.access)throw Error(`Fallback account ${B.id} has no access token`);let X=await G($.access);$.quota=X,$.lastQuotaRefreshError=void 0,b(Z,$),await this.save(Z)}catch(X){throw z0(B,X,this.now()),b(Z,B),X}}}
|
|
92
|
-
export{N0 as g,V0 as h,I as i,d as j,H0 as k,b0 as l,M0 as m,q0 as n,o0 as o,D0 as p,L0 as q,R as r,t0 as s,y as t,$1 as u,z1 as v,X1 as w,G1 as x,L4 as y,M4 as z,_4 as A,U4 as B,u as C,S as D,C as E,u4 as F,s4 as G,p1 as H,n4 as I,r4 as J,a4 as K,W4 as L};
|
package/dist/index-sgfft5d3.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 z=g<100000000000?g*1000:g,B=new Date(z);return Number.isNaN(B.getTime())?void 0:B.toISOString()}let q=new Date(b);return Number.isNaN(q.getTime())?void 0:q.toISOString()}function C(b,g){let q=b.get(g);if(q===null)return;let z=Number(q);if(!Number.isFinite(z))return;return{usedPercent:z,remainingPercent:100-z,resetsAt:A(b.get(`${g.slice(0,-13)}-reset-at`)??void 0),checkedAt:Date.now()}}function G(b){let g={},q=C(b,"x-codex-primary-used-percent");if(q)g.primary=q;let z=C(b,"x-codex-secondary-used-percent");if(z)g.secondary=z;return g}function D(b){if(!b)return;if(!Number.isFinite(b.used_percent))return;return{usedPercent:b.used_percent,remainingPercent:100-b.used_percent,resetsAt:A(b.reset_at),checkedAt:Date.now()}}function J(b){let g={},q=D(b.rate_limits?.primary);if(q)g.primary=q;let z=D(b.rate_limits?.secondary);if(z)g.secondary=z;return g}function E(b){if(!b)return;if(!Number.isFinite(b.used_percent))return;return{usedPercent:b.used_percent,remainingPercent:100-b.used_percent,resetsAt:A(b.reset_at),checkedAt:Date.now()}}function K(b){let g={},q=E(b.rate_limit?.primary_window);if(q)g.primary=q;let z=E(b.rate_limit?.secondary_window);if(z)g.secondary=z;return g}
|
|
2
|
-
export{A as c,G as d,J as e,K as f};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{c as a,d as b,e as c,f as d}from"./index-sgfft5d3.js";import"./index-hrg6bdgb.js";export{a as toResetIso,c as normalizeWsFrame,d as normalizeWham,b as normalizeQuotaHeaders};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{b as a}from"./index-6qjg8qfw.js";import"./index-hrg6bdgb.js";export default a();
|