Files
hyperframes/skills/media-use/scripts/lib/registry.mjs
T
Miguel Ángel 401dd1d27f fix: media-use bug-bash fixes (codex gate, id race, provider/reuse/adopt guards) + CLI unknown-flag rejection (#2033)
* fix(media-use): codex gate misfires as 'not logged in' when piped

codexUnavailableReason() gated generation on parsing `codex login status`
stdout, but that command prints 'Logged in using ChatGPT' to stderr and
exits 0 — so the piped stdout media-use captures (execFileSync returns
stdout only on success) was empty, and the gate falsely reported 'not
logged in'. Every headless / CI / agent run was blocked from codex image
gen even when fully authed.

Gate on the durable credentials file ($CODEX_HOME/auth.json) instead of
the TTY/stderr-only human text. Token validity is still proven by the
exec, which fails cleanly on a stale login. The stdout `features list`
capability check is unchanged.

Verified: reproduced the false 'not logged in' block, then after the fix
generated end-to-end via `resolve -t image --provider codex` (valid
1254x1254 PNG, source=generated, provider=codex.image_gen).

* fix(media-use): bug-bash fixes — id race, provider/reuse/adopt guards

From the bug-bash against main:

- MU-23 (HIGH): concurrent resolves raced on nextId (read-max-then-append,
  non-atomic), so parallel agents got duplicate ids and clobbered each
  other's files. Add allocateId(): a coarse per-project lock (.media/.lock,
  15s stale-steal) around id allocation that scans the manifest AND the
  type dir for reserved ids, then O_EXCL-creates a placeholder file so the
  slow download between allocate and append can't collide. 5 parallel
  resolves now yield 5 distinct ids + files.
- X4: --reuse imported across a type mismatch (bgm asset under images/).
  Apply typesMatch on the --reuse path; reject mismatches (icon<->image
  still interchangeable).
- X5: --provider silently overrode --local-only and made a network call.
  --local-only is now a hard guard: network providers are skipped even
  under a forced provider; the miss message explains the conflict.
- BUG-2: --provider ignored the exact-cache floor and could hand back an
  asset from a different provider. A forced --provider now bypasses all
  reuse rungs (regenerate with THIS provider); the unforced floor is intact.
- MU-26/X6: 0-byte assets accepted. --adopt skips 0-byte files (loud); ingest
  refuses a 0-byte local file (freezeUrl already rejects empty responses).
- BUG-4: unknown/unavailable --provider now errors with the available list
  instead of a generic 'no provider could resolve' (typo != catalog miss).
- BUG-5: --reuse "" gave the wrong 'type and intent required' error; it now
  routes to a clear empty-sha message.
- BUG-3: voice duration leaked an unrounded float into index.md; round all
  durations to 0.1s centrally at record build (matches probe).
- Nits: whitespace-only --intent is rejected; nudge grammar (exists/exist).

Tests: allocateId reservation + registry local-only-wins added; full
media-use suite green. All fixes verified e2e.

* fix(cli): reject unknown flags instead of silently ignoring them

citty is permissive: an unrecognized flag was dropped, not rejected — so
`render . --out x` (the flag is --output/-o) silently ignored --out and
rendered to the default renders/<name>.mp4 path. A mistyped flag read as a
render/catalog miss.

Add assertKnownFlags(): validate every dash-prefixed token against the
command's declared args + aliases + the global set (help/version/json)
before the command runs, in the shared trackCommandFailures run-wrapper so
every leaf command is covered. Handles --flag=value, --no-<bool> negation,
camelCase<->kebab arg names, and combined shorts; stops at --; positionals
and flag values pass through.

Verified: `render . --out x` -> 'Error: Unknown flag: --out'; --output/-o/
--json/--help still accepted. Unit tests added.

* docs(skills): install with --full-depth so agents get current main

The documented `npx skills add heygen-com/hyperframes` fetched the
skills.sh registry blob, which lags GitHub main by hours — so users
following the docs got a stale skill (e.g. media-use v1: no --candidates,
voice stubbed). The CLI's own `hyperframes skills` command already forces
a full clone via --full-depth to bypass this; the docs didn't pass it.

