Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

fix(agent): handle sub-agent lifecycle events in running subagents module

Steven Enamakelb274a293ccbe
diff --git a/crates/openhuman-core/src/agent/orchestration/running_subagents/cancel.rs b/crates/openhuman-core/src/agent/orchestration/running_subagents/cancel.rs
index 38498c31ff..610adcabac 100644
--- a/crates/openhuman-core/src/agent/orchestration/running_subagents/cancel.rs
+++ b/crates/openhuman-core/src/agent/orchestration/running_subagents/cancel.rs
@@ -7,7 +7,9 @@ use std::path::{Path, PathBuf};
use tinyagents_harness::ids::TaskId;
-use super::registry::{registry, SubagentStatus};
+use tinyagents_orchestration::subagent::FinishedOutcome;
+
+use super::registry::registry;
use super::resolve::task_id_for_session_in_workspace;
use super::task_ledger::record_cancelled;
@@ -28,23 +30,6 @@ pub(crate) struct CancelledSubagent {
pub(crate) already_finished: Option<FinishedOutcome>,
}
-/// The terminal outcome of a run that finished before its cancel arrived.
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-pub(crate) enum FinishedOutcome {
- Completed,
- Failed,
-}
-
-impl FinishedOutcome {
- /// Wire name in the `subagent_cancel` answer (`outcome`).
- pub(crate) fn as_str(self) -> &'static str {
- match self {
- Self::Completed => "completed",
- Self::Failed => "failed",
- }
- }
-}
-
/// Abort and drop the sub-agent with `task_id`, returning its metadata so the
/// caller can deliver a "cancelled" notice into the parent chat. Returns `None`
/// if no such sub-agent is registered (already finished, or unknown id).
@@ -55,11 +40,7 @@ impl FinishedOutcome {
pub(crate) fn cancel_by_task(task_id: &str) -> Option<CancelledSubagent> {
let cancelled = registry().cancel_trusted(&TaskId::new(task_id)).ok()?;
// `AwaitingUser` is paused, not finished: cancelling it is a real cancel.
- let already_finished = match cancelled.status {
- SubagentStatus::Completed { .. } => Some(FinishedOutcome::Completed),
- SubagentStatus::Failed { .. } => Some(FinishedOutcome::Failed),
- SubagentStatus::Running | SubagentStatus::AwaitingUser { .. } => None,
- };
+ let already_finished = cancelled.status.finished_outcome();
let metadata = cancelled.metadata;
if already_finished.is_none() {
record_cancelled(&metadata.workspace_dir, task_id);
diff --git a/crates/openhuman-core/src/agent/orchestration/running_subagents/registry.rs b/crates/openhuman-core/src/agent/orchestration/running_subagents/registry.rs
index c73942c4e9..33516a3d04 100644
--- a/crates/openhuman-core/src/agent/orchestration/running_subagents/registry.rs
+++ b/crates/openhuman-core/src/agent/orchestration/running_subagents/registry.rs
@@ -1,5 +1,5 @@
//! The in-process registry of running async sub-agents: registration,
-//! per-task metadata, and the terminal/transient [`SubagentStatus`] each entry
+//! per-task metadata, and the terminal/transient [`DetachedSubagentStatus`] each entry
//! carries.
//!
//! Each running async sub-agent registers here (via [`register`]), keyed by
@@ -10,7 +10,7 @@
//! - a TinyAgents `SteeringHandle` in the process-local
//! `SteeringRegistry` while the child TinyAgents run is active, so
//! steer/collect controls can deliver directly to the crate queue;
-//! - a `watch::Receiver<SubagentStatus>` — so `wait_subagent` can block until the
+//! - a `watch::Receiver<DetachedSubagentStatus>` — so `wait_subagent` can block until the
//! child reaches a terminal status;
//! - an `AbortHandle` — used by `subagent_cancel`/`close_subagent` paths to stop
//! detached work.
@@ -32,27 +32,10 @@ use tinyagents_harness::ids::TaskId;
use tinyagents_harness::run_queue::RunQueue;
use tinyagents_harness::CancellationToken;
-use super::task_ledger::record_spawned;
-
-/// Terminal/transient state of a running async sub-agent, published by the
-/// spawner's background task and observed by `wait_subagent`.
-#[derive(Debug, Clone)]
-pub(crate) enum SubagentStatus {
- /// Still executing its inner tool-call loop.
- Running,
- /// Finished normally with a final response.
- Completed { output: String, iterations: usize },
- /// Paused on `ask_user_clarification`; resume via `continue_subagent`.
- AwaitingUser { question: String },
- /// The run errored out.
- Failed { error: String },
-}
-
-impl SubagentStatus {
- pub(crate) fn is_terminal(&self) -> bool {
- !matches!(self, SubagentStatus::Running)
- }
-}
+use super::task_ledger::{record_spawned, task_store_for_workspace};
+use tinyagents_orchestration::subagent::{
+ spawn_status_watcher, DetachedSubagentStatus, SubagentIdentity,
+};
#[derive(Clone)]
pub(crate) struct RunningSubagentMetadata {
@@ -66,31 +49,28 @@ pub(crate) struct RunningSubagentMetadata {
pub(crate) run_queue: Arc<RunQueue<crate::agent::queued_turn::QueuedTurn>>,
}
-#[derive(Debug, Clone, PartialEq, Eq)]
-pub(crate) struct SubagentResumeRef {
- pub(crate) task_id: String,
- pub(crate) agent_id: String,
- pub(crate) subagent_session_id: Option<String>,
+impl SubagentIdentity for RunningSubagentMetadata {
+ fn agent_id(&self) -> &str {
+ &self.agent_id
+ }
+ fn subagent_session_id(&self) -> Option<&str> {
+ self.subagent_session_id.as_deref()
+ }
}
/// Soft cap on registry size. Terminal entries are only swept when the table
/// grows past this, so the common case (a handful of live sub-agents) never
/// evicts a still-uncollected terminal result out from under a `wait`/`steer`.
const REGISTRY_SOFT_CAP: usize = 256;
-/// Metadata-only timeout mirrored into the TinyAgents task ledger. It matches
-/// `wait_subagent`'s default wait window; execution remains governed by the
-/// existing detached task and wait-tool paths.
-pub(crate) const DETACHED_LEDGER_TIMEOUT_MS: u64 = 120_000;
-
-static REGISTRY: OnceLock<DetachedTaskRegistry<RunningSubagentMetadata, SubagentStatus>> =
+static REGISTRY: OnceLock<DetachedTaskRegistry<RunningSubagentMetadata, DetachedSubagentStatus>> =
OnceLock::new();
-pub(crate) fn registry() -> &'static DetachedTaskRegistry<RunningSubagentMetadata, SubagentStatus> {
+pub(crate) fn registry() -> &'static DetachedTaskRegistry<RunningSubagentMetadata, DetachedSubagentStatus> {
REGISTRY.get_or_init(|| {
DetachedTaskRegistry::new(
shared_steering_registry().clone(),
REGISTRY_SOFT_CAP,
- SubagentStatus::is_terminal,
+ DetachedSubagentStatus::is_terminal,
)
})
}
@@ -98,14 +78,14 @@ pub(crate) fn registry() -> &'static DetachedTaskRegistry<RunningSubagentMetadat
/// Create the status channel a spawner threads into [`register`].
///
/// The spawner moves the [`watch::Sender`] into its detached task and `send`s a
-/// terminal [`SubagentStatus`] on completion. Dropping the sender (e.g. a
+/// terminal [`DetachedSubagentStatus`] on completion. Dropping the sender (e.g. a
/// panicked/aborted task) closes the channel, which `wait_subagent` surfaces as
/// a failure rather than hanging.
pub(crate) fn status_channel() -> (
- watch::Sender<SubagentStatus>,
- watch::Receiver<SubagentStatus>,
+ watch::Sender<DetachedSubagentStatus>,
+ watch::Receiver<DetachedSubagentStatus>,
) {
- watch::channel(SubagentStatus::Running)
+ watch::channel(DetachedSubagentStatus::Running)
}
/// Register a running async sub-agent so it can be steered and waited on.
@@ -125,7 +105,7 @@ pub(crate) fn register(
parent_thread_id: Option<String>,
run_queue: Arc<RunQueue<crate::agent::queued_turn::QueuedTurn>>,
abort: AbortHandle,
- status: watch::Receiver<SubagentStatus>,
+ status: watch::Receiver<DetachedSubagentStatus>,
) {
if let Some(thread_id) = parent_thread_id.as_deref() {
if crate::agent::orchestration::background_completions::mark_stopped_task_if_thread_stopped(
@@ -155,7 +135,11 @@ pub(crate) fn register(
&workspace_dir,
parent_thread_id.as_deref(),
);
- spawn_status_watcher(task_id.clone(), workspace_dir.clone(), status.clone());
+ spawn_status_watcher(
+ task_store_for_workspace(&workspace_dir),
+ task_id.clone(),
+ status.clone(),
+ );
let metadata = RunningSubagentMetadata {
agent_id,
@@ -185,32 +169,3 @@ pub(crate) fn register(
.expect("detached task registry lock poisoned")
);
}
-
-/// Watch a child's status channel and mirror the first terminal status into the
-/// typed lifecycle store. A dropped sender (aborted/panicked task) without a
-/// terminal status is recorded as a failure, matching [`super::wait::wait`].
-fn spawn_status_watcher(
- task_id: String,
- workspace_dir: PathBuf,
- mut status: watch::Receiver<SubagentStatus>,
-) {
- tokio::spawn(async move {
- loop {
- let snapshot = status.borrow_and_update().clone();
- if snapshot.is_terminal() {
- super::task_ledger::record_status(&workspace_dir, &task_id, &snapshot);
- break;
- }
- if status.changed().await.is_err() {
- super::task_ledger::record_status(
- &workspace_dir,
- &task_id,
- &SubagentStatus::Failed {
- error: "sub-agent task ended without reporting a result".to_string(),
- },
- );
- break;
- }
- }
- });
-}
diff --git a/crates/openhuman-core/src/agent/orchestration/running_subagents/resolve.rs b/crates/openhuman-core/src/agent/orchestration/running_subagents/resolve.rs
index 2f52bcbb15..3ca2fee342 100644
--- a/crates/openhuman-core/src/agent/orchestration/running_subagents/resolve.rs
+++ b/crates/openhuman-core/src/agent/orchestration/running_subagents/resolve.rs
@@ -5,16 +5,13 @@
use std::path::Path;
-use tinyagents_harness::ids::TaskId;
-
-use tinyagents_graph::orchestration::OrchestrationTaskRecord;
-
-use super::registry::{registry, SubagentResumeRef};
-use super::task_ledger::{
- list_task_records, record_agent_id, record_parent_session, record_subagent_session_id,
- task_record_for_task_in_workspace,
+use tinyagents_orchestration::subagent::{
+ resume_ref_for_task as live_resume_ref, resume_ref_from_record, task_id_for_session as live_task_id,
+ task_id_for_session_in_records, SubagentResumeRef, WaitError,
};
-use super::wait::WaitError;
+
+use super::registry::registry;
+use super::task_ledger::{list_task_records, task_record_for_task_in_workspace};
/// Resolve a durable `subagent_session_id` to the currently-running transient
/// `task_id`, enforcing parent-session ownership.
@@ -22,33 +19,7 @@ pub(crate) fn task_id_for_session(
subagent_session_id: &str,
parent_session: &str,
) -> Result<String, WaitError> {
- let mut saw_unowned = false;
- let mut owned_terminal: Option<String> = None;
- for snapshot in registry()
- .snapshots(None)
- .expect("detached task registry lock poisoned")
- .into_iter()
- .filter(|snapshot| {
- snapshot.metadata.subagent_session_id.as_deref() == Some(subagent_session_id)
- })
- {
- if snapshot.owner_id != parent_session {
- saw_unowned = true;
- continue;
- }
- let task_id = snapshot.task_id.as_str().to_string();
- if !snapshot.status.is_terminal() {
- return Ok(task_id);
- }
- owned_terminal.get_or_insert(task_id);
- }
- if let Some(task_id) = owned_terminal {
- return Ok(task_id);
- }
- if saw_unowned {
- return Err(WaitError::NotOwned);
- }
- Err(WaitError::Unknown)
+ live_task_id(registry(), subagent_session_id, parent_session)
}
pub(crate) fn task_id_for_session_in_workspace(
@@ -62,45 +33,25 @@ pub(crate) fn task_id_for_session_in_workspace(
Err(WaitError::Unknown) => {}
}
- let mut saw_unowned = false;
- let mut matches: Vec<OrchestrationTaskRecord> = list_task_records(workspace_dir)
- .into_iter()
- .filter(|record| record_subagent_session_id(record) == Some(subagent_session_id))
- .collect();
- matches.sort_by_key(|item| std::cmp::Reverse(item.updated_at));
-
- for record in matches {
- if record_parent_session(&record) != Some(parent_session) {
- saw_unowned = true;
- continue;
- }
- let task_id = record.spec.task_id.as_str().to_string();
- log::debug!(
- "[running_subagents] resolved session from task store subagent_session_id={} task_id={} workspace_dir={}",
- subagent_session_id,
- task_id,
- workspace_dir.display()
- );
- return Ok(task_id);
- }
- if saw_unowned {
- return Err(WaitError::NotOwned);
- }
- Err(WaitError::Unknown)
+ let task_id = task_id_for_session_in_records(
+ list_task_records(workspace_dir),
+ subagent_session_id,
+ parent_session,
+ )?;
+ log::debug!(
+ "[running_subagents] resolved session from task store subagent_session_id={} task_id={} workspace_dir={}",
+ subagent_session_id,
+ task_id,
+ workspace_dir.display()
+ );
+ Ok(task_id)
}
pub(crate) fn resume_ref_for_task(
task_id: &str,
parent_session: &str,
) -> Result<SubagentResumeRef, WaitError> {
- let snapshot = registry()
- .snapshot(&TaskId::new(task_id), parent_session)
- .map_err(super::wait::wait_error_from_registry)?;
- Ok(SubagentResumeRef {
- task_id: task_id.to_string(),
- agent_id: snapshot.metadata.agent_id,
- subagent_session_id: snapshot.metadata.subagent_session_id,
- })
+ live_resume_ref(registry(), task_id, parent_session)
}
pub(crate) fn resume_ref_for_task_in_workspace(
@@ -120,9 +71,5 @@ pub(crate) fn resume_ref_for_task_in_workspace(
task_id,
workspace_dir.display()
);
- Ok(SubagentResumeRef {
- task_id: task_id.to_string(),
- agent_id: record_agent_id(&record),
- subagent_session_id: record_subagent_session_id(&record).map(ToOwned::to_owned),
- })
+ Ok(resume_ref_from_record(task_id, &record))
}
diff --git a/crates/openhuman-core/src/agent/orchestration/running_subagents/roster.rs b/crates/openhuman-core/src/agent/orchestration/running_subagents/roster.rs
index 8d094a0356..90d61d4f50 100644
--- a/crates/openhuman-core/src/agent/orchestration/running_subagents/roster.rs
+++ b/crates/openhuman-core/src/agent/orchestration/running_subagents/roster.rs
@@ -1,56 +1,15 @@
-//! Read-only rosters over the sub-agent registry: a compact snapshot type for
-//! ambient prompt injection, and the durable+live merge used to render the
+//! Read-only rosters over the sub-agent registry: the durable+live merge used to render the
//! `[active_subagents]` context block.
-use super::registry::{registry, SubagentStatus};
-use crate::agent::orchestration::fleet_tools::FleetToolSet;
+use tinyagents_orchestration::subagent::{snapshot_for_owner, SubagentSnapshot};
-/// Compact, read-only view of one registered sub-agent, for ambient injection
-/// into a parent's turn context (see [`active_subagents_context_block`]).
-#[derive(Debug, Clone)]
-pub(crate) struct SubagentSnapshot {
- /// Worker *type* (e.g. `code_executor`). Not unique — two parallel workers
- /// share this; disambiguate on `subagent_session_id` / `task_id`.
- pub(crate) agent_id: String,
- /// Durable, stable per-worker reference the prompt steers/waits/closes by.
- pub(crate) subagent_session_id: Option<String>,
- /// Transient registry key.
- pub(crate) task_id: String,
- /// Stable status label: `running` / `awaiting_user` / `completed` / `failed`.
- pub(crate) status: &'static str,
-}
+use super::registry::registry;
+use crate::agent::orchestration::fleet_tools::FleetToolSet;
/// Snapshot the sub-agents registered under `parent_session`, with each status
-/// read live from its watch channel. Read-only: it takes the registry lock only
-/// long enough to clone out the small summaries, never blocks on a child, and
-/// never mutates the table. Ordered by `agent_id` then `task_id` so the rendered
-/// roster is stable across turns (the underlying map is unordered).
+/// read live from its watch channel (ordered by `agent_id` then `task_id`).
pub(crate) fn snapshot_for_parent(parent_session: &str) -> Vec<SubagentSnapshot> {
- let mut out: Vec<SubagentSnapshot> = registry()
- .snapshots(Some(parent_session))
- .expect("detached task registry lock poisoned")
- .into_iter()
- .map(|entry| {
- let status = match &entry.status {
- SubagentStatus::Running => "running",
- SubagentStatus::Completed { .. } => "completed",
- SubagentStatus::AwaitingUser { .. } => "awaiting_user",
- SubagentStatus::Failed { .. } => "failed",
- };
- SubagentSnapshot {
- agent_id: entry.metadata.agent_id,
- subagent_session_id: entry.metadata.subagent_session_id,
- task_id: entry.task_id.as_str().to_string(),
- status,
- }
- })
- .collect();
- out.sort_by(|a, b| {
- a.agent_id
- .cmp(&b.agent_id)
- .then_with(|| a.task_id.cmp(&b.task_id))
- });
- out
+ snapshot_for_owner(registry(), parent_session)
}
/// The follow-up guidance sentence, built from the tools the parent can see.
diff --git a/crates/openhuman-core/src/agent/orchestration/running_subagents/wait.rs b/crates/openhuman-core/src/agent/orchestration/running_subagents/wait.rs
index 83035b58d5..a8ef890be8 100644
--- a/crates/openhuman-core/src/agent/orchestration/running_subagents/wait.rs
+++ b/crates/openhuman-core/src/agent/orchestration/running_subagents/wait.rs
@@ -5,35 +5,12 @@
use std::path::Path;
use std::time::Duration;
-use tinyagents_graph::orchestration::{DetachedTaskRegistryError, DetachedTaskWaitOutcome};
-use tinyagents_harness::ids::TaskId;
+use tinyagents_orchestration::subagent::{
+ record_to_wait_outcome, task_status_label, wait_detached, WaitError, WaitOutcome,
+};
-use super::registry::{registry, SubagentStatus};
-use super::task_ledger::{record_to_status, task_record_for_task_in_workspace, task_status_label};
-
-/// Why a wait could not be set up.
-#[derive(Debug, PartialEq, Eq)]
-pub(crate) enum WaitError {
- Unknown,
- NotOwned,
-}
-
-pub(crate) fn wait_error_from_registry(error: DetachedTaskRegistryError) -> WaitError {
- match error {
- DetachedTaskRegistryError::NotOwned => WaitError::NotOwned,
- _ => WaitError::Unknown,
- }
-}
-
-/// Result of waiting on a sub-agent.
-#[derive(Debug)]
-pub(crate) enum WaitOutcome {
- /// The sub-agent reached a terminal status (entry pruned).
- Terminal(SubagentStatus),
- /// The timeout elapsed first; the entry is left intact so the parent can
- /// wait again. Carries the latest (non-terminal) status snapshot.
- TimedOut(SubagentStatus),
-}
+use super::registry::registry;
+use super::task_ledger::task_record_for_task_in_workspace;
/// Block until `task_id` reaches a terminal status or `timeout` elapses.
pub(crate) async fn wait(
@@ -41,19 +18,7 @@ pub(crate) async fn wait(
parent_session: &str,
timeout: Duration,
) -> Result<WaitOutcome, WaitError> {
- match registry()
- .wait(&TaskId::new(task_id), parent_session, timeout)
- .await
- {
- Ok(DetachedTaskWaitOutcome::Terminal(status)) => Ok(WaitOutcome::Terminal(status)),
- Ok(DetachedTaskWaitOutcome::TimedOut(status)) => Ok(WaitOutcome::TimedOut(status)),
- Err(DetachedTaskRegistryError::StatusChannelClosed) => {
- Ok(WaitOutcome::Terminal(SubagentStatus::Failed {
- error: "sub-agent task ended without reporting a result".to_string(),
- }))
- }
- Err(error) => Err(wait_error_from_registry(error)),
- }
+ wait_detached(registry(), task_id, parent_session, timeout).await
}
pub(crate) async fn wait_in_workspace(
@@ -75,5 +40,5 @@ pub(crate) async fn wait_in_workspace(
task_status_label(record.status),
workspace_dir.display()
);
- Ok(record_to_status(record))
+ Ok(record_to_wait_outcome(record))
}