@fungi.computer/darkroom 0.11.11 → 0.11.13

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.
Files changed (90) hide show
  1. package/README.md +13 -0
  2. package/examples/standalone/README.md +52 -0
  3. package/examples/standalone/worker.ts +87 -0
  4. package/examples/standalone/wrangler.jsonc +26 -0
  5. package/package.json +8 -2
  6. package/src/app-media-contracts.ts +142 -0
  7. package/src/audio-providers/elevenlabs.ts +108 -0
  8. package/src/audio-reference-types.ts +47 -0
  9. package/src/audio-references.ts +107 -0
  10. package/src/browser-failure.ts +73 -0
  11. package/src/browser.ts +7 -0
  12. package/src/cloudflare/provider-reason.ts +89 -0
  13. package/src/cloudflare/provider.ts +405 -0
  14. package/src/cloudflare/r2-destination.ts +130 -0
  15. package/src/cloudflare/reference-images.ts +193 -0
  16. package/src/cloudflare.ts +38 -0
  17. package/src/cost-estimate.ts +129 -0
  18. package/src/daily-media-meter.ts +163 -0
  19. package/src/effect.ts +2 -0
  20. package/src/execution-error.ts +98 -0
  21. package/src/failure.ts +13 -0
  22. package/src/gateway-models.ts +304 -0
  23. package/src/gateway-wire.ts +36 -0
  24. package/src/index.ts +1454 -0
  25. package/src/media-binding.ts +260 -0
  26. package/src/media-content-type.ts +60 -0
  27. package/src/media-generation.ts +171 -0
  28. package/src/media-operation-contract.ts +173 -0
  29. package/src/media-operation-do.ts +257 -0
  30. package/src/media-operation-owner.ts +1786 -0
  31. package/src/media-operation-storage.ts +110 -0
  32. package/src/media-operation.ts +454 -0
  33. package/src/media-path.ts +8 -0
  34. package/src/media-quote.ts +34 -0
  35. package/src/media-run-lifetime.ts +5 -0
  36. package/src/media-written.ts +38 -0
  37. package/src/model-catalog.ts +1574 -0
  38. package/src/neurons.ts +6 -0
  39. package/src/node-webpmux.d.ts +12 -0
  40. package/src/provenance-bytes.ts +22 -0
  41. package/src/provenance-export.ts +126 -0
  42. package/src/provenance-jpeg.ts +83 -0
  43. package/src/provenance-png.ts +26 -0
  44. package/src/provenance-signed.ts +7 -0
  45. package/src/provenance-xmp.ts +57 -0
  46. package/src/provenance.ts +87 -0
  47. package/src/reference-image-size.ts +67 -0
  48. package/src/reference-read.ts +50 -0
  49. package/src/server.ts +711 -0
  50. package/src/video-providers/index.ts +18 -0
  51. package/src/video-providers/minimax.ts +96 -0
  52. package/src/video-providers/reference-encoding.ts +32 -0
  53. package/src/video-providers/types.ts +47 -0
  54. package/src/video-providers/unified.ts +68 -0
  55. package/test/audio-models.test.ts +428 -0
  56. package/test/audio-references.test.ts +428 -0
  57. package/test/custom-catalogue.test.ts +257 -0
  58. package/test/daily-media-meter.test.ts +287 -0
  59. package/test/failure.test.ts +190 -0
  60. package/test/fixtures/cloudflare-workers.fixture.ts +10 -0
  61. package/test/fixtures/media-operation.fixture.ts +134 -0
  62. package/test/fixtures/media-team-prompts.ts +7 -0
  63. package/test/fixtures/native-sqlite.fixture.ts +40 -0
  64. package/test/gateway-models.test.ts +712 -0
  65. package/test/media-operation-do.test.ts +1565 -0
  66. package/test/media-quote.test.ts +81 -0
  67. package/test/media-retention.test.ts +597 -0
  68. package/test/media-service.test.ts +549 -0
  69. package/test/media-team-prompts.test.ts +92 -0
  70. package/test/model-facts.test.ts +126 -0
  71. package/test/prompt-limit.test.ts +53 -0
  72. package/test/provenance-export.test.ts +144 -0
  73. package/test/provenance-images.fixture.mjs +17 -0
  74. package/test/provenance.test.ts +179 -0
  75. package/test/provider-gateway.test.ts +114 -0
  76. package/test/provider-reasons.test.ts +133 -0
  77. package/test/r2-destination.test.ts +166 -0
  78. package/test/reference-image-size.test.ts +73 -0
  79. package/test/reference-images-billing.test.ts +40 -0
  80. package/test/reference-images.test.ts +399 -0
  81. package/test/standalone.cloudflare.test.mjs +298 -0
  82. package/test/standalone.worker.mjs +70 -0
  83. package/test/transform-models.test.ts +400 -0
  84. package/test/video-capabilities.test.ts +160 -0
  85. package/test/video-contract.test.ts +533 -0
  86. package/test/video-failure-lifecycle.test.ts +177 -0
  87. package/test/video-provider.test.ts +136 -0
  88. package/test/video-wire.test.ts +251 -0
  89. package/vitest.cloudflare.config.ts +22 -0
  90. package/vitest.node.config.ts +14 -0
@@ -0,0 +1,428 @@
1
+ import { describe, expect, it, vi } from "vitest";
2
+ import {
3
+ getMediaModel,
4
+ listMediaModels,
5
+ mediaVideoModelIdSchema,
6
+ validateMediaGenerationSettings,
7
+ validateMediaVideoSelection,
8
+ MediaSettingsError,
9
+ type MediaGenerationSettings,
10
+ } from "../src/index.js";
11
+ import { resolveMediaAudioReferences } from "../src/audio-references.js";
12
+ import { gatewayInput } 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 { mediaModelsSchema } from "../src/app-media-contracts.js";
19
+ import {
20
+ mediaBindingRequest,
21
+ parseMediaBindingCall,
22
+ } from "../src/media-binding.js";
23
+
24
+ /** A silent 8 kHz mono 8-bit PCM WAV of `seconds` seconds: test fixture bytes, not a parser. */
25
+ function wav(seconds: number): Uint8Array {
26
+ const rate = 8_000;
27
+ const data = Math.round(seconds * rate);
28
+ const bytes = new Uint8Array(44 + data);
29
+ const view = new DataView(bytes.buffer);
30
+ const text = (offset: number, value: string) => {
31
+ for (let index = 0; index < value.length; index++)
32
+ bytes[offset + index] = value.charCodeAt(index);
33
+ };
34
+ text(0, "RIFF");
35
+ view.setUint32(4, 36 + data, true);
36
+ text(8, "WAVE");
37
+ text(12, "fmt ");
38
+ view.setUint32(16, 16, true);
39
+ view.setUint16(20, 1, true);
40
+ view.setUint16(22, 1, true);
41
+ view.setUint32(24, rate, true);
42
+ view.setUint32(28, rate, true);
43
+ view.setUint16(32, 1, true);
44
+ view.setUint16(34, 8, true);
45
+ text(36, "data");
46
+ view.setUint32(40, data, true);
47
+ bytes.fill(128, 44);
48
+ return bytes;
49
+ }
50
+ const base64 = (bytes: Uint8Array) => btoa(String.fromCharCode(...bytes));
51
+
52
+ const seedance25 = "bytedance/seedance-2.5";
53
+ /** Validated video settings for any video model, with optional hydrated audio clips. */
54
+ const video = (
55
+ model: string,
56
+ paths?: readonly string[],
57
+ ): MediaGenerationSettings =>
58
+ validateMediaGenerationSettings({
59
+ ...validateMediaVideoSelection({
60
+ model: mediaVideoModelIdSchema.parse(model),
61
+ prompt: "a fern",
62
+ }),
63
+ references: undefined,
64
+ audioReferences: paths?.map((path) => ({ computerId: "pictures", path })),
65
+ });
66
+ const withAudio = (paths: readonly string[]) => video(seedance25, paths);
67
+ const readerOf = (clips: Record<string, Uint8Array>) => ({
68
+ read: vi.fn((reference: { path: string }) => {
69
+ const bytes = clips[reference.path];
70
+ if (bytes === undefined) throw new Error("missing clip");
71
+ return Promise.resolve(bytes);
72
+ }),
73
+ });
74
+
75
+ describe("reference audio admission", () => {
76
+ it.each([
77
+ "bytedance/seedance-2.0",
78
+ "bytedance/seedance-2.0-fast",
79
+ "bytedance/seedance-2.0-mini",
80
+ "google/veo-3.1",
81
+ "google/veo-3.1-fast",
82
+ "minimax/h3-max",
83
+ ])("refuses audio references on %s, which declares none", (model) => {
84
+ expect(getMediaModel(model)?.video?.audioReferences).toBeNull();
85
+ expect(() => video(model, ["/a.wav"])).toThrow(
86
+ "does not take audio references",
87
+ );
88
+ });
89
+
90
+ it("refuses audio references on an image or audio model", () => {
91
+ expect(() =>
92
+ validateMediaGenerationSettings({
93
+ model: "openai/gpt-image-2",
94
+ prompt: "x",
95
+ width: 1024,
96
+ height: 1024,
97
+ audioReferences: [{ computerId: "c", path: "/a.wav" }],
98
+ }),
99
+ ).toThrow("does not take audio references");
100
+ expect(() =>
101
+ validateMediaGenerationSettings({
102
+ model: "elevenlabs/music-v2",
103
+ prompt: "x",
104
+ audioReferences: [{ computerId: "c", path: "/a.wav" }],
105
+ }),
106
+ ).toThrow("takes only a prompt");
107
+ });
108
+
109
+ it("admits up to the model's ten clips and refuses an eleventh before anything is read", () => {
110
+ expect(
111
+ withAudio(
112
+ Array.from({ length: 10 }, (_, index) => `/${String(index)}.wav`),
113
+ ).audioReferences,
114
+ ).toHaveLength(10);
115
+ expect(() =>
116
+ validateMediaVideoSelection({
117
+ model: seedance25,
118
+ prompt: "a fern",
119
+ audioReferences: Array.from({ length: 11 }, (_, index) => ({
120
+ path: `/${String(index)}.wav`,
121
+ })),
122
+ }),
123
+ ).toThrow(MediaSettingsError);
124
+ });
125
+ });
126
+
127
+ describe("reference audio budget", () => {
128
+ it("reads each clip's duration with the parser and accepts exactly 30 seconds", async () => {
129
+ const reader = readerOf({
130
+ "/a.wav": wav(10),
131
+ "/b.wav": wav(10),
132
+ "/c.wav": wav(10),
133
+ });
134
+ const clips = await resolveMediaAudioReferences(
135
+ withAudio(["/a.wav", "/b.wav", "/c.wav"]),
136
+ reader,
137
+ );
138
+ expect(clips.map((clip) => clip.durationSeconds)).toEqual([10, 10, 10]);
139
+ expect(clips.every((clip) => clip.mimeType === "audio/wav")).toBe(true);
140
+ });
141
+
142
+ it("refuses a total over 30 seconds instead of dropping a clip", async () => {
143
+ await expect(
144
+ resolveMediaAudioReferences(
145
+ withAudio(["/a.wav", "/b.wav"]),
146
+ readerOf({ "/a.wav": wav(15), "/b.wav": wav(15.5) }),
147
+ ),
148
+ ).rejects.toThrow("total 30.5 seconds; the limit is 30");
149
+ });
150
+
151
+ it("refuses bytes that are not audio, and an empty file", async () => {
152
+ await expect(
153
+ resolveMediaAudioReferences(
154
+ withAudio(["/a.wav"]),
155
+ readerOf({ "/a.wav": new TextEncoder().encode("not audio at all") }),
156
+ ),
157
+ ).rejects.toBeInstanceOf(MediaSettingsError);
158
+ await expect(
159
+ resolveMediaAudioReferences(
160
+ withAudio(["/a.wav"]),
161
+ readerOf({ "/a.wav": new Uint8Array() }),
162
+ ),
163
+ ).rejects.toThrow("unavailable or exceeds");
164
+ });
165
+
166
+ it("returns nothing when no audio reference is selected", async () => {
167
+ const reader = readerOf({});
168
+ await expect(
169
+ resolveMediaAudioReferences(video(seedance25), reader),
170
+ ).resolves.toEqual([]);
171
+ expect(reader.read).not.toHaveBeenCalled();
172
+ });
173
+ });
174
+
175
+ describe("Seedance 2.5 reference_audios", () => {
176
+ it("sends data:audio URIs of the exact bytes and nothing else new", async () => {
177
+ const clip = wav(2);
178
+ const settings = withAudio(["/a.wav"]);
179
+ const clips = await resolveMediaAudioReferences(
180
+ settings,
181
+ readerOf({ "/a.wav": clip }),
182
+ );
183
+ const body = gatewayInput(settings, [], "png", clips);
184
+ expect(body).toMatchObject({
185
+ prompt: "a fern",
186
+ reference_audios: [`data:audio/wav;base64,${base64(clip)}`],
187
+ });
188
+ expect(Object.keys(body).sort()).toEqual(
189
+ [
190
+ "aspect_ratio",
191
+ "duration",
192
+ "generate_audio",
193
+ "prompt",
194
+ "reference_audios",
195
+ "resolution",
196
+ ].sort(),
197
+ );
198
+ expect(gatewayInput(video(seedance25))).not.toHaveProperty(
199
+ "reference_audios",
200
+ );
201
+ });
202
+
203
+ it("refuses resolved clips that do not match the admitted references", () => {
204
+ expect(() => gatewayInput(withAudio(["/a.wav"]), [], "png", [])).toThrow(
205
+ "must match every admitted audio reference",
206
+ );
207
+ });
208
+ });
209
+
210
+ describe("reference audio through the MEDIA binding and catalog", () => {
211
+ it("attaches the selected Computer to each clip", () => {
212
+ const parsed = parseMediaBindingCall({
213
+ operation: "generate",
214
+ input: {
215
+ kind: "video",
216
+ requestId: "media_request_abcdefghijklmnopqrstu",
217
+ libraryPath: "/workspace/prints",
218
+ settings: {
219
+ model: seedance25,
220
+ prompt: "a fern",
221
+ audioReferences: [{ path: "/workspace/prints/a.wav" }],
222
+ },
223
+ },
224
+ });
225
+ if (parsed.kind !== "parsed" || parsed.call.operation !== "generate")
226
+ throw new Error("video call was refused");
227
+ expect(
228
+ mediaBindingRequest(parsed.call.input, "computer-1").settings
229
+ .audioReferences,
230
+ ).toEqual([{ path: "/workspace/prints/a.wav", computerId: "computer-1" }]);
231
+ });
232
+
233
+ it("lists audioReferences only when the host can read clips", async () => {
234
+ const fixture = mediaOperationFixture();
235
+ try {
236
+ const listed = async (readable: boolean) => {
237
+ const destination = {
238
+ authorize: () => Promise.resolve(),
239
+ remove: () => Promise.resolve("absent" as const),
240
+ write: () => Promise.resolve(),
241
+ readReference: () => Promise.reject(new Error("unused")),
242
+ };
243
+ const service = createMediaService({
244
+ scope: {
245
+ actorId: "a",
246
+ namespace: "n",
247
+ owner: "o",
248
+ destinationId: "d",
249
+ },
250
+ operations: { getByName: () => fixture.owner },
251
+ provider: () => Promise.reject(new Error("unused")),
252
+ metering: "unmetered",
253
+ destination: readable
254
+ ? {
255
+ ...destination,
256
+ readAudioReference: () => Promise.resolve(wav(1)),
257
+ }
258
+ : destination,
259
+ });
260
+ const models = mediaModelsSchema.parse(
261
+ await (await service.request("/models")).json(),
262
+ );
263
+ return models.find((model) => model.id === seedance25)?.video
264
+ ?.audioReferences;
265
+ };
266
+ expect(await listed(true)).toEqual({ max: 10, totalSeconds: 30 });
267
+ expect(await listed(false)).toBeNull();
268
+ } finally {
269
+ fixture.close();
270
+ }
271
+ expect(
272
+ listMediaModels().find((model) => model.id === seedance25)?.video
273
+ ?.audioReferences,
274
+ ).toEqual({ max: 10, totalSeconds: 30 });
275
+ });
276
+ });
277
+
278
+ describe("reference audio through the durable background service", () => {
279
+ it("retains the clips for the alarm, sends them once, and deletes them", async () => {
280
+ const clip = wav(3);
281
+ const run = vi.fn(() =>
282
+ Promise.resolve({
283
+ state: "Completed",
284
+ result: { video: "https://results.example/clip.mp4" },
285
+ }),
286
+ );
287
+ const ai: MediaAiPort = { run };
288
+ const mp4 = Uint8Array.from([
289
+ 0, 0, 0, 0x18, 0x66, 0x74, 0x79, 0x70, 0x69, 0x73, 0x6f, 0x6d, 0, 0, 2, 0,
290
+ 0x69, 0x73, 0x6f, 0x6d, 0x6d, 0x70, 0x34, 0x31,
291
+ ]);
292
+ const provider: MediaProvider = (
293
+ selection,
294
+ references,
295
+ signal,
296
+ format,
297
+ audioReferences,
298
+ ) =>
299
+ generate(
300
+ ai,
301
+ selection,
302
+ references,
303
+ signal,
304
+ undefined,
305
+ () => Promise.resolve(new Response(mp4)),
306
+ format,
307
+ audioReferences,
308
+ );
309
+ const outputs = new Map<string, Uint8Array>();
310
+ const fixture = mediaOperationFixture(":memory:", outputs);
311
+ try {
312
+ const owner = new MediaOperationOwner(
313
+ fixture.context,
314
+ { APP_ARTIFACTS: fixture.bucket },
315
+ () => provider,
316
+ );
317
+ const reads = vi.fn(() => Promise.resolve(clip));
318
+ const service = createMediaService({
319
+ scope: {
320
+ actorId: "actor",
321
+ namespace: "team",
322
+ owner: "installation",
323
+ destinationId: "computer",
324
+ },
325
+ operations: { getByName: () => owner },
326
+ provider,
327
+ metering: "unmetered",
328
+ destination: {
329
+ authorize: () => Promise.resolve(),
330
+ remove: () => Promise.resolve("absent" as const),
331
+ write: () => Promise.resolve(),
332
+ readAudioReference: reads,
333
+ },
334
+ });
335
+ const request = {
336
+ method: "POST",
337
+ headers: {
338
+ "Content-Type": "application/json",
339
+ "X-Request-Id": "audio-reference-video",
340
+ },
341
+ body: JSON.stringify({
342
+ path: "generated/fern.mp4",
343
+ settings: {
344
+ model: seedance25,
345
+ prompt: "a fern",
346
+ width: 1280,
347
+ height: 720,
348
+ durationSeconds: 5,
349
+ audioReferences: [{ computerId: "computer", path: "/a.wav" }],
350
+ },
351
+ }),
352
+ };
353
+ expect((await service.request("/generate", request)).status).toBe(202);
354
+ expect([...outputs.keys()].some((key) => key.includes("audio"))).toBe(
355
+ true,
356
+ );
357
+ await owner.alarm();
358
+ expect((await service.request("/generate", request)).status).toBe(200);
359
+ expect(run).toHaveBeenCalledTimes(1);
360
+ expect(run).toHaveBeenCalledWith(
361
+ seedance25,
362
+ expect.objectContaining({
363
+ reference_audios: [`data:audio/wav;base64,${base64(clip)}`],
364
+ }),
365
+ // SAFETY: asymmetric matcher; vitest checks the real argument is an AbortSignal.
366
+ expect.objectContaining({ signal: expect.any(AbortSignal) as unknown }),
367
+ );
368
+ expect([...outputs.keys()].some((key) => key.includes("audio"))).toBe(
369
+ false,
370
+ );
371
+ } finally {
372
+ fixture.close();
373
+ }
374
+ });
375
+
376
+ it("refuses an over-budget clip set before billing or dispatch", async () => {
377
+ const admit = vi.fn(() => Promise.resolve({ priceMilliunits: 1 }));
378
+ const provider = vi.fn();
379
+ const fixture = mediaOperationFixture();
380
+ try {
381
+ const service = createMediaService({
382
+ scope: {
383
+ actorId: "actor",
384
+ namespace: "team",
385
+ owner: "installation",
386
+ destinationId: "computer",
387
+ },
388
+ operations: { getByName: () => fixture.owner },
389
+ provider,
390
+ metering: { admit, settle: () => Promise.resolve() },
391
+ refusalMessages: {
392
+ insufficient_credits: "refill",
393
+ denied: "denied",
394
+ daily_limit_reached: "daily limit",
395
+ },
396
+ destination: {
397
+ authorize: () => Promise.resolve(),
398
+ remove: () => Promise.resolve("absent" as const),
399
+ write: () => Promise.resolve(),
400
+ readAudioReference: () => Promise.resolve(wav(31)),
401
+ },
402
+ });
403
+ const response = await service.request("/generate", {
404
+ method: "POST",
405
+ headers: {
406
+ "Content-Type": "application/json",
407
+ "X-Request-Id": "audio-reference-over",
408
+ },
409
+ body: JSON.stringify({
410
+ path: "generated/fern.mp4",
411
+ settings: {
412
+ model: seedance25,
413
+ prompt: "a fern",
414
+ width: 1280,
415
+ height: 720,
416
+ durationSeconds: 5,
417
+ audioReferences: [{ computerId: "computer", path: "/a.wav" }],
418
+ },
419
+ }),
420
+ });
421
+ expect(response.status).toBe(400);
422
+ expect(admit).not.toHaveBeenCalled();
423
+ expect(provider).not.toHaveBeenCalled();
424
+ } finally {
425
+ fixture.close();
426
+ }
427
+ });
428
+ });
@@ -0,0 +1,257 @@
1
+ import { describe, expect, it, vi } from "vitest";
2
+ import {
3
+ MediaSettingsError,
4
+ parseMediaCatalogue,
5
+ validateMediaGenerationSettings,
6
+ validateMediaVideoSelection,
7
+ estimateVideoMilliunits,
8
+ type MediaCatalogue,
9
+ } from "../src/index.js";
10
+ import {
11
+ createMediaService,
12
+ generateMedia,
13
+ type MediaServiceHost,
14
+ } from "../src/server.js";
15
+ import { mediaOperationFixture } from "./fixtures/media-operation.fixture.js";
16
+
17
+ const imageEntry = {
18
+ id: "fal-ai/flux/dev",
19
+ label: "FLUX dev (fal.ai)",
20
+ kind: "image",
21
+ tier: "balanced",
22
+ outputFormats: ["png"],
23
+ maxPromptLength: 500,
24
+ input: {
25
+ transport: "json",
26
+ dimensions: "own",
27
+ maxDimension: 1024,
28
+ maxDimensionDocumented: true,
29
+ defaultWidth: 512,
30
+ defaultHeight: 512,
31
+ steps: "steps",
32
+ maxSteps: 12,
33
+ defaultSteps: 6,
34
+ guidance: null,
35
+ referenceField: null,
36
+ maxReferences: 0,
37
+ referenceDimension: null,
38
+ referenceFormat: "png",
39
+ },
40
+ sizes: null,
41
+ video: null,
42
+ };
43
+ const videoEntry = {
44
+ id: "fal-ai/minimax/hailuo-2.3/standard/image-to-video",
45
+ label: "Hailuo 2.3 Standard (fal.ai)",
46
+ kind: "video",
47
+ tier: "draft",
48
+ outputFormats: [],
49
+ maxPromptLength: 2_000,
50
+ input: {
51
+ ...imageEntry.input,
52
+ maxDimension: 1920,
53
+ steps: "fixed",
54
+ maxSteps: null,
55
+ defaultSteps: null,
56
+ guidance: null,
57
+ referenceField: "image_url",
58
+ maxReferences: 1,
59
+ },
60
+ sizes: ["1366x768"],
61
+ video: {
62
+ minSeconds: 6,
63
+ maxSeconds: 10,
64
+ defaultSeconds: 6,
65
+ durations: [6, 10],
66
+ provider: "host",
67
+ formats: [
68
+ {
69
+ resolution: "768p",
70
+ aspectRatio: "16:9",
71
+ width: 1366,
72
+ height: 768,
73
+ },
74
+ ],
75
+ defaultResolution: "768p",
76
+ defaultAspectRatio: "16:9",
77
+ supportsAudio: false,
78
+ defaultGenerateAudio: null,
79
+ referenceRoles: ["first-frame"],
80
+ maxReferenceImages: 0,
81
+ referenceResolutions: [],
82
+ prices: [
83
+ {
84
+ resolution: "768p",
85
+ silentMilliunitsPerSecond: 3_000,
86
+ audioMilliunitsPerSecond: 3_000,
87
+ },
88
+ ],
89
+ },
90
+ };
91
+ const catalogue: MediaCatalogue = parseMediaCatalogue([imageEntry, videoEntry]);
92
+ const gatewayModel = "bytedance/seedance-2.0";
93
+ const customImage = {
94
+ model: imageEntry.id,
95
+ prompt: "a quiet greenhouse",
96
+ width: 512,
97
+ height: 512,
98
+ };
99
+
100
+ describe("provider-owned model catalogue", () => {
101
+ it("accepts a custom provider's model id and applies its defaults", () => {
102
+ expect(
103
+ validateMediaGenerationSettings(customImage, catalogue),
104
+ ).toMatchObject({ model: imageEntry.id, steps: 6 });
105
+ expect(
106
+ validateMediaVideoSelection(
107
+ { model: videoEntry.id, prompt: "x" },
108
+ catalogue,
109
+ ),
110
+ ).toMatchObject({
111
+ model: videoEntry.id,
112
+ width: 1366,
113
+ durationSeconds: 6,
114
+ resolution: "768p",
115
+ });
116
+ expect(
117
+ estimateVideoMilliunits(
118
+ validateMediaVideoSelection(
119
+ { model: videoEntry.id, prompt: "x", durationSeconds: 10 },
120
+ catalogue,
121
+ ),
122
+ catalogue,
123
+ ),
124
+ ).toBe(30_000);
125
+ });
126
+
127
+ it("refuses that model under the built-in provider, and the built-in model under the custom one", () => {
128
+ expect(() => validateMediaGenerationSettings(customImage)).toThrow(
129
+ MediaSettingsError,
130
+ );
131
+ expect(() =>
132
+ validateMediaVideoSelection({ model: videoEntry.id, prompt: "x" }),
133
+ ).toThrow(MediaSettingsError);
134
+ expect(() =>
135
+ validateMediaGenerationSettings(
136
+ { model: gatewayModel, prompt: "x", width: 1280, height: 720 },
137
+ catalogue,
138
+ ),
139
+ ).toThrow(MediaSettingsError);
140
+ });
141
+
142
+ it("refuses settings outside the custom bounds", () => {
143
+ const refuse = (
144
+ settings: Partial<typeof customImage & { steps: number }>,
145
+ ) => {
146
+ expect(() =>
147
+ validateMediaGenerationSettings(
148
+ { ...customImage, ...settings },
149
+ catalogue,
150
+ ),
151
+ ).toThrow(MediaSettingsError);
152
+ };
153
+ refuse({ steps: 13 });
154
+ refuse({ width: 2048 });
155
+ refuse({ prompt: "x".repeat(501) });
156
+ expect(() =>
157
+ validateMediaVideoSelection(
158
+ { model: videoEntry.id, prompt: "x", durationSeconds: 8 },
159
+ catalogue,
160
+ ),
161
+ ).toThrow(MediaSettingsError);
162
+ });
163
+
164
+ it("treats an omitted guidance key as no guidance", () => {
165
+ const { guidance, ...input } = imageEntry.input;
166
+ expect(guidance).toBeNull();
167
+ const parsed = parseMediaCatalogue([{ ...imageEntry, input }]);
168
+ expect(parsed[0]?.input.guidance).toBeNull();
169
+ });
170
+
171
+ it("refuses catalogues that contradict themselves", () => {
172
+ expect(() => parseMediaCatalogue([])).toThrow(MediaSettingsError);
173
+ expect(() => parseMediaCatalogue([imageEntry, imageEntry])).toThrow(
174
+ /duplicate/u,
175
+ );
176
+ expect(() =>
177
+ parseMediaCatalogue([{ ...imageEntry, kind: "video" }]),
178
+ ).toThrow(/video bounds/u);
179
+ expect(() =>
180
+ parseMediaCatalogue([
181
+ { ...videoEntry, video: { ...videoEntry.video, defaultSeconds: 8 } },
182
+ ]),
183
+ ).toThrow(/durations/u);
184
+ });
185
+
186
+ it("generates through the durable operation with a fake provider and its catalogue", async () => {
187
+ const fixture = mediaOperationFixture(
188
+ ":memory:",
189
+ new Map(),
190
+ undefined,
191
+ "media-operation-custom",
192
+ { catalogue: () => catalogue },
193
+ );
194
+ try {
195
+ const provider = vi.fn(() =>
196
+ Promise.resolve({ bytes: new Uint8Array([1, 2, 3]), format: "png" }),
197
+ );
198
+ const write = vi.fn(() => Promise.resolve());
199
+ const host = {
200
+ scope: {
201
+ actorId: "reader",
202
+ namespace: "studio",
203
+ owner: "composer",
204
+ destinationId: "pictures",
205
+ },
206
+ operations: { getByName: () => fixture.owner },
207
+ provider,
208
+ catalogue,
209
+ estimate: () => 1_000,
210
+ metering: "unmetered",
211
+ destination: {
212
+ authorize: () => Promise.resolve(),
213
+ write,
214
+ remove: () => Promise.resolve("absent" as const),
215
+ },
216
+ } satisfies MediaServiceHost;
217
+ const models = await createMediaService(host).request("/models");
218
+ const listed = await models.json<{ id: string; billingUnit: string }[]>();
219
+ expect(listed.map(({ id }) => id)).toEqual([
220
+ imageEntry.id,
221
+ videoEntry.id,
222
+ ]);
223
+ expect(listed.map(({ billingUnit }) => billingUnit)).toEqual([
224
+ "image",
225
+ "video_second",
226
+ ]);
227
+ await expect(
228
+ generateMedia(host, {
229
+ requestId: "custom-model",
230
+ path: "fern.png",
231
+ settings: customImage,
232
+ }),
233
+ ).resolves.toMatchObject({
234
+ kind: "succeeded",
235
+ model: imageEntry.id,
236
+ costMilliunits: 1_000,
237
+ });
238
+ expect(provider).toHaveBeenCalledTimes(1);
239
+ expect(write).toHaveBeenCalledTimes(1);
240
+ await expect(
241
+ generateMedia(host, {
242
+ requestId: "gateway-model",
243
+ path: "clip.mp4",
244
+ settings: {
245
+ model: gatewayModel,
246
+ prompt: "x",
247
+ width: 1280,
248
+ height: 720,
249
+ },
250
+ }),
251
+ ).rejects.toBeInstanceOf(MediaSettingsError);
252
+ expect(provider).toHaveBeenCalledTimes(1);
253
+ } finally {
254
+ fixture.close();
255
+ }
256
+ });
257
+ });