The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
chore: files changed crates/openhuman-core/src/memory/tree/tree/rpc_tests.rs,crates/openhuman-core/s
Steven Enamakelfe63c7e5e72c
diff --git a/crates/openhuman-core/src/integrations/composio/tools/list_connections.rs b/crates/openhuman-core/src/integrations/composio/tools/list_connections.rsnew file mode 100644index 0000000000..31e1fa02df--- /dev/null+++ b/crates/openhuman-core/src/integrations/composio/tools/list_connections.rs@@ -0,0 +1,122 @@+//! The `composio_list_connections` agent tool.++use std::sync::Arc;++use async_trait::async_trait;+use serde_json::{json, Value};++use crate::config::rpc as config_rpc;+use crate::config::Config;+use crate::tools::traits::{PermissionLevel, Tool, ToolCategory, ToolResult};++use super::super::client::{create_composio_client, direct_list_connections, ComposioClientKind};++pub struct ComposioListConnectionsTool {+ /// Held instead of a pre-baked `ComposioClient` so the+ /// [`crate::config::ComposioConfig::mode`] toggle is+ /// honoured on every call (#1710).+ config: Arc<Config>,+}++impl ComposioListConnectionsTool {+ pub fn new(config: Arc<Config>) -> Self {+ Self { config }+ }+}++#[async_trait]+impl Tool for ComposioListConnectionsTool {+ fn name(&self) -> &str {+ "composio_list_connections"+ }+ fn description(&self) -> &str {+ "List the user's **currently-connected** Composio integrations. \+ Only entries with status ACTIVE / CONNECTED are returned; pending, \+ revoked, or failed connections are filtered out. Use this to detect \+ newly-authorised integrations mid-session. Each entry has \+ {id, toolkit, status, createdAt}."+ }+ fn parameters_schema(&self) -> Value {+ json!({ "type": "object", "properties": {}, "additionalProperties": false })+ }+ fn permission_level(&self) -> PermissionLevel {+ PermissionLevel::ReadOnly+ }+ fn category(&self) -> ToolCategory {+ ToolCategory::Workflow+ }+ async fn execute(&self, _args: Value) -> anyhow::Result<ToolResult> {+ tracing::debug!("[composio] tool list_connections.execute");+ // Mirror `ops::composio_list_connections`: route through the mode-aware+ // factory so the agent sees the correct tenant's connections in both+ // backend and direct mode. Before this fix, direct mode returned an+ // empty list regardless of the user's actual Composio connections,+ // which caused the agent to incorrectly conclude that no integrations+ // were linked and prompt unnecessary re-authorization (#1710).+ // [#1710 Wave 4] Reload config fresh per execute so a mid-session+ // `composio.mode` toggle takes effect at the very next tool call.+ // Anchor the reload to this tool's original config path rather+ // than re-resolving process-global `OPENHUMAN_WORKSPACE`; the+ // tool is scoped to the user/workspace it was created for.+ let live_config = match config_rpc::reload_config_snapshot_with_timeout(+ self.config.as_ref(),+ )+ .await+ {+ Ok(c) => c,+ Err(e) => {+ tracing::warn!(error = %e, "[composio] list_connections.execute: load_config failed");+ return Ok(ToolResult::error(format!(+ "composio_list_connections: failed to load live config: {e}"+ )));+ }+ };+ let mut resp = match create_composio_client(&live_config) {+ Ok(ComposioClientKind::Backend(client)) => {+ tracing::debug!("[composio] list_connections.execute: backend variant");+ client.list_connections().await.map_err(|e| {+ anyhow::anyhow!("composio_list_connections (backend) failed: {e}")+ })?+ }+ Ok(ComposioClientKind::Direct(direct)) => {+ tracing::debug!("[composio-direct] list_connections.execute: direct variant");+ direct_list_connections(&direct).await.map_err(|e| {+ // [#1166 / Sentry TAURI-RUST-X9] Symmetric error+ // routing with `ops.rs::composio_list_connections`.+ // The agent-tool path can also fire 401s when a+ // direct-mode user has a bad API key — without this+ // hook the failure escapes the classifier and lands+ // as an unclassified Sentry event. Render WITH the+ // `[composio-direct]` anchor BEFORE reporting so the+ // classifier arm in `is_provider_user_state_message`+ // (gated on that prefix) actually fires.+ let rendered = format!(+ "[composio-direct] composio_list_connections (direct) failed: {e:#}"+ );+ super::super::ops::report_composio_op_error("list_connections", &rendered);+ anyhow::anyhow!("{rendered}")+ })?+ }+ Err(e) => {+ return Ok(ToolResult::error(format!(+ "composio_list_connections failed: {e}"+ )));+ }+ };+ // Filter server-side-indistinguishable states — callers should only+ // see integrations the user can actually act on. Matches the same+ // ACTIVE/CONNECTED allowlist used by `fetch_connected_integrations_uncached`+ // so the tool output and the prompt's Delegation Guide agree on what+ // counts as "connected".+ resp.connections.retain(|c| c.is_active());+ tracing::debug!(+ count = resp.connections.len(),+ "[composio] list_connections.execute: returning active connections"+ );+ Ok(ToolResult::success(+ serde_json::to_string(&resp).unwrap_or_else(|_| "{}".into()),+ ))+ }+}++// ── composio_authorize ──────────────────────────────────────────────diff --git a/crates/openhuman-core/src/integrations/composio/tools/list_toolkits.rs b/crates/openhuman-core/src/integrations/composio/tools/list_toolkits.rsnew file mode 100644index 0000000000..48a9ba6975--- /dev/null+++ b/crates/openhuman-core/src/integrations/composio/tools/list_toolkits.rs@@ -0,0 +1,107 @@+//! The `composio_list_toolkits` agent tool.++use std::sync::Arc;++use async_trait::async_trait;+use serde_json::{json, Value};++use crate::config::rpc as config_rpc;+use crate::config::Config;+use crate::tools::traits::{PermissionLevel, Tool, ToolCategory, ToolResult};++use super::super::client::{create_composio_client, ComposioClientKind};+++pub struct ComposioListToolkitsTool {+ /// Held instead of a pre-baked `ComposioClient` so the+ /// [`crate::config::ComposioConfig::mode`] toggle is+ /// honoured on every call (see [`ComposioExecuteTool`] doc for the+ /// bug this guards against — #1710).+ config: Arc<Config>,+}++impl ComposioListToolkitsTool {+ pub fn new(config: Arc<Config>) -> Self {+ Self { config }+ }+}++#[async_trait]+impl Tool for ComposioListToolkitsTool {+ fn name(&self) -> &str {+ "composio_list_toolkits"+ }+ fn description(&self) -> &str {+ "List the Composio toolkits currently enabled on the backend allowlist. \+ Use this before calling composio_authorize or composio_list_tools to see what \+ is allowed (e.g. gmail, notion)."+ }+ fn parameters_schema(&self) -> Value {+ json!({ "type": "object", "properties": {}, "additionalProperties": false })+ }+ fn permission_level(&self) -> PermissionLevel {+ PermissionLevel::ReadOnly+ }+ fn category(&self) -> ToolCategory {+ // Composio proxies to external SaaS (Gmail, Notion, …), so it+ // lives in the Workflow category and is picked up by sub-agents+ // with `category_filter = "skill"`.+ ToolCategory::Workflow+ }+ async fn execute(&self, _args: Value) -> anyhow::Result<ToolResult> {+ tracing::debug!("[composio] tool list_toolkits.execute");+ // Mirror the mode-aware pattern in+ // `ops::composio_list_toolkits`. In direct mode there is no+ // server-side allowlist; the user's personal Composio account+ // governs availability, so we return an empty toolkits list+ // with an explanatory log instead of silently routing through+ // the backend tinyhumans tenant (#1710).+ // [#1710 Wave 4] Reload config fresh per execute so a mid-session+ // `composio.mode` toggle takes effect at the very next tool call.+ // Anchor the reload to this tool's original config path rather+ // than re-resolving process-global `OPENHUMAN_WORKSPACE`; the+ // tool is scoped to the user/workspace it was created for.+ let live_config =+ match config_rpc::reload_config_snapshot_with_timeout(self.config.as_ref()).await {+ Ok(c) => c,+ Err(e) => {+ tracing::warn!(error = %e, "[composio] tool: load_config failed");+ return Ok(ToolResult::error(format!(+ "composio: failed to load live config: {e}"+ )));+ }+ };+ let client = match create_composio_client(&live_config) {+ Ok(ComposioClientKind::Backend(client)) => {+ tracing::debug!("[composio] list_toolkits.execute: backend variant");+ client+ }+ Ok(ComposioClientKind::Direct(_)) => {+ tracing::info!(+ "[composio-direct] list_toolkits.execute: direct mode active — \+ returning empty toolkits list. Users manage available toolkits \+ via app.composio.dev."+ );+ let resp = super::super::types::ComposioToolkitsResponse::default();+ return Ok(ToolResult::success(+ serde_json::to_string(&resp).unwrap_or_else(|_| "{}".into()),+ ));+ }+ Err(e) => {+ return Ok(ToolResult::error(format!(+ "composio_list_toolkits failed: {e}"+ )));+ }+ };+ match client.list_toolkits().await {+ Ok(resp) => Ok(ToolResult::success(+ serde_json::to_string(&resp).unwrap_or_else(|_| "{}".into()),+ )),+ Err(e) => Ok(ToolResult::error(format!(+ "composio_list_toolkits failed: {e}"+ ))),+ }+ }+}++// ── composio_list_connections ───────────────────────────────────────diff --git a/crates/openhuman-core/src/memory/tree/tree/rpc_tests.rs b/crates/openhuman-core/src/memory/tree/tree/rpc_tests.rsindex 4556021310..918f53a863 100644--- a/crates/openhuman-core/src/memory/tree/tree/rpc_tests.rs+++ b/crates/openhuman-core/src/memory/tree/tree/rpc_tests.rs@@ -94,7 +94,7 @@ fn reported_failure(}}-#[path = "rpc_tests_part_01_tests.rs"]-mod part_01_tests;-#[path = "rpc_tests_part_02_tests.rs"]-mod part_02_tests;+#[path = "rpc_ingest_and_chunk_tests.rs"]+mod ingest_and_chunk_tests;+#[path = "rpc_pipeline_status_tests.rs"]+mod pipeline_status_tests;diff --git a/crates/openhuman-core/src/threads/todos/schemas/handlers.rs b/crates/openhuman-core/src/threads/todos/schemas/handlers.rsnew file mode 100644index 0000000000..35edaf7641--- /dev/null+++ b/crates/openhuman-core/src/threads/todos/schemas/handlers.rs@@ -0,0 +1,395 @@+//! Thin JSON-RPC handlers that parse params and delegate to+//! [`super::super::ops`] and [`super::super::runs`].++use serde::de::DeserializeOwned;+use serde::Deserialize;+use serde_json::{Map, Value};++use crate::agent::task_board::{TaskApprovalMode, TaskBoardCard};+use crate::core::all::ControllerFuture;++use super::super::ops::{self, BoardLocation, CardPatch, TodosSnapshot};+use super::super::runs;++#[derive(Debug, Deserialize)]+struct ThreadIdParams {+ thread_id: String,+}++#[derive(Debug, Deserialize)]+struct AddParams {+ thread_id: String,+ content: String,+ #[serde(default, alias = "sourceMetadata")]+ source_metadata: Option<Value>,+ #[serde(default)]+ status: Option<String>,+ #[serde(default)]+ objective: Option<String>,+ #[serde(default)]+ plan: Option<Vec<String>>,+ #[serde(default, alias = "assignedAgent")]+ assigned_agent: Option<String>,+ #[serde(default)]+ #[serde(alias = "allowedTools")]+ allowed_tools: Option<Vec<String>>,+ #[serde(default)]+ #[serde(alias = "approvalMode")]+ approval_mode: Option<String>,+ #[serde(default)]+ #[serde(alias = "acceptanceCriteria")]+ acceptance_criteria: Option<Vec<String>>,+ #[serde(default)]+ evidence: Option<Vec<String>>,+ #[serde(default)]+ notes: Option<String>,+ #[serde(default)]+ blocker: Option<String>,+}++#[derive(Debug, Deserialize)]+struct EditParams {+ thread_id: String,+ id: String,+ #[serde(default)]+ content: Option<String>,+ #[serde(default)]+ status: Option<String>,+ #[serde(default)]+ objective: Option<String>,+ #[serde(default)]+ plan: Option<Vec<String>>,+ #[serde(default, alias = "assignedAgent")]+ assigned_agent: Option<String>,+ #[serde(default)]+ #[serde(alias = "allowedTools")]+ allowed_tools: Option<Vec<String>>,+ #[serde(default)]+ #[serde(alias = "acceptanceCriteria")]+ acceptance_criteria: Option<Vec<String>>,+ #[serde(default)]+ evidence: Option<Vec<String>>,+ #[serde(default)]+ notes: Option<String>,+ #[serde(default)]+ blocker: Option<String>,+}++#[derive(Debug, Deserialize)]+struct UpdateStatusParams {+ thread_id: String,+ id: String,+ status: String,+}++#[derive(Debug, Deserialize)]+struct RemoveParams {+ thread_id: String,+ id: String,+}++#[derive(Debug, Deserialize)]+struct SetSessionThreadParams {+ thread_id: String,+ id: String,+ #[serde(default, alias = "sessionThreadId")]+ session_thread_id: Option<String>,+}++#[derive(Debug, Deserialize)]+struct DecidePlanParams {+ thread_id: String,+ id: String,+ approve: bool,+}++#[derive(Debug, Deserialize)]+struct RevisePlanParams {+ thread_id: String,+ #[serde(default)]+ feedback: String,+}++#[derive(Debug, Deserialize)]+struct ReplaceParams {+ thread_id: String,+ cards: Vec<TaskBoardCard>,+}++pub(super) fn handle_list(params: Map<String, Value>) -> ControllerFuture {+ Box::pin(async move {+ let p = parse::<ThreadIdParams>(params)?;+ let loc = thread_location(&p.thread_id).await?;+ tracing::debug!(thread_id = %p.thread_id, "[rpc][todos] list entry");+ snapshot_to_json(ops::list(&loc).await?)+ })+}++pub(super) fn handle_add(params: Map<String, Value>) -> ControllerFuture {+ Box::pin(async move {+ let p = parse::<AddParams>(params)?;+ let loc = thread_location(&p.thread_id).await?;+ let patch = CardPatch {+ content: None,+ status: p.status.as_deref().map(ops::parse_status).transpose()?,+ objective: p.objective,+ plan: p.plan,+ assigned_agent: p.assigned_agent,+ allowed_tools: p.allowed_tools,+ approval_mode: Some(parse_approval_mode(p.approval_mode)?),+ acceptance_criteria: p.acceptance_criteria,+ evidence: p.evidence,+ notes: p.notes,+ blocker: p.blocker,+ // Carry the originating source identifiers onto the promoted card so+ // the inbox can tell an item was already picked up (dedup/hide).+ source_metadata: p.source_metadata,+ };+ tracing::debug!(thread_id = %p.thread_id, "[rpc][todos] add entry");+ snapshot_to_json(ops::add(&loc, &p.content, patch).await?)+ })+}++pub(super) fn handle_edit(params: Map<String, Value>) -> ControllerFuture {+ Box::pin(async move {+ let approval_mode = approval_mode_patch_from_params(¶ms)?;+ let p = parse::<EditParams>(params)?;+ let loc = thread_location(&p.thread_id).await?;+ let patch = CardPatch {+ content: p.content,+ status: p.status.as_deref().map(ops::parse_status).transpose()?,+ objective: p.objective,+ plan: p.plan,+ assigned_agent: p.assigned_agent,+ allowed_tools: p.allowed_tools,+ approval_mode,+ acceptance_criteria: p.acceptance_criteria,+ evidence: p.evidence,+ notes: p.notes,+ blocker: p.blocker,+ source_metadata: None,+ };+ tracing::debug!(thread_id = %p.thread_id, id = %p.id, "[rpc][todos] edit entry");+ snapshot_to_json(ops::edit(&loc, &p.id, patch).await?)+ })+}++pub(super) fn handle_update_status(params: Map<String, Value>) -> ControllerFuture {+ Box::pin(async move {+ let p = parse::<UpdateStatusParams>(params)?;+ let loc = thread_location(&p.thread_id).await?;+ let status = ops::parse_status(&p.status)?;+ tracing::debug!(+ thread_id = %p.thread_id,+ id = %p.id,+ status = %p.status,+ "[rpc][todos] update_status entry"+ );+ snapshot_to_json(ops::update_status(&loc, &p.id, status).await?)+ })+}++pub(super) fn handle_set_session_thread(params: Map<String, Value>) -> ControllerFuture {+ Box::pin(async move {+ let p = parse::<SetSessionThreadParams>(params)?;+ let loc = thread_location(&p.thread_id).await?;+ tracing::debug!(+ thread_id = %p.thread_id,+ id = %p.id,+ session_thread_id = ?p.session_thread_id,+ "[rpc][todos] set_session_thread entry"+ );+ snapshot_to_json(ops::set_session_thread(&loc, &p.id, p.session_thread_id).await?)+ })+}++pub(super) fn handle_decide_plan(params: Map<String, Value>) -> ControllerFuture {+ Box::pin(async move {+ let p = parse::<DecidePlanParams>(params)?;+ let loc = thread_location(&p.thread_id).await?;+ tracing::debug!(+ thread_id = %p.thread_id,+ id = %p.id,+ approve = p.approve,+ "[rpc][todos] decide_plan entry"+ );+ snapshot_to_json(ops::decide_plan(&loc, &p.id, p.approve).await?)+ })+}++pub(super) fn handle_revise_plan(params: Map<String, Value>) -> ControllerFuture {+ Box::pin(async move {+ let p = parse::<RevisePlanParams>(params)?;+ let loc = thread_location(&p.thread_id).await?;+ tracing::debug!(+ thread_id = %p.thread_id,+ feedback_len = p.feedback.len(),+ "[rpc][todos] revise_plan entry"+ );+ snapshot_to_json(ops::revise_plan(&loc, &p.feedback).await?)+ })+}++fn parse_approval_mode(raw: Option<String>) -> Result<Option<TaskApprovalMode>, String> {+ let Some(raw) = raw else {+ return Ok(None);+ };+ match raw.trim() {+ "required" => Ok(Some(TaskApprovalMode::Required)),+ "not_required" => Ok(Some(TaskApprovalMode::NotRequired)),+ other => Err(format!(+ "invalid approval_mode '{other}' (expected required|not_required)"+ )),+ }+}++fn approval_mode_patch_from_params(+ params: &Map<String, Value>,+) -> Result<Option<Option<TaskApprovalMode>>, String> {+ let Some(value) = params+ .get("approvalMode")+ .or_else(|| params.get("approval_mode"))+ else {+ return Ok(None);+ };+ if value.is_null() {+ return Ok(Some(None));+ }+ let Some(raw) = value.as_str() else {+ return Err("invalid approval_mode type (expected required|not_required|null)".to_string());+ };+ parse_approval_mode(Some(raw.to_string())).map(Some)+}++pub(super) fn handle_remove(params: Map<String, Value>) -> ControllerFuture {+ Box::pin(async move {+ let p = parse::<RemoveParams>(params)?;+ let loc = thread_location(&p.thread_id).await?;+ tracing::debug!(thread_id = %p.thread_id, id = %p.id, "[rpc][todos] remove entry");+ snapshot_to_json(ops::remove(&loc, &p.id).await?)+ })+}++pub(super) fn handle_replace(params: Map<String, Value>) -> ControllerFuture {+ Box::pin(async move {+ let p = parse::<ReplaceParams>(params)?;+ let loc = thread_location(&p.thread_id).await?;+ tracing::debug!(+ thread_id = %p.thread_id,+ card_count = p.cards.len(),+ "[rpc][todos] replace entry"+ );+ snapshot_to_json(ops::replace(&loc, p.cards).await?)+ })+}++pub(super) fn handle_clear(params: Map<String, Value>) -> ControllerFuture {+ Box::pin(async move {+ let p = parse::<ThreadIdParams>(params)?;+ let loc = thread_location(&p.thread_id).await?;+ tracing::debug!(thread_id = %p.thread_id, "[rpc][todos] clear entry");+ snapshot_to_json(ops::clear(&loc).await?)+ })+}++// ── run handlers ────────────────────────────────────────────────────++#[derive(Debug, Deserialize)]+struct RunListParams {+ thread_id: String,+ #[serde(default, alias = "cardId")]+ card_id: Option<String>,+}++#[derive(Debug, Deserialize)]+struct RunGetParams {+ thread_id: String,+ #[serde(alias = "runId")]+ run_id: String,+}++#[derive(Debug, Deserialize)]+struct ReclaimStaleParams {+ thread_id: String,+ #[serde(default, alias = "heartbeatStaleSecs")]+ heartbeat_stale_secs: Option<u64>,+ #[serde(default, alias = "claimTtlSecs")]+ claim_ttl_secs: Option<u64>,+ #[serde(default, alias = "maxReclaimCount")]+ max_reclaim_count: Option<u32>,+}++pub(super) fn handle_run_list(params: Map<String, Value>) -> ControllerFuture {+ Box::pin(async move {+ let p = parse::<RunListParams>(params)?;+ let loc = thread_location(&p.thread_id).await?;+ tracing::debug!(+ thread_id = %p.thread_id,+ card_id = ?p.card_id,+ "[rpc][todos] run_list entry"+ );+ let run_list = runs::list_runs(&loc, p.card_id.as_deref()).await?;+ serde_json::to_value(&run_list).map_err(|e| format!("serialize runs: {e}"))+ })+}++pub(super) fn handle_run_get(params: Map<String, Value>) -> ControllerFuture {+ Box::pin(async move {+ let p = parse::<RunGetParams>(params)?;+ let loc = thread_location(&p.thread_id).await?;+ tracing::debug!(+ thread_id = %p.thread_id,+ run_id = %p.run_id,+ "[rpc][todos] run_get entry"+ );+ let run = runs::get_run(&loc, &p.run_id).await?;+ serde_json::to_value(&run).map_err(|e| format!("serialize run: {e}"))+ })+}++pub(super) fn handle_reclaim_stale(params: Map<String, Value>) -> ControllerFuture {+ Box::pin(async move {+ let p = parse::<ReclaimStaleParams>(params)?;+ let loc = thread_location(&p.thread_id).await?;+ let limits = runs::RunLimits {+ heartbeat_stale_secs: p+ .heartbeat_stale_secs+ .unwrap_or(runs::DEFAULT_HEARTBEAT_STALE_SECS),+ claim_ttl_secs: p.claim_ttl_secs.unwrap_or(runs::DEFAULT_CLAIM_TTL_SECS),+ max_reclaim_count: p+ .max_reclaim_count+ .unwrap_or(runs::DEFAULT_MAX_RECLAIM_COUNT),+ };+ tracing::debug!(+ thread_id = %p.thread_id,+ ?limits,+ "[rpc][todos] reclaim_stale entry"+ );+ let result = runs::reclaim_stale(&loc, &limits).await?;+ serde_json::to_value(&result).map_err(|e| format!("serialize reclaim result: {e}"))+ })+}++// ── helpers ──────────────────────────────────────────────────────────++async fn thread_location(thread_id: &str) -> Result<BoardLocation, String> {+ let trimmed = thread_id.trim();+ if trimmed.is_empty() {+ return Err("thread_id must not be empty".to_string());+ }+ let config = crate::config::Config::load_or_init()+ .await+ .map_err(|e| format!("load config: {e}"))?;+ Ok(BoardLocation::Thread {+ workspace_dir: config.workspace_dir,+ thread_id: trimmed.to_string(),+ })+}++fn parse<T: DeserializeOwned>(params: Map<String, Value>) -> Result<T, String> {+ serde_json::from_value(Value::Object(params)).map_err(|e| format!("invalid params: {e}"))+}++fn snapshot_to_json(snap: TodosSnapshot) -> Result<Value, String> {+ serde_json::to_value(&snap).map_err(|e| format!("serialize snapshot: {e}"))+}diff --git a/crates/openhuman-core/src/voice/server/singleton.rs b/crates/openhuman-core/src/voice/server/singleton.rsnew file mode 100644index 0000000000..7695a7275b--- /dev/null+++ b/crates/openhuman-core/src/voice/server/singleton.rs@@ -0,0 +1,111 @@+//! The process-global voice server singleton, plus the embedded auto-start+//! and standalone (CLI) entry points that create/drive it.++use std::sync::Arc;++use log::{info, warn};++use crate::config::Config;+use crate::voice::hotkey::ActivationMode;++use super::runtime::VoiceServer;+use super::types::{ServerState, VoiceServerConfig};+use super::LOG_PREFIX;++/// Global voice server instance, lazily initialized.+static VOICE_SERVER: once_cell::sync::OnceCell<Arc<VoiceServer>> = once_cell::sync::OnceCell::new();++/// Get or initialize the global voice server instance.+pub fn global_server(config: VoiceServerConfig) -> Arc<VoiceServer> {+ VOICE_SERVER+ .get_or_init(|| Arc::new(VoiceServer::new(config)))+ .clone()+}++/// Get the global voice server if already initialized.+pub fn try_global_server() -> Option<Arc<VoiceServer>> {+ VOICE_SERVER.get().cloned()+}++/// Start the embedded global voice server when config enables auto-start.+///+/// This is intended for core process startup. The server runs in the background+/// and reuses the process-global singleton so RPC status/stop calls continue to+/// operate on the same instance.+pub async fn start_if_enabled(app_config: &Config) {+ if !app_config.voice_server.auto_start {+ info!("{LOG_PREFIX} auto-start disabled in config, skipping embedded voice server");+ return;+ }++ let server_config = VoiceServerConfig {+ hotkey: app_config.voice_server.hotkey.clone(),+ activation_mode: match app_config.voice_server.activation_mode {+ crate::config::VoiceActivationMode::Tap => ActivationMode::Tap,+ crate::config::VoiceActivationMode::Push => ActivationMode::Push,+ },+ skip_cleanup: app_config.voice_server.skip_cleanup,+ context: None,+ min_duration_secs: app_config.voice_server.min_duration_secs,+ silence_threshold: app_config.voice_server.silence_threshold,+ custom_dictionary: app_config.voice_server.custom_dictionary.clone(),+ };++ if let Some(existing) = try_global_server() {+ let status = existing.status().await;+ if status.state != ServerState::Stopped {+ info!(+ "{LOG_PREFIX} embedded voice server already running: hotkey={} mode={:?}",+ status.hotkey, status.activation_mode+ );+ return;+ }+ }++ info!(+ "{LOG_PREFIX} auto-start enabled, launching embedded voice server: hotkey={} mode={:?}",+ server_config.hotkey, server_config.activation_mode+ );++ let server = global_server(server_config);+ let config_for_run = app_config.clone();+ let server_for_err = server.clone();+ tokio::spawn(async move {+ if let Err(e) = server.run(&config_for_run).await {+ warn!("{LOG_PREFIX} embedded voice server exited with error: {e}");+ server_for_err.set_last_error(&e).await;+ }+ });+}++/// Run the voice server standalone (blocking). Intended for CLI usage.+///+/// Creates a fresh `VoiceServer` that is **not** registered in the global+/// singleton used by `voice_server_status` RPC. This keeps CLI-started+/// instances isolated from the core RPC lifecycle.+pub async fn run_standalone(+ app_config: Config,+ server_config: VoiceServerConfig,+) -> Result<(), String> {+ info!("{LOG_PREFIX} starting standalone voice server");+ info!("{LOG_PREFIX} hotkey: {}", server_config.hotkey);+ info!("{LOG_PREFIX} mode: {:?}", server_config.activation_mode);+ info!("{LOG_PREFIX} press the hotkey to start dictating");++ let server = VoiceServer::new(server_config);++ // Handle Ctrl+C gracefully.+ let server_arc = Arc::new(server);+ let server_for_signal = server_arc.clone();++ tokio::spawn(async move {+ if let Ok(()) = tokio::signal::ctrl_c().await {+ info!("{LOG_PREFIX} Ctrl+C received, shutting down");+ server_for_signal.stop().await;+ }+ });++ // This is safe because we hold the Arc and nothing else moves it.+ // The server.run() borrows &self, and we await it to completion.+ server_arc.run(&app_config).await+}diff --git a/crates/openhuman-core/src/web_chat/web_errors/response_predicates.rs b/crates/openhuman-core/src/web_chat/web_errors/response_predicates.rsnew file mode 100644index 0000000000..26462d5f8d--- /dev/null+++ b/crates/openhuman-core/src/web_chat/web_errors/response_predicates.rs@@ -0,0 +1,130 @@+//! String-flat predicates over a lowercased error message: recognising the+//! shapes of a poisoned tool-call history, an empty provider response, a+//! dropped connection, a rejected 4xx, or a transient outage.++/// String-flat mirror of+/// `crate::core::observability::is_empty_provider_response_message`.+///+/// The typed `AgentError::EmptyProviderResponse` is collapsed to a `String`+/// at the native-bus boundary before reaching this layer, so we re-detect+/// the same canonical phrase the agent harness emits. Anchored on+/// `"model returned an empty response"` (the verbatim user-facing string from+/// `AgentError::EmptyProviderResponse`) — NOT the looser `"empty response"`,+/// so internal fall-through phrases (`"summarizer returned empty response"`,+/// `"provider returned an empty response; returning empty extraction"`) are+/// not misclassified. Keep the anchor in lockstep with the observability+/// mirror.+///+/// Caller passes the already-lowercased error string.+pub(crate) fn is_empty_provider_response_text(lower: &str) -> bool {+ lower.contains("model returned an empty response")+}++/// User-facing copy for a poisoned-history 400 (orphaned tool message). The+/// de-poison guard (`run_task.rs`) has already evicted the offending warm+/// session by the time this is shown, so "send it again" is literally true.+pub(crate) fn malformed_history_user_message() -> &'static str {+ "We hit a temporary glitch in this conversation — we've cleared it. \+ Please send your message again."+}++/// Detect a malformed tool-history rejection (orphaned / mismatched+/// `role:'tool'` message). This is the *poisoned history* shape the de-poison+/// guard recovers from — NOT a model/parameter mismatch — so it earns the+/// "we cleared it, resend" copy instead of "try a different model".+///+/// Anchored on the managed backend's `validateToolMessageOrdering` strings+/// (verified against tinyhumansai/backend `chatCompletions.ts` — "role 'tool' …+/// matching tool_call", "does not match any tool_call from the preceding+/// assistant message"), the raw upstream jinja variant ("tool role … no+/// previous assistant message with a tool call"), and the equivalent BYO+/// provider phrasings. Caller passes the already-lowercased error string.+pub(crate) fn is_malformed_tool_history_text(lower: &str) -> bool {+ let tool_role = lower.contains("role 'tool'") || lower.contains("tool role");+ let about_tool_call = lower.contains("tool call") || lower.contains("tool_call");+ (tool_role && about_tool_call)+ || lower.contains("does not match any tool_call from the preceding assistant message")+}++/// Detect a transport-level connection drop with no provider status / managed+/// `errorCode` — the residue that otherwise falls to the generic `inference`+/// catch-all (issue #3714 bucket #1).+///+/// Anchored on the canonical reqwest/hyper shapes for a severed or never-opened+/// connection (stale keep-alive reused after sleep/wake, network change, raw+/// mid-stream SSE drop). Intentionally does NOT match `"timed out"` (the+/// dedicated `timeout` arm owns that) nor any `4xx/5xx` status (those arms claim+/// their shapes earlier). Caller passes the already-lowercased error string.+pub(crate) fn is_connection_dropped_text(lower: &str) -> bool {+ const DROP_MARKERS: &[&str] = &[+ "connection closed before message completed", // hyper IncompleteMessage+ "error reading a body from connection",+ "connection reset",+ "connection refused",+ "connection aborted",+ "broken pipe",+ "unexpected end of file",+ "unexpected eof",+ "error sending request",+ "tcp connect error",+ "dns error",+ "failed to lookup address",+ ];+ DROP_MARKERS.iter().any(|marker| lower.contains(marker))+}++/// Detect an un-claimed provider 4xx (generic client-side request rejection).+///+/// Mirrors the status tokens emitted by `inference::provider::ops::api_error`+/// (`"<provider> API error (400 Bad Request): …"`). Ordered AFTER the+/// provider-config-rejection and model-unavailable arms in+/// [`classify_inference_error`](super::classify::classify_inference_error), so+/// only 4xx shapes those arms did not claim reach this predicate.+///+/// Caller passes the already-lowercased error string.+pub(crate) fn is_provider_request_rejected_text(lower: &str) -> bool {+ // Match only when the 4xx status appears inside a provider error envelope+ // (`<provider> API error (4xx …)`, emitted by+ // `inference::provider::ops::api_error`). Matching a bare "400"/"404"+ // anywhere would misclassify unrelated errors that merely contain those+ // digits (token counts, byte offsets, timestamps). Per CodeRabbit review+ // on PR #3199.+ const PROVIDER_4XX_MARKERS: &[&str] = &[+ "api error (400",+ "api error (404",+ "api error (409",+ "api error (422",+ ];+ PROVIDER_4XX_MARKERS+ .iter()+ .any(|marker| lower.contains(marker))+}++/// Whether a model-availability error body describes a **transient** upstream+/// outage rather than a user misconfiguration (#5503).+///+/// The `model_unavailable` arm matches on the bare word `unavailable`, which a+/// provider emits for BOTH "you picked a model I don't host" (config, terminal)+/// and "this model is temporarily down / overloaded right now" (transient,+/// retryable). Only the second class carries one of these temporary-outage+/// markers, so it's the safe discriminator: a terminal endpoint rejection like+/// `"model unavailable on this endpoint"` (a 404 for a model that endpoint+/// doesn't host) carries none of them and stays on the config verdict.+///+/// Deliberately does NOT key on the bare word `unavailable` — that's the very+/// ambiguity being disambiguated. Caller passes the already-lowercased string.+pub(crate) fn is_transient_unavailability_text(lower: &str) -> bool {+ const TRANSIENT_MARKERS: &[&str] = &[+ "temporarily",+ "temporary",+ "currently unavailable",+ "currently overloaded",+ "overloaded",+ "try again later",+ "try again in a",+ "please retry",+ ];+ TRANSIENT_MARKERS+ .iter()+ .any(|marker| lower.contains(marker))+}