diff --git a/crates/capri-computer/src/agent.rs b/crates/capri-computer/src/agent.rs new file mode 100644 index 0000000..c72f43e --- /dev/null +++ b/crates/capri-computer/src/agent.rs @@ -0,0 +1,699 @@ +//! The observe → plan → act → verify loop (ported from `computer-agent.mjs`): host-made +//! exact launches, checkpoint plan, argument and repetition guards, preflight replanning, +//! navigation verification, independent completion review and a fresh final observation. +//! Uncertain mutations are never retried; every input goes through the durable journal. +use std::collections::HashMap; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::Arc; +use std::time::Duration; + +use async_trait::async_trait; +use parking_lot::Mutex; +use regex::Regex; +use serde_json::{json, Value}; +use sha2::{Digest, Sha256}; +use tokio_util::sync::CancellationToken; + +use crate::browser; +use crate::error::{Fail, APPLICATION_UNAVAILABLE, BROWSER_WINDOW_UNVERIFIED, FOREGROUND_CHANGED, FULLSCREEN_TOOLBAR, OBSERVATION_CHANGED, TARGET_COVERED}; +use crate::journal::OpJournal; +use crate::keys; +use crate::plan::TaskPlan; +use crate::planner::Planner; +use crate::session::ComputerControl; + +static IMAGES_TAB: std::sync::LazyLock = std::sync::LazyLock::new(|| Regex::new(r"(?i)^(?:Images|Картинки|Bilder|Imágenes|Imagens)$").unwrap()); + +pub fn mentions_discord(goal: &str) -> bool { + let g = goal.to_lowercase(); + g.contains("discord") || g.contains("дискорд") +} + +pub use crate::route::owner_app_launch; + +/// Application-level steps (launch, browser draft, open URL) done by the catalog layer. +#[async_trait] +pub trait ApplicationSteps: Send + Sync { + /// `launch {query, windowTitle?}`, `browser_input {query, text}`, `open_url {query, url}`. + async fn run(&self, action: &str, args: Value, cancel: &CancellationToken) -> Value; + /// Number of exact catalog matches for a name (may discover under full access). + async fn exact_matches(&self, name: &str) -> usize; + fn known_apps(&self) -> Vec; +} + +fn signature(view: &Value) -> String { + let targets: Vec = view["targets"].as_array().into_iter().flatten().map(|t| { + let mut t = t.clone(); + t.as_object_mut().map(|o| o.remove("targetId")); + t + }).collect(); + hex::encode(Sha256::digest(json!({"window": view["window"], "scene": view["scene"], "targets": targets}).to_string())) +} + +/// Argument checks before any journaling. +pub fn argument_problem(step: &Value) -> Option<&'static str> { + let action = step["action"].as_str().unwrap_or(""); + let text = step["text"].as_str(); + if matches!(action, "launch" | "browser_input" | "browser_search" | "open_url") && step["query"].as_str().is_none_or(|q| q.trim().is_empty() || q.chars().count() > 80 || q.chars().any(|c| ":/\\".contains(c) || (c as u32) < 0x20)) { + return Some("query must be the application name, for example Firefox. It cannot be empty or a targetId."); + } + if action == "open_url" && step["url"].as_str().and_then(|u| url::Url::parse(u).ok()).is_none_or(|u| !matches!(u.scheme(), "http" | "https") || !u.username().is_empty() || u.password().is_some() || u.as_str().len() > 2048) { + return Some("open_url needs a complete HTTP/HTTPS url without credentials."); + } + if matches!(action, "browser_input" | "browser_search" | "enter_text") && text.is_none_or(|t| t.trim().is_empty() || t.chars().count() > if action == "browser_search" { 1000 } else { 4000 }) { + return Some("This action needs nonempty text with the exact draft/search query. Choose a click targetId if you want to open a visible tab."); + } + if action == "press_keys" { + let keys: Vec = step["keys"].as_array().into_iter().flatten().filter_map(|k| k.as_str().map(String::from)).collect(); + let unique = keys.iter().collect::>().len() == keys.len(); + if keys.is_empty() || keys.len() > 4 || !unique || keys.iter().any(|k| k.to_uppercase() != *k || !keys::agent_key(k)) { + return Some("press_keys needs one to four supported uppercase key names. Use enter_text or browser_input for words."); + } + if step["holdMs"].as_i64().is_some_and(|h| !(0..=2000).contains(&h)) { + return Some("holdMs must be an integer from 0 to 2000."); + } + } + if action == "scroll" && step["amount"].as_i64().is_none_or(|a| a == 0 || a.abs() > 10) { + return Some("scroll needs a nonzero integer amount between -10 and 10."); + } + if action == "click" && (!["left", "right", "middle"].contains(&step["button"].as_str().unwrap_or("left")) || ![1, 2].contains(&step["clickCount"].as_i64().unwrap_or(1))) { + return Some("click supports left, right or middle button and one or two clicks."); + } + if action == "enter_text" && !["append", "replace"].contains(&step["mode"].as_str().unwrap_or("replace")) { + return Some("enter_text mode must be replace or append."); + } + None +} + +/// Owner-facing summary per outcome, EN/RU; Linux wording ("panel"). +pub fn message(key: &str, ru: bool) -> &'static str { + match (key, ru) { + ("challenge", false) => "The search was submitted, but Google requires a human verification. Complete it in the browser, then ask me to continue.", + ("challenge", true) => "Запрос отправлен, но Google просит подтвердить, что ты не робот. Пройди проверку в браузере, затем попроси меня продолжить.", + ("sign_in", false) => "Netflix opened its sign-in page. Sign in, then ask me to continue.", + ("sign_in", true) => "Netflix открыл страницу входа. Войди в аккаунт, затем попроси меня продолжить.", + ("profile", false) => "Netflix is asking you to choose a profile. Choose one, then ask me to continue.", + ("profile", true) => "Netflix просит выбрать профиль. Выбери его, затем попроси меня продолжить.", + ("navigation", false) => "The search was submitted, but I could not verify that the results loaded. Please check the browser page.", + ("navigation", true) => "Запрос отправлен, но загрузку результатов подтвердить не удалось. Проверь страницу в браузере.", + ("window", false) => "I could not select the intended window. Bring it to the front and try again.", + ("window", true) => "Не смогла однозначно выбрать окно. Выведи нужное окно на передний план и повтори запрос.", + ("covered", false) => "The control under the pointer changed, so I did not click. Check that the intended button is visible.", + ("covered", true) => "Под курсором оказался другой элемент, поэтому я не нажала. Проверь, видна ли нужная кнопка.", + ("foreground", false) => "The foreground window changed, so I stopped sending input. Check which window is active.", + ("foreground", true) => "Активное окно сменилось, и я остановила ввод. Проверь, какое окно сейчас открыто.", + ("launch", false) => "I could not open or focus the requested app. Check whether it is installed.", + ("launch", true) => "Не смогла открыть или активировать нужное приложение. Проверь, установлено ли оно.", + ("stalled", false) => "Stopped because further actions were not making progress. I need help with the current window.", + ("stalled", true) => "Остановилась: дальнейшие действия не дают результата. Нужна помощь с текущим окном.", + ("discord", false) => "Specify the Discord action, server and channel.", + ("discord", true) => "Уточни действие, сервер и канал Discord.", + (_, false) => "I could not verify that all requested steps were completed. Please check the current window.", + (_, true) => "Не смогла подтвердить выполнение всех шагов. Проверь текущее окно.", + } +} + +fn result(ok: bool, status: &str, steps: u32, summary: &str) -> Value { + json!({"ok": ok, "status": status, "steps": steps, "summary": summary}) +} + +pub struct ComputerAgent { + pub control: Arc, + pub planner: Planner, + pub apps: Arc, + pub journal: Arc, + /// Conversation language (`ru` selects Russian summaries). + pub language: Arc String + Send + Sync>, + running: AtomicBool, + trace: Mutex>, + last: Mutex, + /// Progress phases `{type:"computer.task", active, phase, steps}`. + pub progress: tokio::sync::watch::Sender, +} + +impl ComputerAgent { + pub fn new(control: Arc, planner: Planner, apps: Arc, journal: Arc, language: Arc String + Send + Sync>) -> Self { + Self { control, planner, apps, journal, language, running: AtomicBool::new(false), trace: Mutex::default(), last: Mutex::new(Value::Null), progress: tokio::sync::watch::Sender::new(json!({"type": "computer.task", "active": false, "phase": "idle", "steps": 0})) } + } + + pub fn running(&self) -> bool { + self.running.load(Ordering::SeqCst) + } + + fn phase(&self, phase: &str, steps: u32) { + self.progress.send_replace(json!({"type": "computer.task", "active": !matches!(phase, "completed" | "stopped"), "phase": phase, "steps": steps})); + } + + /// Metadata only: never goal, titles, typed text or model output. + pub fn diagnostics(&self) -> Value { + json!({"active": self.running(), "lastOutcome": *self.last.lock(), "actions": *self.trace.lock()}) + } + + /// Runs one owner task in turn `turn`. `previous` = earlier owner task (<= 10 min) for references. + pub async fn run(&self, goal: &str, turn: &str, previous: Option<&str>, cancel: &CancellationToken) -> Value { + if self.running.swap(true, Ordering::SeqCst) { + return json!({"ok": false, "error": "A computer task is already running."}); + } + self.trace.lock().clear(); + let outcome = self.run_inner(goal.trim(), turn, previous, cancel).await; + self.control.stop(false).await; + let steps = outcome["steps"].as_u64().unwrap_or(0) as u32; + self.phase(if outcome["status"] == "completed" { "completed" } else { "stopped" }, steps); + *self.last.lock() = json!({"status": outcome["status"], "steps": steps, "at": capri_perception::now_ms()}); + tracing::info!("Computer task: {}", self.diagnostics()); + self.running.store(false, Ordering::SeqCst); + outcome + } + + async fn run_inner(&self, goal: &str, turn: &str, previous: Option<&str>, outer: &CancellationToken) -> Value { + let ru = (self.language)() == "ru"; + if goal.is_empty() || goal.chars().count() > 8000 || goal.contains('\0') { + return json!({"ok": false, "error": "Describe the owner task."}); + } + if let Err(e) = self.control.begin(goal, turn, 80).await { + return json!({"ok": false, "status": "incomplete", "steps": 0, "summary": e.message}); + } + let cancel = outer.child_token(); + if let Some(t) = self.control.cancel_token() { + let c = cancel.clone(); + tokio::spawn(async move { + t.cancelled().await; + c.cancel(); + }); + } + let mut plan = TaskPlan::default(); + let mut history: Vec = vec![]; + let mut repeated: HashMap = HashMap::new(); + // Label of the control clicked successfully at the previous step. + let mut last_click: Option = None; + let (mut steps, mut failures, mut retries) = (0u32, 0u32, 0u32); + let mut correction = String::new(); + let mut use_vision = false; + let mut pending: Option<(bool, String)> = None; + let opening = owner_app_launch(goal); + let mut host_launch = match &opening { + Some((name, _)) if self.apps.exact_matches(name).await == 1 => Some(json!({"action": "launch", "query": name, "summary": ""})), + _ => None, + }; + let draft_only = browser::draft_only(goal); + for _decision in 0..100 { + if cancel.is_cancelled() { + return result(false, "cancelled", steps, if ru { "Остановлено." } else { "Stopped." }); + } + self.phase("observing", steps); + let view = match self.control.observe(use_vision).await { + Ok(v) => { + retries = 0; + v + } + Err(e) if e.code == Some(APPLICATION_UNAVAILABLE) && steps == 0 && history.is_empty() => json!({"observationUnavailable": true, "window": {}, "targets": [], "scene": null, "screenAvailable": false}), + Err(e) if matches!(e.code, Some(OBSERVATION_CHANGED | APPLICATION_UNAVAILABLE)) && retries < 2 => { + retries += 1; + tokio::time::sleep(Duration::from_millis(200)).await; + continue; + } + Err(e) => return self.failure(&e, steps, ru), + }; + use_vision = false; + if let Some((ok, before)) = pending.take() { + plan.record_outcome(ok, before != signature(&view), false); + } + if plan.exhausted() { + return result(false, "stalled", steps, message("stalled", ru)); + } + // Pending navigation: wait while loading, stop on obstacles that need the owner. + let mut nav_correction = String::new(); + if let Some(nav) = history.iter_mut().rev().find(|s| s["ok"] == true && s["navigationRequested"] == true) + && nav["navigationVerified"] != true + { + let wid = nav["windowId"].as_str().unwrap_or("").to_string(); + let status = match nav["navigationUrl"].as_str() { + Some(u) => browser::navigation_state(&view, &wid, u), + None => browser::search_state(&view, &wid, nav["searchQuery"].as_str().unwrap_or("")), + }; + let age = capri_perception::now_ms() - nav["at"].as_i64().unwrap_or(0); + if status == "ready" { + nav["navigationVerified"] = json!(true); + } else if status == "loading" && browser::navigation_obstacle(&view).is_none() && nav["navigationRecovery"] != true && age < 20_000 { + self.phase("verifying", steps); + tokio::time::sleep(Duration::from_millis(700)).await; + continue; + } else if matches!(status, "challenge" | "sign_in" | "profile") { + return result(false, "needs_user", steps, message(status, ru)); + } else { + if nav["navigationRecovery"] != true { + nav["navigationRecovery"] = json!(true); + plan.record_outcome(false, true, true); + } + nav_correction = format!("Navigation has already been requested but is not verified ({status}; {}). Do not repeat the delivered navigation blindly. Revise the remaining task plan using the current observation. Restore the intended browser if another app is foreground; inspect and resolve an ordinary blocking dialog or wait/retry a confirmed failed page load. Prefer rejecting optional cookies. Never bypass a security warning, CAPTCHA or sign-in; ask_user for those. Finish only after the requested page and remaining owner steps are verified.", browser::navigation_obstacle(&view).unwrap_or("no ready page evidence")); + } + } + self.phase("planning", steps); + let recent: Vec = history.iter().rev().take(16).rev().cloned().collect(); + let completed: Vec = history.iter().rev().skip(16).rev().filter(|s| s["ok"] == true).map(|s| json!({"action": s["action"], "query": s["query"], "target": s["target"], "text": s["text"].as_str().map(|t| t.chars().take(160).collect::()), "keys": s["keys"]})).collect(); + let joined = [nav_correction.as_str(), correction.as_str()].iter().filter(|c| !c.is_empty()).cloned().collect::>().join(" "); + let mut context = json!({ + "originalOwnerGoal": goal, "discordTaskAllowed": false, "language": (self.language)(), "currentObservation": view, + "completedSteps": completed, "actualSteps": recent, "taskPlan": plan.context(), + "correction": joined, + "knownApplications": self.apps.known_apps().into_iter().map(|n| json!({"name": n})).collect::>(), + }); + if let Some(p) = previous { + context["previousOwnerTaskForReferencesOnly"] = json!(p); + } + let exact_launch = host_launch.take(); + let is_host = exact_launch.is_some(); + let mut step = match exact_launch { + Some(s) => s, + None => match self.planner.decide(&context, false, &cancel).await { + Ok(s) => s, + Err(e) => { + if cancel.is_cancelled() { + continue; + } + failures += 1; + if failures >= 2 { + self.trace.lock().push(json!({"action": "plan", "outcome": "planning_failed"})); + tracing::info!("Computer planning failed: {}", e.to_string().chars().take(120).collect::()); + return result(false, "incomplete", steps, message("unverified", ru)); + } + correction = "The last plan was incomplete or invalid. Return one valid JSON step.".into(); + continue; + } + }, + }; + if !is_host + && let Some(problem) = plan.update(&step, |e| browser::evidence_exists(&view, e)) + { + correction = problem.into(); + failures += 1; + if failures >= 3 { + return result(false, "incomplete", steps, message("unverified", ru)); + } + continue; + } + context["taskPlan"] = plan.context(); + let action = step["action"].as_str().unwrap_or("").to_string(); + if view["observationUnavailable"] == true && !matches!(action.as_str(), "launch" | "open_url" | "ask_user") { + correction = "No controllable window is available. Only launch an application or use open_url for a directly requested website, or ask_user. No clicks, draft typing, existing-tab input, completion claims or screen observations are available until a real target is observed.".into(); + failures += 1; + if failures >= 2 { + return result(false, "needs_user", steps, message("window", ru)); + } + continue; + } + if action == "browser_input" && !draft_only + && let Some(text) = step["text"].as_str().map(String::from) + { + let is_url = text.starts_with("http://") || text.starts_with("https://"); + if is_url && browser::navigation_goal(goal) { + step["action"] = json!("open_url"); + step["url"] = json!(text); + } else if !is_url && browser::web_search_goal(goal) && !browser::site_search(goal) { + step["action"] = json!("browser_search"); + } + } + let action = step["action"].as_str().unwrap_or("").to_string(); + if let Some(problem) = argument_problem(&step) { + correction = problem.into(); + self.trace.lock().push(json!({"action": action, "outcome": "invalid_arguments"})); + failures += 1; + if failures >= 3 { + return result(false, "incomplete", steps, message("unverified", ru)); + } + continue; + } + // TODO: Discord GUI tasks are not ported; raw input into Discord for a Discord goal is left to the owner. + if mentions_discord(goal) && view["window"]["applicationKind"] == "discord" && matches!(action.as_str(), "click" | "enter_text" | "press_keys" | "drag" | "scroll") { + return result(false, "needs_user", steps, message("discord", ru)); + } + let targets = view["targets"].as_array().cloned().unwrap_or_default(); + let selected = targets.iter().find(|t| t["targetId"] == step["targetId"]).cloned(); + if action == "enter_text" && selected.as_ref().is_some_and(|t| t["editable"] == true && t["untrustedValue"] == step["text"]) { + correction = "The requested text is ALREADY in the field. Choose a missing step, finish with evidence, or ask_user. Repeated input was not executed.".into(); + failures += 1; + if failures >= 2 { + return result(false, "stalled", steps, message("stalled", ru)); + } + continue; + } + if action == "finish" { + match self.review_finish(goal, &context, &view, &step, &plan, &cancel).await { + Ok(summary) => return json!({"ok": true, "status": "completed", "steps": steps, "verified": true, "summary": summary}), + Err(c) => { + correction = c; + failures += 1; + if failures >= 3 { + return result(false, "incomplete", steps, message("unverified", ru)); + } + continue; + } + } + } + if action == "ask_user" { + return result(false, "needs_user", steps, step["summary"].as_str().unwrap_or("")); + } + if draft_only && (matches!(action.as_str(), "browser_search" | "open_url") || (action == "press_keys" && step["keys"].as_array().is_some_and(|k| k.contains(&json!("ENTER"))))) { + correction = "The owner explicitly prohibited Enter/submission/navigation. This key action was blocked. Type the requested draft without sending it.".into(); + failures += 1; + if failures >= 2 { + return result(false, "incomplete", steps, message("unverified", ru)); + } + continue; + } + let key = format!("{}:{}", signature(&view), json!({"action": action, "target": selected.as_ref().map(|t| t["untrustedLabel"].clone()), "query": step["query"], "text": step["text"], "keys": step["keys"], "button": step["button"], "clickCount": step["clickCount"], "mode": step["mode"], "amount": step["amount"], "url": step["url"], "to": step["toTargetId"]})); + let count = repeated.entry(key).or_default(); + *count += 1; + if *count > 2 { + return result(false, "stalled", steps, message("stalled", ru)); + } + let label = selected.as_ref().and_then(|t| t["untrustedLabel"].as_str()).unwrap_or("").to_string(); + if action == "click" && !label.is_empty() && last_click.as_deref() == Some(label.as_str()) { + // Clicking the same control twice in a row repeats the action (a song restarts). + correction = format!("You already clicked \"{label}\" successfully at the previous step. Clicking it again would repeat that action (for media it restarts playback). Observe its effect instead: if the requested result is now visible or playing (for example a player bar with the title or a pause button), finish with that evidence."); + use_vision = true; + last_click = None; + failures += 1; + if failures >= 3 { + return result(false, "incomplete", steps, message("unverified", ru)); + } + continue; + } + correction.clear(); + if action == "observe" { + use_vision = true; + continue; + } + if action == "wait" { + tokio::time::sleep(Duration::from_millis(700)).await; + continue; + } + if matches!(action.as_str(), "move_pointer" | "click" | "enter_text" | "drag") { + let valid = |id: &Value, editable: bool| targets.iter().any(|t| t["targetId"] == *id && (!editable || t["editable"] == true)); + if !valid(&step["targetId"], action == "enter_text") || (action == "drag" && !valid(&step["toTargetId"], false)) { + correction = "The target is not a current usable control. Copy an exact targetId from currentObservation, or observe for visual analysis. Never invent an ID.".into(); + if view["screenAvailable"] != true && failures == 0 { + use_vision = true; + } + failures += 1; + if failures >= 3 { + return result(false, "incomplete", steps, message("unverified", ru)); + } + continue; + } + } + self.phase("acting", steps); + let before = signature(&view); + let outcome = if matches!(action.as_str(), "launch" | "browser_input" | "browser_search" | "open_url") { + Ok(self.application_step(&step, goal, &view, &cancel).await) + } else { + let mut args = json!({"action": action}); + for k in ["targetId", "toTargetId", "modifiers", "text", "keys", "amount"] { + if !step[k].is_null() { + args[k] = step[k].clone(); + } + } + match action.as_str() { + "click" => { + args["button"] = step.get("button").cloned().unwrap_or(json!("left")); + args["clickCount"] = step.get("clickCount").cloned().unwrap_or(json!(1)); + } + "enter_text" => args["mode"] = step.get("mode").cloned().unwrap_or(json!("replace")), + "press_keys" => { + args["observationId"] = view["observationId"].clone(); + args["holdMs"] = step.get("holdMs").cloned().unwrap_or(json!(0)); + } + "scroll" => args["observationId"] = view["observationId"].clone(), + _ => {} + } + let control = self.control.clone(); + let a = args.clone(); + self.journal.operation(&uuid::Uuid::new_v4().to_string(), &args, || async move { control.input(&a).await.map_err(anyhow::Error::new) }).await.map_err(Fail::from) + }; + let mut res = match outcome { + Ok(r) => { + last_click = (action == "click" && r["ok"] == true && !label.is_empty()).then(|| label.clone()); + r + } + Err(e) if e.replannable() && failures < 2 => { + failures += 1; + plan.record_outcome(false, true, true); + if e.code == Some(TARGET_COVERED) { + use_vision = true; + } + self.trace.lock().push(json!({"action": action, "outcome": "preflight_rejected", "code": e.code})); + correction = match e.code { + Some(FOREGROUND_CHANGED) => "The foreground or keyboard focus changed before input. Observe the current window, then restore the intended app using launch. Verify the original target before choosing the missing action. Do not type in a different app.", + Some(FULLSCREEN_TOOLBAR) => "The browser address bar is hidden in fullscreen. No text was sent. Press F11 once to restore the toolbar and observe before navigating. Leave fullscreen only for the requested navigation, then restore it if the owner requires it.", + _ => "The intended target became stale, covered or redirected focus. No text or click was sent. Observe current controls and choose the actual visible target; if necessary inspect the screenshot. Use open_url for Google home if a new-tab search proxy redirects to the address bar.", + } + .into(); + continue; + } + Err(e) => return self.failure(&e, steps, ru), + }; + if res["ok"] == true && action == "click" && browser::page_state(&view).is_some_and(|p| p["results"] == "web") && selected.as_ref().is_some_and(|t| IMAGES_TAB.is_match(t["untrustedLabel"].as_str().unwrap_or("").trim())) { + res["navigationRequested"] = json!(true); + res["searchQuery"] = browser::page_state(&view).unwrap()["query"].clone(); + res["windowId"] = view["window"]["windowId"].clone(); + } + let succeeded = res["ok"] == true && res["needsWindow"] != true && res["needsApproval"] != true && res["windowVerified"] != false && res["focused"] != false; + self.trace.lock().push(json!({"action": action, "outcome": if res["needsWindow"] == true { "window_selection" } else if succeeded { "applied" } else { "not_applied" }})); + if res["needsWindow"] == true { + if res["inputPerformed"] != false || action == "browser_input" { + return result(false, "needs_user", steps, message("window", ru)); + } + failures += 1; + if failures >= 3 { + return result(false, "needs_user", steps, message("window", ru)); + } + plan.record_outcome(false, true, true); + correction = "No input was performed: several application windows need a deliberate selection. Revise the remaining plan. For a requested website, open_url can navigate directly without a preliminary launch. For an existing draft or explicitly named tab, observe/restore that exact window; never type into an arbitrary window. Ask the owner only if the requested existing window cannot be identified.".into(); + continue; + } + if view["observationUnavailable"] == true && !succeeded { + return result(false, "needs_user", steps, message("window", ru)); + } + if succeeded { + steps += 1; + failures = 0; + } + if succeeded && is_host && opening.as_ref().is_some_and(|o| o.1) && res["windowId"].is_string() && res["focused"] == true { + let name = &opening.as_ref().unwrap().0; + return json!({"ok": true, "status": "completed", "steps": steps, "verified": true, "summary": if ru { format!("Открыла {name}.") } else { format!("Opened {name}.") }}); + } + let mut entry = json!({"action": action, "ok": succeeded, "confirmation": res["confirmation"], "windowId": res["windowId"], "at": capri_perception::now_ms()}); + for k in ["query", "text", "keys"] { + if !step[k].is_null() { + entry[k] = step[k].clone(); + } + } + if let Some(t) = &selected { + entry["target"] = t["untrustedLabel"].clone(); + } + for k in ["navigationRequested", "navigationUrl", "searchQuery", "submitted", "searchSubmitted", "effect"] { + if !res[k].is_null() { + entry[k] = res[k].clone(); + } + } + history.push(entry); + if !succeeded { + if res["error"]["code"].as_str().is_some_and(|c| c == "missing_app_id" || c == "unknown_app_id" || c == "app_not_found") && is_host { + return result(false, "needs_user", steps, message("launch", ru)); + } + failures += 1; + if failures >= 3 { + return result(false, "incomplete", steps, message(if action == "launch" { "launch" } else { "unverified" }, ru)); + } + correction = if res["focused"] == false { "The app is open but did not take focus. Observe and restore it before typing.".into() } else { res.to_string().chars().take(3000).collect() }; + } + pending = Some((succeeded, before)); + } + result(false, "limit", steps, message("stalled", ru)) + } + + fn failure(&self, e: &Fail, steps: u32, ru: bool) -> Value { + let key = match e.code { + Some(TARGET_COVERED) => "covered", + Some(APPLICATION_UNAVAILABLE) => "window", + Some(BROWSER_WINDOW_UNVERIFIED) => "navigation", + Some(FOREGROUND_CHANGED) => "foreground", + _ if e.message.contains("cover") => "covered", + _ => "unverified", + }; + self.trace.lock().push(json!({"action": "native", "outcome": "failed", "code": e.code})); + result(false, "incomplete", steps, message(key, ru)) + } + + /// Finish: no open checkpoints, display requirement, evidence now, independent review, then a + /// fresh observation of the same window still showing the evidence. + async fn review_finish(&self, goal: &str, context: &Value, view: &Value, step: &Value, plan: &TaskPlan, cancel: &CancellationToken) -> Result { + if !plan.remaining().is_empty() { + return Err("The task plan still has unverified checkpoints. Complete the missing owner steps or mark existing checkpoints with exact current evidence in verifiedCheckpoints before finish. If a checkpoint is obsolete, revise only the remaining plan; do not add new work beyond the owner goal.".into()); + } + if !browser::display_requirement_met(goal, view) { + return Err(if view["window"]["modal"] == true { "A modal dialog is still open. The owner goal is not complete: enter the required values and confirm it, then verify the result in the main application. An import/save dialog title is not evidence that its operation completed." } else { "The requested image/fullscreen state is not verified. Open the image preview, then use its fullscreen control or F11 and verify window.fullscreen before finishing." }.into()); + } + if !browser::evidence_exists(view, step["evidence"].as_str().unwrap_or("")) { + return Err("Completion is not proven. Quote actual current evidence or complete the missing step.".into()); + } + self.phase("verifying", self.control.steps()); + let mut claim = context.clone(); + claim["completionClaim"] = step["summary"].clone(); + let review = self.planner.decide(&claim, true, cancel).await.map_err(|_| "The completion review did not provide real evidence.".to_string())?; + if review["action"] == "continue" { + return Err(review["summary"].as_str().unwrap_or("").to_string()); + } + let evidence = review["evidence"].as_str().unwrap_or(""); + if !browser::evidence_exists(view, evidence) { + return Err("The completion review did not provide real evidence.".into()); + } + let fresh = self.control.observe(view["screenAvailable"] == true).await.map_err(|_| "The window changed during completion review. Recheck the new observation before doing anything.".to_string())?; + if fresh["window"]["windowId"] != view["window"]["windowId"] || !browser::display_requirement_met(goal, &fresh) || !browser::evidence_exists(&fresh, evidence) { + return Err("The window changed during completion review. Recheck the new observation before doing anything.".into()); + } + Ok(review["summary"].as_str().unwrap_or("").to_string()) + } + + /// Launch, drafts, searches and URLs through the catalog; searches and + /// URLs are direct navigations whose page is verified on the next decisions. + async fn application_step(&self, step: &Value, goal: &str, view: &Value, cancel: &CancellationToken) -> Value { + let mut args = json!({"query": step["query"]}); + if let Some(t) = step["windowTitle"].as_str().filter(|t| goal.to_lowercase().contains(&t.to_lowercase())) { + args["windowTitle"] = json!(t); // model-invented titles are discarded + } + let action = step["action"].as_str().unwrap_or(""); + match action { + "launch" => self.apps.run("launch", args, cancel).await, + "browser_input" => { + args["text"] = step["text"].clone(); + let mut r = self.apps.run("browser_input", args, cancel).await; + r["effect"] = json!("Draft only. NO keys were pressed; NO search or navigation was performed."); + r + } + "open_url" | "browser_search" => { + if action == "browser_search" && browser::site_search(goal) { + return json!({"ok": false, "inputPerformed": false, "instruction": "This goal asks to search inside a website. Open that site with open_url and use its own visible search field instead of a Google search."}); + } + let page_fields = view["targets"].as_array().into_iter().flatten().filter(|t| t["browserSearch"] == true && t["browserAddress"] != true).count(); + let text = step["text"].as_str().unwrap_or("").trim().to_string(); + let url = if action == "open_url" { + step["url"].as_str().unwrap_or("").to_string() + } else if browser::requires_page_search(goal) && page_fields != 1 { + "https://www.google.com/".to_string() + } else { + let mut u = url::Url::parse("https://www.google.com/search").unwrap(); + u.query_pairs_mut().append_pair("q", &text); + u.to_string() + }; + args["url"] = json!(url); + let mut r = self.apps.run("open_url", args, cancel).await; + if r["ok"] == true && r["navigationRequested"] == true { + if r["windowId"].is_null() { + return json!({"ok": false, "error": {"code": BROWSER_WINDOW_UNVERIFIED, "message": "The browser window could not be verified."}, "inputPerformed": true}); + } + r["submitted"] = json!(true); + if url.starts_with("https://www.google.com/search") { + r["searchSubmitted"] = json!(true); + r["searchQuery"] = json!(text); + } else if url == "https://www.google.com/" && action == "browser_search" { + r["searchSubmitted"] = json!(false); + r["navigationUrl"] = json!(url); + r["confirmation"] = json!("Opened the Google home page. The requested search is NOT submitted yet. Use its visible page search field next."); + } else { + r["navigationUrl"] = json!(url); + } + } + r + } + _ => json!({"ok": false, "error": "Unsupported application step."}), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::native::tests::Fake; + use crate::planner::tests::{reply, Scripted}; + use crate::session::tests::control; + + struct Apps; + #[async_trait] + impl ApplicationSteps for Apps { + async fn run(&self, action: &str, _: Value, _: &CancellationToken) -> Value { + json!({"ok": true, "launched": action == "launch", "windowVerified": true, "focused": true, "windowId": "7", "confirmation": "Opened the application."}) + } + async fn exact_matches(&self, name: &str) -> usize { + usize::from(name == "Kate") + } + fn known_apps(&self) -> Vec { + vec!["Kate".into()] + } + } + + #[test] + fn launch_phrases_and_arguments() { + assert_eq!(owner_app_launch("Capri, open Kate"), Some(("Kate".into(), true))); + assert_eq!(owner_app_launch("please launch Firefox and then search cats"), Some(("Firefox".into(), false))); + assert_eq!(owner_app_launch("открой Steam"), Some(("Steam".into(), true))); + assert!(owner_app_launch("open it").is_none() && owner_app_launch("what is open?").is_none()); + assert!(argument_problem(&json!({"action": "launch", "query": "a/b"})).is_some()); + assert!(argument_problem(&json!({"action": "press_keys", "keys": ["ESCAPE"]})).is_some()); + assert!(argument_problem(&json!({"action": "press_keys", "keys": ["ctrl"]})).is_some(), "uppercase only"); + assert!(argument_problem(&json!({"action": "open_url", "query": "Firefox", "url": "https://u:p@x.org"})).is_some()); + assert!(argument_problem(&json!({"action": "click", "targetId": "x"})).is_none()); + assert!(message("covered", true).starts_with("Под курсором")); + } + + fn agent(fake: &Arc, replies: Vec>) -> (ComputerAgent, tempfile::TempDir) { + let (control, _, _) = control(fake, true); + let dir = tempfile::tempdir().unwrap(); + let journal = Arc::new(OpJournal::open(&dir.path().join("ops.sqlite")).unwrap()); + (ComputerAgent::new(control, Planner::new(Scripted::new(replies), vec!["Firefox".into()]), Arc::new(Apps), journal, Arc::new(|| "en".into())), dir) + } + + #[tokio::test] + async fn exact_launch_needs_no_model() { + let fake = Fake::new(); + let (a, _d) = agent(&fake, vec![]); + let r = a.run("open Kate", "turn-1", None, &CancellationToken::new()).await; + assert_eq!(r["status"], "completed"); + assert_eq!(r["summary"], "Opened Kate."); + assert!(!a.control.active(), "session stopped after the task"); + } + + /// Reads the decorated ids from each request like a real model would. + struct Adaptive(Mutex); + #[async_trait] + impl crate::planner::PlannerModel for Adaptive { + async fn chat(&self, body: Value, _: Duration, _: &CancellationToken) -> Result { + let user = body["messages"][1]["content"].as_str().unwrap(); + let state: Value = serde_json::from_str(user.split("\n\nORIGINAL OWNER GOAL").next().unwrap()).unwrap(); + let field = state["currentObservation"]["targets"].as_array().unwrap().iter().find(|t| t["browserSearch"] == true).unwrap()["targetId"].clone(); + let review = body["messages"][0]["content"].as_str().unwrap().starts_with("Review"); + let n = { let mut n = self.0.lock(); *n += 1; *n }; + let plan = json!([{"id": "type", "label": "Type query", "successCriterion": "query in field"}]); + reply(if review { + json!({"complete": true, "evidence": "cats", "summary": "The query is typed.", "missing": ""}) + } else if n == 1 { + json!({"action": "enter_text", "targetId": field, "text": "cats", "summary": "Type.", "plan": plan}) + } else { + json!({"action": "finish", "evidence": "cats", "summary": "Typed.", "verifiedCheckpoints": [{"id": "type", "evidence": "cats"}]}) + }) + } + } + + #[tokio::test] + async fn type_then_reviewed_finish() { + let fake = Fake::new(); + let (mut a, _d) = agent(&fake, vec![]); + a.planner = Planner::new(Arc::new(Adaptive(Mutex::new(0))), vec![]); + // (A "search field" goal on a Google page would keep finish blocked until a search is submitted.) + let r = a.run("type cats in the text field without pressing enter", "turn-2", None, &CancellationToken::new()).await; + assert_eq!(r["status"], "completed", "{r}"); + assert_eq!(r["summary"], "The query is typed."); + assert!(fake.events.lock().contains(&"type cats".to_string())); + assert_eq!(a.journal.recent().unwrap().len(), 1, "the input went through the journal"); + } +}