Add --full-depth to every documented install command (README, CLAUDE.md,
docs/guides/skills.mdx) with a one-line note on the lag. Addresses the
user-facing half of the publish/registry lag (#2034).

* chore(media-use): collapse resolve.mjs import to satisfy oxfmt --check

* fix(cli): extract longFlagName to keep flag validator under complexity gate

Also regenerate skills-manifest.json (resolve.mjs formatting change re-hashed
the media-use skill). Fixes the Fallow audit + skills-manifest-in-sync CI gates.
2026-07-07 19:19:28 -04:00

138 lines
6.0 KiB
JavaScript

// Provider registry — the v2 contract.
//
// Each media type maps to an ORDERED list of provider entries. Providers are
// tried in order; the first to return a non-null result wins, which keeps
// resolution deterministic (same request -> same provider -> same file ->
// reproducible renders). heygen-CLI is always first for the types it serves.
//
// An entry exposes any of three capability methods — search / generate /
// process — plus { name }. media-use holds no keys; each external tool owns its
// own auth. Providers, by type:
// - heygen CLI: catalog + TTS, first for every type it serves (sub creds)
// - mflux: local FLUX-class image gen, spec-selected to the machine's RAM
// (free, private, offline once cached)
// - codex CLI: image gen on the user's ChatGPT sub — the better-quality upsell
// and the fallback when no local model fits
// - Kokoro (via the hyperframes CLI): local voiceover, free/private default
// for the voice type, ahead of the paid HeyGen TTS upsell
//
// Generation is local-first, cloud-upsell. `ctx.provider` forces one provider
// (e.g. "make an image with codex").
import { bgmProvider } from "./bgm-provider.mjs";
import { sfxProvider } from "./sfx-provider.mjs";
import { imageProvider, iconProvider } from "./image-provider.mjs";
import { brandProvider } from "./brand-provider.mjs";
import { heygenTtsGenerate } from "./voice-provider.mjs";
import { localTtsGenerate } from "./tts-local-provider.mjs";
import { codexImageGenerate } from "./codex-provider.mjs";
import { mfluxImageGenerate } from "./mflux-provider.mjs";
// Provider markers: `network` = hits a remote service (skipped by --local-only).
// `paid` = costs wallet credits (documentation for the agent's cost judgment,
// X4: agent-initiated paid should confirm). HeyGen catalog SEARCH is free;
// HeyGen TTS now costs credits, so it is the paid upsell behind local Kokoro.
const A = (name, caps) => ({ name, ...caps }); // local, free
const N = (name, caps) => ({ name, network: true, ...caps }); // remote, free
const P = (name, caps) => ({ name, network: true, paid: true, ...caps }); // remote, paid
// heygen-CLI first (and currently only). All remote providers are skipped by --local-only.
const REGISTRY = {
bgm: [N("heygen.audio.sounds", { search: bgmProvider.search })],
sfx: [N("heygen.audio.sounds", { search: sfxProvider.search })],
image: [
N("heygen.asset.search", { search: imageProvider.search }),
// Catalog miss -> generate. Local first (best FLUX-class model the machine's
// RAM can run, spec-selected; free, private, kept under --local-only), then
// the codex CLI on the user's ChatGPT sub as the better-quality upsell and
// the fallback when no local model fits.
A("mflux.local", { generate: mfluxImageGenerate }),
N("codex.image_gen", { generate: codexImageGenerate }),
],
icon: [N("heygen.asset.search", { search: iconProvider.search })],
voice: [
// Local Kokoro first (free, private, on-device via the hyperframes CLI, kept
// under --local-only), then HeyGen TTS as the higher-quality paid upsell and
// the fallback when Kokoro is not set up.
A("kokoro.local", { generate: localTtsGenerate }),
P("heygen.tts", { generate: heygenTtsGenerate }),
],
brand: [
// Local design spec, not heygen — reads frame.md / design.md tokens.
A("design_spec", { search: brandProvider.search }),
],
};
function listFor(type) {
const list = REGISTRY[type];
if (!list) throw new Error(`unknown media type: ${type}`);
return list;
}
/** Ordered providers for a type. */
export function getProviders(type) {
return listFor(type);
}
/** All declared media types. */
export function listTypes() {
return Object.keys(REGISTRY);
}
/** Provider names available for a type, in cascade order (for --provider validation). */
export function providerNamesFor(type) {
return listFor(type).map((p) => p.name);
}
/**
* Does an override token (full name like "codex.image_gen" or a prefix like
* "codex") match any provider declared for the type? Same match rule as
* runProviders, so validation and dispatch never disagree.
*/
export function providerMatches(type, want) {
return providerNamesFor(type).some((n) => n === want || n.startsWith(`${want}.`));
}
/**
* Back-compat shim for the v1 single-provider API. Returns the first declared
* provider for the type (tagged with `type`); throws for an unknown type.
* Kept for v1 callers only — new code should use getProviders/runCapability.
*/
export function getProvider(type) {
const first = listFor(type)[0] || {};
return { ...first, type };
}
/**
* Run a capability across an explicit ordered provider list. Tries each in
* order, returns the first non-null result, skips providers that don't expose
* the capability. Pure over its input — the unit-testable core of the cascade.
*
* Offline guard: a `network` provider is skipped when `ctx.localOnly` is set —
* unconditionally, even under a `ctx.provider` override. --local-only is a hard
* safety flag: it must never make a network call. Forcing a network provider
* while offline yields a clean miss (the caller explains the conflict), never a
* silent network request.
* Provider override: `ctx.provider` (a full name like "codex.image_gen" or a
* prefix like "codex") pins resolution to matching providers only — this is how
* a user "make an image WITH codex" forces the upsell instead of taking the
* free-first default.
*/
export async function runProviders(providers, capability, intent, ctx) {
const want = ctx?.provider;
for (const p of providers) {
if (want && p.name !== want && !p.name.startsWith(`${want}.`)) continue;
if (p.network && ctx?.localOnly) continue; // --local-only wins, even over --provider
const fn = p[capability];
if (typeof fn !== "function") continue;
const res = await fn(intent, ctx);
if (res) return res;
}
return null;
}
/** Run a capability over the providers for a type (deterministic, heygen-first). */
export async function runCapability(type, capability, intent, ctx) {
return runProviders(getProviders(type), capability, intent, ctx);
}