@cortexkit/common-auth 0.11.8 → 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 +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 +123 -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/fs/atomic-write.d.ts +13 -0
- package/dist/fs/atomic-write.js +52 -0
- package/dist/opencode2/index.d.ts +2 -2
- package/dist/opencode2/index.js +1 -1
- package/dist/opencode2/integration.d.ts +45 -11
- package/dist/opencode2/integration.js +58 -9
- 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/dist/store/attribution.js +1 -0
- package/dist/store/errors.d.ts +2 -2
- package/dist/store/identity.js +2 -0
- package/dist/store/index.d.ts +2 -1
- package/dist/store/mutate.d.ts +22 -2
- package/dist/store/mutate.js +140 -34
- package/dist/store/pool.d.ts +9 -2
- package/dist/store/pool.js +4 -0
- package/dist/store/publication.d.ts +47 -0
- package/dist/store/publication.js +304 -0
- package/dist/store/pull.js +6 -1
- package/dist/store/refresh.js +2 -0
- package/dist/store/reserved.d.ts +3 -0
- package/dist/store/reserved.js +13 -0
- package/dist/store/rows.d.ts +62 -13
- package/dist/store/rows.js +331 -42
- package/dist/store/runtime.js +13 -1
- package/dist/store/schema.d.ts +18 -0
- package/dist/store/schema.js +58 -2
- package/dist/store/torn.js +1 -1
- package/package.json +1 -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.';
|
|
@@ -98,6 +54,8 @@ function addedText(name, result) {
|
|
|
98
54
|
return `Finished adding ${name}.`;
|
|
99
55
|
case 'rotated':
|
|
100
56
|
return `${name} was already in the pool; its credential was updated.`;
|
|
57
|
+
case 'exists':
|
|
58
|
+
return `${name} was already in the pool; its credential is unchanged.`;
|
|
101
59
|
}
|
|
102
60
|
}
|
|
103
61
|
/**
|
|
@@ -134,22 +92,26 @@ function accountView(row, options) {
|
|
|
134
92
|
function accountsSection(options, snap) {
|
|
135
93
|
const { store, extraLocks } = options;
|
|
136
94
|
const locks = extraLocks ? { extraLocks } : {};
|
|
137
|
-
const scope = options.quota?.scope ?? 'all';
|
|
138
95
|
const ids = snap.rows.map((row) => row.id);
|
|
139
96
|
const problem = loadProblem(snap.load);
|
|
140
97
|
const enabledCount = snap.rows.filter((row) => row.enabled).length;
|
|
141
98
|
const items = snap.rows.map((row, index) => {
|
|
142
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.
|
|
143
103
|
const detail = [
|
|
144
104
|
row.type === 'api' ? 'API key' : 'OAuth',
|
|
145
|
-
row.invalid
|
|
146
|
-
? 'invalid'
|
|
147
|
-
: row.enabled
|
|
148
|
-
? 'enabled'
|
|
149
|
-
: `disabled${row.disabledReason ? ` (${row.disabledReason})` : ''}`,
|
|
150
105
|
...(account.identity !== undefined ? [account.identity] : []),
|
|
151
|
-
|
|
106
|
+
...(!row.invalid && !row.enabled && row.disabledReason
|
|
107
|
+
? [`disabled: ${row.disabledReason}`]
|
|
108
|
+
: []),
|
|
152
109
|
].join(' · ');
|
|
110
|
+
const status = row.invalid
|
|
111
|
+
? 'invalid'
|
|
112
|
+
: row.enabled
|
|
113
|
+
? 'enabled'
|
|
114
|
+
: 'disabled';
|
|
153
115
|
const actions = [];
|
|
154
116
|
if (!row.invalid && row.enabled)
|
|
155
117
|
actions.push({
|
|
@@ -210,7 +172,15 @@ function accountsSection(options, snap) {
|
|
|
210
172
|
return `Removed ${name}.`;
|
|
211
173
|
},
|
|
212
174
|
});
|
|
213
|
-
return {
|
|
175
|
+
return {
|
|
176
|
+
id: row.id,
|
|
177
|
+
label: name,
|
|
178
|
+
detail,
|
|
179
|
+
group: 'Accounts',
|
|
180
|
+
status,
|
|
181
|
+
account,
|
|
182
|
+
actions,
|
|
183
|
+
};
|
|
214
184
|
});
|
|
215
185
|
const login = options.accounts?.login;
|
|
216
186
|
const actions = [];
|
|
@@ -218,6 +188,7 @@ function accountsSection(options, snap) {
|
|
|
218
188
|
actions.push({
|
|
219
189
|
id: 'add',
|
|
220
190
|
label: login.label ?? 'Add account',
|
|
191
|
+
group: ACTIONS_GROUP,
|
|
221
192
|
knobs: login.knobs ?? [],
|
|
222
193
|
run: async ({ values, invocation }) => {
|
|
223
194
|
const outcome = await login.run(values, invocation);
|
|
@@ -255,8 +226,8 @@ function accountsSection(options, snap) {
|
|
|
255
226
|
? [problem]
|
|
256
227
|
: [
|
|
257
228
|
snap.rows.length === 0
|
|
258
|
-
? 'No accounts yet
|
|
259
|
-
: `${snap.rows.length
|
|
229
|
+
? 'No accounts yet'
|
|
230
|
+
: `${count(snap.rows.length, 'account')}, ${enabledCount} enabled`,
|
|
260
231
|
],
|
|
261
232
|
items: problem ? [] : items,
|
|
262
233
|
actions,
|
|
@@ -266,50 +237,79 @@ function accountsSection(options, snap) {
|
|
|
266
237
|
function quotaSection(options, snap) {
|
|
267
238
|
const scope = options.quota?.scope ?? 'all';
|
|
268
239
|
const now = options.now();
|
|
269
|
-
|
|
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) => {
|
|
270
264
|
const { account, name } = accountView(row, options);
|
|
271
265
|
const quota = projected(row, scope);
|
|
272
266
|
return {
|
|
273
267
|
id: row.id,
|
|
274
268
|
label: name,
|
|
275
|
-
|
|
269
|
+
group,
|
|
270
|
+
status: formatQuota(quota, { now, form: 'compact' }),
|
|
271
|
+
detail: formatQuota(quota, { now, form: 'full' }),
|
|
276
272
|
account,
|
|
277
|
-
|
|
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
|
+
],
|
|
278
283
|
};
|
|
279
284
|
});
|
|
280
|
-
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
|
+
});
|
|
281
302
|
const actions = [];
|
|
282
303
|
if (candidates.length > 0)
|
|
283
304
|
actions.push({
|
|
284
305
|
id: 'check',
|
|
285
306
|
label: 'Check now',
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
{ value: '*', label: 'All accounts' },
|
|
293
|
-
...candidates.map((row) => ({
|
|
294
|
-
value: row.id,
|
|
295
|
-
label: accountView(row, options).name,
|
|
296
|
-
})),
|
|
297
|
-
],
|
|
298
|
-
value: '*',
|
|
299
|
-
},
|
|
300
|
-
],
|
|
301
|
-
run: async ({ values, invocation }) => {
|
|
302
|
-
const ids = values.account === '*'
|
|
303
|
-
? candidates.map((row) => row.id)
|
|
304
|
-
: [String(values.account)];
|
|
305
|
-
if (options.quota?.check)
|
|
306
|
-
await options.quota.check(ids, invocation);
|
|
307
|
-
else {
|
|
308
|
-
for (const id of ids)
|
|
309
|
-
options.store.requestReading(id);
|
|
310
|
-
await options.store.pullsSettled();
|
|
311
|
-
}
|
|
312
|
-
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')}.`;
|
|
313
313
|
},
|
|
314
314
|
});
|
|
315
315
|
return {
|
|
@@ -317,7 +317,7 @@ function quotaSection(options, snap) {
|
|
|
317
317
|
slot: 'quota',
|
|
318
318
|
title: 'Quota',
|
|
319
319
|
content: {
|
|
320
|
-
lines: snap.rows.length === 0 ? ['No accounts yet
|
|
320
|
+
lines: snap.rows.length === 0 ? ['No accounts yet'] : unchecked,
|
|
321
321
|
items,
|
|
322
322
|
actions,
|
|
323
323
|
},
|
|
@@ -339,15 +339,16 @@ function routingSection(options, snap) {
|
|
|
339
339
|
const ids = snap.rows.map((row) => row.id);
|
|
340
340
|
const tried = orderForPlacement(ids, resolved.placement, options.routing?.formerMainId ?? DEFAULT_FORMER_MAIN_ID);
|
|
341
341
|
const label = choices.find((choice) => choice.value === current)?.label ?? current;
|
|
342
|
-
const lines = [`Mode: ${label}
|
|
342
|
+
const lines = [`Mode: ${label}`];
|
|
343
343
|
if (ids.length > 0)
|
|
344
|
-
lines.push(`Roster order: ${ids.join(', ')}
|
|
344
|
+
lines.push(`Roster order: ${ids.join(', ')}`);
|
|
345
345
|
if (resolved.mode === 'ordered' && tried.join() !== ids.join())
|
|
346
|
-
lines.push(`Tried in order: ${tried.join(', ')}
|
|
346
|
+
lines.push(`Tried in order: ${tried.join(', ')}`);
|
|
347
347
|
const actions = [
|
|
348
348
|
{
|
|
349
349
|
id: 'mode',
|
|
350
350
|
label: 'Change mode',
|
|
351
|
+
group: ACTIONS_GROUP,
|
|
351
352
|
knobs: [
|
|
352
353
|
{ kind: 'choice', id: 'mode', label: 'Mode', choices, value: current },
|
|
353
354
|
],
|
|
@@ -365,6 +366,7 @@ function routingSection(options, snap) {
|
|
|
365
366
|
actions.push({
|
|
366
367
|
id: 'order',
|
|
367
368
|
label: 'Set order',
|
|
369
|
+
group: ACTIONS_GROUP,
|
|
368
370
|
knobs: [
|
|
369
371
|
{
|
|
370
372
|
kind: 'text',
|
|
@@ -402,6 +404,22 @@ function floorLabels(options, snap) {
|
|
|
402
404
|
labels.push(limit.label);
|
|
403
405
|
return labels.length > 0 ? labels : ['primary'];
|
|
404
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
|
+
}
|
|
405
423
|
function limitsSection(options, snap) {
|
|
406
424
|
const { store, extraLocks } = options;
|
|
407
425
|
const locks = extraLocks ? { extraLocks } : {};
|
|
@@ -409,6 +427,8 @@ function limitsSection(options, snap) {
|
|
|
409
427
|
const enabled = killswitch.enabled === true;
|
|
410
428
|
const floors = record(killswitch.accounts);
|
|
411
429
|
const labels = floorLabels(options, snap);
|
|
430
|
+
const nameOf = floorNames(options, snap);
|
|
431
|
+
const state = enabled ? 'on' : 'off';
|
|
412
432
|
const items = snap.rows.map((row) => {
|
|
413
433
|
const { account, name } = accountView(row, options);
|
|
414
434
|
const own = record(floors[row.id]);
|
|
@@ -416,9 +436,11 @@ function limitsSection(options, snap) {
|
|
|
416
436
|
return {
|
|
417
437
|
id: row.id,
|
|
418
438
|
label: name,
|
|
419
|
-
|
|
439
|
+
group: `Floors · killswitch ${state}`,
|
|
440
|
+
// A floor is the least "% left" the account may fall to.
|
|
441
|
+
status: set.length === 0
|
|
420
442
|
? 'no floors'
|
|
421
|
-
:
|
|
443
|
+
: set.map((label) => `${nameOf(label)} ≥${own[label]}%`).join(' · '),
|
|
422
444
|
account,
|
|
423
445
|
actions: [
|
|
424
446
|
{
|
|
@@ -427,7 +449,7 @@ function limitsSection(options, snap) {
|
|
|
427
449
|
knobs: labels.map((label) => ({
|
|
428
450
|
kind: 'number',
|
|
429
451
|
id: label,
|
|
430
|
-
label: `Minimum % left for ${label}`,
|
|
452
|
+
label: `Minimum % left for ${nameOf(label)}`,
|
|
431
453
|
min: 0,
|
|
432
454
|
max: 100,
|
|
433
455
|
...(typeof own[label] === 'number'
|
|
@@ -468,15 +490,14 @@ function limitsSection(options, snap) {
|
|
|
468
490
|
slot: 'limits',
|
|
469
491
|
title: 'Limits',
|
|
470
492
|
content: {
|
|
471
|
-
lines: [
|
|
472
|
-
`Killswitch: ${enabled ? 'on' : 'off'}.`,
|
|
473
|
-
'With the killswitch on, an account whose quota falls below one of its floors is not used.',
|
|
474
|
-
],
|
|
493
|
+
lines: [`Killswitch ${state}`],
|
|
475
494
|
items,
|
|
476
495
|
actions: [
|
|
477
496
|
{
|
|
478
497
|
id: 'killswitch',
|
|
479
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,
|
|
480
501
|
knobs: [
|
|
481
502
|
{
|
|
482
503
|
kind: 'toggle',
|