feat: add headless agent management to CLI and both desktop clients

This commit is contained in:
tongtong committed 2026-11-12 21:17:44 +08:00
1 parent e91fa0235c
commit 6916dd54fb
50 files changed
+4837 -148

No files matched your search

+12
View File
@@ -0,0 +1,12 @@
[package]
name = "adsctl"
version.workspace = true
edition.workspace = true
license.workspace = true
[dependencies]
ads-core = { path = "../crates/ads-core" }
ads-management = { path = "../crates/ads-management" }
anyhow.workspace = true
clap.workspace = true
serde_json.workspace = true
tokio.workspace = true
+342
View File
@@ -0,0 +1,342 @@
use ads_core::{validate_token, NetworkArgs};
use ads_management::{AgentConfig, DeviceConfig, LogPage, Request, Response};
use anyhow::{bail, Context, Result};
use clap::{Parser, Subcommand};
use std::{path::PathBuf, time::Duration};
#[derive(Parser)]
#[command(version, about = "ADS headless agent management CLI")]
struct Args {
#[command(flatten)]
network: NetworkArgs,
#[arg(long, global = true)]
config: Option<PathBuf>,
/// Remote agent ID; omit for local named pipe / Unix socket
#[arg(long, global = true)]
agent: Option<String>,
#[arg(long, global = true)]
credentials: Option<PathBuf>,
#[arg(long, global = true)]
json: bool,
#[command(subcommand)]
command: Command,
}
#[derive(Subcommand, Clone)]
enum Command {
Init {
#[arg(long)]
id: String,
#[arg(long)]
name: Option<String>,
},
Status,
Restart,
/// Read one structured request from stdin (for GUI and automation clients)
Request,
Agents {
#[command(subcommand)]
command: Agents,
},
Devices {
#[command(subcommand)]
command: Devices,
},
Config {
#[command(subcommand)]
command: Config,
},
Logs {
#[arg(long)]
follow: bool,
#[arg(long, default_value_t = 0)]
after: u64,
#[arg(long, default_value_t = 50)]
limit: u32,
},
Service {
#[command(subcommand)]
command: Service,
#[arg(long, global = true)]
system: bool,
},
}
#[derive(Subcommand, Clone)]
enum Agents {
List,
}
#[derive(Subcommand, Clone)]
enum Devices {
List,
Add {
#[arg(long)]
id: String,
#[arg(
long,
conflicts_with = "adb_serial",
required_unless_present = "adb_serial"
)]
target: Option<String>,
#[arg(long)]
adb_serial: Option<String>,
#[arg(long)]
adb_server: Option<String>,
#[arg(long, default_value_t = 5555)]
device_port: u16,
},
Remove {
id: String,
},
Enable {
id: String,
},
Disable {
id: String,
},
}
#[derive(Subcommand, Clone)]
enum Config {
Get,
Validate {
#[arg(long)]
file: Option<PathBuf>,
},
Set {
#[arg(long)]
file: PathBuf,
},
}
#[derive(Subcommand, Clone)]
enum Service {
Install,
Start,
Stop,
Restart,
Status,
Uninstall,
}
fn print_value(value: &serde_json::Value, json: bool) -> Result<()> {
if json {
println!("{}", serde_json::to_string(value)?)
} else {
println!("{}", serde_json::to_string_pretty(value)?)
};
Ok(())
}
async fn invoke(args: &Args, request: &Request) -> Result<Response> {
if let Some(id) = &args.agent {
if !ads_core::valid_device_id(id) {
bail!("invalid remote agent ID")
}
let credential = args
.credentials
.clone()
.unwrap_or_else(|| ads_management::default_config().with_file_name("admin.env"));
let token = ads_management::credential(&credential, "ADS_ADMIN_TOKEN")?;
let mut ws = ads_core::dial(
args.network.url("/v3/rpc", &[("agent", id)])?,
&token,
args.network.connect_address.as_deref(),
)
.await?;
ads_management::write_ws(&mut ws, request).await?;
tokio::time::timeout(Duration::from_secs(20), ads_management::read_ws(&mut ws))
.await
.context("remote management request timed out")?
} else {
ads_management::ipc::request(
&args
.config
.clone()
.unwrap_or_else(ads_management::default_config),
request,
)
.await
}
}
#[tokio::main]
async fn main() -> Result<()> {
let mut args = Args::parse();
// A private admin.env may carry the same optional TCP origin override as client.env.
if args.network.connect_address.is_none() {
if let Some(path) = &args.credentials {
if let Ok(data) = std::fs::read_to_string(path) {
for line in data.lines() {
if let Some(value) = line.strip_prefix("ADS_CONNECT_ADDRESS=") {
args.network.connect_address = Some(value.into());
}
}
}
}
}
let config = args
.config
.clone()
.unwrap_or_else(ads_management::default_config);
match &args.command {
Command::Init { id, name } => {
if args.agent.is_some() {
bail!("init is a local operation")
};
if config.exists() {
bail!("config already exists; use config set to update it")
}
let cfg = AgentConfig {
version: 1,
id: id.clone(),
name: name.clone().unwrap_or_else(|| id.clone()),
server: args.network.server.clone(),
connect_address: args.network.connect_address.clone(),
allow_insecure: args.network.allow_insecure,
adb_server: "127.0.0.1:5037".into(),
devices: vec![],
};
cfg.validate()?;
let source = args
.credentials
.clone()
.unwrap_or_else(|| config.with_file_name("agent.env"));
let token = ads_management::credential(&source, "ADS_AGENT_TOKEN")?;
validate_token(&token)?;
ads_management::save_private(
&config.with_file_name("agent.env"),
format!("ADS_AGENT_TOKEN={token}\n").as_bytes(),
)?;
ads_management::save_private(&config, &serde_json::to_vec_pretty(&cfg)?)?;
return print_value(&serde_json::json!({"config":config,"agent":id}), args.json);
}
Command::Agents { .. } => {
let path = args
.credentials
.clone()
.unwrap_or_else(|| config.with_file_name("admin.env"));
let token = ads_management::credential(&path, "ADS_ADMIN_TOKEN")?;
let mut ws = ads_core::dial(
args.network.url("/v3/agents", &[])?,
&token,
args.network.connect_address.as_deref(),
)
.await?;
let value: serde_json::Value = ads_management::read_ws(&mut ws).await?;
return print_value(&value, args.json);
}
Command::Config {
command: Config::Validate { file },
} => {
let cfg = if args.agent.is_some() && file.is_none() {
let value = invoke(&args, &Request::ConfigGet).await?.value()?;
let value: AgentConfig = serde_json::from_value(value)?;
value.validate()?;
value
} else {
AgentConfig::load(file.as_ref().unwrap_or(&config))?
};
return print_value(
&serde_json::json!({"valid":true,"agent":cfg.id,"devices":cfg.devices.len()}),
args.json,
);
}
Command::Service { command, system } => {
if args.agent.is_some() {
bail!("service installation and OS service operations are local only; use restart for remote managed restart")
}
use ads_management::service::Action;
let action = match command {
Service::Install => Action::Install,
Service::Start => Action::Start,
Service::Stop => Action::Stop,
Service::Restart => Action::Restart,
Service::Status => Action::Status,
Service::Uninstall => Action::Uninstall,
};
let start_now = !matches!(action, Action::Install)
|| ads_management::ipc::request(&config, &Request::Status)
.await
.is_err();
ads_management::service::run(action, &config, *system, start_now)?;
return print_value(&serde_json::json!({"ok":true}), args.json);
}
Command::Logs {
follow,
after,
limit,
} => {
let mut cursor = *after;
let mut instance = String::new();
loop {
let value = invoke(
&args,
&Request::Logs {
after: cursor,
limit: *limit,
},
)
.await?
.value()?;
let page: LogPage = serde_json::from_value(value.clone())?;
if !instance.is_empty() && instance != page.instance {
cursor = 0;
instance = page.instance;
continue;
}
cursor = page.next;
instance = page.instance;
if args.json {
print_value(&value, true)?
} else {
for entry in page.entries {
println!("{} {} {}", entry.time, entry.level, entry.message)
}
}
if !follow {
return Ok(());
}
tokio::select! {_=tokio::time::sleep(Duration::from_secs(1))=>{},_=tokio::signal::ctrl_c()=>return Ok(())}
}
}
_ => {}
}
let request = match args.command.clone() {
Command::Request => {
use std::io::Read;
let mut input = Vec::new();
std::io::stdin().take(65537).read_to_end(&mut input)?;
if input.len() > 65536 {
bail!("request exceeds 64 KiB")
};
serde_json::from_slice::<Request>(&input)?
}
Command::Status => Request::Status,
Command::Restart => Request::Restart,
Command::Devices { command } => match command {
Devices::List => Request::DevicesList,
Devices::Add {
id,
target,
adb_serial,
adb_server,
device_port,
} => Request::DeviceAdd {
device: DeviceConfig {
id,
target,
adb_serial,
adb_server,
device_port,
enabled: true,
},
},
Devices::Remove { id } => Request::DeviceRemove { id },
Devices::Enable { id } => Request::DeviceEnable { id, enabled: true },
Devices::Disable { id } => Request::DeviceEnable { id, enabled: false },
},
Command::Config {
command: Config::Get,
} => Request::ConfigGet,
Command::Config {
command: Config::Set { ref file },
} => Request::ConfigSet {
config: AgentConfig::load(file)?,
},
_ => unreachable!(),
};
print_value(&invoke(&args, &request).await?.value()?, args.json)
}