claude-roster 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 claude-roster contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,232 @@
1
- # Temporary Holding Version
1
+ # claude-roster
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Multi-account supervisor for **Claude Code official subscriptions**. It is an adapter: it calls
4
+ your existing `claude` binary, gives each account its own `CLAUDE_CONFIG_DIR`, picks the account
5
+ with the most remaining quota, and switches accounts at a turn boundary by resuming the exact
6
+ transcript. It does not patch, replace, or redistribute Claude Code.
7
+
8
+ ## What it is
9
+
10
+ Claude Code enforces 5-hour and 7-day limits per subscription. If you own several Pro / Max /
11
+ Ultra subscriptions, `claude-roster` lets one long-running session move between them instead of
12
+ stopping at a limit screen.
13
+
14
+ - Every account gets a separate `CLAUDE_CONFIG_DIR`; logins are official OAuth and never shared
15
+ between people.
16
+ - Hooks watch `StopFailure` / `Notification rate_limit` / `Stop`; on a limit the supervisor starts
17
+ the next account and resumes the **same transcript path**.
18
+ - Trust / onboarding / bypass state is copied to the next account, so a switch does not stop on
19
+ “trust this folder”.
20
+ - Existing sessions can be adopted; several sessions may share one account on one machine.
21
+
22
+ The `claude-pool` column in the comparison below refers to a separate npm package by another
23
+ author; it is not this project.
24
+
25
+ ## When to use it
26
+
27
+ Use it when:
28
+
29
+ - you have **two or more of your own** Claude subscriptions and regularly hit 5h/7d limits;
30
+ - you want a long session to continue automatically instead of waiting for a reset;
31
+ - you want official OAuth and per-account isolation, not a shared account or an API-key proxy;
32
+ - you work on macOS or Linux (tmux integration is Unix-only).
33
+
34
+ Do not use it when:
35
+
36
+ - you have a single account and never hit limits;
37
+ - you need to share one account with other people (against the subscription terms);
38
+ - you use API keys or third-party endpoints — this tool is for Claude Code official logins;
39
+ - you need first-class Windows support today.
40
+
41
+ ## Requirements
42
+
43
+ - Claude Code CLI (`claude` in `PATH`, or set `CLAUDE_ROSTER_CLAUDE_BIN`)
44
+ - Node.js >= 18
45
+ - Pro / Max / Ultra subscription on each account
46
+ - macOS or Linux (Windows core only, not CI-tested)
47
+
48
+ ## Install
49
+
50
+ ```bash
51
+ npx -y claude-roster@latest
52
+ # or
53
+ npm install -g claude-roster
54
+ ```
55
+
56
+ ## Concepts
57
+
58
+ Account names are **labels you choose** — `primary`, `backup`, `work`, `personal`, anything.
59
+
60
+ | Command | What it does |
61
+ |---|---|
62
+ | `claude-roster setup primary backup` | Creates two account slots under `~/.claude-roster/accounts/`, installs hooks/statusline, but does **not** log in yet. |
63
+ | `claude-roster login primary` | Runs the official OAuth login for that slot. It prints the URL instead of opening a browser; add `--browser` to open it. |
64
+ | `claude-roster prepare` | Optional. Copies trust / onboarding / bypass state from existing configs so the current project does not prompt after a switch. |
65
+ | `claude-roster` | Starts a session on the best available account; later switches happen automatically. |
66
+
67
+ ## Quick start
68
+
69
+ ```bash
70
+ claude-roster setup primary backup # create account slots
71
+ claude-roster login primary # prints an OAuth URL; --browser to open it
72
+ claude-roster login backup
73
+ claude-roster prepare # optional: pre-trust the current project
74
+ claude-roster # start an auto-switching session
75
+ ```
76
+
77
+ With `npx`, prefix commands with `npx -y claude-roster@latest`.
78
+
79
+ ## Usage
80
+
81
+ ```bash
82
+ claude-roster [--account NAME] [claude args...] # new session; fails over automatically
83
+ claude-roster --resume <id|path> # resume a session
84
+ claude-roster --resume-last # resume the last roster session
85
+ claude-roster --resume # current account's session picker
86
+ ```
87
+
88
+ Accounts and quota:
89
+
90
+ ```bash
91
+ claude-roster setup [names...]
92
+ claude-roster login [--browser] <account>
93
+ claude-roster list
94
+ claude-roster status [--brief]
95
+ claude-roster limits
96
+ claude-roster usage [--in-use] [--account EMAIL]
97
+ claude-roster dashboard [--once] [--interval 5]
98
+ claude-roster stats [--days 7]
99
+ ```
100
+
101
+ Sessions and diagnostics:
102
+
103
+ ```bash
104
+ claude-roster sessions | panes | adopt <id|jsonl>
105
+ claude-roster session install [--config DIR] # opt-in: add /roster to any config dir
106
+ claude-roster doctor [--fix]
107
+ claude-roster log [-n N]
108
+ ```
109
+
110
+ ## In-session commands
111
+
112
+ Inside a session started through `claude-roster`, these are answered locally by a
113
+ `UserPromptSubmit` hook and do not spend a model turn:
114
+
115
+ ```
116
+ /roster /roster status /roster limits /roster usage
117
+ /roster dashboard /roster stats /roster doctor /roster fix
118
+ /roster list /roster add <name> /roster login <name>
119
+ /roster login code [name] <code> /roster switch <name>
120
+ ```
121
+
122
+ ## How switching works
123
+
124
+ - `StopFailure` / `Notification rate_limit` marks the account on cooldown, starts the next
125
+ account, and resumes the same transcript with `--resume <path>`.
126
+ - `Stop` with 5h/7d usage above the thresholds switches at a clean turn boundary.
127
+ - Trust / onboarding / bypass state is copied to the next account, so the switch does not stop
128
+ on a prompt.
129
+ - Usage comes from `api.anthropic.com/api/oauth/usage`; expired access tokens are refreshed and
130
+ the rotated refresh token is written back.
131
+
132
+ ## How it compares
133
+
134
+ | Capability | claude-roster | claude-pool (npm) | claude-swap | account-cluster | account-switcher |
135
+ |---|---|---|---|---|---|
136
+ | Switch trigger | hook-driven, turn boundary | CLI exit/message + respawn | thresholds / polling | rate_limit notification | manual |
137
+ | Session continuity | exact transcript path | copies transcript | shared history | `--resume` | per-account command |
138
+ | Trust/onboarding after switch | auto-copy + `prepare` | transcript only | shared config | — | shared config |
139
+ | Account isolation | full `CLAUDE_CONFIG_DIR` | `~/.claude-<account>` | shared `~/.claude` | Keychain | token isolated |
140
+ | Multi-session quota | lowest usage + sharing | priority only | strategies / parallel | — | per-account |
141
+ | Adopt existing sessions | `sessions` / `panes` / `adopt` | — | — | — | — |
142
+ | Usage source | official API + statusline cache | spawns `claude` usage | polling / API | API | statusline cache |
143
+ | Install / runtime | npm, Node >= 18 | npm | pipx / Python | install.sh | Go binary |
144
+ | Platforms | macOS / Linux; Windows untested | macOS / Linux / Windows | macOS / Linux / Windows | macOS | macOS / Linux / Windows |
145
+
146
+ ### Why claude-roster is better
147
+
148
+ - **Switches at a clean turn boundary, not mid-response.** `StopFailure` / `Notification
149
+ rate_limit` / `Stop` trigger the switch, so the current answer is never cut in half.
150
+ - **Exact transcript continuity.** The next account is started with the original transcript path,
151
+ not a copied history or a merged config, so the conversation and tool state stay intact.
152
+ - **No prompt after switching.** Trust / onboarding / bypass state is copied to the next account;
153
+ a switch does not stop at “trust this folder”.
154
+ - **Quota-aware, not just priority.** It ranks accounts by remaining 5h/7d quota and allows
155
+ several sessions to share one account on the same machine.
156
+ - **Adopts what you already have.** `sessions`, `panes`, `adopt`, `--resume-last` map existing
157
+ sessions and tmux panes to accounts instead of forcing a fresh start.
158
+ - **No patching, no wrapper requirement.** It calls your existing `claude` binary and keeps each
159
+ account in its own `CLAUDE_CONFIG_DIR`; global `~/.claude` is untouched by default.
160
+ - **Hooks that keep working.** Hook/statusline/entry scripts are copied to a stable `runtime/`
161
+ directory, so npx cache cleanup or a Node upgrade does not silently disable failover.
162
+ - **Zero-turn in-session commands.** `/roster status|limits|usage|login` are answered by a
163
+ `UserPromptSubmit` hook, not by the model.
164
+ - **One Node runtime.** macOS/Linux, no Python, no Go binary, no daemon.
165
+
166
+ Where other tools are better:
167
+
168
+ - `claude-pool` (npm): more turnkey first-run flow and a larger community.
169
+ - `claude-swap`: more switch strategies and parallel-session features.
170
+ - `claude-code-account-switcher`: single Go binary, no runtime, Windows support.
171
+
172
+ References: [claude-pool](https://github.com/Kbastwad19/claude-pool),
173
+ [claude-swap](https://github.com/realiti4/claude-swap),
174
+ [claude-code-account-cluster](https://github.com/GAMZAMANDU/claude-code-account-cluster),
175
+ [claude-code-account-switcher](https://github.com/claude-code-tools/claude-code-account-switcher).
176
+
177
+ ## State and footprint
178
+
179
+ - State lives in `~/.claude-roster/` (`accounts/<name>/`, `runtime/`, usage cache, logs).
180
+ Override with `CLAUDE_ROSTER_ROOT`.
181
+ - `runtime/` holds stable copies of the hook, statusline, and entry script, so installed hooks
182
+ survive npx cache cleanup and Node upgrades.
183
+ - No `~/.claude` changes and no binary replacement. `session install` is the only opt-in that
184
+ touches another config directory.
185
+ - Uninstall: `npm rm -g claude-roster`; run `claude-roster session remove` first if used; delete
186
+ `~/.claude-roster` to remove account state.
187
+
188
+ ## Configuration
189
+
190
+ | Variable | Meaning |
191
+ |---|---|
192
+ | `CLAUDE_ROSTER_ROOT` | state directory (default `~/.claude-roster`) |
193
+ | `CLAUDE_ROSTER_CLAUDE_BIN` | Claude Code binary (default `claude`) |
194
+ | `CLAUDE_ROSTER_THRESHOLD` | 5h switch-away line (default 90) |
195
+ | `CLAUDE_ROSTER_WEEKLY_THRESHOLD` | 7d switch-away line (default 90) |
196
+ | `CLAUDE_ROSTER_STRATEGY` | `best` / `priority` / `weekly-first` |
197
+ | `CLAUDE_ROSTER_LANG` | `en` / `zh` for CLI and statusline |
198
+ | `CLAUDE_ROSTER_DEBUG` | `1` prints OAuth-refresh diagnostics |
199
+
200
+ All environment variables use the `CLAUDE_ROSTER_` prefix.
201
+
202
+ ## Limitations
203
+
204
+ - The usage endpoint is undocumented and may rate-limit; cached values are used instead.
205
+ - Per-model limits (e.g. Opus weekly) are not visible to the statusline; failover still reacts to
206
+ limit errors.
207
+ - Windows core is implemented but not CI-tested; `panes`/tmux is Unix-only.
208
+ - Multiple accounts are for your own devices. Do not share an account with other people.
209
+ - Not affiliated with Anthropic; use of multiple subscriptions is your responsibility.
210
+
211
+ ## License
212
+
213
+ MIT
214
+
215
+ ---
216
+
217
+ ## 中文速览
218
+
219
+ `claude-roster` 是 Claude Code 官方订阅的多账号 supervisor:不替换 `claude`,每个账号独立
220
+ `CLAUDE_CONFIG_DIR`,限额时自动换号并用 transcript 绝对路径恢复原会话。
221
+
222
+ **适合**:自己有 2 个以上 Pro/Max/Ultra 订阅,长会话经常撞 5h/7d 限额,希望自动续上。
223
+ **不适合**:只有一个号、需要和别人共享账号、走 API key/第三方端点。
224
+
225
+ - 安装:`npm i -g claude-roster`,或 `npx -y claude-roster@latest`
226
+ - `primary` / `backup` 只是你起的账号名,可以任意命名
227
+ - `setup primary backup`:建账号槽 + 装 hook,不登录
228
+ - `login primary`:对该槽跑官方 OAuth,打印 URL(`--browser` 才自动打开)
229
+ - `prepare`:可选,预置当前项目的 trust,切号不弹窗
230
+ - 日常:`claude-roster` 新会话;`claude-roster --resume <id|路径>` 续会话
231
+ - 会话内:`/roster status`、`/roster limits`、`/roster usage`、`/roster login <账号>`
232
+ - 状态目录:`~/.claude-roster`;卸载前先 `claude-roster session remove`
@@ -0,0 +1,29 @@
1
+ #!/usr/bin/env node
2
+ // claude-roster hook: persist the Claude Code hook payload as an event file.
3
+ // Node-only so it works on macOS, Linux, and Windows.
4
+ import { mkdirSync, writeFileSync } from 'node:fs';
5
+ import { join } from 'node:path';
6
+
7
+ const dir = process.env.CLAUDE_ROSTER_EVENT_DIR;
8
+ if (!dir) process.exit(0);
9
+
10
+ try {
11
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
12
+ } catch {
13
+ process.exit(0);
14
+ }
15
+
16
+ let input = '';
17
+ process.stdin.setEncoding('utf8');
18
+ process.stdin.on('data', chunk => {
19
+ if (input.length < 1_000_000) input += chunk;
20
+ });
21
+ process.stdin.on('end', () => {
22
+ const file = join(dir, `event-${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2)}.json`);
23
+ try {
24
+ writeFileSync(file, input, { mode: 0o600 });
25
+ } catch {
26
+ // A failed event must never break Claude Code.
27
+ }
28
+ process.exit(0);
29
+ });
@@ -0,0 +1,151 @@
1
+ #!/usr/bin/env node
2
+ // claude-roster statusline — account prefix + plan + 5h/7d usage.
3
+ // Node-only so it works on macOS, Linux, and Windows.
4
+ import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
5
+ import { homedir } from 'node:os';
6
+ import { dirname, join } from 'node:path';
7
+
8
+ let data;
9
+ try {
10
+ data = JSON.parse(readFileSync(0, 'utf8'));
11
+ } catch {
12
+ process.exit(0);
13
+ }
14
+
15
+ const limits = data.rate_limits || {};
16
+ let five = limits.five_hour?.used_percentage;
17
+ let week = limits.seven_day?.used_percentage;
18
+ let fiveReset = limits.five_hour?.resets_at;
19
+ let weekReset = limits.seven_day?.resets_at;
20
+
21
+ const account = process.env.CLAUDE_ROSTER_ACCOUNT_NAME;
22
+ const root = process.env.CLAUDE_ROSTER_ROOT || join(homedir(), '.claude-roster');
23
+ const eventDir = process.env.CLAUDE_ROSTER_EVENT_DIR;
24
+
25
+ let lang = String(process.env.CLAUDE_ROSTER_LANG || '').toLowerCase();
26
+ if (!['zh', 'en'].includes(lang)) {
27
+ const locale = String(process.env.LC_ALL || process.env.LANG || '').toLowerCase();
28
+ lang = locale.startsWith('zh') ? 'zh' : 'en';
29
+ }
30
+ const text = {
31
+ zh: { usage: '用量 …', signedOut: '未登录' },
32
+ en: { usage: 'usage …', signedOut: 'signed out' },
33
+ }[lang];
34
+
35
+ const isNum = value => typeof value === 'number' && Number.isFinite(value);
36
+ const paint = (code, value) => (process.env.NO_COLOR ? String(value) : `\x1b[${code}m${value}\x1b[0m`);
37
+
38
+ function writePrivate(path, value) {
39
+ const directory = dirname(path);
40
+ mkdirSync(directory, { recursive: true, mode: 0o700 });
41
+ const tmp = join(directory, `.tmp-${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2)}`);
42
+ writeFileSync(tmp, value, { mode: 0o600 });
43
+ try { chmodSync(tmp, 0o600); } catch { /* Windows */ }
44
+ renameSync(tmp, path);
45
+ }
46
+
47
+ function readJson(path, fallback) {
48
+ try { return JSON.parse(readFileSync(path, 'utf8')); } catch { return fallback; }
49
+ }
50
+
51
+ function resetIn(epoch) {
52
+ const ts = Number(epoch);
53
+ if (!Number.isFinite(ts) || ts <= 0) return '';
54
+ const sec = ts - Math.floor(Date.now() / 1000);
55
+ if (sec <= 0) return 'now';
56
+ if (sec < 3600) return `${Math.floor(sec / 60)}m`;
57
+ if (sec < 86400) return `${Math.floor(sec / 3600)}h${Math.floor((sec % 3600) / 60)}m`;
58
+ return `${Math.floor(sec / 86400)}d${Math.floor((sec % 86400) / 3600)}h`;
59
+ }
60
+
61
+ function bar(pct, width = 5) {
62
+ const filled = Math.max(0, Math.min(width, Math.round(pct / 100 * width)));
63
+ return '█'.repeat(filled) + '░'.repeat(width - filled);
64
+ }
65
+
66
+ function colorFor(pct) {
67
+ if (pct >= 90) return '1;31';
68
+ if (pct >= 75) return '31';
69
+ if (pct >= 50) return '33';
70
+ return '32';
71
+ }
72
+
73
+ function segment(label, pct, resetAt) {
74
+ if (!isNum(pct)) return null;
75
+ let value = `${label} ${paint(colorFor(pct), bar(pct))} ${Math.round(pct)}%`;
76
+ const remaining = resetIn(resetAt);
77
+ if (remaining) value += ` ${paint('2', `↻${remaining}`)}`;
78
+ return value;
79
+ }
80
+
81
+ const usagePath = account ? join(root, 'usage', `${account}.json`) : null;
82
+ const cached = usagePath ? readJson(usagePath, {}) : {};
83
+ const accountInfo = account ? readJson(join(root, 'accounts-info.json'), {})?.[account] || {} : {};
84
+ const curFive = five;
85
+ const curWeek = week;
86
+
87
+ if (!isNum(five) && isNum(cached.five_hour)) {
88
+ five = cached.five_hour;
89
+ fiveReset = cached.five_hour_reset_at;
90
+ }
91
+ if (!isNum(week) && isNum(cached.seven_day)) {
92
+ week = cached.seven_day;
93
+ weekReset = cached.seven_day_reset_at;
94
+ }
95
+
96
+ // Only refresh with values Claude Code actually reported. Writing nulls here
97
+ // would wipe the last good usage and make a new session look empty.
98
+ if (usagePath && (isNum(curFive) || isNum(curWeek))) {
99
+ const usage = { ...cached };
100
+ if (isNum(curFive)) {
101
+ usage.five_hour = curFive;
102
+ usage.five_hour_reset_at = fiveReset;
103
+ }
104
+ if (isNum(curWeek)) {
105
+ usage.seven_day = curWeek;
106
+ usage.seven_day_reset_at = weekReset;
107
+ }
108
+ usage.session_id = data.session_id;
109
+ usage.transcript_path = data.transcript_path;
110
+ usage.updated_at = Date.now();
111
+ try { writePrivate(usagePath, JSON.stringify(usage)); } catch { /* cache only */ }
112
+ }
113
+
114
+ const segments = [
115
+ segment('5h', five, fiveReset),
116
+ segment('7d', week, weekReset),
117
+ ].filter(Boolean);
118
+
119
+ const displayName = accountInfo.prefix || accountInfo.email || account || 'pool';
120
+ let plan = accountInfo.planLabel || '';
121
+ if (accountInfo.loggedIn === false) {
122
+ plan = plan ? `${plan} · ${text.signedOut}` : text.signedOut;
123
+ }
124
+ let line = paint('1;36', displayName + (plan ? ` · ${plan}` : ''));
125
+ line += paint('2', ' │ ') + (segments.length ? segments.join(paint('2', ' │ ')) : paint('2', text.usage));
126
+ process.stdout.write(line + '\n');
127
+
128
+ let threshold = Number(process.env.CLAUDE_ROSTER_THRESHOLD || 90);
129
+ if (!Number.isFinite(threshold)) threshold = 90;
130
+ let weekly = Number(process.env.CLAUDE_ROSTER_WEEKLY_THRESHOLD || threshold);
131
+ if (!Number.isFinite(weekly)) weekly = threshold;
132
+
133
+ const crossed = (isNum(curFive) && curFive >= threshold) || (isNum(curWeek) && curWeek >= weekly);
134
+ if (eventDir && crossed) {
135
+ const event = {
136
+ kind: 'usage',
137
+ five_hour: curFive,
138
+ seven_day: curWeek,
139
+ five_hour_reset_at: fiveReset,
140
+ seven_day_reset_at: weekReset,
141
+ session_id: data.session_id,
142
+ transcript_path: data.transcript_path,
143
+ account,
144
+ };
145
+ try {
146
+ mkdirSync(eventDir, { recursive: true, mode: 0o700 });
147
+ const tmp = join(eventDir, `.event-${process.pid}-${Date.now()}.json`);
148
+ writeFileSync(tmp, JSON.stringify(event), { mode: 0o600 });
149
+ renameSync(tmp, join(eventDir, 'event-usage.json'));
150
+ } catch { /* event only */ }
151
+ }