swapdex 0.72.0

Switch between multiple Claude Code, Codex, Gemini, and Antigravity login accounts, locally and safely.
Documentation
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
use clap::{CommandFactory, Parser};
use swapdex::commands::{self, ToolSel};
use swapdex::paths::Paths;

#[derive(Parser)]
#[command(
    name = "swapdex",
    version,
    about = "Switch Claude Code / Codex / Gemini / Antigravity login accounts, locally and safely."
)]
struct Cli {
    #[command(subcommand)]
    cmd: Option<Cmd>,
}

#[derive(clap::Subcommand)]
enum ServiceCmd {
    /// Install and start the agent, so the proxy survives a closed terminal and
    /// comes back by itself
    Install {
        /// Which tool's proxy (default: claude)
        #[arg(long, value_enum)]
        tool: Option<ToolSel>,
    },
    /// Stop and remove it
    Uninstall {
        #[arg(long, value_enum)]
        tool: Option<ToolSel>,
    },
    /// Where the unit is and whether it is loaded
    Status,
}

#[derive(clap::Subcommand)]
enum Cmd {
    /// Save the current live login as a named profile
    Add {
        /// Profile name (omit on a terminal to get a suggestion)
        name: Option<String>,
        #[arg(long, value_enum)]
        tool: Option<ToolSel>,
        /// Replace an existing snapshot for the tool
        #[arg(long)]
        update: bool,
    },
    /// Switch the active login to a saved profile
    Use {
        /// The saved profile to switch to (see `swapdex ls`)
        name: String,
        /// Limit the switch to one tool (default: every tool the profile has)
        #[arg(long, value_enum)]
        tool: Option<ToolSel>,
        /// Show what would change without writing
        #[arg(long)]
        dry_run: bool,
        /// After switching, open the tool right away (needs --tool)
        #[arg(long)]
        open: bool,
        /// Folder to open the conversation in (with --open; default: current dir)
        #[arg(long)]
        dir: Option<std::path::PathBuf>,
        /// Switch even if a Claude session is running on this login slot (it may
        /// log that account out on its next token refresh)
        #[arg(long)]
        force: bool,
    },
    /// Launch Claude in an account's own permanent slot (concurrent-safe)
    Run {
        /// The account to launch
        name: String,
        /// Which tool to launch it in (default: claude)
        #[arg(long, value_enum)]
        tool: Option<ToolSel>,
        /// Create the slot without launching anything
        #[arg(long)]
        no_launch: bool,
        /// Extra args passed straight to the tool (after `--`)
        #[arg(trailing_var_arg = true, allow_hyphen_values = true)]
        args: Vec<String>,
    },
    /// Find which account holds a conversation (searches every account's store)
    Whereis {
        /// Part of the project path, e.g. Project/ROS (omit to list the newest)
        project: Option<String>,
    },

