mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-25 20:22:39 +00:00
Merge pull request #2391 from davidmann4/agents-reexport-next
craft-automation: re-export the agents code from craft-control (#2390)
This commit is contained in:
Generated
+1
-3
@@ -2047,10 +2047,8 @@ name = "craft-automation"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"craft-ai-agents",
|
||||
"craft-atomic",
|
||||
"craft-behavior",
|
||||
"craft-flags",
|
||||
"craft-control",
|
||||
"craft-host",
|
||||
"craft-keymap",
|
||||
"craft-platform",
|
||||
|
||||
@@ -25,12 +25,15 @@ ui = ["dep:craft-behavior", "dep:craft-keymap", "dep:craft-ui", "dep:egui"]
|
||||
# The Actions panel's and the Agents page's stories and mock, and the integration binary `tests/it`.
|
||||
screen-testing = ["ui", "agents", "craft-ui/testing"]
|
||||
# Agents in the open window (desktop): the ArtCraft Launcher's switch, the connection file an
|
||||
# app's `<id>-cli mcp` reads, and with `ui` the link host and the Agents page. The agent settings
|
||||
# build on every target without it.
|
||||
agents = ["dep:craft-ai-agents", "dep:craft-flags", "dep:craft-atomic", "dep:craft-host"]
|
||||
# app's `<id>-cli mcp` reads and that CLI's live client (all `craft-control`'s, re-exported), and
|
||||
# with `ui` the link host and the Agents page. The agent settings build on every target without it.
|
||||
agents = ["craft-control/agents", "dep:craft-host"]
|
||||
|
||||
[dependencies]
|
||||
craft-behavior = { workspace = true, optional = true }
|
||||
# The agents code without a UI toolkit (settings, the launcher's switch, the connection file, the
|
||||
# CLI's live client), re-exported by `agents` so every app shares one copy.
|
||||
craft-control = { workspace = true }
|
||||
craft-keymap = { workspace = true, optional = true }
|
||||
craft-theme = { workspace = true }
|
||||
craft-ui = { workspace = true, optional = true }
|
||||
@@ -42,9 +45,6 @@ serde_json = { workspace = true }
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
|
||||
base64 = "0.22"
|
||||
craft-platform = { workspace = true }
|
||||
craft-ai-agents = { workspace = true, optional = true }
|
||||
craft-atomic = { workspace = true, optional = true }
|
||||
craft-flags = { workspace = true, optional = true }
|
||||
craft-host = { workspace = true, optional = true }
|
||||
getrandom = "0.3"
|
||||
hmac = "0.12"
|
||||
|
||||
@@ -8,7 +8,7 @@ Features: `ui` (the egui parts), `agents` (agents in the open window: the launch
|
||||
| --- | --- |
|
||||
| `actions` | Recorded actions (every target): `ActionList` of `Action`s and `ActionStep`s, `ActionsFile`, playback with `ActionPlayer` and `ActionRunner` under a `PlaybackBudget`, and `Recording`. The app keeps the command table. |
|
||||
| `ui::actions` | `ActionsPanel` (every target): sets, actions and steps as a tree, include and dialog cells, rename (`start_rename`), drag to move, Button Mode, the footer and the menus (`ActionsPanelCommands`, `ActionsMenuFacts` and `panel_rows`, which leaves out the rows the host has no command for). It runs nothing; it reports `ActionsEvent`s. `ActionsPanelState` holds its view state. `ActionsWords` holds its words. |
|
||||
| `agents` | AI agents in the open window. Every target: `AgentSettings` (Control Port, the folders agents may open from and save to, `WhenAppClosed`, Allow Agent Control) and `agents_allowed`. Desktop, feature `agents`: `AgentSwitch`, the ArtCraft Launcher's switch for the app behind the suite's `AI-MCP` flag, watched on a thread; the connection file (`Connection`, `write_connection`, `read_connection`, `remove_stale_connection`, `probe`) that the app's `<id>-cli mcp` finds the open window by. With `ui`: `AgentLink`, the link host that starts, moves, stops and retries the agents' control server to match the settings and publishes the connection file. |
|
||||
| `agents` | AI agents in the open window. Every target: `AgentSettings` (Control Port, the folders agents may open from and save to, `WhenAppClosed`, Allow Agent Control) and `agents_allowed`. Desktop, feature `agents`: `AgentSwitch`, the ArtCraft Launcher's switch for the app behind the suite's `AI-MCP` flag, watched on a thread; the connection file (`Connection`, `write_connection`, `read_connection`, `remove_stale_connection`, `probe`) that the app's `<id>-cli mcp` finds the open window by; the CLI's live client (`Live`, `LiveConfig`, `Route`). All of these are `craft_control::agents`, re-exported, so apps without the shared UI library use the same code. With `ui`: `AgentLink`, the link host that starts, moves, stops and retries the agents' control server to match the settings and publishes the connection file. |
|
||||
| `ui::agents` | `AgentsPage` (desktop, features `agents` and `ui`): the Agents page of Preferences, a custom page over the agent settings in the Preferences draft, with the link's status; the folder rows are `PathSetting`s. `AgentsWords` holds its words. |
|
||||
| `args` | `ControlOptions`: the `--control <PORT>`, `--control-token`, `--control-token-file` values and their `<APP>_CONTROL_*` environment fallbacks, checked the way the apps' command lines report them (usage errors exit 2). |
|
||||
| `security` | Tokens (`generate_token`, `validate_token`, `server_token`, `client_token`), the authentication handshake (`ServerHandshake`: the challenge handshake, which never sends the token, or the one-frame `auth {token}`), bounded line reads, connection and request limits. |
|
||||
|
||||
@@ -1,117 +0,0 @@
|
||||
//! The connection file: where an app's control server listens for agents.
|
||||
|
||||
use std::net::{SocketAddr, TcpStream};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::Duration;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::AutomationError;
|
||||
|
||||
/// The connection file in the app's settings folder, present while the app accepts agents.
|
||||
pub const CONNECTION_FILE: &str = "agent-connection.json";
|
||||
/// The token file the app keeps in its settings folder for agent connections.
|
||||
pub const TOKEN_FILE: &str = "agent-control.token";
|
||||
/// How long [`probe`] waits for a connection to be accepted.
|
||||
pub const PROBE_TIMEOUT: Duration = Duration::from_millis(500);
|
||||
/// The version of the [`Connection`] file format.
|
||||
const CONNECTION_VERSION: u32 = 1;
|
||||
/// The largest connection file read; anything bigger is not one.
|
||||
const MAX_CONNECTION_BYTES: u64 = 1 << 20;
|
||||
|
||||
/// What an app publishes in [`CONNECTION_FILE`]: `{"version", "pid", "port", "tokenFile", "app"}`.
|
||||
/// Holds no secret: the token stays in its own owner-only file.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Connection {
|
||||
/// The file format's version (1).
|
||||
pub version: u32,
|
||||
/// The app's process id: only that process removes the file.
|
||||
pub pid: u32,
|
||||
/// The loopback port of the control server.
|
||||
pub port: u16,
|
||||
/// The file holding the token.
|
||||
pub token_file: PathBuf,
|
||||
/// The app's version, for diagnostics.
|
||||
pub app: String,
|
||||
}
|
||||
|
||||
impl Connection {
|
||||
/// This process's connection on `port`, naming `app` (the app's version string).
|
||||
pub fn new(port: u16, token_file: PathBuf, app: impl Into<String>) -> Self {
|
||||
Self { version: CONNECTION_VERSION, pid: std::process::id(), port, token_file, app: app.into() }
|
||||
}
|
||||
|
||||
/// `127.0.0.1:<port>`.
|
||||
pub fn addr(&self) -> String {
|
||||
format!("127.0.0.1:{}", self.port)
|
||||
}
|
||||
}
|
||||
|
||||
fn io_error(path: &Path, e: impl std::fmt::Display) -> AutomationError {
|
||||
AutomationError::Io(format!("{}: {e}", path.display()))
|
||||
}
|
||||
|
||||
/// Publishes `c` in `dir` (made if missing), written atomically so a reader never sees half a
|
||||
/// file.
|
||||
pub fn write_connection(dir: &Path, c: &Connection) -> Result<(), AutomationError> {
|
||||
std::fs::create_dir_all(dir).map_err(|e| io_error(dir, e))?;
|
||||
let path = dir.join(CONNECTION_FILE);
|
||||
let text = serde_json::to_string_pretty(c).map_err(|e| io_error(&path, e))?;
|
||||
craft_atomic::atomic_write(&path, text.as_bytes()).map_err(|e| io_error(&path, e))
|
||||
}
|
||||
|
||||
/// The connection published in `dir`, if any. A file of another version, with port 0, or one
|
||||
/// that does not parse (invalid UTF-8 included) counts as none: the app rewrites it when it next
|
||||
/// starts listening. Anything but a regular file (a FIFO would block the read) or a file over
|
||||
/// 1 MiB is an error, and left alone.
|
||||
pub fn read_connection(dir: &Path) -> Result<Option<Connection>, AutomationError> {
|
||||
let path = dir.join(CONNECTION_FILE);
|
||||
let meta = match std::fs::metadata(&path) {
|
||||
Ok(m) => m,
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
|
||||
Err(e) => return Err(io_error(&path, e)),
|
||||
};
|
||||
if !meta.is_file() {
|
||||
return Err(io_error(&path, "not a regular file"));
|
||||
}
|
||||
if meta.len() > MAX_CONNECTION_BYTES {
|
||||
return Err(io_error(&path, format!("larger than {MAX_CONNECTION_BYTES} bytes")));
|
||||
}
|
||||
let bytes = match std::fs::read(&path) {
|
||||
Ok(b) => b,
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
|
||||
Err(e) => return Err(io_error(&path, e)),
|
||||
};
|
||||
Ok(serde_json::from_slice::<Connection>(&bytes).ok().filter(|c| c.version == CONNECTION_VERSION && c.port != 0))
|
||||
}
|
||||
|
||||
/// Removes the connection file in `dir` if process `pid` wrote it (another instance may have
|
||||
/// published its own since). Errors are ignored: a stale file only fails [`probe`].
|
||||
pub fn remove_connection(dir: &Path, pid: u32) {
|
||||
if let Ok(Some(c)) = read_connection(dir)
|
||||
&& c.pid == pid
|
||||
{
|
||||
let _ = std::fs::remove_file(dir.join(CONNECTION_FILE));
|
||||
}
|
||||
}
|
||||
|
||||
/// Removes the connection file in `dir` when nothing listens on its port any more (an app that
|
||||
/// crashed or quit without removing it), or when it does not read as a connection. A live
|
||||
/// instance's file is kept, and so is anything but a regular file. Errors are ignored.
|
||||
pub fn remove_stale_connection(dir: &Path) {
|
||||
let path = dir.join(CONNECTION_FILE);
|
||||
let stale = match read_connection(dir) {
|
||||
Ok(Some(c)) => !probe(c.port, PROBE_TIMEOUT),
|
||||
Ok(None) => path.is_file(),
|
||||
Err(_) => false,
|
||||
};
|
||||
if stale {
|
||||
let _ = std::fs::remove_file(path);
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether something accepts connections on loopback `port` within `timeout`; port 0 never does.
|
||||
pub fn probe(port: u16, timeout: Duration) -> bool {
|
||||
port != 0 && TcpStream::connect_timeout(&SocketAddr::from(([127, 0, 0, 1], port)), timeout).is_ok()
|
||||
}
|
||||
@@ -9,8 +9,8 @@
|
||||
//! While agents may connect, the app serves its control channel on loopback ([`AgentLink`], over
|
||||
//! [`crate::server`]) and publishes where in its settings folder ([`CONNECTION_FILE`]): the port,
|
||||
//! its process id and the token file ([`TOKEN_FILE`], created `0600` on Unix). The app's
|
||||
//! `<id>-cli mcp` reads that file on every tool call, then the token from the file it names, so an
|
||||
//! MCP client's configuration never holds a port or a token.
|
||||
//! `<id>-cli mcp` reads that file on every tool call ([`Live`]), then the token from the file it
|
||||
//! names, so an MCP client's configuration never holds a port or a token.
|
||||
//!
|
||||
//! The file holds no secret. A crashed (or, on macOS, quit) app can leave it behind; nothing then
|
||||
//! listens on its port ([`probe`]), and the app's next launch removes it
|
||||
@@ -18,29 +18,32 @@
|
||||
//! checks that [`Connection::pid`] is still running before it sends anything derived from the
|
||||
//! token, and authenticates with the challenge handshake ([`crate::security::ServerHandshake`]).
|
||||
//!
|
||||
//! Everything but the link host is `craft_control::agents`, re-exported here: apps that don't use
|
||||
//! the shared UI library use it from there, with the same files and formats.
|
||||
//!
|
||||
//! | Part | Names | Builds |
|
||||
//! |---|---|---|
|
||||
//! | Settings | [`AgentSettings`], [`WhenAppClosed`], [`agents_allowed`], [`folder`] | every target |
|
||||
//! | The launcher's switch | [`AgentSwitch`], [`mcp_flag`], [`launcher_allows`], [`POLL`] | desktop, feature `agents` |
|
||||
//! | The connection file | [`Connection`], [`write_connection`], [`read_connection`], [`remove_connection`], [`remove_stale_connection`], [`probe`] | desktop, feature `agents` |
|
||||
//! | The CLI's side | [`Live`], [`LiveConfig`], [`Route`], [`Window`], [`Consent`], [`HeadlessFolders`], [`find_window`], [`launcher`] | desktop, feature `agents` |
|
||||
//! | The link host | [`AgentLink`], [`AgentLinkStatus`], [`LinkProblem`], [`LinkUpdate`] | desktop, features `agents` and `ui` |
|
||||
//!
|
||||
//! The Agents page of Preferences is [`crate::ui::agents`].
|
||||
|
||||
mod settings;
|
||||
pub use settings::{AgentSettings, WhenAppClosed, agents_allowed, folder};
|
||||
// The links above name items of the `agents` and `ui` features; without them they have nothing to
|
||||
// point at, and the docs of the settings alone still build.
|
||||
#![cfg_attr(not(all(feature = "agents", feature = "ui", not(target_arch = "wasm32"))), allow(rustdoc::broken_intra_doc_links))]
|
||||
|
||||
pub use craft_control::agents::{AgentSettings, WhenAppClosed, agents_allowed, folder};
|
||||
|
||||
#[cfg(all(feature = "agents", not(target_arch = "wasm32")))]
|
||||
mod connection;
|
||||
#[cfg(all(feature = "agents", feature = "ui", not(target_arch = "wasm32")))]
|
||||
mod link;
|
||||
#[cfg(all(feature = "agents", not(target_arch = "wasm32")))]
|
||||
mod switch;
|
||||
#[cfg(all(feature = "agents", not(target_arch = "wasm32")))]
|
||||
pub use connection::{
|
||||
CONNECTION_FILE, Connection, PROBE_TIMEOUT, TOKEN_FILE, probe, read_connection, remove_connection, remove_stale_connection, write_connection,
|
||||
pub use craft_control::agents::{
|
||||
AgentSwitch, CONNECTION_FILE, ConnectFn, Connection, Consent, ConsentFn, HeadlessFn, HeadlessFolders, LAUNCH_POLL, LAUNCH_TIMEOUT, LaunchFn,
|
||||
Live, LiveConfig, POLL, PROBE_TIMEOUT, Route, TOKEN_FILE, Window, find_window, launcher, launcher_allows, mcp_flag, probe, read_connection,
|
||||
remove_connection, remove_stale_connection, write_connection,
|
||||
};
|
||||
#[cfg(all(feature = "agents", feature = "ui", not(target_arch = "wasm32")))]
|
||||
pub use link::{AgentLink, AgentLinkStatus, LinkProblem, LinkUpdate, RETRY};
|
||||
#[cfg(all(feature = "agents", not(target_arch = "wasm32")))]
|
||||
pub use switch::{AgentSwitch, POLL, launcher_allows, mcp_flag};
|
||||
|
||||
@@ -1,124 +0,0 @@
|
||||
//! The agent settings an app saves in its preferences, and who decides that agents may connect.
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// The agent settings of an app's Preferences (its `integrations` section in PhotoCraft). Saved in
|
||||
/// camelCase: `allowAgentControl`, `controlPort`, `readRoot`, `writeRoot`, `whenAppClosed`.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
#[non_exhaustive]
|
||||
pub struct AgentSettings {
|
||||
/// Off refuses every control server, `--control` included.
|
||||
pub allow_agent_control: bool,
|
||||
/// The loopback port agents connect to; 0 is any free port, published in the connection file.
|
||||
pub control_port: u32,
|
||||
/// The folder agents may open from; empty is none. Applied at once while agents are connected.
|
||||
pub read_root: String,
|
||||
/// The folder agents may save to; empty is none. Applied at once while agents are connected.
|
||||
pub write_root: String,
|
||||
/// What the app's `<id>-cli mcp` does while agents may use the app but it is closed.
|
||||
pub when_app_closed: WhenAppClosed,
|
||||
}
|
||||
|
||||
impl Default for AgentSettings {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
allow_agent_control: true,
|
||||
control_port: 0,
|
||||
read_root: String::new(),
|
||||
write_root: String::new(),
|
||||
when_app_closed: WhenAppClosed::Launch,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl AgentSettings {
|
||||
/// [`Self::read_root`] as a path ([`folder`]).
|
||||
pub fn read_folder(&self) -> Option<PathBuf> {
|
||||
folder(&self.read_root)
|
||||
}
|
||||
|
||||
/// [`Self::write_root`] as a path ([`folder`]).
|
||||
pub fn write_folder(&self) -> Option<PathBuf> {
|
||||
folder(&self.write_root)
|
||||
}
|
||||
}
|
||||
|
||||
/// A folder setting as a path, trimmed; empty or blank is `None`.
|
||||
pub fn folder(pref: &str) -> Option<PathBuf> {
|
||||
let pref = pref.trim();
|
||||
(!pref.is_empty()).then(|| PathBuf::from(pref))
|
||||
}
|
||||
|
||||
/// What an app's `<id>-cli mcp` does when an agent calls a tool while the app is closed.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum WhenAppClosed {
|
||||
/// Open the app and wait for it.
|
||||
#[default]
|
||||
Launch,
|
||||
/// Run the tool without a window.
|
||||
Headless,
|
||||
/// Answer with an error that asks to open the app.
|
||||
Error,
|
||||
}
|
||||
|
||||
impl WhenAppClosed {
|
||||
/// The saved names, in [`Self::ALL`] order.
|
||||
pub const NAMES: &'static [&'static str] = &["launch", "headless", "error"];
|
||||
/// Every choice, in the order a menu lists them.
|
||||
pub const ALL: [Self; 3] = [Self::Launch, Self::Headless, Self::Error];
|
||||
|
||||
/// The saved name.
|
||||
pub fn name(self) -> &'static str {
|
||||
match self {
|
||||
Self::Launch => "launch",
|
||||
Self::Headless => "headless",
|
||||
Self::Error => "error",
|
||||
}
|
||||
}
|
||||
|
||||
/// The choice a saved name means; `None` for any other text.
|
||||
pub fn parse(name: &str) -> Option<Self> {
|
||||
Self::ALL.into_iter().find(|c| c.name() == name)
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether agents may use the open window. With the suite's `AI-MCP` flag only the launcher's
|
||||
/// switch decides: one switch for every Craft app, none in the app. Without the flag the app's own
|
||||
/// earlier consent decides (`legacy`; PhotoCraft's is a Control Port saved before the switch).
|
||||
/// Allow Agent Control off still refuses agents either way ([`AgentSettings::allow_agent_control`]).
|
||||
pub fn agents_allowed(mcp_flag: bool, launcher: bool, legacy: bool) -> bool {
|
||||
if mcp_flag { launcher } else { legacy }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use craft_ui::testing::trial;
|
||||
|
||||
// The saved names read back as the same choice, and nothing else reads as one.
|
||||
#[trial]
|
||||
fn when_app_closed_names_round_trip() {
|
||||
for choice in WhenAppClosed::ALL {
|
||||
assert_eq!(WhenAppClosed::parse(choice.name()), Some(choice));
|
||||
assert_eq!(serde_json::to_value(choice).unwrap(), serde_json::json!(choice.name()));
|
||||
}
|
||||
assert_eq!(WhenAppClosed::NAMES, WhenAppClosed::ALL.map(WhenAppClosed::name));
|
||||
assert_eq!(WhenAppClosed::parse("Launch"), None);
|
||||
let settings: AgentSettings = serde_json::from_str(r#"{"whenAppClosed": "headless", "controlPort": 7878}"#).unwrap();
|
||||
assert_eq!((settings.when_app_closed, settings.control_port, settings.allow_agent_control), (WhenAppClosed::Headless, 7878, true));
|
||||
}
|
||||
|
||||
// A folder setting is trimmed; empty or blank means no folder.
|
||||
#[trial]
|
||||
fn folder_preferences_are_trimmed() {
|
||||
assert_eq!(folder(""), None);
|
||||
assert_eq!(folder(" "), None);
|
||||
assert_eq!(folder(" /work/project "), Some(PathBuf::from("/work/project")));
|
||||
let settings = AgentSettings { read_root: " /in ".into(), ..AgentSettings::default() };
|
||||
assert_eq!((settings.read_folder(), settings.write_folder()), (Some(PathBuf::from("/in")), None));
|
||||
}
|
||||
}
|
||||
@@ -1,94 +0,0 @@
|
||||
//! The ArtCraft Launcher's switch for one app, behind the suite's `AI-MCP` flag.
|
||||
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::{Arc, Weak};
|
||||
use std::time::Duration;
|
||||
|
||||
use craft_host::Wake;
|
||||
|
||||
use super::agents_allowed;
|
||||
|
||||
/// How often [`AgentSwitch::watch`] reads the launcher's app list.
|
||||
pub const POLL: Duration = Duration::from_secs(2);
|
||||
|
||||
/// The suite's `AI-MCP` flag (`ArtCraft/flags.toml` or `CRAFT_FLAGS`). Reads the flags file;
|
||||
/// what could not be read is logged.
|
||||
pub fn mcp_flag() -> bool {
|
||||
let flags = craft_flags::load();
|
||||
for problem in &flags.problems {
|
||||
log::warn!("flags: {problem}");
|
||||
}
|
||||
flags.enabled(&craft_flags::AI_MCP)
|
||||
}
|
||||
|
||||
/// The launcher's switch (Settings › AI agents › *Let AI agents use Craft apps*) lets agents use
|
||||
/// the app `app_id`: the `AI-MCP` flag is on and the launcher's app list names the app. Reads two
|
||||
/// small files; ask from a timer or a command, not every frame ([`AgentSwitch`] does that).
|
||||
pub fn launcher_allows(app_id: &str) -> bool {
|
||||
mcp_flag() && craft_ai_agents::allowed(app_id)
|
||||
}
|
||||
|
||||
/// The launcher's switch for one app, watched on a thread so a frame can ask without touching the
|
||||
/// disk. The `AI-MCP` flag is read once, at [`Self::watch`]; the launcher's list every [`POLL`].
|
||||
/// Clones share one watch; the thread ends after the last clone is dropped.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct AgentSwitch {
|
||||
mcp_flag: bool,
|
||||
on: Arc<AtomicBool>,
|
||||
}
|
||||
|
||||
impl AgentSwitch {
|
||||
/// Watches the launcher's list for `app_id`; a change logs `agents on/off` and calls `wake`.
|
||||
/// Without the `AI-MCP` flag nothing is watched: the launcher's list means nothing then.
|
||||
pub fn watch(app_id: &'static str, wake: Wake) -> Self {
|
||||
let flag = mcp_flag();
|
||||
if !flag {
|
||||
return Self::fixed(false, false);
|
||||
}
|
||||
Self::watch_with(flag, move || craft_ai_agents::allowed(app_id), POLL, wake)
|
||||
}
|
||||
|
||||
/// A switch that never changes: tests, the web, an app without agents.
|
||||
pub fn fixed(mcp_flag: bool, launcher: bool) -> Self {
|
||||
Self { mcp_flag, on: Arc::new(AtomicBool::new(launcher)) }
|
||||
}
|
||||
|
||||
/// [`Self::watch`] with the flag given, `probe` asked once now and then every `poll`.
|
||||
#[doc(hidden)]
|
||||
pub fn watch_with(mcp_flag: bool, probe: impl Fn() -> bool + Send + 'static, poll: Duration, wake: Wake) -> Self {
|
||||
let on = Arc::new(AtomicBool::new(probe()));
|
||||
let seen: Weak<AtomicBool> = Arc::downgrade(&on);
|
||||
let started = std::thread::Builder::new().name("launcher-agents".into()).spawn(move || {
|
||||
loop {
|
||||
std::thread::sleep(poll);
|
||||
let now = probe();
|
||||
let Some(seen) = seen.upgrade() else { return };
|
||||
if seen.swap(now, Ordering::Relaxed) != now {
|
||||
log::info!("ArtCraft Launcher: agents {}", if now { "on" } else { "off" });
|
||||
wake.wake();
|
||||
}
|
||||
}
|
||||
});
|
||||
// Without a thread the answer stays what it was at launch.
|
||||
if let Err(e) = started {
|
||||
log::warn!("couldn't watch the ArtCraft Launcher's agents switch: {e}");
|
||||
}
|
||||
Self { mcp_flag, on }
|
||||
}
|
||||
|
||||
/// The `AI-MCP` flag as it was when the watch started.
|
||||
pub fn mcp_flag(&self) -> bool {
|
||||
self.mcp_flag
|
||||
}
|
||||
|
||||
/// Whether the launcher's list named the app at the last poll.
|
||||
pub fn launcher(&self) -> bool {
|
||||
self.on.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
/// Whether agents may use the open window ([`agents_allowed`]); `legacy` is the app's own
|
||||
/// earlier consent, which counts only without the flag.
|
||||
pub fn allows(&self, legacy: bool) -> bool {
|
||||
agents_allowed(self.mcp_flag, self.launcher(), legacy)
|
||||
}
|
||||
}
|
||||
@@ -14,7 +14,7 @@ use craft_automation::agents::{
|
||||
};
|
||||
use craft_automation::server;
|
||||
use craft_automation::ui::agents::AgentsPage;
|
||||
use craft_host::{AppInfo, Host, PickId, Picked, ScriptedFiles, Wake};
|
||||
use craft_host::{AppInfo, Host, PickId, Picked, ScriptedFiles};
|
||||
use craft_ui::contract::Role;
|
||||
use craft_ui::patterns::preferences::SettingsDraft;
|
||||
use craft_ui::runtime::motion;
|
||||
@@ -68,9 +68,9 @@ fn the_switch_wakes_once_per_change() {
|
||||
};
|
||||
let wake = {
|
||||
let wakes = wakes.clone();
|
||||
Wake::new(move || {
|
||||
move || {
|
||||
wakes.fetch_add(1, Ordering::Relaxed);
|
||||
})
|
||||
}
|
||||
};
|
||||
let switch = AgentSwitch::watch_with(true, probe, Duration::from_millis(5), wake);
|
||||
let clone = switch.clone();
|
||||
@@ -161,7 +161,9 @@ fn host() -> WindowHost {
|
||||
}
|
||||
|
||||
fn on(port: u32) -> AgentSettings {
|
||||
AgentSettings { control_port: port, ..AgentSettings::default() }
|
||||
let mut s = AgentSettings::default();
|
||||
s.control_port = port;
|
||||
s
|
||||
}
|
||||
|
||||
/// A port nothing listens on: bound, then closed.
|
||||
@@ -188,7 +190,8 @@ fn turning_agents_on_publishes_a_reachable_connection_and_off_removes_it() {
|
||||
assert!(probe(port, PROBE_TIMEOUT));
|
||||
let token = std::fs::read_to_string(dir.path().join(TOKEN_FILE)).unwrap();
|
||||
|
||||
let folders = AgentSettings { read_root: "/in".into(), ..on(0) };
|
||||
let mut folders = on(0);
|
||||
folders.read_root = "/in".into();
|
||||
let kept = link.sync(Some(&folders), &host);
|
||||
assert!(kept.requests.is_none() && !kept.stopped && kept.changed, "a folder change keeps the server");
|
||||
assert_eq!(link.status().port, Some(port));
|
||||
@@ -266,7 +269,9 @@ fn allow_agent_control_off_and_no_settings_folder_keep_agents_out() {
|
||||
let mut link = AgentLink::new(Some(dir.path().to_path_buf()), "x");
|
||||
assert!(link.sync(Some(&on(0)), &host).requests.is_some());
|
||||
let port = link.status().port.expect("listening");
|
||||
let refused = link.sync(Some(&AgentSettings { allow_agent_control: false, ..on(0) }), &host);
|
||||
let mut off = on(0);
|
||||
off.allow_agent_control = false;
|
||||
let refused = link.sync(Some(&off), &host);
|
||||
assert!(refused.stopped && refused.requests.is_none());
|
||||
assert_eq!(link.status().problem, Some(LinkProblem::NotAllowed));
|
||||
assert!(!dir.path().join(CONNECTION_FILE).exists());
|
||||
|
||||
@@ -23,8 +23,8 @@
|
||||
//! | The connection file | [`Connection`], [`write_connection`], [`read_connection`], [`remove_connection`], [`remove_stale_connection`], [`probe`] | desktop, feature `agents` |
|
||||
//! | The CLI's side | [`Live`], [`LiveConfig`], [`Route`], [`Window`], [`Consent`], [`HeadlessFolders`], [`find_window`], [`launcher`] | desktop, feature `agents` |
|
||||
//!
|
||||
//! The same formats as `craft_automation::agents` on the shared UI library's branch (`next`),
|
||||
//! which adds the egui link host and the Agents page of Preferences.
|
||||
//! `craft_automation::agents` re-exports all of this and adds the egui link host and the Agents
|
||||
//! page of Preferences, for apps on the shared UI library.
|
||||
//!
|
||||
//! # Adding an app
|
||||
//!
|
||||
|
||||
@@ -1123,7 +1123,7 @@ Control channel, screenshot queue, profiler and recorded actions for tests and s
|
||||
| `protocol` | JSON-lines wire format and parameter validators | exists |
|
||||
| `security` | Tokens, the authentication handshake (challenge or one-frame token) and transport limits | exists |
|
||||
| `server` | Loopback JSON-lines TCP transport (native): `listen`, `serve`, stopped by dropping its `Listening` | exists |
|
||||
| `agents`, `ui::agents` | AI agents in the open window: the agent settings, the ArtCraft Launcher's switch, the connection file, the link host and the Agents page of Preferences | exists |
|
||||
| `agents`, `ui::agents` | AI agents in the open window: the agent settings, the ArtCraft Launcher's switch, the connection file and the CLI's live client (re-exported from `craft-control`), the link host and the Agents page of Preferences | exists |
|
||||
| `client` | JSON-lines client for tests and command-line tools (native) | exists |
|
||||
| `synthetic` | Synthetic pointer and keyboard input: `ui.click`, `ui.move`, `ui.key`, `ui.type` | exists |
|
||||
| `dialogs` | `ui.dialog.set`, `ui.dialog.confirm` and `ui.dialog.cancel` over a `DialogHost` | exists |
|
||||
|
||||
Reference in New Issue
Block a user