From 8ae5bd48cf233315b5f36a7a6b39002a5e77f74b Mon Sep 17 00:00:00 2001 From: salmonik Date: Sun, 15 Nov 2026 18:00:12 +0100 Subject: 0.7.0: resume shows where you left off; no approval for unparsable calls - --continue prints the last answer, or the last reasoning block if there was none - tool arguments are validated before prompting, so an empty bash call becomes an error for the model instead of a blank approval - empty placeholder tool calls are dropped and reported - sessions tolerate invalid UTF-8 lines from a torn write - AGENT686_DEBUG_STREAM=1 dumps SSE frames --- CHANGELOG.md | 20 +++++++++++++++++ Cargo.lock | 2 +- Cargo.toml | 2 +- README.md | 1 + src/agent.rs | 13 ++++++++++- src/main.rs | 43 ++++++++++++++++++++++++++++++++++++ src/provider.rs | 15 ++++++++++++- src/session.rs | 66 +++++++++++++++++++++++++++++++++++++++++++++++++------ src/tools/mod.rs | 24 ++++++++++++++++++++ tests/loop.rs | 53 ++++++++++++++++++++++++++++++++++++++++++++ tests/mock.rs | 25 +++++++++++++++++++++ tests/sessions.rs | 59 +++++++++++++++++++++++++++++++++++++++++++++++++ tests/tools.rs | 15 +++++++++++++ 13 files changed, 327 insertions(+), 11 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 99b92db..5d1e21e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,26 @@ break the interface, **PATCH** for bug fixes. file, and the tool schemas the model sees. Anything a script or a resumed session could depend on counts as API. +## 0.7.0 + +### Added +- Resuming a session (`--continue` or `--session`) prints the last assistant + block before the prompt, or the last reasoning block when the model produced no + content. Twenty lines at most, with a pointer to `--show`. +- `AGENT686_DEBUG_STREAM=1` prints every SSE frame to stderr (truncated), for + diagnosing provider quirks without a proxy. + +### Fixed +- A `bash`, `write` or `edit` call with missing or unparsable arguments used to + reach the approval prompt, so you were asked to approve an empty command. + Arguments are validated before any prompt: invalid JSON and empty required + fields are returned to the model as errors instead. +- Empty placeholder tool calls sent by a provider are dropped and reported, + rather than becoming a blank approval. +- A session containing a line with invalid UTF-8 — the shape a torn write leaves + after `kill -9` — could not be opened at all. Reading is now byte-based and + lossy per line, so a torn line costs that line, not the session. + ## 0.6.2 ### Fixed diff --git a/Cargo.lock b/Cargo.lock index 0ce01e2..a6ef8f8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -10,7 +10,7 @@ checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" [[package]] name = "agent686" -version = "0.6.2" +version = "0.7.0" dependencies = [ "crossterm", "libc", diff --git a/Cargo.toml b/Cargo.toml index 38fc125..72520a4 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "agent686" -version = "0.6.2" +version = "0.7.0" edition = "2021" description = "A small coding agent for a 32-bit Debian box" publish = false diff --git a/README.md b/README.md index e4d6fbc..f98e661 100644 --- a/README.md +++ b/README.md @@ -30,6 +30,7 @@ export OPENCODE_API_KEY=... # or write it to ~/.config/agent686/key ./agent686 -c # continue the most recent session ./agent686 --session # resume it, or create it if the id is new ./agent686 --list # id, model, message count, age +./agent686 -c # continue; prints where you left off ./agent686 --show [id] # render a transcript ./agent686 --doctor # key, dirs, provider, model ./agent686 --yolo "..." # approve every tool call diff --git a/src/agent.rs b/src/agent.rs index 4bf19ed..f0e1292 100644 --- a/src/agent.rs +++ b/src/agent.rs @@ -342,8 +342,19 @@ fn execute( cancel: &AtomicBool, step: usize, ) -> ToolOutcome { - let args: Value = serde_json::from_str(&call.arguments).unwrap_or_else(|_| json!({})); + let args: Value = match serde_json::from_str(&call.arguments) { + Ok(args) => args, + Err(error) => { + return ToolOutcome::Failed(format!( + "arguments were not valid JSON ({error}); issue the call again with the \ + complete arguments" + )) + } + }; ui::tool_line(step, &call.name, &args); + if let Err(error) = tools::validate(&call.name, &args) { + return ToolOutcome::Failed(format!("{error}; the call was not run")); + } match tools::approval(&call.name) { Approval::Never => match tools::run(&call.name, &args, cancel) { diff --git a/src/main.rs b/src/main.rs index 91d54da..45ca8c6 100644 --- a/src/main.rs +++ b/src/main.rs @@ -195,6 +195,7 @@ fn run(args: Args) { } }; + let resuming = args.session.is_some() || args.continue_last; let (mut session, mut history) = match open_session(&cfg, args.session, args.continue_last) { Ok(pair) => pair, Err(message) => { @@ -205,6 +206,9 @@ fn run(args: Args) { cfg.session = session.id.clone(); warn_if_moved(&session); + if resuming { + print_last_reply(&session.id); + } if !session.version.is_empty() && session.version != env!("CARGO_PKG_VERSION") { eprintln!( "agent686: this session was written by {}; the prompt and tool schemas may \ @@ -647,3 +651,42 @@ fn render_message(message: &Value, color: bool) -> String { other => format!("[{other}]\n"), } } + +/// 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) { + if !std::io::stdout().is_terminal() { + return; + } + let Some(reply) = session::last_reply(id) else { + return; + }; + let text = if reply.content.trim().is_empty() { + reply.reasoning.trim() + } else { + reply.content.trim() + }; + if text.is_empty() { + return; + } + + let lines: Vec<&str> = text.lines().collect(); + let limit = 20; + println!(); + println!("{}", style("2", "── where you left off ──", true)); + for line in lines.iter().take(limit) { + println!("{line}"); + } + if lines.len() > limit { + println!( + "{}", + style( + "2", + &format!("… {} more line(s); `agent686 --show` for the transcript", lines.len() - limit), + true + ) + ); + } + println!(); +} diff --git a/src/provider.rs b/src/provider.rs index 1b9e220..0973e8c 100644 --- a/src/provider.rs +++ b/src/provider.rs @@ -358,7 +358,17 @@ pub fn chat_with( } } - outcome.tool_calls = calls.into_values().collect(); + let before = calls.len(); + outcome.tool_calls = calls + .into_values() + // Some backends emit an empty placeholder alongside a real call; asking + // a human to approve a blank command is worse than dropping it. + .filter(|call| !(call.name.is_empty() && call.arguments.trim().is_empty())) + .collect(); + let dropped_calls = before - outcome.tool_calls.len(); + if dropped_calls > 0 { + eprintln!("agent686: ignored {dropped_calls} empty tool call(s)"); + } if outcome.usage.as_ref().is_some_and(|u| u.is_null()) { outcome.usage = None; } @@ -393,6 +403,9 @@ fn handle_event( if data.is_empty() { return false; } + if std::env::var_os("AGENT686_DEBUG_STREAM").is_some() { + eprintln!("sse: {}", truncate(data, 400)); + } if data.trim() == "[DONE]" { *completed = true; return true; diff --git a/src/session.rs b/src/session.rs index d017eda..8e0ef02 100644 --- a/src/session.rs +++ b/src/session.rs @@ -130,8 +130,8 @@ impl Session { /// that was frozen when the session started. pub fn open(id: &str) -> Result<(Session, Value, Vec), String> { let path = sessions_dir().join(format!("{id}.jsonl")); - let file = File::open(&path).map_err(|e| format!("{}: {e}", path.display()))?; - let reader = BufReader::new(file.try_clone().map_err(|e| e.to_string())?); + let raw = std::fs::read(&path).map_err(|e| format!("{}: {e}", path.display()))?; + let _ = File::open(&path); let mut model = String::new(); let mut system = Value::Null; @@ -140,14 +140,15 @@ impl Session { let mut version = String::new(); let mut messages = Vec::new(); - for line in reader.lines() { - let line = line.map_err(|e| e.to_string())?; - if line.trim().is_empty() { + for line in raw.split(|&byte| byte == b'\n') { + if line.is_empty() { continue; } - let value: Value = match serde_json::from_str(&line) { + // Lossy decoding: a torn write can split a multi-byte character, and + // one bad byte must not make the whole transcript unopenable. + let text = String::from_utf8_lossy(line); + let value: Value = match serde_json::from_str(&text) { Ok(v) => v, - // A torn last line is expected after kill -9; ignore it. Err(_) => continue, }; match value.get("t").and_then(|t| t.as_str()) { @@ -232,6 +233,57 @@ impl Session { } } +pub struct LastReply { + pub content: String, + 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/tools/mod.rs b/src/tools/mod.rs index a8851ab..060dd7b 100644 --- a/src/tools/mod.rs +++ b/src/tools/mod.rs @@ -24,6 +24,30 @@ pub fn approval(name: &str) -> Approval { } } +/// Rejects a call that cannot possibly run, before a human is asked to approve +/// it. An empty `cmd` used to mean an approval prompt for `run: `. +pub fn validate(name: &str, args: &Value) -> Result<(), String> { + let text = |key: &str| args.get(key).and_then(|value| value.as_str()).unwrap_or(""); + let required = |key: &str| { + if text(key).trim().is_empty() { + Err(format!("`{key}` is required and must not be empty")) + } else { + Ok(()) + } + }; + + match name { + "bash" => required("cmd"), + "read" | "write" => required("path"), + "edit" => { + required("path")?; + required("old") + } + "grep" | "glob" => required("pattern"), + _ => Ok(()), + } +} + /// Tools that execute immediately. pub fn run(name: &str, args: &Value, cancel: &std::sync::atomic::AtomicBool) -> Result { match name { diff --git a/tests/loop.rs b/tests/loop.rs index b7e56f9..f90d19d 100644 --- a/tests/loop.rs +++ b/tests/loop.rs @@ -334,3 +334,56 @@ fn opening_a_session_with_unanswered_calls_repairs_it() { }); assert!(repaired, "missing result for call_2 should be synthesised"); } + +#[test] +fn an_empty_bash_call_is_never_approved() { + let dir = temp_dir("empty-bash"); + let empty_call = sse(&format!( + "data: {}\n\ndata: [DONE]\n\n", + json!({ + "choices": [{ + "delta": { "tool_calls": [{ + "index": 0, + "id": "call_empty", + "function": { "name": "bash", "arguments": "{}" } + }]}, + "finish_reason": "tool_calls" + }] + }) + )); + let final_round = sse( + "data: {\"choices\":[{\"delta\":{\"content\":\"ok\"},\"finish_reason\":\"stop\"}]}\n\n\ + data: [DONE]\n\n", + ); + + let base = serve_sequence(vec![empty_call, final_round]); + std::env::set_var("AGENT686_DATA", dir.join("data")); + + let system = agent::system_prompt(); + let mut session = Session::create("test-model", &system).unwrap(); + let cfg = Config { + base_url: base, + api_key: "test-key".into(), + model: "test-model".into(), + session: session.id.clone(), + yolo: false, + }; + let mut history = agent::new_history(system); + // Not a terminal: if this reaches the approval path it is denied, which the + // assertion below would catch. + let mut approver = Approver::new(false); + + agent::run_turn( + &cfg, + &mut session, + &mut history, + "run something", + &AtomicBool::new(false), + &mut approver, + ) + .expect("the turn should survive a malformed call"); + + let result = history[3]["content"].as_str().unwrap(); + assert!(result.contains("`cmd` is required"), "{result}"); + assert!(!result.contains("denied"), "must not reach an approval prompt: {result}"); +} diff --git a/tests/mock.rs b/tests/mock.rs index 9b9a56d..7e076e3 100644 --- a/tests/mock.rs +++ b/tests/mock.rs @@ -442,3 +442,28 @@ fn a_final_frame_without_a_newline_is_not_lost() { .expect("a trailing frame without a newline should still count"); assert_eq!(outcome.content, "last"); } + +#[test] +fn an_empty_placeholder_tool_call_is_dropped() { + const SSE: &str = concat!( + "HTTP/1.1 200 OK\r\n", + "Content-Type: text/event-stream\r\n", + "Connection: close\r\n", + "\r\n", + "data: {\"choices\":[{\"delta\":{\"tool_calls\":[{\"index\":0,\"id\":\"call_1\",\"function\":{\"name\":\"read\",\"arguments\":\"{\\\"path\\\":\\\"a\\\"}\"}},{\"index\":1}]},\"finish_reason\":\"tool_calls\"}]}\n\n", + "data: [DONE]\n\n", + ); + let (base, _rx) = serve_once(SSE); + let mut sink = Collector::default(); + let outcome = provider::chat( + &config(base), + &[json!({ "role": "user", "content": "hi" })], + &[], + &AtomicBool::new(false), + &mut sink, + ) + .expect("chat should succeed"); + + assert_eq!(outcome.tool_calls.len(), 1, "{:?}", outcome.tool_calls); + assert_eq!(outcome.tool_calls[0].name, "read"); +} diff --git a/tests/sessions.rs b/tests/sessions.rs index 1d40f64..df2f3b2 100644 --- a/tests/sessions.rs +++ b/tests/sessions.rs @@ -110,3 +110,62 @@ fn listing_reports_the_model_in_use_after_a_switch() { assert_eq!(listed.len(), 1); assert_eq!(listed[0].model, "model-b"); } + +#[test] +fn a_torn_utf8_line_does_not_brick_a_session() { + let _env = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + let dir = temp_dir("torn"); + std::env::set_var("AGENT686_DATA", &dir); + let sessions = dir.join("sessions"); + fs::create_dir_all(&sessions).unwrap(); + + let mut raw = Vec::new(); + raw.extend_from_slice( + br#"{"t":"header","session":"torn","model":"m","cwd":"/tmp","system":{"role":"system","content":"s"}} +"#, + ); + raw.extend_from_slice(br#"{"t":"msg","role":"user","content":"hello"} +"#); + // A killed write that split a multi-byte character. + raw.extend_from_slice(b"{\"t\":\"msg\",\"role\":\"user\",\"content\":\"caf\xc3\"}\n"); + fs::write(sessions.join("torn.jsonl"), raw).unwrap(); + + let (_session, _system, messages) = Session::open("torn").expect("torn line must not fail"); + // Lossy decoding keeps the message (with a replacement character) rather + // than dropping a valid JSON line; what matters is that open succeeds. + assert_eq!(messages.len(), 2); + assert_eq!(messages[0]["content"], "hello"); + assert!(messages[1]["content"].as_str().unwrap().starts_with("caf")); +} + +#[test] +fn last_reply_prefers_content_and_falls_back_to_reasoning() { + let _env = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + let dir = temp_dir("last-reply"); + std::env::set_var("AGENT686_DATA", &dir); + + let system = json!({ "role": "system", "content": "x" }); + let mut session = Session::create_as("reply".into(), "m", &system).unwrap(); + session + .append( + &json!({ "role": "assistant", "content": "the answer" }), + Some("the thinking"), + ) + .unwrap(); + session + .append(&json!({ "role": "assistant", "content": null }), Some("only thinking")) + .unwrap(); + + let reply = session::last_reply("reply").expect("there is a reply"); + assert_eq!(reply.content, "the answer", "prefers a real block"); + assert_eq!(reply.reasoning, "the thinking", "and its own reasoning"); + + // With no content anywhere, reasoning is the fallback. + let mut session = Session::create_as("reasoning-only".into(), "m", &system).unwrap(); + session + .append(&json!({ "role": "assistant", "content": null }), Some("thoughts")) + .unwrap(); + let reply = session::last_reply("reasoning-only").unwrap(); + assert!(reply.content.is_empty()); + assert_eq!(reply.reasoning, "thoughts"); +} diff --git a/tests/tools.rs b/tests/tools.rs index 77c1698..a400df0 100644 --- a/tests/tools.rs +++ b/tests/tools.rs @@ -419,3 +419,18 @@ fn glob_follows_file_symlinks_but_not_directories() { assert!(text.contains("link.rs"), "{text}"); assert!(text.contains("inner.rs"), "{text}"); } + +#[test] +fn validate_rejects_calls_that_cannot_run() { + use agent686::tools::validate; + + assert!(validate("bash", &json!({ "cmd": "" })).is_err()); + assert!(validate("bash", &json!({})).is_err()); + assert!(validate("bash", &json!({ "cmd": "ls" })).is_ok()); + + assert!(validate("read", &json!({ "path": " " })).is_err()); + assert!(validate("edit", &json!({ "path": "a", "old": "" })).is_err()); + assert!(validate("grep", &json!({ "pattern": "" })).is_err()); + // Empty content is how you create an empty file. + assert!(validate("write", &json!({ "path": "a", "content": "" })).is_ok()); +} -- cgit v1.2.3