fix: abort stops running tool calls and kills bash process group
Race the tool round against abort, check abort before starting tools, answer pending calls with an aborted result, deny permission prompts on abort, and kill the bash process group on drop. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
951b69837a
commit
8f0de9465d
3 files changed
+120
-9
No files matched your search
@@ -421,6 +421,25 @@ impl Agent {
|
|||||||
*self.abort.borrow()
|
*self.abort.borrow()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn abort_calls(
|
||||||
|
&mut self,
|
||||||
|
calls: &[(String, String, serde_json::Value)],
|
||||||
|
) -> Result<Message, Error> {
|
||||||
|
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<String>) -> Result<Message, Error> {
|
pub async fn run(&mut self, prompt: impl Into<String>) -> Result<Message, Error> {
|
||||||
let r = self.run_inner(prompt.into()).await;
|
let r = self.run_inner(prompt.into()).await;
|
||||||
self.emit(Event::RunEnd {
|
self.emit(Event::RunEnd {
|
||||||
@@ -529,6 +548,9 @@ impl Agent {
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if self.aborted() {
|
||||||
|
return self.abort_calls(&calls);
|
||||||
|
}
|
||||||
let mut results: Vec<Option<ContentBlock>> = vec![None; calls.len()];
|
let mut results: Vec<Option<ContentBlock>> = vec![None; calls.len()];
|
||||||
let mut runnable = vec![];
|
let mut runnable = vec![];
|
||||||
for (i, (id, name, args)) in calls.iter().enumerate() {
|
for (i, (id, name, args)) in calls.iter().enumerate() {
|
||||||
@@ -577,10 +599,12 @@ impl Agent {
|
|||||||
&self.cx,
|
&self.cx,
|
||||||
);
|
);
|
||||||
tokio::pin!(round);
|
tokio::pin!(round);
|
||||||
|
let mut ab = self.abort.clone();
|
||||||
loop {
|
loop {
|
||||||
tokio::select! {
|
tokio::select! {
|
||||||
outs = &mut round => break outs,
|
outs = &mut round => break Some(outs),
|
||||||
Some(line) = nrx.recv() => { self.emit(Event::Info(line)).await; }
|
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()
|
.lock()
|
||||||
.unwrap_or_else(|e| e.into_inner())
|
.unwrap_or_else(|e| e.into_inner())
|
||||||
.take();
|
.take();
|
||||||
|
let Some(outs) = outs else {
|
||||||
|
return self.abort_calls(&calls);
|
||||||
|
};
|
||||||
while let Ok(line) = nrx.try_recv() {
|
while let Ok(line) = nrx.try_recv() {
|
||||||
self.emit(Event::Info(line)).await;
|
self.emit(Event::Info(line)).await;
|
||||||
}
|
}
|
||||||
@@ -1093,6 +1120,62 @@ mod tests {
|
|||||||
assert!(matches!(a.run("again").await, Err(Error::Aborted)));
|
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]
|
#[tokio::test]
|
||||||
async fn mask_boundary_waits_for_big_context_and_is_recorded() {
|
async fn mask_boundary_waits_for_big_context_and_is_recorded() {
|
||||||
let big = "z".repeat(8000);
|
let big = "z".repeat(8000);
|
||||||
|
|||||||
@@ -135,7 +135,14 @@ pub async fn gate_why(cx: &ToolCtx, req: crate::permit::Request) -> Result<(), S
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
let rule = req.rule.clone();
|
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::Once => {}
|
||||||
Decision::Always => allow().add(&rule),
|
Decision::Always => allow().add(&rule),
|
||||||
Decision::Edits => allow().allow_edits(),
|
Decision::Edits => allow().allow_edits(),
|
||||||
|
|||||||
@@ -366,6 +366,19 @@ impl Tool for ExitPlan {
|
|||||||
|
|
||||||
const LIVE_TAIL: usize = 2048;
|
const LIVE_TAIL: usize = 2048;
|
||||||
|
|
||||||
|
#[cfg(unix)]
|
||||||
|
struct KillGroup(Option<u32>);
|
||||||
|
#[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;
|
pub struct Bash;
|
||||||
#[async_trait]
|
#[async_trait]
|
||||||
impl Tool for Bash {
|
impl Tool for Bash {
|
||||||
@@ -396,6 +409,8 @@ impl Tool for Bash {
|
|||||||
Err(e) => return ToolResult::err(format!("spawn: {e}")),
|
Err(e) => return ToolResult::err(format!("spawn: {e}")),
|
||||||
};
|
};
|
||||||
let pid = child.id();
|
let pid = child.id();
|
||||||
|
#[cfg(unix)]
|
||||||
|
let mut group = KillGroup(pid);
|
||||||
let mut so = child.stdout.take().expect("piped");
|
let mut so = child.stdout.take().expect("piped");
|
||||||
let live = &cx.state.live;
|
let live = &cx.state.live;
|
||||||
let run = async {
|
let run = async {
|
||||||
@@ -420,15 +435,21 @@ impl Tool for Bash {
|
|||||||
let res = tokio::time::timeout(Duration::from_secs(secs), run).await;
|
let res = tokio::time::timeout(Duration::from_secs(secs), run).await;
|
||||||
live.lock().unwrap_or_else(|e| e.into_inner()).remove(cmd);
|
live.lock().unwrap_or_else(|e| e.into_inner()).remove(cmd);
|
||||||
let (out, code) = match res {
|
let (out, code) = match res {
|
||||||
Ok(Ok((o, st))) => (o, st.code()),
|
Ok(Ok((o, st))) => {
|
||||||
Ok(Err(e)) => return ToolResult::err(format!("wait: {e}")),
|
|
||||||
Err(_) => {
|
|
||||||
#[cfg(unix)]
|
#[cfg(unix)]
|
||||||
if let Some(pid) = pid {
|
{
|
||||||
let _ = std::process::Command::new("kill")
|
group.0 = None;
|
||||||
.args(["-KILL", &format!("-{pid}")])
|
|
||||||
.status();
|
|
||||||
}
|
}
|
||||||
|
(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"));
|
return ToolResult::err(format!("timed out after {secs}s"));
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|||||||
Reference in new issue
Block a user