@cortexkit/common-auth 0.30.0 → 0.32.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.
@@ -0,0 +1,530 @@
1
+ // The one quota wording every surface shows: the command menu's dialogs on
2
+ // OpenCode and Pi, the terminal auth menu, and the plugins' sidebars. Each of
3
+ // them calls `formatQuota`, `quotaTextParts`, or `quotaWindowParts`, so the
4
+ // wording cannot drift between plugins or between a dialog and a sidebar.
5
+ //
6
+ // The rules: a window is named by its length (`5h`, `7d`), or, for a window
7
+ // that binds only one model family, by the label the plugin stored it under.
8
+ // Every figure is "% left". A window the provider did not report (an absence
9
+ // record or a retirement tombstone) is left out rather than written as "not
10
+ // reported". A reset is a short time from now (`resets 2h`). A reading older
11
+ // than fifteen minutes says how old it is (`checked 3h ago`).
12
+ //
13
+ // Like the rest of this module it reads no clock: `now` is a parameter.
14
+
15
+ import { ALL_SCOPE, type QuotaCredits } from './map.js'
16
+ import type {
17
+ ProjectedLimit,
18
+ ProjectedQuota,
19
+ QuotaGroup,
20
+ } from './projection.js'
21
+
22
+ /** A reading older than this is marked with its age. */
23
+ export const QUOTA_STALE_AFTER_MS = 15 * 60_000
24
+
25
+ /** What `formatQuota` returns when there is no reading at all. */
26
+ export const NO_QUOTA_READING = 'no quota reading yet'
27
+
28
+ /**
29
+ * What `formatQuota` returns when the provider answered but reported no
30
+ * limit for any window (every window is an absence record or a tombstone).
31
+ */
32
+ export const NO_LIMITS_REPORTED = 'no limits reported'
33
+
34
+ /**
35
+ * `compact` fits a footer or a sidebar row: each window's figure, the credit
36
+ * budget and the stale marker, without reset times. `full` adds each reset.
37
+ * `narrow` fits one line per account in a narrow sidebar: `5h 92% · 7d 66%
38
+ * · Fa 98% left`, the account-wide windows plus at most one model-scoped
39
+ * window or the budget (as `cr`), and no stale marker (see `isQuotaStale`).
40
+ * A reading whose windows belong to named groups and that has no
41
+ * account-wide window reads up to two groups instead:
42
+ * `Ge 7d 62% · Ot 7d 48% left`.
43
+ */
44
+ export type QuotaTextForm = 'compact' | 'full' | 'narrow'
45
+
46
+ export interface QuotaTextOptions {
47
+ /** The current time in ms, for reset countdowns and the stale marker. */
48
+ now: number
49
+ /** Defaults to `full`. */
50
+ form?: QuotaTextForm
51
+ /** Defaults to `QUOTA_STALE_AFTER_MS`. */
52
+ staleAfterMs?: number
53
+ }
54
+
55
+ export interface QuotaWindowPart {
56
+ kind: 'window' | 'budget'
57
+ /** The display name of a quota window, or `credits` for the budget. */
58
+ name: string
59
+ /**
60
+ * The label the narrow line gives this item: an account-wide window keeps
61
+ * its name (`5h`), a model-scoped window reads as its model's short name
62
+ * (`Fa` for Fable, extended until names in the same reading differ), and
63
+ * the budget reads `cr`. For layouts too narrow for the full name.
64
+ */
65
+ short: string
66
+ /** The shared figure wording, including `credits` for budget figures. */
67
+ figure: string
68
+ /** The unrounded remaining percentage, clamped to 0–100, when known. */
69
+ remainingPercent?: number
70
+ /** A bare relative reset span such as `4d`, only when the reset is future. */
71
+ resetIn?: string
72
+ checkedAt: number
73
+ /** Whether the reset followed this reading and has arrived by `now`. */
74
+ resetSinceReading: boolean
75
+ }
76
+
77
+ export interface QuotaParts {
78
+ /** Reported windows in display order, followed by the budget when present. */
79
+ windows: QuotaWindowPart[]
80
+ /** The shared checked-age wording, present only when the reading is stale. */
81
+ age?: string
82
+ }
83
+
84
+ /**
85
+ * A time span in at most its two largest units: `45m`, `2h29m`, `5h`, `3d23h`,
86
+ * `7d`. Every unit is rounded down, so a reset is never shown later than it is;
87
+ * the one exception is a span under a minute, which reads `1m` rather than
88
+ * zero. A zero second unit is left out.
89
+ */
90
+ function shortSpan(ms: number): string {
91
+ const minutes = Math.max(1, Math.floor(ms / 60_000))
92
+ if (minutes < 60) return `${minutes}m`
93
+ if (minutes < 1440) {
94
+ const hours = Math.floor(minutes / 60)
95
+ const rest = minutes % 60
96
+ return rest === 0 ? `${hours}h` : `${hours}h${rest}m`
97
+ }
98
+ const days = Math.floor(minutes / 1440)
99
+ const hours = Math.floor((minutes % 1440) / 60)
100
+ return hours === 0 ? `${days}d` : `${days}d${hours}h`
101
+ }
102
+
103
+ /** A stored window length in minutes as its exact name: `5h`, `7d`, `90m`. */
104
+ function lengthName(minutes: number): string {
105
+ if (minutes % 1440 === 0) return `${minutes / 1440}d`
106
+ if (minutes % 60 === 0) return `${minutes / 60}h`
107
+ return `${minutes}m`
108
+ }
109
+
110
+ /**
111
+ * The name a window is shown under. A general window (scope `all`) is named
112
+ * by its stored length; a model-scoped window keeps the label the plugin
113
+ * stored it under, which already names the model (`seven_day_opus`). A
114
+ * general window stored without a length (a snapshot from before lengths
115
+ * were recorded) falls back to its label.
116
+ */
117
+ export function quotaWindowName(
118
+ limit: Pick<ProjectedLimit, 'scope' | 'label' | 'windowMinutes'>,
119
+ ): string {
120
+ if (limit.scope !== ALL_SCOPE || limit.windowMinutes === undefined)
121
+ return limit.label
122
+ return lengthName(limit.windowMinutes)
123
+ }
124
+
125
+ function clampPercent(remaining: number): number {
126
+ return Math.min(100, Math.max(0, remaining))
127
+ }
128
+
129
+ /** A remaining percentage as the whole number every form shows. */
130
+ function wholePercent(remaining: number): number {
131
+ return Math.round(clampPercent(remaining))
132
+ }
133
+
134
+ function percentLeft(remaining: number): string {
135
+ return `${wholePercent(remaining)}% left`
136
+ }
137
+
138
+ function resetDetails(
139
+ resetsAt: string | undefined,
140
+ checkedAt: number,
141
+ now: number,
142
+ ): { resetIn?: string; resetSinceReading: boolean } {
143
+ const at = resetsAt === undefined ? Number.NaN : Date.parse(resetsAt)
144
+ return {
145
+ ...(Number.isFinite(at) && at > now
146
+ ? { resetIn: shortSpan(at - now) }
147
+ : {}),
148
+ resetSinceReading: Number.isFinite(at) && at > checkedAt && at <= now,
149
+ }
150
+ }
151
+
152
+ /** Shortest window first, so `5h` reads before `7d`; unknown lengths last. */
153
+ function displayOrder(left: ProjectedLimit, right: ProjectedLimit): number {
154
+ const l = left.windowMinutes
155
+ const r = right.windowMinutes
156
+ if (l !== undefined && r !== undefined && l !== r) return l - r
157
+ if ((l === undefined) !== (r === undefined)) return l === undefined ? 1 : -1
158
+ if (left.scope !== right.scope) {
159
+ if (left.scope === ALL_SCOPE) return -1
160
+ if (right.scope === ALL_SCOPE) return 1
161
+ return left.scope < right.scope ? -1 : 1
162
+ }
163
+ return left.label < right.label ? -1 : left.label > right.label ? 1 : 0
164
+ }
165
+
166
+ /**
167
+ * Structured quota wording for layouts that need one row per window. The
168
+ * windows use the same filtering and order as `quotaTextParts`; future resets
169
+ * and the optional age keep the shared formatter's wording.
170
+ */
171
+ export function quotaWindowParts(
172
+ quota: ProjectedQuota | undefined,
173
+ options: QuotaTextOptions,
174
+ ): QuotaParts {
175
+ const { windows, age } = scopedWindowParts(quota, options)
176
+ const parts = windows.map(({ part }) => part)
177
+ return age === undefined ? { windows: parts } : { windows: parts, age }
178
+ }
179
+
180
+ /**
181
+ * The narrow label of each scoped window part, as `narrowTextParts` names
182
+ * them: model short names are worked out over every model-scoped window in
183
+ * the reading, so two models never share a short name.
184
+ */
185
+ function withShortNames(windows: ScopedWindowPart[]): ScopedWindowPart[] {
186
+ const abbreviations = scopeAbbreviations(
187
+ windows
188
+ .filter(
189
+ ({ part, scope }) => part.kind === 'window' && scope !== ALL_SCOPE,
190
+ )
191
+ .map(({ scope }) => scope),
192
+ )
193
+ for (const window of windows) {
194
+ window.part.short =
195
+ window.part.kind === 'budget'
196
+ ? 'cr'
197
+ : window.scope === ALL_SCOPE
198
+ ? window.part.name
199
+ : (abbreviations.get(window.scope) ?? window.scope)
200
+ }
201
+ return windows
202
+ }
203
+
204
+ /** A window part with the scope its limit was stored under (`all` for the budget). */
205
+ interface ScopedWindowPart {
206
+ part: QuotaWindowPart
207
+ scope: string
208
+ /** On a window only: its stored length, when the provider reported one. */
209
+ windowMinutes?: number
210
+ /** On the budget only: the provider reported it spent. */
211
+ spent?: boolean
212
+ }
213
+
214
+ /**
215
+ * `quotaWindowParts` with each window's scope kept beside it. The narrow form
216
+ * needs the scope to name and pick model-scoped windows; the public parts do
217
+ * not carry it, so their shape stays as it was.
218
+ */
219
+ function scopedWindowParts(
220
+ quota: ProjectedQuota | undefined,
221
+ options: QuotaTextOptions,
222
+ ): { windows: ScopedWindowPart[]; age?: string } {
223
+ if (!quota) return { windows: [] }
224
+ const { now } = options
225
+ const readings = quota.limits
226
+ .filter(
227
+ (limit) =>
228
+ limit.kind === 'reading' && limit.remainingPercent !== undefined,
229
+ )
230
+ .sort(displayOrder)
231
+ const windows: ScopedWindowPart[] = readings.map((limit) => {
232
+ const remainingPercent = clampPercent(limit.remainingPercent ?? 0)
233
+ return {
234
+ scope: limit.scope,
235
+ ...(limit.windowMinutes === undefined
236
+ ? {}
237
+ : { windowMinutes: limit.windowMinutes }),
238
+ part: {
239
+ kind: 'window',
240
+ name: quotaWindowName(limit),
241
+ short: '',
242
+ figure: percentLeft(limit.remainingPercent ?? 0),
243
+ remainingPercent,
244
+ checkedAt: limit.checkedAt,
245
+ ...resetDetails(limit.resetsAt, limit.checkedAt, now),
246
+ },
247
+ }
248
+ })
249
+ const budget = quota.budget
250
+ if (budget) {
251
+ const remainingPercent = budget.remainingPercent
252
+ const figure = budget.reached
253
+ ? 'credits spent'
254
+ : remainingPercent !== undefined
255
+ ? `credits ${percentLeft(remainingPercent)}`
256
+ : 'credits available'
257
+ windows.push({
258
+ scope: ALL_SCOPE,
259
+ spent: budget.reached,
260
+ part: {
261
+ kind: 'budget',
262
+ name: 'credits',
263
+ short: '',
264
+ figure,
265
+ ...(remainingPercent === undefined
266
+ ? {}
267
+ : { remainingPercent: clampPercent(remainingPercent) }),
268
+ checkedAt: budget.checkedAt,
269
+ ...resetDetails(budget.resetsAt, budget.checkedAt, now),
270
+ },
271
+ })
272
+ }
273
+
274
+ withShortNames(windows)
275
+ if (windows.length > 0) {
276
+ const age = now - Math.min(...windows.map(({ part }) => part.checkedAt))
277
+ if (age > (options.staleAfterMs ?? QUOTA_STALE_AFTER_MS)) {
278
+ return { windows, age: `checked ${shortSpan(age)} ago` }
279
+ }
280
+ }
281
+ return { windows }
282
+ }
283
+
284
+ /**
285
+ * Whether the reading is stale: true exactly when the compact and full forms
286
+ * would end with `checked … ago`. The narrow form leaves that age out to stay
287
+ * short, so a caller drawing a narrow line uses this to dim it instead.
288
+ */
289
+ export function isQuotaStale(
290
+ quota: ProjectedQuota | undefined,
291
+ options: QuotaTextOptions,
292
+ ): boolean {
293
+ return scopedWindowParts(quota, options).age !== undefined
294
+ }
295
+
296
+ /**
297
+ * The model a scope names, as a display name: any namespace before a colon
298
+ * is dropped (`model:claude-opus-4` → `claude-opus-4`) and the first letter is
299
+ * capitalized (`fable` → `Fable`); the rest stays as written.
300
+ */
301
+ function scopeDisplayName(scope: string): string {
302
+ const model = scope.slice(scope.indexOf(':') + 1)
303
+ return model.charAt(0).toUpperCase() + model.slice(1)
304
+ }
305
+
306
+ /**
307
+ * Short names for the model scopes in one row: the first two letters of each
308
+ * display name. Names that would read the same for different models are each
309
+ * extended one letter at a time until they differ (`Fable` and `Fabric` read
310
+ * `Fabl` and `Fabr`); a name that runs out of letters stays whole.
311
+ */
312
+ function scopeAbbreviations(scopes: readonly string[]): Map<string, string> {
313
+ const names = [...new Set(scopes.map(scopeDisplayName))]
314
+ const lengths = new Map(names.map((name) => [name, 2]))
315
+ const short = (name: string) => name.slice(0, lengths.get(name))
316
+ for (;;) {
317
+ const byShort = new Map<string, string[]>()
318
+ for (const name of names) {
319
+ byShort.set(short(name), [...(byShort.get(short(name)) ?? []), name])
320
+ }
321
+ let extended = false
322
+ for (const group of byShort.values()) {
323
+ if (group.length < 2) continue
324
+ for (const name of group) {
325
+ const length = lengths.get(name) ?? 2
326
+ if (length < name.length) {
327
+ lengths.set(name, length + 1)
328
+ extended = true
329
+ }
330
+ }
331
+ }
332
+ if (!extended) break
333
+ }
334
+ return new Map(scopes.map((scope) => [scope, short(scopeDisplayName(scope))]))
335
+ }
336
+
337
+ /** The most groups a grouped narrow line shows. */
338
+ const NARROW_GROUP_LIMIT = 2
339
+
340
+ /**
341
+ * The names the groups read under in the narrow line, one per listed group:
342
+ * each label's short name, derived exactly as a model window's is (`Gemini`
343
+ * → `Ge`, `Other models` → `Ot`, colliding names extended until they
344
+ * differ), computed over every listed group so a group keeps its name
345
+ * whichever groups show. A blank label falls back to the group's scope.
346
+ */
347
+ function groupShortNames(groups: readonly QuotaGroup[]): string[] {
348
+ const labels = groups.map((group) => group.label.trim() || group.scope)
349
+ const short = scopeAbbreviations(labels)
350
+ return labels.map((label) => short.get(label) ?? label)
351
+ }
352
+
353
+ /**
354
+ * The narrow line of a reading whose windows belong to named groups and that
355
+ * has no account-wide window: for each group, its tightest window as
356
+ * `Ge 7d 62%`, with ` left` once at the end. The tightest window is the
357
+ * one with least left, compared before rounding; on a tie the first in
358
+ * display order (the shorter window) wins. At most two groups show: the two
359
+ * with least left, earlier-listed first on a tie, and always in the order
360
+ * the reading lists them, so the line does not reorder as the figures move.
361
+ * A group with no reported window is skipped. Windows outside the listed
362
+ * groups and the credit budget are left out. Undefined when the rule does
363
+ * not apply, so the caller uses the ordinary narrow rule.
364
+ */
365
+ function groupedNarrowPieces(
366
+ groups: readonly QuotaGroup[] | undefined,
367
+ windows: readonly ScopedWindowPart[],
368
+ ): string[] | undefined {
369
+ if (!groups || groups.length === 0) return undefined
370
+ const reported = windows.filter(({ part }) => part.kind === 'window')
371
+ if (reported.some(({ scope }) => scope === ALL_SCOPE)) return undefined
372
+ const candidates = groups.flatMap((group, listed) => {
373
+ const inGroup = reported.filter(({ scope }) => scope === group.scope)
374
+ // `windows` is already in display order, and strictly lower wins, so on
375
+ // a tie the shorter window keeps the place.
376
+ const groupTightest = inGroup.reduce<ScopedWindowPart | undefined>(
377
+ (least, window) =>
378
+ least === undefined ||
379
+ (window.part.remainingPercent ?? 0) < (least.part.remainingPercent ?? 0)
380
+ ? window
381
+ : least,
382
+ undefined,
383
+ )
384
+ return groupTightest ? [{ group, listed, window: groupTightest }] : []
385
+ })
386
+ if (candidates.length === 0) return undefined
387
+ const names = groupShortNames(groups)
388
+ const left = (candidate: (typeof candidates)[number]) =>
389
+ candidate.window.part.remainingPercent ?? 0
390
+ const shown = [...candidates]
391
+ .sort((a, b) => left(a) - left(b) || a.listed - b.listed)
392
+ .slice(0, NARROW_GROUP_LIMIT)
393
+ .sort((a, b) => a.listed - b.listed)
394
+ return shown.map((candidate, index) => {
395
+ const { windowMinutes } = candidate.window
396
+ const piece = [
397
+ names[candidate.listed] ?? candidate.group.scope,
398
+ ...(windowMinutes === undefined ? [] : [lengthName(windowMinutes)]),
399
+ `${wholePercent(left(candidate))}%`,
400
+ ].join(' ')
401
+ return index === shown.length - 1 ? `${piece} left` : piece
402
+ })
403
+ }
404
+
405
+ /**
406
+ * The narrow form's pieces: every account-wide window as `5h 92%`, then at
407
+ * most one more item, with ` left` added once to the last piece. That item is
408
+ * the tightest (least remaining) of the model-scoped windows and the credit
409
+ * budget, so the line stays bounded whatever the account carries: a scoped
410
+ * window reads under its short model name (`Fa 98%`), the budget as `cr 75%`
411
+ * (`cr 0%` when spent). On a tie a scoped window wins over the budget, and
412
+ * among scoped windows the first in display order wins. The choice depends
413
+ * only on the reading, never on a width. A budget without a percentage cannot
414
+ * be chosen; when nothing at all is shown it keeps its compact wording
415
+ * (`credits available`). No age is added; `isQuotaStale` says whether the
416
+ * reading is stale. A window whose reset arrived after the reading keeps its
417
+ * figure, as in the other forms. A reading that lists named groups and has no
418
+ * account-wide window reads one item per group instead (see
419
+ * `groupedNarrowPieces`).
420
+ */
421
+ function narrowTextParts(
422
+ quota: ProjectedQuota | undefined,
423
+ options: QuotaTextOptions,
424
+ ): string[] {
425
+ const { windows } = scopedWindowParts(quota, options)
426
+ const grouped = groupedNarrowPieces(quota?.groups, windows)
427
+ if (grouped) return grouped
428
+ const general = windows.filter(
429
+ ({ part, scope }) => part.kind === 'window' && scope === ALL_SCOPE,
430
+ )
431
+ const scoped = windows.filter(
432
+ ({ part, scope }) => part.kind === 'window' && scope !== ALL_SCOPE,
433
+ )
434
+ // The items competing for the one slot after the account-wide windows, in
435
+ // tie-break order: scoped windows in display order, then the budget. A
436
+ // spent budget counts as 0% left; one without a percentage cannot compete.
437
+ // Their labels are the parts' short names, so the narrow line and a layout
438
+ // reading `short` always agree.
439
+ const budget = windows.find(({ part }) => part.kind === 'budget')
440
+ const budgetLeft = budget?.spent ? 0 : budget?.part.remainingPercent
441
+ const extras = [
442
+ ...scoped.map(({ part }) => ({
443
+ label: part.short,
444
+ remaining: part.remainingPercent ?? 0,
445
+ })),
446
+ ...(budgetLeft === undefined || budget === undefined
447
+ ? []
448
+ : [{ label: budget.part.short, remaining: budgetLeft }]),
449
+ ]
450
+ // Strictly lower wins, so on a tie the earlier item keeps the slot.
451
+ const tightest = extras.reduce<(typeof extras)[number] | undefined>(
452
+ (best, item) =>
453
+ best === undefined || item.remaining < best.remaining ? item : best,
454
+ undefined,
455
+ )
456
+ const pieces = general.map(
457
+ ({ part }) => `${part.name} ${wholePercent(part.remainingPercent ?? 0)}%`,
458
+ )
459
+ if (tightest) {
460
+ pieces.push(`${tightest.label} ${wholePercent(tightest.remaining)}%`)
461
+ }
462
+ if (pieces.length === 0) return windows.map(({ part }) => part.figure)
463
+ return pieces.map((piece, index) =>
464
+ index === pieces.length - 1 ? `${piece} left` : piece,
465
+ )
466
+ }
467
+
468
+ /**
469
+ * The pieces of a quota text, in order: one per reported window
470
+ * (`5h 58% left, resets 2h`), then the credit budget when there is one, then
471
+ * `checked 3h ago` when the oldest piece shown is stale. Empty when nothing
472
+ * was reported; `formatQuota` turns that into a sentence. A caller printing
473
+ * one line per window (the terminal auth menu) uses these directly. In the
474
+ * narrow form the pieces are the narrow line's (`5h 92%`, `7d 66% left`).
475
+ */
476
+ export function quotaTextParts(
477
+ quota: ProjectedQuota | undefined,
478
+ options: QuotaTextOptions,
479
+ ): string[] {
480
+ if (options.form === 'narrow') return narrowTextParts(quota, options)
481
+ const parts = quotaWindowParts(quota, options)
482
+ const full = (options.form ?? 'full') === 'full'
483
+ const text = parts.windows.map((part) => {
484
+ const reset = full && part.resetIn ? `, resets ${part.resetIn}` : ''
485
+ return `${part.kind === 'budget' ? '' : `${part.name} `}${part.figure}${reset}`
486
+ })
487
+ return parts.age === undefined ? text : [...text, parts.age]
488
+ }
489
+
490
+ /**
491
+ * A row's quota as one line: `5h 58% left · 7d 90% left` in the compact
492
+ * form, with `, resets 2h` after each window in the full form, and
493
+ * `5h 58% · 7d 90% left` in the narrow form. With nothing
494
+ * reported it is `NO_QUOTA_READING`, or `NO_LIMITS_REPORTED` when the
495
+ * provider answered without a limit for any window.
496
+ */
497
+ export function formatQuota(
498
+ quota: ProjectedQuota | undefined,
499
+ options: QuotaTextOptions,
500
+ ): string {
501
+ const parts = quotaTextParts(quota, options)
502
+ if (parts.length > 0) return parts.join(' · ')
503
+ return quota && quota.limits.length > 0
504
+ ? NO_LIMITS_REPORTED
505
+ : NO_QUOTA_READING
506
+ }
507
+
508
+ /**
509
+ * Prepaid credits as one short value, worded as the official Codex client's
510
+ * status view words them: `Unlimited` for unlimited credits, `<n> credits`
511
+ * for a finite positive balance (rounded to a whole number), `Available` when
512
+ * the account has credits but no usable balance was reported, and undefined
513
+ * when the account has no credits (or `credits` is undefined), so a caller
514
+ * shows no credits row at all. Unlimited wins even when `hasCredits` is false.
515
+ * No other formatter adds this text; a caller that wants a credits row asks
516
+ * for it.
517
+ */
518
+ export function quotaCreditsText(
519
+ credits:
520
+ | Pick<QuotaCredits, 'hasCredits' | 'unlimited' | 'balance'>
521
+ | undefined,
522
+ ): string | undefined {
523
+ if (credits === undefined) return undefined
524
+ if (credits.unlimited) return 'Unlimited'
525
+ if (!credits.hasCredits) return undefined
526
+ const { balance } = credits
527
+ return typeof balance === 'number' && Number.isFinite(balance) && balance > 0
528
+ ? `${Math.round(balance)} credits`
529
+ : 'Available'
530
+ }