diff options
| -rw-r--r-- | CHANGELOG.md | 22 | ||||
| -rw-r--r-- | Cargo.toml | 2 | ||||
| -rw-r--r-- | src/line.rs | 23 | ||||
| -rw-r--r-- | src/main.rs | 39 | ||||
| -rw-r--r-- | src/session.rs | 75 | ||||
| -rw-r--r-- | src/signal.rs | 4 | ||||
| -rw-r--r-- | src/tools/mod.rs | 58 | ||||
| -rw-r--r-- | src/tools/shell.rs | 28 | ||||
| -rw-r--r-- | tests/cli.rs | 25 | ||||
| -rw-r--r-- | tests/sessions.rs | 8 | ||||
| -rw-r--r-- | tests/tools.rs | 27 |
11 files changed, 214 insertions, 97 deletions
diff --git a/CHANGELOG.md b/CHANGELOG.md index be3c6b8..d9e3d09 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md | |||
| @@ -7,6 +7,28 @@ 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.1 | ||
| 11 | |||
| 12 | ### Fixed | ||
| 13 | - The 64 MiB output limit went unreported when a pipeline or redirect overflowed | ||
| 14 | via a grandchild of `sh` (which exits 128+25 instead of being signalled). | ||
| 15 | Detection now checks the output file's size, not just the child's signal. | ||
| 16 | - `bash` temp files leaked on spawn/clone/read error paths; a scope guard removes | ||
| 17 | them on every path. | ||
| 18 | - `validate` did not require `content`/`new` that the tool schemas declare | ||
| 19 | required; a `write` without `content` or an `edit` without `new` fell through to | ||
| 20 | a generic message. Both are now required (present, but may be empty). | ||
| 21 | - Resuming a session ignored `model` switch records, so the "session used A, | ||
| 22 | continuing with B" warning was suppressed and `--list` disagreed with resume. | ||
| 23 | - A combining mark after a character that filled the last terminal column was | ||
| 24 | counted as wrapping to a new row; it now stays on the prior cell. | ||
| 25 | - `--session --list` swallowed `--list` as the id. Flag-shaped values are | ||
| 26 | rejected, and every value flag now accepts `--flag=value` (so `--session=-abc` | ||
| 27 | works). | ||
| 28 | - Removed dead code (`is_placeholder`, `signal::reset`, `DrawState.rows`) and | ||
| 29 | folded the standalone `last_reply` into `Session::open`, so resume no longer | ||
| 30 | reads the transcript twice. | ||
| 31 | |||
| 10 | ## 0.9.0 | 32 | ## 0.9.0 |
| 11 | 33 | ||
| 12 | Driven by a field report from a real task (porting a Neovim config to Helix). | 34 | Driven by a field report from a real task (porting a Neovim config to Helix). |
| @@ -1,6 +1,6 @@ | |||
| 1 | [package] | 1 | [package] |
| 2 | name = "agent686" | 2 | name = "agent686" |
| 3 | version = "0.9.0" | 3 | version = "0.9.1" |
| 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 |
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 { | |||
| 65 | let width = terminal_width(); | 65 | let width = terminal_width(); |
| 66 | let (cursor_row, _) = layout(prompt, &buffer, cursor, width); | 66 | let (cursor_row, _) = layout(prompt, &buffer, cursor, width); |
| 67 | state.cursor_row = cursor_row; | 67 | state.cursor_row = cursor_row; |
| 68 | state.rows = layout(prompt, &buffer, buffer.len(), width).0 + 1; | ||
| 69 | } | 68 | } |
| 70 | Event::Key(key) if key.kind == KeyEventKind::Press => { | 69 | Event::Key(key) if key.kind == KeyEventKind::Press => { |
| 71 | match handle_key(key, &mut buffer, &mut cursor, self) { | 70 | 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 | |||
| 271 | pending_wrap = false; | 270 | pending_wrap = false; |
| 272 | continue; | 271 | continue; |
| 273 | } | 272 | } |
| 273 | let cells = cells(ch, col); | ||
| 274 | if cells == 0 { | ||
| 275 | // Combining marks draw on top of the previous cell and never wrap. | ||
| 276 | continue; | ||
| 277 | } | ||
| 274 | if pending_wrap { | 278 | if pending_wrap { |
| 275 | row += 1; | 279 | row += 1; |
| 276 | col = 0; | 280 | col = 0; |
| 277 | pending_wrap = false; | 281 | pending_wrap = false; |
| 278 | } | 282 | } |
| 279 | |||
| 280 | let cells = cells(ch, col); | ||
| 281 | if cells == 0 { | ||
| 282 | // Combining marks draw on top of the previous cell. | ||
| 283 | continue; | ||
| 284 | } | ||
| 285 | if col + cells > width { | 283 | if col + cells > width { |
| 286 | row += 1; | 284 | row += 1; |
| 287 | col = 0; | 285 | col = 0; |
| @@ -310,7 +308,6 @@ fn cells(ch: char, col: usize) -> usize { | |||
| 310 | /// that row, not by the number of rows the block occupies. | 308 | /// that row, not by the number of rows the block occupies. |
| 311 | #[derive(Default, Clone, Copy)] | 309 | #[derive(Default, Clone, Copy)] |
| 312 | struct DrawState { | 310 | struct DrawState { |
| 313 | rows: usize, | ||
| 314 | cursor_row: usize, | 311 | cursor_row: usize, |
| 315 | } | 312 | } |
| 316 | 313 | ||
| @@ -358,7 +355,6 @@ fn draw_to<W: Write>( | |||
| 358 | } | 355 | } |
| 359 | execute!(out, MoveToColumn(clamp(cursor_col)))?; | 356 | execute!(out, MoveToColumn(clamp(cursor_col)))?; |
| 360 | 357 | ||
| 361 | state.rows = end_row + 1; | ||
| 362 | state.cursor_row = cursor_row; | 358 | state.cursor_row = cursor_row; |
| 363 | Ok(()) | 359 | Ok(()) |
| 364 | } | 360 | } |
| @@ -503,6 +499,15 @@ mod tests { | |||
| 503 | } | 499 | } |
| 504 | 500 | ||
| 505 | #[test] | 501 | #[test] |
| 502 | fn a_combining_mark_at_the_wrap_boundary_does_not_wrap() { | ||
| 503 | let text: Vec<char> = ['a', 'b', '\u{0301}'].to_vec(); | ||
| 504 | // width 2: 'b' fills the last column (pending wrap), the mark must not | ||
| 505 | // consume that pending wrap and move to a new row. | ||
| 506 | let (row, col) = layout("", &text, 3, 2); | ||
| 507 | assert_eq!((row, col), (0, 1)); | ||
| 508 | } | ||
| 509 | |||
| 510 | #[test] | ||
| 506 | fn layout_counts_wide_and_combining_characters() { | 511 | fn layout_counts_wide_and_combining_characters() { |
| 507 | let wide: Vec<char> = "日本語".chars().collect(); | 512 | let wide: Vec<char> = "日本語".chars().collect(); |
| 508 | assert_eq!(layout("> ", &wide, 3, 20), (0, 8)); | 513 | assert_eq!(layout("> ", &wide, 3, 20), (0, 8)); |
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<Args, String> { | |||
| 93 | words.push(arg); | 93 | words.push(arg); |
| 94 | continue; | 94 | continue; |
| 95 | } | 95 | } |
| 96 | // `--flag=value` form, so a value that begins with `-` is expressible. | ||
| 97 | if arg.starts_with('-') { | ||
| 98 | if let Some((flag, value)) = arg.split_once('=') { | ||
| 99 | match flag { | ||
| 100 | "-m" | "--model" => { | ||
| 101 | args.model = Some(value.to_string()); | ||
| 102 | continue; | ||
| 103 | } | ||
| 104 | "--base-url" => { | ||
| 105 | args.base_url = Some(value.to_string()); | ||
| 106 | continue; | ||
| 107 | } | ||
| 108 | "--session" | "--resume" => { | ||
| 109 | args.session = Some(value.to_string()); | ||
| 110 | continue; | ||
| 111 | } | ||
| 112 | "--show" => { | ||
| 113 | args.show = Some(Some(value.to_string())); | ||
| 114 | continue; | ||
| 115 | } | ||
| 116 | _ => return Err(format!("unknown flag {flag}\n\n{HELP}")), | ||
| 117 | } | ||
| 118 | } | ||
| 119 | } | ||
| 96 | match arg.as_str() { | 120 | match arg.as_str() { |
| 97 | "--" => literal = true, | 121 | "--" => literal = true, |
| 98 | "-m" | "--model" => args.model = Some(take_value(&mut iter, "--model")?), | 122 | "-m" | "--model" => args.model = Some(take_value(&mut iter, "--model")?), |
| @@ -147,8 +171,13 @@ fn parse_args() -> Result<Args, String> { | |||
| 147 | 171 | ||
| 148 | fn take_value(iter: &mut impl Iterator<Item = String>, flag: &str) -> Result<String, String> { | 172 | fn take_value(iter: &mut impl Iterator<Item = String>, flag: &str) -> Result<String, String> { |
| 149 | match iter.next() { | 173 | match iter.next() { |
| 150 | Some(value) if !value.trim().is_empty() => Ok(value), | 174 | Some(value) |
| 151 | _ => Err(format!("{flag} needs a value")), | 175 | if !value.trim().is_empty() |
| 176 | && !(value.starts_with('-') && value.len() > 1) => | ||
| 177 | { | ||
| 178 | Ok(value) | ||
| 179 | } | ||
| 180 | _ => Err(format!("{flag} needs a value (use --{flag}=… for a value starting with -)")), | ||
| 152 | } | 181 | } |
| 153 | } | 182 | } |
| 154 | 183 | ||
| @@ -207,7 +236,7 @@ fn run(args: Args) { | |||
| 207 | 236 | ||
| 208 | warn_if_moved(&session); | 237 | warn_if_moved(&session); |
| 209 | if resuming { | 238 | if resuming { |
| 210 | print_last_reply(&session.id); | 239 | print_last_reply(&session); |
| 211 | } | 240 | } |
| 212 | if !session.version.is_empty() && session.version != env!("CARGO_PKG_VERSION") { | 241 | if !session.version.is_empty() && session.version != env!("CARGO_PKG_VERSION") { |
| 213 | eprintln!( | 242 | eprintln!( |
| @@ -655,11 +684,11 @@ fn render_message(message: &Value, color: bool) -> String { | |||
| 655 | /// On resume, show where the conversation left off: the last answer, or the last | 684 | /// On resume, show where the conversation left off: the last answer, or the last |
| 656 | /// reasoning when the model never produced content. Only on a terminal, so piped | 685 | /// reasoning when the model never produced content. Only on a terminal, so piped |
| 657 | /// runs stay clean. | 686 | /// runs stay clean. |
| 658 | fn print_last_reply(id: &str) { | 687 | fn print_last_reply(session: &Session) { |
| 659 | if !std::io::stdout().is_terminal() { | 688 | if !std::io::stdout().is_terminal() { |
| 660 | return; | 689 | return; |
| 661 | } | 690 | } |
| 662 | let Some(reply) = session::last_reply(id) else { | 691 | let Some(reply) = session.last_reply.as_ref() else { |
| 663 | return; | 692 | return; |
| 664 | }; | 693 | }; |
| 665 | let text = if reply.content.trim().is_empty() { | 694 | 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 { | |||
| 68 | pub cwd: String, | 68 | pub cwd: String, |
| 69 | /// Harness version that created the session, for prefix-change warnings. | 69 | /// Harness version that created the session, for prefix-change warnings. |
| 70 | pub version: String, | 70 | pub version: String, |
| 71 | /// Last assistant block, for the resume banner. Computed during the same pass | ||
| 72 | /// that loads messages, so resume does not read the file twice. | ||
| 73 | pub last_reply: Option<LastReply>, | ||
| 71 | path: PathBuf, | 74 | path: PathBuf, |
| 72 | file: File, | 75 | file: File, |
| 73 | } | 76 | } |
| @@ -121,6 +124,7 @@ impl Session { | |||
| 121 | model: model.to_string(), | 124 | model: model.to_string(), |
| 122 | cwd, | 125 | cwd, |
| 123 | version: env!("CARGO_PKG_VERSION").to_string(), | 126 | version: env!("CARGO_PKG_VERSION").to_string(), |
| 127 | last_reply: None, | ||
| 124 | path, | 128 | path, |
| 125 | file, | 129 | file, |
| 126 | }) | 130 | }) |
| @@ -138,6 +142,8 @@ impl Session { | |||
| 138 | let mut cwd = String::new(); | 142 | let mut cwd = String::new(); |
| 139 | let mut version = String::new(); | 143 | let mut version = String::new(); |
| 140 | let mut messages = Vec::new(); | 144 | let mut messages = Vec::new(); |
| 145 | let mut last_content: Option<LastReply> = None; | ||
| 146 | let mut last_reasoning: Option<LastReply> = None; | ||
| 141 | 147 | ||
| 142 | for line in raw.split(|&byte| byte == b'\n') { | 148 | for line in raw.split(|&byte| byte == b'\n') { |
| 143 | if line.is_empty() { | 149 | if line.is_empty() { |
| @@ -168,7 +174,29 @@ impl Session { | |||
| 168 | version = v.to_string(); | 174 | version = v.to_string(); |
| 169 | } | 175 | } |
| 170 | } | 176 | } |
| 177 | Some("model") => { | ||
| 178 | if let Some(name) = value.get("model").and_then(|m| m.as_str()) { | ||
| 179 | model = name.to_string(); | ||
| 180 | } | ||
| 181 | } | ||
| 171 | Some("msg") => { | 182 | Some("msg") => { |
| 183 | if value.get("role").and_then(|r| r.as_str()) == Some("assistant") { | ||
| 184 | let content = value | ||
| 185 | .get("content") | ||
| 186 | .and_then(|c| c.as_str()) | ||
| 187 | .unwrap_or("") | ||
| 188 | .to_string(); | ||
| 189 | let reasoning = value | ||
| 190 | .get("_reasoning") | ||
| 191 | .and_then(|r| r.as_str()) | ||
| 192 | .unwrap_or("") | ||
| 193 | .to_string(); | ||
| 194 | if !content.trim().is_empty() { | ||
| 195 | last_content = Some(LastReply { content, reasoning }); | ||
| 196 | } else if !reasoning.trim().is_empty() { | ||
| 197 | last_reasoning = Some(LastReply { content, reasoning }); | ||
| 198 | } | ||
| 199 | } | ||
| 172 | let mut message = value.clone(); | 200 | let mut message = value.clone(); |
| 173 | if let Some(object) = message.as_object_mut() { | 201 | if let Some(object) = message.as_object_mut() { |
| 174 | object.remove("t"); | 202 | object.remove("t"); |
| @@ -194,6 +222,7 @@ impl Session { | |||
| 194 | model, | 222 | model, |
| 195 | cwd, | 223 | cwd, |
| 196 | version, | 224 | version, |
| 225 | last_reply: last_content.or(last_reasoning), | ||
| 197 | path, | 226 | path, |
| 198 | file, | 227 | file, |
| 199 | }, | 228 | }, |
| @@ -237,52 +266,6 @@ pub struct LastReply { | |||
| 237 | pub reasoning: String, | 266 | pub reasoning: String, |
| 238 | } | 267 | } |
| 239 | 268 | ||
| 240 | /// The last thing the agent said, for the resume banner. Prefers a real answer; | ||
| 241 | /// falls back to reasoning when the last block had no content. | ||
| 242 | pub fn last_reply(id: &str) -> Option<LastReply> { | ||
| 243 | let raw = std::fs::read(sessions_dir().join(format!("{id}.jsonl"))).ok()?; | ||
| 244 | let mut with_content: Option<LastReply> = None; | ||
| 245 | let mut with_reasoning: Option<LastReply> = None; | ||
| 246 | |||
| 247 | for line in raw.split(|&byte| byte == b'\n') { | ||
| 248 | if line.is_empty() { | ||
| 249 | continue; | ||
| 250 | } | ||
| 251 | let text = String::from_utf8_lossy(line); | ||
| 252 | let Ok(value) = serde_json::from_str::<Value>(&text) else { | ||
| 253 | continue; | ||
| 254 | }; | ||
| 255 | if value.get("role").and_then(|role| role.as_str()) != Some("assistant") { | ||
| 256 | continue; | ||
| 257 | } | ||
| 258 | let content = value | ||
| 259 | .get("content") | ||
| 260 | .and_then(|c| c.as_str()) | ||
| 261 | .unwrap_or("") | ||
| 262 | .to_string(); | ||
| 263 | let reasoning = value | ||
| 264 | .get("_reasoning") | ||
| 265 | .and_then(|r| r.as_str()) | ||
| 266 | .unwrap_or("") | ||
| 267 | .to_string(); | ||
| 268 | let reply = LastReply { | ||
| 269 | content, | ||
| 270 | reasoning, | ||
| 271 | }; | ||
| 272 | if !reply.content.trim().is_empty() { | ||
| 273 | with_content = Some(LastReply { | ||
| 274 | content: reply.content.clone(), | ||
| 275 | reasoning: reply.reasoning.clone(), | ||
| 276 | }); | ||
| 277 | } | ||
| 278 | if !reply.reasoning.trim().is_empty() { | ||
| 279 | with_reasoning = Some(reply); | ||
| 280 | } | ||
| 281 | } | ||
| 282 | |||
| 283 | with_content.or(with_reasoning) | ||
| 284 | } | ||
| 285 | |||
| 286 | pub fn exists(id: &str) -> bool { | 269 | pub fn exists(id: &str) -> bool { |
| 287 | sessions_dir().join(format!("{id}.jsonl")).is_file() | 270 | sessions_dir().join(format!("{id}.jsonl")).is_file() |
| 288 | } | 271 | } |
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() { | |||
| 17 | libc::signal(libc::SIGINT, handler as libc::sighandler_t); | 17 | libc::signal(libc::SIGINT, handler as libc::sighandler_t); |
| 18 | } | 18 | } |
| 19 | } | 19 | } |
| 20 | |||
| 21 | pub fn reset() { | ||
| 22 | CANCEL.store(false, Ordering::SeqCst); | ||
| 23 | } | ||
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 { | |||
| 24 | } | 24 | } |
| 25 | } | 25 | } |
| 26 | 26 | ||
| 27 | /// True when the call cannot be replayed as a real tool call at all: no name. | ||
| 28 | /// (Named calls with no arguments are kept so the model can be told what went | ||
| 29 | /// wrong and retry.) | ||
| 30 | pub fn is_placeholder(arguments: &str) -> bool { | ||
| 31 | arguments.trim().is_empty() | ||
| 32 | } | ||
| 33 | |||
| 34 | /// Returns the keys the model actually sent, quoted and bounded. | 27 | /// Returns the keys the model actually sent, quoted and bounded. |
| 35 | fn received_keys(args: &Value) -> String { | 28 | fn received_keys(args: &Value) -> String { |
| 36 | let Some(object) = args.as_object() else { | 29 | let Some(object) = args.as_object() else { |
| @@ -55,32 +48,45 @@ fn received_keys(args: &Value) -> String { | |||
| 55 | /// arrived with no arguments at all (usually argument loss in transit). They | 48 | /// 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. | 49 | /// used to share one message, which pointed callers at the wrong fix. |
| 57 | pub fn validate(name: &str, args: &Value) -> Result<(), String> { | 50 | pub fn validate(name: &str, args: &Value) -> Result<(), String> { |
| 58 | let required = |key: &str| match args.get(key).and_then(|value| value.as_str()) { | 51 | let missing = |key: &str| { |
| 52 | if args.as_object().map(|o| o.is_empty()).unwrap_or(true) { | ||
| 53 | format!( | ||
| 54 | "the call arrived with no arguments at all, so `{key}` is missing. \ | ||
| 55 | If you sent one, it was lost in transit — retry the call" | ||
| 56 | ) | ||
| 57 | } else { | ||
| 58 | format!( | ||
| 59 | "missing `{key}`; received {}. The parameter is `{key}`", | ||
| 60 | received_keys(args) | ||
| 61 | ) | ||
| 62 | } | ||
| 63 | }; | ||
| 64 | // Must be present and non-blank. | ||
| 65 | let required_text = |key: &str| match args.get(key).and_then(|value| value.as_str()) { | ||
| 59 | Some(value) if !value.trim().is_empty() => Ok(()), | 66 | Some(value) if !value.trim().is_empty() => Ok(()), |
| 60 | Some(_) => Err(format!("`{key}` is present but empty")), | 67 | Some(_) => Err(format!("`{key}` is present but empty")), |
| 61 | None => { | 68 | None => Err(missing(key)), |
| 62 | if args.as_object().map(|o| o.is_empty()).unwrap_or(true) { | 69 | }; |
| 63 | Err(format!( | 70 | // Must be present, but may be the empty string (an empty file, a deletion). |
| 64 | "the call arrived with no arguments at all, so `{key}` is missing. \ | 71 | let required_string = |key: &str| match args.get(key) { |
| 65 | If you sent one, it was lost in transit — retry the call" | 72 | Some(Value::String(_)) => Ok(()), |
| 66 | )) | 73 | Some(_) => Err(format!("`{key}` must be a string")), |
| 67 | } else { | 74 | None => Err(missing(key)), |
| 68 | Err(format!( | ||
| 69 | "missing `{key}`; received {}. The parameter is `{key}`", | ||
| 70 | received_keys(args) | ||
| 71 | )) | ||
| 72 | } | ||
| 73 | } | ||
| 74 | }; | 75 | }; |
| 75 | 76 | ||
| 76 | match name { | 77 | match name { |
| 77 | "bash" => required("cmd"), | 78 | "bash" => required_text("cmd"), |
| 78 | "read" | "write" => required("path"), | 79 | "read" => required_text("path"), |
| 80 | "write" => { | ||
| 81 | required_text("path")?; | ||
| 82 | required_string("content") | ||
| 83 | } | ||
| 79 | "edit" => { | 84 | "edit" => { |
| 80 | required("path")?; | 85 | required_text("path")?; |
| 81 | required("old") | 86 | required_text("old")?; |
| 87 | required_string("new") | ||
| 82 | } | 88 | } |
| 83 | "grep" | "glob" => required("pattern"), | 89 | "grep" | "glob" => required_text("pattern"), |
| 84 | "" => Err("the tool call arrived without a tool name; it was probably truncated in transit — retry the call".into()), | 90 | "" => Err("the tool call arrived without a tool name; it was probably truncated in transit — retry the call".into()), |
| 85 | _ => Ok(()), | 91 | _ => Ok(()), |
| 86 | } | 92 | } |
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; | |||
| 18 | 18 | ||
| 19 | static COUNTER: AtomicU64 = AtomicU64::new(0); | 19 | static COUNTER: AtomicU64 = AtomicU64::new(0); |
| 20 | 20 | ||
| 21 | /// Removes both temp files when dropped, so an early `?` on the spawn/read paths | ||
| 22 | /// cannot leak `agent686-…-{out,err}.log` files into $TMPDIR. | ||
| 23 | struct TempGuard { | ||
| 24 | out: PathBuf, | ||
| 25 | err: PathBuf, | ||
| 26 | } | ||
| 27 | |||
| 28 | impl Drop for TempGuard { | ||
| 29 | fn drop(&mut self) { | ||
| 30 | let _ = std::fs::remove_file(&self.out); | ||
| 31 | let _ = std::fs::remove_file(&self.err); | ||
| 32 | } | ||
| 33 | } | ||
| 34 | |||
| 21 | pub fn bash( | 35 | pub fn bash( |
| 22 | args: &Value, | 36 | args: &Value, |
| 23 | timeout: Duration, | 37 | timeout: Duration, |
| @@ -44,6 +58,10 @@ pub fn bash( | |||
| 44 | let serial = COUNTER.fetch_add(1, Ordering::Relaxed); | 58 | let serial = COUNTER.fetch_add(1, Ordering::Relaxed); |
| 45 | let out_path = temp_path("out", serial); | 59 | let out_path = temp_path("out", serial); |
| 46 | let err_path = temp_path("err", serial); | 60 | let err_path = temp_path("err", serial); |
| 61 | let _guard = TempGuard { | ||
| 62 | out: out_path.clone(), | ||
| 63 | err: err_path.clone(), | ||
| 64 | }; | ||
| 47 | let mut out_file = create(&out_path)?; | 65 | let mut out_file = create(&out_path)?; |
| 48 | let mut err_file = create(&err_path)?; | 66 | let mut err_file = create(&err_path)?; |
| 49 | let stdout = out_file.try_clone().map_err(|e| e.to_string())?; | 67 | let stdout = out_file.try_clone().map_err(|e| e.to_string())?; |
| @@ -104,15 +122,17 @@ pub fn bash( | |||
| 104 | } | 122 | } |
| 105 | }; | 123 | }; |
| 106 | 124 | ||
| 107 | // A child that blew the file-size limit was killed by SIGXFSZ. | 125 | // SIGXFSZ lands on whichever process crossed the limit — usually a |
| 108 | let over_limit = status.signal() == Some(libc::SIGXFSZ); | 126 | // grandchild of `sh` — so `sh` exits 128+25 rather than being signalled. |
| 127 | // The reliable signal is the file itself having reached the limit. | ||
| 128 | let over_limit = status.signal() == Some(libc::SIGXFSZ) | ||
| 129 | || out_file.metadata().map(|m| m.len()).unwrap_or(0) >= MAX_FILE_BYTES | ||
| 130 | || err_file.metadata().map(|m| m.len()).unwrap_or(0) >= MAX_FILE_BYTES; | ||
| 109 | 131 | ||
| 110 | let (out_text, out_cut) = read_capped(&mut out_file, head_budget, tail_budget)?; | 132 | let (out_text, out_cut) = read_capped(&mut out_file, head_budget, tail_budget)?; |
| 111 | let (err_text, err_cut) = read_capped(&mut err_file, head_budget, tail_budget)?; | 133 | let (err_text, err_cut) = read_capped(&mut err_file, head_budget, tail_budget)?; |
| 112 | drop(out_file); | 134 | drop(out_file); |
| 113 | drop(err_file); | 135 | drop(err_file); |
| 114 | let _ = std::fs::remove_file(&out_path); | ||
| 115 | let _ = std::fs::remove_file(&err_path); | ||
| 116 | 136 | ||
| 117 | let marker = if over_limit { | 137 | let marker = if over_limit { |
| 118 | format!( | 138 | format!( |
diff --git a/tests/cli.rs b/tests/cli.rs index 6c041fb..5a4c03f 100644 --- a/tests/cli.rs +++ b/tests/cli.rs | |||
| @@ -145,3 +145,28 @@ fn show_renders_a_transcript() { | |||
| 145 | assert!(stdout.contains("on it"), "{stdout}"); | 145 | assert!(stdout.contains("on it"), "{stdout}"); |
| 146 | assert!(stdout.contains("thinking about it"), "{stdout}"); | 146 | assert!(stdout.contains("thinking about it"), "{stdout}"); |
| 147 | } | 147 | } |
| 148 | |||
| 149 | #[test] | ||
| 150 | fn a_flag_shaped_value_is_rejected_unless_attached() { | ||
| 151 | let output = agent().args(["--session", "--list"]).output().unwrap(); | ||
| 152 | assert_eq!(output.status.code(), Some(2)); | ||
| 153 | assert!( | ||
| 154 | String::from_utf8_lossy(&output.stderr).contains("needs a value"), | ||
| 155 | "{:?}", | ||
| 156 | String::from_utf8_lossy(&output.stderr) | ||
| 157 | ); | ||
| 158 | |||
| 159 | // The attached form works and creates a session whose id starts with `-`. | ||
| 160 | let home = temp_home("dash-session"); | ||
| 161 | let output = agent() | ||
| 162 | .env("HOME", &home) | ||
| 163 | .env("OPENCODE_API_KEY", "test") | ||
| 164 | .args(["--session=-abc", "--base-url", "http://127.0.0.1:9/v1"]) | ||
| 165 | .stdin(std::process::Stdio::null()) | ||
| 166 | .output() | ||
| 167 | .unwrap(); | ||
| 168 | assert_eq!(output.status.code(), Some(0), "{output:?}"); | ||
| 169 | assert!(home | ||
| 170 | .join(".local/share/agent686/sessions/-abc.jsonl") | ||
| 171 | .exists()); | ||
| 172 | } | ||
diff --git a/tests/sessions.rs b/tests/sessions.rs index 748b689..b381888 100644 --- a/tests/sessions.rs +++ b/tests/sessions.rs | |||
| @@ -159,7 +159,9 @@ fn last_reply_prefers_content_and_falls_back_to_reasoning() { | |||
| 159 | .append(&json!({ "role": "assistant", "content": null }), Some("only thinking")) | 159 | .append(&json!({ "role": "assistant", "content": null }), Some("only thinking")) |
| 160 | .unwrap(); | 160 | .unwrap(); |
| 161 | 161 | ||
| 162 | let reply = session::last_reply("reply").expect("there is a reply"); | 162 | drop(session); |
| 163 | let (opened, _system, _messages) = Session::open("reply").expect("open"); | ||
| 164 | let reply = opened.last_reply.expect("there is a reply"); | ||
| 163 | assert_eq!(reply.content, "the answer", "prefers a real block"); | 165 | assert_eq!(reply.content, "the answer", "prefers a real block"); |
| 164 | assert_eq!(reply.reasoning, "the thinking", "and its own reasoning"); | 166 | assert_eq!(reply.reasoning, "the thinking", "and its own reasoning"); |
| 165 | 167 | ||
| @@ -168,7 +170,9 @@ fn last_reply_prefers_content_and_falls_back_to_reasoning() { | |||
| 168 | session | 170 | session |
| 169 | .append(&json!({ "role": "assistant", "content": null }), Some("thoughts")) | 171 | .append(&json!({ "role": "assistant", "content": null }), Some("thoughts")) |
| 170 | .unwrap(); | 172 | .unwrap(); |
| 171 | let reply = session::last_reply("reasoning-only").unwrap(); | 173 | drop(session); |
| 174 | let (opened, _system, _messages) = Session::open("reasoning-only").unwrap(); | ||
| 175 | let reply = opened.last_reply.unwrap(); | ||
| 172 | assert!(reply.content.is_empty()); | 176 | assert!(reply.content.is_empty()); |
| 173 | assert_eq!(reply.reasoning, "thoughts"); | 177 | assert_eq!(reply.reasoning, "thoughts"); |
| 174 | } | 178 | } |
diff --git a/tests/tools.rs b/tests/tools.rs index e54b5ff..4a8176e 100644 --- a/tests/tools.rs +++ b/tests/tools.rs | |||
| @@ -490,3 +490,30 @@ fn bash_honours_a_per_call_output_budget() { | |||
| 490 | assert!(text.contains("output truncated"), "{text}"); | 490 | assert!(text.contains("output truncated"), "{text}"); |
| 491 | assert!(text.len() < 10_000, "output was {} bytes", text.len()); | 491 | assert!(text.len() < 10_000, "output was {} bytes", text.len()); |
| 492 | } | 492 | } |
| 493 | |||
| 494 | #[test] | ||
| 495 | fn validate_requires_content_and_new_but_allows_empty() { | ||
| 496 | use agent686::tools::validate; | ||
| 497 | |||
| 498 | // Missing, not empty. | ||
| 499 | assert!(validate("write", &json!({ "path": "a" })).is_err()); | ||
| 500 | assert!(validate("edit", &json!({ "path": "a", "old": "b" })).is_err()); | ||
| 501 | // Present but empty is legitimate (empty file, deletion). | ||
| 502 | assert!(validate("write", &json!({ "path": "a", "content": "" })).is_ok()); | ||
| 503 | assert!(validate("edit", &json!({ "path": "a", "old": "b", "new": "" })).is_ok()); | ||
| 504 | } | ||
| 505 | |||
| 506 | #[test] | ||
| 507 | fn a_pipeline_that_exceeds_the_file_limit_is_reported() { | ||
| 508 | // 70 MiB through a pipeline: the grandchild (head) is the writer, so only the | ||
| 509 | // file-length check can detect the limit. | ||
| 510 | let text = run( | ||
| 511 | "bash", | ||
| 512 | &json!({ "cmd": "yes | head -c 70000000" }), | ||
| 513 | ) | ||
| 514 | .unwrap(); | ||
| 515 | assert!( | ||
| 516 | text.contains("output exceeded 64 MiB"), | ||
| 517 | "should report the file limit: {text}" | ||
| 518 | ); | ||
| 519 | } | ||
