rho-coding-agent 3.13.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! The masked prompt for a daemon's secret ask: the person types the secret
//! an MCP server reads, or declines.
//!
//! The value leaves only in the reply, which becomes the daemon's answer.
//! It never reaches the transcript, the prompt history, or a log: the field
//! takes no paste burst and `Debug` hides it. The field's buffer is wiped
//! once the prompt closes, as a best effort: copies the string left behind
//! as it grew, and the reply's own, are not.
//!
//! A request that closes elsewhere while the prompt is open leaves the
//! prompt holding the keyboard, saying so, until Enter or Esc dismisses it,
//! so what the person goes on typing or pasting never reaches the composer
//! and, from there, the agent.

use std::fmt;

use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use rho_protocol::{SecretAsk, SecretDestination, SecretValue};
use tokio::sync::oneshot;
use zeroize::Zeroize;

use super::{
    composer_chrome,
    line_editor::LineEditor,
    line_editor_view::EditorPresentation,
    masked_input::{apply_masked_key, MaskedKey},
    panel_text::indented_wrapped_lines,
    styled_line, truncate_one_line,
    view_composer::{editor_frame, ComposerFrame},
    App, ComposerMode, LineFill, Theme, UserWait,
};

/// What the person gave at a secret ask.
#[derive(Debug, PartialEq, Eq)]
pub(super) enum SecretReply {
    Save(SecretValue),
    Decline,
}

/// What a key did at the secret prompt.
#[derive(Debug, PartialEq, Eq)]
pub(super) enum SecretKey {
    /// The prompt stays: the key edited the field, or did nothing.
    Kept,
    /// The person answered.
    Reply(SecretReply),
    /// The person dismissed a prompt whose request had closed.
    Dismiss,
}

/// The open secret ask: what it asks, the masked field, and where the
/// reply goes, until the request closes elsewhere.
pub(super) struct SecretAskComposer {
    ask: SecretAsk,
    pub(super) editor: LineEditor,
    /// The person pressed Enter on a blank field; the prompt says it needs
    /// a value until they type.
    blank_refused: bool,
    /// `None` once the request closed elsewhere: the prompt takes no more
    /// input, only its dismissal.
    reply: Option<oneshot::Sender<SecretReply>>,
    /// `/side` was open when the prompt replaced it, so it comes back.
    restore_side: bool,
}

impl SecretAskComposer {
    fn new(ask: SecretAsk, reply: oneshot::Sender<SecretReply>, restore_side: bool) -> Self {
        Self {
            ask,
            editor: LineEditor::new(""),
            blank_refused: false,
            reply: Some(reply),
            restore_side,
        }
    }

    /// Whether the request is still open, so the prompt asks.
    fn asking(&self) -> bool {
        self.reply.is_some()
    }

    /// What `key` does. While asking, Ctrl+C declines as Esc does, and
    /// Enter on a blank field only says it needs a value. Once the request
    /// closed, only Enter and Esc do anything: they dismiss the prompt.
    fn apply_key(&mut self, key: KeyEvent) -> SecretKey {
        if !self.asking() {
            return match key.code {
                KeyCode::Enter | KeyCode::Esc => SecretKey::Dismiss,
                _ => SecretKey::Kept,
            };
        }
        if key.modifiers.contains(KeyModifiers::CONTROL) && key.code == KeyCode::Char('c') {
            return SecretKey::Reply(SecretReply::Decline);
        }
        match apply_masked_key(&mut self.editor, key) {
            MaskedKey::Handled => {
                self.blank_refused &= self.editor.value.is_empty();
                SecretKey::Kept
            }
            MaskedKey::Submit => {
                let reply = typed_reply(&self.editor.value);
                self.blank_refused = reply.is_none();
                reply.map_or(SecretKey::Kept, SecretKey::Reply)
            }
            MaskedKey::Cancel => SecretKey::Reply(SecretReply::Decline),
        }
    }

    /// Pastes `text` into the field while asking; drops it once the request
    /// closed.
    pub(super) fn insert_text(&mut self, text: &str) {
        if self.asking() {
            self.editor.insert_text(text);
        }
    }

    fn respond(&mut self, reply: SecretReply) {
        self.editor.value.zeroize();
        if let Some(sender) = self.reply.take() {
            let _ = sender.send(reply);
        }
    }

    /// The request closed elsewhere: wipe the field and take no more input.
    fn close(&mut self) {
        self.editor.value.zeroize();
        self.editor = LineEditor::new("");
        self.blank_refused = false;
        self.reply = None;
    }
}

impl Drop for SecretAskComposer {
    fn drop(&mut self) {
        self.editor.value.zeroize();
    }
}

impl fmt::Debug for SecretAskComposer {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("SecretAskComposer")
            .field("ask", &self.ask)
            .field("editor", &"[redacted]")
            .field("blank_refused", &self.blank_refused)
            .finish_non_exhaustive()
    }
}

