Skip to main content

adk_surface/tui/
commands.rs

1//! Slash commands an embedder adds to the terminal, and completing their names in the message
2//! box (spec 3.3 §5.2).
3
4use std::fmt;
5use std::sync::Arc;
6
7use async_trait::async_trait;
8
9/// A slash command the terminal runs for its embedder: `/name args` in the message box runs
10/// it, and what it returns is shown in a pane (spec 3.3 §5.2).
11///
12/// `adk-rust` adds the harness REPL's commands this way (`/todos`, `/rules`, `/memory`,
13/// `/hooks`, ...), so the full screen runs the same code as the REPL, in process or on a
14/// kernel. The terminal's own commands (`/help`, `/today`, `/permissions`, `/mode`,
15/// `/session`, `/stop`, `/resume`, `/quit`, `/exit`) take precedence over an added command of
16/// the same name; an added `mode` or `session` answers the bare `/mode` and `/session`, which
17/// show the mode and the session. What a command returns is shown as plain text, every
18/// control character escaped (S-I9).
19///
20/// # Example
21///
22/// ```rust
23/// use adk_surface::tui::{CommandContext, TerminalCommand};
24/// use async_trait::async_trait;
25///
26/// struct Uptime;
27///
28/// #[async_trait]
29/// impl TerminalCommand for Uptime {
30///     fn name(&self) -> &str {
31///         "uptime"
32///     }
33///
34///     fn description(&self) -> &str {
35///         "How long the kernel has run"
36///     }
37///
38///     async fn run(&self, _args: &str, context: &CommandContext) -> adk_core::Result<String> {
39///         Ok(format!("Up 3 hours; this thread is {}", context.session_id))
40///     }
41/// }
42/// ```
43#[async_trait]
44pub trait TerminalCommand: Send + Sync {
45    /// The name typed after the slash: `todos` for `/todos`.
46    fn name(&self) -> &str;
47
48    /// One line shown next to the name while completing and in `/help`.
49    fn description(&self) -> &str;
50
51    /// Runs the command with the text after its name, trimmed, in the session the terminal
52    /// shows, and returns what to show.
53    ///
54    /// # Errors
55    ///
56    /// An error is shown in the pane in place of the output, and the terminal carries on.
57    async fn run(&self, args: &str, context: &CommandContext) -> adk_core::Result<String>;
58}
59
60/// Where a [`TerminalCommand`] runs: the session whose thread the terminal shows (spec 3.3
61/// §5.2), which changes with `Tab` and `/session`.
62///
63/// # Example
64///
65/// ```rust
66/// use adk_surface::tui::CommandContext;
67///
68/// assert_eq!(CommandContext::new("s1").session_id, "s1");
69/// ```
70#[derive(Debug, Clone, PartialEq, Eq)]
71#[non_exhaustive]
72pub struct CommandContext {
73    /// The session the terminal shows.
74    pub session_id: String,
75}
76
77impl CommandContext {
78    /// The context of a command run while `session_id` is shown.
79    pub fn new(session_id: impl Into<String>) -> Self {
80        Self { session_id: session_id.into() }
81    }
82}
83
84/// The terminal's own commands, in `/help` order: they win over an added command of the
85/// same name.
86pub(crate) const BUILT_IN: &[(&str, &str)] = &[
87    ("help", "Keys and commands"),
88    ("today", "Today: while you were away"),
89    ("permissions", "Permissions: what your agents can do"),
90    ("agents", "Your agents"),
91    ("mode", "Show or set the mode: just look, suggest, ask first or go ahead"),
92    ("session", "This session; /session new or /session ID opens another"),
93    ("stop", "Stop all"),
94    ("resume", "Resume all"),
95    ("quit", "Leave; a kernel's agents carry on"),
96    ("exit", "Leave; a kernel's agents carry on"),
97];
98
99/// The heading `/help` lists the screen actions under (spec 3.3 §2 item 7).
100pub(crate) const ON_YOUR_SCREENS: &str = "On your screens";
101
102/// The screen actions an embedder may add, by name, with how to use each and a second line:
103/// `/help` lists them under [`ON_YOUR_SCREENS`] (spec 3.3 §5.2).
104const SCREEN_ACTIONS: &[(&str, &str, &str)] =
105    &[("snooze", "<title> [tomorrow]", "an hour later, or the same time tomorrow")];
106
107/// `/name args` when `text` is a screen action typed as a message, such as `/snooze News digest`.
108pub(crate) fn screen_action(text: &str) -> Option<(&str, &str)> {
109    let typed = text.trim().strip_prefix('/')?;
110    let (name, args) = typed.split_once(char::is_whitespace).unwrap_or((typed, ""));
111    SCREEN_ACTIONS.iter().any(|(screen, _, _)| *screen == name).then(|| (name, args.trim()))
112}
113
114/// The commands the terminal offers: its own, then the embedder's.
115#[derive(Clone, Default)]
116pub(crate) struct Commands {
117    added: Vec<Arc<dyn TerminalCommand>>,
118    /// Added commands named as one of the terminal's own: they answer only its bare form.
119    shadowed: Vec<Arc<dyn TerminalCommand>>,
120}
121
122impl fmt::Debug for Commands {
123    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
124        f.debug_list().entries(self.added.iter().map(|command| command.name())).finish()
125    }
126}
127
128impl Commands {
129    /// Adds `command`: the first one of a name stays, and one named as the terminal's own
130    /// answers only that command's bare form.
131    pub(crate) fn add(&mut self, command: Arc<dyn TerminalCommand>) {
132        let name = command.name();
133        if self.added.iter().chain(&self.shadowed).any(|added| added.name() == name) {
134            return;
135        }
136        if BUILT_IN.iter().any(|(built_in, _)| *built_in == name) {
137            self.shadowed.push(command);
138        } else {
139            self.added.push(command);
140        }
141    }
142
143    /// The added command `name`, if there is one.
144    pub(crate) fn find(&self, name: &str) -> Option<Arc<dyn TerminalCommand>> {
145        self.added.iter().find(|command| command.name() == name).cloned()
146    }
147
148    /// The added command named as the terminal's own `name`, which answers its bare form.
149    pub(crate) fn shadowed(&self, name: &str) -> Option<Arc<dyn TerminalCommand>> {
150        self.shadowed.iter().find(|command| command.name() == name).cloned()
151    }
152
153    /// The added commands' names and descriptions, in the order they were added.
154    pub(crate) fn added(&self) -> Vec<(String, String)> {
155        self.added
156            .iter()
157            .map(|command| (command.name().to_string(), command.description().to_string()))
158            .collect()
159    }
160
161    /// The added commands that are screen actions, for `/help`'s "On your screens": each one's
162    /// name, how to use it, its description and a second line.
163    pub(crate) fn screens(&self) -> Vec<(String, String, String, String)> {
164        self.added
165            .iter()
166            .filter_map(|command| {
167                let (_, usage, more) =
168                    SCREEN_ACTIONS.iter().find(|(name, _, _)| *name == command.name())?;
169                Some((
170                    command.name().to_string(),
171                    (*usage).to_string(),
172                    command.description().to_string(),
173                    (*more).to_string(),
174                ))
175            })
176            .collect()
177    }
178
179    /// Every command whose name starts with `typed`, ignoring case: the terminal's own first,
180    /// then the added ones.
181    pub(crate) fn matching(&self, typed: &str) -> Vec<(String, String)> {
182        let typed = typed.to_lowercase();
183        BUILT_IN
184            .iter()
185            .map(|(name, description)| ((*name).to_string(), (*description).to_string()))
186            .chain(self.added())
187            .filter(|(name, _)| name.to_lowercase().starts_with(&typed))
188            .collect()
189    }
190}
191
192/// Completing a command's name while the message box holds `/` and the start of a name.
193#[derive(Debug, Clone, Default, PartialEq, Eq)]
194pub(crate) struct Completion {
195    /// The name typed so far, without the slash.
196    pub typed: String,
197    /// The commands it matches, with their descriptions.
198    pub candidates: Vec<(String, String)>,
199    /// The candidate the arrows have chosen.
200    pub selected: usize,
201}
202
203impl Completion {
204    /// The completion for `text` in the message box: only while it is `/` and a name with no
205    /// space after it.
206    pub(crate) fn of(text: &str, commands: &Commands) -> Option<Self> {
207        let typed = text.strip_prefix('/')?;
208        if typed.contains(char::is_whitespace) {
209            return None;
210        }
211        Some(Self { typed: typed.to_string(), candidates: commands.matching(typed), selected: 0 })
212    }
213
214    /// The chosen candidate's name.
215    pub(crate) fn chosen(&self) -> Option<&str> {
216        self.candidates.get(self.selected).map(|(name, _)| name.as_str())
217    }
218
219    /// Whether what was typed is a whole command's name.
220    pub(crate) fn whole(&self) -> bool {
221        self.candidates.iter().any(|(name, _)| *name == self.typed)
222    }
223
224    /// Moves the choice by `step`, wrapping around.
225    pub(crate) fn step(&mut self, step: isize) {
226        let count = self.candidates.len();
227        if count == 0 {
228            return;
229        }
230        let at = self.selected as isize + step;
231        self.selected = at.rem_euclid(count as isize) as usize;
232    }
233
234    /// What Tab puts in the message box: the only candidate, or the longest start every
235    /// candidate shares when it is longer than what was typed, else the chosen candidate; a
236    /// whole name gets a space after it, ready for its arguments.
237    pub(crate) fn accept(&self) -> Option<String> {
238        let names: Vec<&str> = self.candidates.iter().map(|(name, _)| name.as_str()).collect();
239        match names.as_slice() {
240            [] => None,
241            [only] => Some(format!("/{only} ")),
242            _ => {
243                let shared = shared_start(&names);
244                if shared.chars().count() > self.typed.chars().count() {
245                    Some(format!("/{shared}"))
246                } else {
247                    names.get(self.selected).map(|name| format!("/{name} "))
248                }
249            }
250        }
251    }
252}
253
254/// The longest start all of `names` share.
255fn shared_start(names: &[&str]) -> String {
256    let Some((first, rest)) = names.split_first() else {
257        return String::new();
258    };
259    let mut end = first.len();
260    for name in rest {
261        end = first
262            .char_indices()
263            .zip(name.chars())
264            .take_while(|((_, a), b)| a == b)
265            .last()
266            .map_or(0, |((index, a), _)| index + a.len_utf8())
267            .min(end);
268    }
269    first[..end].to_string()
270}
271
272#[cfg(test)]
273mod tests {
274    use super::*;
275
276    struct Named(&'static str, &'static str);
277
278    #[async_trait]
279    impl TerminalCommand for Named {
280        fn name(&self) -> &str {
281            self.0
282        }
283
284        fn description(&self) -> &str {
285            self.1
286        }
287
288        async fn run(&self, args: &str, _: &CommandContext) -> adk_core::Result<String> {
289            Ok(format!("{} {args}", self.0))
290        }
291    }
292
293    fn commands(names: &[(&'static str, &'static str)]) -> Commands {
294        let mut commands = Commands::default();
295        for (name, description) in names {
296            commands.add(Arc::new(Named(name, description)));
297        }
298        commands
299    }
300
301    #[test]
302    fn the_terminals_own_commands_and_the_first_added_win() {
303        let commands = commands(&[
304            ("mode", "The REPL's mode"),
305            ("todos", "The todo list"),
306            ("todos", "A second todo list"),
307        ]);
308        assert_eq!(commands.added(), vec![("todos".to_string(), "The todo list".to_string())]);
309        assert!(commands.find("mode").is_none());
310        assert!(commands.find("todos").is_some());
311        // The REPL's `/mode` answers the bare `/mode` only.
312        assert_eq!(
313            commands.shadowed("mode").map(|command| command.description().to_string()),
314            Some("The REPL's mode".into())
315        );
316    }
317
318    #[test]
319    fn completion_lists_the_own_commands_first_then_the_added_ones() {
320        let commands = commands(&[("memory", "Notes and facts"), ("mcp", "MCP servers")]);
321        let completion = Completion::of("/m", &commands).unwrap();
322        let names: Vec<&str> =
323            completion.candidates.iter().map(|(name, _)| name.as_str()).collect();
324        assert_eq!(names, ["mode", "memory", "mcp"]);
325        assert!(Completion::of("/mode ask", &commands).is_none());
326        assert!(Completion::of("mode", &commands).is_none());
327        assert_eq!(completion.chosen(), Some("mode"));
328        assert!(!completion.whole());
329        assert!(Completion::of("/mcp", &commands).unwrap().whole());
330    }
331
332    #[test]
333    fn tab_takes_the_only_name_the_shared_start_or_the_chosen_name() {
334        let commands = commands(&[("memory", "Notes and facts"), ("mcp", "MCP servers")]);
335        assert_eq!(
336            Completion::of("/mem", &commands).unwrap().accept().as_deref(),
337            Some("/memory ")
338        );
339        assert_eq!(Completion::of("/me", &commands).unwrap().accept().as_deref(), Some("/memory "));
340        let mut several = Completion::of("/m", &commands).unwrap();
341        assert_eq!(several.accept().as_deref(), Some("/mode "));
342        several.step(1);
343        assert_eq!(several.accept().as_deref(), Some("/memory "));
344        several.step(-2);
345        assert_eq!(several.accept().as_deref(), Some("/mcp "));
346        assert_eq!(Completion::of("/zz", &commands).unwrap().accept(), None);
347        let shared = commands_with_shared_start();
348        // "resume" shares only "r" with them, so Tab takes the chosen name.
349        assert_eq!(Completion::of("/r", &shared).unwrap().accept().as_deref(), Some("/resume "));
350        assert_eq!(Completion::of("/ru", &shared).unwrap().accept().as_deref(), Some("/rule"));
351    }
352
353    fn commands_with_shared_start() -> Commands {
354        commands(&[("rules", "Standing rules"), ("rulebook", "The rulebook")])
355    }
356
357    #[test]
358    fn the_shared_start_respects_characters_wider_than_a_byte() {
359        assert_eq!(shared_start(&["café", "cafés"]), "café");
360        assert_eq!(shared_start(&["éa", "éb"]), "é");
361        assert_eq!(shared_start(&["a", "b"]), "");
362    }
363}