From 7799bf2e03e988f9f6f75410436e3343da0c4444 Mon Sep 17 00:00:00 2001 From: Mochamad Aufa Date: Mon, 30 Nov 2026 18:57:24 +0700 Subject: [PATCH 1/9] feat(agent): a full-height Agent panel with one-click connections and canvas context - The Agent is its own left-sidebar tab, holding only the chat: messages, grouped tool steps, approval cards and a pinned composer. - Connections: subscriptions through the installed Claude Code, Codex or OpenCode CLI (tools served over a loopback MCP endpoint with a bearer token), or an API key that is checked by listing models and picks a default model; the rest sits under Advanced. - Canvas context: the selection shows as chips and goes with the message; "Ask agent..." and quick actions in the layer menu and Cmd+Shift+M. - Reference images from the clipboard, a drop, or a render of the selection. - Message controls: copy, edit the last request, try again, a queue while a turn runs, and a per-file chat history. --- Cargo.lock | 46 + Cargo.toml | 5 + apps/figcraft/src/services.rs | 4 + crates/agent/Cargo.toml | 21 + crates/agent/src/anthropic.rs | 260 +++ crates/agent/src/bridge.rs | 104 ++ crates/agent/src/cli.rs | 615 +++++++ crates/agent/src/config.rs | 511 ++++++ crates/agent/src/http.rs | 99 ++ crates/agent/src/lib.rs | 250 +++ crates/agent/src/mcp_http.rs | 389 +++++ crates/agent/src/neutral.rs | 183 +++ crates/agent/src/openai.rs | 277 ++++ crates/agent/src/session.rs | 647 ++++++++ crates/agent/src/sse.rs | 86 + crates/ui-egui/Cargo.toml | 3 + crates/ui-egui/locales/en.toml | 100 +- crates/ui-egui/src/app.rs | 16 + crates/ui-egui/src/chat.rs | 2371 +++++++++++++++++++++++++++ crates/ui-egui/src/chat_tests.rs | 149 ++ crates/ui-egui/src/control.rs | 20 +- crates/ui-egui/src/lib.rs | 7 + crates/ui-egui/src/menus.rs | 5 + crates/ui-egui/src/panels/layers.rs | 21 +- crates/ui-egui/src/services.rs | 5 + crates/ui-egui/src/state.rs | 2 + docs/architecture.md | 1 + docs/harness.md | 252 +++ xtask/src/layers.rs | 4 +- 29 files changed, 6449 insertions(+), 4 deletions(-) create mode 100644 crates/agent/Cargo.toml create mode 100644 crates/agent/src/anthropic.rs create mode 100644 crates/agent/src/bridge.rs create mode 100644 crates/agent/src/cli.rs create mode 100644 crates/agent/src/config.rs create mode 100644 crates/agent/src/http.rs create mode 100644 crates/agent/src/lib.rs create mode 100644 crates/agent/src/mcp_http.rs create mode 100644 crates/agent/src/neutral.rs create mode 100644 crates/agent/src/openai.rs create mode 100644 crates/agent/src/session.rs create mode 100644 crates/agent/src/sse.rs create mode 100644 crates/ui-egui/src/chat.rs create mode 100644 crates/ui-egui/src/chat_tests.rs create mode 100644 docs/harness.md diff --git a/Cargo.lock b/Cargo.lock index d780844ed..87d229a46 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1062,12 +1062,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" @@ -2807,6 +2836,19 @@ dependencies = [ "zbus", ] +[[package]] +name = "figcraft-agent" +version = "0.19.0" +dependencies = [ + "base64 0.22.1", + "figcraft-mcp", + "log", + "proptest", + "serde", + "serde_json", + "ureq", +] + [[package]] name = "figcraft-cli" version = "0.19.0" @@ -3130,6 +3172,7 @@ dependencies = [ "craft-window", "egui", "egui_extras", + "figcraft-agent", "figcraft-color", "figcraft-doc", "figcraft-engine", @@ -7449,12 +7492,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 d8239ba64..5eb6d9ba7 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). @@ -144,6 +145,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..1e3ee2821 --- /dev/null +++ b/crates/agent/Cargo.toml @@ -0,0 +1,21 @@ +[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 } +serde = { workspace = true } +serde_json = { workspace = true } +base64 = { workspace = true } +log = { workspace = true } +# Blocking HTTP with rustls (the same TLS provider collab-net uses), no async runtime. +ureq = { workspace = true } + +[dev-dependencies] +proptest = { workspace = true } diff --git a/crates/agent/src/anthropic.rs b/crates/agent/src/anthropic.rs new file mode 100644 index 000000000..4c9bdd9ed --- /dev/null +++ b/crates/agent/src/anthropic.rs @@ -0,0 +1,260 @@ +//! The Anthropic Messages dialect. + +use std::collections::BTreeMap; +use std::sync::atomic::{AtomicBool, Ordering}; + +use serde_json::{Value, json}; + +use crate::config::Provider; +use crate::http::{Http, read_error}; +use crate::neutral::{Block, Message, Role}; +use crate::sse::Sse; +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 mut sse = Sse::new(reply.body); + let mut step = Step::default(); + // Blocks being built, by index: (id, name, arguments JSON text). + let mut pending: BTreeMap = BTreeMap::new(); + while let Some(event) = sse.next_event()? { + if cancel.load(Ordering::Relaxed) { + return Err("stopped".to_string()); + } + 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_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(); + // A non-streamed endpoint may already have given the input. + let raw = block.get("input").filter(|i| !i.is_null()).map(|i| i.to_string()).unwrap_or_default(); + pending.insert(index, (id, name, raw)); + } + 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.2.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); + } + _ => {} + } + } + for (i, (id, name, raw)) in pending { + if name.is_empty() { + continue; + } + let id = if id.is_empty() { format!("toolu_{i}") } else { id }; + let args = if raw.trim().is_empty() { json!({}) } else { serde_json::from_str(&raw).unwrap_or(Value::Null) }; + step.calls.push(Invocation { id, name, args, args_raw: raw }); + } + Ok(step) +} + +#[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)); + } + + #[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/cli.rs b/crates/agent/src/cli.rs new file mode 100644 index 000000000..1aabb2670 --- /dev/null +++ b/crates/agent/src/cli.rs @@ -0,0 +1,615 @@ +//! 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); + cmd.arg("exec"); + if let Some(s) = turn.session { + cmd.args(["resume", s]); + } + 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()); + } + 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() +} + +/// Write the attached images where the program can read them; their paths, in order. +fn write_images(turn: &Turn<'_>) -> Result, String> { + if turn.images.is_empty() || turn.kind == ApiKind::ClaudeCode { + return Ok(Vec::new()); + } + use base64::Engine as _; + let dir = turn.workdir.join("attachments"); + std::fs::create_dir_all(&dir).map_err(|e| format!("can't make {}: {e}", dir.display()))?; + let stamp = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_millis()).unwrap_or(0); + 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!("{stamp}-{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(); + let files = match write_images(turn) { + 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, + } + } + let status = child.wait(); + 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 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..83edec9fc --- /dev/null +++ b/crates/agent/src/config.rs @@ -0,0 +1,511 @@ +//! 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. The automation roots still confine file access. + 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..a3c9bb595 --- /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..e5605d3de --- /dev/null +++ b/crates/agent/src/lib.rs @@ -0,0 +1,250 @@ +//! 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 cli; +pub mod config; +pub mod http; +pub mod mcp_http; +pub mod neutral; +pub mod openai; +pub mod session; +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, + /// 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 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; + 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, 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..683e04861 --- /dev/null +++ b/crates/agent/src/mcp_http.rs @@ -0,0 +1,389 @@ +//! 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::collections::hash_map::RandomState; +use std::hash::{BuildHasher, Hasher}; +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, +} + +/// 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(); + 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 server = figcraft_mcp::Server::new(Box::new(remote)); + while let Ok((msg, reply)) = inbox.recv() { + let answer = handle_gated(&mut server, &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, gate: &Gate, msg: Value) -> Option { + if msg.get("method").and_then(Value::as_str) != Some("tools/call") { + 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() }); + 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 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})")); + } + } + 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)); + 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 mut line = String::new(); + match reader.read_line(&mut line) { + Ok(0) => return Ok(None), + Ok(_) => {} + Err(_) => 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 mut h = String::new(); + if reader.read_line(&mut h).map_err(|_| 400u16)? == 0 { + return Err(400); + } + 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 })) +} + +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", + _ => "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 standard library's per-process random hash keys. +fn new_token() -> String { + let mut out = String::new(); + for i in 0..2u64 { + let mut h = RandomState::new().build_hasher(); + h.write_u64(i); + h.write_u128(std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_nanos()).unwrap_or(0)); + out.push_str(&format!("{:016x}", h.finish())); + } + out +} + +#[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 tokens_differ() { + assert_ne!(new_token(), new_token()); + assert_eq!(new_token().len(), 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..ab5d2933c --- /dev/null +++ b/crates/agent/src/openai.rs @@ -0,0 +1,277 @@ +//! 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, Ordering}; + +use serde_json::{Value, json}; + +use crate::config::Provider; +use crate::http::{Http, read_error}; +use crate::neutral::{Block, Message, Role}; +use crate::sse::Sse; +use crate::{Invocation, Step, Usage}; + +/// 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 mut sse = Sse::new(reply.body); + let mut step = Step::default(); + // 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) = sse.next_event()? { + if cancel.load(Ordering::Relaxed) { + return Err("stopped".to_string()); + } + let data = event.data.trim(); + if data.is_empty() { + continue; + } + if data == "[DONE]" { + 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(); + } + } + 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..e02e218db --- /dev/null +++ b/crates/agent/src/session.rs @@ -0,0 +1,647 @@ +//! 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, +} + +impl Agent { + pub fn new(provider: Provider, backend: crate::bridge::Remote) -> Self { + let tools = figcraft_mcp::tool_definitions(); + 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, + } + } + + /// 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(); + + 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), + }; + if !step.text.trim().is_empty() { + // The panel already has the streamed text; nothing more to add here. + } + let mut blocks = Vec::new(); + if !step.text.is_empty() { + blocks.push(Block::Text(step.text.clone())); + } + 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(); + for call in step.calls { + if cancel.load(Ordering::Relaxed) { + out(ChatEvent::Done { stopped: true }); + return Ok(()); + } + let outcome = self.run_tool(call, out, cancel); + results.push(outcome); + } + self.messages.push(Message { role: Role::User, blocks: results }); + 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> { + 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() }; + 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 { + out(ChatEvent::Done { stopped: true }); + return Ok(()); + } + if let Some(e) = outcome.error { + return Err(e); + } + out(ChatEvent::Done { stopped: false }); + Ok(()) + } + + fn stream(&mut self, out: &dyn Fn(ChatEvent), cancel: &Arc) -> Result { + let mut on_text = |t: &str| { + out(ChatEvent::Text(t.to_string())); + }; + let result = match self.provider.kind { + ApiKind::OpenAiCompletions => { + crate::openai::stream(&self.http, &self.provider, &self.system, &self.messages, &self.tools, &self.session, &mut on_text, cancel) + } + ApiKind::AnthropicMessages => { + crate::anthropic::stream(&self.http, &self.provider, &self.system, &self.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 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; + } + 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(); + out(ChatEvent::ToolEnd { + id, + name: "screenshot".into(), + ok: image.is_some() && !result.is_error, + title: "screenshot".into(), + text: if image.is_some() { "Looking at the canvas".into() } else { crate::neutral::clip(&text, 200) }, + }); + match image { + Some(image) => { + self.messages.push(Message { role: Role::User, blocks: vec![Block::Text(REVIEW_PROMPT.into()), Block::Image(image)] }); + true + } + None => false, + } + } + + /// 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.provider.context_window as usize).saturating_mul(CHARS_PER_TOKEN).saturating_sub(24_000).clamp(60_000, 800_000); + trim_messages(&mut self.messages, budget); + } +} + +/// Shorten the oldest tool output until the conversation fits `budget`, keeping the last eight +/// messages whole: the recent steps are what the model is working from. +fn trim_messages(messages: &mut [Message], budget: usize) { + let mut total: usize = messages.iter().map(message_chars).sum(); + let mut i = 0; + while total > budget && i + 8 < messages.len() { + let before = message_chars(&messages[i]); + for block in &mut messages[i].blocks { + if let Block::ToolResult { text, images, .. } = block + && text.len() > 200 + { + *text = "[older tool output left out]".to_string(); + images.clear(); + } + } + 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). +fn mutating(name: &str, args: &Value) -> bool { + match name { + "create_node" | "set_properties" | "batch" | "undo" | "redo" => true, + "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 == "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) + } + _ => 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 cmd.starts_with("plugin.") || cmd.starts_with("library.") { + return Some("installs or reaches a plugin or library server".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\ +- 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." + .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()); + assert!(approval("screenshot", &json!({})).is_none()); + } + + #[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/sse.rs b/crates/agent/src/sse.rs new file mode 100644 index 000000000..0f76b5d8c --- /dev/null +++ b/crates/agent/src/sse.rs @@ -0,0 +1,86 @@ +//! 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; + +/// 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 } + } + + /// 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(); + loop { + let mut line = String::new(); + let read = self.reader.read_line(&mut line).map_err(|e| format!("reading the stream failed: {e}"))?; + if read == 0 { + 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 let Some(rest) = line.strip_prefix(':') { + let _ = rest; + continue; + } + if let Some(rest) = line.strip_prefix("event:") { + name = rest.trim().to_string(); + } else if let Some(rest) = line.strip_prefix("data:") { + data.push(rest.strip_prefix(' ').unwrap_or(rest).to_string()); + } + // Other fields (`id:`, `retry:`) are not used by either dialect. + } + } +} + +#[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()); + } +} diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index 2123edaec..6ad904808 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -52,3 +52,6 @@ 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 } diff --git a/crates/ui-egui/locales/en.toml b/crates/ui-egui/locales/en.toml index 38998ba1f..8931d2ea2 100644 --- a/crates/ui-egui/locales/en.toml +++ b/crates/ui-egui/locales/en.toml @@ -12,7 +12,9 @@ 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" ".fig (experimental)" = ".fig (experimental)" +"1 step" = "1 step" "1 year" = "1 year" "1…9, 0" = "1…9, 0" "30 days" = "30 days" @@ -78,8 +80,97 @@ 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" +"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}" +"Can't attach {name}: {error}" = "Can't attach {name}: {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}" +"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" +"Default model" = "Default model" +"Delete this chat" = "Delete this chat" +"Deny" = "Deny" +"Describe what to design…" = "Describe what to design…" +"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" +"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:" +"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 pricing section with three plans" = "Make a pricing section with three plans" +"Make three variations of this" = "Make three variations of this" +"Manage connections…" = "Manage connections…" +"Model: {model}" = "Model: {model}" +"New chat" = "New chat" +"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?" +"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}" "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" +"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}" +"Run everything without asking" = "Run everything without asking" +"Running {tool}" = "Running {tool}" +"Select this layer on the canvas" = "Select this layer on the canvas" +"Send" = "Send" +"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." +"Something went wrong" = "Something went wrong" +"Stopped." = "Stopped." +"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." +"Tidy up the spacing and alignment" = "Tidy up the spacing and alignment" +"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" +"Undid this turn's changes." = "Undid this turn's changes." +"Undo every change the agent made in its last answer" = "Undo every change the agent made in its last answer" +"Undo this turn" = "Undo this turn" +"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}\"" @@ -414,6 +505,14 @@ name = "English" "In code" = "In code" "Source file" = "Source file" "Variant value" = "Variant value" +"Versions: {count}" = "Versions: {count}" +"What should we design?" = "What should we design?" +"Working…" = "Working…" +"{count} steps" = "{count} steps" +"{count} steps, {failed} failed" = "{count} steps, {failed} failed" +"{input} in · {output} out" = "{input} in · {output} out" +"{name} is not an image this app reads: {error}" = "{name} is not an image this app reads: {error}" +"≈ ${cost} at API rates" = "≈ ${cost} at API rates" "⌘ click a padding field" = "⌘ click a padding field" "Ctrl+scroll" = "Ctrl+scroll" "Current name" = "Current name" @@ -2102,7 +2201,6 @@ name = "English" "Space" = "Space" "Nothing to pick: the page is empty" = "Nothing to pick: the page is empty" "Pick select: Tab and Shift+Tab move between layers, Enter goes into one, Shift+Enter out, Space selects, Escape cancels" = "Pick select: Tab and Shift+Tab move between layers, Enter goes into one, Shift+Enter out, Space selects, Escape cancels" - "Retry with higher import limits?" = "Retry with higher import limits?" "Some layers were left out. Retrying opens a new tab and keeps the partial copy." = "Some layers were left out. Retrying opens a new tab and keeps the partial copy." "This file reached the import limit before it could open." = "This file reached the import limit before it could open." diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index d6c9d490a..f26a1828d 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). @@ -345,6 +360,7 @@ impl FigApp { _ if self.ui.versions.open => i18n::tr("Version history"), LeftTab::File => i18n::tr("Layers"), LeftTab::Assets => i18n::tr("Assets"), + 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..057ca5590 --- /dev/null +++ b/crates/ui-egui/src/chat.rs @@ -0,0 +1,2371 @@ +//! 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, + }, + 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, + }, +} + +/// A layer attached to a request. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct LayerRef { + pub id: u64, + pub name: String, +} + +/// 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, + 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), + 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. +type ModelFetch = (usize, Receiver, String>>); + +/// 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, + /// Canvas changes made in this turn, for "Undo turn". + turn_steps: usize, + /// The undo depth the turn started at. + turn_mark: 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, + 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, + /// The conversation on screen, when it is not the document's first one (`-