shelly-cli 0.2.2

CLI for managing and controlling Shelly devices
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
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
use std::collections::HashMap;

use clap::CommandFactory;
use serde_json::{Value, json};

use crate::cli::Cli;

/// Static metadata that cannot be derived from clap alone.
struct CommandMeta {
    mutating: bool,
    output_fields: &'static [(&'static str, &'static str)],
}

fn build_metadata() -> HashMap<&'static str, CommandMeta> {
    macro_rules! meta {
        ($path:expr, mutating: $mut:expr, fields: [$($name:expr => $typ:expr),* $(,)?]) => {
            ($path, CommandMeta {
                mutating: $mut,
                output_fields: &[$(($name, $typ)),*],
            })
        };
    }

    HashMap::from([
        meta!("discover", mutating: false, fields: [
            "name" => "string", "ip" => "string", "model" => "string",
            "generation" => "string", "mac" => "string", "firmware_version" => "string",
        ]),
        meta!("devices", mutating: false, fields: [
            "name" => "string", "ip" => "string", "model" => "string",
            "generation" => "string", "mac" => "string", "firmware_version" => "string",
        ]),
        meta!("status", mutating: false, fields: [
            "device" => "string", "ip" => "string",
            "uptime" => "integer | null", "temperature_c" => "number | null",
            "switches" => "array",
        ]),
        meta!("switch status", mutating: false, fields: [
            "device" => "string", "id" => "integer", "output" => "boolean",
            "power_watts" => "number | null",
        ]),
        meta!("switch on", mutating: true, fields: [
            "device" => "string", "was_on" => "boolean",
        ]),
        meta!("switch off", mutating: true, fields: [
            "device" => "string", "was_on" => "boolean",
        ]),
        meta!("switch toggle", mutating: true, fields: [
            "device" => "string", "was_on" => "boolean",
        ]),
        meta!("on", mutating: true, fields: [
            "device" => "string", "was_on" => "boolean",
        ]),
        meta!("off", mutating: true, fields: [
            "device" => "string", "was_on" => "boolean",
        ]),
        meta!("toggle", mutating: true, fields: [
            "device" => "string", "was_on" => "boolean",
        ]),
        meta!("light status", mutating: false, fields: [
            "device" => "string", "id" => "integer", "output" => "boolean",
            "brightness" => "number | null", "rgb" => "array | null",
        ]),
        meta!("light on", mutating: true, fields: [
            "device" => "string", "was_on" => "boolean",
        ]),
        meta!("light off", mutating: true, fields: [
            "device" => "string", "was_on" => "boolean",
        ]),
        meta!("light toggle", mutating: true, fields: [
            "device" => "string", "was_on" => "boolean",
        ]),
        meta!("light set", mutating: true, fields: [
            "device" => "string", "id" => "integer",
        ]),
        meta!("power", mutating: false, fields: [
            "device" => "string", "power_watts" => "number",
            "voltage" => "number | null", "current" => "number | null",
            "total_energy_wh" => "number",
        ]),
        meta!("energy", mutating: false, fields: [
            "device" => "string", "total_kwh" => "number",
        ]),
        meta!("firmware check", mutating: false, fields: [
            "device" => "string", "firmware" => "string", "has_update" => "boolean",
            "stable" => "string | null", "beta" => "string | null",
        ]),
        meta!("firmware update", mutating: true, fields: [
            "device" => "string", "status" => "string", "from" => "string | null",
        ]),
        meta!("config get", mutating: false, fields: []),
        meta!("config set", mutating: true, fields: [
            "device" => "string", "key" => "string", "value" => "string",
            "status" => "string",
        ]),
        meta!("schedule list", mutating: false, fields: [
            "device" => "string", "id" => "integer",
            "timespec" => "string", "enable" => "boolean",
        ]),
        meta!("webhook list", mutating: false, fields: [
            "device" => "string", "id" => "integer",
            "name" => "string", "event" => "string", "enable" => "boolean",
        ]),
        meta!("backup", mutating: false, fields: [
            "device" => "string", "file" => "string",
        ]),
        meta!("restore", mutating: true, fields: [
            "device" => "string", "backup_file" => "string", "status" => "string",
        ]),
        meta!("rename", mutating: true, fields: [
            "device" => "string", "new_name" => "string",
        ]),
        meta!("reboot", mutating: true, fields: [
            "device" => "string", "status" => "string",
        ]),
        meta!("info", mutating: false, fields: [
            "name" => "string", "model" => "string", "generation" => "string",
            "ip" => "string", "mac" => "string", "firmware" => "string",
            "uptime_seconds" => "integer | null", "switches" => "array",
        ]),
        meta!("health", mutating: false, fields: [
            "device" => "string", "online" => "boolean", "status" => "string",
        ]),
        meta!("group list", mutating: false, fields: [
            "name" => "string", "devices" => "array",
        ]),
        meta!("group add", mutating: true, fields: [
            "group" => "string", "devices" => "array",
        ]),
        meta!("group remove", mutating: true, fields: [
            "group" => "string", "removed" => "boolean",
        ]),
        meta!("group show", mutating: false, fields: [
            "name" => "string", "ip" => "string", "model" => "string",
            "generation" => "string",
        ]),
        meta!("schema", mutating: false, fields: []),
        meta!("capabilities", mutating: false, fields: [
            "generations" => "array", "features" => "array", "structured_output" => "boolean",
        ]),
        meta!("completions", mutating: false, fields: []),
    ])
}

