Mod: run each Claude Code session on its own Claude subscription account, and switch live from a sidebar (Ctrl+Alt+Shift+numpad -) or /account-switch

A Claude Code mod for people with more than one Claude subscription. Each session can run on a different account, and you can switch a session live without logging out. Two terminals open side by side can be on your work and personal accounts at the same time.

It needs Claude Code 2.1.287 or later, the first release that loads mods. It has been tested on Linux with 2.1.296. The macOS and Windows code paths have unit tests but have not been run on either system.
Install it, start Claude Code, and run /login once for each account you want to use. After that, press Ctrl+Alt+Shift+numpad minus or run /account-switch to open the sidebar.
The one-liners below install from GitHub. From a clone, run ./install.sh or .\install.ps1 in the repository folder instead.
curl -fsSL https://github.com/sam-ruff/account-switcher-claude-code-mod/raw/main/install.sh | sh -s -- https://github.com/sam-ruff/account-switcher-claude-code-mod.git
curl -fsSL https://github.com/sam-ruff/account-switcher-claude-code-mod/raw/main/install.sh | sh -s -- https://github.com/sam-ruff/account-switcher-claude-code-mod.git
In PowerShell:
& ([scriptblock]::Create((irm https://github.com/sam-ruff/account-switcher-claude-code-mod/raw/main/install.ps1))) -Source https://github.com/sam-ruff/account-switcher-claude-code-mod.git
Each script checks your Claude Code version, adds this repository as a plugin marketplace and installs the mod. To remove it, run the same script with --uninstall (-Uninstall on Windows).
/login signs in to an account and saves it. A new login never replaces the one other sessions are using: the mod files it as an account of its own, and the session you ran /login in switches to it.
Open the sidebar with Ctrl+Alt+Shift+numpad minus, with /account-switch, or by clicking the "Account:" line above the prompt.
| Key | In the sidebar | | :- | :- | | Tab, Shift+Tab | Move between accounts and controls | | Up, Down | Move between accounts and controls, keeping the selection visible | | Enter | Switch this session to the selected account | | Right, Left | Change the hat Clawd wears for that account | | a | Add an account (runs /login) | | s | Toggle auto-switch | | r | Refresh usage | | Esc | Close |

The green account row is the one this session uses. Every other session keeps its own, and new sessions start on whichever account you picked last. A row turns red when that account is out of credits, even if it is the active one. Keyboard focus adds a light background tint and a padded name highlight; moving focus does not switch accounts until you press Enter. Clawd and his hat sit beside the account name, with matching space above and below each row. There are 13 hats to choose from, and each account remembers its own.
The compact ledger shows each account's remaining five-hour and weekly usage, with reset icons and local dates and times. Opening the panel reads usage using each account's own login, without switching the session. Usage refreshes every 15 seconds while the panel is open; closing it stops polling. Press r to request an immediate refresh. Missing or stale readings show as unknown. If the server rate-limits a refresh, automatic and manual refreshes both wait for its retry delay, with a minimum wait of 15 seconds. Expired logins need a switch to that account to refresh. Model-specific limits and extra usage are not included.
Accounts scroll inside the panel, separated by dividers. Use Up and Down or Tab to move focus; the selected account scrolls into view. The mouse wheel scrolls the account list. Controls and hints stay in a fixed footer. Names, emails and usage share the same left alignment. In narrow terminals the panel opens inline, and reset times stack below percentages when space is tight.
Alice has keyboard focus below, while Bob remains active in green. The original Clawd artwork keeps its proportions, including when wearing a hat.

In an 80-column terminal, scrolling from Bob to Carol leaves the controls and hints in place.


The screenshots use fictional accounts and fixed usage readings from the integration test's local API.
The same things work as commands, which is handy in claude -p where there is no sidebar:
/account-switch work switch by label, email, or the start of either
/account-switch 2 switch by position in the list
/account-switch list
/account-switch rename sam@acme.example Work
/account-switch hat work crown
/account-switch forget client
/account-switch auto on enable automatic budget failover
/account-switch auto off disable it
Auto-switch is off by default. Enable it in the sidebar or with /account-switch auto on; the mod remembers the setting. When an account hits a usage or billing limit, the session switches to the next signed-in account in list order, wrapping to the top, and sends a continuation prompt. Each account is tried once before stopping. Accounts needing /login are skipped. A new prompt from you, a manual switch, or toggling the setting starts a fresh attempt. Other sessions keep their own account.
Temporary server limits, other API errors, interrupted turns and subagent failures do not trigger auto-switch.
Don't use /logout to change accounts. Claude Code revokes the login on Anthropic's side when you log out, so every session using that account is signed out and you would have to sign in to it again. The mod asks before letting /logout go ahead.

The shortcut and the hat keys live in ~/.claude/keybindings.json, which the mod edits the first time it runs. It binds Ctrl+Alt+Shift+- to open the sidebar, and Right and Left in mod panes to change hats.
/account-switch keys off. /account-switch keys on puts them back.ctrl+alt+shift+- entry in the Global block to any key you like. Keep its value, app:toggleDiffPreSession.Pane context, the mod leaves your binding alone. Hats can then still be set with /account-switch hat.The numpad minus works in terminals that report modifier keys on it: kitty, WezTerm, Ghostty, foot, iTerm2 with the kitty keyboard protocol, and xterm with modifyOtherKeys. Claude Code can't tell numpad minus from the main minus key, so Ctrl+Alt+Shift with the main minus opens the sidebar too. In a terminal that reports neither, rebind it as above.
CLAUDE_CONFIG_DIR is respected if you keep Claude Code's files somewhere other than ~/.claude.
Claude Code reads its login from the directory named by CLAUDE_SECURESTORAGE_CONFIG_DIR, or from ~/.claude when that is unset. The mod gives each account a directory of its own under ~/.claude/accounts/ and points each session's variable at the account it should use. Token refreshes then land in that account's own copy, and a second session on another account never sees them. The login in ~/.claude itself is the default account, which claude without the mod keeps using. A new session starts on the last account chosen in any session, or on the default if that account has been forgotten or needs /login.
On Linux and Windows each account's login is a .credentials.json in its directory, readable only by you, the same way Claude Code stores its own. On macOS, where Claude Code keeps logins in the Keychain, each account is a Keychain item named after its directory.
There is one catch. ~/.claude.json holds a single "signed in as" record that every session shares, and /status reads it. So /status first points that record at the session's own account and waits about a second and a half for Claude Code to re-read the file. Requests never depend on that record, because they use each session's own login.
A session remembers its account across claude --resume.
To try the current checkout with your own accounts, run this from the repository root, then enter /account-switch. Use /login if an account needs signing in again.
claude --plugin-dir "$PWD/mods/account-switcher"
For a browser terminal, install ttyd and run:
COLORTERM=truecolor FORCE_COLOR=3 ttyd -i 127.0.0.1 -p 7681 -W -O -w "$PWD" claude --plugin-dir "$PWD/mods/account-switcher"
Open localhost:7681. This runs Claude Code with your local profile and accounts; it is an interactive terminal bound to this machine's loopback address.
Run the automated checks from the repository root:
npm test # unit tests, no session or network
scripts/integration-test.sh [path-to-claude] # two real sessions against a fake API
uv run --with pytest --with pyte pytest scripts/test_auto_switch.py
The integration test runs two Claude Code sessions side by side on one throwaway home directory. One stays on the default account and the other switches away and back. A fake API records which token each session sent, and both sessions run /status. It needs Python with pyte.
To regenerate the terminal screenshots and demo from the current implementation:
LEDGER_SCREENSHOTS="$PWD/docs/designs" uv run --with pytest --with pyte --with Pillow --with fonttools pytest scripts/test_auto_switch.py -k '140 or 80'
CI runs on the local [self-hosted, sophie] pool. After tests pass on a push to main, semantic-release uses Conventional Commits to update both plugin manifests and the changelog, then publishes a GitHub tag and release. feat makes a minor release; fix, perf and refactor make patches; breaking changes make major releases. The release job needs the repository's GITHUB_TOKEN to write contents, including the version commit on main.
The usage and reset design study contains three sidebar concepts with illustrative data. These previews do not fetch live usage.
hooks/register.ts 622 lines1import type { EngineInterface, Register, Timer } from 'claude-code'
2import {
3 type Account,
4 AccountStore,
5 bindsSwitchKey,
6 describe,
7 displayName,
8 FileCredentials,
9 hasHatBinding,
10 hasOldBinding,
11 hasSwitchBinding,
12 type Io,
13 matchAccount,
14 parseObject,
15 resolvePaths,
16 startingAccount,
17 SWITCH_ACTION,
18 SWITCH_KEY_LABEL,
19 withoutSwitchBinding,
20 withSwitchBinding,
21} from './accounts.ts'
22import { cycleHat, HATS } from './clawd.ts'
23import { detectStore, KeychainCredentials } from './keychain.ts'
24import { nextPanelFocus, orderedAccounts, panel, panelGeometry, panelRows, useKey } from './panel.ts'
25import { type Commands, commandsFor, detectPlatform, homeDir, joiner, type Platform } from './platform.ts'
26import { HttpUsageApi, UsageCache, USAGE_REFRESH_MS } from './usage.ts'
27
28const PANE = 'accounts'
29const PANE_COLUMNS = 52
30// Claude Code re-reads .claude.json about every half second; /status waits this long.
31const CONFIG_SETTLE_MS = 1500
32const SESSIONS_KEY = 'sessions'
33const KEYS_OFF_KEY = 'keys-off'
34const AUTO_SWITCH_KEY = 'auto-switch'
35const LAST_ACCOUNT_KEY = 'last-account'
36
37const HELP = [
38 'Usage:',
39 ` /account-switch open the account sidebar (or press ${SWITCH_KEY_LABEL})`,
40 ' /account-switch <name|number> switch this session to a saved account',
41 ' /account-switch list',
42 ' /account-switch auto on|off switch accounts when the budget runs out',
43 ' /account-switch add sign in to another account (same as /login)',
44 ' /account-switch rename <name> <label>',
45 ` /account-switch hat <name> <hat> one of: ${HATS.map(h => h.id).join(', ')}`,
46 ' /account-switch forget <name>',
47 ` /account-switch keys on|off add or remove the ${SWITCH_KEY_LABEL} and hat keys`,
48].join('\n')
49
50let accounts: Account[] = []
51let current: Account | undefined
52let focused = ''
53let notice = ''
54let autoSwitch = false
55const exhausted = new Set<string>()
56let switching = false
57let budgetFailure = false
58let usage: UsageCache | undefined
59let usageTimer: Timer | undefined
60let continuationTimer: Timer | undefined
61let listOffset = 0
62let panelWidth = PANE_COLUMNS
63let panelHeight = 30
64
65async function refreshUsage($: EngineInterface, force = false): Promise<void> {
66 const s = await refresh($)
67 usage ??= new UsageCache(new HttpUsageApi((url, init) => $.http.fetch(url, init), (await $.env.get('ANTHROPIC_BASE_URL')) || undefined), () => $.clock.now())
68 const cache = usage
69 await Promise.all(accounts.map(async account => {
70 await cache.refresh(account, async () => s.usageToken(account, await $.clock.now()), force)
71 $.ui.invalidate('ui.render')
72 }))
73}
74
75async function setAutoSwitch($: EngineInterface, enabled: boolean): Promise<string> {
76 await $.store.set(AUTO_SWITCH_KEY, enabled)
77 autoSwitch = enabled
78 exhausted.clear()
79 $.ui.invalidate('ui.render')
80 return `Auto-switch is ${enabled ? 'on' : 'off'}.`
81}
82
83async function switchAfterLimit($: EngineInterface): Promise<void> {
84 if (!autoSwitch || switching) return
85 switching = true
86 let continuationScheduled = false
87 try {
88 const s = await refresh($)
89 if (!current) return
90 exhausted.add(current.dir)
91 const index = accounts.findIndex(a => a.dir === current?.dir)
92 const ordered = [...accounts.slice(index + 1), ...accounts.slice(0, index)]
93 const target = ordered.find(a => !a.needsLogin && !exhausted.has(a.dir))
94 if (!target) {
95 notice = 'Auto-switch stopped: all available accounts are out of budget. Try again when a budget resets.'
96 $.ui.log(notice)
97 $.ui.invalidate('ui.render')
98 return
99 }
100 await useAccount($, s, target)
101 $.ui.log(`Budget exhausted. Switched this session to ${displayName(target)}.`)
102 continuationScheduled = true
103 continuationTimer = $.clock.every(CONFIG_SETTLE_MS, async () => {
104 continuationTimer?.cancel()
105 continuationTimer = undefined
106 try {
107 const continuation = await $.prompt.submit({ text: 'Continue the previous task from where it stopped because the account budget was exhausted.' })
108 if (continuation.drop) $.ui.log(`Auto-switch could not continue: ${continuation.drop}`)
109 } catch (error) {
110 $.ui.log(`Auto-switch could not continue: ${error instanceof Error ? error.message : String(error)}`)
111 } finally {
112 switching = false
113 }
114 })
115 } catch (error) {
116 $.ui.log(`Auto-switch failed: ${error instanceof Error ? error.message : String(error)}`)
117 } finally {
118 if (!continuationScheduled) switching = false
119 }
120}
121
122interface Env {
123 platform: Platform
124 commands: Commands
125 join: (...parts: string[]) => string
126}
127
128async function environment($: EngineInterface): Promise<Env> {
129 const platform = detectPlatform({ appData: await $.env.get('APPDATA'), userProfile: await $.env.get('USERPROFILE') })
130 return { platform, commands: commandsFor(platform), join: joiner(platform) }
131}
132
133async function readText($: EngineInterface, env: Env, path: string): Promise<string | null> {
134 if (!(await $.fs.exists(path))) return null
135 try {
136 return String(await $.fs.read(path))
137 } catch {
138 // $.fs.read stops at 4 MiB and a long-lived ~/.claude.json can be larger.
139 const r = await $.process.run(env.commands.read(path))
140 if (r.exitCode !== 0) throw new Error(`could not read ${path}: ${r.stderr.trim()}`)
141 return r.stdout
142 }
143}
144
145async function writeText($: EngineInterface, env: Env, path: string, text: string): Promise<void> {
146 const r = await $.process.run(env.commands.writeSecret(path), { stdin: text })
147 if (r.exitCode !== 0) throw new Error(`could not write ${path}: ${r.stderr.trim() || `exit ${r.exitCode}`}`)
148}
149
150function makeIo($: EngineInterface, env: Env, accountsDir: string): Io {
151 return {
152 read: path => readText($, env, path),
153 writeSecret: (path, text) => writeText($, env, path, text),
154 list: async dir => ((await $.fs.exists(dir)) ? (await $.fs.list(dir)).map(e => e.name) : []),
155 removeTree: async path => {
156 // Only ever delete inside the accounts directory.
157 if (!path.startsWith(accountsDir) || path === accountsDir) throw new Error(`refusing to delete ${path}`)
158 await $.process.run(env.commands.removeTree(path))
159 },
160 mkdir: async path => (await $.process.run(env.commands.mkdir(path))).exitCode === 0,
161 rmdir: async path => {
162 await $.process.run(env.commands.rmdir(path))
163 },
164 mtime: async path => ((await $.fs.exists(path)) ? (await $.fs.stat(path)).mtimeMs : null),
165 sleep: ms => $.clock.sleep(ms),
166 now: () => $.clock.now(),
167 }
168}
169
170async function store($: EngineInterface): Promise<AccountStore> {
171 const env = await environment($)
172 const home = homeDir(env.platform, { home: await $.env.get('HOME'), userProfile: await $.env.get('USERPROFILE') })
173 const configDir = await $.env.get('CLAUDE_CONFIG_DIR')
174 const legacy = await $.fs.exists(env.join(configDir || env.join(home, '.claude'), '.config.json'))
175 const paths = resolvePaths(home, configDir, legacy, env.join)
176 const io = makeIo($, env, paths.accountsDir)
177 const files = new FileCredentials(io, env.join)
178 const keychain = await macKeychain($, paths.configDir)
179 return new AccountStore(io, paths, await detectStore(files, keychain, paths.configDir))
180}
181
182/** The Keychain store on macOS, where `security` exists; undefined elsewhere. */
183async function macKeychain($: EngineInterface, defaultDir: string): Promise<KeychainCredentials | undefined> {
184 if (await $.env.get('APPDATA')) return undefined
185 const probe = await $.process.run(['sh', '-c', 'command -v security && uname -s']).catch(() => undefined)
186 if (!probe || probe.exitCode !== 0 || !probe.stdout.includes('Darwin')) return undefined
187 const user = (await $.env.get('USER')) || 'claude-code-user'
188 return new KeychainCredentials(
189 async (args, stdin) => {
190 const r = await $.process.run(['security', ...args], stdin === undefined ? {} : { stdin })
191 return { exitCode: r.exitCode, stdout: r.stdout }
192 },
193 /^[a-zA-Z0-9._-]+$/.test(user) ? user : 'claude-code-user',
194 defaultDir,
195 )
196}
197
198async function refresh($: EngineInterface): Promise<AccountStore> {
199 const s = await store($)
200 accounts = await s.list()
201 current = await s.forSession(await $.env.get('CLAUDE_SECURESTORAGE_CONFIG_DIR'))
202 $.ui.invalidate('ui.render')
203 return s
204}
205
206/** Switches this session to `account` and makes it the one new sessions start on. */
207async function useAccount($: EngineInterface, s: AccountStore, account: Account): Promise<void> {
208 await $.store.set(LAST_ACCOUNT_KEY, account.dir)
209 await applyAccount($, s, account)
210}
211
212/** Points this session's credential storage, and the shared account details, at `account`. */
213async function applyAccount($: EngineInterface, s: AccountStore, account: Account): Promise<void> {
214 await s.shareFromHome(account)
215 await $.env.set('CLAUDE_SECURESTORAGE_CONFIG_DIR', account.isHome ? undefined : account.dir)
216 await $.env.set('CLAUDE_CODE_ORGANIZATION_UUID', account.oauthAccount.organizationUuid)
217 await s.pointConfigAt(account.oauthAccount)
218 await rememberSession($, account)
219 await refresh($)
220}
221
222async function pointConfigAtSession($: EngineInterface): Promise<void> {
223 const s = await refresh($)
224 if (!current) return
225 await s.pointConfigAt(current.oauthAccount, true)
226 await $.clock.sleep(CONFIG_SETTLE_MS)
227}
228
229async function rememberSession($: EngineInterface, account: Account): Promise<void> {
230 const id = await $.session.id()
231 const saved = ((await $.store.get(SESSIONS_KEY)) as Record<string, string> | undefined) ?? {}
232 const next = Object.fromEntries(Object.entries({ ...saved, [id]: account.dir }).slice(-200))
233 await $.store.set(SESSIONS_KEY, next)
234}
235
236async function restoreSession($: EngineInterface, s: AccountStore): Promise<void> {
237 if (await $.env.get('CLAUDE_SECURESTORAGE_CONFIG_DIR')) return
238 const id = await $.session.id()
239 const saved = ((await $.store.get(SESSIONS_KEY)) as Record<string, string> | undefined) ?? {}
240 const last = await $.store.get(LAST_ACCOUNT_KEY)
241 const account = startingAccount(await s.list(), saved[id], typeof last === 'string' ? last : undefined)
242 if (account && !account.isHome) await applyAccount($, s, account)
243}
244
245async function keybindingsPath($: EngineInterface, s: AccountStore): Promise<string> {
246 return (await environment($)).join(s.configDir, 'keybindings.json')
247}
248
249async function installKeys($: EngineInterface, s: AccountStore, on: boolean): Promise<string> {
250 const env = await environment($)
251 const path = await keybindingsPath($, s)
252 const file = parseObject(await readText($, env, path), path) ?? {}
253 if (on && bindsSwitchKey(file) && !hasSwitchBinding(file)) {
254 return `${SWITCH_KEY_LABEL} already has a binding in keybindings.json, so it was left alone.`
255 }
256 await writeText($, env, path, JSON.stringify(on ? withSwitchBinding(file) : withoutSwitchBinding(file), null, 2))
257 await $.store.set(KEYS_OFF_KEY, !on)
258 return on
259 ? `${SWITCH_KEY_LABEL} opens the account sidebar, and Right and Left in it change Clawd's hat.`
260 : `Removed the ${SWITCH_KEY_LABEL} shortcut and the hat keys.`
261}
262
263/** Installs the shortcuts the first time, and upgrades the ones earlier versions used. */
264async function ensureKeys($: EngineInterface, s: AccountStore): Promise<void> {
265 if (await $.store.get(KEYS_OFF_KEY)) return
266 const env = await environment($)
267 const path = await keybindingsPath($, s)
268 const file = parseObject(await readText($, env, path), path) ?? {}
269 if (hasOldBinding(file)) {
270 await writeText($, env, path, JSON.stringify(withSwitchBinding(file), null, 2))
271 $.ui.log(`The account sidebar moved to ${SWITCH_KEY_LABEL}, and Ctrl+Shift+- is undo again.`)
272 return
273 }
274 if (hasSwitchBinding(file) && !hasHatBinding(file)) {
275 await writeText($, env, path, JSON.stringify(withSwitchBinding(file), null, 2))
276 return
277 }
278 if (bindsSwitchKey(file)) return
279 $.ui.log(await installKeys($, s, true))
280}
281
282function nameOf(account: Account | undefined): string {
283 return account ? displayName(account) : 'no account'
284}
285
286function formatList(list: Account[], active: Account | undefined): string {
287 if (list.length === 0) return 'No accounts yet. Run /login to sign in.'
288 return list
289 .map((a, i) => {
290 const flags = [a.dir === active?.dir ? 'this session' : '', a.isHome ? 'default' : '', a.needsLogin ? 'needs /login' : '']
291 .filter(Boolean)
292 .join(', ')
293 const detail = describe(a)
294 return `${i + 1}. ${displayName(a)}${detail ? ` ${detail}` : ''}${flags ? ` (${flags})` : ''}`
295 })
296 .join('\n')
297}
298
299async function switchTo($: EngineInterface, query: string): Promise<string> {
300 const s = await refresh($)
301 const match = matchAccount(accounts, query)
302 if (match.kind === 'none') return `No account matches "${query}".\n${formatList(accounts, current)}`
303 if (match.kind === 'ambiguous') return `"${query}" matches more than one account: ${match.candidates.map(displayName).join(', ')}`
304 if (match.account.dir === current?.dir) return `This session already uses ${displayName(match.account)}.`
305 await useAccount($, s, match.account)
306 exhausted.clear()
307 const warning = match.account.needsLogin ? ' Its login has expired, so run /login to sign in to it again.' : ''
308 return `This session now uses ${displayName(match.account)}. Other sessions keep their own account.${warning}`
309}
310
311async function setHat($: EngineInterface, account: Account, hat: string): Promise<void> {
312 const s = await store($)
313 await s.setHat(account, hat)
314 accounts = accounts.map(a => (a.dir === account.dir ? { ...a, hat } : a))
315 if (current?.dir === account.dir) current = { ...current, hat }
316 $.ui.invalidate('ui.render')
317}
318
319async function runCommand($: EngineInterface, args: string): Promise<string | null> {
320 const [verb = '', ...rest] = args.trim().split(/\s+/).filter(Boolean)
321 const s = await refresh($)
322
323 switch (verb.toLowerCase()) {
324 case '':
325 return null
326 case 'help':
327 return HELP
328 case 'list':
329 case 'ls':
330 return formatList(accounts, current)
331 case 'auto':
332 if (rest.length !== 1 || (rest[0] !== 'on' && rest[0] !== 'off')) return 'Usage: /account-switch auto on|off'
333 return setAutoSwitch($, rest[0] === 'on')
334 case 'add':
335 case 'login':
336 return 'Run /login and sign in. The new account is added and this session switches to it.'
337 case 'rename': {
338 const [query, ...label] = rest
339 if (!query || label.length === 0) return 'Usage: /account-switch rename <name> <label>'
340 const match = matchAccount(accounts, query)
341 if (match.kind !== 'found') return `No single account matches "${query}".`
342 await s.rename(match.account, label.join(' '))
343 await refresh($)
344 return `Renamed ${displayName(match.account)} to ${label.join(' ').trim()}.`
345 }
346 case 'hat': {
347 const [query, hatId] = rest
348 const hat = HATS.find(h => h.id === hatId?.toLowerCase())
349 if (!query || !hat) return `Usage: /account-switch hat <name> <${HATS.map(h => h.id).join('|')}>`
350 const match = matchAccount(accounts, query)
351 if (match.kind !== 'found') return `No single account matches "${query}".`
352 await setHat($, match.account, hat.id)
353 return `${displayName(match.account)}'s Clawd now wears: ${hat.name}.`
354 }
355 case 'forget':
356 case 'remove':
357 case 'rm': {
358 const query = rest.join(' ')
359 if (!query) return 'Usage: /account-switch forget <name>'
360 const match = matchAccount(accounts, query)
361 if (match.kind !== 'found') return `No single account matches "${query}".`
362 if (match.account.isHome) return `${displayName(match.account)} is the default login in ~/.claude. Use /logout from a session on it to remove it.`
363 if (match.account.dir === current?.dir) return `This session uses ${displayName(match.account)}. Switch to another account first.`
364 await s.forget(match.account)
365 await refresh($)
366 return `Forgot ${displayName(match.account)}. Its login stays valid on Anthropic's side until it expires.`
367 }
368 case 'keys':
369 return installKeys($, s, rest[0]?.toLowerCase() !== 'off')
370 case 'use':
371 case 'switch':
372 return rest.length ? switchTo($, rest.join(' ')) : HELP
373 default:
374 return switchTo($, args)
375 }
376}
377
378async function togglePane($: EngineInterface): Promise<void> {
379 if ((await $.ui.panes()).some(p => p.id === PANE)) {
380 await $.ui.close({ id: PANE })
381 return
382 }
383 notice = ''
384 listOffset = 0
385 await refresh($)
386 focused = current ? useKey(current) : ''
387 await $.ui.open({ id: PANE, title: 'Accounts', focus: true, closeOnEscape: true, columns: PANE_COLUMNS, rows: panelRows({ accounts, current }) })
388 await refreshUsage($)
389 usageTimer?.cancel()
390 usageTimer = $.clock.every(USAGE_REFRESH_MS, async () => {
391 if (!(await $.ui.panes()).some(p => p.id === PANE)) {
392 usageTimer?.cancel()
393 usageTimer = undefined
394 return
395 }
396 await refreshUsage($, true)
397 })
398}
399
400export const register: Register = on => {
401 on('ui.close', { id: PANE }, async ($, e, next) => {
402 const result = await next(e)
403 usageTimer?.cancel()
404 usageTimer = undefined
405 return result
406 })
407
408 on('session.end', async ($, e, next) => {
409 usageTimer?.cancel()
410 usageTimer = undefined
411 return next(e)
412 })
413
414 on('session.start', async ($, e, next) => {
415 try {
416 autoSwitch = (await $.store.get(AUTO_SWITCH_KEY)) === true
417 exhausted.clear()
418 usage = undefined
419 usageTimer?.cancel()
420 usageTimer = undefined
421 const s = await store($)
422 await s.learnHome()
423 await restoreSession($, s)
424 await refresh($)
425 if (e.isInteractive) await ensureKeys($, s)
426 } catch (error) {
427 $.ui.log(`account-switcher could not start: ${error instanceof Error ? error.message : String(error)}`, { to: 'debug' })
428 }
429 await $.command.register({
430 name: 'account-switch',
431 description: 'Switch this session between Claude subscription accounts',
432 argumentHint: '[name|list|add|rename|hat|forget|keys|auto]',
433 immediate: true,
434 })
435 return next(e)
436 })
437
438 on('prompt.submit', async ($, e, next) => {
439 if (['composer', 'bridge', 'sdk'].includes(e.origin.kind)) {
440 continuationTimer?.cancel()
441 continuationTimer = undefined
442 switching = false
443 exhausted.clear()
444 }
445 return next(e)
446 })
447
448 on('classic.StopFailure', async ($, e, next) => {
449 const result = await next(e)
450 const temporaryLimit = /not your usage limit/i.test(e.last_assistant_message ?? '')
451 if (!e.agent_id && !temporaryLimit && !result.preventContinuation && !result.block && (e.error === 'rate_limit' || e.error === 'billing_error')) {
452 budgetFailure = true
453 }
454 return result
455 })
456
457 on('turn.complete', async ($, e, next) => {
458 const result = await next(e)
459 if (e.agentId) return result
460 const shouldSwitch = budgetFailure && e.reason === 'error' && !e.isAborted
461 budgetFailure = false
462 if (shouldSwitch) await switchAfterLimit($)
463 return result
464 })
465
466 on('command.run', { command: 'account-switch' }, async ($, e) => {
467 try {
468 const text = await runCommand($, e.args)
469 if (text !== null) return { text }
470 } catch (error) {
471 return { text: `Account switch failed: ${error instanceof Error ? error.message : String(error)}` }
472 }
473 if ((await $.session.surfaces()).length === 0) return { text: formatList(accounts, current) }
474 await togglePane($)
475 return {}
476 })
477
478 // .claude.json holds one account for every session, and /status reads it, so
479 // point it at this session's account first and give Claude Code time to re-read it.
480 on('command.run', { command: 'status' }, async ($, e, next) => {
481 await pointConfigAtSession($)
482 return next(e)
483 }).catch(async ($, e, next) => next(e))
484
485 // A new login goes into a scratch directory so it never overwrites the login this
486 // session or any other is using, then becomes an account of its own.
487 on('command.run', { command: 'login' }, async ($, e, next) => {
488 const s = await refresh($)
489 const before = current
490 await s.clearPending()
491 await $.env.set('CLAUDE_SECURESTORAGE_CONFIG_DIR', s.pendingDir)
492
493 let result
494 try {
495 result = await next(e)
496 } finally {
497 const added = await s.adoptPending(await s.configAccount())
498 const target = added ?? before
499 if (target) await useAccount($, s, target)
500 else await $.env.set('CLAUDE_SECURESTORAGE_CONFIG_DIR', undefined)
501 if (added) $.ui.log(`This session now uses ${nameOf(added)}. Switch back any time with ${SWITCH_KEY_LABEL} or /account-switch.`)
502 }
503 return result
504 }).catch(async ($, e, next) => next(e))
505
506 // /logout revokes the login on Anthropic's side, which signs out every session on it.
507 on('command.run', { command: 'logout' }, async ($, e, next) => {
508 const s = await refresh($)
509 const leaving = current
510 if (!leaving) return next(e)
511
512 let answer = 'Log out'
513 try {
514 answer = await $.ui.ask(
515 `Logging out revokes ${nameOf(leaving)}'s login, so every session using it is signed out and you would have to sign in again. To use a different account in this session, use /account-switch instead. Log out anyway?`,
516 { header: 'Logout', options: ['Log out', 'Cancel'] },
517 )
518 } catch {
519 // No one to ask, as in claude -p.
520 }
521 if (answer !== 'Log out') return { text: 'Logout cancelled.' }
522
523 const result = await next(e)
524 await s.forget(leaving)
525 const home = (await s.list()).find(a => a.isHome)
526 if (home && !leaving.isHome) await useAccount($, s, home)
527 else await refresh($)
528 return result
529 }).catch(async ($, e, next) => next(e))
530
531 on('ui.focus', { requestId: PANE }, async ($, e, next) => {
532 const result = await next(e)
533 if (!result.deny && e.element && focused !== e.element) {
534 focused = e.element
535 const index = orderedAccounts({ accounts, current }).findIndex(a => useKey(a) === focused)
536 if (index >= 0) {
537 const geometry = panelGeometry(panelWidth, panelHeight, accounts.length, listOffset)
538 const top = index * geometry.rowHeight
539 if (top < listOffset) listOffset = top
540 else if (top + geometry.rowHeight > listOffset + geometry.listHeight) listOffset = Math.min(top, top + geometry.rowHeight - geometry.listHeight)
541 }
542 $.ui.invalidate('ui.render')
543 }
544 return result
545 }).catch(async ($, e, next) => next(e))
546
547 // Right and Left arrive as page scrolls (see HAT_KEYS); over an account they change its hat.
548 on('ui.scroll', { requestId: PANE }, async ($, e, next) => {
549 const account = accounts.find(a => focused === useKey(a))
550 const isPageKey = e.origin.kind === 'person' && !e.pointer && Math.abs(e.by) >= e.bodyRows
551 if (account && isPageKey) {
552 await setHat($, account, cycleHat(account.hat, e.by > 0 ? 1 : -1).id)
553 return { deny: 'changed the hat instead' }
554 }
555 if (e.origin.kind === 'person' && !e.pointer && Math.abs(e.by) === 1) {
556 const keys = [...orderedAccounts({ accounts, current }).map(useKey), 'auto-switch', 'add', 'refresh-usage']
557 const target = nextPanelFocus(keys, focused, e.by)
558 if (target && target !== focused) await $.ui.focus({ requestId: PANE, key: target })
559 return { deny: 'moved the panel selection' }
560 }
561 if (e.origin.kind !== 'person') return { deny: 'keep the panel footer fixed' }
562 const geometry = panelGeometry(panelWidth, panelHeight, accounts.length, listOffset)
563 if (!e.pointer || (e.pointer.row >= 2 && e.pointer.row < 2 + geometry.listHeight)) {
564 listOffset = panelGeometry(panelWidth, panelHeight, accounts.length, listOffset + e.by).offset
565 $.ui.invalidate('ui.render')
566 }
567 return { deny: 'scroll accounts inside the fixed panel' }
568 }).catch(async ($, e, next) => next(e))
569
570 // The account line above the prompt. Clicking it, or the shortcut, opens the sidebar.
571 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
572 if (e.props.hasSurvey) return next(e)
573 const theirs = await next(e)
574 const { Box, Button } = $.ui.resolve(e)
575 const plan = current?.plan ? ` · ${current.plan.charAt(0).toUpperCase()}${current.plan.slice(1)}` : ''
576 const line = Button({
577 key: 'account-switch',
578 label: `Account: ${nameOf(current)}${plan}`,
579 plain: true,
580 dimColor: true,
581 action: SWITCH_ACTION,
582 onPress: () => togglePane($),
583 })
584 return theirs ? Box({ flexDirection: 'column', children: [theirs, line] }) : line
585 })
586
587 on('ui.render', { component: 'Pane' }, async ($, e, next) => {
588 if (e.requestId !== PANE) return next(e)
589 panelWidth = e.props.bodyColumns
590 panelHeight = e.props.scroll.bodyRows
591 listOffset = panelGeometry(panelWidth, panelHeight, accounts.length, listOffset).offset
592 const { Box, Text, Button } = $.ui.resolve(e)
593 return panel(
594 { Box, Text, Button },
595 { accounts, current, focused, notice, autoSwitch, width: panelWidth, height: panelHeight, offset: listOffset, usage: usage?.entries ?? new Map(), now: await $.clock.now() },
596 {
597 refreshUsage: () => refreshUsage($, true),
598 toggleAutoSwitch: async () => {
599 notice = await setAutoSwitch($, !autoSwitch)
600 $.ui.invalidate('ui.render')
601 },
602 choose: account => async () => {
603 notice = await switchTo($, account.isHome ? 'home' : account.key).catch(
604 error => `Account switch failed: ${error instanceof Error ? error.message : String(error)}`,
605 )
606 if (notice.startsWith('This session')) {
607 await $.ui.close({ id: PANE })
608 $.ui.log(notice)
609 notice = ''
610 return
611 }
612 $.ui.invalidate('ui.render')
613 },
614 add: async () => {
615 await $.ui.close({ id: PANE })
616 await $.prompt.fill({ text: '/login' })
617 },
618 },
619 )
620 })
621}
622hooks/accounts.ts 585 lines1// Per-session Claude subscription accounts.
2//
3// Each saved account owns a directory, ~/.claude/accounts/<key>/, holding its own
4// .credentials.json. A session uses one by pointing CLAUDE_SECURESTORAGE_CONFIG_DIR
5// at that directory, so two sessions can run on two accounts and each token refresh
6// lands in the right file. The login in ~/.claude itself is the "home" account,
7// which sessions use by default and which `claude` outside the mod keeps using.
8
9export interface Io {
10 read(path: string): Promise<string | null>
11 /** Atomic write with a 0600 file and 0700 parent directories. */
12 writeSecret(path: string, text: string): Promise<void>
13 /** Names of the entries in a directory, or none if it is missing. */
14 list(dir: string): Promise<string[]>
15 removeTree(path: string): Promise<void>
16 /** Creates a directory, resolving false if it already exists. */
17 mkdir(path: string): Promise<boolean>
18 rmdir(path: string): Promise<void>
19 mtime(path: string): Promise<number | null>
20 sleep(ms: number): Promise<void>
21 now(): Promise<number>
22}
23
24/**
25 * Where an account's login lives. Linux and Windows keep it in `<dir>/.credentials.json`;
26 * macOS keeps it in a Keychain item whose name Claude Code derives from `dir`.
27 */
28export interface CredentialStore {
29 read(dir: string): Promise<Record<string, unknown> | null>
30 write(dir: string, creds: Record<string, unknown>): Promise<void>
31 remove(dir: string): Promise<void>
32}
33
34export class FileCredentials implements CredentialStore {
35 constructor(
36 private readonly io: Io,
37 private readonly join: Join,
38 ) {}
39
40 async read(dir: string): Promise<Record<string, unknown> | null> {
41 const path = this.join(dir, CREDENTIALS)
42 try {
43 return parseObject(await this.io.read(path), path)
44 } catch {
45 return null
46 }
47 }
48
49 async write(dir: string, creds: Record<string, unknown>): Promise<void> {
50 await this.io.writeSecret(this.join(dir, CREDENTIALS), JSON.stringify(creds, null, 2))
51 }
52
53 async remove(): Promise<void> {
54 // The file goes with its directory.
55 }
56}
57
58export type Join = (...parts: string[]) => string
59
60export const posixJoin: Join = (...parts) => parts.join('/')
61
62export interface Paths {
63 configDir: string
64 globalConfig: string
65 accountsDir: string
66 join: Join
67}
68
69export interface OauthAccount {
70 accountUuid: string
71 emailAddress?: string
72 organizationUuid?: string
73 organizationName?: string
74 [key: string]: unknown
75}
76
77export interface Account {
78 key: string
79 label?: string
80 /** Id of the hat Clawd wears beside this account. */
81 hat?: string
82 oauthAccount: OauthAccount
83 /** Directory holding this account's .credentials.json. */
84 dir: string
85 isHome: boolean
86 plan?: string
87 needsLogin: boolean
88}
89
90export type Match = { kind: 'found'; account: Account } | { kind: 'none' } | { kind: 'ambiguous'; candidates: Account[] }
91
92export const HOME_KEY = 'home'
93export const CREDENTIALS = '.credentials.json'
94const META = 'account.json'
95const PENDING = '.pending'
96
97// Keys in .credentials.json that belong to the signed-in account. The rest, such as
98// MCP server logins, are shared from the home account into the others.
99export const ACCOUNT_CREDENTIAL_KEYS = ['claudeAiOauth', 'organizationUuid', 'trustedDeviceToken', 'designOauth']
100
101// Per-account caches Claude Code drops from .claude.json when the account changes.
102export const ACCOUNT_CACHE_KEYS = [
103 'additionalModelOptionsCache',
104 'additionalModelOptionsAnsweredAt',
105 'additionalModelCostsCache',
106 'modelAccessCache',
107 'orgModelDefaultCache',
108 'cachedArtifactRoster',
109 'artifactRosterDenied',
110 'lastSeenOrgDefaultUpdatedAt',
111 'clientDataCache',
112 'clientDataCacheSlots',
113 'autoCompactWindowsCache',
114 'cachedUsageUtilization',
115 'metricsStatusCache',
116 'metricsStatusCacheByPrincipal',
117 'githubWebConnectionStatusCache',
118 'startupPrefetchedAt',
119]
120
121// Claude Code treats its own locks as stale after 15s and refreshes live ones well
122// before that. The wait stays under the 10s hook time limit.
123const LOCK_STALE_MS = 20_000
124const LOCK_RETRY_MS = 100
125const LOCK_ATTEMPTS = 50
126
127export function resolvePaths(home: string, configDirEnv: string | undefined, legacyConfigExists: boolean, join: Join = posixJoin): Paths {
128 const configDir = configDirEnv || join(home, '.claude')
129 const globalConfig = legacyConfigExists
130 ? join(configDir, '.config.json')
131 : configDirEnv
132 ? join(configDirEnv, '.claude.json')
133 : join(home, '.claude.json')
134 return { configDir, globalConfig, accountsDir: join(configDir, 'accounts'), join }
135}
136
137export function accountKey(oauth: OauthAccount): string {
138 return `${oauth.accountUuid}_${oauth.organizationUuid ?? 'personal'}`.replace(/[^A-Za-z0-9_-]/g, '-')
139}
140
141export function displayName(account: Pick<Account, 'label' | 'oauthAccount' | 'key'>): string {
142 return account.label ?? account.oauthAccount.emailAddress ?? account.key
143}
144
145export function describe(account: Account): string {
146 const parts: string[] = []
147 if (account.label && account.oauthAccount.emailAddress) parts.push(account.oauthAccount.emailAddress)
148 if (account.plan) parts.push(account.plan.charAt(0).toUpperCase() + account.plan.slice(1))
149 if (account.oauthAccount.organizationName) parts.push(account.oauthAccount.organizationName)
150 return parts.join(' · ')
151}
152
153/** Matches by 1-based position, exact name, then case-insensitive prefix of label or email. */
154export function matchAccount(accounts: Account[], query: string): Match {
155 const q = query.trim().toLowerCase()
156 if (!q) return { kind: 'none' }
157
158 const index = Number(q)
159 if (Number.isInteger(index) && index >= 1 && index <= accounts.length) {
160 return { kind: 'found', account: accounts[index - 1] }
161 }
162
163 const names = (a: Account) =>
164 [a.label, a.oauthAccount.emailAddress, a.isHome ? HOME_KEY : a.key]
165 .filter((n): n is string => !!n)
166 .map(n => n.toLowerCase())
167
168 const exact = accounts.filter(a => names(a).includes(q))
169 if (exact.length === 1) return { kind: 'found', account: exact[0] }
170
171 const prefixed = accounts.filter(a => names(a).some(n => n.startsWith(q)))
172 if (prefixed.length === 1) return { kind: 'found', account: prefixed[0] }
173 if (prefixed.length > 1) return { kind: 'ambiguous', candidates: prefixed }
174 return { kind: 'none' }
175}
176
177/**
178 * The account a session starts on: the one it used before a resume, otherwise the
179 * last account chosen in any session, provided it is still signed in.
180 */
181export function startingAccount(accounts: Account[], sessionDir: string | undefined, lastDir: string | undefined): Account | undefined {
182 if (sessionDir) return accounts.find(a => a.dir === sessionDir)
183 return accounts.find(a => a.dir === lastDir && !a.needsLogin)
184}
185
186export function applyAccountConfig(config: Record<string, unknown>, oauth: OauthAccount): Record<string, unknown> {
187 const next = { ...config }
188 const current = config.oauthAccount as OauthAccount | undefined
189 if (!current || accountKey(current) !== accountKey(oauth)) {
190 for (const key of ACCOUNT_CACHE_KEYS) delete next[key]
191 }
192 next.oauthAccount = oauth
193 return next
194}
195
196export function splitCredentials(creds: Record<string, unknown>): { account: Record<string, unknown>; shared: Record<string, unknown> } {
197 const account: Record<string, unknown> = {}
198 const shared: Record<string, unknown> = {}
199 for (const [key, value] of Object.entries(creds)) {
200 if (ACCOUNT_CREDENTIAL_KEYS.includes(key)) account[key] = value
201 else shared[key] = value
202 }
203 return { account, shared }
204}
205
206// The shortcut is a Button bound to an engine action that nothing else handles
207// while the newer /diff mod is enabled. Claude Code reads numpad minus as "-", so
208// Ctrl+Alt+Shift+numpad minus arrives as ctrl+alt+shift+- from terminals that
209// report modifiers on it (kitty protocol, xterm modifyOtherKeys, and keypad mode).
210export const SWITCH_ACTION = 'app:toggleDiffPreSession'
211export const SWITCH_KEY = 'ctrl+alt+shift+-'
212export const SWITCH_KEY_LABEL = 'Ctrl+Alt+Shift+numpad -'
213
214// A mod can't read Right and Left in its pane, so they are bound to page scrolls,
215// which the mod refuses and turns into changing the focused account's hat.
216export const HAT_KEYS: Record<string, string> = { right: 'pane:pageDown', left: 'pane:pageUp' }
217
218// What version 0.2 installed, removed on upgrade so undo gets its key back.
219const OLD_SWITCH_KEYS = ['ctrl+shift+-', 'ctrl+_']
220const OLD_UNDO_FALLBACK = 'ctrl+x ctrl+u'
221
222interface BindingBlock {
223 context: string
224 bindings: Record<string, string | null>
225}
226
227function bindingBlocks(file: Record<string, unknown>): BindingBlock[] {
228 return Array.isArray(file.bindings) ? (file.bindings as BindingBlock[]) : []
229}
230
231/** Whether the keybindings file already binds the switch key to anything. */
232export function bindsSwitchKey(file: Record<string, unknown>): boolean {
233 return bindingBlocks(file).some(b => SWITCH_KEY in (b.bindings ?? {}))
234}
235
236/** Whether the switch key is bound to the sidebar. */
237export function hasSwitchBinding(file: Record<string, unknown>): boolean {
238 return bindingBlocks(file).some(b => b.context === 'Global' && b.bindings?.[SWITCH_KEY] === SWITCH_ACTION)
239}
240
241export function hasOldBinding(file: Record<string, unknown>): boolean {
242 return bindingBlocks(file).some(b => b.context === 'Global' && OLD_SWITCH_KEYS.some(k => b.bindings?.[k] === SWITCH_ACTION))
243}
244
245/** Drops the bindings an older version of the mod installed. */
246export function withoutOldBinding(file: Record<string, unknown>): Record<string, unknown> {
247 const blocks = bindingBlocks(file)
248 .map(b => {
249 const bindings = { ...b.bindings }
250 for (const key of OLD_SWITCH_KEYS) {
251 if (b.context === 'Global' && bindings[key] === SWITCH_ACTION) delete bindings[key]
252 if (b.context === 'Chat' && bindings[key] === null) delete bindings[key]
253 }
254 if (b.context === 'Chat' && bindings[OLD_UNDO_FALLBACK] === 'chat:undo') delete bindings[OLD_UNDO_FALLBACK]
255 return { ...b, bindings }
256 })
257 .filter(b => Object.keys(b.bindings).length > 0)
258 return { ...file, bindings: blocks }
259}
260
261/** Whether Right and Left in a pane already reach the mod as hat changes. */
262export function hasHatBinding(file: Record<string, unknown>): boolean {
263 const pane = bindingBlocks(file).find(b => b.context === 'Pane')
264 return Object.entries(HAT_KEYS).every(([key, action]) => pane?.bindings?.[key] === action)
265}
266
267/** Adds the sidebar shortcut, and the hat keys unless the user bound Right or Left in panes themselves. */
268export function withSwitchBinding(file: Record<string, unknown>): Record<string, unknown> {
269 const blocks = bindingBlocks(withoutOldBinding(file)).map(b => ({ ...b, bindings: { ...b.bindings } }))
270 const block = (context: string) => {
271 let found = blocks.find(b => b.context === context)
272 if (!found) {
273 found = { context, bindings: {} }
274 blocks.push(found)
275 }
276 return found
277 }
278 block('Global').bindings[SWITCH_KEY] = SWITCH_ACTION
279 const pane = block('Pane')
280 for (const [key, action] of Object.entries(HAT_KEYS)) {
281 if (!(key in pane.bindings)) pane.bindings[key] = action
282 }
283 return { ...file, bindings: blocks }
284}
285
286export function withoutSwitchBinding(file: Record<string, unknown>): Record<string, unknown> {
287 const blocks = bindingBlocks(withoutOldBinding(file))
288 .map(b => {
289 const bindings = { ...b.bindings }
290 if (b.context === 'Global' && bindings[SWITCH_KEY] === SWITCH_ACTION) delete bindings[SWITCH_KEY]
291 if (b.context === 'Pane') {
292 for (const [key, action] of Object.entries(HAT_KEYS)) if (bindings[key] === action) delete bindings[key]
293 }
294 return { ...b, bindings }
295 })
296 .filter(b => Object.keys(b.bindings).length > 0)
297 return { ...file, bindings: blocks }
298}
299
300interface Tokens {
301 refreshToken?: string
302 subscriptionType?: string
303 refreshTokenExpiresAt?: number
304}
305
306function tokensOf(creds: Record<string, unknown> | null): Tokens | undefined {
307 const value = creds?.claudeAiOauth
308 if (value === null || typeof value !== 'object') return undefined
309 return value as Tokens
310}
311
312export function parseObject(text: string | null, path: string): Record<string, unknown> | null {
313 if (text === null || text.trim() === '') return null
314 const value: unknown = JSON.parse(text)
315 if (value === null || typeof value !== 'object' || Array.isArray(value)) {
316 throw new Error(`${path} does not hold a JSON object`)
317 }
318 return value as Record<string, unknown>
319}
320
321function sameJson(a: unknown, b: unknown): boolean {
322 return JSON.stringify(a) === JSON.stringify(b)
323}
324
325interface Meta {
326 oauthAccount: OauthAccount
327 label?: string
328 hat?: string
329}
330
331function metaOf(value: Record<string, unknown> | null): Meta | undefined {
332 const oauth = value?.oauthAccount as OauthAccount | undefined
333 if (!oauth?.accountUuid) return undefined
334 return {
335 oauthAccount: oauth,
336 ...(typeof value?.label === 'string' ? { label: value.label } : {}),
337 ...(typeof value?.hat === 'string' ? { hat: value.hat } : {}),
338 }
339}
340
341export class AccountStore {
342 constructor(
343 private readonly io: Io,
344 private readonly paths: Paths,
345 private readonly creds: CredentialStore,
346 ) {}
347
348 get pendingDir(): string {
349 return this.join(this.paths.accountsDir, PENDING)
350 }
351
352 private get join(): Join {
353 return this.paths.join
354 }
355
356 private get homeMetaPath(): string {
357 return this.join(this.paths.accountsDir, 'home.json')
358 }
359
360 private dirFor(key: string): string {
361 return this.join(this.paths.accountsDir, key)
362 }
363
364 get configDir(): string {
365 return this.paths.configDir
366 }
367
368 async usageToken(account: Account, now: number): Promise<string | undefined> {
369 const credentials = await this.creds.read(account.dir)
370 const oauth = credentials?.claudeAiOauth as { accessToken?: unknown; expiresAt?: unknown } | undefined
371 if (typeof oauth?.expiresAt === 'number' && oauth.expiresAt <= now) return undefined
372 return typeof oauth?.accessToken === 'string' && oauth.accessToken ? oauth.accessToken : undefined
373 }
374
375 /** Every account with a login: the home account first, then saved ones by name. */
376 async list(): Promise<Account[]> {
377 const now = await this.io.now()
378 const accounts: Account[] = []
379
380 const home = await this.homeAccount(now)
381 if (home) accounts.push(home)
382
383 const saved: Account[] = []
384 for (const name of await this.io.list(this.paths.accountsDir)) {
385 if (name.startsWith('.') || name.endsWith('.json')) continue
386 const dir = this.dirFor(name)
387 const metaPath = this.join(dir, META)
388 try {
389 const meta = metaOf(parseObject(await this.io.read(metaPath), metaPath))
390 if (meta) saved.push(await this.hydrate({ key: name, ...meta }, dir, false, now))
391 } catch {
392 // A corrupt entry should not hide the others.
393 }
394 }
395 saved.sort((a, b) => displayName(a).localeCompare(displayName(b)))
396 return [...accounts, ...saved]
397 }
398
399 /** The account a session uses, from its CLAUDE_SECURESTORAGE_CONFIG_DIR. */
400 async forSession(storageDir: string | undefined): Promise<Account | undefined> {
401 const dir = storageDir || this.paths.configDir
402 return (await this.list()).find(a => a.dir === dir)
403 }
404
405 /**
406 * Records who the home account is the first time the mod runs. Afterwards
407 * .claude.json follows whichever session switched last, so it can't be trusted.
408 */
409 async learnHome(): Promise<void> {
410 if (await this.homeMeta()) return
411 const creds = await this.creds.read(this.paths.configDir)
412 if (!tokensOf(creds)?.refreshToken) return
413 const oauth = await this.configAccount()
414 if (oauth) await this.rememberHome(oauth)
415 }
416
417 /**
418 * Files the login that `/login` just wrote into the pending directory. It replaces
419 * the home login when there is none or it is the same account, and otherwise
420 * becomes a saved account of its own. Returns the account, or undefined if the
421 * login did not finish.
422 */
423 async adoptPending(oauth: OauthAccount | undefined): Promise<Account | undefined> {
424 const pending = await this.creds.read(this.pendingDir)
425 if (!oauth || !pending || !tokensOf(pending)?.refreshToken) {
426 await this.clearPending()
427 return undefined
428 }
429
430 const key = accountKey(oauth)
431 const home = await this.homeMeta()
432 const homeCreds = await this.creds.read(this.paths.configDir)
433 const intoHome = !tokensOf(homeCreds)?.refreshToken || (home && accountKey(home.oauthAccount) === key)
434
435 if (intoHome) {
436 await this.withLock(this.join(this.paths.configDir, '.storage-write'), async () => {
437 const live = (await this.creds.read(this.paths.configDir)) ?? {}
438 await this.creds.write(this.paths.configDir, { ...splitCredentials(live).shared, ...splitCredentials(pending).account })
439 })
440 await this.rememberHome(oauth)
441 } else {
442 const dir = this.dirFor(key)
443 const metaPath = this.join(dir, META)
444 const existing = metaOf(parseObject(await this.io.read(metaPath), metaPath))
445 await this.creds.write(dir, { ...splitCredentials(homeCreds ?? {}).shared, ...splitCredentials(pending).account })
446 await this.writeMeta(dir, { ...existing, oauthAccount: oauth })
447 }
448
449 await this.clearPending()
450 const target = intoHome ? this.paths.configDir : this.dirFor(key)
451 return (await this.list()).find(a => a.dir === target)
452 }
453
454 async clearPending(): Promise<void> {
455 await this.creds.remove(this.pendingDir)
456 await this.io.removeTree(this.pendingDir)
457 }
458
459 /** Copies MCP logins and other shared entries from the home account where the account has none. */
460 async shareFromHome(account: Account): Promise<void> {
461 if (account.isHome) return
462 const { shared } = splitCredentials((await this.creds.read(this.paths.configDir)) ?? {})
463 await this.withLock(this.join(account.dir, '.storage-write'), async () => {
464 const creds = (await this.creds.read(account.dir)) ?? {}
465 const missing = Object.fromEntries(Object.entries(shared).filter(([k]) => !(k in creds)))
466 if (Object.keys(missing).length === 0) return
467 await this.creds.write(account.dir, { ...creds, ...missing })
468 })
469 }
470
471 async rename(account: Account, label: string): Promise<void> {
472 const trimmed = label.trim()
473 await this.updateMeta(account, meta => {
474 const { label: _old, ...rest } = meta
475 return trimmed ? { ...rest, label: trimmed } : rest
476 })
477 }
478
479 async setHat(account: Account, hat: string): Promise<void> {
480 await this.updateMeta(account, meta => ({ ...meta, hat }))
481 }
482
483 async forget(account: Account): Promise<void> {
484 if (account.isHome) {
485 await this.io.removeTree(this.homeMetaPath)
486 return
487 }
488 await this.creds.remove(account.dir)
489 await this.io.removeTree(account.dir)
490 }
491
492 /**
493 * Points .claude.json's account details at `oauth`. /status reads them, and the
494 * file is shared by every session, so each session points it at its own account
495 * when it needs them right. With `touch`, the file is rewritten even when it
496 * already matches, because a running session only re-reads it when its mtime is
497 * newer than the copy it holds. Resolves true if it wrote.
498 */
499 async pointConfigAt(oauth: OauthAccount, touch = false): Promise<boolean> {
500 return this.withLock(this.paths.globalConfig, async () => {
501 const config = parseObject(await this.io.read(this.paths.globalConfig), this.paths.globalConfig) ?? {}
502 const next = applyAccountConfig(config, oauth)
503 if (!touch && sameJson(config, next)) return false
504 await this.io.writeSecret(this.paths.globalConfig, JSON.stringify(next, null, 2))
505 return true
506 })
507 }
508
509 async configAccount(): Promise<OauthAccount | undefined> {
510 const config = parseObject(await this.io.read(this.paths.globalConfig), this.paths.globalConfig)
511 const oauth = config?.oauthAccount as OauthAccount | undefined
512 return oauth?.accountUuid ? oauth : undefined
513 }
514
515 async configValue(key: string): Promise<unknown> {
516 return parseObject(await this.io.read(this.paths.globalConfig), this.paths.globalConfig)?.[key]
517 }
518
519 private async rememberHome(oauth: OauthAccount): Promise<void> {
520 const home = await this.homeMeta()
521 const same = home && accountKey(home.oauthAccount) === accountKey(oauth)
522 await this.writeMeta(null, same ? { ...home, oauthAccount: oauth } : { oauthAccount: oauth })
523 }
524
525 private async updateMeta(account: Account, change: (meta: Meta) => Meta): Promise<void> {
526 if (account.isHome) {
527 const home = await this.homeMeta()
528 if (home) await this.writeMeta(null, change(home))
529 return
530 }
531 const path = this.join(account.dir, META)
532 const meta = metaOf(parseObject(await this.io.read(path), path)) ?? { oauthAccount: account.oauthAccount }
533 await this.writeMeta(account.dir, change(meta))
534 }
535
536 /** Writes a saved account's metadata, or the home account's when `dir` is null. */
537 private async writeMeta(dir: string | null, meta: Meta): Promise<void> {
538 const path = dir === null ? this.homeMetaPath : this.join(dir, META)
539 await this.io.writeSecret(path, JSON.stringify(meta, null, 2))
540 }
541
542 private async homeMeta(): Promise<Meta | undefined> {
543 return metaOf(parseObject(await this.io.read(this.homeMetaPath), this.homeMetaPath))
544 }
545
546 private async homeAccount(now: number): Promise<Account | undefined> {
547 const home = await this.homeMeta()
548 if (!home) return undefined
549 const account = await this.hydrate({ key: HOME_KEY, ...home }, this.paths.configDir, true, now)
550 return account.needsLogin && !account.plan ? undefined : account
551 }
552
553 private async hydrate(meta: Meta & { key: string }, dir: string, isHome: boolean, now: number): Promise<Account> {
554 const tokens = tokensOf(await this.creds.read(dir))
555 const expired = typeof tokens?.refreshTokenExpiresAt === 'number' && tokens.refreshTokenExpiresAt < now
556 return {
557 ...meta,
558 dir,
559 isHome,
560 ...(tokens?.subscriptionType ? { plan: tokens.subscriptionType } : {}),
561 needsLogin: !tokens?.refreshToken || expired,
562 }
563 }
564
565 private async withLock<T>(target: string, work: () => Promise<T>): Promise<T> {
566 const lockDir = `${target}.lock`
567 for (let attempt = 0; attempt < LOCK_ATTEMPTS; attempt++) {
568 if (await this.io.mkdir(lockDir)) {
569 try {
570 return await work()
571 } finally {
572 await this.io.rmdir(lockDir)
573 }
574 }
575 const mtime = await this.io.mtime(lockDir)
576 if (mtime !== null && (await this.io.now()) - mtime > LOCK_STALE_MS) {
577 await this.io.rmdir(lockDir)
578 continue
579 }
580 await this.io.sleep(LOCK_RETRY_MS)
581 }
582 throw new Error(`timed out waiting for ${lockDir}`)
583 }
584}
585hooks/clawd.ts 81 lines1// Clawd, the Claude Code mascot as its welcome banner draws him, with a hat row
2// on top. Every row is nine cells wide. A hat can also swap his face row, which
3// is how sunglasses sit over his eyes.
4
5export interface Segment {
6 text: string
7 colour: string
8 background?: string
9}
10
11export interface Hat {
12 id: string
13 name: string
14 /** The row above Clawd's head. */
15 top: Segment[]
16 /** Replaces Clawd's face row when set. */
17 face?: Segment[]
18}
19
20export const CLAWD_COLOUR = 'rgb(215,119,87)'
21export const CLAWD_ROWS = [' ▐▛███▜▌ ', '▝▜█████▛▘', ' ▘▘ ▝▝ ']
22
23const BLANK: Segment[] = [{ text: ' ', colour: 'text' }]
24const solid = (text: string, colour: string): Segment[] => [{ text, colour }]
25const SHADES = 'rgb(30,30,36)'
26
27export const HATS: Hat[] = [
28 { id: 'none', name: 'No hat', top: BLANK },
29 { id: 'top', name: 'Top hat', top: solid(' ▗███▖ ', 'rgb(90,90,100)') },
30 {
31 // A cone in pink, blue and yellow stripes.
32 id: 'party',
33 name: 'Party hat',
34 top: [
35 { text: ' ', colour: 'text' },
36 { text: '▗', colour: 'rgb(232,121,249)' },
37 { text: '▟', colour: 'rgb(96,165,250)' },
38 { text: '█', colour: 'rgb(250,204,21)' },
39 { text: '▙', colour: 'rgb(232,121,249)' },
40 { text: '▖', colour: 'rgb(96,165,250)' },
41 { text: ' ', colour: 'text' },
42 ],
43 },
44 { id: 'crown', name: 'Crown', top: solid(' ▙▟▙▟▙ ', 'rgb(250,204,21)') },
45 { id: 'beanie', name: 'Beanie', top: solid(' ▗▟█▙▖ ', 'rgb(96,165,250)') },
46 { id: 'cap', name: 'Cap', top: solid(' ▗███▄▄ ', 'rgb(239,68,68)') },
47 { id: 'wizard', name: 'Wizard hat', top: solid(' ▗█▖ ', 'rgb(139,92,246)') },
48 { id: 'chef', name: 'Chef hat', top: solid(' ▟███▙ ', 'rgb(245,245,245)') },
49 { id: 'cowboy', name: 'Cowboy hat', top: solid(' ▄▄▟█▙▄▄ ', 'rgb(180,83,9)') },
50 { id: 'halo', name: 'Halo', top: solid(' ▁▁▁▁▁ ', 'rgb(253,224,71)') },
51 { id: 'bow', name: 'Bow', top: solid(' ▚▄▞ ', 'rgb(244,114,182)') },
52 { id: 'headphones', name: 'Headphones', top: solid(' ▗▛▀▀▀▜▖ ', 'rgb(34,197,94)') },
53 {
54 id: 'sunglasses',
55 name: 'Sunglasses',
56 top: BLANK,
57 // Dark lenses over the lower half of his face row, where his eyes are, with
58 // his face showing above them and a bridge between.
59 face: [
60 { text: ' ▐', colour: CLAWD_COLOUR },
61 { text: '▄▄▄▄▄', colour: SHADES, background: CLAWD_COLOUR },
62 { text: '▌ ', colour: CLAWD_COLOUR },
63 ],
64 },
65]
66
67export function hatById(id: string | undefined): Hat {
68 return HATS.find(h => h.id === id) ?? HATS[0]
69}
70
71/** The hat `step` places along from `id`, wrapping at either end. */
72export function cycleHat(id: string | undefined, step: number): Hat {
73 const index = HATS.indexOf(hatById(id))
74 return HATS[(((index + step) % HATS.length) + HATS.length) % HATS.length]
75}
76
77/** Clawd's four rows wearing `hat`, each as coloured segments. */
78export function clawdRows(hat: Hat): Segment[][] {
79 return [hat.top, hat.face ?? solid(CLAWD_ROWS[0], CLAWD_COLOUR), solid(CLAWD_ROWS[1], CLAWD_COLOUR), solid(CLAWD_ROWS[2], CLAWD_COLOUR)]
80}
81hooks/keychain.ts 71 lines1import type { CredentialStore } from './accounts.ts'
2
3/**
4 * Picks the store Claude Code is using: the credentials file when one exists, as
5 * on Linux and Windows and on recent macOS builds, else the macOS Keychain.
6 */
7export async function detectStore(
8 files: CredentialStore,
9 keychain: CredentialStore | undefined,
10 defaultDir: string,
11): Promise<CredentialStore> {
12 if (!keychain || (await files.read(defaultDir))) return files
13 return (await keychain.read(defaultDir)) ? keychain : files
14}
15
16/** Runs `security` and returns its exit code and output. */
17export type Security = (args: string[], stdin?: string) => Promise<{ exitCode: number; stdout: string }>
18
19const SERVICE = 'Claude Code-credentials'
20const NOT_FOUND = 44
21
22async function sha256Hex(text: string): Promise<string> {
23 const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(text))
24 return [...new Uint8Array(digest)].map(b => b.toString(16).padStart(2, '0')).join('')
25}
26
27/**
28 * The Keychain item Claude Code reads for a credential directory: the plain
29 * service name for the default directory, and otherwise the name followed by the
30 * first eight hex digits of the directory's SHA-256.
31 */
32export async function serviceFor(dir: string, defaultDir: string): Promise<string> {
33 if (dir === defaultDir) return SERVICE
34 return `${SERVICE}-${(await sha256Hex(dir.normalize('NFC'))).slice(0, 8)}`
35}
36
37/** macOS: each account's login is a generic password in the login Keychain. */
38export class KeychainCredentials implements CredentialStore {
39 constructor(
40 private readonly security: Security,
41 private readonly user: string,
42 private readonly defaultDir: string,
43 ) {}
44
45 async read(dir: string): Promise<Record<string, unknown> | null> {
46 const service = await serviceFor(dir, this.defaultDir)
47 const r = await this.security(['find-generic-password', '-a', this.user, '-w', '-s', service])
48 if (r.exitCode === NOT_FOUND || r.exitCode !== 0) return null
49 try {
50 const value: unknown = JSON.parse(r.stdout.trim())
51 return value && typeof value === 'object' && !Array.isArray(value) ? (value as Record<string, unknown>) : null
52 } catch {
53 return null
54 }
55 }
56
57 async write(dir: string, creds: Record<string, unknown>): Promise<void> {
58 const service = await serviceFor(dir, this.defaultDir)
59 const hex = [...new TextEncoder().encode(JSON.stringify(creds))].map(b => b.toString(16).padStart(2, '0')).join('')
60 // Passing the secret on stdin through `security -i` keeps it out of the process list.
61 const line = `add-generic-password -U -a "${this.user}" -s "${service}" -X "${hex}"\n`
62 const r = await this.security(['-i'], line)
63 if (r.exitCode !== 0) throw new Error(`could not save the login to the Keychain (security exited ${r.exitCode})`)
64 }
65
66 async remove(dir: string): Promise<void> {
67 const service = await serviceFor(dir, this.defaultDir)
68 await this.security(['delete-generic-password', '-a', this.user, '-s', service])
69 }
70}
71hooks/panel.ts 151 lines1import type { Elements, RenderElement } from 'claude-code'
2import { type Account, displayName } from './accounts.ts'
3import { clawdRows, hatById, type Segment } from './clawd.ts'
4import { type UsageEntry, USAGE_STALE_MS, remaining, resetLabel, usageStatus } from './usage.ts'
5
6export type PanelElements = Pick<Elements['terminal'], 'Box' | 'Text' | 'Button'>
7
8export interface PanelState {
9 accounts: Account[]
10 current: Account | undefined
11 focused: string
12 notice: string
13 autoSwitch: boolean
14 width: number
15 height: number
16 offset: number
17 usage: ReadonlyMap<string, UsageEntry>
18 now: number
19}
20
21export interface PanelActions {
22 choose(account: Account): () => Promise<void>
23 add(): Promise<void>
24 toggleAutoSwitch(): Promise<void>
25 refreshUsage(): Promise<void>
26}
27
28export const useKey = (account: Account) => `use-${account.key}`
29
30export function nextPanelFocus(keys: string[], focused: string, direction: number): string | undefined {
31 return keys[Math.max(0, Math.min(keys.length - 1, keys.indexOf(focused) + Math.sign(direction)))]
32}
33
34export function panelGeometry(width: number, height: number, count: number, offset: number) {
35 const rowHeight = width < 44 ? 12 : 10
36 const footerHeight = Math.min(8, Math.max(4, height - 5))
37 const listHeight = Math.max(1, height - footerHeight - 2)
38 const maxOffset = Math.max(0, count * rowHeight - (count ? 1 : 0) - listHeight)
39 return { rowHeight, footerHeight, listHeight, maxOffset, offset: Math.max(0, Math.min(offset, maxOffset)) }
40}
41
42export function orderedAccounts(state: Pick<PanelState, 'accounts' | 'current'>): Account[] {
43 return [...(state.current ? [state.current] : []), ...state.accounts.filter(a => a.dir !== state.current?.dir)]
44}
45
46function segmentLine({ Box, Text }: PanelElements, segments: Segment[]): RenderElement {
47 return Box({ flexDirection: 'row', children: segments.map(s => Text({ color: s.colour, ...(s.background ? { backgroundColor: s.background } : {}), children: [s.text] })) })
48}
49
50function usageRows({ Box, Text }: PanelElements, entry: UsageEntry | undefined, state: PanelState, header: boolean): RenderElement[] {
51 const text = (value: string, colour?: string) => Text({ ...(colour ? { color: colour } : { dimColor: true }), wrap: 'wrap', children: [value] })
52 if (!entry || entry.status === 'loading') return [text('Reading usage…')]
53 if (entry.status === 'sign-in') return [text('Sign in again with /login', 'warning')]
54 if (entry.status === 'refresh-login') return [text('Usage unavailable · switch to refresh login')]
55 if (entry.status === 'limited') return [text('Usage refresh rate-limited · try later')]
56 if (entry.status !== 'ready') return [text('Usage unavailable · r to retry')]
57
58 const narrow = state.width < 44
59 const stale = entry.checkedAt === undefined || state.now - entry.checkedAt >= USAGE_STALE_MS
60 const rows: RenderElement[] = header ? [text(narrow ? 'WINDOW LEFT / RESETS' : 'WINDOW LEFT RESETS')] : []
61 for (const label of ['5h', 'Week']) {
62 const window = entry.windows.find(w => w.label === label)
63 const resetPassed = window?.resetsAt && Date.parse(window.resetsAt) <= state.now
64 const left = window && !stale && !resetPassed ? remaining(window) : undefined
65 const fraction = left === 0 && window !== undefined && window.used < 100
66 const colour = left === undefined ? 'subtle' : left === 0 && !fraction ? 'error' : left < 30 ? 'warning' : 'success'
67 const blocks = left === undefined ? '····' : '▰'.repeat(Math.floor(left / 25)) + '▱'.repeat(4 - Math.floor(left / 25))
68 const percent = left === undefined ? ' --%' : fraction ? ' <1%' : `${left}%`.padStart(4)
69 const reset = resetPassed ? 'Reset passed · r to refresh' : resetLabel(window?.resetsAt)
70 const values = Box({ flexDirection: 'row', children: [text(label.padEnd(8), 'text'), text(`${percent} ${blocks} `, colour)] })
71 rows.push(narrow
72 ? Box({ flexDirection: 'column', children: [values, text(`↻ ${reset}`)] })
73 : Box({ flexDirection: 'row', children: [values, text(`↻ ${reset}`)] }))
74 }
75 return rows
76}
77
78/** Out of credits tints red, even on the active row, whose label still says it is active. */
79export function rowBackground(active: boolean, focused: boolean, exhausted: boolean): string | undefined {
80 if (exhausted) return focused ? 'rgb(74,40,43)' : 'rgb(52,30,33)'
81 if (active) return focused ? 'rgb(40,65,49)' : 'rgb(31,48,38)'
82 return focused ? 'rgb(53,53,57)' : undefined
83}
84
85function accountRow(el: PanelElements, state: PanelState, actions: PanelActions, account: Account, first: boolean): RenderElement {
86 const { Box, Text, Button } = el
87 const active = account.dir === state.current?.dir
88 const focused = state.focused === useKey(account)
89 const entry = account.needsLogin ? { status: 'sign-in' as const, windows: [] } : state.usage.get(account.dir)
90 const status = usageStatus(entry, state.now)
91 const backgroundColor = rowBackground(active, focused, status.exhausted === true)
92 const plan = account.plan ? account.plan.charAt(0).toUpperCase() + account.plan.slice(1) : ''
93 return Box({ key: `row-${account.key}`, height: panelGeometry(state.width, state.height, state.accounts.length, 0).rowHeight - 1, backgroundColor, paddingX: 1, paddingY: 1, flexDirection: 'column', children: [
94 Box({ flexDirection: 'column', flexGrow: 1, flexShrink: 1, children: [
95 Box({ flexDirection: 'row', justifyContent: 'space-between', alignItems: 'flex-start', height: 4, children: [
96 Box({ flexDirection: 'column', flexShrink: 1, children: [
97 Box({ flexDirection: state.width < 44 ? 'column' : 'row', columnGap: 1, children: [
98 Box({ flexShrink: 1, children: [Button({ key: useKey(account), plain: true, ...(first ? { autoFocus: true as const } : {}), onPress: actions.choose(account), children: [Text({ bold: true, color: 'text', wrap: 'truncate-end', children: [` ${displayName(account)} `] })] })] }),
99 Text({ color: active ? 'success' : status.colour, children: [active ? '● active' : status.label] }),
100 ] }),
101 Box({ paddingLeft: 1, children: [Text({ dimColor: true, wrap: 'truncate-end', children: [[account.oauthAccount.emailAddress, plan].filter(Boolean).join(' · ')] })] }),
102 ] }),
103 ...(state.width >= 36 ? [Box({ flexDirection: 'column', flexShrink: 0, width: 9, height: 4, children: clawdRows(hatById(account.hat)).map(row => segmentLine(el, row)) })] : []),
104 ] }),
105 Box({ paddingLeft: 1, flexDirection: 'column', children: usageRows(el, entry, state, true) }),
106 ] }),
107 ] })
108}
109
110export function panel(el: PanelElements, state: PanelState, actions: PanelActions): RenderElement {
111 const { Box, Text, Button } = el
112 const accounts = orderedAccounts(state)
113 const focused = state.accounts.find(a => state.focused === useKey(a))
114 const geometry = panelGeometry(state.width, state.height, accounts.length, state.offset)
115 const line = '─'.repeat(Math.max(1, state.width - (state.width < 36 ? 2 : 4)))
116 const hint = (value: string) => Text({ dimColor: true, wrap: 'truncate-end', children: [value] })
117 // One spare row keeps native scroll keys active; the hook scrolls only the list.
118 return Box({ flexDirection: 'column', width: state.width, height: state.height + 1, paddingX: state.width < 36 ? 1 : 2, overflow: 'hidden', children: [
119 Box({ height: 2, flexShrink: 0, justifyContent: 'space-between', children: [
120 Text({ bold: true, children: ['Accounts'] }),
121 hint(geometry.maxOffset ? `${geometry.offset > 0 ? '↑' : ' '} ${geometry.offset < geometry.maxOffset ? '↓' : ' '}` : ''),
122 ] }),
123 Box({ key: 'account-list', height: geometry.listHeight, flexShrink: 0, overflow: 'hidden', children: [
124 Box({ position: 'absolute', top: -geometry.offset, left: 0, right: 0, flexDirection: 'column', children: accounts.length ? accounts.map((account, index) =>
125 Box({ height: geometry.rowHeight, flexShrink: 0, flexDirection: 'column', overflow: 'hidden', children: [
126 accountRow(el, state, actions, account, index === 0),
127 Box({ position: 'absolute', bottom: 0, left: 0, right: 0, children: [hint(line)] }),
128 ] })) : [hint('No saved accounts.')] }),
129 ] }),
130 Box({ key: 'account-footer', height: geometry.footerHeight, flexShrink: 0, flexDirection: 'column', overflow: 'hidden', children: [
131 hint(line),
132 Button({ key: 'auto-switch', plain: true, hotkey: 's', label: `Auto-switch: ${state.autoSwitch ? 'on' : 'off'}`, onPress: actions.toggleAutoSwitch }),
133 Box({ flexDirection: state.width < 40 ? 'column' : 'row', columnGap: 2, children: [
134 Button({ key: 'add', plain: true, hotkey: 'a', label: '+ Add account', onPress: actions.add }),
135 Button({ key: 'refresh-usage', plain: true, hotkey: 'r', label: 'Refresh usage', onPress: actions.refreshUsage }),
136 ] }),
137 hint('15s refresh · local reset times'),
138 ...(geometry.footerHeight >= 7 ? [hint(focused ? `${hatById(focused.hat).name} · ←→ to change hat` : '←→ change account hat')] : []),
139 ...(geometry.footerHeight >= 8 && state.width >= 40 ? [state.notice
140 ? Text({ color: 'warning', wrap: 'truncate-end', children: [state.notice] })
141 : hint('Auto-switch tries each signed-in account.')] : []),
142 ...(geometry.footerHeight >= 6 ? [hint('↑↓ / tab move · enter select')] : []),
143 ...(geometry.footerHeight >= 5 ? [hint('esc close')] : []),
144 ] }),
145 ] })
146}
147
148export function panelRows(state: Pick<PanelState, 'accounts' | 'current'>): number {
149 return 16 + state.accounts.length * 10
150}
151hooks/platform.ts 85 lines1// The shell commands behind each file operation, per platform. Linux and macOS use
2// POSIX tools; Windows uses PowerShell, which every supported Windows ships.
3
4export type Platform = 'posix' | 'windows'
5
6export interface Commands {
7 /** Writes stdin to the path atomically, owner-only, creating parent directories. */
8 writeSecret(path: string): string[]
9 removeTree(path: string): string[]
10 /** Exits 0 only if it created the directory. */
11 mkdir(path: string): string[]
12 rmdir(path: string): string[]
13 read(path: string): string[]
14}
15
16// Writes go through a temp file and rename so readers never see half a file,
17// and through readlink so a symlinked ~/.claude.json keeps its link.
18const POSIX_WRITE = [
19 'set -e',
20 'umask 077',
21 't=$1',
22 'if [ -L "$t" ]; then t=$(readlink -f -- "$t"); fi',
23 'mkdir -p -- "$(dirname -- "$t")"',
24 'tmp="$t.tmp.$$"',
25 'cat > "$tmp"',
26 'mv -f -- "$tmp" "$t"',
27].join('\n')
28
29// The path arrives as an argument, never inside the script, so no quoting is needed.
30// The file inherits the user profile's ACL, which only that user and SYSTEM can read.
31const WINDOWS_WRITE = [
32 '$t = $args[0]',
33 '$item = Get-Item -LiteralPath $t -ErrorAction SilentlyContinue',
34 'if ($item -and $item.LinkType) { $t = $item.Target }',
35 '$dir = Split-Path -Parent $t',
36 'New-Item -ItemType Directory -Force -Path $dir | Out-Null',
37 '$tmp = "$t.tmp.$PID"',
38 '$text = [Console]::In.ReadToEnd()',
39 '[IO.File]::WriteAllText($tmp, $text, (New-Object Text.UTF8Encoding $false))',
40 'Move-Item -LiteralPath $tmp -Destination $t -Force',
41].join('; ')
42
43const POWERSHELL = ['powershell', '-NoProfile', '-NonInteractive', '-Command']
44
45const posix: Commands = {
46 writeSecret: path => ['sh', '-c', POSIX_WRITE, 'sh', path],
47 removeTree: path => ['rm', '-rf', '--', path],
48 mkdir: path => ['mkdir', '--', path],
49 rmdir: path => ['rmdir', '--', path],
50 read: path => ['cat', '--', path],
51}
52
53const windows: Commands = {
54 writeSecret: path => [...POWERSHELL, WINDOWS_WRITE, path],
55 removeTree: path => [...POWERSHELL, 'Remove-Item -LiteralPath $args[0] -Recurse -Force -ErrorAction SilentlyContinue', path],
56 // New-Item fails when the directory exists, which is what the lock relies on.
57 mkdir: path => [...POWERSHELL, 'New-Item -ItemType Directory -Path $args[0] -ErrorAction Stop | Out-Null', path],
58 rmdir: path => [...POWERSHELL, 'Remove-Item -LiteralPath $args[0] -Force -ErrorAction SilentlyContinue', path],
59 read: path => [...POWERSHELL, 'Get-Content -LiteralPath $args[0] -Raw -Encoding UTF8', path],
60}
61
62export function commandsFor(platform: Platform): Commands {
63 return platform === 'windows' ? windows : posix
64}
65
66/** Windows always sets APPDATA and USERPROFILE; Linux and macOS set neither. */
67export function detectPlatform(env: { appData?: string; userProfile?: string }): Platform {
68 return env.appData && env.userProfile ? 'windows' : 'posix'
69}
70
71/**
72 * The home directory Claude Code itself uses: USERPROFILE on Windows, HOME
73 * elsewhere. Kept in its native spelling, since Claude Code names a credential
74 * directory's Keychain item and lock files after the exact string.
75 */
76export function homeDir(platform: Platform, env: { home?: string; userProfile?: string }): string {
77 return (platform === 'windows' ? env.userProfile || env.home : env.home) ?? ''
78}
79
80/** Joins path parts with the platform's separator. */
81export function joiner(platform: Platform): (...parts: string[]) => string {
82 const sep = platform === 'windows' ? '\\' : '/'
83 return (...parts) => parts.map((p, i) => (i === 0 ? p.replace(/[\\/]+$/, '') : p.replace(/^[\\/]+|[\\/]+$/g, ''))).join(sep)
84}
85hooks/usage.ts 130 lines1import type { EngineInterface } from 'claude-code'
2import type { Account } from './accounts.ts'
3
4export interface UsageWindow {
5 label: string
6 used: number
7 resetsAt?: string
8}
9
10export interface UsageEntry {
11 status: 'loading' | 'ready' | 'unavailable' | 'sign-in' | 'refresh-login' | 'limited'
12 windows: UsageWindow[]
13 checkedAt?: number
14 retryAt?: number
15}
16
17export interface UsageApi {
18 fetch(accessToken: string): Promise<{ status: number; body: string; retryAfter?: string }>
19}
20
21export class HttpUsageApi implements UsageApi {
22 constructor(private readonly fetchHttp: EngineInterface['http']['fetch'], private readonly baseUrl = 'https://api.anthropic.com') {}
23
24 async fetch(accessToken: string) {
25 const response = await this.fetchHttp(`${this.baseUrl.replace(/\/$/, '')}/api/oauth/usage`, {
26 headers: { Authorization: `Bearer ${accessToken}`, 'anthropic-beta': 'oauth-2025-04-20', Accept: 'application/json' },
27 })
28 return { status: response.status, body: response.text, retryAfter: response.headers['retry-after'] }
29 }
30}
31
32export const USAGE_REFRESH_MS = 15_000
33// Leaves room for the next poll to land before a shown reading counts as stale.
34export const USAGE_STALE_MS = 2 * USAGE_REFRESH_MS
35
36export function parseUsage(body: string): UsageWindow[] {
37 const data: unknown = JSON.parse(body)
38 if (!data || typeof data !== 'object' || Array.isArray(data)) throw new Error('Invalid usage response')
39 const windows: UsageWindow[] = []
40 for (const [key, label] of [['five_hour', '5h'], ['seven_day', 'Week']]) {
41 const raw = (data as Record<string, unknown>)[key as string]
42 if (raw === undefined || raw === null) continue
43 if (typeof raw !== 'object') throw new Error('Invalid usage window')
44 const { utilization, resets_at } = raw as { utilization?: unknown; resets_at?: unknown }
45 if (typeof utilization !== 'number' || !Number.isFinite(utilization) || utilization < 0) throw new Error('Invalid usage percentage')
46 const resetsAt = typeof resets_at === 'string' && Number.isFinite(Date.parse(resets_at)) ? resets_at : undefined
47 windows.push({ label: label as string, used: utilization, ...(resetsAt ? { resetsAt } : {}) })
48 }
49 return windows
50}
51
52export class UsageCache {
53 readonly entries = new Map<string, UsageEntry>()
54 private readonly pending = new Map<string, Promise<void>>()
55
56 constructor(private readonly api: UsageApi, private readonly now: () => Promise<number>) {}
57
58 async refresh(account: Account, token: () => Promise<string | undefined>, force = false): Promise<void> {
59 const pending = this.pending.get(account.dir)
60 if (pending) return pending
61 const work = this.load(account, token, force)
62 this.pending.set(account.dir, work)
63 try {
64 await work
65 } finally {
66 this.pending.delete(account.dir)
67 }
68 }
69
70 private async load(account: Account, token: () => Promise<string | undefined>, force: boolean): Promise<void> {
71 const now = await this.now()
72 if (account.needsLogin) {
73 this.entries.set(account.dir, { status: 'sign-in', windows: [], checkedAt: now })
74 return
75 }
76 const previous = this.entries.get(account.dir)
77 if (previous?.retryAt && previous.retryAt > now) return
78 const resetPassed = previous?.windows.some(w => w.resetsAt && Date.parse(w.resetsAt) <= now && Date.parse(w.resetsAt) > (previous.checkedAt ?? 0))
79 if (!force && !resetPassed && previous?.checkedAt !== undefined && now - previous.checkedAt < USAGE_REFRESH_MS) return
80 // Keep showing the last reading while a refresh is in flight.
81 if (!previous) this.entries.set(account.dir, { status: 'loading', windows: [] })
82 let entry: UsageEntry = { status: 'unavailable', windows: [], checkedAt: now }
83 try {
84 const accessToken = await token()
85 if (!accessToken) {
86 this.entries.set(account.dir, { ...entry, status: 'refresh-login' })
87 return
88 }
89 const response = await this.api.fetch(accessToken)
90 if (response.status === 200) {
91 const windows = parseUsage(response.body)
92 entry = { ...entry, status: windows.length ? 'ready' : 'unavailable', windows }
93 } else if (response.status === 401 || response.status === 403) {
94 entry.status = 'refresh-login'
95 } else if (response.status === 429) {
96 const seconds = response.retryAfter ? Number(response.retryAfter) : NaN
97 const retryAt = Number.isFinite(seconds) ? now + seconds * 1000 : Date.parse(response.retryAfter ?? '')
98 entry = { ...entry, status: 'limited', retryAt: Math.max(now + USAGE_REFRESH_MS, Number.isFinite(retryAt) ? retryAt : 0) }
99 }
100 } catch {
101 // Keep failed reads separate from an exhausted subscription budget.
102 }
103 this.entries.set(account.dir, entry)
104 }
105}
106
107export function remaining(window: UsageWindow): number {
108 return Math.max(0, Math.floor(100 - window.used))
109}
110
111export function usageStatus(entry: UsageEntry | undefined, now: number): { label: string; colour: string; exhausted?: true } {
112 if (!entry || entry.status === 'loading') return { label: '· loading', colour: 'subtle' }
113 if (entry.status === 'sign-in') return { label: '! sign in', colour: 'warning' }
114 if (entry.status !== 'ready' || entry.checkedAt === undefined || now - entry.checkedAt >= USAGE_STALE_MS || entry.windows.some(w => w.resetsAt && Date.parse(w.resetsAt) <= now)) {
115 return { label: '? unknown', colour: 'subtle' }
116 }
117 if (entry.windows.some(w => w.used >= 100)) return { label: '◷ exhausted', colour: 'error', exhausted: true }
118 if (!['5h', 'Week'].every(label => entry.windows.some(w => w.label === label))) return { label: '? unknown', colour: 'subtle' }
119 if (entry.windows.some(w => remaining(w) < 30)) return { label: '! low budget', colour: 'warning' }
120 return { label: '○ available', colour: 'success' }
121}
122
123export function resetLabel(iso: string | undefined, timeZone?: string): string {
124 if (!iso || !Number.isFinite(Date.parse(iso))) return 'Not reported'
125 const date = new Date(iso)
126 const day = date.toLocaleDateString('en-GB', { weekday: 'short', day: '2-digit', month: 'short', ...(timeZone ? { timeZone } : {}) })
127 const time = date.toLocaleTimeString('en-GB', { hour: '2-digit', minute: '2-digit', hour12: false, ...(timeZone ? { timeZone } : {}) })
128 return `${day.replace(',', '')} ${time}`
129}
130