roswire 0.1.1

JSON-first RouterOS CLI bridge for AI agents and automation.
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
use crate::error::{RosWireError, RosWireResult};
use clap::{Parser, ValueEnum};
use std::collections::BTreeMap;

#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
pub enum ProtocolMode {
    Auto,
    Api,
    ApiSsl,
    Rest,
}

impl ProtocolMode {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Auto => "auto",
            Self::Api => "api",
            Self::ApiSsl => "api-ssl",
            Self::Rest => "rest",
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
pub enum RouterOsVersionMode {
    Auto,
    V6,
    V7,
}

impl RouterOsVersionMode {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Auto => "auto",
            Self::V6 => "v6",
            Self::V7 => "v7",
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
pub enum TransferMode {
    Ssh,
}

impl TransferMode {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Ssh => "ssh",
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
pub enum TransferIfExists {
    Overwrite,
    Skip,
    Fail,
}

impl TransferIfExists {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Overwrite => "overwrite",
            Self::Skip => "skip",
            Self::Fail => "fail",
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParsedInvocation {
    pub path: Vec<String>,
    pub action: String,
    pub resolved_args: BTreeMap<String, String>,
}

#[derive(Debug, Parser)]
#[command(
    name = "roswire",
    version,
    about = "JSON-first RouterOS CLI bridge for AI agents and automation.",
    long_about = None
)]
pub struct Cli {
    #[arg(long)]
    pub profile: Option<String>,

    #[arg(long)]
    pub host: Option<String>,

    #[arg(long)]
    pub user: Option<String>,

    #[arg(long)]
    pub password: Option<String>,

    #[arg(long, value_enum)]
    pub protocol: Option<ProtocolMode>,

    #[arg(long = "routeros-version", value_enum)]
    pub routeros_version: Option<RouterOsVersionMode>,

    #[arg(long, value_enum)]
    pub transfer: Option<TransferMode>,

    #[arg(long)]
    pub port: Option<u16>,

    /// Output machine-readable JSON.
    #[arg(long)]
    pub json: bool,

    /// Enable debug diagnostics on stderr.
    #[arg(long)]
    pub debug: bool,

    /// Enable remote capability/schema probing for introspection commands.
    #[arg(long)]
    pub remote: bool,

    /// Force remote schema discovery to bypass cached schema metadata.
    #[arg(long)]
    pub refresh: bool,

    /// Build a plan without connecting to or modifying RouterOS.
    #[arg(long = "dry-run")]
    pub dry_run: bool,

    /// Include read-only remote RouterOS diagnostics for doctor.
    #[arg(long = "include-remote")]
    pub include_remote: bool,

    /// Read a secret value from stdin for secret set commands.
    #[arg(long)]
    pub stdin: bool,

    /// Expected RouterOS SSH host key fingerprint for transfer workflows.
    #[arg(long = "ssh-host-key")]
    pub ssh_host_key: Option<String>,

    /// RouterOS SSH service port for transfer workflows.
    #[arg(long = "ssh-port")]
    pub ssh_port: Option<u16>,

    /// SSH username for transfer workflows; defaults to RouterOS API user.
    #[arg(long = "ssh-user")]
    pub ssh_user: Option<String>,

    /// SSH password for transfer workflows; defaults to RouterOS API password.
    #[arg(long = "ssh-password")]
    pub ssh_password: Option<String>,

    /// SSH private key path for transfer workflows.
    #[arg(long = "ssh-key")]
    pub ssh_key: Option<String>,

    /// Allow-list CIDR for SSH access during transfer workflows.
    #[arg(long = "allow-from")]
    pub allow_from: Vec<String>,

    /// Permit the plan to ensure RouterOS SSH service state.
    #[arg(long = "ensure-ssh")]
    pub ensure_ssh: bool,

    /// Restore RouterOS SSH service state after transfer workflows.
    #[arg(long = "restore-ssh")]
    pub restore_ssh: bool,

    /// Policy when transfer destination already exists.
    #[arg(long = "if-exists", value_enum, default_value_t = TransferIfExists::Overwrite)]
    pub if_exists: TransferIfExists,

    /// SSH/API connection timeout in seconds for transfer workflows.
    #[arg(long = "connect-timeout-seconds")]
    pub connect_timeout_seconds: Option<u64>,

    /// Timeout in seconds while waiting for RouterOS-generated workflow files.
    #[arg(long = "wait-timeout-seconds")]
    pub wait_timeout_seconds: Option<u64>,

