/** * AN AGENT IN A CHAT (owner, 23 Nov 2026): the person's own * connected assistant, added by them to a Cotton group, reads what is said * there from then on and posts, replies and reacts, always marked as the * agent's. `assets/design/chat/CONTRACT.md` "An agent in a chat" is the * contract; the phone's half is crates/cotton-ffi/src/phone/chat_agent.rs. * * The agent holds no chat keys and the object none either, so the person's own * phones carry both ways: * * - `POST /v1/agents/chat { agent, thread, on, name?, about? }`: a phone of * the person says one of their agents (a member of `agent_member`, src/ * agent.ts) is in a chat or left it. `about` (the chat's name and people) is * sealed to that member's key. Leaving deletes the chat's feed at once. * - `POST /v1/agents/feed { items: [{ agent, thread, id, box }] }`: what was * said in a chat the agent is in, each box sealed (`w1`) to the member key, * which only the member's own connection opens (its tokens' carriers). Kept * once per (agent, thread, id), for 30 days and 500 a chat. * - What the agent asks over MCP (`agent_chat_post`, `agent_chat_react`) is * held for each of the person's devices that says it opens such acts * (`chat_device.can` holds "agent") as a chat item of kind `agent`, a `c1` * box sealed to that device's chat key, handed to its open sockets or * nudged by a silent push. Only this object makes such items: a peer's send * of that kind is refused (chat.ts `KINDS`). The object keeps the act's * state, never its words: `POST /v1/agents/done { id, state, error? }`. * * Every agent route answers for the person's own signed-in phones only, and * every MCP tool only for the calling connection's member, in the chats that * member is in: any other chat is `not_in_chat`. */importtype { Env } from"../env.ts";import { json, readJson, refuse } from"../http.ts";import { unwrap } from"../window.ts";importtype { Platform } from"../calling/push.ts";import { nudge } from"./push.ts";import { sealFor } from"./seal.ts";import { outsideText } from"../mcp/outside.ts";exportconst SCHEMA = `CREATE TABLE IF NOT EXISTS agent_chat (member_id TEXT NOT NULL, thread TEXT NOT NULL, name TEXT, about TEXT, since INTEGER NOT NULL, PRIMARY KEY (member_id, thread));CREATE TABLE IF NOT EXISTS agent_feed (seq INTEGER PRIMARY KEY AUTOINCREMENT, member_id TEXT NOT NULL, thread TEXT NOT NULL, id TEXT NOT NULL, box TEXT NOT NULL, at INTEGER NOT NULL, UNIQUE (member_id, thread, id));CREATE INDEX IF NOT EXISTS agent_feed_chat ON agent_feed (member_id, thread, seq);CREATE TABLE IF NOT EXISTS agent_act (id TEXT PRIMARY KEY, member_id TEXT NOT NULL, thread TEXT NOT NULL, kind TEXT NOT NULL, state TEXT NOT NULL, error TEXT, at INTEGER NOT NULL);CREATE INDEX IF NOT EXISTS agent_act_member ON agent_act (member_id, at);`;/** What a device may say it opens, beyond messages. */exportconst CAN = ["agent"] asconst;/** A chat's feed at most, newest kept. */exportconst FEED_MAX = 500;/** A feed item kept this long. */exportconst FEED_DAYS = 30;/** Items one feed post carries at most. */exportconst FEED_BATCH = 500;/** A sealed feed box at most, characters. */exportconst BOX_MAX = 64 * 1024;/** An agent's words at most, bytes (a message's, cotton-core payload BODY_MAX). */exportconst BODY_MAX = 16 * 1024;/** Acts one agent asks in an hour at most. */exportconst ACTS_PER_HOUR = 120;/** An act's state kept this long. */const ACT_DAYS = 7;const DAY = 86_400_000;const THREAD = /^[A-Za-z0-9_:.-]{1,128}$/;const MEMBER = /^[A-Za-z0-9_-]{1,64}$/;exportinterfaceAgentHost { sql: SqlStorage; env: Env; ownerPhone: string | null;/** The open chat sockets of one of this object's devices. */ sockets(deviceId: string): WebSocket[]; waitUntil(work: Promise<unknown>): void;}/** The tables made, and `chat_device.can` on an object made before it. */exportfunction ready(sql: SqlStorage): void { sql.exec(SCHEMA);const device = [...sql.exec("PRAGMA table_info(chat_device)")].map((c) => c.name);if (device.length && !device.includes("can")) sql.exec("ALTER TABLE chat_device ADD COLUMN can TEXT");}/** What a device said it opens (`POST /v1/chat/device { can }`), kept as the known words alone. */exportfunction keepCan(sql: SqlStorage, deviceId: string, said: unknown): void {const can = Array.isArray(said) ? CAN.filter((c) => said.includes(c)) : []; sql.exec("UPDATE chat_device SET can = ? WHERE device_id = ?", can.length ? can.join(",") : null, deviceId);}function isMember(sql: SqlStorage, id: string): boolean {return sql.exec("SELECT 1 FROM agent_member WHERE id = ?", id).toArray().length > 0;}function text(body: Record<string, unknown>, key: string, pattern: RegExp, said: string): string {const v = body[key];if (typeof v !== "string" || !pattern.test(v)) refuse(400, "bad_request", said);return v;}// ── the phone's routes ──────────────────────────────────────────────────/** The routes under /v1/agents, for a signed-in phone of the person; null for any other path. */exportasyncfunction route(host: AgentHost, deviceId: string | null, request: Request, url: URL): Promise<Response | null> {const path = url.pathname;if (!path.startsWith("/v1/agents/")) returnnull;if (!deviceId) refuse(401, "sign_in", "an agent's chats are told from a signed-in phone");if (request.method !== "POST") refuse(405, "method", "POST"); ready(host.sql);const body = await readJson(request);if (path === "/v1/agents/chat") return json(chat(host, body));if (path === "/v1/agents/feed") return json(feed(host, body));if (path === "/v1/agents/done") return json(done(host, body)); refuse(404, "not_found", "no such agent route");}function chat(host: AgentHost, body: Record<string, unknown>): { ok: true } {const member = text(body, "agent", MEMBER, "agent: the member id of one of the person's connected assistants");const thread = text(body, "thread", THREAD, "thread: the chat's id");if (!isMember(host.sql, member)) refuse(404, "no_agent", "no connected assistant has that id");if (body.on === true) {const about = typeof body.about === "string" && body.about.startsWith("w1:") && body.about.length <= BOX_MAX ? body.about : null;const name = typeof body.name === "string" ? body.name.trim().slice(0, 60) : null; host.sql.exec("INSERT INTO agent_chat (member_id, thread, name, about, since) VALUES (?, ?, ?, ?, ?) ON CONFLICT (member_id, thread) DO UPDATE SET name = COALESCE(excluded.name, agent_chat.name), about = COALESCE(excluded.about, agent_chat.about)", member, thread, name, about, Date.now()); } elseif (body.on === false) { host.sql.exec("DELETE FROM agent_chat WHERE member_id = ? AND thread = ?", member, thread); host.sql.exec("DELETE FROM agent_feed WHERE member_id = ? AND thread = ?", member, thread); } else refuse(400, "bad_request", "on: true or false");return { ok: true };}function feed(host: AgentHost, body: Record<string, unknown>): { ok: true; kept: number } {const items = Array.isArray(body.items) ? body.items : refuse(400, "bad_request", "items: [{ agent, thread, id, box }]");if (items.length > FEED_BATCH) refuse(413, "too_many", `at most ${FEED_BATCH} items a post`);const now = Date.now();let kept = 0;const chats = newSet<string>();for (const raw of items) {const item = (raw ?? {}) asRecord<string, unknown>;const [member, thread, id, box] = [item.agent, item.thread, item.id, item.box];if (typeof member !== "string" || typeof thread !== "string" || typeof id !== "string" || typeof box !== "string") continue;if (!MEMBER.test(member) || !THREAD.test(thread) || !THREAD.test(id) || !box.startsWith("w1:") || box.length > BOX_MAX) continue;// Only a chat the agent is in takes what is said there.if (!host.sql.exec("SELECT 1 FROM agent_chat WHERE member_id = ? AND thread = ?", member, thread).toArray().length) continue;if (host.sql.exec("SELECT 1 FROM agent_feed WHERE member_id = ? AND thread = ? AND id = ?", member, thread, id).toArray().length) continue; host.sql.exec("INSERT INTO agent_feed (member_id, thread, id, box, at) VALUES (?, ?, ?, ?, ?)", member, thread, id, box, now); kept += 1; chats.add(`${member}\u0000${thread}`); }for (const key of chats) {const [member, thread] = key.split("\u0000") as [string, string]; host.sql.exec("DELETE FROM agent_feed WHERE member_id = ? AND thread = ? AND (at < ? OR seq NOT IN (SELECT seq FROM agent_feed WHERE member_id = ? AND thread = ? ORDER BY seq DESC LIMIT ?))", member, thread, now - FEED_DAYS * DAY, member, thread, FEED_MAX); }return { ok: true, kept };}function done(host: AgentHost, body: Record<string, unknown>): { ok: true } {const id = text(body, "id", MEMBER, "id: the act's id");const state = body.state === "sent" || body.state === "failed" ? body.state : refuse(400, "bad_request", "state: sent or failed");const error = typeof body.error === "string" ? body.error.slice(0, 300) : null;// A failure never takes back a sent: the person's other phone may have sent it first. host.sql.exec("UPDATE agent_act SET state = ?, error = ? WHERE id = ? AND state != 'sent'", state, state === "failed" ? error : null, id);return { ok: true };}// ── the agent's side (MCP) ──────────────────────────────────────────────/** The calling connection's member, opened for this call (src/agent.ts `Agents.opened`). */exportinterfaceMember { memberId: string; secret: Uint8Array; pub: Uint8Array;}exportclassNotInChatextendsError {readonly code = "not_in_chat"; constructor() {super("You are not in that chat: the owner adds you to a chat from its page in Comms."); }}asyncfunction opened(m: Member, box: string | null): Promise<Record<string, unknown> | null> {if (!box) returnnull;const plain = await unwrap(m.secret, m.pub, box);if (!plain) returnnull;try {return JSON.parse(newTextDecoder().decode(plain)) asRecord<string, unknown>; } catch {returnnull; } finally { plain.fill(0); }}function inChat(sql: SqlStorage, m: Member, thread: unknown): string {if (typeof thread !== "string" || !sql.exec("SELECT 1 FROM agent_chat WHERE member_id = ? AND thread = ?", m.memberId, thread).toArray().length) thrownewNotInChat();return thread;}/** `agent_chats`: the chats this member is in, newest first. */exportasyncfunction chats(host: AgentHost, m: Member): Promise<{ chats: { thread: string; title: string | null; members: string[]; since: string }[] }> { ready(host.sql);const rows = host.sql.exec<{ thread: string; about: string | null; since: number }>("SELECT thread, about, since FROM agent_chat WHERE member_id = ? ORDER BY since DESC", m.memberId).toArray();const out = [];for (const r of rows) {const about = await opened(m, r.about);const members = Array.isArray(about?.members) ? (about.members as { name?: unknown }[]).map((p) => String(p?.name ?? "")).filter(Boolean) : []; out.push({ thread: r.thread, title: typeof about?.title === "string" ? about.title : null, members, since: newDate(r.since).toISOString() }); }return { chats: out };}/** `agent_chat_read`: what came after `after` (absent: the last `limit`), oldest first, and the mark to pass back. */exportasyncfunction readChat(host: AgentHost, m: Member, args: Record<string, unknown>): Promise<{ thread: string; messages: Record<string, unknown>[]; mark: number }> { ready(host.sql);const thread = inChat(host.sql, m, args.thread);const limit = typeof args.limit === "number" && Number.isInteger(args.limit) ? Math.min(Math.max(args.limit, 1), 200) : 50;const after = typeof args.after === "number" && Number.isInteger(args.after) && args.after >= 0 ? args.after : null;const rows = after === null ? host.sql.exec<{ seq: number; box: string }>("SELECT seq, box FROM agent_feed WHERE member_id = ? AND thread = ? ORDER BY seq DESC LIMIT ?", m.memberId, thread, limit).toArray().reverse() : host.sql.exec<{ seq: number; box: string }>("SELECT seq, box FROM agent_feed WHERE member_id = ? AND thread = ? AND seq > ? ORDER BY seq LIMIT ?", m.memberId, thread, after, limit).toArray();const messages: Record<string, unknown>[] = [];for (const r of rows) {const said = await opened(m, r.box);if (!said) continue;const message: Record<string, unknown> = { id: said.id, at: said.at, from: said.from, name: said.name, mine: said.mine === true, body: said.body ?? "", pictures: said.pictures ?? 0 };if (said.agent) message.agent = said.agent;if (said.replyTo) message.reply_to = said.replyTo;// AUDIT C 4: another member's words are outside content (src/mcp/outside.ts); the owner's and the agents' are not.if (said.mine !== true && !said.agent) message.outside = outsideText(typeof said.name === "string" && said.name ? said.name : null); messages.push(message); }const mark = rows.length ? rows[rows.length - 1]!.seq : (after ?? 0);return { thread, messages, mark };}/** `agent_chat_post` and `agent_chat_react`: the act held for each of the person's phones that opens acts. */exportasyncfunction act(host: AgentHost, m: Member, kind: "post" | "react", args: Record<string, unknown>): Promise<{ id: string; state: "waiting" | "failed"; error?: string }> { ready(host.sql);const thread = inChat(host.sql, m, args.thread);const now = Date.now(); host.sql.exec("DELETE FROM agent_act WHERE at < ?", now - ACT_DAYS * DAY);const recent = host.sql.exec<{ n: number }>("SELECT COUNT(*) AS n FROM agent_act WHERE member_id = ? AND at > ?", m.memberId, now - 3_600_000).one().n;if (recent >= ACTS_PER_HOUR) thrownewError(`At most ${ACTS_PER_HOUR} posts and reactions an hour; try again later.`);const said: Record<string, unknown> = { id: crypto.randomUUID(), agent: m.memberId, thread, kind };if (kind === "post") {const body = typeof args.body === "string" ? args.body.trim() : "";if (!body) thrownewError("body: what you say, some words.");if (newTextEncoder().encode(body).length > BODY_MAX) thrownewError("body: 16 KB at most."); said.body = body;if (typeof args.reply_to === "string" && THREAD.test(args.reply_to)) said.replyTo = args.reply_to; } else {const emoji = typeof args.emoji === "string" ? args.emoji.trim() : "";if (!emoji || newTextEncoder().encode(emoji).length > 32) thrownewError("emoji: one emoji.");if (typeof args.message !== "string" || !THREAD.test(args.message)) thrownewError("message: a message id from agent_chat_read."); said.message = args.message; said.emoji = emoji; }const id = said.id as string;const devices = host.sql .exec<{ device_id: string; public_key: string; platform: Platform | null; token: string | null; topic: string | null; sandbox: number }>("SELECT device_id, public_key, platform, token, topic, sandbox FROM chat_device WHERE ',' || COALESCE(can, '') || ',' LIKE '%,agent,%'") .toArray();if (!devices.length) {const error = "None of the owner's phones can carry an agent's words yet: Comms needs updating."; host.sql.exec("INSERT INTO agent_act (id, member_id, thread, kind, state, error, at) VALUES (?, ?, ?, ?, 'failed', ?, ?)", id, m.memberId, thread, kind, error, now);return { id, state: "failed", error }; } host.sql.exec("INSERT INTO agent_act (id, member_id, thread, kind, state, error, at) VALUES (?, ?, ?, ?, 'waiting', NULL, ?)", id, m.memberId, thread, kind, now);for (const d of devices) {const box = await sealFor(d.public_key, { v: 1, act: said });if (!box) continue;const item = { id, kind: "agent", peer: host.ownerPhone ?? "", out: false, request: false, box, at: now, group: null }; host.sql.exec("INSERT OR IGNORE INTO chat_held (device_id, kind, id, peer, out, request, box, at, group_id) VALUES (?, 'agent', ?, ?, 0, 0, ?, ?, NULL)", d.device_id, id, item.peer, box, now);let handed = false;for (const ws of host.sockets(d.device_id)) {try { ws.send(JSON.stringify({ t: "envelope", item })); handed = true; } catch {// Closing as it was sent to: the item stays held. } }if (!handed && d.platform && d.token) {const to = { platform: d.platform, token: d.token, topic: d.topic ?? "", sandbox: d.sandbox === 1 }; host.waitUntil(nudge(host.env, to).catch(() => undefined)); } }return { id, state: "waiting" };}/** `agent_chat_state`. */exportfunction stateOf(host: AgentHost, m: Member, id: unknown): { id: string; state: string; error?: string } { ready(host.sql);const row = typeof id === "string" ? host.sql.exec<{ state: string; error: string | null }>("SELECT state, error FROM agent_act WHERE id = ? AND member_id = ?", id, m.memberId).toArray()[0] : undefined;if (!row) thrownewError("No post or reaction of yours has that id (an act's state is kept 7 days).");return { id: id as string, state: row.state, ...(row.error ? { error: row.error } : {}) };}