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 ++++++++++++++++++++++++++++++++++++++++++++++++++--------- 1 file changed, 134 insertions(+), 22 deletions(-) (limited to 'src/agent.rs') 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 } } } -- cgit v1.2.3