Cotton code
482 lines · 19.9 KB · RustRaw
//! Claude Code, spawned unmodified.//!//! Facts this adapter relies on, all of them the agent's own documented//! surface (Claude Code 2.1.274)://!//! - `--settings <file>` takes a PATH, and the hooks in it **merge** with the//!   person's own `settings.json` in `~/.claude` rather than replacing them. That is//!   the whole reason the host never edits the person's settings: a crashed//!   host leaves no hooks behind, because the file it wrote is inside the//!   session's own directory and nothing else reads it.//! - `--session-id <uuid>` makes the agent's session id the host's, so one id//!   names the session everywhere.//! - `--dangerously-skip-permissions` is bypass mode. In bypass mode no//!   `PermissionRequest` hook fires at all, which is why the default costs the//!   phone nothing.//! - Hook stdin carries `session_id`, `transcript_path`, `cwd`,//!   `hook_event_name` and `permission_mode`. A `PostToolUse` adds//!   `tool_name`, `tool_input` and the tool's result; its matcher is a REGEX//!   over the tool name, which is why the task-list arm names one tool exactly//!   and no other tool's call reaches this host.//! - The status line's stdin carries the account's windows as//!   `rate_limits.five_hour.{used_percentage,resets_at}` and//!   `rate_limits.seven_day.{…}` on a subscription that has them, and nothing//!   at all before the session's first API response.//! - The transcript is `~/.claude/projects/<slug>/<session-id>.jsonl`, one//!   JSON object per line, `type` `user` or `assistant` with//!   `message.content` an array of typed blocks.//!//! WHAT IS DELIBERATELY NOT USED: `--name`. It is not in this version's//! `--help`, and a flag the binary refuses is a launch that never starts. The//! session's name is Cotton's, on the launch row.use std::collections::BTreeMap;use serde_json::json;use super::{join_text_blocks, Adapter, AdoptedMeta, HookFile, Launch, NOTIFICATION_MATCHER,            PERMISSION_TIMEOUT_SECONDS};use crate::protocol::{    Decision, PermissionMode, Provider, SignedIn, Tool, Turn, TurnRole, Usage,};use crate::pty::SpawnPlan;use crate::tasks::{TASKS_EVENT, TASKS_TOOL};/// The adapter.#[derive(Debug, Clone, Copy, Default)]pub struct Claude;/// The settings file written for one launch.pub const SETTINGS_FILE: &str = "claude-settings.json";/// The MCP servers file written for one launch — the browser tool's, when/// the Mac offers it.////// `--mcp-config` ADDS these to the person's own servers (only/// `--strict-mcp-config` would replace them, and it is never passed), and/// like the settings file it lives in the session's own directory.pub const MCP_FILE: &str = "claude-mcp.json";/// The `system` record's subtype that means this session is over.////// The ONE marker an adopted Claude transcript can be read as ended by. A/// transcript that never carries it leaves its session `idle` — see/// [`super::Adapter::transcript_ended`], and `crates/cotton-session-host/src/adopted.rs`/// for what the phone shows then.pub const END_SUBTYPE: &str = "session_end";impl Claude {    /// Where this launch's settings file goes.    pub fn settings_path(launch: &Launch) -> String {        format!("{}/{SETTINGS_FILE}", launch.launch_dir)    }    /// Where this launch's MCP servers file goes.    pub fn mcp_path(launch: &Launch) -> String {        format!("{}/{MCP_FILE}", launch.launch_dir)    }    /// The `--mcp-config` file's contents for a Mac that offers the browser.    pub fn mcp_config(launch: &Launch, offer: &crate::browser::Offer) -> serde_json::Value {        let server = crate::browser::mcp_server(&launch.host_binary, offer);        json!({            "mcpServers": {                (server.name): {                    "type": "stdio",                    "command": server.command,                    "args": server.args,                    "env": server.env                }            }        })    }    /// The directory slug Claude files a transcript under.    ///    /// The working directory with every `/` turned into `-`, so    /// `/Users/x/Code/repo` is `-Users-x-Code-repo`. Pinned by a test because    /// it is the agent's own convention and nothing in this crate can make it    /// true.    pub fn transcript_slug(cwd: &str) -> String {        cwd.replace('/', "-")    }}impl Adapter for Claude {    fn tool(&self) -> Tool {        Tool::Claude    }    fn spawn_plan(&self, launch: &Launch) -> SpawnPlan {        // **`--resume` REPLACES `--session-id`, it does not join it.** One        // says "be this new session", the other "continue that one", and an        // agent handed both has been told two contradictory things. A resumed        // session keeps the id it already had, so the row addressing it over        // the socket goes on addressing it.        let mut argv = match launch.resume.as_deref() {            Some(id) => vec!["claude".to_string(), "--resume".to_string(), id.to_string()],            None => vec![                "claude".to_string(),                "--session-id".to_string(),                launch.session_id.clone(),            ],        };        // **`--mcp-config` TAKES A LIST** (`<configs...>`), so whatever        // follows its file is read as another config until the next flag. It        // goes BEFORE `--settings` for exactly that reason: a prompt in        // `argv_extras` placed after it would be swallowed as a file name.        if launch.browser.is_some() {            argv.extend(["--mcp-config".to_string(), Self::mcp_path(launch)]);        }        argv.extend(["--settings".to_string(), Self::settings_path(launch)]);        if launch.permission_mode == PermissionMode::Bypass {            argv.push("--dangerously-skip-permissions".to_string());        }        argv.extend(launch.argv_extras.iter().cloned());        let mut env = launch.env.clone();        env.extend(quiet_env());        for name in NEVER_SET {            env.remove(name);        }        SpawnPlan {            argv,            env,            cwd: launch.cwd.clone(),            cols: launch.cols,            rows: launch.rows,        }    }    fn hook_files(&self, launch: &Launch) -> Vec<HookFile> {        let command = |event: &str| format!("{} hook {event}", launch.host_binary);        let plain = |event: &str, timeout: u64| {            json!([{ "hooks": [{ "type": "command", "command": command(event), "timeout": timeout }] }])        };        let settings = json!({            "hooks": {                "SessionStart": plain("SessionStart", 10),                // A turn began. The hook prints NOTHING — this agent reads a                // prompt hook's stdout into the turn as context, and the host                // has nothing to say to the agent, only to the card.                "UserPromptSubmit": plain("UserPromptSubmit", 10),                "Stop": plain("Stop", 10),                "SessionEnd": plain("SessionEnd", 10),                // The session's task list, every time the agent rewrites it.                // MATCHED TO ONE TOOL NAME: a bare `PostToolUse` would be a                // socket round trip after every file this session read.                TASKS_EVENT: json!([{                    "matcher": TASKS_TOOL,                    "hooks": [{                        "type": "command",                        "command": command(TASKS_EVENT),                        "timeout": 10                    }]                }]),                "Notification": json!([{                    "matcher": NOTIFICATION_MATCHER,                    "hooks": [{                        "type": "command",                        "command": command("Notification"),                        "timeout": 10                    }]                }]),                // The ONE hook that blocks: its stdout IS the decision, and it                // waits for the phone. Its timeout is the agent's outer bound                // on ours — a second longer, so the host's own timeout is what                // ends the wait and the fallback is the host's written one.                "PermissionRequest": json!([{                    "hooks": [{                        "type": "command",                        "command": command("PermissionRequest"),                        "timeout": PERMISSION_TIMEOUT_SECONDS + 1                    }]                }])            },            "statusLine": {                "type": "command",                "command": format!("{} statusline", launch.host_binary)            }        });        let mut files = vec![HookFile {            path: Self::settings_path(launch),            contents: format!(                "{}\n",                serde_json::to_string_pretty(&settings)                    .expect("a settings object this crate built encodes")            ),        }];        if let Some(offer) = &launch.browser {            files.push(HookFile {                path: Self::mcp_path(launch),                contents: format!(                    "{}\n",                    serde_json::to_string_pretty(&Self::mcp_config(launch, offer))                        .expect("an MCP config this crate built encodes")                ),            });        }        files    }    fn read_last_turn(&self, transcript: &str) -> Option<Turn> {        // **THE AGENT'S OWN LAST WORD WINS.** A transcript does not end on the        // assistant: Claude writes a `user` record for every tool result and        // for its own hook output, so the last readable record is very often        // one of those or — measured on a real session, 2026-09-19 — the        // person's own prompt. Taking it made `cotton_sessions.last_line` read        // back the words the person had just typed, on a card whose whole job        // is to say what the session said.        //        // A user record is STILL a turn, and it is the answer when there is no        // assistant one — a session that has been asked something and has not        // answered yet has a last turn, and it is the question.        let mut first_user: Option<Turn> = None;        for line in transcript.lines().rev() {            let Some(turn) = self.turn_from_record(line) else {                continue;            };            match turn.role {                TurnRole::Assistant => return Some(turn),                TurnRole::User => first_user = first_user.or(Some(turn)),            }        }        first_user    }    fn read_adopted_meta(&self, head: &str) -> Option<AdoptedMeta> {        // Claude stamps EVERY record with `sessionId`, `cwd` and `timestamp`,        // so the first record that carries each one answers — and a head with        // no `sessionId` anywhere in it is not a transcript this adapter can        // name a session from.        let mut session_id = None;        let mut cwd = None;        let mut started_at = None;        for line in head.lines() {            let Ok(record) = serde_json::from_str::<serde_json::Value>(line) else {                continue;            };            let field = |name: &str| {                record                    .get(name)                    .and_then(serde_json::Value::as_str)                    .filter(|value| !value.trim().is_empty())                    .map(str::to_string)            };            session_id = session_id.or_else(|| field("sessionId"));            cwd = cwd.or_else(|| field("cwd"));            started_at = started_at.or_else(|| field("timestamp"));            if session_id.is_some() && cwd.is_some() && started_at.is_some() {                break;            }        }        Some(AdoptedMeta {            session_id: session_id?,            cwd,            started_at,        })    }    fn transcript_ended(&self, tail: &str) -> bool {        tail.lines().rev().any(|line| {            let Ok(record) = serde_json::from_str::<serde_json::Value>(line) else {                return false;            };            record.get("type").and_then(serde_json::Value::as_str) == Some("system")                && record.get("subtype").and_then(serde_json::Value::as_str) == Some(END_SUBTYPE)        })    }    fn read_usage(&self, event: &serde_json::Value, _now: &str) -> Option<Usage> {        // Claude reports an INSTANT (`resets_at`), so the arrival time is        // nothing this parser needs. See [`reset_instant`] for its two        // spellings.        let limits = event.get("rate_limits")?;        let window = |name: &str| {            let window = limits.get(name);            let pct = window                .and_then(|window| window.get("used_percentage"))                .and_then(serde_json::Value::as_f64);            let resets = window                .and_then(|window| window.get("resets_at"))                .and_then(reset_instant);            (pct, resets)        };        let (five_hour_pct, five_hour_resets_at) = window("five_hour");        let (weekly_pct, weekly_resets_at) = window("seven_day");        if five_hour_pct.is_none() && weekly_pct.is_none() {            // `rate_limits` present but empty is not a reading. Answering            // `Some` here would publish two zeroes as "nothing used".            return None;        }        Some(Usage {            provider: Provider::Anthropic,            email: account_email(event),            five_hour_pct,            five_hour_resets_at,            weekly_pct,            weekly_resets_at,        })    }    fn account_argv(&self) -> Option<&'static [&'static str]> {        // `claude auth status` prints one JSON object and exits 0 signed in,        // 1 signed out. It reads the agent's own login and prints no token.        Some(&["auth", "status"])    }    fn read_account(&self, said: &str) -> Option<SignedIn> {        let answer: serde_json::Value = serde_json::from_str(said.trim()).ok()?;        // `loggedIn: false` still prints an object, so the flag is read and        // not inferred from the exit code or from a field being present.        if answer.get("loggedIn").and_then(serde_json::Value::as_bool) != Some(true) {            return None;        }        let email = answer            .get("email")            .and_then(serde_json::Value::as_str)            .map(str::trim)            .filter(|email| !email.is_empty())?;        Some(SignedIn {            provider: Provider::Anthropic,            email: email.to_string(),            plan: answer                .get("subscriptionType")                .and_then(serde_json::Value::as_str)                .map(str::trim)                .filter(|plan| !plan.is_empty())                .map(str::to_string),        })    }    fn permission_reply(&self, decision: Decision) -> serde_json::Value {        let (verdict, reason) = match decision {            Decision::Allow => ("allow", "allowed from Cotton on the owner's phone"),            // The session-wide form is the agent's own, and this host does not            // have it: what it can say is "allow", and the phone's            // `allowSession` is Cotton's own record that it need not ask            // again. Spelled out rather than silently collapsed.            Decision::AllowSession => (                "allow",                "allowed from Cotton on the owner's phone, for this session",            ),            Decision::Deny => ("deny", "declined from Cotton on the owner's phone"),        };        json!({            "hookSpecificOutput": {                "hookEventName": "PermissionRequest",                "permissionDecision": verdict,                "permissionDecisionReason": reason            }        })    }}/// A window's `resets_at`, as the RFC 3339 UTC instant every stamp in the file/// takes.////// **Claude Code sends a NUMBER — epoch seconds** — on its status line/// (`"resets_at": 1790000000`). This read accepted only a string until 30 Sep/// 2026, so every real reading arrived with no reset time at all and the phone/// could not say when a window refills. A string is still accepted: an RFC 3339/// instant (normalised to UTC), or the same epoch seconds written as text. A/// value that is neither is no reset time rather than a guess.fn reset_instant(value: &serde_json::Value) -> Option<String> {    let epoch = match value {        serde_json::Value::Number(number) => number            .as_i64()            .or_else(|| number.as_f64().map(|seconds| seconds.floor() as i64))?,        serde_json::Value::String(text) => {            let text = text.trim();            if let Ok(at) = chrono::DateTime::parse_from_rfc3339(text) {                return Some(                    at.with_timezone(&chrono::Utc)                        .to_rfc3339_opts(chrono::SecondsFormat::Secs, true),                );            }            text.parse::<i64>().ok()?        }        _ => return None,    };    chrono::DateTime::from_timestamp(epoch, 0)        .map(|at| at.to_rfc3339_opts(chrono::SecondsFormat::Secs, true))}/// The signed-in address, when the forwarded event carries one.////// It is not on every payload, so this answers `None` rather than a placeholder/// — the host then files the reading under the login the agent itself last/// reported ([`super::Adapter::read_account`]), and a made-up address here/// would be a second account in the person's list.fn account_email(event: &serde_json::Value) -> Option<String> {    for path in [        ["account", "email"].as_slice(),        ["account", "email_address"].as_slice(),        ["oauth_account", "email_address"].as_slice(),    ] {        let mut here = event;        let mut found = true;        for step in path {            match here.get(step) {                Some(next) => here = next,                None => {                    found = false;                    break;                }            }        }        if found {            if let Some(email) = here.as_str() {                return Some(email.to_string());            }        }    }    None}/// Claude's own environment, for a caller that wants to see it without/// building a plan.////// A session inside a hosted terminal must not restart itself under the/// person, so the updater is off. **The traffic switches stay ON.**/// `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC` (and `DISABLE_TELEMETRY`) also/// turn off the feature flags the agent reads, and with them go the Monitor/// tool and every claude.ai connector,/// Cotton's among them (measured 14 Oct 2026, Claude Code 2.1.300: 104 tools/// with them on, 21 with the switch set). Whatever this map sets is the/// agent's own switch; [`NEVER_SET`] are the ones it must not.pub fn quiet_env() -> BTreeMap<String, String> {    BTreeMap::from([("DISABLE_AUTOUPDATER".to_string(), "1".to_string())])}/// Switches a hosted Claude Code session is never given, because each takes/// a tool the session needs away (see [`quiet_env`]).pub const NEVER_SET: [&str; 2] = ["CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC", "DISABLE_TELEMETRY"];impl Claude {    /// One transcript record, as a turn, or `None` when it is not one.    ///    /// Anything that is neither a `user` nor an `assistant` record, and any    /// record whose content holds no text (a tool use, a tool result, a bare    /// thinking block), is NOT a turn rather than an empty one.    fn turn_from_record(&self, line: &str) -> Option<Turn> {        let record: serde_json::Value = serde_json::from_str(line).ok()?;        let role = match record.get("type").and_then(serde_json::Value::as_str)? {            "assistant" => TurnRole::Assistant,            "user" => TurnRole::User,            _ => return None,        };        let content = record.get("message")?.get("content")?;        // A string content block is what an older record shape used; an array        // of typed blocks is the current one. Both are read, and anything else        // is NOT a turn rather than an empty one.        let text = match content {            serde_json::Value::String(text) if !text.trim().is_empty() => text.clone(),            other => join_text_blocks(other, &["text"])?,        };        Some(Turn { role, text })    }}