paseo-plugin-account-switcher 0.2.0 → 0.3.1

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/server/store.ts CHANGED
@@ -2,7 +2,7 @@ import { readFile, mkdir } from "node:fs/promises";
2
2
  import { randomUUID } from "node:crypto";
3
3
  import { join } from "node:path";
4
4
  import { z } from "zod";
5
- import { AccountSchema, BindingSchema, type Provider, type AccountState } from "../shared/contracts";
5
+ import { AccountSchema, BindingSchema, ProviderSchema, type Provider, type AccountState } from "../shared/contracts";
6
6
  import { atomicWrite, isMissing } from "./files";
7
7
 
8
8
  export const StoredAccountSchema = AccountSchema.extend({ home: z.string(), identityKey: z.string().nullable(), generation: z.number().int(), loginToken:z.string().nullable().default(null) });
@@ -16,7 +16,10 @@ export const RegistrySchema = z.object({
16
16
  sourceHomes: z.object({claude:z.string(),codex:z.string()}),
17
17
  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
18
  commands: CommandsSchema, originalCommands: CommandsSchema,
19
- integration: z.object({enabled:z.boolean(),error:z.string().nullable()}),
19
+ // Whether discovery found each provider CLI. Registries written before this field assumed both.
20
+ available: z.object({claude:z.boolean(),codex:z.boolean()}).default({claude:true,codex:true}),
21
+ // Providers whose Paseo commands the plugin owns while integration is enabled.
22
+ integration: z.object({enabled:z.boolean(),error:z.string().nullable(),providers:z.array(ProviderSchema).default(["claude","codex"])}),
20
23
  });
21
24
  export type Registry = z.infer<typeof RegistrySchema>;
22
25
  export async function readRegistry(root: string): Promise<Registry> {
@@ -57,7 +60,8 @@ export class AccountStore {
57
60
  }
58
61
  async snapshot():Promise<AccountState> {
59
62
  const state=await this.read();
60
- return { accounts:state.accounts.map(a=>AccountSchema.parse(a)),bindings:state.bindings.map(b=>BindingSchema.parse(b)),defaults:state.defaults,integration:state.integration };
63
+ 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")} };
61
65
  }
62
66
  async add(provider:Provider,label:string):Promise<StoredAccount> {
63
67
  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;});
@@ -1,7 +1,7 @@
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, type Binding, type Provider } from "../shared/contracts";
4
+ import { BindingSchema, cliName, type Binding, type Provider } from "../shared/contracts";
5
5
  import { AccountStore, accountFrom, type StoredBinding } from "./store";
6
6
 
7
7
  export interface SwitchDependencies {
@@ -10,10 +10,22 @@ export interface SwitchDependencies {
10
10
  checkAccount:(accountId:string)=>Promise<{authStatus:string}>;
11
11
  reload:(agentId:string)=>Promise<void>;
12
12
  applying?:Set<string>;
13
+ receiptTimeoutMs?:number;
14
+ }
15
+ // Paseo 0.11 starts provider CLIs lazily, so the launch receipt can land after reload returns.
16
+ async function confirmLaunch(root:string,agentId:string,accountId:string,token:string,timeoutMs:number):Promise<boolean>{
17
+ const path=join(root,"receipts",encodeURIComponent(agentId)+".json"),deadline=Date.now()+timeoutMs;
18
+ for(;;){
19
+ try{const receipt=JSON.parse(await readFile(path,"utf8"));if(receipt.accountId===accountId&&receipt.launchToken===token)return true;}
20
+ catch(error){if((error as NodeJS.ErrnoException).code!=="ENOENT"&&!(error instanceof SyntaxError))throw error;}
21
+ if(Date.now()>=deadline)return false;
22
+ await new Promise(done=>setTimeout(done,100));
23
+ }
13
24
  }
14
25
  export class SwitchService {
15
26
  private applying:Set<string>;
16
- constructor(private readonly deps:SwitchDependencies){this.applying=deps.applying??new Set();}
27
+ private receiptTimeoutMs:number;
28
+ constructor(private readonly deps:SwitchDependencies){this.applying=deps.applying??new Set();this.receiptTimeoutMs=deps.receiptTimeoutMs??15_000;}
17
29
  async prepare(agentId:string,accountId:string|null):Promise<Binding>{
18
30
  if(this.applying.has(agentId))throw new Error("An account switch is already in progress.");
19
31
  const agent=await this.deps.inspect(agentId);
@@ -32,6 +44,8 @@ export class SwitchService {
32
44
  const selected=state.bindings.find(b=>b.agentId===agentId);
33
45
  if(!selected?.pendingAccountId)throw new Error("Select an account first.");
34
46
  const target=accountFrom(state,selected.pendingAccountId);
47
+ // Without the launcher in its command, the provider would never confirm the new account.
48
+ if(!state.integration.providers.includes(target.provider))throw new Error(`Account switching is off for ${cliName[target.provider]}. Enable integration again to include it.`);
35
49
  if(target.loginToken)throw new Error("Finish signing in to the selected account first.");
36
50
  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.");};
37
51
  await assertIdle();
@@ -39,8 +53,7 @@ export class SwitchService {
39
53
  await assertIdle();
40
54
  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;});
41
55
  await this.deps.reload(agentId);
42
- const receipt=JSON.parse(await readFile(join(store.root,"receipts",encodeURIComponent(agentId)+".json"),"utf8"));
43
- if(receipt.accountId!==target.id||receipt.launchToken!==token)throw new Error("The new account did not confirm its launch.");
56
+ if(!await confirmLaunch(store.root,agentId,target.id,token,this.receiptTimeoutMs))throw new Error("The new account did not confirm its launch.");
44
57
  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);});
