//! AN AGENT IN A CHAT (owner, 23 Nov 2026): the person adds //! their own connected assistant to a Cotton group, where it reads what is //! said from then on, posts, replies and reacts, always marked as the agent's //! and never as the person. `assets/design/chat/CONTRACT.md` "An agent in a //! chat" is the contract; the group's op and fold are //! `cotton_core::chat::group` (`What::Agent`), the mark on the wire //! `cotton_core::chat::payload::AgentMark`. //! //! The agent holds no chat keys, so this phone carries both ways: //! - **the feed**: every message that has landed in or left this phone in a //! group holding one of the person's agents goes to the Worker sealed to that //! agent's member key (`w1`), which only its connection's tokens open //! ([`feed`], from `chat.flush` and `chat.incoming`); //! - **the acts**: what the agent asks comes back as a chat item of kind //! `agent`, a `c1` box the Worker sealed for this device; [`take`] checks the //! agent is the person's own and in that group, writes the message (or the //! reaction) and the outbox sends it as the person's own envelope with the //! mark, then [`report`] tells the Worker how it went. //! //! Which of the person's agents are in which group the Worker learns from //! [`tell_worker`], run from the group pass whenever the fold and what was told //! differ, so an admin's removal or the person leaving reaches it too. use rusqlite::types::Value as SqlValue; use serde_json::{json, Map, Value}; use cotton_client::transport::object::ObjectRefusal; use cotton_core::chat::group::{self, AgentId, State, What as Change}; use cotton_core::chat::payload::{Item, What}; use cotton_core::chat::{ids, seal, CHANNEL}; use cotton_core::rules::shell_lines::LineSet; use cotton_tools::mcp::handlers::common::{insert_row, update_row}; use super::cotton_chat::{ask, exists, iso, meta_value, my_number, namespace, now_ms, one, read, rows, text, touch_thread, words, write, ws, MESSAGES, THREADS}; use crate::methods::MethodError; use crate::shell::client::ClientController; pub const METHODS: [&str; 3] = ["chat.agent.add", "chat.agent.choices", "chat.agent.remove"]; /// The Worker's agent routes (apps/business/src/chat/agents.ts). pub mod routes { pub const CHAT: &str = "/v1/agents/chat"; pub const FEED: &str = "/v1/agents/feed"; pub const DONE: &str = "/v1/agents/done"; } /// Messages one feed pass hands over for a group at most: the rest go at the next pass. pub const FEED_BATCH: usize = 100; /// A quoted message's words in a feed item at most, in characters. const EXCERPT_CHARS: usize = 140; pub fn over(client: &ClientController, method: &str, request: &Value) -> Result { match method { "chat.agent.choices" => choices(client, request), "chat.agent.add" => add(client, request), "chat.agent.remove" => remove(client, request), other => Err(MethodError::new("unknown_method", format!("`{other}` is not an agent method"))), } } /// Comms' lines. pub(crate) fn lines() -> Option { LineSet::shipped("chat") } fn say(id: &str, fill: &[(&str, &str)]) -> String { lines().and_then(|l| l.say(id, fill)).unwrap_or_else(|| id.to_string()) } // ── who the person's agents are ───────────────────────────────────────── /// One of the person's connected assistants: the member its connection is, by the live grant Connect Claude made. #[derive(Debug, Clone)] pub(crate) struct Connected { pub id: String, pub name: String, pub key: [u8; 32], } /// The person's connected assistants, newest connection first, each once. pub(crate) fn connected(client: &ClientController) -> Vec { let Ok((_, file)) = super::unlock::copy(client) else { return Vec::new() }; let grants = super::unlock::rows(&file, super::unlock::GRANTS).unwrap_or_default(); let mut out: Vec = Vec::new(); for grant in cotton_core::rules::assistants::live(&grants) { let (Some(id), Some(key)) = (grant["member_id"].as_str(), grant["member_pub"].as_str().and_then(seal::key_from_text)) else { continue }; if !group::is_agent_id(id) || out.iter().any(|c| c.id == id) { continue; } let name = grant["client"].as_str().map(str::trim).filter(|n| group::agent_name_ok(n)).unwrap_or("Claude").to_string(); out.push(Connected { id: id.to_string(), name, key }); } out } /// The reaction actor an agent's reactions are kept under: never the person's own (`self`), never a number. pub(crate) fn actor(agent: &str) -> String { let tail: String = agent.chars().filter(|c| c.is_ascii_alphanumeric() || *c == '-').map(|c| c.to_ascii_lowercase()).take(25).collect(); format!("agent-{tail}") } // ── the methods ───────────────────────────────────────────────────────── fn group_of(client: &ClientController, thread: &str) -> Result<(super::chat_group::Kept, State, String), MethodError> { // A chat that is no Cotton group says so; anything else (this phone's copy not here yet, a read that failed) says // its own words: on the walk a group made before the copy arrived read "Agents join Cotton groups only". let kept = super::chat_group::kept_for(client, thread).map_err(|e| if e.code == "not_group" { words("not_group", "Agents join Cotton groups only.") } else { e })?; let state = group::fold(&kept.ops); let me = my_number(client).ok_or_else(super::cotton_chat::not_connected)?; if !state.made { return Err(words("not_group", "Agents join Cotton groups only.")); } Ok((kept, state, me)) } fn choices(client: &ClientController, request: &Value) -> Result { let thread = text(request, "thread")?.to_string(); let (_, state, me) = group_of(client, &thread)?; let agents: Vec = connected(client).into_iter().map(|c| json!({ "agent": c.id, "name": c.name, "in": state.is_agent_of(&c.id, &me) })).collect(); let connect = agents.is_empty(); Ok(json!({ "agents": agents, "connect": connect, "line": if connect { Value::from(say("app.group.agent_connect", &[])) } else { Value::Null } })) } fn add(client: &ClientController, request: &Value) -> Result { let thread = text(request, "thread")?.to_string(); let wanted = text(request, "agent")?.to_string(); let (_, state, me) = group_of(client, &thread)?; if !state.is_member(&me) { return Err(super::chat_group::refusal(group::Refusal::NotMember)); } let t = thread.clone(); let asked = read(client, "chat.agent.request", move |ctx| Ok(super::cotton_chat::request_state(ctx, &t)?.map(Value::from).unwrap_or(Value::Null)))?; if asked.as_str() == Some("pending") { return Err(words("not_joined", "Join the group to write in it.")); } let Some(agent) = connected(client).into_iter().find(|c| c.id == wanted) else { return Err(words("no_agent", &say("app.group.agent_connect", &[]))); }; super::chat_group::change(client, request, |_| Ok(Change::Agent { agent: AgentId { id: agent.id.clone(), name: agent.name.clone() }, on: true })) } fn remove(client: &ClientController, request: &Value) -> Result { let thread = text(request, "thread")?.to_string(); let wanted = text(request, "agent")?.to_string(); let (_, state, _) = group_of(client, &thread)?; let Some(seat) = state.agents.get(&wanted).filter(|a| a.on) else { return Err(super::chat_group::refusal(group::Refusal::NoOne)); }; let name = seat.name.clone(); super::chat_group::change(client, request, |_| Ok(Change::Agent { agent: AgentId { id: wanted.clone(), name }, on: false })) } /// The group's agents as its page lists them, after the people. pub(crate) fn info_agents(client: &ClientController, state: &State, me: &str) -> Value { let mut out: Vec = state .agents_on() .into_iter() .map(|(id, a)| { let yours = a.of == me; let of_name = if yours { say("app.group.you", &[]) } else { super::cotton_chat::person_of(client, &a.of).1.unwrap_or_else(|| a.of.clone()) }; let line = if yours { say("app.group.agent_yours", &[]) } else { say("app.group.agent_of", &[("name", &of_name)]) }; json!({ "agent": id, "name": a.name, "of": a.of, "ofName": of_name, "line": line, "yours": yours, "can": { "remove": yours || state.is_admin(me) } }) }) .collect(); out.sort_by(|a, b| (!a["yours"].as_bool().unwrap_or(false), a["name"].as_str().unwrap_or("").to_lowercase()).cmp(&(!b["yours"].as_bool().unwrap_or(false), b["name"].as_str().unwrap_or("").to_lowercase()))); Value::Array(out) } // ── telling the Worker ────────────────────────────────────────────────── /// The Worker told which of this person's agents are in `thread` now: each one new `on`, with the chat's name and /// its people sealed to the agent's own key, and each one gone `off` (its feed deleted there at once). pub(crate) fn tell_worker(client: &ClientController, thread: &str, state: &State, was: &[String], want: &[String]) -> Result<(), ObjectRefusal> { let agents = connected(client); for id in was.iter().filter(|id| !want.contains(id)) { ask(client, "POST", routes::CHAT, Some(&json!({ "agent": id, "thread": thread, "on": false })))?; } for id in want.iter().filter(|id| !was.contains(id)) { // A connection the person has since removed: there is no member left to tell. let Some(agent) = agents.iter().find(|c| &c.id == id) else { continue }; let people: Vec = state.members().iter().map(|n| json!({ "name": super::cotton_chat::person_of(client, n).1.unwrap_or_else(|| n.clone()) })).collect(); let about = json!({ "title": state.title, "members": people }); let sealed = cotton_core::vault::wrap::wrap(&agent.key, about.to_string().as_bytes()).ok_or_else(|| local("the chat could not be sealed for the agent"))?; ask(client, "POST", routes::CHAT, Some(&json!({ "agent": id, "thread": thread, "on": true, "name": agent.name, "about": sealed })))?; } Ok(()) } fn local(message: &str) -> ObjectRefusal { ObjectRefusal { status: 400, code: "refused".into(), message: message.into() } } // ── the feed ──────────────────────────────────────────────────────────── /// Every message in a group holding one of this person's agents, since that agent joined, not yet handed to it: /// sealed to each such agent and posted, then marked fed. Answers how many went. Never fails the pass it rides on. pub(crate) fn feed(client: &ClientController) -> usize { feed_pass(client).unwrap_or(0) } fn feed_pass(client: &ClientController) -> Result { // The number as this phone already knows it: asking would fetch the inbox, and the feed never takes what waits there. let Some(me) = super::cotton_chat::known_number(client) else { return Ok(0) }; let groups = read(client, "chat.agent.groups", |ctx| { if !super::cotton_chat::holds(ctx, THREADS, "group_log")? { return Ok(json!([])); } Ok(Value::Array(rows(ctx, &format!("SELECT id, group_log FROM {THREADS} WHERE workspace_id = ? AND group_log IS NOT NULL AND group_log LIKE '%\"agent\"%'"), &[ws(ctx)])?.into_iter().map(Value::Object).collect())) })?; // The grants are read only when a group holds an agent: most phones never get past here. if groups.as_array().is_none_or(Vec::is_empty) { return Ok(0); } let agents = connected(client); let mut fed = 0; for row in groups.as_array().into_iter().flatten() { let Some(kept) = row["group_log"].as_str().and_then(|t| serde_json::from_str::(t).ok()) else { continue }; let state = group::fold(&kept.ops); if !state.is_member(&me) { continue; } // Each of the person's agents here, with when it last came in: it reads from then on. let mine: Vec<(&Connected, i64)> = state .agents_on() .into_iter() .filter(|(_, a)| a.of == me) .filter_map(|(id, a)| { let joined = kept.ops.iter().filter(|op| op.rev == a.rev && matches!(&op.what, Change::Agent { agent, on: true } if &agent.id == id)).map(|op| op.at).max()?; Some((agents.iter().find(|c| &c.id == id)?, joined)) }) .collect(); if mine.is_empty() { continue; } let thread = row["id"].as_str().unwrap_or_default().to_string(); let since = iso(mine.iter().map(|(_, at)| *at).min().unwrap_or(0)); let t = thread.clone(); let found = read(client, "chat.agent.feed", move |ctx| { let seats = super::chat_group::SEATS; let rows_ = rows( ctx, &format!( "SELECT m.id, m.direction, m.body, m.sent_at, m.meta, m.reply_to_id, m.send_state, s.display_name AS seat_name, q.body AS quoted FROM {MESSAGES} m LEFT JOIN {seats} s ON s.id = m.sender_participant_id LEFT JOIN {MESSAGES} q ON q.id = m.reply_to_id WHERE m.workspace_id = ? AND m.thread_id = ? AND m.sent_at >= ? AND m.trashed_at IS NULL AND m.deleted_at IS NULL AND json_extract(m.meta, '$.system') IS NULL AND json_extract(m.meta, '$.cotton.fed') IS NULL ORDER BY m.sent_at, m.id LIMIT {FEED_BATCH}" ), &[ws(ctx), SqlValue::Text(t.clone()), SqlValue::Text(since.clone())], )?; Ok(Value::Array(rows_.into_iter().map(Value::Object).collect())) })?; let own_name = super::chat_people::own_profile(client).and_then(|p| p.name).unwrap_or_else(|| say("app.group.you", &[])); let mut items = Vec::new(); let mut done = Vec::new(); for m in found.as_array().into_iter().flatten() { let out = m["direction"].as_str() == Some("out"); // The person's own words count once they have gone; a message still on its way waits for the next pass. if out && !matches!(m["send_state"].as_str(), Some("sent" | "delivered" | "read")) { continue; } let meta = meta_value(&m["meta"]); let agent = meta["cotton"]["agent"].clone(); let at = m["sent_at"].as_str().unwrap_or_default(); let written_at = meta["cotton"]["written_at"].as_str().unwrap_or(at); for (c, joined) in &mine { if iso(*joined).as_str() > written_at.max(at) { continue; } let from = if out { me.clone() } else { meta["cotton"]["from"].as_str().unwrap_or_default().to_string() }; let name = if !agent.is_null() { agent["name"].as_str().unwrap_or("Claude").to_string() } else if out { own_name.clone() } else { m["seat_name"].as_str().map(str::to_string).unwrap_or_else(|| from.clone()) }; let pictures = meta["cotton"]["pictures"].as_array().map_or(0, Vec::len); let mut said = json!({ "v": 1, "id": m["id"], "at": at, "from": from, "name": name, "mine": out && agent.is_null(), "body": m["body"].as_str().unwrap_or_default(), "pictures": pictures }); if !agent.is_null() { said["agent"] = json!({ "id": agent["id"], "name": agent["name"], "self": agent["id"].as_str() == Some(c.id.as_str()) }); } if let Some(reply) = m["reply_to_id"].as_str() { let excerpt: String = m["quoted"].as_str().unwrap_or_default().chars().take(EXCERPT_CHARS).collect(); said["replyTo"] = json!({ "id": reply, "excerpt": excerpt }); } let Some(sealed) = cotton_core::vault::wrap::wrap(&c.key, said.to_string().as_bytes()) else { continue }; items.push(json!({ "agent": c.id, "thread": thread, "id": m["id"], "box": sealed })); } done.push(m["id"].as_str().unwrap_or_default().to_string()); } if done.is_empty() { continue; } if !items.is_empty() && ask(client, "POST", routes::FEED, Some(&json!({ "items": items }))).is_err() { continue; } fed += done.len(); write(client, "chat.agent.fed", move |ctx| { for id in &done { let row = one(ctx, &format!("SELECT meta FROM {MESSAGES} WHERE workspace_id = ? AND id = ?"), &[ws(ctx), SqlValue::Text(id.clone())])?; let mut meta = meta_value(row.as_ref().and_then(|r| r.get("meta")).unwrap_or(&Value::Null)); if !meta["cotton"].is_object() { meta["cotton"] = json!({}); } meta["cotton"]["fed"] = json!(true); let mut patch = Map::new(); patch.insert("meta".into(), meta); update_row(ctx, MESSAGES, id, patch).map_err(|f| f.to_string())?; } Ok(Value::Null) })?; } Ok(fed) } // ── the acts ──────────────────────────────────────────────────────────── /// What one act asks (the box the Worker sealed for this device). #[derive(Debug, Clone, serde::Deserialize)] struct Act { id: String, agent: String, thread: String, kind: String, #[serde(default)] body: Option, #[serde(default, rename = "replyTo")] reply_to: Option, #[serde(default)] message: Option, #[serde(default)] emoji: Option, } #[derive(Debug, Clone, serde::Deserialize)] struct Asked { v: u32, act: Act, } /// One `agent` item from this person's own object: opened, checked and written. Answers what changed (a thread to /// redraw) or nothing; a box that does not open, or an act this phone refuses, is reported and dropped. pub(crate) fn take(client: &ClientController, secret: &[u8; 32], item: &Item) -> Option { let opened = seal::open(secret, &item.sealed)?; let asked: Asked = serde_json::from_slice(&opened.payload).ok().filter(|a: &Asked| a.v == 1)?; let act = asked.act; match take_act(client, &act) { Ok(changed) => Some(changed), Err(why) => { report(client, &act.id, false, Some(&why.message)); None } } } fn take_act(client: &ClientController, act: &Act) -> Result { let not_in = || words("not_in_chat", "This agent is not in that chat."); let (_, state, me) = group_of(client, &act.thread).map_err(|_| not_in())?; if !state.is_member(&me) || !state.is_agent_of(&act.agent, &me) { return Err(not_in()); } let name = state.agents.get(&act.agent).map(|a| a.name.clone()).unwrap_or_else(|| "Claude".into()); let ns = namespace(client)?; let thread = act.thread.clone(); match act.kind.as_str() { "post" => { let words_ = act.body.as_deref().map(str::trim).filter(|b| !b.is_empty()).ok_or_else(|| words("empty", "Write something first."))?.to_string(); if words_.len() > cotton_core::chat::payload::BODY_MAX { return Err(words("too_long", "That message is too long to send.")); } // One row for the act on every phone of the person: its id comes from the act's. let client_id = format!("agent-{}", act.id.chars().filter(|c| c.is_ascii_alphanumeric() || *c == '-').take(48).collect::()); let id = ids::message_id(&ns, ids::ME, &client_id); let written = now_ms(client); let (a, r, i) = (act.clone(), act.reply_to.clone(), id.clone()); write(client, "chat.agent.post", move |ctx| { if exists(ctx, MESSAGES, &i)? { return Ok(Value::Null); } let now = iso(written); let reply_external = match &r { Some(row) => one(ctx, &format!("SELECT external_id FROM {MESSAGES} WHERE workspace_id = ? AND id = ? AND thread_id = ?"), &[ws(ctx), SqlValue::Text(row.clone()), SqlValue::Text(thread.clone())])?.and_then(|row| row.get("external_id").and_then(Value::as_str).map(str::to_string)), None => None, }; let mut columns = Map::new(); columns.insert("thread_id".into(), json!(thread)); columns.insert("direction".into(), json!("out")); columns.insert("channel".into(), json!(CHANNEL)); columns.insert("origin".into(), json!("live")); columns.insert("body".into(), json!(words_)); columns.insert("external_id".into(), json!(client_id)); columns.insert("sent_at".into(), json!(now)); columns.insert("send_state".into(), json!("queued")); columns.insert("send_attempts".into(), json!(0)); let mut meta = json!({ "cotton": { "written_at": now, "pending_pictures": [], "agent": { "id": a.agent, "name": name }, "act": a.id } }); let seconds = super::chat_timer::timer_of(ctx, &thread)?; super::chat_timer::stamp(&mut meta, written, seconds); columns.insert("meta".into(), meta); if let (Some(reply), Some(external)) = (&r, reply_external) { columns.insert("reply_to_id".into(), json!(reply)); columns.insert("reply_to_external_id".into(), json!(external)); } insert_row(ctx, MESSAGES, &i, columns).map_err(|f| f.to_string())?; touch_thread(ctx, &thread, &now, Some(&words_), false)?; Ok(Value::Null) })?; Ok(json!({ "thread": act.thread, "message": id })) } "react" => { let target = act.message.clone().ok_or_else(|| words("no_message", "That message isn't here any more."))?; let emoji = act.emoji.as_deref().map(str::trim).filter(|e| !e.is_empty() && e.len() <= cotton_core::chat::payload::EMOJI_MAX).ok_or_else(|| words("bad_emoji", "That reaction can't be sent."))?.to_string(); let (a, n, at) = (act.clone(), name, now_ms(client)); let answer = write(client, "chat.agent.react", move |ctx| { let Some(row) = one(ctx, &format!("SELECT id, external_id FROM {MESSAGES} WHERE workspace_id = ? AND id = ? AND thread_id = ?"), &[ws(ctx), SqlValue::Text(target.clone()), SqlValue::Text(thread.clone())])? else { return Ok(Value::Null); }; let external = row.get("external_id").and_then(Value::as_str).unwrap_or_default().to_string(); // Kept here under the agent's own actor, never the person's. let who = actor(&a.agent); let row_id = cotton_core::messages::ids::reaction_row_id(&target, &who).map_err(|e| e.to_string())?; let mut columns = Map::new(); columns.insert("emoji".into(), json!(emoji)); if exists(ctx, "cotton_msg_reactions", &row_id)? { update_row(ctx, "cotton_msg_reactions", &row_id, columns).map_err(|f| f.to_string())?; } else { columns.insert("thread_id".into(), json!(thread)); columns.insert("message_id".into(), json!(target)); columns.insert("actor".into(), json!(who)); insert_row(ctx, "cotton_msg_reactions", &row_id, columns).map_err(|f| f.to_string())?; } // Told to every member as the person's change, with the mark; the act is reported once it went. let list = one(ctx, &format!("SELECT changes_waiting FROM {THREADS} WHERE workspace_id = ? AND id = ?"), &[ws(ctx), SqlValue::Text(thread.clone())])?; let mut waiting: Vec = list.and_then(|r| r.get("changes_waiting").and_then(Value::as_str).and_then(|t| serde_json::from_str(t).ok())).unwrap_or_default(); if waiting.iter().any(|c| c["act"] == json!(a.id)) { return Ok(json!({ "thread": thread, "message": target })); } waiting.push(json!({ "id": format!("agent-{}", a.id), "what": What::React, "message": external, "emoji": emoji, "at": at, "agent": { "id": a.agent, "name": n }, "act": a.id })); let mut patch = Map::new(); patch.insert("changes_waiting".into(), json!(serde_json::to_string(&waiting).unwrap_or_default())); update_row(ctx, THREADS, &thread, patch).map_err(|f| f.to_string())?; Ok(json!({ "thread": thread, "message": target })) })?; if answer.is_null() { return Err(words("no_message", "That message isn't here any more.")); } Ok(answer) } _ => Err(words("bad_act", "This phone does not know that act.")), } } /// The Worker told how an act went, so the agent's `agent_chat_state` can say. A report that does not reach it is /// let go: the agent sees its words in the chat's feed once they went. pub(crate) fn report(client: &ClientController, act: &str, sent: bool, error: Option<&str>) { let mut body = json!({ "id": act, "state": if sent { "sent" } else { "failed" } }); if let Some(error) = error { body["error"] = json!(error); } let _ = ask(client, "POST", routes::DONE, Some(&body)); } /// After the outbox tried a message: when it was an agent's, its act reported. pub(crate) fn tried(client: &ClientController, message: &str, sent: bool, error: Option<&str>) { let id = message.to_string(); let Ok(meta) = read(client, "chat.agent.tried", move |ctx| Ok(one(ctx, &format!("SELECT meta FROM {MESSAGES} WHERE workspace_id = ? AND id = ?"), &[ws(ctx), SqlValue::Text(id.clone())])?.and_then(|r| r.get("meta").cloned()).unwrap_or(Value::Null))) else { return }; if let Some(act) = meta_value(&meta)["cotton"]["act"].as_str() { report(client, act, sent, error); } } /// The agent a message row's meta says wrote it: (id, name). pub(crate) fn agent_of(meta: &Value) -> Option<(String, String)> { let a = &meta["cotton"]["agent"]; Some((a["id"].as_str()?.to_string(), a["name"].as_str().unwrap_or("Claude").to_string())) }