Cotton code
239 lines · 10.3 KB · RustRaw
//! The two adapters, behind one trait.//!//! An adapter is where EVERY difference between `claude` and `codex` lives://! the argv, the environment, the hook files written for one launch, the//! transcript format, the usage record, and the exact JSON a blocked//! permission hook must print. Nothing else in the crate branches on which//! agent a session runs.//!//! **Two adapters, and no generalisation for a third until a third is in use.**//! The trait is the shape the two of them already have, not a plugin surface.//!//! Everything here is a PURE FUNCTION over values: `spawn_plan` builds an argv,//! `hook_files` builds file contents, `read_last_turn` parses text,//! `read_usage` parses JSON. Nothing spawns, reads a file or reads a clock — so//! `tests/adapters.rs` and `tests/transcripts.rs` pin all of it against//! fixtures without an agent installed. (`codex` is not installed on the//! machine this was written on; the Codex adapter is held entirely by its//! fixtures, which is why they are hand-written from the published formats and//! say so.)use std::collections::BTreeMap;use crate::protocol::{Decision, PermissionMode, SignedIn, Tool, Turn, Usage};use crate::pty::SpawnPlan;pub mod claude;pub mod codex;/// Everything an adapter needs to describe one launch.#[derive(Debug, Clone, PartialEq, Eq)]pub struct Launch {    /// The launch row this answers.    pub launch_id: String,    /// The HOST's id for the session — a uuid the host minted or the caller    /// supplied. `claude` is told to use it (`--session-id`); `codex` mints    /// its own and the host learns it from the `SessionStart` hook.    pub session_id: String,    /// Arguments appended after the ones the adapter owns.    pub argv_extras: Vec<String>,    /// Where the agent runs.    pub cwd: String,    /// Environment on top of the adapter's own.    pub env: BTreeMap<String, String>,    /// Terminal width.    pub cols: u16,    /// Terminal height.    pub rows: u16,    /// Whether the agent asks before it acts.    pub permission_mode: PermissionMode,    /// The absolute path of THIS binary, which every hook command re-invokes.    pub host_binary: String,    /// `<dataDir>/sessions/<session_id>` — where the hook files go.    pub launch_dir: String,    /// **THE AGENT SESSION THIS ONE CONTINUES**, when it continues one.    ///    /// Resolved by [`crate::serve`] before the adapter sees it: for `claude`    /// it is the host's own id, for `codex` the id the agent minted and the    /// `SessionStart` hook reported. `None` is an ordinary first start.    #[allow(clippy::struct_field_names)]    pub resume: Option<String>,    /// **THE BROWSER TOOL**, when this Mac can offer it    /// ([`crate::browser::offer`]): the session gets one more MCP server,    /// [`crate::browser::MCP_SERVER_NAME`], added to the person's own — never    /// replacing them. `None` is a session exactly as before.    pub browser: Option<crate::browser::Offer>,}/// A file an adapter wants written before the agent starts.#[derive(Debug, Clone, PartialEq, Eq)]pub struct HookFile {    /// Absolute path.    pub path: String,    /// Contents.    pub contents: String,}/// What an adapter read out of the HEAD of a transcript it did not spawn.////// Adopted sessions (Cotton note "The Code tool — why a Mac holds the sessions") are found as files, so/// everything the card needs — which session this is, where it runs, when it/// started — has to come out of the agent's own record rather than out of a/// launch nobody placed.#[derive(Debug, Clone, PartialEq, Eq)]pub struct AdoptedMeta {    /// The agent's own session id. Without one there is no session to adopt:    /// a file whose head names none is skipped, never adopted under a guess.    pub session_id: String,    /// Where the agent is running, when the transcript says.    pub cwd: Option<String>,    /// RFC 3339, when the transcript's own first record carries one.    pub started_at: Option<String>,}/// What the two agents have in common, and nothing more.pub trait Adapter: Send + Sync {    /// Which agent this is.    fn tool(&self) -> Tool;    /// The argv, the environment and the working directory for one launch.    fn spawn_plan(&self, launch: &Launch) -> SpawnPlan;    /// The files to write before spawning, for THIS launch only.    ///    /// Never the person's own settings: `settings.json` in `~/.claude` and    /// `~/.codex/config.toml` are theirs, and a host that edited one would    /// leave its hooks behind on the day it crashed.    fn hook_files(&self, launch: &Launch) -> Vec<HookFile>;    /// The last turn in a transcript.    ///    /// Takes the transcript's TEXT, not its path: the parser is a pure    /// function and the read is the caller's.    fn read_last_turn(&self, transcript: &str) -> Option<Turn>;    /// The account's windows, out of a forwarded event.    ///    /// Claude's arrives on the status line; Codex's is a `token_count` record    /// in the rollout file. Both are JSON, and neither is invented when it is    /// absent — `None` means "we have not been told", never "zero used".    ///    /// `now` is RFC 3339 and is the instant the event arrived. It exists    /// because Codex reports a window as "resets in N seconds" while the    /// product stores an instant, and a parser that read the clock itself    /// could not be tested against a fixture.    fn read_usage(&self, event: &serde_json::Value, now: &str) -> Option<Usage>;    /// The arguments that make the agent say who is signed in, or `None` for    /// an agent that has no way to be asked.    ///    /// The agent's own command, run in the login environment a session runs    /// in — so the answer is about the login a session would actually open.    fn account_argv(&self) -> Option<&'static [&'static str]>;    /// Who is signed in, out of what [`Self::account_argv`] printed.    ///    /// `None` is signed out, or an answer that names no address. Never a    /// placeholder: a made-up address would be a second login in the person's    /// list and a Mac that reads as ready when it is not.    fn read_account(&self, said: &str) -> Option<SignedIn>;    /// Who this transcript belongs to, out of its first few kilobytes.    ///    /// The HEAD rather than the tail, because both agents put the session's    /// identity in its first records and neither repeats it at the end. Takes    /// text, like every other parser here: the read is the caller's.    fn read_adopted_meta(&self, head: &str) -> Option<AdoptedMeta>;    /// Whether this transcript's tail carries the agent's own end marker.    ///    /// **A marker, never a guess.** An adopted session's process belongs to    /// whoever started it, so this host cannot reap it and will not invent an    /// exit: a transcript with no marker leaves its session `idle` for as long    /// as it stays quiet. The markers are hand-written from the agents' formats    /// and pinned by `tests/fixtures/*-ended.jsonl`, so a version that stops    /// writing one is a session that reads idle — never one that reads ended    /// because a parser returned false about something else.    fn transcript_ended(&self, tail: &str) -> bool;    /// The exact JSON a blocked `PermissionRequest` hook must print on stdout    /// to carry this decision.    fn permission_reply(&self, decision: Decision) -> serde_json::Value;}/// The adapter for a tool.pub fn adapter(tool: Tool) -> Box<dyn Adapter> {    match tool {        Tool::Claude => Box::new(claude::Claude),        Tool::Codex => Box::new(codex::Codex),    }}/// The hook events both adapters register, in the order they are written.////// A NAMED LIST, never "every event the agent has": an event nobody handles is/// a hook that blocks a turn for nothing.////// `UserPromptSubmit` is what says a turn BEGAN. Without it a session that/// was handed a reply read `idle` for the whole of the turn that answered it —/// `Stop` says a turn ended and nothing said the next one had started — so a/// card offered Reply to a session that was busy working on the last one.////// **It is not everything this host HANDLES.** Claude registers one more,/// [`crate::tasks::TASKS_EVENT`], matched to one tool name — Codex has no such/// tool, and an unmatched `PostToolUse` there would be a socket round trip/// after every command it ran. [`handled_hook_events`] is the whole set.pub const HOOK_EVENTS: [&str; 6] = [    "SessionStart",    "UserPromptSubmit",    "Stop",    "SessionEnd",    "Notification",    "PermissionRequest",];/// Every event `cotton-session-host hook <event>` answers — the six both/// adapters register plus Claude's task-list one.////// What the daemon names when it is handed an event it does not know.pub fn handled_hook_events() -> Vec<&'static str> {    let mut events = HOOK_EVENTS.to_vec();    events.push(crate::tasks::TASKS_EVENT);    events}/// The `Notification` matcher both adapters use.////// The four kinds a session can be waiting on a person for. Written as one/// alternation because a matcher is a regex and four entries would register/// the same command four times.pub const NOTIFICATION_MATCHER: &str =    "permission_prompt|idle_prompt|agent_needs_input|elicitation_dialog";/// How long a blocked `PermissionRequest` hook waits for the phone.////// Ten minutes: long enough for somebody to pick up their phone, short enough/// that a session left waiting overnight falls back to its own prompt in the/// TUI rather than hanging on a socket for ever. On a timeout the hook prints/// NOTHING and exits 0, which both agents read as "the hook had no opinion".pub const PERMISSION_TIMEOUT_SECONDS: u64 = 600;/// The text content blocks of a transcript message, joined.////// Shared by both parsers because both agents' transcripts carry an array of/// typed blocks and only the block's type name differs.pub(crate) fn join_text_blocks(content: &serde_json::Value, type_names: &[&str]) -> Option<String> {    let blocks = content.as_array()?;    let text = blocks        .iter()        .filter(|block| {            block                .get("type")                .and_then(serde_json::Value::as_str)                .is_some_and(|kind| type_names.contains(&kind))        })        .filter_map(|block| block.get("text").and_then(serde_json::Value::as_str))        .collect::<Vec<_>>()        .join("\n");    (!text.trim().is_empty()).then_some(text)}