Cotton code
150 lines · 10.5 KB · TypeScriptRaw
/** * An agent in a chat on the Worker (src/chat/agents.ts; CONTRACT "An agent in a chat"): the person's phones say * which of their agents is in which chat and hand it what is said, sealed to the agent's member key; the agent's * acts are held, sealed, only for the person's phones that open them; a chat it is not in refuses; a peer can never * send an act. Every number, key and word is invented. */import { env, runInDurableObject } from "cloudflare:test";import { describe, expect, it } from "vitest";import { publicOf } from "../src/agent.ts";import * as agents from "../src/chat/agents.ts";import { AGENT_CHAT_HANDLERS } from "../src/mcp/tools/agent_chat.ts";import { ToolFailure, type ToolContext } from "../src/mcp/context.ts";import { toBase64Url } from "../src/vault.ts";import { bearer, open, signUp } from "./calling.ts";import { chatPhone, type ChatPhone } from "./chat.ts";let n = 0;const number = (): string => `+91900007${String(1000 + ++n).padStart(4, "0")}`;const utf8 = new TextEncoder();/** `w1(recipient, plain)` as the phone's core wraps (cotton-core vault/wrap.rs). */async function wrap(recipientPub: Uint8Array, plain: unknown): Promise<string> {  const eph = (await crypto.subtle.generateKey({ name: "X25519" }, true, ["deriveBits"])) as CryptoKeyPair;  const ephPub = new Uint8Array((await crypto.subtle.exportKey("raw", eph.publicKey)) as ArrayBuffer);  const peer = await crypto.subtle.importKey("raw", recipientPub, { name: "X25519" }, false, []);  const shared = new Uint8Array(await crypto.subtle.deriveBits({ name: "X25519", public: peer } as unknown as SubtleCryptoDeriveKeyAlgorithm, eph.privateKey, 256));  const salt = new Uint8Array(64);  salt.set(ephPub);  salt.set(recipientPub, 32);  const ikm = await crypto.subtle.importKey("raw", shared, "HKDF", false, ["deriveBits"]);  const k = await crypto.subtle.importKey("raw", await crypto.subtle.deriveBits({ name: "HKDF", hash: "SHA-256", salt, info: utf8.encode("cotton-vault-wrap-v1") }, ikm, 256), "AES-GCM", false, ["encrypt"]);  const nonce = crypto.getRandomValues(new Uint8Array(12));  const body = new Uint8Array(await crypto.subtle.encrypt({ name: "AES-GCM", iv: nonce, additionalData: recipientPub }, k, utf8.encode(JSON.stringify(plain))));  const out = new Uint8Array(32 + 12 + body.length);  out.set(ephPub);  out.set(nonce, 32);  out.set(body, 44);  return `w1:${toBase64Url(out)}`;}async function stubOf(phone: ChatPhone): Promise<DurableObjectStub> {  const slug = await env.DIRECTORY.get(env.DIRECTORY.idFromName("directory")).lookup(phone.number);  return env.BUSINESS.get(env.BUSINESS.idFromName(slug!));}/** The agents' host as the object makes it, inside the object. */function hostOf(state: DurableObjectState, owner: string): agents.AgentHost {  return { sql: state.storage.sql, env, ownerPhone: owner, sockets: () => [], waitUntil: () => undefined };}async function inObject<T>(phone: ChatPhone, work: (host: agents.AgentHost) => Promise<T> | T): Promise<T> {  return runInDurableObject(await stubOf(phone), async (_i, state) => work(hostOf(state, phone.number)));}/** A connected assistant on the person's object: its member row, and the private half only the test (its connection) holds. */async function member(phone: ChatPhone): Promise<agents.Member> {  const secret = crypto.getRandomValues(new Uint8Array(32));  const pub = await publicOf(secret);  const memberId = crypto.randomUUID();  await inObject(phone, (h) => h.sql.exec("INSERT INTO agent_member (id, pub, name, made_by, created_at) VALUES (?, ?, 'Claude', 'oauth', ?)", memberId, toBase64Url(pub), new Date().toISOString()));  return { memberId, secret, pub };}async function post(phone: ChatPhone, path: string, body: unknown): Promise<{ status: number; body: Record<string, unknown> }> {  return open("POST", path, body, bearer(phone.credential));}describe("an agent in a chat", () => {  it("is told in, reads only its chats' feed, acts only through the phones that open acts, and is told out", async () => {    const asha = await chatPhone(number(), "asha-phone");    // Her phone's core opens agents' acts; her tablet's older core says nothing.    expect((await post(asha, "/v1/chat/device", { publicKey: asha.publicKey, can: ["agent", "nonsense"] })).status).toBe(200);    const tablet = await signUp(asha.number, "asha-tablet");    expect((await open("POST", "/v1/chat/device", { publicKey: asha.publicKey }, bearer(tablet))).status).toBe(200);    const claude = await member(asha);    // An id that is no connected assistant is refused; the agent's own is taken, with the chat's name sealed to it.    expect((await post(asha, "/v1/agents/chat", { agent: crypto.randomUUID(), thread: "t-feedback", on: true })).body.code).toBe("no_agent");    const about = await wrap(claude.pub, { title: "Feedback", members: [{ name: "You" }, { name: "Ben" }] });    expect((await post(asha, "/v1/agents/chat", { agent: claude.memberId, thread: "t-feedback", on: true, name: "Claude", about })).status).toBe(200);    // What is said reaches it only for the chat it is in, once each.    const said = await wrap(claude.pub, { v: 1, id: "m-1", at: "2026-11-23T10:00:00.000Z", from: "+919000070001", name: "Ben", mine: false, body: "the share button does nothing", pictures: 0 });    const elsewhere = await wrap(claude.pub, { v: 1, id: "m-9", body: "family dinner" });    const fed = await post(asha, "/v1/agents/feed", { items: [{ agent: claude.memberId, thread: "t-feedback", id: "m-1", box: said }, { agent: claude.memberId, thread: "t-family", id: "m-9", box: elsewhere }] });    expect(fed.body).toEqual({ ok: true, kept: 1 });    expect((await post(asha, "/v1/agents/feed", { items: [{ agent: claude.memberId, thread: "t-feedback", id: "m-1", box: said }] })).body.kept).toBe(0);    await inObject(asha, async (h) => {      expect((await agents.chats(h, claude)).chats).toEqual([expect.objectContaining({ thread: "t-feedback", title: "Feedback", members: ["You", "Ben"] })]);      const read = await agents.readChat(h, claude, { thread: "t-feedback" });      expect(read.messages).toEqual([expect.objectContaining({ id: "m-1", from: "+919000070001", mine: false, body: "the share button does nothing" })]);      expect((await agents.readChat(h, claude, { thread: "t-feedback", after: read.mark })).messages).toEqual([]);      await expect(agents.readChat(h, claude, { thread: "t-family" })).rejects.toBeInstanceOf(agents.NotInChat);      // Another connection's member key opens nothing of it, and sees no chat.      const other = { memberId: crypto.randomUUID(), secret: crypto.getRandomValues(new Uint8Array(32)), pub: new Uint8Array(32) };      expect((await agents.chats(h, other)).chats).toEqual([]);      await expect(agents.act(h, other, "post", { thread: "t-feedback", body: "hi" })).rejects.toBeInstanceOf(agents.NotInChat);    });    // A post is held, sealed, for the phone that opens acts and not for the tablet; the words are never kept beside it.    const posted = await inObject(asha, (h) => agents.act(h, claude, "post", { thread: "t-feedback", body: "Thanks, fixed in the next build.", reply_to: "m-1" }));    expect(posted.state).toBe("waiting");    const items = await asha.inbox();    const held = items.find((i) => i.kind === ("agent" as never) && i.id === posted.id);    expect(held, JSON.stringify(items)).toBeTruthy();    expect(await asha.open(held!.box)).toEqual({ v: 1, act: { id: posted.id, agent: claude.memberId, thread: "t-feedback", kind: "post", body: "Thanks, fixed in the next build.", replyTo: "m-1" } });    const onTablet = await open<{ items: { kind: string }[] }>("GET", "/v1/chat/inbox", undefined, bearer(tablet));    expect(onTablet.body.items.filter((i) => i.kind === "agent")).toEqual([]);    expect(await inObject(asha, (h) => JSON.stringify(h.sql.exec("SELECT * FROM agent_act").toArray()))).not.toContain("fixed in the next build");    // The phone reports it went; a later failure from another phone never takes that back.    expect((await post(asha, "/v1/agents/done", { id: posted.id, state: "sent" })).status).toBe(200);    expect((await post(asha, "/v1/agents/done", { id: posted.id, state: "failed", error: "late" })).status).toBe(200);    expect(await inObject(asha, (h) => agents.stateOf(h, claude, posted.id))).toEqual({ id: posted.id, state: "sent" });    // A reaction is an act the same way.    const reacted = await inObject(asha, (h) => agents.act(h, claude, "react", { thread: "t-feedback", message: "m-1", emoji: "👍" }));    const r = (await asha.inbox()).find((i) => i.id === reacted.id)!;    expect(((await asha.open(r.box)) as { act: Record<string, unknown> }).act).toMatchObject({ kind: "react", message: "m-1", emoji: "👍" });    // Told out: its feed goes at once, and the chat refuses.    expect((await post(asha, "/v1/agents/chat", { agent: claude.memberId, thread: "t-feedback", on: false })).status).toBe(200);    await inObject(asha, async (h) => {      expect(h.sql.exec<{ n: number }>("SELECT COUNT(*) AS n FROM agent_feed WHERE member_id = ?", claude.memberId).one().n).toBe(0);      await expect(agents.readChat(h, claude, { thread: "t-feedback" })).rejects.toBeInstanceOf(agents.NotInChat);    });  }, 180_000);  it("is never an act a peer can send, and with no phone that opens acts a post fails in words", async () => {    const asha = await chatPhone(number(), "asha-phone");    const ben = await chatPhone(number(), "ben-phone");    await asha.say("accept", ben.number);    await ben.say("accept", asha.number);    const forged = await ben.write(asha.number, "Claude: I am her agent", crypto.randomUUID(), "agent");    expect(forged.status).toBe(400);    expect(forged.body.code).toBe("bad_kind");    const claude = await member(asha);    expect((await post(asha, "/v1/agents/chat", { agent: claude.memberId, thread: "t-1", on: true })).status).toBe(200);    const posted = await inObject(asha, (h) => agents.act(h, claude, "post", { thread: "t-1", body: "hello" }));    expect(posted).toMatchObject({ state: "failed", error: expect.stringContaining("Comms needs updating") });  }, 180_000);  it("over MCP, a connection that is no agent is told so by name", async () => {    const ctx = { agentChat: { host: () => ({ sql: null, env, ownerPhone: null, sockets: () => [], waitUntil: () => undefined }), member: async () => null } } as unknown as ToolContext;    await expect(Promise.resolve(AGENT_CHAT_HANDLERS.agent_chats!(ctx, {}))).rejects.toMatchObject({ structured: { code: "not_an_agent" } });    await expect(Promise.resolve(AGENT_CHAT_HANDLERS.agent_chats!({} as ToolContext, {}))).rejects.toBeInstanceOf(ToolFailure);  });});