garage44.eu/jeroen/midas

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

.. /src/acp.rs

raw

//! `midas acp`: Claude Code as an Agent Client Protocol agent (DESIGN.md,
//! decision 19), so midas's agents need nothing installed beside it.
//!
//! The sessions runner (sessions.rs) and the bot host (host.rs) speak ACP —
//! JSON-RPC on an agent's stdin and stdout. Claude Code does not, but its
//! `--print` mode speaks a stream of JSON lines of its own, the one its SDKs
//! drive: user messages in; assistant messages, tool results, partial text and
//! a `result` at the end of each turn out; and **control requests** both ways
//! (`initialize`, `interrupt`, `set_permission_mode` from us; `can_use_tool`
//! from it, when `--permission-prompt-tool stdio` routes its permission
//! questions here). This is the translation, one `claude` per ACP session:
//!
//! | ACP (from the client)            | Claude Code                                  |
//! |----------------------------------|----------------------------------------------|
//! | `session/new`, `session/load`    | `claude -p … --session-id` / `--resume`      |
//! | their `additionalDirectories`    | `--add-dir`, one per root beside the cwd     |
//! | `session/prompt`                 | a user message; answered at its `result`     |
//! | `session/cancel`                 | control request `interrupt`                  |
//! | `session/set_mode`               | control request `set_permission_mode`        |
//! | `session/set_model`              | control request `set_model`                  |
//! | `session/request_permission` (to)| control request `can_use_tool` (from)        |
//! | `session/update` (to)            | partial text, tool uses, tool results        |
//! | `session/close`                  | stdin closed: Claude Code ends, transcript whole |
//! | `session/list`                   | the transcripts in the cwd's projects directory |
//! | `session/delete`                 | closed, and its transcript set aside (`<id>.jsonl.deleted`) |
//!
//! A `session/load` replays the conversation from the transcript before it is
//! answered, as ACP asks (`replay`); a tool call carries the file it touches
//! and an edit its diff; the commands Claude Code lists go to the client as
//! `available_commands_update`.
//!
//! What it does not do: serve files or terminals (it asks for none — Claude
//! Code has its own), or offer an "always" that outlives the session: the only standing permission
//! it passes on is one Claude Code itself suggests for this session alone.
//! `AskUserQuestion` is on only for a client that takes forms
//! (`clientCapabilities.elicitation.form`): each question goes to it as an ACP
//! form elicitation (`elicitation/create`) — one field per question, single or
//! multiple choice, with an "Other" box beside it — and the answers go back to
//! Claude Code as the tool's `answers`, as the CLI's own dialog gives them. For
//! any other client it is off, and the agent asks in words.
//!
//! The session's `_meta.claudeCode.options` set Claude Code's own fence (the
//! bot's: no built-in tools, no settings files, only midas's MCP server), each
//! as its flag. An option this does not know is refused, not ignored: a fence
//! silently dropped is no fence.
//!
//! Claude Code runs in this process's group, so the runner's stop reaches it;
//! when the client goes, or the last session's `claude` does, this ends too —
//! a client that wants the session back starts it again and loads it.

use std::collections::{BTreeMap, VecDeque};
use std::io::{BufRead, BufReader, Read, Write};
use std::process::{Child, ChildStdin, Command, Stdio};
use std::sync::mpsc::{self, Sender};

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

const ACP_VERSION: u64 = 1;

/// The notification that says what runs for a session between turns (`Adapter::background`).
pub const BACKGROUND: &str = "_midas/background";

/// The modes a session offers, as Zed offers Claude Code's: a session starts in
/// `default` whatever its user's settings say, and only the client moves it.
/// `bypassPermissions` exists only where the session was opened allowing it
/// (`claudeCode.options.allowBypass`, on unless set false; the bot's fence sets it false).
const MODES: &[(&str, &str, &str)] = &[
    ("default", "Manual", "Asks before every edit and command"),
    ("acceptEdits", "Accept edits", "Makes file edits without asking; asks for the rest"),
    ("plan", "Plan", "Reads and plans; changes nothing"),
    ("auto", "Auto", "Claude Code's own check decides what needs asking"),
    ("bypassPermissions", "Trusted", "Does everything without asking"),
];

/// The models a session offers: Claude Code's aliases, which it resolves to the
/// current model of each kind, so the list does not go stale. `default` is
/// Claude Code's own choice for the account; a session starts there unless
/// the client asks for another (`claudeCode.options.model`).
const MODELS: &[(&str, &str, &str)] = &[
    ("default", "Default", "Claude Code's own choice for this account"),
    ("fable", "Fable", "The most capable, for the hardest work"),
    ("opus", "Opus", "Very capable; slower and dearer than Sonnet"),
    (FAST, "Opus ⚡ fast", "Opus answering faster, at a higher price; needs extra usage on the account"),
    ("sonnet", "Sonnet", "Fast and capable: the everyday one"),
    ("haiku", "Haiku", "The fastest, for small jobs"),
];

/// Opus in Claude Code's fast mode: no model of its own but a setting
/// (`fastMode`), offered as one so it is chosen where the model is.
const FAST: &str = "opus-fast";

/// The `--settings` a fast session's Claude Code is started with.
const FAST_SETTINGS: &str = r#"{"fastMode":true}"#;

/// What arrives, from the client or from one session's Claude Code.
enum Ev {
    Client(Value),
    ClientGone,
    Claude(String, Value),
    ClaudeGone(String),
}

/// One ACP session: its Claude Code, and what is waiting on it.
struct Session {
    child: Child,
    stdin: ChildStdin,
    /// The `session/new` or `session/load` to answer when Claude Code has
    /// answered our `initialize`.
    opening: Option<Value>,
    /// The `session/prompt`s sent, oldest first: each is answered by a `result`.
    prompts: VecDeque<Value>,
    /// `session/set_mode`s sent on, by control request id: (rpc id, mode).
    modes: BTreeMap<String, (Value, String)>,
    /// `session/set_model`s sent on, by control request id: (rpc id, model).
    models: BTreeMap<String, (Value, String)>,
    cancelling: bool,
    next_control: u64,
    /// What its Claude Code was started with, for the modes it offers.
    args: Vec<String>,
    /// The permission mode it is in, as last set or reported.
    mode: String,
    /// Tokens the context held at its last message.
    context: u64,
    /// Its working directory, where its transcript is kept (`transcript`).
    cwd: String,
    /// Opened by `session/load`: its history is replayed before the answer.
    loaded: bool,
    /// Tool calls shown as a diff (an edit, a write): their result keeps it.
    diffs: std::collections::HashSet<String>,
    /// Its background tasks, as Claude Code last listed them (`background`).
    tasks: Vec<Value>,
    /// A turn Claude Code started by itself, with no prompt: one a finished
    /// background task woke. It ends with the next `result`.
    unprompted: bool,
    /// In fast mode, as started or last chosen (`FAST`).
    fast: bool,
    /// Told the client fast mode is off although chosen, once per choosing.
    fast_told: bool,
}

impl Session {
    fn send(&mut self, v: &Value) {
        // A Claude Code gone is noticed at its output's end (ClaudeGone).
        let _ = writeln!(self.stdin, "{v}").and_then(|_| self.stdin.flush());
    }

    fn control(&mut self, request: Value) -> String {
        self.next_control += 1;
        let id = format!("midas-{}", self.next_control);
        self.send(&json!({"type": "control_request", "request_id": id, "request": request}));
        id
    }
}

/// A permission question from Claude Code, put to the client.
struct Ask {
    session: String,
    request_id: String,
    input: Value,
    /// What Claude Code suggests allowing for the rest of the session.
    for_session: Vec<Value>,
    /// AskUserQuestion's questions, when this is one put as a form.
    questions: Option<Vec<Value>>,
}

struct Adapter<W: Write> {
    out: W,
    tx: Sender<Ev>,
    claude: String,
    sessions: BTreeMap<String, Session>,
    asks: BTreeMap<u64, Ask>,
    next_id: u64,
    /// The client takes forms (`elicitation.form`): AskUserQuestion goes to it as one.
    forms: bool,
    /// Titles of transcripts listed, by path, for as long as the file is unchanged.
    titles: BTreeMap<std::path::PathBuf, (std::time::SystemTime, u64, Option<String>)>,
}

/// `midas acp` as a shell command, by this binary's own path: the agent the
/// sessions runner and a hosted bot start unless told another.
pub fn command() -> String {
    let exe = crate::util::exe().map(|p| p.to_string_lossy().to_string()).unwrap_or_else(|_| "midas".into());
    format!("{} acp", crate::bot::sh_quote(&exe))
}

/// A hosted bot's fence, when midas runs its agent and nobody gave another:
/// none of Claude Code's own tools, no settings files (no hooks, no rules, no
/// MCP servers of the user's), only the MCP server the host gives it — the
/// bot. The host's permission rule stands behind it (host.rs, `decide`).
pub fn bot_fence() -> Value {
    json!({"claudeCode": {"options": {"tools": [], "settingSources": [], "strictMcpConfig": true, "allowBypass": false}}})
}

/// `midas acp`: serve ACP on stdin and stdout until the client goes.
pub fn run() -> Result<i32> {
    // SAFETY: ignoring SIGPIPE, so a Claude Code gone is a write error, not our end.
    unsafe { libc::signal(libc::SIGPIPE, libc::SIG_IGN) };
    let claude = crate::client::setting("MIDAS_CLAUDE").unwrap_or_else(|| "claude".into());
    serve(std::io::stdin(), std::io::stdout(), claude);
    Ok(0)
}

/// The adapter over any pair of streams (the tests use pipes).
pub fn serve<R: Read + Send + 'static, W: Write>(input: R, out: W, claude: String) {
    let (tx, rx) = mpsc::channel();
    {
        let tx = tx.clone();
        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(Ev::Client(v)).is_err() {
                        return;
                    }
                }
            }
            let _ = tx.send(Ev::ClientGone);
        });
    }
    let mut a = Adapter { out, tx, claude, sessions: BTreeMap::new(), asks: BTreeMap::new(), next_id: 0, forms: false,
                         titles: BTreeMap::new() };
    while let Ok(ev) = rx.recv() {
        match ev {
            Ev::Client(v) => a.from_client(v),
            Ev::ClientGone => break,
            Ev::Claude(sid, v) => a.from_claude(&sid, v),
            Ev::ClaudeGone(sid) => {
                if a.gone(&sid) {
                    break;
                }
            }
        }
    }
    for (_, mut s) in std::mem::take(&mut a.sessions) {
        let _ = s.child.kill();
        let _ = s.child.wait();
    }
}

impl<W: Write> Adapter<W> {
    fn write(&mut self, v: &Value) {
        let _ = writeln!(self.out, "{v}").and_then(|_| self.out.flush());
    }

    fn answer(&mut self, id: &Value, result: Value) {
        self.write(&json!({"jsonrpc": "2.0", "id": id, "result": result}));
    }

    fn refuse(&mut self, id: &Value, code: i64, message: &str) {
        self.write(&json!({"jsonrpc": "2.0", "id": id, "error": {"code": code, "message": message}}));
    }

    fn update(&mut self, sid: &str, update: Value) {
        self.write(&json!({"jsonrpc": "2.0", "method": "session/update", "params": {"sessionId": sid, "update": update}}));
    }

