mesh-llm-cli 0.75.0

Reusable CLI support surface for mesh-llm
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
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
use std::ffi::OsString;

use super::commands::Cli;

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum RuntimeSurface {
    Serve,
    Client,
}

#[derive(Clone, Debug)]
pub struct NormalizedRuntimeArgs {
    pub original: Vec<OsString>,
    pub normalized: Vec<OsString>,
    pub explicit_surface: Option<RuntimeSurface>,
}

pub fn normalize_runtime_surface_args<I, S>(args: I) -> NormalizedRuntimeArgs
where
    I: IntoIterator<Item = S>,
    S: Into<OsString>,
{
    let original: Vec<OsString> = args.into_iter().map(Into::into).collect();
    let mut normalized = original.clone();
    let mut explicit_surface = None;

    // Skip leading global flags to find the pseudo-subcommand position.
    // Recognized value-taking flags: --log-format, --mesh-discovery-mode, --max-vram,
    // --llama-flavor, --device, --tensor-split, --bind-port, --bind-ip, --max-clients,
    // --port, --console, --swarm-capture, --draft-max, --ctx-size.
    // Boolean flags: --help-advanced, --auto, --client, --local-model-only, --headless, --publish,
    // --plugin, --auto-update, --no-draft, --split, --no-enumerate-host, --listen-all,
    // --no-console, --owner-required.
    let value_taking_flags = [
        "--log-format",
        "--mesh-discovery-mode",
        "--max-vram",
        "--llama-flavor",
        "--device",
        "--tensor-split",
        "--bind-port",
        "--bind-ip",
        "--max-clients",
        "--port",
        "--console",
        "--swarm-capture",
        "--draft-max",
        "--ctx-size",
        "--model",
        "--gguf",
        "--mmproj",
        "--join",
        "--discover",
        "--mesh-name",
        "--region",
        "--name",
        "--plugin",
        "--draft",
        "--bin-dir",
        "--relay",
        "--relay-auth",
        "--nostr-relay",
        "--config",
        "--owner-key",
        "--control-bind",
        "--control-advertise-addr",
        "--node-label",
        "--trust-policy",
        "--trust-owner",
    ];

    let mut pos = 1;
    while pos < original.len() {
        let arg_str = original.get(pos).and_then(|arg| arg.to_str()).unwrap_or("");

        // Check for --flag=value form
        if let Some(eq_idx) = arg_str.find('=') {
            let flag_part = &arg_str[..eq_idx];
            if value_taking_flags.contains(&flag_part) {
                pos += 1;
                continue;
            }
        }

        // Check for --flag value form
        if value_taking_flags.contains(&arg_str) {
            // Advance by 2 if next token exists and doesn't start with '-'
            if let Some(next) = original.get(pos + 1).and_then(|arg| arg.to_str())
                && !next.starts_with('-')
            {
                pos += 2;
                continue;
            }
            // If next doesn't exist or starts with '-', advance by 1 (let Clap handle the error)
            pos += 1;
            continue;
        }

        // If it starts with '-' but isn't a recognized flag, it's likely a parse error or unknown flag
        if arg_str.starts_with('-') {
            pos += 1;
            continue;
        }

        // Found the first positional argument (serve/client/other subcommand)
        break;
    }

    // Now apply the serve/client normalization logic at the discovered position
    match original.get(pos).and_then(|arg| arg.to_str()) {
        Some("serve") => match original.get(pos + 1).and_then(|arg| arg.to_str()) {
            Some(arg) if arg.starts_with('-') => {
                normalized.remove(pos);
                explicit_surface = Some(RuntimeSurface::Serve);
            }
            None => {
                normalized.remove(pos);
                explicit_surface = Some(RuntimeSurface::Serve);
            }
            _ => {}
        },
        Some("client") => {
            normalized.remove(pos);
            normalized.insert(pos, OsString::from("--client"));
            explicit_surface = Some(RuntimeSurface::Client);
        }
        _ => {}
    }

    NormalizedRuntimeArgs {
        original,
        normalized,
        explicit_surface,
    }
}

