Skip to content

Open source Grok Bot alternative, Bring your own agent and subscription: message Claude Code, Codex, Gemini CLI, Cursor, Copilot and 40+ AI agents as bots on your own computer, from iPhone, Mac, Windows, Linux or terminal. Agent-agnostic and free. Also a Muse and Dots alternative. Built in Rust.

fix(host): stop an agent's whole process tree when it exits, crashes or is dropped

leepokai51a72343b931
diff --git a/docs/architecture/file-structure.md b/docs/architecture/file-structure.md
index b6715cfa..ee858a72 100644
--- a/docs/architecture/file-structure.md
+++ b/docs/architecture/file-structure.md
@@ -89,7 +89,7 @@ Codync/
| CLI and background service | `host/src/main.rs`, `service/` |
| API, caller permissions, event ordering | `host/src/api/`, `hub.rs` |
| SQLite transcript, bots, lanes and sessions | `host/src/store/` (`entries.rs`, `bots.rs`, `model.rs`, `devices.rs`, `schema.rs`) |
-| Agent process, ACP, queue and session lifecycle | `host/src/agent/bot/` (`launch.rs`, `queue.rs`, `session.rs`, `turn.rs`, `updates.rs`), `acp.rs` (+ `acp/codebuddy.rs`, CodeBuddy's ACP extensions) |
+| Agent process, ACP, queue and session lifecycle | `host/src/agent/bot/` (`launch.rs`, `queue.rs`, `session.rs`, `turn.rs`, `updates.rs`), `acp.rs` (+ `acp/codebuddy.rs`, CodeBuddy's ACP extensions), `process.rs` (process-tree ownership; `process_windows.rs` on Windows) |
| Compaction timing and rollover | `host/src/agent/bot/compaction.rs`, the handoff card in `host/src/chat/handoff.rs`; the rules in `codync-mem`'s `compaction.rs` |
| Group room turns / bot-to-bot requests | `host/src/chat/group.rs` / `team.rs` |
| Voice calls (the call, the voice's instructions and tools, transcripts, call lines) | `host/src/chat/calls/` (`mod.rs`, `context.rs`, `project.rs` the git state, `tools.rs`, `announce.rs` what the voice hears while the call lasts, `speech.rs` text as a voice says it); the user's messages it relays go through `host/src/chat/messages.rs` like typed ones; clients' `CallLink` (iPhone `CodyncUI/Call/CallLink.swift`, desktop `views/call/call-link.ts`, Android `core/Calls.kt` + `HostCallLink.kt`) and call rows (`CallRows`); the call on the iPhone's Lock Screen (`CodyncUI/Call/CallActivity.swift`, the Live Activity) and Android's call notification (`VoiceService.kt`) |
diff --git a/host/Cargo.lock b/host/Cargo.lock
index 58a1d68d..0665cc0c 100644
--- a/host/Cargo.lock
+++ b/host/Cargo.lock
@@ -754,6 +754,7 @@ dependencies = [
"tracing-subscriber",
"unicode-width",
"uuid",
+ "windows-sys 0.61.2",
"x25519-dalek",
"zeroize",
]
diff --git a/host/Cargo.toml b/host/Cargo.toml
index 87a5f926..26dd7dfa 100644
--- a/host/Cargo.toml
+++ b/host/Cargo.toml
@@ -69,6 +69,7 @@ keyring = { version = "3.6.3", features = ["sync-secret-service", "crypto-rust",
[target.'cfg(windows)'.dependencies]
keyring = { version = "3.6.3", features = ["windows-native"] }
+windows-sys = { version = "0.61.2", features = ["Win32_Foundation", "Win32_System_JobObjects", "Win32_System_Threading", "Win32_System_Diagnostics_ToolHelp", "Win32_Security"] }
# rust-skills lint-* rules: all default groups plus pedantic, with the
# library-oriented pedantic lints turned off for this binary crate.
diff --git a/host/src/agent/acp.rs b/host/src/agent/acp.rs
index 97ab7fae..7579095b 100644
--- a/host/src/agent/acp.rs
+++ b/host/src/agent/acp.rs
@@ -2,6 +2,7 @@
//! process's stdio. Updates are kept as `serde_json::Value` on purpose so a
//! newer adapter adding a variant never breaks parsing.
+use super::process::Process;
use crate::LockExt;
use crate::agent::fallback::reason::{self, Reason};
use anyhow::{Context, Result};
@@ -12,9 +13,8 @@ use std::sync::Arc;
use std::sync::atomic::{AtomicI64, Ordering};
use std::time::Duration;
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
-use tokio::process::{Child, ChildStdin, Command};
+use tokio::process::ChildStdin;
use tokio::sync::{mpsc, oneshot};
-use tokio::time::Instant;
pub mod codebuddy;
@@ -114,12 +114,15 @@ impl std::error::Error for Failure {}
/// A request already written to the agent, waiting for its response.
pub struct Answer {
- rx: oneshot::Receiver<std::result::Result<Value, Value>>,
+ id: i64,
+ pending: Pending,
+ rx: Option<oneshot::Receiver<std::result::Result<Value, Value>>>,
}
impl Answer {
- pub async fn response(self) -> Result<Value> {
- match self.rx.await {
+ pub async fn response(mut self) -> Result<Value> {
+ let receiver = self.rx.take().expect("a response is consumed once");
+ match receiver.await {
Ok(Ok(v)) => Ok(v),
Ok(Err(e)) => Err(rpc_error(&e).into()),
// The reader drops every waiter when the process goes away.
@@ -128,6 +131,13 @@ impl Answer {
}
}
+/// An abandoned request (timed out, cancelled) no longer waits for its response.
+impl Drop for Answer {
+ fn drop(&mut self) {
+ self.pending.locked().remove(&self.id);
+ }
+}
+
/// A JSON-RPC error object as an [`RpcError`].
fn rpc_error(e: &Value) -> RpcError {
let msg = e["message"].as_str().map_or_else(|| e.to_string(), str::to_owned);
@@ -163,8 +173,8 @@ pub struct Acp {
stdin: tokio::sync::Mutex<Option<ChildStdin>>,
next_id: AtomicI64,
pending: Pending,
- /// `None` once stopped (handed to [`reap`]).
- child: tokio::sync::Mutex<Option<Child>>,
+ /// Owns the agent's whole process tree: dropping it kills what the agent started.
+ child: Arc<tokio::sync::Mutex<Process>>,
/// The process (and, on Unix, process group) leader.
pid: Option<u32>,
}
@@ -188,10 +198,15 @@ impl Acp {
// Its own group, so `kill` can stop everything it started.
#[cfg(unix)]
process.process_group(0);
+ #[cfg(windows)]
+ process.creation_flags(windows_sys::Win32::System::Threading::CREATE_SUSPENDED);
let mut child = process.spawn().with_context(|| format!("starting `{command}`"))?;
let stdin = child.stdin.take().expect("stdin is piped");
let stdout = child.stdout.take().expect("stdout is piped");
let stderr = child.stderr.take().expect("stderr is piped");
+ let pid = child.id();
+ let child = Arc::new(tokio::sync::Mutex::new(Process::new(child)?));
+ Process::monitor(&child);
// Deliberately unbounded: `session/load` replays a whole history as notifications
// *before* its response, while the bot is still awaiting that response. A bounded
// queue would stall this reader, and with it the response — a deadlock.
@@ -251,12 +266,11 @@ impl Acp {
});
}
- let pid = child.id();
let acp = Arc::new(Self {
stdin: tokio::sync::Mutex::new(Some(stdin)),
next_id: AtomicI64::new(1),
pending,
- child: tokio::sync::Mutex::new(Some(child)),
+ child,
pid,
});
Ok((acp, rx))
@@ -277,7 +291,8 @@ impl Acp {
}
pub async fn request(&self, method: &str, params: Value) -> Result<Value> {
- self.send(method, params).await?.response().await
+ let answer = self.send(method, params).await?;
+ answer.response().await
}
/// Writes a request and returns its pending answer: anything written after this
@@ -286,8 +301,9 @@ impl Acp {
let id = self.next_id.fetch_add(1, Ordering::Relaxed);
let (tx, rx) = oneshot::channel();
self.pending.locked().insert(id, tx);
+ let answer = Answer { id, pending: self.pending.clone(), rx: Some(rx) };
self.write(json!({"jsonrpc": "2.0", "id": id, "method": method, "params": params})).await?;
- Ok(Answer { rx })
+ Ok(answer)
}
pub async fn notify(&self, method: &str, params: Value) -> Result<()> {
@@ -306,12 +322,15 @@ impl Acp {
/// lets it exit by itself first: Claude Code killed during an OAuth refresh loses the new
/// refresh token, and the user's login with it.
pub async fn kill(&self) {
- self.stdin.lock().await.take();
- if let Some(child) = self.child.lock().await.take() {
- let mut stopping = STOPPING.locked();
- stopping.retain(|task| !task.is_finished());
- stopping.push(tokio::spawn(reap(child)));
+ let mut child = self.child.lock().await;
+ if !child.begin_stop() {
+ return;
}
+ self.stdin.lock().await.take();
+ let owned = self.child.clone();
+ let mut stopping = STOPPING.locked();
+ stopping.retain(|task| !task.is_finished());
+ stopping.push(tokio::spawn(async move { owned.lock().await.stop_within(EXIT_GRACE).await }));
}
}
@@ -321,52 +340,6 @@ pub async fn stopped() {
futures::future::join_all(tasks).await;
}
-/// Gives the agent [`EXIT_GRACE`] to exit with everything it started (ACP adapters spawn
-/// CLIs, MCP servers and tools), then kills its process group (Windows: process tree).
-async fn reap(mut child: Child) {
- let Some(pid) = child.id() else { return };
- let deadline = Instant::now() + EXIT_GRACE;
- let exited = tokio::time::timeout_at(deadline, child.wait()).await.is_ok();
- if !exited || outlived(pid, deadline).await {
- let mut tree = if cfg!(windows) {
- let mut c = Command::new("taskkill");
- c.args(["/T", "/F", "/PID", &pid.to_string()]);
- c
- } else {
- let mut c = Command::new("/bin/kill");
- c.args(["-KILL", "--", &format!("-{pid}")]);
- c
- };
- let _ = tree.stdout(Stdio::null()).stderr(Stdio::null()).status().await;
- }
- // Already exited is fine; anything else is worth a log line.
- if let Err(error) = child.kill().await
- && error.kind() != std::io::ErrorKind::InvalidInput
- {
- tracing::debug!(%error, "couldn't kill agent process");
- }
-}
-
-/// Whether part of the exited agent's process group is still running at `deadline`.
-#[cfg(unix)]
-async fn outlived(pid: u32, deadline: Instant) -> bool {
- let Ok(group) = libc::pid_t::try_from(pid) else { return true };
- // SAFETY: signal 0 sends nothing; it only checks that the group still has a process.
- let running = || unsafe { libc::killpg(group, 0) } == 0;
- while running() && Instant::now() < deadline {
- tokio::time::sleep(Duration::from_millis(100)).await;
- }
- running()
-}
-
-/// Windows has no process groups: what the agent started got the same closed pipes, and its
-/// tree can't be found once it's gone.
-#[cfg(windows)]
-#[allow(clippy::unused_async)] // the Unix check's signature
-async fn outlived(_pid: u32, _deadline: Instant) -> bool {
- false
-}
-
/// Plain-text rendering of an ACP content block list / tool-call content list.
pub fn content_text(v: &Value) -> String {
match v {
@@ -399,6 +372,74 @@ pub fn truncate(s: &str, max: usize) -> String {
mod tests {
use super::*;
+ async fn descendant_agent() -> (Arc<Acp>, mpsc::UnboundedReceiver<Incoming>) {
+ let script = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/process_agent.py");
+ let python = if cfg!(windows) { "python" } else { "python3" };
+ let command = format!("{python} -u {}", crate::shell::quote(&script.display().to_string()));
+ let (acp, mut rx) = Acp::spawn(&command, env!("CARGO_MANIFEST_DIR"), &[]).unwrap();
+ let ready = tokio::time::timeout(Duration::from_secs(15), rx.recv()).await;
+ let ready = ready.unwrap();
+ assert!(matches!(ready, Some(Incoming::Notification { method, .. }) if method == "ready"));
+ (acp, rx)
+ }
+
+ async fn assert_descendant_pipes_close(mut rx: mpsc::UnboundedReceiver<Incoming>) {
+ let closed = tokio::time::timeout(Duration::from_secs(5), rx.recv()).await;
+ let closed = closed.unwrap();
+ assert!(matches!(closed, Some(Incoming::Closed { .. })));
+ }
+
+ #[tokio::test]
+ async fn leader_exit_releases_descendants_without_waiting_for_stdout_eof() {
+ let (acp, rx) = descendant_agent().await;
+ let notified = acp.notify("exit", json!({})).await;
+ notified.unwrap();
+ assert_descendant_pipes_close(rx).await;
+ }
+
+ #[tokio::test]
+ async fn dropping_an_agent_releases_its_process_tree() {
+ let (acp, rx) = descendant_agent().await;
+ drop(acp);
+ assert_descendant_pipes_close(rx).await;
+ }
+
+ #[tokio::test]
+ async fn actor_unwinding_releases_its_process_tree() {
+ let (acp, rx) = descendant_agent().await;
+ let task = tokio::spawn(async move {
+ let _owned = acp;
+ panic!("simulated actor panic");
+ });
+ let panicked = task.await;
+ assert!(panicked.unwrap_err().is_panic());
+ assert_descendant_pipes_close(rx).await;
+ }
+
+ #[tokio::test]
+ async fn timed_out_requests_do_not_accumulate_pending_answers() {
+ let (acp, rx) = descendant_agent().await;
+ for _ in 0..10 {
+ let response = tokio::time::timeout(Duration::from_millis(10), acp.request("never", json!({}))).await;
+ assert!(response.is_err());
+ assert_eq!(acp.pending.locked().len(), 0);
+ }
+ acp.kill().await;
+ stopped().await;
+ assert_descendant_pipes_close(rx).await;
+ }
+
+ #[cfg(unix)]
+ #[tokio::test]
+ async fn a_stopped_agent_that_exits_cleanly_does_not_hold_the_host_for_the_grace_period() {
+ let (acp, mut rx) = Acp::spawn("cat", env!("CARGO_MANIFEST_DIR"), &[]).unwrap();
+ let started = tokio::time::Instant::now();
+ acp.kill().await;
+ stopped().await;
+ assert!(started.elapsed() < EXIT_GRACE / 2, "stopping waited out the grace period");
+ assert!(matches!(rx.recv().await, Some(Incoming::Closed { .. })));
+ }
+
#[test]
fn content_text_flattens_blocks() {
let v = json!([
@@ -415,7 +456,10 @@ mod tests {
let kind = |data: Value| async move {
let (tx, rx) = oneshot::channel();
let _ = tx.send(Err(json!({"code": -32603, "message": "Internal error", "data": data})));
- let e = Answer { rx }.response().await.expect_err("an error answer");
+ let e = Answer { id: 0, pending: Pending::default(), rx: Some(rx) }
+ .response()
+ .await
+ .expect_err("an error answer");
e.downcast::<RpcError>().expect("an RpcError").kind
};
assert_eq!(kind(json!({"errorKind": "rate_limit"})).await.as_deref(), Some("rate_limit"));
diff --git a/host/src/agent/mod.rs b/host/src/agent/mod.rs
index bfe23b3f..1a03001e 100644
--- a/host/src/agent/mod.rs
+++ b/host/src/agent/mod.rs
@@ -13,3 +13,7 @@ pub mod own_memory;
pub mod registry;
pub mod term;
pub mod workspace;
+
+mod process;
+#[cfg(windows)]
+mod process_windows;
diff --git a/host/src/agent/process.rs b/host/src/agent/process.rs
new file mode 100644
index 00000000..8f05613e
--- /dev/null
+++ b/host/src/agent/process.rs
@@ -0,0 +1,229 @@
+//! Own the agent's descendants even after its leader exits or the actor unwinds.
+
+use anyhow::{Context, Result};
+use std::sync::Arc;
+use std::time::Duration;
+use tokio::process::Child;
+use tokio::sync::Mutex;
+use tokio::time::Instant;
+
+const REAP_TIMEOUT: Duration = Duration::from_secs(5);
+const POLL: Duration = Duration::from_millis(100);
+
+pub(super) struct Process {
+ // Drop the tree before Child can reap the leader and make its PID reusable.
+ tree: Tree,
+ child: Child,
+ stopping: bool,
+}
+
+impl Process {
+ pub(super) fn new(child: Child) -> Result<Self> {
+ let tree = Tree::new(&child)?;
+ let owned = Self { tree, child, stopping: false };
+ #[cfg(windows)]
+ super::process_windows::resume(&owned.child)?;
+ Ok(owned)
+ }
+
+ pub(super) fn monitor(child: &Arc<Mutex<Self>>) {
+ let weak = Arc::downgrade(child);
+ tokio::spawn(async move {
+ loop {
+ let Some(child) = weak.upgrade() else { break };
+ let mut process = child.lock().await;
+ if process.stopping {
+ break;
+ }
+ match process.exited() {
+ Ok(true) => {
+ process.kill().await;
+ break;
+ }
+ Ok(false) => {}
+ Err(error) => {
+ tracing::warn!(%error, "couldn't observe agent process exit");
+ process.kill().await;
+ break;
+ }
+ }
+ drop(process);
+ drop(child);
+ tokio::time::sleep(POLL).await;
+ }
+ });
+ }
+
+ #[cfg(unix)]
+ fn exited(&self) -> std::io::Result<bool> {
+ let Some(pid) = self.child.id() else { return Ok(true) };
+ // SAFETY: zero is a valid siginfo value; waitid writes only into this object.
+ let mut info: libc::siginfo_t = unsafe { std::mem::zeroed() };
+ // Keep the leader unreaped until its group is killed, preventing PID reuse.
+ // SAFETY: pid identifies our owned child and the output pointer is writable.
+ let result =
+ unsafe { libc::waitid(libc::P_PID, pid, &raw mut info, libc::WEXITED | libc::WNOHANG | libc::WNOWAIT) };
+ if result == -1 {
+ let error = std::io::Error::last_os_error();
+ if error.kind() == std::io::ErrorKind::Interrupted {
+ return Ok(false);
+ }
+ return Err(error);
+ }
+ #[cfg(target_os = "macos")]
+ let exited = info.si_pid != 0;
+ #[cfg(not(target_os = "macos"))]
+ // SAFETY: waitid initialized the child-status variant of siginfo.
+ let exited = unsafe { info.si_pid() } != 0;
+ Ok(exited)
+ }
+
+ #[cfg(windows)]
+ fn exited(&self) -> std::io::Result<bool> {
+ use windows_sys::Win32::Foundation::{WAIT_FAILED, WAIT_OBJECT_0};
+ let Some(handle) = self.child.raw_handle() else { return Ok(true) };
+ // SAFETY: the child owns this valid process handle; a zero timeout cannot block.
+ let status = unsafe { windows_sys::Win32::System::Threading::WaitForSingleObject(handle, 0) };
+ if status == WAIT_FAILED {
+ return Err(std::io::Error::last_os_error());
+ }
+ Ok(status == WAIT_OBJECT_0)
+ }
+
+ /// The graceful-shutdown task keeps ownership until its deadline.
+ pub(super) fn begin_stop(&mut self) -> bool {
+ !std::mem::replace(&mut self.stopping, true)
+ }
+
+ /// Gives the leader and everything it started until `grace` runs out to finish by themselves,
+ /// then kills what is left. Returns as soon as nothing is left.
+ pub(super) async fn stop_within(&mut self, grace: Duration) {
+ let deadline = Instant::now() + grace;
+ while !self.exited().unwrap_or(true) && Instant::now() < deadline {
+ tokio::time::sleep(POLL).await;
+ }
+ #[cfg(unix)]
+ if self.exited().unwrap_or(false) {
+ // Reaped, the leader no longer pins its PID: only a live group member does, and
+ // that is what `drained` waits out.
+ let _ = self.child.wait().await;
+ self.tree.drained(deadline).await;
+ }
+ self.kill().await;
+ }
+
+ pub(super) async fn kill(&mut self) {
+ if let Err(error) = self.tree.terminate() {
+ tracing::warn!(%error, "couldn't terminate agent descendants");
+ }
+ let result = tokio::time::timeout(REAP_TIMEOUT, self.child.kill()).await;
+ match result {
+ Ok(Ok(())) => {}
+ Ok(Err(error)) if error.kind() == std::io::ErrorKind::InvalidInput => {}
+ Ok(Err(error)) => tracing::warn!(%error, "couldn't reap agent process"),
+ Err(error) => tracing::warn!(%error, "agent process did not exit before the cleanup deadline"),
+ }
+ }
+}
+
+#[cfg(unix)]
+struct Tree {
+ group: Option<libc::pid_t>,
+}
+
+#[cfg(unix)]
+impl Tree {
+ fn new(child: &Child) -> Result<Self> {
+ let pid = child.id().context("agent exited before process ownership was established")?;
+ Ok(Self { group: Some(libc::pid_t::try_from(pid)?) })
+ }
+
+ /// Waits until the group has no process left, or `deadline`; an empty group is forgotten so
+ /// its (reusable) ID is never signalled.
+ async fn drained(&mut self, deadline: Instant) {
+ let Some(group) = self.group else { return };
+ // SAFETY: signal 0 sends nothing; it only checks that the group still has a process.
+ let running = || unsafe { libc::killpg(group, 0) } == 0;
+ while running() && Instant::now() < deadline {
+ tokio::time::sleep(POLL).await;
+ }
+ if !running() {
+ self.group = None;
+ }
+ }
+
+ fn terminate(&mut self) -> std::io::Result<()> {
+ let Some(group) = self.group.take() else { return Ok(()) };
+ // SAFETY: spawn put this still-owned, unreaped child in its own process group.
+ // A negative PID signals that group. No pointer or shared memory is involved.
+ if unsafe { libc::kill(-group, libc::SIGKILL) } == -1 {
+ let error = std::io::Error::last_os_error();
+ if error.raw_os_error() != Some(libc::ESRCH) {
+ return Err(error);
+ }
+ }
+ Ok(())
+ }
+}
+
+#[cfg(unix)]
+impl Drop for Tree {
+ fn drop(&mut self) {
+ if let Err(error) = self.terminate() {
+ tracing::warn!(%error, "couldn't release agent process group");
+ }
+ }
+}
+
+#[cfg(windows)]
+struct Tree {
+ handle: std::os::windows::io::OwnedHandle,
+}
+
+#[cfg(windows)]
+impl Tree {
+ fn new(child: &Child) -> Result<Self> {
+ use std::os::windows::io::{AsRawHandle, FromRawHandle};
+ use windows_sys::Win32::System::JobObjects::{
+ AssignProcessToJobObject, CreateJobObjectW, JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE,
+ JOBOBJECT_EXTENDED_LIMIT_INFORMATION, JobObjectExtendedLimitInformation, SetInformationJobObject,
+ };
+ // SAFETY: null uses default security and an unnamed, newly owned job.
+ let raw = unsafe { CreateJobObjectW(std::ptr::null(), std::ptr::null()) };
+ if raw.is_null() {
+ return Err(std::io::Error::last_os_error()).context("creating agent process job");
+ }
+ // SAFETY: CreateJobObjectW transferred a unique valid handle to this owner.
+ let handle = unsafe { std::os::windows::io::OwnedHandle::from_raw_handle(raw) };
+ let mut limits = JOBOBJECT_EXTENDED_LIMIT_INFORMATION::default();
+ limits.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
+ let size = u32::try_from(size_of_val(&limits))?;
+ // SAFETY: limits is initialized and its exact size is supplied for this class.
+ if unsafe {
+ SetInformationJobObject(
+ handle.as_raw_handle(),
+ JobObjectExtendedLimitInformation,
+ std::ptr::from_ref(&limits).cast(),
+ size,
+ )
+ } == 0
+ {
+ return Err(std::io::Error::last_os_error()).context("configuring agent process job");
+ }
+ let process = child.raw_handle().context("agent exited before process ownership was established")?;
+ // SAFETY: the child and job handles remain owned and valid during assignment.
+ if unsafe { AssignProcessToJobObject(handle.as_raw_handle(), process) } == 0 {
+ return Err(std::io::Error::last_os_error()).context("owning agent process descendants");
+ }
+ Ok(Self { handle })
+ }
+
+ fn terminate(&mut self) -> std::io::Result<()> {
+ use std::os::windows::io::AsRawHandle;
+ // SAFETY: this object owns the job handle; termination does not close it.
+ if unsafe { windows_sys::Win32::System::JobObjects::TerminateJobObject(self.handle.as_raw_handle(), 1) } == 0 {
+ return Err(std::io::Error::last_os_error());
+ }
+ Ok(())
+ }
+}
diff --git a/host/src/agent/process_windows.rs b/host/src/agent/process_windows.rs
new file mode 100644
index 00000000..c9ce4af8
--- /dev/null
+++ b/host/src/agent/process_windows.rs
@@ -0,0 +1,49 @@
+//! Resume the suspended ACP shell only after its job owns future descendants.
+
+use anyhow::{Context, Result, bail};
+use std::os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle};
+use tokio::process::Child;
+use windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE;
+use windows_sys::Win32::System::Diagnostics::ToolHelp::{
+ CreateToolhelp32Snapshot, TH32CS_SNAPTHREAD, THREADENTRY32, Thread32First, Thread32Next,
+};
+use windows_sys::Win32::System::Threading::{OpenThread, ResumeThread, THREAD_SUSPEND_RESUME};
+
+pub(super) fn resume(child: &Child) -> Result<()> {
+ let pid = child.id().context("agent exited before it could be resumed")?;
+ // SAFETY: this creates an owned thread snapshot; no pointers are supplied.
+ let raw = unsafe { CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0) };
+ if raw == INVALID_HANDLE_VALUE {
+ return Err(std::io::Error::last_os_error()).context("finding suspended agent thread");
+ }
+ // SAFETY: a successful snapshot transfers a unique valid handle to us.
+ let snapshot = unsafe { OwnedHandle::from_raw_handle(raw) };
+ let mut entry = THREADENTRY32::default();
+ entry.dwSize = u32::try_from(size_of_val(&entry))?;
+ // SAFETY: the snapshot is valid and entry has the required initialized size.
+ let mut present = unsafe { Thread32First(snapshot.as_raw_handle(), &raw mut entry) };
+ while present != 0 {
+ if entry.th32OwnerProcessID == pid {
+ // The owned shell was created suspended and cannot have started more threads.
+ // SAFETY: this opens that thread with only permission to resume it.
+ let raw = unsafe { OpenThread(THREAD_SUSPEND_RESUME, 0, entry.th32ThreadID) };
+ if raw.is_null() {
+ return Err(std::io::Error::last_os_error()).context("opening suspended agent thread");
+ }
+ // SAFETY: OpenThread transferred a unique valid handle to us.
+ let thread = unsafe { OwnedHandle::from_raw_handle(raw) };
+ // SAFETY: we own a valid handle with THREAD_SUSPEND_RESUME rights.
+ let count = unsafe { ResumeThread(thread.as_raw_handle()) };
+ if count == u32::MAX {
+ return Err(std::io::Error::last_os_error()).context("resuming agent thread");
+ }
+ if count != 1 {
+ bail!("agent thread had an unexpected suspension count");
+ }
+ return Ok(());
+ }
+ // SAFETY: the snapshot and writable entry remain valid during iteration.
+ present = unsafe { Thread32Next(snapshot.as_raw_handle(), &raw mut entry) };
+ }
+ bail!("couldn't find the suspended agent's initial thread")
+}
diff --git a/host/tests/fixtures/process_agent.py b/host/tests/fixtures/process_agent.py
new file mode 100644
index 00000000..ad4b936b
--- /dev/null
+++ b/host/tests/fixtures/process_agent.py
@@ -0,0 +1,19 @@
+"""Keep two descendant generations holding ACP stdout after the leader exits."""
+
+import json
+import subprocess
+import sys
+import time
+
+if len(sys.argv) > 1:
+ if sys.argv[1] == "child":
+ subprocess.Popen([sys.executable, "-u", __file__, "leaf"], stdin=subprocess.DEVNULL, stdout=sys.stdout, stderr=sys.stderr)
+ if sys.argv[1] == "leaf":
+ print(json.dumps({"jsonrpc": "2.0", "method": "ready"}), flush=True)
+ time.sleep(60)
+else:
+ subprocess.Popen([sys.executable, "-u", __file__, "child"], stdin=subprocess.DEVNULL, stdout=sys.stdout, stderr=sys.stderr)
+ for line in sys.stdin:
+ message = json.loads(line)
+ if message.get("method") == "exit":
+ break