agl 43.6.0 → 43.7.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/changelog.md +10 -0
- package/dist_serve/bundle.js +1801 -1783
- package/dist_serve/bundle.js.map +2 -2
- package/dist_ts/00_commitinfo_data.js +1 -1
- package/dist_ts/classes.accountsactions.d.ts +3 -1
- package/dist_ts/classes.accountsactions.js +17 -1
- package/dist_ts/classes.controller.d.ts +3 -3
- package/dist_ts/classes.controller.js +5 -4
- package/dist_ts/classes.inferencerouter.d.ts +21 -3
- package/dist_ts/classes.inferencerouter.js +40 -17
- package/dist_ts/classes.inferenceservice.js +2 -2
- package/dist_ts/functions.inferencecli.js +2 -1
- package/dist_ts/interfaces.auth.d.ts +1 -1
- package/dist_ts/interfaces.auth.js +2 -1
- package/dist_ts/plugins.d.ts +2 -1
- package/dist_ts/plugins.js +4 -2
- package/dist_ts_authswitch/authority-contract.d.ts +26 -0
- package/dist_ts_authswitch/authority-contract.js +1 -1
- package/dist_ts_authswitch/authority-overview.d.ts +8 -0
- package/dist_ts_authswitch/authority-overview.js +10 -4
- package/dist_ts_authswitch/authority-placement.d.ts +16 -9
- package/dist_ts_authswitch/authority-placement.js +10 -7
- package/dist_ts_authswitch/authority-priority.d.ts +20 -0
- package/dist_ts_authswitch/authority-priority.js +21 -0
- package/dist_ts_authswitch/classes.authoritybroker.d.ts +7 -0
- package/dist_ts_authswitch/classes.authoritybroker.js +26 -2
- package/dist_ts_authswitch/classes.authoritycli.d.ts +1 -0
- package/dist_ts_authswitch/classes.authoritycli.js +43 -3
- package/dist_ts_authswitch/classes.authorityclient.d.ts +6 -1
- package/dist_ts_authswitch/classes.authorityclient.js +12 -4
- package/dist_ts_authswitch/classes.authoritydaemon.js +7 -1
- package/dist_ts_authswitch/classes.authoritydatabase.d.ts +6 -0
- package/dist_ts_authswitch/classes.authoritydatabase.js +13 -2
- package/dist_ts_authswitch/classes.authoritymodels.d.ts +7 -0
- package/dist_ts_authswitch/classes.authoritymodels.js +17 -8
- package/dist_ts_interfaces/requests.accounts.d.ts +19 -0
- package/dist_ts_interfaces/requests.accounts.js +1 -1
- package/dist_ts_interfaces/requests.d.ts +2 -2
- package/dist_ts_interfaces/requests.js +1 -1
- package/docs/authswitch.md +25 -0
- package/package.json +1 -1
- package/readme.md +29 -5
- package/ts/00_commitinfo_data.ts +1 -1
- package/ts/classes.accountsactions.ts +25 -0
- package/ts/classes.controller.ts +4 -3
- package/ts/classes.inferencerouter.ts +61 -16
- package/ts/classes.inferenceservice.ts +1 -1
- package/ts/functions.inferencecli.ts +1 -0
- package/ts/interfaces.auth.ts +1 -0
- package/ts/plugins.ts +3 -0
- package/ts_authswitch/authority-contract.ts +21 -0
- package/ts_authswitch/authority-overview.ts +19 -5
- package/ts_authswitch/authority-placement.ts +18 -10
- package/ts_authswitch/authority-priority.ts +25 -0
- package/ts_authswitch/classes.authoritybroker.ts +26 -1
- package/ts_authswitch/classes.authoritycli.ts +48 -2
- package/ts_authswitch/classes.authorityclient.ts +14 -4
- package/ts_authswitch/classes.authoritydaemon.ts +8 -1
- package/ts_authswitch/classes.authoritydatabase.ts +11 -1
- package/ts_authswitch/classes.authoritymodels.ts +17 -6
- package/ts_authswitch/readme.md +1 -1
- package/ts_interfaces/requests.accounts.ts +17 -0
- package/ts_interfaces/requests.ts +2 -0
- package/ts_web/00_commitinfo_data.ts +1 -1
- package/ts_web/accounts.plugins.ts +4 -2
- package/ts_web/classes.accountsreadmodel.ts +36 -2
- package/ts_web/elements.accounts.ts +48 -0
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Where a new session goes: an account's lifecycle against its lapse date, and how much of its usage it can spend per
|
|
3
|
-
* hour before that usage resets, the account lapses or it renews. The inference proxy places
|
|
4
|
-
* authswitch command line and `agl proxy status` show it; an existing session keeps its
|
|
5
|
-
* is never placed again by it.
|
|
3
|
+
* hour before that usage resets, the account lapses or it renews, after its owner's priority. The inference proxy places
|
|
4
|
+
* new sessions by it, and the authswitch command line and `agl proxy status` show it; an existing session keeps its
|
|
5
|
+
* account for the prompt cache and is never placed again by it.
|
|
6
6
|
*
|
|
7
7
|
* Besides types, the module imports only the limit rule of `authority-usagelimit.ts`, the window reader it uses, the
|
|
8
8
|
* spend month of `authority-spend.ts` and the renewal of `authority-renewal.ts`, whose own imports carry nothing to a
|
|
@@ -86,25 +86,33 @@ export const authSwitchPlacement = (readingArg: TAuthSwitchUsageReading | null,
|
|
|
86
86
|
return { lifecycle, eligibility, score: scores.length ? Math.min(...scores) : null };
|
|
87
87
|
};
|
|
88
88
|
|
|
89
|
-
/**
|
|
89
|
+
/**
|
|
90
|
+
* An account as placement ranks it: whether its owner's priority holds now (`authSwitchPriorityActive` of
|
|
91
|
+
* `authority-priority.ts`, judged at the moment of placing), its score, whether it is a last resort, and its headroom
|
|
92
|
+
* below its threshold.
|
|
93
|
+
*/
|
|
90
94
|
export interface IAuthSwitchPlacementRank {
|
|
91
95
|
id: string;
|
|
96
|
+
priority: boolean;
|
|
92
97
|
score: number | null;
|
|
93
98
|
lastResort: boolean;
|
|
94
99
|
headroom: number;
|
|
95
100
|
}
|
|
96
101
|
|
|
97
102
|
/**
|
|
98
|
-
* The order a new session is placed in: an account
|
|
99
|
-
* then by the
|
|
100
|
-
*
|
|
101
|
-
*
|
|
102
|
-
*
|
|
103
|
+
* The order a new session is placed in: an account with its owner's priority (AGL-1809) before every account without
|
|
104
|
+
* one, then by the rest of the order among each of the two. An account that lapses within `lapseHorizonMs` only after
|
|
105
|
+
* every other one; then by the account's score shared among the requests it serves now -- `score / (1 + in flight)`, so
|
|
106
|
+
* new sessions spread over the accounts in proportion to what each can spend per hour, and usage that resets, lapses or
|
|
107
|
+
* meets a renewal soon is spent first -- then by headroom and id. An account without a counted window comes after every
|
|
108
|
+
* scored one, the least busy of them first. The order ranks only accounts that take the request: one at its limit or
|
|
109
|
+
* reserve, resting after a 429, lapsed or without the model is never ranked, whatever its priority.
|
|
103
110
|
*/
|
|
104
111
|
export const authSwitchPlacementOrder = (inFlightArg: (accountIdArg: string) => number) => (
|
|
105
112
|
left: IAuthSwitchPlacementRank,
|
|
106
113
|
right: IAuthSwitchPlacementRank,
|
|
107
|
-
): number => Number(
|
|
114
|
+
): number => Number(right.priority) - Number(left.priority)
|
|
115
|
+
|| Number(left.lastResort) - Number(right.lastResort)
|
|
108
116
|
|| Number(left.score === null) - Number(right.score === null)
|
|
109
117
|
|| (left.score !== null && right.score !== null
|
|
110
118
|
? right.score / (1 + inFlightArg(right.id)) - left.score / (1 + inFlightArg(left.id))
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* An account's priority (AGL-1809), as its owner sets it: for 24 hours from when it was set, or until the owner turns it
|
|
3
|
+
* off, AGL's inference proxy places a new session on a priority account of its pool before any other account, as long as
|
|
4
|
+
* one takes the request (`authSwitchPlacementOrder`). Several accounts can hold it at once; among them the placement
|
|
5
|
+
* order decides as it always does. A session already running stays on its account.
|
|
6
|
+
*
|
|
7
|
+
* The account holds the moment its priority ends (`IAuthSwitchAccount.priorityUntil`), and every reader judges it against
|
|
8
|
+
* its own clock, so it ends by itself with nothing running at its end: one that ended reads as none.
|
|
9
|
+
*
|
|
10
|
+
* The module imports nothing, so it bundles for a browser as it is.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
/** How long a priority holds once its owner sets it: 24 hours. Setting it again starts the 24 hours again. */
|
|
14
|
+
export const authSwitchPriorityMs = 86_400_000;
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Whether an account's priority holds at `nowArg` (epoch milliseconds): strictly before the moment it ends
|
|
18
|
+
* (`priorityUntilArg`, `IAuthSwitchAccount.priorityUntil`). One that ended is none.
|
|
19
|
+
*/
|
|
20
|
+
export const authSwitchPriorityActive = (priorityUntilArg: string | null | undefined, nowArg: number): boolean =>
|
|
21
|
+
typeof priorityUntilArg === 'string' && Date.parse(priorityUntilArg) > nowArg;
|
|
22
|
+
|
|
23
|
+
/** When an account's priority ends while it holds at `nowArg`, ISO 8601 UTC as stored; `null` without one or once it ended. */
|
|
24
|
+
export const authSwitchPriorityUntil = (priorityUntilArg: string | null, nowArg: number): string | null =>
|
|
25
|
+
authSwitchPriorityActive(priorityUntilArg, nowArg) ? priorityUntilArg : null;
|
|
@@ -11,6 +11,7 @@ import { authSwitchApiKeyOtherProvider, authSwitchApiKeyProviderNames, authSwitc
|
|
|
11
11
|
type TAuthSwitchApiKeyVerdict, type TAuthSwitchApiKeyVerifier } from './authority-apikeys.js';
|
|
12
12
|
import { isAuthSwitchSpendLimitMicroUsd } from './authority-spend.js';
|
|
13
13
|
import { isAuthSwitchRenewsAt } from './authority-renewal.js';
|
|
14
|
+
import { authSwitchPriorityMs } from './authority-priority.js';
|
|
14
15
|
import { AuthSwitchAuthorityDatabase, authorityBindPurpose, authSwitchBindPurposes, type TAuthSwitchBindPurpose,
|
|
15
16
|
type TStoredNativeHome } from './classes.authoritydatabase.js';
|
|
16
17
|
import { authorityApiKeyProvider, type IStoredAuthorityAccount, type IStoredAuthorityBinding,
|
|
@@ -157,7 +158,8 @@ const notOnApiKey = 'An API key account has no usage windows to keep a reserve o
|
|
|
157
158
|
const publicAccount = (account: IStoredAuthorityAccount): IAuthSwitchAccount => ({
|
|
158
159
|
id: account.id, providerId: account.providerId, label: account.label, email: account.email,
|
|
159
160
|
plan: account.plan, organizationId: account.workspaceId, maxUsagePercent: account.maxUsagePercent, reserveLiftUntil: account.reserveLiftUntil,
|
|
160
|
-
lapsesAt: account.lapsesAt, renewsAt: account.renewsAt ?? null,
|
|
161
|
+
lapsesAt: account.lapsesAt, renewsAt: account.renewsAt ?? null, priorityUntil: account.priorityUntil ?? null,
|
|
162
|
+
spendLimitMicroUsd: account.spendLimitMicroUsd,
|
|
161
163
|
keyHint: account.keyHint, claudeCode: account.claudeCode,
|
|
162
164
|
removed: account.removed, revision: account.revision, statusObservedAt: account.statusObservedAt,
|
|
163
165
|
});
|
|
@@ -974,6 +976,29 @@ export class AuthSwitchAuthorityBroker {
|
|
|
974
976
|
return publicAccount(updated.account);
|
|
975
977
|
}
|
|
976
978
|
|
|
979
|
+
/**
|
|
980
|
+
* Gives an account the owner's priority until 24 hours from now on the authority's clock (`authSwitchPriorityMs`), or
|
|
981
|
+
* ends it, as `setAccountRenewal` sets a renewal. Any account can hold one, and giving it to one that holds it starts the
|
|
982
|
+
* 24 hours again. The stored record carries `priorityUntil` only while it is set: ending it removes the member, and the
|
|
983
|
+
* first write of the account after it ended drops it (`AuthSwitchAuthorityDatabase.persistAccount`).
|
|
984
|
+
*/
|
|
985
|
+
public async setAccountPriority(accountId: string, expectedRevision: number,
|
|
986
|
+
priority: boolean): Promise<IAuthSwitchAccount> {
|
|
987
|
+
if (!isId(accountId) || !validRevision(expectedRevision) || typeof priority !== 'boolean') {
|
|
988
|
+
throw new Error('Invalid account change.');
|
|
989
|
+
}
|
|
990
|
+
const updateId = plugins.crypto.randomUUID();
|
|
991
|
+
const updated = await this.database.changeAccount(updateId, accountId, account => {
|
|
992
|
+
if (!account || account.removed || account.revision !== expectedRevision) throw new AuthSwitchRefusal('account_changed', 'Account changed; refresh before editing.');
|
|
993
|
+
const now = this.now();
|
|
994
|
+
const { priorityUntil: _previous, ...rest } = account;
|
|
995
|
+
return { ...rest, ...(priority ? { priorityUntil: new Date(now + authSwitchPriorityMs).toISOString() } : {}),
|
|
996
|
+
revision: account.revision + 1, updateId, statusObservedAt: new Date(now).toISOString() };
|
|
997
|
+
});
|
|
998
|
+
this.publish();
|
|
999
|
+
return publicAccount(updated.account);
|
|
1000
|
+
}
|
|
1001
|
+
|
|
977
1002
|
/** Refuses a removal that would not go ahead, changing nothing; `removeAccount` refuses the same. */
|
|
978
1003
|
public async assertAccountRemovable(accountId: string, expectedRevision: number): Promise<void> {
|
|
979
1004
|
if (!isId(accountId) || !validRevision(expectedRevision)) throw new Error('Invalid account change.');
|
|
@@ -20,6 +20,7 @@ import { authSwitchApiKeyPaymentProblemText, authSwitchPaymentProblemText,
|
|
|
20
20
|
import { localDateTime } from './timetext.js';
|
|
21
21
|
import { authSwitchAccountLifecycle, lapseHorizonMs } from './authority-placement.js';
|
|
22
22
|
import { authSwitchRenewal, isAuthSwitchRenewsAt } from './authority-renewal.js';
|
|
23
|
+
import { authSwitchPriorityMs, authSwitchPriorityUntil } from './authority-priority.js';
|
|
23
24
|
import { authSwitchPackageIdentity, authSwitchRelease } from './packageidentity.js';
|
|
24
25
|
import { describeOomScoreAdjust } from './serviceoom.js';
|
|
25
26
|
import * as plugins from './plugins.js';
|
|
@@ -61,6 +62,7 @@ export interface IAuthSwitchAuthorityCliClient {
|
|
|
61
62
|
maxUsagePercent: number | null): Promise<IAuthSwitchAccount>;
|
|
62
63
|
setAccountLapse(accountId: string, expectedRevision: number, lapsesAt: string | null): Promise<IAuthSwitchAccount>;
|
|
63
64
|
setAccountRenewal(accountId: string, expectedRevision: number, renewsAt: string | null): Promise<IAuthSwitchAccount>;
|
|
65
|
+
setAccountPriority(accountId: string, expectedRevision: number, priority: boolean): Promise<IAuthSwitchAccount>;
|
|
64
66
|
setAccountSpendLimit(accountId: string, expectedRevision: number,
|
|
65
67
|
spendLimitMicroUsd: number | null): Promise<IAuthSwitchAccount>;
|
|
66
68
|
setAccountClaudeCode(accountId: string, expectedRevision: number, claudeCode: boolean): Promise<IAuthSwitchAccount>;
|
|
@@ -105,6 +107,7 @@ type TAuthorityCliCommand =
|
|
|
105
107
|
| { kind: 'setMaxUsage'; accountId: string; maxUsagePercent: number | null; json: boolean }
|
|
106
108
|
| { kind: 'setLapse'; accountId: string; lapsesAt: string | null; json: boolean }
|
|
107
109
|
| { kind: 'setRenewal'; accountId: string; renewsAt: string | null; json: boolean }
|
|
110
|
+
| { kind: 'setPriority'; accountId: string; priority: boolean; json: boolean }
|
|
108
111
|
| { kind: 'setSpendLimit'; accountId: string; spendLimitMicroUsd: number | null; json: boolean }
|
|
109
112
|
| { kind: 'setClaudeCode'; accountId: string; claudeCode: boolean; json: boolean }
|
|
110
113
|
| { kind: 'get'; operationId: string; json: boolean }
|
|
@@ -123,7 +126,7 @@ class AuthorityCliFailure extends Error {
|
|
|
123
126
|
}
|
|
124
127
|
}
|
|
125
128
|
|
|
126
|
-
const usage = 'Usage: authswitch --help | authswitch --version [--json] | authswitch list [--json] | authswitch limits [--json] | authswitch account list [--json] | authswitch account add openai|claude [--json] | authswitch account add anthropic-api-key|openai-api-key [--label <label>] [--spend-limit <dollars>] [--json] | authswitch account use codex <account-id> [--json] | authswitch account release codex <account-id> [--end-running-turns] [--json] | authswitch account release claude <account-id> [--end-native-sessions] [--json] | authswitch account repair claude [--json] | authswitch account reauth <account-id> <login-id> [--json] | authswitch account recheck <account-id> [--json] | authswitch account remove <account-id> [--revoke] [--json] | authswitch account set <account-id> --max-usage <percent>|--clear|--lapses-at <date-time>|--clear-lapse|--renews-at <date-time>|--clear-renewal|--spend-limit <dollars>|--clear-spend-limit [--json] | authswitch account operation get|cancel|resume <operation-id> [--json] | authswitch account preuse <account-id> <login-id>|--all [--prompt <text>] [--model <id>] [--json] | authswitch account preuse operation get|cancel|resume <operation-id> [--json] | authswitch authority doctor [--json] | authswitch authority import inventory [--json] | authswitch authority import status [--json] | authswitch authority import submit <source-id> --digest <source-digest> [--json] | authswitch authority service install|status|enable|start|stop | authswitch authority daemon';
|
|
129
|
+
const usage = 'Usage: authswitch --help | authswitch --version [--json] | authswitch list [--json] | authswitch limits [--json] | authswitch account list [--json] | authswitch account add openai|claude [--json] | authswitch account add anthropic-api-key|openai-api-key [--label <label>] [--spend-limit <dollars>] [--json] | authswitch account use codex <account-id> [--json] | authswitch account release codex <account-id> [--end-running-turns] [--json] | authswitch account release claude <account-id> [--end-native-sessions] [--json] | authswitch account repair claude [--json] | authswitch account reauth <account-id> <login-id> [--json] | authswitch account recheck <account-id> [--json] | authswitch account remove <account-id> [--revoke] [--json] | authswitch account set <account-id> --max-usage <percent>|--clear|--lapses-at <date-time>|--clear-lapse|--renews-at <date-time>|--clear-renewal|--priority|--clear-priority|--spend-limit <dollars>|--clear-spend-limit [--json] | authswitch account operation get|cancel|resume <operation-id> [--json] | authswitch account preuse <account-id> <login-id>|--all [--prompt <text>] [--model <id>] [--json] | authswitch account preuse operation get|cancel|resume <operation-id> [--json] | authswitch authority doctor [--json] | authswitch authority import inventory [--json] | authswitch authority import status [--json] | authswitch authority import submit <source-id> --digest <source-digest> [--json] | authswitch authority service install|status|enable|start|stop | authswitch authority daemon';
|
|
127
130
|
|
|
128
131
|
/** Every command, one per line, with what it does; `authswitch --help` prints it. */
|
|
129
132
|
const help = (): string => `authswitch ${authSwitchRelease.version}
|
|
@@ -181,6 +184,12 @@ Usage
|
|
|
181
184
|
(a past one too): the AGL proxy spends first the usage a
|
|
182
185
|
window would still hold at the next renewal;
|
|
183
186
|
--clear-renewal removes it
|
|
187
|
+
authswitch account set <account-id> --priority|--clear-priority [--json]
|
|
188
|
+
for 24 hours from now the AGL proxy places new sessions on
|
|
189
|
+
this account before any other of its pool, as long as it
|
|
190
|
+
takes them (several accounts can have it, and sessions
|
|
191
|
+
running elsewhere stay); again restarts the 24 hours;
|
|
192
|
+
--clear-priority ends it
|
|
184
193
|
authswitch account set <account-id> --spend-limit <dollars>|--clear-spend-limit [--json]
|
|
185
194
|
an API key's monthly spend limit (calendar month, UTC) on
|
|
186
195
|
what AGL's proxy relayed on it: at the limit the proxy places
|
|
@@ -399,6 +408,9 @@ const parse = (argv: readonly string[]): TAuthorityCliCommand | null => {
|
|
|
399
408
|
if (options.length === 2 && options[0] === '--renews-at' && isAuthSwitchRenewsAt(options[1])) {
|
|
400
409
|
return { kind: 'setRenewal', accountId: argv[2], renewsAt: options[1], json };
|
|
401
410
|
}
|
|
411
|
+
if (options.length === 1 && (options[0] === '--priority' || options[0] === '--clear-priority')) {
|
|
412
|
+
return { kind: 'setPriority', accountId: argv[2], priority: options[0] === '--priority', json };
|
|
413
|
+
}
|
|
402
414
|
if (options.length === 1 && options[0] === '--clear-spend-limit') {
|
|
403
415
|
return { kind: 'setSpendLimit', accountId: argv[2], spendLimitMicroUsd: null, json };
|
|
404
416
|
}
|
|
@@ -537,6 +549,10 @@ class ScopedAuthorityCliClient implements IAuthSwitchAuthorityCliClient {
|
|
|
537
549
|
return this.client.setAccountRenewal(accountId, expectedRevision, renewsAt, this.controller.signal);
|
|
538
550
|
}
|
|
539
551
|
|
|
552
|
+
public setAccountPriority(accountId: string, expectedRevision: number, priority: boolean): Promise<IAuthSwitchAccount> {
|
|
553
|
+
return this.client.setAccountPriority(accountId, expectedRevision, priority, this.controller.signal);
|
|
554
|
+
}
|
|
555
|
+
|
|
540
556
|
public addApiKey(providerId: TAuthSwitchApiKeyProvider, apiKey: string,
|
|
541
557
|
options: { label?: string; spendLimitMicroUsd?: number }): Promise<IReq_AuthSwitchAddApiKey['response']> {
|
|
542
558
|
return this.client.addApiKey(providerId, apiKey, options, this.controller.signal);
|
|
@@ -655,6 +671,21 @@ const renderRenewal = (account: IAuthSwitchAccount, nowArg: number): string =>
|
|
|
655
671
|
+ (account.renewsAt === null ? 'no renewal set.\n'
|
|
656
672
|
: `${renewalText(account, nowArg)}; usage it would still hold then is used first.\n`);
|
|
657
673
|
|
|
674
|
+
/**
|
|
675
|
+
* An account's priority in words, as `account set --priority` and `account list` state it: when it ends, while it holds
|
|
676
|
+
* at `nowArg`. Empty for an account without one, or once it ended.
|
|
677
|
+
*/
|
|
678
|
+
const priorityText = (account: IAuthSwitchAccount, nowArg: number): string => {
|
|
679
|
+
const until = authSwitchPriorityUntil(account.priorityUntil, nowArg);
|
|
680
|
+
return until === null ? '' : `priority until ${safe(until)} (set by the owner)`;
|
|
681
|
+
};
|
|
682
|
+
|
|
683
|
+
const renderPriority = (account: IAuthSwitchAccount, nowArg: number): string =>
|
|
684
|
+
`Account ${safe(account.email ?? account.label)} (${safe(account.id)}): `
|
|
685
|
+
+ (priorityText(account, nowArg) === '' ? 'no priority.\n'
|
|
686
|
+
: `${priorityText(account, nowArg)}; the AGL proxy places new sessions on it before any other account of its pool `
|
|
687
|
+
+ `as long as it takes them, for ${authSwitchPriorityMs / 3_600_000} hours or until --clear-priority.\n`);
|
|
688
|
+
|
|
658
689
|
/** A re-check as `account recheck` states it: how the read went, and whether the account is still held. */
|
|
659
690
|
const renderRecheck = (account: IAuthSwitchAccount, recheck: IAuthSwitchUsageRecheck): string =>
|
|
660
691
|
`Account ${safe(account.email ?? account.label)} (${safe(account.id)}): ${authSwitchRecheckOutcomeText(recheck.outcome)}\n`
|
|
@@ -710,7 +741,9 @@ const renderList = (snapshot: IAuthSwitchSnapshot, nowArg: number): string => {
|
|
|
710
741
|
` account ${safe(account.id)}; organization ${account.organizationId === undefined ? 'not published'
|
|
711
742
|
: safe(account.organizationId)}; plan ${safe(account.plan)}; max usage ${account.maxUsagePercent === null ? 'not set'
|
|
712
743
|
: `${account.maxUsagePercent}%`}; ${lapseText(account, nowArg)}; `
|
|
713
|
-
+ `${account.renewsAt === null ? '' : `${renewalText(account, nowArg)}; `}
|
|
744
|
+
+ `${account.renewsAt === null ? '' : `${renewalText(account, nowArg)}; `}`
|
|
745
|
+
+ `${priorityText(account, nowArg) === '' ? '' : `${priorityText(account, nowArg)}; `}`
|
|
746
|
+
+ `${account.removed ? 'removed' : 'registered'}; `
|
|
714
747
|
+ `stored ${safe(account.statusObservedAt)}`);
|
|
715
748
|
const logins = snapshot.logins.filter(login => login.accountId === account.id);
|
|
716
749
|
if (logins.length === 0) lines.push(' logins: none');
|
|
@@ -1544,6 +1577,19 @@ export const runAuthSwitchAuthorityCli = async (argv: readonly string[],
|
|
|
1544
1577
|
await writeOutput(command.json ? JSON.stringify({ account: changed }) + '\n' : renderRenewal(changed, now()));
|
|
1545
1578
|
return 0;
|
|
1546
1579
|
}
|
|
1580
|
+
if (command.kind === 'setPriority') {
|
|
1581
|
+
const account = (await activeClient.snapshotAll()).accounts.find(item => item.id === command.accountId && !item.removed);
|
|
1582
|
+
if (!account) {
|
|
1583
|
+
await writeDiagnostic('No authority account has this id. Run `authswitch account list` for the ids.\n');
|
|
1584
|
+
return 1;
|
|
1585
|
+
}
|
|
1586
|
+
const changed = await activeClient.setAccountPriority(account.id, account.revision, command.priority);
|
|
1587
|
+
if (changed.id !== account.id || (changed.priorityUntil === null) === command.priority) {
|
|
1588
|
+
throw new AuthorityCliFailure('response');
|
|
1589
|
+
}
|
|
1590
|
+
await writeOutput(command.json ? JSON.stringify({ account: changed }) + '\n' : renderPriority(changed, now()));
|
|
1591
|
+
return 0;
|
|
1592
|
+
}
|
|
1547
1593
|
if (command.kind === 'setSpendLimit') {
|
|
1548
1594
|
const account = (await activeClient.snapshotAll()).accounts.find(item => item.id === command.accountId && !item.removed);
|
|
1549
1595
|
if (!account) {
|
|
@@ -7,7 +7,7 @@ import type {
|
|
|
7
7
|
IReq_AuthSwitchClaudeHostLogin, IReq_AuthSwitchEvents, IReq_AuthSwitchReleaseClaudeNative,
|
|
8
8
|
IReq_AuthSwitchClaudeNativeReleaseOperation, IReq_AuthSwitchRepairClaudeHost,
|
|
9
9
|
IReq_AuthSwitchGetBinding, IReq_AuthSwitchGetOperation, IReq_AuthSwitchListOperations,
|
|
10
|
-
IReq_AuthSwitchRemoveAccount, IReq_AuthSwitchRenameAccount, IReq_AuthSwitchSetAccountLapse, IReq_AuthSwitchSetAccountRenewal, IReq_AuthSwitchSetAccountMaxUsage, IReq_AuthSwitchLiftAccountReserve,
|
|
10
|
+
IReq_AuthSwitchRemoveAccount, IReq_AuthSwitchRenameAccount, IReq_AuthSwitchSetAccountLapse, IReq_AuthSwitchSetAccountRenewal, IReq_AuthSwitchSetAccountPriority, IReq_AuthSwitchSetAccountMaxUsage, IReq_AuthSwitchLiftAccountReserve,
|
|
11
11
|
IReq_AuthSwitchCancelPreuse, IReq_AuthSwitchGetPreuse, IReq_AuthSwitchSnapshot,
|
|
12
12
|
IReq_AuthSwitchStartPreuse, IReq_AuthSwitchUsage, IReq_AuthSwitchObserveUsage, IReq_AuthSwitchReportPaymentProblem,
|
|
13
13
|
IReq_AuthSwitchRecordSpend, IAuthSwitchSpendAnswer, TAuthSwitchPaymentProblemCause, TAuthSwitchApiKeyProvider,
|
|
@@ -122,8 +122,8 @@ export class AuthSwitchDaemonOutdatedError extends Error {
|
|
|
122
122
|
* A snapshot page carries every member of this release's contract. `schemaVersion` is not bumped for an
|
|
123
123
|
* additive member; version 3 adds the gateway runtime, every account states its `maxUsagePercent` from 38.3.0
|
|
124
124
|
* on, its `lapsesAt` from 38.4.0 on, its `reserveLiftUntil` with reserve lifts, its `spendLimitMicroUsd` and
|
|
125
|
-
* `keyHint` with API keys of both providers, its `claudeCode` from AGL-1146 on,
|
|
126
|
-
* Consumers still check their supported version.
|
|
125
|
+
* `keyHint` with API keys of both providers, its `claudeCode` from AGL-1146 on, its `renewsAt` from AGL-1644 on, and its
|
|
126
|
+
* `priorityUntil` from AGL-1809 on. Consumers still check their supported version.
|
|
127
127
|
*/
|
|
128
128
|
const assertCurrentSnapshot = (snapshot: IAuthSwitchSnapshot): IAuthSwitchSnapshot => {
|
|
129
129
|
const page: Partial<IAuthSwitchSnapshot> = snapshot;
|
|
@@ -135,7 +135,8 @@ const assertCurrentSnapshot = (snapshot: IAuthSwitchSnapshot): IAuthSwitchSnapsh
|
|
|
135
135
|
|| (account as Partial<IAuthSwitchAccount>).spendLimitMicroUsd === undefined
|
|
136
136
|
|| (account as Partial<IAuthSwitchAccount>).keyHint === undefined
|
|
137
137
|
|| (account as Partial<IAuthSwitchAccount>).claudeCode === undefined
|
|
138
|
-
|| (account as Partial<IAuthSwitchAccount>).renewsAt === undefined
|
|
138
|
+
|| (account as Partial<IAuthSwitchAccount>).renewsAt === undefined
|
|
139
|
+
|| (account as Partial<IAuthSwitchAccount>).priorityUntil === undefined)) {
|
|
139
140
|
throw new AuthSwitchDaemonOutdatedError();
|
|
140
141
|
}
|
|
141
142
|
return snapshot;
|
|
@@ -563,6 +564,15 @@ export class AuthSwitchClient {
|
|
|
563
564
|
return (await this.request<IReq_AuthSwitchSetAccountRenewal>('authswitch.authority.renewal',
|
|
564
565
|
{ accountId, expectedRevision, renewsAt }, 35_000, false, signal)).account;
|
|
565
566
|
}
|
|
567
|
+
/**
|
|
568
|
+
* Gives an account the owner's priority for 24 hours from now, or ends it with `false` (see
|
|
569
|
+
* `IReq_AuthSwitchSetAccountPriority`).
|
|
570
|
+
*/
|
|
571
|
+
public async setAccountPriority(accountId: string, expectedRevision: number, priority: boolean,
|
|
572
|
+
signal?: AbortSignal): Promise<IReq_AuthSwitchSetAccountPriority['response']['account']> {
|
|
573
|
+
return (await this.request<IReq_AuthSwitchSetAccountPriority>('authswitch.authority.priority',
|
|
574
|
+
{ accountId, expectedRevision, priority }, 35_000, false, signal)).account;
|
|
575
|
+
}
|
|
566
576
|
/**
|
|
567
577
|
* Removes an account; `revoke: true` also revokes its ChatGPT sign-in at OpenAI (see
|
|
568
578
|
* `IReq_AuthSwitchRemoveAccount`). An older daemon refuses `revoke` as an invalid request before it changes
|
|
@@ -8,7 +8,7 @@ import type {
|
|
|
8
8
|
IReq_AuthSwitchRepairClaudeHost,
|
|
9
9
|
IReq_AuthSwitchEvents, IReq_AuthSwitchGetBinding, IReq_AuthSwitchGetOperation, IReq_AuthSwitchListOperations,
|
|
10
10
|
IReq_AuthSwitchRemoveAccount,
|
|
11
|
-
IReq_AuthSwitchRenameAccount, IReq_AuthSwitchSetAccountLapse, IReq_AuthSwitchSetAccountRenewal, IReq_AuthSwitchSetAccountMaxUsage, IReq_AuthSwitchSetAccountSpendLimit, IReq_AuthSwitchSetAccountClaudeCode, IReq_AuthSwitchLiftAccountReserve, IReq_AuthSwitchSnapshot,
|
|
11
|
+
IReq_AuthSwitchRenameAccount, IReq_AuthSwitchSetAccountLapse, IReq_AuthSwitchSetAccountRenewal, IReq_AuthSwitchSetAccountPriority, IReq_AuthSwitchSetAccountMaxUsage, IReq_AuthSwitchSetAccountSpendLimit, IReq_AuthSwitchSetAccountClaudeCode, IReq_AuthSwitchLiftAccountReserve, IReq_AuthSwitchSnapshot,
|
|
12
12
|
IReq_AuthSwitchCancelPreuse, IReq_AuthSwitchGetPreuse, IReq_AuthSwitchStartPreuse, IReq_AuthSwitchUsage,
|
|
13
13
|
IReq_AuthSwitchObserveUsage, IReq_AuthSwitchReportPaymentProblem, IReq_AuthSwitchRecheckUsage, IReq_AuthSwitchRecordSpend,
|
|
14
14
|
IReq_AuthSwitchMoveClaudeHomeIn, IReq_AuthSwitchMoveClaudeHomeOut, IReq_AuthSwitchRegisterClaudeHome,
|
|
@@ -762,6 +762,13 @@ export class AuthSwitchAuthorityDaemon {
|
|
|
762
762
|
return { account: await this.broker.setAccountRenewal(request.accountId, request.expectedRevision,
|
|
763
763
|
request.renewsAt) };
|
|
764
764
|
}));
|
|
765
|
+
this.managementRouter.addTypedHandler(this.handler<IReq_AuthSwitchSetAccountPriority>(
|
|
766
|
+
'authswitch.authority.priority', async request => {
|
|
767
|
+
if (!hasKeys(request, ['accountId', 'expectedRevision', 'priority']) || typeof request.accountId !== 'string'
|
|
768
|
+
|| typeof request.expectedRevision !== 'number' || typeof request.priority !== 'boolean') invalid();
|
|
769
|
+
return { account: await this.broker.setAccountPriority(request.accountId, request.expectedRevision,
|
|
770
|
+
request.priority) };
|
|
771
|
+
}));
|
|
765
772
|
this.managementRouter.addTypedHandler(this.handler<IReq_AuthSwitchGetBinding>(
|
|
766
773
|
'authswitch.authority.binding', async request => {
|
|
767
774
|
if (!hasKeys(request, ['bindingId']) || !validBindingId(request.bindingId)) invalid();
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import * as plugins from './plugins.js';
|
|
2
2
|
import { AuthSwitchRefusal, authSwitchPreemptibleRuntimes, type IAuthSwitchSpendAnswer } from './authority-contract.js';
|
|
3
3
|
import { authSwitchSpendExhausted, authSwitchSpendPeriod, type IAuthSwitchSpendReading } from './authority-spend.js';
|
|
4
|
+
import { authSwitchPriorityActive } from './authority-priority.js';
|
|
4
5
|
import {
|
|
5
6
|
AuthSwitchAuthorityAccountModel, AuthSwitchAuthorityBindingModel, AuthSwitchAuthorityClaudeContainerHomeModel,
|
|
6
7
|
AuthSwitchAuthorityClaudeHandoffModel, AuthSwitchAuthorityClaudeHomeModel, AuthSwitchAuthorityCodexHandoffModel,
|
|
@@ -1568,8 +1569,16 @@ export class AuthSwitchAuthorityDatabase {
|
|
|
1568
1569
|
return next;
|
|
1569
1570
|
}
|
|
1570
1571
|
|
|
1572
|
+
/**
|
|
1573
|
+
* Writes an account record. A priority that ended by the write's own time (`statusObservedAt`, which every writer sets
|
|
1574
|
+
* to its clock), or one on a removed account, is none: the write drops it from the draft, which the caller answers
|
|
1575
|
+
* with, so the record goes back to the one an earlier accounts service reads with no timer at its end (AGENTS.md,
|
|
1576
|
+
* rollback floor).
|
|
1577
|
+
*/
|
|
1571
1578
|
private async persistAccount(session: TSession, current: Awaited<ReturnType<typeof AuthSwitchAuthorityAccountModel.exact.findStoredOne>>,
|
|
1572
1579
|
draft: IStoredAuthorityAccount): Promise<void> {
|
|
1580
|
+
if (draft.priorityUntil !== undefined && (draft.removed
|
|
1581
|
+
|| !authSwitchPriorityActive(draft.priorityUntil, Date.parse(draft.statusObservedAt)))) delete draft.priorityUntil;
|
|
1573
1582
|
assertStoredAuthorityAccount(draft);
|
|
1574
1583
|
if (current) {
|
|
1575
1584
|
const prior = AuthSwitchAuthorityAccountModel.exact.toPersisted(current);
|
|
@@ -1579,8 +1588,9 @@ export class AuthSwitchAuthorityDatabase {
|
|
|
1579
1588
|
const result = await AuthSwitchAuthorityAccountModel.exact.transition({
|
|
1580
1589
|
current, change: model => {
|
|
1581
1590
|
Object.assign(model, draft);
|
|
1582
|
-
// Optional: a draft without
|
|
1591
|
+
// Optional: a draft without them drops them, which `Object.assign` alone would keep (AGENTS.md, rollback floor).
|
|
1583
1592
|
model.renewsAt = draft.renewsAt;
|
|
1593
|
+
model.priorityUntil = draft.priorityUntil;
|
|
1584
1594
|
},
|
|
1585
1595
|
}, { session });
|
|
1586
1596
|
if (result.status !== 'transitioned') throw new Error('Account changed concurrently.');
|
|
@@ -37,6 +37,12 @@ export interface IStoredAuthorityAccount {
|
|
|
37
37
|
* member (the transition sets it to `undefined`), never stores null.
|
|
38
38
|
*/
|
|
39
39
|
renewsAt?: string;
|
|
40
|
+
/**
|
|
41
|
+
* When the owner's priority on the account ends, ISO 8601 UTC (`IAuthSwitchAccount.priorityUntil`, AGL-1809). Present
|
|
42
|
+
* only while the owner holds one set, as `renewsAt` is: turning it off removes the member, and so does any write of the
|
|
43
|
+
* account once it ended or the account is removed (`AuthSwitchAuthorityDatabase.persistAccount`).
|
|
44
|
+
*/
|
|
45
|
+
priorityUntil?: string;
|
|
40
46
|
/** An API key account's monthly spend limit in micro-dollars, or `null` (`IAuthSwitchAccount.spendLimitMicroUsd`). */
|
|
41
47
|
spendLimitMicroUsd: number | null;
|
|
42
48
|
/** How an API key account's key ends, or `null` (`IAuthSwitchAccount.keyHint`). */
|
|
@@ -738,15 +744,19 @@ const storedAccountKeys = ['id', 'providerId', 'issuer', 'subject', 'workspaceId
|
|
|
738
744
|
'primaryGrantId', 'maxUsagePercent', 'reserveLiftUntil', 'lapsesAt', 'spendLimitMicroUsd', 'keyHint', 'claudeCode',
|
|
739
745
|
'removed', 'revision', 'statusObservedAt', 'updateId'] as const;
|
|
740
746
|
|
|
747
|
+
/** The members an account record holds only while they hold a value (AGENTS.md, rollback floor). */
|
|
748
|
+
const optionalAccountKeys = ['renewsAt', 'priorityUntil'] as const;
|
|
749
|
+
|
|
741
750
|
/**
|
|
742
|
-
* An account record holds every member of `storedAccountKeys` and nothing else,
|
|
743
|
-
* (`renewsAt`, only on a Claude sign-in)
|
|
744
|
-
* valid
|
|
751
|
+
* An account record holds every member of `storedAccountKeys` and nothing else, besides any of `optionalAccountKeys`:
|
|
752
|
+
* a renewal anchor (`renewsAt`, only on a Claude sign-in) and the end of the owner's priority (`priorityUntil`, on any
|
|
753
|
+
* account). Each optional member is checked on its own: a record that holds it holds a valid value, never null.
|
|
745
754
|
*/
|
|
746
755
|
const storedAccountMembers = (value: Record<string, unknown>): boolean =>
|
|
747
|
-
exactKeys(value, storedAccountKeys)
|
|
748
|
-
|
|
749
|
-
&& value.providerId === 'anthropic' && value.workspaceId !== 'api-key')
|
|
756
|
+
exactKeys(value, [...storedAccountKeys, ...optionalAccountKeys.filter(key => Object.hasOwn(value, key))])
|
|
757
|
+
&& (!Object.hasOwn(value, 'renewsAt') || (iso(value.renewsAt) && isAuthSwitchRenewsAt(value.renewsAt)
|
|
758
|
+
&& value.providerId === 'anthropic' && value.workspaceId !== 'api-key'))
|
|
759
|
+
&& (!Object.hasOwn(value, 'priorityUntil') || iso(value.priorityUntil));
|
|
750
760
|
|
|
751
761
|
export const assertStoredAuthorityAccount: (value: unknown) => asserts value is IStoredAuthorityAccount = value => {
|
|
752
762
|
if (!object(value) || !storedAccountMembers(value)
|
|
@@ -1321,6 +1331,7 @@ export class AuthSwitchAuthorityAccountModel extends plugins.nosqldb.SmartDataDb
|
|
|
1321
1331
|
@plugins.nosqldb.svDb() public reserveLiftUntil!: string | null;
|
|
1322
1332
|
@plugins.nosqldb.svDb() public lapsesAt!: string | null;
|
|
1323
1333
|
@plugins.nosqldb.svDb() public renewsAt?: string;
|
|
1334
|
+
@plugins.nosqldb.svDb() public priorityUntil?: string;
|
|
1324
1335
|
@plugins.nosqldb.svDb() public spendLimitMicroUsd!: number | null;
|
|
1325
1336
|
@plugins.nosqldb.svDb() public keyHint!: string | null;
|
|
1326
1337
|
@plugins.nosqldb.svDb() public claudeCode!: boolean;
|
package/ts_authswitch/readme.md
CHANGED
|
@@ -8,6 +8,6 @@ Keep the authority in its own process. The controller never owns refresh grants.
|
|
|
8
8
|
|
|
9
9
|
Native credential files belong to their tools: the authority writes one only through a verified, journaled handoff, and never destroys or overwrites a native credential it has not first proven it can restore. Every operation that stops the owned Codex app-server restarts it on both success and failure. Structured authority state uses the existing NoSQLDB models and versioned migrations.
|
|
10
10
|
|
|
11
|
-
Tests isolate all harness homes and use injected provider/process adapters. Never run account-mutating tests against the developer's own installations. Module import, CLI help/version and the browser leaves (`authority-contract.ts`, `authority-spend.ts`, `authority-usagewindows.ts`, `authority-usagelimit.ts`, `authority-usageheaders.ts`, `authority-usagetokens.ts`, `authority-placement.ts`, `authority-subscription.ts`, `preuse-text.ts`) must not initialize a controller or touch credentials. `authority-subscription.ts` holds the one map of what Claude's `subscription_status` values mean (empty until a value is confirmed) and the words of a payment problem and a re-check, which the command line and the Accounts screen share; `classes.authorityusage.ts` holds a payment problem on the usage record (`reportPaymentProblem`) and clears it on a read that finds a changed subscription or a healthy re-check (`recheck`); a problem held without a subscription takes the one the next healthy read finds, and that read clears nothing. `authority-placement.ts` is the one rule of an account's lifecycle against its `lapsesAt` and of the placement score the proxy places new sessions by; `authority-renewal.ts` (imports nothing) is the one rule of a Claude sign-in's monthly renewal as its owner set it (`renewsAt`), which placement counts as a window deadline. `authority-usageheaders.ts` reads the usage a provider's answer headers state and joins it to the authority's own reading; the authority holds such observations in memory and answers every usage read with them (`authswitch.authority.usage.observe`). `classes.authorityusage.ts` owns the one usage-read schedule: each account is read from the provider every 10 minutes on the authority's timer and at once after an inference 429, a failed read keeps the held reading `stale` and waits for `retry-after` or the next slot, and no question waits for a read or an unseal. `authority-usagetokens.ts` (browser-safe) weighs the tokens the proxy reports by Anthropic's published prices, and `classes.authorityusageestimate.ts` carries each Claude window forward between reads with a ratio learned per account and window, in memory only. `authority-usagelimit.ts` is the one rule of whether an account's usage, against its `maxUsagePercent`, lets it take work -- a switch on the reading's `kind`, where an API key's `spend` reading is judged by its spend limit alone; the proxy, Flex, the CLI and the Accounts screen all call it rather than restating it. `authority-spend.ts` (imports nothing) is the calendar month in UTC a key's spend counts in (`authSwitchSpendPeriod`, the one calendar function), the spend reading, the spend limit rule and dollar amounts. `authority-apikeys.ts` holds the key verifier (`authSwitchApiKeyVerifier`, a read of the provider's model list) and the guard against a key of the other provider; `AuthSwitchAuthorityDatabase.recordSpend` / `readSpend` keep the monthly ledger (`authswitch_authority_spend_entries`, `authswitch_authority_spend_periods`), and `classes.authorityusage.ts` answers a key's usage from it and holds a key's payment problem, by cause, on the key's usage record. A sealed key is `{ kind: 'anthropicApiKey' | 'openaiApiKey', apiKey }`, one kind per provider; never add a kind a reader must keep forever.
|
|
11
|
+
Tests isolate all harness homes and use injected provider/process adapters. Never run account-mutating tests against the developer's own installations. Module import, CLI help/version and the browser leaves (`authority-contract.ts`, `authority-spend.ts`, `authority-usagewindows.ts`, `authority-usagelimit.ts`, `authority-usageheaders.ts`, `authority-usagetokens.ts`, `authority-placement.ts`, `authority-priority.ts`, `authority-subscription.ts`, `preuse-text.ts`) must not initialize a controller or touch credentials. `authority-subscription.ts` holds the one map of what Claude's `subscription_status` values mean (empty until a value is confirmed) and the words of a payment problem and a re-check, which the command line and the Accounts screen share; `classes.authorityusage.ts` holds a payment problem on the usage record (`reportPaymentProblem`) and clears it on a read that finds a changed subscription or a healthy re-check (`recheck`); a problem held without a subscription takes the one the next healthy read finds, and that read clears nothing. `authority-placement.ts` is the one rule of an account's lifecycle against its `lapsesAt` and of the placement score the proxy places new sessions by; `authority-renewal.ts` (imports nothing) is the one rule of a Claude sign-in's monthly renewal as its owner set it (`renewsAt`), which placement counts as a window deadline; `authority-priority.ts` (imports nothing) is the one rule of an account's priority (`priorityUntil`, 24 hours from when the owner gave it), which placement ranks first and every view judges against its own clock. `authority-usageheaders.ts` reads the usage a provider's answer headers state and joins it to the authority's own reading; the authority holds such observations in memory and answers every usage read with them (`authswitch.authority.usage.observe`). `classes.authorityusage.ts` owns the one usage-read schedule: each account is read from the provider every 10 minutes on the authority's timer and at once after an inference 429, a failed read keeps the held reading `stale` and waits for `retry-after` or the next slot, and no question waits for a read or an unseal. `authority-usagetokens.ts` (browser-safe) weighs the tokens the proxy reports by Anthropic's published prices, and `classes.authorityusageestimate.ts` carries each Claude window forward between reads with a ratio learned per account and window, in memory only. `authority-usagelimit.ts` is the one rule of whether an account's usage, against its `maxUsagePercent`, lets it take work -- a switch on the reading's `kind`, where an API key's `spend` reading is judged by its spend limit alone; the proxy, Flex, the CLI and the Accounts screen all call it rather than restating it. `authority-spend.ts` (imports nothing) is the calendar month in UTC a key's spend counts in (`authSwitchSpendPeriod`, the one calendar function), the spend reading, the spend limit rule and dollar amounts. `authority-apikeys.ts` holds the key verifier (`authSwitchApiKeyVerifier`, a read of the provider's model list) and the guard against a key of the other provider; `AuthSwitchAuthorityDatabase.recordSpend` / `readSpend` keep the monthly ledger (`authswitch_authority_spend_entries`, `authswitch_authority_spend_periods`), and `classes.authorityusage.ts` answers a key's usage from it and holds a key's payment problem, by cause, on the key's usage record. A sealed key is `{ kind: 'anthropicApiKey' | 'openaiApiKey', apiKey }`, one kind per provider; never add a kind a reader must keep forever.
|
|
12
12
|
|
|
13
13
|
Imported from authswitch 11.4.1, commit `c3fed26`; future fixes and releases belong to AGL. OpenAI adaptations retain their headers and the notices in the repository's `third-party-notices.md` and `openai-codex-license.txt`.
|
|
@@ -273,6 +273,23 @@ export interface IReq_ControllerAccountsRenewal extends plugins.typedrequestInte
|
|
|
273
273
|
response: { answer: TControllerAccountsAnswer<TControllerAccount> };
|
|
274
274
|
}
|
|
275
275
|
|
|
276
|
+
/**
|
|
277
|
+
* Gives an account the owner's priority (AGL-1809) for 24 hours from now, by the accounts service's clock, or ends it
|
|
278
|
+
* with `priority: false`; giving it to an account that holds it starts the 24 hours again. Until it ends, AGL's inference
|
|
279
|
+
* proxy places a new session on the account before any account of its pool without one, as long as it takes the
|
|
280
|
+
* request; several accounts can hold it. Any account can have one. `expectedRevision` is the revision the view showed,
|
|
281
|
+
* so a change of an account that changed meanwhile is refused as `account_changed` by the service. The answer arrives
|
|
282
|
+
* only once the projection shows the result.
|
|
283
|
+
*/
|
|
284
|
+
export interface IReq_ControllerAccountsPriority extends plugins.typedrequestInterfaces.implementsTR<
|
|
285
|
+
plugins.typedrequestInterfaces.ITypedRequest,
|
|
286
|
+
IReq_ControllerAccountsPriority
|
|
287
|
+
> {
|
|
288
|
+
method: 'controller.accounts.priority';
|
|
289
|
+
request: { accountId: string; expectedRevision: number; priority: boolean };
|
|
290
|
+
response: { answer: TControllerAccountsAnswer<TControllerAccount> };
|
|
291
|
+
}
|
|
292
|
+
|
|
276
293
|
/** Duration validation shared with the authority; no implicit duration is supplied. */
|
|
277
294
|
export const isControllerReserveLiftHours = plugins.authswitchAuthority.isAuthSwitchReserveLiftHours;
|
|
278
295
|
|
|
@@ -33,6 +33,7 @@ import type {
|
|
|
33
33
|
IReq_ControllerAccountsSpendLimit,
|
|
34
34
|
IReq_ControllerAccountsClaudeCode,
|
|
35
35
|
IReq_ControllerAccountsRenewal,
|
|
36
|
+
IReq_ControllerAccountsPriority,
|
|
36
37
|
IReq_ControllerAccountsSnapshot,
|
|
37
38
|
IReq_ControllerAccountsUsageGet,
|
|
38
39
|
IReq_ControllerAccountsUsageRecheck,
|
|
@@ -413,6 +414,7 @@ export type TControllerRequest =
|
|
|
413
414
|
| IReq_ControllerAccountsSpendLimit
|
|
414
415
|
| IReq_ControllerAccountsClaudeCode
|
|
415
416
|
| IReq_ControllerAccountsRenewal
|
|
417
|
+
| IReq_ControllerAccountsPriority
|
|
416
418
|
| IReq_ControllerAccountsRemove
|
|
417
419
|
| IReq_ControllerAccountsAdd
|
|
418
420
|
| IReq_ControllerAccountsReauth
|
|
@@ -15,9 +15,11 @@ import * as authswitchSubscription from '../ts_authswitch/authority-subscription
|
|
|
15
15
|
import * as authswitchSpend from '../ts_authswitch/authority-spend.js';
|
|
16
16
|
// A Claude sign-in's monthly renewal: its next one, rolled forward as placement rolls it; it imports nothing.
|
|
17
17
|
import * as authswitchRenewal from '../ts_authswitch/authority-renewal.js';
|
|
18
|
+
// An account's priority as its owner set it: whether it holds now, as placement judges it; it imports nothing.
|
|
19
|
+
import * as authswitchPriority from '../ts_authswitch/authority-priority.js';
|
|
18
20
|
// The service's contract, which the controller's interfaces load already: the processes holding a Claude sign-in, in
|
|
19
21
|
// the words the command line uses.
|
|
20
22
|
import * as authswitchAuthority from '../ts_authswitch/authority-contract.js';
|
|
21
23
|
|
|
22
|
-
export { authswitchAuthority, authswitchPreuseText, authswitchRenewal, authswitchSpend,
|
|
23
|
-
authswitchUsageLimit, authswitchUsageWindows };
|
|
24
|
+
export { authswitchAuthority, authswitchPreuseText, authswitchPriority, authswitchRenewal, authswitchSpend,
|
|
25
|
+
authswitchSubscription, authswitchUsageLimit, authswitchUsageWindows };
|
|
@@ -149,6 +149,8 @@ export type TAccountActionId =
|
|
|
149
149
|
| 'claudeCode'
|
|
150
150
|
| 'renewal'
|
|
151
151
|
| 'clearRenewal'
|
|
152
|
+
| 'priority'
|
|
153
|
+
| 'clearPriority'
|
|
152
154
|
| 'addApiKey'
|
|
153
155
|
| 'remove'
|
|
154
156
|
| 'usage'
|
|
@@ -363,6 +365,13 @@ export interface IAccountRow {
|
|
|
363
365
|
* one and for every other account.
|
|
364
366
|
*/
|
|
365
367
|
renewsAt: string | null;
|
|
368
|
+
/**
|
|
369
|
+
* When the owner's priority on the account ends, while it holds at the view's time (ISO 8601 UTC, AGL-1809), or `null`
|
|
370
|
+
* without one, once it ended and on a removed account.
|
|
371
|
+
*/
|
|
372
|
+
priorityUntil: string | null;
|
|
373
|
+
/** The priority as a badge beside its actions: `Priority until 14:05`, in local time; `null` without one. */
|
|
374
|
+
priorityStatus: IAccountStatus | null;
|
|
366
375
|
/** What a removal does that the owner must know, said with the removal; empty for a sign-in. */
|
|
367
376
|
removeNote: string;
|
|
368
377
|
label: string;
|
|
@@ -1347,12 +1356,27 @@ export const renewalListText = (renewsAtArg: string | null, nowArg: number): str
|
|
|
1347
1356
|
};
|
|
1348
1357
|
|
|
1349
1358
|
/**
|
|
1350
|
-
*
|
|
1351
|
-
*
|
|
1359
|
+
* An account's priority as its row and its page say it (AGL-1809), in the reader's local time: `priority until 14:05`,
|
|
1360
|
+
* or `priority until tomorrow 14:05` when it ends on the next day, since it holds 24 hours at most; empty without one
|
|
1361
|
+
* or once it ended.
|
|
1362
|
+
*/
|
|
1363
|
+
export const priorityText = (priorityUntilArg: string | null, nowArg: number): string => {
|
|
1364
|
+
const until = plugins.authswitchPriority.authSwitchPriorityUntil(priorityUntilArg, nowArg);
|
|
1365
|
+
if (until === null) return '';
|
|
1366
|
+
const end = plugins.authswitchPreuseText.localDateTime(until);
|
|
1367
|
+
const today = plugins.authswitchPreuseText.localDateTime(new Date(nowArg).toISOString()).slice(0, 10);
|
|
1368
|
+
return `priority until ${end.slice(0, 10) === today ? '' : 'tomorrow '}${end.slice(11)}`;
|
|
1369
|
+
};
|
|
1370
|
+
|
|
1371
|
+
/**
|
|
1372
|
+
* The list row's second line: the owner's priority while it holds, then who the account is -- email and plan, or a
|
|
1373
|
+
* key's identity -- and who uses it. A Claude sign-in says when it renews instead of naming the AGL proxy, which every
|
|
1374
|
+
* one of them is used by.
|
|
1352
1375
|
*/
|
|
1353
1376
|
const listMeta = (accountArg: TAccount, chipsArg: readonly IAccountHarnessChip[], nowArg: number): string => {
|
|
1354
1377
|
const claudeSignIn = !isApiKeyAccount(accountArg) && accountArg.providerId === 'anthropic';
|
|
1355
1378
|
return [
|
|
1379
|
+
priorityText(accountArg.priorityUntil, nowArg),
|
|
1356
1380
|
...isApiKeyAccount(accountArg) ? [keyIdentityText(accountArg)] : [
|
|
1357
1381
|
accountArg.email && accountArg.email !== accountArg.label ? accountArg.email : '',
|
|
1358
1382
|
accountArg.plan ? `${accountArg.plan} plan` : '',
|
|
@@ -1593,6 +1617,9 @@ const serviceRow = (
|
|
|
1593
1617
|
const claudeSignIn = !apiKey && accountArg.providerId === 'anthropic';
|
|
1594
1618
|
const provider = keyProvider(accountArg.providerId);
|
|
1595
1619
|
const identity = apiKey ? keyIdentityText(accountArg) : identityText(accountArg.email, accountArg.plan);
|
|
1620
|
+
const priorityUntil = accountArg.removed ? null
|
|
1621
|
+
: plugins.authswitchPriority.authSwitchPriorityUntil(accountArg.priorityUntil, contextArg.now);
|
|
1622
|
+
const priority = priorityText(priorityUntil, contextArg.now);
|
|
1596
1623
|
const liftedUntil = !accountArg.removed && accountArg.maxUsagePercent !== null
|
|
1597
1624
|
&& plugins.authswitchUsageLimit.authSwitchReserveLiftActive(accountArg.reserveLiftUntil, contextArg.now)
|
|
1598
1625
|
? accountArg.reserveLiftUntil! : null;
|
|
@@ -1607,6 +1634,8 @@ const serviceRow = (
|
|
|
1607
1634
|
spendLimitMicroUsd: apiKey ? accountArg.spendLimitMicroUsd : null,
|
|
1608
1635
|
claudeCode: accountArg.claudeCode,
|
|
1609
1636
|
renewsAt: claudeSignIn ? accountArg.renewsAt : null,
|
|
1637
|
+
priorityUntil,
|
|
1638
|
+
priorityStatus: priority ? { text: `${priority.charAt(0).toUpperCase()}${priority.slice(1)}`, tone: 'info' } : null,
|
|
1610
1639
|
removeNote: apiKey
|
|
1611
1640
|
? `AGL stops using the key. It stays valid at ${provider.name} until you revoke it in ${provider.console}.`
|
|
1612
1641
|
: '',
|
|
@@ -1663,6 +1692,11 @@ const serviceRow = (
|
|
|
1663
1692
|
? [serviceSlot('liftReserve', 'Lift reserve', 'lucide:Clock', contextArg.service, removed)] : []),
|
|
1664
1693
|
// A renewal is a Claude subscription's: neither a key nor a ChatGPT account has one to set.
|
|
1665
1694
|
...(claudeSignIn ? [serviceSlot('renewal', 'Renewal', 'lucide:CalendarClock', contextArg.service, removed)] : []),
|
|
1695
|
+
// Any account can have priority; giving it again starts its 24 hours again.
|
|
1696
|
+
serviceSlot('priority', priorityUntil === null ? 'Give priority' : 'Restart 24 hours', 'lucide:Star',
|
|
1697
|
+
contextArg.service, removed),
|
|
1698
|
+
...(priorityUntil === null ? []
|
|
1699
|
+
: [serviceSlot('clearPriority', 'Turn off', 'lucide:StarOff', contextArg.service, removed)]),
|
|
1666
1700
|
serviceSlot('remove', 'Remove', 'lucide:Trash2', contextArg.service, removed),
|
|
1667
1701
|
...(usageLogin ? [serviceSlot('usage', 'Show latest usage', 'lucide:Gauge', contextArg.service)] : []),
|
|
1668
1702
|
...(usageLogin && payment ? [serviceSlot('recheck', 'Re-check', 'lucide:RotateCcw', contextArg.service)] : []),
|