garage44.eu/jeroen/midas

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

.. /src/tap.rs

raw

//! `midas acp --mirror`: an Agent Client Protocol agent that sits between an
//! editor (Zed) and another ACP agent — midas's own Claude Code adapter unless
//! `--agent` names one — passes everything through unchanged, and mirrors each
//! session to the hub as a session the page shows: what was said and done, and
//! where it waits. The page steers it as it does one a runner runs: a message
//! is a prompt (queued while a turn runs), and a permission answer, a cancel or
//! a mode goes to the agent, whichever of the page and the editor acts first.
//!
//! The agent runs here, in the editor's checkout, with this machine's Claude
//! login; the hub holds a copy of the conversation, never the conversation
//! itself, so a mirrored session cannot be reopened on the page (sessions.rs,
//! `reopen`). Each is attached at its first prompt — an editor opens sessions
//! nobody uses — and found again by its agent's id when the editor loads it.
//!
//! **Handed over** (the page's Continue on midas): once no turn runs, the
//! agent's session is closed here (`session/close`, its transcript whole), and
//! the reporter carries it over (`carry`): the checkout's work to its branch
//! (handoff.rs, the checkout itself untouched), the transcript to the hub, and
//! the hub told, which queues it for its runner. The editor's thread says
//! where it went, and its prompts are refused. **Handed back** from the page,
//! it comes back when the editor loads it again (`load_back`): the runner's
//! transcript in place before the load goes on, so its history replays, and
//! its work in the checkout if that has not changed since; the person and the
//! agent are told which.
//!
//! **Archived** in Zed's sidebar: archived at the hub too, and brought back
//! with it (zedthreads.rs, which reads Zed's own database: ACP does not say).
//!
//! **Deleted** in the editor (`session/delete`, once the agent has done it):
//! the session is archived at the hub, its list's entry and its board card,
//! and its mirror ends. One the editor deletes from its history, unopened
//! since, is found at the hub by its agent's id.
//!
//! The hub is never in the editor's way: reports and the page's messages go
//! through threads of their own, and a hub that cannot be reached costs the
//! page its copy, not the editor its session.
//!
//! What the page cannot do here: end the agent (End session stops the mirror,
//! the editor's session goes on), answer a question form (the editor takes
//! none), or show what the agent shows (`midas show` is for a runner's sessions).

use std::collections::{BTreeMap, BTreeSet, VecDeque};
use std::io::{BufRead, BufReader, Write};
use std::os::unix::process::CommandExt;
use std::process::{Child, ChildStdin, Command, Stdio};
use std::sync::mpsc::{self, Receiver, RecvTimeoutError, Sender};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};

use anyhow::{Context, Result};
use serde_json::{json, Value};

use crate::sessions::{self, Queued};

enum Ev {
    Client(Value),
    ClientGone,
    Agent(Value),
    AgentGone,
    /// Something the page said to a session, by the agent's session id.
    Input(String, Value),
    /// A handover done (the hub's id for the session) or failed (why), by the agent's session id.
    Handed(String, Result<String, String>),
    /// A `session/load` ready to go on to the agent, and what its time
    /// elsewhere means here (`load_back`).
    Loading(Value, Option<Return>),
}

/// What a session loaded here brings from its time at the hub (`load_back`).
struct Return {
    /// For the person, in the editor's thread.
    person: String,
    /// For the agent, with the next prompt.
    agent: Option<String>,
    /// Still at the hub, as this id: the editor's prompts are refused.
    away: Option<String>,
}

/// For the reporter: a session's news, and how to attach it if the hub does
/// not have it yet (`None` until its first prompt gives it a title).
struct Report {
    sid: String,
    attach: Option<Value>,
    items: Vec<Value>,
    status: Option<&'static str>,
    queue: Option<Value>,
    /// The mirror stops: the hub hears this, then nothing more.
    detach: bool,
    /// Hand the session over to the hub's runner (its checkout), after its last news.
    handoff: Option<String>,
    /// Deleted in the editor: archived at the hub, after its last news.
    archive: bool,
}

