Skip to content

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

fix(voice): handle missing memory guard in realtime agent

Steven Enamakel4767e0ab72a0
diff --git a/crates/openhuman-core/src/memory/guard/test_support/fixtures.rs b/crates/openhuman-core/src/memory/guard/test_support/fixtures.rs
new file mode 100644
index 0000000000..b25e88daff
--- /dev/null
+++ b/crates/openhuman-core/src/memory/guard/test_support/fixtures.rs
@@ -0,0 +1,288 @@
+//! `RecordingProvider`'s type, constructor, call log, and the guard/entity
+//! fixtures the family tests build from.
+//!
+//! Split out of the original `test_support.rs` (see that module's doc
+//! comment for why `RecordingProvider` implements every family rather than
+//! relying on the null driver). The family trait implementations that answer
+//! each call recorded here live in the sibling `*_impls` files under
+//! [`super`].
+
+use std::sync::{Arc, Mutex};
+
+use crate::memory::api::provider::MemoryProvider;
+use crate::memory::api::provider::types::{ExportRecord, SourceScope};
+use crate::memory::api::provider::episodic::ConversationSegment;
+use crate::memory::api::provider::episodic::EpisodicTurn;
+use crate::memory::api::provider::retrieval::RetrievalResponse;
+use crate::memory::api::types::{
+ MemoryCategory, MemoryEntry, MemoryTaint, NamespaceDocumentInput, NamespaceMemoryHit,
+ NamespaceSummary,
+};
+
+
+/// One call that reached the driver.
+#[derive(Debug, Clone, PartialEq)]
+pub struct Call {
+ pub method: String,
+ /// Content the driver was handed, when the method carries any.
+ pub content: Option<String>,
+ /// Provenance the driver was handed, when the method carries any.
+ pub taint: Option<MemoryTaint>,
+ /// Whether the method received a `Some(scope)`.
+ pub scoped: Option<bool>,
+}
+
+/// The scope's allow list rendered for assertions, sorted for determinism.
+pub(super) fn rendered_scope(scope: Option<&SourceScope>) -> Option<String> {
+ scope.map(|s| {
+ let mut allow = s.allow.clone();
+ allow.sort();
+ allow.join(",")
+ })
+}
+
+impl Call {
+ fn plain(method: &str) -> Self {
+ Self {
+ method: method.into(),
+ content: None,
+ taint: None,
+ scoped: None,
+ }
+ }
+}
+
+/// A provider that records and answers with empties.
+pub struct RecordingProvider {
+ pub(super) calls: Mutex<Vec<Call>>,
+ /// What `recall` returns, so budget tests can drive a known result set.
+ pub(super) recall_result: Mutex<Vec<MemoryEntry>>,
+ /// What `fast_retrieve` returns, so the auto-recall lane can be driven
+ /// through a real guard with known hits.
+ pub(super) fast_retrieve_result: Mutex<RetrievalResponse>,
+ /// What `recall_namespace_scored` returns, so the vector-floored recall
+ /// paths (Lane B, the contradiction check) can be driven with known scores.
+ pub(super) namespace_hits: Mutex<Vec<NamespaceMemoryHit>>,
+ /// What `namespaces` returns, so a namespace can look populated (Lane B
+ /// asks for the count before it pays for an embed) without a real store.
+ pub(super) namespace_summaries: Mutex<Vec<NamespaceSummary>>,
+ /// What `session_turns` returns, so the archivist's finalize path can be
+ /// driven past its empty-entries early return without an engine behind it.
+ pub(super) session_turns: Mutex<Vec<EpisodicTurn>>,
+ /// What `segments_pending_summary` returns, so the re-summarisation pass
+ /// (#6186) can be driven over a known queue.
+ pub(super) pending_segments: Mutex<Vec<ConversationSegment>>,
+}
+
+impl Default for RecordingProvider {
+ fn default() -> Self {
+ Self::new()
+ }
+
+/// A [`GuardPolicy`](super::GuardPolicy) over an embedded driver with default
+/// budgets — the shipped configuration.
+pub fn embedded_policy() -> super::GuardPolicy {
+ super::GuardPolicy::new(
+ "recording",
+ crate::core::subsystem::DriverClass::Embedded,
+ crate::config::schema::MemoryHooksConfig::default(),
+ super::policy::TRUSTED,
+ )
+}
+
+/// A policy over an *external* driver. No such driver can bind today
+/// (`binding::admit` refuses them), so this is the only way to reach the class
+/// branches that land for real in M6.
+pub fn external_policy(trust_state: &str) -> super::GuardPolicy {
+ super::GuardPolicy::new(
+ "supermemory",
+ crate::core::subsystem::DriverClass::External,
+ crate::config::schema::MemoryHooksConfig::default(),
+ trust_state,
+ )
+}
+
+/// An [`ExportRecord`] fixture.
+pub fn export_record(taint: MemoryTaint) -> ExportRecord {
+ ExportRecord {
+ kind: "entry".into(),
+ id: "r1".into(),
+ namespace: Some("ns".into()),
+ taint,
+ payload: serde_json::Value::Null,
+ }
+}
+
+/// A guard over a fresh recording provider, plus a handle on that provider.
+pub fn guarded(policy: super::GuardPolicy) -> (Arc<RecordingProvider>, super::MemoryGuard) {
+ guarded_with(RecordingProvider::new(), policy)
+}
+
+/// As [`guarded`], over a caller-configured provider.
+pub fn guarded_with(
+ provider: RecordingProvider,
+ policy: super::GuardPolicy,
+) -> (Arc<RecordingProvider>, super::MemoryGuard) {
+ let provider = Arc::new(provider);
+ let guard = super::MemoryGuard::new(
+ Arc::clone(&provider) as Arc<dyn MemoryProvider>,
+ Arc::new(policy),
+ );
+ (provider, guard)
+}
+
+/// A [`MemoryEntry`] fixture.
+pub fn entry(content: &str) -> MemoryEntry {
+ MemoryEntry {
+ id: "id".into(),
+ key: "key".into(),
+ content: content.into(),
+ namespace: Some("ns".into()),
+ category: MemoryCategory::Core,
+ timestamp: "2026-01-01T00:00:00Z".into(),
+ session_id: None,
+ score: None,
+ taint: MemoryTaint::Internal,
+ }
+}
+
+pub fn document(content: &str, taint: MemoryTaint) -> NamespaceDocumentInput {
+ NamespaceDocumentInput {
+ namespace: "ns".into(),
+ key: "k".into(),
+ title: "t".into(),
+ content: content.into(),
+ source_type: "chat".into(),
+ priority: "normal".into(),
+ tags: vec![],
+ metadata: serde_json::Value::Null,
+ category: "core".into(),
+ session_id: None,
+ document_id: None,
+ taint,
+ }
+}
+
+
+
+impl RecordingProvider {
+ /// A provider with an empty call log and every seeded answer at its
+ /// default — the shape most tests want before layering a `with_*` on top.
+ pub fn new() -> Self {
+ Self {
+ calls: Mutex::new(Vec::new()),
+ recall_result: Mutex::new(Vec::new()),
+ fast_retrieve_result: Mutex::new(RetrievalResponse::default()),
+ namespace_hits: Mutex::new(Vec::new()),
+ namespace_summaries: Mutex::new(Vec::new()),
+ session_turns: Mutex::new(Vec::new()),
+ pending_segments: Mutex::new(Vec::new()),
+ }
+ }
+
+ /// Seed what `recall` answers, so a budget test can drive a known set.
+ pub fn with_recall_result(self, entries: Vec<MemoryEntry>) -> Self {
+ *self.recall_result.lock().unwrap() = entries;
+ self
+ }
+
+ /// Seed what `fast_retrieve` answers, so the auto-recall lane can run
+ /// through a real guard with known hits.
+ pub fn with_fast_retrieve_result(self, response: RetrievalResponse) -> Self {
+ *self.fast_retrieve_result.lock().unwrap() = response;
+ self
+ }
+
+ /// Seed what `recall_namespace_scored` answers, so the vector-floored
+ /// paths can be driven with known scores.
+ pub fn with_namespace_hits(self, hits: Vec<NamespaceMemoryHit>) -> Self {
+ *self.namespace_hits.lock().unwrap() = hits;
+ self
+ }
+
+ /// Seed what `namespaces` answers, so a namespace can look populated
+ /// without a real store behind it.
+ pub fn with_namespace_summaries(self, summaries: Vec<NamespaceSummary>) -> Self {
+ *self.namespace_summaries.lock().unwrap() = summaries;
+ self
+ }
+
+ /// Seed what `session_turns` answers. Without this the archivist's
+ /// finalize path stops at its empty-entries early return and never
+ /// reaches the recap it is being tested for.
+ pub fn with_session_turns(self, turns: Vec<EpisodicTurn>) -> Self {
+ *self.session_turns.lock().unwrap() = turns;
+ self
+ }
+
+ /// Seed the re-summarisation queue (#6186). The default is empty, so a
+ /// test that does not set this drives the pass over nothing — which is
+ /// the state a healthy store is in.
+ pub fn with_pending_segments(self, segments: Vec<ConversationSegment>) -> Self {
+ *self.pending_segments.lock().unwrap() = segments;
+ self
+ }
+
+ /// Append one call to the log. Every family impl funnels through this.
+ pub(super) fn record(&self, call: Call) {
+ self.calls.lock().unwrap().push(call);
+ }
+
+ /// Every call the driver saw, in order.
+ pub fn calls(&self) -> Vec<Call> {
+ self.calls.lock().unwrap().clone()
+ }
+
+ /// How many calls reached the driver — for tests that only care that a
+ /// path was or was not taken.
+ pub fn call_count(&self) -> usize {
+ self.calls.lock().unwrap().len()
+ }
+
+ /// The single recorded call, panicking when there is not exactly one.
+ pub fn only_call(&self) -> Call {
+ let calls = self.calls();
+ assert_eq!(
+ calls.len(),
+ 1,
+ "expected exactly one driver call: {calls:?}"
+ );
+ calls.into_iter().next().unwrap()
+ }
+}
+
+pub fn namespace_summary(namespace: &str, count: usize) -> NamespaceSummary {
+ NamespaceSummary {
+ namespace: namespace.into(),
+ count,
+ last_updated: None,
+ }
+}
+
+/// A [`NamespaceMemoryHit`] with only the vector component set — the signal the
+/// vector-floored recall paths (Lane B, the contradiction check) filter on.
+pub fn namespace_hit(
+ namespace: &str,
+ key: &str,
+ content: &str,
+ vector_similarity: f64,
+) -> NamespaceMemoryHit {
+ NamespaceMemoryHit {
+ id: format!("{namespace}/{key}"),
+ kind: crate::memory::api::types::MemoryItemKind::Kv,
+ namespace: namespace.into(),
+ key: key.into(),
+ title: None,
+ content: content.into(),
+ category: "core".into(),
+ source_type: None,
+ updated_at: 0.0,
+ score: vector_similarity,
+ score_breakdown: crate::memory::api::types::RetrievalScoreBreakdown {
+ vector_similarity,
+ ..Default::default()
+ },
+ document_id: None,
+ chunk_id: None,
+ supporting_relations: Vec::new(),
+ taint: MemoryTaint::default(),
diff --git a/crates/openhuman-core/src/voice/realtime_harness/agent.rs b/crates/openhuman-core/src/voice/realtime_harness/agent.rs
new file mode 100644
index 0000000000..32b0e1c0d6
--- /dev/null
+++ b/crates/openhuman-core/src/voice/realtime_harness/agent.rs
@@ -0,0 +1,180 @@
+//! Building and running the per-turn voice orchestrator: a fresh, isolated
+//! `Agent` pinned to a fast non-thinking model, seeded from the relayed
+//! history, run under the hard per-turn ceiling with the same chat-scoped
+//! approval surface web chat installs.
+
+use std::time::Duration;
+
+use log::{info, warn};
+use serde_json::Value;
+
+use crate::agent::harness::session::Agent;
+use crate::agent::progress::AgentProgress;
+use crate::agent::turn_origin::{with_origin, AgentTurnOrigin};
+
+use super::chat_delivery::{VOICE_CHAT_CLIENT_ID, VOICE_CHAT_THREAD_ID};
+use super::prompt::messages_to_history_pairs;
+
+/// Hard ceiling on the background turn — not on how long the caller waits, which
+/// the ack deadline in the turn handler caps at ~8s.
+///
+/// This governs the deferred half: the orchestrator keeps working after the voice
+/// turn closes, and its answer is delivered into chat and read aloud if the call
+/// is still up. At 90s that ceiling was cutting real answers. Observed on staging:
+/// the same "summarize my emails" request finished in ~53s on one call and was
+/// still running past 90s on the next, where it aborted and the caller got a
+/// failure notice instead of their summary — a hard failure caused purely by
+/// Composio round-trip variance, not by anything being wrong.
+///
+/// Kept in step with `DEFAULT_TIMEOUT_MS` in the backend's `relayService.ts`,
+/// which must stay above this so the desktop's own specific error wins the race
+/// rather than the relay's generic timeout.
+const TURN_TIMEOUT_SECS: u64 = 180;
+
+/// Voice-scoped transcript namespace. Building a fresh orchestrator per turn
+/// would otherwise resume the *chat* orchestrator's latest transcript by name,
+/// bleeding an unrelated conversation into (or out of) the voice session. A
+/// dedicated name isolates voice from chat; multi-turn context comes from the
+/// relayed `messages` we seed below, not from this resume path.
+const VOICE_AGENT_NAME: &str = "voice";
+
+/// Model pinned for realtime voice turns. The cloud voice session cancels a turn
+/// that has produced no spoken token in ~11-12s ("Generating the LLM response
+/// took too long"), and the orchestrator's default reasoning model spends that
+/// whole budget *thinking* before its first word. `chat-v1` (DeepSeek-V4-Flash,
+/// thinking off) is a short-turn, tool-capable SKU: the master still routes
+/// delegation through the prompt (per-turn classification is disabled — see the
+/// model pin in `agent/harness/session/turn/core.rs`), so tool turns keep working
+/// while spoken replies start in ~1s instead of ~6s. Reasoning models are the
+/// wrong tool for a latency-capped realtime channel.
+const VOICE_MODEL: &str = "chat-v1";
+
+/// Spoken-output directive appended to the orchestrator profile so replies read
+/// naturally through TTS instead of as markdown.
+///
+/// It deliberately does NOT ask for a spoken preface before tool use any more.
+/// That clause existed to get audio to the caller early, back when the relay's
+/// filler was inaudible until the turn closed. It cost far more than it bought:
+/// a reply carrying only text and no tool call *is* the end of a turn, so a model
+/// that dutifully announced "let me pull up your inbox — I'll drop the summary in
+/// your chat" ended there, and that sentence was delivered as the final answer.
+/// The caller got a promise and no summary — observed live, with the model
+/// echoing this doc's own former example almost verbatim.
+///
+/// The acknowledgement is the relay's job now (`VOICE_FILLERS` in
+/// `voiceAgent.ts`, spoken ~700ms in) precisely because it does not depend on the
+/// model choosing to speak first. So the directive tells the model the opposite:
+/// call the tool and answer from the result.
+pub(super) const VOICE_DIRECTIVE: &str = "You are speaking aloud in a live voice conversation. \
+Reply in natural, concise spoken sentences. Do not use markdown, code blocks, \
+bullet lists, headings, or emoji. When answering needs a tool or a delegate (email, \
+calendar, files, the web), call it straight away and answer from what it returns. \
+Do NOT announce what you are about to do: a reply that only says what you are \
+going to do ends your turn, so the caller is left with a promise and never gets \
+the answer. The caller already hears a short acknowledgement while you work, so \
+say nothing until you have something to tell them.";
+
+/// Build the fresh voice orchestrator, attach the streaming sink, run one turn
+/// under the hard per-turn ceiling, then detach the sink so the forwarder's
+/// channel closes. Runs entirely on the background task, so the ack deadline in
+/// the caller covers both the build and the model round-trips.
+pub(super) async fn run_voice_turn(
+ correlation_id: &str,
+ messages: &[Value],
+ prompt: &str,
+ progress_tx: tokio::sync::mpsc::Sender<AgentProgress>,
+) -> Result<String, String> {
+ let mut agent = build_voice_agent(correlation_id, messages, prompt).await?;
+
+ // Attach the streaming sink before the turn: its presence switches the harness
+ // onto the true per-token streaming path, and each `AgentProgress::TextDelta`
+ // is forwarded to the relay socket by `forward_reply_deltas`.
+ agent.set_on_progress(Some(progress_tx));
+
+ let outcome = run_single_with_timeout(&mut agent, correlation_id, prompt).await;
+
+ // Detach the sink so the forwarder's channel closes the moment the turn ends,
+ // deterministically rather than waiting on `agent`'s drop.
+ agent.set_on_progress(None);
+ outcome
+}
+
+/// Construct the per-turn voice orchestrator: load config, pin the fast voice
+/// model, isolate the transcript namespace, and seed the relayed history.
+async fn build_voice_agent(
+ correlation_id: &str,
+ messages: &[Value],
+ prompt: &str,
+) -> Result<Agent, String> {
+ let config = crate::config::ops::load_config_with_timeout().await?;
+ let mut agent = Agent::from_config_for_agent_with_profile(
+ &config,
+ "orchestrator",
+ Some(VOICE_DIRECTIVE.to_string()),
+ None,
+ )
+ .map_err(|e| format!("orchestrator build failed: {e}"))?;
+ agent.set_event_context(format!("voice_{correlation_id}"), "voice_agent");
+ // Isolate the voice transcript namespace from the chat orchestrator so a
+ // fresh-per-turn agent can't resume an unrelated conversation by name.
+ agent.set_agent_definition_name(VOICE_AGENT_NAME);
+ // Pin a fast, non-thinking model so the first spoken token lands inside the
+ // realtime session's response-time ceiling (see VOICE_MODEL).
+ agent.set_model_name(VOICE_MODEL);
+
+ // Seed the authoritative prior turns the relay carries (OpenAI `messages`),
+ // so follow-ups like "what about tomorrow?" keep their context. No-ops when
+ // there is nothing prior to the current user message.
+ let history = messages_to_history_pairs(messages);
+ if let Err(e) = agent.seed_resume_from_messages(history, prompt) {
+ warn!("[voice-harness] seed prior messages failed correlation={correlation_id}: {e}");
+ }
+
+ info!(
+ "[voice-harness] orchestrator turn correlation={correlation_id} prompt_chars={} history_msgs={}",
+ prompt.chars().count(),
+ messages.len()
+ );
+ Ok(agent)
+}
+
+/// Run the orchestrator turn under the hard per-turn ceiling. The streaming sink
+/// must already be attached; deltas flow out while this runs.
+async fn run_single_with_timeout(
+ agent: &mut Agent,
+ correlation_id: &str,
+ prompt: &str,
+) -> Result<String, String> {
+ // Scope the turn with the SAME chat context the web-chat path installs
+ // (`APPROVAL_CHAT_CONTEXT` + `with_thread_id`), so approval-surfaced tools
+ // behave identically on voice. Without it `composio_connect` fails closed
+ // for lack of a routable surface, which the model paraphrases to the user as
+ // a confabulated "reconnect your Gmail" mid email-summary (#5399). See
+ // VOICE_CHAT_THREAD_ID for the full rationale. Nesting mirrors web chat:
+ // origin (outer) → approval context → thread id → the agent run.
+ let approval_ctx = crate::security::approval::ApprovalChatContext {
+ thread_id: VOICE_CHAT_THREAD_ID.to_string(),
+ client_id: VOICE_CHAT_CLIENT_ID.to_string(),
+ };
+ let scoped_run = crate::agent::tinyagents::thread_context::with_thread_id(
+ VOICE_CHAT_THREAD_ID,
+ agent.run_single(prompt),
+ );
+ let fut = with_origin(
+ AgentTurnOrigin::ExternalChannel {
+ channel: "voice".to_string(),
+ sender: None,
+ reply_target: correlation_id.to_string(),
+ message_id: format!("voice-{correlation_id}"),
+ },
+ crate::security::approval::APPROVAL_CHAT_CONTEXT.scope(approval_ctx, scoped_run),
+ );
+
+ match tokio::time::timeout(Duration::from_secs(TURN_TIMEOUT_SECS), fut).await {
+ Ok(Ok(text)) => Ok(text),
+ Ok(Err(e)) => Err(format!("orchestrator run_single failed: {e}")),
+ Err(_) => Err(format!(
+ "orchestrator turn timed out after {TURN_TIMEOUT_SECS}s"
+ )),
+ }
+}