paseo-plugin-account-switcher 0.6.0 → 0.7.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/OVERVIEW.md CHANGED
@@ -6,11 +6,14 @@ Limits cover every window the provider reports, such as 5-hour and weekly use, w
6
6
 
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
- - The account chip in the composer opens the switcher for that chat. Your selection applies only when you choose **Apply** while the agent is idle with no pending permission request, and Paseo reloads the agent with its session intact. If the switch fails, the plugin tries to restore the previous account.
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
+ - `/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
+ - 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
+ - The account chip in the composer opens the switcher for that chat. Your selection applies only when you choose **Apply**, or type `/account name`, while the agent is idle with no pending permission request, and Paseo reloads the agent with its session intact. If the switch fails, the plugin tries to restore the previous account.
10
13
 
11
14
  ## Setup
12
15
 
13
- - Paseo 0.11 to 0.13 on a macOS or Linux daemon, with Node.js 22.12 or newer.
16
+ - Paseo 0.11 to 0.14 on a macOS or Linux daemon, with Node.js 22.12 or newer.
14
17
  - 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.
15
18
  - A Claude or ChatGPT subscription for each account. API keys are not supported. Adding an account runs the official CLI sign-in from Paseo.
16
19
 
package/OVERVIEW.zh-CN.md CHANGED
@@ -8,11 +8,14 @@ Account Switcher 让你在 Paseo 中使用多个 Claude 和 ChatGPT/Codex 订阅
8
8
 
9
9
  - 你添加的每个账号都有独立的凭据配置文件。设置、技能和会话历史仍与现有 CLI 配置共享,因此配置文件并不是沙箱。
10
10
  - 在 Accounts 中选择 **Enable**,会让 Paseo 的 Claude 和 Codex 命令指向插件的启动器,启动器以智能体所选账号运行官方 CLI。**Disable** 会恢复原始命令;移除插件前请先执行它。
11
- - 输入框旁的账号标签会打开当前对话的切换器。只有在智能体空闲且没有待处理的权限请求时选择 **Apply**,所选账号才会生效,Paseo 会重新加载智能体并保留会话。如果切换失败,插件会尝试恢复之前的账号。
11
+ - 新智能体会使用其提供商的默认账号。如果最近读取的数据显示:默认账号已用尽某个账号级限制且重置时间尚未到来、Codex 报告不允许常规使用、其套餐不提供为该智能体选择的 Codex 模型,或默认账号需要重新登录,智能体会改用剩余百分比最多的已登录账号。单个模型的限制和额外付费用量不计入。所有账号都被排除时,仍使用默认账号。在 Accounts 中该提供商下选择 **Always use the default** 可关闭此行为,使默认账号始终生效。
12
+ - 在输入框中输入 `/account 名称` 可切换当前对话的账号,`/account default` 切换到提供商的默认账号:智能体空闲时立即生效,否则在切换器中通过 **Apply** 应用。命令中心(⌘K)为每个已登录账号提供 **Make “名称” the default**。
13
+ - 对话中会有一行记录已应用的切换,以及新智能体未使用默认账号的原因。这些记录是尽力而为的,在守护进程重启后不会保留。
14
+ - 输入框旁的账号标签会打开当前对话的切换器。只有在智能体空闲且没有待处理的权限请求时选择 **Apply** 或输入 `/account 名称`,所选账号才会生效,Paseo 会重新加载智能体并保留会话。如果切换失败,插件会尝试恢复之前的账号。
12
15
 
13
16
  ## 设置
14
17
 
15
- - macOS 或 Linux 守护进程上的 Paseo 0.11 至 0.13,以及 Node.js 22.12 或更高版本。
18
+ - macOS 或 Linux 守护进程上的 Paseo 0.11 至 0.14,以及 Node.js 22.12 或更高版本。
16
19
  - 守护进程上需要官方 Paseo CLI,以及 Claude Code 或 Codex 至少其一。缺少 CLI 的提供商会显示为不可用;安装后重新加载插件,并在该提供商的分区中选择 **Enable**。
17
20
  - 每个账号都需要 Claude 或 ChatGPT 订阅。不支持 API 密钥。添加账号时,会在 Paseo 中运行官方 CLI 登录流程。
18
21
 
package/README.md CHANGED
@@ -11,14 +11,16 @@ Listed in the [Paseo plugin directory](https://paseo.sh/plugins/dutchakdev/accou
11
11
  ![Accounts in Paseo: two Claude accounts with their 5-hour and weekly limits and the start of a Codex account. Personal details are redacted.](docs/assets/accounts.png)
12
12
 
13
13
  - **Sign in from Paseo.** Add an account, finish the official provider sign-in, and return to your chat.
14
- - **Switch per agent.** The account chip opens a dialog on desktop or a bottom sheet on mobile. Changes apply only when you choose **Apply**.
14
+ - **Switch per agent.** The account chip opens a dialog on desktop or a bottom sheet on mobile. Changes apply only when you choose **Apply** or type `/account name`.
15
15
  - **Keep your setup.** Profiles separate credentials while sharing provider settings, skills, and session history.
16
16
  - **Track account limits.** See used and remaining percentages, reset times, and freshness for every reported window.
17
- - **Use a default.** Choose the account used by new agents for each provider.
17
+ - **Switch from the keyboard.** Type `/account work` in a chat, or pick **Make “Work” the Codex default** in the Command Center (⌘K).
18
+ - **See it in the chat.** A line in the chat records applied switches, and why a new agent did not start on the default.
19
+ - **Use a default.** Choose the account used by new agents for each provider. When the latest limits show it would fail, a new agent starts on another signed-in account instead.
18
20
 
19
21
  ## Requirements
20
22
 
21
- - **Paseo 0.11.x through 0.13.x**, including beta releases after 0.11.0, on a **macOS or Linux** daemon and on the connected client.
23
+ - **Paseo 0.11.x through 0.14.x**, including beta releases after 0.11.0, on a **macOS or Linux** daemon and on the connected client.
22
24
  - **Node.js 22.12.0 or newer**, with npm.
23
25
  - 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.
24
26
  - Claude or ChatGPT subscription authentication. API keys and custom authentication/provider overrides are unsupported.
@@ -29,7 +31,7 @@ The interface is in English. Reset dates use the viewing device's local time zon
29
31
 
30
32
  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 it sends no model messages. The commands below target the local daemon; for another host, see [remote daemons](docs/installation.md#remote-daemons).
31
33
 
32
- On Paseo 0.11.0 or a later release, including 0.12 and 0.13, install the reviewed version from the plugin directory:
34
+ On Paseo 0.11.0 or a later release, including 0.12, 0.13 and 0.14, install the reviewed version from the plugin directory:
33
35
 
34
36
  ```sh
