Skip to content

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

chore: files changed crates/openhuman-core/src/flows/ops.rs,crates/openhuman-core/src/flows/ops/run.

Steven Enamakele44fb9c6b55d
diff --git a/crates/openhuman-core/src/flows/ops.rs b/crates/openhuman-core/src/flows/ops.rs
index 05a6cea993..af50c665da 100644
--- a/crates/openhuman-core/src/flows/ops.rs
+++ b/crates/openhuman-core/src/flows/ops.rs
@@ -156,7 +156,6 @@ pub use connections::*;
pub use definitions::*;
pub use discovery::*;
pub use drafts::*;
-use execution::*;
pub(crate) use inference_readiness::*;
pub use resume::*;
pub use run::*;
diff --git a/crates/openhuman-core/src/flows/ops/run.rs b/crates/openhuman-core/src/flows/ops/run.rs
index c648543304..496ac5a1bd 100644
--- a/crates/openhuman-core/src/flows/ops/run.rs
+++ b/crates/openhuman-core/src/flows/ops/run.rs
@@ -1,27 +1,9 @@
use super::*;
-/// Runs a saved flow end-to-end: compile → build capabilities → durable
-/// checkpointed run → record the outcome onto the flow's summary fields and
-/// into a `flow_runs` history row.
-///
-/// Uses `tinyflows::engine::run_with_checkpointer` (not the simpler `run`) so
-/// a run that pauses at a human-in-the-loop approval gate is durably
-/// checkpointed and can survive a process restart (resumed later via
-/// [`flows_resume`]; see
-/// `my_docs/ohxtf/b1-engine-seam-domain/05-checkpointer-and-state.md`).
-///
-/// The whole run is scoped under `AgentTurnOrigin::TrustedAutomation {
-/// Workflow }` (issue B2) regardless of caller (an interactive RPC "Run" or
-/// an automatic trigger dispatch from `flows::bus::FlowTriggerSubscriber`):
-/// the trust argument is about the *flow* (a saved, validated graph whose
-/// `tool_call`/`http_request` nodes are pre-declared), not about who started
-/// the run — see `TrustedAutomationSource::Workflow`'s doc and
-/// `my_docs/ohxtf/b2-triggers-trust/01-triggers-and-trust.md` §3.
-/// `input` is the free-form trigger payload (reachable as `=run.trigger.…`);
-/// `inputs` supplies values for the flow's *declared* workflow inputs by name
-/// (reachable as `=inputs.<name>`). The two are separate channels — see
-/// [`tinyflows::engine::RunInput`]. A declared-input problem (missing required
-/// value, wrong type, undeclared key) is rejected before any run row exists.
+/// Run a saved workflow and return the existing `{output,pending_approvals,
+/// thread_id}` controller result after the TinyFlows module parks or settles
+/// the run. The module validates inputs and graph compilation before it
+/// creates any durable run state.
pub async fn flows_run(
ctx: &crate::core::runtime::DispatchCtx,
config: &Config,
@@ -30,61 +12,29 @@ pub async fn flows_run(
inputs: serde_json::Map<String, Value>,
trigger: FlowRunTrigger,
) -> Result<Outcome<Value>, String> {
- // Prep synchronously (validate + compile-check + resolve inputs + mint the
- // run id), insert the initial `running` row, and announce it, then hand off
- // to the shared run body. Both the synchronous "Run" RPC path (this fn) and
- // the detached agent path ([`flows_run_detached`]) reuse `run_flow_body` so
- // a single [`RunRowFinalizer`] guards the row on every exit — bug B42.
let prepared = prepare_flow_run(ctx, config, flow_id, &inputs).await?;
- let thread_id = prepared.thread_id.clone();
- let no_actionable_nodes = prepared.no_actionable_nodes;
- let resolved_inputs = prepared.inputs;
-
- // Register BEFORE the row exists, so a `flows_cancel_run` can never observe
- // a `running` row that no live run owns (see [`run_flow_body`]'s doc).
- let (cancel_token, run_guard) = run_registry::register(&thread_id);
- start_flow_run_row(config, &thread_id, flow_id);
- publish_flow_run_started(flow_id, &thread_id);
-
- run_flow_body(
- ctx.clone(),
- Arc::new(config.clone()),
- prepared.flow,
- flow_id.to_string(),
- thread_id,
+ let (session, mut events) = crate::flows::runs_adapter::start_run(
+ ctx,
+ config,
+ &prepared.flow,
+ &prepared.run_id,
input,
- resolved_inputs,
+ inputs,
trigger,
- no_actionable_nodes,
- cancel_token,
- run_guard,
)
- .await
+ .await?;
+ let result = crate::flows::runs_adapter::wait_for_outcome(
+ &mut events,
+ &prepared.run_id,
+ 0,
+ )
+ .await?;
+ drop(session);
+ Ok(run_outcome(result, prepared.no_actionable_nodes))
}
-/// Agent-initiated `run_flow` entry point (bug B41). Unlike [`flows_run`], this
-/// does NOT block on the engine: the tinyagents harness caps a single tool call
-/// at 120s, but any flow whose first real node is a live-research agent node
-/// (`web_search` + `web_fetch` + `parallel_research`) inherently runs longer
-/// than that, so a blocking `run_flow` tool call could *never* succeed for a
-/// realistic flow — it died at exactly 120s, orphaning the run row (bug B42).
-///
-/// Instead this validates + compile-checks the flow synchronously (so a broken
-/// flow still returns an immediate, actionable error to the agent), inserts the
-/// `running` row, publishes `FlowRunStarted`, then spawns [`run_flow_body`] on a
-/// background task and returns `{ run_id, status: "running", detached: true }`
-/// in well under 120s. The copilot already polls `get_flow_run(run_id)` (seen
-/// in live traces), so it observes the run settle to a terminal state on its
-/// own cadence. Also exposed over RPC as `flows.run_detached` (see
-/// `schemas::handle_run_detached`) — the UI "Run" control (canvas + Workflows
-/// list) calls that entry point directly, and the trigger bus
-/// (`flows::bus::spawn_run`) fires runs the same fire-and-forget way. Combined
-/// with B42's finalizer + boot sweep, a detached run ALWAYS settles to a
-/// terminal row even if the process dies mid-run.
-///
-/// `input` / `inputs` mean exactly what they do on [`flows_run`]: the trigger
-/// payload and the flow's declared inputs. Both are validated synchronously, so
-/// the agent still gets an immediate, actionable error for a bad call.
+/// Start an agent-requested workflow without waiting for its engine result.
+/// The RPC response remains the detached admission acknowledgement.
pub async fn flows_run_detached(
ctx: &crate::core::runtime::DispatchCtx,
config: &Config,
@@ -94,67 +44,25 @@ pub async fn flows_run_detached(
trigger: FlowRunTrigger,
) -> Result<Outcome<Value>, String> {
let prepared = prepare_flow_run(ctx, config, flow_id, &inputs).await?;
- let thread_id = prepared.thread_id.clone();
- let no_actionable_nodes = prepared.no_actionable_nodes;
- let resolved_inputs = prepared.inputs;
-
- // Register BEFORE the `run_id` becomes observable to the agent. The spawned
- // task below may not be polled for some time, so registering inside it
- // would leave a window where a `flows_cancel_run` on the returned `run_id`
- // sees no in-flight run, settles the row `cancelled` + drops the
- // checkpoint, and the background run then executes the flow's real side
- // effects anyway and overwrites that terminal status. Registering here
- // means such a cancel always takes the signalled branch and this run's own
- // cancellation arm unwinds it. See [`run_flow_body`]'s doc.
- let (cancel_token, run_guard) = run_registry::register(&thread_id);
- start_flow_run_row(config, &thread_id, flow_id);
- publish_flow_run_started(flow_id, &thread_id);
-
- tracing::info!(
- target: "flows",
- flow_id = %flow_id,
- run_id = %thread_id,
- "[flows] flows_run_detached: registered + spawning background run; returning run_id immediately"
- );
-
- let config_arc = Arc::new(config.clone());
- let body_ctx = ctx.clone();
- let flow = prepared.flow;
- let flow_id_owned = flow_id.to_string();
- let body_thread_id = thread_id.clone();
- tokio::spawn(crate::core::runtime::context::CoreContext::propagate(
- async move {
- if let Err(e) = run_flow_body(
- body_ctx,
- config_arc,
- flow,
- flow_id_owned,
- body_thread_id,
- input,
- resolved_inputs,
- trigger,
- no_actionable_nodes,
- cancel_token,
- run_guard,
- )
- .await
- {
- // The row is already reconciled by the body's terminal write /
- // finalizer — this only logs that the detached run ended in error.
- tracing::warn!(target: "flows", error = %e, "[flows] flows_run_detached: background run ended with error (row already reconciled)");
- }
- },
- ));
-
+ let (_session, _events) = crate::flows::runs_adapter::start_run(
+ ctx,
+ config,
+ &prepared.flow,
+ &prepared.run_id,
+ input,
+ inputs,
+ trigger,
+ )
+ .await?;
let result = json!({
- "run_id": thread_id,
+ "run_id": prepared.run_id,
"flow_id": flow_id,
"status": "running",
"detached": true,
});
Ok(Outcome::single_log(
result,
- format!("flow run started (detached): {thread_id}"),
+ format!("flow run started (detached): {}", prepared.run_id),
))
}
@@ -169,122 +77,79 @@ pub(crate) async fn flows_run_copilot(
flows_run_detached(ctx, config, flow_id, input, inputs, FlowRunTrigger::Rpc).await
}
-/// A validated, ready-to-execute flow run: the loaded [`Flow`], the freshly
-/// minted `thread_id` (== run id / checkpointer key), and whether the graph has
-/// no actionable nodes. Produced by [`prepare_flow_run`] and consumed by both
-/// `flows_run` entry points.
+fn run_outcome(
+ result: crate::flows::runs_adapter::RunOutcome,
+ no_actionable_nodes: bool,
+) -> Outcome<Value> {
+ const NO_ACTIONABLE_NODES_NOTE: &str = "This flow's graph has no actionable nodes beyond \
+ its trigger (no downstream action nodes, or no edges connecting them) — the run \
+ completed without doing anything. Add and wire up at least one action node.";
+
+ let status = result.status.clone();
+ let mut value = json!({
+ "output": result.output,
+ "pending_approvals": result.pending_approvals,
+ "thread_id": result.run_id,
+ });
+ let mut logs = vec![format!("flow run {status}")];
+ if no_actionable_nodes {
+ value["note"] = json!(NO_ACTIONABLE_NODES_NOTE);
+ logs.push(NO_ACTIONABLE_NODES_NOTE.to_string());
+ }
+ Outcome::new(value, logs)
+}
+
+/// A validated host envelope for one upcoming Runs.StartRun call.
pub(super) struct PreparedFlowRun {
pub(super) flow: Flow,
- pub(super) thread_id: String,
+ pub(super) run_id: String,
pub(super) no_actionable_nodes: bool,
- /// The flow's declared inputs resolved against the caller's values —
- /// defaults applied, one entry per declaration.
- pub(super) inputs: serde_json::Map<String, Value>,
}
-/// Synchronous prep shared by [`flows_run`] and [`flows_run_detached`]: loads
-/// the flow, warns on an actionless graph, rejects an engine-incompatible
-/// topology, compile-checks the graph so a broken flow fails fast *before* any
-/// `running` row is inserted, resolves the caller's declared-input values, and
-/// mints the run's `thread_id`. Returns an error (never a wedged row) if the
-/// flow can't run at all.
-///
-/// Input resolution happens *here* rather than being left to the engine so a
-/// bad call never creates a `running` row, a thread id, or a registry entry.
-/// The engine re-resolves the same values (it is the authority on its own
-/// contract); doing it twice is cheap and keeps this host from having to trust
-/// its own copy of the rules.
+/// Perform OpenHuman-owned checks before the module admits a run. Inference
+/// readiness stays here so an unavailable provider fails before StartRun,
+/// while graph compatibility, compilation, declared-input validation, row
+/// creation, and execution remain module-owned.
pub(super) async fn prepare_flow_run(
ctx: &crate::core::runtime::DispatchCtx,
config: &Config,
flow_id: &str,
- inputs: &serde_json::Map<String, Value>,
+ _inputs: &serde_json::Map<String, Value>,
) -> Result<PreparedFlowRun, String> {
let flow = store::get_flow(config, flow_id)
- .map_err(|e| e.to_string())?
+ .map_err(|error| error.to_string())?
.ok_or_else(|| format!("flow '{flow_id}' not found"))?;
-
- // Live finding: a graph with no actionable nodes (only a `trigger`, or a
- // `trigger` plus nodes with no edges wiring them up) compiles and "runs"
- // cleanly but does nothing — and previously reported
- // `status="completed" pending_approvals=0` indistinguishably from a real
- // run, reading as "triggered but nothing happened" was actually a
- // success. Surface it loudly instead of letting it pass silently: warn
- // now (independent of how the run below turns out), and attach a
- // human-readable note to the returned outcome so the UI can show
- // "nothing to run" rather than a bare "completed".
let no_actionable_nodes = !graph_has_actionable_nodes(&flow.graph);
if no_actionable_nodes {
tracing::warn!(
target: "flows",
- flow_id = %flow_id,
+ flow_id,
"[flows] flows_run: flow has no actionable nodes — nothing to execute"
);
}
- // `store::get_flow` already ran the stored `graph_json` through
- // `tinyflows::migrate::migrate` before deserializing, so `flow.graph` is
- // always on the current schema here.
- //
- // Author-time validation cannot protect definitions persisted by an older
- // OpenHuman build. Re-check immediately before compilation so an upgrade
- // fails explicitly instead of silently committing incomplete merge data.
if let Err(error) = ensure_config_aware_engine_compatible(ctx, config, &flow.graph).await {
tracing::warn!(
target: "flows",
- flow_id = %flow_id,
+ flow_id,
%error,
"[flows] flows_run: rejected — unsupported engine topology"
);
return Err(error);
}
- // Compile-check up front so a structurally broken graph fails the caller
- // immediately, before a `running` row exists. `run_flow_body` recompiles
- // (cheap) to actually execute.
- tinyflows::compiler::compile(&flow.graph).map_err(|e| e.to_string())?;
- // Declared inputs, before anything observable exists for this run.
- let resolved_inputs =
- tinyflows::model::resolve_inputs(&flow.graph.inputs, inputs).map_err(|e| {
- tracing::warn!(
- target: "flows",
- flow_id = %flow_id,
- input = %e.input_name(),
- code = %e.code(),
- "[flows] flows_run: rejected — bad workflow input"
- );
- e.to_string()
- })?;
-
- let thread_id = format!("flow:{flow_id}:{}", uuid::Uuid::new_v4());
- tracing::debug!(
- target: "flows",
- flow_id = %flow_id,
- thread_id = %thread_id,
- require_approval = flow.require_approval,
- "[flows] flows_run: prepared checkpointed run"
- );
+ let inference_errors = validate_inference_readiness(ctx, config, &flow.graph).await;
+ if !inference_errors.is_empty() {
+ return Err(format!(
+ "This flow's AI step needs a working AI provider to run. {}",
+ inference_errors.join(" ")
+ ));
+ }
+ let run_id = format!("flow:{flow_id}:{}", uuid::Uuid::new_v4());
Ok(PreparedFlowRun {
flow,
- thread_id,
+ run_id,
no_actionable_nodes,
- inputs: resolved_inputs,
})
}
-
-/// Announces a freshly-started run on the global event bus so the frontend run
-/// list flips to `running` immediately. Factored out of [`flows_run`] so both
-/// entry points publish identically.
-fn publish_flow_run_started(flow_id: &str, thread_id: &str) {
- tracing::debug!(
- target: "flows",
- flow_id = %flow_id,
- run_id = %thread_id,
- "[flows] flows_run: publishing FlowRunStarted"
- );
- crate::core::bus::BUS.publish(crate::core::events::DomainEvent::FlowRunStarted {
- flow_id: flow_id.to_string(),
- run_id: thread_id.to_string(),
- });
-}
diff --git a/crates/openhuman-core/src/flows/runs_adapter.rs b/crates/openhuman-core/src/flows/runs_adapter.rs
index eb417ec5d7..b151777384 100644
--- a/crates/openhuman-core/src/flows/runs_adapter.rs
+++ b/crates/openhuman-core/src/flows/runs_adapter.rs
@@ -22,12 +22,13 @@ use crate::modules::tinyflows as module;
const RUN_TIMEOUT_MS: u64 = 600_000;
-pub(crate) use session::{RunKey, RunSession, run_bindings};
+pub(crate) use session::{RunKey, RunSession};
/// Callback authorities retained for one owner-scoped flow run.
pub(crate) struct RunBindings {
catalog: Arc<CatalogStorageRegistration>,
caps: Arc<CapsHostRegistration>,
+ pub(crate) flow: Flow,
pub(crate) flow_id: String,
pub(crate) run_id: String,
pub(crate) require_approval: bool,
@@ -61,21 +62,28 @@ pub(crate) struct RunOutcome {
/// Typed result returned to the existing `flows_resume` controller.
pub(crate) type ResumeOutcome = RunOutcome;
+/// Return the retained bindings only for the exact owner scope and opaque run
+/// id. This key is shared with the module's live Poll/Cancel owner identity.
+pub(crate) fn run_bindings(
+ storage: &tinyflows_bus::catalog::CatalogStorage,
+ run_id: &str,
+) -> Option<Arc<RunBindings>> {
+ session::get(storage, run_id).map(|session| session.current_bindings())
+}
+
/// Retain one run's owner callback and its per-run capability callback.
pub(crate) async fn register_bindings(
ctx: &DispatchCtx,
config: &Config,
- flow_id: &str,
+ flow: &Flow,
run_id: &str,
- require_approval: bool,
) -> Result<Arc<RunBindings>, String> {
let catalog = catalog_storage::register(ctx, config).await?;
register_with_catalog(
ctx,
config,
- flow_id,
+ flow,
run_id,
- require_approval,
catalog,
)
.await
@@ -84,26 +92,26 @@ pub(crate) async fn register_bindings(
async fn register_with_catalog(
ctx: &DispatchCtx,
config: &Config,
- flow_id: &str,
+ flow: &Flow,
run_id: &str,
- require_approval: bool,
catalog: Arc<CatalogStorageRegistration>,
) -> Result<Arc<RunBindings>, String> {
let caps = caps_host::serve(
ctx.clone(),
Arc::new(config.clone()),
- flow_id.to_owned(),
+ flow.id.clone(),
run_id.to_owned(),
- require_approval,
+ flow.require_approval,
Arc::clone(&catalog),
)
.await?;
Ok(Arc::new(RunBindings {
catalog,
caps: Arc::new(caps),
- flow_id: flow_id.to_owned(),
+ flow: flow.clone(),
+ flow_id: flow.id.clone(),
run_id: run_id.to_owned(),
- require_approval,
+ require_approval: flow.require_approval,
}))
}
@@ -117,14 +125,7 @@ pub(crate) async fn start_run(
inputs: serde_json::Map<String, Value>,
trigger: FlowRunTrigger,
) -> Result<(Arc<RunSession>, tokio::sync::mpsc::UnboundedReceiver<runs::RunEvent>), String> {
- let bindings = register_bindings(
- ctx,
- config,
- &flow.id,
- run_id,
- flow.require_approval,
- )
- .await?;
+ let bindings = register_bindings(ctx, config, flow, run_id).await?;
let session = RunSession::new(
Arc::clone(&bindings),
Arc::new(config.clone()),
@@ -215,6 +216,253 @@ pub(crate) async fn wait_for_outcome(
}
}
+/// Bind a fresh resume capability to the current owner and verify the parked
+/// run is visible in that same CatalogStorage scope.
+pub(crate) async fn register_resume_bindings(
+ ctx: &DispatchCtx,
+ config: &Config,
+ flow_id: &str,
+ run_id: &str,
+ require_approval: bool,
+) -> Result<Arc<RunBindings>, String> {
+ use tinyflows_bus::catalog::{self, FlowRun as WireRun, Workflow};
+
+ let catalog = catalog_storage::register(ctx, config).await?;
+ let storage = catalog.storage();
+ let runs = module::catalog_proxy(config).await?;
+ let run: Option<WireRun> = runs
+ .call(
+ catalog::members::GET_RUN,
+ (catalog::RunIdRequest {
+ storage: storage.clone(),
+ id: run_id.to_owned(),
+ },),
+ )
+ .await
+ .map_err(|error| error.wire_message())?;
+ let run = run.ok_or_else(|| format!("flow run '{run_id}' not found"))?;
+ if run.flow_id != flow_id {
+ return Err(format!("flow run '{run_id}' does not belong to flow '{flow_id}'"));
+ }
+ if run.status != "pending_approval" {
+ return Err(format!("flow run '{run_id}' is not waiting for approval"));
+ }
+
+ let workflow: Option<Workflow> = runs
+ .call(
+ catalog::members::GET_WORKFLOW,
+ (storage, flow_id.to_owned()),
+ )
+ .await
+ .map_err(|error| error.wire_message())?;
+ let flow: Flow = crate::flows::store::roundtrip(
+ workflow.ok_or_else(|| format!("flow '{flow_id}' not found"))?,
+ )
+ .map_err(|error| format!("decode workflow for resume: {error}"))?;
+ if flow.require_approval != require_approval {
+ return Err("workflow approval policy changed during resume".to_string());
+ }
+
+ if let Some(session) = session::get(&catalog.storage(), run_id) {
+ if session.flow_id() != flow_id {
+ return Err(format!("flow run '{run_id}' is bound to a different workflow"));
+ }
+ }
+ register_with_catalog(ctx, config, &flow, run_id, catalog).await
+}
+
+/// Resume a parked module run and await only the next segment's parked or
+/// terminal event. The prior parked cursor is drained before admission so a
+/// process-restarted waiter cannot mistake an earlier `parked` event for the
+/// result of this resume.
+pub(crate) async fn resume_and_wait(
+ ctx: &DispatchCtx,
+ config: &Config,
+ request: ResumeRun,
+ candidate: Arc<RunBindings>,
+) -> Result<ResumeOutcome, String> {
+ let storage = request.storage.clone();
+ let key = RunKey::new(&storage, &request.run_id);
+ let proxy = module::runs_proxy(config).await?;
+ let (session, inserted) = match session::get(&storage, &request.run_id) {
+ Some(session) => (session, false),
+ None => {
+ let session = RunSession::new(
+ Arc::clone(&candidate),
+ Arc::new(config.clone()),
+ candidate.flow.clone(),
+ FlowRunTrigger::Resume,
+ 0,
+ );
+ if session.drain(&proxy, false).await? {
+ return Err(format!("flow run '{}' is already finished", request.run_id));
+ }
+ session::insert(Arc::clone(&session))?;
+ (session, true)
+ }
+ };
+
+ if !inserted {
+ session.drain(&proxy, true).await?;
+ }
+ let baseline = session.cursor();
+ let mut receiver = session.subscribe();
+ let resumed: runs::ResumeRunResponse = match proxy
+ .call(runs::methods::RESUME_RUN, (request.clone(),))
+ .await
+ {
+ Ok(resumed) => resumed,
+ Err(error) => {
+ if inserted {
+ session::remove(&session);
+ }
+ return Err(error.wire_message());
+ }
+ };
+ if resumed.run_id != request.run_id {
+ if inserted {
+ session::remove(&session);
+ }
+ return Err("TinyFlows resumed a different run id".to_string());
+ }
+
+ session.replace_flow(candidate.flow.clone()).await;
+ session.set_trigger(FlowRunTrigger::Resume);
+ session.replace_bindings(candidate).await;
+ session.start_polling(proxy);
+ let _ = ctx;
+ wait_for_outcome(&mut receiver, &request.run_id, baseline).await
+}
+
+/// Cancel a run through its exact owner-scoped CatalogStorage callback.
+pub(crate) async fn cancel_run(
+ config: &Config,
+ storage: tinyflows_bus::catalog::CatalogStorage,
+ run_id: &str,
+) -> Result<(bool, bool), String> {
+ let active = session::get(&storage, run_id);
+ let proxy = module::runs_proxy(config).await?;
+ let response: runs::CancelRunResponse = proxy
+ .call(
+ runs::methods::CANCEL_RUN,
+ (runs::RunControlRequest {
+ storage,
+ run_id: run_id.to_owned(),
+ cursor: 0,
+ },),
+ )
+ .await
+ .map_err(|error| error.wire_message())?;
+ let was_in_flight = response.signalled && active.is_some();
+ Ok((response.signalled, was_in_flight))
+}
+
+/// Expire parked runs in a scope, then drain their terminal events through the
+/// same projector used by active sessions.
+pub(crate) async fn expire_parked(
+ ctx: &DispatchCtx,
+ config: &Config,
+ catalog: Arc<CatalogStorageRegistration>,
+) -> Result<runs::ExpireParkedResponse, String> {
+ let proxy = module::runs_proxy(config).await?;
+ let response: runs::ExpireParkedResponse = proxy
+ .call(
+ runs::methods::EXPIRE_PARKED,
+ (runs::ExpireParked {
+ storage: catalog.storage(),
+ },),
+ )
+ .await
+ .map_err(|error| error.wire_message())?;
+ for (run_id, _) in &response.expired {
+ after_recovery(&catalog, run_id, config).await?;
+ }
+ let _ = ctx;
+ Ok(response)
+}
+
+/// Sweep orphaned runs in this scope and project only rows changed by the
+/// module's winning compare-and-swap.
+pub(crate) async fn boot_sweep(
+ ctx: &DispatchCtx,
+ config: &Config,
+ catalog: Arc<CatalogStorageRegistration>,
+) -> Result<runs::BootSweepResponse, String> {
+ let proxy = module::runs_proxy(config).await?;
+ let response: runs::BootSweepResponse = proxy
+ .call(
+ runs::methods::BOOT_SWEEP,
+ (runs::BootSweep {
+ storage: catalog.storage(),
+ shared_backend: crate::storage::installed_is_shared(),
+ },),
+ )
+ .await
+ .map_err(|error| error.wire_message())?;
+ for run_id in &response.interrupted {
+ after_recovery(&catalog, run_id, config).await?;
+ }
+ let _ = ctx;
+ Ok(response)
+}
+
+/// Project a recovered terminal event without reconstructing run state in the
+/// host. The storage address remains part of the dedupe key and data lookup.
+pub(crate) async fn after_recovery(
+ catalog: &Arc<CatalogStorageRegistration>,
+ run_id: &str,
+ config: &Config,
+) -> Result<(), String> {
+ let storage = catalog.storage();
+ if let Some(session) = session::get(&storage, run_id) {
+ let proxy = module::runs_proxy(config).await?;
+ let _ = session.drain(&proxy, true).await?;
+ return Ok(());
+ }
+
+ let key = RunKey::new(&storage, run_id);
+ let runs_proxy = module::runs_proxy(config).await?;
+ let catalog_proxy = module::catalog_proxy(config).await?;
+ let mut cursor = 0;
+ loop {
+ let page: runs::PollRun = runs_proxy
+ .call(
+ runs::methods::POLL_RUN,
+ (runs::RunControlRequest {
+ storage: storage.clone(),
+ run_id: run_id.to_owned(),
+ cursor,
+ },),
+ )
+ .await
+ .map_err(|error| error.wire_message())?;
+ for event in &page.events {
+ if event.kind == "finished" {
+ let run: Option<tinyflows_bus::catalog::FlowRun> = catalog_proxy
+ .call(
+ tinyflows_bus::catalog::members::GET_RUN,
+ (tinyflows_bus::catalog::RunIdRequest {
+ storage: storage.clone(),
+ id: run_id.to_owned(),
+ },),
+ )
+ .await
+ .map_err(|error| error.wire_message())?;
+ let flow_id = run
+ .ok_or_else(|| format!("flow run '{run_id}' disappeared during recovery"))?
+ .flow_id;
+ projection::project_recovered_finished(&key, &flow_id, run_id, event);
+ }
+ cursor = event.seq;
+ }
+ if page.done || page.events.is_empty() || page.next_cursor <= cursor {
+ break;
+ }
+ cursor = page.next_cursor;
+ }
+ Ok(())
+}
+
fn finished_outcome(
finished: runs::RunFinished,
run_id: &str,
diff --git a/crates/openhuman-core/src/flows/runs_adapter/projection.rs b/crates/openhuman-core/src/flows/runs_adapter/projection.rs
new file mode 100644
index 0000000000..a72f990a5e
--- /dev/null
+++ b/crates/openhuman-core/src/flows/runs_adapter/projection.rs
@@ -0,0 +1,124 @@
+//! Project module-owned PollRun events onto OpenHuman events and Langfuse.
+
+use serde_json::Value;
+use tinyflows_bus::runs::{self, RunEvent};
+use tinyflows_catalog::types::FlowRunTrigger;
+
+use crate::core::events::DomainEvent;
+use crate::flows::runs_adapter::session::RunSession;
+
+pub(super) async fn project(session: &RunSession, event: &RunEvent) {
+ match event.kind.as_str() {
+ "started" => {
+ if session.mark_started() {
+ crate::core::bus::BUS.publish(DomainEvent::FlowRunStarted {
+ flow_id: session.flow_id().to_owned(),
+ run_id: session.run_id.clone(),
+ });
+ }
+ }
+ "resumed" => session.set_trigger(FlowRunTrigger::Resume),
+ "step_started" => {
+ if let Some(node_id) = event.data.get("node_id").and_then(Value::as_str) {
+ publish_step(session, node_id, "running");
+ }
+ }
+ "step" => {
+ if let (Some(node_id), Some(status)) = (
+ event.data.get("node_id").and_then(Value::as_str),
+ event.data.get("status").and_then(Value::as_str),
+ ) {
+ publish_step(session, node_id, status);
+ }
+ }
+ "graph_observation" => match serde_json::from_value::<tinyagents_graph::GraphObservation>(
+ event.data.clone(),
+ ) {
+ Ok(observation) => session.add_observation(observation),
+ Err(_) => tracing::warn!(
+ target: "flows",
+ run_id = %session.run_id,
+ "[flows] PollRun graph observation could not be decoded for Langfuse"
+ ),
+ },
+ "agent_progress" => {
+ // The UI's existing workflow overlay is node-based. The detailed
+ // agent events stay on the module stream; consume them here so the
+ // shared cursor remains the sole owner of event ordering.
+ }
+ "parked" => {
+ let parked = match serde_json::from_value::<runs::RunParked>(event.data.clone()) {
+ Ok(parked) => parked,
+ Err(_) => {
+ tracing::warn!(
+ target: "flows",
+ run_id = %session.run_id,
+ "[flows] PollRun parked outcome could not be decoded"
+ );
+ return;
+ }
+ };
+ let flow = session.flow().await;
+ crate::flows::ops::notify_pending_approval(
+ &flow,
+ &session.run_id,
+ &parked.pending_approvals,
+ );
+ export_segment(session, "pending_approval").await;
+ }
+ "finished" => {
+ let finished = match serde_json::from_value::<runs::RunFinished>(event.data.clone()) {
+ Ok(finished) => finished,
+ Err(_) => {
+ tracing::warn!(
+ target: "flows",
+ run_id = %session.run_id,
+ "[flows] PollRun terminal outcome could not be decoded"
+ );
+ return;
+ }
+ };
+ if session.mark_finished() {
+ crate::core::bus::BUS.publish(DomainEvent::FlowRunFinished {
+ flow_id: session.flow_id().to_owned(),
+ run_id: session.run_id.clone(),
+ status: finished.status.clone(),
+ });
+ }
+ export_segment(session, &finished.status).await;
+ }
+ _ => {}
+ }
+}
+
+fn publish_step(session: &RunSession, node_id: &str, status: &str) {
+ crate::core::bus::BUS.publish(DomainEvent::FlowRunProgress {
+ run_id: session.run_id.clone(),
+ node_id: node_id.to_owned(),
+ status: status.to_owned(),
+ });
+}
+
+async fn export_segment(session: &RunSession, status: &str) {
+ let observations = session.take_observations();
+ let flow = session.flow().await;
+ crate::flows::ops::export_run_to_langfuse(
+ &session.config,
+ &flow.name,
+ &flow.id,
+ &session.run_id,
+ status,
+ bus_trigger(session.trigger()),
+ &observations,
+ )
+ .await;
+}
+
+fn bus_trigger(trigger: FlowRunTrigger) -> runs::FlowRunTrigger {
+ match trigger {
+ FlowRunTrigger::Rpc => runs::FlowRunTrigger::Rpc,
+ FlowRunTrigger::Schedule => runs::FlowRunTrigger::Schedule,
+ FlowRunTrigger::AppEvent => runs::FlowRunTrigger::AppEvent,
+ FlowRunTrigger::Resume => runs::FlowRunTrigger::Resume,
+ }
+}
diff --git a/crates/openhuman-core/src/flows/runs_adapter/session.rs b/crates/openhuman-core/src/flows/runs_adapter/session.rs
index ed1a24c240..ad9b44d1d1 100644
--- a/crates/openhuman-core/src/flows/runs_adapter/session.rs
+++ b/crates/openhuman-core/src/flows/runs_adapter/session.rs
@@ -36,12 +36,15 @@ pub(crate) struct RunSession {
pub(super) bindings: std::sync::RwLock<Arc<RunBindings>>,
pub(super) config: Arc<Config>,
pub(super) flow: tokio::sync::RwLock<Flow>,
+ flow_id: String,
pub(super) trigger: Mutex<FlowRunTrigger>,
pub(super) run_id: String,
cursor: std::sync::atomic::AtomicU64,
poll_lock: tokio::sync::Mutex<()>,
watchers: Mutex<Vec<tokio::sync::mpsc::UnboundedSender<RunEvent>>>,
- started: std::sync::atomic::AtomicBool,
+ poller_started: std::sync::atomic::AtomicBool,
+ started_event: std::sync::atomic::AtomicBool,
+ finished_event: std::sync::atomic::AtomicBool,
observations: Mutex<Vec<tinyagents_graph::GraphObservation>>,
}
@@ -58,6 +61,7 @@ impl RunSession {
) -> Arc<Self> {
Arc::new(Self {
run_id: bindings.run_id.clone(),
+ flow_id: bindings.flow_id.clone(),
bindings: std::sync::RwLock::new(bindings),
config,
flow: tokio::sync::RwLock::new(flow),
@@ -65,7 +69,9 @@ impl RunSession {
cursor: std::sync::atomic::AtomicU64::new(cursor),
poll_lock: tokio::sync::Mutex::new(()),
watchers: Mutex::new(Vec::new()),
- started: std::sync::atomic::AtomicBool::new(false),
+ poller_started: std::sync::atomic::AtomicBool::new(false),
+ started_event: std::sync::atomic::AtomicBool::new(false),
+ finished_event: std::sync::atomic::AtomicBool::new(false),
observations: Mutex::new(Vec::new()),
})
}
@@ -127,14 +133,43 @@ impl RunSession {
.unwrap_or_else(std::sync::PoisonError::into_inner) = bindings;
}
+ pub(super) fn current_bindings(&self) -> Arc<RunBindings> {
+ Arc::clone(
+ &self
+ .bindings
+ .read()
+ .unwrap_or_else(std::sync::PoisonError::into_inner),
+ )
+ }
+
pub(super) async fn replace_flow(&self, flow: Flow) {
*self.flow.write().await = flow;
}
+ pub(super) async fn flow(&self) -> Flow {
+ self.flow.read().await.clone()
+ }
+
+ pub(super) fn flow_id(&self) -> &str {
+ &self.flow_id
+ }
+
+ pub(super) fn mark_started(&self) -> bool {
+ !self
+ .started_event
+ .swap(true, std::sync::atomic::Ordering::AcqRel)
+ }
+
+ pub(super) fn mark_finished(&self) -> bool {
+ !self
+ .finished_event
+ .swap(true, std::sync::atomic::Ordering::AcqRel)
+ }
+
/// Start the one PollRun task for this process/run owner.
pub(super) fn start_polling(self: &Arc<Self>, proxy: tinybus::Proxy) {
if self
- .started
+ .poller_started
.swap(true, std::sync::atomic::Ordering::AcqRel)
{
return;