shuvarie 0.2.2

Blazingly fast AI coding TUI for chivalrous people
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
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
pub const TRIGGER_CHARS: [char; 2] = ['/', ':'];

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum CommandAction {
    OpenModelSelect,
    AddProvider,
    OpenSessionPicker,
    OpenTree,
    OpenScenePicker,
    OpenVariantPicker,
    NewSession,
    EditTitle,
    GenTitle,
    Export,
    UndoLastTurn,
    Replay,
    Reload,
    McpServers,
    McpReconnect,
    ToggleSidebar,
    Search,
    Quit,
}

impl CommandAction {
    pub const ALL: [CommandAction; 18] = [
        CommandAction::OpenModelSelect,
        CommandAction::AddProvider,
        CommandAction::OpenSessionPicker,
        CommandAction::OpenTree,
        CommandAction::OpenScenePicker,
        CommandAction::OpenVariantPicker,
        CommandAction::NewSession,
        CommandAction::EditTitle,
        CommandAction::GenTitle,
        CommandAction::Export,
        CommandAction::UndoLastTurn,
        CommandAction::Replay,
        CommandAction::Reload,
        CommandAction::McpServers,
        CommandAction::McpReconnect,
        CommandAction::ToggleSidebar,
        CommandAction::Search,
        CommandAction::Quit,
    ];

    pub fn slash_name(self) -> &'static str {
        match self {
            CommandAction::OpenModelSelect => "model",
            CommandAction::AddProvider => "provider",
            CommandAction::OpenSessionPicker => "sessions",
            CommandAction::OpenTree => "tree",
            CommandAction::OpenScenePicker => "scene",
            CommandAction::OpenVariantPicker => "variant",
            CommandAction::NewSession => "new",
            CommandAction::EditTitle => "title",
            CommandAction::GenTitle => "gen-title",
            CommandAction::Export => "export",
            CommandAction::UndoLastTurn => "undo",
            CommandAction::Replay => "replay",
            CommandAction::Reload => "reload",
            CommandAction::McpServers => "mcp",
            CommandAction::McpReconnect => "mcp-reconnect",
            CommandAction::ToggleSidebar => "sidebar",
            CommandAction::Search => "search",
            CommandAction::Quit => "quit",
        }
    }

    /// Whether the command accepts free-form arguments after its name
    /// (e.g. `/title My title`).
    pub fn takes_args(self) -> bool {
        matches!(
            self,
            CommandAction::EditTitle
                | CommandAction::Export
                | CommandAction::McpReconnect
                | CommandAction::OpenScenePicker
                | CommandAction::OpenVariantPicker
                | CommandAction::Search
        )
    }
}

#[derive(Clone)]
pub struct CommandEntry {
    pub name: String,
    pub description: String,
    pub action: CommandRef,
    pub available: bool,
}

/// What running an entry dispatches to: a built-in UI action or a custom
/// command (a prompt template loaded from `.shuvarie/commands`).
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum CommandRef {
    Builtin(CommandAction),
    Custom {
        /// The command directory name (its slash alias).
        name: String,
        /// The command's `model` frontmatter override
        /// (`<provider_type>/<model>`), passed through to the core for the
        /// turn.
        model: Option<String>,
    },
}

impl CommandRef {
    /// The slash alias this entry answers to: a builtin's slash name, or a
    /// custom command's name — rendered `custom:<name>` when it collides with
    /// a builtin's name (the builtin keeps the plain alias).
    pub fn slash_alias(&self) -> String {
        match self {
            CommandRef::Builtin(action) => action.slash_name().to_string(),
            CommandRef::Custom { name, .. } => {
                if CommandAction::ALL.iter().any(|a| a.slash_name() == name) {
                    format!("custom:{name}")
                } else {
                    name.clone()
                }
            }
        }
    }
}

impl CommandEntry {
    pub fn builtin(name: &'static str, description: &'static str, action: CommandAction) -> Self {
        Self {
            name: name.to_string(),
            description: description.to_string(),
            action: CommandRef::Builtin(action),
            available: true,
        }
    }

    pub fn custom(command: &shuvarie_core::CustomCommand) -> Self {
        Self {
            name: command.title.clone(),
            description: "Custom command".to_string(),
            action: CommandRef::Custom {
                name: command.name.clone(),
                model: command.model.clone(),
            },
            available: true,
        }
    }
}