/// The set of global arg IDs that appear on every command and should not be
/// repeated inside per-command `args` arrays.
const GLOBAL_ARG_IDS: &[&str] = &[
    "help", "version", "host", "name", "group", "output", "json", "quiet", "password", "timeout",
];

fn arg_to_json(a: &clap::Arg) -> Value {
    let id = a.get_id().as_str();
    let takes_value = a.get_action().takes_values();

    let value_type = if !takes_value {
        "boolean"
    } else {
        match id {
            "id" | "timeout" | "interval" | "limit" | "offset" => "integer",
            _ => "string",
        }
    };

    let flag_name = if a.is_positional() {
        id.to_string()
    } else {
        format!("--{id}")
    };

    let mut info = json!({
        "name": flag_name,
        "type": value_type,
        "required": a.is_required_set(),
        "description": a.get_help().map(|h| h.to_string()).unwrap_or_default(),
    });

    if a.is_positional() {
        info["positional"] = json!(true);
    }

    if let Some(default) = a.get_default_values().first() {
        info["default"] = json!(default.to_string_lossy());
    }

    if let Some(possible) = {
        let vals: Vec<_> = a.get_possible_values().into_iter().collect();
        if vals.is_empty() { None } else { Some(vals) }
    } {
        let enum_vals: Vec<Value> = possible.iter().map(|v| json!(v.get_name())).collect();
        info["enum"] = json!(enum_vals);
    }

    info
}

fn walk_commands(
    cmd: &clap::Command,
    prefix: &str,
    metadata: &HashMap<&str, CommandMeta>,
    out: &mut Vec<Value>,
) {
    for sub in cmd.get_subcommands() {
        let name = sub.get_name();
        if name == "help" || name.starts_with('_') || sub.is_hide_set() {
            continue;
        }

        let path = if prefix.is_empty() {
            name.to_string()
        } else {
            format!("{prefix} {name}")
        };

        let real_subcommands: Vec<_> = sub
            .get_subcommands()
            .filter(|s| s.get_name() != "help")
            .collect();

        if !real_subcommands.is_empty() {
            walk_commands(sub, &path, metadata, out);
            continue;
        }

        // Collect args that are not global-level flags
        let args: Vec<Value> = sub
            .get_arguments()
            .filter(|a| {
                let id = a.get_id().as_str();
                !GLOBAL_ARG_IDS.contains(&id)
            })
            .map(arg_to_json)
            .collect();

        let meta = metadata.get(path.as_str());

        let mut entry = serde_json::Map::new();
        entry.insert("name".into(), json!(path));
        if let Some(about) = sub.get_about().map(|a| a.to_string())
            && !about.is_empty()
        {
            entry.insert("description".into(), json!(about));
        }
        entry.insert("mutating".into(), json!(meta.is_some_and(|m| m.mutating)));
        entry.insert("args".into(), json!(args));

        if let Some(m) = meta
            && !m.output_fields.is_empty()
        {
            let fields: Vec<Value> = m
                .output_fields
                .iter()
                .map(|(n, t)| json!({"name": n, "type": t}))
                .collect();
            entry.insert("output_fields".into(), json!(fields));
        }

        out.push(Value::Object(entry));
    }
}

