rho-coding-agent 3.2.0

A fast Rust agent harness with a small footprint and opinionated defaults
use std::sync::Arc;

use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};

use super::{
    daemon_gate::{command_route, CommandRoute},
    palette::{ActivePalette, DiscoveryCache, PALETTE_CACHE_TTL},
    App, CommandChoice, CommandChoiceKind,
};
use crate::commands;

/// What a command-palette key did, so the idle and running composers share
/// one handler and keep only their own submit path.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum CommandPaletteKeyOutcome {
    /// Not a palette key; keep routing.
    Ignored,
    /// The palette consumed the key; nothing submits.
    Handled,
    /// Enter accepted the composer; the caller submits for its mode.
    Submit,
}

impl App {
    /// What decides which commands and arguments are on offer. The session
    /// says itself whether its model has a fast mode.
    pub(super) fn command_context(&self) -> commands::CommandContext {
        commands::CommandContext {
            fast_mode_supported: self
                .daemon_options
                .as_ref()
                .is_some_and(|options| options.fast_mode.is_some()),
        }
    }

    /// Command matches when the command palette is what the composer shows.
    ///
    /// Callers must already have excluded other composer modes; this owns the
    /// command-palette-specific guards.
    pub(super) fn visible_command_matches(&mut self) -> Option<Vec<CommandChoice>> {
        if self.input_ui.command_palette_dismissed() {
            return None;
        }
        let matches = self.command_matches();
        (!matches.is_empty()
            && (self.cursor_in_command_token()
                || !commands::argument_choices(
                    self.input_ui.text(),
                    self.input_ui.cursor(),
                    &self.command_context(),
                )
                .is_empty()
                || !self.mcp_argument_choices().is_empty()
                || self.skill_mention_cursor().is_some()))
        .then_some(matches)
    }

    /// The palette's matches: a settled command's argument values alone,
    /// else the matching commands in the built-in order with an exact
    /// match's arguments after them, then the session's own commands. A
    /// built-in the daemon runs as a prompt is listed only while the session
    /// offers it.
    pub(super) fn command_matches(&mut self) -> Vec<CommandChoice> {
        // A `$` mention can sit anywhere in a prompt, command arguments
        // included, and asks only for skills.
        if let Some(cursor) = self.skill_mention_cursor() {
            return self.skill_mention_choices(&cursor);
        }
        let context = self.command_context();
        let arguments =
            commands::argument_choices(self.input_ui.text(), self.input_ui.cursor(), &context);
        if !arguments.is_empty() {
            return arguments.iter().map(argument_command_choice).collect();
        }
        // Argument values belong to a command the user has already settled, so
        // they are offered where command matching has nothing left to say
        // rather than mixed into the command list.
        let mcp_arguments = self.mcp_argument_choices();
        if !mcp_arguments.is_empty() {
            return mcp_arguments;
        }
        let Some(prefix) = commands::command_prefix(self.input_ui.text()) else {
            return Vec::new();
        };
        let prefix = prefix.trim_start_matches('/').to_ascii_lowercase();
        let offered: Vec<_> = self
            .daemon_options
            .iter()
            .flat_map(|options| &options.commands)
            .filter(|command| command.kind == rho_protocol::CommandKind::Slash)
            .collect();
        let session_choice = |command: &rho_protocol::SessionCommand| CommandChoice {
            name: command.name.clone(),
            usage: match &command.input_hint {
                Some(hint) => format!("/{} {hint}", command.name),
                None => format!("/{}", command.name),
            },
            description: command.description.clone(),
            kind: CommandChoiceKind::SessionCommand,
        };
        let mut builtins = commands::matching_commands(&prefix);
        builtins.retain(|command| context.is_discoverable(command.id));
        let exact = builtins
            .iter()
            .find(|command| command.name.eq_ignore_ascii_case(&prefix))
            .copied();
        let mut choices: Vec<_> = builtins
            .into_iter()
            .filter_map(|command| match command_route(command.id) {
                CommandRoute::Prompt => offered
                    .iter()
                    .find(|offered| offered.name == command.name)
                    .map(|offered| session_choice(offered)),
                CommandRoute::Ui | CommandRoute::Options => Some(CommandChoice {
                    name: command.name.into(),
                    usage: command.usage.into(),
                    description: command.description.into(),
                    kind: CommandChoiceKind::Builtin(command),
                }),
            })
            .collect();
        if let Some(command) = exact {
            choices.extend(command.argument_choices.iter().map(argument_command_choice));
        }
        choices.extend(
            offered
                .iter()
                .filter(|command| command.name.to_ascii_lowercase().starts_with(&prefix))
                .filter(|command| {
                    !commands::COMMANDS
                        .iter()
                        .any(|builtin| builtin.name == command.name)
                })
                .map(|command| session_choice(command)),
        );
        choices
    }

