garage44.eu/jeroen/midas

logclone: git clone https://garage44.eu/jeroen/midas.git

.. /src/host.rs

raw

//! A bot with an agent of its own (DESIGN.md §2, "Bots"; decision 18).
//!
//! `midas bot start --agent` starts the bot on its node as always, then a
//! **host** here, where the agent's login is: a detached process that runs the
//! agent and talks to it over the **Agent Client Protocol** (ACP,
//! <https://agentclientprotocol.com>) — JSON-RPC on the agent's stdin and
//! stdout, as an editor drives Claude Code, Codex or Gemini. The agent is
//! Claude Code through midas's own adapter (`midas acp`, acp.rs) unless
//! `--agent '<command>'` names another. The host is the agent's whole world:
//!
//! * **Its tools are the bot's.** The session is opened with one MCP server,
//!   `bot`, which is `midas bot mcp`; every permission the agent asks for is
//!   granted only for a tool of that server, and every other refused.
//!   The agent's own fence stands in front of ours: for midas's Claude Code,
//!   no built-in tools and no settings files (`acp::bot_fence`); for another
//!   agent, whatever `--agent-meta` passes it.
//! * **Its input is the bot's inbox.** A second connection to the bot calls the
//!   inbox tool (`--inbox`, cartopolis's `inbox`) in a loop; it waits until
//!   somebody speaks and answers with what they said, pictures as images. Each
//!   answer becomes one prompt, or joins the next one while a turn is running.
//!   `midas bot tell` adds the operator's own line.
//! * **Nothing keeps it awake.** Between prompts the agent waits on its stdin,
//!   as a Remote Control session waits for its next message, and costs nothing.
//!
//! The lease stays the starting worktree's, so the bot is built from its tree;
//! a session ending leaves a hosted bot alone (`release --keep-hosted`, which
//! the session hook runs). The host gives the node back when it stops: asked
//! (`midas bot stop`), idle for `--idle`, the bot gone, or the agent dying over
//! and over. Its files are in `~/.local/state/midas/bots/<name>/`: the
//! configuration, the session id (a restarted agent loads it and remembers),
//! `transcript.log` (what was heard, said and done) and `host.log`.
//!
//! Nothing here knows about chat: the inbox's content blocks are the prompt,
//! verbatim, and what the agent does about them is between it and the bot.

use std::collections::VecDeque;
use std::fs::{self, OpenOptions};
use std::io::{BufRead, BufReader, Write};
use std::os::unix::process::CommandExt;
use std::path::{Path, PathBuf};
use std::process::{Child, ChildStdin, Command, Stdio};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::{self, Receiver, RecvTimeoutError, Sender};
use std::time::{Duration, Instant};

use anyhow::{anyhow, bail, Context, Result};
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};

use crate::util::short;

/// The ACP revision midas speaks.
const ACP_VERSION: u64 = 1;
/// The MCP server's name in the agent's session; the permission rule keys on it.
pub const SERVER: &str = "bot";
/// How long the inbox tool may wait for somebody to speak (cartopolis caps it at 600).
const INBOX_WAIT_S: u64 = 600;
/// An agent's first start may download it (`npx -y …`) and log in.
const AGENT_START: Duration = Duration::from_secs(300);
/// This many agent deaths inside [`DEATH_WINDOW`] and the host gives up.
const DEATHS: usize = 3;
const DEATH_WINDOW: Duration = Duration::from_secs(600);
/// Consecutive failures to reach the bot's inbox before the host decides the
/// bot is gone. With the backoff, about two minutes.
const INBOX_FAILURES: u32 = 6;

static STOP: AtomicBool = AtomicBool::new(false);

extern "C" fn on_signal(_: libc::c_int) {
    STOP.store(true, Ordering::SeqCst);
}

/// How a hosted bot is run: kept beside it, so the host needs nothing of the
/// worktree that started it.
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
pub struct Config {
    pub name: String,
    /// The lease's owner: the worktree that started it.
    pub owner: String,
    pub node: String,
    /// The ACP agent, a shell command run here.
    pub agent: String,
    /// The bot's instructions: the session's system prompt where the agent
    /// takes one, else the first prompt.
    #[serde(default)]
    pub brief: Option<String>,
    /// `_meta` for `session/new`: the agent's own settings.
    #[serde(default)]
    pub meta: Option<Value>,
    /// The bot's MCP tool that waits for input and answers it as content.
    pub inbox: String,
    /// Stop after this long without input; 0 never.
    pub idle_s: u64,
    /// The ACP session mode to put the session in (`session/set_mode`): one
    /// in which the agent asks before using a tool.
    #[serde(default)]
    pub mode: Option<String>,
    pub started_at: i64,
}

// ─── where its files are ─────────────────────────────────────────────────────

pub fn root() -> PathBuf {
    let base = std::env::var_os("XDG_STATE_HOME").map(PathBuf::from)
        .unwrap_or_else(|| PathBuf::from(std::env::var("HOME").unwrap_or_else(|_| "/tmp".into())).join(".local/state"));
    base.join("midas/bots")
}

pub fn dir(name: &str) -> PathBuf {
    root().join(name)
}

/// A bot's name is a directory's: letters, digits, `-` and `_`.
pub fn name_ok(name: &str) -> bool {
    !name.is_empty() && name.len() <= 40 && name.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
}

fn read_config(name: &str) -> Option<Config> {
    crate::store::read(&dir(name).join("config.json"))
}

