@cortexkit/opencode-openai-auth 0.3.4 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -0
- package/dist/cli.js +1 -1
- package/dist/codex-http.d.ts +3 -0
- package/dist/config.d.ts +3 -0
- package/dist/core/accounts.d.ts +9 -3
- package/dist/core/oauth.d.ts +1 -1
- package/dist/core/quota-manager.d.ts +2 -2
- package/dist/{index-k5zwf3j1.js → index-1anzb8jh.js} +1 -1
- package/dist/index-1r02s323.js +6 -0
- package/dist/index-2ng03cby.js +2 -0
- package/dist/{index-e7m7qbne.js → index-6y6ss1kc.js} +1 -1
- package/dist/{index-1xmasv0x.js → index-b6kp9ydc.js} +1 -1
- package/dist/index-cz1bkmjz.js +2 -0
- package/dist/index-dzg88nw2.js +89 -0
- package/dist/index-y67qn95a.js +2 -0
- package/dist/index.d.ts +8 -1
- package/dist/index.js +65 -65
- package/dist/model-costs.d.ts +29 -0
- package/dist/prompt-context.d.ts +1 -1
- package/dist/quota-normalize-8yzxqy78.js +1 -0
- package/dist/quota-normalize.d.ts +13 -4
- 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.d.ts +47 -2
- package/dist/sidebar-state.js +1 -1
- package/dist/token-util-h46jb3eg.js +1 -0
- package/dist/token-yzcb1p3e.js +1 -0
- package/dist/tui/command-dialogs.d.ts +8 -1
- package/dist/tui-preferences.js +1 -1
- package/dist/tui.d.ts +18 -1
- package/dist/version.d.ts +1 -1
- package/dist/ws-pool.d.ts +1 -0
- package/package.json +6 -5
- package/src/core/refresh-file-lock.ts +293 -0
- package/src/sidebar-state.ts +392 -13
- package/src/tui/command-dialogs.tsx +43 -25
- package/src/tui-compiled/sidebar-state.ts +392 -13
- package/src/tui-compiled/tui/command-dialogs.tsx +25 -20
- package/src/tui-compiled/tui.tsx +228 -171
- package/src/tui.tsx +142 -64
- package/dist/index-5s67238f.js +0 -2
- package/dist/index-d9hq0tmc.js +0 -2
- package/dist/index-mrg2fms9.js +0 -2
- package/dist/index-qdh7pt5a.js +0 -3
- package/dist/index-y8d01tgn.js +0 -92
- package/dist/quota-normalize-dfdpwwm3.js +0 -1
- package/dist/token-01dcf92a.js +0 -1
- package/dist/token-util-rkqd82q9.js +0 -1
package/src/tui.tsx
CHANGED
|
@@ -23,12 +23,13 @@ import {
|
|
|
23
23
|
type AccountQuota,
|
|
24
24
|
computeQuotaPacing,
|
|
25
25
|
DEFAULT_SIDEBAR_STATE,
|
|
26
|
-
FIVE_HOUR_MS,
|
|
27
26
|
getCollapsedQuotaSummary,
|
|
27
|
+
getPresentQuotaWindows,
|
|
28
28
|
getSidebarState,
|
|
29
29
|
type QuotaPacing,
|
|
30
|
+
type QuotaWindow,
|
|
30
31
|
resolveActiveAccount,
|
|
31
|
-
|
|
32
|
+
resolveSessionSidebarRouting,
|
|
32
33
|
type SidebarState,
|
|
33
34
|
} from './sidebar-state.js'
|
|
34
35
|
import { openCommandDialog } from './tui/command-dialogs.js'
|
|
@@ -228,6 +229,54 @@ function CollapsedRow(props: {
|
|
|
228
229
|
)
|
|
229
230
|
}
|
|
230
231
|
|
|
232
|
+
export interface QuotaDisplayRow {
|
|
233
|
+
key: 'primary' | 'secondary'
|
|
234
|
+
label: string
|
|
235
|
+
window: QuotaWindow
|
|
236
|
+
pacing: QuotaPacing | null
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
// Maps present quota windows onto display rows and computes pacing against each
|
|
240
|
+
// dynamic duration or the historical 5h/7d duration for legacy snapshots.
|
|
241
|
+
export function buildQuotaRowsForDisplay(
|
|
242
|
+
quota: AccountQuota | null,
|
|
243
|
+
now: number,
|
|
244
|
+
pacingEnabled: boolean,
|
|
245
|
+
): QuotaDisplayRow[] {
|
|
246
|
+
return getPresentQuotaWindows(quota).map((row) => ({
|
|
247
|
+
key: row.key,
|
|
248
|
+
label: row.label,
|
|
249
|
+
window: row.window,
|
|
250
|
+
pacing:
|
|
251
|
+
pacingEnabled && row.windowMs !== null
|
|
252
|
+
? computeQuotaPacing(row.window, row.windowMs, now)
|
|
253
|
+
: null,
|
|
254
|
+
}))
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
export function isQuotaLoaded(quota: AccountQuota | null): boolean {
|
|
258
|
+
return quota !== null
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
export function getQuotaMetadataRows(
|
|
262
|
+
state: SidebarState,
|
|
263
|
+
): Array<{ label: string; value: string }> {
|
|
264
|
+
const rows: Array<{ label: string; value: string }> = []
|
|
265
|
+
if (state.planType) rows.push({ label: 'Plan', value: state.planType })
|
|
266
|
+
if (state.credits !== undefined) {
|
|
267
|
+
rows.push({ label: 'Credits', value: String(state.credits) })
|
|
268
|
+
}
|
|
269
|
+
return rows
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
export function getAccountMetadataRows(
|
|
273
|
+
resetCredits: number | undefined,
|
|
274
|
+
): Array<{ label: string; value: string }> {
|
|
275
|
+
return resetCredits === undefined
|
|
276
|
+
? []
|
|
277
|
+
: [{ label: 'resets', value: String(resetCredits) }]
|
|
278
|
+
}
|
|
279
|
+
|
|
231
280
|
// Quota window row: muted label left, tone-colored bar + percentage right,
|
|
232
281
|
// with an optional muted reset suffix. When pacing data is present, the bar
|
|
233
282
|
// gains a pace segment and an off-pace window adds a muted subline with the
|
|
@@ -311,21 +360,15 @@ function AccountBlock(props: {
|
|
|
311
360
|
killed: boolean
|
|
312
361
|
active: boolean
|
|
313
362
|
pacingEnabled: boolean
|
|
363
|
+
resetCredits?: number
|
|
314
364
|
marginTop?: number
|
|
315
365
|
}) {
|
|
316
366
|
const statusWord = () =>
|
|
317
367
|
props.killed ? 'blocked' : props.active ? 'active' : 'idle'
|
|
318
368
|
const statusTone = (): Tone =>
|
|
319
369
|
props.killed ? 'err' : props.active ? 'ok' : 'muted'
|
|
320
|
-
const
|
|
321
|
-
|
|
322
|
-
| { usedPercent: number; remainingPercent: number; resetsAt?: string }
|
|
323
|
-
| undefined,
|
|
324
|
-
windowMs: number,
|
|
325
|
-
) =>
|
|
326
|
-
props.pacingEnabled && window
|
|
327
|
-
? computeQuotaPacing(window, windowMs, Date.now())
|
|
328
|
-
: null
|
|
370
|
+
const rows = () =>
|
|
371
|
+
buildQuotaRowsForDisplay(props.quota, Date.now(), props.pacingEnabled)
|
|
329
372
|
return (
|
|
330
373
|
<box width='100%' flexDirection='column' marginTop={props.marginTop ?? 0}>
|
|
331
374
|
<box width='100%' flexDirection='row' justifyContent='space-between'>
|
|
@@ -337,24 +380,36 @@ function AccountBlock(props: {
|
|
|
337
380
|
</text>
|
|
338
381
|
</box>
|
|
339
382
|
<Show
|
|
340
|
-
when={props.quota}
|
|
383
|
+
when={isQuotaLoaded(props.quota)}
|
|
341
384
|
fallback={<text fg={props.theme.textMuted}>{'checking\u2026'}</text>}
|
|
342
385
|
>
|
|
343
|
-
<
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
386
|
+
<Show
|
|
387
|
+
when={rows().length > 0}
|
|
388
|
+
fallback={<text fg={props.theme.textMuted}>{'\u2014'}</text>}
|
|
389
|
+
>
|
|
390
|
+
<For each={rows()}>
|
|
391
|
+
{(row) => (
|
|
392
|
+
<QuotaRow
|
|
393
|
+
theme={props.theme}
|
|
394
|
+
appearance={props.appearance}
|
|
395
|
+
label={row.label}
|
|
396
|
+
window={row.window}
|
|
397
|
+
pacing={row.pacing}
|
|
398
|
+
/>
|
|
399
|
+
)}
|
|
400
|
+
</For>
|
|
401
|
+
</Show>
|
|
357
402
|
</Show>
|
|
403
|
+
<For each={getAccountMetadataRows(props.resetCredits)}>
|
|
404
|
+
{(row) => (
|
|
405
|
+
<StatRow
|
|
406
|
+
theme={props.theme}
|
|
407
|
+
label={row.label}
|
|
408
|
+
value={row.value}
|
|
409
|
+
tone='text'
|
|
410
|
+
/>
|
|
411
|
+
)}
|
|
412
|
+
</For>
|
|
358
413
|
</box>
|
|
359
414
|
)
|
|
360
415
|
}
|
|
@@ -366,6 +421,7 @@ function AccountBlock(props: {
|
|
|
366
421
|
function QuotaDialogContent(props: {
|
|
367
422
|
api: TuiPluginApi
|
|
368
423
|
controller: SidebarController
|
|
424
|
+
sessionId: string | undefined
|
|
369
425
|
}) {
|
|
370
426
|
const prefs = props.controller.prefs
|
|
371
427
|
const [state, setState] = createSignal<SidebarState>(DEFAULT_SIDEBAR_STATE)
|
|
@@ -385,6 +441,7 @@ function QuotaDialogContent(props: {
|
|
|
385
441
|
const theme = () => props.api.theme.current
|
|
386
442
|
const enabledFallbacks = () =>
|
|
387
443
|
(state().fallbacks ?? []).filter((f) => f.enabled)
|
|
444
|
+
const activeId = () => resolveQuotaDialogActiveId(state(), props.sessionId)
|
|
388
445
|
return (
|
|
389
446
|
<box flexDirection='column' padding={2} width='100%' alignItems='center'>
|
|
390
447
|
<box flexDirection='column' width={58}>
|
|
@@ -399,8 +456,9 @@ function QuotaDialogContent(props: {
|
|
|
399
456
|
name='main'
|
|
400
457
|
quota={state().main?.quota ?? null}
|
|
401
458
|
killed={state().main?.killed ?? false}
|
|
402
|
-
active={
|
|
459
|
+
active={activeId() === 'main'}
|
|
403
460
|
pacingEnabled={prefs().sections.pacing}
|
|
461
|
+
resetCredits={state().main?.resetCredits}
|
|
404
462
|
/>
|
|
405
463
|
<Show when={prefs().sections.fallbackAccounts}>
|
|
406
464
|
<For each={enabledFallbacks()}>
|
|
@@ -411,8 +469,9 @@ function QuotaDialogContent(props: {
|
|
|
411
469
|
name={fb.label ?? fb.id}
|
|
412
470
|
quota={fb.quota}
|
|
413
471
|
killed={fb.killed}
|
|
414
|
-
active={
|
|
472
|
+
active={activeId() === fb.id}
|
|
415
473
|
pacingEnabled={prefs().sections.pacing}
|
|
474
|
+
resetCredits={fb.resetCredits}
|
|
416
475
|
marginTop={1}
|
|
417
476
|
/>
|
|
418
477
|
)}
|
|
@@ -429,6 +488,16 @@ export async function readStateFromFile(): Promise<SidebarState> {
|
|
|
429
488
|
return getSidebarState()
|
|
430
489
|
}
|
|
431
490
|
|
|
491
|
+
export function resolveQuotaDialogActiveId(
|
|
492
|
+
state: SidebarState,
|
|
493
|
+
sessionId: string | undefined,
|
|
494
|
+
now = Date.now(),
|
|
495
|
+
): string | undefined {
|
|
496
|
+
return sessionId
|
|
497
|
+
? resolveSessionSidebarRouting(state, sessionId, now).activeId
|
|
498
|
+
: state.activeId
|
|
499
|
+
}
|
|
500
|
+
|
|
432
501
|
interface SidebarController {
|
|
433
502
|
prefs: () => OpenaiAuthTuiPrefs
|
|
434
503
|
collapsed: () => boolean
|
|
@@ -496,6 +565,7 @@ function createSidebarController(
|
|
|
496
565
|
function QuotaSidebar(props: {
|
|
497
566
|
api: TuiPluginApi
|
|
498
567
|
controller: SidebarController
|
|
568
|
+
sessionId: string
|
|
499
569
|
}) {
|
|
500
570
|
const prefs = props.controller.prefs
|
|
501
571
|
const collapsed = props.controller.collapsed
|
|
@@ -547,22 +617,23 @@ function QuotaSidebar(props: {
|
|
|
547
617
|
const name = prefs().header.label
|
|
548
618
|
return !hasData() ? name : collapsed() ? `\u25b6 ${name}` : `\u25bc ${name}`
|
|
549
619
|
}
|
|
550
|
-
const
|
|
620
|
+
const sessionRouting = () =>
|
|
621
|
+
resolveSessionSidebarRouting(state(), props.sessionId)
|
|
622
|
+
const sessionState = (): SidebarState => ({
|
|
623
|
+
...state(),
|
|
624
|
+
activeId: sessionRouting().activeId,
|
|
625
|
+
route: sessionRouting().route,
|
|
626
|
+
})
|
|
627
|
+
const activeAccount = () => resolveActiveAccount(sessionState())
|
|
551
628
|
const activeQuotaSummary = () =>
|
|
552
629
|
getCollapsedQuotaSummary(activeAccount().quota)
|
|
553
630
|
const activePacingDeficit = () => {
|
|
554
631
|
if (!prefs().sections.pacing) return false
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
[quota.secondary, SEVEN_DAY_MS],
|
|
561
|
-
]
|
|
562
|
-
return windows.some(
|
|
563
|
-
([w, ms]) =>
|
|
564
|
-
w != null && computeQuotaPacing(w, ms, now)?.state === 'deficit',
|
|
565
|
-
)
|
|
632
|
+
return buildQuotaRowsForDisplay(
|
|
633
|
+
activeAccount().quota,
|
|
634
|
+
Date.now(),
|
|
635
|
+
true,
|
|
636
|
+
).some((row) => row.pacing?.state === 'deficit')
|
|
566
637
|
}
|
|
567
638
|
const activeQuotaTone = (): Tone => {
|
|
568
639
|
const summary = activeQuotaSummary()
|
|
@@ -640,7 +711,7 @@ function QuotaSidebar(props: {
|
|
|
640
711
|
</Show>
|
|
641
712
|
</box>
|
|
642
713
|
|
|
643
|
-
{/* Collapsed: active account
|
|
714
|
+
{/* Collapsed: active account's present quota windows + dot (red ⊘ when killed) */}
|
|
644
715
|
<Show when={collapsed() && hasData()}>
|
|
645
716
|
<CollapsedRow theme={theme()} label={activeAccount().name}>
|
|
646
717
|
<Show
|
|
@@ -684,8 +755,9 @@ function QuotaSidebar(props: {
|
|
|
684
755
|
name='main'
|
|
685
756
|
quota={state().main?.quota ?? null}
|
|
686
757
|
killed={state().main?.killed ?? false}
|
|
687
|
-
active={
|
|
758
|
+
active={sessionRouting().activeId === 'main'}
|
|
688
759
|
pacingEnabled={prefs().sections.pacing}
|
|
760
|
+
resetCredits={state().main?.resetCredits}
|
|
689
761
|
/>
|
|
690
762
|
<Show when={prefs().sections.fallbackAccounts}>
|
|
691
763
|
<For each={enabledFallbacks()}>
|
|
@@ -696,8 +768,9 @@ function QuotaSidebar(props: {
|
|
|
696
768
|
name={fb.label ?? fb.id}
|
|
697
769
|
quota={fb.quota}
|
|
698
770
|
killed={fb.killed}
|
|
699
|
-
active={
|
|
771
|
+
active={sessionRouting().activeId === fb.id}
|
|
700
772
|
pacingEnabled={prefs().sections.pacing}
|
|
773
|
+
resetCredits={fb.resetCredits}
|
|
701
774
|
marginTop={1}
|
|
702
775
|
/>
|
|
703
776
|
)}
|
|
@@ -712,30 +785,22 @@ function QuotaSidebar(props: {
|
|
|
712
785
|
<StatRow
|
|
713
786
|
theme={theme()}
|
|
714
787
|
label='Route'
|
|
715
|
-
value={
|
|
788
|
+
value={sessionRouting().route}
|
|
716
789
|
tone='accent'
|
|
717
790
|
/>
|
|
718
791
|
</Show>
|
|
719
792
|
|
|
720
|
-
{/* Plan
|
|
721
|
-
<
|
|
722
|
-
|
|
793
|
+
{/* Plan and credits — whichever are present */}
|
|
794
|
+
<For each={getQuotaMetadataRows(state())}>
|
|
795
|
+
{(row) => (
|
|
723
796
|
<StatRow
|
|
724
797
|
theme={theme()}
|
|
725
|
-
label=
|
|
726
|
-
value={
|
|
798
|
+
label={row.label}
|
|
799
|
+
value={row.value}
|
|
727
800
|
tone='text'
|
|
728
801
|
/>
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
<StatRow
|
|
732
|
-
theme={theme()}
|
|
733
|
-
label='Credits'
|
|
734
|
-
value={String(state().credits)}
|
|
735
|
-
tone='text'
|
|
736
|
-
/>
|
|
737
|
-
</Show>
|
|
738
|
-
</Show>
|
|
802
|
+
)}
|
|
803
|
+
</For>
|
|
739
804
|
|
|
740
805
|
{/* Health — only when something is wrong */}
|
|
741
806
|
<Show when={degraded() && prefs().sections.health}>
|
|
@@ -776,8 +841,14 @@ const tui: TuiPlugin = async (api) => {
|
|
|
776
841
|
api.slots.register({
|
|
777
842
|
order: computeEffectiveOrder(root, PLUGIN_KEY, DEFAULT_SLOT_ORDER),
|
|
778
843
|
slots: {
|
|
779
|
-
sidebar_content(_ctx: unknown,
|
|
780
|
-
return
|
|
844
|
+
sidebar_content(_ctx: unknown, props: { session_id: string }) {
|
|
845
|
+
return (
|
|
846
|
+
<QuotaSidebar
|
|
847
|
+
api={api}
|
|
848
|
+
controller={controller}
|
|
849
|
+
sessionId={props.session_id}
|
|
850
|
+
/>
|
|
851
|
+
)
|
|
781
852
|
},
|
|
782
853
|
},
|
|
783
854
|
})
|
|
@@ -815,12 +886,19 @@ const tui: TuiPlugin = async (api) => {
|
|
|
815
886
|
if (message.payload.command === 'openai-quota') {
|
|
816
887
|
api.ui.dialog.setSize('xlarge')
|
|
817
888
|
api.ui.dialog.replace(() => (
|
|
818
|
-
<QuotaDialogContent
|
|
889
|
+
<QuotaDialogContent
|
|
890
|
+
api={api}
|
|
891
|
+
controller={controller}
|
|
892
|
+
sessionId={sessionId}
|
|
893
|
+
/>
|
|
819
894
|
))
|
|
820
895
|
continue
|
|
821
896
|
}
|
|
822
|
-
openCommandDialog(
|
|
823
|
-
|
|
897
|
+
openCommandDialog(
|
|
898
|
+
api,
|
|
899
|
+
message.payload,
|
|
900
|
+
(command, args) => rpcClient.apply({ command, arguments: args }),
|
|
901
|
+
sessionId,
|
|
824
902
|
)
|
|
825
903
|
}
|
|
826
904
|
})
|
package/dist/index-5s67238f.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{ia as Y,ka as K}from"./index-e7m7qbne.js";var V=Y((rz,O)=>{var{defineProperty:J,getOwnPropertyDescriptor:r,getOwnPropertyNames:t}=Object,e=Object.prototype.hasOwnProperty,o=(z,B)=>{for(var F in B)J(z,F,{get:B[F],enumerable:!0})},zz=(z,B,F,H)=>{if(B&&typeof B==="object"||typeof B==="function"){for(let G of t(B))if(!e.call(z,G)&&G!==F)J(z,G,{get:()=>B[G],enumerable:!(H=r(B,G))||H.enumerable})}return z},Bz=(z)=>zz(J({},"__esModule",{value:!0}),z),M={};o(M,{VercelOidcTokenError:()=>j});O.exports=Bz(M);class j extends Error{constructor(z,B){super(z);this.name="VercelOidcTokenError",this.cause=B}toString(){if(this.cause)return`${this.name}: ${this.message}: ${this.cause}`;return`${this.name}: ${this.message}`}}});var C=Y((tz,x)=>{var{create:Fz,defineProperty:v,getOwnPropertyDescriptor:Gz,getOwnPropertyNames:Hz,getPrototypeOf:Kz}=Object,Qz=Object.prototype.hasOwnProperty,Wz=(z,B)=>{for(var F in B)v(z,F,{get:B[F],enumerable:!0})},S=(z,B,F,H)=>{if(B&&typeof B==="object"||typeof B==="function"){for(let G of Hz(B))if(!Qz.call(z,G)&&G!==F)v(z,G,{get:()=>B[G],enumerable:!(H=Gz(B,G))||H.enumerable})}return z},N=(z,B,F)=>(F=z!=null?Fz(Kz(z)):{},S(B||!z||!z.__esModule?v(F,"default",{value:z,enumerable:!0}):F,z)),Xz=(z)=>S(v({},"__esModule",{value:!0}),z),E={};Wz(E,{findRootDir:()=>$z,getUserDataDir:()=>qz});x.exports=Xz(E);var Z=N(K("path")),Yz=N(K("fs")),A=N(K("os")),Zz=V();function $z(){try{let z=process.cwd();while(z!==Z.default.dirname(z)){let B=Z.default.join(z,".vercel");if(Yz.default.existsSync(B))return z;z=Z.default.dirname(z)}}catch(z){throw new Zz.VercelOidcTokenError("Token refresh only supported in node server environments")}return null}function qz(){if(process.env.XDG_DATA_HOME)return process.env.XDG_DATA_HOME;switch(A.default.platform()){case"darwin":return Z.default.join(A.default.homedir(),"Library/Application Support");case"linux":return Z.default.join(A.default.homedir(),".local/share");case"win32":if(process.env.LOCALAPPDATA)return process.env.LOCALAPPDATA;return null;default:return null}}});var c=Y((ez,g)=>{var{create:vz,defineProperty:b,getOwnPropertyDescriptor:bz,getOwnPropertyNames:Uz,getPrototypeOf:Lz}=Object,Jz=Object.prototype.hasOwnProperty,Vz=(z,B)=>{for(var F in B)b(z,F,{get:B[F],enumerable:!0})},y=(z,B,F,H)=>{if(B&&typeof B==="object"||typeof B==="function"){for(let G of Uz(B))if(!Jz.call(z,G)&&G!==F)b(z,G,{get:()=>B[G],enumerable:!(H=bz(B,G))||H.enumerable})}return z},u=(z,B,F)=>(F=z!=null?vz(Lz(z)):{},y(B||!z||!z.__esModule?b(F,"default",{value:z,enumerable:!0}):F,z)),Az=(z)=>y(b({},"__esModule",{value:!0}),z),P={};Vz(P,{isValidAccessToken:()=>wz,readAuthConfig:()=>Rz,writeAuthConfig:()=>Iz});g.exports=Az(P);var $=u(K("fs")),l=u(K("path")),Nz=k();function h(){let z=(0,Nz.getVercelDataDir)();if(!z)throw Error(`Unable to find Vercel CLI data directory. Your platform: ${process.platform}. Supported: darwin, linux, win32.`);return l.join(z,"auth.json")}function Rz(){try{let z=h();if(!$.existsSync(z))return null;let B=$.readFileSync(z,"utf8");if(!B)return null;return JSON.parse(B)}catch(z){return null}}function Iz(z){let B=h(),F=l.dirname(B);if(!$.existsSync(F))$.mkdirSync(F,{mode:504,recursive:!0});$.writeFileSync(B,JSON.stringify(z,null,2),{mode:384})}function wz(z){if(!z.token)return!1;if(typeof z.expiresAt!=="number")return!0;let B=Math.floor(Date.now()/1000);return z.expiresAt>=B}});var p=Y((oz,d)=>{var{defineProperty:w,getOwnPropertyDescriptor:Dz,getOwnPropertyNames:Tz}=Object,Mz=Object.prototype.hasOwnProperty,jz=(z,B)=>{for(var F in B)w(z,F,{get:B[F],enumerable:!0})},Oz=(z,B,F,H)=>{if(B&&typeof B==="object"||typeof B==="function"){for(let G of Tz(B))if(!Mz.call(z,G)&&G!==F)w(z,G,{get:()=>B[G],enumerable:!(H=Dz(B,G))||H.enumerable})}return z},Sz=(z)=>Oz(w({},"__esModule",{value:!0}),z),i={};jz(i,{processTokenResponse:()=>uz,refreshTokenRequest:()=>yz});d.exports=Sz(i);var R=K("os"),Ez="https://vercel.com",xz="cl_HYyOPBNtFMfHhaUn9L4QPfTZz6TP47bp",f=`@vercel/oidc node-${process.version} ${(0,R.platform)()} (${(0,R.arch)()}) ${(0,R.hostname)()}`,I=null;async function Cz(){if(I)return I;let z=`${Ez}/.well-known/openid-configuration`,B=await fetch(z,{headers:{"user-agent":f}});if(!B.ok)throw Error("Failed to discover OAuth endpoints");let F=await B.json();if(!F||typeof F.token_endpoint!=="string")throw Error("Invalid OAuth discovery response");let H=F.token_endpoint;return I=H,H}async function yz(z){let B=await Cz();return await fetch(B,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded","user-agent":f},body:new URLSearchParams({client_id:xz,grant_type:"refresh_token",...z})})}async function uz(z){let B=await z.json();if(!z.ok){let F=typeof B==="object"&&B&&"error"in B?String(B.error):"Token refresh failed";return[Error(F)]}if(typeof B!=="object"||B===null)return[Error("Invalid token response")];if(typeof B.access_token!=="string")return[Error("Missing access_token in response")];if(B.token_type!=="Bearer")return[Error("Invalid token_type in response")];if(typeof B.expires_in!=="number")return[Error("Missing expires_in in response")];return[null,B]}});var k=Y((zB,n)=>{var{create:Pz,defineProperty:U,getOwnPropertyDescriptor:lz,getOwnPropertyNames:hz,getPrototypeOf:gz}=Object,cz=Object.prototype.hasOwnProperty,kz=(z,B)=>{for(var F in B)U(z,F,{get:B[F],enumerable:!0})},a=(z,B,F,H)=>{if(B&&typeof B==="object"||typeof B==="function"){for(let G of hz(B))if(!cz.call(z,G)&&G!==F)U(z,G,{get:()=>B[G],enumerable:!(H=lz(B,G))||H.enumerable})}return z},_=(z,B,F)=>(F=z!=null?Pz(gz(z)):{},a(B||!z||!z.__esModule?U(F,"default",{value:z,enumerable:!0}):F,z)),iz=(z)=>a(U({},"__esModule",{value:!0}),z),m={};kz(m,{assertVercelOidcTokenResponse:()=>D,findProjectInfo:()=>sz,getTokenPayload:()=>mz,getVercelCliToken:()=>dz,getVercelDataDir:()=>fz,getVercelOidcToken:()=>pz,isExpired:()=>nz,loadToken:()=>_z,saveToken:()=>az});n.exports=iz(m);var q=_(K("path")),Q=_(K("fs")),X=V(),L=C(),W=c(),s=p();function fz(){let B=(0,L.getUserDataDir)();if(!B)return null;return q.join(B,"com.vercel.cli")}async function dz(){let z=(0,W.readAuthConfig)();if(!z)return null;if((0,W.isValidAccessToken)(z))return z.token||null;if(!z.refreshToken)return(0,W.writeAuthConfig)({}),null;try{let B=await(0,s.refreshTokenRequest)({refresh_token:z.refreshToken}),[F,H]=await(0,s.processTokenResponse)(B);if(F||!H)return(0,W.writeAuthConfig)({}),null;let G={token:H.access_token,expiresAt:Math.floor(Date.now()/1000)+H.expires_in};if(H.refresh_token)G.refreshToken=H.refresh_token;return(0,W.writeAuthConfig)(G),G.token??null}catch(B){return(0,W.writeAuthConfig)({}),null}}async function pz(z,B,F){let H=`https://api.vercel.com/v1/projects/${B}/token?source=vercel-oidc-refresh${F?`&teamId=${F}`:""}`,G=await fetch(H,{method:"POST",headers:{Authorization:`Bearer ${z}`}});if(!G.ok)throw new X.VercelOidcTokenError(`Failed to refresh OIDC token: ${G.statusText}`);let T=await G.json();return D(T),T}function D(z){if(!z||typeof z!=="object")throw TypeError("Vercel OIDC token is malformed. Expected an object. Please run `vc env pull` and try again");if(!("token"in z)||typeof z.token!=="string")throw TypeError("Vercel OIDC token is malformed. Expected a string-valued token property. Please run `vc env pull` and try again")}function sz(){let z=(0,L.findRootDir)();if(!z)throw new X.VercelOidcTokenError("Unable to find project root directory. Have you linked your project with `vc link?`");let B=q.join(z,".vercel","project.json");if(!Q.existsSync(B))throw new X.VercelOidcTokenError("project.json not found, have you linked your project with `vc link?`");let F=JSON.parse(Q.readFileSync(B,"utf8"));if(typeof F.projectId!=="string"&&typeof F.orgId!=="string")throw TypeError("Expected a string-valued projectId property. Try running `vc link` to re-link your project.");return{projectId:F.projectId,teamId:F.orgId}}function az(z,B){let F=(0,L.getUserDataDir)();if(!F)throw new X.VercelOidcTokenError("Unable to find user data directory. Please reach out to Vercel support.");let H=q.join(F,"com.vercel.token",`${B}.json`),G=JSON.stringify(z);Q.mkdirSync(q.dirname(H),{mode:504,recursive:!0}),Q.writeFileSync(H,G),Q.chmodSync(H,432);return}function _z(z){let B=(0,L.getUserDataDir)();if(!B)throw new X.VercelOidcTokenError("Unable to find user data directory. Please reach out to Vercel support.");let F=q.join(B,"com.vercel.token",`${z}.json`);if(!Q.existsSync(F))return null;let H=JSON.parse(Q.readFileSync(F,"utf8"));return D(H),H}function mz(z){let B=z.split(".");if(B.length!==3)throw new X.VercelOidcTokenError("Invalid token. Please run `vc env pull` and try again");let F=B[1].replace(/-/g,"+").replace(/_/g,"/"),H=F.padEnd(F.length+(4-F.length%4)%4,"=");return JSON.parse(Buffer.from(H,"base64").toString("utf8"))}function nz(z){return z.exp*1000<Date.now()}});
|
|
2
|
-
export{V as a,k as b};
|
package/dist/index-d9hq0tmc.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
function A(b){if(b==null||b==="")return;let g=typeof b==="number"?b:Number(b);if(Number.isFinite(g)){let q=g<100000000000?g*1000:g,B=new Date(q);return Number.isNaN(B.getTime())?void 0:B.toISOString()}let z=new Date(b);return Number.isNaN(z.getTime())?void 0:z.toISOString()}function C(b,g){let z=b.get(g);if(z===null||z.trim()==="")return;let q=Number(z);if(!Number.isFinite(q)||q<0||q>100)return;return{usedPercent:q,remainingPercent:100-q,resetsAt:A(b.get(`${g.slice(0,-13)}-reset-at`)??void 0),checkedAt:Date.now()}}function G(b){let g={},z=C(b,"x-codex-primary-used-percent");if(z)g.primary=z;let q=C(b,"x-codex-secondary-used-percent");if(q)g.secondary=q;return g}function D(b){if(!b)return;if(!Number.isFinite(b.used_percent)||b.used_percent<0||b.used_percent>100)return;return{usedPercent:b.used_percent,remainingPercent:100-b.used_percent,resetsAt:A(b.reset_at),checkedAt:Date.now()}}function J(b){let g={},z=D(b.rate_limits?.primary);if(z)g.primary=z;let q=D(b.rate_limits?.secondary);if(q)g.secondary=q;return g}function E(b){if(!b)return;if(!Number.isFinite(b.used_percent)||b.used_percent<0||b.used_percent>100)return;return{usedPercent:b.used_percent,remainingPercent:100-b.used_percent,resetsAt:A(b.reset_at),checkedAt:Date.now()}}function K(b){let g={},z=E(b.rate_limit?.primary_window);if(z)g.primary=z;let q=E(b.rate_limit?.secondary_window);if(q)g.secondary=q;return g}
|
|
2
|
-
export{A as c,G as d,J as e,K as f};
|
package/dist/index-mrg2fms9.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{ca as v}from"./index-qdh7pt5a.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 R,B as S,b as T,A as U,m as V,w as W,c as X,l as Y,o as Z,d as _,s as $};
|
package/dist/index-qdh7pt5a.js
DELETED
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
import{appendFileSync as Y,chmodSync as w,existsSync as B,renameSync as N,statSync as C}from"node:fs";import{tmpdir as F}from"node:os";import{join as x}from"node:path";var $={error:0,warn:1,info:2,debug:3,trace:4},A=!1,D=5242880;function X(){return process.env.OPENCODE_OPENAI_AUTH_LOG_FILE??x(F(),"opencode-openai-auth.log")}var G;function k(q){if(q===void 0||q in $)G=q}function I(){if(G)return G;let q=process.env.OPENCODE_OPENAI_AUTH_LOG_LEVEL;if(q&&q in $)return q;return"info"}var K=/^(authorization|x-api-key|cookie|set-cookie|refresh|access|token)$/i;function b(q){if(K.test(q))return!0;let H=q.toLowerCase().replace(/[-_]/g,"");if(H==="chatgptaccountid")return!0;if(H.includes("apikey"))return!0;if(H.endsWith("secret")||H.endsWith("password"))return!0;if(H.endsWith("token")&&!H.endsWith("tokens"))return!0;return!1}var L=/\b(Bearer\s+[\w.-]+|sk-[\w-]+|eyJ[\w.-]+)\b/g;function P(q){return M(q,new WeakSet)}function M(q,H){if(typeof q==="string")return q.replace(L,"***REDACTED***");if(Array.isArray(q)){if(H.has(q))return"[Circular]";H.add(q);let J=q.map((Q)=>M(Q,H));return H.delete(q),J}if(q&&typeof q==="object"){if(H.has(q))return"[Circular]";H.add(q);let J={};for(let[Q,j]of Object.entries(q))J[Q]=b(Q)?"***REDACTED***":M(j,H);return H.delete(q),J}return q}var Z=[],z,_=3;function U(q){try{w(q,384)}catch{}}function g(){try{let q=X();if(!(B(q)&&C(q).size>D))return;for(let J=_-1;J>=1;J--)if(B(`${q}.${J}`)){let Q=`${q}.${J+1}`;N(`${q}.${J}`,Q),U(Q)}let H=`${q}.1`;N(q,H),U(H)}catch{}}function V(){if(!Z.length)return;let q=Z.join("");Z=[];try{g();let H=X();if(B(H))U(H);Y(H,q,{encoding:"utf8",mode:384})}catch{}}function O(){if(!z)z=setTimeout(()=>{z=void 0,V()},500)}if(!A)process.on("exit",V);function p(q){try{return` ${JSON.stringify(P(q))}`}catch{return" [unserializable]"}}function W(q,H,J,Q){if($[H]>$[I()])return;let j=`[${new Date().toISOString()}] ${H.toUpperCase()} [${q}] ${J}`+(Q===void 0?"":p(Q))+`
|
|
2
|
-
`;if(Z.push(j),Z.length>=50)V();else O()}function y(q){return{error:(H,J)=>W(q,"error",H,J),warn:(H,J)=>W(q,"warn",H,J),info:(H,J)=>W(q,"info",H,J),debug:(H,J)=>W(q,"debug",H,J),trace:(H,J)=>W(q,"trace",H,J)}}
|
|
3
|
-
export{k as aa,P as ba,y as ca};
|
package/dist/index-y8d01tgn.js
DELETED
|
@@ -1,92 +0,0 @@
|
|
|
1
|
-
import{ca as g0}from"./index-qdh7pt5a.js";import{ka as U3}from"./index-e7m7qbne.js";import{createHash as e0}from"node:crypto";var B3=86400000,Z3=300000,$3=3600000,z3=60000,W3=900000,X3=300000;function W0(B){return B instanceof Error?B.message:String(B)}function G3(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 X0(B){let Z=W0(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 C0(B){return e0("sha256").update(B).digest("hex")}function S0(B){let Z=C0(B.refreshToken),z=(B.previous?.tokenHash===Z?B.previous.retryCount??0:0)+1,X,W=B.error?.retryAfter;if(typeof W==="number"&&W>0)X=W*1000;else if(G3(B.error))X=Math.min($3,Z3*2**Math.min(z-1,6));else X=B3;return{message:W0(B.error),checkedAt:B.now,nextRetryAt:B.now+X,retryCount:z,tokenHash:Z}}function q(B,Z,$){if(!B?.nextRetryAt||B.nextRetryAt<=$)return!1;if(!Z)return!0;return B.tokenHash===C0(Z)}function a(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 l(B){let $=(B.previous?.retryCount??0)+1,z,X=B.error?.retryAfter;if(typeof X==="number"&&X>0)z=X*1000;else if(X0(B.error))z=Math.min(W3,z3*2**Math.min($-1,6));else z=X3;return{message:W0(B.error),checkedAt:B.now,nextRetryAt:B.now+z,retryCount:$}}function I(B,Z){if(!B?.nextRetryAt||B.nextRetryAt<=Z)return!1;return!0}function G0(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 K3}from"node:http";import{setTimeout as Y3}from"node:timers/promises";var R0="0.3.4";var e="app_EMoamEEZ73f0CkXaXp7hrann",R="https://auth.openai.com",d=1455,J3=3000,x0=`cortexkit-opencode-openai-auth/${R0}`,A0="main",H3=`"${A0}" is a reserved account id; choose a different label.`;function I0(B){let Z=new Uint8Array(B),$=String.fromCharCode(...Z);return btoa($).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function j3(){let Z=Array.from(crypto.getRandomValues(new Uint8Array(43))).map((z)=>"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~"[z%66]).join(""),$=I0(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(Z)));return{verifier:Z,challenge:$}}function E0(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 y0(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 X=z[0];if(X&&typeof X==="object"&&!Array.isArray(X)&&typeof X.id==="string"&&X.id.length>0)return X.id}return}function t(B){if(B.id_token){let Z=E0(B.id_token),$=Z&&y0(Z);if($)return $}if(B.access_token){let Z=E0(B.access_token);return Z?y0(Z):void 0}return}function Q3(B){return typeof B==="string"&&B.toLowerCase()===A0}function K0(B){if(Q3(B))throw Error(H3);return B}function V3(B,Z,$){let z=new URLSearchParams({response_type:"code",client_id:e,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 N3(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:e,code_verifier:$.verifier}).toString()});if(!z.ok)throw Error(`Token exchange failed: ${z.status}`);return await z.json()}function L3(B){return B.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}var b3=`<!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>`,o=(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">${L3(B)}</div>
|
|
85
|
-
</div>
|
|
86
|
-
</body>
|
|
87
|
-
</html>`,i,g,O=new Map;function C(){return O.size}function E(B){if(O.delete(B),C()===0)S()}async function F3(){let B=`http://localhost:${d}/auth/callback`;if(i)return{port:d,redirectUri:B};if(g)return g;g=(async()=>{let Z=K3(($,z)=>{let X=new URL($.url||"/",`http://127.0.0.1:${d}`);if(X.pathname==="/auth/callback"){let W=X.searchParams.get("code"),G=X.searchParams.get("state"),K=X.searchParams.get("error"),Y=X.searchParams.get("error_description");if(K){let H=Y||K;if(G){let V=O.get(G);if(V)V.reject(Error(H)),E(G);else if(C()===0)S()}else if(C()===0)S();z.writeHead(200,{"Content-Type":"text/html"}),z.end(o(H));return}if(!G){if(C()===0)S();z.writeHead(400,{"Content-Type":"text/html"}),z.end(o("Missing state parameter"));return}if(!W){if(C()===0)S();z.writeHead(400,{"Content-Type":"text/html"}),z.end(o("Missing authorization code"));return}let J=O.get(G);if(!J){if(C()===0)S();z.writeHead(400,{"Content-Type":"text/html"}),z.end(o("Unknown state — authorization may have expired"));return}E(G),N3(W,B,J.pkce).then((H)=>J.resolve(H)).catch((H)=>J.reject(H)),z.writeHead(200,{"Content-Type":"text/html"}),z.end(b3);return}if(X.pathname==="/cancel"){let W=X.searchParams.get("state"),G=W?[W]:[...O.keys()];z.writeHead(200),z.end("Login cancelled");for(let K of G){let Y=O.get(K);if(!Y)continue;Y.reject(Error("Login cancelled")),E(K)}if(C()===0)S();return}z.writeHead(404),z.end("Not found")});return await new Promise(($,z)=>{Z.once("error",z),Z.listen(d,"127.0.0.1",()=>{Z.off("error",z),$()})}),i=Z,{port:d,redirectUri:B}})();try{return await g}finally{g=void 0}}function S(){if(i){let B=i;i=void 0,B.close(()=>{}),B.closeIdleConnections?.(),setTimeout(()=>{B.closeAllConnections?.()},25).unref?.()}}function D3(B,Z,$=300000,z){return new Promise((X,W)=>{if(z?.aborted){E(Z),W(Error("Login cancelled"));return}let G=setTimeout(()=>{if(O.get(Z))E(Z),W(Error("OAuth callback timeout — authorization took too long"))},$),K=()=>{if(clearTimeout(G),O.get(Z))E(Z),W(Error("Login cancelled"))};if(z)z.addEventListener("abort",K);O.set(Z,{pkce:B,state:Z,resolve:(Y)=>{if(clearTimeout(G),z)z.removeEventListener("abort",K);X(Y)},reject:(Y)=>{if(clearTimeout(G),z)z.removeEventListener("abort",K);W(Y)}})})}async function O3(){let B=await fetch(`${R}/api/accounts/deviceauth/usercode`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":x0},body:JSON.stringify({client_id:e})});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 P3(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),X=!Number.isNaN(z)&&z>0?z*1000:900000,W=Date.now();while(!0){if(Z?.aborted)throw Error("Device authorization cancelled");if(Date.now()-W>X)throw Error("Device authorization expired");let G=await fetch(`${R}/api/accounts/deviceauth/token`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":x0},body:JSON.stringify({device_auth_id:B.device_auth_id,user_code:B.user_code})});if(G.ok){let J=await G.json(),H=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:e,code_verifier:J.code_verifier}).toString()});if(!H.ok)throw Error(`Token exchange failed: ${H.status}`);return await H.json()}if(G.status!==403&&G.status!==404)throw Error(`Device authorization failed: ${G.status}`);let K=X-(Date.now()-W);if(K<=0)throw Error("Device authorization expired");let Y=Math.min($+J3,K);try{await Y3(Y,void 0,{signal:Z})}catch(J){if(J instanceof Error&&J.name==="AbortError")throw Error("Device authorization cancelled");throw J}}}function a4(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 o4(B={}){let{label:Z,headless:$=!1,signal:z}=B;if(K0(Z),$){let{deviceData:J,url:H,instructions:V}=await O3(),F=(async()=>{let Q=await P3(J,z),N=Date.now(),_=t(Q);return{id:K0(Z||_||crypto.randomUUID()),label:Z||void 0,type:"oauth",access:Q.access_token,refresh:Q.refresh_token,expires:N+(Q.expires_in??3600)*1000,enabled:!0,addedAt:N,lastUsed:N,lastRefreshedAt:N,accountId:_}})();return{url:H,instructions:V,completion:F}}let{redirectUri:X}=await F3(),W=await j3(),G=I0(crypto.getRandomValues(new Uint8Array(32)).buffer),K=V3(X,W,G),Y=(async()=>{try{if(z?.aborted)throw Error("Login cancelled");let J=await D3(W,G,void 0,z),H=Date.now(),V=t(J);return{id:K0(Z||V||crypto.randomUUID()),label:Z||void 0,type:"oauth",access:J.access_token,refresh:J.refresh_token,expires:H+(J.expires_in??3600)*1000,enabled:!0,addedAt:H,lastUsed:H,lastRefreshedAt:H,accountId:V}}finally{E(G)}})();return{url:K,instructions:"Complete authorization in your browser. This window will close automatically.",completion:Y}}var T="primary",f="secondary",M3="app_EMoamEEZ73f0CkXaXp7hrann",_3="https://auth.openai.com";async function BB(B){let Z=await B.fetchImpl(`${_3}/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:M3}).toString()});if(!Z.ok){let z=G0(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 q3="https://chatgpt.com/backend-api/wham/usage";async function ZB(B){let Z=await B.fetchImpl(q3,{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=G0(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-dfdpwwm3.js");return $(await Z.json())}import{randomUUID as Y0}from"node:crypto";import{mkdir as C3,readFile as J0,rename as S3,rm as u,stat as T0,writeFile as H0}from"node:fs/promises";import{homedir as R3}from"node:os";import{dirname as KB,join as s}from"node:path";var E3=globalThis.setTimeout.bind(globalThis),y3=globalThis.clearTimeout.bind(globalThis),x3="openai-auth.json";function A3(){if(process.env.OPENCODE_CONFIG_DIR?.trim())return process.env.OPENCODE_CONFIG_DIR.trim();return s(process.env.XDG_CONFIG_HOME||s(R3(),".config"),"opencode")}function I3(B){let Z=B?.code;return Z==="ENOENT"||Z==="EINVAL"||Z==="ENOTDIR"}function T3(){return process.env.OPENCODE_OPENAI_AUTH_FILE?.trim()||s(A3(),x3)}async function m(B){let $=`${B.path??T3()}.${B.name}.lock`,z=s($,"owner.json"),X=Y0(),W=B.now??Date.now,G=null,K=!1;async function Y(){try{return JSON.parse(await J0($,"utf8"))}catch(Q){if(Q.code!=="EISDIR")throw Q;return JSON.parse(await J0(z,"utf8"))}}async function J(){await H0($,`${JSON.stringify({ownerId:X,expiresAt:W()+B.ttlMs})}
|
|
88
|
-
`,{encoding:"utf8",mode:384})}async function H(){try{return await H0($,`${JSON.stringify({ownerId:X,expiresAt:W()+B.ttlMs})}
|
|
89
|
-
`,{encoding:"utf8",mode:384,flag:"wx"}),!0}catch(Q){let N=Q.code;if(N==="EEXIST"||N==="EISDIR")return!1;throw Q}}function V(){if(!B.renew||K)return;let Q=B.renewIntervalMs??Math.max(1000,Math.floor(B.ttlMs/3));if(G=E3(()=>{(async()=>{try{let N=await Y(),_=W();if(K||N?.ownerId!==X||Number(N?.expiresAt)<=_)return;await J(),V()}catch{}})()},Q),"unref"in G)G.unref()}let F=await H();if(!F){let Q=`${$}.evicting`,N=s(Q,"owner.json"),_=Y0(),l4=5000,d4=8;async function c(){await new Promise((D)=>setTimeout(D,Math.floor(Math.random()*4)))}async function P0(){try{let D=await Y();return Number(D?.expiresAt)>W()}catch{try{return(await T0($)).mtimeMs+B.ttlMs>W()}catch{return!1}}}async function v(){try{return JSON.parse(await J0(N,"utf8"))?.ownerId===_}catch{return!1}}async function t0(){await C3(Q);try{await H0(N,`${JSON.stringify({ownerId:_,createdAt:W()})}
|
|
90
|
-
`,{encoding:"utf8",mode:384,flag:"wx"})}catch(D){if(I3(D))return!1;throw await U0(),D}return await B.onStep?.("eviction-marker-acquired"),!0}async function U0(){if(await v())await u(Q,{recursive:!0,force:!0}).catch(()=>{})}for(let D=0;D<8;D++){if(F=await H(),F)break;if(await P0())return null;try{if(!await t0()){await c();continue}}catch(M0){if(M0.code!=="EEXIST")throw M0;let _0;try{_0=await T0(Q)}catch(p){if(p.code==="ENOENT"){await c();continue}throw p}if(_0.mtimeMs+5000>W())return null;await B.onStep?.("stale-marker-stat");let q0=`${Q}.${Y0()}`;try{await S3(Q,q0)}catch(p){if(p.code==="ENOENT"){await c();continue}throw p}await B.onStep?.("stale-marker-claimed"),await u(q0,{recursive:!0,force:!0}).catch(()=>{}),await c();continue}try{if(await P0())return null;if(!await v())return null;if(await B.onStep?.("stale-lock-confirmed"),!await v())return null;if(await u($,{recursive:!0,force:!0}).catch(()=>{}),!await v())return null;if(F=await H(),!F)return null;if(!await v())return await u($,{recursive:!0,force:!0}).catch(()=>{}),F=!1,null;break}finally{await U0()}}}if(!F)return null;return V(),{release:async()=>{if(K=!0,G)y3(G),G=null;try{if((await Y())?.ownerId!==X)return}catch{return}await u($,{recursive:!0,force:!0}).catch(()=>{})}}}import{createHash as f3}from"node:crypto";var m3=globalThis.setTimeout,w3=5;function w(B){let Z=B?.quota?.checkIntervalMinutes??w3;return Math.max(1,Z)*60000}function k3(B){return B?.quota?.enabled!==!1}function Q0(B,Z){if(!B?.resetsAt)return!1;let $=Date.parse(B.resetsAt);return Number.isFinite($)&&$<=Z}function VB(B,Z,$,z){let X=Z===T?B?.primary:Z===f?B?.secondary:void 0,W=X?.resetsAt?Date.parse(X.resetsAt):NaN;if(Number.isFinite(W)&&W>$)return W;return $+z}function h3(B){let Z=B?.quota?.minimumRemaining||{};return{primary:Z.primary??Z["5h"]??15,secondary:Z.secondary??Z["1w"]??10}}function f0(B,Z,$){if(!k3(Z))return $+w(Z);let z=h3(Z),X=[];for(let W of["primary","secondary"]){let G=B?.[W];if(!G)return $+w(Z);if(G.remainingPercent>=z[W])continue;let K=G.resetsAt?Date.parse(G.resetsAt):Number.NaN;if(!Number.isFinite(K)||K<=$)return $+w(Z);X.push(K)}if(!X.length)return $+w(Z);return Math.min(...X)+60000}function v3(B){if(!B?.quota?.mainQuota||!B.quota.mainQuotaCheckedAt)return null;return{quota:B.quota.mainQuota,checkedAt:B.quota.mainQuotaCheckedAt,tokenFingerprint:B.quota.mainQuotaToken}}function p3(B){let Z=B?.quota?.refreshEveryNRequests;return typeof Z==="number"&&Number.isFinite(Z)&&Z>0?Math.floor(Z):0}function b(B){return f3("sha256").update(B).digest("hex").slice(0,16)}class P{main=null;mainTokenFp=null;mainQuotaAccountId=null;fallbacks=new Map;fallbackTokenFps=new Map;inflightMain=null;inflightMainFp=null;inflightFallbacks=new Map;mainLastApiError=void 0;fallbackApiErrors=new Map;fallbackErrorTokenFps=new Map;rateLimitedUntilMap=new Map;apiGate=Promise.resolve();lastApiCallAt=0;storage;fetchImpl;now;fetchQuotaFn;onMainQuotaFetched;onApiError;constructor(B){this.storage=B.storage,this.fetchImpl=B.fetchImpl??fetch,this.now=B.now??Date.now,this.fetchQuotaFn=B.fetchQuotaFn,this.onMainQuotaFetched=B.onMainQuotaFetched,this.onApiError=B.onApiError,this.seedMainFromStorage(B.storage),this.seedMainBackoffFromStorage(B.storage)}getMain(B){if(B&&this.main&&this.mainTokenFp&&this.mainTokenFp!==b(B))this.main=null,this.mainTokenFp=null;return this.main}getFallback(B,Z){let $=this.fallbacks.get(B)??null;if(!Z||!$)return $;if(this.fallbackTokenFps.get(B)!==b(Z))return this.fallbacks.delete(B),this.fallbackTokenFps.delete(B),null;return $}getAllFallbacks(){return this.fallbacks}setMain(B,Z,$){if(!m0(Z.quota))return;if(this.mainTokenFp=b(B),$&&this.mainQuotaAccountId&&this.mainQuotaAccountId!==$)this.clearRateLimited("main");if($)this.mainQuotaAccountId=$;if(this.main=Z,j0(Z.quota))this.clearRateLimited("main")}peekMainForPolicy(B){if(B&&this.mainQuotaAccountId&&this.mainQuotaAccountId!==B)return null;return this.main}peekFallbackForPolicy(B){return this.fallbacks.get(B)??null}setFallback(B,Z,$){if(!m0(Z.quota))return;if(this.fallbacks.set(B,Z),$)this.fallbackTokenFps.set(B,b($));else this.fallbackTokenFps.delete(B);if(j0(Z.quota))this.clearRateLimited(B)}markRateLimited(B,Z){let $=this.rateLimitedUntilMap.get(B);if($!==void 0&&$>Z)return;this.rateLimitedUntilMap.set(B,Z)}isRateLimited(B){let Z=this.rateLimitedUntilMap.get(B);return Z!==void 0&&this.now()<Z}rateLimitedUntil(B){return this.rateLimitedUntilMap.get(B)}clearRateLimited(B){this.rateLimitedUntilMap.delete(B)}async refreshMain(B){let Z=b(B);if(this.mainTokenFp&&this.mainTokenFp!==Z)this.main=null,this.mainTokenFp=null;if(this.inflightMain&&this.inflightMainFp===Z)return this.inflightMain;if(this.isBackedOff()){if(this.main)return this.main.quota;throw Error("Quota API rate-limited — try again later")}return this.inflightMainFp=Z,this.inflightMain=this._fetchMain(B),this.inflightMain}async refreshFallback(B,Z){let $=P.fallbackInflightKey(B,Z),z=this.inflightFallbacks.get($);if(z)return z;if(this.isFallbackBackedOff(B,Z)){let W=this.getFallback(B,Z);if(W)return W.quota;throw Error("Quota API rate-limited — try again later")}let X=this._fetchFallback(B,Z);return this.inflightFallbacks.set($,X),X}async refreshAllFallbacks(B){let Z=this.now();for(let $ of B){if($.enabled===!1)continue;if(!$.access)continue;let z=this.getFallback($.id,$.access);if(z&&Z<z.refreshAfter)continue;try{await this.refreshFallback($.id,$.access)}catch{}}}refreshMainInBackground(B){let Z=b(B);if(this.inflightMain&&this.inflightMainFp===Z)return;if(this.isBackedOff())return;this.refreshMain(B).catch(()=>{})}isMainStale(){if(!this.main)return!0;return this.now()>=this.main.refreshAfter}isFallbackStale(B,Z){let $=this.getFallback(B,Z);if(!$)return!0;return this.now()>=$.refreshAfter}shouldRefreshOnRequestCount(B){let Z=p3(this.storage);if(Z<=0)return!1;return B>0&&B%Z===0}needsRefresh(B){return this.isMainStale()||this.shouldRefreshOnRequestCount(B)}updateStorage(B){this.storage=B,this.seedMainFromStorage(B),this.seedMainBackoffFromStorage(B)}seedMainFromStorage(B,Z){let $=v3(B);if(!$)return;let z=Z?b(Z):null;if(z&&$.tokenFingerprint&&$.tokenFingerprint!==z)return;let X={quota:$.quota,refreshAfter:f0($.quota,B,$.checkedAt),checkedAt:$.checkedAt};if(this.main&&this.main.checkedAt>=X.checkedAt&&(!z||!this.mainTokenFp||this.mainTokenFp===z))return;if(this.main=X,this.mainTokenFp=$.tokenFingerprint??null,B?.mainAccountId){if(this.mainQuotaAccountId&&this.mainQuotaAccountId!==B.mainAccountId)this.clearRateLimited("main");this.mainQuotaAccountId=B.mainAccountId}}seedMainBackoffFromStorage(B){let Z=B?.quota?.mainLastQuotaApiError;this.mainLastApiError=Z&&I(Z,this.now())?Z:void 0}seedFallbacksFromAccounts(B){let Z=w(this.storage);for(let $ of B){if($.enabled===!1)continue;if(!$.quota)continue;let z=Math.max($.quota.primary?.checkedAt??0,$.quota.secondary?.checkedAt??0);if(z<=0)continue;let X=this.getFallback($.id,$.access);if(X&&X.checkedAt>=z)continue;this.setFallback($.id,{quota:$.quota,refreshAfter:z+Z,checkedAt:z},$.access)}}isBackedOff(){return I(this.mainLastApiError,this.now())}isFallbackBackedOff(B,Z){if(Z){if(this.fallbackErrorTokenFps.get(B)!==b(Z))return!1}return I(this.fallbackApiErrors.get(B),this.now())}getLastApiError(){return this.mainLastApiError}static API_CALL_GAP_MS=1000;static fallbackInflightKey(B,Z){return JSON.stringify([B,b(Z)])}static quotaLockName(B){return`opencode-fallback-quota-refresh-${B.replace(/[^a-zA-Z0-9._-]+/g,"-")||"account"}`}_enqueueApiFetch(B){let Z=async()=>{let z=this.now()-this.lastApiCallAt;if(z<P.API_CALL_GAP_MS)await new Promise((X)=>{let W=m3(X,P.API_CALL_GAP_MS-z);if(typeof W==="object"&&"unref"in W)W.unref()});return this.lastApiCallAt=this.now(),B()},$=this.apiGate.then(Z,Z);return this.apiGate=$.catch(()=>{}),$}async _fetchMain(B){let Z=b(B);return this._enqueueApiFetch(async()=>{try{if(this.isBackedOff()){if(this.main)return this.main.quota;throw Error("Quota API rate-limited — try again later")}let $=await m({name:"opencode-main-quota-refresh",ttlMs:30000});if(!$){let z=this.main;if(z&&this.now()<z.refreshAfter)return z.quota;throw Error("Quota refresh is already in progress")}try{let z=this.now(),X=await this._fetchQuota(B),W=this.now();if(this.mainTokenFp=b(B),this.main={quota:X,refreshAfter:f0(X,this.storage,W),checkedAt:W},j0(X))this.clearRateLimited("main");return this.mainLastApiError=void 0,this.onMainQuotaFetched?.(X,W,this.mainTokenFp,z),X}catch(z){throw this._handleMainFetchError(z),z}finally{await $.release()}}finally{if(this.inflightMainFp===Z)this.inflightMain=null,this.inflightMainFp=null}})}async _fetchFallback(B,Z){return this._enqueueApiFetch(async()=>{try{if(this.isFallbackBackedOff(B,Z)){let z=this.getFallback(B,Z);if(z)return z.quota;throw Error("Quota API rate-limited — try again later")}let $=await m({name:P.quotaLockName(B),ttlMs:30000});if(!$){let z=this.getFallback(B,Z);if(z&&this.now()<z.refreshAfter)return z.quota;throw Error("Quota refresh is already in progress")}try{let z=await this._fetchQuota(Z),X=this.now();return this.setFallback(B,{quota:z,refreshAfter:X+w(this.storage),checkedAt:X},Z),this.fallbackApiErrors.delete(B),this.fallbackErrorTokenFps.delete(B),z}finally{await $.release()}}catch($){throw this._handleFallbackFetchError(B,Z,$),$}finally{this.inflightFallbacks.delete(P.fallbackInflightKey(B,Z))}})}async _fetchQuota(B){if(!this.fetchQuotaFn)throw Error("Quota fetch not available — no fetchQuotaFn injected (push-only mode)");return this.fetchQuotaFn({accessToken:B,fetchImpl:this.fetchImpl,now:this.now})}static isAuthError(B){return B?.status===401}_handleMainFetchError(B){if(P.isAuthError(B))return;this.mainLastApiError=l({error:B,now:this.now(),previous:this.mainLastApiError}),this.onApiError?.(this.mainLastApiError)}_handleFallbackFetchError(B,Z,$){if(P.isAuthError($))return;let z=b(Z),X=this.fallbackErrorTokenFps.get(B)===z?this.fallbackApiErrors.get(B):void 0;this.fallbackApiErrors.set(B,l({error:$,now:this.now(),previous:X})),this.fallbackErrorTokenFps.set(B,z)}}function m0(B){for(let Z of Object.keys(B))return!0;return!1}function j0(B){let{primary:Z,secondary:$}=B;if(!Z||!$)return!1;return Z.usedPercent<100&&$.usedPercent<100}import{createHash as r3,randomUUID as n3}from"node:crypto";import{homedir as c3}from"node:os";import{dirname as a3,join as B0}from"node:path";import{setTimeout as o3}from"node:timers/promises";import{randomUUID as l3}from"node:crypto";import{mkdir as d3,rename as g3,rm as i3,writeFile as u3}from"node:fs/promises";import{dirname as s3}from"node:path";async function k(B,Z){await d3(s3(B),{recursive:!0});let $=`${B}.${l3()}.tmp`;await u3($,`${JSON.stringify(Z,null,2)}
|
|
91
|
-
`,{encoding:"utf8",mode:384});try{await g3($,B)}catch(z){throw await i3($,{force:!0}).catch(()=>{}),z}}import{readFile as Y4}from"node:fs/promises";var y=g0("refresh"),w0=1e4,t3=50,i0="openai-auth.json",e3="openai-auth-state.json";function B4(){if(process.env.OPENCODE_CONFIG_DIR?.trim())return process.env.OPENCODE_CONFIG_DIR.trim();return B0(process.env.XDG_CONFIG_HOME||B0(c3(),".config"),"opencode")}function h(){return process.env.OPENCODE_OPENAI_AUTH_FILE?.trim()||B0(B4(),i0)}function z0(B=h()){let Z=process.env.OPENCODE_OPENAI_AUTH_STATE_FILE?.trim();if(Z)return Z;return Z4(B)}function Z4(B){return B.endsWith(i0)?B0(a3(B),e3):`${B}.state.json`}function U(B){return B.type==="oauth"}function $4(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 xB(B){return B.costZeroing?.enabled!==!1}class Z0 extends Error{code="ACCOUNT_REMOVED_DURING_REFRESH";constructor(B){super(`Fallback account ${B} was removed before refresh`);this.name="AccountRemovedDuringRefreshError"}}var z4=[401,403,429],k0={primary:0,secondary:0},W4=!1,L0={primary:5,secondary:10};function j(B){return B!=null&&typeof B==="object"&&!Array.isArray(B)}function X4(B){return B instanceof Z0||j(B)&&B.name==="AccountRemovedDuringRefreshError"&&B.code==="ACCOUNT_REMOVED_DURING_REFRESH"}function h0(B){return{id:typeof B.id==="string"&&B.id.trim()?B.id.trim():n3(),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 v0(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 G4(B){if(!j(B))return;let Z={};for(let $ of["primary","secondary"]){let z=B[$];if(!j(z))continue;let X=Number(z.usedPercent),W=Number(z.remainingPercent),G=Number(z.checkedAt);if(!Number.isFinite(X)||!Number.isFinite(W)||!Number.isFinite(G))continue;Z[$]={usedPercent:X,remainingPercent:W,checkedAt:G,resetsAt:typeof z.resetsAt==="string"?z.resetsAt:void 0}}return Object.keys(Z).length?Z:void 0}function K4(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(!$4(Z))return null;let z=B.authHeader==="x-api-key"?"x-api-key":"authorization-bearer";return{...h0(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{...h0(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:v0(B.lastRefreshError),lastQuotaRefreshError:v0(B.lastQuotaRefreshError),quota:G4(B.quota)}}function u0(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(K4).filter((Z)=>Z!=null)}}async function A(B){try{return{exists:!0,value:JSON.parse(await Y4(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))}async function J4(B){let Z;try{Z=(await A(B)).value}catch{return null}if(!j(Z)||!Array.isArray(Z.accounts))return null;let $=new Set;for(let z of Z.accounts)if(j(z)&&typeof z.id==="string")$.add(z.id);return $}function s0(B,Z){if(!j(B))return B;let $=j(Z)?Z:{},z=j($.main)?$.main:void 0,X=j($.accounts)?$.accounts:{},W=j(B.quota)?B.quota:{},G=j(B.refresh)?B.refresh:{},K=z??W,Y=z??G,H=Array.isArray(B.accounts)?B.accounts.map((V)=>{if(!j(V))return V;let F=typeof V.id==="string"&&j(X[V.id])?X[V.id]:{};return{...V,...F}}):void 0;return r0({...B,refresh:M({...G,mainLastRefreshError:Y.lastRefreshError,mainRefreshLeaseId:Y.refreshLeaseId,mainRefreshLeaseUntil:Y.refreshLeaseUntil,mainRefreshLeaseTokenHash:Y.refreshLeaseTokenHash}),quota:M({...W,mainQuota:K.quota,mainQuotaCheckedAt:K.quotaCheckedAt,mainQuotaToken:K.quotaToken,mainLastQuotaApiError:K.lastQuotaApiError}),accounts:H})}async function H4(B=h()){let Z=await A(B);if(!Z.exists)return null;let $=await A(z0(B));return u0(s0(Z.value,$.value))}function r0(B){return Object.fromEntries(Object.entries(B).filter(([,Z])=>Z!==void 0))}function j4(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 n0(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 $0(B){return Math.max(B?.primary?.checkedAt??0,B?.secondary?.checkedAt??0)}function r(B,Z,$){if($ in Z)B[$]=Z[$];else delete B[$]}function Q4(B,Z){return B.access===Z.access&&B.refresh===Z.refresh&&B.expires===Z.expires&&B.lastRefreshedAt===Z.lastRefreshedAt}function V4(B,Z){if(!Q4(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 N4(B,Z,$){let z=Z.lastRefreshedAt??0,X=$.lastRefreshedAt??0,W=Z.expires??0,G=$.expires??0,K=X>z?$:z>X?Z:G>W?$:W>G?Z:V4(Z,$);r(B,K,"access"),r(B,K,"refresh"),r(B,K,"expires"),r(B,K,"lastRefreshedAt"),r(B,K,"lastRefreshError")}function L4(B,Z){if(!j(B))return Z;let $=B,z=$0($.quota),X=$0(Z.quota),W=z>X,G=W?{...$,...Z,quota:$.quota,lastQuotaRefreshError:$.lastQuotaRefreshError}:{...$,...Z};if(!W&&!("lastQuotaRefreshError"in Z))delete G.lastQuotaRefreshError;if(!("lastRefreshError"in Z))delete G.lastRefreshError;if(typeof $.lastUsed==="number"&&(typeof Z.lastUsed!=="number"||$.lastUsed>Z.lastUsed))G.lastUsed=$.lastUsed;return N4(G,$,Z),G}function c0(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 r0({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(j4)})}async function n(B){let Z=Date.now()+w0;while(Date.now()<=Z){let $=await m({name:"save",ttlMs:w0,path:B});if($)return $;let z=Z-Date.now();if(z<=0)break;await o3(Math.min(t3,z))}throw Error(`Timed out acquiring account store lock for ${B}; refusing to overwrite newer account data`)}function a0(B){let Z=Object.fromEntries(B.accounts.map(($)=>[$.id,n0($)]));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 IB(B,Z=h()){let $=z0(Z),z=await n(Z);try{let X=await n($);try{let W=await A(Z),G=await A($),K=(W.exists?u0(s0(W.value,G.value)):null)??b4(),Y=B(K)??K,H={...j(W.value)?W.value:{},...c0(Y)};return await k(Z,H),await k($,a0(Y)),Y}finally{await X.release()}}finally{await z.release()}}function b4(){return{version:1,main:{type:"opencode",provider:"openai"},accounts:[]}}function F4(B,Z){B.main=B.main??{};let $=typeof B.main.quotaCheckedAt==="number"?B.main.quotaCheckedAt:$0(B.main.quota),z=typeof Z.quota?.mainQuotaCheckedAt==="number"?Z.quota.mainQuotaCheckedAt:$0(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 D4(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 b0(B){if(Array.isArray(B))return B.map(b0);if(!j(B))return B;return Object.fromEntries(Object.entries(B).filter(([,Z])=>Z!==void 0).map(([Z,$])=>[Z,b0($)]))}async function O4(B,Z=h(),$={mainQuota:!0,mainRefresh:!0,accounts:!0}){let z=z0(Z),X=await n(z);try{let W=(await A(z)).value,G=j(W)?{...W,version:1}:{version:1};if($.mainQuota)F4(G,B);if($.mainRefresh)D4(G,B);if($.accounts){let K=$.accounts===!0?null:new Set($.accounts),Y=await J4(Z);G.accounts={...j(G.accounts)?G.accounts:{}};for(let J of B.accounts){if(K&&!K.has(J.id))continue;if(Y&&!Y.has(J.id))continue;G.accounts[J.id]=L4(G.accounts[J.id],n0(J))}if(K){for(let J of K)if(!B.accounts.some((H)=>H.id===J))delete G.accounts[J]}if(Y){for(let J of Object.keys(G.accounts))if(!Y.has(J))delete G.accounts[J]}}await k(z,b0(G))}finally{await X.release()}}function P4(B){return B?.fallbackOn?.length?B.fallbackOn:z4}function TB(B,Z){return P4(Z).includes(B)}function U4(B){let Z=B?.quota?.minimumRemaining||{};return{primary:Z.primary??Z["5h"]??k0.primary,secondary:Z.secondary??Z["1w"]??k0.secondary}}function F0(B){return B?.quota?.enabled!==!1}function O0(B){return B?.quota?.failClosedOnUnknownQuota??W4}function o0(B,Z,$=Date.now()){if(!F0(Z))return!0;let z=U4(Z);for(let X of["primary","secondary"]){let W=B?.[X];if(!W||Q0(W,$))return!O0(Z);if(W.remainingPercent<z[X])return!1}return!0}function M4(B){return B?.killswitch?.enabled===!0}function p0(B){return{primary:B?.primary??B?.["5h"]??L0.primary,secondary:B?.secondary??B?.["1w"]??L0.secondary}}function _4(B,Z){if(!B?.killswitch)return L0;if(Z&&B.killswitch.accounts?.[Z])return p0(B.killswitch.accounts[Z]);return p0(B.killswitch.main)}function fB(B,Z,$,z=Date.now()){if(!M4(Z))return!0;let X=_4(Z,$),W=!1;for(let G of["primary","secondary"]){let K=B?.[G];if(!K||Q0(K,z)){W=!0;continue}if(K.remainingPercent<X[G])return!1}if(W)return!O0(Z);return!0}function mB(B,Z,$){let z=[],X=[B,...Z.map((G)=>G.quota)];for(let G of X)for(let K of["primary","secondary"]){let Y=G?.[K]?.resetsAt;if(!Y)continue;let J=Date.parse(Y);if(Number.isFinite(J)&&J>$)z.push(J)}if(z.length===0)return 300;let W=Math.min(...z);return Math.max(1,Math.ceil((W-$)/1000))}function q4(B){return typeof B.version==="number"&&Array.isArray(B.accounts)}async function wB(B,Z=h()){let $=z0(Z),z=await n(Z);try{let X=await n($);try{let W=await A(Z);if(W.exists&&j(W.value)){if(q4(W.value))return}if(!B)return;let G={version:1,main:{type:"opencode",provider:"openai"},accounts:[]};if(B.access){let J=t({id_token:"",access_token:B.access,refresh_token:B.refresh});if(J)G.mainAccountId=J}let Y={...W.exists&&j(W.value)?W.value:{},...c0(G)};await k(Z,Y),await k($,a0(G))}finally{await X.release()}}finally{await z.release()}}function C4(B){return B?.refresh?.enabled!==!1}function S4(B){return(B?.refresh?.refreshBeforeExpiryMinutes??240)*60000}function R4(B){return Math.floor(Math.random()*(B+1))}function x(B,Z,$){return!B.access||!B.expires||B.expires-$<=S4(Z)}function E4(B,Z){return Boolean(B.access&&typeof B.expires==="number"&&B.expires>Z)}function y4(B,Z){return Boolean(B.mainAccountId&&Z.accountId&&Z.accountId===B.mainAccountId)}function L(B,Z){let $=B.accounts.findIndex((z)=>z.id===Z.id);if($!==-1)B.accounts[$]=Z}function V0(B){return B instanceof Error?B.message:String(B)}function D0(B,Z,$){B.lastRefreshError=S0({error:Z,now:$,refreshToken:B.refresh,previous:B.lastRefreshError})}function N0(B,Z,$){if(B.lastQuotaRefreshError=l({error:Z,now:$,previous:B.lastQuotaRefreshError}),Z?.isRefreshError===!0)D0(B,Z,$)}function x4(B){return`fallback-oauth-refresh-${r3("sha256").update(B).digest("base64url").slice(0,16)}`}function l0(B,Z){if(!B)return!1;if(!B.resetsAt)return!0;let $=Date.parse(B.resetsAt);return Number.isFinite($)?$>Z:!0}function A4(B,Z){if(!B)return!1;return l0(B[T],Z)||l0(B[f],Z)}function I4(B,Z,$){if(!B)return!1;let z=Z?.quota?.checkIntervalMinutes??5,X=Math.max(1,z)*60000,W=Math.max(B[T]?.checkedAt??0,B[f]?.checkedAt??0);return $-W<X}function d0(B,Z,$){return!I4(B.quota,Z,$)}function T4(B,Z,$,z){return X0($)&&o0(B.quota,Z,z)&&A4(B.quota,z)}function f4(B){let Z=B?.quota?.checkIntervalMinutes??5;return Math.max(1,Z)*60000}var m4=60000,w4=60000,k4=600000,h4=1e4,v4=100;var kB=globalThis.setTimeout.bind(globalThis),hB=globalThis.clearTimeout.bind(globalThis);class p4{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??h(),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[T]?.checkedAt??0,B.quota[f]?.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:$+f4(Z),checkedAt:$},B.access)}async load(){return H4(this.configPath)}async save(B,Z){await O4(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(()=>{})},m4+R4(w4)),"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 X of Z.accounts){if(X.enabled===!1||!U(X))continue;if(y4(Z,X))continue;let W=!1,G=X;try{if(x(G,Z,this.now())){let K=G.lastRefreshError;if(K&&q(K,G.refresh,this.now()))throw W=!0,Error(a(K,this.now()));try{G=await this.refreshAccount(G,Z),z=!0}catch(Y){if(X4(Y))continue;W=!0;let J=Z.accounts.find((H)=>H.id===X.id&&U(H));if(J&&!q(J.lastRefreshError,J.refresh,this.now()))D0(J,Y,this.now()),L(Z,J),z=!0;throw Y}}if(this.seedFallbackQuota(G,Z),this.accountPassesQuotaPolicy(this.quotaPolicyAccount(G),Z))$.push(G)}catch(K){let Y=E4(G,this.now());if(W){if(!Y)continue}else if(!Y)continue;if(T4(G,Z,K,this.now()))y.debug("fallback quota using cached quota after refresh error",{pid:process.pid,accountId:G.id,error:V0(K)}),$.push(G);else if(!O0(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 o0(B.quota,Z,this.now())}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||!C4(B))return;let Z=!1;for(let $ of B.accounts){if($.enabled===!1||!U($))continue;if(!x($,B,this.now()))continue;if(q($.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:V0(z)}),D0($,z,this.now()),L(B,$),Z=!0}}if(Z)await this.save(B)}async refreshQuotaForDueAccounts(){let B=await this.load();if(!B||!F0(B))return;if(!this.options.fetchQuotaFn)return;let Z=!1;for(let $ of B.accounts){if($.enabled===!1||!U($))continue;let z=$;try{if(x(z,B,this.now())){if(q(z.lastRefreshError,z.refresh,this.now()))continue;z=await this.refreshAccount(z,B),Z=!0}if(I(z.lastQuotaRefreshError,this.now()))continue;if(this.seedFallbackQuota(z,B),!(this.quotaManager?this.quotaManager.isFallbackStale(z.id,z.access):d0(z,B,this.now())))continue;await this.refreshAccountQuota(z,B),Z=!0}catch(X){N0($,X,this.now()),L(B,$),Z=!0}}if(Z)await this.save(B),this.onFallbackStorageChanged?.()}async refreshQuotaForAllAccounts(B={}){let Z=await this.load(),$=[];if(!Z||!F0(Z))return{storage:Z,errors:$};if(!this.options.fetchQuotaFn)return{storage:Z,errors:$};let z=B.force??!1,X=!1;for(let W of Z.accounts){if(W.enabled===!1||!U(W))continue;let G=W;try{if(x(G,Z,this.now())){let K=G.lastRefreshError;if(K&&q(K,G.refresh,this.now()))throw Error(a(K,this.now()));G=await this.refreshAccount(G,Z),X=!0}if(!z&&!d0(G,Z,this.now())){if(G.lastQuotaRefreshError)G.lastQuotaRefreshError=void 0,L(Z,G),X=!0;continue}await this.refreshAccountQuota(G,Z),X=!0}catch(K){N0(W,K,this.now()),L(Z,W),X=!0,$.push({accountId:W.id,message:V0(K)})}}if(X)await this.save(Z);return{storage:Z,errors:$}}async refreshAccount(B,Z,$={}){let z=this.refreshPromises.get(B.id);if(z){let G=await z;return L(Z,G),G}let X=this.refreshAccountNow(B,Z,$).finally(()=>{this.refreshPromises.delete(B.id)});this.refreshPromises.set(B.id,X);let W=await X;return L(Z,W),W}async waitForConcurrentFallbackRefresh(B,Z,$,z){let X=Date.now()+h4;while(Date.now()<X){await new Promise((J)=>setTimeout(J,v4));let W=await this.load(),G=W?.accounts.find((J)=>J.id===B.id&&U(J));if(!G)continue;if((G.access!==$.access||G.refresh!==$.refresh||(G.expires??0)>($.expires??0)+60000)&&(z.force||!x(G,W,this.now())))return L(Z,G),y.debug("fallback oauth joined concurrent refresh",{pid:process.pid,accountId:G.id,expiresInMs:G.expires?G.expires-this.now():void 0}),G;let Y=G.lastRefreshError;if(Y&&q(Y,G.refresh,this.now()))throw L(Z,G),Error(a(Y,this.now()))}return null}async refreshAccountNow(B,Z,$){let z=await this.load(),X=z?.accounts.find((K)=>K.id===B.id&&U(K));if(X&&!$.force&&!x(X,z,this.now()))return L(Z,X),X;let W=X??B,G=await m({name:x4(W.id),ttlMs:k4,path:this.configPath,now:this.now,renew:!0});if(!G){y.debug("fallback oauth refresh skipped file lock",{pid:process.pid,accountId:W.id});let K=await this.waitForConcurrentFallbackRefresh(B,Z,W,$);if(K)return K;throw Error("Fallback OAuth refresh is already in progress")}try{if(z=await this.load(),X=z?.accounts.find((H)=>H.id===B.id&&U(H)),X&&!$.force&&!x(X,z,this.now()))return L(Z,X),X;if(!X)throw new Z0(B.id);W=X;let K=this.options.refreshFn??(async()=>{throw Error("No refreshFn injected into FallbackAccountManager")});y.debug("fallback oauth refresh request start",{pid:process.pid,accountId:W.id,force:$.force===!0,expiresInMs:W.expires?W.expires-this.now():void 0});let Y=await K({refreshToken:W.refresh,fetchImpl:this.fetchImpl,now:this.now});if(W.access=Y.access,W.refresh=Y.refresh,W.expires=Y.expires,W.lastRefreshedAt=Y.expires-Y.expiresIn*1000,W.lastRefreshError=void 0,L(Z,W),await this.save(Z),!(await this.load())?.accounts.some((H)=>H.id===B.id))throw new Z0(B.id);return y.debug("fallback oauth refresh succeeded",{pid:process.pid,accountId:W.id,expiresInMs:W.expires?W.expires-this.now():void 0}),W}finally{await G.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")}),X=(W)=>this.quotaManager?this.quotaManager.refreshFallback($.id,W):z({accessToken:W,fetchImpl:this.fetchImpl,now:this.now});try{if(!$.access)throw Error(`Fallback account ${B.id} has no access token`);let W=await X($.access);$.quota=W,$.lastQuotaRefreshError=void 0,L(Z,$),await this.save(Z)}catch(W){throw N0(B,W,this.now()),L(Z,B),W}}}
|
|
92
|
-
export{C0 as g,S0 as h,q as i,a as j,x0 as k,I0 as l,j3 as m,E0 as n,y0 as o,t as p,K0 as q,V3 as r,E as s,F3 as t,D3 as u,O3 as v,P3 as w,a4 as x,o4 as y,BB as z,ZB as A,m as B,Q0 as C,VB as D,P as E,h as F,U as G,xB as H,L0 as I,H4 as J,IB as K,TB as L,M4 as M,fB as N,mB as O,wB as P,p4 as Q};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{c as a,d as b,e as c,f as d}from"./index-d9hq0tmc.js";import"./index-e7m7qbne.js";export{a as toResetIso,c as normalizeWsFrame,d as normalizeWham,b as normalizeQuotaHeaders};
|
package/dist/token-01dcf92a.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a as U,b as V}from"./index-5s67238f.js";import{ia as R}from"./index-e7m7qbne.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();
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{b as a}from"./index-5s67238f.js";import"./index-e7m7qbne.js";export default a();
|