pub fn legacy_runtime_surface_warning(
    cli: &Cli,
    original_args: &[OsString],
    explicit_surface: Option<RuntimeSurface>,
) -> Option<String> {
    if explicit_surface.is_some() || cli.command.is_some() {
        return None;
    }

    if cli.client {
        return Some(format!(
            "⚠️ top-level `--client` now maps to `mesh-llm client`.\n  Please use: {}",
            suggested_client_command(original_args)
        ));
    }

    if !cli.model.is_empty() || !cli.gguf.is_empty() || cli.mmproj.is_some() {
        return Some(format!(
            "⚠️ top-level serving flags now map to `mesh-llm serve`.\n  Please use: {}",
            suggested_serve_command(original_args)
        ));
    }

    None
}

fn suggested_serve_command(original_args: &[OsString]) -> String {
    let mut args = Vec::with_capacity(original_args.len() + 1);
    if let Some(program) = original_args.first() {
        args.push(program.clone());
    } else {
        args.push(OsString::from("mesh-llm"));
    }
    args.push(OsString::from("serve"));
    args.extend(original_args.iter().skip(1).cloned());
    shell_join(&args)
}

fn suggested_client_command(original_args: &[OsString]) -> String {
    let mut args = Vec::with_capacity(original_args.len());
    if let Some(program) = original_args.first() {
        args.push(program.clone());
    } else {
        args.push(OsString::from("mesh-llm"));
    }
    args.push(OsString::from("client"));
    let mut skipped_client = false;
    for arg in original_args.iter().skip(1) {
        if !skipped_client && arg.to_string_lossy() == "--client" {
            skipped_client = true;
            continue;
        }
        args.push(arg.clone());
    }
    shell_join(&args)
}

fn shell_join(args: &[OsString]) -> String {
    args.iter().map(shell_display).collect::<Vec<_>>().join(" ")
}

