diff --git a/AGENTS.md b/AGENTS.md index 81ca8809a7..66489eea41 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -82,7 +82,7 @@ For the crates you changed: `cargo fmt --check`, `cargo clippy -p -- -D - Hostile-input sweep: `crates/automation/tests/it/hostile_args.rs`. The last-resort `catch_unwind` guards are in `crates/engine/src/doc_state.rs` and `crates/ui-egui/src/frame_guard.rs`. - Attribution: `ATTRIBUTION.toml` is the source (one entry per asset, SHA-256 each); `ATTRIBUTION.md` is generated by `cargo xtask assets --write`. The ArtCraft logos in `docs/brand/` are trademark assets under `docs/brand/LICENSE-brand.txt`. - Translations come from storytold/craft-i18n at the commit in `craft-i18n.rev`; PdfCraft keeps no catalogs. Fonts come from storytold/craft-fonts through `CRAFT_FONTS_DIR` (optional build input; `.cargo/config.toml` points it at `../craft-fonts`, and a `CRAFT_FONTS_DIR` in the environment wins; code using `pdfcraft_fonts::CRAFT_FONTS` must work when it is empty); the Latin UI fonts in `assets/fonts/` stay here. The system interface font is read at runtime through `OnDemandFonts` with `SystemCandidates` (never embedded or shipped). -- Automation: every feature is a tool in `crates/automation` (`pdfcraft-cli run` and `pdfcraft-cli mcp` share the table; see `crates/automation/README.md`). MCP and the UI control channel are opt-in. The control channel runs only with `--control `, binds to loopback and authenticates with a token (`--control-token`, or an owner-only file named by `--control-token-file`, which `craft_platform::owner_only` sets and checks); never enable it by default or log the token. +- Automation: every feature is a tool in `crates/automation` (`pdfcraft-cli run` and `pdfcraft-cli mcp` share the table; see `crates/automation/README.md`). MCP and the UI control channel are opt-in. The control channel runs only with `--control ` or while the ArtCraft Launcher's AI agents switch names PdfCraft (`crates/ui-egui/src/agents.rs`, token file in the settings folder, requests held to the agent folders; docs/mcp.md), binds to loopback and authenticates with a token (`--control-token`, or an owner-only file named by `--control-token-file`, which `craft_platform::owner_only` sets and checks); never enable it by default or log the token. - Page modules register `PagePart`s (`canvas/page_parts.rs`) and act through the tool host (`canvas/page_tools.rs`). Keys and clipboard events are commands and tool claims, and the framework blocks both while a modal is open. - Large binary test oracles live in storytold/photocraft-corpus, not here; `cargo xtask corpus` fetches the pdf.js corpus pinned by commit and SHA-256. - Screenshots: `cargo xtask screenshots`; contributor credits: `docs/contributors.md`. diff --git a/Cargo.lock b/Cargo.lock index 78345be496..8bc9a3cba5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1372,6 +1372,7 @@ dependencies = [ "craft-behavior", "craft-browse", "craft-color-ui", + "craft-control", "craft-dialogs", "craft-docpath", "craft-draw", @@ -1402,6 +1403,16 @@ dependencies = [ "toml", ] +[[package]] +name = "craft-ai-agents" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-ai-integrations?rev=d94a3593adcff504eaaad9e5aee4c84fd2f07a72#d94a3593adcff504eaaad9e5aee4c84fd2f07a72" +dependencies = [ + "dirs", + "serde", + "serde_json", +] + [[package]] name = "craft-atomic" version = "0.1.0" @@ -1523,7 +1534,12 @@ name = "craft-control" version = "0.1.0" source = "git+https://github.com/storytold/craft-libs?rev=9888a585552d872ec94734daf064f96a0a25c41e#9888a585552d872ec94734daf064f96a0a25c41e" dependencies = [ + "craft-ai-agents", + "craft-atomic", + "craft-flags", + "dirs", "getrandom 0.3.4", + "log", "serde", "serde_json", ] @@ -1628,6 +1644,16 @@ dependencies = [ "serde", ] +[[package]] +name = "craft-flags" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8#6afe03f5b6de3c288ddcd3dbf0bb0320a2b20ca8" +dependencies = [ + "craft-atomic", + "dirs", + "toml_edit", +] + [[package]] name = "craft-flow" version = "0.1.0" @@ -6169,6 +6195,7 @@ dependencies = [ "egui_kittest", "fmv-macos-events", "log", + "pdfcraft-automation", "pdfcraft-engine", "pdfcraft-platform", "pdfcraft-ui-egui", diff --git a/apps/pdfcraft-cli/Cargo.toml b/apps/pdfcraft-cli/Cargo.toml index cbc315186e..8602f2dbdd 100644 --- a/apps/pdfcraft-cli/Cargo.toml +++ b/apps/pdfcraft-cli/Cargo.toml @@ -22,7 +22,7 @@ pdfcraft-preflight = { workspace = true } pdfcraft-automation = { workspace = true } pdfcraft-platform = { workspace = true } base64 = "0.23" -craft = { workspace = true, features = ["automation", "atomic"] } +craft = { workspace = true, features = ["automation", "atomic", "control-agents", "settings"] } [dev-dependencies] # Decodes `render` output in tests/it/owner_password.rs. diff --git a/apps/pdfcraft-cli/src/agents.rs b/apps/pdfcraft-cli/src/agents.rs new file mode 100644 index 0000000000..807860fe3d --- /dev/null +++ b/apps/pdfcraft-cli/src/agents.rs @@ -0,0 +1,515 @@ +//! Agents in the open window: the CLI's side of the ArtCraft Launcher's switch. +//! +//! While the launcher's *Settings › AI agents* switch names PdfCraft (behind the suite's `AI-MCP` +//! flag), the desktop app serves its control channel on loopback and publishes where in its +//! settings folder (`craft::automation::agents::AgentLink`, `pdfcraft_ui_egui::agents`). Plain +//! `pdfcraft-cli mcp` reads that file on every call ([`LiveSessions`], over the shared +//! `craft::control::agents::Live`), so an MCP client's configuration holds no port and no token, +//! and the app may start, quit or move to another port while the client stays connected. Adding +//! PdfCraft to MCP clients is the launcher's job (one entry for every Craft app); PdfCraft writes +//! no client configuration. +//! +//! The window answers its `ui.*` control methods, which the `ui_*` tools and `control_call` +//! reach. PdfCraft's document tools don't run in the window yet: while the window is the route +//! they run in a session of this command's own, held to the agent folders, and `ui_open` shows a +//! saved result in the window. Without the window (the person doesn't let agents in, or the app +//! is closed and the closed-app choice says so) every call runs in a session without a window, as +//! `mcp` always worked. +//! +//! What is PdfCraft's here: its launcher id, its window client ([`Window`], which makes the app +//! prove it holds the token before the client proves it holds it too), its tools for the window +//! and its sessions (an [`Automation`] with the agent folders as automation roots). + +use std::io::{BufRead, BufReader, ErrorKind, Read, Write}; +use std::net::{SocketAddr, TcpStream}; +use std::path::{Path, PathBuf}; +use std::sync::{Arc, Mutex, PoisonError}; +use std::time::{Duration, Instant}; + +use base64::Engine as _; +use craft::automation::client::CALL_TIMEOUT; +use craft::automation::protocol::MAX_RESPONSE_BYTES; +use craft::automation::security::{self, ProofRole}; +use craft::control::agents::{ + self as shared, AgentFolders, Consent, FOLDERS_TOOL, FOLDERS_TOOL_DESCRIPTION, HeadlessFolders, Route, WhenAppClosed, folders_answer, +}; +use pdfcraft_automation::file_access::AutomationRoots; +use pdfcraft_automation::mcp::Sessions; +use pdfcraft_automation::{Automation, Content}; +use serde_json::{Value, json}; + +#[path = "../../../crates/ui-egui/src/agent_settings.rs"] +mod agent_settings; + +pub use agent_settings::read_settings; + +/// The id the ArtCraft Launcher's app list names PdfCraft by (its catalog id). +pub const LAUNCHER_APP_ID: &str = "pdfcraft"; +/// The app's name in messages and its default agent folder (`Documents/ArtCraft/Agents/PdfCraft`). +pub const APP_NAME: &str = "PdfCraft"; +/// The desktop app's file name beside the CLI (without `.exe`). +pub const APP_EXE: &str = "pdfcraft"; + +/// How long connecting to the window may take: it is on this computer. +const CONNECT_TIMEOUT: Duration = Duration::from_secs(5); +/// The longest reply line read from the window: the server's own cap and the line's framing. +const MAX_REPLY_BYTES: u64 = MAX_RESPONSE_BYTES as u64 + 1024; + +/// Whether the person lets agents use PdfCraft now: with the suite's `AI-MCP` flag, the +/// launcher's switch. PdfCraft had no agent consent of its own before the switch, so without the +/// flag agents get a session without a window. +pub fn allowed_now() -> bool { + shared::agents_allowed(shared::mcp_flag(), shared::launcher_allows(LAUNCHER_APP_ID), false) +} + +/// The desktop app's settings folder, chosen the way the app chooses it (`PDFCRAFT_CONFIG_DIR`, a +/// portable data folder beside the executables, else the platform's folder): the same names as +/// `pdfcraft_ui_egui::settings::PdfCraftSettings`. `None` when there is none (an empty +/// `PDFCRAFT_CONFIG_DIR`, no home folder). +pub fn settings_dir() -> Option { + use craft::settings::paths::{self, Portable, Probe}; + let portable = Portable { markers: &["portable.txt", "PdfCraft.portable"], dir: "PdfCraftData" }; + paths::resolve_named("pdfcraft", "PdfCraft", &portable, &craft::settings::Location::Auto, &Probe::default()).dir +} + +// ---- The open window --------------------------------------------------------------------------- + +/// One authenticated connection to the open window. The app proves it holds the token first +/// (`auth.challenge`), then the client answers with its own proof: the token never crosses the +/// wire, and a program that took a stale port learns nothing derived from it. +pub struct Window { + addr: SocketAddr, + token: String, + conn: Option, + next_id: u64, +} + +type Conn = (BufReader, TcpStream); + +impl Window { + /// A client for the window on `127.0.0.1:port` with `token`; connects on the first call. + pub fn new(port: u16, token: String) -> Self { + Self { addr: SocketAddr::from(([127, 0, 0, 1], port)), token, conn: None, next_id: 1 } + } + + /// Connects and runs the challenge handshake. + pub fn connect(&mut self) -> Result<(), String> { + self.conn = None; + let stream = TcpStream::connect_timeout(&self.addr, CONNECT_TIMEOUT).map_err(|e| e.to_string())?; + stream.set_nodelay(true).ok(); + stream.set_write_timeout(Some(CALL_TIMEOUT)).map_err(|e| e.to_string())?; + let mut conn = (BufReader::new(stream.try_clone().map_err(|e| e.to_string())?), stream); + let client_nonce = security::generate_nonce().map_err(|e| e.to_string())?; + let challenge = round_trip(&mut conn, 0, security::CHALLENGE_METHOD, json!({"clientNonce": client_nonce}))? + .map_err(|e| format!("{} refused challenge authentication ({e}); the agent token was not used", self.addr))?; + let field = |key: &str| challenge.get(key).and_then(Value::as_str).filter(|v| security::is_hex256(v)).map(str::to_owned); + let (Some(server_nonce), Some(server_proof)) = (field("serverNonce"), field("serverProof")) else { + return Err(format!("{} answered the challenge without a proof; the agent token was not used", self.addr)); + }; + if !security::proof_matches(&self.token, ProofRole::Server, &client_nonce, &server_nonce, &server_proof) { + return Err(format!("{} could not prove it holds PdfCraft's agent token; nothing was sent to it", self.addr)); + } + let proof = security::handshake_proof(&self.token, ProofRole::Client, &client_nonce, &server_nonce).map_err(|e| e.to_string())?; + round_trip(&mut conn, 0, security::AUTH_METHOD, json!({"proof": proof}))?.map_err(|e| format!("PdfCraft refused the agent token: {e}"))?; + self.conn = Some(conn); + Ok(()) + } + + /// One control request to the window. A lost connection is never sent again (the request may + /// have run); the next call reconnects. + pub fn call(&mut self, method: &str, params: Value) -> Result { + if self.conn.is_none() { + self.connect().map_err(|e| format!("the PdfCraft window is not reachable: {e}; `{method}`: nothing was sent"))?; + } + let id = self.next_id; + self.next_id = self.next_id.wrapping_add(1).max(1); + let Some(conn) = self.conn.as_mut() else { return Err("not connected".into()) }; + match round_trip(conn, id, method, params) { + Ok(answer) => answer, + Err(e) => { + self.conn = None; + Err(format!("lost the connection to the PdfCraft window ({e}); `{method}` may or may not have run: check the window before retrying")) + } + } + } +} + +/// Sends one request and reads the reply with its `id` (lines for other ids are skipped): `Err` +/// when the connection failed, `Ok(Err)` when the app answered with an error. +fn round_trip(conn: &mut Conn, id: u64, method: &str, params: Value) -> Result, String> { + let (reader, writer) = conn; + let line = json!({"id": id, "method": method, "params": params}).to_string(); + writer.write_all(line.as_bytes()).and_then(|()| writer.write_all(b"\n")).and_then(|()| writer.flush()).map_err(|e| e.to_string())?; + let deadline = Instant::now() + CALL_TIMEOUT; + loop { + let reply = read_line(reader, deadline)?; + let v: Value = serde_json::from_slice(&reply).map_err(|e| format!("bad reply from the window: {e}"))?; + if v.get("id").and_then(Value::as_u64) != Some(id) { + continue; + } + return Ok(if v.get("ok").and_then(Value::as_bool) == Some(true) { + Ok(v.get("result").cloned().unwrap_or(Value::Null)) + } else { + Err(v.get("error").and_then(Value::as_str).unwrap_or("unknown error").to_owned()) + }); + } +} + +/// One reply line, at most [`MAX_REPLY_BYTES`], read by `deadline`. +fn read_line(reader: &mut BufReader, deadline: Instant) -> Result, String> { + let mut line = Vec::new(); + loop { + let left = deadline.saturating_duration_since(Instant::now()); + if left.is_zero() { + return Err("the window did not answer in time".into()); + } + reader.get_ref().set_read_timeout(Some(left)).map_err(|e| e.to_string())?; + let room = (MAX_REPLY_BYTES + 1).saturating_sub(line.len() as u64); + // `read_until` keeps what it read before a timeout, so the line goes on where it stopped. + match reader.by_ref().take(room).read_until(b'\n', &mut line) { + Ok(0) => return Err("the window closed the connection".into()), + Ok(_) if line.ends_with(b"\n") => return Ok(line), + Ok(_) if line.len() as u64 > MAX_REPLY_BYTES => return Err("the window's reply is too long".into()), + Ok(_) => return Err("the window closed the connection".into()), + Err(e) if matches!(e.kind(), ErrorKind::WouldBlock | ErrorKind::TimedOut | ErrorKind::Interrupted) => {} + Err(e) => return Err(e.to_string()), + } + } +} + +// ---- The tools for the window ------------------------------------------------------------------ + +/// The tools that reach the open window, by name: the control method each one sends. +const WINDOW_TOOLS: [(&str, &str); 6] = [ + ("ui_state", "ui.state"), + ("ui_inspect", "ui.inspect"), + ("ui_screenshot", "ui.screenshot"), + ("ui_open", "ui.open"), + ("ui_command", "ui.command"), + ("control_call", ""), +]; + +/// The MCP entries of the window tools and [`FOLDERS_TOOL`]. +fn tool_entries() -> Vec { + let read_only = + |title: &str| json!({"title": title, "readOnlyHint": true, "destructiveHint": false, "idempotentHint": true, "openWorldHint": false}); + let acting = + |title: &str| json!({"title": title, "readOnlyHint": false, "destructiveHint": true, "idempotentHint": false, "openWorldHint": false}); + let object = |properties: Value, required: Vec<&str>| json!({"type": "object", "properties": properties, "required": required, "additionalProperties": false}); + vec![ + json!({"name": FOLDERS_TOOL, "title": "Agent folders", "description": FOLDERS_TOOL_DESCRIPTION, + "inputSchema": object(json!({}), vec![]), "annotations": read_only("Agent folders")}), + json!({"name": "ui_state", "title": "Window state", + "description": "The open PdfCraft window: its documents (name, path, page count, dirty), the active document, page and zoom, mode, panels, open dialog and notices. Needs the open window (ArtCraft Launcher › Settings › AI agents).", + "inputSchema": object(json!({}), vec![]), "annotations": read_only("Window state")}), + json!({"name": "ui_inspect", "title": "Window controls", + "description": "The controls of the open PdfCraft window in tree order: id, role, label, value, rect (points), enabled, toggled, focused. Filter by query (words in the label), role or focused; limit caps the list. Needs the open window.", + "inputSchema": object(json!({"query": {"type": "string"}, "role": {"type": "string"}, "focused": {"type": "boolean"}, "limit": {"type": "integer", "minimum": 1}}), vec![]), + "annotations": read_only("Window controls")}), + json!({"name": "ui_screenshot", "title": "Window screenshot", + "description": "A PNG of the open PdfCraft window, or of region {x, y, width, height} in points. Needs the open window.", + "inputSchema": object(json!({"region": {"type": "object", "properties": {"x": {"type": "number"}, "y": {"type": "number"}, "width": {"type": "number"}, "height": {"type": "number"}}}}), vec![]), + "annotations": read_only("Window screenshot")}), + json!({"name": "ui_open", "title": "Open in the window", + "description": "Opens a file in the open PdfCraft window, as the person would. The file must be in the agent read folder (agent_folders). Needs the open window.", + "inputSchema": object(json!({"path": {"type": "string"}}), vec!["path"]), "annotations": acting("Open in the window")}), + json!({"name": "ui_command", "title": "Run a window command", + "description": "Runs a PdfCraft menu command by id in the open window, as the menu would (control_call with method ui.commands lists the ids and whether each can run now). Needs the open window.", + "inputSchema": object(json!({"id": {"type": "string"}}), vec!["id"]), "annotations": acting("Run a window command")}), + json!({"name": "control_call", "title": "Window control method", + "description": "Calls any method of the open PdfCraft window's control channel with raw params: ui.click, ui.key, ui.type, ui.set, ui.dialog.*, ui.pick, ui.commands, ui.quit and the others the automation README lists. Files stay inside the agent folders. Needs the open window.", + "inputSchema": object(json!({"method": {"type": "string"}, "params": {"type": "object"}}), vec!["method"]), "annotations": acting("Window control method")}), + ] +} + +/// The control method and params a window tool sends; `Err` for bad arguments. +fn window_request(tool: &str, method: &str, args: &Value) -> Result<(String, Value), String> { + let args = match args { + Value::Null => json!({}), + Value::Object(_) => args.clone(), + _ => return Err(format!("{tool} takes an object")), + }; + if tool != "control_call" { + return Ok((method.to_owned(), args)); + } + let method = args.get("method").and_then(Value::as_str).ok_or("control_call needs a method, such as ui.click")?; + if let Some(unknown) = args.as_object().and_then(|o| o.keys().find(|k| !matches!(k.as_str(), "method" | "params"))) { + return Err(format!("control_call: unknown argument {unknown:?} (expected: method, params)")); + } + let params = match args.get("params") { + None | Some(Value::Null) => json!({}), + Some(p @ Value::Object(_)) => p.clone(), + Some(_) => return Err("control_call: params must be an object".into()), + }; + Ok((method.to_owned(), params)) +} + +/// A window reply as tool content: a screenshot's PNG as an image after the rest of the reply. +fn window_content(mut reply: Value) -> Result, String> { + let png = reply.as_object_mut().and_then(|o| o.remove("base64")); + let Some(png) = png.as_ref().and_then(Value::as_str) else { return Ok(vec![Content::Json(reply)]) }; + let data = base64::engine::general_purpose::STANDARD.decode(png).map_err(|e| format!("the window's screenshot is not base64: {e}"))?; + let (width, height) = png_size(&data).ok_or("the window's screenshot is not a PNG")?; + Ok(vec![Content::Json(reply), Content::Png { data, width, height }]) +} + +/// The width and height a PNG's header names. +fn png_size(png: &[u8]) -> Option<(u32, u32)> { + let header = png.get(..24)?; + if header.get(..8)? != b"\x89PNG\r\n\x1a\n" || header.get(12..16)? != b"IHDR" { + return None; + } + let word = |at: usize| header.get(at..at + 4).and_then(|b| b.try_into().ok()).map(u32::from_be_bytes); + Some((word(16)?, word(20)?)) +} + +// ---- The sessions ------------------------------------------------------------------------------ + +/// Agent folders `read` and `write`. +fn folders(read: Option, write: Option) -> AgentFolders { + let mut folders = AgentFolders::default(); + folders.read = read; + folders.write = write; + folders +} + +/// The folders of a session without a window the shared lookup chose. +pub struct Headless { + folders: AgentFolders, + roots: Option>, +} + +type SharedWindow = Arc>; +type SharedHeadless = Arc; + +/// The automation roots for `folders`; `None` (nothing confined) only when `confine` is off and +/// there are no folders, as a plain `mcp` without root flags works. `Err` when agent folders are +/// wanted and none can be used. +fn roots_for(folders: &AgentFolders, confine: bool) -> Result>, String> { + let roots = AutomationRoots::new(folders.read.as_deref(), folders.write.as_deref())?; + if roots.is_none() && confine { + return Err( + "there is no agent folder (Documents/ArtCraft/Agents/PdfCraft could not be made, and none is set in Preferences › AI Integrations)" + .into(), + ); + } + Ok(roots) +} + +/// Makes the command's session from its first automation roots (with `--root`, if given). +pub type Maker = Box>) -> Result>; + +/// What plain `pdfcraft-cli mcp` needs to find the window. +pub struct LiveConfig { + /// The app's settings folder: connection file, token file and agent settings. + pub config_dir: PathBuf, + /// Overrides the app's closed-app choice (`--when-closed`). + pub when_closed: Option, + /// The command's own folders (`--automation-read-root`, `--automation-write-root`). + pub read_root: Option, + pub write_root: Option, + /// Starts the app; `None` when this install can't. + pub launch: Option, + pub launch_timeout: Duration, + /// Whether agents may use the app now ([`allowed_now`]); tests replace it. + pub allowed: fn() -> bool, + /// The default agent folder for an empty folder setting; tests replace it. + pub default_folder: Option, +} + +impl LiveConfig { + /// The settings in `config_dir`, the launcher's switch and the default agent folder. + pub fn new(config_dir: PathBuf) -> Self { + Self { + config_dir, + when_closed: None, + read_root: None, + write_root: None, + launch: None, + launch_timeout: shared::LAUNCH_TIMEOUT, + allowed: allowed_now, + default_folder: shared::default_folder(APP_NAME), + } + } +} + +/// Plain `pdfcraft-cli mcp`: the window tools go to the open window while the person lets agents +/// use it; the document tools run in one session of this command's for its whole run, as plain +/// `mcp` always had. Its documents stay when the route or the folders change; what it may open +/// and save follows the route: the agent folders while the window is the route, otherwise the +/// folders the shared lookup chose (the closed-app choice). +pub struct LiveSessions { + live: shared::Live, + make: Maker, + config_dir: PathBuf, + default_folder: Option, + command_folders: AgentFolders, + session: Option, + /// The folders the session holds now, and whether it is confined. + applied: Option<(AgentFolders, bool)>, +} + +impl LiveSessions { + pub fn new(cfg: LiveConfig, make: Maker) -> Self { + let LiveConfig { config_dir, when_closed, read_root, write_root, launch, launch_timeout, allowed, default_folder } = cfg; + let consent = move |dir: &Path| Consent::new(allowed(), read_settings(dir)); + let connect = |w: &shared::Window| -> Result { + let mut window = Window::new(w.port, w.token.clone()); + window.connect()?; + Ok(Arc::new(Mutex::new(window))) + }; + let settings_dir = config_dir.clone(); + let command_folders = folders(read_root.clone(), write_root.clone()); + let headless = move |wanted: &HeadlessFolders| -> Result { + // The command's own roots count as a pair, as given: the shared lookup fills a root the + // command left out from Preferences, which would grant access the command didn't. + let folders = if command_folders.read.is_some() || command_folders.write.is_some() { + command_folders.clone() + } else { + folders(wanted.read.first().cloned(), wanted.write.clone()) + }; + // Agents the person let in get only folders; a session for others keeps `mcp`'s old reach. + let confine = allowed() && read_settings(&settings_dir).allow_agent_control; + let roots = roots_for(&folders, confine)?; + Ok(Arc::new(Headless { folders, roots })) + }; + let mut shared_cfg = shared::LiveConfig::new(APP_NAME, config_dir.clone(), consent, connect, headless); + shared_cfg.when_closed = when_closed; + shared_cfg.read_roots = read_root.iter().cloned().collect(); + shared_cfg.write_root = write_root.clone(); + shared_cfg.launch = launch; + shared_cfg.launch_timeout = launch_timeout; + shared_cfg.default_folder = default_folder.clone(); + let command_folders = folders(read_root, write_root); + Self { live: shared::Live::new(shared_cfg), make, config_dir, default_folder, command_folders, session: None, applied: None } + } + + /// Whether the command was given folders of its own: then they alone count, as given (a root + /// left out grants none of its access), not filled in from Preferences. + fn has_command_folders(&self) -> bool { + self.command_folders.read.is_some() || self.command_folders.write.is_some() + } + + /// The folders agents in the open window use: the command's own, else the agent folders of + /// Preferences (the default agent folder for an empty one). + fn window_folders(&self) -> AgentFolders { + if self.has_command_folders() { + return self.command_folders.clone(); + } + read_settings(&self.config_dir).folders_with(self.default_folder.as_deref()) + } + + /// The folders the session uses now, and whether it is confined. + fn current_folders(&mut self) -> Result<(AgentFolders, bool), String> { + self.session()?; + Ok(self.applied.clone().unwrap_or_default()) + } + + /// Whether the window tools may be used. The window holds an agent's requests to its own agent + /// folders (Preferences, or the default agent folder) for every file it opens or saves (Save, + /// Save As, exports, file picks), and it never sees the command's roots. So a command given + /// folders of its own reaches the window only when they are the same folders; otherwise a Save + /// in the window could write where the command may not. + fn check_window_folders(&self) -> Result<(), String> { + if !self.has_command_folders() { + return Ok(()); + } + let window = read_settings(&self.config_dir).folders_with(self.default_folder.as_deref()); + let same = |a: &Option, b: &Option| match (a, b) { + (Some(a), Some(b)) => std::fs::canonicalize(a).ok().is_some_and(|a| std::fs::canonicalize(b).ok().is_some_and(|b| a == b)), + (None, None) => true, + _ => false, + }; + if same(&self.command_folders.read, &window.read) && same(&self.command_folders.write, &window.write) { + return Ok(()); + } + Err( + "this command was started with folders of its own (--automation-read-root/--automation-write-root), and the PdfCraft window holds agents to the agent folders of its Preferences › AI Integrations instead, so the window tools are off: start the command without those flags, or set the same folders there. The document tools work." + .into(), + ) + } +} + +impl Sessions for LiveSessions { + fn session(&mut self) -> Result<&mut Automation, String> { + let (folders, roots) = match self.live.resolve()? { + Route::Headless(h) => (h.folders.clone(), h.roots.clone()), + Route::Window(_) => { + let folders = self.window_folders(); + if self.session.is_some() && self.applied.as_ref().is_some_and(|(kept, confined)| *confined && *kept == folders) { + return self.session.as_mut().ok_or_else(|| "no session".to_string()); + } + let roots = roots_for(&folders, true).map_err(|e| format!("PdfCraft's agent folders can't be used: {e}"))?; + (folders, roots) + } + }; + let want = (folders, roots.is_some()); + if self.session.is_none() || self.applied.as_ref() != Some(&want) { + // The open documents and their undo history stay; only the folders change, and every + // later open or save is checked against the new ones. + let session = match self.session.take() { + Some(session) => session.with_automation_roots(roots), + None => (self.make)(roots)?, + }; + self.session = Some(session); + self.applied = Some(want); + } + self.session.as_mut().ok_or_else(|| "no session".to_string()) + } + + fn extra_tools(&self) -> Vec { + tool_entries() + } + + fn call_extra(&mut self, name: &str, args: &Value) -> Option, String>> { + if name == FOLDERS_TOOL { + if args.as_object().is_some_and(|o| !o.is_empty()) { + return Some(Err(format!("{FOLDERS_TOOL} takes no arguments"))); + } + return Some(self.current_folders().map(|(folders, confined)| { + let mut answer = folders_answer(&folders); + answer["confined"] = json!(confined); + vec![Content::Json(answer)] + })); + } + let (_, method) = WINDOW_TOOLS.iter().find(|(tool, _)| *tool == name)?; + Some(window_request(name, method, args).and_then(|(method, params)| { + self.check_window_folders()?; + // With folders of its own, the request carries them: the window runs it only while + // they are still its agent folders. They go as absolute paths, so the window compares the + // folders checked here, not the given ones read from its own working folder. + let (method, params) = if self.has_command_folders() { + let path = |p: &Option| -> Result { + match p { + Some(p) => std::fs::canonicalize(p) + .map(|p| json!(p.to_string_lossy())) + .map_err(|e| format!("this command's folder {} can't be used: {e}", p.display())), + None => Ok(Value::Null), + } + }; + let folders = json!({"read": path(&self.command_folders.read)?, "write": path(&self.command_folders.write)?}); + ("agents.call".to_owned(), json!({"method": method, "params": params, "folders": folders})) + } else { + (method, params) + }; + match self.live.resolve()? { + Route::Window(window) => window_content(window.lock().unwrap_or_else(PoisonError::into_inner).call(&method, params)?), + Route::Headless(_) => Err(format!( + "{name} needs the open PdfCraft window, and this session works without one: open PdfCraft with AI agents on in ArtCraft Launcher › Settings › AI agents. The document tools work here." + )), + } + })) + } + + fn instructions(&self) -> Option<&str> { + Some( + "While PdfCraft's window is open and AI agents may use it (ArtCraft Launcher › Settings › AI agents), ui_state, ui_inspect, \ + ui_screenshot, ui_open, ui_command and control_call drive that window. The document tools work on documents this session \ + opens itself, not on the window's tabs: open and save files in the folders agent_folders names, and show a saved result in \ + the window with ui_open.", + ) + } +} + +#[cfg(test)] +mod tests; diff --git a/apps/pdfcraft-cli/src/agents/tests.rs b/apps/pdfcraft-cli/src/agents/tests.rs new file mode 100644 index 0000000000..2965321e90 --- /dev/null +++ b/apps/pdfcraft-cli/src/agents/tests.rs @@ -0,0 +1,256 @@ +#![allow(clippy::unwrap_used, clippy::expect_used)] + +use std::io::{BufRead, BufReader, Write}; +use std::net::TcpListener; +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::sync::atomic::{AtomicUsize, Ordering}; + +use craft::automation::security::{AuthStep, ServerHandshake, generate_token}; +use craft::control::agents::{Connection, TOKEN_FILE, WhenAppClosed, write_connection}; +use serde_json::{Value, json}; + +use super::*; + +fn temp(tag: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("pdfcraft-cli-agents-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir +} + +/// A stand-in for the open window: answers the challenge handshake with `token` and then every +/// request with its method and params. Counts the requests it answered. +fn fake_window(token: String) -> (u16, Arc) { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let port = listener.local_addr().unwrap().port(); + let answered = Arc::new(AtomicUsize::new(0)); + let count = answered.clone(); + std::thread::spawn(move || { + for stream in listener.incoming() { + let Ok(stream) = stream else { return }; + let (token, count) = (token.clone(), count.clone()); + std::thread::spawn(move || { + let mut writer = stream.try_clone().unwrap(); + let mut handshake = ServerHandshake::new(); + let mut authenticated = false; + for line in BufReader::new(stream).lines() { + let Ok(line) = line else { return }; + let reply = if authenticated { + let req: Value = serde_json::from_str(&line).unwrap(); + count.fetch_add(1, Ordering::SeqCst); + json!({"id": req["id"], "ok": true, "result": {"method": req["method"], "params": req["params"]}}) + } else { + let (reply, step) = handshake.reply(&line, &token); + authenticated = step == AuthStep::Authenticated; + if step == AuthStep::Rejected { + let _ = writeln!(writer, "{reply}"); + return; + } + reply + }; + if writeln!(writer, "{reply}").is_err() { + return; + } + } + }); + } + }); + (port, answered) +} + +/// Publishes a window on `port` in `dir` as the app does, with `token` in the token file, which +/// only its owner may read. +fn publish(dir: &Path, port: u16, token: &str) { + let token_file = dir.join(TOKEN_FILE); + let mut options = std::fs::OpenOptions::new(); + options.write(true).create_new(true); + #[cfg(unix)] + std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600); + options.open(&token_file).unwrap().write_all(token.as_bytes()).unwrap(); + write_connection(dir, &Connection::new(port, token_file, "PdfCraft test")).unwrap(); +} + +fn sessions(dir: &Path, allowed: fn() -> bool, folder: &Path) -> LiveSessions { + let mut cfg = LiveConfig::new(dir.to_path_buf()); + cfg.allowed = allowed; + cfg.default_folder = Some(folder.to_path_buf()); + cfg.when_closed = Some(WhenAppClosed::Headless); + LiveSessions::new(cfg, Box::new(|roots| Ok(Automation::new().with_automation_roots(roots)))) +} + +fn json_of(content: Vec) -> Value { + content.into_iter().find_map(|c| if let Content::Json(v) = c { Some(v) } else { None }).unwrap() +} + +fn tool(s: &mut LiveSessions, name: &str, args: Value) -> Result { + s.call_extra(name, &args).expect("a tool the router adds").map(json_of) +} + +// With the window published and agents allowed, the window tools reach it, and the document +// tools run in a session held to the agent folders. +#[test] +fn allowed_window_takes_the_window_tools_and_documents_stay_in_the_agent_folders() { + let base = temp("window"); + let (dir, folder, outside) = (base.join("settings"), base.join("agents"), base.join("elsewhere")); + for d in [&dir, &folder, &outside] { + std::fs::create_dir_all(d).unwrap(); + } + let token = generate_token().unwrap(); + let (port, answered) = fake_window(token.clone()); + publish(&dir, port, &token); + let mut s = sessions(&dir, || true, &folder); + + let reply = tool(&mut s, "ui_open", json!({"path": "x.pdf"})).unwrap(); + assert_eq!(reply["method"], "ui.open", "ui_open went to the window as its control method"); + let reply = tool(&mut s, "control_call", json!({"method": "ui.key", "params": {"key": "A"}})).unwrap(); + assert_eq!((reply["method"].as_str(), reply["params"]["key"].as_str()), (Some("ui.key"), Some("A"))); + assert_eq!(answered.load(Ordering::SeqCst), 2); + + let folders = tool(&mut s, FOLDERS_TOOL, json!({})).unwrap(); + assert_eq!(folders["confined"], true); + assert!(folders["write_folder"].as_str().is_some_and(|f| Path::new(f) == folder)); + + std::fs::write(outside.join("secret.pdf"), b"%PDF-1.4").unwrap(); + let refused = s.session().unwrap().call("doc_open", &json!({"path": outside.join("secret.pdf").to_string_lossy()})); + assert!(refused.is_err(), "a document outside the agent folders is refused beside the window"); + let _ = std::fs::remove_dir_all(base); +} + +// While the person doesn't let agents in, nothing reaches the window and `mcp` works as it +// always did: no folders forced on the session. +#[test] +fn not_allowed_means_no_window_tools_and_an_unconfined_session() { + let base = temp("off"); + let (dir, folder) = (base.join("settings"), base.join("agents")); + std::fs::create_dir_all(&dir).unwrap(); + let mut s = sessions(&dir, || false, &folder); + + let refused = tool(&mut s, "ui_state", json!({})).unwrap_err(); + assert!(refused.contains("needs the open PdfCraft window"), "{refused}"); + let folders = tool(&mut s, FOLDERS_TOOL, json!({})).unwrap(); + assert_eq!(folders["confined"], false); + assert!(!folder.exists(), "no agent folder is made for an agent the person didn't let in"); + let _ = std::fs::remove_dir_all(base); +} + +// A connection file a crashed app left behind (nothing listens on its port) is no window. +#[test] +fn a_stale_connection_file_is_no_window() { + let base = temp("stale"); + let (dir, folder) = (base.join("settings"), base.join("agents")); + std::fs::create_dir_all(&dir).unwrap(); + let port = TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port(); + publish(&dir, port, &generate_token().unwrap()); + let mut s = sessions(&dir, || true, &folder); + + assert!(tool(&mut s, "ui_state", json!({})).is_err(), "nothing listens there"); + let folders = tool(&mut s, FOLDERS_TOOL, json!({})).unwrap(); + assert_eq!(folders["confined"], true, "the closed-app session for an allowed agent gets the agent folders"); + let _ = std::fs::remove_dir_all(base); +} + +// A program on the published port that can't prove it holds the token gets nothing. +#[test] +fn a_window_without_the_token_is_refused() { + let base = temp("token"); + let (dir, folder) = (base.join("settings"), base.join("agents")); + std::fs::create_dir_all(&dir).unwrap(); + let (port, answered) = fake_window(generate_token().unwrap()); + publish(&dir, port, &generate_token().unwrap()); + let mut s = sessions(&dir, || true, &folder); + + let refused = tool(&mut s, "ui_state", json!({})).unwrap_err(); + assert!(refused.contains("could not prove"), "{refused}"); + assert_eq!(answered.load(Ordering::SeqCst), 0, "no request reached it"); + let _ = std::fs::remove_dir_all(base); +} + +/// `sessions` for a command given its own `--automation-read-root`/`--automation-write-root`. +fn sessions_with_roots(dir: &Path, folder: &Path, read: Option<&Path>, write: Option<&Path>) -> LiveSessions { + let mut cfg = LiveConfig::new(dir.to_path_buf()); + cfg.allowed = || true; + cfg.default_folder = Some(folder.to_path_buf()); + cfg.read_root = read.map(Path::to_path_buf); + cfg.write_root = write.map(Path::to_path_buf); + LiveSessions::new(cfg, Box::new(|roots| Ok(Automation::new().with_automation_roots(roots)))) +} + +// A command root given alone stays alone: the other direction isn't filled in from the agent +// folders of Preferences. The window holds agents to those Preferences folders (a Save writes the +// document's own path), so with other folders of its own the command doesn't reach the window. +#[test] +fn the_commands_own_folders_are_not_filled_in_from_preferences() { + let base = temp("command-roots"); + let (dir, folder, input, outside) = (base.join("settings"), base.join("agents"), base.join("in"), base.join("elsewhere")); + for d in [&dir, &folder, &input, &outside] { + std::fs::create_dir_all(d).unwrap(); + } + let token = generate_token().unwrap(); + let (port, answered) = fake_window(token.clone()); + publish(&dir, port, &token); + let mut s = sessions_with_roots(&dir, &folder, Some(&input), None); + + let folders = tool(&mut s, FOLDERS_TOOL, json!({})).unwrap(); + assert!(folders["read_folder"].as_str().is_some_and(|f| Path::new(f) == input)); + assert!(folders["write_folder"].is_null(), "no write folder was given, so none is used: {folders}"); + for path in [outside.join("x.pdf"), input.join("x.pdf")] { + let refused = tool(&mut s, "ui_open", json!({"path": path.to_string_lossy()})).unwrap_err(); + assert!(refused.contains("window tools are off"), "{refused}"); + } + assert!(tool(&mut s, "control_call", json!({"method": "ui.command", "params": {"id": "file.save"}})).is_err()); + assert_eq!(answered.load(Ordering::SeqCst), 0, "nothing was sent to the window"); + + // The same folders as the window's: the window enforces them itself. + let mut same = sessions_with_roots(&dir, &folder, Some(&folder), Some(&folder)); + let reply = tool(&mut same, "ui_state", json!({})).unwrap(); + assert_eq!(answered.load(Ordering::SeqCst), 1); + // Bound to the folders checked, as absolute paths, which the window compares with its own + // when it runs it. + assert_eq!((reply["method"].as_str(), reply["params"]["method"].as_str()), (Some("agents.call"), Some("ui.state"))); + let checked = std::fs::canonicalize(&folder).unwrap(); + assert!(reply["params"]["folders"]["write"].as_str().is_some_and(|f| Path::new(f) == checked), "{reply}"); + let _ = std::fs::remove_dir_all(base); +} + +// The person changing the agent folders keeps the command's open documents and their unsaved +// edits; only what the session may open and save follows the new folders. +#[test] +fn documents_stay_when_the_agent_folders_change() { + let base = temp("folders-change"); + let (dir, folder, other) = (base.join("settings"), base.join("agents"), base.join("other")); + for d in [&dir, &folder, &other] { + std::fs::create_dir_all(d).unwrap(); + } + let token = generate_token().unwrap(); + let (port, _) = fake_window(token.clone()); + publish(&dir, port, &token); + let mut s = sessions(&dir, || true, &folder); + s.session().unwrap().call("doc_create", &json!({"from": "blank", "pages": 1, "width": 100, "height": 100})).unwrap(); + + let other_text = other.to_string_lossy(); + std::fs::write(dir.join("agents.json"), json!({"readRoot": other_text, "writeRoot": other_text}).to_string()).unwrap(); + let folders = tool(&mut s, FOLDERS_TOOL, json!({})).unwrap(); + assert!(folders["write_folder"].as_str().is_some_and(|f| Path::new(f) == other), "{folders}"); + let documents = json_of(s.session().unwrap().call("doc_inspect", &json!({})).unwrap()); + assert_eq!(documents["documents"].as_array().map(Vec::len), Some(1), "the unsaved document is still open: {documents}"); + let _ = std::fs::remove_dir_all(base); +} + +// With the app closed and agents allowed, the closed-app session too takes a command root given +// alone as it is, without a write folder from Preferences. +#[test] +fn a_closed_app_keeps_the_commands_own_folders_as_given() { + let base = temp("closed-roots"); + let (dir, folder, input) = (base.join("settings"), base.join("agents"), base.join("in")); + for d in [&dir, &folder, &input] { + std::fs::create_dir_all(d).unwrap(); + } + let mut s = sessions_with_roots(&dir, &folder, Some(&input), None); + std::fs::write(dir.join("agents.json"), json!({"whenAppClosed": "headless"}).to_string()).unwrap(); + + let folders = tool(&mut s, FOLDERS_TOOL, json!({})).unwrap(); + assert!(folders["read_folder"].as_str().is_some_and(|f| Path::new(f) == input), "{folders}"); + assert!(folders["write_folder"].is_null(), "{folders}"); + let _ = std::fs::remove_dir_all(base); +} diff --git a/apps/pdfcraft-cli/src/main.rs b/apps/pdfcraft-cli/src/main.rs index 284bc79954..65174c7ec5 100644 --- a/apps/pdfcraft-cli/src/main.rs +++ b/apps/pdfcraft-cli/src/main.rs @@ -17,6 +17,8 @@ #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +#[cfg(feature = "mcp")] +mod agents; #[cfg(feature = "mcp")] mod automation_args; mod batch; @@ -36,7 +38,12 @@ macro_rules! mcp_usage { () => { "\ pdfcraft-cli mcp [--root DIR] [--compact] [--automation-read-root DIR] [--automation-write-root DIR] + [--headless] [--when-closed launch|headless|error] MCP server on stdin/stdout (opt-in) + while AI agents may use PdfCraft (ArtCraft Launcher › Settings › + AI agents), the ui_* tools drive the open window, found without a + port or token; --headless never looks for it; --when-closed + overrides what a closed app does (Preferences › AI Integrations) --compact lists a core set of tools plus tool_search and tool_call --automation-read-root / --automation-write-root confine the files the agent's tools read (open, combine, import, fonts, certificates…) and diff --git a/apps/pdfcraft-cli/src/options.rs b/apps/pdfcraft-cli/src/options.rs index 7b57d10e9f..18e1c573bb 100644 --- a/apps/pdfcraft-cli/src/options.rs +++ b/apps/pdfcraft-cli/src/options.rs @@ -150,8 +150,12 @@ pub(crate) const UI_OPTIONS: &[OptionSpec] = &[ ]; #[cfg(feature = "mcp")] -pub(crate) const MCP_OPTIONS: &[OptionSpec] = - &[OptionSpec { name: "--root", takes_value: true }, OptionSpec { name: "--compact", takes_value: false }]; +pub(crate) const MCP_OPTIONS: &[OptionSpec] = &[ + OptionSpec { name: "--root", takes_value: true }, + OptionSpec { name: "--compact", takes_value: false }, + OptionSpec { name: "--headless", takes_value: false }, + OptionSpec { name: "--when-closed", takes_value: true }, +]; /// The arguments that are not options or their values. Which tokens are values is the spec's /// answer: skipping the one after every option made `check-one --edit file.pdf` report "missing diff --git a/apps/pdfcraft-cli/src/run.rs b/apps/pdfcraft-cli/src/run.rs index 0726087d9d..cfa1acd6ba 100644 --- a/apps/pdfcraft-cli/src/run.rs +++ b/apps/pdfcraft-cli/src/run.rs @@ -142,11 +142,19 @@ pub(crate) fn run(args: &[String]) -> Result<(), CliError> { print_output(&auto, content, flag(args, "--out")) } +/// The automation roots a command was given, opened, and the folders as given. +#[cfg(feature = "mcp")] +pub(crate) struct GivenRoots { + pub roots: Option>, + pub read: Option, + pub write: Option, +} + /// Take `--automation-read-root` / `--automation-write-root` (each `--flag DIR` or `--flag=DIR`, /// once) out of `args`, and open the roots, which must be existing folders. Returns the arguments /// that are left. A malformed root flag is an error, never a root silently left out. #[cfg(feature = "mcp")] -fn automation_roots(command: &str, args: &[String]) -> Result<(Option>, Vec), String> { +fn automation_roots(command: &str, args: &[String]) -> Result<(GivenRoots, Vec), String> { let mut found = automation_args::AutomationArgs::new(None, None); let mut left = Vec::new(); let mut it = args.iter().cloned(); @@ -157,17 +165,30 @@ fn automation_roots(command: &str, args: &[String]) -> Result<(Option Result<(), CliError> { - let (roots, args) = automation_roots("mcp", args)?; + let (given, args) = automation_roots("mcp", args)?; let args = args.as_slice(); validate_options("mcp", args, MCP_OPTIONS)?; let compact = args.iter().any(|a| a == "--compact"); + // `value_of_flag` refuses `--when-closed` given without a value. + let when_closed = match super::options::value_of_flag("mcp", args, MCP_OPTIONS, "--when-closed")? { + Some(name) => Some( + craft::control::agents::WhenAppClosed::parse(name).ok_or(format!("mcp: --when-closed takes launch, headless or error, not {name:?}"))?, + ), + None => None, + }; let mut auto = automation(args)?; - if let Some(roots) = roots { + // Plain `mcp` follows the open window while the suite's AI-MCP flag is on, unless `--headless` + // says otherwise or there is no settings folder to find the window by. + let live_dir = if args.iter().any(|a| a == "--headless") || !craft::control::agents::mcp_flag() { None } else { super::agents::settings_dir() }; + if let Some(dir) = live_dir { + return mcp_live(dir, given, when_closed, flag(args, "--root").map(std::path::PathBuf::from), compact); + } + if let Some(roots) = given.roots { let show = |root: Option<&Path>| root.map_or_else(|| "none".to_string(), |r| r.display().to_string()); let _ = writeln!( std::io::stderr().lock(), @@ -186,3 +207,37 @@ pub(crate) fn mcp(args: &[String]) -> Result<(), CliError> { ); server.serve(std::io::stdin().lock(), std::io::stdout().lock()).map_err(|e| CliError::Message(e.to_string())) } + +/// Plain `mcp` with the launcher's switch in play: the open window while the person lets agents +/// use PdfCraft, otherwise a session without a window ([`super::agents`]). +#[cfg(feature = "mcp")] +fn mcp_live( + dir: std::path::PathBuf, + given: GivenRoots, + when_closed: Option, + root: Option, + compact: bool, +) -> Result<(), CliError> { + use super::agents::{APP_EXE, LiveConfig, LiveSessions}; + let mut cfg = LiveConfig::new(dir); + cfg.when_closed = when_closed; + cfg.read_root = given.read; + cfg.write_root = given.write; + cfg.launch = std::env::current_exe().ok().and_then(|exe| craft::control::agents::launcher(&exe, APP_EXE)); + let make = Box::new(move |roots| { + let a = pdfcraft_automation::Automation::new(); + let a = match &root { + Some(root) => a.with_root(root).map_err(|e| format!("--root {}: {e}", root.display()))?, + None => a, + }; + Ok(a.with_automation_roots(roots)) + }); + let mut server = pdfcraft_automation::mcp::McpServer::routed(LiveSessions::new(cfg, make)).with_compact(compact); + let _ = writeln!( + std::io::stderr().lock(), + "pdfcraft-cli: MCP server on stdio (protocol {}{}); the open PdfCraft window while AI agents may use it (ArtCraft Launcher › Settings › AI agents), otherwise a session without a window; close stdin to stop", + pdfcraft_automation::mcp::PROTOCOL_VERSIONS[0], + if compact { ", compact tool list" } else { "" } + ); + server.serve(std::io::stdin().lock(), std::io::stdout().lock()).map_err(|e| CliError::Message(e.to_string())) +} diff --git a/apps/pdfcraft-cli/tests/it/automation_roots.rs b/apps/pdfcraft-cli/tests/it/automation_roots.rs index 162d79bafd..dc870fa7d4 100644 --- a/apps/pdfcraft-cli/tests/it/automation_roots.rs +++ b/apps/pdfcraft-cli/tests/it/automation_roots.rs @@ -32,7 +32,16 @@ fn folders(tag: &str) -> PathBuf { /// Run `mcp `, send `calls` as `tools/call` requests and return the replies. fn session(flags: &[String], calls: &[(&str, Value)]) -> (Vec, String) { - let mut child = Command::new(BIN).arg("mcp").args(flags).stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped()).spawn().unwrap(); + // A session without a window, whatever this computer's AI-MCP flag says. + let mut child = Command::new(BIN) + .arg("mcp") + .args(flags) + .env("CRAFT_FLAGS", "-AI-MCP") + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .unwrap(); let mut input = String::from("{\"jsonrpc\":\"2.0\",\"id\":0,\"method\":\"initialize\",\"params\":{}}\n"); for (i, (name, args)) in calls.iter().enumerate() { let r = json!({"jsonrpc": "2.0", "id": i + 1, "method": "tools/call", "params": {"name": name, "arguments": args}}); diff --git a/apps/pdfcraft-cli/tests/it/main.rs b/apps/pdfcraft-cli/tests/it/main.rs index aff6ba18dd..92ba01f71b 100644 --- a/apps/pdfcraft-cli/tests/it/main.rs +++ b/apps/pdfcraft-cli/tests/it/main.rs @@ -12,6 +12,7 @@ mod help; mod info_repairs; mod info_standards; mod mcp_compact; +mod mcp_live; mod option_operands; mod options; mod owner_password; diff --git a/apps/pdfcraft-cli/tests/it/mcp_compact.rs b/apps/pdfcraft-cli/tests/it/mcp_compact.rs index a3864d46e4..693a2ecc92 100644 --- a/apps/pdfcraft-cli/tests/it/mcp_compact.rs +++ b/apps/pdfcraft-cli/tests/it/mcp_compact.rs @@ -11,6 +11,8 @@ fn session(flags: &[&str], requests: &[Value]) -> Vec { let mut child = Command::new(env!("CARGO_BIN_EXE_pdfcraft-cli")) .arg("mcp") .args(flags) + // A session without a window, whatever this computer's AI-MCP flag says. + .env("CRAFT_FLAGS", "-AI-MCP") .stdin(Stdio::piped()) .stdout(Stdio::piped()) .stderr(Stdio::null()) diff --git a/apps/pdfcraft-cli/tests/it/mcp_live.rs b/apps/pdfcraft-cli/tests/it/mcp_live.rs new file mode 100644 index 0000000000..69cc901722 --- /dev/null +++ b/apps/pdfcraft-cli/tests/it/mcp_live.rs @@ -0,0 +1,80 @@ +//! Plain `pdfcraft-cli mcp` with the suite's AI-MCP flag: it looks for the open window the +//! ArtCraft Launcher's switch lets agents into, and works without one when there is none. +#![cfg(feature = "mcp")] + +use std::io::Write as _; +use std::path::{Path, PathBuf}; +use std::process::{Command, Stdio}; + +use serde_json::{Value, json}; + +const BIN: &str = env!("CARGO_BIN_EXE_pdfcraft-cli"); + +fn temp(tag: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("pdfcraft-cli-live-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(dir.join("settings")).unwrap(); + std::fs::create_dir_all(dir.join("launcher")).unwrap(); + dir +} + +/// `mcp ` with AI-MCP on, its settings in `base/settings` and a launcher that lists no app +/// (the switch off for PdfCraft); sends `requests` and returns the replies. +fn session(base: &Path, flags: &[&str], requests: &[Value]) -> Vec { + let mut child = Command::new(BIN) + .arg("mcp") + .args(flags) + .env("CRAFT_FLAGS", "AI-MCP") + .env("CRAFT_MCP_DIR", base.join("launcher")) + .env("PDFCRAFT_CONFIG_DIR", base.join("settings")) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::null()) + .spawn() + .unwrap(); + let mut stdin = child.stdin.take().unwrap(); + for r in requests { + writeln!(stdin, "{r}").unwrap(); + } + drop(stdin); + let out = child.wait_with_output().unwrap(); + String::from_utf8(out.stdout).unwrap().lines().map(|l| serde_json::from_str(l).unwrap()).collect() +} + +fn tool_names(reply: &Value) -> Vec { + reply["result"]["tools"].as_array().unwrap().iter().map(|t| t["name"].as_str().unwrap().to_owned()).collect() +} + +// Plain `mcp` offers the window tools and the folders tool; with the switch off they say what to +// do, and the document tools work in a session without a window. +#[test] +fn plain_mcp_offers_the_window_and_works_without_it() { + let base = temp("plain"); + let call = |id: u64, name: &str| json!({"jsonrpc": "2.0", "id": id, "method": "tools/call", "params": {"name": name, "arguments": {}}}); + let replies = session(&base, &[], &[json!({"jsonrpc": "2.0", "id": 1, "method": "tools/list"}), call(2, "ui_state"), call(3, "doc_inspect")]); + let names = tool_names(&replies[0]); + assert!(names.iter().any(|n| n == "ui_state") && names.iter().any(|n| n == "agent_folders"), "{names:?}"); + assert_eq!(replies[1]["result"]["isError"], true); + assert!(replies[1]["result"]["content"][0]["text"].as_str().unwrap().contains("needs the open PdfCraft window"), "{}", replies[1]); + assert_eq!(replies[2]["result"]["isError"], false, "{}", replies[2]); + let _ = std::fs::remove_dir_all(base); +} + +// `--headless` never looks for the window: the tool list is the document tools alone. +#[test] +fn headless_mcp_has_no_window_tools() { + let base = temp("headless"); + let replies = session(&base, &["--headless"], &[json!({"jsonrpc": "2.0", "id": 1, "method": "tools/list"})]); + let names = tool_names(&replies[0]); + assert!(!names.iter().any(|n| n.starts_with("ui_") || n == "agent_folders"), "{names:?}"); + let _ = std::fs::remove_dir_all(base); +} + +// `--when-closed` without a value stops the command instead of falling back to the saved choice. +#[test] +fn when_closed_needs_a_value() { + let out = Command::new(BIN).args(["mcp", "--when-closed"]).stdin(Stdio::null()).output().unwrap(); + assert!(!out.status.success(), "a bare --when-closed must not start a server"); + assert!(out.stdout.is_empty()); + assert!(String::from_utf8_lossy(&out.stderr).contains("--when-closed"), "{}", String::from_utf8_lossy(&out.stderr)); +} diff --git a/apps/pdfcraft/Cargo.toml b/apps/pdfcraft/Cargo.toml index 733708686f..4e86670b48 100644 --- a/apps/pdfcraft/Cargo.toml +++ b/apps/pdfcraft/Cargo.toml @@ -14,11 +14,13 @@ workspace = true pdfcraft-ui-egui = { workspace = true } # The framework, through its facade (contract head): host, platform, automation, pages and quit, # and the UI runtime and window policy the window is installed with. -craft = { workspace = true, features = ["platform", "automation", "pages", "quit", "ui", "window"] } +craft = { workspace = true, features = ["platform", "automation", "automation-agents", "control-agents", "pages", "quit", "ui", "window"] } # Shared nightly-v1 profile isolation, launch protocol, and security fence. craft-nightly = { workspace = true } # `build_info`: the version and compile-time build label for `--version` and the log. pdfcraft-engine = { workspace = true } +# The agent folders' rules for agents in the open window, the same as `pdfcraft-cli mcp`'s. +pdfcraft-automation = { workspace = true } # `crypto_env`: the cryptography environment the engine opens files with. pdfcraft-platform = { workspace = true } # wgpu draws; OpenGL (glow) is the fallback when wgpu can't start on an old or unusual GPU or diff --git a/apps/pdfcraft/src/main.rs b/apps/pdfcraft/src/main.rs index 70d123d9fa..0dde642517 100644 --- a/apps/pdfcraft/src/main.rs +++ b/apps/pdfcraft/src/main.rs @@ -193,6 +193,45 @@ fn settings_dir() -> Option { pdfcraft_ui_egui::settings::resolution().dir.clone() } +/// Agents in the open window (`pdfcraft_ui_egui::agents`): while the ArtCraft Launcher's switch +/// names PdfCraft, the window serves agents on loopback and publishes the connection in its +/// settings folder `dir`, where `pdfcraft-cli mcp` finds it. A connection file a crashed run left +/// is removed first. With `--control` (`launched`: the port it listens on) that channel serves the +/// whole run and the link stays off. +fn agents_link(ctx: &egui::Context, dir: std::path::PathBuf, launched: Option>) -> pdfcraft_ui_egui::agents::Agents { + use craft::automation::agents::{AgentSwitch, remove_stale_connection}; + use pdfcraft_automation::file_access::{Access, AutomationRoots}; + use pdfcraft_ui_egui::agent_scope::{self, FileUse, Guard}; + use pdfcraft_ui_egui::agents::{Agents, GuardFn, LAUNCHER_APP_ID, SaveFn, read_settings, write_settings}; + remove_stale_connection(&dir); + let switch = AgentSwitch::watch(LAUNCHER_APP_ID, { + let ctx = ctx.clone(); + move || ctx.request_repaint() + }); + let save_dir = dir.clone(); + let save: SaveFn = Box::new(move |settings| { + write_settings(&save_dir, settings).map_err(|e| format!("couldn't save the agent settings in {}: {e}", save_dir.display())) + }); + // The same folder rules as `pdfcraft-cli mcp --automation-read-root/--automation-write-root`. + let guard_for: GuardFn = Box::new(|folders| { + let Some(roots) = AutomationRoots::new(folders.read.as_deref(), folders.write.as_deref())? else { return Ok(agent_scope::deny_all()) }; + let guard: Guard = std::sync::Arc::new(move |path: &std::path::Path, use_| { + let access = match use_ { + FileUse::Read => Access::Read, + FileUse::Write => Access::Write, + }; + roots.check_path(&path.to_string_lossy(), path, access) + }); + Ok(guard) + }); + let version = format!("PdfCraft {}", env!("CARGO_PKG_VERSION")); + let agents = Agents::new(dir.clone(), version, switch, read_settings(&dir), save, guard_for); + match launched { + Some(port) => agents.launched_with_control(port), + None => agents, + } +} + /// Whether settings, logs and recovery live beside the executable (#157). fn portable() -> bool { pdfcraft_ui_egui::settings::resolution().rule == craft::settings::Rule::Portable @@ -715,12 +754,20 @@ fn app_creator<'a>( } // `--control` was asked for: carrying on without the server would leave a script driving // nothing, so a port that can't be listened on stops the launch before any document opens. + let mut launched_control = None; if let Some((port, token)) = &control { let host = craft::ui::runtime::windows::WindowHost::of(&cc.egui_ctx); let (requests, listening) = craft::automation::server::listen(*port, token.clone(), host).map_err(|e| format!("--control {port}: {e}"))?; + launched_control = Some(listening.addr.port()); app.attach_control(craft::automation::ControlChannel::new(requests), Some(listening)); } + // A nightly lets no agents into the window, nor does a run without a settings folder. + if !is_nightly() + && let Some(dir) = settings_dir() + { + app.with_agents(agents_link(&cc.egui_ctx, dir, control.is_some().then_some(launched_control))); + } // The OCR Verify screen stores its per-language dictionary in the data folder. app.ocr_verify.dictionary_dir = pdfcraft_ui_egui::settings::dictionary_dir(); if let Some(state) = &cc.wgpu_render_state { diff --git a/crates/automation/src/mcp.rs b/crates/automation/src/mcp.rs index 5b248b3a17..479a662896 100644 --- a/crates/automation/src/mcp.rs +++ b/crates/automation/src/mcp.rs @@ -65,8 +65,38 @@ pub const COMPACT_CORE_TOOLS: &[&str] = &[ const TOOL_SEARCH: &str = "tool_search"; const TOOL_CALL: &str = "tool_call"; -pub struct McpServer { - automation: Automation, +/// Where a server's calls run. A plain [`Automation`] runs them all in its one session; plain +/// `pdfcraft-cli mcp` routes them to the open window or a session without one (the CLI's `agents` +/// module), and adds the tools that reach the window. +pub trait Sessions { + /// The session the next document call (a tool or a resource) runs in. `Err` is that call's error. + fn session(&mut self) -> Result<&mut Automation, String>; + + /// The tools this router adds, listed after the automation tools (MCP tool objects). + fn extra_tools(&self) -> Vec { + Vec::new() + } + + /// Runs an added tool; `None` for a name it doesn't add. + fn call_extra(&mut self, name: &str, args: &Value) -> Option, String>> { + let _ = (name, args); + None + } + + /// A sentence the server's instructions end with. + fn instructions(&self) -> Option<&str> { + None + } +} + +impl Sessions for Automation { + fn session(&mut self) -> Result<&mut Automation, String> { + Ok(self) + } +} + +pub struct McpServer { + automation: S, compact: bool, } @@ -75,6 +105,17 @@ impl McpServer { Self { automation, compact: false } } + pub fn automation(&self) -> &Automation { + &self.automation + } +} + +impl McpServer { + /// A server whose calls `sessions` routes. + pub fn routed(sessions: S) -> Self { + Self { automation: sessions, compact: false } + } + /// In compact mode `tools/list` returns only [`COMPACT_CORE_TOOLS`] plus `tool_search` and /// `tool_call`, which find and run any other tool. `tools/call` accepts every tool by name /// either way. Off by default. @@ -83,10 +124,6 @@ impl McpServer { self } - pub fn automation(&self) -> &Automation { - &self.automation - } - /// Serve until `input` reaches end of file. pub fn serve(&mut self, mut input: impl BufRead, mut output: impl Write) -> std::io::Result<()> { while let Some(incoming) = read_message(&mut input, MAX_LINE_BYTES)? { @@ -137,7 +174,11 @@ impl McpServer { "protocolVersion": version, "capabilities": { "tools": { "listChanged": false }, "resources": { "listChanged": false, "subscribe": false } }, "serverInfo": { "name": "pdfcraft", "title": "PdfCraft", "version": env!("CARGO_PKG_VERSION"), "websiteUrl": pdfcraft_engine::links::APP_PAGE }, - "instructions": if self.compact { format!("{INSTRUCTIONS}{COMPACT_INSTRUCTIONS}") } else { INSTRUCTIONS.to_string() }, + "instructions": format!( + "{INSTRUCTIONS}{}{}", + if self.compact { COMPACT_INSTRUCTIONS } else { "" }, + self.automation.instructions().map(|more| format!(" {more}")).unwrap_or_default() + ), })) } "ping" => Ok(json!({})), @@ -158,7 +199,14 @@ impl McpServer { Ok(pair) => pair, Err(message) => return Ok(tool_error(&message)), }; - return Ok(match self.automation.call(&inner, &inner_args) { + if let Some(result) = self.automation.call_extra(&inner, &inner_args) { + return Ok(extra_result(&inner, result)); + } + let session = match self.automation.session() { + Ok(session) => session, + Err(message) => return Ok(tool_error(&message)), + }; + return Ok(match session.call(&inner, &inner_args) { Ok(content) => tool_content(&inner, content), Err(ToolError::UnknownTool(t)) => tool_error(&format!("unknown tool {t:?}; use tool_search to find the right name")), Err(e) => tool_error(&e.to_string()), @@ -173,13 +221,20 @@ impl McpServer { .unwrap_or_default(); check_keys(name, &args, &keys).map_err(|e| (INVALID_PARAMS, e))?; } - match self.automation.call(name, &args) { + if let Some(result) = self.automation.call_extra(name, &args) { + return Ok(extra_result(name, result)); + } + let session = match self.automation.session() { + Ok(session) => session, + Err(message) => return Ok(tool_error(&message)), + }; + match session.call(name, &args) { Ok(content) => Ok(tool_content(name, content)), Err(ToolError::UnknownTool(t)) => Err((INVALID_PARAMS, format!("unknown tool {t:?}"))), Err(e) => Ok(tool_error(&e.to_string())), } } - "resources/list" => Ok(json!({ "resources": self.resource_list() })), + "resources/list" => Ok(json!({ "resources": self.resource_list()? })), "resources/templates/list" => Ok(json!({ "resourceTemplates": resource_templates() })), "resources/read" => { let uri = params.get("uri").and_then(Value::as_str).ok_or((INVALID_PARAMS, "resources/read needs a uri".to_string()))?; @@ -190,19 +245,31 @@ impl McpServer { } } -impl McpServer { - /// What `tools/list` returns: every tool, or in compact mode the core set and the meta tools. +impl McpServer { + /// What `tools/list` returns: every tool, or in compact mode the core set and the meta tools; + /// then the router's own tools. fn tool_list(&self) -> Vec { let all = crate::tools(); - if !self.compact { - return all.iter().map(tool_json).collect(); - } - let mut out: Vec = COMPACT_CORE_TOOLS.iter().filter_map(|n| all.iter().find(|t| t.name == *n)).map(tool_json).collect(); - out.extend(meta_tools()); + let mut out: Vec = if self.compact { + let mut out: Vec = COMPACT_CORE_TOOLS.iter().filter_map(|n| all.iter().find(|t| t.name == *n)).map(tool_json).collect(); + out.extend(meta_tools()); + out + } else { + all.iter().map(tool_json).collect() + }; + out.extend(self.automation.extra_tools()); out } } +/// A router tool's result, as the agent reads it. +fn extra_result(name: &str, result: Result, String>) -> Value { + match result { + Ok(content) => tool_content(name, content), + Err(message) => tool_error(&message), + } +} + /// The two tools only compact mode lists. fn meta_tools() -> [Value; 2] { [ @@ -397,9 +464,11 @@ fn resource_templates() -> Value { ]) } -impl McpServer { - fn resource_list(&mut self) -> Vec { - let docs = self.automation.call("doc_list", &json!({})).ok().and_then(|c| match c.into_iter().next() { +impl McpServer { + fn resource_list(&mut self) -> Result, (i64, String)> { + // A route that can't be used is the call's error, not an empty session. + let session = self.automation.session().map_err(|e| (INVALID_PARAMS, e))?; + let docs = session.call("doc_list", &json!({})).ok().and_then(|c| match c.into_iter().next() { Some(Content::Json(v)) => v["documents"].as_array().cloned(), _ => None, }); @@ -422,7 +491,7 @@ impl McpServer { json!({"uri":"pdfcraft://document","name":"Open documents","mimeType":"application/json","description":"Session document state, as doc_inspect without arguments."}), json!({"uri":"pdfcraft://commands","name":"Command catalog","mimeType":"application/json","description":"Commands and mapped tool schemas, as command_list without arguments."}), ]); - out + Ok(out) } fn read_resource(&mut self, uri: &str) -> Result { @@ -431,7 +500,8 @@ impl McpServer { "pdfcraft://commands" => Some("command_list"), _ => None, } { - let content = self.automation.call(tool, &json!({})).map_err(|e| (INVALID_PARAMS, e.to_string()))?; + let content = + self.automation.session().map_err(|e| (INVALID_PARAMS, e))?.call(tool, &json!({})).map_err(|e| (INVALID_PARAMS, e.to_string()))?; let value = content .into_iter() .find_map(|c| match c { @@ -442,6 +512,7 @@ impl McpServer { return Ok(json!({"uri":uri,"mimeType":"application/json","text":value.to_string()})); } let r = parse_uri(uri).ok_or((INVALID_PARAMS, format!("unknown resource {uri:?}")))?; + let session = self.automation.session().map_err(|e| (INVALID_PARAMS, e))?; let call = |a: &mut Automation, tool: &str, args: Value| a.call(tool, &args).map_err(|e| (INVALID_PARAMS, e.to_string())); let json_of = |c: Vec| c.into_iter().find_map(|c| if let Content::Json(v) = c { Some(v) } else { None }).unwrap_or(Value::Null); let text_of = |v: &Value, headings: bool| { @@ -457,15 +528,15 @@ impl McpServer { }; Ok(match r { Resource::Info(doc) => { - let v = json_of(call(&mut self.automation, "doc_info", json!({ "doc": doc }))?); + let v = json_of(call(session, "doc_info", json!({ "doc": doc }))?); json!({ "uri": uri, "mimeType": "application/json", "text": serde_json::to_string_pretty(&v).unwrap_or_default() }) } Resource::Text(doc) => { - let v = json_of(call(&mut self.automation, "text_extract", json!({ "doc": doc }))?); + let v = json_of(call(session, "text_extract", json!({ "doc": doc }))?); json!({ "uri": uri, "mimeType": "text/plain", "text": text_of(&v, true) }) } Resource::PageText(doc, page) => { - let v = json_of(call(&mut self.automation, "text_extract", json!({ "doc": doc, "pages": [page] }))?); + let v = json_of(call(session, "text_extract", json!({ "doc": doc, "pages": [page] }))?); json!({ "uri": uri, "mimeType": "text/plain", "text": text_of(&v, false) }) } Resource::PageImage(doc, page, dpi) => { @@ -473,9 +544,8 @@ impl McpServer { if let Some(d) = dpi { args["dpi"] = json!(d); } - let png = call(&mut self.automation, "page_render", args)? - .into_iter() - .find_map(|c| if let Content::Png { data, .. } = c { Some(data) } else { None }); + let png = + call(session, "page_render", args)?.into_iter().find_map(|c| if let Content::Png { data, .. } = c { Some(data) } else { None }); let png = png.ok_or((INVALID_PARAMS, "the page could not be rendered".to_string()))?; json!({ "uri": uri, "mimeType": "image/png", "blob": base64::engine::general_purpose::STANDARD.encode(png) }) } diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index 5a001a1100..a53ebc1666 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -60,7 +60,8 @@ skrifa = "0.44" # Help ▸ Check for updates: the facade's update crate builds only natively. The file service and the save flow # (`dialogs`) sit on rfd's blocking panels and threads, so they are native too; the web saves through the # platform's BrowserFiles (`editing/save.rs`). -craft = { workspace = true, features = ["update", "platform-clipboard-system", "dialogs"] } +# Agents in the open window (`agents.rs`): the ArtCraft Launcher's switch, the link host and the Agents page. +craft = { workspace = true, features = ["update", "platform-clipboard-system", "dialogs", "automation-agents", "control-agents"] } # Control-channel tokens. getrandom = "0.4" # Create ▸ Clipboard (images; already in the tree through egui-winit). diff --git a/crates/ui-egui/src/agent_scope.rs b/crates/ui-egui/src/agent_scope.rs new file mode 100644 index 0000000000..194486b5dd --- /dev/null +++ b/crates/ui-egui/src/agent_scope.rs @@ -0,0 +1,53 @@ +//! The agent folders in force on the UI thread: while the window answers a request from an agent +//! in the open window, and while the input that request queued is handled, every file the window +//! opens or saves for it must lie in the agent folders ([`crate::agents`]). The person's own work +//! runs with nothing in force. +//! +//! The window checks a path where it opens a file ([`crate::PdfCraftApp::open_path`] and the +//! others that open through it) and in its file service ([`crate::confined_files::ConfinedFiles`]: +//! saves, reads, and the file picks a request answers). + +use std::cell::RefCell; +use std::path::Path; +use std::sync::Arc; + +/// Opening a file, or saving one. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum FileUse { + Read, + Write, +} + +/// Whether the agent folders allow `FileUse` of a path; `Err` says why not, in words for the agent. +pub type Guard = Arc Result<(), String> + Send + Sync>; + +/// A guard that allows nothing: agents have no folder to use. +pub fn deny_all() -> Guard { + Arc::new(|path, _| Err(format!("agents have no folder to open or save files in, so {} can't be used", path.display()))) +} + +thread_local! { + static CURRENT: RefCell> = const { RefCell::new(None) }; +} + +/// Runs `f` with `guard` in force on this thread (none: as before), then puts back what was. +pub fn confine(guard: Option<&Guard>, f: impl FnOnce() -> R) -> R { + let before = CURRENT.with(|current| current.replace(guard.cloned())); + let result = f(); + CURRENT.with(|current| *current.borrow_mut() = before); + result +} + +/// Whether an agent's folders are in force on this thread. +pub fn confined() -> bool { + CURRENT.with(|current| current.borrow().is_some()) +} + +/// `Err` when the folders in force refuse `use_` of `path`; `Ok` with none in force. +pub fn check(path: &Path, use_: FileUse) -> Result<(), String> { + let guard = CURRENT.with(|current| current.borrow().clone()); + match guard { + Some(guard) => guard(path, use_), + None => Ok(()), + } +} diff --git a/crates/ui-egui/src/agent_settings.rs b/crates/ui-egui/src/agent_settings.rs new file mode 100644 index 0000000000..50d67aacf4 --- /dev/null +++ b/crates/ui-egui/src/agent_settings.rs @@ -0,0 +1,68 @@ +//! The agent settings of Preferences › AI Integrations, in `agents.json` in the settings folder. +//! The desktop app writes them when the person changes them (`crate::agents::write_settings`); `pdfcraft-cli` +//! (which includes this file) reads them on every tool call of plain `mcp`, for the closed-app +//! choice and the agent folders. No egui here: the CLI builds it too. + +use std::io::Read as _; +use std::path::Path; + +use craft::control::agents::AgentSettings; +use serde_json::Value; + +/// The file in the settings folder: `{"controlPort", "readRoot", "writeRoot", "whenAppClosed", +/// "allowAgentControl"}`, the framework's `AgentSettings`. +pub const SETTINGS_FILE: &str = "agents.json"; + +/// The largest settings file read; the settings are a few short strings. +const MAX_SETTINGS_FILE: u64 = 64 * 1024; + +/// The agent settings saved in `dir`; the defaults when nothing is saved or the file can't be read, +/// so neither the app nor the CLI fails over them. One bad value resets only itself. +pub fn read_settings(dir: &Path) -> AgentSettings { + let Ok(file) = std::fs::File::open(dir.join(SETTINGS_FILE)) else { return AgentSettings::default() }; + let mut text = String::new(); + if file.take(MAX_SETTINGS_FILE + 1).read_to_string(&mut text).is_err() || text.len() as u64 > MAX_SETTINGS_FILE { + return AgentSettings::default(); + } + let Ok(Value::Object(saved)) = serde_json::from_str::(&text) else { return AgentSettings::default() }; + let mut settings = AgentSettings::default(); + for (key, value) in saved { + let Ok(Value::Object(mut one)) = serde_json::to_value(&settings) else { continue }; + if one.contains_key(&key) { + one.insert(key, value); + if let Ok(next) = serde_json::from_value(Value::Object(one)) { + settings = next; + } + } + } + settings +} + +#[cfg(test)] +mod tests { + #![allow(clippy::unwrap_used)] + + use super::*; + use craft::control::agents::WhenAppClosed; + + // Settings the app saves read back in the CLI, and a damaged file or value never fails it. + #[test] + fn saved_settings_read_back_and_bad_values_reset_alone() { + let dir = std::env::temp_dir().join(format!("pdfcraft-agent-settings-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + assert_eq!(read_settings(&dir), AgentSettings::default()); + let mut settings = AgentSettings::default(); + settings.read_root = "/in".into(); + settings.when_app_closed = WhenAppClosed::Headless; + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join(SETTINGS_FILE), serde_json::to_vec(&settings).unwrap()).unwrap(); + assert_eq!(read_settings(&dir), settings); + std::fs::write(dir.join(SETTINGS_FILE), "not json").unwrap(); + assert_eq!(read_settings(&dir), AgentSettings::default()); + std::fs::write(dir.join(SETTINGS_FILE), r#"{"whenAppClosed": "error", "readRoot": 5, "unknown": true}"#).unwrap(); + let read = read_settings(&dir); + assert_eq!(read.when_app_closed, WhenAppClosed::Error); + assert_eq!(read.read_root, ""); + let _ = std::fs::remove_dir_all(&dir); + } +} diff --git a/crates/ui-egui/src/agents.rs b/crates/ui-egui/src/agents.rs new file mode 100644 index 0000000000..b1e5f5bfe8 --- /dev/null +++ b/crates/ui-egui/src/agents.rs @@ -0,0 +1,228 @@ +//! Agents in the open window: while the ArtCraft Launcher's *Settings › AI agents* switch names +//! PdfCraft, the window serves its control channel to agents on loopback. +//! +//! The switch, the control server, its token and the connection file `pdfcraft-cli mcp` finds the +//! window by are the framework's (`craft::automation::agents::AgentSwitch` and `AgentLink`). +//! PdfCraft supplies its agent settings (`agents.json`, [`crate::agent_settings`]), answers the +//! requests with its own control methods ([`crate::control`]) and holds every file they open or +//! save to the agent folders ([`crate::agent_scope`]): those set in Preferences › AI Integrations, +//! or `Documents/ArtCraft/Agents/PdfCraft` for an empty one. Without a folder of a kind, that kind +//! of access is refused. + +use std::path::{Path, PathBuf}; + +use craft::automation::ControlChannel; +use craft::automation::agents::{AgentLink, AgentLinkStatus, AgentSettings, AgentSwitch, LinkProblem}; +use craft::control::agents::AgentFolders; +use craft::ui::runtime::windows::WindowHost; +use serde_json::{Value, json}; + +use crate::PdfCraftApp; +use crate::agent_scope::{self, Guard}; + +pub use crate::agent_settings::{SETTINGS_FILE, read_settings}; + +/// The id the ArtCraft Launcher's app list names PdfCraft by (its catalog id). +pub const LAUNCHER_APP_ID: &str = "pdfcraft"; +/// The app's name in messages and its default agent folder (`Documents/ArtCraft/Agents/PdfCraft`). +pub const APP_NAME: &str = "PdfCraft"; +/// The id of the Preferences page of the agent settings, and the key they sit under in its draft. +pub const PAGE: &str = "integrations"; +/// The page's title in Preferences, as the other Craft apps name it. +pub const PAGE_TITLE: &str = "AI Integrations"; + +/// Saves the agent settings where `pdfcraft-cli mcp` reads them; `Err` says why it couldn't. +pub type SaveFn = Box Result<(), String>>; +/// What agents may open and save with these folders; `Err` says why a folder can't be used. +pub type GuardFn = Box Result>; + +/// Saves `settings` in `dir` (created when missing), replacing the file in one step, so a +/// `pdfcraft-cli mcp` reading it at the same time sees the old or the new settings, never half. +pub fn write_settings(dir: &Path, settings: &AgentSettings) -> std::io::Result<()> { + std::fs::create_dir_all(dir)?; + let text = serde_json::to_vec_pretty(settings).map_err(std::io::Error::other)?; + let partial = dir.join(format!("{SETTINGS_FILE}.{}.tmp", std::process::id())); + std::fs::write(&partial, text)?; + std::fs::rename(&partial, dir.join(SETTINGS_FILE)).inspect_err(|_| { + let _ = std::fs::remove_file(&partial); + }) +} + +/// The agents link of the open window. +pub struct Agents { + /// The link; `None` while the launch options (`--control`) manage the control channel. + link: Option, + /// The status shown while the launch options manage the control channel. + launch: AgentLinkStatus, + switch: AgentSwitch, + settings: AgentSettings, + save: SaveFn, + guard_for: GuardFn, + default_folder: Option, +} + +impl Agents { + /// The link for the window, keeping its token and connection file in `settings_dir` and naming + /// `app` (the version string) in the connection file, following `switch` with the saved + /// `settings`; `save` stores the settings when the person changes them, `guard_for` turns the + /// agent folders into the check every file an agent's request opens or saves goes through. + pub fn new(settings_dir: PathBuf, app: String, switch: AgentSwitch, settings: AgentSettings, save: SaveFn, guard_for: GuardFn) -> Self { + Self { + link: Some(AgentLink::new(Some(settings_dir), app)), + launch: AgentLinkStatus::default(), + switch, + settings, + save, + guard_for, + default_folder: craft::control::agents::default_folder(APP_NAME), + } + } + + /// The window was started with `--control`, listening on `port`: that channel serves the whole + /// run, the link stays off and Preferences says the launch options manage it. + pub fn launched_with_control(mut self, port: Option) -> Self { + self.link = None; + self.launch.port = port; + self.launch.launch_flags = true; + self + } + + /// `default` replaces the default agent folder (tests). + pub fn with_default_folder(mut self, default: Option) -> Self { + self.default_folder = default; + self + } + + /// The saved agent settings. + pub fn settings(&self) -> &AgentSettings { + &self.settings + } + + /// Where the link stands, for Preferences and `ui.state`. + pub fn status(&self) -> &AgentLinkStatus { + self.link.as_ref().map_or(&self.launch, AgentLink::status) + } + + /// The suite's `AI-MCP` flag: the launcher's switch decides, and Preferences shows its state. + pub fn mcp_flag(&self) -> bool { + self.switch.mcp_flag() + } + + /// Whether the launcher's switch lets agents use PdfCraft now. + pub fn allowed(&self) -> bool { + // PdfCraft had no agent consent of its own before the switch. + self.switch.allows(false) + } +} + +impl PdfCraftApp { + /// Lets agents into this window while the ArtCraft Launcher's switch names PdfCraft + /// ([`crate::agents`]): their requests, the input they queue and the files the window opens + /// and saves for them stay inside the agent folders. + pub fn with_agents(&mut self, agents: Agents) { + self.agents = Some(Box::new(agents)); + } + + /// Saves `settings` as the agent settings; the link applies them on the next pass. Refused + /// while an agent's request or its input is handled: widening the agent folders is the + /// person's choice. + pub(crate) fn set_agent_settings(&mut self, settings: AgentSettings) -> Result<(), String> { + let Some(agents) = self.agents.as_mut() else { return Err("this window lets no agents in".into()) }; + if agent_scope::confined() { + return Err(format!("agents can't change the agent settings: the person sets them in Preferences › {PAGE_TITLE}")); + } + if settings.control_port > u32::from(u16::MAX) { + return Err(format!("the control port must be 0 to {}, not {}", u16::MAX, settings.control_port)); + } + (agents.save)(&settings)?; + agents.settings = settings; + Ok(()) + } + + /// What Preferences' Agents page needs: the saved settings, the link's status and the suite's + /// `AI-MCP` flag; `None` when the window lets no agents in. + pub(crate) fn agents_page_state(&self) -> Option<(AgentSettings, AgentLinkStatus, bool)> { + let agents = self.agents.as_ref()?; + Some((agents.settings().clone(), agents.status().clone(), agents.mcp_flag())) + } + + /// `ui.state`'s `agents`: the link's status, the launcher's switch and the flag. + pub(crate) fn agents_state(&self) -> Value { + match self.agents.as_ref() { + Some(agents) => json!({"status": agents.status(), "allowed": agents.allowed(), "mcpFlag": agents.mcp_flag()}), + None => Value::Null, + } + } +} + +/// Once a frame, before the control requests are answered: brings the link in line with the +/// launcher's switch and the saved settings. The control server starts, moves or stops; while it +/// runs, its requests are the window's control channel and run inside the agent folders. +pub(crate) fn sync(app: &mut PdfCraftApp, ctx: &egui::Context) { + let Some(agents) = app.agents.as_mut() else { return }; + let allowed = agents.allowed(); + let Some(link) = agents.link.as_mut() else { return }; + let update = link.sync(allowed.then_some(&agents.settings), &WindowHost::of(ctx)); + if update.stopped { + // Keys and clicks an agent queued must not run once its folders are no longer in force. + if app.agent_input.take().is_some() { + WindowHost::of(ctx).withdraw_injected(egui::ViewportId::ROOT); + } + app.control = None; + } + if let Some(requests) = update.requests { + app.control = Some(ControlChannel::new(requests)); + } + if !update.changed { + return; + } + app.agent_folders = None; + app.agent_guard = Some(if link.status().port.is_none() { + agent_scope::deny_all() + } else { + // Looked up only when something changed: the default folder is created on the way. + let folders = agents.settings.folders_with(agents.default_folder.as_deref()); + match (agents.guard_for)(&folders) { + Ok(guard) => { + app.agent_folders = Some(folders); + guard + } + Err(e) => { + link.note(LinkProblem::App(format!("Agents can't open or save files: {e}"))); + agent_scope::deny_all() + } + } + }); +} + +/// `agents.call {method, params, folders: {read, write}}`: runs `method` only while the agent +/// folders the window holds requests to are `folders`. `pdfcraft-cli mcp` started with folders of +/// its own checked that they are the window's; this binds the request to that check, so a change +/// in Preferences while the request is on its way can't let it run under other folders. +pub const BOUND_CALL: &str = "agents.call"; + +/// The method and params of an `agents.call` whose folders still hold; `Err` says why not. +pub(crate) fn bound_request(app: &PdfCraftApp, params: &Value) -> Result<(String, Value), String> { + let method = params.get("method").and_then(Value::as_str).ok_or("agents.call needs a method")?; + if method == BOUND_CALL { + return Err("agents.call can't call itself".into()); + } + let folder = |key: &str| match params.get("folders").and_then(|f| f.get(key)) { + Some(Value::String(path)) => Ok(Some(PathBuf::from(path))), + Some(Value::Null) => Ok(None), + _ => Err(format!("agents.call needs folders.{key}: a path or null")), + }; + let (read, write) = (folder("read")?, folder("write")?); + let same = |a: &Option, b: &Option| match (a, b) { + (Some(a), Some(b)) => std::fs::canonicalize(a).ok().is_some_and(|a| std::fs::canonicalize(b).ok().is_some_and(|b| a == b)), + (None, None) => true, + _ => false, + }; + let held = app.agent_folders.as_ref().is_some_and(|now| same(&read, &now.read) && same(&write, &now.write)); + if !held { + return Err( + "the agent folders in PdfCraft's Preferences › AI Integrations changed; nothing was done: check agent_folders and try again".into() + ); + } + Ok((method.to_owned(), params.get("params").cloned().unwrap_or_else(|| json!({})))) +} diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index e1d6de3f30..de008fc004 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -45,6 +45,7 @@ mod window; pub(crate) use metal_fullscreen::MetalFullscreen; pub(crate) use clipboard::{ObjectClipMark, copy_refused, print_refused}; +pub(crate) use control::AgentInput; pub(crate) use files::same_file; pub(crate) use prefs::{MAX_AUTHOR_CHARS, date_text_for_pdf}; @@ -179,6 +180,8 @@ impl PdfCraftApp { pub fn with_intake(ctx: &egui::Context, intake: FileIntake) -> Self { let services = AppServices::system(ctx, intake); let (files, panels) = craft::dialogs::service::FileService::new(services.wake.clone()); + // An agent's request in the open window reaches only the agent folders, also through the window's own saves. + let files = crate::confined_files::ConfinedFiles::new(Arc::new(files)); let host = Host::builder(APP_INFO).files(Arc::new(files)).i18n(i18n::host_catalogs()).build(); let mut app = Self::with_host(Arc::new(host), services); app.file_panels = Some(panels); @@ -507,6 +510,12 @@ impl PdfCraftApp { #[cfg(not(target_arch = "wasm32"))] control_server: None, control_epoch: 0, + #[cfg(not(target_arch = "wasm32"))] + agents: None, + agent_guard: None, + #[cfg(not(target_arch = "wasm32"))] + agent_folders: None, + agent_input: None, bookmark_clipboard: None, word_count_options: Default::default(), printer_marks_draft: Default::default(), @@ -759,7 +768,9 @@ impl PdfCraftApp { impl eframe::App for PdfCraftApp { /// The runtime's fired commands and this frame's root values, before egui reads the input. fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) { - self.prepare_raw_input(ctx, raw); + // The commands the keys and clicks an agent queued fire here, held to its folders. + let scope = self.agent_scope(); + crate::agent_scope::confine(scope.as_ref(), || self.prepare_raw_input(ctx, raw)); } /// The preferences go to the settings store, which writes them when they changed. @@ -791,7 +802,8 @@ impl eframe::App for PdfCraftApp { self.begin_logic(); #[cfg(not(target_arch = "wasm32"))] self.update_logic(ctx); - self.guarded_frame(ctx, |app| app.logic_unguarded(ctx)); + let scope = self.agent_scope(); + crate::agent_scope::confine(scope.as_ref(), || self.guarded_frame(ctx, |app| app.logic_unguarded(ctx))); self.run_close_path(ctx); } @@ -809,7 +821,9 @@ impl eframe::App for PdfCraftApp { panels.pump_with(&mut self.dialogs, Some(&*frame)); } let ctx = ui.ctx().clone(); - self.guarded_frame(&ctx, |app| app.ui_unguarded(ui)); + let scope = self.agent_scope(); + crate::agent_scope::confine(scope.as_ref(), || self.guarded_frame(&ctx, |app| app.ui_unguarded(ui))); + self.settle_agent_input(&ctx); self.end_ui(); if !self.frame_panicked && let Some(start) = self.startup_time.take() diff --git a/crates/ui-egui/src/app/control.rs b/crates/ui-egui/src/app/control.rs index 8f676c3508..bb47a9b440 100644 --- a/crates/ui-egui/src/app/control.rs +++ b/crates/ui-egui/src/app/control.rs @@ -3,7 +3,54 @@ use super::{ prepare, scroll_speed, ui_scale, }; +/// The agent folders an agent's request leaves in force while the input it queued is handled. +pub(crate) struct AgentInput { + guard: crate::agent_scope::Guard, + /// The frame the window host was first seen with no queued input left, once it was. + idle_since: Option, +} + impl PdfCraftApp { + /// The agent folders in force for this pass: those of an agent whose queued input is still to + /// be handled, otherwise none (the person's own input). + pub(crate) fn agent_scope(&self) -> Option { + self.agent_input.as_ref().map(|input| input.guard.clone()) + } + + /// `ui.state`'s `agents`: the link's status and the launcher's switch; `null` where agents + /// can't use the window. + pub(crate) fn agents_ui_state(&self) -> serde_json::Value { + #[cfg(not(target_arch = "wasm32"))] + return self.agents_state(); + #[cfg(target_arch = "wasm32")] + serde_json::Value::Null + } + + /// An agent's request queued input: its folders stay in force until that input is handled. + pub(crate) fn hold_agent_input(&mut self, guard: crate::agent_scope::Guard) { + self.agent_input = Some(AgentInput { guard, idle_since: None }); + } + + /// After a UI pass: once the window host has handled all the queued input, and one more frame + /// has passed (a shortcut fires its command in the next frame's input), the agent folders are + /// no longer in force. + pub(crate) fn settle_agent_input(&mut self, ctx: &egui::Context) { + let Some(input) = self.agent_input.as_mut() else { return }; + if !craft::ui::runtime::windows::WindowHost::of(ctx).injected_idle() { + input.idle_since = None; + return; + } + let frame = ctx.cumulative_frame_nr(); + match input.idle_since { + None => { + input.idle_since = Some(frame); + ctx.request_repaint(); + } + Some(since) if frame > since => self.agent_input = None, + Some(_) => {} + } + } + /// Enable the UI control channel (opt-in; see [`control`]): `channel` receives the requests, /// and `listening` is the loopback server that feeds it (`None` when something else feeds it). #[cfg(not(target_arch = "wasm32"))] diff --git a/crates/ui-egui/src/app/files.rs b/crates/ui-egui/src/app/files.rs index f3533cd53c..d994059d00 100644 --- a/crates/ui-egui/src/app/files.rs +++ b/crates/ui-egui/src/app/files.rs @@ -922,6 +922,10 @@ impl PdfCraftApp { display_override: Option<(canvas::PageDisplay, bool)>, target_group: Option<(crate::tab_group::TabGroupId, crate::panes::Place)>, ) -> OpenOutcome { + // An agent in the open window opens only from its read folder (`agent_scope`). + if let Err(refused) = crate::agent_scope::check(std::path::Path::new(path), crate::agent_scope::FileUse::Read) { + return OpenOutcome::Failed(refused); + } // One file, one tab (#2166): a file that is open already comes to the front instead, // and the tool it was opened for runs on it. One still being opened is left to that. if let Some(i) = self.tab_showing(path) { diff --git a/crates/ui-egui/src/confined_files.rs b/crates/ui-egui/src/confined_files.rs new file mode 100644 index 0000000000..b77ecee04f --- /dev/null +++ b/crates/ui-egui/src/confined_files.rs @@ -0,0 +1,135 @@ +//! The window's file service, held to the agent folders in force ([`crate::agent_scope`]). +//! +//! The window saves through the host's file service (Save, Save As, exports) and answers file +//! picks there (`ui.pick`). [`ConfinedFiles`] checks every such path while an agent's request or +//! the input it queued is handled, so an agent in the open window reaches only the agent folders. +//! Outside those nothing changes. + +use std::path::{Path, PathBuf}; +use std::sync::Arc; + +use craft::host::{FileError, Files, PickId, PickRequest, Picked, WriteIntent}; + +use crate::agent_scope::{self, FileUse}; + +/// `inner`, with every path checked against the agent folders in force on the calling thread. +pub struct ConfinedFiles { + inner: Arc, +} + +impl ConfinedFiles { + /// Wraps the window's file service. + pub fn new(inner: Arc) -> Self { + Self { inner } + } +} + +fn check(path: &Path, use_: FileUse) -> Result<(), FileError> { + agent_scope::check(path, use_).map_err(FileError::Other) +} + +impl Files for ConfinedFiles { + fn pick(&self, request: PickRequest) -> PickId { + self.inner.pick(request) + } + + fn take_answer(&self, id: PickId) -> Option { + self.inner.take_answer(id) + } + + fn forget(&self, id: PickId) { + self.inner.forget(id) + } + + fn pick_pending(&self) -> bool { + self.inner.pick_pending() + } + + fn read(&self, path: &Path) -> Result, FileError> { + check(path, FileUse::Read)?; + self.inner.read(path) + } + + fn write(&self, path: &Path, bytes: &[u8], intent: WriteIntent) -> Result { + check(path, FileUse::Write)?; + self.inner.write(path, bytes, intent) + } + + fn exists(&self, path: &Path) -> bool { + // A file the folders keep from the request isn't there for it either. + check(path, FileUse::Read).is_ok() && self.inner.exists(path) + } + + fn last_folder(&self, purpose: &str) -> Option { + self.inner.last_folder(purpose) + } + + fn save(&self, request: PickRequest, bytes: Vec) -> PickId { + self.inner.save(request, bytes) + } + + fn can_pick(&self) -> bool { + self.inner.can_pick() + } + + fn browser_saves(&self) -> bool { + self.inner.browser_saves() + } + + fn answer_next(&self, picked: Picked) -> Result<(), FileError> { + // The pick may be one to open or one the service saves to itself, past `write`: an + // agent's answer must be a path it may both read and write. + if agent_scope::confined() { + for path in picked.paths() { + check(&path, FileUse::Read)?; + check(&path, FileUse::Write)?; + } + } + self.inner.answer_next(picked) + } +} + +#[cfg(test)] +mod tests { + #![allow(clippy::unwrap_used)] + + use super::*; + use craft::host::NoPickFiles; + + fn temp(tag: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("pdfcraft-confined-files-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir + } + + // The window's own reads, saves and pick answers reach only the agent folders while they are + // in force, and everything as before outside them. + #[test] + fn reads_saves_and_picks_follow_the_folders_in_force() { + let base = temp("rw"); + let (inside, outside) = (base.join("agents"), base.join("elsewhere")); + std::fs::create_dir_all(&inside).unwrap(); + std::fs::create_dir_all(&outside).unwrap(); + std::fs::write(outside.join("secret.pdf"), b"secret").unwrap(); + std::fs::write(inside.join("doc.pdf"), b"doc").unwrap(); + let files = ConfinedFiles::new(Arc::new(NoPickFiles::default())); + let allowed = inside.clone(); + let guard: agent_scope::Guard = + Arc::new(move |path, _| if path.starts_with(&allowed) { Ok(()) } else { Err(format!("outside: {}", path.display())) }); + + agent_scope::confine(Some(&guard), || { + assert_eq!(files.read(&inside.join("doc.pdf")).unwrap(), b"doc"); + assert!(files.read(&outside.join("secret.pdf")).is_err(), "a read outside the folders is refused"); + assert!(!files.exists(&outside.join("secret.pdf")), "nor is it there for the request"); + assert!(files.write(&inside.join("out.pdf"), b"pdf", WriteIntent::SaveAs).is_ok()); + assert!(files.write(&outside.join("out.pdf"), b"pdf", WriteIntent::Save).is_err(), "a save outside is refused"); + assert!(files.answer_next(Picked::Paths(vec![outside.join("secret.pdf")])).is_err(), "so is a pick answer"); + }); + assert!(!outside.join("out.pdf").exists()); + // The person at the keyboard: nothing in force. + assert_eq!(files.read(&outside.join("secret.pdf")).unwrap(), b"secret"); + assert!(files.write(&outside.join("mine.pdf"), b"pdf", WriteIntent::SaveAs).is_ok()); + let _ = std::fs::remove_dir_all(base); + } +} diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 651a92f9e0..ec1c97500c 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -1,8 +1,10 @@ //! The UI control channel: lets an agent see and drive the running app. //! -//! **Opt-in only.** Nothing here runs unless the app is started with `--control ` (or a -//! test attaches a [`ControlChannel`]). The transport is the framework's `server::listen`: loopback -//! only, a random port, and every connection must first present the random token written to ``. +//! **Opt-in only.** Nothing here runs unless the app is started with `--control `, the +//! ArtCraft Launcher's AI agents switch lets agents into the window ([`crate::agents`], whose +//! requests run held to the agent folders), or a test attaches a [`ControlChannel`]. The transport +//! is the framework's `server::listen`: loopback only, and every connection must first prove it +//! holds the token. //! //! The channel, the injected-input queue, the screenshot queue and the access tree belong to the //! framework (`craft::automation`). This module is the app's method table over it: the framework's @@ -74,6 +76,8 @@ impl PdfCraftApp { /// Answers the control requests of this frame and finishes the screenshots that are due. Runs in the /// logic phase; the runtime and fonts are installed at creation (L-227), so every frame can answer. pub(crate) fn control_logic(&mut self, ctx: &egui::Context) { + #[cfg(not(target_arch = "wasm32"))] + crate::agents::sync(self, ctx); let Some(mut channel) = self.control.take() else { return }; let host = WindowHost::of(ctx); let document = Some(self.capture_document()); @@ -81,8 +85,15 @@ impl PdfCraftApp { let finished = channel.captures.drain(motion::now(), document); channel.finish_captures(finished, &mut |_path, _png| Err("ui.screenshot writes no files; omit path".to_string())); channel.poll_input(&host); + // The agents link's requests run held to the agent folders; the launch options' as before. + let guard = self.agent_guard.clone(); while let Some(req) = channel.next_request() { - let reply = self.answer(ctx, &req); + let reply = crate::agent_scope::confine(guard.as_ref(), || self.answer(ctx, &req)); + if let Some(guard) = &guard + && matches!(reply, Reply::AfterInput) + { + self.hold_agent_input(guard.clone()); + } let settle = settle_ms(ctx.global_style().animation_time); channel.settle(req, reply, document, settle); } @@ -120,6 +131,14 @@ impl PdfCraftApp { /// The reply to one request: the framework's methods, then the app's. fn answer(&mut self, ctx: &egui::Context, req: &ControlRequest) -> Reply { let (method, params) = (req.method.as_str(), &req.params); + // An agent's request bound to the agent folders it was checked against (`crate::agents`). + #[cfg(not(target_arch = "wasm32"))] + if method == crate::agents::BOUND_CALL { + return match crate::agents::bound_request(self, params) { + Ok((method, params)) => self.answer(ctx, &ControlRequest::new(method, params).0), + Err(e) => Reply::from_result(Err(e)), + }; + } let host = WindowHost::of(ctx); if let Some(queued) = input_method(method, params, &host, ViewportId::ROOT, &|_, _| None) { return match queued { diff --git a/crates/ui-egui/src/control/host.rs b/crates/ui-egui/src/control/host.rs index 0dde19a2c9..44fa7a6a46 100644 --- a/crates/ui-egui/src/control/host.rs +++ b/crates/ui-egui/src/control/host.rs @@ -168,6 +168,7 @@ impl crate::PdfCraftApp { "progress": progress, "password_prompt": self.password_prompt.is_some(), "close_prompt": self.close_guard.is_some(), + "agents": self.agents_ui_state(), }) } diff --git a/crates/ui-egui/src/dialogs/preferences.rs b/crates/ui-egui/src/dialogs/preferences.rs index abb406e742..693a38e696 100644 --- a/crates/ui-egui/src/dialogs/preferences.rs +++ b/crates/ui-egui/src/dialogs/preferences.rs @@ -39,6 +39,66 @@ pub struct PreferencesSession { host: DialogHost, /// The colours the picker answered, waiting for `Prefs::nested` to write them into the draft. answers: Answers, + /// The AI Integrations page, where the window lets agents in. + #[cfg(not(target_arch = "wasm32"))] + agents: Option, +} + +/// Preferences › AI Integrations: the agent settings, saved apart from the preferences where +/// `pdfcraft-cli mcp` reads them ([`crate::agents`]), and the link's state the page shows. +#[cfg(not(target_arch = "wasm32"))] +struct AgentsPart { + /// The settings as the page edits them, under [`crate::agents::PAGE`]. + draft: craft::ui::patterns::preferences::SettingsDraft, + /// The settings last saved. + saved: craft::automation::agents::AgentSettings, + status: craft::automation::agents::AgentLinkStatus, + mcp_flag: bool, +} + +#[cfg(not(target_arch = "wasm32"))] +impl AgentsPart { + fn new((saved, status, mcp_flag): (craft::automation::agents::AgentSettings, craft::automation::agents::AgentLinkStatus, bool)) -> Self { + let mut part = Self { draft: Default::default(), saved, status, mcp_flag }; + part.reset(); + part + } + + /// The draft back to the settings last saved. + fn reset(&mut self) { + self.draft.set(crate::agents::PAGE, &self.saved); + } + + /// The settings the draft holds. + fn edited(&self) -> craft::automation::agents::AgentSettings { + self.draft.get(crate::agents::PAGE).unwrap_or_else(|| self.saved.clone()) + } + + /// Follows the settings and the link as the window has them now. + fn refresh(&mut self, app: &PdfCraftApp) { + let Some((saved, status, mcp_flag)) = app.agents_page_state() else { return }; + if saved != self.saved { + self.saved = saved; + self.reset(); + } + self.status = status; + self.mcp_flag = mcp_flag; + } + + /// The page: with the suite's `AI-MCP` flag, the framework's Agents page over the draft (the + /// ArtCraft Launcher's switch decides; the page has none of its own); without it, a line that + /// says so, as PdfCraft had no agent settings before the switch. Returns whether the draft changed. + fn show(&mut self, ui: &mut Ui) -> bool { + if !self.mcp_flag { + craft::ui::display::Text::new(tl!( + "Agents use PdfCraft without a window. The ArtCraft Launcher's Settings › AI agents switch lets them into the open window once the suite's AI-MCP flag is on." + )) + .shade(craft::ui::display::Shade::Muted) + .show(ui); + return false; + } + craft::automation::ui::agents::AgentsPage::new(crate::agents::PAGE, &mut self.draft, &self.status).mcp_flag(true).show(ui).changed + } } /// Colour answers by row key, filled by the picker's `then` and drained in the same window's pass. @@ -52,6 +112,8 @@ impl PreferencesSession { selection: SelectionChange::default(), host: DialogHost::new(), answers: Answers::default(), + #[cfg(not(target_arch = "wasm32"))] + agents: app.agents_page_state().map(AgentsPart::new), } } } @@ -223,10 +285,22 @@ impl PdfCraftApp { let Some(mut session) = self.preferences.take() else { return; }; + #[cfg(not(target_arch = "wasm32"))] + if let Some(agents) = session.agents.as_mut() { + agents.refresh(self); + } + #[cfg(not(target_arch = "wasm32"))] + let PreferencesSession { state, draft, selection, host, answers, agents } = &mut session; + #[cfg(target_arch = "wasm32")] let PreferencesSession { state, draft, selection, host, answers } = &mut session; let ctx = ui.ctx().clone(); let output = { + #[cfg_attr(target_arch = "wasm32", allow(unused_mut))] let mut prefs = Prefs::new(self, draft, selection, host, answers, &ctx); + #[cfg(not(target_arch = "wasm32"))] + { + prefs.agents = agents.as_mut(); + } PreferencesWindow::new(Bind::bound(state)) .mode(PreferencesMode::Live) .layout(PreferencesLayout::Cards) @@ -313,6 +387,9 @@ struct Prefs<'a> { answers: &'a Answers, ctx: &'a egui::Context, texts: Texts, + /// The AI Integrations page, when the window lets agents in. + #[cfg(not(target_arch = "wasm32"))] + agents: Option<&'a mut AgentsPart>, } impl<'a> Prefs<'a> { @@ -325,7 +402,17 @@ impl<'a> Prefs<'a> { ctx: &'a egui::Context, ) -> Self { let texts = Texts::new(app, draft, ctx); - Self { app, draft, selection, host, answers, ctx, texts } + Self { + app, + draft, + selection, + host, + answers, + ctx, + texts, + #[cfg(not(target_arch = "wasm32"))] + agents: None, + } } } @@ -427,7 +514,21 @@ fn date_language_picker_name(ctx: &egui::Context, l: &pdfcraft_engine::dates::Da impl PreferencesModel for Prefs<'_> { fn pages(&self) -> Vec> { - vec![self.general_page(), self.appearance_page(), self.documents_page(), self.comment_page(), self.fill_sign_page(), self.javascript_page()] + #[cfg_attr(target_arch = "wasm32", allow(unused_mut))] + let mut pages = vec![ + self.general_page(), + self.appearance_page(), + self.documents_page(), + self.comment_page(), + self.fill_sign_page(), + self.javascript_page(), + ]; + #[cfg(not(target_arch = "wasm32"))] + if self.agents.is_some() { + let keywords = "agents AI MCP ArtCraft Launcher control port folders"; + pages.push(PageSpec::custom(crate::agents::PAGE, tl!(crate::agents::PAGE_TITLE)).keywords(keywords)); + } + pages } fn set(&mut self, key: &str, value: PrefValue) { @@ -539,6 +640,12 @@ impl PreferencesModel for Prefs<'_> { } fn custom_page(&mut self, ui: &mut Ui, page: &str) -> bool { + #[cfg(not(target_arch = "wasm32"))] + if page == crate::agents::PAGE + && let Some(agents) = self.agents.as_deref_mut() + { + return agents.show(ui); + } if page != "appearance" { return false; } @@ -557,6 +664,13 @@ impl PreferencesModel for Prefs<'_> { } fn reset_page(&mut self, page: &str) { + #[cfg(not(target_arch = "wasm32"))] + if page == crate::agents::PAGE + && let Some(agents) = self.agents.as_deref_mut() + { + agents.draft.set(crate::agents::PAGE, &craft::automation::agents::AgentSettings::default()); + return; + } let fresh = PrefsDraft::defaults(); let d = &mut *self.draft; match page { @@ -628,6 +742,10 @@ impl PreferencesDraft for Prefs<'_> { let mut saved = PrefsDraft::from_app(self.app); // Opening the custom colour controls is a UI choice, even if no colour has changed. saved.custom_reading_colors = self.draft.custom_reading_colors; + #[cfg(not(target_arch = "wasm32"))] + if self.agents.as_deref().is_some_and(|agents| agents.edited() != agents.saved) { + return true; + } *self.draft != saved || *self.selection != SelectionChange::default() } @@ -636,6 +754,19 @@ impl PreferencesDraft for Prefs<'_> { } fn apply(&mut self) -> Result<(), String> { + // The agent settings first: an agent's input clicking through this page is refused, and + // the page goes back to what is saved. + #[cfg(not(target_arch = "wasm32"))] + if let Some(agents) = self.agents.as_deref_mut() { + let edited = agents.edited(); + if edited != agents.saved { + if let Err(refused) = self.app.set_agent_settings(edited.clone()) { + agents.reset(); + return Err(refused); + } + agents.saved = edited; + } + } let d = self.draft.clone(); self.app.date_text(Some(&d.date_format))?; let old_defaults = self.app.view_defaults; @@ -706,6 +837,10 @@ impl PreferencesDraft for Prefs<'_> { } fn cancel(&mut self) { + #[cfg(not(target_arch = "wasm32"))] + if let Some(agents) = self.agents.as_deref_mut() { + agents.reset(); + } i18n::set_current(Lang::from_pref(&self.app.language)); *self.selection = SelectionChange::default(); } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 57acccdba7..b4ac124d3e 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -88,9 +88,15 @@ pub use recovery::AUTOSAVE_SECS; pub use workflows::js_dialogs::JsDialog; pub use workflows::ocr_verify::{OcrVerify, Phase}; +pub mod agent_scope; +#[cfg(not(target_arch = "wasm32"))] +mod agent_settings; +#[cfg(not(target_arch = "wasm32"))] +pub mod agents; mod app; pub(crate) mod brand; pub(crate) mod colour_picker; +pub mod confined_files; pub(crate) mod credits_data; pub mod fonts; mod frame_guard; @@ -727,6 +733,17 @@ pub struct PdfCraftApp { /// Changes whenever what injected input aims at changes, so the control channel withdraws /// input aimed at what was there before. pub(crate) control_epoch: u64, + /// Agents in the open window, while the ArtCraft Launcher's switch may let them in. + #[cfg(not(target_arch = "wasm32"))] + agents: Option>, + /// The agent folders the agents link's requests run with (`None`: the control channel is the + /// launch options' and runs unconfined, as before). + agent_guard: Option, + /// The agent folders `agent_guard` holds requests to (`agents.call` checks them). + #[cfg(not(target_arch = "wasm32"))] + agent_folders: Option, + /// The agent folders an agent's request leaves in force while the input it queued is handled. + agent_input: Option, /// Bookmarks copied or cut in the Bookmarks panel, with their subtrees, ready to paste into /// any document. Destinations are page indices. pub bookmark_clipboard: Option>, diff --git a/crates/ui-egui/tests/it/agents.rs b/crates/ui-egui/tests/it/agents.rs new file mode 100644 index 0000000000..5224dcc8cd --- /dev/null +++ b/crates/ui-egui/tests/it/agents.rs @@ -0,0 +1,167 @@ +//! Agents in the open window: the ArtCraft Launcher's switch starts and stops the window's control +//! server for agents, and an agent's requests reach only the agent folders. + +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::mpsc; +use std::time::Duration; + +use craft::automation::agents::{AgentSettings, AgentSwitch, TOKEN_FILE, probe, read_connection}; +use craft::automation::client::ControlClient; +use craft::host::{Host, ScriptedFiles}; +use egui_kittest::Harness; +use pdfcraft_ui_egui::PdfCraftApp; +use pdfcraft_ui_egui::agent_scope::Guard; +use pdfcraft_ui_egui::agents::{Agents, GuardFn}; +use pdfcraft_ui_egui::confined_files::ConfinedFiles; +use serde_json::{Value, json}; + +fn temp(tag: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("pdfcraft-agents-it-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir +} + +/// Paths below the folders `guard_for` is given are allowed; a stand-in for the automation roots +/// the desktop app passes. +fn prefix_guards() -> GuardFn { + Box::new(|folders| { + let (read, write) = (folders.read.clone(), folders.write.clone()); + let guard: Guard = Arc::new(move |path: &Path, use_| { + let folder = match use_ { + pdfcraft_ui_egui::agent_scope::FileUse::Read => read.as_ref(), + pdfcraft_ui_egui::agent_scope::FileUse::Write => write.as_ref(), + }; + match folder { + Some(folder) if path.starts_with(folder) => Ok(()), + _ => Err(format!("outside the agent folders: {}", path.display())), + } + }); + Ok(guard) + }) +} + +/// A window whose agents link follows `switch`, with its settings in `dir` and `folder` as the +/// agent folder. +fn window(dir: &Path, folder: &Path, switch: Arc) -> Harness<'static, PdfCraftApp> { + let (dir, folder) = (dir.to_path_buf(), folder.to_path_buf()); + Harness::builder().with_size(egui::vec2(1000.0, 700.0)).build_eframe(move |cc| { + crate::support::install_runtime(&cc.egui_ctx); + let files = Arc::new(ConfinedFiles::new(Arc::new(ScriptedFiles::default()))); + let host = Host::builder(crate::control::info()).files(files).build(); + let mut app = PdfCraftApp::with_host(Arc::new(host), crate::control::services()); + let watched = switch.clone(); + let switch = AgentSwitch::watch_with(true, move || watched.load(Ordering::SeqCst), Duration::from_millis(10), || {}); + let mut settings = AgentSettings::default(); + settings.read_root = folder.to_string_lossy().into_owned(); + settings.write_root = folder.to_string_lossy().into_owned(); + let save = Box::new(|_: &AgentSettings| Ok(())); + app.with_agents(Agents::new(dir, "PdfCraft test".into(), switch, settings, save, prefix_guards())); + app + }) +} + +/// Runs frames until `ready` holds (at most 30 s). +fn frames_until(h: &mut Harness<'static, PdfCraftApp>, mut ready: impl FnMut() -> bool) -> bool { + crate::support::step_until(h, |_| ready()) +} + +/// One request from an agent's client on another thread, answered while the window runs frames. +fn agent_call( + h: &mut Harness<'static, PdfCraftApp>, + client: &Arc>, + method: &str, + params: Value, +) -> Result { + let (tx, rx) = mpsc::channel(); + let (client, method) = (client.clone(), method.to_owned()); + std::thread::spawn(move || { + let _ = tx.send(client.lock().unwrap().call(&method, params)); + }); + let mut reply = None; + assert!(frames_until(h, || { + reply = rx.try_recv().ok(); + reply.is_some() + })); + reply.unwrap() +} + +/// The agent's client for the window `dir` publishes. +fn connect(dir: &Path) -> Arc> { + let connection = read_connection(dir).unwrap().expect("the window published its connection"); + let token = std::fs::read_to_string(dir.join(TOKEN_FILE)).unwrap(); + let addr = std::net::SocketAddr::from(([127, 0, 0, 1], connection.port)); + Arc::new(std::sync::Mutex::new(ControlClient::connect(addr, token.trim()).unwrap())) +} + +// The launcher's switch on: the window listens and publishes where; off: it stops and the +// connection file goes, so `pdfcraft-cli mcp` finds no window. +#[test] +fn the_switch_starts_and_stops_the_window_for_agents() { + let base = temp("switch"); + let (dir, folder) = (base.join("settings"), base.join("agents")); + std::fs::create_dir_all(&folder).unwrap(); + let switch = Arc::new(AtomicBool::new(false)); + let mut h = window(&dir, &folder, switch.clone()); + h.run_steps(3); + assert!(read_connection(&dir).unwrap().is_none(), "nothing is published while the switch is off"); + + switch.store(true, Ordering::SeqCst); + assert!(frames_until(&mut h, || read_connection(&dir).ok().flatten().is_some()), "the window publishes once the switch is on"); + let client = connect(&dir); + let state = agent_call(&mut h, &client, "ui.state", json!({})).unwrap(); + assert_eq!(state["agents"]["allowed"], true); + let port = read_connection(&dir).unwrap().unwrap().port; + + switch.store(false, Ordering::SeqCst); + assert!(frames_until(&mut h, || read_connection(&dir).ok().flatten().is_none()), "the connection file goes when the switch turns off"); + assert!(!probe(port, Duration::from_millis(300)), "and nothing listens on its port"); + let _ = std::fs::remove_dir_all(base); +} + +// An agent opens files only from the agent folder, and can't answer a file pick with a path +// outside it. +#[test] +fn agent_requests_stay_in_the_agent_folders() { + let base = temp("folders"); + let (dir, folder, outside) = (base.join("settings"), base.join("agents"), base.join("elsewhere")); + std::fs::create_dir_all(&folder).unwrap(); + std::fs::create_dir_all(&outside).unwrap(); + std::fs::write(outside.join("secret.pdf"), b"%PDF-1.4\n%%EOF\n").unwrap(); + let mut h = window(&dir, &folder, Arc::new(AtomicBool::new(true))); + assert!(frames_until(&mut h, || read_connection(&dir).ok().flatten().is_some())); + let client = connect(&dir); + + let secret = outside.join("secret.pdf").to_string_lossy().into_owned(); + let refused = agent_call(&mut h, &client, "ui.open", json!({"path": secret})).unwrap_err(); + assert!(refused.contains("outside the agent folders"), "{refused}"); + assert!(h.state().views.is_empty(), "nothing opened"); + let refused = agent_call(&mut h, &client, "ui.pick", json!({"files": [secret]})).unwrap_err(); + assert!(refused.contains("outside the agent folders"), "{refused}"); + let _ = std::fs::remove_dir_all(base); +} + +// A request bound to the agent folders it was checked against runs only while they are still the +// window's folders, so a Preferences change while it is on its way can't widen it. +#[test] +fn a_bound_request_runs_only_under_the_folders_it_was_checked_against() { + let base = temp("bound"); + let (dir, folder, other) = (base.join("settings"), base.join("agents"), base.join("other")); + std::fs::create_dir_all(&folder).unwrap(); + std::fs::create_dir_all(&other).unwrap(); + let mut h = window(&dir, &folder, Arc::new(AtomicBool::new(true))); + assert!(frames_until(&mut h, || read_connection(&dir).ok().flatten().is_some())); + let client = connect(&dir); + let bound = |folders: &Path| { + let path = folders.to_string_lossy().into_owned(); + json!({"method": "ui.state", "params": {}, "folders": {"read": path, "write": path}}) + }; + + let state = agent_call(&mut h, &client, "agents.call", bound(&folder)).unwrap(); + assert_eq!(state["agents"]["allowed"], true, "the checked folders hold: it ran"); + let refused = agent_call(&mut h, &client, "agents.call", bound(&other)).unwrap_err(); + assert!(refused.contains("changed"), "{refused}"); + let _ = std::fs::remove_dir_all(base); +} diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index 8c9088afb6..431401f842 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -19,6 +19,7 @@ fn gpu() -> std::sync::MutexGuard<'static, ()> { mod accessibility; mod actions; +mod agents; mod animate; mod attach_picker_target; mod attachment_row; diff --git a/docs/mcp.md b/docs/mcp.md index 8aa30ec6e8..4dbc97ec2f 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1,8 +1,10 @@ # MCP conventions -Start explicitly with `pdfcraft-cli mcp [--root DIR] [--compact] [--automation-read-root DIR] [--automation-write-root DIR]`. The server uses JSON lines on +Start explicitly with `pdfcraft-cli mcp [--root DIR] [--compact] [--automation-read-root DIR] [--automation-write-root DIR] [--headless] [--when-closed launch|headless|error]`. The server uses JSON lines on stdin/stdout, opens no port, and stops on EOF. `--root` confines all reads and writes, including -commands invoked through the common tools. Logs stay on stderr. +commands invoked through the common tools. Logs stay on stderr. With the ArtCraft Launcher's AI +agents switch, the same command also reaches the open PdfCraft window +([Agents in the open window](#agents-in-the-open-window)). Supply `--root` at most once, followed by a nonempty directory path. Missing operands, repeated roots and another long option in place of the directory are refused before any @@ -103,8 +105,10 @@ config works across the suite) keep the agent to the folders you give it: - `--root DIR` still works and can be combined with these flags. Both then apply: a path must be inside `--root` and inside the matching automation root. -`pdfcraft-cli mcp` always runs the session in its own process (there is no flag to connect it to a -running app), so the roots cover every server it starts. The desktop app is not confined by them. +The document tools always run in `pdfcraft-cli mcp`'s own session, so the roots cover every +document an agent opens with them. In the open window an agent's requests are held to the agent +folders instead ([Agents in the open window](#agents-in-the-open-window)); the person's own work +in the window is not confined. What the roots do not cover: tools that take no path still read and change the open documents, and `text_extract` and the other inspection tools return their content. Keychain and Windows @@ -117,6 +121,57 @@ A path is checked, then opened: another program that swaps a link in between can race, so the roots keep an agent to the files it was given rather than guarding against other software on the computer. +## Agents in the open window + +The ArtCraft Launcher's *Settings › AI agents* switch (*Let AI agents use Craft apps*) lets agents +into every Craft app; the launcher writes the one `ArtCraft` entry MCP clients use, and PdfCraft +writes no client configuration of its own. The switch counts while the suite's `AI-MCP` flag is on +(`ArtCraft/flags.toml` or `CRAFT_FLAGS`). + +- **The window.** While the switch names PdfCraft, the window serves its control channel to agents + on `127.0.0.1` and publishes where in its settings folder: `agent-connection.json` (port, process + id, the token file's path) and the token file `agent-control.token` (made once, owner-only on + Unix). The port is the *Control Port* setting (0: any free port); a port that is taken is tried + again every 5 seconds. Turning the switch off stops the server and removes the file. A run with + `--control` keeps its own channel instead, and a nightly lets no agents in. +- **Preferences › AI Integrations** shows whether agents can connect and on which port, and holds + the agent folders and the closed-app choice. It has no switch of its own: the launcher's decides. + Without the `AI-MCP` flag the page says so. +- **The agent folders.** Agents open files from the *read folder* and save to the *write folder*; + an empty setting is `Documents/ArtCraft/Agents/PdfCraft`, made when first used. Every file an + agent's request opens or saves in the window, and every file pick it answers, must lie there: + `ui.open`, the files a click or key it sent opens, Save and Save As, exports. Outside it the + request gets the refusal (`automation path rejected: outside the read root …`). Agents can't + change these settings, not even by clicking through Preferences. +- **Plain `pdfcraft-cli mcp`** reads the connection file on every call, so the client's + configuration holds no port and no token, and the app may start, quit or change port while the + client stays connected. It checks that the published process is still running and makes the + window prove it holds the token before it sends anything derived from it (the challenge + handshake); a file a crashed run left is ignored and removed on the next start. + - `ui_state`, `ui_inspect`, `ui_screenshot`, `ui_open`, `ui_command` and `control_call` (any + `ui.*` method, such as `ui.click`, `ui.key`, `ui.pick` or `ui.quit`) drive the open window. + - The document tools don't reach the window's tabs yet: while the window is open they run in the + command's own session, held to the agent folders, and `ui_open` shows a saved result in the + window. + - That session lasts as long as the command, as it always did: its open documents, unsaved + edits and undo history stay when the app opens or quits and when the person changes the agent + folders. Only the folders it may open from and save to follow: every later open or save is + checked against the folders in force then. + - `agent_folders` tells the agent which folders it may use (`read_folder`, `write_folder`, and + `confined`). + - With the app closed, the closed-app choice decides (`--when-closed` overrides it): **launch** + starts PdfCraft and waits for it, **headless** works without a window in the agent folders, and + **error** says to open PdfCraft. + - The command's own `--automation-read-root` and `--automation-write-root` replace the agent + folders as a pair, as given: a root left out grants none of its access, rather than falling + back to Preferences. The window holds every agent request to its own agent folders (a Save + writes the document's own path), so with folders of its own that differ from those, the + command's window tools are off and say so; the document tools still work. With the same + folders, each window request carries them (`agents.call`), and the window runs it only if + they are still its agent folders when it gets there. + - While the switch doesn't name PdfCraft, `mcp` works as before: no window, and only the folders + the command was given. `--headless` always works that way. + ## Tools | Tool | Arguments |