From f9ebae49c0176c0f2e433a9686031a2dd7bfe40e Mon Sep 17 00:00:00 2001 From: David Mann Date: Fri, 20 Nov 2026 15:00:40 +0100 Subject: [PATCH] craft-control agents: default agent folder in Documents and the agent_folders tool (#2548) An empty agent folder setting meant no file access, so an agent reached through the launcher's MCP entry could neither open nor save a file, and nothing told it where to put files. - default_folder(app): Documents/ArtCraft/Agents/ (dirs::document_dir, else ~/Documents), only for plain app names. - AgentSettings::folders / folders_with: the person's own folders win; an empty setting falls back to the default, created on first use. - The live client's headless sessions use it (LiveConfig::default_folder). - FOLDERS_TOOL, folders_tool, folders_answer: the tool each app offers so an agent learns the folders it may use. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 1 + crates/control/Cargo.toml | 4 +- crates/control/src/agents/folders.rs | 196 +++++++++++++++++++++++++++ crates/control/src/agents/live.rs | 25 +++- crates/control/src/agents/mod.rs | 9 ++ crates/control/tests/agents.rs | 30 ++++ 6 files changed, 257 insertions(+), 8 deletions(-) create mode 100644 crates/control/src/agents/folders.rs diff --git a/Cargo.lock b/Cargo.lock index a726aa5ee..1a5ba0899 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1714,6 +1714,7 @@ dependencies = [ "craft-ai-agents", "craft-atomic", "craft-flags", + "dirs", "getrandom 0.3.4", "log", "proptest", diff --git a/crates/control/Cargo.toml b/crates/control/Cargo.toml index 5c4a90242..3e756aff7 100644 --- a/crates/control/Cargo.toml +++ b/crates/control/Cargo.toml @@ -14,7 +14,7 @@ workspace = true default = [] # AI agents in the open window (desktop): the ArtCraft Launcher's switch, the connection file and # the `-cli mcp` side that finds the open window. The agent settings build without it. -agents = ["dep:craft-ai-agents", "dep:craft-atomic", "dep:craft-flags", "dep:log"] +agents = ["dep:craft-ai-agents", "dep:craft-atomic", "dep:craft-flags", "dep:dirs", "dep:log"] [dependencies] serde = { workspace = true } @@ -28,6 +28,8 @@ getrandom = "0.3" craft-ai-agents = { workspace = true, optional = true } craft-atomic = { workspace = true, optional = true } craft-flags = { workspace = true, optional = true } +# The system's Documents folder for the default agent folder, on every desktop system (MIT OR Apache-2.0). +dirs = { version = "7", optional = true } log = { workspace = true, optional = true } [dev-dependencies] diff --git a/crates/control/src/agents/folders.rs b/crates/control/src/agents/folders.rs new file mode 100644 index 000000000..7d1c6a193 --- /dev/null +++ b/crates/control/src/agents/folders.rs @@ -0,0 +1,196 @@ +//! The folder agents open and save files in when the person set none, and the tool that tells an +//! agent which folders it may use. +//! +//! Each app has its own default folder, `Documents/ArtCraft/Agents/`, in the system's +//! Documents folder on every desktop system, so people find what an agent made. The person's own +//! folder settings ([`AgentSettings::read_root`], [`AgentSettings::write_root`]) win; an empty one +//! falls back to the default folder ([`AgentSettings::folders`]). +//! +//! An agent learns the folders from the app's own MCP tool [`FOLDERS_TOOL`], answered with +//! [`folders_answer`]. The ArtCraft gateway passes app tools through, so the agent finds it by +//! searching for "folder" or "files", and the app reports the folders it really uses. + +use std::path::{Path, PathBuf}; + +use serde_json::{Value, json}; + +use super::AgentSettings; + +/// The folders under Documents that hold every app's default agent folder. +pub const DEFAULT_FOLDER_PARENTS: [&str; 2] = ["ArtCraft", "Agents"]; + +/// Longest app name a default folder is made for; app names are short catalog names. +const MAX_APP_NAME: usize = 64; + +/// The MCP tool an app offers to tell agents its folders. +pub const FOLDERS_TOOL: &str = "agent_folders"; + +/// [`FOLDERS_TOOL`]'s description, for the app's tool list. +pub const FOLDERS_TOOL_DESCRIPTION: &str = "Where this app opens and saves files for agents. Put files the app should open in \ + read_folder (or a folder below it) and find what it saves in write_folder. Both are usually the app's agent folder in \ + Documents/ArtCraft/Agents; the person may have set others. null means the app has no such folder now."; + +/// The folders an agent session may open from and save to, after the default is filled in. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +#[non_exhaustive] +pub struct AgentFolders { + /// The folder files may be opened from. + pub read: Option, + /// The folder files may be saved to. + pub write: Option, +} + +/// The app's default agent folder, `Documents/ArtCraft/Agents/`. `None` when the +/// system names no Documents folder and no home folder, or when `app_name` isn't a plain name +/// (empty, too long, or with anything other than ASCII letters, digits, `-` and `_`), so a name +/// can't lead outside the Agents folder. Doesn't touch the disk. +pub fn default_folder(app_name: &str) -> Option { + default_folder_in(dirs::document_dir(), dirs::home_dir(), app_name) +} + +/// [`default_folder`] for these system folders: Documents, otherwise `/Documents` (Linux +/// without an XDG Documents folder). A relative folder is ignored. +fn default_folder_in(documents: Option, home: Option, app_name: &str) -> Option { + if !plain_app_name(app_name) { + return None; + } + let documents = documents.filter(|d| d.is_absolute()).or_else(|| home.filter(|h| h.is_absolute()).map(|h| h.join("Documents")))?; + Some(DEFAULT_FOLDER_PARENTS.iter().fold(documents, |path, part| path.join(part)).join(app_name)) +} + +/// A name that is one ordinary path component on every system. +fn plain_app_name(name: &str) -> bool { + !name.is_empty() && name.len() <= MAX_APP_NAME && name.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_') +} + +impl AgentSettings { + /// The folders for agents of the app `app_name`: the person's own folder settings, and + /// [`default_folder`] for an empty one ([`Self::folders_with`]). + pub fn folders(&self, app_name: &str) -> AgentFolders { + self.folders_with(default_folder(app_name).as_deref()) + } + + /// The person's own folder settings, and `default` for an empty one. The default folder is + /// created when it is used; if it can't be, that direction has no folder (and the reason is + /// logged), so an agent is refused rather than pointed at a folder that isn't there. + pub fn folders_with(&self, default: Option<&Path>) -> AgentFolders { + let (read, write) = (self.read_folder(), self.write_folder()); + let default = if read.is_none() || write.is_none() { default.and_then(created) } else { None }; + AgentFolders { read: read.or_else(|| default.clone()), write: write.or(default) } + } +} + +/// `dir`, created with its parents if missing; `None` when it can't be. +fn created(dir: &Path) -> Option { + match std::fs::create_dir_all(dir) { + Ok(()) => Some(dir.to_path_buf()), + Err(e) => { + log::warn!("couldn't create the agent folder {}: {e}", dir.display()); + None + } + } +} + +/// [`FOLDERS_TOOL`]'s answer: `read_folder` and `write_folder`, each a path or `null`. A path +/// that isn't Unicode is shown with replacement characters. +pub fn folders_answer(folders: &AgentFolders) -> Value { + let path = |p: &Option| p.as_deref().map(|p| p.to_string_lossy().into_owned()); + json!({ "read_folder": path(&folders.read), "write_folder": path(&folders.write) }) +} + +/// [`FOLDERS_TOOL`] as an MCP tool entry (`name`, `description`, an `inputSchema` with no +/// parameters), for an app that lists its tools as JSON. +pub fn folders_tool() -> Value { + json!({ + "name": FOLDERS_TOOL, + "description": FOLDERS_TOOL_DESCRIPTION, + "inputSchema": { "type": "object", "properties": {}, "additionalProperties": false }, + }) +} + +#[cfg(test)] +mod tests { + #![allow(clippy::unwrap_used)] + use super::*; + + fn abs(parts: &[&str]) -> PathBuf { + let root = if cfg!(windows) { PathBuf::from(r"C:\") } else { PathBuf::from("/") }; + parts.iter().fold(root, |p, part| p.join(part)) + } + + // The default folder is in Documents; without one, in /Documents. + #[test] + fn default_folder_is_in_documents_then_home() { + let docs = abs(&["Users", "a", "Docs"]); + let home = abs(&["Users", "a"]); + assert_eq!( + default_folder_in(Some(docs.clone()), Some(home.clone()), "PhotoCraft"), + Some(docs.join("ArtCraft").join("Agents").join("PhotoCraft")) + ); + assert_eq!( + default_folder_in(None, Some(home.clone()), "PhotoCraft"), + Some(home.join("Documents").join("ArtCraft").join("Agents").join("PhotoCraft")) + ); + // A relative Documents folder is no place to put files. + assert_eq!( + default_folder_in(Some(PathBuf::from("Docs")), Some(home.clone()), "PhotoCraft"), + Some(home.join("Documents").join("ArtCraft").join("Agents").join("PhotoCraft")) + ); + assert_eq!(default_folder_in(None, Some(PathBuf::from("rel")), "PhotoCraft"), None); + assert_eq!(default_folder_in(None, None, "PhotoCraft"), None); + } + + // A name that could lead outside the Agents folder gets no default folder. + #[test] + fn odd_app_names_get_no_default_folder() { + let docs = Some(abs(&["Docs"])); + for name in ["", ".", "..", "../x", "a/b", r"a\b", "C:", "a b", "x".repeat(MAX_APP_NAME + 1).as_str(), "Fotó"] { + assert_eq!(default_folder_in(docs.clone(), None, name), None, "{name:?}"); + } + assert!(default_folder_in(docs, None, "grid-craft_2").is_some()); + } + + // The person's own folders win; the default only fills an empty setting, and is created. + #[test] + fn own_folders_win_and_the_default_is_created() { + let mine = AgentSettings { read_root: " /in ".into(), write_root: "/out".into(), ..AgentSettings::default() }; + assert_eq!(mine.folders("PhotoCraft"), AgentFolders { read: Some(PathBuf::from("/in")), write: Some(PathBuf::from("/out")) }); + + let dir = tempfile::tempdir().unwrap(); + let default = default_folder_in(Some(dir.path().to_path_buf()), None, "PhotoCraft").unwrap(); + assert_eq!(created(&default), Some(default.clone())); + assert!(default.is_dir()); + // A file where the folder should be: no folder, not a crash. + let blocked = dir.path().join("file"); + std::fs::write(&blocked, b"x").unwrap(); + assert_eq!(created(&blocked.join("Agents")), None); + } + + // With no own folders, both directions get the one default folder, created; a default that + // can't be created leaves them without one. + #[test] + fn empty_settings_use_one_default_folder() { + let dir = tempfile::tempdir().unwrap(); + let default = dir.path().join("ArtCraft").join("Agents").join("PhotoCraft"); + let folders = AgentSettings::default().folders_with(Some(&default)); + assert_eq!(folders, AgentFolders { read: Some(default.clone()), write: Some(default.clone()) }); + assert!(default.is_dir()); + let only_read = AgentSettings { read_root: "/in".into(), ..AgentSettings::default() }; + assert_eq!(only_read.folders_with(Some(&default)), AgentFolders { read: Some(PathBuf::from("/in")), write: Some(default) }); + + let file = dir.path().join("file"); + std::fs::write(&file, b"x").unwrap(); + assert_eq!(AgentSettings::default().folders_with(Some(&file.join("PhotoCraft"))), AgentFolders::default()); + assert_eq!(AgentSettings::default().folders("..").read, None); + } + + // The tool's answer names both folders, null where there is none. + #[test] + fn the_answer_names_both_folders() { + let folders = AgentFolders { read: Some(PathBuf::from("/in")), write: None }; + assert_eq!(folders_answer(&folders), json!({"read_folder": "/in", "write_folder": null})); + let tool = folders_tool(); + assert_eq!(tool["name"], FOLDERS_TOOL); + assert_eq!(tool["inputSchema"]["properties"], json!({})); + } +} diff --git a/crates/control/src/agents/live.rs b/crates/control/src/agents/live.rs index 49b242ff5..fd975fd28 100644 --- a/crates/control/src/agents/live.rs +++ b/crates/control/src/agents/live.rs @@ -14,7 +14,7 @@ //! folders are for agents the person let in. //! - No app accepts agents, but agents are allowed: the closed-app choice decides //! ([`LiveConfig::when_closed`], otherwise [`AgentSettings::when_app_closed`]): start the app and -//! wait until it accepts agents, a headless session with the app's agent folders (the command's +//! wait until it accepts agents, a headless session with the app's agent folders ([`AgentSettings::folders`], the default agent folder for an empty setting; the command's //! folders win), or an error that says what to do. //! //! Once headless, the session stays headless: documents don't move under the agent. Only a session @@ -138,6 +138,9 @@ pub struct LiveConfig { /// The folder a headless session may save to (the CLI's write root); while agents are allowed /// it replaces the app's write folder. pub write_root: Option, + /// The app's default agent folder, used for an empty folder setting + /// ([`AgentSettings::folders_with`]); [`super::default_folder`] of `app_name` unless changed. + pub default_folder: Option, /// Starts the app; `None` when this install can't ([`launcher`] found nothing to start). pub launch: Option, /// How long a started app gets to accept agents ([`LAUNCH_TIMEOUT`]; at most 10 minutes). @@ -159,8 +162,10 @@ impl LiveConfig { connect: impl Fn(&Window) -> Result + Send + Sync + 'static, headless: impl Fn(&HeadlessFolders) -> Result + Send + Sync + 'static, ) -> Self { + let app_name = app_name.into(); Self { - app_name: app_name.into(), + default_folder: super::default_folder(&app_name), + app_name, config_dir, when_closed: None, read_roots: Vec::new(), @@ -260,11 +265,17 @@ impl Live { match self.cfg.when_closed.unwrap_or(consent.settings.when_app_closed) { WhenAppClosed::Error => Err(format!("{app} isn't running: open it, then try again.")), WhenAppClosed::Headless => { - let app_read = self.cfg.read_roots.is_empty() && consent.settings.read_folder().is_some(); - let app_write = self.cfg.write_root.is_none() && consent.settings.write_folder().is_some(); - let read = - if self.cfg.read_roots.is_empty() { consent.settings.read_folder().into_iter().collect() } else { self.cfg.read_roots.clone() }; - let write = self.cfg.write_root.clone().or_else(|| consent.settings.write_folder()); + // The app's folders, its default agent folder for an empty setting; only looked up + // (and the default created) when the command leaves a direction open. + let own = if self.cfg.read_roots.is_empty() || self.cfg.write_root.is_none() { + consent.settings.folders_with(self.cfg.default_folder.as_deref()) + } else { + super::AgentFolders::default() + }; + let app_read = self.cfg.read_roots.is_empty() && own.read.is_some(); + let app_write = self.cfg.write_root.is_none() && own.write.is_some(); + let read = if self.cfg.read_roots.is_empty() { own.read.into_iter().collect() } else { self.cfg.read_roots.clone() }; + let write = self.cfg.write_root.clone().or(own.write); let why = format!("{app} isn't running and its agent folders can't be used"); self.headless(&HeadlessFolders { read, write }, app_read || app_write, &why) } diff --git a/crates/control/src/agents/mod.rs b/crates/control/src/agents/mod.rs index e1b0b9923..df8273d94 100644 --- a/crates/control/src/agents/mod.rs +++ b/crates/control/src/agents/mod.rs @@ -20,6 +20,7 @@ //! |---|---|---| //! | Settings | [`AgentSettings`], [`WhenAppClosed`], [`agents_allowed`], [`folder`] | every target | //! | The launcher's switch | [`AgentSwitch`], [`mcp_flag`], [`launcher_allows`], [`POLL`] | desktop, feature `agents` | +//! | The agent folders | [`AgentFolders`], [`AgentSettings::folders`], [`default_folder`], [`FOLDERS_TOOL`], [`folders_answer`], [`folders_tool`] | desktop, feature `agents` | //! | The connection file | [`Connection`], [`write_connection`], [`read_connection`], [`remove_connection`], [`remove_stale_connection`], [`probe`] | desktop, feature `agents` | //! | The CLI's side | [`Live`], [`LiveConfig`], [`Route`], [`Window`], [`Consent`], [`HeadlessFolders`], [`find_window`], [`launcher`] | desktop, feature `agents` | //! @@ -41,6 +42,10 @@ //! the app's process id. No restart, no agents switch of its own. There is one connection file //! per settings folder: an app that runs more than one process on one folder lets only one of //! them accept agents. +//! 3. The folders agents open from and save to are `settings.folders("GridCraft")` +//! ([`AgentSettings::folders`]): the person's own, otherwise `Documents/ArtCraft/Agents/GridCraft`. +//! Its MCP server offers [`FOLDERS_TOOL`] (described by [`FOLDERS_TOOL_DESCRIPTION`] or listed +//! as [`folders_tool`]), answered with [`folders_answer`] for the folders it uses. //! //! Its `gridcraft-cli mcp`: //! @@ -62,6 +67,8 @@ pub use settings::{AgentSettings, WhenAppClosed, agents_allowed, folder}; #[cfg(all(feature = "agents", not(target_arch = "wasm32")))] mod connection; #[cfg(all(feature = "agents", not(target_arch = "wasm32")))] +mod folders; +#[cfg(all(feature = "agents", not(target_arch = "wasm32")))] mod live; #[cfg(all(feature = "agents", not(target_arch = "wasm32")))] mod switch; @@ -70,6 +77,8 @@ pub use connection::{ CONNECTION_FILE, Connection, PROBE_TIMEOUT, TOKEN_FILE, probe, read_connection, remove_connection, remove_stale_connection, write_connection, }; #[cfg(all(feature = "agents", not(target_arch = "wasm32")))] +pub use folders::{AgentFolders, DEFAULT_FOLDER_PARENTS, FOLDERS_TOOL, FOLDERS_TOOL_DESCRIPTION, default_folder, folders_answer, folders_tool}; +#[cfg(all(feature = "agents", not(target_arch = "wasm32")))] pub use live::{ ConnectFn, Consent, ConsentFn, HeadlessFn, HeadlessFolders, LAUNCH_POLL, LAUNCH_TIMEOUT, LaunchFn, Live, LiveConfig, Route, Window, find_window, launcher, diff --git a/crates/control/tests/agents.rs b/crates/control/tests/agents.rs index 95a4651eb..5dfaa90c2 100644 --- a/crates/control/tests/agents.rs +++ b/crates/control/tests/agents.rs @@ -201,6 +201,8 @@ fn config(dir: &Path, consent: Consent, made: &Arc) -> LiveConfig::new(), None)); +} + /// Agents allowed, app closed, "error": the call fails with words that name the app; the command's /// choice wins over the app's. #[test]