import { getJob, jobView, runningJob, startJob } from "@/lib/jobs"; import { invalidateProjects, projectRef } from "@/lib/projects"; import { agentToken, routeCaller } from "@/lib/annotations/agentAuth.mjs"; import { ClipsNewError, planClipsNew } from "@/lib/report/clipsNew.mjs"; import { liveClips } from "@/lib/report/clipsLive.mjs"; import { clipEditorHref } from "@/lib/hrefs"; import { kindMakesTakes } from "@/lib/projects/kinds.mjs"; import { readReactions } from "yt-dlp-transcript-common/lib/clips/reactions.mjs"; import { clipsSteps } from "@/lib/report/reactions.mjs"; export const dynamic = "force-dynamic"; // THE CLIP FINDER (release 35 C1) -- "Find the clips" (the laugh scan and the // voices on the recording's sound, then a proposal pass) and "Re-propose" // (the pass alone, after a role flip or a param change), as ONE job on the // app's runner (lib/jobs.ts: one at a time, a log, the NDJSON events, // Cancel). The job runs the CLI (`umtool clips analyze|propose`), so the // button and a terminal do the same thing. Local (CED-mini and TitaNet on the // CPU, nice'd), no network, no LLM. // // GET ?job=[&since=&sinceEvent=] that job // GET ?project= the project's reactions.json summary, and the job running, if any // POST { project, mode?: "analyze" | "propose", from?: "/", target?: seconds, host?: speaker, // scope?: [from, to] | "auto" | "all", segment?: "s1" } → { jobId, job } // POST { mode: "new", slug, from: "/", target?, scope?: "auto" (default) | "all" | [from, to], // segment?, wordsPath? } (release 36: the editor's Find clips) → { jobId, job, project, created, segments, // segment, scope, href, notes } — a reactions project for the same recording whose scope covers the // chosen one is analyzed again (`created: false`), else `slug` is scaffolded (lib/report/clipsNew.mjs) // POST { mode: "live", slug, from: "/", final?, check? } (live pre-clip, the editor's // live-preclip job after each tick) → { project, created, proposals, clips, minedTo, flags, notes, href } // — synchronous, no job: the stream's project grown from data//live-transcript.json // (lib/report/clipsLive.mjs); `final` hands it to the corpus // ?cancel= stop it // A POST with no Authorization header is the app's page; `Bearer ` the editor; any other: 401. export async function GET(request: Request) { const url = new URL(request.url); const headers = { "cache-control": "no-store" }; const id = url.searchParams.get("job"); if (id) { const job = getJob(id); if (!job) return Response.json({ error: "no such job" }, { status: 404 }); return Response.json(jobView(job, Number(url.searchParams.get("since") ?? 0), Number(url.searchParams.get("sinceEvent") ?? 0)), { headers }); } const project = await projectRef(String(url.searchParams.get("project") ?? "")); if (!project) return Response.json({ error: "no such project" }, { status: 404 }); const doc = await readReactions(project.dir); const running = runningJob(); const used = doc ? doc.proposals.filter((p) => p.used) : []; return Response.json( { reactions: doc ? { source: doc.source, params: doc.params, speakers: doc.speakers, laughs: doc.laughs.length, laughSource: doc.laughSource ?? null, proposals: doc.proposals.length, used: used.length, usedSeconds: Math.round(used.reduce((n, p) => n + (p.end - p.start), 0)), proposedAt: doc.proposedAt ?? null, rolesChangedAt: doc.rolesChangedAt ?? null, segments: Array.isArray(doc.segments) ? doc.segments : null, segment: doc.segment ?? null, chat: doc.chat ? { source: doc.chat.source, lagS: doc.chat.lagS, lag: doc.chat.lag ?? null, messages: doc.chat.messages ?? null, bursts: doc.chat.bursts ?? null } : null, } : null, running: running && running.project === project.id && running.kind.startsWith("clips-") ? jobView(running) : null, }, { headers }, ); } export async function POST(request: Request) { const url = new URL(request.url); const who = routeCaller(request.headers.get("authorization"), agentToken(), "/api/report/clips"); if (!who.ok) return Response.json({ error: who.error }, { status: who.status }); const cancel = url.searchParams.get("cancel"); if (cancel) { const { cancelJob } = await import("@/lib/jobs"); return Response.json({ cancelled: cancelJob(cancel) }); } const body = (await request.json().catch(() => null)) as Record | null; if (!body || typeof body !== "object") return Response.json({ error: "bad json" }, { status: 400 }); if (body.mode === "new") return startNew(body); if (body.mode === "live") return liveMode(body); const project = await projectRef(String(body.project ?? "")); if (!project) return Response.json({ error: "no such project" }, { status: 404 }); if (!kindMakesTakes(project.kind)) return Response.json({ error: "clips are found for a report video" }, { status: 400 }); const running = runningJob(); if (running) { return Response.json({ error: `a job is already running (${running.kind})`, running: jobView(running) }, { status: 409 }); } const plan = clipsSteps(project, { mode: body.mode === "propose" ? "propose" : "analyze", ...(typeof body.from === "string" ? { from: body.from } : {}), ...(typeof body.target === "number" ? { target: body.target } : {}), ...(typeof body.host === "number" ? { host: body.host } : {}), ...(Array.isArray(body.scope) || body.scope === "auto" || body.scope === "all" ? { scope: body.scope as [number, number | null] | "auto" | "all" } : {}), ...(typeof body.segment === "string" ? { segment: body.segment } : {}), }); try { const job = startJob(plan.kind, plan.steps, { project: project.id }); return Response.json({ ok: true, jobId: job.id, job: jobView(job) }, { headers: { "cache-control": "no-store" } }); } catch (e) { return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 409 }); } } /** * `mode: "live"` (plans/live-preclip.md): the stream's project made or grown * from the editor's live transcript — one proposal pass, answered here, never * a job (it must not wait behind a render). `final: true` hands it to the * corpus (lib/report/clipsLive.mjs). */ async function liveMode(body: Record) { try { const r = await liveClips(body); invalidateProjects(); return Response.json({ ok: true, ...r }, { headers: { "cache-control": "no-store" } }); } catch (e) { const status = e instanceof ClipsNewError ? e.status : 500; return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status }); } } /** `mode: "new"`: the project found or scaffolded, then `clips analyze` as one job. */ async function startNew(body: Record) { const running = runningJob(); if (running) { return Response.json({ error: `a job is already running (${running.kind})`, running: jobView(running) }, { status: 409 }); } let r: Awaited>; try { r = await planClipsNew(body); } catch (e) { const status = e instanceof ClipsNewError ? e.status : 500; return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status }); } invalidateProjects(); try { const job = startJob(r.plan.kind, r.plan.steps, { project: r.project.id }); return Response.json( { ok: true, jobId: job.id, job: jobView(job), project: r.project.id, created: r.created, segments: r.segments, segment: r.segment, scope: r.scope, href: clipEditorHref(r.project.id), notes: r.notes, }, { headers: { "cache-control": "no-store" } }, ); } catch (e) { return Response.json({ error: e instanceof Error ? e.message : String(e), project: r.project.id, created: r.created }, { status: 409 }); } }