Skip to main content

systemprompt_cli/runner/
mod.rs

1//! CLI runtime entry point and bootstrap helpers.
2//!
3//! Owns argument parsing (`args`), profile/secrets bootstrap (`bootstrap`),
4//! and cloud routing ([`routing`], [`profile_routing`]). [`run`] is the
5//! process entry point.
6//!
7//! Copyright (c) systemprompt.io — Business Source License 1.1.
8//! See <https://systemprompt.io> for licensing details.
9
10pub mod args;
11mod bootstrap;
12mod db_url;
13pub mod profile_routing;
14pub mod routing;
15mod structured_output;
16
17use anyhow::{Context, Result, bail};
18use clap::Parser;
19use systemprompt_logging::set_startup_mode;
20use systemprompt_runtime::DatabaseContext;
21
22use crate::cli_settings::{CliConfig, OutputFormat};
23use crate::commands::{admin, analytics, cloud, core, infrastructure, plugins, web};
24use crate::context::CommandContext;
25use crate::descriptor::{CommandDescriptor, DescribeCommand};
26use crate::env_overrides::EnvOverrides;
27
28pub async fn run() -> Result<()> {
29    let outcome = Box::pin(run_inner()).await;
30    structured_output::finalize(&outcome);
31    outcome
32}
33
34async fn run_inner() -> Result<()> {
35    let cli = args::Cli::parse();
36
37    set_startup_mode(cli.command.is_none());
38
39    let env = EnvOverrides::from_process_env();
40    let cli_config = args::build_cli_config(&cli, &env);
41    systemprompt_logging::set_structured_output(cli_config.output_format() != OutputFormat::Table);
42
43    if cli.display.no_color || !cli_config.should_use_color() {
44        console::set_colors_enabled(false);
45    }
46
47    if let Some(database_url) = cli.database.database_url.clone() {
48        match cli.command.as_ref().map(args::Commands::db_url_routing) {
49            Some(db_url::DbUrlRouting::Direct) => {
50                return Box::pin(run_with_database_url(
51                    cli.command,
52                    cli_config,
53                    env,
54                    &database_url,
55                ))
56                .await;
57            },
58            Some(db_url::DbUrlRouting::Unsupported) => bail!(
59                "This command cannot run with --database-url; it requires full profile \
60                 initialization. Remove --database-url."
61            ),
62            Some(db_url::DbUrlRouting::ProfileDriven) | None => {},
63        }
64    }
65
66    let desc = cli
67        .command
68        .as_ref()
69        .map_or(CommandDescriptor::FULL, DescribeCommand::descriptor);
70
71    if !desc.database() {
72        let effective_level = resolve_log_level(&cli_config, &env);
73        systemprompt_logging::init_console_logging_with_level(effective_level.as_deref());
74    }
75
76    if desc.profile() {
77        match profile_routing::bootstrap_profile(&cli, &desc, &cli_config, &env).await? {
78            profile_routing::BootstrapOutcome::RemoteExecuted => return Ok(()),
79            profile_routing::BootstrapOutcome::ExternalDbUrl(external_db_url) => {
80                return Box::pin(run_with_database_url(
81                    cli.command,
82                    cli_config,
83                    env,
84                    &external_db_url,
85                ))
86                .await;
87            },
88            profile_routing::BootstrapOutcome::ContinueLocal => {},
89        }
90    }
91
92    let ctx = CommandContext::new(cli_config, env);
93    Box::pin(dispatch_command(cli.command, &ctx)).await
94}
95
96fn resolve_log_level(cli_config: &CliConfig, env: &EnvOverrides) -> Option<String> {
97    if env.rust_log.is_some() {
98        return None;
99    }
100
101    if let Some(level) = cli_config.verbosity.as_tracing_filter() {
102        return Some(level.to_owned());
103    }
104
105    if let Ok(resolved) = bootstrap::resolve_profile(cli_config.profile_override.as_deref(), env)
106        && let Some(log_level) = bootstrap::try_load_log_level(&resolved.path)
107    {
108        return Some(log_level.as_tracing_filter().to_owned());
109    }
110
111    Some("warn".to_owned())
112}
113
114async fn dispatch_command(command: Option<args::Commands>, ctx: &CommandContext) -> Result<()> {
115    if ctx.is_database_scoped() {
116        match &command {
117            Some(
118                args::Commands::Core(_)
119                | args::Commands::Infra(_)
120                | args::Commands::Admin(_)
121                | args::Commands::Analytics(_),
122            ) => {},
123            Some(_) => bail!(
124                "This command requires full profile initialization. Remove --database-url flag."
125            ),
126            None => bail!("No subcommand provided. Use --help to see available commands."),
127        }
128    }
129
130    match command {
131        Some(args::Commands::Core(cmd)) => core::execute(cmd, ctx).await?,
132        Some(args::Commands::Infra(cmd)) => infrastructure::execute(cmd, ctx).await?,
133        Some(args::Commands::Admin(cmd)) => Box::pin(admin::execute(cmd, ctx)).await?,
134        Some(args::Commands::Cloud(cmd)) => cloud::execute(cmd, ctx).await?,
135        Some(args::Commands::Analytics(cmd)) => analytics::execute(cmd, ctx).await?,
136        Some(args::Commands::Web(cmd)) => web::execute(cmd, ctx)?,
137        Some(args::Commands::Plugins(cmd)) => Box::pin(plugins::execute(cmd, ctx)).await?,
138        Some(args::Commands::Build(cmd)) => {
139            crate::commands::build::execute(cmd, ctx)?;
140        },
141        None => {
142            args::Cli::parse_from(["systemprompt", "--help"]);
143        },
144    }
145
146    Ok(())
147}
148
149async fn run_with_database_url(
150    command: Option<args::Commands>,
151    cli_config: CliConfig,
152    env: EnvOverrides,
153    database_url: &str,
154) -> Result<()> {
155    let db_ctx = DatabaseContext::from_url(database_url)
156        .await
157        .context("Failed to connect to database")?;
158
159    systemprompt_logging::init_logging(db_ctx.db_pool_arc());
160
161    let ctx = CommandContext::with_database(cli_config, env, db_ctx, database_url.to_owned());
162    Box::pin(dispatch_command(command, &ctx)).await
163}