Skip to content

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

refactor(agent): consume generic team orchestration

Steven Enamakel30857c13a8e2
diff --git a/.sdd-progress.md b/.sdd-progress.md
index 0f5d6734b8..b329ecefb7 100644
--- a/.sdd-progress.md
+++ b/.sdd-progress.md
@@ -12,6 +12,19 @@ in progress. They require direct imports with no compatibility shims and preserv
OpenHuman policy/security, persistence-root wiring, BUS/progress/RPC projection,
and concrete execution adapters.
+Orchestration O1-O2: complete locally, pending independent review and paired
+commits. `tinyagents-orchestration` is now a correctly spelled default workspace
+member with a tested one-way dependency gate and no OpenHuman dependency. It
+owns the neutral `TeamLedger`/`TeamWorker` seams, `SessionTeamLedger`,
+dependency-aware `TeamService`, claim selection, and generic member completion
+graph. OpenHuman's agent-team controllers, runtime, and topology import that
+crate directly; the prior local `types`, `ops`, and `graph` modules and their
+facades are deleted. OpenHuman retains its root-parent context, subagent
+execution, message delivery/reconciliation, persistence-root selection and RPC
+schemas. `cargo test -p tinyagents-orchestration` (8 tests), metadata, and
+`cargo check -p openhuman` pass. O3-O6 remain: workflow types/scheduler,
+workflow execution/resume, host workflow adapters, and parallel/worktree cleanup.
+
Session extraction S1-S4: in progress. `tinyagents-session::transcript` owns
the neutral append-only JSONL codec, paths, display/model readers, metadata,
history and locator interfaces. Its public history API now stays entirely on
diff --git a/Cargo.lock b/Cargo.lock
index 24f5deeeff..1af499530a 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -4154,6 +4154,7 @@ dependencies = [
"tinyagents-graph",
"tinyagents-harness",
"tinyagents-language",
+ "tinyagents-orchestration",
"tinyagents-registry",
"tinyagents-session",
"tinybus",
@@ -6510,6 +6511,22 @@ dependencies = [
"tinyagents-harness",
]
+[[package]]
+name = "tinyagents-orchestration"
+version = "2.1.2"
+dependencies = [
+ "anyhow",
+ "async-trait",
+ "chrono",
+ "serde",
+ "serde_json",
+ "tinyagents-graph",
+ "tinyagents-harness",
+ "tinyagents-session",
+ "tokio",
+ "uuid",
+]
+
[[package]]
name = "tinyagents-registry"
version = "2.1.2"
diff --git a/crates/openhuman-core/Cargo.toml b/crates/openhuman-core/Cargo.toml
index bcb47010c8..525ae1a98f 100644
--- a/crates/openhuman-core/Cargo.toml
+++ b/crates/openhuman-core/Cargo.toml
@@ -416,6 +416,7 @@ tinyagents-graph = { path = "../../vendor/tinyagents/crates/tinyagents-graph", f
tinyagents-language = { path = "../../vendor/tinyagents/crates/tinyagents-language" }
tinyagents-registry = { path = "../../vendor/tinyagents/crates/tinyagents-registry" }
tinyagents-session = { path = "../../vendor/tinyagents/crates/tinyagents-session" }
+tinyagents-orchestration = { path = "../../vendor/tinyagents/crates/tinyagents-orchestration" }
tinyinference-core = { path = "../../vendor/tinyagents/vendor/tinyinference/crates/tinyinference-core" }
tinyinference-embeddings = { path = "../../vendor/tinyagents/vendor/tinyinference/crates/tinyinference-embeddings" }
tinyinference-llm = { path = "../../vendor/tinyagents/vendor/tinyinference/crates/tinyinference-llm" }
diff --git a/crates/openhuman-core/src/agent/orchestration/agent_teams/graph.rs b/crates/openhuman-core/src/agent/orchestration/agent_teams/graph.rs
deleted file mode 100644
index b098802165..0000000000
--- a/crates/openhuman-core/src/agent/orchestration/agent_teams/graph.rs
+++ /dev/null
@@ -1,207 +0,0 @@
-//! Team-member execution as a conditional-routing `tinyagents` graph (#4249, B2).
-//!
-//! This is the `agent_teams` folder's `graph.rs` per the per-folder graph
-//! convention: the folder's tinyagents graph definition (member-run state
-//! machine) lives here; `runtime.rs` drives it.
-//!
-//! A teammate's live run is a small state machine: **execute** the worker
-//! sub-agent, then route on its terminal outcome to **complete** (quality-gate +
-//! idle) or **fail** (release + idle + record), joining at a single **done**
-//! finish node. Historically this was a hand-rolled `match` in
-//! [`super::runtime::drive_member`]; here it is a real `tinyagents`
-//! [`CompiledGraph`] with command-routing:
-//!
-//! ```text
-//! ┌─ complete ─┐
-//! execute ──►┤ ├─► done (finish)
-//! └─ fail ─────┘
-//! ```
-//!
-//! The worker run and the two reconciliation effects are **injected** as
-//! closures so the graph mechanics (conditional routing + the engine-error
-//! propagation contract) are unit-testable with trivial stubs while production
-//! passes the real `spawn_agent`/`wait_agents` + run-ledger writes.
-//!
-//! Error contract (preserved from the legacy `drive_member`): `run_worker`
-//! returns `Err` only for engine-internal failures (spawn/wait) — those
-//! propagate out of the graph so the caller releases the task and idles the
-//! member. A worker that *ran* but did not complete is a normal `Failed`
-//! outcome handled by `on_failed`, which returns `Ok`.
-
-use std::future::Future;
-use std::sync::Arc;
-
-use tinyagents_graph::export::GraphTopology;
-use tinyagents_graph::{
- ClosureStateReducer, Command, CompiledGraph, GraphBuilder, NodeContext, NodeResult,
-};
-
-use crate::agent::tinyagents::observability::GraphTracingSink;
-
-/// Lift an injected effect's `anyhow` error into the graph's error type so it
-/// fails the run (and propagates back out via [`run_member_execution_graph`]).
-fn graph_err(e: anyhow::Error) -> tinyagents_harness::TinyAgentsError {
- tinyagents_harness::TinyAgentsError::Graph(e.to_string())
-}
-
-/// Terminal classification of a teammate worker run, produced by the `execute`
-/// node and used to route to `complete` or `fail`.
-pub(super) enum MemberOutcome {
- /// The worker completed; `output` is its result summary (completion
- /// evidence).
- Completed { output: String },
- /// The worker ran but did not complete (failed / cancelled / closed /
- /// defensively, non-terminal); `reason` explains why.
- Failed { reason: String },
-}
-
-/// Typed state threaded through the member graph: carries the routed payload
-/// (worker output on the complete path, failure reason on the fail path) so the
-/// terminal node can run the matching reconciliation.
-#[derive(Clone, Default)]
-struct MemberState {
- payload: Option<String>,
-}
-
-/// Reducer update emitted by the member graph nodes.
-enum MemberUpdate {
- /// Store the routed payload (output or reason).
- Payload(String),
- /// Terminal node fired; no state change.
- Noop,
-}
-
-/// Drive a team member's execution on the conditional-routing graph above.
-///
-/// Returns `Ok(())` once the member reached a reconciled terminal node, or `Err`
-/// when `run_worker` (or a reconciliation closure) failed with an
-/// engine-internal error — the caller maps that to release-task + idle-member.
-pub(super) async fn run_member_execution_graph<W, WF, C, CF, F, FF>(
- label: &str,
- run_worker: W,
- on_complete: C,
- on_failed: F,
-) -> anyhow::Result<()>
-where
- W: Fn() -> WF + Clone + Send + Sync + 'static,
- WF: Future<Output = anyhow::Result<MemberOutcome>> + Send + 'static,
- C: Fn(String) -> CF + Clone + Send + Sync + 'static,
- CF: Future<Output = anyhow::Result<()>> + Send + 'static,
- F: Fn(String) -> FF + Clone + Send + Sync + 'static,
- FF: Future<Output = anyhow::Result<()>> + Send + 'static,
-{
- let graph = build_member_graph(run_worker, on_complete, on_failed)?
- .with_event_sink(Arc::new(GraphTracingSink::new(label.to_string())));
-
- tracing::debug!(
- target: "orchestration",
- label,
- "[orchestration] driving team member execution on tinyagents graph"
- );
-
- graph
- .run(MemberState::default())
- .await
- .map_err(|e| anyhow::anyhow!("member graph run failed: {e}"))?;
- Ok(())
-}
-
-/// Build (but do not run) the member-execution `CompiledGraph`. Shared by
-/// [`run_member_execution_graph`] and [`member_graph_topology`] so the graph's
-/// structure has one definition.
-fn build_member_graph<W, WF, C, CF, F, FF>(
- run_worker: W,
- on_complete: C,
- on_failed: F,
-) -> anyhow::Result<CompiledGraph<MemberState, MemberUpdate>>
-where
- W: Fn() -> WF + Clone + Send + Sync + 'static,
- WF: Future<Output = anyhow::Result<MemberOutcome>> + Send + 'static,
- C: Fn(String) -> CF + Clone + Send + Sync + 'static,
- CF: Future<Output = anyhow::Result<()>> + Send + 'static,
- F: Fn(String) -> FF + Clone + Send + Sync + 'static,
- FF: Future<Output = anyhow::Result<()>> + Send + 'static,
-{
- let mut builder = GraphBuilder::<MemberState, MemberUpdate>::new().set_reducer(
- ClosureStateReducer::new(|mut s: MemberState, u: MemberUpdate| {
- if let MemberUpdate::Payload(p) = u {
- s.payload = Some(p);
- }
- Ok(s)
- }),
- );
-
- // `execute`: run the worker, classify its outcome, and route accordingly.
- builder = builder.add_node("execute", move |_s: MemberState, _c: NodeContext| {
- let run_worker = run_worker.clone();
- async move {
- match run_worker().await.map_err(graph_err)? {
- MemberOutcome::Completed { output } => Ok(NodeResult::Command(
- Command::default()
- .with_update(MemberUpdate::Payload(output))
- .with_goto(["complete"]),
- )),
- MemberOutcome::Failed { reason } => Ok(NodeResult::Command(
- Command::default()
- .with_update(MemberUpdate::Payload(reason))
- .with_goto(["fail"]),
- )),
- }
- }
- });
-
- // `complete`: quality-gate + idle via the injected reconciliation.
- builder = builder.add_node("complete", move |s: MemberState, _c: NodeContext| {
- let on_complete = on_complete.clone();
- async move {
- on_complete(s.payload.unwrap_or_default())
- .await
- .map_err(graph_err)?;
- Ok(NodeResult::Update(MemberUpdate::Noop))
- }
- });
-
- // `fail`: release + idle + record via the injected reconciliation.
- builder = builder.add_node("fail", move |s: MemberState, _c: NodeContext| {
- let on_failed = on_failed.clone();
- async move {
- on_failed(s.payload.unwrap_or_default())
- .await
- .map_err(graph_err)?;
- Ok(NodeResult::Update(MemberUpdate::Noop))
- }
- });
-
- let graph = builder
- .add_node("done", |_s: MemberState, _c: NodeContext| async move {
- Ok(NodeResult::Update(MemberUpdate::Noop))
- })
- .add_edge("complete", "done")
- .add_edge("fail", "done")
- .set_entry("execute")
- .mark_command_routing("execute")
- .set_finish("done")
- .compile()
- .map_err(|e| anyhow::anyhow!("member graph compile failed: {e}"))?;
- Ok(graph)
-}
-
-/// Structure-only [`GraphTopology`] of the member-execution graph for debug /
-/// inspection (issue #4249, Phase 4). Built with no-op stub closures — the
-/// topology exposes only node names, edges, and routing, never closure bodies.
-pub(crate) fn member_graph_topology() -> anyhow::Result<GraphTopology> {
- let graph = build_member_graph(
- || async {
- Ok(MemberOutcome::Completed {
- output: String::new(),
- })
- },
- |_: String| async { Ok(()) },
- |_: String| async { Ok(()) },
- )?;
- Ok(graph.topology())
-}
-
-#[cfg(test)]
-#[path = "graph_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/agent/orchestration/agent_teams/graph_tests.rs b/crates/openhuman-core/src/agent/orchestration/agent_teams/graph_tests.rs
deleted file mode 100644
index 4967ba5cf5..0000000000
--- a/crates/openhuman-core/src/agent/orchestration/agent_teams/graph_tests.rs
+++ /dev/null
@@ -1,87 +0,0 @@
-use super::*;
-use std::sync::atomic::{AtomicBool, Ordering};
-
-#[tokio::test]
-async fn completed_outcome_routes_to_complete() {
- let completed = Arc::new(AtomicBool::new(false));
- let failed = Arc::new(AtomicBool::new(false));
- let c = completed.clone();
- let f = failed.clone();
- run_member_execution_graph(
- "test:complete",
- || async {
- Ok(MemberOutcome::Completed {
- output: "ok".into(),
- })
- },
- move |out| {
- let c = c.clone();
- async move {
- assert_eq!(out, "ok");
- c.store(true, Ordering::SeqCst);
- Ok(())
- }
- },
- move |_reason| {
- let f = f.clone();
- async move {
- f.store(true, Ordering::SeqCst);
- Ok(())
- }
- },
- )
- .await
- .expect("graph runs");
- assert!(completed.load(Ordering::SeqCst), "complete path ran");
- assert!(!failed.load(Ordering::SeqCst), "fail path did not run");
-}
-
-#[tokio::test]
-async fn failed_outcome_routes_to_fail() {
- let completed = Arc::new(AtomicBool::new(false));
- let failed = Arc::new(AtomicBool::new(false));
- let c = completed.clone();
- let f = failed.clone();
- run_member_execution_graph(
- "test:fail",
- || async {
- Ok(MemberOutcome::Failed {
- reason: "boom".into(),
- })
- },
- move |_out| {
- let c = c.clone();
- async move {
- c.store(true, Ordering::SeqCst);
- Ok(())
- }
- },
- move |reason| {
- let f = f.clone();
- async move {
- assert_eq!(reason, "boom");
- f.store(true, Ordering::SeqCst);
- Ok(())
- }
- },
- )
- .await
- .expect("graph runs");
- assert!(failed.load(Ordering::SeqCst), "fail path ran");
- assert!(
- !completed.load(Ordering::SeqCst),
- "complete path did not run"
- );
-}
-
-#[tokio::test]
-async fn engine_error_from_worker_propagates() {
- let result = run_member_execution_graph(
- "test:err",
- || async { Err(anyhow::anyhow!("spawn failed")) },
- |_out| async { Ok(()) },
- |_reason| async { Ok(()) },
- )
- .await;
- assert!(result.is_err(), "worker engine error propagates out");
-}
diff --git a/crates/openhuman-core/src/agent/orchestration/agent_teams/mod.rs b/crates/openhuman-core/src/agent/orchestration/agent_teams/mod.rs
index de3ff3bc2a..aa11ba7340 100644
--- a/crates/openhuman-core/src/agent/orchestration/agent_teams/mod.rs
+++ b/crates/openhuman-core/src/agent/orchestration/agent_teams/mod.rs
@@ -22,20 +22,10 @@
//! Namespace note: `agent_team` is distinct from the existing `team` domain,
//! which manages backend org/team membership.
-mod graph;
-pub(crate) use graph::member_graph_topology;
-pub mod ops;
pub mod runtime;
mod schemas;
-pub mod types;
-
-pub use ops::{
- assign_task, claim_task, close_team, complete_task, create_team, get_team, list_messages,
- list_teams, message_member, shutdown_member, NewMember,
-};
pub use runtime::start_member_run;
pub use schemas::{
all_controller_schemas as all_agent_team_controller_schemas,
all_registered_controllers as all_agent_team_registered_controllers,
};
-pub use types::{MemberShutdown, StartMemberOutcome, TeamError, TeamView};
diff --git a/crates/openhuman-core/src/agent/orchestration/agent_teams/ops.rs b/crates/openhuman-core/src/agent/orchestration/agent_teams/ops.rs
deleted file mode 100644
index 24b0191b6e..0000000000
--- a/crates/openhuman-core/src/agent/orchestration/agent_teams/ops.rs
+++ /dev/null
@@ -1,447 +0,0 @@
-//! Business logic for durable agent-team coordination (#3374).
-//!
-//! Thin orchestration over `tinyagents_session::run_ledger`: create teams + members,
-//! assign dependency-aware tasks (with self/unknown/cycle validation reusing
-//! the same Kahn's-algorithm shape as `workflow_runs`), atomically claim tasks,
-//! and exchange teammate messages. Messaging rides the run-ledger event stream
-//! (`run_id = team_id`, `event_type = "team_message"`) — no new message table.
-
-use std::collections::HashSet;
-
-use anyhow::{anyhow, Result};
-use chrono::Utc;
-use serde_json::json;
-use uuid::Uuid;
-
-use crate::config::Config;
-use tinyagents_graph::dag::{has_cycle, DagNode};
-use tinyagents_session::run_ledger::{
- self, AgentTeam, AgentTeamListRequest, AgentTeamListResponse, AgentTeamMemberStatus,
- AgentTeamMemberUpsert, AgentTeamStatus, AgentTeamTask, AgentTeamTaskStatus,
- AgentTeamTaskUpsert, AgentTeamUpsert, ClaimOutcome, CompletionOutcome, RunEvent,
- RunEventAppend, RunEventListRequest,
-};
-
-use super::types::{MemberShutdown, TeamError, TeamView};
-
-const LOG_PREFIX: &str = "[agent_team]";
-const TEAM_MESSAGE_EVENT: &str = "team_message";
-
-/// One member to create at team-creation time.
-#[derive(Debug, Clone)]
-pub struct NewMember {
- pub name: String,
- pub agent_id: Option<String>,
-}
-
-/// Create a team and its initial members.
-///
-/// Rejects duplicate member names ([`TeamError::DuplicateMemberName`]).
-pub fn create_team(
- config: &Config,
- lead_agent_id: &str,
- parent_thread_id: Option<&str>,
- summary: Option<&str>,
- members: &[NewMember],
-) -> Result<TeamView> {
- log::debug!(
- "{LOG_PREFIX} create_team.entry lead={lead_agent_id} members={}",
- members.len()
- );
-
- let mut seen: HashSet<&str> = HashSet::new();
- for member in members {
- if !seen.insert(member.name.as_str()) {
- return Err(anyhow!(TeamError::DuplicateMemberName {
- name: member.name.clone(),
- }));
- }
- }
-
- let team_id = format!("team-{}", Uuid::new_v4().simple());
- run_ledger::upsert_agent_team(
- &config.workspace_dir,
- AgentTeamUpsert {
- id: team_id.clone(),
- parent_thread_id: parent_thread_id.map(str::to_string),
- lead_agent_id: lead_agent_id.to_string(),
- status: AgentTeamStatus::Active,
- summary: summary.map(str::to_string),
- created_at: None,
- closed_at: None,
- },
- )?;
-
- for member in members {
- run_ledger::upsert_agent_team_member(
- &config.workspace_dir,
- AgentTeamMemberUpsert {
- id: format!("member-{}", Uuid::new_v4().simple()),
- team_id: team_id.clone(),
- name: member.name.clone(),
- agent_id: member.agent_id.clone(),
- member_status: AgentTeamMemberStatus::Pending,
- current_task_id: None,
- worker_thread_id: None,
- run_id: None,
- created_at: None,
- },
- )?;
- }
-
- let view = team_view(config, &team_id)?;
- log::debug!("{LOG_PREFIX} create_team.exit id={team_id}");
- Ok(view)
-}
-
-/// List teams (delegates to the run ledger).
-pub fn list_teams(
- config: &Config,
- request: &AgentTeamListRequest,
-) -> Result<AgentTeamListResponse> {
- log::debug!("{LOG_PREFIX} list_teams.entry status={:?}", request.status);
- Ok(run_ledger::list_agent_teams(
- &config.workspace_dir,
- request,
- )?)
-}
-
-/// Build the aggregate [`TeamView`] for a team id; `None` if the team is absent.
-pub fn get_team(config: &Config, team_id: &str) -> Result<Option<TeamView>> {
- log::debug!("{LOG_PREFIX} get_team.entry id={team_id}");
- match run_ledger::get_agent_team(&config.workspace_dir, team_id)? {
- Some(_) => Ok(Some(team_view(config, team_id)?)),
- None => {
- log::debug!("{LOG_PREFIX} get_team.exit id={team_id} found=false");
- Ok(None)
- }
- }
-}
-
-/// Assign a new dependency-aware task to a team.
-///
-/// Validates `depends_on`: rejects self-dependency, unknown dependency ids, and
-/// dependency cycles (Kahn's algorithm over the team's existing tasks plus the
-/// new one). An optional `owner_member_id` must reference a real member.
-#[allow(clippy::too_many_arguments)]
-pub fn assign_task(
- config: &Config,
- team_id: &str,
- title: &str,
- objective: Option<&str>,
- owner_member_id: Option<&str>,
- depends_on: &[String],
-) -> Result<AgentTeamTask> {
- log::debug!(
- "{LOG_PREFIX} assign_task.entry team={team_id} deps={}",
- depends_on.len()
- );
-
- let team = run_ledger::get_agent_team(&config.workspace_dir, team_id)?
- .ok_or_else(|| anyhow!("unknown team: {team_id}"))?;
- let _ = team;
-
- let existing = run_ledger::list_agent_team_tasks(&config.workspace_dir, team_id)?;
- let task_id = format!("task-{}", Uuid::new_v4().simple());
-
- if let Some(owner) = owner_member_id {
- let members = run_ledger::list_agent_team_members(&config.workspace_dir, team_id)?;
- if !members.iter().any(|m| m.id == owner) {
- return Err(anyhow!(TeamError::UnknownMember {
- member_id: owner.to_string(),
- }));
- }
- }
-
- validate_dependencies(&task_id, depends_on, &existing)?;
-
- let order_index = existing.len() as i64;
- let task = run_ledger::upsert_agent_team_task(
- &config.workspace_dir,
- AgentTeamTaskUpsert {
- id: task_id.clone(),
- team_id: team_id.to_string(),
- title: title.to_string(),
- objective: objective.map(str::to_string),
- status: AgentTeamTaskStatus::Todo,
- owner_member_id: owner_member_id.map(str::to_string),
- depends_on: depends_on.to_vec(),
- gate_status: None,
- gate_reason: None,
- evidence: vec![],
- source_run_id: None,
- order_index,
- created_at: None,
- },
- )?;
- log::debug!("{LOG_PREFIX} assign_task.exit team={team_id} task={task_id}");
- Ok(task)
-}
-
-/// Atomically claim a task for a member (delegates to the run-ledger CAS).
-pub fn claim_task(
- config: &Config,
- team_id: &str,
- task_id: &str,
- member_id: &str,
- claim_token: &str,
-) -> Result<ClaimOutcome> {
- log::debug!("{LOG_PREFIX} claim_task.entry team={team_id} task={task_id} member={member_id}");
- let members = run_ledger::list_agent_team_members(&config.workspace_dir, team_id)?;
- if !members.iter().any(|m| m.id == member_id) {
- return Err(anyhow!(TeamError::UnknownMember {
- member_id: member_id.to_string(),
- }));
- }
- Ok(run_ledger::claim_agent_team_task(
- &config.workspace_dir,
- team_id,
- task_id,
- member_id,
- claim_token,
- )?)
-}
-
-/// Sentinel `from` value for a message that originates from the team lead / the
-/// human user rather than a teammate member. The UI send-composer uses this so a
-/// person can address a named teammate without being a member row themselves.
-pub const LEAD_SENDER: &str = "lead";
-
-/// Send a message from one member to another (or broadcast).
-///
-/// `from_member_id = None` marks a lead/user-originated message (stored with
-/// `from = "lead"`); `Some(id)` is a teammate-to-teammate message and must
-/// reference a real member. Persisted as a run-ledger event keyed by
-/// `run_id = team_id`, so the messaging stream reuses the durable event log with
-/// no new table.
-pub fn message_member(
- config: &Config,
- team_id: &str,
- from_member_id: Option<&str>,
- to_member_id: Option<&str>,
- content: &str,
- visibility: Option<&str>,
-) -> Result<RunEvent> {
- log::debug!(
- "{LOG_PREFIX} message_member.entry team={team_id} from={:?} to={:?}",
- from_member_id,
- to_member_id
- );
-
- // Reject unknown teams up front. A lead-origin broadcast (`from = None`,
- // `to = None`) skips both member checks below, so without this guard an
- // unknown `team_id` would still append an orphan `team_message` event to a
- // non-existent team's run ledger.
- if run_ledger::get_agent_team(&config.workspace_dir, team_id)?.is_none() {
- return Err(anyhow!("unknown team: {team_id}"));
- }
-
- let members = run_ledger::list_agent_team_members(&config.workspace_dir, team_id)?;
- if let Some(from) = from_member_id {
- if !members.iter().any(|m| m.id == from) {
- return Err(anyhow!(TeamError::UnknownMember {
- member_id: from.to_string(),
- }));
- }
- }
- if let Some(to) = to_member_id {
- if !members.iter().any(|m| m.id == to) {
- return Err(anyhow!(TeamError::UnknownMember {
- member_id: to.to_string(),
- }));
- }
- }
-
- let from_value = from_member_id.unwrap_or(LEAD_SENDER);
- let event = run_ledger::append_run_event(
- &config.workspace_dir,
- RunEventAppend {
- run_id: team_id.to_string(),
- event_type: TEAM_MESSAGE_EVENT.to_string(),
- payload: json!({
- "from": from_value,
- "to": to_member_id,
- "content": content,
- "visibility": visibility.unwrap_or("team"),
- }),
- },
- )?;
- log::debug!(
- "{LOG_PREFIX} message_member.exit team={team_id} sequence={}",
- event.sequence
- );
- Ok(event)
-}
-
-/// List the team's message events in sequence order.
-pub fn list_messages(config: &Config, team_id: &str, limit: Option<u32>) -> Result<Vec<RunEvent>> {
- log::debug!("{LOG_PREFIX} list_messages.entry team={team_id}");
- let response = run_ledger::list_recent_run_events(
- &config.workspace_dir,
- &RunEventListRequest {
- run_id: team_id.to_string(),
- after_sequence: None,
- limit,
- },
- )?;
- let messages: Vec<RunEvent> = response
- .events
- .into_iter()
- .filter(|e| e.event_type == TEAM_MESSAGE_EVENT)
- .collect();
- log::debug!(
- "{LOG_PREFIX} list_messages.exit team={team_id} count={}",
- messages.len()
- );
- Ok(messages)
-}
-
-/// Mark a team closed.
-pub fn close_team(config: &Config, team_id: &str, summary: Option<&str>) -> Result<AgentTeam> {
- log::debug!("{LOG_PREFIX} close_team.entry team={team_id}");
- let existing = run_ledger::get_agent_team(&config.workspace_dir, team_id)?
- .ok_or_else(|| anyhow!("unknown team: {team_id}"))?;
- let team = run_ledger::upsert_agent_team(
- &config.workspace_dir,
- AgentTeamUpsert {
- id: team_id.to_string(),
- parent_thread_id: existing.parent_thread_id.clone(),
- lead_agent_id: existing.lead_agent_id.clone(),
- status: AgentTeamStatus::Closed,
- summary: summary.map(str::to_string),
- created_at: Some(existing.created_at),
- closed_at: Some(Utc::now()),
- },
- )?;
- log::debug!("{LOG_PREFIX} close_team.exit team={team_id}");
- Ok(team)
-}
-
-/// Complete a claimed task, gating its transition to `done`.
-///
-/// Validates the completing member belongs to the team, then delegates to the
-/// run-ledger completion CAS, which enforces the quality gate (dependencies
-/// done, claimant owns the task, evidence present when `require_evidence`) and
-/// only flips the task to `done` when every invariant holds.
-pub fn complete_task(
- config: &Config,
- team_id: &str,
- task_id: &str,
- member_id: &str,
- evidence: &[String],
- require_evidence: bool,
-) -> Result<CompletionOutcome> {
- log::debug!(
- "{LOG_PREFIX} complete_task.entry team={team_id} task={task_id} member={member_id}"
- );
- let members = run_ledger::list_agent_team_members(&config.workspace_dir, team_id)?;
- if !members.iter().any(|m| m.id == member_id) {
- return Err(anyhow!(TeamError::UnknownMember {
- member_id: member_id.to_string(),
- }));
- }
- let outcome = run_ledger::complete_agent_team_task(
- &config.workspace_dir,
- team_id,
- task_id,
- member_id,
- evidence,
- require_evidence,
- )?;
- log::debug!("{LOG_PREFIX} complete_task.exit team={team_id} task={task_id}");
- Ok(outcome)
-}
-
-/// Stop a team member, releasing any task it was actively working on.
-///
-/// Unknown member ids surface as [`TeamError::UnknownMember`]; otherwise returns
-/// the stopped member plus the ids of tasks released back to `todo`.
-pub fn shutdown_member(config: &Config, team_id: &str, member_id: &str) -> Result<MemberShutdown> {
- log::debug!("{LOG_PREFIX} shutdown_member.entry team={team_id} member={member_id}");
- let (member, released_task_ids) =
- run_ledger::shutdown_agent_team_member(&config.workspace_dir, team_id, member_id)?
- .ok_or_else(|| {
- anyhow!(TeamError::UnknownMember {
- member_id: member_id.to_string(),
- })
- })?;
- log::debug!(
- "{LOG_PREFIX} shutdown_member.exit team={team_id} member={member_id} released={}",
- released_task_ids.len()
- );
- Ok(MemberShutdown {
- member,
- released_task_ids,
- })
-}
-
-fn team_view(config: &Config, team_id: &str) -> Result<TeamView> {
- let team = run_ledger::get_agent_team(&config.workspace_dir, team_id)?
- .ok_or_else(|| anyhow!("team missing after creation: {team_id}"))?;
- let members = run_ledger::list_agent_team_members(&config.workspace_dir, team_id)?;
- let tasks = run_ledger::list_agent_team_tasks(&config.workspace_dir, team_id)?;
- Ok(TeamView {
- team,
- members,
- tasks,
- })
-}
-
-/// Validate a new task's dependency edges against the team's existing tasks.
-///
-/// Rejects self-dependency, unknown dependency ids, and any edge that would
-/// introduce a cycle. The self and unknown checks stay here because they are
-/// scoped to the *new* task: a pre-existing task carrying a dangling edge is
-/// not this caller's fault and must not block the assignment. The cycle check
-/// delegates to `tinyagents_graph::dag`.
-fn validate_dependencies(
- new_task_id: &str,
- depends_on: &[String],
- existing: &[AgentTeamTask],
-) -> Result<()> {
- let known: HashSet<&str> = existing.iter().map(|t| t.id.as_str()).collect();
-
- for dep in depends_on {
- if dep == new_task_id {
- return Err(anyhow!(TeamError::SelfDependency {
- task_id: new_task_id.to_string(),
- }));
- }
- if !known.contains(dep.as_str()) {
- return Err(anyhow!(TeamError::UnknownDependency {
- depends_on: dep.clone(),
- }));
- }
- }
-
- if has_task_cycle(new_task_id, depends_on, existing) {
- return Err(anyhow!(TeamError::CyclicDependency));
- }
-
- Ok(())
-}
-
-/// Cycle check over the task dependency graph (existing tasks plus the
-/// candidate new task), delegating to `tinyagents_graph::dag::has_cycle`.
-///
-/// Edge `dep -> task` means `task` depends on `dep`. Edges pointing at unknown
-/// ids are ignored by the shared validator (they are rejected separately).
-fn has_task_cycle(
- new_task_id: &str,
- new_depends_on: &[String],
- existing: &[AgentTeamTask],
-) -> bool {
- let mut nodes: Vec<DagNode<'_>> = existing
- .iter()
- .map(|t| DagNode::new(t.id.as_str(), t.depends_on.iter().map(String::as_str)))
- .collect();
- nodes.push(DagNode::new(
- new_task_id,
- new_depends_on.iter().map(String::as_str),
- ));
- has_cycle(&nodes)
-}
-
-#[cfg(test)]
-#[path = "ops_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/agent/orchestration/agent_teams/ops_tests.rs b/crates/openhuman-core/src/agent/orchestration/agent_teams/ops_tests.rs
deleted file mode 100644
index 58fab15eea..0000000000
--- a/crates/openhuman-core/src/agent/orchestration/agent_teams/ops_tests.rs
+++ /dev/null
@@ -1,419 +0,0 @@
-use super::*;
-use tempfile::TempDir;
-
-fn test_config(dir: &TempDir) -> Config {
- let mut config = Config::default();
- config.workspace_dir = dir.path().to_path_buf();
- config.action_dir = dir.path().join("actions");
- config
-}
-
-fn team_err(err: anyhow::Error) -> TeamError {
- err.downcast::<TeamError>().expect("TeamError")
-}
-
-#[test]
-fn create_team_rejects_duplicate_member_names() {
- let dir = TempDir::new().unwrap();
- let config = test_config(&dir);
- let err = create_team(
- &config,
- "lead",
- None,
- None,
- &[
- NewMember {
- name: "alice".into(),
- agent_id: None,
- },
- NewMember {
- name: "alice".into(),
- agent_id: None,
- },
- ],
- )
- .unwrap_err();
- assert_eq!(
- team_err(err),
- TeamError::DuplicateMemberName {
- name: "alice".into()
- }
- );
-}
-
-#[test]
-fn assign_task_rejects_self_unknown_and_cycle() {
- let dir = TempDir::new().unwrap();
- let config = test_config(&dir);
- let view = create_team(
- &config,
- "lead",
- None,
- None,
- &[NewMember {
- name: "alice".into(),
- agent_id: None,
- }],
- )
- .unwrap();
- let team_id = view.team.id.clone();
-
- // Unknown dependency.
- let err =
- assign_task(&config, &team_id, "task one", None, None, &["ghost".into()]).unwrap_err();
- assert_eq!(
- team_err(err),
- TeamError::UnknownDependency {
- depends_on: "ghost".into()
- }
- );
-
- // Seed A, then B depends_on A — fine.
- let a = assign_task(&config, &team_id, "A", None, None, &[]).unwrap();
- let b = assign_task(&config, &team_id, "B", None, None, &[a.id.clone()]).unwrap();
-
- // No cycle: a fresh candidate depending on B is a plain extension of
- // the existing chain (A -> B -> C).
- let existing = run_ledger::list_agent_team_tasks(&config.workspace_dir, &team_id).unwrap();
- assert!(!has_task_cycle("C", &[b.id.clone()], &existing));
-
- // Cycle: `has_task_cycle` is exercised directly (rather than through
- // `assign_task`, which only ever creates new tasks and can never make
- // an existing one depend on something newer) with a synthetic fixture
- // list. Using ids distinct from every existing task matters here:
- // `tinyagents_graph::dag::has_cycle` deliberately processes only the
- // *first* declaration of a repeated id and ignores the rest (see its
- // doc comment on `DagIssue::DuplicateNode`), so reusing `a.id` for the
- // new candidate — as this test previously did — is silently ignored
- // by the crate rather than fabricating a cycle, and the assertion
- // that depended on the old host-side Kahn implementation's
- // duplicate-merging behaviour no longer holds. A three-node chain
- // with unique ids (x depends on z, y depends on x, and a new z
- // depending on y) closes a real x -> z -> y -> x loop without ever
- // repeating an id.
- let fixture_existing = vec![
- task_fixture(&team_id, "x", &["z"]),
- task_fixture(&team_id, "y", &["x"]),
- ];
- assert!(has_task_cycle("z", &["y".to_string()], &fixture_existing));
-}
-
-fn task_fixture(team_id: &str, id: &str, depends_on: &[&str]) -> AgentTeamTask {
- let now = Utc::now();
- AgentTeamTask {
- id: id.to_string(),
- team_id: team_id.to_string(),
- title: id.to_string(),
- objective: None,
- status: AgentTeamTaskStatus::Todo,
- owner_member_id: None,
- claimed_by_member_id: None,
- claim_token: None,
- depends_on: depends_on.iter().map(|d| d.to_string()).collect(),
- gate_status: "pending".to_string(),
- gate_reason: None,
- evidence: Vec::new(),
- source_run_id: None,
- order_index: 0,
- created_at: now,
- updated_at: now,
- }
-}
-
-#[test]
-fn self_dependency_is_rejected() {
- // Directly exercise validate_dependencies with a matching id.
- let err = validate_dependencies("task-self", &["task-self".into()], &[]).unwrap_err();
- assert_eq!(
- team_err(err),
- TeamError::SelfDependency {
- task_id: "task-self".into()
- }
- );
-}
-
-#[test]
-fn message_append_then_list_in_order() {
- let dir = TempDir::new().unwrap();
- let config = test_config(&dir);
- let view = create_team(
- &config,
- "lead",
- None,
- None,
- &[
- NewMember {
- name: "alice".into(),
- agent_id: None,
- },
- NewMember {
- name: "bob".into(),
- agent_id: None,
- },
- ],
- )
- .unwrap();
- let team_id = view.team.id.clone();
- let alice = view.members[0].id.clone();
- let bob = view.members[1].id.clone();
-
- message_member(&config, &team_id, Some(&alice), Some(&bob), "first", None).unwrap();
- message_member(&config, &team_id, Some(&bob), Some(&alice), "second", None).unwrap();
-
- let messages = list_messages(&config, &team_id, None).unwrap();
- assert_eq!(messages.len(), 2);
- assert_eq!(messages[0].sequence, 1);
- assert_eq!(messages[1].sequence, 2);
- assert_eq!(messages[0].payload["content"], "first");
- assert_eq!(messages[1].payload["content"], "second");
-}
-
-#[test]
-fn message_member_lead_origin_and_unknown_from() {
- let dir = TempDir::new().unwrap();
- let config = test_config(&dir);
- let (team_id, alice) = solo_team(&config, "alice");
-
- // Lead/user-originated message: from = None → stored as "lead", no
- // member validation on the sender.
- message_member(&config, &team_id, None, Some(&alice), "from the lead", None).unwrap();
- let messages = list_messages(&config, &team_id, None).unwrap();
- assert_eq!(messages.len(), 1);
- assert_eq!(messages[0].payload["from"], LEAD_SENDER);
- assert_eq!(messages[0].payload["to"], alice);
-
- // A non-None sender that is not a member is still rejected.
- let err =
- message_member(&config, &team_id, Some("ghost"), Some(&alice), "x", None).unwrap_err();
- assert_eq!(
- team_err(err),
- TeamError::UnknownMember {
- member_id: "ghost".into()
- }
- );
-}
-
-/// Create a single-member team and return `(team_id, member_id)`.
-fn solo_team(config: &Config, name: &str) -> (String, String) {
- let view = create_team(
- config,
- "lead",
- None,
- None,
- &[NewMember {
- name: name.into(),
- agent_id: None,
- }],
- )
- .unwrap();
- let member_id = view.members[0].id.clone();
- (view.team.id, member_id)
-}
-
-#[test]
-fn complete_task_gate_passes_and_marks_done() {
- let dir = TempDir::new().unwrap();
- let config = test_config(&dir);
- let (team_id, alice) = solo_team(&config, "alice");
-
- let task = assign_task(&config, &team_id, "ship it", None, None, &[]).unwrap();
- let claim = claim_task(&config, &team_id, &task.id, &alice, "tok-1").unwrap();
- assert!(matches!(claim, ClaimOutcome::Claimed(_)));
-
- let outcome = complete_task(
- &config,
- &team_id,
- &task.id,
- &alice,
- &["https://ci/run/1".to_string()],
- true,
- )
- .unwrap();
- match outcome {
- CompletionOutcome::Completed(done) => {
- assert_eq!(done.status, AgentTeamTaskStatus::Done);
- assert_eq!(done.gate_status, "passed");
- assert_eq!(done.gate_reason, None);
- assert_eq!(done.evidence, vec!["https://ci/run/1".to_string()]);
- }
- other => panic!("expected Completed, got {other:?}"),
- }
-}
-
-#[test]
-fn complete_task_requires_evidence_then_recovers() {
- let dir = TempDir::new().unwrap();
- let config = test_config(&dir);
- let (team_id, alice) = solo_team(&config, "alice");
-
- let task = assign_task(&config, &team_id, "ship it", None, None, &[]).unwrap();
- claim_task(&config, &team_id, &task.id, &alice, "tok-1").unwrap();
-
- // No evidence + require_evidence → gate fails, task stays in progress.
- let failed = complete_task(&config, &team_id, &task.id, &alice, &[], true).unwrap();
- match failed {
- CompletionOutcome::GateFailed { reasons } => {
- assert!(
- reasons.iter().any(|r| r.contains("evidence")),
- "{reasons:?}"
- );
- }
- other => panic!("expected GateFailed, got {other:?}"),
- }
- let mid = run_ledger::get_agent_team_task(&config.workspace_dir, &task.id)
- .unwrap()
- .unwrap();
- assert_eq!(mid.status, AgentTeamTaskStatus::InProgress);
- assert_eq!(mid.gate_status, "failed");
-
- // Retry with evidence → passes.
- let ok = complete_task(
- &config,
- &team_id,
- &task.id,
- &alice,
- &["proof".to_string()],
- true,
- )
- .unwrap();
- assert!(matches!(ok, CompletionOutcome::Completed(_)));
-}
-
-#[test]
-fn complete_task_is_not_double_completable() {
- let dir = TempDir::new().unwrap();
- let config = test_config(&dir);
- let (team_id, alice) = solo_team(&config, "alice");
-
- let task = assign_task(&config, &team_id, "ship it", None, None, &[]).unwrap();
- claim_task(&config, &team_id, &task.id, &alice, "tok-1").unwrap();
-
- let first = complete_task(&config, &team_id, &task.id, &alice, &[], false).unwrap();
- assert!(matches!(first, CompletionOutcome::Completed(_)));
-
- // A task that is already `done` is no longer in progress, so a second
- // completion is rejected (the `status = 'in_progress'` UPDATE guard makes
- // the CAS airtight even under a concurrent double-complete).
- let second = complete_task(&config, &team_id, &task.id, &alice, &[], false).unwrap();
- assert_eq!(second, CompletionOutcome::NotClaimed);
-}
-
-#[test]
-fn complete_task_rejects_non_claimant() {
- let dir = TempDir::new().unwrap();
- let config = test_config(&dir);
- let view = create_team(
- &config,
- "lead",
- None,
- None,
- &[
- NewMember {
- name: "alice".into(),
- agent_id: None,
- },
- NewMember {
- name: "bob".into(),
- agent_id: None,
- },
- ],
- )
- .unwrap();
- let team_id = view.team.id.clone();
- let alice = view.members[0].id.clone();
- let bob = view.members[1].id.clone();
-
- let task = assign_task(&config, &team_id, "ship it", None, None, &[]).unwrap();
- claim_task(&config, &team_id, &task.id, &alice, "tok-1").unwrap();
-
- // Bob is a member but not the claimant → NotClaimed.
- let outcome = complete_task(&config, &team_id, &task.id, &bob, &[], false).unwrap();
- assert_eq!(outcome, CompletionOutcome::NotClaimed);
-
- // Unknown member → typed error (not an outcome).
- let err = complete_task(&config, &team_id, &task.id, "ghost", &[], false).unwrap_err();
- assert_eq!(
- team_err(err),
- TeamError::UnknownMember {
- member_id: "ghost".into()
- }
- );
-}
-
-#[test]
-fn complete_task_owner_mismatch_fails_gate() {
- let dir = TempDir::new().unwrap();
- let config = test_config(&dir);
- let view = create_team(
- &config,
- "lead",
- None,
- None,
- &[
- NewMember {
- name: "alice".into(),
- agent_id: None,
- },
- NewMember {
- name: "bob".into(),
- agent_id: None,
- },
- ],
- )
- .unwrap();
- let team_id = view.team.id.clone();
- let alice = view.members[0].id.clone();
- let bob = view.members[1].id.clone();
-
- // Task owned by bob, but alice claims + tries to complete.
- let task = assign_task(&config, &team_id, "ship it", None, Some(&bob), &[]).unwrap();
- claim_task(&config, &team_id, &task.id, &alice, "tok-1").unwrap();
-
- let outcome = complete_task(&config, &team_id, &task.id, &alice, &[], false).unwrap();
- match outcome {
- CompletionOutcome::GateFailed { reasons } => {
- assert!(
- reasons.iter().any(|r| r.contains("owned by")),
- "{reasons:?}"
- );
- }
- other => panic!("expected GateFailed, got {other:?}"),
- }
-}
-
-#[test]
-fn shutdown_member_releases_in_progress_tasks() {
- let dir = TempDir::new().unwrap();
- let config = test_config(&dir);
- let (team_id, alice) = solo_team(&config, "alice");
-
- let task = assign_task(&config, &team_id, "ship it", None, None, &[]).unwrap();
- claim_task(&config, &team_id, &task.id, &alice, "tok-1").unwrap();
-
- let result = shutdown_member(&config, &team_id, &alice).unwrap();
- assert_eq!(result.released_task_ids, vec![task.id.clone()]);
- assert_eq!(result.member.member_status, AgentTeamMemberStatus::Stopped);
-
- // Task is back to todo and unclaimed → another teammate could claim it.
- let released = run_ledger::get_agent_team_task(&config.workspace_dir, &task.id)
- .unwrap()
- .unwrap();
- assert_eq!(released.status, AgentTeamTaskStatus::Todo);
- assert_eq!(released.claimed_by_member_id, None);
- assert_eq!(released.claim_token, None);
-}
-
-#[test]
-fn shutdown_member_unknown_errors() {
- let dir = TempDir::new().unwrap();
- let config = test_config(&dir);
- let (team_id, _alice) = solo_team(&config, "alice");
-
- let err = shutdown_member(&config, &team_id, "ghost").unwrap_err();
- assert_eq!(
- team_err(err),
- TeamError::UnknownMember {
- member_id: "ghost".into()
- }
- );
-}
diff --git a/crates/openhuman-core/src/agent/orchestration/agent_teams/runtime.rs b/crates/openhuman-core/src/agent/orchestration/agent_teams/runtime.rs
index 26159d7797..d04c23b5b3 100644
--- a/crates/openhuman-core/src/agent/orchestration/agent_teams/runtime.rs
+++ b/crates/openhuman-core/src/agent/orchestration/agent_teams/runtime.rs
@@ -36,11 +36,11 @@ use crate::agent::orchestration::{
};
use crate::config::Config;
use tinyagents_session::run_ledger::{
- self, AgentTeamMemberStatus, AgentTeamTask, AgentTeamTaskStatus, ClaimOutcome, RunEvent,
+ self, AgentTeamMemberStatus, AgentTeamTask, ClaimOutcome, RunEvent,
RunEventAppend, RunEventListRequest,
};
-use super::types::{StartMemberOutcome, TeamError};
+use tinyagents_orchestration::teams::{claimable_task, run_member_graph, MemberOutcome, TeamError};
const LOG_TARGET: &str = "agent_team_runtime";
/// Fallback worker archetype when a member carries no explicit `agent_id`.
@@ -59,6 +59,26 @@ const EVENT_PAGE_SIZE: u32 = 1000;
/// Cap on how much worker output is captured as evidence (UTF-8 safe).
const EVIDENCE_MAX_CHARS: usize = 280;
+/// Host-side result of accepting a request to run a durable team member.
+///
+/// Actual worker execution remains OpenHuman-specific because it creates a
+/// root parent context, selects a model and tools, and emits host progress.
+#[derive(Debug, Clone, PartialEq, serde::Serialize)]
+#[serde(rename_all = "camelCase", tag = "kind")]
+pub enum StartMemberOutcome {
+ Started {
+ run_id: String,
+ task: Box<AgentTeamTask>,
+ },
+ Blocked {
+ unmet: Vec<String>,
+ },
+ AlreadyClaimed,
+ AlreadyActive,
+ NoClaimableTask,
+ UnknownTask,
+}
+
/// Start a live run for a team member. **Non-blocking.**
///
/// Resolves a target task (the explicit `task_id`, else the member's next
@@ -112,7 +132,7 @@ pub async fn start_member_run(
Some(t) => t.clone(),
None => return Ok(StartMemberOutcome::UnknownTask),
},
- None => match pick_claimable(&tasks, member_id) {
+ None => match claimable_task(&tasks, member_id) {
Some(t) => t.clone(),
None => return Ok(StartMemberOutcome::NoClaimableTask),
},
@@ -299,21 +319,21 @@ async fn drive_member(
.ok_or_else(|| anyhow!("worker snapshot missing after wait"))?;
Ok(match snapshot.status {
- OrchestrationTaskStatus::Completed => super::graph::MemberOutcome::Completed {
+ OrchestrationTaskStatus::Completed => MemberOutcome::Completed {
output: snapshot.result_summary.unwrap_or_default(),
},
OrchestrationTaskStatus::Failed
| OrchestrationTaskStatus::Cancelled
| OrchestrationTaskStatus::CancelRequested
| OrchestrationTaskStatus::TimedOut
- | OrchestrationTaskStatus::Abandoned => super::graph::MemberOutcome::Failed {
+ | OrchestrationTaskStatus::Abandoned => MemberOutcome::Failed {
reason: snapshot
.error
.unwrap_or_else(|| "worker ended without completing".to_string()),
},
// `wait_agents` with no timeout only returns on terminal
// status, so this is purely defensive — treat as a failure.
- other => super::graph::MemberOutcome::Failed {
+ other => MemberOutcome::Failed {
reason: format!("worker returned non-terminal status {other:?}"),
},
})
@@ -397,35 +417,7 @@ async fn drive_member(
}
};
- super::graph::run_member_execution_graph(
- &format!("team:{team_id}:{member_id}"),
- run_worker,
- on_complete,
- on_failed,
- )
- .await
-}
-
-/// Pick the member's next claimable task: the first (by order) task that is
-/// `todo`/`ready`, unclaimed, owned by no-one or by this member, and whose
-/// dependencies are all `done`.
-fn pick_claimable<'a>(tasks: &'a [AgentTeamTask], member_id: &str) -> Option<&'a AgentTeamTask> {
- let done: std::collections::HashSet<&str> = tasks
- .iter()
- .filter(|t| t.status == AgentTeamTaskStatus::Done)
- .map(|t| t.id.as_str())
- .collect();
- tasks.iter().find(|t| {
- matches!(
- t.status,
- AgentTeamTaskStatus::Todo | AgentTeamTaskStatus::Ready
- ) && t.claimed_by_member_id.is_none()
- && t.owner_member_id
- .as_deref()
- .map(|o| o == member_id)
- .unwrap_or(true)
- && t.depends_on.iter().all(|d| done.contains(d.as_str()))
- })
+ run_member_graph(run_worker, on_complete, on_failed).await
}
/// Compose the worker prompt from the task + any pending messages addressed to
diff --git a/crates/openhuman-core/src/agent/orchestration/agent_teams/runtime_tests.rs b/crates/openhuman-core/src/agent/orchestration/agent_teams/runtime_tests.rs
index f3dcaf67f1..8db2f34032 100644
--- a/crates/openhuman-core/src/agent/orchestration/agent_teams/runtime_tests.rs
+++ b/crates/openhuman-core/src/agent/orchestration/agent_teams/runtime_tests.rs
@@ -20,6 +20,7 @@ use crate::agent::harness::fork_context::{with_parent_context, ParentExecutionCo
use crate::agent::prompts::ToolCallFormat;
use crate::config::{AgentConfig, Config};
use crate::memory::{Memory, MemoryCategory, MemoryEntry, NamespaceSummary, RecallOpts};
+use tinyagents_orchestration::teams::{SessionTeamLedger, TeamService};
use tinyagents_session::run_ledger::{
self, AgentTeamMemberStatus, AgentTeamMemberUpsert, AgentTeamStatus, AgentTeamTaskStatus,
AgentTeamTaskUpsert, AgentTeamUpsert,
@@ -146,6 +147,10 @@ fn test_config() -> (tempfile::TempDir, Config) {
(dir, config)
}
+fn team_service(config: &Config) -> TeamService<SessionTeamLedger> {
+ TeamService::new(SessionTeamLedger::new(config.workspace_dir.clone()))
+}
+
fn seed_team(config: &Config, team_id: &str) {
run_ledger::upsert_agent_team(
&config.workspace_dir,
@@ -598,7 +603,8 @@ fn pick_claimable_respects_deps_ownership_and_claim() {
updated_at: chrono::Utc::now(),
},
];
- let picked = pick_claimable(&tasks, "m1").expect("c is claimable");
+ let picked =
+ tinyagents_orchestration::teams::claimable_task(&tasks, "m1").expect("c is claimable");
assert_eq!(picked.id, "c");
}
@@ -608,11 +614,16 @@ fn deliver_pending_messages_injects_then_watermarks() {
seed_team(&config, "team-1");
seed_member(&config, "team-1", "m1", None);
// Direct to m1, a broadcast, and one addressed elsewhere.
- super::super::ops::message_member(&config, "team-1", None, Some("m1"), "hello m1", None)
+ team_service(&config)
+ .message_member("team-1", None, Some("m1"), "hello m1", None)
+ .unwrap();
+ team_service(&config)
+ .message_member("team-1", None, None, "broadcast", None)
.unwrap();
- super::super::ops::message_member(&config, "team-1", None, None, "broadcast", None).unwrap();
seed_member(&config, "team-1", "m2", None);
- super::super::ops::message_member(&config, "team-1", None, Some("m2"), "for m2", None).unwrap();
+ team_service(&config)
+ .message_member("team-1", None, Some("m2"), "for m2", None)
+ .unwrap();
let first = deliver_pending_messages(&config, "team-1", "m1").unwrap();
assert_eq!(first, vec!["hello m1".to_string(), "broadcast".to_string()]);
@@ -647,7 +658,8 @@ fn deliver_pending_messages_pages_past_first_event_page() {
}
// This message is appended at sequence > 150 — unreachable on the first page.
- super::super::ops::message_member(&config, "team-1", None, Some("m1"), "late note", None)
+ team_service(&config)
+ .message_member("team-1", None, Some("m1"), "late note", None)
.unwrap();
let delivered = deliver_pending_messages(&config, "team-1", "m1").unwrap();
diff --git a/crates/openhuman-core/src/agent/orchestration/agent_teams/schemas.rs b/crates/openhuman-core/src/agent/orchestration/agent_teams/schemas.rs
index eeb13a3b87..72145a547e 100644
--- a/crates/openhuman-core/src/agent/orchestration/agent_teams/schemas.rs
+++ b/crates/openhuman-core/src/agent/orchestration/agent_teams/schemas.rs
@@ -15,8 +15,8 @@ use crate::core::{ControllerSchema, FieldSchema, TypeSchema};
use crate::rpc::RpcOutcome;
use tinyagents_session::run_ledger::AgentTeamListRequest;
-use super::ops::{self, NewMember};
use super::runtime;
+use tinyagents_orchestration::teams::{NewMember, SessionTeamLedger, TeamService};
/// Controller schemas exposed by the agent-teams module.
pub fn all_controller_schemas() -> Vec<ControllerSchema> {
@@ -264,14 +264,14 @@ fn handle_create(params: Map<String, Value>) -> ControllerFuture {
let summary = opt_str(&params, "summary");
let members = parse_members(&params)?;
log::debug!(target: "agent_team_rpc", "[agent_team_rpc][{cid}] create.parsed lead={lead} members={}", members.len());
- let view = ops::create_team(
- &config,
- &lead,
- parent_thread_id.as_deref(),
- summary.as_deref(),
- &members,
- )
- .map_err(|e| log_err(&cid, "create", e))?;
+ let view = team_service(&config)
+ .create_team(
+ &lead,
+ parent_thread_id.as_deref(),
+ summary.as_deref(),
+ &members,
+ )
+ .map_err(|e| log_err(&cid, "create", e))?;
log::debug!(target: "agent_team_rpc", "[agent_team_rpc][{cid}] create.success id={}", view.team.id);
to_json(view)
})
@@ -295,7 +295,9 @@ fn handle_list(params: Map<String, Value>) -> ControllerFuture {
s
})?
};
- let response = ops::list_teams(&config, &request).map_err(|e| log_err(&cid, "list", e))?;
+ let response = team_service(&config)
+ .list_teams(&request)
+ .map_err(|e| log_err(&cid, "list", e))?;
log::debug!(target: "agent_team_rpc", "[agent_team_rpc][{cid}] list.success count={}", response.count);
to_json(response)
})
@@ -309,7 +311,9 @@ fn handle_get(params: Map<String, Value>) -> ControllerFuture {
log::warn!(target: "agent_team_rpc", "[agent_team_rpc][{cid}] get.config_failed err={err}");
})?;
let team_id = require_str(&params, "teamId")?;
- let view = ops::get_team(&config, &team_id).map_err(|e| log_err(&cid, "get", e))?;
+ let view = team_service(&config)
+ .get_team(&team_id)
+ .map_err(|e| log_err(&cid, "get", e))?;
log::debug!(target: "agent_team_rpc", "[agent_team_rpc][{cid}] get.success id={team_id} found={}", view.is_some());
to_json(serde_json::json!({ "team": view }))
})
@@ -328,15 +332,15 @@ fn handle_assign_task(params: Map<String, Value>) -> ControllerFuture {
let owner = opt_str(&params, "ownerMemberId");
let depends_on = opt_str_array(&params, "dependsOn");
log::debug!(target: "agent_team_rpc", "[agent_team_rpc][{cid}] assign_task.parsed team={team_id} deps={}", depends_on.len());
- let task = ops::assign_task(
- &config,
- &team_id,
- &title,
- objective.as_deref(),
- owner.as_deref(),
- &depends_on,
- )
- .map_err(|e| log_err(&cid, "assign_task", e))?;
+ let task = team_service(&config)
+ .assign_task(
+ &team_id,
+ &title,
+ objective.as_deref(),
+ owner.as_deref(),
+ &depends_on,
+ )
+ .map_err(|e| log_err(&cid, "assign_task", e))?;
log::debug!(target: "agent_team_rpc", "[agent_team_rpc][{cid}] assign_task.success task={}", task.id);
to_json(serde_json::json!({ "task": task }))
})
@@ -353,7 +357,8 @@ fn handle_claim_task(params: Map<String, Value>) -> ControllerFuture {
let task_id = require_str(&params, "taskId")?;
let member_id = require_str(&params, "memberId")?;
let claim_token = require_str(&params, "claimToken")?;
- let outcome = ops::claim_task(&config, &team_id, &task_id, &member_id, &claim_token)
+ let outcome = team_service(&config)
+ .claim_task(&team_id, &task_id, &member_id, &claim_token)
.map_err(|e| log_err(&cid, "claim_task", e))?;
log::debug!(target: "agent_team_rpc", "[agent_team_rpc][{cid}] claim_task.success team={team_id} task={task_id}");
to_json(serde_json::json!({ "result": outcome }))
@@ -374,15 +379,15 @@ fn handle_message_member(params: Map<String, Value>) -> ControllerFuture {
let to = opt_str(&params, "toMemberId");
let content = require_str(&params, "content")?;
let visibility = opt_str(&params, "visibility");
- let event = ops::message_member(
- &config,
- &team_id,
- from.as_deref(),
- to.as_deref(),
- &content,
- visibility.as_deref(),
- )
- .map_err(|e| log_err(&cid, "message_member", e))?;
+ let event = team_service(&config)
+ .message_member(
+ &team_id,
+ from.as_deref(),
+ to.as_deref(),
+ &content,
+ visibility.as_deref(),
+ )
+ .map_err(|e| log_err(&cid, "message_member", e))?;
log::debug!(target: "agent_team_rpc", "[agent_team_rpc][{cid}] message_member.success team={team_id} sequence={}", event.sequence);
to_json(serde_json::json!({ "message": event }))
})
@@ -400,7 +405,8 @@ fn handle_list_messages(params: Map<String, Value>) -> ControllerFuture {
.get("limit")
.and_then(Value::as_u64)
.map(|v| v as u32);
- let messages = ops::list_messages(&config, &team_id, limit)
+ let messages = team_service(&config)
+ .list_messages(&team_id, limit)
.map_err(|e| log_err(&cid, "list_messages", e))?;
log::debug!(target: "agent_team_rpc", "[agent_team_rpc][{cid}] list_messages.success team={team_id} count={}", messages.len());
to_json(serde_json::json!({ "messages": messages }))
@@ -423,15 +429,9 @@ fn handle_complete_task(params: Map<String, Value>) -> ControllerFuture {
.and_then(Value::as_bool)
.unwrap_or(false);
log::debug!(target: "agent_team_rpc", "[agent_team_rpc][{cid}] complete_task.parsed team={team_id} task={task_id} evidence={} requireEvidence={require_evidence}", evidence.len());
- let outcome = ops::complete_task(
- &config,
- &team_id,
- &task_id,
- &member_id,
- &evidence,
- require_evidence,
- )
- .map_err(|e| log_err(&cid, "complete_task", e))?;
+ let outcome = team_service(&config)
+ .complete_task(&team_id, &task_id, &member_id, &evidence, require_evidence)
+ .map_err(|e| log_err(&cid, "complete_task", e))?;
log::debug!(target: "agent_team_rpc", "[agent_team_rpc][{cid}] complete_task.success team={team_id} task={task_id}");
to_json(serde_json::json!({ "result": outcome }))
})
@@ -446,7 +446,8 @@ fn handle_shutdown_member(params: Map<String, Value>) -> ControllerFuture {
})?;
let team_id = require_str(&params, "teamId")?;
let member_id = require_str(&params, "memberId")?;
- let result = ops::shutdown_member(&config, &team_id, &member_id)
+ let result = team_service(&config)
+ .shutdown_member(&team_id, &member_id)
.map_err(|e| log_err(&cid, "shutdown_member", e))?;
log::debug!(target: "agent_team_rpc", "[agent_team_rpc][{cid}] shutdown_member.success team={team_id} member={member_id} released={}", result.released_task_ids.len());
to_json(serde_json::json!({ "result": result }))
@@ -462,7 +463,8 @@ fn handle_close(params: Map<String, Value>) -> ControllerFuture {
})?;
let team_id = require_str(&params, "teamId")?;
let summary = opt_str(&params, "summary");
- let team = ops::close_team(&config, &team_id, summary.as_deref())
+ let team = team_service(&config)
+ .close_team(&team_id, summary.as_deref())
.map_err(|e| log_err(&cid, "close", e))?;
log::debug!(target: "agent_team_rpc", "[agent_team_rpc][{cid}] close.success team={team_id}");
to_json(serde_json::json!({ "team": team }))
@@ -520,6 +522,12 @@ fn parse_members(params: &Map<String, Value>) -> Result<Vec<NewMember>, String>
Ok(members)
}
+/// OpenHuman chooses the persistence root; the generic service owns only team
+/// coordination over that already-authorized ledger.
+fn team_service(config: &crate::config::Config) -> TeamService<SessionTeamLedger> {
+ TeamService::new(SessionTeamLedger::new(config.workspace_dir.clone()))
+}
+
fn require_str(params: &Map<String, Value>, key: &str) -> Result<String, String> {
params
.get(key)
diff --git a/crates/openhuman-core/src/agent/orchestration/agent_teams/types.rs b/crates/openhuman-core/src/agent/orchestration/agent_teams/types.rs
deleted file mode 100644
index 43862b974e..0000000000
--- a/crates/openhuman-core/src/agent/orchestration/agent_teams/types.rs
+++ /dev/null
@@ -1,97 +0,0 @@
-//! Aggregate + validation types for durable agent-team coordination (#3374).
-//!
-//! The durable row types ([`AgentTeam`], [`AgentTeamMember`], [`AgentTeamTask`],
-//! [`ClaimOutcome`]) live in `tinyagents_session::run_ledger`. This module adds the
-//! read-aggregate view returned by the controllers and the validation error
-//! surface used by `ops::assign_task`.
-
-use serde::Serialize;
-
-use tinyagents_session::run_ledger::{AgentTeam, AgentTeamMember, AgentTeamTask};
-
-/// A team plus its members and tasks — the shape returned by `get`.
-#[derive(Debug, Clone, PartialEq, Serialize)]
-#[serde(rename_all = "camelCase")]
-pub struct TeamView {
- pub team: AgentTeam,
- pub members: Vec<AgentTeamMember>,
- pub tasks: Vec<AgentTeamTask>,
-}
-
-/// Result of shutting a member down: the stopped member plus the ids of any
-/// `in_progress` tasks that were released back to `todo` for another teammate.
-#[derive(Debug, Clone, PartialEq, Serialize)]
-#[serde(rename_all = "camelCase")]
-pub struct MemberShutdown {
- pub member: AgentTeamMember,
- pub released_task_ids: Vec<String>,
-}
-
-/// Outcome of starting a live run for a team member ([`ops::start_member`]).
-///
-/// `Started` means a task was atomically claimed for the member and a worker
-/// agent was dispatched on a background task (the member flips to `active` with
-/// the returned `run_id`); the run drives to completion asynchronously and the
-/// UI observes progress by polling `get`. The non-`Started` variants mean no
-/// worker was spawned — the caller can surface the reason without any side
-/// effect on member or task state.
-#[derive(Debug, Clone, PartialEq, Serialize)]
-#[serde(rename_all = "camelCase", tag = "kind")]
-pub enum StartMemberOutcome {
- /// A task was claimed and a worker dispatched. `run_id` is the orchestration
- /// id of the spawned agent; `task` is the freshly-claimed task row.
- Started {
- run_id: String,
- task: Box<AgentTeamTask>,
- },
- /// The target task's dependencies are not all `done`; `unmet` lists them.
- Blocked { unmet: Vec<String> },
- /// The target task is already claimed by another member.
- AlreadyClaimed,
- /// The member is already `active` on a run — starting again would spawn a
- /// second concurrent worker and clobber its task/run pointer. Rejected before
- /// any claim or state mutation.
- AlreadyActive,
- /// No explicit task was given and the member has no claimable ready task.
- NoClaimableTask,
- /// An explicit `task_id` was given but no such task exists in the team.
- UnknownTask,
-}
-
-/// A validation / coordination problem surfaced by the agent-team ops.
-#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
-#[serde(rename_all = "camelCase", tag = "kind", content = "detail")]
-pub enum TeamError {
- /// A member name collides with an existing member in the same team.
- DuplicateMemberName { name: String },
- /// A referenced member id is not part of the team.
- UnknownMember { member_id: String },
- /// A task declared itself as one of its own dependencies.
- SelfDependency { task_id: String },
- /// A dependency edge would introduce a cycle among the team's tasks.
- CyclicDependency,
- /// A dependency named a task id that does not exist in the team.
- UnknownDependency { depends_on: String },
-}
-
-impl std::fmt::Display for TeamError {
- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- match self {
- TeamError::DuplicateMemberName { name } => {
- write!(f, "duplicate member name: {name}")
- }
- TeamError::UnknownMember { member_id } => {
- write!(f, "unknown member: {member_id}")
- }
- TeamError::SelfDependency { task_id } => {
- write!(f, "task {task_id} cannot depend on itself")
- }
- TeamError::CyclicDependency => write!(f, "dependency cycle detected"),
- TeamError::UnknownDependency { depends_on } => {
- write!(f, "unknown dependency: {depends_on}")
- }
- }
- }
-}
-
-impl std::error::Error for TeamError {}
diff --git a/crates/openhuman-core/src/agent/tinyagents/topology.rs b/crates/openhuman-core/src/agent/tinyagents/topology.rs
index b947e828f4..c46dec52e5 100644
--- a/crates/openhuman-core/src/agent/tinyagents/topology.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/topology.rs
@@ -45,7 +45,7 @@ fn describe(name: &'static str, topology: &GraphTopology) -> GraphTopologyReport
pub(crate) fn all_graph_topologies() -> Vec<GraphTopologyReport> {
let mut out = Vec::new();
- if let Ok(t) = crate::agent::orchestration::agent_teams::member_graph_topology() {
+ if let Ok(t) = tinyagents_orchestration::teams::member_graph_topology() {
out.push(describe("agent_teams:member", &t));
}
diff --git a/crates/openhuman-core/src/agent/tinyagents/topology_tests.rs b/crates/openhuman-core/src/agent/tinyagents/topology_tests.rs
index 0acd363a63..0a3204c3f7 100644
--- a/crates/openhuman-core/src/agent/tinyagents/topology_tests.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/topology_tests.rs
@@ -104,8 +104,8 @@ fn delegation_topology_names_the_revision_loop_nodes() {
#[test]
fn member_report_renders_mermaid_and_valid_json() {
- let t = crate::agent::orchestration::agent_teams::member_graph_topology()
- .expect("member topology builds");
+ let t =
+ tinyagents_orchestration::teams::member_graph_topology().expect("member topology builds");
let report = describe("agent_teams:member", &t);
// Mermaid is a flowchart with at least the entry node rendered.
diff --git a/vendor/tinyagents b/vendor/tinyagents
index ea2a78842e..3bbe25eaa5 160000
--- a/vendor/tinyagents
+++ b/vendor/tinyagents
@@ -1 +1 @@
-Subproject commit ea2a78842ec0fea6b7a0f5d1b42012c62d118a54
+Subproject commit 3bbe25eaa58f6ba0f1b36f1d99699ad2e7a445da