Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion skills-manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@
"files": 1
},
"media-use": {
"hash": "b07cf8ba10a8ac7b",
"hash": "d0875c7f8bc28d51",
"files": 109
},
"motion-graphics": {
Expand Down
10 changes: 6 additions & 4 deletions skills/media-use/SKILL.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
---
name: media-use
description: Agent Media OS for a HyperFrames project. Resolve BGM, SFX, image, icon, brand logo, voice, color grade, or LUT into a frozen local file or paste-ready block + ledger record (one verb, `resolve`); generate via TTS / music / image models when the catalog misses; produce voiceover, transcription, captions, and background removal through one shared audio engine; operate on media (cut / reframe / transform); and reuse assets across projects. Also use for vague feedback that real footage looks dark, flat, boring, should feel retro/camcorder/print/ASCII, needs privacy, or needs a media reveal. When the host app provides its own music or sound-effect tools, use those for music and sound effects; `resolve --type bgm|sfx` needs the heygen CLI.
description: Agent Media OS for a HyperFrames project. Resolve BGM, SFX, image, icon, brand logo, voice, color grade, or LUT into a frozen local file or paste-ready block + ledger record (one verb, `resolve`); generate via TTS / music / image models when the catalog misses; produce voiceover, transcription, captions, and background removal through one shared audio engine; operate on media (cut / reframe / transform); and reuse assets across projects. Also use for vague feedback that real footage looks dark, flat, boring, should feel retro/camcorder/print/ASCII, needs privacy, or needs a media reveal. When the host app provides its own music or sound-effect tools, use those for music and sound effects; `resolve --type bgm|sfx` needs the heygen CLI. When `HEYGEN_API_BASE` is set, HeyGen calls go through that host with no CLI sign-in.
---

**Plugin installs:** Before setup or freshness commands, follow [plugin execution rules](../hyperframes/references/plugin-installation.md) when this skill is inside a HyperFrames plugin. Standalone installs keep the update instructions below.
Expand All @@ -9,11 +9,13 @@ description: Agent Media OS for a HyperFrames project. Resolve BGM, SFX, image,

The media OS for HyperFrames: resolve · generate · operate · remember — every media type, one skill, zero context noise.

First run, when you will use HeyGen media (catalog search, TTS, avatar video): install and sign in to the `heygen` CLI (the free-usage path), then verify with `npx hyperframes media-use resolve --doctor`. Setup and providers: `references/setup-providers.md`.
Only when `HEYGEN_API_BASE` is set in your environment (a host app set it and pays for HeyGen with its own key): HeyGen media is already paid for. Do not ask the person to install or sign in to the `heygen` CLI and do not offer its OAuth allowance; catalog search, TTS and avatar calls here go through the host. When that same host also gives you its own HeyGen tools, use those first. When a call through the host is refused, tell the person the host's message as written (it names the fix, such as adding or replacing the key in the app's Settings) and stop; do not switch to another provider unless they ask.

Music and sound effects inside a host app: when the app you run in gives you its own music or sound-effect tools, use those. `resolve --type bgm` and `--type sfx` search the HeyGen catalog through the `heygen` CLI; without it they fail and say so (`sfx` still answers from its bundled library).
First run otherwise (no `HEYGEN_API_BASE`), when you will use HeyGen media (catalog search, TTS, avatar video): install and sign in to the `heygen` CLI (the free-usage path), then verify with `npx hyperframes media-use resolve --doctor`. Setup and providers: `references/setup-providers.md`.

Before generating a voiceover or an avatar video, tell the person: signing in to the heygen CLI with OAuth (`heygen auth login --oauth`) gives a free allowance for TTS voiceover and avatar videos, while an API key bills API credits.
Music and sound effects inside a host app: when the app you run in gives you its own music or sound-effect tools, use those. Without `HEYGEN_API_BASE`, `resolve --type bgm` and `--type sfx` search the HeyGen catalog through the `heygen` CLI; without it they fail and say so (`sfx` still answers from its bundled library).

Without `HEYGEN_API_BASE`, before generating a voiceover or an avatar video, tell the person: signing in to the heygen CLI with OAuth (`heygen auth login --oauth`) gives a free allowance for TTS voiceover and avatar videos, while an API key bills API credits.

