paseo-plugin-account-switcher 0.5.0 → 0.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/OVERVIEW.md +5 -2
- package/OVERVIEW.zh-CN.md +5 -2
- package/README.md +43 -7
- package/assets/icon.png +0 -0
- package/client/accounts.tsx +10 -1
- package/client/command.ts +64 -0
- package/client/note.tsx +13 -0
- package/client/runtime.ts +19 -2
- package/client/switcher.tsx +1 -1
- package/index.client.tsx +20 -1
- package/index.server.ts +54 -5
- package/npm-shrinkwrap.json +2 -2
- package/package.json +2 -1
- package/paseo-plugin.json +1 -1
- package/server/controller.ts +2 -2
- package/server/launcher-artifact.ts +1 -1
- package/server/selection.ts +49 -0
- package/server/store.ts +3 -1
- package/server/switching.ts +28 -8
- package/server/timeline.ts +12 -0
- package/server/usage/index.ts +3 -3
- package/server/usage/parsers.ts +10 -6
- package/shared/contracts.ts +8 -1
- package/shared/timeline.ts +27 -0
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import type { UsageSnapshot, UsageWindow } from "../shared/contracts";
|
|
2
|
+
|
|
3
|
+
export type SelectionAccount = { id: string; authStatus: string; loginToken?: string | null };
|
|
4
|
+
export type Blocker = "exhausted" | "model";
|
|
5
|
+
|
|
6
|
+
// Only limits that stop every request of the account count; a model's own week or extra paid usage do not.
|
|
7
|
+
const binding = (window: UsageWindow) => window.scope === "account";
|
|
8
|
+
const inEffect = (window: UsageWindow, now: number) => !window.resetsAt || Date.parse(window.resetsAt) > now;
|
|
9
|
+
|
|
10
|
+
/** Why an account would certainly fail a new agent, from provider-reported data only; null when nothing proves it.
|
|
11
|
+
* A full window proves it only with a known future reset: within a window, use only grows until the reset.
|
|
12
|
+
* The provider's verdict and the plan's model list count only from a fresh reading, since both can change. */
|
|
13
|
+
export function blocker(snapshot: UsageSnapshot | undefined, model: string | null, now: number): Blocker | null {
|
|
14
|
+
if (!snapshot) return null;
|
|
15
|
+
const fresh = snapshot.status === "ok";
|
|
16
|
+
if (fresh && model && snapshot.models && !snapshot.models.includes(model)) return "model";
|
|
17
|
+
if (fresh && snapshot.usageAllowed === false) return "exhausted";
|
|
18
|
+
if (snapshot.status !== "ok" && snapshot.status !== "stale") return null;
|
|
19
|
+
return snapshot.windows.some(window => binding(window) && window.usedPercent !== null && window.usedPercent >= 100 && window.resetsAt !== null && inEffect(window, now)) ? "exhausted" : null;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** Percent left in the tightest account-wide window still in effect, or null without data. */
|
|
23
|
+
export function room(snapshot: UsageSnapshot | undefined, now: number): number | null {
|
|
24
|
+
const left = (snapshot?.windows ?? []).filter(window => binding(window) && window.usedPercent !== null && inEffect(window, now)).map(window => 100 - window.usedPercent!);
|
|
25
|
+
return left.length ? Math.max(0, Math.min(...left)) : null;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** Accounts a new agent tries, in order. The default leads unless provider data shows it would fail;
|
|
29
|
+
* then signed-in accounts follow by room, unknown room last, and the default stays as the last resort. */
|
|
30
|
+
export function launchOrder(input: { defaultId: string; accounts: readonly SelectionAccount[]; usage: readonly UsageSnapshot[]; model: string | null; now: number }): string[] {
|
|
31
|
+
const { defaultId, accounts, usage, now } = input;
|
|
32
|
+
const snapshotOf = (id: string) => usage.find(item => item.accountId === id);
|
|
33
|
+
// The hint is the requested model, before Paseo resolves aliases; one no account lists proves nothing.
|
|
34
|
+
const known = accounts.some(account => snapshotOf(account.id)?.models?.includes(input.model ?? ""));
|
|
35
|
+
const model = known ? input.model : null;
|
|
36
|
+
const spares = accounts
|
|
37
|
+
.filter(account => account.id !== defaultId && !account.loginToken && account.authStatus === "ready" && !blocker(snapshotOf(account.id), model, now))
|
|
38
|
+
.map((account, index) => ({ id: account.id, index, room: room(snapshotOf(account.id), now) }))
|
|
39
|
+
.sort((a, b) => (b.room ?? -1) - (a.room ?? -1) || a.index - b.index)
|
|
40
|
+
.map(account => account.id);
|
|
41
|
+
return blocker(snapshotOf(defaultId), model, now) ? [...spares, defaultId] : [defaultId, ...spares];
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** Why the default was passed over, with the same evidence `launchOrder` used. */
|
|
45
|
+
export function defaultBlocker(input: Parameters<typeof launchOrder>[0]): Blocker | null {
|
|
46
|
+
const snapshotOf = (id: string) => input.usage.find(item => item.accountId === id);
|
|
47
|
+
const known = input.accounts.some(account => snapshotOf(account.id)?.models?.includes(input.model ?? ""));
|
|
48
|
+
return blocker(snapshotOf(input.defaultId), known ? input.model : null, input.now);
|
|
49
|
+
}
|
package/server/store.ts
CHANGED
|
@@ -13,6 +13,8 @@ const CommandsSchema = z.object({ claude: z.array(z.string()).nullable(), codex:
|
|
|
13
13
|
export const RegistrySchema = z.object({
|
|
14
14
|
version: z.literal(1), accounts: z.array(StoredAccountSchema), bindings: z.array(StoredBindingSchema),
|
|
15
15
|
defaults: z.object({claude:z.string().nullable(),codex:z.string().nullable()}),
|
|
16
|
+
// Whether a new agent may start on another account when the default would fail; registries before 0.7 had no choice and default to on.
|
|
17
|
+
fallback: z.object({claude:z.boolean(),codex:z.boolean()}).default({claude:true,codex:true}),
|
|
16
18
|
sourceHomes: z.object({claude:z.string(),codex:z.string()}),
|
|
17
19
|
sourceEnvironment: z.object({claude:z.object({CLAUDE_CONFIG_DIR:z.string().optional(),CLAUDE_SECURESTORAGE_CONFIG_DIR:z.string().optional()}),codex:z.object({CODEX_HOME:z.string().optional()})}).default({claude:{},codex:{}}),
|
|
18
20
|
commands: CommandsSchema, originalCommands: CommandsSchema,
|
|
@@ -61,7 +63,7 @@ export class AccountStore {
|
|
|
61
63
|
async snapshot():Promise<AccountState> {
|
|
62
64
|
const state=await this.read();
|
|
63
65
|
const status=(provider:Provider)=>({available:state.available[provider],integrated:state.integration.enabled&&state.integration.providers.includes(provider)});
|
|
64
|
-
return { accounts:state.accounts.map(a=>AccountSchema.parse(a)),bindings:state.bindings.map(b=>BindingSchema.parse(b)),defaults:state.defaults,integration:{enabled:state.integration.enabled,error:state.integration.error},providers:{claude:status("claude"),codex:status("codex")} };
|
|
66
|
+
return { accounts:state.accounts.map(a=>AccountSchema.parse(a)),bindings:state.bindings.map(b=>BindingSchema.parse(b)),defaults:state.defaults,fallback:state.fallback,integration:{enabled:state.integration.enabled,error:state.integration.error},providers:{claude:status("claude"),codex:status("codex")} };
|
|
65
67
|
}
|
|
66
68
|
async add(provider:Provider,label:string):Promise<StoredAccount> {
|
|
67
69
|
return this.change(state=>{const account:StoredAccount={id:randomUUID(),provider,label:label.trim(),source:"managed",home:"",email:null,plan:null,authStatus:"needs_auth",createdAt:new Date().toISOString(),identityKey:null,generation:0,loginToken:null};account.home=join(this.root,"accounts",account.id,provider);state.accounts.push(account);return account;});
|
package/server/switching.ts
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { randomUUID } from "node:crypto";
|
|
2
2
|
import { readFile } from "node:fs/promises";
|
|
3
3
|
import { join } from "node:path";
|
|
4
|
-
import { BindingSchema, cliName, type Binding, type Provider } from "../shared/contracts";
|
|
4
|
+
import { BindingSchema, cliName, type Binding, type Provider, type UsageSnapshot } from "../shared/contracts";
|
|
5
|
+
import { defaultBlocker, launchOrder, type Blocker } from "./selection";
|
|
5
6
|
import { AccountStore, accountFrom, type StoredBinding } from "./store";
|
|
6
7
|
|
|
7
8
|
export interface SwitchDependencies {
|
|
@@ -9,6 +10,8 @@ export interface SwitchDependencies {
|
|
|
9
10
|
inspect:(agentId:string)=>Promise<{provider:string;busy:boolean;archived:boolean}>;
|
|
10
11
|
checkAccount:(accountId:string)=>Promise<{authStatus:string}>;
|
|
11
12
|
reload:(agentId:string)=>Promise<void>;
|
|
13
|
+
/** Last known limits; read from the cache, so creating an agent never waits for a provider. */
|
|
14
|
+
usage?:()=>Promise<UsageSnapshot[]>;
|
|
12
15
|
applying?:Set<string>;
|
|
13
16
|
receiptTimeoutMs?:number;
|
|
14
17
|
}
|
|
@@ -33,7 +36,8 @@ export class SwitchService {
|
|
|
33
36
|
if(agent.provider!=="claude"&&agent.provider!=="codex")throw new Error("Only Claude and Codex are supported.");
|
|
34
37
|
return BindingSchema.parse(await this.deps.store.prepare(agentId,agent.provider,accountId));
|
|
35
38
|
}
|
|
36
|
-
|
|
39
|
+
/** `expected` is the account the caller showed or named; another client's later selection must not be applied in its place. */
|
|
40
|
+
async apply(agentId:string,expected?:string):Promise<Binding>{
|
|
37
41
|
if(this.applying.has(agentId))throw new Error("An account switch is already in progress.");
|
|
38
42
|
this.applying.add(agentId);
|
|
39
43
|
let previous:StoredBinding|undefined;
|
|
@@ -43,6 +47,7 @@ export class SwitchService {
|
|
|
43
47
|
if(!state.integration.enabled)throw new Error("Enable account integration first.");
|
|
44
48
|
const selected=state.bindings.find(b=>b.agentId===agentId);
|
|
45
49
|
if(!selected?.pendingAccountId)throw new Error("Select an account first.");
|
|
50
|
+
if(expected&&selected.pendingAccountId!==expected)throw new Error("The account selection changed; try again.");
|
|
46
51
|
const target=accountFrom(state,selected.pendingAccountId);
|
|
47
52
|
// Without the launcher in its command, the provider would never confirm the new account.
|
|
48
53
|
if(!state.integration.providers.includes(target.provider))throw new Error(`Account switching is off for ${cliName[target.provider]}. Enable integration again to include it.`);
|
|
@@ -73,19 +78,34 @@ export class SwitchService {
|
|
|
73
78
|
throw error;
|
|
74
79
|
} finally {this.applying.delete(agentId);}
|
|
75
80
|
}
|
|
76
|
-
|
|
81
|
+
/** Binds a new agent to the default account, or to the next usable one when provider data shows the default would fail. */
|
|
82
|
+
async bindNewAgent(agentId:string,provider:Provider,model:string|null=null):Promise<{accountId:string;defaultId:string;reason:Blocker|"sign-in"|"unverified"|null}|undefined>{
|
|
77
83
|
const state=await this.deps.store.read();
|
|
78
84
|
if(!state.integration.enabled||!state.integration.providers.includes(provider)||state.bindings.some(b=>b.agentId===agentId))return;
|
|
79
85
|
const selected=state.defaults[provider];if(!selected)return;
|
|
80
86
|
const account=accountFrom(state,selected);
|
|
81
87
|
if(account.provider!==provider)throw new Error("The default account belongs to another provider.");
|
|
82
88
|
if(account.loginToken)throw new Error("Default account sign-in is still in progress.");
|
|
83
|
-
|
|
84
|
-
|
|
89
|
+
const usage=await this.deps.usage?.().catch(()=>[])??[];
|
|
90
|
+
const evidence={defaultId:selected,accounts:state.accounts.filter(a=>a.provider===provider),usage,model,now:Date.now()};
|
|
91
|
+
let chosen:string|undefined,defaultStatus:string|undefined;
|
|
92
|
+
// With fallback off the default is binding, as before 0.7: the agent starts there or not at all.
|
|
93
|
+
for(const id of state.fallback[provider]?launchOrder(evidence):[selected]){
|
|
94
|
+
const {authStatus}=await this.deps.checkAccount(id);
|
|
95
|
+
if(id===selected)defaultStatus=authStatus;
|
|
96
|
+
if(authStatus==="ready"){chosen=id;break;}
|
|
97
|
+
}
|
|
98
|
+
if(!chosen)throw new Error("The default account requires authentication. Sign in or select another default account.");
|
|
99
|
+
// Only the official probe's `needs_auth` means sign-in; a timeout or an unknown answer is reported as unverified.
|
|
100
|
+
const reason=chosen===selected?null:defaultBlocker(evidence)??(defaultStatus==="needs_auth"?"sign-in":"unverified");
|
|
101
|
+
if(reason)console.log(`New agent ${agentId}: the default ${provider} account would fail (${reason}); starting on account ${chosen}.`);
|
|
102
|
+
const bound=await this.deps.store.change(r=>{
|
|
85
103
|
if(!r.integration.enabled||!r.integration.providers.includes(provider)||r.bindings.some(b=>b.agentId===agentId))return;
|
|
86
|
-
|
|
87
|
-
if(accountFrom(r,
|
|
88
|
-
r.bindings.push({agentId,provider,currentAccountId:null,pendingAccountId:null,launchAccountId:
|
|
104
|
+
if(r.defaults[provider]!==selected)throw new Error("The default account changed; create the agent again.");
|
|
105
|
+
if(accountFrom(r,chosen).loginToken)throw new Error("Account sign-in is still in progress.");
|
|
106
|
+
r.bindings.push({agentId,provider,currentAccountId:null,pendingAccountId:null,launchAccountId:chosen,launchToken:randomUUID(),status:"ready",error:null,registrationObserved:false});
|
|
107
|
+
return true;
|
|
89
108
|
});
|
|
109
|
+
return bound?{accountId:chosen,defaultId:selected,reason}:undefined;
|
|
90
110
|
}
|
|
91
111
|
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import type { PaseoApi } from "./paseo-api";
|
|
3
|
+
import { ACCOUNT_NOTE_KIND, ACCOUNT_NOTE_VERSION, type AccountNote } from "../shared/timeline";
|
|
4
|
+
|
|
5
|
+
/** Records the agent's account in its timeline. A host that refuses the row never fails the switch itself. */
|
|
6
|
+
export async function appendAccountNote(paseo: PaseoApi, agentId: string, note: AccountNote): Promise<void> {
|
|
7
|
+
try {
|
|
8
|
+
await paseo.agents.ref(agentId).timeline.append({ type: "plugin", id: `${ACCOUNT_NOTE_KIND}-${randomUUID()}`, kind: ACCOUNT_NOTE_KIND, version: ACCOUNT_NOTE_VERSION, data: note });
|
|
9
|
+
} catch (error) {
|
|
10
|
+
console.error(`Could not add the account note to agent ${agentId}: ${error instanceof Error ? error.message : String(error)}`);
|
|
11
|
+
}
|
|
12
|
+
}
|
package/server/usage/index.ts
CHANGED
|
@@ -8,7 +8,7 @@ import { object } from "./parsers";
|
|
|
8
8
|
|
|
9
9
|
export type QuotaAccount = { id: string; provider: Provider; home: string; command: string[]; env: NodeJS.ProcessEnv; identityKey: string | null; generation: number; credentialVersion?: string; identityCredentialVersion?: string; requireIdentityVerification?: boolean };
|
|
10
10
|
export { readCredentialVersion } from "./credentials";
|
|
11
|
-
export type CollectedUsage = { identityKey: string | null; plan: string | null; windows: UsageWindow[]; models?: string[] | null };
|
|
11
|
+
export type CollectedUsage = { identityKey: string | null; plan: string | null; windows: UsageWindow[]; models?: string[] | null; usageAllowed?: boolean | null };
|
|
12
12
|
export type FetchUsage = (account: QuotaAccount, signal?: AbortSignal) => Promise<CollectedUsage>;
|
|
13
13
|
export type AccountReadOptions = { verifyAccountId?: string };
|
|
14
14
|
export type UsageOptions = { getAccounts: (input?: AccountReadOptions) => Promise<QuotaAccount[]>; fetchUsage?: FetchUsage; cachePath?: string; now?: () => number };
|
|
@@ -161,7 +161,7 @@ export function createUsageService(options: UsageOptions) {
|
|
|
161
161
|
if(requested&&account.credentialVersion!==verified.credentialVersion&&(!identityProven(account)||!identityProven(verified)||result?.identityKey!==account.identityKey))failure??=new UsageError("unavailable","response_identity_unverified");
|
|
162
162
|
const checkedAt = new Date(now()).toISOString();
|
|
163
163
|
if (result && !failure) {
|
|
164
|
-
const snapshot: UsageSnapshot = {accountId:account.id,provider:account.provider,status:"ok",plan:result.plan,windows:result.windows,models:result.models??null,fetchedAt:checkedAt,checkedAt,nextRetryAt:null,error:null};
|
|
164
|
+
const snapshot: UsageSnapshot = {accountId:account.id,provider:account.provider,status:"ok",plan:result.plan,windows:result.windows,models:result.models??null,usageAllowed:result.usageAllowed??null,fetchedAt:checkedAt,checkedAt,nextRetryAt:null,error:null};
|
|
165
165
|
entry.snapshot=snapshot;entry.success=account.identityKey===null?undefined:snapshot;entry.attempts=0;entry.retryAt=0;
|
|
166
166
|
} else {
|
|
167
167
|
const error=failure??new UsageError("unavailable","request_failed");
|
|
@@ -170,7 +170,7 @@ export function createUsageService(options: UsageOptions) {
|
|
|
170
170
|
entry.retryAt=now()+backoff;
|
|
171
171
|
if (error.status==="needs_auth") entry.success=undefined;
|
|
172
172
|
const previous=entry.success;
|
|
173
|
-
entry.snapshot={accountId:account.id,provider:account.provider,status:error.status==="needs_auth"?"needs_auth":previous?"stale":"unavailable",plan:previous?.plan??null,windows:previous?.windows??[],models:previous?.models??null,fetchedAt:previous?.fetchedAt??null,checkedAt,nextRetryAt:new Date(entry.retryAt).toISOString(),error:error.message};
|
|
173
|
+
entry.snapshot={accountId:account.id,provider:account.provider,status:error.status==="needs_auth"?"needs_auth":previous?"stale":"unavailable",plan:previous?.plan??null,windows:previous?.windows??[],models:previous?.models??null,usageAllowed:previous?.usageAllowed??null,fetchedAt:previous?.fetchedAt??null,checkedAt,nextRetryAt:new Date(entry.retryAt).toISOString(),error:error.message};
|
|
174
174
|
}
|
|
175
175
|
await persist();
|
|
176
176
|
} finally { release(); }
|
package/server/usage/parsers.ts
CHANGED
|
@@ -27,17 +27,20 @@ export function parseCodexUsage(payload: unknown): CollectedUsage {
|
|
|
27
27
|
const map = object(root.rateLimitsByLimitId);
|
|
28
28
|
const fallback = object(root.rateLimits);
|
|
29
29
|
const buckets = map && Object.keys(map).length ? Object.entries(map) : fallback ? [[string(fallback.limitId) ?? "codex", fallback] as const] : [];
|
|
30
|
+
// `rateLimits` is the account's main bucket; others, such as a model's own bucket, limit only that model.
|
|
31
|
+
const main = string(fallback?.limitId) ?? (buckets.length === 1 ? buckets[0][0] : null);
|
|
30
32
|
const windows: UsageWindow[] = [];
|
|
31
33
|
let plan: string | null = null;
|
|
32
34
|
for (const [id, candidate] of buckets) {
|
|
33
35
|
const bucket = object(candidate);
|
|
34
36
|
if (!bucket) continue;
|
|
35
37
|
plan ??= string(bucket.planType);
|
|
38
|
+
const scope = id === main ? "account" as const : "model" as const;
|
|
36
39
|
for (const key of ["primary", "secondary"]) {
|
|
37
40
|
const window = object(bucket[key]);
|
|
38
41
|
if (!window) continue;
|
|
39
42
|
const duration = numeric(window.windowDurationMins);
|
|
40
|
-
windows.push({ id: `${id}:${key}`, label: `${string(bucket.limitName) ?? id} · ${durationLabel(duration, key)}`, usedPercent: numeric(window.usedPercent), windowDurationMins: duration, resetsAt: date(window.resetsAt, true) });
|
|
43
|
+
windows.push({ id: `${id}:${key}`, label: `${string(bucket.limitName) ?? id} · ${durationLabel(duration, key)}`, usedPercent: numeric(window.usedPercent), windowDurationMins: duration, resetsAt: date(window.resetsAt, true), scope });
|
|
41
44
|
}
|
|
42
45
|
// Usage-based workspaces (e.g. enterprise_cbp_usage_based) report a monthly credit allowance instead of windows.
|
|
43
46
|
const spend = object(bucket.individualLimit);
|
|
@@ -46,10 +49,10 @@ export function parseCodexUsage(payload: unknown): CollectedUsage {
|
|
|
46
49
|
const limit = amount(spend.limit);
|
|
47
50
|
const used = amount(spend.used);
|
|
48
51
|
windows.push({ id: `${id}:individual`, label: `${string(bucket.limitName) ?? id} · monthly credits`, usedPercent: 100 - Math.min(100, remaining), windowDurationMins: null, resetsAt: date(spend.resetsAt, true),
|
|
49
|
-
detail: limit !== null && used !== null ? `${credits(Math.max(0, limit - used))} of ${credits(limit)} credits left` : null });
|
|
52
|
+
detail: limit !== null && used !== null ? `${credits(Math.max(0, limit - used))} of ${credits(limit)} credits left` : null, scope });
|
|
50
53
|
}
|
|
51
54
|
}
|
|
52
|
-
return { identityKey: string(root.accountId), plan, windows };
|
|
55
|
+
return { identityKey: string(root.accountId), plan, windows, usageAllowed: typeof root.ordinaryUsageAllowed === "boolean" ? root.ordinaryUsageAllowed : null };
|
|
53
56
|
}
|
|
54
57
|
|
|
55
58
|
export function parseClaudeUsage(payload: unknown): CollectedUsage {
|
|
@@ -61,7 +64,8 @@ export function parseClaudeUsage(payload: unknown): CollectedUsage {
|
|
|
61
64
|
if (value !== null && !row) continue;
|
|
62
65
|
const weekly = key !== "five_hour";
|
|
63
66
|
const suffix = key.slice("seven_day_".length).replaceAll("_", " ");
|
|
64
|
-
windows.push({ id: key, label: !weekly ? "5 hours" : key === "seven_day" ? "Weekly" : `Weekly · ${suffix}`, usedPercent: numeric(row?.utilization), windowDurationMins: weekly ? 10080 : 300, resetsAt: date(row?.resets_at)
|
|
67
|
+
windows.push({ id: key, label: !weekly ? "5 hours" : key === "seven_day" ? "Weekly" : `Weekly · ${suffix}`, usedPercent: numeric(row?.utilization), windowDurationMins: weekly ? 10080 : 300, resetsAt: date(row?.resets_at),
|
|
68
|
+
scope: key === "five_hour" || key === "seven_day" ? "account" : "model" });
|
|
65
69
|
}
|
|
66
70
|
if (Array.isArray(root.limits)) for (const [index, value] of root.limits.entries()) {
|
|
67
71
|
const row = object(value);
|
|
@@ -71,7 +75,7 @@ export function parseClaudeUsage(payload: unknown): CollectedUsage {
|
|
|
71
75
|
const surface = object(scope?.surface);
|
|
72
76
|
const labels = [string(model?.display_name) ?? string(scope?.model), string(surface?.display_name) ?? string(scope?.surface)].filter((s): s is string => !!s);
|
|
73
77
|
if (!labels.length) continue;
|
|
74
|
-
windows.push({ id: `weekly_scoped:${index}`, label: `Weekly · ${labels.join(" · ")}`, usedPercent: numeric(row.percent), windowDurationMins: 10080, resetsAt: date(row.resets_at) });
|
|
78
|
+
windows.push({ id: `weekly_scoped:${index}`, label: `Weekly · ${labels.join(" · ")}`, usedPercent: numeric(row.percent), windowDurationMins: 10080, resetsAt: date(row.resets_at), scope: "model" });
|
|
75
79
|
}
|
|
76
80
|
// Enterprise seats report a monthly spend allowance; amounts are in minor units of `currency`.
|
|
77
81
|
const extra = object(root.extra_usage);
|
|
@@ -82,7 +86,7 @@ export function parseClaudeUsage(payload: unknown): CollectedUsage {
|
|
|
82
86
|
const currency = string(extra.currency) ?? "USD";
|
|
83
87
|
const money = (value: number) => { try { return (value / scale).toLocaleString("en-US", { style: "currency", currency }); } catch { return `${(value / scale).toFixed(2)} ${currency}`; } };
|
|
84
88
|
const spend: UsageWindow = { id: "extra_usage", label: "Monthly spend", usedPercent: numeric(extra.utilization) ?? (used === null ? null : used / limit * 100), windowDurationMins: null, resetsAt: null,
|
|
85
|
-
detail: used === null ? null : `${money(Math.max(0, limit - used))} of ${money(limit)} left
|
|
89
|
+
detail: used === null ? null : `${money(Math.max(0, limit - used))} of ${money(limit)} left`, scope: "spend" };
|
|
86
90
|
// Without any plan limits the empty plan rows are noise; the spend allowance is the only quota.
|
|
87
91
|
return { identityKey: null, plan: null, windows: windows.some((quota) => quota.usedPercent !== null) ? [...windows, spend] : [spend] };
|
|
88
92
|
}
|
package/shared/contracts.ts
CHANGED
|
@@ -33,6 +33,7 @@ export type ProviderStatus = z.infer<typeof ProviderStatusSchema>;
|
|
|
33
33
|
export const StateSchema = z.object({
|
|
34
34
|
accounts: z.array(AccountSchema), bindings: z.array(BindingSchema),
|
|
35
35
|
defaults: z.object({ claude: z.string().nullable(), codex: z.string().nullable() }),
|
|
36
|
+
fallback: z.object({ claude: z.boolean(), codex: z.boolean() }).default({ claude: true, codex: true }),
|
|
36
37
|
integration: z.object({ enabled: z.boolean(), error: z.string().nullable() }),
|
|
37
38
|
providers: z.object({ claude: ProviderStatusSchema, codex: ProviderStatusSchema }),
|
|
38
39
|
});
|
|
@@ -42,6 +43,8 @@ export const UsageWindowSchema = z.object({
|
|
|
42
43
|
windowDurationMins: z.number().nullable(), resetsAt: z.string().nullable(),
|
|
43
44
|
// Provider-reported amounts behind the percentage, such as "3,765 of 5,000 credits left".
|
|
44
45
|
detail: z.string().nullable().optional(),
|
|
46
|
+
// What a full window stops: every request of the account, one model's requests, or extra paid usage.
|
|
47
|
+
scope: z.enum(["account", "model", "spend"]).optional(),
|
|
45
48
|
});
|
|
46
49
|
export type UsageWindow = z.infer<typeof UsageWindowSchema>;
|
|
47
50
|
export const UsageSnapshotSchema = z.object({
|
|
@@ -50,6 +53,8 @@ export const UsageSnapshotSchema = z.object({
|
|
|
50
53
|
plan: z.string().nullable(), windows: z.array(UsageWindowSchema),
|
|
51
54
|
// Model IDs the account's plan offers; null or absent when the provider does not list them.
|
|
52
55
|
models: z.array(z.string()).nullable().optional(),
|
|
56
|
+
// The provider's own verdict that ordinary usage is allowed (Codex `ordinaryUsageAllowed`); null when not reported.
|
|
57
|
+
usageAllowed: z.boolean().nullable().optional(),
|
|
53
58
|
fetchedAt: z.string().nullable(), checkedAt: z.string(), nextRetryAt: z.string().nullable(),
|
|
54
59
|
error: z.string().nullable(),
|
|
55
60
|
});
|
|
@@ -61,13 +66,15 @@ export const addAccount = defineRpc({ name: "accounts.add", input: z.object({ pr
|
|
|
61
66
|
export const renameAccount = defineRpc({ name: "accounts.rename", input: AccountId.extend({ label: z.string().trim().min(1).max(80) }), output: AccountSchema });
|
|
62
67
|
export const removeAccount = defineRpc({ name: "accounts.remove", input: AccountId, output: Empty });
|
|
63
68
|
export const setDefaultAccount = defineRpc({ name: "accounts.default", input: z.object({ provider: ProviderSchema, accountId: z.string().nullable() }), output: Empty });
|
|
69
|
+
export const setFallback = defineRpc({ name: "accounts.fallback", input: z.object({ provider: ProviderSchema, enabled: z.boolean() }), output: Empty });
|
|
64
70
|
export const startLogin = defineRpc({ name: "auth.start", input: AccountId.extend({ mode: LoginModeSchema.optional() }), output: LoginSessionSchema });
|
|
65
71
|
export const getLoginStatus = defineRpc({ name: "auth.status", input: AccountId.extend({ sessionId: z.string().min(1) }), output: LoginSessionSchema });
|
|
66
72
|
export const submitLoginCode = defineRpc({ name: "auth.submit-code", input: AccountId.extend({ sessionId: z.string().min(1), code: z.string().trim().min(1).max(2048) }), output: LoginSessionSchema });
|
|
67
73
|
export const checkLogin = defineRpc({ name: "auth.check", input: AccountId, output: AccountSchema });
|
|
68
74
|
export const cancelLogin = defineRpc({ name: "auth.cancel", input: AccountId.extend({ sessionId: z.string().min(1).optional() }), output: AccountSchema });
|
|
69
75
|
export const prepareSwitch = defineRpc({ name: "switch.prepare", input: z.object({ agentId: z.string().min(1), accountId: z.string().nullable() }), output: BindingSchema });
|
|
70
|
-
|
|
76
|
+
// `accountId`: the selection the caller saw; the switch is refused when another client changed it since.
|
|
77
|
+
export const applySwitch = defineRpc({ name: "switch.apply", input: z.object({ agentId: z.string().min(1), accountId: z.string().min(1).optional() }), output: BindingSchema });
|
|
71
78
|
export const setIntegration = defineRpc({ name: "integration.set", input: z.object({ enabled: z.boolean() }), output: StateSchema });
|
|
72
79
|
export const listUsage = defineRpc({ name: "usage.list", input: z.object({ visible: z.boolean().optional() }), output: z.object({ accounts: z.array(UsageSnapshotSchema) }) });
|
|
73
80
|
export const refreshUsage = defineRpc({ name: "usage.refresh", input: z.object({ accountId: z.string().optional() }), output: z.object({ accounts: z.array(UsageSnapshotSchema) }) });
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
|
|
3
|
+
/** A plugin row in an agent's timeline recording which account it runs on and why. */
|
|
4
|
+
export const ACCOUNT_NOTE_KIND = "account-note";
|
|
5
|
+
export const ACCOUNT_NOTE_VERSION = 1;
|
|
6
|
+
|
|
7
|
+
export const AccountNoteSchema = z.object({
|
|
8
|
+
kind: z.enum(["switched", "started"]),
|
|
9
|
+
from: z.string().nullable(),
|
|
10
|
+
to: z.string(),
|
|
11
|
+
// Why a new agent did not start on the default; null for a switch the user applied.
|
|
12
|
+
reason: z.enum(["exhausted", "model", "sign-in", "unverified"]).nullable(),
|
|
13
|
+
});
|
|
14
|
+
export type AccountNote = z.infer<typeof AccountNoteSchema>;
|
|
15
|
+
|
|
16
|
+
const why: Record<NonNullable<AccountNote["reason"]>, (from: string) => string> = {
|
|
17
|
+
exhausted: (from) => `the default ${from} has used up a limit`,
|
|
18
|
+
model: (from) => `the default ${from}'s plan does not offer this agent's model`,
|
|
19
|
+
"sign-in": (from) => `the default ${from} needs sign-in`,
|
|
20
|
+
unverified: (from) => `the default ${from} could not be checked`,
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
export function noteText(note: AccountNote): string {
|
|
24
|
+
if (note.kind === "switched") return note.from ? `Account switched from ${note.from} to ${note.to}.` : `Account switched to ${note.to}.`;
|
|
25
|
+
// Written before the CLI confirms its launch, so it says where the agent is starting, not where it started.
|
|
26
|
+
return note.reason && note.from ? `Starting on ${note.to}: ${why[note.reason](note.from)}.` : `Starting on ${note.to}.`;
|
|
27
|
+
}
|