Cotton code
306 lines · 14.4 KB · TypeScriptRaw
/** * `list_sessions` (records_2/sessions.rs) and `get_session` * (records_2/conversations.rs): the session rows as the Rust tools answered * them, key for key in the Rust insertion order. */import { boundedLimit, fail, isoTimestamp, optionalString, type Data, type ToolContext } from "../../context.ts";import { col, typeOf, type Cond, type StoredRow } from "../../../store.ts";import { equalSql } from "../records/where.ts";import { flag, int, NO_PROJECT_FILTER, projectFilter, projectsOf, slugOf, text, type ProjectFilter, type ProjectRef } from "./common.ts";import { matchPhrases, searchPrompts, tokenize } from "./search.ts";import { exactToken, queryTokens } from "../../../seal.ts";import { SealedRows } from "../sealed_rows.ts";const SESSION_KINDS = ["conversation", "thread"];const MAX_LIST = 5000;const RECENT_PROMPTS = 20;/** Up to this many prompts, a search reads every one (exactly FTS5's BM25); past it, only those that can match. */export const EXACT_PROMPTS = 20_000;/** The newest prompts whose length stands for the whole table's in a big table's BM25. */const LENGTH_SAMPLE = 2_000;const CURSOR_REFUSAL = "cursor is not one list_sessions handed out — pass nextCursor from the previous page exactly as it came, or drop it to start the list again";interface Cursor {  key: string;  id: string;}function b64urlEncode(value: string): string {  let bin = "";  for (const b of new TextEncoder().encode(value)) bin += String.fromCharCode(b);  return btoa(bin).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");}/** URL-safe base64 with no padding, strictly: what `URL_SAFE_NO_PAD.decode` accepts. */function b64urlDecode(raw: string): string | null {  if (!/^[A-Za-z0-9_-]*$/.test(raw) || raw.length % 4 === 1) return null;  let bin: string;  try {    bin = atob(raw.replace(/-/g, "+").replace(/_/g, "/"));  } catch {    return null;  }  const bytes = Uint8Array.from(bin, (c) => c.charCodeAt(0));  let back = "";  for (const b of bytes) back += String.fromCharCode(b);  if (btoa(back).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "") !== raw) return null; // trailing bits set  try {    return new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(bytes);  } catch {    return null;  }}/** * The prompts matching every phrase (searchPrompts). On a big prompt table (his: hundreds of thousands, a whole read * took 6.6 s on a million-row object, coordinator 23 Nov 2026) only the rows that can match are read: those whose * stored JSON holds each ASCII word (LIKE folds ASCII case as the tokenizer does), and every row holding a letter * outside ASCII, so an accented spelling the tokenizer folds is never missed. N is the table's count and the average * length the newest LENGTH_SAMPLE's, so a rank can differ a little from an exact one; a small table is read whole. */function promptHits(ctx: ToolContext, phrases: string[][], limit: number): ReturnType<typeof searchPrompts> {  const reread = (id: string): StoredRow | null => ctx.get("prompt", id);  const n = ctx.store.count("prompt");  if (n <= EXACT_PROMPTS) return searchPrompts(ctx.scan("prompt"), phrases, limit, reread);  const conds: Cond[] = [];  for (const term of new Set(phrases.flat())) {    if (!/^[\x20-\x7e]+$/.test(term)) continue;    // A row holds a letter outside ASCII exactly when its characters are fewer than its UTF-8 bytes.    conds.push({ sql: "(data LIKE ? OR length(data) <> length(CAST(data AS BLOB)))", args: [`%${term}%`] });  }  const sample = ctx.store.select("prompt", [], "created_at DESC, id DESC", LENGTH_SAMPLE);  const avgdl = sample.length ? sample.reduce((s, row) => s + tokenize(text(row.data, "text") ?? "").length, 0) / sample.length : 0;  return searchPrompts(ctx.scan("prompt", conds), phrases, limit, reread, { n, avgdl });}/** The most prompts a sealed search opens: its blind-token matches, newest first. */const SEALED_PROMPT_HITS = 2_000;/** * The prompts matching every phrase when prompt is sealed (OPEN TABLES, 24 Nov 2026): the rows whose blind tokens hold * every word (a word whole, the last as a word's start), newest first and at most SEALED_PROMPT_HITS, opened and then * matched and ranked as an open table's are. Only those rows are opened. */async function sealedPromptHits(ctx: ToolContext, rows: SealedRows, phrases: string[][], limit: number): Promise<ReturnType<typeof searchPrompts>> {  const keys = rows.keys("prompt");  if (!keys) return [];  const tokens = await queryTokens(keys.bk, "text", phrases.map((p) => p.join(" ")).join(" "));  const ids = ctx.store.blindIds("prompt", tokens, "ts", SEALED_PROMPT_HITS);  const held = ids.flatMap((id) => {    const row = ctx.get("prompt", id);    return row ? [row] : [];  });  const opened = new Map((await rows.open("prompt", held)).map((r) => [r.id, r]));  // The table's size for the rank; the average length the opened rows' own (the rest stay sealed).  const avgdl = opened.size ? [...opened.values()].reduce((sum, r) => sum + tokenize(text(r.data, "text") ?? "").length, 0) / opened.size : 0;  return searchPrompts(opened.values(), phrases, limit, (id) => opened.get(id) ?? null, { n: ctx.store.count("prompt"), avgdl });}export function encodeCursor(c: Cursor): string {  return b64urlEncode(JSON.stringify({ v: 1, key: c.key, id: c.id }));}function decodeCursor(raw: string): Cursor | null {  const decoded = b64urlDecode(raw);  if (decoded === null) return null;  let payload: unknown;  try {    payload = JSON.parse(decoded);  } catch {    return null;  }  if (!payload || typeof payload !== "object" || Array.isArray(payload)) return null;  const p = payload as Data;  if (p.v !== 1 || typeof p.key !== "string" || typeof p.id !== "string") return null;  return { key: p.key, id: p.id };}function sessionOut(row: StoredRow, projects: ProjectRef[]): Data {  const d = row.data;  return {    id: row.id,    tool: text(d, "tool"),    externalId: text(d, "external_id"),    machine: text(d, "machine"),    deviceId: text(d, "device_id"),    account: text(d, "account"),    project: slugOf(projects, text(d, "project")),    repoUrl: text(d, "repo_url"),    branch: text(d, "branch"),    startedAt: text(d, "started_at"),    lastActiveAt: text(d, "last_active_at"),    endedAt: text(d, "ended_at"),    title: text(d, "title"),    model: text(d, "model"),    summary: text(d, "summary"),    shipped: Array.isArray(d.shipped) ? (d.shipped as unknown[]).filter((s) => typeof s === "string") : [],    turnCount: int(d, "turn_count"),    promptCount: int(d, "prompt_count"),    transcriptRef: text(d, "transcript_ref"),    state: text(d, "state"),    stateAt: text(d, "state_at"),    waitingKind: text(d, "waiting_kind"),    waitingRef: text(d, "waiting_ref"),    lastLine: text(d, "last_line"),    hostOwned: flag(d, "host_owned"),    prompt: text(d, "prompt"),    requestedDeviceId: text(d, "requested_device_id"),    chosenBy: text(d, "chosen_by"),    holdReason: text(d, "hold_reason"),    error: text(d, "error"),    todoId: text(d, "todo_id"),    todoDatabase: text(d, "todo_database"),    kind: text(d, "kind") ?? "thread",    parentSessionId: text(d, "parent_session_id"),  };}/** One session's mirrored task list, in the agent's own order. */async function sessionTasks(ctx: ToolContext, rows: SealedRows, sessionId: string): Promise<Data[]> {  return (await rows.open("session_task", ctx.where("session_task", "session", sessionId)))    .sort((a, b) => int(a.data, "seq") - int(b.data, "seq"))    .map((t) => ({ seq: int(t.data, "seq"), text: text(t.data, "text"), state: text(t.data, "state") ?? "open" }));}export async function listSessions(ctx: ToolContext, args: Data): Promise<Data> {  let since: string | null = null;  if (args.since !== undefined && args.since !== null) {    since = typeof args.since === "string" ? isoTimestamp(args.since) : null;    if (since === null) fail("since must be an ISO 8601 timestamp");  }  const rawCursor = optionalString(args, "cursor");  const cursor = rawCursor === null ? null : (decodeCursor(rawCursor) ?? fail(CURSOR_REFUSAL));  const limit = boundedLimit(args, 20, MAX_LIST);  const projectSlug = optionalString(args, "project");  const machine = optionalString(args, "machine");  const q = optionalString(args, "q");  const parent = optionalString(args, "parent");  const kind = optionalString(args, "kind");  if (kind !== null && !SESSION_KINDS.includes(kind)) fail(`kind is one of ${SESSION_KINDS.join(", ")} — not \`${kind}\``);  const projects = projectsOf(ctx);  // AN ARCHIVED PROJECT'S SESSIONS ARE STILL ITS OWN: any project's slug reads its sessions.  let filter: ProjectFilter;  const named = projectSlug !== null && projectSlug !== NO_PROJECT_FILTER ? projects.find((p) => p.slug === projectSlug) : undefined;  if (named) filter = { kind: "project", id: named.id };  else filter = projectFilter(projects, projectSlug);  // Sealed (OPEN TABLES): only the rows answered are opened; with no window and a sealed row held, the call asks for one.  const rows = await SealedRows.of(ctx, ["session", "prompt"]);  await rows.need(q !== null ? ["session", "prompt"] : ["session"]);  let hits: Map<string, Data[]> | null = null;  if (q !== null) {    hits = new Map();    const phrases = matchPhrases(q);    if (phrases) {      for (const hit of rows.sealed("prompt") ? await sealedPromptHits(ctx, rows, phrases, limit * 10) : promptHits(ctx, phrases, limit * 10)) {        const bucket = hits.get(hit.sessionId);        if (!bucket) hits.set(hit.sessionId, [{ seq: hit.seq, snippet: hit.snippet }]);        else if (bucket.length < 5) bucket.push({ seq: hit.seq, snippet: hit.snippet });      }    }    if (!hits.size) return { sessions: [] };  }  // Narrowed, ordered and cut in SQL: the session table is never read whole.  const textOf = (key: string): string => `${typeOf(key)} = 'text'`;  const conds: Cond[] = [];  if (filter.kind === "none") conds.push({ sql: `NOT (${textOf("project")} AND ${col("project")} IN (SELECT value FROM json_each(?)))`, args: [JSON.stringify(projects.map((p) => p.id))] });  if (filter.kind === "project") conds.push(equalSql("project", filter.id));  if (machine !== null) {    // A sealed session's machine is found by its blind-exact token, never read here.    const keys = rows.keys("session");    if (rows.sealed("session") && keys) {      const token = await exactToken(keys.bk, "machine", machine);      conds.push(token ? ctx.store.blindCond("session", [token]) : { sql: "0", args: [] });    } else conds.push(equalSql("machine", machine));  }  if (parent !== null) conds.push(equalSql("parent_session_id", parent));  if (kind !== null) conds.push(equalSql("kind", kind));  if (since !== null) conds.push({ sql: `${textOf("last_active_at")} AND ${col("last_active_at")} >= ?`, args: [since] });  if (hits) conds.push({ sql: "id IN (SELECT value FROM json_each(?))", args: [JSON.stringify([...hits.keys()])] });  if (cursor) conds.push({ sql: `${textOf("last_active_at")} AND (${col("last_active_at")}, id) < (?, ?)`, args: [cursor.key, cursor.id] });  const found = ctx.store.select("session", conds, `CASE WHEN ${textOf("last_active_at")} THEN ${col("last_active_at")} ELSE '' END DESC, id DESC`, limit);  const counts = new Map<string, [number, number]>();  for (const row of found) counts.set(row.id, [0, 0]);  for (const row of found)    for (const task of ctx.where("session_task", "session", row.id)) {      const c = counts.get(row.id)!;      c[1] += 1;      if (text(task.data, "state") === "done") c[0] += 1;    }  const opened = new Map((await rows.open("session", found)).map((r) => [r.id, r]));  const sessions = found.flatMap((held) => {    const row = opened.get(held.id);    if (!row) return [];    const out = sessionOut(row, projects);    const [done, total] = counts.get(row.id) ?? [0, 0];    out.tasksDone = done;    out.tasksTotal = total;    if (hits) out.hits = hits.get(row.id) ?? [];    return [out];  });  const out: Data = { sessions };  if (rows.parked) out.parked = rows.parked;  const last = found.at(-1);  if (found.length === limit && last) {    const key = text(last.data, "last_active_at");    if (key !== null) out.nextCursor = encodeCursor({ key, id: last.id });  }  return out;}export async function getSession(ctx: ToolContext, args: Data): Promise<Data> {  const id = optionalString(args, "sessionId") ?? fail("sessionId is required — the id list_sessions answers with");  const rows = await SealedRows.of(ctx, ["session", "session_task", "prompt"]);  await rows.need(["session", "session_task", "prompt"]);  if (!ctx.get("session", id)) fail(`no session with id ${id}`);  const row = (await rows.get("session", id)) ?? fail(`session ${id} does not open with this window's keys`, { code: "parked" });  const projects = projectsOf(ctx);  const d = row.data;  const out: Data = {    id: row.id,    tool: text(d, "tool"),    externalId: text(d, "external_id"),    machine: text(d, "machine"),    deviceId: text(d, "device_id"),    account: text(d, "account"),    project: slugOf(projects, text(d, "project")),    repoUrl: text(d, "repo_url"),    branch: text(d, "branch"),    cwd: text(d, "cwd"),    title: text(d, "title"),    model: text(d, "model"),    prompt: text(d, "prompt"),    summary: text(d, "summary"),    state: text(d, "state"),    stateAt: text(d, "state_at"),    waitingKind: text(d, "waiting_kind"),    lastLine: text(d, "last_line"),    holdReason: text(d, "hold_reason"),    error: text(d, "error"),    todoId: text(d, "todo_id"),    todoDatabase: text(d, "todo_database"),    startedAt: text(d, "started_at"),    lastActiveAt: text(d, "last_active_at"),    endedAt: text(d, "ended_at"),    hostOwned: flag(d, "host_owned"),    kind: text(d, "kind") ?? "thread",    parentSessionId: text(d, "parent_session_id"),  };  // The last twenty turns, oldest first once they are chosen.  // The last twenty turns, chosen by their clear seq, and only those opened.  const recent = ctx    .where("prompt", "session", id)    .sort((a, b) => int(b.data, "seq") - int(a.data, "seq"))    .slice(0, RECENT_PROMPTS);  out.prompts = (await rows.open("prompt", recent))    .sort((a, b) => int(a.data, "seq") - int(b.data, "seq"))    .map((p) => ({ seq: int(p.data, "seq"), ts: text(p.data, "ts"), role: text(p.data, "role") ?? "user", text: text(p.data, "text") }));  const tasks = await sessionTasks(ctx, rows, id);  out.tasksDone = tasks.filter((t) => t.state === "done").length;  out.tasksTotal = tasks.length;  out.tasks = tasks;  return out;}