kura-cli 0.1.16

Kura Training CLI for interacting with the Kura API and MCP runtime.
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
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
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
use clap::{CommandFactory, Parser, Subcommand, ValueEnum};
use serde_json::{Value, json};

use kura_cli::commands;
use kura_cli::util::{
    CliOutputMode, CliRuntimeOptions, exit_error, print_json_stderr, print_json_stdout,
    resolve_token, set_cli_runtime_options,
};

#[derive(Copy, Clone, Debug, Eq, PartialEq, ValueEnum)]
enum OutputFormatArg {
    Json,
    JsonCompact,
}

impl From<OutputFormatArg> for CliOutputMode {
    fn from(value: OutputFormatArg) -> Self {
        match value {
            OutputFormatArg::Json => CliOutputMode::Json,
            OutputFormatArg::JsonCompact => CliOutputMode::JsonCompact,
        }
    }
}

#[derive(Parser)]
#[command(
    name = "kura",
    version,
    about = "Kura Training CLI — Agent interface for training, nutrition, and health data"
)]
struct Cli {
    /// API base URL
    #[arg(long, env = "KURA_API_URL", default_value = "http://localhost:3000")]
    api_url: String,

    /// Skip credential check (for use behind an auth-injecting proxy)
    #[arg(long, env = "KURA_NO_AUTH")]
    no_auth: bool,

    /// JSON output format
    #[arg(long, global = true, value_enum, default_value_t = OutputFormatArg::Json, env = "KURA_OUTPUT")]
    output: OutputFormatArg,

    /// Suppress non-JSON stderr lines (notices/progress)
    #[arg(long, global = true, env = "KURA_QUIET_STDERR")]
    quiet_stderr: bool,

    /// Do not execute mutating operations (POST/PUT/PATCH/DELETE)
    #[arg(long, global = true, env = "KURA_DRY_RUN")]
    dry_run: bool,

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

#[derive(Subcommand)]
enum Commands {
    /// Check API health
    Health,

    /// Access request operations
    Access {
        #[command(subcommand)]
        command: commands::access::AccessCommands,
    },

    /// Direct API access (like gh api — works with any endpoint)
    Api(commands::api::ApiArgs),

    /// Execute one request from a JSON envelope file (defaults to stdin)
    Exec(commands::exec::ExecArgs),

    /// Emit machine-readable schema for CLI commands/args
    Schema {
        /// Optional command path, e.g. `api` or `agent request`
        #[arg(value_name = "COMMAND", num_args = 0..)]
        path: Vec<String>,
    },

    /// Event operations (create, list, batch)
    Event {
        #[command(subcommand)]
        command: commands::event::EventCommands,
    },

    /// Projection operations (get, list)
    Projection {
        #[command(subcommand)]
        command: commands::projection::ProjectionCommands,
    },

    /// Analysis operations (blocking run, async create/status)
    Analysis {
        #[command(subcommand)]
        command: commands::analysis::AnalysisCommands,
    },

    /// Deterministic read/inspect workflows for startup context and targeted follow-up fetches
    Read {
        #[command(subcommand)]
        command: commands::read::ReadCommands,
    },

    /// Agent operations (capabilities, context, structured write, evidence, preferences, visualization)
    Agent {
        #[command(subcommand)]
        command: commands::agent::AgentCommands,
    },

    /// Log one routine workout payload through the dedicated flat training route
    Log(commands::agent::LogTrainingArgs),

    /// Observation workflows (draft visibility + promotion)
    Observation {
        #[command(subcommand)]
        command: commands::observation::ObservationCommands,
    },

    /// MCP server operations (Model Context Protocol over stdio)
    Mcp {
        #[command(subcommand)]
        command: commands::mcp::McpCommands,
    },

    /// External import job operations
    Import {
        #[command(subcommand)]
        command: commands::imports::ImportCommands,
    },

    /// Provider connection operations
    Provider {
        #[command(subcommand)]
        command: commands::provider::ProviderCommands,
    },

    /// Offline replay evaluation wrappers (worker-backed)
    Eval {
        #[command(subcommand)]
        command: commands::eval::EvalCommands,
    },

    /// Get all projections in one call (agent bootstrap snapshot)
    Snapshot,

    /// Get system configuration (dimensions, conventions, event types)
    Config,

    /// Legacy alias for `kura agent context`
    #[command(hide = true)]
    Context {
        /// Max exercise_progression projections to include (default: 5)
        #[arg(long)]
        exercise_limit: Option<u32>,
        /// Max strength_inference projections to include (default: 5)
        #[arg(long)]
        strength_limit: Option<u32>,
        /// Max custom projections to include (default: 10)
        #[arg(long)]
        custom_limit: Option<u32>,
        /// Optional task intent used for context ranking
        #[arg(long)]
        task_intent: Option<String>,
        /// Include deployment-static system config in response payload
        #[arg(long)]
        include_system: Option<bool>,
        /// Optional response token budget hint (min 400, max 12000)
        #[arg(long)]
        budget_tokens: Option<u32>,
    },

