@cortexkit/common-auth 0.17.0 → 0.17.2

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.
@@ -1,8 +1,25 @@
1
1
  import { randomUUID } from 'node:crypto';
2
- import { mkdir, open, readFile, rename, rm, stat, writeFile, } from 'node:fs/promises';
2
+ import { mkdir, open, readFile, rename, rm, stat } from 'node:fs/promises';
3
3
  import { dirname, join } from 'node:path';
4
4
  import { createPrivateBytes, createPrivateDirectoryExclusive, ensurePrivateDirectory, PrivateFileError, privateOperation, readPrivateText, verifyPrivate, windowsPrivateFiles, writePrivateAtomic, } from './private-files.js';
5
5
  import { LockOwnershipError, lockPathFor } from './with-lock.js';
6
+ /**
7
+ * Create a new owner-only file and write `text` into it, failing with EEXIST if
8
+ * the file already exists. Writing through the handle rather than path-based
9
+ * `writeFile(path, …, { flag: 'wx' })` matters: Bun's path form also truncates
10
+ * the file it has just created, and on some Linux filesystems (XFS under load)
11
+ * that redundant ftruncate stalls for hundreds of milliseconds, inside every
12
+ * lock acquisition.
13
+ */
14
+ async function createExclusiveText(path, text) {
15
+ const handle = await open(path, 'wx', 0o600);
16
+ try {
17
+ await handle.writeFile(text, 'utf8');
18
+ }
19
+ finally {
20
+ await handle.close();
21
+ }
22
+ }
6
23
  const setRefreshLockRenewalTimeout = globalThis.setTimeout.bind(globalThis);
7
24
  const clearRefreshLockRenewalTimeout = globalThis.clearTimeout.bind(globalThis);
8
25
  // A concurrent contender renaming the freshly-created eviction-marker directory
@@ -152,11 +169,7 @@ export async function acquireRefreshFileLock(options) {
152
169
  if (windowsPrivateFiles)
153
170
  await createPrivateBytes(lockPath, bytes);
154
171
  else
155
- await writeFile(lockPath, bytes, {
156
- encoding: 'utf8',
157
- mode: 0o600,
158
- flag: 'wx',
159
- });
172
+ await createExclusiveText(lockPath, bytes);
160
173
  }