45
58
  } catch(error) {
46
59
  if(previous){
@@ -52,8 +65,7 @@ export class SwitchService {
52
65
  try{
53
66
  const agent=await this.deps.inspect(agentId);if(agent.busy||agent.archived)throw new Error("Agent is busy");
54
67
  await this.deps.reload(agentId);
55
- const receipt=JSON.parse(await readFile(join(this.deps.store.root,"receipts",encodeURIComponent(agentId)+".json"),"utf8"));
56
- restored=receipt.accountId===rollback.currentAccountId&&receipt.launchToken===rollbackToken;
68
+ restored=await confirmLaunch(this.deps.store.root,agentId,rollback.currentAccountId,rollbackToken,this.receiptTimeoutMs);
57
69
  }catch{/* Keep the account unknown unless rollback launch is confirmed. */}
58
70
  }
59
71
  await this.deps.store.change(r=>{const b=r.bindings.find(b=>b.agentId===agentId);if(b?.launchToken===rollbackToken){b.currentAccountId=restored?rollback.currentAccountId:null;b.pendingAccountId=rollback.pendingAccountId;b.status="error";b.launchToken=null;b.error=restored?"The account switch failed. The previous account was restored.":"Account not confirmed for the running session. Select an account and apply it again.";}});
@@ -63,14 +75,14 @@ export class SwitchService {
63
75
  }
64
76
  async bindNewAgent(agentId:string,provider:Provider):Promise<void>{
65
77
  const state=await this.deps.store.read();
66
- if(!state.integration.enabled||state.bindings.some(b=>b.agentId===agentId))return;
78
+ if(!state.integration.enabled||!state.integration.providers.includes(provider)||state.bindings.some(b=>b.agentId===agentId))return;
67
79
  const selected=state.defaults[provider];if(!selected)return;
68
80
  const account=accountFrom(state,selected);
69
81
  if(account.provider!==provider)throw new Error("The default account belongs to another provider.");
70
82
  if(account.loginToken)throw new Error("Default account sign-in is still in progress.");
71
83
  if((await this.deps.checkAccount(selected)).authStatus!=="ready")throw new Error("The default account requires authentication. Sign in or select another default account.");
72
84
  await this.deps.store.change(r=>{
73
- if(!r.integration.enabled||r.bindings.some(b=>b.agentId===agentId))return;
85
+ if(!r.integration.enabled||!r.integration.providers.includes(provider)||r.bindings.some(b=>b.agentId===agentId))return;
74
86
  const accountId=r.defaults[provider];if(accountId!==selected)throw new Error("The default account changed; create the agent again.");
75
87
  if(accountFrom(r,accountId).loginToken)throw new Error("Default account sign-in is still in progress.");
76
88
  r.bindings.push({agentId,provider,currentAccountId:null,pendingAccountId:null,launchAccountId:accountId,launchToken:randomUUID(),status:"ready",error:null,registrationObserved:false});
@@ -3,6 +3,8 @@ import { z } from "zod";
3
3
 
4
4
  export const ProviderSchema = z.enum(["claude", "codex"]);
5
5
  export type Provider = z.infer<typeof ProviderSchema>;
6
+ export const cliName: Record<Provider, string> = { claude: "Claude Code", codex: "Codex" };
7
+ export const missingCli = (provider: Provider): string => `${cliName[provider]} CLI was not found on the daemon. Install it or configure its command in Paseo, then reload the plugin.`;
6
8
  export const LoginModeSchema = z.enum(["device", "browser"]);
7
9
  export const LoginSessionSchema = z.object({
8
10
  id: z.string(), accountId: z.string(), provider: ProviderSchema, mode: LoginModeSchema,
@@ -25,10 +27,14 @@ export const BindingSchema = z.object({
25
27
  status: z.enum(["ready", "switching", "error"]), error: z.string().nullable(),
26
28
  });
27
29
  export type Binding = z.infer<typeof BindingSchema>;
30
+ // `available`: the daemon found the provider CLI. `integrated`: its launches go through the account launcher.
31
+ export const ProviderStatusSchema = z.object({ available: z.boolean(), integrated: z.boolean() });
32
+ export type ProviderStatus = z.infer<typeof ProviderStatusSchema>;
28
33
  export const StateSchema = z.object({
29
34
  accounts: z.array(AccountSchema), bindings: z.array(BindingSchema),
30
35
  defaults: z.object({ claude: z.string().nullable(), codex: z.string().nullable() }),
31
36
  integration: z.object({ enabled: z.boolean(), error: z.string().nullable() }),
37
+ providers: z.object({ claude: ProviderStatusSchema, codex: ProviderStatusSchema }),
32
38
  });
33
39
  export type AccountState = z.infer<typeof StateSchema>;
34
40
  export const UsageWindowSchema = z.object({