#!/usr/bin/env node // Synthesize a cut's narration BY ASKING THE EDITOR, never by running a TTS // engine here (release 25, T2 -- the "no ASR by hand" rule's twin). // // node umtool/report-to-video/narrate-via-editor.mjs // [--out ] [--variant sourced|full] [--only ] [--progress ndjson] // // `--only ` asks for that one card's narration (umtool's narration // review plays it before anything is approved). // // Every card `narration` in the manifest (or in one cut of it, `--variant`) is // one `POST /api/ops/tts` -- `{ text, engine, voice, speed, tuning?, reading? }`, the engine and // voice always named (narration.mjs's defaults: kokoro · af_heart) -- all asked // up front, as one batch; then each job is followed (`GET /api/ops/job/`) // to its end, and its log's `@@tts-result ` line names the WAV the // editor wrote. That sound is copied in beside the build and measured // (narration-store.mjs, `out/narration/.{wav,json}`), so build-video // reads it from there. A narration already kept is not asked again; the editor // answers a repeat ask from its own cache too. // // The ask's body keys are the editor's (`{text, engine, voice, speed, tuning?, // reading?}` of its `{text, file, voice, engine, speed, out, tuning, reading}`); `out` is never sent -- the // editor writes into its own cache and its result names the file. Its result // line carries the disclosure ("Narration: synthetic voice (Kokoro-82M · // af_heart)"), which is kept with the narration and used verbatim. // // The editor is `ARCHILYZER_EDITOR_URL` (default http://localhost:3001), asked // with the shared `WORKER_TOKEN` -- both from the environment, never argv, as // fetch-via-editor.mjs. It waits as long as the jobs do (the editor's tts // queue is serial), saying a queued job's place as it moves; Ctrl-C stops // waiting (exit 130) and the jobs finish on the editor, so the next ask is a // cache hit. // // The build runs the same code (`narrateCut`) for any narration it finds // missing, unless `--skip-fetch`; the driver runs this script as its own step // before the build, so the build finds them all kept. import { readFile } from "node:fs/promises"; import path from "node:path"; import { agentToken, editorEnvFiles } from "../lib/annotations/agentAuth.mjs"; import { narrationsOf } from "./narration.mjs"; import { keepNarration, narrationDir, readNarrationRecord } from "./narration-store.mjs"; export const DEFAULT_EDITOR = "http://localhost:3001"; /** The log line a tts job's result is on: this marker, then the result as compact JSON. */ export const TTS_RESULT_MARKER = "@@tts-result "; const POLL_MS = Number(process.env.NARRATE_VIA_EDITOR_POLL_MS) > 0 ? Number(process.env.NARRATE_VIA_EDITOR_POLL_MS) : 1000; const MAX_POLL_FAILURES = 10; const MAX_BACKOFF_MS = 30_000; const TAIL_LINES = 80; // Re-reads of a done job's tail before its result line counts as missing. const RESULT_RETRIES = 10; const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); /** * The editor to ask and the token to ask with: ARCHILYZER_EDITOR_URL, and WORKER_TOKEN from the environment, else * the editor's own env files (editor/.env.local, editor/.env, then the main worktree's -- agentAuth.mjs agentToken, * the rule `pnpm ops` and umtool's other editor calls read it by). Throws naming the variable and the files; the * token itself is never in a message. */ export function editorFromEnv(env = process.env, files = editorEnvFiles()) { const url = (env.ARCHILYZER_EDITOR_URL || DEFAULT_EDITOR).replace(/\/+$/, ""); const token = agentToken(env, files); if (!token) { throw new Error( "WORKER_TOKEN is not set, so the editor cannot be asked for the narration " + `(not in the environment, nor in ${files.length ? files.join(", ") : "an editor env file"}). ` + "Set WORKER_TOKEN to the same value the editor runs with.", ); } return { url, token }; } /** The `@@tts-result` in a job's log lines, parsed; null when there is none. The last one wins. */ export function ttsResultIn(lines) { let found = null; for (const line of lines ?? []) { const at = String(line).indexOf(TTS_RESULT_MARKER); if (at < 0) continue; try { found = JSON.parse(String(line).slice(at + TTS_RESULT_MARKER.length)); } catch { /* a mangled line: the next one may be whole */ } } return found; } /** * The body one narration is asked with: its words, and the engine, voice and speed always named; its tuning and * reading only when the card asks for them (narration.mjs), so a card without them is the same ask as before. */ export const ttsBody = (n) => ({ text: n.text, engine: n.engine, voice: n.voice, speed: n.speed, ...(n.tuning ? { tuning: n.tuning } : {}), ...(n.reading > 0 ? { reading: n.reading } : {}), }); /** * Ask the editor for every narration in `narrations` (narrationsOf) not yet * kept in `dir`, wait for each, keep each. Returns the records by card id -- * the ones already kept included. * * @param {{ narrations: any[], dir: string, editor?: { url: string, token: string }, * emit?: (ev: string, fields?: object) => void, pollMs?: number, * onWaiting?: (jobIds: Set) => void }} opts */ export async function narrateCut({ narrations, dir, editor = editorFromEnv(), emit = () => {}, pollMs = POLL_MS, onWaiting = () => {} }) { const records = new Map(); const ask = []; for (const n of narrations) { const rec = await readNarrationRecord(dir, n.key); if (rec) { records.set(n.id, rec); emit("narrate", { id: n.id, key: n.key, cached: true, seconds: rec.seconds, engine: rec.engine, voice: rec.voice }); } else { ask.push(n); } } if (!ask.length) return records; const headers = { authorization: `Bearer ${editor.token}`, "content-type": "application/json" }; const reach = async (url, init) => { try { return await fetch(url, init); } catch (err) { throw new Error(`could not reach the editor at ${editor.url}: ${err?.message ?? err}`); } }; // One batch: every ask posted before any is waited for. Two cards with the // same words, voice, speed, tuning and reading are one ask (one key). const pending = new Map(); // jobId -> { ns: narration[], last: status, place: line } const byKey = new Map(); for (const n of ask) { if (byKey.has(n.key)) { byKey.get(n.key).ns.push(n); continue; } const res = await reach(`${editor.url}/api/ops/tts`, { method: "POST", headers, body: JSON.stringify(ttsBody(n)) }); const body = await res.json().catch(() => ({})); if (!res.ok || !body.ok || typeof body.jobId !== "string") { // Verbatim: the editor's operator is the person who can act on it. throw new Error(`the editor refused ${n.id}'s narration (HTTP ${res.status}): ${body.error ?? "no reason given"}`); } const slot = { ns: [n], last: "", place: "" }; byKey.set(n.key, slot); pending.set(body.jobId, slot); emit("note", { message: ` ${n.id}: narration asked of the editor as job ${body.jobId} (${n.engine} · ${n.voice})` }); } onWaiting(new Set(pending.keys())); // Polls one job; retries an unanswered poll with a back-off. const poll = async (jobId, tail) => { let backoff = pollMs; for (let failures = 1; ; failures += 1) { let res; try { res = await fetch(`${editor.url}/api/ops/job/${encodeURIComponent(jobId)}${tail ? `?tail=${TAIL_LINES}` : ""}`, { headers }); } catch (err) { if (failures >= MAX_POLL_FAILURES) { throw new Error(`lost contact with the editor at ${editor.url}: ${failures} polls of job ${jobId} in a row went unanswered (${err?.message ?? err}); it may still be running there`); } await sleep(backoff); backoff = Math.min(backoff * 2, MAX_BACKOFF_MS); continue; } const j = await res.json().catch(() => ({})); if (!res.ok || !j.ok) throw new Error(`polling editor job ${jobId} failed (HTTP ${res.status}): ${j.error ?? ""}`); return j; } }; const failed = []; while (pending.size) { for (const [jobId, slot] of pending) { const j = await poll(jobId, false); const status = j.job?.status ?? "unknown"; const label = slot.ns.map((n) => n.id).join(", "); if (status !== slot.last) { slot.last = status; emit("note", { message: ` editor job ${jobId} (${label}): ${status}` }); } const q = j.job?.queue; if (status === "queued" && q && Number(q.position) > 0) { const line = `queued — position ${q.position}${Number(q.queued) > 0 ? ` of ${q.queued}` : ""}${q.key ? ` on ${q.key}` : ""}`; if (line !== slot.place) emit("note", { message: ` editor job ${jobId} (${label}): ${line}` }); slot.place = line; } if (status === "queued" || status === "running") continue; pending.delete(jobId); let done = await poll(jobId, true); // A cache hit can say `done` a few ms before its log line is on disk: // read the tail again, briefly, before calling the result missing. for (let i = 0; status === "done" && !ttsResultIn(done.tail) && i < RESULT_RETRIES; i += 1) { await sleep(Math.max(pollMs, 100)); done = await poll(jobId, true); } if (status !== "done") { const why = (done.tail ?? []).slice(-3).join(" / "); failed.push(`${label}: editor job ${jobId} ${status === "archived" ? "was lost by the editor (restarted?)" : status}${why ? ` — ${why}` : ""}`); continue; } const result = ttsResultIn(done.tail); if (!result) { failed.push(`${label}: editor job ${jobId} is done, but its log carries no ${TTS_RESULT_MARKER.trim()} line`); continue; } // Kept once, under its key; every card that asked for it reads that record. const rec = await keepNarration(dir, slot.ns[0], result, { jobId }); for (const n of slot.ns) { records.set(n.id, rec); emit("narrate", { id: n.id, key: n.key, cached: false, editorCached: result.cached === true, seconds: rec.seconds, engine: rec.engine, voice: rec.voice, jobId, }); } } onWaiting(new Set(pending.keys())); if (pending.size) await sleep(pollMs); } if (failed.length) throw new Error(`not every narration was synthesized:\n ${failed.join("\n ")}`); return records; } /** * ONE ASK, waited for (a narrated post item's take: `umtool posts narrate * --take`): `POST /api/ops/tts` with `body` -- `{ text, engine, voice, * speed?, out? }`, `out` an absolute .wav the editor copies its result to -- * then the job followed to its end. Returns `{ jobId, result }`, the * `@@tts-result` of its log. `onJob(jobId)` is told the job's id as soon as * the editor answers (a caller that is stopped can say where it runs). * * @param {{ text: string, engine?: string, voice?: string, speed?: number, out?: string, tuning?: Record, reading?: number }} body * @param {{ editor?: { url: string, token: string }, emit?: (ev: string, f?: object) => void, pollMs?: number, onJob?: (id: string) => void }} [o] */ export async function askEditorTts(body, o = {}) { return askEditorOp("/api/ops/tts", body, o); } /** The editor has no engine for an op (its route is missing, or it says the engine is not installed). */ export class OpNotInstalled extends Error { constructor(route, detail) { super(`the editor has no engine for ${route} yet (not installed${detail ? `: ${detail}` : ""})`); this.name = "OpNotInstalled"; this.route = route; } } /** The result line of a voice op (`@@voice-result `), else a tts one; null when none. */ export function opResultIn(lines) { let found = null; for (const line of lines ?? []) { for (const marker of ["@@voice-result ", TTS_RESULT_MARKER]) { const at = String(line).indexOf(marker); if (at < 0) continue; try { found = JSON.parse(String(line).slice(at + marker.length)); } catch { /* a mangled line */ } } } return found; } /** * ONE ASK OF ANY OF THE EDITOR's MEDIA OPS, waited for: `POST ` with * `body` (its `out` the absolute file the result is written to), then its job * followed to the end. Returns `{ jobId, result }` (result: the job's result * line, null when the op writes none and `out` is given). An op the editor * has no engine for throws OpNotInstalled. `onState({ jobId, status, queue, tail })` is told each poll of a job that * is queued or running (read it with `opWaitOf`). */ /** An op that did not finish by its deadline (`askEditorOp`'s `deadlineMs`): its job may still be in the editor's queue. */ export class OpDeadline extends Error { constructor(route, jobId, ms) { super(`the editor's ${route} job ${jobId} did not finish within ${Math.round(ms / 1000)} s (it may still be queued there)`); this.name = "OpDeadline"; this.jobId = jobId; } } /** How many of a job's last lines a caller that watches its state is handed (`askEditorOp`'s `onState`). */ export const STATE_TAIL_LINES = 6; /** * WHERE A QUEUED OR RUNNING EDITOR JOB IS, from one poll of it (`{ status, queue?, tail? }`): `queued` (behind other * jobs of its queue: `position`), `memory` / `slot` (it runs, and its engine waits at the machine's heavy slot), else * `running`. THE GATE WORKING, not an error. The gate speaks in the job's log (scripts/queue-lock.mjs, its stderr): * * heavy: waiting for memory — 6706 MB available, 8000 MB promised to 2 running jobs, the floor is 6000 MB * running: … (indented lines continue the one above) * (HEAVY_MIN_FREE_MB= to change it; …) * heavy: still waiting (memory, 30s; 6372 MB available) memory | build | exclusive * heavy: waiting for the build slot — … · heavy: waiting for a job that runs alone: … * queue-lock: held for a render (…) — waiting · queue-lock: still waiting for the render (…) * heavy: 7000 MB available after 1m10s — admitted · heavy: admitted beside … · heavy: capped at … · … let go after … * * The LAST gate line of the tail decides: a wait that has not been answered by an admission (or by a line of the * engine's after it) is where the job is. Pure. */ export function opWaitOf({ status, queue = null, tail = [] } = {}) { if (status === "queued") return { state: "queued", position: Number(queue?.position) > 0 ? Number(queue.position) : null, line: null }; const lines = (tail ?? []).map((l) => String(l)).filter((l) => l.trim()); const isGate = (l) => /\b(heavy|queue-lock): /.test(l); const continues = (l) => /^\s+\S/.test(l) || /^\(?(running: |\(HEAVY_MIN_FREE_MB|\(render mode:|\(heavy jobs)/.test(l.trim()); let at = -1; for (let i = lines.length - 1; i >= 0; i -= 1) { if (isGate(lines[i])) { at = i; break; } } const running = { state: "running", position: null, line: lines.at(-1)?.trim() ?? null }; if (at < 0) return running; const line = lines[at].trim(); // Something else was said after it (the engine's own output): it is in. if (lines.slice(at + 1).some((l) => !continues(l))) return running; if (/admitted|available after|capped at|let go after|running uncapped|not waiting for it|is not checked/.test(line)) return running; if (/waiting for memory|still waiting \(memory|under the \d+ MB floor/.test(line)) return { state: "memory", position: null, line }; if (/waiting|held for a render/.test(line)) return { state: "slot", position: null, line }; return running; } export async function askEditorOp(route, body, { editor = editorFromEnv(), emit = () => {}, pollMs = POLL_MS, onJob = () => {}, deadlineMs = null, onState = null } = {}) { const started = Date.now(); const headers = { authorization: `Bearer ${editor.token}`, "content-type": "application/json" }; const reach = async (url, init) => { try { return await fetch(url, init); } catch (err) { throw new Error(`could not reach the editor at ${editor.url}: ${err?.message ?? err}`); } }; const clean = Object.fromEntries(Object.entries(body).filter(([, v]) => v !== undefined && v !== null)); const res = await reach(`${editor.url}${route}`, { method: "POST", headers, body: JSON.stringify(clean) }); const j = await res.json().catch(() => ({})); if (res.status === 404 || /not installed|no engine|unknown op/i.test(String(j.error ?? ""))) throw new OpNotInstalled(route, j.error ?? (res.status === 404 ? "no such op" : "")); if (!res.ok || !j.ok || typeof j.jobId !== "string") throw new Error(`the editor refused it (${route}, HTTP ${res.status}): ${j.error ?? "no reason given"}`); const jobId = j.jobId; onJob(jobId); emit("note", { message: ` asked the editor as job ${jobId} (${clean.engine ?? "its default"} · ${clean.voice ?? "its default"})` }); let last = ""; let place = ""; let failures = 0; for (;;) { let r; try { // A caller that shows where the job is (`onState`) is handed its last lines too: the heavy slot's gate speaks there. r = await fetch(`${editor.url}/api/ops/job/${encodeURIComponent(jobId)}${onState ? `?tail=${STATE_TAIL_LINES}` : ""}`, { headers }); } catch (err) { failures += 1; if (failures >= MAX_POLL_FAILURES) throw new Error(`lost contact with the editor at ${editor.url} while job ${jobId} ran (${err?.message ?? err}); it may still be running there`); await sleep(Math.min(MAX_BACKOFF_MS, pollMs * 2 ** failures)); continue; } failures = 0; const st = await r.json().catch(() => ({})); if (!r.ok || !st.ok) throw new Error(`polling editor job ${jobId} failed (HTTP ${r.status}): ${st.error ?? ""}`); const status = st.job?.status ?? "unknown"; if (status !== last) emit("note", { message: ` editor job ${jobId}: ${status}` }); last = status; const q = st.job?.queue; if (onState && (status === "queued" || status === "running")) onState({ jobId, status, queue: q ?? null, tail: Array.isArray(st.tail) ? st.tail : [] }); if (status === "queued" && q && Number(q.position) > 0) { const line = `queued — position ${q.position}${Number(q.queued) > 0 ? ` of ${q.queued}` : ""}`; if (line !== place) emit("note", { message: ` editor job ${jobId}: ${line}` }); place = line; } if (status === "queued" || status === "running") { // A caller that must not wait unbounded (a beep's word timing behind a held lane) gives up here. if (deadlineMs !== null && Date.now() - started >= deadlineMs) throw new OpDeadline(route, jobId, deadlineMs); await sleep(pollMs); continue; } let tail = []; for (let i = 0; i <= RESULT_RETRIES; i += 1) { const d = await reach(`${editor.url}/api/ops/job/${encodeURIComponent(jobId)}?tail=${TAIL_LINES}`, { headers }); tail = ((await d.json().catch(() => ({}))).tail ?? []); if (status !== "done" || opResultIn(tail)) break; await sleep(Math.max(pollMs, 100)); } if (status !== "done") throw new Error(`editor job ${jobId} ${status}${tail.length ? ` — ${tail.slice(-3).join(" / ")}` : ""}`); const result = opResultIn(tail); if (!result && !clean.out) throw new Error(`editor job ${jobId} is done, but its log carries no result line`); return { jobId, result }; } } async function main() { const argv = process.argv.slice(2); const flag = (n) => { const i = argv.indexOf(n); return i < 0 ? undefined : argv[i + 1]; }; const valued = new Set(["--out", "--variant", "--progress", "--only"]); const manifestPath = argv.find((a, i) => !a.startsWith("--") && !valued.has(argv[i - 1])); let EMIT = (ev, f = {}) => { if (ev === "note") console.log(f.message); else if (ev === "narrate") console.log(` ${f.id}: ${f.cached ? "kept already" : "synthesized"} — ${f.seconds}s (${f.engine} · ${f.voice})`); else if (ev === "done") console.log(`narration: ${f.narrations} card(s)`); else if (ev === "error") console.error(f.message); }; if (flag("--progress") === "ndjson") EMIT = (ev, f = {}) => process.stdout.write(JSON.stringify({ ev, ...f }) + "\n"); const die = (message, code = 1) => { EMIT("error", { message }); if (flag("--progress") === "ndjson") process.stderr.write(`${message}\n`); process.exit(code); }; if (!manifestPath) die("usage: narrate-via-editor.mjs [--out ] [--variant sourced|full] [--only ] [--progress ndjson]", 2); const whole = JSON.parse(await readFile(manifestPath, "utf8")); // Validated as the build validates it: a manifest the build would refuse is // never sent to the editor. const { validateNarration } = await import("./narration.mjs"); const errors = validateNarration(whole); if (errors.length) die(`manifest: ${errors.join("; ")}`); let cut = whole; if (flag("--variant")) { const { selectVariant } = await import("./build-video.mjs"); cut = selectVariant(whole, flag("--variant")); } const only = flag("--only"); const narrations = narrationsOf(cut).filter((n) => !only || n.id === only); if (only && !narrations.length) die(`${only} is not a card with a narration in this manifest`); if (!narrations.length) { EMIT("note", { message: "no card carries a narration — nothing to synthesize" }); EMIT("done", { narrations: 0 }); return; } const outRoot = flag("--out") ?? path.join(path.dirname(path.resolve(manifestPath)), "out"); let waiting = new Set(); process.on("SIGINT", () => { if (waiting.size) EMIT("note", { message: `stopped waiting; editor job(s) ${[...waiting].join(", ")} keep running there (ask again and the narration is cached)` }); process.exit(130); }); try { const records = await narrateCut({ narrations, dir: narrationDir(outRoot), editor: editorFromEnv(), emit: EMIT, onWaiting: (s) => { waiting = s; }, }); EMIT("done", { narrations: records.size, dir: narrationDir(outRoot) }); } catch (err) { die(err?.message ?? String(err)); } } if (import.meta.url === `file://${process.argv[1]}`) { main().catch((err) => { console.error(err?.message ?? err); process.exit(1); }); }