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
feat(agent): add task ledger documents for running subagents
Steven Enamakel25207601f2bb
diff --git a/crates/openhuman-core/src/agent/orchestration/running_subagents.rs b/crates/openhuman-core/src/agent/orchestration/running_subagents.rsindex 1597520bf3..b879b636d9 100644--- a/crates/openhuman-core/src/agent/orchestration/running_subagents.rs+++ b/crates/openhuman-core/src/agent/orchestration/running_subagents.rs@@ -56,7 +56,6 @@ mod resolve;mod roster;mod steering;mod task_ledger;-mod task_ledger_documents;mod wait;#[cfg(test)]diff --git a/crates/openhuman-core/src/agent/orchestration/running_subagents/task_ledger.rs b/crates/openhuman-core/src/agent/orchestration/running_subagents/task_ledger.rsindex cfae03c032..ea70c2f596 100644--- a/crates/openhuman-core/src/agent/orchestration/running_subagents/task_ledger.rs+++ b/crates/openhuman-core/src/agent/orchestration/running_subagents/task_ledger.rs@@ -1,15 +1,15 @@//! Durable per-workspace task store plumbing and the typed lifecycle ledger//! that mirrors each detached sub-agent's status into it (issue #4249).//!-//! The caching and the durable→memory fallback are TinyAgents'-//! (`TaskStoreRegistry` / `open_jsonl_task_store_or_memory`): opening a second-//! store over the same append log would give two writers with independently-//! replayed state, and a workspace that cannot be written should degrade to an-//! in-memory ledger rather than take orchestration down. What stays here is the-//! path layout, the record shape, and the reconciliation of orphaned tasks on-//! boot.+//! The store is TinyAgents' `DriverTaskStore` over the storage backend's+//! documents, cached per workspace and scope (`TaskStoreRegistry`); a backend+//! that cannot be reached degrades to an in-memory ledger rather than taking+//! orchestration down. What stays here is the record shape and the+//! reconciliation of orphaned tasks on boot.-use std::path::{Path, PathBuf};+use std::path::Path;+#[cfg(test)]+use std::path::PathBuf;use std::sync::{Arc, OnceLock};use tinyagents_orchestration::subagent::{@@ -18,20 +18,10 @@ use tinyagents_orchestration::subagent::{subagent_record_for_task, task_status_label, SpawnedSubagent, WaitError,};use tinyagents_tasks::{- open_jsonl_task_store_or_memory, reconcile_orphaned_tasks, InMemoryTaskStore,- OrchestrationTaskFilter, OrchestrationTaskRecord, TaskStore, TaskStoreRegistry,+ reconcile_orphaned_tasks, DriverTaskStore, InMemoryTaskStore, OrchestrationTaskFilter,+ OrchestrationTaskRecord, TaskStore, TaskStoreRegistry,};-/// Where a workspace's detached-task ledger lives.-///-/// A product path, not a generic one: TinyAgents opens whatever file it is-/// given, and this is where OpenHuman keeps it.-fn task_store_path(workspace_dir: &Path) -> PathBuf {- workspace_dir- .join(".openhuman")- .join("orchestration_tasks.jsonl")-}-#[cfg(test)]fn default_task_store_workspace() -> PathBuf {crate::config::default_root_openhuman_dir()@@ -39,46 +29,47 @@ fn default_task_store_workspace() -> PathBuf {.unwrap_or_else(|_| PathBuf::from(".openhuman").join("workspace"))}-/// One cached ledger: a workspace, and under a storage backend the storage-/// scope it was opened for (`None` for the workspace's JSONL file).-type LedgerKey = (PathBuf, Option<String>);+/// One cached ledger: a workspace and the storage scope it was opened for.+type LedgerKey = (PathBuf, String);++const DOMAIN: &str = "running_subagents::task_ledger";/// Process-wide typed lifecycle ledger for detached sub-agents (issue #4249),-/// one durable store per workspace (and per storage scope when the host-/// configured a storage backend, where it is a document collection instead of-/// the JSONL file).+/// one durable store per workspace and storage scope: the `orchestration_*`+/// document collections of the storage backend (TinyAgents' `DriverTaskStore`).static TASK_STORES: OnceLock<TaskStoreRegistry<LedgerKey>> = OnceLock::new();fn task_stores() -> &'static TaskStoreRegistry<LedgerKey> {TASK_STORES.get_or_init(|| {TaskStoreRegistry::new(|(workspace_dir, scope): &LedgerKey| {- if scope.is_some() {- match super::task_ledger_documents::current() {- Ok(Some(repo)) => return super::task_ledger_documents::open_or_memory(repo),- Ok(None) => {}- Err(error) => {- log::warn!("[running_subagents] task ledger scope unavailable; using memory: {error:#}");- return Arc::new(InMemoryTaskStore::new());- }+ match open_driver_store(workspace_dir) {+ Ok(store) => store,+ Err(error) => {+ // A backend that cannot be reached degrades to an+ // in-memory ledger rather than taking orchestration down.+ log::warn!(+ "[running_subagents] task ledger unavailable for scope={scope}; using memory: {error:#}"+ );+ Arc::new(InMemoryTaskStore::new())}}- open_jsonl_task_store_or_memory(&task_store_path(workspace_dir))})})}-/// The cache key for this call: the storage scope joins it when a backend is-/// installed, so two agents on one workspace never share a ledger.+fn open_driver_store(workspace_dir: &Path) -> anyhow::Result<Arc<dyn TaskStore>> {+ let opened = crate::storage::local::open(DOMAIN, workspace_dir)?;+ let scoped = opened.scoped()?;+ let store = DriverTaskStore::new(Arc::clone(scoped.documents()))+ .map_err(|error| anyhow::anyhow!("start the task store bridge: {error}"))?;+ Ok(Arc::new(store))+}++/// The cache key for this call: the storage scope joins the workspace, so two+/// agents on one workspace never share a ledger.fn ledger_key(workspace_dir: &Path) -> Option<LedgerKey> {- #[cfg(test)]- let pinned = super::task_ledger_documents::overridden();- #[cfg(not(test))]- let pinned = false;- if crate::storage::installed().is_none() && !pinned {- return Some((workspace_dir.to_path_buf(), None));- }match crate::storage::current_scope() {- Ok(scope) => Some((workspace_dir.to_path_buf(), Some(scope.to_string()))),+ Ok(scope) => Some((workspace_dir.to_path_buf(), scope.to_string())),Err(error) => {log::warn!("[running_subagents] task ledger has no storage scope: {error}");None@@ -169,7 +160,7 @@ pub(crate) fn list_task_records(workspace_dir: &Path) -> Vec<OrchestrationTaskRe/// A detached sub-agent runs as a `tokio` task owned by the process that spawned/// it. When the core restarts, that task — and its live [`tokio::task::AbortHandle`] //// [`tinyagents_harness::CancellationToken`] — is gone, but the durable-/// `JsonlTaskStore` still holds a non-terminal (`Pending`/`Running`/`Awaiting`/+/// task ledger still holds a non-terminal (`Pending`/`Running`/`Awaiting`//// `CancelRequested`) record for it. Such a record is **orphaned**: there is no/// live executor to re-attach to (OpenHuman spawns child processes, so an/// in-flight run from a dead parent cannot be resumed), and the run-ledgerdiff --git a/crates/openhuman-core/src/agent/orchestration/running_subagents/task_ledger_documents.rs b/crates/openhuman-core/src/agent/orchestration/running_subagents/task_ledger_documents.rsdeleted file mode 100644index 7429e2cec7..0000000000--- a/crates/openhuman-core/src/agent/orchestration/running_subagents/task_ledger_documents.rs+++ /dev/null@@ -1,265 +0,0 @@-//! The detached-task ledger on the `tinystoragedrivers` document port.-//!-//! Used instead of `<workspace>/.openhuman/orchestration_tasks.jsonl` when the-//! host configured a storage backend ([`crate::storage`]); `task_ledger.rs`-//! picks it when it opens a workspace's store. The store lives under the-//! storage scope of the call that opened it (the acting agent, `local` on a-//! single-user host), and `task_ledger.rs` keys its cache by that scope.-//!-//! # Layout-//!-//! | Collection | Document id | Holds |-//! | --- | --- | --- |-//! | `orchestration_tasks` | task id | `record` (the latest [`OrchestrationTaskRecord`]) and `history` (every transition, oldest first) |-//!-//! The transition rules are TinyAgents' (`InMemoryTaskStore` is the state-//! machine); this type only replays the documents on open and writes the-//! changed task's document after each transition, as `JsonlTaskStore` appends-//! a line. A task id belongs to one process (it is a detached run's id), so-//! the document is replaced outright rather than compare-and-swapped.--use std::collections::HashMap;-use std::sync::{Arc, Mutex};--use anyhow::Result as AnyResult;-use serde_json::{json, Value};-use tinyagents_harness::error::{Result, TinyAgentsError};-use tinyagents_harness::ids::TaskId;-use tinyagents_tasks::{- InMemoryTaskStore, OrchestrationControlOutcome, OrchestrationTaskFilter,- OrchestrationTaskRecord, OrchestrationTaskResult, OrchestrationTaskSpec, TaskStore,-};-use tinystoragedrivers::{CollectionSpec, Precondition, Query};--use crate::storage::documents::Repo;-use crate::storage::DocumentStoreExt;--const TASKS: &str = "orchestration_tasks";-const DOMAIN: &str = "running_subagents::task_ledger";--fn collections() -> Vec<CollectionSpec> {- vec![CollectionSpec::new(TASKS)]-}--/// The repo for this call, when the host configured a backend.-pub(super) fn current() -> AnyResult<Option<Repo>> {- #[cfg(test)]- if let Some(repo) = TEST_OVERRIDE.with(|slot| slot.borrow().clone()) {- return Ok(Some(repo));- }- Repo::current(DOMAIN, collections)-}--/// Whether a test pinned a document store for this thread.-#[cfg(test)]-pub(super) fn overridden() -> bool {- TEST_OVERRIDE.with(|slot| slot.borrow().is_some())-}--/// Runs `f` with `repo` standing in for the installed backend, on this thread-/// only, so tests exercise the dispatch without the process-wide slot.-#[cfg(test)]-pub(super) fn with_override<T>(repo: Repo, f: impl FnOnce() -> T) -> T {- TEST_OVERRIDE.with(|slot| *slot.borrow_mut() = Some(repo));- let out = f();- TEST_OVERRIDE.with(|slot| *slot.borrow_mut() = None);- out-}--#[cfg(test)]-thread_local! {- static TEST_OVERRIDE: std::cell::RefCell<Option<Repo>> = const { std::cell::RefCell::new(None) };-}--/// A [`TaskStore`] that keeps every task as a document.-pub(super) struct DocumentTaskStore {- inner: InMemoryTaskStore,- repo: Repo,- history: Mutex<HashMap<TaskId, Vec<OrchestrationTaskRecord>>>,-}--fn graph_error(what: &str, error: impl std::fmt::Display) -> TinyAgentsError {- TinyAgentsError::Graph(format!("{what}: {error}"))-}--impl DocumentTaskStore {- /// Opens the ledger over `repo`, replaying every stored task.- pub(super) fn open(repo: Repo) -> Result<Self> {- let stored = repo- .run(|docs| async move { docs.query_all(TASKS, &Query::all()).await })- .map_err(|error| graph_error("read task ledger", error))?;- let mut history: HashMap<TaskId, Vec<OrchestrationTaskRecord>> = HashMap::new();- let mut latest = Vec::new();- for item in stored {- let record: Option<OrchestrationTaskRecord> = item- .doc- .get("record")- .and_then(|value| serde_json::from_value(value.clone()).ok());- let Some(record) = record else {- log::warn!(- "[running_subagents] skipping malformed task document id={}",- item.id- );- continue;- };- let timeline: Vec<OrchestrationTaskRecord> = item- .doc- .get("history")- .and_then(|value| serde_json::from_value(value.clone()).ok())- .unwrap_or_else(|| vec![record.clone()]);- history.insert(record.spec.task_id.clone(), timeline);- latest.push(record);- }- log::debug!(- "[running_subagents] opened document task ledger tasks={}",- latest.len()- );- Ok(Self {- inner: InMemoryTaskStore::from_records(latest),- repo,- history: Mutex::new(history),- })- }-- fn persist(&self, record: &OrchestrationTaskRecord) -> Result<()> {- let task_id = record.spec.task_id.clone();- let timeline = {- let mut history = self- .history- .lock()- .map_err(|_| graph_error("task ledger", "history lock poisoned"))?;- let timeline = history.entry(task_id.clone()).or_default();- timeline.push(record.clone());- timeline.clone()- };- let doc: Value = json!({- "record": record,- "history": timeline,- });- let id = task_id.as_str().to_string();- self.repo- .run(|docs| async move {- docs.put(TASKS, &id, doc, Precondition::None)- .await- .map(|_| ())- })- .map_err(|error| graph_error("write task ledger", error))- }-- fn persist_current(&self, task_id: &TaskId) -> Result<()> {- if let Some(record) = self.inner.get(task_id) {- self.persist(&record)?;- }- Ok(())- }-}--impl TaskStore for DocumentTaskStore {- fn insert(&self, spec: OrchestrationTaskSpec) -> Result<OrchestrationTaskRecord> {- let record = self.inner.insert(spec)?;- self.persist(&record)?;- Ok(record)- }-- fn get(&self, task_id: &TaskId) -> Option<OrchestrationTaskRecord> {- self.inner.get(task_id)- }-- fn list(&self, filter: OrchestrationTaskFilter) -> Vec<OrchestrationTaskRecord> {- self.inner.list(filter)- }-- fn history(&self, task_id: &TaskId) -> Vec<OrchestrationTaskRecord> {- self.history- .lock()- .ok()- .and_then(|history| history.get(task_id).cloned())- .unwrap_or_default()- }-- fn mark_running(&self, task_id: &TaskId) -> Result<OrchestrationTaskRecord> {- let record = self.inner.mark_running(task_id)?;- self.persist(&record)?;- Ok(record)- }-- fn mark_awaiting(&self, task_id: &TaskId) -> Result<OrchestrationTaskRecord> {- let record = self.inner.mark_awaiting(task_id)?;- self.persist(&record)?;- Ok(record)- }-- fn mark_awaiting_with_question(- &self,- task_id: &TaskId,- question: String,- ) -> Result<OrchestrationTaskRecord> {- let record = self.inner.mark_awaiting_with_question(task_id, question)?;- self.persist(&record)?;- Ok(record)- }-- fn complete(- &self,- task_id: &TaskId,- result: OrchestrationTaskResult,- ) -> Result<OrchestrationTaskRecord> {- let record = self.inner.complete(task_id, result)?;- self.persist(&record)?;- Ok(record)- }-- fn fail(&self, task_id: &TaskId, error: String) -> Result<OrchestrationTaskRecord> {- let record = self.inner.fail(task_id, error)?;- self.persist(&record)?;- Ok(record)- }-- fn timeout(&self, task_id: &TaskId, error: String) -> Result<OrchestrationTaskRecord> {- let record = self.inner.timeout(task_id, error)?;- self.persist(&record)?;- Ok(record)- }-- fn request_cancel(&self, task_id: &TaskId) -> Result<OrchestrationControlOutcome> {- let outcome = self.inner.request_cancel(task_id)?;- self.persist_current(task_id)?;- Ok(outcome)- }-- fn mark_cancelled(&self, task_id: &TaskId) -> Result<OrchestrationTaskRecord> {- let record = self.inner.mark_cancelled(task_id)?;- self.persist(&record)?;- Ok(record)- }-- fn kill(&self, task_id: &TaskId) -> Result<OrchestrationControlOutcome> {- let outcome = self.inner.kill(task_id)?;- self.persist_current(task_id)?;- Ok(outcome)- }-- fn set_timeout_ms(&self, task_id: &TaskId, timeout_ms: u64) -> Result<OrchestrationTaskRecord> {- let record = self.inner.set_timeout_ms(task_id, timeout_ms)?;- self.persist(&record)?;- Ok(record)- }-}--/// Opens the document ledger for `repo`, or an in-memory one when the-/// documents cannot be read (degrading like the file ledger does).-pub(super) fn open_or_memory(repo: Repo) -> Arc<dyn TaskStore> {- match DocumentTaskStore::open(repo) {- Ok(store) => Arc::new(store),- Err(error) => {- log::warn!(- "[running_subagents] document task ledger unavailable; using memory: {error}"- );- Arc::new(InMemoryTaskStore::new())- }- }-}--#[cfg(test)]-#[path = "task_ledger_documents_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/agent/orchestration/running_subagents/task_ledger_documents_tests.rs b/crates/openhuman-core/src/agent/orchestration/running_subagents/task_ledger_documents_tests.rsdeleted file mode 100644index 3634c6fa17..0000000000--- a/crates/openhuman-core/src/agent/orchestration/running_subagents/task_ledger_documents_tests.rs+++ /dev/null@@ -1,159 +0,0 @@-use super::*;-use crate::storage::{MemoryStorage, Scope, StorageBackend};-use tinyagents_tasks::{OrchestrationTaskKind, OrchestrationTaskStatus};--fn repo_in(storage: &MemoryStorage, scope: &str) -> Repo {- let scoped = storage.for_scope(&Scope::new(scope).unwrap()).unwrap();- Repo::over(&scoped, DOMAIN, collections)-}--fn spec(id: &str) -> OrchestrationTaskSpec {- OrchestrationTaskSpec::new(id, OrchestrationTaskKind::SubAgent { agent: "a".into() })-}--#[test]-fn transitions_persist_and_replay_on_reopen() {- let storage = MemoryStorage::new();- let store = DocumentTaskStore::open(repo_in(&storage, "local")).unwrap();- store.insert(spec("t1")).unwrap();- store.mark_running(&TaskId::from("t1")).unwrap();- store.insert(spec("t2")).unwrap();- store.mark_running(&TaskId::from("t2")).unwrap();- store.fail(&TaskId::from("t2"), "boom".into()).unwrap();-- let reopened = DocumentTaskStore::open(repo_in(&storage, "local")).unwrap();- let t1 = reopened.get(&TaskId::from("t1")).unwrap();- assert_eq!(t1.status, OrchestrationTaskStatus::Running);- let t2 = reopened.get(&TaskId::from("t2")).unwrap();- assert_eq!(t2.status, OrchestrationTaskStatus::Failed);- assert_eq!(t2.error.as_deref(), Some("boom"));- assert_eq!(reopened.list(OrchestrationTaskFilter::default()).len(), 2);- // pending -> running -> failed- assert_eq!(reopened.history(&TaskId::from("t2")).len(), 3);-}--#[test]-fn cancel_requests_persist() {- let storage = MemoryStorage::new();- let store = DocumentTaskStore::open(repo_in(&storage, "local")).unwrap();- store.insert(spec("t1")).unwrap();- store.mark_running(&TaskId::from("t1")).unwrap();- store.request_cancel(&TaskId::from("t1")).unwrap();- let reopened = DocumentTaskStore::open(repo_in(&storage, "local")).unwrap();- assert_eq!(- reopened.get(&TaskId::from("t1")).unwrap().status,- OrchestrationTaskStatus::CancelRequested- );-}--#[test]-fn scopes_do_not_share_a_ledger() {- let storage = MemoryStorage::new();- let alice = DocumentTaskStore::open(repo_in(&storage, "alice")).unwrap();- alice.insert(spec("t1")).unwrap();- let bob = DocumentTaskStore::open(repo_in(&storage, "bob")).unwrap();- assert!(bob.list(OrchestrationTaskFilter::default()).is_empty());- assert!(bob.get(&TaskId::from("t1")).is_none());- let alice_again = DocumentTaskStore::open(repo_in(&storage, "alice")).unwrap();- assert!(alice_again.get(&TaskId::from("t1")).is_some());-}--fn id(raw: &str) -> TaskId {- TaskId::from(raw)-}--#[test]-fn every_transition_is_written_through() {- let storage = MemoryStorage::new();- let store = DocumentTaskStore::open(repo_in(&storage, "local")).unwrap();- for name in ["a", "b", "c", "d", "e", "f"] {- store.insert(spec(name)).unwrap();- }- store.mark_awaiting(&id("a")).unwrap();- store- .mark_awaiting_with_question(&id("b"), "which one?".into())- .unwrap();- store.mark_running(&id("c")).unwrap();- store- .complete(&id("c"), OrchestrationTaskResult::text("done"))- .unwrap();- store.timeout(&id("d"), "too slow".into()).unwrap();- store.request_cancel(&id("e")).unwrap();- store.mark_cancelled(&id("e")).unwrap();- store.kill(&id("f")).unwrap();- store.set_timeout_ms(&id("a"), 5_000).unwrap();-- let reopened = DocumentTaskStore::open(repo_in(&storage, "local")).unwrap();- let status = |name: &str| reopened.get(&id(name)).unwrap().status;- assert_eq!(status("a"), OrchestrationTaskStatus::Awaiting);- assert_eq!(status("b"), OrchestrationTaskStatus::Awaiting);- assert_eq!(- reopened.get(&id("b")).unwrap().error.as_deref(),- Some("which one?")- );- assert_eq!(status("c"), OrchestrationTaskStatus::Completed);- assert_eq!(status("d"), OrchestrationTaskStatus::TimedOut);- assert_eq!(status("e"), OrchestrationTaskStatus::Cancelled);- assert_eq!(status("f"), OrchestrationTaskStatus::Abandoned);- assert_eq!(reopened.get(&id("a")).unwrap().spec.timeout_ms, Some(5_000));-}--#[test]-fn an_invalid_transition_is_rejected_and_not_written() {- let storage = MemoryStorage::new();- let store = DocumentTaskStore::open(repo_in(&storage, "local")).unwrap();- store.insert(spec("a")).unwrap();- assert!(store.mark_cancelled(&id("a")).is_err());- assert!(store.mark_running(&id("missing")).is_err());- assert_eq!(store.history(&id("a")).len(), 1);-}--#[test]-fn a_malformed_document_is_skipped_on_open() {- let storage = MemoryStorage::new();- let repo = repo_in(&storage, "local");- repo.run(|docs| async move {- docs.put(- TASKS,- "bad",- serde_json::json!({ "record": 1 }),- Precondition::None,- )- .await- .map(|_| ())- })- .unwrap();- let store = DocumentTaskStore::open(repo.clone()).unwrap();- assert!(store.list(OrchestrationTaskFilter::default()).is_empty());- let boxed = open_or_memory(repo);- assert!(boxed.list(OrchestrationTaskFilter::default()).is_empty());-}--#[test]-fn the_ledger_dispatches_to_documents_when_a_backend_is_pinned() {- let storage = MemoryStorage::new();- let workspace = tempfile::tempdir().unwrap();- let repo = repo_in(&storage, "local");- with_override(repo.clone(), || {- let store = super::super::task_ledger::task_store_for_workspace(workspace.path());- store.insert(spec("pinned")).unwrap();- });- // The record is in the documents, and no JSONL file was made.- let reopened = DocumentTaskStore::open(repo).unwrap();- assert!(reopened.get(&id("pinned")).is_some());- assert!(!workspace- .path()- .join(".openhuman/orchestration_tasks.jsonl")- .exists());-}--#[test]-fn the_ledger_uses_the_jsonl_file_with_no_backend() {- let workspace = tempfile::tempdir().unwrap();- let store = super::super::task_ledger::task_store_for_workspace(workspace.path());- store.insert(spec("plain")).unwrap();- assert!(workspace- .path()- .join(".openhuman/orchestration_tasks.jsonl")- .exists());-}