/// The host's pid, if it is running: the pid file names a live process whose
/// command line is a `bot host` for this name.
pub fn running(name: &str) -> Option<u32> {
    let pid: u32 = fs::read_to_string(dir(name).join("host.pid")).ok()?.trim().parse().ok()?;
    let cmdline = fs::read(format!("/proc/{pid}/cmdline")).ok()?;
    let words: Vec<String> = cmdline.split(|b| *b == 0).map(|w| String::from_utf8_lossy(w).to_string()).collect();
    let ours = words.windows(2).any(|w| w[0] == "bot" && w[1] == "host") && words.iter().any(|w| w == name);
    ours.then_some(pid)
}

/// Every hosted bot this machine knows of, running or not.
pub fn all() -> Vec<Config> {
    let mut v: Vec<Config> = fs::read_dir(root()).into_iter().flatten().flatten()
        .filter_map(|e| read_config(&e.file_name().to_string_lossy())).collect();
    v.sort_by(|a, b| a.name.cmp(&b.name));
    v
}

/// The running host for a lease owner, if there is one.
pub fn hosted_by(owner: &str) -> Option<Config> {
    all().into_iter().find(|c| c.owner == owner && running(&c.name).is_some())
}

/// The bot `name` names, or else the one `owner`'s lease runs.
pub fn find(name: Option<&str>, owner: &str) -> Option<Config> {
    match name {
        Some(n) => read_config(n),
        None => all().into_iter().filter(|c| c.owner == owner).max_by_key(|c| (running(&c.name).is_some(), c.started_at)),
    }
}

// ─── starting and stopping, from where agents work ───────────────────────────

/// Start the host for `cfg` (the bot is up already), detached, and wait until
/// it has a session with its agent. Returns the host's last words on failure.
pub fn launch(cfg: &Config) -> Result<()> {
    let d = dir(&cfg.name);
    fs::create_dir_all(d.join("work"))?;
    fs::create_dir_all(d.join("tell"))?;
    restrict(&d);
    let _ = fs::remove_file(d.join("ready"));
    let _ = fs::remove_file(d.join("failed"));
    // Whole or not at all: `bot status` and `release --keep-hosted` read it any time.
    crate::store::write_json(&d.join("config.json"), cfg, crate::store::PRIVATE)?;
    let log = OpenOptions::new().create(true).append(true).open(d.join("host.log"))?;
    let exe = crate::util::exe().context("finding midas")?;
    let mut c = Command::new(exe);
    c.args(["bot", "host", &cfg.name]).current_dir(&d)
        // Every ssh it makes is to its own bot, built already: no flush, and no
        // check that the directory it runs in holds the node.
        .env("MIDAS_FLUSHING", "1")
        .stdin(Stdio::null()).stdout(log.try_clone()?).stderr(log);
    // The starting session's own variables (its id, its messaging socket and
    // token, "you are inside Claude Code") are not the agent's: a Claude Code
    // agent that inherited them would take itself for part of that session.
    // Where the login lives (CLAUDE_CONFIG_DIR) is kept.
    for (k, _) in std::env::vars_os() {
        let k = k.to_string_lossy();
        if session_var(&k) {
            c.env_remove(&*k);
        }
    }
    // SAFETY: setsid in the child before exec, async-signal-safe.
    unsafe {
        c.pre_exec(|| {
            if libc::setsid() == -1 {
                return Err(std::io::Error::last_os_error());
            }
            Ok(())
        });
    }
    let mut child = c.spawn().context("starting the host")?;
    let limit = AGENT_START + Duration::from_secs(60);
    let until = Instant::now() + limit;
    loop {
        if d.join("ready").exists() {
            // Not waited for: it outlives this process, and init reaps it.
            return Ok(());
        }
        if let Ok(why) = fs::read_to_string(d.join("failed")) {
            let _ = child.wait();
            bail!("{}", why.trim());
        }
        if let Some(st) = child.try_wait()? {
            bail!("the host exited ({st}) before its agent was ready — {}", d.join("host.log").display());
        }
        if Instant::now() > until {
            bail!("the host's agent was not ready in {}s — {}", limit.as_secs(), d.join("host.log").display());
        }
        std::thread::sleep(Duration::from_millis(300));
    }
}

/// A variable of the agent session that ran `bot start`, not to be handed on.
pub fn session_var(k: &str) -> bool {
    k == "CLAUDECODE" || k == "CLAUDE_PID" || k == "CLAUDE_EFFORT" || k.starts_with("CLAUDE_CODE_")
}

/// Only this user reads a bot's directory: the transcript is its chat.
fn restrict(d: &Path) {
    use std::os::unix::fs::PermissionsExt;
    let _ = fs::set_permissions(d, fs::Permissions::from_mode(0o700));
}

/// Ask the host to stop and wait for it; it gives the node back itself.
/// Returns false when no host was running.
pub fn stop(name: &str) -> bool {
    let Some(pid) = running(name) else { return false };
    // SAFETY: kill(2) on the host this user started, found by its pid file.
    unsafe { libc::kill(pid as i32, libc::SIGTERM) };
    let until = Instant::now() + Duration::from_secs(40);
    while running(name).is_some() && Instant::now() < until {
        std::thread::sleep(Duration::from_millis(200));
    }
    if running(name).is_some() {
        unsafe { libc::kill(pid as i32, libc::SIGKILL) };
    }
    true
}

/// `midas bot tell`: one line from the operator, for the agent's next prompt.
pub fn tell(name: &str, text: &str) -> Result<i32> {
    if running(name).is_none() {
        eprintln!("no hosted bot {name} is running");
        return Ok(1);
    }
    let d = dir(name).join("tell");
    let stamp = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH)?.as_nanos();
    let tmp = d.join(format!(".{stamp}"));
    fs::write(&tmp, text)?;
    fs::rename(&tmp, d.join(format!("{stamp}.txt")))?;
    eprintln!("told {name}; it hears it with its next prompt (midas bot log {name} shows what it did)");
    Ok(0)
}