/// What waits to reach the hub for one session: log items, its status, its queue.
type Held = (Vec<Value>, Option<&'static str>, Option<Value>);

/// The sessions the hub has: hub id → (agent session id, inbox lines heard).
type Polled = Arc<Mutex<BTreeMap<String, (String, u64)>>>;

/// One session as the mirror follows it.
struct Tap {
    /// Where it runs, for the hub: the checkout, its branch, its owner, and its
    /// repository (`owner/name`, its origin's), the project a runner goes on in.
    cwd: String,
    branch: Option<String>,
    owner: String,
    repo: Option<String>,
    attach: Option<Value>,
    detached: bool,
    /// Prompts unanswered, by rpc id (as text): the editor's and the page's.
    turns: BTreeSet<String>,
    /// Permission requests unanswered, by rpc id (as text) → (options, tool call id).
    pending: BTreeMap<String, (Value, Value)>,
    /// The page's messages waiting for the turn to end.
    queue: VecDeque<Queued>,
    queue_dirty: bool,
    text: String,
    out: Vec<Value>,
    status: Option<&'static str>,
    mode: Option<String>,
    last_report: Instant,
    /// The page asked for it to go on at the hub, by whom: done once no turn runs.
    handing: Option<String>,
    /// Archived on the page, by whom: ended here once no turn runs.
    ending: Option<String>,
    /// For the agent with the next prompt: where its conversation has been.
    note: Option<String>,
    /// Deleted in the editor: archived at the hub with its last news.
    archive: bool,
    /// Something runs for it between turns (`acp::BACKGROUND`).
    busy: bool,
}

impl Tap {
    fn item(&mut self, v: Value) {
        self.flush_text();
        self.out.push(v);
    }

    fn flush_text(&mut self) {
        if !self.text.is_empty() {
            let t = std::mem::take(&mut self.text);
            self.out.push(json!({"kind": "agent", "text": t}));
        }
    }

    fn mode_is(&mut self, mode: &str) {
        if self.mode.as_deref() != Some(mode) {
            self.mode = Some(mode.to_string());
            self.item(json!({"kind": "mode", "current": mode}));
        }
    }

    /// Asking or not, after an answer: what the session is doing now.
    fn settle(&mut self) {
        self.status = Some(sessions::settled(!self.pending.is_empty(), !self.turns.is_empty() || self.busy));
    }
}

struct Mirror {
    out: std::io::Stdout,
    agent: Child,
    to_agent: ChildStdin,
    reports: Sender<Report>,
    taps: BTreeMap<String, Tap>,
    /// `session/new` and `session/load` asked, by rpc id (as text) → (cwd, the id loaded).
    opening: BTreeMap<String, (String, Option<String>)>,
    /// Our own requests to the agent, by id → what they were.
    ours: BTreeMap<String, (String, Value)>,
    next_ours: u64,
    /// Permission requests the page answered: the editor's late answer is dropped.
    answered: BTreeSet<String>,
    /// The editor as it names itself (`clientInfo`), and this machine.
    client: String,
    machine: String,
    user: String,
    /// Sessions handed over to the hub, by the agent's id → the hub's: the editor's prompts are refused.
    handed: BTreeMap<String, String>,
    /// Archived on the page and ended here, by the agent's id → by whom: its
    /// prompts refused until the editor opens it again.
    ended: BTreeMap<String, String>,
    /// What a loaded session is to be told, by the agent's id, until it opens.
    notes: BTreeMap<String, String>,
    /// For threads that work out what a load needs (`load_back`).
    tx: Sender<Ev>,
    /// Words for the person in the editor, once their session has opened.
    pending_says: Vec<(String, String)>,
    /// `session/set_model`s the editor asked, by rpc id → (session, model).
    models_asked: BTreeMap<String, (String, String)>,
    /// `session/delete`s the editor asked, by rpc id → session.
    deleting: BTreeMap<String, String>,
}

/// `midas acp --mirror`.
pub fn run(agent: Option<String>) -> Result<i32> {
    // SAFETY: ignoring SIGPIPE, so an agent or editor gone is a write error, not our end.
    unsafe { libc::signal(libc::SIGPIPE, libc::SIG_IGN) };
    let cmd = agent.unwrap_or_else(crate::acp::command);
    let mut c = Command::new("bash");
    c.arg("-c").arg(&cmd).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 agent = c.spawn().with_context(|| format!("starting the agent `{cmd}`"))?;
    let to_agent = agent.stdin.take().expect("piped");
    let from_agent = agent.stdout.take().expect("piped");
    let (tx, rx) = mpsc::channel();
    lines_into(std::io::stdin(), tx.clone(), Ev::Client, Ev::ClientGone);
    lines_into(from_agent, tx.clone(), Ev::Agent, Ev::AgentGone);

    // The machine as the workspace names it (`mini`), which its hostname need not be.
    let machine = crate::client::setting("MIDAS_MACHINE").or_else(|| Command::new("hostname").arg("-s").output().ok()
        .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string()).filter(|h| !h.is_empty())).unwrap_or_else(|| "?".into());
    let polled: Polled = Arc::default();
    let (rtx, rrx) = mpsc::channel();
    let mut m = Mirror {
        out: std::io::stdout(), agent, to_agent, reports: rtx, taps: BTreeMap::new(),
        opening: BTreeMap::new(), ours: BTreeMap::new(), next_ours: 0, answered: BTreeSet::new(),
        client: "an editor".into(), machine, user: std::env::var("USER").unwrap_or_else(|_| "?".into()),
        handed: BTreeMap::new(), ended: BTreeMap::new(), notes: BTreeMap::new(), tx: tx.clone(), pending_says: Vec::new(), models_asked: BTreeMap::new(),
        deleting: BTreeMap::new(),
    };
    let reporter = {
        let (polled, tx) = (polled.clone(), tx.clone());
        std::thread::spawn(move || report_loop(rrx, polled, tx))
    };
    {
        let (polled, tx, runner) = (polled, tx, m.runner());
        std::thread::spawn(move || poll_loop(polled, tx, runner));
    }
    // A thread archived in Zed is archived on the page too (zedthreads.rs).
    {
        let machine = m.machine.clone();
        std::thread::spawn(move || crate::zedthreads::follow(machine));
    }
    loop {
        match rx.recv_timeout(Duration::from_millis(300)) {
            Ok(Ev::Client(v)) => m.from_client(v),
            Ok(Ev::Agent(v)) => m.from_agent(v),
            Ok(Ev::Input(sid, i)) => m.from_page(&sid, &i),
            Ok(Ev::Handed(sid, r)) => m.handed_over(&sid, r),
            Ok(Ev::Loading(v, back)) => {
                if let Some(b) = back {
                    let sid = v["params"]["sessionId"].as_str().unwrap_or("").to_string();
                    if let Some(note) = b.agent {
                        m.notes.insert(sid.clone(), note);
                    }
                    match b.away {
                        Some(id) => m.handed.insert(sid.clone(), id),
                        None => m.handed.remove(&sid),
                    };
                    // After the load's answer, which the client waits for: queued behind it.
                    m.pending_says.push((sid, b.person));
                }
                m.send_agent(&v);
            }
            Ok(Ev::ClientGone) => {
                m.end_all(&format!("{} closed it", m.client));
                break;
            }
            Ok(Ev::AgentGone) | Err(RecvTimeoutError::Disconnected) => {
                m.end_all("its agent ended");
                break;
            }
            Err(RecvTimeoutError::Timeout) => {}
        }
        m.report(false);
    }
    m.report(true);
    let pg = m.agent.id() as i32;
    if pg > 1 {
        // SAFETY: kill(2) on the agent's own process group (pgid > 1, ours).
        unsafe { libc::kill(-pg, libc::SIGTERM) };
    }
    let _ = m.agent.wait();
    // The last word reaches the hub before this ends (or does not: the hub may be gone).
    drop(m);
    let _ = reporter.join();
    Ok(0)
}

