// `report-draft {"task": "video-assist", "project", "request" | "note", // "scope"?, "model"?, "maxUsd"?, "answers"?, "dryRun"?}` — the video // assistant (release 38 lane E) as an editor job. umtool's Ask box (the Build // tab's Look panel, the clip editor's side column, a project-level note) // starts it through `editorCall`; `pnpm ops report-draft` and the MCP's // `generate` do the same. // // project the video project's directory (absolute; it must hold a // video.manifest.json, and it is never inside the corpus) // request what to change, in words (or `note`: a project-level note's // text is the request, and the proposals are posted to it as the // agent's reply with an Apply — `POST /api/notes`) // scope look | clips | fx | all (default): what the ask may touch // answers the `code` route: a Claude Code session's answer // (`{ops: [{op, id, key, value}], reply}`), checked exactly as a // model's — no model is called // dryRun (the ops route) the plan: the prompt, its estimate; nothing written // // Out: `/assist-proposals.json` — PROPOSALS ONLY; nothing is applied. // Routed by settings.generation.routes["video-assist"] (local by default: // `draft:local`, every ollama call through the GPU arbiter, so it waits behind // a transcription; ollama unloaded when the job ends) or the API (`draft:api`: // the narration cap, the daily cap, its usage in the ledger as task // `video-assist`). The log ends `@@report-draft {article: "", iteration: 0, // task: "video-assist", project, status, summary, usd, assist}`. import { modelLogged } from "./jobModelLog"; import { runManagedFunction, type StreamActionResult } from "../jobs/streamCommand"; import { DRAFT_API_QUEUE, DRAFT_LOCAL_QUEUE } from "../lib/queueKeys"; import { getSettings } from "../lib/settings"; import { capFor } from "../lib/generationSettings"; import { providerOf, unloadOllama } from "../lib/llm"; import { usageOf } from "../lib/report/draft/tasks/run"; import { ASSIST_CODE_MODEL, VIDEO_ASSIST_TASK, VideoAssistRefusal, loadAssistProject, noteReplyOf, noteRequestOf, planVideoAssist, runVideoAssist, scopeOf, type VideoAssistOutcome, type VideoAssistPlan, } from "../lib/report/draft/tasks/videoAssist"; import { getWorkerToken } from "../lib/workerToken"; import { appendGenerationUsage, dailyCapRefusal, dayUsage, utcDay, type GenerationUsageRow } from "./generationUsage"; import { projectDirOf, umtoolOrigin } from "./clipsSuggest"; import { REPORT_DRAFT_JOB_KIND, REPORT_DRAFT_RESULT_MARKER, llmConfigOf, modelFor, type ReportDraftBody, type ReportDraftDeps, type ReportDraftEnqueued } from "./reportDraft"; export { ASSIST_CODE_MODEL, VIDEO_ASSIST_TASK }; /** An Ask on a note: the reply posted to umtool's notes as the agent's, with the proposals' Apply. */ export type AssistNoteReply = { project: string; note: string; text: string; proposal: { kind: "assist"; at: string; ops: number } | null }; export type VideoAssistJobDeps = ReportDraftDeps & { postReply?: (r: AssistNoteReply) => Promise; umtoolUrl?: string | null; workerToken?: string; }; /** POST the reply to umtool's notes as the agent's. */ export async function postAssistReplyToUmtool(r: AssistNoteReply, o: { umtoolUrl: string; workerToken: string; fetch?: typeof fetch }): Promise { const f = o.fetch ?? fetch; const res = await f(`${o.umtoolUrl}/api/notes?project=${encodeURIComponent(r.project)}`, { method: "POST", headers: { authorization: `Bearer ${o.workerToken}`, "content-type": "application/json" }, body: JSON.stringify({ op: { op: "reply", id: r.note, text: r.text, ...(r.proposal ? { proposal: r.proposal } : {}) } }), }); if (!res.ok) { const j = (await res.json().catch(() => ({}))) as { error?: string }; throw new Error(`umtool refused the reply (${res.status}): ${j.error ?? res.statusText}`); } } type Refused = { result: StreamActionResult & { ok: false } }; /** The model a job runs on: a session's answer is `claude-code`'s; else the asked one, else the route's. */ function modelOfBody(body: ReportDraftBody, gen: ReturnType["generation"]): string { if (body.answers !== undefined) return ASSIST_CODE_MODEL; return modelFor(gen, VIDEO_ASSIST_TASK, body.model); } async function requestOf(body: ReportDraftBody, dir: string): Promise { if (body.note) return noteRequestOf(dir, body.note); if (!body.request) throw new VideoAssistRefusal("the assistant needs a request (or a note): say what to change"); return body.request; } /** `dryRun`: the plan, nothing written (the ops route answers `{ ok, plan }`). */ export async function planVideoAssistJob(body: ReportDraftBody, deps: Pick): Promise { const gen = (deps.settings ?? getSettings)().generation; const dir = projectDirOf(body.project ?? "", deps.paths); const route = gen.routes[VIDEO_ASSIST_TASK]; const model = body.model ?? (route === "code" ? ASSIST_CODE_MODEL : modelFor(gen, VIDEO_ASSIST_TASK)); return planVideoAssist({ project: dir, model, request: await requestOf(body, dir), scope: scopeOf(body.scope) }, { llm: llmConfigOf(gen, deps.paths) }); } export async function enqueueVideoAssist(body: ReportDraftBody, deps: VideoAssistJobDeps): Promise { const refuse = (error: string): Refused => ({ result: { ok: false as const, error } }); const paths = deps.paths; const gen = (deps.settings ?? getSettings)().generation; let dir: string; let model: string; let request: string; try { dir = projectDirOf(body.project ?? "", paths); model = modelOfBody(body, gen); // Refused at the ask, not at the job's turn: no manifest, no note, no request. await loadAssistProject(dir); request = await requestOf(body, dir); } catch (e) { return refuse((e as Error).message); } const scope = scopeOf(body.scope); const onNote = !!body.note; const umtool = deps.umtoolUrl === undefined ? umtoolOrigin() : deps.umtoolUrl; const token = deps.workerToken ?? getWorkerToken(); if (onNote && !deps.postReply) { if (!umtool) return refuse("UMTOOL_URL is not set on the editor: the assistant's reply is posted to umtool's notes"); if (!token) return refuse("WORKER_TOKEN is not set on the editor: umtool takes the assistant's reply with it"); } const provider = model === ASSIST_CODE_MODEL ? "code" : providerOf(model); let maxUsd: number | undefined; if (provider === "api") { try { maxUsd = capFor(gen.caps, "narration", body.maxUsd); } catch (e) { return refuse((e as Error).message); } const refusal = dailyCapRefusal(await dayUsage(paths.generationUsageFile, utcDay(deps.now?.())), gen.caps.daily); if (refusal) return refuse(refusal); } const postReply = deps.postReply ?? ((r: AssistNoteReply) => postAssistReplyToUmtool(r, { umtoolUrl: umtool!, workerToken: token })); const result = await runManagedFunction({ kind: REPORT_DRAFT_JOB_KIND, queueKey: provider === "local" ? DRAFT_LOCAL_QUEUE : DRAFT_API_QUEUE, paths, fn: modelLogged({ paths, task: "video-assist" }, async (onLog, signal, setProgress, ctx) => { const g = (deps.settings ?? getSettings)().generation; if (provider === "api") { const late = dailyCapRefusal(await dayUsage(paths.generationUsageFile, utcDay(deps.now?.())), g.caps.daily); if (late) throw new Error(late); } onLog( `video-assist${onNote ? ` on ${body.note}` : ""} in ${dir} on ${model} (` + (provider === "api" ? `the Claude API, cap $${maxUsd}` : provider === "local" ? "the local model, through the GPU arbiter: it waits for a transcription" : "a Claude Code session's answer") + ")", ); setProgress?.({ metric: "turns", initial: 0, target: 1, current: 0 }); let out: VideoAssistOutcome | null = null; try { out = await runVideoAssist( { project: dir, model, request, scope, ...(body.note ? { note: body.note } : {}), ...(maxUsd !== undefined ? { maxUsd } : {}), ...(body.answers !== undefined ? { answers: body.answers } : {}), }, { llm: llmConfigOf(g, paths, provider === "local" ? { onLog, signal } : undefined), log: onLog, signal, ...(deps.now ? { now: deps.now } : {}), }, ); } finally { if (provider === "local") { await unloadOllama({ baseUrl: g.ollamaUrl || paths.ollamaUrl }, model).then( () => onLog(`unloaded ${model} from ollama`), (e) => onLog(`ollama unload failed: ${(e as Error).message}`), ); } } setProgress?.({ metric: "turns", initial: 0, target: 1, current: 1 }); if (provider === "api") { const at = deps.now?.() ?? new Date(); const rows: GenerationUsageRow[] = Object.entries(out.byModel) .filter(([, t]) => t.calls > 0) .map(([m, t]) => { const u = usageOf(t); return { at: at.toISOString(), day: utcDay(at), jobId: ctx.jobId, article: "", iteration: 0, task: VIDEO_ASSIST_TASK, model: m, inputTokens: u.inputTokens, outputTokens: u.outputTokens, cacheReadTokens: u.cacheReadTokens ?? 0, cacheWriteTokens: u.cacheWriteTokens ?? 0, usd: Math.round(u.usd * 10_000) / 10_000, }; }); await appendGenerationUsage(paths.generationUsageFile, rows).catch((e) => onLog(`usage not recorded: ${(e as Error).message}`)); } if (onNote && out.status === "done" && out.proposals) { const p = out.proposals; await postReply({ project: dir, note: body.note!, text: noteReplyOf(p), proposal: p.ops.length ? { kind: "assist", at: p.at, ops: p.ops.length } : null }); onLog(`replied to ${body.note}`); } const p = out.proposals; onLog( `${REPORT_DRAFT_RESULT_MARKER}${JSON.stringify({ article: "", iteration: 0, task: VIDEO_ASSIST_TASK, project: dir, status: out.status, summary: out.summary, usd: out.usd, assist: { at: p?.at ?? null, proposed: p?.ops.length ?? 0, refused: p?.refused.length ?? 0, diff: p?.diff ?? [], file: out.file, ...(body.note ? { note: body.note } : {}) }, })}`, ); if (out.status === "cancelled" || signal.aborted) throw new Error("cancelled"); if (out.status === "failed") throw new Error(out.summary); }), }); if (!result.ok) return { result }; return { result, iteration: 0 }; }