pub fn default_commands() -> Vec<CommandEntry> {
    vec![
        CommandEntry::builtin(
            "Select model",
            "Pick the active model",
            CommandAction::OpenModelSelect,
        ),
        CommandEntry::builtin(
            "Add provider",
            "Add a new LLM provider",
            CommandAction::AddProvider,
        ),
        CommandEntry::builtin(
            "Switch session",
            "Resume or delete past sessions",
            CommandAction::OpenSessionPicker,
        ),
        CommandEntry::builtin(
            "New session",
            "Start a fresh conversation",
            CommandAction::NewSession,
        ),
        CommandEntry::builtin(
            "Session tree",
            "Walk the tree, fork from a node",
            CommandAction::OpenTree,
        ),
        CommandEntry::builtin(
            "Switch scene",
            "Pick the scene the agent runs under",
            CommandAction::OpenScenePicker,
        ),
        CommandEntry::builtin(
            "Select variant",
            "Pick the model's reasoning effort",
            CommandAction::OpenVariantPicker,
        ),
        CommandEntry::builtin(
            "Edit title",
            "Rename the current session",
            CommandAction::EditTitle,
        ),
        CommandEntry::builtin(
            "Generate title",
            "Draft the session title with the LLM",
            CommandAction::GenTitle,
        ),
        CommandEntry::builtin(
            "Export session",
            "Write the session to a JSON file",
            CommandAction::Export,
        ),
        CommandEntry::builtin(
            "Undo last turn",
            "Fork before the last prompt",
            CommandAction::UndoLastTurn,
        ),
        CommandEntry::builtin(
            "Replay last turn",
            "Fork + re-run the last turn",
            CommandAction::Replay,
        ),
        CommandEntry::builtin(
            "Reload skills",
            "Re-discover skills and commands without a restart",
            CommandAction::Reload,
        ),
        CommandEntry::builtin(
            "MCP servers",
            "Show MCP server states",
            CommandAction::McpServers,
        ),
        CommandEntry::builtin(
            "Reconnect MCP",
            "Reconnect an MCP server",
            CommandAction::McpReconnect,
        ),
        CommandEntry::builtin(
            "Toggle sidebar",
            "Collapse or expand the sidebar",
            CommandAction::ToggleSidebar,
        ),
        CommandEntry::builtin(
            "Search chat",
            "Highlight text in the chat live",
            CommandAction::Search,
        ),
        CommandEntry::builtin("Quit", "Exit the program", CommandAction::Quit),
    ]
}

/// Whether the text starts with a doubled trigger char (`//` or `::`), which
/// escapes the prefix into a literal character.
pub fn is_escaped(text: &str) -> bool {
    let mut chars = text.chars();
    match (chars.next(), chars.next()) {
        (Some(c), Some(d)) => TRIGGER_CHARS.contains(&c) && c == d,
        _ => false,
    }
}

/// Strip one escaped trigger char (`//x` -> `/x`).
pub fn unescape(text: &str) -> &str {
    if is_escaped(text) {
        let skip = text.chars().next().map_or(0, char::len_utf8);
        &text[skip..]
    } else {
        text
    }
}

/// A parsed `<trigger><alias> [args]` submission.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ParsedCommand {
    pub action: CommandAction,
    /// The trimmed remainder after the command name, `Some` only when
    /// non-empty. Commands that take no args (see
    /// [`CommandAction::takes_args`]) never parse with one.
    pub args: Option<String>,
}

/// Parse submitted text as a slash command: the whole (trimmed) text must be
/// of the form `<trigger><alias>` matching a known command
/// (case-insensitive), optionally followed by an argument string for commands
/// that take one. Escaped prefixes (`//`, `::`) never parse.
pub fn parse_command(text: &str) -> Option<ParsedCommand> {
    let text = text.trim();
    let first = text.chars().next()?;
    if !TRIGGER_CHARS.contains(&first) || is_escaped(text) {
        return None;
    }
    let rest = &text[first.len_utf8()..];
    let (alias, args) = match rest.find(char::is_whitespace) {
        Some(i) => (&rest[..i], rest[i..].trim()),
        None => (rest, ""),
    };
    if alias.is_empty() {
        return None;
    }
    let action = CommandAction::ALL
        .iter()
        .copied()
        .find(|a| a.slash_name().eq_ignore_ascii_case(alias))?;
    if !args.is_empty() && !action.takes_args() {
        return None;
    }
    Some(ParsedCommand {
        action,
        args: (!args.is_empty()).then(|| args.to_string()),
    })
}

