Skip to content

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

feat(flows): run flow events under their owning agent scope

Steven Enamakel0d95879a2558
diff --git a/crates/openhuman-core/src/flows/bus.rs b/crates/openhuman-core/src/flows/bus.rs
index db2a222e68..a196a4d065 100644
--- a/crates/openhuman-core/src/flows/bus.rs
+++ b/crates/openhuman-core/src/flows/bus.rs
@@ -15,6 +15,7 @@
mod tests;
mod dedup_commit;
+mod owner;
mod run_digest;
mod trigger;
diff --git a/crates/openhuman-core/src/flows/bus/dedup_commit.rs b/crates/openhuman-core/src/flows/bus/dedup_commit.rs
index 8116d8a904..9f9fc1aaee 100644
--- a/crates/openhuman-core/src/flows/bus/dedup_commit.rs
+++ b/crates/openhuman-core/src/flows/bus/dedup_commit.rs
@@ -325,7 +325,13 @@ impl EventHandler<DomainEvent> for DedupCommitSubscriber {
status,
} = event
{
- self.handle_finished(flow_id, run_id, status).await;
+ // Settle the run as the agent its flow belongs to (`super::owner`).
+ let owner = super::owner::flow_owner(&self.config, flow_id).await;
+ crate::storage::agents::within_agent(
+ owner.as_deref(),
+ self.handle_finished(flow_id, run_id, status),
+ )
+ .await;
}
}
}
diff --git a/crates/openhuman-core/src/flows/bus/owner.rs b/crates/openhuman-core/src/flows/bus/owner.rs
new file mode 100644
index 0000000000..abc6c2d7bd
--- /dev/null
+++ b/crates/openhuman-core/src/flows/bus/owner.rs
@@ -0,0 +1,64 @@
+//! Which agent a flow belongs to, for the subscribers that act on a flow
+//! named only by id in an event (`FlowScheduleTick`, `FlowRunFinished`).
+//!
+//! A flow saved from inside an agent's context lives in that agent's storage
+//! scope (`crate::storage`). The subscribers run outside any agent, so they
+//! look the flow up here and handle the event as its owner
+//! (`crate::storage::agents::within_agent`); without a storage backend every
+//! flow is `local` and this is a no-op.
+
+use std::collections::HashMap;
+use std::sync::{LazyLock, Mutex};
+
+use crate::config::Config;
+
+/// Flows whose owner this process has resolved (`None` = `local`).
+static OWNERS: LazyLock<Mutex<HashMap<String, Option<String>>>> =
+ LazyLock::new(Default::default);
+
+/// The agent `flow_id` belongs to: `None` for `local`, or when no scope has
+/// the flow (the handler then reports the flow as unknown, as before).
+pub(super) async fn flow_owner(config: &Config, flow_id: &str) -> Option<String> {
+ if crate::storage::installed().is_none() {
+ return None;
+ }
+ if let Some(owner) = OWNERS
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .get(flow_id)
+ .cloned()
+ {
+ return owner;
+ }
+ let found = crate::storage::agents::find_owner("flow owner", || async {
+ matches!(crate::flows::store::get_flow(config, flow_id), Ok(Some(_)))
+ })
+ .await;
+ let Some(owner) = found else {
+ return None;
+ };
+ tracing::debug!(
+ target: "flows",
+ %flow_id,
+ agent = owner.as_deref().unwrap_or("local"),
+ "[flows] resolved the flow's owner"
+ );
+ OWNERS
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .insert(flow_id.to_string(), owner.clone());
+ owner
+}
+
+/// Forgets a cached owner (a removed flow's id may be reused).
+#[cfg_attr(not(test), allow(dead_code))]
+pub(super) fn forget(flow_id: &str) {
+ OWNERS
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .remove(flow_id);
+}
+
+#[cfg(test)]
+#[path = "owner_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-core/src/flows/bus/run_digest.rs b/crates/openhuman-core/src/flows/bus/run_digest.rs
index ce92fdd044..ff340fc83d 100644
--- a/crates/openhuman-core/src/flows/bus/run_digest.rs
+++ b/crates/openhuman-core/src/flows/bus/run_digest.rs
@@ -189,7 +189,13 @@ impl EventHandler<DomainEvent> for FlowRunDigestSubscriber {
status,
} = event
{
- self.handle_finished(flow_id, run_id, status).await;
+ // Settle the run as the agent its flow belongs to (`super::owner`).
+ let owner = super::owner::flow_owner(&self.config, flow_id).await;
+ crate::storage::agents::within_agent(
+ owner.as_deref(),
+ self.handle_finished(flow_id, run_id, status),
+ )
+ .await;
}
}
}
diff --git a/crates/openhuman-core/src/flows/bus/trigger.rs b/crates/openhuman-core/src/flows/bus/trigger.rs
index 9fc7f26695..6c4cbaffa2 100644
--- a/crates/openhuman-core/src/flows/bus/trigger.rs
+++ b/crates/openhuman-core/src/flows/bus/trigger.rs
@@ -199,7 +199,8 @@ impl FlowTriggerSubscriber {
};
let config = self.config.clone();
- tokio::spawn(async move {
+ // Scoped: the run keeps the owner's context the handler entered.
+ crate::core::runtime::spawn_scoped(async move {
// Held for the lifetime of the run; released on drop (including
// on panic) by `InFlightGuard`.
let _guard = guard;
@@ -247,13 +248,28 @@ impl EventHandler<DomainEvent> for FlowTriggerSubscriber {
async fn handle(&self, event: &DomainEvent) {
match event {
- DomainEvent::FlowScheduleTick { flow_id } => self.handle_schedule_tick(flow_id).await,
+ // The flow runs as the agent it belongs to (`super::owner`).
+ DomainEvent::FlowScheduleTick { flow_id } => {
+ let owner = super::owner::flow_owner(&self.config, flow_id).await;
+ crate::storage::agents::within_agent(
+ owner.as_deref(),
+ self.handle_schedule_tick(flow_id),
+ )
+ .await
+ }
+ // Every scope's flows may listen for this trigger: match them in
+ // each, so each run starts as its flow's owner.
DomainEvent::ComposioTriggerReceived {
toolkit,
trigger,
payload,
..
- } => self.handle_app_event(toolkit, trigger, payload).await,
+ } => {
+ crate::storage::agents::for_each_scope("flows app_event", || {
+ self.handle_app_event(toolkit, trigger, payload)
+ })
+ .await;
+ }
DomainEvent::WebhookIncomingRequest { .. } => {
// Best-effort deviation (documented, not silently skipped —
// see `flows::ops::log_webhook_trigger_deferred` for the
diff --git a/crates/openhuman-core/src/storage/agents.rs b/crates/openhuman-core/src/storage/agents.rs
index 1fbc6eaf45..0fc78814aa 100644
--- a/crates/openhuman-core/src/storage/agents.rs
+++ b/crates/openhuman-core/src/storage/agents.rs
@@ -171,6 +171,21 @@ pub async fn within_agent<F: Future>(agent: Option<&str>, fut: F) -> F::Output {
}
}
+/// The scope a record lives in, for background work that holds only its id
+/// (an event naming a flow, a job, a device): the first scope — `local`
+/// first, then each known agent ([`for_each_scope`]) — where `probe` finds
+/// it. `Some(None)` is `local`, `Some(Some(agent))` an agent, `None` nowhere.
+pub async fn find_owner<F, Fut>(label: &str, probe: F) -> Option<Option<String>>
+where
+ F: Fn() -> Fut,
+ Fut: Future<Output = bool>,
+{
+ for_each_scope(label, probe)
+ .await
+ .into_iter()
+ .find_map(|(agent, found)| found.then_some(agent))
+}
+
/// Runs `step` for every storage scope background work must cover: once
/// under the current context (the `local` scope, outside SaaS mode), then
/// once per known agent ([`for_each_agent`]). Each result is returned with