/// `midas bot log`: the last of the transcript.
pub fn log(name: &str, lines: usize) -> Result<i32> {
    let path = dir(name).join("transcript.log");
    let Ok(text) = fs::read_to_string(&path) else {
        eprintln!("no transcript for {name} ({})", path.display());
        return Ok(1);
    };
    let all: Vec<&str> = text.lines().collect();
    for l in &all[all.len().saturating_sub(lines)..] {
        println!("{l}");
    }
    eprintln!("({}; the host's own log: {})", path.display(), dir(name).join("host.log").display());
    Ok(0)
}

/// For `midas bot status`: a line or two about the host.
pub fn describe(cfg: &Config) -> String {
    let state = match running(&cfg.name) {
        Some(pid) => format!("hosted by pid {pid}"),
        None => "its host is not running".into(),
    };
    format!("{}: {state}, since {}; agent `{}`, input from `{}`, idle limit {}",
            cfg.name, crate::cli::ago(cfg.started_at), cfg.agent, cfg.inbox,
            if cfg.idle_s == 0 { "none".to_string() } else { format!("{} min", cfg.idle_s / 60) })
}

// ─── the host ────────────────────────────────────────────────────────────────

enum Event {
    /// A line from agent generation `gen`.
    Agent(u64, Value),
    AgentGone(u64),
    /// Content blocks from the bot's inbox.
    Input(Vec<Value>),
    /// What the inbox held before the host first asked: history, not input.
    Backlog(Vec<Value>),
    /// The bot cannot be reached any more.
    BotGone(String),
}

/// One run of the agent: its process, and the next JSON-RPC id. Its output
/// arrives tagged with the run's generation, so a replaced run's is ignored.
struct Agent {
    child: Child,
    stdin: ChildStdin,
    next_id: u64,
}

impl Agent {
    fn spawn(cfg: &Config, gen: u64, tx: Sender<Event>) -> Result<Agent> {
        let mut c = Command::new("bash");
        c.arg("-c").arg(&cfg.agent).current_dir(dir(&cfg.name).join("work"))
            .stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::inherit());
        // SAFETY: setpgid in the child before exec, async-signal-safe.
        unsafe {
            c.pre_exec(|| {
                libc::setpgid(0, 0);
                Ok(())
            });
        }
        let mut child = c.spawn().with_context(|| format!("starting the agent `{}`", cfg.agent))?;
        let stdin = child.stdin.take().unwrap();
        let out = child.stdout.take().unwrap();
        std::thread::spawn(move || {
            for line in BufReader::new(out).lines().map_while(Result::ok) {
                let Ok(v) = serde_json::from_str::<Value>(&line) else {
                    eprintln!("agent said (not JSON): {}", short(&line, 200));
                    continue;
                };
                if tx.send(Event::Agent(gen, v)).is_err() {
                    return;
                }
            }
            let _ = tx.send(Event::AgentGone(gen));
        });
        Ok(Agent { child, stdin, next_id: 1 })
    }

    fn send(&mut self, v: &Value) -> Result<()> {
        writeln!(self.stdin, "{v}")?;
        self.stdin.flush()?;
        Ok(())
    }

    fn request(&mut self, method: &str, params: Value) -> Result<u64> {
        let id = self.next_id;
        self.next_id += 1;
        self.send(&json!({"jsonrpc": "2.0", "id": id, "method": method, "params": params}))?;
        Ok(id)
    }

    fn kill(&mut self) {
        let pg = self.child.id() as i32;
        // SAFETY: kill(2) on the agent's own process group (pgid > 1, ours).
        if pg > 1 {
            unsafe { libc::kill(-pg, libc::SIGTERM) };
            let until = Instant::now() + Duration::from_secs(5);
            while Instant::now() < until {
                if self.child.try_wait().ok().flatten().is_some() {
                    break;
                }
                std::thread::sleep(Duration::from_millis(100));
            }
            unsafe { libc::kill(-pg, libc::SIGKILL) };
        }
        let _ = self.child.wait();
    }
}

/// What the agent said it can do, from `initialize`.
#[derive(Default, Debug)]
struct Caps {
    load: bool,
    images: bool,
    system_prompt: bool,
}

fn caps_of(init: &Value) -> Caps {
    let a = &init["agentCapabilities"];
    Caps {
        load: a["loadSession"].as_bool().unwrap_or(false),
        images: a["promptCapabilities"]["image"].as_bool().unwrap_or(false),
        system_prompt: a["sessionCapabilities"]["systemPrompt"].is_object(),
    }
}

/// The permission rule: which MCP server a tool call belongs to, as far as the
/// agent says. ACP has no field for it, so the agents' own: Claude Code names
/// the server in `_meta.claudeCode.mcpServer` and the tool `mcp__<server>__…`;
/// others put that name in the title.
pub fn server_of(tool_call: &Value) -> Option<String> {
    let meta = &tool_call["_meta"];
    if let Some(m) = meta.as_object() {
        for v in m.values() {
            if let Some(n) = v["mcpServer"]["name"].as_str() {
                return Some(n.to_string());
            }
        }
        for v in m.values() {
            if let Some(n) = v["toolName"].as_str().and_then(prefixed) {
                return Some(n);
            }
        }
    }
    tool_call["title"].as_str().and_then(prefixed)
}

/// `mcp__<server>__<tool>` → the server.
fn prefixed(name: &str) -> Option<String> {
    let rest = name.strip_prefix("mcp__")?;
    let (server, _) = rest.split_once("__")?;
    Some(server.to_string())
}

