import { existsSync } from "node:fs";
import { mkdir, writeFile } from "node:fs/promises";
import path from "node:path";
import { listTtsEngines } from "yt-dlp-transcript-common/lib/ttsApps";
import { getJob, jobView, runningJob, startJob } from "@/lib/jobs";
import { projectRef } from "@/lib/projects";
import { refuseCaller } from "@/lib/report/caller";
import { crossSiteRefusal } from "@/lib/report/sameOrigin.mjs";
import { castCommand } from "@/lib/report/castCli.mjs";
import { auditionSteps, auditionView, referenceFor, AUDITION_MAX } from "@/lib/report/castAudition.mjs";
import { castForProject } from "@/lib/report/castStore.mjs";
import { UMTOOL_DIR } from "@/lib/report/driver.mjs";
import { addStep } from "@/lib/queue/store.mjs";
import { kickQueue, queueDir } from "@/lib/queue/runner";
import { REPORTS_ROOT } from "@/lib/projects/core.mjs";
import { CAST_CONVERT_ENGINES, ENGINE_WEIGHT, charactersOf } from "umtool-report-to-video/cast";
import { ORPHEUS_TUNING_DEFAULTS, ttsReadingError } from "yt-dlp-transcript-common/lib/ttsTuning.mjs";
import { readPolicy } from "@/lib/articles/generation";
import { castAssignRouteOf } from "@/lib/report/castAssignModel.mjs";
export const dynamic = "force-dynamic";
// THE VOICES PANEL (operator, 6 Nov 2026: "pick different voices for different characters, and in UI alone be able
// to try rendering different ones to compare … and try to maintain consistent voices for different repeating
// characters"): /projects/
/voices. Every write is the CLI's own command (lib/report/castCli.mjs), run here;
// the long work is a JOB (lib/jobs.ts: its log, Cancel) or steps of the QUEUE (/jobs).
//
// GET ?project the project's characters (umtool cast project), the cast, the
// engines and their stock voices, the job running
// GET ?project&who&voices=a,b[&text|&item] an audition as it is kept (auditionView: nothing asked)
// GET ?job=[&since&sinceEvent] that job
// GET ?project&stale= the reads made with other settings than its tuning now (cast stale)
// GET ?project&tries=[&scope=cast|project] a character's TRIES (umtool cast try --list): its tuning,
// the line the page prefills, the tries kept (newest first)
// POST { project, op: "try", who, scope?, text, tuning: { temperature, top_p, repeat_penalty, takes? }, reading | another: true }
// a JOB: one line read in the character's voice (of that layer) with
// that tuning and reading -- or the next after the highest kept
// (umtool cast try: the editor's tts; scratch, no take, no draft)
// POST { project, op: "audition", who, voices: [..], text?, item? } a JOB: the editor's tts for the candidates not
// kept, then (with a reference) their closeness to the real voice
// through the heavy slot
// POST { project, op: "use", who, voice, scope: "project" | "cast" } umtool cast use [--everywhere]
// POST { project, op: "reread", who } QUEUED: one `posts narrate … --take [--thread …]` step per item
// whose picked read says them in another voice (the argv built here)
// POST { project, op: "cast-rm", id } | { op: "cast-undo" } | { op: "cast-set", id, convertEngine?, convertPitch?, convertSemitones?, narrator?, …the preset fields }
// POST { project, op: "character-set", scope: "cast" | "project", id, name?, voice?, speed?, convertEngine?, convertVoice?, convertPitch?,
// convertSemitones?, enhance?, trim?, trimPad?, direction?, handles?, anonymous?, shown?,
// tuning?: { temperature?, top_p?, repeat_penalty?, takes? } | null } a character's PRESETS (umtool cast set /
// cast project set): "" or null for a field puts its default back
// POST { project, op: "character-add", id, name?, voice?, handles?, anonymous?, shown? } one of THIS VIDEO's own (cast project
add)
// POST { project, op: "character-rm", id } | { op: "characters-undo" } cast project
rm | undo
// POST { project, op: "character-pool", id } "Add to the pool": cast project
pool
// POST { project, op: "character-keep", who, anonymous? } "Keep in this video only": cast project keep
// POST { project, op: "item-character", item, character: | null } umtool posts character - | --clear
// POST { project, op: "assign" } umtool cast assign
: PROPOSED characters by rule (applied to nothing)
// POST { project, op: "assign", model: true } a JOB: umtool cast assign
--model (the editor's cast-assign task,
// optional; its answers laid over the rule's rows)
// POST { project, op: "proposal-accept", id | all: true } | { op: "proposal-reject", id | all: true }
// umtool cast assign
--accept | --accept-all | --reject | --reject-all
// POST { project, op: "proposal-change", id, voice?, speed?, name?, direction?, anonymous?, shown? } umtool cast assign --change …
// POST multipart { project, op: "recording", item, as?, clean?, convert?, file } a JOB: posts narrate -
// --recording (kept, cleaned, converted to a STOCK voice)
const headers = { "cache-control": "no-store" };
async function cli(args: string[]) {
const out: string[] = [];
const err: string[] = [];
const code = await castCommand([...args, "--json"], { reportsRoot: REPORTS_ROOT, log: (s: string) => out.push(s), err: (s: string) => err.push(s) });
let json: Record | null = null;
try {
json = JSON.parse(out.join("\n") || "null");
} catch {
json = null;
}
return { code, json, error: code === 0 ? null : (json?.error as string | undefined) ?? (err.join("\n") || "refused") };
}
/** `umtool posts character …`, run here (its JSON, or its refusal in its words). */
async function postsCli(args: string[]) {
const { postsCommand } = await import("@/lib/report/postsCli.mjs");
const said: string[] = [];
const errs: string[] = [];
const code = await postsCommand([...args, "--json"], { root: REPORTS_ROOT, out: (x: string) => said.push(x), err: (x: string) => errs.push(x) });
let json: Record | null = null;
try {
json = JSON.parse(said.join("\n") || "null");
} catch {
json = null;
}
return { code, json, error: code === 0 ? null : (errs.join("\n") || said.join("\n") || "refused").replace(/^umtool posts: /, "") };
}
/**
* A character's preset fields as the CLI's flags (castCli.mjs fieldsOf: it refuses what makes no sense). A field
* that is "" or null puts its default back; one that is absent is left as it is.
*/
function presetArgs(b: Record): string[] {
const args: string[] = [];
const has = (k: string) => b[k] !== undefined;
const blank = (k: string) => b[k] === null || b[k] === "";
const val = (k: string) => String(b[k]).trim();
if (has("name") && !blank("name")) args.push("--name", val("name"));
if (has("handles")) args.push("--handles", (Array.isArray(b.handles) ? b.handles.map(String) : String(b.handles ?? "").split(",")).map((h) => h.trim()).filter(Boolean).join(","));
if (has("voice")) args.push(...(blank("voice") ? ["--no-voice"] : ["--voice", val("voice")]));
if (has("speed")) args.push(...(blank("speed") ? ["--no-speed"] : ["--speed", val("speed")]));
if (has("convertEngine")) args.push("--convert-engine", blank("convertEngine") ? "default" : val("convertEngine"));
if (has("convertVoice")) args.push("--convert-voice", blank("convertVoice") ? "default" : val("convertVoice"));
if (has("convertPitch")) args.push("--convert-pitch", blank("convertPitch") ? "default" : val("convertPitch"));
if (has("convertSemitones")) args.push("--convert-semitones", blank("convertSemitones") ? "0" : val("convertSemitones"));
const onOff = (k: string) => (blank(k) ? "default" : b[k] === true || b[k] === "on" ? "on" : b[k] === false || b[k] === "off" ? "off" : val(k));
if (has("enhance")) args.push("--enhance", onOff("enhance"));
if (has("trim")) args.push("--trim", onOff("trim"));
if (has("trimPad")) args.push("--trim-pad", blank("trimPad") ? "default" : val("trimPad"));
if (has("direction")) args.push("--direction", blank("direction") ? "" : val("direction"));
if (b.anonymous === true || b.anonymous === "on") args.push("--anonymous");
if (b.anonymous === false || b.anonymous === "off") args.push("--no-anonymous");
if (has("shown") && !blank("shown")) args.push("--shown", val("shown"));
if (b.narrator === true || b.narrator === "on") args.push("--narrator");
if (b.narrator === false || b.narrator === "off") args.push("--no-narrator");
if (has("tuning")) args.push(...tuningArgs(b.tuning));
return args;
}
/** The tuning fields a character keeps, and the CLI flag of each (castCli.mjs CHARACTER_TUNING_FLAGS). */
const TUNING_FIELD_FLAGS: Record = { temperature: "--temperature", top_p: "--top-p", repeat_penalty: "--repeat-penalty", takes: "--chunk-takes" };
/**
* A tuning as the CLI's flags, EXACTLY these numbers: each field given, the others `default` (off); null, "" or "none"
* is --no-tuning. A field a character does not keep (top_k, min_p) is refused unless it is Orpheus's default.
*/
function tuningArgs(t: unknown): string[] {
if (t === null || t === "" || t === "none") return ["--no-tuning"];
if (!t || typeof t !== "object" || Array.isArray(t)) throw new TuningAskError("a tuning is { temperature, top_p, repeat_penalty, takes }");
const o = t as Record;
for (const k of Object.keys(o)) {
if (k in TUNING_FIELD_FLAGS) {
const v = o[k];
if (v !== undefined && v !== null && v !== "" && !(typeof v === "number" && Number.isFinite(v))) throw new TuningAskError(`tuning.${k} is a number (got ${JSON.stringify(v)})`);
continue;
}
const dflt = (ORPHEUS_TUNING_DEFAULTS as Record)[k];
if (dflt !== undefined && (o[k] === null || o[k] === undefined || Number(o[k]) === dflt)) continue;
throw new TuningAskError(`a character keeps temperature, top_p, repeat penalty and takes (not ${k})`);
}
const args: string[] = [];
for (const [k, flag] of Object.entries(TUNING_FIELD_FLAGS)) {
const v = o[k];
args.push(flag, v === undefined || v === null || v === "" ? "default" : String(v));
}
return args;
}
class TuningAskError extends Error {}
/** A character as an argv word: its id, or an @handle -- never a flag. */
const whoOk = (v: string) => /^[a-z0-9][a-z0-9_-]{0,47}$/.test(v) || /^@[a-z0-9_.-]{1,64}$/i.test(v);
/** The layer a try's character is looked up in: "cast", "project", or none (this video's own first). */
const scopeArgs = (v: unknown): string[] => (v === "cast" || v === "project" ? ["--scope", v] : []);
/** The checkout's heavy-slot CLI, when this umtool sits in the checkout (speakerCheck.mjs's rule). */
function queueLockScript() {
const file = path.join(/* turbopackIgnore: true */ UMTOOL_DIR, "..", "scripts", "queue-lock.mjs");
return existsSync(/* turbopackIgnore: true */ file) ? file : null;
}
const mine = (project: string) => {
const r = runningJob();
return r && r.project === project && (r.kind.startsWith("cast-audition ") || r.kind.startsWith("cast-recording ") || r.kind.startsWith("cast-assign ") || r.kind.startsWith("cast-try ")) ? jobView(r) : null;
};
export async function GET(request: Request) {
const url = new URL(request.url);
const id = url.searchParams.get("job");
if (id) {
const job = getJob(id);
if (!job) return Response.json({ error: "no such job" }, { status: 404 });
return Response.json(jobView(job, Number(url.searchParams.get("since") ?? 0), Number(url.searchParams.get("sinceEvent") ?? 0)), { headers });
}
const project = await projectRef(String(url.searchParams.get("project") ?? ""));
if (!project) return Response.json({ error: "no such project" }, { status: 404 });
const who = url.searchParams.get("who");
const tries = url.searchParams.get("tries");
try {
// The reads a character's tuning leaves stale (umtool cast stale
): the bench's Keep for says them.
const staleOf = url.searchParams.get("stale");
if (staleOf) {
if (!whoOk(staleOf)) return Response.json({ error: "a character's id, or @handle" }, { status: 400 });
const r = await cli(["stale", project.id, staleOf]);
return Response.json(r.code === 0 ? r.json : { error: r.error }, { status: r.code === 0 ? 200 : 400, headers });
}
if (tries) {
if (!whoOk(tries)) return Response.json({ error: "a character's id, or @handle" }, { status: 400 });
const r = await cli(["try", project.id, tries, ...scopeArgs(url.searchParams.get("scope")), "--list"]);
return Response.json(r.code === 0 ? r.json : { error: r.error }, { status: r.code === 0 ? 200 : 400, headers });
}
if (who) {
const castRead = await castForProject(project.dir);
const voices = String(url.searchParams.get("voices") ?? "").split(",").map((s) => s.trim()).filter(Boolean).slice(0, AUDITION_MAX);
const view = await auditionView(project, castRead.cast, who, { voices, text: url.searchParams.get("text"), item: url.searchParams.get("item") });
return Response.json(view, { headers });
}
const r = await cli(["project", project.id]);
if (r.code !== 0) return Response.json({ error: r.error }, { status: 400 });
const castRead = await castForProject(project.dir);
return Response.json(
{
...r.json,
cast: charactersOf(castRead.cast),
castToken: castRead.token,
engines: listTtsEngines().map((e) => ({ id: e.id, label: e.label, voices: e.voices, defaultVoice: e.defaultVoice, weight: ENGINE_WEIGHT[e.id as keyof typeof ENGINE_WEIGHT] ?? "fast" })),
convertEngines: CAST_CONVERT_ENGINES,
// Where "Ask the model too" would run (settings.generation's cast-assign route), or why it cannot: optional.
assignModel: await readPolicy().then((pol) => castAssignRouteOf(pol.generation), (e: unknown) => ({ route: null, model: null, why: `the editor did not answer (${e instanceof Error ? e.message : String(e)})` })),
running: mine(project.id),
},
{ headers },
);
} catch (e) {
return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 400 });
}
}
export async function POST(request: Request) {
// OUTSIDE THE PROXY (an upload: lib/report/writeGuard.mjs EXEMPT), so crossSiteRefusal here, before the body, on
// EVERY call, a browser's or not: a Host / X-Forwarded-Host not this machine (nor UMTOOL_ALLOWED_HOSTS) is refused
// even from curl, and so is a write from another site's page.
const cross = crossSiteRefusal(request.headers);
if (cross) return Response.json({ error: cross }, { status: 403 });
const refused = refuseCaller(request, "/api/report/voices");
if (refused) return refused;
const multipart = (request.headers.get("content-type") ?? "").startsWith("multipart/");
let b: Record | null = null;
let form: FormData | null = null;
if (multipart) {
form = await request.formData().catch(() => null);
if (!form) return Response.json({ error: "bad form" }, { status: 400 });
b = Object.fromEntries([...form.entries()].filter(([, v]) => typeof v === "string"));
} else b = (await request.json().catch(() => null)) as Record | null;
if (!b) return Response.json({ error: "bad json" }, { status: 400 });
const project = await projectRef(String(b.project ?? ""));
if (!project) return Response.json({ error: "no such project" }, { status: 404 });
const s = (k: string) => (typeof b![k] === "string" ? (b![k] as string).trim() : "");
const op = s("op");
try {
if (op === "audition") {
const who = s("who");
const voices = (Array.isArray(b.voices) ? b.voices : String(b.voices ?? "").split(",")).map((v) => String(v).trim()).filter(Boolean);
if (!who || !voices.length) return Response.json({ error: "an audition is of a character, with its candidates" }, { status: 400 });
if (voices.length > AUDITION_MAX) return Response.json({ error: `at most ${AUDITION_MAX} candidates` }, { status: 400 });
const running = runningJob();
if (running) return Response.json({ error: `a job is already running (${running.kind})`, running: jobView(running) }, { status: 409 });
const castRead = await castForProject(project.dir);
// Check the ask before it is a job: the candidates, the character, the line (auditionView refuses what the CLI would).
const view = await auditionView(project, castRead.cast, who, { voices, text: s("text") || null, item: s("item") || null });
const reference = await referenceFor(project, view.character);
const plan = auditionSteps(project, { who, voices: view.candidates.map((c) => c.spec), text: s("text") || null, item: s("item") || null, score: !!reference, umtoolDir: UMTOOL_DIR, queueLock: queueLockScript() });
const job = startJob(plan.kind, plan.steps, { project: project.id });
return Response.json({ ok: true, job: jobView(job), audition: view }, { headers });
}
if (op === "try") {
// ONE LINE read in the character's voice with a tuning and a reading: the CLI's own command as a job (scratch).
const who = s("who");
const text = s("text");
if (!who || !whoOk(who)) return Response.json({ error: "a try is of a character: its id, or @handle" }, { status: 400 });
if (!text) return Response.json({ error: "type the line to read" }, { status: 400 });
// Another reading: the CLI counts the next one from what it keeps (the line as it is said, not as typed).
const another = b.another === true;
const reading = another || b.reading === undefined || b.reading === null || b.reading === "" ? 0 : b.reading;
const readingError = ttsReadingError(reading);
if (readingError) return Response.json({ error: readingError }, { status: 400 });
let tuning: string[];
try {
tuning = b.tuning === undefined ? [] : tuningArgs(b.tuning).filter((a) => a !== "--no-tuning");
} catch (e) {
return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 400 });
}
// With no tuning given, the try reads with the character's own; "none" reads with the defaults.
if (b.tuning === null || b.tuning === "none") tuning = ["--tuning", "default", "--chunk-takes", "default"];
const running = runningJob();
if (running) return Response.json({ error: `another job is running (${running.kind}): Read it is open again when it ends`, busy: true, running: jobView(running) }, { status: 409 });
const cliPath = path.join(/* turbopackIgnore: true */ UMTOOL_DIR, "bin", "umtool.mjs");
const argv = [process.execPath, cliPath, "cast", "try", project.id, who, ...scopeArgs(b.scope), "--text", text, ...tuning, ...(another ? ["--another"] : ["--reading", String(reading)]), "--progress", "ndjson"];
const job = startJob(`cast-try ${project.id}`, [{ label: `${who}: the line read (the editor's tts), ${another ? "another reading" : `reading ${reading}`}`, argv, cwd: path.join(/* turbopackIgnore: true */ UMTOOL_DIR, ".."), env: {}, ndjson: true, timeoutMs: 45 * 60 * 1000 }], { project: project.id });
return Response.json({ ok: true, job: jobView(job) }, { headers });
}
if (op === "use") {
const scope = s("scope") === "cast" ? "cast" : "project";
const r = await cli(["use", project.id, s("who"), s("voice"), ...(scope === "cast" ? ["--everywhere"] : [])]);
return Response.json(r.code === 0 ? r.json : { error: r.error }, { status: r.code === 0 ? 200 : 400, headers });
}
if (op === "reread") {
// The plan the CLI makes (its argv built from the take's own read record), each item a step of the queue.
const r = await cli(["reread", project.id, s("who"), "--dry-run"]);
if (r.code !== 0) return Response.json({ error: r.error }, { status: 400 });
const items = ((r.json?.items ?? []) as Array<{ id: string; argv: string[] }>).filter((x) => Array.isArray(x.argv) && x.argv[0] === "posts" && x.argv[1] === "narrate" && x.argv[2] === project.id);
const queued: string[] = [];
for (const x of items) {
const step = (await addStep(queueDir(), {
argv: x.argv,
label: `re-read ${x.id} of ${project.id} (${s("who")}'s new voice)`,
target: { project: project.id, take: null },
by: "the umtool app (Voices)",
})) as { qid: string };
queued.push(step.qid);
}
if (queued.length) kickQueue();
return Response.json({ ok: true, queued, items: items.map((x) => x.id), skipped: r.json?.skipped ?? [] }, { headers });
}
if (op === "cast-rm") {
const r = await cli(["rm", s("id")]);
return Response.json(r.code === 0 ? r.json : { error: r.error }, { status: r.code === 0 ? 200 : 400, headers });
}
if (op === "cast-undo") {
const r = await cli(["undo"]);
return Response.json(r.code === 0 ? r.json : { error: r.error }, { status: r.code === 0 ? 200 : 400, headers });
}
const answer = (r: { code: number; json: Record | null; error: string | null }) => Response.json(r.code === 0 ? r.json : { error: r.error }, { status: r.code === 0 ? 200 : 400, headers });
const idOk = (v: string) => /^[a-z0-9][a-z0-9_-]{0,47}$/.test(v);
if (op === "cast-set") {
const args = ["set", s("id")];
if (s("convertEngine")) args.push("--convert-engine", s("convertEngine"));
// The pitch a converted read lands on (castCli.mjs refuses what makes no sense).
if (s("convertPitch")) args.push("--convert-pitch", s("convertPitch"));
if (typeof b.convertSemitones === "number" || s("convertSemitones")) args.push("--convert-semitones", String(b.convertSemitones ?? s("convertSemitones")));
if (b.narrator === true || s("narrator") === "on") args.push("--narrator");
if (b.narrator === false || s("narrator") === "off") args.push("--no-narrator");
if (s("name")) args.push("--name", s("name"));
return answer(await cli(args));
}
// A CHARACTER's PRESETS, the cast's or this video's own -- each the CLI's own command (castCli.mjs).
if (op === "character-set" || op === "character-add") {
const id = s("id");
if (!idOk(id)) return Response.json({ error: "a character's id is lower case letters, digits, - and _" }, { status: 400 });
const own = op === "character-add" || s("scope") === "project";
const head = own ? ["project", project.id, op === "character-add" ? "add" : "set", id] : ["set", id];
let args: string[];
try {
args = presetArgs(b);
} catch (e) {
if (e instanceof TuningAskError) return Response.json({ error: e.message }, { status: 400 });
throw e;
}
return answer(await cli([...head, ...args]));
}
if (op === "character-rm") {
if (!idOk(s("id"))) return Response.json({ error: "which character?" }, { status: 400 });
return answer(await cli(["project", project.id, "rm", s("id")]));
}
if (op === "characters-undo") return answer(await cli(["project", project.id, "undo"]));
if (op === "character-pool") {
if (!idOk(s("id"))) return Response.json({ error: "which character?" }, { status: 400 });
return answer(await cli(["project", project.id, "pool", s("id")]));
}
if (op === "character-keep") {
const who = s("who");
if (!/^@?[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$/.test(who)) return Response.json({ error: "keep takes a cast character's id, or an author (@handle)" }, { status: 400 });
return answer(await cli(["project", project.id, "keep", who, ...(b.anonymous === true ? ["--anonymous"] : []), ...(s("shown") ? ["--shown", s("shown")] : [])]));
}
if (op === "item-character") {
const item = s("item");
if (!/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/.test(item)) return Response.json({ error: "which post item?" }, { status: 400 });
const id = s("character");
if (id && !idOk(id)) return Response.json({ error: "which character?" }, { status: 400 });
return answer(await postsCli(["character", project.id, item, id || "--clear"]));
}
// PROPOSED characters (umtool cast assign): by rule, the model only when asked; accept, change, reject.
if (op === "assign" && b.model === true) {
// The model, on request only: a job (the editor's task, followed), the page following it.
const running = runningJob();
if (running) return Response.json({ error: `a job is already running (${running.kind})`, running: jobView(running) }, { status: 409 });
const cliPath = path.join(/* turbopackIgnore: true */ UMTOOL_DIR, "bin", "umtool.mjs");
const argv = [process.execPath, cliPath, "cast", "assign", project.id, "--model"];
const job = startJob(`cast-assign ${project.id}`, [{ label: "the model's proposals (the editor's cast-assign task), laid over the rule's", argv, cwd: path.join(/* turbopackIgnore: true */ UMTOOL_DIR, ".."), env: {}, timeoutMs: 35 * 60 * 1000 }], { project: project.id });
return Response.json({ ok: true, job: jobView(job) }, { headers });
}
if (op === "assign") return answer(await cli(["assign", project.id]));
if (op === "proposal-accept" || op === "proposal-reject") {
const verb = op === "proposal-accept" ? "--accept" : "--reject";
if (b.all === true) return answer(await cli(["assign", project.id, `${verb}-all`]));
if (!idOk(s("id"))) return Response.json({ error: "which proposal?" }, { status: 400 });
return answer(await cli(["assign", project.id, verb, s("id")]));
}
if (op === "proposal-change") {
if (!idOk(s("id"))) return Response.json({ error: "which proposal?" }, { status: 400 });
const args = ["assign", project.id, "--change", s("id")];
if (s("voice")) args.push("--voice", s("voice"));
if (typeof b.speed === "number" || s("speed")) args.push("--speed", String(b.speed ?? s("speed")));
if (s("name")) args.push("--name", s("name"));
if (b.direction !== undefined) args.push("--direction", s("direction"));
if (b.anonymous === true) args.push("--anonymous");
if (b.anonymous === false) args.push("--no-anonymous");
if (s("shown")) args.push("--shown", s("shown"));
return answer(await cli(args));
}
if (op === "recording") {
const file = form?.get("file");
const item = s("item");
if (!(file instanceof Blob) || !file.size) return Response.json({ error: "a recording is a sound file" }, { status: 400 });
if (!/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/.test(item)) return Response.json({ error: "which post item?" }, { status: 400 });
const running = runningJob();
if (running) return Response.json({ error: `a job is already running (${running.kind})`, running: jobView(running) }, { status: 409 });
const name = String((file as File).name ?? "recording").replace(/[^A-Za-z0-9._-]+/g, "-").slice(-80) || "recording";
const dir = path.join(project.dir, "narration", "uploads");
await mkdir(dir, { recursive: true });
const abs = path.join(dir, `${new Date().toISOString().replace(/[:.]/g, "-")}-${name}`);
await writeFile(abs, Buffer.from(await file.arrayBuffer()));
const cliPath = path.join(/* turbopackIgnore: true */ UMTOOL_DIR, "bin", "umtool.mjs");
const argv = [process.execPath, cliPath, "posts", "narrate", project.id, item, "--recording", abs, ...(s("as") ? ["--as", s("as")] : []), ...(s("clean") === "off" ? ["--no-clean"] : []), ...(s("convert") === "off" ? ["--no-convert"] : []), "--json"];
const job = startJob(`cast-recording ${project.id}`, [{ label: `${item}: the recording kept, cleaned, converted`, argv, cwd: path.join(/* turbopackIgnore: true */ UMTOOL_DIR, ".."), env: {}, timeoutMs: 45 * 60 * 1000 }], { project: project.id });
return Response.json({ ok: true, job: jobView(job), file: path.relative(project.dir, abs) }, { headers });
}
return Response.json({ error: "op must be audition, use, reread, cast-rm, cast-undo, cast-set, character-set, character-add, character-rm, characters-undo, character-pool, character-keep, item-character, assign, proposal-accept, proposal-reject, proposal-change or recording" }, { status: 400 });
} catch (e) {
const status = (e as { status?: number }).status ?? 400;
return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status, headers });
}
}