    /// What runs for session `sid` outside a prompt's turn: its background
    /// tasks (a command, a subagent, a workflow) and a turn it started by
    /// itself. ACP has no update for it, so it is an extension notification
    /// (`_midas/background`), which a client that does not know it ignores.
    fn background(&mut self, sid: &str) {
        let Some(s) = self.sessions.get(sid) else { return };
        let params = json!({"sessionId": sid, "tasks": s.tasks, "turn": s.unprompted});
        self.write(&json!({"jsonrpc": "2.0", "method": BACKGROUND, "params": params}));
    }

    fn from_client(&mut self, v: Value) {
        let id = v.get("id").cloned();
        let params = &v["params"];
        match (v["method"].as_str(), id) {
            (Some(method), Some(id)) => {
                let done = match method {
                    "initialize" => {
                        self.forms = params["clientCapabilities"]["elicitation"]["form"].is_object();
                        self.answer(&id, initialize());
                        Ok(())
                    }
                    "authenticate" => {
                        self.answer(&id, json!({}));
                        Ok(())
                    }
                    "session/new" => self.open(&id, params, None),
                    "session/load" => match params["sessionId"].as_str() {
                        Some(s) if crate::registry::is_uuid(s) => self.open(&id, params, Some(s.to_string())),
                        _ => Err(anyhow!("session/load needs the sessionId Claude Code gave")),
                    },
                    "session/prompt" => self.prompt(&id, params),
                    "session/list" => {
                        let sessions = params["cwd"].as_str().map(|c| self.list(c)).unwrap_or_default();
                        self.answer(&id, json!({"sessions": sessions}));
                        Ok(())
                    }
                    "session/close" => self.close(&id, params),
                    "session/delete" => self.delete(&id, params),
                    "session/set_mode" => self.set_mode(&id, params),
                    "session/set_model" => self.set_model(&id, params),
                    _ => {
                        self.refuse(&id, -32601, &format!("midas's Claude Code adapter offers no {method}"));
                        Ok(())
                    }
                };
                if let Err(e) = done {
                    self.refuse(&id, -32602, &format!("{e:#}"));
                }
            }
            (Some("session/cancel"), None) => self.cancel(params["sessionId"].as_str().unwrap_or("")),
            (Some(_), None) => {}
            // The client's answer to one of our questions.
            (None, Some(id)) => {
                if let Some(ask) = id.as_u64().and_then(|n| self.asks.remove(&n)) {
                    self.answered(ask, &v);
                }
            }
            (None, None) => {}
        }
    }