/// Read JSON lines from `input` into the channel until it ends.
fn lines_into<R: std::io::Read + Send + 'static>(input: R, tx: Sender<Ev>, each: fn(Value) -> Ev, end: Ev) {
    std::thread::spawn(move || {
        for line in BufReader::new(input).lines().map_while(Result::ok) {
            if let Ok(v) = serde_json::from_str::<Value>(&line) {
                if tx.send(each(v)).is_err() {
                    return;
                }
            }
        }
        let _ = tx.send(end);
    });
}

/// What a prompt says, in words: its text, and what it mentions by name.
fn prompt_text(blocks: &Value) -> String {
    let parts: Vec<String> = blocks.as_array().into_iter().flatten().filter_map(|b| match b["type"].as_str() {
        Some("text") => b["text"].as_str().map(str::to_string),
        Some("resource_link") => b["name"].as_str().or(b["uri"].as_str()).map(|n| format!("@{n}")),
        Some("resource") => b["resource"]["uri"].as_str().map(|u| format!("@{}", u.rsplit('/').next().unwrap_or(u))),
        Some("image") => Some("[an image]".into()),
        _ => None,
    }).collect();
    parts.join(" ")
}

/// An rpc id as a map key: `7` and `"7"` stay apart.
fn key(id: &Value) -> String {
    id.to_string()
}

impl Mirror {
    /// The runner's name the hub records: the editor, at this machine.
    fn runner(&self) -> String {
        format!("{}@{}", self.client.to_lowercase().replace(' ', "-"), self.machine)
    }

    /// Who said what the editor sent, for the page.
    fn editor_by(&self) -> String {
        format!("{}:{}", self.client.to_lowercase().replace(' ', "-"), self.user)
    }

    fn send_client(&mut self, v: &Value) {
        let _ = writeln!(self.out, "{v}").and_then(|_| self.out.flush());
    }

    fn send_agent(&mut self, v: &Value) {
        // An agent gone is noticed at its output's end (AgentGone).
        let _ = writeln!(self.to_agent, "{v}").and_then(|_| self.to_agent.flush());
    }

    /// A request of our own to the agent; its answer stays here.
    fn ask_agent(&mut self, method: &str, params: Value, what: (String, Value)) {
        self.next_ours += 1;
        let id = format!("midas-mirror-{}", self.next_ours);
        self.ours.insert(key(&json!(id)), what);
        self.send_agent(&json!({"jsonrpc": "2.0", "id": id, "method": method, "params": params}));
    }

    fn from_client(&mut self, mut v: Value) {
        let id = v.get("id").filter(|i| !i.is_null()).cloned();
        let sid = v["params"]["sessionId"].as_str().unwrap_or("").to_string();
        // Handed over: it goes on at the hub, not here, until it is handed back.
        if let (Some("session/prompt"), Some(rpc), Some(hub)) = (v["method"].as_str(), &id, self.handed.get(&sid)) {
            let why = format!("this session was handed over to midas as {hub}; go on there ({}), or hand it back from there and open \
                this thread here again (as it does by itself when midas cannot take it over)", web_link(hub));
            self.send_client(&json!({"jsonrpc": "2.0", "id": rpc, "error": {"code": -32603, "message": why}}));
            return;
        }
        // Archived on the page, so ended here: until the editor opens it again.
        if let (Some("session/prompt"), Some(rpc), Some(by)) = (v["method"].as_str(), &id, self.ended.get(&sid)) {
            let why = format!("{by} archived this session on midas, so it ended here; archive this thread in {} too, or open it again to go on", self.client);
            self.send_client(&json!({"jsonrpc": "2.0", "id": rpc, "error": {"code": -32603, "message": why}}));
            return;
        }
        let p = &v["params"];
        match (v["method"].as_str(), &id) {
            (Some("initialize"), Some(_)) => {
                let info = &p["clientInfo"];
                if let Some(n) = info["title"].as_str().or(info["name"].as_str()).filter(|n| !n.is_empty() && n.len() <= 40) {
                    self.client = n.to_string();
                }
            }
            (Some(m @ ("session/new" | "session/load")), Some(id)) => {
                self.ended.remove(&sid);
                let cwd = p["cwd"].as_str().unwrap_or("").to_string();
                let loaded = (m == "session/load").then(|| sid.clone());
                self.opening.insert(key(id), (cwd.clone(), loaded));
                // A load waits while its conversation and work come back from the hub, if they are there.
                if m == "session/load" {
                    let tx = self.tx.clone();
                    std::thread::spawn(move || {
                        let said = load_back(&sid, &cwd);
                        let _ = tx.send(Ev::Loading(v, said));
                    });
                    return;
                }
            }
            (Some("session/prompt"), Some(id)) => {
                let by = self.editor_by();
                if let Some(t) = self.taps.get_mut(&sid) {
                    let text = prompt_text(&p["prompt"]);
                    t.item(json!({"kind": "user", "text": text, "by": by}));
                    t.turns.insert(key(id));
                    t.status = Some("working");
                    if t.attach.is_none() {
                        t.attach = Some(json!({"agent_session": sid, "title": text, "branch": t.branch, "owner": t.owner,
                                               "local": {"client": self.client, "machine": self.machine, "cwd": t.cwd, "repo": t.repo}}));
                    }
                }
            }
            // The model the editor chooses: in the log, for the page and for a runner that goes on with it.
            (Some("session/set_model"), Some(id)) => {
                if let Some(model) = p["modelId"].as_str() {
                    self.models_asked.insert(key(id), (sid.clone(), model.to_string()));
                }
            }
            (Some("session/delete"), Some(id)) => {
                self.deleting.insert(key(id), sid.clone());
            }
            (Some("session/cancel"), None) => {
                let who = self.client.clone();
                if let Some(t) = self.taps.get_mut(&sid) {
                    t.item(json!({"kind": "status", "text": format!("cancelled in {who}")}));
                }
            }
            (None, Some(id)) => {
                // The editor's answer to a request of the agent's.
                let k = key(id);
                if self.answered.remove(&k) {
                    return; // the page answered it first
                }
                let by = self.editor_by();
                if let Some(t) = self.taps.values_mut().find(|t| t.pending.contains_key(&k)) {
                    t.pending.remove(&k);
                    let outcome = &v["result"]["outcome"];
                    let option = if outcome["outcome"] == "selected" { outcome["optionId"].clone() } else { Value::Null };
                    t.item(json!({"kind": "permission_answered", "request": k, "option": option, "by": by}));
                    t.settle();
                }
            }
            _ => {}
        }
        // Where it has been, for the agent, with the first prompt since.
        if v["method"] == "session/prompt" {
            if let Some(note) = self.taps.get_mut(&sid).and_then(|t| t.note.take()) {
                if let Some(blocks) = v["params"]["prompt"].as_array_mut() {
                    blocks.insert(0, json!({"type": "text", "text": note}));
                }
            }
        }
        self.send_agent(&v);
    }

