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
37 changes: 33 additions & 4 deletions src/index.music-provider.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,24 @@ describe("music generation provider model list", () => {
expect([...models].sort()).toEqual([...MUSIC_MODEL_IDS].sort());
});

it("offers MiniMax first, as the default, and both Lyria models", () => {
it("offers MiniMax first, as the default, both Lyria models and ElevenLabs", () => {
expect(provider.defaultModel).toBe("minimax/music-2.5+");
expect(models[0]).toBe(provider.defaultModel);
expect(models).toContain("google/lyria-3.5");
expect(models).toContain("google/lyria-3-clip");
expect(models).toContain("elevenlabs/music-v2.5");
expect(models).not.toContain("minimax/music-2.5");
});

it("marks ElevenLabs as taking no lyrics, and every other model as taking them", () => {
const caps = provider.capabilities;
const lyricsFor = (m: string) =>
caps.supportsLyricsByModel?.[m] ?? caps.supportsLyrics === true;
expect(lyricsFor("elevenlabs/music-v2.5")).toBe(false);
for (const m of models.filter((id) => id !== "elevenlabs/music-v2.5")) {
expect(lyricsFor(m)).toBe(true);
}
});
});

describe("estimateMusicCost", () => {
Expand All @@ -34,9 +45,27 @@ describe("estimateMusicCost", () => {
expect(estimateMusicCost("google/lyria-3-clip")).toBeCloseTo(0.04, 9);
});

it("estimates an unknown id at the dearest track, never a cheaper one", () => {
it("prices ElevenLabs per second of the requested length, 30 s when omitted", () => {
expect(estimateMusicCost("elevenlabs/music-v2.5", 60)).toBeCloseTo(0.15, 9);
expect(estimateMusicCost("elevenlabs/music-v2.5", 240)).toBeCloseTo(0.6, 9);
expect(estimateMusicCost("elevenlabs/music-v2.5", 5)).toBeCloseTo(0.0125, 9);
expect(estimateMusicCost("elevenlabs/music-v2.5")).toBeCloseTo(0.075, 9);
expect(estimateMusicCost("elevenlabs/music-v2.5", null)).toBeCloseTo(0.075, 9);
// A length the gateway would refuse is estimated at the longest track.
expect(estimateMusicCost("elevenlabs/music-v2.5", "60")).toBeCloseTo(0.6, 9);
expect(estimateMusicCost("elevenlabs/music-v2.5", 999)).toBeCloseTo(0.6, 9);
// Flat-per-track models ignore the length.
expect(estimateMusicCost("google/lyria-3.5", 240)).toBeCloseTo(0.08, 9);
});

it("estimates the legacy MiniMax id as 2.5+, which the gateway remaps it to", () => {
expect(estimateMusicCost("minimax/music-2.5")).toBeCloseTo(0.199, 9);
expect(estimateMusicCost("some/new-music")).toBeCloseTo(0.199, 9);
expect(estimateMusicCost("toString")).toBeCloseTo(0.199, 9);
});

it("estimates an unknown id at the dearest track, never a cheaper one", () => {
// ElevenLabs at 240 s ($0.60) is now the dearest possible track.
expect(estimateMusicCost("some/new-music")).toBeCloseTo(0.6, 9);
expect(estimateMusicCost("some/new-music", 5)).toBeCloseTo(0.6, 9);
expect(estimateMusicCost("toString")).toBeCloseTo(0.6, 9);
});
});
17 changes: 14 additions & 3 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1520,17 +1520,28 @@ export function buildMusicGenerationProvider(): MusicGenerationProviderPlugin {
label: "BlockRun",
defaultModel: "minimax/music-2.5+",
// What the gateways serve (2026-12-03): MiniMax Music 2.5+ (default, ~3 min
// song), Google Lyria 3.5 (length follows duration roughly) and Lyria 3
// Clip (always 30s). minimax/music-2.5 left blockrun's catalog; the gateway
// song), Google Lyria 3.5 (length follows duration roughly), Lyria 3
// Clip (always 30s) and ElevenLabs Music v2.5 (exactly duration_seconds,
// priced per second, no lyrics: the gateway 400s them before any payment;
// not on Arc, like Lyria). minimax/music-2.5 left blockrun's catalog; the gateway
// remaps pinned callers to music-2.5+, so the picker does not offer it.
// Hand-written, like the image list, because the lifecycle tests fully
// mock ./proxy.js; src/index.music-provider.test.ts pins it to
// MUSIC_MODEL_IDS (proxy.ts MUSIC_PRICING).
models: ["minimax/music-2.5+", "google/lyria-3.5", "google/lyria-3-clip"],
models: [
"minimax/music-2.5+",
"google/lyria-3.5",
"google/lyria-3-clip",
"elevenlabs/music-v2.5",
],
capabilities: {
maxTracks: 1,
maxDurationSeconds: 240,
supportsLyrics: true,
// ElevenLabs Music takes no lyrics (the gateway 400s them before any
// payment). OpenClaw reads this per-model override and drops the lyrics
// as an ignored override instead of sending them.
supportsLyricsByModel: { "elevenlabs/music-v2.5": false },
supportsInstrumental: true,
supportsDuration: true,
supportsFormat: true,
Expand Down
99 changes: 99 additions & 0 deletions src/proxy.music-per-second.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
import { createServer, type Server } from "node:http";
import type { AddressInfo } from "node:net";
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import { startProxy, type ProxyHandle } from "./proxy.js";
import { InMemorySpendControlStorage, SpendControl } from "./spend-control.js";

vi.mock("./logger.js", async (original) => ({
...(await original<typeof import("./logger.js")>()),
logUsage: vi.fn(async () => {}),
}));

/**
* ElevenLabs Music v2.5 is billed per second of the REQUESTED duration_seconds
* ($0.0025/s; 30 s when omitted). On the account rail the music route's
* estimate is what the spend window checks before the call and books when the
* gateway reports no settled charge, so it has to follow the length asked for.
*/
describe("per-second music on the account rail spend window", () => {
const key = "brk_live_music_per_second";
let upstream: Server;
let proxy: ProxyHandle;
let control: SpendControl;
let submitted: Array<Record<string, unknown>> = [];

beforeAll(async () => {
upstream = createServer((req, res) => {
const chunks: Buffer[] = [];
req.on("data", (c: Buffer) => chunks.push(c));
req.on("end", () => {
if (req.url === "/v1/audio/generations" && req.method === "POST") {
submitted.push(JSON.parse(Buffer.concat(chunks).toString() || "{}"));
}
res.setHeader("content-type", "application/json");
res.end('{"data":[]}');
});
});
await new Promise<void>((resolve) => upstream.listen(0, "127.0.0.1", resolve));
});

beforeEach(async () => {
await proxy?.close();
submitted = [];
control = new SpendControl({ storage: new InMemorySpendControlStorage() });
control.setLimit("perRequest", 0.1);
control.setLimit("session", 10);
proxy = await startProxy({
spendControl: control,
apiKey: key,
apiBase: `http://127.0.0.1:${(upstream.address() as AddressInfo).port}`,
port: 0,
allowExistingProxy: false,
});
});

afterAll(async () => {
await proxy?.close();
upstream.closeAllConnections();
await new Promise<void>((resolve) => upstream.close(() => resolve()));
});

const post = (body: Record<string, unknown>) =>
fetch(proxy.baseUrl + "/v1/audio/generations", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify(body),
});

it("books 0.0025 x the requested seconds, and 30 s when none is sent", async () => {
const res = await post({
model: "elevenlabs/music-v2.5",
prompt: "lofi",
duration_seconds: 20,
});
expect(res.status).toBe(200);
expect(control.getSpending("session")).toBeCloseTo(0.05, 9);

const dflt = await post({ model: "elevenlabs/music-v2.5", prompt: "lofi" });
expect(dflt.status).toBe(200);
expect(control.getSpending("session")).toBeCloseTo(0.05 + 0.075, 9);
expect(submitted).toHaveLength(2);
});

it("refuses a length whose per-second price exceeds the per-request cap, before the upstream call", async () => {
// 60 s = $0.15 > $0.10; a flat-rate estimate would have let it through or
// refused every length alike.
const res = await post({
model: "elevenlabs/music-v2.5",
prompt: "lofi",
duration_seconds: 60,
});
expect(res.status).not.toBe(200);
expect(submitted).toHaveLength(0);
expect(control.getSpending("session")).toBe(0);

const ok = await post({ model: "elevenlabs/music-v2.5", prompt: "lofi", duration_seconds: 40 });
expect(ok.status).toBe(200);
expect(submitted).toHaveLength(1);
});
});
66 changes: 58 additions & 8 deletions src/proxy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2368,21 +2368,66 @@ function estimateVideoCost(
// pricePerTrack in blockrun/src/lib/models.ts). Flat per track whatever its
// length; Base adds its transaction fee on top, Solana does not. MiniMax's
// $0.199 is the gateways' fixed final price; Lyria is Google's list price
// (added 2026-12-03). An unknown id (incl. the legacy minimax/music-2.5, which
// the gateway remaps to 2.5+) is estimated at the dearest track.
// (added 2026-12-03).
const MUSIC_PRICING: Record<string, number> = {
"minimax/music-2.5+": 0.199,
"google/lyria-3.5": 0.08,
"google/lyria-3-clip": 0.04,
};
const MUSIC_MAX_PRICE = Math.max(...Object.values(MUSIC_PRICING));
// Per-second music models: the gateway bills rate x the REQUESTED
// duration_seconds (int 5-240; 30 when omitted) and returns exactly that
// length. ElevenLabs Music v2.5 (2026-12-03): $0.0025/s on every rail that
// serves it (Base adds its $0.001 fee, Solana and api.blockrun.ai add none;
// not served on Arc). Unpaid 402 at 60 s: Base 151000 micro, Solana 150000.
const MUSIC_PER_SECOND_PRICING: Record<string, number> = {
"elevenlabs/music-v2.5": 0.0025,
};
const MUSIC_DEFAULT_DURATION_SECONDS = 30;
const MUSIC_MIN_DURATION_SECONDS = 5;
const MUSIC_MAX_DURATION_SECONDS = 240;
// The legacy minimax/music-2.5 left the catalog; the gateway remaps it to 2.5+.
const MUSIC_ALIASES: Record<string, string> = { "minimax/music-2.5": "minimax/music-2.5+" };
// The dearest track any known model can cost: an unknown id is estimated at
// this, never at a cheaper one (ElevenLabs at 240 s, above MiniMax's $0.199).
const MUSIC_MAX_PRICE = Math.max(
...Object.values(MUSIC_PRICING),
...Object.values(MUSIC_PER_SECOND_PRICING).map((rate) => rate * MUSIC_MAX_DURATION_SECONDS),
);

/** Ids the OpenClaw music picker offers; MiniMax first (the default). */
export const MUSIC_MODEL_IDS: readonly string[] = Object.freeze(Object.keys(MUSIC_PRICING));
export const MUSIC_MODEL_IDS: readonly string[] = Object.freeze([
...Object.keys(MUSIC_PRICING),
...Object.keys(MUSIC_PER_SECOND_PRICING),
]);

/**
* The seconds a per-second music model bills: the requested duration_seconds,
* the gateway's 30 when omitted. A value the gateway would refuse is estimated
* at the longest track rather than a shorter one.
*/
function musicBilledSeconds(durationSeconds: unknown): number {
if (durationSeconds === undefined || durationSeconds === null)
return MUSIC_DEFAULT_DURATION_SECONDS;
if (typeof durationSeconds !== "number" || !Number.isFinite(durationSeconds)) {
return MUSIC_MAX_DURATION_SECONDS;
}
return Math.min(
MUSIC_MAX_DURATION_SECONDS,
Math.max(MUSIC_MIN_DURATION_SECONDS, Math.ceil(durationSeconds)),
);
}

/** Estimate one music track's cost (telemetry fallback and account-rail spend window). */
export function estimateMusicCost(model: string): number {
const price = Object.hasOwn(MUSIC_PRICING, model) ? MUSIC_PRICING[model] : MUSIC_MAX_PRICE;
/**
* Estimate one music track's cost (telemetry fallback and account-rail spend
* window). Flat-per-track models ignore `durationSeconds`; a per-second model
* is rate x the requested length (30 s when omitted).
*/
export function estimateMusicCost(model: string, durationSeconds?: unknown): number {
const id = Object.hasOwn(MUSIC_ALIASES, model) ? MUSIC_ALIASES[model] : model;
if (Object.hasOwn(MUSIC_PER_SECOND_PRICING, id)) {
return MUSIC_PER_SECOND_PRICING[id] * musicBilledSeconds(durationSeconds) * MEDIA_MARGIN;
}
const price = Object.hasOwn(MUSIC_PRICING, id) ? MUSIC_PRICING[id] : MUSIC_MAX_PRICE;
return price * MEDIA_MARGIN;
}

Expand Down Expand Up @@ -4608,14 +4653,19 @@ export async function startProxy(options: ProxyOptions): Promise<ProxyHandle> {
}
const reqBody = Buffer.concat(chunks);
let audioModel = "minimax/music-2.5+";
// Per-second models (ElevenLabs Music) bill the requested length, so the
// estimate — the account rail's spend window and the telemetry fallback —
// needs it too.
let audioDurationSeconds: unknown;
try {
const parsed = JSON.parse(reqBody.toString());
audioModel = parsed.model || audioModel;
audioDurationSeconds = parsed.duration_seconds;
} catch {
/* use defaults */
}
try {
const audioEstimate = estimateMusicCost(audioModel);
const audioEstimate = estimateMusicCost(audioModel, audioDurationSeconds);
publishDispatchCost(audioEstimate);
let upstream = await payFetch(`${apiBase}/v1/audio/generations`, {
method: "POST",
Expand Down
2 changes: 2 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -222,6 +222,8 @@ export type MusicGenerationProviderCapabilities = {
maxTracks?: number;
maxDurationSeconds?: number;
supportsLyrics?: boolean;
/** Per-model override of supportsLyrics (OpenClaw drops lyrics for a model mapped to false). */
supportsLyricsByModel?: Readonly<Record<string, boolean>>;
supportsInstrumental?: boolean;
supportsDuration?: boolean;
supportsFormat?: boolean;
Expand Down
Loading