    /// Start a session's Claude Code; the client hears when it has answered.
    fn open(&mut self, rpc: &Value, params: &Value, resume: Option<String>) -> Result<()> {
        let sid = match &resume { Some(s) => s.clone(), None => crate::registry::new_uuid()? };
        if self.sessions.contains_key(&sid) {
            bail!("session {sid} is open already");
        }
        let cwd = params["cwd"].as_str().filter(|c| !c.is_empty()).context("a session needs a cwd")?;
        let args = claude_args_with(params, &sid, resume.is_some(), self.forms)?;
        let mut cmd = Command::new(&self.claude);
        cmd.args(&args).current_dir(cwd).stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::inherit())
            // A runner started from inside a Claude Code session must still
            // start one: Claude Code refuses to run inside itself otherwise.
            .env_remove("CLAUDECODE").env_remove("CLAUDE_CODE_ENTRYPOINT");
        let mut child = cmd.spawn().with_context(|| format!("starting {}", self.claude))?;
        let stdin = child.stdin.take().expect("piped");
        let out = child.stdout.take().expect("piped");
        let tx = self.tx.clone();
        let s2 = sid.clone();
        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(Ev::Claude(s2.clone(), v)).is_err() {
                        return;
                    }
                }
            }
            let _ = tx.send(Ev::ClaudeGone(s2));
        });
        let mut s = Session {
            child, stdin, opening: Some(rpc.clone()), prompts: VecDeque::new(), modes: BTreeMap::new(), models: BTreeMap::new(),
            cancelling: false, next_control: 0, fast: started_fast(&args), fast_told: false, mode: modes(&args)["currentModeId"].as_str().unwrap_or("default").to_string(), args, context: 0, cwd: cwd.to_string(), loaded: resume.is_some(),
            diffs: Default::default(), tasks: Vec::new(), unprompted: false,
        };
        s.send(&json!({"type": "control_request", "request_id": "midas-open", "request": {"subtype": "initialize"}}));
        self.sessions.insert(sid, s);
        Ok(())
    }

    fn session(&mut self, params: &Value) -> Result<(String, &mut Session)> {
        let sid = params["sessionId"].as_str().unwrap_or("").to_string();
        match self.sessions.get_mut(&sid) {
            Some(s) if s.opening.is_none() => Ok((sid, s)),
            Some(_) => bail!("session {sid} is still opening"),
            None => bail!("no session {sid}"),
        }
    }

    fn prompt(&mut self, rpc: &Value, params: &Value) -> Result<()> {
        let content = user_content(params["prompt"].as_array().map(Vec::as_slice).unwrap_or(&[]));
        if content.is_empty() {
            bail!("an empty prompt");
        }
        let (_, s) = self.session(params)?;
        s.send(&json!({"type": "user", "message": {"role": "user", "content": content},
                       "parent_tool_use_id": null, "session_id": ""}));
        s.prompts.push_back(rpc.clone());
        Ok(())
    }

    fn set_mode(&mut self, rpc: &Value, params: &Value) -> Result<()> {
        let mode = params["modeId"].as_str().filter(|m| !m.is_empty()).context("session/set_mode needs a modeId")?.to_string();
        let (_, s) = self.session(params)?;
        let cid = s.control(json!({"subtype": "set_permission_mode", "mode": mode}));
        s.modes.insert(cid, (rpc.clone(), mode));
        Ok(())
    }

    fn set_model(&mut self, rpc: &Value, params: &Value) -> Result<()> {
        let model = params["modelId"].as_str().filter(|m| model_ok(m)).context("session/set_model needs a modelId")?.to_string();
        let (_, s) = self.session(params)?;
        // `default` is no model named: Claude Code's own choice again.
        let named = match model.as_str() {
            "default" => Value::Null,
            FAST => json!("opus"),
            m => json!(m),
        };
        // Fast mode is a setting beside the model: on with FAST, off with any other.
        let fast = model == FAST;
        if fast != s.fast {
            s.control(json!({"subtype": "apply_flag_settings", "settings": {"fastMode": fast}}));
            s.fast = fast;
            s.fast_told = false;
        }
        let cid = s.control(json!({"subtype": "set_model", "model": named}));
        s.models.insert(cid, (rpc.clone(), model));
        Ok(())
    }

    fn cancel(&mut self, sid: &str) {
        let asked: Vec<u64> = self.asks.iter().filter(|(_, a)| a.session == sid).map(|(n, _)| *n).collect();
        for n in asked {
            if let Some(ask) = self.asks.remove(&n) {
                self.tell_claude(&ask, deny("The turn was cancelled."));
            }
        }
        if let Some(s) = self.sessions.get_mut(sid) {
            if !s.prompts.is_empty() {
                s.cancelling = true;
                s.control(json!({"subtype": "interrupt"}));
            }
        }
    }

    /// End a session (`session/close`): what it was doing is cancelled, its
    /// Claude Code stopped, and its transcript left whole for a `session/load`
    /// here or elsewhere. The adapter goes on for the client's other sessions.
    fn close(&mut self, rpc: &Value, params: &Value) -> Result<()> {
        let sid = params["sessionId"].as_str().unwrap_or("").to_string();
        let s = self.sessions.remove(&sid).with_context(|| format!("no session {sid}"))?;
        self.end(&sid, s);
        self.answer(rpc, json!({}));
        Ok(())
    }

    /// Stop an open session's Claude Code, its transcript whole.
    fn end(&mut self, sid: &str, mut s: Session) {
        self.asks.retain(|_, a| a.session != sid);
        for p in s.prompts.drain(..) {
            self.answer(&p, json!({"stopReason": "cancelled"}));
        }
        for p in s.opening.take().into_iter().chain(s.modes.into_values().map(|(r, _)| r)).chain(s.models.into_values().map(|(r, _)| r)) {
            self.refuse(&p, -32603, "the session was closed");
        }
        // Its stdin closed, Claude Code ends by itself once it has written what it has.
        drop(s.stdin);
        let waited = std::time::Instant::now();
        while s.child.try_wait().ok().flatten().is_none() && waited.elapsed() < std::time::Duration::from_secs(5) {
            std::thread::sleep(std::time::Duration::from_millis(50));
        }
        let _ = s.child.kill();
        let _ = s.child.wait();
    }

    /// The client deletes a session (`session/delete`): closed if open, and
    /// its transcript set aside, so neither `session/list` nor Claude Code's
    /// `--resume` offers it again. Renamed, not removed: it can be had back by hand.
    fn delete(&mut self, rpc: &Value, params: &Value) -> Result<()> {
        let sid = params["sessionId"].as_str().filter(|s| crate::registry::is_uuid(s)).context("session/delete needs a session's id")?.to_string();
        if let Some(s) = self.sessions.remove(&sid) {
            self.end(&sid, s);
        }
        let name = format!("{sid}.jsonl");
        for dir in std::fs::read_dir(projects_dir()).into_iter().flatten().flatten() {
            let t = dir.path().join(&name);
            if t.is_file() {
                std::fs::rename(&t, t.with_extension("jsonl.deleted")).with_context(|| format!("setting {} aside", t.display()))?;
            }
        }
        self.answer(rpc, json!({}));
        Ok(())
    }

    /// The sessions had in `cwd`, newest first, from Claude Code's transcripts
    /// there (`session/list`): what a client offers to load again.
    fn list(&mut self, cwd: &str) -> Vec<Value> {
        let dir = project_dir(cwd);
        let mut found: Vec<(std::time::SystemTime, std::path::PathBuf, String)> = std::fs::read_dir(&dir).into_iter().flatten().flatten()
            .filter_map(|e| {
                let p = e.path();
                let sid = p.file_stem()?.to_str()?.to_string();
                let modified = e.metadata().ok()?.modified().ok()?;
                (p.extension().is_some_and(|x| x == "jsonl") && crate::registry::is_uuid(&sid)).then_some((modified, p, sid))
            })
            .collect();
        found.sort_by_key(|f| std::cmp::Reverse(f.0));
        found.truncate(LISTED);
        let mut out = Vec::new();
        for (modified, path, sid) in found {
            let size = std::fs::metadata(&path).map(|m| m.len()).unwrap_or(0);
            let title = match self.titles.get(&path) {
                Some((m, n, t)) if *m == modified && *n == size => t.clone(),
                _ => {
                    let t = crate::import::read(&path).ok().flatten().map(|c| c.title);
                    self.titles.insert(path.clone(), (modified, size, t.clone()));
                    t
                }
            };
            // A transcript nobody said anything in is no session to go back to.
            let Some(title) = title else { continue };
            let at = chrono::DateTime::<chrono::Utc>::from(modified).to_rfc3339_opts(chrono::SecondsFormat::Secs, true);
            out.push(json!({"sessionId": sid, "cwd": cwd, "title": title, "updatedAt": at}));
        }
        out
    }

    /// A loaded session's conversation, told again as it was told live, before
    /// the `session/load` is answered (as ACP asks): what was said, the
    /// agent's text, its tool calls and their outcomes, its plans.
    fn replay(&mut self, sid: &str, cwd: &str) {
        let Ok(Some(c)) = crate::import::read(&transcript(cwd, sid)) else { return };
        let mut diffs = std::collections::HashSet::new();
        for it in &c.items {
            let text = |t: &Value| json!({"type": "text", "text": t.as_str().unwrap_or("")});
            let update = match it["kind"].as_str() {
                Some("user") => json!({"sessionUpdate": "user_message_chunk", "content": text(&it["text"])}),
                Some("agent") => json!({"sessionUpdate": "agent_message_chunk", "content": text(&it["text"])}),
                Some("tool") => {
                    let name = it["title"].as_str().unwrap_or("tool").split(':').next().unwrap_or("tool");
                    let mut call = tool_call(it["id"].as_str().unwrap_or(""), name, &it["input"]);
                    call["title"] = it["title"].clone();
                    call["sessionUpdate"] = json!("tool_call");
                    call["status"] = json!("completed");
                    if call["content"].is_array() {
                        diffs.insert(it["id"].as_str().unwrap_or("").to_string());
                    }
                    call
                }
                Some("tool_update") => {
                    let mut done = json!({"sessionUpdate": "tool_call_update", "toolCallId": it["id"], "status": it["status"],
                        "content": it["output"].as_str().map(|o| json!([{"type": "content", "content": {"type": "text", "text": o}}]))});
                    if diffs.remove(it["id"].as_str().unwrap_or("")) {
                        keep_diff(&mut done);
                    }
                    done
                }
                Some("plan") => json!({"sessionUpdate": "plan", "entries": it["entries"]}),
                // Notes of what happened (an interruption) are not the conversation.
                _ => continue,
            };
            self.update(sid, update);
        }
    }

    fn tell_claude(&mut self, ask: &Ask, response: Value) {
        if let Some(s) = self.sessions.get_mut(&ask.session) {
            s.send(&json!({"type": "control_response",
                           "response": {"subtype": "success", "request_id": ask.request_id, "response": response}}));
        }
    }

    /// The client's answer to a permission question, passed on.
    fn answered(&mut self, ask: Ask, v: &Value) {
        if let Some(questions) = &ask.questions {
            let response = question_response(questions, &ask.input, &v["result"]);
            self.tell_claude(&ask, response);
            return;
        }
        let chosen = v["result"]["outcome"]["optionId"].as_str().filter(|_| v["result"]["outcome"]["outcome"] == "selected");
        let response = match chosen {
            Some("allow") => json!({"behavior": "allow", "updatedInput": ask.input}),
            Some("allow_session") => {
                let updated = self.for_session(&ask);
                json!({"behavior": "allow", "updatedInput": ask.input, "updatedPermissions": updated})
            }
            Some(_) => deny("The person refused this."),
            None => deny("No one allowed this."),
        };
        self.tell_claude(&ask, response);
    }

    /// What "and the like for this session" allows. Claude Code suggests a mode
    /// for some tools (Accept edits, for an edit): taken only from Manual, as it
    /// would otherwise undo a mode the person chose while the question waited
    /// (Trusted, set before answering, became Accept edits behind the page's
    /// back). A mode taken is reported, so the page shows the one in force.
    fn for_session(&mut self, ask: &Ask) -> Vec<Value> {
        let Some(s) = self.sessions.get_mut(&ask.session) else { return Vec::new() };
        let (updated, taken) = session_rules(&s.mode, &ask.for_session);
        if let Some(mode) = taken {
            s.mode = mode.clone();
            self.update(&ask.session, json!({"sessionUpdate": "current_mode_update", "currentModeId": mode}));
        }
        updated
    }

    fn from_claude(&mut self, sid: &str, v: Value) {
        let Some(s) = self.sessions.get_mut(sid) else { return };
        // Output with no prompt waiting is a turn Claude Code started by itself,
        // woken by a background task that ended; its `result` ends it.
        let output = matches!(v["type"].as_str(), Some("assistant" | "stream_event"));
        if output && s.prompts.is_empty() && s.opening.is_none() && !s.unprompted {
            s.unprompted = true;
            self.background(sid);
        }
        let Some(s) = self.sessions.get_mut(sid) else { return };
        // Every `result` ends it, also one a prompt waits for: a prompt sent
        // while it ran is taken into that turn, and its one result answers the
        // prompt. Left on, the session read as at work for hours after
        // (session-s497, 2026-10-29).
        if v["type"] == "result" && std::mem::take(&mut s.unprompted) {
            self.background(sid);
        }
        let Some(s) = self.sessions.get_mut(sid) else { return };
        // Fast mode chosen but not given (the account has no extra usage, say):
        // said once, or "Opus ⚡ fast" reads as fast while it runs at standard speed.
        if s.fast && !s.fast_told && v["fast_mode_state"] == "off" {
            s.fast_told = true;
            let why = v["fast_mode_disabled_reason"].as_str().unwrap_or("Claude Code did not say why").replace('_', " ");
            self.update(sid, json!({"sessionUpdate": "agent_message_chunk",
                                    "content": {"type": "text", "text": format!("_Fast mode is off: {why}. This runs at Opus's standard speed._\n\n")}}));
        }
        let Some(s) = self.sessions.get_mut(sid) else { return };
        if v["type"] == "result" && s.prompts.is_empty() {
            return;
        }
        match v["type"].as_str() {
            // The live background tasks, the whole set each time it changes.
            Some("system") if v["subtype"] == "background_tasks_changed" => {
                s.tasks = live_tasks(&v["tasks"]);
                self.background(sid);
            }
            Some("control_response") => {
                let r = &v["response"];
                let rid = r["request_id"].as_str().unwrap_or("");
                let failed = r["subtype"] == "error";
                let why = r["error"].as_str().unwrap_or("Claude Code refused").to_string();
                if rid == "midas-open" {
                    if let Some(rpc) = s.opening.take() {
                        let offered = modes(&s.args);
                        if failed {
                            self.refuse(&rpc, -32603, &why);
                        } else {
                            let models = models(&s.args);
                            let (loaded, cwd) = (s.loaded, s.cwd.clone());
                            if loaded {
                                self.replay(sid, &cwd);
                            }
                            self.answer(&rpc, json!({"sessionId": sid, "modes": offered, "models": models}));
                            // Its slash commands, as Claude Code lists them for this directory.
                            self.update(sid, json!({"sessionUpdate": "available_commands_update",
                                                    "availableCommands": commands(&r["response"]["commands"])}));
                        }
                    }
                } else if let Some((rpc, _)) = s.models.remove(rid) {
                    if failed {
                        self.refuse(&rpc, -32602, &why);
                    } else {
                        self.answer(&rpc, json!({}));
                    }
                } else if let Some((rpc, mode)) = s.modes.remove(rid) {
                    if failed {
                        self.refuse(&rpc, -32602, &why);
                    } else {
                        s.mode = mode.clone();
                        self.answer(&rpc, json!({}));
                        self.update(sid, json!({"sessionUpdate": "current_mode_update", "currentModeId": mode}));
                    }
                }
            }
            Some("control_request") => {
                let rid = v["request_id"].as_str().unwrap_or("").to_string();
                let r = &v["request"];
                if r["subtype"] != "can_use_tool" {
                    let what = r["subtype"].as_str().unwrap_or("?").to_string();
                    s.send(&json!({"type": "control_response", "response": {"subtype": "error", "request_id": rid,
                                   "error": format!("midas offers no {what}")}}));
                    return;
                }
                let name = r["tool_name"].as_str().unwrap_or("?").to_string();
                let tool_id = r["tool_use_id"].as_str().unwrap_or(&rid).to_string();
                // A question for the person: a form, for a client that takes one.
                if name == "AskUserQuestion" && self.forms {
                    let Some(questions) = valid_questions(&r["input"]) else {
                        s.send(&json!({"type": "control_response", "response": {"subtype": "success", "request_id": rid,
                                       "response": deny("AskUserQuestion was called with no valid questions.")}}));
                        return;
                    };
                    self.next_id += 1;
                    let n = self.next_id;
                    let (message, schema) = question_form(&questions);
                    self.asks.insert(n, Ask { session: sid.to_string(), request_id: rid, input: r["input"].clone(),
                                              for_session: Vec::new(), questions: Some(questions) });
                    self.write(&json!({"jsonrpc": "2.0", "id": n, "method": "elicitation/create",
                                       "params": {"mode": "form", "sessionId": sid, "toolCallId": tool_id,
                                                  "message": message, "requestedSchema": schema}}));
                    return;
                }
                let for_session: Vec<Value> = r["permission_suggestions"].as_array().into_iter().flatten()
                    .filter(|p| p["destination"] == "session").cloned().collect();
                self.next_id += 1;
                let n = self.next_id;
                let mut options = vec![json!({"optionId": "allow", "name": "Allow", "kind": "allow_once"})];
                if !for_session.is_empty() {
                    options.push(json!({"optionId": "allow_session", "name": "Allow, and the like for this session", "kind": "allow_always"}));
                }
                options.push(json!({"optionId": "reject", "name": "Refuse", "kind": "reject_once"}));
                let mut call = tool_call(&tool_id, &name, &r["input"]);
                call["status"] = json!("pending");
                self.asks.insert(n, Ask { session: sid.to_string(), request_id: rid, input: r["input"].clone(), for_session, questions: None });
                self.write(&json!({"jsonrpc": "2.0", "id": n, "method": "session/request_permission",
                                   "params": {"sessionId": sid, "toolCall": call, "options": options}}));
            }
            // Claude Code withdrew a question (an interrupt): its answer is no longer wanted.
            Some("control_cancel_request") => {
                let rid = v["request_id"].as_str().unwrap_or("");
                self.asks.retain(|_, a| !(a.session == sid && a.request_id == rid));
            }
            Some("stream_event") if v["parent_tool_use_id"].is_null() => {
                let d = &v["event"]["delta"];
                let chunk = match d["type"].as_str() {
                    Some("text_delta") => d["text"].as_str().map(|t| ("agent_message_chunk", t)),
                    Some("thinking_delta") => d["thinking"].as_str().map(|t| ("agent_thought_chunk", t)),
                    _ => None,
                };
                if let Some((kind, text)) = chunk.filter(|(_, t)| !t.is_empty()) {
                    self.update(sid, json!({"sessionUpdate": kind, "content": {"type": "text", "text": text}}));
                }
            }
            Some("assistant") => {
                // How full the context is: what the last of its own messages was sent with.
                if v["parent_tool_use_id"].is_null() {
                    if let Some(n) = context_used(&v["message"]["usage"]) {
                        s.context = n;
                    }
                }
                for b in v["message"]["content"].as_array().into_iter().flatten().filter(|b| b["type"] == "tool_use") {
                    let name = b["name"].as_str().unwrap_or("?");
                    let mut call = tool_call(b["id"].as_str().unwrap_or(""), name, &b["input"]);
                    call["sessionUpdate"] = json!("tool_call");
                    call["status"] = json!("pending");
                    if let (true, Some(s)) = (call["content"].is_array(), self.sessions.get_mut(sid)) {
                        s.diffs.insert(b["id"].as_str().unwrap_or("").to_string());
                    }
                    within(&mut call, &v["parent_tool_use_id"]);
                    let plan = (name == "TodoWrite").then(|| plan(&b["input"]));
                    self.update(sid, call);
                    if let Some(p) = plan {
                        self.update(sid, p);
                    }
                }
            }
            Some("user") => {
                for b in v["message"]["content"].as_array().into_iter().flatten().filter(|b| b["type"] == "tool_result") {
                    let mut done = tool_result(b);
                    if self.sessions.get_mut(sid).is_some_and(|s| s.diffs.remove(b["tool_use_id"].as_str().unwrap_or(""))) {
                        keep_diff(&mut done);
                    }
                    within(&mut done, &v["parent_tool_use_id"]);
                    self.update(sid, done);
                }
            }
            Some("result") => {
                let Some(rpc) = s.prompts.pop_front() else { return };
                let cancelled = std::mem::take(&mut s.cancelling);
                if !s.prompts.is_empty() {
                    s.cancelling = cancelled;
                }
                // The context after the turn, against the model's window: as Zed shows it.
                let size = v["modelUsage"].as_object().into_iter().flat_map(|m| m.values()).filter_map(|m| m["contextWindow"].as_u64()).max();
                let used = s.context;
                if let (Some(size), true) = (size, used > 0) {
                    self.update(sid, json!({"sessionUpdate": "usage_update", "used": used, "size": size,
                                            "cost": {"amount": v["total_cost_usd"], "currency": "USD"}}));
                }
                match stop_reason(&v, cancelled) {
                    Ok(r) => self.answer(&rpc, json!({"stopReason": r})),
                    Err(why) => self.refuse(&rpc, -32603, &why),
                }
            }
            _ => {}
        }
    }

    /// A session's Claude Code ended: whatever waited on it fails. True when
    /// no session is left, which ends the adapter.
    fn gone(&mut self, sid: &str) -> bool {
        // One the client closed is gone already, and ends nothing else.
        let Some(mut s) = self.sessions.remove(sid) else { return false };
        let _ = s.child.wait();
        let why = "Claude Code exited";
        for rpc in s.opening.take().into_iter().chain(s.prompts.drain(..))
            .chain(s.modes.into_values().map(|(r, _)| r)).chain(s.models.into_values().map(|(r, _)| r)) {
            self.refuse(&rpc, -32603, why);
        }
        self.asks.retain(|_, a| a.session != sid);
        self.sessions.is_empty()
    }
}

