// THE `clips-suggest` TASK (release 36 lane D): the clip finder's OPTIONAL // AI pass, in two kinds. // // labels every proposal of a reactions project (or the ones named) → a // label (≤ 6 words), a why (one line), a rank (1 = best) — into // `/clip-suggestions.json` through its one writer // (lib/clips/suggest.mjs). The proposals go in batches (30 a call // on the Claude API; fitted to the prompt cap on a local model); // the model scores each 1–10 and CODE ranks them, so a pass in // batches still ranks the whole file. A batch whose answer is not // the shape is refused (its proposals stay unlabelled, named in // the log); a single label over six words is refused, never cut. // ask one comment (a note on a clip, notes.json): the note, the clip's // words labelled by speaker, ±20 s around it and the clips either // side → a reply, and at most one concrete proposal the clip editor // can perform (a trim {from, to}, a merge with the next clip, a // cut). The reply is handed to `postReply` (the controller posts it // to umtool's notes as the agent's); the proposal is NEVER applied // here — the operator's Apply does it. // // It never writes the manifest, a clip, notes.json or reactions.json. An API // model is held to `maxUsd` (each call's estimate checked against the spend so // far: past it the run ends `capped`, keeping what it labelled). // // The words: the project's word timings (reactions.json `source.words`, else // words.json), else the recording's cues from the corpus (`cuesOf`), spread // over their words. import { recordSessionAnswer } from "../../../llm/callLog-server"; import { readFile } from "node:fs/promises"; import path from "node:path"; import { Meter, priceOf, providerOf, StructuredAnswerError, structuredAnswer, structuredPromptEstimate, type LlmConfig } from "../../../llm"; import type { CuesOf } from "../../convertShared"; import { readReactions, type ReactionsDoc } from "../../../clips/reactions.mjs"; import type { Word } from "../../../clips/clips.mjs"; import { ASK_ANSWER_SCHEMA, askClipsOf, askNoteOf, askPrompt, parseAskAnswer, parseSuggestAnswer, readSuggestions, SUGGEST_ANSWER_SCHEMA, SUGGEST_API_BATCH, SUGGEST_PROMPT_VERSION, suggestionsDocOf, suggestItems, suggestPrompt, wordsFor, wordsOfFile, writeSuggestions, type AskClips, type AskNote, type AskProposal, type SuggestAnswerItem, type SuggestInput, } from "../../../clips/suggest.mjs"; import { PROMPT_CAP_TOKENS } from "../../../llm/ollama"; export const CLIPS_SUGGEST_TASK = "clips-suggest" as const; /** The `model` a Claude Code session's answers are written under (the `code` route). */ export const CODE_MODEL = "claude-code"; const LOCAL_CAP = PROMPT_CAP_TOKENS - 400; const ANSWER_TOKENS_PER_ITEM = 60; // A local model answers at most this many in one call (an 8B model loses ids in a long list). export const LOCAL_BATCH_MAX = 20; const ASK_ANSWER_TOKENS = 500; export class ClipsSuggestRefusal extends Error {} export type ClipsSuggestDeps = { llm: LlmConfig; // The recording's cues, when the project holds no word timings. cuesOf?: CuesOf; // The model, stubbed (tests). ask?: (system: string, user: string, schema: object, model: string, maxTokens: number) => Promise; log?: (line: string) => void; progress?: (done: number, total: number) => void; signal?: AbortSignal; now?: () => Date; localCapTokens?: number; }; export type ClipsProject = { dir: string; reactions: ReactionsDoc; words: Word[]; wordsFrom: string }; const isRel = (p: unknown): p is string => typeof p === "string" && !!p && !path.isAbsolute(p) && !p.split(/[\\/]/).some((s) => s === ".." || s === ""); /** A reactions project: its reactions.json (refused without one) and the words its pass reads. */ export async function loadClipsProject(dir: string, deps: Pick): Promise { const reactions = (await readReactions(dir)) as ReactionsDoc | null; if (!reactions) throw new ClipsSuggestRefusal(`${dir} holds no reactions.json: the clip finder has not run there (umtool's Find the clips)`); const rel = isRel(reactions.source?.words) ? reactions.source.words : "words.json"; try { const words = wordsOfFile(JSON.parse(await readFile(path.join(dir, rel), "utf8"))); if (words.length) return { dir, reactions, words, wordsFrom: rel }; } catch { // no word timings in the project: the cues } const { channel, video } = reactions.source ?? ({} as ReactionsDoc["source"]); const cues = channel && video && deps.cuesOf ? await deps.cuesOf(channel, video).catch(() => null) : null; return { dir, reactions, words: wordsFor({ cues: cues ? [...cues] : [] }), wordsFrom: cues?.length ? "cues" : "none" }; } /** The batches a model is asked in: SUGGEST_API_BATCH on the API; on a local model at most LOCAL_BATCH_MAX, fitted to the prompt cap. */ export function batchesOf(items: SuggestInput[], model: string, localCap = LOCAL_CAP): SuggestInput[][] { const out: SuggestInput[][] = []; if (providerOf(model) === "api") { for (let i = 0; i < items.length; i += SUGGEST_API_BATCH) out.push(items.slice(i, i + SUGGEST_API_BATCH)); return out; } let cur: SuggestInput[] = []; for (const it of items) { const next = [...cur, it]; if (cur.length && (cur.length >= LOCAL_BATCH_MAX || structuredPromptEstimate({ ...suggestPrompt(next), schema: SUGGEST_ANSWER_SCHEMA }) > localCap)) { out.push(cur); cur = [it]; } else cur = next; } if (cur.length) out.push(cur); return out; } const callEstimate = (system: string, user: string, schema: object, model: string, outTokens: number) => { const input = structuredPromptEstimate({ system, user, schema }); const p = priceOf(model); return { inputTokens: input, outputTokens: outTokens, usd: (input * p.input + outTokens * p.output) / 1e6 }; }; export type SuggestPlan = { project: string; model: string; provider: "api" | "local" | "code"; promptVersion: string; wordsFrom: string; proposals: number; calls: number; estimate: { inputTokens: number; outputTokens: number; usd: number }; // The request a Claude Code session answers (the `code` route): the prompt and // the answer's shape. request: { system: string; user: string; schema: object; ids: string[] }; }; /** What a labels pass would ask, and roughly what it costs — nothing called, nothing written. */ export async function planClipsSuggest(input: { project: string; model: string; proposals?: string[] }, deps: Pick): Promise { const p = await loadClipsProject(input.project, deps); const items = suggestItems(p.reactions, p.words, { ids: input.proposals?.length ? input.proposals : null }); const code = input.model === CODE_MODEL; const batches = code ? [items] : batchesOf(items, input.model, deps.localCapTokens ?? LOCAL_CAP); let est = { inputTokens: 0, outputTokens: 0, usd: 0 }; for (const b of batches) { const pr = suggestPrompt(b); const e = callEstimate(pr.system, pr.user, SUGGEST_ANSWER_SCHEMA, code ? "claude-sonnet-5-5" : input.model, b.length * ANSWER_TOKENS_PER_ITEM); est = { inputTokens: est.inputTokens + e.inputTokens, outputTokens: est.outputTokens + e.outputTokens, usd: est.usd + (code ? 0 : e.usd) }; } const all = suggestPrompt(items); return { project: input.project, model: input.model, provider: code ? "code" : providerOf(input.model), promptVersion: SUGGEST_PROMPT_VERSION, wordsFrom: p.wordsFrom, proposals: items.length, calls: code ? 0 : batches.length, estimate: { ...est, usd: Math.round(est.usd * 10_000) / 10_000 }, request: { system: all.system, user: all.user, schema: SUGGEST_ANSWER_SCHEMA, ids: items.map((i) => i.id) }, }; } export type ClipsSuggestOutcome = { status: "done" | "capped" | "cancelled" | "failed"; project: string; model: string; labelled: number; refused: { id: string; error: string }[]; failed: { ids: string[]; error: string }[]; file: string | null; usd: number; byModel: ReturnType["byModel"]; summary: string; }; const plural = (n: number, w: string) => `${n} ${w}${n === 1 ? "" : "s"}`; /** * The labels pass: ask the model batch by batch (or take a Claude Code * session's `answers`), then write the file once, merged over the labels of * the old file that are still current. */ export async function runClipsSuggest( input: { project: string; model: string; proposals?: string[]; maxUsd?: number; answers?: unknown }, deps: ClipsSuggestDeps, ): Promise { const log = deps.log ?? (() => {}); const now = () => deps.now?.() ?? new Date(); const p = await loadClipsProject(input.project, deps); const items = suggestItems(p.reactions, p.words, { ids: input.proposals?.length ? input.proposals : null }); const meter = new Meter(); const fresh: SuggestAnswerItem[] = []; const refused: ClipsSuggestOutcome["refused"] = []; const failed: ClipsSuggestOutcome["failed"] = []; let status: ClipsSuggestOutcome["status"] = "done"; if (!items.length) throw new ClipsSuggestRefusal(`${input.project}: reactions.json holds no proposals to label`); log(`clips-suggest ${input.project} on ${input.model}: ${plural(items.length, "proposal")}, words from ${p.wordsFrom} (prompt ${SUGGEST_PROMPT_VERSION})`); if (input.answers !== undefined) { // The `code` route: a Claude Code session's answer, read as a model's is. const all = suggestPrompt(items); recordSessionAnswer({ phase: "labels", system: all.system, prompt: all.user, answer: input.answers, llm: deps.llm }); const r = parseSuggestAnswer(input.answers, items.map((i) => i.id)); if (!r.ok) throw new ClipsSuggestRefusal(`the session's answers are refused: ${r.error}`); fresh.push(...r.items); refused.push(...r.refused); deps.progress?.(items.length, items.length); } else { const ask = deps.ask ?? ((system: string, user: string, schema: object, model: string, maxTokens: number) => structuredAnswer({ llm: deps.llm, model, system, user, schema, meter, ...(deps.signal ? { signal: deps.signal } : {}), maxTokens })); const batches = batchesOf(items, input.model, deps.localCapTokens ?? LOCAL_CAP); const api = providerOf(input.model) === "api"; let done = 0; deps.progress?.(0, items.length); for (const [bi, batch] of batches.entries()) { if (deps.signal?.aborted) { status = "cancelled"; break; } const pr = suggestPrompt(batch); const outTokens = Math.min(8192, 256 + batch.length * ANSWER_TOKENS_PER_ITEM * 2); if (api && input.maxUsd !== undefined) { const next = callEstimate(pr.system, pr.user, SUGGEST_ANSWER_SCHEMA, input.model, batch.length * ANSWER_TOKENS_PER_ITEM).usd; if (meter.usd + next > input.maxUsd) { status = "capped"; log(`stopped at the cap: $${meter.usd.toFixed(4)} spent, the next batch (~$${next.toFixed(4)}) would pass $${input.maxUsd}`); break; } } const ids = batch.map((b) => b.id); try { const raw = await ask(pr.system, pr.user, SUGGEST_ANSWER_SCHEMA, input.model, outTokens); const r = parseSuggestAnswer(raw, ids); if (!r.ok) throw new StructuredAnswerError(`${r.error}: ${JSON.stringify(raw ?? null).slice(0, 120)}`); fresh.push(...r.items); refused.push(...r.refused, ...r.missing.map((id) => ({ id, error: "not answered" }))); log(`batch ${bi + 1}/${batches.length}: ${plural(r.items.length, "label")}${r.refused.length + r.missing.length ? `, ${r.refused.length + r.missing.length} refused or missing` : ""}`); for (const x of r.refused) log(` ${x.id}: refused — ${x.error}`); } catch (err) { if (deps.signal?.aborted) { status = "cancelled"; break; } const error = (err as Error).message.slice(0, 300); failed.push({ ids, error }); log(`batch ${bi + 1}/${batches.length} (${ids[0]}…${ids.at(-1)}): no labels — ${error}`); } done += batch.length; deps.progress?.(done, items.length); } } const usd = Math.round(meter.usd * 1e6) / 1e6; let file: string | null = null; if (fresh.length) { const prev = (await readSuggestions(input.project)).doc; // Read again at the write: a pass that ran meanwhile is what the labels are merged over. const reactions = (await readReactions(input.project)) ?? p.reactions; file = await writeSuggestions(input.project, suggestionsDocOf({ model: input.model, at: now().toISOString(), reactions, fresh, prev })); } if (!fresh.length && status === "done") status = "failed"; const summary = `${plural(fresh.length, "proposal")} labelled on ${input.model}` + (refused.length ? `, ${refused.length} refused` : "") + (failed.length ? `, ${plural(failed.reduce((n, f) => n + f.ids.length, 0), "proposal")} in failed batches` : "") + (status === "capped" ? ", stopped at the cap" : status === "cancelled" ? ", cancelled" : "") + (usd ? ` · $${usd.toFixed(4)}` : ""); return { status, project: input.project, model: input.model, labelled: fresh.length, refused, failed, file, usd, byModel: meter.summary().byModel, summary }; } export type ClipsAskOutcome = { status: "done" | "cancelled"; project: string; model: string; note: string; clip: string; reply: string; proposal: AskProposal | null; dropped: string | null; usd: number; byModel: ReturnType["byModel"]; summary: string; }; /** The note an Ask answers, and the clips it reads, from the project's files. */ export async function loadAsk(dir: string, noteId: string): Promise<{ note: AskNote; clips: AskClips }> { const read = async (name: string) => { try { return JSON.parse(await readFile(path.join(dir, name), "utf8")) as unknown; } catch { return null; } }; const n = askNoteOf(await read("notes.json"), noteId); if ("error" in n) throw new ClipsSuggestRefusal(n.error); const clips = askClipsOf(await read("video.manifest.json"), n.note.clip); if ("error" in clips) throw new ClipsSuggestRefusal(clips.error); return { note: n.note, clips }; } /** An Ask: the reply and its proposal, handed to `postReply`. */ export async function runClipsAsk( input: { project: string; model: string; note: string; maxUsd?: number }, deps: ClipsSuggestDeps & { postReply: (r: { note: string; text: string; proposal: AskProposal | null }) => Promise }, ): Promise { const log = deps.log ?? (() => {}); const p = await loadClipsProject(input.project, deps); const { note, clips } = await loadAsk(input.project, input.note); const pr = askPrompt({ note, clips, words: p.words, turns: p.reactions.turns, speakers: p.reactions.speakers }); log(`clips-suggest ask ${input.note} on ${clips.clip.id} (${input.model}), words from ${p.wordsFrom}`); const meter = new Meter(); if (providerOf(input.model) === "api" && input.maxUsd !== undefined) { const e = callEstimate(pr.system, pr.user, ASK_ANSWER_SCHEMA, input.model, ASK_ANSWER_TOKENS).usd; if (e > input.maxUsd) throw new ClipsSuggestRefusal(`the ask (~$${e.toFixed(4)}) is over its cap of $${input.maxUsd}`); } const ask = deps.ask ?? ((system: string, user: string, schema: object, model: string, maxTokens: number) => structuredAnswer({ llm: deps.llm, model, system, user, schema, meter, ...(deps.signal ? { signal: deps.signal } : {}), maxTokens })); const raw = await ask(pr.system, pr.user, ASK_ANSWER_SCHEMA, input.model, 1024); const r = parseAskAnswer(raw, clips); if (!r.ok) throw new StructuredAnswerError(`${input.model}: ${r.error}: ${JSON.stringify(raw ?? null).slice(0, 120)}`); if (r.dropped) log(`the proposal is not kept: ${r.dropped}`); if (deps.signal?.aborted) { return { status: "cancelled", project: input.project, model: input.model, note: note.id, clip: clips.clip.id, reply: r.reply, proposal: r.proposal, dropped: r.dropped, usd: meter.usd, byModel: meter.summary().byModel, summary: "cancelled" }; } await deps.postReply({ note: note.id, text: r.reply, proposal: r.proposal }); const usd = Math.round(meter.usd * 1e6) / 1e6; const what = r.proposal ? (r.proposal.kind === "trim" ? `a trim to ${r.proposal.from}–${r.proposal.to} s` : r.proposal.kind === "merge" ? `a merge with ${r.proposal.with}` : "a cut") : "no edit"; log(`replied to ${note.id}, proposing ${what}`); return { status: "done", project: input.project, model: input.model, note: note.id, clip: clips.clip.id, reply: r.reply, proposal: r.proposal, dropped: r.dropped, usd, byModel: meter.summary().byModel, summary: `replied to ${note.id} on ${clips.clip.id}, proposing ${what}${usd ? ` · $${usd.toFixed(4)}` : ""}`, }; }