    /// Legacy alias for `kura agent write-structured`
    #[command(hide = true)]
    WriteWithProof(commands::agent::WriteWithProofArgs),

    /// Diagnose setup: API, auth, worker, system config
    Doctor,

    /// Discover API surfaces (OpenAPI endpoints or exercise vocabulary)
    Discover {
        /// Show compact endpoint list only (method, path, summary)
        #[arg(long, conflicts_with = "exercises")]
        endpoints: bool,
        /// Show exercise vocabulary entries from semantic catalog
        #[arg(long, conflicts_with = "endpoints")]
        exercises: bool,
        /// Optional search query (case-insensitive), only with --exercises
        #[arg(long, requires = "exercises")]
        query: Option<String>,
        /// Max number of entries (1..=200), only with --exercises
        #[arg(long, requires = "exercises", value_parser = clap::value_parser!(u32).range(1..=200))]
        limit: Option<u32>,
    },

    /// Account operations
    Account {
        #[command(subcommand)]
        command: commands::account::AccountCommands,
    },

    /// Admin operations (bootstrapping and user management)
    Admin {
        #[command(subcommand)]
        command: commands::admin::AdminCommands,
    },

    /// Authenticate with the Kura API via OAuth
    Login {
        /// Use OAuth Device Authorization flow (code entry in browser UI)
        #[arg(long)]
        device: bool,
    },

