Skip to main content

tea_cli/tui/
commands.rs

1use std::collections::BTreeSet;
2use std::str::FromStr as _;
3
4use tea_mcp::McpServerId;
5use tea_protocol::{MessageId, ModelId, ReasoningEffort, SessionId};
6
7use super::attachment::MAX_COMPOSER_ATTACHMENTS;
8
9const BUILTINS: [&str; 14] = [
10    "compact",
11    "copy",
12    "fork",
13    "help",
14    "image",
15    "mcp",
16    "model",
17    "name",
18    "new",
19    "quit",
20    "resume",
21    "reasoning",
22    "session",
23    "tree",
24];
25const MAX_COMMANDS: usize = 512;
26const MAX_IMAGE_PATH_BYTES: usize = 4096;
27
28/// Parsed interactive slash command.
29#[derive(Debug, Clone, PartialEq, Eq)]
30pub enum SlashCommand {
31    /// Create and switch to a new session.
32    New,
33    /// Resume an explicit session or open the session selector.
34    Resume(Option<SessionId>),
35    /// Open the session selector.
36    Session,
37    /// Set or clear a session display name.
38    Name(Option<String>),
39    /// Set a model or open the model selector.
40    Model(Option<ModelId>),
41    /// Set reasoning effort or open the reasoning selector.
42    Reasoning(Option<ReasoningEffort>),
43    /// Compact the active session.
44    Compact,
45    /// Open the branch tree selector.
46    Tree,
47    /// Fork from one durable message.
48    Fork(MessageId),
49    /// Copy the last assistant response.
50    Copy,
51    /// Load one explicit local image path.
52    Image(String),
53    /// Remove one image by its one-based composer index.
54    ImageRemove(usize),
55    /// Remove every image from the active session composer.
56    ImageClear,
57    /// Display safe MCP server health and frozen aliases.
58    Mcp,
59    /// Reconnect one MCP server only against its frozen discovery snapshot.
60    McpReconnect(McpServerId),
61    /// Show command help.
62    Help,
63    /// Exit the application.
64    Quit,
65    /// Expand one trusted declarative prompt template.
66    Template {
67        /// Canonical template name.
68        name: String,
69        /// Positional template arguments.
70        arguments: Vec<String>,
71    },
72    /// Load one explicit trusted skill invocation.
73    Skill(String),
74}
75
76/// Invalid command catalog or invocation.
77#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
78pub enum CommandError {
79    /// The command name, arguments, or identifier is invalid.
80    #[error("slash command is invalid")]
81    Invalid,
82    /// A declarative resource conflicts with another command.
83    #[error("slash command catalog has a duplicate")]
84    Duplicate,
85    /// The command catalog exceeds its fixed bound.
86    #[error("slash command catalog is too large")]
87    TooMany,
88}
89
90/// Deterministic built-in and declarative slash command catalog.
91#[derive(Debug, Clone)]
92pub struct CommandCatalog {
93    templates: BTreeSet<String>,
94    skills: BTreeSet<String>,
95    completions: Vec<String>,
96}
97
98impl CommandCatalog {
99    /// Builds a bounded catalog from trusted resource names.
100    ///
101    /// # Errors
102    ///
103    /// Rejects invalid, duplicate, conflicting, or oversized names.
104    pub fn new<T, S, TI, SI>(templates: TI, skills: SI) -> Result<Self, CommandError>
105    where
106        T: AsRef<str>,
107        S: AsRef<str>,
108        TI: IntoIterator<Item = T>,
109        SI: IntoIterator<Item = S>,
110    {
111        let templates = collect_names(templates)?;
112        let skills = collect_names(skills)?;
113        if templates
114            .iter()
115            .any(|name| BUILTINS.contains(&name.as_str()))
116        {
117            return Err(CommandError::Duplicate);
118        }
119        if templates.len().saturating_add(skills.len()) + BUILTINS.len() > MAX_COMMANDS {
120            return Err(CommandError::TooMany);
121        }
122        let mut completions = BUILTINS
123            .into_iter()
124            .map(|name| format!("/{name}"))
125            .chain(templates.iter().map(|name| format!("/{name}")))
126            .chain(skills.iter().map(|name| format!("/skill:{name}")))
127            .collect::<Vec<_>>();
128        completions.sort();
129        Ok(Self {
130            templates,
131            skills,
132            completions,
133        })
134    }
135
136    /// Parses one complete command line.
137    ///
138    /// # Errors
139    ///
140    /// Rejects unknown commands, malformed identifiers, or extra arguments.
141    pub fn parse(&self, input: &str) -> Result<SlashCommand, CommandError> {
142        if input.is_empty() || input.contains('\0') || input.len() > crate::tui::MAX_EDITOR_BYTES {
143            return Err(CommandError::Invalid);
144        }
145        if let Some(skill) = input.strip_prefix("/skill:") {
146            let name = skill
147                .split_whitespace()
148                .next()
149                .ok_or(CommandError::Invalid)?;
150            if self.skills.contains(name) {
151                return Ok(SlashCommand::Skill(input.to_owned()));
152            }
153            return Err(CommandError::Invalid);
154        }
155        if input == "/image" || input.starts_with("/image ") {
156            return parse_image(input);
157        }
158        let mut parts = input.split_whitespace();
159        let command = parts
160            .next()
161            .and_then(|value| value.strip_prefix('/'))
162            .ok_or(CommandError::Invalid)?;
163        let arguments = parts.map(str::to_owned).collect::<Vec<_>>();
164        match command {
165            "new" if arguments.is_empty() => Ok(SlashCommand::New),
166            "resume" if arguments.len() <= 1 => Ok(SlashCommand::Resume(
167                arguments
168                    .first()
169                    .map(|value| SessionId::from_str(value))
170                    .transpose()
171                    .map_err(|_| CommandError::Invalid)?,
172            )),
173            "session" if arguments.is_empty() => Ok(SlashCommand::Session),
174            "name" => Ok(SlashCommand::Name(
175                (!arguments.is_empty()).then(|| arguments.join(" ")),
176            )),
177            "model" if arguments.len() <= 1 => Ok(SlashCommand::Model(
178                arguments
179                    .first()
180                    .map(|value| ModelId::from_str(value))
181                    .transpose()
182                    .map_err(|_| CommandError::Invalid)?,
183            )),
184            "reasoning" if arguments.len() <= 1 => Ok(SlashCommand::Reasoning(
185                arguments
186                    .first()
187                    .map(|value| ReasoningEffort::from_str(value))
188                    .transpose()
189                    .map_err(|_| CommandError::Invalid)?,
190            )),
191            "compact" if arguments.is_empty() => Ok(SlashCommand::Compact),
192            "tree" if arguments.is_empty() => Ok(SlashCommand::Tree),
193            "fork" if arguments.len() == 1 => MessageId::from_str(&arguments[0])
194                .map(SlashCommand::Fork)
195                .map_err(|_| CommandError::Invalid),
196            "copy" if arguments.is_empty() => Ok(SlashCommand::Copy),
197            "mcp" if arguments.is_empty() => Ok(SlashCommand::Mcp),
198            "mcp" if arguments.len() == 2 && arguments[0] == "reconnect" => {
199                McpServerId::from_str(&arguments[1])
200                    .map(SlashCommand::McpReconnect)
201                    .map_err(|_| CommandError::Invalid)
202            }
203            "help" if arguments.is_empty() => Ok(SlashCommand::Help),
204            "quit" if arguments.is_empty() => Ok(SlashCommand::Quit),
205            name if self.templates.contains(name) => Ok(SlashCommand::Template {
206                name: name.to_owned(),
207                arguments,
208            }),
209            _ => Err(CommandError::Invalid),
210        }
211    }
212
213    /// Returns sorted prefix completions up to the caller's bound.
214    #[must_use]
215    pub fn complete(&self, prefix: &str, limit: usize) -> Vec<String> {
216        self.completions
217            .iter()
218            .filter(|command| command.starts_with(prefix))
219            .take(limit)
220            .cloned()
221            .collect()
222    }
223}
224
225fn parse_image(input: &str) -> Result<SlashCommand, CommandError> {
226    let argument = input
227        .strip_prefix("/image ")
228        .map(str::trim)
229        .filter(|argument| !argument.is_empty())
230        .ok_or(CommandError::Invalid)?;
231    if argument.len() > MAX_IMAGE_PATH_BYTES || argument.chars().any(char::is_control) {
232        return Err(CommandError::Invalid);
233    }
234
235    let mut parts = argument.split_whitespace();
236    match parts.next() {
237        Some("clear") if parts.next().is_none() => Ok(SlashCommand::ImageClear),
238        Some("clear") | None => Err(CommandError::Invalid),
239        Some("remove") => {
240            let index = parts
241                .next()
242                .and_then(|value| value.parse::<usize>().ok())
243                .filter(|index| (1..=MAX_COMPOSER_ATTACHMENTS).contains(index))
244                .ok_or(CommandError::Invalid)?;
245            if parts.next().is_some() {
246                return Err(CommandError::Invalid);
247            }
248            Ok(SlashCommand::ImageRemove(index))
249        }
250        Some(_) => Ok(SlashCommand::Image(argument.to_owned())),
251    }
252}
253
254fn collect_names<T, I>(values: I) -> Result<BTreeSet<String>, CommandError>
255where
256    T: AsRef<str>,
257    I: IntoIterator<Item = T>,
258{
259    let mut names = BTreeSet::new();
260    for value in values {
261        let value = value.as_ref();
262        if !valid_name(value) {
263            return Err(CommandError::Invalid);
264        }
265        if !names.insert(value.to_owned()) {
266            return Err(CommandError::Duplicate);
267        }
268        if names.len() > MAX_COMMANDS {
269            return Err(CommandError::TooMany);
270        }
271    }
272    Ok(names)
273}
274
275fn valid_name(name: &str) -> bool {
276    !name.is_empty()
277        && name.len() <= 128
278        && name
279            .bytes()
280            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_'))
281}