fn errors_schema() -> Value {
    json!([
        {
            "kind": "invalid_input",
            "exit_code": 1,
            "retryable": false,
            "description": "Invalid argument or unsupported parameter value"
        },
        {
            "kind": "device_not_found",
            "exit_code": 1,
            "retryable": false,
            "description": "Device name not found in the local cache"
        },
        {
            "kind": "no_cached_devices",
            "exit_code": 1,
            "retryable": false,
            "description": "No devices discovered yet; run 'shelly discover' first"
        },
        {
            "kind": "group_not_found",
            "exit_code": 1,
            "retryable": false,
            "description": "Named group not found in groups.toml"
        },
        {
            "kind": "device_unreachable",
            "exit_code": 2,
            "retryable": true,
            "description": "Device did not respond within the configured timeout"
        },
        {
            "kind": "confirmation_required",
            "exit_code": 2,
            "retryable": false,
            "description": "Destructive command requires explicit --yes when stdin is not a terminal"
        },
        {
            "kind": "network_error",
            "exit_code": 2,
            "retryable": true,
            "description": "Network or HTTP error communicating with the device"
        },
        {
            "kind": "auth_required",
            "exit_code": 3,
            "retryable": false,
            "description": "Device has authentication enabled but no password was provided"
        },
        {
            "kind": "partial_failure",
            "exit_code": 4,
            "retryable": false,
            "description": "Operation completed for some devices but failed for others"
        },
        {
            "kind": "conflict",
            "exit_code": 6,
            "retryable": false,
            "description": "Resource already in a conflicting state"
        },
    ])
}

/// Generate a clispec v0.3-compliant machine-readable schema.
pub fn generate_schema() -> Value {
    let cmd = Cli::command();
    let version = cmd.get_version().unwrap_or("unknown");
    let metadata = build_metadata();

    let global_args: Vec<Value> = cmd
        .get_arguments()
        .filter(|a| {
            let id = a.get_id().as_str();
            id != "help" && id != "version"
        })
        .map(arg_to_json)
        .collect();

    let mut commands: Vec<Value> = Vec::new();
    walk_commands(&cmd, "", &metadata, &mut commands);

    let mut schema = json!({
        "clispec": "0.3",
        "name": "shelly",
        "version": version,
        "description": "CLI for managing and controlling Shelly smart home devices over the LAN",
        "global_args": global_args,
        "commands": commands,
        "errors": errors_schema(),
    });
    enrich_v0_3(&mut schema);
    schema
}

