nms-copilot 0.2.0

Interactive galactic copilot for No Man's Sky — REPL with live save file updates and MCP server
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
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
635
636
637
638
//! REPL command parsing -- reuses clap derive for consistent argument handling.

use clap::{Parser, Subcommand};

/// Top-level REPL command parser.
///
/// This is separate from the CLI parser because:
/// - No `--save` flag (the model is already loaded)
/// - Extra REPL-only commands (exit, help, status, set, reset)
/// - Parsed from user input line, not process args
#[derive(Parser, Debug)]
#[command(
    name = "",
    no_binary_name = true,
    disable_help_subcommand = true,
    disable_version_flag = true
)]
pub struct ReplCommand {
    #[command(subcommand)]
    pub action: Option<Action>,
}

#[derive(Subcommand, Debug)]
pub enum Action {
    /// Search planets by biome, distance, name.
    Find {
        /// Filter by biome (e.g., Lush, Toxic, Scorched).
        #[arg(long)]
        biome: Option<String>,

        /// Only show infested planets.
        #[arg(long)]
        infested: bool,

        /// Only within this radius in light-years.
        #[arg(long)]
        within: Option<f64>,

        /// Show only the N nearest results.
        #[arg(long)]
        nearest: Option<usize>,

        /// Only show named planets/systems.
        #[arg(long)]
        named: bool,

        /// Filter by discoverer username (substring match).
        #[arg(long)]
        discoverer: Option<String>,

        /// Distance from this base name (default: current position).
        #[arg(long)]
        from: Option<String>,
    },

    /// Show detailed information about a system or base.
    Show {
        #[command(subcommand)]
        target: ShowTarget,
    },

    /// Display aggregate galaxy statistics.
    Stats {
        /// Show biome distribution table.
        #[arg(long)]
        biomes: bool,

        /// Show discovery counts by type.
        #[arg(long)]
        discoveries: bool,
    },

    /// Convert between NMS coordinate formats.
    Convert {
        /// Portal glyphs as 12 hex digits or emoji.
        #[arg(long, group = "input")]
        glyphs: Option<String>,

        /// Signal booster coordinates (XXXX:YYYY:ZZZZ:SSSS).
        #[arg(long, group = "input")]
        coords: Option<String>,

        /// Galactic address as hex (0x...).
        #[arg(long, group = "input")]
        ga: Option<String>,

        /// Voxel position as X,Y,Z (requires --ssi).
        #[arg(long, group = "input")]
        voxel: Option<String>,

        /// Solar system index (required with --voxel).
        #[arg(long)]
        ssi: Option<u16>,

        /// Planet index (0-15, defaults to 0).
        #[arg(long, default_value = "0")]
        planet: u8,

        /// Galaxy index (0-255) or name.
        #[arg(long, default_value = "0")]
        galaxy: String,
    },

    /// Plan a route through discovered systems.
    Route {
        /// Filter targets by biome (e.g., Lush, Toxic).
        #[arg(long)]
        biome: Option<String>,

        /// Named targets (bases or systems) to visit.
        #[arg(long = "target", num_args = 1)]
        targets: Vec<String>,

        /// Start from this base name (default: current position).
        #[arg(long)]
        from: Option<String>,

        /// Ship warp range in light-years (for hop constraints).
        #[arg(long)]
        warp_range: Option<f64>,

        /// Only consider targets within this radius in light-years.
        #[arg(long)]
        within: Option<f64>,

        /// Maximum number of targets to visit.
        #[arg(long)]
        max_targets: Option<usize>,

        /// Routing algorithm: nn, nearest-neighbor, 2opt, two-opt.
        #[arg(long)]
        algo: Option<String>,

        /// Return to starting system at the end.
        #[arg(long)]
        round_trip: bool,
    },

    /// Set session context (position, biome filter, warp range).
    Set {
        #[command(subcommand)]
        target: SetTarget,
    },

    /// Reset session state.
    Reset {
        /// What to reset (position, biome, warp-range, all).
        #[arg(default_value = "all")]
        target: String,
    },

    /// List reference data or model collections.
    List {
        #[command(subcommand)]
        target: ListTarget,
    },

