@cortexkit/common-auth 0.16.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.
@@ -103,7 +103,12 @@ export interface EnrollmentAncestorOptions {
103
103
  */
104
104
  export declare function refuseWritableAncestor(parent: string, options?: EnrollmentAncestorOptions): Promise<void>;
105
105
  export declare function readClaustrumEnrollmentStatus(paths: ClaustrumEnrollmentPaths, proposedName: string): Promise<ClaustrumEnrollmentStatus>;
106
- /** Resolve the host's account mode from its enrollment files without writing. */
106
+ /**
107
+ * Resolve the host's account mode from its enrollment files. It never changes
108
+ * their contents or the host's mode. On Windows, reading them may create a
109
+ * missing private state folder and tighten an enrollment file's permissions to
110
+ * owner-only, as every private-file read there does.
111
+ */
107
112
  export declare function enrollmentAuthority(paths: ClaustrumEnrollmentPaths, proposedName: string): Promise<'vault' | 'local' | 'unreadable'>;
108
113
  /**
109
114
  * Read fresh bearer material for one scoped operation; never publish it.
@@ -419,7 +419,12 @@ export async function readClaustrumEnrollmentStatus(paths, proposedName) {
419
419
  }
420
420
  return statusFromState(state);
421
421
  }
422
- /** Resolve the host's account mode from its enrollment files without writing. */
422
+ /**
423
+ * Resolve the host's account mode from its enrollment files. It never changes
424
+ * their contents or the host's mode. On Windows, reading them may create a
425
+ * missing private state folder and tighten an enrollment file's permissions to
426
+ * owner-only, as every private-file read there does.
427
+ */
423
428
  export async function enrollmentAuthority(paths, proposedName) {
424
429
  let status;
425
430
  try {
@@ -1,7 +1,7 @@
1
1
  import { createHash } from 'node:crypto';
2
2
  import { acquireRefreshFileLock, withLock, writeJsonAtomic, } from '../fs/index.js';
3
3
  import { readPrivateText, windowsPrivateFiles } from '../fs/private-files.js';
4
- import { isQuotaMap, mergeQuotaObservation, } from '../quota/index.js';
4
+ import { decodeQuotaMap, mergeQuotaObservation, } from '../quota/index.js';
5
5
  import { ClaustrumConsumerError } from './errors.js';
6
6
  import { acceptAccount, declineAccount, isDeclined, } from './interlock.js';
7
7
  export const DEFAULT_ROUTE_PREFIX = 'vault:';
@@ -210,6 +210,7 @@ function optionalString(value) {
210
210
  return value === undefined || typeof value === 'string';
211
211
  }
212
212
  function decodeRow(value) {
213
+ const quota = isRecord(value) ? decodeQuotaMap(value.quota) : undefined;
213
214
  if (!isRecord(value) ||
214
215
  typeof value.routeId !== 'string' ||
215
216
  typeof value.credentialId !== 'string' ||
@@ -224,11 +225,14 @@ function decodeRow(value) {
224
225
  (value.aliases !== undefined &&
225
226
  (!Array.isArray(value.aliases) ||
226
227
  !value.aliases.every((alias) => typeof alias === 'string'))) ||
227
- (value.quota !== undefined && !isQuotaMap(value.quota)) ||
228
+ (value.quota !== undefined && quota === undefined) ||
228
229
  (value.stale !== undefined && value.stale !== true) ||
229
230
  (value.unclaimed !== undefined && value.unclaimed !== true))
230
231
  return undefined;
231
- return value;
232
+ return {
233
+ ...value,
234
+ ...(quota === undefined ? {} : { quota }),
235
+ };
232
236
  }
233
237
  const SKIPPED_REASONS = new Set([
234
238
  'empty credential id',
@@ -1,5 +1,7 @@
1
1
  export interface QuotaCodec {
2
2
  readonly validate: (value: unknown) => boolean;
3
+ /** Normalize persisted data before validation; older codecs may omit this. */
4
+ readonly decode?: (value: unknown) => unknown;
3
5
  readonly merge: (stored: unknown, observation: unknown) => unknown;
4
6
  }
5
7
  /**
@@ -1,4 +1,4 @@
1
- import { isQuotaMap } from './map.js';
1
+ import { decodeQuotaMap, isQuotaMap } from './map.js';
2
2
  import { mergeQuotaObservation } from './merge.js';
3
3
  /**
4
4
  * The quota codec the account-pool store (the `/store` subpath) takes when it
@@ -8,5 +8,6 @@ import { mergeQuotaObservation } from './merge.js';
8
8
  */
9
9
  export const quotaCodec = Object.freeze({
10
10
  validate: isQuotaMap,
11
+ decode: decodeQuotaMap,
11
12
  merge: mergeQuotaObservation,
12
13
  });
@@ -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,9 +1,9 @@
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';
5
- export type { CreditBudgetCleared, CreditBudgetEntry, CreditBudgetReading, QuotaAbsentEntry, QuotaEntry, QuotaMap, QuotaReadingEntry, QuotaRetiredEntry, } from './map.js';
6
- export { ALL_SCOPE, DEFAULT_REQUIRED_LABELS, emptyQuotaMap, isQuotaMap, } from './map.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
+ export type { CreditBudgetCleared, CreditBudgetEntry, CreditBudgetReading, QuotaAbsentEntry, QuotaCounter, QuotaEntry, QuotaMap, QuotaReadingEntry, QuotaRetiredEntry, } from './map.js';
6
+ export { ALL_SCOPE, DEFAULT_REQUIRED_LABELS, decodeQuotaMap, emptyQuotaMap, isQuotaMap, } from './map.js';
7
7
  export type { ObservedBudget, ObservedPair, ObservedReading, QuotaObservation, } from './merge.js';
8
8
  export { isQuotaObservation, mergeQuotaObservation, QuotaCodecError, } from './merge.js';
9
9
  export type { ExhaustionReset, ProjectedBudget, ProjectedLimit, ProjectedQuota, } from './projection.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';
3
- export { ALL_SCOPE, DEFAULT_REQUIRED_LABELS, emptyQuotaMap, isQuotaMap, } from './map.js';
2
+ export { formatQuota, NO_LIMITS_REPORTED, NO_QUOTA_READING, QUOTA_STALE_AFTER_MS, quotaTextParts, quotaWindowName, quotaWindowParts, } from './format.js';
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';
@@ -44,16 +44,27 @@ export interface CreditBudgetCleared {
44
44
  checkedAt: number;
45
45
  }
46
46
  export type CreditBudgetEntry = CreditBudgetReading | CreditBudgetCleared;
47
+ export interface QuotaCounter {
48
+ value: number;
49
+ checkedAt: number;
50
+ }
47
51
  export interface QuotaMap {
48
52
  limits: QuotaEntry[];
49
53
  /** Absent means no observation has reported on the budget yet. */
50
54
  budget?: CreditBudgetEntry;
55
+ /** Provider-named counts, each with its own observation time. */
56
+ counters?: Record<string, QuotaCounter>;
51
57
  }
52
58
  export declare function emptyQuotaMap(): QuotaMap;
53
59
  /** The time an entry speaks for: its reading, retirement or absence time. */
54
60
  export declare function entryTime(entry: QuotaEntry): number;
55
61
  export declare function limitKey(scope: string, label: string): string;
56
62
  export declare function isCreditBudgetEntry(value: unknown): value is CreditBudgetEntry;
63
+ export declare function isQuotaCounters(value: unknown): value is Record<string, QuotaCounter>;
64
+ /** Keep usable counters without letting one malformed count hide a quota map. */
65
+ export declare function readQuotaCounters(value: unknown): Record<string, QuotaCounter> | undefined;
66
+ /** Decode persisted quota, dropping malformed counters but not limit evidence. */
67
+ export declare function decodeQuotaMap(value: unknown): QuotaMap | undefined;
57
68
  /**
58
69
  * True when `value` is a well-formed quota map. Unrecognised top-level keys
59
70
  * are tolerated (and preserved by merge) so a newer writer's additions
package/dist/quota/map.js CHANGED
@@ -83,6 +83,40 @@ export function isCreditBudgetEntry(value) {
83
83
  optional(value, 'remaining', isFiniteNumber) &&
84
84
  optional(value, 'unit', isString));
85
85
  }
86
+ function isQuotaCounter(value) {
87
+ return (isRecord(value) &&
88
+ isFiniteNumber(value.value) &&
89
+ Number.isInteger(value.value) &&
90
+ value.value >= 0 &&
91
+ isFiniteNumber(value.checkedAt));
92
+ }
93
+ export function isQuotaCounters(value) {
94
+ return isRecord(value) && Object.values(value).every(isQuotaCounter);
95
+ }
96
+ /** Keep usable counters without letting one malformed count hide a quota map. */
97
+ export function readQuotaCounters(value) {
98
+ if (!isRecord(value))
99
+ return undefined;
100
+ const entries = Object.entries(value).filter(([, entry]) => isQuotaCounter(entry));
101
+ return entries.length === 0
102
+ ? undefined
103
+ : Object.fromEntries(entries);
104
+ }
105
+ /** Decode persisted quota, dropping malformed counters but not limit evidence. */
106
+ export function decodeQuotaMap(value) {
107
+ // A valid map is returned as the same object, so stored quota keeps the
108
+ // identity it had before counters existed; only a map with a malformed
109
+ // counter is copied without it.
110
+ if (isQuotaMap(value))
111
+ return value;
112
+ if (!isRecord(value))
113
+ return undefined;
114
+ const { counters: rawCounters, ...rest } = value;
115
+ if (!isQuotaMap(rest))
116
+ return undefined;
117
+ const counters = readQuotaCounters(rawCounters);
118
+ return { ...rest, ...(counters === undefined ? {} : { counters }) };
119
+ }
86
120
  /**
87
121
  * True when `value` is a well-formed quota map. Unrecognised top-level keys
88
122
  * are tolerated (and preserved by merge) so a newer writer's additions
@@ -101,5 +135,6 @@ export function isQuotaMap(value) {
101
135
  return false;
102
136
  seen.add(key);
103
137
  }
104
- return optional(value, 'budget', isCreditBudgetEntry);
138
+ return (optional(value, 'budget', isCreditBudgetEntry) &&
139
+ optional(value, 'counters', isQuotaCounters));
105
140
  }
@@ -1,4 +1,4 @@
1
- import { type QuotaMap } from './map.js';
1
+ import { type QuotaCounter, type QuotaMap } from './map.js';
2
2
  export interface ObservedReading {
3
3
  /** Defaults to `all`. */
4
4
  scope?: string;
@@ -32,6 +32,8 @@ export interface QuotaObservation {
32
32
  coverage?: ObservedPair[];
33
33
  /** Absent means the observation says nothing about the budget. */
34
34
  budget?: ObservedBudget;
35
+ /** Each named count uses its own time, independently of limits and budget. */
36
+ counters?: Record<string, QuotaCounter>;
35
37
  }
36
38
  /** Thrown by `mergeQuotaObservation` when either argument is malformed. */
37
39
  export declare class QuotaCodecError extends TypeError {
@@ -11,7 +11,7 @@
11
11
  // no entry gets an absence record. A pair outside the coverage is never
12
12
  // touched, so a header-shaped partial observation (which covers only what it
13
13
  // carries) cannot erase a family limit or the budget.
14
- import { ALL_SCOPE, entryTime, isQuotaMap, limitKey, } from './map.js';
14
+ import { ALL_SCOPE, decodeQuotaMap, entryTime, isQuotaCounters, limitKey, } from './map.js';
15
15
  /** Thrown by `mergeQuotaObservation` when either argument is malformed. */
16
16
  export class QuotaCodecError extends TypeError {
17
17
  constructor(message) {
@@ -83,7 +83,8 @@ export function isQuotaObservation(value) {
83
83
  }
84
84
  if (!coverage.every(isObservedPair))
85
85
  return false;
86
- return value.budget === undefined || isObservedBudget(value.budget);
86
+ return ((value.budget === undefined || isObservedBudget(value.budget)) &&
87
+ (value.counters === undefined || isQuotaCounters(value.counters)));
87
88
  }
88
89
  function compareEntries(left, right) {
89
90
  if (left.scope !== right.scope)
@@ -99,6 +100,16 @@ function mergeBudget(stored, observed, checkedAt) {
99
100
  return stored;
100
101
  return { ...observed, checkedAt };
101
102
  }
103
+ function mergeCounters(stored, observed) {
104
+ const counters = new Map(Object.entries(stored ?? {}));
105
+ for (const [name, counter] of Object.entries(observed ?? {})) {
106
+ const existing = counters.get(name);
107
+ if (existing === undefined || counter.checkedAt >= existing.checkedAt) {
108
+ counters.set(name, counter);
109
+ }
110
+ }
111
+ return counters.size === 0 ? undefined : Object.fromEntries(counters);
112
+ }
102
113
  /**
103
114
  * Applies `observation` to `stored` (undefined for a row with no map yet) and
104
115
  * returns the new map. Pure: neither argument is modified. Throws
@@ -106,13 +117,16 @@ function mergeBudget(stored, observed, checkedAt) {
106
117
  * write rather than persisting a map it could not read back.
107
118
  */
108
119
  export function mergeQuotaObservation(stored, observation) {
109
- if (stored !== undefined && !isQuotaMap(stored)) {
120
+ // Decode the stored map the way reads do, so a malformed counter that reads
121
+ // already hide is dropped here too instead of refusing every later write.
122
+ const decoded = stored === undefined ? undefined : decodeQuotaMap(stored);
123
+ if (stored !== undefined && decoded === undefined) {
110
124
  throw new QuotaCodecError('stored quota map is malformed');
111
125
  }
112
126
  if (!isQuotaObservation(observation)) {
113
127
  throw new QuotaCodecError('quota observation is malformed');
114
128
  }
115
- const base = stored ?? { limits: [] };
129
+ const base = decoded ?? { limits: [] };
116
130
  const at = observation.checkedAt;
117
131
  const entries = new Map();
118
132
  for (const entry of base.limits) {
@@ -152,11 +166,13 @@ export function mergeQuotaObservation(stored, observation) {
152
166
  : { scope, label: pair.label, kind: 'retired', retiredAt: at });
153
167
  }
154
168
  // Keys this module does not recognise are carried over untouched.
155
- const { limits: _limits, budget: _budget, ...unknownKeys } = base;
169
+ const { limits: _limits, budget: _budget, counters: _counters, ...unknownKeys } = base;
156
170
  const budget = mergeBudget(base.budget, observation.budget, at);
171
+ const counters = mergeCounters(base.counters, observation.counters);
157
172
  return {
158
173
  ...unknownKeys,
159
174
  limits: [...entries.values()].sort(compareEntries),
160
175
  ...(budget === undefined ? {} : { budget }),
176
+ ...(counters === undefined ? {} : { counters }),
161
177
  };
162
178
  }
@@ -1,4 +1,4 @@
1
- import { type QuotaMap } from './map.js';
1
+ import { type QuotaCounter, type QuotaMap } from './map.js';
2
2
  export interface ProjectedLimit {
3
3
  scope: string;
4
4
  label: string;
@@ -30,6 +30,7 @@ export interface ProjectedQuota {
30
30
  checkedAt?: number;
31
31
  /** Present only when the stored budget is a reading, not cleared. */
32
32
  budget?: ProjectedBudget;
33
+ counters?: Record<string, QuotaCounter>;
33
34
  }
34
35
  /**
35
36
  * Resolves `map` for a request in `scope` (`all` or a model family). A family
@@ -6,7 +6,7 @@
6
6
  // scope, orders the result the way the primitives expect, and carries each
7
7
  // entry's (scope, label) so a decision names the limit it judged rather than
8
8
  // the position it occupied.
9
- import { ALL_SCOPE, } from './map.js';
9
+ import { ALL_SCOPE, readQuotaCounters, } from './map.js';
10
10
  function project(entry) {
11
11
  if (entry.kind === 'retired') {
12
12
  return {
@@ -94,11 +94,13 @@ export function projectQuota(map, scope = ALL_SCOPE) {
94
94
  ? Math.min(...stamped.map((limit) => limit.checkedAt))
95
95
  : undefined;
96
96
  const budget = map?.budget?.kind === 'reading' ? projectBudget(map.budget) : undefined;
97
+ const counters = readQuotaCounters(map?.counters);
97
98
  return {
98
99
  scope,
99
100
  limits,
100
101
  ...(checkedAt === undefined ? {} : { checkedAt }),
101
102
  ...(budget === undefined ? {} : { budget }),
103
+ ...(counters === undefined ? {} : { counters }),
102
104
  };
103
105
  }
104
106
  /**
@@ -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';
@@ -119,7 +118,12 @@ export async function runSetup(plugin, argv = [], io = {}) {
119
118
  printLine(terminal, 'Checking that OpenCode and Pi are not running…');
120
119
  if (options.dryRun) {
121
120
  try {
122
- const active = await fence.listRunningHosts(env);
121
+ const preview = fence.previewRunningHosts
122
+ ? await fence.previewRunningHosts(env)
123
+ : { hosts: await fence.listRunningHosts(env), uncheckedRuntimes: 0 };
124
+ const active = preview.hosts;
125
+ if (preview.uncheckedRuntimes > 0)
126
+ printLine(terminal, 'Node or Bun programs are running; a real run checks whether any of them is OpenCode or Pi.');
123
127
  const names = new Set(new ProcessFenceViolationError(active).activeHosts.map((host) => host.command.toLowerCase() === 'pi' ? 'Pi' : 'OpenCode'));
124
128
  for (const name of names)
125
129
  printLine(terminal, `${name} is running; setup will ask you to quit it.`);
@@ -134,12 +138,25 @@ export async function runSetup(plugin, argv = [], io = {}) {
134
138
  await stopped();
135
139
  if (options.claustrum && !detection.claustrum.available)
136
140
  throw new Error('Claustrum is not available. Start ck or use --no-claustrum for local sign-in.');
137
- const useVault = options.claustrum ||
138
- (!options.login &&
139
- !options.noClaustrum &&
140
- !assumeYes &&
141
- detection.claustrum.available &&
142
- (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
+ }
143
160
  const mode = useVault ? 'claustrum' : 'local';
144
161
  // Validate every config before login or enrollment can change credential state.
145
162
  const writes = hosts.includes('opencode')
@@ -148,6 +165,8 @@ export async function runSetup(plugin, argv = [], io = {}) {
148
165
  if (options.dryRun) {
149
166
  printLine(terminal, 'Dry run: no registrations, enrollment, sign-in or migration will be performed.');
150
167
  for (const host of hosts) {
168
+ if (plugin.beforeSignIn)
169
+ printLine(terminal, `Would run beforeSignIn(${host}, ${mode}).`);
151
170
  if (useVault) {
152
171
  const paths = hostEnrollmentPaths(plugin.vault.hosts[host].paths);
153
172
  printLine(terminal, `Would Connect ${host}: write ${paths.statePath} and ${paths.tokenPath}; wait for ck auth enroll approve.`);
@@ -165,21 +184,29 @@ export async function runSetup(plugin, argv = [], io = {}) {
165
184
  printLine(terminal, `Would migrate ${host} using the plugin callback (provider-specific writes).`);
166
185
  }
167
186
  else {
187
+ const context = {
188
+ opencodeGeneration: generation,
189
+ mode,
190
+ hosts: Object.freeze([...hosts]),
191
+ piAgentDir: detection.pi.directory,
192
+ };
168
193
  for (const host of hosts) {
194
+ await stopped();
195
+ await plugin.beforeSignIn?.(host, context);
169
196
  await stopped();
170
197
  if (useVault)
171
198
  await connectSetupHost(plugin, host, io, terminal, stopped);
172
199
  else
173
- await plugin.signInLocal(host);
200
+ await plugin.signInLocal(host, context);
174
201
  await stopped();
175
- await plugin.beforeRegister?.(host, mode);
202
+ await plugin.beforeRegister?.(host, mode, context);
176
203
  await stopped();
177
204
  if (host === 'opencode')
178
205
  await registerOpenCode(writes, stopped);
179
206
  else
180
207
  await registerPi(plugin, detection.pi.executable, io);
181
208
  await stopped();
182
- await plugin.migrate(host);
209
+ await plugin.migrate(host, context);
183
210
  }
184
211
  }
185
212
  printLine(terminal, `${options.dryRun ? 'Planned' : 'Configured'} ${plugin.displayName} for ${hosts.join(', ')} (${mode}).`);
@@ -2,4 +2,4 @@ export { AMBIGUOUS_OPENCODE_MESSAGE, runSetup } from './command.js';
2
2
  export { detectHosts, detectOpenCodeGeneration, findExecutableOnPath, openCodeDesktopMarkers, } from './detect.js';
3
3
  export { assertHostsStopped, createProcessFence, listSetupProcesses, ProcessFenceViolationError, ProcessInspectionError, type ProcessInspectionStep, } from './process-fence.js';
4
4
  export { type PlannedWrite, planOpenCodeRegistration, registerOpenCode, registerPi, updatePluginConfig, } from './register.js';
5
- export type { CommandResult, CommandRunner, HostDetection, OpenCodeGeneration, ProcessFence, SetupDetection, SetupEnvironment, SetupFileSystem, SetupHost, SetupIO, SetupPlugin, SetupResult, } from './types.js';
5
+ export type { CommandResult, CommandRunner, HostDetection, OpenCodeGeneration, ProcessFence, SetupCallbackContext, SetupDetection, SetupEnvironment, SetupFileSystem, SetupHost, SetupIO, SetupPlugin, SetupResult, } from './types.js';
@@ -31,6 +31,8 @@ export declare function listSetupProcesses(runner?: CommandRunner, options?: {
31
31
  platform?: string;
32
32
  env?: SetupEnvironment;
33
33
  onStep?: (details: ProcessInspectionStep) => void;
34
+ /** False skips the Windows PowerShell query for Node and Bun command lines. */
35
+ inspectRuntimes?: boolean;
34
36
  }): Promise<Array<{
35
37
  pid: number;
36
38
  command: string;
@@ -3,11 +3,88 @@ import { defaultCommandRunner } from './command-runner.js';
3
3
  // took less than 0.5 s. This is the product's one-shot latency budget, not a test
4
4
  // deadline: 45 s is about three times the worst measured cold start.
5
5
  const WINDOWS_CIM_TIMEOUT_MS = 45_000;
6
- const HOST_PATTERN = /(?:^|[/\\])(opencode|litecode|opencode2|pi)(?:\.(?:exe|cmd|bat|m?js))?(?=$|\s|")/i;
7
- const PI_SCRIPT_PATTERN = /(?:^|[/\\])pi-coding-agent[/\\]dist[/\\](?:(?:bundle|bun)[/\\])?cli\.m?js(?=$|\s|")/i;
6
+ const HOSTS = new Set(['opencode', 'litecode', 'opencode2', 'pi']);
7
+ const RUNTIMES = new Set(['node', 'bun']);
8
+ const PI_SCRIPT_PATTERN = /(?:^|[/\\])pi-coding-agent[/\\]dist[/\\](?:(?:bundle|bun)[/\\])?cli\.m?js$/i;
9
+ /** Splits a command line into arguments, keeping double-quoted ones whole. */
10
+ function commandArguments(command) {
11
+ return [...command.matchAll(/"([^"]*)"|(\S+)/g)].map((match) => match[1] ?? match[2] ?? '');
12
+ }
13
+ function executableName(argument) {
14
+ return (argument.split(/[/\\]/).pop() ?? '')
15
+ .toLowerCase()
16
+ .replace(/\.(?:exe|cmd|bat|m?js)$/, '');
17
+ }
18
+ // Node and Bun options whose value is the next argument, so that value is not
19
+ // mistaken for the script (`node --require ./preload.cjs …/opencode`).
20
+ const VALUE_OPTIONS = new Set([
21
+ '-r',
22
+ '--require',
23
+ '--import',
24
+ '--loader',
25
+ '--experimental-loader',
26
+ '-C',
27
+ '--conditions',
28
+ '--env-file',
29
+ '--title',
30
+ '--input-type',
31
+ '--preload',
32
+ '--cwd',
33
+ '-c',
34
+ '--config',
35
+ '--tsconfig-override',
36
+ '-d',
37
+ '--define',
38
+ '-l',
39
+ '--main-fields',
40
+ ]);
41
+ // Options that run inline code instead of a script file.
42
+ const INLINE_OPTIONS = new Set(['-e', '--eval', '-p', '--print']);
43
+ /** The script a Node or Bun runtime was started with, if any. */
44
+ function runtimeScript(runtime, args) {
45
+ for (let index = 0; index < args.length; index++) {
46
+ const argument = args[index] ?? '';
47
+ if (argument === '--')
48
+ return args[index + 1];
49
+ if (INLINE_OPTIONS.has(argument))
50
+ return undefined;
51
+ if (argument.startsWith('-')) {
52
+ if (!argument.includes('=') && VALUE_OPTIONS.has(argument))
53
+ index++;
54
+ continue;
55
+ }
56
+ // `bun run <script>` names the script after the subcommand.
57
+ if (runtime === 'bun' && argument === 'run')
58
+ continue;
59
+ return argument;
60
+ }
61
+ return undefined;
62
+ }
63
+ /**
64
+ * Names the host a process runs, judged by what it executes: the program
65
+ * itself, or the script a Node or Bun runtime was started with. Any other
66
+ * argument is ignored, so a shell whose command line merely mentions an
67
+ * `opencode` folder (`bash -c "cd …/opencode && …"`) is not a running host.
68
+ * `ps` prints arguments unquoted, so on macOS and Linux a program or script
69
+ * path containing spaces is not recognized; npm and Bun install OpenCode and Pi
70
+ * under paths without spaces.
71
+ */
8
72
  function hostName(command) {
9
- return (HOST_PATTERN.exec(command)?.[1] ??
10
- (PI_SCRIPT_PATTERN.test(command) ? 'pi' : null));
73
+ const [program, ...rest] = commandArguments(command);
74
+ if (program === undefined)
75
+ return null;
76
+ const name = executableName(program);
77
+ if (HOSTS.has(name))
78
+ return name;
79
+ if (!RUNTIMES.has(name))
80
+ return null;
81
+ const script = runtimeScript(name, rest);
82
+ if (script === undefined)
83
+ return null;
84
+ const scriptName = executableName(script);
85
+ if (HOSTS.has(scriptName))
86
+ return scriptName;
87
+ return PI_SCRIPT_PATTERN.test(script) ? 'pi' : null;
11
88
  }
12
89
  export class ProcessInspectionError extends Error {
13
90
  code = 'process-inspection-failed';
@@ -126,7 +203,7 @@ export async function listSetupProcesses(runner = defaultCommandRunner, options
126
203
  throw new ProcessInspectionError(inspection);
127
204
  // tasklist identifies native hosts, but npm Pi/OpenCode scripts appear as Node or Bun.
128
205
  const runtimes = processes.filter((entry) => entry.pid !== process.pid && /^(?:node|bun)\.exe$/i.test(entry.command));
129
- if (windows && runtimes.length) {
206
+ if (windows && runtimes.length && options.inspectRuntimes !== false) {
130
207
  const details = await inspect('CIM', 'powershell.exe', [
131
208
  '-NoProfile',
132
209
  '-NonInteractive',
@@ -164,9 +241,25 @@ export async function listSetupProcesses(runner = defaultCommandRunner, options
164
241
  }
165
242
  }
166
243
  export function createProcessFence(runner = defaultCommandRunner, options = {}) {
244
+ const isHost = (entry) => entry.pid !== process.pid && hostName(entry.command) !== null;
167
245
  return {
168
246
  async listRunningHosts(env) {
169
- return (await listSetupProcesses(runner, { ...options, env })).filter((entry) => entry.pid !== process.pid && hostName(entry.command) !== null);
247
+ return (await listSetupProcesses(runner, { ...options, env })).filter(isHost);
248
+ },
249
+ async previewRunningHosts(env) {
250
+ const processes = await listSetupProcesses(runner, {
251
+ ...options,
252
+ env,
253
+ inspectRuntimes: false,
254
+ });
255
+ const windows = (options.platform ?? process.platform) === 'win32';
256
+ return {
257
+ hosts: processes.filter(isHost),
258
+ uncheckedRuntimes: windows
259
+ ? processes.filter((entry) => entry.pid !== process.pid &&
260
+ /^(?:node|bun)\.exe$/i.test(entry.command)).length
261
+ : 0,
262
+ };
170
263
  },
171
264
  };
172
265
  }
@@ -3,6 +3,28 @@ import type { ClaustrumEnrollmentConnection, hostEnrollmentPaths } from '../clau
3
3
  export type SetupHost = 'opencode' | 'pi';
4
4
  export type OpenCodeGeneration = '1' | '2' | 'both';
5
5
  export type SetupEnvironment = Record<string, string | undefined>;
6
+ /**
7
+ * What setup decided before calling a plugin callback. The OpenCode generation
8
+ * is the one being registered, after `--opencode` or the interactive choice, so
9
+ * a plugin can sign in the way that generation expects (OpenCode 2 does not
10
+ * read OpenCode 1's login file).
11
+ */
12
+ export interface SetupCallbackContext {
13
+ opencodeGeneration: OpenCodeGeneration;
14
+ mode: 'local' | 'claustrum';
15
+ /**
16
+ * Every host this run sets up, in order, so the first `beforeSignIn` can
17
+ * check conditions across all of them (for example that their storage paths
18
+ * do not overlap) before any host is changed.
19
+ */
20
+ hosts: readonly SetupHost[];
21
+ /**
22
+ * Pi's agent folder, resolved the way Pi itself does (`PI_CODING_AGENT_DIR`,
23
+ * with `~` expanded, else `~/.pi/agent`). Pi's own `auth.json` lives here;
24
+ * use it rather than a plugin path setting, which can point elsewhere.
25
+ */
26
+ piAgentDir: string;
27
+ }
6
28
  /** Provider login, credential migration and vault activation stay in plugin callbacks. */
7
29
  export interface SetupPlugin {
8
30
  packages: {
@@ -19,10 +41,17 @@ export interface SetupPlugin {
19
41
  paths: Parameters<typeof hostEnrollmentPaths>[0];
20
42
  }>;
21
43
  };
22
- signInLocal(host: SetupHost): Promise<void>;
23
- migrate(host: SetupHost): Promise<void>;
44
+ /**
45
+ * Runs for each host on a real run after the host, mode and generation are
46
+ * chosen and before the vault ceremony or `signInLocal`, while nothing has
47
+ * changed yet. Rejecting stops setup for that host, so a plugin can ask for
48
+ * consent or check preconditions before any credential or authority change.
49
+ */
50
+ beforeSignIn?(host: SetupHost, context: SetupCallbackContext): Promise<void>;
51
+ signInLocal(host: SetupHost, context: SetupCallbackContext): Promise<void>;
52
+ migrate(host: SetupHost, context: SetupCallbackContext): Promise<void>;
24
53
  /** Reject mixed local/vault credentials and activate provider-specific vault access before registration. */
25
- beforeRegister?(host: SetupHost, mode: 'local' | 'claustrum'): Promise<void>;
54
+ beforeRegister?(host: SetupHost, mode: 'local' | 'claustrum', context: SetupCallbackContext): Promise<void>;
26
55
  }
27
56
  export interface CommandResult {
28
57
  exitCode: number;
@@ -52,6 +81,20 @@ export interface ProcessFence {
52
81
  pid: number;
53
82
  command: string;
54
83
  }>>;
84
+ /**
85
+ * For a dry run, which must change nothing: the hosts found without starting
86
+ * any program that writes files. On Windows that skips the PowerShell query
87
+ * for Node and Bun command lines (PowerShell writes a startup cache into the
88
+ * user's profile), so Node or Bun processes are only counted. A fence without
89
+ * it is previewed with `listRunningHosts`.
90
+ */
91
+ previewRunningHosts?(env?: SetupEnvironment): Promise<{
92
+ hosts: Array<{
93
+ pid: number;
94
+ command: string;
95
+ }>;
96
+ uncheckedRuntimes: number;
97
+ }>;
55
98
  }
56
99
  /** Defaults use the process terminal and environment; overrides are test seams. */
57
100
  export interface SetupIO {
@@ -49,6 +49,8 @@ export type StoredCredential = (OAuthCredential & {
49
49
  /** Quota codec supplied by `/quota`: the store never interprets the map itself. */
50
50
  export interface QuotaCodec {
51
51
  validate(value: unknown): boolean;
52
+ /** Normalize persisted quota before validation, when the codec supports it. */
53
+ decode?(value: unknown): unknown;
52
54
  merge(stored: unknown | undefined, observation: unknown): unknown;
53
55
  }
54
56
  /**
@@ -420,7 +420,8 @@ function parseEntry(raw, codec) {
420
420
  return undefined;
421
421
  if ('disabledReason' in raw && typeof raw.disabledReason !== 'string')
422
422
  return undefined;
423
- if ('quota' in raw && !codec.validate(raw.quota))
423
+ const quota = 'quota' in raw && codec.decode ? codec.decode(raw.quota) : raw.quota;
424
+ if ('quota' in raw && !codec.validate(quota))
424
425
  return undefined;
425
426
  if ('staged' in raw && !parseReservation(raw.staged))
426
427
  return undefined;
@@ -430,7 +431,7 @@ function parseEntry(raw, codec) {
430
431
  ...(typeof raw.disabledReason === 'string'
431
432
  ? { disabledReason: raw.disabledReason }
432
433
  : {}),
433
- ...('quota' in raw ? { quota: raw.quota } : {}),
434
+ ...('quota' in raw ? { quota } : {}),
434
435
  };
435
436
  }
436
437
  function credentialFor(raw, stateEntry) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cortexkit/common-auth",
3
- "version": "0.16.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": {