//! Bots configured on the page (Settings ▸ Bots), and started and stopped //! from there. //! //! For each bot name the hub keeps the account it signs in to Cartopolis with, //! who it works for, where it runs, and, for a bot that talks in calls, the //! OpenAI key its voice uses. `midas bot start --name ` gets the secrets //! with the node's (`/v1/bot/secrets/for`) and hands them to the bot's //! environment over the ssh session's stdin, as it does those (`botsecrets`): //! on no node's disk, in no command line and in no log. The variables are the //! ones the Cartopolis client reads: `CARTO_SERVER` (what `--connect` is given), //! `CARTO_USER` / `CARTO_PASSWORD` (its sign-in) and `OPENAI_API_KEY` for //! `--voice-agent`. //! //! **Start and Stop on the page** go through the sessions runner, because a //! bot's agent is hosted where the Claude login is (`host`), which is the //! runner's machine, and it starts from a checkout of the bot's repository. The //! page asks ([`request`]); the runner takes the request with its next poll //! ([`take_requests`]), runs `midas bot start` with [`start_args`] in a //! worktree of its own (`bot-`), and says how it went ([`report`]). //! //! The page sets a password or key and never reads one back: it sees that one //! is set, and a key's last four characters. What that does not stop, as for //! every bot secret: a caller key reads them through `bot/secrets/for`, and a //! compromised hub has them all. use std::collections::BTreeMap; use std::path::PathBuf; use anyhow::{bail, Result}; use serde::{Deserialize, Serialize}; use serde_json::{json, Value}; use crate::bot::sh_quote; use crate::{events, registry, store}; /// The instructions a bot's agent gets unless told otherwise: the file the /// Cartopolis repository keeps for its bot. pub const DEFAULT_BRIEF: &str = "tools/bot/viberfox.md"; fn yes() -> bool { true } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct Bot { /// The server the bot connects to, as `--connect` takes it. #[serde(default)] pub server: String, #[serde(default)] pub username: String, #[serde(default)] pub password: String, /// The accounts it works for (`--mcp-allow`): whose chat it reads, whose /// calls it answers, who may ask it to act. Comma-separated. #[serde(default)] pub works_for: String, /// It speaks only in private chats (`--mcp-private-only`). #[serde(default = "yes")] pub private_only: bool, /// The node it runs on. Kept the same from start to start: the bot's /// private-chat keys are that node's, and each new node is another device /// of the account. #[serde(default)] pub node: String, /// Its agent's instructions, a file in the repository. #[serde(default)] pub brief: String, /// It takes part in calls by voice, on OpenAI's Realtime API. #[serde(default)] pub voice: bool, /// Its own key for that; empty uses the hub's (Settings ▸ OpenAI key). #[serde(default)] pub openai_key: String, } impl Default for Bot { fn default() -> Self { Bot { server: String::new(), username: String::new(), password: String::new(), works_for: String::new(), private_only: true, node: String::new(), brief: String::new(), voice: false, openai_key: String::new(), } } } /// Where a bot is between Start and Stop, as the runner last said. #[derive(Debug, Clone, Default, Serialize, Deserialize)] pub struct Run { /// Asked for and not yet taken by a runner: `start` or `stop`. #[serde(default)] pub want: Option, /// `queued`, `starting`, `running`, `stopping`, `stopped` or `failed`. #[serde(default)] pub state: String, /// The last words about it: why it failed, where it runs. #[serde(default)] pub detail: String, #[serde(default)] pub at: i64, } type Bots = BTreeMap; type Runs = BTreeMap; fn path() -> PathBuf { registry::root().join("bots.json") } fn runs_path() -> PathBuf { registry::root().join("bot-runs.json") } fn read() -> Bots { store::read(&path()).unwrap_or_default() } fn update(f: impl FnOnce(&mut Bots) -> Result) -> Result { let mut s = store::Store::::open(path())?.private(); let r = f(&mut s.data)?; s.save()?; Ok(r) } fn update_runs(f: impl FnOnce(&mut Runs) -> Result) -> Result { let mut s = store::Store::::open(runs_path())?; let r = f(&mut s.data)?; s.save()?; Ok(r) } fn tail(secret: &str) -> Option { (!secret.is_empty()).then(|| secret.chars().rev().take(4).collect::>().into_iter().rev().collect()) } /// One line, no control characters, at most `max` bytes. fn line_ok(v: &str, max: usize) -> bool { v.len() <= max && !v.chars().any(char::is_control) } /// `sam, anna` → `sam,anna`, or why not. fn names_list(v: &str) -> Result { let names: Vec<&str> = v.split(|c: char| c == ',' || c.is_whitespace()).map(|n| n.trim_start_matches('@')).filter(|n| !n.is_empty()).collect(); for n in &names { if n.len() > 64 || !n.chars().all(|c| c.is_alphanumeric() || "_-.~".contains(c)) { bail!("{n:?} is not a username"); } } Ok(names.join(",")) } /// What the page shows: everything but the secrets, of which only whether /// they are set (and a key's last four characters), and how each run stands. pub fn overview() -> Value { let hub_key = crate::discuss::key().is_some(); let runs: Runs = store::read(&runs_path()).unwrap_or_default(); json!(read().into_iter().map(|(name, b)| { let run = runs.get(&name).cloned().unwrap_or_default(); json!({ "name": name, "server": b.server, "username": b.username, "password_set": !b.password.is_empty(), "works_for": b.works_for, "private_only": b.private_only, "node": b.node, "brief": b.brief, "voice": b.voice, "key": {"own": !b.openai_key.is_empty(), "ends": tail(&b.openai_key), "hub": hub_key}, "run": {"state": if run.state.is_empty() { "stopped" } else { &run.state }, "detail": run.detail, "at": run.at}, "missing": missing(&b), }) }).collect::>()) } /// What a bot still needs before it can start, in words for the page. fn missing(b: &Bot) -> Vec<&'static str> { let mut out = Vec::new(); if b.server.is_empty() { out.push("a server"); } if b.username.is_empty() || b.password.is_empty() { out.push("its account and password"); } if b.works_for.is_empty() { out.push("who it works for"); } if b.node.is_empty() { out.push("a node to run on"); } if b.voice && b.openai_key.is_empty() && crate::discuss::key().is_none() { out.push("an OpenAI key for its voice"); } out } /// Create or change a bot. A field missing from `patch` is kept; a password /// or key given empty is kept too (the page never has them to send back), /// and `clear_key` removes the bot's own key. pub fn set(name: &str, patch: &Value, by: &str) -> Result<()> { if !crate::host::name_ok(name) { bail!("a bot's name is letters, digits, - and _ (at most 40), not {name:?}"); } let text = |k: &str| patch[k].as_str().map(str::trim); update(|bots| { let b = bots.entry(name.to_string()).or_default(); if let Some(v) = text("server") { if !line_ok(v, 200) || v.contains(char::is_whitespace) { bail!("a server is a host name or address, not {v:?}"); } b.server = v.to_string(); } if let Some(v) = text("username") { if !line_ok(v, 64) { bail!("a username is one short line"); } b.username = v.to_string(); } if let Some(v) = patch["password"].as_str().filter(|v| !v.is_empty()) { if !line_ok(v, 4096) { bail!("a password is one line of at most 4096 bytes"); } b.password = v.to_string(); } if let Some(v) = text("works_for") { b.works_for = names_list(v)?; } if let Some(v) = patch["private_only"].as_bool() { b.private_only = v; } if let Some(v) = text("node") { if !v.is_empty() && !registry::nodes().iter().any(|n| n["id"] == v) { bail!("there is no node called {v:?}"); } b.node = v.to_string(); } if let Some(v) = text("brief") { if !line_ok(v, 200) || v.starts_with('/') || v.split('/').any(|p| p == "..") { bail!("the instructions are a file in the repository, as a relative path"); } b.brief = v.to_string(); } if let Some(v) = patch["voice"].as_bool() { b.voice = v; } if let Some(v) = text("openai_key").filter(|v| !v.is_empty()) { if !v.starts_with("sk-") || v.len() < 20 || !line_ok(v, 400) || v.contains(char::is_whitespace) { bail!("that does not look like an OpenAI API key (sk-…)"); } b.openai_key = v.to_string(); } if patch["clear_key"] == true { b.openai_key.clear(); } Ok(()) })?; // What changed, never a value. let fields: Vec<&str> = ["server", "username", "password", "works_for", "private_only", "node", "brief", "voice", "openai_key", "clear_key"] .into_iter().filter(|k| !patch[*k].is_null()).collect(); events::emit("bot_config", json!({"bot": name, "fields": fields, "actor": by})); Ok(()) } pub fn remove(name: &str, by: &str) -> Result { let gone = update(|bots| Ok(bots.remove(name).is_some()))?; if gone { let _ = update_runs(|r| Ok(r.remove(name))); events::emit("bot_config", json!({"bot": name, "removed": true, "actor": by})); } Ok(gone) } /// The environment a bot of this name starts with; empty for a name with no /// configuration. pub fn env_for(name: &str) -> BTreeMap { let mut env = BTreeMap::new(); let Some(b) = read().remove(name) else { return env; }; for (k, v) in [("CARTO_SERVER", &b.server), ("CARTO_USER", &b.username), ("CARTO_PASSWORD", &b.password)] { if !v.is_empty() { env.insert(k.to_string(), v.clone()); } } if b.voice { let key = Some(b.openai_key).filter(|k| !k.is_empty()).or_else(crate::discuss::key); if let Some(k) = key { env.insert("OPENAI_API_KEY".into(), k); } } env } /// The arguments of `midas bot start` for this bot, as the runner runs it in /// a checkout of the Cartopolis repository. No secret is in them: those come /// from the hub at the start (`env_for`), and the client's server is the /// variable, expanded on the node, where the one-word command runs as a shell /// line (`bot::shell_line`). pub fn start_args(name: &str, b: &Bot) -> Vec { let dir = format!("/tmp/bot-{name}"); let sock = format!("{dir}/mcp.sock"); let mut client = format!( "mkdir -p {dir} && exec cargo run -q -p cartopolis -- --mcp-headless --mcp-listen {sock} --connect \"$CARTO_SERVER\"" ); if !b.works_for.is_empty() { client.push_str(&format!(" --mcp-allow {}", sh_quote(&b.works_for))); } if b.private_only { client.push_str(" --mcp-private-only"); } if b.voice { client.push_str(" --voice-agent"); } let brief = if b.brief.is_empty() { DEFAULT_BRIEF } else { &b.brief }; let mut args: Vec = ["bot", "start"].iter().map(|s| (*s).to_string()).collect(); if !b.node.is_empty() { args.extend(["--node".into(), b.node.clone()]); } args.extend([ "--name".into(), name.into(), "--agent".into(), "--brief".into(), brief.into(), // A bot that waits for calls has nothing to answer for hours. "--idle".into(), "0".into(), "--mcp".into(), format!("cargo run -q -p cartopolis -- mcp --socket {sock}"), "--".into(), client, ]); args } /// The page asks for a bot to start or stop. pub fn request(name: &str, action: &str, by: &str) -> Result<()> { let Some(b) = read().remove(name) else { bail!("there is no bot called {name:?}") }; if action == "start" { let gaps = missing(&b); if !gaps.is_empty() { bail!("{name} still needs {} before it can start", gaps.join(", ")); } } else if action != "stop" { bail!("a bot is started or stopped, not {action:?}"); } update_runs(|r| { let run = r.entry(name.to_string()).or_default(); run.want = Some(action.to_string()); run.state = "queued".into(); run.detail = format!("waiting for the sessions runner to {action} it"); run.at = registry::now(); Ok(()) })?; events::emit("bot_requested", json!({"bot": name, "action": action, "actor": by})); // The runner's poll takes it: wake it rather than leave it to its next look. crate::sessions::arrived(); Ok(()) } /// For the runner's poll: the bots asked to start or stop, with what it needs /// to do it. Taken once. pub fn take_requests() -> Vec { let bots = read(); update_runs(|r| { let mut out = Vec::new(); for (name, run) in r.iter_mut() { let Some(action) = run.want.take() else { continue }; let Some(b) = bots.get(name) else { continue }; run.state = if action == "start" { "starting" } else { "stopping" }.into(); run.detail = if action == "start" { format!("building and starting it on {} (a first build takes several minutes)", b.node) } else { "stopping it".into() }; run.at = registry::now(); out.push(json!({"name": name, "action": action, "args": start_args(name, b)})); } Ok(out) }) .unwrap_or_default() } /// The runner says how a start or stop went. pub fn report(name: &str, state: &str, detail: &str) -> Result<()> { if !matches!(state, "running" | "stopped" | "failed") { bail!("not a bot's state: {state:?}"); } let detail: String = detail.chars().take(2000).collect(); update_runs(|r| { let run = r.entry(name.to_string()).or_default(); run.state = state.into(); run.detail = detail.clone(); run.at = registry::now(); Ok(()) })?; events::emit("bot_run", json!({"bot": name, "state": state})); Ok(()) } #[cfg(test)] mod tests { use super::*; #[test] fn a_secret_shows_only_its_tail() { assert_eq!(tail("sk-abcdefgh1234").as_deref(), Some("1234")); assert_eq!(tail(""), None); } #[test] fn a_line_is_one_line() { assert!(line_ok("cartopolis.org", 200)); assert!(!line_ok("a\nb", 200)); assert!(!line_ok(&"x".repeat(201), 200)); } #[test] fn who_it_works_for_reads_as_people_type_it() { assert_eq!(names_list("sam, @anna bob").unwrap(), "sam,anna,bob"); assert!(names_list("sam; rm -rf").is_err()); } #[test] fn the_start_command_carries_no_secret_and_every_choice() { let b = Bot { server: "cartopolis.org".into(), username: "scout".into(), password: "hunter2".into(), works_for: "sam".into(), node: "mac-1".into(), voice: true, ..Bot::default() }; let args = start_args("scout", &b).join(" "); assert!(!args.contains("hunter2") && !args.contains("cartopolis.org"), "{args}"); for part in ["--node mac-1", "--name scout", "--agent", "--brief tools/bot/viberfox.md", "--idle 0", "--connect \"$CARTO_SERVER\"", "--mcp-allow sam", "--mcp-private-only", "--voice-agent"] { assert!(args.contains(part), "{part} in {args}"); } } }