import path from "node:path"; import { fetchClip, validateFetchClipArgs, type FetchClipDeps, } from "yt-dlp-transcript-mcp/research"; import { resolveEvidenceSource } from "yt-dlp-transcript-common/lib/evidenceClip-server"; import { CHANNELS_DIR } from "@/lib/paths"; import { answerOf } from "@/lib/research/fetch"; import { SourceError } from "@/lib/research/sources"; import { projectCache, resolveClip, resolveReport, windowVersion, windowsFor } from "@/lib/report/serve.mjs"; import { corpusMediaUrl } from "@/lib/articles/article"; import type { CitedFetchAnswer, CitedPlay, CitedTarget } from "./types"; import { fetchFailureSentence } from "./words"; // --------------------------------------------------------------------------- // THE CITED CLIP, server side (release 32 R1): what plays a cited span, and // the one button that fetches it when nothing does. // // Playback, best first -- found, never fetched: // 1. a project's own cached window (out/clips-raw, or a corpus window the // project's cache counts), when the span is a project's clip: served by // /api/report/raw, which the clip bench plays too; // 2. a clip window the editor fetched into data//clips/; // 3. a saved video in data// (through its media-tier link); // 4. audio, labelled "audio only". // The prepared evidence clip of a site (lib/articles/evidence.ts) comes before // all of these on the article pages; it is that module's. // // FETCH asks the editor's fetch-window route exactly as the MCP's fetch_clip // asks (requestedBy "umtool"), never yt-dlp. The corpus's channel and video // directories ARE the editor's, so no source lookup stands between: the // editor resolves the page URL from the record. The route never waits: a // queued fetch is polled by job id. // --------------------------------------------------------------------------- const WIN_EPS = 0.02; /** The corpus's own media for a span: a window, a saved video, or audio. */ export async function corpusPlay(t: CitedTarget, channelsDir: string = CHANNELS_DIR): Promise { const span = { from: t.from, to: t.to }; for (const audio of t.audio ? [true] : [false, true]) { const hit = await resolveEvidenceSource({ channelsDir, slug: t.channel, id: t.video, span, audio }).catch(() => null); if (!hit) continue; const kind = hit.kind === "corpus-window" ? "window" : hit.kind === "saved-video" ? "saved" : "audio"; return { kind, url: corpusMediaUrl(hit.path), offset: Math.max(0, t.from - hit.windowStart), audio: hit.kind === "audio", label: kind === "window" ? `clip window ${hit.name}` : kind === "saved" ? `saved ${hit.name}` : `audio ${hit.name}`, }; } return null; } /** A project clip's own cached window holding the span, served through /api/report/raw. */ async function projectPlay(t: CitedTarget): Promise { if (!t.project || !t.clip || t.audio) return null; const r = await resolveClip(t.project, t.clip).catch(() => null); if (!r || "error" in r) return null; const cache = await projectCache(r.project, r.manifest); const windows = (await windowsFor(r.project, { ...r.clip, start: t.from, end: t.to }, cache)) as { name: string; path?: string; from: number; to: number }[]; // The project's OWN window first: a corpus window is shared by every project and // another one's fetch can be wider (clip-bench's after-only fetch leaves vid1's // 0-14), which would play instead of the cache this project counts on. const own = (w: { path?: string }) => (w.path && path.resolve(w.path).startsWith(path.resolve(r.project.dir) + path.sep) ? 0 : 1); const win = windows .filter((w) => w.from <= t.from + WIN_EPS && w.to >= t.to - WIN_EPS) .sort((a, b) => own(a) - own(b))[0]; if (!win) return null; const ver = await windowVersion(win as { name: string; path: string; from: number; to: number }); return { kind: "window", // `v`: the version of the window's bytes (serve.mjs, "A REPLACED FILE IS A NEW FILE"). url: `/api/report/raw?${new URLSearchParams({ project: t.project, clip: t.clip, file: win.name, ...(ver ? { v: ver } : {}) })}`, offset: Math.max(0, t.from - win.from), audio: false, label: `clip window ${win.name}`, }; } /** What plays the span now, or null (nothing on disk: offer Fetch clip). A project's hidden regions ride along. */ export async function findCitedPlay(t: CitedTarget): Promise { const play = (await projectPlay(t)) ?? (await corpusPlay(t)); if (!play || play.audio || !t.project) return play; const hidden = await citedHidden(t); return hidden.length ? { ...play, hidden } : play; } /** The regions a project hides on the cited recording: its clip's (render.censor's and its own), else the recording's. */ async function citedHidden(t: CitedTarget) { const { censorRegionsOf, recordingRegionsOf } = await import("umtool-report-to-video/clip-censor"); const r = t.clip ? await resolveClip(t.project as string, t.clip).catch(() => null) : null; if (r && !("error" in r)) return censorRegionsOf(r.clip, r.manifest.render ?? {}, r.manifest.provenance ?? {}); const rep = await resolveReport(t.project as string).catch(() => null); if (!rep || "error" in rep) return []; return recordingRegionsOf(t.video, t.channel, rep.manifest.render ?? {}, rep.manifest.provenance ?? {}); } /** Parse a target from a query string or a JSON body; throws a 400 in words. */ export function targetOf(get: (k: string) => unknown): CitedTarget { const s = (k: string) => { const v = get(k); return typeof v === "string" ? v.trim() : typeof v === "number" ? String(v) : ""; }; const channel = s("channel"); const video = s("video"); const from = Number(s("from")); const to = Number(s("to")); const id = /^[\w.-]+$/; if (!id.test(channel) || channel === "." || channel === "..") throw new SourceError("channel must be a channel directory"); if (!id.test(video) || video === "." || video === "..") throw new SourceError("video must be a video directory"); if (!Number.isFinite(from) || !Number.isFinite(to) || from < 0 || !(from < to)) throw new SourceError("from and to must be seconds, from < to"); const project = s("project"); const clip = s("clip"); return { channel, video, from, to, ...(project && clip ? { project, clip } : {}), ...(s("audio") === "1" || get("audio") === true ? { audio: true } : {}), }; } const deps: FetchClipDeps = { env: process.env, fetch: (url, init) => globalThis.fetch(url, init), sleep: (ms) => new Promise((r) => setTimeout(r, ms)), now: () => Date.now(), }; /** * Fetch the span through the editor (or poll a fetch already asked for). A * ready answer carries what plays now; a failure its plain sentence. */ export async function fetchCitedClip( req: | { job: string; target?: CitedTarget } | { target: CitedTarget; reason: string; report?: string; storedUrl?: "fallback" | "only" }, d: FetchClipDeps = deps, ): Promise { const args = "job" in req ? { job: req.job, wait_seconds: 0 } : { channel: req.target.channel, video: req.target.video, start: req.target.from, end: req.target.to, reason: req.reason, ...(req.report ? { report: req.report } : {}), // Cut from the stored media URL (release 32 R6): fetch_clip's field. ...(req.storedUrl ? { storedUrl: req.storedUrl } : {}), wait_seconds: 0, }; const v = validateFetchClipArgs(args); if (!v.ok) throw new SourceError(v.error.replace(/^fetch_clip: /, "")); const a = answerOf(await fetchClip(v.request, d, { requestedBy: "umtool" })); if (a.state === "failed") { const plain = fetchFailureSentence(a.message); return { state: "failed", message: plain.message, ...(plain.detail ? { detail: plain.detail } : {}), ...(a.job ? { job: a.job } : {}) }; } if (a.state === "queued") return a; const target = req.target; return { state: "ready", cached: a.cached, ...(a.from !== undefined ? { from: a.from } : {}), ...(a.to !== undefined ? { to: a.to } : {}), play: target ? await findCitedPlay(target) : null, }; }