Cotton code
33 lines · 1.7 KB · TypeScriptRaw
/** * An agent in a chat over Cotton MCP (CONTRACT "An agent in a chat"; src/chat/agents.ts): the calling connection's * agent reads, posts and reacts in the Comms chats the owner added it to, and nowhere else. */import { fail, type Data, type Handler, type ToolContext } from "../context.ts";import * as agents from "../../chat/agents.ts";async function door(ctx: ToolContext): Promise<{ host: agents.AgentHost; member: agents.Member }> {  const host = ctx.agentChat?.host() ?? null;  if (!host) fail("Agents join chats in a person's own Cotton only.", { code: "no_chats" });  const member = (await ctx.agentChat?.member()) ?? null;  if (!member) fail("This connection is no agent of the owner's: connect it under You → Your Claude, then the owner adds it to a chat from the chat's page.", { code: "not_an_agent" });  return { host, member };}async function run<T>(ctx: ToolContext, work: (host: agents.AgentHost, member: agents.Member) => Promise<T> | T): Promise<T> {  const { host, member } = await door(ctx);  try {    return await work(host, member);  } catch (e) {    if (e instanceof agents.NotInChat) fail(e.message, { code: e.code });    if (e instanceof Error && !(e as { structured?: unknown }).structured) fail(e.message);    throw e;  }}export const AGENT_CHAT_HANDLERS: Record<string, Handler> = {  agent_chats: (ctx) => run(ctx, (h, m) => agents.chats(h, m)),  agent_chat_read: (ctx, args: Data) => run(ctx, (h, m) => agents.readChat(h, m, args)),  agent_chat_post: (ctx, args: Data) => run(ctx, (h, m) => agents.act(h, m, "post", args)),  agent_chat_react: (ctx, args: Data) => run(ctx, (h, m) => agents.act(h, m, "react", args)),  agent_chat_state: (ctx, args: Data) => run(ctx, (h, m) => agents.stateOf(h, m, args.id)),};