161
174
  async function leaseContention(error) {
162
175
  const code = error.code;
@@ -304,11 +317,7 @@ export async function acquireRefreshFileLock(options) {
304
317
  if (windowsPrivateFiles)
305
318
  await createPrivateBytes(evictOwnerPath, bytes);
306
319
  else
307
- await writeFile(evictOwnerPath, bytes, {
308
- encoding: 'utf8',
309
- mode: 0o600,
310
- flag: 'wx',
311
- });
320
+ await createExclusiveText(evictOwnerPath, bytes);
312
321
  }
313
322
  catch (error) {
314
323
  // A competing contender can rename our just-created marker directory
@@ -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.
@@ -22,18 +22,23 @@ export const NO_QUOTA_READING = 'no quota reading yet';
22
22
  */
23
23
  export const NO_LIMITS_REPORTED = 'no limits reported';
24
24
  /**
25
- * A length or a time span in its largest whole-ish unit: `45m`, `5h`, `3d`.
26
- * Spans under an hour are minutes, under a day hours, otherwise days, each
27
- * rounded to the nearest unit and never shown as zero.
25
+ * A time span in at most its two largest units: `45m`, `2h29m`, `5h`, `3d23h`,
26
+ * `7d`. Every unit is rounded down, so a reset is never shown later than it is;
27
+ * the one exception is a span under a minute, which reads `1m` rather than
28
+ * zero. A zero second unit is left out.
28
29
  */
29
30
  function shortSpan(ms) {
30
- const minutes = Math.max(1, Math.round(ms / 60_000));
31
+ const minutes = Math.max(1, Math.floor(ms / 60_000));
31
32
  if (minutes < 60)
32
33
  return `${minutes}m`;
33
- const hours = Math.round(minutes / 60);
34
- if (hours < 24)
35
- return `${hours}h`;
36
- return `${Math.max(1, Math.round(minutes / 1440))}d`;
34
+ if (minutes < 1440) {
35
+ const hours = Math.floor(minutes / 60);
36
+ const rest = minutes % 60;
37
+ return rest === 0 ? `${hours}h` : `${hours}h${rest}m`;
38
+ }
39
+ const days = Math.floor(minutes / 1440);
40
+ const hours = Math.floor((minutes % 1440) / 60);
41
+ return hours === 0 ? `${days}d` : `${days}d${hours}h`;
37
42
  }
38
43
  /** A stored window length in minutes as its exact name: `5h`, `7d`, `90m`. */
39
44
  function lengthName(minutes) {
@@ -55,17 +60,20 @@ export function quotaWindowName(limit) {
55
60
  return limit.label;
56
61
  return lengthName(limit.windowMinutes);
57
62
  }
63
+ function clampPercent(remaining) {
64
+ return Math.min(100, Math.max(0, remaining));
65
+ }
58
66
  function percentLeft(remaining) {
59
- return `${Math.round(Math.min(100, Math.max(0, remaining)))}% left`;
67
+ return `${Math.round(clampPercent(remaining))}% left`;
60
68
  }
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)}`;
69
+ function resetDetails(resetsAt, checkedAt, now) {
70
+ const at = resetsAt === undefined ? Number.NaN : Date.parse(resetsAt);
71
+ return {
72
+ ...(Number.isFinite(at) && at > now
73
+ ? { resetIn: shortSpan(at - now) }
74
+ : {}),
75
+ resetSinceReading: Number.isFinite(at) && at > checkedAt && at <= now,
76
+ };
69
77
  }
70
78
  /** Shortest window first, so `5h` reads before `7d`; unknown lengths last. */
71
79
  function displayOrder(left, right) {
@@ -85,42 +93,70 @@ function displayOrder(left, right) {
85
93
  return left.label < right.label ? -1 : left.label > right.label ? 1 : 0;
86
94
  }
87
95
  /**
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.
96
+ * Structured quota wording for layouts that need one row per window. The
97
+ * windows use the same filtering and order as `quotaTextParts`; future resets
98
+ * and the optional age keep the shared formatter's wording.
93
99
  */
94
- export function quotaTextParts(quota, options) {
100
+ export function quotaWindowParts(quota, options) {
95
101
  if (!quota)
96
- return [];
102
+ return { windows: [] };
97
103
  const { now } = options;
98
- const full = (options.form ?? 'full') === 'full';
99
- const parts = [];
100
- const times = [];
101
104
  const readings = quota.limits
102
105
  .filter((limit) => limit.kind === 'reading' && limit.remainingPercent !== undefined)
103
106
  .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
- }
107
+ const windows = readings.map((limit) => {
108
+ const remainingPercent = clampPercent(limit.remainingPercent ?? 0);
109
+ return {
110
+ kind: 'window',
111
+ name: quotaWindowName(limit),
112
+ figure: percentLeft(limit.remainingPercent ?? 0),
113
+ remainingPercent,
114
+ checkedAt: limit.checkedAt,
115
+ ...resetDetails(limit.resetsAt, limit.checkedAt, now),
116
+ };
117
+ });
108
118
  const budget = quota.budget;
109
119
  if (budget) {
110
- times.push(budget.checkedAt);
120
+ const remainingPercent = budget.remainingPercent;
111
121
  const figure = budget.reached
112
122
  ? 'credits spent'
113
- : budget.remainingPercent !== undefined
114
- ? `credits ${percentLeft(budget.remainingPercent)}`
123
+ : remainingPercent !== undefined
124
+ ? `credits ${percentLeft(remainingPercent)}`
115
125
  : 'credits available';
116
- parts.push(`${figure}${full ? resetText(budget.resetsAt, now) : ''}`);
126
+ windows.push({
127
+ kind: 'budget',
128
+ name: 'credits',
129
+ figure,
130
+ ...(remainingPercent === undefined
131
+ ? {}
132
+ : { remainingPercent: clampPercent(remainingPercent) }),
133
+ checkedAt: budget.checkedAt,
134
+ ...resetDetails(budget.resetsAt, budget.checkedAt, now),
135
+ });
117
136
  }
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`);
137
+ if (windows.length > 0) {
138
+ const age = now - Math.min(...windows.map((part) => part.checkedAt));
139
+ if (age > (options.staleAfterMs ?? QUOTA_STALE_AFTER_MS)) {
140
+ return { windows, age: `checked ${shortSpan(age)} ago` };
141
+ }
122
142
  }
123
- return parts;
143
+ return { windows };
144
+ }
145
+ /**
146
+ * The pieces of a quota text, in order: one per reported window
147
+ * (`5h 58% left, resets 2h`), then the credit budget when there is one, then
148
+ * `checked 3h ago` when the oldest piece shown is stale. Empty when nothing
149
+ * was reported; `formatQuota` turns that into a sentence. A caller printing
150
+ * one line per window (the terminal auth menu) uses these directly.
151
+ */
152
+ export function quotaTextParts(quota, options) {
153
+ const parts = quotaWindowParts(quota, options);
154
+ const full = (options.form ?? 'full') === 'full';
155
+ const text = parts.windows.map((part) => {
156
+ const reset = full && part.resetIn ? `, resets ${part.resetIn}` : '';
157
+ return `${part.kind === 'budget' ? '' : `${part.name} `}${part.figure}${reset}`;
158
+ });
159
+ return parts.age === undefined ? text : [...text, parts.age];
124
160
  }
125
161
  /**
126
162
  * 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.2",
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": {