@cortexkit/common-auth 0.17.2 → 0.19.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.
@@ -1,7 +1,7 @@
1
1
  import type { ClaustrumReporterSource } from '@cortexkit/claustrum-client';
2
2
  import type { QuotaObservation } from '../quota/index.js';
3
3
  import type { RoutingRow } from '../routing/index.js';
4
- import { type ClaustrumFamily, type ClaustrumScopedAttempt, type ClaustrumScopedClient, type IdentityParser } from './custody.js';
4
+ import { type ClaustrumFamily, type ClaustrumScopedAttempt, type ClaustrumScopedClient, type IdentityParser, type VaultGrantReach } from './custody.js';
5
5
  import { type ClaustrumLogger } from './errors.js';
6
6
  import { type InsulaQuotaOptions } from './insula.js';
7
7
  import { type AccountMapper, type QuotaReceipt, type VaultRosterFile } from './roster.js';
@@ -71,6 +71,16 @@ export declare class ClaustrumConsumer<Q = QuotaObservation> {
71
71
  constructor(options: ClaustrumConsumerOptions<Q>);
72
72
  /** The last committed roster this instance saw, without any I/O. */
73
73
  snapshot(): VaultRosterFile | undefined;
74
+ /**
75
+ * What this consumer is granted, from its latest discovery, without any I/O.
76
+ * It explains an empty roster: `grants === 0` means no grant at all, while
77
+ * `grants > 0` means a grant that reaches no credential (`tuples` names its
78
+ * selector). Undefined means unknown, never zero: the vault or client is too
79
+ * old to send it, nothing was discovered yet, or the roster now in memory is
80
+ * a different view than the one this instance discovered (a peer process
81
+ * held the discovery lease and its newer roster was served instead).
82
+ */
83
+ grantReach(): VaultGrantReach | undefined;
74
84
  /** Rows for `/routing`, from the last committed roster. */
75
85
  routingRows(): RoutingRow[];
76
86
  refresh(): Promise<VaultRosterFile | undefined>;
@@ -21,6 +21,11 @@ export class ClaustrumConsumer {
21
21
  #connecting;
22
22
  #refreshing;
23
23
  #roster;
24
+ /**
25
+ * The grants named by this instance's latest discovery, with the view that
26
+ * discovery committed. Memory only: the roster file never carries it.
27
+ */
28
+ #grantReach;
24
29
  #timer;
25
30
  #started = false;
26
31
  #insula;
@@ -102,6 +107,21 @@ export class ClaustrumConsumer {
102
107
  snapshot() {
103
108
  return this.#roster;
104
109
  }
110
+ /**
111
+ * What this consumer is granted, from its latest discovery, without any I/O.
112
+ * It explains an empty roster: `grants === 0` means no grant at all, while
113
+ * `grants > 0` means a grant that reaches no credential (`tuples` names its
114
+ * selector). Undefined means unknown, never zero: the vault or client is too
115
+ * old to send it, nothing was discovered yet, or the roster now in memory is
116
+ * a different view than the one this instance discovered (a peer process
117
+ * held the discovery lease and its newer roster was served instead).
118
+ */
119
+ grantReach() {
120
+ const latest = this.#grantReach;
121
+ return latest && this.#roster?.view === latest.view
122
+ ? latest.reach
123
+ : undefined;
124
+ }
105
125
  /** Rows for `/routing`, from the last committed roster. */
106
126
  routingRows() {
107
127
  return vaultRoutingRows(this.#roster);
@@ -113,6 +133,7 @@ export class ClaustrumConsumer {
113
133
  this.#refreshing = (async () => {
114
134
  if (!(await this.#active())) {
115
135
  this.#roster = undefined;
136
+ this.#grantReach = undefined;
116
137
  this.#custody?.close();
117
138
  this.#custody = undefined;
118
139
  this.#insula?.release();
@@ -120,9 +141,17 @@ export class ClaustrumConsumer {
120
141
  return undefined;
121
142
  }
122
143
  const custody = await this.#getCustody();
144
+ // Capture the inventory so its grant fields can be kept beside the roster;
145
+ // the roster file itself never stores them.
146
+ let discovered;
123
147
  const roster = await refreshVaultRoster({
124
148
  path: this.#options.rosterPath,
125
- custody,
149
+ custody: {
150
+ discover: async (signal) => {
151
+ discovered = await custody.discover(signal);
152
+ return discovered;
153
+ },
154
+ },
126
155
  isActive: () => this.#active(),
127
156
  signal: this.#shutdown.signal,
128
157
  projection: () => ({
@@ -135,6 +164,13 @@ export class ClaustrumConsumer {
135
164
  this.#assertOpen();
136
165
  const changed = roster?.view !== this.#roster?.view;
137
166
  this.#roster = roster;
167
+ // Each discovery replaces the previous value, including with unknown. A
168
+ // refresh that served a peer's roster discovered nothing and leaves it;
169
+ // grantReach() hides it once the roster's view no longer matches.
170
+ if (discovered && roster?.view !== undefined)
171
+ this.#grantReach = discovered.grantReach
172
+ ? { view: roster.view, reach: discovered.grantReach }
173
+ : undefined;
138
174
  // Notify on view changes only: subscribers rewrite shared state on each
139
175
  // notification, and the poll runs every few seconds.
140
176
  if (roster && changed)
@@ -389,5 +425,6 @@ export class ClaustrumConsumer {
389
425
  this.#insula?.release();
390
426
  this.#insula = undefined;
391
427
  this.#roster = undefined;
428
+ this.#grantReach = undefined;
392
429
  }
393
430
  }
@@ -44,6 +44,30 @@ export interface SkippedVaultRecord {
44
44
  readonly credentialId?: string;
45
45
  readonly reason: SkippedVaultReason;
46
46
  }
47
+ /**
48
+ * One grant this consumer's enrollment holds, as the vault's list reply names
49
+ * it: for example `{ selectorKind: 'category', selector: 'openai-native',
50
+ * operation: 'read' }`. `selectorKind` is `exact` (the selector is a credential
51
+ * id) or `category` (a bare category name); both open strings.
52
+ */
53
+ export interface VaultGrantTuple {
54
+ readonly selectorKind: string;
55
+ readonly selector: string;
56
+ readonly operation: string;
57
+ }
58
+ /**
59
+ * What this consumer is granted, independent of what those grants currently
60
+ * reach. It is what tells two empty listings apart: no rows with `grants === 0`
61
+ * means no grant at all (the fix is `ck auth grant`), while no rows with
62
+ * `grants > 0` means a grant that reaches no credential, usually logins that
63
+ * lack the category (`ck auth reclassify --from-registry`); `tuples` names the
64
+ * selector that matched nothing. Never written to the roster file.
65
+ */
66
+ export interface VaultGrantReach {
67
+ /** How many grants the consumer holds, deposit grants excluded. */
68
+ readonly grants: number;
69
+ readonly tuples: readonly VaultGrantTuple[];
70
+ }
47
71
  export interface VaultInventory {
48
72
  /**
49
73
  * The vault's change cursor: a digest over exactly what this consumer can see
@@ -53,6 +77,11 @@ export interface VaultInventory {
53
77
  readonly view: string;
54
78
  readonly credentials: readonly VaultCredential[];
55
79
  readonly skipped: readonly SkippedVaultRecord[];
80
+ /**
81
+ * The consumer's grants, as the vault's list reply named them. Undefined means unknown
82
+ * (the vault or client predates the fields), never zero grants.
83
+ */
84
+ readonly grantReach?: VaultGrantReach;
56
85
  }
57
86
  export interface ClaustrumScopedIdentity {
58
87
  readonly credentialId: string;
@@ -83,6 +83,21 @@ function credentialTypeOf(row, family) {
83
83
  return row.refreshAdapter === undefined ? 'api_key' : undefined;
84
84
  return undefined;
85
85
  }
86
+ /**
87
+ * The grants named in the vault's list reply, or undefined when it names none.
88
+ * Both fields must be present: a reply carrying only one of them is treated as
89
+ * unknown rather than completed with a guess. claustrum-client already refuses
90
+ * a malformed value, so nothing here validates it again.
91
+ */
92
+ function grantReachOf(listed) {
93
+ const { grants, grantTuples } = listed;
94
+ if (grants === undefined || grantTuples === undefined)
95
+ return undefined;
96
+ return Object.freeze({
97
+ grants,
98
+ tuples: Object.freeze(grantTuples.map(({ selectorKind, selector, operation }) => Object.freeze({ selectorKind, selector, operation }))),
99
+ });
100
+ }
86
101
  /**
87
102
  * Reads this consumer's vault credentials (list, fetch, 401 report), with the
88
103
  * enrollment token as authorization. Used by every host of a plugin. There is
@@ -217,10 +232,12 @@ export class ClaustrumScopedCustody {
217
232
  }
218
233
  for (const record of skipped)
219
234
  this.#logger.warn('skipped malformed vault record', record);
235
+ const grantReach = grantReachOf(inventory);
220
236
  return {
221
237
  view: inventory.view,
222
238
  credentials: Object.freeze(credentials),
223
239
  skipped: Object.freeze(skipped),
240
+ ...(grantReach && { grantReach }),
224
241
  };
225
242
  }
226
243
  /**
@@ -2,7 +2,7 @@ import { type ClaustrumClientOptions } from '@cortexkit/claustrum-client';
2
2
  import type { ClaustrumScopedClient } from './custody.js';
3
3
  export { ClaustrumCredentialError, type ClaustrumReporterSource, type EnrollmentTokenFile, } from '@cortexkit/claustrum-client';
4
4
  export { ClaustrumConsumer, type ClaustrumConsumerOptions, type SendOptions, } from './consumer.js';
5
- export { type AccountIdentitySource, type ClaustrumFamily, type ClaustrumScopedAttempt, type ClaustrumScopedClient, ClaustrumScopedCustody, type ClaustrumScopedIdentity, decideScopedRetryAfter401, type IdentityParser, isScopedCredentialRotation, type ScopedRetryReason, SERVING_MARGIN_MS, type SkippedVaultReason, type SkippedVaultRecord, type VaultCredential, type VaultCredentialType, type VaultInventory, } from './custody.js';
5
+ export { type AccountIdentitySource, type ClaustrumFamily, type ClaustrumScopedAttempt, type ClaustrumScopedClient, ClaustrumScopedCustody, type ClaustrumScopedIdentity, decideScopedRetryAfter401, type IdentityParser, isScopedCredentialRotation, type ScopedRetryReason, SERVING_MARGIN_MS, type SkippedVaultReason, type SkippedVaultRecord, type VaultCredential, type VaultCredentialType, type VaultGrantReach, type VaultGrantTuple, type VaultInventory, } from './custody.js';
6
6
  export { type ClaustrumEnrollmentClient, type ClaustrumEnrollmentConnection, type ClaustrumEnrollmentDisconnectResult, ClaustrumEnrollmentManager, type ClaustrumEnrollmentPaths, type ClaustrumEnrollmentResetResult, type ClaustrumEnrollmentStatus, classifyEnrollmentError, connectClaustrumEnrollmentClient, disconnectClaustrumEnrollment, type EnrollmentDisposition, enrollmentAuthority, enrollmentName, getClaustrumEnrollmentPaths, hostEnrollmentPaths, RETRYABLE_ENROLLMENT_CODES, readClaustrumEnrollmentStatus, readClaustrumEnrollmentToken, resetClaustrumEnrollmentState, TERMINAL_ENROLLMENT_CODES, } from './enrollment.js';
7
7
  export { ClaustrumConsumerError, type ClaustrumConsumerFailureKind, type ClaustrumLogger, } from './errors.js';
8
8
  export { assertHostSlotMatchesMode, assertNotCustodyPlaceholder, CUSTODY_PLACEHOLDER_PREFIX, classifyHostSlot, custodyPlaceholder, custodyPlaceholderKey, type HostSlotContent, isCustodyPlaceholder, isCustodyPlaceholderValue, } from './host-slot.js';
@@ -13,7 +13,7 @@ export interface RefreshFileLock {
13
13
  whenLost(): Promise<LockLoss>;
14
14
  hasLost(): boolean;
15
15
  }
16
- export declare function acquireRefreshFileLock(options: {
16
+ type RefreshFileLockOptions = {
17
17
  name: string;
18
18
  ttlMs: number;
19
19
  /**
@@ -22,7 +22,6 @@ export declare function acquireRefreshFileLock(options: {
22
22
  * be one host's path.
23
23
  */
24
24
  path: string;
25
- now?: () => number;
26
25
  renew?: boolean;
27
26
  renewIntervalMs?: number;
28
27
  /** Notifies a live-owner refusal without awaiting; observer failures are ignored. */
@@ -30,4 +29,11 @@ export declare function acquireRefreshFileLock(options: {
30
29
  /** Synchronous, never awaited; throws and returned promise/thenable rejections are isolated. */
31
30
  onRenewalTimer?: (event: 'scheduled' | 'cancelled') => void;
32
31
  onStep?: (step: 'stale-marker-stat' | 'stale-marker-claimed' | 'stale-lock-observed' | 'lock-read-ready' | 'lock-missing' | 'stale-lock-confirmed' | 'stale-lock-removed' | 'stale-lock-recreated' | 'eviction-marker-acquired' | 'renewal-owner-confirmed' | 'renewal-marker-unavailable' | 'renewal-write-fenced' | 'renewal-write-ready' | 'renewal-write-finished' | 'relinquish-read' | 'renewal-finished' | 'release-owner-confirmed') => void | Promise<void>;
32
+ };
33
+ /** Filesystem leases share wall time across all callers and processes. */
34
+ export declare function acquireRefreshFileLock(options: RefreshFileLockOptions): Promise<RefreshFileLock | null>;
35
+ /** @internal Clock seam for lease tests; not exported by the package's fs entry point. */
36
+ export declare function acquireRefreshFileLockWithClock(options: RefreshFileLockOptions & {
37
+ now?: () => number;
33
38
  }): Promise<RefreshFileLock | null>;
39
+ export {};
@@ -31,7 +31,12 @@ export function isLostMarkerRaceError(error) {
31
31
  return (code === 'ENOENT' ||
32
32
  (!windowsPrivateFiles && (code === 'EINVAL' || code === 'ENOTDIR')));
33
33
  }
34
- export async function acquireRefreshFileLock(options) {
34
+ /** Filesystem leases share wall time across all callers and processes. */
35
+ export function acquireRefreshFileLock(options) {
36
+ return acquireRefreshFileLockWithClock({ ...options, now: Date.now });
37
+ }
38
+ /** @internal Clock seam for lease tests; not exported by the package's fs entry point. */
39
+ export async function acquireRefreshFileLockWithClock(options) {
35
40
  const lockPath = lockPathFor(options.path, options.name);
36
41
  const legacyOwnerPath = join(lockPath, 'owner.json');
37
42
  const ownerId = randomUUID();
@@ -1,4 +1,4 @@
1
- import { rmdirSync, statSync } from 'node:fs';
1
+ import { rmdirSync, statSync, utimesSync } from 'node:fs';
2
2
  import { mkdir, rmdir, stat, utimes } from 'node:fs/promises';
3
3
  // Protocol source: proper-lockfile 4.1.2 lib/lockfile.js and lib/mtime-precision.js;
4
4
  // line-level citations and the Pi lock options are recorded in docs/sources.md.
@@ -135,7 +135,9 @@ export async function acquirePiLock(authPath, onCompromised, onRenew) {
135
135
  return;
136
136
  let observed;
137
137
  try {
138
- observed = await stat(path);
138
+ // Durable writes can occupy every async filesystem worker in fsync.
139
+ // Renew on the calling thread so their queue cannot consume the lease.
140
+ observed = statSync(path);
139
141
  }
140
142
  catch (error) {
141
143
  retry(error);
@@ -151,12 +153,14 @@ export async function acquirePiLock(authPath, onCompromised, onRenew) {
151
153
  }
152
154
  const next = new Date(precision === 's' ? Math.ceil(Date.now() / 1_000) * 1_000 : Date.now());
153
155
  try {
154
- await utimes(path, next, next);
156
+ utimesSync(path, next, next);
155
157
  }
156
158
  catch (error) {
157
159
  retry(error);
158
160
  return;
159
161
  }
162
+ // A metadata syscall can itself stall; never confirm an expired lease.
163
+ assertFresh();
160
164
  if (released)
161
165
  return;
162
166
  mtime = next.getTime();
@@ -11,8 +11,11 @@ export declare const NO_LIMITS_REPORTED = "no limits reported";
11
11
  /**
12
12
  * `compact` fits a footer or a sidebar row: each window's figure, the credit
13
13
  * budget and the stale marker, without reset times. `full` adds each reset.
14
+ * `narrow` fits one line per account in a narrow sidebar: `5h 92% · 7d 66%
15
+ * · Fa 98% left`, the account-wide windows plus at most one model-scoped
16
+ * window or the budget (as `cr`), and no stale marker (see `isQuotaStale`).
14
17
  */
15
- export type QuotaTextForm = 'compact' | 'full';
18
+ export type QuotaTextForm = 'compact' | 'full' | 'narrow';
16
19
  export interface QuotaTextOptions {
17
20
  /** The current time in ms, for reset countdowns and the stale marker. */
18
21
  now: number;
@@ -55,17 +58,25 @@ export declare function quotaWindowName(limit: Pick<ProjectedLimit, 'scope' | 'l
55
58
  * and the optional age keep the shared formatter's wording.
56
59
  */
57
60
  export declare function quotaWindowParts(quota: ProjectedQuota | undefined, options: QuotaTextOptions): QuotaParts;
61
+ /**
62
+ * Whether the reading is stale: true exactly when the compact and full forms
63
+ * would end with `checked … ago`. The narrow form leaves that age out to stay
64
+ * short, so a caller drawing a narrow line uses this to dim it instead.
65
+ */
66
+ export declare function isQuotaStale(quota: ProjectedQuota | undefined, options: QuotaTextOptions): boolean;
58
67
  /**
59
68
  * The pieces of a quota text, in order: one per reported window
60
69
  * (`5h 58% left, resets 2h`), then the credit budget when there is one, then
61
70
  * `checked 3h ago` when the oldest piece shown is stale. Empty when nothing
62
71
  * was reported; `formatQuota` turns that into a sentence. A caller printing
63
- * one line per window (the terminal auth menu) uses these directly.
72
+ * one line per window (the terminal auth menu) uses these directly. In the
73
+ * narrow form the pieces are the narrow line's (`5h 92%`, `7d 66% left`).
64
74
  */
65
75
  export declare function quotaTextParts(quota: ProjectedQuota | undefined, options: QuotaTextOptions): string[];
66
76
  /**
67
77
  * A row's quota as one line: `5h 58% left · 7d 90% left` in the compact
68
- * form, with `, resets 2h` after each window in the full form. With nothing
78
+ * form, with `, resets 2h` after each window in the full form, and
79
+ * `5h 58% · 7d 90% left` in the narrow form. With nothing
69
80
  * reported it is `NO_QUOTA_READING`, or `NO_LIMITS_REPORTED` when the
70
81
  * provider answered without a limit for any window.
71
82
  */
@@ -63,8 +63,12 @@ export function quotaWindowName(limit) {
63
63
  function clampPercent(remaining) {
64
64
  return Math.min(100, Math.max(0, remaining));
65
65
  }
66
+ /** A remaining percentage as the whole number every form shows. */
67
+ function wholePercent(remaining) {
68
+ return Math.round(clampPercent(remaining));
69
+ }
66
70
  function percentLeft(remaining) {
67
- return `${Math.round(clampPercent(remaining))}% left`;
71
+ return `${wholePercent(remaining)}% left`;
68
72
  }
69
73
  function resetDetails(resetsAt, checkedAt, now) {
70
74
  const at = resetsAt === undefined ? Number.NaN : Date.parse(resetsAt);
@@ -98,6 +102,16 @@ function displayOrder(left, right) {
98
102
  * and the optional age keep the shared formatter's wording.
99
103
  */
100
104
  export function quotaWindowParts(quota, options) {
105
+ const { windows, age } = scopedWindowParts(quota, options);
106
+ const parts = windows.map(({ part }) => part);
107
+ return age === undefined ? { windows: parts } : { windows: parts, age };
108
+ }
109
+ /**
110
+ * `quotaWindowParts` with each window's scope kept beside it. The narrow form
111
+ * needs the scope to name and pick model-scoped windows; the public parts do
112
+ * not carry it, so their shape stays as it was.
113
+ */
114
+ function scopedWindowParts(quota, options) {
101
115
  if (!quota)
102
116
  return { windows: [] };
103
117
  const { now } = options;
@@ -107,12 +121,15 @@ export function quotaWindowParts(quota, options) {
107
121
  const windows = readings.map((limit) => {
108
122
  const remainingPercent = clampPercent(limit.remainingPercent ?? 0);
109
123
  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),
124
+ scope: limit.scope,
125
+ part: {
126
+ kind: 'window',
127
+ name: quotaWindowName(limit),
128
+ figure: percentLeft(limit.remainingPercent ?? 0),
129
+ remainingPercent,
130
+ checkedAt: limit.checkedAt,
131
+ ...resetDetails(limit.resetsAt, limit.checkedAt, now),
132
+ },
116
133
  };
117
134
  });
118
135
  const budget = quota.budget;
@@ -124,32 +141,131 @@ export function quotaWindowParts(quota, options) {
124
141
  ? `credits ${percentLeft(remainingPercent)}`
125
142
  : 'credits available';
126
143
  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),
144
+ scope: ALL_SCOPE,
145
+ spent: budget.reached,
146
+ part: {
147
+ kind: 'budget',
148
+ name: 'credits',
149
+ figure,
150
+ ...(remainingPercent === undefined
151
+ ? {}
152
+ : { remainingPercent: clampPercent(remainingPercent) }),
153
+ checkedAt: budget.checkedAt,
154
+ ...resetDetails(budget.resetsAt, budget.checkedAt, now),
155
+ },
135
156
  });
136
157
  }
137
158
  if (windows.length > 0) {
138
- const age = now - Math.min(...windows.map((part) => part.checkedAt));
159
+ const age = now - Math.min(...windows.map(({ part }) => part.checkedAt));
139
160
  if (age > (options.staleAfterMs ?? QUOTA_STALE_AFTER_MS)) {
140
161
  return { windows, age: `checked ${shortSpan(age)} ago` };
141
162
  }
142
163
  }
143
164
  return { windows };
144
165
  }
166
+ /**
167
+ * Whether the reading is stale: true exactly when the compact and full forms
168
+ * would end with `checked … ago`. The narrow form leaves that age out to stay
169
+ * short, so a caller drawing a narrow line uses this to dim it instead.
170
+ */
171
+ export function isQuotaStale(quota, options) {
172
+ return scopedWindowParts(quota, options).age !== undefined;
173
+ }
174
+ /**
175
+ * The model a scope names, as a display name: any namespace before a colon
176
+ * is dropped (`model:claude-opus-4` → `claude-opus-4`) and the first letter is
177
+ * capitalized (`fable` → `Fable`); the rest stays as written.
178
+ */
179
+ function scopeDisplayName(scope) {
180
+ const model = scope.slice(scope.indexOf(':') + 1);
181
+ return model.charAt(0).toUpperCase() + model.slice(1);
182
+ }
183
+ /**
184
+ * Short names for the model scopes in one row: the first two letters of each
185
+ * display name. Names that would read the same for different models are each
186
+ * extended one letter at a time until they differ (`Fable` and `Fabric` read
187
+ * `Fabl` and `Fabr`); a name that runs out of letters stays whole.
188
+ */
189
+ function scopeAbbreviations(scopes) {
190
+ const names = [...new Set(scopes.map(scopeDisplayName))];
191
+ const lengths = new Map(names.map((name) => [name, 2]));
192
+ const short = (name) => name.slice(0, lengths.get(name));
193
+ for (;;) {
194
+ const byShort = new Map();
195
+ for (const name of names) {
196
+ byShort.set(short(name), [...(byShort.get(short(name)) ?? []), name]);
197
+ }
198
+ let extended = false;
199
+ for (const group of byShort.values()) {
200
+ if (group.length < 2)
201
+ continue;
202
+ for (const name of group) {
203
+ const length = lengths.get(name) ?? 2;
204
+ if (length < name.length) {
205
+ lengths.set(name, length + 1);
206
+ extended = true;
207
+ }
208
+ }
209
+ }
210
+ if (!extended)
211
+ break;
212
+ }
213
+ return new Map(scopes.map((scope) => [scope, short(scopeDisplayName(scope))]));
214
+ }
215
+ /**
216
+ * The narrow form's pieces: every account-wide window as `5h 92%`, then at
217
+ * most one more item, with ` left` added once to the last piece. That item is
218
+ * the tightest (least remaining) of the model-scoped windows and the credit
219
+ * budget, so the line stays bounded whatever the account carries: a scoped
220
+ * window reads under its short model name (`Fa 98%`), the budget as `cr 75%`
221
+ * (`cr 0%` when spent). On a tie a scoped window wins over the budget, and
222
+ * among scoped windows the first in display order wins. The choice depends
223
+ * only on the reading, never on a width. A budget without a percentage cannot
224
+ * be chosen; when nothing at all is shown it keeps its compact wording
225
+ * (`credits available`). No age is added; `isQuotaStale` says whether the
226
+ * reading is stale. A window whose reset arrived after the reading keeps its
227
+ * figure, as in the other forms.
228
+ */
229
+ function narrowTextParts(quota, options) {
230
+ const { windows } = scopedWindowParts(quota, options);
231
+ const general = windows.filter(({ part, scope }) => part.kind === 'window' && scope === ALL_SCOPE);
232
+ const scoped = windows.filter(({ part, scope }) => part.kind === 'window' && scope !== ALL_SCOPE);
233
+ const abbreviations = scopeAbbreviations(scoped.map(({ scope }) => scope));
234
+ // The items competing for the one slot after the account-wide windows, in
235
+ // tie-break order: scoped windows in display order, then the budget. A
236
+ // spent budget counts as 0% left; one without a percentage cannot compete.
237
+ const budget = windows.find(({ part }) => part.kind === 'budget');
238
+ const budgetLeft = budget?.spent ? 0 : budget?.part.remainingPercent;
239
+ const extras = [
240
+ ...scoped.map(({ scope, part }) => ({
241
+ label: abbreviations.get(scope) ?? scope,
242
+ remaining: part.remainingPercent ?? 0,
243
+ })),
244
+ ...(budgetLeft === undefined
245
+ ? []
246
+ : [{ label: 'cr', remaining: budgetLeft }]),
247
+ ];
248
+ // Strictly lower wins, so on a tie the earlier item keeps the slot.
249
+ const tightest = extras.reduce((best, item) => best === undefined || item.remaining < best.remaining ? item : best, undefined);
250
+ const pieces = general.map(({ part }) => `${part.name} ${wholePercent(part.remainingPercent ?? 0)}%`);
251
+ if (tightest) {
252
+ pieces.push(`${tightest.label} ${wholePercent(tightest.remaining)}%`);
253
+ }
254
+ if (pieces.length === 0)
255
+ return windows.map(({ part }) => part.figure);
256
+ return pieces.map((piece, index) => index === pieces.length - 1 ? `${piece} left` : piece);
257
+ }
145
258
  /**
146
259
  * The pieces of a quota text, in order: one per reported window
147
260
  * (`5h 58% left, resets 2h`), then the credit budget when there is one, then
148
261
  * `checked 3h ago` when the oldest piece shown is stale. Empty when nothing
149
262
  * was reported; `formatQuota` turns that into a sentence. A caller printing
150
- * one line per window (the terminal auth menu) uses these directly.
263
+ * one line per window (the terminal auth menu) uses these directly. In the
264
+ * narrow form the pieces are the narrow line's (`5h 92%`, `7d 66% left`).
151
265
  */
152
266
  export function quotaTextParts(quota, options) {
267
+ if (options.form === 'narrow')
268
+ return narrowTextParts(quota, options);
153
269
  const parts = quotaWindowParts(quota, options);
154
270
  const full = (options.form ?? 'full') === 'full';
155
271
  const text = parts.windows.map((part) => {
@@ -160,7 +276,8 @@ export function quotaTextParts(quota, options) {
160
276
  }
161
277
  /**
162
278
  * A row's quota as one line: `5h 58% left · 7d 90% left` in the compact
163
- * form, with `, resets 2h` after each window in the full form. With nothing
279
+ * form, with `, resets 2h` after each window in the full form, and
280
+ * `5h 58% · 7d 90% left` in the narrow form. With nothing
164
281
  * reported it is `NO_QUOTA_READING`, or `NO_LIMITS_REPORTED` when the
165
282
  * provider answered without a limit for any window.
166
283
  */
@@ -1,7 +1,7 @@
1
1
  export type { QuotaCodec } from './codec.js';
2
2
  export { quotaCodec } from './codec.js';
3
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';
4
+ export { formatQuota, isQuotaStale, 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, quotaWindowParts, } from './format.js';
2
+ export { formatQuota, isQuotaStale, 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';
@@ -0,0 +1,32 @@
1
+ import type { SetupHostEnrollment } from './types.js';
2
+ /**
3
+ * Keeps the Pi install refusal message stable while exposing safe process details.
4
+ * A clipped tail can start inside a credential, so discard its first line—or
5
+ * the whole tail if it has no newline—before redacting.
6
+ */
7
+ export declare class SetupCommandError extends Error {
8
+ readonly step = "pi-install";
9
+ readonly exitCode: number | null;
10
+ readonly signal: string | null;
11
+ readonly stderrTail: string;
12
+ constructor(details: {
13
+ exitCode: number | null;
14
+ signal: string | null;
15
+ stderrTail: string;
16
+ stderrTruncated?: boolean;
17
+ });
18
+ }
19
+ /** The line setup prints for one host's outcome, e.g. `Pi: not connected`. */
20
+ export declare function setupEnrollmentLine({ host, outcome, }: SetupHostEnrollment): string;
21
+ /**
22
+ * Remember which hosts a failed setup left connected to the vault, against the
23
+ * thrown value. Only objects can carry a record; a thrown primitive is left as
24
+ * it is, and the printed lines are then the only report.
25
+ */
26
+ export declare function recordSetupEnrollment(failure: unknown, enrollment: readonly SetupHostEnrollment[]): void;
27
+ /**
28
+ * The per-host vault enrollment outcomes a failed `runSetup` recorded for the
29
+ * value it threw, or `undefined` when setup failed before any host's enrollment
30
+ * began, or the value is not one setup threw (or is not an object).
31
+ */
32
+ export declare function setupEnrollment(error: unknown): readonly SetupHostEnrollment[] | undefined;
@@ -0,0 +1,79 @@
1
+ import { redact } from '../logger/redact.js';
2
+ import { STDERR_TAIL_MAX_BYTES } from './command-runner.js';
3
+ const PI_INSTALL_ERROR_MESSAGE = 'Pi install failed; run pi install after checking your npm connection.';
4
+ function utf8Tail(value) {
5
+ const bytes = Buffer.from(value, 'utf8');
6
+ if (bytes.length <= STDERR_TAIL_MAX_BYTES)
7
+ return value;
8
+ let start = bytes.length - STDERR_TAIL_MAX_BYTES;
9
+ while (start < bytes.length) {
10
+ const byte = bytes[start];
11
+ if (byte === undefined || (byte & 0xc0) !== 0x80)
12
+ break;
13
+ start++;
14
+ }
15
+ return bytes.subarray(start).toString('utf8');
16
+ }
17
+ function dropPartialLine(tail) {
18
+ const newline = tail.indexOf('\n');
19
+ return newline < 0 ? '' : tail.slice(newline + 1);
20
+ }
21
+ /**
22
+ * Keeps the Pi install refusal message stable while exposing safe process details.
23
+ * A clipped tail can start inside a credential, so discard its first line—or
24
+ * the whole tail if it has no newline—before redacting.
25
+ */
26
+ export class SetupCommandError extends Error {
27
+ step = 'pi-install';
28
+ exitCode;
29
+ signal;
30
+ stderrTail;
31
+ constructor(details) {
32
+ super(PI_INSTALL_ERROR_MESSAGE);
33
+ this.name = 'SetupCommandError';
34
+ this.exitCode = details.exitCode;
35
+ this.signal = details.signal;
36
+ const tail = details.stderrTruncated
37
+ ? dropPartialLine(details.stderrTail)
38
+ : details.stderrTail;
39
+ const redacted = redact(tail);
40
+ this.stderrTail = utf8Tail(typeof redacted === 'string' ? redacted : '');
41
+ }
42
+ }
43
+ const HOST_LABELS = { opencode: 'OpenCode', pi: 'Pi' };
44
+ const OUTCOME_TEXT = {
45
+ enrolled: 'connected to the vault',
46
+ 'not-enrolled': 'not connected',
47
+ unknown: 'unknown, check with ck auth status',
48
+ };
49
+ /** The line setup prints for one host's outcome, e.g. `Pi: not connected`. */
50
+ export function setupEnrollmentLine({ host, outcome, }) {
51
+ return `${HOST_LABELS[host]}: ${OUTCOME_TEXT[outcome]}`;
52
+ }
53
+ // Outcomes recorded against the value a failed `runSetup` threw. A WeakMap
54
+ // keeps the thrown value itself untouched: setup never reads, rewrites or
55
+ // stringifies what a step or plugin callback threw, so a getter, a proxy or a
56
+ // frozen error behaves exactly as it would without setup in between, and
57
+ // callers that classify errors by message see the original text.
58
+ const recordedEnrollment = new WeakMap();
59
+ /**
60
+ * Remember which hosts a failed setup left connected to the vault, against the
61
+ * thrown value. Only objects can carry a record; a thrown primitive is left as
62
+ * it is, and the printed lines are then the only report.
63
+ */
64
+ export function recordSetupEnrollment(failure, enrollment) {
65
+ if ((typeof failure !== 'object' && typeof failure !== 'function') ||
66
+ !failure)
67
+ return;
68
+ recordedEnrollment.set(failure, Object.freeze(enrollment.map((entry) => Object.freeze({ ...entry }))));
69
+ }
70
+ /**
71
+ * The per-host vault enrollment outcomes a failed `runSetup` recorded for the
72
+ * value it threw, or `undefined` when setup failed before any host's enrollment
73
+ * began, or the value is not one setup threw (or is not an object).
74
+ */
75
+ export function setupEnrollment(error) {
76
+ if ((typeof error !== 'object' && typeof error !== 'function') || !error)
77
+ return undefined;
78
+ return recordedEnrollment.get(error);
79
+ }
@@ -1,4 +1,5 @@
1
1
  import type { CommandResult, CommandRunner, SetupEnvironment } from './types.js';
2
+ export declare const STDERR_TAIL_MAX_BYTES: number;
2
3
  export declare const defaultCommandRunner: CommandRunner;
3
4
  /** Batch launchers need cmd.exe; no free-form user text is accepted as shell arguments. */
4
5
  export declare function runResolvedCommand(runner: CommandRunner, platform: string, file: string, args: readonly string[], env: SetupEnvironment, timeoutMs?: number): Promise<CommandResult>;
@@ -1,35 +1,129 @@
1
- import { execFile } from 'node:child_process';
1
+ import { spawn } from 'node:child_process';
2
+ export const STDERR_TAIL_MAX_BYTES = 4 * 1024;
3
+ const STDOUT_MAX_BYTES = 1024 * 1024;
4
+ class ByteTail {
5
+ buffer = Buffer.alloc(STDERR_TAIL_MAX_BYTES);
6
+ start = 0;
7
+ length = 0;
8
+ truncated = false;
9
+ get didTruncate() {
10
+ return this.truncated;
11
+ }
12
+ push(chunk) {
13
+ if (chunk.length >= STDERR_TAIL_MAX_BYTES) {
14
+ if (chunk.length > STDERR_TAIL_MAX_BYTES || this.length > 0)
15
+ this.truncated = true;
16
+ chunk.copy(this.buffer, 0, chunk.length - STDERR_TAIL_MAX_BYTES);
17
+ this.start = 0;
18
+ this.length = STDERR_TAIL_MAX_BYTES;
19
+ return;
20
+ }
21
+ const overflow = Math.max(0, this.length + chunk.length - STDERR_TAIL_MAX_BYTES);
22
+ if (overflow > 0)
23
+ this.truncated = true;
24
+ this.start = (this.start + overflow) % STDERR_TAIL_MAX_BYTES;
25
+ this.length -= overflow;
26
+ const writeAt = (this.start + this.length) % STDERR_TAIL_MAX_BYTES;
27
+ const firstLength = Math.min(chunk.length, STDERR_TAIL_MAX_BYTES - writeAt);
28
+ chunk.copy(this.buffer, writeAt, 0, firstLength);
29
+ if (firstLength < chunk.length)
30
+ chunk.copy(this.buffer, 0, firstLength);
31
+ this.length += chunk.length;
32
+ }
33
+ toString() {
34
+ const bytes = Buffer.alloc(this.length);
35
+ const firstLength = Math.min(this.length, STDERR_TAIL_MAX_BYTES - this.start);
36
+ this.buffer.copy(bytes, 0, this.start, this.start + firstLength);
37
+ if (firstLength < this.length)
38
+ this.buffer.copy(bytes, firstLength, 0, this.length - firstLength);
39
+ let start = 0;
40
+ while (start < bytes.length) {
41
+ const byte = bytes[start];
42
+ if (byte === undefined || (byte & 0xc0) !== 0x80)
43
+ break;
44
+ start++;
45
+ }
46
+ return bytes.subarray(start).toString('utf8');
47
+ }
48
+ }
2
49
  export const defaultCommandRunner = {
3
50
  run(file, args, options = {}) {
4
51
  return new Promise((resolve) => {
5
52
  const started = performance.now();
6
53
  const timeoutMs = options.timeoutMs ?? 15_000;
7
- execFile(file, [...args], {
8
- env: options.env ?? process.env,
9
- timeout: timeoutMs,
10
- windowsHide: true,
11
- windowsVerbatimArguments: options.windowsVerbatimArguments,
12
- maxBuffer: 1024 * 1024,
13
- }, (error, stdout, stderr) => {
14
- const durationMs = performance.now() - started;
54
+ const stderr = new ByteTail();
55
+ const stdout = [];
56
+ let stdoutLength = 0;
57
+ let outputExceeded = false;
58
+ let spawnError = false;
59
+ let timedOut = false;
60
+ let child;
61
+ try {
62
+ child = spawn(file, [...args], {
63
+ env: options.env ?? process.env,
64
+ windowsHide: true,
65
+ windowsVerbatimArguments: options.windowsVerbatimArguments,
66
+ stdio: ['ignore', 'pipe', 'pipe'],
67
+ });
68
+ }
69
+ catch {
70
+ resolve({
71
+ exitCode: 1,
72
+ stdout: '',
73
+ stderr: '',
74
+ spawnError: true,
75
+ signal: null,
76
+ timedOut: false,
77
+ durationMs: performance.now() - started,
78
+ });
79
+ return;
80
+ }
81
+ const timer = timeoutMs > 0
82
+ ? setTimeout(() => {
83
+ timedOut = true;
84
+ child.kill('SIGTERM');
85
+ }, timeoutMs)
86
+ : undefined;
87
+ child.stdout?.on('data', (chunk) => {
88
+ const remaining = STDOUT_MAX_BYTES - stdoutLength;
89
+ const length = Math.min(remaining, chunk.length);
90
+ if (length > 0) {
91
+ stdout.push(chunk.subarray(0, length));
92
+ stdoutLength += length;
93
+ }
94
+ if (chunk.length > remaining) {
95
+ outputExceeded = true;
96
+ child.kill('SIGTERM');
97
+ }
98
+ });
99
+ child.stderr?.on('data', (chunk) => stderr.push(chunk));
100
+ let settled = false;
101
+ const settle = (code, signal) => {
102
+ if (settled)
103
+ return;
104
+ settled = true;
105
+ if (timer)
106
+ clearTimeout(timer);
15
107
  resolve({
16
- exitCode: error
17
- ? typeof error.code === 'number'
18
- ? error.code
19
- : 1
20
- : 0,
21
- stdout: String(stdout ?? ''),
22
- stderr: String(stderr ?? ''),
23
- signal: error?.signal ?? null,
24
- // Buffer-limit and spawn errors have string codes, not timeout kills.
25
- timedOut: error?.killed === true &&
26
- typeof error.code !== 'string' &&
27
- error.signal === 'SIGTERM' &&
28
- durationMs >= timeoutMs &&
29
- timeoutMs > 0,
30
- durationMs,
108
+ exitCode: spawnError ? 1 : outputExceeded ? 1 : (code ?? 1),
109
+ stdout: Buffer.concat(stdout, stdoutLength).toString('utf8'),
110
+ stderr: stderr.toString(),
111
+ stderrTruncated: stderr.didTruncate,
112
+ ...(spawnError ? { spawnError: true } : {}),
113
+ signal: signal ?? null,
114
+ timedOut,
115
+ durationMs: performance.now() - started,
31
116
  });
117
+ };
118
+ child.once('error', () => {
119
+ spawnError = true;
120
+ // A child that never started (ENOENT, EACCES) has no process for the
121
+ // timer to kill. Node documents no guarantee that 'close' follows that
122
+ // 'error', so settle here rather than wait for it.
123
+ if (child.pid === undefined)
124
+ settle(null, null);
32
125
  });
126
+ child.once('close', (code, signal) => settle(code, signal));
33
127
  });
34
128
  },
35
129
  };
@@ -1,9 +1,10 @@
1
1
  import { select } from '../auth-menu/select.js';
2
2
  import { isInteractive, printLine, processTerminal, } from '../auth-menu/terminal.js';
3
- import { hostEnrollmentPaths } from '../claustrum/enrollment.js';
3
+ import { enrollmentAuthority, hostEnrollmentPaths, } from '../claustrum/enrollment.js';
4
+ import { recordSetupEnrollment, setupEnrollmentLine } from './command-error.js';
4
5
  import { defaultCommandRunner } from './command-runner.js';
5
6
  import { detectHosts } from './detect.js';
6
- import { connectSetupHost } from './enroll.js';
7
+ import { connectSetupHost, HostNotEnrolledError } from './enroll.js';
7
8
  import { setupPaths } from './paths.js';
8
9
  import { assertHostsStopped, createProcessFence, ProcessFenceViolationError, ProcessInspectionError, } from './process-fence.js';
9
10
  import { selectSetupHosts } from './prompts.js';
@@ -52,6 +53,29 @@ function validatePlugin(plugin) {
52
53
  throw new Error('Setup requires lowercase vault names containing only letters, digits and dashes.');
53
54
  }
54
55
  }
56
+ /**
57
+ * Turn what setup recorded into one outcome per selected host, in setup order.
58
+ * A host setup never reached was never asked to enroll. Only a host whose
59
+ * enrollment was in flight when setup failed is checked on disk, by reading its
60
+ * enrollment files once with `enrollmentAuthority`; if that read fails it stays
61
+ * `unknown`.
62
+ */
63
+ async function enrollmentReport(plugin, hosts, recorded) {
64
+ const report = [];
65
+ for (const host of hosts) {
66
+ let outcome = recorded.get(host) ?? 'not-enrolled';
67
+ if (outcome === 'unknown') {
68
+ const { name, paths } = plugin.vault.hosts[host];
69
+ const authority = await enrollmentAuthority(hostEnrollmentPaths(paths), name).catch(() => 'unreadable');
70
+ if (authority === 'vault')
71
+ outcome = 'enrolled';
72
+ else if (authority === 'local')
73
+ outcome = 'not-enrolled';
74
+ }
75
+ report.push({ host, outcome });
76
+ }
77
+ return report;
78
+ }
55
79
  export async function runSetup(plugin, argv = [], io = {}) {
56
80
  const options = flags(argv);
57
81
  validatePlugin(plugin);
@@ -190,23 +214,55 @@ export async function runSetup(plugin, argv = [], io = {}) {
190
214
  hosts: Object.freeze([...hosts]),
191
215
  piAgentDir: detection.pi.directory,
192
216
  };
193
- for (const host of hosts) {
194
- await stopped();
195
- await plugin.beforeSignIn?.(host, context);
196
- await stopped();
197
- if (useVault)
198
- await connectSetupHost(plugin, host, io, terminal, stopped);
199
- else
200
- await plugin.signInLocal(host, context);
201
- await stopped();
202
- await plugin.beforeRegister?.(host, mode, context);
203
- await stopped();
204
- if (host === 'opencode')
205
- await registerOpenCode(writes, stopped);
206
- else
207
- await registerPi(plugin, detection.pi.executable, io);
208
- await stopped();
209
- await plugin.migrate(host, context);
217
+ // Each host's vault enrollment as it happens. A host the operator approved
218
+ // stays enrolled if a later step fails, so a failure reports this record.
219
+ const enrollment = new Map();
220
+ try {
221
+ for (const host of hosts) {
222
+ await stopped();
223
+ await plugin.beforeSignIn?.(host, context);
224
+ await stopped();
225
+ if (useVault) {
226
+ enrollment.set(host, 'unknown');
227
+ try {
228
+ await connectSetupHost(plugin, host, io, terminal, stopped);
229
+ }
230
+ catch (error) {
231
+ if (error instanceof HostNotEnrolledError)
232
+ enrollment.set(host, 'not-enrolled');
233
+ throw error;
234
+ }
235
+ enrollment.set(host, 'enrolled');
236
+ }
237
+ else
238
+ await plugin.signInLocal(host, context);
239
+ await stopped();
240
+ await plugin.beforeRegister?.(host, mode, context);
241
+ await stopped();
242
+ if (host === 'opencode')
243
+ await registerOpenCode(writes, stopped);
244
+ else
245
+ await registerPi(plugin, detection.pi.executable, io);
246
+ await stopped();
247
+ await plugin.migrate(host, context);
248
+ }
249
+ }
250
+ catch (error) {
251
+ // Before any enrollment began nothing is connected: nothing to report.
252
+ if (enrollment.size === 0)
253
+ throw error;
254
+ // A host the operator approved stays enrolled after a later step fails.
255
+ // Print which hosts are connected and record it for `setupEnrollment`,
256
+ // then rethrow the original value untouched. Reporting must never
257
+ // replace the failure, so its own errors are ignored.
258
+ try {
259
+ const report = await enrollmentReport(plugin, hosts, enrollment);
260
+ recordSetupEnrollment(error, report);
261
+ for (const entry of report)
262
+ printLine(terminal, setupEnrollmentLine(entry));
263
+ }
264
+ catch { }
265
+ throw error;
210
266
  }
211
267
  }
212
268
  printLine(terminal, `${options.dryRun ? 'Planned' : 'Configured'} ${plugin.displayName} for ${hosts.join(', ')} (${mode}).`);
@@ -1,4 +1,13 @@
1
1
  import { type MenuTerminal } from '../auth-menu/terminal.js';
2
2
  import type { SetupHost, SetupIO, SetupPlugin } from './types.js';
3
+ /**
4
+ * Thrown when the enrollment ended without writing the host's token: the vault
5
+ * could not be reached, it refused the request, or approval never came before
6
+ * setup stopped waiting. Setup can then report the host as not connected
7
+ * without reading its files. The message is the same one a plain error would
8
+ * carry, so the user sees no difference.
9
+ */
10
+ export declare class HostNotEnrolledError extends Error {
11
+ }
3
12
  /** Enroll an independently revocable host; plugin callbacks choose its credential store and account permissions. */
4
13
  export declare function connectSetupHost(plugin: SetupPlugin, host: SetupHost, io: SetupIO, terminal: MenuTerminal, fence: () => Promise<void>): Promise<void>;
@@ -3,6 +3,16 @@ import { writeEnrollmentTokenFile } from '@cortexkit/claustrum-client';
3
3
  import { printLine } from '../auth-menu/terminal.js';
4
4
  import { ClaustrumEnrollmentManager, connectClaustrumEnrollmentClient, hostEnrollmentPaths, } from '../claustrum/enrollment.js';
5
5
  import { ProcessFenceViolationError, ProcessInspectionError, } from './process-fence.js';
6
+ const ENROLLMENT_INCOMPLETE_MESSAGE = 'Claustrum enrollment did not complete. Inspect and approve with ck, then rerun setup.';
7
+ /**
8
+ * Thrown when the enrollment ended without writing the host's token: the vault
9
+ * could not be reached, it refused the request, or approval never came before
10
+ * setup stopped waiting. Setup can then report the host as not connected
11
+ * without reading its files. The message is the same one a plain error would
12
+ * carry, so the user sees no difference.
13
+ */
14
+ export class HostNotEnrolledError extends Error {
15
+ }
6
16
  /** Enroll an independently revocable host; plugin callbacks choose its credential store and account permissions. */
7
17
  export async function connectSetupHost(plugin, host, io, terminal, fence) {
8
18
  const { name, paths: input } = plugin.vault.hosts[host];
@@ -12,7 +22,7 @@ export async function connectSetupHost(plugin, host, io, terminal, fence) {
12
22
  connectionFile: plugin.vault.connectionFile,
13
23
  handshakeTimeoutMs: 2000,
14
24
  }).catch(() => {
15
- throw new Error('Claustrum connection failed; start ck and rerun setup.');
25
+ throw new HostNotEnrolledError('Claustrum connection failed; start ck and rerun setup.');
16
26
  });
17
27
  try {
18
28
  const manager = new ClaustrumEnrollmentManager({
@@ -42,12 +52,12 @@ export async function connectSetupHost(plugin, host, io, terminal, fence) {
42
52
  return;
43
53
  }
44
54
  if (status.state !== 'pending' && status.state !== 'busy')
45
- throw new Error('Claustrum enrollment refused; inspect its status with ck before rerunning setup.');
55
+ throw new HostNotEnrolledError('Claustrum enrollment refused; inspect its status with ck before rerunning setup.');
46
56
  if (status.state === 'pending' &&
47
57
  status.requestId &&
48
58
  status.requestId !== printedRequest) {
49
59
  if (!/^[a-zA-Z0-9_-]+$/.test(status.requestId))
50
- throw new Error('Invalid enrollment request id.');
60
+ throw new HostNotEnrolledError('Invalid enrollment request id.');
51
61
  printedRequest = status.requestId;
52
62
  printLine(terminal, 'Waiting for approval. In another terminal, run:');
53
63
  printLine(terminal, ` ck auth enroll approve --request-id ${status.requestId} --name ${name}`);
@@ -55,14 +65,16 @@ export async function connectSetupHost(plugin, host, io, terminal, fence) {
55
65
  }
56
66
  await (io.wait ?? delay)(1000);
57
67
  }
58
- throw new Error('Claustrum approval is still pending; approve with ck and rerun setup.');
68
+ throw new HostNotEnrolledError('Claustrum approval is still pending; approve with ck and rerun setup.');
59
69
  }
60
70
  catch (error) {
61
71
  if (error instanceof ProcessFenceViolationError ||
62
72
  error instanceof ProcessInspectionError)
63
73
  throw error;
64
74
  // Enrollment exceptions can carry request secrets or bearer tokens; never display them.
65
- throw new Error('Claustrum enrollment did not complete. Inspect and approve with ck, then rerun setup.');
75
+ if (error instanceof HostNotEnrolledError)
76
+ throw new HostNotEnrolledError(ENROLLMENT_INCOMPLETE_MESSAGE);
77
+ throw new Error(ENROLLMENT_INCOMPLETE_MESSAGE);
66
78
  }
67
79
  finally {
68
80
  client.close();
@@ -1,5 +1,6 @@
1
1
  export { AMBIGUOUS_OPENCODE_MESSAGE, runSetup } from './command.js';
2
+ export { SetupCommandError, setupEnrollment } from './command-error.js';
2
3
  export { detectHosts, detectOpenCodeGeneration, findExecutableOnPath, openCodeDesktopMarkers, } from './detect.js';
3
4
  export { assertHostsStopped, createProcessFence, listSetupProcesses, ProcessFenceViolationError, ProcessInspectionError, type ProcessInspectionStep, } from './process-fence.js';
4
5
  export { type PlannedWrite, planOpenCodeRegistration, registerOpenCode, registerPi, updatePluginConfig, } from './register.js';
5
- export type { CommandResult, CommandRunner, HostDetection, OpenCodeGeneration, ProcessFence, SetupCallbackContext, SetupDetection, SetupEnvironment, SetupFileSystem, SetupHost, SetupIO, SetupPlugin, SetupResult, } from './types.js';
6
+ export type { CommandResult, CommandRunner, HostDetection, OpenCodeGeneration, ProcessFence, SetupCallbackContext, SetupDetection, SetupEnrollmentOutcome, SetupEnvironment, SetupFileSystem, SetupHost, SetupHostEnrollment, SetupIO, SetupPlugin, SetupResult, } from './types.js';
@@ -1,4 +1,5 @@
1
1
  export { AMBIGUOUS_OPENCODE_MESSAGE, runSetup } from './command.js';
2
+ export { SetupCommandError, setupEnrollment } from './command-error.js';
2
3
  export { detectHosts, detectOpenCodeGeneration, findExecutableOnPath, openCodeDesktopMarkers, } from './detect.js';
3
4
  export { assertHostsStopped, createProcessFence, listSetupProcesses, ProcessFenceViolationError, ProcessInspectionError, } from './process-fence.js';
4
5
  export { planOpenCodeRegistration, registerOpenCode, registerPi, updatePluginConfig, } from './register.js';
@@ -1,4 +1,5 @@
1
1
  import { applyEdits, createScanner, findNodeAtLocation, modify, parse, parseTree, } from 'jsonc-parser';
2
+ import { SetupCommandError } from './command-error.js';
2
3
  import { defaultCommandRunner, runResolvedCommand } from './command-runner.js';
3
4
  import { writeHostConfigAtomic } from './config-write.js';
4
5
  import { defaultSetupFileSystem } from './detect.js';
@@ -125,6 +126,11 @@ export async function registerOpenCode(writes, beforeWrite) {
125
126
  export async function registerPi(plugin, executable, io = {}) {
126
127
  const { platform, env } = setupPaths(io);
127
128
  const result = await runResolvedCommand(io.runner ?? defaultCommandRunner, platform, executable, ['install', `npm:${plugin.packages.pi}@${plugin.version}`], env);
128
- if (result.exitCode !== 0)
129
- throw new Error('Pi install failed; run pi install after checking your npm connection.');
129
+ if (result.exitCode !== 0 || result.timedOut)
130
+ throw new SetupCommandError({
131
+ exitCode: result.spawnError ? null : result.exitCode,
132
+ signal: result.signal ?? null,
133
+ stderrTail: result.stderr,
134
+ stderrTruncated: result.stderrTruncated ?? false,
135
+ });
130
136
  }
@@ -3,6 +3,18 @@ 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 a setup run recorded about one host's vault enrollment when it failed:
8
+ * `enrolled` once approval landed and the token was written, `not-enrolled`
9
+ * when the host was never asked or its enrollment was refused or gave up
10
+ * waiting, and `unknown` when setup failed while the enrollment was still in
11
+ * flight and the host's token file could not settle it.
12
+ */
13
+ export type SetupEnrollmentOutcome = 'enrolled' | 'not-enrolled' | 'unknown';
14
+ export interface SetupHostEnrollment {
15
+ host: SetupHost;
16
+ outcome: SetupEnrollmentOutcome;
17
+ }
6
18
  /**
7
19
  * What setup decided before calling a plugin callback. The OpenCode generation
8
20
  * is the one being registered, after `--opencode` or the interactive choice, so
@@ -57,6 +69,8 @@ export interface CommandResult {
57
69
  exitCode: number;
58
70
  stdout: string;
59
71
  stderr: string;
72
+ spawnError?: boolean;
73
+ stderrTruncated?: boolean;
60
74
  signal?: NodeJS.Signals | null;
61
75
  timedOut?: boolean;
62
76
  durationMs?: number;
@@ -42,7 +42,7 @@ export interface OpenPoolStoreOptions {
42
42
  requireCredentialStamps?: boolean;
43
43
  /** Require an exact secret fingerprint for every roster-publication removal. */
44
44
  requireRemovedFingerprint?: boolean;
45
- /** Injected clock for leases, refresh stamps and `addedAt`. */
45
+ /** Logical clock for refresh stamps and `addedAt`; filesystem leases always use wall time. */
46
46
  now?: () => number;
47
47
  /**
48
48
  * Ordered store-lock list held across every read-modify-write. Defaults to
@@ -57,7 +57,6 @@ export function openPoolStore(options) {
57
57
  ],
58
58
  lockDefaults,
59
59
  lockEnv: {
60
- now: options.now ?? Date.now,
61
60
  ...(options.onLockEvent ? { onLockEvent: options.onLockEvent } : {}),
62
61
  ...(options.onLockStep ? { onLockStep: options.onLockStep } : {}),
63
62
  ...(options.onRenewalTimer
@@ -24,7 +24,6 @@ export type LockEvent = {
24
24
  path: string;
25
25
  };
26
26
  export interface LockEnvironment {
27
- now: () => number;
28
27
  onLockEvent?: (event: LockEvent) => void;
29
28
  onLockStep?: (lock: {
30
29
  name: string;
@@ -42,7 +42,6 @@ export async function acquirePoolLock(spec, defaults, env) {
42
42
  name: spec.name,
43
43
  path: spec.path,
44
44
  ttlMs: options.ttlMs,
45
- now: env.now,
46
45
  renew: options.renew,
47
46
  onContended: () => emit('contended'),
48
47
  ...(env.onRenewalTimer
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cortexkit/common-auth",
3
- "version": "0.17.2",
3
+ "version": "0.19.0",
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": {
@@ -140,7 +140,7 @@
140
140
  },
141
141
  "devDependencies": {
142
142
  "@biomejs/biome": "2.5.14",
143
- "@cortexkit/claustrum-client": "0.9.0",
143
+ "@cortexkit/claustrum-client": "0.10.0",
144
144
  "@cortexkit/subc-client": "0.16.1",
145
145
  "@earendil-works/pi-coding-agent": "1.0.4",
146
146
  "@opencode/plugin": "2.0.21",