diff options
| -rw-r--r-- | CHANGELOG.md | 31 | ||||
| -rw-r--r-- | Cargo.lock | 2 | ||||
| -rw-r--r-- | Cargo.toml | 2 | ||||
| -rw-r--r-- | README.md | 7 | ||||
| -rw-r--r-- | src/agent.rs | 39 | ||||
| -rw-r--r-- | src/tools/mod.rs | 74 | ||||
| -rw-r--r-- | src/tools/shell.rs | 185 | ||||
| -rw-r--r-- | src/ui.rs | 13 | ||||
| -rw-r--r-- | tests/loop.rs | 74 | ||||
| -rw-r--r-- | 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. | |||
| 7 | file, and the tool schemas the model sees. Anything a script or a resumed session | 7 | file, and the tool schemas the model sees. Anything a script or a resumed session |
| 8 | could depend on counts as API. | 8 | could depend on counts as API. |
| 9 | 9 | ||
| 10 | ## 0.9.0 | ||
| 11 | |||
| 12 | Driven by a field report from a real task (porting a Neovim config to Helix). | ||
| 13 | The report's most expensive problem was not a missing feature: it was one error | ||
| 14 | message covering four different failures. | ||
| 15 | |||
| 16 | ### Added | ||
| 17 | - `bash` takes `timeout_seconds` (1-600, default 120) and `max_bytes` (per-stream | ||
| 18 | output budget, 1 KiB-16 MiB, default 80 KiB), so the limits are discoverable and | ||
| 19 | adjustable instead of only discoverable by exceeding them. | ||
| 20 | |||
| 21 | ### Changed | ||
| 22 | - `bash` keeps stdout and stderr apart. When both produce output they arrive in | ||
| 23 | labelled `[stdout]` / `[stderr]` sections; stderr alone is labelled; stdout | ||
| 24 | alone is unchanged. A real error printed to stderr can no longer hide inside | ||
| 25 | ordinary output. | ||
| 26 | - A truncated result says so on its final line, next to the exit status. | ||
| 27 | - Tool lines and results carry a per-call label (`[2.1]`, `[2.2]`) when several | ||
| 28 | calls run in one step, so a result is attributable without counting order. | ||
| 29 | |||
| 30 | ### Fixed | ||
| 31 | - The `cmd` validation error covered four distinct causes with one message, and | ||
| 32 | was false about two of them. It now distinguishes: the value is empty; the key | ||
| 33 | is missing and here is what you sent instead; or the call arrived with no | ||
| 34 | arguments at all, which points at argument loss in transit and suggests a | ||
| 35 | retry. | ||
| 36 | - A named call with no arguments is no longer dropped silently. The model is told | ||
| 37 | what arrived and can retry; only nameless calls are dropped, because they | ||
| 38 | cannot be replayed to the provider. | ||
| 39 | - Invalid JSON arguments report a preview of what arrived. | ||
| 40 | |||
| 10 | ## 0.8.2 | 41 | ## 0.8.2 |
| 11 | 42 | ||
| 12 | ### Changed | 43 | ### Changed |
| @@ -10,7 +10,7 @@ checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" | |||
| 10 | 10 | ||
| 11 | [[package]] | 11 | [[package]] |
| 12 | name = "agent686" | 12 | name = "agent686" |
| 13 | version = "0.8.2" | 13 | version = "0.9.0" |
| 14 | dependencies = [ | 14 | dependencies = [ |
| 15 | "crossterm", | 15 | "crossterm", |
| 16 | "libc", | 16 | "libc", |
| @@ -1,6 +1,6 @@ | |||
| 1 | [package] | 1 | [package] |
| 2 | name = "agent686" | 2 | name = "agent686" |
| 3 | version = "0.8.2" | 3 | version = "0.9.0" |
| 4 | edition = "2021" | 4 | edition = "2021" |
| 5 | description = "A small coding agent for a 32-bit Debian box" | 5 | description = "A small coding agent for a 32-bit Debian box" |
| 6 | publish = false | 6 | publish = false |
| @@ -64,9 +64,10 @@ honoured); a 429 that survives them explains itself instead of dumping JSON. | |||
| 64 | 64 | ||
| 65 | `read` (numbered lines, streamed, regular files only), `write` (atomic, never | 65 | `read` (numbered lines, streamed, regular files only), `write` (atomic, never |
| 66 | creates directories), `edit` (exact match that must be unique; CRLF files | 66 | creates directories), `edit` (exact match that must be unique; CRLF files |
| 67 | supported), `bash` (fresh shell per call, own process group, 120 s timeout, | 67 | supported), `bash` (fresh shell per call, own process group, stdout and stderr in |
| 68 | 64 MiB output limit), `grep` (regular expression; `fixed: true` for literals), | 68 | separate labelled sections, `timeout_seconds` and `max_bytes` per call), |
| 69 | `glob` (`*`, `?`, `**`, follows file symlinks). | 69 | `grep` (regular expression; `fixed: true` for literals), `glob` (`*`, `?`, `**`, |
| 70 | follows file symlinks). | ||
| 70 | 71 | ||
| 71 | Reads never prompt. The first `write`/`edit` of a session shows a diff and asks; | 72 | Reads never prompt. The first `write`/`edit` of a session shows a diff and asks; |
| 72 | answering `a` allows the rest of the process. Every `bash` call asks, because | 73 | 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( | |||
| 217 | Err(error) => return Err(error), | 217 | Err(error) => return Err(error), |
| 218 | }; | 218 | }; |
| 219 | 219 | ||
| 220 | // Placeholders are dropped before the assistant message is written: | 220 | // A call with no name cannot be replayed to the provider at all, so it |
| 221 | // recording a call we refuse to run would leave it unanswered. | 221 | // is dropped. A *named* call with no arguments is kept: the model is told |
| 222 | // what arrived and can retry, which is better than silence. | ||
| 222 | let before = outcome.tool_calls.len(); | 223 | let before = outcome.tool_calls.len(); |
| 223 | outcome | 224 | outcome.tool_calls.retain(|call| !call.name.trim().is_empty()); |
| 224 | .tool_calls | ||
| 225 | .retain(|call| !tools::is_placeholder(&call.arguments)); | ||
| 226 | if outcome.tool_calls.len() < before { | 225 | if outcome.tool_calls.len() < before { |
| 227 | eprintln!("agent686: ignored {} empty tool call(s) from the model", before - outcome.tool_calls.len()); | 226 | eprintln!( |
| 227 | "agent686: ignored {} tool call(s) with no name", | ||
| 228 | before - outcome.tool_calls.len() | ||
| 229 | ); | ||
| 228 | } | 230 | } |
| 229 | 231 | ||
| 230 | // A missing id would make the tool result unattachable. | 232 | // A missing id would make the tool result unattachable. |
| @@ -247,7 +249,15 @@ pub fn run_turn( | |||
| 247 | let calls = outcome.tool_calls.clone(); | 249 | let calls = outcome.tool_calls.clone(); |
| 248 | last = Some(outcome); | 250 | last = Some(outcome); |
| 249 | 251 | ||
| 250 | for call in calls { | 252 | let multiple = calls.len() > 1; |
| 253 | for (offset, call) in calls.into_iter().enumerate() { | ||
| 254 | // Thousands of steps are possible in a long turn; the label keeps | ||
| 255 | // each call's lines attributable when several run in one step. | ||
| 256 | let label = if multiple { | ||
| 257 | format!("{steps}.{}", offset + 1) | ||
| 258 | } else { | ||
| 259 | steps.to_string() | ||
| 260 | }; | ||
| 251 | // Cancelling between calls still has to answer every tool call the | 261 | // Cancelling between calls still has to answer every tool call the |
| 252 | // assistant message announced: an unanswered id makes the session | 262 | // assistant message announced: an unanswered id makes the session |
| 253 | // permanently unusable, because history is never rewritten. | 263 | // permanently unusable, because history is never rewritten. |
| @@ -257,7 +267,7 @@ pub fn run_turn( | |||
| 257 | let result = if aborted { | 267 | let result = if aborted { |
| 258 | ToolOutcome::Failed("aborted by the user before this call ran".into()) | 268 | ToolOutcome::Failed("aborted by the user before this call ran".into()) |
| 259 | } else { | 269 | } else { |
| 260 | execute(&call, approver, cancel, steps) | 270 | execute(&call, approver, cancel, &label) |
| 261 | }; | 271 | }; |
| 262 | if result.denied() { | 272 | if result.denied() { |
| 263 | denied += 1; | 273 | denied += 1; |
| @@ -269,7 +279,7 @@ pub fn run_turn( | |||
| 269 | _ => {} | 279 | _ => {} |
| 270 | } | 280 | } |
| 271 | } | 281 | } |
| 272 | ui::tool_result(&result.summary(), aborted); | 282 | ui::tool_result(&label, &result.summary(), aborted); |
| 273 | let message = json!({ | 283 | let message = json!({ |
| 274 | "role": "tool", | 284 | "role": "tool", |
| 275 | "tool_call_id": call.id, | 285 | "tool_call_id": call.id, |
| @@ -350,21 +360,22 @@ fn execute( | |||
| 350 | call: &provider::ToolCall, | 360 | call: &provider::ToolCall, |
| 351 | approver: &mut Approver, | 361 | approver: &mut Approver, |
| 352 | cancel: &AtomicBool, | 362 | cancel: &AtomicBool, |
| 353 | step: usize, | 363 | label: &str, |
| 354 | ) -> ToolOutcome { | 364 | ) -> ToolOutcome { |
| 355 | let args: Value = match serde_json::from_str(&call.arguments) { | 365 | let args: Value = match serde_json::from_str(&call.arguments) { |
| 356 | Ok(args) => args, | 366 | Ok(args) => args, |
| 357 | Err(error) => { | 367 | Err(error) => { |
| 368 | let raw = crate::provider::truncate(call.arguments.trim(), 200); | ||
| 358 | return ToolOutcome::Failed(format!( | 369 | return ToolOutcome::Failed(format!( |
| 359 | "arguments were not valid JSON ({error}); issue the call again with the \ | 370 | "arguments were not valid JSON ({error}). Received: {raw:?}. \ |
| 360 | complete arguments" | 371 | Issue the call again with complete arguments" |
| 361 | )) | 372 | )); |
| 362 | } | 373 | } |
| 363 | }; | 374 | }; |
| 364 | // The bash approval prompt prints the command; do not print it here too. | 375 | // The bash approval prompt prints the command; do not print it here too. |
| 365 | let repeat_detail = !(tools::approval(&call.name) == Approval::EveryCall | 376 | let repeat_detail = !(tools::approval(&call.name) == Approval::EveryCall |
| 366 | && approver.will_prompt_bash()); | 377 | && approver.will_prompt_bash()); |
| 367 | ui::tool_line(step, &call.name, &args, repeat_detail); | 378 | ui::tool_line(label, &call.name, &args, repeat_detail); |
| 368 | if let Err(error) = tools::validate(&call.name, &args) { | 379 | if let Err(error) = tools::validate(&call.name, &args) { |
| 369 | return ToolOutcome::Failed(format!("{error}; the call was not run")); | 380 | return ToolOutcome::Failed(format!("{error}; the call was not run")); |
| 370 | } | 381 | } |
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 { | |||
| 24 | } | 24 | } |
| 25 | } | 25 | } |
| 26 | 26 | ||
| 27 | /// A call with no arguments at all. Every tool here requires at least one, so | 27 | /// True when the call cannot be replayed as a real tool call at all: no name. |
| 28 | /// this is a placeholder some backends emit next to a real call, not an attempt. | 28 | /// (Named calls with no arguments are kept so the model can be told what went |
| 29 | /// wrong and retry.) | ||
| 29 | pub fn is_placeholder(arguments: &str) -> bool { | 30 | pub fn is_placeholder(arguments: &str) -> bool { |
| 30 | let trimmed = arguments.trim(); | 31 | arguments.trim().is_empty() |
| 31 | if trimmed.is_empty() { | 32 | } |
| 32 | return true; | 33 | |
| 34 | /// Returns the keys the model actually sent, quoted and bounded. | ||
| 35 | fn received_keys(args: &Value) -> String { | ||
| 36 | let Some(object) = args.as_object() else { | ||
| 37 | return "no arguments".to_string(); | ||
| 38 | }; | ||
| 39 | if object.is_empty() { | ||
| 40 | return "no arguments".to_string(); | ||
| 33 | } | 41 | } |
| 34 | matches!( | 42 | let mut keys: Vec<String> = object.keys().map(|key| format!("`{key}`")).collect(); |
| 35 | serde_json::from_str::<Value>(trimmed), | 43 | keys.sort(); |
| 36 | Ok(Value::Object(map)) if map.is_empty() | 44 | if keys.len() > 6 { |
| 37 | ) | 45 | keys.truncate(6); |
| 46 | keys.push("…".to_string()); | ||
| 47 | } | ||
| 48 | keys.join(", ") | ||
| 38 | } | 49 | } |
| 39 | 50 | ||
| 40 | /// Rejects a call that cannot possibly run, before a human is asked to approve | 51 | /// Rejects a call that cannot run, before a human is asked to approve it. |
| 41 | /// it. An empty `cmd` used to mean an approval prompt for `run: `. | 52 | /// |
| 53 | /// The message has to distinguish three different failures: the argument is | ||
| 54 | /// empty, the argument is missing because the key is wrong, and the call | ||
| 55 | /// arrived with no arguments at all (usually argument loss in transit). They | ||
| 56 | /// used to share one message, which pointed callers at the wrong fix. | ||
| 42 | pub fn validate(name: &str, args: &Value) -> Result<(), String> { | 57 | pub fn validate(name: &str, args: &Value) -> Result<(), String> { |
| 43 | let text = |key: &str| args.get(key).and_then(|value| value.as_str()).unwrap_or(""); | 58 | let required = |key: &str| match args.get(key).and_then(|value| value.as_str()) { |
| 44 | let required = |key: &str| { | 59 | Some(value) if !value.trim().is_empty() => Ok(()), |
| 45 | if text(key).trim().is_empty() { | 60 | Some(_) => Err(format!("`{key}` is present but empty")), |
| 46 | Err(format!("`{key}` is required and must not be empty")) | 61 | None => { |
| 47 | } else { | 62 | if args.as_object().map(|o| o.is_empty()).unwrap_or(true) { |
| 48 | Ok(()) | 63 | Err(format!( |
| 64 | "the call arrived with no arguments at all, so `{key}` is missing. \ | ||
| 65 | If you sent one, it was lost in transit — retry the call" | ||
| 66 | )) | ||
| 67 | } else { | ||
| 68 | Err(format!( | ||
| 69 | "missing `{key}`; received {}. The parameter is `{key}`", | ||
| 70 | received_keys(args) | ||
| 71 | )) | ||
| 72 | } | ||
| 49 | } | 73 | } |
| 50 | }; | 74 | }; |
| 51 | 75 | ||
| @@ -57,6 +81,7 @@ pub fn validate(name: &str, args: &Value) -> Result<(), String> { | |||
| 57 | required("old") | 81 | required("old") |
| 58 | } | 82 | } |
| 59 | "grep" | "glob" => required("pattern"), | 83 | "grep" | "glob" => required("pattern"), |
| 84 | "" => Err("the tool call arrived without a tool name; it was probably truncated in transit — retry the call".into()), | ||
| 60 | _ => Ok(()), | 85 | _ => Ok(()), |
| 61 | } | 86 | } |
| 62 | } | 87 | } |
| @@ -67,7 +92,14 @@ pub fn run(name: &str, args: &Value, cancel: &std::sync::atomic::AtomicBool) -> | |||
| 67 | "read" => fs::read(args), | 92 | "read" => fs::read(args), |
| 68 | "grep" => fs::grep(args), | 93 | "grep" => fs::grep(args), |
| 69 | "glob" => fs::glob(args), | 94 | "glob" => fs::glob(args), |
| 70 | "bash" => shell::bash(args, std::time::Duration::from_secs(120), cancel), | 95 | "bash" => { |
| 96 | let seconds = args | ||
| 97 | .get("timeout_seconds") | ||
| 98 | .and_then(|value| value.as_u64()) | ||
| 99 | .unwrap_or(120) | ||
| 100 | .clamp(1, 600); | ||
| 101 | shell::bash(args, std::time::Duration::from_secs(seconds), cancel) | ||
| 102 | } | ||
| 71 | other => Err(unknown(other)), | 103 | other => Err(unknown(other)), |
| 72 | } | 104 | } |
| 73 | } | 105 | } |
| @@ -139,12 +171,14 @@ pub fn schemas() -> Vec<Value> { | |||
| 139 | "type": "function", | 171 | "type": "function", |
| 140 | "function": { | 172 | "function": { |
| 141 | "name": "bash", | 173 | "name": "bash", |
| 142 | "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.", | 174 | "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.", |
| 143 | "parameters": { | 175 | "parameters": { |
| 144 | "type": "object", | 176 | "type": "object", |
| 145 | "properties": { | 177 | "properties": { |
| 146 | "cmd": { "type": "string" }, | 178 | "cmd": { "type": "string" }, |
| 147 | "cwd": { "type": "string", "description": "working directory (default: project root)" } | 179 | "cwd": { "type": "string", "description": "working directory (default: project root)" }, |
| 180 | "timeout_seconds": { "type": "integer", "description": "1-600, default 120" }, | ||
| 181 | "max_bytes": { "type": "integer", "description": "per-stream output budget, 1024-16777216, default 81920" } | ||
| 148 | }, | 182 | }, |
| 149 | "required": ["cmd"] | 183 | "required": ["cmd"] |
| 150 | } | 184 | } |
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}; | |||
| 8 | 8 | ||
| 9 | use serde_json::Value; | 9 | use serde_json::Value; |
| 10 | 10 | ||
| 11 | const HEAD_BYTES: usize = 64 * 1024; | 11 | /// Default budget per stream, split 4:1 between head and tail. |
| 12 | const TAIL_BYTES: i64 = 16 * 1024; | 12 | const DEFAULT_MAX_BYTES: usize = 80 * 1024; |
| 13 | /// The child cannot write more than this, so a runaway command cannot fill /tmp | 13 | const MIN_MAX_BYTES: usize = 1024; |
| 14 | /// and take the machine down with it. | 14 | const MAX_MAX_BYTES: usize = 16 * 1024 * 1024; |
| 15 | const MAX_OUTPUT_BYTES: u64 = 64 * 1024 * 1024; | 15 | /// The child cannot write more than this per stream, so a runaway command cannot |
| 16 | /// fill /tmp and take the machine down with it. | ||
| 17 | const MAX_FILE_BYTES: u64 = 64 * 1024 * 1024; | ||
| 18 | |||
| 16 | static COUNTER: AtomicU64 = AtomicU64::new(0); | 19 | static COUNTER: AtomicU64 = AtomicU64::new(0); |
| 17 | 20 | ||
| 18 | pub fn bash( | 21 | pub fn bash( |
| @@ -25,25 +28,26 @@ pub fn bash( | |||
| 25 | None => return Err("missing required argument `cmd`".into()), | 28 | None => return Err("missing required argument `cmd`".into()), |
| 26 | }; | 29 | }; |
| 27 | 30 | ||
| 31 | let max_bytes = args | ||
| 32 | .get("max_bytes") | ||
| 33 | .and_then(|value| value.as_u64()) | ||
| 34 | .unwrap_or(DEFAULT_MAX_BYTES as u64) | ||
| 35 | .clamp(MIN_MAX_BYTES as u64, MAX_MAX_BYTES as u64) as usize; | ||
| 36 | let head_budget = max_bytes * 4 / 5; | ||
| 37 | let tail_budget = max_bytes - head_budget; | ||
| 38 | |||
| 28 | let cwd = resolve_cwd(args.get("cwd").and_then(|v| v.as_str()))?; | 39 | let cwd = resolve_cwd(args.get("cwd").and_then(|v| v.as_str()))?; |
| 29 | if !cwd.is_dir() { | 40 | if !cwd.is_dir() { |
| 30 | return Err(format!("cwd is not a directory: {}", cwd.display())); | 41 | return Err(format!("cwd is not a directory: {}", cwd.display())); |
| 31 | } | 42 | } |
| 32 | 43 | ||
| 33 | let path = std::env::temp_dir().join(format!( | 44 | let serial = COUNTER.fetch_add(1, Ordering::Relaxed); |
| 34 | "agent686-{}-{}.out", | 45 | let out_path = temp_path("out", serial); |
| 35 | std::process::id(), | 46 | let err_path = temp_path("err", serial); |
| 36 | COUNTER.fetch_add(1, Ordering::Relaxed) | 47 | let mut out_file = create(&out_path)?; |
| 37 | )); | 48 | let mut err_file = create(&err_path)?; |
| 38 | let mut file = std::fs::OpenOptions::new() | 49 | let stdout = out_file.try_clone().map_err(|e| e.to_string())?; |
| 39 | .read(true) | 50 | let stderr = err_file.try_clone().map_err(|e| e.to_string())?; |
| 40 | .write(true) | ||
| 41 | .create(true) | ||
| 42 | .truncate(true) | ||
| 43 | .open(&path) | ||
| 44 | .map_err(|e| format!("{}: {e}", path.display()))?; | ||
| 45 | let stdout = file.try_clone().map_err(|e| e.to_string())?; | ||
| 46 | let stderr = file.try_clone().map_err(|e| e.to_string())?; | ||
| 47 | 51 | ||
| 48 | let mut command = Command::new("sh"); | 52 | let mut command = Command::new("sh"); |
| 49 | command | 53 | command |
| @@ -63,8 +67,8 @@ pub fn bash( | |||
| 63 | command.pre_exec(|| { | 67 | command.pre_exec(|| { |
| 64 | // rlim_t is u32 on i686 and u64 on x86-64. | 68 | // rlim_t is u32 on i686 and u64 on x86-64. |
| 65 | let limit = libc::rlimit { | 69 | let limit = libc::rlimit { |
| 66 | rlim_cur: MAX_OUTPUT_BYTES as libc::rlim_t, | 70 | rlim_cur: MAX_FILE_BYTES as libc::rlim_t, |
| 67 | rlim_max: MAX_OUTPUT_BYTES as libc::rlim_t, | 71 | rlim_max: MAX_FILE_BYTES as libc::rlim_t, |
| 68 | }; | 72 | }; |
| 69 | if libc::setrlimit(libc::RLIMIT_FSIZE, &limit) != 0 { | 73 | if libc::setrlimit(libc::RLIMIT_FSIZE, &limit) != 0 { |
| 70 | return Err(std::io::Error::last_os_error()); | 74 | return Err(std::io::Error::last_os_error()); |
| @@ -103,38 +107,97 @@ pub fn bash( | |||
| 103 | // A child that blew the file-size limit was killed by SIGXFSZ. | 107 | // A child that blew the file-size limit was killed by SIGXFSZ. |
| 104 | let over_limit = status.signal() == Some(libc::SIGXFSZ); | 108 | let over_limit = status.signal() == Some(libc::SIGXFSZ); |
| 105 | 109 | ||
| 106 | let output = read_capped(&mut file).map_err(|e| format!("could not read output: {e}"))?; | 110 | let (out_text, out_cut) = read_capped(&mut out_file, head_budget, tail_budget)?; |
| 107 | drop(file); | 111 | let (err_text, err_cut) = read_capped(&mut err_file, head_budget, tail_budget)?; |
| 108 | let _ = std::fs::remove_file(&path); | 112 | drop(out_file); |
| 113 | drop(err_file); | ||
| 114 | let _ = std::fs::remove_file(&out_path); | ||
| 115 | let _ = std::fs::remove_file(&err_path); | ||
| 109 | 116 | ||
| 110 | let mut out = output; | 117 | let marker = if over_limit { |
| 111 | if !out.is_empty() && !out.ends_with('\n') { | 118 | format!( |
| 112 | out.push('\n'); | ||
| 113 | } | ||
| 114 | if over_limit { | ||
| 115 | out.push_str(&format!( | ||
| 116 | "[output exceeded {} MiB; command killed]", | 119 | "[output exceeded {} MiB; command killed]", |
| 117 | MAX_OUTPUT_BYTES / (1024 * 1024) | 120 | MAX_FILE_BYTES / (1024 * 1024) |
| 118 | )); | 121 | ) |
| 119 | } else if aborted { | 122 | } else if aborted { |
| 120 | out.push_str("[aborted by the user]"); | 123 | "[aborted by the user]".to_string() |
| 121 | } else if timed_out { | 124 | } else if timed_out { |
| 122 | out.push_str(&format!( | 125 | format!("[timed out after {:.1}s; process killed]", timeout.as_secs_f64()) |
| 123 | "[timed out after {:.1}s; process killed]", | ||
| 124 | timeout.as_secs_f64() | ||
| 125 | )); | ||
| 126 | } else { | 126 | } else { |
| 127 | match status.code() { | 127 | match status.code() { |
| 128 | Some(code) => out.push_str(&format!("[exit {code}]")), | 128 | Some(code) => format!("[exit {code}]"), |
| 129 | None => { | 129 | None => format!( |
| 130 | out.push_str(&format!( | 130 | "[killed by signal {}]", |
| 131 | "[killed by signal {}]", | 131 | status.signal().unwrap_or_default() |
| 132 | status.signal().unwrap_or_default() | 132 | ), |
| 133 | )); | ||
| 134 | } | ||
| 135 | } | 133 | } |
| 134 | }; | ||
| 135 | |||
| 136 | Ok(format_result( | ||
| 137 | &out_text, out_cut, &err_text, err_cut, &marker, | ||
| 138 | )) | ||
| 139 | } | ||
| 140 | |||
| 141 | /// stdout and stderr are kept apart: a program that prints its real error to | ||
| 142 | /// stderr used to be indistinguishable from one that printed it to stdout. | ||
| 143 | /// Labelling only appears when it carries information. | ||
| 144 | fn format_result( | ||
| 145 | stdout: &str, | ||
| 146 | stdout_truncated: bool, | ||
| 147 | stderr: &str, | ||
| 148 | stderr_truncated: bool, | ||
| 149 | marker: &str, | ||
| 150 | ) -> String { | ||
| 151 | let has_stdout = !stdout.trim().is_empty(); | ||
| 152 | let has_stderr = !stderr.trim().is_empty(); | ||
| 153 | |||
| 154 | let mut out = String::new(); | ||
| 155 | if has_stdout && has_stderr { | ||
| 156 | out.push_str("[stdout]\n"); | ||
| 157 | out.push_str(stdout); | ||
| 158 | end_line(&mut out, stdout); | ||
| 159 | out.push_str("[stderr]\n"); | ||
| 160 | out.push_str(stderr); | ||
| 161 | end_line(&mut out, stderr); | ||
| 162 | } else if has_stderr { | ||
| 163 | out.push_str("[stderr]\n"); | ||
| 164 | out.push_str(stderr); | ||
| 165 | end_line(&mut out, stderr); | ||
| 166 | } else if has_stdout { | ||
| 167 | out.push_str(stdout); | ||
| 168 | end_line(&mut out, stdout); | ||
| 136 | } | 169 | } |
| 137 | Ok(out) | 170 | |
| 171 | let truncated = stdout_truncated || stderr_truncated; | ||
| 172 | out.push_str(marker); | ||
| 173 | if truncated { | ||
| 174 | out.push_str(" (output truncated; raise max_bytes or narrow the command)"); | ||
| 175 | } | ||
| 176 | out | ||
| 177 | } | ||
| 178 | |||
| 179 | fn end_line(out: &mut String, text: &str) { | ||
| 180 | if !text.is_empty() && !text.ends_with('\n') { | ||
| 181 | out.push('\n'); | ||
| 182 | } | ||
| 183 | } | ||
| 184 | |||
| 185 | fn temp_path(kind: &str, serial: u64) -> PathBuf { | ||
| 186 | std::env::temp_dir().join(format!( | ||
| 187 | "agent686-{}-{}-{kind}.log", | ||
| 188 | std::process::id(), | ||
| 189 | serial | ||
| 190 | )) | ||
| 191 | } | ||
| 192 | |||
| 193 | fn create(path: &PathBuf) -> Result<File, String> { | ||
| 194 | std::fs::OpenOptions::new() | ||
| 195 | .read(true) | ||
| 196 | .write(true) | ||
| 197 | .create(true) | ||
| 198 | .truncate(true) | ||
| 199 | .open(path) | ||
| 200 | .map_err(|e| format!("{}: {e}", path.display())) | ||
| 138 | } | 201 | } |
| 139 | 202 | ||
| 140 | fn resolve_cwd(cwd: Option<&str>) -> Result<PathBuf, String> { | 203 | fn resolve_cwd(cwd: Option<&str>) -> Result<PathBuf, String> { |
| @@ -152,26 +215,32 @@ fn resolve_cwd(cwd: Option<&str>) -> Result<PathBuf, String> { | |||
| 152 | }) | 215 | }) |
| 153 | } | 216 | } |
| 154 | 217 | ||
| 155 | fn read_capped(file: &mut File) -> Result<String, String> { | 218 | /// Reads at most `head` bytes from the start and `tail` from the end, noting |
| 219 | /// what was dropped. Returns the text and whether anything was cut. | ||
| 220 | fn read_capped(file: &mut File, head: usize, tail: usize) -> Result<(String, bool), String> { | ||
| 156 | let len = file.metadata().map(|m| m.len()).unwrap_or(0); | 221 | let len = file.metadata().map(|m| m.len()).unwrap_or(0); |
| 157 | file.seek(SeekFrom::Start(0)).map_err(|e| e.to_string())?; | 222 | file.seek(SeekFrom::Start(0)).map_err(|e| e.to_string())?; |
| 158 | 223 | ||
| 159 | let mut out = Vec::new(); | 224 | let mut bytes = Vec::new(); |
| 160 | if len <= HEAD_BYTES as u64 { | 225 | let mut truncated = false; |
| 161 | file.read_to_end(&mut out).map_err(|e| e.to_string())?; | 226 | |
| 227 | if len <= (head + tail) as u64 { | ||
| 228 | file.read_to_end(&mut bytes).map_err(|e| e.to_string())?; | ||
| 162 | } else { | 229 | } else { |
| 163 | file.take(HEAD_BYTES as u64) | 230 | truncated = true; |
| 164 | .read_to_end(&mut out) | 231 | file.take(head as u64) |
| 232 | .read_to_end(&mut bytes) | ||
| 165 | .map_err(|e| e.to_string())?; | 233 | .map_err(|e| e.to_string())?; |
| 166 | let omitted = len.saturating_sub(HEAD_BYTES as u64 + TAIL_BYTES as u64); | 234 | let omitted = len.saturating_sub(head as u64 + tail as u64); |
| 167 | out.extend_from_slice(format!("\n… {omitted} bytes omitted …\n").as_bytes()); | 235 | bytes.extend_from_slice(format!("\n… {omitted} bytes omitted …\n").as_bytes()); |
| 168 | file.seek(SeekFrom::End(-TAIL_BYTES)) | 236 | file.seek(SeekFrom::End(-(tail as i64))) |
| 169 | .map_err(|e| e.to_string())?; | 237 | .map_err(|e| e.to_string())?; |
| 170 | let mut tail = Vec::new(); | 238 | let mut rest = Vec::new(); |
| 171 | file.read_to_end(&mut tail).map_err(|e| e.to_string())?; | 239 | file.read_to_end(&mut rest).map_err(|e| e.to_string())?; |
| 172 | out.extend_from_slice(&tail); | 240 | bytes.extend_from_slice(&rest); |
| 173 | } | 241 | } |
| 174 | Ok(String::from_utf8_lossy(&out).into_owned()) | 242 | |
| 243 | Ok((String::from_utf8_lossy(&bytes).into_owned(), truncated)) | ||
| 175 | } | 244 | } |
| 176 | 245 | ||
| 177 | /// SIGKILL the whole process group the command created. `child.kill()` would | 246 | /// SIGKILL the whole process group the command created. `child.kill()` would |
| @@ -109,7 +109,7 @@ impl<W: Write> Sink for Renderer<W> { | |||
| 109 | } | 109 | } |
| 110 | } | 110 | } |
| 111 | 111 | ||
| 112 | pub fn tool_line(step: usize, name: &str, args: &serde_json::Value, include_detail: bool) { | 112 | pub fn tool_line(label: &str, name: &str, args: &serde_json::Value, include_detail: bool) { |
| 113 | let detail = match name { | 113 | let detail = match name { |
| 114 | "bash" => args | 114 | "bash" => args |
| 115 | .get("cmd") | 115 | .get("cmd") |
| @@ -132,7 +132,7 @@ pub fn tool_line(step: usize, name: &str, args: &serde_json::Value, include_deta | |||
| 132 | .unwrap_or("") | 132 | .unwrap_or("") |
| 133 | .to_string(), | 133 | .to_string(), |
| 134 | }; | 134 | }; |
| 135 | let head = paint("1;36", &format!("● [{step}] {name}")); | 135 | let head = paint("1;36", &format!("● [{label}] {name}")); |
| 136 | if include_detail && !detail.is_empty() { | 136 | if include_detail && !detail.is_empty() { |
| 137 | println!("{head} {detail}"); | 137 | println!("{head} {detail}"); |
| 138 | } else { | 138 | } else { |
| @@ -141,13 +141,18 @@ pub fn tool_line(step: usize, name: &str, args: &serde_json::Value, include_deta | |||
| 141 | let _ = std::io::stdout().flush(); | 141 | let _ = std::io::stdout().flush(); |
| 142 | } | 142 | } |
| 143 | 143 | ||
| 144 | pub fn tool_result(summary: &str, aborted: bool) { | 144 | pub fn tool_result(label: &str, summary: &str, aborted: bool) { |
| 145 | let text = if aborted { | 145 | let text = if aborted { |
| 146 | "aborted".to_string() | 146 | "aborted".to_string() |
| 147 | } else { | 147 | } else { |
| 148 | crate::provider::truncate(summary.trim(), 100) | 148 | crate::provider::truncate(summary.trim(), 100) |
| 149 | }; | 149 | }; |
| 150 | println!(" {} {}", paint("2", "└"), paint("2", &text)); | 150 | println!( |
| 151 | " {} {} {}", | ||
| 152 | paint("2", &format!("[{label}] └")), | ||
| 153 | paint("2", &text), | ||
| 154 | "" | ||
| 155 | ); | ||
| 151 | let _ = std::io::stdout().flush(); | 156 | let _ = std::io::stdout().flush(); |
| 152 | } | 157 | } |
| 153 | 158 | ||
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() { | |||
| 384 | .expect("the turn should survive a malformed call"); | 384 | .expect("the turn should survive a malformed call"); |
| 385 | 385 | ||
| 386 | let result = history[3]["content"].as_str().unwrap(); | 386 | let result = history[3]["content"].as_str().unwrap(); |
| 387 | assert!(result.contains("`cmd` is required"), "{result}"); | 387 | assert!(result.contains("`cmd` is present but empty"), "{result}"); |
| 388 | assert!(!result.contains("denied"), "must not reach an approval prompt: {result}"); | 388 | assert!(!result.contains("denied"), "must not reach an approval prompt: {result}"); |
| 389 | } | 389 | } |
| 390 | 390 | ||
| 391 | #[test] | 391 | #[test] |
| 392 | fn a_tool_call_with_no_arguments_is_dropped_silently() { | 392 | fn a_tool_call_with_no_arguments_is_reported_to_the_model() { |
| 393 | let dir = temp_dir("placeholder"); | 393 | let dir = temp_dir("placeholder"); |
| 394 | let placeholder = sse(&format!( | 394 | let placeholder = sse(&format!( |
| 395 | "data: {}\n\ndata: [DONE]\n\n", | 395 | "data: {}\n\ndata: [DONE]\n\n", |
| @@ -405,7 +405,12 @@ fn a_tool_call_with_no_arguments_is_dropped_silently() { | |||
| 405 | }) | 405 | }) |
| 406 | )); | 406 | )); |
| 407 | 407 | ||
| 408 | let base = serve_sequence(vec![placeholder]); | 408 | let final_round = sse( |
| 409 | "data: {\"choices\":[{\"delta\":{\"content\":\"ok\"},\"finish_reason\":\"stop\"}]}\n\n\ | ||
| 410 | data: [DONE]\n\n", | ||
| 411 | ); | ||
| 412 | |||
| 413 | let base = serve_sequence(vec![placeholder, final_round]); | ||
| 409 | std::env::set_var("AGENT686_DATA", dir.join("data")); | 414 | std::env::set_var("AGENT686_DATA", dir.join("data")); |
| 410 | 415 | ||
| 411 | let system = agent::system_prompt(); | 416 | let system = agent::system_prompt(); |
| @@ -430,11 +435,62 @@ fn a_tool_call_with_no_arguments_is_dropped_silently() { | |||
| 430 | ) | 435 | ) |
| 431 | .expect("a placeholder must not fail the turn"); | 436 | .expect("a placeholder must not fail the turn"); |
| 432 | 437 | ||
| 433 | // system, user, assistant with the call removed: no tool message, no prompt. | 438 | // The named call is kept and answered, so the model can retry instead of |
| 434 | assert_eq!(history.len(), 3, "{history:#?}"); | 439 | // silently losing it: system, user, assistant, tool, assistant. |
| 435 | let assistant = history.last().unwrap(); | 440 | assert_eq!(history.len(), 5, "{history:#?}"); |
| 436 | assert!( | 441 | let result = history[3]["content"].as_str().unwrap(); |
| 437 | assistant.get("tool_calls").is_none(), | 442 | assert!(result.contains("no arguments at all"), "{result}"); |
| 438 | "the placeholder must not be recorded: {assistant}" | 443 | assert!(result.contains("retry"), "{result}"); |
| 444 | } | ||
| 445 | |||
| 446 | #[test] | ||
| 447 | fn a_wrong_argument_key_names_both_keys() { | ||
| 448 | let dir = temp_dir("wrong-key"); | ||
| 449 | let call = sse(&format!( | ||
| 450 | "data: {}\n\ndata: [DONE]\n\n", | ||
| 451 | json!({ | ||
| 452 | "choices": [{ | ||
| 453 | "delta": { "tool_calls": [{ | ||
| 454 | "index": 0, | ||
| 455 | "id": "call_wrong", | ||
| 456 | "function": { "name": "bash", "arguments": "{\"command\":\"ls\"}" } | ||
| 457 | }]}, | ||
| 458 | "finish_reason": "tool_calls" | ||
| 459 | }] | ||
| 460 | }) | ||
| 461 | )); | ||
| 462 | let final_round = sse( | ||
| 463 | "data: {\"choices\":[{\"delta\":{\"content\":\"ok\"},\"finish_reason\":\"stop\"}]}\n\n\ | ||
| 464 | data: [DONE]\n\n", | ||
| 439 | ); | 465 | ); |
| 466 | |||
| 467 | let base = serve_sequence(vec![call, final_round]); | ||
| 468 | std::env::set_var("AGENT686_DATA", dir.join("data")); | ||
| 469 | |||
| 470 | let system = agent::system_prompt(); | ||
| 471 | let mut session = Session::create("test-model", &system).unwrap(); | ||
| 472 | let cfg = Config { | ||
| 473 | base_url: base, | ||
| 474 | api_key: "test-key".into(), | ||
| 475 | model: "test-model".into(), | ||
| 476 | session: session.id.clone(), | ||
| 477 | yolo: false, | ||
| 478 | }; | ||
| 479 | let mut history = agent::new_history(system); | ||
| 480 | let mut approver = Approver::new(false); | ||
| 481 | |||
| 482 | agent::run_turn( | ||
| 483 | &cfg, | ||
| 484 | &mut session, | ||
| 485 | &mut history, | ||
| 486 | "run it", | ||
| 487 | &AtomicBool::new(false), | ||
| 488 | &mut approver, | ||
| 489 | ) | ||
| 490 | .expect("the turn should survive a wrong key"); | ||
| 491 | |||
| 492 | let result = history[3]["content"].as_str().unwrap(); | ||
| 493 | assert!(result.contains("`command`"), "should name what arrived: {result}"); | ||
| 494 | assert!(result.contains("`cmd`"), "should name what was expected: {result}"); | ||
| 495 | assert!(!result.contains("denied"), "{result}"); | ||
| 440 | } | 496 | } |
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() { | |||
| 434 | // Empty content is how you create an empty file. | 434 | // Empty content is how you create an empty file. |
| 435 | assert!(validate("write", &json!({ "path": "a", "content": "" })).is_ok()); | 435 | assert!(validate("write", &json!({ "path": "a", "content": "" })).is_ok()); |
| 436 | } | 436 | } |
| 437 | |||
| 438 | #[test] | ||
| 439 | fn bash_keeps_stderr_separate_from_stdout() { | ||
| 440 | let text = run( | ||
| 441 | "bash", | ||
| 442 | &json!({ "cmd": "printf 'out\\n'; printf 'err\\n' >&2; exit 2" }), | ||
| 443 | ) | ||
| 444 | .unwrap(); | ||
| 445 | |||
| 446 | assert!(text.contains("[stdout]"), "{text}"); | ||
| 447 | assert!(text.contains("[stderr]"), "{text}"); | ||
| 448 | assert!(text.contains("[exit 2]"), "{text}"); | ||
| 449 | let stdout_at = text.find("[stdout]").unwrap(); | ||
| 450 | let stderr_at = text.find("[stderr]").unwrap(); | ||
| 451 | assert!(stdout_at < stderr_at, "{text}"); | ||
| 452 | assert!(text.contains("out"), "{text}"); | ||
| 453 | assert!(text.contains("err"), "{text}"); | ||
| 454 | } | ||
| 455 | |||
| 456 | #[test] | ||
| 457 | fn bash_stdout_alone_is_not_labelled() { | ||
| 458 | let text = run("bash", &json!({ "cmd": "echo hello" })).unwrap(); | ||
| 459 | assert!(!text.contains("[stdout]"), "no label needed: {text}"); | ||
| 460 | assert!(text.contains("hello"), "{text}"); | ||
| 461 | } | ||
| 462 | |||
| 463 | #[test] | ||
| 464 | fn bash_stderr_alone_is_labelled() { | ||
| 465 | let text = run("bash", &json!({ "cmd": "echo problem >&2" })).unwrap(); | ||
| 466 | assert!(text.contains("[stderr]"), "{text}"); | ||
| 467 | assert!(text.contains("problem"), "{text}"); | ||
| 468 | } | ||
| 469 | |||
| 470 | #[test] | ||
| 471 | fn bash_honours_a_per_call_timeout() { | ||
| 472 | let started = std::time::Instant::now(); | ||
| 473 | let text = run( | ||
| 474 | "bash", | ||
| 475 | &json!({ "cmd": "sleep 5", "timeout_seconds": 1 }), | ||
| 476 | ) | ||
| 477 | .unwrap(); | ||
| 478 | assert!(text.contains("timed out after 1.0s"), "{text}"); | ||
| 479 | assert!(started.elapsed() < std::time::Duration::from_secs(4)); | ||
| 480 | } | ||
| 481 | |||
| 482 | #[test] | ||
| 483 | fn bash_honours_a_per_call_output_budget() { | ||
| 484 | let text = run( | ||
| 485 | "bash", | ||
| 486 | &json!({ "cmd": "yes | head -c 200000", "max_bytes": 4096 }), | ||
| 487 | ) | ||
| 488 | .unwrap(); | ||
| 489 | assert!(text.contains("bytes omitted"), "{text}"); | ||
| 490 | assert!(text.contains("output truncated"), "{text}"); | ||
| 491 | assert!(text.len() < 10_000, "output was {} bytes", text.len()); | ||
| 492 | } | ||
