Skip to content

Commit 6de29f5

Browse files
feat(media-use): derive provider cost tier from the registry (#3155)
The provider registry already declares whether a provider is local, free over the network, or paid over the network via its A/N/P constructors, but nothing downstream could read that, so anything needing to know whether resolving through a provider can spend the user's credit had to re-derive it by string-matching provider names. Expose it as providerTierFor(name) over the same table and carry the derived value on the resolve event alongside the provider it came from. Sparse: absent when the record carries no provider or the name is not declared. A name declared under two media types must carry one tier; the index throws at import rather than silently picking one. Covered by unit tests on the lookup and by end-to-end cases that spawn the real CLI and read the value off the payload a local server receives, one per tier.
1 parent bd1c1af commit 6de29f5

5 files changed

Lines changed: 181 additions & 13 deletions

File tree

‎skills-manifest.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@
4646
"files": 10
4747
},
4848
"media-use": {
49-
"hash": "1fc64413fe651bde",
49+
"hash": "7e329ade41b1c1ba",
5050
"files": 152
5151
},
5252
"motion-graphics": {

‎skills/media-use/scripts/lib/registry.mjs‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -127,6 +127,44 @@ export function providerNamesFor(type) {
127127
return listFor(type).map((p) => p.name);
128128
}
129129

130+
/**
131+
* name -> cost tier ("local" | "network_free" | "network_paid") over a collection
132+
* of ordered provider lists, i.e. the A / N / P distinction the constructors above
133+
* already declare. Exported so the conflict rule below is testable against a
134+
* fixture; production reads the REGISTRY-wide index built from it.
135+
*
136+
* A name declared under two media types must carry the same tier in both. If it
137+
* didn't, "did this resolve cost credit" would depend on which type happened to
138+
* serve it, and the telemetry property would mean nothing — so this throws at
139+
* import rather than silently picking one.
140+
*/
141+
export function buildProviderTierIndex(providerLists) {
142+
const tiers = new Map();
143+
for (const list of providerLists) {
144+
for (const p of list) {
145+
const tier = p.paid ? "network_paid" : p.network ? "network_free" : "local";
146+
const prior = tiers.get(p.name);
147+
if (prior && prior !== tier)
148+
throw new Error(
149+
`provider "${p.name}" is declared ${prior} under one media type and ${tier} under another`,
150+
);
151+
tiers.set(p.name, tier);
152+
}
153+
}
154+
return tiers;
155+
}
156+
157+
const PROVIDER_TIERS = buildProviderTierIndex(Object.values(REGISTRY));
158+
159+
/**
160+
* Cost tier of a provider by name, or undefined for a name the registry doesn't
161+
* declare. The registry stays the single owner of "does this cost credit", so
162+
* dashboards and callers never re-derive it from provider-name string matching.
163+
*/
164+
export function providerTierFor(name) {
165+
return PROVIDER_TIERS.get(name);
166+
}
167+
130168
/**
131169
* Does an override token (full name like "codex.image_gen" or a prefix like
132170
* "codex") match any provider declared for the type? Same match rule as

‎skills/media-use/scripts/lib/registry.test.mjs‎

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,8 @@ import {
88
providerNamesFor,
99
runProviders,
1010
runCapability,
11+
providerTierFor,
12+
buildProviderTierIndex,
1113
} from "./registry.mjs";
1214

1315
// --- registry shape -------------------------------------------------------
@@ -185,6 +187,60 @@ test("runCapability('bgm','process') is null — process slot is graceful when u
185187
assert.equal(await runCapability("bgm", "process", "x", {}), null);
186188
});
187189

190+
// --- provider cost tier (telemetry) ---------------------------------------
191+
192+
test("providerTierFor reports the registry's own A/N/P declaration", () => {
193+
assert.equal(providerTierFor("heygen.tts"), "network_paid");
194+
assert.equal(providerTierFor("heygen.video"), "network_paid");
195+
assert.equal(providerTierFor("heygen.audio.sounds"), "network_free");
196+
assert.equal(providerTierFor("heygen.asset.search"), "network_free");
197+
assert.equal(providerTierFor("codex.image_gen"), "network_free");
198+
assert.equal(providerTierFor("bundled.sfx"), "local");
199+
assert.equal(providerTierFor("kokoro.local"), "local");
200+
});
201+
202+
test("providerTierFor agrees across every type that declares the same name", () => {
203+
// heygen.audio.sounds serves both bgm and sfx; heygen.asset.search serves both
204+
// image and icon. A name whose tier depended on the media type would make the
205+
// telemetry property meaningless.
206+
const byName = new Map();
207+
for (const type of listTypes()) {
208+
for (const name of providerNamesFor(type)) {
209+
const tier = providerTierFor(name);
210+
assert.ok(tier, `every declared provider has a tier (${type}/${name})`);
211+
const prior = byName.get(name);
212+
if (prior) assert.equal(tier, prior, `${name} must carry one tier across types`);
213+
byName.set(name, tier);
214+
}
215+
}
216+
});
217+
218+
test("providerTierFor returns undefined for a name the registry does not declare", () => {
219+
assert.equal(providerTierFor("does.not.exist"), undefined);
220+
assert.equal(providerTierFor(undefined), undefined);
221+
assert.equal(providerTierFor(null), undefined);
222+
assert.equal(providerTierFor(""), undefined);
223+
});
224+
225+
test("buildProviderTierIndex throws when one name carries two tiers", () => {
226+
assert.throws(
227+
() =>
228+
buildProviderTierIndex([
229+
[{ name: "dual", network: true }],
230+
[{ name: "dual", network: true, paid: true }],
231+
]),
232+
/declared network_free under one media type and network_paid under another/,
233+
);
234+
});
235+
236+
test("buildProviderTierIndex accepts the same name repeated at the same tier", () => {
237+
const index = buildProviderTierIndex([
238+
[{ name: "same", network: true }],
239+
[{ name: "same", network: true }],
240+
]);
241+
assert.equal(index.get("same"), "network_free");
242+
});
243+
188244
test("--local-only skips every network provider (even free remote ones)", async () => {
189245
let remoteRan = false;
190246
const providers = [

‎skills/media-use/scripts/resolve.mjs‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,13 @@ import {
1414
} from "./lib/manifest.mjs";
1515
import { regenerateIndex } from "./lib/index-gen.mjs";
1616
import { cacheGet, cacheGetByEntity, importFromCache, cachePut } from "./lib/cache.mjs";
17-
import { runCapability, listTypes, providerMatches, providerNamesFor } from "./lib/registry.mjs";
17+
import {
18+
runCapability,
19+
listTypes,
20+
providerMatches,
21+
providerNamesFor,
22+
providerTierFor,
23+
} from "./lib/registry.mjs";
1824
import { freezeUrl, freezeLocalFile, isDirectMediaUrl } from "./lib/freeze.mjs";
1925
import { findExistingAsset } from "./lib/adopt.mjs";
2026
import { track } from "./lib/telemetry.mjs";
@@ -1206,6 +1212,11 @@ async function result(record, source) {
12061212
// signal about the fetch that actually consumed a heygen credit, not
12071213
// about the (free, no-credential) act of copying a cached file.
12081214
auth_method: record.provenance?.authMethod,
1215+
// "local" / "network_free" / "network_paid", straight from the registry's own
1216+
// A/N/P declaration — so a dashboard can separate free lookups from calls that
1217+
// spend credit without hardcoding provider names. Sparse: absent when the
1218+
// record carries no provider (cache and reuse hits) or the name is unknown.
1219+
provider_tier: providerTierFor(record.provenance?.provider),
12091220
local_only: !!args["local-only"],
12101221
provider_override: !!args.provider,
12111222
});

‎skills/media-use/scripts/resolve.test.mjs‎

Lines changed: 74 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -962,8 +962,11 @@ test("identical grade resolve hits the project cache without re-freezing", () =>
962962
// resolve that reaches track("media_use_resolve", ...) with tracking allowed
963963
// posts to a local HTTP server instead of production, and the server actually
964964
// receives it (not just "nothing happened because nothing was listening").
965-
test("track() posts to MEDIA_USE_TELEMETRY_HOST when set, proving real interception", async () => {
966-
setup();
965+
// Spawns a real resolve that hits the manifest for `provider`, intercepts the
966+
// telemetry POST it makes, and hands back the media_use_resolve event actually
967+
// sent. Nothing is stubbed: the CLI runs as its own process, telemetry.mjs builds
968+
// the URL, and a local server reads the payload off the wire.
969+
async function captureResolveEvent({ provider, type = "bgm", intent }) {
967970
const received = [];
968971
const server = createServer((req, res) => {
969972
let body = "";
@@ -972,7 +975,7 @@ test("track() posts to MEDIA_USE_TELEMETRY_HOST when set, proving real intercept
972975
try {
973976
received.push(JSON.parse(body));
974977
} catch {
975-
// ignore malformed body; assertions below fail on empty `received`
978+
// ignore malformed body; callers assert on empty `received`
976979
}
977980
res.writeHead(200, { "Content-Type": "application/json" });
978981
res.end("{}");
@@ -983,8 +986,14 @@ test("track() posts to MEDIA_USE_TELEMETRY_HOST when set, proving real intercept
983986
const sandboxHome = mkdtempSync(join(tmpdir(), "mu-resolve-telemetry-home-"));
984987

985988
try {
989+
// The record's type must match the --type below, otherwise the manifest
990+
// never matches, the cascade calls a live provider, and the run fails for
991+
// reasons that have nothing to do with the tier.
986992
const record = makeRecord({
987-
provenance: { prompt: "telemetry seam test", provider: "test" },
993+
id: `${type}_tier_001`,
994+
type,
995+
path: `.media/audio/${type}/${type}_tier_001.wav`,
996+
provenance: { prompt: intent, provider },
988997
});
989998
appendRecord(tmp, record);
990999
const filePath = join(tmp, record.path);
@@ -1000,7 +1009,7 @@ test("track() posts to MEDIA_USE_TELEMETRY_HOST when set, proving real intercept
10001009
// their real email into this test's local-server payload despite HOME
10011010
// being sandboxed (HEYGEN_CONFIG_DIR, not HOME, resolves the credentials
10021011
// path). Every other test in this file keeps its untouched default env.
1003-
runResolve(["--type", "bgm", "--intent", "telemetry seam test", "--project", tmp, "--json"], {
1012+
runResolve(["--type", type, "--intent", intent, "--project", tmp, "--json"], {
10041013
env: {
10051014
DO_NOT_TRACK: "0",
10061015
HYPERFRAMES_NO_TELEMETRY: "0",
@@ -1013,7 +1022,7 @@ test("track() posts to MEDIA_USE_TELEMETRY_HOST when set, proving real intercept
10131022
});
10141023

10151024
// runResolve blocks synchronously (execFileSync) until the child exits, which
1016-
// pauses this process's own event loop for that whole span — the child's
1025+
// pauses this process's own event loop for that whole span -- the child's
10171026
// request to our local server sits accepted-but-unprocessed in the kernel
10181027
// backlog until control returns here. Poll briefly to let the event loop
10191028
// drain it rather than asserting before the server has had a turn to run.
@@ -1023,16 +1032,70 @@ test("track() posts to MEDIA_USE_TELEMETRY_HOST when set, proving real intercept
10231032
} finally {
10241033
await new Promise((resolve) => server.close(resolve));
10251034
rmSync(sandboxHome, { recursive: true, force: true });
1026-
cleanup();
10271035
}
10281036

10291037
assert.ok(received.length > 0, "expected the local telemetry server to receive a POST");
1030-
const resolveEvent = received[0].batch.find((event) => event.event === "media_use_resolve");
1031-
assert.ok(resolveEvent, "expected a media_use_resolve event in the intercepted batch");
1032-
assert.equal(resolveEvent.properties.provider, "test");
1033-
assert.equal(resolveEvent.properties.type, "bgm");
1038+
const event = received[0].batch.find((e) => e.event === "media_use_resolve");
1039+
assert.ok(event, "expected a media_use_resolve event in the intercepted batch");
1040+
return event;
1041+
}
1042+
1043+
test("track() posts to MEDIA_USE_TELEMETRY_HOST when set, proving real interception", async () => {
1044+
setup();
1045+
try {
1046+
const event = await captureResolveEvent({ provider: "test", intent: "telemetry seam test" });
1047+
assert.equal(event.properties.provider, "test");
1048+
assert.equal(event.properties.type, "bgm");
1049+
// "test" is not a declared registry provider, so the tier is absent rather
1050+
// than guessed, the same sparseness rule auth_method follows.
1051+
assert.equal(
1052+
"provider_tier" in event.properties && event.properties.provider_tier !== undefined,
1053+
false,
1054+
"an undeclared provider must not be assigned a cost tier",
1055+
);
1056+
} finally {
1057+
cleanup();
1058+
}
10341059
});
10351060

1061+
// The registry-derived tier has to survive the whole path -- registry lookup,
1062+
// result(), track(), JSON body -- not just a unit call to providerTierFor. Each
1063+
// case names a provider the registry declares at a different tier and asserts the
1064+
// tier that actually reaches the wire.
1065+
for (const [provider, type, expected] of [
1066+
["heygen.tts", "voice", "network_paid"],
1067+
["heygen.audio.sounds", "bgm", "network_free"],
1068+
["bundled.sfx", "sfx", "local"],
1069+
]) {
1070+
test(`a resolve won by ${provider} sends provider_tier: ${expected}`, async () => {
1071+
setup();
1072+
try {
1073+
const event = await captureResolveEvent({
1074+
provider,
1075+
type,
1076+
intent: `tier seam ${provider}`,
1077+
});
1078+
assert.equal(event.properties.provider, provider);
1079+
assert.equal(
1080+
event.properties.provider_tier,
1081+
expected,
1082+
`${provider} must reach the wire as ${expected}`,
1083+
);
1084+
// The tier is derived from the registry and the auth method from the
1085+
// credential state; they must not become entangled. A non-heygen provider
1086+
// carries a tier and no auth method, whatever credentials exist locally.
1087+
if (!provider.startsWith("heygen."))
1088+
assert.equal(
1089+
event.properties.auth_method,
1090+
undefined,
1091+
"a non-heygen provider must carry a tier without an auth method",
1092+
);
1093+
} finally {
1094+
cleanup();
1095+
}
1096+
});
1097+
}
1098+
10361099
// --- run ---
10371100

10381101
async function main() {

0 commit comments

Comments
 (0)