The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
chore: files changed src/openhuman/agent/harness/subagent_runner/handoff.rs,src/openhuman/agent/orch
Steven Enamakel1f0d89f52cd4
diff --git a/src/openhuman/agent/harness/subagent_runner/handoff.rs b/src/openhuman/agent/harness/subagent_runner/handoff.rsindex 6938580db7..36be70fae0 100644--- a/src/openhuman/agent/harness/subagent_runner/handoff.rs+++ b/src/openhuman/agent/harness/subagent_runner/handoff.rs@@ -20,7 +20,7 @@//! Resolving the effective oversize threshold is host policy: the crate//! takes `threshold_tokens` as an explicit parameter (it deliberately//! dropped an environment-variable backdoor), and this host still needs-//! that backdoor for its own test harnesses —+//! that backdoor for its external test harnesses —//! `OPENHUMAN_TEST_HANDOFF_THRESHOLD_TOKENS` lets a test lower the//! threshold so the handoff path can be exercised on payloads that survive//! tokenjuice's compaction cap (see e.g.@@ -51,10 +51,32 @@ pub(crate) fn apply_handoff(agent_id: &str,result_text: String,) -> String {- let effective_threshold = std::env::var("OPENHUMAN_TEST_HANDOFF_THRESHOLD_TOKENS")- .ok()- .and_then(|v| v.parse::<usize>().ok())- .unwrap_or(HANDOFF_OVERSIZE_THRESHOLD_TOKENS);+ let threshold_override = std::env::var("OPENHUMAN_TEST_HANDOFF_THRESHOLD_TOKENS").ok();+ let effective_threshold = resolve_handoff_threshold(threshold_override.as_deref());+ apply_handoff_with_threshold(+ cache,+ tool_name,+ task_id,+ agent_id,+ result_text,+ effective_threshold,+ )+}++fn resolve_handoff_threshold(threshold_override: Option<&str>) -> usize {+ threshold_override+ .and_then(|value| value.parse::<usize>().ok())+ .unwrap_or(HANDOFF_OVERSIZE_THRESHOLD_TOKENS)+}++fn apply_handoff_with_threshold(+ cache: &ResultHandoffCache,+ tool_name: &str,+ task_id: &str,+ agent_id: &str,+ result_text: String,+ effective_threshold: usize,+) -> String {tinyagents::harness::handoff::apply_handoff(cache,tool_name,@@ -68,61 +90,22 @@ pub(crate) fn apply_handoff(#[cfg(test)]mod tests {use super::*;- use std::sync::{Mutex, OnceLock};-- /// `OPENHUMAN_TEST_HANDOFF_THRESHOLD_TOKENS` is process-global and this- /// suite runs ~11.6k tests in one process, so serialize the two tests in- /// this module that touch it and restore the prior value on drop.- fn env_lock() -> std::sync::MutexGuard<'static, ()> {- static LOCK: OnceLock<Mutex<()>> = OnceLock::new();- LOCK.get_or_init(|| Mutex::new(()))- .lock()- .unwrap_or_else(|e| e.into_inner())- }-- struct EnvGuard {- key: &'static str,- prev: Option<String>,- }-- impl EnvGuard {- fn set(key: &'static str, val: &str) -> Self {- let prev = std::env::var(key).ok();- // SAFETY: caller holds `env_lock()` for the duration of the test.- unsafe { std::env::set_var(key, val) };- Self { key, prev }- }-- fn remove(key: &'static str) -> Self {- let prev = std::env::var(key).ok();- // SAFETY: caller holds `env_lock()` for the duration of the test.- unsafe { std::env::remove_var(key) };- Self { key, prev }- }- }-- impl Drop for EnvGuard {- fn drop(&mut self) {- match &self.prev {- // SAFETY: caller holds `env_lock()` for the duration of the test.- Some(val) => unsafe { std::env::set_var(self.key, val) },- None => unsafe { std::env::remove_var(self.key) },- }- }- }#[test]- fn apply_handoff_uses_the_test_env_threshold_when_set() {- let _guard = env_lock();- let _env = EnvGuard::set("OPENHUMAN_TEST_HANDOFF_THRESHOLD_TOKENS", "5");+ fn apply_handoff_uses_an_injected_threshold() {let cache = ResultHandoffCache::new();// 40 bytes / 4 => 10 estimated tokens, comfortably above the- // env-lowered threshold of 5 but nowhere near the real default of- // 50_000 — this only exercises the handoff path because the env var- // was actually read and honoured.+ // injected threshold of 5 but nowhere near the real default of 50_000.let oversized = "x".repeat(40);- let out = apply_handoff(&cache, "some_tool", "task-1", "agent-1", oversized.clone());+ let out = apply_handoff_with_threshold(+ &cache,+ "some_tool",+ "task-1",+ "agent-1",+ oversized.clone(),+ 5,+ );assert_ne!(out, oversized,@@ -135,16 +118,34 @@ mod tests {}#[test]- fn apply_handoff_falls_back_to_the_default_threshold_when_env_unset() {- let _guard = env_lock();- let _env = EnvGuard::remove("OPENHUMAN_TEST_HANDOFF_THRESHOLD_TOKENS");+ fn threshold_resolution_accepts_valid_overrides_and_rejects_invalid_ones() {+ assert_eq!(resolve_handoff_threshold(Some("5")), 5);+ assert_eq!(+ resolve_handoff_threshold(Some("not-a-number")),+ HANDOFF_OVERSIZE_THRESHOLD_TOKENS+ );+ assert_eq!(+ resolve_handoff_threshold(None),+ HANDOFF_OVERSIZE_THRESHOLD_TOKENS+ );+ }++ #[test]+ fn apply_handoff_uses_the_default_threshold_when_injected() {let cache = ResultHandoffCache::new();// Comfortably below HANDOFF_OVERSIZE_THRESHOLD_TOKENS (50_000 tokens// / 200_000 bytes), so with the env var unset (falling back to the// real default) the text passes through unchanged.let small = "hello world".to_string();- let out = apply_handoff(&cache, "some_tool", "task-1", "agent-1", small.clone());+ let out = apply_handoff_with_threshold(+ &cache,+ "some_tool",+ "task-1",+ "agent-1",+ small.clone(),+ HANDOFF_OVERSIZE_THRESHOLD_TOKENS,+ );assert_eq!(out, small,diff --git a/src/openhuman/agent/orchestration/README.md b/src/openhuman/agent/orchestration/README.mdindex 291a413e5e..e6c27788b8 100644--- a/src/openhuman/agent/orchestration/README.md+++ b/src/openhuman/agent/orchestration/README.md@@ -1,10 +1,12 @@# Agent Orchestration`agent_orchestration` is the high-level control plane for agent-to-agent work.-It owns parent/child lineage, lifecycle state, wait/close/follow-up semantics,-and UI/diagnostic events. The lower-level `agent::harness` remains the execution-engine for prompt construction, policy-filtered tools, model selection, and-sub-agent loops.+It owns parent/child lineage, lifecycle state, wait/cancel semantics, and+UI/diagnostic events. Durable close, retry, and follow-up operations live in+`command_center::control`; the removed process-local mirror is not part of this+surface. The lower-level `agent::harness` remains the execution engine for+prompt construction, policy-filtered tools, model selection, and sub-agent+loops.## Current Inventorydiff --git a/src/openhuman/agent/orchestration/ops.rs b/src/openhuman/agent/orchestration/ops.rsindex 417e08e326..6a2a4f6a08 100644--- a/src/openhuman/agent/orchestration/ops.rs+++ b/src/openhuman/agent/orchestration/ops.rs@@ -223,27 +223,23 @@ impl AgentOrchestrationSession {/// 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.+ /// is published atomically on each child's watch channel first. The+ /// terminal registry entry is retained until a waiter observes it (or a+ /// later soft-cap sweep prunes it), so a concurrent `wait_agents` resolves+ /// with cancellation even when it starts after this method returns.pub async fn abort_all(&self) {- let cancelled = match self.registry.cancel_all() {+ let cancelled = match self+ .registry+ .cancel_all_retaining(|metadata, _status| {+ mark_cancelled(&metadata.status_tx);+ })+ {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,@@ -457,20 +453,19 @@ impl AgentOrchestrationSession {progress_sink: Option<mpsc::Sender<AgentProgress>>,result: Result<SubagentRunOutcome, crate::openhuman::agent::harness::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 _ = status_tx.send(ChildState {+ if !publish_terminal(+ status_tx,+ ChildState {status: OrchestrationTaskStatus::Completed,result_summary: Some(outcome.output.clone()),error: None,updated_at: now(),- });+ },+ ) {+ return;+ }BUS.publish(DomainEvent::AgentOrchestrationCompleted {session_id: self.session_id.clone(),orchestration_id: orchestration_id.to_string(),@@ -504,12 +499,17 @@ impl AgentOrchestrationSession {}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(),- });+ if !publish_terminal(+ status_tx,+ ChildState {+ status: OrchestrationTaskStatus::Failed,+ result_summary: None,+ error: Some(message.clone()),+ updated_at: now(),+ },+ ) {+ return;+ }BUS.publish(DomainEvent::AgentOrchestrationFailed {session_id: self.session_id.clone(),orchestration_id: orchestration_id.to_string(),@@ -530,6 +530,35 @@ impl AgentOrchestrationSession {}}+/// Publish a terminal state only when no terminal writer won the race first.+///+/// The watch-channel update is the compare-and-set boundary for both the state+/// transition and the caller's subsequent lifecycle events: callers emit only+/// when this returns `true`.+fn publish_terminal(status_tx: &watch::Sender<ChildState>, terminal: ChildState) -> bool {+ debug_assert!(terminal.is_terminal());+ status_tx.send_if_modified(|state| {+ if state.is_terminal() {+ return false;+ }+ *state = terminal.clone();+ true+ })+}++/// Atomically mark a live child cancelled while preserving any partial payload.+fn mark_cancelled(status_tx: &watch::Sender<ChildState>) -> bool {+ let updated_at = now();+ status_tx.send_if_modified(|state| {+ if state.is_terminal() {+ return false;+ }+ state.status = OrchestrationTaskStatus::Cancelled;+ state.updated_at = updated_at.clone();+ true+ })+}+/// Publish `Running` unless the child already reached a terminal status.fn mark_running(status_tx: &watch::Sender<ChildState>) {let updated_at = now();diff --git a/src/openhuman/agent/orchestration/ops_tests.rs b/src/openhuman/agent/orchestration/ops_tests.rsindex ce8ff254cf..3b89084fc7 100644--- a/src/openhuman/agent/orchestration/ops_tests.rs+++ b/src/openhuman/agent/orchestration/ops_tests.rs@@ -474,9 +474,9 @@ async fn unit_wait_agents_rejects_an_unknown_child() {);}-/// `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.+/// `abort_all` must retain the terminal registry entry until a waiter observes+/// it, including when cancellation lands before that waiter enters+/// `DetachedTaskRegistry::wait`.#[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();@@ -509,34 +509,8 @@ async fn e2e_abort_all_cancels_an_in_flight_child_for_a_concurrent_waiter() {})};- // Readiness handshake instead of a fixed sleep: `cancel_all` removes the- // registry entry outright, so calling `abort_all` before the child has- // observably reached `Running` risks the waiter's own lookup racing the- // removal and surfacing `AgentNotFound` instead of `Cancelled`. Poll with- // short, non-terminal `wait_agents` calls (the crate only prunes a- // *terminal* entry, so polling a still-running child is side-effect-free)- // until `Running` is observed, bounded so a genuine regression fails fast- // rather than hanging.- 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"- );+ // No readiness handshake: the regression was specifically the gap between+ // a caller knowing the id and entering the registry wait.session.abort_all().await;let response = waiter