Skip to content

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

refactor(agent): use neutral orchestration helpers directly

Steven Enamakel0ea00af7d26d
diff --git a/.sdd-progress.md b/.sdd-progress.md
index b90c5060d7..ec10638a2e 100644
--- a/.sdd-progress.md
+++ b/.sdd-progress.md
@@ -17,14 +17,16 @@ verification are complete, pending 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` seam, `SessionTeamLedger`,
-dependency-aware `TeamService`, claim selection, and generic member completion
-graph (including optional host-provided graph-event sinks). OpenHuman's
-agent-team controllers, runtime, and topology import that crate directly; the
-runtime injects its established `team:<team>:<member>` tracing sink. 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. O3-O4 add direct `tinyagents_orchestration::workflow` definitions and
+dependency-aware `TeamService`, claim selection, generic member completion
+graph (including optional host-provided graph-event sinks), event-log paging,
+member watermark delivery, prompt composition, and Unicode-safe evidence
+truncation. OpenHuman's agent-team controllers, runtime, and topology import
+that crate directly; the runtime injects its established
+`team:<team>:<member>` tracing sink. The prior local `types`, `ops`, `graph`,
+message-delivery, prompt, and truncation helpers and their facades are deleted.
+OpenHuman retains its root-parent context, subagent execution,
+persistence-root selection and RPC schemas. O3-O4 add direct
+`tinyagents_orchestration::workflow` definitions and
validation, opaque host catalog metadata, phase state, a session-ledger
`WorkflowStore`, injected async `WorkflowExecutor`, bounded `map_reduce`
fan-out, cancellation, terminal persistence, resume skipping, upstream prompt
@@ -53,7 +55,12 @@ Historic OpenHuman aliases for git worktree create/list/status/diff/remove,
base refs, errors and overlap detection are deleted; every consumer imports
the harness surface directly. `OpenHumanWorktreeIsolation`, its BUS lifecycle
events, descriptor gate and RPC schemas remain host-owned. Dirty-worktree
-refusal/removal and parallel policy coverage are retained.
+refusal/removal and parallel policy coverage are retained. Final boundary
+remediation also removed the behavior-free OpenHuman
+`workflow_runs::scheduler_topology_preview` forwarder: topology imports
+`tinyagents_orchestration::workflow` directly. TinyAgents orchestration tests
+(31) cover direct/broadcast watermark delivery, paging beyond the ledger cap,
+prompt composition, and UTF-8 truncation.
O5 final durability remediation: complete locally, pending commit/review. The
session ledger now exposes revision-fenced host lifecycle transitions and
diff --git a/crates/openhuman-core/src/agent/orchestration/README.md b/crates/openhuman-core/src/agent/orchestration/README.md
index dcdf040fee..7dfb18a15f 100644
--- a/crates/openhuman-core/src/agent/orchestration/README.md
+++ b/crates/openhuman-core/src/agent/orchestration/README.md
@@ -8,26 +8,28 @@ lower-level `agent::harness` remains the execution engine — prompt
construction, policy-filtered tools, model selection, and the sub-agent run
loop itself.
-Execution fans out on TinyAgents **graphs**: `workflow_runs` schedules phase
-DAGs on a graph engine, `agent_teams` routes members through a
-conditional-routing graph, `delegation` wires the durable
-plan→execute⇄review→finalize graph, and parallel fanout goes through
-`tinyagents_graph::parallel::map_reduce`. What stays in this module is the
-product layer: durable SQL/JSON run ledgers, validation, cancellation
-semantics, compatibility events, and JSON-RPC/tool response formatting.
+The generic durable coordination model lives in
+`tinyagents-orchestration`: team/workflow types, validation, run-ledger
+services, graph composition, member prompt construction, message watermark
+delivery, and diagnostic workflow topology. OpenHuman imports those APIs
+directly. This module retains the product adapters: Config and root-parent
+construction, model/tool selection, `run_subagent`, progress and BUS events,
+RPC/tool formatting, and OpenHuman's worktree policy.
## Responsibilities
- Register, wait on, and cancel child agent runs (`ops.rs`,
`AgentOrchestrationSession`) as thin wrappers over TinyAgents'
`DetachedTaskRegistry`.
-- Durable multi-agent models with their own run-ledger tables: agent teams
- (`agent_teams/`), declarative phase-graph workflows (`workflow_runs/`), and
- the plan→execute⇄review→finalize graph (`delegation.rs`).
+- Host adapters for durable teams and workflows: RPC schemas, root-parent
+ worker execution, model selection, cancellation policy, and BUS/progress
+ integration. Their host-neutral types, storage services, scheduling graphs,
+ prompt composition, and delivery bookkeeping are in
+ `tinyagents-orchestration`.
- A read-only command-center view over background agent runs plus stop/retry/
continue/follow-up control verbs (`command_center/`).
-- Git-worktree isolation so parallel coding workers never clobber the same
- checkout (`worktree.rs`, `worktree_schemas.rs`).
+- OpenHuman's `OpenHumanWorktreeIsolation` adapter and RPC surface; generic
+ worktree operations are used directly from `tinyagents_harness::workspace`.
- User-driven cancel/steer of detached (`spawn_async_subagent`) background
sub-agents from the frontend background-tasks drawer (`subagent_control.rs`).
- Mirroring detached sub-agent lifecycle into a TinyAgents task store, batching
@@ -45,29 +47,29 @@ semantics, compatibility events, and JSON-RPC/tool response formatting.
- `ops.rs` / `types.rs` — `AgentOrchestrationSession`, `OrchestrationError`,
`AgentSnapshot`, `OrchestrationTaskStatus`, `SpawnAgentRequest`/`Response`,
`WaitAgentOptions`/`Response`.
-- `agent_teams/` — durable lead/worker team coordination (issue #3374):
- atomic task claiming, dependency validation, quality-gated completion, and
- live teammate execution via `start_member`.
+- `agent_teams/` — OpenHuman's live member-worker adapter for the generic
+ `tinyagents_orchestration::teams` service: it supplies Config, the root
+ parent context, model/tool execution, progress tracing, and BUS-facing
+ lifecycle behavior.
- `command_center/` — read-only grouped view of background agent runs
(`ops.rs`) plus stop/retry/continue/follow-up transitions (`control.rs`).
-- `workflow_runs/` — declarative `WorkflowDefinition` phase graphs (issue
- #3375), the builtin "parallel research with cross-checking" workflow,
- structural/agent validation, and the live execution engine (`engine.rs`).
+- `workflow_runs/` — OpenHuman's live workflow execution and RPC adapters;
+ workflow definitions, durable state, validation, graphs, and neutral engine
+ mechanics are imported directly from `tinyagents_orchestration::workflow`.
- `delegation.rs` — production worker for TinyAgents' durable
plan→execute⇄review→finalize graph; every stage runs through `run_subagent`.
-- `spawn_parallel_graph.rs` + `spawn_parallel_graph/` (`request.rs`, `staging.rs`,
- `dispatch.rs`, `workers.rs`, `collect.rs`, `graph.rs`, `run.rs`, `types.rs`) —
- the fanout behind
- `spawn_parallel_agents`: request/claim validation, worktree preflight, and the
- bounded `map_reduce` worker run; the tool file only translates `ToolResult`.
+- `spawn_parallel_agents` uses `tinyagents_graph::parallel::map_reduce` with
+ OpenHuman-owned request validation, worktree policy, dispatch, workers, and
+ result formatting. The former parallel coordinator/request graph modules
+ were removed; there is no OpenHuman forwarding layer around the graph API.
- `subagent_events.rs` — the single owner that constructs and publishes
`DomainEvent::Subagent{Spawned,Completed,Failed,AwaitingUser}`.
- `subagent_control.rs` — manual cancel/steer of detached background
sub-agents; the manual counterpart to the automatic thread-close
cancellation in `crate::threads`.
-- `worktree.rs` / `worktree_schemas.rs` — `OpenHumanWorktreeIsolation` adapter
- over TinyAgents' host-agnostic git-worktree plumbing, plus the
- list/status/diff/remove RPC surface.
+- `worktree.rs` / `worktree_schemas.rs` — `OpenHumanWorktreeIsolation` and the
+ list/status/diff/remove RPC surface. They call
+ `tinyagents_harness::workspace` directly rather than maintaining aliases.
- `subagent_sessions/` — durable subagent session records
(`DurableSubagentSessionSummary`, `SubagentSessionStore`) used for
reuse/dedup decisions across turns.
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 0cc3668792..d14a7a2645 100644
--- a/crates/openhuman-core/src/agent/orchestration/agent_teams/runtime.rs
+++ b/crates/openhuman-core/src/agent/orchestration/agent_teams/runtime.rs
@@ -38,28 +38,21 @@ use crate::agent::orchestration::{
};
use crate::config::Config;
use tinyagents_session::run_ledger::{
- self, AgentTeamMemberStatus, AgentTeamTask, ClaimOutcome, RunEvent, RunEventAppend,
- RunEventListRequest,
+ self, AgentTeamMemberStatus, AgentTeamTask, ClaimOutcome, RunEventAppend,
};
-use tinyagents_orchestration::teams::{claimable_task, run_member_graph, MemberOutcome, TeamError};
+use tinyagents_orchestration::teams::{
+ build_member_prompt, claimable_task, deliver_pending_messages, run_member_graph,
+ truncate_chars, MemberOutcome, SessionTeamLedger, TeamError,
+};
use crate::agent::tinyagents::observability::GraphTracingSink;
const LOG_TARGET: &str = "agent_team_runtime";
/// Fallback worker archetype when a member carries no explicit `agent_id`.
const DEFAULT_TEAMMATE_AGENT_ID: &str = "researcher";
-const TEAM_MESSAGE_EVENT: &str = "team_message";
-/// Per-member delivery watermark event: payload `{ memberId, upToSeq }`. Stored
-/// on the same run-event log as the messages, so no schema change is needed.
-const MESSAGE_DELIVERED_EVENT: &str = "team_message_delivered";
/// Event recorded when a worker run ends without completing its task.
const MEMBER_FAILED_EVENT: &str = "team_member_failed";
-/// Page size when draining the full run-event log for a team. `list_recent_run_events`
-/// returns `sequence ASC` from the cursor and caps `limit` at 1000, so a team whose
-/// event count exceeds one page MUST be paged or later events (watermarks + messages)
-/// are silently dropped.
-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;
@@ -265,8 +258,9 @@ async fn drive_member(
run_id: &str,
model_override: Option<String>,
) -> Result<()> {
- let delivered = deliver_pending_messages(config, team_id, member_id)?;
- let prompt = build_member_prompt(task, &delivered);
+ let ledger = SessionTeamLedger::new(config.workspace_dir.clone());
+ let delivered = deliver_pending_messages(&ledger, team_id, member_id)?;
+ let prompt = build_member_prompt(task, &delivered.messages);
let session = AgentOrchestrationSession::new(format!("team-{team_id}-{member_id}"));
@@ -432,101 +426,6 @@ async fn drive_member(
.await
}
-/// Compose the worker prompt from the task + any pending messages addressed to
-/// the member.
-fn build_member_prompt(task: &AgentTeamTask, messages: &[String]) -> String {
- let mut prompt = format!("You are a teammate on an agent team. Task: {}", task.title);
- if let Some(obj) = task.objective.as_deref() {
- if !obj.trim().is_empty() {
- prompt.push_str("\n\nObjective:\n");
- prompt.push_str(obj.trim());
- }
- }
- if !messages.is_empty() {
- prompt.push_str("\n\nMessages from your lead / teammates:\n");
- for msg in messages {
- prompt.push_str("- ");
- prompt.push_str(msg);
- prompt.push('\n');
- }
- }
- prompt.push_str("\n\nComplete the task and report what you did.");
- prompt
-}
-
-/// Drain the entire `sequence ASC` run-event log for a team by paging past the
-/// per-query cap. A single `list_recent_run_events` call returns at most 1000
-/// rows from the cursor, so message delivery MUST page or a team that exceeds
-/// one page would lose every watermark and message beyond it.
-fn drain_run_events(config: &Config, team_id: &str) -> Result<Vec<RunEvent>> {
- let mut events: Vec<RunEvent> = Vec::new();
- let mut after: Option<u64> = None;
- loop {
- let response = run_ledger::list_recent_run_events(
- &config.workspace_dir,
- &RunEventListRequest {
- run_id: team_id.to_string(),
- after_sequence: after,
- limit: Some(EVENT_PAGE_SIZE),
- },
- )?;
- let exhausted = (response.count as u32) < EVENT_PAGE_SIZE;
- after = response.events.last().map(|e| e.sequence);
- events.extend(response.events);
- if exhausted || after.is_none() {
- break;
- }
- }
- Ok(events)
-}
-
-/// Read undelivered messages addressed to `member_id` (direct or broadcast),
-/// advance the per-member delivery watermark, and return their contents. Uses
-/// only the existing run-event log — no schema change.
-fn deliver_pending_messages(
- config: &Config,
- team_id: &str,
- member_id: &str,
-) -> Result<Vec<String>> {
- let events = drain_run_events(config, team_id)?;
-
- let watermark = events
- .iter()
- .filter(|e| e.event_type == MESSAGE_DELIVERED_EVENT)
- .filter(|e| e.payload.get("memberId").and_then(|v| v.as_str()) == Some(member_id))
- .filter_map(|e| e.payload.get("upToSeq").and_then(|v| v.as_i64()))
- .max()
- .unwrap_or(0);
-
- let mut max_seq = watermark;
- let mut contents = Vec::new();
- for event in &events {
- if event.event_type != TEAM_MESSAGE_EVENT || (event.sequence as i64) <= watermark {
- continue;
- }
- let to = event.payload.get("to").and_then(|v| v.as_str());
- // Direct (to == member) or broadcast (to absent/null).
- if to.is_none() || to == Some(member_id) {
- if let Some(content) = event.payload.get("content").and_then(|v| v.as_str()) {
- contents.push(content.to_string());
- }
- max_seq = max_seq.max(event.sequence as i64);
- }
- }
-
- if !contents.is_empty() {
- run_ledger::append_run_event(
- &config.workspace_dir,
- RunEventAppend {
- run_id: team_id.to_string(),
- event_type: MESSAGE_DELIVERED_EVENT.to_string(),
- payload: json!({ "memberId": member_id, "upToSeq": max_seq }),
- },
- )?;
- }
- Ok(contents)
-}
-
fn record_failure_event(
config: &Config,
team_id: &str,
@@ -548,16 +447,6 @@ fn record_failure_event(
);
}
-/// UTF-8-safe truncation by character count (never splits a codepoint).
-fn truncate_chars(s: &str, max: usize) -> String {
- if s.chars().count() <= max {
- return s.to_string();
- }
- let mut out: String = s.chars().take(max).collect();
- out.push('…');
- out
-}
-
#[cfg(test)]
#[path = "runtime_tests.rs"]
mod runtime_tests;
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 8db2f34032..82f3c34443 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
@@ -607,99 +607,3 @@ fn pick_claimable_respects_deps_ownership_and_claim() {
tinyagents_orchestration::teams::claimable_task(&tasks, "m1").expect("c is claimable");
assert_eq!(picked.id, "c");
}
-
-#[test]
-fn deliver_pending_messages_injects_then_watermarks() {
- let (_dir, config) = test_config();
- seed_team(&config, "team-1");
- seed_member(&config, "team-1", "m1", None);
- // Direct to m1, a broadcast, and one addressed elsewhere.
- 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();
- seed_member(&config, "team-1", "m2", None);
- 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()]);
-
- // Second call: watermark advanced → nothing new.
- let second = deliver_pending_messages(&config, "team-1", "m1").unwrap();
- assert!(second.is_empty(), "watermark should suppress redelivery");
-}
-
-#[test]
-fn deliver_pending_messages_pages_past_first_event_page() {
- // Regression: a single `list_recent_run_events` call returns at most one
- // page (1000) from `sequence ASC`, but the pre-fix delivery read one
- // unbounded page (capped at 100). A team with more events than the cap
- // would drop every message AND watermark beyond it. Seed well past one page
- // of filler events, then deliver a message landing at a sequence > the cap.
- let (_dir, config) = test_config();
- seed_team(&config, "team-1");
- seed_member(&config, "team-1", "m1", None);
-
- // Push the sequence far past the old 100-row cap with unrelated events.
- for i in 0..150 {
- run_ledger::append_run_event(
- &config.workspace_dir,
- run_ledger::RunEventAppend {
- run_id: "team-1".into(),
- event_type: "noise".into(),
- payload: json!({ "i": i }),
- },
- )
- .unwrap();
- }
-
- // This message is appended at sequence > 150 — unreachable on the first page.
- team_service(&config)
- .message_member("team-1", None, Some("m1"), "late note", None)
- .unwrap();
-
- let delivered = deliver_pending_messages(&config, "team-1", "m1").unwrap();
- assert_eq!(
- delivered,
- vec!["late note".to_string()],
- "message beyond the first event page must still be delivered"
- );
-
- // Watermark (itself recorded beyond the cap) must also be read back so the
- // redelivery guard holds for long-lived teams.
- let again = deliver_pending_messages(&config, "team-1", "m1").unwrap();
- assert!(
- again.is_empty(),
- "watermark past the first page must suppress redelivery"
- );
-}
-
-#[test]
-fn build_member_prompt_includes_objective_and_messages() {
- let task = AgentTeamTask {
- id: "t1".into(),
- team_id: "team".into(),
- title: "Ship the widget".into(),
- objective: Some("wire it up".into()),
- status: AgentTeamTaskStatus::InProgress,
- owner_member_id: None,
- claimed_by_member_id: Some("m1".into()),
- claim_token: Some("tok".into()),
- depends_on: vec![],
- gate_status: "pending".into(),
- gate_reason: None,
- evidence: vec![],
- source_run_id: None,
- order_index: 0,
- created_at: chrono::Utc::now(),
- updated_at: chrono::Utc::now(),
- };
- let prompt = build_member_prompt(&task, &["go now".to_string()]);
- assert!(prompt.contains("Ship the widget"));
- assert!(prompt.contains("wire it up"));
- assert!(prompt.contains("go now"));
-}
diff --git a/crates/openhuman-core/src/agent/orchestration/workflow_runs/mod.rs b/crates/openhuman-core/src/agent/orchestration/workflow_runs/mod.rs
index f5e4c18670..504932cf64 100644
--- a/crates/openhuman-core/src/agent/orchestration/workflow_runs/mod.rs
+++ b/crates/openhuman-core/src/agent/orchestration/workflow_runs/mod.rs
@@ -25,12 +25,6 @@ mod host;
mod ops;
mod schemas;
-/// A diagnostic topology preview, not the effectful workflow scheduler.
-pub(crate) fn scheduler_topology_preview() -> anyhow::Result<tinyagents_graph::export::GraphTopology>
-{
- tinyagents_orchestration::workflow::scheduler_topology_preview()
-}
-
pub use engine::{resume_workflow_run, start_workflow_run, stop_workflow_run};
pub use ops::{
builtin_definitions, definition_by_id, get_run, list_definitions, list_runs,
diff --git a/crates/openhuman-core/src/agent/tinyagents/topology.rs b/crates/openhuman-core/src/agent/tinyagents/topology.rs
index 0338d2af11..d24316692f 100644
--- a/crates/openhuman-core/src/agent/tinyagents/topology.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/topology.rs
@@ -53,7 +53,7 @@ pub(crate) fn all_graph_topologies() -> Vec<GraphTopologyReport> {
out.push(describe("delegation", &t));
}
- if let Ok(t) = crate::agent::orchestration::workflow_runs::scheduler_topology_preview() {
+ if let Ok(t) = tinyagents_orchestration::workflow::scheduler_topology_preview() {
out.push(describe("workflow_runs:scheduler_preview", &t));
}
diff --git a/vendor/tinyagents b/vendor/tinyagents
index 1b1829950b..f657dbfd2c 160000
--- a/vendor/tinyagents
+++ b/vendor/tinyagents
@@ -1 +1 @@
-Subproject commit 1b1829950b1626c3a1c740c6f54e7e36b2faaad2
+Subproject commit f657dbfd2ca33a2475b737ca5c68fd562af822ca