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