    /// Skills for palette matching, served from the timed cache when fresh.
    ///
    /// Get-or-discover: whichever path asks first — a keystroke or a render
    /// frame — walks skill directories once and shares the result.
    pub(super) fn discovered_skills(&mut self) -> Arc<Vec<crate::skills::Skill>> {
        DiscoveryCache::get_or_refresh(&mut self.palette_caches.skills, PALETTE_CACHE_TTL, || {
            crate::skills::discover(
                &self.info.runtime.cwd,
                crate::workspace::ProjectTrusts::of_this_process(),
            )
        })
    }

    /// The prompt template behind a `prompt:<name>` command, read from disk
    /// now and expanded with `trailing`.
    pub(super) fn resolve_prompt_template(&self, name: &str, trailing: &str) -> Option<String> {
        let template_name = crate::prompt_templates::command_template_name(name)?;
        let templates = crate::prompt_templates::load(
            &self.info.runtime.cwd,
            self.info.runtime.prompt_template_home.as_deref(),
            self.info.runtime.config_prompt_templates.clone(),
        );
        crate::prompt_templates::find(&templates, template_name)
            .map(|template| crate::prompt_templates::expand(template, trailing))
    }

    #[cfg(test)]
    pub(super) fn selected_command(&mut self) -> Option<CommandChoice> {
        let matches = self.command_matches();
        selected_command(&matches, self.input_ui.command_selection())
    }

    pub(super) fn dismiss_command_palette_on_esc(&mut self) {
        if self.input_ui.text() == "/" {
            self.input_ui.clear_text();
            self.input_ui.set_cursor(0);
        }
        self.input_ui.set_command_palette_dismissed(true);
        self.input_ui.reset_command_selection();
    }

    /// Keys the open command palette owns, shared by the idle and running
    /// composers so navigation, tab completion, and the Enter gate stay
    /// defined once. Only the submit that Enter triggers differs per mode,
    /// so the caller performs it.
    pub(super) fn handle_command_palette_key(&mut self, key: KeyEvent) -> CommandPaletteKeyOutcome {
        let Some(ActivePalette::Command(matches)) = self.active_palette() else {
            return CommandPaletteKeyOutcome::Ignored;
        };

        match (key.modifiers, key.code) {
            (KeyModifiers::NONE, KeyCode::Up) => {
                if !matches.is_empty() {
                    let next = if self.input_ui.command_selection() == 0 {
                        matches.len() - 1
                    } else {
                        self.input_ui.command_selection() - 1
                    };
                    self.input_ui.move_command_selection(next);
                }
                CommandPaletteKeyOutcome::Handled
            }
            (KeyModifiers::NONE, KeyCode::Down) => {
                if !matches.is_empty() {
                    let next = (self.input_ui.command_selection() + 1) % matches.len();
                    self.input_ui.move_command_selection(next);
                }
                CommandPaletteKeyOutcome::Handled
            }
            (KeyModifiers::NONE, KeyCode::Tab) => {
                if let Some(choice) = selected_command(&matches, self.input_ui.command_selection())
                {
                    self.complete_command_choice(&choice);
                    self.input_ui.set_command_palette_dismissed(false);
                    self.clamp_command_selection();
                }
                CommandPaletteKeyOutcome::Handled
            }
            (KeyModifiers::NONE, KeyCode::Enter) => {
                if let Some(choice) = selected_command(&matches, self.input_ui.command_selection())
                    .filter(|choice| self.enter_completes_choice(choice))
                {
                    self.complete_command_choice(&choice);
                    self.clamp_command_selection();
                }
                CommandPaletteKeyOutcome::Submit
            }
            (KeyModifiers::NONE, KeyCode::Esc) => {
                self.dismiss_command_palette_on_esc();
                CommandPaletteKeyOutcome::Handled
            }
            _ => CommandPaletteKeyOutcome::Ignored,
        }
    }

