//! The Code tool's owner methods — the settings a person makes on the //! sessions their Macs are hosting. //! //! ## Why these are METHODS and not tools //! //! The same line `session.create` draws: **no assistant asks for a session** //! or sets how one runs. Every one of these is a person on a screen, so it is a //! method through the same `Ctx`, the same writer and the same outbox as every //! other phone write. //! //! **Nothing here answers a session or stops one.** The phone's permission //! answer and stop (`session.decide`, `session.stop`) went with the session //! inbox (Nov 2026): Cotton sends nothing to a session, and the person drives //! their sessions from Claude Code's own app. //! //! Cotton note "The Code tool — why a Mac holds the sessions". use serde_json::{json, Map, Value}; use cotton_tools::mcp::dispatch::Ctx; use cotton_tools::mcp::handlers::common::{maybe_row, update_row}; use cotton_tools::mcp::read_db::{Order, Query}; use crate::handle::CottonHandle; use crate::methods::MethodError; /// Every method this module answers. pub const METHODS: [&str; 4] = [ "device.setSessions", "device.setAiCap", "workspace.setCode", "workspace.setReach", ]; pub fn call(handle: &CottonHandle, method: &str, request: &Value) -> Result { match method { "device.setSessions" => set_sessions(handle, request), "device.setAiCap" => set_ai_cap(handle, request), "workspace.setCode" => set_code(handle, request), "workspace.setReach" => crate::phone::front_door::set_front_door(handle, request), other => Err(MethodError::new( "unknown_method", format!("this core does not answer `{other}`"), )), } } // ── the two settings, which are rows and land today ───────────────────────── /// `device.setSessions { deviceId, sessionsCap }` — how many sessions this Mac /// may run at once. /// /// **A CAP AND NOT A PAUSE.** The pause switches are gone with the dispatch /// modes (schema v23): a Mac that should take no work is a Mac with a cap of /// zero, which is one number the picking rule already reads and one fewer way /// for two settings to disagree about the same Mac. /// /// The cap is the PERSON's column on a row the Mac itself rewrites every /// fifteen minutes, and per-field clocks are what make that safe: the sample /// carries the reading's columns and nothing else, so a cap set on a phone is /// never clobbered by the next reading. pub fn set_sessions(handle: &CottonHandle, request: &Value) -> Result { let args = validate_sessions(request)?; handle .client() .write_rows("device.setSessions", &mut |ctx| { write_sessions(ctx, &args.device_id, args.sessions_cap) }) .map(crate::authoring::own_answer) .map_err(|reason| MethodError::new("write_refused", reason)) } /// What `device.setSessions` takes, checked before a row is touched. #[derive(Debug)] pub struct SessionsArgs { pub device_id: String, pub sessions_cap: i64, } pub fn validate_sessions(request: &Value) -> Result { let device_id = required(request, "deviceId", "a session setting")?; let sessions_cap = match request.get("sessionsCap").and_then(Value::as_i64) { Some(cap) if (0..=32).contains(&cap) => cap, _ => { return Err(bad( "`sessionsCap` is how many sessions this Mac may run at once — 0 to 32, and 0 \ takes it out of the household", )) } }; Ok(SessionsArgs { device_id, sessions_cap, }) } pub fn write_sessions( ctx: &mut Ctx<'_>, device_id: &str, sessions_cap: i64, ) -> Result { // By the KEY, never by the row id: a device is what its key says it is, and // the row id is bookkeeping. let row = maybe_row( ctx, &Query::on("cotton_devices") .columns(&["id", "device_id", "revoked_at"]) .eq("device_id", device_id.to_string()) // The key's LIVE approval first (NULL sorts first), then its newest: // a key holds a row per approval since store version 41. .order_by("revoked_at", Order::Asc) .order_by("approved_at", Order::Desc), ) .map_err(|failure| failure.to_string())? .ok_or_else(|| format!("no device with key {device_id}"))?; let id = row .get("id") .and_then(Value::as_str) .unwrap_or_default() .to_string(); if row.get("revoked_at").and_then(Value::as_str).is_some() { return Err( "that device is revoked — re-admitting a key is a new approval, never a setting" .to_string(), ); } let mut patch = Map::new(); patch.insert("sessions_cap".to_string(), Value::from(sessions_cap)); update_row(ctx, "cotton_devices", &id, patch).map_err(|failure| failure.to_string())?; Ok(json!({ "deviceId": device_id, "sessionsCap": sessions_cap, })) } /// `device.setAiCap` — the most the serving Mac's Anthropic work may spend in /// one of the owner's days, in USD; `null` clears it back to the $5 default. /// /// The owner's column on a row the Mac's server rewrites with its holds and /// spend; per-field clocks keep a cap set on a phone from being clobbered by /// the server's next minute, exactly as `sessions_cap` is kept. pub fn set_ai_cap(handle: &CottonHandle, request: &Value) -> Result { let args = validate_ai_cap(request)?; handle .client() .write_rows("device.setAiCap", &mut |ctx| write_ai_cap(ctx, &args.device_id, args.cap_usd)) .map(crate::authoring::own_answer) .map_err(|reason| MethodError::new("write_refused", reason)) } /// What `device.setAiCap` takes, checked before a row is touched. #[derive(Debug)] pub struct AiCapArgs { pub device_id: String, /// `None` is the default again. pub cap_usd: Option, } /// The most a cap may be: a day's ceiling, not a budget for a month. pub const AI_CAP_MAX_USD: f64 = 1000.0; pub fn validate_ai_cap(request: &Value) -> Result { let device_id = required(request, "deviceId", "a daily Claude API cap")?; let cap_usd = match request.get("capUsd") { None | Some(Value::Null) => None, Some(value) => match value.as_f64() { Some(cap) if cap.is_finite() && (0.0..=AI_CAP_MAX_USD).contains(&cap) => Some(cap), _ => { return Err(bad( "`capUsd` is the most this Mac's Claude API work may spend in a day, in US \ dollars — 0 to 1000, or null for the $5 default", )) } }, }; Ok(AiCapArgs { device_id, cap_usd }) } pub fn write_ai_cap(ctx: &mut Ctx<'_>, device_id: &str, cap_usd: Option) -> Result { let row = maybe_row( ctx, &Query::on("cotton_devices") .columns(&["id", "device_id", "platform", "revoked_at"]) .eq("device_id", device_id.to_string()) .order_by("revoked_at", Order::Asc) .order_by("approved_at", Order::Desc), ) .map_err(|failure| failure.to_string())? .ok_or_else(|| format!("no device with key {device_id}"))?; if row.get("revoked_at").and_then(Value::as_str).is_some() { return Err("that device is revoked — it spends nothing".to_string()); } let id = row.get("id").and_then(Value::as_str).unwrap_or_default().to_string(); let mut patch = Map::new(); patch.insert("ai_day_cap_usd".to_string(), cap_usd.map_or(Value::Null, Value::from)); update_row(ctx, "cotton_devices", &id, patch).map_err(|failure| failure.to_string())?; Ok(json!({ "deviceId": device_id, "capUsd": cap_usd })) } /// `workspace.setCode { permissionDefault }` — the household's one setting. /// /// `session_permission_default` is what the new-session form OFFERS /// ([sessions-start-in-bypass-permissions-mode-by-default-it-s-a-sett]); it is /// a default and never a ceiling, so a person may still pick `ask` for one /// session. The household-wide dispatch pause is gone (schema v23) — a /// household that should take no work is every Mac at a cap of zero, and a /// switch that silently held every queued session while each Mac reported /// itself free was the hardest state in this subsystem to read. /// /// ONE row per workspace, and the workspace is the file's own: the id comes off /// the open file rather than from the caller, so a method cannot be asked to /// write somebody else's settings. pub fn set_code(handle: &CottonHandle, request: &Value) -> Result { let args = validate_code_settings(request)?; handle .client() .write_rows("workspace.setCode", &mut |ctx| { write_code_settings(ctx, &args.permission_default) }) .map(crate::authoring::own_answer) .map_err(|reason| MethodError::new("write_refused", reason)) } /// What a session starts in when nobody has said otherwise. pub const PERMISSION_MODES: [&str; 2] = ["bypass", "ask"]; /// What `workspace.setCode` takes, checked before a row is touched. #[derive(Debug)] pub struct CodeSettingsArgs { pub permission_default: String, } pub fn validate_code_settings(request: &Value) -> Result { let permission_default = match request.get("permissionDefault") { Some(Value::String(mode)) if PERMISSION_MODES.contains(&mode.as_str()) => mode.clone(), _ => { return Err(bad( "`permissionDefault` is bypass or ask — bypass is what a session starts in unless \ the person picks otherwise for that one session", )) } }; Ok(CodeSettingsArgs { permission_default }) } pub fn write_code_settings( ctx: &mut Ctx<'_>, permission_default: &str, ) -> Result { // The workspace is the FILE's, never the caller's. let workspace_id = ctx.workspace_id.to_string(); maybe_row( ctx, &Query::on("cotton_workspaces") .columns(&["id"]) .eq("id", workspace_id.clone()), ) .map_err(|failure| failure.to_string())? .ok_or_else(|| "this file has no workspace row to set".to_string())?; let mut patch = Map::new(); patch.insert( "session_permission_default".to_string(), Value::from(permission_default), ); update_row(ctx, "cotton_workspaces", &workspace_id, patch) .map_err(|failure| failure.to_string())?; Ok(json!({ "permissionDefault": permission_default })) } fn bad(message: impl Into) -> MethodError { MethodError::new("bad_request", message) } fn required(value: &Value, field: &str, what: &str) -> Result { value .get(field) .and_then(Value::as_str) .map(str::trim) .filter(|id| !id.is_empty()) .map(str::to_string) .ok_or_else(|| bad(format!("{what} needs its `{field}`"))) }