Skip to content

Write HTML. Render video. Built for agents.

feat(media-use): clone, list and delete HeyGen voices, and accept a host OAuth token (#4992)

Miguel Ángel2497402b270a
diff --git a/skills-manifest.json b/skills-manifest.json
index 038f8dfa52..0f29762fb9 100644
--- a/skills-manifest.json
+++ b/skills-manifest.json
@@ -54,8 +54,8 @@
"files": 1
},
"media-use": {
- "hash": "92e7e0e170665b11",
- "files": 104
+ "hash": "9b98931fc057f125",
+ "files": 107
},
"motion-graphics": {
"hash": "b01efe567a52b5eb",
diff --git a/skills/media-use/audio/references/tts.md b/skills/media-use/audio/references/tts.md
index 8a4791dcf7..231fcc8a5f 100644
--- a/skills/media-use/audio/references/tts.md
+++ b/skills/media-use/audio/references/tts.md
@@ -40,11 +40,11 @@ Gemini is an explicit alternative to the automatic provider order below. A
request to use Gemini already chooses the provider; do not redirect that user
to HeyGen sign-in. Read the Gemini section for its credential requirement.
-| Order | Provider | Env trigger | Voice IDs | Word timestamps | Audio format |
-| ----- | ----------------- | ------------------------------------------- | ------------------------------------------- | ----------------------------------------- | -------------------- |
-| 1 | HeyGen (Starfish) | `$HEYGEN_API_KEY` / `~/.heygen/credentials` | UUIDs from `GET /v3/voices?engine=starfish` | **Yes** (`word_timestamps[]` in response) | mp3 → wav via ffmpeg |
-| 2 | ElevenLabs | `$ELEVENLABS_API_KEY` | UUIDs from elevenlabs.io dashboard | No | mp3 → wav via ffmpeg |
-| 3 | Kokoro-82M | always (local fallback) | `am_michael`, `af_heart`, … (54 voices) | No | wav direct |
+| Order | Provider | Env trigger | Voice IDs | Word timestamps | Audio format |
+| ----- | ----------------- | -------------------------------------------------------------------- | ------------------------------------------------------------------------------------------ | ----------------------------------------- | -------------------- |
+| 1 | HeyGen (Starfish) | `$HEYGEN_ACCESS_TOKEN` / `$HEYGEN_API_KEY` / `~/.heygen/credentials` | UUIDs from `GET /v3/voices?engine=starfish`, or your cloned voice ids (`heygen-voice.mjs`) | **Yes** (`word_timestamps[]` in response) | mp3 → wav via ffmpeg |
+| 2 | ElevenLabs | `$ELEVENLABS_API_KEY` | UUIDs from elevenlabs.io dashboard | No | mp3 → wav via ffmpeg |
+| 3 | Kokoro-82M | always (local fallback) | `am_michael`, `af_heart`, … (54 voices) | No | wav direct |
```bash
# Local Kokoro CLI
@@ -59,7 +59,8 @@ the skill's bundled script, which calls the HeyGen v3 REST API directly and need
no CLI provider plumbing:
The script resolves a HeyGen credential the same way the CLI does — first source
-wins: `$HEYGEN_API_KEY` → `$HYPERFRAMES_API_KEY` → a project `.env` (auto-loaded,
+wins: a host-injected OAuth `$HEYGEN_ACCESS_TOKEN` → `$HEYGEN_API_KEY` →
+`$HYPERFRAMES_API_KEY` → a project `.env` (auto-loaded,
walks up ≤5 dirs) → `~/.heygen/credentials` (shared with heygen-cli;
`$HEYGEN_CONFIG_DIR` overrides the dir). An OAuth login is sent as
`Authorization: Bearer`; an API key as `X-Api-Key`; both include
@@ -80,11 +81,27 @@ node skills/media-use/audio/scripts/heygen-tts.mjs ./script.txt -o narration.wav
node skills/media-use/audio/scripts/heygen-tts.mjs --list # public starfish voices
```
-- **Voice:** `--voice <id>` must be a **starfish** voice_id (`--list`, or `GET /v3/voices?engine=starfish`). v2-catalog ids are rejected with HTTP 400. Omit `--voice` (English) and it defaults to **Marcia** (`05f19352e8f74b0392a8f411eba40de1`, a fixed default so the choice is deterministic). Non-English with no `--voice` falls back to the first matching catalog voice.
+- **Voice:** `--voice <id>` must be a **starfish** voice_id (`--list`, or `GET /v3/voices?engine=starfish`) or one of your cloned voice ids (below). v2-catalog ids are rejected with HTTP 400. Omit `--voice` (English) and it defaults to **Marcia** (`05f19352e8f74b0392a8f411eba40de1`, a fixed default so the choice is deterministic). Non-English with no `--voice` falls back to the first matching catalog voice.
- **Output:** `.wav` → transcoded to 44.1k mono via ffmpeg; `.mp3` → raw bytes (no ffmpeg needed).
- **Words:** `--words <path>` writes the flat `[{id,text,start,end}]` shape below, drop-in for the captions pipeline. HeyGen's `<start>`/`<end>` boundary sentinels are filtered out and ids are re-contiguous.
- **Non-English:** `--lang <code>` (anything but `en`) is sent as the request `language`.
+## Cloned voices — `scripts/heygen-voice.mjs`
+
+Clone a voice from an mp3 or wav recording, then pass the printed id to
+`heygen-tts.mjs --voice`. Same credential resolution as above. Any API refusal
+(clone limit reached, plan upgrade required, voice not found) prints HeyGen's own
+message to stderr and exits 1.
+
+```bash
+node skills/media-use/audio/scripts/heygen-voice.mjs clone take.mp3 --name "My voice" # → {"voice_id":"..."}
+node skills/media-use/audio/scripts/heygen-voice.mjs list --prefix "My" # → [{"voice_id","name","created_at"}]
+node skills/media-use/audio/scripts/heygen-voice.mjs delete <voice_id>
+```
+
+`clone` waits up to 120 s for the clone to finish. `list` reads
+`GET /v3/voices?type=private`.
+
## When to use which provider
| Goal | Use |
diff --git a/skills/media-use/audio/scripts/heygen-tts.mjs b/skills/media-use/audio/scripts/heygen-tts.mjs
index 3b6dcbf4a8..3e1de356bf 100755
--- a/skills/media-use/audio/scripts/heygen-tts.mjs
+++ b/skills/media-use/audio/scripts/heygen-tts.mjs
@@ -94,7 +94,7 @@ const voiceId = await resolveVoiceId({ provider: "heygen", userVoice, lang });
if (!userVoice) console.error(`· using voice ${voiceId}`);
// ---------- synthesize (shared engine code) ----------
-const { ok, words } = await synthesizeOne({
+const { ok, words, error } = await synthesizeOne({
provider: "heygen",
text,
voiceId,
@@ -103,7 +103,8 @@ const { ok, words } = await synthesizeOne({
wavAbs: output,
hyperframesDir: process.cwd(),
});
-if (!ok) die("synthesis failed (HeyGen request/transcode error)");
+// HeyGen's own refusal, verbatim: a caller shows it or acts on it (a deleted voice, a limit).
+if (!ok) die(error ?? "synthesis failed (HeyGen request/transcode error)");
let wordCount = 0;
if (wordsPath) {
diff --git a/skills/media-use/audio/scripts/heygen-tts.test.mjs b/skills/media-use/audio/scripts/heygen-tts.test.mjs
new file mode 100644
index 0000000000..1730ba8023
--- /dev/null
+++ b/skills/media-use/audio/scripts/heygen-tts.test.mjs
@@ -0,0 +1,38 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { spawnSync } from "node:child_process";
+import { mkdtempSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { fileURLToPath } from "node:url";
+
+const script = fileURLToPath(new URL("./heygen-tts.mjs", import.meta.url));
+// Every fetch answers as HeyGen does for a voice that no longer exists.
+const refusing = `data:text/javascript,globalThis.fetch = async () => new Response(${JSON.stringify(
+ JSON.stringify({ error: { code: "voice_not_found", message: "Voice not found: vc_gone" } }),
+)}, { status: 404, headers: { "content-type": "application/json" } });`;
+
+test("a refused speech prints HeyGen's own message, so a caller can act on it", () => {
+ const dir = mkdtempSync(join(tmpdir(), "heygen-tts-"));
+ const run = spawnSync(
+ process.execPath,
+ ["--import", refusing, script, "Hello", "--voice", "vc_gone", "-o", join(dir, "out.mp3")],
+ {
+ cwd: dir,
+ encoding: "utf8",
+ env: {
+ ...process.env,
+ HEYGEN_API_KEY: "",
+ HYPERFRAMES_API_KEY: "",
+ HEYGEN_ACCESS_TOKEN: "t",
+ },
+ },
+ );
+ assert.equal(run.status, 1);
+ assert.match(run.stderr, /✗ heygen-tts: Voice not found: vc_gone\n/);
+ assert.doesNotMatch(
+ run.stderr,
+ /HTTP 404|"error"/,
+ "HeyGen's message alone, not the raw response",
+ );
+});
diff --git a/skills/media-use/audio/scripts/heygen-voice.mjs b/skills/media-use/audio/scripts/heygen-voice.mjs
new file mode 100644
index 0000000000..7a5559750b
--- /dev/null
+++ b/skills/media-use/audio/scripts/heygen-voice.mjs
@@ -0,0 +1,98 @@
+#!/usr/bin/env node
+// HeyGen voice clones: `clone <audio> --name <n>`, `delete <voice_id>`, `list --prefix <p>` (references/tts.md).
+// The clone id works as `heygen-tts.mjs --voice <id>`. A refusal prints HeyGen's own message and exits 1.
+// Auth: same resolver as heygen-tts.mjs (lib/heygen.mjs).
+
+import { readFileSync } from "node:fs";
+import { extname } from "node:path";
+import { fileURLToPath } from "node:url";
+import { parseArgs } from "node:util";
+import { heygenAuthHeaders, heygenJSON, heygenMessage, loadEnvFromDir } from "./lib/heygen.mjs";
+
+const MEDIA_TYPES = { ".mp3": "audio/mpeg", ".wav": "audio/wav" };
+const POLL_MS = 2_000;
+const DEADLINE_MS = 120_000;
+
+async function clone(file, name, headers, { sleep, now }) {
+ const mediaType = MEDIA_TYPES[extname(file).toLowerCase()];
+ if (!mediaType) throw new Error(`unsupported audio file ${file}: use .mp3 or .wav`);
+ const data = readFileSync(file).toString("base64");
+ const created = await heygenJSON("/voices/clone", {
+ method: "POST",
+ headers,
+ body: { voice_name: name, audio: { type: "base64", media_type: mediaType, data } },
+ });
+ const id = created.data.voice_clone_id;
+ const deadline = now() + DEADLINE_MS;
+ for (;;) {
+ const { data: voice } = await heygenJSON(`/voices/${id}`, { headers });
+ if (voice.status === "complete") return { voice_id: voice.voice_id ?? id };
+ if (voice.status === "failed") throw new Error(voice.failure_message || "voice clone failed");
+ if (now() >= deadline) throw new Error(`voice clone ${id} not ready after 120 s`);
+ await sleep(POLL_MS);
+ }
+}
+
+async function list(prefix, headers) {
+ const mine = [];
+ const seen = new Set();
+ let token;
+ do {
+ if (token && seen.has(token)) throw new Error(`HeyGen returned page token ${token} twice`);
+ if (token) seen.add(token);
+ const query = new URLSearchParams({ type: "private", limit: "100" });
+ if (token) query.set("token", token);
+ const page = await heygenJSON(`/voices?${query}`, { headers });
+ mine.push(...page.data.filter((v) => (v.name ?? "").startsWith(prefix)));
+ token = page.has_more ? page.next_token : null;
+ } while (token);
+ // ponytail: the list response has no created_at, so one GET per match; bounded by the clone limit.
+ return Promise.all(
+ mine.map(async ({ voice_id, name }) => {
+ const { data } = await heygenJSON(`/voices/${voice_id}`, { headers });
+ return { voice_id, name, created_at: data.created_at ?? null };
+ }),
+ );
+}
+
+export async function main(
+ argv,
+ {
+ sleep = (ms) => new Promise((r) => setTimeout(r, ms)),
+ now = Date.now,
+ out = (s) => process.stdout.write(`${s}\n`),
+ err = (s) => process.stderr.write(`${s}\n`),
+ } = {},
+) {
+ try {
+ const { positionals, values } = parseArgs({
+ args: argv,
+ allowPositionals: true,
+ options: { name: { type: "string" }, prefix: { type: "string", default: "" } },
+ });
+ const [command, arg] = positionals;
+ if (command === "clone") {
+ if (!arg || !values.name) throw new Error("usage: clone <audio-file> --name <name>");
+ out(JSON.stringify(await clone(arg, values.name, heygenAuthHeaders(), { sleep, now })));
+ } else if (command === "delete") {
+ if (!arg) throw new Error("usage: delete <voice_id>");
+ await heygenJSON(`/voices/${encodeURIComponent(arg)}`, {
+ method: "DELETE",
+ headers: heygenAuthHeaders(),
+ });
+ } else if (command === "list") {
+ out(JSON.stringify(await list(values.prefix, heygenAuthHeaders())));
+ } else {
+ throw new Error("usage: heygen-voice.mjs clone|delete|list (see the header of this file)");
+ }
+ return 0;
+ } catch (e) {
+ err(heygenMessage(e));
+ return 1;
+ }
+}
+
+if (process.argv[1] === fileURLToPath(import.meta.url)) {
+ loadEnvFromDir(process.cwd());
+ process.exitCode = await main(process.argv.slice(2));
+}
diff --git a/skills/media-use/audio/scripts/heygen-voice.test.mjs b/skills/media-use/audio/scripts/heygen-voice.test.mjs
new file mode 100644
index 0000000000..717b1b1274
--- /dev/null
+++ b/skills/media-use/audio/scripts/heygen-voice.test.mjs
@@ -0,0 +1,233 @@
+import { afterEach, beforeEach, test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { main } from "./heygen-voice.mjs";
+
+const realFetch = globalThis.fetch;
+const savedEnv = {
+ HEYGEN_ACCESS_TOKEN: process.env.HEYGEN_ACCESS_TOKEN,
+ HEYGEN_API_KEY: process.env.HEYGEN_API_KEY,
+};
+let dir;
+let calls;
+
+beforeEach(() => {
+ dir = mkdtempSync(join(tmpdir(), "heygen-voice-"));
+ delete process.env.HEYGEN_ACCESS_TOKEN;
+ process.env.HEYGEN_API_KEY = "hg_test";
+ calls = [];
+});
+
+afterEach(() => {
+ globalThis.fetch = realFetch;
+ for (const [k, v] of Object.entries(savedEnv)) {
+ if (v === undefined) delete process.env[k];
+ else process.env[k] = v;
+ }
+ rmSync(dir, { recursive: true, force: true });
+});
+
+// routes: "METHOD /path" → array of [status, body] answered in order (last one repeats).
+function mockFetch(routes) {
+ globalThis.fetch = async (url, opts) => {
+ const key = `${opts.method} ${String(url).replace("https://api.heygen.com/v3", "")}`;
+ calls.push({ key, opts });
+ const queue = routes[key];
+ if (!queue) throw new Error(`unexpected request ${key}`);
+ const [status, body] = queue.length > 1 ? queue.shift() : queue[0];
+ return new Response(body === undefined ? null : JSON.stringify(body), { status });
+ };
+}
+
+async function run(argv, { sleep = async () => {}, now = () => 0 } = {}) {
+ const out = [];
+ const err = [];
+ const code = await main(argv, {
+ sleep,
+ now,
+ out: (s) => out.push(s),
+ err: (s) => err.push(s),
+ });
+ return { code, out: out.join("\n"), err: err.join("\n") };
+}
+
+function audioFile(name = "sample.mp3") {
+ const path = join(dir, name);
+ writeFileSync(path, Buffer.from("fake-audio"));
+ return path;
+}
+
+test("clone uploads base64 audio, polls until complete, prints the voice id", async () => {
+ mockFetch({
+ "POST /voices/clone": [[200, { data: { voice_clone_id: "vc1" } }]],
+ "GET /voices/vc1": [
+ [200, { data: { status: "processing", voice_id: "vc1" } }],
+ [200, { data: { status: "complete", voice_id: "vc1", name: "Me" } }],
+ ],
+ });
+ const sleeps = [];
+ const r = await run(["clone", audioFile(), "--name", "Me"], {
+ sleep: async (ms) => sleeps.push(ms),
+ });
+ assert.deepEqual(r, { code: 0, out: '{"voice_id":"vc1"}', err: "" });
+ assert.deepEqual(sleeps, [2000]);
+ const post = calls[0];
+ assert.equal(post.opts.headers["X-Api-Key"], "hg_test");
+ assert.deepEqual(JSON.parse(post.opts.body), {
+ voice_name: "Me",
+ audio: {
+ type: "base64",
+ media_type: "audio/mpeg",
+ data: Buffer.from("fake-audio").toString("base64"),
+ },
+ });
+});
+
+test("clone sends audio/wav for a .wav file", async () => {
+ mockFetch({
+ "POST /voices/clone": [[200, { data: { voice_clone_id: "vc1" } }]],
+ "GET /voices/vc1": [[200, { data: { status: "complete", voice_id: "vc1" } }]],
+ });
+ const r = await run(["clone", audioFile("take.WAV"), "--name", "Me"]);
+ assert.equal(r.code, 0);
+ assert.equal(JSON.parse(calls[0].opts.body).audio.media_type, "audio/wav");
+});
+
+test("clone prints HeyGen's refusal verbatim and exits 1", async () => {
+ const message =
+ "Voice clone limit reached (10). Delete unused clones or contact support to increase your limit.";
+ mockFetch({
+ "POST /voices/clone": [[400, { error: { code: "resource_limit_reached", message } }]],
+ });
+ const r = await run(["clone", audioFile(), "--name", "Me"]);
+ assert.deepEqual(r, { code: 1, out: "", err: message });
+});
+
+test("clone surfaces a failed clone's failure_message", async () => {
+ mockFetch({
+ "POST /voices/clone": [[200, { data: { voice_clone_id: "vc1" } }]],
+ "GET /voices/vc1": [[200, { data: { status: "failed", failure_message: "Audio too noisy" } }]],
+ });
+ const r = await run(["clone", audioFile(), "--name", "Me"]);
+ assert.deepEqual(r, { code: 1, out: "", err: "Audio too noisy" });
+});
+
+test("clone gives up after the 120 s deadline", async () => {
+ mockFetch({
+ "POST /voices/clone": [[200, { data: { voice_clone_id: "vc1" } }]],
+ "GET /voices/vc1": [[200, { data: { status: "processing" } }]],
+ });
+ let clock = 0;
+ const r = await run(["clone", audioFile(), "--name", "Me"], {
+ now: () => clock,
+ sleep: async (ms) => {
+ clock += ms;
+ },
+ });
+ assert.deepEqual(r, { code: 1, out: "", err: "voice clone vc1 not ready after 120 s" });
+ assert.equal(calls.filter((c) => c.key === "GET /voices/vc1").length, 61);
+});
+
+test("clone rejects an audio type other than mp3 or wav without calling HeyGen", async () => {
+ mockFetch({});
+ const r = await run(["clone", audioFile("take.ogg"), "--name", "Me"]);
+ assert.equal(r.code, 1);
+ assert.match(r.err, /use \.mp3 or \.wav/);
+ assert.equal(calls.length, 0);
+});
+
+test("delete calls DELETE /voices/<id> and exits 0", async () => {
+ mockFetch({ "DELETE /voices/vc1": [[200, { data: {} }]] });
+ const r = await run(["delete", "vc1"]);
+ assert.deepEqual(r, { code: 0, out: "", err: "" });
+});
+
+test("delete exits 0 on a 204 with no body, and escapes the id in the path", async () => {
+ mockFetch({ "DELETE /voices/a%2Fb": [[204]] });
+ const r = await run(["delete", "a/b"]);
+ assert.deepEqual(r, { code: 0, out: "", err: "" });
+});
+
+test("clone falls back to the clone id when the finished voice has no voice_id", async () => {
+ mockFetch({
+ "POST /voices/clone": [[200, { data: { voice_clone_id: "vc9" } }]],
+ "GET /voices/vc9": [[200, { data: { status: "complete" } }]],
+ });
+ const r = await run(["clone", audioFile(), "--name", "Me"]);
+ assert.deepEqual(r, { code: 0, out: '{"voice_id":"vc9"}', err: "" });
+});
+
+test("list skips a nameless voice and stops on a page token HeyGen repeats", async () => {
+ mockFetch({
+ "GET /voices?type=private&limit=100": [
+ [200, { data: [{ voice_id: "n", name: null }], has_more: true, next_token: "t2" }],
+ ],
+ "GET /voices?type=private&limit=100&token=t2": [
+ [200, { data: [], has_more: true, next_token: "t2" }],
+ ],
+ });
+ // A fake answers at once, so a list that never stops would starve any timeout: cap the calls instead.
+ const answer = globalThis.fetch;
+ globalThis.fetch = (...args) =>
+ calls.length >= 10 ? Promise.reject(new Error("paged forever")) : answer(...args);
+ const r = await run(["list", "--prefix", "desk-"]);
+ assert.deepEqual(r, { code: 1, out: "", err: "HeyGen returned page token t2 twice" });
+});
+
+test("delete prints HeyGen's 404 message verbatim and exits 1", async () => {
+ mockFetch({
+ "DELETE /voices/gone": [
+ [404, { error: { code: "voice_not_found", message: "Voice not found: gone" } }],
+ ],
+ });
+ const r = await run(["delete", "gone"]);
+ assert.deepEqual(r, { code: 1, out: "", err: "Voice not found: gone" });
+});
+
+test("list pages through private voices and returns prefix matches with created_at", async () => {
+ mockFetch({
+ "GET /voices?type=private&limit=100": [
+ [
+ 200,
+ {
+ data: [
+ { voice_id: "a", name: "desk-1" },
+ { voice_id: "b", name: "other" },
+ ],
+ has_more: true,
+ next_token: "t2",
+ },
+ ],
+ ],
+ "GET /voices?type=private&limit=100&token=t2": [
+ [200, { data: [{ voice_id: "c", name: "desk-2" }], has_more: false }],
+ ],
+ "GET /voices/a": [[200, { data: { voice_id: "a", created_at: 1700000000 } }]],
+ "GET /voices/c": [[200, { data: { voice_id: "c", created_at: 1700000100 } }]],
+ });
+ const r = await run(["list", "--prefix", "desk-"]);
+ assert.equal(r.code, 0);
+ assert.deepEqual(JSON.parse(r.out), [
+ { voice_id: "a", name: "desk-1", created_at: 1700000000 },
+ { voice_id: "c", name: "desk-2", created_at: 1700000100 },
+ ]);
+});
+
+test("list prints HeyGen's refusal verbatim and exits 1", async () => {
+ const message = "Invalid or expired API key. Verify your x-api-key header.";
+ mockFetch({
+ "GET /voices?type=private&limit=100": [[401, { error: { code: "unauthorized", message } }]],
+ });
+ const r = await run(["list", "--prefix", "desk-"]);
+ assert.deepEqual(r, { code: 1, out: "", err: message });
+});
+
+test("a host-injected HEYGEN_ACCESS_TOKEN is sent as Bearer", async () => {
+ process.env.HEYGEN_ACCESS_TOKEN = "at_host";
+ mockFetch({ "DELETE /voices/vc1": [[200, { data: {} }]] });
+ await run(["delete", "vc1"]);
+ assert.equal(calls[0].opts.headers.Authorization, "Bearer at_host");
+ assert.equal(calls[0].opts.headers["X-Api-Key"], undefined);
+});
diff --git a/skills/media-use/audio/scripts/lib/heygen.mjs b/skills/media-use/audio/scripts/lib/heygen.mjs
index 245263857f..955e286e33 100644
--- a/skills/media-use/audio/scripts/lib/heygen.mjs
+++ b/skills/media-use/audio/scripts/lib/heygen.mjs
@@ -1,7 +1,8 @@
import { fetchMedia } from "../../../scripts/lib/media-fetch.mjs";
// heygen.mjs — vendored HeyGen REST helpers (auth + transport) for the audio
// pipeline. The credential resolver matches the hyperframes CLI auth: first
-// usable source wins — $HEYGEN_API_KEY / $HYPERFRAMES_API_KEY → a nearby .env → ~/.heygen/
+// usable source wins — a host-injected OAuth $HEYGEN_ACCESS_TOKEN (Bearer) →
+// $HEYGEN_API_KEY / $HYPERFRAMES_API_KEY → a nearby .env → ~/.heygen/
// credentials (oauth → Bearer, else api_key → X-Api-Key; $HEYGEN_CONFIG_DIR
// overrides the dir). Vendored so the skill ships standalone. Pure node.
@@ -67,6 +68,8 @@ export function heygenCredential() {
// (a folder, a locked ~/.heygen), so heygenAuthHeaders can say to fix that path: logging in again would fail there too.
// Read without checking first, so the file cannot change between a check and the read.
function resolveCredential() {
+ const accessToken = process.env.HEYGEN_ACCESS_TOKEN;
+ if (accessToken) return { headers: { Authorization: `Bearer ${accessToken}` } };
const envKey = process.env.HEYGEN_API_KEY || process.env.HYPERFRAMES_API_KEY;
if (envKey) return { headers: { "X-Api-Key": envKey } };
@@ -144,11 +147,22 @@ export async function heygenJSON(path, { method = "GET", headers = {}, body } =
const res = await fetch(`${HEYGEN_BASE}${path}`, opts);
if (!res.ok) {
const detail = await res.text().catch(() => "");
- throw new Error(
- `HeyGen ${method} ${path} → HTTP ${res.status}${detail ? `\n${detail.slice(0, 300)}` : ""}`,
- );
+ const message = `HeyGen ${method} ${path} → HTTP ${res.status}${detail ? `\n${detail.slice(0, 300)}` : ""}`;
+ throw Object.assign(new Error(message), { status: res.status, body: detail });
+ }
+ // A DELETE may answer 204 with no body.
+ const text = await res.text();
+ return text ? JSON.parse(text) : {};
+}
+
+// HeyGen's own words for a failed call: its {"error":{"message"}}, else the raw body, else the error's message.
+export function heygenMessage(e) {
+ if (!e?.body) return e?.message ? String(e.message) : String(e);
+ try {
+ return JSON.parse(e.body).error?.message ?? e.body;
+ } catch {
+ return e.body;
}
- return res.json();
}
// Download a (presigned) URL to destPath; returns byte length.
diff --git a/skills/media-use/audio/scripts/lib/heygen.test.mjs b/skills/media-use/audio/scripts/lib/heygen.test.mjs
index 1fcfa56eb2..84e0bc440b 100644
--- a/skills/media-use/audio/scripts/lib/heygen.test.mjs
+++ b/skills/media-use/audio/scripts/lib/heygen.test.mjs
@@ -11,15 +11,19 @@ import {
} from "./heygen.mjs";
function withCleanHeygenEnv(fn) {
+ const previousAccessToken = process.env.HEYGEN_ACCESS_TOKEN;
const previousApiKey = process.env.HEYGEN_API_KEY;
const previousHyperframesApiKey = process.env.HYPERFRAMES_API_KEY;
const previousConfigDir = process.env.HEYGEN_CONFIG_DIR;
try {
+ delete process.env.HEYGEN_ACCESS_TOKEN;
delete process.env.HEYGEN_API_KEY;
delete process.env.HYPERFRAMES_API_KEY;
delete process.env.HEYGEN_CONFIG_DIR;
return fn();
} finally {
+ if (previousAccessToken === undefined) delete process.env.HEYGEN_ACCESS_TOKEN;
+ else process.env.HEYGEN_ACCESS_TOKEN = previousAccessToken;
if (previousApiKey === undefined) delete process.env.HEYGEN_API_KEY;
else process.env.HEYGEN_API_KEY = previousApiKey;
if (previousHyperframesApiKey === undefined) delete process.env.HYPERFRAMES_API_KEY;
@@ -67,6 +71,19 @@ test("heygenAuthHeaders tags OAuth requests as CLI traffic and with the media-us
});
});
+test("a host-injected HEYGEN_ACCESS_TOKEN wins over an API key and is treated as OAuth", () => {
+ withCleanHeygenEnv(() => {
+ process.env.HEYGEN_ACCESS_TOKEN = "at_host";
+ process.env.HEYGEN_API_KEY = "hg_test";
+ assert.deepEqual(heygenAuthHeaders(), {
+ Authorization: "Bearer at_host",
+ "X-HeyGen-Source": "cli",
+ "X-HeyGen-Client-Source": "media-use",
+ });
+ assert.equal(heygenAuthMethod(), "oauth");
+ });
+});
+
test("heygenAuthMethod returns api_key for an env API key, without tagging headers", () => {
withCleanHeygenEnv(() => {
process.env.HEYGEN_API_KEY = "hg_test";
diff --git a/skills/media-use/audio/scripts/lib/tts.mjs b/skills/media-use/audio/scripts/lib/tts.mjs
index 7136ab0e0e..73d2a688e5 100644
--- a/skills/media-use/audio/scripts/lib/tts.mjs
+++ b/skills/media-use/audio/scripts/lib/tts.mjs
@@ -18,7 +18,7 @@ import { spawn, spawnSync } from "node:child_process";
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
-import { heygenAuthHeaders, heygenCredential, heygenJSON } from "./heygen.mjs";
+import { heygenAuthHeaders, heygenCredential, heygenJSON, heygenMessage } from "./heygen.mjs";
import { pythonInvocation } from "./python.mjs";
import { synthesizeGemini } from "./gemini-tts.mjs";
import { geminiConfigured } from "./gemini-auth.mjs";
@@ -350,7 +350,7 @@ export async function synthesizeHeygen({ text, voiceId, lang, speed, wavAbs }, d
: [];
return { ok: true, words };
} catch (e) {
- return { ok: false, words: null, error: e?.message ? String(e.message) : String(e) };
+ return { ok: false, words: null, error: heygenMessage(e) };
}
}