paseo-plugin-account-switcher 0.2.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,319 @@
1
+ import { execFile } from "node:child_process";
2
+ import { promisify } from "node:util";
3
+ import { homedir } from "node:os";
4
+ import { join, dirname, resolve } from "node:path";
5
+ import { lstat, readFile, realpath, rm } from "node:fs/promises";
6
+ import { randomUUID } from "node:crypto";
7
+ import type { PaseoApi } from "./paseo-api";
8
+ import { AccountSchema, type LoginSession, type Provider } from "../shared/contracts";
9
+ import { AccountStore, accountFrom, type Registry, type StoredAccount } from "./store";
10
+ import { prepareProfile } from "./profiles";
11
+ import { accountCommand, accountEnvironment, launchLogin, probeAccount, removeAccountCredentials } from "./auth";
12
+ import { installIntegration, restoreIntegration, writeLaunchers, prepareRuntime, reconcileIntegration } from "./integration";
13
+ import { SwitchService } from "./switching";
14
+ import { createUsageService, readCredentialVersion, type AccountReadOptions, type QuotaAccount } from "./usage";
15
+ import { LoginSessions, type LoginDependencies } from "./login";
16
+
17
+ const execFileAsync=promisify(execFile);
18
+ export class AccountController {
19
+ readonly store:AccountStore;
20
+ readonly ready:Promise<void>;
21
+ readonly usage:ReturnType<typeof createUsageService>;
22
+ private readonly checks=new Map<string,Promise<StoredAccount>>();
23
+ private readonly credentialVersions=new Map<string,string>();
24
+ private readonly credentialProofs=new Map<string,{version:string;identityKey:string;generation:number}>();
25
+ private readonly switches=new Map<PaseoApi,SwitchService>();
26
+ private readonly applying=new Set<string>();
27
+ private runtimeReady:Promise<void>|undefined;
28
+ private readonly quotaFlights=new Map<string,Promise<QuotaAccount[]>>();
29
+ private integrationChanging=false;
30
+ private readonly startingLogins=new Set<string>();
31
+ private disposed=false;
32
+ private readonly logins:LoginSessions;
33
+ constructor(root=join(process.env.PASEO_HOME||join(homedir(),".paseo"),"account-switcher"),loginDependencies:Omit<LoginDependencies,"finish">={}) {
34
+ this.store=new AccountStore(root);
35
+ this.logins=new LoginSessions({...loginDependencies,finish:(id,token,successful)=>this.completeBackgroundLogin(id,token,successful)});
36
+ this.ready=this.store.initialize({claude:resolve(process.env.CLAUDE_CONFIG_DIR||join(homedir(),".claude")),codex:resolve(process.env.CODEX_HOME||join(homedir(),".codex"))}).then(async()=>{
37
+ await writeLaunchers(this.store);
38
+ // A crash during reload must not leave an unconfirmed account marked applied.
39
+ await this.store.change(state=>{for(const b of state.bindings){if(b.status==="switching"){b.currentAccountId=null;b.launchToken=null;b.status="error";b.error="The account switch was interrupted. Account not confirmed; apply the account again.";}}});
40
+ });
41
+ this.usage=createUsageService({getAccounts:input=>this.quotaAccounts(input),cachePath:join(root,"usage-cache.json")});
42
+ void this.ready.then(()=>{if(!this.disposed)this.usage.start();}).catch(()=>{});
43
+ }
44
+ async ensureRuntime(paseo:PaseoApi){
45
+ await this.ready;
46
+ if(!this.runtimeReady){this.runtimeReady=prepareRuntime(paseo,this.store).catch(error=>{this.runtimeReady=undefined;throw error;});}
47
+ await this.runtimeReady;
48
+ await reconcileIntegration(paseo,this.store);
49
+ }
50
+ async snapshot(paseo:PaseoApi){
51
+ await this.ensureRuntime(paseo);
52
+ await this.reconcileDeletedAgents(paseo);
53
+ await this.reconcileLogins();
54
+ const state=await this.store.read();
55
+ for(const binding of state.bindings.filter(b=>state.integration.enabled&&!this.integrationChanging&&b.currentAccountId===null&&b.status==="ready"&&b.launchAccountId&&b.launchToken)){
56
+ try{
57
+ const receipt=JSON.parse(await readFile(join(this.store.root,"receipts",encodeURIComponent(binding.agentId)+".json"),"utf8"));
58
+ if(receipt.accountId!==binding.launchAccountId||receipt.launchToken!==binding.launchToken)continue;
59
+ const live=await paseo.agents.ref(binding.agentId).refresh();
60
+ if(!live||!["idle","running"].includes(live.agent.status))continue;
61
+ await this.store.change(r=>{const b=r.bindings.find(b=>b.agentId===binding.agentId);if(r.integration.enabled&&!this.integrationChanging&&b&&b.launchToken===binding.launchToken&&b.launchAccountId===binding.launchAccountId&&b.currentAccountId===null&&b.status==="ready"){b.currentAccountId=binding.launchAccountId;b.launchToken=null;b.registrationObserved=true;}});
62
+ }catch{/* The UI keeps the account unconfirmed until native startup succeeds. */}
63
+ }
64
+ return this.store.snapshot();
65
+ }
66
+ async observeAgentRegistration(agentId:string){
67
+ await this.ready;
68
+ await this.store.change(r=>{const binding=r.bindings.find(b=>b.agentId===agentId);if(binding)binding.registrationObserved=true;});
69
+ }
70
+ private async reconcileDeletedAgents(paseo:PaseoApi){
71
+ const before=await this.store.read();
72
+ if(!before.bindings.length)return;
73
+ const captured=new Map(before.bindings.map(binding=>[binding.agentId,JSON.stringify(binding)]));
74
+ const existing=new Set<string>(),cursors=new Set<string>();
75
+ let cursor:string|undefined,complete=false;
76
+ try{
77
+ for(let page=0;page<1000;page++){
78
+ const result=await paseo.agents.list({filter:{includeArchived:true},page:{limit:200,...(cursor?{cursor}:{})}});
79
+ if(!Array.isArray(result.entries)||typeof result.pageInfo?.hasMore!=="boolean")return;
80
+ for(const entry of result.entries){const id=entry.agent?.id;if(typeof id!=="string"||!id||existing.has(id))return;existing.add(id);}
81
+ if(!result.pageInfo.hasMore){if(result.pageInfo.nextCursor!==null)return;complete=true;break;}
82
+ const next=result.pageInfo.nextCursor;if(typeof next!=="string"||!next||cursors.has(next))return;cursors.add(next);cursor=next;
83
+ }
84
+ }catch{return;}
85
+ if(!complete)return;
86
+ await this.store.change(r=>{
87
+ r.bindings=r.bindings.filter(binding=>{
88
+ if(existing.has(binding.agentId)){binding.registrationObserved=true;return true;}
89
+ if(captured.get(binding.agentId)!==JSON.stringify(binding)||this.applying.has(binding.agentId)||binding.status==="switching")return true;
90
+ // session_open runs before native creation/registration. A default binding
91
+ // that has never appeared in Paseo is not proof of a deleted agent.
92
+ return !binding.registrationObserved&&binding.currentAccountId===null;
93
+ });
94
+ });
95
+ }
96
+ async setDefault(provider:Provider,id:string|null){
97
+ await this.ready;
98
+ if(id===null){await this.store.change(r=>{r.defaults[provider]=null;});return;}
99
+ const before=await this.store.read(),account=accountFrom(before,id);
100
+ if(account.provider!==provider)throw new Error("The account belongs to another provider.");
101
+ if(account.loginToken)throw new Error("Account sign-in is still in progress.");
102
+ const checked=await this.checkAccount(id);
103
+ if(checked.authStatus!=="ready")throw new Error("Sign in and verify authentication before making this the default account.");
104
+ await this.store.change(r=>{const current=accountFrom(r,id);if(r.defaults[provider]!==before.defaults[provider])throw new Error("The default account changed; select it again.");if(current.loginToken||current.generation!==checked.generation||current.authStatus!=="ready")throw new Error("Account authentication changed; check sign-in again.");r.defaults[provider]=id;});
105
+ }
106
+ async checkAccount(id:string,verifyCredentials=false):Promise<StoredAccount> {
107
+ await this.ready;
108
+ const existing=this.checks.get(id);
109
+ if(existing){if(!verifyCredentials)return existing;await existing.catch(()=>{});return this.checkAccount(id,true);}
110
+ const task=(async()=>{
111
+ const state=await this.store.read(), account=accountFrom(state,id);
112
+ if(account.loginToken)throw new Error("Finish signing in, then click “Check sign-in”.");
113
+ let identity:Awaited<ReturnType<typeof probeAccount>>;
114
+ let stableVersion:string|undefined;
115
+ if(verifyCredentials){
116
+ this.credentialProofs.delete(id);
117
+ const quota=this.toQuotaAccount(account,state);
118
+ for(let attempt=0;;attempt++){
119
+ const before=await readCredentialVersion(quota);
120
+ identity=await probeAccount(account,state);
121
+ const after=await readCredentialVersion(quota);
122
+ if(after!=="unavailable")this.credentialVersions.set(id,after);
123
+ if(before===after&&after.startsWith("present:")){stableVersion=after;break;}
124
+ if(attempt===1||before==="unavailable"||after==="unavailable")break;
125
+ }
126
+ }else identity=await probeAccount(account,state);
127
+ // A transient CLI failure cannot change identity or discard the last quota.
128
+ const updated=await this.store.updateIdentity(id,identity.authStatus==="error"?{identityKey:account.identityKey,email:account.email,plan:account.plan,authStatus:"error"}:identity,account);
129
+ if(stableVersion&&identity.authStatus==="ready"&&identity.identityKey&&updated.authStatus==="ready"&&updated.identityKey===identity.identityKey&&!updated.loginToken)this.credentialProofs.set(id,{version:stableVersion,identityKey:identity.identityKey,generation:updated.generation});
130
+ if(updated.generation!==account.generation&&!verifyCredentials)await this.usage.invalidate(id);
131
+ return updated;
132
+ })();
133
+ this.checks.set(id,task);
134
+ try{return await task;}finally{if(this.checks.get(id)===task)this.checks.delete(id);}
135
+ }
136
+ async quotaAccounts(input:AccountReadOptions={}):Promise<QuotaAccount[]> {
137
+ const key=input.verifyAccountId??"";
138
+ const existing=this.quotaFlights.get(key);if(existing)return existing;
139
+ const task=this.readQuotaAccounts(input);this.quotaFlights.set(key,task);
140
+ try{return await task;}finally{if(this.quotaFlights.get(key)===task)this.quotaFlights.delete(key);}
141
+ }
142
+ private async readQuotaAccounts(input:AccountReadOptions):Promise<QuotaAccount[]> {
143
+ await this.ready;
144
+ await this.reconcileLogins();
145
+ const initial=await this.store.read();
146
+ const target=initial.accounts.find(account=>account.id===input.verifyAccountId);
147
+ if(target&&initial.commands[target.provider]&&!target.loginToken)await this.checkAccount(target.id,true).catch(()=>{this.credentialProofs.delete(target.id);});
148
+ const state=await this.store.read();
149
+ return state.accounts.filter(a=>state.commands[a.provider]&&!a.loginToken).map(account=>this.toQuotaAccount(account,state));
150
+ }
151
+ private toQuotaAccount(account:StoredAccount,state:Registry):QuotaAccount {
152
+ const env=accountEnvironment(account,state);
153
+ const credentialHome=account.provider==="claude"?(env.CLAUDE_SECURESTORAGE_CONFIG_DIR??env.CLAUDE_CONFIG_DIR)||join(env.HOME||homedir(),".claude"):account.home;
154
+ const quota:QuotaAccount={id:account.id,provider:account.provider,home:credentialHome,identityKey:account.identityKey,generation:account.generation,command:accountCommand(state,account.provider),env,requireIdentityVerification:account.identityKey!==null};
155
+ quota.credentialVersion=this.credentialVersions.get(account.id);
156
+ const proof=this.credentialProofs.get(account.id);
157
+ if(account.authStatus==="ready"&&proof?.identityKey===account.identityKey&&proof?.generation===account.generation)quota.identityCredentialVersion=proof.version;
158
+ return quota;
159
+ }
160
+ async add(provider:Provider,label:string) {
161
+ await this.ready;
162
+ const account=await this.store.add(provider,label);
163
+ try{const state=await this.store.read();await prepareProfile({provider,home:account.home,sourceHome:state.sourceHomes[provider],sourceEnvironment:state.sourceEnvironment[provider]});return AccountSchema.parse(account);}
164
+ catch(error){await this.store.remove(account.id,async()=>{await rm(dirname(account.home),{recursive:true,force:true});});throw error;}
165
+ }
166
+ async login(paseo:PaseoApi,id:string,workspaceId?:string,mode?:"device"|"browser") {
167
+ await this.ready;
168
+ await this.reconcileDeletedAgents(paseo);
169
+ if(this.startingLogins.has(id))throw new Error("Sign-in is already being prepared.");
170
+ const token=randomUUID();
171
+ await this.store.change(state=>{const account=accountFrom(state,id);if(account.source!=="managed")throw new Error("Add a separate account for isolated sign-in.");if(account.loginToken)throw new Error("Sign-in is already open. Continue in the Paseo terminal.");if(state.bindings.some(b=>b.currentAccountId===id||b.launchAccountId===id||b.currentAccountId===null&&b.pendingAccountId===id))throw new Error("Switch agents away from this account before signing in again.");account.loginToken=token;account.login=null;});
172
+ this.usage.invalidate(id);
173
+ this.startingLogins.add(id);
174
+ try{
175
+ // A status probe started before the reservation must finish before the CLI
176
+ // can replace credentials. Completion then always probes the new identity.
177
+ await this.checks.get(id)?.catch(()=>{});
178
+ const session=await launchLogin(paseo,this.store,id,workspaceId,mode);
179
+ await this.store.change(r=>{const a=accountFrom(r,id);if(a.loginToken===token)a.login=session;});
180
+ return session;
181
+ }catch(error){await this.store.change(r=>{const a=accountFrom(r,id);if(a.loginToken===token){a.loginToken=null;a.login=null;}});throw error;}
182
+ finally{this.startingLogins.delete(id);}
183
+ }
184
+ async startLogin(paseo:PaseoApi,id:string,mode:"device"|"browser"="device"):Promise<LoginSession>{
185
+ await this.ready;
186
+ if(this.disposed)throw new Error("Account sign-in is shutting down. Try again shortly.");
187
+ await this.reconcileDeletedAgents(paseo);
188
+ if(this.startingLogins.has(id))throw new Error("Sign-in is already being prepared.");
189
+ this.startingLogins.add(id);
190
+ const token=randomUUID();
191
+ try{
192
+ const registry=await this.store.read(),account=accountFrom(registry,id);
193
+ if(account.loginToken)throw new Error("Sign-in is already open. Continue or cancel the current attempt.");
194
+ if(account.source!=="managed")throw new Error("Add a separate account for isolated sign-in.");
195
+ return await this.logins.start(account,registry,this.store.root,token,mode,async()=>{
196
+ await this.store.change(state=>{const current=accountFrom(state,id);if(current.loginToken)throw new Error("Sign-in is already open. Continue or cancel the current attempt.");if(state.bindings.some(b=>b.currentAccountId===id||b.launchAccountId===id||b.currentAccountId===null&&b.pendingAccountId===id))throw new Error("Switch agents away from this account before signing in again.");current.loginToken=token;current.login={sessionId:token,mode:account.provider==="claude"?"browser":mode};});
197
+ this.usage.invalidate(id);
198
+ await this.checks.get(id)?.catch(()=>{});
199
+ });
200
+ }catch(error){
201
+ // LoginSessions stops its already-established watchdog before rejecting.
202
+ // Clear only our reservation, never a newer attempt.
203
+ if(!this.logins.has(id,token))await this.store.change(r=>{const account=accountFrom(r,id);if(account.loginToken===token){account.loginToken=null;account.login=null;}});
204
+ throw error;
205
+ }finally{this.startingLogins.delete(id);}
206
+ }
207
+ private async completeBackgroundLogin(id:string,token:string,successful:boolean):Promise<boolean>{
208
+ const cleared=await this.store.change(state=>{const account=accountFrom(state,id);if(account.loginToken!==token)return false;account.loginToken=null;account.login=null;return true;});
209
+ if(!cleared)return false;
210
+ const account=await this.checkAccount(id);
211
+ void this.usage.refresh(id).catch(()=>{});
212
+ return successful&&account.authStatus==="ready"&&!account.loginToken;
213
+ }
214
+ async getLoginStatus(id:string,sessionId:string):Promise<LoginSession>{
215
+ await this.ready;
216
+ if(this.logins.has(id,sessionId))return this.logins.status(id,sessionId);
217
+ const account=accountFrom(await this.store.read(),id);
218
+ if(!account.login||!("sessionId" in account.login)||account.login.sessionId!==sessionId)throw new Error("This sign-in attempt is no longer active. Start sign-in again.");
219
+ let completed=false;
220
+ try{const receipt=JSON.parse(await readFile(join(this.store.root,"logins",id+".json"),"utf8"));if(receipt.loginToken===sessionId){const checked=await this.finishLogin(id);completed=receipt.exitCode===0&&checked.authStatus==="ready";}}catch{/* The watchdog must confirm exit before releasing the reservation. */}
221
+ return{id:sessionId,accountId:id,provider:account.provider,mode:account.login.mode,status:completed?"complete":"error",authorizationUrl:null,userCode:null,canSubmitCode:false,expiresAt:null,error:completed?null:"Sign-in was interrupted. Cancel this attempt, then start sign-in again."};
222
+ }
223
+ async submitLoginCode(id:string,sessionId:string,code:string):Promise<LoginSession>{
224
+ await this.ready;
225
+ if(accountFrom(await this.store.read(),id).loginToken!==sessionId)throw new Error("This sign-in attempt is no longer active. Start sign-in again.");
226
+ return this.logins.submit(id,sessionId,code);
227
+ }
228
+ async cancelLogin(paseo:PaseoApi,id:string,sessionId?:string){
229
+ await this.ready;
230
+ if(this.startingLogins.has(id))throw new Error("The sign-in terminal is still being prepared. Try again shortly.");
231
+ const account=accountFrom(await this.store.read(),id),token=account.loginToken;
232
+ if(sessionId&&token!==sessionId)throw new Error("This sign-in attempt is no longer active. Start sign-in again.");
233
+ if(!token)return AccountSchema.parse(await this.checkAccount(id));
234
+ if(account.login&&"sessionId" in account.login){
235
+ if(!sessionId)throw new Error("Select the current sign-in attempt before canceling it.");
236
+ if(this.logins.has(id,token))await this.logins.cancel(id,token);
237
+ else{
238
+ let receipt;try{receipt=JSON.parse(await readFile(join(this.store.root,"logins",id+".json"),"utf8"));}catch{throw new Error("The previous sign-in is still stopping. Try canceling again shortly.");}
239
+ if(receipt.loginToken!==token)throw new Error("The previous sign-in is still stopping. Try canceling again shortly.");
240
+ }
241
+ await this.store.change(r=>{const current=accountFrom(r,id);if(current.loginToken===token){current.loginToken=null;current.login=null;}});
242
+ this.usage.invalidate(id);return AccountSchema.parse(await this.checkAccount(id));
243
+ }
244
+ const terminals=account.login&&"terminalId" in account.login?[account.login.terminalId]:(await paseo.terminals.list({cwd:join(this.store.root,"login",id)})).entries.map(t=>t.id);
245
+ for(const terminalId of terminals){const terminal=paseo.terminals.ref(terminalId);if(await terminal.refresh())await terminal.kill();}
246
+ await this.store.change(r=>{const a=accountFrom(r,id);if(a.loginToken===token){a.loginToken=null;a.login=null;}});
247
+ this.usage.invalidate(id);
248
+ return AccountSchema.parse(await this.checkAccount(id));
249
+ }
250
+ private async reconcileLogins(){
251
+ const state=await this.store.read();
252
+ for(const account of state.accounts.filter(a=>a.loginToken)){
253
+ if(account.login&&"sessionId" in account.login&&this.logins.has(account.id,account.login.sessionId))continue;
254
+ try{
255
+ const receipt=JSON.parse(await readFile(join(this.store.root,"logins",account.id+".json"),"utf8"));
256
+ if(receipt.loginToken===account.loginToken)await this.finishLogin(account.id);
257
+ }catch{/* Pending login remains reserved; the UI can still check explicitly. */}
258
+ }
259
+ }
260
+ async finishLogin(id:string) {
261
+ const before=accountFrom(await this.store.read(),id);
262
+ if(before.login&&"sessionId" in before.login&&this.logins.has(id,before.login.sessionId))throw new Error("Sign-in is still in progress. Continue in the sign-in dialog.");
263
+ if(before.loginToken){
264
+ let receipt;try{receipt=JSON.parse(await readFile(join(this.store.root,"logins",id+".json"),"utf8"));}catch{throw new Error("Sign-in in the terminal has not finished yet.");}
265
+ if(receipt.loginToken!==before.loginToken)throw new Error("Sign-in in the terminal has not finished yet.");
266
+ await this.store.change(r=>{const a=accountFrom(r,id);if(a.loginToken===before.loginToken){a.loginToken=null;a.login=null;}});
267
+ }
268
+ const account=await this.checkAccount(id);
269
+ void this.usage.refresh(id).catch(()=>{});
270
+ return AccountSchema.parse(account);
271
+ }
272
+ async remove(id:string,paseo?:PaseoApi) {
273
+ await this.ready;
274
+ if(paseo)await this.reconcileDeletedAgents(paseo);
275
+ const account=accountFrom(await this.store.read(),id);
276
+ await this.store.remove(id,async(account,state)=>{
277
+ if(account.loginToken)throw new Error("Finish signing in in the terminal first.");
278
+ if(!/^[A-Za-z0-9_-]+$/.test(id)||resolve(account.home)!==join(this.store.root,"accounts",id,account.provider))throw new Error("Invalid profile path.");
279
+ const root=await realpath(this.store.root),paths:string[]=[];
280
+ for(const [directory,name] of [["accounts",id],["login",id],["logins",`${id}.json`]]){
281
+ const parent=join(this.store.root,directory);
282
+ try{if(!(await lstat(parent)).isDirectory()||await realpath(parent)!==join(root,directory))throw new Error("The plugin directory has been redirected; cleanup was refused.");paths.push(join(parent,name));}
283
+ catch(error){if((error as NodeJS.ErrnoException).code!=="ENOENT")throw error;}
284
+ }
285
+ await removeAccountCredentials(account,state);
286
+ for(const path of paths)await rm(path,{recursive:true,force:true});
287
+ });
288
+ await this.usage.invalidate(id);
289
+ this.credentialVersions.delete(account.id);this.credentialProofs.delete(account.id);
290
+ }
291
+ async integration(paseo:PaseoApi,enabled:boolean) {
292
+ await this.ready;
293
+ if(this.applying.size||this.integrationChanging)throw new Error("Wait for the integration or account change to finish.");
294
+ this.integrationChanging=true;
295
+ try{
296
+ if(enabled)await installIntegration(paseo,this.store);else {await restoreIntegration(paseo,this.store);await this.store.change(r=>{for(const b of r.bindings){b.launchToken=null;if(b.currentAccountId!==`system-${b.provider}`){b.pendingAccountId=b.pendingAccountId??b.currentAccountId??b.launchAccountId;b.currentAccountId=null;b.status="error";b.error="Integration is disabled. The next reload will use the system CLI.";}}});}
297
+ return this.store.snapshot();
298
+ }finally{this.integrationChanging=false;}
299
+ }
300
+ switcher(paseo:PaseoApi):SwitchService {
301
+ let service=this.switches.get(paseo);if(service)return service;
302
+ const requireIntegration=async()=>{if(this.integrationChanging)throw new Error("An integration change is still in progress.");await reconcileIntegration(paseo,this.store);if(!(await this.store.read()).integration.enabled)throw new Error("Account integration is no longer active. Check its settings and enable it again.");};
303
+ service=new SwitchService({store:this.store,applying:this.applying,checkAccount:async id=>{await requireIntegration();return this.checkAccount(id);},inspect:async(id)=>{
304
+ const result=await paseo.agents.ref(id).refresh();if(!result)throw new Error("Agent not found.");
305
+ const a=result.agent;
306
+ return{provider:a.provider,busy:a.status==="running"||a.status==="initializing"||!!a.activeTurn||a.pendingPermissions.length>0,archived:!!a.archivedAt};
307
+ },reload:async(id)=>{
308
+ await requireIntegration();
309
+ const config=JSON.parse(await readFile(join(dirname(this.store.root),"config.json"),"utf8"));
310
+ const listen=config.daemon?.listen;
311
+ if(typeof listen!=="string"||!listen)throw new Error("Could not identify the daemon for reload.");
312
+ const host=listen.replace(/^0\.0\.0\.0:/,"127.0.0.1:");
313
+ try{await execFileAsync("paseo",["agent","reload",id,"--json","--host",host],{timeout:120_000,maxBuffer:1024*1024,env:process.env});}
314
+ catch{throw new Error("The native agent reload failed. Check the agent status and try again.");}
315
+ }});
316
+ this.switches.set(paseo,service);return service;
317
+ }
318
+ async close(){this.disposed=true;await this.logins.close();await this.usage.close();}
319
+ }
@@ -0,0 +1,17 @@
1
+ import { mkdir, open, rename, rm } from "node:fs/promises";
2
+ import { dirname } from "node:path";
3
+ import { randomUUID } from "node:crypto";
4
+
5
+ export async function atomicWrite(path: string, content: string, mode = 0o600): Promise<void> {
6
+ await mkdir(dirname(path), { recursive: true, mode: 0o700 });
7
+ const temp = `${path}.${randomUUID()}.tmp`;
8
+ try {
9
+ const file = await open(temp, "wx", mode);
10
+ try { await file.writeFile(content); await file.sync(); } finally { await file.close(); }
11
+ await rename(temp, path);
12
+ } finally { await rm(temp, { force: true }); }
13
+ }
14
+
15
+ export function isMissing(error: unknown): boolean {
16
+ return (error as NodeJS.ErrnoException)?.code === "ENOENT";
17
+ }
@@ -0,0 +1,152 @@
1
+ import { access, realpath } from "node:fs/promises";
2
+ import { constants } from "node:fs";
3
+ import { homedir } from "node:os";
4
+ import { delimiter, isAbsolute, join, resolve } from "node:path";
5
+ import type { PaseoApi } from "./paseo-api";
6
+ import type { Provider } from "../shared/contracts";
7
+ import type { AccountStore, Registry } from "./store";
8
+ import { atomicWrite } from "./files";
9
+ import { LAUNCHER_SOURCE } from "./launcher-artifact";
10
+ import { assertSubscriptionEnvironment } from "./profiles";
11
+
12
+ const providers = ["claude", "codex"] as const;
13
+ const COMMAND_DRIFT = "Provider commands changed outside the plugin. Enable integration again to apply accounts.";
14
+ export const launcherPath = (root: string, provider: Provider): string => join(root, "bin", `${provider}-launcher`);
15
+ export async function writeLaunchers(store: AccountStore): Promise<void> {
16
+ for (const provider of providers) await atomicWrite(launcherPath(store.root, provider), LAUNCHER_SOURCE, 0o700);
17
+ }
18
+
19
+ function commandArray(value: unknown): string[] | null {
20
+ if (value === undefined || value === null) return null;
21
+ if (!Array.isArray(value) || !value.length || !value.every(part => typeof part === "string") || !value[0]) throw new Error("The CLI command must be a nonempty array of arguments.");
22
+ return [...value];
23
+ }
24
+ function owned(command: string[] | null, wrapper: string): boolean { return command?.length === 1 && command[0] === wrapper; }
25
+ async function resolveCommand(command: string[], wrappers: string[]): Promise<string[]> {
26
+ if (command.some(part => wrappers.includes(part))) throw new Error("A recursive launcher command was detected. Restore the original CLI.");
27
+ const candidates = isAbsolute(command[0]) || command[0].includes("/") ? [resolve(command[0])] : (process.env.PATH ?? "").split(delimiter).filter(Boolean).map(path => join(path, command[0]));
28
+ for (const candidate of candidates) {
29
+ try {
30
+ await access(candidate, constants.X_OK);
31
+ const resolved = await realpath(candidate);
32
+ if (wrappers.includes(candidate) || wrappers.includes(resolved)) throw new Error("recursion");
33
+ return [candidate, ...command.slice(1)];
34
+ } catch (error) { if ((error as Error).message === "recursion") throw new Error("A recursive launcher command was detected. Restore the original CLI."); }
35
+ }
36
+ throw new Error("Provider CLI not found. Install Claude Code and Codex or configure their commands in Paseo.");
37
+ }
38
+
39
+ export async function prepareRuntime(paseo: PaseoApi, store: AccountStore): Promise<void> {
40
+ await discoverCommands(paseo, store);
41
+ }
42
+
43
+ function disableIntegration(state: Registry, error: string): void {
44
+ state.integration = { enabled: false, error };
45
+ for (const binding of state.bindings) {
46
+ const awaitingReceipt = binding.launchToken !== null && binding.currentAccountId === null;
47
+ binding.launchToken = null;
48
+ if (binding.status === "switching" || awaitingReceipt) {
49
+ binding.currentAccountId = null; binding.status = "error"; binding.error = error;
50
+ }
51
+ }
52
+ }
53
+
54
+ export async function reconcileIntegration(paseo: PaseoApi, store: AccountStore): Promise<void> {
55
+ let ownership: boolean[];
56
+ try {
57
+ const { config } = await paseo.config.get();
58
+ for (const provider of providers) {
59
+ assertSubscriptionEnvironment(provider, process.env);
60
+ const environment = config.providers[provider]?.env;
61
+ assertSubscriptionEnvironment(provider, environment && typeof environment === "object" ? environment as Record<string, unknown> : {});
62
+ }
63
+ ownership = providers.map(provider => owned(commandArray(config.providers[provider]?.command), launcherPath(store.root, provider)));
64
+ } catch {
65
+ const message = "Could not verify Paseo provider commands. Check the configuration and authentication overrides, then enable integration again.";
66
+ await store.change(state => { disableIntegration(state, message); });
67
+ throw new Error(message);
68
+ }
69
+ // Restoring the wrapper paths alone cannot authorize old launch receipts.
70
+ // Only explicit installIntegration enables a disabled registry again.
71
+ if (ownership.every(Boolean)) return;
72
+ await store.change(state => {
73
+ if (state.integration.enabled || ownership.some(Boolean) || state.bindings.some(binding => binding.launchToken !== null)) disableIntegration(state, COMMAND_DRIFT);
74
+ });
75
+ }
76
+
77
+ async function discoverCommands(paseo: PaseoApi, store: AccountStore) {
78
+ try { return await discoverRuntime(paseo, store); }
79
+ catch (error) {
80
+ await store.change(state => { disableIntegration(state, "Could not verify provider commands or authentication. Check the integration settings."); });
81
+ throw error;
82
+ }
83
+ }
84
+
85
+ async function discoverRuntime(paseo: PaseoApi, store: AccountStore) {
86
+ const { config } = await paseo.config.get(); const registry = await store.read();
87
+ const wrappers = providers.map(provider => launcherPath(store.root, provider));
88
+ const commands = { ...registry.commands }, originals = { ...registry.originalCommands }, sourceHomes = { ...registry.sourceHomes };
89
+ const sourceEnvironment: typeof registry.sourceEnvironment = { claude: {}, codex: {} };
90
+ const ownership: boolean[] = [];
91
+ for (const provider of providers) {
92
+ const current = commandArray(config.providers[provider]?.command);
93
+ ownership.push(owned(current, launcherPath(store.root, provider)));
94
+ if (owned(current, launcherPath(store.root, provider))) {
95
+ if (!commands[provider]) throw new Error("The launcher is active without the original CLI command; restore the configuration manually.");
96
+ commands[provider] = await resolveCommand(commands[provider]!, wrappers);
97
+ } else {
98
+ originals[provider] = current;
99
+ commands[provider] = await resolveCommand(current ?? [provider], wrappers);
100
+ }
101
+ const environment = config.providers[provider]?.env;
102
+ const configured = environment && typeof environment === "object" ? environment as Record<string, unknown> : {};
103
+ assertSubscriptionEnvironment(provider, process.env);
104
+ assertSubscriptionEnvironment(provider, configured);
105
+ const keys = provider === "claude" ? ["CLAUDE_CONFIG_DIR", "CLAUDE_SECURESTORAGE_CONFIG_DIR"] as const : ["CODEX_HOME"] as const;
106
+ for (const key of keys) {
107
+ const value = configured[key] ?? process.env[key];
108
+ // An explicitly empty override selects the default credential namespace.
109
+ if(key==="CLAUDE_SECURESTORAGE_CONFIG_DIR"&&value===""){
110
+ sourceEnvironment.claude.CLAUDE_SECURESTORAGE_CONFIG_DIR="";
111
+ continue;
112
+ }
113
+ if (typeof value === "string" && value) {
114
+ if (!isAbsolute(value)) throw new Error("The provider profile path must be absolute.");
115
+ (sourceEnvironment[provider] as Record<string, string>)[key] = value;
116
+ }
117
+ }
118
+ const value = provider === "claude" ? sourceEnvironment.claude.CLAUDE_CONFIG_DIR : sourceEnvironment.codex.CODEX_HOME;
119
+ sourceHomes[provider] = typeof value === "string" && isAbsolute(value) ? resolve(value) : join(homedir(), provider === "claude" ? ".claude" : ".codex");
120
+ }
121
+ await writeLaunchers(store);
122
+ // The wrapper must see its originals before the daemon can run provider discovery.
123
+ await store.change(state => {
124
+ state.commands = commands; state.originalCommands = originals; state.sourceHomes = sourceHomes; state.sourceEnvironment = sourceEnvironment;
125
+ if (!ownership.every(Boolean) && (ownership.some(Boolean) || state.integration.enabled || state.bindings.some(binding => binding.launchToken !== null))) disableIntegration(state, COMMAND_DRIFT);
126
+ for (const account of state.accounts) if (account.source === "system") account.home = sourceHomes[account.provider];
127
+ });
128
+ return config;
129
+ }
130
+
131
+ export async function installIntegration(paseo: PaseoApi, store: AccountStore): Promise<void> {
132
+ const config = await discoverCommands(paseo, store);
133
+ try {
134
+ await paseo.config.patch({ providers: Object.fromEntries(providers.map(provider => [provider, { ...config.providers[provider], command: [launcherPath(store.root, provider)] }])) });
135
+ await store.change(state => { state.integration = { enabled: true, error: null }; });
136
+ } catch { throw new Error("Paseo did not apply provider integration. Check the configuration and try again."); }
137
+ }
138
+
139
+ export async function restoreIntegration(paseo: PaseoApi, store: AccountStore): Promise<void> {
140
+ const { config } = await paseo.config.get(), registry = await store.read();
141
+ const patch: Record<string, Record<string, unknown>> = {};
142
+ for (const provider of providers) {
143
+ if (!owned(commandArray(config.providers[provider]?.command), launcherPath(store.root, provider))) continue;
144
+ const command = registry.originalCommands[provider] ?? registry.commands[provider];
145
+ if (!command?.length) throw new Error("The original CLI command is missing; automatic restoration is unavailable.");
146
+ patch[provider] = { ...config.providers[provider], command };
147
+ }
148
+ try {
149
+ if (Object.keys(patch).length) await paseo.config.patch({ providers: patch });
150
+ await store.change(state => { state.integration = { enabled: false, error: null }; });
151
+ } catch { throw new Error("Paseo did not restore the original provider commands. Try again."); }
152
+ }