openlatch-provider 0.2.1

Self-service onboarding CLI + runtime daemon for OpenLatch Editors and Providers
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
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
//! CLI surface — clap derive tree per PRD §8.1.
//!
//! The bodies of each subcommand live in submodules under `src/cli/commands/`.
//! At T0 every command is a stub returning `OlError::new(OL_42xx, "not yet
//! implemented")`; tasks T1–T8 fill them in.
//!
//! The dispatcher is intentionally thin — global flags are parsed once into
//! [`GlobalArgs`] and threaded into each command, so commands don't reach into
//! `Cli` themselves.

use crate::error::{OlError, OL_4270_CONFIG_UNREADABLE};
use clap::{Parser, Subcommand, ValueEnum};

pub mod commands;

// ---------------------------------------------------------------------------
// Top-level CLI definition
// ---------------------------------------------------------------------------

#[derive(Parser, Debug)]
#[command(
    name = "openlatch-provider",
    version,
    about = "Publish and run security tools on OpenLatch",
    long_about = None,
    disable_help_subcommand = true,
)]
pub struct Cli {
    #[command(subcommand)]
    pub command: Option<Command>,

    /// Activate a config profile (default: "default").
    #[arg(long, global = true, value_name = "NAME")]
    pub profile: Option<String>,

    /// Output format (TTY default = `table`, non-TTY default = `json`).
    #[arg(long, value_enum, global = true, value_name = "FORMAT")]
    pub output: Option<OutputFormat>,

    /// Suppress info/warn output. Errors still print.
    #[arg(long, short = 'q', global = true)]
    pub quiet: bool,

    /// Verbose human output (extra operational detail).
    #[arg(long, short = 'v', global = true)]
    pub verbose: bool,

    /// Internal state, timings, request/response bodies. Implies `--verbose`.
    #[arg(long, global = true)]
    pub debug: bool,

    /// Strip ANSI colors. Equivalent to setting `NO_COLOR=1`.
    #[arg(long, global = true)]
    pub no_color: bool,

    /// Assume "yes" to all interactive prompts.
    #[arg(long, short = 'y', global = true)]
    pub yes: bool,

    /// Show what would happen without actually doing it.
    #[arg(long, global = true)]
    pub dry_run: bool,

    /// Force-disable any interactive prompts.
    #[arg(long, global = true)]
    pub non_interactive: bool,

    /// (hidden) emit the entire CLI surface as Markdown to stdout.
    /// Used to regenerate `docs/cli-reference.md`.
    #[arg(long, hide = true)]
    pub markdown_help: bool,
}

/// Snapshot of the global flags. Built once by the dispatcher and threaded
/// into each command so tests can build it directly.
#[derive(Debug, Clone, Default)]
pub struct GlobalArgs {
    pub profile: Option<String>,
    pub output: Option<OutputFormat>,
    pub quiet: bool,
    pub verbose: bool,
    pub debug: bool,
    pub no_color: bool,
    pub yes: bool,
    pub dry_run: bool,
    pub non_interactive: bool,
}

impl GlobalArgs {
    pub fn from_cli(cli: &Cli) -> Self {
        Self {
            profile: cli.profile.clone(),
            output: cli.output,
            quiet: cli.quiet,
            verbose: cli.verbose || cli.debug,
            debug: cli.debug,
            no_color: cli.no_color,
            yes: cli.yes,
            dry_run: cli.dry_run,
            non_interactive: cli.non_interactive,
        }
    }
}

#[derive(ValueEnum, Debug, Clone, Copy, PartialEq, Eq)]
pub enum OutputFormat {
    Table,
    Json,
    Yaml,
    Sarif,
}

// ---------------------------------------------------------------------------
// Subcommands — PRD §8.1
// ---------------------------------------------------------------------------

#[derive(Subcommand, Debug)]
pub enum Command {
    /// Sign in to your OpenLatch account.
    Login(commands::auth::LoginArgs),

    /// Sign out and clear your saved credentials.
    Logout,

    /// Show who you're signed in as.
    Whoami,

    /// Set up a new tool — sign in and create your manifest.
    Init(commands::init::InitArgs),

    /// Create a starter tool project from a template.
    New {
        #[command(subcommand)]
        kind: NewKind,
    },

    /// Manage your publisher profile.
    Editor {
        #[command(subcommand)]
        action: EditorAction,
    },

    /// Submit your manifest to OpenLatch.
    Register(commands::register::RegisterArgs),

    /// Publish a new version of your tool.
    Publish(commands::publish::PublishArgs),

    /// Mark a tool version range as deprecated.
    Deprecate(commands::tools::DeprecateArgs),

    /// Split a v1 manifest into a v2 (tool, provider) pair.
    Migrate(commands::migrate::MigrateArgs),

    /// List, delete, or deprecate your tools.
    Tools {
        #[command(subcommand)]
        action: ToolsAction,
    },

    /// List, update, or delete your providers.
    Providers {
        #[command(subcommand)]
        action: ProvidersAction,
    },