fn initialize() -> Value {
    json!({
        "protocolVersion": ACP_VERSION,
        "agentCapabilities": {
            "loadSession": true,
            "promptCapabilities": {"image": true, "audio": false, "embeddedContext": true},
            "mcpCapabilities": {"http": true, "sse": true},
            "sessionCapabilities": {"systemPrompt": {}, "list": {}, "close": {}, "delete": {}, "additionalDirectories": {}},
        },
        "agentInfo": {"name": "midas", "title": "Claude Code, through midas", "version": crate::VERSION},
        "authMethods": [],
    })
}

/// A model's name as Claude Code takes one: an alias or a model id.
pub fn model_ok(m: &str) -> bool {
    !m.is_empty() && m.len() <= 80 && m.bytes().all(|b| b.is_ascii_alphanumeric() || b"-_.[]".contains(&b))
}

/// Whether its Claude Code was started in fast mode.
fn started_fast(args: &[String]) -> bool {
    args.windows(2).any(|w| w[0] == "--settings" && w[1] == FAST_SETTINGS)
}

/// The session's models as ACP has them, the current one from its arguments.
fn models(args: &[String]) -> Value {
    let current = if started_fast(args) {
        FAST
    } else {
        args.iter().position(|a| a == "--model").and_then(|i| args.get(i + 1)).map_or("default", String::as_str)
    };
    let mut available: Vec<Value> = MODELS.iter().map(|(id, name, d)| json!({"modelId": id, "name": name, "description": d})).collect();
    // A model asked for by its full id is offered too, so the list names the one in use.
    if !MODELS.iter().any(|(id, ..)| *id == current) {
        available.push(json!({"modelId": current, "name": current}));
    }
    json!({"currentModelId": current, "availableModels": available})
}

/// The session's modes as ACP has them, from the arguments its Claude Code was started with.
fn modes(args: &[String]) -> Value {
    let current = args.iter().position(|a| a == "--permission-mode").and_then(|i| args.get(i + 1)).map_or("default", String::as_str);
    let bypass = args.iter().any(|a| a == "--allow-dangerously-skip-permissions");
    json!({"currentModeId": current, "availableModes": MODES.iter()
        .filter(|(id, ..)| bypass || *id != "bypassPermissions")
        .map(|(id, name, d)| json!({"id": id, "name": name, "description": d})).collect::<Vec<_>>()})
}

/// The suggestions an "allow for the session" passes on from `mode`, and the
/// mode they move the session to, if any: a suggested mode only from Manual.
fn session_rules(mode: &str, suggested: &[Value]) -> (Vec<Value>, Option<String>) {
    let kept: Vec<Value> = suggested.iter().filter(|p| p["type"] != "setMode" || mode == "default").cloned().collect();
    let taken = kept.iter().rev().find(|p| p["type"] == "setMode").and_then(|p| p["mode"].as_str()).map(str::to_string);
    (kept, taken)
}

fn deny(why: &str) -> Value {
    json!({"behavior": "deny", "message": why})
}

/// The tokens a message was sent with — new, cached and cache-written input,
/// and what it wrote — which is what the context holds at that point.
fn context_used(u: &Value) -> Option<u64> {
    let n = |k: &str| u[k].as_u64().unwrap_or(0);
    let total = n("input_tokens") + n("cache_read_input_tokens") + n("cache_creation_input_tokens") + n("output_tokens");
    (total > 0).then_some(total)
}

/// AskUserQuestion's well-formed questions (text and at least one option), or
/// none.
pub fn valid_questions(input: &Value) -> Option<Vec<Value>> {
    let q: Vec<Value> = input["questions"].as_array()?.iter()
        .filter(|q| q["question"].is_string() && q["options"].as_array().is_some_and(|o| !o.is_empty()))
        .cloned().collect();
    (!q.is_empty()).then_some(q)
}

/// The questions as an ACP form: `question_<n>` a single choice (`oneOf`) or a
/// multiple one (`anyOf`), each option's label its value, and `question_<n>_custom`
/// an "Other" box beside it. Nothing required: the person may skip. Returns the
/// message (the one question, or a line over several) and the schema.
pub fn question_form(questions: &[Value]) -> (String, Value) {
    let single = questions.len() == 1;
    let mut props = serde_json::Map::new();
    for (i, q) in questions.iter().enumerate() {
        let options: Vec<Value> = q["options"].as_array().into_iter().flatten().map(|o| {
            let mut e = json!({"const": o["label"], "title": o["label"]});
            if o["description"].is_string() {
                e["description"] = o["description"].clone();
            }
            e
        }).collect();
        let mut field = if q["multiSelect"] == true {
            json!({"type": "array", "items": {"anyOf": options}})
        } else {
            json!({"type": "string", "oneOf": options})
        };
        if let Some(h) = q["header"].as_str() {
            field["title"] = json!(h);
        }
        if !single {
            field["description"] = q["question"].clone();
        }
        props.insert(format!("question_{i}"), field);
        props.insert(format!("question_{i}_custom"), json!({"type": "string", "title": "Other",
            "description": if q["multiSelect"] == true { "Your own answer, added to those picked (optional)." }
                           else { "Your own answer, or a note to the one picked (optional)." }}));
    }
    let message = if single { questions[0]["question"].as_str().unwrap_or("").to_string() } else { "Please answer these questions.".into() };
    (message, json!({"type": "object", "properties": props}))
}

/// The client's answer to the form, for Claude Code: `answers` keyed by the
/// question's text — a pick's label; several comma-joined (one holding a comma
/// or quote quoted), as the CLI's dialog does; or the "Other" text — and a note
/// to a single pick under `annotations`. Declined: no answers. Cancelled, or no
/// answer at all: the tool is refused.
pub fn question_response(questions: &[Value], input: &Value, result: &Value) -> Value {
    match result["action"].as_str() {
        Some("accept") => {}
        Some("decline") => {
            let mut i = input.clone();
            i["answers"] = json!({});
            return json!({"behavior": "allow", "updatedInput": i});
        }
        _ => return deny("The person did not answer."),
    }
    let content = &result["content"];
    let join = |items: Vec<String>| items.iter()
        .map(|s| if s.contains(", ") || s.contains('"') { Value::String(s.clone()).to_string() } else { s.clone() })
        .collect::<Vec<_>>().join(", ");
    let (mut answers, mut notes) = (serde_json::Map::new(), serde_json::Map::new());
    for (i, q) in questions.iter().enumerate() {
        let text = q["question"].as_str().unwrap_or("").to_string();
        let custom = content[format!("question_{i}_custom")].as_str().unwrap_or("").trim().to_string();
        let picks: Vec<String> = match &content[format!("question_{i}")] {
            Value::Array(a) => a.iter().filter_map(|v| v.as_str()).filter(|s| !s.is_empty()).map(str::to_string).collect(),
            Value::String(s) if !s.is_empty() => vec![s.clone()],
            _ => Vec::new(),
        };
        if q["multiSelect"] == true {
            let mut all = picks;
            if !custom.is_empty() {
                all.push(custom);
            }
            if !all.is_empty() {
                answers.insert(text, json!(join(all)));
            }
        } else if picks.is_empty() {
            if !custom.is_empty() {
                answers.insert(text, json!(custom));
            }
        } else {
            answers.insert(text.clone(), json!(picks.join(", ")));
            if !custom.is_empty() {
                notes.insert(text, json!({"notes": custom}));
            }
        }
    }
    let mut i = input.clone();
    i["answers"] = Value::Object(answers);
    if !notes.is_empty() {
        i["annotations"] = Value::Object(notes);
    }
    json!({"behavior": "allow", "updatedInput": i})
}

/// Claude Code's arguments for a session: the stream, the session, and the
/// client's MCP servers, system prompt and `_meta.claudeCode.options`.
#[cfg(test)]
pub fn claude_args(params: &Value, sid: &str, resume: bool) -> Result<Vec<String>> {
    claude_args_with(params, sid, resume, false)
}

