//! `assistant.*` — the phone's half of Your Claude: the //! one standing grant to the person's own Claude. Decided in the core //! (`cotton_core::rules::assistants`, `cotton_core::seal::agent`); this file //! reads the object's grant rows from the copy, builds and signs the grant, //! and posts it. //! //! - The one card is an `unlock_request` whose `account` is true: the face //! draws it as every card (`unlock.card`), and `unlock.allow` answers it //! here ([`allow_card`]): the tables left on wrapped to the connection's //! member key, the policy (every sealed table except those switched off and //! saved secrets) signed by the person key, posted as `assistant_allow`. //! - `assistant.screen {}` → Account › Assistants as the core words it. //! - `assistant.scope {table, access, privateKey?}`: `off` or `ask` narrows //! every connection at once and moves the table to its next key version (so //! what is written after was never wrapped to Claude); `on` for a table the //! signed policy withholds signs it again (behind the phone's lock: needs //! `privateKey`), else it is a plain setting. //! `{group, access}` sets every table of one of the kit's groups (`reads`) //! together. //! - `assistant.screen` also answers `groups` (the kit's groups a person //! knows, each with how its tables stand) and `reading` (whether Claude //! reads any time, for a while, or asks; the row on You says it). //! - `assistant.askEachTime {}`: Ask each time instead; `assistant.stop {}`: //! Stop now, every window for a while ends. //! - `assistant.remove {}`: every grant to your Claude ends; after the pass //! the phone moves every table it handed to fresh keys (the window's //! advance, [`super::unlock::advance_ended`]). //! - `assistant.connect {privateKey}`: Connect Claude from the app. The phone //! makes the member pair and the grant in one step; the object holds the //! member's private half for 15 minutes, until the next OAuth connection //! claims it. Answers the address to add in Claude. //! //! After every pass ([`top_up`]): for each live grant, the keys of tables the //! kit added and of tables' next versions, inside the signed policy, wrapped //! to the member key with the data key this phone holds (no lock asked); //! nothing when it holds none yet. use base64::engine::general_purpose::URL_SAFE_NO_PAD; use base64::Engine as _; use rand::RngCore; use serde_json::{json, Value}; use zeroize::Zeroizing; use cotton_client::seal::DataKeyStore as _; use cotton_core::rules::assistants as rules; use cotton_core::rules::unlock::UnlockRequest; use cotton_core::seal::agent::{addition, closed, policy, AgentGrant, NEVER}; use super::unlock::{copy, labels, note_handed, post, rows, text_arg, unreadable, writable, GRANTS, READS}; use crate::handle::CottonHandle; use crate::methods::MethodError; use crate::shell::client::ClientController; pub fn call(handle: &CottonHandle, method: &str, request: &Value) -> Result { call_on(&handle.client(), method, request) } pub(crate) fn call_on(client: &ClientController, method: &str, request: &Value) -> Result { match method { "assistant.screen" => screen(client), "assistant.scope" => scope(client, request), "assistant.remove" => { let answer = post(client, "assistant_remove", json!({}))?; client.nudge_sync(); Ok(json!({ "ended": answer["ended"], "said": lines(client)?.say("account.removed", &[]).unwrap_or_default() })) } "assistant.connect" => connect(client, request), "assistant.askEachTime" => ask_each_time(client), "assistant.stop" => stop(client), _ => Err(MethodError::new("unknown_method", format!("`{method}` is not an assistant method"))), } } fn lines(client: &ClientController) -> Result { super::unlock::lines_of(client) } fn sealing(error: cotton_core::seal::SealError) -> MethodError { MethodError::new(error.code(), error.to_string()) } fn key32(text: &str, what: &str) -> Result<[u8; 32], MethodError> { URL_SAFE_NO_PAD .decode(text.trim_end_matches('=')) .ok() .and_then(|bytes| bytes.try_into().ok()) .ok_or_else(|| MethodError::new("bad_request", format!("{what} is not a 32-byte key"))) } /// Every table this database seals, by the definitions the copy keeps (a /// table's `seal` block), else the card's own list. fn sealed_tables(client: &ClientController, database: &str) -> Vec { let mut out: Vec = cotton_client::transport::object::object_definitions(&client.layout().replica(database)) .unwrap_or_default() .into_iter() .filter(|definition| definition.get("seal").is_some_and(Value::is_object)) .filter_map(|definition| definition["id"].as_str().map(str::to_string)) .collect(); // HANDING STUCK (25 Nov 2026): a kit's copy keeps only its own tables' definitions (`kept_to`), so the tables the // object seals beyond them come from its whole answer, held for the launch: Words hands the session tables' keys. if let Some(held) = client.served_definitions() { out.extend(held.sealed()); } out.sort(); out.dedup(); out } /// What this phone handed a grant, by table: the newest version. fn handed(client: &ClientController, database: &str, request_id: &str) -> Result, MethodError> { let file = writable(client, database)?; let mut statement = file.prepare("SELECT tbl, v FROM _unlock_handed WHERE request_id = ?1").map_err(|error| unreadable(error.to_string()))?; let found = statement .query_map([request_id], |row| Ok((row.get::<_, String>(0)?, row.get::<_, u32>(1)?))) .map_err(|error| unreadable(error.to_string()))? .collect::, _>>() .map_err(|error| unreadable(error.to_string())); found } /// Sign a grant to a member key: the vault opens for this call alone (the /// person key signs through its one signing call), then every session locks. fn sign(client: &ClientController, database: &str, member_id: &str, member_pub: &[u8; 32], versions: &[(String, u32)], withheld: &[String], secret: &[u8; 32]) -> Result { let (vmk, version) = crate::phone::vault::opened_vmk(client, secret)?; crate::phone::person_key::ensure(client, &vmk, version)?; let dk = crate::phone::seal::ensure(client, &vmk, version)?; client.vault().map_err(unreadable)?.unlock(vmk, version, client.now()); let signed = (|| { // The statement is the core's; the signature the vault's own call. let unsigned = build_unsigned(&dk, database, member_id, member_pub, versions, withheld)?; let statement = cotton_core::seal::agent::agent_statement(database, member_id, member_pub, &unsigned.withheld, &unsigned.wrapped).map_err(sealing)?; let (public_key, sig) = crate::phone::vault::sign_as_person(client, &statement)?; let signer = cotton_core::keys::person::fingerprint(&public_key).ok_or_else(|| MethodError::new("no_person_key", "the person key is unreadable"))?; Ok(AgentGrant { signer, sig: URL_SAFE_NO_PAD.encode(sig), ..unsigned }) })(); client.vault_session().lock_all(); signed } /// The wrap and the policy before the signature (the vault's signing call /// signs; seal-core's `build_agent_grant` signs with a key in hand, which a /// phone never holds outside the vault). fn build_unsigned(dk: &cotton_core::seal::DataKey, database: &str, member_id: &str, member_pub: &[u8; 32], versions: &[(String, u32)], withheld: &[String]) -> Result { let withheld = policy(withheld).map_err(sealing)?; let wrapped = addition(dk, database, member_id, member_pub, versions, &withheld).map_err(sealing)?; Ok(AgentGrant { withheld, wrapped, signer: String::new(), sig: String::new() }) } /// `unlock.allow` on the one card: the tables left on, wrapped to the /// member key; everything else the card listed withheld. pub(crate) fn allow_card(client: &ClientController, database: &str, asked: &UnlockRequest, versions: &[(String, u32)], secret: &[u8; 32]) -> Result { let member_id = asked.member_id.clone().ok_or_else(|| MethodError::new("bad_request", "the card names no member key"))?; let member_pub = key32(&asked.worker_pub, "the card's member key")?; let on: Vec = versions.iter().map(|(t, _)| t.clone()).collect(); let withheld: Vec = asked.tables.iter().filter(|t| !on.contains(t)).cloned().collect(); let grant = sign(client, database, &member_id, &member_pub, versions, &withheld, secret)?; note_handed(client, database, &asked.id, versions)?; let answer = post(client, "assistant_allow", json!({ "request_id": asked.id, "tables": on, "withheld": grant.withheld, "wrapped": grant.wrapped, "signer": grant.signer, "sig": grant.sig }))?; client.nudge_sync(); Ok(json!({ "grantId": answer["grant"], "standing": true, "tables": on })) } fn screen(client: &ClientController) -> Result { let lines = lines(client)?; let (database, file) = copy(client)?; let grants = rows(&file, GRANTS)?; // The grants something has read through: a pair Connect Claude made says it waits until then. let mut read: Vec = rows(&file, READS)?.iter().filter_map(|r| text(r, "grant_id")).collect(); read.sort(); read.dedup(); drop(file); let sealed = sealed_tables(client, &database); let shown = rules::screen(&grants, &read, &sealed, client.now(), labels(client, &database), &lines); let (reads, core) = kit_reads(client, &sealed); let groups = rules::groups(&grants, &reads, &sealed, &lines, core); let chosen = chosen(&grants, &shown, &groups); let zone = client.time_zone().unwrap_or("UTC").to_string(); let clock = |iso: &str| cotton_core::kit::local_clock(iso, &zone, "%-H:%M").unwrap_or_else(|| iso.to_string()); let reading = rules::reading(&grants, &read, &chosen, client.now(), clock, &lines); let mut answer = serde_json::to_value(shown).unwrap_or(Value::Null); answer["groups"] = serde_json::to_value(groups).unwrap_or(Value::Null); answer["reading"] = serde_json::to_value(reading).unwrap_or(Value::Null); Ok(answer) } /// The groups this app's kit names for Your Claude (`reads`: Comms' six); for a kit that names none, the core's groups /// the card offers (`kits/keys/reads.json`) over `sealed`, so Words, Days and Story list groups a person knows, never /// every table by its own name (owner, 23 Nov 2026). True with them: the groups are the core's. fn kit_reads(client: &ClientController, sealed: &[String]) -> (Vec<(String, Vec)>, bool) { let own = cotton_core::kit::AppKit::at(client.layout().root()).ok().flatten().map(|kit| cotton_core::kit::AppKit::reads_of(&kit.id)).unwrap_or_default(); if own.is_empty() { (cotton_core::rules::unlock::groups_of(sealed), true) } else { (own, false) } } /// What the person chooses between, each table with how it stands: the groups' tables where the kit names groups, /// else every table the screen lists. fn chosen(grants: &[Value], shown: &rules::Screen, groups: &[rules::GroupAccess]) -> Vec<(String, &'static str)> { if groups.is_empty() { return shown.tables.iter().map(|t| (t.table.clone(), t.access)).collect(); } let newest = rules::live(grants).first().copied(); groups.iter().flat_map(|g| g.tables.iter().map(move |t| (t.clone(), rules::access(newest, t)))).collect() } /// The screen's grants and what it lists, read again for an act that sets several tables at once. fn standing_now(client: &ClientController) -> Result<(Vec, Vec<(String, &'static str)>, Vec), MethodError> { let lines = lines(client)?; let (database, file) = copy(client)?; let grants = rows(&file, GRANTS)?; drop(file); let sealed = sealed_tables(client, &database); let shown = rules::screen(&grants, &[], &sealed, client.now(), labels(client, &database), &lines); let (reads, core) = kit_reads(client, &sealed); let groups = rules::groups(&grants, &reads, &sealed, &lines, core); let chosen = chosen(&grants, &shown, &groups); Ok((grants, chosen, groups)) } /// `assistant.askEachTime {}`: Ask each time instead. Every table on of what the person chooses between moves to Ask /// each time (a narrowing, never signed), so Claude asks on this phone before it reads. fn ask_each_time(client: &ClientController) -> Result { let (_, chosen, _) = standing_now(client)?; let tables = rules::to_ask(&chosen); scope_tables(client, &tables, "ask", &json!({}))?; Ok(json!({ "tables": tables, "access": "ask", "said": lines(client)?.say("account.reading.asked_all", &[]).unwrap_or_default() })) } /// `assistant.stop {}`: Stop now. Every window for a while open now ends (`unlock_end`), as End does one. fn stop(client: &ClientController) -> Result { let lines = lines(client)?; let (grants, chosen, _) = standing_now(client)?; let reading = rules::reading(&grants, &[], &chosen, client.now(), |iso: &str| iso.to_string(), &lines); let ended: Vec = reading.act.filter(|act| act.id == "stop").map(|act| act.grant_ids).unwrap_or_default(); for grant_id in &ended { post(client, "unlock_end", json!({ "grant_id": grant_id }))?; } client.nudge_sync(); Ok(json!({ "ended": ended, "said": lines.say("account.reading.stopped", &[]).unwrap_or_default() })) } /// `assistant.scope {table | group, access, privateKey?}`: one table, or every table of one of the kit's groups /// (Comms' Chats, Mail, Photos, Calls, Contacts, Files), set together. fn scope(client: &ClientController, request: &Value) -> Result { let access = text_arg(request, "access")?; if let Some(group) = request["group"].as_str().map(str::trim).filter(|g| !g.is_empty()) { let (_, _, groups) = standing_now(client)?; let tables = groups.into_iter().find(|g| g.id == group).map(|g| g.tables).ok_or_else(|| MethodError::new("bad_request", format!("`{group}` is not one of this app's groups")))?; scope_tables(client, &tables, &access, request)?; return Ok(json!({ "group": group, "tables": tables, "access": access })); } let table = text_arg(request, "table")?; scope_tables(client, std::slice::from_ref(&table), &access, request) } /// Set `tables` to `access` for every connection of your Claude. Turning on a table the signed policy withholds signs /// each connection's grant again with those tables' keys added (behind the phone's lock: `privateKey`); every other /// change is a plain setting, and a narrowing moves the table to its next key version, so what is written after was /// never wrapped to Claude. fn scope_tables(client: &ClientController, tables: &[String], access: &str, request: &Value) -> Result { let (database, file) = copy(client)?; let grants = rows(&file, GRANTS)?; let sealer = crate::phone::personal_object::sealer_of(client, &database); for (id, data) in cotton_client::seal::kept_keys(&file).map_err(unreadable)? { sealer.learn(&id, &data); } drop(file); let live = rules::live(&grants); let withheld_any = |t: &String| live.iter().any(|g| rules::list(g, "withheld").contains(t)); let (signed, plain): (Vec, Vec) = if access == "on" { tables.iter().cloned().partition(|t| withheld_any(t)) } else { (Vec::new(), tables.to_vec()) }; // Widening what Claude may read always asks the phone's lock, as Allow does (coordinator, 22 Nov 2026): the // device key comes only through it, so a phone that did not ask, or a lock cancelled, changes nothing. Stepping // down (Ask each time, Off) asks nothing. let secret = if access == "on" && !tables.is_empty() { Some(Zeroizing::new(crate::phone::vault::private_key_arg(request)?)) } else { None }; if let Some(secret) = secret.as_ref().filter(|_| !signed.is_empty()) { // Widening a table left off on the card is signed: each connection's grant again, these tables' keys added. let versions: Vec<(String, u32)> = signed.iter().map(|t| (t.clone(), sealer.version(t))).collect(); for g in &live { let (Some(grant_id), Some(member_id), Some(member_pub), Some(request_id)) = (text(g, "id"), text(g, "member_id"), text(g, "member_pub"), text(g, "request_id")) else { continue }; let withheld: Vec = rules::list(g, "withheld").into_iter().filter(|t| !signed.contains(t)).collect(); let grant = sign(client, &database, &member_id, &key32(&member_pub, "the grant's member key")?, &versions, &withheld, secret)?; post(client, "assistant_allow", json!({ "grant_id": grant_id, "tables": signed, "withheld": grant.withheld, "wrapped": grant.wrapped, "signer": grant.signer, "sig": grant.sig }))?; note_handed(client, &database, &request_id, &versions)?; } } let mut answer = json!({ "table": tables.first(), "access": access }); for table in &plain { answer = post(client, "assistant_scope", json!({ "table": table, "access": access }))?; // Narrowed: what is written from now on is sealed under keys Claude was never handed. if access != "on" { let door = client.object_door().ok_or_else(|| MethodError::new("sign_in_first", "signed out"))?; door.send("POST", cotton_client::transport::object::routes::ACT, Some(&sealer.advance(table)))?; } } client.nudge_sync(); Ok(answer) } fn text(row: &Value, key: &str) -> Option { row.get(key).and_then(Value::as_str).map(str::trim).filter(|s| !s.is_empty()).map(str::to_string) } fn connect(client: &ClientController, request: &Value) -> Result { let secret = Zeroizing::new(crate::phone::vault::private_key_arg(request)?); let (database, file) = copy(client)?; let grants = rows(&file, GRANTS)?; let sealer = crate::phone::personal_object::sealer_of(client, &database); for (id, data) in cotton_client::seal::kept_keys(&file).map_err(unreadable)? { sealer.learn(&id, &data); } drop(file); // A new connection takes what the person set for the others. let standing: Vec = rules::live(&grants).first().map(|g| [rules::list(g, "withheld"), rules::list(g, "off"), rules::list(g, "ask")].concat()).unwrap_or_default(); let versions: Vec<(String, u32)> = sealed_tables(client, &database).into_iter().filter(|t| !NEVER.contains(&t.as_str()) && !closed(t) && !standing.contains(t)).map(|t| { let v = sealer.version(&t); (t, v) }).collect(); if versions.is_empty() { return Err(MethodError::new("nothing_sealed", "this database seals no table yet: Claude reads it without a grant")); } let mut member_secret = Zeroizing::new([0u8; 32]); rand::rngs::OsRng.fill_bytes(member_secret.as_mut_slice()); let member_pub = cotton_core::vault::wrap::public_of(&member_secret); let mut id = [0u8; 16]; rand::rngs::OsRng.fill_bytes(&mut id); let member_id = format!("m{}", id.iter().map(|b| format!("{b:02x}")).collect::()); let grant = sign(client, &database, &member_id, &member_pub, &versions, &standing, &secret)?; let tables: Vec = versions.iter().map(|(t, _)| t.clone()).collect(); let answer = post( client, "assistant_allow", json!({ "member_id": member_id, "member_secret": URL_SAFE_NO_PAD.encode(member_secret.as_slice()), "name": "Claude", "tables": tables, "withheld": grant.withheld, "wrapped": grant.wrapped, "signer": grant.signer, "sig": grant.sig }), )?; note_handed(client, &database, &format!("connect:{member_id}"), &versions)?; client.nudge_sync(); let address = client.object_door().map(|door| format!("{}/mcp", door.address.origin().text.trim_start_matches("https://").trim_start_matches("http://"))).unwrap_or_else(|| "cottondb.com/mcp".into()); Ok(json!({ "grantId": answer["grant"], "address": address, "said": lines(client)?.say("account.connect_how", &[("address", &address)]).unwrap_or_default() })) } /// Noted in `_unlock_handed` once a wrap carrying the message table's files root went to a grant. const MESSAGE_FILES_HANDED: &str = "message#files"; /// After a pass: every live grant gets the keys inside its policy that this /// phone has not handed yet, wrapped with the data key the phone holds. A /// phone that holds none yet hands nothing and asks nothing. pub(crate) fn top_up(client: &ClientController) -> Result<(), MethodError> { if !client.signed_in() || client.object_door().is_none() || client.require_personal().is_err() { return Ok(()); } let (database, file) = copy(client)?; let grants = rows(&file, GRANTS)?; let live: Vec = rules::live(&grants).into_iter().cloned().collect(); if live.is_empty() { return Ok(()); } let Some(dk) = client.data_keys().data_key(&database).map_err(unreadable)? else { return Ok(()) }; let sealer = crate::phone::personal_object::sealer_of(client, &database); for (id, data) in cotton_client::seal::kept_keys(&file).map_err(unreadable)? { sealer.learn(&id, &data); } drop(file); let sealed = sealed_tables(client, &database); for g in live { let (Some(grant_id), Some(member_id), Some(member_pub), Some(request_id)) = (text(&g, "id"), text(&g, "member_id"), text(&g, "member_pub"), text(&g, "request_id")) else { continue }; let had = handed(client, &database, &request_id)?; let mut more = rules::to_hand(&g, &sealed, &had, |t| sealer.version(t)); // A grant made before a window could open a message's kept chat pictures (22 Nov 2026) holds no // files root for them: hand message once more, whose wrap now carries it (grant.rs `files`). let narrowed = ["withheld", "off", "ask"].iter().any(|k| rules::list(&g, k).iter().any(|t| t == "message")); let message_held = !narrowed && had.iter().chain(more.iter()).any(|(t, _)| t == "message"); if message_held && !had.iter().any(|(t, _)| t == MESSAGE_FILES_HANDED) && !more.iter().any(|(t, _)| t == "message") { more.push(("message".to_string(), sealer.version("message"))); } if more.is_empty() { continue; } let wrapped = addition(&dk, &database, &member_id, &key32(&member_pub, "the grant's member key")?, &more, &rules::list(&g, "withheld")).map_err(sealing)?; let tables: Vec = more.iter().map(|(t, _)| t.clone()).collect(); post(client, "assistant_add", json!({ "grant_id": grant_id, "tables": tables, "wrapped": wrapped }))?; if more.iter().any(|(t, _)| t == "message") { more.push((MESSAGE_FILES_HANDED.to_string(), 1)); } note_handed(client, &database, &request_id, &more)?; } Ok(()) }