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/agent/orchestration/spawn_parallel_graph.rs,crates/op

Steven Enamakel0e9443d0f285
diff --git a/crates/openhuman-core/src/agent/orchestration/spawn_parallel_graph.rs b/crates/openhuman-core/src/agent/orchestration/spawn_parallel_graph.rs
index 5709aa505d..4802a5c864 100644
--- a/crates/openhuman-core/src/agent/orchestration/spawn_parallel_graph.rs
+++ b/crates/openhuman-core/src/agent/orchestration/spawn_parallel_graph.rs
@@ -41,5 +41,8 @@ pub(crate) use run::{
run_spawn_parallel_graph, run_spawn_parallel_graph_with_cancellation,
run_spawn_parallel_graph_with_cancellation_and_workspace,
};
-pub(crate) use staging::with_ownership_boundary;
+pub(crate) use staging::{
+ prepare_spawn_parallel_tasks_from_defs, with_ownership_boundary, ParallelTaskRejectionKind,
+ SpawnParallelTaskPreflight, WorkerDispatchMode,
+};
pub(crate) use types::{ParallelAgentLineage, ParallelAgentResult};
diff --git a/crates/openhuman-core/src/tools/impl/browser/browser_backend_resolution.rs b/crates/openhuman-core/src/tools/impl/browser/browser_backend_resolution.rs
new file mode 100644
index 0000000000..09a7c925d3
--- /dev/null
+++ b/crates/openhuman-core/src/tools/impl/browser/browser_backend_resolution.rs
@@ -0,0 +1,178 @@
+//! Backend selection and computer-use endpoint / URL validation for
+//! [`BrowserTool`].
+
+use super::*;
+
+impl BrowserTool {
+ fn computer_use_endpoint_url(&self) -> anyhow::Result<reqwest::Url> {
+ if self.computer_use.timeout_ms == 0 {
+ anyhow::bail!("browser.computer_use.timeout_ms must be > 0");
+ }
+
+ let endpoint = self.computer_use.endpoint.trim();
+ if endpoint.is_empty() {
+ anyhow::bail!("browser.computer_use.endpoint cannot be empty");
+ }
+
+ let parsed = reqwest::Url::parse(endpoint).map_err(|_| {
+ anyhow::anyhow!(
+ "Invalid browser.computer_use.endpoint: '{endpoint}'. Expected http(s) URL"
+ )
+ })?;
+
+ let scheme = parsed.scheme();
+ if scheme != "http" && scheme != "https" {
+ anyhow::bail!("browser.computer_use.endpoint must use http:// or https://");
+ }
+
+ let host = parsed
+ .host_str()
+ .ok_or_else(|| anyhow::anyhow!("browser.computer_use.endpoint must include host"))?;
+
+ let host_is_private = is_private_host(host);
+ if !self.computer_use.allow_remote_endpoint && !host_is_private {
+ anyhow::bail!(
+ "browser.computer_use.endpoint host '{host}' is public. Set browser.computer_use.allow_remote_endpoint=true to allow it"
+ );
+ }
+
+ if self.computer_use.allow_remote_endpoint && !host_is_private && scheme != "https" {
+ anyhow::bail!(
+ "browser.computer_use.endpoint must use https:// when allow_remote_endpoint=true and host is public"
+ );
+ }
+
+ Ok(parsed)
+ }
+
+ fn computer_use_available(&self) -> anyhow::Result<bool> {
+ let endpoint = self.computer_use_endpoint_url()?;
+ Ok(endpoint_reachable(&endpoint, Duration::from_millis(500)))
+ }
+
+ async fn resolve_backend(&self) -> anyhow::Result<ResolvedBackend> {
+ let configured = self.configured_backend()?;
+
+ match configured {
+ BrowserBackendKind::AgentBrowser => {
+ if Self::is_agent_browser_available().await {
+ Ok(ResolvedBackend::AgentBrowser)
+ } else {
+ anyhow::bail!(
+ "browser.backend='{}' but agent-browser is unavailable. Install it in your environment.",
+ configured.as_str()
+ )
+ }
+ }
+ BrowserBackendKind::Playwright => {
+ if Self::is_playwright_available().await {
+ Ok(ResolvedBackend::Playwright)
+ } else {
+ anyhow::bail!(
+ "browser.backend='playwright' but Playwright is unavailable. Ensure app/node_modules is installed, run `pnpm --filter openhuman-app exec playwright install chromium-headless-shell`, or set OPENHUMAN_PLAYWRIGHT_CWD."
+ )
+ }
+ }
+ BrowserBackendKind::RustNative => {
+ if !Self::rust_native_compiled() {
+ anyhow::bail!(
+ "browser.backend='rust_native' requires build feature 'browser-native'"
+ );
+ }
+ if !self.rust_native_available() {
+ anyhow::bail!(
+ "Rust-native browser backend is enabled but WebDriver endpoint is unreachable. Set browser.native_webdriver_url and start a compatible driver"
+ );
+ }
+ Ok(ResolvedBackend::RustNative)
+ }
+ BrowserBackendKind::ComputerUse => {
+ if !self.computer_use_available()? {
+ anyhow::bail!(
+ "browser.backend='computer_use' but sidecar endpoint is unreachable. Check browser.computer_use.endpoint and sidecar status"
+ );
+ }
+ Ok(ResolvedBackend::ComputerUse)
+ }
+ BrowserBackendKind::Auto => {
+ if Self::rust_native_compiled() && self.rust_native_available() {
+ return Ok(ResolvedBackend::RustNative);
+ }
+ if Self::is_playwright_available().await {
+ return Ok(ResolvedBackend::Playwright);
+ }
+ if Self::is_agent_browser_available().await {
+ return Ok(ResolvedBackend::AgentBrowser);
+ }
+
+ let computer_use_err = match self.computer_use_available() {
+ Ok(true) => return Ok(ResolvedBackend::ComputerUse),
+ Ok(false) => None,
+ Err(err) => Some(err.to_string()),
+ };
+
+ if Self::rust_native_compiled() {
+ if let Some(err) = computer_use_err {
+ anyhow::bail!(
+ "browser.backend='auto' found no usable backend (playwright missing, agent-browser missing, rust-native unavailable, computer-use invalid: {err})"
+ );
+ }
+ anyhow::bail!(
+ "browser.backend='auto' found no usable backend (playwright missing, agent-browser missing, rust-native unavailable, computer-use sidecar unreachable)"
+ )
+ }
+
+ if let Some(err) = computer_use_err {
+ anyhow::bail!(
+ "browser.backend='auto' needs Playwright, agent-browser tool, browser-native, or valid computer-use sidecar (error: {err})"
+ );
+ }
+
+ anyhow::bail!(
+ "browser.backend='auto' needs Playwright, agent-browser tool, browser-native, or computer-use sidecar"
+ )
+ }
+ }
+ }
+
+ /// Validate URL against allowlist
+ fn validate_url(&self, url: &str) -> anyhow::Result<()> {
+ let url = url.trim();
+
+ if url.is_empty() {
+ anyhow::bail!("URL cannot be empty");
+ }
+
+ // Block file:// URLs — browser file access bypasses all SSRF and
+ // domain-allowlist controls and can exfiltrate arbitrary local files.
+ if url.starts_with("file://") {
+ anyhow::bail!("file:// URLs are not allowed in browser automation");
+ }
+
+ if !url.starts_with("https://") && !url.starts_with("http://") {
+ anyhow::bail!("Only http:// and https:// URLs are allowed");
+ }
+
+ if self.allowed_domains.is_empty() && !allow_all_browser_domains() {
+ anyhow::bail!(
+ "Browser tool enabled but no allowed_domains configured. \
+ Add [browser].allowed_domains in config.toml or set OPENHUMAN_BROWSER_ALLOW_ALL=1"
+ );
+ }
+
+ let host = extract_host(url)?;
+
+ if is_private_host(&host) {
+ anyhow::bail!("Blocked local/private host: {host}");
+ }
+
+ if !self.allowed_domains.is_empty() && !host_matches_allowlist(&host, &self.allowed_domains)
+ {
+ anyhow::bail!("Host '{host}' not in browser.allowed_domains");
+ }
+
+ Ok(())
+ }
+
+ /// Execute an agent-browser command
+}
diff --git a/crates/openhuman-core/src/tools/impl/browser/browser_computer_use.rs b/crates/openhuman-core/src/tools/impl/browser/browser_computer_use.rs
new file mode 100644
index 0000000000..d11bb05a4d
--- /dev/null
+++ b/crates/openhuman-core/src/tools/impl/browser/browser_computer_use.rs
@@ -0,0 +1,164 @@
+//! Computer-use (OS-level) action validation and execution for
+//! [`BrowserTool`].
+
+use super::*;
+
+impl BrowserTool {
+ fn validate_coordinate(&self, key: &str, value: i64, max: Option<i64>) -> anyhow::Result<()> {
+ if value < 0 {
+ anyhow::bail!("'{key}' must be >= 0")
+ }
+ if let Some(limit) = max {
+ if limit < 0 {
+ anyhow::bail!("Configured coordinate limit for '{key}' must be >= 0")
+ }
+ if value > limit {
+ anyhow::bail!("'{key}'={value} exceeds configured limit {limit}")
+ }
+ }
+ Ok(())
+ }
+
+ fn read_required_i64(
+ &self,
+ params: &serde_json::Map<String, Value>,
+ key: &str,
+ ) -> anyhow::Result<i64> {
+ params
+ .get(key)
+ .and_then(Value::as_i64)
+ .ok_or_else(|| anyhow::anyhow!("Missing or invalid '{key}' parameter"))
+ }
+
+ fn validate_computer_use_action(
+ &self,
+ action: &str,
+ params: &serde_json::Map<String, Value>,
+ ) -> anyhow::Result<()> {
+ match action {
+ "open" => {
+ let url = params
+ .get("url")
+ .and_then(Value::as_str)
+ .ok_or_else(|| anyhow::anyhow!("Missing 'url' for open action"))?;
+ self.validate_url(url)?;
+ }
+ "mouse_move" | "mouse_click" => {
+ let x = self.read_required_i64(params, "x")?;
+ let y = self.read_required_i64(params, "y")?;
+ self.validate_coordinate("x", x, self.computer_use.max_coordinate_x)?;
+ self.validate_coordinate("y", y, self.computer_use.max_coordinate_y)?;
+ }
+ "mouse_drag" => {
+ let from_x = self.read_required_i64(params, "from_x")?;
+ let from_y = self.read_required_i64(params, "from_y")?;
+ let to_x = self.read_required_i64(params, "to_x")?;
+ let to_y = self.read_required_i64(params, "to_y")?;
+ self.validate_coordinate("from_x", from_x, self.computer_use.max_coordinate_x)?;
+ self.validate_coordinate("to_x", to_x, self.computer_use.max_coordinate_x)?;
+ self.validate_coordinate("from_y", from_y, self.computer_use.max_coordinate_y)?;
+ self.validate_coordinate("to_y", to_y, self.computer_use.max_coordinate_y)?;
+ }
+ _ => {}
+ }
+ Ok(())
+ }
+
+ async fn execute_computer_use_action(
+ &self,
+ action: &str,
+ args: &Value,
+ ) -> anyhow::Result<ToolResult> {
+ let endpoint = self.computer_use_endpoint_url()?;
+
+ let mut params = args
+ .as_object()
+ .cloned()
+ .ok_or_else(|| anyhow::anyhow!("browser args must be a JSON object"))?;
+ params.remove("action");
+
+ self.validate_computer_use_action(action, &params)?;
+
+ let payload = json!({
+ "action": action,
+ "params": params,
+ "policy": {
+ "allowed_domains": self.allowed_domains,
+ "window_allowlist": self.computer_use.window_allowlist,
+ "max_coordinate_x": self.computer_use.max_coordinate_x,
+ "max_coordinate_y": self.computer_use.max_coordinate_y,
+ },
+ "metadata": {
+ "session_name": self.session_name,
+ "source": "openhuman.browser",
+ "version": env!("CARGO_PKG_VERSION"),
+ }
+ });
+
+ let client = crate::config::build_runtime_proxy_client("tool.browser");
+ let mut request = client
+ .post(endpoint)
+ .timeout(Duration::from_millis(self.computer_use.timeout_ms))
+ .json(&payload);
+
+ if let Some(api_key) = self.computer_use.api_key.as_deref() {
+ let token = api_key.trim();
+ if !token.is_empty() {
+ request = request.bearer_auth(token);
+ }
+ }
+
+ let response = request.send().await.with_context(|| {
+ format!(
+ "Failed to call computer-use sidecar at {}",
+ self.computer_use.endpoint
+ )
+ })?;
+
+ let status = response.status();
+ let body = response
+ .text()
+ .await
+ .context("Failed to read computer-use sidecar response body")?;
+
+ if let Ok(parsed) = serde_json::from_str::<ComputerUseResponse>(&body) {
+ if status.is_success() && parsed.success.unwrap_or(true) {
+ let output = parsed
+ .data
+ .map(|data| serde_json::to_string_pretty(&data).unwrap_or_default())
+ .unwrap_or_else(|| {
+ serde_json::to_string_pretty(&json!({
+ "backend": "computer_use",
+ "action": action,
+ "ok": true,
+ }))
+ .unwrap_or_default()
+ });
+
+ return Ok(ToolResult::success(output));
+ }
+
+ let error = parsed.error.or_else(|| {
+ if status.is_success() && parsed.success == Some(false) {
+ Some("computer-use sidecar returned success=false".to_string())
+ } else {
+ Some(format!(
+ "computer-use sidecar request failed with status {status}"
+ ))
+ }
+ });
+
+ return Ok(ToolResult::error(error.unwrap_or_default()));
+ }
+
+ if status.is_success() {
+ return Ok(ToolResult::success(body));
+ }
+
+ Ok(ToolResult::error(format!(
+ "computer-use sidecar request failed with status {status}: {}",
+ body.trim()
+ )))
+ }
+
+}
diff --git a/crates/openhuman-core/src/tools/impl/browser/browser_construction.rs b/crates/openhuman-core/src/tools/impl/browser/browser_construction.rs
new file mode 100644
index 0000000000..bc5700c2b0
--- /dev/null
+++ b/crates/openhuman-core/src/tools/impl/browser/browser_construction.rs
@@ -0,0 +1,96 @@
+//! [`BrowserTool`] construction and availability probes.
+
+use super::*;
+
+impl BrowserTool {
+ pub fn new(
+ security: Arc<SecurityPolicy>,
+ allowed_domains: Vec<String>,
+ session_name: Option<String>,
+ ) -> Self {
+ Self::new_with_backend(
+ security,
+ allowed_domains,
+ session_name,
+ "agent_browser".into(),
+ true,
+ "http://127.0.0.1:9515".into(),
+ None,
+ ComputerUseConfig::default(),
+ )
+ }
+
+ #[allow(clippy::too_many_arguments)]
+ pub fn new_with_backend(
+ security: Arc<SecurityPolicy>,
+ allowed_domains: Vec<String>,
+ session_name: Option<String>,
+ backend: String,
+ native_headless: bool,
+ native_webdriver_url: String,
+ native_chrome_path: Option<String>,
+ computer_use: ComputerUseConfig,
+ ) -> Self {
+ Self {
+ security,
+ allowed_domains: normalize_domains(allowed_domains),
+ session_name,
+ backend,
+ native_headless,
+ native_webdriver_url,
+ native_chrome_path,
+ computer_use,
+ playwright_state: tokio::sync::Mutex::new(
+ playwright_backend::PlaywrightBrowserState::default(),
+ ),
+ #[cfg(feature = "browser-native")]
+ native_state: tokio::sync::Mutex::new(native_backend::NativeBrowserState::default()),
+ }
+ }
+
+ /// Check if agent-browser tool is available
+ pub async fn is_agent_browser_available() -> bool {
+ Command::new("agent-browser")
+ .arg("--version")
+ .stdout(Stdio::null())
+ .stderr(Stdio::null())
+ .status()
+ .await
+ .map(|s| s.success())
+ .unwrap_or(false)
+ }
+
+ /// Backward-compatible alias.
+ pub async fn is_available() -> bool {
+ Self::is_agent_browser_available().await
+ }
+
+ /// Check if the local Playwright package is available to Node.js.
+ pub async fn is_playwright_available() -> bool {
+ playwright_backend::PlaywrightBrowserState::is_available().await
+ }
+
+ fn configured_backend(&self) -> anyhow::Result<BrowserBackendKind> {
+ BrowserBackendKind::parse(&self.backend)
+ }
+
+ fn rust_native_compiled() -> bool {
+ cfg!(feature = "browser-native")
+ }
+
+ fn rust_native_available(&self) -> bool {
+ #[cfg(feature = "browser-native")]
+ {
+ native_backend::NativeBrowserState::is_available(
+ self.native_headless,
+ &self.native_webdriver_url,
+ self.native_chrome_path.as_deref(),
+ )
+ }
+ #[cfg(not(feature = "browser-native"))]
+ {
+ false
+ }
+ }
+
+}
diff --git a/crates/openhuman-core/src/tools/impl/browser/browser_execution.rs b/crates/openhuman-core/src/tools/impl/browser/browser_execution.rs
new file mode 100644
index 0000000000..d8a34cd13c
--- /dev/null
+++ b/crates/openhuman-core/src/tools/impl/browser/browser_execution.rs
@@ -0,0 +1,264 @@
+//! Backend action execution and dispatch for [`BrowserTool`].
+
+use super::*;
+
+impl BrowserTool {
+ async fn run_command(&self, args: &[&str]) -> anyhow::Result<AgentBrowserResponse> {
+ let mut cmd = Command::new("agent-browser");
+
+ // Add session if configured
+ if let Some(ref session) = self.session_name {
+ cmd.arg("--session").arg(session);
+ }
+
+ // Add --json for machine-readable output
+ cmd.args(args).arg("--json");
+
+ debug!("Running: agent-browser {} --json", args.join(" "));
+
+ let output = cmd
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped())
+ .output()
+ .await?;
+
+ let stdout = String::from_utf8_lossy(&output.stdout);
+ let stderr = String::from_utf8_lossy(&output.stderr);
+
+ if !stderr.is_empty() {
+ debug!("agent-browser stderr: {}", stderr);
+ }
+
+ // Parse JSON response
+ if let Ok(resp) = serde_json::from_str::<AgentBrowserResponse>(&stdout) {
+ return Ok(resp);
+ }
+
+ // Fallback for non-JSON output
+ if output.status.success() {
+ Ok(AgentBrowserResponse {
+ success: true,
+ data: Some(json!({ "output": stdout.trim() })),
+ error: None,
+ })
+ } else {
+ Ok(AgentBrowserResponse {
+ success: false,
+ data: None,
+ error: Some(stderr.trim().to_string()),
+ })
+ }
+ }
+
+ /// Execute a browser action via agent-browser tool
+ #[allow(clippy::too_many_lines)]
+ async fn execute_agent_browser_action(
+ &self,
+ action: BrowserAction,
+ ) -> anyhow::Result<ToolResult> {
+ match action {
+ BrowserAction::Open { url } => {
+ self.validate_url(&url)?;
+ let resp = self.run_command(&["open", &url]).await?;
+ self.to_result(resp)
+ }
+
+ BrowserAction::Snapshot {
+ interactive_only,
+ compact,
+ depth,
+ } => {
+ let mut args = vec!["snapshot"];
+ if interactive_only {
+ args.push("-i");
+ }
+ if compact {
+ args.push("-c");
+ }
+ let depth_str;
+ if let Some(d) = depth {
+ args.push("-d");
+ depth_str = d.to_string();
+ args.push(&depth_str);
+ }
+ let resp = self.run_command(&args).await?;
+ self.to_result(resp)
+ }
+
+ BrowserAction::Click { selector } => {
+ let resp = self.run_command(&["click", &selector]).await?;
+ self.to_result(resp)
+ }
+
+ BrowserAction::Fill { selector, value } => {
+ let resp = self.run_command(&["fill", &selector, &value]).await?;
+ self.to_result(resp)
+ }
+
+ BrowserAction::Type { selector, text } => {
+ let resp = self.run_command(&["type", &selector, &text]).await?;
+ self.to_result(resp)
+ }
+
+ BrowserAction::GetText { selector } => {
+ let resp = self.run_command(&["get", "text", &selector]).await?;
+ self.to_result(resp)
+ }
+
+ BrowserAction::GetTitle => {
+ let resp = self.run_command(&["get", "title"]).await?;
+ self.to_result(resp)
+ }
+
+ BrowserAction::GetUrl => {
+ let resp = self.run_command(&["get", "url"]).await?;
+ self.to_result(resp)
+ }
+
+ BrowserAction::Wait { selector, ms, text } => {
+ let mut args = vec!["wait"];
+ let ms_str;
+ if let Some(sel) = selector.as_ref() {
+ args.push(sel);
+ } else if let Some(millis) = ms {
+ ms_str = millis.to_string();
+ args.push(&ms_str);
+ } else if let Some(ref t) = text {
+ args.push("--text");
+ args.push(t);
+ }
+ let resp = self.run_command(&args).await?;
+ self.to_result(resp)
+ }
+
+ BrowserAction::Press { key } => {
+ let resp = self.run_command(&["press", &key]).await?;
+ self.to_result(resp)
+ }
+
+ BrowserAction::Hover { selector } => {
+ let resp = self.run_command(&["hover", &selector]).await?;
+ self.to_result(resp)
+ }
+
+ BrowserAction::Scroll { direction, pixels } => {
+ let mut args = vec!["scroll", &direction];
+ let px_str;
+ if let Some(px) = pixels {
+ px_str = px.to_string();
+ args.push(&px_str);
+ }
+ let resp = self.run_command(&args).await?;
+ self.to_result(resp)
+ }
+
+ BrowserAction::IsVisible { selector } => {
+ let resp = self.run_command(&["is", "visible", &selector]).await?;
+ self.to_result(resp)
+ }
+
+ BrowserAction::Close => {
+ let resp = self.run_command(&["close"]).await?;
+ self.to_result(resp)
+ }
+
+ BrowserAction::Find {
+ by,
+ value,
+ action,
+ fill_value,
+ } => {
+ let mut args = vec!["find", &by, &value, &action];
+ if let Some(ref fv) = fill_value {
+ args.push(fv);
+ }
+ let resp = self.run_command(&args).await?;
+ self.to_result(resp)
+ }
+ }
+ }
+
+ #[allow(clippy::unused_async)]
+ async fn execute_rust_native_action(
+ &self,
+ action: BrowserAction,
+ ) -> anyhow::Result<ToolResult> {
+ #[cfg(feature = "browser-native")]
+ {
+ let mut state = self.native_state.lock().await;
+
+ let output = state
+ .execute_action(
+ action,
+ self.native_headless,
+ &self.native_webdriver_url,
+ self.native_chrome_path.as_deref(),
+ )
+ .await?;
+
+ Ok(ToolResult::success(
+ serde_json::to_string_pretty(&output).unwrap_or_default(),
+ ))
+ }
+
+ #[cfg(not(feature = "browser-native"))]
+ {
+ let _ = action;
+ anyhow::bail!(
+ "Rust-native browser backend is not compiled. Rebuild with --features browser-native"
+ )
+ }
+ }
+
+ async fn execute_playwright_action(&self, action: BrowserAction) -> anyhow::Result<ToolResult> {
+ if let BrowserAction::Open { url } = &action {
+ debug!("[browser] validating playwright open url before dispatch");
+ self.validate_url(url)?;
+ }
+
+ let mut state = self.playwright_state.lock().await;
+ let output = state
+ .execute_action(
+ action,
+ self.native_headless,
+ Some(playwright_backend::BrowserUrlPolicy {
+ allowed_domains: self.allowed_domains.clone(),
+ allow_all: allow_all_browser_domains(),
+ }),
+ )
+ .await
+ .context("Playwright browser action failed")?;
+
+ Ok(ToolResult::success(
+ serde_json::to_string_pretty(&output).unwrap_or_default(),
+ ))
+ }
+
+ async fn execute_action(
+ &self,
+ action: BrowserAction,
+ backend: ResolvedBackend,
+ ) -> anyhow::Result<ToolResult> {
+ match backend {
+ ResolvedBackend::AgentBrowser => self.execute_agent_browser_action(action).await,
+ ResolvedBackend::Playwright => self.execute_playwright_action(action).await,
+ ResolvedBackend::RustNative => self.execute_rust_native_action(action).await,
+ ResolvedBackend::ComputerUse => anyhow::bail!(
+ "Internal error: computer_use backend must be handled before BrowserAction parsing"
+ ),
+ }
+ }
+
+ #[allow(clippy::unnecessary_wraps, clippy::unused_self)]
+ fn to_result(&self, resp: AgentBrowserResponse) -> anyhow::Result<ToolResult> {
+ if resp.success {
+ let output = resp
+ .data
+ .map(|d| serde_json::to_string_pretty(&d).unwrap_or_default())
+ .unwrap_or_default();
+ Ok(ToolResult::success(output))
+ } else {
+ Ok(ToolResult::error(resp.error.unwrap_or_default()))
+ }
+ }
+}
diff --git a/crates/openhuman-core/src/web_chat/ops/budget_correlation.rs b/crates/openhuman-core/src/web_chat/ops/budget_correlation.rs
new file mode 100644
index 0000000000..c965fdf2e4
--- /dev/null
+++ b/crates/openhuman-core/src/web_chat/ops/budget_correlation.rs
@@ -0,0 +1,156 @@
+//! Per-thread inference-budget-exhaustion correlator (#3386).
+//!
+//! When a turn terminates with a budget-exhausted error we record a signal;
+//! a *later* empty-response turn on the same thread and provider binding
+//! consults it to upgrade the generic "empty response" copy into the
+//! actionable out-of-credits copy.
+
+use std::collections::HashMap;
+use std::time::{Duration, Instant};
+
+use once_cell::sync::Lazy;
+use tokio::sync::Mutex;
+
+use super::state::key_for;
+
+/// A recorded budget-exhausted signal: when it happened, and which provider
+/// binding it happened on. The binding scopes the signal so a managed
+/// out-of-credits error never mislabels a later empty turn the user has
+/// re-routed to a different provider (local / BYO), whose balance is unrelated.
+#[derive(Debug, Clone)]
+struct BudgetSignal {
+ provider_binding: String,
+ at: Instant,
+}
+
+/// Per-thread "recent budget-exhausted" signal (issue #3386).
+///
+/// Set when a turn terminates with an inference budget-exhausted error; read by
+/// a *later* turn on the same thread whose provider returned an empty 200. The
+/// managed route closes the SSE cleanly under credit exhaustion (the response
+/// already flushed HTTP 200, so there is no error frame and no inline budget
+/// marker — `OpenHumanBilling` carries only `charged_amount_usd`). Without this
+/// correlator such a budget-caused empty turn surfaces as the generic "empty
+/// response" copy instead of the actionable out-of-credits copy.
+///
+/// The signal is scoped to the provider binding it was recorded on: budget is a
+/// per-provider fact, so a managed-route exhaustion must not reclassify an empty
+/// turn the thread has since re-routed to a local / BYO provider.
+///
+/// Kept in a sibling map rather than on `SessionEntry` so the signal survives
+/// the de-poison session drop (an empty turn is not poisoned, but cold-boot
+/// reseeds would otherwise be the wrong lifetime to hang this on).
+static THREAD_BUDGET_SIGNALS: Lazy<Mutex<HashMap<String, BudgetSignal>>> =
+ Lazy::new(|| Mutex::new(HashMap::new()));
+
+/// How long a recorded budget-exhausted signal stays eligible to reclassify a
+/// later empty turn on the same thread. Five minutes: long enough to bridge a
+/// user retry after the first out-of-credits turn, short enough that a genuine
+/// empty response well after the fact isn't mislabeled. A successful turn clears
+/// the signal regardless (the balance is evidently usable again). See #3386.
+const BUDGET_SIGNAL_TTL: Duration = Duration::from_secs(5 * 60);
+
+/// Pure freshness predicate (age vs TTL), split out for clock-free testing.
+fn budget_signal_is_fresh(age: Duration, ttl: Duration) -> bool {
+ age <= ttl
+}
+
+/// Drop every expired entry from the map, not just the one being queried.
+/// Without this, a thread that hits budget exhaustion and then never retries or
+/// succeeds would leak its entry for the process lifetime. Called on the write
+/// path so each new budget event sweeps the map.
+fn prune_stale_budget_signals(signals: &mut HashMap<String, BudgetSignal>) {
+ signals.retain(|_, sig| budget_signal_is_fresh(sig.at.elapsed(), BUDGET_SIGNAL_TTL));
+}
+
+/// Record that this thread just hit an inference budget-exhausted error on the
+/// given provider binding.
+pub(crate) async fn record_budget_signal(thread_id: &str, provider_binding: &str) {
+ let mut signals = THREAD_BUDGET_SIGNALS.lock().await;
+ prune_stale_budget_signals(&mut signals);
+ signals.insert(
+ key_for(thread_id),
+ BudgetSignal {
+ provider_binding: provider_binding.to_string(),
+ at: Instant::now(),
+ },
+ );
+}
+
+/// Clear any recorded budget signal for this thread — called on a successful
+/// turn, where the balance is evidently usable again.
+pub(crate) async fn clear_budget_signal(thread_id: &str) {
+ let mut signals = THREAD_BUDGET_SIGNALS.lock().await;
+ signals.remove(&key_for(thread_id));
+}
+
+/// Whether this thread has a budget signal recorded within `BUDGET_SIGNAL_TTL`
+/// **on the same provider binding** as the current turn. A binding mismatch or
+/// an expired entry evicts it and reads as not-fresh, so a re-routed turn never
+/// inherits the prior provider's exhaustion.
+pub(crate) async fn has_fresh_budget_signal(thread_id: &str, provider_binding: &str) -> bool {
+ let mut signals = THREAD_BUDGET_SIGNALS.lock().await;
+ let key = key_for(thread_id);
+ match signals.get(&key) {
+ Some(sig)
+ if sig.provider_binding == provider_binding
+ && budget_signal_is_fresh(sig.at.elapsed(), BUDGET_SIGNAL_TTL) =>
+ {
+ true
+ }
+ Some(_) => {
+ signals.remove(&key);
+ false
+ }
+ None => false,
+ }
+}
+
+/// Test-only seeder: record a budget signal on `provider_binding` aged `age`
+/// into the past so expiry can be exercised without sleeping.
+#[cfg(test)]
+async fn record_budget_signal_aged(thread_id: &str, provider_binding: &str, age: Duration) {
+ let mut signals = THREAD_BUDGET_SIGNALS.lock().await;
+ let when = Instant::now().checked_sub(age).unwrap_or_else(Instant::now);
+ signals.insert(
+ key_for(thread_id),
+ BudgetSignal {
+ provider_binding: provider_binding.to_string(),
+ at: when,
+ },
+ );
+}
+
+/// What the budget-correlator should do with a terminated turn (#3386).
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub(crate) enum BudgetCorrelation {
+ /// The terminal error is itself an inference budget-exhausted error:
+ /// record the signal and surface the budget copy.
+ BudgetExhausted,
+ /// An empty provider response coincided with a fresh same-thread budget
+ /// signal: surface the budget copy in place of the "empty response" copy.
+ UpgradeEmptyToBudget,
+ /// No budget correlation — pass the error through unchanged.
+ PassThrough,
+}
+
+/// Pure decision for the budget-correlator, split out so the branch matrix is
+/// unit-testable without a clock or the full `run_chat_task` frame. The async
+/// helpers above supply `has_fresh_signal`.
+pub(crate) fn classify_budget_correlation(
+ is_budget_error: bool,
+ is_empty_response: bool,
+ has_fresh_signal: bool,
+) -> BudgetCorrelation {
+ if is_budget_error {
+ BudgetCorrelation::BudgetExhausted
+ } else if is_empty_response && has_fresh_signal {
+ BudgetCorrelation::UpgradeEmptyToBudget
+ } else {
+ BudgetCorrelation::PassThrough
+ }
+}
+
+#[cfg(test)]
+#[path = "../ops_budget_correlation_tests_tests.rs"]
+mod budget_correlation_tests;