diff options
Diffstat (limited to '')
| -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 |
4 files changed, 215 insertions, 96 deletions
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 | ||