fn enrich_v0_3(schema: &mut Value) {
    schema["output"] = json!({"tty":"text","piped":"json"});
    let Some(commands) = schema["commands"].as_array_mut() else {
        return;
    };
    for command in commands {
        let Some(object) = command.as_object_mut() else {
            continue;
        };
        let name = object["name"].as_str().unwrap_or_default().to_string();
        if name == "backup" {
            object.insert("mutating".into(), json!(true));
        }
        let mutating = object["mutating"].as_bool().unwrap_or(false);
        object.insert(
            "effects".into(),
            json!(if !mutating {
                "read_only"
            } else if name.contains("toggle") {
                "non_idempotent"
            } else {
                "idempotent"
            }),
        );
        if name == "completions" {
            object.remove("output_fields");
            object.insert("output_kind".into(), json!("opaque"));
            object.insert("media_type".into(), json!("text/plain"));
            continue;
        }
        if name == "watch" {
            object.insert("output_kind".into(), json!("stream"));
            object.insert("stream_format".into(), json!("terminal"));
            continue;
        }
        let unbounded = matches!(name.as_str(), "devices" | "schedule list" | "webhook list");
        object.insert(
            "cardinality".into(),
            json!(if unbounded { "unbounded" } else { "bounded" }),
        );
        if unbounded {
            object.insert(
                "pagination".into(),
                json!({"style":"offset","limit_arg":"--limit","offset_arg":"--offset"}),
            );
            object.insert("fields_arg".into(), json!("--fields"));
        }
        if name == "capabilities" {
            object.insert("example".into(), json!({"args":["capabilities"]}));
        }
        if name == "schema" {
            object.remove("output_fields");
            object.insert("cardinality".into(), json!("single"));
            object.insert(
                "stdout_schema".into(),
                json!({"$ref":"https://clispec.dev/schema/v0.3.json"}),
            );
        }
        if matches!(name.as_str(), "restore" | "rename" | "reboot") {
            object.insert("confirmation_bypass_arg".into(), json!("--yes"));
        }
        if let Some(fields) = object
            .get_mut("output_fields")
            .and_then(Value::as_array_mut)
        {
            for field in fields {
                let Some(field) = field.as_object_mut() else {
                    continue;
                };
                let kind = field
                    .get("type")
                    .and_then(Value::as_str)
                    .unwrap_or("string")
                    .to_string();
                if let Some(base) = kind.strip_suffix(" | null") {
                    field.insert("type".into(), json!(base));
                    field.insert("nullable".into(), json!(true));
                }
                if field.get("type").and_then(Value::as_str) == Some("array")
                    && !field.contains_key("items")
                {
                    field.insert("items".into(), json!({"type":"object"}));
                }
            }
        }
        if !object.contains_key("output_fields") && !object.contains_key("stdout_schema") {
            object.insert("stdout_schema".into(), json!({}));
        }
    }
}

#[cfg(test)]
mod tests {
    use super::generate_schema;

