/** * The session vocabulary the session tools share, ported from the Rust * (crates/cotton-tools/src/mcp/handlers/common.rs, records_2/sessions.rs, * cotton-core transforms/redact.rs and rules/memory_briefing.rs). * * The personal package keeps the Rust columns under their Rust names, except * that a `*_id` link is the link column without the suffix: `project_id` is * `project`, `session_id` is `session`, `to_session_id` is `to_session`. */ import { fail, type Data, type ToolContext } from "../../context.ts"; export const SESSION_TOOLS = ["claude-code", "codex", "kimi", "gemini", "opencode", "other"]; export const SESSION_TITLE_MAX = 140; // ── reading a row the way the Rust `text` / `flag` / `int` read one ───────── /** A string value (an empty one included), else null. */ export function text(data: Data, key: string): string | null { const v = data[key]; return typeof v === "string" ? v : null; } /** A whole number, else 0. */ export function int(data: Data, key: string): number { const v = data[key]; return typeof v === "number" && Number.isInteger(v) ? v : 0; } /** A whole number, else null. */ export function intOrNull(data: Data, key: string): number | null { const v = data[key]; return typeof v === "number" && Number.isInteger(v) ? v : null; } /** A boolean column, read as true for `true` or a non-zero number. */ export function flag(data: Data, key: string): boolean { const v = data[key]; if (typeof v === "boolean") return v; if (typeof v === "number") return Number.isInteger(v) && v !== 0; return false; } /** An absent column: null or undefined (SQL NULL). */ export function isNull(data: Data, key: string): boolean { return data[key] === null || data[key] === undefined; } /** `Date.parse` as `parse_ms` does it: any JS-parsable instant, else null. */ export function parseMs(value: string | null): number | null { if (value === null || !value.trim()) return null; const t = Date.parse(value.trim()); return Number.isNaN(t) ? null : t; } const RFC3339 = /^(\d{4})-(\d{2})-(\d{2})[Tt ](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?([Zz]|([+-])(\d{2}):(\d{2}))$/; /** `chrono::DateTime::parse_from_rfc3339`: the strict spelling only, as epoch ms and the sub-second nanos. */ export function rfc3339(value: string | null): { ms: number; nanos: number } | null { if (value === null) return null; const m = RFC3339.exec(value); if (!m) return null; const [y, mo, d, h, mi, s] = [m[1], m[2], m[3], m[4], m[5], m[6]].map(Number) as [number, number, number, number, number, number]; if (mo < 1 || mo > 12 || d < 1 || d > daysIn(y, mo) || h > 23 || mi > 59 || s > 59) return null; const fraction = (m[7] ?? "").slice(0, 9).padEnd(9, "0"); const nanos = Number(fraction); let offset = 0; if (m[9]) { const oh = Number(m[10]); const om = Number(m[11]); if (oh > 23 || om > 59) return null; offset = (m[9] === "-" ? -1 : 1) * (oh * 60 + om) * 60_000; } return { ms: Date.UTC(y, mo - 1, d, h, mi, s) + Math.floor(nanos / 1e6) - offset, nanos }; } function daysIn(year: number, month: number): number { return new Date(Date.UTC(year, month, 0)).getUTCDate(); } // ── redact, then clip ─────────────────────────────────────────────────────── const REDACTIONS: [RegExp, string][] = [ [/-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----/g, "[redacted:private-key]"], [/-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*$/g, "[redacted:private-key]"], [/\bBearer\s+[A-Za-z0-9._~+/=-]{8,}/g, "Bearer [redacted:bearer]"], [/\bctn_[A-Za-z0-9_-]{20,}/g, "[redacted:cotton-token]"], [/\bcfi_[A-Za-z0-9_-]{20,}/g, "[redacted:cotton-ingest-token]"], [/\bctg_[A-Za-z0-9_-]{20,}/g, "[redacted:cotton-code-credential]"], [/\bsk-[A-Za-z0-9_-]{16,}/g, "[redacted:api-key]"], [/\bgh[pousr]_[A-Za-z0-9]{16,}/g, "[redacted:github-token]"], [/\bgithub_pat_[A-Za-z0-9_]{20,}/g, "[redacted:github-token]"], [/\bAKIA[0-9A-Z]{16}\b/g, "[redacted:aws-key]"], [/\beyJ[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g, "[redacted:jwt]"], [/\bxox[bpa]-[A-Za-z0-9-]{10,}/g, "[redacted:slack-token]"], ]; /** `redact_secrets`: every credential-shaped run replaced by its marker, the rules in order. */ export function redactSecrets(value: string): string { let out = value; for (const [pattern, marker] of REDACTIONS) out = out.replace(pattern, () => marker); return out; } /** `utf16_clip`: `slice(0, max)` in UTF-16 units; a pair cut in half ends in U+FFFD, as `from_utf16_lossy` writes it. */ export function utf16Clip(value: string, max: number): string { if (value.length <= max) return value; const cut = value.slice(0, max); const last = cut.charCodeAt(cut.length - 1); return last >= 0xd800 && last <= 0xdbff ? `${cut.slice(0, -1)}�` : cut; } /** Redact, THEN clip — never the other way round. */ export function redactedToFit(value: string, max: number): string { return utf16Clip(redactSecrets(value), max); } /** `clipped`: absent stays absent. */ export function clipped(value: string | null, max: number): string | null { return value === null ? null : redactedToFit(value, max); } // ── arguments ─────────────────────────────────────────────────────────────── export function isUuid(value: string): boolean { return /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/.test(value); } /** `require_uuid`. */ export function requireUuid(args: Data, key: string): string { const v = args[key]; const s = typeof v === "string" ? v.trim() : ""; if (!s || !isUuid(s)) fail(`${key} must be a uuid`); return s; } // ── projects ──────────────────────────────────────────────────────────────── export interface ProjectRef { id: string; slug: string; name: string; repos: string[]; status: string; } /** Every project row, oldest first (`memory_projects` / `projects`). */ export function projectsOf(ctx: ToolContext): ProjectRef[] { return [...ctx.scan("project")].map((row) => ({ id: row.id, slug: text(row.data, "slug") ?? "", name: text(row.data, "name") ?? "", repos: Array.isArray(row.data.repos) ? (row.data.repos as unknown[]).filter((r): r is string => typeof r === "string") : [], status: text(row.data, "status") ?? "", })); } export function slugOf(projects: ProjectRef[], projectId: string | null): string | null { if (projectId === null) return null; return projects.find((p) => p.id === projectId)?.slug ?? null; } /** `resolveProject`: an active project by slug, refused by name. */ export function resolveProject(projects: ProjectRef[], slug: string | null): string | null { if (!slug) return null; const found = projects.find((p) => p.slug === slug && p.status === "active"); if (found) return found.id; const known = projects.filter((p) => p.status === "active").map((p) => p.slug); fail(known.length ? `unknown project ${JSON.stringify(slug)} — projects are: ${known.join(", ")}` : "this workspace has no projects yet — list_projects to confirm, create_project to start one"); } export const NO_PROJECT_FILTER = "none"; export type ProjectFilter = { kind: "every" } | { kind: "none" } | { kind: "project"; id: string }; /** `project_filter`. */ export function projectFilter(projects: ProjectRef[], slug: string | null): ProjectFilter { if (slug === null) return { kind: "every" }; if (slug === NO_PROJECT_FILTER) return { kind: "none" }; const id = resolveProject(projects, slug); return id === null ? { kind: "every" } : { kind: "project", id }; } const JS_EDGE_SPACE = /^\s+|\s+$/g; /** `normalize_repo_url`: one spelling for every way a remote is written. */ export function normalizeRepoUrl(raw: string): string { const lowered = raw.replace(JS_EDGE_SPACE, "").toLowerCase(); const noProtocol = lowered.replace(/^[a-z+]+:\/\//, ""); const noUser = noProtocol.replace(/^[^@/]+@/, ""); const scp = noUser.replace(":", "/"); return scp.replace(/\/{2,}/g, "/").replace(/\.git$/, "").replace(/\/+$/, ""); } /** `projects_for_repo`: the projects whose repo list carries the remote. */ export function projectsForRepo(projects: ProjectRef[], repoUrl: string): ProjectRef[] { const normalized = normalizeRepoUrl(repoUrl); if (!normalized) return []; return projects.filter((p) => p.repos.some((r) => normalizeRepoUrl(r) === normalized)); }