// THE ASSISTANT'S LABELS (release 36 lane D): an OPTIONAL pass over the clip // finder's proposals that names each one, says in a line what makes it land, // and ranks them — and the assistant's answer to a comment on one clip. // // /clip-suggestions.json // { model, at, proposedAt, promptVersion, // items: { : { label, why, rank, score, start, end } } } // // `label` is at most six words ("the badge reveal"), `why` one plain line, // `rank` 1 = the best of the file, `score` the model's 1–10 the rank is made // from (code ranks, so a pass in batches still ranks globally), `start`/`end` // the span that was labelled. `proposedAt` is the reactions.json pass the // labels were made over: a later pass makes the file STALE (shown, marked, // never hidden), and an item whose proposal moved or went is stale on its own. // // What this module is: the pure parts — the prompt a proposal becomes (its // words, each line marked HOST / SUBJECT / OTHER by the turns, and what the // finder heard), the reading of a model's answer (a malformed one is refused, // never repaired into a label), the ranking, the stale rule — and the file's // reader and its one writer (tmp + rename). The model call is the editor's // `report-draft` task `clips-suggest` // (common/lib/report/draft/tasks/clipsSuggest.ts); nothing here calls one. // It NEVER edits a clip or the manifest: the operator's click does, in the // clip editor. // // Plain ESM with a .d.mts beside it. import { readFile, rename, writeFile } from "node:fs/promises"; import path from "node:path"; import { cleanTurns, cleanWords, roleMap, wordsFromCues, wordsIn } from "./clips.mjs"; import { tmpPathFor } from "../atomicFile.mjs"; export const SUGGESTIONS_FILE = "clip-suggestions.json"; export const SUGGEST_PROMPT_VERSION = "clips-suggest-1"; /** A label's most words. */ export const SUGGEST_LABEL_MAX_WORDS = 6; /** A label's most characters (six long words). */ export const SUGGEST_LABEL_MAX_CHARS = 60; /** A why's most characters (one line). */ export const SUGGEST_WHY_MAX = 200; /** The most characters of one proposal's words a prompt carries. */ export const SUGGEST_LINES_MAX_CHARS = 900; /** Proposals per call on the Claude API (a local model's batches are fitted to its prompt cap). */ export const SUGGEST_API_BATCH = 30; /** An Ask's reply: its most characters. */ export const ASK_REPLY_MAX = 1200; /** An Ask reads this many seconds either side of the clip. */ export const ASK_REACH_S = 20; /** A proposed trim may move an edge at most this far. */ export const ASK_TRIM_MAX_MOVE_S = 30; export const ASK_PROPOSAL_KINDS = Object.freeze(["none", "trim", "merge", "cut"]); const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v); const num = (v) => typeof v === "number" && Number.isFinite(v); const r2 = (n) => Math.round(n * 100) / 100; const clock = (s) => { const t = Math.max(0, Math.floor(s)); const h = Math.floor(t / 3600); const m = Math.floor((t % 3600) / 60); const x = String(t % 60).padStart(2, "0"); return h ? `${h}:${String(m).padStart(2, "0")}:${x}` : `${m}:${x}`; }; const ROLE_WORD = { host: "HOST", subject: "SUBJECT", other: "OTHER" }; export const suggestionsFileOf = (dir) => path.join(/* turbopackIgnore: true */ dir, SUGGESTIONS_FILE); // ---- the file ---------------------------------------------------------------------- /** A suggestions doc, checked: `{ doc }` or `{ error }`. Items that are not the shape are an error for the file. */ export function parseSuggestionsDoc(raw) { if (!isObj(raw)) return { error: "not an object" }; if (typeof raw.model !== "string" || !raw.model) return { error: "model is not a model id" }; if (typeof raw.at !== "string" || !raw.at) return { error: "at is not a time" }; if (!isObj(raw.items)) return { error: "items is not an object" }; const items = {}; for (const [id, it] of Object.entries(raw.items)) { if (!isObj(it) || typeof it.label !== "string" || typeof it.why !== "string" || !Number.isInteger(it.rank) || it.rank < 1) return { error: `items.${id} is not { label, why, rank }` }; items[id] = { label: it.label, why: it.why, rank: it.rank, ...(num(it.score) ? { score: it.score } : {}), ...(num(it.start) ? { start: it.start } : {}), ...(num(it.end) ? { end: it.end } : {}), }; } return { doc: { model: raw.model, at: raw.at, ...(typeof raw.proposedAt === "string" ? { proposedAt: raw.proposedAt } : raw.proposedAt === null ? { proposedAt: null } : {}), ...(typeof raw.promptVersion === "string" ? { promptVersion: raw.promptVersion } : {}), items, }, }; } /** `/clip-suggestions.json` as `{ doc, error }`: doc null when there is none (error null) or it is not one (error set). */ export async function readSuggestions(dir) { let text; try { text = await readFile(suggestionsFileOf(dir), "utf8"); } catch (err) { if (err && err.code === "ENOENT") return { doc: null, error: null }; return { doc: null, error: String(err?.message ?? err) }; } let raw; try { raw = JSON.parse(text); } catch (err) { return { doc: null, error: `${SUGGESTIONS_FILE} is not JSON: ${err.message}` }; } const r = parseSuggestionsDoc(raw); return "error" in r ? { doc: null, error: `${SUGGESTIONS_FILE}: ${r.error}` } : { doc: r.doc, error: null }; } /** THE writer: whole, tmp + rename, so a reader never sees half a file. Checked first. */ export async function writeSuggestions(dir, doc) { const r = parseSuggestionsDoc(doc); if ("error" in r) throw new Error(`not a suggestions doc: ${r.error}`); const file = suggestionsFileOf(dir); const tmp = tmpPathFor(file); await writeFile(tmp, `${JSON.stringify(r.doc, null, 1)}\n`); await rename(tmp, file); return file; } /** * Whether the labels still describe the proposals: the file is stale when * reactions.json's proposal pass is newer than the one labelled; an item is * stale when its proposal is gone or its span moved (> 0.05 s). Stale is SHOWN. * @returns {{ stale: boolean, why: string | null, passNewer: boolean, staleIds: string[], missing: string[] }} */ export function suggestionsState(doc, reactions) { if (!doc) return { stale: false, why: null, passNewer: false, staleIds: [], missing: [] }; const proposals = new Map((reactions?.proposals ?? []).filter((p) => isObj(p) && typeof p.id === "string").map((p) => [p.id, p])); const staleIds = []; for (const [id, it] of Object.entries(doc.items ?? {})) { const p = proposals.get(id); if (!p) staleIds.push(id); else if (num(it.start) && num(it.end) && (Math.abs(it.start - p.start) > 0.05 || Math.abs(it.end - p.end) > 0.05)) staleIds.push(id); } const missing = [...proposals.keys()].filter((id) => !doc.items?.[id]); const passNewer = typeof reactions?.proposedAt === "string" && (typeof doc.proposedAt !== "string" || reactions.proposedAt > doc.proposedAt); const why = passNewer ? "the proposals were made again after these labels" : staleIds.length ? `${staleIds.length} proposal${staleIds.length === 1 ? "" : "s"} changed since these labels` : null; return { stale: !!why, why, passNewer, staleIds, missing }; } // ---- what a proposal is, in words -------------------------------------------------- /** A words list from what a words file may hold (`{ words: [...] }` or a bare array; `w`, `word` or `text`). */ export function wordsOfFile(raw) { const list = Array.isArray(raw) ? raw : Array.isArray(raw?.words) ? raw.words : []; return cleanWords(list.map((w) => (isObj(w) ? { ...w, w: String(w.w ?? w.word ?? w.text ?? "") } : w))); } /** The words of a recording a pass reads: the project's word timings, else the cues spread over their words. */ export function wordsFor({ words = null, cues = null } = {}) { if (Array.isArray(words) && words.length) return wordsOfFile(words); return wordsFromCues(Array.isArray(cues) ? cues : []); } /** * The words of [a, b] as lines, each marked by who speaks (the turn holding * the word's middle; a word in no turn joins the line it follows), at most * `max` characters in all. * @returns {{ role: "host" | "subject" | "other" | null, speaker: number | null, text: string }[]} */ export function roleLines({ words, turns, speakers }, a, b, max = SUGGEST_LINES_MAX_CHARS) { const roles = roleMap(Array.isArray(speakers) ? speakers.filter(isObj) : []); const ts = cleanTurns(turns).filter((t) => t.end > a && t.start < b); const lines = []; let used = 0; for (const w of wordsIn(words, a, b)) { const mid = (w.start + w.end) / 2; const t = ts.find((x) => x.start <= mid && mid <= x.end) ?? null; const speaker = t ? t.speaker : (lines.at(-1)?.speaker ?? null); const role = speaker === null ? null : (roles.get(speaker) ?? "other"); if (used + w.w.length + 1 > max) { if (lines.length) lines.at(-1).text += " …"; break; } used += w.w.length + 1; const last = lines.at(-1); if (last && last.speaker === speaker) last.text += ` ${w.w}`; else lines.push({ role, speaker, text: w.w }); } return lines; } const lineText = (l) => `${l.role ? ROLE_WORD[l.role] ?? "OTHER" : "?"}: ${l.text}`; /** * Every proposal of a reactions doc as the prompt reads it: its span, what the * finder heard (the moments' kinds), the finder's score and why, and its lines. * `ids`: only these proposals. */ export function suggestItems(reactions, words, { ids = null } = {}) { const moments = new Map((reactions?.moments ?? []).filter(isObj).map((m) => [m.id, m])); const want = ids ? new Set(ids) : null; return (reactions?.proposals ?? []) .filter((p) => isObj(p) && typeof p.id === "string" && num(p.start) && num(p.end) && p.end > p.start && (!want || want.has(p.id))) .map((p) => ({ id: p.id, start: p.start, end: p.end, score: num(p.score) ? p.score : null, used: !!p.used, kinds: [...new Set((p.moments ?? []).map((m) => moments.get(m)?.kind).filter((k) => typeof k === "string"))], lines: roleLines({ words, turns: reactions?.turns, speakers: reactions?.speakers }, p.start, p.end), })); } export const SUGGEST_SYSTEM = "You read moments from a livestream in which a HOST reacts to a video (the SUBJECT speaks in the video). " + "Each moment is a clip the clip finder proposed: its words, each line marked with who speaks (HOST, SUBJECT, OTHER), " + 'and what the finder heard there ("laugh": someone laughed; "chat": the stream\'s chat laughed; "comment": the host spoke over the video). ' + "For every moment give: label, at most six words naming it like a chapter title (for example: the badge reveal); " + "why, one plain sentence on what makes it land (a joke, a telling line, a reaction) or why it falls flat; " + "score, a whole number from 1 (skip it) to 10 (the best clip of the stream), judged on the clip alone. " + "Use only what is in the words. Plain words, no quotation marks around the label, no hashtags, no emoji."; /** One moment as the prompt shows it. */ export function itemText(it) { const heard = it.kinds.length ? it.kinds.join(", ") : "nothing marked"; const lines = it.lines.length ? it.lines.map(lineText).join("\n") : "(no words)"; return `[${it.id}] ${clock(it.start)}–${clock(it.end)} (${Math.round(it.end - it.start)} s) · heard: ${heard}\n${lines}`; } /** The prompt for a batch of moments. */ export function suggestPrompt(items) { return { system: SUGGEST_SYSTEM, user: `${items.length} moment${items.length === 1 ? "" : "s"}. Answer every id once.\n\n${items.map(itemText).join("\n\n")}`, }; } export const SUGGEST_ANSWER_SCHEMA = Object.freeze({ type: "object", properties: { items: { type: "array", items: { type: "object", properties: { id: { type: "string", description: "The moment's id, as given in brackets." }, label: { type: "string", description: "At most six words naming the moment." }, why: { type: "string", description: "One plain sentence." }, score: { type: "integer", description: "1 (skip it) to 10 (the best clip of the stream)." }, }, required: ["id", "label", "why", "score"], }, }, }, required: ["items"], }); const oneLine = (s) => String(s).replace(/\s+/g, " ").trim(); const words = (s) => s.split(" ").filter(Boolean).length; /** * A model's answer for a batch, read. `{ ok: false, error }` when it is not the * shape at all (the batch is refused). Otherwise each asked id's label, or a * refusal of that one item (a label over six words, an empty one, a score * outside 1–10, an id never asked): REFUSED, never cut down to fit. * @param {unknown} raw * @param {string[]} ids the ids asked * @returns {{ ok: true, items: { id: string, label: string, why: string, score: number }[], refused: { id: string, error: string }[], missing: string[] } | { ok: false, error: string }} */ export function parseSuggestAnswer(raw, ids) { if (!isObj(raw) || !Array.isArray(raw.items)) return { ok: false, error: "the answer is not { items: [...] }" }; const asked = new Set(ids); const seen = new Set(); const items = []; const refused = []; for (const it of raw.items) { if (!isObj(it) || typeof it.id !== "string") { refused.push({ id: "?", error: "an item without an id" }); continue; } const id = it.id.trim().replace(/^\[|\]$/g, ""); if (!asked.has(id)) { refused.push({ id, error: "an id that was not asked" }); continue; } if (seen.has(id)) continue; const label = typeof it.label === "string" ? oneLine(it.label).replace(/^["'“‘]+|["'”’.]+$/g, "") : ""; const why = typeof it.why === "string" ? oneLine(it.why) : ""; const score = typeof it.score === "number" ? it.score : typeof it.score === "string" && /^\d+(\.\d+)?$/.test(it.score.trim()) ? Number(it.score) : NaN; let error = null; if (!label) error = "an empty label"; else if (words(label) > SUGGEST_LABEL_MAX_WORDS) error = `a label of ${words(label)} words (at most ${SUGGEST_LABEL_MAX_WORDS})`; else if (label.length > SUGGEST_LABEL_MAX_CHARS) error = `a label of ${label.length} characters`; else if (!why) error = "no why"; else if (!Number.isFinite(score) || score < 1 || score > 10) error = `a score of ${JSON.stringify(it.score)} (1 to 10)`; if (error) { refused.push({ id, error }); continue; } seen.add(id); items.push({ id, label, why: why.length > SUGGEST_WHY_MAX ? `${why.slice(0, SUGGEST_WHY_MAX - 1).replace(/\s+\S*$/, "")}…` : why, score: Math.round(score) }); } const missing = ids.filter((id) => !seen.has(id) && !refused.some((r) => r.id === id)); return { ok: true, items, refused, missing }; } /** * The file a pass writes: the fresh labels over what the old file still holds * CURRENT (an item whose proposal is gone or moved is dropped), every item * ranked anew — by the model's score, then the finder's, then time. * @param {{ model: string, at: string, reactions: any, fresh: { id: string, label: string, why: string, score: number }[], prev?: any }} o */ export function suggestionsDocOf({ model, at, reactions, fresh, prev = null }) { const proposals = new Map((reactions?.proposals ?? []).filter((p) => isObj(p) && typeof p.id === "string").map((p) => [p.id, p])); const merged = new Map(); const staleIds = new Set(prev ? suggestionsState(prev, reactions).staleIds : []); for (const [id, it] of Object.entries(prev?.items ?? {})) { if (!proposals.has(id) || staleIds.has(id) || !num(it.score)) continue; merged.set(id, { label: it.label, why: it.why, score: it.score }); } for (const f of fresh) if (proposals.has(f.id)) merged.set(f.id, { label: f.label, why: f.why, score: f.score }); const order = [...merged.entries()].sort(([a, x], [b, y]) => { const pa = proposals.get(a); const pb = proposals.get(b); return y.score - x.score || (pb.score ?? 0) - (pa.score ?? 0) || pa.start - pb.start || a.localeCompare(b); }); const items = {}; order.forEach(([id, it], i) => { const p = proposals.get(id); items[id] = { label: it.label, why: it.why, rank: i + 1, score: it.score, start: r2(p.start), end: r2(p.end) }; }); return { model, at, proposedAt: typeof reactions?.proposedAt === "string" ? reactions.proposedAt : null, promptVersion: SUGGEST_PROMPT_VERSION, items, }; } // ---- Ask the assistant (a comment on one clip) ------------------------------------- /** The note an Ask answers, from a notes doc: an open note anchored to one clip. */ export function askNoteOf(notesDoc, noteId) { const n = (isObj(notesDoc) && Array.isArray(notesDoc.notes) ? notesDoc.notes : []).find((x) => isObj(x) && x.id === noteId); if (!n) return { error: `no note ${noteId}` }; if (!isObj(n.anchor) || n.anchor.kind !== "entry" || typeof n.anchor.entry !== "string") return { error: `note ${noteId} is not on a clip` }; return { note: { id: n.id, clip: n.anchor.entry, text: String(n.text ?? ""), status: String(n.status ?? "open"), replies: (Array.isArray(n.replies) ? n.replies : []).filter(isObj).map((r) => ({ author: String(r.author ?? ""), text: String(r.text ?? "") })), }, }; } const cutOf = (e) => ({ cutStart: num(e.cutStart) ? e.cutStart : e.start, cutEnd: num(e.cutEnd) ? e.cutEnd : e.end }); /** * The clip a note is on, its neighbours on the timeline (the next one only * when it is a clip of the same recording — what a merge needs), from the * manifest. */ export function askClipsOf(manifest, clipId) { const timeline = Array.isArray(manifest?.timeline) ? manifest.timeline : []; const i = timeline.findIndex((e) => isObj(e) && e.type === "clip" && e.id === clipId); if (i < 0) return { error: `no clip ${clipId} in the cut` }; const clip = timeline[i]; if (!num(clip.start) || !num(clip.end)) return { error: `${clipId} has no span` }; const at = (e) => (isObj(e) && e.type === "clip" && num(e.start) && num(e.end) ? { id: e.id, video: e.video, channel: e.channel ?? null, ...cutOf(e), quote: typeof e.quote === "string" ? e.quote : "" } : null); const prev = at(timeline[i - 1]); const nx = at(timeline[i + 1]); const same = (o) => o && o.video === clip.video && (o.channel ?? null) === (clip.channel ?? null); return { clip: at(clip), prev: same(prev) ? prev : null, next: same(nx) ? nx : null, nextAny: nx }; } export const ASK_SYSTEM = "You help a person cut highlight clips from a livestream in which a HOST reacts to a video (the SUBJECT). " + "The person left a comment on one clip. Read it, the clip's words (each line marked by speaker, with times in seconds on the recording), " + "and the clips either side, and answer the comment in a few plain sentences. " + "When a concrete edit would do what the comment asks, propose ONE: " + '"trim" with from and to (the clip\'s new start and end, in seconds on the recording, on a pause between words), ' + '"merge" (join it with the next clip), or "cut" (leave the clip out). Otherwise "none". ' + "You only propose: the person applies it. Use only what is in the words."; const timedLines = ({ words, turns, speakers }, a, b) => { const roles = roleMap(Array.isArray(speakers) ? speakers.filter(isObj) : []); const ts = cleanTurns(turns).filter((t) => t.end > a && t.start < b); const out = []; for (const w of wordsIn(words, a, b)) { const mid = (w.start + w.end) / 2; const t = ts.find((x) => x.start <= mid && mid <= x.end) ?? null; const speaker = t ? t.speaker : (out.at(-1)?.speaker ?? null); const last = out.at(-1); if (last && last.speaker === speaker && w.start - last.end < 1.2) { last.text += ` ${w.w}`; last.end = w.end; } else out.push({ speaker, role: speaker === null ? null : (roles.get(speaker) ?? "other"), start: w.start, end: w.end, text: w.w }); } return out.map((l) => `[${l.start.toFixed(1)}–${l.end.toFixed(1)}] ${l.role ? ROLE_WORD[l.role] ?? "OTHER" : "?"}: ${l.text}`); }; /** The prompt an Ask sends. */ export function askPrompt({ note, clips, words, turns, speakers }) { const { clip, prev, next } = clips; const from = Math.max(0, clip.cutStart - ASK_REACH_S); const to = clip.cutEnd + ASK_REACH_S; const thread = note.replies.length ? `\nThe thread so far:\n${note.replies.map((r) => `- ${r.author}: ${oneLine(r.text)}`).join("\n")}` : ""; const user = [ `The comment on clip ${clip.id} (${clip.cutStart.toFixed(1)}–${clip.cutEnd.toFixed(1)} s): ${oneLine(note.text)}${thread}`, prev ? `The clip before: ${prev.id}, ${prev.cutStart.toFixed(1)}–${prev.cutEnd.toFixed(1)} s.` : "No clip of this recording comes before it.", next ? `The next clip: ${next.id}, ${next.cutStart.toFixed(1)}–${next.cutEnd.toFixed(1)} s (a merge joins the two).` : "No clip of this recording follows it: a merge is not possible.", `The words from ${from.toFixed(1)} to ${to.toFixed(1)} s (the clip is ${clip.cutStart.toFixed(1)}–${clip.cutEnd.toFixed(1)}):`, timedLines({ words, turns, speakers }, from, to).join("\n") || "(no words)", ].join("\n\n"); return { system: ASK_SYSTEM, user }; } export const ASK_ANSWER_SCHEMA = Object.freeze({ type: "object", properties: { reply: { type: "string", description: "The answer to the comment, a few plain sentences." }, proposal: { type: "object", properties: { kind: { type: "string", enum: [...ASK_PROPOSAL_KINDS] }, from: { type: "number", description: "A trim's new start, seconds on the recording (0 otherwise)." }, to: { type: "number", description: "A trim's new end, seconds on the recording (0 otherwise)." }, }, required: ["kind", "from", "to"], }, }, required: ["reply", "proposal"], }); /** * An Ask's answer, read: the reply, and the proposal when it is one the clip * editor can perform (a trim inside reach and at least half a second; a merge * only with a next clip of the same recording). A proposal that is not is * dropped with a reason (the reply still goes); a reply that is not text is * refused. * @returns {{ ok: true, reply: string, proposal: null | { kind: "trim", clip: string, from: number, to: number, basis: { cutStart: number, cutEnd: number } } | { kind: "merge", clip: string, with: string, basis: {cutStart: number, cutEnd: number} } | { kind: "cut", clip: string, basis: {cutStart: number, cutEnd: number} }, dropped: string | null } | { ok: false, error: string }} */ export function parseAskAnswer(raw, clips) { if (!isObj(raw) || typeof raw.reply !== "string" || !raw.reply.trim()) return { ok: false, error: "the answer is not { reply, proposal }" }; const reply = raw.reply.trim().replace(/\n{3,}/g, "\n\n"); const clipped = reply.length > ASK_REPLY_MAX ? `${reply.slice(0, ASK_REPLY_MAX - 1).replace(/\s+\S*$/, "")}…` : reply; const p = isObj(raw.proposal) ? raw.proposal : null; const kind = p && typeof p.kind === "string" ? p.kind : "none"; const { clip, next } = clips; const basis = { cutStart: clip.cutStart, cutEnd: clip.cutEnd }; let proposal = null; let dropped = null; if (kind === "trim") { const from = Number(p.from); const to = Number(p.to); if (!Number.isFinite(from) || !Number.isFinite(to)) dropped = "a trim without from and to"; else if (to - from < 0.5) dropped = `a trim of ${(to - from).toFixed(2)} s (at least half a second)`; else if (from < 0) dropped = "a trim before the recording"; else if (Math.abs(from - clip.cutStart) > ASK_TRIM_MAX_MOVE_S || Math.abs(to - clip.cutEnd) > ASK_TRIM_MAX_MOVE_S) dropped = `a trim moving an edge more than ${ASK_TRIM_MAX_MOVE_S} s`; else if (Math.abs(from - clip.cutStart) < 0.05 && Math.abs(to - clip.cutEnd) < 0.05) dropped = "a trim that leaves the clip where it is"; else proposal = { kind: "trim", clip: clip.id, from: r2(from), to: r2(to), basis }; } else if (kind === "merge") { if (!next) dropped = "a merge, with no next clip of this recording"; else proposal = { kind: "merge", clip: clip.id, with: next.id, basis }; } else if (kind === "cut") { proposal = { kind: "cut", clip: clip.id, basis }; } else if (kind !== "none") dropped = `a proposal of kind ${JSON.stringify(kind)}`; return { ok: true, reply: clipped, proposal, dropped }; }