    /// Whether Enter folds the highlighted palette row into the composer
    /// before submitting.
    ///
    /// Command-name rows finish a token someone was already typing, so Enter
    /// completes them uninvited. Argument rows add content nobody typed, so
    /// Enter takes one only after an explicit pick, or once a typed MCP value
    /// already narrows the server's suggestions. Otherwise the bare command
    /// runs as typed: tab fills the trailing space for an argument, and a
    /// blind Enter must not spend that offer on the first row.
    pub(super) fn enter_completes_choice(&self, choice: &CommandChoice) -> bool {
        match choice.kind {
            CommandChoiceKind::Builtin(_) | CommandChoiceKind::SessionCommand => true,
            CommandChoiceKind::BuiltinArgument(_) => self.input_ui.command_selection_explicit(),
            CommandChoiceKind::McpPromptArgument { .. } => {
                self.input_ui.command_selection_explicit()
                    || self
                        .mcp_argument_cursor()
                        .is_some_and(|cursor| !cursor.key.typed.trim().is_empty())
            }
            // `$` and `$20` read as prices, so Enter sends them as typed until
            // the typed name could itself be a mention or a row was picked.
            CommandChoiceKind::SkillMention { .. } => {
                self.input_ui.command_selection_explicit()
                    || self
                        .skill_mention_cursor()
                        .is_some_and(|cursor| crate::skills::mention::mentionable(&cursor.typed))
            }
        }
    }

    pub(super) fn complete_command_choice(&mut self, choice: &CommandChoice) {
        let (input, cursor) = match &choice.kind {
            CommandChoiceKind::Builtin(spec) => {
                self.input_ui
                    .set_submission_mode(super::InputSubmissionMode::ParseCommands);
                commands::complete_command(self.input_ui.text(), self.input_ui.cursor(), spec)
            }
            CommandChoiceKind::BuiltinArgument(choice) => {
                self.input_ui
                    .set_submission_mode(super::InputSubmissionMode::ParseCommands);
                commands::complete_argument_choice(choice)
            }
            // A session command completes to its slash token, which the
            // daemon resolves on submit.
            CommandChoiceKind::SessionCommand => {
                self.input_ui
                    .set_submission_mode(super::InputSubmissionMode::ParseCommands);
                complete_slash_command(self.input_ui.text(), self.input_ui.cursor(), &choice.name)
            }
            // Only the argument's own range is rewritten: the command and every
            // other argument already typed stay exactly as they are.
            CommandChoiceKind::McpPromptArgument { value } => {
                self.input_ui
                    .set_submission_mode(super::InputSubmissionMode::ParseCommands);
                super::mcp_argument_completion::replace_value(
                    self.input_ui.text(),
                    value,
                    &choice.name,
                )
            }
            // Mentions are prompt text, so the submission mode stays as is.
            CommandChoiceKind::SkillMention { token } => {
                self.complete_skill_mention(token, &choice.name);
                self.input_ui.set_shell_mode(None);
                return;
            }
        };
        self.input_ui.set_text_and_cursor(input, cursor);
        self.input_ui.set_shell_mode(None);
    }
}

/// The palette row currently selected among already-resolved matches.
pub(super) fn selected_command(
    matches: &[CommandChoice],
    selection: usize,
) -> Option<CommandChoice> {
    matches
        .get(selection.min(matches.len().saturating_sub(1)))
        .cloned()
}

fn argument_command_choice(choice: &'static commands::CommandArgumentChoice) -> CommandChoice {
    CommandChoice {
        name: choice.completion.to_string(),
        usage: choice.usage.to_string(),
        description: choice.description.to_string(),
        kind: CommandChoiceKind::BuiltinArgument(choice),
    }
}

pub(super) fn slash_command_args(input: &str) -> &str {
    let token_end = input
        .char_indices()
        .find_map(|(index, ch)| ch.is_whitespace().then_some(index))
        .unwrap_or(input.len());
    input[token_end..].trim_start()
}

pub(super) fn complete_slash_command(input: &str, cursor: usize, name: &str) -> (String, usize) {
    let token_end = input
        .char_indices()
        .find_map(|(index, ch)| ch.is_whitespace().then_some(index))
        .unwrap_or(input.len());
    let token_len = input[..token_end].chars().count();
    let args = slash_command_args(input);
    let completed = if args.is_empty() {
        format!("/{name}")
    } else {
        format!("/{name} {args}")
    };
    let completed_token_len = name.chars().count() + 1;
    let new_cursor = if cursor <= token_len {
        completed_token_len
    } else {
        completed
            .chars()
            .count()
            .min(completed_token_len.saturating_add(cursor.saturating_sub(token_len)))
    };
    (completed, new_cursor)
}

#[cfg(test)]
#[path = "command_palette_tests.rs"]
mod tests;