/// As `claude_args`; `questions` leaves AskUserQuestion on, for a client that
/// takes forms.
pub fn claude_args_with(params: &Value, sid: &str, resume: bool, questions: bool) -> Result<Vec<String>> {
    let mut a: Vec<String> = ["-p", "--input-format", "stream-json", "--output-format", "stream-json", "--verbose",
        "--include-partial-messages", "--permission-prompt-tool", "stdio"].map(String::from).to_vec();
    a.extend([if resume { "--resume" } else { "--session-id" }.into(), sid.into()]);
    let mut mode = "default".to_string();
    let mut bypass = true;
    let mut disallowed: Vec<String> = if questions { Vec::new() } else { vec!["AskUserQuestion".to_string()] };
    let servers = params["mcpServers"].as_array().map(Vec::as_slice).unwrap_or(&[]);
    if !servers.is_empty() {
        a.extend(["--mcp-config".into(), mcp_config(servers)?.to_string()]);
    }
    // A multi-root workspace: the roots beside the cwd, each one Claude Code may read and edit too.
    for d in params["additionalDirectories"].as_array().map(Vec::as_slice).unwrap_or(&[]) {
        let d = d.as_str().filter(|d| std::path::Path::new(d).is_absolute())
            .ok_or_else(|| anyhow!("additionalDirectories are absolute paths"))?;
        a.extend(["--add-dir".into(), d.into()]);
    }
    match (params["systemPrompt"]["mode"].as_str(), system_text(&params["systemPrompt"])) {
        (_, None) => {}
        (Some("replace"), Some(t)) => a.extend(["--system-prompt".into(), t]),
        (_, Some(t)) => a.extend(["--append-system-prompt".into(), t]),
    }
    let names = |v: &Value, key: &str| -> Result<Vec<String>> {
        v.as_array().ok_or_else(|| anyhow!("claudeCode.options.{key} is a list"))?.iter()
            .map(|n| n.as_str().map(str::to_string).ok_or_else(|| anyhow!("claudeCode.options.{key} is a list of names")))
            .collect()
    };
    for (key, v) in params["_meta"]["claudeCode"]["options"].as_object().into_iter().flatten() {
        match key.as_str() {
            "tools" => a.extend(["--tools".into(), names(v, key)?.join(",")]),
            "settingSources" => a.extend(["--setting-sources".into(), names(v, key)?.join(",")]),
            "allowedTools" => a.extend(["--allowedTools".into(), names(v, key)?.join(",")]),
            "disallowedTools" => disallowed.extend(names(v, key)?),
            "strictMcpConfig" if v == true => a.push("--strict-mcp-config".into()),
            "strictMcpConfig" if v == false => {}
            "allowBypass" => bypass = v.as_bool().ok_or_else(|| anyhow!("claudeCode.options.allowBypass is true or false"))?,
            "model" | "permissionMode" => {
                let s = v.as_str().ok_or_else(|| anyhow!("claudeCode.options.{key} is a name"))?.to_string();
                if key == "model" {
                    if !model_ok(&s) {
                        bail!("claudeCode.options.model is a model's name: {s}");
                    }
                    // `default` is Claude Code's own choice: no flag.
                    if s == FAST {
                        a.extend(["--model".into(), "opus".into(), "--settings".into(), FAST_SETTINGS.into()]);
                    } else if s != "default" {
                        a.extend(["--model".into(), s]);
                    }
                } else {
                    mode = s;
                }
            }
            _ => bail!("midas's Claude Code adapter does not take claudeCode.options.{key}"),
        }
    }
    // Always a mode of our own: Claude Code otherwise takes its user's, and a
    // mode that approves by itself would never ask the client.
    a.extend(["--permission-mode".into(), mode]);
    if !disallowed.is_empty() {
        a.extend(["--disallowedTools".into(), disallowed.join(",")]);
    }
    // Lets the client switch to bypassPermissions later; switches nothing by itself.
    if bypass {
        a.push("--allow-dangerously-skip-permissions".into());
    }
    Ok(a)
}

fn system_text(sp: &Value) -> Option<String> {
    if let Some(t) = sp.as_str() {
        return Some(t.to_string()).filter(|t| !t.trim().is_empty());
    }
    let t: Vec<&str> = sp["content"].as_array().into_iter().flatten().filter_map(|b| b["text"].as_str()).collect();
    Some(t.join("\n\n")).filter(|t| !t.trim().is_empty())
}

/// ACP's MCP servers as Claude Code's `--mcp-config`.
pub fn mcp_config(servers: &[Value]) -> Result<Value> {
    let pairs = |v: &Value| -> serde_json::Map<String, Value> {
        v.as_array().into_iter().flatten()
            .filter_map(|p| Some((p["name"].as_str()?.to_string(), json!(p["value"].as_str()?)))).collect()
    };
    let mut out = serde_json::Map::new();
    for s in servers {
        let name = s["name"].as_str().filter(|n| !n.is_empty()).context("an MCP server with no name")?;
        let conf = match s["type"].as_str() {
            Some(t @ ("http" | "sse")) => json!({"type": t, "url": s["url"], "headers": pairs(&s["headers"])}),
            None | Some("stdio") => json!({"type": "stdio", "command": s["command"], "args": s["args"].as_array().cloned().unwrap_or_default(),
                                           "env": pairs(&s["env"])}),
            Some(t) => bail!("MCP server {name}: no transport {t}"),
        };
        out.insert(name.to_string(), conf);
    }
    Ok(json!({"mcpServers": out}))
}

/// An ACP prompt as the content of Claude Code's user message.
pub fn user_content(blocks: &[Value]) -> Vec<Value> {
    blocks.iter().filter_map(|b| match b["type"].as_str()? {
        "text" => Some(json!({"type": "text", "text": b["text"].as_str()?})),
        "image" => Some(json!({"type": "image", "source": {"type": "base64", "media_type": b["mimeType"], "data": b["data"]}})),
        "resource_link" => Some(json!({"type": "text", "text": format!("@{}", b["uri"].as_str()?)})),
        "resource" => {
            let r = &b["resource"];
            let uri = r["uri"].as_str().unwrap_or("");
            Some(json!({"type": "text", "text": match r["text"].as_str() {
                Some(t) => format!("<context ref=\"{uri}\">\n{t}\n</context>"),
                None => format!("@{uri}"),
            }}))
        }
        other => Some(json!({"type": "text", "text": format!("[a {other} block, which Claude Code cannot take]")})),
    }).collect()
}

/// A tool use as ACP's tool call. `_meta.claudeCode.toolName` carries the
/// tool's own name (`mcp__<server>__<tool>`), which the bot host's rule reads.
pub fn tool_call(id: &str, name: &str, input: &Value) -> Value {
    let mut call = json!({"toolCallId": id, "title": title(name, input), "kind": kind(name), "rawInput": input,
                          "_meta": {"claudeCode": {"toolName": name}}});
    let path = input["file_path"].as_str().or(input["notebook_path"].as_str());
    // The file it reads or changes, for the client to open; a change as a diff
    // (the edit's own before and after, not the whole file: the adapter does not read it).
    if let Some(p) = path {
        call["locations"] = json!([{"path": p, "line": input["offset"].as_u64()}]);
    }
    let diff = |old: &Value, new: &Value| json!({"type": "diff", "path": path, "oldText": old, "newText": new});
    let content: Vec<Value> = match (name, path) {
        ("Edit", Some(_)) => vec![diff(&input["old_string"], &input["new_string"])],
        ("MultiEdit", Some(_)) => input["edits"].as_array().into_iter().flatten().map(|e| diff(&e["old_string"], &e["new_string"])).collect(),
        ("Write", Some(_)) => vec![diff(&Value::Null, &input["content"])],
        _ => Vec::new(),
    };
    if !content.is_empty() {
        call["content"] = json!(content);
    }
    call
}

/// Claude Code's commands (its `initialize` answer) as ACP's: name,
/// description, and the hint for what follows it.
fn commands(list: &Value) -> Value {
    json!(list.as_array().into_iter().flatten().filter_map(|c| {
        let name = c["name"].as_str().filter(|n| !n.is_empty())?;
        let description: String = c["description"].as_str().unwrap_or("").chars().take(200).collect();
        let hint = c["argumentHint"].as_str().filter(|h| !h.is_empty());
        Some(json!({"name": name, "description": description, "input": hint.map(|h| json!({"hint": h}))}))
    }).collect::<Vec<_>>())
}

/// How many transcripts `session/list` offers, newest first.
const LISTED: usize = 50;

/// Where Claude Code keeps the transcripts of sessions had in `cwd`: its
/// projects directory, named for the real path with every character but a
/// letter or digit a dash (`/Users/x/code/cartopolis` → `-Users-x-code-cartopolis`).
pub fn project_dir(cwd: &str) -> std::path::PathBuf {
    let real = std::fs::canonicalize(cwd).map(|p| p.to_string_lossy().to_string()).unwrap_or_else(|_| cwd.to_string());
    let name: String = real.chars().map(|c| if c.is_ascii_alphanumeric() { c } else { '-' }).collect();
    projects_dir().join(name)
}

/// Claude Code's projects directory: one directory of transcripts per working directory.
fn projects_dir() -> std::path::PathBuf {
    let home = std::env::var("CLAUDE_CONFIG_DIR").map(std::path::PathBuf::from)
        .unwrap_or_else(|_| std::path::PathBuf::from(std::env::var("HOME").unwrap_or_default()).join(".claude"));
    home.join("projects")
}

/// The transcript of session `sid`, had in `cwd`.
pub fn transcript(cwd: &str, sid: &str) -> std::path::PathBuf {
    project_dir(cwd).join(format!("{sid}.jsonl"))
}

/// A subagent's tool call (or its update) names the call it runs under —
/// the Agent tool's — as `_meta.parentToolCallId`, so a client can nest it
/// there. Claude Code's stream gives it as `parent_tool_use_id`; null for the
/// session's own calls, which are left as they are.
pub fn within(update: &mut Value, parent: &Value) {
    if let Some(p) = parent.as_str().filter(|p| !p.is_empty()) {
        if !update["_meta"].is_object() {
            update["_meta"] = json!({});
        }
        update["_meta"]["parentToolCallId"] = json!(p);
    }
}

/// Claude Code's live background tasks (`background_tasks_changed`) as the
/// page has them: id, kind and what it is. Its own housekeeping (`ambient`) is
/// left out, as Claude Code asks of a client.
fn live_tasks(tasks: &Value) -> Vec<Value> {
    tasks.as_array().into_iter().flatten().filter(|t| t["ambient"] != true)
        .map(|t| json!({"id": t["task_id"], "kind": t["task_type"], "description": t["description"]}))
        .collect()
}

pub fn title(name: &str, input: &Value) -> String {
    let arg = ["command", "file_path", "notebook_path", "path", "pattern", "url", "query", "description"]
        .iter().find_map(|k| input[*k].as_str()).map(|a| a.lines().next().unwrap_or("").to_string());
    match arg {
        Some(a) if !a.is_empty() => {
            let a: String = if a.chars().count() > 120 { a.chars().take(119).chain(['…']).collect() } else { a };
            format!("{name}: {a}")
        }
        _ => name.to_string(),
    }
}

fn kind(name: &str) -> &'static str {
    match name {
        "Read" | "NotebookRead" => "read",
        "Write" | "Edit" | "MultiEdit" | "NotebookEdit" => "edit",
        "Bash" | "BashOutput" | "KillShell" => "execute",
        "Grep" | "Glob" | "LS" | "ToolSearch" => "search",
        "WebFetch" | "WebSearch" => "fetch",
        "Task" | "Agent" => "think",
        "ExitPlanMode" | "EnterPlanMode" => "switch_mode",
        _ => "other",
    }
}

pub fn plan(input: &Value) -> Value {
    let entries: Vec<Value> = input["todos"].as_array().into_iter().flatten().map(|t| json!({
        "content": t["content"], "priority": "medium",
        "status": match t["status"].as_str() { Some(s @ ("in_progress" | "completed")) => s, _ => "pending" },
    })).collect();
    json!({"sessionUpdate": "plan", "entries": entries})
}

