import { enumerate, findPost, findVideo, parseSearchArgs, resolveSelectedChannels, type ChannelRef, type SearchHit, } from "yt-dlp-transcript-mcp/research"; import { cuesOfTrack, trackLabel } from "yt-dlp-transcript-common/lib/captionTracks"; import { momentUrl, viewerPostUrl } from "yt-dlp-transcript-common/lib/momentUrl"; import { passesFilters } from "yt-dlp-transcript-common/lib/search/evalTree"; import { clock } from "yt-dlp-transcript-common/lib/search/window"; import type { TranscriptDetail } from "yt-dlp-transcript-common/lib/transcripts"; import { REPORTS_ROOT } from "../paths.mjs"; import { citationText, facetsOf, hitKey, isoDate, trackOf, yearOf } from "./facets.mjs"; import { sessionKey } from "./session.mjs"; import { readLog } from "./log.mjs"; import { writeCensus } from "./census.mjs"; import { markRanges } from "./query.mjs"; import { isLocalOnly } from "./rules.mjs"; import { localMediaFor } from "./media"; import { openSource, SourceError, type ChannelCensus, type Opened } from "./sources"; import type { ChannelChoice, ResultHit, Scope, ScopeSummary, SearchResponse, TrackCensus, WindowCue, WindowResponse, } from "./types"; // --------------------------------------------------------------------------- // RESEARCH OVER THE CORPUS, AS DATA (plans/umtool-redesign.md, R1). // // Every read goes through the SAME engine the MCP tools wrap // (yt-dlp-transcript-mcp/research): a search IS enumerate_matches' scan -- // its scoping, filters, exclusions, alias expansion, mirror collapsing and // caps (MCP_POLICY) -- called once for the whole match set, never paged (the // coverage rule), with snippets on. Nothing here parses a tool's text, and // lib/research/parity.test.ts holds the two to the same total and ids. // // Read-only on the corpus. The reading log is umtool's own (log.mjs). // --------------------------------------------------------------------------- /** Snippets kept per recording; `matches` still counts every hit. */ const SNIPPETS_PER_RECORDING = 12; const BATCH = 8; /** The tool's own arguments for a scope (and a query). */ export function toolArgs(scope: Scope, query?: { query: string; regex?: boolean; exclude?: string[] }): Record { return { ...(query ? { query: query.query, regex: query.regex === true } : {}), ...(query?.exclude?.length ? { exclude: query.exclude } : {}), ...(scope.channels?.length ? { channels: scope.channels } : {}), ...(scope.dateFrom ? { date_from: scope.dateFrom } : {}), ...(scope.dateTo ? { date_to: scope.dateTo } : {}), ...(scope.states?.length ? { states: scope.states } : {}), ...(scope.mediaType ? { media_type: scope.mediaType } : {}), content_types: scope.posts ? ["video", "post"] : ["video"], }; } const DATE = /^\d{4}-\d{2}-\d{2}$/; /** A Scope from a query string or a JSON body, unknowns dropped. */ export function scopeFrom(input: URLSearchParams | Record): Scope { const get = (k: string): unknown => (input instanceof URLSearchParams ? input.get(k) ?? undefined : input[k]); const list = (k: string): string[] | undefined => { const raw = input instanceof URLSearchParams ? input.getAll(k).flatMap((v) => v.split(",")) : get(k); const arr = (Array.isArray(raw) ? raw : typeof raw === "string" ? raw.split(",") : []) .filter((x): x is string => typeof x === "string") .map((x) => x.trim()) .filter(Boolean); return arr.length ? arr : undefined; }; const str = (k: string): string | undefined => { const v = get(k); return typeof v === "string" && v.trim() ? v.trim() : undefined; }; const media = str("media"); const posts = get("posts"); return { source: str("source") ?? "", ...(list("channels") ? { channels: list("channels") } : {}), ...(str("from") && DATE.test(str("from")!) ? { dateFrom: str("from") } : {}), ...(str("to") && DATE.test(str("to")!) ? { dateTo: str("to") } : {}), ...(list("states") ? { states: list("states") } : {}), ...(media === "video" || media === "livestream" ? { mediaType: media } : {}), ...(posts === true || posts === "1" || posts === "true" ? { posts: true } : {}), }; } function choiceOf(ch: ChannelRef): ChannelChoice { return { key: ch.key, slug: ch.slug, name: ch.name, ...(ch.videoCount != null ? { videoCount: ch.videoCount } : {}), ...(ch.siteTitle ? { site: ch.siteTitle } : {}), ...(isLocalOnly(ch.slug) ? { localOnly: true } : {}), }; } function censusOf(opened: Opened, keys: string[]): TrackCensus | null { let counted = 0; const sum = { transcript: 0, captions: 0, unknown: 0 }; for (const k of keys) { const c = opened.census.get(k); if (!c) continue; counted++; sum.transcript += c.transcript; sum.captions += c.captions; sum.unknown += c.unknown; } return counted === 0 ? null : { ...sum, counted, of: keys.length }; } /** What a scope holds, before anything runs: the "holds …" line. */ export async function scopeOf(scope: Scope): Promise { const opened = await openSource(scope.source); const { source } = opened; const parsed = parseSearchArgs(toolArgs(scope)); if (parsed.error) throw new SourceError(parsed.error); const all = await source.listChannels(); const sel = await resolveSelectedChannels(source, { channels: scope.channels }); const keys = new Set(sel.channels.map((c) => c.key)); const slugs = new Map(sel.channels.map((c) => [c.slug, c])); let videos = 0; let first: string | null = null; let last: string | null = null; const index = source.videoIndex ? await source.videoIndex().catch(() => null) : null; if (index && index.size > 0) { for (const v of index.values()) { if (!slugs.has(v.channelSlug)) continue; if (parsed.filters && !passesFilters(v, parsed.filters, v)) continue; videos++; if (/^\d{8}$/.test(v.uploadDate)) { if (!first || v.uploadDate < first) first = v.uploadDate; if (!last || v.uploadDate > last) last = v.uploadDate; } } } else { videos = sel.channels.reduce((n, c) => n + (c.videoCount ?? 0), 0); } const aliases = await source.loadAliases().catch(() => []); return { source: opened.option, channels: all.map(choiceOf), selected: sel.channels.length, videos, first, last, tracks: censusOf(opened, [...keys]), ...(opened.censusStale && !censusOf(opened, [...keys]) ? { tracksStale: `counted on an earlier build (${opened.censusStale.updatedAt.slice(0, 10) || "date unknown"}); the next full search counts again` } : {}), aliases: aliases.length, warnings: [ ...parsed.warnings, ...sel.unknownChannels.map((c) => `unknown channel: ${c}`), ...(index && index.size > 0 ? [] : parsed.filters ? ["this source ships no summaries index: the count ignores the filters"] : []), ], }; } // ── the census: transcripts vs captions, learned from a scan that read a channel whole ── type Seen = { fmt: unknown; duration: number; year: string }; async function recordCensus(opened: Opened, channels: ChannelRef[], seen: Map>): Promise { let counted = 0; for (const ch of channels) { const recs = seen.get(ch.key); if (!recs) continue; let expected: number; try { expected = Object.keys((await opened.source.transcriptsManifest(ch)).slugToPage).length; } catch { continue; } if (recs.size < expected) continue; // read in part (a filter pruned pages, or a cap): not a census const c: ChannelCensus = { total: 0, transcript: 0, captions: 0, unknown: 0, byYear: {} }; for (const r of recs.values()) { const t = trackOf(r.fmt); c.total++; c[t]++; const y = (c.byYear[r.year || "undated"] ??= { transcript: 0, captions: 0, unknown: 0 }); y[t]++; } opened.census.set(ch.key, c); counted++; } // Kept umtool-side for this build (census.mjs), so a restart does not forget it. if (counted > 0 && opened.identity) { try { await writeCensus(REPORTS_ROOT, opened.option.handle, opened.identity, Object.fromEntries(opened.census)); opened.censusStale = null; } catch { /* the counts still serve this process; the file is a convenience */ } } } // ── search ── type Memo = { at: number; value: SearchResponse }; const g = globalThis as { __umtoolResearchSearches?: Map }; const memo = (g.__umtoolResearchSearches ??= new Map()); const MEMO_MS = 10 * 60_000; const MEMO_MAX = 8; export type SearchRequest = Scope & { query: string; regex?: boolean; exclude?: string[]; fresh?: boolean }; /** * One search: enumerate_matches' scan, ONCE, the whole match set -- never a * page of it. The answer says whether it is complete, and what a cap left * unread. The last few are kept ten minutes per session (a reload, a second * tab), and a corpus that moved under them opens a new source anyway. */ export async function runSearch(req: SearchRequest): Promise { const started = Date.now(); const opened = await openSource(req.source); const scope: Scope = { ...req, source: opened.option.handle }; const session = sessionKey({ ...scope, query: req.query, regex: req.regex === true }); const cached = memo.get(session); if (!req.fresh && cached && Date.now() - cached.at < MEMO_MS) { const log = await readLog(REPORTS_ROOT, session); return { ...cached.value, log: { marks: log.marks, ...(log.error ? { error: log.error } : {}) } }; } const { source } = opened; // What the scan reads, per channel: the format (transcript or captions) and // the length of every record -- free, since the scan reads them anyway. const seen = new Map>(); const e = await enumerate(source, toolArgs(scope, req), { includeSnippets: true, snippetsPerVideo: SNIPPETS_PER_RECORDING, onRecord: (rec: TranscriptDetail, ch: ChannelRef) => { let m = seen.get(ch.key); if (!m) seen.set(ch.key, (m = new Map())); m.set(rec.slug, { fmt: (rec as { transcriptFormat?: unknown }).transcriptFormat, duration: rec.duration, year: yearOf(rec.uploadDate), }); }, }); if ("error" in e) throw new SourceError(e.error); const { result, parsed } = e; const selection = await resolveSelectedChannels(source, { channels: scope.channels }); await recordCensus(opened, selection.channels, seen); const avail = await source.availabilityMap().catch(() => new Map()); const byKey = new Map(selection.channels.map((c) => [c.slug, c])); const fired = result.firedAliases.map((a) => ({ pattern: a.suggestion, regex: a.useRegex === true })); const q = { query: e.query, regex: req.regex === true, aliases: fired }; const hits: ResultHit[] = result.hits.map((h: SearchHit) => { const ch = byKey.get(h.channelSlug); const rec = ch ? seen.get(ch.key)?.get(h.slug) : undefined; const post = h.contentType === "post"; return { key: hitKey(h), kind: post ? "post" : "video", videoId: h.videoId, channelSlug: h.channelSlug, channelKey: ch?.key ?? h.channelSlug, channelName: h.channelName, ...(h.siteTitle ? { site: h.siteTitle } : {}), title: h.title, uploadDate: h.uploadDate, track: post ? "post" : trackOf(rec?.fmt), state: (avail.get(h.slug)?.state as string | undefined) ?? "available", ...(rec?.duration ? { duration: rec.duration } : {}), matches: h.matches, snippets: h.snippets.map((s) => ({ t: s.seconds, clock: s.clock, text: s.text, marks: markRanges(s.text, q), ...(s.track ? { track: s.track } : {}), ...(s.scope ? { scope: s.scope } : {}), })), ...(h.mirrors?.length ? { mirrors: h.mirrors.map((m) => ({ videoId: m.videoId, channelName: m.channelName })) } : {}), ...(post && h.author ? { author: h.author } : {}), ...(isLocalOnly(h.channelSlug) ? { localOnly: true } : {}), }; }); const value: SearchResponse = { session, query: e.query, regex: req.regex === true, source: opened.option, total: result.total, matches: hits.reduce((n, h) => n + h.matches, 0), complete: !result.truncated, notReached: result.coverage.channelsNotReached, ...(result.coverage.channelStopped ? { stopped: result.coverage.channelStopped } : {}), scanned: result.scanned, mirrorsFolded: result.duplicates.collapsed, batches: Math.ceil(result.total / BATCH), aliases: result.firedAliases.map((a) => a.label), warnings: [ ...parsed.warnings, ...result.selection.unknownChannels.map((c) => `unknown channel: ${c}`), ...(result.postsScanned.skippedForTagFilter ? ["posts skipped: a tag filter was given"] : []), ], hits, facets: facetsOf(hits), log: { marks: {} }, tookMs: Date.now() - started, }; memo.set(session, { at: Date.now(), value }); while (memo.size > MEMO_MAX) memo.delete(memo.keys().next().value!); const log = await readLog(REPORTS_ROOT, session); return { ...value, log: { marks: log.marks, ...(log.error ? { error: log.error } : {}) } }; } // ── the reader's window ── export type WindowRequest = { source: string; channel: string; video: string; /** The cited second. */ t: number; /** Seconds each side (the ± expand). */ span: number; /** An alternate caption track, when the hit was in one. */ track?: string; kind?: "video" | "post"; }; export const MAX_SPAN = 600; /** The transcript around a cue, with the cue lit, and its citation. */ export async function windowOf(req: WindowRequest): Promise { const opened = await openSource(req.source); const { source } = opened; const avail = await source.availabilityMap().catch(() => new Map()); if (req.kind === "post") { const found = await findPost(source, req.video, req.channel); if (!found) throw new SourceError(`no post ${req.video} in ${opened.option.label}`, 404); const { ch, post } = found; const date = isoDate(post.uploadDate); const author = post.authorName || post.author; const url = viewerPostUrl(ch.siteUrl ?? source.publicOrigin(), post.slug) ?? post.url ?? null; return { kind: "post", title: `Post by ${author}`, channelSlug: ch.slug, channelName: ch.name, videoId: post.id, uploadDate: post.uploadDate, duration: 0, state: "available", track: "post", cueCount: 0, at: 0, span: 0, cues: [], lit: -1, citation: { text: citationText({ quote: post.text, title: "", post: { author, date }, url }), url }, media: [], text: post.text, author, ...(isLocalOnly(ch.slug) ? { localOnly: true } : {}), }; } const found = await findVideo(source, req.video, req.channel); if (!found) throw new SourceError(`no recording ${req.video} in ${opened.option.label}`, 404); const { ch, record } = found; const all = (cuesOfTrack(record, req.track) ?? record.cues ?? []).filter((c) => c && typeof c.start === "number"); const span = Math.max(5, Math.min(MAX_SPAN, Math.round(req.span))); // The cited cue: the one starting nearest the cite (a snippet's second is its cue's start). let litAll = -1; let best = Infinity; for (let i = 0; i < all.length; i++) { const d = Math.abs(all[i].start - req.t); if (d < best) { best = d; litAll = i; } } const lo = req.t - span; const hi = req.t + span; const cues: WindowCue[] = []; let lit = -1; for (let i = 0; i < all.length; i++) { const c = all[i]; if (c.start < lo || c.start > hi) continue; if (i === litAll) lit = cues.length; cues.push({ t: c.start, end: c.end, text: c.text }); } const litCue = litAll >= 0 ? all[litAll] : null; const at = litCue ? litCue.start : req.t; const url = momentUrl({ siteOrigin: ch.siteUrl ?? source.publicOrigin(), slug: record.slug, seconds: at, webpageUrl: record.webpageUrl, platform: record.platform, }); const alt = req.track && req.track !== record.track ? req.track : undefined; return { kind: "video", title: record.title, channelSlug: ch.slug, channelName: ch.name, videoId: record.id, uploadDate: record.uploadDate, duration: record.duration || (all.length ? all[all.length - 1].end : 0), state: (avail.get(record.slug)?.state as string | undefined) ?? "available", track: trackOf((record as { transcriptFormat?: unknown }).transcriptFormat), ...(alt ? { trackLabel: trackLabel(alt) } : {}), cueCount: all.length, at, span, cues, lit, citation: { text: citationText({ quote: litCue?.text, title: record.title, clock: clock(at), url }), url }, media: await localMediaFor(ch.slug, record), ...(isLocalOnly(ch.slug) ? { localOnly: true } : {}), }; }