Cotton code
380 lines · 20.2 KB · TypeScriptRaw
/** * The media a record names, through Cotton MCP: the bytes the object keeps * in R2 under the record's own key (src/media.ts), never a copy. * * - `get_media { id, table?, index?, width?, height? }`: a photo comes as a picture *   the caller sees — whole when it is small and a kind a reader draws, else *   drawn as WebP through the Images binding as a sized GET draws it; any *   other file comes whole as an embedded resource, up to FILE_INLINE_MAX. * - `put_document { name, kind?, bytes_base64 | url, content_type? }`: stores *   a file as the import routes store media — content-addressed under *   `<database id>/documents/<sha256>.<ext>`, counted against the object's *   media, at most MEDIA_MAX_BYTES — and makes its document record. */import { isSealedType, MEDIA_MAX_BYTES } from "../../media.ts";import { Content, fail, optionalString, requireString, type Data, type Handler, type ToolContext } from "../context.ts";import { changeJson, readData, recordJson } from "./records/shape.ts";import { lowerFirst, noLongerHere, resolveTable, tableArg, visibleTables, type Table } from "./records/table.ts";import { arriving } from "./records/write.ts";import { isSealedRow } from "../../seal.ts";import { isSealedTable, openStored, windowFor } from "./window.ts";import { kindOfKey, openF1, personFileKey, tableOfFileKind } from "../../table_files.ts";/** The most a picture is handed over whole; past it, it is drawn smaller. */const IMAGE_INLINE_MAX = 3.5 * 1024 * 1024;/** The longest side a picture is drawn at when the caller names no size. */const DRAWN_SIDE = 1568;/** The most any other file is handed over. */const FILE_INLINE_MAX = 8 * 1024 * 1024;/** The picture kinds a reader takes as they are. */const READABLE_IMAGES = new Set(["image/jpeg", "image/png", "image/gif", "image/webp"]);export const TYPES_BY_EXTENSION: Record<string, string> = {  pdf: "application/pdf",  jpg: "image/jpeg",  jpeg: "image/jpeg",  png: "image/png",  gif: "image/gif",  webp: "image/webp",  heic: "image/heic",  txt: "text/plain",  csv: "text/csv",  json: "application/json",  doc: "application/msword",  docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",  xls: "application/vnd.ms-excel",  xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",};function mediaColumns(t: Table): string[] {  return t.columns.filter((c) => (c.type === "photo" || c.type === "file") && (c.computed === undefined || c.computed === null)).map((c) => c.key);}/** One attachment's key: a bare key, `{ ref, name }`, or a message's `{ key, contentType, … }`. */function oneKey(v: unknown): string | null {  if (typeof v === "string" && v.trim()) return v.trim();  if (v && typeof v === "object") {    for (const k of ["ref", "key"]) {      const at = (v as Data)[k];      if (typeof at === "string" && at.trim()) return at.trim();    }  }  return null;}/** * The keys a photo or file column holds, in order: one key, or a list of attachments (a message's * `media`: a chat picture sent in Comms is kept there, `cottonKept`, and has no photo row of its own). *//** A value's shape, never what it holds: "absent", "text of 120 characters starting [", "a list of 2: objects with fields key, name". */export function shapeOf(v: unknown): string {  if (v === undefined) return "absent";  if (v === null) return "null";  if (typeof v === "string") return v.length ? `text of ${v.length} characters starting ${JSON.stringify(v[0])}` : "empty text";  if (Array.isArray(v)) {    if (!v.length) return "an empty list";    const kinds = [...new Set(v.map((e) => (e && typeof e === "object" && !Array.isArray(e) ? `objects with fields ${Object.keys(e).sort().join(", ")}` : Array.isArray(e) ? "lists" : typeof e)))];    return `a list of ${v.length}: ${kinds.join("; ")}`;  }  if (typeof v === "object") return `an object with fields ${Object.keys(v as object).sort().join(", ") || "none"}`;  return typeof v;}/** A media key's kind alone, for a refusal: `<db>/messages/…`, never the rest. */function kindOf(key: string, database: string): string {  const [db, kind] = key.split("/");  return `${db === database ? "<db>" : "<another database>"}/${kind ?? "?"}/…`;}export function keysOf(v: unknown): string[] {  let value = v;  if (typeof value === "string" && value.trim().startsWith("[")) {    try {      value = JSON.parse(value);    } catch {      return [];    }  }  if (Array.isArray(value)) return value.map(oneKey).filter((k): k is string => k !== null);  const one = oneKey(value);  return one === null ? [] : [one];}export function extensionOf(name: string): string | null {  const m = /\.([A-Za-z0-9]{1,8})$/.exec(name);  return m ? m[1]!.toLowerCase() : null;}function typeOfKey(key: string): string {  return TYPES_BY_EXTENSION[extensionOf(key) ?? ""] ?? "application/octet-stream";}function base64(bytes: Uint8Array): string {  let s = "";  for (let i = 0; i < bytes.length; i += 0x8000) s += String.fromCharCode(...bytes.subarray(i, i + 0x8000));  return btoa(s);}function size(args: Data, key: "width" | "height"): number | undefined {  const v = args[key];  if (v === undefined || v === null) return undefined;  if (typeof v !== "number" || !Number.isInteger(v) || v < 1 || v > 4096) fail(`${key} is 1 to 4096 pixels`);  return v;}function megabytes(bytes: number): string {  return `${(bytes / 1024 / 1024).toFixed(1)} MB`;}async function getMedia(ctx: ToolContext, args: Data): Promise<Content> {  const id = requireString(args, "id", "id is required: the id of a photo, a document or another record that keeps a file");  const width = size(args, "width");  const height = size(args, "height");  const index = args.index === undefined || args.index === null ? 0 : args.index;  if (typeof index !== "number" || !Number.isInteger(index) || index < 0) fail("index is the attachment's place in the record's list, from 0");  const tables = args.table !== undefined && args.table !== null ? [resolveTable(ctx, tableArg(args), args.table)] : visibleTables(ctx).filter((t) => mediaColumns(t).length);  // Each refusal names its step (r3, 22 Nov 2026), so one call says where a file was not found;  // what it says of a value is its shape alone (types, counts, field names), never what it holds.  const step: (name: string, words: string) => never = (name, words) => fail(`${words} [get_media r3, step ${name}]`);  let found: { t: Table; data: Data; sealed: boolean } | null = null;  for (const t of tables) {    const row = ctx.get(t.id, id);    if (row && t.binned(row) === null) {      // A sealed table's row (a message) is read in the caller's window, as get_record reads it: its stored      // form holds its columns only sealed, so its files are not there to find until it is opened (owner, 22 Nov 2026).      // A document keeps its file's key in clear columns: read as it is, no window asked.      const sealedRow = isSealedTable(t) && isSealedRow(row.data);      if (sealedRow && !mediaColumns(t).some((k) => keysOf(row.data[k]).length > 0)) {        const keys = await windowFor(ctx, t, "get_media");        const { row: opened, parked } = await openStored(ctx, t, keys, row);        if (parked) step("open", `That ${lowerFirst(t.name)} is sealed and did not open in this window (${parked}), so its files cannot be read`);        found = { t, data: opened.data, sealed: true };      } else {        found = { t, data: row.data, sealed: sealedRow };      }      break;    }  }  if (!found) {    // A picture sent in a chat has no photo row: it is its message's (owner, 22 Nov 2026).    if (/^photo:[0-9a-f]{64}$/.test(id)) step("row", `no photo ${JSON.stringify(id)} is here. A picture sent or kept in a chat is its message's: get_media { table: "message", id: <the message's id>, index: <its place in the message's media, from 0> }`);    if (tables.length === 1) step("row", `${noLongerHere(tables[0]!)}: no row of ${tables[0]!.id} has that id, or it is in the bin`);    step("row", `no record ${JSON.stringify(id)} keeps a file: name a photo, a document or another record with one`);  }  const { t, data, sealed } = found!;  const columns = mediaColumns(t);  if (!columns.length) step("definition", `That ${lowerFirst(t.name)} keeps no file: this database's ${t.id} table has no photo or file column (${t.columns.filter((c) => /media|file|photo|picture/.test(c.key)).map((c) => `${c.key} is ${c.type}${c.computed ? ", computed" : ""}`).join("; ") || "none named so"})`);  const column = columns.find((k) => keysOf(data[k]).length > 0);  if (!column) step("media", `That ${lowerFirst(t.name)} keeps no file: ${sealed ? "it was opened in this window, and " : "it is not sealed, and "}${columns.map((k) => `${k} is ${shapeOf(data[k])}`).join("; ")}`);  const keys = keysOf(data[column!]);  if (index >= keys.length) step("index", `That ${lowerFirst(t.name)} keeps ${keys.length === 1 ? "one file" : `${keys.length} files`}: index is 0${keys.length > 1 ? ` to ${keys.length - 1}` : ""}`);  const key = keys[index]!;  let at: string;  try {    at = ctx.media.at(key);  } catch {    step("key", `That ${lowerFirst(t.name)}'s file names a key that is not this database's (${kindOf(key, ctx.database.id)})`);  }  const held = await ctx.media.head(at!);  if (!held) step("store", `That ${lowerFirst(t.name)}'s file is not stored yet: nothing is in the store under ${kindOf(key, ctx.database.id)}; the phone or import that kept it uploads it`);  const type = (held.httpMetadata?.contentType ?? "").split(";")[0]!.trim() || typeOfKey(key);  if (isSealedType(type)) return sealedTableFile(ctx, args, step, t, id, column!, key, keys.length, index, held, width, height);  // A file of a kind a sealed table owns that the object still holds plain (a face or a kept chat picture put before  // its kind was sealed, not resealed yet) is read in that table's window as a sealed one would be: no window, no file  // (MEDIA SEAL FINDINGS (1); AVATAR SEAL 3 (1), 27 Nov 2026). ctx.media's reads hold to the same rule for every tool.  const plainOwner = tableOfFileKind(kindOfKey(ctx.database.id, key) ?? "");  if (plainOwner) await windowFor(ctx, resolveTable(ctx, plainOwner), "get_media");  const indexAsked = args.index !== undefined && args.index !== null;  const about: Data = {    table: t.id,    id,    column,    key,    content_type: type,    bytes: held.size,    ...(keys.length > 1 ? { index, files: keys.length } : {}),    // A client whose copy of this tool predates index sends none: say which one this is, and how to ask for the rest.    ...(keys.length > 1 && !indexAsked ? { note: keys.length === 2 ? "the first of 2 files; ask with index 1 for the other" : `the first of ${keys.length} files; ask with index 1 to ${keys.length - 1} for the others` } : {}),  };  const image = type.startsWith("image/") && type !== "image/svg+xml";  if (!image && (width || height)) fail("only an image is drawn at a size");  if (image) {    if (!width && !height && READABLE_IMAGES.has(type) && held.size <= IMAGE_INLINE_MAX) {      const object = (await ctx.media.get(at!)) ?? fail(`That ${lowerFirst(t.name)}'s file is not stored yet`);      return new Content([        { type: "text", text: JSON.stringify(about) },        { type: "image", data: base64(new Uint8Array(await object.arrayBuffer())), mimeType: type },      ]);    }    const asked = width || height ? { ...(width ? { width } : {}), ...(height ? { height } : {}) } : { width: DRAWN_SIDE, height: DRAWN_SIDE };    const drawn = await ctx.media.draw(at!, asked);    if (drawn.byteLength > IMAGE_INLINE_MAX) fail(`drawn at that size the picture is ${megabytes(drawn.byteLength)}, more than ${megabytes(IMAGE_INLINE_MAX)}: ask for it smaller`);    return new Content([      { type: "text", text: JSON.stringify({ ...about, drawn: { ...asked, content_type: "image/webp", bytes: drawn.byteLength } }) },      { type: "image", data: base64(drawn), mimeType: "image/webp" },    ]);  }  if (held.size > FILE_INLINE_MAX) fail(`That file is ${megabytes(held.size)}; get_media hands over a file of at most ${megabytes(FILE_INLINE_MAX)}`);  const object = (await ctx.media.get(at!)) ?? fail(`That ${lowerFirst(t.name)}'s file is not stored yet`);  return new Content([    { type: "text", text: JSON.stringify(about) },    { type: "resource", resource: { uri: `cotton-media:${key}`, mimeType: type, blob: base64(new Uint8Array(await object.arrayBuffer())) } },  ]);}/** * A file sealed on the person's device, opened in the caller's window when its kind is one a window opens: a * message's kept chat picture, under TFR(message), which a window over messages hands (src/table_files.ts). * A photo's or any other kind's root is never handed: refused plainly. The opened bytes are never stored. */async function sealedTableFile(  ctx: ToolContext,  args: Data,  step: (name: string, words: string) => never,  t: Table,  id: string,  column: string,  key: string,  files: number,  index: number,  held: R2Object,  width: number | undefined,  height: number | undefined,): Promise<Content> {  const owner = tableOfFileKind(kindOfKey(ctx.database.id, key) ?? "");  if (!owner) step("sealed file", `That ${lowerFirst(t.name)}'s file is sealed on the person's device, and only their devices open it`);  const ownerTable = resolveTable(ctx, owner!);  const keys = await windowFor(ctx, ownerTable, "get_media");  if (!keys?.files) step("sealed file", `That ${lowerFirst(t.name)}'s file is sealed on the person's device, and this window was allowed by an app too old to open it: ask the owner to update the app and allow again`);  if (held.size > SEALED_OPEN_MAX) step("sealed file", `That ${lowerFirst(t.name)}'s file is ${megabytes(held.size)}; a sealed file is opened here up to ${megabytes(SEALED_OPEN_MAX)}`);  const object = (await ctx.media.get(ctx.media.at(key))) ?? step("store", `That ${lowerFirst(t.name)}'s file is not stored yet`);  const plain = await openF1(await personFileKey(keys!.files!, key), key, new Uint8Array(await object.arrayBuffer()));  if (!plain) step("open file", `That ${lowerFirst(t.name)}'s file did not open with this window's key`);  const type = typeOfKey(key);  const indexAsked = args.index !== undefined && args.index !== null;  const about: Data = {    table: t.id,    id,    column,    key,    content_type: type,    bytes: plain!.length,    sealed: true,    ...(files > 1 ? { index, files } : {}),    ...(files > 1 && !indexAsked ? { note: files === 2 ? "the first of 2 files; ask with index 1 for the other" : `the first of ${files} files; ask with index 1 to ${files - 1} for the others` } : {}),  };  const image = type.startsWith("image/") && type !== "image/svg+xml";  if (!image && (width || height)) fail("only an image is drawn at a size");  if (image) {    if (!width && !height && READABLE_IMAGES.has(type) && plain!.length <= IMAGE_INLINE_MAX) {      return new Content([{ type: "text", text: JSON.stringify(about) }, { type: "image", data: base64(plain!), mimeType: type }]);    }    const asked = width || height ? { ...(width ? { width } : {}), ...(height ? { height } : {}) } : { width: DRAWN_SIDE, height: DRAWN_SIDE };    const drawn = await ctx.media.drawBytes(plain!, asked);    if (drawn.byteLength > IMAGE_INLINE_MAX) fail(`drawn at that size the picture is ${megabytes(drawn.byteLength)}, more than ${megabytes(IMAGE_INLINE_MAX)}: ask for it smaller`);    return new Content([      { type: "text", text: JSON.stringify({ ...about, drawn: { ...asked, content_type: "image/webp", bytes: drawn.byteLength } }) },      { type: "image", data: base64(drawn), mimeType: "image/webp" },    ]);  }  if (plain!.length > FILE_INLINE_MAX) fail(`That file is ${megabytes(plain!.length)}; get_media hands over a file of at most ${megabytes(FILE_INLINE_MAX)}`);  return new Content([{ type: "text", text: JSON.stringify(about) }, { type: "resource", resource: { uri: `cotton-media:${key}`, mimeType: type, blob: base64(plain!) } }]);}/** The most a sealed file is opened in memory here: a chat picture is at most 16 MB. */const SEALED_OPEN_MAX = 24 * 1024 * 1024;/** The bytes put_document was handed, or fetched from its url, with the type they came as. */export async function bytesOf(args: Data): Promise<{ bytes: Uint8Array; type: string | null }> {  const given = optionalString(args, "bytes_base64");  const url = optionalString(args, "url");  if ((given === null) === (url === null)) fail("give the file as bytes_base64 or as url, one of them");  const tooBig = (n: number): never => fail(`that file is ${megabytes(n)}; a document is at most ${megabytes(MEDIA_MAX_BYTES)}`);  if (given !== null) {    const clean = given.replace(/\s+/g, "");    if (Math.floor((clean.length * 3) / 4) > MEDIA_MAX_BYTES) tooBig(Math.floor((clean.length * 3) / 4));    let raw: string;    try {      raw = atob(clean);    } catch {      fail("bytes_base64 is not base64");    }    const bytes = new Uint8Array(raw.length);    for (let i = 0; i < raw.length; i++) bytes[i] = raw.charCodeAt(i);    return { bytes, type: null };  }  let parsed: URL;  try {    parsed = new URL(url!);  } catch {    fail("url must be an absolute web address starting http:// or https://");  }  if (parsed.protocol !== "https:" && parsed.protocol !== "http:") fail("url must be an absolute web address starting http:// or https://");  const res = await fetch(parsed.toString(), { redirect: "follow" });  if (!res.ok) {    await res.body?.cancel();    fail(`${parsed.toString()} answered ${res.status}: nothing was stored`);  }  const declared = Number(res.headers.get("content-length") ?? NaN);  if (Number.isFinite(declared) && declared > MEDIA_MAX_BYTES) {    await res.body?.cancel();    tooBig(declared);  }  const chunks: Uint8Array[] = [];  let total = 0;  const reader = res.body?.getReader();  for (;;) {    if (!reader) break;    const { done, value } = await reader.read();    if (done) break;    total += value.byteLength;    if (total > MEDIA_MAX_BYTES) {      await reader.cancel();      tooBig(total);    }    chunks.push(value);  }  const bytes = new Uint8Array(total);  let offset = 0;  for (const c of chunks) {    bytes.set(c, offset);    offset += c.byteLength;  }  return { bytes, type: (res.headers.get("content-type") ?? "").split(";")[0]!.trim() || null };}async function putDocument(ctx: ToolContext, args: Data): Promise<Data> {  const name = requireString(args, "name", "name is required: the file's name, as a person would read it (\"March statement.pdf\")");  const t = resolveTable(ctx, "document");  const kind = optionalString(args, "kind");  const kinds = t.column("doc_type")?.choices ?? [];  if (kind !== null && !kinds.includes(kind)) fail(`kind is one of ${kinds.join(", ")}`);  // ADMIN KEYS 4: the right to write is checked before anything is fetched, so a key that may not keep the file never  // makes the request (a url's query string carries whatever the caller put in it).  ctx.writable(t.id);  const { bytes, type: came } = await bytesOf(args);  if (!bytes.byteLength) fail("the file is empty");  const type = optionalString(args, "content_type") ?? came ?? TYPES_BY_EXTENSION[extensionOf(name) ?? ""] ?? "application/octet-stream";  const sha = [...new Uint8Array(await crypto.subtle.digest("SHA-256", bytes))].map((b) => b.toString(16).padStart(2, "0")).join("");  const extension = extensionOf(name) ?? Object.entries(TYPES_BY_EXTENSION).find(([, v]) => v === type)?.[0] ?? "bin";  const key = `${ctx.database.id}/documents/${sha}.${extension}`;  const stored = await ctx.media.store(ctx.media.at(key), bytes, type);  const data: Data = {    title: name.replace(/\.[A-Za-z0-9]{1,8}$/, "") || name,    original_name: name,    mime: type,    byte_size: bytes.byteLength,    sha256: sha,    storage_path: key,    source: "agent",    mcp_token_id: ctx.caller.tokenId,    ...(kind ? { doc_type: kind } : {}),  };  const id = crypto.randomUUID();  const kept = await arriving(ctx, t, id, data);  ctx.write((w) => w.create(t.id, kept, { id }));  const row = ctx.get(t.id, id) ?? fail(noLongerHere(t));  return { change: changeJson(ctx, t, "create", id, null, readData(t, data), readData(t, data)), record: recordJson(t, row), stored: stored.stored, ...(kept === data ? {} : { sealed_at_arrival: `${t.plural} are sealed: this one was sealed as it arrived, to the owner's own key.` }) };}export const MEDIA_HANDLERS: Record<string, Handler> = { get_media: getMedia, put_document: putDocument };