    /// Socket read/write timeout in seconds for transfer data plane.
    #[arg(long = "transfer-timeout-seconds")]
    pub transfer_timeout_seconds: Option<u64>,

    /// Cleanup operation timeout in seconds for transfer workflows.
    #[arg(long = "cleanup-timeout-seconds")]
    pub cleanup_timeout_seconds: Option<u64>,

    /// Maximum retry count for retryable transfer workflow steps.
    #[arg(long, default_value_t = 0)]
    pub retries: u8,

    /// Delay in seconds between retry attempts.
    #[arg(long = "retry-delay-seconds", default_value_t = 0)]
    pub retry_delay_seconds: u64,

    /// Allow explicit raw RouterOS passthrough commands that may mutate state.
    #[arg(long = "allow-write")]
    pub allow_write: bool,

    /// Remove temporary remote files after transfer workflows.
    #[arg(long)]
    pub cleanup: bool,

    /// Remote path override for import/upload workflows.
    #[arg(long = "remote-path")]
    pub remote_path: Option<String>,

    /// RouterOS-generated backup/export base name.
    #[arg(long)]
    pub name: Option<String>,

    /// Local text source for script workflows. Use @<path>.
    #[arg(long)]
    pub source: Option<String>,

    /// Request compact RouterOS export output.
    #[arg(long)]
    pub compact: bool,

    /// Internal test hook to exercise structured error output paths.
    #[arg(long, hide = true)]
    pub simulate_error: bool,

    /// Raw command tokens passed after global options.
    #[arg(value_name = "TOKEN")]
    pub tokens: Vec<String>,
}

pub fn parse_invocation(tokens: &[String]) -> RosWireResult<ParsedInvocation> {
    if tokens.is_empty() {
        return Err(Box::new(RosWireError::usage(
            "missing action: expected <path...> <action>",
        )));
    }

    let first_kv_index = tokens
        .iter()
        .position(|token| token.contains('='))
        .unwrap_or(tokens.len());
    let command_tokens = &tokens[..first_kv_index];

    if command_tokens.is_empty() {
        return Err(Box::new(RosWireError::usage(
            "missing action: expected <path...> <action>",
        )));
    }

    let action = command_tokens
        .last()
        .expect("command_tokens cannot be empty")
        .to_owned();
    let path = command_tokens[..command_tokens.len().saturating_sub(1)].to_vec();

    let mut resolved_args = BTreeMap::new();
    for token in &tokens[first_kv_index..] {
        let Some((key, value)) = token.split_once('=') else {
            return Err(Box::new(RosWireError::usage(format!(
                "argument after key=value section must also be key=value: {token}",
            ))));
        };

        if key.is_empty() {
            return Err(Box::new(RosWireError::usage(
                "argument key cannot be empty",
            )));
        }

        resolved_args.insert(key.to_owned(), value.to_owned());
    }

    Ok(ParsedInvocation {
        path,
        action,
        resolved_args,
    })
}

#[cfg(test)]
mod tests {
    use super::{parse_invocation, Cli, ProtocolMode, TransferIfExists};
    use clap::Parser;

    #[test]
    fn parses_print_path_and_action() {
        let cli =
            Cli::try_parse_from(["roswire", "ip", "address", "print"]).expect("args should parse");
        let invocation = parse_invocation(&cli.tokens).expect("invocation should parse");

        assert_eq!(invocation.path, vec!["ip", "address"]);
        assert_eq!(invocation.action, "print");
        assert!(invocation.resolved_args.is_empty());
    }

    #[test]
    fn parses_key_value_args_including_dot_id() {
        let cli = Cli::try_parse_from([
            "roswire",
            "ip",
            "address",
            "remove",
            ".id=*1",
            "comment=wan uplink",
        ])
        .expect("args should parse");

        let invocation = parse_invocation(&cli.tokens).expect("invocation should parse");

        assert_eq!(invocation.path, vec!["ip", "address"]);
        assert_eq!(invocation.action, "remove");
        assert_eq!(
            invocation.resolved_args.get(".id").map(String::as_str),
            Some("*1")
        );
        assert_eq!(
            invocation.resolved_args.get("comment").map(String::as_str),
            Some("wan uplink")
        );
    }

    #[test]
    fn missing_action_returns_usage_error() {
        let error = parse_invocation(&[]).expect_err("missing action should fail");
        assert_eq!(error.error_code, crate::error::ErrorCode::UsageError);
    }