    fn from_agent(&mut self, v: Value) {
        let id = v.get("id").filter(|i| !i.is_null()).cloned();
        let method = v["method"].as_str();
        if let (None, Some(id)) = (method, &id) {
            let k = key(id);
            if let Some(what) = self.ours.remove(&k) {
                return self.answered_us(what, &v);
            }
            let failed = v.get("error").is_some_and(|e| !e.is_null());
            if let Some(sid) = self.deleting.remove(&k) {
                if !failed {
                    self.deleted(&sid);
                }
            } else if let Some((sid, model)) = self.models_asked.remove(&k) {
                if let (false, Some(t)) = (failed, self.taps.get_mut(&sid)) {
                    t.item(json!({"kind": "model", "current": model}));
                }
            } else if let Some((cwd, loaded)) = self.opening.remove(&k) {
                if !failed {
                    self.opened(&v["result"], cwd, loaded);
                }
            } else if let Some((sid, t)) = self.taps.iter_mut().find(|(_, t)| t.turns.contains(&k)) {
                let sid = sid.clone();
                t.turns.remove(&k);
                match v["error"]["message"].as_str() {
                    Some(why) if failed => t.item(json!({"kind": "error", "text": why})),
                    _ => t.item(json!({"kind": "turn_end", "reason": v["result"]["stopReason"]})),
                }
                t.settle();
                self.next_prompt(&sid);
            }
        } else {
            let p = &v["params"];
            let sid = p["sessionId"].as_str().unwrap_or("").to_string();
            if let Some(t) = self.taps.get_mut(&sid) {
                match method {
                    Some("session/update") => {
                        let u = &p["update"];
                        match u["sessionUpdate"].as_str() {
                            Some("agent_message_chunk") => {
                                if let Some(text) = u["content"]["text"].as_str() {
                                    t.text.push_str(text);
                                }
                            }
                            Some("current_mode_update") => {
                                if let Some(mode) = u["currentModeId"].as_str() {
                                    t.mode_is(mode);
                                }
                            }
                            _ => {
                                if let Some(it) = sessions::update_item(u) {
                                    t.item(it);
                                }
                            }
                        }
                    }
                    Some("session/request_permission") if id.is_some() => {
                        let rpc = key(id.as_ref().expect("checked"));
                        t.pending.insert(rpc.clone(), (p["options"].clone(), p["toolCall"]["toolCallId"].clone()));
                        t.item(sessions::permission_item(&rpc, p));
                        t.status = Some("needs_permission");
                    }
                    Some(crate::acp::BACKGROUND) => {
                        t.item(sessions::background_item(p));
                        t.busy = sessions::runs_in_background(p);
                        t.settle();
                    }
                    _ => {}
                }
            }
            // midas's own word to the page: the editor has no use for it.
            if method == Some(crate::acp::BACKGROUND) {
                return;
            }
        }
        self.send_client(&v);
        self.say_pending();
    }

    /// Words for the person whose session has opened since they were written.
    fn say_pending(&mut self) {
        let (now, later): (Vec<_>, Vec<_>) = std::mem::take(&mut self.pending_says).into_iter().partition(|(sid, _)| self.taps.contains_key(sid));
        self.pending_says = later;
        for (sid, text) in now {
            self.say(&sid, &text);
        }
    }

    /// A line in the editor's thread, as the agent's: midas speaking, between turns.
    fn say(&mut self, sid: &str, text: &str) {
        self.send_client(&json!({"jsonrpc": "2.0", "method": "session/update", "params": {"sessionId": sid,
            "update": {"sessionUpdate": "agent_message_chunk", "content": {"type": "text", "text": format!("\n\n— {text}\n")}}}}));
    }

    /// The page asked for the session to go on at the hub (handing) or
    /// archived it (ending), and no turn runs: its agent here is closed (its
    /// transcript whole). Handed over, the reporter then carries it over
    /// (`report_loop`).
    fn start_close(&mut self, sid: &str) {
        let Some(t) = self.taps.get_mut(sid).filter(|t| t.turns.is_empty() && (t.handing.is_some() || t.ending.is_some())) else { return };
        let (text, what) = if t.handing.is_some() { ("handing over: closing it here", "close") } else { ("archived on the page: ending it here", "end") };
        t.item(json!({"kind": "status", "text": text}));
        self.ask_agent("session/close", json!({"sessionId": sid}), (sid.to_string(), json!({"do": what})));
    }

