commit 034176331b0896382d79d099afd7908a575fd7e0
parent bfcfb20c27bb22b2b05e16af1ed98cafec8cfc27
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Thu, 15 Oct 2026 17:13:30 -0400
common, mcp: the frame scan's engine (release 30, lane P) — a saved stream sampled into frames (one ffmpeg a half hour, keyframes only, JPEGs at the profile's width and a dHash each, in a cache on the channel's media side), near-duplicates skipped, the kept frames read by a vision model through a profile (poker first: a reading of what the client shows, every field optional, coerced in code), the transcript's spoken numbers read by rules (numberWords + pokerSpoken), and pure derivation of per-tournament series, events, phase segments and spoken/frame flags; structuredAnswer takes images (Claude image blocks, ollama `images`, a fixed per-image estimate under the cap); settings.generation gains the `frames` task and `frames` block; the frame-scan job kind and controller (on `frames` or draft:local, resumable, capped, the usage ledger); the frame-scan.<profile>.json sidecar; the fakes take and check images; a synthetic poker stream for the tests
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
41 files changed, 3131 insertions(+), 25 deletions(-)
diff --git a/SETTINGS.md b/SETTINGS.md
@@ -988,6 +988,7 @@ Report and video generation (release 27): where each task runs (`code` = Claude
| `cut` | object — see below | The cut task's limits (below). |
| `verdicts` | object — see below | The verdict bench's bar and the models that cleared it (below), set on umtool's /bench after reading a run (`archilyzer reports bench-verdicts`). Verdict proposals run only on `models`. |
| `triage` | object — see below | Triage first (umtool R6): the cheap pass a recurring report runs before its sweep when it asks for one (a watch always does) — the model it judges on, when it escalates to an API sweep of what it flagged, and how often a day it may (below). |
+| `frames` | object — see below | The frame scan (`pnpm ops frame-scan`): the vision model each route reads a saved stream's frames on, a scan's spend cap and its sampling step (below). |
#### `generation.routes`
@@ -1005,6 +1006,7 @@ Report and video generation (release 27): where each task runs (`code` = Claude
| `threads` | `"local"` | A media draft: the cut's threads and each clip's thread. |
| `youtube` | `"local"` | A media draft: the YouTube title and description. |
| `social` | `"local"` | A media draft: the promotion posts for X and Bluesky (`publish.x`, `publish.bluesky`; text only, never posted), the link added by code. |
+| `frames` | `"api"` | A frame scan's readings of a saved stream's frames (`frame-scan.<profile>.json` beside the video): `api` (`frames.apiModel`) or `local` (`frames.localModel`); `code` = none unless the job names a model. |
| `verdicts` | `"local"` | Verdict proposals for a fact-check's unruled claims (`verdicts.proposed.json` beside the article; the operator approves or rejects each). Runs only on a model in `verdicts.models`: the first of them on this route (`api` or `local`), or the one a job names; `code` = none unless named. |
#### `generation.models`
@@ -1082,6 +1084,15 @@ Report and video generation (release 27): where each task runs (`code` = Claude
| `maxEscalationsPerDay` | `3` | The most escalations (tier 2 sweeps) a day (UTC) across every schedule. Past it a tick is held by the cap — a Your call card — with its flags kept. 0 = no cap. |
| `maxCandidates` | `40` | The most candidates one triage judges; the rest stay new for the next tick. |
+#### `generation.frames`
+
+| Key | Default | Description |
+|---|---|---|
+| `apiModel` | `"claude-haiku-4-5"` | The Claude model a scan on the `api` route reads frames with (it must take images). Haiku: about a cent a hundred frames. |
+| `localModel` | `"qwen2.5vl:7b"` | The ollama vision model a scan on the `local` route reads frames with (one frame an ask, under the 8k prompt cap; through the GPU arbiter on `draft:local`). |
+| `maxUsd` | `5` | A scan's API cap when the job names none (at most `caps.max`): the scan stops before an ask that would pass it, and keeps what it read. |
+| `everySeconds` | `10` | Seconds between two sampled frames when the job names none (1 to 600). |
+
Default:
```json
@@ -1100,7 +1111,8 @@ Default:
"threads": "local",
"youtube": "local",
"social": "local",
- "verdicts": "local"
+ "verdicts": "local",
+ "frames": "api"
},
"models": {
"api": "claude-sonnet-5-5",
@@ -1153,6 +1165,12 @@ Default:
"weak": 3,
"maxEscalationsPerDay": 3,
"maxCandidates": 40
+ },
+ "frames": {
+ "apiModel": "claude-haiku-4-5",
+ "localModel": "qwen2.5vl:7b",
+ "maxUsd": 5,
+ "everySeconds": 10
}
}
```
diff --git a/common/controller/frameScan.ts b/common/controller/frameScan.ts
@@ -0,0 +1,287 @@
+// `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)
+// evict remove the frame cache and answer at once (no job)
+//
+// 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 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 { 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, removeFrameCache } from "../lib/frames/sample-server";
+import { isFrameProfile, FRAME_PROFILE_IDS } from "../lib/frames/profiles";
+import { DEFAULT_MAX_FRAMES, runFrameScan, type FrameScanOutcome } from "../lib/frames/scan";
+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", "evict"] 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;
+ evict?: 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<string, unknown>): 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.evict !== undefined) {
+ if (typeof b.evict !== "boolean") fail(`"evict" is true or false`);
+ out.evict = b.evict as boolean;
+ }
+ 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 } };
+
+async function loadCues(videoDir: string): Promise<Cue[] | undefined> {
+ 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<string, unknown>, deps: FrameScanDepsIn): Promise<FrameScanEnqueued> {
+ 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 } };
+ }
+ 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);
+ 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: 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 } : {}),
+ 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 };
+}
diff --git a/common/controller/reportDraft.ts b/common/controller/reportDraft.ts
@@ -190,7 +190,9 @@ export function isKnownApiModel(model: string): boolean {
return model.startsWith("claude-") && Object.keys(PRICES).some((p) => model === p || model.startsWith(`${p}-`));
}
-const TASKS: readonly ReportDraftTask[] = [...GENERATION_TASKS, REFRESH_TASK, TRIAGE_DRAFT_TASK];
+// `frames` is routed by settings.generation like every task, but it is the
+// frame scan's (`pnpm ops frame-scan`), never a report-draft.
+const TASKS: readonly ReportDraftTask[] = [...GENERATION_TASKS.filter((t) => t !== "frames"), REFRESH_TASK, TRIAGE_DRAFT_TASK];
const ymd = /^\d{4}-\d{2}-\d{2}$/;
function fail(msg: string): never {
@@ -700,7 +702,8 @@ async function runReportDraft(
case "refresh":
case "triage":
case "verdicts":
- // A refresh, a triage and verdict proposals are their own jobs (./reportRefresh.ts, ./reportTriage.ts, ./reportVerdicts.ts), never this one.
+ case "frames":
+ // A refresh, a triage, verdict proposals and a frame scan are their own jobs (./reportRefresh.ts, ./reportTriage.ts, ./reportVerdicts.ts, ./frameScan.ts), never this one.
throw new Error(`a ${body.task} runs as its own job`);
case "sweep":
input =
diff --git a/common/jobs/jobKinds.ts b/common/jobs/jobKinds.ts
@@ -979,6 +979,21 @@ const JOB_KINDS: Record<string, JobKindMeta> = {
replayable: false,
queueKeyStrategy: "custom",
},
+ // The frame scan (release 30, lane P): a saved stream sampled into frames
+ // and the kept ones read by a vision model through a profile (poker), into
+ // `frame-scan.<profile>.json` beside the video — `pnpm ops frame-scan`, the
+ // video page's Scan button. On `frames` (API) or `draft:local` (a local
+ // vision model, through the GPU arbiter). OPENS THE SAVED CONTAINER and
+ // writes the frame cache on the channel's media side: needsMedia. Not
+ // replayable: the same body again resumes it (read frames are skipped).
+ "frame-scan": {
+ kind: "frame-scan",
+ label: "Frame scan",
+ drainable: false,
+ replayable: false,
+ queueKeyStrategy: "custom",
+ needsMedia: true,
+ },
"tts-file": {
kind: "tts-file",
label: "Text to speech",
diff --git a/common/jobs/registry.ts b/common/jobs/registry.ts
@@ -33,7 +33,10 @@ export type JobProgressMetric =
// re-count; the runner always sets `current`.
| "turns"
| "cards"
- | "entries";
+ | "entries"
+ // A frame scan (controller/frameScan.ts, release 30): frames sampled, then
+ // frames read. The runner always sets `current`.
+ | "frames";
export type JobProgress = {
metric: JobProgressMetric;
diff --git a/common/lib/frameScan-server.ts b/common/lib/frameScan-server.ts
@@ -0,0 +1,101 @@
+// The frame scan's per-video files (release 30, lane P).
+//
+// channels/<slug>/data/<id>/frame-scan.<profile>.json the timeline sidecar
+// (readings, spoken numbers, the derived series/events/segments) — TEXT,
+// on the corpus disk with every other sidecar. Never published: nothing
+// in the export build reads it.
+// channels/<slug>/media/<id>/frames/<profile>/ the frame CACHE —
+// JPEGs and their index, on the channel's MEDIA side (the media tier's
+// directory, which may be a link to another drive), so a 4-hour stream's
+// frames never land on /home when the channel's media lives elsewhere.
+// A classic channel (no `media/`) keeps them in `data/<id>/frames/`.
+// Evictable at any time (`frame-scan {evict: true}`): a re-run decodes
+// them again, and readings already in the sidecar are not asked again.
+// Deleting the video removes `media/<id>/` and so the cache with it.
+
+import path from "node:path";
+import { lstat } from "node:fs/promises";
+import { sidecar, sidecarField, type Sidecar } from "./sidecar-server";
+import { FRAME_PROFILE_IDS } from "./frames/profiles";
+import { FRAME_SCAN_FORMAT, type Derived, type SpokenReading } from "./frames/types";
+
+export const frameScanFilename = (profile: string) => `frame-scan.${profile}.json`;
+
+export type FrameScanRun = {
+ at: string;
+ jobId?: string;
+ model: string;
+ route: "api" | "local";
+ frames: number;
+ read: number;
+ failed: number;
+ costUsd: number;
+ stopped?: "cap" | "cancelled" | "errors" | "maxFrames";
+};
+
+export type FrameScanRecord = {
+ format: typeof FRAME_SCAN_FORMAT;
+ version: 1;
+ profile: string;
+ source: { savedVideo: string; durationSeconds: number | null };
+ sampling: { everySeconds: number; from: number; to: number; width: number; keyframesOnly: boolean; frames: number; kept: number; skippedDuplicates: number };
+ model: { route: "api" | "local"; model: string; promptVersion: number };
+ costUsd: number;
+ runs: FrameScanRun[];
+ readings: ({ t: number; phase: string } & Record<string, unknown>)[];
+ // Frames not read because they duplicate a read one: [t, the read frame's t].
+ duplicates: [number, number][];
+ spoken: SpokenReading[];
+ derived: Derived;
+ updatedAt: string;
+};
+
+const isObj = (v: unknown): v is Record<string, unknown> => !!v && typeof v === "object" && !Array.isArray(v);
+
+export function coerceFrameScan(v: unknown): FrameScanRecord | null {
+ if (!isObj(v) || v.format !== FRAME_SCAN_FORMAT || typeof v.profile !== "string") return null;
+ if (!Array.isArray(v.readings) || !isObj(v.derived) || !isObj(v.sampling) || !isObj(v.source)) return null;
+ const d = v.derived as Record<string, unknown>;
+ if (!Array.isArray(d.tournaments) || !Array.isArray(d.events) || !Array.isArray(d.segments)) return null;
+ return {
+ ...(v as unknown as FrameScanRecord),
+ runs: Array.isArray(v.runs) ? (v.runs as FrameScanRun[]) : [],
+ spoken: Array.isArray(v.spoken) ? (v.spoken as SpokenReading[]) : [],
+ duplicates: Array.isArray(v.duplicates) ? (v.duplicates as [number, number][]).filter((p) => Array.isArray(p) && p.length === 2) : [],
+ derived: { ...(d as unknown as Derived), flags: Array.isArray(d.flags) ? (d.flags as Derived["flags"]) : [], misreads: Array.isArray(d.misreads) ? (d.misreads as Derived["misreads"]) : [] },
+ costUsd: typeof v.costUsd === "number" ? v.costUsd : 0,
+ };
+}
+
+// One declaration per profile, at load (sidecar()'s naming guard runs then).
+const SIDECARS: Record<string, Sidecar<FrameScanRecord>> = Object.fromEntries(
+ FRAME_PROFILE_IDS.map((p) => [p, sidecar(frameScanFilename(p), sidecarField(coerceFrameScan), { indent: 0 })]),
+);
+
+export function frameScanSidecar(profile: string): Sidecar<FrameScanRecord> {
+ const s = SIDECARS[profile];
+ if (!s) throw new Error(`"${profile}" is not a frame-scan profile`);
+ return s;
+}
+
+export const loadFrameScan = (videoDir: string, profile: string) => frameScanSidecar(profile).load(videoDir);
+
+/** Every profile's sidecar this video has. */
+export async function loadFrameScans(videoDir: string): Promise<FrameScanRecord[]> {
+ const out: FrameScanRecord[] = [];
+ for (const p of FRAME_PROFILE_IDS) {
+ const r = await loadFrameScan(videoDir, p);
+ if (r) out.push(r);
+ }
+ return out;
+}
+
+/** Where a video's frame cache for a profile lives (see the header). */
+export async function frameCacheDirOf(channelsDir: string, slug: string, id: string, profile: string): Promise<string> {
+ const media = path.join(channelsDir, slug, "media");
+ const tiered = await lstat(media).then(
+ (l) => l.isDirectory() || l.isSymbolicLink(),
+ () => false,
+ );
+ return tiered ? path.join(media, id, "frames", profile) : path.join(channelsDir, slug, "data", id, "frames", profile);
+}
diff --git a/common/lib/frames/dhash.test.ts b/common/lib/frames/dhash.test.ts
@@ -0,0 +1,40 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { dHash, duplicatesOf, hamming, hashesOf, THUMB_BYTES, THUMB_H, THUMB_W } from "./dhash";
+
+const flat = (v: number) => new Uint8Array(THUMB_BYTES).fill(v);
+const ramp = (dir: 1 | -1) => {
+ const a = new Uint8Array(THUMB_BYTES);
+ for (let r = 0; r < THUMB_H; r++) for (let c = 0; c < THUMB_W; c++) a[r * THUMB_W + c] = dir === 1 ? c * 10 : 250 - c * 10;
+ return a;
+};
+
+test("dHash: brightness-proof, and a picture that moves changes it", () => {
+ assert.equal(dHash(flat(10)), dHash(flat(200)));
+ assert.equal(dHash(ramp(-1)).length, ((THUMB_W - 1) * THUMB_H) / 4);
+ assert.equal(hamming(dHash(ramp(-1)), dHash(ramp(1))), (THUMB_W - 1) * THUMB_H);
+ assert.equal(hamming(dHash(flat(1)), dHash(flat(1))), 0);
+ assert.throws(() => dHash(new Uint8Array(3)));
+});
+
+test("hamming: Infinity when two hashes cannot be compared", () => {
+ assert.equal(hamming("ab", "abc"), Infinity);
+ assert.equal(hamming("", ""), Infinity);
+ assert.equal(hamming("f0", "0f"), 8);
+});
+
+test("hashesOf: one hash per thumbnail in a rawvideo stream", () => {
+ const raw = Buffer.concat([Buffer.from(flat(5)), Buffer.from(ramp(-1)), Buffer.alloc(7)]);
+ const hs = hashesOf(raw);
+ assert.equal(hs.length, 2);
+ assert.equal(hs[1], dHash(ramp(-1)));
+});
+
+test("duplicatesOf: a duplicate of the last READ frame is skipped; a run is read again every N", () => {
+ const A = "0000";
+ const B = "ffff";
+ const out = duplicatesOf([A, A, A, B, B, A, A, A, A, A], { maxBits: 0, rereadEvery: 3 });
+ assert.deepEqual(out, [null, 0, 0, null, 3, null, 5, 5, null, 8]);
+ // Near enough under maxBits.
+ assert.deepEqual(duplicatesOf(["0000", "0001", "0003"], { maxBits: 1, rereadEvery: 0 }), [null, 0, null]);
+});
diff --git a/common/lib/frames/dhash.ts b/common/lib/frames/dhash.ts
@@ -0,0 +1,70 @@
+// A difference hash of a frame's tiny grey thumbnail (release 30, lane P):
+// the cheap test of "the same picture as the last one" that lets a static
+// lobby or break screen cost one read. Pure.
+//
+// The thumbnail is (w+1)×h grey bytes, row-major, as ffmpeg writes
+// `scale=<w+1>:<h>,format=gray` rawvideo: each bit says whether a pixel is
+// brighter than its right-hand neighbour, so the hash survives a change of
+// overall brightness and of compression noise, and a picture that moves does
+// not.
+
+export const THUMB_W = 17;
+export const THUMB_H = 16;
+export const THUMB_BYTES = THUMB_W * THUMB_H;
+
+/** The dHash (hex, `(w-1)·h` bits) of one `w`×`h` grey thumbnail. */
+export function dHash(px: Uint8Array | Buffer, w = THUMB_W, h = THUMB_H): string {
+ if (px.length < w * h) throw new Error(`a ${w}×${h} thumbnail is ${w * h} bytes, not ${px.length}`);
+ const bits: number[] = [];
+ for (let r = 0; r < h; r++) for (let c = 0; c < w - 1; c++) bits.push(px[r * w + c] > px[r * w + c + 1] ? 1 : 0);
+ while (bits.length % 4) bits.push(0);
+ let hex = "";
+ for (let i = 0; i < bits.length; i += 4) hex += ((bits[i] << 3) | (bits[i + 1] << 2) | (bits[i + 2] << 1) | bits[i + 3]).toString(16);
+ return hex;
+}
+
+const POP = [0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4];
+
+/** Bits two hashes of one length differ by; Infinity when they cannot be compared. */
+export function hamming(a: string, b: string): number {
+ if (!a || a.length !== b.length) return Infinity;
+ let d = 0;
+ for (let i = 0; i < a.length; i++) {
+ const x = parseInt(a[i], 16) ^ parseInt(b[i], 16);
+ if (Number.isNaN(x)) return Infinity;
+ d += POP[x];
+ }
+ return d;
+}
+
+/** Split ffmpeg's rawvideo stream of thumbnails into one hash per frame. */
+export function hashesOf(raw: Buffer | Uint8Array, w = THUMB_W, h = THUMB_H): string[] {
+ const n = Math.floor(raw.length / (w * h));
+ const out: string[] = [];
+ for (let i = 0; i < n; i++) out.push(dHash(raw.subarray(i * w * h, (i + 1) * w * h), w, h));
+ return out;
+}
+
+/**
+ * Which frames a model must read: a frame is a duplicate of the last frame
+ * READ when their hashes differ by at most `maxBits`, and a duplicate run is
+ * read again every `rereadEvery` frames. Answers, per frame in order, null (read
+ * it) or the index of the frame it duplicates.
+ */
+export function duplicatesOf(hashes: readonly string[], o: { maxBits: number; rereadEvery: number }): (number | null)[] {
+ const out: (number | null)[] = [];
+ let lastRead = -1;
+ let run = 0;
+ for (let i = 0; i < hashes.length; i++) {
+ const dup = lastRead >= 0 && hamming(hashes[i], hashes[lastRead]) <= o.maxBits;
+ if (dup && (o.rereadEvery <= 0 || run + 1 < o.rereadEvery)) {
+ out.push(lastRead);
+ run++;
+ } else {
+ out.push(null);
+ lastRead = i;
+ run = 0;
+ }
+ }
+ return out;
+}
diff --git a/common/lib/frames/numberWords.test.ts b/common/lib/frames/numberWords.test.ts
@@ -0,0 +1,33 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { normalizeNumbers, numbersIn } from "./numberWords";
+
+const cases: [string, string][] = [
+ ["eighty five players left", "85 players left"],
+ ["fifteen players left", "15 players left"],
+ ["$2,750 buy in", "$2750 buy in"],
+ ["an opponent at five hundred sixty seven thousand chips", "an opponent at 567000 chips"],
+ ["the average stack is three hundred seventy three thousand, I have two hundred thirty three", "the average stack is 373000, I have 233"],
+ ["a double up would put me in the top twenty", "a double up would put me in the top 20"],
+ ["first place five hundred bucks", "first place 500 bucks"],
+ ["blinds are five ten", "blinds are 5 10"],
+ ["one point five million", "1500000"],
+ ["233k and 10M", "233000 and 10000000"],
+ ["two million three hundred thousand", "2300000"],
+ ["a hundred and five", "105"],
+ ["eighty-five", "85"],
+ ["twenty five hundred", "2500"],
+ ["I have no one to call", "I have no one to call"],
+ ["level 14, blinds 1,500/3,000 ante 3,000", "level 14, blinds 1500/3000 ante 3000"],
+ ["thousand thousand", "1000 1000"],
+ ["a cat", "a cat"],
+];
+
+test("normalizeNumbers: spoken and written numbers become plain digits, the rest is kept", () => {
+ for (const [input, want] of cases) assert.equal(normalizeNumbers(input), want, input);
+});
+
+test("numbersIn: every number, in order", () => {
+ assert.deepEqual(numbersIn("blinds two hundred four hundred, eighty five left"), [200, 400, 85]);
+ assert.deepEqual(numbersIn("nothing here"), []);
+});
diff --git a/common/lib/frames/numberWords.ts b/common/lib/frames/numberWords.ts
@@ -0,0 +1,242 @@
+// Spoken numbers as digits (release 30, lane P). An ASR transcript writes a
+// number the way it was said — "eighty five players left", "three hundred
+// seventy three thousand", "$2,750 buy in", "233k" — and the frame scan's
+// spoken signal (`spoken.ts`) reads stats out of that text with plain
+// patterns. So the text is normalized first: every run of number words (and
+// every digit group with commas, a decimal point or a `k`/`m` suffix) becomes
+// one plain number, and the patterns only ever see digits.
+//
+// Rule-based and pure. What it does NOT do: ordinals ("third"), fractions
+// ("a half"), years read as pairs ("twenty twenty five" is 20 then 25), and
+// "grand". A run that is not a well-formed number splits where the next word
+// cannot continue it ("five ten" is 5 then 10, as blinds are said).
+
+const UNITS: Record<string, number> = {
+ zero: 0, oh: 0, one: 1, two: 2, three: 3, four: 4, five: 5, six: 6, seven: 7, eight: 8, nine: 9,
+ ten: 10, eleven: 11, twelve: 12, thirteen: 13, fourteen: 14, fifteen: 15, sixteen: 16, seventeen: 17,
+ eighteen: 18, nineteen: 19,
+};
+const TENS: Record<string, number> = {
+ twenty: 20, thirty: 30, forty: 40, fourty: 40, fifty: 50, sixty: 60, seventy: 70, eighty: 80, ninety: 90,
+};
+const SCALES: Record<string, number> = { thousand: 1_000, million: 1_000_000, billion: 1_000_000_000 };
+
+// A digit token: "2,750", "1.5", "233k", "$5", "10m". The `$` stays outside.
+const DIGITS = /^(\d{1,3}(?:,\d{3})+|\d+)(?:\.(\d+))?(k|m|mil|bn)?$/i;
+
+type Tok = { word: string; raw: string };
+
+function digitValue(w: string): number | null {
+ const m = DIGITS.exec(w);
+ if (!m) return null;
+ let v = Number(m[1].replace(/,/g, "") + (m[2] ? `.${m[2]}` : ""));
+ const suf = (m[3] ?? "").toLowerCase();
+ if (suf === "k") v *= 1_000;
+ else if (suf === "m" || suf === "mil") v *= 1_000_000;
+ else if (suf === "bn") v *= 1_000_000_000;
+ return Number.isFinite(v) ? v : null;
+}
+
+// What kind of number word a token is, or null.
+function kindOf(w: string): "unit" | "tens" | "hundred" | "scale" | "digits" | null {
+ if (w in UNITS) return "unit";
+ if (w in TENS) return "tens";
+ if (w === "hundred") return "hundred";
+ if (w in SCALES) return "scale";
+ if (digitValue(w) !== null) return "digits";
+ return null;
+}
+
+// One number from a run of tokens that form it (the caller decides the run).
+class Acc {
+ total = 0;
+ current = 0;
+ decimal: string | null = null;
+ last: "unit" | "tens" | "hundred" | "scale" | "digits" | "a" | null = null;
+ any = false;
+ // The count before the last "hundred" ("fifteen hundred" → 15).
+ hundredsCount = 0;
+
+ value(): number {
+ return this.total + this.current;
+ }
+
+ // Whether `w` (of kind `k`) continues the number so far.
+ accepts(k: ReturnType<typeof kindOf> | "a" | "point", w: string): boolean {
+ if (!this.any) return k !== "point";
+ if (this.decimal !== null) return k === "unit" && UNITS[w] <= 9 ? true : k === "scale";
+ switch (k) {
+ case "unit":
+ // "twenty five" and "a hundred five" continue; "five ten" does not.
+ if (this.last === "tens") return UNITS[w] <= 9;
+ return this.last === "hundred" || this.last === "scale";
+ case "tens":
+ return this.last === "hundred" || this.last === "scale";
+ case "hundred":
+ return (this.last === "unit" || this.last === "a") && this.current < 100 && this.current > 0;
+ case "scale":
+ return this.last !== "scale" && this.value() > 0 && (this.lastScale() === 0 || SCALES[w] < this.lastScale());
+ case "digits":
+ return false;
+ case "point":
+ return this.last === "unit" || this.last === "tens" || this.last === "digits";
+ case "a":
+ return false;
+ default:
+ return false;
+ }
+ }
+
+ private scales: number[] = [];
+ private lastScale(): number {
+ // A scale may follow only a smaller one ("two million three hundred
+ // thousand"); "thousand thousand" is two numbers.
+ return this.scales.length ? Math.min(...this.scales) : 0;
+ }
+
+ add(k: NonNullable<ReturnType<typeof kindOf>> | "a" | "point", w: string): void {
+ this.any = true;
+ if (k === "point") {
+ this.decimal = "";
+ this.last = "unit";
+ return;
+ }
+ if (this.decimal !== null && k === "unit") {
+ this.decimal += String(UNITS[w]);
+ this.current = Math.trunc(this.current) + Number(`0.${this.decimal}`);
+ return;
+ }
+ switch (k) {
+ case "a":
+ this.current = 1;
+ break;
+ case "unit":
+ this.current += UNITS[w];
+ break;
+ case "tens":
+ this.current += TENS[w];
+ break;
+ case "hundred":
+ this.hundredsCount = this.current || 1;
+ this.current = (this.current || 1) * 100;
+ break;
+ case "scale":
+ this.total += (this.current || 1) * SCALES[w];
+ this.current = 0;
+ this.scales.push(SCALES[w]);
+ this.decimal = null;
+ break;
+ case "digits":
+ this.current = digitValue(w) ?? 0;
+ break;
+ }
+ this.last = k;
+ }
+}
+
+// "no one", "the one", "this one": a pronoun, not a count.
+const NOT_A_NUMBER_BEFORE_ONE = new Set(["no", "any", "some", "every", "the", "this", "that", "which", "each", "another", "last", "next", "only"]);
+
+function tokenize(text: string): Tok[] {
+ // Words, digit groups and the punctuation between them, every piece kept so
+ // the text can be put back together around the numbers.
+ return (text.match(/\$|\d[\d,]*(?:\.\d+)?(?:k|m|mil|bn)?\b|[A-Za-z]+(?:'[A-Za-z]+)?|[^A-Za-z\d$]+/gi) ?? []).map((raw) => ({
+ raw,
+ word: raw.toLowerCase(),
+ }));
+}
+
+const fmt = (v: number) => (Number.isInteger(v) ? String(v) : String(Math.round(v * 1000) / 1000));
+
+// The words of the number run that would follow token `n` (its own word first).
+function runAhead(toks: readonly Tok[], n: number): string[] {
+ const out: string[] = [toks[n].word];
+ for (let k = n + 1; k + 1 < toks.length && /^[\s-]+$/.test(toks[k].raw); k += 2) {
+ const w = toks[k + 1].word;
+ if (!kindOf(w) && w !== "and") break;
+ out.push(w);
+ }
+ return out;
+}
+
+// Where two numbers said back to back would otherwise run together: "two
+// hundred four hundred" is 200 then 400 (not 204, 100), and "fifteen hundred
+// three thousand" is 1500 then 3000 (blinds, said the colloquial way: a
+// hundreds count of ten or more is a whole number, never the start of a
+// larger one).
+function splitsBefore(acc: Acc, k: string, toks: readonly Tok[], n: number): boolean {
+ if (acc.last !== "hundred" || (k !== "unit" && k !== "tens")) return false;
+ const ahead = runAhead(toks, n);
+ const next = ahead.findIndex((w, i) => i > 0 && (w === "hundred" || w in SCALES));
+ if (next < 0) return false;
+ if (ahead[next] === "hundred") return true;
+ return acc.hundredsCount >= 10;
+}
+
+/**
+ * The text with every spoken or written number as plain digits: "eighty five
+ * players left" → "85 players left", "$2,750" → "$2750", "two hundred thirty
+ * three thousand" → "233000", "1.5 million" → "1500000". Hyphens inside a
+ * number ("eighty-five") join it. Everything else is kept as it was.
+ */
+export function normalizeNumbers(text: string): string {
+ const toks = tokenize(text);
+ const out: string[] = [];
+ let i = 0;
+ while (i < toks.length) {
+ const t = toks[i];
+ const k = kindOf(t.word);
+ // "a hundred", "a thousand": "a" starts a number only before a scale.
+ const aStart = t.word === "a" && i + 2 < toks.length && /^\s+$/.test(toks[i + 1].raw) && (toks[i + 2].word === "hundred" || toks[i + 2].word in SCALES);
+ if (!k && !aStart) {
+ out.push(t.raw);
+ i++;
+ continue;
+ }
+ const acc = new Acc();
+ acc.add(aStart ? "a" : (k as NonNullable<typeof k>), t.word);
+ let j = i + 1;
+ let end = i; // last token index in the number
+ while (j < toks.length) {
+ const sep = toks[j];
+ // A separator between two number words: spaces, a hyphen, " and ".
+ if (/^[\s-]+$/.test(sep.raw) && j + 1 < toks.length) {
+ let n = j + 1;
+ // "three hundred and five": "and" continues a number after hundred/scale.
+ if (toks[n].word === "and" && (acc.last === "hundred" || acc.last === "scale") && n + 2 < toks.length && /^\s+$/.test(toks[n + 1].raw)) n += 2;
+ const w = toks[n].word;
+ const nk = w === "point" ? "point" : kindOf(w);
+ if (nk && acc.accepts(nk, w) && !splitsBefore(acc, nk, toks, n)) {
+ if (nk === "point") {
+ // "one point five": the point needs a unit after it.
+ const after = toks[n + 2]?.word;
+ if (!(n + 2 < toks.length && /^\s+$/.test(toks[n + 1].raw) && after && after in UNITS && UNITS[after] <= 9)) break;
+ }
+ acc.add(nk, w);
+ end = n;
+ j = n + 1;
+ continue;
+ }
+ break;
+ }
+ // A digit group followed directly by a scale word with no space is not a thing; stop.
+ break;
+ }
+ // A lone "oh" or "one" stays a word only when it is plainly not a number:
+ // "oh" alone, never; "one" alone becomes 1 (the patterns need it).
+ const prev = out.length ? (out[out.length - 1].trim() === "" ? out[out.length - 2] ?? "" : out[out.length - 1]).trim().toLowerCase() : "";
+ if (end === i && (t.word === "oh" || (t.word === "one" && NOT_A_NUMBER_BEFORE_ONE.has(prev)))) {
+ out.push(t.raw);
+ i++;
+ continue;
+ }
+ out.push(fmt(acc.value()));
+ i = end + 1;
+ }
+ return out.join("");
+}
+
+/** Every number in a text, in order (after `normalizeNumbers`). */
+export function numbersIn(text: string): number[] {
+ return (normalizeNumbers(text).match(/\d+(?:\.\d+)?/g) ?? []).map(Number);
+}
diff --git a/common/lib/frames/poker.test.ts b/common/lib/frames/poker.test.ts
@@ -0,0 +1,175 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { closeSchema } from "../llm/structured";
+import { coercePokerReading, derivePoker, pokerSchema, pokerSystem, pokerUser, POKER_PROFILE, type PokerReading } from "./poker";
+import type { SpokenReading } from "./types";
+
+type R = PokerReading & { t: number };
+const table = (t: number, stack: number | undefined, more: Partial<NonNullable<PokerReading["tournament"]>> = {}, extra: Partial<PokerReading> = {}): R => ({
+ t,
+ phase: "table",
+ tournament: { name: "Main Event", playersLeft: 85, totalPlayers: 120, level: 3, blinds: { sb: 100, bb: 200 }, ...more },
+ ...(stack !== undefined ? { hero: { stack } } : {}),
+ ...extra,
+});
+const derive = (rs: R[], spoken: SpokenReading[] = []) => derivePoker(rs, spoken, { everySeconds: 10 });
+const series = (d: ReturnType<typeof derive>, field: string, key?: string) =>
+ (key ? d.tournaments.find((t) => t.key === key)! : d.tournaments[0]).series[field];
+
+// ─── coerce ───
+
+test("coerce: a reading's fields are checked; unreadable is absent, never zero", () => {
+ const r = coercePokerReading({
+ frame: 1,
+ phase: "table",
+ tournament: { name: " Main Event ", level: 7, smallBlind: 500, bigBlind: 1000, ante: null, playersLeft: 85, totalPlayers: 1200, prizePool: null },
+ hero: { stack: 23456.4, stackInBigBlinds: null, seat: null, cards: ["Ah", "10d"] },
+ hand: { pot: 4500, board: ["7c", "7c"], action: null },
+ event: null,
+ });
+ assert.deepEqual(r, {
+ phase: "table",
+ tournament: { name: "Main Event", level: 7, blinds: { sb: 500, bb: 1000 }, playersLeft: 85, totalPlayers: 1200 },
+ hero: { stack: 23456, cards: ["Ah", "Td"] },
+ hand: { pot: 4500 },
+ });
+});
+
+test("coerce: refuses what is not a reading, and drops misread pairs", () => {
+ assert.equal(coercePokerReading(null), null);
+ assert.equal(coercePokerReading({ phase: "dancing" }), null);
+ const r = coercePokerReading({ phase: "table", tournament: { smallBlind: 400, bigBlind: 200, playersLeft: 90, totalPlayers: 40 }, hero: { stack: -5 }, event: "fireworks" });
+ assert.deepEqual(r, { phase: "table", tournament: { playersLeft: 90 } });
+});
+
+// ─── the ask ───
+
+test("the prompt carries rules, a hero hint when given, and no sample reading", () => {
+ const s = pokerSystem({ hero: "SynthHero" });
+ assert.match(s, /null/);
+ assert.match(s, /"SynthHero"/);
+ assert.doesNotMatch(s, /\{"phase"/);
+ assert.doesNotMatch(pokerSystem(), /screen name is/);
+ assert.equal(pokerUser([{ t: 65 }, { t: 3725 }]), "2 frames, in order: frame 1 at 1:05; frame 2 at 1:02:05. Read each.");
+});
+
+test("the schema asks for exactly n readings and closes for a strict model", () => {
+ const s = pokerSchema(3) as { properties: { frames: { minItems: number; maxItems: number } } };
+ assert.equal(s.properties.frames.minItems, 3);
+ assert.equal(s.properties.frames.maxItems, 3);
+ const closed = JSON.stringify(closeSchema(pokerSchema(1)));
+ assert.match(closed, /"additionalProperties":false/);
+ assert.ok(POKER_PROFILE.framesPerAsk.local === 1);
+});
+
+// ─── derive ───
+
+test("a stack that jumps 100× for one frame is a misread, not a double-up", () => {
+ const d = derive([table(0, 20000), table(10, 2000000), table(20, 20500), table(30, 21000)]);
+ assert.deepEqual(d.misreads.filter((m) => m.field === "stack"), [{ t: 10, field: "stack", value: 2000000 }]);
+ assert.deepEqual(d.events.filter((e) => e.kind === "double-up"), []);
+ assert.deepEqual(series(d, "stack"), [[0, 20000], [20, 20500], [30, 21000]]);
+});
+
+test("a double-up held by the next frame is an event; a big loss too", () => {
+ const d = derive([table(0, 20000), table(10, 20000), table(20, 41000), table(30, 41500), table(40, 15000), table(50, 15000), table(60, 15500)]);
+ const kinds = d.events.map((e) => [e.t, e.kind]);
+ assert.deepEqual(kinds, [[20, "double-up"], [40, "big-loss"]]);
+ assert.match(d.events[0].detail, /20,000 → 41,000 chips \(2\.0×\)/);
+});
+
+test("stack in big blinds is the client's when shown, else the stack over the big blind", () => {
+ const d = derive([table(0, 20000), table(10, 30000, {}, { hero: { stack: 30000, bb: 150 } })]);
+ assert.deepEqual(series(d, "stackBB"), [[0, 100], [10, 150]]);
+});
+
+test("a bust: the stack at 0 and no chips after it in that tournament", () => {
+ const d = derive([table(0, 9000), table(10, 9000), table(20, 0, {}, { event: "eliminated" }), { t: 30, phase: "lobby", tournament: { name: "Main Event" } }]);
+ const bust = d.events.find((e) => e.kind === "bust")!;
+ assert.equal(bust.t, 20);
+ assert.match(bust.detail, /out from 9,000 chips/);
+ assert.ok(d.events.some((e) => e.kind === "eliminated" && e.source === "frame"));
+});
+
+test("a 0 for one frame between two stacks is a misread, not a bust", () => {
+ const d = derive([table(0, 9000), table(10, 0), table(20, 9100)]);
+ assert.equal(d.events.filter((e) => e.kind === "bust").length, 0);
+});
+
+test("the final table: players left first at 9 or fewer in a larger field", () => {
+ const d = derive([table(0, 1, { playersLeft: 12 }), table(10, 1, { playersLeft: 10 }), table(20, 1, { playersLeft: 9 }), table(30, 1, { playersLeft: 8 })]);
+ assert.deepEqual(d.events.filter((e) => e.kind === "final-table").map((e) => e.t), [20]);
+});
+
+test("a win: one player left and the hero with chips", () => {
+ const d = derive([table(0, 50000, { playersLeft: 2 }), table(10, 240000, { playersLeft: 1 })]);
+ assert.ok(d.events.some((e) => e.kind === "won" && e.t === 10));
+});
+
+test("frame events are one per run: the same banner for a minute is one moment", () => {
+ const d = derive([table(0, 1000, {}, { event: "all-in" }), table(10, 1000, {}, { event: "all-in" }), table(100, 1000, {}, { event: "all-in" })]);
+ assert.deepEqual(d.events.filter((e) => e.kind === "all-in").map((e) => e.t), [0, 100]);
+});
+
+test("phase segments: a one-frame blip between two of another phase is absorbed", () => {
+ const d = derive([
+ { t: 0, phase: "lobby" },
+ { t: 10, phase: "lobby" },
+ table(20, 100),
+ { t: 30, phase: "other" },
+ table(40, 100),
+ { t: 50, phase: "break" },
+ { t: 60, phase: "break" },
+ ]);
+ assert.deepEqual(d.segments.map((s) => [s.from, s.to, s.phase]), [[0, 20, "lobby"], [20, 50, "table"], [50, 70, "break"]]);
+ assert.equal(d.segments[1].tournament, "main event");
+});
+
+test("two tournaments in one stream never share a series", () => {
+ const viewer = (t: number, stack: number): R => ({ t, phase: "table", tournament: { name: "Viewer $1000", playersLeft: 30, totalPlayers: 40 }, hero: { stack } });
+ const d = derive([table(0, 20000), table(10, 21000), { t: 20, phase: "lobby" }, viewer(30, 1500), viewer(40, 3100), viewer(50, 3200)]);
+ assert.deepEqual(d.tournaments.map((t) => [t.key, t.name, t.from]), [["main event", "Main Event", 0], ["viewer $1000", "Viewer $1000", 30]]);
+ assert.deepEqual(series(d, "stack", "main event"), [[0, 20000], [10, 21000]]);
+ assert.deepEqual(series(d, "stack", "viewer $1000"), [[30, 1500], [40, 3100], [50, 3200]]);
+ // The viewer tournament's double-up is its own.
+ assert.ok(d.events.some((e) => e.kind === "double-up" && e.tournament === "viewer $1000"));
+});
+
+test("unnamed readings take the name before them; a field that changes size is another tournament", () => {
+ const d = derive([
+ table(0, 1000, { totalPlayers: 1200 }),
+ { t: 10, phase: "table", tournament: { totalPlayers: 1200 }, hero: { stack: 1100 } },
+ { t: 20, phase: "table", tournament: { totalPlayers: 40 }, hero: { stack: 50 } },
+ ]);
+ assert.deepEqual(d.tournaments.map((t) => t.key), ["main event", "main event#2"]);
+});
+
+test("a spoken number that disagrees with a nearby frame is flagged, never trusted; one that agrees is quiet", () => {
+ const spoken: SpokenReading[] = [
+ { t: 12, field: "playersLeft", value: 85, text: "eighty five players left" },
+ { t: 22, field: "playersLeft", value: 40, text: "forty players left" },
+ ];
+ const d = derive([table(0, 1000), table(10, 1000), table(20, 1000)], spoken);
+ assert.deepEqual(d.flags, [{ t: 22, field: "playersLeft", spoken: 40, frame: 85, frameT: 0, tournament: "main event" }]);
+});
+
+test("a spoken number where no frame read the field fills the series, marked spoken, and makes no event", () => {
+ const spoken: SpokenReading[] = [{ t: 400, field: "stack", value: 60000, text: "I have sixty thousand" }];
+ const rs = [table(0, 20000), ...Array.from({ length: 59 }, (_, i) => table(10 + i * 10, undefined)), table(600, 20500)];
+ const d = derive(rs, spoken);
+ assert.deepEqual(series(d, "stack"), [[0, 20000], [400, 60000, "spoken"], [600, 20500]]);
+ assert.equal(d.events.filter((e) => e.kind === "double-up").length, 0);
+});
+
+test("spoken facts land in the tournament's facts when no frame read them; a buy-in is an event", () => {
+ const spoken: SpokenReading[] = [{ t: 5, field: "buyIn", value: 2750, text: "$2,750 buy in" }];
+ const d = derive([table(0, 1000), table(10, 1000)], spoken);
+ assert.equal(d.tournaments[0].facts.buyIn, 2750);
+ assert.equal(d.tournaments[0].facts.totalPlayers, 120);
+ assert.ok(d.events.some((e) => e.kind === "buy-in" && e.source === "spoken"));
+});
+
+test("derive is pure over its input order", () => {
+ const rs = [table(20, 41000), table(0, 20000), table(10, 20000), table(30, 41000)];
+ assert.deepEqual(derive(rs), derive([...rs].sort((a, b) => a.t - b.t)));
+});
diff --git a/common/lib/frames/poker.ts b/common/lib/frames/poker.ts
@@ -0,0 +1,450 @@
+// The frame scan's first profile: an online poker client on a stream
+// (release 30, lane P). A vision model reads each kept frame into a POKER
+// READING — what the client shows, every field optional and never invented —
+// and pure code derives the rest: the series per tournament (chips, big
+// blinds, players left, level), the events (a double-up, a bust, the final
+// table…), the phase segments, and the flags where a spoken number disagrees
+// with what a frame read.
+//
+// The model reads a frame; code derives everything else (the brief's rule).
+// Counts, ranges and enums are enforced here, in `coercePokerReading`, never
+// trusted from the prompt.
+
+import { pokerSpoken } from "./pokerSpoken";
+import { agree, changesOnly, dropMisreads, nearest, type AgreeRule, type Pt } from "./series";
+import {
+ clock,
+ fmtNum,
+ type Derived,
+ type DerivedEvent,
+ type DerivedFlag,
+ type DerivedSegment,
+ type DerivedTournament,
+ type FrameProfile,
+ type SeriesPoint,
+ type SpokenReading,
+} from "./types";
+
+export const POKER_PHASES = ["lobby", "table", "break", "other"] as const;
+export type PokerPhase = (typeof POKER_PHASES)[number];
+export const POKER_FRAME_EVENTS = ["all-in", "bust", "double-up", "final-table", "eliminated", "won"] as const;
+export type PokerFrameEvent = (typeof POKER_FRAME_EVENTS)[number];
+
+export type PokerReading = {
+ phase: PokerPhase;
+ tournament?: {
+ name?: string;
+ level?: number;
+ blinds?: { sb?: number; bb?: number; ante?: number };
+ playersLeft?: number;
+ totalPlayers?: number;
+ prizePool?: number;
+ position?: number;
+ payout?: number;
+ };
+ hero?: { stack?: number; bb?: number; seat?: number; cards?: string[] };
+ hand?: { number?: number; pot?: number; board?: string[]; action?: string };
+ event?: PokerFrameEvent;
+};
+
+// ─── The ask ───
+
+const num = { type: ["number", "null"] } as const;
+const int = { type: ["integer", "null"] } as const;
+const str = { type: ["string", "null"] } as const;
+const cards = { type: ["array", "null"], items: { type: "string" } } as const;
+
+const READING_SCHEMA = {
+ type: "object",
+ properties: {
+ frame: { type: "integer" },
+ phase: { type: "string", enum: [...POKER_PHASES] },
+ tournament: {
+ type: "object",
+ properties: {
+ name: str,
+ level: int,
+ smallBlind: num,
+ bigBlind: num,
+ ante: num,
+ playersLeft: int,
+ totalPlayers: int,
+ prizePool: num,
+ position: int,
+ payout: num,
+ },
+ },
+ hero: {
+ type: "object",
+ properties: { stack: num, stackInBigBlinds: num, seat: int, cards },
+ },
+ hand: {
+ type: "object",
+ properties: { number: int, pot: num, board: cards, action: str },
+ },
+ event: { type: ["string", "null"], enum: [...POKER_FRAME_EVENTS, null] },
+ },
+ required: ["frame", "phase"],
+} as const;
+
+export function pokerSchema(n: number): object {
+ return {
+ type: "object",
+ properties: { frames: { type: "array", items: READING_SCHEMA, minItems: n, maxItems: n } },
+ required: ["frames"],
+ };
+}
+
+// Rules only (Q0): no worked examples, no sample readings.
+export function pokerSystem(hints: { hero?: string } = {}): string {
+ return [
+ "You read screenshots from a livestream of online poker and report what the poker client shows, as data.",
+ "Rules:",
+ "- Report only what is legible in that frame. A field that is not shown, cut off or unreadable is null. Never guess, never carry a value over from another frame, never compute a value the screen does not show.",
+ "- Numbers are plain numbers: chips as whole chips (expand K and M suffixes), money in dollars, no separators.",
+ "- phase: table when a poker table in play is the main picture; lobby for a tournament lobby, a tournament list, a registration or a results screen; break for a break, a paused or a starting-soon screen; other for anything else (a camera, a desktop, a browser, a chat).",
+ `- The hero is the streamer's own player: the seat whose hole cards are shown face up, usually at the bottom of the table.${hints.hero ? ` The hero's screen name is "${hints.hero}".` : ""}`,
+ "- hero.stack is the hero's chip count; hero.stackInBigBlinds only when the client itself shows the stack in big blinds; hero.cards the hero's hole cards.",
+ "- Cards are rank then suit, one character each: ranks 2-9, T, J, Q, K, A; suits s, h, d, c.",
+ "- tournament.name is the tournament's title as the client shows it; level the blind level's number; smallBlind, bigBlind and ante the current blinds; playersLeft and totalPlayers the field (as in a players-left or a rank-of-field display); position the hero's rank in the field when shown; payout the money the hero has won or is guaranteed, when shown; prizePool when shown.",
+ "- hand.pot is the pot in chips; hand.board the community cards; hand.action a few words for the action shown (a bet, a raise, an all-in), or null.",
+ "- event is set only when the screen shows it in words or a banner: all-in, bust or eliminated (the hero is out), double-up, final-table, won (the hero won the tournament). Otherwise null.",
+ "- Frames come in time order, numbered from 1. Answer one reading per frame, in order, each read on its own.",
+ ].join("\n");
+}
+
+export function pokerUser(frames: { t: number }[]): string {
+ return `${frames.length} frame${frames.length === 1 ? "" : "s"}, in order: ${frames.map((f, i) => `frame ${i + 1} at ${clock(f.t)}`).join("; ")}. Read each.`;
+}
+
+// ─── The reading, cleaned ───
+
+const isObj = (v: unknown): v is Record<string, unknown> => !!v && typeof v === "object" && !Array.isArray(v);
+const nonNeg = (v: unknown, max = 1e12): number | undefined =>
+ typeof v === "number" && Number.isFinite(v) && v >= 0 && v <= max ? v : undefined;
+const whole = (v: unknown, max = 1e12): number | undefined => {
+ const n = nonNeg(v, max);
+ return n === undefined ? undefined : Math.round(n);
+};
+const CARD = /^(?:[2-9TJQKA])[shdc]$/;
+function cardList(v: unknown, max: number): string[] | undefined {
+ if (!Array.isArray(v)) return undefined;
+ const out = v
+ .filter((c): c is string => typeof c === "string")
+ .map((c) => c.trim().replace(/^10/, "T"))
+ .map((c) => (c.length === 2 ? c[0].toUpperCase() + c[1].toLowerCase() : c))
+ .filter((c) => CARD.test(c));
+ return out.length && out.length <= max && new Set(out).size === out.length ? out : undefined;
+}
+const prune = <T extends Record<string, unknown>>(o: T): T | undefined => {
+ for (const k of Object.keys(o)) if (o[k] === undefined) delete o[k];
+ return Object.keys(o).length ? o : undefined;
+};
+
+/** A model's reading as a PokerReading, every field checked; null when it is not a reading. */
+export function coercePokerReading(raw: unknown): PokerReading | null {
+ if (!isObj(raw)) return null;
+ const phase = typeof raw.phase === "string" && (POKER_PHASES as readonly string[]).includes(raw.phase) ? (raw.phase as PokerPhase) : null;
+ if (!phase) return null;
+ const out: PokerReading = { phase };
+ const t = isObj(raw.tournament) ? raw.tournament : null;
+ if (t) {
+ const blinds = prune({ sb: nonNeg(t.smallBlind), bb: nonNeg(t.bigBlind), ante: nonNeg(t.ante) });
+ // A big blind under the small one is a misread pair: neither is kept.
+ const okBlinds = blinds && !(blinds.sb !== undefined && blinds.bb !== undefined && blinds.bb < blinds.sb) ? blinds : undefined;
+ const name = typeof t.name === "string" ? t.name.replace(/\s+/g, " ").trim().slice(0, 120) : "";
+ const tour = prune({
+ name: name || undefined,
+ level: whole(t.level, 500),
+ blinds: okBlinds,
+ playersLeft: whole(t.playersLeft, 10_000_000),
+ totalPlayers: whole(t.totalPlayers, 10_000_000),
+ prizePool: nonNeg(t.prizePool),
+ position: whole(t.position, 10_000_000),
+ payout: nonNeg(t.payout),
+ });
+ // Players left over the field is a misread pair: the field is dropped.
+ if (tour && tour.playersLeft !== undefined && tour.totalPlayers !== undefined && tour.playersLeft > tour.totalPlayers) delete tour.totalPlayers;
+ if (tour) out.tournament = tour;
+ }
+ const h = isObj(raw.hero) ? raw.hero : null;
+ if (h) {
+ const hero = prune({ stack: whole(h.stack), bb: nonNeg(h.stackInBigBlinds ?? h.bb, 1_000_000), seat: whole(h.seat, 12), cards: cardList(h.cards, 6) });
+ if (hero) out.hero = hero;
+ }
+ const hd = isObj(raw.hand) ? raw.hand : null;
+ if (hd) {
+ const action = typeof hd.action === "string" ? hd.action.replace(/\s+/g, " ").trim().slice(0, 80) : "";
+ const hand = prune({ number: whole(hd.number), pot: whole(hd.pot), board: cardList(hd.board, 5), action: action || undefined });
+ if (hand) out.hand = hand;
+ }
+ if (typeof raw.event === "string" && (POKER_FRAME_EVENTS as readonly string[]).includes(raw.event)) out.event = raw.event as PokerFrameEvent;
+ return out;
+}
+
+// ─── Derivation (pure) ───
+
+type R = PokerReading & { t: number };
+
+// How two readings of a field must agree to call a third a misread, and a
+// spoken number a frame's.
+const MISREAD: Record<string, AgreeRule> = {
+ stack: { ratio: 3 },
+ stackBB: { ratio: 3 },
+ playersLeft: { ratio: 1.5, absolute: 3 },
+ level: { ratio: 1.5, absolute: 1 },
+};
+const SPOKEN_AGREE: Record<string, AgreeRule> = {
+ stack: { ratio: 1.3 },
+ stackBB: { ratio: 1.3, absolute: 2 },
+ playersLeft: { ratio: 1.15, absolute: 2 },
+ level: { ratio: 1, absolute: 1 },
+};
+// Spoken fields that are series; the rest are facts.
+const SPOKEN_SERIES = new Set(["stack", "stackBB", "playersLeft", "level"]);
+const SPOKEN_WINDOW_S = 90;
+const FINAL_TABLE = 9;
+
+const normName = (s: string) => s.toLowerCase().replace(/[^a-z0-9$]+/g, " ").trim();
+
+// Which tournament each reading belongs to. A name read on screen keys it;
+// readings with none take the name before them (or, before any, the first
+// one). Within a name, the field changing size by more than half is another
+// tournament of the same name (a re-run, a satellite).
+function keyReadings(rs: readonly R[]): { keys: (string | null)[]; names: Map<string, string> } {
+ const names = new Map<string, string>();
+ const first = rs.find((r) => r.tournament?.name)?.tournament?.name;
+ let current = first ? normName(first) : null;
+ let currentName = first ?? null;
+ const field = new Map<string, number>();
+ const generation = new Map<string, number>();
+ const keys: (string | null)[] = [];
+ for (const r of rs) {
+ const named = r.tournament?.name;
+ if (named) {
+ current = normName(named);
+ currentName = named;
+ }
+ if (r.phase !== "table" && r.phase !== "lobby") {
+ keys.push(null);
+ continue;
+ }
+ const base = current ?? "tournament";
+ const total = r.tournament?.totalPlayers;
+ if (total !== undefined) {
+ const was = field.get(base);
+ if (was !== undefined && !agree(was, total, { ratio: 1.5 })) generation.set(base, (generation.get(base) ?? 1) + 1);
+ field.set(base, total);
+ }
+ const g = generation.get(base) ?? 1;
+ const key = g > 1 ? `${base}#${g}` : base;
+ if (currentName && !names.has(key)) names.set(key, currentName);
+ keys.push(key);
+ }
+ return { keys, names };
+}
+
+const FIELDS: { field: string; of: (r: R) => number | undefined }[] = [
+ { field: "stack", of: (r) => r.hero?.stack },
+ {
+ field: "stackBB",
+ // Shown by the client, else the stack over the big blind on the same frame.
+ of: (r) => {
+ if (r.hero?.bb !== undefined) return r.hero.bb;
+ const s = r.hero?.stack;
+ const bb = r.tournament?.blinds?.bb;
+ return s !== undefined && bb ? Math.round((s / bb) * 10) / 10 : undefined;
+ },
+ },
+ { field: "playersLeft", of: (r) => r.tournament?.playersLeft },
+ { field: "level", of: (r) => r.tournament?.level },
+];
+
+const pts = (s: readonly SeriesPoint[]): Pt[] => s.map(([t, v]) => ({ t, v }));
+
+/**
+ * Readings (and spoken numbers) to tournaments with series, events, phase
+ * segments and flags. Pure; heavily tested (poker.test.ts).
+ */
+export function derivePoker(readingsIn: readonly R[], spoken: readonly SpokenReading[], o: { everySeconds: number; durationSeconds?: number }): Derived {
+ const rs = [...readingsIn].sort((a, b) => a.t - b.t);
+ const segments = phaseSegments(rs, o);
+ const { keys, names } = keyReadings(rs);
+ const misreads: Derived["misreads"] = [];
+ const byKey = new Map<string, R[]>();
+ rs.forEach((r, i) => {
+ const k = keys[i];
+ if (!k) return;
+ if (!byKey.has(k)) byKey.set(k, []);
+ byKey.get(k)!.push(r);
+ });
+
+ const tournaments: DerivedTournament[] = [];
+ // Every kept point per tournament and field (not collapsed to changes): the
+ // events judge a change by the reading after it.
+ const full = new Map<string, Record<string, Pt[]>>();
+ for (const [key, list] of byKey) {
+ const series: Record<string, SeriesPoint[]> = {};
+ const points: Record<string, Pt[]> = {};
+ for (const f of FIELDS) {
+ const raw: Pt[] = [];
+ for (const r of list) {
+ const v = f.of(r);
+ if (v !== undefined) raw.push({ t: r.t, v });
+ }
+ const { kept, dropped } = dropMisreads(raw, MISREAD[f.field]);
+ for (const d of dropped) misreads.push({ t: d.t, field: f.field, value: d.v });
+ points[f.field] = kept;
+ series[f.field] = changesOnly(kept).map((p) => [p.t, p.v] as SeriesPoint);
+ }
+ full.set(key, points);
+ const facts: Record<string, number> = {};
+ for (const r of list) {
+ const t = r.tournament;
+ if (t?.totalPlayers !== undefined) facts.totalPlayers = t.totalPlayers;
+ if (t?.prizePool !== undefined) facts.prizePool = t.prizePool;
+ if (t?.payout !== undefined) facts.payout = t.payout;
+ if (t?.position !== undefined) facts.position = t.position;
+ }
+ const tour: DerivedTournament = { key, from: list[0].t, to: list[list.length - 1].t + o.everySeconds, series, facts };
+ const name = names.get(key);
+ if (name) tour.name = name;
+ tournaments.push(tour);
+ }
+ tournaments.sort((a, b) => a.from - b.from);
+
+ const flags = crossCheck(tournaments, spoken);
+ // Segments say which tournament they are in, when one covers them.
+ for (const s of segments) {
+ const tour = tournaments.find((t) => s.from >= t.from && s.from < t.to);
+ if (tour && (s.phase === "table" || s.phase === "lobby")) s.tournament = tour.key;
+ }
+ const events = [...frameEvents(rs, keys), ...seriesEvents(tournaments, full), ...spokenEvents(spoken)].sort((a, b) => a.t - b.t || a.kind.localeCompare(b.kind));
+ return { tournaments, events, segments, flags, misreads: misreads.sort((a, b) => a.t - b.t) };
+}
+
+// Phase segments: a phase seen on ONE frame between two frames of another
+// (the same both sides) is that other phase — a transition frame, a misread.
+function phaseSegments(rs: readonly R[], o: { everySeconds: number; durationSeconds?: number }): DerivedSegment[] {
+ const phases = rs.map((r) => r.phase as string);
+ for (let i = 1; i < phases.length - 1; i++) if (phases[i - 1] === phases[i + 1] && phases[i] !== phases[i - 1]) phases[i] = phases[i - 1];
+ const out: DerivedSegment[] = [];
+ rs.forEach((r, i) => {
+ const last = out[out.length - 1];
+ if (last && last.phase === phases[i]) return;
+ if (last) last.to = r.t;
+ out.push({ from: r.t, to: r.t, phase: phases[i] });
+ });
+ if (out.length) {
+ const end = rs[rs.length - 1].t + o.everySeconds;
+ out[out.length - 1].to = o.durationSeconds !== undefined ? Math.min(o.durationSeconds, end) : end;
+ }
+ return out;
+}
+
+// The model's own events (a banner on screen), one per run: the same kind
+// again within a minute is the same moment.
+function frameEvents(rs: readonly R[], keys: readonly (string | null)[]): DerivedEvent[] {
+ const out: DerivedEvent[] = [];
+ rs.forEach((r, i) => {
+ if (!r.event) return;
+ const prev = out.filter((e) => e.kind === r.event).pop();
+ if (prev && r.t - prev.t <= 60) return;
+ const e: DerivedEvent = { t: r.t, kind: r.event, detail: `shown on screen at ${clock(r.t)}`, source: "frame" };
+ if (keys[i]) e.tournament = keys[i]!;
+ out.push(e);
+ });
+ return out;
+}
+
+// Events the series show: a double-up (×1.8 or more, held by the next point —
+// a change at a tournament's last point is not judged), a big loss (half or
+// more gone, held), a bust (the stack at 0 and no later
+// chips in that tournament), the final table (players left first ≤ 9 in a
+// field that was larger), a win (one player left, the hero with chips).
+function seriesEvents(tournaments: readonly DerivedTournament[], full: ReadonlyMap<string, Record<string, Pt[]>>): DerivedEvent[] {
+ const out: DerivedEvent[] = [];
+ for (const tour of tournaments) {
+ // Frame points only (a spoken number fills a gap, it does not make an
+ // event), every one of them: a change is judged by the reading after it.
+ const stack = full.get(tour.key)?.stack ?? [];
+ for (let i = 1; i < stack.length; i++) {
+ const a = stack[i - 1];
+ const b = stack[i];
+ if (a.v === b.v) continue;
+ const after = stack[i + 1];
+ // Held: the point after agrees, so one late misread cannot make an event.
+ if (!after) continue;
+ if (a.v > 0 && b.v / a.v >= 1.8 && after.v / a.v >= 1.6) {
+ out.push({ t: b.t, kind: "double-up", detail: `${fmtNum(a.v)} → ${fmtNum(b.v)} chips (${(b.v / a.v).toFixed(1)}×)`, source: "series", tournament: tour.key });
+ } else if (a.v > 0 && b.v > 0 && b.v / a.v <= 0.5 && after.v / a.v <= 0.6) {
+ out.push({ t: b.t, kind: "big-loss", detail: `${fmtNum(a.v)} → ${fmtNum(b.v)} chips`, source: "series", tournament: tour.key });
+ }
+ }
+ const zero = stack.findIndex((p) => p.v === 0);
+ if (zero >= 0 && !stack.slice(zero + 1).some((p) => p.v > 0)) {
+ const before = stack[zero - 1];
+ out.push({ t: stack[zero].t, kind: "bust", detail: before ? `out from ${fmtNum(before.v)} chips` : "out", source: "series", tournament: tour.key });
+ }
+ const left = full.get(tour.key)?.playersLeft ?? [];
+ const larger = (tour.facts.totalPlayers ?? 0) > FINAL_TABLE || left.some((p) => p.v > FINAL_TABLE);
+ const ft = left.find((p) => p.v <= FINAL_TABLE && p.v > 1);
+ if (larger && ft) out.push({ t: ft.t, kind: "final-table", detail: `${ft.v} players left`, source: "series", tournament: tour.key });
+ const one = left.find((p) => p.v === 1);
+ const lastStack = stack[stack.length - 1];
+ if (one && lastStack && lastStack.v > 0 && lastStack.t >= one.t - 120) out.push({ t: one.t, kind: "won", detail: "one player left", source: "series", tournament: tour.key });
+ }
+ return out;
+}
+
+// What the streamer said that is an event in itself: none of the numbers is,
+// but a buy-in or a prize said marks the start of talk about a tournament.
+function spokenEvents(spoken: readonly SpokenReading[]): DerivedEvent[] {
+ return spoken
+ .filter((s) => s.field === "buyIn")
+ .map((s) => ({ t: s.t, kind: "buy-in", detail: `$${fmtNum(s.value)} buy-in said: "${s.text}"`, source: "spoken" as const }));
+}
+
+// A spoken number beside a frame reading of the same field: agree, or a flag.
+// With no frame reading within the window, it fills the series of the
+// tournament the moment is in (marked "spoken"). Facts (buy-in, prize, field)
+// go to the tournament's facts when a frame did not read them.
+function crossCheck(tournaments: DerivedTournament[], spoken: readonly SpokenReading[]): DerivedFlag[] {
+ const flags: DerivedFlag[] = [];
+ const at = (t: number) => tournaments.find((x) => t >= x.from - SPOKEN_WINDOW_S && t <= x.to + SPOKEN_WINDOW_S) ?? null;
+ const fills: { tour: DerivedTournament; field: string; t: number; v: number }[] = [];
+ for (const s of spoken) {
+ const tour = at(s.t);
+ if (!SPOKEN_SERIES.has(s.field)) {
+ if (tour && tour.facts[s.field] === undefined) tour.facts[s.field] = s.value;
+ continue;
+ }
+ if (!tour) continue;
+ const frame = nearest(pts((tour.series[s.field] ?? []).filter((p) => p.length === 2)), s.t, SPOKEN_WINDOW_S);
+ if (frame) {
+ if (!agree(s.value, frame.v, SPOKEN_AGREE[s.field])) flags.push({ t: s.t, field: s.field, spoken: s.value, frame: frame.v, frameT: frame.t, tournament: tour.key });
+ } else fills.push({ tour, field: s.field, t: s.t, v: s.value });
+ }
+ for (const f of fills) {
+ const list = (f.tour.series[f.field] ??= []);
+ list.push([f.t, f.v, "spoken"]);
+ list.sort((a, b) => a[0] - b[0]);
+ }
+ return flags;
+}
+
+export const POKER_PROFILE: FrameProfile<PokerReading> = {
+ id: "poker",
+ promptVersion: 1,
+ // Wide enough for a client's small numbers on a 1080p stream.
+ width: 1280,
+ dupMaxBits: 2,
+ rereadEvery: 6,
+ framesPerAsk: { api: 4, local: 1 },
+ system: pokerSystem,
+ user: pokerUser,
+ schema: pokerSchema,
+ coerce: coercePokerReading,
+ spoken: pokerSpoken,
+ derive: derivePoker,
+};
diff --git a/common/lib/frames/pokerSpoken.test.ts b/common/lib/frames/pokerSpoken.test.ts
@@ -0,0 +1,68 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { pokerSpoken } from "./pokerSpoken";
+
+const cue = (start: number, text: string) => ({ start, end: start + 3, text });
+const pick = (rs: ReturnType<typeof pokerSpoken>, field: string) => rs.filter((r) => r.field === field).map((r) => [r.t, r.value]);
+
+test("players left, said in words, dated by its cue", () => {
+ const rs = pokerSpoken([cue(339, "okay eighty five players left"), cue(3218, "we are down to fifteen players left now")]);
+ assert.deepEqual(pick(rs, "playersLeft"), [[339, 85], [3218, 15]]);
+});
+
+test("a phrase split across two cues still reads, dated by its first cue", () => {
+ const rs = pokerSpoken([cue(10, "we have eighty five"), cue(13, "players left in this one")]);
+ assert.deepEqual(pick(rs, "playersLeft"), [[10, 85]]);
+});
+
+test("a buy-in, in dollars or words", () => {
+ const rs = pokerSpoken([cue(3326, "this is the $2,750 buy in"), cue(5000, "the buy in is six bucks for the viewers")]);
+ assert.deepEqual(pick(rs, "buyIn"), [[3326, 2750], [5000, 6]]);
+});
+
+test("a stack said without 'thousand' beside an average said with it is scaled, and marked approx", () => {
+ const rs = pokerSpoken([cue(6557, "the average stack is three hundred seventy three thousand"), cue(6560, "I have two hundred thirty three")]);
+ assert.deepEqual(pick(rs, "averageStack"), [[6557, 373000]]);
+ const stack = rs.filter((r) => r.field === "stack");
+ assert.deepEqual(stack.map((r) => [r.t, r.value, r.approx]), [[6560, 233000, true]]);
+});
+
+test("a small stack with no average near it is left out, as is a count of something else", () => {
+ const rs = pokerSpoken([cue(10, "I have two hundred thirty three"), cue(20, "I have 2 kings"), cue(30, "I have 500 bucks on this")]);
+ assert.deepEqual(pick(rs, "stack"), []);
+});
+
+test("an opponent's chips are not the hero's", () => {
+ const rs = pokerSpoken([cue(5350, "he's at five hundred sixty seven thousand chips")]);
+ assert.deepEqual(pick(rs, "stack"), []);
+});
+
+test("stack in big blinds, blinds, level, first prize", () => {
+ const rs = pokerSpoken([
+ cue(100, "I'm down to six big blinds"),
+ cue(200, "blinds are fifteen hundred three thousand"),
+ cue(300, "level fourteen"),
+ cue(400, "first place five hundred bucks"),
+ ]);
+ assert.deepEqual(pick(rs, "stackBB"), [[100, 6]]);
+ assert.deepEqual(pick(rs, "bigBlind"), [[200, 3000]]);
+ assert.deepEqual(pick(rs, "smallBlind"), [[200, 1500]]);
+ assert.deepEqual(pick(rs, "level"), [[300, 14]]);
+ assert.deepEqual(pick(rs, "firstPrize"), [[400, 500]]);
+});
+
+test("two numbers beside 'blinds' that are not a blind pair are not read as one", () => {
+ const rs = pokerSpoken([cue(10, "blinds are 5 50")]);
+ assert.deepEqual(pick(rs, "bigBlind"), []);
+});
+
+test("the same number said again within 30 s is one reading", () => {
+ const rs = pokerSpoken([cue(10, "eighty five players left"), cue(20, "yeah eighty five players left"), cue(100, "eighty five players left")]);
+ assert.deepEqual(pick(rs, "playersLeft"), [[10, 85], [100, 85]]);
+});
+
+test("no cues, no readings; the text is kept for a reader", () => {
+ assert.deepEqual(pokerSpoken([]), []);
+ const [r] = pokerSpoken([cue(1, "eighty five players left")]);
+ assert.equal(r.text, "eighty five players left");
+});
diff --git a/common/lib/frames/pokerSpoken.ts b/common/lib/frames/pokerSpoken.ts
@@ -0,0 +1,135 @@
+// The poker stats a streamer SAYS, read out of the cues by pure code
+// (release 30, lane P): the frame scan's second, cheap signal. A frame reading
+// that disagrees with a nearby spoken number is flagged, and a gap the frames
+// leave is filled from it (poker.ts `derive`).
+//
+// The cues are joined into one text so a phrase split across two cues ("eighty
+// five" | "players left") still reads, every number is normalized to digits
+// (numberWords.ts), and plain patterns read the fields. A match is dated by the
+// cue its first character came from. Rule-based: what the patterns do not
+// cover is not read, never guessed.
+
+import { normalizeNumbers } from "./numberWords";
+import type { Cue, SpokenReading } from "./types";
+
+type Piece = { at: number; t: number; cue: number };
+
+// The joined, normalized text and where each cue's part of it starts.
+function joined(cues: readonly Cue[]): { text: string; pieces: Piece[] } {
+ const pieces: Piece[] = [];
+ let text = "";
+ cues.forEach((c, i) => {
+ pieces.push({ at: text.length, t: c.start, cue: i });
+ text += `${normalizeNumbers(String(c.text ?? "")).replace(/\s+/g, " ").trim()} `;
+ });
+ return { text: text.toLowerCase(), pieces };
+}
+
+function pieceAt(pieces: readonly Piece[], at: number): Piece {
+ let lo = 0;
+ let hi = pieces.length - 1;
+ while (lo < hi) {
+ const mid = (lo + hi + 1) >> 1;
+ if (pieces[mid].at <= at) lo = mid;
+ else hi = mid - 1;
+ }
+ return pieces[lo];
+}
+
+const N = String.raw`(\d+(?:\.\d+)?)`;
+const SOFT = String.raw`(?:about |around |like |only |just |roughly |almost |nearly |over |under )?`;
+
+// One field's patterns: the first capture group is the value.
+type Rule = { field: string; re: RegExp; min?: number; max?: number; scale?: (v: number, m: RegExpExecArray) => number };
+
+const RULES: Rule[] = [
+ { field: "playersLeft", re: new RegExp(String.raw`\b${N} (?:players|people|runners|entrants|left in the field|of us)(?: are)? (?:left|remaining)\b`, "g"), min: 1, max: 1_000_000 },
+ { field: "playersLeft", re: new RegExp(String.raw`\b(?:down to|we're at|we are at|there are|there's) ${SOFT}${N} (?:players )?(?:left|remaining)\b`, "g"), min: 1, max: 1_000_000 },
+ { field: "totalPlayers", re: new RegExp(String.raw`\b${N} (?:entrants|entries|runners|players registered|players total|total players)\b`, "g"), min: 2, max: 1_000_000 },
+ { field: "averageStack", re: new RegExp(String.raw`\baverage(?: stack| chip stack)?(?: is| was| of|'s)? ${SOFT}${N}\b`, "g"), min: 100 },
+ // The hero's stack in big blinds: "I'm down to 6 big blinds", "I have 22 bigs".
+ { field: "stackBB", re: new RegExp(String.raw`\b(?:i have|i've got|i got|i'm at|i am at|i'm down to|i am down to|i'm sitting on|i'm sitting at|i'm on|my stack is) ${SOFT}${N} (?:big blinds|bigs|bbs|bb)\b`, "g"), min: 0, max: 100_000 },
+ // The hero's chips: "I have 233" (said without "thousand" beside an average
+ // said with it: scaled below), "I've got 1500000 chips".
+ { field: "stack", re: new RegExp(String.raw`\b(?:i have|i've got|i got|i'm at|i am at|i'm sitting on|i'm sitting at|my stack is|i'm up to|i'm down to) ${SOFT}${N}(?! (?:big blinds|bigs|bbs|bb|players|people|minutes|seconds|hours|dollars|bucks|percent|hands|cards|outs|times|kings|queens|jacks|aces|tens|nines|eights|sevens|sixes|fives|fours|threes|twos|of)\b)`, "g"), min: 100 },
+ { field: "buyIn", re: new RegExp(String.raw`\$?${N} (?:dollar |buck )?buy[- ]?in\b`, "g"), min: 0.01 },
+ { field: "buyIn", re: new RegExp(String.raw`\bbuy[- ]?in (?:is|was|of|for) \$?${N}\b`, "g"), min: 0.01 },
+ { field: "firstPrize", re: new RegExp(String.raw`\bfirst place (?:is |gets |pays |is worth |wins )?\$?${N}\b`, "g"), min: 1 },
+ { field: "prizePool", re: new RegExp(String.raw`\b(?:prize pool|guarantee|guaranteed)(?: is| of)? \$?${N}\b`, "g"), min: 1 },
+ { field: "level", re: new RegExp(String.raw`\blevel ${N}\b`, "g"), min: 1, max: 200 },
+];
+
+// "blinds are 1500 3000", "blinds 5 10", "1500 3000 blinds": both blinds.
+const BLINDS = [
+ new RegExp(String.raw`\bblinds (?:are |at |now |of |going up to |are going up to |up to )?${N}(?: ?/ ?| and | to | )${N}\b`, "g"),
+ new RegExp(String.raw`\b${N}(?: ?/ ?| )${N} blinds\b`, "g"),
+];
+
+/** Every spoken poker stat in the cues, in time order. */
+export function pokerSpoken(cues: readonly Cue[]): SpokenReading[] {
+ if (!cues.length) return [];
+ const { text, pieces } = joined(cues);
+ const out: SpokenReading[] = [];
+ const at = (index: number) => pieceAt(pieces, index);
+ const words = (p: Piece) => String(cues[p.cue].text ?? "").replace(/\s+/g, " ").trim().slice(0, 160);
+ for (const rule of RULES) {
+ rule.re.lastIndex = 0;
+ let m: RegExpExecArray | null;
+ while ((m = rule.re.exec(text))) {
+ const v = Number(m[1]);
+ if (!Number.isFinite(v)) continue;
+ if (rule.min !== undefined && v < rule.min) continue;
+ if (rule.max !== undefined && v > rule.max) continue;
+ const p = at(m.index);
+ out.push({ t: p.t, field: rule.field, value: v, text: words(p) });
+ }
+ }
+ for (const re of BLINDS) {
+ re.lastIndex = 0;
+ let m: RegExpExecArray | null;
+ while ((m = re.exec(text))) {
+ const sb = Number(m[1]);
+ const bb = Number(m[2]);
+ // A big blind is the small one's double (or so): anything else is two
+ // numbers that happen to sit beside "blinds".
+ if (!(sb > 0 && bb > sb && bb <= sb * 3)) continue;
+ const p = at(m.index);
+ out.push({ t: p.t, field: "bigBlind", value: bb, text: words(p) });
+ out.push({ t: p.t, field: "smallBlind", value: sb, text: words(p) });
+ }
+ }
+ out.sort((a, b) => a.t - b.t || a.field.localeCompare(b.field));
+ return scaleStacks(dedupe(out));
+}
+
+// The same field and value said again within 30 s is one reading.
+function dedupe(rs: SpokenReading[]): SpokenReading[] {
+ const out: SpokenReading[] = [];
+ for (const r of rs) {
+ if (out.some((o) => o.field === r.field && o.value === r.value && Math.abs(o.t - r.t) <= 30)) continue;
+ out.push(r);
+ }
+ return out;
+}
+
+// "the average stack is three hundred seventy three thousand… I have two
+// hundred thirty three": a stack said under 1000 within two minutes of an
+// average said in the thousands, and within 50× of it once scaled, is
+// thousands too (marked `approx`). One still under 1000 with no such average
+// is left out: a tournament stack is rarely that small, and the number is
+// more likely something else.
+function scaleStacks(rs: SpokenReading[]): SpokenReading[] {
+ const out: SpokenReading[] = [];
+ for (const r of rs) {
+ if (r.field !== "stack" || r.value >= 1000) {
+ out.push(r);
+ continue;
+ }
+ const avg = rs
+ .filter((o) => o.field === "averageStack" && o.value >= 10_000 && Math.abs(o.t - r.t) <= 120)
+ .sort((a, b) => Math.abs(a.t - r.t) - Math.abs(b.t - r.t))[0];
+ const scaled = r.value * 1000;
+ if (avg && scaled >= avg.value / 50 && scaled <= avg.value * 50) out.push({ ...r, value: scaled, approx: true });
+ }
+ return out;
+}
diff --git a/common/lib/frames/profiles.ts b/common/lib/frames/profiles.ts
@@ -0,0 +1,21 @@
+// The frame scan's profiles (release 30, lane P): what a frame is read for.
+// Poker is the first; a profile is one entry here.
+
+import { POKER_PROFILE } from "./poker";
+import type { FrameProfile } from "./types";
+
+export const FRAME_PROFILES: Readonly<Record<string, FrameProfile<{ phase: string }>>> = {
+ poker: POKER_PROFILE as unknown as FrameProfile<{ phase: string }>,
+};
+
+export const FRAME_PROFILE_IDS = Object.keys(FRAME_PROFILES);
+
+export function isFrameProfile(v: unknown): v is string {
+ return typeof v === "string" && Object.prototype.hasOwnProperty.call(FRAME_PROFILES, v);
+}
+
+export function frameProfile(id: string): FrameProfile<{ phase: string }> {
+ const p = FRAME_PROFILES[id];
+ if (!p) throw new Error(`"${id}" is not a frame-scan profile (${FRAME_PROFILE_IDS.join(", ")})`);
+ return p;
+}
diff --git a/common/lib/frames/sample-server.ts b/common/lib/frames/sample-server.ts
@@ -0,0 +1,211 @@
+// Sampling a saved video into frames (release 30, lane P): ONE ffmpeg per
+// batch of the stream (half an hour by default), never one process per frame.
+// Each batch writes its frames as JPEGs scaled to the profile's width and, on
+// the same decode, a tiny grey thumbnail per frame on stdout for the dHash.
+//
+// By default only the KEYFRAMES are decoded (`-skip_frame nokey`): a 4-hour
+// 1080p stream decodes in a minute or two instead of half an hour, and a
+// frame's picture is then the keyframe nearest its grid time — at most a
+// keyframe interval away (two seconds or so on a stream). `t` is always the
+// grid time in SOURCE seconds, so clips cut from it line up within that.
+//
+// The cache is a directory of JPEGs plus `index.json` (the grid, the width and
+// each frame's hash). A re-run reuses every frame the index already has on the
+// same grid and width. Server-only (node:child_process, node:fs).
+
+import { spawn } from "node:child_process";
+import { mkdir, readdir, readFile, rename, rm, stat } from "node:fs/promises";
+import path from "node:path";
+import { writeJsonAtomic } from "../jsonFile-server";
+import { hashesOf, THUMB_H, THUMB_W } from "./dhash";
+import type { FrameRef } from "./types";
+
+export const FRAME_INDEX_FILE = "index.json";
+export const DEFAULT_BATCH_SECONDS = 1800;
+
+export type FrameIndex = {
+ everySeconds: number;
+ width: number;
+ keyframesOnly: boolean;
+ frames: FrameRef[];
+};
+
+/** A grid time as the frame's file name: `t000012340.jpg` (centiseconds). */
+export const frameFileOf = (t: number) => `t${String(Math.round(t * 100)).padStart(9, "0")}.jpg`;
+
+/** The grid: from, from+N, … below `to`, rounded to the centisecond. */
+export function gridOf(from: number, to: number, every: number): number[] {
+ const out: number[] = [];
+ if (!(every > 0) || !(to > from)) return out;
+ for (let k = 0; ; k++) {
+ const t = Math.round((from + k * every) * 100) / 100;
+ if (t >= to) break;
+ out.push(t);
+ }
+ return out;
+}
+
+/** The batches a grid is sampled in: [from, to) windows of at most `seconds`, on grid points. */
+export function batchesOf(grid: readonly number[], every: number, seconds = DEFAULT_BATCH_SECONDS): number[][] {
+ const per = Math.max(1, Math.floor(seconds / every));
+ const out: number[][] = [];
+ for (let i = 0; i < grid.length; i += per) out.push(grid.slice(i, i + per));
+ return out;
+}
+
+export async function readFrameIndex(dir: string): Promise<FrameIndex | null> {
+ try {
+ const v = JSON.parse(await readFile(path.join(dir, FRAME_INDEX_FILE), "utf8")) as FrameIndex;
+ return v && Array.isArray(v.frames) && typeof v.everySeconds === "number" && typeof v.width === "number" ? v : null;
+ } catch {
+ return null;
+ }
+}
+
+export async function probeDuration(file: string, ffprobe = "ffprobe"): Promise<number | null> {
+ const out = await runCapture(ffprobe, ["-v", "error", "-show_entries", "format=duration", "-of", "default=nw=1:nk=1", file]).catch(() => null);
+ const d = out ? Number(out.stdout.toString("utf8").trim()) : NaN;
+ return Number.isFinite(d) && d > 0 ? d : null;
+}
+
+function runCapture(cmd: string, args: string[], signal?: AbortSignal): Promise<{ stdout: Buffer; stderr: string }> {
+ return new Promise((resolve, reject) => {
+ const p = spawn(cmd, args, { stdio: ["ignore", "pipe", "pipe"], signal });
+ const out: Buffer[] = [];
+ let err = "";
+ p.stdout.on("data", (c: Buffer) => out.push(c));
+ p.stderr.on("data", (c: Buffer) => {
+ err += c.toString("utf8");
+ if (err.length > 20_000) err = err.slice(-10_000);
+ });
+ p.on("error", reject);
+ p.on("close", (code) => {
+ if (code === 0) resolve({ stdout: Buffer.concat(out), stderr: err });
+ else reject(new Error(`${cmd} exited ${code}: ${err.trim().split("\n").slice(-3).join(" | ")}`));
+ });
+ });
+}
+
+/** The ffmpeg arguments for one batch (exported for the test). */
+export function batchArgs(o: { source: string; start: number; seconds: number; every: number; width: number; outPattern: string; keyframesOnly: boolean }): string[] {
+ return [
+ "-hide_banner",
+ "-loglevel",
+ "error",
+ "-nostdin",
+ ...(o.keyframesOnly ? ["-skip_frame", "nokey"] : []),
+ "-ss",
+ String(o.start),
+ "-t",
+ String(o.seconds),
+ "-i",
+ o.source,
+ "-filter_complex",
+ `[0:v]fps=1/${o.every}:round=near,split=2[a][b];[a]scale=${o.width}:-2:flags=area[big];[b]scale=${THUMB_W}:${THUMB_H}:flags=area,format=gray[small]`,
+ "-map",
+ "[big]",
+ "-q:v",
+ "3",
+ "-start_number",
+ "0",
+ o.outPattern,
+ "-map",
+ "[small]",
+ "-f",
+ "rawvideo",
+ "pipe:1",
+ ];
+}
+
+/**
+ * Sample `[from, to)` of `source` every `every` seconds into `dir`. Frames the
+ * index already has (same grid step, width and decode mode) are kept and not
+ * decoded again; a batch with any frame missing is decoded whole. Answers the
+ * index, every frame of the range in order.
+ */
+export async function sampleFrames(o: {
+ source: string;
+ dir: string;
+ from: number;
+ to: number;
+ every: number;
+ width: number;
+ keyframesOnly?: boolean;
+ batchSeconds?: number;
+ ffmpeg?: string;
+ signal?: AbortSignal;
+ onLog?: (line: string) => void;
+ onBatch?: (done: number, total: number) => void;
+}): Promise<FrameIndex> {
+ const keyframesOnly = o.keyframesOnly ?? true;
+ await mkdir(o.dir, { recursive: true });
+ const prev = await readFrameIndex(o.dir);
+ const same = prev && prev.everySeconds === o.every && prev.width === o.width && prev.keyframesOnly === keyframesOnly;
+ const have = new Map<number, FrameRef>();
+ if (same) {
+ const files = new Set(await readdir(o.dir).catch(() => [] as string[]));
+ for (const f of prev!.frames) if (files.has(f.file)) have.set(f.t, f);
+ }
+ const grid = gridOf(o.from, o.to, o.every);
+ const batches = batchesOf(grid, o.every, o.batchSeconds);
+ const index: FrameIndex = { everySeconds: o.every, width: o.width, keyframesOnly, frames: [] };
+ // Frames outside this run's range stay in the index.
+ const keepOutside = same ? prev!.frames.filter((f) => (f.t < o.from || f.t >= o.to) && have.has(f.t)) : [];
+ let done = 0;
+ for (const batch of batches) {
+ if (o.signal?.aborted) throw new Error("cancelled");
+ if (batch.every((t) => have.has(t))) {
+ for (const t of batch) index.frames.push(have.get(t)!);
+ o.onBatch?.(++done, batches.length);
+ continue;
+ }
+ const start = batch[0];
+ const seconds = Math.round((batch[batch.length - 1] - start + o.every) * 100) / 100;
+ const tmp = path.join(o.dir, `.batch-${process.pid}-${Math.round(start * 100)}`);
+ await rm(tmp, { recursive: true, force: true });
+ await mkdir(tmp, { recursive: true });
+ try {
+ const { stdout } = await runCapture(
+ o.ffmpeg ?? "ffmpeg",
+ batchArgs({ source: o.source, start, seconds, every: o.every, width: o.width, outPattern: path.join(tmp, "%06d.jpg"), keyframesOnly }),
+ o.signal,
+ );
+ const hashes = hashesOf(stdout);
+ const written = (await readdir(tmp)).filter((f) => /^\d{6}\.jpg$/.test(f)).sort();
+ const n = Math.min(batch.length, hashes.length, written.length);
+ for (let k = 0; k < n; k++) {
+ const t = batch[k];
+ const file = frameFileOf(t);
+ await rename(path.join(tmp, written[k]), path.join(o.dir, file));
+ index.frames.push({ t, file, hash: hashes[k] });
+ }
+ if (n < batch.length) o.onLog?.(`frames ${batch[0]}–${batch[batch.length - 1]} s: ${n} of ${batch.length} decoded (the stream ends or has no picture there)`);
+ } finally {
+ await rm(tmp, { recursive: true, force: true });
+ }
+ o.onBatch?.(++done, batches.length);
+ // The index after every batch: a cut run keeps what it decoded.
+ await writeIndex(o.dir, index, keepOutside);
+ }
+ await writeIndex(o.dir, index, keepOutside);
+ return index;
+}
+
+async function writeIndex(dir: string, index: FrameIndex, outside: FrameRef[]): Promise<void> {
+ const frames = [...outside, ...index.frames].sort((a, b) => a.t - b.t);
+ const seen = new Set<number>();
+ await writeJsonAtomic(path.join(dir, FRAME_INDEX_FILE), { ...index, frames: frames.filter((f) => (seen.has(f.t) ? false : (seen.add(f.t), true))) }, { indent: 0 });
+}
+
+/** The cache's size on disk, and remove it. */
+export async function frameCacheBytes(dir: string): Promise<number> {
+ let total = 0;
+ for (const f of await readdir(dir).catch(() => [] as string[])) total += (await stat(path.join(dir, f)).catch(() => null))?.size ?? 0;
+ return total;
+}
+
+export async function removeFrameCache(dir: string): Promise<boolean> {
+ const there = await stat(dir).then(() => true, () => false);
+ if (there) await rm(dir, { recursive: true, force: true });
+ return there;
+}
diff --git a/common/lib/frames/scan.test.ts b/common/lib/frames/scan.test.ts
@@ -0,0 +1,270 @@
+// The frame scan end to end over a synthetic stream (ffmpeg-made, in a temp
+// dir) and the fake model servers: sampling, duplicates, the reads with real
+// JPEGs as image blocks, the cap, resume, the derivation. No real model.
+
+import { test, before, after } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtemp, readdir, rm } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import { errorTurn, imagesOf, startFakeAnthropic, toolTurn, type FakeAnthropic } from "../../testing/llm/fakeAnthropic.mjs";
+import { imagesOf as ollamaImagesOf, jsonReply, startFakeOllama } from "../../testing/llm/fakeOllama.mjs";
+import { makeSyntheticPokerStream, pokerTruthAt, SPOKEN_CUES } from "../../testing/frames/syntheticPoker.mjs";
+import { duplicatesOf } from "./dhash";
+import { batchArgs, batchesOf, gridOf, readFrameIndex, sampleFrames } from "./sample-server";
+import { claudeImageTokens, jpegSize, runFrameScan } from "./scan";
+import type { FrameScanRecord } from "../frameScan-server";
+
+let dir = "";
+let video = "";
+
+before(async () => {
+ dir = await mkdtemp(path.join(os.tmpdir(), "frame-scan-"));
+ video = (await makeSyntheticPokerStream(dir)).file;
+});
+after(async () => {
+ await rm(dir, { recursive: true, force: true });
+});
+
+// The fake model: each ask's frame times from its text, each frame read as the
+// synthetic client shows it at that time.
+const timesOf = (body: { messages: { content: unknown }[] }): number[] => {
+ const c = body.messages[0].content;
+ const text = typeof c === "string" ? c : (c as { type: string; text?: string }[]).filter((b) => b.type === "text").map((b) => b.text).join("");
+ return [...text.matchAll(/frame \d+ at (\d+):(\d+)/g)].map((m) => Number(m[1]) * 60 + Number(m[2]));
+};
+const truthTurn = (body: any) => toolTurn("answer", { frames: timesOf(body).map((t, i) => ({ frame: i + 1, ...pokerTruthAt(t) })) });
+
+function memoryStore() {
+ let rec: FrameScanRecord | null = null;
+ let writes = 0;
+ return {
+ load: async () => rec,
+ write: async (r: FrameScanRecord) => {
+ rec = JSON.parse(JSON.stringify(r));
+ writes++;
+ },
+ get: () => rec,
+ writes: () => writes,
+ };
+}
+
+test("gridOf and batchesOf: grid times in source seconds, batches on the grid", () => {
+ assert.deepEqual(gridOf(5, 40, 10), [5, 15, 25, 35]);
+ assert.deepEqual(gridOf(0, 0, 10), []);
+ assert.deepEqual(batchesOf([0, 10, 20, 30, 40], 10, 20), [[0, 10], [20, 30], [40]]);
+ const args = batchArgs({ source: "in.mp4", start: 30, seconds: 60, every: 10, width: 1280, outPattern: "o/%06d.jpg", keyframesOnly: true });
+ assert.ok(args.includes("nokey"));
+ assert.ok(args.join(" ").includes("fps=1/10"));
+ assert.equal(args.indexOf("-ss") < args.indexOf("-i"), true);
+});
+
+test("claudeImageTokens and jpegSize", () => {
+ assert.equal(claudeImageTokens(1280, 720), 1229);
+ assert.ok(claudeImageTokens(3840, 2160) <= 1534);
+ assert.equal(jpegSize(Buffer.from("not a jpeg")), null);
+});
+
+test("sampleFrames: one ffmpeg a batch, JPEGs at the profile's width, a hash each; a re-run decodes nothing", async () => {
+ const cache = path.join(dir, "cache-sample");
+ const idx = await sampleFrames({ source: video, dir: cache, from: 0, to: 210, every: 10, width: 640, batchSeconds: 100 });
+ assert.equal(idx.frames.length, 21);
+ assert.deepEqual(idx.frames.slice(0, 3).map((f) => f.t), [0, 10, 20]);
+ const files = (await readdir(cache)).filter((f) => f.endsWith(".jpg"));
+ assert.equal(files.length, 21);
+ // Static stretches hash alike; a change of picture does not.
+ const dup = duplicatesOf(idx.frames.map((f) => f.hash), { maxBits: 2, rereadEvery: 6 });
+ assert.equal(dup[1], 0); // lobby 10 s = lobby 0 s
+ assert.equal(dup[3], null); // the table at 30 s
+ assert.equal(dup[4], 3);
+ assert.equal(dup[9], null); // the double-up at 90 s
+ const kept = dup.filter((d) => d === null).length;
+ assert.ok(kept >= 7 && kept <= 10, `kept ${kept}`);
+ // The index is reused: a re-run with an ffmpeg that cannot run still answers.
+ const again = await sampleFrames({ source: video, dir: cache, from: 0, to: 210, every: 10, width: 640, batchSeconds: 100, ffmpeg: "/nonexistent/ffmpeg" });
+ assert.deepEqual(again.frames, idx.frames);
+ assert.equal((await readFrameIndex(cache))?.frames.length, 21);
+});
+
+test("a scan on the API: images as JPEG blocks, readings, the derived timeline, the spend; a re-run asks nothing", async () => {
+ const api: FakeAnthropic = await startFakeAnthropic({ turns: Array.from({ length: 20 }, () => truthTurn) });
+ const store = memoryStore();
+ const cache = path.join(dir, "cache-api");
+ const logs: string[] = [];
+ try {
+ const opts = {
+ profile: "poker",
+ source: video,
+ cacheDir: cache,
+ everySeconds: 10,
+ model: "claude-haiku-4-5",
+ llm: { anthropic: { baseUrl: api.url, env: { ANTHROPIC_API_KEY: api.key } } },
+ maxUsd: 1,
+ cues: SPOKEN_CUES,
+ hints: { hero: "SynthHero" },
+ onLog: (l: string) => logs.push(l),
+ now: () => new Date("2026-10-15T12:00:00Z"),
+ };
+ const out = await runFrameScan(opts, store);
+ const r = out.record;
+ // Every ask carried real 1280-px JPEGs, at most four, with the frame times in its text.
+ assert.ok(api.requests.length >= 2);
+ for (const body of api.requests) {
+ const imgs = imagesOf(body);
+ assert.ok(imgs.length >= 1 && imgs.length <= 4);
+ for (const im of imgs) {
+ assert.equal(im.mediaType, "image/jpeg");
+ assert.equal(im.width, 1280);
+ }
+ assert.equal(imgs.length, timesOf(body).length);
+ assert.match(JSON.stringify(body.system), /SynthHero/);
+ }
+ assert.equal(r.sampling.frames, 21);
+ assert.equal(r.readings.length, r.sampling.kept);
+ assert.equal(r.sampling.skippedDuplicates, 21 - r.sampling.kept);
+ assert.equal(r.duplicates.length, r.sampling.skippedDuplicates);
+ assert.equal(out.run.read, r.sampling.kept);
+ assert.equal(out.run.failed, 0);
+ assert.ok(out.run.costUsd > 0 && r.costUsd === out.run.costUsd);
+ assert.equal(r.model.model, "claude-haiku-4-5");
+ assert.equal(r.source.savedVideo, path.basename(video));
+
+ const d = r.derived;
+ const events = d.events.map((e) => [e.t, e.kind]);
+ assert.deepEqual(events.filter(([, k]) => k !== "buy-in"), [
+ [90, "double-up"],
+ [120, "big-loss"],
+ [120, "final-table"],
+ [180, "bust"],
+ [180, "eliminated"],
+ ]);
+ assert.ok(events.some(([t, k]) => k === "buy-in" && t === 35));
+ assert.equal(d.tournaments.length, 1);
+ assert.equal(d.tournaments[0].name, "Synthetic Cup");
+ assert.deepEqual(d.tournaments[0].series.stack, [[30, 20000], [90, 41000], [120, 9000], [180, 0]]);
+ assert.deepEqual(d.segments.map((s) => s.phase), ["lobby", "table", "break", "table", "lobby"]);
+ // The spoken "four players left" against the frames' 9: flagged, not trusted.
+ assert.deepEqual(d.flags.map((f) => [f.t, f.field, f.spoken, f.frame]), [[125, "playersLeft", 4, 9]]);
+
+ // Again: every kept frame is read, so nothing is asked.
+ const asked = api.requests.length;
+ const again = await runFrameScan(opts, store);
+ assert.equal(api.requests.length, asked);
+ assert.equal(again.run.read, 0);
+ assert.equal(again.record.runs.length, 2);
+ assert.equal(again.record.costUsd, out.run.costUsd);
+ } finally {
+ await api.close();
+ }
+});
+
+test("the cap stops a scan before an ask that would pass it; the next run reads the rest", async () => {
+ const api = await startFakeAnthropic({ turns: Array.from({ length: 20 }, () => truthTurn) });
+ const store = memoryStore();
+ try {
+ const base = {
+ profile: "poker",
+ source: video,
+ cacheDir: path.join(dir, "cache-cap"),
+ everySeconds: 10,
+ model: "claude-haiku-4-5",
+ llm: { anthropic: { baseUrl: api.url, env: { ANTHROPIC_API_KEY: api.key } } },
+ framesPerAsk: 1,
+ };
+ // About one ask's worth (~$0.0035 estimated a frame on Haiku 4.5).
+ const first = await runFrameScan({ ...base, maxUsd: 0.005 }, store);
+ assert.equal(first.run.stopped, "cap");
+ assert.ok(first.run.read >= 1 && first.run.read < first.record.sampling.kept, `read ${first.run.read}`);
+ assert.ok(first.run.costUsd <= 0.005);
+ const second = await runFrameScan({ ...base, maxUsd: 1 }, store);
+ assert.equal(second.run.stopped, undefined);
+ assert.equal(first.run.read + second.run.read, second.record.sampling.kept);
+ } finally {
+ await api.close();
+ }
+});
+
+test("three failed asks in a row stop a scan, and nothing is recorded as read", async () => {
+ const api = await startFakeAnthropic({ turns: [errorTurn(400, "invalid_request_error", "this model does not take images"), errorTurn(400, "invalid_request_error", "no"), errorTurn(400, "invalid_request_error", "no")] });
+ const store = memoryStore();
+ try {
+ const out = await runFrameScan(
+ {
+ profile: "poker",
+ source: video,
+ cacheDir: path.join(dir, "cache-err"),
+ everySeconds: 30,
+ model: "claude-haiku-4-5",
+ llm: { anthropic: { baseUrl: api.url, env: { ANTHROPIC_API_KEY: api.key }, maxRetries: 0 } },
+ maxUsd: 1,
+ framesPerAsk: 1,
+ },
+ store,
+ );
+ assert.equal(out.run.stopped, "errors");
+ assert.equal(out.run.failed, 3);
+ assert.equal(out.record.readings.length, 0);
+ } finally {
+ await api.close();
+ }
+});
+
+test("a scan on a local vision model: one frame an ask, as `images`, under the prompt cap", async () => {
+ const ol = await startFakeOllama({
+ models: ["qwen2.5vl:7b"],
+ turns: Array.from({ length: 30 }, () => (body: any) => {
+ const t = [...String(body.messages[1].content).matchAll(/frame \d+ at (\d+):(\d+)/g)].map((m) => Number(m[1]) * 60 + Number(m[2]));
+ return jsonReply({ frames: t.map((x, i) => ({ frame: i + 1, ...pokerTruthAt(x) })) });
+ }),
+ });
+ const store = memoryStore();
+ try {
+ const out = await runFrameScan(
+ {
+ profile: "poker",
+ source: video,
+ cacheDir: path.join(dir, "cache-local"),
+ everySeconds: 20,
+ model: "qwen2.5vl:7b",
+ llm: { ollama: { baseUrl: ol.url } },
+ maxUsd: Number.POSITIVE_INFINITY,
+ },
+ store,
+ );
+ assert.equal(out.run.failed, 0);
+ assert.equal(out.run.costUsd, 0);
+ assert.equal(ol.requests.length, out.run.read);
+ for (const body of ol.requests) {
+ const imgs = ollamaImagesOf(body);
+ assert.equal(imgs.length, 1);
+ assert.equal(imgs[0].width, 1280);
+ }
+ assert.ok(out.record.derived.events.some((e) => e.kind === "bust"));
+ } finally {
+ await ol.close();
+ }
+});
+
+test("maxFrames bounds a scan's range and says so", async () => {
+ const api = await startFakeAnthropic({ turns: Array.from({ length: 5 }, () => truthTurn) });
+ try {
+ const out = await runFrameScan(
+ {
+ profile: "poker",
+ source: video,
+ cacheDir: path.join(dir, "cache-max"),
+ everySeconds: 10,
+ maxFrames: 5,
+ model: "claude-haiku-4-5",
+ llm: { anthropic: { baseUrl: api.url, env: { ANTHROPIC_API_KEY: api.key } } },
+ maxUsd: 1,
+ },
+ memoryStore(),
+ );
+ assert.equal(out.run.stopped, "maxFrames");
+ assert.equal(out.record.sampling.frames, 5);
+ assert.equal(out.record.sampling.to, 50);
+ } finally {
+ await api.close();
+ }
+});
diff --git a/common/lib/frames/scan.ts b/common/lib/frames/scan.ts
@@ -0,0 +1,269 @@
+// One frame scan (release 30, lane P): sample, skip duplicates, read the kept
+// frames through a profile, derive, write the sidecar. Every effect is a dep,
+// so the tests run it over synthetic frames and the fake model servers.
+//
+// RESUMABLE: a reading already in the sidecar (by its grid time) is never
+// asked again, and a frame that duplicates a read frame is not asked at all.
+// The sidecar is written every few asks, so a cancelled or cut job keeps what
+// it read; the next run asks only the rest.
+//
+// CAPPED: the run stops before an ask that could take its spend past
+// `maxUsd` (an estimate per ask, from the frames' sizes and the model's
+// price), and again on the meter's own count. Three failed asks in a row stop
+// it too (a key refused, a model that cannot read images).
+
+import { readFile } from "node:fs/promises";
+import path from "node:path";
+import { Meter, structuredAnswer, priceOf, providerOf, type AnswerImage, type LlmConfig } from "../llm";
+import { CancelledError } from "../llm/anthropic";
+import { PromptTooLargeError } from "../llm/ollama";
+import { duplicatesOf } from "./dhash";
+import { frameProfile } from "./profiles";
+import { probeDuration, sampleFrames, type FrameIndex } from "./sample-server";
+import { FRAME_SCAN_FORMAT, type Cue, type FrameRef } from "./types";
+import type { FrameScanRecord, FrameScanRun } from "../frameScan-server";
+
+export const DEFAULT_EVERY_SECONDS = 10;
+export const DEFAULT_MAX_FRAMES = 5000;
+// Asks between two writes of the sidecar.
+const WRITE_EVERY_ASKS = 5;
+const MAX_FAILED_IN_A_ROW = 3;
+
+export type FrameScanOptions = {
+ profile: string;
+ // The saved container (absolute) and its basename for the record.
+ source: string;
+ cacheDir: string;
+ everySeconds?: number;
+ from?: number;
+ to?: number;
+ maxFrames?: number;
+ model: string;
+ llm: LlmConfig;
+ maxUsd: number;
+ hints?: { hero?: string };
+ framesPerAsk?: number;
+ keyframesOnly?: boolean;
+ cues?: Cue[];
+ jobId?: string;
+ signal?: AbortSignal;
+ onLog?: (line: string) => void;
+ onProgress?: (p: { phase: "sample" | "read"; current: number; total: number }) => void;
+ now?: () => Date;
+};
+
+export type FrameScanDeps = {
+ load: () => Promise<FrameScanRecord | null>;
+ write: (r: FrameScanRecord) => Promise<void>;
+ sample?: typeof sampleFrames;
+ probe?: (file: string) => Promise<number | null>;
+ readImage?: (file: string) => Promise<Buffer>;
+ // One structured ask (default: structuredAnswer).
+ ask?: typeof structuredAnswer;
+};
+
+export type FrameScanOutcome = { record: FrameScanRecord; run: FrameScanRun; spent: ReturnType<Meter["summary"]> };
+
+// What one image costs on the Claude API, in input tokens: (w·h)/750 after the
+// API's own downscale (long edge ≤ 1568, ≤ ~1.15 MP). A JPEG's size is read
+// from its SOF marker; an unreadable one is priced at the most an image costs.
+export function claudeImageTokens(w: number, h: number): number {
+ let s = 1;
+ if (Math.max(w, h) > 1568) s = 1568 / Math.max(w, h);
+ if (w * h * s * s > 1_150_000) s = Math.sqrt(1_150_000 / (w * h));
+ return Math.ceil((w * s * h * s) / 750);
+}
+
+export function jpegSize(buf: Buffer): { w: number; h: number } | null {
+ if (buf.length < 4 || buf[0] !== 0xff || buf[1] !== 0xd8) return null;
+ let i = 2;
+ while (i + 9 < buf.length) {
+ if (buf[i] !== 0xff) return null;
+ const marker = buf[i + 1];
+ const len = buf.readUInt16BE(i + 2);
+ if (marker >= 0xc0 && marker <= 0xcf && marker !== 0xc4 && marker !== 0xc8 && marker !== 0xcc) {
+ return { h: buf.readUInt16BE(i + 5), w: buf.readUInt16BE(i + 7) };
+ }
+ i += 2 + len;
+ }
+ return null;
+}
+
+// An ask's cost estimate before it is sent: its images, the prompt text and
+// a reading's worth of output per frame.
+function askEstimateUsd(model: string, images: Buffer[], promptChars: number): number {
+ if (providerOf(model) !== "api") return 0;
+ const p = priceOf(model);
+ const imgTokens = images.reduce((n, b) => {
+ const s = jpegSize(b);
+ return n + (s ? claudeImageTokens(s.w, s.h) : 1600);
+ }, 0);
+ const input = imgTokens + Math.ceil(promptChars / 3.5);
+ const output = 250 * images.length;
+ return (input * p.input + output * p.output) / 1e6;
+}
+
+export async function runFrameScan(o: FrameScanOptions, deps: FrameScanDeps): Promise<FrameScanOutcome> {
+ const log = o.onLog ?? (() => {});
+ const profile = frameProfile(o.profile);
+ const every = o.everySeconds ?? DEFAULT_EVERY_SECONDS;
+ const route: "api" | "local" = providerOf(o.model);
+ const now = o.now ?? (() => new Date());
+ const meter = new Meter({ maxUsd: o.maxUsd });
+ const prev = await deps.load();
+
+ const duration = await (deps.probe ?? probeDuration)(o.source);
+ const from = Math.max(0, o.from ?? 0);
+ let to = o.to ?? duration ?? 0;
+ if (duration !== null) to = Math.min(to, duration);
+ if (!(to > from)) throw new Error(`nothing to scan: ${from}–${to} s${duration === null ? " (the video's length could not be read)" : ""}`);
+ const maxFrames = o.maxFrames ?? DEFAULT_MAX_FRAMES;
+ let stopped: FrameScanRun["stopped"];
+ if ((to - from) / every > maxFrames) {
+ to = Math.round((from + maxFrames * every) * 100) / 100;
+ stopped = "maxFrames";
+ log(`the range would be over ${maxFrames} frames: scanning ${from}–${to} s only (raise maxFrames or everySeconds)`);
+ }
+
+ log(`sampling ${from}–${Math.round(to)} s every ${every} s at ${profile.width} px wide into ${o.cacheDir}`);
+ const index: FrameIndex = await (deps.sample ?? sampleFrames)({
+ source: o.source,
+ dir: o.cacheDir,
+ from,
+ to,
+ every,
+ width: profile.width,
+ keyframesOnly: o.keyframesOnly ?? true,
+ signal: o.signal,
+ onLog: log,
+ onBatch: (d, n) => o.onProgress?.({ phase: "sample", current: d, total: n }),
+ });
+ const frames = index.frames.filter((f) => f.t >= from && f.t < to).sort((a, b) => a.t - b.t);
+ const dup = duplicatesOf(frames.map((f) => f.hash), { maxBits: profile.dupMaxBits, rereadEvery: profile.rereadEvery });
+ const kept = frames.filter((_, i) => dup[i] === null);
+ const readings = new Map<number, FrameScanRecord["readings"][number]>();
+ for (const r of prev?.readings ?? []) readings.set(r.t, r);
+ const todo = kept.filter((f) => !readings.has(f.t));
+ log(`${frames.length} frames, ${kept.length} kept (${frames.length - kept.length} duplicates), ${kept.length - todo.length} already read, ${todo.length} to read on ${o.model}`);
+
+ const per = Math.max(1, o.framesPerAsk ?? profile.framesPerAsk[route]);
+ const system = profile.system(o.hints ?? {});
+ const ask = deps.ask ?? structuredAnswer;
+ const readImage = deps.readImage ?? ((f: string) => readFile(f));
+ let read = 0;
+ let failed = 0;
+ let inARow = 0;
+ let asks = 0;
+
+ // A duplicate frame shows what the frame it duplicates shows: [t, that t].
+ // Kept with the record (the cache is evictable), merged over runs.
+ const dupPairs = new Map<number, number>();
+ for (const [t, src] of prev?.duplicates ?? []) if (t < from || t >= to) dupPairs.set(t, src);
+ frames.forEach((f, i) => {
+ const d = dup[i];
+ if (d !== null) dupPairs.set(f.t, frames[d].t);
+ });
+ const record = (): FrameScanRecord => {
+ const all = [...readings.values()].sort((a, b) => a.t - b.t);
+ // The derivation reads the duplicates too, as copies of what they show:
+ // a held stack is held on every frame, read or not.
+ const copies = [...dupPairs].flatMap(([t, src]) => {
+ const r = readings.get(src);
+ return r && !readings.has(t) ? [{ ...r, t }] : [];
+ });
+ const expanded = [...all, ...copies].sort((a, b) => a.t - b.t);
+ const spoken = o.cues ? profile.spoken(o.cues) : (prev?.spoken ?? []);
+ return {
+ format: FRAME_SCAN_FORMAT,
+ version: 1,
+ profile: profile.id,
+ source: { savedVideo: path.basename(o.source), durationSeconds: duration },
+ sampling: {
+ everySeconds: every,
+ from,
+ to,
+ width: profile.width,
+ keyframesOnly: index.keyframesOnly,
+ frames: frames.length,
+ kept: kept.length,
+ skippedDuplicates: frames.length - kept.length,
+ },
+ model: { route, model: o.model, promptVersion: profile.promptVersion },
+ costUsd: Math.round(((prev?.costUsd ?? 0) + meter.usd) * 10_000) / 10_000,
+ runs: [...(prev?.runs ?? []), runOf()],
+ readings: all,
+ duplicates: [...dupPairs].sort((a, b) => a[0] - b[0]),
+ spoken,
+ derived: profile.derive(expanded as never, spoken, { everySeconds: every, ...(duration !== null ? { durationSeconds: duration } : {}) }),
+ updatedAt: now().toISOString(),
+ };
+ };
+ const runOf = (): FrameScanRun => ({
+ at: now().toISOString(),
+ ...(o.jobId ? { jobId: o.jobId } : {}),
+ model: o.model,
+ route,
+ frames: frames.length,
+ read,
+ failed,
+ costUsd: Math.round(meter.usd * 10_000) / 10_000,
+ ...(stopped ? { stopped } : {}),
+ });
+
+ for (let i = 0; i < todo.length; i += per) {
+ if (o.signal?.aborted) {
+ stopped = "cancelled";
+ break;
+ }
+ const chunk: FrameRef[] = todo.slice(i, i + per);
+ const bufs = await Promise.all(chunk.map((f) => readImage(path.join(o.cacheDir, f.file))));
+ const user = profile.user(chunk);
+ const schema = profile.schema(chunk.length);
+ const estimate = askEstimateUsd(o.model, bufs, system.length + user.length + JSON.stringify(schema).length);
+ if (meter.over() || (route === "api" && meter.usd + estimate > o.maxUsd)) {
+ stopped = "cap";
+ log(`stopping at the cap: $${meter.usd.toFixed(4)} spent of $${o.maxUsd} (the next ask is ~$${estimate.toFixed(4)})`);
+ break;
+ }
+ const images: AnswerImage[] = bufs.map((b) => ({ mediaType: "image/jpeg", data: b.toString("base64") }));
+ let answer: unknown;
+ try {
+ answer = await ask({ llm: o.llm, model: o.model, system, user, schema, images, meter, signal: o.signal, maxTokens: 400 * chunk.length + 400 });
+ } catch (err) {
+ if (o.signal?.aborted || err instanceof CancelledError) {
+ stopped = "cancelled";
+ break;
+ }
+ failed += chunk.length;
+ inARow++;
+ log(`ask failed for ${chunk.map((f) => f.t).join(", ")} s: ${(err as Error).message}`);
+ if (err instanceof PromptTooLargeError || inARow >= MAX_FAILED_IN_A_ROW) {
+ stopped = "errors";
+ log(`stopping: ${inARow} failed asks in a row`);
+ break;
+ }
+ continue;
+ }
+ inARow = 0;
+ const list = answer && typeof answer === "object" && Array.isArray((answer as { frames?: unknown }).frames) ? ((answer as { frames: unknown[] }).frames) : [];
+ chunk.forEach((f, k) => {
+ // The answer's own frame numbers when it gives them, else its order.
+ const raw = list.find((x) => x && typeof x === "object" && (x as { frame?: unknown }).frame === k + 1) ?? (list.length === chunk.length ? list[k] : undefined);
+ const reading = profile.coerce(raw);
+ if (!reading) {
+ failed++;
+ return;
+ }
+ readings.set(f.t, { t: f.t, ...reading });
+ read++;
+ });
+ asks++;
+ o.onProgress?.({ phase: "read", current: Math.min(todo.length, i + per), total: todo.length });
+ if (asks % WRITE_EVERY_ASKS === 0) await deps.write(record());
+ }
+ const out = record();
+ await deps.write(out);
+ const run = out.runs[out.runs.length - 1];
+ log(`read ${read} frames (${failed} failed), $${meter.usd.toFixed(4)} this run${stopped ? `, stopped: ${stopped}` : ""}; ${out.derived.events.length} events, ${out.derived.tournaments.length} tournament(s)`);
+ return { record: out, run, spent: meter.summary() };
+}
diff --git a/common/lib/frames/series.test.ts b/common/lib/frames/series.test.ts
@@ -0,0 +1,38 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { agree, changesOnly, dropMisreads, nearest, ratioOf } from "./series";
+
+const P = (pairs: [number, number][]) => pairs.map(([t, v]) => ({ t, v }));
+
+test("ratioOf and agree", () => {
+ assert.equal(ratioOf(10, 20), 2);
+ assert.equal(ratioOf(0, 0), 1);
+ assert.equal(ratioOf(0, 5), Infinity);
+ assert.ok(agree(9, 7, { ratio: 1.1, absolute: 2 }));
+ assert.ok(!agree(9, 6, { ratio: 1.1, absolute: 2 }));
+});
+
+test("a single frame that jumps 100× is a misread when its neighbours agree", () => {
+ const { kept, dropped } = dropMisreads(P([[0, 20000], [10, 2000000], [20, 21000]]), { ratio: 3 });
+ assert.deepEqual(dropped, P([[10, 2000000]]));
+ assert.equal(kept.length, 2);
+});
+
+test("a real change is followed by points that agree with it, so it stays", () => {
+ const { dropped } = dropMisreads(P([[0, 20000], [10, 41000], [20, 41000], [30, 40500]]), { ratio: 1.5 });
+ assert.deepEqual(dropped, []);
+});
+
+test("an end point that disagrees hard with the two next to it is a misread", () => {
+ assert.deepEqual(dropMisreads(P([[0, 5], [10, 500], [20, 510]]), { ratio: 2 }).dropped, P([[0, 5]]));
+ assert.deepEqual(dropMisreads(P([[0, 500], [10, 510], [20, 50000]]), { ratio: 2 }).dropped, P([[20, 50000]]));
+ // A series that ends at 0 ended there (a bust); a first reading before a change stays.
+ assert.deepEqual(dropMisreads(P([[0, 500], [10, 510], [20, 0]]), { ratio: 2 }).dropped, []);
+ assert.deepEqual(dropMisreads(P([[0, 20000], [10, 41000], [20, 41000]]), { ratio: 1.5 }).dropped, []);
+});
+
+test("changesOnly and nearest", () => {
+ assert.deepEqual(changesOnly(P([[0, 1], [10, 1], [20, 2], [30, 2], [40, 1]])), P([[0, 1], [20, 2], [40, 1]]));
+ assert.deepEqual(nearest(P([[0, 1], [50, 2], [90, 3]]), 60, 20), { t: 50, v: 2 });
+ assert.equal(nearest(P([[0, 1]]), 60, 20), null);
+});
diff --git a/common/lib/frames/series.ts b/common/lib/frames/series.ts
@@ -0,0 +1,83 @@
+// Series helpers every profile's derivation shares (release 30, lane P). Pure.
+//
+// A model reading a frame misreads now and then — a digit dropped, a
+// neighbour's stack taken for the hero's — and a single frame that jumps
+// 100× is a misread, not a double-up. The rule is AGREEMENT OF NEIGHBOURS: a
+// point is set aside when the points either side of it agree with each other
+// and it agrees with neither. A real change is followed by points that agree
+// with it, so it stays.
+
+export type Pt = { t: number; v: number };
+
+/** How far apart two values are, as a ratio ≥ 1 (Infinity when one is 0 and the other is not). */
+export function ratioOf(a: number, b: number): number {
+ if (a === b) return 1;
+ if (a <= 0 || b <= 0) return Infinity;
+ return a > b ? a / b : b / a;
+}
+
+export type AgreeRule = { ratio: number; absolute?: number };
+
+/** Whether two values agree under a rule: within `ratio`, or within `absolute` of each other. */
+export function agree(a: number, b: number, rule: AgreeRule): boolean {
+ if (rule.absolute !== undefined && Math.abs(a - b) <= rule.absolute) return true;
+ return ratioOf(a, b) <= rule.ratio;
+}
+
+/**
+ * The points with misreads set aside: `kept` and `dropped`. A middle point is
+ * dropped when its two neighbours agree and it agrees with neither; an end
+ * point when the next two (or last two) agree and it disagrees with both by
+ * the square of the ratio — but a last point of 0 is kept (a series that ends
+ * at 0 ended there).
+ * One pass over the original points, so two misreads in a row both stay (the
+ * rule cannot tell them from a change) — that is what `flags` and the review
+ * are for.
+ */
+export function dropMisreads(points: readonly Pt[], rule: AgreeRule): { kept: Pt[]; dropped: Pt[] } {
+ const kept: Pt[] = [];
+ const dropped: Pt[] = [];
+ const n = points.length;
+ for (let i = 0; i < n; i++) {
+ const p = points[i];
+ let a: Pt | undefined;
+ let b: Pt | undefined;
+ if (i > 0 && i < n - 1) {
+ a = points[i - 1];
+ b = points[i + 1];
+ } else if (i === 0 && n >= 3) {
+ a = points[1];
+ b = points[2];
+ } else if (i === n - 1 && n >= 3 && p.v !== 0) {
+ // The last point has nothing after it to agree with, so it is judged by
+ // the two before it — except a 0, which ends a series for real (a bust).
+ a = points[n - 2];
+ b = points[n - 3];
+ }
+ // An end point has only one side to be judged by, so it must disagree
+ // twice as hard (the square of the ratio): a first reading followed by a
+ // real change is kept, a 100× outlier is not.
+ const end = i === 0 || i === n - 1;
+ const r: AgreeRule = end ? { ratio: rule.ratio * rule.ratio, ...(rule.absolute !== undefined ? { absolute: rule.absolute * 2 } : {}) } : rule;
+ if (a && b && agree(a.v, b.v, rule) && !agree(p.v, a.v, r) && !agree(p.v, b.v, r)) dropped.push(p);
+ else kept.push(p);
+ }
+ return { kept, dropped };
+}
+
+/** Collapse a series to its changes: a point equal to the one before it is left out. */
+export function changesOnly(points: readonly Pt[]): Pt[] {
+ const out: Pt[] = [];
+ for (const p of points) if (!out.length || out[out.length - 1].v !== p.v) out.push(p);
+ return out;
+}
+
+/** The point nearest `t` within `window` seconds, or null. */
+export function nearest(points: readonly Pt[], t: number, window: number): Pt | null {
+ let best: Pt | null = null;
+ for (const p of points) {
+ const d = Math.abs(p.t - t);
+ if (d <= window && (!best || d < Math.abs(best.t - t))) best = p;
+ }
+ return best;
+}
diff --git a/common/lib/frames/types.ts b/common/lib/frames/types.ts
@@ -0,0 +1,103 @@
+// The frame scan's shapes (release 30, lane P): a stream sampled into frames,
+// each kept frame read by a vision model through a PROFILE (poker first), the
+// readings and the transcript's spoken numbers turned into series, events and
+// segments by pure code. Pure: types and small helpers only.
+
+/** One sampled frame in the cache. `t` is the SOURCE second (the grid time). */
+export type FrameRef = {
+ t: number;
+ // The JPEG's basename in the cache dir.
+ file: string;
+ // dHash of the frame's grey thumbnail (hex).
+ hash: string;
+};
+
+/** A cue, as `transcript.cues.json` holds it. */
+export type Cue = { start: number; end: number; text: string };
+
+/** A number the streamer SAID, read out of the cues by pure code. */
+export type SpokenReading = {
+ t: number;
+ field: string;
+ value: number;
+ // The cue's words (trimmed), so a reader can see why.
+ text: string;
+ // Scaled by a rule (a stack said without "thousand" beside an average said with it).
+ approx?: boolean;
+};
+
+/** A series point: [t, value], or [t, value, "spoken"] when a spoken number filled it. */
+export type SeriesPoint = [number, number] | [number, number, "spoken"];
+
+export type DerivedEvent = {
+ t: number;
+ kind: string;
+ detail: string;
+ // Where it came from: the model's reading of a frame, the series, or the transcript.
+ source: "frame" | "series" | "spoken";
+ tournament?: string;
+};
+
+export type DerivedSegment = { from: number; to: number; phase: string; tournament?: string };
+
+/** A frame reading and a spoken number that disagree (never silently trusted). */
+export type DerivedFlag = { t: number; field: string; spoken: number; frame: number; frameT: number; tournament?: string };
+
+export type DerivedTournament = {
+ key: string;
+ name?: string;
+ from: number;
+ to: number;
+ series: Record<string, SeriesPoint[]>;
+ // The last values seen: buy-in, prize, field size.
+ facts: Record<string, number>;
+};
+
+export type Derived = {
+ tournaments: DerivedTournament[];
+ events: DerivedEvent[];
+ segments: DerivedSegment[];
+ flags: DerivedFlag[];
+ // Readings the smoothing set aside as misreads, by field.
+ misreads: { t: number; field: string; value: number }[];
+};
+
+/** A profile: what a frame is read for, and how readings become a timeline. */
+export type FrameProfile<R extends { phase: string }> = {
+ id: string;
+ // Bumped whenever the prompt or the schema changes.
+ promptVersion: number;
+ // The width frames are scaled to before a model reads them.
+ width: number;
+ // dHash bits two frames may differ by and still be one picture.
+ dupMaxBits: number;
+ // A duplicate run is read again every this many frames (a number on a
+ // static screen can change too small for the hash to see).
+ rereadEvery: number;
+ // Frames per ask on the API and on a local model.
+ framesPerAsk: { api: number; local: number };
+ system(hints: { hero?: string }): string;
+ user(frames: { t: number }[]): string;
+ // The answer's schema for an ask of `n` frames: `{ frames: [reading…] }`.
+ schema(n: number): object;
+ // A model's reading cleaned to the profile's shape; null when it is not one.
+ coerce(raw: unknown): R | null;
+ spoken(cues: Cue[]): SpokenReading[];
+ derive(readings: (R & { t: number })[], spoken: SpokenReading[], o: { everySeconds: number; durationSeconds?: number }): Derived;
+};
+
+export const FRAME_SCAN_FORMAT = "archilyzer-frame-scan";
+
+/** "1:02:03" / "4:05". */
+export function clock(t: number): string {
+ const s = Math.max(0, Math.round(t));
+ const h = Math.floor(s / 3600);
+ const m = Math.floor((s % 3600) / 60);
+ const sec = s % 60;
+ return h > 0 ? `${h}:${String(m).padStart(2, "0")}:${String(sec).padStart(2, "0")}` : `${m}:${String(sec).padStart(2, "0")}`;
+}
+
+/** 12400 → "12,400"; 1.5 → "1.5". */
+export function fmtNum(v: number): string {
+ return Number.isInteger(v) ? v.toLocaleString("en-US") : String(Math.round(v * 10) / 10);
+}
diff --git a/common/lib/generationSettings.test.ts b/common/lib/generationSettings.test.ts
@@ -129,3 +129,25 @@ test("generation settings: the verdict bench's bar (fractions, clamped) and the
assert.deepEqual(sanitizeGeneration({ verdicts: { window: { mode: "turn", seconds: 30.4 } } }).verdicts.window, { mode: "turn", seconds: 30 });
assert.deepEqual(sanitizeGeneration({ verdicts: { window: { mode: "sentence", seconds: 900 } } }).verdicts.window, { mode: "seconds", seconds: 60 });
});
+
+test("the frame scan (release 30): its own route and settings; a file from before keeps its preset", () => {
+ assert.ok((GENERATION_TASKS as readonly string[]).includes("frames"));
+ assert.equal(GENERATION_PRESETS.code.frames, "code");
+ assert.equal(GENERATION_PRESETS.balanced.frames, "api");
+ assert.equal(GENERATION_PRESETS.local.frames, "local");
+ assert.deepEqual(DEFAULT_GENERATION_SETTINGS.frames, { apiModel: "claude-haiku-4-5", localModel: "qwen2.5vl:7b", maxUsd: 5, everySeconds: 10 });
+ assert.deepEqual(sanitizeGeneration({}).frames, DEFAULT_GENERATION_SETTINGS.frames);
+ assert.deepEqual(sanitizeGeneration({ frames: { apiModel: "claude-haiku-5-5", localModel: "bad model", maxUsd: -1, everySeconds: 0.5 } }).frames, {
+ apiModel: "claude-haiku-5-5",
+ localModel: "qwen2.5vl:7b",
+ maxUsd: 5,
+ everySeconds: 10,
+ });
+ // A file that routes every task but frames keeps its preset.
+ for (const p of ["code", "balanced", "api", "local"] as const) {
+ const routes = Object.fromEntries(GENERATION_TASKS.filter((t) => t !== "frames").map((t) => [t, GENERATION_PRESETS[p][t]]));
+ const g = sanitizeGeneration({ routes });
+ assert.equal(g.preset, p);
+ assert.equal(g.routes.frames, GENERATION_PRESETS[p].frames);
+ }
+});
diff --git a/common/lib/generationSettings.ts b/common/lib/generationSettings.ts
@@ -21,7 +21,10 @@ export const isStepTask = (t: unknown): t is MediaStepTask => typeof t === "stri
// `verdicts` (release 29 M8): verdict proposals for a fact-check's unruled
// claims — no iteration, no step: a sidecar beside the article, and only on a
// model in `verdicts.models` (the bench's bar).
-export const GENERATION_TASKS = ["sweep", "revise-report", "revise-video", "narrate", "research", "cut", "onscreen", "teaser", "flips", "threads", "youtube", "social", "verdicts"] as const;
+// `frames` (release 30, lane P): a frame scan's readings of a saved stream's
+// frames by a vision model — no article, no iteration: a sidecar beside the
+// video. `api` or `local`; `code` = none unless the job names a model.
+export const GENERATION_TASKS = ["sweep", "revise-report", "revise-video", "narrate", "research", "cut", "onscreen", "teaser", "flips", "threads", "youtube", "social", "verdicts", "frames"] as const;
export type GenerationTask = (typeof GENERATION_TASKS)[number];
// The tasks every settings file since release 27 S6 routes.
const FIRST_TASKS: readonly GenerationTask[] = ["sweep", "revise-report", "revise-video", "narrate"];
@@ -33,10 +36,12 @@ export type GenerationRoute = (typeof GENERATION_ROUTES)[number];
const mediaRoutes = <R extends GenerationRoute>(r: R) => ({ cut: r, onscreen: r, teaser: r, flips: r, threads: r, youtube: r, social: r }) as const;
export const GENERATION_PRESETS = {
- code: { sweep: "code", "revise-report": "code", "revise-video": "code", narrate: "code", research: "code", ...mediaRoutes("code"), verdicts: "code" },
- balanced: { sweep: "code", "revise-report": "api", "revise-video": "local", narrate: "local", research: "api", ...mediaRoutes("local"), verdicts: "local" },
- api: { sweep: "api", "revise-report": "api", "revise-video": "api", narrate: "api", research: "api", ...mediaRoutes("api"), verdicts: "api" },
- local: { sweep: "local", "revise-report": "local", "revise-video": "local", narrate: "local", research: "local", ...mediaRoutes("local"), verdicts: "local" },
+ code: { sweep: "code", "revise-report": "code", "revise-video": "code", narrate: "code", research: "code", ...mediaRoutes("code"), verdicts: "code", frames: "code" },
+ // A frame scan is on the API in `balanced`: a vision model is not a given
+ // on the local card, and the cheap model's reads cost cents an hour.
+ balanced: { sweep: "code", "revise-report": "api", "revise-video": "local", narrate: "local", research: "api", ...mediaRoutes("local"), verdicts: "local", frames: "api" },
+ api: { sweep: "api", "revise-report": "api", "revise-video": "api", narrate: "api", research: "api", ...mediaRoutes("api"), verdicts: "api", frames: "api" },
+ local: { sweep: "local", "revise-report": "local", "revise-video": "local", narrate: "local", research: "local", ...mediaRoutes("local"), verdicts: "local", frames: "local" },
} as const satisfies Record<string, Record<GenerationTask, GenerationRoute>>;
export type GenerationPreset = keyof typeof GENERATION_PRESETS;
export const GENERATION_PRESET_NAMES = Object.keys(GENERATION_PRESETS) as GenerationPreset[];
@@ -82,6 +87,11 @@ export type GenerationTriage = {
};
export const DEFAULT_GENERATION_TRIAGE: GenerationTriage = { model: "local", strong: 1, weak: 3, maxEscalationsPerDay: 3, maxCandidates: 40 };
+// The frame scan (release 30, lane P): the vision models each route reads
+// frames on, a scan's default spend cap and its default sampling step.
+export type GenerationFrames = { apiModel: string; localModel: string; maxUsd: number; everySeconds: number };
+export const DEFAULT_GENERATION_FRAMES: GenerationFrames = { apiModel: "claude-haiku-4-5", localModel: "qwen2.5vl:7b", maxUsd: 5, everySeconds: 10 };
+
export type GenerationSettings = {
preset: GenerationPreset | "custom";
routes: GenerationRoutes;
@@ -98,6 +108,7 @@ export type GenerationSettings = {
cut: GenerationCut;
verdicts: GenerationVerdicts;
triage: GenerationTriage;
+ frames: GenerationFrames;
};
export const DEFAULT_GENERATION_VERDICT_WINDOW: GenerationVerdictWindow = { mode: "seconds", seconds: 60 };
@@ -123,6 +134,7 @@ export const DEFAULT_GENERATION_SETTINGS: GenerationSettings = {
cut: { maxClips: 20 },
verdicts: { bar: { ...DEFAULT_GENERATION_VERDICTS.bar }, models: [], window: { ...DEFAULT_GENERATION_VERDICT_WINDOW } },
triage: { ...DEFAULT_GENERATION_TRIAGE },
+ frames: { ...DEFAULT_GENERATION_FRAMES },
};
export const GENERATION_SETTINGS_FIELD_DOCS: FieldDocs<GenerationSettings> = {
@@ -147,6 +159,14 @@ export const GENERATION_SETTINGS_FIELD_DOCS: FieldDocs<GenerationSettings> = {
"The verdict bench's bar and the models that cleared it (below), set on umtool's /bench after reading a run (`archilyzer reports bench-verdicts`). Verdict proposals run only on `models`.",
triage:
"Triage first (umtool R6): the cheap pass a recurring report runs before its sweep when it asks for one (a watch always does) — the model it judges on, when it escalates to an API sweep of what it flagged, and how often a day it may (below).",
+ frames: "The frame scan (`pnpm ops frame-scan`): the vision model each route reads a saved stream's frames on, a scan's spend cap and its sampling step (below).",
+};
+
+export const GENERATION_FRAMES_FIELD_DOCS: FieldDocs<GenerationFrames> = {
+ apiModel: "The Claude model a scan on the `api` route reads frames with (it must take images). Haiku: about a cent a hundred frames.",
+ localModel: "The ollama vision model a scan on the `local` route reads frames with (one frame an ask, under the 8k prompt cap; through the GPU arbiter on `draft:local`).",
+ maxUsd: "A scan's API cap when the job names none (at most `caps.max`): the scan stops before an ask that would pass it, and keeps what it read.",
+ everySeconds: "Seconds between two sampled frames when the job names none (1 to 600).",
};
export const GENERATION_TRIAGE_FIELD_DOCS: FieldDocs<GenerationTriage> = {
@@ -193,6 +213,8 @@ export const GENERATION_ROUTES_FIELD_DOCS: FieldDocs<GenerationRoutes> = {
threads: "A media draft: the cut's threads and each clip's thread.",
youtube: "A media draft: the YouTube title and description.",
social: "A media draft: the promotion posts for X and Bluesky (`publish.x`, `publish.bluesky`; text only, never posted), the link added by code.",
+ frames:
+ "A frame scan's readings of a saved stream's frames (`frame-scan.<profile>.json` beside the video): `api` (`frames.apiModel`) or `local` (`frames.localModel`); `code` = none unless the job names a model.",
verdicts:
"Verdict proposals for a fact-check's unruled claims (`verdicts.proposed.json` beside the article; the operator approves or rejects each). Runs only on a model in `verdicts.models`: the first of them on this route (`api` or `local`), or the one a job names; `code` = none unless named.",
};
@@ -314,6 +336,18 @@ export function sanitizeGeneration(value: unknown): GenerationSettings {
},
verdicts: sanitizeVerdicts(r.verdicts),
triage: sanitizeTriage(r.triage),
+ frames: sanitizeFrames(r.frames, model),
+ };
+}
+
+function sanitizeFrames(v: unknown, model: (v: unknown, fallback: string) => string): GenerationFrames {
+ const d = DEFAULT_GENERATION_FRAMES;
+ const o = v && typeof v === "object" && !Array.isArray(v) ? (v as Record<string, unknown>) : {};
+ return {
+ apiModel: model(o.apiModel, d.apiModel),
+ localModel: model(o.localModel, d.localModel),
+ maxUsd: usd(o.maxUsd, d.maxUsd, 1000),
+ everySeconds: typeof o.everySeconds === "number" && Number.isFinite(o.everySeconds) && o.everySeconds >= 1 && o.everySeconds <= 600 ? Math.round(o.everySeconds * 100) / 100 : d.everySeconds,
};
}
diff --git a/common/lib/llm/ollama.ts b/common/lib/llm/ollama.ts
@@ -46,9 +46,22 @@ export function estimateTokens(v: unknown): number {
return Math.ceil(s.length / CHARS_PER_TOKEN);
}
-// What a chat request is estimated at: its messages, tools and format.
+// An image a vision model reads (release 30, the frame scan) is counted at a
+// fixed cost, not by its base64: a 1280-px frame is about a thousand tokens to
+// a vision model, and its base64 would read as tens of thousands.
+export const IMAGE_TOKEN_ESTIMATE = 1_200;
+
+// What a chat request is estimated at: its messages (each message's `images`
+// at IMAGE_TOKEN_ESTIMATE apiece), tools and format.
export function promptEstimate(req: { messages: unknown[]; tools?: unknown[]; format?: unknown }): number {
- return estimateTokens([req.messages, req.tools ?? null, req.format ?? null]);
+ let images = 0;
+ const messages = req.messages.map((m) => {
+ if (!m || typeof m !== "object" || !Array.isArray((m as { images?: unknown }).images)) return m;
+ const { images: imgs, ...rest } = m as { images: unknown[] };
+ images += imgs.length;
+ return rest;
+ });
+ return estimateTokens([messages, req.tools ?? null, req.format ?? null]) + images * IMAGE_TOKEN_ESTIMATE;
}
export function numCtxOf(cfg: OllamaConfig): number {
diff --git a/common/lib/llm/structured.test.ts b/common/lib/llm/structured.test.ts
@@ -9,8 +9,9 @@ import {
textBlock,
} from "../../testing/llm/fakeAnthropic.mjs";
import { faultReply, jsonReply, reply, startFakeOllama } from "../../testing/llm/fakeOllama.mjs";
-import { closeSchema, structuredAnswer, StructuredAnswerError } from "./structured";
-import { PromptTooLargeError } from "./ollama";
+import { closeSchema, structuredAnswer, structuredPromptEstimate, StructuredAnswerError } from "./structured";
+import { IMAGE_TOKEN_ESTIMATE, PromptTooLargeError, promptEstimate } from "./ollama";
+import { execFileSync } from "node:child_process";
import { Meter } from "./meter";
import { providerOf } from "./config";
@@ -170,3 +171,56 @@ test("a provider without its config is a clear error", async () => {
await assert.rejects(structuredAnswer({ llm: {}, model: "qwen3:8b", system: "s", user: "u", schema }), /no ollama URL/);
await assert.rejects(structuredAnswer({ llm: {}, model: "claude-sonnet-5", system: "s", user: "u", schema }), /no API config/);
});
+
+// ─── Images (release 30, the frame scan) ───
+
+const tinyJpeg = () =>
+ execFileSync("ffmpeg", ["-hide_banner", "-loglevel", "error", "-f", "lavfi", "-i", "color=c=blue:s=64x36:d=1", "-frames:v", "1", "-c:v", "mjpeg", "-f", "image2pipe", "pipe:1"]).toString("base64");
+
+test("Claude with images: image blocks before the text, in the one user turn", async () => {
+ const api = await startFakeAnthropic({ turns: [turn([toolUseBlock("answer", { terms: ["chips"] })])] });
+ try {
+ const data = tinyJpeg();
+ const out = await structuredAnswer<{ terms: string[] }>({
+ llm: { anthropic: { baseUrl: api.url, env: { ANTHROPIC_API_KEY: api.key } } },
+ model: "claude-haiku-4-5",
+ system: "Read the frames.",
+ user: "Two frames.",
+ schema,
+ images: [
+ { mediaType: "image/jpeg", data },
+ { mediaType: "image/jpeg", data },
+ ],
+ });
+ assert.deepEqual(out, { terms: ["chips"] });
+ const content = api.requests[0].messages[0].content;
+ assert.deepEqual(content.map((b: { type: string }) => b.type), ["image", "image", "text"]);
+ assert.equal(content[0].source.media_type, "image/jpeg");
+ assert.equal(content[2].text, "Two frames.");
+ } finally {
+ await api.close();
+ }
+});
+
+test("ollama with images: the user message's images, counted at a fixed cost in the estimate", async () => {
+ const ol = await startFakeOllama({ models: ["qwen2.5vl:7b"], turns: [jsonReply({ terms: ["stack"] })] });
+ try {
+ const data = tinyJpeg();
+ const out = await structuredAnswer<{ terms: string[] }>({
+ llm: { ollama: { baseUrl: ol.url } },
+ model: "qwen2.5vl:7b",
+ system: "Read the frame.",
+ user: "One frame.",
+ schema,
+ images: [{ mediaType: "image/jpeg", data }],
+ });
+ assert.deepEqual(out, { terms: ["stack"] });
+ assert.deepEqual(ol.requests[0].messages[1].images, [data]);
+ const est = structuredPromptEstimate({ system: "s", user: "u", schema, images: [{ mediaType: "image/jpeg", data }] });
+ assert.equal(est, structuredPromptEstimate({ system: "s", user: "u", schema }) + IMAGE_TOKEN_ESTIMATE);
+ // The base64 itself is never counted as text.
+ assert.ok(promptEstimate({ messages: [{ role: "user", content: "u", images: ["A".repeat(100_000)] }] }) < 2000);
+ } finally {
+ await ol.close();
+ }
+});
diff --git a/common/lib/llm/structured.ts b/common/lib/llm/structured.ts
@@ -47,12 +47,18 @@ export function closeSchema<T>(schema: T): T {
return out as T;
}
+// An image the model reads with the question (release 30, the frame scan):
+// base64 bytes and their media type. Claude gets image blocks before the
+// text; ollama gets the user message's `images`.
+export type AnswerImage = { mediaType: "image/jpeg" | "image/png"; data: string };
+
type Opts = {
llm: LlmConfig;
model: string;
system: string;
user: string;
schema: object;
+ images?: AnswerImage[];
meter?: Meter;
signal?: AbortSignal;
maxTokens?: number;
@@ -81,8 +87,17 @@ async function claudeTry<T>(client: AnthropicClient, o: Opts, strict: boolean):
input_schema: strict ? closeSchema(o.schema) : o.schema,
...(strict ? { strict: true } : {}),
};
+ const text = strict ? `${o.user}\n\n${ASK}` : o.user;
let messages: { role: string; content: string | ContentBlock[] }[] = [
- { role: "user", content: strict ? `${o.user}\n\n${ASK}` : o.user },
+ {
+ role: "user",
+ content: o.images?.length
+ ? [
+ ...o.images.map((img) => ({ type: "image", source: { type: "base64", media_type: img.mediaType, data: img.data } })),
+ { type: "text", text },
+ ]
+ : text,
+ },
];
let res: MessagesResponse | undefined;
for (let attempt = 0; attempt < (strict ? 2 : 1); attempt++) {
@@ -108,11 +123,11 @@ async function claudeTry<T>(client: AnthropicClient, o: Opts, strict: boolean):
// What a local structuredAnswer's prompt is estimated at — the very request
// localAnswer sends (its messages and its format), counted as ollamaChat
// counts it against the cap (release 28 Q3: a caller fits its text first).
-export function structuredPromptEstimate(o: { system: string; user: string; schema: object }): number {
+export function structuredPromptEstimate(o: { system: string; user: string; schema: object; images?: AnswerImage[] }): number {
return promptEstimate({
messages: [
{ role: "system", content: o.system },
- { role: "user", content: o.user },
+ { role: "user", content: o.user, ...(o.images?.length ? { images: o.images.map((i) => i.data) } : {}) },
],
format: o.schema,
});
@@ -128,7 +143,7 @@ async function localAnswer<T>(o: Opts): Promise<T> {
model: o.model,
messages: [
{ role: "system", content: o.system },
- { role: "user", content: o.user },
+ { role: "user", content: o.user, ...(o.images?.length ? { images: o.images.map((i) => i.data) } : {}) },
],
format: o.schema,
signal: o.signal,
diff --git a/common/lib/queueKeys.ts b/common/lib/queueKeys.ts
@@ -59,6 +59,12 @@ export const TTS_QUEUE = "tts";
// together (their sweeps would race the day's cap).
export const REPORT_TICK_QUEUE = "report-tick";
+// A frame scan on the Claude API (release 30, controller/frameScan.ts): one
+// at a time machine-wide, apart from the generation lanes — a 4-hour stream's
+// decode and its reads must not hold `draft:api` for an article's draft. A scan
+// on a LOCAL vision model goes on `draft:local` instead (the GPU's lane).
+export const FRAME_SCAN_QUEUE = "frames";
+
// Per-channel queue for channel-local bookkeeping jobs (clean/clear/verify).
export function channelQueueKey(slug: string): string {
return `channel:${slug}`;
diff --git a/common/lib/settingsDocs.ts b/common/lib/settingsDocs.ts
@@ -31,6 +31,7 @@ import {
GENERATION_ROUTES_FIELD_DOCS,
GENERATION_CUT_FIELD_DOCS,
GENERATION_TRIAGE_FIELD_DOCS,
+ GENERATION_FRAMES_FIELD_DOCS,
GENERATION_SETTINGS_FIELD_DOCS,
GENERATION_WEB_FIELD_DOCS,
GENERATION_VERDICTS_FIELD_DOCS,
@@ -305,6 +306,7 @@ export function blockTables(d: SiteSettings): Partial<Record<keyof SiteSettings,
{ path: "generation.verdicts.bar", docs: GENERATION_VERDICT_BAR_FIELD_DOCS, defaults: fromObject(d.generation.verdicts.bar) },
{ path: "generation.verdicts.window", docs: GENERATION_VERDICT_WINDOW_FIELD_DOCS, defaults: fromObject(d.generation.verdicts.window) },
{ path: "generation.triage", docs: GENERATION_TRIAGE_FIELD_DOCS, defaults: fromObject(d.generation.triage) },
+ { path: "generation.frames", docs: GENERATION_FRAMES_FIELD_DOCS, defaults: fromObject(d.generation.frames) },
],
};
}
diff --git a/common/lib/settingsSchema.ts b/common/lib/settingsSchema.ts
@@ -92,6 +92,7 @@ export {
GENERATION_VERDICT_BAR_FIELD_DOCS,
GENERATION_VERDICT_WINDOW_FIELD_DOCS,
GENERATION_TRIAGE_FIELD_DOCS,
+ GENERATION_FRAMES_FIELD_DOCS,
type GenerationSettings,
} from "./generationSettings";
export { ORPHEUS_TTS_SETTINGS_FIELD_DOCS, TTS_SETTINGS_FIELD_DOCS, type TtsSettings } from "./ttsSettings";
diff --git a/common/lib/sidecar-server.test.ts b/common/lib/sidecar-server.test.ts
@@ -10,6 +10,7 @@ import "./archiveOrg-server";
import "./attribution-server";
import "./diarization-server";
import "./digest-server";
+import "./frameScan-server";
import "./metadataHistory-server";
import "./transcriptPin-server";
import "./wayback-server";
@@ -44,7 +45,7 @@ async function scratch(): Promise<string> {
return mkdtemp(path.join(os.tmpdir(), "sidecar-"));
}
-test("every declared sidecar filename escapes SUB_FILE_RE, and all twelve are declared", () => {
+test("every declared sidecar filename escapes SUB_FILE_RE, and all fourteen are declared", () => {
assert.deepEqual([...SIDECAR_FILENAMES].sort(), [
"ai-digest.json",
"ai-digest.overrides.json",
@@ -55,6 +56,7 @@ test("every declared sidecar filename escapes SUB_FILE_RE, and all twelve are de
"do-not-clean.json",
"download-outcome.json",
"exclude-truncated-check.json",
+ "frame-scan.poker.json",
"metadata.history.json",
"transcribe-outcome.json",
"transcript-pin.json",
diff --git a/common/testing/README.md b/common/testing/README.md
@@ -13,6 +13,8 @@ transcript, channel or person goes in these fixtures, ever.
| --- | --- |
| `llm/fakeAnthropic.mjs` | A fake Messages API: scripted turns (`textTurn`, `toolTurn`, `pauseTurn`, `webSearchBlocks`, `thinkingBlock`, `errorTurn`, or a function of the request). It enforces the Sonnet 5.5 400s (temperature, forced `tool_choice`, `thinking: disabled`), signs thinking blocks so an edited history is refused, needs `x-api-key` = `FAKE_KEY`, and estimates usage, cache reads included. |
| `llm/fakeOllama.mjs` | A fake ollama: `/api/chat` with `format` or tools, the 8k prompt cap and the 12k `num_ctx` cap as 400s, `stream: true` refused, `faultReply()` (`done: false`), the `keep_alive: 0` unload, `/api/tags`, `/api/ps`. |
+| images (both fakes) | Release 30: the fake Anthropic takes `image` blocks (base64 JPEG/PNG/GIF/WebP whose bytes match the media type, in a user turn — else a 400) and counts each at (w·h)/750 tokens; the fake ollama takes a message's `images` (base64 images — else a 400), each counted at `IMAGE_TOKENS` (1200) against the cap. `imagesOf(body)` (each) decodes a request's images with their sizes, for a scripted answer or an assertion. |
+| `frames/syntheticPoker.mjs` | Release 30: a synthetic poker stream for the frame scan — `makeSyntheticPokerStream(dir)` paints a fake client (a lobby, a table whose numbers change, a break, a bust) with ffmpeg's `color` + `drawtext` into a 210-s H.264 file (a keyframe every 2 s); `pokerTruthAt(t)` is what it shows at `t` (a fake model's answer), `SPOKEN_CUES` what the streamer "said" (two numbers that agree with the frames, one that does not). Nothing real: no stream, no client, no frames from the corpus. |
| `draft/corpus.mjs` | Two channels of recordings with cues (`CHANNELS`), posts (`POSTS`), `ORIGIN`, `momentHref`, `postHref`, `cuesOf`, `recordOf`, and `writeDraftCorpus(dir)` — a composed public dir for the MCP's `--local`. |
| `draft/sweeps/*.md` | sweep.md variants: `basic` (the canonical shape), `quotes-in-claims` (claims that carry quoted words — the rule they break), `multi-quote` (several quotes per link, several links per item), `posts-only`, `paragraphs` (paragraphs and a sub-heading between findings, a trailing Coverage section), `inexact` (a reversed quote fuzzy recall passes, a quote 200 s from its link, an exact one), `two-line` (a finding's quote and link on the lines under its claim), `fragment` (verbatim quotes that stop mid-thought — on a function word, or under four words — and one whole sentence). |
| `draft/reports/`, `draft/manifests/` | `basic`, `posts-only`, `paragraphs` converted (`report.json`) and taken to a video manifest, as the converters make them today. |
diff --git a/common/testing/fakes.test.ts b/common/testing/fakes.test.ts
@@ -19,8 +19,11 @@ import {
turn,
textBlock,
webSearchBlocks,
+ imagesOf,
+ imageTokens,
} from "./llm/fakeAnthropic.mjs";
-import { faultReply, jsonReply, startFakeOllama, toolCallsReply } from "./llm/fakeOllama.mjs";
+import { faultReply, jsonReply, startFakeOllama, toolCallsReply, imagesOf as ollamaImagesOf } from "./llm/fakeOllama.mjs";
+import { execFileSync } from "node:child_process";
import { CHANNELS, cuesOf, writeDraftCorpus } from "./draft/corpus.mjs";
import { DERIVED, SWEEPS, convertFixture, deriveFixture } from "./draft/derive";
import { validateReport } from "../lib/report/validate";
@@ -181,6 +184,49 @@ test("fake ollama: format and tool replies, the 8k and num_ctx caps, stream refu
}
});
+// ─── Images (release 30, the frame scan) ───
+
+// A tiny real JPEG and PNG, made by ffmpeg (no binary fixture in the tree).
+function tinyImage(kind: "mjpeg" | "png"): string {
+ return execFileSync("ffmpeg", ["-hide_banner", "-loglevel", "error", "-f", "lavfi", "-i", "color=c=red:s=64x36:d=1", "-frames:v", "1", "-c:v", kind, "-f", "image2pipe", "pipe:1"]).toString("base64");
+}
+
+test("fake Anthropic: an image block must be base64 of the type it names, in a user turn; usage counts it by size", async () => {
+ const jpeg = tinyImage("mjpeg");
+ const png = tinyImage("png");
+ const api = await startFakeAnthropic({ turns: [textTurn("ok")] });
+ try {
+ const img = (media_type: string, data: string) => ({ type: "image", source: { type: "base64", media_type, data } });
+ const ask = (content: unknown[], role = "user") => post(`${api.url}/v1/messages`, { model: "claude-haiku-4-5", max_tokens: 10, messages: [{ role, content }] }, auth);
+ assert.equal((await ask([img("image/jpeg", png)])).status, 400);
+ assert.equal((await ask([img("image/png", "not base64!")])).status, 400);
+ assert.equal((await ask([img("image/tiff", jpeg)])).status, 400);
+ const ok = await ask([img("image/jpeg", jpeg), { type: "text", text: "read it" }]);
+ assert.equal(ok.status, 200);
+ assert.ok(ok.json.usage.input_tokens >= imageTokens(64, 36) && ok.json.usage.input_tokens < 100, String(ok.json.usage.input_tokens));
+ assert.deepEqual(imagesOf(api.requests[api.requests.length - 1]).map((i) => [i.mediaType, i.width, i.height]), [["image/jpeg", 64, 36]]);
+ assert.equal(imageTokens(1280, 720), 1229);
+ } finally {
+ await api.close();
+ }
+});
+
+test("fake ollama: a message's images must be base64 images, each counted at a fixed cost against the cap", async () => {
+ const jpeg = tinyImage("mjpeg");
+ const ol = await startFakeOllama({ models: ["qwen2.5vl:7b"], turns: [jsonReply({ ok: true })] });
+ try {
+ const base = { model: "qwen2.5vl:7b", stream: false, messages: [{ role: "user", content: "read", images: [jpeg] }] };
+ assert.equal((await post(`${ol.url}/api/chat`, { ...base, messages: [{ role: "user", content: "read", images: ["!!"] }] })).status, 400);
+ assert.equal((await post(`${ol.url}/api/chat`, { ...base, messages: [{ role: "user", content: "read", images: Array(7).fill(jpeg) }] })).status, 400);
+ const ok = await post(`${ol.url}/api/chat`, base);
+ assert.equal(ok.status, 200);
+ assert.ok(ok.json.prompt_eval_count >= 1200 && ok.json.prompt_eval_count < 1300);
+ assert.equal(ollamaImagesOf(ol.requests[ol.requests.length - 1])[0].width, 64);
+ } finally {
+ await ol.close();
+ }
+});
+
// ─── Fixtures ───
test("fixtures: every sweep converts with no problems, and every report validates", async () => {
diff --git a/common/testing/frames/syntheticPoker.d.mts b/common/testing/frames/syntheticPoker.d.mts
@@ -0,0 +1,22 @@
+export const SYNTH_TOURNAMENT: string;
+export const SYNTH_DURATION: number;
+export const SYNTH_SPANS: {
+ from: number;
+ to: number;
+ phase: string;
+ tournament?: Record<string, unknown>;
+ hero?: Record<string, unknown>;
+ event?: string;
+}[];
+export function pokerTruthAt(t: number): {
+ phase: string;
+ tournament: Record<string, unknown>;
+ hero: Record<string, unknown>;
+ hand: Record<string, unknown>;
+ event: string | null;
+};
+export function makeSyntheticPokerStream(
+ dir: string,
+ o?: { name?: string; width?: number; height?: number; ffmpeg?: string },
+): Promise<{ file: string; duration: number }>;
+export const SPOKEN_CUES: { start: number; end: number; text: string }[];
diff --git a/common/testing/frames/syntheticPoker.mjs b/common/testing/frames/syntheticPoker.mjs
@@ -0,0 +1,99 @@
+// A synthetic poker stream for the frame scan's tests (release 30, lane P).
+// No real stream, no real poker client: ffmpeg's `color` source and
+// `drawtext` paint a fake client — a lobby, a table whose numbers change on a
+// schedule, a break screen, a bust — into a short H.264 file with a keyframe
+// every two seconds, so the scan's keyframe-only sampling has something to
+// find. `pokerTruthAt(t)` is what each moment shows, for the fake models'
+// answers, and `SPOKEN_CUES` the transcript the streamer "said".
+//
+// const { file, duration } = await makeSyntheticPokerStream(dir);
+// pokerTruthAt(95) → { phase: "table", tournament: {...}, hero: {...} }
+
+import { execFile } from "node:child_process";
+import { promisify } from "node:util";
+import path from "node:path";
+
+const run = promisify(execFile);
+
+export const SYNTH_TOURNAMENT = "Synthetic Cup";
+export const SYNTH_DURATION = 210;
+
+// What the fake client shows, by time. Each span is one still picture.
+export const SYNTH_SPANS = [
+ { from: 0, to: 30, phase: "lobby", tournament: { name: SYNTH_TOURNAMENT, totalPlayers: 120, playersLeft: 120 } },
+ { from: 30, to: 90, phase: "table", tournament: { name: SYNTH_TOURNAMENT, level: 3, smallBlind: 100, bigBlind: 200, playersLeft: 85, totalPlayers: 120 }, hero: { stack: 20000 } },
+ { from: 90, to: 120, phase: "table", tournament: { name: SYNTH_TOURNAMENT, level: 4, smallBlind: 150, bigBlind: 300, playersLeft: 60, totalPlayers: 120 }, hero: { stack: 41000 } },
+ { from: 120, to: 150, phase: "table", tournament: { name: SYNTH_TOURNAMENT, level: 5, smallBlind: 200, bigBlind: 400, playersLeft: 9, totalPlayers: 120 }, hero: { stack: 9000 } },
+ { from: 150, to: 180, phase: "break" },
+ { from: 180, to: 200, phase: "table", tournament: { name: SYNTH_TOURNAMENT, level: 6, smallBlind: 300, bigBlind: 600, playersLeft: 7, totalPlayers: 120 }, hero: { stack: 0 }, event: "eliminated" },
+ { from: 200, to: 210, phase: "lobby", tournament: { name: SYNTH_TOURNAMENT, totalPlayers: 120, playersLeft: 6 } },
+];
+
+/** The reading a perfect model gives at `t` (the answer schema's shape, `frame` left to the caller). */
+export function pokerTruthAt(t) {
+ const s = SYNTH_SPANS.find((x) => t >= x.from && t < x.to) ?? SYNTH_SPANS[SYNTH_SPANS.length - 1];
+ return {
+ phase: s.phase,
+ tournament: s.tournament ? { ...s.tournament } : {},
+ hero: s.hero ? { ...s.hero } : {},
+ hand: {},
+ event: s.event ?? null,
+ };
+}
+
+// The line a span paints.
+function spanText(s) {
+ if (s.phase === "break") return "BREAK back in 5 minutes";
+ const t = s.tournament ?? {};
+ if (s.phase === "lobby") return `LOBBY ${t.name} Players ${t.playersLeft} of ${t.totalPlayers}`;
+ return `${t.name} Level ${t.level} Blinds ${t.smallBlind} ${t.bigBlind} Left ${t.playersLeft} of ${t.totalPlayers} Stack ${s.hero?.stack ?? ""}${s.event ? " ELIMINATED" : ""}`;
+}
+
+const COLORS = { lobby: "0x123456", table: "0x0b5d1e", break: "0x333333", other: "0x000000" };
+
+/** Write the stream into `dir`; answers its path and length. */
+export async function makeSyntheticPokerStream(dir, o = {}) {
+ const file = path.join(dir, o.name ?? "synthetic-poker.mp4");
+ const w = o.width ?? 1280;
+ const h = o.height ?? 720;
+ // One color source per span, concatenated, each with its own text.
+ const inputs = [];
+ const chains = [];
+ SYNTH_SPANS.forEach((s, i) => {
+ inputs.push("-f", "lavfi", "-i", `color=c=${COLORS[s.phase]}:s=${w}x${h}:r=2:d=${s.to - s.from}`);
+ chains.push(`[${i}:v]drawtext=text='${spanText(s)}':fontsize=36:fontcolor=white:x=40:y=${h / 2}[v${i}]`);
+ });
+ const concat = `${SYNTH_SPANS.map((_, i) => `[v${i}]`).join("")}concat=n=${SYNTH_SPANS.length}:v=1:a=0[out]`;
+ await run(o.ffmpeg ?? "ffmpeg", [
+ "-hide_banner",
+ "-loglevel",
+ "error",
+ "-y",
+ ...inputs,
+ "-filter_complex",
+ `${chains.join(";")};${concat}`,
+ "-map",
+ "[out]",
+ "-c:v",
+ "libx264",
+ "-preset",
+ "ultrafast",
+ "-g",
+ "4",
+ "-pix_fmt",
+ "yuv420p",
+ file,
+ ]);
+ return { file, duration: SYNTH_DURATION };
+}
+
+// What the streamer says over the synthetic stream: numbers in words, as an
+// ASR transcript writes them. Two agree with the client; the last does not
+// (the frames read 9 left there): a flag.
+export const SPOKEN_CUES = [
+ { start: 5, end: 9, text: "welcome back we're in the synthetic cup" },
+ { start: 31, end: 35, text: "eighty five players left and" },
+ { start: 35, end: 38, text: "the buy in is two hundred bucks" },
+ { start: 92, end: 96, text: "I have forty one thousand now" },
+ { start: 125, end: 130, text: "we're at the final table, there are four players left" },
+];
diff --git a/common/testing/llm/fakeAnthropic.d.mts b/common/testing/llm/fakeAnthropic.d.mts
@@ -33,3 +33,7 @@ export type FakeAnthropic = {
close(): Promise<void>;
};
export function startFakeAnthropic(opts?: { key?: string; strictModels?: string[]; turns?: FakeScripted[] }): Promise<FakeAnthropic>;
+export function imageSize(buf: Buffer): { width: number; height: number } | null;
+export function imageTokens(width: number, height: number): number;
+export function imagesOf(body: any): { mediaType: string; bytes: Buffer; width: number; height: number }[];
+export function imageProblem(body: any): string | null;
diff --git a/common/testing/llm/fakeAnthropic.mjs b/common/testing/llm/fakeAnthropic.mjs
@@ -14,6 +14,8 @@
// turn carrying thinking whose history was edited (or whose block was) is refused,
// so a client must keep history append-only once a thinking block appears;
// - `max_tokens` is required, and `model`, and a non-empty `messages`.
+// - an image block (release 30) is base64 of a JPEG/PNG/GIF/WebP whose bytes
+// match its media type, in a user turn; its usage is (w·h)/750 tokens.
// A missing or wrong `x-api-key` is a 401 authentication_error.
//
// A scripted turn is a response (helpers below), an error (`errorTurn`), or a
@@ -118,6 +120,94 @@ export function signatureProblem(body) {
return null;
}
+// ─── Images (release 30, the frame scan) ───
+
+// A base64 image's size from its bytes (JPEG SOF, PNG IHDR), or null.
+export function imageSize(buf) {
+ if (buf.length >= 24 && buf.readUInt32BE(0) === 0x89504e47) return { width: buf.readUInt32BE(16), height: buf.readUInt32BE(20) };
+ if (buf.length < 4 || buf[0] !== 0xff || buf[1] !== 0xd8) return null;
+ let i = 2;
+ while (i + 9 < buf.length) {
+ if (buf[i] !== 0xff) return null;
+ const m = buf[i + 1];
+ const len = buf.readUInt16BE(i + 2);
+ if (m >= 0xc0 && m <= 0xcf && m !== 0xc4 && m !== 0xc8 && m !== 0xcc) return { height: buf.readUInt16BE(i + 5), width: buf.readUInt16BE(i + 7) };
+ i += 2 + len;
+ }
+ return null;
+}
+
+// What an image costs in input tokens: (w·h)/750 after the API's downscale
+// (long edge ≤ 1568, ≤ ~1.15 MP).
+export function imageTokens(width, height) {
+ let s = 1;
+ if (Math.max(width, height) > 1568) s = 1568 / Math.max(width, height);
+ if (width * height * s * s > 1_150_000) s = Math.sqrt(1_150_000 / (width * height));
+ return Math.ceil((width * s * height * s) / 750);
+}
+
+const IMAGE_TYPES = ["image/jpeg", "image/png", "image/gif", "image/webp"];
+
+// Every image block of a request's messages, decoded: {mediaType, bytes, width, height}.
+export function imagesOf(body) {
+ const out = [];
+ for (const m of Array.isArray(body?.messages) ? body.messages : []) {
+ if (!Array.isArray(m.content)) continue;
+ for (const b of m.content) {
+ if (b?.type !== "image") continue;
+ const bytes = Buffer.from(String(b.source?.data ?? ""), "base64");
+ out.push({ mediaType: b.source?.media_type, bytes, ...(imageSize(bytes) ?? { width: 0, height: 0 }) });
+ }
+ }
+ return out;
+}
+
+// An image block the real API refuses: not base64, an unknown media type, no
+// data, bytes that are not the image type named, or an image in an assistant turn.
+export function imageProblem(body) {
+ const msgs = Array.isArray(body.messages) ? body.messages : [];
+ for (let i = 0; i < msgs.length; i++) {
+ const m = msgs[i];
+ if (!Array.isArray(m.content)) continue;
+ for (let j = 0; j < m.content.length; j++) {
+ const b = m.content[j];
+ if (b?.type !== "image") continue;
+ const at = `messages.${i}.content.${j}`;
+ if (m.role !== "user") return `${at}: an image is only allowed in a user turn`;
+ const src = b.source ?? {};
+ if (src.type !== "base64") return `${at}.source.type: the fake takes base64 images only`;
+ if (!IMAGE_TYPES.includes(src.media_type)) return `${at}.source.media_type: ${src.media_type} is not an image type`;
+ if (typeof src.data !== "string" || !src.data || /[^A-Za-z0-9+/=]/.test(src.data)) return `${at}.source.data: not base64`;
+ const bytes = Buffer.from(src.data, "base64");
+ const size = imageSize(bytes);
+ const isPng = bytes.length > 4 && bytes.readUInt32BE(0) === 0x89504e47;
+ const isJpeg = bytes.length > 2 && bytes[0] === 0xff && bytes[1] === 0xd8;
+ if ((src.media_type === "image/jpeg" && !isJpeg) || (src.media_type === "image/png" && !isPng) || !size)
+ return `${at}: the image bytes are not a ${src.media_type}`;
+ }
+ }
+ return null;
+}
+
+// A request's messages with every image's data replaced by its token cost, for the usage estimate.
+function withoutImageData(messages) {
+ let tokens = 0;
+ const stripped = (messages ?? []).map((m) =>
+ Array.isArray(m.content)
+ ? {
+ ...m,
+ content: m.content.map((b) => {
+ if (b?.type !== "image") return b;
+ const size = imageSize(Buffer.from(String(b.source?.data ?? ""), "base64"));
+ tokens += size ? imageTokens(size.width, size.height) : 1600;
+ return { type: "image" };
+ }),
+ }
+ : m,
+ );
+ return { stripped, tokens };
+}
+
function requestProblem(body) {
if (!body || typeof body !== "object") return "body: not JSON";
if (!body.model) return "model: required";
@@ -163,7 +253,7 @@ export async function startFakeAnthropic(opts = {}) {
if (req.headers["x-api-key"] !== key) return apiError(res, 401, "authentication_error", "invalid x-api-key");
if (!req.headers["anthropic-version"])
return apiError(res, 400, "invalid_request_error", "anthropic-version: header required");
- const problem = requestProblem(body) ?? strictModelProblem(body, strictModels) ?? signatureProblem(body);
+ const problem = requestProblem(body) ?? strictModelProblem(body, strictModels) ?? signatureProblem(body) ?? imageProblem(body);
if (problem) return apiError(res, 400, "invalid_request_error", problem);
let next = script.shift();
@@ -184,8 +274,10 @@ export async function startFakeAnthropic(opts = {}) {
// (same system and tools, its messages a prefix of these) and writes the
// rest up to its last message.
const head = JSON.stringify([body.system ?? null, body.tools ?? null]);
- const total = tok([body.system ?? null, body.tools ?? null, body.messages]);
- const last = tok(body.messages[body.messages.length - 1]);
+ // An image counts at its token cost, not its base64.
+ const { stripped, tokens: imgTokens } = withoutImageData(body.messages);
+ const total = tok([body.system ?? null, body.tools ?? null, stripped]) + imgTokens;
+ const last = tok(stripped[stripped.length - 1]) + withoutImageData(body.messages.slice(-1)).tokens;
const cached = hasCacheControl(body);
let read = 0;
if (cached) {
diff --git a/common/testing/llm/fakeOllama.d.mts b/common/testing/llm/fakeOllama.d.mts
@@ -32,3 +32,6 @@ export function startFakeOllama(opts?: {
numCtxCap?: number;
turns?: OllamaScripted[];
}): Promise<FakeOllama>;
+export const IMAGE_TOKENS: number;
+export function imagesOf(body: any): { bytes: Buffer; width: number; height: number }[];
+export function imageProblem(body: any): string | null;
diff --git a/common/testing/llm/fakeOllama.mjs b/common/testing/llm/fakeOllama.mjs
@@ -14,17 +14,58 @@
// card fails its test instead. `stream: true` is refused: the clients here read
// one JSON answer. A scripted `faultReply()` answers `done: false` — what a GPU
// fault looks like — which a client must read as a failure, not an answer.
+// A message's `images` (release 30) must be base64 of an image; each counts
+// IMAGE_TOKENS against the cap.
//
// A scripted turn is a reply (helpers below) or a function (body, ctx) → reply.
// When the script runs out the server answers 500 "fake: script exhausted".
import http from "node:http";
+import { imageSize } from "./fakeAnthropic.mjs";
export const PROMPT_CAP_TOKENS = 8192;
export const NUM_CTX_CAP = 12288;
const tok = (v) => Math.ceil(JSON.stringify(v ?? "").length / 4);
+// A vision model's image (release 30): counted at a fixed cost, not its base64.
+export const IMAGE_TOKENS = 1200;
+
+// Every message's `images`, decoded: {bytes, width, height}.
+export function imagesOf(body) {
+ const out = [];
+ for (const m of Array.isArray(body?.messages) ? body.messages : [])
+ for (const d of Array.isArray(m.images) ? m.images : []) {
+ const bytes = Buffer.from(String(d), "base64");
+ out.push({ bytes, ...(imageSize(bytes) ?? { width: 0, height: 0 }) });
+ }
+ return out;
+}
+
+// What ollama refuses: an `images` entry that is not base64 of an image.
+export function imageProblem(body) {
+ for (const [i, m] of (Array.isArray(body?.messages) ? body.messages : []).entries()) {
+ if (m.images === undefined) continue;
+ if (!Array.isArray(m.images)) return `messages.${i}.images: not a list`;
+ for (const d of m.images) {
+ if (typeof d !== "string" || !d || /[^A-Za-z0-9+/=]/.test(d)) return `messages.${i}.images: not base64`;
+ if (!imageSize(Buffer.from(d, "base64"))) return `messages.${i}.images: not an image`;
+ }
+ }
+ return null;
+}
+
+const promptTokensOf = (body) => {
+ let images = 0;
+ const messages = (body.messages ?? []).map((m) => {
+ if (!Array.isArray(m?.images)) return m;
+ images += m.images.length;
+ const { images: _drop, ...rest } = m;
+ return rest;
+ });
+ return tok([messages, body.tools ?? null, body.format ?? null]) + images * IMAGE_TOKENS;
+};
+
export const reply = (content, extra = {}) => ({ message: { role: "assistant", content }, done: true, ...extra });
// A `format`-schema answer: the content is the JSON text.
@@ -91,7 +132,9 @@ export async function startFakeOllama(opts = {}) {
const numCtx = body.options?.num_ctx;
if (typeof numCtx === "number" && numCtx > numCtxCap)
return send(res, 400, { error: `fake: num_ctx ${numCtx} is over the ${numCtxCap} cap` });
- const promptTokens = tok([body.messages, body.tools ?? null, body.format ?? null]);
+ const bad = imageProblem(body);
+ if (bad) return send(res, 400, { error: `fake: ${bad}` });
+ const promptTokens = promptTokensOf(body);
if (promptTokens > promptCap)
return send(res, 400, { error: `fake: prompt ~${promptTokens} tokens is over the ${promptCap} cap` });
diff --git a/editor/app/jobs/components/JobProgressBars.tsx b/editor/app/jobs/components/JobProgressBars.tsx
@@ -162,6 +162,7 @@ const METRIC_LABELS: Record<JobProgressMetric, string> = {
turns: "Model turns",
cards: "Cards",
entries: "Entries",
+ frames: "Frames",
};
// Per-metric glyph for the compact line ("↓ 5/10").
@@ -175,6 +176,7 @@ const METRIC_PREFIX: Record<JobProgressMetric, string> = {
turns: "\u21c4 ",
cards: "\u25a4 ",
entries: "\u2261 ",
+ frames: "\u25a3 ",
};
const METRIC_FILL: Record<JobProgressMetric, string> = {
@@ -187,6 +189,7 @@ const METRIC_FILL: Record<JobProgressMetric, string> = {
turns: "bg-info",
cards: "bg-success/60",
entries: "bg-success/60",
+ frames: "bg-info/60",
};
// One-line textual summary of a job's batch progress, e.g. "↓ 5/10 · ~2m left"
diff --git a/mcp/src/generation.ts b/mcp/src/generation.ts
@@ -44,7 +44,8 @@ export type GenerationPolicy = PlanGeneration & {
export type GenerationUsageDay = { day: string; usd: number; jobs: number; daily: number };
// The tasks `generate` takes: the policy's (research included, S11).
-export const GENERATE_TASKS = [...new Set<string>([...GENERATION_TASKS, "research"])];
+// Not `frames`: a frame scan is `frame-scan`, not a generation of an article.
+export const GENERATE_TASKS = [...new Set<string>([...GENERATION_TASKS.filter((t) => t !== "frames"), "research"])];
const ARTICLE_RE = /^[a-z0-9][a-z0-9-]{0,63}$/;
const JOB_RE = /^[A-Za-z0-9_-]+$/;
diff --git a/settings.json.example b/settings.json.example
@@ -255,7 +255,8 @@
"threads": "local",
"youtube": "local",
"social": "local",
- "verdicts": "local"
+ "verdicts": "local",
+ "frames": "api"
},
"models": {
"api": "claude-sonnet-5-5",
@@ -308,6 +309,12 @@
"weak": 3,
"maxEscalationsPerDay": 3,
"maxCandidates": 40
+ },
+ "frames": {
+ "apiModel": "claude-haiku-4-5",
+ "localModel": "qwen2.5vl:7b",
+ "maxUsd": 5,
+ "everySeconds": 10
}
}
}