@cortexkit/opencode-openai-auth 0.8.0 → 0.9.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.
Files changed (40) hide show
  1. package/README.md +1 -1
  2. package/dist/{index-3w4vmckx.js → index-4effjmr6.js} +2 -2
  3. package/dist/{index-507jh8bv.js → index-9ehhb051.js} +1 -1
  4. package/dist/index-g3hsdjh4.js +2 -0
  5. package/dist/index-hh52v8sb.js +2 -0
  6. package/dist/{index-944gsj1s.js → index-jwn4r3sw.js} +1 -1
  7. package/dist/{index-02h7g5f9.js → index-sdt2d2ra.js} +1 -1
  8. package/dist/index-sq36b120.js +211 -0
  9. package/dist/index.d.ts +172 -341
  10. package/dist/index.js +65 -65
  11. package/dist/internal-BTndPmW2.d.ts +914 -0
  12. package/dist/quota-normalize-08hpp51v.js +1 -0
  13. package/dist/rpc/port-file.js +1 -1
  14. package/dist/rpc/protocol.d.ts +1 -1
  15. package/dist/rpc/rpc-client.d.ts +2 -1
  16. package/dist/rpc/rpc-client.js +1 -1
  17. package/dist/rpc/rpc-dir.js +1 -1
  18. package/dist/sidebar-state-CoKYKcLn.d.ts +220 -0
  19. package/dist/sidebar-state.d.ts +2 -172
  20. package/dist/sidebar-state.js +1 -1
  21. package/dist/{token-jdvpwk60.js → token-9823y0pc.js} +1 -1
  22. package/dist/token-util-ypgz7rge.js +1 -0
  23. package/dist/tui-preferences.js +1 -1
  24. package/dist/tui.d.ts +27 -5
  25. package/package.json +3 -2
  26. package/src/tui-compiled/raw/core-custody-state.ts +243 -0
  27. package/src/tui-compiled/raw/sidebar-state.ts +168 -12
  28. package/src/tui-compiled/raw/tui-command-dialogs.tsx +89 -39
  29. package/src/tui-compiled/raw/tui.tsx +138 -18
  30. package/src/tui-compiled/runtime/core-custody-state.ts +243 -0
  31. package/src/tui-compiled/runtime/sidebar-state.ts +168 -12
  32. package/src/tui-compiled/runtime/tui-command-dialogs.tsx +70 -33
  33. package/src/tui-compiled/runtime/tui.tsx +241 -143
  34. package/src/tui-compiled/shared/logger.ts +9 -2
  35. package/dist/index-2xppkvkx.js +0 -2
  36. package/dist/index-nshbgkz1.js +0 -198
  37. package/dist/index-xyg86jgt.js +0 -2
  38. package/dist/protocol-Cv9ZmU0p.d.ts +0 -24
  39. package/dist/quota-normalize-wap0rne8.js +0 -1
  40. package/dist/token-util-zzm7paz9.js +0 -1
@@ -6,10 +6,25 @@ export interface QuotaWindow {
6
6
  windowMinutes?: number
7
7
  }
8
8
 
9
+ export interface SpendControlReading {
10
+ limit: number
11
+ used: number
12
+ remaining: number
13
+ usedPercent: number
14
+ remainingPercent: number
15
+ resetsAt?: string
16
+ unit?: string
17
+ source?: string
18
+ reached: boolean
19
+ }
20
+
9
21
  export interface AccountQuota {
10
22
  checkedAt?: number
11
23
  primary?: QuotaWindow
12
24
  secondary?: QuotaWindow
25
+ spendControl?: SpendControlReading
26
+ // The source reported that no credit budget exists; see OAuthQuotaSnapshot.
27
+ spendControlCleared?: true
13
28
  resetCreditsAvailable?: number
14
29
  }
15
30
 
@@ -88,6 +103,17 @@ export interface SidebarAccountState {
88
103
  killed: boolean
89
104
  enabled: boolean
90
105
  resetCredits?: number
106
+ custody?: SidebarAccountCustody
107
+ }
108
+
109
+ export type SidebarCustodyState = 'vault' | 'needsLogin' | 'local' | 'inert'
110
+
111
+ export type SidebarCustodyReason = CustodyInertReason | 'corrupt'
112
+
113
+ export interface SidebarAccountCustody {
114
+ state: SidebarCustodyState
115
+ reason?: SidebarCustodyReason
116
+ recordVersion?: number
91
117
  }
