paseo-plugin-account-switcher 0.7.0 → 0.8.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.
@@ -0,0 +1,126 @@
1
+ import type { PluginServerContext } from "@getpaseo/plugin/server";
2
+ import { hashAccountKey, windowFromReportedDuration, type UsageAccount, type UsageDetail, type UsageReport, type UsageScope, type UsageWindow as PaseoWindow } from "@getpaseo/plugin/server/usage";
3
+ import { z } from "zod";
4
+ import { cliName, type Provider, type UsageSnapshot, type UsageWindow } from "../shared/contracts";
5
+ import type { Registry } from "./store";
6
+
7
+ // Paseo's Usage view lists every source's accounts side by side. This source adds the managed accounts, from the limits the plugin already collects.
8
+ const SOURCE_ID = "account-switcher";
9
+ const KEY_PATTERN = /^[A-Za-z0-9._-]{1,128}$/;
10
+ // A store locator for `fetch`, never a credential.
11
+ const InputSchema = z.object({ accountId: z.string().min(1) });
12
+
13
+ /** The part of AccountController this source reads; the controller satisfies it. */
14
+ export interface UsageController {
15
+ ready: Promise<void>;
16
+ store: { read(): Promise<Pick<Registry, "accounts">> };
17
+ usage: { list(): Promise<UsageSnapshot[]> };
18
+ }
19
+
20
+ /**
21
+ * Paseo's stable key for an account: the Codex account ID as is, a Claude identity with its `provider:` prefix written `provider-`.
22
+ * Anything Paseo would refuse (an email, a long or empty value) is replaced by a hash, so the key never exposes the identity.
23
+ */
24
+ export function usageKey(provider: Provider, identityKey: string): string {
25
+ const prefix = `${provider}:`;
26
+ const key = identityKey.startsWith(prefix) ? `${provider}-${identityKey.slice(prefix.length)}` : identityKey;
27
+ return KEY_PATTERN.test(key) ? key : hashAccountKey(identityKey);
28
+ }
29
+
30
+ /**
31
+ * Managed accounts for the Usage view's global list. The system account is left to Paseo's built-in source, and so is any managed account signed in as that same login.
32
+ * The session scope is also left to the built-in source: the account profile in an agent's environment (see session-env.ts) already points it at the right login.
33
+ */
34
+ export function discoverAccounts(registry: Pick<Registry, "accounts">, scope: UsageScope): UsageAccount[] {
35
+ if (scope.kind !== "global") return [];
36
+ const systemIdentity = (provider: Provider) => registry.accounts.find(a => a.source === "system" && a.provider === provider)?.identityKey ?? null;
37
+ const found = new Map<string, UsageAccount>();
38
+ for (const account of registry.accounts) {
39
+ // `loginToken` marks a sign-in still in progress. An `error` status is a failed check, so the last limits stay worth showing.
40
+ if (account.source !== "managed" || account.authStatus === "needs_auth" || account.loginToken || !account.identityKey) continue;
41
+ if (account.identityKey === systemIdentity(account.provider)) continue;
42
+ const key = usageKey(account.provider, account.identityKey);
43
+ // Two accounts signed in as one login are one account to Paseo, which wants unique keys.
44
+ if (found.has(key)) continue;
45
+ found.set(key, { key, label: account.label, harness: cliName[account.provider], input: { accountId: account.id } });
46
+ }
47
+ return [...found.values()];
48
+ }
49
+
50
+ // Without a reported duration the Codex collector labels a window by its response slot ("codex · primary"). A slot says where the window sat in the response, not which quota it is.
51
+ const SLOT = / · (?:primary|secondary)$/;
52
+
53
+ /**
54
+ * A window's quota name for Paseo's ids, which pinned windows are matched by. It comes from the label, which names the quota
55
+ * and (for model windows) its period. The collectors' window IDs do not: they are response positions ("weekly_scoped:0", "gpt-5.3-codex-spark:primary").
56
+ */
57
+ function quotaName(label: string): string {
58
+ const slug = label.replace(SLOT, "").toLowerCase().replace(/[^a-z0-9._]+/g, "-").replace(/^-+|-+$/g, "");
59
+ // A label with no ASCII letters or digits has nothing to slug.
60
+ return slug || `quota-${hashAccountKey(label).slice(0, 12)}`;
61
+ }
62
+
63
+ function paseoWindow(window: UsageWindow): PaseoWindow {
64
+ const model = window.scope === "model";
65
+ const name = quotaName(window.label);
66
+ const mapped = windowFromReportedDuration({
67
+ durationSeconds: window.windowDurationMins === null ? null : window.windowDurationMins * 60,
68
+ scope: model ? { id: name, label: window.label } : undefined,
69
+ // Paseo prefixes a model window's id with its scope, which already says everything the label does.
70
+ unknown: { id: model ? "window" : name, label: window.label, shortLabel: "" },
71
+ utilizationPct: window.usedPercent,
72
+ resetsAt: window.resetsAt,
73
+ summary: window.scope === "account",
74
+ });
75
+ if (!model) return mapped;
76
+ // The plugin's model label already names the duration ("Weekly · sonnet"), so the helper's would repeat it.
77
+ const { shortLabel: _repeated, ...rest } = mapped;
78
+ return { ...rest, label: window.label };
79
+ }
80
+
81
+ /** Two readings that name the same quota and period cannot be told apart; numbering the later ones keeps ids unique, which is the only place order enters an id. */
82
+ function withUniqueIds(windows: PaseoWindow[]): PaseoWindow[] {
83
+ const seen = new Map<string, number>();
84
+ return windows.map(window => {
85
+ const count = (seen.get(window.id) ?? 0) + 1;
86
+ seen.set(window.id, count);
87
+ return count === 1 ? window : { ...window, id: `${window.id}:${count}` };
88
+ });
89
+ }
90
+
91
+ export function usageReport(snapshot: UsageSnapshot | undefined): UsageReport {
92
+ if (snapshot?.status === "needs_auth") return { status: "error", error: "Needs sign-in in Account Switcher." };
93
+ if (!snapshot || snapshot.status === "unavailable") return { status: "error", error: "No usage data from the provider yet." };
94
+ // A stale snapshot keeps the last good reading; the plugin's own view marks it, Paseo's has no place for that.
95
+ // A window with neither a percentage nor a detail is a limit the provider names without data (Claude lists several);
96
+ // Paseo's own sources leave those out, and a row of empty meters would only be noise.
97
+ const reported = snapshot.windows.filter(window => window.usedPercent !== null || window.detail?.trim());
98
+ const windows = withUniqueIds(reported.map(paseoWindow));
99
+ const details = reported.flatMap((window, index): UsageDetail[] => {
100
+ const text = window.detail?.trim();
101
+ const shown = windows[index];
102
+ return text && shown ? [{ id: shown.id, label: shown.label, value: text }] : [];
103
+ });
104
+ return { status: "available", ...(snapshot.plan ? { planLabel: snapshot.plan } : {}), windows, ...(details.length ? { details } : {}) };
105
+ }
106
+
107
+ /** Registers the source; false on a daemon without usage sources (Paseo before 0.11). */
108
+ export function registerPaseoUsage(server: PluginServerContext, controller: UsageController): boolean {
109
+ if (typeof server.registerUsageSource !== "function") return false;
110
+ server.registerUsageSource({
111
+ id: SOURCE_ID,
112
+ label: "Account Switcher",
113
+ input: InputSchema,
114
+ async discover(scope) {
115
+ await controller.ready;
116
+ return discoverAccounts(await controller.store.read(), scope);
117
+ },
118
+ // The plugin's cached snapshot: opening the Usage view never costs a provider request.
119
+ async fetch(input) {
120
+ const { accountId } = InputSchema.parse(input);
121
+ const snapshots = await controller.usage.list();
122
+ return usageReport(snapshots.find(snapshot => snapshot.accountId === accountId));
123
+ },
124
+ });
125
+ return true;
126
+ }
@@ -4,8 +4,11 @@ export type SelectionAccount = { id: string; authStatus: string; loginToken?: st
4
4
  export type Blocker = "exhausted" | "model";
5
5
 
6
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;
7
+ export const binding = (window: UsageWindow) => window.scope === "account";
8
+ export const inEffect = (window: UsageWindow, now: number) => !window.resetsAt || Date.parse(window.resetsAt) > now;
9
+ /** An account-wide window that is full until a known reset still ahead: within a window, use only grows until the reset. */
10
+ export const fullUntilReset = (window: UsageWindow, now: number) =>
11
+ binding(window) && window.usedPercent !== null && window.usedPercent >= 100 && window.resetsAt !== null && inEffect(window, now);
9
12
 
10
13
  /** Why an account would certainly fail a new agent, from provider-reported data only; null when nothing proves it.
11
14
  * A full window proves it only with a known future reset: within a window, use only grows until the reset.
@@ -16,7 +19,7 @@ export function blocker(snapshot: UsageSnapshot | undefined, model: string | nul
16
19
  if (fresh && model && snapshot.models && !snapshot.models.includes(model)) return "model";
17
20
  if (fresh && snapshot.usageAllowed === false) return "exhausted";
18
21
  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;
22
+ return snapshot.windows.some(window => fullUntilReset(window, now)) ? "exhausted" : null;
20
23
  }
21
24
 
22
25
  /** Percent left in the tightest account-wide window still in effect, or null without data. */
@@ -0,0 +1,21 @@
1
+ import type { Registry } from "./store";
2
+
3
+ /**
4
+ * The login directory Paseo's own usage sources read for this agent: Claude from `CLAUDE_CONFIG_DIR`,
5
+ * Codex from `CODEX_HOME`. The launcher sets the same variable for the CLI it starts, so naming it
6
+ * here changes what Paseo looks at and not what the CLI runs on.
7
+ *
8
+ * Only a managed account has a directory of its own. The system account is the CLI's own login,
9
+ * which Paseo already reads by default, so it adds nothing.
10
+ */
11
+ export function profileEnv(registry: Registry, agentId: string, provider: string): Record<string, string> {
12
+ if (provider !== "claude" && provider !== "codex") return {};
13
+ // Without the launcher in the chain the CLI runs on the system login, whatever the binding says.
14
+ if (!registry.integration.enabled || !registry.integration.providers.includes(provider)) return {};
15
+ const binding = registry.bindings.find(candidate => candidate.agentId === agentId && candidate.provider === provider);
16
+ // The same choice the launcher makes: the account an agent is launching on wins over the one it ran on.
17
+ const accountId = binding?.launchAccountId ?? binding?.currentAccountId;
18
+ const account = accountId ? registry.accounts.find(candidate => candidate.id === accountId && candidate.provider === provider) : undefined;
19
+ if (account?.source !== "managed") return {};
20
+ return provider === "claude" ? { CLAUDE_CONFIG_DIR: account.home } : { CODEX_HOME: account.home };
21
+ }
package/server/store.ts CHANGED
@@ -15,6 +15,8 @@ export const RegistrySchema = z.object({
15
15
  defaults: z.object({claude:z.string().nullable(),codex:z.string().nullable()}),
16
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
17
  fallback: z.object({claude:z.boolean(),codex:z.boolean()}).default({claude:true,codex:true}),
18
+ // Whether a chat whose turn ran out of its account's limit switches by itself instead of offering a switch; off unless chosen.
19
+ autoFailover: z.object({claude:z.boolean(),codex:z.boolean()}).default({claude:false,codex:false}),
18
20
  sourceHomes: z.object({claude:z.string(),codex:z.string()}),
19
21
  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:{}}),
20
22
  commands: CommandsSchema, originalCommands: CommandsSchema,
@@ -32,6 +34,12 @@ export function accountFrom(registry: Registry, id: string): StoredAccount {
32
34
  if (!account) throw new Error("Account not found.");
33
35
  return account;
34
36
  }
37
+ /** The account an agent runs on as the registry records it: its binding's confirmed account, or for an agent without a
38
+ * binding its provider's Current CLI account. Null while a binding's account is unconfirmed. */
39
+ export function boundAccount(registry: Registry, agentId: string, provider: Provider): string | null {
40
+ const bound = registry.bindings.find(b => b.agentId === agentId);
41
+ return bound ? bound.currentAccountId : registry.accounts.find(a => a.source === "system" && a.provider === provider)?.id ?? null;
42
+ }
35
43
  export class AccountStore {
36
44
  private queue: Promise<unknown> = Promise.resolve();
37
45
  constructor(readonly root: string) {}
@@ -63,7 +71,7 @@ export class AccountStore {
63
71
  async snapshot():Promise<AccountState> {
64
72
  const state=await this.read();
65
73
  const status=(provider:Provider)=>({available:state.available[provider],integrated:state.integration.enabled&&state.integration.providers.includes(provider)});
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")} };
74
+ return { accounts:state.accounts.map(a=>AccountSchema.parse(a)),bindings:state.bindings.map(b=>BindingSchema.parse(b)),defaults:state.defaults,fallback:state.fallback,autoFailover:state.autoFailover,integration:{enabled:state.integration.enabled,error:state.integration.error},providers:{claude:status("claude"),codex:status("codex")} };
67
75
  }
68
76
  async add(provider:Provider,label:string):Promise<StoredAccount> {
69
77
  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;});
@@ -15,6 +15,9 @@ export interface SwitchDependencies {
15
15
  applying?:Set<string>;
16
16
  receiptTimeoutMs?:number;
17
17
  }
18
+ /** A switch refused for a reason written for the user: the chat may show its message. Any other error may carry
19
+ * paths or internals, and only the plugin log gets it. */
20
+ export class SwitchRefusal extends Error { override readonly name = "SwitchRefusal"; }
18
21
  // Paseo 0.11 starts provider CLIs lazily, so the launch receipt can land after reload returns.
19
22
  async function confirmLaunch(root:string,agentId:string,accountId:string,token:string,timeoutMs:number):Promise<boolean>{
20
23
  const path=join(root,"receipts",encodeURIComponent(agentId)+".json"),deadline=Date.now()+timeoutMs;
@@ -30,36 +33,38 @@ export class SwitchService {
30
33
  private receiptTimeoutMs:number;
31
34
  constructor(private readonly deps:SwitchDependencies){this.applying=deps.applying??new Set();this.receiptTimeoutMs=deps.receiptTimeoutMs??15_000;}
32
35
  async prepare(agentId:string,accountId:string|null):Promise<Binding>{
33
- if(this.applying.has(agentId))throw new Error("An account switch is already in progress.");
36
+ if(this.applying.has(agentId))throw new SwitchRefusal("An account switch is already in progress.");
34
37
  const agent=await this.deps.inspect(agentId);
35
- if(agent.archived)throw new Error("The agent is archived.");
36
- if(agent.provider!=="claude"&&agent.provider!=="codex")throw new Error("Only Claude and Codex are supported.");
38
+ if(agent.archived)throw new SwitchRefusal("The agent is archived.");
39
+ if(agent.provider!=="claude"&&agent.provider!=="codex")throw new SwitchRefusal("Only Claude and Codex are supported.");
37
40
  return BindingSchema.parse(await this.deps.store.prepare(agentId,agent.provider,accountId));
38
41
  }
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>{
41
- if(this.applying.has(agentId))throw new Error("An account switch is already in progress.");
42
+ /** `expected` is the account the caller showed or named; another client's later selection must not be applied in its place.
43
+ * `switching` is told once the binding has started switching; a failure from then on is rolled back here. */
44
+ async apply(agentId:string,expected?:string,switching?:()=>void):Promise<Binding>{
45
+ if(this.applying.has(agentId))throw new SwitchRefusal("An account switch is already in progress.");
42
46
  this.applying.add(agentId);
43
47
  let previous:StoredBinding|undefined;
44
48
  const token=randomUUID();
45
49
  try {
46
50
  const {store}=this.deps, state=await store.read();
47
- if(!state.integration.enabled)throw new Error("Enable account integration first.");
51
+ if(!state.integration.enabled)throw new SwitchRefusal("Enable account integration first.");
48
52
  const selected=state.bindings.find(b=>b.agentId===agentId);
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.");
53
+ if(!selected?.pendingAccountId)throw new SwitchRefusal("Select an account first.");
54
+ if(expected&&selected.pendingAccountId!==expected)throw new SwitchRefusal("The account selection changed; try again.");
51
55
  const target=accountFrom(state,selected.pendingAccountId);
52
56
  // Without the launcher in its command, the provider would never confirm the new account.
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.`);
54
- if(target.loginToken)throw new Error("Finish signing in to the selected account first.");
55
- const assertIdle=async()=>{const agent=await this.deps.inspect(agentId);if(agent.archived)throw new Error("The agent is archived.");if(agent.provider!==target.provider)throw new Error("The agent provider changed.");if(agent.busy)throw new Error("Wait for the agent to finish its response.");};
57
+ if(!state.integration.providers.includes(target.provider))throw new SwitchRefusal(`Account switching is off for ${cliName[target.provider]}. Enable integration again to include it.`);
58
+ if(target.loginToken)throw new SwitchRefusal("Finish signing in to the selected account first.");
59
+ const assertIdle=async()=>{const agent=await this.deps.inspect(agentId);if(agent.archived)throw new SwitchRefusal("The agent is archived.");if(agent.provider!==target.provider)throw new SwitchRefusal("The agent provider changed.");if(agent.busy)throw new SwitchRefusal("Wait for the agent to finish its response.");};
56
60
  await assertIdle();
57
- if((await this.deps.checkAccount(target.id)).authStatus!=="ready")throw new Error("Sign in to the selected account first.");
61
+ if((await this.deps.checkAccount(target.id)).authStatus!=="ready")throw new SwitchRefusal("Sign in to the selected account first.");
58
62
  await assertIdle();
59
- previous=await store.change(r=>{const b=r.bindings.find(b=>b.agentId===agentId);if(!r.integration.enabled||!b||b.pendingAccountId!==target.id||b.status==="switching")throw new Error("The account selection changed; try again.");if(accountFrom(r,target.id).loginToken)throw new Error("Account sign-in is still in progress.");const old=structuredClone(b);b.status="switching";b.error=null;b.launchAccountId=target.id;b.launchToken=token;return old;});
63
+ previous=await store.change(r=>{const b=r.bindings.find(b=>b.agentId===agentId);if(!r.integration.enabled||!b||b.pendingAccountId!==target.id||b.status==="switching")throw new SwitchRefusal("The account selection changed; try again.");if(accountFrom(r,target.id).loginToken)throw new SwitchRefusal("Account sign-in is still in progress.");const old=structuredClone(b);b.status="switching";b.error=null;b.launchAccountId=target.id;b.launchToken=token;return old;});
64
+ switching?.();
60
65
  await this.deps.reload(agentId);
61
- if(!await confirmLaunch(store.root,agentId,target.id,token,this.receiptTimeoutMs))throw new Error("The new account did not confirm its launch.");
62
- return await store.change(r=>{const b=r.bindings.find(b=>b.agentId===agentId);if(!r.integration.enabled||!b||b.launchToken!==token)throw new Error("The account switch state changed.");b.currentAccountId=target.id;b.pendingAccountId=null;b.status="ready";b.error=null;b.launchToken=null;b.registrationObserved=true;return BindingSchema.parse(b);});
66
+ if(!await confirmLaunch(store.root,agentId,target.id,token,this.receiptTimeoutMs))throw new SwitchRefusal("The new account did not confirm its launch.");
67
+ return await store.change(r=>{const b=r.bindings.find(b=>b.agentId===agentId);if(!r.integration.enabled||!b||b.launchToken!==token)throw new SwitchRefusal("The account switch state changed.");b.currentAccountId=target.id;b.pendingAccountId=null;b.status="ready";b.error=null;b.launchToken=null;b.registrationObserved=true;return BindingSchema.parse(b);});
63
68
  } catch(error) {
64
69
  if(previous){
65
70
  const rollback=previous,rollbackToken=randomUUID();
@@ -78,14 +83,33 @@ export class SwitchService {
78
83
  throw error;
79
84
  } finally {this.applying.delete(agentId);}
80
85
  }
86
+ /** Selects `accountId` and applies it in one step, for a switch the user did not select in the switcher (the failover
87
+ * row's button, the automatic switch). A refusal before the binding starts switching puts the agent's selection back
88
+ * as it was and drops a binding this call created, so no selection the user never made is left pending. */
89
+ async switchTo(agentId:string,accountId:string):Promise<Binding>{
90
+ const {store}=this.deps,before=(await store.read()).bindings.find(b=>b.agentId===agentId);
91
+ const prepared=await this.prepare(agentId,accountId);
92
+ let started=false;
93
+ try{return await this.apply(agentId,accountId,()=>{started=true;});}
94
+ catch(error){
95
+ // Only a binding exactly as `prepare` left it is put back; anything else is a newer choice of another client.
96
+ if(!started)await store.change(r=>{
97
+ const b=r.bindings.find(b=>b.agentId===agentId);
98
+ if(!b||b.pendingAccountId!==prepared.pendingAccountId||b.status!=="ready"||b.launchToken!==null)return;
99
+ if(!before){r.bindings=r.bindings.filter(other=>other!==b);return;}
100
+ b.pendingAccountId=before.pendingAccountId;b.status=before.status;b.error=before.error;b.launchToken=before.launchToken;
101
+ }).catch(failure=>console.error(`Could not put back the account selection of agent ${agentId}: ${failure instanceof Error?failure.message:String(failure)}`));
102
+ throw error;
103
+ }
104
+ }
81
105
  /** Binds a new agent to the default account, or to the next usable one when provider data shows the default would fail. */
82
106
  async bindNewAgent(agentId:string,provider:Provider,model:string|null=null):Promise<{accountId:string;defaultId:string;reason:Blocker|"sign-in"|"unverified"|null}|undefined>{
83
107
  const state=await this.deps.store.read();
84
108
  if(!state.integration.enabled||!state.integration.providers.includes(provider)||state.bindings.some(b=>b.agentId===agentId))return;
85
109
  const selected=state.defaults[provider];if(!selected)return;
86
110
  const account=accountFrom(state,selected);
87
- if(account.provider!==provider)throw new Error("The default account belongs to another provider.");
88
- if(account.loginToken)throw new Error("Default account sign-in is still in progress.");
111
+ if(account.provider!==provider)throw new SwitchRefusal("The default account belongs to another provider.");
112
+ if(account.loginToken)throw new SwitchRefusal("Default account sign-in is still in progress.");
89
113
  const usage=await this.deps.usage?.().catch(()=>[])??[];
90
114
  const evidence={defaultId:selected,accounts:state.accounts.filter(a=>a.provider===provider),usage,model,now:Date.now()};
91
115
  let chosen:string|undefined,defaultStatus:string|undefined;
@@ -95,14 +119,14 @@ export class SwitchService {
95
119
  if(id===selected)defaultStatus=authStatus;
96
120
  if(authStatus==="ready"){chosen=id;break;}
97
121
  }
98
- if(!chosen)throw new Error("The default account requires authentication. Sign in or select another default account.");
122
+ if(!chosen)throw new SwitchRefusal("The default account requires authentication. Sign in or select another default account.");
99
123
  // Only the official probe's `needs_auth` means sign-in; a timeout or an unknown answer is reported as unverified.
100
124
  const reason=chosen===selected?null:defaultBlocker(evidence)??(defaultStatus==="needs_auth"?"sign-in":"unverified");
101
125
  if(reason)console.log(`New agent ${agentId}: the default ${provider} account would fail (${reason}); starting on account ${chosen}.`);
102
126
  const bound=await this.deps.store.change(r=>{
103
127
  if(!r.integration.enabled||!r.integration.providers.includes(provider)||r.bindings.some(b=>b.agentId===agentId))return;
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.");
128
+ if(r.defaults[provider]!==selected)throw new SwitchRefusal("The default account changed; create the agent again.");
129
+ if(accountFrom(r,chosen).loginToken)throw new SwitchRefusal("Account sign-in is still in progress.");
106
130
  r.bindings.push({agentId,provider,currentAccountId:null,pendingAccountId:null,launchAccountId:chosen,launchToken:randomUUID(),status:"ready",error:null,registrationObserved:false});
107
131
  return true;
108
132
  });
@@ -1,6 +1,7 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
  import type { PaseoApi } from "./paseo-api";
3
3
  import { ACCOUNT_NOTE_KIND, ACCOUNT_NOTE_VERSION, type AccountNote } from "../shared/timeline";
4
+ import { FAILOVER_KIND, FAILOVER_VERSION, type FailoverRow } from "../shared/failover";
4
5
 
5
6
  /** Records the agent's account in its timeline. A host that refuses the row never fails the switch itself. */
6
7
  export async function appendAccountNote(paseo: PaseoApi, agentId: string, note: AccountNote): Promise<void> {
@@ -10,3 +11,12 @@ export async function appendAccountNote(paseo: PaseoApi, agentId: string, note:
10
11
  console.error(`Could not add the account note to agent ${agentId}: ${error instanceof Error ? error.message : String(error)}`);
11
12
  }
12
13
  }
14
+
15
+ /** Adds the failover row, or replaces it: the row keeps its id from the offer to the outcome. Best effort, like the notes. */
16
+ export async function appendFailoverRow(paseo: PaseoApi, agentId: string, row: FailoverRow): Promise<void> {
17
+ try {
18
+ await paseo.agents.ref(agentId).timeline.append({ type: "plugin", id: row.rowId, kind: FAILOVER_KIND, version: FAILOVER_VERSION, data: row });
19
+ } catch (error) {
20
+ console.error(`Could not update the account failover row for agent ${agentId}: ${error instanceof Error ? error.message : String(error)}`);
21
+ }
22
+ }
@@ -34,6 +34,7 @@ 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
36
  fallback: z.object({ claude: z.boolean(), codex: z.boolean() }).default({ claude: true, codex: true }),
37
+ autoFailover: z.object({ claude: z.boolean(), codex: z.boolean() }).default({ claude: false, codex: false }),
37
38
  integration: z.object({ enabled: z.boolean(), error: z.string().nullable() }),
38
39
  providers: z.object({ claude: ProviderStatusSchema, codex: ProviderStatusSchema }),
39
40
  });
@@ -67,6 +68,7 @@ export const renameAccount = defineRpc({ name: "accounts.rename", input: Account
67
68
  export const removeAccount = defineRpc({ name: "accounts.remove", input: AccountId, output: Empty });
68
69
  export const setDefaultAccount = defineRpc({ name: "accounts.default", input: z.object({ provider: ProviderSchema, accountId: z.string().nullable() }), output: Empty });
69
70
  export const setFallback = defineRpc({ name: "accounts.fallback", input: z.object({ provider: ProviderSchema, enabled: z.boolean() }), output: Empty });
71
+ export const setAutoFailover = defineRpc({ name: "accounts.auto-failover", input: z.object({ provider: ProviderSchema, enabled: z.boolean() }), output: Empty });
70
72
  export const startLogin = defineRpc({ name: "auth.start", input: AccountId.extend({ mode: LoginModeSchema.optional() }), output: LoginSessionSchema });
71
73
  export const getLoginStatus = defineRpc({ name: "auth.status", input: AccountId.extend({ sessionId: z.string().min(1) }), output: LoginSessionSchema });
72
74
  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 });
@@ -75,6 +77,9 @@ export const cancelLogin = defineRpc({ name: "auth.cancel", input: AccountId.ext
75
77
  export const prepareSwitch = defineRpc({ name: "switch.prepare", input: z.object({ agentId: z.string().min(1), accountId: z.string().nullable() }), output: BindingSchema });
76
78
  // `accountId`: the selection the caller saw; the switch is refused when another client changed it since.
77
79
  export const applySwitch = defineRpc({ name: "switch.apply", input: z.object({ agentId: z.string().min(1), accountId: z.string().min(1).optional() }), output: BindingSchema });
80
+ // Applies the switch a failover row offers; `rowId` is that row, which shows the outcome. `fromId`: the account the offer
81
+ // moves the agent from; the switch is refused when the agent no longer runs on it.
82
+ export const applyFailover = defineRpc({ name: "failover.apply", input: z.object({ agentId: z.string().min(1), accountId: z.string().min(1), rowId: z.string().min(1), fromId: z.string().min(1).optional() }), output: Empty });
78
83
  export const setIntegration = defineRpc({ name: "integration.set", input: z.object({ enabled: z.boolean() }), output: StateSchema });
79
84
  export const listUsage = defineRpc({ name: "usage.list", input: z.object({ visible: z.boolean().optional() }), output: z.object({ accounts: z.array(UsageSnapshotSchema) }) });
80
85
  export const refreshUsage = defineRpc({ name: "usage.refresh", input: z.object({ accountId: z.string().optional() }), output: z.object({ accounts: z.array(UsageSnapshotSchema) }) });
@@ -0,0 +1,45 @@
1
+ import { z } from "zod";
2
+
3
+ /** A plugin row in an agent's timeline after a turn failed on a used-up account: the offer to switch, then its outcome. */
4
+ export const FAILOVER_KIND = "account-failover";
5
+ export const FAILOVER_VERSION = 1;
6
+
7
+ export const FailoverRowSchema = z.object({
8
+ // The timeline item's own id. A renderer is not told it, and the button needs it to update this row.
9
+ rowId: z.string(),
10
+ // offered: a button switches; none: no account has room; switching: in progress;
11
+ // switched / auto: done by the button / automatically; failed: `error` says why.
12
+ state: z.enum(["offered", "none", "switching", "switched", "auto", "failed"]),
13
+ from: z.string(),
14
+ // The account `from` names. The button's switch is refused once the agent runs on another; rows from before this
15
+ // field skip that check.
16
+ fromId: z.string().optional(),
17
+ to: z.string().nullable(),
18
+ toId: z.string().nullable(),
19
+ // When the account that ran out is usable again; null when the provider gave no time.
20
+ resetsAt: z.string().nullable(),
21
+ error: z.string().nullable(),
22
+ // false: the switch did not ask the agent to continue, so the user's next message runs on `to`. Rows from before
23
+ // this field always asked.
24
+ resumes: z.boolean().optional(),
25
+ });
26
+ export type FailoverRow = z.infer<typeof FailoverRowSchema>;
27
+
28
+ /** The row's sentence. `formatTime` turns the reset time into a local one, so the text stays testable. */
29
+ export function failoverText(row: FailoverRow, formatTime: (value: string) => string): string {
30
+ const used = `${row.from}'s limit is used up${row.resetsAt ? ` until ${formatTime(row.resetsAt)}` : ""}.`;
31
+ const to = row.to ?? "another account";
32
+ switch (row.state) {
33
+ case "offered": return used;
34
+ case "none": return `${used} No other account has room.`;
35
+ case "switching": return `Switching from ${row.from} to ${to}…`;
36
+ case "switched": return `Switched from ${row.from} to ${to}.`;
37
+ case "auto": return `Switched automatically from ${row.from} to ${to}.${row.resumes === false ? ` Your next message runs on ${to}.` : ""}`;
38
+ case "failed": return `Could not switch to ${to}: ${row.error ?? "the switch failed."}`;
39
+ }
40
+ }
41
+
42
+ /** The row's button: only an open offer has one. */
43
+ export function failoverAction(row: FailoverRow): { label: string; accountId: string } | null {
44
+ return row.state === "offered" && row.to && row.toId ? { label: `Switch to ${row.to} and continue`, accountId: row.toId } : null;
45
+ }
File without changes
File without changes