J.A.R.V.I.S-rust/crates/jarvis-core/src/llm/mod.rs

145 lines
4.9 KiB
Rust
Raw Normal View History

mod client;
mod history;
pub use client::{
feat: hot-swap LLM backend + media keys + codebase Q&A + scheduler cancel-by-text + TTS pre-warm Single biggest user-facing change: you can now switch local↔cloud LLM by voice without restarting. Plus four new packs and a perf nudge. Shared LLM global (crates/jarvis-core/src/llm/mod.rs) - GLOBAL: Lazy<RwLock<Option<Arc<LlmClient>>>>. Single source of truth. - init_global() / current() / swap_to(LlmBackend) / current_backend_name() / parse_backend(str). - llm_fallback + llm_router migrated: they no longer own a separate LlmClient, they read from the global on each request. Hot-swap is now LIVE — change backend, next chat call uses the new one. - parse_backend accepts both english and russian aliases: "groq"/"cloud"/"облако"/"клауд" → Groq "ollama"/"local"/"локал"/"локальный" → Ollama Voice + Lua LLM switcher (resources/commands/llm_switch/, 3 commands) - "переключись на локальный" / "перейди на оллама" → swap to Ollama - "переключись на облако" / "используй грок" → swap to Groq - "какой у тебя мозг" / "облако или локально" → status query Underlying Lua API (registered globally): jarvis.llm({messages}, opts) -- as before, now uses global client jarvis.llm_status() -> "groq" | "ollama" | "none" jarvis.llm_switch(name) -> name on success, nil on failure Media keys pack (resources/commands/media_keys/, 4 commands) - "пауза" / "плей" → VK_MEDIA_PLAY_PAUSE - "следующий трек" → VK_MEDIA_NEXT_TRACK - "предыдущий трек" → VK_MEDIA_PREV_TRACK - "стоп музыка" → VK_MEDIA_STOP - Helper _media.ps1 uses user32.keybd_event (P/Invoke through Add-Type). - Works with anything that listens to global media keys: Spotify, Yandex Music, YouTube (focused tab), Foobar2000, Winamp, etc. No OAuth, no API keys. Codebase Q&A pack (resources/commands/codebase_qa/, 3 commands) - "укажи проект <path>" → stores path in jarvis.memory under codebase.root - "какой проект сейчас" → speaks current path - "что делает функция X" / "найди в коде Y" / "объясни код" → walks the folder (depth 3, 30 files cap, 4KB per file, 50KB total), filters by source extensions (rs/py/ts/lua/go/...), feeds digest to LLM with a "senior reviewer" system prompt, speaks 3-5 sentence answer. Scheduler cancel-by-text (crates/jarvis-core/src/scheduler.rs) - new pub fn find_by_text(query, limit) -> Vec<ScheduledTask> - new pub fn remove_by_text(query) -> usize (count removed) - new pure helper find_by_text_in(tasks, query, limit) for tests - Lua: jarvis.scheduler.{find_by_text, remove_by_text} - Voice: "отмени напоминание про воду" / "удали задачу про разминку" - 3 new unit tests (52 total in jarvis-core). TTS pre-warm (crates/jarvis-app/src/main.rs) - Call jarvis_core::tts::backend() once on startup so the first speak() doesn't pay Piper binary discovery + voice loading cost. Cuts first-speak latency by ~150-300ms depending on backend. Build: cargo build --release -p jarvis-app -p jarvis-gui both green. Tests: 52/52 jarvis-core unit tests pass.
2026-05-15 16:15:59 +03:00
ChatMessage, ConfigError, LlmBackend, LlmClient, LlmError,
DEFAULT_BASE_URL, DEFAULT_MODEL, ENV_BASE_URL, ENV_MODEL, ENV_TOKEN,
feat: hot-swap LLM backend + media keys + codebase Q&A + scheduler cancel-by-text + TTS pre-warm Single biggest user-facing change: you can now switch local↔cloud LLM by voice without restarting. Plus four new packs and a perf nudge. Shared LLM global (crates/jarvis-core/src/llm/mod.rs) - GLOBAL: Lazy<RwLock<Option<Arc<LlmClient>>>>. Single source of truth. - init_global() / current() / swap_to(LlmBackend) / current_backend_name() / parse_backend(str). - llm_fallback + llm_router migrated: they no longer own a separate LlmClient, they read from the global on each request. Hot-swap is now LIVE — change backend, next chat call uses the new one. - parse_backend accepts both english and russian aliases: "groq"/"cloud"/"облако"/"клауд" → Groq "ollama"/"local"/"локал"/"локальный" → Ollama Voice + Lua LLM switcher (resources/commands/llm_switch/, 3 commands) - "переключись на локальный" / "перейди на оллама" → swap to Ollama - "переключись на облако" / "используй грок" → swap to Groq - "какой у тебя мозг" / "облако или локально" → status query Underlying Lua API (registered globally): jarvis.llm({messages}, opts) -- as before, now uses global client jarvis.llm_status() -> "groq" | "ollama" | "none" jarvis.llm_switch(name) -> name on success, nil on failure Media keys pack (resources/commands/media_keys/, 4 commands) - "пауза" / "плей" → VK_MEDIA_PLAY_PAUSE - "следующий трек" → VK_MEDIA_NEXT_TRACK - "предыдущий трек" → VK_MEDIA_PREV_TRACK - "стоп музыка" → VK_MEDIA_STOP - Helper _media.ps1 uses user32.keybd_event (P/Invoke through Add-Type). - Works with anything that listens to global media keys: Spotify, Yandex Music, YouTube (focused tab), Foobar2000, Winamp, etc. No OAuth, no API keys. Codebase Q&A pack (resources/commands/codebase_qa/, 3 commands) - "укажи проект <path>" → stores path in jarvis.memory under codebase.root - "какой проект сейчас" → speaks current path - "что делает функция X" / "найди в коде Y" / "объясни код" → walks the folder (depth 3, 30 files cap, 4KB per file, 50KB total), filters by source extensions (rs/py/ts/lua/go/...), feeds digest to LLM with a "senior reviewer" system prompt, speaks 3-5 sentence answer. Scheduler cancel-by-text (crates/jarvis-core/src/scheduler.rs) - new pub fn find_by_text(query, limit) -> Vec<ScheduledTask> - new pub fn remove_by_text(query) -> usize (count removed) - new pure helper find_by_text_in(tasks, query, limit) for tests - Lua: jarvis.scheduler.{find_by_text, remove_by_text} - Voice: "отмени напоминание про воду" / "удали задачу про разминку" - 3 new unit tests (52 total in jarvis-core). TTS pre-warm (crates/jarvis-app/src/main.rs) - Call jarvis_core::tts::backend() once on startup so the first speak() doesn't pay Piper binary discovery + voice loading cost. Cuts first-speak latency by ~150-300ms depending on backend. Build: cargo build --release -p jarvis-app -p jarvis-gui both green. Tests: 52/52 jarvis-core unit tests pass.
2026-05-15 16:15:59 +03:00
OLLAMA_DEFAULT_BASE_URL, OLLAMA_DEFAULT_MODEL,
};
pub use history::ConversationHistory;
feat: hot-swap LLM backend + media keys + codebase Q&A + scheduler cancel-by-text + TTS pre-warm Single biggest user-facing change: you can now switch local↔cloud LLM by voice without restarting. Plus four new packs and a perf nudge. Shared LLM global (crates/jarvis-core/src/llm/mod.rs) - GLOBAL: Lazy<RwLock<Option<Arc<LlmClient>>>>. Single source of truth. - init_global() / current() / swap_to(LlmBackend) / current_backend_name() / parse_backend(str). - llm_fallback + llm_router migrated: they no longer own a separate LlmClient, they read from the global on each request. Hot-swap is now LIVE — change backend, next chat call uses the new one. - parse_backend accepts both english and russian aliases: "groq"/"cloud"/"облако"/"клауд" → Groq "ollama"/"local"/"локал"/"локальный" → Ollama Voice + Lua LLM switcher (resources/commands/llm_switch/, 3 commands) - "переключись на локальный" / "перейди на оллама" → swap to Ollama - "переключись на облако" / "используй грок" → swap to Groq - "какой у тебя мозг" / "облако или локально" → status query Underlying Lua API (registered globally): jarvis.llm({messages}, opts) -- as before, now uses global client jarvis.llm_status() -> "groq" | "ollama" | "none" jarvis.llm_switch(name) -> name on success, nil on failure Media keys pack (resources/commands/media_keys/, 4 commands) - "пауза" / "плей" → VK_MEDIA_PLAY_PAUSE - "следующий трек" → VK_MEDIA_NEXT_TRACK - "предыдущий трек" → VK_MEDIA_PREV_TRACK - "стоп музыка" → VK_MEDIA_STOP - Helper _media.ps1 uses user32.keybd_event (P/Invoke through Add-Type). - Works with anything that listens to global media keys: Spotify, Yandex Music, YouTube (focused tab), Foobar2000, Winamp, etc. No OAuth, no API keys. Codebase Q&A pack (resources/commands/codebase_qa/, 3 commands) - "укажи проект <path>" → stores path in jarvis.memory under codebase.root - "какой проект сейчас" → speaks current path - "что делает функция X" / "найди в коде Y" / "объясни код" → walks the folder (depth 3, 30 files cap, 4KB per file, 50KB total), filters by source extensions (rs/py/ts/lua/go/...), feeds digest to LLM with a "senior reviewer" system prompt, speaks 3-5 sentence answer. Scheduler cancel-by-text (crates/jarvis-core/src/scheduler.rs) - new pub fn find_by_text(query, limit) -> Vec<ScheduledTask> - new pub fn remove_by_text(query) -> usize (count removed) - new pure helper find_by_text_in(tasks, query, limit) for tests - Lua: jarvis.scheduler.{find_by_text, remove_by_text} - Voice: "отмени напоминание про воду" / "удали задачу про разминку" - 3 new unit tests (52 total in jarvis-core). TTS pre-warm (crates/jarvis-app/src/main.rs) - Call jarvis_core::tts::backend() once on startup so the first speak() doesn't pay Piper binary discovery + voice loading cost. Cuts first-speak latency by ~150-300ms depending on backend. Build: cargo build --release -p jarvis-app -p jarvis-gui both green. Tests: 52/52 jarvis-core unit tests pass.
2026-05-15 16:15:59 +03:00
use once_cell::sync::Lazy;
use parking_lot::RwLock;
use std::sync::Arc;
feat: persist LLM/TTS backend choice + reset/repeat context + quick-search + diagnostics Closes the UX hole I created in 5c72450: voice-swap to Ollama used to vanish after restart. Plus P0.3 (long-standing roadmap item) and two new packs. Persistent backend choice (crates/jarvis-core/src/db/structs.rs) - Settings struct gains llm_backend + tts_backend fields (both String, "" / "auto" = follow env/auto-detect). - set("llm_backend", "groq"|"ollama"|"auto") validates input. - llm::init_global() reads DB first, then JARVIS_LLM env, then auto-detect. - llm::swap_to() now persists the choice via db::save_settings. - Voice swap "переключись на локальный" now survives restart. Shared conversation history (P0.3, crates/jarvis-core/src/llm/mod.rs) - HISTORY: Lazy<RwLock<Option<ConversationHistory>>> singleton. - Helpers: init_history, history_push_user, history_push_assistant, history_snapshot, history_clear, history_pop_last_user, history_last_assistant. - llm_fallback migrated off its own Mutex<History> — now reads/writes shared. - ConversationHistory gains last_assistant() method. New Lua APIs - jarvis.llm_reset() → clear conversation turns (keeps system prompt). - jarvis.llm_last_reply() → string or nil (last assistant message text). - jarvis.health() → debug table {tts_backend, llm_backend, llm_model, active_profile, memory_facts, scheduled_tasks, language, voice, microphone, vosk_model, noise_suppression}. No secrets included. New voice packs - resources/commands/llm_context/ (P0.3) * "сбрось контекст" / "забудь разговор" → llm.reset * "повтори последнее" / "повтори ответ" → llm.repeat (uses last_assistant) - resources/commands/quick_search/ (imba P1 item) * "найди в гугле <X>" / "загугли <X>" * Uses DuckDuckGo Instant Answer API (api.duckduckgo.com, no key required). Pulls AbstractText or RelatedTopics into LLM prompt; falls back to pure LLM knowledge if DDG returns nothing useful. Speaks 2-4 sentence answer. - resources/commands/diagnostics/ * "диагностика" / "доложи о себе" / "статус" * Reads jarvis.health() and speaks a one-line summary. Useful when debugging — user can read out their current state for a bug report. Build: cargo build --release -p jarvis-app -p jarvis-gui green. Tests: 52/52 jarvis-core unit tests pass.
2026-05-15 16:25:28 +03:00
// ─── Shared conversation history ───────────────────────────────────────────
//
// Single global history so the LLM fallback chat, the Lua reset/repeat helpers,
// and any future IPC handler all operate on the same buffer. Initialised on
// boot via `init_history(system_prompt, max_turns)`.
static HISTORY: Lazy<RwLock<Option<ConversationHistory>>> = Lazy::new(|| RwLock::new(None));
pub fn init_history(system_prompt: impl Into<String>, max_turns: usize) {
*HISTORY.write() = Some(ConversationHistory::new(system_prompt, max_turns));
}
pub fn history_push_user(content: impl Into<String>) {
if let Some(h) = HISTORY.write().as_mut() {
h.push_user(content);
}
}
pub fn history_push_assistant(content: impl Into<String>) {
if let Some(h) = HISTORY.write().as_mut() {
h.push_assistant(content);
}
}
pub fn history_snapshot() -> Vec<ChatMessage> {
HISTORY.read().as_ref().map(|h| h.snapshot()).unwrap_or_default()
}
pub fn history_clear() {
if let Some(h) = HISTORY.write().as_mut() {
h.clear();
}
}
pub fn history_pop_last_user() {
if let Some(h) = HISTORY.write().as_mut() {
h.pop_last_user();
}
}
/// Return the most recent assistant message text, or None.
pub fn history_last_assistant() -> Option<String> {
HISTORY.read().as_ref()
.and_then(|h| h.last_assistant().map(|m| m.content.clone()))
}
feat: hot-swap LLM backend + media keys + codebase Q&A + scheduler cancel-by-text + TTS pre-warm Single biggest user-facing change: you can now switch local↔cloud LLM by voice without restarting. Plus four new packs and a perf nudge. Shared LLM global (crates/jarvis-core/src/llm/mod.rs) - GLOBAL: Lazy<RwLock<Option<Arc<LlmClient>>>>. Single source of truth. - init_global() / current() / swap_to(LlmBackend) / current_backend_name() / parse_backend(str). - llm_fallback + llm_router migrated: they no longer own a separate LlmClient, they read from the global on each request. Hot-swap is now LIVE — change backend, next chat call uses the new one. - parse_backend accepts both english and russian aliases: "groq"/"cloud"/"облако"/"клауд" → Groq "ollama"/"local"/"локал"/"локальный" → Ollama Voice + Lua LLM switcher (resources/commands/llm_switch/, 3 commands) - "переключись на локальный" / "перейди на оллама" → swap to Ollama - "переключись на облако" / "используй грок" → swap to Groq - "какой у тебя мозг" / "облако или локально" → status query Underlying Lua API (registered globally): jarvis.llm({messages}, opts) -- as before, now uses global client jarvis.llm_status() -> "groq" | "ollama" | "none" jarvis.llm_switch(name) -> name on success, nil on failure Media keys pack (resources/commands/media_keys/, 4 commands) - "пауза" / "плей" → VK_MEDIA_PLAY_PAUSE - "следующий трек" → VK_MEDIA_NEXT_TRACK - "предыдущий трек" → VK_MEDIA_PREV_TRACK - "стоп музыка" → VK_MEDIA_STOP - Helper _media.ps1 uses user32.keybd_event (P/Invoke through Add-Type). - Works with anything that listens to global media keys: Spotify, Yandex Music, YouTube (focused tab), Foobar2000, Winamp, etc. No OAuth, no API keys. Codebase Q&A pack (resources/commands/codebase_qa/, 3 commands) - "укажи проект <path>" → stores path in jarvis.memory under codebase.root - "какой проект сейчас" → speaks current path - "что делает функция X" / "найди в коде Y" / "объясни код" → walks the folder (depth 3, 30 files cap, 4KB per file, 50KB total), filters by source extensions (rs/py/ts/lua/go/...), feeds digest to LLM with a "senior reviewer" system prompt, speaks 3-5 sentence answer. Scheduler cancel-by-text (crates/jarvis-core/src/scheduler.rs) - new pub fn find_by_text(query, limit) -> Vec<ScheduledTask> - new pub fn remove_by_text(query) -> usize (count removed) - new pure helper find_by_text_in(tasks, query, limit) for tests - Lua: jarvis.scheduler.{find_by_text, remove_by_text} - Voice: "отмени напоминание про воду" / "удали задачу про разминку" - 3 new unit tests (52 total in jarvis-core). TTS pre-warm (crates/jarvis-app/src/main.rs) - Call jarvis_core::tts::backend() once on startup so the first speak() doesn't pay Piper binary discovery + voice loading cost. Cuts first-speak latency by ~150-300ms depending on backend. Build: cargo build --release -p jarvis-app -p jarvis-gui both green. Tests: 52/52 jarvis-core unit tests pass.
2026-05-15 16:15:59 +03:00
/// Shared mutable LLM client. Modules read via `current()`; the user can
/// hot-swap backends at runtime via `swap_to(LlmBackend::Ollama)` etc.
///
/// `None` means LLM is disabled (no GROQ_TOKEN and no Ollama reachable, or
/// `init_global()` was never called).
static GLOBAL: Lazy<RwLock<Option<Arc<LlmClient>>>> = Lazy::new(|| RwLock::new(None));
feat: persist LLM/TTS backend choice + reset/repeat context + quick-search + diagnostics Closes the UX hole I created in 5c72450: voice-swap to Ollama used to vanish after restart. Plus P0.3 (long-standing roadmap item) and two new packs. Persistent backend choice (crates/jarvis-core/src/db/structs.rs) - Settings struct gains llm_backend + tts_backend fields (both String, "" / "auto" = follow env/auto-detect). - set("llm_backend", "groq"|"ollama"|"auto") validates input. - llm::init_global() reads DB first, then JARVIS_LLM env, then auto-detect. - llm::swap_to() now persists the choice via db::save_settings. - Voice swap "переключись на локальный" now survives restart. Shared conversation history (P0.3, crates/jarvis-core/src/llm/mod.rs) - HISTORY: Lazy<RwLock<Option<ConversationHistory>>> singleton. - Helpers: init_history, history_push_user, history_push_assistant, history_snapshot, history_clear, history_pop_last_user, history_last_assistant. - llm_fallback migrated off its own Mutex<History> — now reads/writes shared. - ConversationHistory gains last_assistant() method. New Lua APIs - jarvis.llm_reset() → clear conversation turns (keeps system prompt). - jarvis.llm_last_reply() → string or nil (last assistant message text). - jarvis.health() → debug table {tts_backend, llm_backend, llm_model, active_profile, memory_facts, scheduled_tasks, language, voice, microphone, vosk_model, noise_suppression}. No secrets included. New voice packs - resources/commands/llm_context/ (P0.3) * "сбрось контекст" / "забудь разговор" → llm.reset * "повтори последнее" / "повтори ответ" → llm.repeat (uses last_assistant) - resources/commands/quick_search/ (imba P1 item) * "найди в гугле <X>" / "загугли <X>" * Uses DuckDuckGo Instant Answer API (api.duckduckgo.com, no key required). Pulls AbstractText or RelatedTopics into LLM prompt; falls back to pure LLM knowledge if DDG returns nothing useful. Speaks 2-4 sentence answer. - resources/commands/diagnostics/ * "диагностика" / "доложи о себе" / "статус" * Reads jarvis.health() and speaks a one-line summary. Useful when debugging — user can read out their current state for a bug report. Build: cargo build --release -p jarvis-app -p jarvis-gui green. Tests: 52/52 jarvis-core unit tests pass.
2026-05-15 16:25:28 +03:00
/// Initialise the global client. Precedence:
/// 1. Settings DB `llm_backend` field (if non-empty)
/// 2. `JARVIS_LLM` env var
/// 3. Auto-detect (Groq if `GROQ_TOKEN`, else Ollama)
///
feat: hot-swap LLM backend + media keys + codebase Q&A + scheduler cancel-by-text + TTS pre-warm Single biggest user-facing change: you can now switch local↔cloud LLM by voice without restarting. Plus four new packs and a perf nudge. Shared LLM global (crates/jarvis-core/src/llm/mod.rs) - GLOBAL: Lazy<RwLock<Option<Arc<LlmClient>>>>. Single source of truth. - init_global() / current() / swap_to(LlmBackend) / current_backend_name() / parse_backend(str). - llm_fallback + llm_router migrated: they no longer own a separate LlmClient, they read from the global on each request. Hot-swap is now LIVE — change backend, next chat call uses the new one. - parse_backend accepts both english and russian aliases: "groq"/"cloud"/"облако"/"клауд" → Groq "ollama"/"local"/"локал"/"локальный" → Ollama Voice + Lua LLM switcher (resources/commands/llm_switch/, 3 commands) - "переключись на локальный" / "перейди на оллама" → swap to Ollama - "переключись на облако" / "используй грок" → swap to Groq - "какой у тебя мозг" / "облако или локально" → status query Underlying Lua API (registered globally): jarvis.llm({messages}, opts) -- as before, now uses global client jarvis.llm_status() -> "groq" | "ollama" | "none" jarvis.llm_switch(name) -> name on success, nil on failure Media keys pack (resources/commands/media_keys/, 4 commands) - "пауза" / "плей" → VK_MEDIA_PLAY_PAUSE - "следующий трек" → VK_MEDIA_NEXT_TRACK - "предыдущий трек" → VK_MEDIA_PREV_TRACK - "стоп музыка" → VK_MEDIA_STOP - Helper _media.ps1 uses user32.keybd_event (P/Invoke through Add-Type). - Works with anything that listens to global media keys: Spotify, Yandex Music, YouTube (focused tab), Foobar2000, Winamp, etc. No OAuth, no API keys. Codebase Q&A pack (resources/commands/codebase_qa/, 3 commands) - "укажи проект <path>" → stores path in jarvis.memory under codebase.root - "какой проект сейчас" → speaks current path - "что делает функция X" / "найди в коде Y" / "объясни код" → walks the folder (depth 3, 30 files cap, 4KB per file, 50KB total), filters by source extensions (rs/py/ts/lua/go/...), feeds digest to LLM with a "senior reviewer" system prompt, speaks 3-5 sentence answer. Scheduler cancel-by-text (crates/jarvis-core/src/scheduler.rs) - new pub fn find_by_text(query, limit) -> Vec<ScheduledTask> - new pub fn remove_by_text(query) -> usize (count removed) - new pure helper find_by_text_in(tasks, query, limit) for tests - Lua: jarvis.scheduler.{find_by_text, remove_by_text} - Voice: "отмени напоминание про воду" / "удали задачу про разминку" - 3 new unit tests (52 total in jarvis-core). TTS pre-warm (crates/jarvis-app/src/main.rs) - Call jarvis_core::tts::backend() once on startup so the first speak() doesn't pay Piper binary discovery + voice loading cost. Cuts first-speak latency by ~150-300ms depending on backend. Build: cargo build --release -p jarvis-app -p jarvis-gui both green. Tests: 52/52 jarvis-core unit tests pass.
2026-05-15 16:15:59 +03:00
/// Idempotent — replaces any previous global. Returns Ok even when the chosen
/// backend can't be probed: an Ollama server may not be running yet but we
/// stash the client anyway and let calls fail on first request.
pub fn init_global() -> Result<(), ConfigError> {
feat: persist LLM/TTS backend choice + reset/repeat context + quick-search + diagnostics Closes the UX hole I created in 5c72450: voice-swap to Ollama used to vanish after restart. Plus P0.3 (long-standing roadmap item) and two new packs. Persistent backend choice (crates/jarvis-core/src/db/structs.rs) - Settings struct gains llm_backend + tts_backend fields (both String, "" / "auto" = follow env/auto-detect). - set("llm_backend", "groq"|"ollama"|"auto") validates input. - llm::init_global() reads DB first, then JARVIS_LLM env, then auto-detect. - llm::swap_to() now persists the choice via db::save_settings. - Voice swap "переключись на локальный" now survives restart. Shared conversation history (P0.3, crates/jarvis-core/src/llm/mod.rs) - HISTORY: Lazy<RwLock<Option<ConversationHistory>>> singleton. - Helpers: init_history, history_push_user, history_push_assistant, history_snapshot, history_clear, history_pop_last_user, history_last_assistant. - llm_fallback migrated off its own Mutex<History> — now reads/writes shared. - ConversationHistory gains last_assistant() method. New Lua APIs - jarvis.llm_reset() → clear conversation turns (keeps system prompt). - jarvis.llm_last_reply() → string or nil (last assistant message text). - jarvis.health() → debug table {tts_backend, llm_backend, llm_model, active_profile, memory_facts, scheduled_tasks, language, voice, microphone, vosk_model, noise_suppression}. No secrets included. New voice packs - resources/commands/llm_context/ (P0.3) * "сбрось контекст" / "забудь разговор" → llm.reset * "повтори последнее" / "повтори ответ" → llm.repeat (uses last_assistant) - resources/commands/quick_search/ (imba P1 item) * "найди в гугле <X>" / "загугли <X>" * Uses DuckDuckGo Instant Answer API (api.duckduckgo.com, no key required). Pulls AbstractText or RelatedTopics into LLM prompt; falls back to pure LLM knowledge if DDG returns nothing useful. Speaks 2-4 sentence answer. - resources/commands/diagnostics/ * "диагностика" / "доложи о себе" / "статус" * Reads jarvis.health() and speaks a one-line summary. Useful when debugging — user can read out their current state for a bug report. Build: cargo build --release -p jarvis-app -p jarvis-gui green. Tests: 52/52 jarvis-core unit tests pass.
2026-05-15 16:25:28 +03:00
// Try DB-persisted choice first.
let persisted = crate::DB.get().and_then(|db| {
let s = db.read();
let backend = s.llm_backend.trim().to_string();
if backend.is_empty() { None } else { parse_backend(&backend) }
});
let c = match persisted {
Some(LlmBackend::Groq) => LlmClient::groq()?,
Some(LlmBackend::Ollama) => LlmClient::ollama(),
None => LlmClient::from_env()?,
};
feat: hot-swap LLM backend + media keys + codebase Q&A + scheduler cancel-by-text + TTS pre-warm Single biggest user-facing change: you can now switch local↔cloud LLM by voice without restarting. Plus four new packs and a perf nudge. Shared LLM global (crates/jarvis-core/src/llm/mod.rs) - GLOBAL: Lazy<RwLock<Option<Arc<LlmClient>>>>. Single source of truth. - init_global() / current() / swap_to(LlmBackend) / current_backend_name() / parse_backend(str). - llm_fallback + llm_router migrated: they no longer own a separate LlmClient, they read from the global on each request. Hot-swap is now LIVE — change backend, next chat call uses the new one. - parse_backend accepts both english and russian aliases: "groq"/"cloud"/"облако"/"клауд" → Groq "ollama"/"local"/"локал"/"локальный" → Ollama Voice + Lua LLM switcher (resources/commands/llm_switch/, 3 commands) - "переключись на локальный" / "перейди на оллама" → swap to Ollama - "переключись на облако" / "используй грок" → swap to Groq - "какой у тебя мозг" / "облако или локально" → status query Underlying Lua API (registered globally): jarvis.llm({messages}, opts) -- as before, now uses global client jarvis.llm_status() -> "groq" | "ollama" | "none" jarvis.llm_switch(name) -> name on success, nil on failure Media keys pack (resources/commands/media_keys/, 4 commands) - "пауза" / "плей" → VK_MEDIA_PLAY_PAUSE - "следующий трек" → VK_MEDIA_NEXT_TRACK - "предыдущий трек" → VK_MEDIA_PREV_TRACK - "стоп музыка" → VK_MEDIA_STOP - Helper _media.ps1 uses user32.keybd_event (P/Invoke through Add-Type). - Works with anything that listens to global media keys: Spotify, Yandex Music, YouTube (focused tab), Foobar2000, Winamp, etc. No OAuth, no API keys. Codebase Q&A pack (resources/commands/codebase_qa/, 3 commands) - "укажи проект <path>" → stores path in jarvis.memory under codebase.root - "какой проект сейчас" → speaks current path - "что делает функция X" / "найди в коде Y" / "объясни код" → walks the folder (depth 3, 30 files cap, 4KB per file, 50KB total), filters by source extensions (rs/py/ts/lua/go/...), feeds digest to LLM with a "senior reviewer" system prompt, speaks 3-5 sentence answer. Scheduler cancel-by-text (crates/jarvis-core/src/scheduler.rs) - new pub fn find_by_text(query, limit) -> Vec<ScheduledTask> - new pub fn remove_by_text(query) -> usize (count removed) - new pure helper find_by_text_in(tasks, query, limit) for tests - Lua: jarvis.scheduler.{find_by_text, remove_by_text} - Voice: "отмени напоминание про воду" / "удали задачу про разминку" - 3 new unit tests (52 total in jarvis-core). TTS pre-warm (crates/jarvis-app/src/main.rs) - Call jarvis_core::tts::backend() once on startup so the first speak() doesn't pay Piper binary discovery + voice loading cost. Cuts first-speak latency by ~150-300ms depending on backend. Build: cargo build --release -p jarvis-app -p jarvis-gui both green. Tests: 52/52 jarvis-core unit tests pass.
2026-05-15 16:15:59 +03:00
log::info!("LLM global initialised: backend={}, model={}", c.backend().name(), c.model());
*GLOBAL.write() = Some(Arc::new(c));
Ok(())
}
/// Return a clone of the active client. Cheap (Arc).
pub fn current() -> Option<Arc<LlmClient>> {
GLOBAL.read().clone()
}
/// Name of the currently active backend, or "none" if not initialised.
pub fn current_backend_name() -> &'static str {
match GLOBAL.read().as_ref().map(|c| c.backend()) {
Some(LlmBackend::Groq) => "groq",
Some(LlmBackend::Ollama) => "ollama",
None => "none",
}
}
/// Hot-swap to a different backend. Returns the new backend's name on success.
feat: persist LLM/TTS backend choice + reset/repeat context + quick-search + diagnostics Closes the UX hole I created in 5c72450: voice-swap to Ollama used to vanish after restart. Plus P0.3 (long-standing roadmap item) and two new packs. Persistent backend choice (crates/jarvis-core/src/db/structs.rs) - Settings struct gains llm_backend + tts_backend fields (both String, "" / "auto" = follow env/auto-detect). - set("llm_backend", "groq"|"ollama"|"auto") validates input. - llm::init_global() reads DB first, then JARVIS_LLM env, then auto-detect. - llm::swap_to() now persists the choice via db::save_settings. - Voice swap "переключись на локальный" now survives restart. Shared conversation history (P0.3, crates/jarvis-core/src/llm/mod.rs) - HISTORY: Lazy<RwLock<Option<ConversationHistory>>> singleton. - Helpers: init_history, history_push_user, history_push_assistant, history_snapshot, history_clear, history_pop_last_user, history_last_assistant. - llm_fallback migrated off its own Mutex<History> — now reads/writes shared. - ConversationHistory gains last_assistant() method. New Lua APIs - jarvis.llm_reset() → clear conversation turns (keeps system prompt). - jarvis.llm_last_reply() → string or nil (last assistant message text). - jarvis.health() → debug table {tts_backend, llm_backend, llm_model, active_profile, memory_facts, scheduled_tasks, language, voice, microphone, vosk_model, noise_suppression}. No secrets included. New voice packs - resources/commands/llm_context/ (P0.3) * "сбрось контекст" / "забудь разговор" → llm.reset * "повтори последнее" / "повтори ответ" → llm.repeat (uses last_assistant) - resources/commands/quick_search/ (imba P1 item) * "найди в гугле <X>" / "загугли <X>" * Uses DuckDuckGo Instant Answer API (api.duckduckgo.com, no key required). Pulls AbstractText or RelatedTopics into LLM prompt; falls back to pure LLM knowledge if DDG returns nothing useful. Speaks 2-4 sentence answer. - resources/commands/diagnostics/ * "диагностика" / "доложи о себе" / "статус" * Reads jarvis.health() and speaks a one-line summary. Useful when debugging — user can read out their current state for a bug report. Build: cargo build --release -p jarvis-app -p jarvis-gui green. Tests: 52/52 jarvis-core unit tests pass.
2026-05-15 16:25:28 +03:00
/// Persists the choice to the settings DB so it survives restart.
feat: hot-swap LLM backend + media keys + codebase Q&A + scheduler cancel-by-text + TTS pre-warm Single biggest user-facing change: you can now switch local↔cloud LLM by voice without restarting. Plus four new packs and a perf nudge. Shared LLM global (crates/jarvis-core/src/llm/mod.rs) - GLOBAL: Lazy<RwLock<Option<Arc<LlmClient>>>>. Single source of truth. - init_global() / current() / swap_to(LlmBackend) / current_backend_name() / parse_backend(str). - llm_fallback + llm_router migrated: they no longer own a separate LlmClient, they read from the global on each request. Hot-swap is now LIVE — change backend, next chat call uses the new one. - parse_backend accepts both english and russian aliases: "groq"/"cloud"/"облако"/"клауд" → Groq "ollama"/"local"/"локал"/"локальный" → Ollama Voice + Lua LLM switcher (resources/commands/llm_switch/, 3 commands) - "переключись на локальный" / "перейди на оллама" → swap to Ollama - "переключись на облако" / "используй грок" → swap to Groq - "какой у тебя мозг" / "облако или локально" → status query Underlying Lua API (registered globally): jarvis.llm({messages}, opts) -- as before, now uses global client jarvis.llm_status() -> "groq" | "ollama" | "none" jarvis.llm_switch(name) -> name on success, nil on failure Media keys pack (resources/commands/media_keys/, 4 commands) - "пауза" / "плей" → VK_MEDIA_PLAY_PAUSE - "следующий трек" → VK_MEDIA_NEXT_TRACK - "предыдущий трек" → VK_MEDIA_PREV_TRACK - "стоп музыка" → VK_MEDIA_STOP - Helper _media.ps1 uses user32.keybd_event (P/Invoke through Add-Type). - Works with anything that listens to global media keys: Spotify, Yandex Music, YouTube (focused tab), Foobar2000, Winamp, etc. No OAuth, no API keys. Codebase Q&A pack (resources/commands/codebase_qa/, 3 commands) - "укажи проект <path>" → stores path in jarvis.memory under codebase.root - "какой проект сейчас" → speaks current path - "что делает функция X" / "найди в коде Y" / "объясни код" → walks the folder (depth 3, 30 files cap, 4KB per file, 50KB total), filters by source extensions (rs/py/ts/lua/go/...), feeds digest to LLM with a "senior reviewer" system prompt, speaks 3-5 sentence answer. Scheduler cancel-by-text (crates/jarvis-core/src/scheduler.rs) - new pub fn find_by_text(query, limit) -> Vec<ScheduledTask> - new pub fn remove_by_text(query) -> usize (count removed) - new pure helper find_by_text_in(tasks, query, limit) for tests - Lua: jarvis.scheduler.{find_by_text, remove_by_text} - Voice: "отмени напоминание про воду" / "удали задачу про разминку" - 3 new unit tests (52 total in jarvis-core). TTS pre-warm (crates/jarvis-app/src/main.rs) - Call jarvis_core::tts::backend() once on startup so the first speak() doesn't pay Piper binary discovery + voice loading cost. Cuts first-speak latency by ~150-300ms depending on backend. Build: cargo build --release -p jarvis-app -p jarvis-gui both green. Tests: 52/52 jarvis-core unit tests pass.
2026-05-15 16:15:59 +03:00
pub fn swap_to(backend: LlmBackend) -> Result<&'static str, ConfigError> {
let c = match backend {
LlmBackend::Groq => LlmClient::groq()?,
LlmBackend::Ollama => LlmClient::ollama(),
};
let name = c.backend().name();
log::info!("LLM swapped → backend={}, model={}", name, c.model());
*GLOBAL.write() = Some(Arc::new(c));
feat: persist LLM/TTS backend choice + reset/repeat context + quick-search + diagnostics Closes the UX hole I created in 5c72450: voice-swap to Ollama used to vanish after restart. Plus P0.3 (long-standing roadmap item) and two new packs. Persistent backend choice (crates/jarvis-core/src/db/structs.rs) - Settings struct gains llm_backend + tts_backend fields (both String, "" / "auto" = follow env/auto-detect). - set("llm_backend", "groq"|"ollama"|"auto") validates input. - llm::init_global() reads DB first, then JARVIS_LLM env, then auto-detect. - llm::swap_to() now persists the choice via db::save_settings. - Voice swap "переключись на локальный" now survives restart. Shared conversation history (P0.3, crates/jarvis-core/src/llm/mod.rs) - HISTORY: Lazy<RwLock<Option<ConversationHistory>>> singleton. - Helpers: init_history, history_push_user, history_push_assistant, history_snapshot, history_clear, history_pop_last_user, history_last_assistant. - llm_fallback migrated off its own Mutex<History> — now reads/writes shared. - ConversationHistory gains last_assistant() method. New Lua APIs - jarvis.llm_reset() → clear conversation turns (keeps system prompt). - jarvis.llm_last_reply() → string or nil (last assistant message text). - jarvis.health() → debug table {tts_backend, llm_backend, llm_model, active_profile, memory_facts, scheduled_tasks, language, voice, microphone, vosk_model, noise_suppression}. No secrets included. New voice packs - resources/commands/llm_context/ (P0.3) * "сбрось контекст" / "забудь разговор" → llm.reset * "повтори последнее" / "повтори ответ" → llm.repeat (uses last_assistant) - resources/commands/quick_search/ (imba P1 item) * "найди в гугле <X>" / "загугли <X>" * Uses DuckDuckGo Instant Answer API (api.duckduckgo.com, no key required). Pulls AbstractText or RelatedTopics into LLM prompt; falls back to pure LLM knowledge if DDG returns nothing useful. Speaks 2-4 sentence answer. - resources/commands/diagnostics/ * "диагностика" / "доложи о себе" / "статус" * Reads jarvis.health() and speaks a one-line summary. Useful when debugging — user can read out their current state for a bug report. Build: cargo build --release -p jarvis-app -p jarvis-gui green. Tests: 52/52 jarvis-core unit tests pass.
2026-05-15 16:25:28 +03:00
// Persist to settings DB (best-effort — log on failure, don't propagate).
if let Some(db) = crate::DB.get() {
let snapshot = {
let mut s = db.write();
s.llm_backend = name.to_string();
s.clone()
};
if let Err(e) = crate::db::save_settings(&snapshot) {
log::warn!("LLM swap: failed to persist to settings DB: {}", e);
} else {
log::info!("LLM choice persisted: {}", name);
}
}
feat: hot-swap LLM backend + media keys + codebase Q&A + scheduler cancel-by-text + TTS pre-warm Single biggest user-facing change: you can now switch local↔cloud LLM by voice without restarting. Plus four new packs and a perf nudge. Shared LLM global (crates/jarvis-core/src/llm/mod.rs) - GLOBAL: Lazy<RwLock<Option<Arc<LlmClient>>>>. Single source of truth. - init_global() / current() / swap_to(LlmBackend) / current_backend_name() / parse_backend(str). - llm_fallback + llm_router migrated: they no longer own a separate LlmClient, they read from the global on each request. Hot-swap is now LIVE — change backend, next chat call uses the new one. - parse_backend accepts both english and russian aliases: "groq"/"cloud"/"облако"/"клауд" → Groq "ollama"/"local"/"локал"/"локальный" → Ollama Voice + Lua LLM switcher (resources/commands/llm_switch/, 3 commands) - "переключись на локальный" / "перейди на оллама" → swap to Ollama - "переключись на облако" / "используй грок" → swap to Groq - "какой у тебя мозг" / "облако или локально" → status query Underlying Lua API (registered globally): jarvis.llm({messages}, opts) -- as before, now uses global client jarvis.llm_status() -> "groq" | "ollama" | "none" jarvis.llm_switch(name) -> name on success, nil on failure Media keys pack (resources/commands/media_keys/, 4 commands) - "пауза" / "плей" → VK_MEDIA_PLAY_PAUSE - "следующий трек" → VK_MEDIA_NEXT_TRACK - "предыдущий трек" → VK_MEDIA_PREV_TRACK - "стоп музыка" → VK_MEDIA_STOP - Helper _media.ps1 uses user32.keybd_event (P/Invoke through Add-Type). - Works with anything that listens to global media keys: Spotify, Yandex Music, YouTube (focused tab), Foobar2000, Winamp, etc. No OAuth, no API keys. Codebase Q&A pack (resources/commands/codebase_qa/, 3 commands) - "укажи проект <path>" → stores path in jarvis.memory under codebase.root - "какой проект сейчас" → speaks current path - "что делает функция X" / "найди в коде Y" / "объясни код" → walks the folder (depth 3, 30 files cap, 4KB per file, 50KB total), filters by source extensions (rs/py/ts/lua/go/...), feeds digest to LLM with a "senior reviewer" system prompt, speaks 3-5 sentence answer. Scheduler cancel-by-text (crates/jarvis-core/src/scheduler.rs) - new pub fn find_by_text(query, limit) -> Vec<ScheduledTask> - new pub fn remove_by_text(query) -> usize (count removed) - new pure helper find_by_text_in(tasks, query, limit) for tests - Lua: jarvis.scheduler.{find_by_text, remove_by_text} - Voice: "отмени напоминание про воду" / "удали задачу про разминку" - 3 new unit tests (52 total in jarvis-core). TTS pre-warm (crates/jarvis-app/src/main.rs) - Call jarvis_core::tts::backend() once on startup so the first speak() doesn't pay Piper binary discovery + voice loading cost. Cuts first-speak latency by ~150-300ms depending on backend. Build: cargo build --release -p jarvis-app -p jarvis-gui both green. Tests: 52/52 jarvis-core unit tests pass.
2026-05-15 16:15:59 +03:00
Ok(name)
}
/// Parse a backend name (case-insensitive) into the enum.
pub fn parse_backend(name: &str) -> Option<LlmBackend> {
match name.trim().to_lowercase().as_str() {
"groq" | "cloud" | "облако" | "клауд" => Some(LlmBackend::Groq),
"ollama" | "local" | "локал" | "локальн" | "локальный" => Some(LlmBackend::Ollama),
_ => None,
}
}