From 6df7a6403d88a4492ab6ea1c519dcae3a202be96 Mon Sep 17 00:00:00 2001 From: salmonik Date: Wed, 18 Nov 2026 12:01:38 +0100 Subject: 0.9.0: distinguishable tool errors, separated stderr, configurable limits From a field report porting a Neovim config to Helix: - validate() now separates 'empty value', 'wrong key (here is what you sent)' and 'no arguments at all, retry' instead of one false message for all four causes - named calls with no arguments are answered rather than dropped silently - bash keeps stdout and stderr in labelled sections when both produce output - bash gains timeout_seconds (1-600) and max_bytes, and says when output was cut - tool lines/results carry [step.call] labels when a step has several calls - invalid JSON errors include a preview of what arrived --- CHANGELOG.md | 31 +++++++++ Cargo.lock | 2 +- Cargo.toml | 2 +- README.md | 7 +- src/agent.rs | 39 +++++++---- src/tools/mod.rs | 74 +++++++++++++++------ src/tools/shell.rs | 185 ++++++++++++++++++++++++++++++++++++----------------- src/ui.rs | 13 ++-- tests/loop.rs | 74 ++++++++++++++++++--- tests/tools.rs | 56 ++++++++++++++++ 10 files changed, 373 insertions(+), 110 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 10925a7..be3c6b8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,37 @@ break the interface, **PATCH** for bug fixes. file, and the tool schemas the model sees. Anything a script or a resumed session could depend on counts as API. +## 0.9.0 + +Driven by a field report from a real task (porting a Neovim config to Helix). +The report's most expensive problem was not a missing feature: it was one error +message covering four different failures. + +### Added +- `bash` takes `timeout_seconds` (1-600, default 120) and `max_bytes` (per-stream + output budget, 1 KiB-16 MiB, default 80 KiB), so the limits are discoverable and + adjustable instead of only discoverable by exceeding them. + +### Changed +- `bash` keeps stdout and stderr apart. When both produce output they arrive in + labelled `[stdout]` / `[stderr]` sections; stderr alone is labelled; stdout + alone is unchanged. A real error printed to stderr can no longer hide inside + ordinary output. +- A truncated result says so on its final line, next to the exit status. +- Tool lines and results carry a per-call label (`[2.1]`, `[2.2]`) when several + calls run in one step, so a result is attributable without counting order. + +### Fixed +- The `cmd` validation error covered four distinct causes with one message, and + was false about two of them. It now distinguishes: the value is empty; the key + is missing and here is what you sent instead; or the call arrived with no + arguments at all, which points at argument loss in transit and suggests a + retry. +- A named call with no arguments is no longer dropped silently. The model is told + what arrived and can retry; only nameless calls are dropped, because they + cannot be replayed to the provider. +- Invalid JSON arguments report a preview of what arrived. + ## 0.8.2 ### Changed diff --git a/Cargo.lock b/Cargo.lock index e7a389a..c14c2fb 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -10,7 +10,7 @@ checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" [[package]] name = "agent686" -version = "0.8.2" +version = "0.9.0" dependencies = [ "crossterm", "libc", diff --git a/Cargo.toml b/Cargo.toml index 2bc807d..108444b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "agent686" -version = "0.8.2" +version = "0.9.0" edition = "2021" description = "A small coding agent for a 32-bit Debian box" publish = false diff --git a/README.md b/README.md index 056e771..e6b83aa 100644 --- a/README.md +++ b/README.md @@ -64,9 +64,10 @@ honoured); a 429 that survives them explains itself instead of dumping JSON. `read` (numbered lines, streamed, regular files only), `write` (atomic, never creates directories), `edit` (exact match that must be unique; CRLF files -supported), `bash` (fresh shell per call, own process group, 120 s timeout, -64 MiB output limit), `grep` (regular expression; `fixed: true` for literals), -`glob` (`*`, `?`, `**`, follows file symlinks). +supported), `bash` (fresh shell per call, own process group, stdout and stderr in +separate labelled sections, `timeout_seconds` and `max_bytes` per call), +`grep` (regular expression; `fixed: true` for literals), `glob` (`*`, `?`, `**`, +follows file symlinks). Reads never prompt. The first `write`/`edit` of a session shows a diff and asks; answering `a` allows the rest of the process. Every `bash` call asks, because diff --git a/src/agent.rs b/src/agent.rs index 7d4c4ef..afd662c 100644 --- a/src/agent.rs +++ b/src/agent.rs @@ -217,14 +217,16 @@ pub fn run_turn( Err(error) => return Err(error), }; - // Placeholders are dropped before the assistant message is written: - // recording a call we refuse to run would leave it unanswered. + // A call with no name cannot be replayed to the provider at all, so it + // is dropped. A *named* call with no arguments is kept: the model is told + // what arrived and can retry, which is better than silence. let before = outcome.tool_calls.len(); - outcome - .tool_calls - .retain(|call| !tools::is_placeholder(&call.arguments)); + outcome.tool_calls.retain(|call| !call.name.trim().is_empty()); if outcome.tool_calls.len() < before { - eprintln!("agent686: ignored {} empty tool call(s) from the model", before - outcome.tool_calls.len()); + eprintln!( + "agent686: ignored {} tool call(s) with no name", + before - outcome.tool_calls.len() + ); } // A missing id would make the tool result unattachable. @@ -247,7 +249,15 @@ pub fn run_turn( let calls = outcome.tool_calls.clone(); last = Some(outcome); - for call in calls { + let multiple = calls.len() > 1; + for (offset, call) in calls.into_iter().enumerate() { + // Thousands of steps are possible in a long turn; the label keeps + // each call's lines attributable when several run in one step. + let label = if multiple { + format!("{steps}.{}", offset + 1) + } else { + steps.to_string() + }; // Cancelling between calls still has to answer every tool call the // assistant message announced: an unanswered id makes the session // permanently unusable, because history is never rewritten. @@ -257,7 +267,7 @@ pub fn run_turn( let result = if aborted { ToolOutcome::Failed("aborted by the user before this call ran".into()) } else { - execute(&call, approver, cancel, steps) + execute(&call, approver, cancel, &label) }; if result.denied() { denied += 1; @@ -269,7 +279,7 @@ pub fn run_turn( _ => {} } } - ui::tool_result(&result.summary(), aborted); + ui::tool_result(&label, &result.summary(), aborted); let message = json!({ "role": "tool", "tool_call_id": call.id, @@ -350,21 +360,22 @@ fn execute( call: &provider::ToolCall, approver: &mut Approver, cancel: &AtomicBool, - step: usize, + label: &str, ) -> ToolOutcome { let args: Value = match serde_json::from_str(&call.arguments) { Ok(args) => args, Err(error) => { + let raw = crate::provider::truncate(call.arguments.trim(), 200); return ToolOutcome::Failed(format!( - "arguments were not valid JSON ({error}); issue the call again with the \ - complete arguments" - )) + "arguments were not valid JSON ({error}). Received: {raw:?}. \ + Issue the call again with complete arguments" + )); } }; // The bash approval prompt prints the command; do not print it here too. let repeat_detail = !(tools::approval(&call.name) == Approval::EveryCall && approver.will_prompt_bash()); - ui::tool_line(step, &call.name, &args, repeat_detail); + ui::tool_line(label, &call.name, &args, repeat_detail); if let Err(error) = tools::validate(&call.name, &args) { return ToolOutcome::Failed(format!("{error}; the call was not run")); } diff --git a/src/tools/mod.rs b/src/tools/mod.rs index ddb1004..27840e9 100644 --- a/src/tools/mod.rs +++ b/src/tools/mod.rs @@ -24,28 +24,52 @@ pub fn approval(name: &str) -> Approval { } } -/// A call with no arguments at all. Every tool here requires at least one, so -/// this is a placeholder some backends emit next to a real call, not an attempt. +/// True when the call cannot be replayed as a real tool call at all: no name. +/// (Named calls with no arguments are kept so the model can be told what went +/// wrong and retry.) pub fn is_placeholder(arguments: &str) -> bool { - let trimmed = arguments.trim(); - if trimmed.is_empty() { - return true; + arguments.trim().is_empty() +} + +/// Returns the keys the model actually sent, quoted and bounded. +fn received_keys(args: &Value) -> String { + let Some(object) = args.as_object() else { + return "no arguments".to_string(); + }; + if object.is_empty() { + return "no arguments".to_string(); } - matches!( - serde_json::from_str::(trimmed), - Ok(Value::Object(map)) if map.is_empty() - ) + let mut keys: Vec = object.keys().map(|key| format!("`{key}`")).collect(); + keys.sort(); + if keys.len() > 6 { + keys.truncate(6); + keys.push("…".to_string()); + } + keys.join(", ") } -/// Rejects a call that cannot possibly run, before a human is asked to approve -/// it. An empty `cmd` used to mean an approval prompt for `run: `. +/// Rejects a call that cannot run, before a human is asked to approve it. +/// +/// The message has to distinguish three different failures: the argument is +/// empty, the argument is missing because the key is wrong, and the call +/// arrived with no arguments at all (usually argument loss in transit). They +/// used to share one message, which pointed callers at the wrong fix. pub fn validate(name: &str, args: &Value) -> Result<(), String> { - let text = |key: &str| args.get(key).and_then(|value| value.as_str()).unwrap_or(""); - let required = |key: &str| { - if text(key).trim().is_empty() { - Err(format!("`{key}` is required and must not be empty")) - } else { - Ok(()) + let required = |key: &str| match args.get(key).and_then(|value| value.as_str()) { + Some(value) if !value.trim().is_empty() => Ok(()), + Some(_) => Err(format!("`{key}` is present but empty")), + None => { + if args.as_object().map(|o| o.is_empty()).unwrap_or(true) { + Err(format!( + "the call arrived with no arguments at all, so `{key}` is missing. \ + If you sent one, it was lost in transit — retry the call" + )) + } else { + Err(format!( + "missing `{key}`; received {}. The parameter is `{key}`", + received_keys(args) + )) + } } }; @@ -57,6 +81,7 @@ pub fn validate(name: &str, args: &Value) -> Result<(), String> { required("old") } "grep" | "glob" => required("pattern"), + "" => Err("the tool call arrived without a tool name; it was probably truncated in transit — retry the call".into()), _ => Ok(()), } } @@ -67,7 +92,14 @@ pub fn run(name: &str, args: &Value, cancel: &std::sync::atomic::AtomicBool) -> "read" => fs::read(args), "grep" => fs::grep(args), "glob" => fs::glob(args), - "bash" => shell::bash(args, std::time::Duration::from_secs(120), cancel), + "bash" => { + let seconds = args + .get("timeout_seconds") + .and_then(|value| value.as_u64()) + .unwrap_or(120) + .clamp(1, 600); + shell::bash(args, std::time::Duration::from_secs(seconds), cancel) + } other => Err(unknown(other)), } } @@ -139,12 +171,14 @@ pub fn schemas() -> Vec { "type": "function", "function": { "name": "bash", - "description": "Run a shell command. Each call is a fresh shell at the working directory, so `cd` does not persist; pass cwd instead. Times out after 120s. Returns combined output and the exit code.", + "description": "Run a shell command. Each call is a fresh shell at the working directory, so `cd` does not persist; pass cwd instead. stdout and stderr are reported in separate labelled sections when both produce output. Times out after timeout_seconds (default 120, maximum 600). Large output is truncated head+tail with an explicit marker; raise max_bytes if the match you need is in the middle.", "parameters": { "type": "object", "properties": { "cmd": { "type": "string" }, - "cwd": { "type": "string", "description": "working directory (default: project root)" } + "cwd": { "type": "string", "description": "working directory (default: project root)" }, + "timeout_seconds": { "type": "integer", "description": "1-600, default 120" }, + "max_bytes": { "type": "integer", "description": "per-stream output budget, 1024-16777216, default 81920" } }, "required": ["cmd"] } diff --git a/src/tools/shell.rs b/src/tools/shell.rs index 6f095c6..91f2dd9 100644 --- a/src/tools/shell.rs +++ b/src/tools/shell.rs @@ -8,11 +8,14 @@ use std::time::{Duration, Instant}; use serde_json::Value; -const HEAD_BYTES: usize = 64 * 1024; -const TAIL_BYTES: i64 = 16 * 1024; -/// The child cannot write more than this, so a runaway command cannot fill /tmp -/// and take the machine down with it. -const MAX_OUTPUT_BYTES: u64 = 64 * 1024 * 1024; +/// Default budget per stream, split 4:1 between head and tail. +const DEFAULT_MAX_BYTES: usize = 80 * 1024; +const MIN_MAX_BYTES: usize = 1024; +const MAX_MAX_BYTES: usize = 16 * 1024 * 1024; +/// The child cannot write more than this per stream, so a runaway command cannot +/// fill /tmp and take the machine down with it. +const MAX_FILE_BYTES: u64 = 64 * 1024 * 1024; + static COUNTER: AtomicU64 = AtomicU64::new(0); pub fn bash( @@ -25,25 +28,26 @@ pub fn bash( None => return Err("missing required argument `cmd`".into()), }; + let max_bytes = args + .get("max_bytes") + .and_then(|value| value.as_u64()) + .unwrap_or(DEFAULT_MAX_BYTES as u64) + .clamp(MIN_MAX_BYTES as u64, MAX_MAX_BYTES as u64) as usize; + let head_budget = max_bytes * 4 / 5; + let tail_budget = max_bytes - head_budget; + let cwd = resolve_cwd(args.get("cwd").and_then(|v| v.as_str()))?; if !cwd.is_dir() { return Err(format!("cwd is not a directory: {}", cwd.display())); } - let path = std::env::temp_dir().join(format!( - "agent686-{}-{}.out", - std::process::id(), - COUNTER.fetch_add(1, Ordering::Relaxed) - )); - let mut file = std::fs::OpenOptions::new() - .read(true) - .write(true) - .create(true) - .truncate(true) - .open(&path) - .map_err(|e| format!("{}: {e}", path.display()))?; - let stdout = file.try_clone().map_err(|e| e.to_string())?; - let stderr = file.try_clone().map_err(|e| e.to_string())?; + let serial = COUNTER.fetch_add(1, Ordering::Relaxed); + let out_path = temp_path("out", serial); + let err_path = temp_path("err", serial); + let mut out_file = create(&out_path)?; + let mut err_file = create(&err_path)?; + let stdout = out_file.try_clone().map_err(|e| e.to_string())?; + let stderr = err_file.try_clone().map_err(|e| e.to_string())?; let mut command = Command::new("sh"); command @@ -63,8 +67,8 @@ pub fn bash( command.pre_exec(|| { // rlim_t is u32 on i686 and u64 on x86-64. let limit = libc::rlimit { - rlim_cur: MAX_OUTPUT_BYTES as libc::rlim_t, - rlim_max: MAX_OUTPUT_BYTES as libc::rlim_t, + rlim_cur: MAX_FILE_BYTES as libc::rlim_t, + rlim_max: MAX_FILE_BYTES as libc::rlim_t, }; if libc::setrlimit(libc::RLIMIT_FSIZE, &limit) != 0 { return Err(std::io::Error::last_os_error()); @@ -103,38 +107,97 @@ pub fn bash( // A child that blew the file-size limit was killed by SIGXFSZ. let over_limit = status.signal() == Some(libc::SIGXFSZ); - let output = read_capped(&mut file).map_err(|e| format!("could not read output: {e}"))?; - drop(file); - let _ = std::fs::remove_file(&path); + let (out_text, out_cut) = read_capped(&mut out_file, head_budget, tail_budget)?; + let (err_text, err_cut) = read_capped(&mut err_file, head_budget, tail_budget)?; + drop(out_file); + drop(err_file); + let _ = std::fs::remove_file(&out_path); + let _ = std::fs::remove_file(&err_path); - let mut out = output; - if !out.is_empty() && !out.ends_with('\n') { - out.push('\n'); - } - if over_limit { - out.push_str(&format!( + let marker = if over_limit { + format!( "[output exceeded {} MiB; command killed]", - MAX_OUTPUT_BYTES / (1024 * 1024) - )); + MAX_FILE_BYTES / (1024 * 1024) + ) } else if aborted { - out.push_str("[aborted by the user]"); + "[aborted by the user]".to_string() } else if timed_out { - out.push_str(&format!( - "[timed out after {:.1}s; process killed]", - timeout.as_secs_f64() - )); + format!("[timed out after {:.1}s; process killed]", timeout.as_secs_f64()) } else { match status.code() { - Some(code) => out.push_str(&format!("[exit {code}]")), - None => { - out.push_str(&format!( - "[killed by signal {}]", - status.signal().unwrap_or_default() - )); - } + Some(code) => format!("[exit {code}]"), + None => format!( + "[killed by signal {}]", + status.signal().unwrap_or_default() + ), } + }; + + Ok(format_result( + &out_text, out_cut, &err_text, err_cut, &marker, + )) +} + +/// stdout and stderr are kept apart: a program that prints its real error to +/// stderr used to be indistinguishable from one that printed it to stdout. +/// Labelling only appears when it carries information. +fn format_result( + stdout: &str, + stdout_truncated: bool, + stderr: &str, + stderr_truncated: bool, + marker: &str, +) -> String { + let has_stdout = !stdout.trim().is_empty(); + let has_stderr = !stderr.trim().is_empty(); + + let mut out = String::new(); + if has_stdout && has_stderr { + out.push_str("[stdout]\n"); + out.push_str(stdout); + end_line(&mut out, stdout); + out.push_str("[stderr]\n"); + out.push_str(stderr); + end_line(&mut out, stderr); + } else if has_stderr { + out.push_str("[stderr]\n"); + out.push_str(stderr); + end_line(&mut out, stderr); + } else if has_stdout { + out.push_str(stdout); + end_line(&mut out, stdout); } - Ok(out) + + let truncated = stdout_truncated || stderr_truncated; + out.push_str(marker); + if truncated { + out.push_str(" (output truncated; raise max_bytes or narrow the command)"); + } + out +} + +fn end_line(out: &mut String, text: &str) { + if !text.is_empty() && !text.ends_with('\n') { + out.push('\n'); + } +} + +fn temp_path(kind: &str, serial: u64) -> PathBuf { + std::env::temp_dir().join(format!( + "agent686-{}-{}-{kind}.log", + std::process::id(), + serial + )) +} + +fn create(path: &PathBuf) -> Result { + std::fs::OpenOptions::new() + .read(true) + .write(true) + .create(true) + .truncate(true) + .open(path) + .map_err(|e| format!("{}: {e}", path.display())) } fn resolve_cwd(cwd: Option<&str>) -> Result { @@ -152,26 +215,32 @@ fn resolve_cwd(cwd: Option<&str>) -> Result { }) } -fn read_capped(file: &mut File) -> Result { +/// Reads at most `head` bytes from the start and `tail` from the end, noting +/// what was dropped. Returns the text and whether anything was cut. +fn read_capped(file: &mut File, head: usize, tail: usize) -> Result<(String, bool), String> { let len = file.metadata().map(|m| m.len()).unwrap_or(0); file.seek(SeekFrom::Start(0)).map_err(|e| e.to_string())?; - let mut out = Vec::new(); - if len <= HEAD_BYTES as u64 { - file.read_to_end(&mut out).map_err(|e| e.to_string())?; + let mut bytes = Vec::new(); + let mut truncated = false; + + if len <= (head + tail) as u64 { + file.read_to_end(&mut bytes).map_err(|e| e.to_string())?; } else { - file.take(HEAD_BYTES as u64) - .read_to_end(&mut out) + truncated = true; + file.take(head as u64) + .read_to_end(&mut bytes) .map_err(|e| e.to_string())?; - let omitted = len.saturating_sub(HEAD_BYTES as u64 + TAIL_BYTES as u64); - out.extend_from_slice(format!("\n… {omitted} bytes omitted …\n").as_bytes()); - file.seek(SeekFrom::End(-TAIL_BYTES)) + let omitted = len.saturating_sub(head as u64 + tail as u64); + bytes.extend_from_slice(format!("\n… {omitted} bytes omitted …\n").as_bytes()); + file.seek(SeekFrom::End(-(tail as i64))) .map_err(|e| e.to_string())?; - let mut tail = Vec::new(); - file.read_to_end(&mut tail).map_err(|e| e.to_string())?; - out.extend_from_slice(&tail); + let mut rest = Vec::new(); + file.read_to_end(&mut rest).map_err(|e| e.to_string())?; + bytes.extend_from_slice(&rest); } - Ok(String::from_utf8_lossy(&out).into_owned()) + + Ok((String::from_utf8_lossy(&bytes).into_owned(), truncated)) } /// SIGKILL the whole process group the command created. `child.kill()` would diff --git a/src/ui.rs b/src/ui.rs index 03e8dbe..fe0264b 100644 --- a/src/ui.rs +++ b/src/ui.rs @@ -109,7 +109,7 @@ impl Sink for Renderer { } } -pub fn tool_line(step: usize, name: &str, args: &serde_json::Value, include_detail: bool) { +pub fn tool_line(label: &str, name: &str, args: &serde_json::Value, include_detail: bool) { let detail = match name { "bash" => args .get("cmd") @@ -132,7 +132,7 @@ pub fn tool_line(step: usize, name: &str, args: &serde_json::Value, include_deta .unwrap_or("") .to_string(), }; - let head = paint("1;36", &format!("● [{step}] {name}")); + let head = paint("1;36", &format!("● [{label}] {name}")); if include_detail && !detail.is_empty() { println!("{head} {detail}"); } else { @@ -141,13 +141,18 @@ pub fn tool_line(step: usize, name: &str, args: &serde_json::Value, include_deta let _ = std::io::stdout().flush(); } -pub fn tool_result(summary: &str, aborted: bool) { +pub fn tool_result(label: &str, summary: &str, aborted: bool) { let text = if aborted { "aborted".to_string() } else { crate::provider::truncate(summary.trim(), 100) }; - println!(" {} {}", paint("2", "└"), paint("2", &text)); + println!( + " {} {} {}", + paint("2", &format!("[{label}] └")), + paint("2", &text), + "" + ); let _ = std::io::stdout().flush(); } diff --git a/tests/loop.rs b/tests/loop.rs index 4fc1da5..e913302 100644 --- a/tests/loop.rs +++ b/tests/loop.rs @@ -384,12 +384,12 @@ fn an_empty_bash_call_is_never_approved() { .expect("the turn should survive a malformed call"); let result = history[3]["content"].as_str().unwrap(); - assert!(result.contains("`cmd` is required"), "{result}"); + assert!(result.contains("`cmd` is present but empty"), "{result}"); assert!(!result.contains("denied"), "must not reach an approval prompt: {result}"); } #[test] -fn a_tool_call_with_no_arguments_is_dropped_silently() { +fn a_tool_call_with_no_arguments_is_reported_to_the_model() { let dir = temp_dir("placeholder"); let placeholder = sse(&format!( "data: {}\n\ndata: [DONE]\n\n", @@ -405,7 +405,12 @@ fn a_tool_call_with_no_arguments_is_dropped_silently() { }) )); - let base = serve_sequence(vec![placeholder]); + let final_round = sse( + "data: {\"choices\":[{\"delta\":{\"content\":\"ok\"},\"finish_reason\":\"stop\"}]}\n\n\ + data: [DONE]\n\n", + ); + + let base = serve_sequence(vec![placeholder, final_round]); std::env::set_var("AGENT686_DATA", dir.join("data")); let system = agent::system_prompt(); @@ -430,11 +435,62 @@ fn a_tool_call_with_no_arguments_is_dropped_silently() { ) .expect("a placeholder must not fail the turn"); - // system, user, assistant with the call removed: no tool message, no prompt. - assert_eq!(history.len(), 3, "{history:#?}"); - let assistant = history.last().unwrap(); - assert!( - assistant.get("tool_calls").is_none(), - "the placeholder must not be recorded: {assistant}" + // The named call is kept and answered, so the model can retry instead of + // silently losing it: system, user, assistant, tool, assistant. + assert_eq!(history.len(), 5, "{history:#?}"); + let result = history[3]["content"].as_str().unwrap(); + assert!(result.contains("no arguments at all"), "{result}"); + assert!(result.contains("retry"), "{result}"); +} + +#[test] +fn a_wrong_argument_key_names_both_keys() { + let dir = temp_dir("wrong-key"); + let call = sse(&format!( + "data: {}\n\ndata: [DONE]\n\n", + json!({ + "choices": [{ + "delta": { "tool_calls": [{ + "index": 0, + "id": "call_wrong", + "function": { "name": "bash", "arguments": "{\"command\":\"ls\"}" } + }]}, + "finish_reason": "tool_calls" + }] + }) + )); + let final_round = sse( + "data: {\"choices\":[{\"delta\":{\"content\":\"ok\"},\"finish_reason\":\"stop\"}]}\n\n\ + data: [DONE]\n\n", ); + + let base = serve_sequence(vec![call, final_round]); + std::env::set_var("AGENT686_DATA", dir.join("data")); + + let system = agent::system_prompt(); + let mut session = Session::create("test-model", &system).unwrap(); + let cfg = Config { + base_url: base, + api_key: "test-key".into(), + model: "test-model".into(), + session: session.id.clone(), + yolo: false, + }; + let mut history = agent::new_history(system); + let mut approver = Approver::new(false); + + agent::run_turn( + &cfg, + &mut session, + &mut history, + "run it", + &AtomicBool::new(false), + &mut approver, + ) + .expect("the turn should survive a wrong key"); + + let result = history[3]["content"].as_str().unwrap(); + assert!(result.contains("`command`"), "should name what arrived: {result}"); + assert!(result.contains("`cmd`"), "should name what was expected: {result}"); + assert!(!result.contains("denied"), "{result}"); } diff --git a/tests/tools.rs b/tests/tools.rs index a400df0..e54b5ff 100644 --- a/tests/tools.rs +++ b/tests/tools.rs @@ -434,3 +434,59 @@ fn validate_rejects_calls_that_cannot_run() { // Empty content is how you create an empty file. assert!(validate("write", &json!({ "path": "a", "content": "" })).is_ok()); } + +#[test] +fn bash_keeps_stderr_separate_from_stdout() { + let text = run( + "bash", + &json!({ "cmd": "printf 'out\\n'; printf 'err\\n' >&2; exit 2" }), + ) + .unwrap(); + + assert!(text.contains("[stdout]"), "{text}"); + assert!(text.contains("[stderr]"), "{text}"); + assert!(text.contains("[exit 2]"), "{text}"); + let stdout_at = text.find("[stdout]").unwrap(); + let stderr_at = text.find("[stderr]").unwrap(); + assert!(stdout_at < stderr_at, "{text}"); + assert!(text.contains("out"), "{text}"); + assert!(text.contains("err"), "{text}"); +} + +#[test] +fn bash_stdout_alone_is_not_labelled() { + let text = run("bash", &json!({ "cmd": "echo hello" })).unwrap(); + assert!(!text.contains("[stdout]"), "no label needed: {text}"); + assert!(text.contains("hello"), "{text}"); +} + +#[test] +fn bash_stderr_alone_is_labelled() { + let text = run("bash", &json!({ "cmd": "echo problem >&2" })).unwrap(); + assert!(text.contains("[stderr]"), "{text}"); + assert!(text.contains("problem"), "{text}"); +} + +#[test] +fn bash_honours_a_per_call_timeout() { + let started = std::time::Instant::now(); + let text = run( + "bash", + &json!({ "cmd": "sleep 5", "timeout_seconds": 1 }), + ) + .unwrap(); + assert!(text.contains("timed out after 1.0s"), "{text}"); + assert!(started.elapsed() < std::time::Duration::from_secs(4)); +} + +#[test] +fn bash_honours_a_per_call_output_budget() { + let text = run( + "bash", + &json!({ "cmd": "yes | head -c 200000", "max_bytes": 4096 }), + ) + .unwrap(); + assert!(text.contains("bytes omitted"), "{text}"); + assert!(text.contains("output truncated"), "{text}"); + assert!(text.len() < 10_000, "output was {} bytes", text.len()); +} -- cgit v1.2.3