systemprompt-cli 0.1.19

systemprompt.io OS - CLI for agent orchestration, AI operations, and system management
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
use anyhow::{Context, Result, bail};
use dialoguer::Input;
use dialoguer::theme::ColorfulTheme;
use systemprompt_cloud::{
    CloudApiClient, CloudPath, ProfilePath, ProjectContext, StoredTenant, TenantStore, TenantType,
    get_cloud_paths,
};
use systemprompt_logging::CliService;
use systemprompt_models::Profile;

use systemprompt_identifiers::TenantId;

use crate::commands::cloud::tenant::get_credentials;

use super::api_keys::{ApiKeys, collect_api_keys};
use super::builders::{CloudProfileBuilder, LocalProfileBuilder};
use super::create_setup::{get_cloud_user, handle_local_tenant_setup};
use super::create_tenant::{get_tenants_by_type, select_tenant, select_tenant_type};
use super::templates::{
    DatabaseUrls, get_services_path, save_dockerfile, save_dockerignore, save_entrypoint,
    save_profile, save_secrets, update_ai_config_default_provider,
};
use super::{CreateArgs, TenantTypeArg};
use crate::cli_settings::CliConfig;

pub async fn execute(args: &CreateArgs, config: &CliConfig) -> Result<()> {
    let name = &args.name;
    CliService::section(&format!("Create Profile: {}", name));

    let cloud_user = get_cloud_user()?;
    let ctx = ProjectContext::discover();
    let profile_dir = ctx.profile_dir(name);

    if profile_dir.exists() {
        bail!(
            "Profile '{}' already exists at {}\nUse 'systemprompt cloud profile delete {}' first.",
            name,
            profile_dir.display(),
            name
        );
    }

    std::fs::create_dir_all(ctx.profiles_dir())
        .with_context(|| format!("Failed to create {}", ctx.profiles_dir().display()))?;

    let cloud_paths = get_cloud_paths();
    let tenants_path = cloud_paths.resolve(CloudPath::Tenants);
    let store = TenantStore::load_from_path(&tenants_path).unwrap_or_else(|e| {
        CliService::warning(&format!("Failed to load tenant store: {}", e));
        TenantStore::default()
    });

    let (tenant, api_keys) = if config.is_interactive() && args.tenant_id.is_none() {
        let tenant_type = select_tenant_type(&store)?;
        let eligible_tenants = get_tenants_by_type(&store, tenant_type);
        let tenant = select_tenant(&eligible_tenants)?;

        if !tenant.has_database_url() {
            bail!(
                "Tenant '{}' does not have a database URL configured.\nFor local tenants, \
                 recreate with 'systemprompt cloud tenant create'.",
                tenant.name
            );
        }

        CliService::section("API Keys");
        let api_keys = collect_api_keys()?;
        (tenant, api_keys)
    } else {
        let tenant = resolve_tenant_from_args(args, &store)?;

        if !tenant.has_database_url() {
            bail!(
                "Tenant '{}' does not have a database URL configured.\nFor local tenants, \
                 recreate with 'systemprompt cloud tenant create'.",
                tenant.name
            );
        }

        let api_keys = ApiKeys::from_options(
            args.gemini_key.clone(),
            args.anthropic_key.clone(),
            args.openai_key.clone(),
        )?;
        (tenant, api_keys)
    };

    let tenant = ensure_unmasked_credentials(tenant, &tenants_path).await?;

    std::fs::create_dir_all(&profile_dir)
        .with_context(|| format!("Failed to create directory {}", profile_dir.display()))?;

    std::fs::create_dir_all(ctx.storage_dir()).with_context(|| {
        format!(
            "Failed to create storage directory {}",
            ctx.storage_dir().display()
        )
    })?;

    let secrets_path = ProfilePath::Secrets.resolve(&profile_dir);
    let external_url = tenant
        .get_local_database_url()
        .ok_or_else(|| anyhow::anyhow!("Tenant database URL is required"))?;
    let db_urls = DatabaseUrls {
        external: external_url,
        internal: tenant.internal_database_url.as_deref(),
    };
    save_secrets(
        &db_urls,
        &api_keys,
        tenant.sync_token.as_deref(),
        &secrets_path,
        tenant.tenant_type == TenantType::Cloud,
    )?;
    CliService::success(&format!("Created: {}", secrets_path.display()));

    update_ai_config_default_provider(api_keys.selected_provider())?;

    let services_path = get_services_path()?;
    let profile_path = ProfilePath::Config.resolve(&profile_dir);
    let relative_secrets_path = "./secrets.json";

    let built_profile = match tenant.tenant_type {
        TenantType::Local => LocalProfileBuilder::new(name, relative_secrets_path, &services_path)
            .with_tenant_id(TenantId::new(&tenant.id))
            .build(),
        TenantType::Cloud => {
            let mut builder = CloudProfileBuilder::new(name)
                .with_tenant_id(TenantId::new(&tenant.id))
                .with_external_db_access(tenant.external_db_access)
                .with_secrets_path(relative_secrets_path);
            if let Some(hostname) = &tenant.hostname {
                builder = builder.with_external_url(format!("https://{}", hostname));
            }
            builder.build()
        },
    };

    save_profile(&built_profile, &profile_path)?;
    CliService::success(&format!("Created: {}", profile_path.display()));

    let docker_dir = ctx.profile_docker_dir(name);
    std::fs::create_dir_all(&docker_dir)
        .with_context(|| format!("Failed to create docker directory {}", docker_dir.display()))?;

    let dockerfile_path = ctx.profile_dockerfile(name);
    save_dockerfile(&dockerfile_path, name, ctx.root())?;
    CliService::success(&format!("Created: {}", dockerfile_path.display()));

    let entrypoint_path = ctx.profile_entrypoint(name);
    save_entrypoint(&entrypoint_path)?;
    CliService::success(&format!("Created: {}", entrypoint_path.display()));

    let dockerignore_path = ctx.profile_dockerignore(name);
    save_dockerignore(&dockerignore_path)?;
    CliService::success(&format!("Created: {}", dockerignore_path.display()));

    match built_profile.validate() {
        Ok(()) => CliService::success("Profile validated"),
        Err(e) => CliService::warning(&format!("Validation warning: {}", e)),
    }

    if tenant.tenant_type == TenantType::Local {
        let db_url = tenant
            .get_local_database_url()
            .ok_or_else(|| anyhow::anyhow!("Tenant database URL is required"))?;
        handle_local_tenant_setup(&cloud_user, db_url, &tenant.name, &profile_path).await?;
    }

    CliService::section("Next Steps");
    CliService::info(&format!(
        "  export SYSTEMPROMPT_PROFILE={}",
        profile_path.display()
    ));

    match tenant.tenant_type {
        TenantType::Local => CliService::info("  just start"),
        TenantType::Cloud => CliService::info("  just deploy"),
    }

    Ok(())
}