/// A tool's result as the update that ends its call.
pub fn tool_result(b: &Value) -> Value {
    let text = match &b["content"] {
        Value::String(s) => s.clone(),
        Value::Array(parts) => parts.iter().filter_map(|p| p["text"].as_str()).collect::<Vec<_>>().join("\n"),
        _ => String::new(),
    };
    let text: String = if text.chars().count() > 4000 { text.chars().take(4000).chain("\n…".chars()).collect() } else { text };
    json!({"sessionUpdate": "tool_call_update", "toolCallId": b["tool_use_id"],
           "status": if b["is_error"] == true { "failed" } else { "completed" },
           "content": [{"type": "content", "content": {"type": "text", "text": text}}]})
}

/// An edit's or a write's result: its update's content would replace the
/// diff with "updated successfully", so a success sends none and the diff
/// stays. A failure says why.
pub fn keep_diff(done: &mut Value) {
    if done["status"] == "completed" {
        if let Some(o) = done.as_object_mut() {
            o.remove("content");
        }
    }
}

/// How a turn ended, from its `result`; an error the turn could not survive
/// is the prompt's error.
pub fn stop_reason(v: &Value, cancelled: bool) -> Result<&'static str, String> {
    if cancelled {
        return Ok("cancelled");
    }
    match v["subtype"].as_str() {
        // A turn the API refused (a login expired, a bad key): Claude Code calls it a
        // success, with its reason only in a message of its own that is never streamed.
        Some("success") if v["is_error"] == true => {
            Err(v["result"].as_str().filter(|r| !r.is_empty()).unwrap_or("the API refused the turn").to_string())
        }
        Some("success") => Ok(match v["stop_reason"].as_str() {
            Some("max_tokens") => "max_tokens",
            Some("refusal") => "refusal",
            _ => "end_turn",
        }),
        Some("error_max_turns") => Ok("max_turn_requests"),
        other => {
            let errors: Vec<&str> = v["errors"].as_array().into_iter().flatten().filter_map(Value::as_str).collect();
            Err(if !errors.is_empty() { errors.join("; ") } else {
                v["result"].as_str().map(str::to_string).unwrap_or_else(|| format!("the turn failed ({})", other.unwrap_or("?")))
            })
        }
    }
}

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

    #[test]
    fn a_session_offers_the_model_aliases_and_says_which_it_is_on() {
        let none = claude_args_with(&json!({}), "s", false, false).unwrap();
        assert_eq!(models(&none)["currentModelId"], "default");
        assert!(!none.contains(&"--model".to_string()));
        let offered = models(&none);
        let ids: Vec<&str> = offered["availableModels"].as_array().unwrap().iter().filter_map(|m| m["modelId"].as_str()).collect();
        assert_eq!(ids, ["default", "fable", "opus", "opus-fast", "sonnet", "haiku"]);
        let fast = claude_args_with(&json!({"_meta": {"claudeCode": {"options": {"model": "opus-fast"}}}}), "s", false, false).unwrap();
        assert!(fast.windows(2).any(|w| w[0] == "--model" && w[1] == "opus"), "fast mode is Opus");
        assert!(fast.windows(2).any(|w| w[0] == "--settings" && w[1] == r#"{"fastMode":true}"#));
        assert_eq!(models(&fast)["currentModelId"], "opus-fast");
        assert_eq!(models(&fast)["availableModels"].as_array().unwrap().len(), MODELS.len(), "not listed twice");
        let opus = claude_args_with(&json!({"_meta": {"claudeCode": {"options": {"model": "opus"}}}}), "s", false, false).unwrap();
        assert!(opus.windows(2).any(|w| w[0] == "--model" && w[1] == "opus"));
        assert_eq!(models(&opus)["currentModelId"], "opus");
        let dflt = claude_args_with(&json!({"_meta": {"claudeCode": {"options": {"model": "default"}}}}), "s", false, false).unwrap();
        assert!(!dflt.contains(&"--model".to_string()), "default is Claude Code's own choice: no flag");
        let full = claude_args_with(&json!({"_meta": {"claudeCode": {"options": {"model": "claude-opus-5-5"}}}}), "s", false, false).unwrap();
        assert_eq!(models(&full)["availableModels"].as_array().unwrap().last().unwrap()["modelId"], "claude-opus-5-5", "a full id is listed too");
        assert!(claude_args_with(&json!({"_meta": {"claudeCode": {"options": {"model": "x y"}}}}), "s", false, false).is_err());
        assert!(model_ok("opus[1m]") && !model_ok("") && !model_ok("a;b"));
    }

    fn asked() -> Vec<Value> {
        valid_questions(&json!({"questions": [
            {"question": "Which cache?", "header": "Cache", "options": [{"label": "Redis", "description": "fast"}, {"label": "Memcached"}]},
            {"question": "Which targets?", "multiSelect": true, "options": [{"label": "wasm"}, {"label": "android, arm64"}]},
            {"question": "no options", "options": []},
        ]})).unwrap()
    }

    #[test]
    fn questions_become_a_form_with_an_other_box_each() {
        let q = asked();
        assert_eq!(q.len(), 2, "a question with no options is not one");
        let (message, schema) = question_form(&q);
        assert_eq!(message, "Please answer these questions.");
        let p = &schema["properties"];
        assert_eq!(p["question_0"]["oneOf"][0], json!({"const": "Redis", "title": "Redis", "description": "fast"}));
        assert_eq!((p["question_0"]["title"].as_str(), p["question_0"]["description"].as_str()), (Some("Cache"), Some("Which cache?")));
        assert_eq!(p["question_1"]["type"], "array");
        assert_eq!(p["question_1"]["items"]["anyOf"][1]["const"], "android, arm64");
        assert_eq!(p["question_1_custom"]["title"], "Other");
        assert_eq!(question_form(&q[..1]).0, "Which cache?", "one question is its own message");
        assert!(valid_questions(&json!({"questions": []})).is_none());
    }

    #[test]
    fn answers_go_back_as_the_cli_gives_them() {
        let q = asked();
        let input = json!({"questions": q});
        let r = question_response(&q, &input, &json!({"action": "accept", "content": {
            "question_0": "Redis", "question_0_custom": " only for tiles ",
            "question_1": ["wasm", "android, arm64"], "question_1_custom": "ios"}}));
        assert_eq!(r["behavior"], "allow");
        assert_eq!(r["updatedInput"]["answers"], json!({"Which cache?": "Redis", "Which targets?": "wasm, \"android, arm64\", ios"}));
        assert_eq!(r["updatedInput"]["annotations"], json!({"Which cache?": {"notes": "only for tiles"}}), "a note to a single pick");
        assert_eq!(r["updatedInput"]["questions"], input["questions"], "the rest of the input as it was");
        let other = question_response(&q, &input, &json!({"action": "accept", "content": {"question_0_custom": "SQLite"}}));
        assert_eq!(other["updatedInput"]["answers"], json!({"Which cache?": "SQLite"}), "Other is the answer when nothing is picked");
        assert!(other["updatedInput"].get("annotations").is_none());
        assert_eq!(question_response(&q, &input, &json!({"action": "decline"}))["updatedInput"]["answers"], json!({}));
        assert_eq!(question_response(&q, &input, &json!({"action": "cancel"}))["behavior"], "deny");
        assert_eq!(question_response(&q, &input, &Value::Null)["behavior"], "deny");
    }

    #[test]
    fn ask_user_question_is_on_only_for_a_client_that_takes_forms() {
        let off = claude_args_with(&json!({}), "s", false, false).unwrap();
        assert!(off.windows(2).any(|w| w[0] == "--disallowedTools" && w[1] == "AskUserQuestion"));
        let on = claude_args_with(&json!({}), "s", false, true).unwrap();
        assert!(!on.iter().any(|a| a.contains("AskUserQuestion")));
        assert!(!on.contains(&"--disallowedTools".to_string()), "no empty list for the flag");
        let fenced = claude_args_with(&json!({"_meta": {"claudeCode": {"options": {"disallowedTools": ["Bash"]}}}}), "s", false, true).unwrap();
        assert!(fenced.windows(2).any(|w| w[0] == "--disallowedTools" && w[1] == "Bash"));
    }
    use std::io::{BufRead, BufReader, Write};
    use std::os::unix::fs::PermissionsExt;
    use std::time::Duration;

    #[test]
    fn options_become_flags_and_an_unknown_one_is_refused() {
        let p = json!({"mcpServers": [], "_meta": {"claudeCode": {"options": {"tools": [], "settingSources": [], "strictMcpConfig": true}}}});
        let a = claude_args(&p, "s", false).unwrap();
        let after = |f: &str| a.iter().position(|x| x == f).map(|i| a[i + 1].as_str());
        assert_eq!(after("--tools"), Some(""));
        assert_eq!(after("--setting-sources"), Some(""));
        assert_eq!(after("--session-id"), Some("s"));
        assert_eq!(after("--permission-mode"), Some("default"));
        assert_eq!(after("--disallowedTools"), Some("AskUserQuestion"));
        assert!(a.contains(&"--strict-mcp-config".to_string()));
        assert!(!a.contains(&"--mcp-config".to_string()));
        let bad = json!({"_meta": {"claudeCode": {"options": {"hooks": {}}}}});
        assert!(claude_args(&bad, "s", false).is_err());
        let resumed = claude_args(&json!({}), "s", true).unwrap();
        assert!(resumed.windows(2).any(|w| w[0] == "--resume" && w[1] == "s"));
        // Bypass is offered unless the session's fence says not: the bot's does.
        let offered = |a: &[String]| modes(a)["availableModes"].as_array().unwrap().iter().any(|m| m["id"] == "bypassPermissions");
        assert!(offered(&resumed));
        let fenced = claude_args(&json!({"_meta": bot_fence()}), "s", false).unwrap();
        assert!(!fenced.contains(&"--allow-dangerously-skip-permissions".to_string()));
        assert!(!offered(&fenced));
        assert_eq!(modes(&fenced)["currentModeId"], "default");
    }

    #[test]
    fn mcp_servers_and_a_system_prompt_are_passed_on() {
        let p = json!({"mcpServers": [{"name": "bot", "command": "/bin/midas", "args": ["bot", "mcp"], "env": [{"name": "A", "value": "1"}]}],
                       "systemPrompt": {"mode": "append", "content": [{"type": "text", "text": "Be brief."}]}});
        let a = claude_args(&p, "s", false).unwrap();
        let i = a.iter().position(|x| x == "--mcp-config").unwrap();
        let conf: Value = serde_json::from_str(&a[i + 1]).unwrap();
        assert_eq!(conf["mcpServers"]["bot"], json!({"type": "stdio", "command": "/bin/midas", "args": ["bot", "mcp"], "env": {"A": "1"}}));
        assert!(a.windows(2).any(|w| w[0] == "--append-system-prompt" && w[1] == "Be brief."));
    }

    #[test]
    fn the_other_roots_of_a_workspace_are_added() {
        let a = claude_args(&json!({"additionalDirectories": ["/w/podium", "/w/midas"]}), "s", false).unwrap();
        let added: Vec<_> = a.windows(2).filter(|w| w[0] == "--add-dir").map(|w| w[1].as_str()).collect();
        assert_eq!(added, ["/w/podium", "/w/midas"]);
        assert!(claude_args(&json!({"additionalDirectories": ["podium"]}), "s", false).is_err());
    }

    #[test]
    fn a_prompt_keeps_its_text_and_pictures() {
        let c = user_content(&[json!({"type": "text", "text": "look"}), json!({"type": "image", "data": "AAA", "mimeType": "image/png"})]);
        assert_eq!(c[0], json!({"type": "text", "text": "look"}));
        assert_eq!(c[1]["source"], json!({"type": "base64", "media_type": "image/png", "data": "AAA"}));
    }

    #[test]
    fn a_tool_call_says_what_it_does_and_names_the_tool() {
        let t = tool_call("t1", "Bash", &json!({"command": "ls -la\nmore", "description": "List"}));
        assert_eq!((t["title"].as_str(), t["kind"].as_str()), (Some("Bash: ls -la"), Some("execute")));
        let m = tool_call("t2", "mcp__bot__say", &json!({"text": "hi"}));
        assert_eq!(m["_meta"]["claudeCode"]["toolName"], "mcp__bot__say");
        // What the bot host's rule reads to tell the bot's tools from others.
        assert_eq!(crate::host::server_of(&m).as_deref(), Some("bot"));
    }

    #[test]
    fn a_subagents_tool_call_names_the_call_it_runs_under() {
        let mut t = tool_call("t3", "Read", &json!({"file_path": "a.rs"}));
        within(&mut t, &json!("toolu_agent"));
        assert_eq!(t["_meta"]["parentToolCallId"], "toolu_agent");
        assert_eq!(t["_meta"]["claudeCode"]["toolName"], "Read", "what was there stays");
        let mut own = tool_call("t4", "Read", &json!({}));
        within(&mut own, &Value::Null);
        assert!(own["_meta"].get("parentToolCallId").is_none());
        let mut done = tool_result(&json!({"tool_use_id": "t3", "content": "ok"}));
        within(&mut done, &json!("toolu_agent"));
        let item = crate::sessions::update_item(&done).unwrap();
        assert_eq!(item["parent"], "toolu_agent", "the page's log item carries it too");
    }

    #[test]
    fn allowing_for_the_session_never_undoes_a_chosen_mode() {
        let edit = [json!({"type": "setMode", "mode": "acceptEdits", "destination": "session"})];
        assert_eq!(session_rules("default", &edit), (edit.to_vec(), Some("acceptEdits".into())), "from Manual it moves, and says so");
        assert_eq!(session_rules("bypassPermissions", &edit), (vec![], None), "Trusted, chosen while the question waited, stays");
        let rule = [json!({"type": "addRules", "rules": [{"toolName": "Bash"}], "behavior": "allow", "destination": "session"})];
        assert_eq!(session_rules("auto", &rule), (rule.to_vec(), None), "a rule is no mode, and passes in any");
    }

    #[test]
    fn a_turn_ends_as_claude_code_says_or_cancelled() {
        assert_eq!(stop_reason(&json!({"subtype": "success", "stop_reason": "end_turn"}), false), Ok("end_turn"));
        assert_eq!(stop_reason(&json!({"subtype": "error_during_execution"}), true), Ok("cancelled"));
        assert_eq!(stop_reason(&json!({"subtype": "error_max_turns"}), false), Ok("max_turn_requests"));
        // As Claude Code ends a turn whose login expired: a success that is an error.
        assert_eq!(stop_reason(&json!({"subtype": "success", "is_error": true, "stop_reason": "stop_sequence",
            "result": "Failed to authenticate: OAuth session expired and could not be refreshed"}), false),
            Err("Failed to authenticate: OAuth session expired and could not be refreshed".to_string()));
        assert!(stop_reason(&json!({"subtype": "error_during_execution", "errors": ["boom"]}), false).is_err());
        assert_eq!(tool_result(&json!({"tool_use_id": "t", "content": "no", "is_error": true}))["status"], "failed");
        // An edit's diff outlasts its "updated successfully"; its failure still says why.
        let mut ok = tool_result(&json!({"tool_use_id": "e", "content": "The file a.rs has been updated successfully."}));
        keep_diff(&mut ok);
        assert!(ok.get("content").is_none() && ok["status"] == "completed");
        let mut no = tool_result(&json!({"tool_use_id": "e", "content": "old_string not found", "is_error": true}));
        keep_diff(&mut no);
        assert_eq!(no["content"][0]["content"]["text"], "old_string not found");
        assert!(crate::registry::is_uuid(&crate::registry::new_uuid().unwrap()));
    }

    /// A stand-in for Claude Code: answers `initialize`, then for each user
    /// message asks to write a file, and ends the turn once answered, saying
    /// what it was told.
    const FAKE: &str = r#"#!/bin/sh
while IFS= read -r l; do
  case "$l" in
    *'"subtype":"initialize"'*) echo '{"type":"control_response","response":{"subtype":"success","request_id":"midas-open","response":{}}}' ;;
    *'"type":"user"'*)
      echo '{"type":"stream_event","parent_tool_use_id":null,"event":{"type":"content_block_delta","delta":{"type":"text_delta","text":"Writing."}}}'
      echo '{"type":"assistant","message":{"content":[{"type":"tool_use","id":"tu1","name":"Write","input":{"file_path":"b.txt"}}]}}'
      echo '{"type":"control_request","request_id":"q1","request":{"subtype":"can_use_tool","tool_name":"Write","input":{"file_path":"b.txt"},"tool_use_id":"tu1","permission_suggestions":[]}}' ;;
    *'"behavior":"allow"'*)
      echo '{"type":"user","message":{"content":[{"type":"tool_result","tool_use_id":"tu1","content":"done"}]}}'
      echo '{"type":"result","subtype":"success","stop_reason":"end_turn"}' ;;
    *'"behavior":"deny"'*)
      echo '{"type":"user","message":{"content":[{"type":"tool_result","tool_use_id":"tu1","content":"refused","is_error":true}]}}'
      echo '{"type":"result","subtype":"success","stop_reason":"end_turn"}' ;;
  esac
