feat(terra): talk to luna with push-to-talk
luna-voiced: mic -> whisper-cpp (local, vulkan) -> Hermes' API on mars ->
ElevenLabs streaming TTS -> speaker, bound to SUPER+V. State, amplitude
and a viseme timeline are published on a unix socket; nothing consumes
that yet, but it is the data source the quickshell avatar will read.
STT stays local on purpose. mars already runs faster-whisper for Telegram
voice notes, but routing the mic through it would put every spoken word
on the network for no latency win.
Shape notes, all of them things the first live runs decided:
- Viseme offsets are relative to speech_start (emitted when the first
PCM frame reaches the speaker), never wall clock, so the shell and
the daemon never have to compare clocks. ElevenLabs sends character
alignment, not visemes, so the mapping is ours; the glTF morph target
names are the contract.
- clean_for_speech is a whitelist. She writes "(¬‿¬)", whose characters
live in Latin-1 and punctuation blocks rather than any emoji range,
so enumerating what to drop never converges. Em dashes become commas
because they are a pause — dropping one ran two clauses together and
changed what a sentence meant.
- whisper invents words out of silence ("you", "Thank you."), and a
held key over a quiet room is long AND empty, so has_speech gates on
the loudest 100ms window rather than on duration.
- Beeps on key down/up and a distinct low tone for "heard nothing":
push-to-talk with no acknowledgement is indistinguishable from broken,
and a dead mic must not feel like a slow reply.
- A warmup request at startup: her first reply after the container
starts costs ~16s against ~5s warm, and the first one is always the
one you are waiting for.
- `luna-voice watch` prints the socket protocol and `luna-voice say`
runs a turn from typed text, which is how a broken mic is told apart
from a broken pipeline.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,123 @@
|
||||
use anyhow::{bail, Result};
|
||||
use futures_util::StreamExt;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use tokio::sync::mpsc;
|
||||
|
||||
#[derive(Clone, Serialize, Deserialize, Debug)]
|
||||
pub struct Message {
|
||||
pub role: String,
|
||||
pub content: String,
|
||||
}
|
||||
|
||||
impl Message {
|
||||
pub fn user(content: impl Into<String>) -> Self {
|
||||
Message { role: "user".into(), content: content.into() }
|
||||
}
|
||||
pub fn assistant(content: impl Into<String>) -> Self {
|
||||
Message { role: "assistant".into(), content: content.into() }
|
||||
}
|
||||
pub fn system(content: impl Into<String>) -> Self {
|
||||
Message { role: "system".into(), content: content.into() }
|
||||
}
|
||||
}
|
||||
|
||||
/// Streams a reply from Hermes' OpenAI-compatible API, pushing text deltas
|
||||
/// into `tx` as they arrive.
|
||||
///
|
||||
/// /v1/chat/completions with client-side history, not /v1/responses with
|
||||
/// previous_response_id: the Responses API keeps the transcript server-side,
|
||||
/// which is nicer, but this shape is the one every OpenAI client exercises so
|
||||
/// it is the one least likely to differ between Hermes versions. Her memory
|
||||
/// and skills are unaffected either way — those are not conversation state.
|
||||
pub async fn stream_reply(
|
||||
client: &reqwest::Client,
|
||||
base_url: &str,
|
||||
key: &str,
|
||||
model: &str,
|
||||
history: &[Message],
|
||||
tx: mpsc::Sender<String>,
|
||||
) -> Result<String> {
|
||||
let body = serde_json::json!({
|
||||
"model": model,
|
||||
"messages": history,
|
||||
"stream": true,
|
||||
});
|
||||
|
||||
let resp = client
|
||||
.post(format!("{}/v1/chat/completions", base_url.trim_end_matches('/')))
|
||||
.bearer_auth(key)
|
||||
.json(&body)
|
||||
.send()
|
||||
.await?;
|
||||
|
||||
if !resp.status().is_success() {
|
||||
let status = resp.status();
|
||||
let text = resp.text().await.unwrap_or_default();
|
||||
bail!("hermes {status}: {}", text.trim());
|
||||
}
|
||||
|
||||
let mut stream = resp.bytes_stream();
|
||||
let mut pending = String::new();
|
||||
let mut full = String::new();
|
||||
|
||||
while let Some(chunk) = stream.next().await {
|
||||
pending.push_str(&String::from_utf8_lossy(&chunk?));
|
||||
// SSE frames are separated by a blank line; a chunk boundary can land
|
||||
// mid-frame, so only complete frames are consumed.
|
||||
while let Some(idx) = pending.find("\n\n") {
|
||||
let frame: String = pending.drain(..idx + 2).collect();
|
||||
for line in frame.lines() {
|
||||
let Some(data) = line.strip_prefix("data:") else { continue };
|
||||
let data = data.trim();
|
||||
if data == "[DONE]" {
|
||||
return Ok(full);
|
||||
}
|
||||
if let Some(delta) = parse_delta(data) {
|
||||
full.push_str(&delta);
|
||||
// A closed receiver means the reply was cancelled (barge-in).
|
||||
if tx.send(delta).await.is_err() {
|
||||
return Ok(full);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(full)
|
||||
}
|
||||
|
||||
/// Pulls choices[0].delta.content out of one SSE data payload. Tool-call
|
||||
/// frames and role-only frames carry no content and are skipped.
|
||||
fn parse_delta(data: &str) -> Option<String> {
|
||||
let v: serde_json::Value = serde_json::from_str(data).ok()?;
|
||||
let content = v
|
||||
.get("choices")?
|
||||
.get(0)?
|
||||
.get("delta")?
|
||||
.get("content")?
|
||||
.as_str()?;
|
||||
(!content.is_empty()).then(|| content.to_string())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::parse_delta;
|
||||
|
||||
#[test]
|
||||
fn extracts_content_delta() {
|
||||
let d = r#"{"choices":[{"delta":{"content":"hi"}}]}"#;
|
||||
assert_eq!(parse_delta(d).as_deref(), Some("hi"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ignores_role_only_and_tool_frames() {
|
||||
assert!(parse_delta(r#"{"choices":[{"delta":{"role":"assistant"}}]}"#).is_none());
|
||||
assert!(parse_delta(r#"{"choices":[{"delta":{"tool_calls":[]}}]}"#).is_none());
|
||||
assert!(parse_delta(r#"{"choices":[{"delta":{"content":""}}]}"#).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ignores_malformed_json_rather_than_failing_the_stream() {
|
||||
assert!(parse_delta("not json").is_none());
|
||||
assert!(parse_delta("{}").is_none());
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user