## Resolve — the one verb

Expand Down
51 changes: 47 additions & 4 deletions skills/media-use/audio/scripts/lib/heygen.mjs
Original file line number Diff line number Diff line change
@@ -1,16 +1,51 @@
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 — a host-injected OAuth $HEYGEN_ACCESS_TOKEN (Bearer) →
// usable source wins — a host gateway ($HEYGEN_API_BASE with its own
// $HEYGEN_API_KEY) → 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.
// overrides the dir). $HEYGEN_API_BASE moves every request to that host, as it
// does for the heygen CLI; plain HTTP needs $HEYGEN_ALLOW_HTTP=1, as there.
// Vendored so the skill ships standalone. Pure node.

import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { homedir } from "node:os";
import { dirname, join, resolve } from "node:path";

export const HEYGEN_BASE = "https://api.heygen.com/v3";

// The v3 base every request goes to: $HEYGEN_API_BASE when a host app names its own gateway (HyperFrames Desktop
// forwards it to HeyGen with the API key saved in its Settings), else HeyGen's public API. Plain HTTP carries the key
// in the clear, so it needs $HEYGEN_ALLOW_HTTP=1, the heygen CLI's own rule.
export function heygenBase() {
const host = process.env.HEYGEN_API_BASE?.trim().replace(/\/+$/, "");
if (!host) return HEYGEN_BASE;
if (host.startsWith("http://") && process.env.HEYGEN_ALLOW_HTTP !== "1")
throw new Error(
`HEYGEN_API_BASE (${host}) uses HTTP, which sends the key in plaintext. Set HEYGEN_ALLOW_HTTP=1 to allow it.`,
);
return `${host}/v3`;
}

// No base override, or one on HeyGen's own hosts (a canary or dev API).
function heygenOwnBase() {
const host = process.env.HEYGEN_API_BASE?.trim();
if (!host) return true;
try {
const name = new URL(host).hostname;
return name === "heygen.com" || name.endsWith(".heygen.com");
} catch {
return false;
}
}

// A host gateway: the host named its own API base and the key that base accepts. It pays for every call, so it wins
// over any other credential the environment carries.
const hostGatewayKey = () =>
process.env.HEYGEN_API_BASE?.trim() && process.env.HEYGEN_API_KEY
? process.env.HEYGEN_API_KEY
: null;
export const HEYGEN_CLI_SOURCE_HEADERS = { "X-HeyGen-Source": "cli" };
// Tool-attribution sent on EVERY media-use HeyGen call regardless of auth type, so
// the backend can isolate media-use consumption from other free TTS / avatar video.
Expand All @@ -29,6 +64,10 @@ function envFileText(path) {
}
}

// A host app sets these in the environment it spawns, never in a project file: a project's .env naming its own base
// would send the person's shell HEYGEN_API_KEY to that host.
const HOST_ONLY = new Set(["HEYGEN_API_BASE", "HEYGEN_ALLOW_HTTP"]);

