Cotton code
308 lines · 17.0 KB · TypeScriptRaw
/** * The unlock window over Cotton MCP (sealing plan §3.2; src/window.ts): * * - `request_unlock { tables?, reason, minutes? }`: ask the owner's phone to *   let this assistant connection read sealed tables for a while: minutes *   suggests 15, 60, 1440 or 0 (until the owner turns it off); the owner picks *   on the phone and their pick wins. Answers the waiting request (the same *   one again while it waits), the open window, or the request the owner *   declined while that Not now stands (nothing asked). Any connection may *   ask, a lane's and the coordinator's too; only the owner's phone allows. * - `end_unlock {}`: this connection ends its own windows now. * * And what the read tools share: a read that reaches a sealed table with no * window open for its token answers `window_needed` with the request it made * (a token that never gets a window is refused by name, and no request is * made); in a window, its rows open with the table key of their own version, * and a row that does not open is answered parked by name, never blank. */import { fail, optionalString, type Data, type Handler, type ToolContext, type Writer } from "../context.ts";import { col, type StoredRow } from "../../store.ts";import { isSealedRow, openRow, SealError, type SealCode } from "../../seal.ts";import { DEFAULT_MINUTES, isDuration, windowRefusal, type TableKeys } from "../../window.ts";import { recordJson } from "./records/shape.ts";import { resolveTable, visibleTables, type Table } from "./records/table.ts";import unlockLines from "../../../../../crates/cotton-core/kits/shell/lines/unlock.json";/** * Does the table hold a sealed row? A table the rule seals that holds none yet (no phone has swept it since; memory on * the day it was sealed, 22 Nov 2026) is read as the object holds it: its rows are clear here already, so reading them * opens nothing, and nobody is asked for a window until a device has sealed one (it hands Your Claude's grant the key in * the same pass, phone/assistants.rs top_up). */export function holdsSealed(ctx: ToolContext, t: Table): boolean {  for (const _row of ctx.scan(t.id, [{ sql: `${col("seal_v")} IS NOT NULL`, args: [] }])) return true;  return false;}/** Is this a sealed table (its definition carries a `seal` block)? */export function isSealedTable(t: Table): boolean {  return !!t.def.seal;}/** One `unlock` line by its dotted key, `{name}` filled: the kit's words (the personal object keeps no line overrides); the literal `unlock.<line>` when the kit has none (Rust's fallback). */export function say(line: string, fills: Record<string, string> = {}): string {  let at: unknown = unlockLines;  for (const key of line.split(".")) at = at && typeof at === "object" ? (at as Record<string, unknown>)[key] : undefined;  if (typeof at !== "string") return `unlock.${line}`;  return at.replace(/\{(\w+)\}/g, (whole, name: string) => fills[name] ?? whole);}/** Names as one phrase: "a", "a and b", "a, b and c" (or "a or b" with `last` = assistant.either). */function joined(names: string[], last = "joined"): string {  if (names.length < 2) return names[0] ?? "";  return say(last, { rest: names.slice(0, -1).join(say("comma")), last: names[names.length - 1]! });}/** What the asker is told to do: the owner allows it on their phone, in whatever Cotton app is open (the card stands from the shell in every app). */export function askPhone(): string {  return say("assistant.ask");}/** The tables a request names, as this database calls them. */function tableNames(ctx: ToolContext, ids: string[]): string {  const plural = new Map(visibleTables(ctx).map((t) => [t.id, t.plural]));  return joined(ids.map((id) => plural.get(id) ?? id));}/** The owner's Not now on this request still stands: what the asker is told. */function declinedSentence(ctx: ToolContext, request: StoredRow): string {  return say("assistant.declined", { tables: tableNames(ctx, heldIds(request)), until: String(request.data.expires_at), request: request.id });}function heldIds(row: StoredRow): string[] {  return Array.isArray(row.data.tables) ? (row.data.tables as string[]) : [];}/** A read reached sealed tables with no window: refused by name for a token that never gets one, else a request is made (or the waiting one found) and the read answers `window_needed`. */export async function needWindow(ctx: ToolContext, tables: Table[], reason: string): Promise<never> {  const names = tables.map((t) => t.plural).join(", ");  const refusal = windowRefusal(ctx.caller);  if (refusal) fail(`${names} are sealed: ${refusal}`, { code: "window_refused", tables: tables.map((t) => t.id) });  const request = await ctx.window.request(    tables.map((t) => t.id),    reason,    DEFAULT_MINUTES,  );  if (request.data.state === "declined")    fail(declinedSentence(ctx, request), {      code: "window_declined",      request_id: request.id,      tables: request.data.tables,      expires_at: request.data.expires_at,    });  fail(`${neededSentence(ctx, names, request)} Ask again once it is allowed (request ${request.id}, waiting until ${String(request.data.expires_at)}).`, {    code: "window_needed",    card: cardOf(ctx, request),    request_id: request.id,    tables: request.data.tables,    expires_at: request.data.expires_at,  });}/** * Which card the request is, so the assistant knows its case: `account`, the * one card that lets Your Claude read standing; `each_time`, a timed window * for a table the owner keeps asked each time though the standing grant * answers; `window`, a timed window where no standing grant answers. */export function cardOf(ctx: ToolContext, request: StoredRow): "account" | "each_time" | "window" {  if (request.data.account === true) return "account";  return ctx.window.standing ? "each_time" : "window";}/** What a read refused for want of keys says, by its card. */function neededSentence(ctx: ToolContext, names: string, request: StoredRow): string {  switch (cardOf(ctx, request)) {    case "account":      return `${names} are private to the owner. ${say("assistant.account")}`;    case "each_time":      return `${names} are sealed. ${say("assistant.each_time", { tables: tableNames(ctx, heldIds(request)) })}`;    case "window":      return `${names} are sealed and the owner has not opened a window for this assistant. ${askPhone()}`;  }}/** * The keys this read opens `t` with: null for an open table, else the window's, else `window_needed`. The request a * read files carries no reason of its own: the card's title already names the table ("Allow Claude to read Chats?"), * and the reason it carried was the tool's name ("list_records on Chats"), shown to the person on their phone * (the emulator, 21 Nov 2026). An assistant that wants to say why asks with request_unlock and its own sentence. * `_tool` names the reading tool for whoever reads the call; no word the person sees carries it. */export async function windowFor(ctx: ToolContext, t: Table, _tool: string): Promise<TableKeys | null> {  if (!isSealedTable(t)) return null;  return (await ctx.window.keys(t.id)) ?? needWindow(ctx, [t], READ_REASON);}/** What a read that reaches a sealed table files as its reason: nothing, so the card says no tool's name. */export const READ_REASON = "";/** A row as a window reads it: a sealed row opened with its own version's key, or parked by name; an open row as it is. */export async function openStored(ctx: ToolContext, t: Table, keys: TableKeys | null, row: StoredRow): Promise<{ row: StoredRow; parked: SealCode | null }> {  if (!keys || !isSealedRow(row.data)) return { row, parked: null };  const v = row.data.seal_v;  try {    const data = await openRow(typeof v === "number" ? (keys.tk.get(v) ?? null) : null, ctx.database.id, t.id, row.id, row.data);    return { row: { ...row, data }, parked: null };  } catch (error) {    if (error instanceof SealError) return { row, parked: error.code };    throw error;  }}/** A record as a read answers it, opened in a window; a row that did not open says why under `sealed`. */export async function openedJson(ctx: ToolContext, t: Table, keys: TableKeys | null, row: StoredRow): Promise<Data> {  const { row: opened, parked } = await openStored(ctx, t, keys, row);  const out = recordJson(t, opened);  if (parked) out.sealed = parked;  return out;}/** What an answer read in a window says of it. */export function windowNote(keys: TableKeys | null): Data {  if (!keys) return {};  return { window: keys.standing ? { table: keys.table, standing: true } : { table: keys.table, ends_at: keys.ends_at } };}async function requestUnlock(ctx: ToolContext, args: Data): Promise<Data> {  const refusal = windowRefusal(ctx.caller);  if (refusal) fail(refusal, { code: "window_refused" });  const reason = optionalString(args, "reason") ?? fail("reason is required: one sentence the owner reads on the card, saying what you will read and why");  const minutes = args.minutes === undefined || args.minutes === null ? DEFAULT_MINUTES : args.minutes;  if (!isDuration(minutes)) fail("minutes suggests how long: 15, 60 or 1440, or 0 for until the owner turns it off (the owner picks on the phone)");  let tables: Table[];  if (args.tables === undefined || args.tables === null) {    tables = visibleTables(ctx).filter(isSealedTable);    if (!tables.length) fail("this database holds no sealed table: every table reads without a window");  } else {    if (!Array.isArray(args.tables) || !args.tables.length || args.tables.some((x) => typeof x !== "string" || !x.trim())) fail('tables is a list of sealed tables\' ids, e.g. ["message", "note"]');    tables = (args.tables as string[]).map((id) => resolveTable(ctx, id.trim(), id));    const open = tables.find((t) => !isSealedTable(t));    if (open) fail(`${open.id} is not sealed: it reads without a window`);  }  const ids = [...new Set(tables.map((t) => t.id))].sort();  const covered = ctx.window.open().filter((w) => ids.every((id) => w.tables.includes(id)));  if (covered.length) {    const last = covered[covered.length - 1]!;    return last.standing ? { state: "open", tables: ids, standing: true } : { state: "open", tables: ids, ends_at: last.ends_at };  }  const request = await ctx.window.request(ids, reason, minutes);  if (request.data.state === "declined") return { state: "declined", request_id: request.id, tables: request.data.tables, expires_at: request.data.expires_at, sentence: declinedSentence(ctx, request) };  const card = cardOf(ctx, request);  const sentence = card === "account" ? say("assistant.account") : card === "each_time" ? say("assistant.each_time", { tables: tableNames(ctx, heldIds(request)) }) : askPhone();  return { state: "waiting", card, request_id: request.id, tables: request.data.tables, minutes: request.data.minutes, expires_at: request.data.expires_at, sentence };}function endUnlock(ctx: ToolContext): Data {  return { ended: ctx.window.end() };}export const WINDOW_HANDLERS: Record<string, Handler> = { request_unlock: requestUnlock, end_unlock: (ctx) => endUnlock(ctx) };/** * What `brief` reads when memory is sealed. In a window: a context whose * memory rows read opened (a row that does not open is left out and counted). * With none: the briefing in words, saying the owner has not opened a window * for this assistant and what to do, with the request it filed; never an entry * and never a blank. */export async function openedBrief(ctx: ToolContext, tables: Table[]): Promise<{ answer: Data } | { ctx: ToolContext; parked: number }> {  const held = new Map<string, TableKeys>();  for (const t of tables) {    const k = await ctx.window.keys(t.id);    if (k) held.set(t.id, k);  }  // A table with no key and no sealed row yet reads as it is held (holdsSealed); one with sealed rows and no key asks.  if (tables.some((t) => !held.has(t.id) && holdsSealed(ctx, t))) {    const ask = async (): Promise<StoredRow> => ctx.window.request(tables.map((t) => t.id), "brief: to read the owner's memory entries and procedure notes at the start of a session", DEFAULT_MINUTES);    const request = await ask();    const card = cardOf(ctx, request);    const answer: Data = { projects: [], generatedAt: ctx.now, database: ctx.database.id, databaseId: ctx.database.id, tokensEstimate: 0, overBudget: false, code: request.data.state === "declined" ? "window_declined" : "window_needed", card, request_id: request.id, expires_at: request.data.expires_at };    const client = ctx.caller.name || say("brief.this_assistant");    answer.briefing =      request.data.state === "declined"        ? `${say("brief.sealed", { client })} ${declinedSentence(ctx, request)}`        : card === "account"          ? `${say("brief.account", { client })} ${say("brief.filed", { ask: say("assistant.account"), request: request.id, until: String(request.data.expires_at) })}`          : `${say("brief.sealed", { client })} ${say("brief.filed", { ask: card === "each_time" ? say("assistant.each_time", { tables: tableNames(ctx, heldIds(request)) }) : askPhone(), request: request.id, until: String(request.data.expires_at) })}`;    return { answer };  }  return openedView(ctx, tables.filter((t) => held.has(t.id)), held);}/** Rows a view opened: never handed to a write, which would store their opened values in the clear. */const OPENED = new WeakSet<StoredRow>();/** * A context whose rows of `tables` read opened with the window's keys (a row that does not open is left out and * counted as parked, never answered blank); every other table reads as it is. `where` on an opened table compares the * opened values, so a sealed column (a memory's slug) finds its row. A write handed an opened row is refused: what it * would store is the row's opened values, in the clear. Writes to these tables seal their values themselves first * (records/write.ts `sealedWrite`) and write the row as it is stored. */export async function openedView(ctx: ToolContext, tables: Table[], held: Map<string, TableKeys>): Promise<{ ctx: ToolContext; parked: number }> {  const opened = new Map<string, Map<string, StoredRow>>();  let parked = 0;  for (const t of tables) {    const rows = new Map<string, StoredRow>();    for (const row of ctx.scan(t.id)) {      const { row: open, parked: why } = await openStored(ctx, t, held.get(t.id)!, row);      if (why) {        parked++;        continue;      }      if (open !== row) OPENED.add(open);      rows.set(row.id, open);    }    opened.set(t.id, rows);  }  const keep = (table: string, rows: Iterable<StoredRow>): StoredRow[] => {    const mine = opened.get(table)!;    return [...rows].flatMap((r) => (mine.has(r.id) ? [mine.get(r.id)!] : []));  };  const guarded = (w: Writer): Writer =>    new Proxy(w, {      get(target, prop) {        if (prop === "update" || prop === "delete")          return (row: StoredRow, ...rest: unknown[]) => {            if (OPENED.has(row)) throw new Error(`a write was handed ${row.table} ${row.id} as a window opened it: it would be stored in the clear`);            return (target[prop] as (row: StoredRow, ...rest: unknown[]) => StoredRow).call(target, row, ...rest);          };        const value = Reflect.get(target, prop, target) as unknown;        return typeof value === "function" ? (value as (...a: unknown[]) => unknown).bind(target) : value;      },    });  const view: ToolContext = {    ...ctx,    scan: (table, where) => (opened.has(table) ? keep(table, ctx.scan(table, where)) : ctx.scan(table, where)),    where: (table, column, equals) => (opened.has(table) ? [...opened.get(table)!.values()].filter((r) => r.data[column] === equals) : ctx.where(table, column, equals)),    get: (table, id) => (opened.has(table) ? (opened.get(table)!.get(id) ?? null) : ctx.get(table, id)),    write: (fn) => ctx.write((w) => fn(guarded(w))),  };  return { ctx: view, parked };}/** * The tools that read the project table (OPEN TABLES, 24 Nov 2026): their call reads it opened when it is sealed. Its * 13 rows (the owner's) are opened once per call, before the tool runs, so every reader of a project's slug, name and * repos (brief's repo binding, log_session's, the memory and session tools') reads them as before. */export const PROJECT_READERS: ReadonlySet<string> = new Set([  "brief", "recall", "remember", "memory_update", "memory_archive", "list_projects", "create_project", "update_project",  "link_to_project", "log_session", "list_sessions", "get_session", "open_project_conversation",  // A project named by its slug (records/list.ts resolveProject), and list_todos' slugs beside each to-do.  "list_records", "list_todos",]);/** * A call's context with the project table opened, when it is sealed and this call holds its key; as it is otherwise * (open, or no key: the tool then meets sealed rows, and `brief` asks for a window). */export async function withOpenProjects(ctx: ToolContext, tool: string): Promise<ToolContext> {  if (!PROJECT_READERS.has(tool) || !ctx.defs().table("project")) return ctx;  const t = resolveTable(ctx, "project");  if (!isSealedTable(t) || !holdsSealed(ctx, t)) return ctx;  const keys = await ctx.window.keys(t.id);  if (!keys) return ctx;  return (await openedView(ctx, [t], new Map([[t.id, keys]]))).ctx;}