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 client = reqwest::Client::builder()
1012        .timeout(std::time::Duration::from_secs(2))
1013        .build()
1014        .unwrap_or_default();
1015    let deadline = tokio::time::Instant::now()
1016        + std::time::Duration::from_secs(timeout_secs);
1017    while tokio::time::Instant::now() < deadline {
1018        if client.get(&url).send().await
1019            .map(|r| r.status().is_success())
1020            .unwrap_or(false)
1021        {
1022            return true;
1023        }
1024        tokio::time::sleep(std::time::Duration::from_millis(300)).await;
1025    }
1026    false
1027}
1028
1029fn auto_write_shell_export(port: u16) {
1030    use std::io::Write;
1031    let line = format!("export ANTHROPIC_BASE_URL=http://127.0.0.1:{port}");
1032    let Some(profile) = detect_shell_profile() else { return };
1033
1034    if profile.exists() {
1035        if let Ok(contents) = std::fs::read_to_string(&profile) {
1036            if contents.contains(&line) {
1037                // Already exactly correct — nothing to do.
1038                return;
1039            }
1040            if contents.contains("ANTHROPIC_BASE_URL=http://127.0.0.1:") {
1041                // Has the variable but with a different port — update it in-place.
1042                let updated: String = contents
1043                    .lines()
1044                    .map(|l| {
1045                        if l.contains("ANTHROPIC_BASE_URL=http://127.0.0.1:") {
1046                            line.as_str()
1047                        } else {
1048                            l
1049                        }
1050                    })
1051                    .collect::<Vec<_>>()
1052                    .join("\n")
1053                    + "\n";
1054                if std::fs::write(&profile, updated).is_ok() {
1055                    println!("  {} {} updated to port {}  → {}",
1056                        green(CHECK), cyan("ANTHROPIC_BASE_URL"), port,
1057                        dim(&profile.display().to_string()));
1058                }
1059                return;
1060            }
1061            if contents.contains("ANTHROPIC_BASE_URL") {
1062                // Set to something else (e.g. remote URL) — leave it alone.
1063                return;
1064            }
1065        }
1066    }
1067
1068    if let Ok(mut f) = std::fs::OpenOptions::new().create(true).append(true).open(&profile) {
1069        writeln!(f, "\n# Added by shunt").ok();
1070        writeln!(f, "{line}").ok();
1071        println!("  {} {} → {}",
1072            green(CHECK), cyan("ANTHROPIC_BASE_URL"),
1073            dim(&profile.display().to_string()));
1074    }
1075}
1076
1077// ---------------------------------------------------------------------------
1078// status
1079// ---------------------------------------------------------------------------
1080
1081async fn cmd_status(config_override: Option<PathBuf>) -> Result<()> {
1082    let mut config = crate::config::load_config(config_override.as_deref())?;
1083    let _primary_url = format!("http://{}:{}", config.server.host, config.server.port);
1084
1085    // Fetch live status from every provider's proxy (each runs on its own port).
1086    // provider_label → serde_json::Value
1087    let provider_urls = listener_addrs(&config.accounts, &config.server.host, config.server.port);
1088    let mut live_by_provider: std::collections::HashMap<String, serde_json::Value> =
1089        std::collections::HashMap::new();
1090    for (label, url) in &provider_urls {
1091        if let Some(v) = reqwest::get(format!("{url}/status")).await.ok()
1092            .and_then(|r| futures_executor_hack(r))
1093        {
1094            live_by_provider.insert(label.clone(), v);
1095        }
1096    }
1097
1098    // Primary proxy (Anthropic) drives the overall running/stopped display.
1099    let live: Option<&serde_json::Value> = live_by_provider
1100        .get(&crate::provider::Provider::Anthropic.to_string())
1101        .or_else(|| live_by_provider.values().next());
1102
1103    // Back-fill missing emails (existing accounts set up before email support).
1104    // Fetch in parallel, persist any that are new.
1105    let mut store_dirty = false;
1106    let mut store = CredentialsStore::load();
1107    for acc in &mut config.accounts {
1108        if acc.credential.as_ref().map(|c| c.email.is_none()).unwrap_or(false) {
1109            let token = acc.credential.as_ref().map(|c| c.access_token.clone()).unwrap_or_default();
1110            if let Some(email) = crate::oauth::fetch_account_email(&token).await {
1111                if let Some(c) = acc.credential.as_mut() { c.email = Some(email.clone()); }
1112                if let Some(stored) = store.accounts.get_mut(&acc.name) {
1113                    stored.email = Some(email);
1114                    store_dirty = true;
1115                }
1116            }
1117        }
1118    }
1119    if store_dirty {
1120        store.save().ok();
1121    }
1122
1123    // Build running address list: ":8082" or ":8082 · :8083"
1124    let addr_str = if !live_by_provider.is_empty() {
1125        let parts: Vec<String> = provider_urls.iter()
1126            .filter(|(label, _)| live_by_provider.contains_key(label.as_str()))
1127            .map(|(_, url)| {
1128                let port = url.rsplit(':').next().unwrap_or("?");
1129                cyan(&format!(":{port}"))
1130            })
1131            .collect();
1132        parts.join(&dim("  ·  "))
1133    } else {
1134        String::new()
1135    };
1136
1137    let proxy_line = if live.is_some() {
1138        format!("{}  {}  {}", green(DOT), green_bold("running"), addr_str)
1139    } else {
1140        let log_hint = if log_path().exists() {
1141            format!("  {}  {}", dim("·"), dim("shunt logs for details"))
1142        } else {
1143            String::new()
1144        };
1145        format!("{}  {}  {}{}", dim(EMPTY), dim("stopped"), dim("shunt start"), log_hint)
1146    };
1147
1148    let account_names: Vec<&str> = config.accounts.iter().map(|a| a.name.as_str()).collect();
1149    // Build savings summary if proxy is running and has data.
1150    let savings_line: Option<String> = live.and_then(|v| {
1151        let s = v.get("savings")?;
1152        let today_in  = s["today_input"].as_u64().unwrap_or(0);
1153        let today_out = s["today_output"].as_u64().unwrap_or(0);
1154        let today_cost = s["today_cost_usd"].as_f64().unwrap_or(0.0);
1155        let all_cost   = s["all_time_cost_usd"].as_f64().unwrap_or(0.0);
1156        if today_in + today_out == 0 && all_cost == 0.0 { return None; }
1157        let today_tok = crate::term::fmt_tokens(today_in + today_out);
1158        let cost_str  = crate::pricing::fmt_cost(today_cost);
1159        let all_str   = crate::pricing::fmt_cost(all_cost);
1160        Some(format!("{}  today {}  {}  {}  all time {}",
1161            dim("·"), dim(&today_tok), dim(&cost_str), dim("·"), dim(&all_str)))
1162    });
1163
1164    print_routing_header(&account_names, &[
1165        format!("{}  {}", brand_green("shunt"), dim(&format!("v{}", env!("CARGO_PKG_VERSION")))),
1166        proxy_line,
1167    ]);
1168
1169    if let Some(ref line) = savings_line {
1170        println!("  {line}");
1171        println!();
1172    }
1173
1174    let pinned_account = live.and_then(|v| v["pinned"].as_str()).map(|s| s.to_owned());
1175    let last_used_account = live.and_then(|v| v["last_used"].as_str()).map(|s| s.to_owned());
1176
1177    // Pinned notice
1178    if let Some(ref pinned) = pinned_account {
1179        println!("  {}  pinned to {}",
1180            yellow(DIAMOND), bold(pinned));
1181        println!("  {}  run {} to restore auto routing",
1182            dim("·"), cyan("shunt use auto"));
1183        println!();
1184    }
1185
1186    let now_secs = SystemTime::now().duration_since(UNIX_EPOCH).ok().map(|d| d.as_secs()).unwrap_or(0);
1187
1188    for acc in &config.accounts {
1189        let live_acc = live_by_provider.get(&acc.provider.to_string())
1190            .and_then(|v| v["accounts"].as_array())
1191            .and_then(|arr| arr.iter().find(|a| a["name"] == acc.name));
1192
1193        let status = live_acc.and_then(|a| a["status"].as_str()).unwrap_or("offline");
1194
1195        let (status_icon, status_text): (String, String) = match status {
1196            "available"       => (green(CHECK), green("available")),
1197            "cooling"         => (yellow("↻"),  yellow("cooling")),
1198            "disabled"        => (red(CROSS),   red("disabled")),
1199            "reauth_required" => (red(CROSS),   red("session expired")),
1200            _ => match &acc.credential {
1201                None                          => (red(CROSS),   red("no credential")),
1202                Some(c) if c.needs_refresh()  => (yellow(CROSS), yellow("token expired")),
1203                _                             => (dim(EMPTY),   dim("offline")),
1204            },
1205        };
1206
1207        let plan_label = if acc.provider == crate::provider::Provider::OpenAI {
1208            match acc.plan_type.to_lowercase().as_str() {
1209                "plus"  => "ChatGPT Plus",
1210                "pro"   => "ChatGPT Pro",
1211                "team"  => "ChatGPT Team",
1212                _       => "ChatGPT",
1213            }
1214        } else {
1215            match acc.plan_type.to_lowercase().as_str() {
1216                "max" | "claude_max" => "Claude Max",
1217                "team"               => "Claude Team",
1218                _                    => "Claude Pro",
1219            }
1220        };
1221        let email_str = acc.credential.as_ref().and_then(|c| c.email.as_deref()).unwrap_or("");
1222
1223        // ── routing tag ─────────────────────────────────────
1224        let is_pinned  = pinned_account.as_deref() == Some(&acc.name);
1225        let is_last    = !is_pinned && last_used_account.as_deref() == Some(&acc.name);
1226        let (routing_tag, tag_vis_len): (String, usize) = if is_pinned {
1227            (format!("  {}", yellow("pinned")), 8)
1228        } else if is_last {
1229            (format!("  {}", green("active")), 8)
1230        } else {
1231            (String::new(), 0)
1232        };
1233
1234        // ── account header (name + tag + plan) ──────────────
1235        println!("{}", card_header(&acc.name, &green_bold(&acc.name), &routing_tag, tag_vis_len, plan_label));
1236
1237        // ── email + provider badge row ───────────────────────
1238        let is_openai = acc.provider == crate::provider::Provider::OpenAI;
1239        let provider_badge = if is_openai { format!("  {}  {}", dim("·"), dim("openai")) } else { String::new() };
1240        if !email_str.is_empty() {
1241            println!("{}", card_row(&format!("{}{}", dim(email_str), provider_badge)));
1242        } else if is_openai {
1243            println!("{}", card_row(&dim("openai")));
1244        }
1245
1246        println!();
1247
1248        // ── status ───────────────────────────────────────────
1249        println!("{}", card_row(&format!("{}  {}", status_icon, status_text)));
1250
1251        // ── rate limit bars ──────────────────────────────────
1252        if let Some(rl) = live_acc.and_then(|a| a["rate_limit"].as_object()) {
1253            let util_5h   = rl.get("utilization_5h").and_then(|v| v.as_f64());
1254            let reset_5h  = rl.get("reset_5h").and_then(|v| v.as_u64());
1255            let status_5h = rl.get("status_5h").and_then(|v| v.as_str()).unwrap_or("allowed");
1256            let util_7d   = rl.get("utilization_7d").and_then(|v| v.as_f64());
1257            let reset_7d  = rl.get("reset_7d").and_then(|v| v.as_u64());
1258            let status_7d = rl.get("status_7d").and_then(|v| v.as_str()).unwrap_or("allowed");
1259
1260            let window_row = |label: &str, util: Option<f64>, reset: Option<u64>, wstatus: &str| {
1261                if reset.map(|t| t <= now_secs).unwrap_or(false) {
1262                    let ago = reset.map(|t| format!(
1263                        "  {} ago", term::fmt_duration_ms(now_secs.saturating_sub(t) * 1000)
1264                    )).unwrap_or_default();
1265                    println!("{}", card_row(&format!(
1266                        "{}  {}  {}{}",
1267                        dim(label), green(&"─".repeat(20)), green("fresh"), dim(&ago)
1268                    )));
1269                } else if let Some(u) = util {
1270                    let rem = 100u64.saturating_sub((u * 100.0) as u64);
1271                    let bar = util_bar(u, 20);
1272                    let reset_str = reset.and_then(|t| secs_until(t))
1273                        .map(|s| format!("  ·  resets in {}", term::fmt_duration_ms(s * 1000)))
1274                        .unwrap_or_default();
1275                    let pct = if wstatus == "exhausted" {
1276                        red("exhausted")
1277                    } else {
1278                        format!("{}% left", bold(&rem.to_string()))
1279                    };
1280                    println!("{}", card_row(&format!(
1281                        "{}  {}  {}{}",
1282                        dim(label), bar, pct, dim(&reset_str)
1283                    )));
1284                }
1285            };
1286
1287            if util_5h.is_some() || reset_5h.is_some() {
1288                window_row("5h", util_5h, reset_5h, status_5h);
1289            }
1290            if util_7d.is_some() || reset_7d.is_some() {
1291                window_row("7d", util_7d, reset_7d, status_7d);
1292            }
1293        } else if acc.credential.is_none() {
1294            println!("{}", card_row(&format!("{}  run {}",
1295                dim("·"), cyan(&format!("shunt add-account {}", acc.name)))));
1296        } else if status == "reauth_required" {
1297            println!("{}", card_row(&format!("{}  run {}",
1298                dim("·"), cyan(&format!("shunt add-account {}", acc.name)))));
1299        } else if live.is_some() && live_acc.is_some() {
1300            if acc.provider == crate::provider::Provider::Anthropic {
1301                println!("{}", card_row(&dim("· quota data will appear after first request")));
1302            } else {
1303                println!("{}", card_row(&dim("· quota tracking unavailable (OpenAI doesn't report utilization)")));
1304            }
1305        }
1306
1307        // ── separator ────────────────────────────────────────
1308        println!();
1309        println!("{}", card_sep());
1310        println!();
1311    }
1312
1313    Ok(())
1314}
1315
1316// ---------------------------------------------------------------------------
1317// use (pin account)
1318// ---------------------------------------------------------------------------
1319
1320async fn cmd_use(config_override: Option<PathBuf>, account: Option<String>) -> Result<()> {
1321    let config = crate::config::load_config(config_override.as_deref())?;
1322    let use_url = format!("http://{}:{}/use", config.server.host, config.server.port);
1323
1324    // Fetch live state for utilization info
1325    let live: Option<serde_json::Value> = reqwest::get(
1326        &format!("http://{}:{}/status", config.server.host, config.server.port)
1327    ).await.ok().and_then(|r| futures_executor_hack(r));
1328
1329    let current_pinned = live.as_ref()
1330        .and_then(|v| v["pinned"].as_str())
1331        .map(|s| s.to_owned());
1332
1333    // Build menu items
1334    let mut items: Vec<term::SelectItem> = config.accounts.iter().map(|a| {
1335        let live_acc = live.as_ref()
1336            .and_then(|v| v["accounts"].as_array())
1337            .and_then(|arr| arr.iter().find(|x| x["name"] == a.name));
1338
1339        let status = live_acc.and_then(|x| x["status"].as_str()).unwrap_or("offline");
1340        let util = live_acc.and_then(|x| x["rate_limit"]["utilization_5h"].as_f64());
1341        let is_pinned = current_pinned.as_deref() == Some(&a.name);
1342
1343        let status_str = match status {
1344            "reauth_required" => red("session expired"),
1345            "disabled"        => red("disabled"),
1346            "cooling"         => yellow("cooling"),
1347            "available"       => {
1348                match util {
1349                    Some(u) => {
1350                        let rem = 100u64.saturating_sub((u * 100.0) as u64);
1351                        green(&format!("{}% remaining", rem))
1352                    }
1353                    None => dim("fresh").to_string(),
1354                }
1355            }
1356            _ => dim("offline").to_string(),
1357        };
1358
1359        let email = a.credential.as_ref().and_then(|c| c.email.as_deref()).unwrap_or("");
1360        let pin = if is_pinned { format!("  {}", yellow("pinned")) } else { String::new() };
1361
1362        term::SelectItem {
1363            label: format!("{}  {}  {}{}", bold(&pad(&a.name, 12)), dim(&pad(email, 32)), status_str, pin),
1364            value: a.name.clone(),
1365        }
1366    }).collect();
1367
1368    let auto_marker = if current_pinned.is_none() { format!("  {}", yellow("active")) } else { String::new() };
1369    items.push(term::SelectItem {
1370        label: format!("{}  {}{}", bold(&pad("auto", 12)), dim("least-utilization routing"), auto_marker),
1371        value: "auto".to_owned(),
1372    });
1373
1374    // Determine initial cursor position (current pinned account or auto)
1375    let initial = current_pinned.as_ref()
1376        .and_then(|p| items.iter().position(|it| &it.value == p))
1377        .unwrap_or(items.len() - 1);
1378
1379    // If account name was given directly, skip the picker
1380    let chosen = if let Some(name) = account {
1381        name
1382    } else {
1383        match term::select("Route traffic to:", &items, initial) {
1384            Some(v) => v,
1385            None => return Ok(()), // cancelled
1386        }
1387    };
1388
1389    // Validate
1390    let is_auto = chosen == "auto";
1391    if !is_auto && !config.accounts.iter().any(|a| a.name == chosen) {
1392        let names: Vec<_> = config.accounts.iter().map(|a| a.name.as_str()).collect();
1393        anyhow::bail!("Unknown account '{}'. Available: {}", chosen, names.join(", "));
1394    }
1395
1396    let client = reqwest::Client::new();
1397    let resp = client
1398        .post(&use_url)
1399        .json(&serde_json::json!({ "account": chosen }))
1400        .send()
1401        .await;
1402
1403    match resp {
1404        Ok(r) if r.status().is_success() => {
1405            if is_auto {
1406                println!("  {} Automatic routing restored", green(CHECK));
1407            } else {
1408                println!("  {} Pinned to {}  ·  {}", green(CHECK), bold(&chosen), dim("shunt use auto to restore"));
1409            }
1410            println!();
1411        }
1412        Ok(r) => {
1413            let body = r.text().await.unwrap_or_default();
1414            anyhow::bail!("Proxy returned error: {body}");
1415        }
1416        Err(_) => {
1417            // Proxy not running — persist directly to the state file so it
1418            // takes effect when the proxy next starts.
1419            write_pinned_to_state(if is_auto { None } else { Some(chosen.clone()) });
1420            if is_auto {
1421                println!("  {} Automatic routing saved  ·  {}", green(CHECK),
1422                    dim("applies on next shunt start"));
1423            } else {
1424                println!("  {} Pinned to {}  ·  {}", green(CHECK), bold(&chosen),
1425                    dim("applies on next shunt start"));
1426            }
1427            println!();
1428        }
1429    }
1430    Ok(())
1431}
1432
1433/// Write a pinned account directly into the state file (used when proxy is not running).
1434fn write_pinned_to_state(account: Option<String>) {
1435    let path = crate::config::state_path();
1436    let mut data: serde_json::Value = path.exists()
1437        .then(|| std::fs::read_to_string(&path).ok())
1438        .flatten()
1439        .and_then(|t| serde_json::from_str(&t).ok())
1440        .unwrap_or_else(|| serde_json::json!({}));
1441    data["pinned_account"] = match account {
1442        Some(a) => serde_json::Value::String(a),
1443        None => serde_json::Value::Null,
1444    };
1445    if let Some(parent) = path.parent() { let _ = std::fs::create_dir_all(parent); }
1446    let tmp = path.with_extension("tmp");
1447    if let Ok(text) = serde_json::to_string_pretty(&data) {
1448        let _ = std::fs::write(&tmp, text);
1449        let _ = std::fs::rename(&tmp, &path);
1450    }
1451}
1452
1453/// Synchronously awaits a reqwest response to get its JSON.
1454fn futures_executor_hack(resp: reqwest::Response) -> Option<serde_json::Value> {
1455    tokio::task::block_in_place(|| {
1456        tokio::runtime::Handle::current().block_on(async {
1457            resp.json::<serde_json::Value>().await.ok()
1458        })
1459    })
1460}
1461
1462// ---------------------------------------------------------------------------
1463// Helpers
1464// ---------------------------------------------------------------------------
1465
1466/// Circuit shunt symbol: rectangle with wires extending left/right from the mid row,
1467/// and two legs going down from the bottom.
1468///
1469///   ·  ██████  ·
1470///   ███      ███   ← wire row (middle of box)
1471///   ·  ██████  ·
1472///   ·    █ █   ·   ← legs
1473fn build_logo_lines(h: usize, w: usize) -> Vec<String> {
1474    if h == 0 || w < 5 { return vec![]; }
1475
1476    let box_l = w / 4;
1477    let box_r = w - w / 4;  // exclusive
1478    let leg_h = (h / 4).max(1);
1479    let box_h = h.saturating_sub(leg_h).max(2); // at least top + bottom row
1480    let wire_row = box_h / 2; // wire connects at vertical mid of box
1481
1482    // Mirror from each side so legs are symmetric around centre.
1483    let leg1 = w / 3;
1484    let leg2 = w - w / 3 - 1;
1485
1486    let mut out = Vec::new();
1487    for row in 0..h {
1488        let mut r = vec![' '; w];
1489        if row < box_h {
1490            let is_top = row == 0;
1491            let is_bot = row == box_h - 1;
1492            if is_top || is_bot {
1493                for j in box_l..box_r { r[j] = '█'; }
1494            } else {
1495                r[box_l]     = '█';
1496                r[box_r - 1] = '█';
1497            }
1498            if row == wire_row {
1499                for j in 0..box_l  { r[j] = '█'; }
1500                for j in box_r..w  { r[j] = '█'; }
1501            }
1502        } else {
1503            if leg1 < w { r[leg1] = '█'; }
1504            if leg2 < w { r[leg2] = '█'; }
1505        }
1506        out.push(r.into_iter().collect());
1507    }
1508    out
1509}
1510
1511fn render_splash_frame(
1512    f: &mut ratatui::Frame,
1513    title_raw: &str,
1514    subtitle_raw: &str,
1515) {
1516    use ratatui::{
1517        layout::{Constraint, Direction, Layout},
1518        style::{Color, Style},
1519        text::Line,
1520        widgets::{Block, Borders, Paragraph},
1521    };
1522
1523    let brand   = Color::Rgb(188, 255, 96);  // #bcff60
1524    let dim_col = Color::Rgb(100, 160, 40);  // #bcff60 dimmed
1525
1526    // Fixed-width box — does not stretch to fill the terminal.
1527    const BOX_W: u16 = 70;
1528    let full = f.area();
1529    let area = Layout::new(Direction::Horizontal, [
1530        Constraint::Length(BOX_W.min(full.width)),
1531        Constraint::Fill(1),
1532    ]).split(full)[0];
1533
1534    // Outer bordered box.
1535    let outer = Block::default()
1536        .borders(Borders::ALL)
1537        .border_style(Style::default().fg(brand))
1538        .title(Line::styled(format!(" {title_raw} "), Style::default().fg(brand)));
1539    let inner = outer.inner(area);
1540    f.render_widget(outer, area);
1541
1542    const CONTENT_H: u16 = 4;
1543    const LOGO_W:    u16 = 10;
1544
1545    // Main horizontal split: left half | separator | right half
1546    let cols = Layout::new(Direction::Horizontal, [
1547        Constraint::Fill(1),
1548        Constraint::Length(1),
1549        Constraint::Fill(1),
1550    ]).split(inner);
1551    let (left_area, sep_area, right_area) = (cols[0], cols[1], cols[2]);
1552
1553    // Left: vertical centering around the content row.
1554    let has_sub = !subtitle_raw.is_empty();
1555    let left_v_constraints: Vec<Constraint> = if has_sub {
1556        vec![Constraint::Fill(1), Constraint::Length(CONTENT_H), Constraint::Fill(1), Constraint::Length(1)]
1557    } else {
1558        vec![Constraint::Fill(1), Constraint::Length(CONTENT_H), Constraint::Fill(1)]
1559    };
1560    let left_v = Layout::new(Direction::Vertical, left_v_constraints).split(left_area);
1561    let content_row = left_v[1];
1562
1563    // Left content: logo centered horizontally within the left half
1564    let h = Layout::new(Direction::Horizontal, [
1565        Constraint::Fill(1),
1566        Constraint::Length(LOGO_W),
1567        Constraint::Fill(1),
1568    ]).split(content_row);
1569
1570    let logo = build_logo_lines(CONTENT_H as usize, LOGO_W as usize);
1571    f.render_widget(
1572        Paragraph::new(logo.into_iter()
1573            .map(|l| Line::styled(l, Style::default().fg(brand)))
1574            .collect::<Vec<_>>()),
1575        h[1],
1576    );
1577
1578    if has_sub {
1579        f.render_widget(
1580            Paragraph::new(subtitle_raw).style(Style::default().fg(dim_col)),
1581            left_v[3],
1582        );
1583    }
1584
1585    // Vertical separator spanning full inner height.
1586    let sep_lines: Vec<Line> = (0..sep_area.height)
1587        .map(|_| Line::styled("│", Style::default().fg(dim_col)))
1588        .collect();
1589    f.render_widget(Paragraph::new(sep_lines), sep_area);
1590
1591    // Right: brief description, vertically centered, with left padding.
1592    let desc: Vec<Line> = vec![
1593        Line::styled("Pool multiple Claude accounts", Style::default().fg(dim_col)),
1594        Line::styled("behind a single endpoint.", Style::default().fg(dim_col)),
1595        Line::styled("Maximise rate limits across", Style::default().fg(dim_col)),
1596        Line::styled("all accounts automatically.", Style::default().fg(dim_col)),
1597    ];
1598    let desc_h = desc.len() as u16;
1599    let right_v = Layout::new(Direction::Vertical, [
1600        Constraint::Fill(1),
1601        Constraint::Length(desc_h),
1602        Constraint::Fill(1),
1603    ]).split(right_area);
1604    let right_h = Layout::new(Direction::Horizontal, [
1605        Constraint::Fill(1),
1606        Constraint::Length(2),
1607    ]).split(right_v[1]);
1608    f.render_widget(
1609        Paragraph::new(desc).alignment(ratatui::layout::Alignment::Right),
1610        right_h[0],
1611    );
1612}
1613
1614
1615/// Print the splash using ratatui inline viewport — redraws live on resize.
1616fn print_splash(info: &[String]) {
1617    use ratatui::{backend::CrosstermBackend, Terminal, TerminalOptions, Viewport};
1618    use crossterm::{event::{self, Event}, terminal as cterm};
1619    use std::io::stdout;
1620
1621    let title_raw    = info.get(0).map(|s| strip_ansi(s)).unwrap_or_default();
1622    let subtitle_raw = info.get(1).map(|s| strip_ansi(s)).unwrap_or_default();
1623
1624    // Logo = 4 rows content + 2 border + 2 vertical padding + optional subtitle
1625    let splash_h: u16 = 4 + 2 + 2 + if subtitle_raw.is_empty() { 0 } else { 1 };
1626
1627    let mut terminal = match Terminal::with_options(
1628        CrosstermBackend::new(stdout()),
1629        TerminalOptions { viewport: Viewport::Inline(splash_h) },
1630    ) {
1631        Ok(t) => t,
1632        Err(_) => {
1633            // Fallback: plain text header if ratatui fails (e.g. non-TTY).
1634            println!("\n  ◆  {}  {}\n", title_raw.trim(), subtitle_raw);
1635            return;
1636        }
1637    };
1638
1639    let draw = |t: &mut Terminal<CrosstermBackend<std::io::Stdout>>| {
1640        t.draw(|f| render_splash_frame(f, &title_raw, &subtitle_raw)).ok();
1641    };
1642
1643    draw(&mut terminal);
1644
1645    // Redraw on resize for up to 500 ms.
1646    let _ = cterm::enable_raw_mode();
1647    let dl = std::time::Instant::now() + std::time::Duration::from_millis(500);
1648    loop {
1649        let rem = dl.saturating_duration_since(std::time::Instant::now());
1650        if rem.is_zero() { break; }
1651        if event::poll(rem).unwrap_or(false) {
1652            match event::read() {
1653                Ok(Event::Resize(_, _)) => draw(&mut terminal),
1654                _ => break,
1655            }
1656        } else { break; }
1657    }
1658    let _ = cterm::disable_raw_mode();
1659    let _ = terminal.show_cursor();
1660    println!(); // move cursor to next line after the inline viewport
1661}
1662
1663// ---------------------------------------------------------------------------
1664// Account card helpers  (used by cmd_status)
1665// ---------------------------------------------------------------------------
1666
1667/// Target visible width for account header lines and separators.
1668const CARD_W: usize = 58;
1669
1670/// Account header: "  ◆  name  tag                     Plan"
1671fn card_header(name: &str, name_c: &str, routing_tag: &str, tag_vis: usize, plan: &str) -> String {
1672    // Visible prefix: "  ◆  " = 5, then name (name.len()), then tag (tag_vis)
1673    let left_vis = 5 + name.len() + tag_vis;
1674    let gap = CARD_W.saturating_sub(left_vis + plan.len());
1675    format!("  {}  {}{}{}{}", brand_green(DIAMOND), name_c, routing_tag, " ".repeat(gap), dim(plan))
1676}
1677
1678/// An indented content row: "    content"
1679fn card_row(content: &str) -> String {
1680    format!("    {content}")
1681}
1682
1683/// Thin separator line between accounts.
1684fn card_sep() -> String {
1685    format!("  {}", dim(&"─".repeat(CARD_W - 2)))
1686}
1687
1688/// Routing diagram — account names in bold green, connectors in dark green.
1689///
1690/// 1 account:           2 accounts:          3+ accounts:
1691///   main  ─→  [info]    main ─┐ →  [info]    main ─┐
1692///             [info1]   work ─┘     [info1]   work ─┼─→  [info]
1693///                                             sec  ─┘     [info1]
1694fn print_routing_header(account_names: &[&str], info: &[String]) {
1695    println!();
1696    let n = account_names.len();
1697    let name_w = account_names.iter().map(|s| s.len()).max().unwrap_or(4);
1698    let info0 = info.get(0).map(|s| s.as_str()).unwrap_or("");
1699    let info1 = info.get(1).map(|s| s.as_str()).unwrap_or("");
1700
1701    match n {
1702        0 => {
1703            // No accounts yet — clean two-line header
1704            println!("  {}  {}", brand_green(DIAMOND), info0);
1705            if !info1.is_empty() {
1706                println!("       {}", info1);
1707            }
1708        }
1709        1 => {
1710            // "  name  ─→  info0"  (info1 indented to same column)
1711            let indent = name_w + 8; // 2 + name + 2 + "─→" + 2
1712            println!("  {}  {}  {}", green_bold(account_names[0]), dark_green("─→"), info0);
1713            if !info1.is_empty() {
1714                println!("  {}{}", " ".repeat(indent), info1);
1715            }
1716        }
1717        2 => {
1718            // "  name0 ─┐ →  info0"
1719            // "  name1 ─┘     info1"
1720            println!("  {}  {} {}  {}",
1721                green_bold(&pad(account_names[0], name_w)),
1722                dark_green("─┐"), dark_green("→"), info0);
1723            println!("  {}  {}    {}",
1724                green_bold(&pad(account_names[1], name_w)),
1725                dark_green("─┘"), info1);
1726        }
1727        3 => {
1728            // "  name0 ─┐"
1729            // "  name1 ─┼─→  info0"
1730            // "  name2 ─┘     info1"
1731            println!("  {}  {}", green_bold(&pad(account_names[0], name_w)), dark_green("─┐"));
1732            println!("  {}  {}  {}",
1733                green_bold(&pad(account_names[1], name_w)),
1734                dark_green("─┼─→"), info0);
1735            println!("  {}  {}    {}",
1736                green_bold(&pad(account_names[2], name_w)),
1737                dark_green("─┘"), info1);
1738        }
1739        _ => {
1740            // "  name0      ─┐"
1741            // "  + N more   ─┼─→  info0"
1742            // "  nameN      ─┘     info1"
1743            let more = dim(&pad(&format!("+ {} more", n - 2), name_w));
1744            println!("  {}  {}", green_bold(&pad(account_names[0], name_w)), dark_green("─┐"));
1745            println!("  {}  {}  {}", more, dark_green("─┼─→"), info0);
1746            println!("  {}  {}    {}",
1747                green_bold(&pad(account_names[n - 1], name_w)),
1748                dark_green("─┘"), info1);
1749        }
1750    }
1751
1752    println!();
1753}
1754
1755/// Capacity bar — `util` is 0.0–1.0; filled blocks show REMAINING capacity.
1756/// Green = plenty left, yellow = getting low, red = nearly exhausted.
1757fn util_bar(util: f64, width: usize) -> String {
1758    let used = (util.clamp(0.0, 1.0) * width as f64).round() as usize;
1759    let free = width.saturating_sub(used);
1760    // filled = remaining, empty = used — so a full bar means lots of quota left
1761    let bar = format!("{}{}", "█".repeat(free), "░".repeat(used));
1762    let pct = (util * 100.0) as u64;
1763    if pct < 50 { green(&bar) } else if pct < 80 { yellow(&bar) } else { red(&bar) }
1764}
1765
1766/// Seconds until a Unix-epoch reset timestamp. Returns None if past or zero.
1767fn secs_until(epoch_secs: u64) -> Option<u64> {
1768    let now = SystemTime::now().duration_since(UNIX_EPOCH).ok()?.as_secs();
1769    epoch_secs.checked_sub(now).filter(|&s| s > 0)
1770}
1771
1772// ---------------------------------------------------------------------------
1773// Multi-provider listener helpers
1774// ---------------------------------------------------------------------------
1775
1776/// Returns `(provider_label, url)` pairs for every provider present in accounts,
1777/// using `primary_port` for Anthropic and each provider's default port for others.
1778fn listener_addrs(
1779    accounts: &[crate::config::AccountConfig],
1780    host: &str,
1781    primary_port: u16,
1782) -> Vec<(String, String)> {
1783    use crate::provider::Provider;
1784    use std::collections::BTreeSet;
1785
1786    let providers: BTreeSet<String> = accounts.iter()
1787        .map(|a| a.provider.to_string())
1788        .collect();
1789
1790    providers.into_iter().map(|p| {
1791        let port = match Provider::from_str(&p) {
1792            Provider::Anthropic => primary_port,
1793            other => other.default_port(),
1794        };
1795        (p.clone(), format!("http://{host}:{port}"))
1796    }).collect()
1797}
1798
1799/// Bind a listener and spawn an axum server for each provider group found in
1800/// `config.accounts`. All servers run concurrently; the function returns when
1801/// the first one stops (error or clean shutdown).
1802async fn serve_all_providers(
1803    config: crate::config::Config,
1804    state: crate::state::StateStore,
1805    host: &str,
1806    primary_port: u16,
1807) -> anyhow::Result<()> {
1808    use crate::config::{Config, ServerConfig};
1809    use crate::provider::Provider;
1810    use std::collections::HashMap;
1811
1812    // Group accounts by provider.
1813    let mut by_provider: HashMap<String, Vec<crate::config::AccountConfig>> = HashMap::new();
1814    for account in config.accounts {
1815        by_provider.entry(account.provider.to_string()).or_default().push(account);
1816    }
1817
1818    let mut handles = Vec::new();
1819
1820    for (provider_str, accounts) in by_provider {
1821        let provider = Provider::from_str(&provider_str);
1822        let port = match provider {
1823            Provider::Anthropic => primary_port,
1824            ref other => other.default_port(),
1825        };
1826
1827        let provider_config = Config {
1828            accounts,
1829            server: ServerConfig {
1830                host: host.to_owned(),
1831                port,
1832                upstream_url: provider.default_upstream_url().to_owned(),
1833                ..config.server.clone()
1834            },
1835            config_file: config.config_file.clone(),
1836        };
1837
1838        let anthropic_url = if provider == Provider::OpenAI {
1839            Some(format!("http://{}:{}", host, primary_port))
1840        } else {
1841            None
1842        };
1843        let (app, live_creds) = crate::proxy::create_app_with_state(provider_config.clone(), state.clone(), anthropic_url)?;
1844        let listener = tokio::net::TcpListener::bind(format!("{host}:{port}"))
1845            .await
1846            .with_context(|| format!("cannot bind {host}:{port} for {provider_str} proxy"))?;
1847
1848        let cfg_arc = std::sync::Arc::new(provider_config);
1849        tokio::spawn(crate::proxy::prefetch_rate_limits(cfg_arc.clone(), state.clone(), live_creds.clone()));
1850        tokio::spawn(crate::proxy::openai_token_refresh_loop(cfg_arc.clone(), state.clone(), live_creds.clone()));
1851        tokio::spawn(crate::proxy::cooldown_watcher(cfg_arc.clone(), state.clone(), live_creds.clone()));
1852        tokio::spawn(crate::proxy::recovery_watcher(cfg_arc, state.clone(), live_creds));
1853        handles.push(tokio::spawn(async move {
1854            axum::serve(listener, app).await
1855        }));
1856    }
1857
1858    if handles.is_empty() {
1859        return Ok(());
1860    }
1861
1862    // Wait until the first listener stops, then exit (whole daemon restarts on error).
1863    let (result, _idx, _rest) = futures_util::future::select_all(handles).await;
1864    result??;
1865    Ok(())
1866}
1867
1868fn write_pid() {
1869    let p = pid_path();
1870    if let Some(dir) = p.parent() { let _ = std::fs::create_dir_all(dir); }
1871    let _ = std::fs::write(&p, std::process::id().to_string());
1872}
1873
1874/// PIDs of processes listening on the given port.
1875fn port_pids(port: u16) -> Vec<u32> {
1876    let out = std::process::Command::new("lsof")
1877        .args(["-ti", &format!(":{port}")])
1878        .output();
1879    let Ok(out) = out else { return vec![] };
1880    String::from_utf8_lossy(&out.stdout)
1881        .split_whitespace()
1882        .filter_map(|s| s.parse().ok())
1883        .collect()
1884}
1885
1886#[allow(dead_code)]
1887fn kill_port(port: u16) -> bool {
1888    let pids = port_pids(port);
1889    let mut any = false;
1890    for pid in pids {
1891        if std::process::Command::new("kill").arg(pid.to_string()).status().map(|s| s.success()).unwrap_or(false) {
1892            any = true;
1893        }
1894    }
1895    any
1896}
1897
1898/// Pad a string to display width using spaces (strips ANSI codes first; handles Unicode).
1899fn pad(s: &str, width: usize) -> String {
1900    use unicode_width::UnicodeWidthStr;
1901    let visible_width = UnicodeWidthStr::width(strip_ansi(s).as_str());
1902    if visible_width >= width {
1903        s.to_owned()
1904    } else {
1905        format!("{s}{}", " ".repeat(width - visible_width))
1906    }
1907}
1908
1909fn strip_ansi(s: &str) -> String {
1910    let mut out = String::with_capacity(s.len());
1911    let mut chars = s.chars().peekable();
1912    while let Some(c) = chars.next() {
1913        if c == '\x1b' {
1914            if chars.peek() == Some(&'[') {
1915                chars.next();
1916                while let Some(&next) = chars.peek() {
1917                    chars.next();
1918                    if next.is_ascii_alphabetic() { break; }
1919                }
1920            }
1921        } else {
1922            out.push(c);
1923        }
1924    }
1925    out
1926}
1927
1928// ---------------------------------------------------------------------------
1929// monitor
1930// ---------------------------------------------------------------------------
1931
1932async fn cmd_monitor(config_override: Option<PathBuf>) -> Result<()> {
1933    let config = crate::config::load_config(config_override.as_deref())?;
1934    let base_url = format!("http://{}:{}", config.server.host, config.server.port);
1935
1936    // Quick check: is the proxy running?
1937    if reqwest::get(format!("{base_url}/health")).await.is_err() {
1938        println!();
1939        println!("  {} Proxy is not running.", red(CROSS));
1940        println!("  {} Start it first with {}.", dim("·"), cyan("shunt start"));
1941        println!();
1942        return Ok(());
1943    }
1944
1945    crate::monitor::run_monitor(&base_url).await
1946}
1947
1948// ---------------------------------------------------------------------------
1949// remote
1950// ---------------------------------------------------------------------------
1951
1952async fn cmd_remote(code: Option<String>) -> Result<()> {
1953    // Host mode needs the local shunt URL; client mode only needs the relay URL.
1954    let (relay_url, local_url) = if code.is_none() {
1955        let config = crate::config::load_config(None)?;
1956        let local = format!("http://{}:{}", config.server.host, config.server.port);
1957        let relay = config.server.relay_url.clone();
1958        (Some(relay), local)
1959    } else {
1960        let relay_url = std::env::var("SHUNT_RELAY_URL").ok();
1961        (relay_url, String::new())
1962    };
1963    crate::remote::run_remote(code, relay_url, local_url).await
1964}
1965
1966// update
1967// ---------------------------------------------------------------------------
1968
1969async fn cmd_update() -> Result<()> {
1970    const REPO: &str = "ramc10/shunt";
1971    let current = env!("CARGO_PKG_VERSION");
1972
1973    print_splash(&[
1974        format!("{}  {}", brand_green("shunt"), dim(&format!("v{current}"))),
1975    ]);
1976    println!("  {} Checking for updates…", dim("·"));
1977
1978    // Fetch latest release from GitHub API
1979    let client = reqwest::Client::builder()
1980        .user_agent("shunt-updater")
1981        .connect_timeout(std::time::Duration::from_secs(10))
1982        .timeout(std::time::Duration::from_secs(120))
1983        .build()?;
1984
1985    let api_url = format!("https://api.github.com/repos/{REPO}/releases/latest");
1986    let resp = client.get(&api_url).send().await
1987        .context("Failed to reach GitHub API")?;
1988
1989    if !resp.status().is_success() {
1990        bail!("GitHub API returned {}", resp.status());
1991    }
1992
1993    let json: serde_json::Value = resp.json().await?;
1994    let latest_tag = json["tag_name"].as_str().context("Missing tag_name in release")?;
1995    let latest = latest_tag.trim_start_matches('v');
1996
1997    if latest == current {
1998        println!("  {} Already up to date ({})", green(CHECK), bold(&format!("v{current}")));
1999        println!();
2000        return Ok(());
2001    }
2002
2003    println!("  {} Update available: {}  →  {}", green("↑"),
2004        dim(&format!("v{current}")), bold_white(&format!("v{latest}")));
2005    println!();
2006
2007    // Detect platform
2008    let target = detect_update_target()?;
2009    let archive_name = format!("shunt-v{latest}-{target}.tar.gz");
2010    let url = format!(
2011        "https://github.com/{REPO}/releases/download/v{latest}/{archive_name}"
2012    );
2013
2014    print!("  {} Downloading {}… ", dim("↓"), dim(&archive_name));
2015    use std::io::Write as _;
2016    std::io::stdout().flush().ok();
2017
2018    let resp = client.get(&url).send().await
2019        .context("Download request failed")?;
2020
2021    if !resp.status().is_success() {
2022        bail!("Download failed: HTTP {} for {url}", resp.status());
2023    }
2024
2025    let bytes = resp.bytes().await
2026        .context("Failed to read download")?;
2027
2028    // Sanity-check: gzip magic bytes are 0x1f 0x8b
2029    if bytes.len() < 2 || bytes[0] != 0x1f || bytes[1] != 0x8b {
2030        bail!(
2031            "Downloaded file does not look like a gzip archive ({} bytes, first bytes: {:02x?})",
2032            bytes.len(), &bytes[..bytes.len().min(4)]
2033        );
2034    }
2035
2036    println!("{}", green("done"));
2037
2038    // Extract binary from tarball into a temp file next to the current exe
2039    let exe_path = std::env::current_exe().context("Cannot locate current executable")?;
2040    let tmp_path = exe_path.with_extension("tmp");
2041
2042    extract_binary_from_tarball(&bytes, &tmp_path)
2043        .context("Failed to extract binary from archive")?;
2044
2045    // Replace current executable atomically
2046    #[cfg(unix)]
2047    {
2048        use std::os::unix::fs::PermissionsExt;
2049        std::fs::set_permissions(&tmp_path, std::fs::Permissions::from_mode(0o755))?;
2050    }
2051    std::fs::rename(&tmp_path, &exe_path)
2052        .context("Failed to replace binary (try running with sudo?)")?;
2053
2054    // macOS: remove quarantine and ad-hoc sign so Gatekeeper allows unsigned binaries
2055    #[cfg(target_os = "macos")]
2056    {
2057        let p = exe_path.display().to_string();
2058        std::process::Command::new("xattr").args(["-d", "com.apple.quarantine", &p]).status().ok();
2059        std::process::Command::new("codesign").args(["--force", "--deep", "--sign", "-", &p]).status().ok();
2060    }
2061
2062    println!("  {} Updated to {}", green(CHECK), bold_white(&format!("v{latest}")));
2063    println!();
2064    Ok(())
2065}
2066
2067fn detect_update_target() -> Result<&'static str> {
2068    match (std::env::consts::OS, std::env::consts::ARCH) {
2069        ("macos",  "aarch64") => Ok("aarch64-apple-darwin"),
2070        ("linux",  "x86_64")  => Ok("x86_64-unknown-linux-gnu"),
2071        ("linux",  "aarch64") => Ok("aarch64-unknown-linux-gnu"),
2072        (os, arch) => bail!("No pre-built binary for {os}/{arch}. Build from source: cargo install shunt-proxy"),
2073    }
2074}
2075
2076fn extract_binary_from_tarball(data: &[u8], dest: &std::path::Path) -> Result<()> {
2077    let gz = flate2::read::GzDecoder::new(data);
2078    let mut archive = tar::Archive::new(gz);
2079    for entry in archive.entries()? {
2080        let mut entry = entry?;
2081        let path = entry.path()?;
2082        if path.file_name().and_then(|n| n.to_str()) == Some("shunt") {
2083            let mut out = std::fs::File::create(dest)?;
2084            std::io::copy(&mut entry, &mut out)?;
2085            return Ok(());
2086        }
2087    }
2088    bail!("Binary 'shunt' not found in archive")
2089}
2090
2091// ---------------------------------------------------------------------------
2092// share
2093// ---------------------------------------------------------------------------
2094
2095async fn cmd_share(config_override: Option<PathBuf>, tunnel: bool, stop: bool) -> Result<()> {
2096    let config_p = config_override.unwrap_or_else(config_path);
2097    if !config_p.exists() {
2098        bail!("No config found. Run `shunt setup` first.");
2099    }
2100
2101    let mut text = std::fs::read_to_string(&config_p)?;
2102
2103    // If no flags given, show interactive menu
2104    // use an enum to track the chosen mode cleanly
2105    #[derive(Debug)]
2106    enum ShareMode { Lan, Tunnel, CustomDomain, Stop }
2107
2108    let mode: ShareMode = if tunnel {
2109        ShareMode::Tunnel
2110    } else if stop {
2111        ShareMode::Stop
2112    } else {
2113        print_splash(&[
2114            format!("{}  {}", brand_green("shunt"), dim(&format!("v{}", env!("CARGO_PKG_VERSION")))),
2115            dim("Remote sharing").to_string(),
2116            String::new(),
2117        ]);
2118        let top_items = vec![
2119            term::SelectItem {
2120                label: format!("{}  {}", bold("Local network (LAN)"),
2121                    dim("— same Wi-Fi only, no internet required")),
2122                value: "lan".into(),
2123            },
2124            term::SelectItem {
2125                label: format!("{}  {}", bold("Online"),
2126                    dim("— share over the internet")),
2127                value: "online".into(),
2128            },
2129            term::SelectItem {
2130                label: format!("{}  {}", bold("Stop sharing"),
2131                    dim("— revert to localhost-only")),
2132                value: "stop".into(),
2133            },
2134        ];
2135        match term::select("How do you want to share?", &top_items, 0).as_deref() {
2136            Some("lan")    => ShareMode::Lan,
2137            Some("stop")   => ShareMode::Stop,
2138            Some("online") => {
2139                // Sub-menu: temporary vs custom domain
2140                let existing_domain = crate::config::load_config(Some(&config_p))
2141                    .ok()
2142                    .and_then(|c| c.server.custom_domain.clone());
2143                let domain_label = match &existing_domain {
2144                    Some(d) => format!("{}  {}",
2145                        bold("Custom domain (permanent)"),
2146                        dim(&format!("— {} · your domain", d))),
2147                    None => format!("{}  {}",
2148                        bold("Custom domain (permanent)"),
2149                        dim("— your own domain, always-on")),
2150                };
2151                let online_items = vec![
2152                    term::SelectItem {
2153                        label: format!("{}  {}",
2154                            bold("Temporary (Cloudflare tunnel)"),
2155                            dim("— free, random URL, session only")),
2156                        value: "tunnel".into(),
2157                    },
2158                    term::SelectItem {
2159                        label: domain_label,
2160                        value: "custom".into(),
2161                    },
2162                ];
2163                match term::select("Online sharing type:", &online_items, 0).as_deref() {
2164                    Some("tunnel") => ShareMode::Tunnel,
2165                    Some("custom") => ShareMode::CustomDomain,
2166                    _ => return Ok(()),
2167                }
2168            }
2169            _ => return Ok(()),
2170        }
2171    };
2172
2173    if matches!(mode, ShareMode::Stop) {
2174        // Reconfirm before disabling
2175        if !term::confirm("Stop sharing and revert to localhost-only?") {
2176            println!("  {} Cancelled.", dim("·"));
2177            println!();
2178            return Ok(());
2179        }
2180
2181        text = text.lines()
2182            .filter(|l| !l.trim_start().starts_with("remote_key"))
2183            .collect::<Vec<_>>()
2184            .join("\n");
2185        if !text.ends_with('\n') { text.push('\n'); }
2186        text = text.replace("host = \"0.0.0.0\"", "host = \"127.0.0.1\"");
2187        std::fs::write(&config_p, &text)?;
2188
2189        print_splash(&[
2190            format!("{}  {}", brand_green("shunt"), dim(&format!("v{}", env!("CARGO_PKG_VERSION")))),
2191            dim("Remote sharing disabled").to_string(),
2192            String::new(),
2193        ]);
2194        println!("  {} Restart to apply: {}", dim("·"), cyan("shunt start"));
2195        println!();
2196        return Ok(());
2197    }
2198
2199    // Generate or reuse existing remote key
2200    let key = match extract_remote_key(&text) {
2201        Some(k) => k,
2202        None => {
2203            let k = generate_remote_key();
2204            text = insert_into_server_section(&text, &format!("remote_key = \"{k}\""));
2205            k
2206        }
2207    };
2208
2209    // Ensure host is 0.0.0.0
2210    if text.contains("host = \"127.0.0.1\"") {
2211        text = text.replace("host = \"127.0.0.1\"", "host = \"0.0.0.0\"");
2212    }
2213
2214    std::fs::write(&config_p, &text)?;
2215
2216    let (port, relay_url, saved_domain) = match crate::config::load_config(Some(&config_p)) {
2217        Ok(cfg) => {
2218            let relay = std::env::var("SHUNT_RELAY_URL")
2219                .unwrap_or_else(|_| cfg.server.relay_url.clone());
2220            (cfg.server.port, relay, cfg.server.custom_domain)
2221        }
2222        Err(_) => (8082u16,
2223            std::env::var("SHUNT_RELAY_URL")
2224                .unwrap_or_else(|_| "https://relay.ramcharan.shop".to_string()),
2225            None),
2226    };
2227
2228    match mode {
2229        ShareMode::Tunnel => {
2230            print_splash(&[
2231                format!("{}  {}", brand_green("shunt"), dim(&format!("v{}", env!("CARGO_PKG_VERSION")))),
2232                dim("Starting Cloudflare tunnel…").to_string(),
2233                String::new(),
2234            ]);
2235            println!("  {} Make sure the proxy is running: {}", dim("·"), cyan("shunt start"));
2236            println!();
2237
2238            let url = start_cloudflare_tunnel(port)?;
2239            share_and_print(&url, &key, &relay_url, "Tunnel active", &[
2240                format!("  {} Code expires in 10 minutes — one-time use", dim("·")),
2241                format!("  {} Tunnel is active — keep this terminal open.", dim("·")),
2242                format!("  {} Press Ctrl+C to stop.", dim("·")),
2243            ]).await;
2244
2245            tokio::signal::ctrl_c().await.ok();
2246            println!("\n  {} Tunnel closed.", dim("·"));
2247        }
2248
2249        ShareMode::CustomDomain => {
2250            // Resolve domain: use saved, or prompt + save
2251            let domain = if let Some(d) = saved_domain {
2252                d
2253            } else {
2254                use std::io::Write;
2255                println!();
2256                println!("  {} Enter your domain URL (e.g. {}): ",
2257                    dim("·"), dim("https://shunt.mysite.com"));
2258                print!("    ");
2259                std::io::stdout().flush()?;
2260                let mut input = String::new();
2261                std::io::stdin().read_line(&mut input)?;
2262                let domain = input.trim().trim_end_matches('/').to_string();
2263                if domain.is_empty() {
2264                    bail!("No domain entered.");
2265                }
2266                if !domain.starts_with("http") {
2267                    bail!("Domain must start with http:// or https://");
2268                }
2269                // Save to config
2270                let mut cfg_text = std::fs::read_to_string(&config_p)?;
2271                cfg_text = insert_into_server_section(&cfg_text,
2272                    &format!("custom_domain = \"{domain}\""));
2273                std::fs::write(&config_p, &cfg_text)?;
2274                println!("  {} Saved {} to config.", green(CHECK), cyan(&domain));
2275                domain
2276            };
2277
2278            share_and_print(&domain, &key, &relay_url, "Online sharing (custom domain)", &[
2279                format!("  {} Code expires in 10 minutes — one-time use", dim("·")),
2280                format!("  {} Make sure {} is pointing to port {} on this machine.",
2281                    dim("·"), cyan(&domain), port),
2282                format!("  {} Restart to apply: {}", dim("·"), cyan("shunt start")),
2283                format!("  {} To stop sharing:  {}", dim("·"), cyan("shunt share --stop")),
2284            ]).await;
2285        }
2286
2287        ShareMode::Lan => {
2288            let ip = local_ip().unwrap_or_else(|| "<your-ip>".to_string());
2289            let base_url = format!("http://{ip}:{port}");
2290
2291            share_and_print(&base_url, &key, &relay_url, "Remote sharing enabled (LAN)", &[
2292                format!("  {} Code expires in 10 minutes — one-time use", dim("·")),
2293                format!("  {} Both devices must be on the same network.", dim("·")),
2294                format!("  {} Restart to apply: {}", dim("·"), cyan("shunt start")),
2295                format!("  {} To stop sharing:  {}", dim("·"), cyan("shunt share --stop")),
2296            ]).await;
2297        }
2298
2299        ShareMode::Stop => unreachable!(),
2300    }
2301
2302    Ok(())
2303}
2304
2305/// Push share code to relay and print the result (code or fallback manual instructions).
2306async fn share_and_print(base_url: &str, key: &str, relay_url: &str, subtitle: &str, hints: &[String]) {
2307    let share_code = crate::sync::generate_share_code();
2308    match crate::sync::push_share(&share_code, base_url, key, relay_url).await {
2309        Ok(()) => {
2310            print_splash(&[
2311                format!("{}  {}", brand_green("shunt"), dim(&format!("v{}", env!("CARGO_PKG_VERSION")))),
2312                dim(subtitle).to_string(),
2313                String::new(),
2314            ]);
2315            println!("  {}  Share code:\n", green(CHECK));
2316            println!("      {}\n", cyan(&share_code));
2317            println!("  {} On the other device, run:", dim("·"));
2318            println!("       {}", cyan(&format!("shunt connect {share_code}")));
2319            println!();
2320            for hint in hints { println!("{hint}"); }
2321            println!();
2322        }
2323        Err(e) => {
2324            // Relay unavailable — fall back to manual env var instructions
2325            print_splash(&[
2326                format!("{}  {}", brand_green("shunt"), dim(&format!("v{}", env!("CARGO_PKG_VERSION")))),
2327                dim(subtitle).to_string(),
2328                String::new(),
2329            ]);
2330            println!("  Set on the remote device:\n");
2331            println!("    {}{}", dim("export ANTHROPIC_BASE_URL="), cyan(base_url));
2332            println!("    {}{}", dim("export ANTHROPIC_API_KEY="), cyan(key));
2333            println!();
2334            println!("  {} (share code unavailable: {e})", dim("·"));
2335            for hint in hints { println!("{hint}"); }
2336            println!();
2337        }
2338    }
2339}
2340
2341/// Spawn `cloudflared tunnel --url http://localhost:{port}`, wait for the public URL,
2342/// and return it. The cloudflared process is left running in the background.
2343fn start_cloudflare_tunnel(port: u16) -> Result<String> {
2344    use std::io::{BufRead, BufReader};
2345    use std::process::{Command, Stdio};
2346
2347    let mut child = Command::new("cloudflared")
2348        .args(["tunnel", "--url", &format!("http://localhost:{port}")])
2349        .stderr(Stdio::piped())
2350        .stdout(Stdio::null())
2351        .spawn()
2352        .map_err(|e| {
2353            if e.kind() == std::io::ErrorKind::NotFound {
2354                anyhow::anyhow!(
2355                    "cloudflared not found.\n\n  Install it:\n    brew install cloudflared\n  or: https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/downloads/"
2356                )
2357            } else {
2358                anyhow::anyhow!("Failed to start cloudflared: {e}")
2359            }
2360        })?;
2361
2362    let stderr = child.stderr.take().expect("stderr was piped");
2363    let reader = BufReader::new(stderr);
2364
2365    for line in reader.lines() {
2366        let line = line?;
2367        if let Some(url) = extract_cloudflare_url(&line) {
2368            // Leave the child running — it will be killed when the process exits
2369            std::mem::forget(child);
2370            return Ok(url);
2371        }
2372    }
2373
2374    bail!("cloudflared exited before providing a tunnel URL")
2375}
2376
2377fn extract_cloudflare_url(line: &str) -> Option<String> {
2378    // cloudflared prints the URL in a line like:
2379    //   INF | https://random-words.trycloudflare.com |
2380    // or just contains the URL somewhere in the log line
2381    let lower = line.to_lowercase();
2382    if lower.contains("trycloudflare.com") || lower.contains("cfargotunnel.com") {
2383        // Extract the https:// URL from the line
2384        if let Some(start) = line.find("https://") {
2385            let rest = &line[start..];
2386            let end = rest.find(|c: char| c.is_whitespace() || c == '|' || c == '"')
2387                .unwrap_or(rest.len());
2388            return Some(rest[..end].trim_end_matches('/').to_owned());
2389        }
2390    }
2391    None
2392}
2393
2394fn generate_remote_key() -> String {
2395    hex::encode(crate::oauth::rand_bytes::<16>())
2396}
2397
2398fn extract_remote_key(config: &str) -> Option<String> {
2399    for line in config.lines() {
2400        let line = line.trim();
2401        if line.starts_with("remote_key") {
2402            return line.split('=')
2403                .nth(1)
2404                .map(|s| s.trim().trim_matches('"').to_owned());
2405        }
2406    }
2407    None
2408}
2409
2410fn insert_into_server_section(config: &str, line: &str) -> String {
2411    // Insert just before the first [[accounts]] block
2412    if let Some(pos) = config.find("\n[[accounts]]") {
2413        let (before, after) = config.split_at(pos);
2414        format!("{before}\n{line}{after}")
2415    } else {
2416        format!("{config}\n{line}\n")
2417    }
2418}
2419
2420fn local_ip() -> Option<String> {
2421    let socket = std::net::UdpSocket::bind("0.0.0.0:0").ok()?;
2422    socket.connect("8.8.8.8:80").ok()?;
2423    Some(socket.local_addr().ok()?.ip().to_string())
2424}
2425
2426/// If the proxy is currently running, offer to restart it immediately.
2427async fn offer_restart(config_override: Option<PathBuf>) {
2428    use std::io::Write;
2429    let Ok(cfg) = crate::config::load_config(config_override.as_deref()) else { return };
2430    let health_url = format!("http://{}:{}/health", cfg.server.host, cfg.server.port);
2431    let running = reqwest::get(&health_url).await
2432        .map(|r| r.status().is_success())
2433        .unwrap_or(false);
2434    if !running { return; }
2435
2436    print!("  {} Proxy is running — restart now? [Y/n]: ", dim("·"));
2437    std::io::stdout().flush().ok();
2438    let mut buf = String::new();
2439    std::io::stdin().read_line(&mut buf).ok();
2440    if matches!(buf.trim().to_lowercase().as_str(), "n" | "no") {
2441        println!("  {} Run {} when ready.", dim("·"), cyan("shunt restart"));
2442        return;
2443    }
2444    if let Err(e) = cmd_restart(config_override).await {
2445        println!("  {} Restart failed: {e}", red(CROSS));
2446    }
2447}
2448
2449// ---------------------------------------------------------------------------
2450// connect
2451// ---------------------------------------------------------------------------
2452
2453async fn cmd_connect(code: String) -> Result<()> {
2454    use std::io::{self, Write};
2455
2456    crate::sync::validate_share_code(&code)?;
2457
2458    let relay_url = std::env::var("SHUNT_RELAY_URL")
2459        .unwrap_or_else(|_| "https://relay.ramcharan.shop".to_string());
2460
2461    print_splash(&[
2462        format!("{}  {}", brand_green("shunt"), dim(&format!("v{}", env!("CARGO_PKG_VERSION")))),
2463        dim("Connecting to remote shunt…").to_string(),
2464        String::new(),
2465    ]);
2466
2467    println!("  {} Fetching credentials for {}…", dim("·"), cyan(&code));
2468    println!();
2469
2470    let (base_url, api_key) = crate::sync::pull_share(&code, &relay_url).await?;
2471
2472    println!("  {}  Retrieved:", green(CHECK));
2473    println!("      {} {}", dim("ANTHROPIC_BASE_URL ="), cyan(&base_url));
2474    println!("      {} {}", dim("ANTHROPIC_API_KEY  ="), cyan(&format!("{}…", &api_key[..api_key.len().min(12)])));
2475    println!();
2476
2477    // --- Offer to write to shell profile ---
2478    let profile = detect_shell_profile();
2479    let prompt = match &profile {
2480        Some(p) => format!("  Write to {}? [Y/n]: ", dim(&p.display().to_string())),
2481        None => "  Write to shell profile? [Y/n]: ".into(),
2482    };
2483    print!("{prompt}");
2484    io::stdout().flush()?;
2485    let mut buf = String::new();
2486    io::stdin().read_line(&mut buf)?;
2487
2488    if !matches!(buf.trim().to_lowercase().as_str(), "n" | "no") {
2489        match profile {
2490            Some(p) => {
2491                write_connect_vars_to_profile(&p, &base_url, &api_key)?;
2492            }
2493            None => {
2494                println!("  {} Could not detect shell profile. Set manually:", dim("·"));
2495                println!("      export ANTHROPIC_BASE_URL={base_url}");
2496                println!("      export ANTHROPIC_API_KEY={api_key}");
2497            }
2498        }
2499    }
2500
2501    // --- Write to Claude Code settings.json ---
2502    if let Err(e) = write_claude_settings(&base_url, &api_key) {
2503        println!("  {} Could not write ~/.claude/settings.json: {e}", dim("·"));
2504    } else {
2505        println!("  {} Written to {}", green(CHECK), dim("~/.claude/settings.json"));
2506    }
2507
2508    println!();
2509    println!("  {} Done! Restart shell or run: {}", green(CHECK),
2510        cyan(detect_shell_profile()
2511            .map(|p| format!("source {}", p.display()))
2512            .unwrap_or_else(|| "source ~/.zshrc".to_string()).as_str()));
2513    println!();
2514
2515    Ok(())
2516}
2517
2518/// Write ANTHROPIC_BASE_URL and ANTHROPIC_API_KEY to a shell profile, replacing
2519/// existing entries in-place or appending if absent.
2520fn write_connect_vars_to_profile(profile: &std::path::Path, base_url: &str, api_key: &str) -> Result<()> {
2521    use std::io::Write as _;
2522
2523    let url_line = format!("export ANTHROPIC_BASE_URL={base_url}");
2524    let key_line = format!("export ANTHROPIC_API_KEY={api_key}");
2525
2526    if profile.exists() {
2527        let contents = std::fs::read_to_string(profile)?;
2528        let has_url = contents.contains("ANTHROPIC_BASE_URL");
2529        let has_key = contents.contains("ANTHROPIC_API_KEY");
2530
2531        if has_url || has_key {
2532            // Replace in-place
2533            let updated: String = contents
2534                .lines()
2535                .map(|l| {
2536                    if l.contains("ANTHROPIC_BASE_URL") {
2537                        url_line.as_str()
2538                    } else if l.contains("ANTHROPIC_API_KEY") {
2539                        key_line.as_str()
2540                    } else {
2541                        l
2542                    }
2543                })
2544                .collect::<Vec<_>>()
2545                .join("\n")
2546                + "\n";
2547            // Append any var that wasn't already there
2548            let mut final_content = updated;
2549            if !has_url {
2550                final_content.push_str(&format!("{url_line}\n"));
2551            }
2552            if !has_key {
2553                final_content.push_str(&format!("{key_line}\n"));
2554            }
2555            std::fs::write(profile, &final_content)?;
2556            println!("  {} Updated {} — {}", green(CHECK),
2557                dim(&profile.display().to_string()),
2558                cyan("ANTHROPIC_BASE_URL + ANTHROPIC_API_KEY"));
2559            return Ok(());
2560        }
2561    }
2562
2563    // Append both vars
2564    let mut f = std::fs::OpenOptions::new().create(true).append(true).open(profile)?;
2565    writeln!(f, "\n# Added by shunt connect")?;
2566    writeln!(f, "{url_line}")?;
2567    writeln!(f, "{key_line}")?;
2568    println!("  {} Added to {} — {}", green(CHECK),
2569        dim(&profile.display().to_string()),
2570        cyan("ANTHROPIC_BASE_URL + ANTHROPIC_API_KEY"));
2571    Ok(())
2572}
2573
2574/// Write ANTHROPIC_BASE_URL and ANTHROPIC_API_KEY into ~/.claude/settings.json
2575/// under the `env` key, creating the file if absent.
2576fn write_claude_settings(base_url: &str, api_key: &str) -> Result<()> {
2577    let home = dirs::home_dir().context("Cannot find home directory")?;
2578    let settings_path = home.join(".claude").join("settings.json");
2579
2580    let mut root: serde_json::Value = if settings_path.exists() {
2581        let text = std::fs::read_to_string(&settings_path)?;
2582        serde_json::from_str(&text).unwrap_or(serde_json::Value::Object(Default::default()))
2583    } else {
2584        serde_json::Value::Object(Default::default())
2585    };
2586
2587    let obj = root.as_object_mut().context("settings.json root is not an object")?;
2588    let env = obj.entry("env").or_insert(serde_json::Value::Object(Default::default()));
2589    let env_obj = env.as_object_mut().context("settings.json 'env' is not an object")?;
2590    env_obj.insert("ANTHROPIC_BASE_URL".to_string(), serde_json::Value::String(base_url.to_string()));
2591    env_obj.insert("ANTHROPIC_API_KEY".to_string(), serde_json::Value::String(api_key.to_string()));
2592
2593    if let Some(parent) = settings_path.parent() {
2594        std::fs::create_dir_all(parent)?;
2595    }
2596    std::fs::write(&settings_path, serde_json::to_string_pretty(&root)?)?;
2597    Ok(())
2598}
2599
2600fn offer_shell_export() -> Result<()> {
2601    use std::io::{self, Write};
2602
2603    let line = "export ANTHROPIC_BASE_URL=http://127.0.0.1:8082";
2604    println!();
2605    println!("  To use with Claude Code, set:");
2606    println!("    {}", cyan(line));
2607
2608    let profile = detect_shell_profile();
2609    let prompt = match &profile {
2610        Some(p) => format!("  Add to {}? [Y/n]: ", dim(&p.display().to_string())),
2611        None => "  Add to your shell profile? [Y/n]: ".into(),
2612    };
2613
2614    print!("{prompt}");
2615    io::stdout().flush()?;
2616    let mut buf = String::new();
2617    io::stdin().read_line(&mut buf)?;
2618
2619    if matches!(buf.trim().to_lowercase().as_str(), "n" | "no") {
2620        return Ok(());
2621    }
2622
2623    let path = match profile {
2624        Some(p) => p,
2625        None => {
2626            println!("  {} Could not detect shell profile. Add manually.", dim("·"));
2627            return Ok(());
2628        }
2629    };
2630
2631    if path.exists() {
2632        let contents = std::fs::read_to_string(&path)?;
2633        if contents.contains("ANTHROPIC_BASE_URL") {
2634            println!("  {} Already set in {}", CHECK, dim(&path.display().to_string()));
2635            return Ok(());
2636        }
2637    }
2638
2639    let mut f = std::fs::OpenOptions::new().create(true).append(true).open(&path)?;
2640    #[allow(unused_imports)]
2641    use std::io::Write as _;
2642    writeln!(f, "\n# Added by shunt")?;
2643    writeln!(f, "{line}")?;
2644    println!("  {} Added to {} — restart shell or: {}", green(CHECK),
2645        dim(&path.display().to_string()),
2646        cyan(&format!("source {}", path.display())));
2647
2648    Ok(())
2649}
2650
2651// ---------------------------------------------------------------------------
2652// uninstall
2653// ---------------------------------------------------------------------------
2654
2655async fn cmd_uninstall() -> Result<()> {
2656    use std::io::Write as _;
2657
2658    // ── Collect what exists ───────────────────────────────────────────────────
2659    let config_dir = dirs::config_dir()
2660        .unwrap_or_else(|| PathBuf::from("."))
2661        .join("shunt");
2662
2663    let data_dir = dirs::data_local_dir()
2664        .unwrap_or_else(|| PathBuf::from("."))
2665        .join("shunt");
2666
2667    let exe = std::env::current_exe().ok();
2668
2669    // Shell profile line to remove
2670    let shell_profile = detect_shell_profile();
2671    let profile_has_export = shell_profile.as_ref().and_then(|p| {
2672        std::fs::read_to_string(p).ok()
2673    }).map(|s| s.contains("ANTHROPIC_BASE_URL=http://127.0.0.1:")).unwrap_or(false);
2674
2675    #[cfg(target_os = "macos")]
2676    let service_plist = {
2677        let p = service_plist_path();
2678        if p.exists() { Some(p) } else { None }
2679    };
2680    #[cfg(not(target_os = "macos"))]
2681    let service_plist: Option<PathBuf> = None;
2682
2683    #[cfg(target_os = "linux")]
2684    let service_unit = {
2685        let p = service_unit_path();
2686        if p.exists() { Some(p) } else { None }
2687    };
2688    #[cfg(not(target_os = "linux"))]
2689    let service_unit: Option<PathBuf> = None;
2690
2691    // ── Show plan ─────────────────────────────────────────────────────────────
2692    print_splash(&[
2693        format!("{}  {}", brand_green("shunt"), dim(&format!("v{}", env!("CARGO_PKG_VERSION")))),
2694        red("Uninstall").to_string(),
2695        String::new(),
2696    ]);
2697
2698    println!("  This will permanently remove:");
2699    println!();
2700
2701    if service_plist.is_some() || service_unit.is_some() {
2702        println!("  {}  Stop and unregister login service", red("✕"));
2703    }
2704
2705    if config_dir.exists() {
2706        println!("  {}  {} {}", red("✕"), dim("delete"), cyan(&config_dir.display().to_string()));
2707    }
2708    if data_dir.exists() && data_dir != config_dir {
2709        println!("  {}  {} {}", red("✕"), dim("delete"), cyan(&data_dir.display().to_string()));
2710    }
2711    if let Some(ref p) = shell_profile {
2712        if profile_has_export {
2713            println!("  {}  {} ANTHROPIC_BASE_URL from {}", red("✕"), dim("remove"), cyan(&p.display().to_string()));
2714        }
2715    }
2716    if let Some(ref exe_path) = exe {
2717        println!("  {}  {} {}", red("✕"), dim("delete"), cyan(&exe_path.display().to_string()));
2718    }
2719
2720    println!();
2721
2722    // ── Reconfirm ─────────────────────────────────────────────────────────────
2723    if !term::confirm("Are you sure you want to completely uninstall shunt?") {
2724        println!("  {} Cancelled.", dim("·"));
2725        println!();
2726        return Ok(());
2727    }
2728
2729    // Second confirmation — type "uninstall"
2730    println!();
2731    print!("  {} Type {} to confirm: ", dim("·"), bold("uninstall"));
2732    std::io::stdout().flush()?;
2733    let mut buf = String::new();
2734    std::io::stdin().read_line(&mut buf)?;
2735    if buf.trim() != "uninstall" {
2736        println!("  {} Cancelled.", dim("·"));
2737        println!();
2738        return Ok(());
2739    }
2740
2741    println!();
2742
2743    // ── Execute ───────────────────────────────────────────────────────────────
2744
2745    // 1. Stop + unregister service
2746    #[cfg(target_os = "macos")]
2747    if let Some(ref p) = service_plist {
2748        let _ = std::process::Command::new("launchctl")
2749            .args(["unload", &p.display().to_string()])
2750            .output();
2751        let _ = std::fs::remove_file(p);
2752        println!("  {} Login service removed", green(CHECK));
2753    }
2754    #[cfg(target_os = "linux")]
2755    if let Some(ref p) = service_unit {
2756        let _ = std::process::Command::new("systemctl")
2757            .args(["--user", "disable", "--now", "shunt"])
2758            .output();
2759        let _ = std::fs::remove_file(p);
2760        let _ = std::process::Command::new("systemctl")
2761            .args(["--user", "daemon-reload"])
2762            .output();
2763        println!("  {} Login service removed", green(CHECK));
2764    }
2765
2766    // 2. Config + credentials dir
2767    if config_dir.exists() {
2768        std::fs::remove_dir_all(&config_dir)
2769            .with_context(|| format!("failed to remove {}", config_dir.display()))?;
2770        println!("  {} Config removed  {}", green(CHECK), dim(&config_dir.display().to_string()));
2771    }
2772
2773    // 3. Data dir (logs, state, pid) — skip if same as config_dir (macOS)
2774    if data_dir.exists() && data_dir != config_dir {
2775        std::fs::remove_dir_all(&data_dir)
2776            .with_context(|| format!("failed to remove {}", data_dir.display()))?;
2777        println!("  {} Data removed    {}", green(CHECK), dim(&data_dir.display().to_string()));
2778    }
2779
2780    // 4. Shell profile — strip ANTHROPIC_BASE_URL lines
2781    if let Some(ref profile_path) = shell_profile {
2782        if profile_has_export {
2783            if let Ok(contents) = std::fs::read_to_string(profile_path) {
2784                let cleaned: String = contents
2785                    .lines()
2786                    .filter(|l| {
2787                        !l.contains("ANTHROPIC_BASE_URL=http://127.0.0.1:")
2788                            && *l != "# Added by shunt"
2789                    })
2790                    .collect::<Vec<_>>()
2791                    .join("\n");
2792                // Preserve trailing newline if original had one
2793                let cleaned = if contents.ends_with('\n') {
2794                    format!("{cleaned}\n")
2795                } else {
2796                    cleaned
2797                };
2798                std::fs::write(profile_path, cleaned)?;
2799                println!("  {} Shell export removed  {}", green(CHECK),
2800                    dim(&profile_path.display().to_string()));
2801            }
2802        }
2803    }
2804
2805    // 5. Binary — do this last so error messages can still print
2806    if let Some(exe_path) = exe {
2807        // Spawn a tiny shell to delete the binary after this process exits
2808        let path_str = exe_path.display().to_string();
2809        std::process::Command::new("sh")
2810            .args(["-c", &format!("sleep 0.3 && rm -f '{path_str}'")])
2811            .stdin(std::process::Stdio::null())
2812            .stdout(std::process::Stdio::null())
2813            .stderr(std::process::Stdio::null())
2814            .spawn()
2815            .ok();
2816        println!("  {} Binary removed   {}", green(CHECK), dim(&exe_path.display().to_string()));
2817    }
2818
2819    println!();
2820    println!("  {} shunt fully removed.", green(CHECK));
2821    println!("  {} Run {} to clear the proxy from this shell session.", dim("·"), cyan("unset ANTHROPIC_BASE_URL"));
2822    println!();
2823
2824    Ok(())
2825}
2826
2827// ---------------------------------------------------------------------------
2828// service
2829// ---------------------------------------------------------------------------
2830
2831#[cfg(target_os = "macos")]
2832fn service_plist_path() -> PathBuf {
2833    dirs::home_dir()
2834        .unwrap_or_else(|| PathBuf::from("/tmp"))
2835        .join("Library/LaunchAgents/sh.shunt.proxy.plist")
2836}
2837
2838#[cfg(target_os = "linux")]
2839fn service_unit_path() -> PathBuf {
2840    dirs::home_dir()
2841        .unwrap_or_else(|| PathBuf::from("/tmp"))
2842        .join(".config/systemd/user/shunt.service")
2843}
2844
2845/// Write the platform service file and enable it to run at login.
2846/// Write the platform service file and attempt to activate it.
2847/// Returns `true` if the service was successfully loaded/started by the init
2848/// system, `false` if the plist/unit was written but activation was skipped
2849/// or timed out (e.g. SSH session without a GUI bootstrap context).
2850fn register_service() -> Result<bool> {
2851    let exe = std::env::current_exe().context("cannot locate current executable")?;
2852    let exe_str = exe.display().to_string();
2853
2854    #[cfg(target_os = "macos")]
2855    {
2856        let plist_path = service_plist_path();
2857        let plist_was_present = plist_path.exists();
2858        if let Some(parent) = plist_path.parent() {
2859            std::fs::create_dir_all(parent)?;
2860        }
2861        let plist = format!(r#"<?xml version="1.0" encoding="UTF-8"?>
2862<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN"
2863  "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
2864<plist version="1.0">
2865<dict>
2866  <key>Label</key>
2867  <string>sh.shunt.proxy</string>
2868  <key>ProgramArguments</key>
2869  <array>
2870    <string>{exe_str}</string>
2871    <string>start</string>
2872    <string>--foreground</string>
2873  </array>
2874  <key>RunAtLoad</key>
2875  <true/>
2876  <key>KeepAlive</key>
2877  <true/>
2878  <key>StandardOutPath</key>
2879  <string>{home}/Library/Logs/shunt.log</string>
2880  <key>StandardErrorPath</key>
2881  <string>{home}/Library/Logs/shunt.log</string>
2882</dict>
2883</plist>
2884"#,
2885            exe_str = exe_str,
2886            home = dirs::home_dir().unwrap_or_default().display(),
2887        );
2888        std::fs::write(&plist_path, &plist)?;
2889
2890        // launchctl hangs in SSH sessions without a GUI bootstrap context.
2891        // Wrap both unload and load in threads with timeouts.
2892        let plist_str = plist_path.display().to_string();
2893
2894        // Unload only if a plist was already there (i.e. this is a reinstall)
2895        if plist_was_present {
2896            let p = plist_str.clone();
2897            let (tx, rx) = std::sync::mpsc::channel();
2898            std::thread::spawn(move || {
2899                let _ = std::process::Command::new("launchctl")
2900                    .args(["unload", &p])
2901                    .output();
2902                let _ = tx.send(());
2903            });
2904            let _ = rx.recv_timeout(std::time::Duration::from_secs(4));
2905        }
2906
2907        // Load
2908        let (tx, rx) = std::sync::mpsc::channel();
2909        std::thread::spawn(move || {
2910            let ok = std::process::Command::new("launchctl")
2911                .args(["load", "-w", &plist_str])
2912                .output()
2913                .map(|o| o.status.success())
2914                .unwrap_or(false);
2915            let _ = tx.send(ok);
2916        });
2917
2918        let loaded = rx
2919            .recv_timeout(std::time::Duration::from_secs(4))
2920            .unwrap_or(false);
2921
2922        return Ok(loaded);
2923    }
2924
2925    #[cfg(target_os = "linux")]
2926    {
2927        let unit_path = service_unit_path();
2928        if let Some(parent) = unit_path.parent() {
2929            std::fs::create_dir_all(parent)?;
2930        }
2931        let unit = format!(
2932            "[Unit]\nDescription=shunt Claude Code proxy\nAfter=network.target\n\n\
2933             [Service]\nExecStart={exe_str} start --foreground\nRestart=always\nRestartSec=5\n\n\
2934             [Install]\nWantedBy=default.target\n"
2935        );
2936        std::fs::write(&unit_path, &unit)?;
2937
2938        let _ = std::process::Command::new("systemctl")
2939            .args(["--user", "daemon-reload"])
2940            .output();
2941
2942        let out = std::process::Command::new("systemctl")
2943            .args(["--user", "enable", "--now", "shunt"])
2944            .output()
2945            .context("failed to run systemctl")?;
2946
2947        return Ok(out.status.success());
2948    }
2949
2950    #[cfg(not(any(target_os = "macos", target_os = "linux")))]
2951    bail!("Service management is only supported on macOS and Linux.");
2952
2953    #[allow(unreachable_code)]
2954    Ok(false)
2955}
2956
2957async fn cmd_service_install() -> Result<()> {
2958    print_splash(&[
2959        format!("{}  {}", brand_green("shunt"), dim(&format!("v{}", env!("CARGO_PKG_VERSION")))),
2960        dim("Service install"),
2961        String::new(),
2962    ]);
2963
2964    // 1. Ensure config + credentials exist.
2965    //    If stdin is not a TTY (e.g. curl | sh), skip interactive setup to
2966    //    avoid blocking on keychain/OAuth. The service is still registered and
2967    //    the proxy started; user runs `shunt setup` in a terminal to finish.
2968    let config_p = config_path();
2969    let stdin_is_tty = unsafe { libc::isatty(libc::STDIN_FILENO) != 0 };
2970    if !config_p.exists() {
2971        if stdin_is_tty {
2972            cmd_setup_auto(None).await?;
2973        } else {
2974            println!("  {} No config — run {} in a terminal to import credentials",
2975                yellow("·"), cyan("shunt setup"));
2976        }
2977    }
2978
2979    // 2. Read port from config for shell export
2980    let port = crate::config::load_config(None)
2981        .map(|c| c.server.port)
2982        .unwrap_or(8082);
2983
2984    // 3. Register the platform service
2985    print!("  {} Registering login service… ", dim("·"));
2986    use std::io::Write as _;
2987    std::io::stdout().flush().ok();
2988    let service_loaded = register_service()?;
2989    if service_loaded {
2990        println!("{}", green("done"));
2991    } else {
2992        println!("{}", dim("skipped (SSH session — activates on next login)"));
2993    }
2994
2995    // 4. If launchd/systemd couldn't activate the service (e.g. SSH session
2996    //    without a GUI bootstrap context), start the proxy directly.
2997    if !service_loaded {
2998        print!("  {} Starting proxy… ", dim("·"));
2999        std::io::stdout().flush().ok();
3000        let exe = std::env::current_exe().context("cannot locate current executable")?;
3001        let _ = std::process::Command::new(&exe)
3002            .args(["start", "--daemon"])
3003            .stdin(std::process::Stdio::null())
3004            .stdout(std::process::Stdio::null())
3005            .stderr(std::process::Stdio::null())
3006            .spawn();
3007    }
3008
3009    // 5. Write shell export silently
3010    auto_write_shell_export(port);
3011
3012    // 6. Wait for proxy to be healthy
3013    tokio::time::sleep(std::time::Duration::from_millis(500)).await;
3014    let config = crate::config::load_config(None).ok();
3015    let host = config.as_ref().map(|c| c.server.host.clone()).unwrap_or_else(|| "127.0.0.1".into());
3016    let running = wait_for_health(&host, port, 8).await;
3017    if !service_loaded {
3018        println!("{}", if running { green("done").to_string() } else { dim("starting…").to_string() });
3019    }
3020
3021    println!();
3022    if running {
3023        println!("  {}  {}  {}", green(DOT), green_bold("proxy running"),
3024            cyan(&format!("http://{host}:{port}")));
3025    } else {
3026        println!("  {}  {} — proxy starting in background",
3027            yellow(DOT), yellow("starting"));
3028    }
3029
3030    #[cfg(target_os = "macos")]
3031    if service_loaded {
3032        println!("  {}  LaunchAgent registered — starts automatically at login", green(CHECK));
3033    } else {
3034        println!("  {}  LaunchAgent written — will activate on next login", yellow("·"));
3035        println!("  {}  To activate now (in a GUI session): {}",
3036            dim("·"), cyan("launchctl load -w ~/Library/LaunchAgents/sh.shunt.proxy.plist"));
3037    }
3038    #[cfg(target_os = "linux")]
3039    if service_loaded {
3040        println!("  {}  systemd user unit registered — starts automatically at login", green(CHECK));
3041    } else {
3042        println!("  {}  systemd unit written — run {} to activate",
3043            yellow("·"), cyan("systemctl --user enable --now shunt"));
3044    }
3045
3046    println!();
3047    println!("  {} To unregister: {}", dim("·"), cyan("shunt service uninstall"));
3048    println!();
3049
3050    Ok(())
3051}
3052
3053async fn cmd_service_uninstall() -> Result<()> {
3054    #[cfg(target_os = "macos")]
3055    {
3056        let plist_path = service_plist_path();
3057        if plist_path.exists() {
3058            let _ = std::process::Command::new("launchctl")
3059                .args(["unload", &plist_path.display().to_string()])
3060                .output();
3061            std::fs::remove_file(&plist_path)
3062                .context("failed to remove plist")?;
3063            println!("  {} Service unregistered.", green(CHECK));
3064        } else {
3065            println!("  {} Service not registered.", dim("·"));
3066        }
3067    }
3068
3069    #[cfg(target_os = "linux")]
3070    {
3071        let unit_path = service_unit_path();
3072        let _ = std::process::Command::new("systemctl")
3073            .args(["--user", "disable", "--now", "shunt"])
3074            .output();
3075        if unit_path.exists() {
3076            std::fs::remove_file(&unit_path)
3077                .context("failed to remove unit file")?;
3078        }
3079        let _ = std::process::Command::new("systemctl")
3080            .args(["--user", "daemon-reload"])
3081            .output();
3082        println!("  {} Service unregistered.", green(CHECK));
3083    }
3084
3085    #[cfg(not(any(target_os = "macos", target_os = "linux")))]
3086    bail!("Service management is only supported on macOS and Linux.");
3087
3088    println!();
3089    Ok(())
3090}
3091
3092async fn cmd_service_status() -> Result<()> {
3093    #[cfg(target_os = "macos")]
3094    {
3095        let plist_path = service_plist_path();
3096        let registered = plist_path.exists();
3097        if registered {
3098            println!("  {} Registered  {}", green(CHECK), dim(&plist_path.display().to_string()));
3099        } else {
3100            println!("  {} Not registered (run {})", dim("·"), cyan("shunt service install"));
3101        }
3102
3103        // Check if launchd considers it running
3104        let out = std::process::Command::new("launchctl")
3105            .args(["list", "sh.shunt.proxy"])
3106            .output();
3107        let running = out.map(|o| o.status.success()).unwrap_or(false);
3108        if running {
3109            println!("  {} Running (launchd)", green(DOT));
3110        } else {
3111            println!("  {} Not running", dim(DOT));
3112        }
3113    }
3114
3115    #[cfg(target_os = "linux")]
3116    {
3117        let unit_path = service_unit_path();
3118        let registered = unit_path.exists();
3119        if registered {
3120            println!("  {} Registered  {}", green(CHECK), dim(&unit_path.display().to_string()));
3121        } else {
3122            println!("  {} Not registered (run {})", dim("·"), cyan("shunt service install"));
3123        }
3124
3125        let out = std::process::Command::new("systemctl")
3126            .args(["--user", "is-active", "shunt"])
3127            .output();
3128        let active = out.map(|o| o.status.success()).unwrap_or(false);
3129        if active {
3130            println!("  {} Running (systemd)", green(DOT));
3131        } else {
3132            println!("  {} Not running", dim(DOT));
3133        }
3134    }
3135
3136    #[cfg(not(any(target_os = "macos", target_os = "linux")))]
3137    println!("  {} Service management is only supported on macOS and Linux.", dim("·"));
3138
3139    println!();
3140    Ok(())
3141}
3142
3143fn detect_shell_profile() -> Option<PathBuf> {
3144    let home = dirs::home_dir()?;
3145    if let Ok(shell) = std::env::var("SHELL") {
3146        if shell.contains("zsh")  { return Some(home.join(".zshrc")); }
3147        if shell.contains("fish") { return Some(home.join(".config/fish/config.fish")); }
3148        if shell.contains("bash") {
3149            let p = home.join(".bash_profile");
3150            return Some(if p.exists() { p } else { home.join(".bashrc") });
3151        }
3152    }
3153    for f in &[".zshrc", ".bashrc", ".bash_profile"] {
3154        let p = home.join(f);
3155        if p.exists() { return Some(p); }
3156    }
3157    None
3158}