35
37
  paseo plugin add dutchakdev/account-switcher
@@ -79,6 +81,21 @@ Closing the dialog leaves **Continue sign-in** on the account. **Cancel sign-in*
79
81
 
80
82
  The **⋯** menu contains refresh, check sign-in, default, sign-in, rename, and remove actions. Account rows show identity, default status, and counts of current and pending agents.
81
83
 
84
+ ### Default for new agents
85
+
86
+ A new Claude or Codex agent starts on its provider's default account. It starts on another signed-in account of the same provider only when the provider's own data shows the default would fail:
87
+
88
+ - an account-wide limit of the default, such as the 5-hour or weekly window, is at 100% and its reset time is still ahead. Limits of a single model, such as a weekly Opus limit, and extra paid usage do not count, and a full window without a reset time proves nothing;
89
+ - for Codex, the latest reading says ordinary usage is not allowed;
90
+ - for Codex, the latest reading of the default's plan does not offer the model chosen for the agent. This needs a model chosen explicitly at creation and listed by at least one account; aliases resolved later by Paseo are not checked;
91
+ - the official sign-in check says the default needs sign-in, or cannot confirm it.
92
+
93
+ 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.
94
+
95
+ 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.
96
+
97
+ 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.
98
+
82
99
  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.
83
100
 
84
101
  ## Switch an existing chat
@@ -89,6 +106,25 @@ Before signing in again, switch agents away from that profile. To remove a manag
89
106
 
90
107
  <img src="docs/assets/account-dialog.png" width="420" alt="The Account dialog for a Claude agent: limits of its current account and the accounts it can switch to.">
91
108
 
109
+ ### From the keyboard
110
+
111
+ Type `/account` in the message field followed by an account name, or `default` for the provider's default account. An account literally named **Default** takes precedence over the keyword. Names match without regard to case, and a unique beginning is enough: `/account sec` finds **Second**. Several matches or none report the accounts to choose from.
112
+
113
+ - When the agent is idle and nothing warns against the switch, `/account` applies it at once.
114
+ - While the agent is responding, or when the account's plan does not offer the agent's model, the account is selected and the switcher opens, where **Apply** and the warning are visible.
115
+ - `/account` alone, or the account already in use, opens the switcher.
116
+
117
+ The Command Center (⌘K) lists **Make “name” the Claude default** and **Make “name” the Codex default** for every signed-in account that is not already its provider's default.
118
+
119
+ ### In the chat
120
+
121
+ The chat records the account in a quiet line:
122
+
123
+ - after an applied switch: *Account switched from Work to Second.*
124
+ - when a new agent did not start on the default: *Starting on Second: the default Work has used up a limit.* The other reasons are a plan without the agent's model, a default that needs sign-in, and a default whose sign-in could not be checked. The line is written as the agent is created, before its CLI confirms the launch.
125
+
126
+ These lines live in the daemon's memory, like other plugin timeline rows: they stay through reconnects and refetches, but not a daemon restart. They are best effort: when the host refuses a line, the switch still stands and the plugin log records why.
127
+
92
128
  You can select an account during a response, but it is **never applied automatically**. **Cancel selection** clears it. **All accounts** opens the full account list.
