diff --git a/bin.json b/bin.json index 2190ab1..8f7ab7a 100644 --- a/bin.json +++ b/bin.json @@ -1,7 +1,7 @@ { - "version": "0.2.4", + "version": "0.2.5", "sha256": { - "aarch64-apple-darwin": "41ac25d2a2503b6f14ef0a499f914687a515284f06a31830609ef2d8973583fb", - "x86_64-unknown-linux-musl": "fcffc0f959fdbf50e99c09501166c661e695dff5c1feed0f39afc6145821f615" + "aarch64-apple-darwin": "22ae7c596d72dac575c6d1e5c002da6ac0d3aff491ab00e8950b9a48f9505560", + "x86_64-unknown-linux-musl": "9ad1e5222d557842b0dca7311d3b3f519dc8dbfec0cc9cdbc59839f1bf3a5622" } } diff --git a/crates/hx-core/src/agent.rs b/crates/hx-core/src/agent.rs index 9465a87..cfa33de 100644 --- a/crates/hx-core/src/agent.rs +++ b/crates/hx-core/src/agent.rs @@ -421,6 +421,25 @@ impl Agent { *self.abort.borrow() } + fn abort_calls( + &mut self, + calls: &[(String, String, serde_json::Value)], + ) -> Result { + let content = calls + .iter() + .map(|(id, ..)| ContentBlock::ToolResult { + tool_use_id: id.clone(), + content: "aborted by user".into(), + is_error: true, + }) + .collect(); + self.push(Message { + role: Role::User, + content, + })?; + Err(Error::Aborted) + } + pub async fn run(&mut self, prompt: impl Into) -> Result { let r = self.run_inner(prompt.into()).await; self.emit(Event::RunEnd { @@ -529,6 +548,9 @@ impl Agent { continue; } + if self.aborted() { + return self.abort_calls(&calls); + } let mut results: Vec> = vec![None; calls.len()]; let mut runnable = vec![]; for (i, (id, name, args)) in calls.iter().enumerate() { @@ -577,10 +599,12 @@ impl Agent { &self.cx, ); tokio::pin!(round); + let mut ab = self.abort.clone(); loop { tokio::select! { - outs = &mut round => break outs, + outs = &mut round => break Some(outs), Some(line) = nrx.recv() => { self.emit(Event::Info(line)).await; } + _ = async { ab.wait_for(|a| *a).await.is_ok() } => break None, } } }; @@ -590,6 +614,9 @@ impl Agent { .lock() .unwrap_or_else(|e| e.into_inner()) .take(); + let Some(outs) = outs else { + return self.abort_calls(&calls); + }; while let Ok(line) = nrx.try_recv() { self.emit(Event::Info(line)).await; } @@ -1093,6 +1120,62 @@ mod tests { assert!(matches!(a.run("again").await, Err(Error::Aborted))); } + struct Slow; + #[async_trait] + impl Tool for Slow { + fn spec(&self) -> ToolSpec { + ToolSpec { + name: "slow".into(), + description: "sleeps".into(), + input_schema: json!({"type":"object","properties":{}}), + } + } + async fn call(&self, _: Value, _: &crate::tool::ToolCtx) -> ToolResult { + tokio::time::sleep(std::time::Duration::from_secs(30)).await; + ToolResult::ok("done") + } + } + + #[tokio::test] + async fn abort_during_tool_round_stops_it_and_answers_the_calls() { + let p = Arc::new(Script( + Mutex::new(vec![ + asst(vec![tu("1", "slow"), tu("2", "slow")]), + asst(vec![ContentBlock::Text { text: "ok".into() }]), + ]), + Mutex::new(vec![]), + )); + let dir = tempfile::tempdir().unwrap(); + let mut tools = Registry::default(); + tools.add(Slow); + let cx = ToolCtx { + cwd: dir.path().into(), + state: Default::default(), + }; + let (mut a, h) = Agent::new( + p.clone(), + tools, + Session::open(dir.path().join("s.jsonl")).unwrap(), + cx, + ); + tokio::spawn(async move { + tokio::time::sleep(std::time::Duration::from_millis(100)).await; + h.abort(); + }); + let t = std::time::Instant::now(); + assert!(matches!(a.run("go").await, Err(Error::Aborted))); + assert!(t.elapsed() < std::time::Duration::from_secs(5)); + assert!(a.run("again").await.is_ok()); + let reqs = p.1.lock().unwrap(); + let last = &reqs[1].messages; + let results = last + .iter() + .flat_map(|m| &m.content) + .filter(|b| matches!(b, ContentBlock::ToolResult { is_error: true, .. })) + .count(); + assert_eq!(results, 2); + } + #[tokio::test] async fn mask_boundary_waits_for_big_context_and_is_recorded() { let big = "z".repeat(8000); diff --git a/crates/hx-core/src/tool.rs b/crates/hx-core/src/tool.rs index 1e99cdc..9da86a3 100644 --- a/crates/hx-core/src/tool.rs +++ b/crates/hx-core/src/tool.rs @@ -135,7 +135,14 @@ pub async fn gate_why(cx: &ToolCtx, req: crate::permit::Request) -> Result<(), S } } let rule = req.rule.clone(); - match ask(req).await { + let decision = match cx.state.abort.get().cloned() { + Some(mut rx) => tokio::select! { + d = ask(req) => d, + _ = async { rx.wait_for(|a| *a).await.is_ok() } => Decision::Deny, + }, + None => ask(req).await, + }; + match decision { Decision::Once => {} Decision::Always => allow().add(&rule), Decision::Edits => allow().allow_edits(), diff --git a/crates/hx-tools/src/lib.rs b/crates/hx-tools/src/lib.rs index ffa1b3e..7e1d117 100644 --- a/crates/hx-tools/src/lib.rs +++ b/crates/hx-tools/src/lib.rs @@ -366,6 +366,19 @@ impl Tool for ExitPlan { const LIVE_TAIL: usize = 2048; +#[cfg(unix)] +struct KillGroup(Option); +#[cfg(unix)] +impl Drop for KillGroup { + fn drop(&mut self) { + if let Some(pid) = self.0 { + let _ = std::process::Command::new("kill") + .args(["-KILL", &format!("-{pid}")]) + .status(); + } + } +} + pub struct Bash; #[async_trait] impl Tool for Bash { @@ -396,6 +409,8 @@ impl Tool for Bash { Err(e) => return ToolResult::err(format!("spawn: {e}")), }; let pid = child.id(); + #[cfg(unix)] + let mut group = KillGroup(pid); let mut so = child.stdout.take().expect("piped"); let live = &cx.state.live; let run = async { @@ -420,15 +435,21 @@ impl Tool for Bash { let res = tokio::time::timeout(Duration::from_secs(secs), run).await; live.lock().unwrap_or_else(|e| e.into_inner()).remove(cmd); let (out, code) = match res { - Ok(Ok((o, st))) => (o, st.code()), - Ok(Err(e)) => return ToolResult::err(format!("wait: {e}")), - Err(_) => { + Ok(Ok((o, st))) => { #[cfg(unix)] - if let Some(pid) = pid { - let _ = std::process::Command::new("kill") - .args(["-KILL", &format!("-{pid}")]) - .status(); + { + group.0 = None; } + (o, st.code()) + } + Ok(Err(e)) => { + #[cfg(unix)] + { + group.0 = None; + } + return ToolResult::err(format!("wait: {e}")); + } + Err(_) => { return ToolResult::err(format!("timed out after {secs}s")); } };