import { NextResponse } from "next/server"; import { getPaths } from "yt-dlp-transcript-common/lib/paths"; import { getSettings } from "yt-dlp-transcript-common/lib/settings"; import { isIsoDate } from "yt-dlp-transcript-common/lib/lookout"; import { LOOKOUT_ID_RE, LOOKOUT_MAX_DAYS, LOOKOUT_MAX_MAX_VIDEOS, lookoutById } from "yt-dlp-transcript-common/lib/lookoutSettings"; import { LookoutPlanRefusal, planLookout } from "yt-dlp-transcript-common/controller/lookoutPlan"; import { LOOKOUT_MAX_CALLS, cancelLookoutRuns, enqueueLookoutRun, lookoutRunJobs } from "yt-dlp-transcript-common/controller/lookoutRun"; import { LOOKOUT_RUN_ID_RE, listLookoutRunIds, readLookoutRun, surfacedIdeas } from "yt-dlp-transcript-common/lib/lookoutStore"; import { OpsInputError, jobResponse, ops, opsFail, optBool, optPositiveInt, optString, reqString } from "../_lib"; import { readRoute } from "../_read"; export const dynamic = "force-dynamic"; // POST { id, dryRun: true, days?, maxVideos?, until? } -> { ok: true, plan } // POST { id, days?, maxVideos?, until?, model?, maxCalls? } -> { ok: true, jobId, model } // // A saved lookout (settings.lookouts.items, SETTINGS.md). // // DRY RUN — what it would read (common/controller/lookoutPlan.ts): every video // of its channels whose AIR date — `release_timestamp`, else `timestamp`, in // its time zone — falls in the window; duplicate uploads and a stream's // cut-downs folded into one recording; the longest `maxVideos` read and the // rest listed as skipped for the cap, with why for every video left out; the // reading calls and, once a run has been measured, the seconds they would // take. `days` and `maxVideos` override the lookout's for this answer; `until` // (YYYY-MM-DD) ends the window on another day than today. A local media // library channel, or a slug this archive does not hold, is named in // `refused`. Reads text only and writes nothing; synchronous, no job, no // model, no network. // // THE RUN — a `lookout-run` job on `draft:local` // (common/controller/lookoutRun.ts): the same plan made at the job's turn, its // `read` list read by the local model one chunk a call into each video's // private reading notes, the notes grouped into ideas, the run written under // transcripts/.lookouts//runs/. A recording whose notes are fresh is not // read again, so a cancelled run's next start continues where it stopped. // `model` names a local model (default: the `lookout` route's); `maxCalls` // caps the reading calls (default 400; past it the run ends partial). Refused // before any job: lookouts off (settings.lookouts.enabled), the route not // local, a run of this lookout already queued or running, a damaged // verdicts.json. The log ends `@@lookout-run {id, runId, status, …}`. // // POST { id, cancel: true } -> { ok: true, cancelled: [jobId, …] }: the // lookout's queued or running run is cancelled (the reading notes it wrote // are kept; the next run continues from them). Nothing to cancel is `[]`. // // A lookout removed from settings while its run was live is still cancelled by // its id. // // GET ?id=[&run=] -> { ok: true, run, ideasNotSurfaced, running } — `pnpm ops // get lookout-run [--run R]`: the latest run (or the one named) whole — // window, the selection it read, calls, seconds, reading counts, ideas and // what was dropped — or null before the first; its ideas are the ones `get // lookouts` counts (surfacedIdeas: a damaged idea left out, counted in // `ideasNotSurfaced`); and the lookout's run queued // or running now ([{jobId, status}]). const MAX_CALLS = LOOKOUT_MAX_CALLS * 5; export async function POST(request: Request) { return ops(request, ["id", "dryRun", "days", "maxVideos", "until", "model", "maxCalls", "cancel"], async (body) => { const id = reqString(body, "id"); const dryRun = optBool(body, "dryRun") === true; const cancel = optBool(body, "cancel") === true; const days = optPositiveInt(body, "days"); if (days !== undefined && days > LOOKOUT_MAX_DAYS) throw new OpsInputError(`"days" is at most ${LOOKOUT_MAX_DAYS}`); const maxVideos = optPositiveInt(body, "maxVideos"); if (maxVideos !== undefined && maxVideos > LOOKOUT_MAX_MAX_VIDEOS) { throw new OpsInputError(`"maxVideos" is at most ${LOOKOUT_MAX_MAX_VIDEOS}`); } const until = optString(body, "until"); if (until !== undefined && !isIsoDate(until)) throw new OpsInputError('"until" is a date, YYYY-MM-DD'); const model = optString(body, "model"); const maxCalls = optPositiveInt(body, "maxCalls"); if (maxCalls !== undefined && maxCalls > MAX_CALLS) throw new OpsInputError(`"maxCalls" is at most ${MAX_CALLS}`); if (dryRun && (model !== undefined || maxCalls !== undefined)) throw new OpsInputError('a dry run calls no model: "model" and "maxCalls" are the run\'s'); if (cancel && Object.keys(body).some((k) => k !== "id" && k !== "cancel")) throw new OpsInputError('"cancel" takes the lookout\'s "id" alone'); const lookouts = getSettings().lookouts; const item = lookoutById(lookouts, id); // A cancel is by the job's recorded lookout id: a run of a lookout since // removed from settings is still cancelled by its id. if (cancel && LOOKOUT_ID_RE.test(id) && (item || lookoutRunJobs(id).length)) { return NextResponse.json({ ok: true, cancelled: cancelLookoutRuns(id) }); } if (!item) { return opsFail(`no lookout "${id}" — settings.lookouts.items names ${lookouts.items.map((i) => i.id).join(", ") || "none"}`, 404); } if (!dryRun) { const out = await enqueueLookoutRun({ id, days, maxVideos, until, model, maxCalls }, { paths: getPaths() }); if (!out.result.ok || !("model" in out)) return jobResponse(out.result); void out.result.stream.cancel(); return NextResponse.json({ ok: true, jobId: out.result.jobId, model: out.model }); } try { const plan = await planLookout(getPaths(), item, { days, maxVideos, until }); return NextResponse.json({ ok: true, plan }); } catch (err) { if (err instanceof LookoutPlanRefusal) throw new OpsInputError(err.message); throw err; } }); } export async function GET(request: Request) { return readRoute(request, ["id", "run"], async (q) => { const id = q.get("id"); if (!id) return opsFail('"id" names the lookout: ?id='); const lookouts = getSettings().lookouts; if (!lookoutById(lookouts, id)) { return opsFail(`no lookout "${id}" — settings.lookouts.items names ${lookouts.items.map((i) => i.id).join(", ") || "none"}`, 404); } const paths = getPaths(); const asked = q.get("run"); if (asked !== null && !LOOKOUT_RUN_ID_RE.test(asked)) return opsFail(`"${asked}" is not a lookout run id`); let run = null; if (asked !== null) { run = await readLookoutRun(paths, id, asked); if (!run) return opsFail(`lookout "${id}" has no run "${asked}"`, 404); } else { for (const runId of await listLookoutRunIds(paths, id)) { run = await readLookoutRun(paths, id, runId); if (run) break; } } // Its ideas counted and shown as `get lookouts` counts them // (surfacedIdeas): an idea with no whole moment, or whose key is not its // moments', is not a finding; how many the file held beside them is said. if (!run) return { run: null, running: lookoutRunJobs(id) }; const ideas = surfacedIdeas(run); return { run: { ...run, ideas }, ideasNotSurfaced: (Array.isArray(run.ideas) ? run.ideas.length : 0) - ideas.length, running: lookoutRunJobs(id) }; }); }