use std::path::PathBuf;
use anyhow::Result;
use clap::{Parser, Subcommand};
use tracing::{info, warn};
use anyhow::Context;
use ilink_hub::bridge::{
builtin, default_local_credential_path, resolve_hub_connection, run_bridge, BridgeApp,
BridgeStop,
};
use ilink_hub::paths::{
default_bridge_config_path, default_bridge_manager_credentials_dir, default_bridge_profiles_dir,
};
#[derive(Parser)]
#[command(name = "ilink-hub-bridge")]
#[command(
version,
about = "Bridge WeChat (via iLink Hub) to a local coding CLI (Claude Code, Codex, …)"
)]
struct Cli {
#[arg(
long,
env = "WEIXIN_BASE_URL",
default_value = "http://127.0.0.1:8765",
global = true
)]
hub_url: String,
#[arg(long, env = "WEIXIN_TOKEN", global = true)]
token: Option<String>,
#[arg(long, env = "ILINKHUB_BRIDGE_CREDS", global = true)]
cred_file: Option<String>,
#[arg(long, default_value_t = false, global = true)]
pair: bool,
#[arg(long, env = "ILINKHUB_BRIDGE_REGISTER_NAME", global = true)]
register_name: Option<String>,
#[arg(long, default_value_t = false, global = true)]
force_register: bool,
#[arg(long)]
config: Option<PathBuf>,
#[command(subcommand)]
command: Option<Commands>,
}
#[derive(Subcommand)]
enum Commands {
Profile {
#[arg(value_name = "TYPE")]
profile_type: String,
},
Manager {
#[arg(long, default_value_os_t = default_bridge_profiles_dir())]
profiles_dir: PathBuf,
#[arg(long, default_value_os_t = default_bridge_manager_credentials_dir())]
credentials_dir: PathBuf,
#[arg(long, default_value_t = 5)]
scan_interval_secs: u64,
#[arg(long, default_value_t = 5)]
restart_backoff_secs: u64,
#[arg(long, default_value_t = 60)]
max_restart_backoff_secs: u64,
},
}
fn explicit_token(cli: &Cli) -> Option<&str> {
cli.token
.as_deref()
.map(str::trim)
.filter(|s| !s.is_empty())
}
#[tokio::main]
async fn main() -> Result<()> {
tracing_subscriber::fmt()
.with_env_filter(
tracing_subscriber::EnvFilter::from_default_env()
.add_directive("ilink_hub=info".parse()?),
)
.init();
let cli = Cli::parse();
match &cli.command {
Some(Commands::Profile { profile_type }) => {
builtin::run_builtin_profile(profile_type).await
}
Some(Commands::Manager {
profiles_dir,
credentials_dir,
scan_interval_secs,
restart_backoff_secs,
max_restart_backoff_secs,
}) => {
if explicit_token(&cli).is_some()
|| cli.cred_file.is_some()
|| cli.register_name.is_some()
|| cli.pair
{
tracing::warn!(
"manager mode ignores --token/WEIXIN_TOKEN, --cred-file, --register-name, and --pair; \
each profile gets an independent auto-registered child bridge"
);
}
let mut opts = ilink_hub::bridge::manager::BridgeManagerOptions::new(
cli.hub_url.clone(),
profiles_dir.clone(),
credentials_dir.clone(),
);
opts.scan_interval = std::time::Duration::from_secs((*scan_interval_secs).max(1));
opts.restart_backoff = std::time::Duration::from_secs((*restart_backoff_secs).max(1));
opts.max_restart_backoff =
std::time::Duration::from_secs((*max_restart_backoff_secs).max(1));
opts.force_register = cli.force_register;
ilink_hub::bridge::manager::run_bridge_manager(opts).await
}
None => {
let config_path = cli
.config
.clone()
.unwrap_or_else(default_bridge_config_path);
let app = BridgeApp::load(&config_path)?;
info!(config_path = %config_path.display(), "loaded bridge config");
let cred_path = cli
.cred_file
.as_deref()
.map(str::trim)
.filter(|s| !s.is_empty())
.map(std::path::PathBuf::from)
.unwrap_or_else(default_local_credential_path);
let using_explicit_token = explicit_token(&cli).is_some();
'reconnect: loop {
let (hub_url, token) = resolve_hub_connection(
&cli.hub_url,
explicit_token(&cli),
cli.cred_file.as_deref(),
cli.pair,
cli.register_name.as_deref(),
cli.force_register,
Some(config_path.as_path()),
)
.await?;
info!(%hub_url, "using Hub base URL for downstream");
let mut handle = tokio::spawn(run_bridge(hub_url, token, app.clone()));
tokio::select! {
_ = tokio::signal::ctrl_c() => {
handle.abort();
let _ = handle.await;
info!("exit");
return Ok(());
}
result = &mut handle => {
match result {
Ok(BridgeStop::TokenRejected) if using_explicit_token => {
anyhow::bail!(
"Hub 拒绝了 WEIXIN_TOKEN / --token(未注册或已失效)。\
请重新执行 `ilink-hub register` 或 `ilink-hub-bridge --force-register`。"
);
}
Ok(BridgeStop::TokenRejected) => {
warn!(
path = %cred_path.display(),
"hub token revoked at runtime; removing credentials and re-registering"
);
let _ = tokio::fs::remove_file(&cred_path).await;
continue 'reconnect;
}
Err(e) => {
return Err(e).context("bridge task panicked or failed");
}
}
}
}
}
}
}
}