import { projectRef } from "@/lib/projects"; import { kindMakesTakes } from "@/lib/projects/kinds.mjs"; import { askEditor, cancelDraftJob, EditorError, readDraftJob, readPolicy } from "@/lib/articles/generation"; import { withEditNotes } from "@/lib/report/guard"; import { StaleToken, manifestToken } from "@/lib/report/manifest.mjs"; import { AssistRequestError, applyAssistOps, assistJobView, assistRouteOf, clearAssistJob, dismissAssistOps, draftBodyOf, parseAssistRequest, proposalsView, readAssistJob, writeAssistJob, } from "@/lib/report/videoAssist.mjs"; import { refuseCaller } from "@/lib/report/caller"; export const dynamic = "force-dynamic"; // THE VIDEO ASSISTANT (release 38 lane E) -- optional, every part of it. An // Ask (a request in words, or a note on the whole project) starts the // EDITOR's `report-draft` job, task `video-assist`, routed by // settings.generation (local by default, through the GPU arbiter); its // proposals land in `/assist-proposals.json`. This route asks with // the shared WORKER_TOKEN (lib/articles/generation.ts askEditor), follows the // job, and APPLIES on the operator's click: each op re-checked and written // through the manifest's writers (lib/report/videoAssist.mjs), token-guarded. // // GET ?project= { proposals, error, route, editorError, job, token } // GET ?project=&job= that job (ended: forgotten) // POST { project, request | note, scope? } → { jobId, job } // POST { project, action: "apply", ids?, token, at? } → { applied, failed, token, proposals } | 409 // POST { project, action: "dismiss", ids?, at? } → { dismissed, proposals } // POST ?cancel=&project= stop it const headers = { "cache-control": "no-store" }; async function assistProject(id: unknown) { const project = await projectRef(String(id ?? "")); if (!project) return { error: Response.json({ error: "no such project" }, { status: 404, headers }) }; if (!kindMakesTakes(project.kind)) return { error: Response.json({ error: "the assistant works on a report video's cut" }, { status: 400, headers }) }; return { project }; } const failed = (e: unknown) => { if (e instanceof StaleToken) return Response.json({ error: e.message, stale: true }, { status: 409, headers }); const status = e instanceof EditorError ? e.status : e instanceof AssistRequestError ? ((e as AssistRequestError & { status?: number }).status ?? 400) : 500; return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status, headers }); }; async function jobOf(dir: string, id: string) { const rec = await readAssistJob(dir); const job = await readDraftJob(id, 40); const view = assistJobView(rec && rec.jobId === id ? rec : null, job); if (view.ended) await clearAssistJob(dir, id); return view; } export async function GET(request: Request) { const url = new URL(request.url); const r = await assistProject(url.searchParams.get("project")); if ("error" in r) return r.error; const dir = r.project.dir; const id = url.searchParams.get("job"); if (id) { try { return Response.json(await jobOf(dir, id), { headers }); } catch (e) { return failed(e); } } const view = await proposalsView(dir); // The route and the followed job need the editor; without one the proposals still show. const policy = await readPolicy().catch((e: unknown) => e as Error); const rec = await readAssistJob(dir); let job = null; if (rec) { job = await jobOf(dir, rec.jobId).catch(async (e: unknown) => { if (e instanceof EditorError && e.status === 404) await clearAssistJob(dir, rec.jobId); return null; }); } return Response.json( { ...view, route: policy instanceof Error ? null : assistRouteOf(policy.generation, dir), editorError: policy instanceof Error ? policy.message : null, job, token: await manifestToken(dir), }, { headers }, ); } export async function POST(request: Request) { const refused = refuseCaller(request, "/api/report/video-assist"); if (refused) return refused; const url = new URL(request.url); const cancel = url.searchParams.get("cancel"); if (cancel) { const r = await assistProject(url.searchParams.get("project")); if ("error" in r) return r.error; try { await cancelDraftJob(cancel); return Response.json({ cancelled: true }, { headers }); } catch (e) { return failed(e); } } const body = (await request.json().catch(() => null)) as Record | null; if (!body || typeof body !== "object") return Response.json({ error: "bad json" }, { status: 400, headers }); const r = await assistProject(body.project); if ("error" in r) return r.error; const dir = r.project.dir; const ids = Array.isArray(body.ids) ? body.ids.map(String) : null; const at = typeof body.at === "string" ? body.at : null; try { if (body.action === "apply") { const token = body.token === undefined || body.token === null ? null : String(body.token); const { result, editNotes } = await withEditNotes(r.project, () => applyAssistOps(r.project, { ids, token, at })); return Response.json({ ok: true, ...result, editNotes }, { headers }); } if (body.action === "dismiss") return Response.json({ ok: true, ...(await dismissAssistOps(dir, { ids, at })) }, { headers }); if (body.action !== undefined && body.action !== "ask") return Response.json({ error: 'action is "ask", "apply" or "dismiss"' }, { status: 400, headers }); const req = parseAssistRequest(body); const running = await readAssistJob(dir); if (running) { const view = await jobOf(dir, running.jobId).catch(() => null); if (view && !view.ended) return Response.json({ error: "the assistant is already working on this project", job: view }, { status: 409, headers }); } const answer = await askEditor<{ jobId?: string }>("/api/ops/report-draft", { method: "POST", body: draftBodyOf(dir, req) }); const jobId = String(answer.jobId ?? ""); if (!jobId) return Response.json({ error: "the editor started no job" }, { status: 502, headers }); await writeAssistJob(dir, { jobId, ...(req.note ? { note: req.note } : { request: req.request }), scope: req.scope, at: new Date().toISOString() }); const job = await jobOf(dir, jobId).catch(() => ({ id: jobId, status: "queued", ended: false, queue: null, last: null, summary: null })); return Response.json({ ok: true, jobId, job }, { headers }); } catch (e) { return failed(e); } }