1#[derive(Debug, Clone, Copy, PartialEq, Eq)]
20pub enum Front {
21 Repl,
23 Tui,
25 Web,
27}
28
29impl Front {
30 pub fn place(self) -> &'static str {
32 match self {
33 Front::Repl => "the plain REPL",
34 Front::Tui => "the full-screen interface",
35 Front::Web => "the dashboard",
36 }
37 }
38
39 pub fn enter(self) -> &'static str {
41 match self {
42 Front::Repl => "run eclipse --plain",
43 Front::Tui => "run eclipse without --plain",
44 Front::Web => "run eclipse-web",
45 }
46 }
47
48 pub fn keyboard(self) -> bool {
51 matches!(self, Front::Tui | Front::Repl)
52 }
53}
54
55use Front::{Repl, Tui, Web};
59
60#[derive(Debug, Clone, Copy, PartialEq, Eq)]
66pub enum Args {
67 None,
70 Shown(&'static str),
72 Unshown,
74}
75
76impl Args {
77 pub fn takes(self) -> bool {
80 !matches!(self, Args::None)
81 }
82}
83
84#[derive(Debug, PartialEq, Eq)]
85pub struct Command {
86 pub name: &'static str,
88 pub aliases: &'static [&'static str],
90 pub args: Args,
92 pub help: &'static str,
94 pub fronts: &'static [Front],
99}
100
101pub const COMMANDS: &[Command] = &[
106 Command {
107 name: "/new",
108 aliases: &[],
109 args: Args::None,
110 help: "start a new session",
111 fronts: &[Tui, Repl, Web],
112 },
113 Command {
114 name: "/resume",
115 aliases: &["/sessions"],
116 args: Args::None,
117 help: "open a stored session (↑↓, enter)",
118 fronts: &[Tui],
119 },
120 Command {
121 name: "/retry",
122 aliases: &[],
123 args: Args::None,
124 help: "run the last question again, without asking it twice",
125 fronts: &[Tui, Repl],
126 },
127 Command {
128 name: "/bg",
129 aliases: &[],
130 args: Args::Shown("<prompt>"),
131 help: "start it as a task that keeps running after this prompt returns",
132 fronts: &[Tui, Repl],
133 },
134 Command {
135 name: "/tasks",
136 aliases: &[],
137 args: Args::Unshown,
138 help: "the background runs: what each is doing, and how it ended",
139 fronts: &[Tui, Repl],
140 },
141 Command {
142 name: "/model",
143 aliases: &[],
144 args: Args::Unshown,
145 help: "pick a model (↑↓, enter)",
146 fronts: &[Tui, Web],
147 },
148 Command {
149 name: "/id",
150 aliases: &[],
151 args: Args::None,
152 help: "show the current session id",
153 fronts: &[Tui, Repl, Web],
154 },
155 Command {
156 name: "/profile",
157 aliases: &[],
158 args: Args::Unshown,
159 help: "which profile, from which file, under which home (`/profile list` for all)",
160 fronts: &[Tui, Repl],
161 },
162 Command {
163 name: "/gateway",
164 aliases: &["/platforms"],
165 args: Args::None,
166 help: "what the gateway is doing: its state, its age, its port and its jobs",
167 fronts: &[Tui, Repl],
168 },
169 Command {
170 name: "/goal",
171 aliases: &[],
172 args: Args::Shown("<text>"),
173 help: "a standing goal, worked on turn by turn until the judge says it is done",
174 fronts: &[Tui, Repl, Web],
177 },
178 Command {
179 name: "/loop",
180 aliases: &[],
181 args: Args::Shown("<interval> <prompt>"),
182 help: "send this prompt back into this session every interval (`status|pause|resume|stop`)",
183 fronts: &[Tui, Repl, Web],
187 },
188 Command {
189 name: "/cron",
190 aliases: &[],
191 args: Args::Unshown,
192 help: "the scheduled jobs: the table, `run <name>` and `logs <name> [n]`",
193 fronts: &[Tui, Repl, Web],
194 },
195 Command {
196 name: "/reasoning",
197 aliases: &[],
198 args: Args::Unshown,
199 help: "how much it thinks, and how much of it is drawn (`/reasoning high`)",
200 fronts: &[Tui, Repl, Web],
201 },
202 Command {
203 name: "/settings",
204 aliases: &[],
205 args: Args::None,
206 help: "the keys this build reads, and what each is set to",
207 fronts: &[Tui, Repl, Web],
208 },
209 Command {
210 name: "/set",
211 aliases: &[],
212 args: Args::Shown("<key> <value>"),
213 help: "write one setting; the next run uses it",
214 fronts: &[Tui, Repl, Web],
215 },
216 Command {
217 name: "/yolo",
218 aliases: &[],
219 args: Args::Unshown,
220 help: "stop asking before every tool call, until `/yolo off` (this session only)",
221 fronts: &[Tui, Repl, Web],
227 },
228 Command {
229 name: "/status",
230 aliases: &[],
231 args: Args::None,
232 help: "tokens, cache, timings for this process",
233 fronts: &[Tui, Repl, Web],
234 },
235 Command {
236 name: "/compress",
237 aliases: &["/compact"],
238 args: Args::None,
239 help: "replace this session's older turns with the compiled handoff now",
240 fronts: &[Tui, Repl, Web],
241 },
242 Command {
243 name: "/archive",
244 aliases: &[],
245 args: Args::Unshown,
246 help: "file this session away — out of the list, still in the search (`list`, `off`)",
247 fronts: &[Tui, Repl, Web],
248 },
249 Command {
250 name: "/clear",
251 aliases: &[],
252 args: Args::None,
253 help: "clear the transcript",
254 fronts: &[Tui],
255 },
256 Command {
257 name: "/help",
258 aliases: &[],
259 args: Args::None,
260 help: "list the commands",
261 fronts: &[Tui, Repl, Web],
262 },
263 Command {
264 name: "/exit",
265 aliases: &["/quit"],
266 args: Args::None,
267 help: "quit",
268 fronts: &[Tui, Repl],
269 },
270];
271
272impl Command {
273 pub fn label(&self) -> String {
276 match self.args {
277 Args::Shown(args) => format!("{} {args}", self.name),
278 Args::None | Args::Unshown => self.name.to_string(),
279 }
280 }
281
282 pub fn spelling(&self, prefix: &str) -> &'static str {
285 if self.name.starts_with(prefix) {
286 return self.name;
287 }
288 self.aliases
289 .iter()
290 .copied()
291 .find(|a| a.starts_with(prefix))
292 .unwrap_or(self.name)
293 }
294
295 pub fn fill(&self, prefix: &str) -> String {
298 let word = self.spelling(prefix);
299 if self.args.takes() {
300 format!("{word} ")
301 } else {
302 word.to_string()
303 }
304 }
305
306 pub fn serves(&self, viewer: Front) -> bool {
308 self.fronts.contains(&viewer)
309 }
310
311 pub fn unavailable_in(&self, here: Front) -> String {
317 let elsewhere: Vec<Front> = self.fronts.iter().copied().filter(|f| *f != here).collect();
318 let places: Vec<&str> = elsewhere.iter().map(|f| f.place()).collect();
319 let how = elsewhere
320 .iter()
321 .find(|f| f.keyboard())
322 .or_else(|| elsewhere.first())
323 .map_or("", |f| f.enter());
324 let list = match places.split_last() {
325 Some((last, [])) => (*last).to_string(),
326 Some((last, rest)) => format!("{} and {last}", rest.join(", ")),
327 None => "no interface".to_string(),
328 };
329 if how.is_empty() {
330 format!("{} is only in {list}", self.name)
331 } else {
332 format!("{} is only in {list} ({how})", self.name)
333 }
334 }
335}
336
337pub fn lookup(word: &str) -> Option<&'static Command> {
339 COMMANDS
340 .iter()
341 .find(|c| c.name == word || c.aliases.contains(&word))
342}
343
344pub fn matching(prefix: &str, front: Front) -> Vec<&'static Command> {
346 COMMANDS
347 .iter()
348 .filter(|c| c.serves(front))
349 .filter(|c| c.name.starts_with(prefix) || c.aliases.iter().any(|a| a.starts_with(prefix)))
350 .collect()
351}
352
353#[derive(Debug, PartialEq, Eq)]
354pub enum Completion {
355 Unique(&'static Command),
356 Several(Vec<&'static Command>),
357 None,
358}
359
360pub fn is_command_word(line: &str) -> bool {
366 line.starts_with('/') && !line.contains(char::is_whitespace)
367}
368
369pub fn complete(line: &str, front: Front) -> Completion {
373 if !line.starts_with('/') || line.contains(char::is_whitespace) {
374 return Completion::None;
375 }
376 let mut found = matching(line, front);
377 match found.len() {
378 0 => Completion::None,
379 1 => Completion::Unique(found.remove(0)),
380 _ => Completion::Several(found),
381 }
382}
383
384#[derive(Debug, PartialEq, Eq)]
386pub enum Parsed<'a> {
387 Run(&'static Command, &'a str),
389 Elsewhere(&'static Command),
391 Unknown(&'a str),
393}
394
395pub fn parse(line: &str, front: Front) -> Parsed<'_> {
396 let line = line.trim();
397 let (word, rest) = match line.split_once(char::is_whitespace) {
398 Some((word, rest)) => (word, rest.trim()),
399 None => (line, ""),
400 };
401 match lookup(word) {
402 None => Parsed::Unknown(line),
403 Some(c) if !c.serves(front) => Parsed::Elsewhere(c),
404 Some(c) if !rest.is_empty() && !c.args.takes() => Parsed::Unknown(line),
405 Some(c) => Parsed::Run(c, rest),
406 }
407}
408
409pub fn help(front: Front) -> String {
411 let shown: Vec<&Command> = COMMANDS.iter().filter(|c| c.serves(front)).collect();
412 let width = shown
413 .iter()
414 .map(|c| c.label().chars().count())
415 .max()
416 .unwrap_or(0)
417 .max("!command".len());
418 let mut lines: Vec<String> = shown
419 .iter()
420 .map(|c| {
421 let also = if c.aliases.is_empty() {
422 String::new()
423 } else {
424 format!(" (also {})", c.aliases.join(", "))
425 };
426 format!("{:<width$} {}{also}", c.label(), c.help)
427 })
428 .collect();
429 if front.keyboard() {
436 lines.push(format!(
437 "{:<width$} run a shell command here: no turn, no tokens, nothing added to the session",
438 "!command"
439 ));
440 }
441 lines.join("\n")
442}
443
444#[cfg(test)]
445mod tests {
446 use super::*;
447
448 fn names(found: &[&Command]) -> Vec<&'static str> {
449 found.iter().map(|c| c.name).collect()
450 }
451
452 #[test]
457 fn an_unshown_argument_still_parses_but_is_not_in_the_table() {
458 let help = help(Front::Tui);
459 let model_row = help
460 .lines()
461 .find(|l| l.starts_with("/model"))
462 .unwrap_or_default();
463 assert!(
464 model_row.contains("pick a model (↑↓, enter)"),
465 "the row says what happens, in /resume's shape: {model_row:?}"
466 );
467 assert!(
468 !help.contains("[number|name]"),
469 "and no longer teaches the syntax the picker replaced:\n{help}"
470 );
471 assert!(
472 help.contains("/set <key> <value>"),
473 "a command whose arguments are the way in still spells them:\n{help}"
474 );
475
476 match parse("/model 3", Front::Tui) {
479 Parsed::Run(c, rest) => {
480 assert_eq!(c.name, "/model");
481 assert_eq!(rest, "3");
482 }
483 other => panic!("/model 3 must still run: {other:?}"),
484 }
485 assert!(matches!(
486 parse("/new something", Front::Tui),
487 Parsed::Unknown(_)
488 ));
489 assert!(matches!(parse("/model", Front::Tui), Parsed::Run(..)));
490 let model = lookup("/model").expect("in the table");
492 assert_eq!(model.fill("/mo"), "/model ");
493 assert_eq!(model.label(), "/model", "and the label is just its name");
494 }
495
496 #[test]
498 fn a_command_word_is_told_apart_from_prose_and_from_an_argument() {
499 assert!(is_command_word("/"));
500 assert!(is_command_word("/cr"));
501 assert!(
502 is_command_word("/zzz"),
503 "a word with no match is still a word"
504 );
505 assert!(!is_command_word(""));
506 assert!(!is_command_word("hello"));
507 assert!(!is_command_word("/cron brief"), "an argument is not a word");
508 assert!(!is_command_word("/cron "), "a trailing space ends the word");
509 assert!(matching("/zzz", Front::Tui).is_empty());
511 let served = COMMANDS.iter().filter(|c| c.serves(Front::Tui)).count();
512 assert_eq!(matching("/", Front::Tui).len(), served);
513 }
514
515 #[test]
516 fn every_word_in_the_table_is_unique() {
517 let mut words: Vec<&str> = COMMANDS
518 .iter()
519 .flat_map(|c| std::iter::once(c.name).chain(c.aliases.iter().copied()))
520 .collect();
521 let all = words.len();
522 words.sort_unstable();
523 words.dedup();
524 assert_eq!(words.len(), all, "a name or alias is listed twice");
525 assert!(words.iter().all(|w| w.starts_with('/')));
526 }
527
528 #[test]
529 fn lookup_finds_a_name_or_an_alias_exactly() {
530 assert_eq!(lookup("/resume").map(|c| c.name), Some("/resume"));
531 assert_eq!(lookup("/sessions").map(|c| c.name), Some("/resume"));
532 assert_eq!(lookup("/quit").map(|c| c.name), Some("/exit"));
533 assert!(lookup("/re").is_none(), "a prefix is not a command");
534 assert!(lookup("/NEW").is_none());
535 assert!(lookup("new").is_none());
536 }
537
538 #[test]
539 fn matching_lists_names_and_aliases_in_table_order() {
540 assert_eq!(
541 names(&matching("/s", Front::Tui)),
542 ["/resume", "/settings", "/set", "/status"]
543 );
544 assert_eq!(names(&matching("/ses", Front::Tui)), ["/resume"]);
545 assert_eq!(names(&matching("/qu", Front::Tui)), ["/exit"]);
546 assert_eq!(
547 names(&matching("/", Front::Tui)),
548 [
549 "/new",
550 "/resume",
551 "/retry",
552 "/bg",
553 "/tasks",
554 "/model",
555 "/id",
556 "/profile",
557 "/gateway",
558 "/goal",
559 "/loop",
560 "/cron",
561 "/reasoning",
562 "/settings",
563 "/set",
564 "/yolo",
565 "/status",
566 "/compress",
567 "/archive",
568 "/clear",
569 "/help",
570 "/exit"
571 ]
572 );
573 assert!(matching("/zzz", Front::Tui).is_empty());
574 }
575
576 #[test]
577 fn matching_only_offers_what_the_front_end_has() {
578 assert_eq!(
579 names(&matching("/s", Front::Repl)),
580 ["/settings", "/set", "/status"]
581 );
582 assert_eq!(
583 names(&matching("/", Front::Repl)),
584 [
585 "/new",
586 "/retry",
587 "/bg",
588 "/tasks",
589 "/id",
590 "/profile",
591 "/gateway",
592 "/goal",
593 "/loop",
594 "/cron",
595 "/reasoning",
596 "/settings",
597 "/set",
598 "/yolo",
599 "/status",
600 "/compress",
601 "/archive",
602 "/help",
603 "/exit"
604 ]
605 );
606 assert!(matching("/cl", Front::Repl).is_empty());
607 assert_eq!(names(&matching("/cl", Front::Tui)), ["/clear"]);
608 }
609
610 #[test]
611 fn complete_is_unique_several_or_none_by_how_many_match() {
612 assert_eq!(
613 complete("/ne", Front::Repl),
614 Completion::Unique(&COMMANDS[0])
615 );
616 match complete("/s", Front::Tui) {
617 Completion::Several(found) => {
618 assert_eq!(names(&found), ["/resume", "/settings", "/set", "/status"])
619 }
620 other => panic!("expected several, got {other:?}"),
621 }
622 assert_eq!(complete("/zzz", Front::Tui), Completion::None);
623 assert!(matches!(complete("/", Front::Tui), Completion::Several(_)));
624 }
625
626 #[test]
627 fn complete_only_answers_while_the_command_word_is_being_typed() {
628 for line in [
629 "",
630 "hello",
631 "hello /ne",
632 " /ne",
633 "/new ",
634 "/model gem",
635 "/ne w",
636 ] {
637 assert_eq!(complete(line, Front::Tui), Completion::None, "{line:?}");
638 }
639 }
640
641 #[test]
642 fn an_alias_completes_to_the_alias_and_an_argument_command_gets_a_space() {
643 let resume = lookup("/resume").unwrap();
644 assert_eq!(resume.fill("/ses"), "/sessions");
645 assert_eq!(resume.fill("/re"), "/resume");
646 assert_eq!(resume.fill("/"), "/resume");
647 assert_eq!(lookup("/model").unwrap().fill("/mo"), "/model ");
648 assert_eq!(lookup("/exit").unwrap().fill("/qu"), "/quit");
649 assert_eq!(lookup("/new").unwrap().fill("/ne"), "/new");
650 }
651
652 #[test]
653 fn help_has_one_aligned_line_per_command_the_front_end_has() {
654 let tui = help(Front::Tui);
655 assert_eq!(tui.lines().count(), COMMANDS.len() + 1);
658 assert!(tui.contains("!command"), "{tui}");
659 assert!(
660 tui.lines().last().unwrap().starts_with("!command"),
661 "named last, where it is not mistaken for something completable: {tui}"
662 );
663 assert!(tui.contains("/resume"), "{tui}");
664 assert!(tui.contains("(also /sessions)"), "{tui}");
665 assert!(tui.contains("(also /quit)"), "{tui}");
666 let col = |l: &str, needle: &str| l.find(needle);
668 assert_eq!(
669 col(tui.lines().nth(1).unwrap_or(""), "open a stored"),
670 col(tui.lines().nth(5).unwrap_or(""), "pick a model")
671 );
672 assert!(tui.lines().all(|l| l == l.trim_end()));
673
674 let repl = help(Front::Repl);
675 assert_eq!(
676 repl.lines()
677 .map(|l| l.split_whitespace().next().unwrap_or(""))
678 .collect::<Vec<_>>(),
679 [
680 "/new",
681 "/retry",
682 "/bg",
683 "/tasks",
684 "/id",
685 "/profile",
686 "/gateway",
687 "/goal",
688 "/loop",
689 "/cron",
690 "/reasoning",
691 "/settings",
692 "/set",
693 "/yolo",
694 "/status",
695 "/compress",
696 "/archive",
697 "/help",
698 "/exit",
699 "!command"
702 ]
703 );
704 for tui_only in ["/clear", "/resume", "/model"] {
705 assert!(!repl.contains(tui_only), "{repl}");
706 }
707 }
708
709 #[test]
710 fn parse_resolves_aliases_and_separates_the_other_front_ends_commands() {
711 assert_eq!(
712 parse("/sessions", Front::Tui),
713 Parsed::Run(lookup("/resume").unwrap(), "")
714 );
715 assert_eq!(
716 parse(" /model gemma ", Front::Tui),
717 Parsed::Run(lookup("/model").unwrap(), "gemma")
718 );
719 assert_eq!(
720 parse("/clear", Front::Repl),
721 Parsed::Elsewhere(lookup("/clear").unwrap())
722 );
723 assert_eq!(parse("/nope", Front::Tui), Parsed::Unknown("/nope"));
724 assert_eq!(parse("/new now", Front::Tui), Parsed::Unknown("/new now"));
725 assert_eq!(parse("/", Front::Tui), Parsed::Unknown("/"));
726 }
727
728 #[test]
730 fn every_command_is_served_somewhere_and_listed_once() {
731 for c in COMMANDS {
732 assert!(
733 !c.fronts.is_empty(),
734 "{} is in the table with no front end to type it in",
735 c.name
736 );
737 let mut seen = c.fronts.to_vec();
738 seen.sort_by_key(|f| format!("{f:?}"));
739 let before = seen.len();
740 seen.dedup();
741 assert_eq!(before, seen.len(), "{} names a front twice", c.name);
742 }
743 }
744
745 #[test]
749 fn the_dashboards_verbs_are_a_strict_subset_of_the_terminals() {
750 let web: Vec<&str> = COMMANDS
751 .iter()
752 .filter(|c| c.serves(Front::Web))
753 .map(|c| c.name)
754 .collect();
755 let terminal: Vec<&str> = COMMANDS
756 .iter()
757 .filter(|c| c.serves(Front::Repl) || c.serves(Front::Tui))
758 .map(|c| c.name)
759 .collect();
760 assert!(
761 web.iter().all(|n| terminal.contains(n)),
762 "a command only the dashboard has: {web:?}"
763 );
764 assert!(
765 web.len() < terminal.len(),
766 "the web set is not a subset anyone has to think about: {web:?}"
767 );
768 assert_eq!(
773 web,
774 [
775 "/new",
776 "/model",
777 "/id",
778 "/goal",
779 "/loop",
780 "/cron",
781 "/reasoning",
782 "/settings",
783 "/set",
784 "/yolo",
785 "/status",
786 "/compress",
787 "/archive",
788 "/help"
789 ]
790 );
791 assert!(
792 !lookup("/resume").unwrap().serves(Front::Web),
793 "opening a stored session is the sidebar, not a line to type"
794 );
795 assert!(lookup("/yolo").unwrap().serves(Front::Web));
799 }
800
801 #[test]
802 fn an_unavailable_command_says_where_it_is() {
803 let said = lookup("/clear").unwrap().unavailable_in(Front::Repl);
804 assert!(
805 said.contains("/clear") && said.contains("full-screen"),
806 "{said}"
807 );
808 let bg = lookup("/bg").unwrap().unavailable_in(Front::Web);
811 assert!(
812 bg.contains("only in the full-screen interface and the plain REPL"),
813 "{bg}"
814 );
815 assert!(bg.contains("run eclipse without --plain"), "{bg}");
816 let resume = lookup("/resume").unwrap().unavailable_in(Front::Web);
819 assert!(
820 resume.contains("only in the full-screen interface"),
821 "{resume}"
822 );
823 assert!(resume.contains("run eclipse without --plain"), "{resume}");
824 }
825}