/// The answer to a `session/request_permission`: allow once for the bot's own
/// tools, refuse everything else. Never an "always" option, which an agent may
/// write into its settings.
pub fn decide(params: &Value) -> (Value, bool) {
    let ours = server_of(&params["toolCall"]).as_deref() == Some(SERVER);
    let options = params["options"].as_array().cloned().unwrap_or_default();
    let pick = |kind: &str| options.iter().find(|o| o["kind"] == kind).and_then(|o| o["optionId"].as_str()).map(str::to_string);
    let choice = if ours { pick("allow_once") } else { pick("reject_once") };
    let outcome = match choice {
        Some(id) => json!({"outcome": {"outcome": "selected", "optionId": id}}),
        None => json!({"outcome": {"outcome": "cancelled"}}),
    };
    (outcome, ours)
}

/// The content blocks of an inbox answer as a prompt this agent can take:
/// text and images as they are (images only where the agent takes them),
/// anything else said in words.
pub fn prompt_blocks(content: &[Value], images: bool) -> Vec<Value> {
    content.iter().filter_map(|b| match b["type"].as_str() {
        Some("text") => b["text"].as_str().filter(|t| !t.trim().is_empty()).map(|t| json!({"type": "text", "text": t})),
        Some("image") if images => Some(json!({"type": "image", "data": b["data"], "mimeType": b["mimeType"]})),
        Some("image") => Some(json!({"type": "text", "text": "[a picture came with this, which this agent cannot take]"})),
        Some(other) => Some(json!({"type": "text", "text": format!("[a {other} came with this, which midas does not pass on]")})),
        None => None,
    }).collect()
}

struct Host {
    cfg: Config,
    rx: Receiver<Event>,
    tx: Sender<Event>,
    agent: Option<Agent>,
    gen: u64,
    caps: Caps,
    session: Option<String>,
    /// The prompt being answered: its request id and its blocks (put back if
    /// the agent dies under it).
    turn: Option<(u64, Vec<Value>)>,
    queue: VecDeque<Value>,
    /// The brief, when the agent took no system prompt and it is still to be sent.
    brief_first: bool,
    /// A `session/load` is replaying the session's history as updates: told,
    /// not done, so not in the transcript.
    replaying: bool,
    reply: String,
    last_input: Instant,
    /// Why the bot cannot be reached, once the inbox has given up on it.
    bot_gone: Option<String>,
    deaths: VecDeque<Instant>,
    transcript: fs::File,
}

/// `midas bot host <name>`: run until stopped. Its exit gives the node back.
pub fn run(name: &str) -> Result<i32> {
    let cfg = read_config(name).ok_or_else(|| anyhow!("no configuration for bot {name} in {}", dir(name).display()))?;
    let d = dir(name);
    fs::write(d.join("host.pid"), std::process::id().to_string())?;
    // SAFETY: installing a handler that only stores to an atomic.
    unsafe {
        libc::signal(libc::SIGTERM, on_signal as *const () as libc::sighandler_t);
        libc::signal(libc::SIGINT, on_signal as *const () as libc::sighandler_t);
        libc::signal(libc::SIGHUP, on_signal as *const () as libc::sighandler_t);
        libc::signal(libc::SIGPIPE, libc::SIG_IGN);
    }
    let transcript = OpenOptions::new().create(true).append(true).open(d.join("transcript.log"))?;
    let (tx, rx) = mpsc::channel();
    let mut host = Host {
        cfg: cfg.clone(), rx, tx: tx.clone(), agent: None, gen: 0, caps: Caps::default(), session: None,
        turn: None, queue: VecDeque::new(), brief_first: false, replaying: false, reply: String::new(),
        last_input: Instant::now(), bot_gone: None, deaths: VecDeque::new(), transcript,
    };
    host.note(&format!("host started for {} on {}", cfg.owner, cfg.node));
    if let Err(e) = host.start_agent() {
        let why = format!("the agent did not start: {e:#}");
        host.note(&why);
        let _ = fs::write(d.join("failed"), &why);
        host.shutdown(&why);
        return Ok(1);
    }
    fs::write(d.join("ready"), "")?;
    {
        let cfg = cfg.clone();
        std::thread::spawn(move || inbox_loop(&cfg, &tx));
    }
    let why = host.serve();
    host.shutdown(&why);
    Ok(0)
}

impl Host {
    fn note(&mut self, what: &str) {
        let line = format!("{} {what}", chrono::Local::now().format("%Y-%m-%d %H:%M:%S"));
        let _ = writeln!(self.transcript, "{line}");
        eprintln!("{line}");
    }

    fn agent(&mut self) -> Result<&mut Agent> {
        self.agent.as_mut().ok_or_else(|| anyhow!("no agent"))
    }

    /// Start (or restart) the agent and open its session: the saved one where
    /// it can load it, else a new one.
    fn start_agent(&mut self) -> Result<()> {
        self.gen += 1;
        self.agent = Some(Agent::spawn(&self.cfg, self.gen, self.tx.clone())?);
        let init = self.call("initialize", json!({
            "protocolVersion": ACP_VERSION,
            "clientCapabilities": {"fs": {"readTextFile": false, "writeTextFile": false}, "terminal": false},
            "clientInfo": {"name": "midas", "version": crate::VERSION},
        }), AGENT_START)?;
        self.caps = caps_of(&init);
        let cwd = dir(&self.cfg.name).join("work");
        let mut params = json!({"cwd": cwd, "mcpServers": [self.mcp_server()]});
        if let Some(meta) = &self.cfg.meta {
            params["_meta"] = meta.clone();
        }
        if let (true, Some(brief)) = (self.caps.system_prompt, &self.cfg.brief) {
            params["systemPrompt"] = json!({"mode": "append", "content": [{"type": "text", "text": brief}]});
        }
        let saved = fs::read_to_string(dir(&self.cfg.name).join("session")).ok().map(|s| s.trim().to_string());
        if let (true, Some(id)) = (self.caps.load, saved.filter(|s| !s.is_empty())) {
            let mut p = params.clone();
            p["sessionId"] = json!(id);
            self.replaying = true;
            let loaded = self.call("session/load", p, AGENT_START);
            self.replaying = false;
            self.reply.clear();
            match loaded {
                Ok(_) => {
                    self.set_mode(&id)?;
                    self.note(&format!("agent up, session {id} loaded"));
                    self.session = Some(id);
                    return Ok(());
                }
                Err(e) => self.note(&format!("could not load session {id} ({e:#}); starting a new one")),
            }
        }
        let made = self.call("session/new", params, AGENT_START)?;
        let id = made["sessionId"].as_str().ok_or_else(|| anyhow!("session/new answered no sessionId"))?.to_string();
        self.set_mode(&id)?;
        fs::write(dir(&self.cfg.name).join("session"), &id)?;
        self.note(&format!("agent up, new session {id}{}", if self.caps.images { "" } else { " (it takes no images)" }));
        self.session = Some(id);
        self.brief_first = !self.caps.system_prompt && self.cfg.brief.is_some();
        Ok(())
    }