    /// Hand turns to an account without moving where new sessions start
    Serve {
        /// The account to serve turns (omit to show, `--off` to stop directing)
        name: Option<String>,
        /// Let each session pay for itself again
        #[arg(long)]
        off: bool,
        /// Which tool (default: claude)
        #[arg(long, value_enum)]
        tool: Option<ToolSel>,
        /// Print just the name of the account that pays the next turn
        #[arg(long)]
        quiet: bool,
    },
    /// Renew accounts whose access token has lapsed (they stay usable)
    Refresh {
        /// One account, or every Claude account when omitted
        name: Option<String>,
        /// Renew every idle account heading for expiry, not only lapsed ones.
        /// A refresh token rotates when used and goes stale when it is not, so
        /// this is what keeps an account nobody touches from needing a sign-in.
        #[arg(long, conflicts_with = "name")]
        keep_alive: bool,
    },
    /// Keep the proxy running as a background service (launchd / systemd)
    Service {
        #[command(subcommand)]
        what: ServiceCmd,
    },
    /// List the permanent account slots
    Slots,
    /// Install the `claude` shim so a plain `claude` follows `swapdex use`
    Shim,
    /// Register an existing CLAUDE_CONFIG_DIR directory as a slot (in place)
    Adopt {
        /// Name for the account
        name: String,
        /// The existing config dir (e.g. ~/.claude-work, ~/.codex-work)
        dir: std::path::PathBuf,
        /// Which tool the dir belongs to (default: claude)
        #[arg(long, value_enum)]
        tool: Option<ToolSel>,
    },
    /// Give each legacy Claude profile its own permanent slot
    Migrate,
    /// Guided setup: register/migrate your accounts into permanent slots
    Onboard,
    /// Share MCP servers (from ~/.claude.json) into every account slot
    SyncMcp,
    /// List saved profiles (active marked from the live login)
    Ls {
        #[arg(long)]
        json: bool,
        /// Bare profile names, one per line (for scripts/completion)
        #[arg(long)]
        names: bool,
    },
    /// Show the active account per tool
    Status {
        #[arg(long)]
        json: bool,
        /// One compact line (for shell prompts / statuslines)
        #[arg(long)]
        short: bool,
    },
    /// Remove a saved profile (never touches a live login)
    Rm {
        name: String,
        /// Confirm the deletion
        #[arg(long)]
        yes: bool,
    },
    /// Guided first-time setup: save your logins, add more, learn to switch
    Setup,
    /// Log in to a tool and save the result as a profile in one step
    Login {
        name: String,
        #[arg(long, value_enum)]
        tool: Option<ToolSel>,
    },
    /// Rename a saved profile
    Rename { old: String, new: String },
    /// Put back the login that was live before the last switch
    Restore {
        /// Restore only this tool
        #[arg(long, value_enum)]
        tool: Option<commands::ToolSel>,
        /// Show what would be restored without writing
        #[arg(long)]
        dry_run: bool,
    },
    /// Sessions grouped by the account that was active when they ran
    Sessions {
        /// Emit JSON ({"available", "accounts", "total"})
        #[arg(long)]
        json: bool,
    },
    /// Full-screen picker: switch, open a conversation, add accounts
    Ui,
    /// Run a local proxy so a RUNNING Claude session can change accounts
    Proxy {
        /// Port to listen on (0 picks a free one)
        #[arg(long, default_value_t = commands::DEFAULT_PROXY_PORT)]
        port: u16,
        /// Serve every request from this account instead of the current default
        #[arg(long)]
        account: Option<String>,
        /// Which tool's traffic to carry (default: claude)
        #[arg(long, value_enum)]
        tool: Option<ToolSel>,
        /// Continue the SAME session on another account when one runs out
        /// (default: the `swapdex auto` setting)
        #[arg(long)]
        auto: bool,
        /// Force auto-continue OFF for this run, whatever the setting says
        #[arg(long, conflicts_with = "auto")]
        no_auto: bool,
        /// Print the port of a running proxy, starting one in the background if
        /// there is none. Used by the `claude` shim; exits non-zero if it cannot.
        #[arg(long)]
        ensure: bool,
        /// Step off an account once a window reaches this fraction (e.g. 0.98),
        /// instead of waiting for it to refuse a turn. Costs one usage read per
        /// account every couple of minutes.
        #[arg(long)]
        threshold: Option<f64>,
    },
    /// Make every conversation reachable from every account (one-time repair)
    ShareHistory {
        /// Which tool (default: claude)
        #[arg(long, value_enum)]
        tool: Option<ToolSel>,
        /// Say what would happen and change nothing
        #[arg(long)]
        dry_run: bool,
    },
    /// Install a `/sx` slash command for Claude Code (switch without leaving the chat)
    Slash,
    /// Step off an account at this much used (e.g. 0.9 or 90%), or `off`
    Threshold {
        /// A fraction, a percentage, or `off`; omit to show the current setting
        value: Option<String>,
    },
    /// Write this machine's account setup (names and settings, NEVER logins)
    Export {
        /// Where to write it; omit for stdout
        out: Option<std::path::PathBuf>,
    },
    /// Re-create that setup here. Accounts already present are left alone, and
    /// each still needs its own sign-in - a login never travels.
    Import {
        file: std::path::PathBuf,
        /// Show what would change and write nothing
        #[arg(long)]
        dry_run: bool,
    },
    /// A cheaper model to ask for when every account is past the threshold
    FallbackModel {
        /// Omit to show, `off` to clear. e.g. `claude-sonnet-5`
        value: Option<String>,
    },
    /// Which account auto-continue reaches for: `roomiest` or `consume-first`
    Strategy {
        /// Omit to show. `roomiest` takes the account with the most left;
        /// `consume-first` takes the window about to reset, so nothing lapses
        /// unused.
        value: Option<String>,
    },
    /// Turn auto-continue (proxy hands a spent session to another account) on/off
    Auto {
        /// `on`, `off`, or omit to show the current setting
        state: Option<String>,
    },
    /// Local health check: store, snapshots, live logins - with a fix per finding
    Doctor,
    /// Recent local token usage per tool (5h/7d), read from session logs
    Usage {
        /// Emit JSON
        #[arg(long)]
        json: bool,
    },
    /// Remaining Claude quota per account (opt-in live read from Anthropic)
    Quota {
        /// Emit JSON (includes the raw response for any unexpected shape)
        #[arg(long)]
        json: bool,
    },
    /// Run as a read-only MCP server over stdio
    Mcp,
    /// Print a shell completion script (bash, zsh, fish, ...)
    Completions { shell: clap_complete::Shell },
    /// Print the man page (roff) to stdout
    Manpage,
}

