Repository navigation
Expand file tree
/
Copy pathcc-switch.cjs
More file actions
477 lines (445 loc) · 15.1 KB
/
Copy pathcc-switch.cjs
File metadata and controls
477 lines (445 loc) · 15.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
#!/usr/bin/env node
const path = require('path');
const storeIo = require('./lib/store/io.cjs');
const storeAccounts = require('./lib/store/accounts.cjs');
const usageCache = require('./lib/usage/cache.cjs');
const usageFetch = require('./lib/usage/fetch.cjs');
const usageFormat = require('./lib/usage/format.cjs');
const outputAccounts = require('./lib/output/accounts.cjs');
const outputUsage = require('./lib/output/usage.cjs');
const outputMessages = require('./lib/output/messages.cjs');
const syncAction = require('./lib/actions/sync.cjs');
const usageAction = require('./lib/actions/usage.cjs');
const removeAction = require('./lib/actions/remove.cjs');
const listAction = require('./lib/actions/list.cjs');
const switchAction = require('./lib/actions/switch.cjs');
const renameAction = require('./lib/actions/rename.cjs');
const authGuard = require('./lib/auth/guard.cjs');
const authRefresh = require('./lib/auth/refresh.cjs');
const procSessions = require('./lib/proc/sessions.cjs');
const storeLock = require('./lib/store/lock.cjs');
const stagedSwitch = require('./lib/actions/staged.cjs');
const switchWatcher = require('./lib/actions/watcher.cjs');
const {
getDefaultConfigPath,
getDefaultCredentialsPath,
getDefaultStorePath,
getDefaultBackupDir,
ensureDir,
readJson,
readJsonIfExists,
readCredentials,
deepCopy,
writeLiveState,
verifyLiveState,
writeStore,
} = storeIo;
const {
getAccountKey,
normalizeStore,
getDisplayAccounts,
syncStoreFromLive,
findSelection,
removeStoredAccount,
} = storeAccounts;
const {
readSettings,
writeSettings,
getRateLimitResetAt,
setRateLimitResetAt,
setRateLimitResetAtFromIso,
} = usageCache;
const fetchUsageApi = usageFetch.fetchUsage;
const formatUsageInfoUi = usageFormat.formatUsageInfo;
const refreshStoredUsageSnapshotsUi = usageFormat.refreshStoredUsageSnapshots;
const getUsageColumnsUi = outputUsage.getUsageColumns;
const getEntryLabelUi = outputAccounts.getEntryLabel;
const inferPlanTypeUi = outputAccounts.inferPlanType;
const formatAccountSummaryUi = outputAccounts.formatAccountSummary;
const formatRelativeTimeUi = outputUsage.formatRelativeTime;
const getListGuidance = outputMessages.getListGuidance;
const getRestartNotice = outputMessages.getRestartNotice;
const getAvailableAccountsHeading = outputMessages.getAvailableAccountsHeading;
const getStoredAccountsHeading = outputMessages.getStoredAccountsHeading;
const getRemainingAccountsHeading = outputMessages.getRemainingAccountsHeading;
const runSyncAction = syncAction.runSyncAction;
const runUsageAction = usageAction.runUsageAction;
const runRemoveAction = removeAction.runRemoveAction;
const runListAction = listAction.runListAction;
const runSwitchAction = switchAction.runSwitchAction;
const runRenameAction = renameAction.runRenameAction;
const STORE_VERSION = '0.2.9';
const RESET_WINDOW_DAYS = 7;
function parseArgs(argv) {
const settings = readSettings();
const options = {
configPath: getDefaultConfigPath(),
credentialsPath: getDefaultCredentialsPath(),
storePath: getDefaultStorePath(),
backupDir: getDefaultBackupDir(),
syncOnly: false,
touchCurrentOnly: false,
usageOnly: false,
removeOnly: false,
removeIndex: null,
renameOnly: false,
renameIndex: null,
renameAliasParts: [],
showUsage: settings.showUsage !== false,
force: false,
cancelOnly: false,
watchApply: false,
noWatch: false,
selector: '',
};
const args = [...argv];
while (args.length > 0) {
const current = args.shift();
if (current === '--config') {
options.configPath = args.shift() || options.configPath;
continue;
}
if (current === '--credentials') {
options.credentialsPath = args.shift() || options.credentialsPath;
continue;
}
if (current === '--store') {
options.storePath = args.shift() || options.storePath;
continue;
}
if (current === '--backup-dir') {
options.backupDir = args.shift() || options.backupDir;
continue;
}
if (current === '--sync' || current === 'sync') {
options.syncOnly = true;
continue;
}
if (current === '--force' || current === '-f') {
options.force = true;
continue;
}
if (current === '--cancel' || current === 'cancel') {
options.cancelOnly = true;
continue;
}
if (current === '--watch-apply') {
options.watchApply = true;
continue;
}
if (current === '--no-watch') {
options.noWatch = true;
continue;
}
if (current === '--touch-current') {
options.touchCurrentOnly = true;
continue;
}
if (current === '--usage' || current === 'usage') {
options.usageOnly = true;
continue;
}
if (current === '--remove' || current === 'remove') {
options.removeOnly = true;
continue;
}
if (current === '--rename' || current === 'rename') {
options.renameOnly = true;
continue;
}
if (current === '--show-usage') {
options.showUsage = true;
const s = readSettings();
s.showUsage = true;
writeSettings(s, ensureDir);
console.log('Usage display enabled.');
return options;
}
if (current === '--hide-usage') {
options.showUsage = false;
const s = readSettings();
s.showUsage = false;
writeSettings(s, ensureDir);
console.log('Usage display disabled.');
return options;
}
if (options.removeOnly && options.removeIndex === null) {
const numeric = Number.parseInt(current, 10);
if (!Number.isNaN(numeric) && String(numeric) === current) {
options.removeIndex = numeric;
continue;
}
}
if (options.renameOnly) {
if (options.renameIndex === null) {
const numeric = Number.parseInt(current, 10);
if (!Number.isNaN(numeric) && String(numeric) === current) {
options.renameIndex = numeric;
continue;
}
}
options.renameAliasParts.push(current);
continue;
}
if (!options.selector) {
options.selector = current;
continue;
}
}
return options;
}
function buildSwitchContext(extra) {
return {
deepCopy,
writeLiveState,
verifyLiveState,
writeStore,
assessCredentials: authGuard.assessCredentials,
refreshTokens: authRefresh.refreshTokens,
detectClaudeSessions: procSessions.detectClaudeSessions,
tokenCooldown: {
getUntil: () => usageCache.getTokenCooldownUntil(),
start: () => usageCache.setTokenCooldown(ensureDir),
},
now: () => Date.now(),
messages: outputMessages,
stageSwitch: (selected) => {
const staged = stagedSwitch.stageSwitch(selected, {
readSettings,
writeSettings,
ensureDir,
now: () => Date.now(),
});
if (!extra.options.noWatch) {
staged.watcher = switchWatcher.spawnWatcher({
cliPath: __filename,
options: extra.options,
readSettings,
writeSettings,
ensureDir,
});
}
return staged;
},
getDisplayAccounts,
inferPlanType: inferPlanTypeUi,
getEntryLabel: getEntryLabelUi,
getRestartNotice,
getStoredAccountsHeading,
formatAccountSummary: (items) => formatAccountSummaryUi(items, {
formatRelativeTime: formatRelativeTimeUi,
getUsageColumns: getUsageColumnsUi,
}),
...extra,
};
}
// Warns about slots that can no longer be restored without an interactive
// login: a rejected refresh token, or a hard expiry closing in.
function reportSlotHealth(accounts, options) {
const now = Date.now();
for (const entry of accounts) {
const label = getEntryLabelUi(entry);
if (entry.needsReauth) {
console.log(outputMessages.getNeedsReauthNotice(label));
continue;
}
const status = authGuard.getRefreshExpiryStatus(entry.credentials && entry.credentials.claudeAiOauth, now);
if (status.warn) {
console.log(outputMessages.getRefreshExpiryWarning(label, status.daysLeft));
}
}
}
async function main() {
const options = parseArgs(process.argv.slice(2));
if (options.cancelOnly) {
const cancelled = stagedSwitch.clearStagedSwitch({ readSettings, writeSettings, ensureDir });
// The watcher notices the cleared record on its next tick and exits.
console.log(cancelled
? outputMessages.getStagedCancelledNotice(cancelled)
: outputMessages.getStagedMissingNotice());
return;
}
if (options.watchApply) {
await runWatcher(options);
return;
}
try {
// Everything below reads-then-writes the credential files, so the lock is
// taken before the first read: another process (or a concurrent hook) may
// have rotated a single-use refresh token since we last looked.
await storeLock.withLock({}, async () => { await run(options); });
} catch (error) {
console.log(`Switch failed: ${error.message}`);
process.exitCode = 1;
}
}
// Runs detached after a staged switch: waits for the last Claude Code session
// to exit, then applies the switch so the next launch is on the new account.
async function runWatcher(options) {
const applyOptions = { ...options, watchApply: false, selector: '', showUsage: false };
const result = await switchWatcher.runWatchLoop({
detectClaudeSessions: procSessions.detectClaudeSessions,
readStaged: () => stagedSwitch.readStagedSwitch(readSettings()),
applyNow: async () => {
try {
await storeLock.withLock({}, async () => { await run(applyOptions); });
} catch {
return false;
}
// run() clears the staged record only after a verified switch.
return !stagedSwitch.readStagedSwitch(readSettings());
},
sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
now: () => Date.now(),
});
switchWatcher.clearWatcherRecord({ readSettings, writeSettings, ensureDir });
console.log(`Watcher finished: ${result.outcome}`);
return result;
}
async function run(options) {
{
const displayOnly = options.usageOnly || (!options.selector && !options.syncOnly && !options.touchCurrentOnly && !options.removeOnly && !options.renameOnly);
const config = displayOnly ? readJsonIfExists(options.configPath, {}) : readJson(options.configPath);
const credentials = readCredentials(options.credentialsPath, { allowMissing: displayOnly });
const existingStore = normalizeStore(readJsonIfExists(options.storePath, { version: STORE_VERSION, accounts: [] }), STORE_VERSION);
// Listing remains available after Claude Code clears a dead login. Never
// replace saved credentials with an empty live snapshot.
const syncLive = () => {
if (displayOnly && (!config.oauthAccount || !credentials?.claudeAiOauth)) {
return { store: existingStore, changed: false };
}
return syncStoreFromLive(existingStore, config, credentials, deepCopy, STORE_VERSION);
};
if (options.syncOnly) {
runSyncAction(existingStore, config, credentials, {
syncStoreFromLive,
deepCopy,
storeVersion: STORE_VERSION,
writeStore,
options,
path,
});
return;
}
if (options.touchCurrentOnly) {
const syncedTouch = syncStoreFromLive(existingStore, config, credentials, deepCopy, STORE_VERSION);
const storeTouch = syncedTouch.store;
const currentKey = getAccountKey(config.oauthAccount);
const idx = storeTouch.accounts.findIndex((e) => e.key === currentKey);
if (idx >= 0) {
storeTouch.accounts[idx].lastUsedAt = new Date().toISOString();
}
writeStore(storeTouch, options);
return;
}
// Capture the live login before every account operation, including failed
// or staged switches and usage requests that return no fresh API data.
const synced = syncLive();
if (synced.warning) {
console.log(outputMessages.getSyncSkippedWarning(synced.warning));
}
const store = synced.store;
if (synced.changed) {
writeStore(store, options);
console.log(`Synced current account into ${path.basename(options.storePath)}.`);
}
if (options.usageOnly) {
await runUsageAction({
store,
config,
credentials,
fetchUsage: fetchUsageApi,
formatUsageInfo: formatUsageInfoUi,
refreshStoredUsageSnapshots: refreshStoredUsageSnapshotsUi,
writeStore,
options,
getAccountKey,
setRateLimitResetAt,
setRateLimitResetAtFromIso,
ensureDir,
});
return;
}
if (options.removeOnly) {
runRemoveAction(store, options.removeIndex, {
removeStoredAccount,
writeStore,
options,
getEntryLabel: getEntryLabelUi,
getRemainingAccountsHeading,
});
return;
}
if (options.renameOnly) {
runRenameAction(store, options.renameIndex, options.renameAliasParts.join(' '), {
writeStore,
options,
config,
getEntryLabel: getEntryLabelUi,
getDisplayAccounts,
getStoredAccountsHeading,
formatAccountSummary: (items) => formatAccountSummaryUi(items, {
formatRelativeTime: formatRelativeTimeUi,
getUsageColumns: getUsageColumnsUi,
}),
});
return;
}
const accounts = getDisplayAccounts(store, config.oauthAccount);
// A bare invocation is the moment to apply a switch staged earlier from
// inside a Claude Code session that could not safely apply it.
if (!options.selector) {
const staged = stagedSwitch.readStagedSwitch(readSettings());
if (staged) {
const stagedSelection = stagedSwitch.resolveStagedSelection(staged, accounts);
if (!stagedSelection) {
console.log(outputMessages.getStagedStaleNotice(staged));
stagedSwitch.clearStagedSwitch({ readSettings, writeSettings, ensureDir });
} else {
console.log(outputMessages.getStagedApplyingNotice(getEntryLabelUi(stagedSelection), stagedSelection.index));
const stagedResult = await runSwitchAction(buildSwitchContext({
selected: stagedSelection,
store,
config,
options,
fromStaged: true,
}));
if (stagedResult.switched) {
stagedSwitch.clearStagedSwitch({ readSettings, writeSettings, ensureDir });
}
return;
}
}
}
if (!options.selector) {
reportSlotHealth(accounts, options);
await runListAction({
store,
config,
credentials,
options,
writeStore,
getAccountKey,
refreshStoredUsageSnapshots: refreshStoredUsageSnapshotsUi,
fetchUsage: fetchUsageApi,
formatUsageInfo: formatUsageInfoUi,
formatAccountSummary: (items) => formatAccountSummaryUi(items, {
formatRelativeTime: formatRelativeTimeUi,
getUsageColumns: getUsageColumnsUi,
}),
getDisplayAccounts,
getListGuidance,
getAvailableAccountsHeading,
getRateLimitResetAt,
setRateLimitResetAt,
setRateLimitResetAtFromIso,
ensureDir,
RESET_WINDOW_DAYS,
});
return;
}
const selected = findSelection(accounts, options.selector);
await runSwitchAction(buildSwitchContext({ selected, store, config, options }));
}
}
main();