Cotton code
362 lines · 15.0 KB · RustRaw
//! Codex, spawned unmodified.//!//! ## Where this launch's hooks come from, and why//!//! **`-c hooks=<inline TOML table>`, on the command line, for this launch//! alone.** Codex's `-c key=value` overrides take a TOML value, and `hooks` is//! an ordinary configuration table (`[hooks.<Event>]`, each entry//! `{matcher?, hooks=[{type="command", command="…", timeout=N}]}`), so the//! whole table travels as one argument and nothing on disk changes.//!//! The three routes that were refused, each for a reason that is not taste://!//! 1. **`~/.codex/config.toml`** is the person's own file. A host that wrote//!    hooks into it would leave them there the day it crashed, and every//!    `codex` the person ran by hand afterwards would try to reach a socket//!    that is not listening.//! 2. **`<repo>/.codex/hooks.json`** is the person's repository. It outlives//!    the session, it would be committed by accident, and a project layer's//!    hooks load only when that layer is trusted — a state the host cannot//!    grant and nobody is at the keyboard to answer.//! 3. **A `CODEX_HOME` overlay** is the tidy-looking one and is the trap://!    `CODEX_HOME` is where `auth.json` lives. An overlay either COPIES the//!    person's credential — which this host must never touch — or symlinks it,//!    and a symlink survives exactly until Codex refreshes the token by//!    writing beside and renaming, which replaces the link with a file and//!    silently forks the login. Cotton never touches a credential; the login//!    is the agent's own, on this Mac.//!//! `--dangerously-bypass-hook-trust` goes with it: a non-managed hook is//! trust-gated, and the gate is an interactive review. The hooks being waved//! past are the ones this host wrote, on this Mac, for this launch — and a//! session that stopped on a trust prompt would look, from the phone, exactly//! like a session that hung.//!//! **`codex` is not installed on the Mac this was written on.** Nothing here//! has been run against the real binary: the adapter is a pure function and it//! is held entirely by `tests/fixtures/codex-*`, which are hand-written from//! the published formats. That is stated here rather than discovered later.//!//! ## The rest of the surface//!//! - `-C <cwd>` is the working directory; `-m <model>` the model, which//!   arrives in `argv_extras` from the launch row.//! - `--dangerously-bypass-approvals-and-sandbox` is bypass mode. (`--full-auto`//!   is deprecated and is not used.)//! - `-c check_for_update_on_startup=false` keeps an embedded run quiet.//! - Codex mints its OWN session id. The host learns it from the `SessionStart`//!   hook's `session_id`, records it as the session's `agent_session_id`, and//!   that is what `codex resume <id>` later takes.//! - The rollout file is `~/.codex/sessions/YYYY/MM/DD/rollout-*.jsonl`, one//!   `{timestamp, type, payload}` record per line.use super::{    join_text_blocks, Adapter, AdoptedMeta, HookFile, Launch, HOOK_EVENTS, NOTIFICATION_MATCHER,    PERMISSION_TIMEOUT_SECONDS,};use crate::protocol::{    Decision, PermissionMode, Provider, SignedIn, Tool, Turn, TurnRole, Usage,};use crate::pty::SpawnPlan;use serde_json::json;/// The adapter.#[derive(Debug, Clone, Copy, Default)]pub struct Codex;/// The payload types that mean an adopted Codex session is over.////// Two, because Codex writes one on an orderly exit and one when the process/// is shutting down. Neither is inferred — see/// [`super::Adapter::transcript_ended`].pub const END_PAYLOAD_TYPES: [&str; 2] = ["session_end", "shutdown_complete"];/// How long each non-blocking hook gets, in seconds.const QUICK_HOOK_TIMEOUT: u64 = 10;impl Codex {    /// The `hooks` table, as the TOML value `-c` takes.    ///    /// Public because `tests/adapters.rs` compares it with a fixture: this    /// string is the whole of the injection route, and a change to it is a    /// change to how every Codex session reports itself.    pub fn hooks_override(launch: &Launch) -> String {        let command = |event: &str| format!("{} hook {event}", launch.host_binary);        let entries = HOOK_EVENTS            .iter()            .map(|event| {                let timeout = if *event == "PermissionRequest" {                    // A second past the host's own wait, so the wait that ends                    // first is the one whose fallback is written down.                    PERMISSION_TIMEOUT_SECONDS + 1                } else {                    QUICK_HOOK_TIMEOUT                };                let matcher = if *event == "Notification" {                    format!("matcher={},", toml_string(NOTIFICATION_MATCHER))                } else {                    String::new()                };                format!(                    "{event}=[{{{matcher}hooks=[{{type=\"command\",command={},timeout={timeout}}}]}}]",                    toml_string(&command(event))                )            })            .collect::<Vec<_>>()            .join(",");        format!("hooks={{{entries}}}")    }    /// The browser tool as the `-c` override Codex takes: one    /// `mcp_servers.<name>` inline table, for this launch alone — the same    /// route as the hooks, for the same reasons (this module's note).    pub fn browser_override(launch: &Launch, offer: &crate::browser::Offer) -> String {        let server = crate::browser::mcp_server(&launch.host_binary, offer);        let args = server            .args            .iter()            .map(|arg| toml_string(arg))            .collect::<Vec<_>>()            .join(",");        let env = server            .env            .iter()            .map(|(key, value)| format!("{key}={}", toml_string(value)))            .collect::<Vec<_>>()            .join(",");        format!(            "mcp_servers.{}={{command={},args=[{args}],env={{{env}}},startup_timeout_sec={}}}",            server.name,            toml_string(&server.command),            crate::browser::MCP_STARTUP_TIMEOUT_SECONDS        )    }}impl Adapter for Codex {    fn tool(&self) -> Tool {        Tool::Codex    }    fn spawn_plan(&self, launch: &Launch) -> SpawnPlan {        let mut argv = vec!["codex".to_string()];        // **THE SUBCOMMAND COMES FIRST.** `codex resume <id>` continues the        // agent's own session; every flag below is the same either way.        if let Some(id) = launch.resume.as_deref() {            argv.push("resume".to_string());            argv.push(id.to_string());        }        argv.extend([            "-C".to_string(),            launch.cwd.clone(),            "-c".to_string(),            "check_for_update_on_startup=false".to_string(),            "-c".to_string(),            Self::hooks_override(launch),            "--dangerously-bypass-hook-trust".to_string(),        ]);        if let Some(offer) = &launch.browser {            argv.extend(["-c".to_string(), Self::browser_override(launch, offer)]);        }        if launch.permission_mode == PermissionMode::Bypass {            argv.push("--dangerously-bypass-approvals-and-sandbox".to_string());        }        argv.extend(launch.argv_extras.iter().cloned());        SpawnPlan {            argv,            // No environment of its own. Codex's quieting is a `-c` override,            // and `CODEX_HOME` is deliberately left exactly where the person            // signed in — see this module's own note.            env: launch.env.clone(),            cwd: launch.cwd.clone(),            cols: launch.cols,            rows: launch.rows,        }    }    fn hook_files(&self, _launch: &Launch) -> Vec<HookFile> {        // NONE, and that is the point: Codex's hooks travel on the command        // line, so a crashed host leaves nothing behind to clean up.        Vec::new()    }    fn read_last_turn(&self, transcript: &str) -> Option<Turn> {        transcript.lines().rev().find_map(|line| {            let record: serde_json::Value = serde_json::from_str(line).ok()?;            if record.get("type").and_then(serde_json::Value::as_str)? != "response_item" {                return None;            }            let payload = record.get("payload")?;            if payload.get("type").and_then(serde_json::Value::as_str)? != "message" {                return None;            }            let role = match payload.get("role").and_then(serde_json::Value::as_str)? {                "assistant" => TurnRole::Assistant,                "user" => TurnRole::User,                _ => return None,            };            // `output_text` is what an assistant message carries and            // `input_text` what a user message does; both are read, and a            // record with neither is NOT a turn rather than an empty one.            let text = join_text_blocks(payload.get("content")?, &["output_text", "input_text"])?;            Some(Turn { role, text })        })    }    fn read_adopted_meta(&self, head: &str) -> Option<AdoptedMeta> {        // A rollout opens with ONE `session_meta` record and it carries all        // three facts. No other record repeats the id, which is why this reads        // the head and not the tail.        head.lines().find_map(|line| {            let record: serde_json::Value = serde_json::from_str(line).ok()?;            if record.get("type").and_then(serde_json::Value::as_str)? != "session_meta" {                return None;            }            let payload = record.get("payload")?;            let field = |value: Option<&serde_json::Value>| {                value                    .and_then(serde_json::Value::as_str)                    .filter(|held| !held.trim().is_empty())                    .map(str::to_string)            };            Some(AdoptedMeta {                session_id: field(payload.get("id"))?,                cwd: field(payload.get("cwd")),                started_at: field(record.get("timestamp")),            })        })    }    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("payload")                .and_then(|payload| payload.get("type"))                .and_then(serde_json::Value::as_str)                .is_some_and(|kind| END_PAYLOAD_TYPES.contains(&kind))        })    }    fn account_argv(&self) -> Option<&'static [&'static str]> {        // `codex login status` says HOW somebody is signed in ("Logged in        // using ChatGPT") and never as whom. An account row's key is the        // address, so there is nothing here to file one under, and this        // agent is not asked. A Mac with Codex signed in reads as signed out        // until Codex has a way to say who.        None    }    fn read_account(&self, _said: &str) -> Option<SignedIn> {        None    }    fn read_usage(&self, event: &serde_json::Value, now: &str) -> Option<Usage> {        // A `token_count` arrives either as the whole rollout record        // (`{timestamp, type, payload}`) or as the payload on its own,        // depending on which side forwarded it. Both are the documented        // framings of the same record, so both are read — and a value with        // `rate_limits` in neither place is no reading at all.        let limits = event            .get("rate_limits")            .or_else(|| event.get("payload").and_then(|inner| inner.get("rate_limits")))?;        let window = |name: &str| {            let window = limits.get(name);            let pct = window                .and_then(|window| window.get("used_percent"))                .and_then(serde_json::Value::as_f64);            let resets = window                .and_then(|window| window.get("resets_in_seconds"))                .and_then(serde_json::Value::as_i64)                .and_then(|seconds| resets_at(now, seconds));            (pct, resets)        };        // `primary` is the short window and `secondary` the long one — Codex's        // own names for what the product calls five-hour and weekly.        let (five_hour_pct, five_hour_resets_at) = window("primary");        let (weekly_pct, weekly_resets_at) = window("secondary");        if five_hour_pct.is_none() && weekly_pct.is_none() {            return None;        }        Some(Usage {            provider: Provider::Openai,            // A rollout record names no account. Phase 3 fills the address            // from the agent's own account file; a placeholder here would be a            // second account on the person's devices page.            email: None,            five_hour_pct,            five_hour_resets_at,            weekly_pct,            weekly_resets_at,        })    }    fn permission_reply(&self, decision: Decision) -> serde_json::Value {        let behavior = match decision {            // Codex has no session-wide form in the hook's answer either: what            // travels is "allow", and the phone's `allowSession` is Cotton's            // own record that it need not ask again.            Decision::Allow | Decision::AllowSession => "allow",            Decision::Deny => "deny",        };        let mut inner = serde_json::Map::new();        inner.insert("behavior".to_string(), json!(behavior));        if decision == Decision::Deny {            inner.insert(                "message".to_string(),                json!("declined from Cotton on the owner's phone"),            );        }        json!({            "hookSpecificOutput": {                "hookEventName": "PermissionRequest",                "decision": serde_json::Value::Object(inner)            }        })    }}/// `now + seconds`, RFC 3339, or nothing when `now` is not a time.////// Nothing rather than "now": a reset instant that silently became the present/// would read on the phone as a window that has already refilled.fn resets_at(now: &str, seconds: i64) -> Option<String> {    let at = chrono::DateTime::parse_from_rfc3339(now).ok()?;    let then = at.checked_add_signed(chrono::Duration::seconds(seconds))?;    Some(        then.with_timezone(&chrono::Utc)            .to_rfc3339_opts(chrono::SecondsFormat::Secs, true),    )}/// A TOML basic string.////// The only two characters that can appear in what this crate puts in one are/// a quote and a backslash — every value is a path this host built or a/// constant above — so the escaping is those two and the control characters a/// path cannot contain. It is written out rather than reached for from a TOML/// crate because one argument's worth of quoting is not a dependency.fn toml_string(value: &str) -> String {    let mut out = String::with_capacity(value.len() + 2);    out.push('"');    for character in value.chars() {        match character {            '"' => out.push_str("\\\""),            '\\' => out.push_str("\\\\"),            '\n' => out.push_str("\\n"),            '\r' => out.push_str("\\r"),            '\t' => out.push_str("\\t"),            other => out.push(other),        }    }    out.push('"');    out}#[cfg(test)]#[path = "codex_tests.rs"]mod codex_tests;