1use std::fmt;
5use std::sync::Arc;
6
7use async_trait::async_trait;
8
9#[async_trait]
44pub trait TerminalCommand: Send + Sync {
45 fn name(&self) -> &str;
47
48 fn description(&self) -> &str;
50
51 async fn run(&self, args: &str, context: &CommandContext) -> adk_core::Result<String>;
58}
59
60#[derive(Debug, Clone, PartialEq, Eq)]
71#[non_exhaustive]
72pub struct CommandContext {
73 pub session_id: String,
75}
76
77impl CommandContext {
78 pub fn new(session_id: impl Into<String>) -> Self {
80 Self { session_id: session_id.into() }
81 }
82}
83
84pub(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
99pub(crate) const ON_YOUR_SCREENS: &str = "On your screens";
101
102const SCREEN_ACTIONS: &[(&str, &str, &str)] =
105 &[("snooze", "<title> [tomorrow]", "an hour later, or the same time tomorrow")];
106
107pub(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#[derive(Clone, Default)]
116pub(crate) struct Commands {
117 added: Vec<Arc<dyn TerminalCommand>>,
118 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 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 pub(crate) fn find(&self, name: &str) -> Option<Arc<dyn TerminalCommand>> {
145 self.added.iter().find(|command| command.name() == name).cloned()
146 }
147
148 pub(crate) fn shadowed(&self, name: &str) -> Option<Arc<dyn TerminalCommand>> {
150 self.shadowed.iter().find(|command| command.name() == name).cloned()
151 }
152
153 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 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 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#[derive(Debug, Clone, Default, PartialEq, Eq)]
194pub(crate) struct Completion {
195 pub typed: String,
197 pub candidates: Vec<(String, String)>,
199 pub selected: usize,
201}
202
203impl Completion {
204 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 pub(crate) fn chosen(&self) -> Option<&str> {
216 self.candidates.get(self.selected).map(|(name, _)| name.as_str())
217 }
218
219 pub(crate) fn whole(&self) -> bool {
221 self.candidates.iter().any(|(name, _)| *name == self.typed)
222 }
223
224 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 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
254fn 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 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 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}