    /// Manage bindings and webhook secrets.
    Bindings {
        #[command(subcommand)]
        action: BindingsAction,
    },

    /// Start the event listener that handles incoming requests.
    Listen(commands::listen::ListenArgs),

    /// Send a test event to your running listener.
    Trigger(commands::trigger::TriggerArgs),

    /// Watch live events as they arrive.
    Tail(commands::tail::TailArgs),

    /// Inspect events recorded by `listen` (audit JSONL stream).
    Events {
        #[command(subcommand)]
        action: EventsAction,
    },

    /// Check that everything is set up correctly.
    Doctor,

    /// Auto-update via npm registry + minisign verify + atomic swap.
    Update(commands::update::UpdateArgs),

    /// Print shell completions for the given shell.
    Completions {
        /// Target shell.
        #[arg(value_enum)]
        shell: ShellKind,
    },

    /// (Deprecated) Legacy `self update` — replaced by top-level `update`.
    /// Kept as a thin alias for backwards compatibility; will be removed in
    /// v0.2. Forwards to `commands::update`.
    #[command(name = "self", hide = true)]
    SelfCmd {
        #[command(subcommand)]
        action: SelfAction,
    },

    /// View or change your local settings.
    Config {
        #[command(subcommand)]
        action: ConfigAction,
    },
}

// -- nested action enums ----------------------------------------------------

#[derive(Subcommand, Debug)]
pub enum NewKind {
    /// Create a starter tool project (Python, Rust, or Node).
    Tool {
        #[arg(long, value_enum)]
        template: ToolTemplate,
        /// Target directory (default: ./<slug>).
        #[arg(long)]
        out: Option<String>,
    },
}

#[derive(ValueEnum, Debug, Clone, Copy, PartialEq, Eq)]
pub enum ToolTemplate {
    Python,
    Rust,
    Node,
}

#[derive(ValueEnum, Debug, Clone, Copy, PartialEq, Eq)]
pub enum ShellKind {
    Bash,
    Zsh,
    Fish,
    PowerShell,
    Elvish,
}

impl ShellKind {
    fn into_clap_complete(self) -> clap_complete::Shell {
        use clap_complete::Shell::*;
        match self {
            Self::Bash => Bash,
            Self::Zsh => Zsh,
            Self::Fish => Fish,
            Self::PowerShell => PowerShell,
            Self::Elvish => Elvish,
        }
    }
}

#[derive(Subcommand, Debug)]
pub enum EditorAction {
    /// Update your publisher profile.
    Update(commands::editor::UpdateArgs),
}

#[derive(Subcommand, Debug)]
pub enum ToolsAction {
    /// Show all your tools.
    List,
    /// Permanently delete a tool.
    Delete {
        slug: String,
        /// Skip confirmation prompt.
        #[arg(long)]
        yes: bool,
    },
    /// Mark a tool version range as deprecated.
    Deprecate(commands::tools::DeprecateArgs),
    /// Show live status of every managed tool process (PID, uptime, restart
    /// count, last health probe).
    Status {
        /// Admin port the running daemon is listening on.
        #[arg(long, value_name = "PORT", default_value_t = crate::runtime::supervisor::DEFAULT_ADMIN_PORT)]
        admin_port: u16,
    },
    /// Tail a managed tool's JSONL log file.
    Logs {
        /// Tool slug.
        slug: String,
        /// Follow new lines as the daemon writes them.
        #[arg(long)]
        follow: bool,
        /// Lines to print before following. Default 200.
        #[arg(long, default_value_t = 200)]
        tail: usize,
    },
    /// Force the daemon to restart a managed tool.
    Restart {
        /// Tool slug.
        slug: String,
        /// Admin port the running daemon is listening on.
        #[arg(long, value_name = "PORT", default_value_t = crate::runtime::supervisor::DEFAULT_ADMIN_PORT)]
        admin_port: u16,
    },
    /// Run a one-shot /healthz probe through the daemon.
    Probe {
        /// Tool slug.
        slug: String,
        /// Admin port the running daemon is listening on.
        #[arg(long, value_name = "PORT", default_value_t = crate::runtime::supervisor::DEFAULT_ADMIN_PORT)]
        admin_port: u16,
    },
}

#[derive(Subcommand, Debug)]
pub enum ProvidersAction {
    /// Show all your providers.
    List,
    /// Update a provider's settings.
    Update { slug: String },
    /// Permanently delete a provider.
    Delete {
        slug: String,
        #[arg(long)]
        yes: bool,
    },
}

#[derive(Subcommand, Debug)]
pub enum BindingsAction {
    /// Show all your bindings.
    List,
    /// Generate a new webhook signing secret (shown once).
    RotateSecret {
        id: String,
        #[arg(long)]
        yes: bool,
    },
    /// Remove a binding's webhook signing secret.
    DeleteSecret {
        id: String,
        #[arg(long)]
        yes: bool,
    },
    /// Test that a binding's endpoint is reachable.
    Probe { id: String },
    /// Show traffic and latency metrics for a binding.
    Metrics { id: String },
    /// Permanently delete a binding.
    Delete {
        id: String,
        #[arg(long)]
        yes: bool,
    },
}

