use std::{
collections::BTreeMap,
path::Path,
sync::Mutex,
time::{Duration, Instant},
};
use tokio::{io::AsyncReadExt, task::JoinHandle};
use tokio_util::sync::CancellationToken;
use crate::{platform, process, types::SessionId};
use super::{AcpBinding, AgentId, Problem, engine::VerifiedAcpLaunch, wire::Connection};
pub const IDLE_TTL: Duration = Duration::from_secs(5 * 60);
pub const MAX_WARM_SESSIONS: usize = 4;
const STDERR_LIMIT: usize = 16 * 1024;
const STDERR_READ: usize = 4096;
const STOP_GRACE: Duration = Duration::from_secs(2);
pub struct WarmChild {
pub session_id: SessionId,
pub agent_id: AgentId,
pub generation: u64,
pub executable_sha256: String,
pub runtime_fingerprint: String,
pub remote_session_id: Option<String>,
pub connection: Connection,
child: platform::Child,
stderr: JoinHandle<Vec<u8>>,
process_cancel: CancellationToken,
last_used: Instant,
quiescent: bool,
}
impl WarmChild {
pub(crate) async fn spawn(
session_id: SessionId,
launch: &VerifiedAcpLaunch,
generation: u64,
worktree: &Path,
) -> Result<Self, Problem> {
launch.reverify_before_exec(worktree)?;
let spec = &launch.spec;
let resolved_executable = &launch.fingerprint.resolved_executable;
let executable_sha256 = launch.fingerprint.executable_sha256.clone();
let runtime_fingerprint = launch.runtime_fingerprint.clone();
let process_cancel = CancellationToken::new();
let command = process::Command {
program: resolved_executable.as_os_str().to_owned(),
args: spec.args.iter().map(Into::into).collect(),
cwd: worktree.to_path_buf(),
env: spec.build_env(true),
timeout: Duration::MAX,
};
let mut child = process::spawn_supervised(&command, &process_cancel)
.await
.map_err(|error| {
if matches!(&error, process::Error::Spawn(e) if e.kind() == std::io::ErrorKind::NotFound) {
Problem::Missing {
agent: spec.name.clone(),
hint: spec.install_hint.clone(),
}
} else {
Problem::Failed(format!("Cannot start {}: {error}.", spec.name))
}
})?;
let stdout = child.stdout().take().expect("ACP stdout piped");
let stdin = child.stdin().take().expect("ACP stdin piped");
let mut stderr = child.stderr().take().expect("ACP stderr piped");
let stderr_task = tokio::spawn(async move {
let mut kept = Vec::new();
let mut buffer = [0u8; STDERR_READ];
while let Ok(count) = stderr.read(&mut buffer).await {
if count == 0 {
break;
}
kept.extend_from_slice(&buffer[..count]);
if kept.len() > STDERR_LIMIT {
kept.drain(..kept.len() - STDERR_LIMIT);
}
}
kept
});
let connection = Connection::new(
&spec.name,
&spec.install_hint,
stdout,
stdin,
spec.hide_always_options,
spec.known_secrets(),
);
Ok(Self {
session_id,
agent_id: spec.id.clone(),
generation,
executable_sha256,
runtime_fingerprint,
remote_session_id: None,
connection,
child,
stderr: stderr_task,
process_cancel,
last_used: Instant::now(),
quiescent: false,
})
}
pub fn mark_quiescent(&mut self, remote_session_id: Option<String>) {
self.quiescent = true;
self.remote_session_id = remote_session_id;
self.last_used = Instant::now();
}
pub async fn terminate(mut self) -> Vec<u8> {
self.process_cancel.cancel();
drop(self.connection);
let exited = tokio::time::timeout(STOP_GRACE, self.child.wait()).await;
if !matches!(exited, Ok(Ok(_))) {
let _ = process::terminate(&mut self.child).await;
}
let _ = self.child.cleanup().await;
crate::task::joined(self.stderr.await).unwrap_or_default()
}
}
pub enum TakeOutcome {
Warm(Box<WarmChild>),
Retired {
stale: Box<WarmChild>,
digest_mismatch: bool,
},
Absent,
}
#[derive(Default)]
pub struct Pool {
entries: Mutex<BTreeMap<SessionId, WarmChild>>,
}
impl Pool {
pub fn take_for_turn(
&self,
session_id: &SessionId,
binding: Option<&AcpBinding>,
agent_id: &AgentId,
verified_sha256: &str,
runtime_fingerprint: &str,
) -> TakeOutcome {
let mut entries = self.entries.lock().expect("ACP warm pool lock");
let Some(mut child) = entries.remove(session_id) else {
return TakeOutcome::Absent;
};
let digest_mismatch = child.executable_sha256 != verified_sha256;
let matches = child.quiescent
&& !digest_mismatch
&& child.agent_id == *agent_id
&& child.runtime_fingerprint == runtime_fingerprint
&& child.last_used.elapsed() < IDLE_TTL
&& binding.is_some_and(|b| b.generation == child.generation);
if matches {
child.quiescent = false;
child.last_used = Instant::now();
TakeOutcome::Warm(Box::new(child))
} else {
TakeOutcome::Retired {
stale: Box::new(child),
digest_mismatch,
}
}
}
pub fn park(&self, mut child: WarmChild) -> Vec<WarmChild> {
child.last_used = Instant::now();
let mut entries = self.entries.lock().expect("ACP warm pool lock");
let mut evicted = Vec::new();
if let Some(previous) = entries.insert(child.session_id.clone(), child) {
evicted.push(previous);
}
let expired_ids: Vec<SessionId> = entries
.iter()
.filter(|(_, entry)| entry.last_used.elapsed() >= IDLE_TTL)
.map(|(id, _)| id.clone())
.collect();
for id in expired_ids {
if let Some(victim) = entries.remove(&id) {
evicted.push(victim);
}
}
while entries.len() > MAX_WARM_SESSIONS {
let Some(oldest_id) = entries
.iter()
.min_by_key(|(_, entry)| entry.last_used)
.map(|(id, _)| id.clone())
else {
break;
};
if let Some(victim) = entries.remove(&oldest_id) {
evicted.push(victim);
}
}
evicted
}
pub fn take_any(&self, session_id: &SessionId) -> Option<WarmChild> {
self.entries
.lock()
.expect("ACP warm pool lock")
.remove(session_id)
}
pub fn take_if_generation_stale(
&self,
session_id: &SessionId,
saved_generation: Option<u64>,
) -> Option<WarmChild> {
let mut entries = self.entries.lock().expect("ACP warm pool lock");
let stale = entries
.get(session_id)
.is_some_and(|warm| saved_generation != Some(warm.generation));
if stale {
entries.remove(session_id)
} else {
None
}
}
pub fn take_expired(&self) -> Vec<WarmChild> {
let mut entries = self.entries.lock().expect("ACP warm pool lock");
let expired: Vec<SessionId> = entries
.iter()
.filter(|(_, entry)| entry.last_used.elapsed() >= IDLE_TTL)
.map(|(id, _)| id.clone())
.collect();
expired
.into_iter()
.filter_map(|id| entries.remove(&id))
.collect()
}
pub fn drain_all(&self) -> Vec<WarmChild> {
let mut entries = self.entries.lock().expect("ACP warm pool lock");
let ids: Vec<SessionId> = entries.keys().cloned().collect();
ids.into_iter()
.filter_map(|id| entries.remove(&id))
.collect()
}
}