mirror of
https://github.com/heygen-com/hyperframes.git
synced 2026-11-24 16:06:34 +00:00
feat(media-use): resolve cascade engine with provider registry
Add the core resolve pipeline: - resolve.mjs: entry point with cheapest-first cascade (project manifest → global cache → provider search → generate fallback → freeze → register → regenerate index) - providers.mjs: pluggable provider registry with stub implementations (real providers plug in without changing the cascade) - freeze.mjs: download URL or copy local file to .media/ - 9 passing tests covering cache hits, provider interface, CLI flags, and the one-line output contract
This commit is contained in:
@@ -0,0 +1,19 @@
|
||||
import { writeFileSync, copyFileSync, mkdirSync } from "node:fs";
|
||||
import { dirname } from "node:path";
|
||||
|
||||
export async function freezeUrl(url, destPath) {
|
||||
const res = await fetch(url);
|
||||
if (!res.ok)
|
||||
throw new Error(
|
||||
`freeze failed: HTTP ${res.status} for ${String(url).slice(0, 80)}`,
|
||||
);
|
||||
const bytes = Buffer.from(await res.arrayBuffer());
|
||||
mkdirSync(dirname(destPath), { recursive: true });
|
||||
writeFileSync(destPath, bytes);
|
||||
return bytes.length;
|
||||
}
|
||||
|
||||
export function freezeLocalFile(srcPath, destPath) {
|
||||
mkdirSync(dirname(destPath), { recursive: true });
|
||||
copyFileSync(srcPath, destPath);
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
// ponytail: stub providers — real implementations in audio-provider.mjs, image-provider.mjs, brand-provider.mjs
|
||||
// each provider: { search(intent, opts): Promise<{url, localPath?, metadata}|null>, generate?(intent, opts): Promise<{url, localPath?, metadata}|null> }
|
||||
|
||||
function stubProvider(type) {
|
||||
return {
|
||||
async search() {
|
||||
return null;
|
||||
},
|
||||
async generate() {
|
||||
return null;
|
||||
},
|
||||
type,
|
||||
};
|
||||
}
|
||||
|
||||
const registry = {
|
||||
bgm: stubProvider("bgm"),
|
||||
sfx: stubProvider("sfx"),
|
||||
voice: stubProvider("voice"),
|
||||
image: stubProvider("image"),
|
||||
icon: stubProvider("icon"),
|
||||
brand: stubProvider("brand"),
|
||||
};
|
||||
|
||||
export function getProvider(type) {
|
||||
const p = registry[type];
|
||||
if (!p) throw new Error(`unknown media type: ${type}`);
|
||||
return p;
|
||||
}
|
||||
|
||||
export function registerProvider(type, provider) {
|
||||
registry[type] = { ...provider, type };
|
||||
}
|
||||
|
||||
export function listTypes() {
|
||||
return Object.keys(registry);
|
||||
}
|
||||
@@ -0,0 +1,237 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
import { existsSync } from "node:fs";
|
||||
import { resolve, join } from "node:path";
|
||||
import { parseArgs } from "node:util";
|
||||
import {
|
||||
appendRecord,
|
||||
findByPrompt,
|
||||
findByEntity,
|
||||
nextId,
|
||||
} from "./lib/manifest.mjs";
|
||||
import { regenerateIndex } from "./lib/index-gen.mjs";
|
||||
import {
|
||||
cacheGet,
|
||||
cacheGetByEntity,
|
||||
importFromCache,
|
||||
} from "./lib/cache.mjs";
|
||||
import { getProvider, listTypes } from "./lib/providers.mjs";
|
||||
import { freezeUrl, freezeLocalFile } from "./lib/freeze.mjs";
|
||||
|
||||
const { values: args } = parseArgs({
|
||||
options: {
|
||||
type: { type: "string", short: "t" },
|
||||
intent: { type: "string", short: "i" },
|
||||
entity: { type: "string", short: "e" },
|
||||
project: { type: "string", short: "p", default: "." },
|
||||
json: { type: "boolean", default: false },
|
||||
help: { type: "boolean", short: "h", default: false },
|
||||
},
|
||||
strict: true,
|
||||
});
|
||||
|
||||
if (args.help) {
|
||||
console.log(`media-use resolve — turn a media need into a frozen local file
|
||||
|
||||
Usage:
|
||||
node resolve.mjs --type <type> --intent "<description>" [--project <dir>]
|
||||
|
||||
Types: ${listTypes().join(", ")}
|
||||
|
||||
Options:
|
||||
--type, -t Media type (required)
|
||||
--intent, -i What you need (required)
|
||||
--entity, -e Entity name for cache matching (optional)
|
||||
--project, -p Project directory (default: .)
|
||||
--json Output JSON instead of one-line result
|
||||
--help, -h Show this help`);
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
if (!args.type || !args.intent) {
|
||||
console.error("error: --type and --intent are required");
|
||||
process.exit(2);
|
||||
}
|
||||
|
||||
const projectDir = resolve(args.project);
|
||||
const type = args.type;
|
||||
const intent = args.intent;
|
||||
const entity = args.entity || null;
|
||||
|
||||
async function run() {
|
||||
// 1. project manifest — exact-prompt match
|
||||
const projectHit = findByPrompt(projectDir, intent, type);
|
||||
if (projectHit && existsSync(join(projectDir, projectHit.path))) {
|
||||
return result(projectHit, "cached");
|
||||
}
|
||||
|
||||
// 1b. entity match in project
|
||||
if (entity) {
|
||||
const entityHit = findByEntity(projectDir, entity);
|
||||
if (entityHit && entityHit.type === type && existsSync(join(projectDir, entityHit.path))) {
|
||||
return result(entityHit, "cached");
|
||||
}
|
||||
}
|
||||
|
||||
// 2. global cache — exact-prompt or entity match
|
||||
const cacheHit = cacheGet(intent, type);
|
||||
if (cacheHit) {
|
||||
const id = nextId(projectDir, type);
|
||||
const ext = extFromCachedPath(cacheHit.cached_path);
|
||||
const localPath = `.media/${typeSubdir(type)}/${id}${ext}`;
|
||||
const imported = importFromCache(cacheHit, projectDir, id, localPath);
|
||||
if (imported) {
|
||||
appendRecord(projectDir, imported);
|
||||
regenerateIndex(projectDir);
|
||||
return result(imported, "reused");
|
||||
}
|
||||
}
|
||||
|
||||
if (entity) {
|
||||
const entityCacheHit = cacheGetByEntity(entity);
|
||||
if (entityCacheHit && entityCacheHit.type === type) {
|
||||
const id = nextId(projectDir, type);
|
||||
const ext = extFromCachedPath(entityCacheHit.cached_path);
|
||||
const localPath = `.media/${typeSubdir(type)}/${id}${ext}`;
|
||||
const imported = importFromCache(entityCacheHit, projectDir, id, localPath);
|
||||
if (imported) {
|
||||
appendRecord(projectDir, imported);
|
||||
regenerateIndex(projectDir);
|
||||
return result(imported, "reused");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 3. provider search
|
||||
const provider = getProvider(type);
|
||||
let searchResult = null;
|
||||
try {
|
||||
searchResult = await provider.search(intent, { entity, projectDir });
|
||||
} catch {
|
||||
// search failed, try generate
|
||||
}
|
||||
|
||||
// 4. generate fallback
|
||||
if (!searchResult && provider.generate) {
|
||||
try {
|
||||
searchResult = await provider.generate(intent, { entity, projectDir });
|
||||
} catch {
|
||||
// generate failed too
|
||||
}
|
||||
}
|
||||
|
||||
if (!searchResult) {
|
||||
if (args.json) {
|
||||
console.log(JSON.stringify({ ok: false, error: `no provider could resolve ${type}: "${intent}"` }));
|
||||
} else {
|
||||
console.error(`error: no provider could resolve ${type}: "${intent}"`);
|
||||
}
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
// 5. freeze + register
|
||||
const id = nextId(projectDir, type);
|
||||
const ext = searchResult.ext || extFromUrl(searchResult.url || "") || defaultExt(type);
|
||||
const localPath = `.media/${typeSubdir(type)}/${id}${ext}`;
|
||||
const fullPath = join(projectDir, localPath);
|
||||
|
||||
if (searchResult.localPath) {
|
||||
freezeLocalFile(searchResult.localPath, fullPath);
|
||||
} else if (searchResult.url) {
|
||||
await freezeUrl(searchResult.url, fullPath);
|
||||
} else {
|
||||
console.error("error: provider returned no url or localPath");
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const record = {
|
||||
id,
|
||||
type,
|
||||
path: localPath,
|
||||
source: searchResult.source || "search",
|
||||
description: searchResult.metadata?.description || intent,
|
||||
...(searchResult.metadata?.duration != null && { duration: searchResult.metadata.duration }),
|
||||
...(searchResult.metadata?.width != null && { width: searchResult.metadata.width }),
|
||||
...(searchResult.metadata?.height != null && { height: searchResult.metadata.height }),
|
||||
...(searchResult.metadata?.transparent != null && { transparent: searchResult.metadata.transparent }),
|
||||
...(entity && { entity }),
|
||||
provenance: {
|
||||
provider: searchResult.metadata?.provider || "unknown",
|
||||
prompt: intent,
|
||||
...searchResult.metadata?.provenance,
|
||||
},
|
||||
};
|
||||
|
||||
appendRecord(projectDir, record);
|
||||
regenerateIndex(projectDir);
|
||||
return result(record, searchResult.source || "search");
|
||||
}
|
||||
|
||||
function result(record, source) {
|
||||
if (args.json) {
|
||||
console.log(JSON.stringify({ ok: true, ...record, _source: source }));
|
||||
} else {
|
||||
const meta = formatMeta(record, source);
|
||||
console.log(`resolved ${record.id} → ${record.path} (${meta})`);
|
||||
}
|
||||
}
|
||||
|
||||
function formatMeta(record, source) {
|
||||
const parts = [record.type];
|
||||
if (record.duration != null) parts.push(`${record.duration}s`);
|
||||
if (record.width && record.height) parts.push(`${record.width}×${record.height}`);
|
||||
if (record.transparent) parts.push("transparent");
|
||||
if (source === "reused") parts.push("reused");
|
||||
if (source === "generated") parts.push("generated");
|
||||
return parts.join(", ");
|
||||
}
|
||||
|
||||
function typeSubdir(type) {
|
||||
const map = {
|
||||
bgm: "audio/bgm",
|
||||
sfx: "audio/sfx",
|
||||
voice: "audio/voice",
|
||||
image: "images",
|
||||
icon: "images",
|
||||
brand: "images",
|
||||
};
|
||||
return map[type] || type;
|
||||
}
|
||||
|
||||
function extFromUrl(url) {
|
||||
try {
|
||||
const pathname = new URL(url).pathname;
|
||||
const dot = pathname.lastIndexOf(".");
|
||||
if (dot >= 0) return pathname.slice(dot);
|
||||
} catch {
|
||||
// not a valid URL
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function extFromCachedPath(cachedPath) {
|
||||
if (!cachedPath) return defaultExt("bgm");
|
||||
const dot = cachedPath.lastIndexOf(".");
|
||||
return dot >= 0 ? cachedPath.slice(dot) : "";
|
||||
}
|
||||
|
||||
function defaultExt(type) {
|
||||
const map = {
|
||||
bgm: ".wav",
|
||||
sfx: ".mp3",
|
||||
voice: ".wav",
|
||||
image: ".jpg",
|
||||
icon: ".svg",
|
||||
brand: ".png",
|
||||
};
|
||||
return map[type] || ".bin";
|
||||
}
|
||||
|
||||
run().catch((err) => {
|
||||
if (args.json) {
|
||||
console.log(JSON.stringify({ ok: false, error: err.message }));
|
||||
} else {
|
||||
console.error(`error: ${err.message}`);
|
||||
}
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -0,0 +1,198 @@
|
||||
import { strict as assert } from "node:assert";
|
||||
import { mkdtempSync, rmSync, writeFileSync, readFileSync, mkdirSync, existsSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { tmpdir } from "node:os";
|
||||
import { execSync } from "node:child_process";
|
||||
import { appendRecord, readManifest } from "./lib/manifest.mjs";
|
||||
import { regenerateIndex } from "./lib/index-gen.mjs";
|
||||
import { registerProvider, getProvider } from "./lib/providers.mjs";
|
||||
import { freezeLocalFile } from "./lib/freeze.mjs";
|
||||
import { cachePut, cacheGet, importFromCache } from "./lib/cache.mjs";
|
||||
|
||||
const REPO_ROOT = join(import.meta.dirname, "..", "..", "..");
|
||||
let tmp;
|
||||
|
||||
function setup() {
|
||||
tmp = mkdtempSync(join(tmpdir(), "mu-resolve-test-"));
|
||||
}
|
||||
|
||||
function cleanup() {
|
||||
if (tmp) rmSync(tmp, { recursive: true, force: true });
|
||||
}
|
||||
|
||||
function makeRecord(overrides = {}) {
|
||||
return {
|
||||
id: "bgm_001",
|
||||
type: "bgm",
|
||||
path: ".media/audio/bgm/bgm_001.wav",
|
||||
source: "search",
|
||||
description: "soft minimal ambient",
|
||||
duration: 11,
|
||||
provenance: { provider: "test", prompt: "test prompt" },
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function resolveCmd(args) {
|
||||
return `node skills/media-use/scripts/resolve.mjs ${args}`;
|
||||
}
|
||||
|
||||
const tests = [];
|
||||
function test(name, fn) {
|
||||
tests.push({ name, fn });
|
||||
}
|
||||
|
||||
// --- manifest cache hit ---
|
||||
|
||||
test("project manifest hit skips providers", () => {
|
||||
setup();
|
||||
const record = makeRecord({ provenance: { prompt: "cached query", provider: "test" } });
|
||||
appendRecord(tmp, record);
|
||||
const filePath = join(tmp, record.path);
|
||||
mkdirSync(join(filePath, ".."), { recursive: true });
|
||||
writeFileSync(filePath, "cached audio");
|
||||
|
||||
const out = execSync(
|
||||
resolveCmd(`--type bgm --intent "cached query" --project "${tmp}" --json`),
|
||||
{ cwd: REPO_ROOT, encoding: "utf8" },
|
||||
);
|
||||
const parsed = JSON.parse(out.trim());
|
||||
assert.equal(parsed.ok, true);
|
||||
assert.equal(parsed.id, "bgm_001");
|
||||
assert.equal(parsed._source, "cached");
|
||||
cleanup();
|
||||
});
|
||||
|
||||
// --- global cache hit ---
|
||||
|
||||
test("global cache hit copies to project and registers", () => {
|
||||
setup();
|
||||
const sourceFile = join(tmp, "source.wav");
|
||||
writeFileSync(sourceFile, "cached globally for resolve");
|
||||
const record = makeRecord({ provenance: { prompt: "global resolve test" } });
|
||||
cachePut(sourceFile, record);
|
||||
|
||||
const cached = cacheGet("global resolve test", "bgm");
|
||||
assert.ok(cached);
|
||||
|
||||
const projectDir = mkdtempSync(join(tmpdir(), "mu-resolve-proj-"));
|
||||
const imported = importFromCache(cached, projectDir, "bgm_001", ".media/audio/bgm/bgm_001.wav");
|
||||
assert.ok(imported);
|
||||
assert.ok(existsSync(join(projectDir, ".media/audio/bgm/bgm_001.wav")));
|
||||
|
||||
appendRecord(projectDir, imported);
|
||||
regenerateIndex(projectDir);
|
||||
const manifest = readManifest(projectDir);
|
||||
assert.equal(manifest.length, 1);
|
||||
assert.equal(manifest[0].provenance.imported_from, cached.sha);
|
||||
|
||||
rmSync(projectDir, { recursive: true, force: true });
|
||||
cleanup();
|
||||
});
|
||||
|
||||
// --- provider interface ---
|
||||
|
||||
test("registerProvider replaces stub", async () => {
|
||||
registerProvider("bgm", {
|
||||
async search(intent) {
|
||||
return { url: "https://example.com/t.wav", metadata: { description: intent } };
|
||||
},
|
||||
});
|
||||
const p = getProvider("bgm");
|
||||
assert.equal(p.type, "bgm");
|
||||
const r = await p.search("test");
|
||||
assert.ok(r.url);
|
||||
|
||||
// restore stub
|
||||
registerProvider("bgm", { async search() { return null; }, async generate() { return null; } });
|
||||
});
|
||||
|
||||
test("getProvider throws for unknown type", () => {
|
||||
assert.throws(() => getProvider("unknown_type"), /unknown media type/);
|
||||
});
|
||||
|
||||
// --- freeze ---
|
||||
|
||||
test("freezeLocalFile creates parent dirs and copies", () => {
|
||||
setup();
|
||||
const src = join(tmp, "src.bin");
|
||||
writeFileSync(src, "freeze test data");
|
||||
const dest = join(tmp, "deep/nested/dir/file.bin");
|
||||
freezeLocalFile(src, dest);
|
||||
assert.ok(existsSync(dest));
|
||||
assert.equal(readFileSync(dest, "utf8"), "freeze test data");
|
||||
cleanup();
|
||||
});
|
||||
|
||||
// --- CLI interface ---
|
||||
|
||||
test("--help exits 0", () => {
|
||||
const out = execSync(resolveCmd("--help"), { cwd: REPO_ROOT, encoding: "utf8" });
|
||||
assert.ok(out.includes("media-use resolve"));
|
||||
assert.ok(out.includes("--type"));
|
||||
});
|
||||
|
||||
test("missing required args exits 2", () => {
|
||||
try {
|
||||
execSync(resolveCmd(""), { cwd: REPO_ROOT, encoding: "utf8", stdio: "pipe" });
|
||||
assert.fail("should have exited");
|
||||
} catch (err) {
|
||||
assert.equal(err.status, 2);
|
||||
}
|
||||
});
|
||||
|
||||
test("--json returns error JSON on stub provider failure", () => {
|
||||
setup();
|
||||
try {
|
||||
execSync(
|
||||
resolveCmd(`--type bgm --intent "stub fail" --project "${tmp}" --json`),
|
||||
{ cwd: REPO_ROOT, encoding: "utf8", stdio: "pipe" },
|
||||
);
|
||||
assert.fail("should have exited");
|
||||
} catch (err) {
|
||||
const output = err.stdout || "";
|
||||
const parsed = JSON.parse(output.trim());
|
||||
assert.equal(parsed.ok, false);
|
||||
assert.ok(parsed.error.includes("no provider"));
|
||||
}
|
||||
cleanup();
|
||||
});
|
||||
|
||||
test("one-line output format matches contract", () => {
|
||||
setup();
|
||||
const record = makeRecord({ provenance: { prompt: "format test", provider: "test" } });
|
||||
appendRecord(tmp, record);
|
||||
const filePath = join(tmp, record.path);
|
||||
mkdirSync(join(filePath, ".."), { recursive: true });
|
||||
writeFileSync(filePath, "format check");
|
||||
|
||||
const out = execSync(
|
||||
resolveCmd(`--type bgm --intent "format test" --project "${tmp}"`),
|
||||
{ cwd: REPO_ROOT, encoding: "utf8" },
|
||||
);
|
||||
assert.match(out.trim(), /^resolved bgm_001 → .media\/audio\/bgm\/bgm_001\.wav \(bgm/);
|
||||
cleanup();
|
||||
});
|
||||
|
||||
// --- run ---
|
||||
|
||||
async function main() {
|
||||
console.log("media-use · resolve engine tests\n");
|
||||
let passed = 0;
|
||||
let failed = 0;
|
||||
for (const { name, fn } of tests) {
|
||||
try {
|
||||
await fn();
|
||||
passed++;
|
||||
console.log(` \x1b[32m✓\x1b[0m ${name}`);
|
||||
} catch (err) {
|
||||
failed++;
|
||||
console.log(` \x1b[31m✗\x1b[0m ${name}`);
|
||||
console.log(` ${err.message}`);
|
||||
}
|
||||
}
|
||||
console.log(`\n${passed} passed, ${failed} failed`);
|
||||
if (failed > 0) process.exit(1);
|
||||
}
|
||||
|
||||
main();
|
||||
Reference in New Issue
Block a user