// THE VIDEO ASSISTANT, umtool's half (release 38 lane E): the Ask box's // request to the editor, the job the page follows, the proposals file read // for the page, and APPLY -- the one place a proposed op becomes a write. // // assist-proposals.json written by the EDITOR's `report-draft` task // `video-assist` (common lib/report/videoAssistProposals.mjs); // its ops' status marked here (applied / dismissed / failed) // .video-assist-job.json the editor job the page follows, so a reload shows it; // umtool's own file, cleared when the job is seen to end // // Apply re-checks each op against the manifest AS IT IS (common // videoAssistOps.mjs checkAssistOps -- the look's rules, the clip's window, // the declared params), then writes through the manifest's own writers: // updateRender (the look, the slide, the room), the clip editor's // runClipEditorOp (trim, room), updateChrome (a composition's param) -- each // token-guarded, the token carried from one write to the next. A stale token // stops it (409: reload); a refusal fails that op only, with its reason. // Never a raw manifest write, never free HTML. Dismiss marks ops and writes // nothing else. // // Everything is optional: with no editor, no model, or generation routed to // Claude Code, the Look panel and the clip editor are the same as before. import { readFile, rename, rm, writeFile } from "node:fs/promises"; import path from "node:path"; import { checkAssistOps } from "yt-dlp-transcript-common/lib/report/videoAssistOps.mjs"; import { chromeWithParam } from "yt-dlp-transcript-common/lib/report/fxParams.mjs"; import { markProposals, readAssistProposals, writeAssistProposals } from "yt-dlp-transcript-common/lib/report/videoAssistProposals.mjs"; import { readManifest } from "../projects/report.mjs"; import { StaleToken, manifestToken, updateChrome, updateRender } from "./manifest.mjs"; import { runClipEditorOp } from "./clipEditor.mjs"; import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; export const ASSIST_TASK = "video-assist"; export const ASSIST_JOB_FILE = ".video-assist-job.json"; export const ASSIST_SCOPES = Object.freeze(["look", "clips", "fx", "all"]); export const ASSIST_REQUEST_MAX = 2000; const JOB_RE = /^[A-Za-z0-9_-]+$/; const NOTE_RE = /^n_[a-z0-9]{4,32}$/; const OP_ID_RE = /^a\d{1,3}$/; const RESULT_MARKER = "@@report-draft "; const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v); export class AssistRequestError extends Error { constructor(message, status = 400) { super(message); this.status = status; } } /** * A POST's ask, judged: `{ request, scope? }` (the Ask box) or `{ note, scope? }` * (Ask the assistant on a note on the whole project). * @param {unknown} body */ export function parseAssistRequest(body) { if (!isObj(body)) throw new AssistRequestError("a body is { project, request | note, scope? }"); const scope = body.scope === undefined || body.scope === null ? "all" : String(body.scope); if (!ASSIST_SCOPES.includes(scope)) throw new AssistRequestError(`scope is ${ASSIST_SCOPES.join(", ")}`); if (body.note !== undefined && body.note !== null) { if (typeof body.note !== "string" || !NOTE_RE.test(body.note)) throw new AssistRequestError("a note's Ask names the note (n_…)"); if (body.request !== undefined && body.request !== null) throw new AssistRequestError("give a request or a note, not both"); return { note: body.note, scope }; } const request = typeof body.request === "string" ? body.request.replace(/\s+/g, " ").trim() : ""; if (!request) throw new AssistRequestError("say what to change"); if (request.length > ASSIST_REQUEST_MAX) throw new AssistRequestError(`a request is at most ${ASSIST_REQUEST_MAX} characters`); return { request, scope }; } /** The editor's `report-draft` body for an ask on a project directory. */ export function draftBodyOf(dir, req) { return { task: ASSIST_TASK, project: dir, ...(req.note ? { note: req.note } : { request: req.request }), ...(req.scope && req.scope !== "all" ? { scope: req.scope } : {}) }; } const jobFileOf = (dir) => path.join(/* turbopackIgnore: true */ dir, ASSIST_JOB_FILE); /** The job the page follows, or null: `{ jobId, request?, note?, scope, at }`. */ export async function readAssistJob(dir) { try { const j = JSON.parse(await readFile(jobFileOf(dir), "utf8")); return isObj(j) && typeof j.jobId === "string" && JOB_RE.test(j.jobId) ? j : null; } catch { return null; } } /** Remember the job an Ask started (tmp + rename). */ export async function writeAssistJob(dir, rec) { const file = jobFileOf(dir); const tmp = tmpPathFor(file); await writeFile(tmp, `${JSON.stringify(rec)}\n`); await rename(tmp, file); } /** Forget it — only when it is still that job. */ export async function clearAssistJob(dir, jobId) { const cur = await readAssistJob(dir); if (cur && cur.jobId === jobId) await rm(jobFileOf(dir), { force: true }); } export const ENDED = Object.freeze(["done", "failed", "cancelled", "interrupted"]); /** The job's `@@report-draft` result in its log tail, or null. */ export function assistMarkerOf(tail) { for (let i = (tail?.length ?? 0) - 1; i >= 0; i--) { const at = String(tail[i]).indexOf(RESULT_MARKER); if (at < 0) continue; try { return JSON.parse(String(tail[i]).slice(at + RESULT_MARKER.length)); } catch { return null; } } return null; } /** What the page shows of a job: its state, where it waits, its last line, and its result once it ended. */ export function assistJobView(rec, job) { const marker = assistMarkerOf(job.tail); const last = [...(job.tail ?? [])].reverse().find((l) => !String(l).includes(RESULT_MARKER)) ?? null; return { id: job.id, ...(rec?.note ? { note: rec.note } : {}), ...(rec?.request ? { request: rec.request } : {}), status: job.status, ended: ENDED.includes(job.status), queue: job.queue ?? null, last: last === null ? null : String(last).slice(0, 300), summary: typeof marker?.summary === "string" ? marker.summary : null, }; } /** * How the task is routed, for the box: `{ route, model, why }` from the * policy's generation block, or null without one. `why` is set when the box * cannot start a job here (routed to Claude Code, or no route). */ export function assistRouteOf(generation, dir) { if (!isObj(generation) || !isObj(generation.routes)) return null; const route = generation.routes[ASSIST_TASK] ?? null; if (route === "code") return { route, model: null, why: `routed to Claude Code — in a session: /gen on ${dir}: ` }; const model = route === "api" ? generation.models?.api : route === "local" ? generation.models?.local : null; return { route, model: typeof model === "string" ? model : null, why: route ? null : "the editor's policy routes no video-assist" }; } /** * The proposals for the page: each op with whether it would still apply to * the manifest as it is (`now: null` when it would, else the reason). * @param {string} dir */ export async function proposalsView(dir) { const [{ doc, error }, manifest] = await Promise.all([readAssistProposals(dir), readManifest(dir)]); if (!doc) return { proposals: null, error }; const ops = doc.ops.map((o) => { if (o.status !== "proposed" && o.status !== "failed") return { ...o, now: null }; const r = checkAssistOps(manifest ?? {}, [o.op], { request: doc.request, scope: doc.scope }); return { ...o, now: r.refused[0]?.why ?? null, diffNow: r.ops[0]?.diff ?? null }; }); return { proposals: { ...doc, ops }, error: null }; } /** * Apply proposed ops (`ids`, or every one still proposed) in the file's * order, each re-checked against the manifest as the ones before it left it. * `token` is the manifest's as the page read it (null: unguarded — the CLI). * `at`, when given, is the proposals the caller saw: a newer ask's file is a * 409, not a silent apply of other ops. * * @param {{ id: string, dir: string, kind: string }} project * @param {{ ids?: string[] | null, token?: string | null, at?: string | null, now?: string | null }} [o] * @returns {Promise<{ applied: string[], failed: { id: string, error: string }[], token: string | null, proposals: unknown }>} */ export async function applyAssistOps(project, { ids = null, token = null, at = null, now = null } = {}) { const dir = project.dir; const { doc, error } = await readAssistProposals(dir); if (!doc) throw new AssistRequestError(error ?? "no proposals to apply", 404); if (at && doc.at !== at) throw new AssistRequestError("these proposals were replaced by a newer ask — read them again", 409); if (ids && !ids.every((id) => typeof id === "string" && OP_ID_RE.test(id))) throw new AssistRequestError("ids is a list of op ids (a1, a2, …)"); const wanted = doc.ops.filter((o) => (ids ? ids.includes(o.id) : o.status === "proposed") && (o.status === "proposed" || o.status === "failed")); if (!wanted.length) throw new AssistRequestError(ids ? "those ops are not waiting (applied or dismissed already)" : "nothing is waiting to apply"); let cur = await manifestToken(dir); if (token !== null && cur !== token) throw new StaleToken(token, cur); const stamp = now ?? new Date().toISOString(); /** @type {Record} */ const marks = {}; const applied = []; const failed = []; for (const o of wanted) { const manifest = await readManifest(dir); const r = checkAssistOps(manifest ?? {}, [o.op], { request: doc.request, scope: doc.scope }); if (r.refused.length) { marks[o.id] = { status: "failed", error: r.refused[0].why }; failed.push({ id: o.id, error: r.refused[0].why }); continue; } const a = r.ops[0].apply; try { if (a.writer === "render") cur = (await updateRender(dir, a.patch, { token: cur })).token; else if (a.writer === "chrome") { const chrome = chromeWithParam(manifest.render, a.id, a.param, a.value); cur = (await updateChrome(dir, chrome, { token: cur })).token; } else { const res = await runClipEditorOp(project, { ...a.body, token: cur }); cur = res?.view?.token ?? (await manifestToken(dir)); } marks[o.id] = { status: "applied" }; applied.push(o.id); } catch (e) { // Another writer got in between: stop, say so; what was applied stays applied. if (e instanceof StaleToken) { await writeAssistProposals(dir, markProposals(doc, marks, stamp)); throw e; } const msg = e instanceof Error ? (Array.isArray(e.errors) ? e.errors.join("; ") : e.message) : String(e); marks[o.id] = { status: "failed", error: msg }; failed.push({ id: o.id, error: msg }); } } const next = markProposals(doc, marks, stamp); await writeAssistProposals(dir, next); return { applied, failed, token: cur, proposals: next }; } /** * Dismiss ops (`ids`, or every one still waiting): marked, nothing else written. * @param {string} dir * @param {{ ids?: string[] | null, at?: string | null, now?: string | null }} [o] */ export async function dismissAssistOps(dir, { ids = null, at = null, now = null } = {}) { const { doc, error } = await readAssistProposals(dir); if (!doc) throw new AssistRequestError(error ?? "no proposals to dismiss", 404); if (at && doc.at !== at) throw new AssistRequestError("these proposals were replaced by a newer ask — read them again", 409); const marks = Object.fromEntries( doc.ops.filter((o) => (ids ? ids.includes(o.id) : true) && (o.status === "proposed" || o.status === "failed")).map((o) => [o.id, { status: "dismissed" }]), ); const next = markProposals(doc, marks, now ?? new Date().toISOString()); await writeAssistProposals(dir, next); return { dismissed: Object.keys(marks), proposals: next }; }