Cotton code
139 lines · 5.8 KB · RustRaw
//! Utility terminals: a command in a pseudo-terminal, and nothing else.//!//! **WHY THIS EXISTS.** A person who has just installed CottonDB for Mac has//! no coding agent on it, may have no `git`, and has never signed either agent//! in. Every one of those is a line in a terminal — and the whole promise of//! the Code tool is that they never open Terminal.app//! ([i-shouldn-t-need-terminal-app-on-my-mac-the-cotton-mac-app-hosts]). So//! the app asks THIS helper to run the line, in the person's own login//! environment, and draws the bytes in the same terminal view it draws a//! session with.//!//! **A utility is NOT a session, and this module is where that is enforced.**//! It gets://!//!   * no hook files and no `--settings` — nothing is registered, so no hook//!     ever fires for it;//!   * no entry in `sessions/index.json`, so a restart of the daemon does not//!     stamp one as an ended session and `list` never answers for one;//!   * no place in `sessions_running`, which is the number the dispatcher//!     places work by;//!   * no transcript adoption — it writes none;//!   * and an id that says so, so nothing downstream can mistake one for a//!     session even by accident.//!//! **Cotton still never touches a credential.** A sign-in utility runs the//! agent's own `claude` / `codex`, whose browser flow is between the person//! and their provider; what crosses this process is the pseudo-terminal's//! bytes on their way to a screen, exactly as for a session.//!//! **One at a time per purpose.** Two installers writing one directory is a//! failure nobody could read afterwards, and two sign-ins are two browser//! tabs fighting over one callback. The rule is kept on the `purpose`, which//! is also the scrollback's file name — so the same string is the key, the//! folder and the sentence, and they cannot disagree./// What every utility id starts with.////// The namespace is the whole point: `cotton-client`'s mirror, the executor/// and every row-writing path key on a session id, and the one guarantee that/// makes a utility safe to run through the same socket is that its id can/// never be one of those.pub const UTILITY_PREFIX: &str = "util:";/// The terminal a utility gets before a viewer has measured one.////// Wide enough that `curl | bash` and `git clone`'s progress lines do not wrap/// into nonsense in the scrollback a viewer replays. An attached view resizes/// it to its own window immediately, exactly as it does a session's.pub const UTILITY_COLS: u16 = 100;/// The rows a utility gets before a viewer has measured one.pub const UTILITY_ROWS: u16 = 30;/// The most a purpose may be.pub const PURPOSE_MAX: usize = 64;/// Is this id a utility's?pub fn is_utility(id: &str) -> bool {    id.starts_with(UTILITY_PREFIX)}/// Why a purpose is not one this host will run a terminal under, or `None`.////// It is a DIRECTORY NAME as well as a key, so the grammar is the one that/// cannot produce a path: letters, digits, `-` and `_`. A refusal names the/// string rather than repairing it — a purpose quietly rewritten is a/// one-at-a-time rule kept on a key the caller does not know it has.pub fn purpose_refusal(purpose: &str) -> Option<String> {    if purpose.is_empty() {        return Some(            "a utility terminal has to say what it is for — its purpose is the key the \             one-at-a-time rule is kept on"                .to_string(),        );    }    if purpose.len() > PURPOSE_MAX {        return Some(format!(            "`{purpose}` is {} characters and a purpose is at most {PURPOSE_MAX}",            purpose.len()        ));    }    if !purpose        .chars()        .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')    {        return Some(format!(            "`{purpose}` is not a purpose this host will run — a purpose is letters, digits, \             `-` and `_`, because it is also the name of the folder its scrollback is kept in"        ));    }    None}/// Why an argv is not one this host will run, or `None`.pub fn argv_refusal(argv: &[String]) -> Option<String> {    match argv.first() {        None => Some("a utility terminal names no program to run".to_string()),        Some(program) if program.trim().is_empty() => {            Some("a utility terminal's program is an empty string".to_string())        }        Some(_) => None,    }}/// The id of the `n`th utility this host has run for `purpose`.////// The pid is in it because the helper outlives the app and an app holding an/// id from before a restart must not be handed a different terminal under the/// same name. No uuid crate for the same reason/// [`crate::serve::Host::mint_session_id`] takes none: this id is unique on/// one Mac inside one helper, which is the whole of its scope.pub fn utility_id(purpose: &str, pid: u32, n: u64) -> String {    format!("{UTILITY_PREFIX}{purpose}:{pid}-{n}")}/// The refusal a second utility of a purpose earns while the first is running.pub fn busy_refusal(purpose: &str, running: &str) -> String {    format!(        "a {purpose} terminal is already running on this Mac as {running} — watch that one, or \         stop it, rather than starting a second"    )}/// The refusal a program that is not on the person's PATH earns.////// **NAMED, never guessed at.** The helper resolves `argv[0]` against the/// captured login PATH — the same one a session runs on — so a program this/// cannot find is a program the person cannot run either, and the sentence/// says which one rather than letting the terminal open and immediately die/// with a shell's own wording.pub fn no_program_refusal(program: &str) -> String {    format!(        "`{program}` is not on this Mac's PATH, so there is nothing to run — install it first"    )}#[cfg(test)]#[path = "utility_tests.rs"]mod utility_tests;