paseo-plugin-account-switcher 0.8.1 → 0.9.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 +1 -0
- package/OVERVIEW.zh-CN.md +1 -0
- package/README.md +12 -2
- package/index.server.ts +7 -2
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
- package/server/controller.ts +27 -3
- package/server/launcher-artifact.ts +1 -1
- package/server/launcher-main.ts +6 -0
- package/server/process-identity.ts +30 -0
- package/server/store.ts +1 -1
- package/server/switching.ts +35 -3
- package/shared/timeline.ts +2 -1
package/server/launcher-main.ts
CHANGED
|
@@ -40,6 +40,12 @@ async function main(): Promise<void> {
|
|
|
40
40
|
if (!(await lstat(account.home)).isDirectory() || await realpath(account.home) !== join(await realpath(root), "accounts", account.id, provider)) throw new Error();
|
|
41
41
|
} catch { throw new LauncherError("Assigned account profile is missing or redirected; launch refused. Restore the profile or select another account."); }
|
|
42
42
|
try { await prepareProfile({ provider, home: account.home, sourceHome: registry.sourceHomes[provider], sourceEnvironment: registry.sourceEnvironment[provider] }); } catch { throw new LauncherError("Account profile preparation failed; inspect shared provider configuration."); }
|
|
43
|
+
// The plugin can release a new agent's binding while this waited, and then nothing keeps the profile from being removed or signed in again.
|
|
44
|
+
if (!login) {
|
|
45
|
+
let current;
|
|
46
|
+
try { current = await readRegistry(root); } catch { throw new LauncherError("Account registry is missing or corrupt; launch refused."); }
|
|
47
|
+
if (!current.bindings.some(candidate => candidate.agentId === agentId)) throw new LauncherError("The account reservation was released while this agent started; launch refused.");
|
|
48
|
+
}
|
|
43
49
|
env = buildAccountEnv(provider, account.home, env);
|
|
44
50
|
}
|
|
45
51
|
if (login) args = provider === "claude" ? ["auth", "login", "--claudeai"] : args[2] === "--browser" ? ["login"] : ["login", "--device-auth"];
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { execFile } from "node:child_process";
|
|
2
|
+
import { promisify } from "node:util";
|
|
3
|
+
|
|
4
|
+
const execFileAsync = promisify(execFile);
|
|
5
|
+
// ps gives a start to the second, and a CLI starts just before its launcher stamps the receipt.
|
|
6
|
+
const MARGIN_MS = 60_000;
|
|
7
|
+
|
|
8
|
+
/** Reads `ps -o lstart=`, local time such as "Sat Oct 31 20:04:51 2026". NaN for anything else. */
|
|
9
|
+
export function parseProcessStart(text: string): number {
|
|
10
|
+
return Date.parse(text.trim());
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Whether the process a launch receipt names, by PID and the time the receipt was written, still runs.
|
|
15
|
+
* The PID may since have gone to another process, after a reboot above all, so one that started after
|
|
16
|
+
* the receipt is not that process. Anything unclear counts as running: a profile that may be in use stays held.
|
|
17
|
+
*/
|
|
18
|
+
export async function receiptProcessRuns(pid: number, writtenAt: unknown): Promise<boolean> {
|
|
19
|
+
try {
|
|
20
|
+
process.kill(pid, 0);
|
|
21
|
+
} catch (error) {
|
|
22
|
+
return (error as NodeJS.ErrnoException).code !== "ESRCH";
|
|
23
|
+
}
|
|
24
|
+
try {
|
|
25
|
+
const { stdout } = await execFileAsync("ps", ["-o", "lstart=", "-p", String(pid)], { timeout: 5000, env: { ...process.env, LC_ALL: "C" } });
|
|
26
|
+
return !(parseProcessStart(String(stdout)) > Date.parse(String(writtenAt)) + MARGIN_MS);
|
|
27
|
+
} catch {
|
|
28
|
+
return true;
|
|
29
|
+
}
|
|
30
|
+
}
|
package/server/store.ts
CHANGED
|
@@ -7,7 +7,7 @@ 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) });
|
|
9
9
|
export type StoredAccount = z.infer<typeof StoredAccountSchema>;
|
|
10
|
-
const StoredBindingSchema = BindingSchema.extend({ launchAccountId: z.string().nullable(), launchToken: z.string().nullable(), registrationObserved:z.boolean().default(false) });
|
|
10
|
+
const StoredBindingSchema = BindingSchema.extend({ launchAccountId: z.string().nullable(), launchToken: z.string().nullable(), registrationObserved:z.boolean().default(false), boundAt:z.string().optional() });
|
|
11
11
|
export type StoredBinding = z.infer<typeof StoredBindingSchema>;
|
|
12
12
|
const CommandsSchema = z.object({ claude: z.array(z.string()).nullable(), codex: z.array(z.string()).nullable() });
|
|
13
13
|
export const RegistrySchema = z.object({
|
package/server/switching.ts
CHANGED
|
@@ -3,7 +3,7 @@ import { readFile } from "node:fs/promises";
|
|
|
3
3
|
import { join } from "node:path";
|
|
4
4
|
import { BindingSchema, cliName, type Binding, type Provider, type UsageSnapshot } from "../shared/contracts";
|
|
5
5
|
import { defaultBlocker, launchOrder, type Blocker } from "./selection";
|
|
6
|
-
import { AccountStore, accountFrom, type StoredBinding } from "./store";
|
|
6
|
+
import { AccountStore, accountFrom, type Registry, type StoredBinding } from "./store";
|
|
7
7
|
|
|
8
8
|
export interface SwitchDependencies {
|
|
9
9
|
store:AccountStore;
|
|
@@ -103,8 +103,9 @@ export class SwitchService {
|
|
|
103
103
|
}
|
|
104
104
|
}
|
|
105
105
|
/** Binds a new agent to the default account, or to the next usable one when provider data shows the default would fail. */
|
|
106
|
-
async bindNewAgent(agentId:string,provider:Provider,model:string|null=null):Promise<{accountId:string;defaultId:string;reason:Blocker|"sign-in"|"unverified"|null}|undefined>{
|
|
106
|
+
async bindNewAgent(agentId:string,provider:Provider,model:string|null=null,requested:string|null=null):Promise<{accountId:string;defaultId:string|null;reason:Blocker|"sign-in"|"unverified"|"requested"|null}|undefined>{
|
|
107
107
|
const state=await this.deps.store.read();
|
|
108
|
+
if(requested!==null)return this.bindRequested(state,agentId,provider,requested);
|
|
108
109
|
if(!state.integration.enabled||!state.integration.providers.includes(provider)||state.bindings.some(b=>b.agentId===agentId))return;
|
|
109
110
|
const selected=state.defaults[provider];if(!selected)return;
|
|
110
111
|
const account=accountFrom(state,selected);
|
|
@@ -127,9 +128,40 @@ export class SwitchService {
|
|
|
127
128
|
if(!r.integration.enabled||!r.integration.providers.includes(provider)||r.bindings.some(b=>b.agentId===agentId))return;
|
|
128
129
|
if(r.defaults[provider]!==selected)throw new SwitchRefusal("The default account changed; create the agent again.");
|
|
129
130
|
if(accountFrom(r,chosen).loginToken)throw new SwitchRefusal("Account sign-in is still in progress.");
|
|
130
|
-
r.bindings.push({agentId,provider,currentAccountId:null,pendingAccountId:null,launchAccountId:chosen,launchToken:randomUUID(),status:"ready",error:null,registrationObserved:false});
|
|
131
|
+
r.bindings.push({agentId,provider,currentAccountId:null,pendingAccountId:null,launchAccountId:chosen,launchToken:randomUUID(),status:"ready",error:null,registrationObserved:false,boundAt:new Date().toISOString()});
|
|
131
132
|
return true;
|
|
132
133
|
});
|
|
133
134
|
return bound?{accountId:chosen,defaultId:selected,reason}:undefined;
|
|
134
135
|
}
|
|
136
|
+
/** An account named when the agent is created is binding: the agent starts there or not at all. Limits do not move it;
|
|
137
|
+
* Always use the default, the official sign-in check and a sign-in in progress refuse it. */
|
|
138
|
+
private async bindRequested(state:Registry,agentId:string,provider:Provider,requested:string):Promise<{accountId:string;defaultId:string|null;reason:"requested"|null}|undefined>{
|
|
139
|
+
const off=()=>new SwitchRefusal(`Account switching is off for ${cliName[provider]}, so the agent cannot start on ${requested}.`);
|
|
140
|
+
if(!state.integration.enabled||!state.integration.providers.includes(provider))throw off();
|
|
141
|
+
if(state.bindings.some(b=>b.agentId===agentId))return;
|
|
142
|
+
// An ID names one account; a name must name exactly one account of the provider.
|
|
143
|
+
const accounts=state.accounts.filter(a=>a.provider===provider),named=accounts.filter(a=>a.label.trim()===requested);
|
|
144
|
+
const account=accounts.find(a=>a.id===requested)??(named.length===1?named[0]:undefined);
|
|
145
|
+
if(!account)throw new SwitchRefusal(named.length>1?`More than one ${cliName[provider]} account is named ${requested}; name it by its ID instead.`:`No ${cliName[provider]} account is named ${requested}.`);
|
|
146
|
+
// Always use the default promises the default or nothing, so it outranks whoever creates the agent. With no default set it has nothing to keep.
|
|
147
|
+
const keepDefault=(r:Registry)=>{const selected=r.defaults[provider];if(selected&&!r.fallback[provider]&&selected!==account.id)throw new SwitchRefusal(`${cliName[provider]} always uses its default account, so the agent cannot start on ${account.label}. Choose Start on another account in Accounts to allow it.`);};
|
|
148
|
+
keepDefault(state);
|
|
149
|
+
if(account.loginToken)throw new SwitchRefusal(`Sign-in to ${account.label} is still in progress.`);
|
|
150
|
+
const {authStatus}=await this.deps.checkAccount(account.id);
|
|
151
|
+
if(authStatus!=="ready")throw new SwitchRefusal(`${account.label} requires authentication. Sign in to it, or start the agent on another account.`);
|
|
152
|
+
const defaultId=state.defaults[provider]??null;
|
|
153
|
+
const bound=await this.deps.store.change(r=>{
|
|
154
|
+
if(!r.integration.enabled||!r.integration.providers.includes(provider))throw off();
|
|
155
|
+
if(r.bindings.some(b=>b.agentId===agentId))return;
|
|
156
|
+
keepDefault(r);
|
|
157
|
+
const current=r.accounts.find(a=>a.id===account.id);
|
|
158
|
+
if(!current)throw new SwitchRefusal(`${account.label} was removed; create the agent again.`);
|
|
159
|
+
if(current.loginToken)throw new SwitchRefusal(`Sign-in to ${account.label} is still in progress.`);
|
|
160
|
+
r.bindings.push({agentId,provider,currentAccountId:null,pendingAccountId:null,launchAccountId:account.id,launchToken:randomUUID(),status:"ready",error:null,registrationObserved:false,boundAt:new Date().toISOString()});
|
|
161
|
+
return true;
|
|
162
|
+
});
|
|
163
|
+
if(!bound)return;
|
|
164
|
+
console.log(`New agent ${agentId}: starting on the requested ${cliName[provider]} account ${account.id}.`);
|
|
165
|
+
return {accountId:account.id,defaultId,reason:account.id===defaultId?null:"requested"};
|
|
166
|
+
}
|
|
135
167
|
}
|
package/shared/timeline.ts
CHANGED
|
@@ -9,7 +9,7 @@ export const AccountNoteSchema = z.object({
|
|
|
9
9
|
from: z.string().nullable(),
|
|
10
10
|
to: z.string(),
|
|
11
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(),
|
|
12
|
+
reason: z.enum(["exhausted", "model", "sign-in", "unverified", "requested"]).nullable(),
|
|
13
13
|
});
|
|
14
14
|
export type AccountNote = z.infer<typeof AccountNoteSchema>;
|
|
15
15
|
|
|
@@ -18,6 +18,7 @@ const why: Record<NonNullable<AccountNote["reason"]>, (from: string) => string>
|
|
|
18
18
|
model: (from) => `the default ${from}'s plan does not offer this agent's model`,
|
|
19
19
|
"sign-in": (from) => `the default ${from} needs sign-in`,
|
|
20
20
|
unverified: (from) => `the default ${from} could not be checked`,
|
|
21
|
+
requested: (from) => `named when the agent was created, instead of the default ${from}`,
|
|
21
22
|
};
|
|
22
23
|
|
|
23
24
|
export function noteText(note: AccountNote): string {
|