@cortexkit/common-auth 0.12.0 → 0.13.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.
package/README.md CHANGED
@@ -11,10 +11,10 @@ Shared libraries for the CortexKit auth plugins for OpenCode and Pi: openai-auth
11
11
 
12
12
  A passing safety test proves little until it has been seen to fail. [`mutations.toml`](mutations.toml) is the checked-in catalogue: each row deliberately breaks one guard in `src/` (or a CI scan script) and names the Bun test that must fail because of it, so a guard cannot silently stop guarding. A row earns its place by guarding a silent, costly failure: lock exclusion, crash safety, credential loss or leakage, a single-use token used twice, misattributed quota, a wire contract, data loss. Style and cosmetics do not.
13
13
 
14
- The pinned [`ckdev-mutate`](https://github.com/cortexkit/commons/tree/73c7e66145e131eadffdd874c82d93548868b668/crates/cortexkit-mutate) runner replays it from a clean tree. It installs and builds first (fixtures import `dist/`), checks each named test passes, applies the break, rebuilds, requires the test to fail, and restores the source byte for byte:
14
+ The pinned [`ckdev-mutate`](https://github.com/cortexkit/commons/tree/0c99c7e16d8ae22b6e114136b6b7b68be6f1394e/crates/cortexkit-mutate) runner replays it from a clean tree. It installs and builds first (fixtures import `dist/`), checks each named test passes, applies the break, rebuilds, requires the test to fail, and restores the source byte for byte:
15
15
 
16
16
  ```sh
17
- cargo install --locked --git https://github.com/cortexkit/commons --rev 73c7e66145e131eadffdd874c82d93548868b668 cortexkit-mutate
17
+ cargo install --locked --git https://github.com/cortexkit/commons --rev 0c99c7e16d8ae22b6e114136b6b7b68be6f1394e cortexkit-mutate
18
18
  ckdev-mutate check
19
19
  ckdev-mutate run --all
20
20
  ckdev-mutate run --diff origin/main
@@ -42,6 +42,11 @@ export interface AccountMenuOptions {
42
42
  extraActions?: readonly MenuAction[];
43
43
  /** Recorded on a row the menu disables; defaults to `MENU_DISABLE_REASON`. */
44
44
  disableReason?: string;
45
+ /**
46
+ * The current time, used to count down to each quota reset and to tell
47
+ * how old a quota reading is; defaults to `Date.now`.
48
+ */
49
+ now?: () => number;
45
50
  }
46
51
  /**
47
52
  * Whether the store holds any usable credential. Meant as one half of an
@@ -49,8 +54,12 @@ export interface AccountMenuOptions {
49
54
  * no credential does not count, since it gives the menu nothing to manage.
50
55
  */
51
56
  export declare function poolHasCredential(store: PoolStore): Promise<boolean>;
52
- /** Formats a row's stored quota map as one line per window. */
53
- export declare function quotaLines(row: PoolRow): string[];
57
+ /**
58
+ * Formats a row's stored quota map as one line per window, in the shared
59
+ * quota wording (`5h 58% left, resets 2h`; see `formatQuota` in `/quota`).
60
+ * `now` is the current time in ms and defaults to the clock.
61
+ */
62
+ export declare function quotaLines(row: PoolRow, now?: number): string[];
54
63
  /** Adds an account through the plugin's login and reports what the store did. */
55
64
  export declare function addAccountAction(options: AccountMenuOptions): MenuAction;
56
65
  /**
@@ -1,4 +1,4 @@
1
- import { isQuotaMap, projectQuota } from '../quota/index.js';
1
+ import { formatQuota, isQuotaMap, projectQuota, quotaTextParts, } from '../quota/index.js';
2
2
  import { PoolOperationError, } from '../store/index.js';
3
3
  import { doctorAction } from './doctor.js';
4
4
  import { runMenuLogin } from './login.js';
@@ -74,30 +74,16 @@ function defaultAccountId(account, rows) {
74
74
  return id;
75
75
  }
76
76
  }
77
- /** Formats a row's stored quota map as one line per window. */
78
- export function quotaLines(row) {
79
- if (!isQuotaMap(row.quota))
80
- return [' no quota reading'];
81
- const projected = projectQuota(row.quota);
82
- const lines = [];
83
- for (const limit of projected.limits) {
84
- const name = limit.scope === 'all' ? limit.label : `${limit.scope}/${limit.label}`;
85
- if (limit.kind !== 'reading') {
86
- lines.push(` ${name}: no limit reported`);
87
- continue;
88
- }
89
- const resets = limit.resetsAt ? `, resets ${limit.resetsAt}` : '';
90
- lines.push(` ${name}: ${limit.remainingPercent}% left${resets}`);
91
- }
92
- if (projected.budget) {
93
- const budget = projected.budget;
94
- lines.push(budget.reached
95
- ? ' budget: reached'
96
- : budget.remainingPercent === undefined
97
- ? ' budget: available'
98
- : ` budget: ${budget.remainingPercent}% left`);
99
- }
100
- return lines.length > 0 ? lines : [' no quota reading'];
77
+ /**
78
+ * Formats a row's stored quota map as one line per window, in the shared
79
+ * quota wording (`5h 58% left, resets 2h`; see `formatQuota` in `/quota`).
80
+ * `now` is the current time in ms and defaults to the clock.
81
+ */
82
+ export function quotaLines(row, now = Date.now()) {
83
+ const projected = isQuotaMap(row.quota) ? projectQuota(row.quota) : undefined;
84
+ const parts = quotaTextParts(projected, { now, form: 'full' });
85
+ // With nothing to list, the line is the shared formatter's own sentence.
86
+ return (parts.length > 0 ? parts : [formatQuota(projected, { now })]).map((line) => ` ${line}`);
101
87
  }
102
88
  /** Adds an account through the plugin's login and reports what the store did. */
103
89
  export function addAccountAction(options) {
@@ -303,7 +289,7 @@ export function checkQuotasAction(options) {
303
289
  const error = errors.get(row.id);
304
290
  if (error)
305
291
  context.print(` quota check failed: ${error}`);
306
- for (const line of quotaLines(row))
292
+ for (const line of quotaLines(row, (options.now ?? Date.now)()))
307
293
  context.print(line);
308
294
  }
309
295
  },
@@ -102,6 +102,8 @@ export interface EnrollmentAncestorOptions {
102
102
  */
103
103
  export declare function refuseWritableAncestor(parent: string, options?: EnrollmentAncestorOptions): Promise<void>;
104
104
  export declare function readClaustrumEnrollmentStatus(paths: ClaustrumEnrollmentPaths, proposedName: string): Promise<ClaustrumEnrollmentStatus>;
105
+ /** Resolve the host's account mode from its enrollment files without writing. */
106
+ export declare function enrollmentAuthority(paths: ClaustrumEnrollmentPaths, proposedName: string): Promise<'vault' | 'local' | 'unreadable'>;
105
107
  /**
106
108
  * Read fresh bearer material for one scoped operation; never publish it.
107
109
  * Re-reading per operation is what lets an operator reissue a token on disk.
@@ -130,3 +132,27 @@ export declare class ClaustrumEnrollmentManager {
130
132
  export type ClaustrumEnrollmentResetResult = 'reset' | 'idle' | 'refused-pending' | 'refused-approved' | 'busy';
131
133
  /** Reset local terminal metadata without connecting to the credential daemon. */
132
134
  export declare function resetClaustrumEnrollmentState(paths: ClaustrumEnrollmentPaths, proposedName: string): Promise<ClaustrumEnrollmentResetResult>;
135
+ export type ClaustrumEnrollmentDisconnectResult = 'disconnected' | 'idle' | 'busy';
136
+ /**
137
+ * Disconnect this host from the vault on disk: remove its enrollment token,
138
+ * then its ceremony state, so `enrollmentAuthority` reports `local` again.
139
+ * This is the disconnect every plugin uses. Removing only the token is not
140
+ * enough: an approved state without a token is still vault mode and refuses,
141
+ * by design. It never contacts the credential daemon, so the enrollment stays
142
+ * approved in the vault until the operator revokes it there; a later Connect
143
+ * starts a new ceremony. A pending request is abandoned the same way.
144
+ *
145
+ * Takes the ceremony lock `reconcile()` and `resetClaustrumEnrollmentState`
146
+ * take, and returns `busy` without deleting anything while another process
147
+ * holds it. State naming another consumer refuses with `wrong-consumer` and
148
+ * both files stay. The token goes first: a crash between the two deletions
149
+ * leaves an approved state without a token, which is still vault mode (it
150
+ * refuses rather than falls back to local accounts), and calling this again
151
+ * finishes the job. Returns `idle` when neither file exists. Nothing else in
152
+ * the directory is touched. The token is removed without being parsed, so a
153
+ * corrupt token does not stand in the way. A malformed state file (bad JSON
154
+ * or wrong shape) is removed too, since it is what makes `enrollmentAuthority`
155
+ * report `unreadable`; a state file that fails the safety checks (symlink,
156
+ * wrong owner, not owner-only) refuses with `unsafe-file` and both files stay.
157
+ */
158
+ export declare function disconnectClaustrumEnrollment(paths: ClaustrumEnrollmentPaths, proposedName: string): Promise<ClaustrumEnrollmentDisconnectResult>;
@@ -377,6 +377,40 @@ export async function readClaustrumEnrollmentStatus(paths, proposedName) {
377
377
  }
378
378
  return statusFromState(state);
379
379
  }
380
+ /** Resolve the host's account mode from its enrollment files without writing. */
381
+ export async function enrollmentAuthority(paths, proposedName) {
382
+ let status;
383
+ try {
384
+ status = await readClaustrumEnrollmentStatus(paths, proposedName);
385
+ }
386
+ catch (error) {
387
+ if (!(error instanceof ClaustrumConsumerError) ||
388
+ (error.kind !== 'invalid-state' && error.kind !== 'invalid-token')) {
389
+ return 'unreadable';
390
+ }
391
+ // An approved ceremony remains vault mode even when its token is corrupt.
392
+ // Re-read the state so a malformed or unreadable state cannot authorize it.
393
+ try {
394
+ const stateValue = await readBoundedJson(paths.statePath);
395
+ if (stateValue === undefined)
396
+ return 'unreadable';
397
+ const state = decodeEnrollmentState(stateValue);
398
+ return state.phase === 'approved' && state.proposedName === proposedName
399
+ ? 'vault'
400
+ : 'unreadable';
401
+ }
402
+ catch {
403
+ return 'unreadable';
404
+ }
405
+ }
406
+ if ('proposedName' in status && status.proposedName !== proposedName)
407
+ return 'unreadable';
408
+ if (status.state === 'approved' ||
409
+ (status.state === 'blocked' && status.code === 'missing_token')) {
410
+ return 'vault';
411
+ }
412
+ return 'local';
413
+ }
380
414
  /**
381
415
  * Read fresh bearer material for one scoped operation; never publish it.
382
416
  * Re-reading per operation is what lets an operator reissue a token on disk.
@@ -649,3 +683,77 @@ export async function resetClaustrumEnrollmentState(paths, proposedName) {
649
683
  await lock.release();
650
684
  }
651
685
  }
686
+ /** Remove one file, reporting whether it existed; a missing file is not an error. */
687
+ async function removeIfPresent(path) {
688
+ try {
689
+ await unlink(path);
690
+ return true;
691
+ }
692
+ catch (error) {
693
+ if (error.code === 'ENOENT')
694
+ return false;
695
+ throw error;
696
+ }
697
+ }
698
+ /**
699
+ * Disconnect this host from the vault on disk: remove its enrollment token,
700
+ * then its ceremony state, so `enrollmentAuthority` reports `local` again.
701
+ * This is the disconnect every plugin uses. Removing only the token is not
702
+ * enough: an approved state without a token is still vault mode and refuses,
703
+ * by design. It never contacts the credential daemon, so the enrollment stays
704
+ * approved in the vault until the operator revokes it there; a later Connect
705
+ * starts a new ceremony. A pending request is abandoned the same way.
706
+ *
707
+ * Takes the ceremony lock `reconcile()` and `resetClaustrumEnrollmentState`
708
+ * take, and returns `busy` without deleting anything while another process
709
+ * holds it. State naming another consumer refuses with `wrong-consumer` and
710
+ * both files stay. The token goes first: a crash between the two deletions
711
+ * leaves an approved state without a token, which is still vault mode (it
712
+ * refuses rather than falls back to local accounts), and calling this again
713
+ * finishes the job. Returns `idle` when neither file exists. Nothing else in
714
+ * the directory is touched. The token is removed without being parsed, so a
715
+ * corrupt token does not stand in the way. A malformed state file (bad JSON
716
+ * or wrong shape) is removed too, since it is what makes `enrollmentAuthority`
717
+ * report `unreadable`; a state file that fails the safety checks (symlink,
718
+ * wrong owner, not owner-only) refuses with `unsafe-file` and both files stay.
719
+ */
720
+ export async function disconnectClaustrumEnrollment(paths, proposedName) {
721
+ await ensurePrivateDirectory(dirname(paths.statePath));
722
+ const lock = await acquireRefreshFileLock({
723
+ // The same lock as the ceremony, so a token written by a concurrent
724
+ // reconcile() can never land after this removes the files.
725
+ name: 'ceremony',
726
+ path: paths.statePath,
727
+ ttlMs: ENROLLMENT_LOCK_TTL_MS,
728
+ renew: true,
729
+ });
730
+ if (!lock)
731
+ return 'busy';
732
+ try {
733
+ let state;
734
+ try {
735
+ const value = await readBoundedJson(paths.statePath);
736
+ state = value === undefined ? undefined : decodeEnrollmentState(value);
737
+ }
738
+ catch (error) {
739
+ // A malformed state at this host's own path is this host's: the path is
740
+ // per host, and disconnect is the remedy for the `unreadable` authority
741
+ // it causes, so it is removed like any other state. An unsafe file
742
+ // (symlink, wrong owner, group or other bits) is not provably ours and
743
+ // still refuses; those checks run before the file is parsed.
744
+ if (!(error instanceof ClaustrumConsumerError) ||
745
+ error.kind !== 'invalid-state')
746
+ throw error;
747
+ }
748
+ if (state && state.proposedName !== proposedName)
749
+ throw wrongConsumer();
750
+ await lock.assertOwned();
751
+ const removedToken = await removeIfPresent(paths.tokenPath);
752
+ await lock.assertOwned();
753
+ const removedState = await removeIfPresent(paths.statePath);
754
+ return removedToken || removedState ? 'disconnected' : 'idle';
755
+ }
756
+ finally {
757
+ await lock.release();
758
+ }
759
+ }
@@ -3,7 +3,7 @@ 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
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';
6
- export { type ClaustrumEnrollmentClient, type ClaustrumEnrollmentConnection, ClaustrumEnrollmentManager, type ClaustrumEnrollmentPaths, type ClaustrumEnrollmentResetResult, type ClaustrumEnrollmentStatus, classifyEnrollmentError, connectClaustrumEnrollmentClient, type EnrollmentDisposition, enrollmentName, getClaustrumEnrollmentPaths, hostEnrollmentPaths, RETRYABLE_ENROLLMENT_CODES, readClaustrumEnrollmentStatus, readClaustrumEnrollmentToken, resetClaustrumEnrollmentState, TERMINAL_ENROLLMENT_CODES, } from './enrollment.js';
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';
9
9
  export { acceptAccount, type DeclinedAccount, declineAccount, isDeclined, } from './interlock.js';
@@ -7,7 +7,7 @@ import { ClaustrumClient, } from '@cortexkit/claustrum-client';
7
7
  export { ClaustrumCredentialError, } from '@cortexkit/claustrum-client';
8
8
  export { ClaustrumConsumer, } from './consumer.js';
9
9
  export { ClaustrumScopedCustody, decideScopedRetryAfter401, isScopedCredentialRotation, SERVING_MARGIN_MS, } from './custody.js';
10
- export { ClaustrumEnrollmentManager, classifyEnrollmentError, connectClaustrumEnrollmentClient, enrollmentName, getClaustrumEnrollmentPaths, hostEnrollmentPaths, RETRYABLE_ENROLLMENT_CODES, readClaustrumEnrollmentStatus, readClaustrumEnrollmentToken, resetClaustrumEnrollmentState, TERMINAL_ENROLLMENT_CODES, } from './enrollment.js';
10
+ export { ClaustrumEnrollmentManager, classifyEnrollmentError, connectClaustrumEnrollmentClient, disconnectClaustrumEnrollment, enrollmentAuthority, enrollmentName, getClaustrumEnrollmentPaths, hostEnrollmentPaths, RETRYABLE_ENROLLMENT_CODES, readClaustrumEnrollmentStatus, readClaustrumEnrollmentToken, resetClaustrumEnrollmentState, TERMINAL_ENROLLMENT_CODES, } from './enrollment.js';
11
11
  export { ClaustrumConsumerError, } from './errors.js';
12
12
  export { assertHostSlotMatchesMode, assertNotCustodyPlaceholder, CUSTODY_PLACEHOLDER_PREFIX, classifyHostSlot, custodyPlaceholder, custodyPlaceholderKey, isCustodyPlaceholder, isCustodyPlaceholderValue, } from './host-slot.js';
13
13
  export { acceptAccount, declineAccount, isDeclined, } from './interlock.js';
@@ -2,7 +2,7 @@
2
2
  // Routing and Limits. They read the pool and the plugin's settings through
3
3
  // the store and write only through store operations, so a menu action takes
4
4
  // the same locks as any other writer of those files.
5
- import { isQuotaMap, projectQuota, } from '../quota/index.js';
5
+ import { formatQuota, isQuotaMap, projectQuota, quotaWindowName, } from '../quota/index.js';
6
6
  import { DEFAULT_FORMER_MAIN_ID, orderForPlacement, resolveRoutingMode, } from '../routing/index.js';
7
7
  import { projectFailure, } from './seam.js';
8
8
  /** `disabledReason` recorded when the user disables an account from the menu. */
@@ -31,56 +31,12 @@ function rowName(row, identity) {
31
31
  function projected(row, scope) {
32
32
  return isQuotaMap(row.quota) ? projectQuota(row.quota, scope) : undefined;
33
33
  }
34
- function formatPercent(value) {
35
- return `${Math.round(value)}%`;
36
- }
37
- function formatReset(resetsAt, now) {
38
- if (resetsAt === undefined)
39
- return '';
40
- const at = Date.parse(resetsAt);
41
- if (!Number.isFinite(at))
42
- return '';
43
- const minutes = Math.max(0, Math.round((at - now) / 60_000));
44
- if (minutes < 60)
45
- return `, resets in ${minutes}m`;
46
- const hours = Math.floor(minutes / 60);
47
- if (hours < 48)
48
- return `, resets in ${hours}h ${minutes % 60}m`;
49
- return `, resets in ${Math.floor(hours / 24)}d`;
50
- }
51
- /** One line per quota window: `primary 58% left` and the credit budget. */
52
- function quotaSummary(quota) {
53
- if (!quota || (quota.limits.length === 0 && !quota.budget))
54
- return 'no quota reading yet';
55
- const parts = quota.limits.map((limit) => limit.kind === 'reading' && limit.remainingPercent !== undefined
56
- ? `${limit.label} ${formatPercent(limit.remainingPercent)} left`
57
- : `${limit.label} ${limit.kind === 'retired' ? 'retired' : 'not reported'}`);
58
- if (quota.budget)
59
- parts.push(quota.budget.reached
60
- ? 'credits spent'
61
- : quota.budget.remainingPercent !== undefined
62
- ? `credits ${formatPercent(quota.budget.remainingPercent)} left`
63
- : 'credits available');
64
- return parts.join(' · ');
65
- }
66
- function quotaFacts(quota, now) {
67
- const facts = {};
68
- for (const limit of quota?.limits ?? []) {
69
- facts[limit.label] =
70
- limit.kind === 'reading' && limit.usedPercent !== undefined
71
- ? `${formatPercent(limit.usedPercent)} used${formatReset(limit.resetsAt, now)}`
72
- : limit.kind === 'retired'
73
- ? 'retired'
74
- : 'not reported';
75
- }
76
- if (quota?.budget)
77
- facts.credits = quota.budget.reached
78
- ? `spent${formatReset(quota.budget.resetsAt, now)}`
79
- : quota.budget.remainingPercent !== undefined
80
- ? `${formatPercent(quota.budget.remainingPercent)} left`
81
- : 'available';
82
- return facts;
34
+ /** Real plurals for counts in summaries: `1 account`, `3 accounts`. */
35
+ function count(n, noun) {
36
+ return `${n} ${noun}${n === 1 ? '' : 's'}`;
83
37
  }
38
+ /** The header every section's own actions are listed under. */
39
+ const ACTIONS_GROUP = 'Actions';
84
40
  function loadProblem(load) {
85
41
  if (load.status === 'pending-migration')
86
42
  return 'The account pool has not been migrated yet.';
@@ -136,22 +92,26 @@ function accountView(row, options) {
136
92
  function accountsSection(options, snap) {
137
93
  const { store, extraLocks } = options;
138
94
  const locks = extraLocks ? { extraLocks } : {};
139
- const scope = options.quota?.scope ?? 'all';
140
95
  const ids = snap.rows.map((row) => row.id);
141
96
  const problem = loadProblem(snap.load);
142
97
  const enabledCount = snap.rows.filter((row) => row.enabled).length;
143
98
  const items = snap.rows.map((row, index) => {
144
99
  const { account, name } = accountView(row, options);
100
+ // An Accounts row shows only the credential type, identity and any
101
+ // disabled reason; the account's quota windows are shown in the Quota
102
+ // section instead, so this row fits one line.
145
103
  const detail = [
146
104
  row.type === 'api' ? 'API key' : 'OAuth',
147
- row.invalid
148
- ? 'invalid'
149
- : row.enabled
150
- ? 'enabled'
151
- : `disabled${row.disabledReason ? ` (${row.disabledReason})` : ''}`,
152
105
  ...(account.identity !== undefined ? [account.identity] : []),
153
- quotaSummary(projected(row, scope)),
106
+ ...(!row.invalid && !row.enabled && row.disabledReason
107
+ ? [`disabled: ${row.disabledReason}`]
108
+ : []),
154
109
  ].join(' · ');
110
+ const status = row.invalid
111
+ ? 'invalid'
112
+ : row.enabled
113
+ ? 'enabled'
114
+ : 'disabled';
155
115
  const actions = [];
156
116
  if (!row.invalid && row.enabled)
157
117
  actions.push({
@@ -212,7 +172,15 @@ function accountsSection(options, snap) {
212
172
  return `Removed ${name}.`;
213
173
  },
214
174
  });
215
- return { id: row.id, label: name, detail, account, actions };
175
+ return {
176
+ id: row.id,
177
+ label: name,
178
+ detail,
179
+ group: 'Accounts',
180
+ status,
181
+ account,
182
+ actions,
183
+ };
216
184
  });
217
185
  const login = options.accounts?.login;
218
186
  const actions = [];
@@ -220,6 +188,7 @@ function accountsSection(options, snap) {
220
188
  actions.push({
221
189
  id: 'add',
222
190
  label: login.label ?? 'Add account',
191
+ group: ACTIONS_GROUP,
223
192
  knobs: login.knobs ?? [],
224
193
  run: async ({ values, invocation }) => {
225
194
  const outcome = await login.run(values, invocation);
@@ -257,8 +226,8 @@ function accountsSection(options, snap) {
257
226
  ? [problem]
258
227
  : [
259
228
  snap.rows.length === 0
260
- ? 'No accounts yet.'
261
- : `${snap.rows.length} account(s), ${enabledCount} enabled.`,
229
+ ? 'No accounts yet'
230
+ : `${count(snap.rows.length, 'account')}, ${enabledCount} enabled`,
262
231
  ],
263
232
  items: problem ? [] : items,
264
233
  actions,
@@ -268,50 +237,79 @@ function accountsSection(options, snap) {
268
237
  function quotaSection(options, snap) {
269
238
  const scope = options.quota?.scope ?? 'all';
270
239
  const now = options.now();
271
- const items = snap.rows.map((row) => {
240
+ // A scoped menu names its model family in the header, since the quota
241
+ // shown is that family's view of each account.
242
+ const group = scope === 'all' ? 'Accounts' : `Accounts · ${scope}`;
243
+ // Checking quota asks the provider for a fresh reading. A plugin that
244
+ // polls its accounts itself (its own HTTP quota call) supplies
245
+ // `quota.check`; otherwise each row's reading is requested from the store,
246
+ // which runs the plugin's pull for that row. Checking one account and
247
+ // checking all use the same path.
248
+ const check = async (ids, invocation) => {
249
+ if (options.quota?.check)
250
+ await options.quota.check(ids, invocation);
251
+ else {
252
+ for (const id of ids)
253
+ options.store.requestReading(id);
254
+ await options.store.pullsSettled();
255
+ }
256
+ };
257
+ // Only a routing candidate (enabled, valid and holding a credential) is a
258
+ // row, because a row must do something when chosen and its action checks
259
+ // that account's quota. Any other account becomes a read-only line naming
260
+ // why it can't be checked (disabled, invalid, no credential), followed by
261
+ // its last stored quota reading.
262
+ const candidates = snap.rows.filter((row) => row.candidate);
263
+ const items = candidates.map((row) => {
272
264
  const { account, name } = accountView(row, options);
273
265
  const quota = projected(row, scope);
274
266
  return {
275
267
  id: row.id,
276
268
  label: name,
277
- detail: quotaSummary(quota),
269
+ group,
270
+ status: formatQuota(quota, { now, form: 'compact' }),
271
+ detail: formatQuota(quota, { now, form: 'full' }),
278
272
  account,
279
- facts: quotaFacts(quota, now),
273
+ actions: [
274
+ {
275
+ id: 'check',
276
+ label: 'Check this account',
277
+ run: async ({ invocation }) => {
278
+ await check([row.id], invocation);
279
+ return `Checked quota for ${name}.`;
280
+ },
281
+ },
282
+ ],
280
283
  };
281
284
  });
282
- const candidates = snap.rows.filter((row) => row.candidate);
285
+ const unchecked = snap.rows
286
+ .filter((row) => !row.candidate)
287
+ .map((row) => {
288
+ const { name } = accountView(row, options);
289
+ const reason = row.invalid
290
+ ? 'invalid'
291
+ : !row.enabled
292
+ ? 'disabled'
293
+ : row.credential === undefined
294
+ ? 'no credential'
295
+ : 'unavailable';
296
+ const quota = formatQuota(projected(row, scope), {
297
+ now,
298
+ form: 'compact',
299
+ });
300
+ return `${name} (${reason}): ${quota}`;
301
+ });
283
302
  const actions = [];
284
303
  if (candidates.length > 0)
285
304
  actions.push({
286
305
  id: 'check',
287
306
  label: 'Check now',
288
- knobs: [
289
- {
290
- kind: 'choice',
291
- id: 'account',
292
- label: 'Account',
293
- choices: [
294
- { value: '*', label: 'All accounts' },
295
- ...candidates.map((row) => ({
296
- value: row.id,
297
- label: accountView(row, options).name,
298
- })),
299
- ],
300
- value: '*',
301
- },
302
- ],
303
- run: async ({ values, invocation }) => {
304
- const ids = values.account === '*'
305
- ? candidates.map((row) => row.id)
306
- : [String(values.account)];
307
- if (options.quota?.check)
308
- await options.quota.check(ids, invocation);
309
- else {
310
- for (const id of ids)
311
- options.store.requestReading(id);
312
- await options.store.pullsSettled();
313
- }
314
- return `Checked quota for ${ids.length} account(s).`;
307
+ description: 'Checks every account that can be checked.',
308
+ group: ACTIONS_GROUP,
309
+ run: async ({ invocation }) => {
310
+ const ids = candidates.map((row) => row.id);
311
+ await check(ids, invocation);
312
+ return `Checked quota for ${count(ids.length, 'account')}.`;
315
313
  },
316
314
  });
317
315
  return {
@@ -319,7 +317,7 @@ function quotaSection(options, snap) {
319
317
  slot: 'quota',
320
318
  title: 'Quota',
321
319
  content: {
322
- lines: snap.rows.length === 0 ? ['No accounts yet.'] : [`Scope: ${scope}.`],
320
+ lines: snap.rows.length === 0 ? ['No accounts yet'] : unchecked,
323
321
  items,
324
322
  actions,
325
323
  },
@@ -341,15 +339,16 @@ function routingSection(options, snap) {
341
339
  const ids = snap.rows.map((row) => row.id);
342
340
  const tried = orderForPlacement(ids, resolved.placement, options.routing?.formerMainId ?? DEFAULT_FORMER_MAIN_ID);
343
341
  const label = choices.find((choice) => choice.value === current)?.label ?? current;
344
- const lines = [`Mode: ${label}.`];
342
+ const lines = [`Mode: ${label}`];
345
343
  if (ids.length > 0)
346
- lines.push(`Roster order: ${ids.join(', ')}.`);
344
+ lines.push(`Roster order: ${ids.join(', ')}`);
347
345
  if (resolved.mode === 'ordered' && tried.join() !== ids.join())
348
- lines.push(`Tried in order: ${tried.join(', ')}.`);
346
+ lines.push(`Tried in order: ${tried.join(', ')}`);
349
347
  const actions = [
350
348
  {
351
349
  id: 'mode',
352
350
  label: 'Change mode',
351
+ group: ACTIONS_GROUP,
353
352
  knobs: [
354
353
  { kind: 'choice', id: 'mode', label: 'Mode', choices, value: current },
355
354
  ],
@@ -367,6 +366,7 @@ function routingSection(options, snap) {
367
366
  actions.push({
368
367
  id: 'order',
369
368
  label: 'Set order',
369
+ group: ACTIONS_GROUP,
370
370
  knobs: [
371
371
  {
372
372
  kind: 'text',
@@ -404,6 +404,22 @@ function floorLabels(options, snap) {
404
404
  labels.push(limit.label);
405
405
  return labels.length > 0 ? labels : ['primary'];
406
406
  }
407
+ /**
408
+ * The display name for each floor. A floor is keyed by the quota window
409
+ * label the plugin stores readings under (`primary`, `five_hour`). When some
410
+ * account's stored quota reading records that window's length, the floor is
411
+ * shown under the same name `formatQuota` gives the window (`5h`, `7d`);
412
+ * otherwise under the label itself. The settings file keeps the label.
413
+ */
414
+ function floorNames(options, snap) {
415
+ const scope = options.quota?.scope ?? 'all';
416
+ const names = new Map();
417
+ for (const row of snap.rows)
418
+ for (const limit of projected(row, scope)?.limits ?? [])
419
+ if (limit.windowMinutes !== undefined && !names.has(limit.label))
420
+ names.set(limit.label, quotaWindowName(limit));
421
+ return (label) => names.get(label) ?? label;
422
+ }
407
423
  function limitsSection(options, snap) {
408
424
  const { store, extraLocks } = options;
409
425
  const locks = extraLocks ? { extraLocks } : {};
@@ -411,6 +427,8 @@ function limitsSection(options, snap) {
411
427
  const enabled = killswitch.enabled === true;
412
428
  const floors = record(killswitch.accounts);
413
429
  const labels = floorLabels(options, snap);
430
+ const nameOf = floorNames(options, snap);
431
+ const state = enabled ? 'on' : 'off';
414
432
  const items = snap.rows.map((row) => {
415
433
  const { account, name } = accountView(row, options);
416
434
  const own = record(floors[row.id]);
@@ -418,9 +436,11 @@ function limitsSection(options, snap) {
418
436
  return {
419
437
  id: row.id,
420
438
  label: name,
421
- detail: set.length === 0
439
+ group: `Floors · killswitch ${state}`,
440
+ // A floor is the least "% left" the account may fall to.
441
+ status: set.length === 0
422
442
  ? 'no floors'
423
- : `floors: ${set.map((label) => `${label} ${own[label]}%`).join(', ')}`,
443
+ : set.map((label) => `${nameOf(label)} ≥${own[label]}%`).join(' · '),
424
444
  account,
425
445
  actions: [
426
446
  {
@@ -429,7 +449,7 @@ function limitsSection(options, snap) {
429
449
  knobs: labels.map((label) => ({
430
450
  kind: 'number',
431
451
  id: label,
432
- label: `Minimum % left for ${label}`,
452
+ label: `Minimum % left for ${nameOf(label)}`,
433
453
  min: 0,
434
454
  max: 100,
435
455
  ...(typeof own[label] === 'number'
@@ -470,15 +490,14 @@ function limitsSection(options, snap) {
470
490
  slot: 'limits',
471
491
  title: 'Limits',
472
492
  content: {
473
- lines: [
474
- `Killswitch: ${enabled ? 'on' : 'off'}.`,
475
- 'With the killswitch on, an account whose quota falls below one of its floors is not used.',
476
- ],
493
+ lines: [`Killswitch ${state}`],
477
494
  items,
478
495
  actions: [
479
496
  {
480
497
  id: 'killswitch',
481
498
  label: enabled ? 'Turn killswitch off' : 'Turn killswitch on',
499
+ description: 'With the killswitch on, an account whose quota falls below one of its floors is not used.',
500
+ group: ACTIONS_GROUP,
482
501
  knobs: [
483
502
  {
484
503
  kind: 'toggle',
@@ -51,6 +51,11 @@ export interface MenuAction {
51
51
  id: string;
52
52
  label: string;
53
53
  description?: string;
54
+ /**
55
+ * The header a section-level action is listed under (`Actions`). See
56
+ * `MenuSection` for how renderers draw groups.
57
+ */
58
+ group?: string;
54
59
  knobs: MenuKnob[];
55
60
  /** Present when the action must be confirmed before it is applied. */
56
61
  confirm?: MenuConfirmation;
@@ -72,6 +77,13 @@ export interface MenuItem {
72
77
  id: string;
73
78
  label: string;
74
79
  detail?: string;
80
+ /** The header the item is listed under (`Accounts`); see `MenuSection`. */
81
+ group?: string;
82
+ /**
83
+ * A short value shown right-aligned beside the label (`enabled`,
84
+ * `5h 58% left`): an OpenCode dialog option's `footer`.
85
+ */
86
+ status?: string;
75
87
  account?: MenuAccount;
76
88
  /**
77
89
  * Extra name/value pairs a drawer may list under the item. Plugin data
@@ -80,11 +92,33 @@ export interface MenuItem {
80
92
  facts?: Record<string, unknown>;
81
93
  actions: MenuAction[];
82
94
  }
95
+ /**
96
+ * One section of the menu. How every renderer draws it:
97
+ *
98
+ * - Every option a renderer shows can be selected and does something: it is
99
+ * an item with at least one action, or a section-level action. Text that
100
+ * does nothing is never an option; it is a group header or a line.
101
+ * - `lines` are read-only text. On OpenCode they are drawn as header text
102
+ * (a `category`) above the first group; on Pi they are part of the select
103
+ * title.
104
+ * - The options are the items, then the section-level actions, in that
105
+ * order. When an option's `group` differs from the previous one's, a
106
+ * header naming the group is drawn first. A header is never selectable
107
+ * (on OpenCode it is the option's `category`).
108
+ * - An item's `status` is drawn right-aligned beside its label (on
109
+ * OpenCode, `footer`); its `detail` and an action's `description` are
110
+ * the secondary text (`description`).
111
+ *
112
+ * The built-in sections never emit an item without actions, and a plugin
113
+ * section should not either. A renderer that meets one must not offer it as
114
+ * an option: on OpenCode a `disabled` option is hidden altogether, so the
115
+ * item is written as header text instead, and Pi writes it into the title.
116
+ */
83
117
  export interface MenuSection {
84
118
  id: string;
85
119
  slot: SectionSlot;
86
120
  title: string;
87
- /** Read-only lines shown above the items. */
121
+ /** Read-only text shown above the rows; never a selectable option. */
88
122
  lines: string[];
89
123
  items: MenuItem[];
90
124
  actions: MenuAction[];
@@ -158,6 +192,8 @@ type ActionBase = {
158
192
  id: string;
159
193
  label: string;
160
194
  description?: string;
195
+ /** The header a section-level action is listed under; see `MenuSection`. */
196
+ group?: string;
161
197
  knobs?: MenuKnob[];
162
198
  run(input: ActionInput): Promise<string | ActionOutcome>;
163
199
  };
@@ -176,10 +212,15 @@ export interface ItemDefinition {
176
212
  id: string;
177
213
  label: string;
178
214
  detail?: string;
215
+ /** The header the item is listed under; see `MenuSection`. */
216
+ group?: string;
217
+ /** A short value shown right-aligned beside the label. */
218
+ status?: string;
179
219
  facts?: Record<string, unknown>;
180
220
  actions?: ActionDefinition[];
181
221
  }
182
222
  export interface SectionContent {
223
+ /** Read-only text; renderers never make a line selectable. */
183
224
  lines?: string[];
184
225
  items?: ItemDefinition[];
185
226
  actions?: ActionDefinition[];
@@ -16,7 +16,8 @@ export interface PiMenuOptions {
16
16
  /**
17
17
  * Runs one invocation of the slash command on Pi: sections, then an item or
18
18
  * a section action, then the action's inputs and confirmation; after each
19
- * apply the user is back in the same section with the refreshed menu. Backing
19
+ * apply the user is back in the same section with the refreshed menu. Each
20
+ * section's list ends with Back, which returns to the section list; backing
20
21
  * out of the section list ends the invocation.
21
22
  */
22
23
  export declare function runPiCommandMenu(menu: CommandMenu, ui: PiMenuUi, options?: PiMenuOptions): Promise<void>;
@@ -22,11 +22,35 @@ async function pick(ui, title, entries) {
22
22
  function withLines(title, lines) {
23
23
  return lines.length > 0 ? `${title}\n${lines.join('\n')}` : title;
24
24
  }
25
+ /** A row as one line of text: its label, then its status when it has one. */
26
+ function rowText(item) {
27
+ return item.status ? `${item.label} · ${item.status}` : item.label;
28
+ }
29
+ /**
30
+ * The read-only part of a section's select title: its lines, then each item
31
+ * that has no actions, under its group's header. Such an item does nothing
32
+ * when chosen, so it is shown as text rather than offered as an option. Pi's
33
+ * `select` cannot put text between options, so the headers of groups whose
34
+ * rows are all selectable are not shown.
35
+ */
36
+ function sectionText(section) {
37
+ const text = [...section.lines];
38
+ let header;
39
+ for (const item of section.items) {
40
+ if (item.actions.length > 0)
41
+ continue;
42
+ if (item.group !== undefined && item.group !== header)
43
+ text.push(item.group);
44
+ header = item.group;
45
+ text.push(item.group !== undefined ? ` ${rowText(item)}` : rowText(item));
46
+ }
47
+ return text;
48
+ }
25
49
  function itemTitle(item) {
26
50
  const lines = item.detail ? [item.detail] : [];
27
51
  for (const [name, value] of Object.entries(item.facts ?? {}))
28
52
  lines.push(`${name}: ${String(value)}`);
29
- return withLines(item.label, lines);
53
+ return withLines(rowText(item), lines);
30
54
  }
31
55
  /** One knob's value, or undefined when the user backed out or typed nonsense. */
32
56
  async function askKnob(ui, knob) {
@@ -94,7 +118,8 @@ async function askValues(ui, action) {
94
118
  /**
95
119
  * Runs one invocation of the slash command on Pi: sections, then an item or
96
120
  * a section action, then the action's inputs and confirmation; after each
97
- * apply the user is back in the same section with the refreshed menu. Backing
121
+ * apply the user is back in the same section with the refreshed menu. Each
122
+ * section's list ends with Back, which returns to the section list; backing
98
123
  * out of the section list ends the invocation.
99
124
  */
100
125
  export async function runPiCommandMenu(menu, ui, options = {}) {
@@ -118,9 +143,12 @@ export async function runPiCommandMenu(menu, ui, options = {}) {
118
143
  const section = model.sections.find((entry) => entry.id === chosen);
119
144
  if (!section)
120
145
  break;
146
+ // Only rows that do something are options; the rest is title text.
121
147
  const entries = [
122
- ...section.items.map((item) => ({
123
- label: item.detail ? `${item.label}: ${item.detail}` : item.label,
148
+ ...section.items
149
+ .filter((item) => item.actions.length > 0)
150
+ .map((item) => ({
151
+ label: rowText(item),
124
152
  value: { kind: 'item', item },
125
153
  })),
126
154
  ...section.actions.map((action) => ({
@@ -128,21 +156,21 @@ export async function runPiCommandMenu(menu, ui, options = {}) {
128
156
  value: { kind: 'action', action },
129
157
  })),
130
158
  ];
131
- if (entries.length === 0) {
132
- ui.notify(section.lines.join('\n') || 'Nothing to do here.');
159
+ const text = sectionText(section);
160
+ if (entries.length === 0 && text.length === 0) {
161
+ ui.notify('Nothing to do here.');
133
162
  break;
134
163
  }
135
- const choice = await pick(ui, withLines(section.title, section.lines), entries);
136
- if (!choice)
164
+ const choice = await pick(ui, withLines(section.title, text), [
165
+ ...entries,
166
+ { label: 'Back', value: { kind: 'back' } },
167
+ ]);
168
+ if (!choice || choice.kind === 'back')
137
169
  break;
138
170
  let action;
139
171
  let item;
140
172
  if (choice.kind === 'item') {
141
173
  item = choice.item;
142
- if (item.actions.length === 0) {
143
- ui.notify(itemTitle(item));
144
- continue;
145
- }
146
174
  action = await pick(ui, itemTitle(item), item.actions.map((entry) => ({ label: entry.label, value: entry })));
147
175
  if (!action)
148
176
  continue;
@@ -240,6 +240,7 @@ function projectAction(action) {
240
240
  ...(action.description !== undefined
241
241
  ? { description: action.description }
242
242
  : {}),
243
+ ...(action.group !== undefined ? { group: String(action.group) } : {}),
243
244
  knobs: (action.knobs ?? []).map(projectKnob),
244
245
  ...(confirm ? { confirm } : {}),
245
246
  };
@@ -259,6 +260,8 @@ function projectItem(item) {
259
260
  id: item.id,
260
261
  label: item.label,
261
262
  ...(item.detail !== undefined ? { detail: item.detail } : {}),
263
+ ...(item.group !== undefined ? { group: String(item.group) } : {}),
264
+ ...(item.status !== undefined ? { status: String(item.status) } : {}),
262
265
  ...(item.account ? { account: projectAccount(item.account) } : {}),
263
266
  ...(item.facts !== undefined ? { facts: item.facts } : {}),
264
267
  actions: (item.actions ?? []).map(projectAction),
@@ -1,8 +1,8 @@
1
1
  export type { OpenCode2AuthFailureKind } from './errors.js';
2
2
  export { OpenCode2AuthError } from './errors.js';
3
3
  export { ATTEMPT_HEADER, applyHeaderEdits, DEFAULT_MAX_RECORDS, installOpenCode2Auth, } from './install.js';
4
- export type { FormAnswer, PoolAuthorization, PoolLoginMethod, RegisterOpenCode2AuthMethodsOptions, } from './integration.js';
5
- export { isPlaceholderCredential, PLACEHOLDER_LIFETIME_MS, PLACEHOLDER_METADATA_KEY, PLACEHOLDER_PREFIX, placeholderCredential, placeholderSecret, registerOpenCode2AuthMethods, } from './integration.js';
4
+ export type { FormAnswer, LoginContext, PoolAuthorization, PoolLoginMethod, RegisterOpenCode2AuthMethodsOptions, VaultActivationMethod, } from './integration.js';
5
+ export { isPlaceholderCredential, PLACEHOLDER_LIFETIME_MS, PLACEHOLDER_METADATA_KEY, PLACEHOLDER_PREFIX, placeholderCredential, placeholderSecret, registerOpenCode2AuthMethods, VAULT_ACTIVATION_INSTRUCTIONS, } from './integration.js';
6
6
  export type { ServerSentEvent } from './sse.js';
7
7
  export { watchServerSentEvents } from './sse.js';
8
8
  export type { AccountHeadersResult, AccountRequest, Attempt, AttemptEndReason, AttemptOutcome, ChooseAccountInput, EventVerdict, HeaderEdits, HostError, InstallOpenCode2AuthOptions, LimitSignal, OpenCode2AuthAdapter, OpenCode2AuthEventName, OpenCode2AuthEvents, OpenCode2AuthInstallation, OpenCode2AuthLogger, OpenCode2HookContext, RequestKind, RequestScope, ResponseAccount, RetryReason, SelectingHook, Transport, } from './types.js';
@@ -1,4 +1,4 @@
1
1
  export { OpenCode2AuthError } from './errors.js';
2
2
  export { ATTEMPT_HEADER, applyHeaderEdits, DEFAULT_MAX_RECORDS, installOpenCode2Auth, } from './install.js';
3
- export { isPlaceholderCredential, PLACEHOLDER_LIFETIME_MS, PLACEHOLDER_METADATA_KEY, PLACEHOLDER_PREFIX, placeholderCredential, placeholderSecret, registerOpenCode2AuthMethods, } from './integration.js';
3
+ export { isPlaceholderCredential, PLACEHOLDER_LIFETIME_MS, PLACEHOLDER_METADATA_KEY, PLACEHOLDER_PREFIX, placeholderCredential, placeholderSecret, registerOpenCode2AuthMethods, VAULT_ACTIVATION_INSTRUCTIONS, } from './integration.js';
4
4
  export { watchServerSentEvents } from './sse.js';
@@ -47,18 +47,49 @@ export interface PoolLoginMethod<T> {
47
47
  readonly method: IntegrationOAuthMethod;
48
48
  authorize(answer: FormAnswer): Promise<PoolAuthorization<T>>;
49
49
  }
50
+ /** What `activate` and `onLogin` are told about the login they serve. */
51
+ export interface LoginContext {
52
+ readonly integrationID: string;
53
+ readonly methodID: string;
54
+ }
55
+ /**
56
+ * Shown by `opencode auth login` when the vault method starts. The host has no
57
+ * page to open for this method, so the text only says what happens instead.
58
+ */
59
+ export declare const VAULT_ACTIVATION_INSTRUCTIONS = "No browser sign-in: this connects the plugin to the accounts in its vault.";
60
+ /**
61
+ * A login method for a host whose accounts all come from a vault. Choosing it
62
+ * signs in to nothing and writes nothing to the plugin's pool: once
63
+ * `activate` resolves, the host only receives this integration's placeholder,
64
+ * which marks later requests as the plugin's to serve from the vault.
65
+ */
66
+ export interface VaultActivationMethod {
67
+ /** Must not share an ID with any of the pool login methods. */
68
+ readonly method: IntegrationOAuthMethod;
69
+ /**
70
+ * Confirms the host may use this method, normally by checking that
71
+ * `enrollmentAuthority` reports `'vault'`. Throw to refuse: the host shows
72
+ * the error's message and stores nothing, so it must be a fixed text that
73
+ * carries no credential.
74
+ */
75
+ activate(context: LoginContext): Promise<void> | void;
76
+ /** Replaces `VAULT_ACTIVATION_INSTRUCTIONS`. */
77
+ readonly instructions?: string;
78
+ }
50
79
  export interface RegisterOpenCode2AuthMethodsOptions<T> {
51
80
  readonly integrationID: string;
52
81
  readonly methods: readonly PoolLoginMethod<T>[];
82
+ /**
83
+ * Adds a login method that activates the plugin for vault accounts without
84
+ * creating a local account. Leave it out when the plugin has no vault.
85
+ */
86
+ readonly vault?: VaultActivationMethod;
53
87
  /**
54
88
  * Writes a completed login into the plugin's pool. The host only receives
55
89
  * a placeholder once this resolves; if it throws, the login fails in the
56
90
  * host and nothing is stored there.
57
91
  */
58
- onLogin(result: T, context: {
59
- readonly integrationID: string;
60
- readonly methodID: string;
61
- }): Promise<void> | void;
92
+ onLogin(result: T, context: LoginContext): Promise<void> | void;
62
93
  /** Label the host shows for its (placeholder) connection. */
63
94
  readonly label?: string;
64
95
  readonly now?: () => number;
@@ -67,6 +98,10 @@ export interface RegisterOpenCode2AuthMethodsOptions<T> {
67
98
  * Registers the plugin's own login methods with the host so that a login lands
68
99
  * in the plugin's pool and the host keeps only a placeholder credential.
69
100
  *
101
+ * With `vault`, one more method lets a host whose accounts all live in a vault
102
+ * activate the plugin: it calls `activate`, writes nothing to the pool and
103
+ * hands the host the same placeholder under its own method ID.
104
+ *
70
105
  * Host-driven refresh never reaches the pool: it renews only this integration's
71
106
  * placeholder and refuses every other credential without replacing it. Plugins
72
107
  * must register under their own method IDs; a plugin importing an existing
@@ -38,10 +38,19 @@ export function isPlaceholderCredential(value, integrationID) {
38
38
  : secret === expected;
39
39
  return matches(value.access) && matches(value.refresh);
40
40
  }
41
+ /**
42
+ * Shown by `opencode auth login` when the vault method starts. The host has no
43
+ * page to open for this method, so the text only says what happens instead.
44
+ */
45
+ export const VAULT_ACTIVATION_INSTRUCTIONS = 'No browser sign-in: this connects the plugin to the accounts in its vault.';
41
46
  /**
42
47
  * Registers the plugin's own login methods with the host so that a login lands
43
48
  * in the plugin's pool and the host keeps only a placeholder credential.
44
49
  *
50
+ * With `vault`, one more method lets a host whose accounts all live in a vault
51
+ * activate the plugin: it calls `activate`, writes nothing to the pool and
52
+ * hands the host the same placeholder under its own method ID.
53
+ *
45
54
  * Host-driven refresh never reaches the pool: it renews only this integration's
46
55
  * placeholder and refuses every other credential without replacing it. Plugins
47
56
  * must register under their own method IDs; a plugin importing an existing
@@ -80,6 +89,7 @@ export async function registerOpenCode2AuthMethods(ctx, options) {
80
89
  };
81
90
  };
82
91
  return ctx.integration.transform((editor) => {
92
+ const label = options.label === undefined ? {} : { label: () => options.label };
83
93
  for (const login of options.methods) {
84
94
  editor.method.update({
85
95
  integrationID,
@@ -91,8 +101,43 @@ export async function registerOpenCode2AuthMethods(ctx, options) {
91
101
  }
92
102
  return placeholderFor(credential.methodID);
93
103
  },
94
- ...(options.label === undefined ? {} : { label: () => options.label }),
104
+ ...label,
95
105
  });
96
106
  }
107
+ const vault = options.vault;
108
+ if (vault === undefined)
109
+ return;
110
+ const methodID = vault.method.id;
111
+ editor.method.update({
112
+ integrationID,
113
+ method: vault.method,
114
+ // OpenCode 2 has no login method kind that needs no user step: OAuth
115
+ // expects a page, a key method a typed secret, a command method a
116
+ // program. An automatic OAuth authorization with an empty `url` fits:
117
+ // on 2.0.22 the CLI's and the TUI's browser openers refuse anything but
118
+ // an http(s) URL, and the host stores what `callback` resolves to as
119
+ // soon as it settles, so the login completes with no browser.
120
+ authorize: async () => ({
121
+ url: '',
122
+ instructions: vault.instructions ?? VAULT_ACTIVATION_INSTRUCTIONS,
123
+ mode: 'auto',
124
+ // Activation runs in the callback, not before returning, so a refusal
125
+ // marks the host's login attempt failed with the plugin's own message,
126
+ // which the host shows as is.
127
+ callback: Promise.resolve()
128
+ .then(() => vault.activate({ integrationID, methodID }))
129
+ .then(() => placeholderFor(methodID)),
130
+ }),
131
+ // Nothing to renew in the vault: only this method's own placeholder is
132
+ // reissued, and anything else must be signed in again.
133
+ refresh: async (credential) => {
134
+ if (!isPlaceholderCredential(credential, integrationID) ||
135
+ credential.methodID !== methodID) {
136
+ throw new Error("This login method refreshes only its vault placeholder; choose the plugin's vault login method again.");
137
+ }
138
+ return placeholderFor(methodID);
139
+ },
140
+ ...label,
141
+ });
97
142
  });
98
143
  }
@@ -0,0 +1,46 @@
1
+ import type { ProjectedLimit, ProjectedQuota } from './projection.js';
2
+ /** A reading older than this is marked with its age. */
3
+ export declare const QUOTA_STALE_AFTER_MS: number;
4
+ /** What `formatQuota` returns when there is no reading at all. */
5
+ export declare const NO_QUOTA_READING = "no quota reading yet";
6
+ /**
7
+ * What `formatQuota` returns when the provider answered but reported no
8
+ * limit for any window (every window is an absence record or a tombstone).
9
+ */
10
+ export declare const NO_LIMITS_REPORTED = "no limits reported";
11
+ /**
12
+ * `compact` fits a footer or a sidebar row: each window's figure, the credit
13
+ * budget and the stale marker, without reset times. `full` adds each reset.
14
+ */
15
+ export type QuotaTextForm = 'compact' | 'full';
16
+ export interface QuotaTextOptions {
17
+ /** The current time in ms, for reset countdowns and the stale marker. */
18
+ now: number;
19
+ /** Defaults to `full`. */
20
+ form?: QuotaTextForm;
21
+ /** Defaults to `QUOTA_STALE_AFTER_MS`. */
22
+ staleAfterMs?: number;
23
+ }
24
+ /**
25
+ * The name a window is shown under. A general window (scope `all`) is named
26
+ * by its stored length; a model-scoped window keeps the label the plugin
27
+ * stored it under, which already names the model (`seven_day_opus`). A
28
+ * general window stored without a length (a snapshot from before lengths
29
+ * were recorded) falls back to its label.
30
+ */
31
+ export declare function quotaWindowName(limit: Pick<ProjectedLimit, 'scope' | 'label' | 'windowMinutes'>): string;
32
+ /**
33
+ * The pieces of a quota text, in order: one per reported window
34
+ * (`5h 58% left, resets 2h`), then the credit budget when there is one, then
35
+ * `checked 3h ago` when the oldest piece shown is stale. Empty when nothing
36
+ * was reported; `formatQuota` turns that into a sentence. A caller printing
37
+ * one line per window (the terminal auth menu) uses these directly.
38
+ */
39
+ export declare function quotaTextParts(quota: ProjectedQuota | undefined, options: QuotaTextOptions): string[];
40
+ /**
41
+ * A row's quota as one line: `5h 58% left · 7d 90% left` in the compact
42
+ * form, with `, resets 2h` after each window in the full form. With nothing
43
+ * reported it is `NO_QUOTA_READING`, or `NO_LIMITS_REPORTED` when the
44
+ * provider answered without a limit for any window.
45
+ */
46
+ export declare function formatQuota(quota: ProjectedQuota | undefined, options: QuotaTextOptions): string;
@@ -0,0 +1,138 @@
1
+ // The one quota wording every surface shows: the command menu's dialogs on
2
+ // OpenCode and Pi, the terminal auth menu, and the plugins' sidebars. Each of
3
+ // them calls `formatQuota` (or `quotaTextParts` for one line per window), so
4
+ // the wording cannot drift between plugins or between a dialog and a sidebar.
5
+ //
6
+ // The rules: a window is named by its length (`5h`, `7d`), or, for a window
7
+ // that binds only one model family, by the label the plugin stored it under.
8
+ // Every figure is "% left". A window the provider did not report (an absence
9
+ // record or a retirement tombstone) is left out rather than written as "not
10
+ // reported". A reset is a short time from now (`resets 2h`). A reading older
11
+ // than fifteen minutes says how old it is (`checked 3h ago`).
12
+ //
13
+ // Like the rest of this module it reads no clock: `now` is a parameter.
14
+ import { ALL_SCOPE } from './map.js';
15
+ /** A reading older than this is marked with its age. */
16
+ export const QUOTA_STALE_AFTER_MS = 15 * 60_000;
17
+ /** What `formatQuota` returns when there is no reading at all. */
18
+ export const NO_QUOTA_READING = 'no quota reading yet';
19
+ /**
20
+ * What `formatQuota` returns when the provider answered but reported no
21
+ * limit for any window (every window is an absence record or a tombstone).
22
+ */
23
+ export const NO_LIMITS_REPORTED = 'no limits reported';
24
+ /**
25
+ * A length or a time span in its largest whole-ish unit: `45m`, `5h`, `3d`.
26
+ * Spans under an hour are minutes, under a day hours, otherwise days, each
27
+ * rounded to the nearest unit and never shown as zero.
28
+ */
29
+ function shortSpan(ms) {
30
+ const minutes = Math.max(1, Math.round(ms / 60_000));
31
+ if (minutes < 60)
32
+ return `${minutes}m`;
33
+ const hours = Math.round(minutes / 60);
34
+ if (hours < 24)
35
+ return `${hours}h`;
36
+ return `${Math.max(1, Math.round(minutes / 1440))}d`;
37
+ }
38
+ /** A stored window length in minutes as its exact name: `5h`, `7d`, `90m`. */
39
+ function lengthName(minutes) {
40
+ if (minutes % 1440 === 0)
41
+ return `${minutes / 1440}d`;
42
+ if (minutes % 60 === 0)
43
+ return `${minutes / 60}h`;
44
+ return `${minutes}m`;
45
+ }
46
+ /**
47
+ * The name a window is shown under. A general window (scope `all`) is named
48
+ * by its stored length; a model-scoped window keeps the label the plugin
49
+ * stored it under, which already names the model (`seven_day_opus`). A
50
+ * general window stored without a length (a snapshot from before lengths
51
+ * were recorded) falls back to its label.
52
+ */
53
+ export function quotaWindowName(limit) {
54
+ if (limit.scope !== ALL_SCOPE || limit.windowMinutes === undefined)
55
+ return limit.label;
56
+ return lengthName(limit.windowMinutes);
57
+ }
58
+ function percentLeft(remaining) {
59
+ return `${Math.round(Math.min(100, Math.max(0, remaining)))}% left`;
60
+ }
61
+ function resetText(resetsAt, now) {
62
+ if (resetsAt === undefined)
63
+ return '';
64
+ const at = Date.parse(resetsAt);
65
+ // A reset already passed says nothing about the future; leave it out.
66
+ if (!Number.isFinite(at) || at <= now)
67
+ return '';
68
+ return `, resets ${shortSpan(at - now)}`;
69
+ }
70
+ /** Shortest window first, so `5h` reads before `7d`; unknown lengths last. */
71
+ function displayOrder(left, right) {
72
+ const l = left.windowMinutes;
73
+ const r = right.windowMinutes;
74
+ if (l !== undefined && r !== undefined && l !== r)
75
+ return l - r;
76
+ if ((l === undefined) !== (r === undefined))
77
+ return l === undefined ? 1 : -1;
78
+ if (left.scope !== right.scope) {
79
+ if (left.scope === ALL_SCOPE)
80
+ return -1;
81
+ if (right.scope === ALL_SCOPE)
82
+ return 1;
83
+ return left.scope < right.scope ? -1 : 1;
84
+ }
85
+ return left.label < right.label ? -1 : left.label > right.label ? 1 : 0;
86
+ }
87
+ /**
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.
93
+ */
94
+ export function quotaTextParts(quota, options) {
95
+ if (!quota)
96
+ return [];
97
+ const { now } = options;
98
+ const full = (options.form ?? 'full') === 'full';
99
+ const parts = [];
100
+ const times = [];
101
+ const readings = quota.limits
102
+ .filter((limit) => limit.kind === 'reading' && limit.remainingPercent !== undefined)
103
+ .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
+ }
108
+ const budget = quota.budget;
109
+ if (budget) {
110
+ times.push(budget.checkedAt);
111
+ const figure = budget.reached
112
+ ? 'credits spent'
113
+ : budget.remainingPercent !== undefined
114
+ ? `credits ${percentLeft(budget.remainingPercent)}`
115
+ : 'credits available';
116
+ parts.push(`${figure}${full ? resetText(budget.resetsAt, now) : ''}`);
117
+ }
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`);
122
+ }
123
+ return parts;
124
+ }
125
+ /**
126
+ * A row's quota as one line: `5h 58% left · 7d 90% left` in the compact
127
+ * form, with `, resets 2h` after each window in the full form. With nothing
128
+ * reported it is `NO_QUOTA_READING`, or `NO_LIMITS_REPORTED` when the
129
+ * provider answered without a limit for any window.
130
+ */
131
+ export function formatQuota(quota, options) {
132
+ const parts = quotaTextParts(quota, options);
133
+ if (parts.length > 0)
134
+ return parts.join(' · ');
135
+ return quota && quota.limits.length > 0
136
+ ? NO_LIMITS_REPORTED
137
+ : NO_QUOTA_READING;
138
+ }
@@ -1,5 +1,7 @@
1
1
  export type { QuotaCodec } from './codec.js';