// Walk up ≤5 dirs from startDir; load the first .env (shell env always wins).
export function loadEnvFromDir(startDir) {
let dir = resolve(startDir);
Expand All @@ -48,7 +87,7 @@ export function loadEnvFromDir(startDir) {
const end = val.indexOf(q, 1);
val = end > 0 ? val.slice(1, end) : val.slice(1);
}
if (!(key in process.env)) process.env[key] = val;
if (!HOST_ONLY.has(key) && !(key in process.env)) process.env[key] = val;
}
return;
}
Expand All @@ -68,6 +107,10 @@ 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 gatewayKey = hostGatewayKey();
if (gatewayKey) return { headers: { "X-Api-Key": gatewayKey } };
// Every other credential belongs to HeyGen: a base on any other host gets none of them.
if (!heygenOwnBase()) return null;
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;
Expand Down Expand Up @@ -144,7 +187,7 @@ export async function heygenJSON(path, { method = "GET", headers = {}, body } =
opts.headers["Content-Type"] = "application/json";
opts.body = JSON.stringify(body);
}
const res = await fetch(`${HEYGEN_BASE}${path}`, opts);
const res = await fetch(`${heygenBase()}${path}`, opts);
if (!res.ok) {
const detail = await res.text().catch(() => "");
const message = `HeyGen ${method} ${path} → HTTP ${res.status}${detail ? `\n${detail.slice(0, 300)}` : ""}`;
Expand Down
143 changes: 125 additions & 18 deletions skills/media-use/audio/scripts/lib/heygen.test.mjs
Original file line number Diff line number Diff line change
@@ -1,36 +1,47 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
import { createServer } from "node:http";
import { tmpdir } from "node:os";
import { join } from "node:path";
import {
heygenAuthHeaders,
heygenAuthMethod,
heygenBase,
heygenCredential,
heygenJSON,
loadEnvFromDir,
} from "./heygen.mjs";

const HEYGEN_ENV = [
"HEYGEN_ACCESS_TOKEN",
"HEYGEN_API_KEY",
"HYPERFRAMES_API_KEY",
"HEYGEN_CONFIG_DIR",
"HEYGEN_API_BASE",
"HEYGEN_ALLOW_HTTP",
];

// Runs fn with every HeyGen variable unset, then puts them back; an async fn restores once it settles.
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;
const previous = Object.fromEntries(HEYGEN_ENV.map((name) => [name, process.env[name]]));
const restore = () => {
for (const [name, value] of Object.entries(previous)) {
if (value === undefined) delete process.env[name];
else process.env[name] = value;
}
};
for (const name of HEYGEN_ENV) delete process.env[name];
let result;
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;
else process.env.HYPERFRAMES_API_KEY = previousHyperframesApiKey;
if (previousConfigDir === undefined) delete process.env.HEYGEN_CONFIG_DIR;
else process.env.HEYGEN_CONFIG_DIR = previousConfigDir;
result = fn();
} catch (error) {
restore();
throw error;
}
if (result && typeof result.then === "function") return result.finally(restore);
restore();
return result;
}

test("heygenAuthHeaders does not tag API-key requests as CLI traffic, but still carries the media-use tool tag", () => {
Expand Down Expand Up @@ -138,6 +149,27 @@ test("loadEnvFromDir skips a .env folder and loads the .env file above it", () =
}
});

test("a project's .env cannot name the HeyGen base, so a shell key never leaves for its host", () => {
withCleanHeygenEnv(() => {
const project = mkdtempSync(join(tmpdir(), "heygen-env-"));
writeFileSync(
join(project, ".env"),
"HEYGEN_API_BASE=https://proxy.example.com\nHEYGEN_ALLOW_HTTP=1\nMEDIA_USE_ENV_BASE_TEST=loaded\n",
);
try {
process.env.HEYGEN_API_KEY = "hg_shell_real";
loadEnvFromDir(project);
assert.equal(process.env.MEDIA_USE_ENV_BASE_TEST, "loaded");
assert.equal(process.env.HEYGEN_API_BASE, undefined);
assert.equal(process.env.HEYGEN_ALLOW_HTTP, undefined);
assert.equal(heygenBase(), "https://api.heygen.com/v3");
} finally {
delete process.env.MEDIA_USE_ENV_BASE_TEST;
rmSync(project, { recursive: true, force: true });
}
});
});

test("heygenAuthMethod returns null when the credentials path is a folder", () => {
withCleanHeygenEnv(() => {
const dir = mkdtempSync(join(tmpdir(), "heygen-cred-"));
Expand Down Expand Up @@ -183,3 +215,78 @@ test("heygenAuthHeaders says to fix an unreadable credentials path, and to log i
}
});
});

test("heygenBase is HeyGen's public API unless a host names another", () => {
withCleanHeygenEnv(() => {
assert.equal(heygenBase(), "https://api.heygen.com/v3");
process.env.HEYGEN_API_BASE = "https://api-canary.heygen.com/";
assert.equal(heygenBase(), "https://api-canary.heygen.com/v3");
});
});