    /// The reporter has carried the session over, or could not.
    fn handed_over(&mut self, sid: &str, r: Result<String, String>) {
        match r {
            Ok(id) => {
                self.say(sid, &format!("Handed over to midas as {id}: it goes on there, {}. Its work is on branch session/{id}; \
                    this checkout is as it was. To go on here instead, hand it back from that page and open this thread again.", web_link(&id)));
                self.handed.insert(sid.to_string(), id);
            }
            Err(why) => self.say(sid, &format!("Handing it over to midas failed: {why}. It is closed here; open this thread again to go on.")),
        }
    }

    /// A session opened: followed from now, attached at its first prompt.
    fn opened(&mut self, result: &Value, cwd: String, loaded: Option<String>) {
        let Some(sid) = loaded.or_else(|| result["sessionId"].as_str().map(str::to_string)) else { return };
        let dir = std::path::Path::new(&cwd);
        let top = Command::new("git").arg("-C").arg(dir).args(["rev-parse", "--show-toplevel"]).output().ok()
            .filter(|o| o.status.success()).map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string());
        // The owner midas gives work in this checkout: its directory's name, as `cli::owner` has it.
        let owner = top.as_deref().unwrap_or(&cwd).rsplit('/').next().unwrap_or("?").to_string();
        let repo = crate::cli::repo_in(dir);
        let mut t = Tap {
            branch: crate::cli::branch_in(dir), owner, cwd, repo, attach: None, detached: false, turns: BTreeSet::new(), pending: BTreeMap::new(),
            queue: VecDeque::new(), queue_dirty: false, text: String::new(), out: Vec::new(), status: Some("waiting"), mode: None,
            last_report: Instant::now(), handing: None, ending: None, note: None, archive: false, busy: false,
        };
        t.note = self.notes.remove(&sid);
        // The models and modes it offers, for the page's choices, as a runner reports them.
        let models = &result["models"];
        if let Some(current) = models["currentModelId"].as_str() {
            let offered: Vec<Value> = models["availableModels"].as_array().into_iter().flatten()
                .map(|x| json!({"id": x["modelId"], "name": x["name"], "description": x["description"]})).collect();
            t.item(json!({"kind": "models", "available": offered}));
            t.item(json!({"kind": "model", "current": current}));
        }
        let modes = &result["modes"];
        if let Some(current) = modes["currentModeId"].as_str() {
            t.item(json!({"kind": "modes", "available": modes["availableModes"]}));
            t.mode_is(current);
        }
        self.taps.insert(sid, t);
    }

    /// The agent answered one of the page's requests.
    fn answered_us(&mut self, (sid, what): (String, Value), v: &Value) {
        let Some(t) = self.taps.get_mut(&sid) else { return };
        let why = v["error"]["message"].as_str().map(str::to_string);
        match what["do"].as_str() {
            Some("prompt") => {
                t.turns.remove(what["rpc"].as_str().unwrap_or(""));
                match why {
                    Some(w) => t.item(json!({"kind": "error", "text": w})),
                    None => t.item(json!({"kind": "turn_end", "reason": v["result"]["stopReason"]})),
                }
                t.settle();
                self.next_prompt(&sid);
            }
            Some("close") => match why {
                Some(w) => {
                    t.item(json!({"kind": "error", "text": format!("could not close it here to hand it over: {w}")}));
                    t.handing = None;
                    t.settle();
                }
                // Closed: its last news, then the work and the conversation go (`report`).
                None => t.detached = true,
            },
            Some("end") => match why {
                Some(w) => {
                    t.item(json!({"kind": "error", "text": format!("archived, but could not end it here: {w}")}));
                    t.ending = None;
                    t.settle();
                }
                None => {
                    let by = t.ending.clone().unwrap_or_default();
                    t.item(json!({"kind": "status", "text": format!("ended in {} on {}", self.client, self.machine)}));
                    t.status = Some("stopped");
                    t.detached = true;
                    let client = self.client.clone();
                    self.say(&sid, &format!("{by} archived this session on midas, so it has ended here. Archive this thread in {client} too; \
                        to go on with it instead, open it again."));
                    self.ended.insert(sid.clone(), by);
                }
            },
            Some("mode") => {
                if let Some(w) = why {
                    t.item(json!({"kind": "error", "text": format!("mode {}: {w}", what["mode"].as_str().unwrap_or("?"))}));
                }
            }
            Some("model") => match why {
                Some(w) => t.item(json!({"kind": "error", "text": format!("model {}: {w}", what["model"].as_str().unwrap_or("?"))})),
                None => t.item(json!({"kind": "model", "current": what["model"]})),
            },
            _ => {}
        }
    }

    /// The next of the page's messages, when no turn runs: in the editor's
    /// thread too, as the person's words, and then to the agent.
    fn next_prompt(&mut self, sid: &str) {
        let Some(t) = self.taps.get_mut(sid) else { return };
        if !t.turns.is_empty() {
            return;
        }
        // Being handed over or ended: closed now, not given the next message.
        if t.handing.is_some() || t.ending.is_some() {
            return self.start_close(sid);
        }
        let Some(q) = t.queue.pop_front() else { return };
        t.queue_dirty = true;
        let shown: Vec<Value> = q.images.iter().map(|i| json!({"file": i["file"], "mime": i["mime"]})).collect();
        let mut item = json!({"kind": "user", "text": q.text, "by": q.by, "images": shown});
        if q.note.is_object() {
            item["note"] = q.note.clone();
        }
        t.item(item);
        t.status = Some("working");
        let mut blocks: Vec<Value> = Vec::new();
        if !q.text.is_empty() {
            blocks.push(json!({"type": "text", "text": q.text}));
        }
        blocks.extend(q.images.iter().map(|i| json!({"type": "image", "data": i["data"], "mimeType": i["mime"]})));
        let who = sessions_speaker(&q.by);
        self.send_client(&json!({"jsonrpc": "2.0", "method": "session/update", "params": {"sessionId": sid,
            "update": {"sessionUpdate": "user_message_chunk", "content": {"type": "text", "text": format!("{} (from midas): {}", who, q.text)}}}}));
        self.next_ours += 1;
        let rpc = format!("midas-mirror-{}", self.next_ours);
        self.ours.insert(key(&json!(rpc)), (sid.to_string(), json!({"do": "prompt", "rpc": key(&json!(rpc))})));
        if let Some(t) = self.taps.get_mut(sid) {
            t.turns.insert(key(&json!(rpc)));
        }
        self.send_agent(&json!({"jsonrpc": "2.0", "id": rpc, "method": "session/prompt", "params": {"sessionId": sid, "prompt": blocks}}));
    }

    /// What the page said to a session.
    fn from_page(&mut self, sid: &str, i: &Value) {
        let by = i["by"].as_str().unwrap_or("?").to_string();
        let client = self.client.clone();
        let Some(t) = self.taps.get_mut(sid).filter(|t| !t.detached) else { return };
        match i["kind"].as_str() {
            Some("message") => {
                let q = Queued::from_inbox(i);
                let busy = !t.turns.is_empty();
                if busy && i["now"] == true {
                    t.queue.push_front(q);
                    self.cancel(sid, &by);
                } else {
                    t.queue.push_back(q);
                }
                if let Some(t) = self.taps.get_mut(sid) {
                    t.queue_dirty = true;
                }
                self.next_prompt(sid);
            }
            Some("queue") => {
                if let Some(now) = sessions::queue_op(&mut t.queue, i) {
                    t.queue_dirty = true;
                    if now && !t.turns.is_empty() {
                        self.cancel(sid, &by);
                    }
                    self.next_prompt(sid);
                }
            }
            Some("permit") => {
                let rpc = i["request"].as_str().unwrap_or("").to_string();
                if let Some((options, tool)) = t.pending.remove(&rpc) {
                    let outcome = sessions::permission_outcome(&options, i["option"].as_str());
                    t.item(json!({"kind": "permission_answered", "request": rpc, "option": i["option"], "by": by}));
                    t.settle();
                    self.answered.insert(rpc.clone());
                    let id: Value = serde_json::from_str(&rpc).unwrap_or(Value::Null);
                    self.send_agent(&json!({"jsonrpc": "2.0", "id": id, "result": outcome}));
                    // The editor's own question is answered: its tool call goes on.
                    let status = if outcome["outcome"]["outcome"] == "selected" && i["option"].as_str().is_some_and(|o| !o.starts_with("reject")) { "in_progress" } else { "failed" };
                    self.send_client(&json!({"jsonrpc": "2.0", "method": "session/update", "params": {"sessionId": sid,
                        "update": {"sessionUpdate": "tool_call_update", "toolCallId": tool, "status": status}}}));
                }
            }
            Some("mode") => {
                if let Some(mode) = i["mode"].as_str() {
                    self.ask_agent("session/set_mode", json!({"sessionId": sid, "modeId": mode}), (sid.to_string(), json!({"do": "mode", "mode": mode})));
                }
            }
            Some("model") => {
                if let Some(model) = i["model"].as_str() {
                    self.ask_agent("session/set_model", json!({"sessionId": sid, "modelId": model}), (sid.to_string(), json!({"do": "model", "model": model})));
                }
            }
            Some("cancel") => self.cancel(sid, &by),
            Some("handoff") => {
                if t.handing.is_none() {
                    t.handing = Some(by.clone());
                    if !t.turns.is_empty() {
                        self.cancel(sid, &by);
                    }
                    self.start_close(sid);
                }
            }
            // Archived on the page by a person: done, so ended here too, once no turn runs.
            Some("done") => {
                if t.handing.is_none() && t.ending.is_none() {
                    // As the person reads it: their name, not the caller's.
                    t.ending = Some(sessions_speaker(&i["by"]));
                    if !t.turns.is_empty() {
                        self.cancel(sid, &by);
                    }
                    self.start_close(sid);
                }
            }
            Some("stop") => {
                t.item(json!({"kind": "status", "text": format!("{by} stopped mirroring it; it goes on in {client} on {}", self.machine)}));
                t.status = Some("stopped");
                t.detached = true;
            }
            _ => {}
        }
    }

    /// Stop the turn, for the page: the agent is told, and the editor's prompt ends `cancelled`.
    fn cancel(&mut self, sid: &str, by: &str) {
        if let Some(t) = self.taps.get_mut(sid) {
            t.item(json!({"kind": "status", "text": format!("cancelled by {by}")}));
        }
        self.send_agent(&json!({"jsonrpc": "2.0", "method": "session/cancel", "params": {"sessionId": sid}}));
    }

    /// The editor or the agent went: every session the hub has ends there.
    /// The editor deleted a session: archived at the hub, and no longer mirrored.
    fn deleted(&mut self, sid: &str) {
        let who = self.client.clone();
        match self.taps.get_mut(sid) {
            Some(t) => {
                t.item(json!({"kind": "status", "text": format!("deleted in {who}")}));
                t.status = Some("stopped");
                t.detached = true;
                t.archive = true;
            }
            None => {
                let _ = self.reports.send(Report { sid: sid.to_string(), attach: None, items: Vec::new(), status: None, queue: None,
                                                   detach: true, handoff: None, archive: true });
            }
        }
    }

    fn end_all(&mut self, why: &str) {
        for t in self.taps.values_mut().filter(|t| !t.detached) {
            t.item(json!({"kind": "status", "text": why}));
            t.status = Some("stopped");
            t.detached = true;
        }
    }

    /// Hand the reporter what each session has to say: at once, but text only
    /// a few times a second. `all` says everything, now.
    fn report(&mut self, all: bool) {
        for (sid, t) in self.taps.iter_mut() {
            let text_due = !t.text.is_empty() && (all || t.last_report.elapsed() >= Duration::from_millis(400));
            if t.out.is_empty() && t.status.is_none() && !t.queue_dirty && !text_due && !t.detached {
                continue;
            }
            t.flush_text();
            t.last_report = Instant::now();
            let queue = std::mem::take(&mut t.queue_dirty).then(|| Queued::shown(&t.queue));
            // Closed for a handover: the work and the conversation go with its last news.
            let handoff = (t.detached && t.handing.is_some()).then(|| t.cwd.clone());
            let _ = self.reports.send(Report { sid: sid.clone(), attach: t.attach.clone(), items: std::mem::take(&mut t.out),
                                               status: t.status.take(), queue, detach: t.detached, handoff, archive: t.archive });
        }
        // A session the page stopped mirroring has said its last.
        self.taps.retain(|_, t| !t.detached || !t.out.is_empty());
    }
}

