Skip to content

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

refactor(running_subagents): drop the legacy detached-task registry

Steven Enamakel23f0812020ec
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 a2485f709a..ba9e7239bb 100644
--- a/crates/openhuman-core/src/agent/orchestration/running_subagents/cancel.rs
+++ b/crates/openhuman-core/src/agent/orchestration/running_subagents/cancel.rs
@@ -2,16 +2,11 @@
//! durable session id, by owning parent thread (thread deletion), or all at
//! once (a full thread purge).
-use std::collections::HashSet;
use std::path::{Path, PathBuf};
-use tinyagents_harness::ids::TaskId;
-
use tinyagents_orchestration::subagent::FinishedOutcome;
-use super::registry::{control_admits, registry};
use super::resolve::task_id_for_session_in_workspace;
-use super::task_ledger::record_cancelled;
/// Metadata captured when a sub-agent is cancelled, so the caller can surface
/// the cancellation back in the parent chat (record a "cancelled" completion
@@ -26,10 +21,7 @@ pub(crate) struct CancelledSubagent {
/// Admission generation captured for this child, if it originated in a
/// thread. Completion after a later stop/resume must retain this epoch.
pub(crate) parent_epoch: Option<u64>,
- /// How the run had already ended when the cancel arrived, if it had. A
- /// finished entry stays registered until `sweep_terminal`, so a late
- /// "Cancel" still finds it; the caller must not rewrite that outcome as a
- /// user cancellation, and reports it instead.
+ /// How the run had already ended when the cancel arrived, if it had.
pub(crate) already_finished: Option<FinishedOutcome>,
/// The selected durable driver row when a paused child needs host-side
/// terminal projection (its driver callback already returned on pause).
@@ -40,66 +32,17 @@ pub(crate) struct CancelledSubagent {
pub(crate) driver_managed: bool,
}
-/// 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).
-///
-/// User controls check the captured profile in SaaS. The desktop user retains
-/// authority over every sub-agent in their own core.
-pub(crate) fn cancel_by_task(
- ctx: &crate::core::runtime::DispatchCtx,
- task_id: &str,
-) -> Option<CancelledSubagent> {
- cancel_by_task_with_workspace_reason(ctx, task_id, None, None)
- .ok()
- .flatten()
-}
-
/// Cancel with an optional user-provided reason for the driver-owned
/// completion callback. Store failures are returned so the RPC does not report
-/// an unknown task when its durable selector could not be read.
+/// an unknown task when its durable selector could not be read. TinyAgents' job
+/// registry is the live authority; the former host detached-task table was
+/// never populated by production spawns.
pub(crate) fn cancel_by_task_with_workspace_reason(
ctx: &crate::core::runtime::DispatchCtx,
task_id: &str,
fallback_workspace: Option<&Path>,
reason: Option<&str>,
) -> Result<Option<CancelledSubagent>, String> {
- let id = TaskId::new(task_id);
- if let Ok(snapshot) = registry().snapshot_trusted(&id) {
- if !control_admits(ctx, &snapshot.metadata) {
- return Ok(None);
- }
- let Ok(cancelled) = registry().cancel(&id, &snapshot.owner_id) else {
- return Ok(None);
- };
- // `AwaitingUser` is paused, not finished: cancelling it is a real cancel.
- let already_finished = cancelled.status.finished_outcome();
- let metadata = cancelled.metadata;
- if already_finished.is_none() {
- record_cancelled(ctx, &metadata.workspace_dir, task_id);
- }
- log::debug!(
- "[running_subagents] cancel_by_task task_id={} agent_id={} parent_thread_id={:?} live_entries={}",
- task_id,
- metadata.agent_id,
- metadata.parent_thread_id,
- registry()
- .len()
- .expect("detached task registry lock poisoned")
- );
- return Ok(Some(CancelledSubagent {
- agent_id: metadata.agent_id,
- parent_session: metadata.parent_session,
- subagent_session_id: metadata.subagent_session_id,
- workspace_dir: metadata.workspace_dir,
- parent_thread_id: metadata.parent_thread_id,
- parent_epoch: metadata.parent_epoch,
- already_finished,
- driver_pause: None,
- driver_managed: false,
- }));
- }
-
let workspace_dir = match ctx.resolved() {
Some(context) => context.workspace_dir().ok(),
None if !crate::core::runtime::is_saas() => fallback_workspace.map(Path::to_path_buf),
@@ -148,7 +91,9 @@ pub(crate) fn cancel_by_session_in_workspace(
let task_id =
task_id_for_session_in_workspace(ctx, subagent_session_id, parent_session, workspace_dir)
.ok()?;
- cancel_by_task(ctx, &task_id)
+ cancel_by_task_with_workspace_reason(ctx, &task_id, Some(workspace_dir), None)
+ .ok()
+ .flatten()
}
/// Abort and drop every running sub-agent whose parent chat thread is
@@ -156,25 +101,10 @@ pub(crate) fn cancel_by_session_in_workspace(
/// keep running (and later try to deliver) against a thread that no longer
/// exists. Returns the number of sub-agents cancelled.
pub(crate) fn cancel_for_thread(ctx: &crate::core::runtime::DispatchCtx, thread_id: &str) -> usize {
- let own = caller_workspace(ctx);
- let cancelled = registry()
- .cancel_where(|metadata| {
- metadata.parent_thread_id.as_deref() == Some(thread_id) && own.admits(ctx, metadata)
- })
- .expect("detached task registry lock poisoned");
- for entry in &cancelled {
- record_cancelled(ctx, &entry.metadata.workspace_dir, entry.task_id.as_str());
- }
- let count = cancelled.len();
- log::debug!(
- "[running_subagents] cancel_for_thread thread_id={} cancelled={} live_entries={}",
- thread_id,
- count,
- registry()
- .len()
- .expect("detached task registry lock poisoned")
- );
- count
+ let _ = (ctx, thread_id);
+ // The production job-registry thread selector is added by the cancellation
+ // owner leaf; the legacy detached-task registry was always empty in hosts.
+ 0
}
/// Abort every running detached sub-agent spawned from chat thread
@@ -190,37 +120,7 @@ pub(crate) fn stop_for_thread(
ctx: &crate::core::runtime::DispatchCtx,
thread_id: &str,
) -> Vec<String> {
- let own = caller_workspace(ctx);
- let cancelled = registry()
- .cancel_where(|metadata| {
- metadata.parent_thread_id.as_deref() == Some(thread_id) && own.admits(ctx, metadata)
- })
- .expect("detached task registry lock poisoned");
- let mut task_ids = Vec::with_capacity(cancelled.len());
- for entry in cancelled {
- let task_id = entry.task_id.as_str().to_string();
- record_cancelled(ctx, &entry.metadata.workspace_dir, &task_id);
- if let Some(subagent_session_id) = entry.metadata.subagent_session_id.as_deref() {
- let store = crate::agent::orchestration::subagent_sessions::SubagentSessionStore::new(
- entry.metadata.workspace_dir.clone(),
- );
- if let Err(err) = crate::agent::orchestration::subagent_sessions::mark_failed(
- &store,
- subagent_session_id,
- &task_id,
- "cancelled by user".to_string(),
- ) {
- log::warn!(
- "[running_subagents] stop_for_thread mark_failed failed thread_id={} task_id={} subagent_session_id={} error={}",
- thread_id,
- task_id,
- subagent_session_id,
- err
- );
- }
- }
- task_ids.push(task_id);
- }
+ let mut task_ids = Vec::new();
if let Some(core_context) = ctx.resolved() {
if let Ok(workspace_dir) = core_context.workspace_dir() {
let jobs = crate::core::runtime::slot_for::<
@@ -242,14 +142,6 @@ pub(crate) fn stop_for_thread(
}
}
}
- log::info!(
- "[running_subagents] stop_for_thread thread_id={} cancelled={} live_entries={}",
- thread_id,
- task_ids.len(),
- registry()
- .len()
- .expect("detached task registry lock poisoned")
- );
task_ids
}
@@ -260,80 +152,10 @@ pub(crate) fn stop_for_thread(
/// that wins the cooperative-abort race. Headless sub-agents (no parent thread)
/// are still aborted but contribute no id.
pub(crate) fn cancel_all(ctx: &crate::core::runtime::DispatchCtx) -> Vec<String> {
- let own = caller_workspace(ctx);
- let cancelled = registry()
- .cancel_where(|metadata| own.admits(ctx, metadata))
- .expect("detached task registry lock poisoned");
- let count = cancelled.len();
- let mut thread_ids: Vec<String> = Vec::new();
- let mut seen: HashSet<String> = HashSet::new();
- for entry in cancelled {
- record_cancelled(ctx, &entry.metadata.workspace_dir, entry.task_id.as_str());
- if let Some(thread_id) = entry.metadata.parent_thread_id {
- if seen.insert(thread_id.clone()) {
- thread_ids.push(thread_id);
- }
- }
- }
- log::debug!(
- "[running_subagents] cancel_all cancelled={} distinct_threads={}",
- count,
- thread_ids.len()
- );
- thread_ids
-}
-
-/// Which registered sub-agents a thread-scoped cancel may reach.
-///
-/// Thread ids are only unique per user, and the registry is process-wide. On
-/// the desktop every child belongs to the one user, as before. In SaaS only
-/// children working in the caller's own (profile) workspace qualify, so one
-/// user's Stop, delete or purge never reaches another user's work; a caller
-/// with no scope reaches none.
-pub(crate) enum CallerWorkspace {
- All,
- Only(std::path::PathBuf),
- Nothing,
-}
-
-impl CallerWorkspace {
- pub(crate) fn admits(
- &self,
- ctx: &crate::core::runtime::DispatchCtx,
- metadata: &super::registry::RunningSubagentMetadata,
- ) -> bool {
- match self {
- Self::All => true,
- Self::Only(dir) => metadata.workspace_dir == *dir && control_admits(ctx, metadata),
- Self::Nothing => false,
- }
- }
-}
-
-pub(crate) fn caller_workspace(ctx: &crate::core::runtime::DispatchCtx) -> CallerWorkspace {
- caller_workspace_in(crate::core::runtime::is_saas(), ctx.resolved().as_deref())
-}
-
-/// [`caller_workspace`] as a function of the mode and the task's own scope.
-pub(crate) fn caller_workspace_in(
- saas: bool,
- scoped: Option<&crate::core::runtime::CoreContext>,
-) -> CallerWorkspace {
- if !saas {
- return CallerWorkspace::All;
- }
- match scoped.and_then(|ctx| ctx.workspace_dir().ok()) {
- Some(dir) => CallerWorkspace::Only(dir),
- None => {
- log::warn!("[running_subagents] cancel without a tenant scope in SaaS; reaching none");
- CallerWorkspace::Nothing
- }
- }
-}
-
-#[cfg(test)]
-pub(crate) fn prune(task_id: &str) {
- let _ = registry().cancel_trusted(&TaskId::new(task_id));
+ let _ = ctx;
+ // Known legacy limitation tracked by #216: full purge still does not
+ // enumerate upstream driver jobs. Keep this behavior explicit here.
+ Vec::new()
}
pub(crate) fn now_ms() -> u64 {
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 7f33ff7e0f..139cf15167 100644
--- a/crates/openhuman-core/src/agent/orchestration/running_subagents/registry.rs
+++ b/crates/openhuman-core/src/agent/orchestration/running_subagents/registry.rs
@@ -1,83 +1,26 @@
-//! The in-process registry of running async sub-agents: registration,
-//! per-task metadata, and the terminal/transient [`DetachedSubagentStatus`] each entry
-//! carries.
+//! Host admission checks for asynchronous sub-agent spawns.
//!
-//! Each running async sub-agent registers here (via [`register`]), keyed by
-//! its `task_id`, with:
-//! - an `Arc<RunQueue>` — the same steering channel the steering forwarder in
-//! `TurnSpec::run` drains mid-turn, so `steer_subagent` can
-//! inject a message when no crate-native steering handle is registered;
-//! - 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<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.
-//!
-//! TinyAgents owns the process-local watch/cancel/abort/steering mechanics.
-//! OpenHuman retains product metadata, durable task-store projection, and the
-//! legacy `RunQueue` steering fallback. Ownership is enforced by captured profile
-//! and parent session;
-//! terminal entries are pruned on `wait` and swept at the registry soft cap.
-
-use std::path::PathBuf;
-use std::sync::{Arc, OnceLock};
-
-use tokio::sync::watch;
-use tokio::task::AbortHandle;
+//! Live child jobs are owned by TinyAgents' `SubAgentJobRegistry`; OpenHuman
+//! keeps only the caller/workspace checks applied before it admits a spawn.
-use crate::agent::tinyagents::host::steering::shared_steering_registry;
-use tinyagents_harness::ids::TaskId;
-use tinyagents_harness::run_queue::RunQueue;
-use tinyagents_harness::CancellationToken;
-use tinyagents_tasks::DetachedTaskRegistry;
+use tinyagents_orchestration::subagent::WaitError;
-use super::resolve::scoped_task_store;
-use super::task_ledger::record_spawned_in_store;
-use tinyagents_orchestration::subagent::{
- spawn_status_watcher, DetachedSubagentStatus, SpawnedSubagent, SubagentIdentity, WaitError,
-};
-
-#[derive(Clone)]
-pub(crate) struct RunningSubagentMetadata {
- /// Original profile authority, independent of caller-chosen session IDs.
- pub(crate) profile: Option<String>,
- /// Public/durable session ID; the registry owner uses an encoded key.
- pub(crate) parent_session: String,
- pub(crate) agent_id: String,
- pub(crate) subagent_session_id: Option<String>,
- pub(crate) workspace_dir: PathBuf,
- /// Parent chat thread that spawned this sub-agent, captured at registration.
- /// `None` for a headless spawn with no originating thread. Used to abort the
- /// sub-agent when its parent thread is deleted (see [`super::cancel::cancel_for_thread`]).
- pub(crate) parent_thread_id: Option<String>,
- /// Parent lifecycle generation admitted when this child was registered.
- /// Its eventual cancellation record must not be attached to a later turn.
- pub(crate) parent_epoch: Option<u64>,
- pub(crate) run_queue: Arc<RunQueue<crate::agent::queued_turn::QueuedTurn>>,
+/// A refused detached spawn cannot be reported as accepted work.
+#[derive(Debug, thiserror::Error)]
+pub(crate) enum RegistrationError {
+ #[error("missing or mismatched tenant scope")]
+ Scope,
}
/// Resolve the caller's profile without falling back to the operator in SaaS.
-fn caller_profile(ctx: &crate::core::runtime::DispatchCtx) -> Result<Option<String>, WaitError> {
- let profile = ctx.tenant().map_err(|_| WaitError::NotOwned)?.profile;
+fn caller_profile(ctx: &crate::core::runtime::DispatchCtx) -> Result<Option<String>, ()> {
+ let profile = ctx.tenant().map_err(|_| ())?.profile;
if crate::core::runtime::is_saas() && profile.is_none() {
- return Err(WaitError::NotOwned);
+ return Err(());
}
Ok(profile)
}
-/// A refused detached spawn cannot be reported as accepted work.
-#[derive(Debug, thiserror::Error)]
-pub(crate) enum RegistrationError {
- #[error("missing or mismatched tenant scope")]
- Scope,
- #[error("detached task registration failed: {0}")]
- Registry(#[source] tinyagents_harness::error::TinyAgentsError),
- #[error("parent lifecycle admission failed: {0}")]
- ParentLifecycle(#[source] anyhow::Error),
-}
-
/// Check the actual caller before any reusable-session or worker-thread write.
pub(crate) fn admit_spawn(
ctx: &crate::core::runtime::DispatchCtx,
@@ -87,31 +30,6 @@ pub(crate) fn admit_spawn(
caller_profile(ctx).map_err(|_| RegistrationError::Scope)
}
-/// Host ownership adapter over TinyAgents' opaque owner string.
-pub(super) fn owner_key(
- ctx: &crate::core::runtime::DispatchCtx,
- parent_session: &str,
-) -> Result<String, WaitError> {
- let profile = caller_profile(ctx)?;
- Ok(crate::core::runtime::tenant::tenant_key(
- &crate::core::runtime::tenant::Tenant {
- profile,
- agent: None,
- },
- parent_session,
- ))
-}
-
-/// Public user controls may reach any of their profile's parents; desktop
-/// controls retain the process user's existing authority over all workers.
-pub(super) fn control_admits(
- ctx: &crate::core::runtime::DispatchCtx,
- metadata: &RunningSubagentMetadata,
-) -> bool {
- !crate::core::runtime::is_saas()
- || caller_profile(ctx).is_ok_and(|profile| profile == metadata.profile)
-}
-
/// Durable fallback paths must stay in the caller's captured workspace.
pub(super) fn admit_workspace(
ctx: &crate::core::runtime::DispatchCtx,
@@ -120,251 +38,14 @@ pub(super) fn admit_workspace(
if !crate::core::runtime::is_saas() {
return Ok(());
}
- caller_profile(ctx)?;
+ caller_profile(ctx).map_err(|_| WaitError::NotOwned)?;
let context = ctx.resolved().ok_or(WaitError::NotOwned)?;
- if context.workspace_dir().map_err(|_| WaitError::NotOwned)? != workspace {
+ if context
+ .workspace_dir()
+ .map_err(|_| WaitError::NotOwned)?
+ != workspace
+ {
return Err(WaitError::NotOwned);
}
Ok(())
}
-
-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;
-static REGISTRY: OnceLock<DetachedTaskRegistry<RunningSubagentMetadata, DetachedSubagentStatus>> =
- OnceLock::new();
-
-pub(crate) fn registry(
-) -> &'static DetachedTaskRegistry<RunningSubagentMetadata, DetachedSubagentStatus> {
- REGISTRY.get_or_init(|| {
- DetachedTaskRegistry::new(
- shared_steering_registry().clone(),
- REGISTRY_SOFT_CAP,
- DetachedSubagentStatus::is_terminal,
- )
- })
-}
-
-/// Create the status channel a spawner threads into [`register`].
-///
-/// The spawner moves the [`watch::Sender`] into its detached task and `send`s 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<DetachedSubagentStatus>,
- watch::Receiver<DetachedSubagentStatus>,
-) {
- watch::channel(DetachedSubagentStatus::Running)
-}
-
-/// Register a running async sub-agent so it can be steered and waited on.
-///
-/// Call this *after* `tokio::spawn` so the [`AbortHandle`] is available; the
-/// task owns the matching [`watch::Sender`] from [`status_channel`]. Once the
-/// table passes [`REGISTRY_SOFT_CAP`], registration sweeps already-terminal
-/// entries so it stays bounded even if a parent never calls `wait_subagent`.
-#[allow(clippy::too_many_arguments)]
-pub(crate) fn register(
- ctx: &crate::core::runtime::DispatchCtx,
- task_id: String,
- agent_id: String,
- parent_session: String,
- session_parent_prefix: Option<String>,
- subagent_session_id: Option<String>,
- workspace_dir: PathBuf,
- parent_thread_id: Option<String>,
- run_queue: Arc<RunQueue<crate::agent::queued_turn::QueuedTurn>>,
- abort: AbortHandle,
- status: watch::Receiver<DetachedSubagentStatus>,
-) -> Result<(), RegistrationError> {
- if let Err(error) = admit_spawn(ctx, &workspace_dir) {
- abort.abort();
- return Err(error);
- }
- let parent_epoch = match parent_thread_id.as_deref() {
- Some(thread_id) => {
- match crate::agent::orchestration::background_completions::CompletionTarget::new(
- ctx.clone(),
- workspace_dir.clone(),
- parent_session.clone(),
- Some(thread_id.to_owned()),
- ) {
- Ok(target) => target.parent_epoch(),
- Err(error) => {
- abort.abort();
- return Err(RegistrationError::ParentLifecycle(error));
- }
- }
- }
- None => None,
- };
- register_with_parent_epoch(
- ctx,
- task_id,
- agent_id,
- parent_session,
- session_parent_prefix,
- subagent_session_id,
- workspace_dir,
- parent_thread_id,
- parent_epoch,
- run_queue,
- abort,
- status,
- )
-}
-
-/// Test-only lower-level hook for exercising registration after a previously
-/// captured spawn generation has gone stale.
-pub(crate) fn register_with_parent_epoch(
- ctx: &crate::core::runtime::DispatchCtx,
- task_id: String,
- agent_id: String,
- parent_session: String,
- session_parent_prefix: Option<String>,
- subagent_session_id: Option<String>,
- workspace_dir: PathBuf,
- parent_thread_id: Option<String>,
- parent_epoch: Option<u64>,
- run_queue: Arc<RunQueue<crate::agent::queued_turn::QueuedTurn>>,
- abort: AbortHandle,
- status: watch::Receiver<DetachedSubagentStatus>,
-) -> Result<(), RegistrationError> {
- let profile = match admit_spawn(ctx, &workspace_dir) {
- Ok(profile) => profile,
- Err(error) => {
- abort.abort();
- log::warn!("[running_subagents] refusing registration without a SaaS profile");
- return Err(error);
- }
- };
- let task_store = scoped_task_store(ctx, &workspace_dir).map_err(|_| {
- abort.abort();
- RegistrationError::Scope
- })?;
- let owner = crate::core::runtime::tenant::tenant_key(
- &crate::core::runtime::tenant::Tenant {
- profile: profile.clone(),
- agent: None,
- },
- &parent_session,
- );
- if let Some(thread_id) = parent_thread_id.as_deref() {
- if crate::agent::orchestration::background_completions::mark_stopped_task_if_thread_stopped(
- ctx,
- &workspace_dir,
- thread_id,
- &task_id,
- ) {
- // Stop landed after the child was spawned but before this registry
- // entry existed. The completion is tombstoned above; abort promptly
- // so the detached work does not keep consuming resources either.
- abort.abort();
- log::debug!(
- "[running_subagents] aborted late registration task_id={} thread_id={}",
- task_id,
- thread_id
- );
- return Err(RegistrationError::ParentLifecycle(anyhow::anyhow!(
- "parent thread is stopped or deleted"
- )));
- }
- // First spawn in a workspace this process has not scanned: redeliver any
- // completions a previous process finished there but never delivered.
- crate::agent::orchestration::background_delivery::recover_on_boot(ctx, &workspace_dir);
- }
-
- if let Some(thread_id) = parent_thread_id.as_deref() {
- let Some(parent_epoch) = parent_epoch else {
- abort.abort();
- return Err(RegistrationError::ParentLifecycle(anyhow::anyhow!(
- "parent admission generation was not captured at spawn"
- )));
- };
- let router = crate::agent::orchestration::background_completions::router_for_workspace_ctx(
- ctx,
- &workspace_dir,
- );
- match router.parent_generation_admitted(thread_id, parent_epoch) {
- Ok(true) => {}
- Ok(false) => {
- let _ = router.tombstone(&task_id);
- abort.abort();
- return Err(RegistrationError::ParentLifecycle(anyhow::anyhow!(
- "parent admission generation is no longer current"
- )));
- }
- Err(error) => {
- let _ = router.tombstone(&task_id);
- abort.abort();
- return Err(RegistrationError::ParentLifecycle(error.into()));
- }
- }
- } else if parent_epoch.is_some() {
- abort.abort();
- return Err(RegistrationError::ParentLifecycle(anyhow::anyhow!(
- "threadless child cannot carry a parent admission generation"
- )));
- }
-
- let metadata = RunningSubagentMetadata {
- profile,
- parent_session: parent_session.clone(),
- agent_id: agent_id.clone(),
- subagent_session_id: subagent_session_id.clone(),
- workspace_dir: workspace_dir.clone(),
- parent_thread_id: parent_thread_id.clone(),
- parent_epoch,
- run_queue,
- };
- registry()
- .register(
- TaskId::new(task_id.clone()),
- owner,
- metadata,
- status.clone(),
- // Cooperative cancellation is flipped before the registry invokes
- // the hard abort. The child executor can adopt this token without
- // changing the registry/control API.
- CancellationToken::new(),
- abort.clone(),
- )
- .map_err(|error| {
- abort.abort();
- RegistrationError::Registry(error)
- })?;
- // Failed admission must not leave a Running lifecycle record or watcher.
- let workspace = workspace_dir.display().to_string();
- record_spawned_in_store(
- task_store.as_ref(),
- &SpawnedSubagent {
- task_id: &task_id,
- agent_id: &agent_id,
- parent_session: &parent_session,
- session_parent_prefix: session_parent_prefix.as_deref(),
- subagent_session_id: subagent_session_id.as_deref(),
- workspace_dir: &workspace,
- parent_thread_id: parent_thread_id.as_deref(),
- },
- );
- spawn_status_watcher(task_store, task_id.clone(), status);
- log::debug!(
- "[running_subagents] registered task_id={} live_entries={}",
- task_id,
- registry()
- .len()
- .expect("detached task registry lock poisoned")
- );
- Ok(())
-}