Files
capri-core-rust/crates/capri-tools/src/settings_tool.rs
T

184 lines
12 KiB
Rust

//! `settings_control`: status, glitch settings and narrow permission requests.
//! A request never grants anything by itself: only an accepted `ctx.approvals` card does.
use std::sync::Arc;
use std::time::Duration;
use anyhow::{bail, Result};
use async_trait::async_trait;
use capri_agent::tools::{Approval, StateProvider, Tool, ToolContext};
use capri_core::SettingsStore;
use serde_json::{json, Value};
use tokio::sync::mpsc::UnboundedSender;
use crate::{full_access, ToolEvent, ToolsSettings};
const SETTINGS: [&str; 9] = ["glitchEnabled", "glitchStrength", "screenObservation", "fullComputerAccess", "notepad", "calculator", "spotify", "languages", "models"];
const APPROVAL_TIMEOUT: Duration = Duration::from_secs(90);
pub struct SettingsTool {
pub store: Arc<SettingsStore>,
pub events: UnboundedSender<ToolEvent>,
pub external: StateProvider,
}
impl SettingsTool {
fn status(&self) -> Value {
let s: ToolsSettings = self.store.section();
let external = (self.external)();
let mut settings = external.as_object().cloned().unwrap_or_default();
settings.insert("applications".into(), json!({"notepad": s.application_access && s.notepad, "calculator": s.application_access && s.calculator}));
settings.insert("screenObservation".into(), (external["screenObservation"] == true).into());
settings.insert("fullComputerAccess".into(), (full_access(&self.external) && s.application_access).into());
settings.insert("spotify".into(), (s.spotify && s.application_access).into());
json!({"ok": true, "settings": settings})
}
fn emit(&self, event: ToolEvent) {
let _ = self.events.send(event);
}
async fn run(&self, args: &Value, ctx: &ToolContext) -> Result<Value> {
let map = args.as_object().filter(|m| m.keys().all(|k| ["action", "setting", "value"].contains(&k.as_str())));
let Some(map) = map else { bail!("Invalid settings command.") };
let action = map.get("action").and_then(Value::as_str).unwrap_or("");
let setting = map.get("setting").and_then(Value::as_str).filter(|s| SETTINGS.contains(s));
let value = map.get("value");
if action == "status" {
return Ok(self.status());
}
let confirm = |kind: &str, title: &str, detail: String| {
ctx.approvals.confirm(Approval { kind: format!("settings.{kind}"), title: title.into(), detail, timeout: APPROVAL_TIMEOUT })
};
match (action, setting) {
("request", Some("fullComputerAccess")) => {
let enable = match value {
None => true,
Some(Value::Bool(b)) => *b,
_ => bail!("Invalid full computer access request."),
};
if !enable {
self.emit(ToolEvent::Setting { name: "fullComputerAccess", value: false.into() });
return Ok(json!({"ok": true, "enabled": false, "confirmation": "Full computer access is off."}));
}
if full_access(&self.external) {
return Ok(json!({"ok": true, "enabled": true, "alreadyEnabled": true}));
}
let detail = "Capri will be able to use supported file, application, keyboard and mouse actions on your computer without repeated confirmation. Requested actions can change your files and applications. You can revoke this access in Settings at any time. Linux permissions and separate remote-provider settings still apply.";
if !confirm("fullComputerAccess", "Give access to the whole computer?", detail.into()).await {
return Ok(json!({"ok": true, "cancelled": true}));
}
self.emit(ToolEvent::Setting { name: "fullComputerAccess", value: true.into() });
Ok(json!({"ok": true, "enabled": true, "confirmation": "Full computer access enabled."}))
}
("set", Some(name @ ("glitchEnabled" | "glitchStrength"))) => {
let valid = match name {
"glitchEnabled" => value.is_some_and(Value::is_boolean),
_ => value.and_then(Value::as_i64).is_some_and(|v| (0..=100).contains(&v)) && value.and_then(Value::as_f64).is_some_and(|v| v.fract() == 0.0),
};
if !valid {
bail!("Invalid setting value.");
}
let value = value.cloned().unwrap_or_default();
let name = if name == "glitchEnabled" { "glitchEnabled" } else { "glitchStrength" };
self.emit(ToolEvent::Setting { name, value: value.clone() });
Ok(json!({"ok": true, "setting": name, "value": value}))
}
("request", Some(name @ ("screenObservation" | "notepad" | "calculator" | "spotify" | "languages" | "models"))) if value.is_none_or(|v| *v == true) => {
if name == "screenObservation" && (self.external)()["screenObservation"] == true {
return Ok(json!({"ok": true, "enabled": true, "alreadyEnabled": true, "needsApproval": false, "captureStarted": false,
"instruction": "Screen observation is already active for the owner-selected source. No new approval or picker is needed. Answer from the current read-only scene supplied with this turn. If no current scene is available, say that this update is unavailable; do not invent it or call other tools to obtain permission. This call did not start or stop capture."}));
}
if matches!(name, "notepad" | "calculator") {
let label = if name == "notepad" { "the text editor" } else { "the calculator" };
let detail = format!("Allow Capri to open {label}, bring it to the front and read its accessible controls. Revoke this grant in Application access.");
if !confirm(name, "Allow this application?", detail).await {
return Ok(json!({"ok": true, "cancelled": true}));
}
let mut s: ToolsSettings = self.store.section();
if name == "notepad" { s.notepad = true } else { s.calculator = true }
self.store.set_section(&s)?;
return Ok(json!({"ok": true, "confirmation": "Application access enabled."}));
}
let detail = if name == "screenObservation" {
"Choose the exact window or monitor and observation duration. Screen access will not begin until you select a source."
} else {
"Review and apply this setting in its dedicated panel."
};
if !confirm(name, "Open the required controls?", detail.into()).await {
return Ok(json!({"ok": true, "cancelled": true}));
}
let (panel, confirmation) = match name {
"screenObservation" => ("screen", "Choose a window or monitor in Screen snapshot, then press Start observation. Capture has not started yet."),
"spotify" => ("applications", "Opened Application access. Enable Spotify there to connect it."),
"languages" => ("languages", "Opened Languages. Choose the languages, then press Apply languages. No language was changed yet."),
_ => ("models", "Opened Language model. Choose and prepare a model, then apply it. The current model has not changed."),
};
self.emit(ToolEvent::OpenPanel(panel));
let mut result = json!({"ok": true, "applied": false, "setting": name, "confirmation": confirmation});
if name == "screenObservation" {
result["effect"] = "open_screen_picker".into();
result["captureStarted"] = false.into();
}
Ok(result)
}
_ => bail!("That setting needs its dedicated controls."),
}
}
}
const DESCRIPTION: &str = "To enable Full computer access on an explicit owner request, use request with setting fullComputerAccess and value true. The host waits for the real three-second desktop confirmation; chat words cannot approve it. Value false revokes access. A cancelled result ends the task: do not retry or use other tools. For enable-and-execute requests, prefer desktop_control run_task with the complete original goal; it handles confirmation then continues the task. Inspect real Capri settings, change glitch enabled/strength on an explicit owner request, or request narrow permission for a disabled feature. A request proposes approval in the desktop, never enables sensitive access by itself. needsApproval is a pending result, not an error: briefly ask the owner to confirm, then stop calling tools and wait. Never claim enabled until actual success. Glitch strength is 0..100. A question about visible screen contents needs no tool: use the current supplied scene. Do not request access again when observation is active; alreadyEnabled means answer from that scene and stop calling settings tools. For an explicit request to enable disabled screen observation, call action request with setting screenObservation, without value (true is also accepted). Approval only opens the source picker; the owner then selects a source and presses Start observation. No app listing, workspace/configuration file access, test files, terminal commands or tokens are needed. Other settings use their dedicated controls.";
#[async_trait]
impl Tool for SettingsTool {
fn name(&self) -> &str {
"settings_control"
}
fn description(&self) -> String {
DESCRIPTION.into()
}
fn parameters(&self) -> Value {
json!({"type":"object","additionalProperties":false,"required":["action"],"properties":{"action":{"type":"string","enum":["status","set","request"]},"setting":{"type":"string","enum":SETTINGS},"value":{"type":["number","boolean"]}}})
}
/// Covers the owner's approval (Capri: 180 s for fullComputerAccess).
fn timeout(&self) -> Duration {
Duration::from_secs(180)
}
async fn call(&self, args: Value, ctx: ToolContext) -> Value {
self.run(&args, &ctx).await.unwrap_or_else(|e| json!({"ok": false, "error": e.to_string()}))
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::test_support::*;
#[tokio::test]
async fn requests_need_owner_approval() {
let dir = tempfile::tempdir().unwrap();
let (store, _) = store(dir.path());
let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
let tool = SettingsTool { store: store.clone(), events: tx, external: Arc::new(|| json!({"glitchEnabled": true})) };
let refused = tool.call(json!({"action":"request","setting":"calculator"}), ctx("a", answer(false))).await;
assert_eq!(refused, json!({"ok": true, "cancelled": true}));
assert!(!store.section::<ToolsSettings>().calculator);
let approvals = answer(true);
let ok = tool.call(json!({"action":"request","setting":"calculator"}), ctx("b", approvals.clone())).await;
assert_eq!(ok["confirmation"], "Application access enabled.");
assert_eq!(approvals.1.lock()[0].title, "Allow this application?");
let status = tool.call(json!({"action":"status"}), ctx("c", answer(false))).await;
assert_eq!((status["settings"]["applications"]["calculator"].as_bool(), status["settings"]["glitchEnabled"].as_bool()), (Some(true), Some(true)));
let screen = tool.call(json!({"action":"request","setting":"screenObservation"}), ctx("d", answer(true))).await;
assert_eq!(screen["effect"], "open_screen_picker");
assert_eq!(rx.try_recv().unwrap(), ToolEvent::OpenPanel("screen"));
let full = tool.call(json!({"action":"request","setting":"fullComputerAccess","value":true}), ctx("e", answer(false))).await;
assert_eq!(full["cancelled"], true);
assert!(rx.try_recv().is_err(), "a refused request changes nothing");
assert_eq!(tool.call(json!({"action":"set","setting":"glitchStrength","value":101}), ctx("f", answer(true))).await["ok"], false);
assert_eq!(tool.call(json!({"action":"set","setting":"glitchStrength","value":40}), ctx("g", answer(true))).await["value"], 40);
assert_eq!(rx.try_recv().unwrap(), ToolEvent::Setting { name: "glitchStrength", value: 40.into() });
let other = tool.call(json!({"action":"set","setting":"notepad","value":true}), ctx("h", answer(true))).await;
assert_eq!(other["error"], "That setting needs its dedicated controls.");
}
}