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
|
|
@ -7,4 +7,7 @@ pub mod state;
|
|||
pub mod system;
|
||||
pub mod tts;
|
||||
pub mod llm;
|
||||
pub mod text;
|
||||
pub mod text;
|
||||
pub mod memory;
|
||||
pub mod profile;
|
||||
pub mod vision;
|
||||
67
crates/jarvis-core/src/lua/api/memory.rs
Normal file
67
crates/jarvis-core/src/lua/api/memory.rs
Normal file
|
|
@ -0,0 +1,67 @@
|
|||
//! Lua bindings for the long-term memory store.
|
||||
//!
|
||||
//! Usage from Lua scripts:
|
||||
//!
|
||||
//! jarvis.memory.remember("любимый чай", "улун")
|
||||
//! local v = jarvis.memory.recall("любимый чай") -- "улун" or nil
|
||||
//! for _, hit in ipairs(jarvis.memory.search("чай", 5)) do
|
||||
//! print(hit.key, hit.value)
|
||||
//! end
|
||||
//! jarvis.memory.forget("любимый чай")
|
||||
//! local all = jarvis.memory.all() -- array of {key, value, ...}
|
||||
|
||||
use mlua::{Lua, Table};
|
||||
|
||||
use crate::long_term_memory;
|
||||
|
||||
pub fn register(lua: &Lua, jarvis: &Table) -> mlua::Result<()> {
|
||||
let mem = lua.create_table()?;
|
||||
|
||||
let remember = lua.create_function(|_, (k, v): (String, String)| {
|
||||
long_term_memory::remember(&k, &v)
|
||||
.map_err(|e| mlua::Error::external(e))
|
||||
})?;
|
||||
mem.set("remember", remember)?;
|
||||
|
||||
let recall = lua.create_function(|_, k: String| {
|
||||
Ok(long_term_memory::recall(&k))
|
||||
})?;
|
||||
mem.set("recall", recall)?;
|
||||
|
||||
let search = lua.create_function(|lua, (q, n): (String, Option<usize>)| {
|
||||
let hits = long_term_memory::search(&q, n.unwrap_or(5));
|
||||
let arr = lua.create_table()?;
|
||||
for (i, h) in hits.iter().enumerate() {
|
||||
let row = lua.create_table()?;
|
||||
row.set("key", h.key.clone())?;
|
||||
row.set("value", h.value.clone())?;
|
||||
row.set("created_at", h.created_at)?;
|
||||
row.set("last_used_at", h.last_used_at)?;
|
||||
row.set("use_count", h.use_count)?;
|
||||
arr.set(i + 1, row)?;
|
||||
}
|
||||
Ok(arr)
|
||||
})?;
|
||||
mem.set("search", search)?;
|
||||
|
||||
let forget = lua.create_function(|_, k: String| {
|
||||
Ok(long_term_memory::forget(&k))
|
||||
})?;
|
||||
mem.set("forget", forget)?;
|
||||
|
||||
let all = lua.create_function(|lua, ()| {
|
||||
let recs = long_term_memory::all();
|
||||
let arr = lua.create_table()?;
|
||||
for (i, h) in recs.iter().enumerate() {
|
||||
let row = lua.create_table()?;
|
||||
row.set("key", h.key.clone())?;
|
||||
row.set("value", h.value.clone())?;
|
||||
arr.set(i + 1, row)?;
|
||||
}
|
||||
Ok(arr)
|
||||
})?;
|
||||
mem.set("all", all)?;
|
||||
|
||||
jarvis.set("memory", mem)?;
|
||||
Ok(())
|
||||
}
|
||||
63
crates/jarvis-core/src/lua/api/profile.rs
Normal file
63
crates/jarvis-core/src/lua/api/profile.rs
Normal file
|
|
@ -0,0 +1,63 @@
|
|||
//! Lua bindings for profile switching.
|
||||
//!
|
||||
//! Usage from Lua scripts:
|
||||
//!
|
||||
//! local p = jarvis.profile.active() -- table {name, icon, description, ...}
|
||||
//! jarvis.profile.set("work") -- switch to work profile
|
||||
//! local names = jarvis.profile.list() -- {"default", "work", "game", "sleep", "driving"}
|
||||
//! if jarvis.profile.allows("games.steam") then ... end
|
||||
|
||||
use mlua::{Lua, Table};
|
||||
|
||||
use crate::profiles;
|
||||
|
||||
pub fn register(lua: &Lua, jarvis: &Table) -> mlua::Result<()> {
|
||||
let prof = lua.create_table()?;
|
||||
|
||||
let active = lua.create_function(|lua, ()| {
|
||||
let p = profiles::active();
|
||||
let t = lua.create_table()?;
|
||||
t.set("name", p.name)?;
|
||||
t.set("description", p.description)?;
|
||||
t.set("llm_personality", p.llm_personality)?;
|
||||
t.set("greeting", p.greeting)?;
|
||||
t.set("icon", p.icon)?;
|
||||
Ok(t)
|
||||
})?;
|
||||
prof.set("active", active)?;
|
||||
|
||||
let active_name = lua.create_function(|_, ()| Ok(profiles::active_name()))?;
|
||||
prof.set("active_name", active_name)?;
|
||||
|
||||
let set_active = lua.create_function(|lua, name: String| {
|
||||
match profiles::set_active(&name) {
|
||||
Ok(p) => {
|
||||
let t = lua.create_table()?;
|
||||
t.set("name", p.name)?;
|
||||
t.set("icon", p.icon)?;
|
||||
t.set("greeting", p.greeting)?;
|
||||
Ok(t)
|
||||
}
|
||||
Err(e) => Err(mlua::Error::external(e)),
|
||||
}
|
||||
})?;
|
||||
prof.set("set", set_active)?;
|
||||
|
||||
let list = lua.create_function(|lua, ()| {
|
||||
let names = profiles::list();
|
||||
let arr = lua.create_table()?;
|
||||
for (i, n) in names.iter().enumerate() {
|
||||
arr.set(i + 1, n.clone())?;
|
||||
}
|
||||
Ok(arr)
|
||||
})?;
|
||||
prof.set("list", list)?;
|
||||
|
||||
let allows = lua.create_function(|_, cmd_id: String| {
|
||||
Ok(profiles::active().allows_command(&cmd_id))
|
||||
})?;
|
||||
prof.set("allows", allows)?;
|
||||
|
||||
jarvis.set("profile", prof)?;
|
||||
Ok(())
|
||||
}
|
||||
|
|
@ -1,70 +1,35 @@
|
|||
use mlua::{Lua, Table};
|
||||
use std::process::{Command, Stdio};
|
||||
|
||||
use crate::text_utils::sanitize_for_speech;
|
||||
use crate::tts::{self, SpeakOpts};
|
||||
|
||||
pub fn register(lua: &Lua, jarvis: &Table) -> mlua::Result<()> {
|
||||
// jarvis.speak(text, opts?)
|
||||
// opts.lang: ISO 2-letter code (ru, en, de, ...). default "ru"
|
||||
// opts.async: if true, fire-and-forget; if false, block until done. default true
|
||||
// opts.raw: if true, skip text sanitization (default false)
|
||||
//
|
||||
// Uses the active TTS backend (see `crate::tts::backend`). Configured via JARVIS_TTS env var.
|
||||
let speak_fn = lua.create_function(|_, (text, opts): (String, Option<Table>)| {
|
||||
let mut iso = "ru".to_string();
|
||||
let mut detached = true;
|
||||
let mut raw = false;
|
||||
let mut speak_opts = SpeakOpts::default();
|
||||
|
||||
if let Some(t) = opts {
|
||||
if let Ok(v) = t.get::<String>("lang") { iso = v; }
|
||||
if let Ok(v) = t.get::<bool>("async") { detached = v; }
|
||||
if let Ok(v) = t.get::<bool>("raw") { raw = v; }
|
||||
if let Ok(v) = t.get::<String>("lang") { speak_opts.lang = v; }
|
||||
if let Ok(v) = t.get::<bool>("async") { speak_opts.detached = v; }
|
||||
if let Ok(v) = t.get::<bool>("raw") { speak_opts.raw = v; }
|
||||
}
|
||||
|
||||
let prepared = if raw { text } else { sanitize_for_speech(&text) };
|
||||
speak_via_sapi(&prepared, &iso, detached);
|
||||
tts::speak(&text, &speak_opts);
|
||||
Ok(())
|
||||
})?;
|
||||
jarvis.set("speak", speak_fn)?;
|
||||
|
||||
// jarvis.tts.backend() — returns name of active backend ("sapi", "piper", "silero")
|
||||
let tts_table = lua.create_table()?;
|
||||
let backend_fn = lua.create_function(|_, ()| {
|
||||
Ok(tts::backend().name().to_string())
|
||||
})?;
|
||||
tts_table.set("backend", backend_fn)?;
|
||||
jarvis.set("tts", tts_table)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
fn speak_via_sapi(text: &str, iso: &str, detached: bool) {
|
||||
if text.is_empty() {
|
||||
return;
|
||||
}
|
||||
let escaped = text.replace('\'', "''").replace('\r', " ").replace('\n', " ");
|
||||
let safe_iso = if iso.chars().all(|c| c.is_ascii_alphabetic()) && iso.len() == 2 {
|
||||
iso.to_lowercase()
|
||||
} else {
|
||||
"ru".to_string()
|
||||
};
|
||||
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 '{}') {{ \
|
||||
try {{ $s.SelectVoice($v.VoiceInfo.Name); break }} catch {{}} \
|
||||
}} \
|
||||
}} \
|
||||
$s.Speak('{}')",
|
||||
safe_iso, escaped
|
||||
);
|
||||
|
||||
let mut cmd = Command::new("powershell");
|
||||
cmd.args(["-NoProfile", "-ExecutionPolicy", "Bypass", "-Command", &ps])
|
||||
.stdout(Stdio::null())
|
||||
.stderr(Stdio::null());
|
||||
|
||||
if detached {
|
||||
let _ = cmd.spawn();
|
||||
} else {
|
||||
let _ = cmd.status();
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "windows"))]
|
||||
fn speak_via_sapi(text: &str, _iso: &str, _detached: bool) {
|
||||
log::info!("[Lua tts] would speak: {}", text);
|
||||
}
|
||||
|
||||
|
|
|
|||
189
crates/jarvis-core/src/lua/api/vision.rs
Normal file
189
crates/jarvis-core/src/lua/api/vision.rs
Normal file
|
|
@ -0,0 +1,189 @@
|
|||
//! IMBA-4: Multimodal — screenshot + vision LLM.
|
||||
//!
|
||||
//! Lua bindings:
|
||||
//! jarvis.vision.screenshot(path?) -> path on disk (default temp .png)
|
||||
//! jarvis.vision.describe(prompt?) -> string description (vision LLM call)
|
||||
//!
|
||||
//! Windows-only screenshot via PowerShell System.Drawing. Posts to a vision-capable
|
||||
//! Groq model (`llama-3.2-11b-vision-preview` by default; override via `GROQ_VISION_MODEL`).
|
||||
//!
|
||||
//! Requires HTTP sandbox level (registered behind `allows_http()` in engine.rs).
|
||||
|
||||
use mlua::{Lua, Table};
|
||||
|
||||
pub fn register(lua: &Lua, jarvis: &Table) -> mlua::Result<()> {
|
||||
let vision = lua.create_table()?;
|
||||
|
||||
let screenshot = lua.create_function(|_, path: Option<String>| {
|
||||
match take_screenshot(path.as_deref()) {
|
||||
Ok(p) => Ok(Some(p)),
|
||||
Err(e) => {
|
||||
log::warn!("vision.screenshot failed: {}", e);
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
})?;
|
||||
vision.set("screenshot", screenshot)?;
|
||||
|
||||
let describe = lua.create_function(|_, prompt: Option<String>| {
|
||||
let user_prompt = prompt.unwrap_or_else(|| {
|
||||
"Опиши кратко что на этом экране. Если есть ошибки — отметь их.".to_string()
|
||||
});
|
||||
match describe_screen(&user_prompt) {
|
||||
Ok(text) => Ok(Some(text)),
|
||||
Err(e) => {
|
||||
log::warn!("vision.describe failed: {}", e);
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
})?;
|
||||
vision.set("describe", describe)?;
|
||||
|
||||
jarvis.set("vision", vision)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
fn take_screenshot(out_path: Option<&str>) -> Result<String, String> {
|
||||
let target = match out_path {
|
||||
Some(p) => std::path::PathBuf::from(p),
|
||||
None => {
|
||||
let f = tempfile::Builder::new()
|
||||
.prefix("jarvis-screen-")
|
||||
.suffix(".png")
|
||||
.tempfile()
|
||||
.map_err(|e| format!("tempfile: {}", e))?;
|
||||
let p = f.path().to_path_buf();
|
||||
drop(f);
|
||||
p
|
||||
}
|
||||
};
|
||||
|
||||
let escaped = target.display().to_string().replace('\'', "''");
|
||||
let ps = format!(
|
||||
r#"
|
||||
Add-Type -AssemblyName System.Windows.Forms;
|
||||
Add-Type -AssemblyName System.Drawing;
|
||||
$bounds = [System.Windows.Forms.Screen]::PrimaryScreen.Bounds;
|
||||
$bmp = New-Object System.Drawing.Bitmap $bounds.Width, $bounds.Height;
|
||||
$g = [System.Drawing.Graphics]::FromImage($bmp);
|
||||
$g.CopyFromScreen($bounds.Location, [System.Drawing.Point]::Empty, $bounds.Size);
|
||||
$bmp.Save('{}', [System.Drawing.Imaging.ImageFormat]::Png);
|
||||
$g.Dispose(); $bmp.Dispose();
|
||||
"#,
|
||||
escaped
|
||||
);
|
||||
|
||||
let status = std::process::Command::new("powershell")
|
||||
.args(["-NoProfile", "-ExecutionPolicy", "Bypass", "-Command", &ps])
|
||||
.stdout(std::process::Stdio::null())
|
||||
.stderr(std::process::Stdio::null())
|
||||
.status()
|
||||
.map_err(|e| format!("powershell spawn: {}", e))?;
|
||||
|
||||
if !status.success() {
|
||||
return Err(format!("screenshot powershell exited {}", status));
|
||||
}
|
||||
if !target.is_file() {
|
||||
return Err("screenshot file not created".to_string());
|
||||
}
|
||||
Ok(target.display().to_string())
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "windows"))]
|
||||
fn take_screenshot(_out_path: Option<&str>) -> Result<String, String> {
|
||||
Err("screenshot not implemented on this platform".into())
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
fn describe_screen(prompt: &str) -> Result<String, String> {
|
||||
let path = take_screenshot(None)?;
|
||||
let b64 = read_as_base64(&path)?;
|
||||
let _ = std::fs::remove_file(&path);
|
||||
call_vision_llm(prompt, &b64)
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "windows"))]
|
||||
fn describe_screen(_prompt: &str) -> Result<String, String> {
|
||||
Err("vision not implemented on this platform".into())
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
fn read_as_base64(path: &str) -> Result<String, String> {
|
||||
// Avoid a new base64 crate dep — use PowerShell [Convert]::ToBase64String.
|
||||
let escaped = path.replace('\'', "''");
|
||||
let ps = format!(
|
||||
"[Convert]::ToBase64String([IO.File]::ReadAllBytes('{}'))",
|
||||
escaped
|
||||
);
|
||||
let out = std::process::Command::new("powershell")
|
||||
.args(["-NoProfile", "-ExecutionPolicy", "Bypass", "-Command", &ps])
|
||||
.output()
|
||||
.map_err(|e| format!("base64 powershell: {}", e))?;
|
||||
if !out.status.success() {
|
||||
return Err(format!(
|
||||
"base64 powershell exited {}: {}",
|
||||
out.status,
|
||||
String::from_utf8_lossy(&out.stderr)
|
||||
));
|
||||
}
|
||||
let s = String::from_utf8_lossy(&out.stdout).trim().to_string();
|
||||
if s.is_empty() {
|
||||
return Err("base64 output empty".into());
|
||||
}
|
||||
Ok(s)
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
fn call_vision_llm(prompt: &str, image_b64: &str) -> Result<String, String> {
|
||||
use serde_json::json;
|
||||
|
||||
let token = std::env::var("GROQ_TOKEN")
|
||||
.map_err(|_| "GROQ_TOKEN not set".to_string())?;
|
||||
let base = std::env::var("GROQ_BASE_URL")
|
||||
.unwrap_or_else(|_| "https://api.groq.com/openai/v1".to_string());
|
||||
let model = std::env::var("GROQ_VISION_MODEL")
|
||||
.unwrap_or_else(|_| "llama-3.2-11b-vision-preview".to_string());
|
||||
|
||||
let body = json!({
|
||||
"model": model,
|
||||
"max_tokens": 400,
|
||||
"temperature": 0.2,
|
||||
"messages": [{
|
||||
"role": "user",
|
||||
"content": [
|
||||
{ "type": "text", "text": prompt },
|
||||
{ "type": "image_url",
|
||||
"image_url": {
|
||||
"url": format!("data:image/png;base64,{}", image_b64)
|
||||
}
|
||||
}
|
||||
]
|
||||
}]
|
||||
});
|
||||
|
||||
let url = format!("{}/chat/completions", base.trim_end_matches('/'));
|
||||
let client = reqwest::blocking::Client::new();
|
||||
let resp = client
|
||||
.post(&url)
|
||||
.bearer_auth(&token)
|
||||
.json(&body)
|
||||
.send()
|
||||
.map_err(|e| format!("HTTP: {}", e))?;
|
||||
|
||||
let status = resp.status();
|
||||
let text = resp.text().map_err(|e| format!("read body: {}", e))?;
|
||||
if !status.is_success() {
|
||||
return Err(format!("vision API {}: {}", status.as_u16(), text));
|
||||
}
|
||||
|
||||
let json: serde_json::Value =
|
||||
serde_json::from_str(&text).map_err(|e| format!("parse JSON: {}", e))?;
|
||||
json.get("choices")
|
||||
.and_then(|c| c.get(0))
|
||||
.and_then(|c| c.get("message"))
|
||||
.and_then(|m| m.get("content"))
|
||||
.and_then(|c| c.as_str())
|
||||
.map(|s| s.trim().to_string())
|
||||
.ok_or_else(|| format!("no content in response: {}", text))
|
||||
}
|
||||
|
|
@ -78,11 +78,14 @@ impl LuaEngine {
|
|||
api::context::register(&self.lua, &jarvis, context)?;
|
||||
api::tts::register(&self.lua, &jarvis)?;
|
||||
api::text::register(&self.lua, &jarvis)?;
|
||||
api::memory::register(&self.lua, &jarvis)?;
|
||||
api::profile::register(&self.lua, &jarvis)?;
|
||||
|
||||
// sandbox-controlled APIs
|
||||
if self.sandbox.allows_http() {
|
||||
api::http::register(&self.lua, &jarvis)?;
|
||||
api::llm::register(&self.lua, &jarvis)?;
|
||||
api::vision::register(&self.lua, &jarvis)?;
|
||||
}
|
||||
|
||||
if self.sandbox.allows_state() {
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue