@fungi.computer/darkroom 0.11.11 → 0.11.12
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +13 -0
- package/examples/standalone/README.md +52 -0
- package/examples/standalone/worker.ts +87 -0
- package/examples/standalone/wrangler.jsonc +26 -0
- package/package.json +7 -1
- package/src/app-media-contracts.ts +142 -0
- package/src/audio-providers/elevenlabs.ts +108 -0
- package/src/audio-reference-types.ts +47 -0
- package/src/audio-references.ts +107 -0
- package/src/browser-failure.ts +73 -0
- package/src/browser.ts +7 -0
- package/src/cloudflare/provider-reason.ts +89 -0
- package/src/cloudflare/provider.ts +405 -0
- package/src/cloudflare/r2-destination.ts +130 -0
- package/src/cloudflare/reference-images.ts +193 -0
- package/src/cloudflare.ts +38 -0
- package/src/cost-estimate.ts +129 -0
- package/src/daily-media-meter.ts +163 -0
- package/src/effect.ts +2 -0
- package/src/execution-error.ts +98 -0
- package/src/failure.ts +13 -0
- package/src/gateway-models.ts +304 -0
- package/src/gateway-wire.ts +36 -0
- package/src/index.ts +1454 -0
- package/src/media-binding.ts +260 -0
- package/src/media-content-type.ts +60 -0
- package/src/media-generation.ts +171 -0
- package/src/media-operation-contract.ts +173 -0
- package/src/media-operation-do.ts +257 -0
- package/src/media-operation-owner.ts +1786 -0
- package/src/media-operation-storage.ts +110 -0
- package/src/media-operation.ts +454 -0
- package/src/media-path.ts +8 -0
- package/src/media-quote.ts +34 -0
- package/src/media-run-lifetime.ts +5 -0
- package/src/media-written.ts +38 -0
- package/src/model-catalog.ts +1574 -0
- package/src/neurons.ts +6 -0
- package/src/node-webpmux.d.ts +12 -0
- package/src/provenance-bytes.ts +22 -0
- package/src/provenance-export.ts +126 -0
- package/src/provenance-jpeg.ts +83 -0
- package/src/provenance-png.ts +26 -0
- package/src/provenance-signed.ts +7 -0
- package/src/provenance-xmp.ts +57 -0
- package/src/provenance.ts +87 -0
- package/src/reference-image-size.ts +67 -0
- package/src/reference-read.ts +50 -0
- package/src/server.ts +711 -0
- package/src/video-providers/index.ts +18 -0
- package/src/video-providers/minimax.ts +96 -0
- package/src/video-providers/reference-encoding.ts +32 -0
- package/src/video-providers/types.ts +47 -0
- package/src/video-providers/unified.ts +68 -0
- package/test/audio-models.test.ts +428 -0
- package/test/audio-references.test.ts +428 -0
- package/test/custom-catalogue.test.ts +257 -0
- package/test/daily-media-meter.test.ts +287 -0
- package/test/failure.test.ts +190 -0
- package/test/fixtures/cloudflare-workers.fixture.ts +10 -0
- package/test/fixtures/media-operation.fixture.ts +134 -0
- package/test/fixtures/media-team-prompts.ts +7 -0
- package/test/fixtures/native-sqlite.fixture.ts +40 -0
- package/test/gateway-models.test.ts +712 -0
- package/test/media-operation-do.test.ts +1565 -0
- package/test/media-quote.test.ts +81 -0
- package/test/media-retention.test.ts +597 -0
- package/test/media-service.test.ts +549 -0
- package/test/media-team-prompts.test.ts +92 -0
- package/test/model-facts.test.ts +126 -0
- package/test/prompt-limit.test.ts +53 -0
- package/test/provenance-export.test.ts +144 -0
- package/test/provenance-images.fixture.mjs +17 -0
- package/test/provenance.test.ts +179 -0
- package/test/provider-gateway.test.ts +114 -0
- package/test/provider-reasons.test.ts +133 -0
- package/test/r2-destination.test.ts +166 -0
- package/test/reference-image-size.test.ts +73 -0
- package/test/reference-images-billing.test.ts +40 -0
- package/test/reference-images.test.ts +399 -0
- package/test/standalone.cloudflare.test.mjs +298 -0
- package/test/standalone.worker.mjs +70 -0
- package/test/transform-models.test.ts +400 -0
- package/test/video-capabilities.test.ts +160 -0
- package/test/video-contract.test.ts +533 -0
- package/test/video-failure-lifecycle.test.ts +177 -0
- package/test/video-provider.test.ts +136 -0
- package/test/video-wire.test.ts +251 -0
- package/vitest.cloudflare.config.ts +22 -0
- package/vitest.node.config.ts +14 -0
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { unifiedVideoAdapter } from "./unified.js";
|
|
2
|
+
import { minimaxVideoAdapter } from "./minimax.js";
|
|
3
|
+
import type { VideoProvider, VideoProviderAdapter } from "./types.js";
|
|
4
|
+
|
|
5
|
+
export type { CheckedVideoSettings } from "./types.js";
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* One adapter per verified video provider family. Seedance and Veo share
|
|
9
|
+
* `unifiedVideoAdapter`; MiniMax's distinct `content[]` request and
|
|
10
|
+
* `{task: {...}}` answer get their own module. Adding a provider means
|
|
11
|
+
* writing one adapter module and one entry here — `gatewayInput` and
|
|
12
|
+
* `generateThroughGateway` never branch on the provider name themselves.
|
|
13
|
+
*/
|
|
14
|
+
export const videoProviderAdapters = {
|
|
15
|
+
seedance: unifiedVideoAdapter,
|
|
16
|
+
veo: unifiedVideoAdapter,
|
|
17
|
+
minimax: minimaxVideoAdapter,
|
|
18
|
+
} satisfies Record<VideoProvider, VideoProviderAdapter>;
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import * as z from "zod";
|
|
2
|
+
import { MediaSettingsError } from "../model-catalog.js";
|
|
3
|
+
import type {
|
|
4
|
+
MediaVideoReferenceRole,
|
|
5
|
+
MediaVideoResolution,
|
|
6
|
+
} from "../model-catalog.js";
|
|
7
|
+
import { resultUrl } from "../gateway-wire.js";
|
|
8
|
+
import { imageDataUri } from "./reference-encoding.js";
|
|
9
|
+
import type { VideoProviderAdapter } from "./types.js";
|
|
10
|
+
|
|
11
|
+
/** MiniMax's documented `content[]` image role, distinct from our neutral one. */
|
|
12
|
+
export type MinimaxReferenceRole = "first_frame" | "reference_image";
|
|
13
|
+
/** One MiniMax `content[]` entry, exactly as its schema documents it. */
|
|
14
|
+
export type MinimaxContentItem =
|
|
15
|
+
| { type: "text"; text: string }
|
|
16
|
+
| {
|
|
17
|
+
type: "image_url";
|
|
18
|
+
image_url: { url: string };
|
|
19
|
+
role: MinimaxReferenceRole;
|
|
20
|
+
};
|
|
21
|
+
/** MiniMax's documented uppercase resolution literal. */
|
|
22
|
+
export type MinimaxResolution = "480P" | "720P" | "768P" | "1080P" | "4K";
|
|
23
|
+
/** MiniMax H3 Max's documented provider body: multimodal `content[]`, not a
|
|
24
|
+
* flat prompt/image/duration object. */
|
|
25
|
+
export type MinimaxGatewayInput = {
|
|
26
|
+
content: MinimaxContentItem[];
|
|
27
|
+
duration: number;
|
|
28
|
+
resolution: MinimaxResolution;
|
|
29
|
+
ratio: string;
|
|
30
|
+
};
|
|
31
|
+
/** Our lowercase selector to MiniMax's documented uppercase wire literal. */
|
|
32
|
+
const minimaxResolutionWire = {
|
|
33
|
+
"480p": "480P",
|
|
34
|
+
"720p": "720P",
|
|
35
|
+
"768p": "768P",
|
|
36
|
+
"1080p": "1080P",
|
|
37
|
+
"4k": "4K",
|
|
38
|
+
} satisfies Record<MediaVideoResolution, MinimaxResolution>;
|
|
39
|
+
/** Our neutral reference role to MiniMax's documented `content[]` role. */
|
|
40
|
+
const minimaxRoleWire = {
|
|
41
|
+
"first-frame": "first_frame",
|
|
42
|
+
reference: "reference_image",
|
|
43
|
+
} satisfies Partial<Record<MediaVideoReferenceRole, MinimaxReferenceRole>>;
|
|
44
|
+
|
|
45
|
+
/** MiniMax's documented task wrapper: `{task: {status, content: {url}}}`,
|
|
46
|
+
* distinct from the Unified gateway's `{state, result}` shape Seedance and
|
|
47
|
+
* Veo normalize into. https://developers.cloudflare.com/ai/models/minimax/h3-max/ */
|
|
48
|
+
const minimaxTaskOutputSchema = z.lazy(() =>
|
|
49
|
+
z.looseObject({
|
|
50
|
+
task: z.looseObject({
|
|
51
|
+
status: z.enum(["queued", "running", "succeeded", "failed", "cancelled"]),
|
|
52
|
+
content: z.looseObject({ url: resultUrl.optional() }).optional(),
|
|
53
|
+
}),
|
|
54
|
+
}),
|
|
55
|
+
);
|
|
56
|
+
|
|
57
|
+
export const minimaxVideoAdapter: VideoProviderAdapter = {
|
|
58
|
+
buildInput(checked, references, model) {
|
|
59
|
+
if (checked.generateAudio !== undefined)
|
|
60
|
+
throw new MediaSettingsError(
|
|
61
|
+
`${model.id} does not support an audio choice`,
|
|
62
|
+
);
|
|
63
|
+
const content: MinimaxContentItem[] = [
|
|
64
|
+
{ type: "text", text: checked.prompt },
|
|
65
|
+
];
|
|
66
|
+
references.forEach((image, index) => {
|
|
67
|
+
const role = checked.references?.[index]?.role;
|
|
68
|
+
const wireRole =
|
|
69
|
+
role === undefined || role === "last-frame"
|
|
70
|
+
? undefined
|
|
71
|
+
: minimaxRoleWire[role];
|
|
72
|
+
if (wireRole === undefined)
|
|
73
|
+
throw new MediaSettingsError("video reference role was not admitted");
|
|
74
|
+
content.push({
|
|
75
|
+
type: "image_url",
|
|
76
|
+
image_url: { url: imageDataUri(image) },
|
|
77
|
+
role: wireRole,
|
|
78
|
+
});
|
|
79
|
+
});
|
|
80
|
+
const input: MinimaxGatewayInput = {
|
|
81
|
+
content,
|
|
82
|
+
duration: checked.durationSeconds,
|
|
83
|
+
resolution: minimaxResolutionWire[checked.resolution],
|
|
84
|
+
ratio: checked.aspectRatio,
|
|
85
|
+
};
|
|
86
|
+
return input;
|
|
87
|
+
},
|
|
88
|
+
decodeResultUrl(providerValue) {
|
|
89
|
+
const parsed = minimaxTaskOutputSchema.parse(providerValue);
|
|
90
|
+
if (parsed.task.status !== "succeeded")
|
|
91
|
+
throw new Error(`minimax video task ${parsed.task.status}`);
|
|
92
|
+
const url = parsed.task.content?.url;
|
|
93
|
+
if (url === undefined) throw new Error("minimax video task has no URL");
|
|
94
|
+
return url;
|
|
95
|
+
},
|
|
96
|
+
};
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
MediaAudioReferenceBytes,
|
|
3
|
+
MediaReferenceBytes,
|
|
4
|
+
} from "../index.js";
|
|
5
|
+
|
|
6
|
+
/** Encode in multiples of three so only the final chunk needs base64 padding. */
|
|
7
|
+
function base64(bytes: Uint8Array): string {
|
|
8
|
+
const chunks: string[] = [];
|
|
9
|
+
for (let offset = 0; offset < bytes.length; offset += 32_766)
|
|
10
|
+
chunks.push(
|
|
11
|
+
btoa(String.fromCharCode(...bytes.subarray(offset, offset + 32_766))),
|
|
12
|
+
);
|
|
13
|
+
return chunks.join("");
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export function imageBase64(image: MediaReferenceBytes): string {
|
|
17
|
+
return base64(image.bytes);
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* One `reference_audios` entry: a `data:audio/...` base64 URI, the form
|
|
22
|
+
* Seedance 2.5's input schema documents next to HTTP(S) URLs.
|
|
23
|
+
* https://developers.cloudflare.com/ai/models/bytedance/seedance-2.5/schema-input.json
|
|
24
|
+
*/
|
|
25
|
+
export function audioDataUri(clip: MediaAudioReferenceBytes): string {
|
|
26
|
+
return `data:${clip.mimeType};base64,${base64(clip.bytes)}`;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function imageDataUri(image: MediaReferenceBytes): string {
|
|
30
|
+
const mime = image.format === "jpeg" ? "image/jpeg" : `image/${image.format}`;
|
|
31
|
+
return `data:${mime};base64,${imageBase64(image)}`;
|
|
32
|
+
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
MediaAiResult,
|
|
3
|
+
MediaAudioReferenceBytes,
|
|
4
|
+
MediaGenerationSettings,
|
|
5
|
+
MediaReferenceBytes,
|
|
6
|
+
} from "../index.js";
|
|
7
|
+
import type {
|
|
8
|
+
MediaModel,
|
|
9
|
+
MediaVideoAspectRatio,
|
|
10
|
+
MediaVideoModel,
|
|
11
|
+
MediaVideoResolution,
|
|
12
|
+
} from "../model-catalog.js";
|
|
13
|
+
import type { UnifiedGatewayInput } from "./unified.js";
|
|
14
|
+
import type { MinimaxGatewayInput } from "./minimax.js";
|
|
15
|
+
|
|
16
|
+
/** One verified video provider family, as the catalog names it. */
|
|
17
|
+
export type VideoProvider = MediaVideoModel["provider"];
|
|
18
|
+
|
|
19
|
+
/** Validated video settings with every video-only field guaranteed present;
|
|
20
|
+
* `gatewayInput` narrows to this before handing settings to an adapter. */
|
|
21
|
+
export type CheckedVideoSettings = MediaGenerationSettings & {
|
|
22
|
+
resolution: MediaVideoResolution;
|
|
23
|
+
aspectRatio: MediaVideoAspectRatio;
|
|
24
|
+
durationSeconds: number;
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
/** Every documented provider request body this catalog can produce. */
|
|
28
|
+
export type VideoProviderInput = UnifiedGatewayInput | MinimaxGatewayInput;
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* One provider family's wire translation: the exact request body its
|
|
32
|
+
* documented schema expects, and how to pull a validated result URL out of
|
|
33
|
+
* its answer. Adding a provider means writing one adapter and one table
|
|
34
|
+
* entry; `gatewayInput` and `generateThroughGateway` never branch on the
|
|
35
|
+
* provider name themselves.
|
|
36
|
+
*/
|
|
37
|
+
export type VideoProviderAdapter = {
|
|
38
|
+
/** Build the provider JSON body for one validated video generation. */
|
|
39
|
+
buildInput(
|
|
40
|
+
checked: CheckedVideoSettings,
|
|
41
|
+
references: readonly MediaReferenceBytes[],
|
|
42
|
+
model: MediaModel,
|
|
43
|
+
audioReferences: readonly MediaAudioReferenceBytes[],
|
|
44
|
+
): VideoProviderInput;
|
|
45
|
+
/** Extract and validate the HTTPS result URL from the raw provider answer. */
|
|
46
|
+
decodeResultUrl(providerValue: MediaAiResult): string;
|
|
47
|
+
};
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import { MediaSettingsError } from "../model-catalog.js";
|
|
2
|
+
import { gatewayOutputSchema } from "../gateway-wire.js";
|
|
3
|
+
import {
|
|
4
|
+
audioDataUri,
|
|
5
|
+
imageBase64,
|
|
6
|
+
imageDataUri,
|
|
7
|
+
} from "./reference-encoding.js";
|
|
8
|
+
import type { VideoProviderAdapter } from "./types.js";
|
|
9
|
+
|
|
10
|
+
export type UnifiedGatewayInput = {
|
|
11
|
+
prompt: string;
|
|
12
|
+
duration: string | number;
|
|
13
|
+
resolution: string;
|
|
14
|
+
aspect_ratio: string;
|
|
15
|
+
generate_audio?: boolean;
|
|
16
|
+
image?: string;
|
|
17
|
+
last_frame_image?: string;
|
|
18
|
+
reference_images?: string[];
|
|
19
|
+
reference_audios?: string[];
|
|
20
|
+
image_input?: string;
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Seedance and Veo share the Unified AI gateway's `{state, result}` answer
|
|
25
|
+
* and a flat prompt/image request body; only a few fields differ by
|
|
26
|
+
* provider, handled inline below.
|
|
27
|
+
*/
|
|
28
|
+
export const unifiedVideoAdapter: VideoProviderAdapter = {
|
|
29
|
+
buildInput(checked, references, model, audioReferences) {
|
|
30
|
+
const veo = model.video?.provider === "veo";
|
|
31
|
+
const input: UnifiedGatewayInput = {
|
|
32
|
+
prompt: checked.prompt,
|
|
33
|
+
duration: veo
|
|
34
|
+
? `${String(checked.durationSeconds)}s`
|
|
35
|
+
: checked.durationSeconds,
|
|
36
|
+
resolution: checked.resolution,
|
|
37
|
+
aspect_ratio: checked.aspectRatio,
|
|
38
|
+
};
|
|
39
|
+
if (checked.generateAudio !== undefined)
|
|
40
|
+
input.generate_audio = checked.generateAudio;
|
|
41
|
+
const referenceImages: string[] = [];
|
|
42
|
+
references.forEach((image, index) => {
|
|
43
|
+
const role = checked.references?.[index]?.role;
|
|
44
|
+
if (veo) {
|
|
45
|
+
input.image_input = imageBase64(image);
|
|
46
|
+
} else if (role === "first-frame") {
|
|
47
|
+
input.image = imageDataUri(image);
|
|
48
|
+
} else if (role === "last-frame") {
|
|
49
|
+
input.last_frame_image = imageDataUri(image);
|
|
50
|
+
} else if (role === "reference") {
|
|
51
|
+
referenceImages.push(imageDataUri(image));
|
|
52
|
+
} else
|
|
53
|
+
throw new MediaSettingsError("video reference role was not admitted");
|
|
54
|
+
});
|
|
55
|
+
if (referenceImages.length > 0) input.reference_images = referenceImages;
|
|
56
|
+
if (audioReferences.length > 0)
|
|
57
|
+
input.reference_audios = audioReferences.map(audioDataUri);
|
|
58
|
+
return input;
|
|
59
|
+
},
|
|
60
|
+
decodeResultUrl(providerValue) {
|
|
61
|
+
const parsed = gatewayOutputSchema.parse(providerValue);
|
|
62
|
+
if (parsed.state !== "Completed")
|
|
63
|
+
throw new Error("gateway video result is not completed");
|
|
64
|
+
if (parsed.result.video === undefined)
|
|
65
|
+
throw new Error("gateway video result has no URL");
|
|
66
|
+
return parsed.result.video;
|
|
67
|
+
},
|
|
68
|
+
};
|
|
@@ -0,0 +1,428 @@
|
|
|
1
|
+
import { describe, expect, it, vi } from "vitest";
|
|
2
|
+
import {
|
|
3
|
+
getMediaModel,
|
|
4
|
+
listMediaModels,
|
|
5
|
+
parseMediaCatalogue,
|
|
6
|
+
validateMediaGenerationSettings,
|
|
7
|
+
} from "../src/index.js";
|
|
8
|
+
import {
|
|
9
|
+
estimateGatewayMilliunits,
|
|
10
|
+
gatewayInput,
|
|
11
|
+
mediaUnits,
|
|
12
|
+
} from "../src/gateway-models.js";
|
|
13
|
+
import { generate, type MediaAiPort } from "../src/cloudflare/provider.js";
|
|
14
|
+
import type { MediaProvider } from "../src/index.js";
|
|
15
|
+
import { createMediaService } from "../src/server.js";
|
|
16
|
+
import { MediaOperationOwner } from "../src/media-operation-owner.js";
|
|
17
|
+
import { mediaOperationFixture } from "./fixtures/media-operation.fixture.js";
|
|
18
|
+
import {
|
|
19
|
+
mediaBindingRequest,
|
|
20
|
+
parseMediaBindingCall,
|
|
21
|
+
} from "../src/media-binding.js";
|
|
22
|
+
|
|
23
|
+
/** The only voice Cloudflare's ElevenLabs pages list. */
|
|
24
|
+
const voice = "JBFqnCBsd6RMkjVDRZzb";
|
|
25
|
+
const speechModels = [
|
|
26
|
+
"elevenlabs/eleven-multilingual-v2",
|
|
27
|
+
"elevenlabs/eleven-v3",
|
|
28
|
+
] as const;
|
|
29
|
+
const music = "elevenlabs/music-v2";
|
|
30
|
+
const mp3 = Uint8Array.from([0x49, 0x44, 0x33, 3, 0, 0, 0, 0, 0, 0]);
|
|
31
|
+
|
|
32
|
+
const speech = (model: string = speechModels[0], prompt = "Hello fern.") =>
|
|
33
|
+
validateMediaGenerationSettings({ model, prompt });
|
|
34
|
+
const song = (durationSeconds?: number) => {
|
|
35
|
+
const input: Parameters<typeof validateMediaGenerationSettings>[0] = {
|
|
36
|
+
model: music,
|
|
37
|
+
prompt: "a slow kalimba theme",
|
|
38
|
+
};
|
|
39
|
+
if (durationSeconds !== undefined) input.durationSeconds = durationSeconds;
|
|
40
|
+
return validateMediaGenerationSettings(input);
|
|
41
|
+
};
|
|
42
|
+
|
|
43
|
+
describe("ElevenLabs audio models", () => {
|
|
44
|
+
it("lists three audio models with the documented bounds and rates", () => {
|
|
45
|
+
const audio = listMediaModels().filter((model) => model.kind === "audio");
|
|
46
|
+
expect(audio.map((model) => model.id)).toEqual([...speechModels, music]);
|
|
47
|
+
for (const id of speechModels) {
|
|
48
|
+
const model = getMediaModel(id);
|
|
49
|
+
expect(model?.maxPromptLength).toBe(10_000);
|
|
50
|
+
expect(model?.audio?.voices.map((entry) => entry.id)).toEqual([voice]);
|
|
51
|
+
}
|
|
52
|
+
// Multilingual v2 and v3 list $0.0001 per character.
|
|
53
|
+
expect(getMediaModel(speechModels[0])?.audio?.milliunitsPerUnit).toBe(10);
|
|
54
|
+
expect(getMediaModel(speechModels[1])?.audio?.milliunitsPerUnit).toBe(10);
|
|
55
|
+
// Eleven Flash answers 403 code 2047 (BYOK only) on Unified Billing.
|
|
56
|
+
expect(getMediaModel("elevenlabs/eleven-flash-v2-5")).toBeUndefined();
|
|
57
|
+
expect(getMediaModel(music)?.audio).toMatchObject({
|
|
58
|
+
mode: "music",
|
|
59
|
+
voices: [],
|
|
60
|
+
seconds: { min: 3, max: 600, default: 30 },
|
|
61
|
+
milliunitsPerUnit: 250,
|
|
62
|
+
});
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
it("normalizes speech to its default voice and refuses everything else", () => {
|
|
66
|
+
expect(speech()).toEqual({
|
|
67
|
+
model: speechModels[0],
|
|
68
|
+
prompt: "Hello fern.",
|
|
69
|
+
voiceId: voice,
|
|
70
|
+
});
|
|
71
|
+
expect(() =>
|
|
72
|
+
validateMediaGenerationSettings({
|
|
73
|
+
model: speechModels[0],
|
|
74
|
+
prompt: "x",
|
|
75
|
+
voiceId: "not-a-listed-voice",
|
|
76
|
+
}),
|
|
77
|
+
).toThrow("accepts only these voices");
|
|
78
|
+
for (const extra of [
|
|
79
|
+
{ width: 1024 },
|
|
80
|
+
{ height: 1024 },
|
|
81
|
+
{ steps: 4 },
|
|
82
|
+
{ generateAudio: true },
|
|
83
|
+
{ references: [{ computerId: "c", path: "/a.png" }] },
|
|
84
|
+
])
|
|
85
|
+
expect(() =>
|
|
86
|
+
validateMediaGenerationSettings({
|
|
87
|
+
model: speechModels[0],
|
|
88
|
+
prompt: "x",
|
|
89
|
+
...extra,
|
|
90
|
+
}),
|
|
91
|
+
).toThrow("takes only a prompt and a voice");
|
|
92
|
+
expect(() =>
|
|
93
|
+
validateMediaGenerationSettings({
|
|
94
|
+
model: speechModels[0],
|
|
95
|
+
prompt: "x",
|
|
96
|
+
durationSeconds: 5,
|
|
97
|
+
}),
|
|
98
|
+
).toThrow("does not take a duration");
|
|
99
|
+
expect(() => speech(speechModels[0], "x".repeat(10_001))).toThrow(
|
|
100
|
+
"limit is 10000",
|
|
101
|
+
);
|
|
102
|
+
});
|
|
103
|
+
|
|
104
|
+
it("bounds music length to 3 through 600 seconds and refuses a voice", () => {
|
|
105
|
+
expect(song()).toMatchObject({ durationSeconds: 30 });
|
|
106
|
+
expect(song(3)).toMatchObject({ durationSeconds: 3 });
|
|
107
|
+
expect(song(600)).toMatchObject({ durationSeconds: 600 });
|
|
108
|
+
expect(() => song(2)).toThrow("durationSeconds");
|
|
109
|
+
expect(() => song(601)).toThrow("durationSeconds");
|
|
110
|
+
expect(() =>
|
|
111
|
+
validateMediaGenerationSettings({
|
|
112
|
+
model: music,
|
|
113
|
+
prompt: "x",
|
|
114
|
+
voiceId: voice,
|
|
115
|
+
}),
|
|
116
|
+
).toThrow("does not take a voice");
|
|
117
|
+
expect(() =>
|
|
118
|
+
validateMediaGenerationSettings({
|
|
119
|
+
model: "openai/gpt-image-2",
|
|
120
|
+
prompt: "x",
|
|
121
|
+
width: 1024,
|
|
122
|
+
height: 1024,
|
|
123
|
+
voiceId: voice,
|
|
124
|
+
}),
|
|
125
|
+
).toThrow("does not take a voice");
|
|
126
|
+
});
|
|
127
|
+
|
|
128
|
+
it("builds each provider body from its documented schema", () => {
|
|
129
|
+
expect(gatewayInput(speech(speechModels[1], "Hi"))).toEqual({
|
|
130
|
+
text: "Hi",
|
|
131
|
+
voice_id: voice,
|
|
132
|
+
output_format: "mp3_44100_128",
|
|
133
|
+
});
|
|
134
|
+
expect(gatewayInput(song(45))).toEqual({
|
|
135
|
+
prompt: "a slow kalimba theme",
|
|
136
|
+
music_length_ms: 45_000,
|
|
137
|
+
output_format: "mp3_44100_128",
|
|
138
|
+
});
|
|
139
|
+
});
|
|
140
|
+
|
|
141
|
+
it("bills speech per 100-character block and music per second", () => {
|
|
142
|
+
expect(mediaUnits(speech(speechModels[0], "x".repeat(100)))).toEqual({
|
|
143
|
+
unit: "audio_character_block",
|
|
144
|
+
units: 1,
|
|
145
|
+
});
|
|
146
|
+
expect(mediaUnits(speech(speechModels[0], "x".repeat(101)))).toEqual({
|
|
147
|
+
unit: "audio_character_block",
|
|
148
|
+
units: 2,
|
|
149
|
+
});
|
|
150
|
+
expect(mediaUnits(song(45))).toEqual({ unit: "audio_second", units: 45 });
|
|
151
|
+
});
|
|
152
|
+
|
|
153
|
+
it("quotes published rates in milliunits", () => {
|
|
154
|
+
// 100 characters at $0.0001; 45 seconds at $0.0025.
|
|
155
|
+
expect(
|
|
156
|
+
estimateGatewayMilliunits(speech(speechModels[0], "x".repeat(100)), []),
|
|
157
|
+
).toBe(1_000);
|
|
158
|
+
expect(
|
|
159
|
+
estimateGatewayMilliunits(speech(speechModels[1], "x".repeat(100)), []),
|
|
160
|
+
).toBe(1_000);
|
|
161
|
+
expect(estimateGatewayMilliunits(song(45), [])).toBe(11_250);
|
|
162
|
+
});
|
|
163
|
+
|
|
164
|
+
/** The inner value of a live Unified Billing answer (2026-11-13), URL host abbreviated. */
|
|
165
|
+
const liveAnswer = {
|
|
166
|
+
state: "Completed",
|
|
167
|
+
result: {
|
|
168
|
+
audio:
|
|
169
|
+
"https://ai-gateway-outputs.example.r2.cloudflarestorage.com/a.mp3",
|
|
170
|
+
},
|
|
171
|
+
};
|
|
172
|
+
|
|
173
|
+
it("dispatches through the gateway and saves the fetched MP3", async () => {
|
|
174
|
+
const settings = speech(speechModels[0], "Hello fern.");
|
|
175
|
+
const run = vi.fn(() => Promise.resolve(liveAnswer));
|
|
176
|
+
const fetchResult = vi.fn<typeof fetch>(() =>
|
|
177
|
+
Promise.resolve(new Response(mp3)),
|
|
178
|
+
);
|
|
179
|
+
await expect(
|
|
180
|
+
generate(
|
|
181
|
+
{ run },
|
|
182
|
+
settings,
|
|
183
|
+
[],
|
|
184
|
+
undefined,
|
|
185
|
+
{ gateway: { id: "fungi-hub" } },
|
|
186
|
+
fetchResult,
|
|
187
|
+
),
|
|
188
|
+
).resolves.toEqual({ bytes: mp3, format: "mp3" });
|
|
189
|
+
expect(run).toHaveBeenCalledWith(
|
|
190
|
+
speechModels[0],
|
|
191
|
+
{
|
|
192
|
+
text: "Hello fern.",
|
|
193
|
+
voice_id: voice,
|
|
194
|
+
output_format: "mp3_44100_128",
|
|
195
|
+
},
|
|
196
|
+
{ gateway: { id: "fungi-hub" } },
|
|
197
|
+
);
|
|
198
|
+
expect(fetchResult.mock.calls[0]?.[0]).toBe(liveAnswer.result.audio);
|
|
199
|
+
});
|
|
200
|
+
|
|
201
|
+
it("sends music as prompt plus music_length_ms and reads the same answer", async () => {
|
|
202
|
+
const run = vi.fn(() => Promise.resolve(liveAnswer));
|
|
203
|
+
await generate({ run }, song(12), [], undefined, undefined, () =>
|
|
204
|
+
Promise.resolve(new Response(mp3)),
|
|
205
|
+
);
|
|
206
|
+
expect(run).toHaveBeenCalledWith(
|
|
207
|
+
music,
|
|
208
|
+
{
|
|
209
|
+
prompt: "a slow kalimba theme",
|
|
210
|
+
music_length_ms: 12_000,
|
|
211
|
+
output_format: "mp3_44100_128",
|
|
212
|
+
},
|
|
213
|
+
undefined,
|
|
214
|
+
);
|
|
215
|
+
});
|
|
216
|
+
|
|
217
|
+
it.each([
|
|
218
|
+
["the bare schema shape", { audio: "https://results.example/a.mp3" }],
|
|
219
|
+
[
|
|
220
|
+
"a non-HTTPS URL",
|
|
221
|
+
{ state: "Completed", result: { audio: "http://results.example/a.mp3" } },
|
|
222
|
+
],
|
|
223
|
+
["no audio field", { state: "Completed", result: {} }],
|
|
224
|
+
[
|
|
225
|
+
"a state that is not Completed",
|
|
226
|
+
{ state: "Failed", result: { audio: "https://x.example/a" } },
|
|
227
|
+
],
|
|
228
|
+
])("refuses %s", async (_name, answer) => {
|
|
229
|
+
const fetchResult = vi.fn<typeof fetch>(() =>
|
|
230
|
+
Promise.resolve(new Response(mp3)),
|
|
231
|
+
);
|
|
232
|
+
await expect(
|
|
233
|
+
generate(
|
|
234
|
+
{ run: () => Promise.resolve(answer) },
|
|
235
|
+
speech(),
|
|
236
|
+
[],
|
|
237
|
+
undefined,
|
|
238
|
+
undefined,
|
|
239
|
+
fetchResult,
|
|
240
|
+
),
|
|
241
|
+
).rejects.toMatchObject({ stage: "normalization" });
|
|
242
|
+
expect(fetchResult).not.toHaveBeenCalled();
|
|
243
|
+
});
|
|
244
|
+
|
|
245
|
+
it("refuses a failed result download", async () => {
|
|
246
|
+
await expect(
|
|
247
|
+
generate(
|
|
248
|
+
{
|
|
249
|
+
run: () => Promise.resolve(liveAnswer),
|
|
250
|
+
},
|
|
251
|
+
speech(),
|
|
252
|
+
[],
|
|
253
|
+
undefined,
|
|
254
|
+
undefined,
|
|
255
|
+
() => Promise.resolve(new Response("gone", { status: 404 })),
|
|
256
|
+
),
|
|
257
|
+
).rejects.toMatchObject({
|
|
258
|
+
stage: "normalization",
|
|
259
|
+
provider: { category: "result_download", status: 404 },
|
|
260
|
+
});
|
|
261
|
+
});
|
|
262
|
+
});
|
|
263
|
+
|
|
264
|
+
describe("a host catalogue", () => {
|
|
265
|
+
const entry = {
|
|
266
|
+
...structuredClone(getMediaModel(speechModels[0])),
|
|
267
|
+
audio: undefined,
|
|
268
|
+
};
|
|
269
|
+
it("carries audio bounds exactly when the kind is audio", () => {
|
|
270
|
+
expect(() => parseMediaCatalogue([entry])).toThrow(
|
|
271
|
+
"must carry audio bounds exactly when kind is audio",
|
|
272
|
+
);
|
|
273
|
+
expect(
|
|
274
|
+
parseMediaCatalogue([getMediaModel(speechModels[0])])[0]?.audio?.mode,
|
|
275
|
+
).toBe("speech");
|
|
276
|
+
});
|
|
277
|
+
});
|
|
278
|
+
|
|
279
|
+
describe("audio references", () => {
|
|
280
|
+
it("are declared only by Seedance 2.5, at 10 clips and 30 seconds", () => {
|
|
281
|
+
const declared = listMediaModels()
|
|
282
|
+
.filter((model) => model.video?.audioReferences != null)
|
|
283
|
+
.map((model) => [model.id, model.video?.audioReferences]);
|
|
284
|
+
expect(declared).toEqual([
|
|
285
|
+
["bytedance/seedance-2.5", { max: 10, totalSeconds: 30 }],
|
|
286
|
+
]);
|
|
287
|
+
});
|
|
288
|
+
});
|
|
289
|
+
|
|
290
|
+
describe("audio through the MEDIA binding", () => {
|
|
291
|
+
const call = (settings: Record<string, string | number>) =>
|
|
292
|
+
parseMediaBindingCall({
|
|
293
|
+
operation: "generate",
|
|
294
|
+
input: {
|
|
295
|
+
kind: "audio",
|
|
296
|
+
requestId: "media_request_abcdefghijklmnopqrstu",
|
|
297
|
+
libraryPath: "/workspace/prints",
|
|
298
|
+
settings,
|
|
299
|
+
},
|
|
300
|
+
});
|
|
301
|
+
|
|
302
|
+
it("writes speech and music to an .mp3 under the App's folder", () => {
|
|
303
|
+
for (const settings of [
|
|
304
|
+
{ model: speechModels[0], prompt: "Hi" },
|
|
305
|
+
{ model: music, prompt: "theme", durationSeconds: 12 },
|
|
306
|
+
]) {
|
|
307
|
+
const parsed = call(settings);
|
|
308
|
+
if (parsed.kind !== "parsed" || parsed.call.operation !== "generate")
|
|
309
|
+
throw new Error("audio call was refused");
|
|
310
|
+
const request = mediaBindingRequest(parsed.call.input, "computer-1");
|
|
311
|
+
expect(request.path).toBe(
|
|
312
|
+
"/workspace/prints/prints-media_request_abcdefghijklmnopqrstu.mp3",
|
|
313
|
+
);
|
|
314
|
+
expect(request.settings).not.toHaveProperty("references");
|
|
315
|
+
}
|
|
316
|
+
});
|
|
317
|
+
|
|
318
|
+
it("refuses an unlisted model, an unlisted voice and image settings", () => {
|
|
319
|
+
for (const settings of [
|
|
320
|
+
{ model: "elevenlabs/sfx", prompt: "boom" },
|
|
321
|
+
{ model: speechModels[0], prompt: "Hi", voiceId: "nope" },
|
|
322
|
+
{ model: speechModels[0], prompt: "Hi", width: 1024 },
|
|
323
|
+
{ model: music, prompt: "theme", durationSeconds: 601 },
|
|
324
|
+
])
|
|
325
|
+
expect(call(settings)).toMatchObject({ kind: "refused" });
|
|
326
|
+
});
|
|
327
|
+
});
|
|
328
|
+
|
|
329
|
+
describe("audio through the durable service", () => {
|
|
330
|
+
it("runs in the background, bills blocks, saves the MP3 and replays", async () => {
|
|
331
|
+
const run = vi.fn(() =>
|
|
332
|
+
Promise.resolve({
|
|
333
|
+
state: "Completed",
|
|
334
|
+
result: { audio: "https://results.example/voice.mp3" },
|
|
335
|
+
}),
|
|
336
|
+
);
|
|
337
|
+
const ai: MediaAiPort = { run };
|
|
338
|
+
const fetchResult: typeof fetch = () => Promise.resolve(new Response(mp3));
|
|
339
|
+
const provider: MediaProvider = (selection, references, signal, format) =>
|
|
340
|
+
generate(
|
|
341
|
+
ai,
|
|
342
|
+
selection,
|
|
343
|
+
references,
|
|
344
|
+
signal,
|
|
345
|
+
undefined,
|
|
346
|
+
fetchResult,
|
|
347
|
+
format,
|
|
348
|
+
);
|
|
349
|
+
const fixture = mediaOperationFixture();
|
|
350
|
+
const admit = vi.fn(({ units }: { units: number }) =>
|
|
351
|
+
Promise.resolve({ priceMilliunits: units * 100 }),
|
|
352
|
+
);
|
|
353
|
+
const settle = vi.fn(() => Promise.resolve());
|
|
354
|
+
const writes: Uint8Array[] = [];
|
|
355
|
+
try {
|
|
356
|
+
const owner = new MediaOperationOwner(
|
|
357
|
+
fixture.context,
|
|
358
|
+
{ APP_ARTIFACTS: fixture.bucket },
|
|
359
|
+
() => provider,
|
|
360
|
+
);
|
|
361
|
+
const service = createMediaService({
|
|
362
|
+
scope: {
|
|
363
|
+
actorId: "actor-audio",
|
|
364
|
+
namespace: "team-audio",
|
|
365
|
+
owner: "installation-audio",
|
|
366
|
+
destinationId: "computer-audio",
|
|
367
|
+
},
|
|
368
|
+
operations: { getByName: () => owner },
|
|
369
|
+
provider,
|
|
370
|
+
metering: { admit, settle },
|
|
371
|
+
refusalMessages: {
|
|
372
|
+
insufficient_credits: "refill",
|
|
373
|
+
denied: "denied",
|
|
374
|
+
daily_limit_reached: "daily limit",
|
|
375
|
+
},
|
|
376
|
+
destination: {
|
|
377
|
+
authorize: () => Promise.resolve(),
|
|
378
|
+
remove: () => Promise.resolve("absent" as const),
|
|
379
|
+
write: (_path, bytes) => {
|
|
380
|
+
writes.push(bytes);
|
|
381
|
+
return Promise.resolve();
|
|
382
|
+
},
|
|
383
|
+
},
|
|
384
|
+
});
|
|
385
|
+
const request = {
|
|
386
|
+
method: "POST",
|
|
387
|
+
headers: {
|
|
388
|
+
"Content-Type": "application/json",
|
|
389
|
+
"X-Request-Id": "audio-speech",
|
|
390
|
+
},
|
|
391
|
+
body: JSON.stringify({
|
|
392
|
+
path: "generated/fern.mp3",
|
|
393
|
+
settings: {
|
|
394
|
+
model: speechModels[0],
|
|
395
|
+
prompt: "x".repeat(150),
|
|
396
|
+
voiceId: voice,
|
|
397
|
+
},
|
|
398
|
+
}),
|
|
399
|
+
};
|
|
400
|
+
expect((await service.request("/generate", request)).status).toBe(202);
|
|
401
|
+
await owner.alarm();
|
|
402
|
+
const done = await service.request("/generate", request);
|
|
403
|
+
expect(done.status).toBe(200);
|
|
404
|
+
expect(await done.json()).toMatchObject({
|
|
405
|
+
format: "mp3",
|
|
406
|
+
path: "generated/fern.mp3",
|
|
407
|
+
model: speechModels[0],
|
|
408
|
+
bytes: mp3.byteLength,
|
|
409
|
+
});
|
|
410
|
+
const replay = await service.request("/generate", request);
|
|
411
|
+
expect(replay.status).toBe(200);
|
|
412
|
+
expect(run).toHaveBeenCalledTimes(1);
|
|
413
|
+
expect(writes).toEqual([mp3]);
|
|
414
|
+
expect(admit).toHaveBeenCalledWith(
|
|
415
|
+
expect.objectContaining({
|
|
416
|
+
unit: "audio_character_block",
|
|
417
|
+
units: 2,
|
|
418
|
+
providerCostMilliunits: 1_500,
|
|
419
|
+
}),
|
|
420
|
+
);
|
|
421
|
+
expect(settle).toHaveBeenCalledWith(
|
|
422
|
+
expect.objectContaining({ units: 2 }),
|
|
423
|
+
);
|
|
424
|
+
} finally {
|
|
425
|
+
fixture.close();
|
|
426
|
+
}
|
|
427
|
+
});
|
|
428
|
+
});
|