shuvarie 0.1.0

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
pub const TRIGGER_CHARS: [char; 2] = ['/', ':'];

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

impl CommandAction {
    pub const ALL: [CommandAction; 14] = [
        CommandAction::OpenModelSelect,
        CommandAction::AddProvider,
        CommandAction::OpenSessionPicker,
        CommandAction::OpenTree,
        CommandAction::OpenScenePicker,
        CommandAction::OpenVariantPicker,
        CommandAction::NewSession,
        CommandAction::EditTitle,
        CommandAction::Export,
        CommandAction::UndoLastTurn,
        CommandAction::Replay,
        CommandAction::Reload,
        CommandAction::ToggleSidebar,
        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::Export => "export",
            CommandAction::UndoLastTurn => "undo",
            CommandAction::Replay => "replay",
            CommandAction::Reload => "reload",
            CommandAction::ToggleSidebar => "sidebar",
            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::OpenScenePicker
                | CommandAction::OpenVariantPicker
        )
    }
}

#[derive(Clone)]
pub struct CommandEntry {
    pub name: &'static str,
    pub description: &'static str,
    pub action: CommandAction,
    pub available: bool,
}

pub fn default_commands() -> Vec<CommandEntry> {
    vec![
        CommandEntry {
            name: "Select model",
            description: "Pick the active model",
            action: CommandAction::OpenModelSelect,
            available: true,
        },
        CommandEntry {
            name: "Add provider",
            description: "Add a new LLM provider",
            action: CommandAction::AddProvider,
            available: true,
        },
        CommandEntry {
            name: "Switch session",
            description: "Resume or delete past sessions",
            action: CommandAction::OpenSessionPicker,
            available: true,
        },
        CommandEntry {
            name: "New session",
            description: "Start a fresh conversation",
            action: CommandAction::NewSession,
            available: true,
        },
        CommandEntry {
            name: "Session tree",
            description: "Walk the tree, fork from a node",
            action: CommandAction::OpenTree,
            available: true,
        },
        CommandEntry {
            name: "Switch scene",
            description: "Pick the scene the agent runs under",
            action: CommandAction::OpenScenePicker,
            available: true,
        },
        CommandEntry {
            name: "Select variant",
            description: "Pick the model's reasoning effort",
            action: CommandAction::OpenVariantPicker,
            available: true,
        },
        CommandEntry {
            name: "Edit title",
            description: "Rename the current session",
            action: CommandAction::EditTitle,
            available: true,
        },
        CommandEntry {
            name: "Export session",
            description: "Write the session to a JSON file",
            action: CommandAction::Export,
            available: true,
        },
        CommandEntry {
            name: "Undo last turn",
            description: "Fork before the last prompt",
            action: CommandAction::UndoLastTurn,
            available: true,
        },
        CommandEntry {
            name: "Replay last turn",
            description: "Fork + re-run the last turn",
            action: CommandAction::Replay,
            available: true,
        },
        CommandEntry {
            name: "Reload skills",
            description: "Re-discover skills without a restart",
            action: CommandAction::Reload,
            available: true,
        },
        CommandEntry {
            name: "Toggle sidebar",
            description: "Collapse or expand the sidebar",
            action: CommandAction::ToggleSidebar,
            available: true,
        },
        CommandEntry {
            name: "Quit",
            description: "Exit the program",
            action: CommandAction::Quit,
            available: true,
        },
    ]
}

/// 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()),
    })
}

#[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_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_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_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);
    }
}