mod api;
mod auth;
mod commands;
mod config;
mod output;
mod setup;
use std::future::Future;
use clap::{CommandFactory, FromArgMatches, Parser, Subcommand};
#[derive(Parser)]
#[command(
name = "offline",
version,
about = "Build offline-first apps on the Offline Protocol ecosystem",
long_about = "Build offline-first apps on the Offline Protocol ecosystem: authenticate \
with the developer portal, scaffold production-ready apps from ecosystem knowledge, \
and serve that knowledge to AI agents over MCP.\n\nAgent-friendly: every informational \
command supports --json, and `offline mcp serve` exposes the full registry \
as MCP tools/resources."
)]
struct Cli {
#[arg(long, global = true, value_name = "ORG")]
org: Option<String>,
#[command(subcommand)]
command: Command,
}
#[derive(Subcommand)]
enum Command {
Login(commands::login::LoginArgs),
Logout(commands::login::LogoutArgs),
Whoami(commands::login::WhoamiArgs),
Setup(commands::setup::SetupArgs),
#[command(subcommand, alias = "org")]
Orgs(commands::orgs::OrgsCommand),
#[command(subcommand)]
Apps(commands::apps::AppsCommand),
Apply(commands::apply::ApplyArgs),
#[command(subcommand)]
Keys(commands::keys::KeysCommand),
Create(commands::create::CreateArgs),
Init(commands::init::InitArgs),
Add(commands::add::AddArgs),
Plan(commands::plan::PlanArgs),
Doctor(commands::doctor::DoctorArgs),
Update(commands::update::UpdateArgs),
#[command(subcommand)]
Registry(commands::registry::RegistryCommand),
#[command(subcommand)]
Skills(commands::skills::SkillsCommand),
#[command(subcommand)]
Mcp(commands::mcp::McpCommand),
Completions {
#[arg(value_enum)]
shell: clap_complete::Shell,
},
}
#[cfg(unix)]
fn reset_sigpipe() {
unsafe {
libc::signal(libc::SIGPIPE, libc::SIG_DFL);
}
}
#[cfg(not(unix))]
fn reset_sigpipe() {}
fn run_async<F>(future: F) -> anyhow::Result<()>
where
F: Future<Output = anyhow::Result<()>>,
{
tokio::runtime::Builder::new_multi_thread()
.enable_all()
.build()
.expect("tokio runtime")
.block_on(future)
}
const COMMAND_GROUPS: &[(&str, &[&str])] = &[
("Start here", &["create", "init", "doctor"]),
("Build", &["add", "plan", "apply"]),
(
"Account and portal",
&["login", "logout", "whoami", "setup", "orgs", "apps", "keys"],
),
("Knowledge and agents", &["registry", "skills", "mcp"]),
("Maintenance", &["update", "completions"]),
];
fn grouped_commands(cmd: &clap::Command) -> String {
let width = COMMAND_GROUPS
.iter()
.flat_map(|(_, names)| names.iter())
.map(|name| name.len())
.max()
.unwrap_or(0);
let mut out = String::new();
for (heading, names) in COMMAND_GROUPS {
out.push_str(&format!(
"{}\n",
console::style(format!("{heading}:")).bold().underlined()
));
for name in *names {
let about = cmd
.find_subcommand(name)
.and_then(|sub| sub.get_about())
.map(|about| about.to_string())
.unwrap_or_default();
out.push_str(&format!(" {name:<width$} {about}\n"));
}
out.push('\n');
}
out
}
fn cli_command() -> clap::Command {
let cmd = Cli::command();
let groups = grouped_commands(&cmd);
let options = console::style("Options:").bold().underlined();
cmd.help_template(format!(
"{{about-with-newline}}\n{{usage-heading}} {{usage}}\n\n{groups}{options}\n{{options}}{{after-help}}"
))
.after_help(
"New here? Run `offline create` to start a project, or `offline doctor` to check your machine.\n\
`offline <command> --help` describes any command.",
)
}
fn main() {
reset_sigpipe();
let cli = Cli::from_arg_matches(&cli_command().get_matches()).unwrap_or_else(|err| err.exit());
if let Some(org) = cli.org.as_deref().filter(|o| !o.trim().is_empty()) {
std::env::set_var(config::storage::ENV_ORG_ID, org.trim());
}
let result = match cli.command {
Command::Login(args) => run_async(commands::login::login(args)),
Command::Logout(args) => run_async(commands::login::logout(args)),
Command::Whoami(args) => run_async(commands::login::whoami(args)),
Command::Setup(args) => run_async(commands::setup::run(args)),
Command::Orgs(cmd) => run_async(commands::orgs::run(cmd)),
Command::Apps(cmd) => run_async(commands::apps::run(cmd)),
Command::Apply(args) => run_async(commands::apply::run(args)),
Command::Keys(cmd) => run_async(commands::keys::run(cmd)),
Command::Create(args) => run_async(commands::create::run(args)),
Command::Init(args) => commands::init::run(args),
Command::Add(args) => commands::add::run(args),
Command::Plan(args) => commands::plan::run(args),
Command::Doctor(args) => run_async(commands::doctor::run(args)),
Command::Update(args) => commands::update::run(args),
Command::Registry(cmd) => commands::registry::run(cmd),
Command::Skills(cmd) => commands::skills::run(cmd),
Command::Mcp(cmd) => commands::mcp::run(cmd),
Command::Completions { shell } => {
let mut cmd = Cli::command();
clap_complete::generate(shell, &mut cmd, "offline", &mut std::io::stdout());
Ok(())
}
};
if let Err(err) = result {
if let Some(exit) = err.downcast_ref::<output::QuietExit>() {
std::process::exit(exit.0);
}
eprintln!("{} {err:#}", console::style("error:").red().bold());
std::process::exit(1);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn every_command_is_in_exactly_one_help_group() {
let cmd = Cli::command();
let grouped: Vec<&str> = COMMAND_GROUPS
.iter()
.flat_map(|(_, names)| names.iter().copied())
.collect();
for sub in cmd.get_subcommands().filter(|s| !s.is_hide_set()) {
let name = sub.get_name();
let count = grouped.iter().filter(|g| **g == name).count();
assert_eq!(count, 1, "`{name}` is in {count} help groups");
}
for name in &grouped {
assert!(cmd.find_subcommand(name).is_some(), "no command `{name}`");
}
}
#[test]
fn top_level_help_is_grouped_with_a_starting_point() {
let help = cli_command().render_help().to_string();
let start = help.find("Start here:").expect(&help);
assert!(help[start..].starts_with("Start here:\n create"), "{help}");
assert!(help.contains("New here? Run `offline create`"), "{help}");
assert!(!help.contains("\nCommands:"), "{help}");
cli_command().debug_assert();
}
}