93
129
 
94
130
  Apply reloads the agent through Paseo while preserving its native session ID. The plugin confirms the new account only after startup confirmation and successful reload. If a switch fails, it attempts to restore the previous account. **Account not confirmed** means the running account could not be established; select an account and apply again.
@@ -1,7 +1,7 @@
1
1
  import { useRpc, type PluginSurfaceProps } from "@getpaseo/plugin/client";
2
2
  import { useState } from "react";
3
3
  import { ScrollView, Text, View } from "react-native";
4
- import { addAccount, cancelLogin, checkLogin, cliName, missingCli, refreshUsage, removeAccount, renameAccount, setDefaultAccount, setIntegration, startLogin,
4
+ import { addAccount, cancelLogin, checkLogin, cliName, missingCli, refreshUsage, removeAccount, renameAccount, setDefaultAccount, setFallback, setIntegration, startLogin,
5
5
  type Account, type AccountState, type LoginSession, type Provider, type UsageSnapshot } from "../shared/contracts";
6
6
  import { body, Button, Field, heading, IconButton, InlineAction, muted, Notice, QuotaSummary, row, Segmented, StatusDot, toneColor } from "./components";
7
7
  import { useAccountsData, useAction, useNow } from "./data";
@@ -153,6 +153,7 @@ export function AccountsSurface(props: AccountsProps) {
153
153
  const { accounts, usage } = useAccountsData(host.id);
154
154
  const refresh = useRpc(refreshUsage);
155
155
  const integration = useRpc(setIntegration);
156
+ const fallback = useRpc(setFallback);
156
157
  const action = useAction(host.id, onChanged);
157
158
  const now = useNow();
158
159
  const [adding, setAdding] = useState<Provider | null>(null);
@@ -195,6 +196,14 @@ export function AccountsSurface(props: AccountsProps) {
195
196
  <Text accessibilityRole="header" style={heading(theme)}>{providerName[provider]}</Text>
196
197
  <Text style={muted(theme)}>{group.length}</Text>
197
198
  </View>
199
+ {state.defaults[provider] && group.length > 1 ? <View style={{ gap: 4 }}>
200
+ <Segmented theme={theme} label={`When the ${providerName[provider]} default would fail`} value={state.fallback[provider] ? "fallback" : "default"}
201
+ disabled={action.isPending} onChange={(value) => action.run(() => fallback({ provider, enabled: value === "fallback" }))}
202
+ options={[{ value: "fallback", label: "Start on another account" }, { value: "default", label: "Always use the default" }]} />
203
+ <Text style={muted(theme)}>{state.fallback[provider]
204
+ ? "A new agent starts on another signed-in account when the latest limits show the default would fail."
205
+ : "New agents always start on the default, even when its limits are used up."}</Text>
206
+ </View> : null}
198
207
  {!status.available ? <Notice theme={theme}>{missingCli(provider)}</Notice>
199
208
  : enabled && !status.integrated ? <View style={{ flexDirection: "row", alignItems: "center", gap: 8, flexWrap: "wrap" }}>
200
209
  <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>
@@ -0,0 +1,64 @@
1
+ import type { Account, AccountState, Provider, UsageSnapshot } from "../shared/contracts";
2
+ import { agentModel, currentAccount, idleForSwitch, switchRisk } from "./format";
3
+ import { accountAvailable } from "./login";
4
+
5
+ export type AccountArgument = { kind: "open" } | { kind: "account"; account: Account } | { kind: "error"; message: string };
6
+
7
+ const shortName: Record<Provider, string> = { claude: "Claude", codex: "Codex" };
8
+
9
+ /** What `/account <args>` refers to among the agent's provider accounts. Never guesses between several matches. */
10
+ export function resolveAccountArgument(state: AccountState, provider: Provider, args: string): AccountArgument {
11
+ const query = args.trim();
12
+ if (!query) return { kind: "open" };
13
+ const accounts = state.accounts.filter((account) => account.provider === provider);
14
+ let account: Account | undefined;
15
+ // An account that is literally named "Default" wins over the keyword.
16
+ if (query.toLowerCase() === "default" && !accounts.some((item) => item.label.toLowerCase() === "default")) {
17
+ account = accounts.find((item) => item.id === state.defaults[provider]);
18
+ if (!account) return { kind: "error", message: `No default ${shortName[provider]} account is set. Choose one in Accounts.` };
19
+ } else {
20
+ const wanted = query.toLowerCase();
21
+ const exact = accounts.filter((item) => item.label.toLowerCase() === wanted);
22
+ const matches = exact.length ? exact : accounts.filter((item) => item.label.toLowerCase().startsWith(wanted));
23
+ if (matches.length > 1) return { kind: "error", message: `“${query}” matches several ${shortName[provider]} accounts: ${matches.map((item) => item.label).join(", ")}.` };
24
+ if (!matches.length) return { kind: "error", message: `No ${shortName[provider]} account is named “${query}”. Accounts: ${accounts.map((item) => item.label).join(", ")}.` };
25
+ account = matches[0];
26
+ }
27
+ if (!accountAvailable(account)) return { kind: "error", message: `“${account.label}” ${account.login ? "is still signing in" : "needs sign-in"}. Check it in Accounts.` };
28
+ return { kind: "account", account };
29
+ }
30
+
31
+ export type DefaultCommand = { id: string; title: string; provider: Provider; accountId: string };
32
+
33
+ /** Command Center entries that make a signed-in account its provider's default. */
34
+ export function defaultCommands(state: AccountState): DefaultCommand[] {
35
+ return (["codex", "claude"] as const).flatMap((provider) => state.accounts
36
+ .filter((account) => account.provider === provider && accountAvailable(account) && state.defaults[provider] !== account.id)
37
+ .map((account) => ({ id: `default-${account.id}`, title: `Make “${account.label}” the ${shortName[provider]} default`, provider, accountId: account.id })));
38
+ }
39
+
40
+ export type AccountCommandDependencies = {
41
+ state(): Promise<AccountState>;
42
+ usage(): Promise<UsageSnapshot[]>;
43
+ /** The agent's latest snapshot; null when it no longer exists. */
44
+ agent(): Promise<Parameters<typeof idleForSwitch>[0] & Parameters<typeof agentModel>[0]>;
45
+ prepare(accountId: string): Promise<unknown>;
46
+ apply(accountId: string): Promise<unknown>;
47
+ openSwitcher(): void;
48
+ };
49
+
50
+ /** `/account [name | default]`: applies at once when the agent is idle and nothing warns against it; otherwise leaves the
51
+ * selection pending in the switcher, where Apply and any warning are visible. Throws messages for the host's error toast. */
52
+ export async function runAccountCommand(provider: Provider | null, agentId: string, args: string, deps: AccountCommandDependencies): Promise<"opened" | "applied" | "pending"> {
53
+ if (!provider) throw new Error("Account switching is available for Claude and Codex only.");
54
+ const state = await deps.state();
55
+ const target = resolveAccountArgument(state, provider, args);
56
+ if (target.kind === "error") throw new Error(target.message);
57
+ if (target.kind === "open" || currentAccount(state, agentId, provider)?.id === target.account.id) { deps.openSwitcher(); return "opened"; }
58
+ await deps.prepare(target.account.id);
59
+ const [agent, usage] = await Promise.all([deps.agent(), deps.usage().catch(() => [])]);
60
+ const risk = switchRisk({ label: target.account.label, models: usage.find((item) => item.accountId === target.account.id)?.models }, agentModel(agent));
61
+ if (risk || !idleForSwitch(agent)) { deps.openSwitcher(); return "pending"; }
62
+ await deps.apply(target.account.id);
63
+ return "applied";
64
+ }
@@ -0,0 +1,13 @@
1
+ import type { PluginTimelineItemProps } from "@getpaseo/plugin/client";
2
+ import { Icon } from "@getpaseo/plugin/client/react-native";
3
+ import { Text, View } from "react-native";
4
+ import { noteText, type AccountNote } from "../shared/timeline";
5
+ import { muted } from "./components";
6
+
7
+ /** One quiet timeline line: which account the agent runs on from here, and why when the plugin chose it. */
8
+ export function AccountNoteRow({ theme, item }: PluginTimelineItemProps<AccountNote>) {
9
+ return <View accessibilityRole="text" style={{ flexDirection: "row", alignItems: "center", gap: 6, paddingVertical: 4 }}>
10
+ <Icon name="Users" size={14} color={theme.colors.foregroundMuted} />
11
+ <Text style={{ ...muted(theme), flexShrink: 1 }}>{noteText(item.data)}</Text>
12
+ </View>;
13
+ }
package/client/runtime.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import type { PluginButtonIcon, PluginButtonRegistration, PluginClientContext } from "@getpaseo/plugin/client";
2
- import { listAccounts, listUsage, type AccountState, type UsageSnapshot } from "../shared/contracts";
2
+ import { listAccounts, listUsage, setDefaultAccount, type AccountState, type UsageSnapshot } from "../shared/contracts";
3
+ import { defaultCommands } from "./command";
3
4
  import { currentAccount, currentAccountName, errorMessage, supportedProvider, usageSummary } from "./format";
4
5
 
5
6
  // npm installs omit devDependencies, so `@getpaseo/client` types are named through the host SDK entry.
@@ -30,6 +31,8 @@ export function createClientRuntime(client: PluginClientContext, icon: PluginBut
30
31
  let modalTarget: PillTarget | null = null;
31
32
  let observingDirectory = false;
32
33
  let directorySubscription: DirectorySubscription | undefined;
34
+ // Command Center entries, keyed by item ID with their title, so a rename re-registers only that entry.
35
+ const defaultItems = new Map<string, { title: string; remove: () => void }>();
33
36
 
34
37
  function releaseDirectory(subscription: DirectorySubscription | undefined) {
35
38
  if (subscription) void subscription.release().catch((error) => {
@@ -74,6 +77,17 @@ export function createClientRuntime(client: PluginClientContext, icon: PluginBut
74
77
  }) });
75
78
  }
76
79
  function updateAllPills() { for (const agent of agents.values()) updatePill(agent); }
80
+ function syncDefaultItems() {
81
+ const wanted = state ? defaultCommands(state) : [];
82
+ for (const [id, item] of defaultItems) if (!wanted.some((command) => command.id === id && command.title === item.title)) { item.remove(); defaultItems.delete(id); }
83
+ for (const command of wanted) {
84
+ if (defaultItems.has(command.id)) continue;
85
+ const remove = client.addCommandCenterItem({ id: command.id, title: command.title, icon: "Users", context: "global",
86
+ keywords: ["account", "default", command.provider],
87
+ async onSelect({ rpc }) { await rpc(setDefaultAccount, { provider: command.provider, accountId: command.accountId }); void refreshData(); } });
88
+ defaultItems.set(command.id, { title: command.title, remove });
89
+ }
90
+ }
77
91
 
78
92
  const unsubscribe = client.paseo.agents.subscribe((update) => {
79
93
  if (stopped) return;
@@ -127,7 +141,7 @@ export function createClientRuntime(client: PluginClientContext, icon: PluginBut
127
141
  if (usageResult.status === "fulfilled") usage = usageResult.value.accounts;
128
142
  dataError = accountsResult.status === "rejected" ? `Could not refresh accounts: ${errorMessage(accountsResult.reason)}`
129
143
  : usageResult.status === "rejected" ? `Could not refresh limits: ${errorMessage(usageResult.reason)}` : null;
130
- updateAllPills(); notify();
144
+ updateAllPills(); syncDefaultItems(); notify();
131
145
  } catch (error) {
132
146
  if (!stopped) { dataError = `Could not refresh account switchers: ${errorMessage(error)}`; notify(); }
133
147
  } finally {
@@ -144,6 +158,7 @@ export function createClientRuntime(client: PluginClientContext, icon: PluginBut
144
158
  getError: () => directoryError ?? dataError,
145
159
  getModalTarget: () => modalTarget,
146
160
  closeModal,
161
+ openSwitcher: openModal,
147
162
  subscribe(listener: () => void) { listeners.add(listener); return () => { listeners.delete(listener); }; },
148
163
  stop() {
149
164
  if (stopped) return;
@@ -153,6 +168,8 @@ export function createClientRuntime(client: PluginClientContext, icon: PluginBut
153
168
  listeners.clear();
154
169
  for (const { registration } of pills.values()) registration.remove();
155
170
  pills.clear(); agents.clear();
171
+ for (const { remove } of defaultItems.values()) remove();
172
+ defaultItems.clear();
156
173
  },
157
174
  };
158
175
  }
@@ -108,7 +108,7 @@ export function AgentSwitcher({ theme, host, agentId, onChanged, openAccounts, c
108
108
  const latest = (await agent.refresh())?.agent;
109
109
  cache.setQueryData(agentKey, latest ?? null);
110
110
  if (!idleForSwitch(latest)) throw new Error("The agent is now busy. Wait for the turn to finish, then apply your selection again.");
111
- await apply({ agentId });
111
+ await apply({ agentId, accountId: pending.id });
112
112
  })}>{switching || action.isPending ? "Please wait…" : `Apply “${pending.label}”`}</Button>
113
113
  <Button theme={theme} variant="ghost" disabled={action.isPending || switching} onPress={() => action.run(() => prepare({ agentId, accountId: null }))}>Cancel selection</Button>
114
114
  </View>
package/index.client.tsx CHANGED
@@ -1,7 +1,12 @@
1
1
  import type { PluginButtonIconProps, PluginClientContext, PluginSurfaceProps } from "@getpaseo/plugin/client";
2
2
  import { Icon, Modal } from "@getpaseo/plugin/client/react-native";
3
3
  import { useSyncExternalStore } from "react";
4
+ import { applySwitch, listAccounts, listUsage, prepareSwitch } from "./shared/contracts";
5
+ import { ACCOUNT_NOTE_KIND, ACCOUNT_NOTE_VERSION, AccountNoteSchema } from "./shared/timeline";
4
6
  import { AccountsSurface } from "./client/accounts";
7
+ import { runAccountCommand } from "./client/command";
8
+ import { AccountNoteRow } from "./client/note";
9
+ import { supportedProvider } from "./client/format";
5
10
  import { createClientRuntime } from "./client/runtime";
6
11
  import { AgentSwitcher } from "./client/switcher";
7
12
 
@@ -32,5 +37,19 @@ export default function contribute(client: PluginClientContext) {
32
37
  const removeSidebar = client.addSidebarItem({ id: "accounts", title: "Accounts", icon: "Users", surface: "accounts" });
33
38
  const removeCommand = client.addCommandCenterItem({ id: "accounts", title: "Accounts and limits", icon: "Users", context: "global",
34
39
  keywords: ["accounts", "quota", "claude", "codex", "limits", "account"], onSelect: ({ openSurface }) => openSurface("accounts") });
35
- return () => { runtime.stop(); removeCommand(); removeSidebar(); removeSurface(); };
40
+ const removeSlash = client.addSlashCommand({ name: "account", description: "Switch this chat's account, or open the account switcher",
41
+ argumentHint: "[account name | default]", context: "agent",
42
+ async onSubmit({ args, agent, rpc, paseo }) {
43
+ const target = { workspaceId: agent.workspaceId, agentId: agent.id };
44
+ await runAccountCommand(supportedProvider(agent.provider), agent.id, args, {
45
+ state: () => rpc(listAccounts, {}),
46
+ usage: async () => (await rpc(listUsage, {})).accounts,
47
+ agent: async () => (await paseo.agents.ref(agent.id).refresh())?.agent ?? null,
48
+ prepare: (accountId) => rpc(prepareSwitch, { agentId: agent.id, accountId }),
49
+ apply: (accountId) => rpc(applySwitch, { agentId: agent.id, accountId }),
50
+ openSwitcher: () => runtime.openSwitcher(target),
51
+ }).finally(runtime.refresh);
52
+ } });
53
+ const removeNote = client.addTimelineRenderer({ kind: ACCOUNT_NOTE_KIND, version: ACCOUNT_NOTE_VERSION, schema: AccountNoteSchema, Component: AccountNoteRow });
54
+ return () => { runtime.stop(); removeNote(); removeSlash(); removeCommand(); removeSidebar(); removeSurface(); };
36
55
  }
package/index.server.ts CHANGED
@@ -2,13 +2,26 @@ import type { PluginServerContext } from "@getpaseo/plugin/server";
2
2
  import * as rpc from "./shared/contracts";
3
3
  import { AccountController } from "./server/controller";
4
4
  import { accountFrom } from "./server/store";
5
+ import { appendAccountNote } from "./server/timeline";
6
+ import type { AccountNote } from "./shared/timeline";
7
+
8
+ // Paseo hands `agent.create`'s environment to the same agent's first `agent.session_open`, which alone knows the agent ID.
9
+ const MODEL_ENV="PASEO_ACCOUNT_SWITCHER_MODEL";
5
10
 
6
11
  export default function contribute(server:PluginServerContext){
7
12
  const controller=new AccountController();
13
+ // Notes are best effort: a failure while preparing one is logged and never changes the switch or the agent's creation.
14
+ const note=async(agentId:string,make:()=>Promise<AccountNote|null>)=>{try{return await make();}catch(error){console.error(`Could not prepare the account note for agent ${agentId}: ${error instanceof Error?error.message:String(error)}`);return null;}};
15
+ const labelOf=(state:Awaited<ReturnType<typeof controller.store.read>>,id:string|null|undefined)=>id?state.accounts.find(a=>a.id===id)?.label??null:null;
16
+ // A new agent's note waits for `agent.created`: its timeline does not exist yet during session_open.
17
+ // An agent whose creation fails never gets that event, so entries expire.
18
+ const startNotes=new Map<string,{note:AccountNote;at:number}>();
19
+ const NOTE_TTL=600_000;
8
20
  server.handle(rpc.listAccounts,async(_,{paseo})=>controller.snapshot(paseo));
9
21
  server.handle(rpc.addAccount,async({provider,label},{paseo})=>{await controller.ensureRuntime(paseo);return controller.add(provider,label);});
10
22
  server.handle(rpc.renameAccount,async({accountId,label})=>{await controller.ready;return controller.store.change(r=>{const a=accountFrom(r,accountId);a.label=label;return rpc.AccountSchema.parse(a);});});
11
23
  server.handle(rpc.removeAccount,async({accountId},{paseo})=>{await controller.remove(accountId,paseo);return{};});
24
+ server.handle(rpc.setFallback,async({provider,enabled})=>{await controller.ready;await controller.store.change(r=>{r.fallback[provider]=enabled;});return{};});
12
25
  server.handle(rpc.setDefaultAccount,async({provider,accountId},{paseo})=>{await controller.ensureRuntime(paseo);await controller.setDefault(provider,accountId);return{};});
13
26
  server.handle(rpc.startLogin,async({accountId,mode},{paseo})=>{await controller.ensureRuntime(paseo);return controller.startLogin(paseo,accountId,mode);});
14
27
  server.handle(rpc.getLoginStatus,async({accountId,sessionId})=>controller.getLoginStatus(accountId,sessionId));
@@ -16,15 +29,51 @@ export default function contribute(server:PluginServerContext){
16
29
  server.handle(rpc.checkLogin,async({accountId},{paseo})=>{await controller.ensureRuntime(paseo);return controller.finishLogin(accountId);});
17
30
  server.handle(rpc.cancelLogin,async({accountId,sessionId},{paseo})=>{await controller.ensureRuntime(paseo);return controller.cancelLogin(paseo,accountId,sessionId);});
18
31
  server.handle(rpc.prepareSwitch,async({agentId,accountId},{paseo})=>{await controller.ensureRuntime(paseo);return controller.switcher(paseo).prepare(agentId,accountId);});
19
- server.handle(rpc.applySwitch,async({agentId},{paseo})=>{await controller.ensureRuntime(paseo);const binding=await controller.switcher(paseo).apply(agentId);if(binding.currentAccountId)void controller.usage.refresh(binding.currentAccountId).catch(()=>{});return binding;});
32
+ server.handle(rpc.applySwitch,async({agentId,accountId},{paseo})=>{
33
+ await controller.ensureRuntime(paseo);
34
+ const before=await controller.store.read().catch(()=>null);
35
+ const binding=await controller.switcher(paseo).apply(agentId,accountId);
36
+ if(binding.currentAccountId){
37
+ const to=binding.currentAccountId;
38
+ void controller.usage.refresh(to).catch(()=>{});
39
+ const switched=await note(agentId,async()=>{
40
+ const state=await controller.store.read(),prior=before?.bindings.find(b=>b.agentId===agentId);
41
+ // An agent without a binding ran on its provider's Current CLI account.
42
+ const fromId=prior?prior.currentAccountId:state.accounts.find(a=>a.source==="system"&&a.provider===binding.provider)?.id;
43
+ const label=labelOf(state,to);
44
+ return label?{kind:"switched",from:labelOf(state,fromId),to:label,reason:null}:null;
45
+ });
46
+ if(switched)void appendAccountNote(paseo,agentId,switched);
47
+ }
48
+ return binding;
49
+ });
20
50
  server.handle(rpc.setIntegration,({enabled},{paseo})=>controller.integration(paseo,enabled));
21
51
  server.handle(rpc.listUsage,async({visible},{paseo})=>{await controller.ensureRuntime(paseo);return{accounts:await controller.usage.list({visible})};});
22
52
  server.handle(rpc.refreshUsage,async({accountId},{paseo})=>{await controller.ensureRuntime(paseo);return{accounts:await controller.usage.refresh(accountId)};});
53
+ const removeCreate=server.before("agent.create",({request})=>{
54
+ const model=request.config.model;
55
+ if((request.config.provider!=="claude"&&request.config.provider!=="codex")||!model)return request;
56
+ return {...request,env:{...request.env,[MODEL_ENV]:model}};
57
+ });
23
58
  const removeHook=server.before("agent.session_open",async({request},{paseo})=>{
24
59
  await controller.ready;
25
- if(request.purpose==="interactive"&&request.reason==="create"&&(request.provider==="claude"||request.provider==="codex")){await controller.ensureRuntime(paseo);await controller.switcher(paseo).bindNewAgent(request.agentId,request.provider);}
26
- return request;
60
+ const {[MODEL_ENV]:model,...env}=request.env;
61
+ if(request.purpose==="interactive"&&request.reason==="create"&&(request.provider==="claude"||request.provider==="codex")){await controller.ensureRuntime(paseo);const bound=await controller.switcher(paseo).bindNewAgent(request.agentId,request.provider,model||null);
62
+ const reason=bound?.reason;
63
+ if(bound&&reason){
64
+ 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;});
65
+ const now=Date.now();
66
+ for(const [id,entry] of startNotes)if(now-entry.at>NOTE_TTL)startNotes.delete(id);
67
+ if(started)startNotes.set(request.agentId,{note:started,at:now});
68
+ }
69
+ }
70
+ // The model hint must not reach the provider CLI.
71
+ return {...request,env};
72
+ });
73
+ const removeCreated=server.on("agent.created",async({agent},{paseo})=>{
74
+ const pending=startNotes.get(agent.id);startNotes.delete(agent.id);
75
+ if(pending)void appendAccountNote(paseo,agent.id,pending.note);
76
+ await controller.observeAgentRegistration(agent.id);
27
77
  });
28
- const removeCreated=server.on("agent.created",async({agent})=>{await controller.observeAgentRegistration(agent.id);});
29
- return async()=>{removeHook();removeCreated();await controller.close();};
78
+ return async()=>{removeCreate();removeHook();removeCreated();startNotes.clear();await controller.close();};
30
79
  }
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "paseo-plugin-account-switcher",
3
- "version": "0.6.0",
3
+ "version": "0.7.1",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "paseo-plugin-account-switcher",
9
- "version": "0.6.0",
9
+ "version": "0.7.1",
10
10
  "license": "MIT",
11
11
  "dependencies": {
12
12
  "@iarna/toml": "^2.2.5"
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "paseo-plugin-account-switcher",
3
- "version": "0.6.0",
3
+ "version": "0.7.1",
4
4
  "type": "module",
5
5
  "license": "MIT",
6
6
  "author": "dutchakdev",
package/paseo-plugin.json CHANGED
@@ -1 +1 @@
1
- {"id":"account-switcher","icon":"assets/icon.png","requirements":{"paseo":"0.11.* || 0.12.* || 0.13.*"}}
1
+ {"id":"account-switcher","icon":"assets/icon.png","requirements":{"paseo":"0.11.* || 0.12.* || 0.13.* || 0.14.*"}}
@@ -121,7 +121,7 @@ export class AccountController {
121
121
  this.credentialProofs.delete(id);
122
122
  const quota=this.toQuotaAccount(account,state);
123
123
  // An idle account's token expires with no CLI running to renew it. Renew before the proof, so it covers the new token.
124
- if(account.provider==="claude"&&Date.now()-(this.renewals.get(id)??-Infinity)>=RENEWAL_INTERVAL&&await renewExpiredClaudeToken(quota))this.renewals.set(id,Date.now());
124
+ if(account.provider==="claude"&&Date.now()-(this.renewals.get(id)??-Infinity)>=RENEWAL_INTERVAL&&await renewExpiredClaudeToken(quota)){this.renewals.set(id,Date.now());console.log(`Asked the Claude CLI to renew the expired access token of account ${id}.`);}
125
125
  for(let attempt=0;;attempt++){
126
126
  const before=await readCredentialVersion(quota);
127
127
  identity=await probeAccount(account,state);
@@ -308,7 +308,7 @@ export class AccountController {
308
308
  switcher(paseo:PaseoApi):SwitchService {
309
309
  let service=this.switches.get(paseo);if(service)return service;
310
310
  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.");};
311
- service=new SwitchService({store:this.store,applying:this.applying,checkAccount:async id=>{await requireIntegration();return this.checkAccount(id);},inspect:async(id)=>{
311
+ service=new SwitchService({store:this.store,applying:this.applying,usage:()=>this.usage.list(),checkAccount:async id=>{await requireIntegration();return this.checkAccount(id);},inspect:async(id)=>{
312
312
  const result=await paseo.agents.ref(id).refresh();if(!result)throw new Error("Agent not found.");
313
313
  const a=result.agent;
314
314
  return{provider:a.provider,busy:a.status==="running"||a.status==="initializing"||!!a.activeTurn||a.pendingPermissions.length>0,archived:!!a.archivedAt};