| 1 | use agents::{AgentSettings, Invocation, RunPlan}; |
| 2 | |
| 3 | use super::runs::AgentRun; |
| 4 | use crate::runtime; |
| 5 | |
| 6 | pub fn orphan_stop(run: &AgentRun, plan: &RunPlan) -> Option<Invocation> { |
| 7 | plan.stop.clone().or_else(|| pid_kill(run)) |
| 8 | } |
| 9 | |
| 10 | pub fn pid_kill(run: &AgentRun) -> Option<Invocation> { |
| 11 | let launched_as = run.launch_session_id.as_ref().unwrap_or(&run.session_id); |
| 12 | run.process_id |
| 13 | .and_then(|process_id| agents::kill_process_invocation(process_id, launched_as)) |
| 14 | } |
| 15 | |
| 16 | pub fn startup_kill(settings: &AgentSettings, run: &AgentRun) -> Option<Invocation> { |
| 17 | let launched_as = run.launch_session_id.as_ref().unwrap_or(&run.session_id); |
| 18 | settings |
| 19 | .agents |
| 20 | .iter() |
| 21 | .find(|agent| agent.id == run.agent_id) |
| 22 | .and_then(|agent| agents::wsl_stop_invocation(&agent.environment, launched_as)) |
| 23 | .or_else(|| pid_kill(run)) |
| 24 | } |
| 25 | |
| 26 | pub fn kill_for( |
| 27 | run: &AgentRun, |
| 28 | plan: &RunPlan, |
| 29 | plan_for_launch_id: impl Fn(&AgentRun) -> Option<RunPlan>, |
| 30 | ) -> Option<Invocation> { |
| 31 | let Some(launch_session_id) = run |
| 32 | .launch_session_id |
| 33 | .clone() |
| 34 | .filter(|launch| *launch != run.session_id) |
| 35 | else { |
| 36 | return orphan_stop(run, plan); |
| 37 | }; |
| 38 | let launched = AgentRun { |
| 39 | session_id: launch_session_id, |
| 40 | ..run.clone() |
| 41 | }; |
| 42 | let launched_plan = plan_for_launch_id(&launched)?; |
| 43 | for path in &launched_plan.cleanup { |
| 44 | let _ = std::fs::remove_file(path); |
| 45 | } |
| 46 | orphan_stop(&launched, &launched_plan) |
| 47 | } |
| 48 | |
| 49 | pub fn orphan_kill( |
| 50 | run: &AgentRun, |
| 51 | plan_for_run: impl Fn(&AgentRun) -> Option<RunPlan>, |
| 52 | ) -> Option<Invocation> { |
| 53 | let plan = plan_for_run(run)?; |
| 54 | for path in &plan.cleanup { |
| 55 | let _ = std::fs::remove_file(path); |
| 56 | } |
| 57 | kill_for(run, &plan, plan_for_run) |
| 58 | } |
| 59 | |
| 60 | pub async fn execute(stop: Invocation) { |
| 61 | let _ = runtime::spawn(async move { agents::run_stop_invocation(&stop).await }).await; |
| 62 | } |