fn main() {
    let cli = Cli::parse();
    let paths = match Paths::resolve() {
        Ok(p) => p,
        Err(e) => {
            eprintln!("swapdex: {}", swapdex::util::redact_path(&format!("{e:#}")));
            std::process::exit(1);
        }
    };
    let Some(cmd) = &cli.cmd else {
        // No subcommand. On an interactive terminal with saved accounts, open
        // the picker - people expect a bare `swapdex` to DO something (k9s /
        // lazygit / ccusage all launch their UI this way), and a banner that
        // flashes and returns reads as "it opened and closed". Otherwise (a
        // pipe, a dumb terminal, or a fresh machine with nothing saved) print
        // the wordmark + a short hint + where you stand, and never touch the
        // store on a fresh machine.
        use std::io::IsTerminal;
        let interactive = std::io::stdin().is_terminal()
            && std::io::stdout().is_terminal()
            && std::env::var("TERM")
                .map(|t| !t.is_empty() && t != "dumb")
                .unwrap_or(false);
        // Slots count too: they are what `run`, `adopt`, and `onboard` create,
        // so counting only saved profiles showed a banner to a user whose
        // accounts were all slots - the model swapdex itself steers people into.
        let has_profiles = paths.store_dir().exists() && commands::has_any_account(&paths);
        // Also open the UI for a fresh-but-logged-in user: the onboarding
        // screen offers to save the accounts they're already signed into.
        let logged_in = swapdex::adapters::all().iter().any(|a| a.present(&paths));
        // First run with something to set up (existing config dirs to register,
        // or legacy copy-model profiles to migrate): guide onboarding instead of
        // silently dropping into the picker. One-time - marked done afterward.
        if interactive && commands::needs_onboarding(&paths) {
            match commands::onboard(&paths) {
                Ok(code) => std::process::exit(code),
                Err(e) => {
                    eprintln!("swapdex: {e:#}");
                    std::process::exit(1);
                }
            }
        }
        if interactive && (has_profiles || logged_in) {
            match commands::ui(&paths) {
                Ok(code) => std::process::exit(code),
                Err(e) => {
                    eprintln!("swapdex: {e:#}");
                    std::process::exit(1);
                }
            }
        }
        swapdex::banner::print_banner();
        if paths.store_dir().exists() {
            if let Some(line) = commands::short_line(&paths) {
                println!("  active: {line}");
            }
        }
        return;
    };
    // Completions generate swapdex's OWN tab-completion - they do NOT wrap or
    // intercept `claude`/`codex` (that is llmux's territory, deliberately out of
    // scope). Pure codegen, no account access.
    if let Cmd::Completions { shell } = cmd {
        clap_complete::generate(
            *shell,
            &mut Cli::command(),
            "swapdex",
            &mut std::io::stdout(),
        );
        return;
    }
    // Man page: pure codegen like completions (the Homebrew formula consumes
    // this at install time).
    if let Cmd::Manpage = cmd {
        let man = clap_mangen::Man::new(Cli::command());
        let mut buf = Vec::new();
        if let Err(e) = man.render(&mut buf) {
            eprintln!("swapdex: manpage render failed: {e}");
            std::process::exit(1);
        }
        use std::io::Write;
        if std::io::stdout().write_all(&buf).is_err() {
            std::process::exit(1);
        }
        return;
    }
    let result = match cmd {
        Cmd::Add { name, tool, update } => commands::add(&paths, name.as_deref(), *tool, *update),
        Cmd::Use {
            name,
            tool,
            dry_run,
            open,
            dir,
            force,
        } => {
            if *open {
                commands::use_account_open(&paths, name, *tool, dir.as_deref(), *force)
            } else {
                commands::use_account(&paths, name, *tool, *dry_run, *force)
            }
        }
        Cmd::Run {
            name,
            tool,
            no_launch,
            args,
        } => commands::run_account(&paths, name, *tool, *no_launch, args),
        Cmd::Whereis { project } => commands::whereis(&paths, project.as_deref()),
        Cmd::Serve {
            name,
            off,
            tool,
            quiet,
        } => commands::serve(&paths, name.as_deref(), *off, *tool, *quiet),
        Cmd::Refresh { name, keep_alive } => {
            if *keep_alive {
                commands::keep_alive(&paths)
            } else {
                commands::refresh(&paths, name.as_deref())
            }
        }
        Cmd::Service { what } => match what {
            ServiceCmd::Install { tool } => commands::service_install(&paths, *tool),
            ServiceCmd::Uninstall { tool } => commands::service_uninstall(*tool),
            ServiceCmd::Status => commands::service_status(&paths),
        },
        Cmd::Slots => commands::list_slots(&paths),
        Cmd::Shim => commands::install_shim(&paths),
        Cmd::Adopt { name, dir, tool } => commands::adopt_slot(&paths, name, dir, *tool),
        Cmd::Migrate => commands::migrate(&paths),
        Cmd::Onboard => commands::onboard(&paths),
        Cmd::SyncMcp => commands::sync_mcp(&paths),
        Cmd::Ls { json, names } => commands::ls(&paths, *json, *names),
        Cmd::Status { json, short } => commands::status(&paths, *json, *short),
        Cmd::Rm { name, yes } => commands::rm(&paths, name, *yes),
        Cmd::Setup => commands::setup(&paths),
        Cmd::Login { name, tool } => commands::login(&paths, name, *tool),
        Cmd::Rename { old, new } => commands::rename(&paths, old, new),
        Cmd::Restore { tool, dry_run } => commands::restore(&paths, *tool, *dry_run),
        Cmd::Sessions { json } => commands::sessions(&paths, *json),
        Cmd::Ui => commands::ui(&paths),
        Cmd::Proxy {
            port,
            account,
            tool,
            auto,
            no_auto,
            ensure,
            threshold,
        } => commands::proxy(
            &paths,
            *port,
            account.clone(),
            *tool,
            *auto,
            *no_auto,
            *ensure,
            *threshold,
        ),
        Cmd::Export { out } => commands::export(&paths, out.as_deref()),
        Cmd::Import { file, dry_run } => commands::import(&paths, file, *dry_run),
        Cmd::FallbackModel { value } => commands::fallback_model(&paths, value.as_deref()),
        Cmd::Strategy { value } => commands::strategy(&paths, value.as_deref()),
        Cmd::Auto { state } => commands::auto(&paths, state.as_deref()),
        Cmd::ShareHistory { tool, dry_run } => commands::share_history(
            &paths,
            match tool {
                Some(ToolSel::Codex) => "codex",
                _ => "claude-code",
            },
            *dry_run,
        ),
        Cmd::Slash => commands::install_slash(&paths),
        Cmd::Threshold { value } => commands::threshold(&paths, value.as_deref()),
        Cmd::Doctor => commands::doctor(&paths),
        Cmd::Usage { json } => commands::usage(&paths, *json),
        Cmd::Quota { json } => commands::quota(&paths, *json),
        Cmd::Mcp => {
            swapdex::mcp::serve();
            return;
        }
        Cmd::Completions { .. } | Cmd::Manpage => unreachable!("handled above as pure codegen"),
    };
    match result {
        Ok(code) => std::process::exit(code),
        Err(e) => {
            // Redact home paths from any error before it reaches a terminal/log.
            eprintln!("swapdex: {}", swapdex::util::redact_path(&format!("{e:#}")));
            std::process::exit(1);
        }
    }
}