sylphx-cli 0.1.1

Sylphx Platform CLI — dogfoods the Rust Management SDK
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
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
//! Sylphx Platform CLI — thin façade over `sylphx-sdk-management`.
//!
//! Sole Rust operator surface for the Management plane (ADR-3820). No TypeScript
//! fallback. No stub command modules.
//!
//! ## Shipped product commands
//!
//! Typed: `health`, `whoami`, `orgs list`, `projects list|get`,
//! `environments list|get`, `deployments list`, `version-info`.
//! Escape hatch: `api <METHOD> <path>` — full Management REST drop-in through
//! the same authenticated transport as the typed SDK.

use std::path::PathBuf;
use std::process::ExitCode;
use std::time::Duration;

use clap::{Parser, Subcommand, ValueEnum};
use reqwest::Method;
use serde_json::{json, Value};
use sylphx_sdk_core::{RetryConfig, DEFAULT_MANAGEMENT_BASE_URL};
use sylphx_sdk_management::{ListOptions, ManagementClient};

#[derive(Parser, Debug)]
#[command(
    name = "sylphx",
    about = "Sylphx Platform CLI (Rust) — dogfoods sylphx-sdk-management",
    version
)]
struct Cli {
    /// Management API base URL (include /v1).
    #[arg(long, env = "SYLPHX_API_URL", global = true)]
    api_url: Option<String>,

    /// Management token (OAuth JWT or svc_*).
    #[arg(long, env = "SYLPHX_TOKEN", global = true)]
    token: Option<String>,

    /// Emit machine-readable JSON on stdout.
    #[arg(long, global = true, default_value_t = false)]
    json: bool,

    #[command(subcommand)]
    command: Commands,
}

#[derive(Subcommand, Debug)]
enum Commands {
    /// Process health (Management plane).
    Health,
    /// Authenticated principal.
    Whoami,
    /// Organization operations (from WhoAmI).
    Orgs {
        #[command(subcommand)]
        command: OrgCommands,
    },
    /// Project operations.
    Projects {
        #[command(subcommand)]
        command: ProjectCommands,
    },
    /// Environment operations under a project.
    Environments {
        #[command(subcommand)]
        command: EnvironmentCommands,
    },
    /// Deployment operations under a project.
    Deployments {
        #[command(subcommand)]
        command: DeploymentCommands,
    },
    /// Authenticated raw Management REST (escape hatch; full REST drop-in).
    Api {
        /// HTTP method.
        method: ApiMethod,
        /// Path relative to Management base (e.g. /projects).
        path: String,
        /// Optional JSON body (inline string). Mutually exclusive with --input.
        #[arg(long)]
        body: Option<String>,
        /// Read JSON body from file (`-` = stdin).
        #[arg(long)]
        input: Option<PathBuf>,
        /// Optional org scope header.
        #[arg(long)]
        org_id: Option<String>,
    },
    /// Print contract / SDK identity for audit.
    VersionInfo,
}

#[derive(Subcommand, Debug)]
enum OrgCommands {
    /// List organizations for the authenticated principal.
    List,
}

#[derive(Subcommand, Debug)]
enum ProjectCommands {
    /// List projects.
    List {
        /// Optional org scope header.
        #[arg(long)]
        org_id: Option<String>,
    },
    /// Get a project by id.
    Get {
        /// Project id.
        id: String,
        #[arg(long)]
        org_id: Option<String>,
    },
}

#[derive(Subcommand, Debug)]
enum EnvironmentCommands {
    /// List environments for a project.
    List {
        /// Project id.
        project_id: String,
        #[arg(long)]
        org_id: Option<String>,
        /// Opaque page token.
        #[arg(long)]
        page_token: Option<String>,
        /// Page size hint.
        #[arg(long)]
        page_size: Option<u32>,
    },
    /// Get one environment by id or slug.
    Get {
        /// Project id.
        project_id: String,
        /// Environment id or slug.
        environment_id: String,
        #[arg(long)]
        org_id: Option<String>,
    },
}

#[derive(Subcommand, Debug)]
enum DeploymentCommands {
    /// List deployments for a project.
    List {
        /// Project id.
        project_id: String,
        #[arg(long)]
        org_id: Option<String>,
        #[arg(long)]
        page_token: Option<String>,
        #[arg(long)]
        page_size: Option<u32>,
    },
}

