From a62ad6f5431da3a110d5c073edadf6348f9ca6c1 Mon Sep 17 00:00:00 2001 From: fkDead Date: Wed, 11 Nov 2026 20:20:48 +0100 Subject: [PATCH] capri-computer: add route module --- crates/capri-computer/src/route.rs | 285 +++++++++++++++++++++++++++++ 1 file changed, 285 insertions(+) create mode 100644 crates/capri-computer/src/route.rs diff --git a/crates/capri-computer/src/route.rs b/crates/capri-computer/src/route.rs new file mode 100644 index 0000000..46c4c7c --- /dev/null +++ b/crates/capri-computer/src/route.rs @@ -0,0 +1,285 @@ +//! Host-side computer routing (ported from Capri `computer-mode-request.mjs` and +//! `computer-requests.mjs`): small models rarely call `run_task`, so a computer request is +//! recognized before the model turn and executed by the computer agent, and the turn ends with +//! its verified summary. +//! Regexes follow Capri (EN/RU), with French and Spanish phrasing added. +use std::sync::{Arc, LazyLock}; +use std::time::{Duration, Instant}; + +use capri_agent::tools::Approvals; +use capri_core::SettingsStore; +use capri_perception::llm::{self, LocalModel}; +use parking_lot::Mutex; +use regex::Regex; +use serde_json::{json, Value}; +use tokio_util::sync::CancellationToken; +use unicode_normalization::UnicodeNormalization; + +use crate::access; +use crate::tool::DesktopControl; + +macro_rules! re { + ($s:expr) => {{ + static R: LazyLock = LazyLock::new(|| Regex::new($s).unwrap()); + &*R + }}; +} + +const MODE: &str = r"(?:(?:режим\s+)?полн(?:ого|ое|ый|ом|ым)\s+(?:управлени[ея]|доступ[а]?)\s+(?:ко?\s+)?(?:(?:всему|моим|моему|моего|всего)\s+)*(?:компьютер(?:ом|у|а)?|пк)|full\s+(?:computer|pc|desktop)\s+(?:control|access)|full\s+(?:control|access)\s+(?:of|to|over)\s+(?:(?:my|the|this|entire|whole)\s+)*(?:computer|pc|desktop)|computer\s+control|(?:le\s+|l')?(?:mode\s+)?(?:contr[ôo]le|acc[èe]s)\s+(?:total\s+|complet\s+)?(?:de\s+l'|à\s+l'|à\s+mon\s+|de\s+mon\s+|au\s+)?(?:ordinateur|ordi|pc)(?:\s+complet)?)(?:\s+mode)?"; + +fn mode_re(prefix: &str, suffix: &str) -> Regex { + Regex::new(&format!("(?iu){prefix}{MODE}{suffix}")).unwrap() +} + +static ENABLE: LazyLock = LazyLock::new(|| mode_re(r"^(?:enable|activate|turn\s+on|switch\s+to|use|включи(?:ть)?|активируй|используй|задействуй|перейди\s+в|active|activer|allume|utilise|passe\s+en|prends)\s+(?:the\s+)?", r"(?:$|[\s,.:;!?])")); +static DISABLE: LazyLock = LazyLock::new(|| mode_re(r"^(?:disable|deactivate|turn\s+off|revoke|отключи(?:ть)?|выключи(?:ть)?|отзови|d[ée]sactive|d[ée]sactiver|coupe|retire|enl[èe]ve)\s+(?:the\s+)?", r"(?:$|[\s,.:;!?])")); +static USING: LazyLock = LazyLock::new(|| mode_re(r"^(?:using|with|in|через|используя|в(?:\s+режиме)?|avec|en\s+utilisant|via)\s+", r"(?:$|[\s,.:;!?])")); +static TRAILING: LazyLock = LazyLock::new(|| mode_re(r"\s+(?:using|with|через|используя|в(?:\s+режиме)?|avec|en\s+utilisant|via)\s+", r"[.!?\s]*$")); +static MENTION: LazyLock = LazyLock::new(|| mode_re(r"(?:^|\s)", r"(?:$|[\s,.:;!?])")); + +/// Strips the wake word, politeness and "I want you to". +pub fn request_text(text: &str) -> String { + let t: String = text.nfkc().collect::().trim().to_string(); + let t = re!(r"(?iu)^(?:(?:hey\s+)?capri|капри)[,\s:]+").replace(&t, "").into_owned(); + let t = re!(r"(?iu)^(?:(?:please|пожалуйста|s'il\s+te\s+pla[iî]t|stp|svp|por\s+favor)[,\s]+|(?:can|could|would)\s+you\s+(?:please\s+)?|(?:можешь|можете)\s+(?:пожалуйста\s+)?|(?:est-ce\s+que\s+)?(?:tu\s+peux|tu\s+pourrais|peux-tu|pourrais-tu)\s+|(?:puedes|podrías)\s+)").replace(&t, "").into_owned(); + let t = re!(r"(?iu)^(?:i\s+(?:want|need|would\s+like)\s+you\s+to\s+|я\s+(?:хочу|прошу)\s+|je\s+(?:veux|voudrais)\s+que\s+tu\s+)").replace(&t, "").into_owned(); + let t = re!(r"(?iu)^(?:uh|um|please|пожалуйста|euh)\s+").replace(&t, "").into_owned(); + re!(r"(?iu)[,\s]+(?:please|stp|svp|s'il\s+te\s+pla[iî]t|пожалуйста|por\s+favor)[.!?\s]*$").replace(&t, "").trim().to_string() +} + +pub fn mentions_computer_mode(text: &str) -> bool { + MENTION.is_match(&text.nfkc().collect::()) +} + +/// "Don't open…" and similar negations stay conversation. +pub fn rejects_desktop_action(text: &str) -> bool { + re!(r"(?iu)^(?:do\s+not|don['’]t|never|не|ne|n['’])\s*(?:enable|activate|turn\s+on|open|launch|start|use|click|press|включай|включать|включи|активируй|открывай|открыть|открой|запускай|запускайся|используй|нажимай|нажми|ouvre|lance|active|utilise|clique|appuie)(?:\P{L}|$)").is_match(&request_text(text)) +} + +/// (`name`, single step) for "open/launch/start " (EN/RU/ES/FR). +pub fn owner_app_launch(text: &str) -> Option<(String, bool)> { + let request = request_text(text); + let access = ENABLE.find(&request).or_else(|| USING.find(&request)); + let command = access.map_or(request.as_str(), |m| &request[m.end()..]); + let command = re!(r"(?iu)^[,.:;\s]+").replace(command, ""); + let command = re!(r"(?iu)^(?:and|to|и|et|pour)\s+").replace(&command, "").into_owned(); + let launch = re!(r"(?iu)^(?:open|launch|start|открой|запусти|abre|abrir|inicia|iniciar|lanza|lanzar|ouvre|ouvrir|ouvert|lance|lancer|lanc[ée]|lancez|d[ée]marre|d[ée]marrer|mets)\s+"); + let m = launch.find(&command)?; + let remainder = &command[m.end()..]; + if re!(r"(?iu)^(?:it|that|его|её|ее|это|le|la|ça|ca)[.!?\s]*$").is_match(remainder) { + return None; + } + let chain = re!(r"(?iu)(?:[,.;:]\s*(?:(?:then|потом|затем|puis|ensuite)\s+)?|\s+(?:and\s+(?:then\s+)?|then\s+|потом\s+|затем\s+|и\s+|et\s+(?:puis\s+)?|puis\s+|ensuite\s+))(?:go\s+to|click|open|launch|search|find|google|type|write|press|show|play|do|перейди|открой|нажми|найди|напиши|введи|запусти|va|clique|ouvre|lance|cherche|tape|[ée]cris|appuie|mets|joue|affiche)(?:\s|$)"); + let (name, single) = match chain.find(remainder) { + Some(c) => (&remainder[..c.start()], false), + None => (remainder, true), + }; + let name = re!(r"(?iu)(?:[.!?]+|\s+please|,?\s+пожалуйста|,?\s+stp|,?\s+svp)$").replace(name.trim(), "").trim().trim_matches(['"', '«', '»', '“', '”']).trim().to_string(); + re!(r"^[\p{L}\p{N}][\p{L}\p{N} ._+&'’\-]{0,79}$").is_match(&name).then_some((name, single)) +} + +/// References to the previous computer task. +pub fn computer_task_follow_up(text: &str) -> bool { + let r = request_text(text); + re!(r"(?iu)^(?:(?:and\s+)?then\s+)?(?:open|launch|start)\s+(?:it|that)[.!?\s]*$|^(?:тогда\s+)?(?:открой|запусти)\s+(?:его|её|ее|это)[.!?\s]*$|^(?:ouvre|lance)[-\s](?:le|la|les)[.!?\s]*$").is_match(&r) + || re!(r"(?iu)^(?:continue(?:\s+(?:the|that|this)\s+task)?[.!?\s]*$|(?:open|load|show)\s+(?:(?:your|my|the|that|this)\s+)?(?:(?:most\s+)?(?:recent|latest)\s+)?project\b|(?:export|render)\s+(?:it|that|this|the project|the video)\b|продолжи(?:ть)?(?:\s+(?:задачу|это))?[.!?\s]*$|(?:открой|загрузи)\s+(?:(?:мой|этот|последний|текущий)\s+)?проект\b|continue(?:\s+la\s+t[âa]che)?[.!?\s]*$|vas-y[.!?\s]*$)").is_match(&r) +} + +/// A dedicated music request belongs to the Spotify route (abbreviated from Capri). +fn dedicated_music(request: &str) -> bool { + let music = re!(r"(?iu)\b(?:spotify|music|songs?|tracks?|playlists?|shuffle)\b|спотиф|музык|песн|трек|плейлист|\bmusique\b|\bchansons?\b").is_match(request); + let web = re!(r"(?iu)\b(?:youtube|deezer|soundcloud|firefox|chrome|chromium|browser|navigateur|site|web)\b|https?:").is_match(request); + music && !web && re!(r"(?iu)^(?:play|pause|resume|skip|next|previous|put\s+on|turn\s+on|включи|поставь|joue|mets|lance\s+(?:la|de\s+la)\s+musique)").is_match(request) +} + +/// `(enabled, run)` for an explicit computer request, else `None`. +pub fn computer_mode_request(text: &str, full_access: bool) -> Option<(bool, bool)> { + let value = request_text(text); + if let Some(m) = DISABLE.find(&value) + && value[m.end()..].chars().all(|c| c.is_whitespace() || ".!?,;:".contains(c)) + { + return Some((false, false)); + } + if let Some(m) = ENABLE.find(&value).or_else(|| USING.find(&value)) { + let rest = re!(r"(?iu)^[\s,.:;!?]*(?:please|пожалуйста|now|сейчас|maintenant|stp)?[\s,.:;!?]*$").replace(&value[m.end()..], "").trim().to_string(); + return Some((true, !rest.is_empty())); + } + let action = re!(r"(?iu)^(?:open|launch|start|find|search|type|write|click|move|create|copy|delete|play|calculate|открой|запусти|найди|поищи|введи|напиши|нажми|перемести|создай|скопируй|удали|включи|посчитай|ouvre|lance|cherche|tape|[ée]cris|clique|d[ée]place|cr[ée]e|copie|supprime)\s"); + if action.is_match(&value) && TRAILING.is_match(&value) { + return Some((true, true)); + } + if dedicated_music(&value) { + return None; + } + if full_access { + let opening = owner_app_launch(&value); + let browser_draft = opening.as_ref().is_some_and(|(n, _)| re!(r"(?iu)^(?:google chrome|chrome|edge|microsoft edge|browser|браузер|хром|navigateur)$").is_match(n)); + if authorized_sequence(&value) || opening.is_some_and(|(_, single)| single || !browser_draft) { + return Some((true, true)); + } + } + None +} + +/// An already authorized app sequence ("open X then …", "search … in the browser"). +fn authorized_sequence(value: &str) -> bool { + let command = request_text(&re!(r#""[^"\n]*"|“[^”\n]*”|«[^»\n]*»"#).replace_all(value, "")); + let task = re!(r"(?iu)^(?:open|launch|start|search|find|google|use|открой|открыть|запусти|запустить|найди|найти|поищи|используй|ouvre|lance|cherche|recherche|va\s+sur)\s"); + let browser = re!(r"(?iu)\b(?:chrome|edge|browser|firefox|chromium|navigateur|computer\s+control)\b|хром|браузер"); + let next = re!(r"(?iu)(?:,\s*|\b(?:and(?:\s+then)?|then|after\s+(?:this|that)|next|finally|et(?:\s+puis)?|puis|ensuite)\s+|(?:затем|потом|после\s+этого|и)\s+)(?:go\s+to|click|open|search|find|google|show|display|press|navigate|watch|перейди|нажми|открой|найди|поищи|покажи|va|clique|ouvre|cherche|affiche|regarde|mets)\s"); + task.is_match(&command) && ((re!(r"(?iu)^(?:open|launch|start|открой|запусти|ouvre|lance)\s").is_match(&command) && next.is_match(value)) || (browser.is_match(value) && next.is_match(value)) || (re!(r"(?iu)^(?:search|find|google|cherche|recherche)\s").is_match(&command) && browser.is_match(value))) +} + +/// Greetings never need the classifier. +pub fn conversation_only(text: &str) -> bool { + let t = text.nfkc().collect::().trim().to_lowercase(); + t.chars().count() <= 100 && re!(r"(?iu)^(?:(?:hi|hey|hello|привет|здравствуй|bonjour|salut|coucou|hola|hallo|ciao)[\s,!.]*)?(?:capri|капри)?[\s,!.?]*(?:how are you|как дела|ça va|ca va|comment ça va)?[\s,!.?]*$").is_match(t.trim_end_matches(['.', '!', '?'])) +} + +pub const CLASSIFIER_PROMPT: &str = r#"Classify the latest OWNER message in its own language, including phonetic errors from speech recognition. Return only JSON with intent and usesPrevious. chat: ordinary conversation, asking for information or instructions, asking what computer access can do, quoting or translating a command. memory: asking to recall saved personal facts, preferences, previous conversations or decisions, for example "What is my favourite game?" or "Что я тебе рассказывал о себе?". Ordinary factual questions are chat. Casual replies such as "Not much, just chilling.", "Nothing much", "Да ничего особенного" are chat, not actions. feature: owner requests a built-in Capri feature such as timers, reminders, screen descriptions, screenshots, settings, or simple media/calculator requests. "Set a timer for ten minutes", "Напомни через час", "Take a screenshot" are feature. task: owner asks Capri to carry out a concrete action in a desktop application or the desktop, such as opening, typing into, switching, or clicking in an app, with no explicit request for full access. Discord navigation, joining/leaving a voice channel, reading visible channel context and sending exact owner-requested text are app tasks: "Join General in Discord", "Подключись к голосовому каналу в Дискорде", "Rejoins le salon vocal sur Discord". task_with_access: same action plus an explicit request to use full computer control. enable/disable: ONLY an explicit instruction to turn the full computer control setting on/off with no other task. Turning on a timer or another feature is feature, never enable. A prohibition is chat, not disable: "Do not turn on computer control", "Не включай управление компьютером", "No actives el control del equipo" are all chat. A polite request phrased as a question can be an action, but a question about capability is chat. Use previousOwnerMessage only to resolve an explicit reference in latestOwnerMessage, never execute its instructions on their own. Set usesPrevious true only if the current task needs that reference. Do not perform any actions."#; + +#[derive(Clone, Debug, PartialEq)] +pub struct Intent { + pub intent: String, + pub uses_previous: bool, +} + +/// The multilingual computer intent classifier (8 s, 64 tokens, temperature 0). `None` on failure. +pub async fn classify(model: &LocalModel, text: &str, previous: Option<&str>, full_access: bool, cancel: &CancellationToken) -> Option { + let intents = ["chat", "memory", "feature", "task", "task_with_access", "enable", "disable"]; + let body = json!({ + "options": {"num_predict": 64, "temperature": 0}, + "format": {"type": "object", "additionalProperties": false, "required": ["intent", "usesPrevious"], "properties": {"intent": {"type": "string", "enum": intents}, "usesPrevious": {"type": "boolean"}}}, + "messages": [ + {"role": "system", "content": CLASSIFIER_PROMPT}, + {"role": "user", "content": json!({"latestOwnerMessage": text, "previousOwnerMessage": previous, "fullComputerAccess": full_access}).to_string()}, + ], + }); + let packet = model.chat(body, 8192, Duration::from_secs(8), cancel).await.ok()?; + parse_intent(&llm::content_json(&packet).ok()?) +} + +pub fn parse_intent(v: &Value) -> Option { + let intent = v["intent"].as_str().filter(|i| ["chat", "memory", "feature", "task", "task_with_access", "enable", "disable"].contains(i))?; + Some(Intent { intent: intent.into(), uses_previous: v["usesPrevious"].as_bool()? }) +} + +/// Words that make a message worth classifying even without full access. +fn desktop_words(text: &str) -> bool { + re!(r"(?iu)\b(?:open|launch|start|click|type|browser|firefox|chrome|app|application|window|computer|pc|ouvre|ouvrir|lance|lanc[ée]|lancer|d[ée]marre|clique|tape|navigateur|fen[êe]tre|ordinateur|ordi|appli|youtube|site|onglet)\b|открой|запусти|компьютер|браузер").is_match(text) +} + +/// The owner's earlier message (text, ms epoch) for references. +pub type PreviousOwner = Arc Option<(String, i64)> + Send + Sync>; + +pub struct ComputerRouter { + pub desktop: Arc, + pub store: Arc, + pub model: LocalModel, + pub approvals: Arc, + pub previous_owner: PreviousOwner, + last_task: Mutex>, +} + +impl ComputerRouter { + pub fn new(desktop: Arc, store: Arc, model: LocalModel, approvals: Arc, previous_owner: PreviousOwner) -> Self { + Self { desktop, store, model, approvals, previous_owner, last_task: Mutex::default() } + } + + /// `Some(reply)` ends the turn with a host result. + pub async fn route(&self, text: &str, turn: &str, internet: bool, cancel: &CancellationToken) -> Option { + if internet || rejects_desktop_action(text) || conversation_only(text) { + return None; + } + let full = access::allowed(&self.store); + let ru = self.store.get().language.conversation == "ru"; + let mut previous: Option = None; + if full && computer_task_follow_up(text) { + previous = self.last_task.lock().as_ref().filter(|(_, at)| at.elapsed() <= Duration::from_secs(600)).map(|(g, _)| g.clone()); + } + let mut mode = if previous.is_some() { Some((true, true)) } else { computer_mode_request(text, full) }; + if mode.is_none() && (full || desktop_words(text) || mentions_computer_mode(text)) { + let recent = (self.previous_owner)().filter(|(_, at)| capri_perception::now_ms() - at <= 600_000).map(|(t, _)| t.chars().take(800).collect::()); + let intent = classify(&self.model, text, recent.as_deref(), full, cancel).await; + tracing::info!("computer intent: {:?}", intent.as_ref().map(|i| i.intent.as_str())); + match intent { + Some(i) if i.intent == "enable" || i.intent == "disable" => { + let r = access::configure(&self.store, self.approvals.as_ref(), i.intent == "enable", ru).await; + self.desktop.access_changed(); + return Some(r["confirmation"].as_str().unwrap_or("").to_string()); + } + Some(i) if i.intent == "task_with_access" || (i.intent == "task" && full) => { + mode = Some((true, true)); + if i.uses_previous || text.chars().count() <= 32 { + previous = recent; + } + } + _ => {} + } + } + let (enabled, run) = mode?; + let grant = access::configure(&self.store, self.approvals.as_ref(), enabled, ru).await; + self.desktop.access_changed(); + if grant["ok"] != true || !run || !enabled { + return Some(grant["confirmation"].as_str().unwrap_or("").to_string()); + } + let result = self.desktop.agent().run(text, turn, previous.as_deref(), cancel).await; + if result["status"] == "cancelled" || cancel.is_cancelled() { + return None; + } + *self.last_task.lock() = Some((text.to_string(), Instant::now())); + let summary = result["summary"].as_str().or(result["error"].as_str()).unwrap_or("").trim(); + tracing::info!("computer task finished: {} ({} steps)", result["status"], result["steps"]); + Some(capri_agent::stream::plain_dialogue_text(summary)) + } +} + +/// The reply says an action is happening but no action tool ran successfully. +pub fn unbacked_action_claim(reply: &str, successful_actions: usize) -> bool { + successful_actions == 0 + && re!(r"(?iu)\b(?:j['’]ouvre|j['’]ai\s+ouvert|je\s+(?:lance|vais\s+(?:ouvrir|lancer|chercher|taper|cliquer))|j['’]ai\s+lanc[ée]|je\s+suis\s+en\s+train\s+de\s+(?:chercher|ouvrir|lancer)|i(?:['’]m|\s+am)\s+(?:opening|launching|searching|typing|clicking)|i(?:['’]ll|\s+will)\s+(?:open|launch|search|type|click)|i\s+(?:opened|launched|clicked|typed)|открываю|открыла|запускаю|запустила)\b").is_match(reply) +} + +/// Text appended when a reply claims an action without a receipt. +pub fn no_action_text(lang: &str) -> &'static str { + match lang { + "fr" => "(Aucune action n'a été effectuée sur l'ordinateur.)", + "ru" => "(На компьютере ничего не было сделано.)", + _ => "(No action was performed on the computer.)", + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn routes_owner_phrasing() { + assert_eq!(owner_app_launch("tu peux lancé youtube musique stp"), Some(("youtube musique".into(), true))); + assert_eq!(owner_app_launch("Capri, ouvre Firefox et va sur youtube.com"), Some(("Firefox".into(), false))); + assert_eq!(owner_app_launch("open Kate"), Some(("Kate".into(), true))); + assert!(owner_app_launch("ouvre-le").is_none() && owner_app_launch("comment ça va ?").is_none()); + assert_eq!(computer_mode_request("tu peux lancé youtube musique stp", true), Some((true, true))); + assert_eq!(computer_mode_request("tu peux lancé youtube musique stp", false), None, "without the grant the classifier decides"); + assert_eq!(computer_mode_request("active le contrôle de l'ordinateur", false), Some((true, false))); + assert_eq!(computer_mode_request("enable full computer access and open Kate", false), Some((true, true))); + assert_eq!(computer_mode_request("disable full computer access", true), Some((false, false))); + assert_eq!(computer_mode_request("open firefox using computer control", false), Some((true, true))); + assert_eq!(computer_mode_request("joue de la musique", true), None, "dedicated music goes to Spotify"); + assert!(rejects_desktop_action("n'ouvre pas Firefox") && rejects_desktop_action("don't open it") && !rejects_desktop_action("ouvre Firefox")); + assert!(computer_task_follow_up("continue") && computer_task_follow_up("open it") && !computer_task_follow_up("sur firefox")); + assert!(conversation_only("Salut Capri !") && !conversation_only("salut, ouvre Firefox")); + assert_eq!(request_text("Capri, s'il te plaît, ouvre Firefox stp"), "ouvre Firefox"); + assert_eq!(parse_intent(&json!({"intent": "task", "usesPrevious": true})), Some(Intent { intent: "task".into(), uses_previous: true })); + assert!(parse_intent(&json!({"intent": "launch", "usesPrevious": true})).is_none()); + } + + #[test] + fn claim_guard() { + assert!(unbacked_action_claim("D'accord, j'ouvre Firefox pour toi.", 0)); + assert!(unbacked_action_claim("Je suis en train de chercher sur Google.", 0)); + assert!(!unbacked_action_claim("D'accord, j'ouvre Firefox pour toi.", 1)); + assert!(!unbacked_action_claim("Firefox est un navigateur.", 0)); + assert!(unbacked_action_claim("I'm opening Firefox now.", 0)); + } +}