Cotton code
470 lines · 20.4 KB · RustRaw
//! `cotton-session-host` — four subcommands, and the only place in this crate//! that reads the environment or a clock.//!//! ```text//! cotton-session-host serve        # the daemon//! cotton-session-host hook <event> # a hook's JSON on stdin//! cotton-session-host statusline   # the status line's JSON on stdin//! cotton-session-host sample       # this machine, once, as JSON//! cotton-session-host restart      # restart a helper that is not this binary//! cotton-session-host sessions     # what this Mac is holding, as JSON//! cotton-session-host browser …    # the browser tool (`crate::browser`)//! ```use std::io::Read as _;use std::process::ExitCode;use std::sync::Arc;use std::time::Duration;use cotton_session_host::adopted::{Roots, CLAUDE_CONFIG_DIR_ENV, CODEX_HOME_ENV};use cotton_session_host::agents::PERMISSION_TIMEOUT_SECONDS;use cotton_session_host::binary;use cotton_session_host::clock::SystemClock;use cotton_session_host::data_dir::{admitted_data_dir, Flavor, Layout, DATA_DIR_ENV, FLAVOR_ENV};use cotton_session_host::login_env::{self, LoginEnv};use cotton_session_host::machine;use cotton_session_host::serve::Host;use cotton_session_host::{hook, statusline, HOST_VERSION};/// The environment variable a launch may shorten the permission wait with.////// Named here rather than inside the crate so the library stays free of the/// environment; the default is the design's ten minutes.const PERMISSION_TIMEOUT_ENV: &str = "COTTON_SESSION_HOST_PERMISSION_TIMEOUT_SECONDS";const USAGE: &str = "\cotton-session-host <command>  serve             own the pseudo-terminals and answer <dataDir>/session-host.sock  hook <event>      forward a hook's JSON (stdin) to the running host  statusline        forward the status line's JSON (stdin) and print one line  sample            print this machine's sample as JSON  restart           ask a running helper to restart onto THIS binary  sessions [--end]  print the live host-owned sessions as JSON; --end stops them  browser mcp       the browser tool's MCP server, as a session runs it (stdio)  browser open [url]  start Cotton's Chrome and show url in it — to sign it in  browser status    Cotton's Chrome and its profile, as JSON  --version         print this host's version";#[tokio::main]async fn main() -> ExitCode {    let args: Vec<String> = std::env::args().skip(1).collect();    // WHICH APP THIS HELPER SERVES, and so which folder is its own. A folder    // that is the other app's is refused before any subcommand reaches a    // socket or a file in it. A hook and the status line still exit 0 — an    // agent reads any other answer from a hook as an opinion about its turn,    // and this is no host to forward to, exactly as when none is listening.    // The environment first; when it says nothing, the app bundle this binary    // ships in (`Flavor::resolve` says why a launchd registration can be stale).    let flavor = Flavor::resolve(        std::env::var(FLAVOR_ENV).ok().as_deref(),        enclosing_bundle_id().as_deref(),    );    let home_dir = home();    let layout = match admitted_data_dir(        flavor,        &home_dir,        std::env::var(DATA_DIR_ENV).ok().as_deref(),    ) {        Ok(data_dir) => Layout::for_app(flavor, &home_dir, data_dir),        Err(refusal) => {            eprintln!("cotton-session-host: {refusal}");            return match args.first().map(String::as_str) {                Some("hook" | "statusline") => ExitCode::SUCCESS,                _ => ExitCode::FAILURE,            };        }    };    match args.first().map(String::as_str) {        Some("serve") => serve(layout, flavor).await,        Some("hook") => {            let Some(event) = args.get(1) else {                eprintln!("cotton-session-host hook needs the event name, e.g. `hook Stop`");                return ExitCode::from(2);            };            let outcome = hook::run(                event,                &layout.socket(),                &read_stdin(),                Duration::from_secs(permission_timeout_seconds()),            )            .await;            // Nothing to print is the documented silence: the agent reads it            // as "the hook had no opinion" and prompts in its own TUI.            if !outcome.stdout.is_empty() {                print!("{}", outcome.stdout);            }            ExitCode::SUCCESS        }        Some("statusline") => {            let said = statusline::run(&layout.socket(), &read_stdin()).await;            if !said.is_empty() {                println!("{said}");            }            ExitCode::SUCCESS        }        // **THE APP'S ONE QUESTION ABOUT THE HELPER**, asked by running the        // binary the app SHIPS. It knows what it is and it speaks the socket;        // Swift has to know neither (`crate::restart`).        Some("restart") => {            let bundled = cotton_session_host::restart::bundled(                std::env::current_exe().ok().as_deref(),            );            let (outcome, helper) =                cotton_session_host::restart::run(&layout.socket(), &bundled).await;            println!(                "{}",                cotton_session_host::restart::answer(&outcome, &helper, &bundled)            );            // ALWAYS 0. The verdict is the answer, and an exit code would be a            // second one the caller could read differently — a helper that is            // not answering is a fact this command reports, not a failure of            // this command.            ExitCode::SUCCESS        }        // **WHAT IS ALIVE, ASKED WITHOUT CHANGING ANYTHING.** The question        // the app and the install lane both have to ask BEFORE they do        // anything to this Mac's helper, because a live session outranks an        // update (`crate::sessions`, and the 2026-09-24 scar behind it).        Some("sessions") => {            let end = args.iter().skip(1).any(|arg| arg == "--end");            let report = cotton_session_host::sessions::run(&layout.socket(), end).await;            println!("{}", cotton_session_host::sessions::answer(&report));            // ALWAYS 0, for `restart`'s reason: the answer is the answer, and            // an exit code would be a second one the caller could read            // differently.            ExitCode::SUCCESS        }        Some("sample") => {            // The same environment `serve` detects in, so `sample` from a            // terminal and `sample` from the daemon answer the same thing —            // the difference between them is exactly the bug this capture            // exists for.            let env = login_environment();            let detected = machine::detect(&env);            // The executable THIS command is, so `sample` from a terminal and            // `sample` from the daemon report the same fingerprint when they            // are the same binary.            let watch = match std::env::current_exe() {                Ok(path) => binary::Watch::of(path),                Err(_) => binary::Watch::unwatched(),            };            // A REAL process table and one memory reading, so `sample` from a            // terminal prints the numbers the daemon publishes. This command            // owns no session, so there is no headroom to add: what it commits            // is exactly what the kernel says this Mac is using.            let rows = cotton_session_host::processes::snapshot();            let memory = machine::memory();            let measured = machine::Measured {                memory,                committed_gb: cotton_session_host::processes::committed_gb(                    &rows,                    &[],                    memory.used_gb(),                ),                session_peak_gb: None,                session_peak_samples: 0,            };            let accounts = machine::signed_in(&env, &detected);            let reading = machine::sample(                &SystemClock,                layout.own(),                0,                detected.versions,                accounts,                machine::HandedIn {                    binary: watch.report(),                    measured,                    facts: &machine::facts(layout.own()),                },            );            match serde_json::to_string_pretty(&reading) {                Ok(text) => {                    println!("{text}");                    ExitCode::SUCCESS                }                Err(error) => {                    eprintln!("cotton-session-host: the sample would not encode — {error}");                    ExitCode::FAILURE                }            }        }        // **THE BROWSER TOOL** (`crate::browser`). `mcp` is what a session's        // MCP configuration runs, so it writes NOTHING to stdout itself —        // stdout is the protocol, and it belongs to chrome-devtools-mcp.        Some("browser") => {            let home = home();            match args.get(1).map(String::as_str) {                Some("mcp") => cotton_session_host::browser::run_mcp(                    &layout,                    &home,                    &std::env::var("PATH").unwrap_or_default(),                ),                Some("open") => {                    cotton_session_host::browser::run_open(                        &layout,                        &home,                        args.get(2).map(String::as_str),                    )                    .await                }                // The broker a session's relay starts (`crate::browser_broker`);                // anything after `--` is passed on to Chrome.                Some("broker") => {                    let extra: Vec<String> = args                        .iter()                        .skip_while(|arg| arg.as_str() != "--")                        .skip(1)                        .cloned()                        .collect();                    let flag = args                        .iter()                        .take_while(|arg| arg.as_str() != "--")                        .position(|arg| arg == "--profile")                        .and_then(|at| args.get(at + 1))                        .map(String::as_str);                    match cotton_session_host::browser_broker::Profile::parse(&layout, flag) {                        Ok(held) => cotton_session_host::browser_broker::run_profile(&held, &home, &extra).await,                        Err(error) => {                            eprintln!("browser broker: {error}");                            ExitCode::from(2)                        }                    }                }                // The browser-session source's door to one account's profile                // (`browser_broker::profile_up`), run by the serving Mac's server.                Some("profile-up") => {                    let value = |name: &str| {                        args.iter().position(|arg| arg == name).and_then(|at| args.get(at + 1)).map(String::as_str)                    };                    let visible = args.iter().any(|arg| arg == "--visible");                    let host = std::env::current_exe().unwrap_or_default();                    let up = match cotton_session_host::browser_broker::Profile::parse(&layout, value("--profile")) {                        Ok(held) => {                            cotton_session_host::browser_broker::profile_up(&layout, &held, &home, &host, visible, value("--url"))                                .await                        }                        Err(error) => Err(error),                    };                    match up {                        Ok(socket) => {                            println!("{}", socket.display());                            ExitCode::SUCCESS                        }                        Err(error) => {                            eprintln!("browser profile-up: {error}");                            ExitCode::FAILURE                        }                    }                }                // Whether an account's profile is signed in to its site, by                // the presence of the site's session cookie: `yes` or `no`.                Some("has-session") => {                    let value = |name: &str| {                        args.iter().position(|arg| arg == name).and_then(|at| args.get(at + 1)).map(String::as_str)                    };                    let host = std::env::current_exe().unwrap_or_default();                    let answer = match (                        cotton_session_host::browser_broker::Profile::parse(&layout, value("--profile")),                        value("--domain"),                        value("--cookie"),                    ) {                        (Ok(held), Some(domain), Some(cookie)) if held.account.is_some() => {                            cotton_session_host::browser_broker::has_session(&layout, &held, &home, &host, domain, cookie).await                        }                        (Err(error), _, _) => Err(error),                        _ => Err("has-session takes --profile <site>/<account> --domain <host> --cookie <name>".into()),                    };                    match answer {                        Ok(held) => {                            println!("{}", if held { "yes" } else { "no" });                            ExitCode::SUCCESS                        }                        Err(error) => {                            eprintln!("browser has-session: {error}");                            ExitCode::FAILURE                        }                    }                }                Some("status") => {                    let status = cotton_session_host::browser::status(&layout, &home);                    println!("{status:#}");                    ExitCode::SUCCESS                }                _ => {                    eprintln!("cotton-session-host browser needs `mcp`, `open [url]`, `status`, `broker`, `profile-up` or `has-session`");                    ExitCode::from(2)                }            }        }        Some("--version") | Some("-V") => {            println!("{HOST_VERSION}");            ExitCode::SUCCESS        }        Some("--help") | Some("-h") | None => {            print!("{USAGE}");            ExitCode::SUCCESS        }        Some(other) => {            eprintln!("cotton-session-host: there is no `{other}` command\n\n{USAGE}");            ExitCode::from(2)        }    }}async fn serve(layout: Layout, flavor: Flavor) -> ExitCode {    // BEFORE anything that could refuse, because the refusal is the thing a    // person needs to read. Under launchd there is no terminal at all: the    // plist names no `StandardErrorPath` (see `log.rs` for why it cannot), so    // until this runs a failed start is a process that vanished with nothing    // written down anywhere.    redirect_stderr_to_the_log(&layout);    let binary = match std::env::current_exe() {        Ok(path) => path.display().to_string(),        Err(error) => {            // Every hook command the adapters write is this path. A host that            // could not name itself would write hooks that reach nothing, so            // it refuses to start rather than starting broken.            eprintln!("cotton-session-host: this host cannot name its own binary — {error}");            return ExitCode::FAILURE;        }    };    // THE LOGIN ENVIRONMENT, once, before anything is detected or spawned.    // Under launchd this process has `PATH=/usr/bin:/bin:/usr/sbin:/sbin` and    // nothing else; `login_env` says what that cost and how it is repaired.    let login = login_environment();    eprintln!("cotton-session-host: {}", login.summary());    let host = match Host::new(layout, Arc::new(SystemClock), binary, flavor) {        Ok(host) => host.in_login_env(login),        Err(error) => {            eprintln!("cotton-session-host: {error}");            return ExitCode::FAILURE;        }    };    // ADOPTED SESSIONS: the transcript directories, resolved HERE because this    // is the one place in this crate that reads the process. A login with no    // home directory has none of them to watch, and adoption stays off rather    // than walking the root of the filesystem.    let home = home();    let host = Arc::new(if home.is_empty() {        host    } else {        host.watching(Roots::resolve(            &home,            std::env::var(CLAUDE_CONFIG_DIR_ENV).ok().as_deref(),            std::env::var(CODEX_HOME_ENV).ok().as_deref(),        ))    });    let listener = match host.bind().await {        Ok(listener) => listener,        Err(error) => {            eprintln!("cotton-session-host: {error}");            return ExitCode::FAILURE;        }    };    if let Err(error) = host.run(listener).await {        eprintln!("cotton-session-host: {error}");        return ExitCode::FAILURE;    }    ExitCode::SUCCESS}/// Point this process's own stderr at `<dataDir>/session-host.log`.////// `dup2` rather than a logging façade: everything this host says it says with/// `eprintln!`, and a panic says its message the same way. Redirecting the/// DESCRIPTOR catches all of it, including the lines nothing here wrote.////// A failure is reported and survived. The host's job is to hold a person's/// terminals; a disk that will not take a log file is not a reason to refuse/// them, and the sentence still reaches launchd's own log.fn redirect_stderr_to_the_log(layout: &Layout) {    if let Err(error) = std::fs::create_dir_all(layout.own()) {        eprintln!(            "cotton-session-host: no folder for the log at {} — {error}",            layout.own().display()        );        return;    }    let path = layout.log();    let file = match cotton_session_host::log::open(&path) {        Ok(file) => file,        Err(error) => {            eprintln!(                "cotton-session-host: the log at {} could not be opened — {error}",                path.display()            );            return;        }    };    // SAFETY: `file` is an open descriptor this process owns, and `dup2` on    // fd 2 is the documented way to replace stderr. The `File` is leaked    // deliberately — closing it would close the descriptor `dup2` just made a    // copy of the far end of, for the lifetime of a daemon that never stops    // writing.    let ok = unsafe { libc::dup2(std::os::unix::io::AsRawFd::as_raw_fd(&file), libc::STDERR_FILENO) };    if ok < 0 {        eprintln!("cotton-session-host: stderr could not be pointed at {}", path.display());        return;    }    std::mem::forget(file);    eprintln!(        "cotton-session-host {HOST_VERSION}: serving {} — log at {}",        layout.own().display(),        path.display()    );}fn permission_timeout_seconds() -> u64 {    match std::env::var(PERMISSION_TIMEOUT_ENV) {        Ok(said) => said.trim().parse().unwrap_or(PERMISSION_TIMEOUT_SECONDS),        Err(_) => PERMISSION_TIMEOUT_SECONDS,    }}fn read_stdin() -> String {    let mut text = String::new();    // A hook whose stdin could not be read still has an agent waiting on it;    // what it forwards is what it got.    let _ = std::io::stdin().read_to_string(&mut text);    text}/// The person's login-shell environment, captured once.////// THE ONLY READER OF THE PROCESS ENVIRONMENT for this, kept here with the/// other three because `main.rs` is the one place in this crate that reads it.fn login_environment() -> LoginEnv {    let home = home();    let shell = login_env::choose_shell(        std::env::var("SHELL").ok().as_deref(),        login_env::directory_shell().as_deref(),    );    login_env::capture(        &shell,        &home,        std::env::vars().collect(),        login_env::CAPTURE_TIMEOUT,    )}/// The identifier of the app bundle this binary sits in —/// `<App>.app/Contents/Helpers/cotton-session-host` reads/// `<App>.app/Contents/Info.plist`. `None` outside a bundle (a `cargo` build).fn enclosing_bundle_id() -> Option<String> {    let exe = std::env::current_exe().ok()?;    let plist = exe.parent()?.parent()?.join("Info.plist");    let text = std::fs::read_to_string(plist).ok()?;    cotton_session_host::data_dir::bundle_identifier(&text).map(str::to_string)}fn home() -> String {    // The one read of HOME in this crate. A process with none is a process    // with no data directory, and it says so rather than writing into `/`.    std::env::var("HOME").unwrap_or_else(|_| {        eprintln!("cotton-session-host: HOME is not set, so there is no data folder to find — set {DATA_DIR_ENV}");        String::new()    })}