#[derive(Debug)]
pub struct CreatedProfile {
    pub name: String,
}

pub fn create_profile_for_tenant(
    tenant: &StoredTenant,
    api_keys: &ApiKeys,
    profile_name: &str,
) -> Result<CreatedProfile> {
    let ctx = ProjectContext::discover();
    let mut name = profile_name.to_string();

    loop {
        let profile_dir = ctx.profile_dir(&name);
        if !profile_dir.exists() {
            break;
        }

        CliService::warning(&format!(
            "Profile '{}' already exists at {}",
            name,
            profile_dir.display()
        ));

        name = Input::with_theme(&ColorfulTheme::default())
            .with_prompt("Enter a different profile name")
            .interact_text()?;
    }

    let profile_dir = ctx.profile_dir(&name);

    std::fs::create_dir_all(ctx.profiles_dir())
        .with_context(|| format!("Failed to create {}", ctx.profiles_dir().display()))?;

    std::fs::create_dir_all(&profile_dir)
        .with_context(|| format!("Failed to create directory {}", profile_dir.display()))?;

    std::fs::create_dir_all(ctx.storage_dir()).with_context(|| {
        format!(
            "Failed to create storage directory {}",
            ctx.storage_dir().display()
        )
    })?;

    let secrets_path = ProfilePath::Secrets.resolve(&profile_dir);
    let local_db_url = tenant
        .get_local_database_url()
        .ok_or_else(|| anyhow::anyhow!("Tenant database URL is required"))?;
    let db_urls = DatabaseUrls {
        external: local_db_url,
        internal: tenant.internal_database_url.as_deref(),
    };
    save_secrets(
        &db_urls,
        api_keys,
        tenant.sync_token.as_deref(),
        &secrets_path,
        tenant.tenant_type == TenantType::Cloud,
    )?;
    CliService::success(&format!("Created: {}", secrets_path.display()));

    update_ai_config_default_provider(api_keys.selected_provider())?;

    let profile_path = ProfilePath::Config.resolve(&profile_dir);

    let built_profile = match tenant.tenant_type {
        TenantType::Local => {
            let services_path = get_services_path()?;
            LocalProfileBuilder::new(&name, "./secrets.json", &services_path)
                .with_tenant_id(TenantId::new(&tenant.id))
                .build()
        },
        TenantType::Cloud => {
            let mut builder = CloudProfileBuilder::new(&name)
                .with_tenant_id(TenantId::new(&tenant.id))
                .with_external_db_access(tenant.external_db_access)
                .with_secrets_path("./secrets.json");
            if let Some(hostname) = &tenant.hostname {
                builder = builder.with_external_url(format!("https://{}", hostname));
            }
            builder.build()
        },
    };

    save_profile(&built_profile, &profile_path)?;
    CliService::success(&format!("Created: {}", profile_path.display()));

    let docker_dir = ctx.profile_docker_dir(&name);
    std::fs::create_dir_all(&docker_dir)
        .with_context(|| format!("Failed to create docker directory {}", docker_dir.display()))?;

    let dockerfile_path = ctx.profile_dockerfile(&name);
    save_dockerfile(&dockerfile_path, &name, ctx.root())?;
    CliService::success(&format!("Created: {}", dockerfile_path.display()));

    let entrypoint_path = ctx.profile_entrypoint(&name);
    save_entrypoint(&entrypoint_path)?;
    CliService::success(&format!("Created: {}", entrypoint_path.display()));

    let dockerignore_path = ctx.profile_dockerignore(&name);
    save_dockerignore(&dockerignore_path)?;
    CliService::success(&format!("Created: {}", dockerignore_path.display()));

    match built_profile.validate() {
        Ok(()) => CliService::success("Profile validated"),
        Err(e) => CliService::warning(&format!("Validation warning: {}", e)),
    }

    Ok(CreatedProfile { name })
}

