@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
package/src/index.ts
ADDED
|
@@ -0,0 +1,1454 @@
|
|
|
1
|
+
import * as z from "zod";
|
|
2
|
+
import { reportCatchFailure } from "./failure.js";
|
|
3
|
+
import type { MediaAudioReferenceBytes } from "./audio-reference-types.js";
|
|
4
|
+
import { sniffImageFormat } from "./media-content-type.js";
|
|
5
|
+
import { referenceImageSizeIsValid } from "./reference-image-size.js";
|
|
6
|
+
import {
|
|
7
|
+
getGatewayModel,
|
|
8
|
+
getMediaModel,
|
|
9
|
+
mediaAudioModelIdSchema,
|
|
10
|
+
MAX_REFERENCE_COUNT,
|
|
11
|
+
MediaSettingsError,
|
|
12
|
+
mediaModels,
|
|
13
|
+
mediaVideoModelIdSchema,
|
|
14
|
+
mediaVideoResolutionSchema,
|
|
15
|
+
mediaVideoAspectRatioSchema,
|
|
16
|
+
mediaVideoReferenceRoleSchema,
|
|
17
|
+
MAX_MEDIA_PROMPT_LENGTH,
|
|
18
|
+
transformMilliunits,
|
|
19
|
+
type MediaAudioModel,
|
|
20
|
+
type MediaCatalogueModel,
|
|
21
|
+
type MediaModel,
|
|
22
|
+
type MediaTransform,
|
|
23
|
+
type MediaVideoReferenceRole,
|
|
24
|
+
type MediaCatalogue,
|
|
25
|
+
type MediaVideoResolution,
|
|
26
|
+
type MediaVideoAspectRatio,
|
|
27
|
+
} from "./model-catalog.js";
|
|
28
|
+
|
|
29
|
+
export {
|
|
30
|
+
mediaFailureStageSchema,
|
|
31
|
+
MediaExecutionError,
|
|
32
|
+
MediaSafetyFilterRefusal,
|
|
33
|
+
} from "./execution-error.js";
|
|
34
|
+
|
|
35
|
+
export {
|
|
36
|
+
MAX_AUDIO_REFERENCE_BODY_BYTES,
|
|
37
|
+
MAX_AUDIO_REFERENCE_BYTES,
|
|
38
|
+
} from "./audio-reference-types.js";
|
|
39
|
+
export type {
|
|
40
|
+
AudioReferenceMimeType,
|
|
41
|
+
MediaAudioReferenceBytes,
|
|
42
|
+
} from "./audio-reference-types.js";
|
|
43
|
+
export {
|
|
44
|
+
MAX_MEDIA_PROMPT_LENGTH,
|
|
45
|
+
getMediaModel,
|
|
46
|
+
getGatewayModel,
|
|
47
|
+
MAX_REFERENCE_COUNT,
|
|
48
|
+
listMediaModels,
|
|
49
|
+
mediaCatalogueSchema,
|
|
50
|
+
mediaCatalogueModelSchema,
|
|
51
|
+
parseMediaCatalogue,
|
|
52
|
+
mediaModelInputSchema,
|
|
53
|
+
mediaModelSchema,
|
|
54
|
+
mediaRequestedImageFormatSchema,
|
|
55
|
+
mediaModels,
|
|
56
|
+
mediaModelTierSchema,
|
|
57
|
+
MediaSettingsError,
|
|
58
|
+
mediaVideoModelIdSchema,
|
|
59
|
+
mediaVideoResolutionSchema,
|
|
60
|
+
mediaVideoAspectRatioSchema,
|
|
61
|
+
mediaVideoReferenceRoleSchema,
|
|
62
|
+
mediaVideoFormatSchema,
|
|
63
|
+
mediaVideoSchema,
|
|
64
|
+
mediaAudioModelIdSchema,
|
|
65
|
+
mediaAudioSchema,
|
|
66
|
+
mediaAudioVoiceSchema,
|
|
67
|
+
mediaBillingUnitSchema,
|
|
68
|
+
AUDIO_CHARACTER_BLOCK,
|
|
69
|
+
mediaTransformSchema,
|
|
70
|
+
mediaTransformOperationSchema,
|
|
71
|
+
} from "./model-catalog.js";
|
|
72
|
+
export type {
|
|
73
|
+
MediaTransform,
|
|
74
|
+
MediaTransformOperation,
|
|
75
|
+
MediaCatalogue,
|
|
76
|
+
MediaBillingUnit,
|
|
77
|
+
MediaCatalogueModel,
|
|
78
|
+
MediaModel,
|
|
79
|
+
MediaModelInput,
|
|
80
|
+
MediaModelTier,
|
|
81
|
+
MediaVideoModelId,
|
|
82
|
+
MediaVideoResolution,
|
|
83
|
+
MediaVideoAspectRatio,
|
|
84
|
+
MediaVideoReferenceRole,
|
|
85
|
+
MediaVideoModel,
|
|
86
|
+
MediaVideoFormat,
|
|
87
|
+
MediaAudioModelId,
|
|
88
|
+
MediaAudioModel,
|
|
89
|
+
MediaAudioVoice,
|
|
90
|
+
} from "./model-catalog.js";
|
|
91
|
+
|
|
92
|
+
/** A reference file selected by the host, with its destination identity and path. */
|
|
93
|
+
export type MediaReference = Readonly<{
|
|
94
|
+
/** Host-admitted destination or reference identity. */
|
|
95
|
+
computerId: string;
|
|
96
|
+
/** Fixed destination or reference file path. */
|
|
97
|
+
path: string;
|
|
98
|
+
/** Video reference role; a single untagged host reference means first frame. */
|
|
99
|
+
role?: MediaVideoReferenceRole;
|
|
100
|
+
}>;
|
|
101
|
+
/** Supported still-image encodings. */
|
|
102
|
+
export type ImageFormat = "png" | "jpeg" | "gif" | "webp";
|
|
103
|
+
/** MIME type corresponding to a supported image encoding. */
|
|
104
|
+
export type ImageMimeType = `image/${ImageFormat}`;
|
|
105
|
+
/** A saved generation: an image, an MP4 from a video model, or an MP3 from an audio model. */
|
|
106
|
+
export type MediaOutputFormat = ImageFormat | "mp4" | "mp3";
|
|
107
|
+
/** Decoded reference bytes and the dimensions sent to the provider. */
|
|
108
|
+
export type MediaReferenceBytes = Readonly<{
|
|
109
|
+
/** Decoded reference image bytes. */
|
|
110
|
+
bytes: Uint8Array;
|
|
111
|
+
/** Actual reference image encoding. */
|
|
112
|
+
format: ImageFormat;
|
|
113
|
+
/** Reference width in pixels. */
|
|
114
|
+
width: number;
|
|
115
|
+
/** Reference height in pixels. */
|
|
116
|
+
height: number;
|
|
117
|
+
/** Optional filename sent with multipart input. */
|
|
118
|
+
filename?: string;
|
|
119
|
+
}>;
|
|
120
|
+
/** Normalized model settings, including bounded host-selected references. */
|
|
121
|
+
export type MediaGenerationSettings = Readonly<{
|
|
122
|
+
/** Catalog model identifier. */
|
|
123
|
+
model: string;
|
|
124
|
+
/** Trimmed generation prompt. */
|
|
125
|
+
prompt: string;
|
|
126
|
+
/** Requested image width or nominal video resolution/aspect selector; absent for audio. */
|
|
127
|
+
width?: number;
|
|
128
|
+
/** Requested image height or nominal video resolution/aspect selector; absent for audio. */
|
|
129
|
+
height?: number;
|
|
130
|
+
/** Model-specific inference steps. */
|
|
131
|
+
steps?: number;
|
|
132
|
+
/** Prompt guidance for models that take it; the catalog default when omitted. */
|
|
133
|
+
guidance?: number;
|
|
134
|
+
/** Video and music models only: output length in whole seconds. */
|
|
135
|
+
durationSeconds?: number;
|
|
136
|
+
/** Upscale only: the output size in megapixels. */
|
|
137
|
+
targetMegapixels?: number;
|
|
138
|
+
/** Speech models only: the catalog voice that reads the prompt. */
|
|
139
|
+
voiceId?: string;
|
|
140
|
+
/** Video resolution selector, normalized from the catalog. */
|
|
141
|
+
resolution?: MediaVideoResolution;
|
|
142
|
+
/** Requested video aspect; a first image may override it upstream. */
|
|
143
|
+
aspectRatio?: MediaVideoAspectRatio;
|
|
144
|
+
/** Audio selection; omitted for Seedance when its default is undocumented. */
|
|
145
|
+
generateAudio?: boolean;
|
|
146
|
+
/** Host-authorized reference files. */
|
|
147
|
+
references?: readonly MediaReference[];
|
|
148
|
+
/** Host-authorized reference audio clips; video models declaring `audioReferences` only. */
|
|
149
|
+
audioReferences?: readonly MediaReference[];
|
|
150
|
+
}>;
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* One Media provider call: validated settings and reference bytes in, output
|
|
154
|
+
* bytes out. Hosts may bind it to Workers AI or their own transport.
|
|
155
|
+
*/
|
|
156
|
+
export type MediaProvider = (
|
|
157
|
+
settings: MediaGenerationSettings,
|
|
158
|
+
references: readonly MediaReferenceBytes[],
|
|
159
|
+
signal?: AbortSignal,
|
|
160
|
+
outputFormat?: "png" | "jpeg" | "webp",
|
|
161
|
+
audioReferences?: readonly MediaAudioReferenceBytes[],
|
|
162
|
+
) => Promise<
|
|
163
|
+
Readonly<{
|
|
164
|
+
/** Generated output bytes. */
|
|
165
|
+
bytes: Uint8Array;
|
|
166
|
+
/** Actual output encoding. */
|
|
167
|
+
format: string;
|
|
168
|
+
}>
|
|
169
|
+
>;
|
|
170
|
+
|
|
171
|
+
/** A decoded reference image, fitted for the selected model. */
|
|
172
|
+
export type FittedReferenceImage = Omit<MediaReferenceBytes, "filename">;
|
|
173
|
+
/** Decode and fit a reference: image long edge within the model's catalog dimension, video short edge ≥320. */
|
|
174
|
+
export type ReferenceImageFitter = (
|
|
175
|
+
bytes: Uint8Array,
|
|
176
|
+
model: string,
|
|
177
|
+
) => Promise<FittedReferenceImage>;
|
|
178
|
+
|
|
179
|
+
/** The long-edge bounds a viewer may ask for when fitting an image to look at. */
|
|
180
|
+
export const MIN_VIEW_DIMENSION = 256;
|
|
181
|
+
/** Maximum long-edge size accepted by an image viewer, in pixels. */
|
|
182
|
+
export const MAX_VIEW_DIMENSION = 512;
|
|
183
|
+
/** Decode a viewer long-edge size within the supported pixel bounds. */
|
|
184
|
+
export const viewDimensionSchema = z.lazy(() =>
|
|
185
|
+
z.number().int().min(MIN_VIEW_DIMENSION).max(MAX_VIEW_DIMENSION),
|
|
186
|
+
);
|
|
187
|
+
/**
|
|
188
|
+
* Decode one image and re-encode it for a model to look at: scaled within
|
|
189
|
+
* `maxDimension` on the long edge (bounded by {@link viewDimensionSchema}) as
|
|
190
|
+
* a lossy JPEG, so a viewer can step the dimension down to meet a byte budget.
|
|
191
|
+
*/
|
|
192
|
+
export type ImageViewFitter = (
|
|
193
|
+
bytes: Uint8Array,
|
|
194
|
+
maxDimension: number,
|
|
195
|
+
) => Promise<FittedReferenceImage>;
|
|
196
|
+
|
|
197
|
+
/** Reference images in one video request: every verified video model's catalog value. */
|
|
198
|
+
const MAX_VIDEO_REFERENCE_COUNT = 4;
|
|
199
|
+
/** Maximum decoded bytes per reference image. */
|
|
200
|
+
export const MAX_REFERENCE_BYTES = 8 * 1024 * 1024;
|
|
201
|
+
/**
|
|
202
|
+
* Maximum decoded bytes across every reference of one request. Base64 adds a
|
|
203
|
+
* third, so 24 MiB stays near 32 MiB on the wire, under OpenAI's 50 MB cap on
|
|
204
|
+
* one image-edit request.
|
|
205
|
+
* https://platform.openai.com/docs/api-reference/images/createEdit
|
|
206
|
+
*/
|
|
207
|
+
export const MAX_REFERENCE_BODY_BYTES = 24 * 1024 * 1024;
|
|
208
|
+
/** Maximum retained still-image output bytes. */
|
|
209
|
+
export const MAX_OUTPUT_BYTES = 32 * 1024 * 1024;
|
|
210
|
+
|
|
211
|
+
const requiredString = (value: string, name: string): string => {
|
|
212
|
+
const trimmed = value.trim();
|
|
213
|
+
if (trimmed.length === 0)
|
|
214
|
+
throw new MediaSettingsError(`${name} must not be blank`);
|
|
215
|
+
return trimmed;
|
|
216
|
+
};
|
|
217
|
+
const boundedInteger = (
|
|
218
|
+
value: number,
|
|
219
|
+
name: string,
|
|
220
|
+
minimum: number,
|
|
221
|
+
maximum: number,
|
|
222
|
+
): number => {
|
|
223
|
+
if (!Number.isSafeInteger(value) || value < minimum || value > maximum)
|
|
224
|
+
throw new MediaSettingsError(
|
|
225
|
+
`${name} must be an integer from ${String(minimum)} through ${String(maximum)}`,
|
|
226
|
+
);
|
|
227
|
+
return value;
|
|
228
|
+
};
|
|
229
|
+
const normalizeReference = (value: {
|
|
230
|
+
computerId: string;
|
|
231
|
+
path: string;
|
|
232
|
+
role?: MediaVideoReferenceRole | undefined;
|
|
233
|
+
}): MediaReference => {
|
|
234
|
+
const reference = {
|
|
235
|
+
computerId: requiredString(value.computerId, "reference computerId"),
|
|
236
|
+
path: requiredString(value.path, "reference path"),
|
|
237
|
+
};
|
|
238
|
+
if (value.role === undefined) return reference;
|
|
239
|
+
return { ...reference, role: value.role };
|
|
240
|
+
};
|
|
241
|
+
|
|
242
|
+
/** Schema ceiling for audio reference lists; each model's own `audioReferences.max` is enforced after parsing. */
|
|
243
|
+
export const MAX_AUDIO_REFERENCE_COUNT = 10;
|
|
244
|
+
|
|
245
|
+
/** Structural wire grammar for one Media generation request. */
|
|
246
|
+
export const mediaGenerationSettingsSchema = z
|
|
247
|
+
.object({
|
|
248
|
+
/** Provider catalog model identifier. */
|
|
249
|
+
model: z.string().min(1).max(256),
|
|
250
|
+
/** Generation prompt; each model's `maxPromptLength` is enforced on top of this ceiling. */
|
|
251
|
+
prompt: z.string().min(1).max(MAX_MEDIA_PROMPT_LENGTH),
|
|
252
|
+
/** Requested image width or nominal video selector; absent for audio. */
|
|
253
|
+
width: z.number().int().min(1).max(5_040).optional(),
|
|
254
|
+
/** Requested image height or nominal video selector; absent for audio. */
|
|
255
|
+
height: z.number().int().min(1).max(5_040).optional(),
|
|
256
|
+
/** Model-specific inference step count. */
|
|
257
|
+
steps: z.number().int().optional(),
|
|
258
|
+
/** Prompt guidance; models without a catalog guidance range refuse it. */
|
|
259
|
+
guidance: z.number().optional(),
|
|
260
|
+
/** Requested video or music length in whole seconds. */
|
|
261
|
+
durationSeconds: z.number().int().optional(),
|
|
262
|
+
/** Upscale only: the output size in megapixels, one of the model's offered sizes. */
|
|
263
|
+
targetMegapixels: z.number().int().optional(),
|
|
264
|
+
/** Speech models only: a premade voice from the catalog; the default when omitted. */
|
|
265
|
+
voiceId: z.string().min(1).max(64).optional(),
|
|
266
|
+
/** Video resolution; must match the nominal width/height selector. */
|
|
267
|
+
resolution: mediaVideoResolutionSchema.optional(),
|
|
268
|
+
/** Video aspect; must match the nominal width/height selector. */
|
|
269
|
+
aspectRatio: mediaVideoAspectRatioSchema.optional(),
|
|
270
|
+
/** Video audio selection. */
|
|
271
|
+
generateAudio: z.boolean().optional(),
|
|
272
|
+
/** Host-authorized reference images. */
|
|
273
|
+
references: z
|
|
274
|
+
.array(
|
|
275
|
+
z
|
|
276
|
+
.object({
|
|
277
|
+
/** Host-admitted destination or reference identity. */
|
|
278
|
+
computerId: z.string().min(1).max(256),
|
|
279
|
+
/** Fixed destination or reference file path. */
|
|
280
|
+
path: z.string().min(1).max(4_096),
|
|
281
|
+
/** Video-only reference role. */
|
|
282
|
+
role: mediaVideoReferenceRoleSchema.optional(),
|
|
283
|
+
})
|
|
284
|
+
.strict(),
|
|
285
|
+
)
|
|
286
|
+
.max(MAX_REFERENCE_COUNT)
|
|
287
|
+
.optional(),
|
|
288
|
+
/** Host-authorized reference audio clips; only a model declaring `audioReferences` takes them. */
|
|
289
|
+
audioReferences: z
|
|
290
|
+
.array(
|
|
291
|
+
z
|
|
292
|
+
.object({
|
|
293
|
+
/** Host-admitted destination or reference identity. */
|
|
294
|
+
computerId: z.string().min(1).max(256),
|
|
295
|
+
/** Fixed reference file path. */
|
|
296
|
+
path: z.string().min(1).max(4_096),
|
|
297
|
+
})
|
|
298
|
+
.strict(),
|
|
299
|
+
)
|
|
300
|
+
.max(MAX_AUDIO_REFERENCE_COUNT)
|
|
301
|
+
.optional(),
|
|
302
|
+
})
|
|
303
|
+
.strict();
|
|
304
|
+
/** Caller settings before model defaults and refinements are applied. */
|
|
305
|
+
export type MediaGenerationSettingsInput = z.input<
|
|
306
|
+
typeof mediaGenerationSettingsSchema
|
|
307
|
+
>;
|
|
308
|
+
/** A reference may select another Computer; identity never grants access. */
|
|
309
|
+
export const mediaGenerationSelectionSchema =
|
|
310
|
+
mediaGenerationSettingsSchema.extend({
|
|
311
|
+
/** Host-authorized reference images. */
|
|
312
|
+
references: z
|
|
313
|
+
.array(
|
|
314
|
+
z
|
|
315
|
+
.object({
|
|
316
|
+
/** Omit for the selected Computer; the host authorizes every named Computer. */
|
|
317
|
+
computerId: z.string().min(1).max(256).optional(),
|
|
318
|
+
/** Fixed destination or reference file path. */
|
|
319
|
+
path: z.string().min(1).max(4_096),
|
|
320
|
+
/** Video-only reference role. */
|
|
321
|
+
role: mediaVideoReferenceRoleSchema.optional(),
|
|
322
|
+
})
|
|
323
|
+
.strict(),
|
|
324
|
+
)
|
|
325
|
+
.max(MAX_REFERENCE_COUNT)
|
|
326
|
+
.optional(),
|
|
327
|
+
/** Host-authorized reference audio clips. */
|
|
328
|
+
audioReferences: z
|
|
329
|
+
.array(
|
|
330
|
+
z
|
|
331
|
+
.object({
|
|
332
|
+
/** Omit for the selected Computer; the host authorizes every named Computer. */
|
|
333
|
+
computerId: z.string().min(1).max(256).optional(),
|
|
334
|
+
/** Fixed reference file path. */
|
|
335
|
+
path: z.string().min(1).max(4_096),
|
|
336
|
+
})
|
|
337
|
+
.strict(),
|
|
338
|
+
)
|
|
339
|
+
.max(MAX_AUDIO_REFERENCE_COUNT)
|
|
340
|
+
.optional(),
|
|
341
|
+
});
|
|
342
|
+
/** Generation settings with reference paths resolved by an admitting host. */
|
|
343
|
+
export type MediaGenerationSelection = z.output<
|
|
344
|
+
typeof mediaGenerationSelectionSchema
|
|
345
|
+
>;
|
|
346
|
+
type MutableMediaGenerationSettings<Reference> = {
|
|
347
|
+
model: string;
|
|
348
|
+
prompt: string;
|
|
349
|
+
width?: number;
|
|
350
|
+
height?: number;
|
|
351
|
+
steps?: number;
|
|
352
|
+
guidance?: number;
|
|
353
|
+
durationSeconds?: number;
|
|
354
|
+
/** Upscale output size in megapixels. */
|
|
355
|
+
targetMegapixels?: number;
|
|
356
|
+
voiceId?: string;
|
|
357
|
+
/** Video resolution selector, normalized from the catalog. */
|
|
358
|
+
resolution?: MediaVideoResolution;
|
|
359
|
+
/** Requested video aspect; a first image may override it upstream. */
|
|
360
|
+
aspectRatio?: MediaVideoAspectRatio;
|
|
361
|
+
/** Audio selection; omitted for Seedance when its default is undocumented. */
|
|
362
|
+
generateAudio?: boolean;
|
|
363
|
+
references?: readonly Reference[];
|
|
364
|
+
audioReferences?: readonly Reference[];
|
|
365
|
+
};
|
|
366
|
+
|
|
367
|
+
/** Mutable caller input for already-normalized settings, so they can be validated again. */
|
|
368
|
+
export const mediaSettingsInput = (
|
|
369
|
+
settings: MediaGenerationSettings,
|
|
370
|
+
): MediaGenerationSettingsInput => ({
|
|
371
|
+
...settings,
|
|
372
|
+
references: settings.references?.map((reference) => ({ ...reference })),
|
|
373
|
+
audioReferences: settings.audioReferences?.map((reference) => ({
|
|
374
|
+
...reference,
|
|
375
|
+
})),
|
|
376
|
+
});
|
|
377
|
+
|
|
378
|
+
/**
|
|
379
|
+
* Validate caller settings against `catalogue`, the active provider's model
|
|
380
|
+
* list (the Fungi gateway's by default), and apply that model's defaults.
|
|
381
|
+
*/
|
|
382
|
+
export const validateMediaGenerationSettings = (
|
|
383
|
+
raw: MediaGenerationSettingsInput,
|
|
384
|
+
catalogue: MediaCatalogue = mediaModels,
|
|
385
|
+
): MediaGenerationSettings => {
|
|
386
|
+
const parsed = mediaGenerationSettingsSchema.safeParse(raw);
|
|
387
|
+
if (!parsed.success)
|
|
388
|
+
throw new MediaSettingsError("generation settings are invalid");
|
|
389
|
+
return normalizeGenerationSettings(
|
|
390
|
+
parsed.data,
|
|
391
|
+
normalizeReference,
|
|
392
|
+
catalogue,
|
|
393
|
+
);
|
|
394
|
+
};
|
|
395
|
+
|
|
396
|
+
/** Validate selections without granting Computer authority. */
|
|
397
|
+
export const validateMediaGenerationSelection = (
|
|
398
|
+
raw: z.input<typeof mediaGenerationSelectionSchema>,
|
|
399
|
+
catalogue: MediaCatalogue = mediaModels,
|
|
400
|
+
): Readonly<
|
|
401
|
+
Omit<MediaGenerationSettings, "references" | "audioReferences"> & {
|
|
402
|
+
/** Host-authorized reference images. */
|
|
403
|
+
references?: readonly Readonly<{
|
|
404
|
+
/** Fixed destination or reference file path. */
|
|
405
|
+
path: string;
|
|
406
|
+
/** Optional reference Computer; authorization remains host-owned. */
|
|
407
|
+
computerId?: string;
|
|
408
|
+
/** Video-only reference role. */
|
|
409
|
+
role?: MediaVideoReferenceRole;
|
|
410
|
+
}>[];
|
|
411
|
+
/** Host-authorized reference audio clips. */
|
|
412
|
+
audioReferences?: readonly Readonly<{
|
|
413
|
+
/** Fixed reference file path. */
|
|
414
|
+
path: string;
|
|
415
|
+
/** Optional reference Computer; authorization remains host-owned. */
|
|
416
|
+
computerId?: string;
|
|
417
|
+
}>[];
|
|
418
|
+
}
|
|
419
|
+
> => {
|
|
420
|
+
const parsed = mediaGenerationSelectionSchema.safeParse(raw);
|
|
421
|
+
if (!parsed.success)
|
|
422
|
+
throw new MediaSettingsError("generation settings are invalid");
|
|
423
|
+
return normalizeGenerationSettings(
|
|
424
|
+
parsed.data,
|
|
425
|
+
(reference: {
|
|
426
|
+
path: string;
|
|
427
|
+
computerId?: string | undefined;
|
|
428
|
+
role?: MediaVideoReferenceRole | undefined;
|
|
429
|
+
}) => {
|
|
430
|
+
const path = requiredString(reference.path, "reference path");
|
|
431
|
+
const selection =
|
|
432
|
+
reference.computerId === undefined
|
|
433
|
+
? { path }
|
|
434
|
+
: { path, computerId: reference.computerId };
|
|
435
|
+
if (reference.role === undefined) return selection;
|
|
436
|
+
return { ...selection, role: reference.role };
|
|
437
|
+
},
|
|
438
|
+
catalogue,
|
|
439
|
+
);
|
|
440
|
+
};
|
|
441
|
+
|
|
442
|
+
function normalizeGenerationSettings<
|
|
443
|
+
InputReference extends {
|
|
444
|
+
path: string;
|
|
445
|
+
role?: MediaVideoReferenceRole | undefined;
|
|
446
|
+
},
|
|
447
|
+
Reference extends { path: string; role?: MediaVideoReferenceRole },
|
|
448
|
+
>(
|
|
449
|
+
input: Omit<
|
|
450
|
+
z.output<typeof mediaGenerationSettingsSchema>,
|
|
451
|
+
"references" | "audioReferences"
|
|
452
|
+
> & {
|
|
453
|
+
/** Host-authorized reference images. */
|
|
454
|
+
references?: readonly InputReference[] | undefined;
|
|
455
|
+
/** Host-authorized reference audio clips; they carry no role. */
|
|
456
|
+
audioReferences?: readonly InputReference[] | undefined;
|
|
457
|
+
},
|
|
458
|
+
normalize: (reference: InputReference) => Reference,
|
|
459
|
+
catalogue: MediaCatalogue,
|
|
460
|
+
): Readonly<MutableMediaGenerationSettings<Reference>> {
|
|
461
|
+
const modelId = requiredString(input.model, "model");
|
|
462
|
+
const model = getMediaModel(modelId, catalogue);
|
|
463
|
+
if (model === undefined)
|
|
464
|
+
throw new MediaSettingsError(`unknown Media model "${modelId}"`);
|
|
465
|
+
const prompt = requiredString(input.prompt, "prompt");
|
|
466
|
+
if (prompt.length > model.maxPromptLength)
|
|
467
|
+
throw new MediaSettingsError(
|
|
468
|
+
`${model.id} prompt is ${String(prompt.length)} characters; its limit is ${String(model.maxPromptLength)}`,
|
|
469
|
+
);
|
|
470
|
+
if (model.audio !== null) {
|
|
471
|
+
if (
|
|
472
|
+
input.width !== undefined ||
|
|
473
|
+
input.height !== undefined ||
|
|
474
|
+
input.steps !== undefined ||
|
|
475
|
+
input.guidance !== undefined ||
|
|
476
|
+
input.resolution !== undefined ||
|
|
477
|
+
input.aspectRatio !== undefined ||
|
|
478
|
+
input.generateAudio !== undefined ||
|
|
479
|
+
input.references !== undefined ||
|
|
480
|
+
input.audioReferences !== undefined
|
|
481
|
+
)
|
|
482
|
+
throw new MediaSettingsError(
|
|
483
|
+
`${model.id} takes only a prompt${model.audio.mode === "speech" ? " and a voice" : " and a length"}`,
|
|
484
|
+
);
|
|
485
|
+
return normalizeAudioSettings(model, model.audio, prompt, input);
|
|
486
|
+
}
|
|
487
|
+
if (input.voiceId !== undefined)
|
|
488
|
+
throw new MediaSettingsError(`${model.id} does not take a voice`);
|
|
489
|
+
if (model.transform !== null)
|
|
490
|
+
return normalizeTransformSettings(
|
|
491
|
+
model,
|
|
492
|
+
model.transform,
|
|
493
|
+
prompt,
|
|
494
|
+
input,
|
|
495
|
+
normalize,
|
|
496
|
+
);
|
|
497
|
+
if (input.targetMegapixels !== undefined)
|
|
498
|
+
throw new MediaSettingsError(`${model.id} does not take an output size`);
|
|
499
|
+
if (input.width === undefined || input.height === undefined)
|
|
500
|
+
throw new MediaSettingsError(`${model.id} needs a width and a height`);
|
|
501
|
+
const maximumDimension = model.video === null ? 4_096 : 5_040;
|
|
502
|
+
const width = boundedInteger(input.width, "width", 1, maximumDimension);
|
|
503
|
+
const height = boundedInteger(input.height, "height", 1, maximumDimension);
|
|
504
|
+
if (
|
|
505
|
+
model.input.dimensions === "own" &&
|
|
506
|
+
(width < 256 ||
|
|
507
|
+
height < 256 ||
|
|
508
|
+
width > (model.input.maxDimension ?? 4_096) ||
|
|
509
|
+
height > (model.input.maxDimension ?? 4_096))
|
|
510
|
+
)
|
|
511
|
+
throw new MediaSettingsError(
|
|
512
|
+
`${model.id} accepts dimensions from 256 through ${String(model.input.maxDimension)}`,
|
|
513
|
+
);
|
|
514
|
+
|
|
515
|
+
if (
|
|
516
|
+
model.sizes !== null &&
|
|
517
|
+
!model.sizes.includes(`${String(width)}x${String(height)}`)
|
|
518
|
+
)
|
|
519
|
+
throw new MediaSettingsError(
|
|
520
|
+
`${model.id} accepts only these sizes: ${model.sizes.join(", ")}`,
|
|
521
|
+
);
|
|
522
|
+
let durationSeconds: number | undefined;
|
|
523
|
+
if (model.video === null) {
|
|
524
|
+
if (
|
|
525
|
+
input.resolution !== undefined ||
|
|
526
|
+
input.aspectRatio !== undefined ||
|
|
527
|
+
input.generateAudio !== undefined ||
|
|
528
|
+
input.references?.some((reference) => reference.role !== undefined)
|
|
529
|
+
)
|
|
530
|
+
throw new MediaSettingsError(
|
|
531
|
+
`${model.id} does not take video settings or frame roles`,
|
|
532
|
+
);
|
|
533
|
+
if (input.durationSeconds !== undefined)
|
|
534
|
+
throw new MediaSettingsError(`${model.id} does not take a duration`);
|
|
535
|
+
} else {
|
|
536
|
+
durationSeconds = boundedInteger(
|
|
537
|
+
input.durationSeconds ?? model.video.defaultSeconds,
|
|
538
|
+
"durationSeconds",
|
|
539
|
+
model.video.minSeconds,
|
|
540
|
+
model.video.maxSeconds,
|
|
541
|
+
);
|
|
542
|
+
if (!model.video.durations.includes(durationSeconds))
|
|
543
|
+
throw new MediaSettingsError(
|
|
544
|
+
`${model.id} accepts durationSeconds ${model.video.durations.join(", ")}`,
|
|
545
|
+
);
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
let steps: number | undefined;
|
|
549
|
+
if (input.steps !== undefined && model.input.steps === "fixed")
|
|
550
|
+
throw new MediaSettingsError(
|
|
551
|
+
`${model.id} uses fixed steps and cannot be adjusted`,
|
|
552
|
+
);
|
|
553
|
+
if (input.steps !== undefined) {
|
|
554
|
+
steps = boundedInteger(input.steps, "steps", 1, Number.MAX_SAFE_INTEGER);
|
|
555
|
+
if (model.input.maxSteps !== null && steps > model.input.maxSteps)
|
|
556
|
+
throw new MediaSettingsError(
|
|
557
|
+
`${model.id} accepts at most ${String(model.input.maxSteps)} steps`,
|
|
558
|
+
);
|
|
559
|
+
} else if (
|
|
560
|
+
model.input.steps !== "fixed" &&
|
|
561
|
+
model.input.defaultSteps !== null
|
|
562
|
+
) {
|
|
563
|
+
steps = model.input.defaultSteps;
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
let guidance: number | undefined;
|
|
567
|
+
const range = model.input.guidance;
|
|
568
|
+
if (input.guidance !== undefined && range === null)
|
|
569
|
+
throw new MediaSettingsError(`${model.id} does not take guidance`);
|
|
570
|
+
if (range !== null) {
|
|
571
|
+
guidance = input.guidance ?? range.default;
|
|
572
|
+
if (guidance < range.min || guidance > range.max)
|
|
573
|
+
throw new MediaSettingsError(
|
|
574
|
+
`${model.id} accepts guidance from ${String(range.min)} through ${String(range.max)}`,
|
|
575
|
+
);
|
|
576
|
+
}
|
|
577
|
+
|
|
578
|
+
let references: readonly Reference[] | undefined;
|
|
579
|
+
if (input.references !== undefined) {
|
|
580
|
+
if (input.references.length > model.input.maxReferences)
|
|
581
|
+
throw new MediaSettingsError(
|
|
582
|
+
`${model.id} accepts at most ${String(model.input.maxReferences)} reference images`,
|
|
583
|
+
);
|
|
584
|
+
references = input.references.map(normalize);
|
|
585
|
+
}
|
|
586
|
+
const normalized: MutableMediaGenerationSettings<Reference> = {
|
|
587
|
+
model: model.id,
|
|
588
|
+
prompt,
|
|
589
|
+
width,
|
|
590
|
+
height,
|
|
591
|
+
};
|
|
592
|
+
if (steps !== undefined) normalized.steps = steps;
|
|
593
|
+
if (guidance !== undefined) normalized.guidance = guidance;
|
|
594
|
+
if (durationSeconds !== undefined)
|
|
595
|
+
normalized.durationSeconds = durationSeconds;
|
|
596
|
+
if (model.video !== null) {
|
|
597
|
+
const video = model.video;
|
|
598
|
+
const format = video.formats.find(
|
|
599
|
+
(candidate) => candidate.width === width && candidate.height === height,
|
|
600
|
+
);
|
|
601
|
+
if (format === undefined)
|
|
602
|
+
throw new MediaSettingsError("unsupported video size");
|
|
603
|
+
if (
|
|
604
|
+
(input.resolution !== undefined &&
|
|
605
|
+
input.resolution !== format.resolution) ||
|
|
606
|
+
(input.aspectRatio !== undefined &&
|
|
607
|
+
input.aspectRatio !== format.aspectRatio)
|
|
608
|
+
)
|
|
609
|
+
throw new MediaSettingsError(
|
|
610
|
+
"video selectors must match nominal width and height",
|
|
611
|
+
);
|
|
612
|
+
normalized.resolution = format.resolution;
|
|
613
|
+
normalized.aspectRatio = format.aspectRatio;
|
|
614
|
+
const generateAudio = input.generateAudio ?? video.defaultGenerateAudio;
|
|
615
|
+
if (generateAudio !== null) normalized.generateAudio = generateAudio;
|
|
616
|
+
if (references !== undefined) {
|
|
617
|
+
references = references.map((reference) => ({
|
|
618
|
+
...reference,
|
|
619
|
+
role: reference.role ?? mediaVideoReferenceRoleSchema.enum.first,
|
|
620
|
+
}));
|
|
621
|
+
const roles = references.map((reference) => reference.role);
|
|
622
|
+
const refused = roles.find(
|
|
623
|
+
(role) => role === undefined || !video.referenceRoles.includes(role),
|
|
624
|
+
);
|
|
625
|
+
if (refused !== undefined || roles.includes(undefined))
|
|
626
|
+
throw new MediaSettingsError(
|
|
627
|
+
refused === "last-frame"
|
|
628
|
+
? `${model.label} has no last frame`
|
|
629
|
+
: `${model.label} does not take ${String(refused)} images`,
|
|
630
|
+
);
|
|
631
|
+
const first = roles.filter((role) => role === "first-frame").length;
|
|
632
|
+
const last = roles.filter((role) => role === "last-frame").length;
|
|
633
|
+
const referenceCount = roles.filter(
|
|
634
|
+
(role) => role === "reference",
|
|
635
|
+
).length;
|
|
636
|
+
if (first > 1 || last > 1)
|
|
637
|
+
throw new MediaSettingsError(
|
|
638
|
+
video.referenceRoles.includes("last-frame")
|
|
639
|
+
? `${model.label} takes one first frame and one last frame`
|
|
640
|
+
: `${model.label} takes one first frame`,
|
|
641
|
+
);
|
|
642
|
+
if (last > 0 && first !== 1)
|
|
643
|
+
throw new MediaSettingsError(
|
|
644
|
+
"A last frame needs a first frame as well",
|
|
645
|
+
);
|
|
646
|
+
if (referenceCount > 0 && first + last > 0)
|
|
647
|
+
throw new MediaSettingsError(
|
|
648
|
+
"Frames and references cannot be mixed; use a first/last frame or references",
|
|
649
|
+
);
|
|
650
|
+
if (referenceCount > video.maxReferenceImages)
|
|
651
|
+
throw new MediaSettingsError(
|
|
652
|
+
`${model.label} takes up to ${String(video.maxReferenceImages)} reference images`,
|
|
653
|
+
);
|
|
654
|
+
if (
|
|
655
|
+
referenceCount > 0 &&
|
|
656
|
+
!video.referenceResolutions.includes(format.resolution)
|
|
657
|
+
)
|
|
658
|
+
throw new MediaSettingsError(
|
|
659
|
+
`${model.label} takes reference images only at ${video.referenceResolutions.join(", ")}`,
|
|
660
|
+
);
|
|
661
|
+
}
|
|
662
|
+
}
|
|
663
|
+
if (references !== undefined)
|
|
664
|
+
normalized.references = Object.freeze(references);
|
|
665
|
+
if (input.audioReferences !== undefined && input.audioReferences.length > 0) {
|
|
666
|
+
const limits = model.video?.audioReferences ?? null;
|
|
667
|
+
if (limits === null)
|
|
668
|
+
throw new MediaSettingsError(
|
|
669
|
+
`${model.label} does not take audio references`,
|
|
670
|
+
);
|
|
671
|
+
if (input.audioReferences.length > limits.max)
|
|
672
|
+
throw new MediaSettingsError(
|
|
673
|
+
`${model.label} takes up to ${String(limits.max)} audio references`,
|
|
674
|
+
);
|
|
675
|
+
normalized.audioReferences = Object.freeze(
|
|
676
|
+
input.audioReferences.map(normalize),
|
|
677
|
+
);
|
|
678
|
+
}
|
|
679
|
+
return Object.freeze(normalized);
|
|
680
|
+
}
|
|
681
|
+
|
|
682
|
+
/** Speech takes a catalog voice; music takes a bounded length. Neither takes references. */
|
|
683
|
+
function normalizeAudioSettings<Reference>(
|
|
684
|
+
model: Pick<MediaModel, "id">,
|
|
685
|
+
audio: MediaAudioModel,
|
|
686
|
+
prompt: string,
|
|
687
|
+
input: Pick<MediaGenerationSettingsInput, "durationSeconds" | "voiceId">,
|
|
688
|
+
): Readonly<MutableMediaGenerationSettings<Reference>> {
|
|
689
|
+
const normalized: MutableMediaGenerationSettings<Reference> = {
|
|
690
|
+
model: model.id,
|
|
691
|
+
prompt,
|
|
692
|
+
};
|
|
693
|
+
if (audio.mode === "speech") {
|
|
694
|
+
if (input.durationSeconds !== undefined)
|
|
695
|
+
throw new MediaSettingsError(`${model.id} does not take a duration`);
|
|
696
|
+
const voiceId = input.voiceId ?? audio.defaultVoiceId;
|
|
697
|
+
if (voiceId === null || !audio.voices.some((voice) => voice.id === voiceId))
|
|
698
|
+
throw new MediaSettingsError(
|
|
699
|
+
`${model.id} accepts only these voices: ${audio.voices.map((voice) => voice.id).join(", ")}`,
|
|
700
|
+
);
|
|
701
|
+
normalized.voiceId = voiceId;
|
|
702
|
+
return Object.freeze(normalized);
|
|
703
|
+
}
|
|
704
|
+
if (input.voiceId !== undefined)
|
|
705
|
+
throw new MediaSettingsError(`${model.id} does not take a voice`);
|
|
706
|
+
if (audio.seconds === null)
|
|
707
|
+
throw new MediaSettingsError(`${model.id} is missing its length bounds`);
|
|
708
|
+
normalized.durationSeconds = boundedInteger(
|
|
709
|
+
input.durationSeconds ?? audio.seconds.default,
|
|
710
|
+
"durationSeconds",
|
|
711
|
+
audio.seconds.min,
|
|
712
|
+
audio.seconds.max,
|
|
713
|
+
);
|
|
714
|
+
return Object.freeze(normalized);
|
|
715
|
+
}
|
|
716
|
+
|
|
717
|
+
/** Path-only video reference; the host supplies authority and reads its bytes. */
|
|
718
|
+
export const mediaVideoReferenceSchema = z.lazy(() =>
|
|
719
|
+
z.strictObject({
|
|
720
|
+
/** Selected image path, trimmed and nonblank after validation. */
|
|
721
|
+
path: z.string().min(1).max(4_096),
|
|
722
|
+
/** Explicit first frame, last frame, or reference-image role. */
|
|
723
|
+
role: mediaVideoReferenceRoleSchema,
|
|
724
|
+
}),
|
|
725
|
+
);
|
|
726
|
+
/** One path-only video reference. */
|
|
727
|
+
export type MediaVideoReference = z.output<typeof mediaVideoReferenceSchema>;
|
|
728
|
+
/** Path-only audio reference; the host supplies authority and reads its bytes. */
|
|
729
|
+
export const mediaAudioReferenceSelectionSchema = z.lazy(() =>
|
|
730
|
+
z.strictObject({
|
|
731
|
+
/** Selected audio file path, trimmed and nonblank after validation. */
|
|
732
|
+
path: z.string().min(1).max(4_096),
|
|
733
|
+
}),
|
|
734
|
+
);
|
|
735
|
+
/** One path-only audio reference. */
|
|
736
|
+
export type MediaAudioReferenceSelection = z.output<
|
|
737
|
+
typeof mediaAudioReferenceSelectionSchema
|
|
738
|
+
>;
|
|
739
|
+
/** Neutral video selection; model-specific combinations are checked by validateMediaVideoSelection. */
|
|
740
|
+
export const mediaVideoSelectionSchema = z.lazy(() =>
|
|
741
|
+
z.strictObject({
|
|
742
|
+
/** Verified catalog model identifier. */
|
|
743
|
+
model: mediaVideoModelIdSchema,
|
|
744
|
+
/** Trimmed prompt; the selected model's `maxPromptLength` is enforced on top of this ceiling. */
|
|
745
|
+
prompt: z.string().min(1).max(MAX_MEDIA_PROMPT_LENGTH),
|
|
746
|
+
/** Model-specific resolution, default 720p. */
|
|
747
|
+
resolution: mediaVideoResolutionSchema.optional(),
|
|
748
|
+
/** Model-specific aspect, default 16:9. */
|
|
749
|
+
aspectRatio: mediaVideoAspectRatioSchema.optional(),
|
|
750
|
+
/** Whole seconds; Seedance 2.0 4–12, Seedance 2.5 4–30, Veo exactly 4/6/8, MiniMax H3 Max 5–15. */
|
|
751
|
+
durationSeconds: z.number().int().min(4).max(30).optional(),
|
|
752
|
+
/** Veo defaults true; Seedance omits the provider option when unset;
|
|
753
|
+
* MiniMax H3 Max has no audio field and refuses an explicit choice. */
|
|
754
|
+
generateAudio: z.boolean().optional(),
|
|
755
|
+
/** Up to four references, with provider-specific roles and mode limits. */
|
|
756
|
+
references: z
|
|
757
|
+
.array(mediaVideoReferenceSchema)
|
|
758
|
+
.max(MAX_VIDEO_REFERENCE_COUNT)
|
|
759
|
+
.optional(),
|
|
760
|
+
/** Reference audio clips, for a model declaring `audioReferences` (Seedance 2.5: 10 clips, 30 seconds). */
|
|
761
|
+
audioReferences: z
|
|
762
|
+
.array(mediaAudioReferenceSelectionSchema)
|
|
763
|
+
.max(MAX_AUDIO_REFERENCE_COUNT)
|
|
764
|
+
.optional(),
|
|
765
|
+
}),
|
|
766
|
+
);
|
|
767
|
+
/**
|
|
768
|
+
* The same selection for a host's own catalogue: the model is any id that
|
|
769
|
+
* catalogue lists, checked by `validateMediaVideoSelection`.
|
|
770
|
+
*/
|
|
771
|
+
const catalogueVideoSelectionSchema = mediaVideoSelectionSchema
|
|
772
|
+
.unwrap()
|
|
773
|
+
.extend({ model: z.string().min(1).max(256) });
|
|
774
|
+
/** Caller video selection before defaults and model-specific refinements. */
|
|
775
|
+
export type MediaVideoSelectionInput = z.input<
|
|
776
|
+
typeof mediaVideoSelectionSchema
|
|
777
|
+
>;
|
|
778
|
+
/** Normalized path-only video settings, ready for host-authorized reference hydration. */
|
|
779
|
+
export type MediaVideoSelection = Readonly<{
|
|
780
|
+
/** Catalogue video identifier. */
|
|
781
|
+
model: string;
|
|
782
|
+
/** Trimmed, bounded prompt. */
|
|
783
|
+
prompt: string;
|
|
784
|
+
/** Nominal width selecting resolution/aspect, not decoded MP4 dimensions. */
|
|
785
|
+
width: number;
|
|
786
|
+
/** Nominal height selecting resolution/aspect, not decoded MP4 dimensions. */
|
|
787
|
+
height: number;
|
|
788
|
+
/** Validated provider resolution. */
|
|
789
|
+
resolution: MediaVideoResolution;
|
|
790
|
+
/** Validated requested aspect. */
|
|
791
|
+
aspectRatio: MediaVideoAspectRatio;
|
|
792
|
+
/** Validated output duration in whole seconds. */
|
|
793
|
+
durationSeconds: number;
|
|
794
|
+
/** Explicit audio choice, omitted for Seedance when unset. */
|
|
795
|
+
generateAudio?: boolean;
|
|
796
|
+
/** Normalized paths and required frame/reference roles. */
|
|
797
|
+
references?: readonly Readonly<MediaVideoReference>[];
|
|
798
|
+
/** Normalized reference audio paths. */
|
|
799
|
+
audioReferences?: readonly Readonly<MediaAudioReferenceSelection>[];
|
|
800
|
+
}>;
|
|
801
|
+
type MutableMediaVideoSelection = {
|
|
802
|
+
-readonly [Field in keyof MediaVideoSelection]: MediaVideoSelection[Field];
|
|
803
|
+
};
|
|
804
|
+
|
|
805
|
+
/** Validate supported model/size/duration/reference combinations before authority or billing admission. */
|
|
806
|
+
export function validateMediaVideoSelection(
|
|
807
|
+
raw: z.input<typeof catalogueVideoSelectionSchema>,
|
|
808
|
+
catalogue: MediaCatalogue = mediaModels,
|
|
809
|
+
): MediaVideoSelection {
|
|
810
|
+
const parsed = catalogueVideoSelectionSchema.safeParse(raw);
|
|
811
|
+
if (!parsed.success)
|
|
812
|
+
throw new MediaSettingsError("video selection is invalid");
|
|
813
|
+
const input = parsed.data;
|
|
814
|
+
const model = getMediaModel(input.model, catalogue);
|
|
815
|
+
if (model?.video == null) throw new MediaSettingsError("unknown video model");
|
|
816
|
+
const resolution = input.resolution ?? model.video.defaultResolution;
|
|
817
|
+
const aspectRatio = input.aspectRatio ?? model.video.defaultAspectRatio;
|
|
818
|
+
const format = model.video.formats.find(
|
|
819
|
+
(candidate) =>
|
|
820
|
+
candidate.resolution === resolution &&
|
|
821
|
+
candidate.aspectRatio === aspectRatio,
|
|
822
|
+
);
|
|
823
|
+
if (format === undefined)
|
|
824
|
+
throw new MediaSettingsError(
|
|
825
|
+
`${model.id} does not accept this resolution/aspect`,
|
|
826
|
+
);
|
|
827
|
+
const normalized = validateMediaGenerationSelection(
|
|
828
|
+
{
|
|
829
|
+
...input,
|
|
830
|
+
width: format.width,
|
|
831
|
+
height: format.height,
|
|
832
|
+
},
|
|
833
|
+
catalogue,
|
|
834
|
+
);
|
|
835
|
+
const selection: MutableMediaVideoSelection = {
|
|
836
|
+
...format,
|
|
837
|
+
model: input.model,
|
|
838
|
+
prompt: normalized.prompt,
|
|
839
|
+
durationSeconds: normalized.durationSeconds ?? model.video.defaultSeconds,
|
|
840
|
+
};
|
|
841
|
+
if (normalized.generateAudio !== undefined)
|
|
842
|
+
selection.generateAudio = normalized.generateAudio;
|
|
843
|
+
if (normalized.references !== undefined)
|
|
844
|
+
selection.references = Object.freeze(
|
|
845
|
+
normalized.references.map((reference) =>
|
|
846
|
+
Object.freeze(mediaVideoReferenceSchema.parse(reference)),
|
|
847
|
+
),
|
|
848
|
+
);
|
|
849
|
+
if (normalized.audioReferences !== undefined)
|
|
850
|
+
selection.audioReferences = Object.freeze(
|
|
851
|
+
normalized.audioReferences.map((reference) =>
|
|
852
|
+
Object.freeze(mediaAudioReferenceSelectionSchema.parse(reference)),
|
|
853
|
+
),
|
|
854
|
+
);
|
|
855
|
+
return Object.freeze(selection);
|
|
856
|
+
}
|
|
857
|
+
|
|
858
|
+
/**
|
|
859
|
+
* A source-image operation takes exactly one reference and, for an upscale, one
|
|
860
|
+
* of the model's offered output sizes. Its output size is the provider's, so it
|
|
861
|
+
* takes no width, height, steps or video settings.
|
|
862
|
+
*/
|
|
863
|
+
function normalizeTransformSettings<
|
|
864
|
+
InputReference extends {
|
|
865
|
+
path: string;
|
|
866
|
+
role?: MediaVideoReferenceRole | undefined;
|
|
867
|
+
},
|
|
868
|
+
Reference extends { path: string; role?: MediaVideoReferenceRole },
|
|
869
|
+
>(
|
|
870
|
+
model: MediaCatalogueModel,
|
|
871
|
+
transform: MediaTransform,
|
|
872
|
+
prompt: string,
|
|
873
|
+
input: Omit<
|
|
874
|
+
z.output<typeof mediaGenerationSettingsSchema>,
|
|
875
|
+
"references" | "audioReferences"
|
|
876
|
+
> & {
|
|
877
|
+
references?: readonly InputReference[] | undefined;
|
|
878
|
+
audioReferences?: readonly InputReference[] | undefined;
|
|
879
|
+
},
|
|
880
|
+
normalize: (reference: InputReference) => Reference,
|
|
881
|
+
): Readonly<MutableMediaGenerationSettings<Reference>> {
|
|
882
|
+
if (
|
|
883
|
+
input.width !== undefined ||
|
|
884
|
+
input.height !== undefined ||
|
|
885
|
+
input.steps !== undefined ||
|
|
886
|
+
input.guidance !== undefined ||
|
|
887
|
+
input.durationSeconds !== undefined ||
|
|
888
|
+
input.resolution !== undefined ||
|
|
889
|
+
input.aspectRatio !== undefined ||
|
|
890
|
+
input.generateAudio !== undefined ||
|
|
891
|
+
input.audioReferences !== undefined
|
|
892
|
+
)
|
|
893
|
+
throw new MediaSettingsError(
|
|
894
|
+
`${model.id} takes one source image${transform.defaultMegapixels === null ? "" : " and an output size"}`,
|
|
895
|
+
);
|
|
896
|
+
const references = input.references;
|
|
897
|
+
if (references?.length !== 1 || references[0]?.role !== undefined)
|
|
898
|
+
throw new MediaSettingsError(`${model.id} needs exactly one source image`);
|
|
899
|
+
const settings: MutableMediaGenerationSettings<Reference> = {
|
|
900
|
+
model: model.id,
|
|
901
|
+
prompt,
|
|
902
|
+
references: Object.freeze(references.map(normalize)),
|
|
903
|
+
};
|
|
904
|
+
if (transform.defaultMegapixels === null) {
|
|
905
|
+
if (input.targetMegapixels !== undefined)
|
|
906
|
+
throw new MediaSettingsError(`${model.id} does not take an output size`);
|
|
907
|
+
return Object.freeze(settings);
|
|
908
|
+
}
|
|
909
|
+
const target = input.targetMegapixels ?? transform.defaultMegapixels;
|
|
910
|
+
if (transformMilliunits(transform, target) === undefined)
|
|
911
|
+
throw new MediaSettingsError(
|
|
912
|
+
`${model.id} accepts output sizes of ${transform.sizes.map((price) => String(price.megapixels)).join(", ")} megapixels`,
|
|
913
|
+
);
|
|
914
|
+
settings.targetMegapixels = target;
|
|
915
|
+
return Object.freeze(settings);
|
|
916
|
+
}
|
|
917
|
+
|
|
918
|
+
/** Neutral audio selection: speech takes a voice, music a length; model-specific limits are checked by validateMediaGenerationSettings. */
|
|
919
|
+
export const mediaAudioSelectionSchema = z.lazy(() =>
|
|
920
|
+
z.strictObject({
|
|
921
|
+
/** Verified catalog audio model identifier. */
|
|
922
|
+
model: mediaAudioModelIdSchema,
|
|
923
|
+
/** Text to speak, or a description of the music; the model's `maxPromptLength` is enforced on top of this ceiling. */
|
|
924
|
+
prompt: z.string().min(1).max(MAX_MEDIA_PROMPT_LENGTH),
|
|
925
|
+
/** Speech only: a premade catalog voice; the model default when omitted. */
|
|
926
|
+
voiceId: z.string().min(1).max(64).optional(),
|
|
927
|
+
/** Music only: whole seconds, 3 through 600; 30 when omitted. */
|
|
928
|
+
durationSeconds: z.number().int().min(3).max(600).optional(),
|
|
929
|
+
}),
|
|
930
|
+
);
|
|
931
|
+
/** Caller audio selection before defaults and model-specific refinements. */
|
|
932
|
+
export type MediaAudioSelectionInput = z.input<
|
|
933
|
+
typeof mediaAudioSelectionSchema
|
|
934
|
+
>;
|
|
935
|
+
|
|
936
|
+
/** Host-authorized reader for decoded reference images. */
|
|
937
|
+
export type MediaReferenceReader = Readonly<{
|
|
938
|
+
/** Authorize and fit one reference for the selected catalog model. */
|
|
939
|
+
read: (
|
|
940
|
+
reference: MediaReference,
|
|
941
|
+
model: string,
|
|
942
|
+
) => Promise<MediaReferenceBytes>;
|
|
943
|
+
}>;
|
|
944
|
+
const imageFormats = new Set<ImageFormat>(["png", "jpeg", "gif", "webp"]);
|
|
945
|
+
|
|
946
|
+
/**
|
|
947
|
+
* Refuse a source image the operation cannot take, with plain copy, before any
|
|
948
|
+
* paid call: an unsupported encoding, a source over Botanical's size bounds,
|
|
949
|
+
* or an upscale whose source is already as large as the chosen output.
|
|
950
|
+
*/
|
|
951
|
+
function checkTransformSource(
|
|
952
|
+
model: MediaCatalogueModel,
|
|
953
|
+
transform: MediaTransform,
|
|
954
|
+
settings: MediaGenerationSettings,
|
|
955
|
+
image: MediaReferenceBytes,
|
|
956
|
+
): void {
|
|
957
|
+
const { source } = transform;
|
|
958
|
+
const named = (format: string) => (format === "jpeg" ? "JPEG" : "PNG");
|
|
959
|
+
if (!source.formats.some((format) => format === image.format))
|
|
960
|
+
throw new MediaSettingsError(
|
|
961
|
+
`${model.label} takes ${source.formats.map(named).join(" or ")} images, not ${image.format.toUpperCase()}.`,
|
|
962
|
+
);
|
|
963
|
+
if (image.bytes.byteLength > source.maxBytes)
|
|
964
|
+
throw new MediaSettingsError(
|
|
965
|
+
`That image is over ${String(source.maxBytes / (1024 * 1024))} MB, the most ${model.label} takes.`,
|
|
966
|
+
);
|
|
967
|
+
const pixels = image.width * image.height;
|
|
968
|
+
if (pixels > source.maxPixels)
|
|
969
|
+
throw new MediaSettingsError(
|
|
970
|
+
`That image is over ${String(source.maxPixels / 1_000_000)} megapixels, the most ${model.label} takes.`,
|
|
971
|
+
);
|
|
972
|
+
const target = settings.targetMegapixels;
|
|
973
|
+
if (target !== undefined && pixels >= target * 1_000_000)
|
|
974
|
+
throw new MediaSettingsError(
|
|
975
|
+
`That image is already ${(pixels / 1_000_000).toFixed(1)} megapixels. Choose a larger output than ${String(target)} megapixels.`,
|
|
976
|
+
);
|
|
977
|
+
}
|
|
978
|
+
|
|
979
|
+
/** Resolve only provider-accepted references through the caller's reader. */
|
|
980
|
+
export const resolveMediaReferences = async (
|
|
981
|
+
settings: MediaGenerationSettings,
|
|
982
|
+
reader: MediaReferenceReader,
|
|
983
|
+
catalogue: MediaCatalogue = mediaModels,
|
|
984
|
+
): Promise<readonly MediaReferenceBytes[]> => {
|
|
985
|
+
const model = getMediaModel(settings.model, catalogue);
|
|
986
|
+
if (model === undefined) throw new MediaSettingsError("unknown Media model");
|
|
987
|
+
const references = settings.references ?? [];
|
|
988
|
+
if (references.length > model.input.maxReferences)
|
|
989
|
+
throw new MediaSettingsError(
|
|
990
|
+
`${model.id} accepts at most ${String(model.input.maxReferences)} reference images`,
|
|
991
|
+
);
|
|
992
|
+
const resolved: MediaReferenceBytes[] = [];
|
|
993
|
+
let totalBytes = 0;
|
|
994
|
+
for (const reference of references) {
|
|
995
|
+
const image = await reader.read(reference, settings.model);
|
|
996
|
+
if (
|
|
997
|
+
!imageFormats.has(image.format) ||
|
|
998
|
+
!Number.isSafeInteger(image.width) ||
|
|
999
|
+
!Number.isSafeInteger(image.height) ||
|
|
1000
|
+
image.width < 1 ||
|
|
1001
|
+
image.height < 1 ||
|
|
1002
|
+
!referenceImageSizeIsValid(
|
|
1003
|
+
settings.model,
|
|
1004
|
+
image.width,
|
|
1005
|
+
image.height,
|
|
1006
|
+
catalogue,
|
|
1007
|
+
) ||
|
|
1008
|
+
!(image.bytes instanceof Uint8Array) ||
|
|
1009
|
+
image.bytes.byteLength === 0 ||
|
|
1010
|
+
image.bytes.byteLength > MAX_REFERENCE_BYTES
|
|
1011
|
+
)
|
|
1012
|
+
throw new MediaSettingsError(
|
|
1013
|
+
`reference ${reference.computerId}:${reference.path} exceeds the bounded image contract`,
|
|
1014
|
+
);
|
|
1015
|
+
if (model.transform !== null)
|
|
1016
|
+
checkTransformSource(model, model.transform, settings, image);
|
|
1017
|
+
totalBytes += image.bytes.byteLength;
|
|
1018
|
+
if (totalBytes > MAX_REFERENCE_BODY_BYTES)
|
|
1019
|
+
throw new MediaSettingsError(
|
|
1020
|
+
"reference images exceed the total request size limit",
|
|
1021
|
+
);
|
|
1022
|
+
resolved.push(Object.freeze({ ...image }));
|
|
1023
|
+
}
|
|
1024
|
+
return Object.freeze(resolved);
|
|
1025
|
+
};
|
|
1026
|
+
|
|
1027
|
+
/** Provider JSON image input for models without multipart references. */
|
|
1028
|
+
export type MediaJsonBody = Readonly<{
|
|
1029
|
+
/** Generation prompt. */
|
|
1030
|
+
prompt: string;
|
|
1031
|
+
/** Optional model-native output width. */
|
|
1032
|
+
width?: number;
|
|
1033
|
+
/** Optional model-native output height. */
|
|
1034
|
+
height?: number;
|
|
1035
|
+
/** Steps for models using the steps field. */
|
|
1036
|
+
steps?: number;
|
|
1037
|
+
/** Steps for models using the num_steps field. */
|
|
1038
|
+
num_steps?: number;
|
|
1039
|
+
/** Prompt guidance for models that take it. */
|
|
1040
|
+
guidance?: number;
|
|
1041
|
+
}>;
|
|
1042
|
+
type MutableMediaJsonBody = {
|
|
1043
|
+
prompt: string;
|
|
1044
|
+
width?: number;
|
|
1045
|
+
height?: number;
|
|
1046
|
+
steps?: number;
|
|
1047
|
+
num_steps?: number;
|
|
1048
|
+
guidance?: number;
|
|
1049
|
+
};
|
|
1050
|
+
/** A model-specific JSON body or multipart form ready for transport. */
|
|
1051
|
+
export type MediaProviderPayload =
|
|
1052
|
+
| Readonly<{
|
|
1053
|
+
/** Provider input transport. */
|
|
1054
|
+
transport: "json";
|
|
1055
|
+
/** Model-native JSON input. */
|
|
1056
|
+
body: MediaJsonBody;
|
|
1057
|
+
}>
|
|
1058
|
+
| Readonly<{
|
|
1059
|
+
/** Provider input transport. */
|
|
1060
|
+
transport: "multipart";
|
|
1061
|
+
/** Platform-encoded multipart image input. */
|
|
1062
|
+
body: FormData;
|
|
1063
|
+
}>;
|
|
1064
|
+
const mimeForFormat = (format: ImageFormat): ImageMimeType => `image/${format}`;
|
|
1065
|
+
|
|
1066
|
+
/** Build the exact JSON or multipart payload required by a retained model. */
|
|
1067
|
+
export const buildProviderInput = (
|
|
1068
|
+
settings: MediaGenerationSettings,
|
|
1069
|
+
references: readonly MediaReferenceBytes[] = [],
|
|
1070
|
+
): MediaProviderPayload => {
|
|
1071
|
+
const model = getGatewayModel(settings.model);
|
|
1072
|
+
if (model === undefined) throw new MediaSettingsError("unknown Media model");
|
|
1073
|
+
if (model.sizes !== null)
|
|
1074
|
+
throw new MediaSettingsError(`${model.id} runs through the AI Gateway`);
|
|
1075
|
+
if (references.length > model.input.maxReferences)
|
|
1076
|
+
throw new MediaSettingsError(
|
|
1077
|
+
`${model.id} accepts at most ${String(model.input.maxReferences)} reference images`,
|
|
1078
|
+
);
|
|
1079
|
+
if (model.input.referenceField === null && references.length > 0)
|
|
1080
|
+
throw new MediaSettingsError(`${model.id} does not accept references`);
|
|
1081
|
+
if (model.input.transport === "json") {
|
|
1082
|
+
const body: MutableMediaJsonBody = {
|
|
1083
|
+
prompt: settings.prompt,
|
|
1084
|
+
};
|
|
1085
|
+
if (model.input.dimensions === "own") {
|
|
1086
|
+
if (settings.width === undefined || settings.height === undefined)
|
|
1087
|
+
throw new MediaSettingsError(`${model.id} needs a width and a height`);
|
|
1088
|
+
body.width = settings.width;
|
|
1089
|
+
body.height = settings.height;
|
|
1090
|
+
}
|
|
1091
|
+
if (settings.steps !== undefined && model.input.steps === "steps")
|
|
1092
|
+
body.steps = settings.steps;
|
|
1093
|
+
if (settings.steps !== undefined && model.input.steps === "num_steps")
|
|
1094
|
+
body.num_steps = settings.steps;
|
|
1095
|
+
if (settings.guidance !== undefined && model.input.guidance !== null)
|
|
1096
|
+
body.guidance = settings.guidance;
|
|
1097
|
+
return Object.freeze({
|
|
1098
|
+
transport: "json",
|
|
1099
|
+
body: Object.freeze(body),
|
|
1100
|
+
});
|
|
1101
|
+
}
|
|
1102
|
+
const body = new FormData();
|
|
1103
|
+
body.append("prompt", settings.prompt);
|
|
1104
|
+
if (model.input.dimensions === "own") {
|
|
1105
|
+
body.append("width", String(settings.width));
|
|
1106
|
+
body.append("height", String(settings.height));
|
|
1107
|
+
}
|
|
1108
|
+
if (settings.steps !== undefined && model.input.steps === "steps")
|
|
1109
|
+
body.append("steps", String(settings.steps));
|
|
1110
|
+
references.forEach((reference, index) => {
|
|
1111
|
+
body.append(
|
|
1112
|
+
`${model.input.referenceField ?? "input_image_"}${String(index)}`,
|
|
1113
|
+
new Blob([new Uint8Array(reference.bytes).buffer], {
|
|
1114
|
+
type: mimeForFormat(reference.format),
|
|
1115
|
+
}),
|
|
1116
|
+
reference.filename ?? `reference-${String(index)}`,
|
|
1117
|
+
);
|
|
1118
|
+
});
|
|
1119
|
+
return Object.freeze({
|
|
1120
|
+
transport: "multipart",
|
|
1121
|
+
body,
|
|
1122
|
+
});
|
|
1123
|
+
};
|
|
1124
|
+
|
|
1125
|
+
/** One image in a provider envelope, encoded inline or available at a URL. */
|
|
1126
|
+
export type MediaProviderImageEntry = Readonly<{
|
|
1127
|
+
/** Inline base64 image data. */
|
|
1128
|
+
base64?: string | undefined;
|
|
1129
|
+
/** Inline encoded image data. */
|
|
1130
|
+
data?: string | undefined;
|
|
1131
|
+
/** HTTP image URL fetched through the host. */
|
|
1132
|
+
url?: string | undefined;
|
|
1133
|
+
}>;
|
|
1134
|
+
/** Parsed provider representation before conversion to bounded image bytes. */
|
|
1135
|
+
export type MediaProviderOutput =
|
|
1136
|
+
| Readonly<{
|
|
1137
|
+
/** Outcome or model-kind discriminant. */
|
|
1138
|
+
kind: "bytes";
|
|
1139
|
+
/** Generated output bytes. */
|
|
1140
|
+
bytes: Uint8Array;
|
|
1141
|
+
}>
|
|
1142
|
+
| Readonly<{
|
|
1143
|
+
/** Outcome or model-kind discriminant. */
|
|
1144
|
+
kind: "response";
|
|
1145
|
+
/** Provider response or encoded image response. */
|
|
1146
|
+
response: Response;
|
|
1147
|
+
}>
|
|
1148
|
+
| Readonly<{
|
|
1149
|
+
/** Outcome or model-kind discriminant. */
|
|
1150
|
+
kind: "encoded";
|
|
1151
|
+
/** Inline provider image representation. */
|
|
1152
|
+
encoded: string;
|
|
1153
|
+
}>
|
|
1154
|
+
| Readonly<{
|
|
1155
|
+
/** Outcome or model-kind discriminant. */
|
|
1156
|
+
kind: "entries";
|
|
1157
|
+
/** Provider output image entries. */
|
|
1158
|
+
entries: readonly MediaProviderImageEntry[];
|
|
1159
|
+
}>;
|
|
1160
|
+
const providerEntrySchema = z.lazy(() =>
|
|
1161
|
+
z
|
|
1162
|
+
.object({
|
|
1163
|
+
/** Base64-encoded image data. */
|
|
1164
|
+
base64: z.string().optional(),
|
|
1165
|
+
/** Encoded inline image data. */
|
|
1166
|
+
data: z.string().optional(),
|
|
1167
|
+
/** HTTP provider output URL. */
|
|
1168
|
+
url: z
|
|
1169
|
+
.url()
|
|
1170
|
+
.refine(
|
|
1171
|
+
(value) => /^https?:\/\//iu.test(value),
|
|
1172
|
+
"provider image URLs must use HTTP(S)",
|
|
1173
|
+
)
|
|
1174
|
+
.optional(),
|
|
1175
|
+
})
|
|
1176
|
+
.strict(),
|
|
1177
|
+
);
|
|
1178
|
+
const providerEnvelopeSchema = z.lazy(() =>
|
|
1179
|
+
z.union([
|
|
1180
|
+
z.object({
|
|
1181
|
+
/** Encoded provider image. */
|
|
1182
|
+
image: z.string().min(1),
|
|
1183
|
+
}),
|
|
1184
|
+
z.object({
|
|
1185
|
+
/** Provider image entries. */
|
|
1186
|
+
image: z.array(providerEntrySchema),
|
|
1187
|
+
}),
|
|
1188
|
+
z.object({
|
|
1189
|
+
/** Provider output image entries. */
|
|
1190
|
+
images: z.array(providerEntrySchema),
|
|
1191
|
+
}),
|
|
1192
|
+
]),
|
|
1193
|
+
);
|
|
1194
|
+
|
|
1195
|
+
/** Decode the Workers AI binding's raw output at the provider boundary. */
|
|
1196
|
+
export const mediaProviderWireSchema = z.lazy(() =>
|
|
1197
|
+
z.union([
|
|
1198
|
+
providerEnvelopeSchema,
|
|
1199
|
+
z.instanceof(Uint8Array),
|
|
1200
|
+
z.instanceof(Response),
|
|
1201
|
+
z.custom<ReadableStream<Uint8Array>>(
|
|
1202
|
+
(value) => value instanceof ReadableStream,
|
|
1203
|
+
),
|
|
1204
|
+
]),
|
|
1205
|
+
);
|
|
1206
|
+
/** Supported raw provider representations, decoded by mediaProviderWireSchema. */
|
|
1207
|
+
export type MediaProviderWire = z.output<typeof mediaProviderWireSchema>;
|
|
1208
|
+
/** Native Workers AI output or an already decoded provider representation. */
|
|
1209
|
+
export type MediaAiResult = Awaited<ReturnType<Ai["run"]>> | MediaProviderWire;
|
|
1210
|
+
|
|
1211
|
+
/** Parse the provider wire envelope before normalization. */
|
|
1212
|
+
export const parseMediaProviderOutput = (
|
|
1213
|
+
value: MediaProviderWire,
|
|
1214
|
+
): MediaProviderOutput => {
|
|
1215
|
+
if (value instanceof Uint8Array)
|
|
1216
|
+
return {
|
|
1217
|
+
kind: "bytes",
|
|
1218
|
+
bytes: value,
|
|
1219
|
+
};
|
|
1220
|
+
if (value instanceof Response)
|
|
1221
|
+
return {
|
|
1222
|
+
kind: "response",
|
|
1223
|
+
response: value,
|
|
1224
|
+
};
|
|
1225
|
+
if (value instanceof ReadableStream)
|
|
1226
|
+
return {
|
|
1227
|
+
kind: "response",
|
|
1228
|
+
response: new Response(value),
|
|
1229
|
+
};
|
|
1230
|
+
const parsed = providerEnvelopeSchema.parse(value);
|
|
1231
|
+
if ("image" in parsed)
|
|
1232
|
+
return Array.isArray(parsed.image)
|
|
1233
|
+
? {
|
|
1234
|
+
kind: "entries",
|
|
1235
|
+
entries: parsed.image,
|
|
1236
|
+
}
|
|
1237
|
+
: {
|
|
1238
|
+
kind: "encoded",
|
|
1239
|
+
encoded: parsed.image,
|
|
1240
|
+
};
|
|
1241
|
+
return {
|
|
1242
|
+
kind: "entries",
|
|
1243
|
+
entries: parsed.images,
|
|
1244
|
+
};
|
|
1245
|
+
};
|
|
1246
|
+
|
|
1247
|
+
const decodeEncoded = (
|
|
1248
|
+
value: string,
|
|
1249
|
+
maximumBytes: number,
|
|
1250
|
+
): Uint8Array | undefined => {
|
|
1251
|
+
const comma = value.startsWith("data:") ? value.indexOf(",") : -1;
|
|
1252
|
+
const payload = comma >= 0 ? value.slice(comma + 1) : value;
|
|
1253
|
+
if (payload.length > Math.ceil((maximumBytes * 4) / 3) + 4) return undefined;
|
|
1254
|
+
const encoded = z.base64().safeParse(payload);
|
|
1255
|
+
if (!encoded.success) return undefined;
|
|
1256
|
+
const binary = atob(encoded.data);
|
|
1257
|
+
if (binary.length === 0 || binary.length > maximumBytes) return undefined;
|
|
1258
|
+
return Uint8Array.from(binary, (character) => character.charCodeAt(0));
|
|
1259
|
+
};
|
|
1260
|
+
const encodedExceedsBound = (value: string, maximumBytes: number): boolean => {
|
|
1261
|
+
const comma = value.startsWith("data:") ? value.indexOf(",") : -1;
|
|
1262
|
+
const payload = comma >= 0 ? value.slice(comma + 1) : value;
|
|
1263
|
+
return payload.length > Math.ceil((maximumBytes * 4) / 3) + 4;
|
|
1264
|
+
};
|
|
1265
|
+
const declaredDataUrlFormat = (value: string): ImageFormat | undefined => {
|
|
1266
|
+
if (!value.startsWith("data:")) return undefined;
|
|
1267
|
+
const comma = value.indexOf(",");
|
|
1268
|
+
if (comma < 0) return undefined;
|
|
1269
|
+
const mime = value.slice(5, comma).split(";", 1)[0]?.toLowerCase();
|
|
1270
|
+
if (mime === "image/jpeg") return "jpeg";
|
|
1271
|
+
if (mime === "image/png") return "png";
|
|
1272
|
+
if (mime === "image/gif") return "gif";
|
|
1273
|
+
if (mime === "image/webp") return "webp";
|
|
1274
|
+
return undefined;
|
|
1275
|
+
};
|
|
1276
|
+
/** Read a successful provider response within an explicit byte bound, closing its reader. */
|
|
1277
|
+
export const readResponseBytes = async (
|
|
1278
|
+
response: Response,
|
|
1279
|
+
maximumBytes: number,
|
|
1280
|
+
): Promise<Uint8Array> => {
|
|
1281
|
+
if (!response.ok)
|
|
1282
|
+
throw new Error(`provider response status ${String(response.status)}`);
|
|
1283
|
+
const claimedLength = response.headers.get("content-length");
|
|
1284
|
+
if (claimedLength !== null) {
|
|
1285
|
+
const length = Number(claimedLength);
|
|
1286
|
+
if (!Number.isSafeInteger(length) || length < 0 || length > maximumBytes)
|
|
1287
|
+
throw new Error("provider response exceeds the byte bound");
|
|
1288
|
+
}
|
|
1289
|
+
if (response.body === null) throw new Error("provider response had no body");
|
|
1290
|
+
const reader = new ReadableStreamDefaultReader<Uint8Array>(response.body);
|
|
1291
|
+
const chunks: Uint8Array[] = [];
|
|
1292
|
+
let total = 0;
|
|
1293
|
+
try {
|
|
1294
|
+
let item = await reader.read();
|
|
1295
|
+
while (!item.done) {
|
|
1296
|
+
total += item.value.byteLength;
|
|
1297
|
+
if (total > maximumBytes)
|
|
1298
|
+
throw new Error("provider response exceeds the byte bound");
|
|
1299
|
+
chunks.push(item.value);
|
|
1300
|
+
item = await reader.read();
|
|
1301
|
+
}
|
|
1302
|
+
} finally {
|
|
1303
|
+
// Closing a rejected stream must not hide its original read/bound failure.
|
|
1304
|
+
await reader.cancel().catch((cause: unknown) => {
|
|
1305
|
+
reportCatchFailure("provider-response-reader-cancel", cause);
|
|
1306
|
+
});
|
|
1307
|
+
reader.releaseLock();
|
|
1308
|
+
}
|
|
1309
|
+
const bytes = new Uint8Array(total);
|
|
1310
|
+
let offset = 0;
|
|
1311
|
+
for (const chunk of chunks) {
|
|
1312
|
+
bytes.set(chunk, offset);
|
|
1313
|
+
offset += chunk.byteLength;
|
|
1314
|
+
}
|
|
1315
|
+
return bytes;
|
|
1316
|
+
};
|
|
1317
|
+
/** Host-supplied URL fetching and maximum output bytes for normalization. */
|
|
1318
|
+
export type MediaProviderOutputOptions = Readonly<{
|
|
1319
|
+
/** Fetch a provider image URL through host-owned transport. */
|
|
1320
|
+
fetchUrl?: (url: string) => Promise<Response>;
|
|
1321
|
+
/** Maximum output bytes, defaulting to MAX_OUTPUT_BYTES. */
|
|
1322
|
+
maxBytes?: number;
|
|
1323
|
+
}>;
|
|
1324
|
+
/** Normalized bytes and their supported still-image encoding. */
|
|
1325
|
+
export type MediaImageOutput = Readonly<{
|
|
1326
|
+
/** Bounded decoded provider bytes. */
|
|
1327
|
+
bytes: Uint8Array;
|
|
1328
|
+
/** Detected or explicitly declared image encoding. */
|
|
1329
|
+
format: ImageFormat;
|
|
1330
|
+
}>;
|
|
1331
|
+
const tryNormalizeBytes = (
|
|
1332
|
+
bytes: Uint8Array,
|
|
1333
|
+
maximumBytes: number,
|
|
1334
|
+
declaredFormat?: ImageFormat,
|
|
1335
|
+
): MediaImageOutput | undefined => {
|
|
1336
|
+
if (bytes.byteLength === 0 || bytes.byteLength > maximumBytes)
|
|
1337
|
+
return undefined;
|
|
1338
|
+
const format = sniffImageFormat(bytes);
|
|
1339
|
+
if (format === undefined) return undefined;
|
|
1340
|
+
return { bytes, format: declaredFormat ?? format };
|
|
1341
|
+
};
|
|
1342
|
+
const normalizeBytes = (
|
|
1343
|
+
bytes: Uint8Array,
|
|
1344
|
+
maximumBytes: number,
|
|
1345
|
+
declaredFormat?: ImageFormat,
|
|
1346
|
+
): MediaImageOutput => {
|
|
1347
|
+
const output = tryNormalizeBytes(bytes, maximumBytes, declaredFormat);
|
|
1348
|
+
if (output === undefined)
|
|
1349
|
+
throw new Error("provider image has an unsupported format or size");
|
|
1350
|
+
return output;
|
|
1351
|
+
};
|
|
1352
|
+
|
|
1353
|
+
/** Normalize all retained provider envelopes into bounded image bytes. */
|
|
1354
|
+
export const normalizeMediaProviderOutput = async (
|
|
1355
|
+
value: MediaProviderWire,
|
|
1356
|
+
options: MediaProviderOutputOptions = {},
|
|
1357
|
+
): Promise<MediaImageOutput> => {
|
|
1358
|
+
const maximumBytes = options.maxBytes ?? MAX_OUTPUT_BYTES;
|
|
1359
|
+
if (!Number.isSafeInteger(maximumBytes) || maximumBytes < 1)
|
|
1360
|
+
throw new Error("maxBytes must be a positive safe integer");
|
|
1361
|
+
const parsed = parseMediaProviderOutput(value);
|
|
1362
|
+
if (parsed.kind === "bytes")
|
|
1363
|
+
return normalizeBytes(parsed.bytes, maximumBytes);
|
|
1364
|
+
if (parsed.kind === "response")
|
|
1365
|
+
return normalizeBytes(
|
|
1366
|
+
await readResponseBytes(parsed.response, maximumBytes),
|
|
1367
|
+
maximumBytes,
|
|
1368
|
+
);
|
|
1369
|
+
if (parsed.kind === "encoded") {
|
|
1370
|
+
if (encodedExceedsBound(parsed.encoded, maximumBytes))
|
|
1371
|
+
throw new Error("provider image exceeds the byte bound");
|
|
1372
|
+
const bytes = decodeEncoded(parsed.encoded, maximumBytes);
|
|
1373
|
+
if (bytes === undefined)
|
|
1374
|
+
throw new Error("provider image encoding is invalid");
|
|
1375
|
+
return normalizeBytes(
|
|
1376
|
+
bytes,
|
|
1377
|
+
maximumBytes,
|
|
1378
|
+
declaredDataUrlFormat(parsed.encoded),
|
|
1379
|
+
);
|
|
1380
|
+
}
|
|
1381
|
+
for (const entry of parsed.entries) {
|
|
1382
|
+
for (const encoded of [entry.base64, entry.data]) {
|
|
1383
|
+
if (encoded === undefined) continue;
|
|
1384
|
+
const bytes = decodeEncoded(encoded, maximumBytes);
|
|
1385
|
+
if (bytes !== undefined) {
|
|
1386
|
+
const normalized = tryNormalizeBytes(
|
|
1387
|
+
bytes,
|
|
1388
|
+
maximumBytes,
|
|
1389
|
+
declaredDataUrlFormat(encoded),
|
|
1390
|
+
);
|
|
1391
|
+
if (normalized !== undefined) return normalized;
|
|
1392
|
+
}
|
|
1393
|
+
}
|
|
1394
|
+
if (entry.url !== undefined) {
|
|
1395
|
+
const fetchUrl = options.fetchUrl ?? ((url: string) => fetch(url));
|
|
1396
|
+
try {
|
|
1397
|
+
const response = await fetchUrl(entry.url);
|
|
1398
|
+
return normalizeBytes(
|
|
1399
|
+
await readResponseBytes(response, maximumBytes),
|
|
1400
|
+
maximumBytes,
|
|
1401
|
+
);
|
|
1402
|
+
} catch (cause) {
|
|
1403
|
+
reportCatchFailure("provider-entry-fetch", cause);
|
|
1404
|
+
/* Try the next provider entry. */
|
|
1405
|
+
}
|
|
1406
|
+
}
|
|
1407
|
+
}
|
|
1408
|
+
throw new Error("provider returned no valid image bytes");
|
|
1409
|
+
};
|
|
1410
|
+
|
|
1411
|
+
export {
|
|
1412
|
+
estimateImageMilliunits,
|
|
1413
|
+
estimateImageNeurons,
|
|
1414
|
+
} from "./cost-estimate.js";
|
|
1415
|
+
export { neuronsToMilliunits, USD_PER_1K_NEURONS } from "./neurons.js";
|
|
1416
|
+
export type { ImageParams, ImageReference } from "./cost-estimate.js";
|
|
1417
|
+
|
|
1418
|
+
/** Authority-free video quote settings; hydrated host settings are structurally compatible. */
|
|
1419
|
+
export type MediaVideoQuoteSettings = ReturnType<
|
|
1420
|
+
typeof validateMediaGenerationSelection
|
|
1421
|
+
>;
|
|
1422
|
+
|
|
1423
|
+
/** Provider video cost from `catalogue`, in milliunits (1 cent = 1,000). Video-input references are unsupported. */
|
|
1424
|
+
export function estimateVideoMilliunits(
|
|
1425
|
+
settings: MediaVideoQuoteSettings,
|
|
1426
|
+
catalogue: MediaCatalogue = mediaModels,
|
|
1427
|
+
): number {
|
|
1428
|
+
const checked = validateMediaGenerationSelection(
|
|
1429
|
+
{
|
|
1430
|
+
...settings,
|
|
1431
|
+
references: settings.references?.map((reference) => ({
|
|
1432
|
+
path: reference.path,
|
|
1433
|
+
role: reference.role,
|
|
1434
|
+
})),
|
|
1435
|
+
audioReferences: settings.audioReferences?.map((reference) => ({
|
|
1436
|
+
path: reference.path,
|
|
1437
|
+
})),
|
|
1438
|
+
},
|
|
1439
|
+
catalogue,
|
|
1440
|
+
);
|
|
1441
|
+
const model = getMediaModel(checked.model, catalogue);
|
|
1442
|
+
if (model?.video == null || checked.durationSeconds === undefined)
|
|
1443
|
+
throw new MediaSettingsError("video cost requires a verified video model");
|
|
1444
|
+
const price = model.video.prices.find(
|
|
1445
|
+
(candidate) => candidate.resolution === checked.resolution,
|
|
1446
|
+
);
|
|
1447
|
+
if (price === undefined)
|
|
1448
|
+
throw new MediaSettingsError("video price unavailable for this resolution");
|
|
1449
|
+
const rate =
|
|
1450
|
+
checked.generateAudio === true
|
|
1451
|
+
? price.audioMilliunitsPerSecond
|
|
1452
|
+
: price.silentMilliunitsPerSecond;
|
|
1453
|
+
return rate * checked.durationSeconds;
|
|
1454
|
+
}
|