/// A speaker's name as the page gives it (`web:ana` → ana).
fn sessions_speaker(by: &Value) -> String {
    let by = by.as_str().unwrap_or("someone");
    by.rsplit(':').next().unwrap_or(by).to_string()
}

/// The reporter: attaches each session at the hub once it can, and pushes what
/// it says, in order. What the hub could not take waits for the next try.
fn report_loop(rx: Receiver<Report>, polled: Polled, tx: Sender<Ev>) {
    let mut ids: BTreeMap<String, String> = BTreeMap::new();
    let mut held: BTreeMap<String, Held> = BTreeMap::new();
    let mut runner = String::new();
    for r in rx {
        let h = held.entry(r.sid.clone()).or_default();
        h.0.extend(r.items);
        h.1 = r.status.or(h.1);
        h.2 = r.queue.or(h.2.take());
        // A session nobody prompted is not worth the hub's while; a hub away for long is not worth all of it.
        if h.0.len() > 5000 {
            h.0.drain(..h.0.len() - 5000);
        }
        if !ids.contains_key(&r.sid) {
            let Some(a) = r.attach else {
                // Deleted unattached here: the hub may have it from an earlier time.
                if r.archive {
                    archive(None, &r.sid);
                    held.remove(&r.sid);
                }
                continue;
            };
            runner = format!("{}@{}", a["local"]["client"].as_str().unwrap_or("editor").to_lowercase().replace(' ', "-"),
                             a["local"]["machine"].as_str().unwrap_or("?"));
            let mut body = a.clone();
            body["runner"] = json!(runner);
            match crate::client::post("/v1/hosted/attach", &body) {
                Ok(v) => {
                    let Some(id) = v["id"].as_str().map(str::to_string) else { continue };
                    eprintln!("midas: mirroring {} as {id} on the hub", r.sid);
                    polled.lock().unwrap_or_else(|p| p.into_inner()).insert(id.clone(), (r.sid.clone(), v["inbox_after"].as_u64().unwrap_or(0)));
                    ids.insert(r.sid.clone(), id);
                }
                Err(e) => {
                    eprintln!("midas: attaching {} to the hub: {e:#}", r.sid);
                    continue;
                }
            }
        }
        let id = ids[&r.sid].clone();
        let h = held.get_mut(&r.sid).expect("entered");
        let body = json!({"items": h.0, "status": h.1, "runner": runner, "queue": h.2});
        match crate::client::post(&format!("/v1/hosted/{id}/push"), &body) {
            Ok(_) => *h = Default::default(),
            Err(e) => eprintln!("midas: reporting {id} to the hub: {e:#}"),
        }
        if let Some(cwd) = &r.handoff {
            let done = carry(&id, &r.sid, cwd, &runner).map(|()| id.clone()).map_err(|e| format!("{e:#}"));
            if let Err(why) = &done {
                // Closed here and not there: it has ended, and says why.
                let _ = crate::client::post(&format!("/v1/hosted/{id}/push"), &json!({"runner": runner, "status": "stopped",
                    "items": [{"kind": "error", "text": format!("could not hand it over: {why}; it is closed in the editor, which can open it again")}]}));
            }
            let _ = tx.send(Ev::Handed(r.sid.clone(), done));
        }
        if r.archive {
            archive(Some(id.clone()), &r.sid);
        }
        if r.detach {
            polled.lock().unwrap_or_else(|p| p.into_inner()).remove(&id);
            ids.remove(&r.sid);
            held.remove(&r.sid);
        }
    }
}

