Skip to main content

systemprompt_cli/
lib.rs

1mod args;
2mod bootstrap;
3pub mod cli_settings;
4mod commands;
5pub mod descriptor;
6pub mod environment;
7pub mod interactive;
8pub mod paths;
9mod presentation;
10mod routing;
11pub mod session;
12pub mod shared;
13
14pub use cli_settings::{CliConfig, ColorMode, OutputFormat, VerbosityLevel};
15pub use commands::{admin, analytics, build, cloud, core, infrastructure, plugins, web};
16
17use anyhow::{Context, Result, bail};
18use clap::Parser;
19use systemprompt_logging::set_startup_mode;
20use systemprompt_models::{ProfileBootstrap, SecretsBootstrap};
21use systemprompt_runtime::DatabaseContext;
22
23use crate::descriptor::{CommandDescriptor, DescribeCommand};
24
25enum RoutingAction {
26    ContinueLocal,
27    ExternalDbUrl(String),
28}
29
30fn has_local_export_flag(command: Option<&args::Commands>) -> bool {
31    let is_analytics = matches!(command, Some(args::Commands::Analytics(_)));
32    if !is_analytics {
33        return false;
34    }
35    std::env::args().any(|arg| arg == "--export" || arg.starts_with("--export="))
36}
37
38pub async fn run() -> Result<()> {
39    let cli = args::Cli::parse();
40
41    set_startup_mode(cli.command.is_none());
42
43    let cli_config = args::build_cli_config(&cli);
44    cli_settings::set_global_config(cli_config.clone());
45
46    if cli.display.no_color || !cli_config.should_use_color() {
47        console::set_colors_enabled(false);
48    }
49
50    if let Some(database_url) = cli.database.database_url.clone() {
51        return run_with_database_url(cli.command, &cli_config, &database_url).await;
52    }
53
54    let desc = cli
55        .command
56        .as_ref()
57        .map_or(CommandDescriptor::FULL, DescribeCommand::descriptor);
58
59    if !desc.database() {
60        let effective_level = resolve_log_level(&cli_config);
61        systemprompt_logging::init_console_logging_with_level(effective_level.as_deref());
62    }
63
64    if desc.profile() {
65        if let Some(external_db_url) = bootstrap_profile(&cli, &desc, &cli_config).await? {
66            return run_with_database_url(cli.command, &cli_config, &external_db_url).await;
67        }
68    }
69
70    dispatch_command(cli.command, &cli_config).await
71}
72
73async fn bootstrap_profile(
74    cli: &args::Cli,
75    desc: &CommandDescriptor,
76    cli_config: &CliConfig,
77) -> Result<Option<String>> {
78    let has_export = has_local_export_flag(cli.command.as_ref());
79    let ctx = bootstrap::resolve_and_display_profile(cli_config, has_export)?;
80
81    enforce_routing_policy(&ctx, cli, desc).await?;
82
83    match initialize_post_routing(&ctx, desc).await? {
84        RoutingAction::ExternalDbUrl(url) => Ok(Some(url)),
85        RoutingAction::ContinueLocal => Ok(None),
86    }
87}
88
89async fn enforce_routing_policy(
90    ctx: &bootstrap::ProfileContext,
91    cli: &args::Cli,
92    desc: &CommandDescriptor,
93) -> Result<()> {
94    if !ctx.env.is_fly && desc.remote_eligible() && !ctx.has_export {
95        let profile = ProfileBootstrap::get()?;
96        try_remote_routing(cli, profile).await?;
97        return Ok(());
98    }
99
100    if ctx.has_export && ctx.is_cloud && !ctx.external_db_access {
101        bail!(
102            "Export with cloud profile '{}' requires external database access.\nEnable \
103             external_db_access in the profile or use a local profile.",
104            ctx.profile_name
105        );
106    }
107
108    if ctx.is_cloud
109        && !ctx.env.is_fly
110        && !ctx.external_db_access
111        && !is_cloud_bypass_command(cli.command.as_ref())
112    {
113        bail!(
114            "Cloud profile '{}' selected but this command doesn't support remote execution.\nUse \
115             a local profile with --profile <name> or enable external database access.",
116            ctx.profile_name
117        );
118    }
119
120    Ok(())
121}
122
123const fn is_cloud_bypass_command(command: Option<&args::Commands>) -> bool {
124    matches!(
125        command,
126        Some(args::Commands::Cloud(_) | args::Commands::Admin(admin::AdminCommands::Session(_)))
127    )
128}
129
130async fn initialize_post_routing(
131    ctx: &bootstrap::ProfileContext,
132    desc: &CommandDescriptor,
133) -> Result<RoutingAction> {
134    if !ctx.is_cloud || ctx.external_db_access {
135        bootstrap::init_credentials_gracefully().await?;
136    }
137
138    if desc.secrets() {
139        bootstrap::init_secrets()?;
140    }
141
142    if ctx.is_cloud && ctx.external_db_access && desc.paths() && !ctx.env.is_fly {
143        let secrets = SecretsBootstrap::get()
144            .map_err(|e| anyhow::anyhow!("Secrets required for external DB access: {}", e))?;
145        let db_url = secrets.effective_database_url(true).to_string();
146        return Ok(RoutingAction::ExternalDbUrl(db_url));
147    }
148
149    if desc.paths() {
150        bootstrap::init_paths()?;
151        if !desc.skip_validation() {
152            bootstrap::run_validation()?;
153        }
154    }
155
156    if !ctx.is_cloud {
157        bootstrap::validate_cloud_credentials(&ctx.env);
158    }
159
160    Ok(RoutingAction::ContinueLocal)
161}
162
163async fn try_remote_routing(cli: &args::Cli, profile: &systemprompt_models::Profile) -> Result<()> {
164    let is_cloud = profile.target.is_cloud();
165
166    match routing::determine_execution_target() {
167        Ok(routing::ExecutionTarget::Remote {
168            hostname,
169            token,
170            context,
171        }) => {
172            let args = args::reconstruct_args(cli);
173            let exit_code =
174                routing::remote::execute_remote(&hostname, &token, context.as_str(), &args, 300)
175                    .await?;
176            if exit_code != 0 {
177                anyhow::bail!("Remote command exited with code {}", exit_code);
178            }
179            return Ok(());
180        },
181        Ok(routing::ExecutionTarget::Local) if is_cloud => {
182            require_external_db_access(profile, "no tenant is configured")?;
183        },
184        Err(e) if is_cloud => {
185            require_external_db_access(profile, &format!("routing failed: {}", e))?;
186        },
187        _ => {},
188    }
189
190    Ok(())
191}
192
193fn require_external_db_access(profile: &systemprompt_models::Profile, reason: &str) -> Result<()> {
194    if profile.database.external_db_access {
195        tracing::debug!(
196            profile_name = %profile.name,
197            reason = reason,
198            "Cloud profile allowing local execution via external_db_access"
199        );
200        Ok(())
201    } else {
202        bail!(
203            "Cloud profile '{}' requires remote execution but {}.\nRun 'systemprompt admin \
204             session login' to authenticate.",
205            profile.name,
206            reason
207        )
208    }
209}
210
211fn resolve_log_level(cli_config: &CliConfig) -> Option<String> {
212    if std::env::var("RUST_LOG").is_ok() {
213        return None;
214    }
215
216    if let Some(level) = cli_config.verbosity.as_tracing_filter() {
217        return Some(level.to_string());
218    }
219
220    if let Ok(profile_path) = bootstrap::resolve_profile(cli_config.profile_override.as_deref()) {
221        if let Some(log_level) = bootstrap::try_load_log_level(&profile_path) {
222            return Some(log_level.as_tracing_filter().to_string());
223        }
224    }
225
226    None
227}
228
229async fn dispatch_command(command: Option<args::Commands>, config: &CliConfig) -> Result<()> {
230    match command {
231        Some(args::Commands::Core(cmd)) => core::execute(cmd, config).await?,
232        Some(args::Commands::Infra(cmd)) => infrastructure::execute(cmd, config).await?,
233        Some(args::Commands::Admin(cmd)) => admin::execute(cmd, config).await?,
234        Some(args::Commands::Cloud(cmd)) => cloud::execute(cmd, config).await?,
235        Some(args::Commands::Analytics(cmd)) => analytics::execute(cmd, config).await?,
236        Some(args::Commands::Web(cmd)) => web::execute(cmd)?,
237        Some(args::Commands::Plugins(cmd)) => plugins::execute(cmd, config).await?,
238        Some(args::Commands::Build(cmd)) => {
239            build::execute(cmd, config)?;
240        },
241        None => {
242            args::Cli::parse_from(["systemprompt", "--help"]);
243        },
244    }
245
246    Ok(())
247}
248
249async fn run_with_database_url(
250    command: Option<args::Commands>,
251    config: &CliConfig,
252    database_url: &str,
253) -> Result<()> {
254    let db_ctx = DatabaseContext::from_url(database_url)
255        .await
256        .context("Failed to connect to database")?;
257
258    systemprompt_logging::init_logging(db_ctx.db_pool_arc());
259
260    match command {
261        Some(args::Commands::Core(cmd)) => core::execute_with_db(cmd, &db_ctx, config).await,
262        Some(args::Commands::Infra(cmd)) => {
263            infrastructure::execute_with_db(cmd, &db_ctx, config).await
264        },
265        Some(args::Commands::Admin(cmd)) => admin::execute_with_db(cmd, &db_ctx, config).await,
266        Some(args::Commands::Analytics(cmd)) => {
267            analytics::execute_with_db(cmd, &db_ctx, config).await
268        },
269        Some(args::Commands::Cloud(cloud::CloudCommands::Db(cmd))) => {
270            cloud::db::execute_with_database_url(cmd, database_url, config).await
271        },
272        Some(_) => {
273            bail!("This command requires full profile initialization. Remove --database-url flag.")
274        },
275        None => bail!("No subcommand provided. Use --help to see available commands."),
276    }
277}