fn resolve_tenant_from_args(args: &CreateArgs, store: &TenantStore) -> Result<StoredTenant> {
    let tenant_id = args.tenant_id.as_ref().ok_or_else(|| {
        anyhow::anyhow!(
            "Missing required flag: --tenant-id\nIn non-interactive mode, --tenant-id is \
             required.\nList tenants with: systemprompt cloud tenant list"
        )
    })?;

    let tenant = store.find_tenant(tenant_id).ok_or_else(|| {
        anyhow::anyhow!(
            "Tenant '{}' not found.\nList available tenants with: systemprompt cloud tenant list",
            tenant_id
        )
    })?;

    let expected_type: TenantType = match args.tenant_type {
        TenantTypeArg::Local => TenantType::Local,
        TenantTypeArg::Cloud => TenantType::Cloud,
    };

    if tenant.tenant_type != expected_type {
        bail!(
            "Tenant '{}' is type {:?}, but --tenant-type {:?} was specified",
            tenant_id,
            tenant.tenant_type,
            args.tenant_type
        );
    }

    Ok(tenant.clone())
}

struct RefreshedCredentials {
    external_database_url: String,
    internal_database_url: String,
    sync_token: Option<String>,
}

async fn refresh_tenant_credentials(
    client: &CloudApiClient,
    tenant_id: &str,
) -> Result<RefreshedCredentials> {
    let status = client.get_tenant_status(tenant_id).await?;
    let secrets_url = status
        .secrets_url
        .ok_or_else(|| anyhow::anyhow!("No secrets URL available for tenant"))?;
    let secrets = client.fetch_secrets(&secrets_url).await?;
    Ok(RefreshedCredentials {
        external_database_url: secrets.database_url,
        internal_database_url: secrets.internal_database_url,
        sync_token: secrets.sync_token,
    })
}

async fn ensure_unmasked_credentials(
    tenant: StoredTenant,
    tenants_path: &std::path::Path,
) -> Result<StoredTenant> {
    if tenant.tenant_type != TenantType::Cloud {
        return Ok(tenant);
    }

    let external_url = tenant.database_url.as_deref();
    let internal_url = tenant.internal_database_url.as_deref();

    let needs_external = tenant.external_db_access && external_url.is_none();
    let needs_refresh = needs_external
        || external_url.is_some_and(Profile::is_masked_database_url)
        || internal_url.is_none_or(Profile::is_masked_database_url);

    if !needs_refresh {
        return Ok(tenant);
    }

    CliService::info("Fetching database credentials...");
    let creds = get_credentials()?;
    let client = CloudApiClient::new(&creds.api_url, &creds.api_token)?;

    match refresh_tenant_credentials(&client, &tenant.id).await {
        Ok(creds) => {
            let mut updated_tenant = tenant.clone();
            updated_tenant.internal_database_url = Some(creds.internal_database_url);
            if updated_tenant.external_db_access {
                updated_tenant.database_url = Some(creds.external_database_url);
            }
            if let Some(token) = creds.sync_token {
                updated_tenant.sync_token = Some(token);
            }

            let mut store = TenantStore::load_from_path(tenants_path)
                .unwrap_or_else(|_| TenantStore::default());
            if let Some(t) = store.tenants.iter_mut().find(|t| t.id == tenant.id) {
                *t = updated_tenant.clone();
                store.save_to_path(tenants_path)?;
            }

            CliService::success("Database credentials retrieved");
            Ok(updated_tenant)
        },
        Err(e) => {
            CliService::warning(&format!("Could not fetch credentials: {}", e));
            CliService::warning(
                "Run 'systemprompt cloud tenant rotate-credentials' to fetch real credentials.",
            );
            Ok(tenant)
        },
    }
}