import { readFileSync, statSync } from "node:fs"; import os from "node:os"; import path from "node:path"; import { getPaths } from "yt-dlp-transcript-common/lib/paths"; import { callCountOf } from "@/lib/model-log"; import { listPendingArticles } from "yt-dlp-transcript-common/lib/report/registry"; import { iterationLabel, iterationUsd, readIterationFile, readIterations, type Iteration, type IterationsCurrent, } from "yt-dlp-transcript-common/lib/report/iterations"; import { dayUsage } from "yt-dlp-transcript-common/controller/generationUsage"; import { DEFAULT_API_KEY_FILE, GENERATION_PRESETS, GENERATION_ROUTES, GENERATION_TASKS, sanitizeGeneration, type GenerationSettings, } from "yt-dlp-transcript-common/lib/generationSettings"; import { PRICES } from "yt-dlp-transcript-common/lib/llm/prices"; import { agentToken } from "@/lib/annotations/agentAuth.mjs"; import { DEFAULT_PROJECTS_ROOT, REPO_ROOT, chainStart, chainStepsOf, doneSteps } from "@/lib/report/chain.mjs"; import { recentJobs, type Job } from "@/lib/jobs"; import { sitesPaths } from "./sites"; import { REPORTS_ROOT } from "@/lib/paths.mjs"; // GENERATION, AS UMTOOL SEES IT (release 27 S8): an article's iterations, the // policy, the editor's channels, and the editor's report-draft jobs. // // UMTOOL WRITES NOTHING OF THE CORPUS HERE. A generation is a `report-draft` // job the EDITOR runs and writes (POST /api/ops/report-draft); the policy is // the editor's settings (POST /api/ops/settings); a job is cancelled there // (POST /api/ops/job). Each call carries the shared WORKER_TOKEN, which never // reaches the browser. What this module reads directly is read-only: the // iterations store (common's reader) and the usage ledger's day total. // // The API KEY is never read, shown or accepted: the policy names the key // FILE's path and whether it exists — a stat, never an open. // // SERVER-ONLY. const DEFAULT_EDITOR = "http://localhost:3001"; export function editorUrl(): string { return (process.env.ARCHILYZER_EDITOR_URL ?? DEFAULT_EDITOR).replace(/\/+$/, ""); } /** * Why the editor could not be asked, or what it said no with: * no-token umtool has no WORKER_TOKEN, so it never asked * unreachable nothing answered (refused, reset, or no answer in time) * editor-token the editor answered 503: its own WORKER_TOKEN is not set, so * its ops surface is off * denied the editor answered 401: the two tokens differ * refused the editor answered and said no (its words are the message) */ export type EditorErrorReason = "no-token" | "unreachable" | "editor-token" | "denied" | "refused"; export class EditorError extends Error { constructor( message: string, readonly status: number, readonly reason: EditorErrorReason = "refused", ) { super(message); } } /** A GET's answer is kept this long per URL: a page and the rail asking at once ask once. */ export const EDITOR_MEMO_MS = 2000; /** A GET that has not answered in this long is an editor that is not answering. */ export const EDITOR_GET_TIMEOUT_MS = 5000; /** * A POST waits longer: it may have done its write when the answer is late, and * calling that "unreachable" invites a second click that writes twice. */ export const EDITOR_POST_TIMEOUT_MS = 30_000; // The memo, ON globalThis (one per process, not one per Next bundle -- the // lesson of P2a's project cache). It holds the PROMISE, so two callers in the // same moment share one request, and a refusal is kept as long as an answer: // an editor that is down is asked once per 2 s, not once per caller. type Memo = Map }>; const gm = globalThis as typeof globalThis & { __umtoolEditorMemo?: Memo }; const memo: Memo = (gm.__umtoolEditorMemo ??= new Map()); /** Forget every kept answer (a write went through; the next read asks again). */ export function clearEditorMemo(): void { memo.clear(); } async function askOnce(route: string, init: { method?: "GET" | "POST"; body?: unknown }, timeoutMs: number): Promise { const token = agentToken(); if (!token) { throw new EditorError( "WORKER_TOKEN is not set, so the editor cannot be asked. Set it to the same value the editor runs with.", 400, "no-token", ); } let res: Response; try { res = await fetch(`${editorUrl()}${route}`, { method: init.method ?? "GET", headers: { authorization: `Bearer ${token}`, "content-type": "application/json" }, ...(init.body !== undefined ? { body: JSON.stringify(init.body) } : {}), cache: "no-store", signal: AbortSignal.timeout(timeoutMs), }); } catch (err) { const e = err as Error; if (e.name === "TimeoutError" || e.name === "AbortError") { throw new EditorError(`the editor at ${editorUrl()} did not answer in ${Math.round(timeoutMs / 1000)} s`, 504, "unreachable"); } throw new EditorError(`could not reach the editor at ${editorUrl()}: ${e.message}`, 502, "unreachable"); } let body: Record; try { body = (await res.json()) as Record; } catch (err) { // The answer started and then stopped (or was not JSON). A timeout here is // still an editor that did not answer. const e = err as Error; if (e.name === "TimeoutError" || e.name === "AbortError") { throw new EditorError(`the editor at ${editorUrl()} did not answer in ${Math.round(timeoutMs / 1000)} s`, 504, "unreachable"); } body = {}; } if (!res.ok || body.ok === false) { const status = res.status >= 400 ? res.status : 400; const reason: EditorErrorReason = res.status === 503 ? "editor-token" : res.status === 401 ? "denied" : "refused"; throw new EditorError(String(body.error ?? `the editor answered HTTP ${res.status}`), status, reason); } return body as T; } /** * Ask the editor's ops API. Answers its JSON; an editor that refuses (`ok: * false`, or a non-2xx) throws an EditorError carrying its words, status and * reason. A GET is given 5 s and kept 2 s per URL (`fresh` asks again); a POST * is given 30 s, never kept, and drops every kept GET -- what it wrote may be * what the next read is for. */ export async function askEditor>( route: string, init: { method?: "GET" | "POST"; body?: unknown; fresh?: boolean } = {}, ): Promise { const method = init.method ?? "GET"; if (method !== "GET") { clearEditorMemo(); return askOnce(route, init, EDITOR_POST_TIMEOUT_MS); } const key = `${editorUrl()}${route}`; const now = Date.now(); for (const [k, v] of memo) if (now - v.at >= EDITOR_MEMO_MS) memo.delete(k); const hit = memo.get(key); if (hit && !init.fresh) return hit.p as Promise; const p = askOnce(route, init, EDITOR_GET_TIMEOUT_MS); memo.set(key, { at: now, p }); // The kept promise is never an unhandled rejection; each caller sees it. p.catch(() => {}); return p; } /** A route's answer for an error: the editor's status and words, else a 500. */ export function errorResponse(err: unknown): Response { const status = err instanceof EditorError ? err.status : 500; return Response.json({ error: (err as Error).message }, { status, headers: { "cache-control": "no-store" } }); } // ─── The policy ─── export type PolicyView = { generation: GenerationSettings; presets: Record>; tasks: readonly string[]; routes: readonly string[]; /** The key file's path (as configured, `~` kept) and whether a file is there. Never its content. */ keyFile: { path: string; exists: boolean }; /** * Whether an API key is there to use (demo epic D3): ANTHROPIC_API_KEY in * this process's environment, else the key file. Never the key. */ apiKey: { configured: boolean; from: "env" | "file" | null }; /** The models a picker offers: Claude's priced ones, and the local route's. */ models: { api: string[]; local: string[] }; }; const expandHome = (p: string) => (p === "~" ? os.homedir() : p.startsWith("~/") ? path.join(os.homedir(), p.slice(2)) : p); /** * The key file's configured path. The editor's settings read redacts it (its * name reads as a secret), so it is read from the checkout's settings.json, * as the chain reads `projectsRoot` (SETTINGS_FILE overrides). */ function configuredKeyFile(): string { const file = process.env.SETTINGS_FILE ?? path.join(/* turbopackIgnore: true */ REPO_ROOT, "settings.json"); try { const v = JSON.parse(readFileSync(/* turbopackIgnore: true */ file, "utf8"))?.generation?.apiKeyFile; return typeof v === "string" && v.trim() ? sanitizeGeneration({ apiKeyFile: v }).apiKeyFile : DEFAULT_API_KEY_FILE; } catch { return DEFAULT_API_KEY_FILE; } } function keyFileExists(p: string): boolean { try { return statSync(/* turbopackIgnore: true */ expandHome(p)).isFile(); } catch { return false; } } function apiKeyOf(keyPath: string): PolicyView["apiKey"] { if ((process.env.ANTHROPIC_API_KEY ?? "").trim()) return { configured: true, from: "env" }; return keyFileExists(keyPath) ? { configured: true, from: "file" } : { configured: false, from: null }; } export async function readPolicy(): Promise { const answer = await askEditor<{ value?: unknown }>("/api/ops/settings?key=generation"); const raw = (answer.value ?? {}) as Record; const generation = sanitizeGeneration(raw); const keyPath = typeof raw.apiKeyFile === "string" && raw.apiKeyFile !== "" ? generation.apiKeyFile : configuredKeyFile(); generation.apiKeyFile = keyPath; const claude = Object.keys(PRICES).filter((m) => m.startsWith("claude-")); const api = [...new Set([generation.models.api, generation.models.extractor, ...claude].filter((m) => m.startsWith("claude-")))]; const local = [...new Set([generation.models.local, "qwen3:8b"])]; return { generation, presets: GENERATION_PRESETS as unknown as Record>, tasks: GENERATION_TASKS, routes: GENERATION_ROUTES, keyFile: { path: keyPath, exists: keyFileExists(keyPath) }, apiKey: apiKeyOf(keyPath), models: { api, local }, }; } // What umtool may write of `generation`. The key file's path is not here: the // panel shows it, and the editor's own settings page sets it. const POLICY_KEYS = ["routes", "models", "caps", "cacheTtl", "triage", "localSweep"] as const; /** Write the policy through the editor's settings action. Answers the policy as read back. */ export async function writePolicy(patch: Record): Promise { const out: Record = {}; for (const [k, v] of Object.entries(patch)) { if (!(POLICY_KEYS as readonly string[]).includes(k)) { throw new EditorError(`"${k}" is not written here — the policy writes ${POLICY_KEYS.join(", ")}`, 400); } out[k] = v; } if (!Object.keys(out).length) throw new EditorError("nothing to change", 400); await askEditor("/api/ops/settings", { method: "POST", body: { patch: { generation: out } } }); return readPolicy(); } // ─── The editor's channels ─── export type EditorChannel = { slug: string; name: string; kind: string; platform: string | null; sites: string[] }; export async function listEditorChannels(): Promise { const answer = await askEditor<{ channels?: EditorChannel[] }>("/api/ops/channels"); return (answer.channels ?? []) .map((c) => ({ slug: c.slug, name: c.name ?? c.slug, kind: c.kind ?? "video", platform: c.platform ?? null, sites: c.sites ?? [] })) .sort((a, b) => a.name.localeCompare(b.name)); } // ─── The editor's jobs ─── export type DraftJobView = { id: string; kind: string | null; status: string; queue: { key?: string; position?: number } | null; /** The job's progress (release 28 F3: a draft's `turns`, `cards` or `entries`), when it reports one. */ progress: { metric: string; current: number; target: number } | null; tail: string[]; }; export async function readDraftJob(id: string, tail = 12): Promise { if (!/^[A-Za-z0-9_-]+$/.test(id)) throw new EditorError(`"${id}" is not a job id`, 400); const n = Math.max(1, Math.min(200, Math.floor(tail))); const answer = await askEditor<{ job?: Record; queue?: Record; tail?: string[] }>( `/api/ops/job/${id}?tail=${n}`, ); const job = answer.job ?? {}; const queue = (answer.queue ?? job.queue ?? null) as DraftJobView["queue"]; const p = job.progress as { metric?: unknown; current?: unknown; target?: unknown } | undefined; return { id, kind: typeof job.kind === "string" ? job.kind : null, status: String(job.status ?? "unknown"), queue, progress: p && typeof p.current === "number" ? { metric: typeof p.metric === "string" ? p.metric : "progress", current: p.current, target: typeof p.target === "number" ? p.target : p.current } : null, tail: Array.isArray(answer.tail) ? answer.tail.map(String) : [], }; } export async function cancelDraftJob(id: string): Promise { if (!/^[A-Za-z0-9_-]+$/.test(id)) throw new EditorError(`"${id}" is not a job id`, 400); await askEditor("/api/ops/job", { method: "POST", body: { verb: "cancel", ids: [id] } }); } // The body umtool sends to `report-draft`: the action's own keys, nothing else // (the editor refuses an unknown key; this refuses it first, by name). `source` // and `seed` are a research board's hand-off (R2, lib/research/handoff.ts): the // corpus the board was read through, and the board as the sweep's seed.md. // `fetch` is a refresh's (R4: false skips its fetch and build). const DRAFT_KEYS = ["task", "article", "iteration", "model", "extractorModel", "feedback", "question", "channels", "from", "to", "copyOf", "maxUsd", "cards", "entries", "force", "autonomy", "source", "seed", "fetch"]; export async function enqueueDraft(body: Record): Promise<{ jobId: string; iteration: number }> { const out: Record = {}; for (const [k, v] of Object.entries(body)) { if (v === undefined || v === null || v === "") continue; if (!DRAFT_KEYS.includes(k)) throw new EditorError(`"${k}" is not a report-draft key`, 400); out[k] = v; } const answer = await askEditor<{ jobId: string; iteration: number }>("/api/ops/report-draft", { method: "POST", body: out }); return { jobId: answer.jobId, iteration: answer.iteration }; } // ─── An article's iterations ─── export type IterationRow = { n: number; label: string; kind: Iteration["kind"]; model: string; parent: number | null; copyOf: number | null; status: Iteration["status"]; error: string | null; question: string | null; feedback: string | null; scope: Iteration["scope"] | null; usage: { model: string; usd: number; inputTokens: number; outputTokens: number }[]; usd: number; minutes: number | null; ops: { applied: number; refused: number }; checks: { name: string; ok: boolean; detail: string | null }[]; steps: { task: string; model: string | null; status: string; cost: number | null; minutes: number | null; detail: string | null; jobId: string | null }[]; jobId: string | null; createdAt: string; endedAt: string | null; /** It made a report.json of its own. */ hasReport: boolean; /** The iteration whose report it carries (itself, or the nearest ancestor that made one). */ reportFrom: number | null; projectDir: string | null; /** The project's id (its path under REPORTS_ROOT), or null when it is not under it (P4b: the Media tab's link). */ projectId: string | null; hasManifest: boolean; currentReport: boolean; currentVideo: boolean; /** A refresh's outcome (R4: iteration.json's `refresh`), else null. */ refresh: { status: string; summary: string } | null; /** Its model log's count (demo epic D3: every call of its runs and steps), else null. */ calls: { calls: number; seconds: number } | null; }; /** A project directory's id: its path under REPORTS_ROOT, posix, or null outside it. */ function projectIdOfDir(dir: string | null): string | null { if (!dir) return null; const rel = path.relative(REPORTS_ROOT, path.resolve(dir)); if (!rel || rel.startsWith("..") || path.isAbsolute(rel)) return null; return rel.split(path.sep).join("/"); } export type ChainMode = "video" | "draft-all"; export type ChainView = { mode: ChainMode; /** Draft everything with its deck step (release 29 G1). */ deck: boolean; steps: { name: string; label: string; status: string; optional: boolean; detail: string | null }[]; /** Where a start resumes: the first step not done, or null (all done). */ resumeAt: string | null; job: { id: string; state: string; stepIndex: number; of: number; label: string; error: string | null; log: string[] } | null; }; export type ArticleIterations = { article: string; /** No report.json yet: an article in the making. */ pending: boolean; iterations: IterationRow[]; problems: { n: number; problems: string[] }[]; current: IterationsCurrent; /** Something is queued or running (the page polls while it is). */ busy: boolean; }; const exists = (p: string) => { try { return statSync(/* turbopackIgnore: true */ p).isFile(); } catch { return false; } }; // A refresh iteration's outcome as iteration.json keeps it (common's RefreshOutcome), or null. function refreshOutcomeOf(it: Iteration): IterationRow["refresh"] { const r = (it as { refresh?: { status?: unknown; summary?: unknown } }).refresh; return r && typeof r.status === "string" ? { status: r.status, summary: typeof r.summary === "string" ? r.summary : "" } : null; } function rowOf(it: Iteration, hasReport: Map, byN: Map, current: IterationsCurrent): Omit { let reportFrom: number | null = null; for (let at: number | null = it.n; at !== null; at = byN.get(at)?.parent ?? null) { if (hasReport.get(at)) { reportFrom = at; break; } if (!byN.has(at)) break; } const projectDir = it.projectDir ?? null; return { n: it.n, label: iterationLabel(it.n), kind: it.kind, model: it.model, parent: it.parent, copyOf: it.copyOf, status: it.status, error: it.error ?? null, question: it.question ?? null, feedback: it.feedback ?? null, scope: it.scope ?? null, usage: Object.entries(it.usage).map(([model, u]) => ({ model, usd: u.usd, inputTokens: u.inputTokens, outputTokens: u.outputTokens })), usd: iterationUsd(it), minutes: it.minutes ?? null, ops: { applied: it.ops?.applied.length ?? 0, refused: it.ops?.refused.length ?? 0 }, checks: (it.checks ?? []).map((c) => ({ name: c.name, ok: c.ok, detail: c.detail ?? null })), steps: it.steps.map((s) => ({ task: s.task, model: s.model ?? null, status: s.status, cost: s.cost ?? null, minutes: s.minutes ?? null, detail: s.detail ?? null, jobId: s.jobId ?? null, })), jobId: it.jobId ?? null, createdAt: it.createdAt, endedAt: it.endedAt ?? null, hasReport: hasReport.get(it.n) ?? false, reportFrom, projectDir, projectId: projectIdOfDir(projectDir), hasManifest: projectDir ? exists(path.join(/* turbopackIgnore: true */ projectDir, "video.manifest.json")) : false, currentReport: current.report === it.n, currentVideo: current.video === it.n, refresh: refreshOutcomeOf(it), }; } export async function readArticleIterations(article: string): Promise { const paths = sitesPaths(); const read = await readIterations(article, paths); const hasReport = new Map(); for (const it of read.iterations) hasReport.set(it.n, (await readIterationFile(article, it.n, "report.json", paths)) !== null); const byN = new Map(read.iterations.map((it) => [it.n, it])); const rows = await Promise.all(read.iterations.map(async (it) => ({ ...rowOf(it, hasReport, byN, read.current), calls: await callCountOf(article, it.n) }))); rows.reverse(); return { article, pending: !exists(path.join(/* turbopackIgnore: true */ paths.articlesDir, article, "report.json")), iterations: rows, problems: read.problems, current: read.current, busy: rows.some((r) => r.status === "queued" || r.status === "running"), }; } /** The articles in the making, each with its newest iteration. */ export async function readPendingArticles(): Promise<{ id: string; newest: IterationRow | null; count: number }[]> { const ids = await listPendingArticles(sitesPaths()); return Promise.all( ids.map(async (id) => { const its = await readArticleIterations(id).catch(() => null); return { id, newest: its?.iterations[0] ?? null, count: its?.iterations.length ?? 0 }; }), ); } /** The day's API spend (UTC), from the editor's usage ledger, against the daily cap. */ export async function readToday(daily: number): Promise<{ day: string; usd: number; jobs: number; daily: number }> { const d = await dayUsage(getPaths().generationUsageFile); return { ...d, daily }; } // ─── The chain ("make the video") ─── /** The chain job's kind for an iteration, as lib/jobs.ts records it (Draft everything's is its own). */ export const chainKind = (article: string, n: number, mode: ChainMode = "video") => `${mode === "draft-all" ? "draft-all" : "chain"} ${article} ${iterationLabel(n)}`; /** The projects root the editor's policy names (`~` expanded), else the default. */ export function projectsRootOf(gen: GenerationSettings): string { return gen.projectsRoot ? expandHome(gen.projectsRoot) : DEFAULT_PROJECTS_ROOT; } /** * An iteration's chain as umtool shows it. `deck` (Draft everything's option, * release 29 G1) lists the deck step; so does an iteration that recorded one. */ export function chainViewOf(article: string, it: IterationRow, mode: ChainMode = "video", { deck = false }: { deck?: boolean } = {}): ChainView { const done = new Set(doneSteps({ steps: it.steps })); const byTask = new Map(it.steps.map((s) => [s.task, s])); const job: Job | undefined = recentJobs(30).find((j) => j.kind === chainKind(article, it.n, mode)); const withDeck = mode === "draft-all" && (deck || byTask.has("chain:deck")); const defs = chainStepsOf(mode, { deck: withDeck }) as { name: string; label: string; optional?: boolean }[]; return { mode, deck: withDeck, steps: defs.map((s) => { const rec = byTask.get(`chain:${s.name}`); return { name: s.name, label: s.label, status: rec?.status ?? "pending", optional: s.optional === true, detail: rec?.detail ?? null }; }), // chain.mjs's JSDoc types `done` by its default ([]), so it is cast. resumeAt: (chainStart as (o: { done: string[]; mode: string; deck: boolean }) => string | null)({ done: [...done], mode, deck: withDeck }), job: job ? { id: job.id, state: job.state, stepIndex: job.stepIndex, of: job.steps.length, label: job.steps[job.stepIndex]?.label ?? "", error: job.error, log: job.log.slice(-12), } : null, }; }