/// Archive at the hub a session the editor deleted: its list's entry and its
/// board card. Found by the agent's id when this mirror has not attached it.
fn archive(id: Option<String>, sid: &str) {
    let id = id.or_else(|| crate::client::get("/v1/hosted").ok()?.as_array()?.iter()
        .find(|m| m["agent_session"] == sid)?["id"].as_str().map(str::to_string));
    let Some(id) = id else { return };
    match crate::client::post(&format!("/v1/hosted/{id}/archive"), &json!({"on": true})) {
        Ok(_) => eprintln!("midas: {sid} deleted in the editor, {id} archived on the hub"),
        Err(e) => eprintln!("midas: archiving {id} on the hub: {e:#}"),
    }
}

/// Carry a closed session over to the hub: the checkout's work to its
/// branch, the agent's transcript to the hub, and the hub told (sessions.rs,
/// `handed`), which queues it for its runner.
fn carry(id: &str, sid: &str, cwd: &str, runner: &str) -> Result<()> {
    let dir = std::path::Path::new(cwd);
    let snap = crate::handoff::snapshot(dir, &format!("session/{id}"),
        &format!("wip: {id}, handed over to midas from {runner}\n\nWhat the checkout had not committed when the session went on at the hub."))?;
    let path = crate::acp::transcript(cwd, sid);
    let bytes = std::fs::read(&path).with_context(|| format!("reading its transcript, {}", path.display()))?;
    crate::client::put_transcript(id, &bytes)?;
    crate::client::post(&format!("/v1/hosted/{id}/handed"), &json!({"sha": snap.sha, "uncommitted": snap.uncommitted}))?;
    Ok(())
}

