// THE `video-assist` TASK (release 38 lane E): "make the joins 0.15 s with // less smear" on a video project, as PROPOSALS the operator applies. // // in a video project's directory (its video.manifest.json), a request in // words, a scope (look | clips | fx | all: what the view shows and the // ops may touch), and on the `code` route a Claude Code session's // answer (`answers`, read exactly as a model's) // ask ONE schema-bound ask (videoAssistOps ASSIST_OPS_SCHEMA: `{ops: // [{op, id, key, value}], reply}`) over the project's compact view -- // the look, the slide, the room, the clips with their edges and // windows, the declared params of the compositions it draws // (assistView) -- fitted to the prompt cap on a local model; the // same ask on the Claude API (no tool loop: one answer is the batch) // check every op against the manifest (checkAssistOps: the look's rules, // the clip's window and the 3 s slack, the declared params) // out `/assist-proposals.json` (videoAssistProposals.mjs): the // kept ops with their diff lines, the refused with their reasons. // NOTHING IS APPLIED: umtool's Apply does that, op by op, through // the manifest's writers. // // It never writes the manifest, notes.json or a clip. An API model is held to // `maxUsd` (the ask's estimate checked first). import { CallSlot, 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 { ASSIST_OPS_SCHEMA, ASSIST_OPS_TEXT, ASSIST_SCOPES, assistView, checkAssistOps, type AssistScope } from "../../videoAssistOps.mjs"; import { ASSIST_PROMPT_VERSION, proposalsDocOf, writeAssistProposals, type AssistProposals } from "../../videoAssistProposals.mjs"; import { fitLocalAsk } from "./revise-report"; export const VIDEO_ASSIST_TASK = "video-assist" as const; /** The `model` a Claude Code session's answer is written under (the `code` route). */ export const ASSIST_CODE_MODEL = "claude-code"; /** A request's length, at most. */ export const ASSIST_REQUEST_MAX = 2000; const ANSWER_TOKENS = 700; /** The view's budget on the API (a local model's is fitted to its cap). */ const API_VIEW_CHARS = 24_000; export class VideoAssistRefusal extends Error {} export type VideoAssistDeps = { llm: LlmConfig; // The model, stubbed (tests). ask?: (system: string, user: string, schema: object, model: string, maxTokens: number) => Promise; log?: (line: string) => void; signal?: AbortSignal; now?: () => Date; }; export type VideoAssistInput = { project: string; model: string; request: string; scope?: AssistScope; note?: string; maxUsd?: number; answers?: unknown; }; export const scopeOf = (s: unknown): AssistScope => ((ASSIST_SCOPES as readonly string[]).includes(String(s)) ? (s as AssistScope) : "all"); /** A video project: its manifest (refused without one). */ export async function loadAssistProject(dir: string): Promise<{ dir: string; manifest: Record }> { let raw: string; try { raw = await readFile(path.join(dir, "video.manifest.json"), "utf8"); } catch { throw new VideoAssistRefusal(`${dir} holds no video.manifest.json: the assistant works on a video project's cut`); } try { const manifest = JSON.parse(raw) as Record; if (!manifest || typeof manifest !== "object" || !Array.isArray(manifest.timeline)) throw new Error("no timeline"); return { dir, manifest }; } catch (e) { throw new VideoAssistRefusal(`${dir}/video.manifest.json is not a cut (${(e as Error).message})`); } } /** `m:ss.s`, a cut second as the Play view shows it. */ const cutClock = (t: number) => { const s = Math.max(0, Number.isFinite(t) ? t : 0); const m = Math.floor(s / 60); return `${m}:${(s - m * 60).toFixed(1).padStart(4, "0")}`; }; /** * Where a note taken in umtool's Play view was taken (a `cut` anchor), as the * words appended to its request: "(noted while playing take short-19 at * 1:12.4, in clip c04 at source 194.2 s)". The clip names what "this" is; a * take's patch is not what the ops edit (they edit the project's cut). */ export function cutContextOf(a: { t?: unknown; entry?: unknown; sourceT?: unknown; take?: unknown; ask?: unknown }): string { const where = [`at ${cutClock(Number(a.t))}`]; if (typeof a.entry === "string" && a.entry) { where.push(`in clip ${a.entry}${typeof a.sourceT === "number" && Number.isFinite(a.sourceT) ? ` at source ${a.sourceT.toFixed(1)} s` : ""}`); } const take = typeof a.take === "string" && a.take ? `take ${a.take}` : "the cut"; const ask = typeof a.ask === "string" && /^[a-z]{2,8}$/.test(a.ask) && a.ask !== "other" ? `; asks for a ${a.ask}` : ""; return `(noted while playing ${take} ${where.join(", ")}${ask})`; } /** * A note's text, as the request (an Ask on a note): a note on the whole * project, or one taken in the Play view (`cut`: its text with where it was * taken -- the cut second, the clip, the take). */ export async function noteRequestOf(dir: string, noteId: string): Promise { let doc: unknown = null; try { doc = JSON.parse(await readFile(path.join(dir, "notes.json"), "utf8")); } catch { throw new VideoAssistRefusal(`${dir} has no notes.json: no note ${noteId}`); } const notes = (doc as { notes?: unknown[] })?.notes; const n = Array.isArray(notes) ? (notes.find((x) => (x as { id?: unknown })?.id === noteId) as { text?: unknown; status?: unknown; anchor?: { kind?: unknown; t?: unknown; entry?: unknown; sourceT?: unknown; take?: unknown; ask?: unknown } } | undefined) : undefined; if (!n) throw new VideoAssistRefusal(`no note ${noteId} in ${dir}/notes.json`); const kind = n.anchor?.kind; if (kind !== "whole" && kind !== "cut") { throw new VideoAssistRefusal(`${noteId} is on a part of the project: the assistant answers a note on the whole project or one taken in the Play view (a clip's note is the clip editor's Ask)`); } if (n.status !== "open") throw new VideoAssistRefusal(`${noteId} is resolved`); const text = typeof n.text === "string" ? n.text.trim() : ""; if (!text) throw new VideoAssistRefusal(`${noteId} has no text`); if (kind === "cut") { const where = ` ${cutContextOf(n.anchor ?? {})}`; return `${text.slice(0, ASSIST_REQUEST_MAX - where.length)}${where}`; } return text.slice(0, ASSIST_REQUEST_MAX); } const SYSTEM = (scope: AssistScope) => [ "You adjust a video project's settings for its editor. You read the project's settings now and a request in plain words, and answer with the edit operations that carry it out — nothing else changes.", "Rules: use only the operations and keys below; give the new value (\"quicker joins\" → a shorter transition than now; \"louder\" → a higher loudness target than now; \"less\" or \"more\" of something → a value a clear step from the current one, within its bounds).", "If the request asks for something no operation can do, or a value outside the bounds shown, give no op for it and say so in `reply`.", scope === "all" ? "" : `Only ${scope === "look" ? "the look, the slide and the room" : scope === "clips" ? "the clips' edges and room" : "the compositions' params"} may change.`, "`reply` is one short plain sentence for the editor: what you changed, or why not.", "", ASSIST_OPS_TEXT, ] .filter(Boolean) .join("\n"); const userOf = (request: string, view: string) => `THE REQUEST:\n${request}\n\nTHE PROJECT NOW:\n${view}\n\nAnswer with the ops that carry out the request, and the reply.`; /** The prompt one ask sends: on a local model the view is fitted to its prompt cap. */ export function assistPrompt(o: { manifest: unknown; request: string; scope: AssistScope; model: string; llm: LlmConfig }): { system: string; user: string; tokens: number } { const system = SYSTEM(o.scope); const build = (maxChars: number) => userOf(o.request, assistView(o.manifest, { maxChars: maxChars - o.request.length - 120, request: o.request, scope: o.scope }).text); if (providerOf(o.model) === "local") { const fitted = fitLocalAsk({ llm: o.llm, model: o.model, system, schema: ASSIST_OPS_SCHEMA, build }); return { system, user: fitted.user, tokens: fitted.tokens }; } const user = build(API_VIEW_CHARS); return { system, user, tokens: structuredPromptEstimate({ system, user, schema: ASSIST_OPS_SCHEMA }) }; } export type VideoAssistPlan = { project: string; model: string; provider: "api" | "local" | "code"; promptVersion: string; scope: AssistScope; estimate: { inputTokens: number; outputTokens: number; usd: number }; // The request a Claude Code session answers (the `code` route). request: { system: string; user: string; schema: object }; }; /** What one ask would send, and roughly what it costs — nothing called, nothing written. */ export async function planVideoAssist(input: Omit, deps: Pick): Promise { const { manifest } = await loadAssistProject(input.project); const scope = scopeOf(input.scope); const code = input.model === ASSIST_CODE_MODEL; const pr = assistPrompt({ manifest, request: input.request, scope, model: code ? "claude-sonnet-5-5" : input.model, llm: deps.llm }); const p = priceOf(code ? "claude-sonnet-5-5" : input.model); const usd = code || providerOf(input.model) === "local" ? 0 : (pr.tokens * p.input + ANSWER_TOKENS * p.output) / 1e6; return { project: input.project, model: input.model, provider: code ? "code" : providerOf(input.model), promptVersion: ASSIST_PROMPT_VERSION, scope, estimate: { inputTokens: pr.tokens, outputTokens: ANSWER_TOKENS, usd: Math.round(usd * 10_000) / 10_000 }, request: { system: pr.system, user: pr.user, schema: ASSIST_OPS_SCHEMA }, }; } export type VideoAssistOutcome = { status: "done" | "cancelled" | "failed"; project: string; model: string; request: string; scope: AssistScope; proposals: AssistProposals | null; file: string | null; usd: number; byModel: ReturnType["byModel"]; summary: string; }; const plural = (n: number, w: string) => `${n} ${w}${n === 1 ? "" : "s"}`; /** The answer's ops and reply, or why it is not one. */ export function parseAssistAnswer(raw: unknown): { ok: true; ops: unknown[]; reply: string } | { ok: false; error: string } { if (!raw || typeof raw !== "object" || Array.isArray(raw)) return { ok: false, error: "the answer is not { ops: [...] }" }; const a = raw as { ops?: unknown; reply?: unknown }; if (!Array.isArray(a.ops)) return { ok: false, error: "the answer has no ops list" }; if (a.ops.length > 40) return { ok: false, error: `${a.ops.length} ops is more than one request needs (at most 40)` }; return { ok: true, ops: a.ops, reply: typeof a.reply === "string" ? a.reply : "" }; } /** One ask (or a session's answer), checked, written as proposals. */ export async function runVideoAssist(input: VideoAssistInput, deps: VideoAssistDeps): Promise { const log = deps.log ?? (() => {}); const now = () => deps.now?.() ?? new Date(); const request = input.request.replace(/\s+/g, " ").trim(); if (!request) throw new VideoAssistRefusal("the assistant needs a request: say what to change"); if (request.length > ASSIST_REQUEST_MAX) throw new VideoAssistRefusal(`a request is at most ${ASSIST_REQUEST_MAX} characters`); const scope = scopeOf(input.scope); const { manifest } = await loadAssistProject(input.project); const meter = new Meter(); const base = { project: input.project, model: input.model, request, scope }; let raw: unknown; // What code did with the answer's ops (the model log). const slot = new CallSlot(); if (input.answers !== undefined) { log(`video-assist ${input.project}: a Claude Code session's answer (prompt ${ASSIST_PROMPT_VERSION})`); raw = input.answers; const pr = assistPrompt({ manifest, request, scope, model: "claude-sonnet-5-5", llm: deps.llm }); recordSessionAnswer({ phase: "assist", system: pr.system, prompt: pr.user, answer: raw, llm: deps.llm }, slot); } else { const pr = assistPrompt({ manifest, request, scope, model: input.model, llm: deps.llm }); log(`video-assist ${input.project} on ${input.model} (${scope}): one ask, ~${pr.tokens} prompt tokens (prompt ${ASSIST_PROMPT_VERSION})`); if (providerOf(input.model) === "api" && input.maxUsd !== undefined) { const p = priceOf(input.model); const est = (pr.tokens * p.input + ANSWER_TOKENS * p.output) / 1e6; if (est > input.maxUsd) throw new VideoAssistRefusal(`the ask (~$${est.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, call: { phase: "assist", label: request.slice(0, 80), slot } })); try { raw = await ask(pr.system, pr.user, ASSIST_OPS_SCHEMA, input.model, 2048); } catch (e) { if (deps.signal?.aborted) return { ...base, status: "cancelled", proposals: null, file: null, usd: meter.usd, byModel: meter.summary().byModel, summary: "cancelled" }; throw e; } } const parsed = parseAssistAnswer(raw); if (!parsed.ok) { slot.decide("dropped", parsed.error); if (input.answers !== undefined) throw new VideoAssistRefusal(`the session's answer is refused: ${parsed.error}`); throw new StructuredAnswerError(`${input.model}: ${parsed.error}: ${JSON.stringify(raw ?? null).slice(0, 160)}`); } if (deps.signal?.aborted) return { ...base, status: "cancelled", proposals: null, file: null, usd: meter.usd, byModel: meter.summary().byModel, summary: "cancelled" }; // Checked against the manifest as it is NOW: a cut edited while the model thought is what the ops meet. const fresh = (await loadAssistProject(input.project)).manifest; const checked = checkAssistOps(fresh, parsed.ops, { request, scope }); for (const k of checked.ops) log(` proposed: ${k.diff}${k.warning ? ` (${k.warning})` : ""}`); for (const r of checked.refused) log(` refused: ${JSON.stringify(r.op).slice(0, 120)} — ${r.why}`); slot.decide(checked.ops.length ? "kept" : "dropped", checked.ops.length ? `${plural(checked.ops.length, "edit")} proposed` : "no edit proposed", [ ...checked.ops.map((k) => ({ text: k.diff, outcome: "kept" as const, why: k.warning ?? "proposed" })), ...checked.refused.map((r) => ({ text: JSON.stringify(r.op).slice(0, 200), outcome: "dropped" as const, why: r.why })), ]); const proposals = proposalsDocOf({ at: now().toISOString(), model: input.model, request, scope, ...(input.note ? { note: input.note } : {}), reply: parsed.reply || null, checked, }); const file = await writeAssistProposals(input.project, proposals); const usd = Math.round(meter.usd * 1e6) / 1e6; const summary = (checked.ops.length ? `${plural(checked.ops.length, "edit")} proposed (${checked.diff.join("; ")})` : "no edit proposed") + (checked.refused.length ? `, ${checked.refused.length} refused` : "") + ` on ${input.model}` + (usd ? ` · $${usd.toFixed(4)}` : ""); return { ...base, status: "done", proposals, file, usd, byModel: meter.summary().byModel, summary }; } /** The reply an Ask on a note posts: the proposals in words, and where they are applied. */ export function noteReplyOf(p: AssistProposals): string { const kept = p.ops.map((o) => `• ${o.diff}${o.warning ? ` (${o.warning})` : ""}`); const refused = p.refused.map((r) => `• not done: ${r.why}`); const head = kept.length ? `Proposed ${plural(kept.length, "edit")} — Apply below or in the Build tab's Look panel:` : "No edit proposed."; return [p.reply ? p.reply : "", head, ...kept, ...refused].filter(Boolean).join("\n").slice(0, 3800); }