@cortexkit/opencode-openai-auth 0.2.0 → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +6 -6
- package/dist/cli.js +4 -4
- package/dist/core/accounts.d.ts +0 -1
- package/dist/core/oauth.d.ts +1 -1
- package/dist/index-1gjhrsep.js +2 -0
- package/dist/{index-garxs63s.js → index-88b7ha2h.js} +1 -1
- package/dist/{index-mxts9rp6.js → index-nngfcx1x.js} +1 -1
- package/dist/{index-mma66jx7.js → index-qqrj9za2.js} +1 -1
- package/dist/{index-8xgff91h.js → index-r68prrfg.js} +1 -1
- package/dist/{index-2b5wejq3.js → index-vj00ztg7.js} +1 -1
- package/dist/index-xftpnva2.js +92 -0
- package/dist/index.js +56 -62
- package/dist/{quota-normalize-dnaa90ct.js → quota-normalize-s1bctr9a.js} +1 -1
- 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-vyj9bxy1.js → token-c1q4pea2.js} +1 -1
- package/dist/token-util-ff59e4fw.js +1 -0
- package/dist/tui-preferences.js +1 -1
- package/dist/version.d.ts +1 -1
- package/package.json +3 -1
- package/src/logger.ts +140 -0
- package/src/tui/command-dialogs.tsx +3 -61
- package/src/util/error.ts +9 -0
- package/src/util/open-url.ts +30 -0
- package/src/util/proxy-env.ts +42 -0
- package/src/util/record.ts +3 -0
- package/src/util/stable-json.ts +15 -0
- package/src/util/uuid-v7.ts +18 -0
- package/dist/index-8bx5ex97.js +0 -2
- package/dist/index-nzqvhshr.js +0 -92
- package/dist/token-util-xkawvxxx.js +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import{c as a,d as b,e as c,f as d}from"./index-5j7p33r8.js";import"./index-
|
|
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};
|
package/dist/rpc/port-file.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{aa as a,ba as b}from"../index-nngfcx1x.js";import"../index-vj00ztg7.js";export{a as writePortFile,b as discoverPortFile};
|
package/dist/rpc/rpc-client.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{ba as c}from"../index-nngfcx1x.js";import"../index-vj00ztg7.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{ca as a,da as b}from"../index-qqrj9za2.js";import"../index-vj00ztg7.js";export{a as tmpdir,b as getRpcDir};
|
package/dist/sidebar-state.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{P as a,Q as b,R as c,S as d,T as e,U as f,V as g,W as h,X as i,Y as j,Z as k}from"./index-1gjhrsep.js";import"./index-88b7ha2h.js";import"./index-vj00ztg7.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-r68prrfg.js";import{fa as R}from"./index-vj00ztg7.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-r68prrfg.js";import"./index-vj00ztg7.js";export default a();
|
package/dist/tui-preferences.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{ea as P,fa as C,ha as _}from"./index-vj00ztg7.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.2.
|
|
1
|
+
export declare const PackageVersion = "0.2.1";
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cortexkit/opencode-openai-auth",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.1",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"repository": {
|
|
@@ -40,6 +40,8 @@
|
|
|
40
40
|
"src/tui/command-dialogs.tsx",
|
|
41
41
|
"src/sidebar-state.ts",
|
|
42
42
|
"src/tui-preferences.ts",
|
|
43
|
+
"src/logger.ts",
|
|
44
|
+
"src/util",
|
|
43
45
|
"src/rpc",
|
|
44
46
|
"README.md",
|
|
45
47
|
"LICENSE"
|
package/src/logger.ts
ADDED
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
import { appendFileSync, existsSync, renameSync, statSync } from 'node:fs'
|
|
2
|
+
import { tmpdir } from 'node:os'
|
|
3
|
+
import { join } from 'node:path'
|
|
4
|
+
|
|
5
|
+
type Level = 'error' | 'warn' | 'info' | 'debug' | 'trace'
|
|
6
|
+
const ORDER: Record<Level, number> = {
|
|
7
|
+
error: 0,
|
|
8
|
+
warn: 1,
|
|
9
|
+
info: 2,
|
|
10
|
+
debug: 3,
|
|
11
|
+
trace: 4,
|
|
12
|
+
}
|
|
13
|
+
const isTestEnv = process.env.NODE_ENV === 'test'
|
|
14
|
+
const MAX_BYTES = 5 * 1024 * 1024
|
|
15
|
+
|
|
16
|
+
function logFile(): string {
|
|
17
|
+
return (
|
|
18
|
+
process.env.OPENCODE_OPENAI_AUTH_LOG_FILE ??
|
|
19
|
+
join(tmpdir(), 'opencode-openai-auth.log')
|
|
20
|
+
)
|
|
21
|
+
}
|
|
22
|
+
let runtimeLevel: Level | undefined
|
|
23
|
+
export function setLogLevel(l: Level | undefined) {
|
|
24
|
+
if (l === undefined || l in ORDER) runtimeLevel = l
|
|
25
|
+
}
|
|
26
|
+
function configuredLevel(): Level {
|
|
27
|
+
if (runtimeLevel) return runtimeLevel
|
|
28
|
+
const env = process.env.OPENCODE_OPENAI_AUTH_LOG_LEVEL as Level | undefined
|
|
29
|
+
if (env && env in ORDER) return env
|
|
30
|
+
return 'info'
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
const SECRET_KEY_EXACT =
|
|
34
|
+
/^(authorization|x-api-key|cookie|set-cookie|refresh|access|token)$/i
|
|
35
|
+
function isSecretKey(key: string): boolean {
|
|
36
|
+
if (SECRET_KEY_EXACT.test(key)) return true
|
|
37
|
+
const k = key.toLowerCase().replace(/[-_]/g, '')
|
|
38
|
+
// Only the unambiguous ChatGPT stable id (chatgpt-account-id / chatgptAccountId)
|
|
39
|
+
// is sensitive. A bare `accountId` field is overloaded — most diagnostic logs put
|
|
40
|
+
// the INTERNAL account id/key ('main' or a fallback id) there, which is safe and
|
|
41
|
+
// needed for debugging — so it is intentionally NOT redacted by name. The genuine
|
|
42
|
+
// ChatGPT id is kept out of logs at the source instead.
|
|
43
|
+
if (k === 'chatgptaccountid') return true
|
|
44
|
+
if (k.includes('apikey')) return true
|
|
45
|
+
if (k.endsWith('secret') || k.endsWith('password')) return true
|
|
46
|
+
if (k.endsWith('token') && !k.endsWith('tokens')) return true
|
|
47
|
+
return false
|
|
48
|
+
}
|
|
49
|
+
const TOKEN_VALUE = /\b(Bearer\s+[\w.-]+|sk-[\w-]+|eyJ[\w.-]+)\b/g
|
|
50
|
+
function redact(value: unknown): unknown {
|
|
51
|
+
return redactInner(value, new WeakSet<object>())
|
|
52
|
+
}
|
|
53
|
+
function redactInner(value: unknown, seen: WeakSet<object>): unknown {
|
|
54
|
+
if (typeof value === 'string')
|
|
55
|
+
return value.replace(TOKEN_VALUE, '***REDACTED***')
|
|
56
|
+
if (Array.isArray(value)) {
|
|
57
|
+
if (seen.has(value)) return '[Circular]'
|
|
58
|
+
seen.add(value)
|
|
59
|
+
const arr = value.map((v) => redactInner(v, seen))
|
|
60
|
+
seen.delete(value)
|
|
61
|
+
return arr
|
|
62
|
+
}
|
|
63
|
+
if (value && typeof value === 'object') {
|
|
64
|
+
if (seen.has(value)) return '[Circular]'
|
|
65
|
+
seen.add(value)
|
|
66
|
+
const out: Record<string, unknown> = {}
|
|
67
|
+
for (const [k, v] of Object.entries(value))
|
|
68
|
+
out[k] = isSecretKey(k) ? '***REDACTED***' : redactInner(v, seen)
|
|
69
|
+
seen.delete(value)
|
|
70
|
+
return out
|
|
71
|
+
}
|
|
72
|
+
return value
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
let buffer: string[] = []
|
|
76
|
+
let timer: ReturnType<typeof setTimeout> | undefined
|
|
77
|
+
const ROTATE_KEEP = 3
|
|
78
|
+
function rotateIfNeeded() {
|
|
79
|
+
try {
|
|
80
|
+
const f = logFile()
|
|
81
|
+
if (!(existsSync(f) && statSync(f).size > MAX_BYTES)) return
|
|
82
|
+
for (let i = ROTATE_KEEP - 1; i >= 1; i--) {
|
|
83
|
+
if (existsSync(`${f}.${i}`)) renameSync(`${f}.${i}`, `${f}.${i + 1}`)
|
|
84
|
+
}
|
|
85
|
+
renameSync(f, `${f}.1`)
|
|
86
|
+
} catch {
|
|
87
|
+
/* never throw */
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
function flush() {
|
|
91
|
+
if (!buffer.length) return
|
|
92
|
+
const text = buffer.join('')
|
|
93
|
+
buffer = []
|
|
94
|
+
try {
|
|
95
|
+
rotateIfNeeded()
|
|
96
|
+
appendFileSync(logFile(), text)
|
|
97
|
+
} catch {
|
|
98
|
+
/* never throw */
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
function schedule() {
|
|
102
|
+
if (!timer)
|
|
103
|
+
timer = setTimeout(() => {
|
|
104
|
+
timer = undefined
|
|
105
|
+
flush()
|
|
106
|
+
}, 500)
|
|
107
|
+
}
|
|
108
|
+
if (!isTestEnv) process.on('exit', flush)
|
|
109
|
+
|
|
110
|
+
function safeSerialize(data: unknown): string {
|
|
111
|
+
try {
|
|
112
|
+
return ` ${JSON.stringify(redact(data))}`
|
|
113
|
+
} catch {
|
|
114
|
+
return ' [unserializable]'
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function emit(channel: string, level: Level, message: string, data?: unknown) {
|
|
119
|
+
if (ORDER[level] > ORDER[configuredLevel()]) return
|
|
120
|
+
const line =
|
|
121
|
+
`[${new Date().toISOString()}] ${level.toUpperCase()} [${channel}] ${message}` +
|
|
122
|
+
(data === undefined ? '' : safeSerialize(data)) +
|
|
123
|
+
'\n'
|
|
124
|
+
buffer.push(line)
|
|
125
|
+
if (buffer.length >= 50) flush()
|
|
126
|
+
else schedule()
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
export function createLogger(channel: string) {
|
|
130
|
+
return {
|
|
131
|
+
error: (m: string, d?: unknown) => emit(channel, 'error', m, d),
|
|
132
|
+
warn: (m: string, d?: unknown) => emit(channel, 'warn', m, d),
|
|
133
|
+
info: (m: string, d?: unknown) => emit(channel, 'info', m, d),
|
|
134
|
+
debug: (m: string, d?: unknown) => emit(channel, 'debug', m, d),
|
|
135
|
+
trace: (m: string, d?: unknown) => emit(channel, 'trace', m, d),
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
export async function flushForTest() {
|
|
139
|
+
flush()
|
|
140
|
+
}
|
|
@@ -341,10 +341,9 @@ function openAccountDialog(api: TuiPluginApi, apply: ApplyFn) {
|
|
|
341
341
|
showAddFlow()
|
|
342
342
|
return
|
|
343
343
|
}
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
}
|
|
344
|
+
// Main has no per-account actions (routing is mode-driven; main is
|
|
345
|
+
// not removable or reorderable) — the row is informational only.
|
|
346
|
+
if (option.value === 'main') return
|
|
348
347
|
showL2Fallback(option.value)
|
|
349
348
|
}}
|
|
350
349
|
/>
|
|
@@ -352,47 +351,6 @@ function openAccountDialog(api: TuiPluginApi, apply: ApplyFn) {
|
|
|
352
351
|
})
|
|
353
352
|
}
|
|
354
353
|
|
|
355
|
-
function showL2Main() {
|
|
356
|
-
void getSidebarState().then((state) => {
|
|
357
|
-
const DialogSelectInner = api.ui.DialogSelect<string>
|
|
358
|
-
const isActive = state.activeId === 'main' || !state.activeId
|
|
359
|
-
const options: Array<{
|
|
360
|
-
title: string
|
|
361
|
-
value: string
|
|
362
|
-
description: string
|
|
363
|
-
}> = []
|
|
364
|
-
if (!isActive) {
|
|
365
|
-
options.push({
|
|
366
|
-
title: 'Switch to main account',
|
|
367
|
-
value: 'switch',
|
|
368
|
-
description: 'Make main the active account',
|
|
369
|
-
})
|
|
370
|
-
}
|
|
371
|
-
options.push({
|
|
372
|
-
title: 'Back',
|
|
373
|
-
value: 'back',
|
|
374
|
-
description: 'Return to account list',
|
|
375
|
-
})
|
|
376
|
-
api.ui.dialog.setSize('xlarge')
|
|
377
|
-
api.ui.dialog.replace(() => (
|
|
378
|
-
<DialogSelectInner
|
|
379
|
-
title='Main account'
|
|
380
|
-
options={options}
|
|
381
|
-
onSelect={(option) => {
|
|
382
|
-
if (option.value === 'switch') {
|
|
383
|
-
void apply('openai-account', 'switch main').then((r) => {
|
|
384
|
-
api.ui.toast({ message: r.text })
|
|
385
|
-
showL1()
|
|
386
|
-
})
|
|
387
|
-
return
|
|
388
|
-
}
|
|
389
|
-
showL1()
|
|
390
|
-
}}
|
|
391
|
-
/>
|
|
392
|
-
))
|
|
393
|
-
})
|
|
394
|
-
}
|
|
395
|
-
|
|
396
354
|
function showL2Fallback(id: string) {
|
|
397
355
|
void getSidebarState().then((state) => {
|
|
398
356
|
const DialogSelectInner = api.ui.DialogSelect<string>
|
|
@@ -402,21 +360,12 @@ function openAccountDialog(api: TuiPluginApi, apply: ApplyFn) {
|
|
|
402
360
|
showL1()
|
|
403
361
|
return
|
|
404
362
|
}
|
|
405
|
-
const isActive = state.activeId === id
|
|
406
363
|
const options: Array<{
|
|
407
364
|
title: string
|
|
408
365
|
value: string
|
|
409
366
|
description: string
|
|
410
367
|
}> = []
|
|
411
368
|
|
|
412
|
-
if (!isActive) {
|
|
413
|
-
options.push({
|
|
414
|
-
title: 'Switch to this account',
|
|
415
|
-
value: 'switch',
|
|
416
|
-
description: 'Make this the active account',
|
|
417
|
-
})
|
|
418
|
-
}
|
|
419
|
-
|
|
420
369
|
options.push({
|
|
421
370
|
title: 'Remove',
|
|
422
371
|
value: 'remove',
|
|
@@ -457,13 +406,6 @@ function openAccountDialog(api: TuiPluginApi, apply: ApplyFn) {
|
|
|
457
406
|
title={fb.label ?? fb.id}
|
|
458
407
|
options={options}
|
|
459
408
|
onSelect={(option) => {
|
|
460
|
-
if (option.value === 'switch') {
|
|
461
|
-
void apply('openai-account', `switch ${id}`).then((r) => {
|
|
462
|
-
api.ui.toast({ message: r.text })
|
|
463
|
-
showL1()
|
|
464
|
-
})
|
|
465
|
-
return
|
|
466
|
-
}
|
|
467
409
|
if (option.value === 'remove') {
|
|
468
410
|
api.ui.dialog.setSize('xlarge')
|
|
469
411
|
api.ui.dialog.replace(() => (
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { execFileSync as defaultExecFileSync } from 'node:child_process'
|
|
2
|
+
|
|
3
|
+
type BrowserExec = (
|
|
4
|
+
file: string,
|
|
5
|
+
args: string[],
|
|
6
|
+
options: { stdio: 'ignore'; timeout: number },
|
|
7
|
+
) => unknown
|
|
8
|
+
|
|
9
|
+
export function openUrl(
|
|
10
|
+
url: string,
|
|
11
|
+
platform: NodeJS.Platform = process.platform,
|
|
12
|
+
execFileSync: BrowserExec = defaultExecFileSync,
|
|
13
|
+
) {
|
|
14
|
+
try {
|
|
15
|
+
if (platform === 'win32') {
|
|
16
|
+
execFileSync('cmd', ['/c', 'start', '', url], {
|
|
17
|
+
stdio: 'ignore',
|
|
18
|
+
timeout: 3000,
|
|
19
|
+
})
|
|
20
|
+
return
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
execFileSync(platform === 'darwin' ? 'open' : 'xdg-open', [url], {
|
|
24
|
+
stdio: 'ignore',
|
|
25
|
+
timeout: 3000,
|
|
26
|
+
})
|
|
27
|
+
} catch {
|
|
28
|
+
// Browser launch is best effort; the printed URL remains the fallback.
|
|
29
|
+
}
|
|
30
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
function proxyEnv(name: string) {
|
|
2
|
+
return process.env[name] ?? process.env[name.toLowerCase()]
|
|
3
|
+
}
|
|
4
|
+
|
|
5
|
+
function shouldBypassProxy(url: URL): boolean {
|
|
6
|
+
const noProxy = proxyEnv('NO_PROXY')
|
|
7
|
+
if (!noProxy) return false
|
|
8
|
+
|
|
9
|
+
const host = url.hostname.toLowerCase()
|
|
10
|
+
const entries = noProxy
|
|
11
|
+
.split(',')
|
|
12
|
+
.map((s) => s.trim().toLowerCase())
|
|
13
|
+
.filter(Boolean)
|
|
14
|
+
|
|
15
|
+
for (const entry of entries) {
|
|
16
|
+
if (entry === '*') return true
|
|
17
|
+
|
|
18
|
+
if (entry.startsWith('.')) {
|
|
19
|
+
if (host === entry.slice(1) || host.endsWith(entry)) {
|
|
20
|
+
return true
|
|
21
|
+
}
|
|
22
|
+
} else {
|
|
23
|
+
if (host === entry || host.endsWith(`.${entry}`)) {
|
|
24
|
+
return true
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
return false
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export function getProxyForUrl(url: string) {
|
|
33
|
+
const parsed = new URL(url)
|
|
34
|
+
if (shouldBypassProxy(parsed)) return undefined
|
|
35
|
+
|
|
36
|
+
if (parsed.protocol === 'http:') return proxyEnv('HTTP_PROXY')
|
|
37
|
+
if (parsed.protocol === 'https:')
|
|
38
|
+
return proxyEnv('HTTPS_PROXY') ?? proxyEnv('HTTP_PROXY')
|
|
39
|
+
return undefined
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export const ProxyEnv = { getProxyForUrl }
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { isRecord } from './record'
|
|
2
|
+
|
|
3
|
+
export function stableStringify(value: unknown): string {
|
|
4
|
+
return JSON.stringify(stable(value)) ?? 'undefined'
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
function stable(value: unknown): unknown {
|
|
8
|
+
if (Array.isArray(value)) return value.map(stable)
|
|
9
|
+
if (!isRecord(value)) return value
|
|
10
|
+
return Object.fromEntries(
|
|
11
|
+
Object.keys(value)
|
|
12
|
+
.sort()
|
|
13
|
+
.map((key) => [key, stable(value[key])]),
|
|
14
|
+
)
|
|
15
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
// Minimal UUIDv7 generator for Codex session/thread/turn identity parity.
|
|
2
|
+
export function uuidV7(): string {
|
|
3
|
+
const bytes = crypto.getRandomValues(new Uint8Array(16))
|
|
4
|
+
const ms = Date.now()
|
|
5
|
+
// 48-bit big-endian millisecond timestamp.
|
|
6
|
+
bytes[0] = (ms / 2 ** 40) & 0xff
|
|
7
|
+
bytes[1] = (ms / 2 ** 32) & 0xff
|
|
8
|
+
bytes[2] = (ms / 2 ** 24) & 0xff
|
|
9
|
+
bytes[3] = (ms / 2 ** 16) & 0xff
|
|
10
|
+
bytes[4] = (ms / 2 ** 8) & 0xff
|
|
11
|
+
bytes[5] = ms & 0xff
|
|
12
|
+
// Version 7 in the high nibble of byte 6.
|
|
13
|
+
bytes[6] = ((bytes[6] ?? 0) & 0x0f) | 0x70
|
|
14
|
+
// RFC 4122 variant (10xx) in the high bits of byte 8.
|
|
15
|
+
bytes[8] = ((bytes[8] ?? 0) & 0x3f) | 0x80
|
|
16
|
+
const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('')
|
|
17
|
+
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`
|
|
18
|
+
}
|
package/dist/index-8bx5ex97.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{aa as v}from"./index-garxs63s.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 Q,B as R,b as S,A as T,m as U,w as V,c as W,l as X,o as Y,d as Z,s as _};
|
package/dist/index-nzqvhshr.js
DELETED
|
@@ -1,92 +0,0 @@
|
|
|
1
|
-
import{aa as m0}from"./index-garxs63s.js";import{ia as J2}from"./index-2b5wejq3.js";import{createHash as g0}from"node:crypto";var u0=86400000,i0=300000,s0=3600000,c0=60000,n0=900000,r0=300000;function o(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 t(B){let Z=o(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 M0(B){return g0("sha256").update(B).digest("hex")}function O0(B){let Z=M0(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:o(B.error),checkedAt:B.now,nextRetryAt:B.now+K,retryCount:z,tokenHash:Z}}function P(B,Z,$){if(!B?.nextRetryAt||B.nextRetryAt<=$)return!1;if(!Z)return!0;return B.tokenHash===M0(Z)}function u(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 U0(B){let $=(B.previous?.retryCount??0)+1,z,K=B.error?.retryAfter;if(typeof K==="number"&&K>0)z=K*1000;else if(t(B.error))z=Math.min(n0,c0*2**Math.min($-1,6));else z=r0;return{message:o(B.error),checkedAt:B.now,nextRetryAt:B.now+z,retryCount:$}}function _0(B,Z){if(!B?.nextRetryAt||B.nextRetryAt<=Z)return!1;return!0}function e(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 P0="0.2.0";var i="app_EMoamEEZ73f0CkXaXp7hrann",R="https://auth.openai.com",k=1455,e0=3000,R0=`cortexkit-opencode-openai-auth/${P0}`;function y0(B){let Z=new Uint8Array(B),$=String.fromCharCode(...Z);return btoa($).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function B2(){let Z=Array.from(crypto.getRandomValues(new Uint8Array(43))).map((z)=>"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~"[z%66]).join(""),$=y0(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(Z)));return{verifier:Z,challenge:$}}function C0(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 I0(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 S(B){if(B.id_token){let Z=C0(B.id_token),$=Z&&I0(Z);if($)return $}if(B.access_token){let Z=C0(B.access_token);return Z?I0(Z):void 0}return}function Z2(B,Z,$){let z=new URLSearchParams({response_type:"code",client_id:i,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`${R}/oauth/authorize?${z.toString()}`}async function $2(B,Z,$){let z=await fetch(`${R}/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:i,code_verifier:$.verifier}).toString()});if(!z.ok)throw Error(`Token exchange failed: ${z.status}`);return await z.json()}function z2(B){return B.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}var X2=`<!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>`,B0=(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">${z2(B)}</div>
|
|
85
|
-
</div>
|
|
86
|
-
</body>
|
|
87
|
-
</html>`,f,w,D=new Map;function C(){return D.size}function q(B){if(D.delete(B),C()===0)I()}async function G2(){let B=`http://127.0.0.1:${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"),Y=K.searchParams.get("error_description");if(W){let Q=Y||W;if(X){let V=D.get(X);if(V)V.reject(Error(Q)),q(X);else if(C()===0)I()}else if(C()===0)I();z.writeHead(200,{"Content-Type":"text/html"}),z.end(B0(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(C()===0)I()}else if(C()===0)I();z.writeHead(400,{"Content-Type":"text/html"}),z.end(B0(Q));return}let J=D.get(X);if(!J){if(C()===0)I();z.writeHead(400,{"Content-Type":"text/html"}),z.end(B0("Unknown state — authorization may have expired"));return}q(X),$2(G,B,J.pkce).then((Q)=>J.resolve(Q)).catch((Q)=>J.reject(Q)),z.writeHead(200,{"Content-Type":"text/html"}),z.end(X2);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 Y=D.get(W);if(!Y)continue;Y.reject(Error("Login cancelled")),q(W)}if(C()===0)I();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 I(){if(f){let B=f;f=void 0,B.close(()=>{}),B.closeIdleConnections?.(),setTimeout(()=>{B.closeAllConnections?.()},25).unref?.()}}function K2(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:(Y)=>{if(clearTimeout(X),z)z.removeEventListener("abort",W);K(Y)},reject:(Y)=>{if(clearTimeout(X),z)z.removeEventListener("abort",W);G(Y)}})})}async function W2(){let B=await fetch(`${R}/api/accounts/deviceauth/usercode`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":R0},body:JSON.stringify({client_id:i})});if(!B.ok)throw Error("Failed to initiate device authorization");let Z=await B.json();return{deviceData:Z,url:`${R}/codex/device`,instructions:`Enter code: ${Z.user_code}`}}async function Y2(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(`${R}/api/accounts/deviceauth/token`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":R0},body:JSON.stringify({device_auth_id:B.device_auth_id,user_code:B.user_code})});if(X.ok){let J=await X.json(),Q=await fetch(`${R}/oauth/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",code:J.authorization_code,redirect_uri:`${R}/deviceauth/callback`,client_id:i,code_verifier:J.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 Y=Math.min($+e0,W);try{await t0(Y,void 0,{signal:Z})}catch(J){if(J instanceof Error&&J.name==="AbortError")throw Error("Device authorization cancelled");throw J}}}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:J,url:Q,instructions:V}=await W2(),F=(async()=>{let N=await Y2(J,z),H=Date.now();return{id:Z||S(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:S(N)}})();return{url:Q,instructions:V,completion:F}}let{redirectUri:K}=await G2(),G=await B2(),X=y0(crypto.getRandomValues(new Uint8Array(32)).buffer),W=Z2(K,G,X),Y=(async()=>{try{if(z?.aborted)throw Error("Login cancelled");let J=await K2(G,X,void 0,z),Q=Date.now();return{id:Z||S(J)||crypto.randomUUID(),label:Z||void 0,type:"oauth",access:J.access_token,refresh:J.refresh_token,expires:Q+(J.expires_in??3600)*1000,enabled:!0,addedAt:Q,lastUsed:Q,lastRefreshedAt:Q,accountId:S(J)}}finally{q(X)}})();return{url:W,instructions:"Complete authorization in your browser. This window will close automatically.",completion:Y}}var s="primary",c="secondary",Q2="app_EMoamEEZ73f0CkXaXp7hrann",j2="https://auth.openai.com";async function xB(B){let Z=await B.fetchImpl(`${j2}/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:Q2}).toString()});if(!Z.ok){let z=e(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 N2="https://chatgpt.com/backend-api/wham/usage";async function kB(B){let Z=await B.fetchImpl(N2,{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=e(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-dnaa90ct.js");return $(await Z.json())}import{randomUUID as Z0}from"node:crypto";import{mkdir as V2,readFile as $0,rename as H2,rm as m,stat as T0,writeFile as z0}from"node:fs/promises";import{homedir as b2}from"node:os";import{dirname as vB,join as h}from"node:path";var F2=globalThis.setTimeout.bind(globalThis),L2=globalThis.clearTimeout.bind(globalThis),D2="openai-auth.json";function q2(){if(process.env.OPENCODE_CONFIG_DIR?.trim())return process.env.OPENCODE_CONFIG_DIR.trim();return h(process.env.XDG_CONFIG_HOME||h(b2(),".config"),"opencode")}function M2(){return process.env.OPENCODE_OPENAI_AUTH_FILE?.trim()||h(q2(),D2)}async function n(B){let $=`${B.path??M2()}.${B.name}.lock`,z=h($,"owner.json"),K=Z0(),G=B.now??Date.now,X=null,W=!1;async function Y(){try{return JSON.parse(await $0($,"utf8"))}catch(N){if(N.code!=="EISDIR")throw N;return JSON.parse(await $0(z,"utf8"))}}async function J(){await z0($,`${JSON.stringify({ownerId:K,expiresAt:G()+B.ttlMs})}
|
|
88
|
-
`,{encoding:"utf8",mode:384})}async function Q(){try{return await z0($,`${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=F2(()=>{(async()=>{try{let H=await Y(),l=G();if(W||H?.ownerId!==K||Number(H?.expiresAt)<=l)return;await J(),V()}catch{}})()},N),"unref"in X)X.unref()}let F=await Q();if(!F){let N=`${$}.evicting`,H=h(N,"owner.json"),l=Z0(),MB=5000,OB=8;async function g(){await new Promise((L)=>setTimeout(L,Math.floor(Math.random()*4)))}async function b0(){try{let L=await Y();return Number(L?.expiresAt)>G()}catch{try{return(await T0($)).mtimeMs+B.ttlMs>G()}catch{return!1}}}async function A(){try{return JSON.parse(await $0(H,"utf8"))?.ownerId===l}catch{return!1}}async function l0(){await V2(N);try{await z0(H,`${JSON.stringify({ownerId:l,createdAt:G()})}
|
|
90
|
-
`,{encoding:"utf8",mode:384,flag:"wx"})}catch(L){if(L.code==="ENOENT")return!1;throw await F0(),L}return await B.onStep?.("eviction-marker-acquired"),!0}async function F0(){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 b0())return null;try{if(!await l0()){await g();continue}}catch(L0){if(L0.code!=="EEXIST")throw L0;let D0;try{D0=await T0(N)}catch(x){if(x.code==="ENOENT"){await g();continue}throw x}if(D0.mtimeMs+5000>G())return null;await B.onStep?.("stale-marker-stat");let q0=`${N}.${Z0()}`;try{await H2(N,q0)}catch(x){if(x.code==="ENOENT"){await g();continue}throw x}await B.onStep?.("stale-marker-claimed"),await m(q0,{recursive:!0,force:!0}).catch(()=>{}),await g();continue}try{if(await b0())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 F0()}}}if(!F)return null;return V(),{release:async()=>{if(W=!0,X)L2(X),X=null;try{if((await Y())?.ownerId!==K)return}catch{return}await m($,{recursive:!0,force:!0}).catch(()=>{})}}}import{createHash as R2,randomUUID as y2}from"node:crypto";import{homedir as T2}from"node:os";import{dirname as E2,join as r}from"node:path";import{setTimeout as S2}from"node:timers/promises";import{randomUUID as O2}from"node:crypto";import{mkdir as U2,rename as _2,rm as P2,writeFile as C2}from"node:fs/promises";import{dirname as I2}from"node:path";async function M(B,Z){await U2(I2(B),{recursive:!0});let $=`${B}.${O2()}.tmp`;await C2($,`${JSON.stringify(Z,null,2)}
|
|
91
|
-
`,{encoding:"utf8",mode:384});try{await _2($,B)}catch(z){throw await P2($,{force:!0}).catch(()=>{}),z}}import{readFile as d2}from"node:fs/promises";var y=m0("refresh"),E0=1e4,A2=50,h0="openai-auth.json",x2="openai-auth-state.json";function k2(){if(process.env.OPENCODE_CONFIG_DIR?.trim())return process.env.OPENCODE_CONFIG_DIR.trim();return r(process.env.XDG_CONFIG_HOME||r(T2(),".config"),"opencode")}function E(){return process.env.OPENCODE_OPENAI_AUTH_FILE?.trim()||r(k2(),h0)}function d(B=E()){let Z=process.env.OPENCODE_OPENAI_AUTH_STATE_FILE?.trim();if(Z)return Z;return w2(B)}function w2(B){return B.endsWith(h0)?r(E2(B),x2):`${B}.state.json`}function O(B){return B.type==="oauth"}function f2(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 m2=[401,403,429],S0={primary:0,secondary:0},h2=!1,K0={primary:5,secondary:10};function j(B){return B!=null&&typeof B==="object"&&!Array.isArray(B)}function A0(B){return{id:typeof B.id==="string"&&B.id.trim()?B.id.trim():y2(),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 x0(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 p2(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 v2(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(!f2(Z))return null;let z=B.authHeader==="x-api-key"?"x-api-key":"authorization-bearer";return{...A0(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{...A0(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:x0(B.lastRefreshError),lastQuotaRefreshError:x0(B.lastQuotaRefreshError),quota:p2(B.quota)}}function Q0(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(v2).filter((Z)=>Z!=null)}}async function U(B){try{return{exists:!0,value:JSON.parse(await d2(B,"utf8"))}}catch(Z){if(Z.code==="ENOENT")return{exists:!1,value:null};throw Z}}function _(B){return Object.fromEntries(Object.entries(B).filter(([,Z])=>Z!==void 0))}function j0(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,Y=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 p0({...B,refresh:_({...X,mainLastRefreshError:Y.lastRefreshError,mainRefreshLeaseId:Y.refreshLeaseId,mainRefreshLeaseUntil:Y.refreshLeaseUntil,mainRefreshLeaseTokenHash:Y.refreshLeaseTokenHash}),quota:_({...G,mainQuota:W.quota,mainQuotaCheckedAt:W.quotaCheckedAt,mainQuotaToken:W.quotaToken,mainLastQuotaApiError:W.lastQuotaApiError}),accounts:Q})}async function l2(B=E()){let Z=await U(B);if(!Z.exists)return null;let $=await U(d(B));return Q0(j0(Z.value,$.value))}function p0(B){return Object.fromEntries(Object.entries(B).filter(([,Z])=>Z!==void 0))}function g2(B){return _({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 v0(B){if(B.type==="api")return _({apiKey:B.apiKey,lastUsed:B.lastUsed});return _({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 a(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 u2(B,Z){return B.access===Z.access&&B.refresh===Z.refresh&&B.expires===Z.expires&&B.lastRefreshedAt===Z.lastRefreshedAt}function i2(B,Z){if(!u2(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 s2(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:i2(Z,$);p(B,W,"access"),p(B,W,"refresh"),p(B,W,"expires"),p(B,W,"lastRefreshedAt"),p(B,W,"lastRefreshError")}function c2(B,Z){if(!j(B))return Z;let $=B,z=a($.quota),K=a(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 s2(X,$,Z),X}function N0(B){let Z=B.refresh?_({enabled:B.refresh.enabled,intervalMinutes:B.refresh.intervalMinutes,refreshBeforeExpiryMinutes:B.refresh.refreshBeforeExpiryMinutes}):void 0,$=B.quota?_({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 p0({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(g2)})}function n2(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 v(B){let Z=Date.now()+E0;while(Date.now()<=Z){let $=await n({name:"save",ttlMs:E0,path:B});if($)return $;let z=Z-Date.now();if(z<=0)break;await S2(Math.min(A2,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,v0($)]));return{version:1,main:_({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=E()){let $=d(Z),z=await v(Z);try{let K=await v($);try{let G=await U(Z),X=await U($),W=G.exists?Q0(j0(G.value,X.value)):null,Y=n2(W,B),Q={...j(G.value)?G.value:{},...N0(Y)};await M(Z,Q),await M($,V0(Y))}finally{await K.release()}}finally{await z.release()}}async function GZ(B,Z=E()){let $=d(Z),z=await v(Z);try{let K=await v($);try{let G=await U(Z),X=await U($),W=(G.exists?Q0(j0(G.value,X.value)):null)??r2(),Y=B(W)??W,Q={...j(G.value)?G.value:{},...N0(Y)};return await M(Z,Q),await M($,V0(Y)),Y}finally{await K.release()}}finally{await z.release()}}function r2(){return{version:1,main:{type:"opencode",provider:"openai"},accounts:[]}}function a2(B,Z){B.main=B.main??{};let $=typeof B.main.quotaCheckedAt==="number"?B.main.quotaCheckedAt:a(B.main.quota),z=typeof Z.quota?.mainQuotaCheckedAt==="number"?Z.quota.mainQuotaCheckedAt:a(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 o2(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 t2(B,Z=E(),$={mainQuota:!0,mainRefresh:!0,accounts:!0}){let z=d(Z),K=await v(z);try{let G=(await U(z)).value,X=j(G)?{...G,version:1}:{version:1};if($.mainQuota)a2(X,B);if($.mainRefresh)o2(X,B);if($.accounts){let W=$.accounts===!0?null:new Set($.accounts);X.accounts={...j(X.accounts)?X.accounts:{}};for(let Y of B.accounts){if(W&&!W.has(Y.id))continue;X.accounts[Y.id]=c2(X.accounts[Y.id],v0(Y))}if(W){for(let Y of W)if(!B.accounts.some((J)=>J.id===Y))delete X.accounts[Y]}}await M(z,W0(X))}finally{await K.release()}}function e2(B){return B?.fallbackOn?.length?B.fallbackOn:m2}function KZ(B,Z){return e2(Z).includes(B)}function BB(B){let Z=B?.quota?.minimumRemaining||{};return{primary:Z.primary??Z["5h"]??S0.primary,secondary:Z.secondary??Z["1w"]??S0.secondary}}function Y0(B){return B?.quota?.enabled!==!1}function H0(B){return B?.quota?.failClosedOnUnknownQuota??h2}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!H0(Z);if(K.remainingPercent<$[z])return!1}return!0}function ZB(B){return B?.killswitch?.enabled===!0}function k0(B){return{primary:B?.primary??B?.["5h"]??K0.primary,secondary:B?.secondary??B?.["1w"]??K0.secondary}}function $B(B,Z){if(!B?.killswitch)return K0;if(Z&&B.killswitch.accounts?.[Z])return k0(B.killswitch.accounts[Z]);return k0(B.killswitch.main)}function WZ(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!H0(Z);return!0}function YZ(B,Z,$){let z=[],K=[B,...Z.map((X)=>X.quota)];for(let X of K)for(let W of["primary","secondary"]){let Y=X?.[W]?.resetsAt;if(!Y)continue;let J=Date.parse(Y);if(Number.isFinite(J)&&J>$)z.push(J)}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 JZ(B,Z=E()){let $=await n({name:"migrate",ttlMs:30000,path:Z});if(!$)return;try{let z=await U(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=S({id_token:"",access_token:B.access,refresh_token:B.refresh});if(W)K.mainAccountId=W}let X={...z.exists&&j(z.value)?z.value:{},...N0(K)};await M(Z,X),await M(d(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 T(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 X0(B){return B instanceof Error?B.message:String(B)}function J0(B,Z,$){B.lastRefreshError=O0({error:Z,now:$,refreshToken:B.refresh,previous:B.lastRefreshError})}function G0(B,Z,$){if(B.lastQuotaRefreshError=U0({error:Z,now:$,previous:B.lastQuotaRefreshError}),Z?.isRefreshError===!0)J0(B,Z,$)}function JB(B){return`fallback-oauth-refresh-${R2("sha256").update(B).digest("base64url").slice(0,16)}`}function w0(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 w0(B[s],Z)||w0(B[c],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[s]?.checkedAt??0,B[c]?.checkedAt??0);return $-G<K}function f0(B,Z,$){return!jB(B.quota,Z,$)}function NB(B,Z,$,z){return t($)&&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 QZ=globalThis.setTimeout.bind(globalThis),jZ=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??E(),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[s]?.checkedAt??0,B.quota[c]?.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 l2(this.configPath)}async save(B,Z){await t2(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||!O(K))continue;if(YB(Z,K))continue;let G=!1,X=K;try{if(T(X,Z,this.now())){let W=X.lastRefreshError;if(W&&P(W,X.refresh,this.now()))throw G=!0,Error(u(W,this.now()));try{X=await this.refreshAccount(X,Z),z=!0}catch(Y){G=!0;let J=Z.accounts.find((Q)=>Q.id===K.id&&O(Q));if(J&&!P(J.lastRefreshError,J.refresh,this.now()))J0(J,Y,this.now()),b(Z,J),z=!0;throw Y}}if(this.seedFallbackQuota(X,Z),this.accountPassesQuotaPolicy(this.quotaPolicyAccount(X),Z))$.push(X)}catch(W){let Y=WB(X,this.now());if(G){if(!Y)continue}else if(!Y)continue;if(NB(X,Z,W,this.now()))y.debug("fallback quota using cached quota after refresh error",{pid:process.pid,accountId:X.id,error:X0(W)}),$.push(X);else if(!H0(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||!O($))continue;if(!T($,B,this.now()))continue;if(P($.lastRefreshError,$.refresh,this.now()))continue;try{y.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){y.warn("fallback oauth background failed",{pid:process.pid,accountId:$.id,error:X0(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||!O($))continue;let z=$;try{if(T(z,B,this.now())){if(P(z.lastRefreshError,z.refresh,this.now()))continue;z=await this.refreshAccount(z,B),Z=!0}if(_0(z.lastQuotaRefreshError,this.now()))continue;if(this.seedFallbackQuota(z,B),!(this.quotaManager?this.quotaManager.isFallbackStale(z.id,z.access):f0(z,B,this.now())))continue;await this.refreshAccountQuota(z,B),Z=!0}catch(K){G0($,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||!O(G))continue;let X=G;try{if(T(X,Z,this.now())){let W=X.lastRefreshError;if(W&&P(W,X.refresh,this.now()))throw Error(u(W,this.now()));X=await this.refreshAccount(X,Z),K=!0}if(!z&&!f0(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){G0(G,W,this.now()),b(Z,G),K=!0,$.push({accountId:G.id,message:X0(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((J)=>setTimeout(J,DB));let G=await this.load(),X=G?.accounts.find((J)=>J.id===B.id&&O(J));if(!X)continue;if((X.access!==$.access||X.refresh!==$.refresh||(X.expires??0)>($.expires??0)+60000)&&(z.force||!T(X,G,this.now())))return b(Z,X),y.debug("fallback oauth joined concurrent refresh",{pid:process.pid,accountId:X.id,expiresInMs:X.expires?X.expires-this.now():void 0}),X;let Y=X.lastRefreshError;if(Y&&P(Y,X.refresh,this.now()))throw b(Z,X),Error(u(Y,this.now()))}return null}async refreshAccountNow(B,Z,$){let z=await this.load(),K=z?.accounts.find((W)=>W.id===B.id&&O(W));if(K&&!$.force&&!T(K,z,this.now()))return b(Z,K),K;let G=K??B,X=await n({name:JB(G.id),ttlMs:FB,path:this.configPath,now:this.now,renew:!0});if(!X){y.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((J)=>J.id===B.id&&O(J)),K&&!$.force&&!T(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")});y.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 Y=await W({refreshToken:G.refresh,fetchImpl:this.fetchImpl,now:this.now});return G.access=Y.access,G.refresh=Y.refresh,G.expires=Y.expires,G.lastRefreshedAt=Y.expires-Y.expiresIn*1000,G.lastRefreshError=void 0,b(Z,G),await this.save(Z),y.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 G0(B,G,this.now()),b(Z,B),G}}}
|
|
92
|
-
export{M0 as g,O0 as h,P as i,u as j,U0 as k,_0 as l,R0 as m,y0 as n,B2 as o,C0 as p,I0 as q,S as r,Z2 as s,q as t,G2 as u,K2 as v,W2 as w,Y2 as x,TB as y,EB as z,xB as A,kB as B,n as C,E as D,O as E,$Z as F,K0 as G,l2 as H,XZ as I,GZ as J,KZ as K,ZB as L,WZ as M,YZ as N,JZ as O,qB as P};
|