@cortexkit/common-auth 0.12.0 → 0.14.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 +2 -2
- package/dist/auth-menu/accounts.d.ts +11 -2
- package/dist/auth-menu/accounts.js +12 -26
- package/dist/claustrum/enrollment.d.ts +26 -0
- package/dist/claustrum/enrollment.js +108 -0
- package/dist/claustrum/index.d.ts +1 -1
- package/dist/claustrum/index.js +1 -1
- package/dist/commands/builtins.js +121 -102
- package/dist/commands/model.d.ts +42 -1
- package/dist/commands/pi.d.ts +2 -1
- package/dist/commands/pi.js +40 -12
- package/dist/commands/seam.js +3 -0
- package/dist/opencode2/index.d.ts +2 -2
- package/dist/opencode2/index.js +1 -1
- package/dist/opencode2/integration.d.ts +39 -4
- package/dist/opencode2/integration.js +46 -1
- package/dist/pi-slot/index.d.ts +3 -0
- package/dist/pi-slot/index.js +2 -0
- package/dist/pi-slot/lock.d.ts +4 -0
- package/dist/pi-slot/lock.js +179 -0
- package/dist/pi-slot/slot.d.ts +49 -0
- package/dist/pi-slot/slot.js +380 -0
- package/dist/quota/format.d.ts +46 -0
- package/dist/quota/format.js +138 -0
- package/dist/quota/index.d.ts +2 -0
- package/dist/quota/index.js +1 -0
- package/package.json +7 -1
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/
|
|
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
|
|
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
|
-
/**
|
|
53
|
-
|
|
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
|
-
/**
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
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';
|
package/dist/claustrum/index.js
CHANGED
|
@@ -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
|
-
|
|
35
|
-
|
|
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
|
-
|
|
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 {
|
|
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
|
|
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
|
-
|
|
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
|
-
|
|
269
|
+
group,
|
|
270
|
+
status: formatQuota(quota, { now, form: 'compact' }),
|
|
271
|
+
detail: formatQuota(quota, { now, form: 'full' }),
|
|
278
272
|
account,
|
|
279
|
-
|
|
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
|
|
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
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
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
|
|
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
|
-
|
|
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
|
-
:
|
|
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',
|