#[derive(Clone, Debug, ValueEnum)]
enum ApiMethod {
    Get,
    Head,
    Post,
    Put,
    Patch,
    Delete,
}

impl ApiMethod {
    fn to_reqwest(self) -> Method {
        match self {
            Self::Get => Method::GET,
            Self::Head => Method::HEAD,
            Self::Post => Method::POST,
            Self::Put => Method::PUT,
            Self::Patch => Method::PATCH,
            Self::Delete => Method::DELETE,
        }
    }
}

fn page_opts(page_token: Option<String>, page_size: Option<u32>) -> Option<ListOptions> {
    if page_token.is_none() && page_size.is_none() {
        return None;
    }
    Some(ListOptions {
        page_token,
        page_size,
    })
}

#[tokio::main]
async fn main() -> ExitCode {
    match run().await {
        Ok(()) => ExitCode::SUCCESS,
        Err(err) => {
            eprintln!("error: {err}");
            ExitCode::from(1)
        }
    }
}

async fn run() -> anyhow::Result<()> {
    let cli = Cli::parse();
    match &cli.command {
        Commands::VersionInfo => {
            let body = json!({
                "cli": env!("CARGO_PKG_VERSION"),
                "contractPackage": sylphx_wire::CONTRACT_PACKAGE,
                "contractRevision": sylphx_wire::CONTRACT_REVISION,
                "client": "sylphx-sdk-management",
                "product": "rust",
                "shippedCommands": [
                    "health",
                    "whoami",
                    "orgs list",
                    "projects list",
                    "projects get",
                    "environments list",
                    "environments get",
                    "deployments list",
                    "api",
                    "version-info"
                ],
            });
            print_out(&cli, &body, || {
                println!(
                    "sylphx {} (Rust)  contract {}@{}  via sylphx-sdk-management",
                    env!("CARGO_PKG_VERSION"),
                    sylphx_wire::CONTRACT_PACKAGE,
                    sylphx_wire::CONTRACT_REVISION
                );
            });
            return Ok(());
        }
        _ => {}
    }

    let token = cli
        .token
        .clone()
        .filter(|t| !t.trim().is_empty())
        .ok_or_else(|| anyhow::anyhow!("SYLPHX_TOKEN or --token is required"))?;
    let base = cli
        .api_url
        .clone()
        .unwrap_or_else(|| DEFAULT_MANAGEMENT_BASE_URL.to_string());

    let client = ManagementClient::builder(token)
        .base_url(base)
        .retry(RetryConfig {
            max_attempts: 3,
            base_delay: Duration::from_millis(100),
        })
        .build()?;

    match cli.command {
        Commands::Health => {
            let h = client.health().await?;
            print_out(&cli, &h, || {
                println!(
                    "status={} version={} git_sha={}",
                    h.status,
                    h.version.as_deref().unwrap_or("-"),
                    h.git_sha.as_deref().unwrap_or("-")
                );
            });
        }
        Commands::Whoami => {
            let w = client.whoami().await?;
            print_out(&cli, &w, || {
                let user = w.user.as_ref();
                println!(
                    "user_id={} email={} name={} orgs={}",
                    user.map(|u| u.id.as_str()).unwrap_or("-"),
                    user.map(|u| u.email.as_str()).unwrap_or("-"),
                    user.and_then(|u| u.name.as_deref()).unwrap_or("-"),
                    w.orgs.len()
                );
            });
        }
        Commands::Orgs {
            command: OrgCommands::List,
        } => {
            let orgs = client.list_orgs().await?;
            if cli.json {
                println!("{}", serde_json::to_string_pretty(&orgs)?);
            } else {
                for o in &orgs {
                    println!("{}\t{}\t{}", o.id, o.slug, o.name);
                }
                if orgs.is_empty() {
                    println!("(no orgs)");
                }
            }
        }
        Commands::Projects {
            command: ProjectCommands::List { org_id },
        } => {
            let list = client.list_projects(org_id.as_deref(), None).await?;
            if cli.json {
                println!("{}", serde_json::to_string_pretty(&list)?);
            } else {
                for p in &list.data {
                    println!("{}\t{}\t{}", p.id, p.slug, p.name);
                }
                if list.data.is_empty() {
                    println!("(no projects)");
                }
            }
        }
        Commands::Projects {
            command: ProjectCommands::Get { id, org_id },
        } => {
            let p = client.get_project(&id, org_id.as_deref()).await?;
            if cli.json {
                println!("{}", serde_json::to_string_pretty(&p)?);
            } else {
                println!(
                    "id={} slug={} name={} org_id={} active={}",
                    p.id, p.slug, p.name, p.org_id, p.is_active
                );
            }
        }
        Commands::Environments {
            command:
                EnvironmentCommands::List {
                    project_id,
                    org_id,
                    page_token,
                    page_size,
                },
        } => {
            let page = page_opts(page_token, page_size);
            let list = client
                .list_environments(&project_id, page.as_ref(), org_id.as_deref())
                .await?;
            if cli.json {
                println!("{}", serde_json::to_string_pretty(&list)?);
            } else {
                for e in &list.data {
                    println!(
                        "{}\t{}\t{}\t{}",
                        e.id,
                        e.slug,
                        e.name,
                        e.status.as_deref().unwrap_or("-")
                    );
                }
                if list.data.is_empty() {
                    println!("(no environments)");
                }
            }
        }
        Commands::Environments {
            command:
                EnvironmentCommands::Get {
                    project_id,
                    environment_id,
                    org_id,
                },
        } => {
            let e = client
                .get_environment(&project_id, &environment_id, org_id.as_deref())
                .await?;
            if cli.json {
                println!("{}", serde_json::to_string_pretty(&e)?);
            } else {
                println!(
                    "id={} slug={} name={} project_id={} status={}",
                    e.id,
                    e.slug,
                    e.name,
                    e.project_id,
                    e.status.as_deref().unwrap_or("-")
                );
            }
        }
        Commands::Deployments {
            command:
                DeploymentCommands::List {
                    project_id,
                    org_id,
                    page_token,
                    page_size,
                },
        } => {
            let page = page_opts(page_token, page_size);
            let list = client
                .list_deployments(&project_id, page.as_ref(), org_id.as_deref())
                .await?;
            if cli.json {
                println!("{}", serde_json::to_string_pretty(&list)?);
            } else {
                for d in &list.data {
                    println!(
                        "{}\t{}\t{}\t{}",
                        d.id,
                        d.status,
                        d.environment_id.as_deref().unwrap_or("-"),
                        d.git_sha.as_deref().unwrap_or("-")
                    );
                }
                if list.data.is_empty() {
                    println!("(no deployments)");
                }
            }
        }
        Commands::Api {
            method,
            path,
            body,
            input,
            org_id,
        } => {
            let payload = load_body(body.as_deref(), input.as_ref())?;
            let (status, value) = client
                .api(
                    method.to_reqwest(),
                    &path,
                    payload.as_ref(),
                    org_id.as_deref(),
                )
                .await?;
            if cli.json {
                let envelope = json!({"status": status, "body": value});
                println!("{}", serde_json::to_string_pretty(&envelope)?);
            } else if value.is_null() {
                // empty body
            } else {
                println!("{}", serde_json::to_string_pretty(&value)?);
            }
        }
        Commands::VersionInfo => unreachable!(),
    }
    Ok(())
}

fn load_body(
    inline: Option<&str>,
    input: Option<&PathBuf>,
) -> anyhow::Result<Option<Value>> {
    match (inline, input) {
        (Some(_), Some(_)) => Err(anyhow::anyhow!(
            "use only one of --body or --input for request payload"
        )),
        (Some(s), None) => Ok(Some(serde_json::from_str(s)?)),
        (None, Some(path)) => {
            let text = if path.as_os_str() == "-" {
                use std::io::Read;
                let mut buf = String::new();
                std::io::stdin().read_to_string(&mut buf)?;
                buf
            } else {
                std::fs::read_to_string(path)?
            };
            if text.trim().is_empty() {
                Ok(None)
            } else {
                Ok(Some(serde_json::from_str(&text)?))
            }
        }
        (None, None) => Ok(None),
    }
}

fn print_out<T: serde::Serialize>(cli: &Cli, value: &T, human: impl FnOnce()) {
    if cli.json {
        println!(
            "{}",
            serde_json::to_string_pretty(value).expect("serialize json")
        );
    } else {
        human();
    }
}