    /// Remove stored credentials
    Logout,
}

#[tokio::main]
async fn main() {
    let _ = dotenvy::dotenv();
    let cli = Cli::parse();

    set_cli_runtime_options(CliRuntimeOptions {
        output_mode: cli.output.into(),
        quiet_stderr: cli.quiet_stderr,
        dry_run: cli.dry_run,
    });

    let code = match cli.command {
        Commands::Health => commands::health::run(&cli.api_url).await,

        Commands::Access { command } => commands::access::run(&cli.api_url, command).await,

        Commands::Api(mut args) => {
            if cli.no_auth {
                args.no_auth = true;
            }
            commands::api::run(&cli.api_url, args).await
        }

        Commands::Exec(args) => commands::exec::run(&cli.api_url, cli.no_auth, args).await,

        Commands::Schema { path } => emit_cli_schema(&path),

        Commands::Event { command } => {
            let token = resolve_or_exit(&cli.api_url, cli.no_auth).await;
            commands::event::run(&cli.api_url, token.as_deref(), command).await
        }

        Commands::Projection { command } => {
            let token = resolve_or_exit(&cli.api_url, cli.no_auth).await;
            commands::projection::run(&cli.api_url, token.as_deref(), command).await
        }

        Commands::Analysis { command } => {
            let token = resolve_or_exit(&cli.api_url, cli.no_auth).await;
            commands::analysis::run(&cli.api_url, token.as_deref(), command).await
        }

        Commands::Read { command } => {
            let token = resolve_or_exit(&cli.api_url, cli.no_auth).await;
            commands::read::run(&cli.api_url, token.as_deref(), command).await
        }

        Commands::Agent { command } => {
            let token = resolve_or_exit(&cli.api_url, cli.no_auth).await;
            commands::agent::run(&cli.api_url, token.as_deref(), command).await
        }

        Commands::Log(args) => {
            let token = resolve_or_exit(&cli.api_url, cli.no_auth).await;
            commands::agent::log_training(&cli.api_url, token.as_deref(), args).await
        }

        Commands::Observation { command } => {
            let token = resolve_or_exit(&cli.api_url, cli.no_auth).await;
            commands::observation::run(&cli.api_url, token.as_deref(), command).await
        }

        Commands::Mcp { command } => commands::mcp::run(&cli.api_url, cli.no_auth, command).await,

        Commands::Import { command } => {
            let token = resolve_or_exit(&cli.api_url, cli.no_auth).await;
            commands::imports::run(&cli.api_url, token.as_deref(), command).await
        }

        Commands::Provider { command } => {
            let token = resolve_or_exit(&cli.api_url, cli.no_auth).await;
            commands::provider::run(&cli.api_url, token.as_deref(), command).await
        }

        Commands::Eval { command } => commands::eval::run(command).await,

        Commands::Snapshot => {
            let token = resolve_or_exit(&cli.api_url, cli.no_auth).await;
            commands::system::snapshot(&cli.api_url, token.as_deref()).await
        }

        Commands::Config => {
            let token = resolve_or_exit(&cli.api_url, cli.no_auth).await;
            commands::system::config(&cli.api_url, token.as_deref()).await
        }

        Commands::Context {
            exercise_limit,
            strength_limit,
            custom_limit,
            task_intent,
            include_system,
            budget_tokens,
        } => {
            let token = resolve_or_exit(&cli.api_url, cli.no_auth).await;
            commands::agent::context(
                &cli.api_url,
                token.as_deref(),
                exercise_limit,
                strength_limit,
                custom_limit,
                task_intent,
                include_system,
                budget_tokens,
            )
            .await
        }

        Commands::WriteWithProof(args) => {
            let token = resolve_or_exit(&cli.api_url, cli.no_auth).await;
            commands::agent::write_with_proof(&cli.api_url, token.as_deref(), args).await
        }

        Commands::Doctor => commands::system::doctor(&cli.api_url).await,

        Commands::Discover {
            endpoints,
            exercises,
            query,
            limit,
        } => {
            let token = if exercises {
                resolve_or_exit(&cli.api_url, cli.no_auth).await
            } else {
                None
            };
            commands::system::discover(
                &cli.api_url,
                endpoints,
                exercises,
                query,
                limit,
                token.as_deref(),
            )
            .await
        }

        Commands::Account { command } => {
            let token = resolve_or_exit(&cli.api_url, cli.no_auth).await;
            commands::account::run(&cli.api_url, token.as_deref(), command).await
        }

        Commands::Admin { command } => {
            commands::admin::ensure_admin_surface_enabled_or_exit();
            let token = if commands::admin::requires_api_auth(&command) {
                resolve_or_exit(&cli.api_url, cli.no_auth).await
            } else {
                None
            };
            commands::admin::run(&cli.api_url, token.as_deref(), command).await
        }

        Commands::Login { device } => {
            if let Err(e) = commands::auth::login(&cli.api_url, device).await {
                exit_error(&e.to_string(), None);
            }
            0
        }

        Commands::Logout => {
            if let Err(e) = commands::auth::logout() {
                exit_error(&e.to_string(), None);
            }
            0
        }
    };

    std::process::exit(code);
}

fn emit_cli_schema(path: &[String]) -> i32 {
    let root = Cli::command();
    let command = match resolve_schema_path(root, path) {
        Ok(command) => command,
        Err((message, available_subcommands)) => {
            let err = json!({
                "error": "usage_error",
                "message": message,
                "available_subcommands": available_subcommands,
            });
            print_json_stderr(&err);
            return 4;
        }
    };

    let mut payload = command_schema(&command);
    payload["requested_path"] = json!(path);
    print_json_stdout(&payload);
    0
}

fn resolve_schema_path(
    mut command: clap::Command,
    path: &[String],
) -> Result<clap::Command, (String, Vec<String>)> {
    for segment in path {
        let next = command
            .get_subcommands()
            .find(|candidate| candidate.get_name() == segment)
            .cloned();

        match next {
            Some(candidate) => {
                command = candidate;
            }
            None => {
                let available_subcommands: Vec<String> = command
                    .get_subcommands()
                    .filter(|candidate| !candidate.is_hide_set())
                    .map(|candidate| candidate.get_name().to_string())
                    .collect();
                return Err((
                    format!("Unknown command path segment '{segment}' while resolving schema."),
                    available_subcommands,
                ));
            }
        }
    }

    Ok(command)
}

fn command_schema(command: &clap::Command) -> Value {
    let args: Vec<Value> = command
        .get_arguments()
        .filter(|arg| !arg.is_hide_set())
        .map(arg_schema)
        .collect();

    let subcommands: Vec<Value> = command
        .get_subcommands()
        .filter(|child| !child.is_hide_set())
        .map(|child| {
            json!({
                "name": child.get_name(),
                "about": child.get_about().map(|value| value.to_string())
            })
        })
        .collect();

    json!({
        "schema_version": "kura.cli.schema.v1",
        "name": command.get_name(),
        "about": command.get_about().map(|value| value.to_string()),
        "args": args,
        "subcommands": subcommands,
    })
}

fn arg_schema(arg: &clap::Arg) -> Value {
    let value_names: Vec<String> = arg
        .get_value_names()
        .map(|names| names.iter().map(|name| name.to_string()).collect())
        .unwrap_or_default();

    let default_values: Vec<String> = arg
        .get_default_values()
        .iter()
        .map(|value| value.to_string_lossy().to_string())
        .collect();

    let mut payload = json!({
        "id": arg.get_id().as_str(),
        "long": arg.get_long(),
        "short": arg.get_short().map(|value| value.to_string()),
        "required": arg.is_required_set(),
        "action": format!("{:?}", arg.get_action()),
        "help": arg.get_help().map(|value| value.to_string()),
        "value_names": value_names,
        "default_values": default_values,
    });

    if let Some(num_args) = arg.get_num_args() {
        payload["num_args"] = json!(format!("{num_args:?}"));
    }

    payload
}

async fn resolve_or_exit(api_url: &str, no_auth: bool) -> Option<String> {
    if no_auth {
        return None;
    }
    match resolve_token(api_url).await {
        Ok(t) => Some(t),
        Err(e) => exit_error(&e.to_string(), Some("Run `kura login` or set KURA_API_KEY")),
    }
}