Cotton code
323 lines · 12.5 KB · RustRaw
//! `create_session`, `get_session` and `open_project_conversation` — the//! project conversation's own surface (schema v31).//!//! ## NOTHING OVER MCP USED TO START A SESSION//!//! That was the rule until this rung, and it was a rule about WHO: starting an//! agent on somebody's Mac is the owner's act, and no assistant makes one. The//! owner's direction retired it, because a project's CONVERSATION is itself a//! session the owner opened, on a Mac they admitted, and opening threads is//! the whole of what it is for//! (Cotton note "The project conversation — one standing thread per project").//!//! What did NOT change is the shape: every opening goes through//! `crate::session_birth::write_session`, so a session asked for over MCP is//! the same queued row, on the same queue, with the same columns the Mac and//! the dispatcher own left alone.//!//! ## A tool call does not know which session made it//!//! The MCP surface knows the workspace and the caller's scope; it does not//! know which session is on the other end. So `create_session` takes//! `parentSessionId` EXPLICITLY, and the conversation learns its own row id//! from the standing prompt it was opened with//! (`cotton_core::rules::conversation_prompt`). A thread opened without one//! is a standalone, which is the honest answer rather than a guess.use serde_json::{Map, Value};use crate::mcp::dispatch::{Ctx, ToolResult};use crate::mcp::handlers::common::{    fail, flag, maybe_row, or_null, require_string, resolve_project, rows, text, ProjectRef,};use crate::mcp::handlers::records_2::memory::{memory_projects, MemoryProject};use crate::mcp::handlers::records_2::sessions::session_tasks;use crate::mcp::protocol::ToolFailure;use crate::mcp::read_db::{Order, Query};use crate::session_birth::{    ensure_conversation, validate_create, write_session, SessionKind, SESSION_TOOLS,};/// How many of a session's turns `get_session` hands back.////// TWENTY, and the LATEST twenty: a conversation reading a thread wants to/// know where it got to, and the whole transcript is what `list_sessions { q }`/// searches rather than what an expander returns.const RECENT_PROMPTS: i64 = 20;fn project_refs(projects: &[MemoryProject]) -> Vec<ProjectRef> {    projects        .iter()        .map(|project| ProjectRef {            id: project.id.clone(),            slug: project.slug.clone(),            status: project.status.clone(),        })        .collect()}/// The columns `get_session` reads — `SESSION_COLUMNS` plus the two the list/// does not need.const ONE_SESSION_COLUMNS: &[&str] = &[    "id",    "project_id",    "tool",    "external_id",    "machine",    "device_id",    "account",    "repo_url",    "branch",    "cwd",    "started_at",    "last_active_at",    "ended_at",    "summary",    "title",    "model",    "turn_count",    "prompt_count",    "state",    "state_at",    "waiting_kind",    "last_line",    "host_owned",    "prompt",    "requested_device_id",    "chosen_by",    "hold_reason",    "error",    "todo_id",    "todo_database",    "kind",    "parent_session_id",];// ── create_session ──────────────────────────────────────────────────────────/// `create_session` — open a thread, from a session.pub fn create_session(ctx: &mut Ctx<'_>, args: &Map<String, Value>) -> ToolResult {    let request = Value::Object(args.clone());    let Some(slug) = require_string(args, "project") else {        return fail("project is required — a session belongs to one");    };    // A THREAD WITH NOTHING TO DO is a Mac holding a terminal nobody is at, so    // the prompt is required HERE where the phone's own form allows an empty    // one: the owner starting a session from the app is at the keyboard, and a    // session opening one for a session is not.    let Some(prompt) = require_string(args, "prompt") else {        return fail("prompt is required — say what the thread is to do");    };    if prompt.trim().is_empty() {        return fail("prompt is required — say what the thread is to do");    }    let mut create = match validate_create(&request) {        Ok(create) => create,        Err(reason) => return fail(reason),    };    if !SESSION_TOOLS.contains(&create.tool.as_str()) {        return fail(format!(            "tool must be one of {}",            SESSION_TOOLS.join(", ")        ));    }    let projects = memory_projects(ctx)?;    let refs = project_refs(&projects);    // Refused BY NAME for an unknown project, `resolve_project`'s own    // sentence, which is the one an assistant has learned to read.    resolve_project(&refs, Some(&slug))?;    create.project_slug = Some(slug);    create.kind = SessionKind::Thread;    // A PARENT THIS WORKSPACE DOES NOT HOLD is refused rather than dropped: a    // thread silently filed under nobody is a thread the conversation that    // asked for it will never see in its own list.    if let Some(parent) = &create.parent_session_id {        let found = maybe_row(            ctx,            &Query::on("cotton_sessions")                .columns(&["id"])                .eq("id", parent.clone()),        )?;        if found.is_none() {            return fail(format!(                "no session with id {parent} — parentSessionId is the conversation's own row, \                 which the standing prompt names"            ));        }    }    let answer = match write_session(ctx, &create) {        Ok(answer) => answer,        Err(reason) => return Err(ToolFailure::new(reason)),    };    ctx.commit()?;    let id = answer        .get("id")        .and_then(Value::as_str)        .unwrap_or_default()        .to_string();    let mut out = Map::new();    out.insert("id".to_string(), Value::from(id.clone()));    out.insert("state".to_string(), Value::from("queued"));    out.insert("kind".to_string(), Value::from(SessionKind::Thread.as_str()));    out.insert(        "parentSessionId".to_string(),        or_null(create.parent_session_id.clone()),    );    // A queued row nothing has placed yet says why on `hold_reason`, and the    // dispatcher writes it — so it is NULL here, and the caller reads it back    // with `get_session` rather than being told a sentence that does not exist    // yet.    out.insert("holdReason".to_string(), Value::Null);    Ok(Value::Object(out))}// ── get_session ─────────────────────────────────────────────────────────────/// `get_session` — one session, whole: what it is doing, what it last said,/// its recent turns and its task list.pub fn get_session(ctx: &mut Ctx<'_>, args: &Map<String, Value>) -> ToolResult {    let Some(id) = require_string(args, "sessionId") else {        return fail("sessionId is required — the id list_sessions answers with");    };    let Some(row) = maybe_row(        ctx,        &Query::on("cotton_sessions")            .columns(ONE_SESSION_COLUMNS)            .eq("id", id.clone()),    )?    else {        return fail(format!("no session with id {id}"));    };    let projects = memory_projects(ctx)?;    let mut out = Map::new();    out.insert("id".to_string(), or_null(text(&row, "id")));    out.insert("tool".to_string(), or_null(text(&row, "tool")));    out.insert("externalId".to_string(), or_null(text(&row, "external_id")));    out.insert("machine".to_string(), or_null(text(&row, "machine")));    out.insert("deviceId".to_string(), or_null(text(&row, "device_id")));    out.insert("account".to_string(), or_null(text(&row, "account")));    out.insert(        "project".to_string(),        or_null(text(&row, "project_id").and_then(|id| {            projects                .iter()                .find(|project| project.id == id)                .map(|project| project.slug.clone())        })),    );    out.insert("repoUrl".to_string(), or_null(text(&row, "repo_url")));    out.insert("branch".to_string(), or_null(text(&row, "branch")));    out.insert("cwd".to_string(), or_null(text(&row, "cwd")));    out.insert("title".to_string(), or_null(text(&row, "title")));    out.insert("model".to_string(), or_null(text(&row, "model")));    out.insert("prompt".to_string(), or_null(text(&row, "prompt")));    out.insert("summary".to_string(), or_null(text(&row, "summary")));    out.insert("state".to_string(), or_null(text(&row, "state")));    out.insert("stateAt".to_string(), or_null(text(&row, "state_at")));    out.insert(        "waitingKind".to_string(),        or_null(text(&row, "waiting_kind")),    );    out.insert("lastLine".to_string(), or_null(text(&row, "last_line")));    out.insert("holdReason".to_string(), or_null(text(&row, "hold_reason")));    out.insert("error".to_string(), or_null(text(&row, "error")));    // The todo the session was handed, and the database it is in when that is    // not this one: a todo named in another database is answered though this    // database holds no such row.    out.insert("todoId".to_string(), or_null(text(&row, "todo_id")));    out.insert("todoDatabase".to_string(), or_null(text(&row, "todo_database")));    out.insert("startedAt".to_string(), or_null(text(&row, "started_at")));    out.insert(        "lastActiveAt".to_string(),        or_null(text(&row, "last_active_at")),    );    out.insert("endedAt".to_string(), or_null(text(&row, "ended_at")));    out.insert(        "hostOwned".to_string(),        Value::Bool(flag(&row, "host_owned")),    );    out.insert(        "kind".to_string(),        Value::from(text(&row, "kind").unwrap_or_else(|| "thread".to_string())),    );    out.insert(        "parentSessionId".to_string(),        or_null(text(&row, "parent_session_id")),    );    // The last twenty turns, oldest first once they are chosen — a reader    // wants the tail in the order it was said.    let mut recent = rows(        ctx,        &Query::on("cotton_prompts")            .columns(&["id", "session_id", "seq", "ts", "role", "text"])            .eq("session_id", id.clone())            .order_by("seq", Order::Desc)            .limit(RECENT_PROMPTS),    )?;    recent.sort_by_key(|row| row.get("seq").and_then(Value::as_i64).unwrap_or_default());    let prompts: Vec<Value> = recent        .iter()        .map(|row| {            let mut turn = Map::new();            turn.insert(                "seq".to_string(),                Value::from(row.get("seq").and_then(Value::as_i64).unwrap_or_default()),            );            turn.insert("ts".to_string(), or_null(text(row, "ts")));            turn.insert(                "role".to_string(),                Value::from(text(row, "role").unwrap_or_else(|| "user".to_string())),            );            turn.insert("text".to_string(), or_null(text(row, "text")));            Value::Object(turn)        })        .collect();    out.insert("prompts".to_string(), Value::Array(prompts));    let tasks = session_tasks(ctx, &id)?;    let done = tasks        .iter()        .filter(|task| task.get("state").and_then(Value::as_str) == Some("done"))        .count() as i64;    out.insert("tasksDone".to_string(), Value::from(done));    out.insert("tasksTotal".to_string(), Value::from(tasks.len() as i64));    out.insert(        "tasks".to_string(),        Value::Array(tasks.into_iter().map(Value::Object).collect()),    );    Ok(Value::Object(out))}// ── open_project_conversation ───────────────────────────────────────────────/// `open_project_conversation` — the project's standing conversation, opening/// it if it has none.pub fn open_project_conversation(ctx: &mut Ctx<'_>, args: &Map<String, Value>) -> ToolResult {    let Some(slug) = require_string(args, "project") else {        return fail("project is required — a conversation belongs to one");    };    let projects = memory_projects(ctx)?;    let refs = project_refs(&projects);    let Some(project_id) = resolve_project(&refs, Some(&slug))? else {        return fail("project is required — a conversation belongs to one");    };    let answer = match ensure_conversation(ctx, &project_id) {        Ok(answer) => answer,        Err(reason) => return Err(ToolFailure::new(reason)),    };    ctx.commit()?;    let mut out = match answer {        Value::Object(object) => object,        _ => Map::new(),    };    out.insert("project".to_string(), Value::from(slug));    Ok(Value::Object(out))}