use std::future::Future;
use async_trait::async_trait;
use crate::channel::{CommandSpec, Conversation, Sender};
use crate::policy::SenderRole;
pub const MAX_COMMAND_NAME_CHARS: usize = 32;
pub const MAX_COMMAND_DESCRIPTION_CHARS: usize = 100;
#[non_exhaustive]
#[derive(Debug, Clone)]
pub struct CommandContext {
pub channel: String,
pub conversation: Conversation,
pub sender: Sender,
pub role: SenderRole,
pub session_id: String,
pub name: String,
pub args: String,
}
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CommandReply {
Text(String),
Silent,
}
impl CommandReply {
pub fn text(text: impl Into<String>) -> Self {
Self::Text(text.into())
}
}
#[async_trait]
pub trait CommandHandler: Send + Sync {
async fn handle(&self, context: CommandContext) -> CommandReply;
}
#[async_trait]
impl<F, Fut> CommandHandler for F
where
F: Fn(CommandContext) -> Fut + Send + Sync,
Fut: Future<Output = CommandReply> + Send,
{
async fn handle(&self, context: CommandContext) -> CommandReply {
self(context).await
}
}
pub fn builtin_commands(buttons: bool) -> Vec<CommandSpec> {
let mut commands = vec![
CommandSpec::new("stop", "Stop the current run"),
CommandSpec::new("new", "Start a new conversation"),
CommandSpec::new("status", "Show what this conversation is doing"),
];
if !buttons {
commands.push(CommandSpec::new("approve", "Approve a pending action"));
commands.push(CommandSpec::new("deny", "Deny a pending action"));
}
commands
}
pub(crate) fn is_builtin(name: &str) -> bool {
builtin_commands(false).iter().any(|c| c.name == name)
}
pub(crate) fn invalid_spec(spec: &CommandSpec) -> Option<&'static str> {
let name = &spec.name;
let starts_with_letter = name.starts_with(|c: char| c.is_ascii_lowercase());
let allowed = name
.chars()
.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_');
if name.len() > MAX_COMMAND_NAME_CHARS || !starts_with_letter || !allowed {
return Some(
"a command name is 1 to 32 lowercase letters, digits or underscores, starting with a letter",
);
}
let description = spec.description.trim();
if description.is_empty() || description.chars().count() > MAX_COMMAND_DESCRIPTION_CHARS {
return Some("a command description is 1 to 100 characters");
}
None
}