diff --git a/Cargo.lock b/Cargo.lock index 4a2423c33..d18855a94 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1056,12 +1056,41 @@ dependencies = [ "rustversion", ] +[[package]] +name = "cookie" +version = "0.18.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d55f2d6c30eeec7d5c6f98bd4395d4abb1895629eab97ee6522d340623615f8a" +dependencies = [ + "percent-encoding", + "time", + "version_check", +] + [[package]] name = "cookie-factory" version = "0.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9885fa71e26b8ab7855e2ec7cae6e9b380edff76cd052e07c683a0319d51b3a2" +[[package]] +name = "cookie_store" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15b2c103cf610ec6cae3da84a766285b42fd16aad564758459e6ecf128c75206" +dependencies = [ + "cookie", + "document-features", + "idna", + "indexmap", + "log", + "serde", + "serde_derive", + "serde_json", + "time", + "url", +] + [[package]] name = "core-foundation" version = "0.9.4" @@ -2826,6 +2855,22 @@ dependencies = [ "zbus", ] +[[package]] +name = "figcraft-agent" +version = "0.19.0" +dependencies = [ + "base64 0.22.1", + "figcraft-color", + "figcraft-engine", + "figcraft-mcp", + "getrandom 0.4.3", + "log", + "proptest", + "serde", + "serde_json", + "ureq", +] + [[package]] name = "figcraft-cli" version = "0.19.0" @@ -3155,6 +3200,7 @@ dependencies = [ "craft-window", "egui", "egui_extras", + "figcraft-agent", "figcraft-color", "figcraft-doc", "figcraft-engine", @@ -7484,12 +7530,15 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cde93ff05758a36a851a398a772b0b79a82fbe3c186a46f2696baaeaf84c966b" dependencies = [ "base64 0.23.1", + "cookie_store", "flate2", "log", "percent-encoding", "rustls", "rustls-pki-types", "rustls-platform-verifier", + "serde", + "serde_json", "ureq-proto", "utf8-zero", "webpki-roots", diff --git a/Cargo.toml b/Cargo.toml index 9bee84b02..30526c430 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -36,6 +36,7 @@ figcraft-ui-egui = { path = "crates/ui-egui" } figcraft-mcp = { path = "crates/mcp" } figcraft-collab-net = { path = "crates/collab-net" } figcraft-plugin = { path = "crates/plugin" } +figcraft-agent = { path = "crates/agent" } # Keep every craft-libs crate on one rev. # Which paths stored in a document may be followed (craft-libs). @@ -151,6 +152,10 @@ crc32fast = "1" wasmi = { version = "2", default-features = false, features = ["std", "stable", "validate", "portable-dispatch"] } wat = "1.261" +# The agent's HTTP client: blocking, rustls (the TLS provider collab-net already uses), pure Rust +# and forbidden from `unsafe`. Already in the lock through craft-update. +ureq = { version = "3.5", features = ["json"] } + # ui egui = "0.37" egui_extras = { version = "0.37", default-features = false } diff --git a/apps/figcraft/src/services.rs b/apps/figcraft/src/services.rs index e23294567..4d3d70b73 100644 --- a/apps/figcraft/src/services.rs +++ b/apps/figcraft/src/services.rs @@ -493,6 +493,10 @@ pub(crate) fn remembering(last: Arc>>, pick: DialogFuture, } impl Services for Desktop { + fn agent_config_path(&self) -> Option { + crate::services::config_dir().map(|d| d.join("agents.json")) + } + fn pick_open(&mut self, title: &str, exts: &[&str]) -> DialogFuture { let pick = picked(self.dialog_in_last_folder(title).add_filter("Supported files", exts).pick_file()); remembering(self.last_folder.clone(), pick, false) diff --git a/crates/agent/Cargo.toml b/crates/agent/Cargo.toml new file mode 100644 index 000000000..eb23823a2 --- /dev/null +++ b/crates/agent/Cargo.toml @@ -0,0 +1,25 @@ +[package] +name = "figcraft-agent" +version.workspace = true +edition.workspace = true +license.workspace = true +description = "FigCraft's in-app agent: provider adapters, the tool-call loop and the bridge to the open window" + +[lints] +workspace = true + +[dependencies] +figcraft-mcp = { workspace = true } +figcraft-color = { workspace = true } +serde = { workspace = true } +serde_json = { workspace = true } +base64 = { workspace = true } +# The MCP endpoint's bearer token (the OS random source collab-net's session secrets use). +getrandom = "0.4" +log = { workspace = true } +# Blocking HTTP with rustls (the same TLS provider collab-net uses), no async runtime. +ureq = { workspace = true } + +[dev-dependencies] +figcraft-engine = { workspace = true } +proptest = { workspace = true } diff --git a/crates/agent/src/anthropic.rs b/crates/agent/src/anthropic.rs new file mode 100644 index 000000000..20cd67601 --- /dev/null +++ b/crates/agent/src/anthropic.rs @@ -0,0 +1,295 @@ +//! The Anthropic Messages dialect. + +use std::collections::BTreeMap; +use std::sync::atomic::AtomicBool; + +use serde_json::{Value, json}; + +use crate::config::Provider; +use crate::http::{Http, read_error}; +use crate::neutral::{Block, Message, Role}; +use crate::{Invocation, Step}; + +const ANTHROPIC_VERSION: &str = "2023-06-01"; + +pub fn payload(provider: &Provider, system: &str, messages: &[Message], tools: &[Value]) -> Value { + let mut body = json!({ + "model": provider.model, + "max_tokens": provider.max_tokens.max(1), + "system": system, + "messages": wire_messages(messages), + "stream": true, + }); + let tools = crate::neutral::anthropic_tools(tools); + if !tools.is_empty() { + body["tools"] = json!(tools); + } + body +} + +fn wire_messages(messages: &[Message]) -> Vec { + let mut out: Vec = Vec::new(); + for m in messages { + let role = match m.role { + Role::User => "user", + Role::Assistant => "assistant", + }; + let mut content = Vec::new(); + for b in &m.blocks { + match b { + Block::Text(t) => content.push(json!({"type": "text", "text": t})), + Block::Image(i) => content.push(json!({ + "type": "image", + "source": {"type": "base64", "media_type": i.mime, "data": i.data}, + })), + Block::ToolCall { id, name, args } => content.push(json!({ + "type": "tool_use", + "id": id, + "name": name, + "input": args, + })), + Block::ToolResult { id, ok, text, images, .. } => { + let mut blocks = vec![json!({"type": "text", "text": text})]; + for i in images { + blocks.push(json!({ + "type": "image", + "source": {"type": "base64", "media_type": i.mime, "data": i.data}, + })); + } + content.push(json!({ + "type": "tool_result", + "tool_use_id": id, + "content": blocks, + "is_error": !ok, + })); + } + } + } + if content.is_empty() { + continue; + } + // Anthropic wants alternating roles; two user messages in a row (text, then tool results) + // are merged into one. + if let Some(last) = out.last_mut() + && last["role"].as_str() == Some(role) + && let Some(parts) = last["content"].as_array_mut() + { + parts.extend(content); + continue; + } + out.push(json!({"role": role, "content": content})); + } + out +} + +fn headers(provider: &Provider, session: &str) -> Vec<(&'static str, String)> { + let mut h = vec![ + ("x-api-key", provider.api_key.trim().to_string()), + ("anthropic-version", ANTHROPIC_VERSION.to_string()), + ("accept", "text/event-stream".to_string()), + ]; + if provider.base_url.contains("opencode.ai") { + h.push(("x-opencode-session", session.to_string())); + } + h +} + +pub fn stream( + http: &Http, + provider: &Provider, + system: &str, + messages: &[Message], + tools: &[Value], + session: &str, + on_text: &mut dyn FnMut(&str), + cancel: &AtomicBool, +) -> Result { + let reply = http.post(&provider.endpoint(), &headers(provider, session), &payload(provider, system, messages, tools))?; + if reply.status >= 400 { + return Err(read_error(reply.status, reply.body)); + } + let events = crate::sse::spawn_events(reply.body); + let mut step = Step::default(); + let mut pending: BTreeMap = BTreeMap::new(); + // `message_stop` ends a whole answer; a stream that ends before it was cut off. + let mut stopped = false; + while let Some(event) = crate::sse::next(&events, cancel)? { + if event.data.trim().is_empty() { + continue; + } + let v: Value = match serde_json::from_str(&event.data) { + Ok(v) => v, + Err(_) => continue, + }; + match event.name.as_str() { + "message_stop" => { + stopped = true; + break; + } + "message_start" => { + if let Some(u) = v.get("message").and_then(|m| m.get("usage")) { + step.usage.input = u.get("input_tokens").and_then(Value::as_u64).unwrap_or(step.usage.input); + step.usage.output = u.get("output_tokens").and_then(Value::as_u64).unwrap_or(step.usage.output); + } + } + "content_block_start" => { + let index = v.get("index").and_then(Value::as_u64).unwrap_or(0); + let block = &v["content_block"]; + match block.get("type").and_then(Value::as_str) { + Some("tool_use") => { + let id = block.get("id").and_then(Value::as_str).unwrap_or("").to_string(); + let name = block.get("name").and_then(Value::as_str).unwrap_or("").to_string(); + // The start carries `input: {}` as a placeholder before the streamed + // fragments; it is the input only when no fragment follows. + let initial = block.get("input").filter(|i| !i.is_null()).map(|i| i.to_string()).unwrap_or_default(); + pending.insert(index, Pending { id, name, initial, streamed: String::new() }); + } + Some("text") => { + if let Some(t) = block.get("text").and_then(Value::as_str) + && !t.is_empty() + { + step.text.push_str(t); + on_text(t); + } + } + _ => {} + } + } + "content_block_delta" => { + let index = v.get("index").and_then(Value::as_u64).unwrap_or(0); + let delta = &v["delta"]; + match delta.get("type").and_then(Value::as_str) { + Some("text_delta") => { + if let Some(t) = delta.get("text").and_then(Value::as_str) { + step.text.push_str(t); + on_text(t); + } + } + Some("input_json_delta") => { + if let Some(partial) = delta.get("partial_json").and_then(Value::as_str) + && let Some(entry) = pending.get_mut(&index) + { + entry.streamed.push_str(partial); + } + } + _ => {} + } + } + "message_delta" => { + if let Some(reason) = v.get("delta").and_then(|d| d.get("stop_reason")).and_then(Value::as_str) { + step.stop = reason.to_string(); + } + if let Some(u) = v.get("usage") { + step.usage.output = u.get("output_tokens").and_then(Value::as_u64).unwrap_or(step.usage.output); + } + } + "error" => { + let msg = + v.get("error").and_then(|e| e.get("message")).and_then(Value::as_str).map(str::to_string).unwrap_or_else(|| event.data.clone()); + return Err(msg); + } + _ => {} + } + } + if !stopped { + return Err(crate::openai::INTERRUPTED.to_string()); + } + for (i, p) in pending { + if let Some(call) = p.into_call(i) { + step.calls.push(call); + } + } + Ok(step) +} + +/// A tool call being built: the input its start gave, and the fragments streamed after it. +struct Pending { + id: String, + name: String, + initial: String, + streamed: String, +} + +impl Pending { + fn into_call(self, index: u64) -> Option { + if self.name.is_empty() { + return None; + } + let id = if self.id.is_empty() { format!("toolu_{index}") } else { self.id }; + let raw = if self.streamed.trim().is_empty() { self.initial } else { self.streamed }; + let args = if raw.trim().is_empty() { json!({}) } else { serde_json::from_str(&raw).unwrap_or(Value::Null) }; + Some(Invocation { id, name: self.name, args, args_raw: raw }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::config::ApiKind; + + fn provider() -> Provider { + let mut p = Provider::new("Anthropic", ApiKind::AnthropicMessages, "https://api.anthropic.com/v1"); + p.model = "claude-sonnet-5".into(); + p.api_key = "sk-ant".into(); + p.max_tokens = 4096; + p + } + + #[test] + fn the_system_prompt_is_top_level_and_max_tokens_is_sent() { + let messages = vec![Message::user_text("hi")]; + let body = payload(&provider(), "you design", &messages, &[]); + assert_eq!(body["system"], "you design"); + assert_eq!(body["max_tokens"], 4096); + assert_eq!(body["messages"][0]["content"][0]["text"], "hi"); + } + + #[test] + fn tool_results_are_user_blocks_with_images_inside() { + let messages = vec![Message { + role: Role::User, + blocks: vec![Block::ToolResult { + id: "toolu_1".into(), + name: "screenshot".into(), + ok: true, + text: "the page".into(), + images: vec![crate::neutral::Image { mime: "image/png".into(), data: "AAAA".into() }], + }], + }]; + let body = payload(&provider(), "s", &messages, &[]); + let block = &body["messages"][0]["content"][0]; + assert_eq!(block["type"], "tool_result"); + assert_eq!(block["content"][1]["type"], "image"); + assert_eq!(block["content"][1]["source"]["data"], "AAAA"); + } + + #[test] + fn consecutive_user_messages_are_merged() { + let messages = vec![Message::user_text("look"), Message::user_text("again")]; + let body = payload(&provider(), "s", &messages, &[]); + let wire = body["messages"].as_array().cloned().unwrap_or_default(); + assert_eq!(wire.len(), 1, "Anthropic requires alternating roles"); + assert_eq!(wire[0]["content"].as_array().map(Vec::len), Some(2)); + } + + fn call(initial: &str, fragments: &[&str]) -> Option { + let streamed = fragments.concat(); + Pending { id: "toolu_1".into(), name: "load_skill".into(), initial: initial.into(), streamed }.into_call(0) + } + + #[test] + fn streamed_arguments_replace_the_placeholder_input() { + let c = call("{}", &["{\"name\":", "\"Design review\"}"]).expect("a call"); + assert_eq!(c.args["name"], "Design review"); + let none = call("{}", &[]).expect("a call"); + assert_eq!(none.args, json!({}), "no fragments: the start's input is the input"); + } + + #[test] + fn headers_use_x_api_key_not_bearer() { + let h = headers(&provider(), "s"); + assert!(h.iter().any(|(k, v)| *k == "x-api-key" && v == "sk-ant")); + assert!(h.iter().any(|(k, _)| *k == "anthropic-version")); + assert!(!h.iter().any(|(k, _)| *k == "authorization")); + } +} diff --git a/crates/agent/src/bridge.rs b/crates/agent/src/bridge.rs new file mode 100644 index 000000000..13bb6d3dc --- /dev/null +++ b/crates/agent/src/bridge.rs @@ -0,0 +1,104 @@ +//! The bridge to the open window. +//! +//! The agent runs on its own thread and must not touch the session (it lives on the UI thread). +//! Every tool call becomes a [`Call`] the UI drains into its control queue, exactly like a request +//! from `figcraft-cli mcp --attach`; the reply comes back on the call's channel. Implementing +//! [`figcraft_mcp::Backend`] over that channel is what lets the agent reuse the MCP tool set +//! unchanged, with the same behaviour an external MCP client gets. + +use std::sync::Arc; +use std::sync::mpsc::{Receiver, Sender, channel}; +use std::time::Duration; + +use serde_json::{Value, json}; + +/// One control request from the agent thread to the UI thread. +pub struct Call { + pub method: String, + pub params: Value, + pub reply: Sender>, +} + +/// The UI side: the calls the agent thread is waiting for. +pub struct Bridge { + pub calls: Receiver, +} + +/// The agent side: sends calls and waits for their answers. +#[derive(Clone)] +pub struct Remote { + tx: Sender, + /// The name every command runs as, so the app shows the agent's avatar and signs its comments. + agent: String, + /// Wakes the window, which is idle between frames while the agent waits for an answer. + wake: Arc, +} + +/// A fresh pair: the UI keeps the bridge, the agent thread keeps the remote. +pub fn pair(agent: impl Into, wake: Arc) -> (Bridge, Remote) { + let (tx, rx) = channel(); + (Bridge { calls: rx }, Remote { tx, agent: agent.into(), wake }) +} + +impl Remote { + /// How long one tool call waits for the UI before giving up. + const WAIT: Duration = Duration::from_secs(600); + + /// Send one control method and wait for its answer. + pub fn request(&self, method: &str, params: Value) -> Result { + self.send(method, params) + } + + fn send(&self, method: &str, mut params: Value) -> Result { + if method == "engine.execute" { + // The app shows an AI agent's presence from this, and signs its comments. + params["agent"] = json!(self.agent); + } + let (reply, answer) = channel(); + self.tx.send(Call { method: method.to_string(), params, reply }).map_err(|_| "the window closed".to_string())?; + (self.wake)(); + match answer.recv_timeout(Self::WAIT) { + Ok(r) => r, + Err(_) => Err(format!("the window did not answer `{method}` in time")), + } + } +} + +impl figcraft_mcp::Backend for Remote { + fn call(&mut self, method: &str, params: Value) -> Result { + self.send(method, params) + } + + fn has_ui(&self) -> bool { + true + } + + fn describe(&self) -> String { + "the open window".to_string() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_call_carries_the_agent_name_and_its_reply() { + let (bridge, mut remote) = pair("FigCraft Agent", Arc::new(|| {})); + let t = std::thread::spawn(move || figcraft_mcp::Backend::call(&mut remote, "engine.execute", json!({"command": "frame.create"}))); + let call = bridge.calls.recv().expect("a call"); + assert_eq!(call.method, "engine.execute"); + assert_eq!(call.params["agent"], "FigCraft Agent"); + call.reply.send(Ok(json!({"id": 7}))).expect("reply"); + assert_eq!(t.join().expect("thread"), Ok(json!({"id": 7}))); + } + + #[test] + fn a_closed_window_fails_the_call_instead_of_hanging() { + let (bridge, remote) = pair("Agent", Arc::new(|| {})); + drop(bridge); + let mut remote = remote; + let err = figcraft_mcp::Backend::call(&mut remote, "document.inspect", json!({})).unwrap_err(); + assert!(err.contains("window closed")); + } +} diff --git a/crates/agent/src/brief.rs b/crates/agent/src/brief.rs new file mode 100644 index 000000000..c3215e098 --- /dev/null +++ b/crates/agent/src/brief.rs @@ -0,0 +1,898 @@ +//! The file's design system and the page it lives on, `00 · Design System`: the choices behind +//! it (product, colour, type, shape, icons, voice) become variables, styles, review settings and +//! a guidelines text on that page, in one step the agent takes with the `design_system` tool. +//! +//! The foundations follow what public design-system guides cover (Material 3, IBM Carbon, Apple's +//! Human Interface Guidelines, Atlassian, Shopify Polaris, and the W3C Design Tokens format +//! 2025.10): colour roles with light and dark modes, a type scale, a 4 or 8 spacing step, radius, +//! elevation, an icon set and style, voice, and contrast targets. The idea of starting a file from +//! a design library with variables and themes comes from pen.dev's public documentation +//! (docs.pencil.dev: design systems, variables, AI agents). Ideas only; nothing here is copied. +//! +//! [`Brief::steps`] builds the commands for the engine's `command.batch`, so making (or updating) +//! the system is one undo step and works the same from the panel, the CLI or MCP. + +use std::collections::{BTreeMap, BTreeSet}; + +use figcraft_color::{Color, Oklch}; +use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; + +/// The collections and their modes the steps make. +pub const PRIMITIVES: &str = "Primitives"; +pub const THEME: &str = "Theme"; +pub const SIZES: &str = "Sizes"; + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum Platform { + Mobile, + #[default] + Web, + Both, +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum Neutral { + Cool, + #[default] + Neutral, + Warm, +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum Modes { + Light, + Dark, + #[default] + Both, +} + +impl Modes { + pub fn names(self) -> &'static [&'static str] { + match self { + Modes::Light => &["Light"], + Modes::Dark => &["Dark"], + Modes::Both => &["Light", "Dark"], + } + } +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum TypeScale { + /// 14 px body, sizes 1.2 apart. + Compact, + /// 16 px body, 1.25 apart. + #[default] + Default, + /// 18 px body, 1.25 apart. + Large, +} + +impl TypeScale { + fn base_ratio(self) -> (f64, f64) { + match self { + TypeScale::Compact => (14.0, 1.2), + TypeScale::Default => (16.0, 1.25), + TypeScale::Large => (18.0, 1.25), + } + } +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum Radius { + Sharp, + #[default] + Soft, + Round, + Pill, +} + +impl Radius { + /// Small, medium, large. + fn values(self) -> [f64; 3] { + match self { + Radius::Sharp => [2.0, 4.0, 6.0], + Radius::Soft => [4.0, 8.0, 12.0], + Radius::Round => [8.0, 16.0, 24.0], + Radius::Pill => [12.0, 20.0, 28.0], + } + } +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum Elevation { + Flat, + #[default] + Subtle, + Raised, +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum IconStyle { + #[default] + Outline, + Filled, + Duotone, +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum Contrast { + #[default] + Aa, + Aaa, +} + +/// Open-source icon sets a brief can name: (name, licence, what it looks like). Nothing is +/// downloaded; the agent draws icons in the set's manner, or the person imports them. +pub const ICON_SETS: &[(&str, &str, &str)] = &[ + ("Lucide", "ISC", "Clean outline icons on a 24 grid, 2 px strokes, round caps; a wide everyday set."), + ("Heroicons", "MIT", "Outline (1.5 px) and solid versions at 24, with smaller solid sizes; plain and friendly."), + ("Tabler Icons", "MIT", "A very large outline set on a 24 grid with 2 px strokes; consistent and neutral."), + ("Phosphor", "MIT", "One set in six weights from thin to fill plus duotone; soft, rounded shapes."), + ("Feather", "MIT", "A small, light outline set on a 24 grid with 2 px strokes; minimal."), + ("Material Symbols", "Apache-2.0", "Google's set with fill, weight and size variations; geometric and familiar on Android."), +]; + +/// What the file's design system should be. Every field has a default, so an older or partial +/// brief reads back. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default, rename_all = "camelCase")] +pub struct Brief { + pub version: u32, + // The product. + pub product: String, + pub description: String, + pub audience: String, + pub platform: Platform, + /// The language the copy is written in. + pub language: String, + // Colour (hex). + pub primary: String, + pub secondary: String, + pub accent: String, + pub neutral: Neutral, + pub success: String, + pub warning: String, + pub danger: String, + pub info: String, + pub modes: Modes, + // Type. + pub heading_font: String, + pub body_font: String, + pub mono_font: String, + pub scale: TypeScale, + // Shape. + /// 4 or 8. + pub spacing: u8, + pub radius: Radius, + pub elevation: Elevation, + pub border: f64, + // Icons. + /// A name from [`ICON_SETS`], or anything the person typed. + pub icon_set: String, + pub icon_style: IconStyle, + pub icon_stroke: f64, + pub icon_size: u8, + // Voice and rules. + pub tone: String, + pub imagery: String, + pub contrast: Contrast, + pub notes: String, +} + +impl Default for Brief { + fn default() -> Self { + Self { + version: 1, + product: String::new(), + description: String::new(), + audience: String::new(), + platform: Platform::Web, + language: String::new(), + primary: "#2563EB".into(), + secondary: String::new(), + accent: String::new(), + neutral: Neutral::Neutral, + success: "#16A34A".into(), + warning: "#D97706".into(), + danger: "#DC2626".into(), + info: "#0284C7".into(), + modes: Modes::Both, + heading_font: "Inter".into(), + body_font: "Inter".into(), + mono_font: "JetBrains Mono".into(), + scale: TypeScale::Default, + spacing: 4, + radius: Radius::Soft, + elevation: Elevation::Subtle, + border: 1.0, + icon_set: "Lucide".into(), + icon_style: IconStyle::Outline, + icon_stroke: 2.0, + icon_size: 24, + tone: String::new(), + imagery: String::new(), + contrast: Contrast::Aa, + notes: String::new(), + } + } +} + +/// The ramp steps every colour gets. +pub const STEPS: [u16; 10] = [50, 100, 200, 300, 400, 500, 600, 700, 800, 900]; +/// OKLCH lightness per step, light to dark. +const RAMP_L: [f32; 10] = [0.97, 0.93, 0.87, 0.79, 0.70, 0.61, 0.52, 0.44, 0.36, 0.28]; +/// Share of the colour's own chroma per step (pale and deep ends are calmer). +const RAMP_C: [f32; 10] = [0.15, 0.3, 0.5, 0.75, 0.92, 1.0, 0.95, 0.85, 0.72, 0.6]; + +/// Ten shades of `hex` from 50 (palest) to 900 (deepest), keeping its hue; `None` if it is not a +/// colour. +pub fn ramp(hex: &str) -> Option> { + let base = Oklch::from_color(Color::from_hex(hex)?); + Some(ramp_of(base.c, base.h)) +} + +fn ramp_of(chroma: f32, hue: f32) -> Vec { + (0..STEPS.len()).map(|i| Oklch { l: RAMP_L[i], c: chroma * RAMP_C[i], h: hue }.to_color().to_css_hex()).collect() +} + +/// A grey ramp, tinted cool (blue), warm (sand) or not at all. +fn neutral_ramp(tone: Neutral) -> Vec { + match tone { + Neutral::Cool => ramp_of(0.02, 255.0), + Neutral::Neutral => ramp_of(0.0, 0.0), + Neutral::Warm => ramp_of(0.018, 70.0), + } +} + +/// `hex` made lighter, for the dark mode of a status colour. +fn lighter(hex: &str) -> String { + match Color::from_hex(hex) { + Some(c) => { + let o = Oklch::from_color(c); + Oklch { l: (o.l + 0.12).min(0.85), ..o }.to_color().to_css_hex() + } + None => hex.to_string(), + } +} + +/// What a file already has, so running the steps again updates rather than duplicates. +#[derive(Clone, Debug, Default)] +pub struct Existing { + /// Collection name → its mode names. + pub collections: BTreeMap>, + /// (collection name, variable name) → the variable's id, so an update names that one variable + /// even when another collection has one of the same name. + pub variables: BTreeMap<(String, String), String>, + pub styles: BTreeSet, +} + +impl Existing { + /// Read `variable.list` and `style.list` results. + pub fn from_lists(variables: &Value, styles: &Value) -> Self { + let mut e = Existing::default(); + let mut by_id = BTreeMap::new(); + for c in variables.get("collections").and_then(Value::as_array).into_iter().flatten() { + let (Some(id), Some(name)) = (c.get("id").and_then(Value::as_str), c.get("name").and_then(Value::as_str)) else { continue }; + let modes = c + .get("modes") + .and_then(Value::as_array) + .into_iter() + .flatten() + .filter_map(|m| m.get("name").and_then(Value::as_str)) + .map(str::to_string); + e.collections.insert(name.to_string(), modes.collect()); + by_id.insert(id.to_string(), name.to_string()); + } + for v in variables.get("variables").and_then(Value::as_array).into_iter().flatten() { + let (Some(c), Some(name)) = (v.get("collection").and_then(Value::as_str), v.get("name").and_then(Value::as_str)) else { continue }; + if let Some(cname) = by_id.get(c) { + let id = v.get("id").and_then(Value::as_str).unwrap_or(name); + e.variables.insert((cname.clone(), name.to_string()), id.to_string()); + } + } + for s in styles.as_array().into_iter().flatten() { + if let Some(name) = s.get("name").and_then(Value::as_str) { + e.styles.insert(name.to_string()); + } + } + e + } +} + +/// A variable's value per mode: a colour, a number, or an alias to another variable. +#[derive(Clone, Debug)] +enum Val { + Lit(Value), + Alias(String), +} + +impl Val { + fn json(&self) -> Value { + match self { + Val::Lit(v) => v.clone(), + Val::Alias(name) => json!({"alias": name}), + } + } +} + +impl Brief { + /// Read a brief kept as page data; a damaged one gives the defaults back. + pub fn from_json(text: &str) -> Option { + serde_json::from_str(text).ok() + } + + pub fn to_json(&self) -> String { + serde_json::to_string(self).unwrap_or_default() + } + + fn hex_or<'a>(value: &'a str, fallback: &'a str) -> &'a str { + if Color::from_hex(value).is_some() { value } else { fallback } + } + + /// The colour ramps of the Primitives collection: (group name, ten shades). + fn ramps(&self) -> Vec<(&'static str, Vec)> { + let mut out = vec![("Primary", ramp(Self::hex_or(&self.primary, "#2563EB")).unwrap_or_default())]; + for (name, hex) in [("Secondary", &self.secondary), ("Accent", &self.accent)] { + if let Some(r) = ramp(hex) { + out.push((name, r)); + } + } + out.push(("Neutral", neutral_ramp(self.neutral))); + out + } + + /// The Theme roles: (name, Light value, Dark value). + fn roles(&self) -> Vec<(String, Val, Val)> { + let a = |s: &str| Val::Alias(s.to_string()); + let lit = |s: &str| Val::Lit(json!(s)); + // Text on the primary colour: white or near-black, whichever reads better on Primary/600. + let primary = ramp(Self::hex_or(&self.primary, "#2563EB")).unwrap_or_default(); + let on_primary = primary + .get(6) + .and_then(|p| Color::from_hex(p)) + .map(|p| { + let (white, ink) = (Color::new(1.0, 1.0, 1.0, 1.0), Color::from_hex("#111111").unwrap_or(Color::new(0.07, 0.07, 0.07, 1.0))); + if p.contrast(white) >= p.contrast(ink) { "#FFFFFF" } else { "#111111" } + }) + .unwrap_or("#FFFFFF"); + let mut roles = vec![ + ("Background".to_string(), lit("#FFFFFF"), a("Neutral/900")), + ("Surface".into(), a("Neutral/50"), a("Neutral/800")), + ("Surface raised".into(), lit("#FFFFFF"), a("Neutral/700")), + ("Text".into(), a("Neutral/900"), a("Neutral/50")), + ("Text muted".into(), a("Neutral/600"), a("Neutral/300")), + ("Border".into(), a("Neutral/200"), a("Neutral/700")), + ("Primary".into(), a("Primary/600"), a("Primary/400")), + ("Primary hover".into(), a("Primary/700"), a("Primary/300")), + ("On primary".into(), lit(on_primary), a("Neutral/900")), + ("Focus".into(), a("Primary/500"), a("Primary/400")), + ]; + for (name, hex) in [("Secondary", &self.secondary), ("Accent", &self.accent)] { + if Color::from_hex(hex).is_some() { + roles.push((name.into(), a(&format!("{name}/600")), a(&format!("{name}/400")))); + } + } + for (name, hex, fallback) in [ + ("Success", &self.success, "#16A34A"), + ("Warning", &self.warning, "#D97706"), + ("Danger", &self.danger, "#DC2626"), + ("Info", &self.info, "#0284C7"), + ] { + let hex = Self::hex_or(hex, fallback); + roles.push((name.into(), lit(hex), Val::Lit(json!(lighter(hex))))); + } + roles + } + + /// The Sizes collection: (name, value). + fn sizes(&self) -> Vec<(String, f64)> { + let base = if self.spacing == 8 { 8.0 } else { 4.0 }; + let mut out: Vec<(String, f64)> = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 8.0, 10.0, 12.0, 16.0] + .iter() + .map(|m| { + let v = base * m; + (format!("Space/{v}"), v) + }) + .collect(); + let [s, m, l] = self.radius.values(); + out.extend([("Radius/S".to_string(), s), ("Radius/M".into(), m), ("Radius/L".into(), l), ("Radius/Full".into(), 9999.0)]); + out.extend([ + ("Border/Default".to_string(), self.border.clamp(0.5, 4.0)), + ("Border/Focus".into(), 2.0), + ("Icon/Size".into(), f64::from(self.icon_size.clamp(12, 48))), + ("Icon/Stroke".into(), self.icon_stroke.clamp(0.5, 4.0)), + ]); + out + } + + /// Text styles: (name, size, weight, line height, family). + fn type_styles(&self) -> Vec<(&'static str, f64, u16, f64, String)> { + let (b, r) = self.scale.base_ratio(); + let size = |step: i32| (b * r.powi(step)).round(); + let font = |f: &str, fallback: &str| if f.trim().is_empty() { fallback.to_string() } else { f.trim().to_string() }; + let (head, body, mono) = (font(&self.heading_font, "Inter"), font(&self.body_font, "Inter"), font(&self.mono_font, "JetBrains Mono")); + let tight = |s: f64| (s * 1.2 / 2.0).round() * 2.0; + let loose = |s: f64| (s * 1.5 / 2.0).round() * 2.0; + let list: [(&str, i32, u16, bool, &str); 10] = [ + ("Display", 5, 700, true, "h"), + ("Heading 1", 4, 700, true, "h"), + ("Heading 2", 3, 600, true, "h"), + ("Heading 3", 2, 600, true, "h"), + ("Body large", 1, 400, false, "b"), + ("Body", 0, 400, false, "b"), + ("Body small", -1, 400, false, "b"), + ("Caption", -2, 400, false, "b"), + ("Label", -1, 500, false, "b"), + ("Code", -1, 400, false, "m"), + ]; + list.iter() + .map(|(name, step, weight, heading, fam)| { + let s = size(*step); + let family = match *fam { + "h" => head.clone(), + "m" => mono.clone(), + _ => body.clone(), + }; + (*name, s, *weight, if *heading { tight(s) } else { loose(s) }, family) + }) + .collect() + } + + /// Shadow styles: (name, y offset, blur, spread, opacity). + fn shadows(&self) -> [(&'static str, f64, f64, f64, f64); 3] { + let k = match self.elevation { + Elevation::Flat => 0.5, + Elevation::Subtle => 1.0, + Elevation::Raised => 1.6, + }; + [("Shadow/S", 1.0, 2.0, 0.0, 0.06 * k), ("Shadow/M", 4.0, 10.0, -2.0, 0.08 * k), ("Shadow/L", 12.0, 28.0, -6.0, 0.11 * k)] + } + + /// The file's design review settings (`design.configure`) from the brief: its spacing step as + /// the grid, its corners as the radii, its colours as the brand, and the contrast target. + pub fn review_settings(&self) -> Value { + let preset = match self.contrast { + Contrast::Aa => "recommended", + Contrast::Aaa => "accessibility", + }; + let brand: Vec = [&self.primary, &self.secondary, &self.accent] + .into_iter() + .filter_map(|h| Color::from_hex(h).map(|c| c.to_css_hex())) + .chain(ramp(Self::hex_or(&self.primary, "#2563EB")).unwrap_or_default().into_iter().skip(4).take(4)) + .collect(); + json!({ + "preset": preset, + "grid": if self.spacing == 8 { 8 } else { 4 }, + "radii": self.radius.values(), + "brand": brand, + }) + } + + /// The commands that make (or bring up to date) the file's variables and styles, for + /// `command.batch`: `[{command, params}]`. + pub fn steps(&self, existing: &Existing) -> Vec { + let mut out = Vec::new(); + // Primitives: one mode, the colour ramps. + let mut prim: Vec<(String, Vec)> = Vec::new(); + for (group, shades) in self.ramps() { + for (step, hex) in STEPS.iter().zip(shades) { + prim.push((format!("{group}/{step}"), vec![Val::Lit(json!(hex))])); + } + } + collection(&mut out, existing, PRIMITIVES, &["Default"], "color", prim); + // Theme: the roles, per mode. + let modes = self.modes.names(); + let theme = self + .roles() + .into_iter() + .map(|(name, light, dark)| { + let values = modes.iter().map(|m| if *m == "Dark" { dark.clone() } else { light.clone() }).collect(); + (name, values) + }) + .collect(); + collection(&mut out, existing, THEME, modes, "color", theme); + // Sizes. + let sizes = self.sizes().into_iter().map(|(n, v)| (n, vec![Val::Lit(json!(v))])).collect(); + collection(&mut out, existing, SIZES, &["Default"], "number", sizes); + // Text styles. + for (name, size, weight, line, family) in self.type_styles() { + let value = json!({"fontFamily": family, "fontSize": size, "fontWeight": weight, "lineHeight": line}); + out.push(if existing.styles.contains(name) { + json!({"command": "style.update", "params": {"style": name, "value": value}}) + } else { + json!({"command": "style.create", "params": {"type": "text", "name": name, "value": value}}) + }); + } + // FigCraft's design review checks against the same choices. + out.push(json!({"command": "design.configure", "params": self.review_settings()})); + // Shadows. + for (name, y, blur, spread, alpha) in self.shadows() { + let a = (alpha.clamp(0.0, 1.0) * 255.0).round() as u8; + let value = json!([{"type": "dropShadow", "color": format!("#0F172A{a:02X}"), "offset": [0.0, y], "radius": blur, "spread": spread}]); + out.push(if existing.styles.contains(name) { + json!({"command": "style.update", "params": {"style": name, "value": value}}) + } else { + json!({"command": "style.create", "params": {"type": "effect", "name": name, "value": value}}) + }); + } + out + } + + /// The design guidelines as written on the design system page. + pub fn guidelines(&self) -> String { + let mut lines = vec![GUIDELINES.to_string()]; + let opt = |label: &str, v: &str| if v.trim().is_empty() { None } else { Some(format!("{label}: {}", v.trim())) }; + lines.extend(opt("Product", &self.product)); + lines.extend(opt("What it does", &self.description)); + lines.extend(opt("For", &self.audience)); + lines.push(format!( + "Platform: {}", + match self.platform { + Platform::Mobile => "mobile app (390 x 844 frames)", + Platform::Web => "web (1440 wide desktop frames, plus 390 mobile when asked)", + Platform::Both => "mobile app and web", + } + )); + lines.extend(opt("Write the copy in", &self.language)); + lines.push(format!( + "Colour: primary {}{}{}; status colours success {}, warning {}, danger {}, info {}; modes {}. Use the Theme variables (Background, Surface, Text, Text muted, Border, Primary, On primary…) for every colour once they exist.", + self.primary, + if self.secondary.trim().is_empty() { String::new() } else { format!(", secondary {}", self.secondary.trim()) }, + if self.accent.trim().is_empty() { String::new() } else { format!(", accent {}", self.accent.trim()) }, + self.success, + self.warning, + self.danger, + self.info, + self.modes.names().join(" and "), + )); + let (base, ratio) = self.scale.base_ratio(); + lines.push(format!( + "Type: headings in {}, body in {}, code in {}; body {base} px, sizes {ratio} apart. Use the text styles (Display, Heading 1-3, Body, Body small, Caption, Label, Code).", + self.heading_font, self.body_font, self.mono_font + )); + lines.push(format!( + "Shape: spacing in steps of {} (Sizes/Space variables), corners {:?} (Radius variables), elevation {:?} (Shadow styles), borders {} px.", + if self.spacing == 8 { 8 } else { 4 }, + self.radius, + self.elevation, + self.border + )); + let set = ICON_SETS.iter().find(|(n, _, _)| n.eq_ignore_ascii_case(self.icon_set.trim())); + lines.push(format!( + "Icons: {} ({:?}, {} px stroke, {} px){}. Draw each icon as vector paths in that set's manner on a {} grid, or use an icon the user imported; never emoji.", + if self.icon_set.trim().is_empty() { "a line icon set" } else { self.icon_set.trim() }, + self.icon_style, + self.icon_stroke, + self.icon_size, + set.map(|(_, _, d)| format!(": {d}")).unwrap_or_default(), + self.icon_size + )); + lines.extend(opt("Voice", &self.tone)); + lines.extend(opt("Imagery", &self.imagery)); + lines.push(match self.contrast { + Contrast::Aa => "Accessibility: WCAG AA (text 4.5:1, large text and controls 3:1), touch targets at least 44.".to_string(), + Contrast::Aaa => "Accessibility: WCAG AAA (text 7:1, large text 4.5:1), touch targets at least 44.".to_string(), + }); + lines.extend(opt("Also", &self.notes)); + lines.join("\n") + } +} + +/// Steps for one collection: create it (or add missing modes), then create or set each variable. +fn collection(out: &mut Vec, existing: &Existing, name: &str, modes: &[&str], kind: &str, vars: Vec<(String, Vec)>) { + match existing.collections.get(name) { + None => out.push(json!({"command": "variable.createCollection", "params": {"name": name, "modes": modes}})), + Some(have) => { + for m in modes { + if !have.iter().any(|h| h == m) { + out.push(json!({"command": "variable.addMode", "params": {"collection": name, "name": m}})); + } + } + } + } + for (var, values) in vars { + if let Some(id) = existing.variables.get(&(name.to_string(), var.clone())) { + for (m, v) in modes.iter().zip(&values) { + out.push(json!({"command": "variable.set", "params": {"variable": id, "mode": m, "value": v.json()}})); + } + } else { + let values: serde_json::Map = modes.iter().map(ToString::to_string).zip(values.iter().map(Val::json)).collect(); + out.push(json!({"command": "variable.create", "params": {"collection": name, "name": var, "type": kind, "values": values}})); + } + } +} + +/// The tool the model reads and makes the design system page with. +pub const TOOL_NAME: &str = "design_system"; + +/// The page every file's design system lives on, first in the file. +pub const PAGE: &str = "00 · Design System"; + +/// The text layer on that page holding the choices tokens can't hold (icons, voice, rules). +pub const GUIDELINES: &str = "Design guidelines"; + +/// The `design_system` tool, as the tool list has it. +pub fn tool_definition() -> Value { + json!({ + "name": TOOL_NAME, + "description": "The file's design system, which lives on the page '00 · Design System'. With no arguments: whether that page exists, its frames, its design guidelines and the variable collections. With `spec`: make or update it in one undo step: the page (first in the file), the variables (colour ramps, Theme roles with Light/Dark, Sizes), text and shadow styles, the review settings design.audit uses, and a 'Design guidelines' text on the page with the choices tokens can't hold. Spec fields (all optional): product, description, audience, platform (mobile|web|both), language, primary, secondary, accent (hex), neutral (cool|neutral|warm), success, warning, danger, info (hex), modes (light|dark|both), headingFont, bodyFont, monoFont, scale (compact|default|large), spacing (4|8), radius (sharp|soft|round|pill), elevation (flat|subtle|raised), border, iconSet (e.g. Lucide, Heroicons, Tabler Icons, Phosphor, Feather, Material Symbols), iconStyle (outline|filled|duotone), iconStroke, iconSize, tone, imagery, contrast (aa|aaa), notes.", + "inputSchema": { + "type": "object", + "properties": { + "spec": {"type": "object", "description": "Design system choices to make (others take defaults)"} + } + } + }) +} + +/// Run a command on the file the operation started in (`document`, from `doc.list`), so a tab the +/// person switches to meanwhile is never written to; a file closed meanwhile fails the call. +fn exec(b: &mut dyn figcraft_mcp::Backend, document: Option, cmd: &str, params: Value) -> Result { + let mut request = json!({"command": cmd, "params": params}); + if let Some(d) = document { + request["document"] = json!(d); + } + b.call("engine.execute", request) +} + +/// The id of the file in front, which the whole operation then works in. +fn front_document(b: &mut dyn figcraft_mcp::Backend) -> Option { + let list = exec(b, None, "doc.list", json!({})).ok()?; + list.as_array()?.iter().find(|d| d.get("active").and_then(Value::as_bool) == Some(true))?.get("id")?.as_u64() +} + +/// Whether a page name is the design system page (its number and words, however typed). +pub fn is_page(name: &str) -> bool { + let spaced: String = name.to_lowercase().chars().map(|c| if c.is_alphanumeric() { c } else { ' ' }).collect(); + spaced.split_whitespace().collect::>().join(" ") == "00 design system" +} + +/// The design system page (id) and the guidelines text layer on it (id, text), if there. +/// The design system page's id, and its guidelines text layer (id, text), each if there. +type Found = (Option, Option<(u64, String)>); + +fn find(b: &mut dyn figcraft_mcp::Backend, doc: Option) -> Result { + let pages = exec(b, doc, "page.list", json!({}))?; + let Some(page) = pages + .as_array() + .into_iter() + .flatten() + .find(|p| p.get("name").and_then(Value::as_str).is_some_and(is_page)) + .and_then(|p| p.get("id").and_then(Value::as_u64)) + else { + return Ok((None, None)); + }; + let found = exec(b, doc, "node.find", json!({"name": GUIDELINES, "root": page, "type": "text"}))?; + let ids: Vec = found.get("ids").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_u64).collect(); + for id in ids { + let node = exec(b, doc, "node.get", json!({"id": id}))?; + if let Some(text) = node.get("characters").or_else(|| node.get("text")).and_then(Value::as_str) { + return Ok((Some(page), Some((id, text.to_string())))); + } + } + Ok((Some(page), None)) +} + +/// Answer a `design_system` call through the window (or file) the agent works in: the text for +/// the model, and whether it worked. +pub fn call(b: &mut dyn figcraft_mcp::Backend, args: &Value) -> (String, bool) { + match run(b, args) { + Ok(text) => (text, true), + Err(e) => (format!("design_system failed: {e}"), false), + } +} + +fn run(b: &mut dyn figcraft_mcp::Backend, args: &Value) -> Result { + let doc = front_document(b); + let (page, guidelines) = find(b, doc)?; + let vars = exec(b, doc, "variable.list", json!({}))?; + let styles = exec(b, doc, "style.list", json!({}))?; + let existing = Existing::from_lists(&vars, &styles); + let collections: Vec<&String> = existing.collections.keys().collect(); + let Some(fields) = args.get("spec").or_else(|| args.get("brief")).and_then(Value::as_object) else { + return Ok(match page { + None => format!( + "This file has no '{PAGE}' page yet. Variable collections: {}.", + if collections.is_empty() { "none".to_string() } else { format!("{collections:?}") } + ), + Some(id) => format!( + "'{PAGE}' is page {id}; read its frames with design_context. Variable collections: {collections:?}.\n{}", + guidelines.map(|(_, t)| t).unwrap_or_else(|| "It has no 'Design guidelines' text yet.".into()) + ), + }); + }; + let mut merged = serde_json::to_value(Brief::default()).map_err(|e| e.to_string())?; + if let Some(obj) = merged.as_object_mut() { + for (k, v) in fields { + let v = match v { + Value::String(s) + if matches!(k.as_str(), "platform" | "neutral" | "modes" | "scale" | "radius" | "elevation" | "iconStyle" | "contrast") => + { + Value::String(s.to_lowercase()) + } + other => other.clone(), + }; + obj.insert(k.clone(), v); + } + } + let spec: Brief = serde_json::from_value(merged).map_err(|e| format!("the spec has a field with a wrong value: {e}"))?; + // The page (first in the file), the tokens, styles and review settings, and the guidelines + // text, in one batch: one undo step, and nothing changed when any part fails. + let text = spec.guidelines(); + let tokens = spec.steps(&existing); + let made = tokens.iter().filter(|s| matches!(s["command"].as_str(), Some("variable.create" | "style.create"))).count(); + let mut steps = Vec::with_capacity(tokens.len() + 3); + let page_ref = match page { + Some(id) => json!(id), + None => { + steps.push(json!({"command": "page.add", "params": {"name": PAGE}, "as": "dsPage"})); + json!({"$ref": "dsPage"}) + } + }; + steps.push(json!({"command": "page.move", "params": {"id": page_ref, "index": 0}})); + steps.extend(tokens); + steps.push(match guidelines { + Some((id, _)) => json!({"command": "node.set", "params": {"ids": [id], "props": {"characters": text}}}), + None => json!({"command": "node.create", "params": { + "type": "text", "parent": page_ref, "name": GUIDELINES, "x": -560, "y": 0, "characters": text, "select": false, + "props": {"width": 480, "textAutoResize": "height", "fontSize": 14, "lineHeight": 22}}}), + }); + exec(b, doc, "command.batch", json!({"label": "Design system", "commands": steps}))?; + let (page, _) = find(b, doc)?; + let page = page.ok_or("the design system page is missing after it was made")?; + Ok(format!( + "'{PAGE}' is page {page} (first in the file), with {made} new variables and styles: {PRIMITIVES} (colour ramps 50-900), {THEME} (roles, modes {}), {SIZES} (Space/…, Radius/S|M|L|Full, Border/…, Icon/…); text styles Display, Heading 1-3, Body large, Body, Body small, Caption, Label, Code; shadow styles Shadow/S, M, L; design.audit settings from the spec; and a 'Design guidelines' text. Lay out the foundations and base components on that page next (the 'Design system setup' skill).\n{text}", + spec.modes.names().join(", ") + )) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_brief_reads_back_and_an_old_one_takes_the_defaults() { + let b = Brief { product: "Klinik".into(), icon_set: "Phosphor".into(), ..Brief::default() }; + assert_eq!(Brief::from_json(&b.to_json()), Some(b)); + let old = Brief::from_json(r#"{"product": "X"}"#).expect("a partial brief"); + assert_eq!(old.product, "X"); + assert_eq!(old.spacing, Brief::default().spacing); + } + + #[test] + fn a_ramp_goes_from_pale_to_deep_in_the_colours_hue() { + let r = ramp("#2563EB").expect("a colour"); + assert_eq!(r.len(), STEPS.len()); + let lum: Vec = r.iter().filter_map(|h| Color::from_hex(h)).map(Color::luminance).collect(); + assert!(lum.windows(2).all(|w| w[0] > w[1]), "each step darker: {r:?}"); + assert!(ramp("not a colour").is_none()); + } + + #[test] + fn running_again_updates_instead_of_making_copies() { + let b = Brief::default(); + let fresh = b.steps(&Existing::default()); + let creates = |steps: &[Value], cmd: &str| steps.iter().filter(|s| s["command"] == cmd).count(); + assert!(creates(&fresh, "variable.createCollection") == 3); + assert!(creates(&fresh, "variable.create") > 40); + assert!(creates(&fresh, "style.create") >= 13); + + let mut existing = Existing::default(); + for s in &fresh { + let p = &s["params"]; + match s["command"].as_str() { + Some("variable.createCollection") => { + let modes = p["modes"].as_array().into_iter().flatten().filter_map(Value::as_str).map(str::to_string).collect(); + existing.collections.insert(p["name"].as_str().unwrap_or_default().to_string(), modes); + } + Some("variable.create") => { + let name: String = p["name"].as_str().unwrap_or_default().into(); + existing.variables.insert((p["collection"].as_str().unwrap_or_default().into(), name.clone()), name); + } + Some("style.create") => { + existing.styles.insert(p["name"].as_str().unwrap_or_default().into()); + } + _ => {} + } + } + let again = b.steps(&existing); + assert_eq!(creates(&again, "variable.createCollection") + creates(&again, "variable.create") + creates(&again, "style.create"), 0); + assert!(creates(&again, "variable.set") > 0 && creates(&again, "style.update") > 0); + } + + #[test] + fn the_prompt_names_the_icon_set_and_its_style() { + let b = Brief { icon_set: "Phosphor".into(), icon_style: IconStyle::Duotone, ..Brief::default() }; + let p = b.guidelines(); + assert!(p.contains("Phosphor") && p.contains("Duotone")); + assert!(p.contains("never emoji")); + } + + #[test] + fn only_the_design_system_page_itself_counts() { + assert!(is_page("00 · Design System") && is_page("00 - design system") && is_page("00_Design_System")); + assert!(!is_page("00 · Design System exploration")); + assert!(!is_page("Design System")); + } + + #[test] + fn an_update_names_the_variable_of_its_own_collection() { + let vars = json!({ + "collections": [{"id": "c1", "name": "Other", "modes": [{"name": "Default"}]}, {"id": "c2", "name": SIZES, "modes": [{"name": "Default"}]}], + "variables": [{"id": "v1", "collection": "c1", "name": "Radius/S"}, {"id": "v2", "collection": "c2", "name": "Radius/S"}], + }); + let existing = Existing::from_lists(&vars, &json!([])); + let steps = Brief::default().steps(&existing); + let set = steps.iter().find(|s| s["command"] == "variable.set" && s["params"]["variable"].as_str().is_some_and(|v| v.starts_with('v'))); + assert_eq!(set.map(|s| s["params"]["variable"].clone()), Some(json!("v2"))); + } + + /// The engine as the agent's tools see it, without a window. + struct Engine(figcraft_engine::Session); + + impl figcraft_mcp::Backend for Engine { + fn call(&mut self, method: &str, params: Value) -> Result { + match method { + "engine.execute" => { + let cmd = params["command"].as_str().unwrap_or_default().to_string(); + self.0.execute(&cmd, ¶ms["params"]).map_err(|e| e.to_string()) + } + other => Err(format!("not here: {other}")), + } + } + + fn has_ui(&self) -> bool { + false + } + + fn describe(&self) -> String { + "test".into() + } + } + + #[test] + fn the_agent_makes_the_design_system_page_with_one_call_and_reads_it_back() { + let mut engine = Engine(figcraft_engine::Session::new()); + let (text, ok) = call(&mut engine, &json!({})); + assert!(ok && text.contains("no '00 · Design System' page"), "{text}"); + + let spec = json!({"spec": {"product": "Klinik", "primary": "#0F766E", "radius": "Round", "iconSet": "Phosphor", "spacing": 8}}); + let (text, ok) = call(&mut engine, &spec); + assert!(ok, "{text}"); + let pages = engine.0.execute("page.list", &json!({})).expect("pages"); + assert_eq!(pages[0]["name"], PAGE, "first in the file: {pages}"); + + // A later conversation finds the page and the guidelines on it. + let (text, ok) = call(&mut engine, &json!({})); + assert!(ok && text.contains("Phosphor") && text.contains("Klinik"), "{text}"); + let vars = engine.0.execute("variable.list", &json!({})).expect("variables"); + assert!(vars["collections"].as_array().into_iter().flatten().any(|c| c["name"] == THEME)); + let audit = engine.0.execute("design.audit", &json!({"scope": "page"})).expect("an audit"); + assert_eq!(audit["grid"], json!(8.0), "the spacing step is the review grid"); + + // One call is one undo step. + let undo_to = engine.0.undo_depth().0; + let (_, ok) = call(&mut engine, &json!({"spec": {"iconSet": "Feather"}})); + assert!(ok); + assert_eq!(engine.0.undo_depth().0, undo_to + 1, "one undo step"); + + // Again: the same page and guidelines, updated, not copied. + let (_, ok) = call(&mut engine, &json!({"spec": {"iconSet": "Lucide"}})); + assert!(ok); + let pages = engine.0.execute("page.list", &json!({})).expect("pages"); + assert_eq!(pages.as_array().into_iter().flatten().filter(|p| p["name"] == PAGE).count(), 1); + let (text, _) = call(&mut engine, &json!({})); + assert!(text.contains("Lucide")); + let found = engine.0.execute("node.find", &json!({"name": GUIDELINES, "root": pages[0]["id"]})).expect("find"); + assert_eq!(found["total"], json!(1)); + } +} diff --git a/crates/agent/src/cli.rs b/crates/agent/src/cli.rs new file mode 100644 index 000000000..8ba330c38 --- /dev/null +++ b/crates/agent/src/cli.rs @@ -0,0 +1,667 @@ +//! Connections through an installed command-line agent: Claude Code, Codex or OpenCode. +//! +//! The person signs in to those programs with their own plan; FigCraft never sees that login. A +//! turn runs the program once, non-interactively, with FigCraft's tools attached over MCP +//! ([`crate::mcp_http`]) and its own built-in tools left out, and reads its JSON event stream. The +//! program keeps the conversation; the next turn resumes it by the session id it reported. + +use std::io::{BufRead, BufReader, Read}; +use std::path::{Path, PathBuf}; +use std::process::{Command, Stdio}; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::mpsc::channel; +use std::time::Duration; + +use serde_json::{Value, json}; + +use crate::Usage; +use crate::config::ApiKind; + +/// Whether a command-line agent can be used. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Status { + /// Not found on this computer. + Missing, + /// Installed but not signed in. + SignedOut(PathBuf), + /// Installed and signed in (or the program could not tell; the first turn will). + Ready(PathBuf), +} + +/// Find the program: the `PATH` the app was started with, then the folders installers use (an app +/// opened from the Finder gets a short `PATH`). +pub fn locate(kind: ApiKind) -> Option { + let name = kind.program()?; + let exe = if cfg!(windows) { format!("{name}.exe") } else { name.to_string() }; + let mut dirs: Vec = std::env::var_os("PATH").map(|p| std::env::split_paths(&p).collect()).unwrap_or_default(); + if let Some(home) = home() { + for d in [".local/bin", ".opencode/bin", ".bun/bin", ".npm-global/bin", ".claude/local", ".cargo/bin", "bin"] { + dirs.push(home.join(d)); + } + } + for d in ["/opt/homebrew/bin", "/usr/local/bin", "/usr/bin"] { + dirs.push(PathBuf::from(d)); + } + dirs.into_iter().map(|d| d.join(&exe)).find(|p| p.is_file()) +} + +fn home() -> Option { + std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE")).map(PathBuf::from) +} + +/// Whether the program is there and signed in. Runs it briefly, so call it off the UI thread. +pub fn status(kind: ApiKind) -> Status { + let Some(path) = locate(kind) else { return Status::Missing }; + let signed_in = match kind { + ApiKind::ClaudeCode => output(&path, &["auth", "status"]).map(|o| { + serde_json::from_str::(&o).ok().and_then(|v| v.get("loggedIn").and_then(Value::as_bool)).unwrap_or(!o.contains("Not logged in")) + }), + ApiKind::Codex => output(&path, &["login", "status"]).map(|o| !o.to_ascii_lowercase().contains("not logged in")), + ApiKind::OpenCode => output(&path, &["auth", "list"]).map(|o| o.lines().any(|l| l.contains("stored") || l.contains("environment"))), + ApiKind::OpenAiCompletions | ApiKind::AnthropicMessages => None, + }; + match signed_in { + Some(false) => Status::SignedOut(path), + _ => Status::Ready(path), + } +} + +/// The models the program offers, when it can list them (OpenCode); `None` keeps the preset's. +pub fn models(kind: ApiKind) -> Option> { + if kind != ApiKind::OpenCode { + return None; + } + let path = locate(kind)?; + let out = output(&path, &["models"])?; + let ids: Vec = out.lines().map(str::trim).filter(|l| l.contains('/') && !l.contains(' ')).map(str::to_string).collect(); + if ids.is_empty() { None } else { Some(ids) } +} + +/// Run `program args`, giving up after 20 seconds; its standard output, or `None`. +fn output(program: &Path, args: &[&str]) -> Option { + let mut child = Command::new(program).args(args).stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped()).spawn().ok()?; + let mut stdout = child.stdout.take()?; + let mut stderr = child.stderr.take()?; + let (tx, rx) = channel(); + std::thread::spawn(move || { + let mut s = String::new(); + let _ = stdout.read_to_string(&mut s); + let mut e = String::new(); + let _ = stderr.read_to_string(&mut e); + let _ = tx.send(format!("{s}\n{e}")); + }); + match rx.recv_timeout(Duration::from_secs(20)) { + Ok(s) => { + let _ = child.wait(); + Some(s) + } + Err(_) => { + let _ = child.kill(); + let _ = child.wait(); + None + } + } +} + +/// Everything one turn needs to start the program. +pub struct Turn<'a> { + pub kind: ApiKind, + pub program: &'a Path, + pub model: &'a str, + /// The conversation to continue, from the last turn. + pub session: Option<&'a str>, + pub prompt: &'a str, + /// FigCraft's rules for the agent, added to the program's own. + pub system: &'a str, + pub mcp_url: &'a str, + pub mcp_token: &'a str, + /// The folder the program runs in (it keeps nothing of the person's there). + pub workdir: &'a Path, + /// Images the person attached to this request. + pub images: &'a [crate::neutral::Image], +} + +/// The token's environment variable for Codex, which reads a bearer token from one. +const TOKEN_ENV: &str = "FIGCRAFT_MCP_TOKEN"; + +/// The command for one turn. `files` are the attached images written to disk, for the programs +/// that take images as files (Codex, OpenCode); Claude Code reads them from its input instead +/// ([`stdin_message`]). +pub fn command(turn: &Turn<'_>, files: &[PathBuf]) -> Command { + let mut cmd = Command::new(turn.program); + let piped = turn.kind == ApiKind::ClaudeCode && !turn.images.is_empty(); + cmd.current_dir(turn.workdir).stdin(if piped { Stdio::piped() } else { Stdio::null() }).stdout(Stdio::piped()).stderr(Stdio::piped()); + match turn.kind { + ApiKind::ClaudeCode => { + let config = json!({"mcpServers": {"figcraft": { + "type": "http", + "url": turn.mcp_url, + "headers": {"Authorization": format!("Bearer {}", turn.mcp_token)}, + }}}); + cmd.args(["-p", "--output-format", "stream-json", "--verbose", "--include-partial-messages"]); + // Only FigCraft's tools: no shell, no file edits, no other MCP servers. + cmd.args(["--strict-mcp-config", "--mcp-config"]).arg(config.to_string()); + cmd.args(["--tools", "", "--allowedTools", "mcp__figcraft", "--disable-slash-commands"]); + cmd.arg("--append-system-prompt").arg(turn.system); + if !turn.model.trim().is_empty() { + cmd.arg("--model").arg(turn.model.trim()); + } + if let Some(s) = turn.session { + cmd.arg("--resume").arg(s); + } + if piped { + // The request, images included, arrives as one message on standard input. + cmd.args(["--input-format", "stream-json"]); + } else { + cmd.arg("--").arg(turn.prompt); + } + } + ApiKind::Codex => { + cmd.env(TOKEN_ENV, turn.mcp_token); + // `exec`'s own options come before `resume`: that subcommand doesn't take them, and a + // resumed turn must keep the read-only sandbox. + cmd.arg("exec"); + cmd.args(["--json", "--skip-git-repo-check", "--sandbox", "read-only"]); + cmd.arg("-c").arg(format!("mcp_servers.figcraft.url={}", toml_string(turn.mcp_url))); + cmd.arg("-c").arg(format!("mcp_servers.figcraft.bearer_token_env_var={}", toml_string(TOKEN_ENV))); + if !turn.model.trim().is_empty() { + cmd.arg("--model").arg(turn.model.trim()); + } + if let Some(s) = turn.session { + cmd.args(["resume", s]); + } + for f in files { + cmd.arg("--image").arg(f); + } + // Codex has no flag for added instructions: the first turn carries them. + let prompt = if turn.session.is_none() { format!("{}\n\n---\n\n{}", turn.system, turn.prompt) } else { turn.prompt.to_string() }; + cmd.arg("--").arg(prompt); + } + ApiKind::OpenCode => { + let config = json!({ + "$schema": "https://opencode.ai/config.json", + "mcp": {"figcraft": { + "type": "remote", + "url": turn.mcp_url, + "enabled": true, + "headers": {"Authorization": format!("Bearer {}", turn.mcp_token)}, + }}, + "agent": {"figcraft": { + "description": "Designs in the open FigCraft window", + "mode": "primary", + "prompt": turn.system, + "tools": {"*": false, "figcraft_*": true}, + }}, + }); + cmd.env("OPENCODE_CONFIG_CONTENT", config.to_string()); + cmd.args(["run", "--format", "json", "--agent", "figcraft"]); + if !turn.model.trim().is_empty() { + cmd.arg("--model").arg(turn.model.trim()); + } + if let Some(s) = turn.session { + cmd.arg("--session").arg(s); + } + for f in files { + cmd.arg("--file").arg(f); + } + cmd.arg("--").arg(turn.prompt); + } + ApiKind::OpenAiCompletions | ApiKind::AnthropicMessages => {} + } + cmd +} + +/// Claude Code's input when the request carries images: one user message, text and images. +pub fn stdin_message(turn: &Turn<'_>) -> String { + let mut content = vec![json!({"type": "text", "text": turn.prompt})]; + for i in turn.images { + content.push(json!({"type": "image", "source": {"type": "base64", "media_type": i.mime, "data": i.data}})); + } + json!({"type": "user", "message": {"role": "user", "content": content}}).to_string() +} + +/// A folder of copies made for one run, removed when it is dropped (after the program has exited). +struct Staged(Option); + +impl Drop for Staged { + fn drop(&mut self) { + if let Some(dir) = self.0.take() { + let _ = std::fs::remove_dir_all(dir); + } + } +} + +/// Write the attached images where the program can read them, in a folder of this run's own that +/// goes away with `staged`; their paths, in order. +fn write_images(turn: &Turn<'_>, staged: &mut Staged) -> Result, String> { + if turn.images.is_empty() || turn.kind == ApiKind::ClaudeCode { + return Ok(Vec::new()); + } + use base64::Engine as _; + let stamp = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_nanos()).unwrap_or(0); + let dir = turn.workdir.join("attachments").join(format!("{stamp}-{}", std::process::id())); + std::fs::create_dir_all(&dir).map_err(|e| format!("can't make {}: {e}", dir.display()))?; + staged.0 = Some(dir.clone()); + let mut out = Vec::new(); + for (n, i) in turn.images.iter().enumerate() { + let ext = match i.mime.as_str() { + "image/jpeg" => "jpg", + "image/webp" => "webp", + "image/gif" => "gif", + _ => "png", + }; + let bytes = base64::engine::general_purpose::STANDARD.decode(i.data.as_bytes()).map_err(|e| format!("an attached image is damaged: {e}"))?; + let path = dir.join(format!("{n}.{ext}")); + std::fs::write(&path, bytes).map_err(|e| format!("can't write {}: {e}", path.display()))?; + out.push(path); + } + Ok(out) +} + +fn toml_string(s: &str) -> String { + format!("\"{}\"", s.replace('\\', "\\\\").replace('"', "\\\"")) +} + +/// One thing read off the program's event stream. +#[derive(Clone, Debug, PartialEq)] +pub enum Parsed { + /// The conversation id to resume next time. + Session(String), + Text(String), + /// Tokens this event used (added to the turn's total). + Usage(Usage), + Error(String), +} + +/// Reads one program's JSON lines into [`Parsed`] events. +pub struct Parser { + kind: ApiKind, + /// Claude Code sends text twice (deltas, then the whole message); once deltas came, the whole + /// message is skipped. + deltas: bool, + /// Whether any text was given yet, so a later block starts a new paragraph. + wrote: bool, +} + +impl Parser { + pub fn new(kind: ApiKind) -> Self { + Self { kind, deltas: false, wrote: false } + } + + fn text(&mut self, out: &mut Vec, t: &str, new_block: bool) { + if t.is_empty() { + return; + } + if new_block && self.wrote { + out.push(Parsed::Text("\n\n".into())); + } + self.wrote = true; + out.push(Parsed::Text(t.to_string())); + } + + pub fn line(&mut self, line: &str) -> Vec { + let mut out = Vec::new(); + let Ok(v) = serde_json::from_str::(line.trim()) else { return out }; + let ty = v.get("type").and_then(Value::as_str).unwrap_or(""); + let s = |p: &str| v.pointer(p).and_then(Value::as_str).unwrap_or("").to_string(); + let n = |x: &Value, p: &str| x.pointer(p).and_then(Value::as_u64).unwrap_or(0); + match self.kind { + ApiKind::ClaudeCode => match ty { + "system" if s("/subtype") == "init" => out.push(Parsed::Session(s("/session_id"))), + "stream_event" => { + let e = &v["event"]; + match e.get("type").and_then(Value::as_str) { + Some("content_block_start") if e.pointer("/content_block/type").and_then(Value::as_str) == Some("text") => { + self.deltas = true; + let t = e.pointer("/content_block/text").and_then(Value::as_str).unwrap_or(""); + if self.wrote { + out.push(Parsed::Text("\n\n".into())); + } + self.wrote = true; + if !t.is_empty() { + out.push(Parsed::Text(t.to_string())); + } + } + Some("content_block_delta") if e.pointer("/delta/type").and_then(Value::as_str) == Some("text_delta") => { + self.deltas = true; + self.wrote = true; + let t = e.pointer("/delta/text").and_then(Value::as_str).unwrap_or(""); + if !t.is_empty() { + out.push(Parsed::Text(t.to_string())); + } + } + _ => {} + } + } + "assistant" if !self.deltas => { + for block in v.pointer("/message/content").and_then(Value::as_array).into_iter().flatten() { + if block.get("type").and_then(Value::as_str) == Some("text") { + let t = block.get("text").and_then(Value::as_str).unwrap_or("").to_string(); + self.text(&mut out, &t, true); + } + } + } + "result" => { + if !s("/session_id").is_empty() { + out.push(Parsed::Session(s("/session_id"))); + } + let u = &v["usage"]; + let input = n(u, "/input_tokens") + n(u, "/cache_creation_input_tokens") + n(u, "/cache_read_input_tokens"); + out.push(Parsed::Usage(Usage { input, output: n(u, "/output_tokens") })); + if v.get("is_error").and_then(Value::as_bool).unwrap_or(false) { + let why = if s("/result").is_empty() { s("/subtype") } else { s("/result") }; + out.push(Parsed::Error(why)); + } + } + _ => {} + }, + ApiKind::OpenCode => { + if let Some(id) = v.get("sessionID").and_then(Value::as_str) { + out.push(Parsed::Session(id.to_string())); + } + match ty { + "text" => { + let t = s("/part/text"); + self.text(&mut out, &t, true); + } + "step_finish" => { + let tk = &v["part"]["tokens"]; + let input = n(tk, "/input") + n(tk, "/cache/read") + n(tk, "/cache/write"); + out.push(Parsed::Usage(Usage { input, output: n(tk, "/output") + n(tk, "/reasoning") })); + } + "error" => { + let why = [s("/error/data/message"), s("/error/message"), s("/message")].into_iter().find(|m| !m.is_empty()); + out.push(Parsed::Error(why.unwrap_or_else(|| line.chars().take(300).collect()))); + } + _ => {} + } + } + ApiKind::Codex => match ty { + "thread.started" => out.push(Parsed::Session(s("/thread_id"))), + "item.completed" if s("/item/type") == "agent_message" => { + let t = s("/item/text"); + self.text(&mut out, &t, true); + } + "turn.completed" => { + let u = &v["usage"]; + out.push(Parsed::Usage(Usage { input: n(u, "/input_tokens"), output: n(u, "/output_tokens") })); + } + "turn.failed" => out.push(Parsed::Error(s("/error/message"))), + "error" => out.push(Parsed::Error(s("/message"))), + _ => {} + }, + ApiKind::OpenAiCompletions | ApiKind::AnthropicMessages => {} + } + out + } +} + +/// What a finished run reports. +pub struct Outcome { + pub session: Option, + pub usage: Usage, + pub stopped: bool, + /// The error to show, when the run failed. + pub error: Option, +} + +/// Run one turn to the end, streaming text through `on_text`; Stop kills the program. +pub fn run(turn: &Turn<'_>, on_text: &mut dyn FnMut(&str), cancel: &Arc) -> Outcome { + let mut outcome = Outcome { session: turn.session.map(str::to_string), usage: Usage::default(), stopped: false, error: None }; + let _ = std::fs::create_dir_all(turn.workdir); + let name = turn.kind.label(); + // Declared before the child, so the copies outlive it: removed after it has exited. + let mut staged = Staged(None); + let files = match write_images(turn, &mut staged) { + Ok(f) => f, + Err(e) => { + outcome.error = Some(e); + return outcome; + } + }; + let mut child = match command(turn, &files).spawn() { + Ok(c) => c, + Err(e) => { + outcome.error = Some(format!("can't start {name} ({}): {e}", turn.program.display())); + return outcome; + } + }; + if let Some(mut stdin) = child.stdin.take() { + use std::io::Write as _; + let message = stdin_message(turn); + // Closing standard input after the message ends the request. + std::thread::spawn(move || { + let _ = stdin.write_all(message.as_bytes()); + let _ = stdin.write_all(b"\n"); + }); + } + let (tx, rx) = channel::(); + if let Some(stdout) = child.stdout.take() { + std::thread::spawn(move || { + for line in BufReader::new(stdout).lines() { + let Ok(line) = line else { break }; + if tx.send(line).is_err() { + break; + } + } + }); + } + let (etx, erx) = channel::(); + if let Some(mut stderr) = child.stderr.take() { + std::thread::spawn(move || { + let mut s = String::new(); + let _ = stderr.read_to_string(&mut s); + let _ = etx.send(s); + }); + } + let mut parser = Parser::new(turn.kind); + let mut failed: Vec = Vec::new(); + loop { + if cancel.load(Ordering::Relaxed) { + let _ = child.kill(); + let _ = child.wait(); + outcome.stopped = true; + return outcome; + } + match rx.recv_timeout(Duration::from_millis(100)) { + Ok(line) => { + for p in parser.line(&line) { + match p { + Parsed::Session(s) if !s.is_empty() => outcome.session = Some(s), + Parsed::Session(_) => {} + Parsed::Text(t) => on_text(&t), + Parsed::Usage(u) => { + outcome.usage.input = outcome.usage.input.saturating_add(u.input); + outcome.usage.output = outcome.usage.output.saturating_add(u.output); + } + Parsed::Error(e) if !e.is_empty() => failed.push(e), + Parsed::Error(_) => {} + } + } + } + Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {} + Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => break, + } + } + // The program closed its output but may still be running: Stop keeps working until it exits. + let status = loop { + if cancel.load(Ordering::Relaxed) { + let _ = child.kill(); + let _ = child.wait(); + outcome.stopped = true; + return outcome; + } + match child.try_wait() { + Ok(Some(s)) => break Ok(s), + Ok(None) => std::thread::sleep(Duration::from_millis(100)), + Err(e) => break Err(e), + } + }; + let stderr = erx.recv_timeout(Duration::from_secs(2)).unwrap_or_default(); + if !failed.is_empty() { + outcome.error = Some(format!("{name}: {}", failed.join("; "))); + } else if let Ok(s) = status + && !s.success() + { + let tail: String = stderr.lines().rev().find(|l| !l.trim().is_empty()).unwrap_or("").chars().take(400).collect(); + outcome.error = Some(if tail.is_empty() { format!("{name} exited with {s}") } else { format!("{name}: {tail}") }); + } + outcome +} + +#[cfg(test)] +mod tests { + use super::*; + + fn texts(p: &[Parsed]) -> String { + p.iter() + .filter_map(|x| match x { + Parsed::Text(t) => Some(t.as_str()), + _ => None, + }) + .collect() + } + + #[test] + fn claude_code_text_arrives_once_and_blocks_are_paragraphs() { + let mut p = Parser::new(ApiKind::ClaudeCode); + let mut all = Vec::new(); + for line in [ + r#"{"type":"system","subtype":"init","session_id":"s-1"}"#, + r#"{"type":"stream_event","event":{"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}}"#, + r#"{"type":"stream_event","event":{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"Making "}}}"#, + r#"{"type":"stream_event","event":{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"a card."}}}"#, + r#"{"type":"assistant","message":{"content":[{"type":"text","text":"Making a card."}]}}"#, + r#"{"type":"stream_event","event":{"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}}"#, + r#"{"type":"stream_event","event":{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"Done."}}}"#, + r#"{"type":"result","subtype":"success","is_error":false,"session_id":"s-1","usage":{"input_tokens":3,"cache_read_input_tokens":10,"output_tokens":5}}"#, + ] { + all.extend(p.line(line)); + } + assert_eq!(texts(&all), "Making a card.\n\nDone."); + assert!(all.contains(&Parsed::Session("s-1".into()))); + assert!(all.iter().any(|x| matches!(x, Parsed::Usage(u) if u.input > u.output))); + assert!(!all.iter().any(|x| matches!(x, Parsed::Error(_)))); + } + + #[test] + fn a_failed_claude_code_run_says_why() { + let mut p = Parser::new(ApiKind::ClaudeCode); + let out = p.line(r#"{"type":"result","subtype":"error","is_error":true,"result":"Not logged in · Please run /login","usage":{}}"#); + assert!(out.iter().any(|x| matches!(x, Parsed::Error(e) if e.contains("login")))); + } + + #[test] + fn opencode_parts_become_text_usage_and_a_session() { + let mut p = Parser::new(ApiKind::OpenCode); + let mut all = Vec::new(); + for line in [ + r#"{"type":"step_start","sessionID":"ses_1","part":{"type":"step-start"}}"#, + r#"{"type":"text","sessionID":"ses_1","part":{"type":"text","text":"First."}}"#, + r#"{"type":"text","sessionID":"ses_1","part":{"type":"text","text":"Second."}}"#, + r#"{"type":"step_finish","sessionID":"ses_1","part":{"tokens":{"input":70,"output":3,"reasoning":2,"cache":{"read":5,"write":0}}}}"#, + "not json", + ] { + all.extend(p.line(line)); + } + assert_eq!(texts(&all), "First.\n\nSecond."); + assert!(all.contains(&Parsed::Session("ses_1".into()))); + assert!(all.iter().any(|x| matches!(x, Parsed::Usage(u) if u.input == 75 && u.output == 5))); + } + + #[test] + fn codex_messages_and_failures_are_read() { + let mut p = Parser::new(ApiKind::Codex); + let mut all = Vec::new(); + for line in [ + r#"{"type":"thread.started","thread_id":"th-9"}"#, + r#"{"type":"item.completed","item":{"id":"i0","type":"reasoning","text":"thinking"}}"#, + r#"{"type":"item.completed","item":{"id":"i1","type":"agent_message","text":"Built it."}}"#, + r#"{"type":"turn.completed","usage":{"input_tokens":20,"output_tokens":4}}"#, + r#"{"type":"turn.failed","error":{"message":"usage limit reached"}}"#, + ] { + all.extend(p.line(line)); + } + assert_eq!(texts(&all), "Built it.", "reasoning is not the answer"); + assert!(all.contains(&Parsed::Session("th-9".into()))); + assert!(all.iter().any(|x| matches!(x, Parsed::Error(e) if e.contains("limit")))); + } + + #[test] + fn claude_code_gets_only_figcraft_tools() { + let dir = std::env::temp_dir(); + let turn = Turn { + kind: ApiKind::ClaudeCode, + program: Path::new("claude"), + model: "", + session: Some("s-1"), + prompt: "--dangerous-looking prompt", + system: "rules", + mcp_url: "http://127.0.0.1:1/mcp", + mcp_token: "t", + workdir: &dir, + images: &[], + }; + let cmd = command(&turn, &[]); + let args: Vec = cmd.get_args().map(|a| a.to_string_lossy().into_owned()).collect(); + let at = |flag: &str| args.iter().position(|a| a == flag).map(|i| args[i + 1].clone()); + assert_eq!(at("--tools").as_deref(), Some(""), "no built-in tools"); + assert_eq!(at("--allowedTools").as_deref(), Some("mcp__figcraft")); + assert!(args.contains(&"--strict-mcp-config".to_string()), "no other MCP servers"); + assert_eq!(at("--resume").as_deref(), Some("s-1")); + assert_eq!(at("--").as_deref(), Some("--dangerous-looking prompt"), "the prompt is never read as a flag"); + assert!(!args.iter().any(|a| a == "--model"), "the default model"); + } + + #[test] + fn a_resumed_codex_turn_keeps_the_read_only_sandbox() { + let dir = std::env::temp_dir(); + let turn = Turn { + kind: ApiKind::Codex, + program: Path::new("codex"), + model: "", + session: Some("th-1"), + prompt: "again", + system: "rules", + mcp_url: "http://127.0.0.1:1/mcp", + mcp_token: "t", + workdir: &dir, + images: &[], + }; + let args: Vec = command(&turn, &[]).get_args().map(|a| a.to_string_lossy().into_owned()).collect(); + let at = |a: &str| args.iter().position(|x| x == a); + let resume = at("resume").expect("resumes"); + assert!(at("--sandbox").is_some_and(|i| i < resume && args[i + 1] == "read-only"), "{args:?}"); + assert!(at("--json").is_some_and(|i| i < resume)); + } + + #[test] + fn attached_images_reach_each_program_its_own_way() { + let dir = std::env::temp_dir(); + let images = [crate::neutral::Image { mime: "image/png".into(), data: "AAAA".into() }]; + let mut turn = Turn { + kind: ApiKind::ClaudeCode, + program: Path::new("claude"), + model: "", + session: None, + prompt: "like this", + system: "rules", + mcp_url: "http://127.0.0.1:1/mcp", + mcp_token: "t", + workdir: &dir, + images: &images, + }; + let args = |c: &Command| c.get_args().map(|a| a.to_string_lossy().into_owned()).collect::>(); + let claude = args(&command(&turn, &[])); + assert!(claude.windows(2).any(|w| w == ["--input-format", "stream-json"]), "Claude Code reads the request from its input"); + assert!(!claude.contains(&"like this".to_string()), "the prompt is in the message, not an argument"); + let message: Value = serde_json::from_str(&stdin_message(&turn)).expect("json"); + assert_eq!(message.pointer("/message/content/1/type").and_then(Value::as_str), Some("image")); + turn.kind = ApiKind::OpenCode; + let file = PathBuf::from("/tmp/a.png"); + assert!(args(&command(&turn, std::slice::from_ref(&file))).windows(2).any(|w| w == ["--file", "/tmp/a.png"])); + turn.kind = ApiKind::Codex; + assert!(args(&command(&turn, std::slice::from_ref(&file))).windows(2).any(|w| w == ["--image", "/tmp/a.png"])); + } +} diff --git a/crates/agent/src/config.rs b/crates/agent/src/config.rs new file mode 100644 index 000000000..aa2225949 --- /dev/null +++ b/crates/agent/src/config.rs @@ -0,0 +1,512 @@ +//! The agent's settings: connected providers, the chosen model and how much the agent may do on +//! its own. Stored in `agents.json` beside the app's preferences, readable only by the user (it +//! holds API keys). + +use std::path::Path; + +use serde::{Deserialize, Serialize}; + +/// Which wire dialect a provider speaks. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum ApiKind { + #[default] + OpenAiCompletions, + AnthropicMessages, + /// The person's own Claude Code install (`claude`), signed in with their Claude plan. + ClaudeCode, + /// The person's own Codex install (`codex`), signed in with their ChatGPT plan. + Codex, + /// The person's own OpenCode install (`opencode`), with the providers it is signed in to. + OpenCode, +} + +impl ApiKind { + pub fn label(self) -> &'static str { + match self { + ApiKind::OpenAiCompletions => "OpenAI Completions", + ApiKind::AnthropicMessages => "Anthropic Messages", + ApiKind::ClaudeCode => "Claude Code", + ApiKind::Codex => "Codex", + ApiKind::OpenCode => "OpenCode", + } + } + + /// Whether requests go through an installed command-line agent rather than an HTTP endpoint. + pub fn is_cli(self) -> bool { + matches!(self, ApiKind::ClaudeCode | ApiKind::Codex | ApiKind::OpenCode) + } + + /// The program a command-line connection runs. + pub fn program(self) -> Option<&'static str> { + match self { + ApiKind::ClaudeCode => Some("claude"), + ApiKind::Codex => Some("codex"), + ApiKind::OpenCode => Some("opencode"), + ApiKind::OpenAiCompletions | ApiKind::AnthropicMessages => None, + } + } +} + +/// How much a reasoning model may think before answering (OpenAI-compatible endpoints; the +/// Anthropic adapter leaves its provider default alone). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum Reasoning { + #[default] + Auto, + Low, + Medium, + High, +} + +impl Reasoning { + pub fn label(self) -> &'static str { + match self { + Reasoning::Auto => "Auto", + Reasoning::Low => "Low", + Reasoning::Medium => "Medium", + Reasoning::High => "High", + } + } + + /// The `reasoning_effort` value, `None` for Auto (the provider's own default). + pub fn effort(self) -> Option<&'static str> { + match self { + Reasoning::Auto => None, + Reasoning::Low => Some("low"), + Reasoning::Medium => Some("medium"), + Reasoning::High => Some("high"), + } + } + + pub const CHOICES: &'static [Reasoning] = &[Reasoning::Auto, Reasoning::Low, Reasoning::Medium, Reasoning::High]; +} + +/// How much the agent does without asking. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum Permission { + /// Canvas edits run at once; anything that reads or writes a file, or reaches the network, + /// waits for the person's Allow. + #[default] + AskFiles, + /// Everything runs at once. File access is confined only when the app was started with + /// automation roots; a window opened normally has none. + Auto, +} + +/// One connected model endpoint. +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Provider { + pub name: String, + #[serde(default)] + pub kind: ApiKind, + /// The API root, e.g. `https://opencode.ai/zen/go/v1`; the adapter adds `/chat/completions` + /// or `/messages`. + pub base_url: String, + #[serde(default)] + pub api_key: String, + #[serde(default)] + pub model: String, + /// Model ids seen from this endpoint (`/models`), for the picker. + #[serde(default)] + pub models: Vec, + /// The model's limits, in tokens. + #[serde(default = "default_context")] + pub context_window: u32, + #[serde(default = "default_max_tokens")] + pub max_tokens: u32, + /// Whether the model reads images (screenshots of the canvas). + #[serde(default = "default_true")] + pub vision: bool, + /// Reasoning effort, where the endpoint supports one. + #[serde(default)] + pub reasoning: Reasoning, + /// What the endpoint charges, in US dollars per million tokens; 0 leaves the estimate out. + #[serde(default)] + pub price_in: f64, + #[serde(default)] + pub price_out: f64, +} + +fn default_context() -> u32 { + 128_000 +} + +fn default_max_tokens() -> u32 { + 8_192 +} + +fn default_true() -> bool { + true +} + +impl Provider { + pub fn new(name: &str, kind: ApiKind, base_url: &str) -> Self { + Self { + name: name.to_string(), + kind, + base_url: base_url.trim_end_matches('/').to_string(), + api_key: String::new(), + model: String::new(), + models: Vec::new(), + context_window: default_context(), + max_tokens: default_max_tokens(), + vision: true, + reasoning: Reasoning::Auto, + price_in: 0.0, + price_out: 0.0, + } + } + + /// The endpoint a request goes to. + pub fn endpoint(&self) -> String { + let root = self.base_url.trim_end_matches('/'); + match self.kind { + ApiKind::OpenAiCompletions => format!("{root}/chat/completions"), + ApiKind::AnthropicMessages => format!("{root}/messages"), + ApiKind::ClaudeCode | ApiKind::Codex | ApiKind::OpenCode => String::new(), + } + } + + /// Whether enough is filled in to send a request. A command-line connection needs nothing: + /// an empty model means that program's own default. + pub fn ready(&self) -> bool { + self.kind.is_cli() || (!self.base_url.trim().is_empty() && !self.model.trim().is_empty()) + } + + /// The model as the panel shows it. + pub fn model_label(&self) -> &str { + if self.model.trim().is_empty() { "Default model" } else { self.model.as_str() } + } + + /// A connection to the preset, with its model filled in later by [`pick_model`]. + pub fn from_preset(preset: &Preset) -> Self { + Self::new(preset.name, preset.kind, preset.base_url) + } + + /// A connection to an installed command-line agent. + pub fn from_cli(cli: &CliPreset) -> Self { + let mut p = Self::new(cli.name, cli.kind, ""); + p.models = cli.models.iter().map(|m| m.to_string()).collect(); + p + } +} + +/// A provider the person connects with an API key (or nothing, for a local server); the model is +/// picked from the endpoint's list. +pub struct Preset { + pub name: &'static str, + pub kind: ApiKind, + pub base_url: &'static str, + /// One line under the name on the connection card. + pub blurb: &'static str, + /// Where the person gets a key; `None` for a local server, which needs none. + pub key_url: Option<&'static str>, + /// Model ids (or parts of them) to choose first, in order, after the list arrives. + pub prefer: &'static [&'static str], +} + +impl Preset { + pub fn needs_key(&self) -> bool { + self.key_url.is_some() + } +} + +pub const PRESETS: &[Preset] = &[ + Preset { + name: "Anthropic", + kind: ApiKind::AnthropicMessages, + base_url: "https://api.anthropic.com/v1", + blurb: "Claude models with an API key", + key_url: Some("https://console.anthropic.com/settings/keys"), + prefer: &["claude-sonnet", "claude-opus"], + }, + Preset { + name: "OpenAI", + kind: ApiKind::OpenAiCompletions, + base_url: "https://api.openai.com/v1", + blurb: "GPT models with an API key", + key_url: Some("https://platform.openai.com/api-keys"), + prefer: &["gpt-5", "gpt-4.1"], + }, + Preset { + name: "OpenCode Go", + kind: ApiKind::OpenAiCompletions, + base_url: "https://opencode.ai/zen/go/v1", + blurb: "Open models on the OpenCode Go plan", + key_url: Some("https://opencode.ai/auth"), + prefer: &["kimi-k3", "glm-5", "qwen", "deepseek"], + }, + Preset { + name: "OpenCode Zen", + kind: ApiKind::OpenAiCompletions, + base_url: "https://opencode.ai/zen/v1", + blurb: "Pay-as-you-go models from OpenCode", + key_url: Some("https://opencode.ai/auth"), + prefer: &["claude-sonnet", "gpt-5", "kimi"], + }, + Preset { + name: "OpenRouter", + kind: ApiKind::OpenAiCompletions, + base_url: "https://openrouter.ai/api/v1", + blurb: "Many providers behind one key", + key_url: Some("https://openrouter.ai/keys"), + prefer: &["anthropic/claude-sonnet", "openai/gpt-5"], + }, + Preset { + name: "DeepSeek", + kind: ApiKind::OpenAiCompletions, + base_url: "https://api.deepseek.com/v1", + blurb: "DeepSeek models with an API key", + key_url: Some("https://platform.deepseek.com/api_keys"), + prefer: &["deepseek-chat"], + }, + Preset { + name: "Ollama", + kind: ApiKind::OpenAiCompletions, + base_url: "http://localhost:11434/v1", + blurb: "Models running on this computer", + key_url: None, + prefer: &[], + }, + Preset { + name: "LM Studio", + kind: ApiKind::OpenAiCompletions, + base_url: "http://localhost:1234/v1", + blurb: "Models running on this computer", + key_url: None, + prefer: &[], + }, +]; + +/// An installed command-line agent the person signs in to with their own plan. +pub struct CliPreset { + pub name: &'static str, + pub kind: ApiKind, + pub blurb: &'static str, + /// How to install it, shown when it is missing. + pub install: &'static str, + /// How to sign in, shown when it is installed but signed out. + pub login: &'static str, + /// Models offered before the program is asked for its own list (empty: its default only). + pub models: &'static [&'static str], +} + +pub const SUBSCRIPTIONS: &[CliPreset] = &[ + CliPreset { + name: "Claude Code", + kind: ApiKind::ClaudeCode, + blurb: "Use your Claude Pro or Max plan", + install: "curl -fsSL https://claude.ai/install.sh | bash", + login: "claude auth login", + models: &["sonnet", "opus", "haiku"], + }, + CliPreset { + name: "Codex", + kind: ApiKind::Codex, + blurb: "Use your ChatGPT plan", + install: "brew install codex", + login: "codex login", + models: &[], + }, + CliPreset { + name: "OpenCode", + kind: ApiKind::OpenCode, + blurb: "Use the providers OpenCode is signed in to", + install: "curl -fsSL https://opencode.ai/install | bash", + login: "opencode auth login", + models: &[], + }, +]; + +/// The model to start with once an endpoint listed its models: the first id that matches one of +/// `prefer` (newest first, skipping small and non-chat models), else the first chat model. +pub fn pick_model(prefer: &[&str], models: &[String]) -> Option { + const NOT_CHAT: &[&str] = &["embed", "audio", "realtime", "tts", "transcribe", "moderation", "image", "search", "whisper", "dall-e"]; + const SMALL: &[&str] = &["nano", "mini", "haiku", "flash", "lite"]; + let chat: Vec<&String> = models.iter().filter(|m| !NOT_CHAT.iter().any(|n| m.to_ascii_lowercase().contains(n))).collect(); + for want in prefer { + let mut hits: Vec<&&String> = chat.iter().filter(|m| m.contains(want)).collect(); + hits.sort_by(|a, b| b.cmp(a)); + if let Some(m) = hits.iter().find(|m| !SMALL.iter().any(|s| m.contains(s))).or(hits.first()) { + return Some((**m).to_string()); + } + } + chat.iter().find(|m| !SMALL.iter().any(|s| m.contains(s))).or(chat.first()).map(|m| m.to_string()) +} + +/// Everything `agents.json` holds. +#[derive(Clone, Debug, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AgentsFile { + #[serde(default)] + pub providers: Vec, + /// Index into `providers`; out of range means the first. + #[serde(default)] + pub active: usize, + #[serde(default)] + pub permission: Permission, + /// Whether the app opens on the Agent tab (the rail's Agent button was the last one used). + #[serde(default)] + pub panel: bool, + /// Whether the agent looks at the canvas after a turn that changed it and fixes what it sees + /// (models that read images only). + #[serde(default = "default_true")] + pub review: bool, + /// How many versions one request builds (1: just the design, up to 3 side by side). + #[serde(default = "one")] + pub variants: u8, +} + +fn one() -> u8 { + 1 +} + +impl AgentsFile { + /// The provider requests go to. + pub fn active(&self) -> Option<&Provider> { + self.providers.get(self.active).or_else(|| self.providers.first()) + } + + pub fn active_mut(&mut self) -> Option<&mut Provider> { + let i = if self.active < self.providers.len() { self.active } else { 0 }; + self.providers.get_mut(i) + } + + /// Read the file; a missing one is an empty setup, a damaged one is an empty setup with the + /// reason kept for the panel. + pub fn load(path: Option<&Path>) -> (Self, Option) { + let Some(path) = path else { return (Self::default(), None) }; + let bytes = match std::fs::read(path) { + Ok(b) => b, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return (Self::default(), None), + Err(e) => return (Self::default(), Some(format!("can't read {}: {e}", path.display()))), + }; + match serde_json::from_slice::(&bytes) { + Ok(mut f) => { + if f.active >= f.providers.len() { + f.active = 0; + } + (f, None) + } + Err(e) => (Self::default(), Some(format!("{} is damaged: {e}", path.display()))), + } + } + + /// Write the file, readable only by the user: it holds API keys. + pub fn save(&self, path: Option<&Path>) -> Result<(), String> { + let Some(path) = path else { return Err("this build has no settings folder to keep providers in".into()) }; + if let Some(dir) = path.parent() { + std::fs::create_dir_all(dir).map_err(|e| format!("can't make {}: {e}", dir.display()))?; + } + let bytes = serde_json::to_vec_pretty(self).map_err(|e| format!("can't encode the agent settings: {e}"))?; + write_private(path, &bytes) + } +} + +/// Write `bytes` to `path` through a temporary file, keeping the file owner-only where the +/// platform has permissions. +pub fn write_private(path: &Path, bytes: &[u8]) -> Result<(), String> { + if let Some(dir) = path.parent() { + std::fs::create_dir_all(dir).map_err(|e| format!("can't make {}: {e}", dir.display()))?; + } + let mut tmp = path.to_path_buf(); + tmp.set_extension("json.tmp"); + { + let mut opts = std::fs::OpenOptions::new(); + opts.write(true).create(true).truncate(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt as _; + opts.mode(0o600); + } + let mut file = opts.open(&tmp).map_err(|e| format!("can't write {}: {e}", tmp.display()))?; + use std::io::Write as _; + file.write_all(bytes).map_err(|e| format!("can't write {}: {e}", tmp.display()))?; + file.flush().map_err(|e| format!("can't write {}: {e}", tmp.display()))?; + } + std::fs::rename(&tmp, path).map_err(|e| format!("can't replace {}: {e}", path.display())) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn endpoints_follow_the_dialect() { + let mut p = Provider::new("Go", ApiKind::OpenAiCompletions, "https://opencode.ai/zen/go/v1/"); + assert_eq!(p.endpoint(), "https://opencode.ai/zen/go/v1/chat/completions"); + p.kind = ApiKind::AnthropicMessages; + assert_eq!(p.endpoint(), "https://opencode.ai/zen/go/v1/messages"); + assert!(!p.ready(), "no model chosen"); + p.model = "claude-haiku-5-5".into(); + assert!(p.ready()); + } + + #[test] + fn the_first_model_is_a_capable_chat_model() { + let ids = |v: &[&str]| v.iter().map(|s| s.to_string()).collect::>(); + let anthropic = ids(&["claude-haiku-5-5", "claude-opus-4-1", "claude-sonnet-4-5", "claude-sonnet-5-5"]); + assert_eq!(pick_model(&["claude-sonnet"], &anthropic).as_deref(), Some("claude-sonnet-5-5"), "the newest preferred"); + let openai = ids(&["gpt-5-nano", "gpt-5.5", "text-embedding-3", "gpt-5-mini"]); + assert_eq!(pick_model(&["gpt-5"], &openai).as_deref(), Some("gpt-5.5"), "not a small model"); + let local = ids(&["nomic-embed", "llama4"]); + assert_eq!(pick_model(&[], &local).as_deref(), Some("llama4"), "not an embedding model"); + assert_eq!(pick_model(&["x"], &[]), None); + } + + #[test] + fn a_command_line_connection_needs_no_model() { + let p = Provider::from_cli(&SUBSCRIPTIONS[0]); + assert!(p.ready()); + assert!(p.kind.is_cli()); + assert!(!p.models.is_empty()); + } + + #[test] + fn settings_round_trip_through_a_private_file() { + let dir = std::env::temp_dir().join(format!("figcraft-agent-test-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let path = dir.join("agents.json"); + let mut f = AgentsFile::default(); + f.providers.push(Provider::new("Go", ApiKind::OpenAiCompletions, "https://example.test/v1")); + f.providers[0].api_key = "sk-secret".into(); + f.providers[0].model = "deepseek-v4.1-flash".into(); + f.providers[0].reasoning = Reasoning::Medium; + f.providers[0].price_in = 1.5; + f.providers[0].price_out = 6.0; + f.active = 0; + f.permission = Permission::Auto; + f.variants = 3; + f.save(Some(&path)).expect("saved"); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt as _; + let mode = std::fs::metadata(&path).map(|m| m.permissions().mode()).unwrap_or(0); + assert_eq!(mode & 0o777, 0o600, "the key file is owner-only"); + } + let (back, err) = AgentsFile::load(Some(&path)); + assert!(err.is_none()); + assert_eq!(back.providers[0].api_key, "sk-secret"); + assert_eq!(back.permission, Permission::Auto); + assert_eq!(back.providers[0].reasoning, Reasoning::Medium); + assert_eq!(back.providers[0].price_out, 6.0); + assert_eq!(back.variants, 3); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn a_damaged_file_is_reported_not_fatal() { + let dir = std::env::temp_dir().join(format!("figcraft-agent-bad-{}", std::process::id())); + let _ = std::fs::create_dir_all(&dir); + let path = dir.join("agents.json"); + std::fs::write(&path, b"{not json").expect("write"); + let (f, err) = AgentsFile::load(Some(&path)); + assert!(f.providers.is_empty()); + assert!(err.is_some()); + let _ = std::fs::remove_dir_all(&dir); + } +} diff --git a/crates/agent/src/http.rs b/crates/agent/src/http.rs new file mode 100644 index 000000000..4e3bccb0f --- /dev/null +++ b/crates/agent/src/http.rs @@ -0,0 +1,99 @@ +//! Blocking HTTP for the provider adapters: rustls, no async runtime (the shape `figcraft-mcp` +//! and `collab-net` already use). + +use std::io::{BufRead, BufReader}; +use std::time::Duration; + +use serde_json::Value; + +pub struct Http { + agent: ureq::Agent, +} + +/// A response whose body is still being read (the SSE stream of a model answer). +pub struct Reply { + pub status: u16, + pub body: Box, +} + +impl Http { + pub fn new() -> Self { + let config = ureq::Agent::config_builder() + // A streamed answer can run for minutes: no whole-request deadline, but a stuck + // connection is caught by the per-read limit. + .timeout_global(None) + .timeout_connect(Some(Duration::from_secs(20))) + .timeout_recv_response(Some(Duration::from_secs(120))) + .timeout_per_read(Some(Duration::from_secs(300))) + // A 4xx carries the provider's message: read it, don't turn it into a bare error. + .http_status_as_error(false) + .build(); + Self { agent: config.new_agent() } + } + + fn send(&self, request: ureq::RequestBuilder, headers: &[(&str, String)], body: &Value) -> Result { + let mut request = request; + for (name, value) in headers { + request = request.header(*name, value.clone()); + } + let response = request.send_json(body).map_err(network)?; + let status = response.status().as_u16(); + let body = Box::new(BufReader::new(response.into_body().into_reader())); + Ok(Reply { status, body }) + } + + /// POST JSON and stream the answer back. + pub fn post(&self, url: &str, headers: &[(&str, String)], body: &Value) -> Result { + self.send(self.agent.post(url), headers, body) + } + + /// GET JSON (model lists), with the response body read whole. + pub fn get_json(&self, url: &str, headers: &[(&str, String)]) -> Result { + let mut request = self.agent.get(url); + for (name, value) in headers { + request = request.header(*name, value.clone()); + } + let response = request.call().map_err(network)?; + let status = response.status().as_u16(); + let mut body = response.into_body(); + let text = body.read_to_string().map_err(|e| format!("reading the answer failed: {e}"))?; + if status >= 400 { + return Err(status_message(status, &text)); + } + serde_json::from_str(&text).map_err(|e| format!("the endpoint sent something that is not JSON: {e}")) + } +} + +impl Default for Http { + fn default() -> Self { + Self::new() + } +} + +fn network(e: ureq::Error) -> String { + match e { + ureq::Error::Timeout(t) => format!("the endpoint did not answer in time ({t})"), + ureq::Error::StatusCode(code) => format!("the endpoint answered {code}"), + ureq::Error::Io(e) => format!("network error: {e}"), + other => format!("request failed: {other}"), + } +} + +/// The provider's own error message when it sent one, else the status and the start of the body. +pub fn status_message(status: u16, body: &str) -> String { + if let Ok(v) = serde_json::from_str::(body) + && let Some(m) = v.get("error").and_then(|e| e.get("message")).and_then(Value::as_str) + { + return format!("{status}: {m}"); + } + let head: String = body.chars().take(400).collect(); + format!("{status}: {}", head.trim()) +} + +/// The whole body of a failed reply, for its message. +pub fn read_error(status: u16, body: Box) -> String { + use std::io::Read as _; + let mut text = String::new(); + let _ = body.take(64 * 1024).read_to_string(&mut text); + status_message(status, &text) +} diff --git a/crates/agent/src/lib.rs b/crates/agent/src/lib.rs new file mode 100644 index 000000000..37dbcaaae --- /dev/null +++ b/crates/agent/src/lib.rs @@ -0,0 +1,257 @@ +//! FigCraft's in-app agent. +//! +//! Two provider dialects (OpenAI Chat Completions and Anthropic Messages), the tool-call loop on +//! top of [`figcraft_mcp`]'s tool set, and the bridge that lets the loop run on its own thread +//! while the session stays on the UI thread. +//! +//! The app shows a chat panel; the panel owns a [`Worker`], which owns an [`Agent`]. Every tool +//! call goes through [`figcraft_mcp::Backend`], so the in-app agent and an external MCP client +//! behave the same. + +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] + +pub mod anthropic; +pub mod bridge; +pub mod brief; +pub mod cli; +pub mod config; +pub mod http; +pub mod mcp_http; +pub mod neutral; +pub mod openai; +pub mod session; +pub mod skills; +pub mod sse; + +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, AtomicU8, Ordering}; +use std::sync::mpsc::{Receiver, Sender, channel}; + +use serde_json::Value; + +pub use config::{AgentsFile, ApiKind, CliPreset, PRESETS, Permission, Preset, Provider, SUBSCRIPTIONS, pick_model}; +pub use session::{AGENT_NAME, Agent, ChatEvent, approval, system_prompt}; + +/// Token counts one request used. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +pub struct Usage { + pub input: u64, + pub output: u64, +} + +/// One tool call the model asked for. +#[derive(Clone, Debug, PartialEq)] +pub struct Invocation { + pub id: String, + pub name: String, + /// The arguments; `Value::Null` when the model sent text that is not JSON. + pub args: Value, + pub args_raw: String, +} + +/// One streamed model step: its text, its tool calls and what it used. +#[derive(Clone, Debug, Default)] +pub struct Step { + pub text: String, + pub calls: Vec, + pub stop: String, + pub usage: Usage, +} + +/// What the panel tells the worker to do. +pub enum Command { + Turn { + text: String, + context: Option, + /// Images the person attached (references, a render of the selection). + images: Vec, + }, + /// Switch the model (or endpoint) without losing the conversation. + SetProvider(Provider), + /// Move the conversation to another file (the next document's chat): the current one is + /// saved first, then the new one is read if it exists. + SetHistory(Option), + Clear, + Shutdown, +} + +/// The agent thread the panel talks to. It lives as long as the conversation does, keeping the +/// messages (and the provider's prompt cache) between turns. +pub struct Worker { + commands: Sender, + /// Events of the running (or last) turn, drained by the panel every frame. + pub events: Receiver, + /// Set to stop the running turn; the worker clears it when the next one starts. + pub cancel: Arc, + /// 0: ask before file and network tools, 1: auto. + pub permission: Arc, + /// Whether a turn that changes the canvas ends with a look at it. + pub review: Arc, + /// The skills the model can load; the panel keeps it current. + pub skills: skills::SkillBook, + /// False once the thread ended (a panic included), so the panel can say so. + alive: Arc, + handle: Option>, +} + +/// Clears the worker's `alive` flag however the thread ends, a panic included. +struct Alive(Arc); + +impl Drop for Alive { + fn drop(&mut self) { + self.0.store(false, Ordering::Relaxed); + } +} + +impl Worker { + /// Start an agent thread for `provider`, whose tool calls go through `backend`. + pub fn spawn(provider: Provider, backend: bridge::Remote, wake: Arc) -> Self { + let (commands, inbox) = channel::(); + let (out, events) = channel::(); + let cancel = Arc::new(AtomicBool::new(false)); + let permission = Arc::new(AtomicU8::new(0)); + let review = Arc::new(AtomicBool::new(true)); + let skills: skills::SkillBook = Arc::new(std::sync::RwLock::new(skills::builtins())); + let thread_skills = skills.clone(); + let alive = Arc::new(AtomicBool::new(true)); + let thread_cancel = cancel.clone(); + let thread_permission = permission.clone(); + let thread_review = review.clone(); + let thread_alive = alive.clone(); + let handle = std::thread::Builder::new().name("figcraft-agent".into()).spawn(move || { + let _alive = Alive(thread_alive); + let mut agent = Agent::new(provider, backend); + agent.permission = thread_permission; + agent.review = thread_review; + agent.skills = thread_skills; + let mut history: Option = None; + // Every event wakes the window: it is idle between frames and would otherwise show + // the answer only on the next mouse move. + let shared: Arc = Arc::new(move |event: ChatEvent| { + let _ = out.send(event); + wake(); + }); + agent.sink = Some(shared.clone()); + let sink = |event: ChatEvent| shared(event); + while let Ok(command) = inbox.recv() { + match command { + Command::Turn { text, context, images } => { + thread_cancel.store(false, Ordering::Relaxed); + match agent.run_turn_with(&text, context, images, &sink, &thread_cancel) { + Ok(()) => {} + Err(e) => { + sink(ChatEvent::Error(e)); + sink(ChatEvent::Done { stopped: false }); + } + } + if let Some(path) = &history { + let _ = agent.save_history(path); + } + } + Command::Clear => { + agent.clear(); + if let Some(path) = &history { + let _ = agent.save_history(path); + } + } + Command::SetProvider(p) => agent.set_provider(p), + Command::SetHistory(path) => { + if let Some(old) = history.as_ref() { + let _ = agent.save_history(old); + } + history = path; + // The next conversation starts empty unless its own file holds one: the + // last one's messages must not carry over. + agent.clear(); + // A command-line agent runs beside the saved chats, never in a project. + if let Some(dir) = history.as_deref().and_then(std::path::Path::parent) { + agent.workdir = Some(dir.join("cli")); + } + if let Some(new) = history.as_ref() { + let _ = agent.load_history(new); + } + } + Command::Shutdown => break, + } + } + }); + Self { commands, events, cancel, permission, review, skills, alive, handle: handle.ok() } + } + + pub fn send_turn(&self, text: String, context: Option) -> Result<(), String> { + self.send_turn_with(text, context, Vec::new()) + } + + /// [`send_turn`](Self::send_turn) with images attached to the request. + pub fn send_turn_with(&self, text: String, context: Option, images: Vec) -> Result<(), String> { + self.commands.send(Command::Turn { text, context, images }).map_err(|_| "the agent thread stopped".to_string()) + } + + pub fn clear(&self) -> Result<(), String> { + self.commands.send(Command::Clear).map_err(|_| "the agent thread stopped".to_string()) + } + + pub fn set_provider(&self, provider: Provider) -> Result<(), String> { + self.commands.send(Command::SetProvider(provider)).map_err(|_| "the agent thread stopped".to_string()) + } + + /// Ask the running turn to stop; the layer edits it already made stay. + pub fn stop(&self) { + self.cancel.store(true, Ordering::Relaxed); + } + + pub fn set_auto(&self, auto: bool) { + self.permission.store(u8::from(auto), Ordering::Relaxed); + } + + pub fn set_review(&self, on: bool) { + self.review.store(on, Ordering::Relaxed); + } + + /// False once the agent thread ended (a panic included). + pub fn alive(&self) -> bool { + self.alive.load(Ordering::Relaxed) + } + + /// Move the conversation to another file (the next document's chat). + pub fn set_history(&self, path: Option) -> Result<(), String> { + self.commands.send(Command::SetHistory(path)).map_err(|_| "the agent thread stopped".to_string()) + } +} + +impl Drop for Worker { + fn drop(&mut self) { + let _ = self.commands.send(Command::Shutdown); + // The thread may be waiting on the network; it ends after that answer. Dropping the + // handle detaches it rather than blocking the UI thread here. + self.handle.take(); + } +} + +/// The model ids an endpoint lists (`GET {base}/models`). +pub fn list_models(provider: &Provider) -> Result, String> { + let http = http::Http::new(); + let url = format!("{}/models", provider.base_url.trim_end_matches('/')); + if provider.kind.is_cli() { + return cli::models(provider.kind).ok_or_else(|| format!("{} keeps its own model list", provider.kind.label())); + } + let mut headers: Vec<(&str, String)> = match provider.kind { + ApiKind::AnthropicMessages => vec![("x-api-key", provider.api_key.trim().to_string()), ("anthropic-version", "2023-06-01".to_string())], + _ => vec![("authorization", format!("Bearer {}", provider.api_key.trim()))], + }; + if provider.api_key.trim().is_empty() { + headers.retain(|(k, _)| *k == "anthropic-version"); + } + let v = http.get_json(&url, &headers)?; + let mut ids: Vec = v + .get("data") + .and_then(Value::as_array) + .map(|a| a.iter().filter_map(|m| m.get("id").and_then(Value::as_str).map(str::to_string)).collect()) + .unwrap_or_default(); + ids.sort(); + ids.dedup(); + if ids.is_empty() { + return Err("the endpoint listed no models; type the model id instead".into()); + } + Ok(ids) +} diff --git a/crates/agent/src/mcp_http.rs b/crates/agent/src/mcp_http.rs new file mode 100644 index 000000000..3f95cd590 --- /dev/null +++ b/crates/agent/src/mcp_http.rs @@ -0,0 +1,458 @@ +//! FigCraft's tools for a command-line agent (Claude Code, Codex, OpenCode). +//! +//! Those programs run their own loop and reach tools over MCP. This serves the same tool set the +//! in-app loop uses ([`figcraft_mcp::Server`] over the [`Remote`](crate::bridge::Remote) bridge) on +//! a loopback HTTP endpoint for the length of the conversation: one JSON-RPC message per `POST`, +//! answered as `application/json` (MCP's Streamable HTTP transport without server-sent events). +//! +//! Only this app's child processes are meant to call it: it listens on 127.0.0.1 only, refuses a +//! request without the bearer token handed to the child, and refuses browser requests (an `Origin` +//! header, or a `Host` that is not loopback). Tool calls pass the same Ask/Auto gate as the in-app +//! loop, and report to the panel the same way. + +use std::io::{BufRead, BufReader, Write}; +use std::net::{TcpListener, TcpStream}; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, AtomicU8, Ordering}; +use std::sync::mpsc::{Receiver, Sender, channel}; +use std::time::Duration; + +use serde_json::{Value, json}; + +use crate::bridge::Remote; +use crate::session::ChatEvent; + +/// The largest request body accepted (tool arguments are small; an image goes the other way). +const MAX_BODY: usize = 16 * 1024 * 1024; +/// The largest header block accepted. +const MAX_HEADERS: usize = 64 * 1024; + +/// Where a tool call reports to the panel, and how much it may do without asking. +#[derive(Clone)] +pub struct Gate { + /// 0: ask before file and network tools, 1: auto (shared with the panel's toggle). + pub permission: Arc, + /// The panel's event stream. + pub sink: Arc, + /// Set by Stop: calls still arriving are refused. + pub cancel: Arc, + /// Set when a call changed the document, so the turn can end with a look at the canvas. + pub edited: Arc, + /// The skills `load_skill` answers from (a tool this endpoint adds to FigCraft's own). + pub skills: crate::skills::SkillBook, +} + +/// A running endpoint; dropping it stops the listener. +pub struct Endpoint { + pub url: String, + pub token: String, + stop: Arc, + port: u16, +} + +impl Drop for Endpoint { + fn drop(&mut self) { + self.stop.store(true, Ordering::Relaxed); + // Wake the blocking accept so the thread sees the flag. + let _ = TcpStream::connect_timeout(&std::net::SocketAddr::from(([127, 0, 0, 1], self.port)), Duration::from_millis(200)); + } +} + +/// One JSON-RPC message on its way to the server thread, and where its answer goes. +type Job = (Value, Sender>); + +/// Start serving FigCraft's tools on a free loopback port. +pub fn start(remote: Remote, gate: Gate) -> std::io::Result { + let listener = TcpListener::bind(("127.0.0.1", 0))?; + let port = listener.local_addr()?.port(); + let token = new_token().map_err(std::io::Error::other)?; + let stop = Arc::new(AtomicBool::new(false)); + + // The MCP server is not `Send` (its backend is a trait object), so it lives on one thread and + // the connections hand it messages. + let (jobs, inbox) = channel::(); + std::thread::Builder::new().name("figcraft-agent-mcp".into()).spawn(move || serve_jobs(remote, gate, inbox))?; + + let accept_stop = stop.clone(); + let accept_token = token.clone(); + std::thread::Builder::new().name("figcraft-agent-mcp-accept".into()).spawn(move || { + for stream in listener.incoming() { + if accept_stop.load(Ordering::Relaxed) { + break; + } + let Ok(stream) = stream else { continue }; + let jobs = jobs.clone(); + let token = accept_token.clone(); + let _ = std::thread::Builder::new().name("figcraft-agent-mcp-conn".into()).spawn(move || connection(stream, &token, &jobs)); + } + })?; + Ok(Endpoint { url: format!("http://127.0.0.1:{port}/mcp"), token, stop, port }) +} + +fn serve_jobs(remote: Remote, gate: Gate, inbox: Receiver) { + let mut own = remote.clone(); + let mut server = figcraft_mcp::Server::new(Box::new(remote)); + while let Ok((msg, reply)) = inbox.recv() { + let answer = handle_gated(&mut server, &mut own, &gate, msg); + let _ = reply.send(answer); + } +} + +/// Run one message, with `tools/call` going through the Ask/Auto gate and reported to the panel. +fn handle_gated(server: &mut figcraft_mcp::Server, own: &mut Remote, gate: &Gate, msg: Value) -> Option { + match msg.get("method").and_then(Value::as_str) { + Some("tools/call") => {} + Some("tools/list") => { + let mut answer = server.handle(msg)?; + if let Some(tools) = answer.pointer_mut("/result/tools").and_then(Value::as_array_mut) { + tools.push(crate::skills::tool_definition()); + tools.push(crate::brief::tool_definition()); + } + return Some(answer); + } + _ => return server.handle(msg), + } + let id = msg.get("id").cloned().unwrap_or(Value::Null); + let params = msg.get("params").cloned().unwrap_or(Value::Null); + let name = params.get("name").and_then(Value::as_str).unwrap_or("").to_string(); + let args = params.get("arguments").cloned().unwrap_or_else(|| json!({})); + let call_id = id.to_string(); + let refuse = |text: String| Some(json!({"jsonrpc": "2.0", "id": id, "result": {"content": [{"type": "text", "text": text}], "isError": true}})); + + (gate.sink)(ChatEvent::ToolStart { id: call_id.clone(), name: name.clone(), args: args.clone() }); + // A call that arrives after Stop runs nothing, FigCraft's own tools included. + if gate.cancel.load(Ordering::Relaxed) { + (gate.sink)(ChatEvent::ToolEnd { id: call_id, name: name.clone(), ok: false, title: name, text: "Stopped by the user".into() }); + return refuse("Not run: the user stopped the agent".into()); + } + if name == crate::brief::TOOL_NAME { + let (text, ok) = crate::brief::call(own, &args); + if ok && (args.get("spec").is_some() || args.get("brief").is_some()) { + gate.edited.store(true, Ordering::Relaxed); + } + (gate.sink)(ChatEvent::ToolEnd { + id: call_id, + name: name.clone(), + ok, + title: crate::session::tool_title(&name, &args), + text: crate::session::summarize(&text), + }); + return Some(json!({"jsonrpc": "2.0", "id": id, "result": {"content": [{"type": "text", "text": text}], "isError": !ok}})); + } + if name == crate::skills::TOOL_NAME { + let (text, ok) = crate::skills::call(&gate.skills, &args); + (gate.sink)(ChatEvent::ToolEnd { + id: call_id, + name: name.clone(), + ok, + title: crate::session::tool_title(&name, &args), + text: crate::session::summarize(&text), + }); + return Some(json!({"jsonrpc": "2.0", "id": id, "result": {"content": [{"type": "text", "text": text}], "isError": !ok}})); + } + if let Some(reason) = crate::session::approval(&name, &args) + && gate.permission.load(Ordering::Relaxed) == 0 + { + let (tx, rx) = channel(); + (gate.sink)(ChatEvent::Permission { id: call_id.clone(), name: name.clone(), args: args.clone(), reason: reason.clone(), reply: tx }); + if !rx.recv_timeout(Duration::from_secs(600)).unwrap_or(false) { + (gate.sink)(ChatEvent::ToolEnd { id: call_id, name: name.clone(), ok: false, title: name, text: "Denied by the user".into() }); + return refuse(format!("Not run: the user denied this action ({reason})")); + } + // Stop may have come while the Allow was waiting. + if gate.cancel.load(Ordering::Relaxed) { + (gate.sink)(ChatEvent::ToolEnd { id: call_id, name: name.clone(), ok: false, title: name, text: "Stopped by the user".into() }); + return refuse("Not run: the user stopped the agent".into()); + } + } + let answer = server.handle(msg); + let result = answer.as_ref().and_then(|a| a.get("result")); + let ok = result.is_some_and(|r| !r.get("isError").and_then(Value::as_bool).unwrap_or(false)); + if ok && crate::session::mutating(&name, &args) { + gate.edited.store(true, Ordering::Relaxed); + } + let text = result + .and_then(|r| r.get("content")) + .and_then(Value::as_array) + .and_then(|c| c.iter().find_map(|b| b.get("text").and_then(Value::as_str))) + .map(str::to_string) + .or_else(|| answer.as_ref().and_then(|a| a.pointer("/error/message")).and_then(Value::as_str).map(str::to_string)) + .unwrap_or_default(); + (gate.sink)(ChatEvent::ToolEnd { + id: call_id, + name: name.clone(), + ok, + title: crate::session::tool_title(&name, &args), + text: crate::session::summarize(&text), + }); + answer +} + +/// Serve one keep-alive connection until it closes or sends something unreadable. +fn connection(stream: TcpStream, token: &str, jobs: &Sender) { + let _ = stream.set_read_timeout(Some(Duration::from_secs(900))); + let Ok(mut out) = stream.try_clone() else { return }; + let mut reader = BufReader::new(stream); + loop { + let request = match read_request(&mut reader) { + Ok(Some(r)) => r, + Ok(None) => return, + Err(status) => { + let _ = write_response(&mut out, &Response::status(status)); + return; + } + }; + let close = request.header("connection").is_some_and(|v| v.eq_ignore_ascii_case("close")); + let response = respond(&request, token, &mut |msg| { + let (tx, rx) = channel(); + if jobs.send((msg, tx)).is_err() { + return None; + } + rx.recv().ok().flatten() + }); + if write_response(&mut out, &response).is_err() || close { + return; + } + } +} + +/// One HTTP request as read off the socket. +pub struct Request { + pub method: String, + pub path: String, + pub headers: Vec<(String, String)>, + pub body: Vec, +} + +impl Request { + pub fn header(&self, name: &str) -> Option<&str> { + self.headers.iter().find(|(k, _)| k.eq_ignore_ascii_case(name)).map(|(_, v)| v.as_str()) + } +} + +pub struct Response { + pub status: u16, + pub body: Vec, +} + +impl Response { + fn status(status: u16) -> Self { + Self { status, body: Vec::new() } + } +} + +/// Answer one request: the checks, then the JSON-RPC message (or batch) through `forward`. +pub fn respond(req: &Request, token: &str, forward: &mut dyn FnMut(Value) -> Option) -> Response { + if req.header("origin").is_some() { + return Response::status(403); + } + let host = req.header("host").unwrap_or(""); + let host_name = host.rsplit_once(':').map_or(host, |(h, _)| h); + if !matches!(host_name, "127.0.0.1" | "localhost" | "[::1]") { + return Response::status(403); + } + let authorized = req.header("authorization").and_then(|v| v.strip_prefix("Bearer ")).is_some_and(|t| same(t.trim(), token)); + if !authorized { + return Response::status(401); + } + if req.path.split('?').next() != Some("/mcp") { + return Response::status(404); + } + match req.method.as_str() { + "POST" => {} + // No server-initiated stream and no sessions to end. + _ => return Response::status(405), + } + let Ok(msg) = serde_json::from_slice::(&req.body) else { + let body = json!({"jsonrpc": "2.0", "id": null, "error": {"code": -32700, "message": "parse error"}}); + return Response { status: 400, body: body.to_string().into_bytes() }; + }; + let answer = match msg { + Value::Array(batch) => { + let answers: Vec = batch.into_iter().filter_map(&mut *forward).collect(); + if answers.is_empty() { None } else { Some(Value::Array(answers)) } + } + one => forward(one), + }; + match answer { + Some(a) => Response { status: 200, body: a.to_string().into_bytes() }, + // A notification or a client's response: accepted, nothing to say. + None => Response::status(202), + } +} + +/// Compare without stopping at the first different byte. +fn same(a: &str, b: &str) -> bool { + a.len() == b.len() && a.bytes().zip(b.bytes()).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0 +} + +/// Read one request; `Ok(None)` when the peer closed the connection between requests, `Err` with +/// the status to answer for a request this server will not read. +fn read_request(reader: &mut impl BufRead) -> Result, u16> { + let line = match read_line_limited(reader, MAX_HEADERS) { + Ok(Some(l)) => l, + Ok(None) => return Ok(None), + Err(LineError::TooLong) => return Err(431), + Err(LineError::Io) => return Ok(None), + }; + let mut parts = line.split_whitespace(); + let (Some(method), Some(path)) = (parts.next(), parts.next()) else { return Err(400) }; + let (method, path) = (method.to_string(), path.to_string()); + let mut headers = Vec::new(); + let mut size = line.len(); + loop { + let h = match read_line_limited(reader, MAX_HEADERS.saturating_sub(size)) { + Ok(Some(h)) => h, + Ok(None) | Err(LineError::Io) => return Err(400), + Err(LineError::TooLong) => return Err(431), + }; + size += h.len(); + if size > MAX_HEADERS { + return Err(431); + } + let h = h.trim_end_matches(['\r', '\n']); + if h.is_empty() { + break; + } + if let Some((k, v)) = h.split_once(':') { + headers.push((k.trim().to_string(), v.trim().to_string())); + } + } + let req = Request { method, path, headers, body: Vec::new() }; + if req.header("transfer-encoding").is_some() { + return Err(411); + } + let length = match req.header("content-length") { + Some(v) => v.parse::().map_err(|_| 400u16)?, + None => 0, + }; + if length > MAX_BODY { + return Err(413); + } + let mut body = vec![0; length]; + reader.read_exact(&mut body).map_err(|_| 400u16)?; + Ok(Some(Request { body, ..req })) +} + +enum LineError { + TooLong, + Io, +} + +/// One line of at most `limit` bytes, read without keeping more than that; `None` at the end. +fn read_line_limited(reader: &mut impl BufRead, limit: usize) -> Result, LineError> { + use std::io::Read as _; + let mut bytes = Vec::new(); + let read = reader.by_ref().take(limit as u64 + 1).read_until(b'\n', &mut bytes).map_err(|_| LineError::Io)?; + if read == 0 { + return Ok(None); + } + if bytes.len() > limit { + return Err(LineError::TooLong); + } + Ok(Some(String::from_utf8_lossy(&bytes).into_owned())) +} + +fn write_response(out: &mut impl Write, r: &Response) -> std::io::Result<()> { + let reason = match r.status { + 200 => "OK", + 202 => "Accepted", + 400 => "Bad Request", + 401 => "Unauthorized", + 403 => "Forbidden", + 404 => "Not Found", + 405 => "Method Not Allowed", + 411 => "Length Required", + 413 => "Payload Too Large", + 431 => "Request Header Fields Too Large", + _ => "Error", + }; + let mut head = format!("HTTP/1.1 {} {reason}\r\nContent-Length: {}\r\n", r.status, r.body.len()); + if !r.body.is_empty() { + head.push_str("Content-Type: application/json\r\n"); + } + if r.status == 405 { + head.push_str("Allow: POST\r\n"); + } + head.push_str("\r\n"); + out.write_all(head.as_bytes())?; + out.write_all(&r.body)?; + out.flush() +} + +/// 128 random bits as hex, from the operating system's secure random number generator. +fn new_token() -> Result { + let mut b = [0u8; 16]; + getrandom::fill(&mut b).map_err(|e| format!("no secure random numbers: {e}"))?; + Ok(b.iter().map(|x| format!("{x:02x}")).collect()) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn request(headers: &[(&str, &str)], body: &str) -> Request { + Request { + method: "POST".into(), + path: "/mcp".into(), + headers: headers.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect(), + body: body.as_bytes().to_vec(), + } + } + + fn echo(msg: Value) -> Option { + msg.get("id").map(|id| json!({"jsonrpc": "2.0", "id": id, "result": {}})) + } + + #[test] + fn only_the_child_with_the_token_reaches_the_tools() { + let body = r#"{"jsonrpc":"2.0","id":1,"method":"tools/list"}"#; + let ok = respond(&request(&[("Host", "127.0.0.1:5"), ("Authorization", "Bearer secret")], body), "secret", &mut echo); + assert_eq!(ok.status, 200); + let none = respond(&request(&[("Host", "127.0.0.1:5")], body), "secret", &mut echo); + assert_eq!(none.status, 401); + let wrong = respond(&request(&[("Host", "127.0.0.1:5"), ("Authorization", "Bearer secreT")], body), "secret", &mut echo); + assert_eq!(wrong.status, 401); + let browser = respond( + &request(&[("Host", "127.0.0.1:5"), ("Origin", "https://x.test"), ("Authorization", "Bearer secret")], body), + "secret", + &mut echo, + ); + assert_eq!(browser.status, 403, "a page in a browser is refused even with the token"); + let rebound = respond(&request(&[("Host", "evil.test:5"), ("Authorization", "Bearer secret")], body), "secret", &mut echo); + assert_eq!(rebound.status, 403, "a rebound host name is refused"); + } + + #[test] + fn a_notification_is_accepted_without_a_body() { + let r = respond( + &request(&[("Host", "localhost:1"), ("Authorization", "Bearer t")], r#"{"jsonrpc":"2.0","method":"notifications/initialized"}"#), + "t", + &mut echo, + ); + assert_eq!(r.status, 202); + assert!(r.body.is_empty()); + } + + #[test] + fn a_request_is_read_with_its_body_and_the_next_one_waits() { + let raw = "POST /mcp HTTP/1.1\r\nHost: 127.0.0.1\r\nContent-Length: 2\r\n\r\n{}POST"; + let mut reader = BufReader::new(raw.as_bytes()); + let r = read_request(&mut reader).ok().flatten().expect("a request"); + assert_eq!(r.body, b"{}"); + assert!(read_request(&mut reader).is_err(), "a cut-off request is refused, not waited on forever"); + } + + #[test] + fn an_endless_header_is_refused_before_it_is_all_read() { + let raw = format!("POST /mcp HTTP/1.1\r\nX-Long: {}", "a".repeat(MAX_HEADERS * 2)); + let mut reader = BufReader::new(raw.as_bytes()); + assert_eq!(read_request(&mut reader).err(), Some(431)); + } + + #[test] + fn tokens_differ() { + assert_ne!(new_token(), new_token()); + assert_eq!(new_token().map(|t| t.len()), Ok(32)); + } +} diff --git a/crates/agent/src/neutral.rs b/crates/agent/src/neutral.rs new file mode 100644 index 000000000..a9d3d46ed --- /dev/null +++ b/crates/agent/src/neutral.rs @@ -0,0 +1,183 @@ +//! The conversation in a provider-neutral shape: messages made of text, image, tool-call and +//! tool-result blocks. Each adapter translates these to its wire format, so switching provider +//! keeps the history. + +use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; + +/// One image travelling with a message: base64 data and its media type. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Image { + pub mime: String, + pub data: String, +} + +/// A piece of a message. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub enum Block { + Text(String), + Image(Image), + /// The model asked for a tool. + ToolCall { + id: String, + name: String, + args: Value, + }, + /// What the tool returned, for the model to read on the next step. + ToolResult { + id: String, + name: String, + ok: bool, + text: String, + images: Vec, + }, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub enum Role { + User, + Assistant, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct Message { + pub role: Role, + pub blocks: Vec, +} + +impl Message { + pub fn user_text(text: impl Into) -> Self { + Self { role: Role::User, blocks: vec![Block::Text(text.into())] } + } + + /// The message as plain text (`None` when it holds anything but text). + pub fn as_text(&self) -> Option { + let mut out = String::new(); + for block in &self.blocks { + match block { + Block::Text(t) => out.push_str(t), + _ => return None, + } + } + Some(out) + } +} + +/// The MCP tool definitions as OpenAI Chat Completions tools. +pub fn openai_tools(defs: &[Value]) -> Vec { + defs.iter() + .filter_map(|d| { + let name = d.get("name")?.as_str()?; + Some(json!({ + "type": "function", + "function": { + "name": name, + "description": d.get("description").and_then(Value::as_str).unwrap_or(""), + "parameters": d.get("inputSchema").cloned().unwrap_or_else(|| json!({"type": "object", "properties": {}})), + } + })) + }) + .collect() +} + +/// The MCP tool definitions as Anthropic Messages tools. +pub fn anthropic_tools(defs: &[Value]) -> Vec { + defs.iter() + .filter_map(|d| { + let name = d.get("name")?.as_str()?; + Some(json!({ + "name": name, + "description": d.get("description").and_then(Value::as_str).unwrap_or(""), + "input_schema": d.get("inputSchema").cloned().unwrap_or_else(|| json!({"type": "object", "properties": {}})), + })) + }) + .collect() +} + +/// One tool result from an MCP [`figcraft_mcp::ToolResult`]: its text and any images. +pub fn tool_output(result: &figcraft_mcp::ToolResult) -> (String, Vec) { + let mut text = String::new(); + let mut images = Vec::new(); + for c in &result.content { + match c.get("type").and_then(Value::as_str) { + Some("text") => { + let t = c.get("text").and_then(Value::as_str).unwrap_or(""); + if !text.is_empty() && !t.is_empty() { + text.push('\n'); + } + text.push_str(t); + } + Some("image") => { + let mime = c.get("mimeType").and_then(Value::as_str).unwrap_or("image/png"); + if let Some(data) = c.get("data").and_then(Value::as_str) { + images.push(Image { mime: mime.to_string(), data: data.to_string() }); + } + } + _ => {} + } + } + (text, images) +} + +/// Cut a tool's text to a size a model can take, keeping both ends: the start names what ran and +/// the end holds the error or the summary. +pub fn clip(text: &str, max: usize) -> String { + if text.len() <= max { + return text.to_string(); + } + let keep = max.saturating_div(2); + let mut start = keep; + while start > 0 && !text.is_char_boundary(start) { + start -= 1; + } + let mut end = text.len() - keep; + while end < text.len() && !text.is_char_boundary(end) { + end += 1; + } + format!("{}\n…[{} bytes left out]…\n{}", &text[..start], end - start, &text[end..]) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn tools_keep_their_schema_in_both_dialects() { + let defs = vec![json!({ + "name": "create_node", + "description": "Create a layer", + "inputSchema": {"type": "object", "properties": {"type": {"type": "string"}}} + })]; + let o = openai_tools(&defs); + assert_eq!(o[0]["function"]["name"], "create_node"); + assert_eq!(o[0]["function"]["parameters"]["properties"]["type"]["type"], "string"); + let a = anthropic_tools(&defs); + assert_eq!(a[0]["name"], "create_node"); + assert_eq!(a[0]["input_schema"]["type"], "object"); + } + + #[test] + fn tool_output_separates_text_and_images() { + let r = figcraft_mcp::ToolResult { + content: vec![ + json!({"type": "text", "text": "hello"}), + json!({"type": "image", "mimeType": "image/png", "data": "AAAA"}), + json!({"type": "text", "text": "world"}), + ], + is_error: false, + }; + let (text, images) = tool_output(&r); + assert_eq!(text, "hello\nworld"); + assert_eq!(images.len(), 1); + assert_eq!(images[0].mime, "image/png"); + } + + #[test] + fn clipping_keeps_both_ends_and_stays_on_char_boundaries() { + let s = format!("start{}end", "é".repeat(100)); + let out = clip(&s, 40); + assert!(out.starts_with("start")); + assert!(out.ends_with("end")); + assert!(out.len() < s.len()); + } +} diff --git a/crates/agent/src/openai.rs b/crates/agent/src/openai.rs new file mode 100644 index 000000000..b52958c96 --- /dev/null +++ b/crates/agent/src/openai.rs @@ -0,0 +1,284 @@ +//! The OpenAI Chat Completions dialect: most gateways speak it (OpenAI, OpenCode Zen/Go, +//! OpenRouter, DeepSeek, Ollama, LM Studio and custom endpoints). + +use std::collections::BTreeMap; +use std::sync::atomic::AtomicBool; + +use serde_json::{Value, json}; + +use crate::config::Provider; +use crate::http::{Http, read_error}; +use crate::neutral::{Block, Message, Role}; +use crate::{Invocation, Step, Usage}; + +/// What a stream that ended before the answer did is reported as. +pub const INTERRUPTED: &str = "the connection closed before the answer finished; ask the agent to continue"; + +/// The request body for one step of the conversation. +pub fn payload(provider: &Provider, system: &str, messages: &[Message], tools: &[Value]) -> Value { + let mut body = json!({ + "model": provider.model, + "messages": wire_messages(system, messages), + "stream": true, + "stream_options": {"include_usage": true}, + }); + if let Some(effort) = provider.reasoning.effort() { + body["reasoning_effort"] = json!(effort); + } + let tools = crate::neutral::openai_tools(tools); + if !tools.is_empty() { + body["tools"] = json!(tools); + body["tool_choice"] = json!("auto"); + } + body +} + +fn wire_messages(system: &str, messages: &[Message]) -> Vec { + let mut out = vec![json!({"role": "system", "content": system})]; + for m in messages { + match m.role { + Role::Assistant => { + let mut text = String::new(); + let mut calls = Vec::new(); + for b in &m.blocks { + match b { + Block::Text(t) => text.push_str(t), + Block::ToolCall { id, name, args } => calls.push(json!({ + "id": id, + "type": "function", + "function": {"name": name, "arguments": serde_json::to_string(args).unwrap_or_else(|_| "{}".into())}, + })), + _ => {} + } + } + let mut msg = json!({"role": "assistant", "content": if text.is_empty() { Value::Null } else { json!(text) }}); + if !calls.is_empty() { + msg["tool_calls"] = json!(calls); + } + out.push(msg); + } + Role::User => { + let mut content = Vec::new(); + // Images from tool results cannot ride in the `tool` role's text, so they follow + // in a user message (every compatible endpoint accepts that). + let mut tool_images = Vec::new(); + for b in &m.blocks { + match b { + Block::Text(t) => content.push(json!({"type": "text", "text": t})), + Block::Image(i) => content.push(json!({"type": "image_url", "image_url": {"url": data_url(i)}})), + Block::ToolResult { id, text, images, .. } => { + out.push(json!({"role": "tool", "tool_call_id": id, "content": text})); + tool_images.extend(images.iter().map(data_url)); + } + Block::ToolCall { .. } => {} + } + } + if !content.is_empty() { + out.push(json!({"role": "user", "content": content})); + } + if !tool_images.is_empty() { + let mut parts = vec![json!({"type": "text", "text": "Images from the tool results above:"})]; + for url in tool_images { + parts.push(json!({"type": "image_url", "image_url": {"url": url}})); + } + out.push(json!({"role": "user", "content": parts})); + } + } + } + } + out +} + +fn data_url(image: &crate::neutral::Image) -> String { + format!("data:{};base64,{}", image.mime, image.data) +} + +fn headers(provider: &Provider, session: &str) -> Vec<(&'static str, String)> { + let mut h = vec![("authorization", format!("Bearer {}", provider.api_key.trim())), ("accept", "text/event-stream".to_string())]; + // OpenCode Zen/Go asks for one stable id per conversation, to route it to the same upstream + // and keep its prompt cache warm. + if provider.base_url.contains("opencode.ai") { + h.push(("x-opencode-session", session.to_string())); + } + h +} + +/// Send the conversation and read the streamed answer into a [`Step`]. +pub fn stream( + http: &Http, + provider: &Provider, + system: &str, + messages: &[Message], + tools: &[Value], + session: &str, + on_text: &mut dyn FnMut(&str), + cancel: &AtomicBool, +) -> Result { + let reply = http.post(&provider.endpoint(), &headers(provider, session), &payload(provider, system, messages, tools))?; + if reply.status >= 400 { + return Err(read_error(reply.status, reply.body)); + } + let events = crate::sse::spawn_events(reply.body); + let mut step = Step::default(); + // Whether the endpoint said the answer is over (`finish_reason` or `[DONE]`); a stream that + // just ends without it was cut off. + let mut finished = false; + // Tool calls arrive split across chunks: keyed by their `index`, their name once, their + // arguments as JSON text joined together. + let mut calls: BTreeMap = BTreeMap::new(); + while let Some(event) = crate::sse::next(&events, cancel)? { + let data = event.data.trim(); + if data.is_empty() { + continue; + } + if data == "[DONE]" { + finished = true; + break; + } + let v: Value = match serde_json::from_str(data) { + Ok(v) => v, + // An endpoint may send a keep-alive payload that is not JSON. + Err(_) => continue, + }; + if let Some(err) = v.get("error").filter(|e| !e.is_null()) { + let msg = err.get("message").and_then(Value::as_str).map(str::to_string).unwrap_or_else(|| err.to_string()); + return Err(msg); + } + if let Some(u) = v.get("usage").filter(|u| !u.is_null()) { + step.usage = Usage { + input: u.get("prompt_tokens").and_then(Value::as_u64).unwrap_or(step.usage.input), + output: u.get("completion_tokens").and_then(Value::as_u64).unwrap_or(step.usage.output), + }; + } + let Some(choice) = v.get("choices").and_then(|c| c.get(0)) else { continue }; + if let Some(delta) = choice.get("delta") { + match delta.get("content") { + Some(Value::String(t)) => { + step.text.push_str(t); + on_text(t); + } + Some(Value::Array(parts)) => { + for part in parts { + if part.get("type").and_then(Value::as_str) == Some("text") + && let Some(t) = part.get("text").and_then(Value::as_str) + { + step.text.push_str(t); + on_text(t); + } + } + } + _ => {} + } + if let Some(list) = delta.get("tool_calls").and_then(Value::as_array) { + for tc in list { + let index = tc.get("index").and_then(Value::as_u64).unwrap_or(0); + let entry = calls.entry(index).or_default(); + if let Some(id) = tc.get("id").and_then(Value::as_str) { + entry.0 = id.to_string(); + } + if let Some(name) = tc.get("function").and_then(|f| f.get("name")).and_then(Value::as_str) { + entry.1.push_str(name); + } + if let Some(args) = tc.get("function").and_then(|f| f.get("arguments")).and_then(Value::as_str) { + entry.2.push_str(args); + } + } + } + } + if let Some(reason) = choice.get("finish_reason").and_then(Value::as_str) { + step.stop = reason.to_string(); + finished = true; + } + } + if !finished { + return Err(INTERRUPTED.to_string()); + } + for (i, (id, name, raw)) in calls { + if name.is_empty() { + continue; + } + let id = if id.is_empty() { format!("call_{i}") } else { id }; + step.calls.push(Invocation { id, name, args: parse_args(&raw), args_raw: raw }); + } + Ok(step) +} + +fn parse_args(raw: &str) -> Value { + if raw.trim().is_empty() { + return json!({}); + } + serde_json::from_str(raw).unwrap_or(Value::Null) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::config::ApiKind; + + fn provider() -> Provider { + let mut p = Provider::new("Go", ApiKind::OpenAiCompletions, "https://opencode.ai/zen/go/v1"); + p.model = "deepseek-v4.1-flash".into(); + p.api_key = "sk-test".into(); + p + } + + #[test] + fn tool_calls_and_tool_results_use_the_compatible_shape() { + let mut messages = vec![Message::user_text("hi")]; + messages.push(Message { + role: Role::Assistant, + blocks: vec![ + Block::Text("looking".into()), + Block::ToolCall { id: "call_1".into(), name: "run_command".into(), args: json!({"command": "frame.create"}) }, + ], + }); + messages.push(Message { + role: Role::User, + blocks: vec![Block::ToolResult { id: "call_1".into(), name: "run_command".into(), ok: true, text: "{\"id\":3}".into(), images: vec![] }], + }); + let body = payload(&provider(), "system", &messages, &[]); + let wire = body["messages"].as_array().cloned().unwrap_or_default(); + assert_eq!(wire[0]["role"], "system"); + assert_eq!(wire[1]["content"][0]["text"], "hi"); + assert_eq!(wire[2]["tool_calls"][0]["function"]["name"], "run_command"); + assert_eq!(wire[3]["role"], "tool"); + assert_eq!(wire[3]["tool_call_id"], "call_1"); + } + + #[test] + fn an_image_comes_back_as_a_data_url_on_the_user_message() { + let messages = vec![Message { + role: Role::User, + blocks: vec![Block::Text("what is this".into()), Block::Image(crate::neutral::Image { mime: "image/png".into(), data: "AAAA".into() })], + }]; + let body = payload(&provider(), "s", &messages, &[]); + let parts = body["messages"][1]["content"].as_array().cloned().unwrap_or_default(); + assert_eq!(parts[0]["type"], "text"); + assert_eq!(parts[1]["image_url"]["url"], "data:image/png;base64,AAAA"); + } + + #[test] + fn reasoning_effort_is_sent_only_when_chosen() { + use crate::config::Reasoning; + let mut p = provider(); + let messages = vec![Message::user_text("hi")]; + assert!(payload(&p, "s", &messages, &[]).get("reasoning_effort").is_none(), "Auto leaves it to the endpoint"); + p.reasoning = Reasoning::High; + assert_eq!(payload(&p, "s", &messages, &[])["reasoning_effort"], "high"); + } + + #[test] + fn opencode_gets_a_stable_session_header() { + let h = headers(&provider(), "abc"); + assert!(h.iter().any(|(k, v)| *k == "x-opencode-session" && v == "abc")); + assert!(h.iter().any(|(k, v)| *k == "authorization" && v == "Bearer sk-test")); + } + + #[test] + fn arguments_that_do_not_parse_stay_null_for_the_loop_to_report() { + let mut calls: BTreeMap = BTreeMap::new(); + calls.insert(0, ("id".into(), "run_command".into(), "{broken".into())); + let (_, _, raw) = calls.remove(&0).unwrap_or_default(); + assert!(parse_args(&raw).is_null()); + } +} diff --git a/crates/agent/src/session.rs b/crates/agent/src/session.rs new file mode 100644 index 000000000..30019c840 --- /dev/null +++ b/crates/agent/src/session.rs @@ -0,0 +1,886 @@ +//! The agent loop: send the conversation, stream the answer, run the tools the model asks for on +//! the open window, feed the results back, and repeat until it stops asking for tools. + +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, AtomicU8, Ordering}; +use std::sync::mpsc::Sender; + +use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; + +use crate::config::{ApiKind, Permission, Provider}; +use crate::http::Http; +use crate::neutral::{Block, Message, Role}; +use crate::{Invocation, Step, Usage}; + +/// How many model steps one request may take before the loop stops (each step may run tools). +const MAX_STEPS: usize = 60; +/// Characters of conversation kept before the oldest tool output is shortened, per the model's +/// context window (about three characters a token, with room for the answer). +const CHARS_PER_TOKEN: usize = 3; +/// Tool output longer than this is clipped before the model sees it. +const TOOL_TEXT_MAX: usize = 60_000; +/// The name every command runs as in the app (its avatar, its comment signature). +pub const AGENT_NAME: &str = "FigCraft Agent"; +/// What the agent is told when it is handed the canvas to check its own work. +const REVIEW_PROMPT: &str = "Automatic self-review: the canvas after your changes is attached. \ +Compare it with what the user asked for. Fix anything wrong with the tools (overlap, clipping, \ +spacing, hierarchy, contrast, text that does not fit). If it looks right, reply to the user in one \ +or two sentences; do not take another screenshot for review. +"; + +/// What the worker tells the panel while a request runs. +pub enum ChatEvent { + /// Streamed answer text. + Text(String), + /// A tool call started. + ToolStart { id: String, name: String, args: Value }, + /// A tool call finished (`text` is a short summary for the card). + ToolEnd { id: String, name: String, ok: bool, title: String, text: String }, + /// The agent wants to do something outside the canvas; `reply` takes the person's answer. + Permission { id: String, name: String, args: Value, reason: String, reply: Sender }, + /// Tokens used so far. + Usage(Usage), + /// The request failed (network, provider, a bad answer). + Error(String), + /// The request is over. `stopped`: the person pressed Stop. + Done { stopped: bool }, +} + +/// An agent bound to one window, with the conversation it has had so far. +pub struct Agent { + pub provider: Provider, + pub messages: Vec, + http: Http, + backend: crate::bridge::Remote, + system: String, + tools: Vec, + session: String, + usage: Usage, + /// 0: ask before file and network tools, 1: auto. Shared with the panel's toggle, so changing + /// it mid-request applies to the next tool call. + pub permission: Arc, + /// Whether a turn that changed the canvas ends with the agent looking at it once. + pub review: Arc, + did_edit: bool, + reviewed: bool, + /// The panel's event stream, for tool calls a command-line agent makes over MCP (they arrive + /// on another thread, outside [`run_turn`](Self::run_turn)'s `out`). + pub sink: Option>, + /// Where a command-line agent runs (beside the saved chats); a temporary folder without one. + pub workdir: Option, + /// The command-line agent's conversation to resume, and which program it belongs to. + cli_session: Option<(ApiKind, String)>, + /// FigCraft's tools served to a command-line agent, started on its first turn. + endpoint: Option, + /// Set by the endpoint when the command-line agent changed the document this turn. + cli_edited: Arc, + /// The skills `load_skill` answers from. + pub skills: crate::skills::SkillBook, +} + +impl Agent { + pub fn new(provider: Provider, backend: crate::bridge::Remote) -> Self { + let mut tools = figcraft_mcp::tool_definitions(); + tools.push(crate::skills::tool_definition()); + tools.push(crate::brief::tool_definition()); + let session = format!("figcraft-{}", now_id()); + Self { + provider, + messages: Vec::new(), + http: Http::new(), + backend, + system: system_prompt(), + tools, + session, + usage: Usage::default(), + permission: Arc::new(AtomicU8::new(0)), + review: Arc::new(AtomicBool::new(true)), + did_edit: false, + reviewed: false, + sink: None, + workdir: None, + cli_session: None, + endpoint: None, + cli_edited: Arc::new(AtomicBool::new(false)), + skills: Arc::new(std::sync::RwLock::new(crate::skills::builtins())), + } + } + + /// Switch the model or the connection. A command-line agent's conversation lives in that + /// program, so moving to another one starts a new conversation there. + pub fn set_provider(&mut self, provider: Provider) { + if self.cli_session.as_ref().is_some_and(|(kind, _)| *kind != provider.kind) { + self.cli_session = None; + } + self.provider = provider; + } + + /// The permission the panel's toggle holds now. + fn permission(&self) -> Permission { + if self.permission.load(Ordering::Relaxed) == 1 { Permission::Auto } else { Permission::AskFiles } + } + + pub fn usage(&self) -> Usage { + self.usage + } + + /// Forget the conversation (a new chat), keeping the provider and tools. + pub fn clear(&mut self) { + self.messages.clear(); + self.usage = Usage::default(); + self.cli_session = None; + } + + /// Run one request to completion. Reports everything through `out`; returns the error the + /// panel shows as a failed turn (the loop's own stops are not errors). + pub fn run_turn(&mut self, text: &str, context: Option, out: &dyn Fn(ChatEvent), cancel: &Arc) -> Result<(), String> { + self.run_turn_with(text, context, Vec::new(), out, cancel) + } + + /// [`run_turn`](Self::run_turn) with images the person attached. + pub fn run_turn_with( + &mut self, + text: &str, + context: Option, + images: Vec, + out: &dyn Fn(ChatEvent), + cancel: &Arc, + ) -> Result<(), String> { + let mut prompt = String::new(); + if let Some(c) = context.filter(|c| !c.trim().is_empty()) { + prompt.push_str(&c); + prompt.push_str("\n\n"); + } + prompt.push_str(text); + if self.provider.kind.is_cli() { + return self.run_cli_turn(&prompt, &images, out, cancel); + } + let mut message = Message::user_text(prompt); + // A model that reads no images is told what was left out rather than failing the request. + if self.provider.vision { + message.blocks.extend(images.into_iter().map(Block::Image)); + } else if !images.is_empty() { + message.blocks.push(Block::Text(format!("[{} attached image(s) left out: this model does not read images]", images.len()))); + } + self.messages.push(message); + self.did_edit = false; + self.reviewed = false; + self.trim(); + if self.messages.last().map(message_chars).unwrap_or(0) > self.budget() { + self.messages.pop(); + return Err("this request is too large for the model's context window; attach fewer or smaller images, or shorten it".into()); + } + + for _step in 0..MAX_STEPS { + if cancel.load(Ordering::Relaxed) { + out(ChatEvent::Done { stopped: true }); + return Ok(()); + } + let step = match self.stream(out, cancel) { + Ok(step) => step, + Err(e) if e == "stopped" => { + out(ChatEvent::Done { stopped: true }); + return Ok(()); + } + Err(e) => return Err(e), + }; + let mut blocks = Vec::new(); + if !step.text.is_empty() { + blocks.push(Block::Text(step.text.clone())); + } + // An answer cut off at the output limit may end inside a tool call's arguments: keep + // its text, run none of its calls, and say so. + if matches!(step.stop.as_str(), "length" | "max_tokens") { + if !blocks.is_empty() { + self.messages.push(Message { role: Role::Assistant, blocks }); + } + return Err("the answer hit the model's output limit before it finished; ask the agent to continue".into()); + } + for call in &step.calls { + blocks.push(Block::ToolCall { id: call.id.clone(), name: call.name.clone(), args: call.args.clone() }); + } + if !blocks.is_empty() { + self.messages.push(Message { role: Role::Assistant, blocks }); + } + if step.calls.is_empty() { + // One look at the canvas after a turn that changed it, when the model can see. + if self.review.load(Ordering::Relaxed) && self.provider.vision && self.did_edit && !self.reviewed { + self.reviewed = true; + if self.review_once(out, cancel) { + continue; + } + } + out(ChatEvent::Usage(self.usage)); + out(ChatEvent::Done { stopped: false }); + return Ok(()); + } + let mut results = Vec::new(); + let mut stopped = false; + for call in step.calls { + // Every call gets a result, run or not: a call without one fails the next request. + if stopped || cancel.load(Ordering::Relaxed) { + stopped = true; + results.push(Block::ToolResult { + id: call.id, + name: call.name, + ok: false, + text: "Not run: the user stopped the agent".into(), + images: vec![], + }); + continue; + } + let outcome = self.run_tool(call, out, cancel); + results.push(outcome); + } + self.messages.push(Message { role: Role::User, blocks: results }); + if stopped { + out(ChatEvent::Done { stopped: true }); + return Ok(()); + } + self.trim(); + } + out(ChatEvent::Done { stopped: false }); + Err(format!("the agent stopped after {MAX_STEPS} steps without finishing; ask it to continue")) + } + + /// One turn through an installed command-line agent: it runs its own loop and calls + /// FigCraft's tools over MCP; the tool cards reach the panel from the MCP side. + fn run_cli_turn( + &mut self, + prompt: &str, + images: &[crate::neutral::Image], + out: &dyn Fn(ChatEvent), + cancel: &Arc, + ) -> Result<(), String> { + self.cli_edited.store(false, Ordering::Relaxed); + if self.cli_pass(prompt, images, out, cancel)? { + out(ChatEvent::Done { stopped: true }); + return Ok(()); + } + // One look at the canvas after a turn that changed it, as the API connections do: the + // program gets the picture in the same conversation and fixes what it sees. + if self.review.load(Ordering::Relaxed) + && self.cli_edited.load(Ordering::Relaxed) + && !cancel.load(Ordering::Relaxed) + && let Some(image) = self.look(out) + { + // The request itself is done; a model that can't take the picture leaves it at that. + match self.cli_pass(REVIEW_PROMPT, &[image], out, cancel) { + Ok(true) => { + out(ChatEvent::Done { stopped: true }); + return Ok(()); + } + Ok(false) => {} + Err(e) => out(ChatEvent::Text(format!("(The check of the result did not run: {})", crate::neutral::clip(&e, 200)))), + } + } + out(ChatEvent::Done { stopped: false }); + Ok(()) + } + + /// Run the command-line agent once; `true` when the person stopped it. + fn cli_pass( + &mut self, + prompt: &str, + images: &[crate::neutral::Image], + out: &dyn Fn(ChatEvent), + cancel: &Arc, + ) -> Result { + let kind = self.provider.kind; + let program = crate::cli::locate(kind) + .ok_or_else(|| format!("{} is not installed on this computer; install it or pick another connection", kind.label()))?; + if self.endpoint.is_none() { + let sink = self.sink.clone().ok_or_else(|| "the agent has no panel to report to".to_string())?; + let gate = crate::mcp_http::Gate { + permission: self.permission.clone(), + sink, + cancel: cancel.clone(), + edited: self.cli_edited.clone(), + skills: self.skills.clone(), + }; + let endpoint = crate::mcp_http::start(self.backend.clone(), gate).map_err(|e| format!("can't serve FigCraft's tools: {e}"))?; + self.endpoint = Some(endpoint); + } + let endpoint = self.endpoint.as_ref().ok_or_else(|| "can't serve FigCraft's tools".to_string())?; + let workdir = self.workdir.clone().unwrap_or_else(|| std::env::temp_dir().join("figcraft-agent")); + let session = self.cli_session.as_ref().filter(|(k, _)| *k == kind).map(|(_, s)| s.clone()); + let system = app_rules(); + let turn = crate::cli::Turn { + kind, + program: &program, + model: &self.provider.model, + session: session.as_deref(), + prompt, + system: &system, + mcp_url: &endpoint.url, + mcp_token: &endpoint.token, + workdir: &workdir, + images, + }; + let mut on_text = |t: &str| out(ChatEvent::Text(t.to_string())); + let outcome = crate::cli::run(&turn, &mut on_text, cancel); + if let Some(s) = outcome.session { + self.cli_session = Some((kind, s)); + } + self.usage.input = self.usage.input.saturating_add(outcome.usage.input); + self.usage.output = self.usage.output.saturating_add(outcome.usage.output); + out(ChatEvent::Usage(self.usage)); + if outcome.stopped { + return Ok(true); + } + match outcome.error { + Some(e) => Err(e), + None => Ok(false), + } + } + + fn stream(&mut self, out: &dyn Fn(ChatEvent), cancel: &Arc) -> Result { + let mut on_text = |t: &str| { + out(ChatEvent::Text(t.to_string())); + }; + // A model that reads no images gets none, also from earlier in the conversation (a chat + // begun on another connection); the saved conversation keeps them. + let filtered; + let messages: &[Message] = if self.provider.vision { + &self.messages + } else { + filtered = without_images(&self.messages); + &filtered + }; + let result = match self.provider.kind { + ApiKind::OpenAiCompletions => { + crate::openai::stream(&self.http, &self.provider, &self.system, messages, &self.tools, &self.session, &mut on_text, cancel) + } + ApiKind::AnthropicMessages => { + crate::anthropic::stream(&self.http, &self.provider, &self.system, messages, &self.tools, &self.session, &mut on_text, cancel) + } + ApiKind::ClaudeCode | ApiKind::Codex | ApiKind::OpenCode => Err("a command-line agent runs its own loop".to_string()), + }; + if let Ok(step) = &result { + self.usage.input = self.usage.input.saturating_add(step.usage.input); + self.usage.output = self.usage.output.saturating_add(step.usage.output); + out(ChatEvent::Usage(self.usage)); + } + result + } + + fn run_tool(&mut self, call: Invocation, out: &dyn Fn(ChatEvent), cancel: &Arc) -> Block { + out(ChatEvent::ToolStart { id: call.id.clone(), name: call.name.clone(), args: call.args.clone() }); + let denied = |reason: String| Block::ToolResult { + id: call.id.clone(), + name: call.name.clone(), + ok: false, + text: format!("Not run: {reason}"), + images: vec![], + }; + if call.args.is_null() { + return denied("the model sent arguments that are not valid JSON; try again".into()); + } + if call.name == crate::brief::TOOL_NAME { + let (text, ok) = crate::brief::call(&mut self.backend, &call.args); + if ok && (call.args.get("spec").is_some() || call.args.get("brief").is_some()) { + self.did_edit = true; + } + out(ChatEvent::ToolEnd { + id: call.id.clone(), + name: call.name.clone(), + ok, + title: tool_title(&call.name, &call.args), + text: summarize(&text), + }); + return Block::ToolResult { id: call.id, name: call.name, ok, text, images: vec![] }; + } + if call.name == crate::skills::TOOL_NAME { + let (text, ok) = crate::skills::call(&self.skills, &call.args); + out(ChatEvent::ToolEnd { + id: call.id.clone(), + name: call.name.clone(), + ok, + title: tool_title(&call.name, &call.args), + text: summarize(&text), + }); + return Block::ToolResult { id: call.id, name: call.name, ok, text, images: vec![] }; + } + if let Some(reason) = approval(&call.name, &call.args) + && self.permission() == Permission::AskFiles + { + let (tx, rx) = std::sync::mpsc::channel(); + out(ChatEvent::Permission { id: call.id.clone(), name: call.name.clone(), args: call.args.clone(), reason: reason.clone(), reply: tx }); + let allowed = rx.recv_timeout(std::time::Duration::from_secs(600)).unwrap_or(false); + if !allowed { + let result = denied(format!("the user denied this action ({reason})")); + out(ChatEvent::ToolEnd { + id: call.id.clone(), + name: call.name.clone(), + ok: false, + title: call.name.clone(), + text: "Denied by the user".into(), + }); + return result; + } + } + if cancel.load(Ordering::Relaxed) { + return denied("the user stopped the agent".into()); + } + let result = figcraft_mcp::call_tool(&mut self.backend, &call.name, &call.args); + if !result.is_error && mutating(&call.name, &call.args) { + self.did_edit = true; + } + let (text, mut images) = crate::neutral::tool_output(&result); + // A model that does not read images gets the text alone: sending one would fail the + // whole request (some endpoints reject it). + if !self.provider.vision { + images.clear(); + } + let text = crate::neutral::clip(&text, TOOL_TEXT_MAX); + out(ChatEvent::ToolEnd { + id: call.id.clone(), + name: call.name.clone(), + ok: !result.is_error, + title: tool_title(&call.name, &call.args), + text: summarize(&text), + }); + Block::ToolResult { id: call.id, name: call.name, ok: !result.is_error, text, images } + } + + /// Capture the page and hand it back to the model for one review pass. `true` when the image + /// is now in the conversation (the loop continues); `false` when there is nothing to see. + fn review_once(&mut self, out: &dyn Fn(ChatEvent), cancel: &Arc) -> bool { + if cancel.load(Ordering::Relaxed) { + return false; + } + match self.look(out) { + Some(image) => { + self.messages.push(Message { role: Role::User, blocks: vec![Block::Text(REVIEW_PROMPT.into()), Block::Image(image)] }); + true + } + None => false, + } + } + + /// Capture the page for a review, shown as a step in the panel. + fn look(&mut self, out: &dyn Fn(ChatEvent)) -> Option { + let id = "self-review".to_string(); + out(ChatEvent::ToolStart { id: id.clone(), name: "screenshot".into(), args: json!({}) }); + let result = figcraft_mcp::call_tool(&mut self.backend, "screenshot", &json!({})); + let (text, images) = crate::neutral::tool_output(&result); + let image = images.into_iter().next().filter(|_| !result.is_error); + out(ChatEvent::ToolEnd { + id, + name: "screenshot".into(), + ok: image.is_some(), + title: "Checking the result".into(), + text: if image.is_some() { "Looking at the canvas".into() } else { crate::neutral::clip(&text, 200) }, + }); + image + } + + /// Save the model's conversation beside the document's chat. + pub fn save_history(&self, path: &Path) -> Result<(), String> { + let (cli_kind, cli_session) = match &self.cli_session { + Some((k, s)) => (Some(*k), Some(s.clone())), + None => (None, None), + }; + let file = ContextFile { version: 1, messages: self.messages.clone(), usage: self.usage, cli_kind, cli_session }; + let bytes = serde_json::to_vec(&file).map_err(|e| format!("can't encode the conversation: {e}"))?; + crate::config::write_private(path, &bytes) + } + + /// Read back a conversation saved by [`save_history`](Self::save_history). + pub fn load_history(&mut self, path: &Path) -> Result<(), String> { + let bytes = std::fs::read(path).map_err(|e| format!("can't read {}: {e}", path.display()))?; + let file: ContextFile = serde_json::from_slice(&bytes).map_err(|e| format!("{} is damaged: {e}", path.display()))?; + if file.version != 1 { + return Err(format!("{} was saved by another version", path.display())); + } + self.messages = file.messages; + self.usage = file.usage; + self.cli_session = file.cli_kind.zip(file.cli_session); + self.trim(); + Ok(()) + } + + /// Shorten the oldest tool output when the conversation grows past what the model's context + /// window takes, so a long session keeps its shape without resending megabytes. + fn trim(&mut self) { + let budget = self.budget(); + trim_messages(&mut self.messages, budget); + } + + /// Characters of conversation the model's context window takes, with room for the answer. + fn budget(&self) -> usize { + (self.provider.context_window as usize).saturating_mul(CHARS_PER_TOKEN).saturating_sub(24_000).clamp(60_000, 800_000) + } +} + +/// The conversation without its images, for a model that reads none; each left-out image is named +/// so the model knows something was there. +fn without_images(messages: &[Message]) -> Vec { + messages + .iter() + .map(|m| { + let mut blocks = Vec::with_capacity(m.blocks.len()); + for b in &m.blocks { + match b { + Block::Image(_) => blocks.push(Block::Text("[an image left out: this model does not read images]".into())), + Block::ToolResult { id, name, ok, text, images } if !images.is_empty() => blocks.push(Block::ToolResult { + id: id.clone(), + name: name.clone(), + ok: *ok, + text: format!("{text}\n[{} image(s) left out: this model does not read images]", images.len()), + images: vec![], + }), + other => blocks.push(other.clone()), + } + } + Message { role: m.role, blocks } + }) + .collect() +} + +/// Shorten the oldest messages until the conversation fits `budget`, keeping the last eight +/// messages whole: the recent steps are what the model is working from. First old tool output and +/// images go, then long old text; messages stay, so every tool call keeps its result. +fn trim_messages(messages: &mut [Message], budget: usize) { + let keep = messages.len().saturating_sub(8); + let mut total: usize = messages.iter().map(message_chars).sum(); + for pass in 0..2 { + let mut i = 0; + while total > budget && i < keep { + let before = message_chars(&messages[i]); + for block in &mut messages[i].blocks { + match block { + Block::ToolResult { text, images, .. } if pass == 0 => { + if text.len() > 200 { + *text = "[older tool output left out]".to_string(); + } + images.clear(); + } + Block::Image(_) if pass == 0 => *block = Block::Text("[older image left out]".into()), + Block::Text(t) if pass == 1 && t.len() > 2_000 => *t = "[older message shortened]".to_string(), + _ => {} + } + } + let after = message_chars(&messages[i]); + total = total.saturating_sub(before.saturating_sub(after)); + i += 1; + } + } +} + +#[derive(Serialize, Deserialize)] +struct ContextFile { + version: u32, + messages: Vec, + usage: Usage, + /// A command-line agent's conversation id, resumed on the next turn. + #[serde(default, skip_serializing_if = "Option::is_none")] + cli_kind: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + cli_session: Option, +} + +/// Whether a tool call can change what the canvas looks like (so a look at it is worth a review). +pub(crate) fn mutating(name: &str, args: &Value) -> bool { + match name { + "create_node" | "set_properties" | "batch" | "undo" | "redo" => true, + crate::brief::TOOL_NAME => args.get("spec").is_some() || args.get("brief").is_some(), + "run_command" => { + let cmd = args.get("command").and_then(Value::as_str).unwrap_or(""); + !(cmd.starts_with("inspect.") + || cmd.starts_with("variable.list") + || cmd.starts_with("style.list") + || cmd == "design.audit" + || cmd == "design.assert" + || cmd == "design.rules" + || cmd == "node.find" + || cmd == "comment.list" + || cmd == "text.fonts" + || cmd == "text.missingFonts" + || cmd == "image.presets" + || cmd == "list_commands") + } + _ => false, + } +} + +fn message_chars(m: &Message) -> usize { + m.blocks + .iter() + .map(|b| match b { + Block::Text(t) => t.len(), + Block::Image(i) => i.data.len(), + Block::ToolCall { name, args, .. } => name.len() + args.to_string().len(), + Block::ToolResult { text, images, .. } => text.len() + images.iter().map(|i| i.data.len()).sum::(), + }) + .sum() +} + +pub(crate) fn summarize(text: &str) -> String { + let first = text.lines().find(|l| !l.trim().is_empty()).unwrap_or("").trim(); + let mut s: String = first.chars().take(160).collect(); + if first.chars().count() > 160 { + s.push('…'); + } + s +} + +/// The card's title: the tool's own name plus what it acted on. +pub(crate) fn tool_title(name: &str, args: &Value) -> String { + if name == crate::skills::TOOL_NAME { + return format!("Skill: {}", args.get("name").and_then(Value::as_str).unwrap_or("")); + } + if name == crate::brief::TOOL_NAME { + return if args.get("spec").is_some() || args.get("brief").is_some() { + "Design system: make the 00 · Design System page".into() + } else { + "Design system: read the 00 · Design System page".into() + }; + } + if name == "run_command" + && let Some(cmd) = args.get("command").and_then(Value::as_str) + { + return cmd.to_string(); + } + name.to_string() +} + +/// Why a tool needs the person's Allow, or `None` when it only changes the canvas. +/// +/// Canvas edits (layers, styles, variables, components, layout, selection, undo) run at once; a +/// tool that reads or writes a file, joins a server, installs a plugin or downloads a font asks. +pub fn approval(tool: &str, args: &Value) -> Option { + match tool { + "open_file" => Some("reads a file".into()), + "save_file" => Some("writes the document to a file".into()), + "export" => Some("writes an export to a file".into()), + "export_assets" => Some("writes assets into a project folder".into()), + "sync_mappings" => Some("reads or writes figcraft.connect.json".into()), + "compare_design" => Some("reads a capture from disk".into()), + "component_mappings" => Some("reads a code project".into()), + "run_command" => { + let cmd = args.get("command").and_then(Value::as_str).unwrap_or(""); + command_reason(cmd).or_else(|| if cmd == "command.batch" { batch_reason(args.get("params"), 0) } else { None }) + } + "batch" => batch_reason(Some(args), 0), + _ => None, + } +} + +/// The first reason a step of a batch needs the person's Allow, nested batches included. +fn batch_reason(params: Option<&Value>, depth: usize) -> Option { + // Deeper than the engine accepts: refuse to guess, ask. + if depth > 16 { + return Some("runs deeply nested commands".into()); + } + params?.get("commands")?.as_array()?.iter().find_map(|step| { + let cmd = step.get("command").and_then(Value::as_str).unwrap_or(""); + command_reason(cmd).or_else(|| if cmd == "command.batch" { batch_reason(step.get("params"), depth + 1) } else { None }) + }) +} + +fn command_reason(cmd: &str) -> Option { + let file = [ + "file.open", + "file.save", + "file.saveAs", + "file.export", + "file.import", + "file.revert", + "file.recover", + "file.placeImage", + "file.exportSvg", + "file.exportLayers", + "file.exportFramesPdf", + "file.openRecent", + ]; + if file.iter().any(|p| cmd.starts_with(p)) { + return Some("reads or writes a file".into()); + } + if cmd.starts_with("collab.") { + return Some("reaches a collaboration server".into()); + } + if ["plugin.", "plugins.", "library.", "libraries."].iter().any(|p| cmd.starts_with(p)) { + return Some("installs or runs a plugin, or reaches a library server".into()); + } + if cmd == "pref.publishServer" { + return Some("changes where shared files are sent".into()); + } + if cmd.starts_with("font.download") { + return Some("downloads a font".into()); + } + if cmd.starts_with("variable.import") || cmd.starts_with("variable.export") || cmd.starts_with("codeConnect.") { + return Some("reads or writes a file".into()); + } + if cmd == "image.place" || cmd == "image.replace" { + return Some("reads an image file".into()); + } + None +} + +/// The instructions an in-app agent gets: the MCP conventions the external clients get, plus how +/// this one is expected to behave in front of the person. +pub fn system_prompt() -> String { + format!("{}\n\n---\n{}", figcraft_mcp::INSTRUCTIONS, app_rules()) +} + +/// How the in-app agent behaves in front of the person. A command-line agent gets these alone: +/// FigCraft's tool conventions reach it through the MCP server's own instructions. +pub fn app_rules() -> String { + "You are the FigCraft agent, running inside the window the user has open. \ +They see every change on the canvas as you make it.\n\ +- Work in small steps and verify with `screenshot` (or `design_context`) before claiming a screen is done.\n\ +- The user's current selection is given with each request; change that unless they name something else.\n\ +- Prefer auto layout, components and variables over absolutely placed copies.\n\ +- Read and change the file freely: every page and layer is yours to inspect (design_context, inspect_document, get_node, screenshot) \ +and to edit (create_node, set_properties, batch, run_command with any command: pages, layers, components, variables, styles, prototype). \ +Pages are part of the file's structure, like components: the request lists them with their frames. The design system lives on the page \ +'00 · Design System'; screens go on pages named by flow or area (create one with page.add when none fits). A page the user names with @ \ +means the frames on it.\n\ +- Keep the reply short: say what you changed and which frames it touched. Do not describe the tool calls one by one.\n\ +- If a tool is denied or fails, say so plainly and continue with what you can do.\n\ +\n\ +How you work on a design request (new screens, pages, flows or components; not small edits to existing layers):\n\ +1. Foundations first. The file must have the page '00 · Design System'. If the request's page list has none, call `design_system` (no arguments) to check, \ +then propose a design system from what the user said: product and platform, primary colour (and secondary or accent if it helps), greys, light/dark, \ +heading and body fonts, corners, shadows, an open-source icon set and its style, tone and copy language. Give it in a few short lines and ask the user \ +to confirm or change it; stop there. When the user confirms (or asked you to go ahead without asking), call `design_system` with the spec: it makes \ +the page, the variables, the styles and the guidelines. Then lay out the foundations and base components on that page (the `Design system setup` skill). \ +When the page exists, read it first (`design_system` with no arguments for its guidelines, design_context for its frames).\n\ +2. Design with the system: Theme colours as {$var: name}, Sizes for spacing and corners, the text and shadow styles, existing components; \ +icons drawn in the brief's set and style, never emoji. Add a raw value only when nothing fits, and say so.\n\ +3. Before you say it is done, load the `Design review` skill and follow it: `design.audit` on what you made, `design.fix` for what it can repair, \ +then a screenshot for what no rule measures; fix what is safe to fix." + .to_string() +} + +fn now_id() -> u128 { + std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_nanos()).unwrap_or(0) +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + #[test] + fn canvas_edits_need_no_approval_but_files_do() { + assert!(approval("create_node", &json!({})).is_none()); + assert!(approval("set_properties", &json!({})).is_none()); + assert!(approval("run_command", &json!({"command": "node.set"})).is_none()); + assert!(approval("run_command", &json!({"command": "file.save"})).is_some()); + assert!(approval("run_command", &json!({"command": "collab.host"})).is_some()); + assert!(approval("save_file", &json!({})).is_some()); + for cmd in ["plugins.runLast", "libraries.publish", "pref.publishServer"] { + assert!(approval("run_command", &json!({"command": cmd})).is_some(), "{cmd}"); + } + assert!(approval("screenshot", &json!({})).is_none()); + // Pages and the canvas are the agent's to read and change. + for cmd in + ["page.add", "page.select", "page.rename", "page.move", "page.delete", "object.moveToPage", "node.set", "variable.create", "design.fix"] + { + assert!(approval("run_command", &json!({"command": cmd})).is_none(), "{cmd}"); + } + assert!(approval("design_system", &json!({"spec": {}})).is_none()); + } + + #[test] + fn a_file_command_inside_a_batch_still_asks() { + let nested = json!({"commands": [{"command": "node.set"}, {"command": "command.batch", "params": {"commands": [{"command": "file.save"}]}}]}); + assert!(approval("batch", &nested).is_some()); + assert!(approval("run_command", &json!({"command": "command.batch", "params": nested})).is_some()); + assert!(approval("batch", &json!({"commands": [{"command": "node.set"}]})).is_none()); + } + + #[test] + fn old_images_go_even_beside_short_text() { + let image = crate::neutral::Image { mime: "image/png".into(), data: "A".repeat(5_000) }; + let mut messages: Vec = (0..30) + .map(|_| Message { + role: Role::User, + blocks: vec![Block::ToolResult { + id: "t".into(), + name: "screenshot".into(), + ok: true, + text: "ok".into(), + images: vec![image.clone()], + }], + }) + .collect(); + trim_messages(&mut messages, 60_000); + let total: usize = messages.iter().map(message_chars).sum(); + assert!(total <= 60_000, "fits the budget: {total}"); + } + + #[test] + fn a_text_only_model_gets_no_image_from_earlier_in_the_chat() { + let messages = vec![Message { + role: Role::User, + blocks: vec![Block::Text("look".into()), Block::Image(crate::neutral::Image { mime: "image/png".into(), data: "AAAA".into() })], + }]; + let sent = without_images(&messages); + assert!(!sent[0].blocks.iter().any(|b| matches!(b, Block::Image(_)))); + assert!(matches!(messages[0].blocks[1], Block::Image(_)), "the conversation itself keeps it"); + } + + #[test] + fn trimming_shortens_the_oldest_output_and_keeps_the_last_steps_whole() { + let mut messages: Vec = (0..40) + .map(|_| Message { + role: Role::User, + blocks: vec![Block::ToolResult { + id: "t".into(), + name: "inspect_document".into(), + ok: true, + text: "x".repeat(5_000), + images: vec![], + }], + }) + .collect(); + let before: usize = messages.iter().map(message_chars).sum(); + let budget = 60_000; + assert!(before > budget); + trim_messages(&mut messages, budget); + let after: usize = messages.iter().map(message_chars).sum(); + assert!(after <= budget, "fits the budget"); + assert_eq!(messages.len(), 40, "messages stay, their bulk goes"); + match &messages[0].blocks[0] { + Block::ToolResult { text, .. } => assert_eq!(text, "[older tool output left out]"), + _ => panic!("a tool result"), + } + match &messages[39].blocks[0] { + Block::ToolResult { text, .. } => assert_eq!(text.len(), 5_000, "the newest step is untouched"), + _ => panic!("a tool result"), + } + } + + #[test] + fn the_conversation_round_trips_through_its_file() { + let dir = std::env::temp_dir().join(format!("figcraft-conv-{}", std::process::id())); + std::fs::create_dir_all(&dir).expect("dir"); + let path = dir.join("chat.context.json"); + let mut p = Provider::new("Go", ApiKind::OpenAiCompletions, "https://example.test/v1"); + p.model = "m".into(); + let (bridge, remote) = crate::bridge::pair("Test", Arc::new(|| {})); + drop(bridge); + let mut agent = Agent::new(p.clone(), remote); + agent.messages.push(Message::user_text("hello")); + agent.usage.input = 12; + agent.save_history(&path).expect("saved"); + let (bridge, remote) = crate::bridge::pair("Test", Arc::new(|| {})); + drop(bridge); + let mut back = Agent::new(p, remote); + back.load_history(&path).expect("loaded"); + assert_eq!(back.messages.len(), 1); + assert_eq!(back.usage.input, 12); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn a_card_title_names_the_command() { + assert_eq!(tool_title("run_command", &json!({"command": "frame.create"})), "frame.create"); + assert_eq!(tool_title("screenshot", &json!({})), "screenshot"); + } +} diff --git a/crates/agent/src/skills.rs b/crates/agent/src/skills.rs new file mode 100644 index 000000000..b00c58ec1 --- /dev/null +++ b/crates/agent/src/skills.rs @@ -0,0 +1,307 @@ +//! Skills: named instructions for a kind of work (a mobile screen, a landing page, a review…). +//! +//! A skill is a Markdown file with a small header: +//! +//! ```text +//! --- +//! name: Landing page +//! description: When to use it, in one line (the model reads this to decide). +//! --- +//! The instructions. +//! ``` +//! +//! The app ships a few (built in, read-only); the person's own live in `agent-skills/` beside +//! `agents.json`, and one with the same name as a built-in one replaces it. The person attaches a +//! skill to a request with `/` in the composer; the model sees the list (names and descriptions) +//! and loads one it needs with the `load_skill` tool, so only the skills used cost tokens. + +use std::path::{Path, PathBuf}; +use std::sync::{Arc, RwLock}; + +use serde_json::{Value, json}; + +/// The tool the model loads a skill with. +pub const TOOL_NAME: &str = "load_skill"; + +/// The longest skill body kept (a skill is instructions, not a document). +const MAX_BODY: usize = 20_000; + +#[derive(Clone, Debug, PartialEq)] +pub struct Skill { + pub name: String, + pub description: String, + pub body: String, + /// Shipped with the app (read-only). + pub builtin: bool, + /// The person's file, for one of their own. + pub file: Option, +} + +/// The skills the agent can load, shared between the panel (which keeps it current) and the agent +/// thread (which answers `load_skill`). +pub type SkillBook = Arc>>; + +/// Read a skill file's text: its header's name and description, and the body after it. +pub fn parse(text: &str) -> Option<(String, String, String)> { + let text = text.trim_start_matches('\u{feff}'); + let rest = text.strip_prefix("---")?; + let end = rest.find("\n---")?; + let (head, body) = (&rest[..end], &rest[end + 4..]); + let field = |key: &str| { + head.lines().find_map(|l| { + let (k, v) = l.split_once(':')?; + (k.trim().eq_ignore_ascii_case(key)).then(|| v.trim().trim_matches('"').to_string()) + }) + }; + let name = field("name").filter(|n| !n.is_empty())?; + let description = field("description").unwrap_or_default(); + let body = body.trim_start_matches(['\r', '\n']).trim_end().to_string(); + Some((name, description, body)) +} + +/// A skill as the text of its file. +pub fn to_text(name: &str, description: &str, body: &str) -> String { + let one_line = |s: &str| s.replace(['\r', '\n'], " ").trim().to_string(); + format!("---\nname: {}\ndescription: {}\n---\n{}\n", one_line(name), one_line(description), body.trim()) +} + +/// The built-in skills and the person's own from `dir` (theirs replace a built-in one of the same +/// name), sorted by name. +pub fn load(dir: Option<&Path>) -> Vec { + let mut skills = builtins(); + let mut own = Vec::new(); + if let Some(dir) = dir + && let Ok(entries) = std::fs::read_dir(dir) + { + for e in entries.flatten() { + let path = e.path(); + if path.extension().and_then(|x| x.to_str()) != Some("md") { + continue; + } + let Ok(text) = std::fs::read_to_string(&path) else { continue }; + if let Some((name, description, body)) = parse(&text) { + let body = crate::neutral::clip(&body, MAX_BODY); + own.push(Skill { name, description, body, builtin: false, file: Some(path) }); + } + } + } + for s in own { + skills.retain(|b| !b.name.eq_ignore_ascii_case(&s.name)); + skills.push(s); + } + skills.sort_by_key(|s| s.name.to_lowercase()); + skills +} + +/// Write one of the person's skills to `dir` (replacing `old`, its file before a rename). +pub fn save(dir: &Path, name: &str, description: &str, body: &str, old: Option<&Path>) -> Result { + let name = name.trim(); + if name.is_empty() { + return Err("a skill needs a name".into()); + } + std::fs::create_dir_all(dir).map_err(|e| format!("can't create {}: {e}", dir.display()))?; + let path = dir.join(format!("{}.md", slug(name))); + let text = to_text(name, description, body); + let write_err = |e: std::io::Error| format!("can't write {}: {e}", path.display()); + // Two names can share a file name ("Brand voice", "Brand-voice"): only this skill's own file is + // replaced; any other file there, unreadable or not a skill included, is left alone. + let own = old == Some(path.as_path()) + || std::fs::read_to_string(&path).ok().and_then(|t| parse(&t)).is_some_and(|(other, _, _)| other.eq_ignore_ascii_case(name)); + if own { + std::fs::write(&path, text).map_err(write_err)?; + } else { + use std::io::Write as _; + let mut file = std::fs::OpenOptions::new().write(true).create_new(true).open(&path).map_err(|e| { + if e.kind() == std::io::ErrorKind::AlreadyExists { + format!("another file is saved as {}; give this skill a different name", path.display()) + } else { + write_err(e) + } + })?; + file.write_all(text.as_bytes()).map_err(write_err)?; + } + if let Some(old) = old + && old != path + { + let _ = std::fs::remove_file(old); + } + Ok(path) +} + +/// A file name for a skill's name. +fn slug(name: &str) -> String { + let s: String = name.chars().map(|c| if c.is_alphanumeric() { c.to_ascii_lowercase() } else { '-' }).collect(); + let s = s.split('-').filter(|p| !p.is_empty()).collect::>().join("-"); + if s.is_empty() { "skill".into() } else { s.chars().take(60).collect() } +} + +/// The skill named `name` (case does not matter). +pub fn find(book: &SkillBook, name: &str) -> Option { + let name = name.trim().trim_start_matches('/'); + book.read().ok()?.iter().find(|s| s.name.eq_ignore_ascii_case(name)).cloned() +} + +/// What the model is told about the skills it can load. +pub fn catalog(skills: &[Skill]) -> Option { + if skills.is_empty() { + return None; + } + let mut text = format!( + "[Skills: instructions for kinds of work. When one fits the request, call `{TOOL_NAME}` with its name before you start, and follow it.]" + ); + for s in skills { + text.push_str(&format!("\n- {}: {}", s.name, s.description)); + } + Some(text) +} + +/// The `load_skill` tool, as the tool list has it. +pub fn tool_definition() -> Value { + json!({ + "name": TOOL_NAME, + "description": "Load a skill: instructions for a kind of work (the list of skills comes with the request). Call it before starting work that a skill fits.", + "inputSchema": { + "type": "object", + "properties": {"name": {"type": "string", "description": "The skill's name, as listed"}}, + "required": ["name"] + } + }) +} + +/// Answer a `load_skill` call: the skill's instructions, or why not (`false`). +pub fn call(book: &SkillBook, args: &Value) -> (String, bool) { + let name = args.get("name").and_then(Value::as_str).unwrap_or(""); + match find(book, name) { + Some(s) => (format!("Skill \"{}\":\n{}", s.name, s.body), true), + None => { + let names: Vec = book.read().map(|b| b.iter().map(|s| s.name.clone()).collect()).unwrap_or_default(); + (format!("No skill named \"{name}\". Skills: {}", names.join(", ")), false) + } + } +} + +fn builtin(name: &str, description: &str, body: &str) -> Skill { + Skill { name: name.into(), description: description.into(), body: body.trim().into(), builtin: true, file: None } +} + +/// The skills that come with the app (our own wording). +pub fn builtins() -> Vec { + vec![ + builtin( + "Mobile app screen", + "Designing a phone app screen or flow (iOS or Android).", + r#" +- One frame per screen, 390 x 844, named after the screen. Several screens sit in a row, 80 apart. +- Vertical auto layout for the screen; leave 47 at the top (status bar) and 34 at the bottom (home indicator). +- Padding 16 or 20 at the sides; spacing in steps of 4 (8, 12, 16, 24, 32). +- Touch targets at least 44 high; primary action at the bottom, full width, within thumb reach. +- Type: title 28-34 bold, section 17-20 semibold, body 15-17, caption 12-13. At most three sizes per screen. +- Navigation: a top bar with title and back, or a bottom tab bar with 3-5 items (icon and label). +- Use the file's variables, styles and components first; make a component for anything repeated. +- Real copy, not lorem ipsum, in the language the user writes in. +"#, + ), + builtin( + "Landing page", + "Designing a marketing website page or section (desktop first).", + r#" +- A 1440 wide frame, content at most 1200 wide and centred; vertical auto layout, sections 96-128 apart. +- Order: navigation, hero (headline, one-line value, primary and secondary action, visual), proof (logos or numbers), features (3-6, icon, title, one sentence), how it works or a showcase, testimonials, pricing if asked, FAQ, final call to action, footer. +- Hero headline 56-72, section titles 36-44, body 18. One primary colour for actions only. +- Each section is its own frame named after it, so it can be moved or reused. +- Real, specific copy for the product the user describes; no lorem ipsum. +- When asked for mobile too, add a 390 wide frame with the same section names, stacked to one column. +"#, + ), + builtin( + "Design review", + "Checking a design for problems (contrast, spacing, alignment, consistency) and fixing them.", + r#" +Measure first, then judge. FigCraft's own checker does the measuring; you do what it cannot. +1. If the file has a design brief, its spacing step, corners, brand colours and contrast target are already the review settings (design.configure); otherwise run design.configure with the grid, radii and brand colours the design uses. +2. run_command design.audit on the selection, or on the frames you made (ids), with the Theme mode you designed in (modes: {Theme: Light}). Read the score, the counts and each finding (rule, node, message, fixable). +3. run_command design.fix with the same scope (dryRun first if many layers change): it repairs the fixable findings in one undo step. Then design.audit again to confirm. +4. Fix the rest by hand where it is safe (text colour for contrast, a gap onto the step, a raw colour onto a Theme variable); leave content and naming to the user unless asked. +5. Then look: a screenshot of the frames, compared with the request, for what no rule measures: hierarchy, balance, alignment between sections, empty or crowded areas, copy that does not fit. +6. Report briefly: the score before and after, what you fixed, and what is left as a suggestion with where it is. +"#, + ), + builtin( + "Design system setup", + "Making or completing the file's design system on the page '00 · Design System': tokens, styles, foundations and base components.", + r#" +- Everything goes on the page '00 · Design System', first in the file. `design_system` with a spec makes the page, the variables (Primitives, Theme with Light/Dark, Sizes), the text and shadow styles, the review settings and a 'Design guidelines' text; call it first when they are missing, and use what it made instead of a second set. +- Lay the page out in sections side by side (frames with vertical auto layout, 80 apart, each with a heading in Heading 2): Colour (a swatch per Theme role, one frame per mode with variable.setMode), Type (a line per text style with its size and weight), Spacing and corners (bars and squares bound to the Sizes variables), Elevation (cards with Shadow/S, M, L), Icons (the set and style from the guidelines, with a few sample icons drawn as vectors on the icon grid), and the Design guidelines text. +- Components on the same page, in a "Components" section: Button (Primary, Secondary, Ghost; Default, Hover, Disabled), Input (Default, Focus, Error), Card, Badge, Icon button, as component sets with auto layout, every colour, radius and gap bound to the variables (variable.bind, fill {$var}) and text in the text styles. +- Check contrast of text on its background in both modes before finishing. +"#, + ), + builtin( + "Dark mode", + "Making a dark version of a design or adding a dark theme.", + r#" +- Prefer variables: add a Dark mode to the colour collection and set each semantic colour; switch the frame's mode instead of repainting layers. +- Without variables, duplicate the frame beside the original, named "... / Dark", and recolour it. +- Backgrounds near #0F1115-#1A1D23, surfaces a step lighter; text #E8EAED and muted #9AA0A6; keep 4.5:1 contrast. +- Lower the saturation of bright brand colours a little; shadows become subtle borders or lighter surfaces. +"#, + ), + ] +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_skill_file_reads_back_as_it_was_written() { + let text = to_text("Brand voice", "Writing copy\nfor us", "- Friendly\n- Short"); + let (name, description, body) = parse(&text).expect("a skill"); + assert_eq!(name, "Brand voice"); + assert_eq!(description, "Writing copy for us", "the description stays one line"); + assert_eq!(body, "- Friendly\n- Short"); + assert!(parse("no header here").is_none()); + assert!(parse("---\ndescription: x\n---\nbody").is_none(), "a skill needs a name"); + } + + #[test] + fn the_persons_skill_replaces_a_builtin_one_of_the_same_name() { + let dir = std::env::temp_dir().join(format!("figcraft-skills-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + save(&dir, "landing PAGE", "Ours", "Our rules", None).expect("saved"); + let skills = load(Some(&dir)); + let landing: Vec<&Skill> = skills.iter().filter(|s| s.name.eq_ignore_ascii_case("landing page")).collect(); + assert_eq!(landing.len(), 1); + assert!(!landing[0].builtin); + assert_eq!(landing[0].body, "Our rules"); + assert!(skills.iter().any(|s| s.builtin), "the other built-in skills stay"); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn a_skill_never_overwrites_another_with_the_same_file_name() { + let dir = std::env::temp_dir().join(format!("figcraft-skills-clash-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let first = save(&dir, "Brand voice", "", "One", None).expect("saved"); + assert!(save(&dir, "Brand-voice", "", "Two", None).is_err(), "a different skill, the same file"); + save(&dir, "brand voice", "", "Edited", None).expect("the same skill saves again"); + save(&dir, "Brand voice", "", "Again", Some(&first)).expect("editing it in place"); + assert!(load(Some(&dir)).iter().any(|s| s.body == "Again")); + let notes = dir.join("notes.md"); + std::fs::write(¬es, "not a skill").expect("write"); + assert!(save(&dir, "Notes", "", "Mine", None).is_err(), "a file that is not a skill stays"); + assert_eq!(std::fs::read_to_string(¬es).ok().as_deref(), Some("not a skill")); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn load_skill_answers_with_the_instructions_or_the_names_there_are() { + let book: SkillBook = Arc::new(RwLock::new(builtins())); + let (text, ok) = call(&book, &json!({"name": "dark mode"})); + assert!(ok); + assert!(text.contains("variables")); + let (text, ok) = call(&book, &json!({"name": "nope"})); + assert!(!ok); + assert!(text.contains("Dark mode"), "it lists what there is"); + } +} diff --git a/crates/agent/src/sse.rs b/crates/agent/src/sse.rs new file mode 100644 index 000000000..00bf2d343 --- /dev/null +++ b/crates/agent/src/sse.rs @@ -0,0 +1,179 @@ +//! A Server-Sent Events reader: the provider streams one JSON object per `data:` line, ended by a +//! blank line. Hand-written because the crate has no async runtime. + +use std::io::{BufRead, Read}; +use std::sync::mpsc::{Receiver, sync_channel}; + +/// The longest line read from a stream; a provider sending more without a newline is refused. +pub const MAX_LINE: usize = 1024 * 1024; +/// The most data one event may join. +pub const MAX_EVENT: usize = 16 * 1024 * 1024; + +/// One event: its `event:` name when the stream set one, and its joined `data:` lines. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Event { + pub name: String, + pub data: String, +} + +pub struct Sse { + reader: R, +} + +impl Sse { + pub fn new(reader: R) -> Self { + Self { reader } + } + + /// One line, at most [`MAX_LINE`] long; `None` at the end of the stream. + fn line(&mut self) -> Result, String> { + let mut bytes = Vec::new(); + let read = + (&mut self.reader).take(MAX_LINE as u64 + 1).read_until(b'\n', &mut bytes).map_err(|e| format!("reading the stream failed: {e}"))?; + if read == 0 { + return Ok(None); + } + if bytes.len() > MAX_LINE && bytes.last() != Some(&b'\n') { + return Err(format!("the stream sent a line longer than {MAX_LINE} bytes")); + } + Ok(Some(String::from_utf8_lossy(&bytes).into_owned())) + } + + /// The next event, `None` at the end of the stream. + pub fn next_event(&mut self) -> Result, String> { + let mut name = String::new(); + let mut data: Vec = Vec::new(); + let mut size = 0usize; + loop { + let Some(line) = self.line()? else { + return Ok(if data.is_empty() && name.is_empty() { None } else { Some(Event { name, data: data.join("\n") }) }); + }; + let line = line.trim_end_matches(['\n', '\r']); + if line.is_empty() { + if data.is_empty() && name.is_empty() { + continue; + } + return Ok(Some(Event { name, data: data.join("\n") })); + } + if line.starts_with(':') { + continue; + } + if let Some(rest) = line.strip_prefix("event:") { + name = rest.trim().to_string(); + } else if let Some(rest) = line.strip_prefix("data:") { + let part = rest.strip_prefix(' ').unwrap_or(rest); + size = size.saturating_add(part.len() + 1); + if size > MAX_EVENT { + return Err(format!("the stream sent an event larger than {MAX_EVENT} bytes")); + } + data.push(part.to_string()); + } + // Other fields (`id:`, `retry:`) are not used by either dialect. + } + } +} + +/// Read the stream's events on their own thread, so the caller can stop waiting at any moment +/// (Stop) without depending on the network to answer. The thread ends at the end of the stream, +/// on an error, or at its next event once the receiver is dropped. +pub fn spawn_events(body: Box) -> Receiver> { + let (tx, rx) = sync_channel(64); + let spawned = std::thread::Builder::new().name("figcraft-agent-sse".into()).spawn(move || { + let mut sse = Sse::new(body); + loop { + match sse.next_event() { + Ok(Some(e)) => { + if tx.send(Ok(e)).is_err() { + return; + } + } + Ok(None) => return, + Err(e) => { + let _ = tx.send(Err(e)); + return; + } + } + } + }); + if let Err(e) = spawned { + let (tx, rx) = sync_channel(1); + let _ = tx.send(Err(format!("can't read the answer: {e}"))); + return rx; + } + rx +} + +/// The next event from [`spawn_events`], checking `cancel` while waiting: `Err("stopped")` when it +/// is set, `Ok(None)` at the end of the stream. +pub fn next(events: &Receiver>, cancel: &std::sync::atomic::AtomicBool) -> Result, String> { + use std::sync::atomic::Ordering; + use std::sync::mpsc::RecvTimeoutError; + loop { + if cancel.load(Ordering::Relaxed) { + return Err("stopped".to_string()); + } + match events.recv_timeout(std::time::Duration::from_millis(100)) { + Ok(Ok(e)) => return Ok(Some(e)), + Ok(Err(e)) => return Err(e), + Err(RecvTimeoutError::Timeout) => {} + Err(RecvTimeoutError::Disconnected) => return Ok(None), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::io::Cursor; + + #[test] + fn events_join_data_lines_and_keep_their_name() { + let stream = "event: text\ndata: {\"a\":1}\ndata: {\"b\":2}\n\ndata: [DONE]\n\n"; + let mut sse = Sse::new(Cursor::new(stream.as_bytes())); + let first = sse.next_event().expect("read").expect("one event"); + assert_eq!(first.name, "text"); + assert_eq!(first.data, "{\"a\":1}\n{\"b\":2}"); + let second = sse.next_event().expect("read").expect("another"); + assert_eq!(second.name, ""); + assert_eq!(second.data, "[DONE]"); + assert!(sse.next_event().expect("read").is_none()); + } + + #[test] + fn comments_and_windows_newlines_are_tolerated() { + let stream = ": keep-alive\r\n\r\ndata: hi\r\n\r\n"; + let mut sse = Sse::new(Cursor::new(stream.as_bytes())); + let e = sse.next_event().expect("read").expect("one event"); + assert_eq!(e.data, "hi"); + } + + #[test] + fn an_unterminated_last_event_is_still_delivered() { + let mut sse = Sse::new(Cursor::new(b"data: last".as_slice())); + let e = sse.next_event().expect("read").expect("one event"); + assert_eq!(e.data, "last"); + assert!(sse.next_event().expect("read").is_none()); + } + + #[test] + fn an_endless_line_is_refused_instead_of_kept() { + let long = format!("data: {}", "x".repeat(MAX_LINE + 10)); + let mut sse = Sse::new(Cursor::new(long.into_bytes())); + assert!(sse.next_event().is_err()); + } + + #[test] + fn stop_ends_the_wait_without_the_stream_answering() { + // A reader that never sends anything. + struct Silent; + impl std::io::Read for Silent { + fn read(&mut self, _: &mut [u8]) -> std::io::Result { + std::thread::sleep(std::time::Duration::from_secs(30)); + Ok(0) + } + } + let events = spawn_events(Box::new(std::io::BufReader::new(Silent))); + let cancel = std::sync::atomic::AtomicBool::new(true); + assert_eq!(next(&events, &cancel), Err("stopped".to_string())); + } +} diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index da0258399..a7f765050 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -52,5 +52,8 @@ egui = { workspace = true, features = ["default_fonts", "monochrome_emoji_fonts" [target.'cfg(not(target_arch = "wasm32"))'.dependencies] craft-update = { workspace = true } +# The in-app agent: HTTP providers and a worker thread, so desktop only (the browser build shows +# the panel's setup card through the stub in `panels/layers.rs`). +figcraft-agent = { workspace = true } # Colour emoji (COLR, sbix, CBDT) in the UI from the system's emoji face; the web build has none. craft-ui = { workspace = true, features = ["color_fonts"] } diff --git a/crates/ui-egui/locales/en.toml b/crates/ui-egui/locales/en.toml index fa853b62d..349c1f1c7 100644 --- a/crates/ui-egui/locales/en.toml +++ b/crates/ui-egui/locales/en.toml @@ -12,13 +12,16 @@ name = "English" "(no longer published)" = "(no longer published)" "({n} warnings: some entries were skipped)" = { one = "({n} warning: some entries were skipped)", other = "({n} warnings: some entries were skipped)" } "+ Create variable" = "+ Create variable" +"+{count} more" = "+{count} more" ", changed" = ", changed" ".fig (experimental)" = ".fig (experimental)" +"1 step" = "1 step" "1 year" = "1 year" "1…9, 0" = "1…9, 0" "30 days" = "30 days" "90 days" = "90 days" "@{login}: {prs} PRs, {commits} commits, +{added} / −{deleted} lines (Δ {delta}), +{bin_added} / −{bin_deleted} binary assets, {first} – {last}" = "@{login}: {prs} PRs, {commits} commits, +{added} / −{deleted} lines (Δ {delta}), +{bin_added} / −{bin_deleted} binary assets, {first} – {last}" +"A built-in skill. Make a copy to change it; your copy replaces it." = "A built-in skill. Make a copy to change it; your copy replaces it." "A collection of this file with these modes and variables: override their values per mode and add variables of its own" = "A collection of this file with these modes and variables: override their values per mode and add variables of its own" "A .figcraft file with this name already exists. Choose its full name to confirm replacement." = "A .figcraft file with this name already exists. Choose its full name to confirm replacement." "A later vote" = "A later vote" @@ -59,6 +62,7 @@ name = "English" "Add effect" = "Add effect" "Add export setting" = "Add export setting" "Add fill" = "Add fill" +"Add hover, pressed and disabled variants" = "Add hover, pressed and disabled variants" "Add interaction" = "Add interaction" "Add layout grid" = "Add layout grid" "Add library" = "Add library" @@ -79,17 +83,139 @@ name = "English" "Add stroke" = "Add stroke" "Add variant" = "Add variant" "Add variant with a new value" = "Add variant with a new value" +"Agent quick actions" = "Agent quick actions" +"Allow" = "Allow" +"Always check with a screenshot" = "Always check with a screenshot" +"API key" = "API key" +"Ask" = "Ask" +"Ask agent…" = "Ask agent…" +"At most {count} images go with one request." = "At most {count} images go with one request." +"Attach" = "Attach" +"Attach an image or the selection. You can also drop an image on this panel." = "Attach an image or the selection. You can also drop an image on this panel." +"Attach the selection as an image" = "Attach the selection as an image" +"Attached image {name}" = "Attached image {name}" +"Bring this answer's changes back" = "Bring this answer's changes back" +"Built in" = "Built in" +"Can't attach {name}: {error}" = "Can't attach {name}: {error}" +"Can't delete {path}: {error}" = "Can't delete {path}: {error}" +"Can't reach the provider. Check the internet connection and try again." = "Can't reach the provider. Check the internet connection and try again." +"Can't read {name}: {error}" = "Can't read {name}: {error}" +"Can't render the selection: {error}" = "Can't render the selection: {error}" +"Changed 1 layer" = "Changed 1 layer" +"Changed the file" = "Changed the file" +"Changed {count} layers" = "Changed {count} layers" +"Changes undone" = "Changes undone" +"Chat history" = "Chat history" +"Check again" = "Check again" +"Check contrast and accessibility, then fix what fails" = "Check contrast and accessibility, then fix what fails" +"Check the connection" = "Check the connection" +"Check the selection for spacing and contrast problems" = "Check the selection for spacing and contrast problems" +"Checking…" = "Checking…" +"Choose a model first." = "Choose a model first." +"Choose how the agent reaches an AI model. It takes one step." = "Choose how the agent reaches an AI model. It takes one step." +"Connect" = "Connect" +"Connect a model" = "Connect a model" +"Connect a model first." = "Connect a model first." +"Connect a model to start" = "Connect a model to start" +"Connected, but the provider listed no chat model. Pick one under Advanced." = "Connected, but the provider listed no chat model. Pick one under Advanced." +"Connections" = "Connections" +"Copy this answer" = "Copy this answer" +"Copy this code" = "Copy this code" "Couldn't download {name}: {why}" = "Couldn't download {name}: {why}" "Couldn't open {name}." = "Couldn't open {name}." +"Default model" = "Default model" +"Delete this chat" = "Delete this chat" +"Deny" = "Deny" +"Describe what to design… @ names a layer, / adds a skill" = "Describe what to design… @ names a layer, / adds a skill" +"Design a sign-in screen for a mobile app" = "Design a sign-in screen for a mobile app" +"Dropped image" = "Dropped image" "Edit property" = "Edit property" +"Endpoint" = "Endpoint" +"Everything runs without asking" = "Everything runs without asking" +"Files and network ask first" = "Files and network ask first" +"Fill this with realistic content" = "Fill this with realistic content" +"Fix the type hierarchy" = "Fix the type hierarchy" "Frame {start} isn't in this file: presenting from the start." = "Frame {start} isn't in this file: presenting from the start." +"Get a key" = "Get a key" +"How many versions of the design to build" = "How many versions of the design to build" +"In $/1M" = "In $/1M" +"In use" = "In use" +"Installed, not signed in. Sign in with:" = "Installed, not signed in. Sign in with:" +"Instructions" = "Instructions" +"Instructions the agent follows for a kind of work. Type / in the box to add one to a request; the agent also loads one when it fits." = "Instructions the agent follows for a kind of work. Type / in the box to add one to a request; the agent also loads one when it fits." +"Layer" = "Layer" +"Layer {name}: select it" = "Layer {name}: select it" +"Leave {name} out of the request" = "Leave {name} out of the request" +"Look at the canvas after each change" = "Look at the canvas after each change" +"Make a copy to edit" = "Make a copy to edit" +"Make a pricing section with three plans" = "Make a pricing section with three plans" +"Make this responsive with auto layout" = "Make this responsive with auto layout" +"Make three variations of this" = "Make three variations of this" +"Manage connections…" = "Manage connections…" +"Match the colours to the file's styles" = "Match the colours to the file's styles" +"Model: {model}" = "Model: {model}" +"New chat" = "New chat" +"New skill" = "New skill" +"No earlier chats for this file" = "No earlier chats for this file" +"Not installed. Install it with:" = "Not installed. Install it with:" +"Nothing answered at this address. Is the local model server running?" = "Nothing answered at this address. Is the local model server running?" "Nothing to present." = "Nothing to present." "Nothing to present: {why}" = "Nothing to present: {why}" +"On: after every answer that changed the canvas, the agent takes a screenshot, compares it with the request and fixes what is off (one more request). Off: it takes one only when it decides to." = "On: after every answer that changed the canvas, the agent takes a screenshot, compares it with the request and fixes what is off (one more request). Off: it takes one only when it decides to." +"One line: the agent reads it to decide" = "One line: the agent reads it to decide" "Only a file on this site can be presented: {file}" = "Only a file on this site can be presented: {file}" "Lasso select" = "Lasso select" +"Only the last answer can be undone here, while nothing else changed since. Use Edit > Undo for single steps." = "Only the last answer can be undone here, while nothing else changed since. Use Edit > Undo for single steps." +"Out $/1M" = "Out $/1M" +"Paste a key and FigCraft picks a model for you. Keys stay in this app's settings, readable only by you." = "Paste a key and FigCraft picks a model for you. Keys stay in this app's settings, readable only by you." +"Paste image from clipboard" = "Paste image from clipboard" +"Paste your API key first." = "Paste your API key first." +"Pasted image {n}" = "Pasted image {n}" "Point eraser" = "Point eraser" "Preferred components" = "Preferred components" +"Price per million tokens (for the cost estimate)" = "Price per million tokens (for the cost estimate)" +"Put this request back in the box to change it" = "Put this request back in the box to change it" +"Queued" = "Queued" +"Reasoning" = "Reasoning" +"Rebuild as editable layers" = "Rebuild as editable layers" +"Rebuild this screenshot as editable layers" = "Rebuild this screenshot as editable layers" +"Recreate the attached screenshot as layers with auto layout" = "Recreate the attached screenshot as layers with auto layout" +"Redo" = "Redo" +"Refresh the model list" = "Refresh the model list" +"Remove image {name}" = "Remove image {name}" +"Remove queued request: {text}" = "Remove queued request: {text}" +"Remove {name}" = "Remove {name}" +"Rewrite the copy to be clearer and shorter" = "Rewrite the copy to be clearer and shorter" +"Run everything without asking" = "Run everything without asking" +"Running {tool}" = "Running {tool}" +"Select the changed layers and zoom to them" = "Select the changed layers and zoom to them" +"Select the layers this step changed and zoom to them" = "Select the layers this step changed and zoom to them" +"Select this layer on the canvas" = "Select this layer on the canvas" +"Send" = "Send" +"Show 1 layer" = "Show 1 layer" +"Show {count} layers" = "Show {count} layers" +"Sign in once in the program itself; FigCraft uses that sign-in and never sees it." = "Sign in once in the program itself; FigCraft uses that sign-in and never sees it." +"Skills" = "Skills" +"Skills can't be saved: the app has no settings folder." = "Skills can't be saved: the app has no settings folder." +"Something went wrong" = "Something went wrong" +"Stopped." = "Stopped." "Stroke eraser" = "Stroke eraser" +"The agent is working on the canvas" = "The agent is working on the canvas" +"The agent stopped unexpectedly." = "The agent stopped unexpectedly." +"The agent wants to: {reason}" = "The agent wants to: {reason}" +"The agent works on this canvas: describe a screen, or select layers and ask for a change." = "The agent works on this canvas: describe a screen, or select layers and ask for a change." +"The clipboard holds no image." = "The clipboard holds no image." +"The model reads images" = "The model reads images" +"The provider refused this key. Check that it is copied whole and still active." = "The provider refused this key. Check that it is copied whole and still active." +"Those layers are no longer in this file." = "Those layers are no longer in this file." +"Tidy up the spacing and alignment" = "Tidy up the spacing and alignment" +"Translate the text to English" = "Translate the text to English" +"Turn the selection into a component with variants" = "Turn the selection into a component with variants" +"Turn this into a component with variants" = "Turn this into a component with variants" +"Undo" = "Undo" +"Undo every change this answer made" = "Undo every change this answer made" +"Use a subscription" = "Use a subscription" +"Use an API key" = "Use an API key" "Values" = "Values" "Added" = "Added" "Added the library \"{name}\"" = "Added the library \"{name}\"" @@ -374,6 +500,15 @@ name = "English" "Open preview in a new window" = "Open preview in a new window" "Return preview to the editor" = "Return preview to the editor" "The contrast can't be told when a gradient, image or blend mode is in this fill or behind the layer" = "The contrast can't be told when a gradient, image or blend mode is in this fill or behind the layer" +"Versions: {count}" = "Versions: {count}" +"What should we design?" = "What should we design?" +"When to use it" = "When to use it" +"Working…" = "Working…" +"Write a description for this component" = "Write a description for this component" +"{count} steps" = "{count} steps" +"{count} steps, {failed} failed" = "{count} steps, {failed} failed" +"{count} tokens" = "{count} tokens" +"{input} in · {output} out" = "{input} in · {output} out" "{level} needs {needed}:1 against {backdrop}" = "{level} needs {needed}:1 against {backdrop}" "Contributors" = "Contributors" "Contributors: {people} · Commits: {commits}" = "Contributors: {people} · Commits: {commits}" @@ -436,6 +571,10 @@ name = "English" "In code" = "In code" "Source file" = "Source file" "Variant value" = "Variant value" +"{m} min {s} s" = "{m} min {s} s" +"{name} is not an image this app reads: {error}" = "{name} is not an image this app reads: {error}" +"{n} s" = "{n} s" +"≈ ${cost} at API rates" = "≈ ${cost} at API rates" "⌘ click a padding field" = "⌘ click a padding field" "Ctrl+scroll" = "Ctrl+scroll" "Current name" = "Current name" @@ -1855,6 +1994,7 @@ name = "English" "Yellow" = "Yellow" "Yesterday" = "Yesterday" "You" = "You" +"You edited the file while the agent worked, so Undo answer is off for this turn; use Edit › Undo." = "You edited the file while the agent worked, so Undo answer is off for this turn; use Edit › Undo." "You'll get the shared file as a new tab and edit it together." = "You'll get the shared file as a new tab and edit it together." "You're spotlighting: everyone follows your view" = "You're spotlighting: everyone follows your view" "Your copy of the file stays open" = "Your copy of the file stays open" diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index eef7e4426..0f8081b5c 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -41,6 +41,8 @@ impl FigApp { field_focus: false, panels_unsaved: false, control_queue: Vec::new(), + #[cfg(not(target_arch = "wasm32"))] + chat: crate::chat::Chat::default(), control_waits: Default::default(), control_input: Vec::new(), frame_stats: frame_stats::FrameStats::default(), @@ -214,6 +216,19 @@ impl FigApp { // target/caret. Outgoing IME receipts run after mutation and cannot authorize it. let ime_input = shortcuts::ImeInputBaseline::capture(self); let t = theme::Tokens::get(&ctx); + // The agent's settings are read once, before the first frame lays out the panels: a + // window last left on the Agent tab opens on it. + #[cfg(not(target_arch = "wasm32"))] + if !self.chat.is_loaded() { + let path = self.services.agent_config_path(); + self.chat.ensure_loaded(path); + if self.chat.agents.panel { + self.ui.left_tab = LeftTab::Agent; + self.ui.left_collapsed = false; + } + } + #[cfg(not(target_arch = "wasm32"))] + crate::chat::shortcut(self, &ctx); // A field that had the keyboard when the frame began keeps its keys from the shortcuts // even if it lets go during the frame (Enter commits it), or as it began (egui drops the // focus on Escape before the frame, which cancels the field's edit and nothing else). @@ -361,6 +376,7 @@ impl FigApp { LeftTab::File => i18n::tr("Layers"), LeftTab::Assets => i18n::tr("Assets"), LeftTab::Plugins => i18n::tr("Plugins"), + LeftTab::Agent => i18n::tr("Agent"), }; a11y::region(&mut self.ui.nav, ui, a11y::Region::Layers, egui::accesskit::Role::Pane, label); layers::left_panel(self, ui) diff --git a/crates/ui-egui/src/chat.rs b/crates/ui-egui/src/chat.rs new file mode 100644 index 000000000..7e4e9acb2 --- /dev/null +++ b/crates/ui-egui/src/chat.rs @@ -0,0 +1,3628 @@ +//! The Agent tab: the conversation with the agent, filling the left panel. +//! +//! The panel owns the worker thread ([`figcraft_agent::Worker`]); every tool call the model asks +//! for goes to the UI thread through the bridge ([`Chat::take_bridge_calls`]) and runs like a +//! control request, so the agent and an external MCP client behave the same. +//! +//! Connecting is one step: pick a subscription the person already signed in to in its own tool +//! (Claude Code, Codex, OpenCode), or paste an API key; the model list and a sensible model come +//! from the provider. Endpoints, limits and prices stay under Advanced. + +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::sync::mpsc::{Receiver, Sender, TryRecvError, channel}; + +use egui::{Align, CornerRadius, Layout, Margin, RichText, Sense, Stroke, Ui, pos2, vec2}; +use figcraft_agent::bridge::{self, Bridge}; +use figcraft_agent::cli::Status as CliStatus; +use figcraft_agent::config::Reasoning; +use figcraft_agent::{AGENT_NAME, AgentsFile, ApiKind, ChatEvent, PRESETS, Provider, SUBSCRIPTIONS, Usage, Worker}; +use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; + +use crate::control::{ControlReply, ControlRequest, RequestGate}; +use crate::i18n::{tr, trf}; +use crate::theme::{Tokens, regular, semibold}; +use crate::widgets::{self, PAD}; +use crate::{FigApp, a11y, icons}; + +/// One line of the conversation. +#[derive(Clone, Debug, Serialize, Deserialize)] +pub enum Entry { + User(String), + Assistant(String), + Tool { + title: String, + summary: String, + state: ToolState, + /// The layers this step added or changed (its own changes, not the layers around them). + #[serde(default)] + layers: Vec, + }, + Note(String), + /// A turn that failed (network, provider, sign-in), shown with a way to fix the connection. + Error(String), + /// What the person attached to the request after it: layers (clickable, to select them again) + /// and the names of images. + Refs { + layers: Vec, + images: Vec, + /// Skills attached with `/`. + #[serde(default)] + skills: Vec, + }, + /// How long an answer took and the tokens it used. + Stats { + secs: u64, + tokens: u64, + }, + /// What an answer changed on the canvas, after it: the layers, and the undo steps it took. + Changes { + layers: Vec, + steps: usize, + /// The undo depth right after the answer; undoing it is offered only while nothing else + /// was done since. + depth: usize, + #[serde(default)] + undone: bool, + /// Made in this run of the app (undo history is not kept across launches). + #[serde(skip)] + live: bool, + }, +} + +/// A layer attached to a request. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct LayerRef { + pub id: u64, + pub name: String, +} + +/// A skill open in the editor. `file`: the person's skill it replaces (none for a new one). +#[derive(Clone, Debug, Default)] +struct SkillDraft { + name: String, + description: String, + body: String, + file: Option, + /// A built-in skill, shown read-only until copied. + builtin: bool, +} + +/// A layer offered for the @ being typed. +#[derive(Clone, Debug)] +pub struct MentionHit { + pub layer: LayerRef, + pub icon: icons::Icon, + /// What it is ("Component", "Page"…), shown beside its name. + pub kind: &'static str, +} + +/// What the selection is, for the suggestions above the composer. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum SelKind { + #[default] + None, + Text, + Component, + Instance, + Frame, + Other, +} + +/// An image attached to the next request. +pub struct Attachment { + pub name: String, + pub image: figcraft_agent::neutral::Image, + thumb: Option, +} + +/// Another conversation kept for this document. +pub struct PastChat { + pub key: String, + pub title: String, + pub current: bool, +} + +/// At most this many images go with one request. +const MAX_IMAGES: usize = 6; +/// The longest side an attached image is scaled down to (what vision models read at full detail). +const IMAGE_SIDE: u32 = 1568; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub enum ToolState { + Running, + Ok, + Failed, +} + +/// Something the panel asks the app to do after drawing (it needs the whole `FigApp`). +pub enum Action { + Send, + /// Send this text (a suggestion) as the request. + SendText(String), + Stop, + /// Undo, or redo, the canvas changes of the answer at this entry. + UndoChanges(usize), + RedoChanges(usize), + /// Select these layers and bring them into view. + ShowLayers(Vec), + NewChat, + OpenSettings, + CloseSettings, + FetchModels, + ToggleAuto, + CycleVariants, + Allow(usize), + Deny(usize), + /// Connect a subscription (an installed command-line agent). + ConnectCli(ApiKind), + /// Check the installed programs again. + RefreshCli, + /// Connect the API-key preset with this index, using the key typed on its card. + ConnectKey(usize), + /// Make the provider with this index the one requests go to. + Use(usize), + /// Choose this model on the active provider. + UseModel(String), + Remove(usize), + /// Select this layer on the canvas (a chip was clicked). + SelectLayer(u64), + /// Leave this selected layer out of the next request. + Exclude(u64), + /// Take a layer named with @ off the next request. + Unmention(u64), + /// Put the layer offered for the @ being typed into the request. + Mention(usize), + /// Rebuild the attached screenshot as editable layers. + Rebuild, + /// Attach the skill offered at this index for the `/` being typed. + PickSkill(usize), + /// Take an attached skill off the next request. + Unskill(String), + OpenSkills, + /// Turn the screenshot check after every answer that changed the canvas on or off. + ToggleReview, + + RemoveImage(usize), + PasteImage, + AttachRender, + CopyText(String), + /// Put the last request back in the composer. + EditLast, + /// Send the last request again. + Retry, + Unqueue(usize), + OpenChat(String), + DeleteChat(String), +} + +struct Approval { + reason: String, + name: String, + args: Value, + reply: Sender, +} + +/// A tool call's answer on its way back to the agent thread. +type ReplyForward = (Receiver, Sender>); + +/// A model list being fetched: the provider it belongs to and the thread's answer. +/// A model list being fetched: the connection's row, what identified it then (a row removed +/// meanwhile moves the others up), and the answer on its way. +type ModelFetch = (usize, String, Receiver, String>>); + +/// What identifies a connection for a model list: its kind, address and name. +fn fetch_identity(p: &Provider) -> String { + format!("{:?}|{}|{}", p.kind, p.base_url, p.name) +} + +/// A request as it was sent, so Try again sends it the same way (its images and the instructions +/// the person did not type included). +#[derive(Clone)] +pub(crate) struct SentRequest { + text: String, + hidden: String, + skills: Vec, + image_names: Vec, + images: Vec, +} + +/// An API-key connection being tried: the preset, and the provider with its model list once the +/// endpoint answered. +type KeyTrial = (usize, Receiver>); + +/// The installed command-line agents, as last checked. +type CliCheck = Receiver>; + +/// The prompts offered on an empty conversation. +const SUGGESTIONS: &[&str] = &[ + crate::i18n::tr_noop("Design a sign-in screen for a mobile app"), + crate::i18n::tr_noop("Make a pricing section with three plans"), + crate::i18n::tr_noop("Turn the selection into a component with variants"), + crate::i18n::tr_noop("Check the selection for spacing and contrast problems"), +]; + +/// The chat panel's state, kept on the window. +#[derive(Default)] +pub struct Chat { + /// `agents.json`'s contents and where it lives. + pub agents: AgentsFile, + path: Option, + loaded: bool, + /// The Connections screen is showing instead of the conversation. + pub settings_open: bool, + pub error: Option, + pub draft: String, + pub entries: Vec, + pub running: bool, + pub auto: bool, + pub usage: Usage, + /// The undo depth the turn started at. + turn_mark: Option, + /// The document as the turn found it, and as the last finished step left it: comparing + /// them with the document now tells which layers an answer, or a step, changed. + turn_doc: Option>, + step_doc: Option>, + /// The tool card that just finished, waiting for its changed layers. + last_ended: Option, + /// The document on screen and its undo and redo depth, read each frame for the answers' + /// Undo and Redo buttons. + history_now: Option<(u64, (usize, usize))>, + /// The turn's document as it is now, read with `history_now`. + doc_now: Option>, + /// The answer entry whose Undo or Redo ran last (or that just finished), and the document it + /// left: its buttons work only while the document is still that one. The undo depth alone + /// can come back to the same number after the person undid a step and made one of their own. + answer_doc: Option<(usize, Arc)>, + /// When the turn started and the tokens used before it, for the line under the answer. + turn_started: Option, + usage_before: Usage, + /// Layers named with @ in the composer, going with the next request beside the selection. + pub(crate) mentioned: Vec<(LayerRef, icons::Icon)>, + /// The @ being typed (its character index in the draft, and what follows it), the layers it + /// matches, and the one the arrow keys are on. + mention: Option<(usize, String)>, + pub(crate) mention_hits: Vec, + mention_pick: usize, + /// An @ the person closed with Escape: not offered again until they type another. + mention_closed: Option, + /// What kind of layers are selected, for the suggestions above the composer. + sel_kind: SelKind, + /// The design system summary last sent in this conversation (its hash): sent again only + /// when it changed. + design_sent: Option, + /// Instructions for the model that go with the next request without showing in its bubble. + hidden: Option, + /// The skills: built in and the person's own (`agent-skills/` beside `agents.json`). + pub(crate) skills: Vec, + skills_dir: Option, + /// The Skills screen is showing, and the skill being edited there. + pub skills_open: bool, + skill_edit: Option, + /// Skills attached to the next request with `/`, by name. + pub(crate) picked_skills: Vec, + /// The `/` being typed and the skills it matches (indices into `skills`). + slash: Option<(usize, String)>, + slash_hits: Vec, + /// The skill list last told to this conversation (its hash). + catalog_sent: Option, + + /// The page list last told to this conversation (its hash). + pages_sent: Option, + + /// The composer's id, to move its cursor after an @ is picked. + composer_id: Option, + /// The window and document the conversation works in, pinned when a request is sent: a turn + /// must not follow the person to another tab or window halfway through. + window: Option, + pub(crate) document: Option, + /// The conversation on screen belongs to this file (a slug of its path or name). + pub(crate) doc_key: Option, + /// Where the per-document chats are kept (`agent-chats/` beside `agents.json`). + pub(crate) chats_dir: Option, + worker: Option, + pub(crate) bridge: Option, + /// Calls waiting for their answer, to hand it back to the agent thread. + pending: Vec, + approvals: Vec, + /// Model lists being fetched, and the provider they belong to. + fetching: Option, + /// The API-key card that is open, and what is typed in it. + key_card: Option, + key_draft: String, + trial: Option, + /// The installed command-line agents, and a check on its way. + cli: Vec<(ApiKind, CliStatus)>, + cli_check: Option, + /// The Advanced settings of the active connection are open. + advanced: bool, + /// Give the composer the keyboard on the next frame (the tab was just opened). + focus_composer: bool, + /// Whether the composer had the keyboard on the last frame (a paste there may be an image). + composer_focused: bool, + /// The canvas selection as the composer's chips, with each layer's icon. + selection: Vec<(LayerRef, icons::Icon)>, + /// Selected layers the person took off the next request; forgotten when the selection changes. + excluded: Vec, + /// Images going with the next request. + pub images: Vec, + /// Requests typed while the agent was working, sent in turn when it finishes. + pub queue: Vec, + /// Queued requests of other conversations (by conversation key), kept until that conversation + /// is on screen again, with whether its last turn failed. + parked: std::collections::HashMap, bool)>, + /// The last turn ended in an error: queued requests wait for the person. + pub(crate) turn_failed: bool, + /// New chat was asked for while a turn was running: it opens once that turn is over. + pending_new_chat: bool, + /// The last request sent, for Try again. + last_sent: Option, + /// Try again: the request `send` repeats instead of reading the composer. + retry: Option, + /// Undo steps the agent's own calls added this turn (minus the ones they undid); anything + /// else that changed the undo history was the person's. + agent_steps: i64, + /// The document as the agent's last call left it. Another one in its place means the person + /// changed it in between, even where the undo depth came out the same (undo, then a new edit). + agent_doc: Option>, + /// The person changed the document between the agent's calls this turn. + mixed: bool, + /// The conversation on screen, when it is not the document's first one (`-