    /// Open interactive galaxy map.
    Map,

    /// Show current session state.
    Status,

    /// Display save file summary.
    Info,

    /// Show help for REPL commands.
    Help,

    /// Exit the REPL.
    Exit,

    /// Exit the REPL.
    Quit,
}

#[derive(Subcommand, Debug)]
pub enum SetTarget {
    /// Set reference position to a base name.
    Position {
        /// Base name or address.
        name: String,
    },
    /// Set active biome filter.
    Biome {
        /// Biome name (e.g., Lush, Toxic).
        name: String,
    },
    /// Set default warp range.
    #[command(name = "warp-range")]
    WarpRange {
        /// Range in light-years.
        ly: f64,
    },
}

#[derive(Subcommand, Debug)]
pub enum ListTarget {
    /// List all 256 galaxies.
    Galaxies {
        /// Filter by galaxy type (Normal, Lush, Harsh, Empty).
        #[arg(long = "type")]
        galaxy_type: Option<String>,
    },
    /// List biome types and their variants.
    Biomes,
    /// List portal glyphs.
    Glyphs,
    /// List player bases.
    Bases {
        /// Maximum number of bases to display (0 for all).
        #[arg(long, default_value = "0")]
        limit: usize,

        /// Show all bases (equivalent to --limit 0).
        #[arg(long)]
        all: bool,
    },
    /// List discovered systems.
    Systems {
        /// Maximum number of systems to display (0 for all).
        #[arg(long, default_value = "50")]
        limit: usize,

        /// Show all systems (equivalent to --limit 0).
        #[arg(long)]
        all: bool,
    },
    /// List terrain generation types (GcBiomeSubType).
    #[command(name = "terrain-types")]
    TerrainTypes,
}

#[derive(Subcommand, Debug)]
pub enum ShowTarget {
    /// Show system details.
    System {
        /// System name or hex address.
        name: String,
    },
    /// Show base details.
    Base {
        /// Base name (case-insensitive).
        name: String,
    },
}

/// Parse a REPL input line into a command.
///
/// Returns `None` for empty lines.
/// Returns `Err` with clap's error message for invalid commands.
pub fn parse_line(line: &str) -> Result<Option<Action>, String> {
    let line = line.trim();
    if line.is_empty() {
        return Ok(None);
    }

    let mut args = shell_words(line);

    // Rewrite "<command> help" to "<command> --help" so clap generates
    // per-command help even though the top-level help subcommand is disabled.
    if args.len() >= 2 && args.last().map(|s| s.as_str()) == Some("help") {
        // Don't rewrite "show help" or "set help" — those have subcommands
        // that could legitimately be named "help". But for top-level commands
        // like "find help", "route help", etc., rewrite to --help.
        let last = args.len() - 1;
        args[last] = "--help".to_string();
    }

    match ReplCommand::try_parse_from(args) {
        Ok(cmd) => Ok(cmd.action),
        Err(e) => {
            let rendered = e.render().to_string();
            if e.use_stderr() {
                Err(rendered)
            } else {
                // Help text -- print it and return None
                print!("{rendered}");
                Ok(None)
            }
        }
    }
}

