Skip to content

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

chore: files changed crates/openhuman-core/src/agent/orchestration/ops.rs,crates/openhuman-core/src/

Steven Enamakelb8a1737ff6f9
diff --git a/crates/openhuman-core/src/agent/orchestration/ops.rs b/crates/openhuman-core/src/agent/orchestration/ops.rs
deleted file mode 100644
index ee36e59e89..0000000000
--- a/crates/openhuman-core/src/agent/orchestration/ops.rs
+++ /dev/null
@@ -1,643 +0,0 @@
-//! High-level orchestration control plane over TinyAgents' detached-task registry.
-//!
-//! This session used to own a second, bespoke process-local task table
-//! (`HashMap<String, AgentRecord>` + `HashMap<String, JoinHandle>` plus a
-//! `Notify` plus a hand-rolled terminal sweep). TinyAgents'
-//! [`DetachedTaskRegistry`] is a strict superset of that: it owns the status
-//! watch channels, cooperative cancellation tokens, hard-abort handles,
-//! owner-scoped lookup, the wait/timeout loop, and the soft-cap terminal sweep.
-//! `spawn_agent` / `wait_agents` / `abort_all` are now thin product wrappers
-//! over `register` / `wait` / `cancel_all`, following the shape
-//! [`running_subagents`](super::running_subagents) already established.
-//!
-//! What stays host-side is exactly the product layer: the
-//! [`DomainEvent::AgentOrchestrationSpawned`] /
-//! [`DomainEvent::AgentOrchestrationCompleted`] /
-//! [`DomainEvent::AgentOrchestrationFailed`] event-bus bridge, the parent
-//! [`AgentProgress`] fan-out, agent-definition resolution, and the
-//! [`AgentSnapshot`] response shape callers already consume.
-//!
-//! One behavioural consequence of the crate registry is worth knowing: `wait`
-//! **prunes** an entry once it observes a terminal status, so a child can be
-//! waited on once. Every caller in-tree spawns and waits exactly once, and this
-//! is the same contract `running_subagents` runs under.
-
-use super::types::{
- AgentSnapshot, SpawnAgentRequest, SpawnAgentResponse, WaitAgentOptions, WaitAgentResponse,
-};
-use crate::agent::harness::fork_context::ParentExecutionContext;
-use crate::agent::subagent_host::{
- run_subagent, SubagentRunError, SubagentRunOptions, SubagentRunOutcome, SubagentRunStatus,
-};
-use crate::agent::tinyagents::host::steering::shared_steering_registry;
-use crate::agent_registry::host_definition::{AgentDefinition, AgentDefinitionRegistry};
-use crate::core::bus::BUS;
-use crate::core::events::DomainEvent;
-use crate::progress::AgentProgress;
-use std::collections::BTreeMap;
-use std::sync::Arc;
-use thiserror::Error;
-use tinyagents_harness::ids::TaskId;
-use tinyagents_harness::CancellationToken;
-use tinyagents_tasks::{
- DetachedTaskRegistry, DetachedTaskRegistryError, DetachedTaskWaitOutcome,
- OrchestrationTaskStatus,
-};
-use tokio::sync::{mpsc, watch};
-use tokio::time::Duration;
-
-#[derive(Debug, Error)]
-pub enum OrchestrationError {
- #[error("agent orchestration requires an active parent agent turn")]
- NoParentContext,
- #[error("agent definition registry has not been initialized")]
- RegistryUnavailable,
- #[error("agent definition '{0}' not found")]
- DefinitionNotFound(String),
- #[error("orchestration agent '{0}' not found")]
- AgentNotFound(String),
- #[error("agent_id and prompt are required")]
- InvalidSpawnRequest,
- #[error("orchestration task registry unavailable: {0:?}")]
- Registry(DetachedTaskRegistryError),
-}
-
-/// Soft cap on live children per session. Terminal entries are only swept when
-/// the table grows past this, matching [`super::running_subagents`].
-const REGISTRY_SOFT_CAP: usize = 256;
-
-/// Product metadata retained alongside each detached child's executor handles.
-///
-/// `status_tx` rides in the metadata deliberately: it is what lets
-/// [`AgentOrchestrationSession::abort_all`] publish a terminal `Cancelled`
-/// status to an in-flight `wait_agents` before the crate hard-aborts the task.
-/// Without it, cancelling drops the sender and a concurrent waiter sees a closed
-/// channel instead of a cancellation.
-#[derive(Clone)]
-struct ChildMetadata {
- agent_id: String,
- parent_agent_id: Option<String>,
- prompt: String,
- created_at: String,
- metadata: BTreeMap<String, String>,
- status_tx: Arc<watch::Sender<ChildState>>,
-}
-
-/// Live status plus the terminal payload a snapshot reports.
-#[derive(Clone)]
-struct ChildState {
- status: OrchestrationTaskStatus,
- result_summary: Option<String>,
- error: Option<String>,
- updated_at: String,
-}
-
-impl ChildState {
- fn pending(updated_at: String) -> Self {
- Self {
- status: OrchestrationTaskStatus::Pending,
- result_summary: None,
- error: None,
- updated_at,
- }
- }
-
- fn is_terminal(&self) -> bool {
- self.status.is_terminal()
- }
-}
-
-type ChildRegistry = DetachedTaskRegistry<ChildMetadata, ChildState>;
-
-#[derive(Clone)]
-pub struct AgentOrchestrationSession {
- session_id: String,
- registry: Arc<ChildRegistry>,
-}
-
-impl AgentOrchestrationSession {
- /// Create an orchestration session backed by its own TinyAgents
- /// detached-task registry.
- ///
- /// The `session_id` identifies the parent orchestration run in emitted
- /// [`DomainEvent`] payloads and is the registry's owner id, so one session
- /// can never wait on or cancel another's children.
- pub fn new(session_id: impl Into<String>) -> Self {
- Self {
- session_id: session_id.into(),
- registry: Arc::new(DetachedTaskRegistry::new(
- shared_steering_registry().clone(),
- REGISTRY_SOFT_CAP,
- ChildState::is_terminal,
- )),
- }
- }
-
- /// Return the stable parent orchestration session id.
- pub fn session_id(&self) -> &str {
- &self.session_id
- }
-
- /// Spawn a child agent under `parent`, the explicit execution context of the
- /// agent turn (or controller-built root, see
- /// [`with_root_parent`](crate::agent::orchestration::parent_context::with_root_parent))
- /// that is starting it.
- ///
- /// `request` must provide a non-empty `agent_id` and `prompt`; optional
- /// context, model, parent id, and metadata are carried into the
- /// child record and sub-agent run options. On success this returns the
- /// accepted child id and initial status while a background task executes the
- /// child through [`run_subagent`].
- ///
- /// Returns [`OrchestrationError::InvalidSpawnRequest`] for an empty
- /// agent id or prompt, [`OrchestrationError::RegistryUnavailable`] when the
- /// agent definition registry is not initialized, or
- /// [`OrchestrationError::DefinitionNotFound`] for an unknown agent id. Side
- /// effects include registering the child in the detached-task registry,
- /// publishing a [`DomainEvent::AgentOrchestrationSpawned`] event, and
- /// emitting parent progress when available.
- pub async fn spawn_agent(
- &self,
- parent: ParentExecutionContext,
- request: SpawnAgentRequest,
- ) -> Result<SpawnAgentResponse, OrchestrationError> {
- let definition = resolve_definition(&request)?;
- self.spawn_agent_with_definition(parent, definition, request)
- .await
- }
-
- /// Wait for one or more child agents to reach terminal status.
- ///
- /// `options.orchestration_ids` names the children to observe. An empty id
- /// list returns the current full session snapshot immediately. When
- /// `timeout_ms` is present, the wait returns a partial response with
- /// `completed = false` after the timeout instead of failing; the deadline
- /// covers the whole id list, not each child in turn.
- ///
- /// Returns [`OrchestrationError::AgentNotFound`] if any requested child id
- /// is unknown to this session's registry.
- pub async fn wait_agents(
- &self,
- options: WaitAgentOptions,
- ) -> Result<WaitAgentResponse, OrchestrationError> {
- if options.orchestration_ids.is_empty() {
- return Ok(WaitAgentResponse {
- completed: true,
- agents: self.all_snapshots()?,
- });
- }
-
- let timeout = options.timeout_ms.map(Duration::from_millis);
- let task_ids: Vec<_> = options
- .orchestration_ids
- .iter()
- .cloned()
- .map(TaskId::new)
- .collect();
- let items = self
- .registry
- .wait_many(&task_ids, &self.session_id, timeout)
- .await
- .map_err(|failure| self.lookup_error(failure.task_id.as_str(), failure.error))?;
- let mut agents = Vec::with_capacity(options.orchestration_ids.len());
- let mut completed = true;
-
- for item in items {
- let state = match item.outcome {
- DetachedTaskWaitOutcome::Terminal(state)
- | DetachedTaskWaitOutcome::TimedOut(state) => state,
- };
- if !state.is_terminal() {
- completed = false;
- }
- agents.push(snapshot_of(item.task_id.as_str(), &item.metadata, &state));
- }
-
- Ok(WaitAgentResponse { completed, agents })
- }
-
- /// Abort every in-flight child and mark non-terminal children
- /// [`OrchestrationTaskStatus::Cancelled`].
- ///
- /// Used by the workflow engine on stop/interrupt to drain a session's
- /// running children. Idempotent — the crate registry cancels the
- /// cooperative token and the hard abort handle, and the `Cancelled` status
- /// is published on each child's watch channel first so a concurrent
- /// `wait_agents` resolves with a cancellation rather than a closed channel.
- pub async fn abort_all(&self) {
- let cancelled = match self.registry.cancel_all() {
- Ok(cancelled) => cancelled,
- Err(err) => {
- log::warn!("[agent_orchestration] abort_all could not drain registry: {err:?}");
- return;
- }
- };
- for entry in &cancelled {
- if entry.status.is_terminal() {
- continue;
- }
- let _ = entry.metadata.status_tx.send(ChildState {
- status: OrchestrationTaskStatus::Cancelled,
- result_summary: entry.status.result_summary.clone(),
- error: entry.status.error.clone(),
- updated_at: now(),
- });
- }
- log::debug!(
- "[agent_orchestration] abort_all session={} cancelled={}",
- self.session_id,
- cancelled.len()
- );
- }
-
- /// Every child snapshot still live in this session's registry, ordered by
- /// creation time.
- fn all_snapshots(&self) -> Result<Vec<AgentSnapshot>, OrchestrationError> {
- let mut agents: Vec<AgentSnapshot> = self
- .registry
- .snapshots(Some(&self.session_id))
- .map_err(OrchestrationError::Registry)?
- .into_iter()
- .map(|entry| snapshot_of(entry.task_id.as_str(), &entry.metadata, &entry.status))
- .collect();
- agents.sort_by(|a, b| a.created_at.cmp(&b.created_at));
- Ok(agents)
- }
-
- fn lookup_error(&self, id: &str, err: DetachedTaskRegistryError) -> OrchestrationError {
- match err {
- DetachedTaskRegistryError::Unknown | DetachedTaskRegistryError::NotOwned => {
- OrchestrationError::AgentNotFound(id.to_string())
- }
- other => OrchestrationError::Registry(other),
- }
- }
-
- async fn spawn_agent_with_definition(
- &self,
- parent: ParentExecutionContext,
- definition: AgentDefinition,
- request: SpawnAgentRequest,
- ) -> Result<SpawnAgentResponse, OrchestrationError> {
- let agent_id = request.agent_id.trim().to_string();
- let prompt = request.prompt.trim().to_string();
- if agent_id.is_empty() || prompt.is_empty() {
- return Err(OrchestrationError::InvalidSpawnRequest);
- }
-
- let orchestration_id = format!("agent-{}", uuid::Uuid::new_v4());
- let created_at = now();
- let (status_tx, status_rx) = watch::channel(ChildState::pending(created_at.clone()));
- let status_tx = Arc::new(status_tx);
- let metadata = ChildMetadata {
- agent_id: agent_id.clone(),
- parent_agent_id: request.parent_agent_id.clone(),
- prompt: prompt.clone(),
- created_at,
- metadata: request.metadata.clone(),
- status_tx: status_tx.clone(),
- };
-
- BUS.publish(DomainEvent::AgentOrchestrationSpawned {
- session_id: self.session_id.clone(),
- orchestration_id: orchestration_id.clone(),
- agent_id: agent_id.clone(),
- parent_agent_id: request.parent_agent_id,
- });
-
- let progress_sink = parent.on_progress.clone();
- if let Some(progress) = progress_sink.clone() {
- let resolved_display_name = AgentDefinitionRegistry::current()
- .and_then(|reg| reg.get(&agent_id).map(|def| def.display_name().to_string()));
- let _ = progress
- .send(AgentProgress::SubagentSpawned {
- agent_id: agent_id.clone(),
- task_id: orchestration_id.clone(),
- mode: "typed".to_string(),
- dedicated_thread: false,
- prompt_chars: prompt.chars().count(),
- prompt: prompt.clone(),
- worker_thread_id: None,
- display_name: resolved_display_name,
- parent_call_id: None,
- })
- .await;
- }
-
- let parent_workspace_descriptor = parent.workspace_descriptor.clone();
- let parent_worktree_action_dir = parent_workspace_descriptor
- .as_ref()
- .map(|descriptor| descriptor.root.clone());
- // This control-plane API crosses a `tokio::spawn` boundary, so retain
- // the live parent carrier before that boundary. The detached child must
- // share cancellation, origin, dispatch and progress with its caller;
- // only its route/usage observations are isolated by `child()` in the
- // subagent runner.
- let cancellation = CancellationToken::new();
- let mut run_context = crate::agent::tinyagents::host::OpenHumanRunContext::new()
- .with_host_env(&parent.host_env);
- run_context.parent = Some(parent.clone());
- run_context.progress = parent.on_progress.clone().or(run_context.progress);
- run_context.workspace = parent_workspace_descriptor
- .clone()
- .or(run_context.workspace);
- run_context.cancellation = cancellation.clone();
- if let Some(descriptor) = parent_workspace_descriptor.as_ref() {
- tracing::debug!(
- orchestration_id = %orchestration_id,
- agent_id = %agent_id,
- workspace_root = %descriptor.root.display(),
- policy_id = %descriptor.policy_id,
- "[agent_orchestration] inheriting parent workspace descriptor"
- );
- }
-
- let options = SubagentRunOptions {
- skill_filter_override: None,
- context: request.context,
- model_override: request.model,
- task_id: Some(orchestration_id.clone()),
- thread_id: None,
- run_context,
- worker_thread_id: None,
- initial_history: None,
- checkpoint_dir: None,
- worktree_action_dir: parent_worktree_action_dir,
- workspace_descriptor: parent_workspace_descriptor,
- // Not a dropped value: this is the harness's mid-run steering
- // channel, and this path has never offered live steering — the
- // orchestration control plane's `message_agent` recorded metadata
- // only, and it is gone. The child's *registry* entry does carry a
- // cooperative `CancellationToken` and an `AbortHandle` below, which
- // is what `abort_all` uses.
- run_queue: None,
- message_run_queue: None,
- };
-
- let session = self.clone();
- let task_id = orchestration_id.clone();
- let task_status_tx = status_tx.clone();
- let task_agent_id = agent_id.clone();
- // Captured on *this* task: a `tokio::task_local` does not cross
- // `tokio::spawn`, so the turn's origin label and workspace root are
- // carried across the same boundary the parent execution context
- // already is. Without the origin the spawned agent's external-effect
- // tools reach the approval gate unlabelled and are refused.
- let handle = tokio::spawn(crate::security::turn_origin::propagate(async move {
- mark_running(&task_status_tx);
- // The parent rides `options.run_context.parent`, built above.
- let result = run_subagent(&definition, &prompt, options).await;
- session
- .finish_agent(
- &task_id,
- &task_agent_id,
- &task_status_tx,
- progress_sink,
- result,
- )
- .await;
- }));
-
- self.registry
- .register(
- TaskId::new(orchestration_id.clone()),
- self.session_id.clone(),
- metadata,
- status_rx,
- cancellation,
- handle.abort_handle(),
- )
- .map_err(|err| {
- log::error!("[agent_orchestration] duplicate detached child id: {err}");
- // Registration failed, so the registry holds no record of this
- // task and `abort_all`/`cancel_all` can never reach it. Dropping
- // `handle` here would only detach the `JoinHandle` — the spawned
- // task keeps running orphaned. Abort it explicitly so a failed
- // spawn never leaves a live, unreachable child behind.
- handle.abort();
- OrchestrationError::InvalidSpawnRequest
- })?;
-
- log::debug!(
- "[agent_orchestration] spawned session={} orchestration_id={} agent_id={}",
- self.session_id,
- orchestration_id,
- agent_id
- );
-
- Ok(SpawnAgentResponse {
- orchestration_id,
- agent_id,
- status: OrchestrationTaskStatus::Pending,
- })
- }
-
- async fn finish_agent(
- &self,
- orchestration_id: &str,
- agent_id: &str,
- status_tx: &watch::Sender<ChildState>,
- progress_sink: Option<mpsc::Sender<AgentProgress>>,
- result: Result<SubagentRunOutcome, SubagentRunError>,
- ) {
- // A cancelled child has already reached a terminal status via
- // `abort_all`; do not overwrite it with a late completion.
- if status_tx.borrow().is_terminal() {
- return;
- }
-
- match result {
- Ok(outcome) => {
- let emit_lifecycle_effects = outcome.should_emit_lifecycle_effects();
- match outcome.status {
- SubagentRunStatus::Completed => {
- let _ = status_tx.send(ChildState {
- status: OrchestrationTaskStatus::Completed,
- result_summary: Some(outcome.output.clone()),
- error: None,
- updated_at: now(),
- });
- if !emit_lifecycle_effects {
- return;
- }
- BUS.publish(DomainEvent::AgentOrchestrationCompleted {
- session_id: self.session_id.clone(),
- orchestration_id: orchestration_id.to_string(),
- agent_id: outcome.agent_id.clone(),
- elapsed_ms: outcome.elapsed.as_millis() as u64,
- output_chars: outcome.output.chars().count(),
- iterations: outcome.iterations,
- });
- if let Some(progress) = progress_sink {
- let _ = progress
- .send(AgentProgress::SubagentCompleted {
- agent_id: outcome.agent_id.clone(),
- task_id: orchestration_id.to_string(),
- elapsed_ms: outcome.elapsed.as_millis() as u64,
- iterations: outcome.iterations as u32,
- output_chars: outcome.output.chars().count(),
- output: outcome.output.clone(),
- // Detached by construction: this spawn path
- // builds a fresh `OpenHumanRunContext::new()`
- // (see `spawn_agent`) and never sets
- // `parent_subagent_usage`, so the child's
- // spend is not in the parent turn's totals.
- usage: Some(outcome.usage),
- worktree_path: None,
- changed_files: Vec::new(),
- dirty_status: None,
- stop: None,
- })
- .await;
- }
- }
- SubagentRunStatus::AwaitingUser { question, .. } => {
- let _ = status_tx.send(ChildState {
- status: OrchestrationTaskStatus::Awaiting,
- result_summary: Some(question.clone()),
- error: None,
- updated_at: now(),
- });
- if emit_lifecycle_effects {
- if let Some(progress) = progress_sink {
- let _ = progress
- .send(AgentProgress::SubagentAwaitingUser {
- agent_id: outcome.agent_id,
- task_id: orchestration_id.to_string(),
- question,
- worker_thread_id: None,
- checkpoint_path: None,
- })
- .await;
- }
- }
- }
- SubagentRunStatus::Incomplete { reason } => {
- let message = format!("sub-agent stopped incomplete: {reason}");
- let _ = status_tx.send(ChildState {
- status: OrchestrationTaskStatus::Failed,
- result_summary: Some(outcome.output),
- error: Some(message.clone()),
- updated_at: now(),
- });
- if emit_lifecycle_effects {
- BUS.publish(DomainEvent::AgentOrchestrationFailed {
- session_id: self.session_id.clone(),
- orchestration_id: orchestration_id.to_string(),
- agent_id: outcome.agent_id.clone(),
- error: message.clone(),
- });
- if let Some(progress) = progress_sink {
- let _ = progress
- .send(AgentProgress::SubagentFailed {
- agent_id: outcome.agent_id,
- task_id: orchestration_id.to_string(),
- error: message,
- })
- .await;
- }
- }
- }
- SubagentRunStatus::Cancelled => {
- let message = "sub-agent was cancelled".to_string();
- let _ = status_tx.send(ChildState {
- status: OrchestrationTaskStatus::Cancelled,
- result_summary: None,
- error: Some(message.clone()),
- updated_at: now(),
- });
- if emit_lifecycle_effects {
- BUS.publish(DomainEvent::AgentOrchestrationClosed {
- session_id: self.session_id.clone(),
- orchestration_id: orchestration_id.to_string(),
- reason: Some(message.clone()),
- });
- if let Some(progress) = progress_sink {
- let _ = progress
- .send(AgentProgress::SubagentFailed {
- agent_id: outcome.agent_id,
- task_id: orchestration_id.to_string(),
- error: message,
- })
- .await;
- }
- }
- }
- }
- }
- Err(error) => {
- let message = error.to_string();
- let _ = status_tx.send(ChildState {
- status: OrchestrationTaskStatus::Failed,
- result_summary: None,
- error: Some(message.clone()),
- updated_at: now(),
- });
- BUS.publish(DomainEvent::AgentOrchestrationFailed {
- session_id: self.session_id.clone(),
- orchestration_id: orchestration_id.to_string(),
- agent_id: agent_id.to_string(),
- error: message.clone(),
- });
- if let Some(progress) = progress_sink {
- let _ = progress
- .send(AgentProgress::SubagentFailed {
- agent_id: agent_id.to_string(),
- task_id: orchestration_id.to_string(),
- error: message,
- })
- .await;
- }
- }
- }
- }
-}
-
-/// Publish `Running` unless the child already reached a terminal status.
-fn mark_running(status_tx: &watch::Sender<ChildState>) {
- let updated_at = now();
- status_tx.send_if_modified(|state| {
- if state.is_terminal() || state.status == OrchestrationTaskStatus::Running {
- return false;
- }
- state.status = OrchestrationTaskStatus::Running;
- state.updated_at = updated_at;
- true
- });
-}
-
-fn snapshot_of(
- orchestration_id: &str,
- metadata: &ChildMetadata,
- state: &ChildState,
-) -> AgentSnapshot {
- AgentSnapshot {
- orchestration_id: orchestration_id.to_string(),
- agent_id: metadata.agent_id.clone(),
- parent_agent_id: metadata.parent_agent_id.clone(),
- status: state.status,
- prompt: metadata.prompt.clone(),
- result_summary: state.result_summary.clone(),
- error: state.error.clone(),
- created_at: metadata.created_at.clone(),
- updated_at: state.updated_at.clone(),
- metadata: metadata.metadata.clone(),
- }
-}
-
-fn resolve_definition(request: &SpawnAgentRequest) -> Result<AgentDefinition, OrchestrationError> {
- let agent_id = request.agent_id.trim();
- if agent_id.is_empty() || request.prompt.trim().is_empty() {
- return Err(OrchestrationError::InvalidSpawnRequest);
- }
- let registry =
- AgentDefinitionRegistry::current().ok_or(OrchestrationError::RegistryUnavailable)?;
- registry
- .get(agent_id)
- .cloned()
- .ok_or_else(|| OrchestrationError::DefinitionNotFound(agent_id.to_string()))
-}
-
-fn now() -> String {
- chrono::Utc::now().to_rfc3339()
-}
diff --git a/crates/openhuman-core/src/agent/orchestration/ops_tests.rs b/crates/openhuman-core/src/agent/orchestration/ops_tests.rs
deleted file mode 100644
index aa437055ce..0000000000
--- a/crates/openhuman-core/src/agent/orchestration/ops_tests.rs
+++ /dev/null
@@ -1,509 +0,0 @@
-use super::*;
-use crate::agent::harness::fork_context::ParentExecutionContext;
-use crate::agent_registry::host_definition::AgentDefinitionRegistry;
-use crate::config::AgentConfig;
-use async_trait::async_trait;
-use parking_lot::Mutex;
-use std::future::Future;
-use std::sync::{
- atomic::{AtomicUsize, Ordering},
- Arc,
-};
-use tinyagents_tasks::OrchestrationTaskStatus;
-use tinyinference_llm::model::{ChatModel, ModelProfile, ModelRequest, ModelResponse};
-use tinytools::Tool;
-use tinytools_agent::dialect::ToolCallFormat;
-use tokio::time::Duration;
-
-fn parent_context(model: Arc<dyn ChatModel<()>>) -> ParentExecutionContext {
- ParentExecutionContext {
- workspace_descriptor: None,
- agent_definition_id: "orchestrator".to_string(),
- allowed_subagent_ids: ["task_manager_agent".to_string()].into_iter().collect(),
- turn_model_source: crate::agent::tinyagents::TurnModelSource::from_model_with_profile(
- model,
- ModelProfile {
- tool_calling: true,
- parallel_tool_calls: true,
- ..ModelProfile::default()
- },
- ),
- all_tools: Arc::new(Vec::<Box<dyn Tool>>::new()),
- all_tool_specs: Arc::new(Vec::new()),
- visible_tool_specs: Arc::new(Vec::new()),
- visible_tool_names: std::collections::HashSet::new(),
- subagent_tool_ceiling_names: std::collections::HashSet::new(),
- model_name: "test-model".to_string(),
- temperature: 0.2,
- workspace_dir: std::env::temp_dir(),
- agent_config: AgentConfig::default(),
- workflows: Arc::new(Vec::new()),
- memory_context: Arc::new(None),
- session_id: "orchestrator-session".to_string(),
- channel: "test".to_string(),
- connected_integrations: Vec::new(),
- tool_call_format: ToolCallFormat::PFormat,
- session_key: "0_orchestrator".to_string(),
- session_parent_prefix: None,
- on_progress: None,
- run_queue: None,
- host_env: Default::default(),
- }
-}
-
-fn text_response(text: impl Into<String>) -> ModelResponse {
- ModelResponse::assistant(text)
-}
-
-#[derive(Default)]
-struct ConversationState {
- prompts: Mutex<Vec<String>>,
-}
-
-#[derive(Clone, Default)]
-struct CodingQuestionModel {
- state: Arc<ConversationState>,
-}
-
-impl CodingQuestionModel {
- fn prompts(&self) -> Vec<String> {
- self.state.prompts.lock().clone()
- }
-}
-
-#[async_trait]
-impl ChatModel<()> for CodingQuestionModel {
- async fn invoke(
- &self,
- _state: &(),
- request: ModelRequest,
- ) -> tinyinference_llm::Result<ModelResponse> {
- let flattened = request
- .messages
- .iter()
- .map(|message| message.text())
- .collect::<Vec<_>>()
- .join("\n");
- self.state.prompts.lock().push(flattened.clone());
-
- if flattened.contains("ORCH_ANSWER_USE_RPC") {
- return Ok(text_response(
- "CODE_AGENT_DONE: implemented controller-registry route after orchestrator answer",
- ));
- }
-
- Ok(text_response(
- "CODE_AGENT_QUESTION: should this use controller registry or direct jsonrpc branch?",
- ))
- }
-}
-
-/// Number of parallel sub-agents the parallel-coding test spawns. The model's
-/// synchronization barrier is sized to this so the peak-concurrency assertion is
-/// deterministic regardless of scheduler/load.
-const PARALLEL_CHILDREN: usize = 3;
-
-struct ParallelState {
- calls: AtomicUsize,
- active: AtomicUsize,
- max_active: AtomicUsize,
- prompts: Mutex<Vec<String>>,
- /// Rendezvous point: every child parks here (yielding its worker thread)
- /// until all `PARALLEL_CHILDREN` are concurrently inside `chat`, so
- /// `max_active` deterministically reaches the peak instead of depending on
- /// whether the brief model calls happen to overlap in wall-clock time.
- gate: tokio::sync::Barrier,
-}
-
-impl Default for ParallelState {
- fn default() -> Self {
- Self {
- calls: AtomicUsize::new(0),
- active: AtomicUsize::new(0),
- max_active: AtomicUsize::new(0),
- prompts: Mutex::new(Vec::new()),
- gate: tokio::sync::Barrier::new(PARALLEL_CHILDREN),
- }
- }
-}
-
-#[derive(Clone, Default)]
-struct ParallelCodingModel {
- state: Arc<ParallelState>,
-}
-
-impl ParallelCodingModel {
- fn calls(&self) -> usize {
- self.state.calls.load(Ordering::SeqCst)
- }
-
- fn max_active(&self) -> usize {
- self.state.max_active.load(Ordering::SeqCst)
- }
-
- fn prompts(&self) -> Vec<String> {
- self.state.prompts.lock().clone()
- }
-
- fn record_peak(&self, current: usize) {
- let mut observed = self.state.max_active.load(Ordering::SeqCst);
- while current > observed {
- match self.state.max_active.compare_exchange(
- observed,
- current,
- Ordering::SeqCst,
- Ordering::SeqCst,
- ) {
- Ok(_) => break,
- Err(next) => observed = next,
- }
- }
- }
-}
-
-#[async_trait]
-impl ChatModel<()> for ParallelCodingModel {
- async fn invoke(
- &self,
- _state: &(),
- request: ModelRequest,
- ) -> tinyinference_llm::Result<ModelResponse> {
- self.state.calls.fetch_add(1, Ordering::SeqCst);
- let current = self.state.active.fetch_add(1, Ordering::SeqCst) + 1;
- self.record_peak(current);
- // Park until all children have entered `chat` (or a generous timeout, so
- // an unexpected missing child fails the assertion fast rather than
- // hanging). Once released, every child was concurrently active, so the
- // recorded peak equals `PARALLEL_CHILDREN`.
- let _ = tokio::time::timeout(Duration::from_secs(10), self.state.gate.wait()).await;
-
- let flattened = request
- .messages
- .iter()
- .map(|message| message.text())
- .collect::<Vec<_>>()
- .join("\n");
- self.state.prompts.lock().push(flattened.clone());
- self.state.active.fetch_sub(1, Ordering::SeqCst);
-
- if flattened.contains("PARALLEL_ALPHA") {
- Ok(text_response("ALPHA_DONE"))
- } else if flattened.contains("PARALLEL_BETA") {
- Ok(text_response("BETA_DONE"))
- } else if flattened.contains("PARALLEL_GAMMA") {
- Ok(text_response("GAMMA_DONE"))
- } else {
- Ok(text_response("UNKNOWN_DONE"))
- }
- }
-}
-
-#[test]
-fn unit_status_serializes_as_snake_case() {
- let value = serde_json::to_value(OrchestrationTaskStatus::Completed).expect("serialize status");
- assert_eq!(value, serde_json::json!("completed"));
-}
-
-#[tokio::test]
-async fn e2e_orchestrator_answers_coding_agent_question_and_resumes_child() {
- AgentDefinitionRegistry::init_global_builtins().unwrap();
- let provider = CodingQuestionModel::default();
- let parent = parent_context(Arc::new(provider.clone()));
- let session = AgentOrchestrationSession::new("orchestrator-session");
-
- let first = (async {
- session
- .spawn_agent(
- parent.clone(),
- SpawnAgentRequest {
- agent_id: "task_manager_agent".to_string(),
- prompt: "Implement RPC wiring for AGENT_ORCH_E2E".to_string(),
- model: Some("test-model".to_string()),
- ..Default::default()
- },
- )
- .await
- })
- .await
- .expect("spawn coding agent");
-
- // These waits spawn a *real* builtin (`task_manager_agent`) sub-agent on the
- // detached executor, which builds the full agent (prompt assembly, tool
- // resolution, registry) before the mock model returns — ~2.7s per child.
- // The wait budget must clear that with CI headroom; a tight 2s expires first
- // and reports the child as `Running`.
- let first_wait = session
- .wait_agents(WaitAgentOptions {
- orchestration_ids: vec![first.orchestration_id.clone()],
- timeout_ms: Some(15_000),
- })
- .await
- .expect("wait first child");
- let first_child = &first_wait.agents[0];
- assert_eq!(first_child.status, OrchestrationTaskStatus::Completed);
- assert!(first_child
- .result_summary
- .as_deref()
- .unwrap_or_default()
- .contains("CODE_AGENT_QUESTION"));
-
- // `message_agent`/`follow_up` are gone (superseded by the durable verbs in
- // `command_center::control`). The orchestrator now records its answer by
- // spawning the linked continuation child directly — the same thing
- // `follow_up` did internally.
- let follow_up = (async {
- session
- .spawn_agent(
- parent.clone(),
- SpawnAgentRequest {
- agent_id: "task_manager_agent".to_string(),
- prompt: "Continue after the orchestrator answered: ORCH_ANSWER_USE_RPC"
- .to_string(),
- context: Some("Parent answered: use controller registry".to_string()),
- model: Some("test-model".to_string()),
- parent_agent_id: Some(first.orchestration_id.clone()),
- ..Default::default()
- },
- )
- .await
- })
- .await
- .expect("spawn follow-up coding child");
-
- let final_wait = session
- .wait_agents(WaitAgentOptions {
- orchestration_ids: vec![follow_up.orchestration_id.clone()],
- timeout_ms: Some(15_000),
- })
- .await
- .expect("wait follow-up");
- let final_child = &final_wait.agents[0];
- assert_eq!(
- final_child.parent_agent_id.as_deref(),
- Some(first.orchestration_id.as_str())
- );
- assert_eq!(final_child.status, OrchestrationTaskStatus::Completed);
- assert!(final_child
- .result_summary
- .as_deref()
- .unwrap_or_default()
- .contains("CODE_AGENT_DONE"));
-
- let prompts = provider.prompts();
- assert_eq!(prompts.len(), 2);
- assert!(prompts[0].contains("AGENT_ORCH_E2E"));
- assert!(prompts[1].contains("ORCH_ANSWER_USE_RPC"));
-}
-
-// Multi-thread runtime: this test asserts the three detached sub-agents run
-// *concurrently* (`max_active >= 2`). Each child does a CPU-bound builtin-agent
-// build before its (mock) model call; on a single-threaded runtime those
-// builds serialize, so the brief model calls never overlap and the peak-
-// concurrency assertion flakes under load. Real worker threads let the builds —
-// and therefore the model calls — actually overlap.
-#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
-async fn e2e_orchestrator_waits_for_multiple_parallel_coding_subagents() {
- AgentDefinitionRegistry::init_global_builtins().unwrap();
- let provider = ParallelCodingModel::default();
- let parent = parent_context(Arc::new(provider.clone()));
- let session = AgentOrchestrationSession::new("parallel-orchestrator-session");
-
- let spawned = (async {
- let alpha = session
- .spawn_agent(
- parent.clone(),
- SpawnAgentRequest {
- agent_id: "task_manager_agent".to_string(),
- prompt: "Work independently on PARALLEL_ALPHA".to_string(),
- model: Some("test-model".to_string()),
- ..Default::default()
- },
- )
- .await?;
- let beta = session
- .spawn_agent(
- parent.clone(),
- SpawnAgentRequest {
- agent_id: "task_manager_agent".to_string(),
- prompt: "Work independently on PARALLEL_BETA".to_string(),
- model: Some("test-model".to_string()),
- ..Default::default()
- },
- )
- .await?;
- let gamma = session
- .spawn_agent(
- parent.clone(),
- SpawnAgentRequest {
- agent_id: "task_manager_agent".to_string(),
- prompt: "Work independently on PARALLEL_GAMMA".to_string(),
- model: Some("test-model".to_string()),
- ..Default::default()
- },
- )
- .await?;
- Ok::<_, OrchestrationError>(vec![
- alpha.orchestration_id,
- beta.orchestration_id,
- gamma.orchestration_id,
- ])
- })
- .await
- .expect("spawn parallel coding agents");
-
- let waited = session
- .wait_agents(WaitAgentOptions {
- orchestration_ids: spawned,
- timeout_ms: Some(15_000),
- })
- .await
- .expect("wait parallel children");
-
- assert!(waited.completed);
- assert_eq!(waited.agents.len(), 3);
- assert!(waited
- .agents
- .iter()
- .all(|agent| agent.status == OrchestrationTaskStatus::Completed));
- let outputs = waited
- .agents
- .iter()
- .filter_map(|agent| agent.result_summary.as_deref())
- .collect::<Vec<_>>()
- .join("\n");
- assert!(outputs.contains("ALPHA_DONE"));
- assert!(outputs.contains("BETA_DONE"));
- assert!(outputs.contains("GAMMA_DONE"));
- assert_eq!(provider.calls(), 3);
- assert!(
- provider.max_active() >= 2,
- "expected overlapping subagent calls, max_active={}",
- provider.max_active()
- );
- let prompts = provider.prompts().join("\n");
- assert!(prompts.contains("PARALLEL_ALPHA"));
- assert!(prompts.contains("PARALLEL_BETA"));
- assert!(prompts.contains("PARALLEL_GAMMA"));
-}
-
-/// A model that parks long enough for `abort_all` to land while the child is
-/// still running.
-#[derive(Clone, Default)]
-struct BlockingModel;
-
-#[async_trait]
-impl ChatModel<()> for BlockingModel {
- async fn invoke(
- &self,
- _state: &(),
- _request: ModelRequest,
- ) -> tinyinference_llm::Result<ModelResponse> {
- tokio::time::sleep(Duration::from_secs(60)).await;
- Ok(text_response("NEVER_REACHED"))
- }
-}
-
-#[tokio::test]
-async fn unit_wait_agents_with_no_ids_returns_an_empty_complete_response() {
- let session = AgentOrchestrationSession::new("empty-session");
- let response = session
- .wait_agents(WaitAgentOptions::default())
- .await
- .expect("empty wait succeeds");
-
- assert!(response.completed);
- assert!(response.agents.is_empty());
-}
-
-#[tokio::test]
-async fn unit_wait_agents_rejects_an_unknown_child() {
- let session = AgentOrchestrationSession::new("unknown-session");
- let error = session
- .wait_agents(WaitAgentOptions {
- orchestration_ids: vec!["agent-does-not-exist".to_string()],
- timeout_ms: Some(50),
- })
- .await
- .unwrap_err();
-
- assert!(
- matches!(&error, OrchestrationError::AgentNotFound(id) if id == "agent-does-not-exist"),
- "unexpected error: {error:?}"
- );
-}
-
-/// `abort_all` must publish a terminal `Cancelled` status on each live child's
-/// watch channel *before* the crate registry hard-aborts it, so a waiter in
-/// flight resolves with a cancellation rather than a closed status channel.
-#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
-async fn e2e_abort_all_cancels_an_in_flight_child_for_a_concurrent_waiter() {
- AgentDefinitionRegistry::init_global_builtins().unwrap();
- let parent = parent_context(Arc::new(BlockingModel));
- let session = AgentOrchestrationSession::new("abort-session");
-
- let spawned = (async {
- session
- .spawn_agent(
- parent.clone(),
- SpawnAgentRequest {
- agent_id: "task_manager_agent".to_string(),
- prompt: "Park until the orchestrator interrupts".to_string(),
- model: Some("test-model".to_string()),
- ..Default::default()
- },
- )
- .await
- })
- .await
- .expect("spawn blocking child");
-
- let waiter_session = session.clone();
- let waiter_id = spawned.orchestration_id.clone();
- let mut waiter = Box::pin(async move {
- waiter_session
- .wait_agents(WaitAgentOptions {
- orchestration_ids: vec![waiter_id],
- timeout_ms: Some(30_000),
- })
- .await
- });
-
- // Observe Running before cancellation, then poll the waiter future once
- // until it suspends inside wait_agents. This ensures its registry snapshot
- // and watch subscription are established before abort_all removes the
- // entry; a task-level start signal alone leaves that lookup racy.
- let observed_running = tokio::time::timeout(Duration::from_secs(10), async {
- loop {
- let response = session
- .wait_agents(WaitAgentOptions {
- orchestration_ids: vec![spawned.orchestration_id.clone()],
- timeout_ms: Some(5),
- })
- .await
- .expect("poll for readiness succeeds while the child is still live");
- if response.agents[0].status == OrchestrationTaskStatus::Running {
- break;
- }
- tokio::task::yield_now().await;
- }
- })
- .await;
- assert!(
- observed_running.is_ok(),
- "child never reached Running before the readiness timeout"
- );
- futures::future::poll_fn(|cx| match waiter.as_mut().poll(cx) {
- std::task::Poll::Pending => std::task::Poll::Ready(()),
- std::task::Poll::Ready(_) => panic!("waiter completed before cancellation"),
- })
- .await;
- session.abort_all().await;
-
- let response = waiter.await.expect("wait resolves after abort_all");
- assert!(response.completed);
- assert_eq!(response.agents.len(), 1);
- assert_eq!(
- response.agents[0].status,
- OrchestrationTaskStatus::Cancelled
- );
-}
diff --git a/crates/openhuman-core/src/agent/orchestration/types.rs b/crates/openhuman-core/src/agent/orchestration/types.rs
deleted file mode 100644
index 169e27c882..0000000000
--- a/crates/openhuman-core/src/agent/orchestration/types.rs
+++ /dev/null
@@ -1,66 +0,0 @@
-//! Public data model for high-level agent orchestration.
-//!
-//! The status vocabulary is TinyAgents'
-//! [`OrchestrationTaskStatus`] — the host's own `AgentStatus` copy was retired
-//! once the control plane moved onto the crate's `DetachedTaskRegistry`. It
-//! never appeared on a JSON-RPC schema, and the detached sub-agent path was
-//! already reporting the crate enum, so the two vocabularies are now one.
-
-use serde::{Deserialize, Serialize};
-use std::collections::BTreeMap;
-
-use tinyagents_tasks::OrchestrationTaskStatus;
-
-/// Request to spawn a child agent from the current parent agent turn.
-#[derive(Debug, Clone, Default, Serialize, Deserialize)]
-pub struct SpawnAgentRequest {
- pub agent_id: String,
- pub prompt: String,
- #[serde(default)]
- pub context: Option<String>,
- #[serde(default)]
- pub model: Option<String>,
- #[serde(default)]
- pub parent_agent_id: Option<String>,
- #[serde(default)]
- pub metadata: BTreeMap<String, String>,
-}
-
-/// Result returned immediately after an agent is accepted for execution.
-#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
-pub struct SpawnAgentResponse {
- pub orchestration_id: String,
- pub agent_id: String,
- pub status: OrchestrationTaskStatus,
-}
-
-/// Wait request for one or more children.
-#[derive(Debug, Clone, Default, Serialize, Deserialize)]
-pub struct WaitAgentOptions {
- pub orchestration_ids: Vec<String>,
- #[serde(default)]
- pub timeout_ms: Option<u64>,
-}
-
-/// Wait response with the latest snapshots known to the orchestrator.
-#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
-pub struct WaitAgentResponse {
- pub completed: bool,
- pub agents: Vec<AgentSnapshot>,
-}
-
-/// Serializable child-agent state for UI, diagnostics, and future persistence.
-#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
-pub struct AgentSnapshot {
- pub orchestration_id: String,
- pub agent_id: String,
- pub parent_agent_id: Option<String>,
- pub status: OrchestrationTaskStatus,
- pub prompt: String,
- pub result_summary: Option<String>,
- pub error: Option<String>,
- pub created_at: String,
- pub updated_at: String,
- #[serde(default)]
- pub metadata: BTreeMap<String, String>,
-}
diff --git a/crates/openhuman-core/src/agent/orchestration/workflow_runs/engine/lifecycle.rs b/crates/openhuman-core/src/agent/orchestration/workflow_runs/engine/lifecycle.rs
deleted file mode 100644
index 2f560736fe..0000000000
--- a/crates/openhuman-core/src/agent/orchestration/workflow_runs/engine/lifecycle.rs
+++ /dev/null
@@ -1,452 +0,0 @@
-//! Public entry points (`start`/`stop`/`resume`) and the spawned engine loop
-//! that drives a run's phase DAG to completion.
-
-use crate::core::runtime::DispatchCtx;
-use anyhow::{anyhow, Context, Result};
-use serde_json::Value;
-use std::sync::{Arc, OnceLock};
-use tinyagents_orchestration::workflow::{
- reset_running_phases, WorkflowEngine, WorkflowRunHandle, WorkflowRunSupervisor,
-};
-
-use crate::agent::harness::ParentExecutionContext;
-use crate::agent::orchestration::parent_context::with_root_parent;
-use crate::config::Config;
-use tinyagents_session::run_ledger::{WorkflowRun, WorkflowRunStatus, WorkflowRunUpsert};
-
-use super::ops::{
- compare_and_swap_workflow_run_lifecycle, definition_by_id, get_workflow_run, workflow_store,
-};
-use super::LOG_TARGET;
-use tinyagents_orchestration::workflow::WorkflowDefinition;
-
-fn workflow_supervisor() -> &'static WorkflowRunSupervisor {
- static SUPERVISOR: OnceLock<WorkflowRunSupervisor> = OnceLock::new();
- SUPERVISOR.get_or_init(WorkflowRunSupervisor::default)
-}
-
-fn record_failed_if_current(
- config: &Config,
- run_id: &str,
- handle: &WorkflowRunHandle,
- expected_revision: u64,
- summary: String,
-) {
- let supervisor = workflow_supervisor();
- let _ = supervisor.with_current(handle, || {
- if let Ok(Some(run)) = get_workflow_run(config, run_id) {
- if matches!(
- run.status,
- WorkflowRunStatus::Completed
- | WorkflowRunStatus::Failed
- | WorkflowRunStatus::Cancelled
- | WorkflowRunStatus::Interrupted
- ) || run.revision != expected_revision
- {
- return;
- }
- let _ = compare_and_swap_workflow_run_lifecycle(
- config,
- WorkflowRunUpsert {
- id: run.id.clone(),
- definition_id: run.definition_id.clone(),
- parent_thread_id: run.parent_thread_id.clone(),
- input: run.input.clone(),
- phase_states: run.phase_states.clone(),
- child_run_ids: run.child_run_ids.clone(),
- status: WorkflowRunStatus::Failed,
- summary: Some(summary),
- started_at: Some(run.started_at),
- completed_at: Some(chrono::Utc::now()),
- },
- expected_revision,
- );
- }
- });
-}
-
-/// Install the owner generation, then build OpenHuman's root context and
-/// origin around the scheduled drive. The host retains the callback handle
-/// only so failure projection can reject a stale generation.
-fn schedule_workflow_drive(
- ctx: &DispatchCtx,
- run_id: String,
- definition: WorkflowDefinition,
- resume: bool,
- commit: impl FnOnce() -> Result<WorkflowRun>,
-) -> Result<(WorkflowRunHandle, WorkflowRun)> {
- let supervisor = workflow_supervisor().clone();
- let task_ctx = ctx.clone();
- let handle_slot = Arc::new(OnceLock::<WorkflowRunHandle>::new());
- let config_slot = Arc::new(OnceLock::<Config>::new());
- let parent_slot = Arc::new(OnceLock::<ParentExecutionContext>::new());
- let admission_revision = Arc::new(OnceLock::<u64>::new());
- let drive_handle_slot = Arc::clone(&handle_slot);
- let drive_config_slot = Arc::clone(&config_slot);
- let drive_parent_slot = Arc::clone(&parent_slot);
- let drive_revision_slot = Arc::clone(&admission_revision);
- let drive_run_id = run_id.clone();
- let drive_definition = definition.clone();
- let root_ctx = task_ctx.clone();
- let root_config_slot = Arc::clone(&config_slot);
- let root_parent_slot = Arc::clone(&parent_slot);
- let root_handle_slot = Arc::clone(&handle_slot);
- let root_revision_slot = Arc::clone(&admission_revision);
- let root_run_id = run_id.clone();
- let root_parent = move |drive| {
- let task_ctx = root_ctx.clone();
- let config_slot = Arc::clone(&root_config_slot);
- let parent_slot = Arc::clone(&root_parent_slot);
- let handle_slot = Arc::clone(&root_handle_slot);
- let revision_slot = Arc::clone(&root_revision_slot);
- let run_id = root_run_id.clone();
- async move {
- match crate::config::ops::load_current_or_init(&task_ctx).await {
- Ok(task_config) => {
- let _ = config_slot.set(task_config.clone());
- if let Err(error) = with_root_parent(
- &task_ctx,
- None,
- &task_config,
- "workflow_engine",
- "workflow",
- "workflow",
- |parent| async move {
- let _ = parent_slot.set(parent);
- drive.await;
- },
- )
- .await
- {
- if let Some(handle) = handle_slot.get() {
- if let Some(revision) = revision_slot.get().copied() {
- record_failed_if_current(
- &task_config,
- &run_id,
- handle,
- revision,
- format!("root parent context failed: {error:#}"),
- );
- }
- }
- }
- }
- Err(error) => log::error!(
- target: LOG_TARGET,
- "[workflow_run_engine] drive.config_load_failed run={run_id} err={error}"
- ),
- }
- }
- };
- let inherited_origin = crate::security::turn_origin::capture();
- let origin =
- move |future| crate::security::turn_origin::with_inherited_origin(inherited_origin, future);
- let make_future = move |cancel_token| {
- let run_id = drive_run_id.clone();
- let definition = drive_definition.clone();
- let handle_slot = Arc::clone(&drive_handle_slot);
- let config_slot = Arc::clone(&drive_config_slot);
- let parent_slot = Arc::clone(&drive_parent_slot);
- let revision_slot = Arc::clone(&drive_revision_slot);
- async move {
- let (Some(handle), Some(config), Some(parent)) = (
- handle_slot.get().cloned(),
- config_slot.get().cloned(),
- parent_slot.get().cloned(),
- ) else {
- return;
- };
- let Some(admission_revision) = revision_slot.get().copied() else {
- log::error!(
- target: LOG_TARGET,
- "[workflow_run_engine] drive missing admission revision run={run_id}"
- );
- return;
- };
- run_engine_loop(
- &config,
- &run_id,
- definition,
- handle,
- admission_revision,
- cancel_token,
- Some(parent),
- )
- .await;
- }
- };
- let spawn_ctx = task_ctx;
- let spawn_handle_slot = Arc::clone(&handle_slot);
- let spawn = move |handle, future| {
- let _ = spawn_handle_slot.set(handle);
- spawn_ctx.spawn(future);
- };
-
- let revision_slot = Arc::clone(&admission_revision);
- let commit = move || -> Result<WorkflowRun> {
- let run = commit()?;
- let _ = revision_slot.set(run.revision);
- Ok(run)
- };
-
- if resume {
- supervisor.resume_scoped_with_commit(
- run_id,
- commit,
- make_future,
- root_parent,
- origin,
- spawn,
- )
- } else {
- supervisor.start_scoped_with_commit(run_id, commit, make_future, root_parent, origin, spawn)
- }
-}
-
-/// Start a new workflow run and return immediately.
-///
-/// Resolves `definition_id` to a builtin [`WorkflowDefinition`], creates a
-/// `Running` ledger row with `phase_states` initialised to one `pending` entry
-/// per phase, persists it, then `tokio::spawn`s the engine loop. The returned
-/// [`WorkflowRun`] is the freshly-created row (status `Running`); callers poll
-/// `workflow_run_get` to observe progress.
-pub async fn start_workflow_run(
- ctx: &DispatchCtx,
- config: &Config,
- definition_id: &str,
- input: Value,
- parent_thread_id: Option<String>,
-) -> Result<WorkflowRun> {
- log::debug!(
- target: LOG_TARGET,
- "[workflow_run_engine] start.entry definition={definition_id} parent_thread={parent_thread_id:?}"
- );
- let definition = definition_by_id(definition_id)
- .ok_or_else(|| anyhow!("unknown workflow definition: {definition_id}"))?;
- let safety_tier = super::host::admit_workflow(&definition)?;
-
- let run_id = format!("wfrun-{}", uuid::Uuid::new_v4());
- let initial_engine = WorkflowEngine::new(
- workflow_store(config)?,
- Arc::new(super::host::OpenHumanWorkflowExecutor::new(
- &run_id,
- None,
- safety_tier,
- None,
- )),
- );
- let initial_run_id = run_id.clone();
- let initial_definition = definition.clone();
- let (handle, run) =
- schedule_workflow_drive(ctx, run_id.clone(), definition, false, move || {
- initial_engine
- .initialise(initial_run_id, &initial_definition, input, parent_thread_id)
- .context("persist initial workflow run")
- })?;
- let _handle = handle;
-
- log::debug!(
- target: LOG_TARGET,
- "[workflow_run_engine] start.spawned run={run_id} phases={}",
- run.phase_states.as_object().map(|m| m.len()).unwrap_or(0)
- );
- Ok(run)
-}
-
-/// Signal a running workflow to stop after its current phase.
-///
-/// Flips the run's cancellation flag (checked by the loop between phases) and
-/// eagerly marks the persisted row `Interrupted` so a poller sees the intent
-/// immediately even while the in-flight phase drains. Idempotent: stopping a
-/// terminal or unknown run is a no-op that returns the current row.
-pub async fn stop_workflow_run(config: &Config, id: &str) -> Result<Option<WorkflowRun>> {
- log::debug!(target: LOG_TARGET, "[workflow_run_engine] stop.entry run={id}");
- let Some(run) = get_workflow_run(config, id)? else {
- log::debug!(target: LOG_TARGET, "[workflow_run_engine] stop.unknown run={id}");
- return Ok(None);
- };
-
- if matches!(
- run.status,
- WorkflowRunStatus::Completed | WorkflowRunStatus::Failed | WorkflowRunStatus::Cancelled
- ) {
- log::debug!(
- target: LOG_TARGET,
- "[workflow_run_engine] stop.already_terminal run={id} status={}",
- run.status.as_str()
- );
- return Ok(Some(run));
- }
-
- // Capture the exact live generation before fencing its durable row. If a
- // concurrent resume wins instead, this stop's CAS fails and it must not
- // cancel that successor's fresh token.
- let supervisor = workflow_supervisor();
- let handle = supervisor.current_handle(id);
-
- let mut phase_states = run.phase_states.clone();
- reset_running_phases(
- &mut phase_states,
- "workflow interrupted by host; phase will retry on resume",
- );
- let updated = compare_and_swap_workflow_run_lifecycle(
- config,
- WorkflowRunUpsert {
- id: run.id.clone(),
- definition_id: run.definition_id.clone(),
- parent_thread_id: run.parent_thread_id.clone(),
- input: run.input.clone(),
- phase_states,
- child_run_ids: run.child_run_ids.clone(),
- status: WorkflowRunStatus::Interrupted,
- summary: run.summary.clone(),
- started_at: Some(run.started_at),
- completed_at: None,
- },
- run.revision,
- )
- .context("persist workflow run interrupt")?;
- let updated = updated.ok_or_else(|| {
- anyhow!("workflow run {id} changed while stop was being applied; reload and retry")
- })?;
- if let Some(handle) = handle.as_ref() {
- let _ = supervisor.stop_generation(handle);
- }
-
- log::debug!(target: LOG_TARGET, "[workflow_run_engine] stop.marked_interrupted run={id}");
- Ok(Some(updated))
-}
-
-/// Resume an interrupted (or otherwise incomplete) workflow run.
-///
-/// Reloads the run, clears any stale cancellation flag, flips the row back to
-/// `Running`, and spawns a fresh engine loop. Phases already `completed` in
-/// `phase_states` are skipped; the loop continues from the first incomplete
-/// phase whose dependencies are satisfied. Returns the run row (now `Running`),
-/// or an error if the run is unknown / already terminal-complete / its
-/// definition no longer exists.
-pub async fn resume_workflow_run(
- ctx: &DispatchCtx,
- config: &Config,
- id: &str,
-) -> Result<WorkflowRun> {
- log::debug!(target: LOG_TARGET, "[workflow_run_engine] resume.entry run={id}");
- let run = get_workflow_run(config, id)?.ok_or_else(|| anyhow!("unknown workflow run: {id}"))?;
-
- if matches!(run.status, WorkflowRunStatus::Completed) {
- return Err(anyhow!("workflow run {id} is already completed"));
- }
-
- let definition = definition_by_id(&run.definition_id)
- .ok_or_else(|| anyhow!("definition {} no longer exists", run.definition_id))?;
- let _safety_tier = super::host::admit_workflow(&definition)?;
-
- let resume_config = config.clone();
- let resume_run = run.clone();
- let resume_id = id.to_string();
- let (handle, resumed) = schedule_workflow_drive(
- ctx,
- id.to_string(),
- definition,
- true,
- move || {
- compare_and_swap_workflow_run_lifecycle(
- &resume_config,
- WorkflowRunUpsert {
- id: resume_run.id.clone(),
- definition_id: resume_run.definition_id.clone(),
- parent_thread_id: resume_run.parent_thread_id.clone(),
- input: resume_run.input.clone(),
- phase_states: resume_run.phase_states.clone(),
- child_run_ids: resume_run.child_run_ids.clone(),
- status: WorkflowRunStatus::Running,
- summary: resume_run.summary.clone(),
- started_at: Some(resume_run.started_at),
- completed_at: None,
- },
- resume_run.revision,
- )
- .context("persist workflow run resume")?
- .ok_or_else(|| {
- anyhow!("workflow run {resume_id} changed while resume was being applied; reload and retry")
- })
- },
- )?;
- let _handle = handle;
-
- log::debug!(target: LOG_TARGET, "[workflow_run_engine] resume.spawned run={id}");
- Ok(resumed)
-}
-
-/// Drive the phase DAG with the parent context created by the owner's scoped
-/// lifecycle. The owner engine fences durable drive transitions with its run
-/// lease; the host only projects failures from setup before that engine starts.
-pub(crate) async fn run_engine_loop(
- config: &Config,
- run_id: &str,
- definition: WorkflowDefinition,
- handle: WorkflowRunHandle,
- admission_revision: u64,
- cancel_token: tinyagents_harness::CancellationToken,
- parent_override: Option<ParentExecutionContext>,
-) {
- let model_override = get_workflow_run(config, run_id)
- .ok()
- .flatten()
- .and_then(|run| {
- run.input
- .get("modelOverride")
- .and_then(Value::as_str)
- .map(str::to_owned)
- })
- .filter(|model| !model.trim().is_empty());
- let safety_tier = match super::host::admit_workflow(&definition) {
- Ok(tier) => tier,
- Err(error) => {
- log::error!(target: LOG_TARGET, "[workflow_run_engine] loop.safety_admission_failed run={run_id} err={error}");
- record_failed_if_current(
- config,
- run_id,
- &handle,
- admission_revision,
- format!("workflow safety admission failed: {error}"),
- );
- return;
- }
- };
- let store = match workflow_store(config) {
- Ok(store) => store,
- Err(error) => {
- log::error!(target: LOG_TARGET, "[workflow_run_engine] loop.no_store run={run_id} err={error:#}");
- return;
- }
- };
- let parent = parent_override.expect("owner lifecycle created the OpenHuman root parent");
- let engine = WorkflowEngine::new(
- store,
- Arc::new(super::host::OpenHumanWorkflowExecutor::new(
- run_id,
- model_override,
- safety_tier,
- Some(parent),
- )),
- )
- .with_event_sink(Arc::new(tinyagents_graph::GraphTracingSink::new(format!(
- "workflow:{run_id}"
- ))));
- let outcome = engine
- .drive(run_id, &definition, cancel_token)
- .await
- .map_err(anyhow::Error::msg);
-
- if let Err(err) = outcome {
- log::error!(
- target: LOG_TARGET,
- "[workflow_run_engine] loop.failed run={run_id} err={err}"
- );
- }
-}
-
-#[cfg(test)]
-#[path = "lifecycle_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/agent/orchestration/workflow_runs/engine/lifecycle_tests.rs b/crates/openhuman-core/src/agent/orchestration/workflow_runs/engine/lifecycle_tests.rs
deleted file mode 100644
index 9eb4df5969..0000000000
--- a/crates/openhuman-core/src/agent/orchestration/workflow_runs/engine/lifecycle_tests.rs
+++ /dev/null
@@ -1,290 +0,0 @@
-use super::*;
-use serde_json::json;
-
-#[tokio::test]
-async fn stop_fences_the_driver_and_makes_a_running_phase_resumable() {
- let workspace = tempfile::tempdir().expect("workspace");
- let config = Config {
- workspace_dir: workspace.path().to_path_buf(),
- ..Config::default()
- };
- let run = crate::storage::sessions::with_ledger(&config.workspace_dir, |ledger| {
- let ledger_arg_0 = WorkflowRunUpsert {
- id: "stop-resume-lifecycle".into(),
- definition_id: "parallel_research_cross_check".into(),
- parent_thread_id: None,
- input: json!({"question":"q"}),
- phase_states: json!({
- "decompose": {"status":"completed", "outputs": []},
- "research": {"status":"running", "outputs": []}
- }),
- child_run_ids: vec!["live-child".into()],
- status: WorkflowRunStatus::Running,
- summary: None,
- started_at: None,
- completed_at: None,
- };
- async move { ledger.upsert_workflow_run(ledger_arg_0).await }
- })
- .expect("seed run");
-
- let stopped = stop_workflow_run(&config, &run.id)
- .await
- .expect("stop succeeds")
- .expect("row exists");
- assert_eq!(stopped.status, WorkflowRunStatus::Interrupted);
- assert_eq!(stopped.phase_states["research"]["status"], json!("pending"));
- assert!(stopped.lease_owner.is_none());
- assert!(
- stopped.revision > run.revision,
- "stop must fence the old driver"
- );
-}
-
-#[tokio::test]
-async fn stale_workflow_generation_cannot_fail_its_replacement() {
- let workspace = tempfile::tempdir().expect("workspace");
- let config = Config {
- workspace_dir: workspace.path().to_path_buf(),
- ..Config::default()
- };
- let run_id = format!("stale-generation-{}", uuid::Uuid::new_v4());
- let seeded = crate::storage::sessions::with_ledger(&config.workspace_dir, |ledger| {
- let row = WorkflowRunUpsert {
- id: run_id.clone(),
- definition_id: "parallel_research_cross_check".into(),
- parent_thread_id: None,
- input: json!({"question":"q"}),
- phase_states: json!({"research":{"status":"pending","outputs":[]}}),
- child_run_ids: Vec::new(),
- status: WorkflowRunStatus::Running,
- summary: None,
- started_at: None,
- completed_at: None,
- };
- async move { ledger.upsert_workflow_run(row).await }
- })
- .expect("seed run");
-
- let supervisor = workflow_supervisor().clone();
- let old = supervisor.start_scoped_with_handle(
- run_id.clone(),
- |token| async move { token.cancelled().await },
- |future| future,
- |future| future,
- |_handle, future| {
- tokio::spawn(future);
- },
- );
- let current = supervisor.start_scoped_with_handle(
- run_id.clone(),
- |token| async move { token.cancelled().await },
- |future| future,
- |future| future,
- |_handle, future| {
- tokio::spawn(future);
- },
- );
- assert!(!supervisor.is_current(&old));
- assert!(supervisor.is_current(&current));
-
- let advanced = compare_and_swap_workflow_run_lifecycle(
- &config,
- WorkflowRunUpsert {
- id: seeded.id.clone(),
- definition_id: seeded.definition_id.clone(),
- parent_thread_id: seeded.parent_thread_id.clone(),
- input: seeded.input.clone(),
- phase_states: seeded.phase_states.clone(),
- child_run_ids: seeded.child_run_ids.clone(),
- status: WorkflowRunStatus::Running,
- summary: Some("replacement revision".into()),
- started_at: Some(seeded.started_at),
- completed_at: None,
- },
- seeded.revision,
- )
- .expect("advance workflow revision")
- .expect("the seeded revision is current");
-
- record_failed_if_current(
- &config,
- &run_id,
- &old,
- seeded.revision,
- "stale sentinel".into(),
- );
- record_failed_if_current(
- &config,
- &run_id,
- &current,
- seeded.revision,
- "stale revision sentinel".into(),
- );
- let unchanged = crate::storage::sessions::with_ledger(&config.workspace_dir, |ledger| {
- let id = run_id.clone();
- async move { ledger.get_workflow_run(&id).await }
- })
- .expect("read row")
- .expect("run exists");
- assert_eq!(unchanged.revision, advanced.revision);
- assert_eq!(unchanged.summary.as_deref(), Some("replacement revision"));
-
- let stopped = stop_workflow_run(&config, &run_id)
- .await
- .expect("stop succeeds")
- .expect("run exists");
- assert_eq!(stopped.status, WorkflowRunStatus::Interrupted);
- assert!(current.cancellation_token().is_cancelled());
-}
-
-#[tokio::test]
-async fn losing_resume_cas_keeps_the_installed_workflow_generation() {
- let workspace = tempfile::tempdir().expect("workspace");
- let config = Config {
- workspace_dir: workspace.path().to_path_buf(),
- ..Config::default()
- };
- let run_id = format!("resume-cas-race-{}", uuid::Uuid::new_v4());
- let interrupted = crate::storage::sessions::with_ledger(&config.workspace_dir, |ledger| {
- let row = WorkflowRunUpsert {
- id: run_id.clone(),
- definition_id: "parallel_research_cross_check".into(),
- parent_thread_id: None,
- input: json!({"question":"q"}),
- phase_states: json!({"research":{"status":"pending","outputs":[]}}),
- child_run_ids: Vec::new(),
- status: WorkflowRunStatus::Interrupted,
- summary: None,
- started_at: None,
- completed_at: None,
- };
- async move { ledger.upsert_workflow_run(row).await }
- })
- .expect("seed interrupted run");
-
- let supervisor = workflow_supervisor().clone();
- let old = supervisor.start_scoped_with_handle(
- run_id.clone(),
- |token| async move { token.cancelled().await },
- |future| future,
- |future| future,
- |_handle, future| {
- tokio::spawn(future);
- },
- );
- let make_commit = || {
- let config = config.clone();
- let interrupted = interrupted.clone();
- move || {
- compare_and_swap_workflow_run_lifecycle(
- &config,
- WorkflowRunUpsert {
- id: interrupted.id.clone(),
- definition_id: interrupted.definition_id.clone(),
- parent_thread_id: interrupted.parent_thread_id.clone(),
- input: interrupted.input.clone(),
- phase_states: interrupted.phase_states.clone(),
- child_run_ids: interrupted.child_run_ids.clone(),
- status: WorkflowRunStatus::Running,
- summary: interrupted.summary.clone(),
- started_at: Some(interrupted.started_at),
- completed_at: None,
- },
- interrupted.revision,
- )?
- .ok_or_else(|| anyhow!("workflow run changed before resume"))
- }
- };
- let resume = |commit| {
- supervisor.resume_scoped_with_commit(
- run_id.clone(),
- commit,
- |token| async move { token.cancelled().await },
- |future| future,
- |future| future,
- |_handle, future| {
- tokio::spawn(future);
- },
- )
- };
-
- let (winner, resumed) = resume(make_commit()).expect("one resume commits");
- assert!(old.cancellation_token().is_cancelled());
- assert!(supervisor.is_current(&winner));
- assert_eq!(resumed.status, WorkflowRunStatus::Running);
-
- assert!(resume(make_commit()).is_err(), "stale resume CAS must lose");
- assert!(supervisor.is_current(&winner));
- assert!(
- !winner.cancellation_token().is_cancelled(),
- "a losing resume must not cancel the committed generation"
- );
-}
-
-#[tokio::test]
-async fn stale_setup_failure_does_not_overwrite_another_process_lease() {
- use tinyagents_session::run_ledger::WorkflowLeaseClaim;
-
- let workspace = tempfile::tempdir().expect("workspace");
- let config = Config {
- workspace_dir: workspace.path().to_path_buf(),
- ..Config::default()
- };
- let run_id = format!("workflow-lease-owner-{}", uuid::Uuid::new_v4());
- let seeded = crate::storage::sessions::with_ledger(&config.workspace_dir, |ledger| {
- let row = WorkflowRunUpsert {
- id: run_id.clone(),
- definition_id: "parallel_research_cross_check".into(),
- parent_thread_id: None,
- input: json!({"question":"q"}),
- phase_states: json!({"research":{"status":"pending","outputs":[]}}),
- child_run_ids: Vec::new(),
- status: WorkflowRunStatus::Running,
- summary: None,
- started_at: None,
- completed_at: None,
- };
- async move { ledger.upsert_workflow_run(row).await }
- })
- .expect("seed run");
- let claim = crate::storage::sessions::with_ledger(&config.workspace_dir, |ledger| {
- let id = run_id.clone();
- async move {
- ledger
- .try_claim_workflow_run(&id, "other-process", chrono::Duration::hours(1))
- .await
- }
- })
- .expect("claim workflow lease");
- let claimed = match claim {
- WorkflowLeaseClaim::Acquired(run) => run,
- other => panic!("expected lease acquisition, got {other:?}"),
- };
-
- let supervisor = workflow_supervisor().clone();
- let handle = supervisor.start_scoped_with_handle(
- run_id.clone(),
- |token| async move { token.cancelled().await },
- |future| future,
- |future| future,
- |_handle, future| {
- tokio::spawn(future);
- },
- );
- record_failed_if_current(
- &config,
- &run_id,
- &handle,
- seeded.revision,
- "stale setup failure".into(),
- );
-
- let after = get_workflow_run(&config, &run_id)
- .expect("read run")
- .expect("run remains present");
- assert_eq!(after.status, WorkflowRunStatus::Running);
- assert_eq!(after.lease_owner.as_deref(), Some("other-process"));
- assert_eq!(after.revision, claimed.revision);
- assert_ne!(after.summary.as_deref(), Some("stale setup failure"));
-}
diff --git a/crates/openhuman-core/src/agent/orchestration/workflow_runs/host.rs b/crates/openhuman-core/src/agent/orchestration/workflow_runs/host.rs
deleted file mode 100644
index 7fcc4202d4..0000000000
--- a/crates/openhuman-core/src/agent/orchestration/workflow_runs/host.rs
+++ /dev/null
@@ -1,193 +0,0 @@
-//! OpenHuman's thin, policy-owning adapter for the neutral workflow engine.
-
-use std::sync::Arc;
-
-use anyhow::{anyhow, Result};
-use async_trait::async_trait;
-use serde_json::json;
-use tinyagents_harness::CancellationToken;
-use tinyagents_orchestration::workflow::{
- OrchestrationError, WorkflowChildRegistration, WorkflowChildRequest, WorkflowChildResult,
- WorkflowDefinition, WorkflowExecutor,
-};
-
-use crate::agent::harness::ParentExecutionContext;
-use crate::agent_registry::host_definition::AgentDefinitionRegistry;
-use tinyagents_definition::{SandboxMode, ToolScope};
-use {
- crate::agent::orchestration::AgentOrchestrationSession,
- crate::agent::orchestration::SpawnAgentRequest, crate::agent::orchestration::WaitAgentOptions,
- tinyagents_tasks::OrchestrationTaskStatus,
-};
-
-/// Product policy deliberately remains in OpenHuman. The portable engine sees
-/// no safety labels; this adapter admits a catalog definition and keeps its
-/// children inside the advertised capability envelope.
-#[derive(Clone, Copy)]
-pub(super) enum WorkflowSafetyTier {
- ReadOnly,
-}
-
-pub(super) fn admit_workflow(definition: &WorkflowDefinition) -> Result<WorkflowSafetyTier> {
- match definition
- .extensions
- .get("safetyTier")
- .and_then(serde_json::Value::as_str)
- {
- Some("read_only") => Ok(WorkflowSafetyTier::ReadOnly),
- Some(other) => Err(anyhow!(
- "workflow '{}' has unsupported safetyTier '{other}'",
- definition.id
- )),
- None => Err(anyhow!(
- "workflow '{}' is missing required safetyTier",
- definition.id
- )),
- }
-}
-
-/// Host policy has already admitted the parent context before this executor is
-/// created. This adapter only translates one neutral child request into the
-/// existing OpenHuman subagent session and retains BUS/progress behaviour there.
-#[derive(Clone)]
-pub(super) struct OpenHumanWorkflowExecutor {
- session: AgentOrchestrationSession,
- model_override: Option<String>,
- safety_tier: WorkflowSafetyTier,
- /// The root parent execution context the children are spawned under.
- /// `None` for an executor that only persists the initial run row and never
- /// spawns (`start_workflow_run`'s `initialise`).
- parent: Option<ParentExecutionContext>,
-}
-
-impl OpenHumanWorkflowExecutor {
- pub(super) fn new(
- run_id: &str,
- model_override: Option<String>,
- safety_tier: WorkflowSafetyTier,
- parent: Option<ParentExecutionContext>,
- ) -> Self {
- Self {
- session: AgentOrchestrationSession::new(format!("workflow-engine-{run_id}")),
- model_override,
- safety_tier,
- parent,
- }
- }
-
- fn admit_child(&self, agent_id: &str) -> Result<(), OrchestrationError> {
- match self.safety_tier {
- WorkflowSafetyTier::ReadOnly => {
- let registry = AgentDefinitionRegistry::current().ok_or_else(|| {
- OrchestrationError(
- "workflow safety admission requires the agent registry".to_owned(),
- )
- })?;
- let definition = registry.get(agent_id).ok_or_else(|| {
- OrchestrationError(format!(
- "workflow safety admission rejected unknown agent '{agent_id}'"
- ))
- })?;
- let allowed_named_tool = |tool: &str| {
- matches!(
- tool,
- "web_search_tool" | "web_answer_tool" | "web_contents_tool" | "web_fetch"
- )
- };
- let read_only = matches!(definition.sandbox_mode, SandboxMode::ReadOnly)
- || matches!(&definition.tools, ToolScope::Named(tools) if tools.iter().all(|tool| allowed_named_tool(tool)));
- if read_only {
- Ok(())
- } else {
- Err(OrchestrationError(format!(
- "workflow safetyTier read_only rejected agent '{agent_id}' with acting-capable tools"
- )))
- }
- }
- }
- }
-}
-
-#[async_trait]
-impl WorkflowExecutor for OpenHumanWorkflowExecutor {
- async fn execute(
- &self,
- request: WorkflowChildRequest,
- cancel: CancellationToken,
- registration: Arc<dyn WorkflowChildRegistration>,
- ) -> Result<WorkflowChildResult, OrchestrationError> {
- self.admit_child(&request.agent_id)?;
- if cancel.is_cancelled() {
- return Err(OrchestrationError(
- "workflow cancelled before child spawn".to_owned(),
- ));
- }
- let parent = self.parent.clone().ok_or_else(|| {
- OrchestrationError(
- "workflow child spawn requires a parent execution context".to_owned(),
- )
- })?;
- let response = self
- .session
- .spawn_agent(
- parent,
- SpawnAgentRequest {
- agent_id: request.agent_id.clone(),
- prompt: request.prompt,
- model: self.model_override.clone(),
- ..Default::default()
- },
- )
- .await
- .map_err(|error| OrchestrationError(error.to_string()))?;
-
- // This must happen before awaiting the child: stop() can now cancel
- // every real orchestration id while a worker remains in flight.
- registration.register(response.orchestration_id.clone())?;
- if cancel.is_cancelled() {
- self.session.abort_all().await;
- return Err(OrchestrationError(
- "workflow cancelled after child spawn".to_owned(),
- ));
- }
- let wait = self
- .session
- .wait_agents(WaitAgentOptions {
- orchestration_ids: vec![response.orchestration_id.clone()],
- timeout_ms: None,
- })
- .await
- .map_err(|error| OrchestrationError(error.to_string()))?;
- let child = wait.agents.into_iter().next().ok_or_else(|| {
- OrchestrationError("workflow child returned no terminal snapshot".to_owned())
- })?;
- if child.status != OrchestrationTaskStatus::Completed {
- return Err(OrchestrationError(format!(
- "child '{}' (agent '{}') ended {:?}: {}",
- child.orchestration_id,
- child.agent_id,
- child.status,
- child.error.unwrap_or_default()
- )));
- }
- Ok(WorkflowChildResult {
- child_id: response.orchestration_id,
- // Do not coerce to text: the neutral engine faithfully carries
- // host output JSON into downstream prompts and synthesis.
- output: json!({
- "agentId": child.agent_id,
- "summary": child.result_summary,
- }),
- })
- }
-
- async fn cancel_children(&self, _child_ids: &[String]) {
- // AgentOrchestrationSession is per workflow run, so this aborts exactly
- // its registered children while retaining existing BUS/progress events.
- self.session.abort_all().await;
- }
-}
-
-#[cfg(test)]
-#[path = "host_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/agent/orchestration/workflow_runs/host_tests.rs b/crates/openhuman-core/src/agent/orchestration/workflow_runs/host_tests.rs
deleted file mode 100644
index b4368aa772..0000000000
--- a/crates/openhuman-core/src/agent/orchestration/workflow_runs/host_tests.rs
+++ /dev/null
@@ -1,29 +0,0 @@
-use super::*;
-use std::collections::BTreeMap;
-use tinyagents_orchestration::workflow::WorkflowDefinition;
-
-fn definition(safety_tier: Option<&str>) -> WorkflowDefinition {
- let mut extensions = BTreeMap::new();
- if let Some(safety_tier) = safety_tier {
- extensions.insert("safetyTier".to_owned(), serde_json::json!(safety_tier));
- }
- WorkflowDefinition {
- id: "host-safety".into(),
- name: "host safety".into(),
- description: String::new(),
- phases: Vec::new(),
- default_concurrency: 1,
- max_children: 1,
- extensions,
- }
-}
-
-#[test]
-fn host_admits_only_explicit_supported_safety_tiers() {
- assert!(matches!(
- admit_workflow(&definition(Some("read_only"))),
- Ok(WorkflowSafetyTier::ReadOnly)
- ));
- assert!(admit_workflow(&definition(None)).is_err());
- assert!(admit_workflow(&definition(Some("full"))).is_err());
-}
diff --git a/crates/openhuman-core/src/agent_registry/agents/critic/agent.toml b/crates/openhuman-core/src/agent_registry/agents/critic/agent.toml
deleted file mode 100644
index 1bb48bd2a0..0000000000
--- a/crates/openhuman-core/src/agent_registry/agents/critic/agent.toml
+++ /dev/null
@@ -1,21 +0,0 @@
-id = "critic"
-display_name = "Critic"
-delegate_name = "review_code"
-when_to_use = "Workflow-run worker: adversarial read-only cross-check of claims, diffs and code (vulnerabilities, regressions, missing tests). Not a chat delegate."
-temperature = 0.4
-max_iterations = 5
-# Bound the review verdict that flows up to the orchestrator verbatim
-# (delegate_critic). 8000 chars (~2000 tokens) matches the normal
-# sub-agent cap (planner) and keeps long diffs from leaking
-# an unbounded critique into the orchestrator's context (#4099).
-max_result_chars = 8000
-sandbox_mode = "read_only"
-omit_identity = true
-omit_memory_context = true
-omit_safety_preamble = true
-
-[model]
-hint = "agentic"
-
-[tools]
-named = ["read_diff", "run_linter", "run_tests", "file_read"]
diff --git a/crates/openhuman-core/src/agent_registry/agents/critic/prompt.md b/crates/openhuman-core/src/agent_registry/agents/critic/prompt.md
deleted file mode 100644
index 85c678facf..0000000000
--- a/crates/openhuman-core/src/agent_registry/agents/critic/prompt.md
+++ /dev/null
@@ -1,25 +0,0 @@
-# Critic — Adversarial QA Reviewer
-
-You are the **Critic** agent. Your job is to find problems before they reach production.
-
-## Capabilities
-
-- Read git diffs to review changes
-- Run linters (clippy, eslint) and interpret findings
-- Run test suites and verify correctness
-- Read project files for context
-
-## Review Checklist
-
-1. **Security** — SQL injection, XSS, command injection, hardcoded secrets, OWASP top 10.
-2. **Correctness** — Edge cases, off-by-one errors, null/None handling, race conditions.
-3. **Style** — Naming conventions, code organization, consistency with existing patterns.
-4. **Tests** — Are new paths covered? Do existing tests still pass?
-5. **SOUL.md compliance** — Does the code align with the project's core principles?
-
-## Rules
-
-- **Be specific** — "Line 42: SQL string interpolation is injectable" not "code might have security issues".
-- **Prioritise** — Flag critical issues first (security > correctness > style).
-- **Be constructive** — Suggest fixes, not just complaints.
-- **Read-only** — You review but never modify code. Report findings to the Orchestrator.
diff --git a/crates/openhuman-core/src/agent_registry/agents/critic/prompt.rs b/crates/openhuman-core/src/agent_registry/agents/critic/prompt.rs
deleted file mode 100644
index 35e464b1f2..0000000000
--- a/crates/openhuman-core/src/agent_registry/agents/critic/prompt.rs
+++ /dev/null
@@ -1,31 +0,0 @@
-//! System prompt builder for the `critic` built-in agent.
-//!
-//! Returns the final, fully-assembled system prompt — archetype body
-//! (from the sibling `prompt.md`) plus the same section helpers the
-//! runtime uses for every other agent.
-
-use crate::agent::prompts::PromptContext;
-use crate::prompts::{render_tools, render_workspace};
-use anyhow::Result;
-
-const ARCHETYPE: &str = include_str!("prompt.md");
-
-pub fn build(ctx: &PromptContext<'_>) -> Result<String> {
- let mut out = String::with_capacity(4096);
- out.push_str(ARCHETYPE.trim_end());
- out.push_str("\n\n");
-
- let tools = render_tools(ctx)?;
- if !tools.trim().is_empty() {
- out.push_str(tools.trim_end());
- out.push_str("\n\n");
- }
-
- let workspace = render_workspace(ctx)?;
- if !workspace.trim().is_empty() {
- out.push_str(workspace.trim_end());
- out.push('\n');
- }
-
- Ok(out)
-}
diff --git a/crates/openhuman-core/src/agent_registry/agents/planner/agent.toml b/crates/openhuman-core/src/agent_registry/agents/planner/agent.toml
deleted file mode 100644
index 73f92fc516..0000000000
--- a/crates/openhuman-core/src/agent_registry/agents/planner/agent.toml
+++ /dev/null
@@ -1,83 +0,0 @@
-id = "planner"
-display_name = "Planner"
-delegate_name = "plan"
-when_to_use = "Workflow-run worker: decompose a question into independent research angles, or research one angle, grounded in memory and the web. Read-only; not a chat delegate."
-temperature = 0.4
-max_iterations = 8
-iteration_policy = "extended"
-max_result_chars = 8000
-sandbox_mode = "read_only"
-omit_identity = true
-omit_memory_context = false
-omit_safety_preamble = true
-# The planner keeps `omit_memory_context = false`, so it receives the
-# compiled memory context at session start. It has no `memory` tool: the
-# tool reports `Write` permission without arguments, which a read-only
-# sandbox cannot admit, so deeper memory lookups are the caller's concern
-# and arrive in the delegation prompt.
-
-# Spawn hierarchy: this is the deep-thinking tier (reasoning model hint).
-# The planner produces a DAG of leaf tasks for downstream workers; it
-# must NOT delegate to another `reasoning` agent. The loader rejects
-# any same-tier entry added to a future `subagents` list.
-agent_tier = "reasoning"
-
-[model]
-hint = "reasoning"
-
-[tools]
-# Read + research only. The planner produces plans — it never mutates
-# the workspace, memory, or state. Any writes the plan requires get
-# executed by the caller after the workflow run.
-#
-# Composio meta-tools are included so the planner can inspect connected
-# integrations, list available actions, and pull data needed to ground
-# a plan. `sandbox_mode = "read_only"` above triggers the agent-level
-# gate in `composio_execute` that rejects Write/Admin-scoped action
-# slugs (#685), so the planner cannot send email / create pages / etc.
-# even though `composio_execute` is on this list. Only `Read`-scoped
-# actions slip past the gate.
-named = [
- "file_read",
- # Read-only nav primitives from #1208. `edit`, `apply_patch`, `lsp`
- # are intentionally NOT included — sandbox_mode = "read_only" above
- # forbids workspace mutations, and downstream agents do the writing.
- # `todo` lets the planner emit a structured todo list. (`todowrite` was
- # a legacy alias that resolved to no registered tool, and `plan_exit`'s
- # marker had no consumer, so both left.)
- "grep",
- "glob",
- "list",
- "todo",
- "web_fetch",
- "web_search_tool",
- # Grounded answers + market-data lookups so plans can be anchored in
- # real numbers (stock/crypto prices) and current web context, not just
- # whatever the model happens to remember.
- "web_answer_tool",
- # Reads up to ten pages per call; with `web_answer_tool` `depth: "deep"`
- # this is how the planner does its own multi-source research (there is no
- # research sub-agent to hand it to).
- "web_contents_tool",
- "stock_quote",
- "stock_exchange_rate",
- "stock_crypto_series",
- "stock_commodity",
- "composio_list_toolkits",
- "composio_list_connections",
- "composio_list_tools",
- "composio_execute",
- # MCP discovery (read-only) so plans can be grounded in the user's
- # connected MCP servers — what's connected (`mcp_registry_status`),
- # which servers are installed (`mcp_registry_installed_list`), and what
- # tools each connected server exposes (`mcp_registry_list_tools`). All
- # three are `PermissionLevel::ReadOnly` (no side effects), so they fit
- # the read-only sandbox. `mcp_registry_tool_call` is deliberately NOT
- # here: unlike `composio_execute` (gated to Read-scoped slugs by the
- # sandbox), an MCP tool call invokes an arbitrary server tool the core
- # cannot classify as read vs. write, so there is no safe read-only gate.
- # Executing connected-MCP tools stays with the orchestrator (`tool_search`).
- "mcp_registry_status",
- "mcp_registry_installed_list",
- "mcp_registry_list_tools",
-]
diff --git a/crates/openhuman-core/src/agent_registry/agents/planner/prompt.md b/crates/openhuman-core/src/agent_registry/agents/planner/prompt.md
deleted file mode 100644
index b68e856c65..0000000000
--- a/crates/openhuman-core/src/agent_registry/agents/planner/prompt.md
+++ /dev/null
@@ -1,60 +0,0 @@
-# Planner — Task Architect
-
-You are the **Planner** agent. Your job is to decompose a complex user goal into a **directed acyclic graph (DAG)** of discrete tasks.
-
-Before you plan, **gather context** so the plan is grounded in reality, not guesses:
-
-- Read the memory context your session opened with and the context the caller handed you — past decisions, user preferences, project context, prior plans. Planning blind is expensive.
-- Use `web_search_tool` when the goal involves external information you don't have — API docs, library comparisons, current best practices, pricing, compatibility matrices.
-- Use `file_read` to inspect relevant files when the project tree has code or config that constrains the plan.
-
-Only produce the plan JSON **after** you have the context you need. A plan built on assumptions the provided context or a quick search could have resolved is a bad plan.
-
-## Output Format
-
-Return **only** valid JSON matching this schema:
-
-```json
-{
- "root_goal": "the user's original goal",
- "context_gathered": "Brief summary of what you learned from memory/search that shaped the plan",
- "nodes": [
- {
- "id": "task-1",
- "description": "Clear, actionable instruction for the sub-agent",
- "agent_id": "planner",
- "depends_on": [],
- "acceptance_criteria": "How to verify this task is done correctly"
- }
- ]
-}
-```
-
-## Where your output goes
-
-You run as a worker inside a workflow run (the `parallel_research_cross_check` template), not as a chat delegate. The run hands your result to the next phase:
-
-- In a **decompose** phase, return the plan JSON above; each node is one independent research angle, and `agent_id` names the phase worker (`planner`) or is omitted.
-- In a **research** phase, you are given one angle: gather evidence for it with `web_answer_tool` (`depth: "deep"` for multi-source research, when offered), `web_search_tool`, `web_contents_tool` and `web_fetch`, and return the findings with their sources instead of a plan.
-
-## Rules
-
-0. **You are a read-only reasoning worker.** You never spawn other agents. Connected-service actions and writes belong to the caller, not to you.
-1. **Gather before planning** — Use the provided context and search the web first. Don't guess what you can look up.
-2. **Minimise tasks** — Use the fewest nodes needed. Don't over-decompose.
-3. **Dependencies matter** — Use `depends_on` to express ordering. Independent tasks run in parallel.
-4. **Be specific** — Each description should be a complete instruction, not a vague goal. Include relevant context you gathered.
-5. **Include acceptance criteria** — How will we know the task succeeded?
-6. **Simple goals = single node** — If the goal is straightforward, return exactly 1 node.
-7. **No cycles** — The graph must be a DAG (directed acyclic graph).
-8. **Max 8 nodes** — Keep plans manageable. Split larger projects into multiple plans.
-9. **Read-only** — You have no write tools. If a plan depends on saving something, say so in the node's description so the caller performs the write.
-
-## Long-horizon Artifacts
-
-Plans for long-horizon work should hand data between nodes by **path**, not by pasting it forward.
-
-- When a node produces a large deliverable (a report, a dataset, a generated document), say so in its description and have it written under `outputs/`.
-- Reference that path in the dependent node's description, so the downstream worker reads the file instead of receiving the payload through context.
-- `workspace/` is for per-node scratch that no later node needs.
-- Both directories are relative to the action directory. Plans must never target the core's internal workspace state.
diff --git a/crates/openhuman-core/src/agent_registry/agents/planner/prompt.rs b/crates/openhuman-core/src/agent_registry/agents/planner/prompt.rs
deleted file mode 100644
index 0cd12fe67f..0000000000
--- a/crates/openhuman-core/src/agent_registry/agents/planner/prompt.rs
+++ /dev/null
@@ -1,38 +0,0 @@
-//! System prompt builder for the `planner` built-in agent.
-//!
-//! Returns the fully-assembled system prompt. Each agent's `build()`
-//! composes section helpers from [`crate::agent::prompts`]
-//! in the order it wants — so the output IS what the LLM sees, no
-//! post-processing in the runner.
-
-use crate::agent::prompts::PromptContext;
-use crate::prompts::{render_datetime, render_tools, render_workspace};
-use anyhow::Result;
-
-const ARCHETYPE: &str = include_str!("prompt.md");
-
-pub fn build(ctx: &PromptContext<'_>) -> Result<String> {
- let mut out = String::with_capacity(4096);
- out.push_str(ARCHETYPE.trim_end());
- out.push_str("\n\n");
-
- let tools = render_tools(ctx)?;
- if !tools.trim().is_empty() {
- out.push_str(tools.trim_end());
- out.push_str("\n\n");
- }
-
- let datetime = render_datetime(ctx)?;
- if !datetime.trim().is_empty() {
- out.push_str(datetime.trim_end());
- out.push_str("\n\n");
- }
-
- let workspace = render_workspace(ctx)?;
- if !workspace.trim().is_empty() {
- out.push_str(workspace.trim_end());
- out.push('\n');
- }
-
- Ok(out)
-}
diff --git a/crates/openhuman-core/src/agent_runs/workflow_runs/mod.rs b/crates/openhuman-core/src/agent_runs/workflow_runs/mod.rs
deleted file mode 100644
index 6f35f9d5d6..0000000000
--- a/crates/openhuman-core/src/agent_runs/workflow_runs/mod.rs
+++ /dev/null
@@ -1,15 +0,0 @@
-//! Durable dynamic workflow run RPC surface.
-
-#[path = "../../agent/orchestration/workflow_runs/host.rs"]
-mod host;
-#[path = "../../agent/orchestration/workflow_runs/engine/lifecycle.rs"]
-mod lifecycle;
-const LOG_TARGET: &str = "workflow_run_engine";
-mod ops;
-mod schemas;
-
-pub(crate) use lifecycle::{resume_workflow_run, start_workflow_run, stop_workflow_run};
-pub(crate) use schemas::{
- all_controller_schemas as all_workflow_run_controller_schemas,
- all_registered_controllers as all_workflow_run_registered_controllers,
-};
diff --git a/crates/openhuman-core/src/agent_runs/workflow_runs/ops.rs b/crates/openhuman-core/src/agent_runs/workflow_runs/ops.rs
deleted file mode 100644
index 42084738d8..0000000000
--- a/crates/openhuman-core/src/agent_runs/workflow_runs/ops.rs
+++ /dev/null
@@ -1,107 +0,0 @@
-//! OpenHuman's workflow catalog and ledger read adapters.
-//!
-//! Definitions, validation, scheduling and fan-out live in
-//! `tinyagents-orchestration`. This module retains only product catalog
-//! selection, live agent lookup and the configured persistence root.
-
-use std::collections::BTreeMap;
-
-use anyhow::Result;
-use serde_json::json;
-use std::sync::Arc;
-use tinyagents_orchestration::workflow::{
- WorkflowDefinition, WorkflowDefinitionListResponse, WorkflowPhase,
-};
-
-use tinyagents_orchestration::workflow::SessionWorkflowStore;
-use tinyagents_session::run_ledger::{
- WorkflowRun, WorkflowRunListRequest, WorkflowRunListResponse, WorkflowRunUpsert,
-};
-
-use crate::config::Config;
-
-pub const PARALLEL_RESEARCH_ID: &str = "parallel_research_cross_check";
-
-/// Product-selected workflow catalog. `safetyTier` remains opaque data here;
-/// the host's admission adapter remains responsible for policy enforcement.
-pub fn builtin_definitions() -> Vec<WorkflowDefinition> {
- vec![WorkflowDefinition {
- id: PARALLEL_RESEARCH_ID.to_owned(),
- name: "Parallel research with cross-checking".to_owned(),
- description: "Decompose a question into angles, research them in parallel, cross-check the claims with a critic, then synthesize a cited report. Read-only.".to_owned(),
- phases: vec![
- WorkflowPhase { name: "decompose".into(), description: "Break the question into independent research angles.".into(), agent_ids: vec!["planner".into()], depends_on: vec![] },
- WorkflowPhase { name: "research".into(), description: "Research each angle in parallel.".into(), agent_ids: vec!["planner".into(), "planner".into()], depends_on: vec!["decompose".into()] },
- WorkflowPhase { name: "cross_check".into(), description: "Adversarially cross-check the gathered claims.".into(), agent_ids: vec!["critic".into()], depends_on: vec!["research".into()] },
- WorkflowPhase { name: "synthesize".into(), description: "Synthesize a single cited report.".into(), agent_ids: vec!["summarizer".into()], depends_on: vec!["cross_check".into()] },
- ],
- default_concurrency: 2,
- max_children: 8,
- extensions: BTreeMap::from([("safetyTier".to_owned(), json!("read_only"))]),
- }]
-}
-
-pub fn definition_by_id(id: &str) -> Option<WorkflowDefinition> {
- builtin_definitions()
- .into_iter()
- .find(|definition| definition.id == id)
-}
-
-pub fn list_definitions() -> WorkflowDefinitionListResponse {
- let definitions = builtin_definitions();
- WorkflowDefinitionListResponse {
- count: definitions.len(),
- definitions,
- }
-}
-
-pub fn list_runs(
- config: &Config,
- request: &WorkflowRunListRequest,
-) -> Result<WorkflowRunListResponse> {
- let request = request.clone();
- Ok(crate::storage::sessions::with_ledger(
- &config.workspace_dir,
- |ledger| async move { ledger.list_workflow_runs(&request).await },
- )?)
-}
-
-pub fn get_run(config: &Config, id: &str) -> Result<Option<WorkflowRun>> {
- get_workflow_run(config, id)
-}
-
-/// The workflow run `id` on the calling tenant's run ledger.
-pub(super) fn get_workflow_run(config: &Config, id: &str) -> Result<Option<WorkflowRun>> {
- let id = id.to_string();
- Ok(crate::storage::sessions::with_ledger(
- &config.workspace_dir,
- |ledger| async move { ledger.get_workflow_run(&id).await },
- )?)
-}
-
-/// A host lifecycle transition (stop, resume) fenced on the revision the
-/// caller observed; `None` when another writer moved the row first.
-pub(super) fn compare_and_swap_workflow_run_lifecycle(
- config: &Config,
- upsert: WorkflowRunUpsert,
- expected_revision: u64,
-) -> Result<Option<WorkflowRun>> {
- Ok(crate::storage::sessions::with_ledger(
- &config.workspace_dir,
- |ledger| async move {
- ledger
- .compare_and_swap_workflow_run_lifecycle(upsert, expected_revision)
- .await
- },
- )?)
-}
-
-/// The engine's workflow store over the calling tenant's run ledger.
-pub(super) fn workflow_store(config: &Config) -> Result<Arc<SessionWorkflowStore>> {
- let ledger = crate::storage::sessions::require_ledger(&config.workspace_dir)?;
- Ok(Arc::new(SessionWorkflowStore::new(ledger)?))
-}
-
-#[cfg(test)]
-#[path = "ops_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/agent_runs/workflow_runs/ops_tests.rs b/crates/openhuman-core/src/agent_runs/workflow_runs/ops_tests.rs
deleted file mode 100644
index 7fe46fcb60..0000000000
--- a/crates/openhuman-core/src/agent_runs/workflow_runs/ops_tests.rs
+++ /dev/null
@@ -1,151 +0,0 @@
-use super::*;
-use tinyagents_orchestration::workflow::{
- validate_agents, validate_structure, DefinitionError, WorkflowDefinition, WorkflowPhase,
-};
-
-fn good_def() -> WorkflowDefinition {
- definition_by_id(PARALLEL_RESEARCH_ID).expect("builtin present")
-}
-
-#[test]
-fn builtin_is_structurally_valid() {
- assert!(validate_structure(&good_def()).is_empty());
-}
-
-#[test]
-fn builtin_agents_pass_when_all_known() {
- // Treat the four referenced agents as registered.
- let known = ["planner", "researcher", "critic", "summarizer"];
- let errors = validate_agents(&good_def(), |id| known.contains(&id));
- assert!(errors.is_empty(), "unexpected: {errors:?}");
-}
-
-#[test]
-fn unknown_agent_is_reported() {
- let errors = validate_agents(&good_def(), |id| id == "planner");
- // critic and summarizer are unknown -> 2 errors.
- assert_eq!(errors.len(), 2, "{errors:?}");
- assert!(errors.iter().any(
- |e| matches!(e, DefinitionError::UnknownAgent { agent_id, .. } if agent_id == "critic")
- ));
-}
-
-#[test]
-fn no_phases_is_rejected() {
- let mut def = good_def();
- def.phases.clear();
- assert_eq!(validate_structure(&def), vec![DefinitionError::NoPhases]);
-}
-
-#[test]
-fn duplicate_and_empty_phase_are_reported() {
- let def = WorkflowDefinition {
- phases: vec![
- WorkflowPhase {
- name: "a".into(),
- description: String::new(),
- agent_ids: vec!["researcher".into()],
- depends_on: vec![],
- },
- WorkflowPhase {
- name: "a".into(),
- description: String::new(),
- agent_ids: vec![],
- depends_on: vec![],
- },
- ],
- ..good_def()
- };
- let errors = validate_structure(&def);
- assert!(errors.contains(&DefinitionError::DuplicatePhase { name: "a".into() }));
- assert!(errors.contains(&DefinitionError::EmptyPhase { phase: "a".into() }));
-}
-
-#[test]
-fn unknown_dependency_is_reported() {
- let def = WorkflowDefinition {
- phases: vec![WorkflowPhase {
- name: "only".into(),
- description: String::new(),
- agent_ids: vec!["researcher".into()],
- depends_on: vec!["ghost".into()],
- }],
- ..good_def()
- };
- let errors = validate_structure(&def);
- assert!(errors.contains(&DefinitionError::UnknownDependency {
- phase: "only".into(),
- depends_on: "ghost".into(),
- }));
-}
-
-#[test]
-fn cycle_is_detected() {
- let def = WorkflowDefinition {
- phases: vec![
- WorkflowPhase {
- name: "a".into(),
- description: String::new(),
- agent_ids: vec!["researcher".into()],
- depends_on: vec!["b".into()],
- },
- WorkflowPhase {
- name: "b".into(),
- description: String::new(),
- agent_ids: vec!["researcher".into()],
- depends_on: vec!["a".into()],
- },
- ],
- ..good_def()
- };
- assert!(validate_structure(&def).contains(&DefinitionError::CyclicDependency));
-}
-
-#[test]
-fn duplicate_phase_names_do_not_report_false_cycle() {
- let def = WorkflowDefinition {
- phases: vec![
- WorkflowPhase {
- name: "a".into(),
- description: String::new(),
- agent_ids: vec!["researcher".into()],
- depends_on: vec![],
- },
- WorkflowPhase {
- name: "a".into(),
- description: String::new(),
- agent_ids: vec!["researcher".into()],
- depends_on: vec![],
- },
- ],
- ..good_def()
- };
- let errors = validate_structure(&def);
- assert!(errors.contains(&DefinitionError::DuplicatePhase { name: "a".into() }));
- assert!(
- !errors.contains(&DefinitionError::CyclicDependency),
- "duplicate names must not trip a false cycle: {errors:?}"
- );
-}
-
-#[test]
-fn zero_concurrency_is_rejected() {
- let def = WorkflowDefinition {
- default_concurrency: 0,
- max_children: 0,
- ..good_def()
- };
- assert!(
- validate_structure(&def).contains(&DefinitionError::InvalidConcurrency {
- default_concurrency: 0,
- max_children: 0,
- })
- );
-}
-
-#[test]
-fn list_definitions_returns_builtins() {
- let resp = list_definitions();
- assert_eq!(resp.count, 1);
- assert_eq!(resp.definitions[0].id, PARALLEL_RESEARCH_ID);
-}
diff --git a/crates/openhuman-core/src/agent_runs/workflow_runs/schemas.rs b/crates/openhuman-core/src/agent_runs/workflow_runs/schemas.rs
deleted file mode 100644
index 32a58d37ea..0000000000
--- a/crates/openhuman-core/src/agent_runs/workflow_runs/schemas.rs
+++ /dev/null
@@ -1,330 +0,0 @@
-//! Controller schemas + JSON-RPC dispatchers for durable workflow runs.
-//!
-//! Read surface (PR1): list builtin definitions, list durable runs, get a run
-//! by id. Execution surface (PR2): start / stop / resume, delegating to the
-//! the workflow phase scheduler. Namespace `workflow_run` — distinct from
-//! the existing `workflows` domain (SKILL.md/WORKFLOW.md discovery).
-
-use crate::core::runtime::DispatchCtx;
-use serde_json::{Map, Value};
-
-use crate::core::all::{ControllerFuture, RegisteredController};
-use crate::core::Outcome;
-use crate::core::{ControllerSchema, FieldSchema, TypeSchema};
-use tinyagents_session::run_ledger::WorkflowRunListRequest;
-
-/// Controller schemas exposed by the workflow-runs module.
-pub fn all_controller_schemas() -> Vec<ControllerSchema> {
- vec![
- schema_for("workflow_run_list_definitions"),
- schema_for("workflow_run_list"),
- schema_for("workflow_run_get"),
- schema_for("workflow_run_start"),
- schema_for("workflow_run_stop"),
- schema_for("workflow_run_resume"),
- ]
-}
-
-/// Registered controllers (schema + handler) for workflow runs.
-pub fn all_registered_controllers() -> Vec<RegisteredController> {
- vec![
- RegisteredController {
- schema: schema_for("workflow_run_list_definitions"),
- handler: handle_list_definitions,
- },
- RegisteredController {
- schema: schema_for("workflow_run_list"),
- handler: handle_list,
- },
- RegisteredController {
- schema: schema_for("workflow_run_get"),
- handler: handle_get,
- },
- RegisteredController {
- schema: schema_for("workflow_run_start"),
- handler: handle_start,
- },
- RegisteredController {
- schema: schema_for("workflow_run_stop"),
- handler: handle_stop,
- },
- RegisteredController {
- schema: schema_for("workflow_run_resume"),
- handler: handle_resume,
- },
- ]
-}
-
-fn schema_for(function: &str) -> ControllerSchema {
- match function {
- "workflow_run_list_definitions" => ControllerSchema {
- namespace: "workflow_run",
- function: "list_definitions",
- description: "List available declarative workflow definitions (builtins).",
- inputs: vec![],
- outputs: vec![json_output(
- "result",
- "WorkflowDefinitionListResponse with definitions and count.",
- )],
- },
- "workflow_run_list" => ControllerSchema {
- namespace: "workflow_run",
- function: "list",
- description: "List durable workflow runs with optional filters and pagination.",
- inputs: vec![
- optional_str("definitionId", "Filter by workflow definition id."),
- optional_str("status", "Filter by run status."),
- optional_str("parentThreadId", "Filter by parent thread id."),
- optional_u64("limit", "Max runs to return (default 50, max 500)."),
- optional_u64("offset", "Pagination offset."),
- ],
- outputs: vec![json_output(
- "result",
- "WorkflowRunListResponse with runs array and count.",
- )],
- },
- "workflow_run_get" => ControllerSchema {
- namespace: "workflow_run",
- function: "get",
- description: "Get a durable workflow run by id.",
- inputs: vec![required_str("id", "Workflow run id.")],
- outputs: vec![json_output("workflowRun", "WorkflowRun payload or null.")],
- },
- "workflow_run_start" => ControllerSchema {
- namespace: "workflow_run",
- function: "start",
- description: "Start a workflow run from a definition id; returns the created \
- Running run. Execution proceeds asynchronously — poll \
- workflow_run_get for progress.",
- inputs: vec![
- required_str("definitionId", "Workflow definition id to run."),
- optional_json("input", "Run input (e.g. { \"question\": \"...\" })."),
- optional_str("parentThreadId", "Originating thread id, for lineage."),
- ],
- outputs: vec![json_output(
- "workflowRun",
- "The created WorkflowRun (status running).",
- )],
- },
- "workflow_run_stop" => ControllerSchema {
- namespace: "workflow_run",
- function: "stop",
- description: "Stop a running workflow after its current phase; marks the run \
- interrupted and aborts in-flight child agents.",
- inputs: vec![required_str("id", "Workflow run id.")],
- outputs: vec![json_output(
- "workflowRun",
- "Updated WorkflowRun payload or null.",
- )],
- },
- "workflow_run_resume" => ControllerSchema {
- namespace: "workflow_run",
- function: "resume",
- description: "Resume an interrupted workflow run, skipping phases already \
- completed and continuing from the first incomplete phase.",
- inputs: vec![required_str("id", "Workflow run id.")],
- outputs: vec![json_output(
- "workflowRun",
- "The resumed WorkflowRun (status running).",
- )],
- },
- other => unreachable!("unknown workflow_run schema: {other}"),
- }
-}
-
-fn handle_list_definitions(_ctx: DispatchCtx, _params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let cid = new_correlation_id();
- log::debug!(target: "workflow_run_rpc", "[workflow_run_rpc][{cid}] list_definitions.entry");
- let response = super::ops::list_definitions();
- log::debug!(target: "workflow_run_rpc", "[workflow_run_rpc][{cid}] list_definitions.success count={}", response.count);
- to_json(response)
- })
-}
-
-fn handle_list(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let cid = new_correlation_id();
- log::debug!(target: "workflow_run_rpc", "[workflow_run_rpc][{cid}] list.entry");
- let config = ctx.load_config().await.inspect_err(|err| {
- log::warn!(target: "workflow_run_rpc", "[workflow_run_rpc][{cid}] list.config_failed err={err}");
- })?;
- let request: WorkflowRunListRequest = if params.is_empty() {
- log::debug!(target: "workflow_run_rpc", "[workflow_run_rpc][{cid}] list.branch=default_request");
- WorkflowRunListRequest::default()
- } else {
- log::debug!(target: "workflow_run_rpc", "[workflow_run_rpc][{cid}] list.branch=parsed_params");
- serde_json::from_value(Value::Object(params)).map_err(|e| {
- let s = format!("invalid workflow run list params: {e}");
- log::warn!(target: "workflow_run_rpc", "[workflow_run_rpc][{cid}] list.bad_params err={s}");
- s
- })?
- };
- let response = super::ops::list_runs(&config, &request).map_err(|e| {
- let s = e.to_string();
- log::warn!(target: "workflow_run_rpc", "[workflow_run_rpc][{cid}] list.error err={s}");
- s
- })?;
- log::debug!(target: "workflow_run_rpc", "[workflow_run_rpc][{cid}] list.success count={}", response.count);
- to_json(response)
- })
-}
-
-fn handle_get(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let cid = new_correlation_id();
- log::debug!(target: "workflow_run_rpc", "[workflow_run_rpc][{cid}] get.entry");
- let config = ctx.load_config().await.inspect_err(|err| {
- log::warn!(target: "workflow_run_rpc", "[workflow_run_rpc][{cid}] get.config_failed err={err}");
- })?;
- let id = params
- .get("id")
- .and_then(|v| v.as_str())
- .ok_or_else(|| "missing required param: id".to_string())?;
- log::debug!(target: "workflow_run_rpc", "[workflow_run_rpc][{cid}] get.id={id}");
- let run = super::ops::get_run(&config, id).map_err(|e| {
- let s = e.to_string();
- log::warn!(target: "workflow_run_rpc", "[workflow_run_rpc][{cid}] get.error id={id} err={s}");
- s
- })?;
- log::debug!(target: "workflow_run_rpc", "[workflow_run_rpc][{cid}] get.success id={id} found={}", run.is_some());
- to_json(serde_json::json!({ "workflowRun": run }))
- })
-}
-
-fn handle_start(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let cid = new_correlation_id();
- log::debug!(target: "workflow_run_rpc", "[workflow_run_rpc][{cid}] start.entry");
- let config = ctx.load_config().await.inspect_err(|err| {
- log::warn!(target: "workflow_run_rpc", "[workflow_run_rpc][{cid}] start.config_failed err={err}");
- })?;
- let definition_id = params
- .get("definitionId")
- .and_then(|v| v.as_str())
- .ok_or_else(|| "missing required param: definitionId".to_string())?
- .to_string();
- let input = params.get("input").cloned().unwrap_or(Value::Null);
- let parent_thread_id = params
- .get("parentThreadId")
- .and_then(|v| v.as_str())
- .map(str::to_string);
- log::debug!(target: "workflow_run_rpc", "[workflow_run_rpc][{cid}] start.definition={definition_id}");
- let run = super::start_workflow_run(
- &ctx,
- &config,
- &definition_id,
- input,
- parent_thread_id,
- )
- .await
- .map_err(|e| {
- let s = e.to_string();
- log::warn!(target: "workflow_run_rpc", "[workflow_run_rpc][{cid}] start.error err={s}");
- s
- })?;
- log::debug!(target: "workflow_run_rpc", "[workflow_run_rpc][{cid}] start.success id={}", run.id);
- to_json(serde_json::json!({ "workflowRun": run }))
- })
-}
-
-fn handle_stop(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let cid = new_correlation_id();
- log::debug!(target: "workflow_run_rpc", "[workflow_run_rpc][{cid}] stop.entry");
- let config = ctx.load_config().await.inspect_err(|err| {
- log::warn!(target: "workflow_run_rpc", "[workflow_run_rpc][{cid}] stop.config_failed err={err}");
- })?;
- let id = params
- .get("id")
- .and_then(|v| v.as_str())
- .ok_or_else(|| "missing required param: id".to_string())?;
- log::debug!(target: "workflow_run_rpc", "[workflow_run_rpc][{cid}] stop.id={id}");
- let run = super::stop_workflow_run(&config, id).await.map_err(|e| {
- let s = e.to_string();
- log::warn!(target: "workflow_run_rpc", "[workflow_run_rpc][{cid}] stop.error id={id} err={s}");
- s
- })?;
- log::debug!(target: "workflow_run_rpc", "[workflow_run_rpc][{cid}] stop.success id={id} found={}", run.is_some());
- to_json(serde_json::json!({ "workflowRun": run }))
- })
-}
-
-fn handle_resume(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let cid = new_correlation_id();
- log::debug!(target: "workflow_run_rpc", "[workflow_run_rpc][{cid}] resume.entry");
- let config = ctx.load_config().await.inspect_err(|err| {
- log::warn!(target: "workflow_run_rpc", "[workflow_run_rpc][{cid}] resume.config_failed err={err}");
- })?;
- let id = params
- .get("id")
- .and_then(|v| v.as_str())
- .ok_or_else(|| "missing required param: id".to_string())?;
- log::debug!(target: "workflow_run_rpc", "[workflow_run_rpc][{cid}] resume.id={id}");
- let run = super::resume_workflow_run(&ctx, &config, id).await.map_err(|e| {
- let s = e.to_string();
- log::warn!(target: "workflow_run_rpc", "[workflow_run_rpc][{cid}] resume.error id={id} err={s}");
- s
- })?;
- log::debug!(target: "workflow_run_rpc", "[workflow_run_rpc][{cid}] resume.success id={}", run.id);
- to_json(serde_json::json!({ "workflowRun": run }))
- })
-}
-
-fn to_json<T: serde::Serialize>(value: T) -> Result<Value, String> {
- Outcome::new(value, vec![]).into_cli_compatible_json()
-}
-
-fn new_correlation_id() -> String {
- uuid::Uuid::new_v4().simple().to_string()[..8].to_string()
-}
-
-fn required_str(name: &'static str, comment: &'static str) -> FieldSchema {
- FieldSchema {
- name,
- ty: TypeSchema::String,
- comment,
- required: true,
- }
-}
-
-fn optional_str(name: &'static str, comment: &'static str) -> FieldSchema {
- FieldSchema {
- name,
- ty: TypeSchema::Option(Box::new(TypeSchema::String)),
- comment,
- required: false,
- }
-}
-
-fn optional_u64(name: &'static str, comment: &'static str) -> FieldSchema {
- FieldSchema {
- name,
- ty: TypeSchema::Option(Box::new(TypeSchema::U64)),
- comment,
- required: false,
- }
-}
-
-fn optional_json(name: &'static str, comment: &'static str) -> FieldSchema {
- FieldSchema {
- name,
- ty: TypeSchema::Option(Box::new(TypeSchema::Json)),
- comment,
- required: false,
- }
-}
-
-fn json_output(name: &'static str, comment: &'static str) -> FieldSchema {
- FieldSchema {
- name,
- ty: TypeSchema::Json,
- comment,
- required: true,
- }
-}
-
-#[cfg(test)]
-#[path = "schemas_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/agent_runs/workflow_runs/schemas_tests.rs b/crates/openhuman-core/src/agent_runs/workflow_runs/schemas_tests.rs
deleted file mode 100644
index 59d195efb4..0000000000
--- a/crates/openhuman-core/src/agent_runs/workflow_runs/schemas_tests.rs
+++ /dev/null
@@ -1,18 +0,0 @@
-use super::*;
-
-#[test]
-fn registered_controllers_match_schemas() {
- let schemas = all_controller_schemas();
- let registered = all_registered_controllers();
- assert_eq!(schemas.len(), registered.len());
- assert_eq!(
- schemas.len(),
- 6,
- "expected 3 read + 3 execution controllers"
- );
- assert!(schemas.iter().all(|s| s.namespace == "workflow_run"));
- assert_eq!(schema_for("workflow_run_get").function, "get");
- assert_eq!(schema_for("workflow_run_start").function, "start");
- assert_eq!(schema_for("workflow_run_stop").function, "stop");
- assert_eq!(schema_for("workflow_run_resume").function, "resume");
-}