    fn find_command<'a>(
        commands: &'a [serde_json::Value],
        name: &str,
    ) -> Option<&'a serde_json::Value> {
        commands
            .iter()
            .find(|c| c["name"] == serde_json::json!(name))
    }

    #[test]
    fn schema_has_required_top_level_fields() {
        let schema = generate_schema();
        assert!(schema["name"].is_string(), "name must be present");
        assert!(schema["version"].is_string(), "version must be present");
        assert!(schema["commands"].is_array(), "commands must be an array");
        assert!(
            schema["global_args"].is_array(),
            "global_args must be an array"
        );
        assert!(schema["errors"].is_array(), "errors must be an array");
        assert_eq!(
            schema["clispec"],
            serde_json::json!("0.3"),
            "clispec version must be 0.3"
        );
    }

    #[test]
    fn schema_name_is_shelly() {
        let schema = generate_schema();
        assert_eq!(schema["name"], serde_json::json!("shelly"));
    }

    #[test]
    fn light_mutating_commands_are_marked() {
        let schema = generate_schema();
        let commands = schema["commands"].as_array().unwrap();

        for name in ["light on", "light off", "light toggle", "light set"] {
            let cmd = find_command(commands, name).unwrap_or_else(|| panic!("{name} not found"));
            assert_eq!(
                cmd["mutating"],
                serde_json::json!(true),
                "{name} should be mutating"
            );
        }

        let cmd = find_command(commands, "light status").expect("light status not found");
        assert_eq!(
            cmd["mutating"],
            serde_json::json!(false),
            "light status should be read-only"
        );
    }

    #[test]
    fn all_commands_have_mutating_field() {
        let schema = generate_schema();
        let commands = schema["commands"].as_array().unwrap();
        for cmd in commands {
            let name = cmd["name"].as_str().unwrap_or("?");
            assert!(
                cmd.get("mutating").is_some(),
                "command '{name}' is missing the mutating field"
            );
        }
    }

    #[test]
    fn errors_array_has_required_fields() {
        let schema = generate_schema();
        let errors = schema["errors"].as_array().unwrap();
        assert!(!errors.is_empty(), "errors array must not be empty");
        for err in errors {
            let kind = err["kind"].as_str().unwrap_or("?");
            assert!(
                err["exit_code"].is_number(),
                "error kind '{kind}' missing exit_code"
            );
            assert!(
                err["retryable"].is_boolean(),
                "error kind '{kind}' missing retryable"
            );
        }
    }

    #[test]
    fn confirmation_required_kind_is_declared() {
        let schema = generate_schema();
        let errors = schema["errors"].as_array().unwrap();
        let found = errors
            .iter()
            .any(|e| e["kind"] == serde_json::json!("confirmation_required"));
        assert!(
            found,
            "confirmation_required must be declared in errors array"
        );
    }

    #[test]
    fn conflict_kind_is_declared() {
        let schema = generate_schema();
        let errors = schema["errors"].as_array().unwrap();
        let found = errors
            .iter()
            .any(|e| e["kind"] == serde_json::json!("conflict"));
        assert!(found, "conflict must be declared in errors array");
    }

    #[test]
    fn list_commands_have_limit_and_offset_args() {
        let schema = generate_schema();
        let commands = schema["commands"].as_array().unwrap();

        for cmd_name in ["devices", "schedule list", "webhook list", "group list"] {
            let cmd =
                find_command(commands, cmd_name).unwrap_or_else(|| panic!("{cmd_name} not found"));
            let args = cmd["args"].as_array().unwrap();
            let arg_names: Vec<_> = args.iter().filter_map(|a| a["name"].as_str()).collect();
            assert!(
                arg_names.contains(&"--limit"),
                "{cmd_name} should have --limit arg"
            );
            assert!(
                arg_names.contains(&"--offset"),
                "{cmd_name} should have --offset arg"
            );
            assert!(
                arg_names.contains(&"--fields"),
                "{cmd_name} should have --fields arg"
            );
        }
    }

    #[test]
    fn output_fields_are_declared_for_key_commands() {
        let schema = generate_schema();
        let commands = schema["commands"].as_array().unwrap();

        for cmd_name in ["devices", "status", "power", "energy", "switch status"] {
            let cmd =
                find_command(commands, cmd_name).unwrap_or_else(|| panic!("{cmd_name} not found"));
            assert!(
                cmd.get("output_fields").is_some(),
                "{cmd_name} should have output_fields declared"
            );
        }
    }

    #[test]
    fn global_args_includes_output_flag() {
        let schema = generate_schema();
        let global_args = schema["global_args"].as_array().unwrap();
        let names: Vec<_> = global_args
            .iter()
            .filter_map(|a| a["name"].as_str())
            .collect();
        assert!(
            names.contains(&"--output"),
            "global_args must include --output"
        );
    }

    #[test]
    fn yes_flag_on_destructive_commands() {
        let schema = generate_schema();
        let commands = schema["commands"].as_array().unwrap();

        for cmd_name in [
            "reboot",
            "restore",
            "rename",
            "firmware update",
            "group remove",
        ] {
            let cmd =
                find_command(commands, cmd_name).unwrap_or_else(|| panic!("{cmd_name} not found"));
            let args = cmd["args"].as_array().unwrap();
            let has_yes = args.iter().any(|a| a["name"] == serde_json::json!("--yes"));
            assert!(has_yes, "{cmd_name} should have a --yes flag");
        }
    }
}