92
118
 
93
119
  export interface ActiveRoutingEntry {
@@ -132,6 +158,7 @@ export interface SidebarState {
132
158
  quota: AccountQuota | null
133
159
  /** ChatGPT identity of the main account this quota belongs to. */
134
160
  mainAccountId?: string
161
+ custody?: SidebarAccountCustody
135
162
  killed: boolean
136
163
  quotaBackedOff?: boolean
137
164
  quotaBackoffUntil?: number
@@ -156,6 +183,11 @@ import { chmod, mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises'
156
183
  import { tmpdir } from 'node:os'
157
184
  import { dirname, join } from 'node:path'
158
185
  import { acquireRefreshFileLock } from '../shared/internal.ts'
186
+ import {
187
+ CUSTODY_INERT_REASONS,
188
+ type CustodyInertReason,
189
+ type CustodyVerdict,
190
+ } from './core-custody-state.ts'
159
191
  import { createLogger } from './logger.ts'
160
192
 
161
193
  const logSb = createLogger('sidebar')
@@ -183,6 +215,49 @@ function resetCreditsField(value: unknown): { resetCredits?: number } {
183
215
  return credits !== undefined ? { resetCredits: credits } : {}
184
216
  }
185
217
 
218
+ const CUSTODY_STATES = new Set<SidebarCustodyState>([
219
+ 'vault',
220
+ 'needsLogin',
221
+ 'local',
222
+ 'inert',
223
+ ])
224
+
225
+ const CUSTODY_REASONS = new Set<SidebarCustodyReason>([
226
+ ...CUSTODY_INERT_REASONS,
227
+ 'corrupt',
228
+ ])
229
+
230
+ /**
231
+ * Tolerant reader for the per-fallback `custody` projection. Unknown state
232
+ * or reason values are dropped (NOT replaced with a default — a stale state
233
+ * file with an experimental `vaultHealing` value must not silently render
234
+ * as `local`, it must render as no-projection-at-all). Valid values round-
235
+ * trip byte-identical. The output contains only `state` and `reason`.
236
+ */
237
+ function normalizeSidebarCustody(
238
+ value: unknown,
239
+ ): SidebarAccountCustody | undefined {
240
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) {
241
+ return undefined
242
+ }
243
+ const c = value as Record<string, unknown>
244
+ if (
245
+ typeof c.state !== 'string' ||
246
+ !CUSTODY_STATES.has(c.state as SidebarCustodyState)
247
+ ) {
248
+ return undefined
249
+ }
250
+ const state = c.state as SidebarCustodyState
251
+ const out: SidebarAccountCustody = { state }
252
+ if (
253
+ typeof c.reason === 'string' &&
254
+ CUSTODY_REASONS.has(c.reason as SidebarCustodyReason)
255
+ ) {
256
+ out.reason = c.reason as SidebarCustodyReason
257
+ }
258
+ return out
259
+ }
260
+
186
261
  function normalizeActiveRouting(value: unknown): ActiveRoutingMap | undefined {
187
262
  if (value === null || typeof value !== 'object' || Array.isArray(value)) {
188
263
  return undefined
@@ -276,6 +351,23 @@ export function getSidebarStateFile(): string {
276
351
  return process.env[STATE_FILE_ENV] || DEFAULT_STATE_FILE
277
352
  }
278
353
 
354
+ export function projectCustodyForSidebar(
355
+ verdict: CustodyVerdict,
356
+ ): SidebarAccountCustody {
357
+ switch (verdict.kind) {
358
+ case 'LOCAL':
359
+ return { state: 'local' }
360
+ case 'VAULT':
361
+ return { state: 'vault' }
362
+ case 'INERT':
363
+ return { state: 'inert', reason: verdict.reason }
364
+ case 'NEEDS_LOGIN':
365
+ return verdict.reason === 'corrupt'
366
+ ? { state: 'needsLogin', reason: 'corrupt' }
367
+ : { state: 'needsLogin' }
368
+ }
369
+ }
370
+
279
371
  export const DEFAULT_SIDEBAR_STATE: SidebarState = {
280
372
  main: { quota: null, killed: false },
281
373
  fallbacks: [],
@@ -315,6 +407,10 @@ export function normalizeSidebarState(raw: unknown): SidebarState {
315
407
  ...(typeof m.mainAccountId === 'string'
316
408
  ? { mainAccountId: m.mainAccountId }
317
409
  : {}),
410
+ ...(() => {
411
+ const custody = normalizeSidebarCustody(m.custody)
412
+ return custody ? { custody } : {}
413
+ })(),
318
414
  // Preserve optional backoff fields if present
319
415
  ...(typeof m.quotaBackedOff === 'boolean'
320
416
  ? { quotaBackedOff: m.quotaBackedOff }
@@ -347,17 +443,21 @@ export function normalizeSidebarState(raw: unknown): SidebarState {
347
443
  !Array.isArray(entry) &&
348
444
  typeof (entry as Record<string, unknown>).id === 'string',
349
445
  )
350
- .map((e) => ({
351
- id: e.id as string,
352
- label: typeof e.label === 'string' ? e.label : undefined,
353
- ...(typeof e.accountId === 'string'
354
- ? { accountId: e.accountId }
355
- : {}),
356
- quota: ('quota' in e ? e.quota : null) as AccountQuota | null,
357
- killed: typeof e.killed === 'boolean' ? e.killed : false,
358
- enabled: typeof e.enabled === 'boolean' ? e.enabled : true,
359
- ...resetCreditsField(e.resetCredits),
360
- }))
446
+ .map((e) => {
447
+ const custody = normalizeSidebarCustody(e.custody)
448
+ return {
449
+ id: e.id as string,
450
+ label: typeof e.label === 'string' ? e.label : undefined,
451
+ ...(typeof e.accountId === 'string'
452
+ ? { accountId: e.accountId }
453
+ : {}),
454
+ quota: ('quota' in e ? e.quota : null) as AccountQuota | null,
455
+ killed: typeof e.killed === 'boolean' ? e.killed : false,
456
+ enabled: typeof e.enabled === 'boolean' ? e.enabled : true,
457
+ ...resetCreditsField(e.resetCredits),
458
+ ...(custody ? { custody } : {}),
459
+ }
460
+ })
361
461
  : []
362
462
 
363
463
  // activeId — string or undefined
@@ -428,6 +528,27 @@ export function isUsableRoutingEntry(
428
528
  )
429
529
  }
430
530
 
531
+ // The credit budget's own exhaustion signal, shared by admission and sticky
532
+ // migration so both agree on what "spent" means. `reached` is the provider's
533
+ // authoritative boolean — the percentage is only a display approximation — and
534
+ // the check fails open on a missing or lapsed reset exactly like a rate-limit
535
+ // window, so a stale or corrupt reading never blocks.
536
+ export function spendControlExhaustedResetAt(
537
+ quota: AccountQuota | null | undefined,
538
+ now = Date.now(),
539
+ ): { resetsAt: string; resetAtMs: number } | undefined {
540
+ const spendControl = quota?.spendControl
541
+ if (
542
+ spendControl?.reached !== true ||
543
+ typeof spendControl.resetsAt !== 'string'
544
+ ) {
545
+ return undefined
546
+ }
547
+ const resetAtMs = Date.parse(spendControl.resetsAt)
548
+ if (!Number.isFinite(resetAtMs) || resetAtMs <= now) return undefined
549
+ return { resetsAt: spendControl.resetsAt, resetAtMs }
550
+ }
551
+
431
552
  // Earliest future reset among the quota's exhausted windows, or undefined when
432
553
  // no present window is exhausted. Every present window is evaluated — matching
433
554
  // the admission policy, which rejects an account when ANY live window is below
@@ -454,6 +575,12 @@ export function exhaustedQuotaResetAt(
454
575
  earliest = { resetsAt: window.resetsAt, resetAtMs }
455
576
  }
456
577
  }
578
+ // The credit budget is a third axis on its own reset clock (a month, not
579
+ // 5h/7d), judged by the same shared signal sticky migration uses.
580
+ const spendReset = spendControlExhaustedResetAt(quota, now)
581
+ if (spendReset && (!earliest || spendReset.resetAtMs < earliest.resetAtMs)) {
582
+ earliest = spendReset
583
+ }
457
584
  return earliest
458
585
  }
459
586
 
@@ -979,6 +1106,19 @@ function freshestWindow(
979
1106
  // of the merged result. Only safe when both snapshots share an account identity
980
1107
  // (sameAccountIdentity) — an identity switch must whole-pick (freshestQuota) so
981
1108
  // windows from two accounts are never combined.
1109
+ // The fresher side decides the budget when it knows anything about it: its own
1110
+ // reading, or its report that no budget exists. Only when it says nothing (a
1111
+ // header or WebSocket push, which never carries spend control) does the other
1112
+ // side's reading survive, and even then not if that side reported none.
1113
+ function mergeSpendControl(
1114
+ fresher: AccountQuota,
1115
+ older: AccountQuota,
1116
+ ): SpendControlReading | undefined {
1117
+ if (fresher.spendControl !== undefined) return fresher.spendControl
1118
+ if (fresher.spendControlCleared === true) return undefined
1119
+ return older.spendControl
1120
+ }
1121
+
982
1122
  function mergeQuotaByWindow(
983
1123
  incoming: AccountQuota | null,
984
1124
  existing: AccountQuota | null,
@@ -1004,6 +1144,13 @@ function mergeQuotaByWindow(
1004
1144
  incoming.checkedAt,
1005
1145
  existing.checkedAt,
1006
1146
  )
1147
+ const spendControl = existingSnapshotIsFresher
1148
+ ? mergeSpendControl(existing, incoming)
1149
+ : mergeSpendControl(incoming, existing)
1150
+ const spendControlCleared =
1151
+ spendControl === undefined &&
1152
+ (incoming.spendControlCleared === true ||
1153
+ existing.spendControlCleared === true)
1007
1154
  let checkedAt: number | undefined
1008
1155
  for (const stamp of [
1009
1156
  finiteWindowCheckedAt(primary),
@@ -1013,10 +1160,19 @@ function mergeQuotaByWindow(
1013
1160
  checkedAt = checkedAt === undefined ? stamp : Math.max(checkedAt, stamp)
1014
1161
  }
1015
1162
  }
1163
+ // Both budget fields are decided above, so neither may leak in from the
1164
+ // spread: an older incoming budget must not survive a fresher "no budget".
1165
+ const {
1166
+ spendControl: _incomingSpendControl,
1167
+ spendControlCleared: _incomingCleared,
1168
+ ...incomingRest
1169
+ } = incoming
1016
1170
  return {
1017
- ...incoming,
1171
+ ...incomingRest,
1018
1172
  primary,
1019
1173
  secondary,
1174
+ ...(spendControl !== undefined ? { spendControl } : {}),
1175
+ ...(spendControlCleared ? { spendControlCleared: true as const } : {}),
1020
1176
  checkedAt: checkedAt ?? incoming.checkedAt,
1021
1177
  }
1022
1178
  }
@@ -466,7 +466,7 @@ export function openCommandDialog(api, payload, apply, sessionId) {
466
466
  return;
467
467
  }
468
468
  if (payload.command === 'openai-account') {
469
- openAccountDialog(api, apply, sessionId);
469
+ openAccountDialog(api, apply, sessionId, payload);
470
470
  return;
471
471
  }
472
472
 
@@ -507,8 +507,49 @@ export function buildAccountDialogRows(state, sessionId) {
507
507
  description: formatQuotaWindows(fb.quota)
508
508
  }))];
509
509
  }
510
- function openAccountDialog(api, apply, sessionId) {
510
+ export function accountDialogModeOption(mode) {
511
+ const claustrum = mode === 'claustrum';
512
+ return {
513
+ title: claustrum ? 'Leave Claustrum' : 'Enter Claustrum',
514
+ value: claustrum ? '__local__' : '__claustrum__',
515
+ description: claustrum ? 'Require fresh local logins before local refresh resumes' : 'Verify every enabled account before custody takes over'
516
+ };
517
+ }
518
+ export function buildFallbackAccountOptions(input) {
519
+ const name = input.label ?? input.id;
520
+ const options = [{
521
+ title: input.enabled ? 'Disable' : 'Enable',
522
+ value: input.enabled ? 'disable' : 'enable',
523
+ description: `${input.enabled ? 'Disable' : 'Enable'} ${name}`
524
+ }, {
525
+ title: 'Remove',
526
+ value: 'remove',
527
+ description: `Remove ${name}`
528
+ }];
529
+ if (input.index > 0) {
530
+ options.push({
531
+ title: 'Move up',
532
+ value: 'move_up',
533
+ description: 'Swap with the preceding fallback'
534
+ });
535
+ }
536
+ if (input.index < input.count - 1) {
537
+ options.push({
538
+ title: 'Move down',
539
+ value: 'move_down',
540
+ description: 'Swap with the following fallback'
541
+ });
542
+ }
543
+ options.push({
544
+ title: 'Back',
545
+ value: 'back',
546
+ description: 'Return to account list'
547
+ });
548
+ return options;
549
+ }
550
+ function openAccountDialog(api, apply, sessionId, payload) {
511
551
  const DialogConfirm = api.ui.DialogConfirm;
552
+ let claustrumMode = payload?.knobs.claustrumMode;
512
553
  function showL1() {
513
554
  void getSidebarState().then(state => {
514
555
  const DialogSelectInner = api.ui.DialogSelect;
@@ -516,13 +557,24 @@ function openAccountDialog(api, apply, sessionId) {
516
557
  api.ui.dialog.replace(() => _$createComponent(DialogSelectInner, {
517
558
  title: "OpenAI Accounts",
518
559
  get options() {
519
- return [...buildAccountDialogRows(state, sessionId), {
560
+ return [accountDialogModeOption(claustrumMode), ...buildAccountDialogRows(state, sessionId), {
520
561
  title: 'Add account\u2026',
521
562
  value: '__add__',
522
563
  description: 'Sign in to a new OpenAI account'
523
564
  }];
524
565
  },
525
566
  onSelect: option => {
567
+ if (option.value === '__claustrum__' || option.value === '__local__') {
568
+ const args = option.value === '__claustrum__' ? 'claustrum' : 'local';
569
+ void apply('openai-account', args).then(r => {
570
+ api.ui.toast({
571
+ message: r.text
572
+ });
573
+ claustrumMode = r.knobs.claustrumMode;
574
+ showL1();
575
+ });
576
+ return;
577
+ }
526
578
  if (option.value === '__add__') {
527
579
  showAddFlow();
528
580
  return;
@@ -544,36 +596,12 @@ function openAccountDialog(api, apply, sessionId) {
544
596
  showL1();
545
597
  return;
546
598
  }
547
- const options = [];
548
- options.push({
549
- title: 'Remove',
550
- value: 'remove',
551
- description: `Remove ${fb.label ?? fb.id}`
552
- });
553
- if (fbIndex > 0) {
554
- const neighbor = state.fallbacks[fbIndex - 1];
555
- if (neighbor) {
556
- options.push({
557
- title: 'Move up',
558
- value: 'move_up',
559
- description: `Swap with ${neighbor.label ?? neighbor.id}`
560
- });
561
- }
562
- }
563
- if (fbIndex < state.fallbacks.length - 1) {
564
- const neighbor = state.fallbacks[fbIndex + 1];
565
- if (neighbor) {
566
- options.push({
567
- title: 'Move down',
568
- value: 'move_down',
569
- description: `Swap with ${neighbor.label ?? neighbor.id}`
570
- });
571
- }
572
- }
573
- options.push({
574
- title: 'Back',
575
- value: 'back',
576
- description: 'Return to account list'
599
+ const options = buildFallbackAccountOptions({
600
+ id: fb.id,
601
+ label: fb.label,
602
+ enabled: fb.enabled,
603
+ index: fbIndex,
604
+ count: state.fallbacks.length
577
605
  });
578
606
  api.ui.dialog.setSize('xlarge');
579
607
  api.ui.dialog.replace(() => _$createComponent(DialogSelectInner, {
@@ -601,6 +629,15 @@ function openAccountDialog(api, apply, sessionId) {
601
629
  }));
602
630
  return;
603
631
  }
632
+ if (option.value === 'enable' || option.value === 'disable') {
633
+ void apply('openai-account', `${option.value} ${id}`).then(r => {
634
+ api.ui.toast({
635
+ message: r.text
636
+ });
637
+ showL1();
638
+ });
639
+ return;
640
+ }
604
641
  if (option.value === 'move_up') {
605
642
  const neighbor = state.fallbacks[fbIndex - 1];
606
643
  if (neighbor) {