Skip to content

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

refactor(voice): reduce voice module to transcript screening adapter

Steven Enamakel0daad9921e6f
diff --git a/crates/openhuman-core/src/modules/voice.rs b/crates/openhuman-core/src/modules/voice.rs
index 280f830e62..c156f37de6 100644
--- a/crates/openhuman-core/src/modules/voice.rs
+++ b/crates/openhuman-core/src/modules/voice.rs
@@ -1,48 +1,16 @@
-//! Calling the `tinyvoice` module: the voice primitives, over the bus.
-//!
-//! Each function here is the host half of one method on
-//! `ai.tinyhumans.tinyvoice.Voice`. They exist so the voice domain does not
-//! have to know about proxies, base64 framing, or wire error names — a caller
-//! asks a question about a transcript or a buffer and gets an answer.
-//!
-//! # A call costs about 15 microseconds
-//!
-//! Measured on the real loaded module (`bench_call` in the `tinyvoice` repo):
-//! ~15 µs per round trip, against a 20 ms audio frame. A TinyBus module shares
-//! this address space — a call is a channel send and a JSON hop, not IPC.
-//!
-//! So there is no per-call budget to protect and nothing here is too hot to go
-//! over the bus, including the hotkey-driven recording session state machine.
-//!
-//! **What stays on this side is decided by the audio callback, not by cost.**
-//! `cpal` delivers on a realtime thread where blocking is a dropout, so the
-//! callback converts the sample format and forwards raw interleaved samples;
-//! every transform happens in an async worker that calls this module. That is
-//! *less* work on the audio thread than the in-process version did, not more.
-//!
-//! # Failure is not fatal here
-//!
-//! Every function returns a [`VoiceCallError`] the caller can fall back from,
-//! and the callers do. A module that will not load must degrade voice to its
-//! pre-module behaviour — deferring to the agent, or skipping a filter — rather
-//! than taking dictation down with it. The one thing none of them may do is
-//! guess: see [`is_hallucinated`].
+//! TinyVoice's transcript screening adapter.
use tinyvoice_bus::names::methods;
use super::{ops, registry};
use crate::config::Config;
-/// Registry id of the module these calls go to.
const MODULE_ID: &str = "tinyvoice";
-/// Why a voice call did not produce an answer.
+/// Why a voice screening call did not produce an answer.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum VoiceCallError {
- /// The module is not loaded and cannot be: unsupported host, downloads off,
- /// disabled in config, or a load that already failed in this process.
Unavailable(String),
- /// The call itself failed — a malformed payload, or a refused argument.
Failed(String),
}
@@ -54,322 +22,25 @@ impl std::fmt::Display for VoiceCallError {
}
}
-/// Which hallucination list applies.
-///
-/// The contract's own type under the name the voice domain has always used for
-/// it. It was redeclared here — with a comment saying it had to be, "because
-/// this crate does not depend on `tinyvoice`" — and that is no longer true:
-/// `tinyvoice-bus` is exactly that dependency, and it costs `serde` and
-/// nothing else.
+/// Hallucination list used for a transcript check.
pub use tinyvoice_bus::transcript::Mode as HallucinationMode;
-/// The wire value for a screening mode.
-///
-/// The interface takes the mode as a plain string argument rather than a JSON
-/// value, so this reaches the same spelling the contract's `rename_all =
-/// "snake_case"` derive produces without a `serde_json` round trip. The match
-/// is exhaustive, so a variant added upstream is a compile error here rather
-/// than a mode that silently screens as something else.
-fn hallucination_mode_wire(mode: HallucinationMode) -> &'static str {
- match mode {
- HallucinationMode::Dictation => "dictation",
- HallucinationMode::Conversation => "conversation",
- }
-}
-
-/// Recording-session vocabulary shared with the loaded TinyVoice module.
-pub use tinyvoice_bus::{
- GateVerdict, RecordingGates, SessionAction, SessionAdvance, SessionInput, SessionPhase,
- SessionStatus,
-};
-
-/// Native capture lease types shared with the loaded TinyVoice module.
-pub use tinyvoice_bus::capture::{
- CaptureError, CaptureHandle, CaptureResult, MicrophonePermission, RecordingFinishRequest,
- RecordingStartRequest,
-};
-
-/// Hotkey lifecycle types shared with the loaded TinyVoice module.
-pub use tinyvoice_bus::hotkey::{
- ActivationMode, HostKeyFact, HotkeyBatch, HotkeyError, HotkeyEvent, HotkeyFeedRequest,
- HotkeyHandle, HotkeyHandleRequest, HotkeyReadRequest, HotkeyReply, HotkeyRequest,
- HotkeyReserveRequest, HotkeySource, HotkeyStartRequest, HotkeyState, SequencedHostFact,
-};
-
-/// Apply the pre-transcription recording gates (minimum duration, silence).
-///
-/// # Errors
-///
-/// [`VoiceCallError`] when the module is unavailable or the call fails.
-pub async fn gate_recording(
- config: &Config,
- duration_secs: f32,
- peak_rms: f32,
- gates: RecordingGates,
-) -> Result<GateVerdict, VoiceCallError> {
- let json: String = call(
- config,
- methods::GATE_RECORDING,
- (
- duration_secs,
- peak_rms,
- gates.min_duration_secs,
- gates.silence_threshold,
- ),
- )
- .await?;
- serde_json::from_str(&json)
- .map_err(|e| VoiceCallError::Failed(format!("could not decode verdict: {e}")))
-}
-
/// Whether an STT transcript looks like a hallucination rather than speech.
///
-/// # Errors
-///
-/// [`VoiceCallError`] when the module is unavailable or the call fails.
-///
-/// **A caller that cannot reach the module must not guess.** Treating an error
-/// as "hallucinated" silently deletes real speech; treating it as "clean" lets
-/// `[BLANK_AUDIO]` reach the agent as an instruction. Of the two, passing the
-/// text through is recoverable and losing it is not, so callers here fall open
-/// — and say so at the call site rather than burying it in a default.
+/// A caller that cannot reach TinyVoice must pass the transcript through: an
+/// unavailable filter must not silently discard real speech.
pub async fn is_hallucinated(
config: &Config,
text: &str,
mode: HallucinationMode,
) -> Result<bool, VoiceCallError> {
- call(
- config,
- methods::IS_HALLUCINATED,
- (text, hallucination_mode_wire(mode)),
- )
- .await
-}
-
-/// Downmix, resample to 16 kHz, optionally silence-gate, and frame as WAV.
-///
-/// This is the whole capture-side pipeline in one call. Three separate calls
-/// would ship the same audio across the bus three times to do work that is
-/// microseconds of arithmetic.
-///
-/// `samples` are interleaved `f32`; `gate_threshold` of zero disables the
-/// silence gate.
-///
-/// # Errors
-///
-/// [`VoiceCallError`], including a `Failed` when `samples` is not a whole
-/// number of frames for `channels`.
-pub async fn prepare_capture(
- config: &Config,
- samples: &[f32],
- source_rate: u32,
- channels: u16,
- gate_threshold: f32,
-) -> Result<Vec<u8>, VoiceCallError> {
- let encoded = encode_samples(samples);
- let wav: String = call(
- config,
- methods::PREPARE_CAPTURE,
- (encoded, source_rate, channels, gate_threshold),
- )
- .await?;
- decode_audio(&wav)
-}
-
-/// A hotkey-driven recording session held by the module.
-///
-/// The module owns the hotkey -> record -> finish state machine (phase,
-/// generation guard, setup / stop-intent buffering). The host reports facts as
-/// [`SessionInput`]s and performs the one [`SessionAction`] each answer names.
-///
-/// Not `Drop`-based: call
-/// [`close`](Self::close) when the server stops.
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-pub struct RecorderSession {
- id: u64,
-}
-
-impl RecorderSession {
- /// A session handle for an id no module issued, so host tests can drive
- /// code that must survive the module being absent.
- #[cfg(test)]
- pub(crate) const fn unopened_for_test() -> Self {
- Self { id: u64::MAX }
- }
-
- /// Open a stopped session.
- ///
- /// # Errors
- ///
- /// [`VoiceCallError`] when the module is unavailable or at its session cap.
- pub async fn open(config: &Config) -> Result<Self, VoiceCallError> {
- let id: u64 = call(config, methods::SESSION_OPEN, ()).await?;
- Ok(Self { id })
- }
-
- /// Apply `input` and return the module's verdict and the action to take.
- ///
- /// # Errors
- ///
- /// [`VoiceCallError`] when the module is unavailable or the session is not
- /// open (it was closed, or the process restarted the module).
- pub async fn advance(
- &self,
- config: &Config,
- input: SessionInput,
- ) -> Result<SessionAdvance, VoiceCallError> {
- let json = serde_json::to_string(&input)
- .map_err(|e| VoiceCallError::Failed(format!("could not encode session input: {e}")))?;
- let reply: String = call(config, methods::SESSION_ADVANCE, (self.id, json)).await?;
- serde_json::from_str(&reply)
- .map_err(|e| VoiceCallError::Failed(format!("could not decode session advance: {e}")))
- }
-
- /// The session's phase and latest generation.
- ///
- /// # Errors
- ///
- /// [`VoiceCallError`] when the module is unavailable or the session is not open.
- pub async fn status(&self, config: &Config) -> Result<SessionStatus, VoiceCallError> {
- let reply: String = call(config, methods::SESSION_STATUS, (self.id,)).await?;
- serde_json::from_str(&reply)
- .map_err(|e| VoiceCallError::Failed(format!("could not decode session status: {e}")))
- }
-
- /// Release the session. Closing one that is already gone is not an error.
- ///
- /// # Errors
- ///
- /// [`VoiceCallError`] only when the module itself is unreachable.
- pub async fn close(&self, config: &Config) -> Result<(), VoiceCallError> {
- call(config, methods::SESSION_CLOSE, (self.id,)).await
- }
-}
-
-/// Load the voice module if it is not already serving.
-///
-/// Callers do not have to invoke this — every operation above does it — but a
-/// caller that wraps its work in a deadline should, *outside* that deadline. A
-/// first use may download and verify an artifact, and charging that against a
-/// dictation timeout means the first utterance a user ever speaks is the one
-/// that fails.
-///
-/// # Errors
-///
-/// The same [`VoiceCallError::Unavailable`] the operations return.
-pub async fn ensure_ready(config: &Config) -> Result<(), VoiceCallError> {
- ops::ensure_loaded(config, MODULE_ID)
- .await
- .map_err(VoiceCallError::Unavailable)
-}
-
-/// Reserve an opaque handle before native microphone startup.
-pub async fn reserve_capture(
- config: &Config,
- permission: MicrophonePermission,
-) -> Result<CaptureResult<CaptureHandle>, VoiceCallError> {
- call(
- config,
- methods::RESERVE_CAPTURE,
- (RecordingStartRequest {
- permission,
- handle: None,
- },),
- )
- .await
-}
-
-/// Reserve a native or host-fed hotkey listener before startup.
-pub async fn reserve_hotkey(
- config: &Config,
- request: HotkeyRequest,
-) -> Result<Result<HotkeyHandle, HotkeyError>, VoiceCallError> {
- call(
- config,
- methods::HOTKEY_RESERVE,
- (HotkeyReserveRequest { request },),
- )
- .await
-}
-
-/// Start a reserved listener. Repeated starts recover a lost reply.
-pub async fn start_hotkey(
- config: &Config,
- handle: HotkeyHandle,
-) -> Result<Result<HotkeyReply, HotkeyError>, VoiceCallError> {
- call(
- config,
- methods::HOTKEY_START,
- (HotkeyStartRequest { handle },),
- )
- .await
-}
-
-/// Read an acknowledged/replayable batch of activation events.
-pub async fn read_hotkey(
- config: &Config,
- request: HotkeyReadRequest,
-) -> Result<Result<HotkeyBatch, HotkeyError>, VoiceCallError> {
- call(config, methods::HOTKEY_READ, (request,)).await
-}
-
-/// Feed a bounded batch of host-owned generic key facts.
-pub async fn feed_hotkey(
- config: &Config,
- request: HotkeyFeedRequest,
-) -> Result<Result<HotkeyReply, HotkeyError>, VoiceCallError> {
- call(config, methods::HOTKEY_FEED, (request,)).await
-}
-
-/// Stop a listener after its native hook has been removed and joined.
-pub async fn stop_hotkey(
- config: &Config,
- handle: HotkeyHandle,
-) -> Result<Result<HotkeyReply, HotkeyError>, VoiceCallError> {
- call(
- config,
- methods::HOTKEY_STOP,
- (HotkeyHandleRequest { handle },),
- )
- .await
-}
-
-/// Shut down every listener and wait for native cleanup.
-pub async fn shutdown_hotkeys(
- config: &Config,
-) -> Result<Result<HotkeyReply, HotkeyError>, VoiceCallError> {
- call(config, methods::HOTKEY_SHUTDOWN, ()).await
-}
-
-/// Base64 little-endian `f32`, which is how the interface carries samples.
-fn encode_samples(samples: &[f32]) -> String {
- use base64::Engine as _;
- let bytes: Vec<u8> = samples.iter().flat_map(|s| s.to_le_bytes()).collect();
- base64::engine::general_purpose::STANDARD.encode(bytes)
-}
-
-/// Decode base64 little-endian `f32` samples the module produced.
-fn decode_samples(encoded: &str) -> Result<Vec<f32>, VoiceCallError> {
- let bytes = decode_audio(encoded)?;
- if !bytes.len().is_multiple_of(4) {
- return Err(VoiceCallError::Failed(format!(
- "module returned {} bytes, not a whole number of f32 samples",
- bytes.len()
- )));
- }
- let (samples, _) = bytes.as_chunks::<4>();
- Ok(samples.iter().copied().map(f32::from_le_bytes).collect())
-}
-
-/// Decode a base64 audio payload the module produced.
-fn decode_audio(encoded: &str) -> Result<Vec<u8>, VoiceCallError> {
- use base64::Engine as _;
- base64::engine::general_purpose::STANDARD
- .decode(encoded)
- .map_err(|e| VoiceCallError::Failed(format!("module returned invalid base64: {e}")))
+ let mode = match mode {
+ HallucinationMode::Dictation => "dictation",
+ HallucinationMode::Conversation => "conversation",
+ };
+ call(config, methods::IS_HALLUCINATED, (text, mode)).await
}
-/// Ensure the module is serving, then make one call on it.
async fn call<A, R>(config: &Config, method: &str, args: A) -> Result<R, VoiceCallError>
where
A: serde::Serialize + Send,
@@ -386,21 +57,13 @@ where
let proxy = runtime
.proxy(record.bus_name, record.object_path)
.map_err(|error| VoiceCallError::Failed(error.to_string()))?;
-
proxy
.call(method, args)
.await
- .map_err(|error| classify(&error))
-}
-
-/// Map a wire error onto the two outcomes a caller distinguishes.
-fn classify(error: &tinybus::Error) -> VoiceCallError {
- let message = error.to_string();
- match error.wire_name() {
- // Loaded but not answering: refused, faulted, or gone.
- name if name.contains("ModuleUnavailable") => VoiceCallError::Unavailable(message),
- _ => VoiceCallError::Failed(message),
- }
+ .map_err(|error| match error.wire_name() {
+ name if name.contains("ModuleUnavailable") => VoiceCallError::Unavailable(error.to_string()),
+ _ => VoiceCallError::Failed(error.to_string()),
+ })
}
#[cfg(test)]
diff --git a/crates/openhuman-core/src/modules/voice_tests.rs b/crates/openhuman-core/src/modules/voice_tests.rs
index ba10d46e97..87b7aed537 100644
--- a/crates/openhuman-core/src/modules/voice_tests.rs
+++ b/crates/openhuman-core/src/modules/voice_tests.rs
@@ -1,170 +1,19 @@
-//! Tests for the voice call client.
-//!
-//! Nothing here loads a module. What is testable without one is the part
-//! that decides what a caller does next: mode spellings, sample encoding, and
-//! that the unavailable path is reached without a
-//! broker. The round trips themselves are covered where they can be
-//! honest — `tinyvoice`'s own loader E2E, which drives a real module over
-//! a real broker against the published artifact.
-
-use super::{encode_samples, hallucination_mode_wire, HallucinationMode, VoiceCallError};
-use crate::config::Config;
-#[test]
-fn hallucination_modes_use_the_wire_spelling() {
- // The module rejects an unknown mode rather than defaulting, so a typo
- // here is a hard failure at runtime rather than a silent mode swap.
- assert_eq!(
- hallucination_mode_wire(HallucinationMode::Dictation),
- "dictation"
- );
- assert_eq!(
- hallucination_mode_wire(HallucinationMode::Conversation),
- "conversation"
- );
-}
-
-#[test]
-fn samples_encode_as_little_endian_f32() {
- use base64::Engine as _;
- let encoded = encode_samples(&[1.0f32, -1.0f32]);
- let bytes = base64::engine::general_purpose::STANDARD
- .decode(&encoded)
- .expect("valid base64");
- assert_eq!(bytes.len(), 8);
- assert_eq!(&bytes[0..4], &1.0f32.to_le_bytes());
- assert_eq!(&bytes[4..8], &(-1.0f32).to_le_bytes());
-}
-
-#[test]
-fn errors_render_as_their_message() {
- assert_eq!(
- VoiceCallError::Unavailable("downloads are off".to_string()).to_string(),
- "downloads are off"
- );
- assert_eq!(
- VoiceCallError::Failed("bad payload".to_string()).to_string(),
- "bad payload"
- );
-}
-
-/// A config with modules enabled but nothing fetchable.
-fn offline_config() -> Config {
- let mut config = Config::default();
- config.modules.enabled = true;
- config.modules.allow_download = false;
- config
-}
+use super::{is_hallucinated, HallucinationMode, VoiceCallError};
#[tokio::test]
-async fn a_disabled_host_reports_unavailable_without_starting_a_broker() {
- // Every entry point has to reach the unavailable path on its own: they
- // each call `ensure_loaded` separately, so one of them forgetting to
- // would only show up as a hang or a panic in the field.
- let mut config = offline_config();
+async fn transcript_screening_reports_unavailable_when_modules_are_disabled() {
+ let mut config = crate::config::Config::default();
config.modules.enabled = false;
assert!(matches!(
- super::gate_recording(
- &config,
- 1.0,
- 0.5,
- super::RecordingGates {
- min_duration_secs: 0.3,
- silence_threshold: 0.01
- }
- )
- .await,
- Err(VoiceCallError::Unavailable(_))
- ));
- assert!(matches!(
- super::is_hallucinated(&config, "okay", HallucinationMode::Dictation).await,
- Err(VoiceCallError::Unavailable(_))
- ));
- assert!(matches!(
- super::prepare_capture(&config, &[0.1, 0.2], 32_000, 2, 0.0).await,
- Err(VoiceCallError::Unavailable(_))
- ));
- assert!(matches!(
- super::ensure_ready(&config).await,
+ is_hallucinated(&config, "recognized words", HallucinationMode::Conversation).await,
Err(VoiceCallError::Unavailable(_))
));
}
#[test]
-fn the_registry_entry_matches_the_interface_this_client_calls() {
- // The registry is a plain `const` table and cannot name a gated crate, so
- // the bus name and object path are still written out there by hand. This
- // is what checks them against the contract's own constants — a mismatch is
- // not a compile error, it is a `NameHasNoOwner` at first use, in the field,
- // on whichever platform nobody tested.
+fn tinyvoice_module_remains_registered_for_transcript_screening() {
let record = crate::modules::registry::find("tinyvoice").expect("tinyvoice is registered");
assert_eq!(record.bus_name, tinyvoice_bus::names::BUS_NAME);
assert_eq!(record.object_path, tinyvoice_bus::names::OBJECT_PATH);
- assert!(
- record.object_path.starts_with('/') && !record.object_path.contains('.'),
- "an object path with a dot in it is rejected by the loader, not by the compiler"
- );
-}
-
-#[test]
-fn every_member_this_client_calls_is_one_the_contract_declares() {
- // Host adapters use contract constants for call sites. Keep the curated
- // surface, including capture leases and hotkeys, aligned with the module.
- use tinyvoice_bus::names::methods;
- let called = [
- methods::IS_HALLUCINATED,
- methods::PREPARE_CAPTURE,
- methods::RESERVE_CAPTURE,
- methods::LIST_INPUT_DEVICES,
- methods::RECORDING_START,
- methods::RECORDING_FINISH,
- methods::RECORDING_SUMMARY,
- methods::RECORDING_CANCEL,
- methods::READ_AUDIO_OUTPUT,
- methods::RELEASE_AUDIO_OUTPUT,
- methods::HOTKEY_RESERVE,
- methods::HOTKEY_START,
- methods::HOTKEY_READ,
- methods::HOTKEY_FEED,
- methods::HOTKEY_STOP,
- methods::HOTKEY_SHUTDOWN,
- ];
- for member in called {
- assert!(
- tinyvoice_bus::names::METHODS.contains(&member),
- "the host calls `{member}`, which the contract does not dispatch"
- );
- }
-}
-
-/// The session input and action tags are a wire contract with the module: a
-/// rename on either side makes a hotkey press a no-op, which looks like a dead
-/// key rather than an error, so the spellings the host sends and expects are
-/// pinned.
-#[test]
-fn recording_session_wire_spellings_match_the_contract() {
- use super::{SessionAction, SessionAdvance, SessionInput, SessionPhase};
- assert_eq!(
- serde_json::to_string(&SessionInput::SetupReady {
- stop_buffered: false
- })
- .unwrap(),
- r#"{"input":"setup_ready","stop_buffered":false}"#
- );
- assert_eq!(
- serde_json::to_string(&SessionInput::Finished { generation: 4 }).unwrap(),
- r#"{"input":"finished","generation":4}"#
- );
- let reply: SessionAdvance = serde_json::from_str(
- r#"{"accepted":true,"phase":"recording","generation":2,"action":{"action":"defer_stop","generation":2,"after_ms":1500}}"#,
- )
- .unwrap();
- assert_eq!(reply.phase, SessionPhase::Recording);
- assert_eq!(
- reply.action,
- SessionAction::DeferStop {
- generation: 2,
- after_ms: 1500
- }
- );
}