feat: TTS backend abstraction + 4 'imba' features + Lua packs
Big push driven by user feedback ("делай имбу") and web research on what
voice assistants need to be the ideal:
TTS backend abstraction (P0.1)
- new module crates/jarvis-core/src/tts/{mod,sapi,piper,silero}.rs
- TtsBackend trait with SapiBackend (current PowerShell), PiperBackend
(rhasspy/piper, neural quality), SileroBackend (python subprocess)
- JARVIS_TTS env var picks (sapi|piper|silero). Auto-detect Piper if
binary + voice present in tools/piper/. Falls back to SAPI on missing.
- SpeakOpts {lang, detached, raw} replaces ad-hoc args. text_utils
sanitiser applied unless raw=true.
- llm_fallback + lua/api/tts both routed through tts::backend().
- tools/piper/install.ps1 downloads piper.exe + ru_RU-irina-medium.onnx
from rhasspy releases + huggingface. Smoke-test included.
- tools/silero/silero_tts.py helper (PyTorch); rust spawns it as subprocess.
IMBA-1 Agentic LLM router
- crates/jarvis-app/src/llm_router.rs
- When fuzzy/intent matcher fails, LLM picks the closest command from the
full registry. Returns JSON {command_id, confidence, reason}.
- Threshold-gated re-dispatch via substitute phrase. JARVIS_LLM_ROUTER=1
enables; JARVIS_LLM_ROUTER_THRESHOLD overrides 0.55 default.
- Inserted in app.rs::execute_command between "no match" and existing
llm_fallback chat fallback.
IMBA-2 Long-term memory
- crates/jarvis-core/src/long_term_memory.rs — JSON store at
APP_CONFIG_DIR/long_term_memory.json. Atomic write-through.
- remember/recall/search/forget/all/build_context API.
- Lua bindings: jarvis.memory.* (5 functions).
- llm_fallback auto-injects relevant facts (substring search of prompt)
into system message before LLM call.
- Pack resources/commands/memory_pack/ with 4 commands: remember, recall,
forget, list.
IMBA-3 Profile switching (work/game/sleep/driving/default)
- crates/jarvis-core/src/profiles.rs — JSON profiles at APP_CONFIG_DIR/profiles/
Auto-seeds 5 defaults on first run with personality + allow/deny lists +
greetings + emoji icons.
- active_profile.txt persists choice across restart.
- Lua bindings: jarvis.profile.{active,set,list,allows,active_name}.
- llm_fallback prepends profile personality to system prompt.
- Pack resources/commands/profile_switch/ with 6 voice triggers.
IMBA-4 Multimodal screenshot + vision LLM
- crates/jarvis-core/src/lua/api/vision.rs — gated on HTTP sandbox.
- jarvis.vision.screenshot() captures via PowerShell System.Drawing.
- jarvis.vision.describe(prompt?) sends base64 PNG to Groq vision model
(default llama-3.2-11b-vision-preview, override via GROQ_VISION_MODEL).
- Pack resources/commands/vision/ with 2 commands: describe + read_error.
P0.2 Continuous conversation grace window
- config::CONVERSATION_GRACE_MS = 30_000.
- app.rs: after command result, if grace_ms > 0 keep listening WITHOUT
re-wake for the grace duration. Existing CMS_WAIT_DELAY back-dated so
the existing timeout fires at start + grace_ms.
Tests: 24/24 jarvis-core unit tests pass (including 5 text_utils).
Build: cargo build --release -p jarvis-app and -p jarvis-gui both succeed
on Windows MSVC (VS 2026 Enterprise vcvars64).
Notes for setup:
- Piper voice install: pwsh tools/piper/install.ps1 (downloads ~90 MB).
- GROQ_TOKEN needed for IMBA-1 (router) and IMBA-4 (vision).
- All features are opt-in via env vars or auto-detect; existing SAPI +
fuzzy match path remains the default.
This commit is contained in:
parent
80b54af1ee
commit
0b1f1d4480
34 changed files with 2304 additions and 90 deletions
|
|
@ -323,21 +323,45 @@ fn recognize_command(
|
|||
// execute command and check if we should chain
|
||||
let should_chain = execute_command(&recognized_voice, rt);
|
||||
|
||||
if should_chain {
|
||||
// chain: reset and continue listening
|
||||
info!("Chaining enabled, continuing to listen...");
|
||||
let grace_ms = jarvis_core::config::CONVERSATION_GRACE_MS;
|
||||
if should_chain || grace_ms > 0 {
|
||||
// Either explicit chain OR P0.2 continuous-conversation grace window.
|
||||
// Reset listening state and keep going without re-wake.
|
||||
if should_chain {
|
||||
info!("Chain requested, continuing to listen...");
|
||||
} else {
|
||||
info!(
|
||||
"Continuous conversation: {}ms grace window for follow-up.",
|
||||
grace_ms
|
||||
);
|
||||
}
|
||||
stt::reset_speech_recognizer();
|
||||
vad_state = VadState::WaitingForVoice;
|
||||
silence_frames = 0;
|
||||
start = SystemTime::now();
|
||||
// For grace-mode, shorten the deadline to grace_ms (instead of CMS_WAIT_DELAY).
|
||||
// We set `start` such that the existing timeout check (line ~360) fires at
|
||||
// start + CMS_WAIT_DELAY = now + grace_ms.
|
||||
if !should_chain {
|
||||
let cms = jarvis_core::config::CMS_WAIT_DELAY.as_millis() as u64;
|
||||
if grace_ms < cms {
|
||||
// back-date `start` so the existing timeout fires at now + grace_ms
|
||||
let backdate_ms = cms - grace_ms;
|
||||
start = SystemTime::now()
|
||||
.checked_sub(std::time::Duration::from_millis(backdate_ms))
|
||||
.unwrap_or_else(SystemTime::now);
|
||||
} else {
|
||||
start = SystemTime::now();
|
||||
}
|
||||
} else {
|
||||
start = SystemTime::now();
|
||||
}
|
||||
audio_buffer.clear();
|
||||
webrtc_vad.reset();
|
||||
window = ListenWindow::new(jarvis_core::audio_processing::vad::webrtc::FRAME_MS);
|
||||
ipc::send(IpcEvent::Listening);
|
||||
continue;
|
||||
} else {
|
||||
// no chain: return to wake word
|
||||
info!("No chain, returning to wake word mode.");
|
||||
info!("Conversation grace disabled, returning to wake word mode.");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
|
@ -460,6 +484,26 @@ fn execute_command(text: &str, rt: &tokio::runtime::Runtime) -> bool {
|
|||
} else {
|
||||
info!("No command found for: {}", text);
|
||||
|
||||
// IMBA-1: Agentic LLM router — try to map unknown phrase to a known command
|
||||
// by asking the LLM. This is the killer feature competitors don't have.
|
||||
if crate::llm_router::is_enabled() {
|
||||
if let Some(routed) = crate::llm_router::try_route(text) {
|
||||
info!(
|
||||
"Router → {} ({}%): {} | substitute='{}'",
|
||||
routed.command_id,
|
||||
(routed.confidence * 100.0) as u32,
|
||||
routed.reason,
|
||||
routed.substitute_phrase
|
||||
);
|
||||
|
||||
// Re-dispatch with the canonical phrase for the chosen command.
|
||||
// Guard against infinite recursion: pass a marker if needed.
|
||||
if routed.substitute_phrase != text {
|
||||
return execute_command(&routed.substitute_phrase, rt);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if jarvis_core::config::LLM_AUTO_FALLBACK
|
||||
&& crate::llm_fallback::is_enabled()
|
||||
&& text.chars().count() >= jarvis_core::config::LLM_AUTO_FALLBACK_MIN_CHARS
|
||||
|
|
|
|||
|
|
@ -5,6 +5,9 @@ use jarvis_core::config;
|
|||
use jarvis_core::i18n;
|
||||
use jarvis_core::ipc::{self, IpcEvent};
|
||||
use jarvis_core::llm::{ChatMessage, ConversationHistory, LlmClient};
|
||||
use jarvis_core::long_term_memory;
|
||||
use jarvis_core::profiles;
|
||||
use jarvis_core::tts::{self, SpeakOpts};
|
||||
use jarvis_core::voices;
|
||||
|
||||
struct State {
|
||||
|
|
@ -90,7 +93,27 @@ pub fn handle(prompt: &str) {
|
|||
let snapshot: Vec<ChatMessage> = {
|
||||
let mut h = state.history.lock();
|
||||
h.push_user(prompt);
|
||||
h.snapshot()
|
||||
let mut snap = h.snapshot();
|
||||
|
||||
// Inject (a) profile personality (b) relevant long-term memory as a fresh
|
||||
// system message right after the base prompt. Both are optional.
|
||||
let profile = profiles::active();
|
||||
let mut overlay = String::new();
|
||||
if !profile.llm_personality.is_empty() {
|
||||
overlay.push_str(&format!("Активный профиль: {} {}\nХарактер для ответа: {}\n",
|
||||
profile.icon, profile.name, profile.llm_personality));
|
||||
}
|
||||
let mem_ctx = long_term_memory::build_context(prompt, 5);
|
||||
if !mem_ctx.is_empty() {
|
||||
overlay.push_str(&mem_ctx);
|
||||
}
|
||||
if !overlay.is_empty() {
|
||||
// Insert after the base system prompt (index 0 typically), before user msgs.
|
||||
let insert_at = if !snap.is_empty() && snap[0].role == "system" { 1 } else { 0 };
|
||||
snap.insert(insert_at, ChatMessage::system(overlay));
|
||||
}
|
||||
|
||||
snap
|
||||
};
|
||||
|
||||
match state.client.complete(&snapshot, state.max_tokens) {
|
||||
|
|
@ -100,7 +123,7 @@ pub fn handle(prompt: &str) {
|
|||
state.history.lock().push_assistant(reply.clone());
|
||||
ipc::send(IpcEvent::LlmReply { text: reply.clone() });
|
||||
voices::play_ok();
|
||||
speak_via_sapi(&reply);
|
||||
speak_reply(&reply);
|
||||
}
|
||||
Err(e) => {
|
||||
error!("LLM request failed: {}", e);
|
||||
|
|
@ -108,41 +131,14 @@ pub fn handle(prompt: &str) {
|
|||
let err_text = config::LLM_FALLBACK_ERROR_RU.to_string();
|
||||
ipc::send(IpcEvent::LlmReply { text: err_text.clone() });
|
||||
voices::play_error();
|
||||
speak_via_sapi(&err_text);
|
||||
speak_reply(&err_text);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
fn speak_via_sapi(text: &str) {
|
||||
fn speak_reply(text: &str) {
|
||||
if std::env::var("JARVIS_LLM_TTS").as_deref() == Ok("false") {
|
||||
return;
|
||||
}
|
||||
let cleaned = jarvis_core::text_utils::sanitize_for_speech(text);
|
||||
let escaped = cleaned.replace('\'', "''");
|
||||
let ps = format!(
|
||||
"Add-Type -AssemblyName System.Speech; \
|
||||
$s = New-Object System.Speech.Synthesis.SpeechSynthesizer; \
|
||||
foreach ($v in $s.GetInstalledVoices()) {{ \
|
||||
if ($v.VoiceInfo.Culture.TwoLetterISOLanguageName -eq 'ru') {{ \
|
||||
try {{ $s.SelectVoice($v.VoiceInfo.Name); break }} catch {{ }} \
|
||||
}} \
|
||||
}} \
|
||||
$s.Speak('{}')",
|
||||
escaped,
|
||||
);
|
||||
match std::process::Command::new("powershell")
|
||||
.args(["-NoProfile", "-Command", &ps])
|
||||
.stdout(std::process::Stdio::null())
|
||||
.stderr(std::process::Stdio::null())
|
||||
.spawn()
|
||||
{
|
||||
Ok(_) => {}
|
||||
Err(e) => warn!("SAPI spawn failed: {}", e),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "windows"))]
|
||||
fn speak_via_sapi(_text: &str) {
|
||||
// No-op on non-Windows; LLM reply still arrives via IPC for the GUI to render.
|
||||
tts::speak(text, &SpeakOpts::lang("ru"));
|
||||
}
|
||||
|
|
|
|||
224
crates/jarvis-app/src/llm_router.rs
Normal file
224
crates/jarvis-app/src/llm_router.rs
Normal file
|
|
@ -0,0 +1,224 @@
|
|||
//! IMBA-1: Agentic LLM router.
|
||||
//!
|
||||
//! When the fuzzy/intent matcher fails to find a command for the user's phrase,
|
||||
//! ask the LLM to pick the best matching command from the registry. If confidence
|
||||
//! exceeds the threshold, we substitute the user's phrase with a canonical phrase
|
||||
//! from the chosen command and re-dispatch through the normal pipeline.
|
||||
//!
|
||||
//! This is what Алиса / Siri / Cortana cannot do: they bounce unknown queries to
|
||||
//! web search. J.A.R.V.I.S. instead reasons about its OWN capabilities.
|
||||
|
||||
use once_cell::sync::OnceCell;
|
||||
use serde::Deserialize;
|
||||
|
||||
use jarvis_core::config;
|
||||
use jarvis_core::i18n;
|
||||
use jarvis_core::llm::{ChatMessage, LlmClient};
|
||||
use jarvis_core::{JCommandsList, COMMANDS_LIST};
|
||||
|
||||
const SYSTEM_PROMPT_RU: &str = "Ты — диспетчер голосовых команд J.A.R.V.I.S. \
|
||||
Тебе даётся фраза пользователя и список доступных команд (id + примеры фраз). \
|
||||
Твоя задача: выбрать ОДНУ команду, которая лучше всего подходит, ИЛИ ответить \"none\" если ничего не подходит. \
|
||||
Отвечай СТРОГО в формате JSON, без markdown-блоков: \
|
||||
{\"command_id\": \"<id или 'none'>\", \"confidence\": 0.0-1.0, \"reason\": \"<краткое пояснение>\"}. \
|
||||
Если фраза неоднозначна, выбирай команду с большим purpose-match. \
|
||||
Если фраза похожа на просьбу 'поболтать' или вопрос, требующий длинного ответа — отвечай command_id='none'.";
|
||||
|
||||
const SYSTEM_PROMPT_EN: &str = "You are the voice command dispatcher for J.A.R.V.I.S. \
|
||||
You receive the user's phrase and a list of available commands (id + example phrases). \
|
||||
Your job: pick ONE command that best matches, OR reply \"none\" if nothing fits. \
|
||||
Respond STRICTLY in JSON, no markdown blocks: \
|
||||
{\"command_id\": \"<id or 'none'>\", \"confidence\": 0.0-1.0, \"reason\": \"<short reason>\"}. \
|
||||
If the phrase looks like 'chat' or a question requiring a long answer, return command_id='none'.";
|
||||
|
||||
const DEFAULT_THRESHOLD: f32 = 0.55;
|
||||
const MAX_TOKENS: u32 = 200;
|
||||
const TEMPERATURE: f32 = 0.1;
|
||||
const TOP_P: f32 = 0.9;
|
||||
const MAX_PHRASES_PER_CMD: usize = 4;
|
||||
|
||||
struct State {
|
||||
client: LlmClient,
|
||||
threshold: f32,
|
||||
}
|
||||
|
||||
static STATE: OnceCell<Option<State>> = OnceCell::new();
|
||||
|
||||
pub fn init() {
|
||||
let _ = STATE.set(build_state());
|
||||
}
|
||||
|
||||
fn build_state() -> Option<State> {
|
||||
if !router_enabled() {
|
||||
info!("LLM router disabled (set JARVIS_LLM_ROUTER=1 to enable).");
|
||||
return None;
|
||||
}
|
||||
let client = match LlmClient::from_env() {
|
||||
Ok(c) => c,
|
||||
Err(e) => {
|
||||
warn!("LLM router disabled: {}. Set GROQ_TOKEN to enable.", e);
|
||||
return None;
|
||||
}
|
||||
};
|
||||
let threshold = std::env::var("JARVIS_LLM_ROUTER_THRESHOLD")
|
||||
.ok()
|
||||
.and_then(|v| v.parse::<f32>().ok())
|
||||
.unwrap_or(DEFAULT_THRESHOLD);
|
||||
|
||||
info!("LLM router enabled (threshold {:.2}).", threshold);
|
||||
Some(State { client, threshold })
|
||||
}
|
||||
|
||||
fn router_enabled() -> bool {
|
||||
std::env::var("JARVIS_LLM_ROUTER")
|
||||
.map(|v| matches!(v.trim().to_lowercase().as_str(), "1" | "true" | "yes" | "on"))
|
||||
.unwrap_or(true) // default ON when GROQ_TOKEN is present
|
||||
&& config::LLM_DEFAULT_ENABLED
|
||||
}
|
||||
|
||||
pub fn is_enabled() -> bool {
|
||||
STATE.get().and_then(|s| s.as_ref()).is_some()
|
||||
}
|
||||
|
||||
/// Result of routing an unknown phrase.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct RouteResult {
|
||||
pub command_id: String,
|
||||
pub substitute_phrase: String,
|
||||
pub confidence: f32,
|
||||
pub reason: String,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct RouteJson {
|
||||
#[serde(default)]
|
||||
command_id: String,
|
||||
#[serde(default)]
|
||||
confidence: f32,
|
||||
#[serde(default)]
|
||||
reason: String,
|
||||
}
|
||||
|
||||
/// Try to route `text` to a known command via LLM. Returns `None` if disabled,
|
||||
/// LLM call fails, no match, or confidence below threshold.
|
||||
pub fn try_route(text: &str) -> Option<RouteResult> {
|
||||
let state = STATE.get().and_then(|s| s.as_ref())?;
|
||||
let commands_list = COMMANDS_LIST.get()?;
|
||||
let lang = i18n::get_language();
|
||||
|
||||
let prompt = build_routing_prompt(commands_list, text, &lang);
|
||||
let system = if lang.starts_with("ru") { SYSTEM_PROMPT_RU } else { SYSTEM_PROMPT_EN };
|
||||
|
||||
let messages = vec![
|
||||
ChatMessage::system(system.to_string()),
|
||||
ChatMessage::user(prompt),
|
||||
];
|
||||
|
||||
let raw = match state.client.complete_with(&messages, MAX_TOKENS, TEMPERATURE, TOP_P) {
|
||||
Ok(r) => r,
|
||||
Err(e) => {
|
||||
warn!("LLM router request failed: {}", e);
|
||||
return None;
|
||||
}
|
||||
};
|
||||
|
||||
debug!("Router raw reply: {}", raw);
|
||||
|
||||
let parsed: RouteJson = match parse_json(&raw) {
|
||||
Some(p) => p,
|
||||
None => {
|
||||
warn!("Router reply not valid JSON: {}", raw);
|
||||
return None;
|
||||
}
|
||||
};
|
||||
|
||||
if parsed.command_id.is_empty() || parsed.command_id == "none" {
|
||||
info!("Router: no match (reason: {})", parsed.reason);
|
||||
return None;
|
||||
}
|
||||
|
||||
if parsed.confidence < state.threshold {
|
||||
info!(
|
||||
"Router: {} below threshold {:.2} (confidence {:.2}, reason: {})",
|
||||
parsed.command_id, state.threshold, parsed.confidence, parsed.reason
|
||||
);
|
||||
return None;
|
||||
}
|
||||
|
||||
let substitute = lookup_first_phrase(commands_list, &parsed.command_id, &lang)?;
|
||||
|
||||
Some(RouteResult {
|
||||
command_id: parsed.command_id,
|
||||
substitute_phrase: substitute,
|
||||
confidence: parsed.confidence,
|
||||
reason: parsed.reason,
|
||||
})
|
||||
}
|
||||
|
||||
fn build_routing_prompt(commands_list: &[JCommandsList], user_text: &str, lang: &str) -> String {
|
||||
let mut buf = String::with_capacity(4096);
|
||||
|
||||
if lang.starts_with("ru") {
|
||||
buf.push_str("Доступные команды:\n");
|
||||
} else {
|
||||
buf.push_str("Available commands:\n");
|
||||
}
|
||||
|
||||
for pack in commands_list {
|
||||
for cmd in &pack.commands {
|
||||
let phrases = cmd.get_phrases(lang);
|
||||
if phrases.is_empty() { continue; }
|
||||
let sample: Vec<&str> = phrases.iter()
|
||||
.take(MAX_PHRASES_PER_CMD)
|
||||
.map(|s| s.as_str())
|
||||
.collect();
|
||||
buf.push_str(&format!("- id={} ", cmd.id));
|
||||
if !cmd.description.is_empty() {
|
||||
buf.push_str(&format!("({}) ", cmd.description));
|
||||
}
|
||||
buf.push_str(&format!("examples=[{}]\n", sample.join(" | ")));
|
||||
}
|
||||
}
|
||||
|
||||
if lang.starts_with("ru") {
|
||||
buf.push_str(&format!("\nФраза пользователя: \"{}\"\n", user_text));
|
||||
buf.push_str("Верни JSON.");
|
||||
} else {
|
||||
buf.push_str(&format!("\nUser phrase: \"{}\"\n", user_text));
|
||||
buf.push_str("Return JSON.");
|
||||
}
|
||||
|
||||
buf
|
||||
}
|
||||
|
||||
fn lookup_first_phrase(commands_list: &[JCommandsList], cmd_id: &str, lang: &str) -> Option<String> {
|
||||
for pack in commands_list {
|
||||
for cmd in &pack.commands {
|
||||
if cmd.id == cmd_id {
|
||||
let phrases = cmd.get_phrases(lang);
|
||||
if let Some(first) = phrases.first() {
|
||||
return Some(first.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn parse_json(raw: &str) -> Option<RouteJson> {
|
||||
// LLM sometimes wraps in ```json ... ``` despite instructions.
|
||||
let cleaned = raw
|
||||
.trim()
|
||||
.trim_start_matches("```json")
|
||||
.trim_start_matches("```")
|
||||
.trim_end_matches("```")
|
||||
.trim();
|
||||
|
||||
// Find the first '{' and last '}' to be tolerant of prose around the JSON.
|
||||
let start = cleaned.find('{')?;
|
||||
let end = cleaned.rfind('}')?;
|
||||
if end <= start { return None; }
|
||||
|
||||
let slice = &cleaned[start..=end];
|
||||
serde_json::from_str(slice).ok()
|
||||
}
|
||||
|
|
@ -19,6 +19,7 @@ mod log;
|
|||
// include app
|
||||
mod app;
|
||||
mod llm_fallback;
|
||||
mod llm_router;
|
||||
|
||||
// include tray
|
||||
// @TODO. macOS currently not supported for tray functionality.
|
||||
|
|
@ -59,6 +60,19 @@ fn main() -> Result<(), String> {
|
|||
eprintln!("[jarvis-app] step: llm_fallback::init");
|
||||
llm_fallback::init();
|
||||
|
||||
eprintln!("[jarvis-app] step: llm_router::init");
|
||||
llm_router::init();
|
||||
|
||||
eprintln!("[jarvis-app] step: long_term_memory::init");
|
||||
if let Err(e) = jarvis_core::long_term_memory::init() {
|
||||
warn!("Long-term memory init failed: {}", e);
|
||||
}
|
||||
|
||||
eprintln!("[jarvis-app] step: profiles::init");
|
||||
if let Err(e) = jarvis_core::profiles::init() {
|
||||
warn!("Profiles init failed: {}", e);
|
||||
}
|
||||
|
||||
eprintln!("[jarvis-app] step: recorder::init");
|
||||
if recorder::init().is_err() {
|
||||
notify_mic_problem();
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue