@cortexkit/common-auth 0.17.0 → 0.17.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.
@@ -21,6 +21,26 @@ export interface QuotaTextOptions {
21
21
  /** Defaults to `QUOTA_STALE_AFTER_MS`. */
22
22
  staleAfterMs?: number;
23
23
  }
24
+ export interface QuotaWindowPart {
25
+ kind: 'window' | 'budget';
26
+ /** The display name of a quota window, or `credits` for the budget. */
27
+ name: string;
28
+ /** The shared figure wording, including `credits` for budget figures. */
29
+ figure: string;
30
+ /** The unrounded remaining percentage, clamped to 0–100, when known. */
31
+ remainingPercent?: number;
32
+ /** A bare relative reset span such as `4d`, only when the reset is future. */
33
+ resetIn?: string;
34
+ checkedAt: number;
35
+ /** Whether the reset followed this reading and has arrived by `now`. */
36
+ resetSinceReading: boolean;
37
+ }
38
+ export interface QuotaParts {
39
+ /** Reported windows in display order, followed by the budget when present. */
40
+ windows: QuotaWindowPart[];
41
+ /** The shared checked-age wording, present only when the reading is stale. */
42
+ age?: string;
43
+ }
24
44
  /**
25
45
  * The name a window is shown under. A general window (scope `all`) is named
26
46
  * by its stored length; a model-scoped window keeps the label the plugin
@@ -29,6 +49,12 @@ export interface QuotaTextOptions {
29
49
  * were recorded) falls back to its label.
30
50
  */
31
51
  export declare function quotaWindowName(limit: Pick<ProjectedLimit, 'scope' | 'label' | 'windowMinutes'>): string;
52
+ /**
53
+ * Structured quota wording for layouts that need one row per window. The
54
+ * windows use the same filtering and order as `quotaTextParts`; future resets
55
+ * and the optional age keep the shared formatter's wording.
56
+ */
57
+ export declare function quotaWindowParts(quota: ProjectedQuota | undefined, options: QuotaTextOptions): QuotaParts;
32
58
  /**
33
59
  * The pieces of a quota text, in order: one per reported window
34
60
  * (`5h 58% left, resets 2h`), then the credit budget when there is one, then
@@ -1,7 +1,7 @@
1
1
  // The one quota wording every surface shows: the command menu's dialogs on
2
2
  // OpenCode and Pi, the terminal auth menu, and the plugins' sidebars. Each of
3
- // them calls `formatQuota` (or `quotaTextParts` for one line per window), so
4
- // the wording cannot drift between plugins or between a dialog and a sidebar.
3
+ // them calls `formatQuota`, `quotaTextParts`, or `quotaWindowParts`, so the
4
+ // wording cannot drift between plugins or between a dialog and a sidebar.
5
5
  //
6
6
  // The rules: a window is named by its length (`5h`, `7d`), or, for a window
7
7
  // that binds only one model family, by the label the plugin stored it under.
@@ -55,17 +55,20 @@ export function quotaWindowName(limit) {
55
55
  return limit.label;
56
56
  return lengthName(limit.windowMinutes);
57
57
  }
58
+ function clampPercent(remaining) {
59
+ return Math.min(100, Math.max(0, remaining));
60
+ }
58
61
  function percentLeft(remaining) {
59
- return `${Math.round(Math.min(100, Math.max(0, remaining)))}% left`;
62
+ return `${Math.round(clampPercent(remaining))}% left`;
60
63
  }
61
- function resetText(resetsAt, now) {
62
- if (resetsAt === undefined)
63
- return '';
64
- const at = Date.parse(resetsAt);
65
- // A reset already passed says nothing about the future; leave it out.
66
- if (!Number.isFinite(at) || at <= now)
67
- return '';
68
- return `, resets ${shortSpan(at - now)}`;
64
+ function resetDetails(resetsAt, checkedAt, now) {
65
+ const at = resetsAt === undefined ? Number.NaN : Date.parse(resetsAt);
66
+ return {
67
+ ...(Number.isFinite(at) && at > now
68
+ ? { resetIn: shortSpan(at - now) }
69
+ : {}),
70
+ resetSinceReading: Number.isFinite(at) && at > checkedAt && at <= now,
71
+ };
69
72
  }
70
73
  /** Shortest window first, so `5h` reads before `7d`; unknown lengths last. */