    /// Put the session in `--agent-mode`, every time it is opened: an agent may
    /// otherwise take its mode from its user's settings or the resumed
    /// session's, and a mode that approves tool calls by itself never asks the
    /// host. (Claude Code took "auto" from this container's settings, and its
    /// own check refused the bot's first private message.) No mode set, no
    /// session.
    fn set_mode(&mut self, session: &str) -> Result<()> {
        let Some(mode) = self.cfg.mode.clone() else { return Ok(()) };
        self.call("session/set_mode", json!({"sessionId": session, "modeId": mode}), Duration::from_secs(60))
            .with_context(|| format!("putting the session in mode {mode}"))?;
        Ok(())
    }

    /// The bot, as the one MCP server the agent's session has. `bot mcp` is
    /// given its owner, and sets what its ssh needs itself, so an agent that
    /// starts servers with a bare environment reaches the bot too.
    fn mcp_server(&self) -> Value {
        let exe = crate::util::exe().map(|p| p.to_string_lossy().to_string()).unwrap_or_else(|_| "midas".into());
        json!({"name": SERVER, "command": exe, "args": ["bot", "mcp", "--owner", self.cfg.owner],
               "env": [{"name": "MIDAS_FLUSHING", "value": "1"}]})
    }

    /// A request to the agent, answered within `wait`; what arrives meanwhile
    /// is handled as usual (inbox input queues).
    fn call(&mut self, method: &str, params: Value, wait: Duration) -> Result<Value> {
        let id = self.agent()?.request(method, params)?;
        let gen = self.gen;
        let until = Instant::now() + wait;
        loop {
            if STOP.load(Ordering::SeqCst) {
                bail!("stopped while waiting for {method}");
            }
            let left = until.saturating_duration_since(Instant::now());
            if left.is_zero() {
                bail!("no answer to {method} in {}s", wait.as_secs());
            }
            match self.rx.recv_timeout(left.min(Duration::from_secs(1))) {
                Ok(Event::Agent(g, msg)) if g == gen && msg["id"] == id && msg.get("method").is_none() => {
                    if let Some(e) = msg.get("error") {
                        bail!("{method}: {}", e["message"].as_str().unwrap_or(&e.to_string()));
                    }
                    return Ok(msg["result"].clone());
                }
                Ok(Event::AgentGone(g)) if g == gen => bail!("the agent exited during {method}"),
                Ok(ev) => self.handle(ev)?,
                Err(RecvTimeoutError::Timeout) => {}
                Err(RecvTimeoutError::Disconnected) => bail!("lost the agent's output"),
            }
        }
    }

    /// Until something ends it; returns why.
    fn serve(&mut self) -> String {
        loop {
            if STOP.load(Ordering::SeqCst) {
                return "asked to stop".into();
            }
            if self.cfg.idle_s > 0 && self.turn.is_none() && self.last_input.elapsed() > Duration::from_secs(self.cfg.idle_s) {
                return format!("nothing to answer for {} min", self.cfg.idle_s / 60);
            }
            if let Some(why) = self.bot_gone.take() {
                return format!("the bot is gone: {why}");
            }
            match self.rx.recv_timeout(Duration::from_secs(1)) {
                Ok(Event::AgentGone(g)) if g == self.gen => {
                    if let Err(why) = self.revive() {
                        return why;
                    }
                }
                Ok(ev) => {
                    if let Err(e) = self.handle(ev) {
                        self.note(&format!("talking to the agent failed: {e:#}"));
                    }
                }
                Err(RecvTimeoutError::Timeout) => {}
                Err(RecvTimeoutError::Disconnected) => return "lost every input".into(),
            }
            self.take_tells();
            if let Err(e) = self.prompt_if_due() {
                self.note(&format!("could not prompt the agent: {e:#}"));
            }
        }
    }

    /// The agent died: start it again, unless it keeps dying.
    fn revive(&mut self) -> Result<(), String> {
        let now = Instant::now();
        self.deaths.push_back(now);
        while self.deaths.front().is_some_and(|t| now.duration_since(*t) > DEATH_WINDOW) {
            self.deaths.pop_front();
        }
        if let Some((_, blocks)) = self.turn.take() {
            for b in blocks.into_iter().rev() {
                self.queue.push_front(b);
            }
        }
        if let Some(mut a) = self.agent.take() {
            a.kill();
        }
        if self.deaths.len() >= DEATHS {
            return Err(format!("the agent exited {DEATHS} times in {} min", DEATH_WINDOW.as_secs() / 60));
        }
        self.note("the agent exited; starting it again");
        self.start_agent().map_err(|e| format!("the agent would not start again: {e:#}"))
    }