/// A parsed `/skill:<name> [args]` invocation (also accepted with the `:`
/// trigger: `:skill:<name>`).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SkillInvocation {
    pub name: String,
    pub args: Option<String>,
}

/// Parse submitted text as a skill invocation: `<trigger>skill:<name> [args]`.
/// Escaped prefixes (`//`, `::`) never parse. The first token after `skill:`
/// is the skill name; the rest (trimmed) is the args.
pub fn parse_skill_invocation(text: &str) -> Option<SkillInvocation> {
    let text = text.trim();
    let first = text.chars().next()?;
    if !TRIGGER_CHARS.contains(&first) || is_escaped(text) {
        return None;
    }
    let rest = text[first.len_utf8()..].strip_prefix("skill:")?;
    let (name, args) = match rest.find(char::is_whitespace) {
        Some(i) => (&rest[..i], rest[i..].trim()),
        None => (rest, ""),
    };
    if name.is_empty() {
        return None;
    }
    Some(SkillInvocation {
        name: name.to_string(),
        args: (!args.is_empty()).then(|| args.to_string()),
    })
}

/// A parsed `<trigger><name> [args]` custom-command submission (also accepted
/// in the `custom:`-prefixed form `<trigger>custom:<name> [args]`, which is
/// how a command sharing a builtin's name is invoked).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CustomInvocation {
    pub name: String,
    pub args: Option<String>,
}

/// Whether `name` could be a custom-command name (the loader-validated
/// set: lowercase a-z, 0-9, and hyphens).
fn is_command_name(name: &str) -> bool {
    !name.is_empty()
        && name
            .chars()
            .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-')
}

