Skip to content

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

feat(prompts): add flow archetype text to prompt context

Steven Enamakel609596c74de0
diff --git a/crates/openhuman-core/src/agent/progress_tracing/graph_langfuse.rs b/crates/openhuman-core/src/agent/progress_tracing/graph_langfuse.rs
new file mode 100644
index 0000000000..f201073023
--- /dev/null
+++ b/crates/openhuman-core/src/agent/progress_tracing/graph_langfuse.rs
@@ -0,0 +1,163 @@
+//! Langfuse export for durable graph runs.
+//!
+//! The graph observations and flow trigger are serde-only bus contracts. The
+//! host that owns engine observations adapts them before calling this module;
+//! this exporter owns the graph trace identity, metadata, and OTLP projection.
+
+use std::time::Duration;
+
+use serde_json::{json, Map, Value};
+use tinyagents_graph::{GraphLangfuseExporter, GraphObservation};
+use tinyagents_harness::{LangfuseAuth, LangfuseClient, LangfuseTraceConfig};
+use tinyflows_bus::runs::FlowRunTrigger;
+
+use crate::config::Config;
+use crate::security::credentials::session_support::direct_backend_credential;
+
+const LOG_TARGET: &str = "flows::langfuse";
+const PUSH_TIMEOUT: Duration = Duration::from_secs(10);
+const APP_VERSION: &str = env!("CARGO_PKG_VERSION");
+
+fn trigger_name(trigger: FlowRunTrigger) -> &'static str {
+ match trigger {
+ FlowRunTrigger::Rpc => "rpc",
+ FlowRunTrigger::Schedule => "schedule",
+ FlowRunTrigger::AppEvent => "app_event",
+ FlowRunTrigger::Resume => "resume",
+ }
+}
+
+fn build_flow_trace_config(
+ flow_name: &str,
+ flow_id: &str,
+ thread_id: &str,
+ status: &str,
+ trigger: FlowRunTrigger,
+) -> LangfuseTraceConfig {
+ let trigger = trigger_name(trigger);
+ LangfuseTraceConfig {
+ trace_id: Some(thread_id.to_string()),
+ name: Some(format!("flow.run:{flow_name}")),
+ session_id: Some(format!("flow:{flow_id}")),
+ release: Some(APP_VERSION.to_string()),
+ tags: vec!["run:flow".to_string(), format!("trigger:{trigger}")],
+ metadata: json!({
+ "flow_id": flow_id,
+ "status": status,
+ "source": "flows",
+ "run_type": "flow",
+ "trigger": trigger,
+ "app_version": APP_VERSION,
+ }),
+ ..Default::default()
+ }
+}
+
+fn build_flow_exporter(client: LangfuseClient, flow_id: &str) -> GraphLangfuseExporter {
+ let flow_id = flow_id.to_string();
+ GraphLangfuseExporter::new(client).with_span_metadata_fn(move |_obs| {
+ let mut extra = Map::new();
+ extra.insert("flow_id".to_string(), json!(flow_id));
+ Some(extra)
+ })
+}
+
+fn flow_otlp_requests(
+ exporter: &GraphLangfuseExporter,
+ trace: LangfuseTraceConfig,
+ observations: &[GraphObservation],
+) -> tinyagents_harness::error::Result<Vec<Value>> {
+ exporter.build_otlp_requests(trace, observations, crate::agent::progress_tracing::export_brand().product)
+}
+
+fn graph_otlp_requests(
+ flow_name: &str,
+ flow_id: &str,
+ thread_id: &str,
+ status: &str,
+ trigger: FlowRunTrigger,
+ observations: &[GraphObservation],
+) -> tinyagents_harness::error::Result<Vec<Value>> {
+ let client = LangfuseClient::new(
+ "https://backend.invalid/telemetry/langfuse/ingestion",
+ LangfuseAuth::Bearer {
+ token: String::new(),
+ },
+ )?;
+ let exporter = build_flow_exporter(client, flow_id);
+ flow_otlp_requests(
+ &exporter,
+ build_flow_trace_config(flow_name, flow_id, thread_id, status, trigger),
+ observations,
+ )
+}
+
+/// Exports one settled flow graph to Langfuse. Failures are logged and
+/// swallowed so tracing cannot fail or delay-fail the flow run.
+pub(crate) async fn export_graph_run_trace(
+ config: &Config,
+ flow_name: &str,
+ flow_id: &str,
+ thread_id: &str,
+ status: &str,
+ trigger: FlowRunTrigger,
+ observations: &[GraphObservation],
+) {
+ if !config.observability.share_usage_data {
+ tracing::debug!(target: LOG_TARGET, flow_id = %flow_id, "[flows] langfuse export skipped: observability.share_usage_data is off");
+ return;
+ }
+ if observations.is_empty() {
+ tracing::debug!(target: LOG_TARGET, flow_id = %flow_id, thread_id = %thread_id, "[flows] langfuse export skipped: run journal is empty");
+ return;
+ }
+
+ let url = super::langfuse::ingestion_url(config);
+ if !url.starts_with("http") {
+ tracing::warn!(target: LOG_TARGET, flow_id = %flow_id, "[flows] langfuse export skipped: could not resolve ingestion URL from backend host (got {url:?})");
+ return;
+ }
+ let token = match direct_backend_credential(config, "flows langfuse export") {
+ Some(crate::security::credentials::session_support::BackendCredential::Session(token)) => token,
+ _ => {
+ tracing::debug!(target: LOG_TARGET, flow_id = %flow_id, "[flows] langfuse export skipped: hosted backend not available");
+ return;
+ }
+ };
+ let client = match LangfuseClient::new(
+ url.clone(),
+ LangfuseAuth::Bearer {
+ token: token.clone(),
+ },
+ ) {
+ Ok(client) => client,
+ Err(err) => {
+ tracing::warn!(target: LOG_TARGET, flow_id = %flow_id, error = %err, "[flows] langfuse export skipped: could not build client for {url}");
+ return;
+ }
+ };
+ let exporter = build_flow_exporter(client, flow_id);
+ let trace = build_flow_trace_config(flow_name, flow_id, thread_id, status, trigger);
+ let requests = match flow_otlp_requests(&exporter, trace, observations) {
+ Ok(requests) => requests,
+ Err(err) => {
+ tracing::warn!(target: LOG_TARGET, flow_id = %flow_id, thread_id = %thread_id, error = %err, "[flows] langfuse export skipped: could not build OTLP requests");
+ return;
+ }
+ };
+ let request_count = requests.len();
+ let send = crate::agent::progress_tracing::otlp::push_otlp_json_requests(
+ &exporter.client().otlp_endpoint(),
+ &token,
+ &requests,
+ );
+ match tokio::time::timeout(PUSH_TIMEOUT, send).await {
+ Ok(Ok(())) => tracing::debug!(target: LOG_TARGET, flow_id = %flow_id, thread_id = %thread_id, observation_count = observations.len(), request_count, "[flows] pushed flow run trace to Langfuse"),
+ Ok(Err(err)) => tracing::warn!(target: LOG_TARGET, flow_id = %flow_id, thread_id = %thread_id, error = %err, "[flows] langfuse export failed (run unaffected)"),
+ Err(_) => tracing::warn!(target: LOG_TARGET, flow_id = %flow_id, thread_id = %thread_id, timeout_secs = PUSH_TIMEOUT.as_secs(), "[flows] langfuse export timed out (run unaffected)"),
+ }
+}
+
+#[cfg(test)]
+#[path = "graph_langfuse_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-core/src/agent/progress_tracing/otlp.rs b/crates/openhuman-core/src/agent/progress_tracing/otlp.rs
index a850ec2dae..4455b6244c 100644
--- a/crates/openhuman-core/src/agent/progress_tracing/otlp.rs
+++ b/crates/openhuman-core/src/agent/progress_tracing/otlp.rs
@@ -13,42 +13,25 @@ use crate::config::Config;
use crate::security::credentials::jwt::bearer_authorization_value;
use crate::security::credentials::session_support::direct_backend_credential;
-pub(super) async fn push_spans(config: &Config, spans: &[TraceSpan]) -> Result<(), String> {
- if spans.is_empty() {
- return Ok(());
- }
- let legacy_url = ingestion_url(config);
- let url = legacy_url.replace("/langfuse/ingestion", "/langfuse/otel/v1/traces");
- let environment = environment_for_base(&url);
- if skip_push(environment) {
- return Ok(());
- }
- if !url.starts_with("http") {
- return Err("Langfuse backend proxy URL is unavailable".to_string());
- }
- // No TinyHumans connection, or no usable credential (signed out, offline
- // local session): a configured state, so skip quietly rather than failing
- // every turn's push.
- let token = match direct_backend_credential(config, "langfuse otlp push") {
- Some(crate::security::credentials::session_support::BackendCredential::Session(token)) => {
- token
- }
- _ => return Ok(()),
- };
- // Backend traffic: the transport's client carries the host's attribution
- // headers (product identity, versions).
+/// Pushes already-rendered OTLP/HTTP JSON requests through the authenticated
+/// backend client used by agent and graph exports.
+pub(super) async fn push_otlp_json_requests(
+ url: &str,
+ token: &str,
+ requests: &[Value],
+) -> Result<(), String> {
let client = crate::backend::resolve_backend_transport()
.map_err(|err| format!("Langfuse OTLP push has no backend transport: {err}"))?
.http_client(crate::backend::TransportProfile::Api);
- for payload in otlp_requests(spans, environment, &super::export_brand()) {
+ for payload in requests {
let response = client
- .post(&url)
+ .post(url)
.header(
reqwest::header::AUTHORIZATION,
- bearer_authorization_value(&token),
+ bearer_authorization_value(token),
)
.timeout(std::time::Duration::from_secs(10))
- .json(&payload)
+ .json(payload)
.send()
.await
.map_err(|err| format!("Langfuse OTLP transport failed: {err}"))?;
@@ -71,6 +54,32 @@ pub(super) async fn push_spans(config: &Config, spans: &[TraceSpan]) -> Result<(
Ok(())
}
+pub(super) async fn push_spans(config: &Config, spans: &[TraceSpan]) -> Result<(), String> {
+ if spans.is_empty() {
+ return Ok(());
+ }
+ let legacy_url = ingestion_url(config);
+ let url = legacy_url.replace("/langfuse/ingestion", "/langfuse/otel/v1/traces");
+ let environment = environment_for_base(&url);
+ if skip_push(environment) {
+ return Ok(());
+ }
+ if !url.starts_with("http") {
+ return Err("Langfuse backend proxy URL is unavailable".to_string());
+ }
+ // No TinyHumans connection, or no usable credential (signed out, offline
+ // local session): a configured state, so skip quietly rather than failing
+ // every turn's push.
+ let token = match direct_backend_credential(config, "langfuse otlp push") {
+ Some(crate::security::credentials::session_support::BackendCredential::Session(token)) => {
+ token
+ }
+ _ => return Ok(()),
+ };
+ let requests = otlp_requests(spans, environment, &super::export_brand());
+ push_otlp_json_requests(&url, &token, &requests).await
+}
+
#[cfg(test)]
#[path = "otlp_tests.rs"]
mod tests;
diff --git a/crates/openhuman-core/src/agent/prompts/flow_archetype.rs b/crates/openhuman-core/src/agent/prompts/flow_archetype.rs
new file mode 100644
index 0000000000..ac0089db80
--- /dev/null
+++ b/crates/openhuman-core/src/agent/prompts/flow_archetype.rs
@@ -0,0 +1,58 @@
+//! Scoped TinyFlows archetype prompt loading for the two flow builtins.
+
+use anyhow::{anyhow, ensure, Result};
+use tinyagents_definition::{AgentDefinition as GenericAgentDefinition, DefinitionSource, PromptSource};
+
+use crate::{
+ config::Config,
+ agent::harness::host_definition::AgentDefinition,
+};
+
+/// Whether `definition` is one of the bus-backed builtin flow prompt owners.
+///
+/// User definitions and static/session prompt overrides keep their own source
+/// and never cause a TinyFlows module lookup, even when they reuse a builtin id.
+pub(crate) fn is_bus_backed_builtin(definition: &AgentDefinition) -> bool {
+ matches!(&definition.source, DefinitionSource::Builtin)
+ && matches!(&definition.system_prompt, PromptSource::Dynamic(()))
+ && matches!(definition.id.as_str(), "workflow_builder" | "flow_discovery")
+}
+
+/// Fetch the archetype for a resolved definition through the module bus.
+///
+/// The caller supplies the exact config snapshot that selected the module
+/// generation. No ambient config or fallback prompt is used.
+pub(crate) async fn load_for_definition(
+ config: Option<&Config>,
+ definition: &AgentDefinition,
+) -> Result<Option<String>> {
+ if !is_bus_backed_builtin(definition) {
+ return Ok(None);
+ }
+
+ let config = config.ok_or_else(|| {
+ anyhow!(
+ "cannot render TinyFlows builtin `{}` without its scoped runtime config",
+ definition.id
+ )
+ })?;
+ let proxy = crate::modules::tinyflows::copilot_proxy(config)
+ .await
+ .map_err(anyhow::Error::msg)
+ .map_err(|error| error.context(format!("loading TinyFlows prompt `{}`", definition.id)))?;
+ let response: tinyflows_bus::copilot::TextResponse = proxy
+ .call("GetPrompt", (definition.id.clone(),))
+ .await
+ .map_err(|error| anyhow!(error.wire_message()))
+ .map_err(|error| error.context(format!("fetching TinyFlows prompt `{}`", definition.id)))?;
+ ensure!(
+ !response.text.trim().is_empty(),
+ "TinyFlows returned an empty prompt for builtin `{}`",
+ definition.id
+ );
+ Ok(Some(response.text))
+}
+
+#[cfg(test)]
+#[path = "flow_archetype_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-core/src/agent/prompts/flow_archetype_tests.rs b/crates/openhuman-core/src/agent/prompts/flow_archetype_tests.rs
new file mode 100644
index 0000000000..79aa5c6ec4
--- /dev/null
+++ b/crates/openhuman-core/src/agent/prompts/flow_archetype_tests.rs
@@ -0,0 +1,58 @@
+use super::*;
+
+#[test]
+fn only_dynamic_builtin_flow_definitions_use_the_bus_prompt() {
+ let registry = crate::agent::harness::host_definition::AgentDefinitionRegistry::builtins_only();
+ for id in ["workflow_builder", "flow_discovery"] {
+ let mut definition = registry.get(id).expect("builtin flow agent").clone();
+ assert!(is_bus_backed_builtin(&definition));
+
+ definition.system_prompt = PromptSource::Inline("session prompt override".into());
+ assert!(!is_bus_backed_builtin(&definition));
+
+ let mut definition = registry.get(id).expect("builtin flow agent").clone();
+ definition.source = DefinitionSource::Workspace;
+ assert!(!is_bus_backed_builtin(&definition));
+ }
+}
+
+#[tokio::test]
+async fn flow_prompt_requires_the_scoped_config_and_respects_component_disable() {
+ let registry = crate::agent::harness::host_definition::AgentDefinitionRegistry::builtins_only();
+ let definition = registry
+ .get("workflow_builder")
+ .expect("workflow_builder builtin");
+ let error = load_for_definition(None, definition)
+ .await
+ .expect_err("scoped config is required");
+ assert!(error.to_string().contains("scoped runtime config"));
+
+ let mut config = Config::default();
+ config.components.tinyflows = false;
+ let error = load_for_definition(Some(&config), definition)
+ .await
+ .expect_err("disabled module must fail closed");
+ assert!(error.to_string().contains("COMPONENT_DISABLED:tinyflows"));
+}
+
+#[tokio::test]
+async fn flow_prompt_fetch_uses_the_copilot_get_prompt_bus_member() {
+ let registry = crate::agent::harness::host_definition::AgentDefinitionRegistry::builtins_only();
+ let mut config = Config::default();
+ let temp = tempfile::tempdir().expect("workspace");
+ config.workspace_dir = temp.path().join("workspace");
+ config.config_path = temp.path().join("config.toml");
+
+ for id in ["workflow_builder", "flow_discovery"] {
+ let definition = registry.get(id).expect("builtin flow agent");
+ let text = load_for_definition(Some(&config), definition)
+ .await
+ .expect("bus prompt fetch")
+ .expect("flow builtin prompt");
+ assert!(!text.trim().is_empty(), "{id} prompt must be nonempty");
+ assert!(
+ !text.contains("tinyflows_copilot::prompts"),
+ "host receives prompt text over the bus"
+ );
+ }
+}
diff --git a/crates/openhuman-core/src/agent/prompts/mod.rs b/crates/openhuman-core/src/agent/prompts/mod.rs
index 93c2fc2999..27e9e9c8d8 100644
--- a/crates/openhuman-core/src/agent/prompts/mod.rs
+++ b/crates/openhuman-core/src/agent/prompts/mod.rs
@@ -4,6 +4,8 @@
pub mod types;
pub use types::*;
+#[cfg(feature = "flows")]
+pub(crate) mod flow_archetype;
mod connected_identities;
pub use connected_identities::render_connected_identities;
diff --git a/crates/openhuman-core/src/agent/prompts/types.rs b/crates/openhuman-core/src/agent/prompts/types.rs
index 58876451f3..e9cd52d9c4 100644
--- a/crates/openhuman-core/src/agent/prompts/types.rs
+++ b/crates/openhuman-core/src/agent/prompts/types.rs
@@ -293,6 +293,11 @@ pub struct PromptContext<'a> {
pub model_name: &'a str,
/// Id of the agent this prompt is being built for.
pub agent_id: &'a str,
+ /// Archetype text fetched by the caller for a TinyFlows-backed builtin.
+ ///
+ /// Flow prompt builders remain synchronous; async host entrypoints fetch
+ /// this value from the scoped TinyFlows Copilot bus before rendering.
+ pub flow_archetype_text: Option<&'a str>,
pub tools: &'a [PromptTool<'a>],
pub workflows: &'a [Workflow],
pub dispatcher_instructions: &'a str,