Skip to main content

shunt/
cli.rs

1use anyhow::{bail, Context as _, Result};
2use clap::{Parser, Subcommand};
3use std::path::PathBuf;
4use std::time::{SystemTime, UNIX_EPOCH};
5
6use crate::config::{config_path, config_template, credentials_path, log_path, pid_path, CredentialsStore};
7use crate::oauth::{claude_credentials_path, read_claude_credentials, refresh_token, revoke_token, run_oauth_flow};
8use crate::term::{self, bold, bold_white, brand_green, cyan, dark_green, dim, green, green_bold, red, yellow, CHECK, CROSS, DIAMOND, DOT, EMPTY};
9
10#[derive(Parser)]
11#[command(name = "shunt", about = "Local Claude Code account-pooling proxy", version)]
12struct Cli {
13    #[command(subcommand)]
14    command: Command,
15}
16
17#[derive(Subcommand)]
18enum Command {
19    /// Interactive setup — auto-imports your existing Claude Code session
20    Setup {
21        #[arg(long)]
22        config: Option<PathBuf>,
23    },
24    /// Start the proxy (runs setup first if not configured)
25    Start {
26        #[arg(long)]
27        config: Option<PathBuf>,
28        #[arg(long)]
29        host: Option<String>,
30        #[arg(long)]
31        port: Option<u16>,
32        /// Keep the process in the foreground instead of daemonizing
33        #[arg(long)]
34        foreground: bool,
35        /// Enable debug-level logging (shows routing decisions and token refresh details)
36        #[arg(long)]
37        verbose: bool,
38        /// Internal: running as background daemon (do not use directly)
39        #[arg(long, hide = true)]
40        daemon: bool,
41    },
42    /// Stop the running proxy daemon
43    Stop,
44    /// Restart the proxy daemon (stop then start)
45    Restart {
46        #[arg(long)]
47        config: Option<PathBuf>,
48    },
49    /// Print current config and proxy status
50    Status {
51        #[arg(long)]
52        config: Option<PathBuf>,
53    },
54    /// Tail the proxy log file
55    ///
56    /// Examples:
57    ///   shunt logs           — last 50 lines
58    ///   shunt logs -f        — follow in real time
59    ///   shunt logs -n 100    — last 100 lines
60    Logs {
61        #[arg(long)]
62        config: Option<PathBuf>,
63        /// Follow log output in real time (like tail -f)
64        #[arg(short, long)]
65        follow: bool,
66        /// Number of lines to show
67        #[arg(short = 'n', long, default_value = "50")]
68        lines: usize,
69    },
70    /// Import the current Claude Code session as an additional account
71    AddAccount {
72        #[arg(long)]
73        config: Option<PathBuf>,
74        /// Name for this account (e.g. "secondary", "work"). Prompted if omitted.
75        name: Option<String>,
76        /// Provider: "anthropic" or "openai". Prompted interactively if omitted.
77        #[arg(long)]
78        provider: Option<String>,
79    },
80    /// Remove an account from the pool
81    RemoveAccount {
82        #[arg(long)]
83        config: Option<PathBuf>,
84        /// Name of the account to remove (omit to pick interactively)
85        name: Option<String>,
86    },
87    /// Enable remote access — expose the proxy to other devices
88    Share {
89        #[arg(long)]
90        config: Option<PathBuf>,
91        /// Create a public tunnel via Cloudflare (works over any network, not just LAN)
92        #[arg(long)]
93        tunnel: bool,
94        /// Disable remote access and revert to localhost-only
95        #[arg(long)]
96        stop: bool,
97    },
98    /// Log out of an account — clears stored credentials (keeps account in config)
99    ///
100    /// Examples:
101    ///   shunt logout           — interactive picker
102    ///   shunt logout work      — log out 'work'
103    ///   shunt logout --all     — log out every account
104    Logout {
105        #[arg(long)]
106        config: Option<PathBuf>,
107        /// Account name to log out. Omit to pick interactively.
108        name: Option<String>,
109        /// Log out all accounts at once
110        #[arg(long)]
111        all: bool,
112    },
113    /// Live fullscreen TUI dashboard — shows account utilization and request log
114    Monitor {
115        #[arg(long)]
116        config: Option<PathBuf>,
117    },
118    /// Watch a remote shunt instance and fire local system notifications
119    ///
120    /// Run with no arguments on the machine running shunt to get a watch code,
121    /// then enter that code on another device to receive notifications there.
122    ///
123    /// Examples:
124    ///   shunt remote                  — host: generate a watch code
125    ///   shunt remote RM-a3f2b1c4...  — client: connect with a watch code
126    Remote {
127        /// Watch code from `shunt remote` on the host. Omit to start hosting.
128        code: Option<String>,
129    },
130    /// Connect this device to a remote shunt instance
131    ///
132    /// Fetches the proxy URL and API key for the given share code (printed by
133    /// `shunt share` on the host) and writes them to your shell profile so
134    /// Claude Code routes through the shared proxy automatically.
135    ///
136    /// Examples:
137    ///   shunt connect SC-a3f2b1c4d5e6f7a8b9
138    Connect {
139        /// Share code printed by `shunt share` on the host
140        code: String,
141    },
142    /// Update shunt to the latest release
143    Update,
144    /// Completely remove shunt — stops service, deletes config, removes binary
145    Uninstall,
146    /// Manage shunt as a system service (auto-start on login)
147    ///
148    /// Examples:
149    ///   shunt service install    — register + start (called by install.sh)
150    ///   shunt service uninstall  — stop + remove
151    ///   shunt service status     — is service registered/running?
152    Service {
153        #[command(subcommand)]
154        action: ServiceAction,
155    },
156    /// Pin routing to a specific account, or restore automatic routing
157    ///
158    /// Examples:
159    ///   shunt use            — interactive picker
160    ///   shunt use work       — force all requests through 'work'
161    ///   shunt use auto       — restore automatic least-utilization routing
162    Use {
163        #[arg(long)]
164        config: Option<PathBuf>,
165        /// Account name to pin to, or "auto". Omit to pick interactively.
166        account: Option<String>,
167    },
168}
169
170#[derive(Subcommand)]
171enum ServiceAction {
172    /// Register shunt as a login service and start it immediately
173    Install,
174    /// Stop and unregister the shunt login service
175    Uninstall,
176    /// Show whether the service is registered and running
177    Status,
178}
179
180pub async fn run() -> Result<()> {
181    let cli = Cli::parse();
182    match cli.command {
183        Command::Setup { config } => cmd_setup(config).await,
184        Command::Start { config, host, port, foreground, verbose, daemon } => cmd_start(config, host, port, foreground, verbose, daemon).await,
185        Command::Stop => cmd_stop().await,
186        Command::Restart { config } => cmd_restart(config).await,
187        Command::Status { config } => cmd_status(config).await,
188        Command::Logs { config, follow, lines } => cmd_logs(config, follow, lines).await,
189        Command::AddAccount { config, name, provider } => cmd_add_account(config, name, provider.as_deref()).await,
190        Command::RemoveAccount { config, name } => cmd_remove_account(config, name).await,
191        Command::Logout { config, name, all } => cmd_logout(config, name, all).await,
192        Command::Monitor { config } => cmd_monitor(config).await,
193        Command::Remote { code } => cmd_remote(code).await,
194        Command::Connect { code } => cmd_connect(code).await,
195        Command::Update => cmd_update().await,
196        Command::Share { config, tunnel, stop } => cmd_share(config, tunnel, stop).await,
197        Command::Uninstall => cmd_uninstall().await,
198        Command::Use { config, account } => cmd_use(config, account).await,
199        Command::Service { action } => match action {
200            ServiceAction::Install   => cmd_service_install().await,
201            ServiceAction::Uninstall => cmd_service_uninstall().await,
202            ServiceAction::Status    => cmd_service_status().await,
203        },
204    }
205}
206
207// ---------------------------------------------------------------------------
208// setup
209// ---------------------------------------------------------------------------
210
211pub async fn cmd_setup(config_override: Option<PathBuf>) -> Result<()> {
212    let config_p = config_override.clone().unwrap_or_else(config_path);
213
214    print_splash(&[
215        format!("{}  {}", brand_green("shunt"), dim(&format!("v{}", env!("CARGO_PKG_VERSION")))),
216        dim("Setup"),
217        String::new(),
218    ]);
219
220    if config_p.exists() {
221        println!("  {} Already configured.", green(CHECK));
222        println!("  {} Use {} to add more accounts.", dim("·"), cyan("shunt add-account"));
223        println!();
224        return Ok(());
225    }
226
227    // Auto-detect existing Claude Code session — no user action needed
228    let cred = match read_claude_credentials() {
229        Some(mut c) => {
230            if c.needs_refresh() {
231                print!("  {} Token expired, refreshing… ", yellow("↻"));
232                use std::io::Write;
233                std::io::stdout().flush().ok();
234                match refresh_token(&c).await {
235                    Ok(fresh) => { println!("{}", green("done")); c = fresh; }
236                    Err(e) => println!("{} ({})", yellow("failed"), dim(&e.to_string())),
237                }
238            } else {
239                println!("  {} Claude Code session found", green(CHECK));
240            }
241            c
242        }
243        None => {
244            println!("  {} No Claude Code session at {}", red(CROSS), dim(&claude_credentials_path().display().to_string()));
245            println!("  {} Run {} first, then re-run setup.", dim("·"), cyan("claude"));
246            println!();
247            bail!("No Claude Code credentials found.");
248        }
249    };
250
251    let plan = crate::oauth::read_claude_session_info()
252        .map(|s| s.plan)
253        .unwrap_or_else(|| "pro".to_string());
254    println!("  {} Plan: {}", green(CHECK), bold(&plan));
255
256    // Fetch account email (non-fatal)
257    let email = crate::oauth::fetch_account_email(&cred.access_token).await;
258    if let Some(ref e) = email {
259        println!("  {} Account: {}", green(CHECK), bold(e));
260    }
261    let mut cred = cred;
262    cred.email = email;
263
264    // Write config
265    if let Some(parent) = config_p.parent() {
266        std::fs::create_dir_all(parent)?;
267    }
268    std::fs::write(&config_p, config_template(&[("main", &plan)]))?;
269    #[cfg(unix)]
270    {
271        use std::os::unix::fs::PermissionsExt;
272        std::fs::set_permissions(&config_p, std::fs::Permissions::from_mode(0o600))?;
273    }
274
275    // Store credential
276    let mut store = CredentialsStore::default();
277    store.accounts.insert("main".into(), cred);
278    store.save()?;
279
280    println!();
281    println!("  {} Config      {}", green("→"), dim(&config_p.display().to_string()));
282    println!("  {} Credentials {}", green("→"), dim(&credentials_path().display().to_string()));
283
284    offer_shell_export()?;
285
286    println!();
287    println!("  {} Run {} to start.", green(CHECK), cyan("shunt start"));
288
289    Ok(())
290}
291
292// ---------------------------------------------------------------------------
293// add-account
294// ---------------------------------------------------------------------------
295
296async fn cmd_add_account(
297    config_override: Option<PathBuf>,
298    name_arg: Option<String>,
299    provider_arg: Option<&str>,
300) -> Result<()> {
301    use crate::provider::Provider;
302
303    let config_p = config_override.clone().unwrap_or_else(config_path);
304    if !config_p.exists() {
305        bail!("No config found. Run `shunt setup` first.");
306    }
307
308    print_splash(&[
309        format!("{}  {}", brand_green("shunt"), dim(&format!("v{}", env!("CARGO_PKG_VERSION")))),
310        "Add account".to_string(),
311        String::new(),
312    ]);
313
314    // ── Step 1: choose provider ──────────────────────────────────────────────
315    let provider = if let Some(p) = provider_arg {
316        Provider::from_str(p)
317    } else {
318        let items = vec![
319            term::SelectItem {
320                label: format!("{}  {}",
321                    bold("Claude Code"),
322                    dim("(claude.ai — Anthropic)")),
323                value: "anthropic".into(),
324            },
325            term::SelectItem {
326                label: format!("{}  {}",
327                    bold("Codex"),
328                    dim("(chatgpt.com — OpenAI)")),
329                value: "openai".into(),
330            },
331        ];
332        match term::select("Which provider?", &items, 0) {
333            Some(v) => Provider::from_str(&v),
334            None => return Ok(()),
335        }
336    };
337
338    println!();
339
340    // ── Step 2: choose name ──────────────────────────────────────────────────
341    let existing_config = std::fs::read_to_string(&config_p)?;
342    let store = CredentialsStore::load();
343
344    let (name, already_in_config) = if let Some(n) = name_arg {
345        let in_config = existing_config.contains(&format!("name = \"{n}\""));
346        let has_cred  = store.accounts.contains_key(&n);
347        let is_expired = store.accounts.get(&n).map(|c| c.needs_refresh()).unwrap_or(false);
348        let is_auth_failed = crate::state::StateStore::load(&crate::config::state_path())
349            .account_states().get(&n).map(|s| s.auth_failed).unwrap_or(false);
350        if in_config && has_cred && !is_expired && !is_auth_failed {
351            bail!("Account '{}' already has a valid credential.", n);
352        }
353        (n, in_config)
354    } else {
355        // Check for existing config entries that are missing credentials for this provider
356        let config = crate::config::load_config(config_override.as_deref())?;
357        let missing: Vec<_> = config.accounts.iter()
358            .filter(|a| a.provider == provider && a.credential.is_none())
359            .collect();
360
361        match missing.len() {
362            1 => {
363                println!("  {} Authorizing account {}", yellow("↻"), bold(&format!("'{}'", missing[0].name)));
364                println!();
365                (missing[0].name.clone(), true)
366            }
367            n if n > 1 => {
368                let items: Vec<term::SelectItem> = missing.iter().map(|a| term::SelectItem {
369                    label: bold(&a.name).to_string(),
370                    value: a.name.clone(),
371                }).collect();
372                match term::select("Which account to authorize?", &items, 0) {
373                    Some(v) => (v, true),
374                    None => return Ok(()),
375                }
376            }
377            _ => {
378                // All configured — prompt for a new name
379                print!("  {} Account name: ", dim("·"));
380                use std::io::Write;
381                std::io::stdout().flush().ok();
382                let mut input = String::new();
383                std::io::stdin().read_line(&mut input)?;
384                let n = input.trim().to_string();
385                if n.is_empty() { bail!("Account name cannot be empty."); }
386                (n, false)
387            }
388        }
389    };
390
391    // ── Step 3: OAuth flow ───────────────────────────────────────────────────
392    let mut cred = match provider {
393        Provider::Anthropic => run_oauth_flow().await?,
394        Provider::OpenAI    => crate::oauth::run_openai_oauth_flow().await?,
395    };
396
397    // Fetch email (non-fatal)
398    let email = match provider {
399        Provider::Anthropic => crate::oauth::fetch_account_email(&cred.access_token).await,
400        Provider::OpenAI    => crate::oauth::fetch_openai_account_email(&cred.access_token).await,
401    };
402    if let Some(ref e) = email {
403        println!("  {} Signed in as {}", green(CHECK), bold(e));
404    }
405    cred.email = email;
406
407    // ── Step 4: persist ──────────────────────────────────────────────────────
408    if !already_in_config {
409        let mut config_text = existing_config;
410        match provider {
411            Provider::Anthropic => config_text.push_str(&format!(
412                "\n[[accounts]]\nname = \"{name}\"\nplan_type = \"pro\"\n"
413            )),
414            Provider::OpenAI => config_text.push_str(&format!(
415                "\n[[accounts]]\nname = \"{name}\"\nplan_type = \"pro\"\nprovider = \"openai\"\n"
416            )),
417        }
418        std::fs::write(&config_p, &config_text)?;
419    }
420
421    let mut store = CredentialsStore::load();
422    store.accounts.insert(name.clone(), cred.clone());
423    store.save()?;
424
425    // Keep ~/.codex/auth.json in sync so the Codex CLI works without re-login.
426    if cred.id_token.is_some() {
427        crate::oauth::write_codex_auth_file(&cred);
428    }
429
430    println!();
431    println!("  {} Account {} added.", green(CHECK), bold(&format!("'{name}'")));
432    offer_restart(config_override).await;
433    println!();
434    Ok(())
435}
436
437// ---------------------------------------------------------------------------
438// remove-account
439// ---------------------------------------------------------------------------
440
441async fn cmd_remove_account(config_override: Option<PathBuf>, name: Option<String>) -> Result<()> {
442    let config_p = config_override.clone().unwrap_or_else(config_path);
443    if !config_p.exists() {
444        bail!("No config found. Run `shunt setup` first.");
445    }
446
447    // Resolve name — pick interactively if not given
448    let name = if let Some(n) = name {
449        n
450    } else {
451        let config = crate::config::load_config(config_override.as_deref())?;
452        let removable: Vec<_> = config.accounts.iter().collect();
453        if removable.is_empty() {
454            bail!("No accounts to remove.");
455        }
456        let items: Vec<term::SelectItem> = removable.iter().map(|a| {
457            let email = a.credential.as_ref().and_then(|c| c.email.as_deref()).unwrap_or("");
458            term::SelectItem {
459                label: format!("{}  {}", bold(&pad(&a.name, 12)), dim(&pad(email, 32))),
460                value: a.name.clone(),
461            }
462        }).collect();
463        match term::select("Remove account:", &items, 0) {
464            Some(v) => v,
465            None => return Ok(()),
466        }
467    };
468
469    let config_text = std::fs::read_to_string(&config_p)?;
470    if !config_text.contains(&format!("name = \"{name}\"")) {
471        bail!("Account '{name}' not found.");
472    }
473
474    if !term::confirm(&format!("Remove account '{name}'? This cannot be undone.")) {
475        println!("  {} Cancelled.", dim("·"));
476        println!();
477        return Ok(());
478    }
479
480    print_splash(&[
481        format!("{}  {}", brand_green("shunt"), dim(&format!("v{}", env!("CARGO_PKG_VERSION")))),
482        format!("Removing account {}", bold(&format!("'{name}'"))),
483        String::new(),
484    ]);
485
486    // Strip the [[accounts]] block for this name from config
487    let new_config = remove_account_block(&config_text, &name);
488    std::fs::write(&config_p, &new_config)?;
489    println!("  {} Removed from config", green(CHECK));
490
491    // Remove credential from store
492    let mut store = CredentialsStore::load();
493    if store.accounts.remove(&name).is_some() {
494        store.save()?;
495        println!("  {} Credential removed", green(CHECK));
496    }
497
498    println!();
499    println!("  {} Account {} removed.", green(CHECK), bold(&format!("'{name}'")));
500    offer_restart(config_override).await;
501    println!();
502    Ok(())
503}
504
505// ---------------------------------------------------------------------------
506// logout
507// ---------------------------------------------------------------------------
508
509async fn cmd_logout(config_override: Option<PathBuf>, name: Option<String>, all: bool) -> Result<()> {
510    let config_p = config_override.clone().unwrap_or_else(config_path);
511    if !config_p.exists() {
512        bail!("No config found. Run `shunt setup` first.");
513    }
514
515    let config = crate::config::load_config(config_override.as_deref())?;
516
517    // Collect account names to log out
518    let names: Vec<String> = if all {
519        config.accounts.iter()
520            .filter(|a| a.credential.is_some())
521            .map(|a| a.name.clone())
522            .collect()
523    } else if let Some(n) = name {
524        if !config.accounts.iter().any(|a| a.name == n) {
525            bail!("Account '{n}' not found.");
526        }
527        vec![n]
528    } else {
529        // Interactive picker — show only accounts that have credentials
530        let with_cred: Vec<_> = config.accounts.iter()
531            .filter(|a| a.credential.is_some())
532            .collect();
533        if with_cred.is_empty() {
534            println!("  {} No logged-in accounts.", dim("·"));
535            println!();
536            return Ok(());
537        }
538        let items: Vec<term::SelectItem> = with_cred.iter().map(|a| {
539            let email = a.credential.as_ref().and_then(|c| c.email.as_deref()).unwrap_or("");
540            term::SelectItem {
541                label: format!("{}  {}", bold(&pad(&a.name, 12)), dim(&pad(email, 32))),
542                value: a.name.clone(),
543            }
544        }).collect();
545        match term::select("Log out account:", &items, 0) {
546            Some(v) => vec![v],
547            None => return Ok(()),
548        }
549    };
550
551    if names.is_empty() {
552        println!("  {} No logged-in accounts.", dim("·"));
553        println!();
554        return Ok(());
555    }
556
557    let label = if names.len() == 1 {
558        format!("account {}", bold(&format!("'{}'", names[0])))
559    } else {
560        format!("{} accounts", bold(&names.len().to_string()))
561    };
562
563    // Reconfirm for --all or multi-account logout
564    if names.len() > 1 {
565        if !term::confirm(&format!("Log out all {} accounts? You will need to re-authorize each one.", names.len())) {
566            println!("  {} Cancelled.", dim("·"));
567            println!();
568            return Ok(());
569        }
570    }
571
572    print_splash(&[
573        format!("{}  {}", brand_green("shunt"), dim(&format!("v{}", env!("CARGO_PKG_VERSION")))),
574        format!("Logging out {label}"),
575        String::new(),
576    ]);
577
578    let mut store = CredentialsStore::load();
579
580    for name in &names {
581        // Revoke token on the server (best-effort)
582        if let Some(cred) = store.accounts.get(name) {
583            print!("  {} Revoking '{}' token… ", dim("↻"), name);
584            use std::io::Write;
585            std::io::stdout().flush().ok();
586            if revoke_token(&cred.access_token).await {
587                println!("{}", green("done"));
588            } else {
589                println!("{}", dim("(server did not confirm — cleared locally)"));
590            }
591        }
592
593        // Remove credential from local store
594        store.accounts.remove(name);
595        println!("  {} Credential for '{}' removed", green(CHECK), name);
596    }
597
598    store.save()?;
599
600    println!();
601    println!("  {} Logged out {}.", green(CHECK), label);
602    println!("  {} To re-authorize: {}", dim("·"), cyan("shunt add-account"));
603    println!();
604    Ok(())
605}
606
607/// Remove a `[[accounts]]` TOML block with the given name from config text.
608/// Uses toml_edit for correct structured editing that handles comments and edge cases.
609fn remove_account_block(config: &str, name: &str) -> String {
610    let mut doc = match config.parse::<toml_edit::DocumentMut>() {
611        Ok(d) => d,
612        Err(_) => return config.to_owned(), // unparseable — leave unchanged
613    };
614
615    if let Some(item) = doc.get_mut("accounts") {
616        if let Some(arr) = item.as_array_of_tables_mut() {
617            // Collect indices to remove in reverse order so removal doesn't shift indices
618            let to_remove: Vec<usize> = arr.iter()
619                .enumerate()
620                .filter(|(_, t)| t.get("name").and_then(|v| v.as_str()) == Some(name))
621                .map(|(i, _)| i)
622                .collect();
623            for i in to_remove.into_iter().rev() {
624                arr.remove(i);
625            }
626        }
627    }
628
629    doc.to_string()
630}
631
632#[cfg(test)]
633mod tests {
634    use super::*;
635
636    const SAMPLE_CONFIG: &str = r#"
637[server]
638port = 8082
639
640[[accounts]]
641name = "alice"
642plan_type = "pro"
643
644[[accounts]]
645name = "bob"
646plan_type = "max"
647
648[[accounts]]
649name = "charlie"
650plan_type = "pro"
651"#;
652
653    #[test]
654    fn test_remove_account_block_removes_target() {
655        let result = remove_account_block(SAMPLE_CONFIG, "bob");
656        // bob must be gone
657        assert!(!result.contains("\"bob\"") && !result.contains("'bob'") && !result.contains("bob"),
658            "removed account must not appear: {result}");
659        // others must remain
660        assert!(result.contains("alice"));
661        assert!(result.contains("charlie"));
662    }
663
664    #[test]
665    fn test_remove_account_block_preserves_others() {
666        let result = remove_account_block(SAMPLE_CONFIG, "alice");
667        assert!(!result.contains("alice"), "alice must be removed");
668        assert!(result.contains("bob"),     "bob must remain");
669        assert!(result.contains("charlie"), "charlie must remain");
670    }
671
672    #[test]
673    fn test_remove_account_block_noop_when_not_found() {
674        let result = remove_account_block(SAMPLE_CONFIG, "dave");
675        // All three must still be present
676        assert!(result.contains("alice"));
677        assert!(result.contains("bob"));
678        assert!(result.contains("charlie"));
679    }
680
681    #[test]
682    fn test_remove_account_block_last_account() {
683        let cfg = "[[accounts]]\nname = \"only\"\nplan_type = \"pro\"\n";
684        let result = remove_account_block(cfg, "only");
685        assert!(!result.contains("only"), "sole account must be removed");
686    }
687
688    #[test]
689    fn test_remove_account_block_handles_unparseable_input() {
690        let bad = "not valid [[toml{{ garbage";
691        let result = remove_account_block(bad, "anything");
692        // Must return input unchanged, not panic
693        assert_eq!(result, bad);
694    }
695
696    #[test]
697    fn test_remove_account_block_with_inline_comment() {
698        let cfg = "[[accounts]]\nname = \"alice\" # main account\nplan_type = \"pro\"\n\n[[accounts]]\nname = \"bob\"\nplan_type = \"max\"\n";
699        let result = remove_account_block(cfg, "alice");
700        assert!(!result.contains("alice"));
701        assert!(result.contains("bob"));
702    }
703}
704
705// ---------------------------------------------------------------------------
706// start
707// ---------------------------------------------------------------------------
708
709async fn cmd_start(
710    config_override: Option<PathBuf>,
711    host_override: Option<String>,
712    port_override: Option<u16>,
713    foreground: bool,
714    verbose: bool,
715    daemon: bool,
716) -> Result<()> {
717    let config_p = config_override.clone().unwrap_or_else(config_path);
718
719    // ── Daemon mode: internal re-exec, no user output ────────────────────────
720    if daemon {
721        if !config_p.exists() { return Ok(()); }
722        let mut config = crate::config::load_config(config_override.as_deref())?;
723        let host = host_override.unwrap_or_else(|| config.server.host.clone());
724        let port = port_override.unwrap_or(config.server.port);
725
726        for account in &mut config.accounts {
727            if let Some(cred) = &account.credential {
728                if cred.needs_refresh() {
729                    if let Ok(Ok(fresh)) = tokio::time::timeout(
730                        std::time::Duration::from_secs(10),
731                        account.provider.refresh_token(cred),
732                    ).await {
733                        let mut store = CredentialsStore::load();
734                        store.accounts.insert(account.name.clone(), fresh.clone());
735                        store.save().ok();
736                        account.credential = Some(fresh);
737                    }
738                }
739            }
740        }
741
742        let lp = log_path();
743        let log_level = if verbose { "debug" } else { config.server.log_level.as_str() };
744        crate::logging::prune_old_logs(&lp, 7);
745        let _log_guard = crate::logging::setup(&lp, log_level)?;
746        let state = crate::state::StateStore::load(&crate::config::state_path());
747        write_pid();
748        serve_all_providers(config, state, &host, port).await?;
749        return Ok(());
750    }
751
752    // ── Auto-setup on first run ───────────────────────────────────────────────
753    if !config_p.exists() {
754        cmd_setup_auto(config_override.clone()).await?;
755    }
756
757    let config = crate::config::load_config(config_override.as_deref())?;
758    let host = host_override.clone().unwrap_or_else(|| config.server.host.clone());
759    let port = port_override.unwrap_or(config.server.port);
760
761    // Kill any previous instance on this port
762    for pid in port_pids(port) {
763        let _ = std::process::Command::new("kill").arg(pid.to_string()).status();
764    }
765    if !port_pids(port).is_empty() {
766        std::thread::sleep(std::time::Duration::from_millis(400));
767    }
768
769    // ── Foreground mode (debugging) ───────────────────────────────────────────
770    if foreground {
771        use std::io::Write as _;
772        let mut config = config;
773        let account_names: Vec<&str> = config.accounts.iter().map(|a| a.name.as_str()).collect();
774        print_routing_header(&account_names, &[
775            format!("{}  {}", brand_green("shunt"), dim(&format!("v{}", env!("CARGO_PKG_VERSION")))),
776            dim("foreground").to_string(),
777        ]);
778        for account in &mut config.accounts {
779            if let Some(cred) = &account.credential {
780                if cred.needs_refresh() {
781                    print!("  {} Refreshing '{}'… ", yellow("↻"), account.name);
782                    std::io::stdout().flush().ok();
783                    match tokio::time::timeout(
784                        std::time::Duration::from_secs(10),
785                        account.provider.refresh_token(cred),
786                    ).await {
787                        Ok(Ok(fresh)) => {
788                            println!("{}", green("done"));
789                            let mut store = CredentialsStore::load();
790                            store.accounts.insert(account.name.clone(), fresh.clone());
791                            store.save().ok();
792                            account.credential = Some(fresh);
793                        }
794                        Ok(Err(e)) => println!("{}", yellow(&format!("failed ({})", e))),
795                        Err(_)    => println!("{}", yellow("timed out")),
796                    }
797                }
798            }
799        }
800        let lp = log_path();
801        let log_level = if verbose { "debug" } else { config.server.log_level.as_str() };
802        crate::logging::prune_old_logs(&lp, 7);
803        let _log_guard = crate::logging::setup(&lp, log_level)?;
804        let col = 13usize;
805        for (p, addr) in listener_addrs(&config.accounts, &host, port) {
806            println!("  {}  {} {}", dim(&pad("listening", col)), dim(&format!("[{p}]")), green_bold(&addr));
807        }
808        println!("  {}  {}", dim(&pad("logs", col)), dim(&lp.display().to_string()));
809        println!();
810        let state = crate::state::StateStore::load(&crate::config::state_path());
811        write_pid();
812        serve_all_providers(config, state, &host, port).await?;
813        return Ok(());
814    }
815
816    // ── Background mode (default) ─────────────────────────────────────────────
817    let exe = std::env::current_exe().context("cannot locate current executable")?;
818    let mut cmd = std::process::Command::new(&exe);
819    cmd.arg("start").arg("--daemon");
820    if let Some(ref p) = config_override { cmd.args(["--config", &p.display().to_string()]); }
821    if let Some(ref h) = host_override   { cmd.args(["--host", h]); }
822    if let Some(p) = port_override       { cmd.args(["--port", &p.to_string()]); }
823    if verbose                           { cmd.arg("--verbose"); }
824    cmd.stdin(std::process::Stdio::null())
825       .stdout(std::process::Stdio::null())
826       .stderr(std::process::Stdio::null())
827       .spawn()
828       .context("failed to start proxy in background")?;
829
830    // Wait until the proxy is accepting connections (up to 8 s)
831    let ready = wait_for_health(&host, port, 8).await;
832
833    // Auto-write ANTHROPIC_BASE_URL to shell profile (silent if already there)
834    auto_write_shell_export(port);
835
836    let account_names: Vec<&str> = config.accounts.iter().map(|a| a.name.as_str()).collect();
837    let status_line = if ready {
838        format!("{}  {}  {}", green(DOT), green_bold("running"), cyan(&format!("http://{host}:{port}")))
839    } else {
840        format!("{}  {}  {}", yellow(DOT), yellow("starting"), dim(&format!("http://{host}:{port}")))
841    };
842    print_routing_header(&account_names, &[
843        format!("{}  {}", brand_green("shunt"), dim(&format!("v{}", env!("CARGO_PKG_VERSION")))),
844        status_line,
845    ]);
846
847    Ok(())
848}
849
850// ---------------------------------------------------------------------------
851// stop
852// ---------------------------------------------------------------------------
853
854async fn cmd_stop() -> Result<()> {
855    let pid_p = pid_path();
856    let content = match std::fs::read_to_string(&pid_p) {
857        Ok(c) => c,
858        Err(_) => {
859            println!("  {} Proxy is not running.", dim("·"));
860            println!();
861            return Ok(());
862        }
863    };
864    let pid = match content.trim().parse::<u32>() {
865        Ok(p) => p,
866        Err(_) => {
867            let _ = std::fs::remove_file(&pid_p);
868            println!("  {} Proxy is not running.", dim("·"));
869            println!();
870            return Ok(());
871        }
872    };
873    if !is_shunt_pid(pid) {
874        let _ = std::fs::remove_file(&pid_p);
875        println!("  {} Proxy is not running.", dim("·"));
876        println!();
877        return Ok(());
878    }
879
880    // SIGTERM — let axum drain connections cleanly
881    unsafe { libc::kill(pid as i32, libc::SIGTERM) };
882
883    // Wait up to 3 s for clean exit, then SIGKILL
884    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(3);
885    while std::time::Instant::now() < deadline {
886        std::thread::sleep(std::time::Duration::from_millis(100));
887        if !is_shunt_pid(pid) { break; }
888    }
889    if is_shunt_pid(pid) {
890        unsafe { libc::kill(pid as i32, libc::SIGKILL) };
891        std::thread::sleep(std::time::Duration::from_millis(200));
892    }
893
894    let _ = std::fs::remove_file(&pid_p);
895    println!("  {} Proxy stopped.", green(CHECK));
896    println!();
897    Ok(())
898}
899
900fn is_shunt_pid(pid: u32) -> bool {
901    let Ok(out) = std::process::Command::new("ps")
902        .args(["-p", &pid.to_string(), "-o", "comm="])
903        .output()
904    else { return false };
905    String::from_utf8_lossy(&out.stdout).trim().contains("shunt")
906}
907
908// ---------------------------------------------------------------------------
909// restart
910// ---------------------------------------------------------------------------
911
912async fn cmd_restart(config_override: Option<PathBuf>) -> Result<()> {
913    cmd_stop().await?;
914    tokio::time::sleep(std::time::Duration::from_millis(300)).await;
915    cmd_start(config_override, None, None, false, false, false).await
916}
917
918// ---------------------------------------------------------------------------
919// logs
920// ---------------------------------------------------------------------------
921
922async fn cmd_logs(_config_override: Option<PathBuf>, follow: bool, lines: usize) -> Result<()> {
923    use std::io::{BufRead, BufReader, Write};
924
925    let log = log_path();
926    if !log.exists() {
927        println!("  {} No log file found.", dim("·"));
928        println!("  {} Start the proxy first: {}", dim("·"), cyan("shunt start"));
929        println!();
930        return Ok(());
931    }
932
933    let file = std::fs::File::open(&log)?;
934    let mut reader = BufReader::new(file);
935
936    // Use a ring buffer so we only keep the last N lines in memory
937    // regardless of how large the log file is.
938    let mut ring: std::collections::VecDeque<String> = std::collections::VecDeque::with_capacity(lines + 1);
939    let mut line = String::new();
940    while reader.read_line(&mut line)? > 0 {
941        if ring.len() >= lines {
942            ring.pop_front();
943        }
944        ring.push_back(std::mem::take(&mut line));
945    }
946    for l in &ring {
947        print!("{l}");
948    }
949    std::io::stdout().flush().ok();
950
951    if !follow {
952        return Ok(());
953    }
954
955    // Follow mode — poll for new content
956    eprintln!("{}", dim("--- following (Ctrl+C to stop) ---"));
957    loop {
958        line.clear();
959        if reader.read_line(&mut line)? > 0 {
960            print!("{line}");
961            std::io::stdout().flush().ok();
962        } else {
963            tokio::time::sleep(std::time::Duration::from_millis(200)).await;
964        }
965    }
966}
967
968
969/// Non-interactive setup called from `cmd_start`.
970/// Imports the existing Claude Code session silently.
971/// The only user interaction is the OAuth code paste if no session exists.
972async fn cmd_setup_auto(config_override: Option<PathBuf>) -> Result<()> {
973    let config_p = config_override.clone().unwrap_or_else(config_path);
974
975    let mut cred = match crate::oauth::read_claude_credentials() {
976        Some(mut c) => {
977            if c.needs_refresh() {
978                if let Ok(fresh) = refresh_token(&c).await { c = fresh; }
979            }
980            c
981        }
982        None => {
983            // No session on disk — run the full OAuth flow (user pastes code)
984            println!("  {} No Claude Code session found — opening browser for login…", yellow("·"));
985            crate::oauth::run_oauth_flow().await?
986        }
987    };
988
989    let plan = crate::oauth::read_claude_session_info()
990        .map(|s| s.plan)
991        .unwrap_or_else(|| "pro".to_string());
992
993    cred.email = crate::oauth::fetch_account_email(&cred.access_token).await;
994
995    if let Some(parent) = config_p.parent() { std::fs::create_dir_all(parent)?; }
996    std::fs::write(&config_p, crate::config::config_template(&[("main", &plan)]))?;
997    #[cfg(unix)] {
998        use std::os::unix::fs::PermissionsExt;
999        std::fs::set_permissions(&config_p, std::fs::Permissions::from_mode(0o600))?;
1000    }
1001
1002    let mut store = CredentialsStore::default();
1003    store.accounts.insert("main".into(), cred);
1004    store.save()?;
1005
1006    Ok(())
1007}
1008
1009async fn wait_for_health(host: &str, port: u16, timeout_secs: u64) -> bool {
1010    let url = format!("http://{host}:{port}/health");
1011    let deadline = tokio::time::Instant::now()
1012        + std::time::Duration::from_secs(timeout_secs);
1013    while tokio::time::Instant::now() < deadline {
1014        if reqwest::get(&url).await.map(|r| r.status().is_success()).unwrap_or(false) {
1015            return true;
1016        }
1017        tokio::time::sleep(std::time::Duration::from_millis(200)).await;
1018    }
1019    false
1020}
1021
1022fn auto_write_shell_export(port: u16) {
1023    use std::io::Write;
1024    let line = format!("export ANTHROPIC_BASE_URL=http://127.0.0.1:{port}");
1025    let Some(profile) = detect_shell_profile() else { return };
1026
1027    if profile.exists() {
1028        if let Ok(contents) = std::fs::read_to_string(&profile) {
1029            if contents.contains(&line) {
1030                // Already exactly correct — nothing to do.
1031                return;
1032            }
1033            if contents.contains("ANTHROPIC_BASE_URL=http://127.0.0.1:") {
1034                // Has the variable but with a different port — update it in-place.
1035                let updated: String = contents
1036                    .lines()
1037                    .map(|l| {
1038                        if l.contains("ANTHROPIC_BASE_URL=http://127.0.0.1:") {
1039                            line.as_str()
1040                        } else {
1041                            l
1042                        }
1043                    })
1044                    .collect::<Vec<_>>()
1045                    .join("\n")
1046                    + "\n";
1047                if std::fs::write(&profile, updated).is_ok() {
1048                    println!("  {} {} updated to port {}  → {}",
1049                        green(CHECK), cyan("ANTHROPIC_BASE_URL"), port,
1050                        dim(&profile.display().to_string()));
1051                }
1052                return;
1053            }
1054            if contents.contains("ANTHROPIC_BASE_URL") {
1055                // Set to something else (e.g. remote URL) — leave it alone.
1056                return;
1057            }
1058        }
1059    }
1060
1061    if let Ok(mut f) = std::fs::OpenOptions::new().create(true).append(true).open(&profile) {
1062        writeln!(f, "\n# Added by shunt").ok();
1063        writeln!(f, "{line}").ok();
1064        println!("  {} {} → {}",
1065            green(CHECK), cyan("ANTHROPIC_BASE_URL"),
1066            dim(&profile.display().to_string()));
1067    }
1068}
1069
1070// ---------------------------------------------------------------------------
1071// status
1072// ---------------------------------------------------------------------------
1073
1074async fn cmd_status(config_override: Option<PathBuf>) -> Result<()> {
1075    let mut config = crate::config::load_config(config_override.as_deref())?;
1076    let _primary_url = format!("http://{}:{}", config.server.host, config.server.port);
1077
1078    // Fetch live status from every provider's proxy (each runs on its own port).
1079    // provider_label → serde_json::Value
1080    let provider_urls = listener_addrs(&config.accounts, &config.server.host, config.server.port);
1081    let mut live_by_provider: std::collections::HashMap<String, serde_json::Value> =
1082        std::collections::HashMap::new();
1083    for (label, url) in &provider_urls {
1084        if let Some(v) = reqwest::get(format!("{url}/status")).await.ok()
1085            .and_then(|r| futures_executor_hack(r))
1086        {
1087            live_by_provider.insert(label.clone(), v);
1088        }
1089    }
1090
1091    // Primary proxy (Anthropic) drives the overall running/stopped display.
1092    let live: Option<&serde_json::Value> = live_by_provider
1093        .get(&crate::provider::Provider::Anthropic.to_string())
1094        .or_else(|| live_by_provider.values().next());
1095
1096    // Back-fill missing emails (existing accounts set up before email support).
1097    // Fetch in parallel, persist any that are new.
1098    let mut store_dirty = false;
1099    let mut store = CredentialsStore::load();
1100    for acc in &mut config.accounts {
1101        if acc.credential.as_ref().map(|c| c.email.is_none()).unwrap_or(false) {
1102            let token = acc.credential.as_ref().map(|c| c.access_token.clone()).unwrap_or_default();
1103            if let Some(email) = crate::oauth::fetch_account_email(&token).await {
1104                if let Some(c) = acc.credential.as_mut() { c.email = Some(email.clone()); }
1105                if let Some(stored) = store.accounts.get_mut(&acc.name) {
1106                    stored.email = Some(email);
1107                    store_dirty = true;
1108                }
1109            }
1110        }
1111    }
1112    if store_dirty {
1113        store.save().ok();
1114    }
1115
1116    // Build running address list: ":8082" or ":8082 · :8083"
1117    let addr_str = if !live_by_provider.is_empty() {
1118        let parts: Vec<String> = provider_urls.iter()
1119            .filter(|(label, _)| live_by_provider.contains_key(label.as_str()))
1120            .map(|(_, url)| {
1121                let port = url.rsplit(':').next().unwrap_or("?");
1122                cyan(&format!(":{port}"))
1123            })
1124            .collect();
1125        parts.join(&dim("  ·  "))
1126    } else {
1127        String::new()
1128    };
1129
1130    let proxy_line = if live.is_some() {
1131        format!("{}  {}  {}", green(DOT), green_bold("running"), addr_str)
1132    } else {
1133        let log_hint = if log_path().exists() {
1134            format!("  {}  {}", dim("·"), dim("shunt logs for details"))
1135        } else {
1136            String::new()
1137        };
1138        format!("{}  {}  {}{}", dim(EMPTY), dim("stopped"), dim("shunt start"), log_hint)
1139    };
1140
1141    let account_names: Vec<&str> = config.accounts.iter().map(|a| a.name.as_str()).collect();
1142    // Build savings summary if proxy is running and has data.
1143    let savings_line: Option<String> = live.and_then(|v| {
1144        let s = v.get("savings")?;
1145        let today_in  = s["today_input"].as_u64().unwrap_or(0);
1146        let today_out = s["today_output"].as_u64().unwrap_or(0);
1147        let today_cost = s["today_cost_usd"].as_f64().unwrap_or(0.0);
1148        let all_cost   = s["all_time_cost_usd"].as_f64().unwrap_or(0.0);
1149        if today_in + today_out == 0 && all_cost == 0.0 { return None; }
1150        let today_tok = crate::term::fmt_tokens(today_in + today_out);
1151        let cost_str  = crate::pricing::fmt_cost(today_cost);
1152        let all_str   = crate::pricing::fmt_cost(all_cost);
1153        Some(format!("{}  today {}  {}  {}  all time {}",
1154            dim("·"), dim(&today_tok), dim(&cost_str), dim("·"), dim(&all_str)))
1155    });
1156
1157    print_routing_header(&account_names, &[
1158        format!("{}  {}", brand_green("shunt"), dim(&format!("v{}", env!("CARGO_PKG_VERSION")))),
1159        proxy_line,
1160    ]);
1161
1162    if let Some(ref line) = savings_line {
1163        println!("  {line}");
1164        println!();
1165    }
1166
1167    let pinned_account = live.and_then(|v| v["pinned"].as_str()).map(|s| s.to_owned());
1168    let last_used_account = live.and_then(|v| v["last_used"].as_str()).map(|s| s.to_owned());
1169
1170    // Pinned notice
1171    if let Some(ref pinned) = pinned_account {
1172        println!("  {}  pinned to {}",
1173            yellow(DIAMOND), bold(pinned));
1174        println!("  {}  run {} to restore auto routing",
1175            dim("·"), cyan("shunt use auto"));
1176        println!();
1177    }
1178
1179    let now_secs = SystemTime::now().duration_since(UNIX_EPOCH).ok().map(|d| d.as_secs()).unwrap_or(0);
1180
1181    for acc in &config.accounts {
1182        let live_acc = live_by_provider.get(&acc.provider.to_string())
1183            .and_then(|v| v["accounts"].as_array())
1184            .and_then(|arr| arr.iter().find(|a| a["name"] == acc.name));
1185
1186        let status = live_acc.and_then(|a| a["status"].as_str()).unwrap_or("offline");
1187
1188        let (status_icon, status_text): (String, String) = match status {
1189            "available"       => (green(CHECK), green("available")),
1190            "cooling"         => (yellow("↻"),  yellow("cooling")),
1191            "disabled"        => (red(CROSS),   red("disabled")),
1192            "reauth_required" => (red(CROSS),   red("session expired")),
1193            _ => match &acc.credential {
1194                None                          => (red(CROSS),   red("no credential")),
1195                Some(c) if c.needs_refresh()  => (yellow(CROSS), yellow("token expired")),
1196                _                             => (dim(EMPTY),   dim("offline")),
1197            },
1198        };
1199
1200        let plan_label = if acc.provider == crate::provider::Provider::OpenAI {
1201            match acc.plan_type.to_lowercase().as_str() {
1202                "plus"  => "ChatGPT Plus",
1203                "pro"   => "ChatGPT Pro",
1204                "team"  => "ChatGPT Team",
1205                _       => "ChatGPT",
1206            }
1207        } else {
1208            match acc.plan_type.to_lowercase().as_str() {
1209                "max" | "claude_max" => "Claude Max",
1210                "team"               => "Claude Team",
1211                _                    => "Claude Pro",
1212            }
1213        };
1214        let email_str = acc.credential.as_ref().and_then(|c| c.email.as_deref()).unwrap_or("");
1215
1216        // ── routing tag ─────────────────────────────────────
1217        let is_pinned  = pinned_account.as_deref() == Some(&acc.name);
1218        let is_last    = !is_pinned && last_used_account.as_deref() == Some(&acc.name);
1219        let (routing_tag, tag_vis_len): (String, usize) = if is_pinned {
1220            (format!("  {}", yellow("pinned")), 8)
1221        } else if is_last {
1222            (format!("  {}", green("active")), 8)
1223        } else {
1224            (String::new(), 0)
1225        };
1226
1227        // ── account header (name + tag + plan) ──────────────
1228        println!("{}", card_header(&acc.name, &green_bold(&acc.name), &routing_tag, tag_vis_len, plan_label));
1229
1230        // ── email + provider badge row ───────────────────────
1231        let is_openai = acc.provider == crate::provider::Provider::OpenAI;
1232        let provider_badge = if is_openai { format!("  {}  {}", dim("·"), dim("openai")) } else { String::new() };
1233        if !email_str.is_empty() {
1234            println!("{}", card_row(&format!("{}{}", dim(email_str), provider_badge)));
1235        } else if is_openai {
1236            println!("{}", card_row(&dim("openai")));
1237        }
1238
1239        println!();
1240
1241        // ── status ───────────────────────────────────────────
1242        println!("{}", card_row(&format!("{}  {}", status_icon, status_text)));
1243
1244        // ── rate limit bars ──────────────────────────────────
1245        if let Some(rl) = live_acc.and_then(|a| a["rate_limit"].as_object()) {
1246            let util_5h   = rl.get("utilization_5h").and_then(|v| v.as_f64());
1247            let reset_5h  = rl.get("reset_5h").and_then(|v| v.as_u64());
1248            let status_5h = rl.get("status_5h").and_then(|v| v.as_str()).unwrap_or("allowed");
1249            let util_7d   = rl.get("utilization_7d").and_then(|v| v.as_f64());
1250            let reset_7d  = rl.get("reset_7d").and_then(|v| v.as_u64());
1251            let status_7d = rl.get("status_7d").and_then(|v| v.as_str()).unwrap_or("allowed");
1252
1253            let window_row = |label: &str, util: Option<f64>, reset: Option<u64>, wstatus: &str| {
1254                if reset.map(|t| t <= now_secs).unwrap_or(false) {
1255                    let ago = reset.map(|t| format!(
1256                        "  {} ago", term::fmt_duration_ms(now_secs.saturating_sub(t) * 1000)
1257                    )).unwrap_or_default();
1258                    println!("{}", card_row(&format!(
1259                        "{}  {}  {}{}",
1260                        dim(label), green(&"─".repeat(20)), green("fresh"), dim(&ago)
1261                    )));
1262                } else if let Some(u) = util {
1263                    let rem = 100u64.saturating_sub((u * 100.0) as u64);
1264                    let bar = util_bar(u, 20);
1265                    let reset_str = reset.and_then(|t| secs_until(t))
1266                        .map(|s| format!("  ·  resets in {}", term::fmt_duration_ms(s * 1000)))
1267                        .unwrap_or_default();
1268                    let pct = if wstatus == "exhausted" {
1269                        red("exhausted")
1270                    } else {
1271                        format!("{}% left", bold(&rem.to_string()))
1272                    };
1273                    println!("{}", card_row(&format!(
1274                        "{}  {}  {}{}",
1275                        dim(label), bar, pct, dim(&reset_str)
1276                    )));
1277                }
1278            };
1279
1280            if util_5h.is_some() || reset_5h.is_some() {
1281                window_row("5h", util_5h, reset_5h, status_5h);
1282            }
1283            if util_7d.is_some() || reset_7d.is_some() {
1284                window_row("7d", util_7d, reset_7d, status_7d);
1285            }
1286        } else if acc.credential.is_none() {
1287            println!("{}", card_row(&format!("{}  run {}",
1288                dim("·"), cyan(&format!("shunt add-account {}", acc.name)))));
1289        } else if status == "reauth_required" {
1290            println!("{}", card_row(&format!("{}  run {}",
1291                dim("·"), cyan(&format!("shunt add-account {}", acc.name)))));
1292        } else if live.is_some() && live_acc.is_some() {
1293            if acc.provider == crate::provider::Provider::Anthropic {
1294                println!("{}", card_row(&dim("· quota data will appear after first request")));
1295            } else {
1296                println!("{}", card_row(&dim("· quota tracking unavailable (OpenAI doesn't report utilization)")));
1297            }
1298        }
1299
1300        // ── separator ────────────────────────────────────────
1301        println!();
1302        println!("{}", card_sep());
1303        println!();
1304    }
1305
1306    Ok(())
1307}
1308
1309// ---------------------------------------------------------------------------
1310// use (pin account)
1311// ---------------------------------------------------------------------------
1312
1313async fn cmd_use(config_override: Option<PathBuf>, account: Option<String>) -> Result<()> {
1314    let config = crate::config::load_config(config_override.as_deref())?;
1315    let use_url = format!("http://{}:{}/use", config.server.host, config.server.port);
1316
1317    // Fetch live state for utilization info
1318    let live: Option<serde_json::Value> = reqwest::get(
1319        &format!("http://{}:{}/status", config.server.host, config.server.port)
1320    ).await.ok().and_then(|r| futures_executor_hack(r));
1321
1322    let current_pinned = live.as_ref()
1323        .and_then(|v| v["pinned"].as_str())
1324        .map(|s| s.to_owned());
1325
1326    // Build menu items
1327    let mut items: Vec<term::SelectItem> = config.accounts.iter().map(|a| {
1328        let live_acc = live.as_ref()
1329            .and_then(|v| v["accounts"].as_array())
1330            .and_then(|arr| arr.iter().find(|x| x["name"] == a.name));
1331
1332        let status = live_acc.and_then(|x| x["status"].as_str()).unwrap_or("offline");
1333        let util = live_acc.and_then(|x| x["rate_limit"]["utilization_5h"].as_f64());
1334        let is_pinned = current_pinned.as_deref() == Some(&a.name);
1335
1336        let status_str = match status {
1337            "reauth_required" => red("session expired"),
1338            "disabled"        => red("disabled"),
1339            "cooling"         => yellow("cooling"),
1340            "available"       => {
1341                match util {
1342                    Some(u) => {
1343                        let rem = 100u64.saturating_sub((u * 100.0) as u64);
1344                        green(&format!("{}% remaining", rem))
1345                    }
1346                    None => dim("fresh").to_string(),
1347                }
1348            }
1349            _ => dim("offline").to_string(),
1350        };
1351
1352        let email = a.credential.as_ref().and_then(|c| c.email.as_deref()).unwrap_or("");
1353        let pin = if is_pinned { format!("  {}", yellow("pinned")) } else { String::new() };
1354
1355        term::SelectItem {
1356            label: format!("{}  {}  {}{}", bold(&pad(&a.name, 12)), dim(&pad(email, 32)), status_str, pin),
1357            value: a.name.clone(),
1358        }
1359    }).collect();
1360
1361    let auto_marker = if current_pinned.is_none() { format!("  {}", yellow("active")) } else { String::new() };
1362    items.push(term::SelectItem {
1363        label: format!("{}  {}{}", bold(&pad("auto", 12)), dim("least-utilization routing"), auto_marker),
1364        value: "auto".to_owned(),
1365    });
1366
1367    // Determine initial cursor position (current pinned account or auto)
1368    let initial = current_pinned.as_ref()
1369        .and_then(|p| items.iter().position(|it| &it.value == p))
1370        .unwrap_or(items.len() - 1);
1371
1372    // If account name was given directly, skip the picker
1373    let chosen = if let Some(name) = account {
1374        name
1375    } else {
1376        match term::select("Route traffic to:", &items, initial) {
1377            Some(v) => v,
1378            None => return Ok(()), // cancelled
1379        }
1380    };
1381
1382    // Validate
1383    let is_auto = chosen == "auto";
1384    if !is_auto && !config.accounts.iter().any(|a| a.name == chosen) {
1385        let names: Vec<_> = config.accounts.iter().map(|a| a.name.as_str()).collect();
1386        anyhow::bail!("Unknown account '{}'. Available: {}", chosen, names.join(", "));
1387    }
1388
1389    let client = reqwest::Client::new();
1390    let resp = client
1391        .post(&use_url)
1392        .json(&serde_json::json!({ "account": chosen }))
1393        .send()
1394        .await;
1395
1396    match resp {
1397        Ok(r) if r.status().is_success() => {
1398            if is_auto {
1399                println!("  {} Automatic routing restored", green(CHECK));
1400            } else {
1401                println!("  {} Pinned to {}  ·  {}", green(CHECK), bold(&chosen), dim("shunt use auto to restore"));
1402            }
1403            println!();
1404        }
1405        Ok(r) => {
1406            let body = r.text().await.unwrap_or_default();
1407            anyhow::bail!("Proxy returned error: {body}");
1408        }
1409        Err(_) => {
1410            // Proxy not running — persist directly to the state file so it
1411            // takes effect when the proxy next starts.
1412            write_pinned_to_state(if is_auto { None } else { Some(chosen.clone()) });
1413            if is_auto {
1414                println!("  {} Automatic routing saved  ·  {}", green(CHECK),
1415                    dim("applies on next shunt start"));
1416            } else {
1417                println!("  {} Pinned to {}  ·  {}", green(CHECK), bold(&chosen),
1418                    dim("applies on next shunt start"));
1419            }
1420            println!();
1421        }
1422    }
1423    Ok(())
1424}
1425
1426/// Write a pinned account directly into the state file (used when proxy is not running).
1427fn write_pinned_to_state(account: Option<String>) {
1428    let path = crate::config::state_path();
1429    let mut data: serde_json::Value = path.exists()
1430        .then(|| std::fs::read_to_string(&path).ok())
1431        .flatten()
1432        .and_then(|t| serde_json::from_str(&t).ok())
1433        .unwrap_or_else(|| serde_json::json!({}));
1434    data["pinned_account"] = match account {
1435        Some(a) => serde_json::Value::String(a),
1436        None => serde_json::Value::Null,
1437    };
1438    if let Some(parent) = path.parent() { let _ = std::fs::create_dir_all(parent); }
1439    let tmp = path.with_extension("tmp");
1440    if let Ok(text) = serde_json::to_string_pretty(&data) {
1441        let _ = std::fs::write(&tmp, text);
1442        let _ = std::fs::rename(&tmp, &path);
1443    }
1444}
1445
1446/// Synchronously awaits a reqwest response to get its JSON.
1447fn futures_executor_hack(resp: reqwest::Response) -> Option<serde_json::Value> {
1448    tokio::task::block_in_place(|| {
1449        tokio::runtime::Handle::current().block_on(async {
1450            resp.json::<serde_json::Value>().await.ok()
1451        })
1452    })
1453}
1454
1455// ---------------------------------------------------------------------------
1456// Helpers
1457// ---------------------------------------------------------------------------
1458
1459/// Circuit shunt symbol: rectangle with wires extending left/right from the mid row,
1460/// and two legs going down from the bottom.
1461///
1462///   ·  ██████  ·
1463///   ███      ███   ← wire row (middle of box)
1464///   ·  ██████  ·
1465///   ·    █ █   ·   ← legs
1466fn build_logo_lines(h: usize, w: usize) -> Vec<String> {
1467    if h == 0 || w < 5 { return vec![]; }
1468
1469    let box_l = w / 4;
1470    let box_r = w - w / 4;  // exclusive
1471    let leg_h = (h / 4).max(1);
1472    let box_h = h.saturating_sub(leg_h).max(2); // at least top + bottom row
1473    let wire_row = box_h / 2; // wire connects at vertical mid of box
1474
1475    // Mirror from each side so legs are symmetric around centre.
1476    let leg1 = w / 3;
1477    let leg2 = w - w / 3 - 1;
1478
1479    let mut out = Vec::new();
1480    for row in 0..h {
1481        let mut r = vec![' '; w];
1482        if row < box_h {
1483            let is_top = row == 0;
1484            let is_bot = row == box_h - 1;
1485            if is_top || is_bot {
1486                for j in box_l..box_r { r[j] = '█'; }
1487            } else {
1488                r[box_l]     = '█';
1489                r[box_r - 1] = '█';
1490            }
1491            if row == wire_row {
1492                for j in 0..box_l  { r[j] = '█'; }
1493                for j in box_r..w  { r[j] = '█'; }
1494            }
1495        } else {
1496            if leg1 < w { r[leg1] = '█'; }
1497            if leg2 < w { r[leg2] = '█'; }
1498        }
1499        out.push(r.into_iter().collect());
1500    }
1501    out
1502}
1503
1504fn render_splash_frame(
1505    f: &mut ratatui::Frame,
1506    title_raw: &str,
1507    subtitle_raw: &str,
1508) {
1509    use ratatui::{
1510        layout::{Constraint, Direction, Layout},
1511        style::{Color, Style},
1512        text::Line,
1513        widgets::{Block, Borders, Paragraph},
1514    };
1515
1516    let brand   = Color::Rgb(188, 255, 96);  // #bcff60
1517    let dim_col = Color::Rgb(100, 160, 40);  // #bcff60 dimmed
1518
1519    // Fixed-width box — does not stretch to fill the terminal.
1520    const BOX_W: u16 = 70;
1521    let full = f.area();
1522    let area = Layout::new(Direction::Horizontal, [
1523        Constraint::Length(BOX_W.min(full.width)),
1524        Constraint::Fill(1),
1525    ]).split(full)[0];
1526
1527    // Outer bordered box.
1528    let outer = Block::default()
1529        .borders(Borders::ALL)
1530        .border_style(Style::default().fg(brand))
1531        .title(Line::styled(format!(" {title_raw} "), Style::default().fg(brand)));
1532    let inner = outer.inner(area);
1533    f.render_widget(outer, area);
1534
1535    const CONTENT_H: u16 = 4;
1536    const LOGO_W:    u16 = 10;
1537
1538    // Main horizontal split: left half | separator | right half
1539    let cols = Layout::new(Direction::Horizontal, [
1540        Constraint::Fill(1),
1541        Constraint::Length(1),
1542        Constraint::Fill(1),
1543    ]).split(inner);
1544    let (left_area, sep_area, right_area) = (cols[0], cols[1], cols[2]);
1545
1546    // Left: vertical centering around the content row.
1547    let has_sub = !subtitle_raw.is_empty();
1548    let left_v_constraints: Vec<Constraint> = if has_sub {
1549        vec![Constraint::Fill(1), Constraint::Length(CONTENT_H), Constraint::Fill(1), Constraint::Length(1)]
1550    } else {
1551        vec![Constraint::Fill(1), Constraint::Length(CONTENT_H), Constraint::Fill(1)]
1552    };
1553    let left_v = Layout::new(Direction::Vertical, left_v_constraints).split(left_area);
1554    let content_row = left_v[1];
1555
1556    // Left content: logo centered horizontally within the left half
1557    let h = Layout::new(Direction::Horizontal, [
1558        Constraint::Fill(1),
1559        Constraint::Length(LOGO_W),
1560        Constraint::Fill(1),
1561    ]).split(content_row);
1562
1563    let logo = build_logo_lines(CONTENT_H as usize, LOGO_W as usize);
1564    f.render_widget(
1565        Paragraph::new(logo.into_iter()
1566            .map(|l| Line::styled(l, Style::default().fg(brand)))
1567            .collect::<Vec<_>>()),
1568        h[1],
1569    );
1570
1571    if has_sub {
1572        f.render_widget(
1573            Paragraph::new(subtitle_raw).style(Style::default().fg(dim_col)),
1574            left_v[3],
1575        );
1576    }
1577
1578    // Vertical separator spanning full inner height.
1579    let sep_lines: Vec<Line> = (0..sep_area.height)
1580        .map(|_| Line::styled("│", Style::default().fg(dim_col)))
1581        .collect();
1582    f.render_widget(Paragraph::new(sep_lines), sep_area);
1583
1584    // Right: brief description, vertically centered, with left padding.
1585    let desc: Vec<Line> = vec![
1586        Line::styled("Pool multiple Claude accounts", Style::default().fg(dim_col)),
1587        Line::styled("behind a single endpoint.", Style::default().fg(dim_col)),
1588        Line::styled("Maximise rate limits across", Style::default().fg(dim_col)),
1589        Line::styled("all accounts automatically.", Style::default().fg(dim_col)),
1590    ];
1591    let desc_h = desc.len() as u16;
1592    let right_v = Layout::new(Direction::Vertical, [
1593        Constraint::Fill(1),
1594        Constraint::Length(desc_h),
1595        Constraint::Fill(1),
1596    ]).split(right_area);
1597    let right_h = Layout::new(Direction::Horizontal, [
1598        Constraint::Fill(1),
1599        Constraint::Length(2),
1600    ]).split(right_v[1]);
1601    f.render_widget(
1602        Paragraph::new(desc).alignment(ratatui::layout::Alignment::Right),
1603        right_h[0],
1604    );
1605}
1606
1607
1608/// Print the splash using ratatui inline viewport — redraws live on resize.
1609fn print_splash(info: &[String]) {
1610    use ratatui::{backend::CrosstermBackend, Terminal, TerminalOptions, Viewport};
1611    use crossterm::{event::{self, Event}, terminal as cterm};
1612    use std::io::stdout;
1613
1614    let title_raw    = info.get(0).map(|s| strip_ansi(s)).unwrap_or_default();
1615    let subtitle_raw = info.get(1).map(|s| strip_ansi(s)).unwrap_or_default();
1616
1617    // Logo = 4 rows content + 2 border + 2 vertical padding + optional subtitle
1618    let splash_h: u16 = 4 + 2 + 2 + if subtitle_raw.is_empty() { 0 } else { 1 };
1619
1620    let mut terminal = match Terminal::with_options(
1621        CrosstermBackend::new(stdout()),
1622        TerminalOptions { viewport: Viewport::Inline(splash_h) },
1623    ) {
1624        Ok(t) => t,
1625        Err(_) => {
1626            // Fallback: plain text header if ratatui fails (e.g. non-TTY).
1627            println!("\n  ◆  {}  {}\n", title_raw.trim(), subtitle_raw);
1628            return;
1629        }
1630    };
1631
1632    let draw = |t: &mut Terminal<CrosstermBackend<std::io::Stdout>>| {
1633        t.draw(|f| render_splash_frame(f, &title_raw, &subtitle_raw)).ok();
1634    };
1635
1636    draw(&mut terminal);
1637
1638    // Redraw on resize for up to 500 ms.
1639    let _ = cterm::enable_raw_mode();
1640    let dl = std::time::Instant::now() + std::time::Duration::from_millis(500);
1641    loop {
1642        let rem = dl.saturating_duration_since(std::time::Instant::now());
1643        if rem.is_zero() { break; }
1644        if event::poll(rem).unwrap_or(false) {
1645            match event::read() {
1646                Ok(Event::Resize(_, _)) => draw(&mut terminal),
1647                _ => break,
1648            }
1649        } else { break; }
1650    }
1651    let _ = cterm::disable_raw_mode();
1652    let _ = terminal.show_cursor();
1653    println!(); // move cursor to next line after the inline viewport
1654}
1655
1656// ---------------------------------------------------------------------------
1657// Account card helpers  (used by cmd_status)
1658// ---------------------------------------------------------------------------
1659
1660/// Target visible width for account header lines and separators.
1661const CARD_W: usize = 58;
1662
1663/// Account header: "  ◆  name  tag                     Plan"
1664fn card_header(name: &str, name_c: &str, routing_tag: &str, tag_vis: usize, plan: &str) -> String {
1665    // Visible prefix: "  ◆  " = 5, then name (name.len()), then tag (tag_vis)
1666    let left_vis = 5 + name.len() + tag_vis;
1667    let gap = CARD_W.saturating_sub(left_vis + plan.len());
1668    format!("  {}  {}{}{}{}", brand_green(DIAMOND), name_c, routing_tag, " ".repeat(gap), dim(plan))
1669}
1670
1671/// An indented content row: "    content"
1672fn card_row(content: &str) -> String {
1673    format!("    {content}")
1674}
1675
1676/// Thin separator line between accounts.
1677fn card_sep() -> String {
1678    format!("  {}", dim(&"─".repeat(CARD_W - 2)))
1679}
1680
1681/// Routing diagram — account names in bold green, connectors in dark green.
1682///
1683/// 1 account:           2 accounts:          3+ accounts:
1684///   main  ─→  [info]    main ─┐ →  [info]    main ─┐
1685///             [info1]   work ─┘     [info1]   work ─┼─→  [info]
1686///                                             sec  ─┘     [info1]
1687fn print_routing_header(account_names: &[&str], info: &[String]) {
1688    println!();
1689    let n = account_names.len();
1690    let name_w = account_names.iter().map(|s| s.len()).max().unwrap_or(4);
1691    let info0 = info.get(0).map(|s| s.as_str()).unwrap_or("");
1692    let info1 = info.get(1).map(|s| s.as_str()).unwrap_or("");
1693
1694    match n {
1695        0 => {
1696            // No accounts yet — clean two-line header
1697            println!("  {}  {}", brand_green(DIAMOND), info0);
1698            if !info1.is_empty() {
1699                println!("       {}", info1);
1700            }
1701        }
1702        1 => {
1703            // "  name  ─→  info0"  (info1 indented to same column)
1704            let indent = name_w + 8; // 2 + name + 2 + "─→" + 2
1705            println!("  {}  {}  {}", green_bold(account_names[0]), dark_green("─→"), info0);
1706            if !info1.is_empty() {
1707                println!("  {}{}", " ".repeat(indent), info1);
1708            }
1709        }
1710        2 => {
1711            // "  name0 ─┐ →  info0"
1712            // "  name1 ─┘     info1"
1713            println!("  {}  {} {}  {}",
1714                green_bold(&pad(account_names[0], name_w)),
1715                dark_green("─┐"), dark_green("→"), info0);
1716            println!("  {}  {}    {}",
1717                green_bold(&pad(account_names[1], name_w)),
1718                dark_green("─┘"), info1);
1719        }
1720        3 => {
1721            // "  name0 ─┐"
1722            // "  name1 ─┼─→  info0"
1723            // "  name2 ─┘     info1"
1724            println!("  {}  {}", green_bold(&pad(account_names[0], name_w)), dark_green("─┐"));
1725            println!("  {}  {}  {}",
1726                green_bold(&pad(account_names[1], name_w)),
1727                dark_green("─┼─→"), info0);
1728            println!("  {}  {}    {}",
1729                green_bold(&pad(account_names[2], name_w)),
1730                dark_green("─┘"), info1);
1731        }
1732        _ => {
1733            // "  name0      ─┐"
1734            // "  + N more   ─┼─→  info0"
1735            // "  nameN      ─┘     info1"
1736            let more = dim(&pad(&format!("+ {} more", n - 2), name_w));
1737            println!("  {}  {}", green_bold(&pad(account_names[0], name_w)), dark_green("─┐"));
1738            println!("  {}  {}  {}", more, dark_green("─┼─→"), info0);
1739            println!("  {}  {}    {}",
1740                green_bold(&pad(account_names[n - 1], name_w)),
1741                dark_green("─┘"), info1);
1742        }
1743    }
1744
1745    println!();
1746}
1747
1748/// Capacity bar — `util` is 0.0–1.0; filled blocks show REMAINING capacity.
1749/// Green = plenty left, yellow = getting low, red = nearly exhausted.
1750fn util_bar(util: f64, width: usize) -> String {
1751    let used = (util.clamp(0.0, 1.0) * width as f64).round() as usize;
1752    let free = width.saturating_sub(used);
1753    // filled = remaining, empty = used — so a full bar means lots of quota left
1754    let bar = format!("{}{}", "█".repeat(free), "░".repeat(used));
1755    let pct = (util * 100.0) as u64;
1756    if pct < 50 { green(&bar) } else if pct < 80 { yellow(&bar) } else { red(&bar) }
1757}
1758
1759/// Seconds until a Unix-epoch reset timestamp. Returns None if past or zero.
1760fn secs_until(epoch_secs: u64) -> Option<u64> {
1761    let now = SystemTime::now().duration_since(UNIX_EPOCH).ok()?.as_secs();
1762    epoch_secs.checked_sub(now).filter(|&s| s > 0)
1763}
1764
1765// ---------------------------------------------------------------------------
1766// Multi-provider listener helpers
1767// ---------------------------------------------------------------------------
1768
1769/// Returns `(provider_label, url)` pairs for every provider present in accounts,
1770/// using `primary_port` for Anthropic and each provider's default port for others.
1771fn listener_addrs(
1772    accounts: &[crate::config::AccountConfig],
1773    host: &str,
1774    primary_port: u16,
1775) -> Vec<(String, String)> {
1776    use crate::provider::Provider;
1777    use std::collections::BTreeSet;
1778
1779    let providers: BTreeSet<String> = accounts.iter()
1780        .map(|a| a.provider.to_string())
1781        .collect();
1782
1783    providers.into_iter().map(|p| {
1784        let port = match Provider::from_str(&p) {
1785            Provider::Anthropic => primary_port,
1786            other => other.default_port(),
1787        };
1788        (p.clone(), format!("http://{host}:{port}"))
1789    }).collect()
1790}
1791
1792/// Bind a listener and spawn an axum server for each provider group found in
1793/// `config.accounts`. All servers run concurrently; the function returns when
1794/// the first one stops (error or clean shutdown).
1795async fn serve_all_providers(
1796    config: crate::config::Config,
1797    state: crate::state::StateStore,
1798    host: &str,
1799    primary_port: u16,
1800) -> anyhow::Result<()> {
1801    use crate::config::{Config, ServerConfig};
1802    use crate::provider::Provider;
1803    use std::collections::HashMap;
1804
1805    // Group accounts by provider.
1806    let mut by_provider: HashMap<String, Vec<crate::config::AccountConfig>> = HashMap::new();
1807    for account in config.accounts {
1808        by_provider.entry(account.provider.to_string()).or_default().push(account);
1809    }
1810
1811    let mut handles = Vec::new();
1812
1813    for (provider_str, accounts) in by_provider {
1814        let provider = Provider::from_str(&provider_str);
1815        let port = match provider {
1816            Provider::Anthropic => primary_port,
1817            ref other => other.default_port(),
1818        };
1819
1820        let provider_config = Config {
1821            accounts,
1822            server: ServerConfig {
1823                host: host.to_owned(),
1824                port,
1825                upstream_url: provider.default_upstream_url().to_owned(),
1826                ..config.server.clone()
1827            },
1828            config_file: config.config_file.clone(),
1829        };
1830
1831        let anthropic_url = if provider == Provider::OpenAI {
1832            Some(format!("http://{}:{}", host, primary_port))
1833        } else {
1834            None
1835        };
1836        let (app, live_creds) = crate::proxy::create_app_with_state(provider_config.clone(), state.clone(), anthropic_url)?;
1837        let listener = tokio::net::TcpListener::bind(format!("{host}:{port}"))
1838            .await
1839            .with_context(|| format!("cannot bind {host}:{port} for {provider_str} proxy"))?;
1840
1841        let cfg_arc = std::sync::Arc::new(provider_config);
1842        tokio::spawn(crate::proxy::prefetch_rate_limits(cfg_arc.clone(), state.clone(), live_creds.clone()));
1843        tokio::spawn(crate::proxy::openai_token_refresh_loop(cfg_arc.clone(), state.clone(), live_creds.clone()));
1844        tokio::spawn(crate::proxy::cooldown_watcher(cfg_arc.clone(), state.clone(), live_creds.clone()));
1845        tokio::spawn(crate::proxy::recovery_watcher(cfg_arc, state.clone(), live_creds));
1846        handles.push(tokio::spawn(async move {
1847            axum::serve(listener, app).await
1848        }));
1849    }
1850
1851    if handles.is_empty() {
1852        return Ok(());
1853    }
1854
1855    // Wait until the first listener stops, then exit (whole daemon restarts on error).
1856    let (result, _idx, _rest) = futures_util::future::select_all(handles).await;
1857    result??;
1858    Ok(())
1859}
1860
1861fn write_pid() {
1862    let p = pid_path();
1863    if let Some(dir) = p.parent() { let _ = std::fs::create_dir_all(dir); }
1864    let _ = std::fs::write(&p, std::process::id().to_string());
1865}
1866
1867/// PIDs of processes listening on the given port.
1868fn port_pids(port: u16) -> Vec<u32> {
1869    let out = std::process::Command::new("lsof")
1870        .args(["-ti", &format!(":{port}")])
1871        .output();
1872    let Ok(out) = out else { return vec![] };
1873    String::from_utf8_lossy(&out.stdout)
1874        .split_whitespace()
1875        .filter_map(|s| s.parse().ok())
1876        .collect()
1877}
1878
1879#[allow(dead_code)]
1880fn kill_port(port: u16) -> bool {
1881    let pids = port_pids(port);
1882    let mut any = false;
1883    for pid in pids {
1884        if std::process::Command::new("kill").arg(pid.to_string()).status().map(|s| s.success()).unwrap_or(false) {
1885            any = true;
1886        }
1887    }
1888    any
1889}
1890
1891/// Pad a string to display width using spaces (strips ANSI codes first; handles Unicode).
1892fn pad(s: &str, width: usize) -> String {
1893    use unicode_width::UnicodeWidthStr;
1894    let visible_width = UnicodeWidthStr::width(strip_ansi(s).as_str());
1895    if visible_width >= width {
1896        s.to_owned()
1897    } else {
1898        format!("{s}{}", " ".repeat(width - visible_width))
1899    }
1900}
1901
1902fn strip_ansi(s: &str) -> String {
1903    let mut out = String::with_capacity(s.len());
1904    let mut chars = s.chars().peekable();
1905    while let Some(c) = chars.next() {
1906        if c == '\x1b' {
1907            if chars.peek() == Some(&'[') {
1908                chars.next();
1909                while let Some(&next) = chars.peek() {
1910                    chars.next();
1911                    if next.is_ascii_alphabetic() { break; }
1912                }
1913            }
1914        } else {
1915            out.push(c);
1916        }
1917    }
1918    out
1919}
1920
1921// ---------------------------------------------------------------------------
1922// monitor
1923// ---------------------------------------------------------------------------
1924
1925async fn cmd_monitor(config_override: Option<PathBuf>) -> Result<()> {
1926    let config = crate::config::load_config(config_override.as_deref())?;
1927    let base_url = format!("http://{}:{}", config.server.host, config.server.port);
1928
1929    // Quick check: is the proxy running?
1930    if reqwest::get(format!("{base_url}/health")).await.is_err() {
1931        println!();
1932        println!("  {} Proxy is not running.", red(CROSS));
1933        println!("  {} Start it first with {}.", dim("·"), cyan("shunt start"));
1934        println!();
1935        return Ok(());
1936    }
1937
1938    crate::monitor::run_monitor(&base_url).await
1939}
1940
1941// ---------------------------------------------------------------------------
1942// remote
1943// ---------------------------------------------------------------------------
1944
1945async fn cmd_remote(code: Option<String>) -> Result<()> {
1946    // Host mode needs the local shunt URL; client mode only needs the relay URL.
1947    let (relay_url, local_url) = if code.is_none() {
1948        let config = crate::config::load_config(None)?;
1949        let local = format!("http://{}:{}", config.server.host, config.server.port);
1950        let relay = config.server.relay_url.clone();
1951        (Some(relay), local)
1952    } else {
1953        let relay_url = std::env::var("SHUNT_RELAY_URL").ok();
1954        (relay_url, String::new())
1955    };
1956    crate::remote::run_remote(code, relay_url, local_url).await
1957}
1958
1959// update
1960// ---------------------------------------------------------------------------
1961
1962async fn cmd_update() -> Result<()> {
1963    const REPO: &str = "ramc10/shunt";
1964    let current = env!("CARGO_PKG_VERSION");
1965
1966    print_splash(&[
1967        format!("{}  {}", brand_green("shunt"), dim(&format!("v{current}"))),
1968    ]);
1969    println!("  {} Checking for updates…", dim("·"));
1970
1971    // Fetch latest release from GitHub API
1972    let client = reqwest::Client::builder()
1973        .user_agent("shunt-updater")
1974        .connect_timeout(std::time::Duration::from_secs(10))
1975        .timeout(std::time::Duration::from_secs(120))
1976        .build()?;
1977
1978    let api_url = format!("https://api.github.com/repos/{REPO}/releases/latest");
1979    let resp = client.get(&api_url).send().await
1980        .context("Failed to reach GitHub API")?;
1981
1982    if !resp.status().is_success() {
1983        bail!("GitHub API returned {}", resp.status());
1984    }
1985
1986    let json: serde_json::Value = resp.json().await?;
1987    let latest_tag = json["tag_name"].as_str().context("Missing tag_name in release")?;
1988    let latest = latest_tag.trim_start_matches('v');
1989
1990    if latest == current {
1991        println!("  {} Already up to date ({})", green(CHECK), bold(&format!("v{current}")));
1992        println!();
1993        return Ok(());
1994    }
1995
1996    println!("  {} Update available: {}  →  {}", green("↑"),
1997        dim(&format!("v{current}")), bold_white(&format!("v{latest}")));
1998    println!();
1999
2000    // Detect platform
2001    let target = detect_update_target()?;
2002    let archive_name = format!("shunt-v{latest}-{target}.tar.gz");
2003    let url = format!(
2004        "https://github.com/{REPO}/releases/download/v{latest}/{archive_name}"
2005    );
2006
2007    print!("  {} Downloading {}… ", dim("↓"), dim(&archive_name));
2008    use std::io::Write as _;
2009    std::io::stdout().flush().ok();
2010
2011    let resp = client.get(&url).send().await
2012        .context("Download request failed")?;
2013
2014    if !resp.status().is_success() {
2015        bail!("Download failed: HTTP {} for {url}", resp.status());
2016    }
2017
2018    let bytes = resp.bytes().await
2019        .context("Failed to read download")?;
2020
2021    // Sanity-check: gzip magic bytes are 0x1f 0x8b
2022    if bytes.len() < 2 || bytes[0] != 0x1f || bytes[1] != 0x8b {
2023        bail!(
2024            "Downloaded file does not look like a gzip archive ({} bytes, first bytes: {:02x?})",
2025            bytes.len(), &bytes[..bytes.len().min(4)]
2026        );
2027    }
2028
2029    println!("{}", green("done"));
2030
2031    // Extract binary from tarball into a temp file next to the current exe
2032    let exe_path = std::env::current_exe().context("Cannot locate current executable")?;
2033    let tmp_path = exe_path.with_extension("tmp");
2034
2035    extract_binary_from_tarball(&bytes, &tmp_path)
2036        .context("Failed to extract binary from archive")?;
2037
2038    // Replace current executable atomically
2039    #[cfg(unix)]
2040    {
2041        use std::os::unix::fs::PermissionsExt;
2042        std::fs::set_permissions(&tmp_path, std::fs::Permissions::from_mode(0o755))?;
2043    }
2044    std::fs::rename(&tmp_path, &exe_path)
2045        .context("Failed to replace binary (try running with sudo?)")?;
2046
2047    // macOS: remove quarantine and ad-hoc sign so Gatekeeper allows unsigned binaries
2048    #[cfg(target_os = "macos")]
2049    {
2050        let p = exe_path.display().to_string();
2051        std::process::Command::new("xattr").args(["-d", "com.apple.quarantine", &p]).status().ok();
2052        std::process::Command::new("codesign").args(["--force", "--deep", "--sign", "-", &p]).status().ok();
2053    }
2054
2055    println!("  {} Updated to {}", green(CHECK), bold_white(&format!("v{latest}")));
2056    println!();
2057    Ok(())
2058}
2059
2060fn detect_update_target() -> Result<&'static str> {
2061    match (std::env::consts::OS, std::env::consts::ARCH) {
2062        ("macos",  "aarch64") => Ok("aarch64-apple-darwin"),
2063        ("linux",  "x86_64")  => Ok("x86_64-unknown-linux-gnu"),
2064        ("linux",  "aarch64") => Ok("aarch64-unknown-linux-gnu"),
2065        (os, arch) => bail!("No pre-built binary for {os}/{arch}. Build from source: cargo install shunt-proxy"),
2066    }
2067}
2068
2069fn extract_binary_from_tarball(data: &[u8], dest: &std::path::Path) -> Result<()> {
2070    let gz = flate2::read::GzDecoder::new(data);
2071    let mut archive = tar::Archive::new(gz);
2072    for entry in archive.entries()? {
2073        let mut entry = entry?;
2074        let path = entry.path()?;
2075        if path.file_name().and_then(|n| n.to_str()) == Some("shunt") {
2076            let mut out = std::fs::File::create(dest)?;
2077            std::io::copy(&mut entry, &mut out)?;
2078            return Ok(());
2079        }
2080    }
2081    bail!("Binary 'shunt' not found in archive")
2082}
2083
2084// ---------------------------------------------------------------------------
2085// share
2086// ---------------------------------------------------------------------------
2087
2088async fn cmd_share(config_override: Option<PathBuf>, tunnel: bool, stop: bool) -> Result<()> {
2089    let config_p = config_override.unwrap_or_else(config_path);
2090    if !config_p.exists() {
2091        bail!("No config found. Run `shunt setup` first.");
2092    }
2093
2094    let mut text = std::fs::read_to_string(&config_p)?;
2095
2096    // If no flags given, show interactive menu
2097    // use an enum to track the chosen mode cleanly
2098    #[derive(Debug)]
2099    enum ShareMode { Lan, Tunnel, CustomDomain, Stop }
2100
2101    let mode: ShareMode = if tunnel {
2102        ShareMode::Tunnel
2103    } else if stop {
2104        ShareMode::Stop
2105    } else {
2106        print_splash(&[
2107            format!("{}  {}", brand_green("shunt"), dim(&format!("v{}", env!("CARGO_PKG_VERSION")))),
2108            dim("Remote sharing").to_string(),
2109            String::new(),
2110        ]);
2111        let top_items = vec![
2112            term::SelectItem {
2113                label: format!("{}  {}", bold("Local network (LAN)"),
2114                    dim("— same Wi-Fi only, no internet required")),
2115                value: "lan".into(),
2116            },
2117            term::SelectItem {
2118                label: format!("{}  {}", bold("Online"),
2119                    dim("— share over the internet")),
2120                value: "online".into(),
2121            },
2122            term::SelectItem {
2123                label: format!("{}  {}", bold("Stop sharing"),
2124                    dim("— revert to localhost-only")),
2125                value: "stop".into(),
2126            },
2127        ];
2128        match term::select("How do you want to share?", &top_items, 0).as_deref() {
2129            Some("lan")    => ShareMode::Lan,
2130            Some("stop")   => ShareMode::Stop,
2131            Some("online") => {
2132                // Sub-menu: temporary vs custom domain
2133                let existing_domain = crate::config::load_config(Some(&config_p))
2134                    .ok()
2135                    .and_then(|c| c.server.custom_domain.clone());
2136                let domain_label = match &existing_domain {
2137                    Some(d) => format!("{}  {}",
2138                        bold("Custom domain (permanent)"),
2139                        dim(&format!("— {} · your domain", d))),
2140                    None => format!("{}  {}",
2141                        bold("Custom domain (permanent)"),
2142                        dim("— your own domain, always-on")),
2143                };
2144                let online_items = vec![
2145                    term::SelectItem {
2146                        label: format!("{}  {}",
2147                            bold("Temporary (Cloudflare tunnel)"),
2148                            dim("— free, random URL, session only")),
2149                        value: "tunnel".into(),
2150                    },
2151                    term::SelectItem {
2152                        label: domain_label,
2153                        value: "custom".into(),
2154                    },
2155                ];
2156                match term::select("Online sharing type:", &online_items, 0).as_deref() {
2157                    Some("tunnel") => ShareMode::Tunnel,
2158                    Some("custom") => ShareMode::CustomDomain,
2159                    _ => return Ok(()),
2160                }
2161            }
2162            _ => return Ok(()),
2163        }
2164    };
2165
2166    if matches!(mode, ShareMode::Stop) {
2167        // Reconfirm before disabling
2168        if !term::confirm("Stop sharing and revert to localhost-only?") {
2169            println!("  {} Cancelled.", dim("·"));
2170            println!();
2171            return Ok(());
2172        }
2173
2174        text = text.lines()
2175            .filter(|l| !l.trim_start().starts_with("remote_key"))
2176            .collect::<Vec<_>>()
2177            .join("\n");
2178        if !text.ends_with('\n') { text.push('\n'); }
2179        text = text.replace("host = \"0.0.0.0\"", "host = \"127.0.0.1\"");
2180        std::fs::write(&config_p, &text)?;
2181
2182        print_splash(&[
2183            format!("{}  {}", brand_green("shunt"), dim(&format!("v{}", env!("CARGO_PKG_VERSION")))),
2184            dim("Remote sharing disabled").to_string(),
2185            String::new(),
2186        ]);
2187        println!("  {} Restart to apply: {}", dim("·"), cyan("shunt start"));
2188        println!();
2189        return Ok(());
2190    }
2191
2192    // Generate or reuse existing remote key
2193    let key = match extract_remote_key(&text) {
2194        Some(k) => k,
2195        None => {
2196            let k = generate_remote_key();
2197            text = insert_into_server_section(&text, &format!("remote_key = \"{k}\""));
2198            k
2199        }
2200    };
2201
2202    // Ensure host is 0.0.0.0
2203    if text.contains("host = \"127.0.0.1\"") {
2204        text = text.replace("host = \"127.0.0.1\"", "host = \"0.0.0.0\"");
2205    }
2206
2207    std::fs::write(&config_p, &text)?;
2208
2209    let (port, relay_url, saved_domain) = match crate::config::load_config(Some(&config_p)) {
2210        Ok(cfg) => {
2211            let relay = std::env::var("SHUNT_RELAY_URL")
2212                .unwrap_or_else(|_| cfg.server.relay_url.clone());
2213            (cfg.server.port, relay, cfg.server.custom_domain)
2214        }
2215        Err(_) => (8082u16,
2216            std::env::var("SHUNT_RELAY_URL")
2217                .unwrap_or_else(|_| "https://relay.ramcharan.shop".to_string()),
2218            None),
2219    };
2220
2221    match mode {
2222        ShareMode::Tunnel => {
2223            print_splash(&[
2224                format!("{}  {}", brand_green("shunt"), dim(&format!("v{}", env!("CARGO_PKG_VERSION")))),
2225                dim("Starting Cloudflare tunnel…").to_string(),
2226                String::new(),
2227            ]);
2228            println!("  {} Make sure the proxy is running: {}", dim("·"), cyan("shunt start"));
2229            println!();
2230
2231            let url = start_cloudflare_tunnel(port)?;
2232            share_and_print(&url, &key, &relay_url, "Tunnel active", &[
2233                format!("  {} Code expires in 10 minutes — one-time use", dim("·")),
2234                format!("  {} Tunnel is active — keep this terminal open.", dim("·")),
2235                format!("  {} Press Ctrl+C to stop.", dim("·")),
2236            ]).await;
2237
2238            tokio::signal::ctrl_c().await.ok();
2239            println!("\n  {} Tunnel closed.", dim("·"));
2240        }
2241
2242        ShareMode::CustomDomain => {
2243            // Resolve domain: use saved, or prompt + save
2244            let domain = if let Some(d) = saved_domain {
2245                d
2246            } else {
2247                use std::io::Write;
2248                println!();
2249                println!("  {} Enter your domain URL (e.g. {}): ",
2250                    dim("·"), dim("https://shunt.mysite.com"));
2251                print!("    ");
2252                std::io::stdout().flush()?;
2253                let mut input = String::new();
2254                std::io::stdin().read_line(&mut input)?;
2255                let domain = input.trim().trim_end_matches('/').to_string();
2256                if domain.is_empty() {
2257                    bail!("No domain entered.");
2258                }
2259                if !domain.starts_with("http") {
2260                    bail!("Domain must start with http:// or https://");
2261                }
2262                // Save to config
2263                let mut cfg_text = std::fs::read_to_string(&config_p)?;
2264                cfg_text = insert_into_server_section(&cfg_text,
2265                    &format!("custom_domain = \"{domain}\""));
2266                std::fs::write(&config_p, &cfg_text)?;
2267                println!("  {} Saved {} to config.", green(CHECK), cyan(&domain));
2268                domain
2269            };
2270
2271            share_and_print(&domain, &key, &relay_url, "Online sharing (custom domain)", &[
2272                format!("  {} Code expires in 10 minutes — one-time use", dim("·")),
2273                format!("  {} Make sure {} is pointing to port {} on this machine.",
2274                    dim("·"), cyan(&domain), port),
2275                format!("  {} Restart to apply: {}", dim("·"), cyan("shunt start")),
2276                format!("  {} To stop sharing:  {}", dim("·"), cyan("shunt share --stop")),
2277            ]).await;
2278        }
2279
2280        ShareMode::Lan => {
2281            let ip = local_ip().unwrap_or_else(|| "<your-ip>".to_string());
2282            let base_url = format!("http://{ip}:{port}");
2283
2284            share_and_print(&base_url, &key, &relay_url, "Remote sharing enabled (LAN)", &[
2285                format!("  {} Code expires in 10 minutes — one-time use", dim("·")),
2286                format!("  {} Both devices must be on the same network.", dim("·")),
2287                format!("  {} Restart to apply: {}", dim("·"), cyan("shunt start")),
2288                format!("  {} To stop sharing:  {}", dim("·"), cyan("shunt share --stop")),
2289            ]).await;
2290        }
2291
2292        ShareMode::Stop => unreachable!(),
2293    }
2294
2295    Ok(())
2296}
2297
2298/// Push share code to relay and print the result (code or fallback manual instructions).
2299async fn share_and_print(base_url: &str, key: &str, relay_url: &str, subtitle: &str, hints: &[String]) {
2300    let share_code = crate::sync::generate_share_code();
2301    match crate::sync::push_share(&share_code, base_url, key, relay_url).await {
2302        Ok(()) => {
2303            print_splash(&[
2304                format!("{}  {}", brand_green("shunt"), dim(&format!("v{}", env!("CARGO_PKG_VERSION")))),
2305                dim(subtitle).to_string(),
2306                String::new(),
2307            ]);
2308            println!("  {}  Share code:\n", green(CHECK));
2309            println!("      {}\n", cyan(&share_code));
2310            println!("  {} On the other device, run:", dim("·"));
2311            println!("       {}", cyan(&format!("shunt connect {share_code}")));
2312            println!();
2313            for hint in hints { println!("{hint}"); }
2314            println!();
2315        }
2316        Err(e) => {
2317            // Relay unavailable — fall back to manual env var instructions
2318            print_splash(&[
2319                format!("{}  {}", brand_green("shunt"), dim(&format!("v{}", env!("CARGO_PKG_VERSION")))),
2320                dim(subtitle).to_string(),
2321                String::new(),
2322            ]);
2323            println!("  Set on the remote device:\n");
2324            println!("    {}{}", dim("export ANTHROPIC_BASE_URL="), cyan(base_url));
2325            println!("    {}{}", dim("export ANTHROPIC_API_KEY="), cyan(key));
2326            println!();
2327            println!("  {} (share code unavailable: {e})", dim("·"));
2328            for hint in hints { println!("{hint}"); }
2329            println!();
2330        }
2331    }
2332}
2333
2334/// Spawn `cloudflared tunnel --url http://localhost:{port}`, wait for the public URL,
2335/// and return it. The cloudflared process is left running in the background.
2336fn start_cloudflare_tunnel(port: u16) -> Result<String> {
2337    use std::io::{BufRead, BufReader};
2338    use std::process::{Command, Stdio};
2339
2340    let mut child = Command::new("cloudflared")
2341        .args(["tunnel", "--url", &format!("http://localhost:{port}")])
2342        .stderr(Stdio::piped())
2343        .stdout(Stdio::null())
2344        .spawn()
2345        .map_err(|e| {
2346            if e.kind() == std::io::ErrorKind::NotFound {
2347                anyhow::anyhow!(
2348                    "cloudflared not found.\n\n  Install it:\n    brew install cloudflared\n  or: https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/downloads/"
2349                )
2350            } else {
2351                anyhow::anyhow!("Failed to start cloudflared: {e}")
2352            }
2353        })?;
2354
2355    let stderr = child.stderr.take().expect("stderr was piped");
2356    let reader = BufReader::new(stderr);
2357
2358    for line in reader.lines() {
2359        let line = line?;
2360        if let Some(url) = extract_cloudflare_url(&line) {
2361            // Leave the child running — it will be killed when the process exits
2362            std::mem::forget(child);
2363            return Ok(url);
2364        }
2365    }
2366
2367    bail!("cloudflared exited before providing a tunnel URL")
2368}
2369
2370fn extract_cloudflare_url(line: &str) -> Option<String> {
2371    // cloudflared prints the URL in a line like:
2372    //   INF | https://random-words.trycloudflare.com |
2373    // or just contains the URL somewhere in the log line
2374    let lower = line.to_lowercase();
2375    if lower.contains("trycloudflare.com") || lower.contains("cfargotunnel.com") {
2376        // Extract the https:// URL from the line
2377        if let Some(start) = line.find("https://") {
2378            let rest = &line[start..];
2379            let end = rest.find(|c: char| c.is_whitespace() || c == '|' || c == '"')
2380                .unwrap_or(rest.len());
2381            return Some(rest[..end].trim_end_matches('/').to_owned());
2382        }
2383    }
2384    None
2385}
2386
2387fn generate_remote_key() -> String {
2388    hex::encode(crate::oauth::rand_bytes::<16>())
2389}
2390
2391fn extract_remote_key(config: &str) -> Option<String> {
2392    for line in config.lines() {
2393        let line = line.trim();
2394        if line.starts_with("remote_key") {
2395            return line.split('=')
2396                .nth(1)
2397                .map(|s| s.trim().trim_matches('"').to_owned());
2398        }
2399    }
2400    None
2401}
2402
2403fn insert_into_server_section(config: &str, line: &str) -> String {
2404    // Insert just before the first [[accounts]] block
2405    if let Some(pos) = config.find("\n[[accounts]]") {
2406        let (before, after) = config.split_at(pos);
2407        format!("{before}\n{line}{after}")
2408    } else {
2409        format!("{config}\n{line}\n")
2410    }
2411}
2412
2413fn local_ip() -> Option<String> {
2414    let socket = std::net::UdpSocket::bind("0.0.0.0:0").ok()?;
2415    socket.connect("8.8.8.8:80").ok()?;
2416    Some(socket.local_addr().ok()?.ip().to_string())
2417}
2418
2419/// If the proxy is currently running, offer to restart it immediately.
2420async fn offer_restart(config_override: Option<PathBuf>) {
2421    use std::io::Write;
2422    let Ok(cfg) = crate::config::load_config(config_override.as_deref()) else { return };
2423    let health_url = format!("http://{}:{}/health", cfg.server.host, cfg.server.port);
2424    let running = reqwest::get(&health_url).await
2425        .map(|r| r.status().is_success())
2426        .unwrap_or(false);
2427    if !running { return; }
2428
2429    print!("  {} Proxy is running — restart now? [Y/n]: ", dim("·"));
2430    std::io::stdout().flush().ok();
2431    let mut buf = String::new();
2432    std::io::stdin().read_line(&mut buf).ok();
2433    if matches!(buf.trim().to_lowercase().as_str(), "n" | "no") {
2434        println!("  {} Run {} when ready.", dim("·"), cyan("shunt restart"));
2435        return;
2436    }
2437    if let Err(e) = cmd_restart(config_override).await {
2438        println!("  {} Restart failed: {e}", red(CROSS));
2439    }
2440}
2441
2442// ---------------------------------------------------------------------------
2443// connect
2444// ---------------------------------------------------------------------------
2445
2446async fn cmd_connect(code: String) -> Result<()> {
2447    use std::io::{self, Write};
2448
2449    crate::sync::validate_share_code(&code)?;
2450
2451    let relay_url = std::env::var("SHUNT_RELAY_URL")
2452        .unwrap_or_else(|_| "https://relay.ramcharan.shop".to_string());
2453
2454    print_splash(&[
2455        format!("{}  {}", brand_green("shunt"), dim(&format!("v{}", env!("CARGO_PKG_VERSION")))),
2456        dim("Connecting to remote shunt…").to_string(),
2457        String::new(),
2458    ]);
2459
2460    println!("  {} Fetching credentials for {}…", dim("·"), cyan(&code));
2461    println!();
2462
2463    let (base_url, api_key) = crate::sync::pull_share(&code, &relay_url).await?;
2464
2465    println!("  {}  Retrieved:", green(CHECK));
2466    println!("      {} {}", dim("ANTHROPIC_BASE_URL ="), cyan(&base_url));
2467    println!("      {} {}", dim("ANTHROPIC_API_KEY  ="), cyan(&format!("{}…", &api_key[..api_key.len().min(12)])));
2468    println!();
2469
2470    // --- Offer to write to shell profile ---
2471    let profile = detect_shell_profile();
2472    let prompt = match &profile {
2473        Some(p) => format!("  Write to {}? [Y/n]: ", dim(&p.display().to_string())),
2474        None => "  Write to shell profile? [Y/n]: ".into(),
2475    };
2476    print!("{prompt}");
2477    io::stdout().flush()?;
2478    let mut buf = String::new();
2479    io::stdin().read_line(&mut buf)?;
2480
2481    if !matches!(buf.trim().to_lowercase().as_str(), "n" | "no") {
2482        match profile {
2483            Some(p) => {
2484                write_connect_vars_to_profile(&p, &base_url, &api_key)?;
2485            }
2486            None => {
2487                println!("  {} Could not detect shell profile. Set manually:", dim("·"));
2488                println!("      export ANTHROPIC_BASE_URL={base_url}");
2489                println!("      export ANTHROPIC_API_KEY={api_key}");
2490            }
2491        }
2492    }
2493
2494    // --- Write to Claude Code settings.json ---
2495    if let Err(e) = write_claude_settings(&base_url, &api_key) {
2496        println!("  {} Could not write ~/.claude/settings.json: {e}", dim("·"));
2497    } else {
2498        println!("  {} Written to {}", green(CHECK), dim("~/.claude/settings.json"));
2499    }
2500
2501    println!();
2502    println!("  {} Done! Restart shell or run: {}", green(CHECK),
2503        cyan(detect_shell_profile()
2504            .map(|p| format!("source {}", p.display()))
2505            .unwrap_or_else(|| "source ~/.zshrc".to_string()).as_str()));
2506    println!();
2507
2508    Ok(())
2509}
2510
2511/// Write ANTHROPIC_BASE_URL and ANTHROPIC_API_KEY to a shell profile, replacing
2512/// existing entries in-place or appending if absent.
2513fn write_connect_vars_to_profile(profile: &std::path::Path, base_url: &str, api_key: &str) -> Result<()> {
2514    use std::io::Write as _;
2515
2516    let url_line = format!("export ANTHROPIC_BASE_URL={base_url}");
2517    let key_line = format!("export ANTHROPIC_API_KEY={api_key}");
2518
2519    if profile.exists() {
2520        let contents = std::fs::read_to_string(profile)?;
2521        let has_url = contents.contains("ANTHROPIC_BASE_URL");
2522        let has_key = contents.contains("ANTHROPIC_API_KEY");
2523
2524        if has_url || has_key {
2525            // Replace in-place
2526            let updated: String = contents
2527                .lines()
2528                .map(|l| {
2529                    if l.contains("ANTHROPIC_BASE_URL") {
2530                        url_line.as_str()
2531                    } else if l.contains("ANTHROPIC_API_KEY") {
2532                        key_line.as_str()
2533                    } else {
2534                        l
2535                    }
2536                })
2537                .collect::<Vec<_>>()
2538                .join("\n")
2539                + "\n";
2540            // Append any var that wasn't already there
2541            let mut final_content = updated;
2542            if !has_url {
2543                final_content.push_str(&format!("{url_line}\n"));
2544            }
2545            if !has_key {
2546                final_content.push_str(&format!("{key_line}\n"));
2547            }
2548            std::fs::write(profile, &final_content)?;
2549            println!("  {} Updated {} — {}", green(CHECK),
2550                dim(&profile.display().to_string()),
2551                cyan("ANTHROPIC_BASE_URL + ANTHROPIC_API_KEY"));
2552            return Ok(());
2553        }
2554    }
2555
2556    // Append both vars
2557    let mut f = std::fs::OpenOptions::new().create(true).append(true).open(profile)?;
2558    writeln!(f, "\n# Added by shunt connect")?;
2559    writeln!(f, "{url_line}")?;
2560    writeln!(f, "{key_line}")?;
2561    println!("  {} Added to {} — {}", green(CHECK),
2562        dim(&profile.display().to_string()),
2563        cyan("ANTHROPIC_BASE_URL + ANTHROPIC_API_KEY"));
2564    Ok(())
2565}
2566
2567/// Write ANTHROPIC_BASE_URL and ANTHROPIC_API_KEY into ~/.claude/settings.json
2568/// under the `env` key, creating the file if absent.
2569fn write_claude_settings(base_url: &str, api_key: &str) -> Result<()> {
2570    let home = dirs::home_dir().context("Cannot find home directory")?;
2571    let settings_path = home.join(".claude").join("settings.json");
2572
2573    let mut root: serde_json::Value = if settings_path.exists() {
2574        let text = std::fs::read_to_string(&settings_path)?;
2575        serde_json::from_str(&text).unwrap_or(serde_json::Value::Object(Default::default()))
2576    } else {
2577        serde_json::Value::Object(Default::default())
2578    };
2579
2580    let obj = root.as_object_mut().context("settings.json root is not an object")?;
2581    let env = obj.entry("env").or_insert(serde_json::Value::Object(Default::default()));
2582    let env_obj = env.as_object_mut().context("settings.json 'env' is not an object")?;
2583    env_obj.insert("ANTHROPIC_BASE_URL".to_string(), serde_json::Value::String(base_url.to_string()));
2584    env_obj.insert("ANTHROPIC_API_KEY".to_string(), serde_json::Value::String(api_key.to_string()));
2585
2586    if let Some(parent) = settings_path.parent() {
2587        std::fs::create_dir_all(parent)?;
2588    }
2589    std::fs::write(&settings_path, serde_json::to_string_pretty(&root)?)?;
2590    Ok(())
2591}
2592
2593fn offer_shell_export() -> Result<()> {
2594    use std::io::{self, Write};
2595
2596    let line = "export ANTHROPIC_BASE_URL=http://127.0.0.1:8082";
2597    println!();
2598    println!("  To use with Claude Code, set:");
2599    println!("    {}", cyan(line));
2600
2601    let profile = detect_shell_profile();
2602    let prompt = match &profile {
2603        Some(p) => format!("  Add to {}? [Y/n]: ", dim(&p.display().to_string())),
2604        None => "  Add to your shell profile? [Y/n]: ".into(),
2605    };
2606
2607    print!("{prompt}");
2608    io::stdout().flush()?;
2609    let mut buf = String::new();
2610    io::stdin().read_line(&mut buf)?;
2611
2612    if matches!(buf.trim().to_lowercase().as_str(), "n" | "no") {
2613        return Ok(());
2614    }
2615
2616    let path = match profile {
2617        Some(p) => p,
2618        None => {
2619            println!("  {} Could not detect shell profile. Add manually.", dim("·"));
2620            return Ok(());
2621        }
2622    };
2623
2624    if path.exists() {
2625        let contents = std::fs::read_to_string(&path)?;
2626        if contents.contains("ANTHROPIC_BASE_URL") {
2627            println!("  {} Already set in {}", CHECK, dim(&path.display().to_string()));
2628            return Ok(());
2629        }
2630    }
2631
2632    let mut f = std::fs::OpenOptions::new().create(true).append(true).open(&path)?;
2633    #[allow(unused_imports)]
2634    use std::io::Write as _;
2635    writeln!(f, "\n# Added by shunt")?;
2636    writeln!(f, "{line}")?;
2637    println!("  {} Added to {} — restart shell or: {}", green(CHECK),
2638        dim(&path.display().to_string()),
2639        cyan(&format!("source {}", path.display())));
2640
2641    Ok(())
2642}
2643
2644// ---------------------------------------------------------------------------
2645// uninstall
2646// ---------------------------------------------------------------------------
2647
2648async fn cmd_uninstall() -> Result<()> {
2649    use std::io::Write as _;
2650
2651    // ── Collect what exists ───────────────────────────────────────────────────
2652    let config_dir = dirs::config_dir()
2653        .unwrap_or_else(|| PathBuf::from("."))
2654        .join("shunt");
2655
2656    let data_dir = dirs::data_local_dir()
2657        .unwrap_or_else(|| PathBuf::from("."))
2658        .join("shunt");
2659
2660    let exe = std::env::current_exe().ok();
2661
2662    // Shell profile line to remove
2663    let shell_profile = detect_shell_profile();
2664    let profile_has_export = shell_profile.as_ref().and_then(|p| {
2665        std::fs::read_to_string(p).ok()
2666    }).map(|s| s.contains("ANTHROPIC_BASE_URL=http://127.0.0.1:")).unwrap_or(false);
2667
2668    #[cfg(target_os = "macos")]
2669    let service_plist = {
2670        let p = service_plist_path();
2671        if p.exists() { Some(p) } else { None }
2672    };
2673    #[cfg(not(target_os = "macos"))]
2674    let service_plist: Option<PathBuf> = None;
2675
2676    #[cfg(target_os = "linux")]
2677    let service_unit = {
2678        let p = service_unit_path();
2679        if p.exists() { Some(p) } else { None }
2680    };
2681    #[cfg(not(target_os = "linux"))]
2682    let service_unit: Option<PathBuf> = None;
2683
2684    // ── Show plan ─────────────────────────────────────────────────────────────
2685    print_splash(&[
2686        format!("{}  {}", brand_green("shunt"), dim(&format!("v{}", env!("CARGO_PKG_VERSION")))),
2687        red("Uninstall").to_string(),
2688        String::new(),
2689    ]);
2690
2691    println!("  This will permanently remove:");
2692    println!();
2693
2694    if service_plist.is_some() || service_unit.is_some() {
2695        println!("  {}  Stop and unregister login service", red("✕"));
2696    }
2697
2698    if config_dir.exists() {
2699        println!("  {}  {} {}", red("✕"), dim("delete"), cyan(&config_dir.display().to_string()));
2700    }
2701    if data_dir.exists() && data_dir != config_dir {
2702        println!("  {}  {} {}", red("✕"), dim("delete"), cyan(&data_dir.display().to_string()));
2703    }
2704    if let Some(ref p) = shell_profile {
2705        if profile_has_export {
2706            println!("  {}  {} ANTHROPIC_BASE_URL from {}", red("✕"), dim("remove"), cyan(&p.display().to_string()));
2707        }
2708    }
2709    if let Some(ref exe_path) = exe {
2710        println!("  {}  {} {}", red("✕"), dim("delete"), cyan(&exe_path.display().to_string()));
2711    }
2712
2713    println!();
2714
2715    // ── Reconfirm ─────────────────────────────────────────────────────────────
2716    if !term::confirm("Are you sure you want to completely uninstall shunt?") {
2717        println!("  {} Cancelled.", dim("·"));
2718        println!();
2719        return Ok(());
2720    }
2721
2722    // Second confirmation — type "uninstall"
2723    println!();
2724    print!("  {} Type {} to confirm: ", dim("·"), bold("uninstall"));
2725    std::io::stdout().flush()?;
2726    let mut buf = String::new();
2727    std::io::stdin().read_line(&mut buf)?;
2728    if buf.trim() != "uninstall" {
2729        println!("  {} Cancelled.", dim("·"));
2730        println!();
2731        return Ok(());
2732    }
2733
2734    println!();
2735
2736    // ── Execute ───────────────────────────────────────────────────────────────
2737
2738    // 1. Stop + unregister service
2739    #[cfg(target_os = "macos")]
2740    if let Some(ref p) = service_plist {
2741        let _ = std::process::Command::new("launchctl")
2742            .args(["unload", &p.display().to_string()])
2743            .output();
2744        let _ = std::fs::remove_file(p);
2745        println!("  {} Login service removed", green(CHECK));
2746    }
2747    #[cfg(target_os = "linux")]
2748    if let Some(ref p) = service_unit {
2749        let _ = std::process::Command::new("systemctl")
2750            .args(["--user", "disable", "--now", "shunt"])
2751            .output();
2752        let _ = std::fs::remove_file(p);
2753        let _ = std::process::Command::new("systemctl")
2754            .args(["--user", "daemon-reload"])
2755            .output();
2756        println!("  {} Login service removed", green(CHECK));
2757    }
2758
2759    // 2. Config + credentials dir
2760    if config_dir.exists() {
2761        std::fs::remove_dir_all(&config_dir)
2762            .with_context(|| format!("failed to remove {}", config_dir.display()))?;
2763        println!("  {} Config removed  {}", green(CHECK), dim(&config_dir.display().to_string()));
2764    }
2765
2766    // 3. Data dir (logs, state, pid) — skip if same as config_dir (macOS)
2767    if data_dir.exists() && data_dir != config_dir {
2768        std::fs::remove_dir_all(&data_dir)
2769            .with_context(|| format!("failed to remove {}", data_dir.display()))?;
2770        println!("  {} Data removed    {}", green(CHECK), dim(&data_dir.display().to_string()));
2771    }
2772
2773    // 4. Shell profile — strip ANTHROPIC_BASE_URL lines
2774    if let Some(ref profile_path) = shell_profile {
2775        if profile_has_export {
2776            if let Ok(contents) = std::fs::read_to_string(profile_path) {
2777                let cleaned: String = contents
2778                    .lines()
2779                    .filter(|l| {
2780                        !l.contains("ANTHROPIC_BASE_URL=http://127.0.0.1:")
2781                            && *l != "# Added by shunt"
2782                    })
2783                    .collect::<Vec<_>>()
2784                    .join("\n");
2785                // Preserve trailing newline if original had one
2786                let cleaned = if contents.ends_with('\n') {
2787                    format!("{cleaned}\n")
2788                } else {
2789                    cleaned
2790                };
2791                std::fs::write(profile_path, cleaned)?;
2792                println!("  {} Shell export removed  {}", green(CHECK),
2793                    dim(&profile_path.display().to_string()));
2794            }
2795        }
2796    }
2797
2798    // 5. Binary — do this last so error messages can still print
2799    if let Some(exe_path) = exe {
2800        // Spawn a tiny shell to delete the binary after this process exits
2801        let path_str = exe_path.display().to_string();
2802        std::process::Command::new("sh")
2803            .args(["-c", &format!("sleep 0.3 && rm -f '{path_str}'")])
2804            .stdin(std::process::Stdio::null())
2805            .stdout(std::process::Stdio::null())
2806            .stderr(std::process::Stdio::null())
2807            .spawn()
2808            .ok();
2809        println!("  {} Binary removed   {}", green(CHECK), dim(&exe_path.display().to_string()));
2810    }
2811
2812    println!();
2813    println!("  {} shunt fully removed.", green(CHECK));
2814    println!("  {} Run {} to clear the proxy from this shell session.", dim("·"), cyan("unset ANTHROPIC_BASE_URL"));
2815    println!();
2816
2817    Ok(())
2818}
2819
2820// ---------------------------------------------------------------------------
2821// service
2822// ---------------------------------------------------------------------------
2823
2824#[cfg(target_os = "macos")]
2825fn service_plist_path() -> PathBuf {
2826    dirs::home_dir()
2827        .unwrap_or_else(|| PathBuf::from("/tmp"))
2828        .join("Library/LaunchAgents/sh.shunt.proxy.plist")
2829}
2830
2831#[cfg(target_os = "linux")]
2832fn service_unit_path() -> PathBuf {
2833    dirs::home_dir()
2834        .unwrap_or_else(|| PathBuf::from("/tmp"))
2835        .join(".config/systemd/user/shunt.service")
2836}
2837
2838/// Write the platform service file and enable it to run at login.
2839/// Write the platform service file and attempt to activate it.
2840/// Returns `true` if the service was successfully loaded/started by the init
2841/// system, `false` if the plist/unit was written but activation was skipped
2842/// or timed out (e.g. SSH session without a GUI bootstrap context).
2843fn register_service() -> Result<bool> {
2844    let exe = std::env::current_exe().context("cannot locate current executable")?;
2845    let exe_str = exe.display().to_string();
2846
2847    #[cfg(target_os = "macos")]
2848    {
2849        let plist_path = service_plist_path();
2850        if let Some(parent) = plist_path.parent() {
2851            std::fs::create_dir_all(parent)?;
2852        }
2853        let plist = format!(r#"<?xml version="1.0" encoding="UTF-8"?>
2854<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN"
2855  "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
2856<plist version="1.0">
2857<dict>
2858  <key>Label</key>
2859  <string>sh.shunt.proxy</string>
2860  <key>ProgramArguments</key>
2861  <array>
2862    <string>{exe_str}</string>
2863    <string>start</string>
2864    <string>--foreground</string>
2865  </array>
2866  <key>RunAtLoad</key>
2867  <true/>
2868  <key>KeepAlive</key>
2869  <true/>
2870  <key>StandardOutPath</key>
2871  <string>{home}/Library/Logs/shunt.log</string>
2872  <key>StandardErrorPath</key>
2873  <string>{home}/Library/Logs/shunt.log</string>
2874</dict>
2875</plist>
2876"#,
2877            exe_str = exe_str,
2878            home = dirs::home_dir().unwrap_or_default().display(),
2879        );
2880        std::fs::write(&plist_path, &plist)?;
2881
2882        // Unload first (silent — ignore errors if not loaded)
2883        let _ = std::process::Command::new("launchctl")
2884            .args(["unload", &plist_path.display().to_string()])
2885            .output();
2886
2887        // launchctl hangs in SSH sessions without a GUI bootstrap context.
2888        // Run it in a thread with a 4-second timeout; if it times out or fails,
2889        // the plist is still written and will auto-load on next GUI login.
2890        let plist_str = plist_path.display().to_string();
2891        let (tx, rx) = std::sync::mpsc::channel();
2892        std::thread::spawn(move || {
2893            let ok = std::process::Command::new("launchctl")
2894                .args(["load", "-w", &plist_str])
2895                .output()
2896                .map(|o| o.status.success())
2897                .unwrap_or(false);
2898            let _ = tx.send(ok);
2899        });
2900
2901        let loaded = rx
2902            .recv_timeout(std::time::Duration::from_secs(4))
2903            .unwrap_or(false);
2904
2905        return Ok(loaded);
2906    }
2907
2908    #[cfg(target_os = "linux")]
2909    {
2910        let unit_path = service_unit_path();
2911        if let Some(parent) = unit_path.parent() {
2912            std::fs::create_dir_all(parent)?;
2913        }
2914        let unit = format!(
2915            "[Unit]\nDescription=shunt Claude Code proxy\nAfter=network.target\n\n\
2916             [Service]\nExecStart={exe_str} start --foreground\nRestart=always\nRestartSec=5\n\n\
2917             [Install]\nWantedBy=default.target\n"
2918        );
2919        std::fs::write(&unit_path, &unit)?;
2920
2921        let _ = std::process::Command::new("systemctl")
2922            .args(["--user", "daemon-reload"])
2923            .output();
2924
2925        let out = std::process::Command::new("systemctl")
2926            .args(["--user", "enable", "--now", "shunt"])
2927            .output()
2928            .context("failed to run systemctl")?;
2929
2930        return Ok(out.status.success());
2931    }
2932
2933    #[cfg(not(any(target_os = "macos", target_os = "linux")))]
2934    bail!("Service management is only supported on macOS and Linux.");
2935
2936    #[allow(unreachable_code)]
2937    Ok(false)
2938}
2939
2940async fn cmd_service_install() -> Result<()> {
2941    print_splash(&[
2942        format!("{}  {}", brand_green("shunt"), dim(&format!("v{}", env!("CARGO_PKG_VERSION")))),
2943        dim("Service install"),
2944        String::new(),
2945    ]);
2946
2947    // 1. Ensure config + credentials exist (OAuth flow if needed)
2948    let config_p = config_path();
2949    if !config_p.exists() {
2950        cmd_setup_auto(None).await?;
2951    }
2952
2953    // 2. Read port from config for shell export
2954    let port = crate::config::load_config(None)
2955        .map(|c| c.server.port)
2956        .unwrap_or(8082);
2957
2958    // 3. Register the platform service
2959    let service_loaded = register_service()?;
2960
2961    // 4. If launchd/systemd couldn't activate the service (e.g. SSH session
2962    //    without a GUI bootstrap context), start the proxy directly.
2963    if !service_loaded {
2964        let exe = std::env::current_exe().context("cannot locate current executable")?;
2965        let _ = std::process::Command::new(&exe)
2966            .args(["start", "--daemon"])
2967            .stdin(std::process::Stdio::null())
2968            .stdout(std::process::Stdio::null())
2969            .stderr(std::process::Stdio::null())
2970            .spawn();
2971    }
2972
2973    // 5. Write shell export silently
2974    auto_write_shell_export(port);
2975
2976    // 6. Wait for proxy to be healthy
2977    tokio::time::sleep(std::time::Duration::from_millis(1000)).await;
2978    let config = crate::config::load_config(None).ok();
2979    let host = config.as_ref().map(|c| c.server.host.clone()).unwrap_or_else(|| "127.0.0.1".into());
2980    let running = wait_for_health(&host, port, 6).await;
2981
2982    println!();
2983    if running {
2984        println!("  {}  {}  {}", green(DOT), green_bold("proxy running"),
2985            cyan(&format!("http://{host}:{port}")));
2986    } else {
2987        println!("  {}  {} — proxy starting in background",
2988            yellow(DOT), yellow("starting"));
2989    }
2990
2991    #[cfg(target_os = "macos")]
2992    if service_loaded {
2993        println!("  {}  LaunchAgent registered — starts automatically at login", green(CHECK));
2994    } else {
2995        println!("  {}  LaunchAgent written — will activate on next login", yellow("·"));
2996        println!("  {}  To activate now (in a GUI session): {}",
2997            dim("·"), cyan("launchctl load -w ~/Library/LaunchAgents/sh.shunt.proxy.plist"));
2998    }
2999    #[cfg(target_os = "linux")]
3000    if service_loaded {
3001        println!("  {}  systemd user unit registered — starts automatically at login", green(CHECK));
3002    } else {
3003        println!("  {}  systemd unit written — run {} to activate",
3004            yellow("·"), cyan("systemctl --user enable --now shunt"));
3005    }
3006
3007    println!();
3008    println!("  {} To unregister: {}", dim("·"), cyan("shunt service uninstall"));
3009    println!();
3010
3011    Ok(())
3012}
3013
3014async fn cmd_service_uninstall() -> Result<()> {
3015    #[cfg(target_os = "macos")]
3016    {
3017        let plist_path = service_plist_path();
3018        if plist_path.exists() {
3019            let _ = std::process::Command::new("launchctl")
3020                .args(["unload", &plist_path.display().to_string()])
3021                .output();
3022            std::fs::remove_file(&plist_path)
3023                .context("failed to remove plist")?;
3024            println!("  {} Service unregistered.", green(CHECK));
3025        } else {
3026            println!("  {} Service not registered.", dim("·"));
3027        }
3028    }
3029
3030    #[cfg(target_os = "linux")]
3031    {
3032        let unit_path = service_unit_path();
3033        let _ = std::process::Command::new("systemctl")
3034            .args(["--user", "disable", "--now", "shunt"])
3035            .output();
3036        if unit_path.exists() {
3037            std::fs::remove_file(&unit_path)
3038                .context("failed to remove unit file")?;
3039        }
3040        let _ = std::process::Command::new("systemctl")
3041            .args(["--user", "daemon-reload"])
3042            .output();
3043        println!("  {} Service unregistered.", green(CHECK));
3044    }
3045
3046    #[cfg(not(any(target_os = "macos", target_os = "linux")))]
3047    bail!("Service management is only supported on macOS and Linux.");
3048
3049    println!();
3050    Ok(())
3051}
3052
3053async fn cmd_service_status() -> Result<()> {
3054    #[cfg(target_os = "macos")]
3055    {
3056        let plist_path = service_plist_path();
3057        let registered = plist_path.exists();
3058        if registered {
3059            println!("  {} Registered  {}", green(CHECK), dim(&plist_path.display().to_string()));
3060        } else {
3061            println!("  {} Not registered (run {})", dim("·"), cyan("shunt service install"));
3062        }
3063
3064        // Check if launchd considers it running
3065        let out = std::process::Command::new("launchctl")
3066            .args(["list", "sh.shunt.proxy"])
3067            .output();
3068        let running = out.map(|o| o.status.success()).unwrap_or(false);
3069        if running {
3070            println!("  {} Running (launchd)", green(DOT));
3071        } else {
3072            println!("  {} Not running", dim(DOT));
3073        }
3074    }
3075
3076    #[cfg(target_os = "linux")]
3077    {
3078        let unit_path = service_unit_path();
3079        let registered = unit_path.exists();
3080        if registered {
3081            println!("  {} Registered  {}", green(CHECK), dim(&unit_path.display().to_string()));
3082        } else {
3083            println!("  {} Not registered (run {})", dim("·"), cyan("shunt service install"));
3084        }
3085
3086        let out = std::process::Command::new("systemctl")
3087            .args(["--user", "is-active", "shunt"])
3088            .output();
3089        let active = out.map(|o| o.status.success()).unwrap_or(false);
3090        if active {
3091            println!("  {} Running (systemd)", green(DOT));
3092        } else {
3093            println!("  {} Not running", dim(DOT));
3094        }
3095    }
3096
3097    #[cfg(not(any(target_os = "macos", target_os = "linux")))]
3098    println!("  {} Service management is only supported on macOS and Linux.", dim("·"));
3099
3100    println!();
3101    Ok(())
3102}
3103
3104fn detect_shell_profile() -> Option<PathBuf> {
3105    let home = dirs::home_dir()?;
3106    if let Ok(shell) = std::env::var("SHELL") {
3107        if shell.contains("zsh")  { return Some(home.join(".zshrc")); }
3108        if shell.contains("fish") { return Some(home.join(".config/fish/config.fish")); }
3109        if shell.contains("bash") {
3110            let p = home.join(".bash_profile");
3111            return Some(if p.exists() { p } else { home.join(".bashrc") });
3112        }
3113    }
3114    for f in &[".zshrc", ".bashrc", ".bash_profile"] {
3115        let p = home.join(f);
3116        if p.exists() { return Some(p); }
3117    }
3118    None
3119}