/// Parse submitted text as a custom-command invocation. Escaped prefixes
/// (`//`, `::`) never parse. A builtin's slash name without the `custom:`
/// prefix is never claimed here — it belongs to the builtin (which
/// [`parse_command`] handled or rejected for its args).
pub fn parse_custom_invocation(text: &str) -> Option<CustomInvocation> {
    let text = text.trim();
    let first = text.chars().next()?;
    if !TRIGGER_CHARS.contains(&first) || is_escaped(text) {
        return None;
    }
    let rest = &text[first.len_utf8()..];
    let (prefixed, rest) = match rest.strip_prefix("custom:") {
        Some(custom) => (true, custom),
        None => (false, rest),
    };
    let (name, args) = match rest.find(char::is_whitespace) {
        Some(i) => (&rest[..i], rest[i..].trim()),
        None => (rest, ""),
    };
    if name.is_empty() || !is_command_name(name) {
        return None;
    }
    if !prefixed && CommandAction::ALL.iter().any(|a| a.slash_name() == name) {
        return None;
    }
    Some(CustomInvocation {
        name: name.to_string(),
        args: (!args.is_empty()).then(|| args.to_string()),
    })
}

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

    #[test]
    fn escaped_prefixes_detected() {
        assert!(is_escaped("//"));
        assert!(is_escaped("//x"));
        assert!(is_escaped("::"));
        assert!(is_escaped("::x"));
        assert!(!is_escaped("/x"));
        assert!(!is_escaped(":x"));
        assert!(!is_escaped("/"));
        assert!(!is_escaped(":"));
        assert!(!is_escaped("x//"));
        assert!(
            is_escaped("// x"),
            "the doubled prefix is the escape sequence"
        );
    }

    #[test]
    fn unescape_strips_one_char() {
        assert_eq!(unescape("//model"), "/model");
        assert_eq!(unescape("::hi"), ":hi");
        assert_eq!(unescape("///x"), "//x");
        assert_eq!(unescape("/model"), "/model");
        assert_eq!(unescape("plain"), "plain");
    }

    #[test]
    fn parse_recognizes_commands() {
        assert_eq!(
            parse_command("/model"),
            Some(ParsedCommand {
                action: CommandAction::OpenModelSelect,
                args: None
            })
        );
        assert_eq!(
            parse_command(":MODEL"),
            Some(ParsedCommand {
                action: CommandAction::OpenModelSelect,
                args: None
            })
        );
        assert_eq!(
            parse_command("/undo"),
            Some(ParsedCommand {
                action: CommandAction::UndoLastTurn,
                args: None
            })
        );
        assert_eq!(
            parse_command("/reload"),
            Some(ParsedCommand {
                action: CommandAction::Reload,
                args: None
            })
        );
        assert_eq!(
            parse_command("  /new  "),
            Some(ParsedCommand {
                action: CommandAction::NewSession,
                args: None
            })
        );
        assert_eq!(
            parse_command(":quit"),
            Some(ParsedCommand {
                action: CommandAction::Quit,
                args: None
            })
        );
        assert_eq!(
            parse_command("/QUIT"),
            Some(ParsedCommand {
                action: CommandAction::Quit,
                args: None
            })
        );
    }

    #[test]
    fn parse_command_with_arguments() {
        assert_eq!(
            parse_command("/title My title"),
            Some(ParsedCommand {
                action: CommandAction::EditTitle,
                args: Some("My title".into())
            })
        );
        assert_eq!(
            parse_command(":TITLE   spaced   out  "),
            Some(ParsedCommand {
                action: CommandAction::EditTitle,
                args: Some("spaced   out".into())
            })
        );
        assert_eq!(
            parse_command("/title"),
            Some(ParsedCommand {
                action: CommandAction::EditTitle,
                args: None
            })
        );
        assert_eq!(
            parse_command("/title   "),
            Some(ParsedCommand {
                action: CommandAction::EditTitle,
                args: None
            }),
            "whitespace-only remainder is no args"
        );
        assert_eq!(
            parse_command("/variant"),
            Some(ParsedCommand {
                action: CommandAction::OpenVariantPicker,
                args: None
            })
        );
        assert_eq!(
            parse_command("/variant   "),
            Some(ParsedCommand {
                action: CommandAction::OpenVariantPicker,
                args: None
            }),
            "whitespace-only remainder is no args"
        );
        assert_eq!(
            parse_command("/variant HIGH"),
            Some(ParsedCommand {
                action: CommandAction::OpenVariantPicker,
                args: Some("HIGH".into())
            })
        );
    }

    #[test]
    fn parse_mcp_commands() {
        assert_eq!(
            parse_command("/mcp"),
            Some(ParsedCommand {
                action: CommandAction::McpServers,
                args: None
            })
        );
        assert_eq!(
            parse_command("/MCP"),
            Some(ParsedCommand {
                action: CommandAction::McpServers,
                args: None
            })
        );
        assert_eq!(parse_command("/mcp extra"), None, "/mcp takes no arguments");
        assert_eq!(
            parse_command("/mcp-reconnect github"),
            Some(ParsedCommand {
                action: CommandAction::McpReconnect,
                args: Some("github".into())
            })
        );
        assert_eq!(
            parse_command("/mcp-reconnect"),
            Some(ParsedCommand {
                action: CommandAction::McpReconnect,
                args: None
            })
        );
    }

    #[test]
    fn parse_rejects_non_commands() {
        assert_eq!(parse_command("//model"), None);
        assert_eq!(parse_command("::model"), None);
        assert_eq!(parse_command("/unknown"), None);
        assert_eq!(
            parse_command("/model x"),
            None,
            "commands without args never parse with one"
        );
        assert_eq!(parse_command("/"), None);
        assert_eq!(parse_command(":"), None);
        assert_eq!(parse_command("hello"), None);
        assert_eq!(parse_command(""), None);
        assert_eq!(parse_command("/undo now"), None);
        assert_eq!(parse_command(":/undo"), None);
    }

    #[test]
    fn parse_recognizes_search_command() {
        assert_eq!(
            parse_command("/search"),
            Some(ParsedCommand {
                action: CommandAction::Search,
                args: None
            })
        );
        assert_eq!(
            parse_command(":SEARCH foo bar"),
            Some(ParsedCommand {
                action: CommandAction::Search,
                args: Some("foo bar".into())
            })
        );
    }

    #[test]
    fn parse_recognizes_export_with_optional_path() {
        assert_eq!(
            parse_command("/export"),
            Some(ParsedCommand {
                action: CommandAction::Export,
                args: None
            })
        );
        assert_eq!(
            parse_command("/EXPORT backups/out.json"),
            Some(ParsedCommand {
                action: CommandAction::Export,
                args: Some("backups/out.json".into())
            })
        );
    }

    #[test]
    fn parse_recognizes_gen_title_command() {
        assert_eq!(
            parse_command("/gen-title"),
            Some(ParsedCommand {
                action: CommandAction::GenTitle,
                args: None
            })
        );
        assert_eq!(
            parse_command(":GEN-TITLE"),
            Some(ParsedCommand {
                action: CommandAction::GenTitle,
                args: None
            })
        );
        // The command takes no arguments, so it never parses with one.
        assert_eq!(parse_command("/gen-title now"), None);
    }

    #[test]
    fn parse_skill_invocations() {
        assert_eq!(
            parse_skill_invocation("/skill:tokio"),
            Some(SkillInvocation {
                name: "tokio".into(),
                args: None
            })
        );
        assert_eq!(
            parse_skill_invocation("/skill:tokio explain buffering"),
            Some(SkillInvocation {
                name: "tokio".into(),
                args: Some("explain buffering".into())
            })
        );
        assert_eq!(
            parse_skill_invocation(":skill:tokio"),
            Some(SkillInvocation {
                name: "tokio".into(),
                args: None
            })
        );
        assert_eq!(
            parse_skill_invocation("  /skill:tokio  "),
            Some(SkillInvocation {
                name: "tokio".into(),
                args: None
            })
        );
    }

    #[test]
    fn parse_skill_invocation_rejects() {
        assert_eq!(parse_skill_invocation("//skill:tokio"), None);
        assert_eq!(parse_skill_invocation("::skill:tokio"), None);
        assert_eq!(parse_skill_invocation("/skill:"), None);
        assert_eq!(parse_skill_invocation("/skill: x"), None);
        assert_eq!(parse_skill_invocation("/skills:tokio"), None);
        assert_eq!(parse_skill_invocation("skill:tokio"), None);
        assert_eq!(parse_skill_invocation("/undo"), None);
        assert_eq!(parse_skill_invocation("hello"), None);
    }

    #[test]
    fn parse_custom_invocations() {
        assert_eq!(
            parse_custom_invocation("/commit"),
            Some(CustomInvocation {
                name: "commit".into(),
                args: None
            })
        );
        assert_eq!(
            parse_custom_invocation(":commit fix the tests"),
            Some(CustomInvocation {
                name: "commit".into(),
                args: Some("fix the tests".into())
            })
        );
        assert_eq!(
            parse_custom_invocation("/commit fix the tests"),
            Some(CustomInvocation {
                name: "commit".into(),
                args: Some("fix the tests".into())
            })
        );
        assert_eq!(
            parse_custom_invocation("  /custom:model  "),
            Some(CustomInvocation {
                name: "model".into(),
                args: None
            })
        );
    }

    #[test]
    fn parse_custom_invocation_rejects() {
        assert_eq!(parse_custom_invocation("//commit"), None);
        assert_eq!(parse_custom_invocation("::commit"), None);
        assert_eq!(parse_custom_invocation("/custom:"), None);
        // Invalid name charset: falls through to a literal send.
        assert_eq!(parse_custom_invocation("/usr/bin/ls"), None);
        assert_eq!(parse_custom_invocation("/Commit"), None);
        assert_eq!(parse_custom_invocation("/skill:x"), None);
        assert_eq!(parse_custom_invocation("hello"), None);
    }

    #[test]
    fn slash_alias_collisions_render_as_custom() {
        assert_eq!(
            CommandRef::Custom {
                name: "commit".into(),
                model: None
            }
            .slash_alias(),
            "commit"
        );
        assert_eq!(
            CommandRef::Custom {
                name: "model".into(),
                model: None
            }
            .slash_alias(),
            "custom:model"
        );
        assert_eq!(
            CommandRef::Builtin(CommandAction::OpenModelSelect).slash_alias(),
            "model"
        );
    }
}