2
2
  export { quotaCodec } from './codec.js';
3
+ export type { QuotaTextForm, QuotaTextOptions } from './format.js';
4
+ export { formatQuota, NO_LIMITS_REPORTED, NO_QUOTA_READING, QUOTA_STALE_AFTER_MS, quotaTextParts, quotaWindowName, } from './format.js';
3
5
  export type { CreditBudgetCleared, CreditBudgetEntry, CreditBudgetReading, QuotaAbsentEntry, QuotaEntry, QuotaMap, QuotaReadingEntry, QuotaRetiredEntry, } from './map.js';
4
6
  export { ALL_SCOPE, DEFAULT_REQUIRED_LABELS, emptyQuotaMap, isQuotaMap, } from './map.js';
5
7
  export type { ObservedBudget, ObservedPair, ObservedReading, QuotaObservation, } from './merge.js';
@@ -1,4 +1,5 @@
1
1
  export { quotaCodec } from './codec.js';
2
+ export { formatQuota, NO_LIMITS_REPORTED, NO_QUOTA_READING, QUOTA_STALE_AFTER_MS, quotaTextParts, quotaWindowName, } from './format.js';
2
3
  export { ALL_SCOPE, DEFAULT_REQUIRED_LABELS, emptyQuotaMap, isQuotaMap, } from './map.js';
3
4
  export { isQuotaObservation, mergeQuotaObservation, QuotaCodecError, } from './merge.js';
4
5
  export { budgetExhaustedResetAt, futureResetAt, projectQuota, readsExhausted, } from './projection.js';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cortexkit/common-auth",
3
- "version": "0.12.0",
3
+ "version": "0.13.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": {