Skip to content

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

feat(flows): add bounded CapsHost agent run registry

Steven Enamakelb61e3483977a
diff --git a/crates/openhuman-core/src/flows/caps_host/binding.rs b/crates/openhuman-core/src/flows/caps_host/binding.rs
index 0066213cee..59cfcaa1af 100644
--- a/crates/openhuman-core/src/flows/caps_host/binding.rs
+++ b/crates/openhuman-core/src/flows/caps_host/binding.rs
@@ -1,7 +1,10 @@
//! One trusted `CapsHost` callback object for a single TinyFlows run.
use std::future::Future;
-use std::{collections::HashMap, sync::Arc};
+use std::{
+ collections::{HashMap, HashSet, VecDeque},
+ sync::Arc,
+};
use crate::config::Config;
use crate::core::runtime::DispatchCtx;
@@ -29,8 +32,112 @@ pub(crate) struct CapsHostBinding {
pub(crate) security: Arc<crate::security::SecurityPolicy>,
pub(crate) approval: crate::security::approval::ApprovalTurnContext,
pub(crate) cancellation: tokio_util::sync::CancellationToken,
- pub(crate) agent_runs:
- tokio::sync::Mutex<HashMap<String, Arc<tokio::sync::Mutex<AgentRunState>>>>,
+ pub(crate) agent_runs: tokio::sync::Mutex<AgentRunRegistry>,
+}
+
+/// Bounds invocation records and cancel-before-start tombstones retained by
+/// one run binding. Once either capacity is exhausted, new ids fail closed for
+/// the remaining lifetime of the binding.
+const MAX_AGENT_RUN_RECORDS: usize = 10_000;
+const MAX_AGENT_CANCEL_TOMBSTONES: usize = 4_096;
+
+pub(crate) struct AgentRunEntry {
+ pub(crate) handle: String,
+ pub(crate) state: Arc<tokio::sync::Mutex<AgentRunState>>,
+ pub(crate) cancellation: tokio_util::sync::CancellationToken,
+}
+
+pub(crate) struct AgentRunAdmission {
+ pub(crate) entry: AgentRunEntry,
+ pub(crate) start_task: bool,
+ pub(crate) cancelled_before_admission: bool,
+}
+
+#[derive(Default)]
+pub(crate) struct AgentRunRegistry {
+ by_request_id: HashMap<String, AgentRunEntry>,
+ by_handle: HashMap<String, Arc<tokio::sync::Mutex<AgentRunState>>>,
+ cancelled_before_start: HashSet<String>,
+ cancellation_order: VecDeque<String>,
+ reject_new_ids: bool,
+}
+
+impl AgentRunRegistry {
+ pub(crate) fn admit(
+ &mut self,
+ client_request_id: String,
+ state: Arc<tokio::sync::Mutex<AgentRunState>>,
+ cancellation: tokio_util::sync::CancellationToken,
+ ) -> Result<AgentRunAdmission, String> {
+ if let Some(entry) = self.by_request_id.get(&client_request_id) {
+ return Ok(AgentRunAdmission {
+ entry: entry.clone(),
+ start_task: false,
+ cancelled_before_admission: false,
+ });
+ }
+ if self.reject_new_ids {
+ return Err("CapsHost agent invocation capacity is exhausted".to_owned());
+ }
+ if self.by_request_id.len() >= MAX_AGENT_RUN_RECORDS {
+ self.reject_new_ids = true;
+ return Err("CapsHost agent invocation capacity is exhausted".to_owned());
+ }
+
+ let cancelled_before_admission = self.cancelled_before_start.remove(&client_request_id);
+ if cancelled_before_admission {
+ self.cancellation_order
+ .retain(|request_id| request_id != &client_request_id);
+ cancellation.cancel();
+ }
+ let entry = AgentRunEntry {
+ handle: uuid::Uuid::new_v4().simple().to_string(),
+ state: Arc::clone(&state),
+ cancellation,
+ };
+ self.by_handle.insert(entry.handle.clone(), state);
+ self.by_request_id
+ .insert(client_request_id, entry.clone());
+ Ok(AgentRunAdmission {
+ entry,
+ start_task: !cancelled_before_admission,
+ cancelled_before_admission,
+ })
+ }
+
+ pub(crate) fn cancel(&mut self, client_request_id: String) {
+ if let Some(entry) = self.by_request_id.get(&client_request_id) {
+ entry.cancellation.cancel();
+ return;
+ }
+ if self.cancelled_before_start.contains(&client_request_id) {
+ return;
+ }
+ if self.cancelled_before_start.len() >= MAX_AGENT_CANCEL_TOMBSTONES {
+ self.reject_new_ids = true;
+ return;
+ }
+ self.cancelled_before_start
+ .insert(client_request_id.clone());
+ self.cancellation_order.push_back(client_request_id);
+ }
+
+ pub(crate) fn state_for_handle(
+ &self,
+ handle: &str,
+ ) -> Option<Arc<tokio::sync::Mutex<AgentRunState>>> {
+ self.by_handle.get(handle).cloned()
+ }
+}
+
+impl Clone for AgentRunEntry {
+ fn clone(&self) -> Self {
+ Self {
+ handle: self.handle.clone(),
+ state: Arc::clone(&self.state),
+ cancellation: self.cancellation.clone(),
+ }
+ }
}
impl Drop for CapsHostRegistration {
@@ -93,7 +200,7 @@ pub(crate) async fn serve(
security,
approval,
cancellation: tokio_util::sync::CancellationToken::new(),
- agent_runs: tokio::sync::Mutex::new(HashMap::new()),
+ agent_runs: tokio::sync::Mutex::new(AgentRunRegistry::default()),
});
let path = format!(
"/ai/tinyhumans/openhuman/CapsHost/{}",
diff --git a/crates/openhuman-core/src/flows/mod.rs b/crates/openhuman-core/src/flows/mod.rs
index 6deac9a867..88b83597ed 100644
--- a/crates/openhuman-core/src/flows/mod.rs
+++ b/crates/openhuman-core/src/flows/mod.rs
@@ -2,9 +2,7 @@
//! create/get/list/update/delete/enable/run, backed by SQLite. Mirrors
//! `crates/openhuman-core/src/cron/`'s module shape.
//!
-//! Business logic lives in [`ops`]; persistence in `store` (private, with a
-//! handful of functions re-exported below for the capability seam's
-//! `tinyflows_sqlite::flows::SqliteStateStore`); the RPC/CLI
+//! Business logic lives in [`ops`]; workflow definitions in `store`; the RPC/CLI
//! controller surface in `schemas` (private, re-exported below).
//!
//! # Gate shape — leaf, not facade
@@ -52,16 +50,6 @@ pub use schemas::{
all_controller_schemas as all_flows_controller_schemas,
all_registered_controllers as all_flows_registered_controllers,
};
-// `kv_get`/`kv_set` are re-exported (not just `pub(crate)`-visible within this
-// domain's own module tree) because `tinyflows_sqlite::flows::SqliteStateStore`
-// (built in `crates/openhuman-core/src/flows/tinyflows/caps/ops.rs`) lives in a sibling module and needs
-// them to implement `tinyflows::caps::StateStore` without duplicating the
-// `flow_state` table's persistence logic.
-// `upsert_flow_run_step` is likewise re-exported for the tinyflows seam: the
-// live run observer (`tinyflows::observability::FlowRunObserver`, issue G2)
-// lives in the sibling `tinyflows` domain and persists each finished step onto
-// the `flow_runs` row through this function as the run executes.
-pub use store::{kv_get, kv_set, upsert_flow_run_step};
pub use {node_contracts::all_node_kind_contracts, node_contracts::node_kind_contract};
// Flow memory scoping (`flow:<id>` tags over memory v2) lives in
// `memory_tools`, the sibling that owns the agent tools; the digest
diff --git a/crates/openhuman-core/src/flows/ops.rs b/crates/openhuman-core/src/flows/ops.rs
index 63eb9cff92..1a6589e56d 100644
--- a/crates/openhuman-core/src/flows/ops.rs
+++ b/crates/openhuman-core/src/flows/ops.rs
@@ -19,9 +19,8 @@
//! | `triggers` | enable/disable, trigger binding, boot reconciliation, trigger warnings |
//! | `connections` | the `connection_ref` picker list and required-connection CTAs |
//! | `run` | `flows_run` / `flows_run_detached` entry points and run prep |
-//! | `execution` | the shared run body, origin, Langfuse export, approval notification |
+//! | `execution` | Langfuse export and approval notification |
//! | `resume` | `flows_resume` and the T-M1 graph pin |
-//! | `run_rows` | `flow_runs` row persistence, drop-guard finalizer, step settlement |
//! | `run_management` | cancel, run listing/pruning, TTL and boot sweeps |
//! | `discovery` | Flow Scout discovery and suggestion lifecycle |
//! | `streaming` | copilot/scout progress bridge onto the web-channel socket |
@@ -46,15 +45,11 @@ use tinyflows::triggers::graph_trigger_warnings;
pub(crate) use tinyflows_catalog::graph_policy::{
enforce_side_effect_approval, graph_has_actionable_nodes, trigger_is_automatic,
};
-use tokio_util::sync::CancellationToken;
-
-use crate::agent::turn_origin::{with_origin, AgentTurnOrigin};
use crate::config::Config;
use crate::core::Outcome;
use crate::flows::bus;
use crate::flows::draft_store;
use crate::flows::store;
-use crate::security::approval::{ApprovalChatContext, ApprovalTurnContext};
use tinyflows_catalog::build_registry;
use tinyflows_catalog::types::{
FlowConnection, FlowRunTrigger, FlowSuggestion, SuggestionStatus,
@@ -91,15 +86,13 @@ const GRAPH_CHANGED_SINCE_PARK_ERROR: &str = "the workflow changed after this ru
// Phase 2 — autonomy-tier gating of acting flow nodes
// ─────────────────────────────────────────────────────────────────────────────
//
-// A `flows_run` / `flows_resume` executes under a `TrustedAutomation { Workflow }`
-// origin (see `workflow_origin` below), but the *acting power* of a run is still
-// bounded by the user's `[autonomy]` tier — the same `SecurityPolicy`
-// (`crates/openhuman-core/src/security/`) the agent tool-loop honors, built via
-// `SecurityPolicy::from_config(&config.autonomy, …)` inside
-// `tinyflows::caps::build_capabilities`.
+// A `flows_run` / `flows_resume` executes under a trusted workflow origin, but
+// its acting power is still bounded by the user's `[autonomy]` tier. The
+// `CapsHost` adapter applies OpenHuman policy and approvals at the host
+// callback; TinyFlows owns graph execution and lifecycle settlement.
//
// Before an acting node dispatches, its capability adapter
-// (`crates/openhuman-core/src/flows/tinyflows/caps.rs::enforce_node_tier_gate`) maps the node to a
+// (`crates/openhuman-core/src/flows/caps_host/`) maps the node to a
// `CommandClass` and consults `SecurityPolicy::gate_decision`. `Block` refuses
// outright (`[policy-blocked]` error, no dispatch); `Prompt`/`Allow` fall through
// to the process-global `ApprovalGate`, which performs the human round-trip for
@@ -118,7 +111,7 @@ const GRAPH_CHANGED_SINCE_PARK_ERROR: &str = "the workflow changed after this ru
// ¹ tool_call routes through the deny-by-default curation/scope gate plus the
// ApprovalGate rather than `gate_decision`; a Network-class Composio action
// still prompts under supervised/full and the curation gate is the hard
-// allowlist. See `caps.rs::OpenHumanTools`.
+// allowlist. See `caps_host::service_tools`.
//
// `Network` is never `Allow` in any tier (always `Prompt` when not blocked), so
// even a full-tier http_request node prompts unless a pre-declared trust root /
diff --git a/crates/openhuman-core/src/flows/tinyflows/mod.rs b/crates/openhuman-core/src/flows/tinyflows/mod.rs
new file mode 100644
index 0000000000..8f651cb080
--- /dev/null
+++ b/crates/openhuman-core/src/flows/tinyflows/mod.rs
@@ -0,0 +1,8 @@
+//! TinyFlows' framework-neutral graph vocabulary used by OpenHuman's
+//! authoring and validation adapters.
+//!
+//! Execution, capabilities, persistence, checkpoints, and run observation are
+//! served through the TinyBus module contract. This module re-exports only the
+//! generic graph model and legacy graph migration needed by host-facing APIs.
+
+pub use ::tinyflows::{migrate, model};
diff --git a/crates/openhuman-core/src/modules/tinyflows.rs b/crates/openhuman-core/src/modules/tinyflows.rs
index 5ebf6186af..5e3d564848 100644
--- a/crates/openhuman-core/src/modules/tinyflows.rs
+++ b/crates/openhuman-core/src/modules/tinyflows.rs
@@ -58,7 +58,7 @@ mod imp {
#[cfg(not(test))]
use crate::modules::ops;
use crate::modules::runtime;
- use tinybus::{ObjectPath, Proxy};
+ use tinybus::{InterfaceName, InterfaceVersion, ObjectPath, PeerManifest, Proxy, Version};
use tinyflows_bus::schedule;
/// Longest a store or maths call waits. Job execution is not a call to the
@@ -70,6 +70,10 @@ mod imp {
/// (an agent turn, a shell command) inside the call.
const RUN_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(2 * 60 * 60);
+ /// Serialize CapsHost manifest read-modify-announce operations on the
+ /// process-wide module-runtime peer.
+ static CAPS_HOST_MANIFEST_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
+
/// Make sure the module serves. In unit tests this attaches the linked
/// module built into the test binary; everywhere else it goes through the
/// registry resolver (release, `source` or `linked` per configuration).
@@ -263,6 +267,7 @@ mod imp {
path: String,
object: impl tinybus::service::Interface + 'static,
) -> Result<ServedObjectRegistration, String> {
+ let announces_caps_host = object.name().as_str() == tinyflows_bus::runs::CAPS_INTERFACE;
let runtime = runtime::runtime()
.await
.map_err(|error| format!("the module bus is unavailable: {error}"))?;
@@ -275,15 +280,46 @@ mod imp {
.await
.map_err(|error| error.to_string())?;
connection
- .serve_at(object_path, object)
+ .serve_at(object_path.clone(), object)
.await
.map_err(|error| error.to_string())?;
+ if announces_caps_host
+ && let Err(error) = announce_caps_host_v2(&connection).await
+ {
+ let _ = connection.unserve(&object_path).await;
+ return Err(error);
+ }
Ok(ServedObjectRegistration(path))
})
.await
.map_err(|error| format!("serving the host object did not finish: {error}"))?
}
+ async fn announce_caps_host_v2(connection: &tinybus::Connection) -> Result<(), String> {
+ let _lock = CAPS_HOST_MANIFEST_LOCK.lock().await;
+ let interface = InterfaceName::new(tinyflows_bus::runs::CAPS_INTERFACE)
+ .map_err(|error| error.to_string())?;
+ let mut manifest = connection
+ .manifest_of(HOST_BUS_NAME)
+ .await
+ .map_err(|error| error.to_string())?
+ .unwrap_or_else(|| PeerManifest::new("openhuman-module-host"));
+ let caps_host = InterfaceVersion::provided(interface.clone(), Version::new(2, 0, 0));
+ if let Some(provided) = manifest
+ .provides
+ .iter_mut()
+ .find(|provided| provided.interface == interface)
+ {
+ *provided = caps_host;
+ } else {
+ manifest.provides.push(caps_host);
+ }
+ connection
+ .announce(&manifest)
+ .await
+ .map_err(|error| format!("announcing the CapsHost v2 contract failed: {error}"))
+ }
+
/// Serve two interfaces at one object path and return an RAII token for
/// their shared registration. The token is created on the module runtime
/// task, so if the caller is cancelled while this operation is in flight,