use std::sync::Arc;
use std::time::Duration;
use rpi_agent::agent_tool::AgentTool;
use rpi_agent::error::AgentError;
use rpi_tools::{
BashToolOptions, ExecutionToolContext, FileSystem, InMemoryExecutionEnv, ShellScript,
DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES,
};
use tokio_util::sync::CancellationToken;
fn fresh_context() -> (Arc<InMemoryExecutionEnv>, ExecutionToolContext) {
let env = Arc::new(InMemoryExecutionEnv::with_cwd("/tmp/work".into()));
let env_dyn: Arc<dyn rpi_tools::ExecutionEnv> = env.clone();
let mut_env: Arc<dyn rpi_tools::MutatingEnv> = env.clone();
let ctx = ExecutionToolContext::new(env_dyn, Some(mut_env));
(env, ctx)
}
async fn run_bash(
tool: Arc<dyn AgentTool>,
params: serde_json::Value,
) -> Result<rpi_agent::types::AgentToolResult, AgentError> {
let signal = CancellationToken::new();
let on_update = Arc::new(|_p| ());
let prepared = tool
.prepare_arguments(params.clone())
.unwrap_or_else(|_| params);
tool.execute("bash-x", prepared, signal, on_update).await
}
fn text_output(r: &rpi_agent::types::AgentToolResult) -> String {
use rpi_agent::types::TextContentOrImage;
r.content
.iter()
.filter_map(|c| match c {
TextContentOrImage::Text(t) => Some(t.text.clone()),
_ => None,
})
.collect::<Vec<_>>()
.join("\n")
}
fn err_text(e: &AgentError) -> String {
match e {
AgentError::Tool(m) => m.clone(),
AgentError::StructuredTool(r) => text_output(r),
other => format!("{other:?}"),
}
}
#[tokio::test]
async fn no_output_renders_placeholder() {
let (env, ctx) = fresh_context();
env.register_shell("noop", ShellScript::success("")).await;
let tool = rpi_tools::create_bash_tool(&ctx, None);
let r = run_bash(tool, serde_json::json!({ "command": "noop" }))
.await
.expect("ok");
assert_eq!(text_output(&r), "(no output)");
}
#[tokio::test]
async fn combines_stdout_and_stderr() {
let (env, ctx) = fresh_context();
env.register_shell(
"both",
ShellScript {
stdout: "out".into(),
stderr: "err".into(),
exit_code: 0,
delay_ms: None,
},
)
.await;
let tool = rpi_tools::create_bash_tool(&ctx, None);
let r = run_bash(tool, serde_json::json!({ "command": "both" }))
.await
.expect("ok");
let out = text_output(&r);
assert!(out.contains("out"), "{out}");
assert!(out.contains("err"), "{out}");
}
#[tokio::test]
async fn nonzero_exit_returns_error_with_output() {
let (env, ctx) = fresh_context();
env.register_shell(
"fail",
ShellScript {
stdout: "failed".into(),
stderr: String::new(),
exit_code: 7,
delay_ms: None,
},
)
.await;
let tool = rpi_tools::create_bash_tool(&ctx, None);
let err = run_bash(tool, serde_json::json!({ "command": "fail" }))
.await
.expect_err("nonzero exit → Err");
let msg = err_text(&err);
assert!(msg.contains("failed"), "{msg}");
assert!(msg.contains("Command exited with code 7"), "{msg}");
let AgentError::StructuredTool(result) = &err else {
panic!("bash failures must carry structured details: {err:?}");
};
assert_eq!(result.details["exit_code"], 7);
assert_eq!(result.details["failure_kind"], "command_failed");
}
#[tokio::test]
async fn abort_returns_error() {
let (env, ctx) = fresh_context();
env.register_shell(
"slow",
ShellScript {
stdout: "x".into(),
stderr: String::new(),
exit_code: 0,
delay_ms: Some(1000),
},
)
.await;
let tool = rpi_tools::create_bash_tool(&ctx, None);
let signal = CancellationToken::new();
let on_update = Arc::new(|_p| ());
let handle = {
let tool = tool.clone();
let sig = signal.clone();
tokio::spawn(async move {
tool.execute(
"bash-abort",
serde_json::json!({ "command": "slow" }),
sig,
on_update,
)
.await
})
};
tokio::time::sleep(Duration::from_millis(20)).await;
signal.cancel();
let err = handle.await.expect("join").expect_err("abort → Err");
let msg = err_text(&err);
assert!(msg.contains("aborted") || msg.contains("Aborted"), "{msg}");
}
#[tokio::test]
async fn persists_truncated_full_output_to_temp_file() {
let (env, ctx) = fresh_context();
let lines: String = (0..(DEFAULT_MAX_LINES + 1))
.map(|i| format!("line-{}", i + 1))
.collect::<Vec<_>>()
.join("\n")
+ "\n";
env.register_shell("big", ShellScript::success(lines)).await;
let tool = rpi_tools::create_bash_tool(&ctx, None);
let r = run_bash(tool, serde_json::json!({ "command": "big" }))
.await
.expect("ok");
let trunc = r.details.get("truncation").expect("truncation present");
assert_eq!(trunc["truncated"], true);
assert_eq!(trunc["truncated_by"], "lines");
assert_eq!(trunc["total_lines"], DEFAULT_MAX_LINES + 1);
assert_eq!(trunc["output_lines"], DEFAULT_MAX_LINES);
let full_path = r
.details
.get("full_output_path")
.and_then(|v| v.as_str())
.expect("full_output_path present");
let full = env
.read_text_file(full_path, None)
.await
.expect("read full output");
assert!(full.contains("line-1\nline-2"), "{full}");
assert!(
full.contains(&format!(
"line-{}\nline-{}",
DEFAULT_MAX_LINES,
DEFAULT_MAX_LINES + 1
)),
"{full}"
);
}
#[tokio::test]
async fn byte_limited_output_reports_the_visible_range_and_saves_every_line() {
let (env, ctx) = fresh_context();
let lines: Vec<_> = (1..=150)
.map(|number| format!("{number:03} {}", "x".repeat(995)))
.collect();
let expected = lines.join("\n") + "\n";
env.register_shell("large", ShellScript::success(expected.clone()))
.await;
let tool = rpi_tools::create_bash_tool(&ctx, None);
let result = run_bash(tool, serde_json::json!({"command": "large"}))
.await
.expect("bash completes");
let truncation = &result.details["truncation"];
let path = result.details["full_output_path"].as_str().unwrap();
let full = env.read_text_file(path, None).await.unwrap();
let notice = text_output(&result);
let footer = notice.lines().last().unwrap();
assert_eq!(
(
truncation["output_lines"].as_u64(),
full.len(),
footer.contains("Showing lines 100-150 of 150"),
),
(Some(51), expected.len(), true),
"{footer}"
);
assert_eq!(truncation["total_bytes"], expected.len());
assert!(full == expected, "the file must preserve all output bytes");
assert!(notice.starts_with(&lines[99..].join("\n")));
}
#[tokio::test]
async fn reports_oversized_final_line_size() {
let (env, ctx) = fresh_context();
let line_bytes = DEFAULT_MAX_BYTES + 5000;
let big_line = "0".repeat(line_bytes) + "\n";
env.register_shell("oneline", ShellScript::success(big_line))
.await;
let tool = rpi_tools::create_bash_tool(&ctx, None);
let r = run_bash(tool, serde_json::json!({ "command": "oneline" }))
.await
.expect("ok");
let out = text_output(&r);
assert!(out.contains("Showing last"), "{out}");
let footer = out.lines().last().unwrap();
assert!(
footer.contains(&format!(
"line 1 (line is {})",
rpi_tools::format_size(line_bytes)
)),
"{footer}"
);
}
#[tokio::test]
async fn native_cancellation_keeps_the_complete_captured_output() {
use rpi_tools::shell_output::{execute_shell_with_capture, ShellCaptureOptions};
use rpi_tools::{ExecutionEnv, ExecutionErrorCode, OsExecutionEnv};
let dir = tempfile::tempdir().unwrap();
let env: Arc<dyn ExecutionEnv> = Arc::new(OsExecutionEnv::with_cwd(dir.path().to_path_buf()));
let expected = "0123456789\n".repeat(DEFAULT_MAX_BYTES / 3) + "capture end marker\n";
std::fs::write(dir.path().join("output.txt"), &expected).unwrap();
let cancel = CancellationToken::new();
let from_callback = cancel.clone();
let capture = tokio::time::timeout(
Duration::from_secs(10),
execute_shell_with_capture(
&env,
"cat output.txt; sleep 30",
ShellCaptureOptions {
cancel: Some(&cancel),
return_execution_errors: true,
on_chunk: Some(Box::new(move |_chunk, progress| {
if progress().output.trim_end().ends_with("capture end marker") {
from_callback.cancel();
}
})),
..Default::default()
},
),
)
.await
.expect("cancellation must settle the shell")
.expect("capture must settle");
if let Some(error) = capture.execution_error {
if error.code == ExecutionErrorCode::ShellUnavailable {
eprintln!("skipping native capture test: {error}");
return;
}
panic!("native shell failed: {error}");
}
assert!(capture.cancelled);
assert_eq!(capture.exit_code, None);
let path = capture.full_output_path.expect("complete output was saved");
let full = std::fs::read(&path).unwrap();
std::fs::remove_file(&path).unwrap();
assert_eq!(capture.truncation.total_bytes, expected.len());
assert!(
full == expected.as_bytes(),
"the saved output must be complete"
);
}
#[tokio::test]
async fn supports_command_prefix() {
let (env, ctx) = fresh_context();
env.register_shell("value=hello\necho hello", ShellScript::success("hello"))
.await;
let tool = rpi_tools::create_bash_tool(
&ctx,
Some(BashToolOptions {
command_prefix: Some("value=hello".into()),
default_timeout: None,
prepare: None,
}),
);
env.register_shell("value=hello", ShellScript::success("hello"))
.await;
let r = run_bash(tool, serde_json::json!({ "command": "echo ignored" }))
.await
.expect("ok");
assert_eq!(text_output(&r), "hello");
}
#[test]
fn schema_describes_effective_default_timeout() {
let (_, ctx) = fresh_context();
for (options, expected) in [
(None, 120.0),
(Some(BashToolOptions::default()), 120.0),
(
Some(BashToolOptions {
default_timeout: Some(30.0),
..Default::default()
}),
30.0,
),
] {
let tool = rpi_tools::create_bash_tool(&ctx, options);
assert!(tool
.schema()
.description
.contains(&format!("{expected}-second timeout")));
let params = serde_json::to_value(&tool.schema().parameters).unwrap();
assert!(params["properties"]["timeout"]["description"]
.as_str()
.unwrap()
.contains(&format!("defaults to {expected} seconds")));
}
}
#[tokio::test]
async fn real_shell_honors_fallback_and_explicit_timeouts() {
use rpi_tools::{ExecutionErrorCode, OsExecutionEnv, Shell, ShellExecOptions};
let tmp = tempfile::tempdir().unwrap();
let env = Arc::new(OsExecutionEnv::with_cwd(tmp.path().to_path_buf()));
match env
.exec(
"echo ready",
ShellExecOptions {
timeout: Some(5.0),
..Default::default()
},
)
.await
{
Err(error) if error.code == ExecutionErrorCode::ShellUnavailable => {
eprintln!("skipping real-shell timeout test: {error}");
return;
}
result => {
result.expect("shell is available");
}
}
let ctx = ExecutionToolContext::new(env, None);
for (default_timeout, params) in [
(0.1, serde_json::json!({ "command": "sleep 30" })),
(
0.1,
serde_json::json!({ "command": "sleep 30", "timeout": null }),
),
(
30.0,
serde_json::json!({ "command": "sleep 30", "timeout": 0.1 }),
),
] {
let tool = rpi_tools::create_bash_tool(
&ctx,
Some(BashToolOptions {
default_timeout: Some(default_timeout),
..Default::default()
}),
);
let result = tokio::time::timeout(Duration::from_secs(10), run_bash(tool, params))
.await
.expect("bash must return within its deadline");
let msg = err_text(&result.expect_err("slow command must time out"));
assert!(msg.contains("Command timed out after 0.1s"), "{msg}");
}
}
#[cfg(windows)]
#[tokio::test]
async fn real_shell_bash_tool_returns_utf8_chinese_output() {
use rpi_tools::{ExecutionErrorCode, OsExecutionEnv, Shell, ShellExecOptions};
let tmp = tempfile::tempdir().unwrap();
let env = Arc::new(OsExecutionEnv::with_cwd(tmp.path().to_path_buf()));
match env.exec("true", ShellExecOptions::default()).await {
Ok(_) => {}
Err(error) if error.code == ExecutionErrorCode::ShellUnavailable => {
eprintln!("skipping: no usable bash on this host ({error})");
return;
}
Err(error) => panic!("unexpected shell error: {error:?}"),
}
let ctx = ExecutionToolContext::new(env, None);
let tool = rpi_tools::create_bash_tool(&ctx, None);
let result = run_bash(
tool,
serde_json::json!({ "command": r#"printf '中文输出\n'"# }),
)
.await
.expect("bash tool runs a real Git Bash");
let out = text_output(&result);
assert_eq!(out, "中文输出\n");
assert!(!out.contains('\u{fffd}'), "garbled output: {out:?}");
}
#[cfg(windows)]
#[tokio::test]
async fn bash_tool_surfaces_a_rejected_wsl_shell() {
use rpi_tools::OsExecutionEnv;
let tmp = tempfile::tempdir().unwrap();
let env = Arc::new(
OsExecutionEnv::with_cwd(tmp.path().to_path_buf())
.with_shell_path(std::path::PathBuf::from(r"C:\Windows\System32\bash.exe")),
);
let ctx = ExecutionToolContext::new(env, None);
let tool = rpi_tools::create_bash_tool(&ctx, None);
let err = run_bash(tool, serde_json::json!({ "command": "echo hi" }))
.await
.expect_err("a rejected shell must not look like success");
let msg = err_text(&err);
assert!(msg.contains("WSL"), "{msg}");
}
#[tokio::test]
async fn review_issue14_failure_kind_axis_and_success_have_no_classification() {
let (env, ctx) = fresh_context();
env.register_shell(
"fail",
ShellScript {
stdout: "grep: no match".into(),
stderr: String::new(),
exit_code: 1,
delay_ms: None,
},
)
.await;
env.register_shell("ok", ShellScript::success("done")).await;
let tool = rpi_tools::create_bash_tool(&ctx, None);
let ok = run_bash(tool.clone(), serde_json::json!({ "command": "ok" }))
.await
.expect("success");
assert!(ok.details.get("failure_kind").is_none(), "{:?}", ok.details);
assert_eq!(ok.details["exit_code"], 0);
let err = run_bash(tool.clone(), serde_json::json!({ "command": "fail" }))
.await
.expect_err("nonzero exit stays an error");
let AgentError::StructuredTool(result) = &err else {
panic!("expected StructuredTool: {err:?}");
};
assert_eq!(result.details["exit_code"], 1);
assert_eq!(result.details["failure_kind"], "command_failed");
assert!(text_output(result).contains("grep: no match"));
use rpi_tools::{ExecutionErrorCode, OsExecutionEnv, Shell, ShellExecOptions};
let tmp = tempfile::tempdir().unwrap();
let os_env = Arc::new(OsExecutionEnv::with_cwd(tmp.path().to_path_buf()));
match os_env
.exec(
"echo ready",
ShellExecOptions {
timeout: Some(5.0),
..Default::default()
},
)
.await
{
Err(error) if error.code == ExecutionErrorCode::ShellUnavailable => {
eprintln!("skipping timeout cell: no bash on this host");
}
result => {
result.expect("shell is available");
let os_ctx =
ExecutionToolContext::new(os_env.clone() as Arc<dyn rpi_tools::ExecutionEnv>, None);
let slow_tool = rpi_tools::create_bash_tool(&os_ctx, None);
let err = run_bash(
slow_tool,
serde_json::json!({ "command": "sleep 30", "timeout": 0.1 }),
)
.await
.expect_err("timeout stays an error");
let AgentError::StructuredTool(result) = &err else {
panic!("expected StructuredTool: {err:?}");
};
assert_eq!(result.details["failure_kind"], "timeout");
}
}
let (env3, ctx3) = fresh_context();
env3.register_shell(
"slow3",
ShellScript {
stdout: String::new(),
stderr: String::new(),
exit_code: 0,
delay_ms: Some(5000),
},
)
.await;
let cancel_tool = rpi_tools::create_bash_tool(&ctx3, None);
let signal = CancellationToken::new();
let on_update = Arc::new(|_p| ());
let cancel = signal.clone();
tokio::spawn(async move {
tokio::time::sleep(Duration::from_millis(30)).await;
cancel.cancel();
});
let err = cancel_tool
.execute(
"bash-x",
serde_json::json!({ "command": "slow3" }),
signal,
on_update,
)
.await
.expect_err("cancel stays an error");
let AgentError::StructuredTool(result) = &err else {
panic!("expected StructuredTool: {err:?}");
};
assert_eq!(result.details["failure_kind"], "cancelled");
}