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 Setup {
22 #[arg(long)]
23 config: Option<PathBuf>,
24 },
25 Start {
27 #[arg(long)]
28 config: Option<PathBuf>,
29 #[arg(long)]
30 host: Option<String>,
31 #[arg(long)]
32 port: Option<u16>,
33 #[arg(long)]
35 foreground: bool,
36 #[arg(long)]
38 verbose: bool,
39 #[arg(long, hide = true)]
41 daemon: bool,
42 },
43 Stop,
45 Restart {
47 #[arg(long)]
48 config: Option<PathBuf>,
49 },
50 Status {
52 #[arg(long)]
53 config: Option<PathBuf>,
54 },
55 Logs {
62 #[arg(long)]
63 config: Option<PathBuf>,
64 #[arg(short, long)]
66 follow: bool,
67 #[arg(short = 'n', long, default_value = "50")]
69 lines: usize,
70 },
71 Config {
73 #[arg(long)]
74 config: Option<PathBuf>,
75 },
76 #[command(hide = true)]
78 AddAccount {
79 #[arg(long)]
80 config: Option<PathBuf>,
81 name: Option<String>,
83 #[arg(long)]
85 provider: Option<String>,
86 },
87 #[command(hide = true)]
89 RemoveAccount {
90 #[arg(long)]
91 config: Option<PathBuf>,
92 name: Option<String>,
94 },
95 Share {
97 #[arg(long)]
98 config: Option<PathBuf>,
99 #[arg(long)]
101 tunnel: bool,
102 #[arg(long)]
104 stop: bool,
105 },
106 #[command(hide = true)]
108 Logout {
109 #[arg(long)]
110 config: Option<PathBuf>,
111 name: Option<String>,
113 #[arg(long)]
115 all: bool,
116 },
117 Monitor {
119 #[arg(long)]
120 config: Option<PathBuf>,
121 },
122 Remote {
131 code: Option<String>,
133 },
134 Connect {
143 code: String,
145 },
146 Update,
148 Uninstall,
150 Service {
157 #[command(subcommand)]
158 action: ServiceAction,
159 },
160 Use {
167 #[arg(long)]
168 config: Option<PathBuf>,
169 account: Option<String>,
171 },
172}
173
174#[derive(Subcommand)]
175enum ServiceAction {
176 Install,
178 Uninstall,
180 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
212pub 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 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 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 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 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
297async 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
324async 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 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 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 "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 let state_p = crate::config::state_path();
411 let state = crate::state::StateStore::load(&state_p);
412 state.clear_auth_failed(&name);
413 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 "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 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 "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 "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 "logout" => {
472 return cmd_logout(config_override, Some(name), false).await;
473 }
474
475 "remove" => {
477 return cmd_remove_account(config_override, Some(name)).await;
478 }
479
480 _ => {}
481 }
482
483 println!();
484 Ok(())
485}
486
487fn 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
507async 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 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 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 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 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 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 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 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 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 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 None
655 }
656 };
657
658 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 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
699fn read_secret_line() -> Result<String> {
702 #[cfg(unix)]
704 {
705 use std::io::{BufRead, Write};
706 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 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
730async 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 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 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 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
798async 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 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 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 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 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 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
900fn 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(), };
907
908 if let Some(item) = doc.get_mut("accounts") {
909 if let Some(arr) = item.as_array_of_tables_mut() {
910 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 assert!(!result.contains("\"bob\"") && !result.contains("'bob'") && !result.contains("bob"),
951 "removed account must not appear: {result}");
952 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 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 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
998async 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 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 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 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 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 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 let control_port = config.server.control_port;
1134 let ready = wait_for_health(&host, control_port, 8).await;
1135
1136 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
1153async 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 unsafe { libc::kill(pid as i32, libc::SIGTERM) };
1185
1186 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
1211async 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
1221async 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 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 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
1272async 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 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 return;
1342 }
1343 if contents.contains("ANTHROPIC_BASE_URL=http://127.0.0.1:") {
1344 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 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
1380async fn cmd_status(config_override: Option<PathBuf>) -> Result<()> {
1385 let mut config = crate::config::load_config(config_override.as_deref())?;
1386
1387 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 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 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 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 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 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 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 _ => "",
1542 };
1543 let email_str = acc.credential.as_ref().and_then(|c| c.email()).unwrap_or("");
1544
1545 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 println!("{}", card_header(&acc.name, &green_bold(&acc.name), &routing_tag, tag_vis_len, plan_label));
1558
1559 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 println!("{}", card_row(&format!("{} {}", status_icon, status_text)));
1580
1581 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 println!();
1647 println!("{}", card_sep());
1648 println!();
1649 }
1650
1651 Ok(())
1652}
1653
1654async 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 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 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 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 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(()), }
1725 };
1726
1727 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 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
1771fn 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
1791fn 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
1800fn 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; let leg_h = (h / 4).max(1);
1817 let box_h = h.saturating_sub(leg_h).max(2); let wire_row = box_h / 2; 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::Rgb(34, 197, 94); let dim_col = Color::Rgb(120, 120, 120); let dk_green = Color::Rgb(22, 101, 52); 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 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 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 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 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 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 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 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
1964fn 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 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 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 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 print!("\r\n");
2012}
2013
2014fn 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 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
2060const CARD_W: usize = 58;
2066
2067fn card_header(name: &str, name_c: &str, routing_tag: &str, tag_vis: usize, plan: &str) -> String {
2069 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
2075fn card_row(content: &str) -> String {
2077 format!(" {content}")
2078}
2079
2080fn card_sep() -> String {
2082 format!(" {}", dim(&"─".repeat(CARD_W - 2)))
2083}
2084
2085fn 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 println!(" {} {}", brand_green(DIAMOND), info0);
2102 if !info1.is_empty() {
2103 println!(" {}", info1);
2104 }
2105 }
2106 1 => {
2107 let indent = name_w + 8; println!(" {} {} {}", green_bold(account_names[0]), dark_green("─→"), info0);
2110 if !info1.is_empty() {
2111 println!(" {}{}", " ".repeat(indent), info1);
2112 }
2113 }
2114 2 => {
2115 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 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 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
2152fn 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 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
2163fn 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
2169fn 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
2196async 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 let all_accounts = config.accounts.clone();
2211 let control_port = config.server.control_port;
2212
2213 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 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 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 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
2305fn 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
2329fn 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
2359async 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 if reqwest::get(format!("{base_url}/health")).await.is_err() {
2369 println!();
2370 println!(" {} Proxy is not running.", red(CROSS));
2371 println!(" {} Start it first with {}.", dim("·"), cyan("shunt start"));
2372 println!();
2373 return Ok(());
2374 }
2375
2376 crate::monitor::run_monitor(&base_url).await
2377}
2378
2379async fn cmd_remote(code: Option<String>) -> Result<()> {
2384 let (relay_url, local_url) = if code.is_none() {
2386 let config = crate::config::load_config(None)?;
2387 let local = format!("http://{}:{}", config.server.host, config.server.port);
2388 let relay = config.server.relay_url.clone();
2389 (Some(relay), local)
2390 } else {
2391 let relay_url = std::env::var("SHUNT_RELAY_URL").ok();
2392 (relay_url, String::new())
2393 };
2394 crate::remote::run_remote(code, relay_url, local_url).await
2395}
2396
2397async fn cmd_update() -> Result<()> {
2401 const REPO: &str = "ramc10/shunt";
2402 let current = env!("CARGO_PKG_VERSION");
2403
2404 print_splash(&[
2405 format!("{} {}", brand_green("shunt"), dim(&format!("v{current}"))),
2406 ]);
2407
2408 macro_rules! status {
2411 ($($arg:tt)*) => { println!("\r{}", format_args!($($arg)*)) };
2412 }
2413
2414 status!(" {} Checking for updates…", dim("·"));
2415
2416 let client = reqwest::Client::builder()
2418 .user_agent("shunt-updater")
2419 .connect_timeout(std::time::Duration::from_secs(10))
2420 .timeout(std::time::Duration::from_secs(120))
2421 .build()?;
2422
2423 let api_url = format!("https://api.github.com/repos/{REPO}/releases/latest");
2424 let resp = client.get(&api_url).send().await
2425 .context("Failed to reach GitHub API")?;
2426
2427 if !resp.status().is_success() {
2428 bail!("GitHub API returned {}", resp.status());
2429 }
2430
2431 let json: serde_json::Value = resp.json().await?;
2432 let latest_tag = json["tag_name"].as_str().context("Missing tag_name in release")?;
2433 let latest = latest_tag.trim_start_matches('v');
2434
2435 if parse_version(latest) <= parse_version(current) {
2438 status!(" {} Already up to date ({})", green(CHECK), bold(&format!("v{current}")));
2439 println!();
2440 return Ok(());
2441 }
2442
2443 status!(" {} Update available: {} → {}", green("↑"),
2444 dim(&format!("v{current}")), bold_white(&format!("v{latest}")));
2445 println!();
2446
2447 let target = detect_update_target()?;
2449 let archive_name = format!("shunt-v{latest}-{target}.tar.gz");
2450 let url = format!(
2451 "https://github.com/{REPO}/releases/download/v{latest}/{archive_name}"
2452 );
2453
2454 print!("\r {} Downloading {}… ", dim("↓"), dim(&archive_name));
2455 use std::io::Write as _;
2456 std::io::stdout().flush().ok();
2457
2458 let resp = client.get(&url).send().await
2459 .context("Download request failed")?;
2460
2461 if !resp.status().is_success() {
2462 bail!("Download failed: HTTP {} for {url}", resp.status());
2463 }
2464
2465 let bytes = resp.bytes().await
2466 .context("Failed to read download")?;
2467
2468 if bytes.len() < 2 || bytes[0] != 0x1f || bytes[1] != 0x8b {
2470 bail!(
2471 "Downloaded file does not look like a gzip archive ({} bytes, first bytes: {:02x?})",
2472 bytes.len(), &bytes[..bytes.len().min(4)]
2473 );
2474 }
2475
2476 println!("{}", green("done"));
2477
2478 let exe_path = std::env::current_exe().context("Cannot locate current executable")?;
2480 let tmp_path = exe_path.with_extension("tmp");
2481
2482 extract_binary_from_tarball(&bytes, &tmp_path)
2483 .context("Failed to extract binary from archive")?;
2484
2485 #[cfg(unix)]
2487 {
2488 use std::os::unix::fs::PermissionsExt;
2489 std::fs::set_permissions(&tmp_path, std::fs::Permissions::from_mode(0o755))?;
2490 }
2491 std::fs::rename(&tmp_path, &exe_path)
2492 .context("Failed to replace binary (try running with sudo?)")?;
2493
2494 #[cfg(target_os = "macos")]
2496 {
2497 let p = exe_path.display().to_string();
2498 std::process::Command::new("xattr").args(["-d", "com.apple.quarantine", &p])
2499 .stdout(std::process::Stdio::null()).stderr(std::process::Stdio::null()).status().ok();
2500 std::process::Command::new("codesign").args(["--force", "--deep", "--sign", "-", &p])
2501 .stdout(std::process::Stdio::null()).stderr(std::process::Stdio::null()).status().ok();
2502 }
2503
2504 status!(" {} Updated to {}", green(CHECK), bold_white(&format!("v{latest}")));
2505 println!();
2506 Ok(())
2507}
2508
2509fn parse_version(s: &str) -> (u32, u32, u32) {
2512 let mut it = s.split('.');
2513 let maj = it.next().and_then(|p| p.parse().ok()).unwrap_or(0);
2514 let min = it.next().and_then(|p| p.parse().ok()).unwrap_or(0);
2515 let pat = it.next().and_then(|p| p.parse().ok()).unwrap_or(0);
2516 (maj, min, pat)
2517}
2518
2519fn detect_update_target() -> Result<&'static str> {
2520 match (std::env::consts::OS, std::env::consts::ARCH) {
2521 ("macos", "aarch64") => Ok("aarch64-apple-darwin"),
2522 ("linux", "x86_64") => Ok("x86_64-unknown-linux-gnu"),
2523 ("linux", "aarch64") => Ok("aarch64-unknown-linux-gnu"),
2524 (os, arch) => bail!("No pre-built binary for {os}/{arch}. Build from source: cargo install shunt-proxy"),
2525 }
2526}
2527
2528fn extract_binary_from_tarball(data: &[u8], dest: &std::path::Path) -> Result<()> {
2529 let gz = flate2::read::GzDecoder::new(data);
2530 let mut archive = tar::Archive::new(gz);
2531 for entry in archive.entries()? {
2532 let mut entry = entry?;
2533 let path = entry.path()?;
2534 if path.file_name().and_then(|n| n.to_str()) == Some("shunt") {
2535 let mut out = std::fs::File::create(dest)?;
2536 std::io::copy(&mut entry, &mut out)?;
2537 return Ok(());
2538 }
2539 }
2540 bail!("Binary 'shunt' not found in archive")
2541}
2542
2543async fn cmd_share(config_override: Option<PathBuf>, tunnel: bool, stop: bool) -> Result<()> {
2548 let config_p = config_override.unwrap_or_else(config_path);
2549 if !config_p.exists() {
2550 bail!("No config found. Run `shunt setup` first.");
2551 }
2552
2553 let mut text = std::fs::read_to_string(&config_p)?;
2554
2555 #[derive(Debug)]
2558 enum ShareMode { Lan, Tunnel, CustomDomain, Stop }
2559
2560 let mode: ShareMode = if tunnel {
2561 ShareMode::Tunnel
2562 } else if stop {
2563 ShareMode::Stop
2564 } else {
2565 print_splash(&[
2566 format!("{} {}", brand_green("shunt"), dim(&format!("v{}", env!("CARGO_PKG_VERSION")))),
2567 dim("Remote sharing").to_string(),
2568 String::new(),
2569 ]);
2570 let top_items = vec![
2571 term::SelectItem {
2572 label: format!("{} {}", bold("Local network (LAN)"),
2573 dim("— same Wi-Fi only, no internet required")),
2574 value: "lan".into(),
2575 },
2576 term::SelectItem {
2577 label: format!("{} {}", bold("Online"),
2578 dim("— share over the internet")),
2579 value: "online".into(),
2580 },
2581 term::SelectItem {
2582 label: format!("{} {}", bold("Stop sharing"),
2583 dim("— revert to localhost-only")),
2584 value: "stop".into(),
2585 },
2586 ];
2587 match term::select("How do you want to share?", &top_items, 0).as_deref() {
2588 Some("lan") => ShareMode::Lan,
2589 Some("stop") => ShareMode::Stop,
2590 Some("online") => {
2591 let existing_domain = crate::config::load_config(Some(&config_p))
2593 .ok()
2594 .and_then(|c| c.server.custom_domain.clone());
2595 let domain_label = match &existing_domain {
2596 Some(d) => format!("{} {}",
2597 bold("Custom domain (permanent)"),
2598 dim(&format!("— {} · your domain", d))),
2599 None => format!("{} {}",
2600 bold("Custom domain (permanent)"),
2601 dim("— your own domain, always-on")),
2602 };
2603 let online_items = vec![
2604 term::SelectItem {
2605 label: format!("{} {}",
2606 bold("Temporary (Cloudflare tunnel)"),
2607 dim("— free, random URL, session only")),
2608 value: "tunnel".into(),
2609 },
2610 term::SelectItem {
2611 label: domain_label,
2612 value: "custom".into(),
2613 },
2614 ];
2615 match term::select("Online sharing type:", &online_items, 0).as_deref() {
2616 Some("tunnel") => ShareMode::Tunnel,
2617 Some("custom") => ShareMode::CustomDomain,
2618 _ => return Ok(()),
2619 }
2620 }
2621 _ => return Ok(()),
2622 }
2623 };
2624
2625 if matches!(mode, ShareMode::Stop) {
2626 if !term::confirm("Stop sharing and revert to localhost-only?") {
2628 println!(" {} Cancelled.", dim("·"));
2629 println!();
2630 return Ok(());
2631 }
2632
2633 text = text.lines()
2634 .filter(|l| !l.trim_start().starts_with("remote_key"))
2635 .collect::<Vec<_>>()
2636 .join("\n");
2637 if !text.ends_with('\n') { text.push('\n'); }
2638 text = text.replace("host = \"0.0.0.0\"", "host = \"127.0.0.1\"");
2639 std::fs::write(&config_p, &text)?;
2640
2641 print_splash(&[
2642 format!("{} {}", brand_green("shunt"), dim(&format!("v{}", env!("CARGO_PKG_VERSION")))),
2643 dim("Remote sharing disabled").to_string(),
2644 String::new(),
2645 ]);
2646 println!(" {} Restart to apply: {}", dim("·"), cyan("shunt start"));
2647 println!();
2648 return Ok(());
2649 }
2650
2651 let key = match extract_remote_key(&text) {
2653 Some(k) => k,
2654 None => {
2655 let k = generate_remote_key();
2656 text = insert_into_server_section(&text, &format!("remote_key = \"{k}\""));
2657 k
2658 }
2659 };
2660
2661 if text.contains("host = \"127.0.0.1\"") {
2663 text = text.replace("host = \"127.0.0.1\"", "host = \"0.0.0.0\"");
2664 }
2665
2666 std::fs::write(&config_p, &text)?;
2667
2668 let (port, relay_url, saved_domain) = match crate::config::load_config(Some(&config_p)) {
2669 Ok(cfg) => {
2670 let relay = std::env::var("SHUNT_RELAY_URL")
2671 .unwrap_or_else(|_| cfg.server.relay_url.clone());
2672 (cfg.server.port, relay, cfg.server.custom_domain)
2673 }
2674 Err(_) => (8082u16,
2675 std::env::var("SHUNT_RELAY_URL")
2676 .unwrap_or_else(|_| "https://relay.ramcharan.shop".to_string()),
2677 None),
2678 };
2679
2680 match mode {
2681 ShareMode::Tunnel => {
2682 print_splash(&[
2683 format!("{} {}", brand_green("shunt"), dim(&format!("v{}", env!("CARGO_PKG_VERSION")))),
2684 dim("Starting Cloudflare tunnel…").to_string(),
2685 String::new(),
2686 ]);
2687 println!(" {} Make sure the proxy is running: {}", dim("·"), cyan("shunt start"));
2688 println!();
2689
2690 let url = start_cloudflare_tunnel(port)?;
2691 share_and_print(&url, &key, &relay_url, "Tunnel active", &[
2692 format!(" {} Code expires in 10 minutes — one-time use", dim("·")),
2693 format!(" {} Tunnel is active — keep this terminal open.", dim("·")),
2694 format!(" {} Press Ctrl+C to stop.", dim("·")),
2695 ]).await;
2696
2697 tokio::signal::ctrl_c().await.ok();
2698 println!("\n {} Tunnel closed.", dim("·"));
2699 }
2700
2701 ShareMode::CustomDomain => {
2702 let domain = if let Some(d) = saved_domain {
2704 d
2705 } else {
2706 use std::io::Write;
2707 println!();
2708 println!(" {} Enter your domain URL (e.g. {}): ",
2709 dim("·"), dim("https://shunt.mysite.com"));
2710 print!(" ");
2711 std::io::stdout().flush()?;
2712 let mut input = String::new();
2713 std::io::stdin().read_line(&mut input)?;
2714 let domain = input.trim().trim_end_matches('/').to_string();
2715 if domain.is_empty() {
2716 bail!("No domain entered.");
2717 }
2718 if !domain.starts_with("http") {
2719 bail!("Domain must start with http:// or https://");
2720 }
2721 let mut cfg_text = std::fs::read_to_string(&config_p)?;
2723 cfg_text = insert_into_server_section(&cfg_text,
2724 &format!("custom_domain = \"{domain}\""));
2725 std::fs::write(&config_p, &cfg_text)?;
2726 println!(" {} Saved {} to config.", green(CHECK), cyan(&domain));
2727 domain
2728 };
2729
2730 share_and_print(&domain, &key, &relay_url, "Online sharing (custom domain)", &[
2731 format!(" {} Code expires in 10 minutes — one-time use", dim("·")),
2732 format!(" {} Make sure {} is pointing to port {} on this machine.",
2733 dim("·"), cyan(&domain), port),
2734 format!(" {} Restart to apply: {}", dim("·"), cyan("shunt start")),
2735 format!(" {} To stop sharing: {}", dim("·"), cyan("shunt share --stop")),
2736 ]).await;
2737 }
2738
2739 ShareMode::Lan => {
2740 let ip = local_ip().unwrap_or_else(|| "<your-ip>".to_string());
2741 let base_url = format!("http://{ip}:{port}");
2742
2743 share_and_print(&base_url, &key, &relay_url, "Remote sharing enabled (LAN)", &[
2744 format!(" {} Code expires in 10 minutes — one-time use", dim("·")),
2745 format!(" {} Both devices must be on the same network.", dim("·")),
2746 format!(" {} Restart to apply: {}", dim("·"), cyan("shunt start")),
2747 format!(" {} To stop sharing: {}", dim("·"), cyan("shunt share --stop")),
2748 ]).await;
2749 }
2750
2751 ShareMode::Stop => unreachable!(),
2752 }
2753
2754 Ok(())
2755}
2756
2757async fn share_and_print(base_url: &str, key: &str, relay_url: &str, subtitle: &str, hints: &[String]) {
2759 let share_code = crate::sync::generate_share_code();
2760 match crate::sync::push_share(&share_code, base_url, key, relay_url).await {
2761 Ok(()) => {
2762 print_splash(&[
2763 format!("{} {}", brand_green("shunt"), dim(&format!("v{}", env!("CARGO_PKG_VERSION")))),
2764 dim(subtitle).to_string(),
2765 String::new(),
2766 ]);
2767 println!(" {} Share code:\n", green(CHECK));
2768 println!(" {}\n", cyan(&share_code));
2769 println!(" {} On the other device, run:", dim("·"));
2770 println!(" {}", cyan(&format!("shunt connect {share_code}")));
2771 println!();
2772 for hint in hints { println!("{hint}"); }
2773 println!();
2774 }
2775 Err(e) => {
2776 print_splash(&[
2778 format!("{} {}", brand_green("shunt"), dim(&format!("v{}", env!("CARGO_PKG_VERSION")))),
2779 dim(subtitle).to_string(),
2780 String::new(),
2781 ]);
2782 println!(" Set on the remote device:\n");
2783 println!(" {}{}", dim("export ANTHROPIC_BASE_URL="), cyan(base_url));
2784 println!(" {}{}", dim("export ANTHROPIC_API_KEY="), cyan(key));
2785 println!();
2786 println!(" {} (share code unavailable: {e})", dim("·"));
2787 for hint in hints { println!("{hint}"); }
2788 println!();
2789 }
2790 }
2791}
2792
2793fn start_cloudflare_tunnel(port: u16) -> Result<String> {
2796 use std::io::{BufRead, BufReader};
2797 use std::process::{Command, Stdio};
2798
2799 let mut child = Command::new("cloudflared")
2800 .args(["tunnel", "--url", &format!("http://localhost:{port}")])
2801 .stderr(Stdio::piped())
2802 .stdout(Stdio::null())
2803 .spawn()
2804 .map_err(|e| {
2805 if e.kind() == std::io::ErrorKind::NotFound {
2806 anyhow::anyhow!(
2807 "cloudflared not found.\n\n Install it:\n brew install cloudflared\n or: https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/downloads/"
2808 )
2809 } else {
2810 anyhow::anyhow!("Failed to start cloudflared: {e}")
2811 }
2812 })?;
2813
2814 let stderr = child.stderr.take().expect("stderr was piped");
2815 let reader = BufReader::new(stderr);
2816
2817 for line in reader.lines() {
2818 let line = line?;
2819 if let Some(url) = extract_cloudflare_url(&line) {
2820 std::mem::forget(child);
2822 return Ok(url);
2823 }
2824 }
2825
2826 bail!("cloudflared exited before providing a tunnel URL")
2827}
2828
2829fn extract_cloudflare_url(line: &str) -> Option<String> {
2830 let lower = line.to_lowercase();
2834 if lower.contains("trycloudflare.com") || lower.contains("cfargotunnel.com") {
2835 if let Some(start) = line.find("https://") {
2837 let rest = &line[start..];
2838 let end = rest.find(|c: char| c.is_whitespace() || c == '|' || c == '"')
2839 .unwrap_or(rest.len());
2840 return Some(rest[..end].trim_end_matches('/').to_owned());
2841 }
2842 }
2843 None
2844}
2845
2846fn generate_remote_key() -> String {
2847 hex::encode(crate::oauth::rand_bytes::<16>())
2848}
2849
2850fn extract_remote_key(config: &str) -> Option<String> {
2851 for line in config.lines() {
2852 let line = line.trim();
2853 if line.starts_with("remote_key") {
2854 return line.split('=')
2855 .nth(1)
2856 .map(|s| s.trim().trim_matches('"').to_owned());
2857 }
2858 }
2859 None
2860}
2861
2862fn insert_into_server_section(config: &str, line: &str) -> String {
2863 if let Some(pos) = config.find("\n[[accounts]]") {
2865 let (before, after) = config.split_at(pos);
2866 format!("{before}\n{line}{after}")
2867 } else {
2868 format!("{config}\n{line}\n")
2869 }
2870}
2871
2872fn local_ip() -> Option<String> {
2873 let socket = std::net::UdpSocket::bind("0.0.0.0:0").ok()?;
2874 socket.connect("8.8.8.8:80").ok()?;
2875 Some(socket.local_addr().ok()?.ip().to_string())
2876}
2877
2878async fn offer_restart(config_override: Option<PathBuf>) {
2880 use std::io::Write;
2881 let Ok(cfg) = crate::config::load_config(config_override.as_deref()) else { return };
2882 let health_url = format!("http://{}:{}/health", cfg.server.host, cfg.server.port);
2883 let running = reqwest::get(&health_url).await
2884 .map(|r| r.status().is_success())
2885 .unwrap_or(false);
2886 if !running { return; }
2887
2888 print!(" {} Proxy is running — restart now? [Y/n]: ", dim("·"));
2889 std::io::stdout().flush().ok();
2890 let mut buf = String::new();
2891 std::io::stdin().read_line(&mut buf).ok();
2892 if matches!(buf.trim().to_lowercase().as_str(), "n" | "no") {
2893 println!(" {} Run {} when ready.", dim("·"), cyan("shunt restart"));
2894 return;
2895 }
2896 if let Err(e) = cmd_restart(config_override).await {
2897 println!(" {} Restart failed: {e}", red(CROSS));
2898 }
2899}
2900
2901async fn cmd_connect(code: String) -> Result<()> {
2906 use std::io::{self, Write};
2907
2908 crate::sync::validate_share_code(&code)?;
2909
2910 let relay_url = std::env::var("SHUNT_RELAY_URL")
2911 .unwrap_or_else(|_| "https://relay.ramcharan.shop".to_string());
2912
2913 print_splash(&[
2914 format!("{} {}", brand_green("shunt"), dim(&format!("v{}", env!("CARGO_PKG_VERSION")))),
2915 dim("Connecting to remote shunt…").to_string(),
2916 String::new(),
2917 ]);
2918
2919 println!(" {} Fetching credentials for {}…", dim("·"), cyan(&code));
2920 println!();
2921
2922 let (base_url, api_key) = crate::sync::pull_share(&code, &relay_url).await?;
2923
2924 println!(" {} Retrieved:", green(CHECK));
2925 println!(" {} {}", dim("ANTHROPIC_BASE_URL ="), cyan(&base_url));
2926 println!(" {} {}", dim("ANTHROPIC_API_KEY ="), cyan(&format!("{}…", &api_key[..api_key.len().min(12)])));
2927 println!();
2928
2929 let profile = detect_shell_profile();
2931 let prompt = match &profile {
2932 Some(p) => format!(" Write to {}? [Y/n]: ", dim(&p.display().to_string())),
2933 None => " Write to shell profile? [Y/n]: ".into(),
2934 };
2935 print!("{prompt}");
2936 io::stdout().flush()?;
2937 let mut buf = String::new();
2938 io::stdin().read_line(&mut buf)?;
2939
2940 if !matches!(buf.trim().to_lowercase().as_str(), "n" | "no") {
2941 match profile {
2942 Some(p) => {
2943 write_connect_vars_to_profile(&p, &base_url, &api_key)?;
2944 }
2945 None => {
2946 println!(" {} Could not detect shell profile. Set manually:", dim("·"));
2947 println!(" export ANTHROPIC_BASE_URL={base_url}");
2948 println!(" export ANTHROPIC_API_KEY={api_key}");
2949 }
2950 }
2951 }
2952
2953 if let Err(e) = write_claude_settings(&base_url, &api_key) {
2955 println!(" {} Could not write ~/.claude/settings.json: {e}", dim("·"));
2956 } else {
2957 println!(" {} Written to {}", green(CHECK), dim("~/.claude/settings.json"));
2958 }
2959
2960 println!();
2961 println!(" {} Done! Restart shell or run: {}", green(CHECK),
2962 cyan(detect_shell_profile()
2963 .map(|p| format!("source {}", p.display()))
2964 .unwrap_or_else(|| "source ~/.zshrc".to_string()).as_str()));
2965 println!();
2966
2967 Ok(())
2968}
2969
2970fn write_connect_vars_to_profile(profile: &std::path::Path, base_url: &str, api_key: &str) -> Result<()> {
2973 use std::io::Write as _;
2974
2975 let url_line = format!("export ANTHROPIC_BASE_URL={base_url}");
2976 let key_line = format!("export ANTHROPIC_API_KEY={api_key}");
2977
2978 if profile.exists() {
2979 let contents = std::fs::read_to_string(profile)?;
2980 let has_url = contents.contains("ANTHROPIC_BASE_URL");
2981 let has_key = contents.contains("ANTHROPIC_API_KEY");
2982
2983 if has_url || has_key {
2984 let updated: String = contents
2986 .lines()
2987 .map(|l| {
2988 if l.contains("ANTHROPIC_BASE_URL") {
2989 url_line.as_str()
2990 } else if l.contains("ANTHROPIC_API_KEY") {
2991 key_line.as_str()
2992 } else {
2993 l
2994 }
2995 })
2996 .collect::<Vec<_>>()
2997 .join("\n")
2998 + "\n";
2999 let mut final_content = updated;
3001 if !has_url {
3002 final_content.push_str(&format!("{url_line}\n"));
3003 }
3004 if !has_key {
3005 final_content.push_str(&format!("{key_line}\n"));
3006 }
3007 std::fs::write(profile, &final_content)?;
3008 println!(" {} Updated {} — {}", green(CHECK),
3009 dim(&profile.display().to_string()),
3010 cyan("ANTHROPIC_BASE_URL + ANTHROPIC_API_KEY"));
3011 return Ok(());
3012 }
3013 }
3014
3015 let mut f = std::fs::OpenOptions::new().create(true).append(true).open(profile)?;
3017 writeln!(f, "\n# Added by shunt connect")?;
3018 writeln!(f, "{url_line}")?;
3019 writeln!(f, "{key_line}")?;
3020 println!(" {} Added to {} — {}", green(CHECK),
3021 dim(&profile.display().to_string()),
3022 cyan("ANTHROPIC_BASE_URL + ANTHROPIC_API_KEY"));
3023 Ok(())
3024}
3025
3026fn write_claude_settings(base_url: &str, api_key: &str) -> Result<()> {
3029 let home = dirs::home_dir().context("Cannot find home directory")?;
3030 let settings_path = home.join(".claude").join("settings.json");
3031
3032 let mut root: serde_json::Value = if settings_path.exists() {
3033 let text = std::fs::read_to_string(&settings_path)?;
3034 serde_json::from_str(&text).unwrap_or(serde_json::Value::Object(Default::default()))
3035 } else {
3036 serde_json::Value::Object(Default::default())
3037 };
3038
3039 let obj = root.as_object_mut().context("settings.json root is not an object")?;
3040 let env = obj.entry("env").or_insert(serde_json::Value::Object(Default::default()));
3041 let env_obj = env.as_object_mut().context("settings.json 'env' is not an object")?;
3042 env_obj.insert("ANTHROPIC_BASE_URL".to_string(), serde_json::Value::String(base_url.to_string()));
3043 env_obj.insert("ANTHROPIC_API_KEY".to_string(), serde_json::Value::String(api_key.to_string()));
3044
3045 if let Some(parent) = settings_path.parent() {
3046 std::fs::create_dir_all(parent)?;
3047 }
3048 std::fs::write(&settings_path, serde_json::to_string_pretty(&root)?)?;
3049 Ok(())
3050}
3051
3052fn offer_shell_export() -> Result<()> {
3053 use std::io::{self, Write};
3054
3055 let line = "export ANTHROPIC_BASE_URL=http://127.0.0.1:8082";
3056 println!();
3057 println!(" To use with Claude Code, set:");
3058 println!(" {}", cyan(line));
3059
3060 let profile = detect_shell_profile();
3061 let prompt = match &profile {
3062 Some(p) => format!(" Add to {}? [Y/n]: ", dim(&p.display().to_string())),
3063 None => " Add to your shell profile? [Y/n]: ".into(),
3064 };
3065
3066 print!("{prompt}");
3067 io::stdout().flush()?;
3068 let mut buf = String::new();
3069 io::stdin().read_line(&mut buf)?;
3070
3071 if matches!(buf.trim().to_lowercase().as_str(), "n" | "no") {
3072 return Ok(());
3073 }
3074
3075 let path = match profile {
3076 Some(p) => p,
3077 None => {
3078 println!(" {} Could not detect shell profile. Add manually.", dim("·"));
3079 return Ok(());
3080 }
3081 };
3082
3083 if path.exists() {
3084 let contents = std::fs::read_to_string(&path)?;
3085 if contents.contains("ANTHROPIC_BASE_URL") {
3086 println!(" {} Already set in {}", CHECK, dim(&path.display().to_string()));
3087 return Ok(());
3088 }
3089 }
3090
3091 let mut f = std::fs::OpenOptions::new().create(true).append(true).open(&path)?;
3092 #[allow(unused_imports)]
3093 use std::io::Write as _;
3094 writeln!(f, "\n# Added by shunt")?;
3095 writeln!(f, "{line}")?;
3096 println!(" {} Added to {} — restart shell or: {}", green(CHECK),
3097 dim(&path.display().to_string()),
3098 cyan(&format!("source {}", path.display())));
3099
3100 Ok(())
3101}
3102
3103async fn cmd_uninstall() -> Result<()> {
3108 use std::io::Write as _;
3109
3110 let config_dir = dirs::config_dir()
3112 .unwrap_or_else(|| PathBuf::from("."))
3113 .join("shunt");
3114
3115 let data_dir = dirs::data_local_dir()
3116 .unwrap_or_else(|| PathBuf::from("."))
3117 .join("shunt");
3118
3119 let exe = std::env::current_exe().ok();
3120
3121 let shell_profile = detect_shell_profile();
3123 let profile_has_export = shell_profile.as_ref().and_then(|p| {
3124 std::fs::read_to_string(p).ok()
3125 }).map(|s| s.contains("ANTHROPIC_BASE_URL=http://127.0.0.1:")).unwrap_or(false);
3126
3127 #[cfg(target_os = "macos")]
3128 let service_plist = {
3129 let p = service_plist_path();
3130 if p.exists() { Some(p) } else { None }
3131 };
3132 #[cfg(not(target_os = "macos"))]
3133 let service_plist: Option<PathBuf> = None;
3134
3135 #[cfg(target_os = "linux")]
3136 let service_unit = {
3137 let p = service_unit_path();
3138 if p.exists() { Some(p) } else { None }
3139 };
3140 #[cfg(not(target_os = "linux"))]
3141 let service_unit: Option<PathBuf> = None;
3142
3143 print_splash(&[
3145 format!("{} {}", brand_green("shunt"), dim(&format!("v{}", env!("CARGO_PKG_VERSION")))),
3146 red("Uninstall").to_string(),
3147 String::new(),
3148 ]);
3149
3150 println!(" This will permanently remove:");
3151 println!();
3152
3153 if service_plist.is_some() || service_unit.is_some() {
3154 println!(" {} Stop and unregister login service", red("✕"));
3155 }
3156
3157 if config_dir.exists() {
3158 println!(" {} {} {}", red("✕"), dim("delete"), cyan(&config_dir.display().to_string()));
3159 }
3160 if data_dir.exists() && data_dir != config_dir {
3161 println!(" {} {} {}", red("✕"), dim("delete"), cyan(&data_dir.display().to_string()));
3162 }
3163 if let Some(ref p) = shell_profile {
3164 if profile_has_export {
3165 println!(" {} {} ANTHROPIC_BASE_URL from {}", red("✕"), dim("remove"), cyan(&p.display().to_string()));
3166 }
3167 }
3168 if let Some(ref exe_path) = exe {
3169 println!(" {} {} {}", red("✕"), dim("delete"), cyan(&exe_path.display().to_string()));
3170 }
3171
3172 println!();
3173
3174 if !term::confirm("Are you sure you want to completely uninstall shunt?") {
3176 println!(" {} Cancelled.", dim("·"));
3177 println!();
3178 return Ok(());
3179 }
3180
3181 println!();
3183 print!(" {} Type {} to confirm: ", dim("·"), bold("uninstall"));
3184 std::io::stdout().flush()?;
3185 let mut buf = String::new();
3186 std::io::stdin().read_line(&mut buf)?;
3187 if buf.trim() != "uninstall" {
3188 println!(" {} Cancelled.", dim("·"));
3189 println!();
3190 return Ok(());
3191 }
3192
3193 println!();
3194
3195 #[cfg(target_os = "macos")]
3199 if let Some(ref p) = service_plist {
3200 let _ = std::process::Command::new("launchctl")
3201 .args(["unload", &p.display().to_string()])
3202 .output();
3203 let _ = std::fs::remove_file(p);
3204 println!(" {} Login service removed", green(CHECK));
3205 }
3206 #[cfg(target_os = "linux")]
3207 if let Some(ref p) = service_unit {
3208 let _ = std::process::Command::new("systemctl")
3209 .args(["--user", "disable", "--now", "shunt"])
3210 .output();
3211 let _ = std::fs::remove_file(p);
3212 let _ = std::process::Command::new("systemctl")
3213 .args(["--user", "daemon-reload"])
3214 .output();
3215 println!(" {} Login service removed", green(CHECK));
3216 }
3217
3218 if config_dir.exists() {
3220 std::fs::remove_dir_all(&config_dir)
3221 .with_context(|| format!("failed to remove {}", config_dir.display()))?;
3222 println!(" {} Config removed {}", green(CHECK), dim(&config_dir.display().to_string()));
3223 }
3224
3225 if data_dir.exists() && data_dir != config_dir {
3227 std::fs::remove_dir_all(&data_dir)
3228 .with_context(|| format!("failed to remove {}", data_dir.display()))?;
3229 println!(" {} Data removed {}", green(CHECK), dim(&data_dir.display().to_string()));
3230 }
3231
3232 if let Some(ref profile_path) = shell_profile {
3234 if profile_has_export {
3235 if let Ok(contents) = std::fs::read_to_string(profile_path) {
3236 let cleaned: String = contents
3237 .lines()
3238 .filter(|l| {
3239 !l.contains("ANTHROPIC_BASE_URL=http://127.0.0.1:")
3240 && *l != "# Added by shunt"
3241 })
3242 .collect::<Vec<_>>()
3243 .join("\n");
3244 let cleaned = if contents.ends_with('\n') {
3246 format!("{cleaned}\n")
3247 } else {
3248 cleaned
3249 };
3250 std::fs::write(profile_path, cleaned)?;
3251 println!(" {} Shell export removed {}", green(CHECK),
3252 dim(&profile_path.display().to_string()));
3253 }
3254 }
3255 }
3256
3257 if let Some(exe_path) = exe {
3259 let path_str = exe_path.display().to_string();
3261 std::process::Command::new("sh")
3262 .args(["-c", &format!("sleep 0.3 && rm -f '{path_str}'")])
3263 .stdin(std::process::Stdio::null())
3264 .stdout(std::process::Stdio::null())
3265 .stderr(std::process::Stdio::null())
3266 .spawn()
3267 .ok();
3268 println!(" {} Binary removed {}", green(CHECK), dim(&exe_path.display().to_string()));
3269 }
3270
3271 println!();
3272 println!(" {} shunt fully removed.", green(CHECK));
3273 println!(" {} Run {} to clear the proxy from this shell session.", dim("·"), cyan("unset ANTHROPIC_BASE_URL"));
3274 println!();
3275
3276 Ok(())
3277}
3278
3279#[cfg(target_os = "macos")]
3284fn service_plist_path() -> PathBuf {
3285 dirs::home_dir()
3286 .unwrap_or_else(|| PathBuf::from("/tmp"))
3287 .join("Library/LaunchAgents/sh.shunt.proxy.plist")
3288}
3289
3290#[cfg(target_os = "linux")]
3291fn service_unit_path() -> PathBuf {
3292 dirs::home_dir()
3293 .unwrap_or_else(|| PathBuf::from("/tmp"))
3294 .join(".config/systemd/user/shunt.service")
3295}
3296
3297fn register_service() -> Result<bool> {
3303 let exe = std::env::current_exe().context("cannot locate current executable")?;
3304 let exe_str = exe.display().to_string();
3305
3306 #[cfg(target_os = "macos")]
3307 {
3308 let plist_path = service_plist_path();
3309 let plist_was_present = plist_path.exists();
3310 if let Some(parent) = plist_path.parent() {
3311 std::fs::create_dir_all(parent)?;
3312 }
3313 let plist = format!(r#"<?xml version="1.0" encoding="UTF-8"?>
3314<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN"
3315 "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
3316<plist version="1.0">
3317<dict>
3318 <key>Label</key>
3319 <string>sh.shunt.proxy</string>
3320 <key>ProgramArguments</key>
3321 <array>
3322 <string>{exe_str}</string>
3323 <string>start</string>
3324 <string>--foreground</string>
3325 </array>
3326 <key>RunAtLoad</key>
3327 <true/>
3328 <key>KeepAlive</key>
3329 <true/>
3330 <key>StandardOutPath</key>
3331 <string>{home}/Library/Logs/shunt.log</string>
3332 <key>StandardErrorPath</key>
3333 <string>{home}/Library/Logs/shunt.log</string>
3334</dict>
3335</plist>
3336"#,
3337 exe_str = exe_str,
3338 home = dirs::home_dir().unwrap_or_default().display(),
3339 );
3340 std::fs::write(&plist_path, &plist)?;
3341
3342 let plist_str = plist_path.display().to_string();
3345
3346 if plist_was_present {
3348 let p = plist_str.clone();
3349 let (tx, rx) = std::sync::mpsc::channel();
3350 std::thread::spawn(move || {
3351 let _ = std::process::Command::new("launchctl")
3352 .args(["unload", &p])
3353 .output();
3354 let _ = tx.send(());
3355 });
3356 let _ = rx.recv_timeout(std::time::Duration::from_secs(4));
3357 }
3358
3359 let (tx, rx) = std::sync::mpsc::channel();
3361 std::thread::spawn(move || {
3362 let ok = std::process::Command::new("launchctl")
3363 .args(["load", "-w", &plist_str])
3364 .output()
3365 .map(|o| o.status.success())
3366 .unwrap_or(false);
3367 let _ = tx.send(ok);
3368 });
3369
3370 let loaded = rx
3371 .recv_timeout(std::time::Duration::from_secs(4))
3372 .unwrap_or(false);
3373
3374 return Ok(loaded);
3375 }
3376
3377 #[cfg(target_os = "linux")]
3378 {
3379 let unit_path = service_unit_path();
3380 if let Some(parent) = unit_path.parent() {
3381 std::fs::create_dir_all(parent)?;
3382 }
3383 let unit = format!(
3384 "[Unit]\nDescription=shunt Claude Code proxy\nAfter=network.target\n\n\
3385 [Service]\nExecStart={exe_str} start --foreground\nRestart=always\nRestartSec=5\n\n\
3386 [Install]\nWantedBy=default.target\n"
3387 );
3388 std::fs::write(&unit_path, &unit)?;
3389
3390 let _ = std::process::Command::new("systemctl")
3391 .args(["--user", "daemon-reload"])
3392 .output();
3393
3394 let out = std::process::Command::new("systemctl")
3395 .args(["--user", "enable", "--now", "shunt"])
3396 .output()
3397 .context("failed to run systemctl")?;
3398
3399 return Ok(out.status.success());
3400 }
3401
3402 #[cfg(not(any(target_os = "macos", target_os = "linux")))]
3403 bail!("Service management is only supported on macOS and Linux.");
3404
3405 #[allow(unreachable_code)]
3406 Ok(false)
3407}
3408
3409async fn cmd_service_install() -> Result<()> {
3410 print_splash(&[
3411 format!("{} {}", brand_green("shunt"), dim(&format!("v{}", env!("CARGO_PKG_VERSION")))),
3412 dim("Service install"),
3413 String::new(),
3414 ]);
3415
3416 let config_p = config_path();
3421 let stdin_is_tty = unsafe { libc::isatty(libc::STDIN_FILENO) != 0 };
3422 if !config_p.exists() {
3423 if stdin_is_tty {
3424 cmd_setup_auto(None).await?;
3425 } else {
3426 println!(" {} No config — run {} in a terminal to import credentials",
3427 yellow("·"), cyan("shunt setup"));
3428 }
3429 }
3430
3431 let port = crate::config::load_config(None)
3433 .map(|c| c.server.port)
3434 .unwrap_or(8082);
3435
3436 print!(" {} Registering login service… ", dim("·"));
3438 use std::io::Write as _;
3439 std::io::stdout().flush().ok();
3440 let service_loaded = register_service()?;
3441 if service_loaded {
3442 println!("{}", green("done"));
3443 } else {
3444 println!("{}", dim("skipped (SSH session — activates on next login)"));
3445 }
3446
3447 if !service_loaded {
3450 print!(" {} Starting proxy… ", dim("·"));
3451 std::io::stdout().flush().ok();
3452 let exe = std::env::current_exe().context("cannot locate current executable")?;
3453 let _ = std::process::Command::new(&exe)
3454 .args(["start", "--daemon"])
3455 .stdin(std::process::Stdio::null())
3456 .stdout(std::process::Stdio::null())
3457 .stderr(std::process::Stdio::null())
3458 .spawn();
3459 }
3460
3461 auto_write_shell_export(port);
3463
3464 tokio::time::sleep(std::time::Duration::from_millis(500)).await;
3466 let config = crate::config::load_config(None).ok();
3467 let host = config.as_ref().map(|c| c.server.host.clone()).unwrap_or_else(|| "127.0.0.1".into());
3468 let running = wait_for_health(&host, port, 8).await;
3469 if !service_loaded {
3470 println!("{}", if running { green("done").to_string() } else { dim("starting…").to_string() });
3471 }
3472
3473 println!();
3474 if running {
3475 println!(" {} {} {}", green(DOT), green_bold("proxy running"),
3476 cyan(&format!("http://{host}:{port}")));
3477 } else {
3478 println!(" {} {} — proxy starting in background",
3479 yellow(DOT), yellow("starting"));
3480 }
3481
3482 #[cfg(target_os = "macos")]
3483 if service_loaded {
3484 println!(" {} LaunchAgent registered — starts automatically at login", green(CHECK));
3485 } else {
3486 println!(" {} LaunchAgent written — will activate on next login", yellow("·"));
3487 println!(" {} To activate now (in a GUI session): {}",
3488 dim("·"), cyan("launchctl load -w ~/Library/LaunchAgents/sh.shunt.proxy.plist"));
3489 }
3490 #[cfg(target_os = "linux")]
3491 if service_loaded {
3492 println!(" {} systemd user unit registered — starts automatically at login", green(CHECK));
3493 } else {
3494 println!(" {} systemd unit written — run {} to activate",
3495 yellow("·"), cyan("systemctl --user enable --now shunt"));
3496 }
3497
3498 println!();
3499 println!(" {} To unregister: {}", dim("·"), cyan("shunt service uninstall"));
3500 println!();
3501
3502 Ok(())
3503}
3504
3505async fn cmd_service_uninstall() -> Result<()> {
3506 #[cfg(target_os = "macos")]
3507 {
3508 let plist_path = service_plist_path();
3509 if plist_path.exists() {
3510 let _ = std::process::Command::new("launchctl")
3511 .args(["unload", &plist_path.display().to_string()])
3512 .output();
3513 std::fs::remove_file(&plist_path)
3514 .context("failed to remove plist")?;
3515 println!(" {} Service unregistered.", green(CHECK));
3516 } else {
3517 println!(" {} Service not registered.", dim("·"));
3518 }
3519 }
3520
3521 #[cfg(target_os = "linux")]
3522 {
3523 let unit_path = service_unit_path();
3524 let _ = std::process::Command::new("systemctl")
3525 .args(["--user", "disable", "--now", "shunt"])
3526 .output();
3527 if unit_path.exists() {
3528 std::fs::remove_file(&unit_path)
3529 .context("failed to remove unit file")?;
3530 }
3531 let _ = std::process::Command::new("systemctl")
3532 .args(["--user", "daemon-reload"])
3533 .output();
3534 println!(" {} Service unregistered.", green(CHECK));
3535 }
3536
3537 #[cfg(not(any(target_os = "macos", target_os = "linux")))]
3538 bail!("Service management is only supported on macOS and Linux.");
3539
3540 println!();
3541 Ok(())
3542}
3543
3544async fn cmd_service_status() -> Result<()> {
3545 #[cfg(target_os = "macos")]
3546 {
3547 let plist_path = service_plist_path();
3548 let registered = plist_path.exists();
3549 if registered {
3550 println!(" {} Registered {}", green(CHECK), dim(&plist_path.display().to_string()));
3551 } else {
3552 println!(" {} Not registered (run {})", dim("·"), cyan("shunt service install"));
3553 }
3554
3555 let out = std::process::Command::new("launchctl")
3557 .args(["list", "sh.shunt.proxy"])
3558 .output();
3559 let running = out.map(|o| o.status.success()).unwrap_or(false);
3560 if running {
3561 println!(" {} Running (launchd)", green(DOT));
3562 } else {
3563 println!(" {} Not running", dim(DOT));
3564 }
3565 }
3566
3567 #[cfg(target_os = "linux")]
3568 {
3569 let unit_path = service_unit_path();
3570 let registered = unit_path.exists();
3571 if registered {
3572 println!(" {} Registered {}", green(CHECK), dim(&unit_path.display().to_string()));
3573 } else {
3574 println!(" {} Not registered (run {})", dim("·"), cyan("shunt service install"));
3575 }
3576
3577 let out = std::process::Command::new("systemctl")
3578 .args(["--user", "is-active", "shunt"])
3579 .output();
3580 let active = out.map(|o| o.status.success()).unwrap_or(false);
3581 if active {
3582 println!(" {} Running (systemd)", green(DOT));
3583 } else {
3584 println!(" {} Not running", dim(DOT));
3585 }
3586 }
3587
3588 #[cfg(not(any(target_os = "macos", target_os = "linux")))]
3589 println!(" {} Service management is only supported on macOS and Linux.", dim("·"));
3590
3591 println!();
3592 Ok(())
3593}
3594
3595fn detect_shell_profile() -> Option<PathBuf> {
3596 let home = dirs::home_dir()?;
3597 if let Ok(shell) = std::env::var("SHELL") {
3598 if shell.contains("zsh") { return Some(home.join(".zshrc")); }
3599 if shell.contains("fish") { return Some(home.join(".config/fish/config.fish")); }
3600 if shell.contains("bash") {
3601 let p = home.join(".bash_profile");
3602 return Some(if p.exists() { p } else { home.join(".bashrc") });
3603 }
3604 }
3605 for f in &[".zshrc", ".bashrc", ".bash_profile"] {
3606 let p = home.join(f);
3607 if p.exists() { return Some(p); }
3608 }
3609 None
3610}