/// Where the page shows session `id`.
fn web_link(id: &str) -> String {
    let base = crate::client::setting("MIDAS_WEB_URL").unwrap_or_else(crate::client::hub_url);
    format!("{}/sessions/{id}", base.trim_end_matches('/'))
}

/// Before a session is loaded here: if it went to the hub and was handed
/// back, its conversation (the transcript the runner left) and its work (its
/// branch, into the checkout if that is as it was) come back first. Says what
/// to tell the person and the agent about it, if anything. A session still
/// at the hub is loaded as it is here, and the person told where it is.
fn load_back(sid: &str, cwd: &str) -> Option<Return> {
    let all = crate::client::get("/v1/hosted").ok()?;
    let m = all.as_array()?.iter().find(|m| m["agent_session"] == sid)?.clone();
    let id = m["id"].as_str()?.to_string();
    if m["handed"].is_object() && !m["local"].is_object() {
        return Some(Return { person: format!("This session is on midas as {id} now ({}): what is said here does not reach it. \
            Hand it back from that page to go on here.", web_link(&id)), agent: None, away: Some(id) });
    }
    if m["back"]["pending"] != true {
        return None;
    }
    let branch = m["back"]["branch"].as_str().unwrap_or("").to_string();
    let r = (|| -> Result<crate::handoff::Back> {
        let bytes = crate::client::get_transcript(&id)?;
        let path = crate::acp::transcript(cwd, sid);
        if let Some(d) = path.parent() {
            std::fs::create_dir_all(d)?;
        }
        crate::store::write_atomic(&path, &bytes, crate::store::PRIVATE)?;
        Ok(crate::handoff::bring_back(std::path::Path::new(cwd), &branch, m["handed"]["sha"].as_str().unwrap_or(""))?.0)
    })();
    use crate::handoff::Back;
    let (person, agent) = match r {
        Ok(Back::Restored) => ("its work is in this checkout again, uncommitted, as it was when it left",
                               "That work is in this checkout now, as uncommitted changes."),
        Ok(Back::Already) => ("this checkout has its work already", "This checkout has that work already."),
        Ok(Back::Diverged) => ("this checkout changed since it left, so its work was not brought in: it is on that branch",
                               "That work is NOT in this checkout, which changed meanwhile: it is on origin/{branch}. Bring it over, or ask the person, before going on."),
        Err(e) => return Some(Return { person: format!("Coming back from midas ({id}) failed: {e:#}. This is the conversation as it left here."),
                                     agent: None, away: None }),
    };
    Some(Return {
        person: format!("Back from midas ({id}): the conversation went on there, on branch {branch}, and {person}."),
        agent: Some(format!("[midas: this conversation went on at the midas hub's runner, in a worktree of branch {branch}, and has come back \
                             to this checkout ({cwd}). {}]", agent.replace("{branch}", &branch))),
        away: None,
    })
}

/// The page's words for the attached sessions, as a runner hears them: a long
/// poll that starts nothing (`take` false).
fn poll_loop(polled: Polled, tx: Sender<Ev>, runner: String) {
    loop {
        let have: serde_json::Map<String, Value> = polled.lock().unwrap_or_else(|p| p.into_inner())
            .iter().map(|(id, (_, n))| (id.clone(), json!(n))).collect();
        if have.is_empty() {
            std::thread::sleep(Duration::from_secs(1));
            continue;
        }
        let v = match crate::client::post("/v1/hosted/runner/poll", &json!({"runner": runner, "have": have, "take": false})) {
            Ok(v) => v,
            Err(_) => {
                std::thread::sleep(Duration::from_secs(5));
                continue;
            }
        };
        for (id, items) in v["inputs"].as_object().into_iter().flatten() {
            let mut p = polled.lock().unwrap_or_else(|p| p.into_inner());
            let Some((sid, n)) = p.get_mut(id) else { continue };
            for it in items.as_array().into_iter().flatten() {
                *n = (*n).max(it["n"].as_u64().unwrap_or(0));
                if tx.send(Ev::Input(sid.clone(), it.clone())).is_err() {
                    return;
                }
            }
        }
    }
}

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

    #[test]
    fn a_prompt_reads_as_its_words_and_what_it_mentions() {
        let p = json!([{"type": "text", "text": "look at"}, {"type": "resource_link", "name": "lib.rs", "uri": "file:///x/lib.rs"},
                       {"type": "resource", "resource": {"uri": "file:///x/main.rs", "text": "fn main() {}"}}, {"type": "image", "data": "…"}]);
        assert_eq!(prompt_text(&p), "look at @lib.rs @main.rs [an image]");
    }

    #[test]
    fn rpc_ids_of_either_kind_stay_apart() {
        assert_ne!(key(&json!(7)), key(&json!("7")));
        assert_eq!(serde_json::from_str::<Value>(&key(&json!("midas-mirror-1"))).unwrap(), json!("midas-mirror-1"));
    }
}