Cotton code
232 lines · 11.4 KB · TypeScriptRaw
/** * What a Cotton MCP tool handler is handed: the personal object's rows, a * writer that runs every write through the definitions engine in one * transaction and one version, the vault, and who is calling. * * The handlers answer the shapes the Rust tools answered * (crates/cotton-tools/src/mcp/handlers), so the hooks and scripts that call * them work unchanged except for URL and token. A refusal is a ToolFailure * whose message is the exact sentence the Rust tool said. */import type { Definitions } from "../definitions.ts";import { machineWrite, type Journal } from "../changes.ts";import type { Engine, Outcome } from "../engine.ts";import type { Now } from "../recurrence.ts";import type { Env } from "../env.ts";import type { Cond, Stamps, Store, StoredRow } from "../store.ts";import type { TableKeys } from "../window.ts";export type Data = Record<string, unknown>;export class ToolFailure extends Error {  /** Extra MCP `structuredContent` a few refusals carry (database_mismatch, no tool draws this table). */  readonly structured?: Data;  constructor(message: string, structured?: Data) {    super(message);    this.structured = structured;  }}export function fail(message: string, structured?: Data): never {  throw new ToolFailure(message, structured);}/** Who presented the bearer: one mcp_token row, its scopes read at the front door. */export interface McpCaller {  tokenId: string;  name: string;  /** The scope words held: owner, coordinator, read, write, machines, lane:<name>. */  scopes: ReadonlySet<string>;  /** The lane a `lane:<name>` token is, or null. */  lane: string | null;  /** What the key may read, write and do outside (src/key_allow.ts); null or absent, a key made before allows: its scopes alone. */  allow?: import("../key_allow.ts").Allow | null;}export interface Writer {  readonly version: number;  readonly engine: Engine;  readonly outcome: Outcome;  /** Where this write's row changes are logged; a handler sets its `kind` when a write is said as other than it is (a bin's delete, a put back). */  readonly journal: Journal;  /** The write's moment and the database's zone, as a repeating todo's occurrences are worked out. */  readonly now: Now;  create(table: string, data: Data, keep?: Stamps & { id?: string }): StoredRow;  update(row: StoredRow, patch: Data, stamps?: Stamps): StoredRow;  delete(row: StoredRow): StoredRow;}export interface ToolContext {  readonly env: Env;  readonly store: Store;  readonly caller: McpCaller;  /**   * The one write guard (ADMIN KEYS 1b, 2, 4): answers `table` when this caller may write it, else refuses: a table that   * holds who may do what is never a key's, and a key with a list writes only what it names. Every writer goes   * through it (Writer.create/update/delete call it; undo, restore_version and a fetch before its write ask it first).   */  writable(table: string): string;  /** A definition write's guard (definition_writes `definable`): never a protected table; a key's list must read it. */  definable(table: string): string;  /**   * A `seal_key` row the object's own sealing reads for a write (a table's key version `v:<table>`, the arrival public key   * `arrival`): never a key's read, so never held to its list. Public halves and numbers only; a tool never answers it.   */  sealRow(id: string): StoredRow | null;  /** The personal database's id and name, as Rust answered them (`databaseId`, the initialize instructions). */  readonly database: { id: string; name: string };  /** `new Date().toISOString()` at the call: one clock per call. */  readonly now: string;  readonly timezone: string;  defs(): Definitions;  /**   * A table's live rows where every condition holds, oldest first, read a page   * at a time by a keyed cursor: no handler holds a whole table, and a list a   * person asks for pages in SQL (`store.select`, `store.count`).   */  scan(table: string, where?: Cond[]): Iterable<StoredRow>;  /** Live rows where one column equals a value (indexed for link columns). */  where(table: string, column: string, equals: unknown): StoredRow[];  get(table: string, id: string): StoredRow | null;  /** Run writes in one transaction and one version; a refusal inside rolls every write back. Each row write is logged (src/changes.ts). */  write<T>(fn: (w: Writer) => T): T;  /** The tool being called and the changes its writes logged, in order: the answer carries the first as its `change_id`. */  readonly trail: ChangeTrail;  /** The owner's other databases this endpoint reaches by `database` (Work), each an object of its own. */  readonly siblings: readonly Sibling[];  /** Run one tool call in a sibling's object as this same caller; answers its MCP result as it came. */  forward(sibling: Sibling, tool: string, args: Data): Promise<unknown>;  /**   * One act through the object's own `/v1/act` dispatch (src/acts.ts), as   * this caller: an owner token as the owner, any other as staff. Answers   * the act's answer; a refusal is thrown as the dispatch said it (`Refused`).   */  act(act: string, args: Data): Promise<Data>;  /** The object's media in R2 (src/media.ts), by bucket path. */  readonly media: MediaDoor;  /** What the object holds against its caps: its SQLite file and its media, in bytes. */  size(): { database: number; databaseCap: number; media: number; mediaCap: number; worker?: { id: string; at: string | null } | null };  seal(rowId: string, plaintext: string): Promise<string>;  open(rowId: string, sealed: string): Promise<string | null>;  /** This caller's unlock window over sealed tables (src/window.ts). */  readonly window: WindowDoor;  /** Notes that this caller's token called a memory tool (src/memory_lock.ts gate 1); absent off the personal object. */  readonly memoryRead?: () => void;  /** Notes that this call's token reads the open tables lock's tables (src/open_tables_lock.ts gate 1). */  readonly tablesRead?: () => void;  /** An agent in a chat (src/chat/agents.ts): the object's chat tables and this caller's member, when it is one. */  readonly agentChat?: AgentChatDoor;}export interface AgentChatDoor {  /** The agents' host on a personal object; null elsewhere. */  host(): import("../chat/agents.ts").AgentHost | null;  /** The member this caller's connection is (Connect Claude), opened for this call; null for a token that is none. */  member(): Promise<import("../chat/agents.ts").Member | null>;}/** The unlock window, as this caller's connection holds it (src/window.ts). */export interface WindowDoor {  /** The keys this caller's open window holds for a sealed table, or null: the guard, checked on every call. */  keys(table: string): Promise<TableKeys | null>;  /** Ask the owner's phone for a window (a waiting one for these tables is answered again, and a declined one naming any of them while its Not now stands, state "declined"); refused by name for a token that never gets one. */  request(tables: string[], reason: string, minutes: number): Promise<StoredRow>;  /** End every window this caller holds; answers how many. */  end(): number;  /** The tables this caller's open windows hold and when each ends. */  open(): { tables: string[]; ends_at: string; standing: boolean }[];  /** Write what was read (or written) in a window where the owner sees it: one `assistant_read` row per window the keys came from. */  log(keys: readonly TableKeys[], tool: string, rows: number, wrote?: boolean): void;  /** The keys `keys` handed out during this call, so the call is logged once it answers. */  readonly handed: TableKeys[];  /** Your Claude's standing grant answers for this caller: a timed request it still files is for a table the owner keeps asked each time. */  readonly standing?: boolean;}export interface MediaDoor {  /** A row's media key as its bucket path; a key that is not this database's is refused (`bucketKey`). */  at(key: string): string;  head(at: string): Promise<R2Object | null>;  get(at: string): Promise<R2ObjectBody | null>;  /** An image drawn at a size, as WebP bytes. */  draw(at: string, size: { width?: number; height?: number }): Promise<Uint8Array>;  /** Bytes already opened (a kept chat picture opened in a window), drawn as WebP at a size; never stored. */  drawBytes(bytes: Uint8Array, size: { width?: number; height?: number }): Promise<Uint8Array>;  /** Bytes stored as a media PUT stores them: the per-file and per-object caps, counted. */  store(at: string, bytes: Uint8Array, contentType: string): Promise<{ stored: boolean; bytes: number }>;  /** A file of `length` bytes written as `fill` makes it, counted as a PUT is; answers its SHA-256 (`storeStream`). */  storeStream(at: string, length: number, contentType: string, fill: (write: (chunk: Uint8Array) => Promise<void>) => Promise<void>): Promise<{ bytes: number; sha256: string }>;}/** One call's changes: the server names the tool before the handler runs and reads the ids after. */export interface ChangeTrail {  tool: string | null;  ids: number[];}/** * What a write's answer says of its changes: the first one's id to undo it by, and how many there were when more than * one. A machine's write or an import (src/changes.ts MACHINE_WRITERS) keeps only that it happened: not undoable. */export function changeIds(source: { ids: readonly number[]; tool?: string | null; kind?: string | null }): Data {  const ids = source.ids;  if (!ids.length) return {};  const kept = source.kind !== "machine" && source.kind !== "import" && !(source.tool && machineWrite(source.tool));  return { change_id: ids[0], undoable: kept, ...(ids.length > 1 ? { changes: ids.length } : {}) };}/** Content blocks a tool answers in place of its JSON text: a picture the caller can see, a file it can read. */export class Content {  readonly blocks: Data[];  constructor(blocks: Data[]) {    this.blocks = blocks;  }}export interface Sibling {  id: string;  name: string;  /** The object's slug on this Worker. */  slug: string;}export type Handler = (ctx: ToolContext, args: Data) => unknown | Promise<unknown>;// ── the argument readers the Rust handlers share (handlers/common.rs) ───────/** A string argument, trimmed; blank or not a string is absent. */export function optionalString(args: Data, key: string): string | null {  const v = args[key];  return typeof v === "string" && v.trim() ? v.trim() : null;}export function requireString(args: Data, key: string, message = `${key} is required`): string {  return optionalString(args, key) ?? fail(message);}export function optionalBool(args: Data, key: string): boolean | null {  const v = args[key];  return typeof v === "boolean" ? v : null;}/** `bounded_limit`: a finite number truncated and clamped to [1, max]; anything else the fallback. */export function boundedLimit(args: Data, fallback: number, max: number): number {  const v = args.limit;  if (typeof v !== "number" || !Number.isFinite(v)) return fallback;  return Math.min(max, Math.max(1, Math.trunc(v)));}/** `iso_timestamp`: any Date-parsable string in the one spelling, or null. */export function isoTimestamp(v: unknown): string | null {  if (typeof v !== "string" || !v.trim()) return null;  const t = Date.parse(v.trim());  return Number.isNaN(t) ? null : new Date(t).toISOString();}/** `derived_id`, cotton-rules' (src/import/ids.ts asks the rules module). */export { derivedId } from "../import/ids.ts";/** Text length the way JS (and the Rust handlers, in UTF-16 units) counts it. */export function units(text: string): number {  return text.length;}