    fn handle(&mut self, ev: Event) -> Result<()> {
        match ev {
            Event::Input(content) => {
                self.last_input = Instant::now();
                let blocks = prompt_blocks(&content, self.caps.images);
                for b in &blocks {
                    match b["type"].as_str() {
                        Some("text") => {
                            let t = b["text"].as_str().unwrap_or("").to_string();
                            self.note(&format!("heard: {}", t.replace('\n', "\n    ")));
                        }
                        _ => self.note("heard: [a picture]"),
                    }
                }
                self.queue.extend(blocks);
            }
            Event::Backlog(content) => {
                let text: Vec<&str> = content.iter().filter_map(|b| b["text"].as_str()).collect();
                self.note(&format!("skipped what was said before it started:\n    {}", text.join("\n").replace('\n', "\n    ")));
            }
            Event::Agent(gen, msg) if gen == self.gen => self.from_agent(msg)?,
            // A message from an agent run already replaced, or its end.
            Event::Agent(..) | Event::AgentGone(_) => {}
            // `serve` ends on it, after whatever it is in the middle of.
            Event::BotGone(why) => self.bot_gone = Some(why),
        }
        Ok(())
    }

    fn from_agent(&mut self, msg: Value) -> Result<()> {
        let method = msg["method"].as_str();
        match (method, msg.get("id")) {
            // A request to us.
            (Some(m), Some(id)) => {
                let id = id.clone();
                let answer = if m == "session/request_permission" {
                    let (outcome, ours) = decide(&msg["params"]);
                    let title = msg["params"]["toolCall"]["title"].as_str().unwrap_or("?").to_string();
                    if !ours {
                        self.note(&format!("refused: {title} (not one of the bot's tools)"));
                    }
                    json!({"jsonrpc": "2.0", "id": id, "result": outcome})
                } else {
                    json!({"jsonrpc": "2.0", "id": id, "error": {"code": -32601, "message": format!("midas offers no {m}")}})
                };
                self.agent()?.send(&answer)?;
            }
            // A notification.
            (Some("session/update"), None) if self.replaying => {}
            (Some("session/update"), None) => {
                let u = &msg["params"]["update"];
                match u["sessionUpdate"].as_str() {
                    Some("agent_message_chunk") => {
                        if let Some(t) = u["content"]["text"].as_str() {
                            self.reply.push_str(t);
                        }
                    }
                    Some("tool_call") => {
                        let title = u["title"].as_str().unwrap_or("a tool").to_string();
                        let input = u.get("rawInput").filter(|v| v.as_object().is_some_and(|o| !o.is_empty()))
                            .map(|v| format!(" {}", short(&v.to_string(), 300))).unwrap_or_default();
                        self.note(&format!("did: {}{input}", short(&title, 160)));
                    }
                    Some("tool_call_update") if u["status"] == "failed" => {
                        let why = u["content"].as_array().into_iter().flatten()
                            .filter_map(|c| c["content"]["text"].as_str()).collect::<Vec<_>>().join(" ");
                        self.note(&format!("failed: {}", short(&why, 300)));
                    }
                    _ => {}
                }
            }
            (Some(_), None) => {}
            // An answer: the prompt's, when its turn ends.
            (None, Some(id)) => {
                if self.turn.as_ref().is_some_and(|(t, _)| msg["id"] == *t) {
                    self.turn = None;
                    let said = std::mem::take(&mut self.reply);
                    if !said.trim().is_empty() {
                        self.note(&format!("thought: {}", short(said.trim(), 600).replace('\n', "\n    ")));
                    }
                    match (msg["result"]["stopReason"].as_str(), msg.get("error")) {
                        (_, Some(e)) => self.note(&format!("the turn failed: {}", e["message"].as_str().unwrap_or("?"))),
                        (Some("end_turn"), _) | (None, _) => {}
                        (Some(r), _) => self.note(&format!("the turn ended: {r}")),
                    }
                } else if let Some(e) = msg.get("error") {
                    self.note(&format!("the agent refused request {id}: {}", e["message"].as_str().unwrap_or("?")));
                }
            }
            (None, None) => {}
        }
        Ok(())
    }

    /// The operator's lines (`midas bot tell`), oldest first.
    fn take_tells(&mut self) {
        let d = dir(&self.cfg.name).join("tell");
        let mut files: Vec<PathBuf> = fs::read_dir(&d).into_iter().flatten().flatten().map(|e| e.path())
            .filter(|p| p.extension().is_some_and(|x| x == "txt")).collect();
        files.sort();
        for f in files {
            if let Ok(text) = fs::read_to_string(&f) {
                self.note(&format!("told: {}", text.trim()));
                self.queue.push_back(json!({"type": "text", "text": format!(
                    "A note from the operator, through midas (not from chat): {}", text.trim())}));
                self.last_input = Instant::now();
            }
            let _ = fs::remove_file(&f);
        }
    }

    /// Everything queued, as one prompt, once the agent is between turns.
    fn prompt_if_due(&mut self) -> Result<()> {
        if self.turn.is_some() || self.queue.is_empty() {
            return Ok(());
        }
        let Some(session) = self.session.clone() else { return Ok(()) };
        let mut blocks: Vec<Value> = self.queue.drain(..).collect();
        if self.brief_first {
            self.brief_first = false;
            if let Some(brief) = &self.cfg.brief {
                blocks.insert(0, json!({"type": "text", "text": format!("Your instructions, from the operator:\n\n{brief}")}));
            }
        }
        let id = self.agent()?.request("session/prompt", json!({"sessionId": session, "prompt": blocks}))?;
        self.turn = Some((id, blocks));
        Ok(())
    }

