use std::fmt;
use std::sync::Arc;
use async_trait::async_trait;
#[async_trait]
pub trait TerminalCommand: Send + Sync {
fn name(&self) -> &str;
fn description(&self) -> &str;
async fn run(&self, args: &str, context: &CommandContext) -> adk_core::Result<String>;
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct CommandContext {
pub session_id: String,
}
impl CommandContext {
pub fn new(session_id: impl Into<String>) -> Self {
Self { session_id: session_id.into() }
}
}
pub(crate) const BUILT_IN: &[(&str, &str)] = &[
("help", "Keys and commands"),
("today", "Today: while you were away"),
("permissions", "Permissions: what your agents can do"),
("agents", "Your agents"),
("mode", "Show or set the mode: just look, suggest, ask first or go ahead"),
("session", "This session; /session new or /session ID opens another"),
("stop", "Stop all"),
("resume", "Resume all"),
("quit", "Leave; a kernel's agents carry on"),
("exit", "Leave; a kernel's agents carry on"),
];
pub(crate) const ON_YOUR_SCREENS: &str = "On your screens";
const SCREEN_ACTIONS: &[(&str, &str, &str)] =
&[("snooze", "<title> [tomorrow]", "an hour later, or the same time tomorrow")];
pub(crate) fn screen_action(text: &str) -> Option<(&str, &str)> {
let typed = text.trim().strip_prefix('/')?;
let (name, args) = typed.split_once(char::is_whitespace).unwrap_or((typed, ""));
SCREEN_ACTIONS.iter().any(|(screen, _, _)| *screen == name).then(|| (name, args.trim()))
}
#[derive(Clone, Default)]
pub(crate) struct Commands {
added: Vec<Arc<dyn TerminalCommand>>,
shadowed: Vec<Arc<dyn TerminalCommand>>,
}
impl fmt::Debug for Commands {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_list().entries(self.added.iter().map(|command| command.name())).finish()
}
}
impl Commands {
pub(crate) fn add(&mut self, command: Arc<dyn TerminalCommand>) {
let name = command.name();
if self.added.iter().chain(&self.shadowed).any(|added| added.name() == name) {
return;
}
if BUILT_IN.iter().any(|(built_in, _)| *built_in == name) {
self.shadowed.push(command);
} else {
self.added.push(command);
}
}
pub(crate) fn find(&self, name: &str) -> Option<Arc<dyn TerminalCommand>> {
self.added.iter().find(|command| command.name() == name).cloned()
}
pub(crate) fn shadowed(&self, name: &str) -> Option<Arc<dyn TerminalCommand>> {
self.shadowed.iter().find(|command| command.name() == name).cloned()
}
pub(crate) fn added(&self) -> Vec<(String, String)> {
self.added
.iter()
.map(|command| (command.name().to_string(), command.description().to_string()))
.collect()
}
pub(crate) fn screens(&self) -> Vec<(String, String, String, String)> {
self.added
.iter()
.filter_map(|command| {
let (_, usage, more) =
SCREEN_ACTIONS.iter().find(|(name, _, _)| *name == command.name())?;
Some((
command.name().to_string(),
(*usage).to_string(),
command.description().to_string(),
(*more).to_string(),
))
})
.collect()
}
pub(crate) fn matching(&self, typed: &str) -> Vec<(String, String)> {
let typed = typed.to_lowercase();
BUILT_IN
.iter()
.map(|(name, description)| ((*name).to_string(), (*description).to_string()))
.chain(self.added())
.filter(|(name, _)| name.to_lowercase().starts_with(&typed))
.collect()
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub(crate) struct Completion {
pub typed: String,
pub candidates: Vec<(String, String)>,
pub selected: usize,
}
impl Completion {
pub(crate) fn of(text: &str, commands: &Commands) -> Option<Self> {
let typed = text.strip_prefix('/')?;
if typed.contains(char::is_whitespace) {
return None;
}
Some(Self { typed: typed.to_string(), candidates: commands.matching(typed), selected: 0 })
}
pub(crate) fn chosen(&self) -> Option<&str> {
self.candidates.get(self.selected).map(|(name, _)| name.as_str())
}
pub(crate) fn whole(&self) -> bool {
self.candidates.iter().any(|(name, _)| *name == self.typed)
}
pub(crate) fn step(&mut self, step: isize) {
let count = self.candidates.len();
if count == 0 {
return;
}
let at = self.selected as isize + step;
self.selected = at.rem_euclid(count as isize) as usize;
}
pub(crate) fn accept(&self) -> Option<String> {
let names: Vec<&str> = self.candidates.iter().map(|(name, _)| name.as_str()).collect();
match names.as_slice() {
[] => None,
[only] => Some(format!("/{only} ")),
_ => {
let shared = shared_start(&names);
if shared.chars().count() > self.typed.chars().count() {
Some(format!("/{shared}"))
} else {
names.get(self.selected).map(|name| format!("/{name} "))
}
}
}
}
}
fn shared_start(names: &[&str]) -> String {
let Some((first, rest)) = names.split_first() else {
return String::new();
};
let mut end = first.len();
for name in rest {
end = first
.char_indices()
.zip(name.chars())
.take_while(|((_, a), b)| a == b)
.last()
.map_or(0, |((index, a), _)| index + a.len_utf8())
.min(end);
}
first[..end].to_string()
}
#[cfg(test)]
mod tests {
use super::*;
struct Named(&'static str, &'static str);
#[async_trait]
impl TerminalCommand for Named {
fn name(&self) -> &str {
self.0
}
fn description(&self) -> &str {
self.1
}
async fn run(&self, args: &str, _: &CommandContext) -> adk_core::Result<String> {
Ok(format!("{} {args}", self.0))
}
}
fn commands(names: &[(&'static str, &'static str)]) -> Commands {
let mut commands = Commands::default();
for (name, description) in names {
commands.add(Arc::new(Named(name, description)));
}
commands
}
#[test]
fn the_terminals_own_commands_and_the_first_added_win() {
let commands = commands(&[
("mode", "The REPL's mode"),
("todos", "The todo list"),
("todos", "A second todo list"),
]);
assert_eq!(commands.added(), vec![("todos".to_string(), "The todo list".to_string())]);
assert!(commands.find("mode").is_none());
assert!(commands.find("todos").is_some());
assert_eq!(
commands.shadowed("mode").map(|command| command.description().to_string()),
Some("The REPL's mode".into())
);
}
#[test]
fn completion_lists_the_own_commands_first_then_the_added_ones() {
let commands = commands(&[("memory", "Notes and facts"), ("mcp", "MCP servers")]);
let completion = Completion::of("/m", &commands).unwrap();
let names: Vec<&str> =
completion.candidates.iter().map(|(name, _)| name.as_str()).collect();
assert_eq!(names, ["mode", "memory", "mcp"]);
assert!(Completion::of("/mode ask", &commands).is_none());
assert!(Completion::of("mode", &commands).is_none());
assert_eq!(completion.chosen(), Some("mode"));
assert!(!completion.whole());
assert!(Completion::of("/mcp", &commands).unwrap().whole());
}
#[test]
fn tab_takes_the_only_name_the_shared_start_or_the_chosen_name() {
let commands = commands(&[("memory", "Notes and facts"), ("mcp", "MCP servers")]);
assert_eq!(
Completion::of("/mem", &commands).unwrap().accept().as_deref(),
Some("/memory ")
);
assert_eq!(Completion::of("/me", &commands).unwrap().accept().as_deref(), Some("/memory "));
let mut several = Completion::of("/m", &commands).unwrap();
assert_eq!(several.accept().as_deref(), Some("/mode "));
several.step(1);
assert_eq!(several.accept().as_deref(), Some("/memory "));
several.step(-2);
assert_eq!(several.accept().as_deref(), Some("/mcp "));
assert_eq!(Completion::of("/zz", &commands).unwrap().accept(), None);
let shared = commands_with_shared_start();
assert_eq!(Completion::of("/r", &shared).unwrap().accept().as_deref(), Some("/resume "));
assert_eq!(Completion::of("/ru", &shared).unwrap().accept().as_deref(), Some("/rule"));
}
fn commands_with_shared_start() -> Commands {
commands(&[("rules", "Standing rules"), ("rulebook", "The rulebook")])
}
#[test]
fn the_shared_start_respects_characters_wider_than_a_byte() {
assert_eq!(shared_start(&["café", "cafés"]), "café");
assert_eq!(shared_start(&["éa", "éb"]), "é");
assert_eq!(shared_start(&["a", "b"]), "");
}
}