use agent_client_protocol::v2::schema as v2;
use std::time::Duration;
use tokio::time::Instant;
pub(super) const BACKGROUND_BUDGET: Duration = Duration::from_secs(600);
pub(super) const FOLLOW_UP_WAIT: Duration = Duration::from_secs(30);
#[derive(Default)]
pub(super) struct Background {
listed: Vec<Item>,
running: bool,
ended: Vec<Item>,
open: Vec<String>,
budget: Option<Instant>,
follow_up: Option<Instant>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
enum Item {
Command(String),
ToolCall(String),
Subagent(String),
Other(String),
}
impl std::fmt::Display for Item {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Command(id) => write!(f, "command {id}"),
Self::ToolCall(id) => write!(f, "tool call {id}"),
Self::Subagent(id) => write!(f, "subagent {id}"),
Self::Other(kind) => write!(f, "{kind} work"),
}
}
}
impl Background {
pub(super) fn observe(&mut self, state: &v2::StateUpdate) {
let running = matches!(
state,
v2::StateUpdate::Running(_) | v2::StateUpdate::RequiresAction(_)
);
if running && !self.running {
self.ended.clear();
self.open.clear();
self.follow_up = None;
}
self.running = running;
let listed: Vec<Item> = state
.background()
.unwrap_or_default()
.iter()
.map(item)
.collect();
let gone = self.listed.iter().filter(|item| !listed.contains(item));
self.ended.extend(gone.cloned());
self.listed = listed;
}
pub(super) fn tool_call(&mut self, call: &v2::ToolCallUpdate) {
if !self.running {
return;
}
let id = call.tool_call_id.to_string();
match call.status.value() {
Some(v2::ToolCallStatus::Pending | v2::ToolCallStatus::InProgress) => {
if !self.open.contains(&id) {
self.open.push(id);
}
}
Some(v2::ToolCallStatus::Completed | v2::ToolCallStatus::Failed) => {
let Some(at) = self.open.iter().position(|open| *open == id) else {
return;
};
self.open.swap_remove(at);
self.ended.retain(|item| !matches!(item, Item::Command(_)));
}
_ => {}
}
}
pub(super) fn idle(&mut self, now: Instant) -> Option<Instant> {
if self.listed.is_empty() && self.ended.is_empty() {
return None;
}
self.budget.get_or_insert(now + BACKGROUND_BUDGET);
if self.listed.is_empty() {
self.follow_up.get_or_insert(now + FOLLOW_UP_WAIT);
} else {
self.follow_up = None;
}
self.deadline()
}
pub(super) fn keeping(&self) -> bool {
self.budget.is_some()
}
pub(super) fn deadline(&self) -> Option<Instant> {
match (self.budget, self.follow_up) {
(Some(budget), Some(follow_up)) => Some(budget.min(follow_up)),
(budget, follow_up) => budget.or(follow_up),
}
}
pub(super) fn expired(&self, now: Instant) -> Option<String> {
if self.budget.is_none_or(|budget| now < budget) {
return None;
}
let turn = self
.running
.then(|| "a turn the agent started on its own".to_owned());
let still: Vec<String> = turn
.into_iter()
.chain(self.listed.iter().map(Item::to_string))
.collect();
let still = match still.is_empty() {
true => "the report of work that ended".to_owned(),
false => still.join(", "),
};
Some(format!(
"acp: background work budget of {} min after the prompted turn is spent; stopping the agent with still running: {still}",
BACKGROUND_BUDGET.as_secs() / 60,
))
}
pub(super) fn prompted(&mut self) {
self.budget = None;
self.follow_up = None;
}
}
fn item(work: &v2::BackgroundWork) -> Item {
match work {
v2::BackgroundWork::Terminal(terminal) => Item::Command(terminal.terminal_id.to_string()),
v2::BackgroundWork::ToolCall(call) => Item::ToolCall(call.tool_call_id.to_string()),
v2::BackgroundWork::Subagent(subagent) => Item::Subagent(subagent.session_id.to_string()),
v2::BackgroundWork::Other(other) => Item::Other(other.kind.clone()),
_ => Item::Other("background".to_owned()),
}
}
#[cfg(test)]
#[path = "background_tests.rs"]
mod tests;