CI / test (push) Has been cancelled
First run and backend - The companion opens without Ollama or a model (OFFLINE / SETUP REQUIRED), opens Settings > Language model and picks the model up once downloaded. - Model, provider and GPU changes apply without restarting (Ollama is restarted when launch settings change); no silent fallback from API mode. - Fatal startup errors are shown in a window; the fallback avatar loads again; the shipped Capri artwork is used when nothing was imported. Packaging and tooling - packaging/arch/PKGBUILD, capri.desktop (KWin ScreenShot2 key), icons, artwork under /usr/share/capri/assets, Gitea Actions CI. - xtask: `icons` and `release-check` (no private data or credentials). Runtime - One instance per data folder (flock + control socket): second launch shows the window; capri stop / restart / toggle / status (JSON, starts nothing) / doctor / setup / diagnostics export / purge. - A foreign program on the Ollama port is refused; an Ollama left behind by Capri is replaced. Privacy and security - No raw Ollama log on disk; API keys are never saved in plaintext (old ones move to the keyring); refused credential notes are stored as [Credentials omitted]; launched apps get an allow-listed environment. Fixes - Stop/Escape silence the voice; saved voice effects apply to replies; settings_control glitch settings apply; distinct KWin cursor scripts; KDE window capture authorized for source builds; Linux wording. - Voice pack references zipped with Windows separators are found. Wired features - Initiatives, request router, resource monitor, "clip that", questions about a snapshot, sleep mode, tap reactions, stopwatch, attachments, Internet mode button, voice-synced subtitles, wake visuals, dictation draft, tray switches, Spotify seek/shuffle/repeat; computer-control planner and classifier follow model switches and API mode. - Approval cards: one shown, 8 queued, deduplicated, cancelled on stop, failure, lock or pause; one Application access switch. Desktop - Compositor detection (no black overlay on i3 without picom), i3lock detection, unsupported desktops reported at startup, screenshot-only control without AT-SPI, fontconfig fallbacks, translatable feature pages with French translations. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1202 lines
58 KiB
Rust
1202 lines
58 KiB
Rust
//! Turn lifecycle: routing, tool loop, output pipeline.
|
||
use std::future::Future;
|
||
use std::pin::Pin;
|
||
use std::sync::atomic::{AtomicBool, Ordering};
|
||
use std::sync::Arc;
|
||
use std::time::Duration;
|
||
|
||
use anyhow::Result;
|
||
use capri_core::avatar::Catalog;
|
||
use capri_core::{utf16_len, Paths, Settings};
|
||
use capri_llm::{ChatRequest, LlmBackend, LlmError, Message, Options};
|
||
use parking_lot::Mutex;
|
||
use tokio_util::sync::CancellationToken;
|
||
|
||
use crate::journal::{AvatarRef, Journal, JournalMessage};
|
||
use crate::prompt::{self, PromptMode};
|
||
use crate::route::{conversation_only, ToolProgressGuard};
|
||
use crate::tools::{Approvals, DenyAll, StateProvider, Tool, ToolContext};
|
||
use crate::session::Session;
|
||
use crate::stream::{AvatarEvent, AvatarStreamParser, PlainTextStream, VisibleAnswerStream};
|
||
|
||
pub const MAX_INPUT: usize = 8000;
|
||
const MAX_OUTPUT: usize = 65536;
|
||
const SESSION_KEY: &str = "agent:capri:main";
|
||
/// Defensive cap on model calls per turn (Capri relied on its deadlines only).
|
||
const MAX_MODEL_CALLS: usize = 16;
|
||
/// Tool results larger than this are cut before reaching the model.
|
||
const MAX_TOOL_RESULT: usize = 20_000;
|
||
const SETTLED_TOOLS_INSTRUCTION: &str = "The requested tools have finished. Give the owner your final answer now, based only on the tool results above. Do not call another tool and do not repeat any completed action.";
|
||
const SETTLED_TOOLS_FALLBACK: &str = "The tool run finished, but no final summary was produced. I did not repeat any completed actions.";
|
||
|
||
/// Answers a turn without the model (explicit owner notes). `Some(reply)` ends the turn.
|
||
pub type FastPath = Arc<dyn Fn(&str) -> Option<String> + Send + Sync>;
|
||
/// Request router: `(text, up to 2 previous owner messages)` → `true` for plain small talk,
|
||
/// answered with dialogue-only instructions and no action tools (spec 02 INF-66).
|
||
pub type Classifier = Arc<dyn Fn(String, Vec<String>) -> Pin<Box<dyn Future<Output = bool> + Send>> + Send + Sync>;
|
||
/// `true` when the owner input must be stored as [`CREDENTIALS_OMITTED`].
|
||
pub type InputRedactor = Arc<dyn Fn(&str) -> bool + Send + Sync>;
|
||
/// Visible-history text of an input that carried credentials.
|
||
pub const CREDENTIALS_OMITTED: &str = "[Credentials omitted]";
|
||
/// Summarizes `messages` (oldest first) given the previous summary. Must call the model
|
||
/// without tools and fall back to an extractive summary itself.
|
||
pub type Compactor = Arc<dyn Fn(Vec<Message>, Option<String>) -> Pin<Box<dyn Future<Output = Result<String>> + Send>> + Send + Sync>;
|
||
/// Sees every turn event, whoever submitted the turn (voice, UI, terminal).
|
||
pub type Observer = Arc<dyn Fn(&TurnEvent) + Send + Sync>;
|
||
/// Called after each committed turn with (stored messages, stored bytes), e.g. for memory indexing.
|
||
pub type TurnHook = Arc<dyn Fn(usize, usize) + Send + Sync>;
|
||
|
||
/// Extra context appended to the model's copy of the user message (memory excerpts, web results...).
|
||
/// Receives the owner's text; returns an already formatted block (or an empty string).
|
||
pub type ContextHook = Arc<dyn Fn(String) -> Pin<Box<dyn Future<Output = String> + Send>> + Send + Sync>;
|
||
/// Async pre-model route (e.g. host-run computer tasks): receives (owner text, turn id,
|
||
/// turn cancellation). `Some(reply)` answers the turn without the model; the reply is stored as
|
||
/// the assistant message of the turn.
|
||
pub type Router = Arc<dyn Fn(String, String, CancellationToken) -> Pin<Box<dyn Future<Output = Option<String>> + Send>> + Send + Sync>;
|
||
/// One executed tool call of a turn: (tool name, arguments, result).
|
||
pub type ToolCallRecord = (String, serde_json::Value, serde_json::Value);
|
||
/// After a model reply: (visible reply, executed tool calls) → text appended to the
|
||
/// reply (receipts, or a correction when the reply claims an action no tool performed).
|
||
pub type ReplyGuard = Arc<dyn Fn(&str, &[ToolCallRecord]) -> Option<String> + Send + Sync>;
|
||
|
||
#[derive(Clone, Debug, PartialEq)]
|
||
pub enum TurnEvent {
|
||
Started { turn_id: String, text: String },
|
||
Delta { turn_id: String, text: String },
|
||
Avatar { turn_id: String, id: String, follow_up: bool },
|
||
/// A model tool call started (`ok == None`) or finished.
|
||
Tool { turn_id: String, name: String, ok: Option<bool> },
|
||
Completed { turn_id: String, text: String },
|
||
Failed { turn_id: String, message: String, code: String },
|
||
Cancelled { turn_id: String },
|
||
}
|
||
|
||
#[derive(Clone, Copy, Debug)]
|
||
pub struct Deadlines {
|
||
pub turn: Duration,
|
||
pub first_text: Duration,
|
||
pub load: Duration,
|
||
}
|
||
|
||
impl Deadlines {
|
||
/// Capri `responsiveness.mjs`: slow = total RAM <= 17 GiB or CPU-only inference.
|
||
pub fn for_machine(settings: &Settings) -> Self {
|
||
let slow = settings.acceleration == "cpu" || total_memory_bytes().is_some_and(|b| b <= 17 << 30);
|
||
Self {
|
||
turn: Duration::from_secs(if slow { 300 } else { 180 }),
|
||
first_text: Duration::from_secs(if slow { 120 } else { 30 }),
|
||
load: Duration::from_secs(180),
|
||
}
|
||
}
|
||
}
|
||
|
||
fn total_memory_bytes() -> Option<u64> {
|
||
let text = std::fs::read_to_string("/proc/meminfo").ok()?;
|
||
let kib: u64 = text.lines().find(|l| l.starts_with("MemTotal:"))?.split_whitespace().nth(1)?.parse().ok()?;
|
||
Some(kib * 1024)
|
||
}
|
||
|
||
pub struct Engine {
|
||
paths: Paths,
|
||
settings: Mutex<Settings>,
|
||
backend: Mutex<LlmBackend>,
|
||
model: Mutex<String>,
|
||
capabilities: Mutex<Vec<String>>,
|
||
/// The local model's own capabilities, kept while an API is active.
|
||
local_caps: Mutex<Vec<String>>,
|
||
catalog: Arc<Catalog>,
|
||
session: Mutex<Session>,
|
||
journal: Mutex<Journal>,
|
||
active: Mutex<Option<CancellationToken>>,
|
||
tools: Mutex<Vec<Arc<dyn Tool>>>,
|
||
approvals: Mutex<Arc<dyn Approvals>>,
|
||
state: Mutex<Vec<StateProvider>>,
|
||
context: Mutex<Vec<ContextHook>>,
|
||
internet: AtomicBool,
|
||
fast_path: Mutex<Option<FastPath>>,
|
||
redact_input: Mutex<Option<InputRedactor>>,
|
||
classifier: Mutex<Option<Classifier>>,
|
||
/// Base64 images for the next owner message (attachments), consumed by it.
|
||
pending_images: Mutex<Vec<String>>,
|
||
/// Context text for the next owner message (what an attached snapshot shows), consumed by it.
|
||
pending_note: Mutex<String>,
|
||
/// Pre-model routes, tried in order; the first answer wins (clip command, computer tasks…).
|
||
routers: Mutex<Vec<Router>>,
|
||
reply_guard: Mutex<Option<ReplyGuard>>,
|
||
compactor: Mutex<Option<Compactor>>,
|
||
after_turn: Mutex<Option<TurnHook>>,
|
||
observers: Mutex<Vec<Observer>>,
|
||
pub deadlines: Deadlines,
|
||
}
|
||
|
||
fn now() -> String {
|
||
chrono::Utc::now().format("%Y-%m-%dT%H:%M:%S%.3fZ").to_string()
|
||
}
|
||
|
||
fn public_message(error: &TurnError) -> &'static str {
|
||
match error {
|
||
TurnError::Timeout => "Capri took too long to respond. You can try again.",
|
||
TurnError::Empty => "The response could not be completed. Check the local core or reconnect.",
|
||
TurnError::ToolLoop => "The action could not be completed after repeated attempts. Check Application access or try a larger language model.",
|
||
TurnError::ModelLoad => "The local model could not load. Free some memory or choose a smaller Qwen model, then try again.",
|
||
TurnError::ModelMissing => "No language model is installed yet. Download one in Settings › Language model, then try again.",
|
||
TurnError::Offline => "The local core is not running. Install Ollama (pacman -S ollama) or check Settings › Language model, then try again.",
|
||
TurnError::Llm(LlmError::Http { status: 401 | 403, .. }) => "The local core rejected authentication. Check its configuration.",
|
||
TurnError::Llm(LlmError::Http { status: 409 | 429, .. }) => "The local core is busy. Please wait and try again.",
|
||
TurnError::Llm(LlmError::Http { status: 500..=599, .. }) => "The local model could not finish this response. Please try again.",
|
||
TurnError::Llm(_) | TurnError::Internal(_) => "The response could not be completed. Check the local core or reconnect.",
|
||
}
|
||
}
|
||
|
||
#[derive(Debug)]
|
||
enum TurnError {
|
||
Timeout,
|
||
Empty,
|
||
ModelLoad,
|
||
ModelMissing,
|
||
Offline,
|
||
ToolLoop,
|
||
Llm(LlmError),
|
||
Internal(#[allow(dead_code, reason = "read through Debug in the failure log")] anyhow::Error),
|
||
}
|
||
|
||
impl TurnError {
|
||
fn code(&self) -> &'static str {
|
||
match self {
|
||
Self::Timeout => "CAPRI_TIMEOUT",
|
||
Self::Empty => "CAPRI_LLM_RESPONSE_EMPTY",
|
||
Self::ModelLoad | Self::ModelMissing => "CAPRI_MODEL_NOT_READY",
|
||
Self::Offline => "CAPRI_LLM_NETWORK_ERROR",
|
||
Self::ToolLoop => "CAPRI_TOOL_LOOP",
|
||
Self::Llm(e) => e.code(),
|
||
Self::Internal(_) => "CAPRI_INTERNAL",
|
||
}
|
||
}
|
||
}
|
||
|
||
/// Text pipeline state for one reply.
|
||
struct Output {
|
||
visible: VisibleAnswerStream,
|
||
avatar: AvatarStreamParser,
|
||
plain: PlainTextStream,
|
||
text: String,
|
||
avatar_id: Option<(String, bool)>,
|
||
}
|
||
|
||
impl Output {
|
||
fn new(catalog: &Catalog) -> Self {
|
||
let sprites = catalog.model_sprites.iter().map(|s| {
|
||
let alias = catalog.frame(&s.frame_id).filter(|_| s.animation.is_none()).map(|f| format!("{}/{}", f.pose, f.expression));
|
||
(s.id.clone(), alias)
|
||
});
|
||
Self {
|
||
visible: VisibleAnswerStream::default(),
|
||
avatar: AvatarStreamParser::new(sprites),
|
||
plain: PlainTextStream::default(),
|
||
text: String::new(),
|
||
avatar_id: None,
|
||
}
|
||
}
|
||
|
||
/// Returns (new visible text, newly selected avatar).
|
||
fn push(&mut self, delta: &str, last: bool) -> (String, Option<(String, bool)>) {
|
||
let visible = self.visible.push(delta, last);
|
||
let mut events = self.avatar.push(&visible);
|
||
if last {
|
||
events.extend(self.avatar.finish());
|
||
}
|
||
let mut out = String::new();
|
||
let mut chosen = None;
|
||
for event in events {
|
||
match event {
|
||
AvatarEvent::Text(t) => out.push_str(&self.plain.push(&t, false)),
|
||
AvatarEvent::Avatar { id, follow_up } => {
|
||
chosen = Some((id.clone(), follow_up));
|
||
self.avatar_id = Some((id, follow_up));
|
||
}
|
||
}
|
||
}
|
||
if last {
|
||
out.push_str(&self.plain.push("", true));
|
||
}
|
||
if self.text.trim().is_empty() {
|
||
out = out.trim_start().to_string();
|
||
}
|
||
self.text.push_str(&out);
|
||
(out, chosen)
|
||
}
|
||
}
|
||
|
||
impl Engine {
|
||
/// `backend`: an `Ollama` client or any [`LlmBackend`]; `capabilities` of the local model.
|
||
pub fn new(paths: Paths, settings: Settings, backend: impl Into<LlmBackend>, model: String, capabilities: &[String], catalog: Arc<Catalog>) -> Result<Self> {
|
||
paths.ensure()?;
|
||
let session = Session::open(&paths.agent_db(), SESSION_KEY)?;
|
||
let journal = Journal::open(paths.state().join("transcript.json"));
|
||
Ok(Self {
|
||
deadlines: Deadlines::for_machine(&settings),
|
||
paths,
|
||
settings: Mutex::new(settings),
|
||
backend: Mutex::new(backend.into()),
|
||
model: Mutex::new(model),
|
||
capabilities: Mutex::new(capabilities.to_vec()),
|
||
local_caps: Mutex::new(capabilities.to_vec()),
|
||
catalog,
|
||
session: Mutex::new(session),
|
||
journal: Mutex::new(journal),
|
||
active: Mutex::new(None),
|
||
tools: Mutex::new(vec![]),
|
||
approvals: Mutex::new(Arc::new(DenyAll)),
|
||
state: Mutex::new(vec![]),
|
||
context: Mutex::new(vec![]),
|
||
internet: AtomicBool::new(false),
|
||
fast_path: Mutex::new(None),
|
||
redact_input: Mutex::new(None),
|
||
classifier: Mutex::new(None),
|
||
pending_images: Mutex::new(vec![]),
|
||
pending_note: Mutex::new(String::new()),
|
||
routers: Mutex::new(vec![]),
|
||
reply_guard: Mutex::new(None),
|
||
compactor: Mutex::new(None),
|
||
after_turn: Mutex::new(None),
|
||
observers: Mutex::new(vec![]),
|
||
})
|
||
}
|
||
|
||
/// Tools offered to the model (each still decides through `Tool::available`).
|
||
pub fn set_tools(&self, tools: Vec<Arc<dyn Tool>>) {
|
||
*self.tools.lock() = tools;
|
||
}
|
||
|
||
pub fn set_approvals(&self, approvals: Arc<dyn Approvals>) {
|
||
*self.approvals.lock() = approvals;
|
||
}
|
||
|
||
/// Adds live values to the `DESKTOP STATE FOR THIS TURN` envelope.
|
||
pub fn add_state(&self, provider: StateProvider) {
|
||
self.state.lock().push(provider);
|
||
}
|
||
|
||
/// Adds a context block (memory excerpts, screen description, web results) to every turn.
|
||
pub fn add_context(&self, hook: ContextHook) {
|
||
self.context.lock().push(hook);
|
||
}
|
||
|
||
pub fn set_fast_path(&self, hook: FastPath) {
|
||
*self.fast_path.lock() = Some(hook);
|
||
}
|
||
|
||
pub fn set_classifier(&self, classifier: Classifier) {
|
||
*self.classifier.lock() = Some(classifier);
|
||
}
|
||
|
||
/// Owner inputs that must not be kept in the visible history (AG-02, AG-04).
|
||
pub fn set_input_redactor(&self, hook: InputRedactor) {
|
||
*self.redact_input.lock() = Some(hook);
|
||
}
|
||
|
||
/// Adds a pre-model route after the existing ones.
|
||
pub fn set_router(&self, router: Router) {
|
||
self.routers.lock().push(router);
|
||
}
|
||
|
||
pub fn set_reply_guard(&self, guard: ReplyGuard) {
|
||
*self.reply_guard.lock() = Some(guard);
|
||
}
|
||
|
||
pub fn set_compactor(&self, compactor: Compactor) {
|
||
*self.compactor.lock() = Some(compactor);
|
||
}
|
||
|
||
pub fn add_observer(&self, observer: Observer) {
|
||
self.observers.lock().push(observer);
|
||
}
|
||
|
||
pub fn set_after_turn(&self, hook: TurnHook) {
|
||
*self.after_turn.lock() = Some(hook);
|
||
}
|
||
|
||
/// Model view for this turn; summarizes the oldest messages first when they no longer fit.
|
||
async fn prepared_history(&self, budget: usize, ctx: u32) -> Result<Vec<Message>> {
|
||
let compactor = self.compactor.lock().clone();
|
||
if let Some(compactor) = compactor {
|
||
let (entries, summary) = self.session.lock().since_boundary()?;
|
||
let total: usize = entries.iter().map(|(_, m)| crate::session::size(m)).sum::<usize>() + summary.as_ref().map_or(0, String::len);
|
||
if total > budget {
|
||
// Keep about min(4096, ctx/8) recent tokens (~4 chars each), cut on a user message.
|
||
let keep_chars = 4096.min(ctx as usize / 8) * 4;
|
||
let mut acc = 0;
|
||
let mut cut = None;
|
||
for (i, (_, m)) in entries.iter().enumerate().rev() {
|
||
acc += crate::session::size(m);
|
||
if acc > keep_chars {
|
||
break;
|
||
}
|
||
if m.role == "user" {
|
||
cut = Some(i);
|
||
}
|
||
}
|
||
if let Some(cut) = cut.filter(|&c| c > 0) {
|
||
let old: Vec<Message> = entries[..cut].iter().map(|(_, m)| m.clone()).collect();
|
||
match compactor(old, summary).await {
|
||
Ok(text) if !text.trim().is_empty() => self.session.lock().compact(&text, entries[cut].0)?,
|
||
Ok(_) => tracing::warn!("compaction returned an empty summary"),
|
||
Err(e) => tracing::warn!("compaction failed, oldest messages are dropped: {e:#}"),
|
||
}
|
||
}
|
||
}
|
||
}
|
||
self.session.lock().model_view(budget)
|
||
}
|
||
|
||
/// Internet mode: the answer uses host-supplied web evidence and no action tools.
|
||
pub fn set_internet(&self, enabled: bool) {
|
||
self.internet.store(enabled, Ordering::Relaxed);
|
||
}
|
||
|
||
pub fn internet(&self) -> bool {
|
||
self.internet.load(Ordering::Relaxed)
|
||
}
|
||
|
||
/// Applies changed settings (language, generation options) from the next turn on.
|
||
pub fn update_settings(&self, settings: Settings) {
|
||
*self.settings.lock() = settings;
|
||
}
|
||
|
||
pub fn model(&self) -> String {
|
||
self.model.lock().clone()
|
||
}
|
||
|
||
/// Switches the local model (after a download or a model change). The conversation is kept.
|
||
/// `capabilities` replace the current ones only while the local backend is active.
|
||
pub fn set_model(&self, model: String, capabilities: &[String]) -> Result<(), String> {
|
||
if self.busy() {
|
||
return Err("Wait for the current reply to finish.".into());
|
||
}
|
||
if self.backend.lock().is_local() {
|
||
*self.capabilities.lock() = capabilities.to_vec();
|
||
}
|
||
*self.local_caps.lock() = capabilities.to_vec();
|
||
*self.model.lock() = model;
|
||
Ok(())
|
||
}
|
||
|
||
/// `Local · <model>` or `API · <host> · <model>`.
|
||
pub fn label(&self) -> String {
|
||
self.backend.lock().label(&self.model())
|
||
}
|
||
|
||
/// Switches between the local model and an API connection. The conversation is kept.
|
||
/// `local_capabilities` is used for the local backend; APIs report their own.
|
||
pub fn set_backend(&self, backend: LlmBackend, local_capabilities: &[String]) -> Result<(), String> {
|
||
if self.busy() {
|
||
return Err("Wait for the current reply to finish.".into());
|
||
}
|
||
*self.capabilities.lock() = backend.api_capabilities().unwrap_or_else(|| local_capabilities.to_vec());
|
||
*self.local_caps.lock() = local_capabilities.to_vec();
|
||
*self.backend.lock() = backend;
|
||
Ok(())
|
||
}
|
||
|
||
fn has(&self, capability: &str) -> bool {
|
||
self.capabilities.lock().iter().any(|c| c == capability)
|
||
}
|
||
|
||
/// The backend the conversation uses now (local Ollama or an API), for auxiliary calls.
|
||
pub fn backend(&self) -> LlmBackend {
|
||
self.backend.lock().clone()
|
||
}
|
||
|
||
/// Capabilities of the local model (the active ones when the local backend is in use).
|
||
pub fn local_capabilities(&self) -> Vec<String> {
|
||
if self.backend.lock().is_local() { self.capabilities.lock().clone() } else { self.local_caps.lock().clone() }
|
||
}
|
||
|
||
/// Capability of the active model or API (`tools`, `vision`, `thinking`).
|
||
pub fn supports(&self, capability: &str) -> bool {
|
||
self.has(capability)
|
||
}
|
||
|
||
/// Images (base64) sent with the next owner message; a context hook may call this.
|
||
pub fn attach_images(&self, images: Vec<String>) {
|
||
self.pending_images.lock().extend(images);
|
||
}
|
||
|
||
/// Context text added to the next owner message only (e.g. which screen a snapshot shows).
|
||
pub fn attach_note(&self, note: &str) {
|
||
self.pending_note.lock().push_str(note);
|
||
}
|
||
|
||
pub fn catalog(&self) -> &Arc<Catalog> {
|
||
&self.catalog
|
||
}
|
||
|
||
pub fn history(&self) -> Vec<JournalMessage> {
|
||
self.journal.lock().messages.clone()
|
||
}
|
||
|
||
pub fn history_warning(&self) -> Option<String> {
|
||
self.journal.lock().warning.clone()
|
||
}
|
||
|
||
pub fn busy(&self) -> bool {
|
||
self.active.lock().is_some()
|
||
}
|
||
|
||
/// Stops the active reply, if any.
|
||
pub fn cancel(&self) {
|
||
if let Some(token) = self.active.lock().as_ref() {
|
||
token.cancel();
|
||
}
|
||
}
|
||
|
||
/// Starts a new model session and clears the visible history.
|
||
pub fn reset_conversation(&self) -> Result<()> {
|
||
anyhow::ensure!(!self.busy(), "Wait for the current reply to finish.");
|
||
self.session.lock().reset()?;
|
||
self.journal.lock().clear()
|
||
}
|
||
|
||
/// Loads the model so the first reply does not pay the load time.
|
||
pub async fn warm_up(&self) -> Result<()> {
|
||
let keep_alive = self.settings.lock().keep_alive;
|
||
let backend = self.backend.lock().clone();
|
||
tokio::time::timeout(self.deadlines.load, backend.load(&self.model(), keep_alive))
|
||
.await
|
||
.map_err(|_| anyhow::anyhow!("The model took too long to load."))??;
|
||
Ok(())
|
||
}
|
||
|
||
fn avatar_ref(&self, id: &str) -> Option<AvatarRef> {
|
||
let sprite = self.catalog.model_sprite(id)?;
|
||
let frame = self.catalog.frame(&sprite.frame_id)?;
|
||
Some(AvatarRef { id: id.into(), pose: frame.pose.clone(), expression: frame.expression.clone() })
|
||
}
|
||
|
||
/// A short line Capri says on her own (tap reaction, initiative): one model call without
|
||
/// tools or history. `clean` filters the raw text; a kept line is stored as an assistant
|
||
/// message (`origin` = `{"kind": …}`) and emitted like a turn so it is shown and spoken.
|
||
/// `Ok(None)`: the model gave nothing usable. `Err`: a reply is running or the model failed.
|
||
pub async fn say(&self, system: String, user: String, origin: serde_json::Value, clean: impl Fn(&str) -> Option<String>, emit: impl Fn(TurnEvent) + Send + Sync) -> Result<Option<String>, String> {
|
||
let cancel = {
|
||
let mut active = self.active.lock();
|
||
if active.is_some() {
|
||
return Err("A reply is already in progress.".into());
|
||
}
|
||
let token = CancellationToken::new();
|
||
*active = Some(token.clone());
|
||
token
|
||
};
|
||
let result = self.say_inner(system, user, origin, clean, &cancel, emit).await;
|
||
*self.active.lock() = None;
|
||
result
|
||
}
|
||
|
||
async fn say_inner(&self, system: String, user: String, origin: serde_json::Value, clean: impl Fn(&str) -> Option<String>, cancel: &CancellationToken, emit: impl Fn(TurnEvent) + Send + Sync) -> Result<Option<String>, String> {
|
||
let settings = self.settings.lock().clone();
|
||
let backend = self.backend.lock().clone();
|
||
let request = ChatRequest {
|
||
model: self.model(),
|
||
messages: vec![Message::new("system", system), Message::new("user", user)],
|
||
tools: vec![],
|
||
options: Options {
|
||
num_ctx: backend.context_tokens(&settings).min(4096),
|
||
temperature: settings.temperature,
|
||
repeat_last_n: settings.repeat_last_n,
|
||
num_gpu: (settings.acceleration == "cpu").then_some(0),
|
||
num_thread: settings.cpu_threads,
|
||
num_predict: Some(96),
|
||
},
|
||
keep_alive: settings.keep_alive,
|
||
stream: true,
|
||
think: self.has("thinking").then_some(false),
|
||
};
|
||
let call = tokio::time::timeout(self.deadlines.load + self.deadlines.first_text, backend.chat(&request, |_| {}));
|
||
let done = tokio::select! {
|
||
_ = cancel.cancelled() => return Ok(None),
|
||
done = call => match done {
|
||
Ok(Ok(done)) => done,
|
||
Ok(Err(e)) => return Err(e.to_string()),
|
||
Err(_) => return Err("Capri took too long to respond.".into()),
|
||
},
|
||
};
|
||
if !done.tool_calls.is_empty() || done.done_reason.as_deref() == Some("length") {
|
||
return Ok(None);
|
||
}
|
||
let Some(line) = clean(&done.content) else { return Ok(None) };
|
||
let turn_id = uuid::Uuid::new_v4().to_string();
|
||
let mut extra = serde_json::Map::new();
|
||
extra.insert("origin".into(), origin);
|
||
let message = JournalMessage {
|
||
id: uuid::Uuid::new_v4().to_string(),
|
||
turn_id: turn_id.clone(),
|
||
role: "assistant".into(),
|
||
text: line.clone(),
|
||
status: "complete".into(),
|
||
created_at: now(),
|
||
avatar: None,
|
||
follow_up: Some(false),
|
||
extra,
|
||
};
|
||
self.journal.lock().put(message).map_err(|e| e.to_string())?;
|
||
let observers = self.observers.lock().clone();
|
||
let send = |event: TurnEvent| {
|
||
for observer in &observers {
|
||
observer(&event);
|
||
}
|
||
emit(event);
|
||
};
|
||
send(TurnEvent::Started { turn_id: turn_id.clone(), text: String::new() });
|
||
send(TurnEvent::Delta { turn_id: turn_id.clone(), text: line.clone() });
|
||
send(TurnEvent::Completed { turn_id, text: line.clone() });
|
||
Ok(Some(line))
|
||
}
|
||
|
||
/// Keeps a line Capri said on her own (initiative) in the visible history and the model
|
||
/// session, so later replies know it was said. `label` describes its origin for the model.
|
||
pub fn record_line(&self, turn_id: &str, text: &str, avatar: Option<&str>, origin: serde_json::Value, label: &str) -> Result<()> {
|
||
let mut extra = serde_json::Map::new();
|
||
extra.insert("origin".into(), origin);
|
||
self.journal.lock().put(JournalMessage {
|
||
id: uuid::Uuid::new_v4().to_string(),
|
||
turn_id: turn_id.into(),
|
||
role: "assistant".into(),
|
||
text: text.into(),
|
||
status: "complete".into(),
|
||
created_at: now(),
|
||
avatar: avatar.and_then(|id| self.avatar_ref(id)),
|
||
follow_up: Some(false),
|
||
extra,
|
||
})?;
|
||
let content = if label.is_empty() { text.to_string() } else { format!("[{label}] {text}") };
|
||
self.session.lock().append(Some(turn_id), &[("assistant", Message::new("assistant", content))])?;
|
||
Ok(())
|
||
}
|
||
|
||
/// Sends a recorded line to the observers (voice, approval cleanup) like a finished turn.
|
||
pub fn announce(&self, turn_id: &str, text: &str, avatar: Option<&str>) {
|
||
let observers = self.observers.lock().clone();
|
||
let mut events = vec![TurnEvent::Started { turn_id: turn_id.into(), text: String::new() }];
|
||
if let Some(id) = avatar {
|
||
events.push(TurnEvent::Avatar { turn_id: turn_id.into(), id: id.into(), follow_up: false });
|
||
}
|
||
events.push(TurnEvent::Delta { turn_id: turn_id.into(), text: text.into() });
|
||
events.push(TurnEvent::Completed { turn_id: turn_id.into(), text: text.into() });
|
||
for event in &events {
|
||
for observer in &observers {
|
||
observer(event);
|
||
}
|
||
}
|
||
}
|
||
|
||
/// Runs one owner turn. `Err` is a validation message shown to the owner without starting a turn.
|
||
pub async fn submit(&self, text: &str, emit: impl Fn(TurnEvent) + Send + Sync) -> Result<(), String> {
|
||
let text = text.trim();
|
||
let len = utf16_len(text);
|
||
if len == 0 || len > MAX_INPUT || text.contains('\0') {
|
||
return Err("Enter between 1 and 8000 characters.".into());
|
||
}
|
||
let cancel = {
|
||
let mut active = self.active.lock();
|
||
if active.is_some() {
|
||
return Err("A reply is already in progress.".into());
|
||
}
|
||
let token = CancellationToken::new();
|
||
*active = Some(token.clone());
|
||
token
|
||
};
|
||
let observers = self.observers.lock().clone();
|
||
let emit = |event: TurnEvent| {
|
||
for observer in &observers {
|
||
observer(&event);
|
||
}
|
||
emit(event);
|
||
};
|
||
let result = self.run(text, &cancel, &emit).await;
|
||
*self.active.lock() = None;
|
||
result.map_err(|e| e.to_string())
|
||
}
|
||
|
||
fn tool_mode(&self, text: &str) -> (PromptMode, Vec<Arc<dyn Tool>>) {
|
||
let mut tools: Vec<Arc<dyn Tool>> = self.tools.lock().iter().filter(|t| t.available()).cloned().collect();
|
||
tools.sort_by(|a, b| a.name().cmp(b.name()));
|
||
if self.internet() {
|
||
return (PromptMode::Web, vec![]);
|
||
}
|
||
if tools.is_empty() || !self.has("tools") {
|
||
return (PromptMode::ChatOnly, vec![]);
|
||
}
|
||
if conversation_only(text) {
|
||
return (PromptMode::Dialogue, vec![]);
|
||
}
|
||
(PromptMode::Tools, tools)
|
||
}
|
||
|
||
/// The model's copy of the owner message: text, context blocks and the live desktop state.
|
||
async fn user_message(&self, text: &str, mode: PromptMode) -> Message {
|
||
let mut state = serde_json::json!({"microphone": false, "screenObservation": false});
|
||
for provider in self.state.lock().iter() {
|
||
if let (Some(target), serde_json::Value::Object(extra)) = (state.as_object_mut(), provider()) {
|
||
target.extend(extra);
|
||
}
|
||
}
|
||
if mode == PromptMode::Dialogue {
|
||
state = serde_json::json!({});
|
||
}
|
||
let hooks: Vec<ContextHook> = self.context.lock().clone();
|
||
let mut context = String::new();
|
||
for hook in hooks {
|
||
context.push_str(&hook(text.to_string()).await);
|
||
}
|
||
context.push_str(&std::mem::take(&mut *self.pending_note.lock()));
|
||
let mut message = Message::new("user", format!("{text}{}{context}", prompt::envelope(&state)));
|
||
message.images = std::mem::take(&mut *self.pending_images.lock());
|
||
message
|
||
}
|
||
|
||
async fn run(&self, text: &str, cancel: &CancellationToken, emit: &(impl Fn(TurnEvent) + Send + Sync)) -> Result<()> {
|
||
let turn_id = uuid::Uuid::new_v4().to_string();
|
||
let created = now();
|
||
// A refused credential note is answered, but its text is never stored or echoed.
|
||
let redactor = self.redact_input.lock().clone();
|
||
let shown = if redactor.is_some_and(|r| r(text)) { CREDENTIALS_OMITTED } else { text };
|
||
let user = JournalMessage {
|
||
id: uuid::Uuid::new_v4().to_string(),
|
||
turn_id: turn_id.clone(),
|
||
role: "user".into(),
|
||
text: shown.into(),
|
||
status: "complete".into(),
|
||
created_at: created.clone(),
|
||
avatar: None,
|
||
follow_up: None,
|
||
extra: Default::default(),
|
||
};
|
||
let mut reply = JournalMessage { id: uuid::Uuid::new_v4().to_string(), role: "assistant".into(), text: String::new(), status: "streaming".into(), ..user.clone() };
|
||
{
|
||
let mut journal = self.journal.lock();
|
||
journal.put(user)?;
|
||
journal.put(reply.clone())?;
|
||
}
|
||
emit(TurnEvent::Started { turn_id: turn_id.clone(), text: shown.into() });
|
||
|
||
let fast = self.fast_path.lock().clone();
|
||
if let Some(answer) = fast.and_then(|f| f(text)) {
|
||
let id = self.catalog.default_id.clone();
|
||
reply.avatar = self.avatar_ref(&id);
|
||
reply.follow_up = Some(false);
|
||
reply.text = answer.clone();
|
||
reply.status = "complete".into();
|
||
emit(TurnEvent::Avatar { turn_id: turn_id.clone(), id, follow_up: false });
|
||
emit(TurnEvent::Delta { turn_id: turn_id.clone(), text: answer.clone() });
|
||
self.journal.lock().put(reply)?;
|
||
emit(TurnEvent::Completed { turn_id, text: answer });
|
||
return Ok(());
|
||
}
|
||
|
||
let routers = self.routers.lock().clone();
|
||
for router in routers {
|
||
let routed = router(text.to_string(), turn_id.clone(), cancel.clone()).await;
|
||
if cancel.is_cancelled() {
|
||
reply.status = "interrupted".into();
|
||
self.journal.lock().put(reply)?;
|
||
emit(TurnEvent::Cancelled { turn_id });
|
||
return Ok(());
|
||
}
|
||
if let Some(answer) = routed {
|
||
let id = self.catalog.default_id.clone();
|
||
reply.avatar = self.avatar_ref(&id);
|
||
reply.follow_up = Some(false);
|
||
reply.text = answer.clone();
|
||
reply.status = "complete".into();
|
||
emit(TurnEvent::Avatar { turn_id: turn_id.clone(), id, follow_up: false });
|
||
emit(TurnEvent::Delta { turn_id: turn_id.clone(), text: answer.clone() });
|
||
self.journal.lock().put(reply)?;
|
||
self.session.lock().append(Some(&turn_id), &[("user", Message::new("user", text)), ("assistant", Message::new("assistant", answer.clone()))])?;
|
||
emit(TurnEvent::Completed { turn_id, text: answer });
|
||
return Ok(());
|
||
}
|
||
}
|
||
|
||
let (mut mode, mut tools) = self.tool_mode(text);
|
||
let classifier = self.classifier.lock().clone();
|
||
if mode == PromptMode::Tools
|
||
&& let Some(classify) = classifier
|
||
{
|
||
// The two owner messages before this one (this one is already in the journal).
|
||
let mut context: Vec<String> = self.journal.lock().messages.iter().rev().filter(|m| m.role == "user").skip(1).take(2).map(|m| m.text.clone()).collect();
|
||
context.reverse();
|
||
if classify(text.to_string(), context).await {
|
||
(mode, tools) = (PromptMode::Dialogue, vec![]);
|
||
}
|
||
}
|
||
let user_message = self.user_message(text, mode).await;
|
||
let mut output = Output::new(&self.catalog);
|
||
let mut calls: Vec<ToolCallRecord> = Vec::new();
|
||
let outcome = tokio::select! {
|
||
r = self.generate(&user_message, mode, &tools, &mut output, &mut calls, cancel, &turn_id, emit) => r,
|
||
_ = cancel.cancelled() => Err(TurnError::Timeout),
|
||
_ = tokio::time::sleep(self.deadlines.turn) => Err(TurnError::Timeout),
|
||
};
|
||
|
||
reply.text = output.text.clone();
|
||
let avatar = output.avatar_id.clone();
|
||
if let Some((id, follow_up)) = &avatar {
|
||
reply.avatar = self.avatar_ref(id);
|
||
reply.follow_up = Some(*follow_up);
|
||
}
|
||
let guard = self.reply_guard.lock().clone();
|
||
let outcome = outcome.map(|mut entries| {
|
||
if let Some(extra) = guard.and_then(|g| g(&reply.text, &calls)).filter(|e| !e.trim().is_empty()) {
|
||
let extra = if reply.text.trim().is_empty() { extra } else { format!(" {extra}") };
|
||
reply.text.push_str(&extra);
|
||
emit(TurnEvent::Delta { turn_id: turn_id.clone(), text: extra.clone() });
|
||
if let Some((_, last)) = entries.iter_mut().rev().find(|(role, _)| *role == "assistant") {
|
||
last.content.push_str(&extra);
|
||
}
|
||
}
|
||
entries
|
||
});
|
||
match outcome {
|
||
Ok(entries) => {
|
||
if avatar.is_none() {
|
||
let id = self.catalog.default_id.clone();
|
||
reply.avatar = self.avatar_ref(&id);
|
||
emit(TurnEvent::Avatar { turn_id: turn_id.clone(), id, follow_up: false });
|
||
}
|
||
reply.status = "complete".into();
|
||
self.journal.lock().put(reply.clone())?;
|
||
let mut all = vec![("user", user_message)];
|
||
all.extend(entries);
|
||
self.session.lock().append(Some(&turn_id), &all)?;
|
||
if let Some(hook) = self.after_turn.lock().clone() {
|
||
hook(all.len(), all.iter().map(|(_, m)| m.content.len()).sum());
|
||
}
|
||
emit(TurnEvent::Completed { turn_id, text: reply.text });
|
||
}
|
||
Err(_) if cancel.is_cancelled() => {
|
||
reply.status = "interrupted".into();
|
||
self.journal.lock().put(reply.clone())?;
|
||
if !reply.text.trim().is_empty() {
|
||
self.session.lock().append(Some(&turn_id), &[("user", user_message), ("assistant", Message::new("assistant", reply.text.clone()))])?;
|
||
}
|
||
emit(TurnEvent::Cancelled { turn_id });
|
||
}
|
||
Err(error) => {
|
||
tracing::warn!(code = error.code(), "turn failed: {error:?}");
|
||
reply.status = "error".into();
|
||
self.journal.lock().put(reply)?;
|
||
let message = match &error {
|
||
TurnError::Llm(e) => e.public_message().map(str::to_string),
|
||
_ => None,
|
||
}
|
||
.unwrap_or_else(|| public_message(&error).into());
|
||
emit(TurnEvent::Failed { turn_id, message, code: error.code().into() });
|
||
}
|
||
}
|
||
Ok(())
|
||
}
|
||
|
||
/// Runs the model and its tool calls until a final answer. Returns the session entries
|
||
/// to store after the user message (assistant messages with tool calls, tool results, answer).
|
||
#[allow(clippy::too_many_arguments)]
|
||
async fn generate(
|
||
&self,
|
||
user: &Message,
|
||
mode: PromptMode,
|
||
tools: &[Arc<dyn Tool>],
|
||
output: &mut Output,
|
||
calls: &mut Vec<ToolCallRecord>,
|
||
cancel: &CancellationToken,
|
||
turn_id: &str,
|
||
emit: &(impl Fn(TurnEvent) + Send + Sync),
|
||
) -> Result<Vec<(&'static str, Message)>, TurnError> {
|
||
let settings = self.settings.lock().clone();
|
||
let backend = self.backend.lock().clone();
|
||
// Model preparation has its own deadline so a cold load is not counted as "no text".
|
||
match tokio::time::timeout(self.deadlines.load, backend.load(&self.model(), settings.keep_alive)).await {
|
||
Ok(Ok(())) => {}
|
||
Ok(Err(LlmError::Http { status: 404, .. })) => return Err(TurnError::ModelMissing),
|
||
Ok(Err(LlmError::Network { .. })) => return Err(TurnError::Offline),
|
||
Ok(Err(e)) => {
|
||
tracing::warn!("model load failed: {e}");
|
||
return Err(TurnError::ModelLoad);
|
||
}
|
||
Err(_) => return Err(TurnError::ModelLoad),
|
||
}
|
||
let system = prompt::system_prompt(&self.paths.workspace(), &settings.language, &self.catalog.model_sprites, mode).map_err(TurnError::Internal)?;
|
||
let specs: Vec<serde_json::Value> = tools
|
||
.iter()
|
||
.map(|t| serde_json::json!({"type": "function", "function": {"name": t.name(), "description": t.description(), "parameters": t.parameters()}}))
|
||
.collect();
|
||
let ctx = backend.context_tokens(&settings);
|
||
let num_predict = 2048.min(ctx as i32 / 2);
|
||
let fixed = system.len() + user.content.len() + serde_json::to_string(&specs).map_or(0, |s| s.len());
|
||
// ~3 chars per token, minus the fixed prompt and the output reserve.
|
||
let history_chars = ((ctx as usize).saturating_sub(num_predict as usize) * 3).saturating_sub(fixed);
|
||
let history = self.prepared_history(history_chars, ctx).await.map_err(TurnError::Internal)?;
|
||
let mut messages = vec![Message::new("system", system)];
|
||
messages.extend(history);
|
||
messages.push(user.clone());
|
||
|
||
let mut entries: Vec<(&'static str, Message)> = Vec::new();
|
||
let mut guard = ToolProgressGuard::default();
|
||
let mut used_tools = false;
|
||
let mut settled_retry = false;
|
||
for _ in 0..MAX_MODEL_CALLS {
|
||
let request = ChatRequest {
|
||
model: self.model(),
|
||
messages: messages.clone(),
|
||
tools: if settled_retry { vec![] } else { specs.clone() },
|
||
options: Options {
|
||
num_ctx: ctx,
|
||
// Capri answers after tool results with a low temperature (factual confirmation).
|
||
temperature: if used_tools { 0.2 } else { settings.temperature },
|
||
repeat_last_n: settings.repeat_last_n,
|
||
num_gpu: (settings.acceleration == "cpu").then_some(0),
|
||
num_thread: settings.cpu_threads,
|
||
num_predict: Some(num_predict),
|
||
},
|
||
keep_alive: settings.keep_alive,
|
||
stream: true,
|
||
think: self.has("thinking").then_some(false),
|
||
};
|
||
let done = self.stream_call(&backend, &request, output, turn_id, emit).await?;
|
||
let mut content = done.content.clone();
|
||
if done.tool_calls.is_empty() && content.trim().is_empty() && done.thinking.trim_start().starts_with("[avatar:") {
|
||
// Thinking leak recovery: the reply went entirely into the reasoning channel.
|
||
content = done.thinking.clone();
|
||
self.show(output, &content, turn_id, emit);
|
||
}
|
||
let mut assistant = Message::new("assistant", content);
|
||
assistant.tool_calls = done.tool_calls.clone();
|
||
messages.push(assistant.clone());
|
||
entries.push(("assistant", assistant));
|
||
if done.tool_calls.is_empty() {
|
||
self.show(output, "", turn_id, emit);
|
||
if !output.text.trim().is_empty() {
|
||
return Ok(entries);
|
||
}
|
||
if used_tools && !settled_retry {
|
||
settled_retry = true;
|
||
// Transient instruction: not stored in the session.
|
||
messages.push(Message::new("user", SETTLED_TOOLS_INSTRUCTION));
|
||
continue;
|
||
}
|
||
if used_tools {
|
||
output.text = SETTLED_TOOLS_FALLBACK.into();
|
||
emit(TurnEvent::Delta { turn_id: turn_id.into(), text: SETTLED_TOOLS_FALLBACK.into() });
|
||
return Ok(entries);
|
||
}
|
||
return Err(TurnError::Empty);
|
||
}
|
||
used_tools = true;
|
||
for call in done.tool_calls {
|
||
let name = call.function.name.clone();
|
||
let args = match &call.function.arguments {
|
||
serde_json::Value::String(raw) => serde_json::from_str(raw).unwrap_or(serde_json::Value::Null),
|
||
other => other.clone(),
|
||
};
|
||
let result = self.run_tool(tools, &name, args.clone(), call.id.clone().unwrap_or_default(), cancel, turn_id, emit).await;
|
||
calls.push((name.clone(), args.clone(), result.clone()));
|
||
if guard.record(&name, &args, &result).is_err() {
|
||
return Err(TurnError::ToolLoop);
|
||
}
|
||
let mut content = result.to_string();
|
||
if content.len() > MAX_TOOL_RESULT {
|
||
let cut = (0..=MAX_TOOL_RESULT).rev().find(|&i| content.is_char_boundary(i)).unwrap_or(0);
|
||
content.truncate(cut);
|
||
content.push_str(" [result truncated]");
|
||
}
|
||
let message = Message { role: "tool".into(), content, tool_name: Some(name), ..Default::default() };
|
||
messages.push(message.clone());
|
||
entries.push(("tool_result", message));
|
||
}
|
||
}
|
||
Err(TurnError::ToolLoop)
|
||
}
|
||
|
||
#[allow(clippy::too_many_arguments)]
|
||
async fn run_tool(
|
||
&self,
|
||
tools: &[Arc<dyn Tool>],
|
||
name: &str,
|
||
args: serde_json::Value,
|
||
call_id: String,
|
||
cancel: &CancellationToken,
|
||
turn_id: &str,
|
||
emit: &(impl Fn(TurnEvent) + Send + Sync),
|
||
) -> serde_json::Value {
|
||
let Some(tool) = tools.iter().find(|t| t.name() == name) else {
|
||
return serde_json::json!({"ok": false, "error": "Tool is not available in this turn."});
|
||
};
|
||
if !args.is_object() {
|
||
return serde_json::json!({"ok": false, "error": "Tool arguments must be a JSON object."});
|
||
}
|
||
emit(TurnEvent::Tool { turn_id: turn_id.into(), name: name.into(), ok: None });
|
||
// Durable id (Capri broker): the same model call is never executed twice across retries.
|
||
let call_id = {
|
||
use sha2::Digest;
|
||
let session = self.session.lock().id.clone();
|
||
hex::encode(sha2::Sha256::digest(format!("{SESSION_KEY}\0{session}\0{turn_id}:{call_id}")))
|
||
};
|
||
let ctx = ToolContext { turn_id: turn_id.into(), call_id, approvals: self.approvals.lock().clone(), cancel: cancel.child_token() };
|
||
let token = ctx.cancel.clone();
|
||
let result = match tokio::time::timeout(tool.timeout(), tool.call(args, ctx)).await {
|
||
Ok(result) => result,
|
||
Err(_) => {
|
||
token.cancel();
|
||
serde_json::json!({"ok": false, "error": "The tool did not finish in time."})
|
||
}
|
||
};
|
||
emit(TurnEvent::Tool { turn_id: turn_id.into(), name: name.into(), ok: Some(result["ok"] == true) });
|
||
result
|
||
}
|
||
|
||
/// Sends text through the output pipeline and emits what becomes visible.
|
||
fn show(&self, output: &mut Output, text: &str, turn_id: &str, emit: &(impl Fn(TurnEvent) + Send + Sync)) {
|
||
let (visible, avatar) = output.push(text, text.is_empty());
|
||
if let Some((id, follow_up)) = avatar {
|
||
emit(TurnEvent::Avatar { turn_id: turn_id.into(), id, follow_up });
|
||
}
|
||
if !visible.is_empty() {
|
||
emit(TurnEvent::Delta { turn_id: turn_id.into(), text: visible });
|
||
}
|
||
}
|
||
|
||
/// One streamed model call with the first-output watchdog.
|
||
async fn stream_call(
|
||
&self,
|
||
backend: &LlmBackend,
|
||
request: &ChatRequest,
|
||
output: &mut Output,
|
||
turn_id: &str,
|
||
emit: &(impl Fn(TurnEvent) + Send + Sync),
|
||
) -> Result<capri_llm::ChatDone, TurnError> {
|
||
let got_text = AtomicBool::new(false);
|
||
let too_long = AtomicBool::new(false);
|
||
let cell = Mutex::new(std::mem::replace(output, Output::new(&self.catalog)));
|
||
let on_text = |delta: &str| {
|
||
let mut out = cell.lock();
|
||
let (text, avatar) = out.push(delta, false);
|
||
if let Some((id, follow_up)) = avatar {
|
||
emit(TurnEvent::Avatar { turn_id: turn_id.into(), id, follow_up });
|
||
}
|
||
if out.text.len() > MAX_OUTPUT {
|
||
too_long.store(true, Ordering::Relaxed);
|
||
}
|
||
got_text.store(true, Ordering::Relaxed);
|
||
if !text.is_empty() {
|
||
emit(TurnEvent::Delta { turn_id: turn_id.into(), text });
|
||
}
|
||
};
|
||
let watchdog = async {
|
||
tokio::time::sleep(self.deadlines.first_text).await;
|
||
if got_text.load(Ordering::Relaxed) {
|
||
std::future::pending::<()>().await;
|
||
}
|
||
};
|
||
let result = tokio::select! {
|
||
r = backend.chat(request, on_text) => r.map_err(TurnError::Llm),
|
||
_ = watchdog => Err(TurnError::Timeout),
|
||
};
|
||
*output = cell.into_inner();
|
||
if too_long.load(Ordering::Relaxed) {
|
||
return Err(TurnError::Llm(LlmError::StreamInvalid("Response exceeds limit".into())));
|
||
}
|
||
result
|
||
}
|
||
}
|
||
|
||
#[cfg(test)]
|
||
mod tests {
|
||
use super::*;
|
||
use capri_llm::Ollama;
|
||
use wiremock::matchers::{body_partial_json, method, path};
|
||
use wiremock::{Mock, MockServer, ResponseTemplate};
|
||
|
||
async fn engine(body: &str) -> (Engine, tempfile::TempDir, MockServer) {
|
||
let server = MockServer::start().await;
|
||
Mock::given(method("POST")).and(path("/api/chat")).and(body_partial_json(serde_json::json!({"stream": false})))
|
||
.respond_with(ResponseTemplate::new(200).set_body_string("{\"done\":true}")).mount(&server).await;
|
||
Mock::given(method("POST")).and(path("/api/chat")).and(body_partial_json(serde_json::json!({"stream": true})))
|
||
.respond_with(ResponseTemplate::new(200).set_body_string(body.to_string())).mount(&server).await;
|
||
let dir = tempfile::tempdir().unwrap();
|
||
let paths = Paths::under(dir.path().to_path_buf());
|
||
let engine = Engine::new(paths, Settings::default(), Ollama::new(server.uri()), "m".into(), &["thinking".into()], Arc::new(Catalog::fallback())).unwrap();
|
||
(engine, dir, server)
|
||
}
|
||
|
||
fn line(content: &str, done: bool) -> String {
|
||
serde_json::json!({"message": {"role": "assistant", "content": content}, "done": done}).to_string() + "\n"
|
||
}
|
||
|
||
#[tokio::test]
|
||
async fn full_turn_streams_filters_and_persists() {
|
||
let body = line("[avatar:neutral]\n", false) + &line("Hello **there** 👋", false) + &line("", true);
|
||
let (engine, _dir, server) = engine(&body).await;
|
||
let events = Mutex::new(vec![]);
|
||
engine.submit(" hi Capri ", |e| events.lock().push(e)).await.unwrap();
|
||
let events = events.into_inner();
|
||
assert!(matches!(&events[0], TurnEvent::Started { text, .. } if text == "hi Capri"));
|
||
assert!(events.iter().any(|e| matches!(e, TurnEvent::Avatar { id, .. } if id == "neutral")));
|
||
let TurnEvent::Completed { text, .. } = events.last().unwrap() else { panic!("{events:?}") };
|
||
assert_eq!(text, "Hello there ");
|
||
let history = engine.history();
|
||
assert_eq!(history.len(), 2);
|
||
assert_eq!(history[1].status, "complete");
|
||
assert_eq!(history[1].avatar.as_ref().unwrap().id, "neutral");
|
||
// The second turn sends the first exchange as history.
|
||
engine.submit("again", |_| {}).await.unwrap();
|
||
let requests = server.received_requests().await.unwrap();
|
||
let last: serde_json::Value = serde_json::from_slice(&requests.last().unwrap().body).unwrap();
|
||
let messages = last["messages"].as_array().unwrap();
|
||
assert_eq!(messages.len(), 4);
|
||
assert_eq!(messages[0]["role"], "system");
|
||
assert!(messages[1]["content"].as_str().unwrap().starts_with("hi Capri\n\nDESKTOP STATE"));
|
||
assert_eq!(last["think"], false);
|
||
}
|
||
|
||
#[tokio::test]
|
||
async fn router_answers_and_guard_appends() {
|
||
let (engine, _dir, _server) = engine(&(line("[avatar:neutral]\nJ'ouvre Firefox.", false) + &line("", true))).await;
|
||
engine.set_router(Arc::new(|text: String, _turn: String, _c: CancellationToken| Box::pin(async move { text.starts_with("open").then(|| "Opened Firefox.".to_string()) })));
|
||
engine.set_reply_guard(Arc::new(|reply: &str, calls: &[ToolCallRecord]| (calls.is_empty() && reply.contains("ouvre")).then(|| "No action was performed.".to_string())));
|
||
let events = Mutex::new(vec![]);
|
||
engine.submit("open firefox", |e| events.lock().push(e)).await.unwrap();
|
||
assert!(matches!(events.lock().last().unwrap(), TurnEvent::Completed { text, .. } if text == "Opened Firefox."));
|
||
events.lock().clear();
|
||
engine.submit("sur firefox", |e| events.lock().push(e)).await.unwrap();
|
||
assert!(matches!(events.lock().last().unwrap(), TurnEvent::Completed { text, .. } if text.ends_with(" No action was performed.")));
|
||
assert_eq!(engine.history().len(), 4);
|
||
}
|
||
|
||
#[tokio::test]
|
||
async fn validation_and_empty_reply() {
|
||
let (engine, _dir, _server) = engine(&(line("[avatar:neutral]", false) + &line("", true))).await;
|
||
assert!(engine.submit(" ", |_| {}).await.is_err());
|
||
assert!(engine.submit(&"x".repeat(8001), |_| {}).await.is_err());
|
||
let events = Mutex::new(vec![]);
|
||
engine.submit("hi", |e| events.lock().push(e)).await.unwrap();
|
||
assert!(matches!(events.into_inner().last().unwrap(), TurnEvent::Failed { code, .. } if code == "CAPRI_LLM_RESPONSE_EMPTY"));
|
||
assert_eq!(engine.history()[1].status, "error");
|
||
}
|
||
|
||
struct Clock;
|
||
#[async_trait::async_trait]
|
||
impl Tool for Clock {
|
||
fn name(&self) -> &str { "time_control" }
|
||
fn description(&self) -> String { "Reads the clock.".into() }
|
||
fn parameters(&self) -> serde_json::Value { serde_json::json!({"type": "object", "properties": {"action": {"type": "string"}}}) }
|
||
async fn call(&self, args: serde_json::Value, _ctx: ToolContext) -> serde_json::Value {
|
||
crate::tools::ok(serde_json::json!({"time": "12:00", "echo": args["action"]}))
|
||
}
|
||
}
|
||
|
||
#[tokio::test]
|
||
async fn tool_loop_calls_tool_then_answers() {
|
||
let server = MockServer::start().await;
|
||
Mock::given(method("POST")).and(path("/api/chat")).and(body_partial_json(serde_json::json!({"stream": false})))
|
||
.respond_with(ResponseTemplate::new(200).set_body_string("{\"done\":true}")).mount(&server).await;
|
||
let call = serde_json::json!({"message": {"role": "assistant", "content": "", "tool_calls": [{"function": {"name": "time_control", "arguments": {"action": "now"}}}]}, "done": true}).to_string() + "\n";
|
||
Mock::given(method("POST")).and(path("/api/chat")).and(body_partial_json(serde_json::json!({"stream": true})))
|
||
.respond_with(ResponseTemplate::new(200).set_body_string(call)).up_to_n_times(1).mount(&server).await;
|
||
Mock::given(method("POST")).and(path("/api/chat")).and(body_partial_json(serde_json::json!({"stream": true})))
|
||
.respond_with(ResponseTemplate::new(200).set_body_string(line("[avatar:neutral]\nIt is noon.", false) + &line("", true))).mount(&server).await;
|
||
let dir = tempfile::tempdir().unwrap();
|
||
let engine = Engine::new(Paths::under(dir.path().to_path_buf()), Settings::default(), Ollama::new(server.uri()), "m".into(), &["tools".into()], Arc::new(Catalog::fallback())).unwrap();
|
||
engine.set_tools(vec![Arc::new(Clock)]);
|
||
engine.add_state(Arc::new(|| serde_json::json!({"microphone": true})));
|
||
let events = Mutex::new(vec![]);
|
||
engine.submit("what time is it?", |e| events.lock().push(e)).await.unwrap();
|
||
let events = events.into_inner();
|
||
assert!(events.contains(&TurnEvent::Tool { turn_id: match &events[0] { TurnEvent::Started { turn_id, .. } => turn_id.clone(), _ => unreachable!() }, name: "time_control".into(), ok: Some(true) }));
|
||
assert!(matches!(events.last().unwrap(), TurnEvent::Completed { text, .. } if text == "It is noon."), "{events:?}");
|
||
let requests = server.received_requests().await.unwrap();
|
||
let second: serde_json::Value = serde_json::from_slice(&requests.last().unwrap().body).unwrap();
|
||
let msgs = second["messages"].as_array().unwrap();
|
||
assert_eq!(msgs.last().unwrap()["role"], "tool");
|
||
assert!(msgs.last().unwrap()["content"].as_str().unwrap().contains("12:00"));
|
||
assert!(msgs[0]["content"].as_str().unwrap().contains("CURRENT DESKTOP INTERFACE:"));
|
||
assert!(msgs[1]["content"].as_str().unwrap().contains("\"microphone\":true"));
|
||
assert_eq!(second["options"]["temperature"], 0.2);
|
||
// A greeting hides the tools.
|
||
engine.submit("salut capri", |_| {}).await.unwrap();
|
||
let last: serde_json::Value = serde_json::from_slice(&server.received_requests().await.unwrap().last().unwrap().body).unwrap();
|
||
assert!(last.get("tools").is_none());
|
||
// So does the request router's small-talk decision, which sees the earlier owner messages.
|
||
let seen = Arc::new(Mutex::new(vec![]));
|
||
let context = seen.clone();
|
||
engine.set_classifier(Arc::new(move |_text: String, previous: Vec<String>| {
|
||
*context.lock() = previous;
|
||
Box::pin(async { true })
|
||
}));
|
||
engine.submit("tell me a joke", |_| {}).await.unwrap();
|
||
let last: serde_json::Value = serde_json::from_slice(&server.received_requests().await.unwrap().last().unwrap().body).unwrap();
|
||
assert!(last.get("tools").is_none());
|
||
assert_eq!(seen.lock().last().map(String::as_str), Some("salut capri"));
|
||
}
|
||
|
||
#[tokio::test]
|
||
async fn say_stores_and_emits_a_filtered_line() {
|
||
let server = MockServer::start().await;
|
||
Mock::given(method("POST")).and(path("/api/chat"))
|
||
.respond_with(ResponseTemplate::new(200).set_body_string(line("*Hey*, easy on the hand! 😄", false) + &line("", true))).mount(&server).await;
|
||
let dir = tempfile::tempdir().unwrap();
|
||
let engine = Engine::new(Paths::under(dir.path().to_path_buf()), Settings::default(), Ollama::new(server.uri()), "m".into(), &[], Arc::new(Catalog::fallback())).unwrap();
|
||
let seen = Arc::new(Mutex::new(vec![]));
|
||
let observed = seen.clone();
|
||
engine.add_observer(Arc::new(move |e: &TurnEvent| observed.lock().push(format!("{e:?}"))));
|
||
let events = Mutex::new(vec![]);
|
||
let said = engine.say("sys".into(), "user".into(), serde_json::json!({"kind": "avatar-click"}), crate::reaction::clean_line, |e| events.lock().push(e)).await.unwrap();
|
||
assert_eq!(said.as_deref(), Some("Hey, easy on the hand!"));
|
||
assert!(matches!(events.lock().last(), Some(TurnEvent::Completed { text, .. }) if text == "Hey, easy on the hand!"));
|
||
assert_eq!(seen.lock().len(), 3, "the voice observer gets the line too");
|
||
let stored = engine.history().pop().unwrap();
|
||
assert_eq!((stored.role.as_str(), stored.extra["origin"]["kind"].as_str()), ("assistant", Some("avatar-click")));
|
||
assert!(!engine.busy());
|
||
// A line the filter rejects is neither stored nor shown.
|
||
assert_eq!(engine.say("s".into(), "u".into(), serde_json::json!({}), |_| None, |_| {}).await.unwrap(), None);
|
||
assert_eq!(engine.history().len(), 1);
|
||
}
|
||
|
||
#[tokio::test]
|
||
async fn fast_path_and_compaction() {
|
||
let body = line("[avatar:neutral]\nok", false) + &line("", true);
|
||
let server = MockServer::start().await;
|
||
Mock::given(method("POST")).and(path("/api/chat")).and(body_partial_json(serde_json::json!({"stream": false})))
|
||
.respond_with(ResponseTemplate::new(200).set_body_string("{\"done\":true}")).mount(&server).await;
|
||
Mock::given(method("POST")).and(path("/api/chat")).and(body_partial_json(serde_json::json!({"stream": true})))
|
||
.respond_with(ResponseTemplate::new(200).set_body_string(body)).mount(&server).await;
|
||
let dir = tempfile::tempdir().unwrap();
|
||
let settings = Settings { context_tokens: 2000, ..Settings::default() };
|
||
let engine = Engine::new(Paths::under(dir.path().to_path_buf()), settings, Ollama::new(server.uri()), "m".into(), &[], Arc::new(Catalog::fallback())).unwrap();
|
||
engine.set_fast_path(Arc::new(|t: &str| t.starts_with("remember that").then(|| "Done.".to_string())));
|
||
let summarized = Arc::new(Mutex::new(0usize));
|
||
let seen = summarized.clone();
|
||
engine.set_compactor(Arc::new(move |messages: Vec<Message>, _prev: Option<String>| {
|
||
*seen.lock() += messages.len();
|
||
Box::pin(async { Ok("SUMMARY".to_string()) })
|
||
}));
|
||
let events = Mutex::new(vec![]);
|
||
engine.submit("remember that my cat is Neo", |e| events.lock().push(e)).await.unwrap();
|
||
assert!(matches!(events.into_inner().last().unwrap(), TurnEvent::Completed { text, .. } if text == "Done."));
|
||
let calls = server.received_requests().await.unwrap().len();
|
||
assert_eq!(calls, 0, "a note never reaches the model");
|
||
// A refused credential note is answered but never kept in the visible history.
|
||
engine.set_input_redactor(Arc::new(|t: &str| t.contains("password")));
|
||
engine.set_fast_path(Arc::new(|t: &str| t.starts_with("remember that").then(|| "I can’t save passwords.".to_string())));
|
||
let started = Mutex::new(String::new());
|
||
engine.submit("remember that my password is hunter22", |e| if let TurnEvent::Started { text, .. } = e { *started.lock() = text }).await.unwrap();
|
||
assert_eq!(*started.lock(), CREDENTIALS_OMITTED);
|
||
assert!(engine.history().iter().all(|m| !m.text.contains("hunter22")));
|
||
let transcript = std::fs::read_to_string(dir.path().join("data/desktop/transcript.json")).unwrap();
|
||
assert!(!transcript.contains("hunter22") && transcript.contains(CREDENTIALS_OMITTED));
|
||
let long = "x".repeat(600);
|
||
for _ in 0..3 {
|
||
engine.submit(&long, |_| {}).await.unwrap();
|
||
}
|
||
assert!(*summarized.lock() >= 2, "oldest exchange was summarized");
|
||
let last: serde_json::Value = serde_json::from_slice(&server.received_requests().await.unwrap().last().unwrap().body).unwrap();
|
||
assert!(last["messages"][1]["content"].as_str().unwrap().contains("<summary>\nSUMMARY\n</summary>"));
|
||
}
|
||
} |