Merge remote-tracking branch 'origin/main' into sec-media-use-refuse-links

# Conflicts:
#	skills-manifest.json
This commit is contained in:
Michael Wang
2026-11-20 16:30:21 -08:00
13 changed files with 379 additions and 77 deletions
+91 -1
View File
@@ -1,5 +1,14 @@
import { execFileSync } from "node:child_process";
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import {
existsSync,
lstatSync,
mkdirSync,
mkdtempSync,
readFileSync,
rmSync,
symlinkSync,
writeFileSync,
} from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from "vitest";
@@ -658,6 +667,82 @@ describe("generate", () => {
},
);
const canLink = (() => {
const dir = mkdtempSync(join(tmpdir(), "hf-generate-link-"));
try {
symlinkSync(join(dir, "nowhere"), join(dir, "link"));
return true;
} catch {
return false;
} finally {
rmSync(dir, { recursive: true, force: true });
}
})();
it.skipIf(!canLink)(
"replaces a live or dangling link at --out, never writing through it",
async () => {
const outside = mkdtempSync(join(tmpdir(), "hf-generate-outside-"));
try {
const kept = join(outside, "kept");
writeFileSync(kept, "keep me");
const live = join(project, "assets/linked-live.png");
const dangling = join(project, "assets/linked-dangling.png");
mkdirSync(join(project, "assets"), { recursive: true });
symlinkSync(kept, live);
symlinkSync(join(outside, "made"), dangling);
vi.stubGlobal("fetch", async (url: string) =>
url === "https://files.test/linked.png"
? new Response(new Uint8Array([7]))
: json({
data: {
id: "img-linked",
status: "completed",
images: [{ url: "https://files.test/linked.png" }],
},
}),
);
for (const out of [live, dangling]) {
await generate({ type: "image", out, prompt: "a linked picture" });
expect(lstatSync(out).isFile()).toBe(true);
expect(readFileSync(out)).toEqual(Buffer.from([7]));
}
expect(readFileSync(kept, "utf8")).toBe("keep me");
expect(existsSync(join(outside, "made"))).toBe(false);
} finally {
rmSync(outside, { recursive: true, force: true });
}
},
);
it.skipIf(!ffmpeg || !canLink)(
"crops past a live or dangling link at <out>.fit.mp4, never writing through it",
async () => {
const outside = mkdtempSync(join(tmpdir(), "hf-generate-outside-"));
try {
const kept = join(outside, "kept");
writeFileSync(kept, "keep me");
answers(textured("wide-linked.mp4", "1344x768", false));
const cases = [
[join(project, "assets/fit-live.mp4"), kept],
[join(project, "assets/fit-dangling.mp4"), join(outside, "made")],
] as const;
for (const [out, target] of cases) {
symlinkSync(target, `${out}.fit.mp4`);
const r = await generate({ type: "video", out, prompt: "p" });
expect(lstatSync(r.out).isFile()).toBe(true);
const { width, height } = probeVideo(r.out);
expect([width, height]).toEqual([1344, 756]);
expect(lstatSync(`${out}.fit.mp4`).isSymbolicLink()).toBe(true);
}
expect(readFileSync(kept, "utf8")).toBe("keep me");
expect(existsSync(join(outside, "made"))).toBe(false);
} finally {
rmSync(outside, { recursive: true, force: true });
}
},
);
const still = (name: string, size: string) => {
const path = join(project, name);
execFileSync(ffmpeg!, [
@@ -1027,6 +1112,11 @@ describe("generate", () => {
expect(check("nano-banana-2")).toThrow("nano-banana-2 is no longer offered here");
expect(check("gpt-image-2.5", "16:9")).toThrow("gpt-image-2.5 is no longer offered here");
expect(check("some-new-model", "7:5")).not.toThrow();
// A name every object carries is a model this build has no entry for, like any other.
for (const model of ["constructor", "toString", "__proto__", "hasOwnProperty"]) {
expect(check(model, "7:5")).not.toThrow();
expect(check(model, undefined, 20)).toThrow("no file at");
}
});
it("prices only a request the real call would accept", () => {
+23 -22
View File
@@ -2,7 +2,8 @@
// from one photo, a voice, or music. Every call is priced first with --plan, keyed for idempotency, downloaded into
// the project and recorded in the media ledger as generated.
import { randomUUID } from "node:crypto";
import { existsSync, mkdtempSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
import { replaceFileAtomically } from "@hyperframes/core/atomic-file";
import { makeOutputFolder } from "../utils/outputFolder.js";
import { tmpdir } from "node:os";
import { basename, dirname, extname, join, relative, resolve } from "node:path";
@@ -16,7 +17,15 @@ import type {
MusicCreateRequest,
} from "../cloud/_gen/types.js";
import { findCuts, signatures } from "../measure/cuts.js";
import { Fix, probeVideo, projectOf, round, runFfmpeg, videoClip } from "../measure/media.js";
import {
Fix,
ffmpegToFile,
probeVideo,
projectOf,
round,
runFfmpeg,
videoClip,
} from "../measure/media.js";
import { loadSharp } from "../utils/optionalPackages.js";
import {
chargedCredits,
@@ -202,11 +211,14 @@ const need = <T>(value: T | undefined, flag: string, example: string): T => {
return value;
};
const ownEntry = <T>(table: Record<string, T>, name: string): T | undefined =>
Object.hasOwn(table, name) ? table[name] : undefined;
function imageModel(r: GenerateRequest): string {
const model = r.model ?? DEFAULTS.image;
const replacement = RETIRED_IMAGE_MODELS[model];
const replacement = ownEntry(RETIRED_IMAGE_MODELS, model);
if (replacement) throw new Fix(`${model} is no longer offered here`, `--model ${replacement}`);
const spec = IMAGE_MODELS[model];
const spec = ownEntry(IMAGE_MODELS, model);
if (!spec) return model;
if (r.aspect && !spec.aspects.includes(r.aspect))
throw new Fix(`${model} does not make ${r.aspect}`, `--aspect ${spec.aspects.join("|")}`);
@@ -564,24 +576,13 @@ function fitAspect(out: string, aspect: string): string | undefined {
const even = (n: number) => n - (n % 2);
const [w, h] =
width / height > want ? [even(height * want), height] : [width, even(width / want)];
const fitted = `${out}.fit${extname(out)}`;
runFfmpeg([
...[
"-y",
"-i",
out,
"-vf",
`crop=${w}:${h}`,
"-c:v",
"libx264",
"-crf",
"12",
"-preset",
"slow",
ffmpegToFile(
[
...["-y", "-i", out, "-vf", `crop=${w}:${h}`, "-c:v", "libx264", "-crf", "12"],
...["-preset", "slow", "-pix_fmt", "yuv420p", "-c:a", "copy"],
],
...["-pix_fmt", "yuv420p", "-c:a", "copy", fitted],
]);
renameSync(fitted, out);
out,
);
return `HeyGen returned ${width}x${height} for ${aspect}; cropped to ${w}x${h} (centre), not stretched`;
}
@@ -753,7 +754,7 @@ export async function generate(
`could not download the result (${res.status})`,
"run the same command again; it re-reads the job",
);
writeFileSync(out, Buffer.from(await res.arrayBuffer()));
replaceFileAtomically(out, Buffer.from(await res.arrayBuffer()));
const charged = chargedCredits(job);
// HeyGen sometimes cuts inside a shot on its own; the shot is paid for and kept, the cuts are reported.
let cuts: number[] | null | undefined;
+20 -3
View File
@@ -114,15 +114,32 @@ export function refuseLink(path) {
export function replaceFile(path, content) {
// Same shape as core atomicTempPath, which Studio's project history skips.
const temp = `${path}.hf${randomBytes(3).toString("hex")}.tmp`;
writeFileSync(temp, content, { flag: "wx" });
try {
renameSync(temp, path);
writeFileSync(temp, content, { flag: "wx" });
renameRidingWindowsHolds(temp, path);
} catch (error) {
rmSync(temp, { force: true });
// EEXIST: the random name belongs to another writer, so it is left alone.
if (error?.code !== "EEXIST") rmSync(temp, { force: true });
throw error;
}
}
// Windows refuses a rename for a moment while antivirus or a just-exited process still holds the file.
const WINDOWS_HOLD = new Set(["EPERM", "EACCES", "EBUSY"]);
const HOLD_BACKOFF_MS = [10, 20, 40, 80, 160, 320, 640];
function renameRidingWindowsHolds(from, to) {
for (let attempt = 0; ; attempt++) {
try {
return renameSync(from, to);
} catch (error) {
const held = process.platform === "win32" && WINDOWS_HOLD.has(error?.code);
if (!held || attempt >= HOLD_BACKOFF_MS.length) throw error;
sleepMs(HOLD_BACKOFF_MS[attempt]);
}
}
}
export function appendRecord(projectDir, record) {
ownMediaDir(projectDir, typeSubdir(record.type));
+10
View File
@@ -2,10 +2,20 @@ import { describe, expect, it } from "vitest";
import {
BUNDLED_VOICES,
SUPPORTED_LANGS,
ensureModel,
inferLangFromVoiceId,
isSupportedLang,
} from "./manager.js";
describe("ensureModel", () => {
it.each(["no-such-model", "constructor", "toString", "__proto__"])(
"names %s as an unknown model",
async (model) => {
await expect(ensureModel(model)).rejects.toThrow(`Unknown TTS model: ${model}.`);
},
);
});
describe("inferLangFromVoiceId", () => {
it.each([
["af_heart", "en-us"],
+3 -2
View File
@@ -117,8 +117,9 @@ export async function ensureModel(
model: string = DEFAULT_MODEL,
options?: { onProgress?: (message: string) => void },
): Promise<string> {
const url = MODEL_URLS[model];
const pin = MODEL_PINS[model];
const known = Object.hasOwn(MODEL_URLS, model) && Object.hasOwn(MODEL_PINS, model);
const url = known ? MODEL_URLS[model] : undefined;
const pin = known ? MODEL_PINS[model] : undefined;
if (!url || !pin) {
throw new Error(
`Unknown TTS model: ${model}. Available: ${Object.keys(MODEL_URLS).join(", ")}`,
+1 -1
View File
@@ -18,7 +18,7 @@
"files": 13
},
"media-use": {
"hash": "c163c42866c22486",
"hash": "78085d6f3c4afd96",
"files": 131
},
"remotion-to-hyperframes": {
@@ -15,9 +15,10 @@
// --voice (starfish id), --speed, --lang, --list.
// Requires: $HEYGEN_API_KEY / OAuth ~/.hyperframes credentials and ffmpeg for .wav output.
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { existsSync, mkdirSync, readFileSync } from "node:fs";
import { dirname, resolve } from "node:path";
import { heygenAuthHeaders, heygenJSON, loadEnvFromDir } from "./lib/heygen.mjs";
import { replaceFile } from "../../scripts/lib/manifest.mjs";
import { terminalText } from "../../scripts/lib/terminal-text.mjs";
import { ffprobeDuration, resolveVoiceId, synthesizeOne, withWordIds } from "./lib/tts.mjs";
@@ -111,7 +112,7 @@ let wordCount = 0;
if (wordsPath) {
if (words && words.length) {
mkdirSync(dirname(wordsPath), { recursive: true });
writeFileSync(wordsPath, JSON.stringify(withWordIds(words), null, 2));
replaceFile(wordsPath, JSON.stringify(withWordIds(words), null, 2));
wordCount = words.length;
} else {
console.error("⚠ no word_timestamps in response — run `hyperframes transcribe` instead");
@@ -1,7 +1,15 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { spawnSync } from "node:child_process";
import { mkdtempSync } from "node:fs";
import {
existsSync,
lstatSync,
mkdtempSync,
readFileSync,
rmSync,
symlinkSync,
writeFileSync,
} from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
@@ -36,3 +44,95 @@ test("a refused speech prints HeyGen's own message, so a caller can act on it",
"HeyGen's message alone, not the raw response",
);
});
// Speech with one timed word; the audio itself is the file named by $TTS_AUDIO.
const speaking = `data:text/javascript,import { readFileSync } from "node:fs";
globalThis.fetch = async (url) => String(url).endsWith("/voices/speech")
? new Response(JSON.stringify({ data: { audio_url: "https://audio.example/a",
word_timestamps: [{ word: "Hello", start: 0, end: 0.4 }] } }),
{ headers: { "content-type": "application/json" } })
: new Response(readFileSync(process.env.TTS_AUDIO));`;
const hasFfmpeg = spawnSync("ffmpeg", ["-version"], { stdio: "ignore" }).status === 0;
const canLink = (() => {
const dir = mkdtempSync(join(tmpdir(), "heygen-tts-link-"));
try {
symlinkSync(join(dir, "nowhere"), join(dir, "link"));
return true;
} catch {
return false;
} finally {
rmSync(dir, { recursive: true, force: true });
}
})();
function speak(dir, args, audio) {
return spawnSync(process.execPath, ["--import", speaking, script, "Hello", ...args], {
cwd: dir,
encoding: "utf8",
env: {
...process.env,
HEYGEN_API_KEY: "",
HYPERFRAMES_API_KEY: "",
HEYGEN_ACCESS_TOKEN: "t",
TTS_AUDIO: audio,
},
});
}
test(
"a link at the wav and words outputs is replaced, and the files it points at are kept",
{ skip: !canLink || !hasFfmpeg },
() => {
const dir = mkdtempSync(join(tmpdir(), "heygen-tts-"));
const outside = mkdtempSync(join(tmpdir(), "heygen-tts-outside-"));
try {
const audio = join(outside, "speech.wav");
spawnSync("ffmpeg", ["-v", "error", "-y", "-f", "lavfi", "-i", "sine=d=0.5", audio]);
const wavTarget = join(outside, "wav-target");
const wordsTarget = join(outside, "words-target");
writeFileSync(wavTarget, "keep me");
writeFileSync(wordsTarget, "keep me too");
symlinkSync(wavTarget, join(dir, "narration.wav"));
symlinkSync(wordsTarget, join(dir, "words.json"));
const run = speak(dir, ["--voice", "v1", "--words", "words.json"], audio);
assert.equal(run.status, 0, run.stderr);
assert.equal(readFileSync(wavTarget, "utf8"), "keep me");
assert.equal(readFileSync(wordsTarget, "utf8"), "keep me too");
assert.ok(lstatSync(join(dir, "narration.wav")).isFile());
assert.ok(lstatSync(join(dir, "words.json")).isFile());
assert.equal(JSON.parse(readFileSync(join(dir, "words.json"), "utf8"))[0].text, "Hello");
} finally {
rmSync(dir, { recursive: true, force: true });
rmSync(outside, { recursive: true, force: true });
}
},
);
test(
"a dangling link at the mp3 and words outputs creates nothing where it points",
{ skip: !canLink },
() => {
const dir = mkdtempSync(join(tmpdir(), "heygen-tts-"));
const outside = mkdtempSync(join(tmpdir(), "heygen-tts-outside-"));
try {
const audio = join(outside, "speech.mp3");
writeFileSync(audio, "mp3 bytes");
symlinkSync(join(outside, "made.mp3"), join(dir, "narration.mp3"));
symlinkSync(join(outside, "made.json"), join(dir, "words.json"));
const run = speak(
dir,
["--voice", "v1", "-o", "narration.mp3", "--words", "words.json"],
audio,
);
assert.equal(run.status, 0, run.stderr);
assert.equal(existsSync(join(outside, "made.mp3")), false);
assert.equal(existsSync(join(outside, "made.json")), false);
assert.equal(readFileSync(join(dir, "narration.mp3"), "utf8"), "mp3 bytes");
assert.ok(lstatSync(join(dir, "words.json")).isFile());
} finally {
rmSync(dir, { recursive: true, force: true });
rmSync(outside, { recursive: true, force: true });
}
},
);
@@ -1,5 +1,6 @@
import { mkdirSync, writeFileSync } from "node:fs";
import { mkdirSync } from "node:fs";
import { dirname } from "node:path";
import { replaceFile } from "../../../scripts/lib/manifest.mjs";
import { geminiAuth } from "./gemini-auth.mjs";
export const GEMINI_TTS_MODEL = "gemini-3.8-flash-tts";
@@ -82,7 +83,7 @@ export async function synthesizeGemini(
throw new Error("Gemini TTS returned invalid WAV audio");
}
mkdirSync(dirname(wavAbs), { recursive: true });
writeFileSync(wavAbs, bytes);
replaceFile(wavAbs, bytes);
return { ok: true, words: null };
} catch (error) {
// Error responses must never echo the credential into logs or metadata.
@@ -1,8 +1,17 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { mkdtempSync, readFileSync, rmSync, existsSync } from "node:fs";
import {
existsSync,
lstatSync,
mkdirSync,
mkdtempSync,
readFileSync,
rmSync,
symlinkSync,
writeFileSync,
} from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { dirname, join } from "node:path";
import { synthesizeGemini, GEMINI_TTS_MODEL } from "./gemini-tts.mjs";
import { pickProvider, resolveVoiceId, synthesizeOne } from "./tts.mjs";
@@ -64,6 +73,27 @@ test("Gemini preserves verbatim text, directs style separately, saves WAV and re
assert.deepEqual(readFileSync(args.wavAbs), wav);
});
test("Gemini replaces a link at the output instead of writing through it", async (t) => {
const { wav, payload, args } = fixture(t);
const outside = mkdtempSync(join(tmpdir(), "gemini-tts-outside-"));
t.after(() => rmSync(outside, { recursive: true, force: true }));
const kept = join(outside, "kept");
writeFileSync(kept, "keep me");
mkdirSync(dirname(args.wavAbs), { recursive: true });
try {
symlinkSync(kept, args.wavAbs);
} catch {
t.skip("symbolic links are not available here");
return;
}
t.mock.method(globalThis, "fetch", async () => Response.json(payload));
const result = await synthesizeOne({ ...args, provider: "gemini" });
assert.deepEqual(result, { ok: true, words: null });
assert.equal(readFileSync(kept, "utf8"), "keep me");
assert.ok(lstatSync(args.wavAbs).isFile());
assert.deepEqual(readFileSync(args.wavAbs), wav);
});
test("Flash-Lite and GOOGLE_API_KEY work without a Gemini key", async (t) => {
const { payload, args } = fixture(t);
delete process.env.GEMINI_API_KEY;
@@ -17,14 +17,16 @@ if (args[0] === "--version") {
const input = args[2];
const output = args[0] === "-c" ? args[4] : args[args.indexOf("--output") + 1];
const text = fs.readFileSync(input, "utf8");
fs.writeFileSync(output + ".started", input);
// Side files go to the case root under the output's name: the output itself is in a private folder.
const side = path.join(process.env.CASE_ROOT, path.basename(output));
fs.writeFileSync(side + ".started", input);
const finish = () => {
if (text === "slow" && !fs.existsSync(process.env.RELEASE_FILE)) {
setTimeout(finish, 5);
return;
}
const consumed = fs.readFileSync(input, "utf8");
fs.writeFileSync(output + ".json", JSON.stringify({ input, text, consumed, args }));
fs.writeFileSync(side + ".json", JSON.stringify({ input, text, consumed, args }));
if (process.env.CASE_MODE === "nonzero") process.exit(7);
if (process.env.CASE_MODE !== "no-output") fs.writeFileSync(output, consumed);
};
@@ -78,11 +80,11 @@ if (["allocation", "write", "spawn-throw"].includes(mode)) {
const slow = request("elevenlabs", "slow", slowWav);
try {
const deadline = Date.now() + 5000;
while (!fs.existsSync(slowWav + ".started")) {
while (!fs.existsSync(join(root, "slow.wav.started"))) {
assert.ok(Date.now() < deadline, "slow subprocess must start");
await new Promise(resolve => setTimeout(resolve, 5));
}
const slowInput = fs.readFileSync(slowWav + ".started", "utf8");
const slowInput = fs.readFileSync(join(root, "slow.wav.started"), "utf8");
assert.deepEqual(await request("kokoro"), { ok: true, words: null });
assert.deepEqual(owned(), [dirname(slowInput).split(/[\\\\/]/).pop()]);
assert.equal(fs.readFileSync(slowInput, "utf8"), "slow");
@@ -91,6 +93,21 @@ if (["allocation", "write", "spawn-throw"].includes(mode)) {
await slow;
}
assert.equal(fs.readFileSync(slowWav, "utf8"), "slow");
} else if (mode === "link") {
const outside = join(root, "outside");
fs.mkdirSync(project, { recursive: true });
fs.writeFileSync(outside, "keep me");
fs.symlinkSync(outside, wavAbs);
const dangling = join(project, "dangling.wav");
fs.symlinkSync(join(root, "made-outside"), dangling);
assert.deepEqual(await request(), { ok: true, words: null });
assert.deepEqual(await request(provider, "synthetic café", dangling), { ok: true, words: null });
assert.equal(fs.readFileSync(outside, "utf8"), "keep me");
assert.equal(fs.existsSync(join(root, "made-outside")), false);
for (const out of [wavAbs, dangling]) {
assert.ok(fs.lstatSync(out).isFile());
assert.equal(fs.readFileSync(out, "utf8"), "synthetic café");
}
} else {
const result = await request();
const label = provider === "elevenlabs" ? "elevenlabs (python)" : "kokoro (npx hyperframes tts)";
@@ -106,7 +123,7 @@ if (["allocation", "write", "spawn-throw"].includes(mode)) {
assert.equal(fs.readFileSync(wavAbs, "utf8"), "synthetic café");
}
if (mode !== "enoent") {
const log = JSON.parse(fs.readFileSync(wavAbs + ".json", "utf8"));
const log = JSON.parse(fs.readFileSync(join(root, "line.wav.json"), "utf8"));
assert.equal(log.text, "synthetic café");
assert.equal(log.consumed, log.text);
if (provider === "kokoro") assert.deepEqual(log.args.slice(-4), ["--lang", "es", "--speed", "0.8"]);
@@ -165,6 +182,7 @@ for (const provider of ["elevenlabs", "kokoro"]) {
"allocation",
"write",
"cleanup",
"link",
]) {
test(
`synthesizeOne(${provider}) preserves ${mode} behavior and cleans only its text directory`,
+49 -33
View File
@@ -1,6 +1,7 @@
import "../../../scripts/lib/windows-exe-search.mjs";
import { fetchMedia } from "../../../scripts/lib/media-fetch.mjs";
import { refuseUnderLimit } from "../../../scripts/lib/credit-limit.mjs";
import { replaceFile } from "../../../scripts/lib/manifest.mjs";
// tts.mjs — multi-provider TTS for the media audio engine. The provider chain,
// auto-detected from env, is the one documented in ../SKILL.md:
//
@@ -19,7 +20,7 @@ import { refuseUnderLimit } from "../../../scripts/lib/credit-limit.mjs";
import { spawn, spawnSync } from "node:child_process";
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { dirname, isAbsolute, join } from "node:path";
import { basename, dirname, isAbsolute, join } from "node:path";
import {
heygenAuthHeaders,
heygenCredential,
@@ -254,19 +255,26 @@ export function spawnP(
});
}
// mp3/whatever bytes → wav 44.1k mono at destWav (ffmpeg detects true format).
// mp3/whatever bytes → wav 44.1k mono at destWav (ffmpeg detects true format). ffmpeg writes in a
// private temp folder and the result replaces destWav, so a link at destWav is replaced, not followed.
function transcodeToWav(bytes, destWav) {
const td = mkdtempSync(join(tmpdir(), "hf-tts-"));
const tmp = join(td, "a.mp3");
writeFileSync(tmp, bytes);
mkdirSync(dirname(destWav), { recursive: true });
const ff = spawnSync(
"ffmpeg",
["-y", "-loglevel", "error", "-i", tmp, "-ar", "44100", "-ac", "1", destWav],
{ stdio: "ignore" },
);
rmSync(td, { recursive: true, force: true });
return ff.status === 0 && existsSync(destWav);
try {
const tmp = join(td, "a.mp3");
const wav = join(td, "a.wav");
writeFileSync(tmp, bytes);
const ff = spawnSync(
"ffmpeg",
["-y", "-loglevel", "error", "-i", tmp, "-ar", "44100", "-ac", "1", wav],
{ stdio: "ignore" },
);
if (ff.status !== 0 || !existsSync(wav)) return false;
mkdirSync(dirname(destWav), { recursive: true });
replaceFile(destWav, readFileSync(wav));
return true;
} finally {
rmSync(td, { recursive: true, force: true });
}
}
const ELEVENLABS_PY = `
@@ -302,32 +310,43 @@ export async function synthesizeOne({
if (provider === "gemini")
return synthesizeGemini({ text, voiceId, model, style, speed, wavAbs });
if (provider === "elevenlabs") {
// The Python helper writes straight to wavAbs; unlike heygen (transcodeToWav)
// and kokoro (the `hyperframes tts` CLI), it does NOT create the parent dir,
// so on a fresh project (no assets/voice/ yet) the save fails and the line is
// silently dropped as "TTS failed - omitted". Create it first, like the other
// providers do. Guarded so a mkdir failure (EACCES/EROFS) returns
// { ok:false } like the rest of this branch rather than throwing (the
// function's contract is "never throws; failures return { ok:false }").
// The output folder is made before the request, so a folder that cannot be made
// (EACCES/EROFS) drops the line before it spends a generation. Guarded so that
// failure returns { ok:false } rather than throwing (the function's contract is
// "never throws; failures return { ok:false }").
try {
mkdirSync(dirname(wavAbs), { recursive: true });
} catch {
return { ok: false, words: null };
}
return withTmpText(text, async (textPath) => {
const { cmd, args } = pythonInvocation(["-c", ELEVENLABS_PY, textPath, voiceId, wavAbs]);
const r = await spawnP(cmd, args, {});
return synthResult(r, wavAbs, "elevenlabs (python)");
return withStagedWav(text, wavAbs, "elevenlabs (python)", (textPath, staged) => {
const { cmd, args } = pythonInvocation(["-c", ELEVENLABS_PY, textPath, voiceId, staged]);
return spawnP(cmd, args, {});
});
}
// kokoro — via the published CLI; --output is relative to the project dir.
const wavRel = relTo(hyperframesDir, wavAbs);
return withTmpText(text, async (textPath) => {
const args = ["hyperframes", "tts", textPath, "--voice", voiceId, "--output", wavRel];
// kokoro — via the published CLI, run in the project dir.
return withStagedWav(text, wavAbs, "kokoro (npx hyperframes tts)", (textPath, staged) => {
const args = ["hyperframes", "tts", textPath, "--voice", voiceId, "--output", staged];
if (lang !== "en") args.push("--lang", lang);
if (speed !== 1) args.push("--speed", String(speed));
const r = await spawnP("npx", args, { cwd: hyperframesDir });
return synthResult(r, wavAbs, "kokoro (npx hyperframes tts)");
return spawnP("npx", args, { cwd: hyperframesDir });
});
}
// The subprocess writes into the private text folder; its wav then replaces wavAbs, so a link
// at wavAbs is replaced, not followed.
function withStagedWav(text, wavAbs, label, run) {
return withTmpText(text, async (textPath) => {
const staged = join(dirname(textPath), basename(wavAbs));
const result = synthResult(await run(textPath, staged), staged, label);
if (!result.ok) return result;
try {
mkdirSync(dirname(wavAbs), { recursive: true });
replaceFile(wavAbs, readFileSync(staged));
} catch (error) {
return { ok: false, words: null, error: `${label}: ${error.message}` };
}
return result;
});
}
@@ -380,7 +399,7 @@ export async function synthesizeHeygen({ text, voiceId, lang, speed, wavAbs }, d
}
} else {
mkdirSync(dirname(wavAbs), { recursive: true });
writeFileSync(wavAbs, bytes);
replaceFile(wavAbs, bytes);
}
const words = Array.isArray(inner.word_timestamps)
? inner.word_timestamps
@@ -431,6 +450,3 @@ async function withTmpText(text, run) {
} catch {}
}
}
function relTo(base, abs) {
return abs.startsWith(base + "/") ? abs.slice(base.length + 1) : abs;
}
+20 -3
View File
@@ -114,15 +114,32 @@ export function refuseLink(path) {
export function replaceFile(path, content) {
// Same shape as core atomicTempPath, which Studio's project history skips.
const temp = `${path}.hf${randomBytes(3).toString("hex")}.tmp`;
writeFileSync(temp, content, { flag: "wx" });
try {
renameSync(temp, path);
writeFileSync(temp, content, { flag: "wx" });
renameRidingWindowsHolds(temp, path);
} catch (error) {
rmSync(temp, { force: true });
// EEXIST: the random name belongs to another writer, so it is left alone.
if (error?.code !== "EEXIST") rmSync(temp, { force: true });
throw error;
}
}
// Windows refuses a rename for a moment while antivirus or a just-exited process still holds the file.
const WINDOWS_HOLD = new Set(["EPERM", "EACCES", "EBUSY"]);
const HOLD_BACKOFF_MS = [10, 20, 40, 80, 160, 320, 640];
function renameRidingWindowsHolds(from, to) {
for (let attempt = 0; ; attempt++) {
try {
return renameSync(from, to);
} catch (error) {
const held = process.platform === "win32" && WINDOWS_HOLD.has(error?.code);
if (!held || attempt >= HOLD_BACKOFF_MS.length) throw error;
sleepMs(HOLD_BACKOFF_MS[attempt]);
}
}
}
export function appendRecord(projectDir, record) {
ownMediaDir(projectDir, typeSubdir(record.type));