paseo-plugin-account-switcher 0.8.1 → 0.10.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 +3 -2
- package/OVERVIEW.zh-CN.md +3 -2
- package/README.md +14 -4
- package/client/accounts.tsx +8 -6
- package/client/screens.ts +1 -1
- package/index.server.ts +11 -4
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
- package/paseo-plugin.json +1 -1
- package/server/controller.ts +54 -21
- 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/server/usage/index.ts +12 -5
- package/shared/contracts.ts +2 -2
- package/shared/timeline.ts +2 -1
package/OVERVIEW.md
CHANGED
|
@@ -7,6 +7,7 @@ Limits cover every window the provider reports, such as 5-hour and weekly use, w
|
|
|
7
7
|
- Each account you add gets its own credential profile. Settings, skills, and session history stay shared with your existing CLI setup, so a profile is not a sandbox.
|
|
8
8
|
- **Enable** in Accounts points Paseo's Claude and Codex commands at the plugin's launchers, which start the official CLI under the agent's account. **Disable** restores the original commands; use it before removing the plugin.
|
|
9
9
|
- A new agent starts on its provider's default account. When the latest readings show the default has used up an account-wide limit that resets later, Codex reports that ordinary usage is not allowed, its plan lacks the Codex model chosen for the agent, or the default needs sign-in, the agent starts on the signed-in account with the largest percentage left instead. Limits of a single model and extra paid usage do not count. With every account ruled out, it stays on the default. **Always use the default** under a provider in Accounts turns this off, so the default stays binding.
|
|
10
|
+
- A tool that creates agents can name the account to start on: an agent created with `PASEO_ACCOUNT_SWITCHER_ACCOUNT` in its environment, set to an account's name or ID, starts on that account whatever its limits. It is not created when that account cannot be used, or when **Always use the default** is on and that account is not the default.
|
|
10
11
|
- `/account name` in the message field switches the chat's account, or `/account default` its provider's default: at once when the agent is idle, otherwise in the switcher for **Apply**. The Command Center offers **Make “name” the default** for each signed-in account.
|
|
11
12
|
- A line in the chat records applied switches, and why a new agent did not start on the default. These lines are best effort and do not survive a daemon restart.
|
|
12
13
|
- Signed-in accounts also appear in Paseo's Usage view, and Paseo's usage popover for an agent on a managed account shows that account.
|
|
@@ -15,7 +16,7 @@ Limits cover every window the provider reports, such as 5-hour and weekly use, w
|
|
|
15
16
|
|
|
16
17
|
## Setup
|
|
17
18
|
|
|
18
|
-
- Paseo 0.11
|
|
19
|
+
- Paseo 0.11 or newer on a macOS or Linux daemon, with Node.js 22.12 or newer.
|
|
19
20
|
- The official Paseo CLI and at least one of Claude Code or Codex on the daemon. A provider without its CLI shows as unavailable; after you install it, reload the plugin and select **Enable** in that provider's section.
|
|
20
21
|
- A Claude or ChatGPT subscription for each account. API keys are not supported. Adding an account runs the official CLI sign-in from Paseo.
|
|
21
22
|
|
|
@@ -25,7 +26,7 @@ Limits cover every window the provider reports, such as 5-hour and weekly use, w
|
|
|
25
26
|
- Claude limits come from a request to `api.anthropic.com` with the account's access token. When that token has expired, for example on an idle account, the plugin runs `claude -p /usage --no-session-persistence` under the account so the official CLI renews it, at most every 10 minutes. The command sends no model message and saves no session. Codex limits and the plan's model list come from the official `codex app-server`, which asks OpenAI and may refresh the account's token. Limit checks send no model messages.
|
|
26
27
|
- To list accounts in Paseo's Usage view, the plugin reports the limits it has already collected under the source name Account Switcher, without new provider requests. For an agent on a managed account, it adds that account's profile directory to the agent's session environment so Paseo's usage popover reads the right account.
|
|
27
28
|
- The only message the plugin sends to an agent is **Continue.**, after a switch made from the limit row, or by automatic switching after a failed turn.
|
|
28
|
-
- Limits refresh every 5 minutes, and every minute while Accounts or the switcher is open. Missing values show as no data, and a failed refresh can keep the last values, marked stale.
|
|
29
|
+
- Limits refresh every 5 minutes, and every minute while Accounts or the switcher is open. Missing values show as no data, and a failed refresh can keep the last values, marked stale. With **Check usage** off in the host's settings (Paseo 0.15 and newer), the plugin makes no limit requests and offers no switch when a limit runs out; Accounts says so.
|
|
29
30
|
- Removing a managed account deletes its profile and stored sign-in, including a Claude account's Keychain item on macOS. Shared session history stays.
|
|
30
31
|
|
|
31
32
|
## Limitations
|
package/OVERVIEW.zh-CN.md
CHANGED
|
@@ -9,6 +9,7 @@ Account Switcher 让你在 Paseo 中使用多个 Claude 和 ChatGPT/Codex 订阅
|
|
|
9
9
|
- 你添加的每个账号都有独立的凭据配置文件。设置、技能和会话历史仍与现有 CLI 配置共享,因此配置文件并不是沙箱。
|
|
10
10
|
- 在 Accounts 中选择 **Enable**,会让 Paseo 的 Claude 和 Codex 命令指向插件的启动器,启动器以智能体所选账号运行官方 CLI。**Disable** 会恢复原始命令;移除插件前请先执行它。
|
|
11
11
|
- 新智能体会使用其提供商的默认账号。如果最近读取的数据显示:默认账号已用尽某个账号级限制且重置时间尚未到来、Codex 报告不允许常规使用、其套餐不提供为该智能体选择的 Codex 模型,或默认账号需要重新登录,智能体会改用剩余百分比最多的已登录账号。单个模型的限制和额外付费用量不计入。所有账号都被排除时,仍使用默认账号。在 Accounts 中该提供商下选择 **Always use the default** 可关闭此行为,使默认账号始终生效。
|
|
12
|
+
- 创建智能体的工具可以指定起始账号:创建时在智能体环境中设置 `PASEO_ACCOUNT_SWITCHER_ACCOUNT` 为账号名称或 ID,智能体就会在该账号上启动,不受限制影响。该账号无法使用,或已选择 **Always use the default** 而该账号不是默认账号时,不会创建智能体。
|
|
12
13
|
- 在输入框中输入 `/account 名称` 可切换当前对话的账号,`/account default` 切换到提供商的默认账号:智能体空闲时立即生效,否则在切换器中通过 **Apply** 应用。命令中心(⌘K)为每个已登录账号提供 **Make “名称” the default**。
|
|
13
14
|
- 对话中会有一行记录已应用的切换,以及新智能体未使用默认账号的原因。这些记录是尽力而为的,在守护进程重启后不会保留。
|
|
14
15
|
- 已登录的账号也会显示在 Paseo 的 Usage 视图中;使用托管账号的智能体,其 Paseo 用量弹窗会显示该账号。
|
|
@@ -17,7 +18,7 @@ Account Switcher 让你在 Paseo 中使用多个 Claude 和 ChatGPT/Codex 订阅
|
|
|
17
18
|
|
|
18
19
|
## 设置
|
|
19
20
|
|
|
20
|
-
- macOS 或 Linux 守护进程上的 Paseo 0.11
|
|
21
|
+
- macOS 或 Linux 守护进程上的 Paseo 0.11 或更高版本,以及 Node.js 22.12 或更高版本。
|
|
21
22
|
- 守护进程上需要官方 Paseo CLI,以及 Claude Code 或 Codex 至少其一。缺少 CLI 的提供商会显示为不可用;安装后重新加载插件,并在该提供商的分区中选择 **Enable**。
|
|
22
23
|
- 每个账号都需要 Claude 或 ChatGPT 订阅。不支持 API 密钥。添加账号时,会在 Paseo 中运行官方 CLI 登录流程。
|
|
23
24
|
|
|
@@ -27,7 +28,7 @@ Account Switcher 让你在 Paseo 中使用多个 Claude 和 ChatGPT/Codex 订阅
|
|
|
27
28
|
- Claude 限制来自使用该账号访问令牌向 `api.anthropic.com` 发出的请求。当该令牌过期时(例如账号闲置),插件会以该账号运行 `claude -p /usage --no-session-persistence`,由官方 CLI 续期令牌,每 10 分钟最多一次。该命令不发送模型消息,也不保存会话。Codex 限制和套餐的模型列表来自官方 `codex app-server`,它会向 OpenAI 查询,并可能刷新账号令牌。限制检查不会发送任何模型消息。
|
|
28
29
|
- 为在 Paseo 的 Usage 视图中列出账号,插件会以来源名称 Account Switcher 上报它已收集的限制数据,不会产生新的提供商请求。对于使用托管账号的智能体,插件会把该账号的配置文件目录加入智能体的会话环境,使 Paseo 的用量弹窗读取正确的账号。
|
|
29
30
|
- 插件发给智能体的唯一消息是 **Continue.**,仅在通过限制行完成切换之后,或在失败回合之后自动切换完成时发送。
|
|
30
|
-
- 限制每 5 分钟刷新一次;Accounts
|
|
31
|
+
- 限制每 5 分钟刷新一次;Accounts 或切换器打开时每分钟刷新一次。缺失的值显示为无数据,刷新失败时可能保留上次的值并标记为过期。在主机设置中关闭 **Check usage** 时(Paseo 0.15 及更新版本),插件不发起额度请求,额度用尽时也不提供切换;Accounts 页面会说明这一点。
|
|
31
32
|
- 移除托管账号会删除其配置文件和已保存的登录信息,在 macOS 上包括 Claude 账号的钥匙串项。共享的会话历史会保留。
|
|
32
33
|
|
|
33
34
|
## 限制
|
package/README.md
CHANGED
|
@@ -22,7 +22,7 @@ Listed in the [Paseo plugin directory](https://paseo.sh/plugins/dutchakdev/accou
|
|
|
22
22
|
|
|
23
23
|
## Requirements
|
|
24
24
|
|
|
25
|
-
- **Paseo 0.11.
|
|
25
|
+
- **Paseo 0.11.0 or newer**, including beta releases after 0.11.0, on a **macOS or Linux** daemon and on the connected client.
|
|
26
26
|
- **Node.js 22.12.0 or newer**, with npm.
|
|
27
27
|
- The official **Paseo** CLI and at least one of **Claude Code** or **Codex** available to the daemon. A provider whose CLI is missing is skipped; after installing it, reload the plugin and select **Enable** in its section.
|
|
28
28
|
- Claude or ChatGPT subscription authentication. API keys and custom authentication/provider overrides are unsupported.
|
|
@@ -33,7 +33,7 @@ The interface is in English. Reset dates use the viewing device's local time zon
|
|
|
33
33
|
|
|
34
34
|
Paseo plugins are trusted, unsandboxed code with the daemon user's access to files, processes, credentials, and network. Account Switcher reads your Claude and Codex sign-ins to identify accounts and check their limits, and checking limits sends no model messages. The only message it sends to an agent is **Continue.**, after you switch from the row a used-up limit adds to the chat, or after an automatic switch that followed a failed turn. The commands below target the local daemon; for another host, see [remote daemons](docs/installation.md#remote-daemons).
|
|
35
35
|
|
|
36
|
-
On Paseo 0.11.0 or a later release,
|
|
36
|
+
On Paseo 0.11.0 or a later release, install the reviewed version from the plugin directory:
|
|
37
37
|
|
|
38
38
|
```sh
|
|
39
39
|
paseo plugin add dutchakdev/account-switcher
|
|
@@ -94,12 +94,22 @@ A new Claude or Codex agent starts on its provider's default account. It starts
|
|
|
94
94
|
|
|
95
95
|
The replacement is the account with the largest percentage left in its tightest account-wide window; accounts without limit data come after the measured ones. Percentages do not compare the size of different plans. If every account is ruled out, the agent starts on the default, as before. Choosing an account for a chat yourself always takes precedence, and nothing changes when no default is set.
|
|
96
96
|
|
|
97
|
-
To keep the default binding, for example when one provider holds both work and personal subscriptions, choose **Always use the default** under that provider in Accounts. New agents then start on the default or not at all, as in 0.6.0. **Start on another account** is the initial choice; the control appears once a provider has a default and more than one account.
|
|
97
|
+
To keep the default binding, for example when one provider holds both work and personal subscriptions, choose **Always use the default** under that provider in Accounts. New agents then start on the default or not at all, as in 0.6.0, and a tool that names another account is refused. **Start on another account** is the initial choice; the control appears once a provider has a default and more than one account.
|
|
98
98
|
|
|
99
99
|
Limits come from the plugin's last reading, so creating an agent does not wait for a provider's limits. It does run the official sign-in check for the default, and for each further account it tries.
|
|
100
100
|
|
|
101
101
|
Before signing in again, switch agents away from that profile. To remove a managed account, clear its default and all current or pending selections first. Removal asks for confirmation. **Archived agents retain their account binding for resume**; restore and switch them before removing the account. **Current CLI** accounts cannot be removed.
|
|
102
102
|
|
|
103
|
+
### Start an agent on a chosen account
|
|
104
|
+
|
|
105
|
+
A tool that creates agents can name the account a new Claude or Codex agent starts on: set `PASEO_ACCOUNT_SWITCHER_ACCOUNT` in the agent's environment to the account's name, as shown in Accounts, or its ID. With the Paseo CLI:
|
|
106
|
+
|
|
107
|
+
```sh
|
|
108
|
+
paseo run --provider codex --env PASEO_ACCOUNT_SWITCHER_ACCOUNT=Work "Review the open pull requests"
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
The named account is binding: the agent starts there or is not created, and the error says why. Limits do not move it to another account. A name must belong to exactly one account of the agent's provider; use the ID when two accounts share a name. Creation is refused when no such account exists, its sign-in is still in progress, the official sign-in check does not confirm it, **Always use the default** is on and the account is not the default, account switching is off for the provider, or the agent's provider is not Claude or Codex. The variable works only at creation: it reaches neither the provider CLI nor later sessions of the agent, and set in a provider's configured environment it selects nothing. The chat records the start when the account is not the default. Afterwards the agent behaves like any other: switching, and switching when a limit runs out, follow your settings.
|
|
112
|
+
|
|
103
113
|
## Switch an existing chat
|
|
104
114
|
|
|
105
115
|
1. Select the account chip beside the message field to open **Account** over the current chat.
|
|
@@ -182,7 +192,7 @@ Before disabling or removing the plugin, select **Disable** in Accounts to resto
|
|
|
182
192
|
|
|
183
193
|
## Scope
|
|
184
194
|
|
|
185
|
-
This project supports same-provider switching with subscription accounts. Switching is manual, except for the opt-in automatic switch after a turn stopped on a used-up limit. Rotating accounts to spread usage, API-key authentication, and Claude-to-Codex transfers are outside its scope. Provider authentication and limit formats can change with CLI versions; unsupported data is shown as unavailable.
|
|
195
|
+
This project supports same-provider switching with subscription accounts. Switching is manual, except for the opt-in automatic switch after a turn stopped on a used-up limit. A tool can name the account a new agent starts on; that choice is the tool's, and the plugin itself never rotates accounts. Rotating accounts to spread usage, API-key authentication, and Claude-to-Codex transfers are outside its scope. Provider authentication and limit formats can change with CLI versions; unsupported data is shown as unavailable.
|
|
186
196
|
|
|
187
197
|
Automated tests cover the implementation with synthetic accounts and provider responses. They do not establish real A → B → A switching, compaction, child-session behavior, or rewind for your accounts. Recorded checks and remaining live verification are in [verification](docs/verification.md).
|
|
188
198
|
|
package/client/accounts.tsx
CHANGED
|
@@ -22,8 +22,8 @@ function listed(account: Account, state: AccountState): boolean {
|
|
|
22
22
|
return state.providers[account.provider].available || account.source === "managed";
|
|
23
23
|
}
|
|
24
24
|
|
|
25
|
-
function AccountCard({ account, state, snapshot, now, theme, layout, host, onChanged, onStarted, onResume }: AccountsProps & SignInActions & {
|
|
26
|
-
account: Account; state: AccountState; snapshot: UsageSnapshot | undefined; now: number;
|
|
25
|
+
function AccountCard({ account, state, snapshot, checksOff, now, theme, layout, host, onChanged, onStarted, onResume }: AccountsProps & SignInActions & {
|
|
26
|
+
account: Account; state: AccountState; snapshot: UsageSnapshot | undefined; checksOff: boolean; now: number;
|
|
27
27
|
}) {
|
|
28
28
|
const rename = useRpc(renameAccount);
|
|
29
29
|
const remove = useRpc(removeAccount);
|
|
@@ -81,7 +81,7 @@ function AccountCard({ account, state, snapshot, now, theme, layout, host, onCha
|
|
|
81
81
|
{"sessionId" in loginSession ? "Finish signing in in your browser. Status and limits will update automatically." : "A sign-in from an older version is still open. Cancel it, then sign in again to use the browser flow."}
|
|
82
82
|
</Notice> : null}
|
|
83
83
|
{panel === "menu" ? <View style={{ ...row, paddingTop: 2 }}>
|
|
84
|
-
<Button theme={theme} variant="ghost" disabled={busy || Boolean(loginSession)} onPress={() => action.run(() => refresh({ accountId: account.id }))}>Refresh limits</Button>
|
|
84
|
+
<Button theme={theme} variant="ghost" disabled={busy || checksOff || Boolean(loginSession)} onPress={() => action.run(() => refresh({ accountId: account.id }))}>Refresh limits</Button>
|
|
85
85
|
<Button theme={theme} variant="ghost" disabled={busy} onPress={() => action.run(async () => {
|
|
86
86
|
const result = await check({ accountId: account.id });
|
|
87
87
|
setNotice(result.authStatus === "ready" ? "Sign-in confirmed. You can now select this account for agents." : "Sign-in is not confirmed yet. Finish signing in in your browser, then check again.");
|
|
@@ -111,7 +111,7 @@ function AccountCard({ account, state, snapshot, now, theme, layout, host, onCha
|
|
|
111
111
|
{notice ? <Notice theme={theme}>{notice}</Notice> : null}
|
|
112
112
|
{action.error ? <Notice theme={theme} tone="danger">{errorMessage(action.error)}</Notice> : null}
|
|
113
113
|
<QuotaSummary theme={theme} snapshot={snapshot} now={now} compact={layout.compact}
|
|
114
|
-
onRefresh={loginSession ? undefined : () => action.run(() => refresh({ accountId: account.id }))} refreshing={busy} />
|
|
114
|
+
onRefresh={loginSession || checksOff ? undefined : () => action.run(() => refresh({ accountId: account.id }))} refreshing={busy} />
|
|
115
115
|
</View>;
|
|
116
116
|
}
|
|
117
117
|
|
|
@@ -177,6 +177,7 @@ export function AccountsSurface(props: AccountsProps) {
|
|
|
177
177
|
const onStarted = (account: Account, session: LoginSession) => setSignIn({ account, hostId: host.id, sessionId: session.id, initial: session, autoOpen: true });
|
|
178
178
|
const onResume = (account: Account, sessionId: string) => setSignIn({ account, hostId: host.id, sessionId, autoOpen: false });
|
|
179
179
|
const state = accounts.data;
|
|
180
|
+
const checksOff = usage.data?.checksOff === true;
|
|
180
181
|
const enabled = state?.integration.enabled ?? false;
|
|
181
182
|
const installed = providers.filter((option) => state?.providers[option.value].available ?? true);
|
|
182
183
|
const toggleIntegration = () => action.run(() => integration({ enabled: !enabled }));
|
|
@@ -190,7 +191,7 @@ export function AccountsSurface(props: AccountsProps) {
|
|
|
190
191
|
{enabled ? <InlineAction theme={theme} disabled={action.isPending} onPress={toggleIntegration}>Disable</InlineAction> : null}
|
|
191
192
|
</View> : <Text style={muted(theme)}>{accounts.isPending ? "Loading…" : "Data unavailable"}</Text>}
|
|
192
193
|
</View>
|
|
193
|
-
<IconButton theme={theme} icon="RefreshCw" label="Refresh all limits" disabled={action.isPending} onPress={() => action.run(() => refresh({}))} />
|
|
194
|
+
<IconButton theme={theme} icon="RefreshCw" label="Refresh all limits" disabled={action.isPending || checksOff} onPress={() => action.run(() => refresh({}))} />
|
|
194
195
|
<Button theme={theme} variant="primary" disabled={action.isPending || (!adding && !installed.length)} onPress={() => setAdding(adding ? null : installed[0]?.value ?? null)}>{adding ? "Close" : "Add"}</Button>
|
|
195
196
|
</View>
|
|
196
197
|
{state && !enabled ? <View style={{ flexDirection: "row", alignItems: "center", gap: 8, flexWrap: "wrap" }}>
|
|
@@ -198,6 +199,7 @@ export function AccountsSurface(props: AccountsProps) {
|
|
|
198
199
|
<Button theme={theme} disabled={action.isPending} onPress={toggleIntegration}>Enable</Button>
|
|
199
200
|
</View> : null}
|
|
200
201
|
{state?.integration.error ? <Notice theme={theme} tone="danger">{state.integration.error}</Notice> : null}
|
|
202
|
+
{checksOff ? <Notice theme={theme} tone="warning">Check usage is off in this host's settings: limits stop updating, and a used-up account gets no switch offer.</Notice> : null}
|
|
201
203
|
{runtimeError ? <Notice theme={theme} tone="danger">{runtimeError}</Notice> : null}
|
|
202
204
|
{action.error ? <Notice theme={theme} tone="danger">{errorMessage(action.error)}</Notice> : null}
|
|
203
205
|
{accounts.error ? <Notice theme={theme} tone="danger">Could not refresh accounts: {errorMessage(accounts.error)}</Notice> : null}
|
|
@@ -225,7 +227,7 @@ export function AccountsSurface(props: AccountsProps) {
|
|
|
225
227
|
<View style={{ flex: 1, minWidth: 200 }}><Notice theme={theme} tone="warning">Account switching is off for {cliName[provider]}: its agents use the system CLI.</Notice></View>
|
|
226
228
|
<Button theme={theme} disabled={action.isPending} onPress={enableIntegration}>Enable</Button>
|
|
227
229
|
</View> : null}
|
|
228
|
-
{group.map((account) => <AccountCard key={account.id} {...props} account={account} state={state} snapshot={usage.data?.accounts.find((item) => item.accountId === account.id)} now={now} onStarted={onStarted} onResume={onResume} />)}
|
|
230
|
+
{group.map((account) => <AccountCard key={account.id} {...props} account={account} state={state} snapshot={usage.data?.accounts.find((item) => item.accountId === account.id)} checksOff={checksOff} now={now} onStarted={onStarted} onResume={onResume} />)}
|
|
229
231
|
{!group.length && status.available ? <View style={{ flexDirection: "row", alignItems: "center", gap: 6 }}>
|
|
230
232
|
<Text style={muted(theme)}>No accounts.</Text>
|
|
231
233
|
<InlineAction theme={theme} onPress={() => setAdding(provider)}>Add</InlineAction>
|
package/client/screens.ts
CHANGED
|
@@ -10,7 +10,7 @@ function AccountsSidebarRow({ currentScreen, openScreen }: PluginSidebarItemProp
|
|
|
10
10
|
return createElement(SidebarRow, { icon: ICON, active: currentScreen?.screenId === SCREEN_ID, onPress: () => openScreen({ screenId: SCREEN_ID }) });
|
|
11
11
|
}
|
|
12
12
|
|
|
13
|
-
// The screen API replaced surfaces in Paseo 0.11;
|
|
13
|
+
// The screen API replaced surfaces in Paseo 0.11; the old names are deprecated. Ask the app what it has, not its version.
|
|
14
14
|
// Each registration is decided on its own, so an app that has only half of the new API still gets both pieces.
|
|
15
15
|
export function registerAccountsScreen(client: PluginClientContext, Component: ComponentType<PluginScreenProps>): () => void {
|
|
16
16
|
const removeScreen = typeof client.addScreen === "function"
|
package/index.server.ts
CHANGED
|
@@ -13,6 +13,8 @@ import type { AccountNote } from "./shared/timeline";
|
|
|
13
13
|
|
|
14
14
|
// Paseo hands `agent.create`'s environment to the same agent's first `agent.session_open`, which alone knows the agent ID.
|
|
15
15
|
const MODEL_ENV="PASEO_ACCOUNT_SWITCHER_MODEL";
|
|
16
|
+
// Set by whoever creates the agent (e.g. `paseo run --env PASEO_ACCOUNT_SWITCHER_ACCOUNT=Work`): the account it starts on.
|
|
17
|
+
const ACCOUNT_ENV="PASEO_ACCOUNT_SWITCHER_ACCOUNT";
|
|
16
18
|
// The prompt that resumes an agent's work on the account it was switched to.
|
|
17
19
|
const CONTINUE="Continue.";
|
|
18
20
|
const reason=(error:unknown)=>error instanceof Error?error.message:String(error);
|
|
@@ -124,8 +126,8 @@ export default function contribute(server:PluginServerContext){
|
|
|
124
126
|
return{};
|
|
125
127
|
});
|
|
126
128
|
server.handle(rpc.setIntegration,({enabled},{paseo})=>controller.integration(paseo,enabled));
|
|
127
|
-
server.handle(rpc.listUsage,async({visible},{paseo})=>{await controller.ensureRuntime(paseo);return{accounts:await controller.usage.list({visible})};});
|
|
128
|
-
server.handle(rpc.refreshUsage,async({accountId},{paseo})=>{await controller.ensureRuntime(paseo);return{accounts:await controller.usage.refresh(accountId)};});
|
|
129
|
+
server.handle(rpc.listUsage,async({visible},{paseo})=>{await controller.ensureRuntime(paseo);return{accounts:await controller.usage.list({visible}),checksOff:!await controller.usage.checksEnabled()};});
|
|
130
|
+
server.handle(rpc.refreshUsage,async({accountId},{paseo})=>{await controller.ensureRuntime(paseo);return{accounts:await controller.usage.refresh(accountId),checksOff:!await controller.usage.checksEnabled()};});
|
|
129
131
|
// Paseo's Usage view lists the managed accounts too; a daemon before 0.11 has no usage sources, and the Accounts screen still shows the same limits.
|
|
130
132
|
registerPaseoUsage(server,controller);
|
|
131
133
|
const removeCreate=server.before("agent.create",({request})=>{
|
|
@@ -135,8 +137,11 @@ export default function contribute(server:PluginServerContext){
|
|
|
135
137
|
});
|
|
136
138
|
const removeHook=server.before("agent.session_open",async({request},{paseo})=>{
|
|
137
139
|
await controller.ready;
|
|
138
|
-
|
|
139
|
-
|
|
140
|
+
// Neither hint from the creation reaches the CLI, on this or any later session of the agent.
|
|
141
|
+
const {[MODEL_ENV]:model,[ACCOUNT_ENV]:account,...env}=request.env;
|
|
142
|
+
const creating=request.purpose==="interactive"&&request.reason==="create",requested=account?.trim()||null;
|
|
143
|
+
if(creating&&requested&&request.provider!=="claude"&&request.provider!=="codex")throw new SwitchRefusal(`Account Switcher manages only Claude Code and Codex accounts, so the ${request.provider} agent cannot start on ${requested}.`);
|
|
144
|
+
if(creating&&(request.provider==="claude"||request.provider==="codex")){await controller.ensureRuntime(paseo);const bound=await controller.switcher(paseo).bindNewAgent(request.agentId,request.provider,model||null,requested);
|
|
140
145
|
const reason=bound?.reason;
|
|
141
146
|
if(bound&&reason){
|
|
142
147
|
const started=await note(request.agentId,async()=>{const state=await controller.store.read(),to=labelOf(state,bound.accountId);return to?{kind:"started",from:labelOf(state,bound.defaultId),to,reason}:null;});
|
|
@@ -175,6 +180,8 @@ export default function contribute(server:PluginServerContext){
|
|
|
175
180
|
const state=await controller.store.read();
|
|
176
181
|
// Without that provider's launcher the CLI runs on the system login, so a switch could not take effect.
|
|
177
182
|
if(!state.integration.enabled||!state.integration.providers.includes(provider)||settled(state))return;
|
|
183
|
+
// With the host's usage checks off nothing can read the account again, and an old reading is no proof that it ran out.
|
|
184
|
+
if(!await controller.usage.checksEnabled())return;
|
|
178
185
|
// An agent started with no app open may have a launch nothing has confirmed yet; its receipt confirms it now.
|
|
179
186
|
const fromId=await controller.accountOf(paseo,agent.id,provider,state),from=labelOf(state,fromId);
|
|
180
187
|
if(!fromId||!from)return;
|
package/npm-shrinkwrap.json
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "paseo-plugin-account-switcher",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.10.0",
|
|
4
4
|
"lockfileVersion": 3,
|
|
5
5
|
"requires": true,
|
|
6
6
|
"packages": {
|
|
7
7
|
"": {
|
|
8
8
|
"name": "paseo-plugin-account-switcher",
|
|
9
|
-
"version": "0.
|
|
9
|
+
"version": "0.10.0",
|
|
10
10
|
"license": "MIT",
|
|
11
11
|
"dependencies": {
|
|
12
12
|
"@iarna/toml": "^2.2.5"
|
package/package.json
CHANGED
package/paseo-plugin.json
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"id":"account-switcher","icon":"assets/icon.png","requirements":{"paseo":"0.11
|
|
1
|
+
{"id":"account-switcher","icon":"assets/icon.png","requirements":{"paseo":">=0.11.0"}}
|
package/server/controller.ts
CHANGED
|
@@ -11,9 +11,10 @@ import { prepareProfile } from "./profiles";
|
|
|
11
11
|
import { accountCommand, accountEnvironment, launchLogin, probeAccount, removeAccountCredentials } from "./auth";
|
|
12
12
|
import { installIntegration, restoreIntegration, writeLaunchers, prepareRuntime, reconcileIntegration } from "./integration";
|
|
13
13
|
import { SwitchRefusal, SwitchService } from "./switching";
|
|
14
|
-
import { createUsageService, readCredentialVersion, type AccountReadOptions, type QuotaAccount } from "./usage";
|
|
14
|
+
import { createUsageService, readCredentialVersion, usageChecksEnabled, type AccountReadOptions, type QuotaAccount } from "./usage";
|
|
15
15
|
import { renewExpiredClaudeToken } from "./usage/claude";
|
|
16
16
|
import { LoginSessions, type LoginDependencies } from "./login";
|
|
17
|
+
import { receiptProcessRuns } from "./process-identity";
|
|
17
18
|
|
|
18
19
|
const execFileAsync=promisify(execFile);
|
|
19
20
|
// Paseo sets these for its own Node processes, this plugin's included, and removes them before it starts an outside
|
|
@@ -25,6 +26,9 @@ const RUNTIME_ENV=["PASEO_NODE_ENV","PASEO_DESKTOP_MANAGED","PASEO_SUPERVISED","
|
|
|
25
26
|
function paseoCli(){const env={...process.env};for(const key of RUNTIME_ENV)delete env[key];return{command:process.env.PASEO_CLI?.trim()||"paseo",env};}
|
|
26
27
|
// A revoked sign-in fails every renewal; this bounds how often it starts the CLI.
|
|
27
28
|
const RENEWAL_INTERVAL=600000;
|
|
29
|
+
// A new agent's binding is written before its CLI starts, and Paseo reports no failed creation. This covers the time until the
|
|
30
|
+
// CLI reads the binding, where each plugin hook gets 30 seconds; from then on the launcher's receipt says whether that CLI still runs.
|
|
31
|
+
const CREATION_WAIT=600000;
|
|
28
32
|
// Agent statuses that show a launch got under way, for the receipt check: the Accounts list waits for a session that is
|
|
29
33
|
// up. Failover also takes "error", which Paseo sets when a turn fails, before the plugin's turn_ended hook runs: the
|
|
30
34
|
// launcher wrote the receipt when it started the CLI, so the receipt still names the account the agent started on.
|
|
@@ -53,7 +57,7 @@ export class AccountController {
|
|
|
53
57
|
// A crash during reload must not leave an unconfirmed account marked applied.
|
|
54
58
|
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.";}}});
|
|
55
59
|
});
|
|
56
|
-
this.usage=createUsageService({getAccounts:input=>this.quotaAccounts(input),cachePath:join(root,"usage-cache.json")});
|
|
60
|
+
this.usage=createUsageService({getAccounts:input=>this.quotaAccounts(input),cachePath:join(root,"usage-cache.json"),checksEnabled:()=>usageChecksEnabled(join(dirname(root),"config.json"))});
|
|
57
61
|
void this.ready.then(()=>{if(!this.disposed)this.usage.start();}).catch(()=>{});
|
|
58
62
|
}
|
|
59
63
|
async ensureRuntime(paseo:PaseoApi){
|
|
@@ -113,16 +117,36 @@ export class AccountController {
|
|
|
113
117
|
}
|
|
114
118
|
}catch{return;}
|
|
115
119
|
if(!complete)return;
|
|
120
|
+
// The list leaves agents out, those in background workspaces among them, so only Paseo's answer for the agent itself proves it is gone.
|
|
121
|
+
const now=Date.now(),gone=new Set<string>();
|
|
122
|
+
for(const binding of before.bindings){
|
|
123
|
+
if(existing.has(binding.agentId)||this.applying.has(binding.agentId)||binding.status==="switching")continue;
|
|
124
|
+
if(!binding.registrationObserved&&binding.currentAccountId===null&&!await this.creationOver(binding,now))continue;
|
|
125
|
+
const known=await paseo.agents.ref(binding.agentId).refresh().then(found=>!!found,()=>undefined);
|
|
126
|
+
if(known)existing.add(binding.agentId);else if(known===false)gone.add(binding.agentId);
|
|
127
|
+
}
|
|
116
128
|
await this.store.change(r=>{
|
|
117
129
|
r.bindings=r.bindings.filter(binding=>{
|
|
118
130
|
if(existing.has(binding.agentId)){binding.registrationObserved=true;return true;}
|
|
119
131
|
if(captured.get(binding.agentId)!==JSON.stringify(binding)||this.applying.has(binding.agentId)||binding.status==="switching")return true;
|
|
120
|
-
|
|
121
|
-
//
|
|
122
|
-
|
|
132
|
+
if(gone.has(binding.agentId))return false;
|
|
133
|
+
// session_open runs before native creation/registration, so a new agent's binding that has never appeared in Paseo
|
|
134
|
+
// may belong to a creation still under way. A binding from before 0.9 starts its wait here.
|
|
135
|
+
if(!binding.registrationObserved&&binding.currentAccountId===null)binding.boundAt??=new Date(now).toISOString();
|
|
136
|
+
return true;
|
|
123
137
|
});
|
|
124
138
|
});
|
|
125
139
|
}
|
|
140
|
+
/** Whether a new agent's creation can no longer use its profile: the wait is over and no CLI of its launch still runs.
|
|
141
|
+
* A profile that may be in use is not released, so anything unclear about the receipt keeps the binding. */
|
|
142
|
+
private async creationOver(binding:StoredBinding,now:number):Promise<boolean>{
|
|
143
|
+
if(!binding.boundAt||now-Date.parse(binding.boundAt)<CREATION_WAIT)return false;
|
|
144
|
+
let pid:unknown,at:unknown;
|
|
145
|
+
try{({pid,at}=JSON.parse(await readFile(join(this.store.root,"receipts",encodeURIComponent(binding.agentId)+".json"),"utf8")));}
|
|
146
|
+
catch(error){return (error as NodeJS.ErrnoException).code==="ENOENT";}
|
|
147
|
+
if(typeof pid!=="number"||!Number.isInteger(pid)||pid<=0)return false;
|
|
148
|
+
return !await receiptProcessRuns(pid,at);
|
|
149
|
+
}
|
|
126
150
|
async setDefault(provider:Provider,id:string|null){
|
|
127
151
|
await this.ready;
|
|
128
152
|
if(id===null){await this.store.change(r=>{r.defaults[provider]=null;});return;}
|
|
@@ -340,25 +364,34 @@ export class AccountController {
|
|
|
340
364
|
return{provider:a.provider,busy:a.status==="running"||a.status==="initializing"||!!a.activeTurn||a.pendingPermissions.length>0,archived:!!a.archivedAt};
|
|
341
365
|
},reload:async(id)=>{
|
|
342
366
|
await requireIntegration();
|
|
343
|
-
const
|
|
344
|
-
|
|
345
|
-
if(
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
const
|
|
356
|
-
|
|
357
|
-
|
|
367
|
+
const agent=paseo.agents.ref(id) as {reload?:()=>Promise<unknown>;commands?:()=>Promise<unknown>};
|
|
368
|
+
// From Paseo 0.14 the SDK sends the request the CLI would, with no process to start and no daemon address to find.
|
|
369
|
+
if(agent.reload){
|
|
370
|
+
try{await agent.reload();}
|
|
371
|
+
catch(error){
|
|
372
|
+
console.error(`Native reload of agent ${id} failed: ${stripVTControlCharacters(error instanceof Error?error.message:String(error)).replace(/\s+/g," ").trim().slice(0,500)||"no output"}`);
|
|
373
|
+
throw new SwitchRefusal("The native agent reload failed. Check the agent status and try again.");
|
|
374
|
+
}
|
|
375
|
+
}else{
|
|
376
|
+
const config=JSON.parse(await readFile(join(dirname(this.store.root),"config.json"),"utf8"));
|
|
377
|
+
const listen=config.daemon?.listen;
|
|
378
|
+
if(typeof listen!=="string"||!listen)throw new SwitchRefusal("Could not identify the daemon for reload.");
|
|
379
|
+
const host=listen.replace(/^0\.0\.0\.0:/,"127.0.0.1:");
|
|
380
|
+
const cli=paseoCli();let command=cli.command;
|
|
381
|
+
const reload=(file:string)=>execFileAsync(file,["agent","reload",id,"--json","--host",host],{timeout:120_000,maxBuffer:1024*1024,env:cli.env});
|
|
382
|
+
try{
|
|
383
|
+
// A CLI that could not start reloaded nothing, so `paseo` on PATH can still try. One that ran and failed is not repeated.
|
|
384
|
+
await reload(command).catch(error=>{const code=(error as {code?:unknown}).code;if(command==="paseo"||(code!=="ENOENT"&&code!=="EACCES"))throw error;command="paseo";return reload(command);});
|
|
385
|
+
}
|
|
386
|
+
catch(error){
|
|
387
|
+
// The chat gets the refusal; the cause, which can name local paths, goes only to the plugin log.
|
|
388
|
+
const {code,signal,stderr}=error as {code?:unknown;signal?:unknown;stderr?:unknown};
|
|
389
|
+
console.error(`Native reload of agent ${id} with ${command} failed (${signal?`signal ${signal}`:`code ${code}`}): ${stripVTControlCharacters(String(stderr??"")).replace(/\s+/g," ").trim().slice(0,500)||"no output"}`);
|
|
390
|
+
throw new SwitchRefusal("The native agent reload failed. Check the agent status and try again.");
|
|
391
|
+
}
|
|
358
392
|
}
|
|
359
393
|
// Paseo 0.11 reloads into an idle session and spawns the CLI on first use; listing
|
|
360
394
|
// commands starts it so the launcher can confirm the account. Older hosts already started it.
|
|
361
|
-
const agent=paseo.agents.ref(id) as {commands?:()=>Promise<unknown>};
|
|
362
395
|
if(agent.commands)await agent.commands().catch(()=>{/* The receipt check reports a failed start. */});
|
|
363
396
|
}});
|
|
364
397
|
this.switches.set(paseo,service);return service;
|