    #[test]
    fn supports_protocol_value_enum() {
        let cli = Cli::try_parse_from(["roswire", "--protocol", "rest", "ip", "address", "print"])
            .expect("protocol enum should parse");

        assert_eq!(cli.protocol, Some(ProtocolMode::Rest));
        assert!(!cli.remote);
        assert!(!cli.refresh);
        assert!(!cli.dry_run);
        assert!(!cli.include_remote);
        assert!(!cli.stdin);
    }

    #[test]
    fn supports_remote_schema_refresh_flag() {
        let cli = Cli::try_parse_from(["roswire", "schema", "discover", "--remote", "--refresh"])
            .expect("refresh flag should parse");

        assert!(cli.remote);
        assert!(cli.refresh);
        assert_eq!(cli.tokens, vec!["schema", "discover"]);
    }

    #[test]
    fn supports_secret_stdin_flag() {
        let cli = Cli::try_parse_from([
            "roswire",
            "secret",
            "set",
            "studio",
            "password",
            "type=plain",
            "--stdin",
        ])
        .expect("stdin flag should parse");

        assert!(cli.stdin);
        assert_eq!(
            cli.tokens,
            vec!["secret", "set", "studio", "password", "type=plain"]
        );
    }

    #[test]
    fn supports_transfer_dry_run_flags() {
        let cli = Cli::try_parse_from([
            "roswire",
            "file",
            "upload",
            "setup.rsc",
            "flash/setup.rsc",
            "--dry-run",
            "--ssh-host-key",
            "SHA256:test",
            "--ssh-port",
            "2222",
            "--ssh-user",
            "backup",
            "--ssh-password",
            "transfer-value",
            "--ssh-key",
            "/Users/example/.ssh/id_ed25519",
            "--allow-from",
            "203.0.113.10/32",
            "--ensure-ssh",
            "--restore-ssh",
            "--if-exists",
            "skip",
            "--connect-timeout-seconds",
            "5",
            "--wait-timeout-seconds",
            "6",
            "--transfer-timeout-seconds",
            "7",
            "--cleanup-timeout-seconds",
            "8",
            "--retries",
            "2",
            "--retry-delay-seconds",
            "1",
            "--cleanup",
        ])
        .expect("transfer flags should parse");

        assert!(cli.dry_run);
        assert_eq!(cli.ssh_host_key.as_deref(), Some("SHA256:test"));
        assert_eq!(cli.ssh_port, Some(2222));
        assert_eq!(cli.ssh_user.as_deref(), Some("backup"));
        assert_eq!(cli.ssh_password.as_deref(), Some("transfer-value"));
        assert_eq!(
            cli.ssh_key.as_deref(),
            Some("/Users/example/.ssh/id_ed25519")
        );
        assert_eq!(cli.allow_from, vec!["203.0.113.10/32"]);
        assert!(cli.ensure_ssh);
        assert!(cli.restore_ssh);
        assert_eq!(cli.if_exists, TransferIfExists::Skip);
        assert_eq!(cli.connect_timeout_seconds, Some(5));
        assert_eq!(cli.wait_timeout_seconds, Some(6));
        assert_eq!(cli.transfer_timeout_seconds, Some(7));
        assert_eq!(cli.cleanup_timeout_seconds, Some(8));
        assert_eq!(cli.retries, 2);
        assert_eq!(cli.retry_delay_seconds, 1);
        assert!(cli.cleanup);
        assert_eq!(
            cli.tokens,
            vec!["file", "upload", "setup.rsc", "flash/setup.rsc"]
        );
    }

    #[test]
    fn supports_script_source_flag_after_tokens() {
        let cli = Cli::try_parse_from([
            "roswire",
            "script",
            "put",
            "bootstrap",
            "--source",
            "@setup.rsc",
            "--dry-run",
        ])
        .expect("script source flag should parse");

        assert_eq!(cli.source.as_deref(), Some("@setup.rsc"));
        assert!(cli.dry_run);
        assert_eq!(cli.tokens, vec!["script", "put", "bootstrap"]);
    }

    #[test]
    fn supports_raw_allow_write_flag_after_tokens() {
        let cli = Cli::try_parse_from([
            "roswire",
            "raw",
            "/ip/address/add",
            "address=192.0.2.10/24",
            "--allow-write",
        ])
        .expect("raw allow-write flag should parse");

        assert!(cli.allow_write);
        assert_eq!(
            cli.tokens,
            vec!["raw", "/ip/address/add", "address=192.0.2.10/24"]
        );
    }
}