#[derive(Subcommand, Debug)]
pub enum SelfAction {
    /// Update openlatch-provider to the latest version.
    Update {
        /// Check for an update without installing it.
        #[arg(long)]
        check: bool,
        /// Install the update without prompting.
        #[arg(long)]
        apply: bool,
        /// Release channel (`stable` or `beta`).
        #[arg(long)]
        channel: Option<String>,
    },
}

#[derive(Subcommand, Debug)]
pub enum EventsAction {
    /// Stream the runtime audit log (`~/.openlatch/provider/logs/runtime-*.jsonl`).
    Tail {
        /// Follow new lines as the daemon writes them.
        #[arg(long)]
        follow: bool,
        /// Lines to print before following. Default 200.
        #[arg(long, default_value_t = 200)]
        tail: usize,
    },
}

#[derive(Subcommand, Debug)]
pub enum ConfigAction {
    /// Read a setting value.
    Get { key: String },
    /// Change a setting value.
    Set { key: String, value: String },
    /// Show all your profiles and their settings.
    List,
}

// ---------------------------------------------------------------------------
// Dispatcher
// ---------------------------------------------------------------------------

/// Parse `argv` into the typed [`Cli`] surface. Exposed so `main.rs` can
/// initialise the tracing subscriber from [`GlobalArgs`] *before* dispatching.
pub fn parse_cli() -> Cli {
    Cli::parse()
}

/// Parse the CLI and dispatch to the matching command. Equivalent to
/// `dispatch_cli(parse_cli())` — retained for tests and external callers
/// that don't need to interpose between parse and dispatch.
pub async fn dispatch() -> Result<(), OlError> {
    dispatch_cli(parse_cli()).await
}

/// Dispatch a pre-parsed [`Cli`]. Bodies are stubs at T0 — most return
/// `OL-42xx not-yet-implemented` errors. Each task fills in its slice in
/// subsequent commits.
pub async fn dispatch_cli(cli: Cli) -> Result<(), OlError> {
    if cli.markdown_help {
        // `--markdown-help` synchronously dumps the entire CLI tree to
        // stdout as GitHub-flavoured markdown. CI's `docs-drift` job runs
        // this and asserts the output matches the committed
        // `docs/cli-reference.md` to catch flag drift.
        let markdown = clap_markdown::help_markdown::<Cli>();
        println!("{markdown}");
        return Ok(());
    }

    let g = GlobalArgs::from_cli(&cli);

    match cli.command {
        None => {
            let out = crate::ui::output::OutputConfig::resolve(&g);
            crate::ui::header::print_full_banner(&out);
            <Cli as clap::CommandFactory>::command()
                .print_help()
                .map_err(|e| {
                    OlError::new(OL_4270_CONFIG_UNREADABLE, format!("printing help: {e}"))
                })?;
            println!();
            Ok(())
        }
        Some(Command::Login(args)) => commands::auth::login(&g, args).await,
        Some(Command::Logout) => commands::auth::logout(&g).await,
        Some(Command::Whoami) => commands::auth::whoami(&g).await,
        Some(Command::Init(args)) => commands::init::run(&g, args).await,
        Some(Command::New { kind }) => commands::new::run(&g, kind).await,
        Some(Command::Editor { action }) => commands::editor::run(&g, action).await,
        Some(Command::Register(args)) => commands::register::run(&g, args).await,
        Some(Command::Publish(args)) => commands::publish::run(&g, args).await,
        Some(Command::Deprecate(args)) => commands::tools::deprecate(&g, args).await,
        Some(Command::Migrate(args)) => commands::migrate::run(&g, args).await,
        Some(Command::Tools { action }) => commands::tools::run(&g, action).await,
        Some(Command::Providers { action }) => commands::providers::run(&g, action).await,
        Some(Command::Bindings { action }) => commands::bindings::run(&g, action).await,
        Some(Command::Listen(args)) => commands::listen::run(&g, args).await,
        Some(Command::Trigger(args)) => commands::trigger::run(&g, args).await,
        Some(Command::Tail(args)) => commands::tail::run(&g, args).await,
        Some(Command::Events { action }) => commands::events::run(&g, action).await,
        Some(Command::Doctor) => commands::doctor::run(&g).await,
        Some(Command::Update(args)) => commands::update::run(&g, args).await,
        Some(Command::Completions { shell }) => {
            use clap::CommandFactory;
            let mut cmd = Cli::command();
            let bin = cmd.get_name().to_string();
            clap_complete::generate(
                shell.into_clap_complete(),
                &mut cmd,
                bin,
                &mut std::io::stdout(),
            );
            Ok(())
        }
        Some(Command::SelfCmd { action }) => commands::self_update::run(&g, action).await,
        Some(Command::Config { action }) => commands::config::run(&g, action).await,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use clap::CommandFactory;

    #[test]
    fn cli_definition_compiles() {
        // clap derive macro panics at startup if the definition is malformed;
        // calling debug_assert validates argument shapes.
        Cli::command().debug_assert();
    }
}