done
"#;

    #[test]
    fn a_session_runs_a_turn_and_its_permission_through_the_client() {
        let dir = std::env::temp_dir().join(format!("midas-acp-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let fake = dir.join("claude");
        std::fs::write(&fake, FAKE).unwrap();
        std::fs::set_permissions(&fake, std::fs::Permissions::from_mode(0o755)).unwrap();
        let (in_r, mut in_w) = std::io::pipe().unwrap();
        let (out_r, out_w) = std::io::pipe().unwrap();
        let claude = fake.to_string_lossy().to_string();
        let server = std::thread::spawn(move || serve(in_r, out_w, claude));
        let (tx, rx) = mpsc::channel::<Value>();
        std::thread::spawn(move || {
            for l in BufReader::new(out_r).lines().map_while(Result::ok) {
                let _ = tx.send(serde_json::from_str(&l).unwrap());
            }
        });
        let mut say = |v: Value| writeln!(in_w, "{v}").unwrap();
        let next = || rx.recv_timeout(Duration::from_secs(10)).expect("the adapter said nothing");

        say(json!({"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {"protocolVersion": 1}}));
        assert_eq!(next()["result"]["agentCapabilities"]["loadSession"], true);
        say(json!({"jsonrpc": "2.0", "id": 2, "method": "session/new", "params": {"cwd": dir, "mcpServers": []}}));
        let made = next();
        let sid = made["result"]["sessionId"].as_str().unwrap().to_string();
        assert_eq!(made["result"]["modes"]["currentModeId"], "default");
        assert_eq!(next()["params"]["update"]["sessionUpdate"], "available_commands_update", "its commands, once it is open");

        for (turn, choice, status) in [(3, "allow", "completed"), (4, "reject", "failed")] {
            say(json!({"jsonrpc": "2.0", "id": turn, "method": "session/prompt",
                       "params": {"sessionId": sid, "prompt": [{"type": "text", "text": "write b.txt"}]}}));
            assert_eq!(next()["params"]["update"]["content"]["text"], "Writing.");
            let call = next();
            assert_eq!((call["params"]["update"]["sessionUpdate"].as_str(), call["params"]["update"]["title"].as_str()),
                       (Some("tool_call"), Some("Write: b.txt")));
            let ask = next();
            assert_eq!(ask["method"], "session/request_permission");
            assert_eq!(ask["params"]["options"].as_array().unwrap().len(), 2, "no session-wide option without a suggestion");
            say(json!({"jsonrpc": "2.0", "id": ask["id"], "result": {"outcome": {"outcome": "selected", "optionId": choice}}}));
            assert_eq!(next()["params"]["update"]["status"], status);
            let end = next();
            assert_eq!((end["id"].as_u64(), end["result"]["stopReason"].as_str()), (Some(turn), Some("end_turn")));
        }

        // An unknown session, and the end of the client, which ends it all.
        say(json!({"jsonrpc": "2.0", "id": 5, "method": "session/prompt", "params": {"sessionId": "nope", "prompt": [{"type": "text", "text": "x"}]}}));
        assert!(next()["error"]["message"].as_str().unwrap().contains("no session"));
        drop(say);
        drop(in_w);
        server.join().unwrap();
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// A stand-in for Claude Code that starts a command in the background,
    /// ends its turn, and once the command ends takes a turn by itself — as
    /// Claude Code 2.1.281 does in stream mode (measured 2026-10-27).
    const FAKE_BACKGROUND: &str = r#"#!/bin/sh
while IFS= read -r l; do
  case "$l" in
    *'"subtype":"initialize"'*) echo '{"type":"control_response","response":{"subtype":"success","request_id":"midas-open","response":{}}}' ;;
    *'"type":"user"'*)
      echo '{"type":"assistant","message":{"content":[{"type":"tool_use","id":"tu1","name":"Bash","input":{"command":"cargo test","run_in_background":true}}]}}'
      echo '{"type":"system","subtype":"background_tasks_changed","tasks":[{"task_id":"b1","task_type":"local_bash","description":"cargo test"},{"task_id":"h","task_type":"x","description":"tidy","ambient":true}]}'
      echo '{"type":"result","subtype":"success","stop_reason":"end_turn"}'
      echo '{"type":"system","subtype":"background_tasks_changed","tasks":[]}'
      echo '{"type":"stream_event","parent_tool_use_id":null,"event":{"type":"content_block_delta","delta":{"type":"text_delta","text":"Tests pass."}}}'
      echo '{"type":"result","subtype":"success","stop_reason":"end_turn"}' ;;
  esac
done
"#;

    #[test]
    fn background_work_and_a_turn_it_wakes_are_said_between_turns() {
        let dir = std::env::temp_dir().join(format!("midas-acp-bg-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let fake = dir.join("claude");
        std::fs::write(&fake, FAKE_BACKGROUND).unwrap();
        std::fs::set_permissions(&fake, std::fs::Permissions::from_mode(0o755)).unwrap();
        let (in_r, mut in_w) = std::io::pipe().unwrap();
        let (out_r, out_w) = std::io::pipe().unwrap();
        let claude = fake.to_string_lossy().to_string();
        let server = std::thread::spawn(move || serve(in_r, out_w, claude));
        let (tx, rx) = mpsc::channel::<Value>();
        std::thread::spawn(move || {
            for l in BufReader::new(out_r).lines().map_while(Result::ok) {
                let _ = tx.send(serde_json::from_str(&l).unwrap());
            }
        });
        let mut say = |v: Value| writeln!(in_w, "{v}").unwrap();
        let next = || rx.recv_timeout(Duration::from_secs(10)).expect("the adapter said nothing");

        say(json!({"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {"protocolVersion": 1}}));
        next();
        say(json!({"jsonrpc": "2.0", "id": 2, "method": "session/new", "params": {"cwd": dir, "mcpServers": []}}));
        let sid = next()["result"]["sessionId"].as_str().unwrap().to_string();
        next(); // its commands
        say(json!({"jsonrpc": "2.0", "id": 3, "method": "session/prompt",
                   "params": {"sessionId": sid, "prompt": [{"type": "text", "text": "test it"}]}}));
        assert_eq!(next()["params"]["update"]["sessionUpdate"], "tool_call");
        let bg = |v: Value| { assert_eq!(v["method"], BACKGROUND, "{v}"); (v["params"]["tasks"].clone(), v["params"]["turn"].clone()) };
        assert_eq!(bg(next()), (json!([{"id": "b1", "kind": "local_bash", "description": "cargo test"}]), json!(false)),
                   "its command, and not Claude Code's own housekeeping");
        assert_eq!(next()["result"]["stopReason"], "end_turn");
        assert_eq!(bg(next()), (json!([]), json!(false)));
        assert_eq!(bg(next()), (json!([]), json!(true)), "a turn nobody prompted starts");
        assert_eq!(next()["params"]["update"]["content"]["text"], "Tests pass.");
        assert_eq!(bg(next()), (json!([]), json!(false)), "and ends with its result");
        drop(say);
        drop(in_w);
        server.join().unwrap();
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// A stand-in for Claude Code that, after its first turn, takes one by
    /// itself, and takes the next prompt into that turn: one `result` for both.
    const FAKE_MERGED: &str = r#"#!/bin/sh
n=0
while IFS= read -r l; do
  case "$l" in
    *'"subtype":"initialize"'*) echo '{"type":"control_response","response":{"subtype":"success","request_id":"midas-open","response":{}}}' ;;
    *'"type":"user"'*)
      n=$((n+1))
      if [ $n = 1 ]; then
        echo '{"type":"result","subtype":"success","stop_reason":"end_turn"}'
        echo '{"type":"stream_event","parent_tool_use_id":null,"event":{"type":"content_block_delta","delta":{"type":"text_delta","text":"Woke."}}}'
      else
        echo '{"type":"result","subtype":"success","stop_reason":"end_turn"}'
      fi ;;
  esac
done
"#;

    #[test]
    fn a_turn_it_woke_ends_with_the_result_of_a_prompt_taken_into_it() {
        let dir = std::env::temp_dir().join(format!("midas-acp-merged-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let fake = dir.join("claude");
        std::fs::write(&fake, FAKE_MERGED).unwrap();
        std::fs::set_permissions(&fake, std::fs::Permissions::from_mode(0o755)).unwrap();
        let (in_r, mut in_w) = std::io::pipe().unwrap();
        let (out_r, out_w) = std::io::pipe().unwrap();
        let claude = fake.to_string_lossy().to_string();
        let server = std::thread::spawn(move || serve(in_r, out_w, claude));
        let (tx, rx) = mpsc::channel::<Value>();
        std::thread::spawn(move || {
            for l in BufReader::new(out_r).lines().map_while(Result::ok) {
                let _ = tx.send(serde_json::from_str(&l).unwrap());
            }
        });
        let mut say = |v: Value| writeln!(in_w, "{v}").unwrap();
        let next = || rx.recv_timeout(Duration::from_secs(10)).expect("the adapter said nothing");

        say(json!({"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {"protocolVersion": 1}}));
        next();
        say(json!({"jsonrpc": "2.0", "id": 2, "method": "session/new", "params": {"cwd": dir, "mcpServers": []}}));
        let sid = next()["result"]["sessionId"].as_str().unwrap().to_string();
        next(); // its commands
        let prompt = |id: u64| json!({"jsonrpc": "2.0", "id": id, "method": "session/prompt",
                                      "params": {"sessionId": sid, "prompt": [{"type": "text", "text": "go on"}]}});
        say(prompt(3));
        assert_eq!(next()["result"]["stopReason"], "end_turn");
        let turn = |v: Value| { assert_eq!(v["method"], BACKGROUND, "{v}"); v["params"]["turn"].clone() };
        assert_eq!(turn(next()), json!(true), "a turn nobody prompted starts");
        assert_eq!(next()["params"]["update"]["content"]["text"], "Woke.");
        say(prompt(4));
        assert_eq!(turn(next()), json!(false), "its one result ends it, though a prompt waited for that result");
        assert_eq!(next()["id"], 4);
        drop(say);
        drop(in_w);
        server.join().unwrap();
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn an_edit_shows_as_its_diff_and_a_read_as_its_place() {
        let e = tool_call("t", "Edit", &json!({"file_path": "/x/a.rs", "old_string": "a", "new_string": "b"}));
        assert_eq!(e["content"], json!([{"type": "diff", "path": "/x/a.rs", "oldText": "a", "newText": "b"}]));
        assert_eq!(e["locations"][0]["path"], "/x/a.rs");
        let w = tool_call("t", "Write", &json!({"file_path": "/x/new.rs", "content": "fn x() {}"}));
        assert_eq!((w["content"][0]["oldText"].clone(), w["content"][0]["newText"].clone()), (Value::Null, json!("fn x() {}")), "a new file");
        let m = tool_call("t", "MultiEdit", &json!({"file_path": "/x/a.rs", "edits": [{"old_string": "1", "new_string": "2"}, {"old_string": "3", "new_string": "4"}]}));
        assert_eq!(m["content"].as_array().unwrap().len(), 2);
        let r = tool_call("t", "Read", &json!({"file_path": "/x/a.rs", "offset": 40}));
        assert_eq!((r["locations"][0]["line"].as_u64(), r.get("content")), (Some(40), None), "a read changes nothing");
        assert!(tool_call("t", "Bash", &json!({"command": "ls"})).get("locations").is_none());
        let c = commands(&json!([{"name": "review", "description": "Review it", "argumentHint": "[pr]"}, {"name": "", "description": "x"}]));
        assert_eq!(c, json!([{"name": "review", "description": "Review it", "input": {"hint": "[pr]"}}]));
    }

    #[test]
    fn a_session_had_before_is_listed_loaded_with_its_history_and_closed() {
        let _g = crate::tests::SERIAL.lock().unwrap_or_else(|p| p.into_inner());
        let dir = std::env::temp_dir().join(format!("midas-acp-load-{}", std::process::id()));
        let work = dir.join("work");
        std::fs::create_dir_all(&work).unwrap();
        // SAFETY: tests that set the environment hold SERIAL.
        unsafe { std::env::set_var("CLAUDE_CONFIG_DIR", dir.join("claude")) };
        let fake = dir.join("claude-bin");
        std::fs::write(&fake, FAKE).unwrap();
        std::fs::set_permissions(&fake, std::fs::Permissions::from_mode(0o755)).unwrap();
        let sid = "11111111-2222-4333-8444-555555555555";
        let t = transcript(&work.to_string_lossy(), sid);
        std::fs::create_dir_all(t.parent().unwrap()).unwrap();
        std::fs::write(&t, [
            json!({"type": "user", "sessionId": sid, "timestamp": "2026-10-22T07:00:00Z", "message": {"role": "user", "content": "Fix the sky"}}),
            json!({"type": "assistant", "sessionId": sid, "timestamp": "2026-10-22T07:00:05Z", "message": {"content": [
                {"type": "text", "text": "Looking."}, {"type": "tool_use", "id": "tu1", "name": "Read", "input": {"file_path": "/w/sky.rs"}}]}}),
            json!({"type": "user", "sessionId": sid, "timestamp": "2026-10-22T07:00:06Z", "message": {"content": [
                {"type": "tool_result", "tool_use_id": "tu1", "content": "fn sky() {}"}]}}),
        ].iter().map(|l| format!("{l}\n")).collect::<String>()).unwrap();
        assert!(t.to_string_lossy().contains("-work"), "named for its directory: {}", t.display());

        let (in_r, mut in_w) = std::io::pipe().unwrap();
        let (out_r, out_w) = std::io::pipe().unwrap();
        let claude = fake.to_string_lossy().to_string();
        let server = std::thread::spawn(move || serve(in_r, out_w, claude));
        let (tx, rx) = mpsc::channel::<Value>();
        std::thread::spawn(move || {
            for l in BufReader::new(out_r).lines().map_while(Result::ok) {
                let _ = tx.send(serde_json::from_str(&l).unwrap());
            }
        });
        let mut say = |v: Value| writeln!(in_w, "{v}").unwrap();
        let next = || rx.recv_timeout(Duration::from_secs(10)).expect("the adapter said nothing");
        say(json!({"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {"protocolVersion": 1}}));
        let caps = &next()["result"]["agentCapabilities"]["sessionCapabilities"];
        assert_eq!((&caps["list"], &caps["delete"]), (&json!({}), &json!({})));
        assert_eq!(caps["additionalDirectories"], json!({}));
        say(json!({"jsonrpc": "2.0", "id": 2, "method": "session/list", "params": {"cwd": work}}));
        let listed = next();
        assert_eq!(listed["result"]["sessions"], json!([{"sessionId": sid, "cwd": work, "title": "Fix the sky",
            "updatedAt": listed["result"]["sessions"][0]["updatedAt"]}]));

        say(json!({"jsonrpc": "2.0", "id": 3, "method": "session/load", "params": {"sessionId": sid, "cwd": work, "mcpServers": []}}));
        let mut told = Vec::new();
        let answer = loop {
            let v = next();
            if v.get("id").is_some() {
                break v;
            }
            told.push(v["params"]["update"]["sessionUpdate"].as_str().unwrap_or("").to_string());
        };
        assert_eq!(told, ["user_message_chunk", "agent_message_chunk", "tool_call", "tool_call_update"], "its history, before the answer");
        assert_eq!(answer["result"]["sessionId"], sid);
        assert_eq!(next()["params"]["update"]["sessionUpdate"], "available_commands_update");

        // Closed, it is gone; the adapter is not.
        say(json!({"jsonrpc": "2.0", "id": 4, "method": "session/close", "params": {"sessionId": sid}}));
        assert_eq!(next()["result"], json!({}));
        say(json!({"jsonrpc": "2.0", "id": 5, "method": "session/prompt", "params": {"sessionId": sid, "prompt": [{"type": "text", "text": "x"}]}}));
        assert!(next()["error"]["message"].as_str().unwrap().contains("no session"));
        say(json!({"jsonrpc": "2.0", "id": 6, "method": "session/list", "params": {"cwd": work}}));
        assert_eq!(next()["result"]["sessions"].as_array().unwrap().len(), 1, "still answering");

        // Deleted, it is no longer offered; its transcript is set aside, not lost.
        say(json!({"jsonrpc": "2.0", "id": 7, "method": "session/delete", "params": {"sessionId": sid}}));
        assert_eq!(next()["result"], json!({}));
        assert!(!t.exists() && t.with_extension("jsonl.deleted").is_file());
        say(json!({"jsonrpc": "2.0", "id": 8, "method": "session/list", "params": {"cwd": work}}));
        assert_eq!(next()["result"]["sessions"], json!([]));
        drop(say);
        drop(in_w);
        server.join().unwrap();
        unsafe { std::env::remove_var("CLAUDE_CONFIG_DIR") };
        let _ = std::fs::remove_dir_all(&dir);
    }
}