From 84e70c0e73460e5db1297c47d02d9b76802bfdf7 Mon Sep 17 00:00:00 2001 From: salmonik Date: Wed, 18 Nov 2026 12:28:29 +0100 Subject: 0.9.1: correctness fixes from the audit - 64 MiB limit detected by file length, so pipelines and redirects are reported - bash temp files removed on every path via a scope guard - validate requires content/new as the schemas declare (present, may be empty) - Session::open folds in model-switch records; resume matches --list - combining mark at a wrap boundary no longer counts as a new row - --flag=value accepted; flag-shaped values rejected - dead code removed; last_reply folded into open (one read per resume) --- src/line.rs | 23 ++++++++++------- src/main.rs | 39 ++++++++++++++++++++++++---- src/session.rs | 75 +++++++++++++++++++++--------------------------------- src/signal.rs | 4 --- src/tools/mod.rs | 58 ++++++++++++++++++++++------------------- src/tools/shell.rs | 28 +++++++++++++++++--- 6 files changed, 133 insertions(+), 94 deletions(-) (limited to 'src') diff --git a/src/line.rs b/src/line.rs index 2b6c894..9877c48 100644 --- a/src/line.rs +++ b/src/line.rs @@ -65,7 +65,6 @@ impl Editor { let width = terminal_width(); let (cursor_row, _) = layout(prompt, &buffer, cursor, width); state.cursor_row = cursor_row; - state.rows = layout(prompt, &buffer, buffer.len(), width).0 + 1; } Event::Key(key) if key.kind == KeyEventKind::Press => { match handle_key(key, &mut buffer, &mut cursor, self) { @@ -271,17 +270,16 @@ fn layout(prompt: &str, buffer: &[char], upto: usize, width: usize) -> (usize, u pending_wrap = false; continue; } + let cells = cells(ch, col); + if cells == 0 { + // Combining marks draw on top of the previous cell and never wrap. + continue; + } if pending_wrap { row += 1; col = 0; pending_wrap = false; } - - let cells = cells(ch, col); - if cells == 0 { - // Combining marks draw on top of the previous cell. - continue; - } if col + cells > width { row += 1; col = 0; @@ -310,7 +308,6 @@ fn cells(ch: char, col: usize) -> usize { /// that row, not by the number of rows the block occupies. #[derive(Default, Clone, Copy)] struct DrawState { - rows: usize, cursor_row: usize, } @@ -358,7 +355,6 @@ fn draw_to( } execute!(out, MoveToColumn(clamp(cursor_col)))?; - state.rows = end_row + 1; state.cursor_row = cursor_row; Ok(()) } @@ -502,6 +498,15 @@ mod tests { ); } + #[test] + fn a_combining_mark_at_the_wrap_boundary_does_not_wrap() { + let text: Vec = ['a', 'b', '\u{0301}'].to_vec(); + // width 2: 'b' fills the last column (pending wrap), the mark must not + // consume that pending wrap and move to a new row. + let (row, col) = layout("", &text, 3, 2); + assert_eq!((row, col), (0, 1)); + } + #[test] fn layout_counts_wide_and_combining_characters() { let wide: Vec = "日本語".chars().collect(); diff --git a/src/main.rs b/src/main.rs index 45ca8c6..0e5d49a 100644 --- a/src/main.rs +++ b/src/main.rs @@ -93,6 +93,30 @@ fn parse_args() -> Result { words.push(arg); continue; } + // `--flag=value` form, so a value that begins with `-` is expressible. + if arg.starts_with('-') { + if let Some((flag, value)) = arg.split_once('=') { + match flag { + "-m" | "--model" => { + args.model = Some(value.to_string()); + continue; + } + "--base-url" => { + args.base_url = Some(value.to_string()); + continue; + } + "--session" | "--resume" => { + args.session = Some(value.to_string()); + continue; + } + "--show" => { + args.show = Some(Some(value.to_string())); + continue; + } + _ => return Err(format!("unknown flag {flag}\n\n{HELP}")), + } + } + } match arg.as_str() { "--" => literal = true, "-m" | "--model" => args.model = Some(take_value(&mut iter, "--model")?), @@ -147,8 +171,13 @@ fn parse_args() -> Result { fn take_value(iter: &mut impl Iterator, flag: &str) -> Result { match iter.next() { - Some(value) if !value.trim().is_empty() => Ok(value), - _ => Err(format!("{flag} needs a value")), + Some(value) + if !value.trim().is_empty() + && !(value.starts_with('-') && value.len() > 1) => + { + Ok(value) + } + _ => Err(format!("{flag} needs a value (use --{flag}=… for a value starting with -)")), } } @@ -207,7 +236,7 @@ fn run(args: Args) { warn_if_moved(&session); if resuming { - print_last_reply(&session.id); + print_last_reply(&session); } if !session.version.is_empty() && session.version != env!("CARGO_PKG_VERSION") { eprintln!( @@ -655,11 +684,11 @@ fn render_message(message: &Value, color: bool) -> String { /// On resume, show where the conversation left off: the last answer, or the last /// reasoning when the model never produced content. Only on a terminal, so piped /// runs stay clean. -fn print_last_reply(id: &str) { +fn print_last_reply(session: &Session) { if !std::io::stdout().is_terminal() { return; } - let Some(reply) = session::last_reply(id) else { + let Some(reply) = session.last_reply.as_ref() else { return; }; let text = if reply.content.trim().is_empty() { diff --git a/src/session.rs b/src/session.rs index a1da28f..881b1ed 100644 --- a/src/session.rs +++ b/src/session.rs @@ -68,6 +68,9 @@ pub struct Session { pub cwd: String, /// Harness version that created the session, for prefix-change warnings. pub version: String, + /// Last assistant block, for the resume banner. Computed during the same pass + /// that loads messages, so resume does not read the file twice. + pub last_reply: Option, path: PathBuf, file: File, } @@ -121,6 +124,7 @@ impl Session { model: model.to_string(), cwd, version: env!("CARGO_PKG_VERSION").to_string(), + last_reply: None, path, file, }) @@ -138,6 +142,8 @@ impl Session { let mut cwd = String::new(); let mut version = String::new(); let mut messages = Vec::new(); + let mut last_content: Option = None; + let mut last_reasoning: Option = None; for line in raw.split(|&byte| byte == b'\n') { if line.is_empty() { @@ -168,7 +174,29 @@ impl Session { version = v.to_string(); } } + Some("model") => { + if let Some(name) = value.get("model").and_then(|m| m.as_str()) { + model = name.to_string(); + } + } Some("msg") => { + if value.get("role").and_then(|r| r.as_str()) == Some("assistant") { + let content = value + .get("content") + .and_then(|c| c.as_str()) + .unwrap_or("") + .to_string(); + let reasoning = value + .get("_reasoning") + .and_then(|r| r.as_str()) + .unwrap_or("") + .to_string(); + if !content.trim().is_empty() { + last_content = Some(LastReply { content, reasoning }); + } else if !reasoning.trim().is_empty() { + last_reasoning = Some(LastReply { content, reasoning }); + } + } let mut message = value.clone(); if let Some(object) = message.as_object_mut() { object.remove("t"); @@ -194,6 +222,7 @@ impl Session { model, cwd, version, + last_reply: last_content.or(last_reasoning), path, file, }, @@ -237,52 +266,6 @@ pub struct LastReply { pub reasoning: String, } -/// The last thing the agent said, for the resume banner. Prefers a real answer; -/// falls back to reasoning when the last block had no content. -pub fn last_reply(id: &str) -> Option { - let raw = std::fs::read(sessions_dir().join(format!("{id}.jsonl"))).ok()?; - let mut with_content: Option = None; - let mut with_reasoning: Option = None; - - for line in raw.split(|&byte| byte == b'\n') { - if line.is_empty() { - continue; - } - let text = String::from_utf8_lossy(line); - let Ok(value) = serde_json::from_str::(&text) else { - continue; - }; - if value.get("role").and_then(|role| role.as_str()) != Some("assistant") { - continue; - } - let content = value - .get("content") - .and_then(|c| c.as_str()) - .unwrap_or("") - .to_string(); - let reasoning = value - .get("_reasoning") - .and_then(|r| r.as_str()) - .unwrap_or("") - .to_string(); - let reply = LastReply { - content, - reasoning, - }; - if !reply.content.trim().is_empty() { - with_content = Some(LastReply { - content: reply.content.clone(), - reasoning: reply.reasoning.clone(), - }); - } - if !reply.reasoning.trim().is_empty() { - with_reasoning = Some(reply); - } - } - - with_content.or(with_reasoning) -} - pub fn exists(id: &str) -> bool { sessions_dir().join(format!("{id}.jsonl")).is_file() } diff --git a/src/signal.rs b/src/signal.rs index 8705660..c11f078 100644 --- a/src/signal.rs +++ b/src/signal.rs @@ -17,7 +17,3 @@ pub fn install() { libc::signal(libc::SIGINT, handler as libc::sighandler_t); } } - -pub fn reset() { - CANCEL.store(false, Ordering::SeqCst); -} diff --git a/src/tools/mod.rs b/src/tools/mod.rs index 27840e9..7c6a921 100644 --- a/src/tools/mod.rs +++ b/src/tools/mod.rs @@ -24,13 +24,6 @@ pub fn approval(name: &str) -> Approval { } } -/// 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 { - 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 { @@ -55,32 +48,45 @@ fn received_keys(args: &Value) -> String { /// 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 required = |key: &str| match args.get(key).and_then(|value| value.as_str()) { + let missing = |key: &str| { + if args.as_object().map(|o| o.is_empty()).unwrap_or(true) { + 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 { + format!( + "missing `{key}`; received {}. The parameter is `{key}`", + received_keys(args) + ) + } + }; + // Must be present and non-blank. + let required_text = |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) - )) - } - } + None => Err(missing(key)), + }; + // Must be present, but may be the empty string (an empty file, a deletion). + let required_string = |key: &str| match args.get(key) { + Some(Value::String(_)) => Ok(()), + Some(_) => Err(format!("`{key}` must be a string")), + None => Err(missing(key)), }; match name { - "bash" => required("cmd"), - "read" | "write" => required("path"), + "bash" => required_text("cmd"), + "read" => required_text("path"), + "write" => { + required_text("path")?; + required_string("content") + } "edit" => { - required("path")?; - required("old") + required_text("path")?; + required_text("old")?; + required_string("new") } - "grep" | "glob" => required("pattern"), + "grep" | "glob" => required_text("pattern"), "" => Err("the tool call arrived without a tool name; it was probably truncated in transit — retry the call".into()), _ => Ok(()), } diff --git a/src/tools/shell.rs b/src/tools/shell.rs index 91f2dd9..c38f032 100644 --- a/src/tools/shell.rs +++ b/src/tools/shell.rs @@ -18,6 +18,20 @@ const MAX_FILE_BYTES: u64 = 64 * 1024 * 1024; static COUNTER: AtomicU64 = AtomicU64::new(0); +/// Removes both temp files when dropped, so an early `?` on the spawn/read paths +/// cannot leak `agent686-…-{out,err}.log` files into $TMPDIR. +struct TempGuard { + out: PathBuf, + err: PathBuf, +} + +impl Drop for TempGuard { + fn drop(&mut self) { + let _ = std::fs::remove_file(&self.out); + let _ = std::fs::remove_file(&self.err); + } +} + pub fn bash( args: &Value, timeout: Duration, @@ -44,6 +58,10 @@ pub fn bash( let serial = COUNTER.fetch_add(1, Ordering::Relaxed); let out_path = temp_path("out", serial); let err_path = temp_path("err", serial); + let _guard = TempGuard { + out: out_path.clone(), + err: err_path.clone(), + }; 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())?; @@ -104,15 +122,17 @@ pub fn bash( } }; - // A child that blew the file-size limit was killed by SIGXFSZ. - let over_limit = status.signal() == Some(libc::SIGXFSZ); + // SIGXFSZ lands on whichever process crossed the limit — usually a + // grandchild of `sh` — so `sh` exits 128+25 rather than being signalled. + // The reliable signal is the file itself having reached the limit. + let over_limit = status.signal() == Some(libc::SIGXFSZ) + || out_file.metadata().map(|m| m.len()).unwrap_or(0) >= MAX_FILE_BYTES + || err_file.metadata().map(|m| m.len()).unwrap_or(0) >= MAX_FILE_BYTES; 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 marker = if over_limit { format!( -- cgit v1.2.3