    /// Stop the agent and give the node back.
    fn shutdown(&mut self, why: &str) {
        self.note(&format!("stopping: {why}"));
        if let (Some((_, _)), Some(session)) = (&self.turn, self.session.clone()) {
            if let Some(a) = self.agent.as_mut() {
                let _ = a.send(&json!({"jsonrpc": "2.0", "method": "session/cancel", "params": {"sessionId": session}}));
            }
        }
        if let Some(mut a) = self.agent.take() {
            a.kill();
        }
        crate::events::emit("bot_host_stopped", json!({"name": self.cfg.name, "node": self.cfg.node,
                                                       "owner": self.cfg.owner, "why": why}));
        // Stops the bot on the node first (`cli::release`); a lease already
        // gone has nothing to release.
        let _ = crate::cli::release(&self.cfg.owner, Some(&self.cfg.node), false);
        let d = dir(&self.cfg.name);
        let _ = fs::remove_file(d.join("host.pid"));
        let _ = fs::remove_file(d.join("ready"));
    }
}

// ─── the bot's inbox ─────────────────────────────────────────────────────────

/// One MCP connection to the bot (`midas bot mcp`), for the inbox alone.
struct Mcp {
    child: Child,
    stdin: ChildStdin,
    rx: Receiver<Value>,
    next_id: u64,
}

impl Mcp {
    fn open(cfg: &Config) -> Result<Mcp> {
        let exe = crate::util::exe()?;
        let mut c = Command::new(exe);
        c.args(["bot", "mcp", "--owner", &cfg.owner]).env("MIDAS_FLUSHING", "1")
            .stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::inherit());
        // SAFETY: setpgid in the child before exec, async-signal-safe.
        unsafe {
            c.pre_exec(|| {
                libc::setpgid(0, 0);
                Ok(())
            });
        }
        let mut child = c.spawn()?;
        let stdin = child.stdin.take().unwrap();
        let out = child.stdout.take().unwrap();
        let (tx, rx) = mpsc::channel();
        std::thread::spawn(move || {
            for line in BufReader::new(out).lines().map_while(Result::ok) {
                if let Ok(v) = serde_json::from_str::<Value>(&line) {
                    if tx.send(v).is_err() {
                        return;
                    }
                }
            }
        });
        let mut m = Mcp { child, stdin, rx, next_id: 1 };
        m.call("initialize", json!({"protocolVersion": crate::mcp::PROTOCOL, "capabilities": {},
                                    "clientInfo": {"name": "midas-host", "version": crate::VERSION}}), Duration::from_secs(60))?;
        writeln!(m.stdin, "{}", json!({"jsonrpc": "2.0", "method": "notifications/initialized"}))?;
        Ok(m)
    }

    fn call(&mut self, method: &str, params: Value, wait: Duration) -> Result<Value> {
        let id = self.next_id;
        self.next_id += 1;
        writeln!(self.stdin, "{}", json!({"jsonrpc": "2.0", "id": id, "method": method, "params": params}))?;
        self.stdin.flush()?;
        let until = Instant::now() + wait;
        loop {
            let left = until.saturating_duration_since(Instant::now());
            if left.is_zero() {
                bail!("no answer to {method} in {}s", wait.as_secs());
            }
            match self.rx.recv_timeout(left) {
                Ok(v) if v["id"] == id => {
                    if let Some(e) = v.get("error") {
                        bail!("{method}: {}", e["message"].as_str().unwrap_or(&e.to_string()));
                    }
                    return Ok(v["result"].clone());
                }
                Ok(_) => {}
                Err(RecvTimeoutError::Timeout) => bail!("no answer to {method} in {}s", wait.as_secs()),
                Err(RecvTimeoutError::Disconnected) => bail!("the connection to the bot ended"),
            }
        }
    }
}

impl Drop for Mcp {
    fn drop(&mut self) {
        let pg = self.child.id() as i32;
        // SAFETY: kill(2) on the relay's own process group (pgid > 1, ours).
        if pg > 1 {
            unsafe { libc::kill(-pg, libc::SIGKILL) };
        }
        let _ = self.child.wait();
    }
}

/// Call the inbox until the host stops, handing every non-empty answer on.
fn inbox_loop(cfg: &Config, tx: &Sender<Event>) {
    let mut failures = 0u32;
    // A client that has just signed in holds the chat history the server sent
    // it, all unread: the first hosted agent answered a day-old "follow me".
    // Asked once without waiting, that is the backlog, and only logged.
    let mut backlog = true;
    while !STOP.load(Ordering::SeqCst) {
        let last = match Mcp::open(cfg) {
            Ok(mut m) => loop {
                if backlog {
                    match m.call("tools/call", json!({"name": cfg.inbox, "arguments": {"wait_s": 0}}), Duration::from_secs(90)) {
                        Ok(r) if r["isError"] != true => {
                            backlog = false;
                            let content = r["content"].as_array().cloned().unwrap_or_default();
                            if !content.is_empty() && tx.send(Event::Backlog(content)).is_err() {
                                return;
                            }
                        }
                        // Signed out, or still signing in: ask again below.
                        Ok(_) => {}
                        Err(e) => break format!("the inbox connection failed: {e:#}"),
                    }
                }
                if STOP.load(Ordering::SeqCst) {
                    return;
                }
                match m.call("tools/call", json!({"name": cfg.inbox, "arguments": {"wait_s": INBOX_WAIT_S}}),
                             Duration::from_secs(INBOX_WAIT_S + 90)) {
                    Ok(r) => {
                        failures = 0;
                        let content = r["content"].as_array().cloned().unwrap_or_default();
                        if r["isError"] == true {
                            // A refusal (signed out, offline): the bot is there,
                            // its account is not; ask again in a while.
                            let why = content.iter().filter_map(|b| b["text"].as_str()).collect::<Vec<_>>().join(" ");
                            eprintln!("{} the inbox refused: {}", chrono::Local::now().format("%H:%M:%S"), short(&why, 200));
                            std::thread::sleep(Duration::from_secs(20));
                        } else if !content.is_empty() && tx.send(Event::Input(content)).is_err() {
                            return;
                        }
                    }
                    Err(e) => break format!("the inbox connection failed: {e:#}"),
                }
            },
            Err(e) => format!("could not reach the bot: {e:#}"),
        };
        eprintln!("{} {last}", chrono::Local::now().format("%H:%M:%S"));
        failures += 1;
        if failures >= INBOX_FAILURES {
            let _ = tx.send(Event::BotGone(last));
            return;
        }
        std::thread::sleep(Duration::from_secs(5 * failures as u64));
    }
}