71
74
  function displayOrder(left, right) {
@@ -85,42 +88,70 @@ function displayOrder(left, right) {
85
88
  return left.label < right.label ? -1 : left.label > right.label ? 1 : 0;
86
89
  }
87
90
  /**
88
- * The pieces of a quota text, in order: one per reported window
89
- * (`5h 58% left, resets 2h`), then the credit budget when there is one, then
90
- * `checked 3h ago` when the oldest piece shown is stale. Empty when nothing
91
- * was reported; `formatQuota` turns that into a sentence. A caller printing
92
- * one line per window (the terminal auth menu) uses these directly.
91
+ * Structured quota wording for layouts that need one row per window. The
92
+ * windows use the same filtering and order as `quotaTextParts`; future resets
93
+ * and the optional age keep the shared formatter's wording.
93
94
  */
94
- export function quotaTextParts(quota, options) {
95
+ export function quotaWindowParts(quota, options) {
95
96
  if (!quota)
96
- return [];
97
+ return { windows: [] };
97
98
  const { now } = options;
98
- const full = (options.form ?? 'full') === 'full';
99
- const parts = [];
100
- const times = [];
101
99
  const readings = quota.limits
102
100
  .filter((limit) => limit.kind === 'reading' && limit.remainingPercent !== undefined)
103
101
  .sort(displayOrder);
104
- for (const limit of readings) {
105
- times.push(limit.checkedAt);
106
- parts.push(`${quotaWindowName(limit)} ${percentLeft(limit.remainingPercent ?? 0)}${full ? resetText(limit.resetsAt, now) : ''}`);
107
- }
102
+ const windows = readings.map((limit) => {
103
+ const remainingPercent = clampPercent(limit.remainingPercent ?? 0);
104
+ return {
105
+ kind: 'window',
106
+ name: quotaWindowName(limit),
107
+ figure: percentLeft(limit.remainingPercent ?? 0),
108
+ remainingPercent,
109
+ checkedAt: limit.checkedAt,
110
+ ...resetDetails(limit.resetsAt, limit.checkedAt, now),
111
+ };
112
+ });
108
113
  const budget = quota.budget;
109
114
  if (budget) {
110
- times.push(budget.checkedAt);
115
+ const remainingPercent = budget.remainingPercent;
111
116
  const figure = budget.reached
112
117
  ? 'credits spent'
113
- : budget.remainingPercent !== undefined
114
- ? `credits ${percentLeft(budget.remainingPercent)}`
118
+ : remainingPercent !== undefined
119
+ ? `credits ${percentLeft(remainingPercent)}`
115
120
  : 'credits available';
116
- parts.push(`${figure}${full ? resetText(budget.resetsAt, now) : ''}`);
121
+ windows.push({
122
+ kind: 'budget',
123
+ name: 'credits',
124
+ figure,
125
+ ...(remainingPercent === undefined
126
+ ? {}
127
+ : { remainingPercent: clampPercent(remainingPercent) }),
128
+ checkedAt: budget.checkedAt,
129
+ ...resetDetails(budget.resetsAt, budget.checkedAt, now),
130
+ });
117
131
  }
118
- if (times.length > 0) {
119
- const age = now - Math.min(...times);
120
- if (age > (options.staleAfterMs ?? QUOTA_STALE_AFTER_MS))
121
- parts.push(`checked ${shortSpan(age)} ago`);
132
+ if (windows.length > 0) {
133
+ const age = now - Math.min(...windows.map((part) => part.checkedAt));
134
+ if (age > (options.staleAfterMs ?? QUOTA_STALE_AFTER_MS)) {
135
+ return { windows, age: `checked ${shortSpan(age)} ago` };
136
+ }
122
137
  }
123
- return parts;
138
+ return { windows };
139
+ }
140
+ /**
141
+ * The pieces of a quota text, in order: one per reported window
142
+ * (`5h 58% left, resets 2h`), then the credit budget when there is one, then
143
+ * `checked 3h ago` when the oldest piece shown is stale. Empty when nothing
144
+ * was reported; `formatQuota` turns that into a sentence. A caller printing
145
+ * one line per window (the terminal auth menu) uses these directly.
146
+ */
147
+ export function quotaTextParts(quota, options) {
148
+ const parts = quotaWindowParts(quota, options);
149
+ const full = (options.form ?? 'full') === 'full';
150
+ const text = parts.windows.map((part) => {
151
+ const reset = full && part.resetIn ? `, resets ${part.resetIn}` : '';
152
+ return `${part.kind === 'budget' ? '' : `${part.name} `}${part.figure}${reset}`;
153
+ });
154
+ return parts.age === undefined ? text : [...text, parts.age];
124
155
  }
125
156
  /**
126
157
  * A row's quota as one line: `5h 58% left · 7d 90% left` in the compact
@@ -1,7 +1,7 @@
1
1
  export type { QuotaCodec } from './codec.js';
2
2
  export { quotaCodec } from './codec.js';
3
- export type { QuotaTextForm, QuotaTextOptions } from './format.js';
4
- export { formatQuota, NO_LIMITS_REPORTED, NO_QUOTA_READING, QUOTA_STALE_AFTER_MS, quotaTextParts, quotaWindowName, } from './format.js';
3
+ export type { QuotaParts, QuotaTextForm, QuotaTextOptions, QuotaWindowPart, } from './format.js';
4
+ export { formatQuota, NO_LIMITS_REPORTED, NO_QUOTA_READING, QUOTA_STALE_AFTER_MS, quotaTextParts, quotaWindowName, quotaWindowParts, } from './format.js';
5
5
  export type { CreditBudgetCleared, CreditBudgetEntry, CreditBudgetReading, QuotaAbsentEntry, QuotaCounter, QuotaEntry, QuotaMap, QuotaReadingEntry, QuotaRetiredEntry, } from './map.js';
6
6
  export { ALL_SCOPE, DEFAULT_REQUIRED_LABELS, decodeQuotaMap, emptyQuotaMap, isQuotaMap, } from './map.js';
7
7
  export type { ObservedBudget, ObservedPair, ObservedReading, QuotaObservation, } from './merge.js';
@@ -1,5 +1,5 @@
1
1
  export { quotaCodec } from './codec.js';
2
- export { formatQuota, NO_LIMITS_REPORTED, NO_QUOTA_READING, QUOTA_STALE_AFTER_MS, quotaTextParts, quotaWindowName, } from './format.js';
2
+ export { formatQuota, NO_LIMITS_REPORTED, NO_QUOTA_READING, QUOTA_STALE_AFTER_MS, quotaTextParts, quotaWindowName, quotaWindowParts, } from './format.js';
3
3
  export { ALL_SCOPE, DEFAULT_REQUIRED_LABELS, decodeQuotaMap, emptyQuotaMap, isQuotaMap, } from './map.js';
4
4
  export { isQuotaObservation, mergeQuotaObservation, QuotaCodecError, } from './merge.js';
5
5
  export { budgetExhaustedResetAt, futureResetAt, projectQuota, readsExhausted, } from './projection.js';
@@ -1,4 +1,3 @@
1
- import { confirm } from '../auth-menu/confirm.js';
2
1
  import { select } from '../auth-menu/select.js';
3
2
  import { isInteractive, printLine, processTerminal, } from '../auth-menu/terminal.js';
4
3
  import { hostEnrollmentPaths } from '../claustrum/enrollment.js';
@@ -139,12 +138,25 @@ export async function runSetup(plugin, argv = [], io = {}) {
139
138
  await stopped();
140
139
  if (options.claustrum && !detection.claustrum.available)
141
140
  throw new Error('Claustrum is not available. Start ck or use --no-claustrum for local sign-in.');
142
- const useVault = options.claustrum ||
143
- (!options.login &&
144
- !options.noClaustrum &&
145
- !assumeYes &&
146
- detection.claustrum.available &&
147
- (await confirm(terminal, 'Connect these hosts to the Claustrum vault?')));
141
+ let useVault = Boolean(options.claustrum);
142
+ if (!useVault &&
143
+ !options.login &&
144
+ !options.noClaustrum &&
145
+ !assumeYes &&
146
+ detection.claustrum.available &&
147
+ isInteractive(terminal)) {
148
+ // Not `confirm`: it reads Escape and Ctrl-C as "No", and "No" here means
149
+ // a local sign-in. Cancelling must stop setup before anything changes.
150
+ const choice = await select(terminal, [
151
+ { label: 'No', value: false },
152
+ { label: 'Yes', value: true },
153
+ ], { message: 'Connect these hosts to the Claustrum vault?' });
154
+ if (choice === null) {
155
+ printLine(terminal, 'Setup cancelled. Nothing was changed.');
156
+ return { hosts: [], dryRun: options.dryRun, mode: 'local', detection };
157
+ }
158
+ useVault = choice === true;
159
+ }
148
160
  const mode = useVault ? 'claustrum' : 'local';
149
161
  // Validate every config before login or enrollment can change credential state.
150
162
  const writes = hosts.includes('opencode')
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cortexkit/common-auth",
3
- "version": "0.17.0",
3
+ "version": "0.17.1",
4
4
  "description": "Shared code for the CortexKit auth plugins: account pool, quota and routing, commands and auth menu, OpenCode 2 hooks, Claustrum custody, and plumbing (loopback RPC, file locks, logger, sidebar state, TUI preferences and build).",
5
5
  "license": "MIT",
6
6
  "repository": {