offline-cli 0.4.0

The Offline Protocol developer CLI
//! Offline Protocol developer CLI.

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 {
    /// Organization to use for this command (id or name), overriding the default from `offline org use`
    #[arg(long, global = true, value_name = "ORG")]
    org: Option<String>,
    #[command(subcommand)]
    command: Command,
}

#[derive(Subcommand)]
enum Command {
    /// Authenticate with the Offline Protocol developer portal
    Login(commands::login::LoginArgs),
    /// Revoke the stored API key and clear local credentials
    Logout(commands::login::LogoutArgs),
    /// Show what this machine is signed in as (exits 1 when signed out)
    Whoami(commands::login::WhoamiArgs),
    /// Provision org, application, and default API key (needs a developer session)
    ///
    /// Needs the developer session `offline login` stores. An app key from
    /// `offline login --api-key` (CI) can't run it. Reuses the API key this
    /// machine already created for the application.
    Setup(commands::setup::SetupArgs),
    /// Manage organizations: list, create, and `use` one as the default (needs a developer session)
    ///
    /// Needs the developer session `offline login` stores. An app key from
    /// `offline login --api-key` (CI) can't run it.
    #[command(subcommand, alias = "org")]
    Orgs(commands::orgs::OrgsCommand),
    /// Manage applications: native apps, origins, features, status (needs a developer session)
    ///
    /// Needs the developer session `offline login` stores (or
    /// OFFLINE_ACCESS_TOKEN). An app key from `offline login --api-key` (CI)
    /// can't run it.
    #[command(subcommand)]
    Apps(commands::apps::AppsCommand),
    /// Converge the application to the "app" block of offline.config.json (native apps, origins, features)
    ///
    /// Additive and idempotent: registers what is missing and never removes a
    /// registration. With --detect it also registers the native apps the
    /// project ships (app.json, Xcode, Gradle, assetlinks.json).
    Apply(commands::apply::ApplyArgs),
    /// Manage application API keys (needs a developer session)
    ///
    /// Needs the developer session `offline login` stores. An app key from
    /// `offline login --api-key` (CI) can't run it.
    #[command(subcommand)]
    Keys(commands::keys::KeysCommand),
    /// Create a new project from a workflow, template, or natural-language prompt
    Create(commands::create::CreateArgs),
    /// Wire Offline Protocol config + agent guidance into an existing project (JS/TS, Python, Swift, Kotlin/Java)
    Init(commands::init::InitArgs),
    /// Add an Offline Protocol package to an existing project
    Add(commands::add::AddArgs),
    /// Plan an app from a prompt: workflow, packages, architecture documents
    Plan(commands::plan::PlanArgs),
    /// Check your environment for everything Offline Protocol development needs
    Doctor(commands::doctor::DoctorArgs),
    /// Check for a newer release of this CLI
    Update(commands::update::UpdateArgs),
    /// Query the ecosystem registry (packages, workflows, skills, templates)
    #[command(subcommand)]
    Registry(commands::registry::RegistryCommand),
    /// Read integration skills (deep guides with accurate SDK usage)
    #[command(subcommand)]
    Skills(commands::skills::SkillsCommand),
    /// Model Context Protocol server for AI agents
    #[command(subcommand)]
    Mcp(commands::mcp::McpCommand),
    /// Generate shell completions
    Completions {
        /// Shell to generate completions for
        #[arg(value_enum)]
        shell: clap_complete::Shell,
    },
}

/// Restore SIG_DFL for SIGPIPE so piping to `head` does not panic.
#[cfg(unix)]
fn reset_sigpipe() {
    // SAFETY: setting a signal disposition to SIG_DFL is async-signal-safe
    // and has no preconditions.
    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)
}

/// The top-level commands by what a developer is doing, in the order they
/// usually need them. Every visible command appears in exactly one group (a
/// test checks this), and each line's description is the command's own.
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"]),
];

/// The command list for top-level help, grouped by [`COMMAND_GROUPS`].
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
}

/// The CLI with its grouped top-level help and a starting point at the end.
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());
    // `--org` overrides the stored default for this command, like OFFLINE_ORG_ID.
    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 {
        // A command that has already said why it failed (`whoami` signed
        // out) only sets the exit status.
        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();
    }
}