/// Simple shell-like word splitting that respects double quotes.
fn shell_words(input: &str) -> Vec<String> {
    let mut words = Vec::new();
    let mut current = String::new();
    let mut in_quotes = false;

    for ch in input.chars() {
        match ch {
            '"' => in_quotes = !in_quotes,
            ' ' if !in_quotes => {
                if !current.is_empty() {
                    words.push(std::mem::take(&mut current));
                }
            }
            _ => current.push(ch),
        }
    }

    if !current.is_empty() {
        words.push(current);
    }

    words
}

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

    #[test]
    fn test_parse_empty_line() {
        assert!(parse_line("").unwrap().is_none());
        assert!(parse_line("   ").unwrap().is_none());
    }

    #[test]
    fn test_parse_exit() {
        let action = parse_line("exit").unwrap().unwrap();
        assert!(matches!(action, Action::Exit));
    }

    #[test]
    fn test_parse_quit() {
        let action = parse_line("quit").unwrap().unwrap();
        assert!(matches!(action, Action::Quit));
    }

    #[test]
    fn test_parse_help() {
        let action = parse_line("help").unwrap().unwrap();
        assert!(matches!(action, Action::Help));
    }

    #[test]
    fn test_parse_find_with_biome() {
        let action = parse_line("find --biome Lush --nearest 5")
            .unwrap()
            .unwrap();
        match action {
            Action::Find { biome, nearest, .. } => {
                assert_eq!(biome.as_deref(), Some("Lush"));
                assert_eq!(nearest, Some(5));
            }
            _ => panic!("Expected Find"),
        }
    }

    #[test]
    fn test_parse_show_base_quoted() {
        let action = parse_line("show base \"Acadia National Park\"")
            .unwrap()
            .unwrap();
        match action {
            Action::Show {
                target: ShowTarget::Base { name },
            } => {
                assert_eq!(name, "Acadia National Park");
            }
            _ => panic!("Expected Show Base"),
        }
    }

    #[test]
    fn test_parse_unknown_command() {
        assert!(parse_line("foobar").is_err());
    }

    #[test]
    fn test_shell_words_basic() {
        let words = shell_words("find --biome Lush");
        assert_eq!(words, vec!["find", "--biome", "Lush"]);
    }

    #[test]
    fn test_shell_words_quoted() {
        let words = shell_words("show base \"My Base Name\"");
        assert_eq!(words, vec!["show", "base", "My Base Name"]);
    }

    #[test]
    fn test_parse_stats_flags() {
        let action = parse_line("stats --biomes").unwrap().unwrap();
        match action {
            Action::Stats {
                biomes,
                discoveries,
            } => {
                assert!(biomes);
                assert!(!discoveries);
            }
            _ => panic!("Expected Stats"),
        }
    }

    #[test]
    fn test_parse_info() {
        let action = parse_line("info").unwrap().unwrap();
        assert!(matches!(action, Action::Info));
    }

    #[test]
    fn test_parse_status() {
        let action = parse_line("status").unwrap().unwrap();
        assert!(matches!(action, Action::Status));
    }

    #[test]
    fn test_parse_set_biome() {
        let action = parse_line("set biome Lush").unwrap().unwrap();
        match action {
            Action::Set {
                target: SetTarget::Biome { name },
            } => assert_eq!(name, "Lush"),
            _ => panic!("Expected Set Biome"),
        }
    }

    #[test]
    fn test_parse_set_position() {
        let action = parse_line("set position \"Home Base\"").unwrap().unwrap();
        match action {
            Action::Set {
                target: SetTarget::Position { name },
            } => assert_eq!(name, "Home Base"),
            _ => panic!("Expected Set Position"),
        }
    }

    #[test]
    fn test_parse_set_warp_range() {
        let action = parse_line("set warp-range 2500").unwrap().unwrap();
        match action {
            Action::Set {
                target: SetTarget::WarpRange { ly },
            } => assert_eq!(ly, 2500.0),
            _ => panic!("Expected Set WarpRange"),
        }
    }

    #[test]
    fn test_parse_reset_default() {
        let action = parse_line("reset").unwrap().unwrap();
        match action {
            Action::Reset { target } => assert_eq!(target, "all"),
            _ => panic!("Expected Reset"),
        }
    }

    #[test]
    fn test_parse_route_with_biome_and_warp_range() {
        let action = parse_line("route --biome Lush --warp-range 2500")
            .unwrap()
            .unwrap();
        match action {
            Action::Route {
                biome, warp_range, ..
            } => {
                assert_eq!(biome.as_deref(), Some("Lush"));
                assert_eq!(warp_range, Some(2500.0));
            }
            _ => panic!("Expected Route"),
        }
    }

    #[test]
    fn test_parse_route_with_targets() {
        let action = parse_line("route --target \"Alpha Base\" --target \"Beta Base\"")
            .unwrap()
            .unwrap();
        match action {
            Action::Route { targets, .. } => {
                assert_eq!(targets.len(), 2);
                assert_eq!(targets[0], "Alpha Base");
                assert_eq!(targets[1], "Beta Base");
            }
            _ => panic!("Expected Route"),
        }
    }

    #[test]
    fn test_parse_route_round_trip() {
        let action = parse_line("route --biome Lush --round-trip")
            .unwrap()
            .unwrap();
        match action {
            Action::Route { round_trip, .. } => {
                assert!(round_trip);
            }
            _ => panic!("Expected Route"),
        }
    }

    #[test]
    fn test_parse_reset_biome() {
        let action = parse_line("reset biome").unwrap().unwrap();
        match action {
            Action::Reset { target } => assert_eq!(target, "biome"),
            _ => panic!("Expected Reset"),
        }
    }

    #[test]
    fn test_parse_list_galaxies() {
        let action = parse_line("list galaxies").unwrap().unwrap();
        match action {
            Action::List {
                target: ListTarget::Galaxies { galaxy_type },
            } => assert!(galaxy_type.is_none()),
            _ => panic!("Expected List Galaxies"),
        }
    }

    #[test]
    fn test_parse_list_galaxies_with_type() {
        let action = parse_line("list galaxies --type Lush").unwrap().unwrap();
        match action {
            Action::List {
                target: ListTarget::Galaxies { galaxy_type },
            } => assert_eq!(galaxy_type.as_deref(), Some("Lush")),
            _ => panic!("Expected List Galaxies"),
        }
    }

    #[test]
    fn test_parse_list_biomes() {
        let action = parse_line("list biomes").unwrap().unwrap();
        assert!(matches!(
            action,
            Action::List {
                target: ListTarget::Biomes
            }
        ));
    }

    #[test]
    fn test_parse_list_glyphs() {
        let action = parse_line("list glyphs").unwrap().unwrap();
        assert!(matches!(
            action,
            Action::List {
                target: ListTarget::Glyphs
            }
        ));
    }

    #[test]
    fn test_parse_list_bases() {
        let action = parse_line("list bases").unwrap().unwrap();
        assert!(matches!(
            action,
            Action::List {
                target: ListTarget::Bases { .. }
            }
        ));
    }

    #[test]
    fn test_parse_list_bases_with_all() {
        let action = parse_line("list bases --all").unwrap().unwrap();
        match action {
            Action::List {
                target: ListTarget::Bases { all, .. },
            } => assert!(all),
            _ => panic!("Expected List Bases"),
        }
    }

    #[test]
    fn test_parse_list_systems() {
        let action = parse_line("list systems").unwrap().unwrap();
        match action {
            Action::List {
                target: ListTarget::Systems { limit, all },
            } => {
                assert_eq!(limit, 50);
                assert!(!all);
            }
            _ => panic!("Expected List Systems"),
        }
    }

    #[test]
    fn test_parse_list_systems_with_all() {
        let action = parse_line("list systems --all").unwrap().unwrap();
        match action {
            Action::List {
                target: ListTarget::Systems { all, .. },
            } => assert!(all),
            _ => panic!("Expected List Systems"),
        }
    }

    #[test]
    fn test_parse_list_systems_with_limit() {
        let action = parse_line("list systems --limit 10").unwrap().unwrap();
        match action {
            Action::List {
                target: ListTarget::Systems { limit, .. },
            } => assert_eq!(limit, 10),
            _ => panic!("Expected List Systems"),
        }
    }

    #[test]
    fn test_parse_list_terrain_types() {
        let action = parse_line("list terrain-types").unwrap().unwrap();
        assert!(matches!(
            action,
            Action::List {
                target: ListTarget::TerrainTypes
            }
        ));
    }

    #[test]
    fn test_parse_map() {
        let action = parse_line("map").unwrap().unwrap();
        assert!(matches!(action, Action::Map));
    }

    #[test]
    fn test_parse_command_help_shows_subcommand_help() {
        // "find help" should be rewritten to "find --help" and produce help output
        let result = parse_line("find help");
        // clap prints help text and parse_line returns Ok(None)
        assert!(result.unwrap().is_none());
    }

    #[test]
    fn test_parse_command_dash_help_shows_subcommand_help() {
        let result = parse_line("find --help");
        assert!(result.unwrap().is_none());
    }
}