From 714534475818e6e5dced91ecad100ca9e286ccce Mon Sep 17 00:00:00 2001 From: salmonik Date: Sun, 15 Nov 2026 15:37:56 +0100 Subject: 0.4.1 + 0.4.2: abort integrity, stream completeness, tool-call indexing - an aborted multi-call step now answers every announced tool call - sessions with unanswered calls are repaired by appending results - a stream without [DONE]/finish_reason is an error, not an answer - tool call deltas keyed by index can no longer vanish or invent empty calls - one-shot exit codes: 130 aborted, 3 denied --- src/agent.rs | 156 ++++++++++++++++++++++++++++++++++++++++++++++++-------- src/main.rs | 22 ++++++-- src/provider.rs | 128 ++++++++++++++++++++++++++++++++++++---------- src/ui.rs | 26 +++++----- 4 files changed, 268 insertions(+), 64 deletions(-) (limited to 'src') diff --git a/src/agent.rs b/src/agent.rs index 7e652ed..46da069 100644 --- a/src/agent.rs +++ b/src/agent.rs @@ -95,6 +95,46 @@ pub fn new_history(system: Value) -> Vec { vec![system] } +#[derive(Debug, Default, Clone, Copy)] +pub struct TurnReport { + pub steps: usize, + pub aborted: bool, + pub denied: usize, +} + +pub enum ToolOutcome { + Ok(String), + Denied, + Failed(String), +} + +impl ToolOutcome { + fn content(&self) -> String { + match self { + ToolOutcome::Ok(output) => output.clone(), + ToolOutcome::Denied => "error: denied by the user".to_string(), + ToolOutcome::Failed(error) => format!("error: {error}"), + } + } + + fn summary(&self) -> String { + match self { + ToolOutcome::Ok(output) => output + .lines() + .find(|line| !line.trim().is_empty()) + .unwrap_or("") + .trim() + .to_string(), + ToolOutcome::Denied => "denied".to_string(), + ToolOutcome::Failed(error) => format!("error: {error}"), + } + } + + fn denied(&self) -> bool { + matches!(self, ToolOutcome::Denied) + } +} + /// Runs one turn to completion: model, tools, model, ... until the model answers /// without asking for a tool. Every message that is sent is also appended to the /// session file, in order, before the next request. @@ -105,8 +145,11 @@ pub fn run_turn( prompt: &str, cancel: &AtomicBool, approver: &mut Approver, -) -> Result<(), Error> { +) -> Result { + // A Ctrl-C pressed after the previous turn finished must not abort this one. + cancel.store(false, std::sync::atomic::Ordering::SeqCst); let started = Instant::now(); + repair_tool_results(session, history); let user = json!({ "role": "user", "content": prompt }); push(session, history, user, None); @@ -114,11 +157,12 @@ pub fn run_turn( let schemas = tools::schemas(); let mut steps = 0usize; let mut last: Option = None; + let mut aborted = false; + let mut denied = 0usize; loop { if cancel.load(std::sync::atomic::Ordering::Relaxed) { - crate::signal::reset(); - eprintln!("aborted"); + aborted = true; break; } @@ -127,8 +171,7 @@ pub fn run_turn( let mut outcome = match provider::chat(cfg, history, &schemas, cancel, &mut renderer) { Ok(outcome) => outcome, Err(Error::Aborted) => { - crate::signal::reset(); - eprintln!("aborted"); + aborted = true; break; } Err(error) => return Err(error), @@ -152,54 +195,123 @@ pub fn run_turn( last = Some(outcome); for call in calls { + // Cancelling between calls still has to answer every tool call the + // assistant message announced: an unanswered id makes the session + // permanently unusable, because history is never rewritten. if cancel.load(std::sync::atomic::Ordering::Relaxed) { - crate::signal::reset(); - eprintln!("aborted"); - break; + aborted = true; } - let result = execute(&call, approver); - ui::tool_result(&result); - let content = match result { - Ok(output) => output, - Err(error) => format!("error: {error}"), + let result = if aborted { + ToolOutcome::Failed("aborted by the user before this call ran".into()) + } else { + execute(&call, approver) }; + if result.denied() { + denied += 1; + } + ui::tool_result(&result.summary(), aborted); let message = json!({ "role": "tool", "tool_call_id": call.id, - "content": content, + "content": result.content(), }); push(session, history, message, None); } + + if aborted { + break; + } } + if aborted { + eprintln!("aborted"); + } if let Some(outcome) = last { ui::status(steps, started.elapsed(), &outcome); } - Ok(()) + Ok(TurnReport { + steps, + aborted, + denied, + }) } -fn execute(call: &provider::ToolCall, approver: &mut Approver) -> Result { +/// Any assistant message whose tool calls never got results would be rejected by +/// the provider, and the transcript is append-only. Repair by appending the +/// missing results, which is legal: only rewriting is forbidden. +fn repair_tool_results(session: &mut Session, history: &mut Vec) { + let index = match history.iter().rposition(|message| { + message.get("role").and_then(|role| role.as_str()) == Some("assistant") + && message + .get("tool_calls") + .and_then(|calls| calls.as_array()) + .is_some_and(|calls| !calls.is_empty()) + }) { + Some(index) => index, + None => return, + }; + + let ids: Vec = history[index]["tool_calls"] + .as_array() + .map(|calls| { + calls + .iter() + .filter_map(|call| call.get("id").and_then(|id| id.as_str())) + .map(|id| id.to_string()) + .collect() + }) + .unwrap_or_default(); + + let answered: std::collections::HashSet = history[index + 1..] + .iter() + .filter_map(|message| message.get("tool_call_id").and_then(|id| id.as_str())) + .map(|id| id.to_string()) + .collect(); + + for id in ids { + if answered.contains(&id) { + continue; + } + let message = json!({ + "role": "tool", + "tool_call_id": id, + "content": "error: this call was interrupted before it ran", + }); + push(session, history, message, None); + } +} + +fn execute(call: &provider::ToolCall, approver: &mut Approver) -> ToolOutcome { let args: Value = serde_json::from_str(&call.arguments).unwrap_or_else(|_| json!({})); ui::tool_line(&call.name, &args); match tools::approval(&call.name) { - Approval::Never => tools::run(&call.name, &args), + Approval::Never => match tools::run(&call.name, &args) { + Ok(output) => ToolOutcome::Ok(output), + Err(error) => ToolOutcome::Failed(error), + }, Approval::Once => match tools::plan(&call.name, &args) { Ok(change) => { if approver.allow_edit(change.path(), &change.preview()) { - change.apply() + match change.apply() { + Ok(output) => ToolOutcome::Ok(output), + Err(error) => ToolOutcome::Failed(error), + } } else { - Err("denied by the user".into()) + ToolOutcome::Denied } } - Err(error) => Err(error), + Err(error) => ToolOutcome::Failed(error), }, Approval::EveryCall => { let cmd = args.get("cmd").and_then(|v| v.as_str()).unwrap_or(""); if approver.allow_bash(cmd) { - tools::run(&call.name, &args) + match tools::run(&call.name, &args) { + Ok(output) => ToolOutcome::Ok(output), + Err(error) => ToolOutcome::Failed(error), + } } else { - Err("denied by the user".into()) + ToolOutcome::Denied } } } diff --git a/src/main.rs b/src/main.rs index ccd4e37..9a5012f 100644 --- a/src/main.rs +++ b/src/main.rs @@ -114,7 +114,7 @@ fn main() { if !prompt_words.is_empty() { let prompt = prompt_words.join(" "); - if let Err(error) = agent::run_turn( + match agent::run_turn( &cfg, &mut session, &mut history, @@ -122,14 +122,30 @@ fn main() { &signal::CANCEL, &mut approver, ) { - eprintln!("agent686: {error}"); - std::process::exit(1); + Ok(report) => { + if report.aborted { + std::process::exit(130); + } + if report.denied > 0 { + std::process::exit(3); + } + } + Err(error) => { + eprintln!("agent686: {error}"); + std::process::exit(1); + } } return; } let mut editor = Editor::new(); let interactive = editor.is_interactive(); + if !interactive && !cfg.yolo { + eprintln!( + "agent686: stdin is not a terminal, so write/edit/bash will be denied; \ + pass --yolo to allow them" + ); + } if interactive { eprintln!( "agent686 · {} · session {}{}", diff --git a/src/provider.rs b/src/provider.rs index 16c9013..b45282e 100644 --- a/src/provider.rs +++ b/src/provider.rs @@ -115,6 +115,23 @@ impl SseDecoder { self.buf.drain(..start); out } + + /// Anything left when the connection closes without a final newline. + pub fn finish(&mut self) -> Vec { + let mut out = Vec::new(); + if !self.buf.is_empty() { + let mut line = &self.buf[..]; + if line.last() == Some(&b'\r') { + line = &line[..line.len() - 1]; + } + if let Some(payload) = line.strip_prefix(b"data:") { + let payload = payload.strip_prefix(b" ").unwrap_or(payload); + out.push(String::from_utf8_lossy(payload).into_owned()); + } + self.buf.clear(); + } + out + } } const MAX_ATTEMPTS: usize = 4; @@ -290,9 +307,12 @@ pub fn chat( let mut decoder = SseDecoder::new(); let mut buf = [0u8; 8192]; let mut reader = resp.body_mut().as_reader(); + let mut calls: std::collections::BTreeMap = std::collections::BTreeMap::new(); + let mut completed = false; let mut done = false; + let mut dropped = 0usize; - while !done { + loop { // Blocking reads mean an abort is only noticed when bytes arrive or the // per-read timeout fires. Good enough: the model streams constantly. if cancel.load(Ordering::Relaxed) { @@ -304,31 +324,83 @@ pub fn chat( Err(e) => return Err(Error::Transport(e.to_string())), }; for data in decoder.feed(&buf[..n]) { - if data.is_empty() { - continue; - } - if data.trim() == "[DONE]" { + if handle_event(&data, &mut outcome, &mut calls, &mut completed, &mut dropped, sink) { done = true; break; } - let chunk: Chunk = match serde_json::from_str(&data) { - Ok(c) => c, - // A malformed frame is dropped rather than killing the turn. - Err(_) => continue, - }; - apply_chunk(&chunk, &mut outcome, sink); + } + if done { + break; + } + } + + // A final `data:` frame with no trailing newline is legitimate. + if !done { + for data in decoder.finish() { + if handle_event(&data, &mut outcome, &mut calls, &mut completed, &mut dropped, sink) { + break; + } } } + outcome.tool_calls = calls.into_values().collect(); if outcome.usage.as_ref().is_some_and(|u| u.is_null()) { outcome.usage = None; } + if dropped > 0 { + eprintln!("agent686: ignored {dropped} malformed stream frame(s)"); + } + + // A connection that closes early, or a 200 that is not SSE at all, must not + // be recorded as a complete answer. + if !completed { + return Err(Error::Transport(format!( + "stream ended before completion ({} bytes of text, {} tool call(s)); \ + the turn was not recorded as answered", + outcome.content.len(), + outcome.tool_calls.len() + ))); + } + sink.done(&outcome, started.elapsed()); Ok(outcome) } -fn apply_chunk(chunk: &Chunk, outcome: &mut Outcome, sink: &mut dyn Sink) { +fn handle_event( + data: &str, + outcome: &mut Outcome, + calls: &mut std::collections::BTreeMap, + completed: &mut bool, + dropped: &mut usize, + sink: &mut dyn Sink, +) -> bool { + if data.is_empty() { + return false; + } + if data.trim() == "[DONE]" { + *completed = true; + return true; + } + match serde_json::from_str::(data) { + Ok(chunk) => { + if chunk.choices.iter().any(|choice| choice.finish_reason.is_some()) { + *completed = true; + } + apply_chunk(&chunk, outcome, calls, sink); + } + // Counted and reported rather than silently swallowed. + Err(_) => *dropped += 1, + } + false +} + +fn apply_chunk( + chunk: &Chunk, + outcome: &mut Outcome, + calls: &mut std::collections::BTreeMap, + sink: &mut dyn Sink, +) { if let Some(usage) = &chunk.usage { outcome.usage = Some(usage.clone()); } @@ -345,9 +417,9 @@ fn apply_chunk(chunk: &Chunk, outcome: &mut Outcome, sink: &mut dyn Sink) { sink.text(t); } } - if let Some(calls) = &choice.delta.tool_calls { - for call in calls { - accumulate_tool_call(&mut outcome.tool_calls, call); + if let Some(deltas) = &choice.delta.tool_calls { + for delta in deltas { + accumulate_tool_call(calls, delta); } } if let Some(finish) = &choice.finish_reason { @@ -357,18 +429,19 @@ fn apply_chunk(chunk: &Chunk, outcome: &mut Outcome, sink: &mut dyn Sink) { } /// Tool call deltas arrive split across chunks and are keyed by `index`: the -/// name and id usually come once, the arguments a fragment at a time. -fn accumulate_tool_call(calls: &mut Vec, delta: &ToolCallDelta) { - while calls.len() <= delta.index { - let index = calls.len(); - calls.push(ToolCall { - index, - id: String::new(), - name: String::new(), - arguments: String::new(), - }); - } - let call = &mut calls[delta.index]; +/// name and id usually come once, the arguments a fragment at a time. A map +/// keyed by index means a missing or non-contiguous index cannot invent an +/// empty call or shift the others. +fn accumulate_tool_call( + calls: &mut std::collections::BTreeMap, + delta: &ToolCallDelta, +) { + let call = calls.entry(delta.index).or_insert_with(|| ToolCall { + index: delta.index, + id: String::new(), + name: String::new(), + arguments: String::new(), + }); if let Some(id) = &delta.id { call.id.push_str(id); } @@ -434,6 +507,7 @@ struct Delta { #[derive(Debug, Deserialize)] struct ToolCallDelta { + #[serde(default)] index: usize, #[serde(default)] id: Option, diff --git a/src/ui.rs b/src/ui.rs index 2ec0821..38546ab 100644 --- a/src/ui.rs +++ b/src/ui.rs @@ -104,14 +104,13 @@ pub fn tool_line(name: &str, args: &serde_json::Value) { let _ = std::io::stdout().flush(); } -pub fn tool_result(result: &Result) { - let text = match result { - Ok(output) => output, - Err(error) => error, +pub fn tool_result(summary: &str, aborted: bool) { + let text = if aborted { + "aborted".to_string() + } else { + crate::provider::truncate(summary.trim(), 100) }; - let first = text.lines().find(|l| !l.trim().is_empty()).unwrap_or(""); - let summary = crate::provider::truncate(first.trim(), 100); - println!(" {} {}", paint("2", "└"), paint("2", &summary)); + println!(" {} {}", paint("2", "└"), paint("2", &text)); let _ = std::io::stdout().flush(); } @@ -163,7 +162,7 @@ impl Approver { self.yolo } - fn ask(&self, question: &str) -> Answer { + fn ask(&self, question: &str, allow_always: bool) -> Answer { if self.yolo { return Answer::Yes; } @@ -174,7 +173,8 @@ impl Approver { ); return Answer::No; } - print!("\n{} {} ", question, paint("2", "[y/N/a]")); + let hint = if allow_always { "[y/N/a]" } else { "[y/N]" }; + print!("\n{} {} ", question, paint("2", hint)); let _ = std::io::stdout().flush(); let mut line = String::new(); @@ -183,7 +183,7 @@ impl Approver { } match line.trim().to_ascii_lowercase().as_str() { "y" | "yes" => Answer::Yes, - "a" | "always" => Answer::Always, + "a" | "always" if allow_always => Answer::Always, _ => Answer::No, } } @@ -194,7 +194,7 @@ impl Approver { return true; } println!("{preview}"); - match self.ask(&format!("apply this change to {path}?")) { + match self.ask(&format!("apply this change to {path}?"), true) { Answer::Yes => true, Answer::Always => { self.edits_allowed = true; @@ -209,6 +209,8 @@ impl Approver { if self.yolo { return true; } - self.ask(&format!("run: {}", crate::provider::truncate(cmd, 200))) == Answer::Yes + // Bash prompts every call by design, so "always" is not offered here. + self.ask(&format!("run: {}", crate::provider::truncate(cmd, 200)), false) + == Answer::Yes } } -- cgit v1.2.3