test("heygenBase refuses a plain-HTTP host unless HEYGEN_ALLOW_HTTP is set, as the heygen CLI does", () => {
withCleanHeygenEnv(() => {
process.env.HEYGEN_API_BASE = "http://127.0.0.1:4100";
assert.throws(() => heygenBase(), /HEYGEN_ALLOW_HTTP=1/);
process.env.HEYGEN_ALLOW_HTTP = "1";
assert.equal(heygenBase(), "http://127.0.0.1:4100/v3");
});
});

test("a host gateway (HEYGEN_API_BASE with its own HEYGEN_API_KEY) wins over a host OAuth token", () => {
withCleanHeygenEnv(() => {
process.env.HEYGEN_API_BASE = "http://127.0.0.1:4100";
process.env.HEYGEN_ALLOW_HTTP = "1";
process.env.HEYGEN_API_KEY = "gateway-token";
process.env.HEYGEN_ACCESS_TOKEN = "at_host";
assert.deepEqual(heygenAuthHeaders(), {
"X-Api-Key": "gateway-token",
"X-HeyGen-Client-Source": "media-use",
});
assert.equal(heygenAuthMethod(), "api_key");
});
});

test("heygenJSON sends its request to the host's HEYGEN_API_BASE with the host's key", async () => {
/** @type {{ url?: string, key?: string | string[] }} */
const seen = {};
const server = createServer((req, res) => {
seen.url = req.url;
seen.key = req.headers["x-api-key"];
res.writeHead(200, { "content-type": "application/json" }).end('{"data":[]}');
});
await new Promise((done) => server.listen(0, "127.0.0.1", done));
const { port } = /** @type {import("node:net").AddressInfo} */ (server.address());
try {
await withCleanHeygenEnv(async () => {
process.env.HEYGEN_API_BASE = `http://127.0.0.1:${port}`;
process.env.HEYGEN_ALLOW_HTTP = "1";
process.env.HEYGEN_API_KEY = "gateway-token";
const reply = await heygenJSON("/voices?limit=1", { headers: heygenAuthHeaders() });
assert.deepEqual(reply, { data: [] });
});
assert.equal(seen.url, "/v3/voices?limit=1");
assert.equal(seen.key, "gateway-token");
} finally {
server.close();
}
});

test("a base that isn't HeyGen's gets no stored or host OAuth credential, only a key named for it", () => {
withCleanHeygenEnv(() => {
const dir = mkdtempSync(join(tmpdir(), "heygen-cred-"));
try {
process.env.HEYGEN_CONFIG_DIR = dir;
writeFileSync(join(dir, "credentials"), JSON.stringify({ api_key: "hg_stored" }));
process.env.HEYGEN_ACCESS_TOKEN = "at_host";
process.env.HEYGEN_API_BASE = "https://proxy.example.com";
assert.equal(heygenCredential(), null);
assert.throws(() => heygenAuthHeaders(), /no HeyGen credentials/);
// HeyGen's own hosts keep every credential source.
process.env.HEYGEN_API_BASE = "https://api-canary.heygen.com";
assert.equal(heygenAuthMethod(), "oauth");
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
});
13 changes: 13 additions & 0 deletions skills/media-use/references/setup-providers.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,19 @@ This unlocks the FREE path for bgm/sfx/image/icon catalog search, TTS (voice), a
npx hyperframes media-use resolve --doctor
```

## Host HeyGen access (no CLI sign-in)

A host app can give media-use HeyGen access of its own by setting
`HEYGEN_API_BASE` (its gateway), `HEYGEN_API_KEY` (the token that gateway
accepts) and, for a loopback gateway, `HEYGEN_ALLOW_HTTP=1`. The gateway adds
the host's key, so it never enters the agent's environment, and every
call is charged to that key's API credits. The `heygen` CLI honours the same
variables, so `resolve` (bgm/sfx/image/icon/voice/avatar-video) and the audio
engine's TTS all go through the host. With host access, skip CLI install and
sign-in, prefer the host's own HeyGen tools where it has them, never fall back
to a local or third-party generator on your own, and relay a refused call's
message (for example "add a key in Settings > Account") as written.

## Providers

media-use holds no keys; every external tool owns its auth. Generation is
Expand Down
Loading