use ai_agent::Agent;
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::Mutex;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
println!("--- Example 27: Interrupting Agent Execution ---\n");
let model = std::env::var("AI_MODEL").unwrap_or_else(|_| "claude-sonnet-4-6".to_string());
let agent = Arc::new(Mutex::new(Agent::new(&model).max_turns(10)));
let interrupt_agent = Arc::clone(&agent);
let interrupt_task = tokio::spawn(async move {
tokio::time::sleep(Duration::from_secs(3)).await;
println!("\n[Task] Calling interrupt()\n");
interrupt_agent.lock().await.interrupt();
});
let result = {
let ag = agent.lock().await;
ag.query("List 10 files in the current directory, then read each of them")
.await
};
let _ = tokio::time::timeout(Duration::from_secs(5), interrupt_task).await;
match result {
Ok(resp) => {
println!(
"[Agent] Prompt completed: {} turns, {} output tokens",
resp.num_turns, resp.usage.output_tokens
);
}
Err(ai_agent::error::AgentError::UserAborted) => {
println!("[Agent] Prompt was interrupted (UserAborted)!");
}
Err(e) => {
println!("[Agent] Prompt errored: {:?}", e);
}
}
println!("\n--- Example complete ---");
Ok(())
}