use std::{
error::Error,
io::{self, Write},
};
use super::diff::{show_edit_diff, show_write_preview};
use super::frame::{
GUTTER, GUTTER_WIDTH, gutter_line, title_case, truncate_ellipsis, write_band_on,
};
use super::wrap::{MAX_LINE_WIDTH, wrap_line};
use tinyharness_lib::provider::ToolCall;
use crate::style::*;
fn describe(name: &str) -> &'static str {
match name {
"run" => "execute a shell command",
"write" => "create or overwrite a file",
"edit" => "modify a file in place",
"read" => "read a file",
"ls" => "list a directory",
"grep" => "search file contents",
"glob" => "match files by pattern",
_ => "",
}
}
const CMD_PREFIX_WIDTH: usize = GUTTER_WIDTH + 2;
fn write_command_lines<W: Write>(stdout: &mut W, cmd: &str) -> Result<(), Box<dyn Error>> {
let avail = MAX_LINE_WIDTH - CMD_PREFIX_WIDTH;
for (i, row) in wrap_line(cmd, avail, avail).into_iter().enumerate() {
let prefix = if i == 0 { "$ " } else { "> " };
gutter_line(
stdout,
GUTTER,
&format!("{FG_FAINT}{prefix}{RESET}{FG_CMD}{row}{RESET}", row = row),
)?;
}
Ok(())
}
pub enum Confirmation {
Yes,
No,
AutoAccept,
}
pub fn prompt_tool_confirmation<W: Write>(
stdout: &mut W,
call: &ToolCall,
) -> Result<Confirmation, Box<dyn Error>> {
let name = &call.function.name;
let args = &call.function.arguments;
let effect = describe(name);
let mut segments: Vec<(&str, &str)> = vec![
("▲", FG_WARN),
(" ", FG_FAINT),
("Allow?", FG_WARN),
(" · ", FG_FAINT),
];
let label = title_case(name);
if effect.is_empty() {
segments.push((label.as_str(), FG_BAND));
} else {
segments.push((name.as_str(), FG_BAND));
segments.push((" — ", FG_FAINT));
segments.push((effect, FG_MUTED));
}
write_band_on(stdout, BG_PROMPT, &segments)?;
let skip_keys: &[&str] = match name.as_str() {
"edit" => &["old_str", "new_str", "content"],
"write" => &["content"],
"run" => &["command"],
_ => &[],
};
if let serde_json::Value::Object(map) = args {
for (key, val) in map {
if skip_keys.contains(&key.as_str()) {
continue;
}
let val_str = match val {
serde_json::Value::String(s) => truncate_ellipsis(
s.lines().next().unwrap_or_default(),
MAX_LINE_WIDTH - GUTTER_WIDTH - key.len() - 2,
),
other => other.to_string(),
};
gutter_line(
stdout,
GUTTER,
&format!(
"{FG_MUTED}{key}:{RESET} {FG_ACCENT}{val}{RESET}",
key = key,
val = val_str
),
)?;
}
}
if let serde_json::Value::Object(map) = args {
let path = map.get("path").and_then(|v| v.as_str()).unwrap_or("");
if !path.trim().is_empty() && name == "edit" {
let old_str = map.get("old_str").and_then(|v| v.as_str()).unwrap_or("");
let new_str = map.get("new_str").and_then(|v| v.as_str()).unwrap_or("");
if !old_str.is_empty() {
show_edit_diff(stdout, path, old_str, new_str)?;
}
}
if name == "run" {
let cmd = map.get("command").and_then(|v| v.as_str()).unwrap_or("");
if !cmd.is_empty() {
write_command_lines(stdout, cmd)?;
}
}
}
if let serde_json::Value::Object(map) = args {
let path = map.get("path").and_then(|v| v.as_str()).unwrap_or("");
if !path.trim().is_empty() && name == "write" {
let content = map.get("content").and_then(|v| v.as_str()).unwrap_or("");
if !content.is_empty() {
show_write_preview(stdout, path, content)?;
}
}
}
write!(
stdout,
" {FG_WARN}▲{RESET} {BOLD}[y]{RESET}{FG_FAINT}es{RESET} {BOLD}[n]{RESET}{FG_FAINT}o{RESET} \
{BOLD}[a]{RESET}{FG_FAINT}uto-accept the rest of this turn{RESET} {FG_FAINT}›{RESET} "
)?;
stdout.flush()?;
let mut input = String::new();
io::stdin()
.read_line(&mut input)
.expect("Failed to read line");
let input = input.trim().to_lowercase();
Ok(match input.as_str() {
"y" | "yes" => Confirmation::Yes,
"a" | "auto" => Confirmation::AutoAccept,
_ => Confirmation::No,
})
}
#[cfg(test)]
mod tests {
use super::*;
fn strip_ansi(s: &str) -> String {
let re = regex::Regex::new(r"\x1b\[[0-9;]*[mK]").unwrap();
re.replace_all(s, "").to_string()
}
#[test]
fn test_short_command_single_line() {
let mut buf = Vec::new();
write_command_lines(&mut buf, "ls -la").unwrap();
let output = strip_ansi(&String::from_utf8(buf).unwrap());
assert_eq!(output, " │ $ ls -la\n", "rows stay open until the ▲ line");
}
#[test]
fn test_long_command_wraps() {
let long_cmd: Vec<String> = (0..60).map(|i| format!("argument_number_{i}")).collect();
let cmd = long_cmd.join(" ");
let mut buf = Vec::new();
write_command_lines(&mut buf, &cmd).unwrap();
let output = strip_ansi(&String::from_utf8(buf).unwrap());
let lines: Vec<&str> = output.lines().collect();
assert!(lines.len() > 1, "long command should wrap: {output}");
assert!(lines[0].starts_with(" │ $ "), "first line has $ prompt");
assert!(
lines[1..].iter().all(|l| l.starts_with(" │ > ")),
"continuation lines use > and stay in the gutter"
);
for line in &lines {
assert!(line.chars().count() <= MAX_LINE_WIDTH, "overflow: {line}");
}
}
#[test]
fn test_command_no_spaces_hard_breaks() {
let cmd = "a".repeat(MAX_LINE_WIDTH);
let mut buf = Vec::new();
write_command_lines(&mut buf, &cmd).unwrap();
let output = strip_ansi(&String::from_utf8(buf).unwrap());
assert!(
output.lines().count() > 1,
"no-space command should hard-break"
);
}
#[test]
fn known_tools_describe_their_effect() {
assert_eq!(describe("run"), "execute a shell command");
assert_eq!(describe("write"), "create or overwrite a file");
assert!(describe("my_tool").is_empty());
}
}