// `frame-scan` — a saved stream's frames read for a profile's progress // (release 30, lane P): `pnpm ops frame-scan` → POST /api/ops/frame-scan → // here, and the video page's Scan button. // // slug, id the video (its source container must be in the saved-video store) // profile what the frames are read for (default "poker") // everySeconds the sampling step (default settings.generation.frames.everySeconds) // from, to the range in source seconds (default the whole video) // maxFrames at most this many frames (default 5000) // model the vision model (default the `frames` route's) // maxUsd the run's API cap (default frames.maxUsd, at most caps.max) // hero the hero's screen name, a hint to the model // framesPerAsk frames per ask (default the profile's: 4 on the API, 1 local) // crop [x, y, w, h], fractions: the part of the picture read (the // poker client, not the webcam beside it); also what is hashed // fresh read every frame again (another model or prompt): the // readings so far are dropped, the runs and the spend kept // evict remove the frame cache and answer at once (no job) // rederive work `derived` out again from the stored readings (and the // cues' spoken numbers) and answer at once: no job, no model, // no frame (refused while a scan of this video is queued or // running); `hero` may be given with it // // THE QUEUE: on the API a scan runs on `frames`, one at a time and apart from // the generation lanes; on a local model it runs on `draft:local`, every ollama // call through the GPU arbiter and the model unloaded at the end, however it // ends (as the verdict bench). `needsMedia`: it opens the saved container and // writes the cache on the media side, so a channel whose media is unreachable // is refused. // // An API scan is refused past the day's cap, and its spend is appended to the // usage ledger (task `frame-scan`, no article). The log ends // `@@frame-scan {json}` with the run's counts, spend, and events. import { modelLogged } from "./jobModelLog"; import path from "node:path"; import { readFile } from "node:fs/promises"; import { getSettings } from "../lib/settings"; import type { Paths } from "../lib/paths"; import type { GenerationSettings } from "../lib/generationSettings"; import { runManagedFunction, type StreamActionResult } from "../jobs/streamCommand"; import { DRAFT_LOCAL_QUEUE, FRAME_SCAN_QUEUE } from "../lib/queueKeys"; import { localOnlyJobRefusal, providerOf, unloadOllama } from "../lib/llm"; import { isSafeChannelSegment, isSafeIdSegment } from "../lib/citations/moments"; import { resolveSavedVideo } from "../lib/savedVideo-server"; import { frameCacheDirOf, frameScanSidecar } from "../lib/frameScan-server"; import { frameCacheBytes, isCrop, removeFrameCache, type Crop } from "../lib/frames/sample-server"; import { isFrameProfile, FRAME_PROFILE_IDS } from "../lib/frames/profiles"; import { DEFAULT_MAX_FRAMES, rederiveRecord, runFrameScan, type FrameScanOutcome } from "../lib/frames/scan"; import { getRegistry } from "../jobs/registry"; import type { FrameScanRecord } from "../lib/frameScan-server"; import type { Cue } from "../lib/frames/types"; import { appendGenerationUsage, dailyCapRefusal, dayUsage, utcDay, type GenerationUsageRow } from "./generationUsage"; import { llmConfigOf } from "./reportDraft"; export const FRAME_SCAN_JOB_KIND = "frame-scan"; export const FRAME_SCAN_RESULT_MARKER = "@@frame-scan "; export const FRAME_SCAN_BODY_KEYS = ["slug", "id", "profile", "everySeconds", "from", "to", "maxFrames", "model", "maxUsd", "hero", "framesPerAsk", "crop", "fresh", "evict", "rederive"] as const; export class FrameScanInputError extends Error { constructor(message: string) { super(message); this.name = "FrameScanInputError"; } } export type FrameScanBody = { slug: string; id: string; profile: string; everySeconds?: number; from?: number; to?: number; maxFrames?: number; model?: string; maxUsd?: number; hero?: string; framesPerAsk?: number; crop?: Crop; fresh?: boolean; evict?: boolean; rederive?: boolean; }; const fail = (msg: string): never => { throw new FrameScanInputError(msg); }; const numIn = (v: unknown, lo: number, hi: number) => typeof v === "number" && Number.isFinite(v) && v >= lo && v <= hi; // The body, judged without touching the disk. export function parseFrameScanBody(b: Record): FrameScanBody { if (!isSafeChannelSegment(b.slug)) fail(`"slug" is a channel's slug`); if (!isSafeIdSegment(b.id)) fail(`"id" is a video's id`); const profile = b.profile ?? "poker"; if (!isFrameProfile(profile)) fail(`"profile" is one of ${FRAME_PROFILE_IDS.join(", ")}`); const out: FrameScanBody = { slug: b.slug as string, id: b.id as string, profile: profile as string }; if (b.everySeconds !== undefined) { if (!numIn(b.everySeconds, 1, 600)) fail(`"everySeconds" is a number of seconds, 1 to 600`); out.everySeconds = b.everySeconds as number; } for (const k of ["from", "to"] as const) { if (b[k] === undefined) continue; if (!numIn(b[k], 0, 1e7)) fail(`"${k}" is a number of seconds into the video`); out[k] = b[k] as number; } if (out.from !== undefined && out.to !== undefined && !(out.to > out.from)) fail(`"to" must be after "from"`); if (b.maxFrames !== undefined) { if (!(Number.isInteger(b.maxFrames) && numIn(b.maxFrames, 1, 100_000))) fail(`"maxFrames" is a whole number, 1 to 100000`); out.maxFrames = b.maxFrames as number; } if (b.model !== undefined) { if (typeof b.model !== "string" || !/^[A-Za-z0-9][A-Za-z0-9._:/-]{0,127}$/.test(b.model.trim())) fail(`"model" is a model's name`); out.model = (b.model as string).trim(); } if (b.maxUsd !== undefined) { if (!numIn(b.maxUsd, 0.01, 1000)) fail(`"maxUsd" is a number of dollars`); out.maxUsd = b.maxUsd as number; } if (b.hero !== undefined) { if (typeof b.hero !== "string" || !b.hero.trim() || b.hero.length > 60) fail(`"hero" is the hero's screen name (at most 60 characters)`); out.hero = (b.hero as string).trim(); } if (b.framesPerAsk !== undefined) { if (!(Number.isInteger(b.framesPerAsk) && numIn(b.framesPerAsk, 1, 8))) fail(`"framesPerAsk" is a whole number, 1 to 8`); out.framesPerAsk = b.framesPerAsk as number; } if (b.crop !== undefined) { if (!isCrop(b.crop)) fail(`"crop" is [x, y, w, h] as fractions of the picture (each 0 to 1, inside it, at least 0.05 wide and high)`); out.crop = b.crop as Crop; } if (b.fresh !== undefined) { if (typeof b.fresh !== "boolean") fail(`"fresh" is true or false`); out.fresh = b.fresh as boolean; } if (b.evict !== undefined) { if (typeof b.evict !== "boolean") fail(`"evict" is true or false`); out.evict = b.evict as boolean; } if (b.rederive !== undefined) { if (typeof b.rederive !== "boolean") fail(`"rederive" is true or false`); out.rederive = b.rederive as boolean; } if (out.rederive && out.evict) fail(`"rederive" and "evict" are two different asks — one at a time`); return out; } /** The model a scan runs on: the asked one, else the `frames` route's. */ export function frameScanModel(gen: GenerationSettings, asked?: string): string { if (asked) return asked; const route = gen.routes.frames; if (route === "code") fail(`frames is routed to Claude Code (settings.generation.routes.frames) — name a "model", or route frames to api or local`); return route === "api" ? gen.frames.apiModel : gen.frames.localModel; } /** The run's API cap: the asked one within caps.max, else frames.maxUsd (at most caps.max). */ export function frameScanCap(gen: GenerationSettings, asked?: number): number { if (asked !== undefined) { if (asked > gen.caps.max) fail(`maxUsd $${asked} is over the settings' max of $${gen.caps.max} (settings.generation.caps.max)`); return asked; } return Math.min(gen.frames.maxUsd, gen.caps.max); } export type FrameScanDepsIn = { paths: Paths; settings?: () => { generation: GenerationSettings }; now?: () => Date; }; export type FrameScanEnqueued = | { result: StreamActionResult; model: string; queueKey: string } | { result: StreamActionResult & { ok: false } } | { evicted: { dir: string; removed: boolean; bytes: number } } | { rederived: FrameScanRederived }; /** What a re-derive changed, in counts: before → after. */ export type FrameScanRederived = { file: string; readings: number; before: { tournaments: number; events: number; flags: number; misreads: number }; after: { tournaments: number; events: number; flags: number; misreads: number }; tournaments: { key: string; name?: string; from: number; to: number }[]; eventsByKind: Record; }; export function rederivedSummary(before: FrameScanRecord, after: FrameScanRecord, file: string): FrameScanRederived { const counts = (r: FrameScanRecord) => ({ tournaments: r.derived.tournaments.length, events: r.derived.events.length, flags: r.derived.flags.length, misreads: r.derived.misreads.length }); const eventsByKind: Record = {}; for (const e of after.derived.events) eventsByKind[e.kind] = (eventsByKind[e.kind] ?? 0) + 1; return { file, readings: after.readings.length, before: counts(before), after: counts(after), tournaments: after.derived.tournaments.map((t) => ({ key: t.key, ...(t.name ? { name: t.name } : {}), from: t.from, to: t.to })), eventsByKind, }; } /** Is a frame scan of this video queued or running? (It writes the sidecar.) */ export function frameScanBusy(slug: string, id: string): boolean { return getRegistry() .list() .some((j) => j.kind === FRAME_SCAN_JOB_KIND && j.channelSlug === slug && j.videoId === id && (j.status === "queued" || j.status === "running")); } /** A video's cues (`transcript.cues.json`), sorted, or undefined. */ export async function loadCues(videoDir: string): Promise { try { const doc = JSON.parse(await readFile(path.join(videoDir, "transcript.cues.json"), "utf8")) as { cues?: unknown }; if (!Array.isArray(doc.cues)) return undefined; return doc.cues .filter((c): c is Cue => !!c && typeof c === "object" && typeof (c as Cue).start === "number" && typeof (c as Cue).end === "number" && typeof (c as Cue).text === "string") .sort((a, b) => a.start - b.start); } catch { return undefined; } } export async function enqueueFrameScan(raw: Record, deps: FrameScanDepsIn): Promise { const refuse = (error: string) => ({ result: { ok: false as const, error } }); let body: FrameScanBody; try { body = parseFrameScanBody(raw); } catch (e) { return refuse((e as Error).message); } const paths = deps.paths; const videoDir = path.join(paths.channelsDir, body.slug, "data", body.id); const cacheDir = await frameCacheDirOf(paths.channelsDir, body.slug, body.id, body.profile); if (body.evict) { const bytes = await frameCacheBytes(cacheDir); return { evicted: { dir: cacheDir, removed: await removeFrameCache(cacheDir), bytes } }; } if (body.rederive) { if (frameScanBusy(body.slug, body.id)) return refuse(`a frame scan of ${body.slug}/${body.id} is queued or running — re-derive when it is done (it writes the sidecar)`); const sidecar = frameScanSidecar(body.profile); const rec = await sidecar.load(videoDir); if (!rec) return refuse(`${body.slug}/${body.id} has no ${sidecar.filename} to re-derive — scan it first`); const cues = await loadCues(videoDir); const out = rederiveRecord(rec, { ...(cues ? { cues } : {}), ...(body.hero ? { hero: body.hero } : {}), ...(deps.now ? { now: deps.now } : {}) }); await sidecar.write(videoDir, out); return { rederived: rederivedSummary(rec, out, sidecar.filename) }; } const source = await resolveSavedVideo(videoDir); if (!source) { return refuse( `${body.slug}/${body.id} has no saved video to read frames from — save it first: ` + `pnpm ops persist-videos --json '{"items":[{"slug":"${body.slug}","id":"${body.id}"}],"format":"original"}'`, ); } const gen = (deps.settings ?? getSettings)().generation; let model: string; let maxUsd: number; try { model = frameScanModel(gen, body.model); maxUsd = frameScanCap(gen, body.maxUsd); } catch (e) { return refuse((e as Error).message); } const route = providerOf(model); // LOCAL ONLY (lib/llm/localOnly.ts): refused at the ask with a sentence; // the API client refuses again before any request. const localOnly = localOnlyJobRefusal({ models: [model] }, (m) => providerOf(m) === "local"); if (localOnly) return refuse(localOnly); const capRefusal = async () => (route === "api" ? dailyCapRefusal(await dayUsage(paths.generationUsageFile, utcDay(deps.now?.())), gen.caps.daily) : null); const early = await capRefusal(); if (early) return refuse(early); const queueKey = route === "local" ? DRAFT_LOCAL_QUEUE : FRAME_SCAN_QUEUE; const result = await runManagedFunction({ kind: FRAME_SCAN_JOB_KIND, queueKey, paths, channelSlug: body.slug, videoId: body.id, fn: modelLogged({ paths, task: "frames" }, async (onLog, signal, setProgress, ctx) => { const g = (deps.settings ?? getSettings)().generation; // Again at the job's turn: jobs ahead in the queue may have spent the day. const late = await capRefusal(); if (late) throw new Error(late); onLog(`frame scan ${body.slug}/${body.id} (${body.profile}) on ${model}${route === "api" ? ` (API cap $${maxUsd})` : ""}`); const sidecar = frameScanSidecar(body.profile); let out: FrameScanOutcome | null = null; try { out = await runFrameScan( { profile: body.profile, source, cacheDir, everySeconds: body.everySeconds ?? g.frames.everySeconds, ...(body.from !== undefined ? { from: body.from } : {}), ...(body.to !== undefined ? { to: body.to } : {}), maxFrames: body.maxFrames ?? DEFAULT_MAX_FRAMES, model, llm: llmConfigOf(g, paths, route === "local" ? { onLog, signal } : undefined), maxUsd: route === "api" ? maxUsd : Number.POSITIVE_INFINITY, ...(body.hero ? { hints: { hero: body.hero } } : {}), ...(body.framesPerAsk ? { framesPerAsk: body.framesPerAsk } : {}), ...(body.crop ? { crop: body.crop } : {}), ...(body.fresh ? { fresh: true } : {}), cues: await loadCues(videoDir), jobId: ctx.jobId, signal, onLog, onProgress: (p) => setProgress({ metric: "frames", initial: 0, target: p.total, current: p.current }), ...(deps.now ? { now: deps.now } : {}), }, { load: () => sidecar.load(videoDir), write: (r) => sidecar.write(videoDir, r) }, ); const r = out.record; onLog( `${FRAME_SCAN_RESULT_MARKER}${JSON.stringify({ slug: body.slug, id: body.id, profile: body.profile, file: sidecar.filename, frames: out.run.frames, kept: r.sampling.kept, read: out.run.read, failed: out.run.failed, readings: r.readings.length, spentUsd: out.run.costUsd, totalUsd: r.costUsd, events: r.derived.events.length, tournaments: r.derived.tournaments.length, flags: r.derived.flags.length, ...(out.run.stopped ? { stopped: out.run.stopped } : {}), })}`, ); if (out.run.stopped === "cancelled" || signal.aborted) throw new Error("cancelled"); } finally { if (route === "local") { await unloadOllama({ baseUrl: g.ollamaUrl || paths.ollamaUrl }, model).then( () => onLog(`unloaded ${model} from ollama`), (e) => onLog(`ollama unload failed: ${(e as Error).message}`), ); } if (out && route === "api") { const at = deps.now?.() ?? new Date(); const rows: GenerationUsageRow[] = Object.entries(out.spent.byModel) .filter(([, t]) => t.calls > 0) .map(([m, t]) => ({ at: at.toISOString(), day: utcDay(at), jobId: ctx.jobId, article: "", iteration: 0, task: FRAME_SCAN_JOB_KIND, model: m, inputTokens: t.input, outputTokens: t.output, cacheReadTokens: t.cacheRead, cacheWriteTokens: t.cacheWrite, usd: Math.round(t.usd * 10_000) / 10_000, })); await appendGenerationUsage(paths.generationUsageFile, rows).catch((e) => onLog(`usage not recorded: ${(e as Error).message}`)); } } }), }); if (!result.ok) return { result }; return { result, model, queueKey }; }