/// `--idle`: seconds, or with a unit (`90m`, `2h`, `1d`); 0 is never.
pub fn parse_idle(s: &str) -> Result<u64> {
    crate::util::seconds(s).ok_or_else(|| anyhow!("--idle takes seconds or 90m, 2h, 1d; not {s:?}"))
}

/// `--agent-meta`: JSON, or `@file` holding it.
pub fn parse_meta(s: &str) -> Result<Value> {
    let text = match s.strip_prefix('@') {
        Some(path) => fs::read_to_string(path).with_context(|| format!("reading {path}"))?,
        None => s.to_string(),
    };
    let v: Value = serde_json::from_str(&text).context("--agent-meta is not JSON")?;
    if !v.is_object() {
        bail!("--agent-meta must be a JSON object");
    }
    Ok(v)
}

#[cfg(test)]
mod tests {
    use super::*;

    fn permission(tool_call: Value) -> Value {
        json!({"sessionId": "s", "toolCall": tool_call, "options": [
            {"optionId": "always", "name": "Always allow", "kind": "allow_always"},
            {"optionId": "once", "name": "Allow", "kind": "allow_once"},
            {"optionId": "no", "name": "Reject", "kind": "reject_once"},
        ]})
    }

    #[test]
    fn only_the_bots_own_tools_are_allowed_and_only_once() {
        let claude = permission(json!({"toolCallId": "1", "title": "walk_to",
            "_meta": {"claudeCode": {"toolName": "mcp__bot__walk_to", "mcpServer": {"name": "bot", "source": "dynamic"}}}}));
        assert_eq!(decide(&claude), (json!({"outcome": {"outcome": "selected", "optionId": "once"}}), true));
        let titled = permission(json!({"toolCallId": "2", "title": "mcp__bot__say"}));
        assert!(decide(&titled).1);
        for other in [json!({"toolCallId": "3", "title": "Bash", "kind": "execute", "_meta": {"claudeCode": {"toolName": "Bash"}}}),
                      json!({"toolCallId": "4", "title": "mcp__midas__node_take"}),
                      json!({"toolCallId": "5", "title": "walk_to"}),
                      json!({"toolCallId": "6", "title": "x", "_meta": {"claudeCode": {"mcpServer": {"name": "bot2"}}}})] {
            assert_eq!(decide(&permission(other)), (json!({"outcome": {"outcome": "selected", "optionId": "no"}}), false));
        }
    }

    #[test]
    fn a_request_with_no_reject_option_is_cancelled() {
        let p = json!({"toolCall": {"title": "Bash"}, "options": [{"optionId": "ok", "kind": "allow_once"}]});
        assert_eq!(decide(&p).0, json!({"outcome": {"outcome": "cancelled"}}));
    }

    #[test]
    fn the_server_name_comes_from_the_agents_own_fields() {
        assert_eq!(server_of(&json!({"_meta": {"other": {"mcpServer": {"name": "bot"}}}})).as_deref(), Some("bot"));
        assert_eq!(server_of(&json!({"_meta": {"claudeCode": {"toolName": "mcp__bot__look"}}})).as_deref(), Some("bot"));
        assert_eq!(server_of(&json!({"title": "Read"})), None);
        assert_eq!(server_of(&json!({"title": "mcp__bot"})), None);
    }

    #[test]
    fn pictures_pass_only_to_an_agent_that_takes_them() {
        let content = vec![json!({"type": "text", "text": "[12] sam: look"}),
                           json!({"type": "image", "data": "AAAA", "mimeType": "image/jpeg"}),
                           json!({"type": "text", "text": "  "}),
                           json!({"type": "audio", "data": "x"})];
        let with = prompt_blocks(&content, true);
        assert_eq!(with[1], json!({"type": "image", "data": "AAAA", "mimeType": "image/jpeg"}));
        assert_eq!(with.len(), 3);
        let without = prompt_blocks(&content, false);
        assert_eq!(without[1]["type"], "text");
        assert!(without[2]["text"].as_str().unwrap().contains("audio"));
    }

    #[test]
    fn capabilities_are_read_from_initialize() {
        let c = caps_of(&json!({"protocolVersion": 1, "agentCapabilities": {"loadSession": true,
            "promptCapabilities": {"image": true}, "sessionCapabilities": {"systemPrompt": {"mode": {}}}}}));
        assert!(c.load && c.images && c.system_prompt);
        let none = caps_of(&json!({"agentCapabilities": {}}));
        assert!(!none.load && !none.images && !none.system_prompt);
    }

    #[test]
    fn idle_and_names() {
        assert_eq!(parse_idle("2h").unwrap(), 7200);
        assert_eq!(parse_idle("90m").unwrap(), 5400);
        assert_eq!(parse_idle("0").unwrap(), 0);
        assert!(parse_idle("soon").is_err());
        assert!(name_ok("scout") && name_ok("bot-2"));
        assert!(!name_ok("../x") && !name_ok(""));
    }
}