/// The reply Enter gives for `typed`: the value, trimmed as a pasted key
/// often needs, or none when nothing is left.
fn typed_reply(typed: &str) -> Option<SecretReply> {
    let value = typed.trim();
    (!value.is_empty()).then(|| SecretReply::Save(SecretValue::new(value)))
}

/// What the prompt says receives the secret.
fn destination_line(name: &str, destination: &SecretDestination) -> String {
    match destination {
        SecretDestination::Process { command, args } => {
            let line = std::iter::once(command.as_str())
                .chain(args.iter().map(String::as_str))
                .collect::<Vec<_>>()
                .join(" ");
            format!("{name} goes to the process `{line}`")
        }
        SecretDestination::Http { url } => format!("{name} goes as a header to {url}"),
        // A destination a newer daemon names.
        _ => format!("{name} goes where the server's config sends it"),
    }
}

/// The prompt: the server it is for, what receives the secret, the agent's
/// reason, then the masked field under its key hints. Once the request
/// closed, it says so instead of offering the field.
pub(super) fn secret_ask_frame(composer: &SecretAskComposer, width: usize) -> ComposerFrame {
    let ask = &composer.ask;
    let mut lines = vec![styled_line(
        truncate_one_line(&format!("Secret for {}", ask.server), width),
        width,
        Theme::input_prompt(),
        LineFill::Natural,
    )];
    lines.extend(indented_wrapped_lines(
        &destination_line(&ask.name, &ask.destination),
        /*indent*/ 0,
        width,
        Theme::dim(),
    ));
    if !composer.asking() {
        let prompt = format!(
            "the secret request closed; nothing was sent  {}",
            composer_chrome::join_footer_parts(["Enter/Esc dismiss"])
        );
        let mut frame = editor_frame(
            &prompt,
            composer.editor.viewport(EditorPresentation::Masked, width),
            width,
        );
        frame.cursor.y = frame.cursor.y.saturating_add(lines.len() as u16);
        lines.append(&mut frame.lines);
        frame.lines = lines;
        return frame;
    }
    if let Some(reason) = ask
        .reason
        .as_deref()
        .filter(|reason| !reason.trim().is_empty())
    {
        lines.extend(indented_wrapped_lines(
            reason,
            /*indent*/ 0,
            width,
            Theme::text(),
        ));
    }
    let field = if composer.blank_refused {
        format!("{} must not be empty", ask.name)
    } else {
        format!("enter {}", ask.name)
    };
    let prompt = format!(
        "{field}  {}",
        composer_chrome::join_footer_parts(["Enter save", "Esc decline"])
    );
    let mut frame = editor_frame(
        &prompt,
        composer.editor.viewport(EditorPresentation::Masked, width),
        width,
    );
    frame.cursor.y = frame.cursor.y.saturating_add(lines.len() as u16);
    lines.append(&mut frame.lines);
    frame.lines = lines;
    frame
}

impl App {
    /// Opens the masked prompt for `ask`, whose reply goes to `reply`.
    pub(super) async fn open_secret_ask(
        &mut self,
        ask: SecretAsk,
        reply: oneshot::Sender<SecretReply>,
    ) {
        // A paste burst still pending belongs to the composer it began in.
        self.flush_pending_paste_burst();
        let restore_side = self.side_overlay_open();
        self.input_ui
            .set_composer(ComposerMode::SecretAsk(SecretAskComposer::new(
                ask,
                reply,
                restore_side,
            )));
        self.set_status(UserWait::Secret.message());
        self.wait_for_user(UserWait::Secret).await;
    }

    /// The prompt's request closed elsewhere: the prompt stays, saying so,
    /// and holds the keyboard until the person dismisses it.
    pub(super) fn withdraw_secret_ask(&mut self) {
        if let ComposerMode::SecretAsk(composer) = self.input_ui.composer_mut() {
            composer.close();
        }
    }

    /// Keys for the open secret ask, which owns the keyboard while open.
    /// Returns whether it was open.
    pub(super) fn handle_secret_ask_key(&mut self, key: KeyEvent) -> bool {
        let ComposerMode::SecretAsk(composer) = self.input_ui.composer_mut() else {
            return false;
        };
        let outcome = composer.apply_key(key);
        self.ctrl_c_streak = 0;
        if outcome == SecretKey::Kept {
            return true;
        }
        if let ComposerMode::SecretAsk(mut composer) = self.input_ui.take_composer() {
            if let SecretKey::Reply(reply) = outcome {
                composer.respond(reply);
            }
            self.restore_after_secret_ask(&composer);
        }
        if self.daemon_turn_runs() {
            self.set_status("running");
        }
        true
    }

    fn restore_after_secret_ask(&mut self, composer: &SecretAskComposer) {
        if composer.restore_side && self.side_chat.is_some() {
            self.input_ui.set_composer(ComposerMode::Side);
        }
    }
}

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