fn shell_display(arg: &OsString) -> String {
    let text = arg.to_string_lossy();
    if text.is_empty() {
        "\"\"".into()
    } else if text
        .chars()
        .any(|ch| ch.is_whitespace() || matches!(ch, '"' | '\'' | '\\'))
    {
        format!("{text:?}")
    } else {
        text.into_owned()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::parser::{Cli, Command, MeshDiscoveryMode};
    use clap::Parser;
    use mesh_llm_events::LogFormat;
    use std::ffi::OsString;
    use std::path::PathBuf;

    #[test]
    fn normalize_runtime_surface_args_rewrites_serve_invocation() {
        let normalized = normalize_runtime_surface_args([
            "mesh-llm",
            "serve",
            "--auto",
            "--model",
            "Qwen3-8B-Q4_K_M",
        ]);

        assert_eq!(normalized.explicit_surface, Some(RuntimeSurface::Serve));
        assert_eq!(
            normalized.normalized,
            vec!["mesh-llm", "--auto", "--model", "Qwen3-8B-Q4_K_M"]
                .into_iter()
                .map(OsString::from)
                .collect::<Vec<_>>()
        );
    }

    #[test]
    fn normalize_runtime_surface_args_bare_serve_loads_default_config() {
        let normalized = normalize_runtime_surface_args(["mesh-llm", "serve"]);

        assert_eq!(normalized.explicit_surface, Some(RuntimeSurface::Serve));
        assert_eq!(
            normalized.normalized,
            vec!["mesh-llm"]
                .into_iter()
                .map(OsString::from)
                .collect::<Vec<_>>()
        );
    }

    #[test]
    fn normalize_runtime_surface_args_rewrites_client_invocation() {
        let normalized =
            normalize_runtime_surface_args(["mesh-llm", "client", "--auto", "--port", "9337"]);

        assert_eq!(normalized.explicit_surface, Some(RuntimeSurface::Client));
        assert_eq!(
            normalized.normalized,
            vec!["mesh-llm", "--client", "--auto", "--port", "9337"]
                .into_iter()
                .map(OsString::from)
                .collect::<Vec<_>>()
        );
    }

    #[test]
    fn normalize_runtime_surface_args_treats_relay_auth_as_value_taking_before_serve() {
        // Regression: --relay-auth carries a `URL=TOKEN` value, so the
        // pseudo-subcommand scanner must skip the value and still discover
        // `serve` (or `client`) as the runtime surface. If --relay-auth is not
        // in the value-taking list the scanner stops at the token and Clap
        // sees a malformed command.
        let normalized = normalize_runtime_surface_args([
            "mesh-llm",
            "--relay-auth",
            "https://gated.example/=token",
            "serve",
            "--relay",
            "https://gated.example/",
            "--auto",
        ]);

        assert_eq!(normalized.explicit_surface, Some(RuntimeSurface::Serve));
        assert_eq!(
            normalized.normalized,
            vec![
                "mesh-llm",
                "--relay-auth",
                "https://gated.example/=token",
                "--relay",
                "https://gated.example/",
                "--auto",
            ]
            .into_iter()
            .map(OsString::from)
            .collect::<Vec<_>>()
        );

        // And the resulting argv must actually parse cleanly through Clap so
        // the relay-auth value reaches `Cli::relay_auth`.
        let cli = Cli::try_parse_from(&normalized.normalized).expect("clap parse");
        assert_eq!(
            cli.relay_auth,
            vec![("https://gated.example/".to_string(), "token".to_string())],
        );
    }

    #[test]
    fn normalize_runtime_surface_args_relay_auth_before_client_invocation() {
        // Same regression but for the `client` surface, including a token
        // containing `=` (NIP-98-style base64 padding).
        let normalized = normalize_runtime_surface_args([
            "mesh-llm",
            "--relay-auth",
            "https://gated.example/=eyJhbGciOiJFZERTQSJ9.payload==",
            "client",
            "--auto",
        ]);

        assert_eq!(normalized.explicit_surface, Some(RuntimeSurface::Client));
        let cli = Cli::try_parse_from(&normalized.normalized).expect("clap parse");
        assert!(cli.client, "client surface flag should be set");
        assert_eq!(
            cli.relay_auth,
            vec![(
                "https://gated.example/".to_string(),
                "eyJhbGciOiJFZERTQSJ9.payload==".to_string()
            )],
        );
    }

    #[test]
    fn normalize_runtime_surface_args_keeps_non_runtime_subcommands() {
        let normalized = normalize_runtime_surface_args(["mesh-llm", "download", "foo"]);

        assert_eq!(normalized.explicit_surface, None);
        assert_eq!(
            normalized.normalized,
            vec!["mesh-llm", "download", "foo"]
                .into_iter()
                .map(OsString::from)
                .collect::<Vec<_>>()
        );
    }

    #[test]
    fn legacy_runtime_surface_warning_for_top_level_serve_flags() {
        let normalized =
            normalize_runtime_surface_args(["mesh-llm", "--auto", "--model", "Qwen3-8B-Q4_K_M"]);
        let cli = Cli::parse_from(normalized.normalized.clone());

        let warning =
            legacy_runtime_surface_warning(&cli, &normalized.original, normalized.explicit_surface)
                .expect("warning should be present");

        assert!(warning.contains("mesh-llm serve --auto --model Qwen3-8B-Q4_K_M"));
    }

    #[test]
    fn legacy_runtime_surface_warning_for_top_level_client_flag() {
        let normalized = normalize_runtime_surface_args(["mesh-llm", "--auto", "--client"]);
        let cli = Cli::parse_from(normalized.normalized.clone());

        let warning =
            legacy_runtime_surface_warning(&cli, &normalized.original, normalized.explicit_surface)
                .expect("warning should be present");

        assert!(warning.contains("mesh-llm client --auto"));
    }

    #[test]
    fn explicit_runtime_surface_suppresses_legacy_warning() {
        let normalized = normalize_runtime_surface_args(["mesh-llm", "client", "--auto"]);
        let cli = Cli::parse_from(normalized.normalized.clone());

        assert!(
            legacy_runtime_surface_warning(&cli, &normalized.original, normalized.explicit_surface)
                .is_none()
        );
    }

    #[test]
    fn cli_accepts_headless_flag_for_serve_surface() {
        let args = vec!["mesh-llm", "serve", "--headless", "--auto"];
        let normalized = normalize_runtime_surface_args(args);
        let cli = Cli::try_parse_from(&normalized.normalized).unwrap();
        assert!(cli.headless);
    }

    #[test]
    fn cli_accepts_headless_flag_for_client_surface() {
        let args = vec!["mesh-llm", "client", "--headless", "--auto"];
        let normalized = normalize_runtime_surface_args(args);
        let cli = Cli::try_parse_from(&normalized.normalized).unwrap();
        assert!(cli.headless);
    }

    #[test]
    fn cli_accepts_swarm_capture_flag_for_client_surface() {
        let args = vec![
            "mesh-llm",
            "client",
            "--swarm-capture",
            "/tmp/mesh-capture",
            "--auto",
        ];
        let normalized = normalize_runtime_surface_args(args);
        let cli = Cli::try_parse_from(&normalized.normalized).unwrap();

        assert!(cli.client);
        assert_eq!(cli.swarm_capture, Some(PathBuf::from("/tmp/mesh-capture")));
    }

    #[test]
    fn cli_accepts_global_swarm_capture_before_client() {
        let normalized = normalize_runtime_surface_args([
            "mesh-llm",
            "--swarm-capture",
            "/tmp/mesh-capture",
            "client",
            "--auto",
        ]);
        let cli = Cli::parse_from(normalized.normalized);

        assert!(cli.client);
        assert_eq!(cli.swarm_capture, Some(PathBuf::from("/tmp/mesh-capture")));
        assert_eq!(normalized.explicit_surface, Some(RuntimeSurface::Client));
    }

    #[test]
    fn legacy_no_console_remains_ignored_in_headless_tests() {
        let args = vec!["mesh-llm", "serve", "--no-console"];
        let normalized = normalize_runtime_surface_args(args);
        let cli = Cli::try_parse_from(&normalized.normalized).unwrap();
        assert!(
            !cli.headless,
            "--no-console must not activate headless mode"
        );
    }

    #[test]
    fn local_model_only_is_an_explicit_serve_topology() {
        let args = vec![
            "mesh-llm",
            "serve",
            "--local-model-only",
            "--model",
            "/models/model.gguf",
        ];
        let normalized = normalize_runtime_surface_args(args);
        let cli = Cli::try_parse_from(&normalized.normalized).unwrap();

        assert_eq!(normalized.explicit_surface, Some(RuntimeSurface::Serve));
        assert!(cli.local_model_only);
        assert!(!cli.client);
    }

    #[test]
    fn unknown_top_level_command_is_captured_for_plugin_dispatch() {
        let normalized = normalize_runtime_surface_args([
            "mesh-llm",
            "goose-next",
            "--model",
            "auto",
            "--",
            "prompt.txt",
        ]);
        let cli = Cli::parse_from(normalized.normalized);

        match cli.command.expect("external plugin command expected") {
            Command::ExternalPlugin(args) => {
                assert_eq!(
                    args,
                    vec![
                        OsString::from("goose-next"),
                        OsString::from("--model"),
                        OsString::from("auto"),
                        OsString::from("--"),
                        OsString::from("prompt.txt"),
                    ]
                );
            }
            other => panic!("unexpected command: {other:?}"),
        }
    }

    #[test]
    fn cli_defaults_log_format_to_pretty() {
        let normalized = normalize_runtime_surface_args(["mesh-llm", "serve", "--auto"]);
        let cli = Cli::parse_from(normalized.normalized);

        assert_eq!(cli.log_format, LogFormat::Pretty);
    }

    #[test]
    fn cli_accepts_json_log_format() {
        let normalized =
            normalize_runtime_surface_args(["mesh-llm", "serve", "--log-format", "json", "--auto"]);
        let cli = Cli::parse_from(normalized.normalized);

        assert_eq!(cli.log_format, LogFormat::Json);
    }

    #[test]
    fn cli_accepts_global_log_format_before_serve() {
        let normalized =
            normalize_runtime_surface_args(["mesh-llm", "--log-format", "json", "serve", "--auto"]);
        let cli = Cli::parse_from(normalized.normalized);

        assert_eq!(cli.log_format, LogFormat::Json);
        assert_eq!(normalized.explicit_surface, Some(RuntimeSurface::Serve));
    }

    #[test]
    fn cli_accepts_global_log_format_before_serve_with_model() {
        let normalized = normalize_runtime_surface_args([
            "mesh-llm",
            "--log-format",
            "json",
            "serve",
            "--model",
            "Qwen3-8B-Q4_K_M",
        ]);
        let cli = Cli::parse_from(normalized.normalized);

        assert_eq!(cli.log_format, LogFormat::Json);
        assert_eq!(cli.model, vec![std::path::PathBuf::from("Qwen3-8B-Q4_K_M")]);
        assert_eq!(normalized.explicit_surface, Some(RuntimeSurface::Serve));
    }

    #[test]
    fn cli_accepts_global_log_format_equals_before_serve() {
        let normalized =
            normalize_runtime_surface_args(["mesh-llm", "--log-format=json", "serve", "--auto"]);
        let cli = Cli::parse_from(normalized.normalized);

        assert_eq!(cli.log_format, LogFormat::Json);
        assert_eq!(normalized.explicit_surface, Some(RuntimeSurface::Serve));
    }

    #[test]
    fn cli_accepts_global_log_format_before_client() {
        let normalized = normalize_runtime_surface_args([
            "mesh-llm",
            "--log-format",
            "json",
            "client",
            "--auto",
        ]);
        let cli = Cli::parse_from(normalized.normalized);

        assert_eq!(cli.log_format, LogFormat::Json);
        assert_eq!(normalized.explicit_surface, Some(RuntimeSurface::Client));
    }

    #[test]
    fn cli_accepts_global_bind_ip_before_serve() {
        let normalized = normalize_runtime_surface_args([
            "mesh-llm",
            "--bind-ip",
            "10.1.2.3",
            "serve",
            "--bind-port",
            "47916",
        ]);
        let cli = Cli::parse_from(normalized.normalized);

        assert_eq!(cli.bind_ip, Some("10.1.2.3".parse().unwrap()));
        assert_eq!(cli.bind_port, Some(47916));
        assert_eq!(normalized.explicit_surface, Some(RuntimeSurface::Serve));
    }

    #[test]
    fn cli_accepts_global_mesh_discovery_mode_before_serve() {
        let normalized = normalize_runtime_surface_args([
            "mesh-llm",
            "--mesh-discovery-mode",
            "mdns",
            "serve",
            "--auto",
        ]);
        let cli = Cli::parse_from(normalized.normalized);

        assert_eq!(cli.mesh_discovery_mode, MeshDiscoveryMode::Mdns);
        assert_eq!(normalized.explicit_surface, Some(RuntimeSurface::Serve));
    }

    #[test]
    fn cli_defaults_mesh_discovery_mode_to_nostr() {
        let normalized = normalize_runtime_surface_args(["mesh-llm", "serve", "--auto"]);
        let cli = Cli::parse_from(normalized.normalized);

        assert_eq!(cli.mesh_discovery_mode, MeshDiscoveryMode::Nostr);
    }

    #[test]
    fn cli_accepts_mdns_discovery_mode_for_runtime_surfaces() {
        let normalized =
            normalize_runtime_surface_args(["mesh-llm", "client", "--mesh-discovery-mode", "mdns"]);
        let cli = Cli::parse_from(normalized.normalized);

        assert!(cli.client);
        assert_eq!(cli.mesh_discovery_mode, MeshDiscoveryMode::Mdns);
    }
}