capri-tools: add crate root
This commit is contained in:
1 file changed
+208
@@ -0,0 +1,208 @@
|
||||
//! Model tools other than memory, perception and computer control:
|
||||
//! `filesystem_control`, `application_control`, `time_control`, `settings_control`, `spotify_control`,
|
||||
//! plus host-side web search, action receipts, the XDG application catalog and their settings pages.
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
|
||||
use anyhow::Result;
|
||||
use capri_agent::tools::{StateProvider, Tool};
|
||||
use capri_core::{Paths, Section, SettingsStore};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
use sha2::{Digest, Sha256};
|
||||
use tokio::sync::mpsc::UnboundedSender;
|
||||
|
||||
pub mod apps;
|
||||
pub mod calc;
|
||||
pub mod files;
|
||||
pub mod receipts;
|
||||
pub mod settings_tool;
|
||||
pub mod spotify;
|
||||
pub mod time;
|
||||
pub mod ui;
|
||||
pub mod web;
|
||||
|
||||
pub use apps::{catalog, launch, AppEntry};
|
||||
pub use receipts::factual_action_reply;
|
||||
pub use time::{notify, reminder_notification, reminder_speech, TimeService};
|
||||
pub use ui::{settings_ui, timers_ui};
|
||||
pub use web::{web_context, WebContext, WEB_SEARCH_INSTRUCTION};
|
||||
|
||||
/// Settings owned by this crate, stored under `sections["tools"]`.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct ToolsSettings {
|
||||
/// Master switch; when off, application, Spotify and trash actions are paused.
|
||||
pub application_access: bool,
|
||||
/// Fixed application grants: text editor ("Notepad") and calculator.
|
||||
pub notepad: bool,
|
||||
pub calculator: bool,
|
||||
/// `spotify_control` is offered only when true.
|
||||
pub spotify: bool,
|
||||
/// Wake Capri and prepare her voice for reminders (read by the reminder delivery in the app).
|
||||
pub wake_on_reminder: bool,
|
||||
/// Folder grants. The installation scope (`files::INSTALLATION_ID`, root = data dir,
|
||||
/// stored with an empty root) is granted writable by default and stays removed once revoked.
|
||||
pub folders: Vec<files::Scope>,
|
||||
}
|
||||
|
||||
impl Default for ToolsSettings {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
application_access: true,
|
||||
notepad: false,
|
||||
calculator: false,
|
||||
spotify: false,
|
||||
wake_on_reminder: true,
|
||||
folders: vec![files::Scope { id: files::INSTALLATION_ID.into(), root: PathBuf::new(), write: true }],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Section for ToolsSettings {
|
||||
const NAME: &'static str = "tools";
|
||||
}
|
||||
|
||||
/// Events for the app. Never contain file contents or secrets.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum ToolEvent {
|
||||
/// A reminder or timer is due: show `reminder_notification`, the due card, and speak
|
||||
/// `reminder_speech`. The object is the time snapshot row plus `deliveryId` and `overdueMs`.
|
||||
TimeDue(Value),
|
||||
/// Timers changed (created, paused, due...): refresh the timers panel / stopwatch HUD.
|
||||
TimeChanged,
|
||||
/// The owner approved opening a settings panel: `screen`, `applications`, `languages` or `models`.
|
||||
OpenPanel(&'static str),
|
||||
/// The owner approved (or the model set) a setting owned by another crate:
|
||||
/// `glitchEnabled` (bool), `glitchStrength` (0..100), `fullComputerAccess` (bool).
|
||||
Setting { name: &'static str, value: Value },
|
||||
}
|
||||
|
||||
/// Everything the app keeps after building the tools.
|
||||
pub struct Tools {
|
||||
pub list: Vec<Arc<dyn Tool>>,
|
||||
/// Start its scheduler with `time.clone().spawn()` inside the tokio runtime; call `close()` at exit.
|
||||
pub time: Arc<TimeService>,
|
||||
}
|
||||
|
||||
/// Builds the tools. `external` returns live values owned by other crates:
|
||||
/// `{"fullComputerAccess": bool, "screenObservation": bool, "glitchEnabled": bool, "glitchStrength": n, ...}`.
|
||||
pub fn tools(
|
||||
store: Arc<SettingsStore>,
|
||||
paths: &Paths,
|
||||
events: UnboundedSender<ToolEvent>,
|
||||
external: StateProvider,
|
||||
) -> Result<Tools> {
|
||||
let time = Arc::new(TimeService::open(&paths.state().join("time.sqlite"), events.clone())?);
|
||||
let access = Arc::new(files::Access::new(store.clone(), paths, external.clone())?);
|
||||
let list: Vec<Arc<dyn Tool>> = vec![
|
||||
Arc::new(files::FilesystemTool::new(access, paths)?),
|
||||
Arc::new(apps::ApplicationTool { store: store.clone(), external: external.clone() }),
|
||||
Arc::new(time::TimeTool(time.clone())),
|
||||
Arc::new(settings_tool::SettingsTool { store: store.clone(), events, external }),
|
||||
Arc::new(spotify::SpotifyTool::new(store, Arc::new(spotify::Mpris::default()))),
|
||||
];
|
||||
Ok(Tools { list, time })
|
||||
}
|
||||
|
||||
pub(crate) fn sha256_hex(bytes: impl AsRef<[u8]>) -> String {
|
||||
hex::encode(Sha256::digest(bytes))
|
||||
}
|
||||
|
||||
/// SHA-256 of the JSON of `value` with object keys sorted (Capri operation fingerprints).
|
||||
pub(crate) fn fingerprint(value: &Value) -> String {
|
||||
fn sorted(value: &Value) -> Value {
|
||||
match value {
|
||||
Value::Object(map) => {
|
||||
let mut keys: Vec<_> = map.keys().collect();
|
||||
keys.sort();
|
||||
Value::Object(keys.into_iter().map(|k| (k.clone(), sorted(&map[k]))).collect())
|
||||
}
|
||||
Value::Array(items) => Value::Array(items.iter().map(sorted).collect()),
|
||||
other => other.clone(),
|
||||
}
|
||||
}
|
||||
sha256_hex(sorted(value).to_string())
|
||||
}
|
||||
|
||||
pub(crate) fn full_access(external: &StateProvider) -> bool {
|
||||
external()["fullComputerAccess"] == true
|
||||
}
|
||||
|
||||
pub(crate) const PAUSED: &str = "Application access is paused. Turn it on from Capri’s toolbar.";
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) mod test_support {
|
||||
use super::*;
|
||||
use async_trait::async_trait;
|
||||
use capri_agent::tools::{Approval, Approvals, ToolContext};
|
||||
use parking_lot::Mutex;
|
||||
|
||||
/// Records requests and answers with a fixed choice.
|
||||
pub struct Answer(pub bool, pub Mutex<Vec<Approval>>);
|
||||
#[async_trait]
|
||||
impl Approvals for Answer {
|
||||
async fn confirm(&self, request: Approval) -> bool {
|
||||
self.1.lock().push(request);
|
||||
self.0
|
||||
}
|
||||
}
|
||||
|
||||
pub fn ctx(call_id: &str, approvals: Arc<Answer>) -> ToolContext {
|
||||
ToolContext {
|
||||
turn_id: "t".into(),
|
||||
call_id: call_id.into(),
|
||||
approvals,
|
||||
cancel: Default::default(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn answer(accept: bool) -> Arc<Answer> {
|
||||
Arc::new(Answer(accept, Mutex::new(vec![])))
|
||||
}
|
||||
|
||||
pub fn store(dir: &std::path::Path) -> (Arc<SettingsStore>, Paths) {
|
||||
let paths = Paths::under(dir.to_path_buf());
|
||||
paths.ensure().unwrap();
|
||||
(SettingsStore::new(paths.clone(), Default::default()), paths)
|
||||
}
|
||||
|
||||
pub fn no_external() -> StateProvider {
|
||||
Arc::new(|| serde_json::json!({}))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn fingerprint_ignores_key_order() {
|
||||
assert_eq!(fingerprint(&json!({"a":1,"b":{"d":2,"c":3}})), fingerprint(&json!({"b":{"c":3,"d":2},"a":1})));
|
||||
assert_ne!(fingerprint(&json!({"a":1})), fingerprint(&json!({"a":2})));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn constructor_registers_capri_tool_names() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let (store, paths) = test_support::store(dir.path());
|
||||
let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
|
||||
let tools = tools(store, &paths, tx, test_support::no_external()).unwrap();
|
||||
let names: Vec<_> = tools.list.iter().map(|t| t.name().to_string()).collect();
|
||||
assert_eq!(names, ["filesystem_control", "application_control", "time_control", "settings_control", "spotify_control"]);
|
||||
assert!(!tools.list[4].available(), "Spotify is off by default");
|
||||
assert!(paths.state().join("time.sqlite").exists() && paths.data.join("filesystem/operations.sqlite").exists());
|
||||
for tool in &tools.list {
|
||||
assert_eq!(tool.parameters()["required"], json!(["action"]));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_section_grants_installation_scope_and_revocation_persists() {
|
||||
let s: ToolsSettings = serde_json::from_value(json!({"folders": []})).unwrap();
|
||||
assert!(s.folders.is_empty());
|
||||
assert!(s.application_access);
|
||||
assert_eq!(ToolsSettings::default().folders[0].id, files::INSTALLATION_ID);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user