@fungi.computer/darkroom 0.9.2 → 0.10.0

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 CHANGED
@@ -262,6 +262,35 @@ const service = createMediaService({
262
262
  settings outside its bounds, is refused before billing or dispatch. The
263
263
  gateway's own models are refused by this provider the same way.
264
264
 
265
+ ### What a model entry tells an App
266
+
267
+ `GET /models` and `listMediaModels()` return the same typed entry
268
+ (`MediaModel`), so an App draws each model's controls from it and keeps no
269
+ per-model rules of its own. Where the host mediates, it may remove a reference
270
+ capability it cannot serve (`input.maxReferences` 0, `video.audioReferences`
271
+ null) and adds `priceEstimate`.
272
+
273
+ | An App needs | Field |
274
+ | --------------------- | --------------------------------------------------------------------------------------------------------------------- |
275
+ | Kind | `kind`: `image`, `video` or `audio` |
276
+ | Sizes and aspects | `sizes` (`WIDTHxHEIGHT` list, null for any size within `input.maxDimension`); `video.formats` (resolution and aspect) |
277
+ | Duration options | `video.durations`, `video.defaultSeconds`; music `audio.seconds` |
278
+ | Maximum prompt length | `maxPromptLength` (characters) |
279
+ | Reference images | `input.maxReferences`; video `video.maxReferenceImages` and `video.referenceResolutions` |
280
+ | Video reference roles | `video.referenceRoles` (`first-frame`, `last-frame`, `reference`) |
281
+ | Audio references | `video.audioReferences` (`{max, totalSeconds}` or null) |
282
+ | Sound on video | `video.supportsAudio`, `video.defaultGenerateAudio` |
283
+ | Price basis | `billingUnit`: `image`, `video_second`, `audio_second` or `audio_character_block` |
284
+
285
+ `billingUnit` names what one generation is billed in; it is derived from the
286
+ model's kind (and speech or music mode) by the same rule `mediaUnits` uses, so
287
+ it cannot drift from billing. Cost per unit depends on the settings: output
288
+ size, steps and references for images, resolution and sound for video. An App
289
+ therefore shows `priceEstimate` (a labelled estimate at the model's defaults,
290
+ added by hosts that quote) and asks its host to quote the exact settings, which
291
+ runs `quoteMediaGeneration`, before it shows a final number. Speech bills one
292
+ unit per 100 characters.
293
+
265
294
  ## API reference
266
295
 
267
296
  | Import | Purpose |
@@ -327,6 +356,55 @@ metadata while preserving the AI marker, print ID and image encoding. It returns
327
356
  bytes, MIME type and filename extension. The public XMP format uses
328
357
  `https://fungi.computer/ns/provenance/1.0/`.
329
358
 
359
+ ## Use your own R2 bucket
360
+
361
+ Keep reference images and generated output in a bucket you already own.
362
+ `createR2MediaDestination` (from `@fungi.computer/darkroom/cloudflare`) is the
363
+ whole destination: object keys are the paths, and URLs are never accepted.
364
+
365
+ ```ts
366
+ import { createMediaService } from "@fungi.computer/darkroom/server";
367
+ import {
368
+ createImagesReferenceFitter,
369
+ createR2MediaDestination,
370
+ createWorkersAiMediaProvider,
371
+ } from "@fungi.computer/darkroom/cloudflare";
372
+
373
+ const app = createMediaService({
374
+ scope: {
375
+ actorId,
376
+ namespace: "studio",
377
+ owner: "media",
378
+ destinationId: "studio-bucket",
379
+ },
380
+ operations: env.MEDIA_OPERATION, // MediaOperationDO binding
381
+ provider: createWorkersAiMediaProvider(env.AI),
382
+ metering: "unmetered",
383
+ destination: createR2MediaDestination({
384
+ bucket: env.STUDIO_BUCKET, // your R2 binding
385
+ destinationId: "studio-bucket", // a reference must carry this same id
386
+ fit: createImagesReferenceFitter(env.IMAGES),
387
+ authorize: (key) => assertActorMayUse(actorId, key), // your permission check
388
+ }),
389
+ });
390
+ ```
391
+
392
+ Select a reference with `{ computerId: "studio-bucket", path: "<object key>" }`.
393
+ The field is named `computerId` for historical reasons; it carries your
394
+ destination id.
395
+
396
+ The host still owns who may touch which key (`authorize`, which runs before
397
+ every dispatch, write and reference read; omitted, any valid key in the bucket
398
+ is allowed), the destination id it admits, the provider account and its billing.
399
+
400
+ Darkroom guarantees that every key is validated as a path, a reference for
401
+ another destination is refused, and a missing, empty or oversized reference (8
402
+ MiB for images, 16 MiB for audio) is refused. These refusals, and a failed
403
+ `authorize`, happen before any paid dispatch. Generation is priced from the
404
+ validated settings. Output is saved with its content type, and a retry with the
405
+ same request ID reuses the saved output instead of calling the provider again. A
406
+ runnable Worker is in [`examples/standalone`](examples/standalone).
407
+
330
408
  ## Limits
331
409
 
332
410
  References are bounded to four files and 8 MiB per image. Image-model references
@@ -488,9 +566,7 @@ through the same durable alarm as video: HTTP returns 202 until the retained MP3
488
566
  is ready, and the output has no embedded provenance. Hub public sharing does not
489
567
  cover audio. The MEDIA binding accepts `kind: "audio"` with `prompt`, `voiceId`
490
568
  or `durationSeconds`, and saves `<libraryPath>/prints-<requestId>.mp3`. The
491
- `/models` listing still carries pictures and video only, because the Agar and
492
- Prints catalog decoders have no audio kind yet; audio models are generated by
493
- id.
569
+ `/models` listing includes audio models with `kind: "audio"`.
494
570
 
495
571
  Video models declare `video.audioReferences` (`{max, totalSeconds}`, or null).
496
572
  Only Seedance 2.5 sets it, at 10 clips and 30 seconds, from its Cloudflare input
@@ -16,6 +16,7 @@ export declare const mediaModelPriceEstimateSchema: z.ZodObject<{
16
16
  height: z.ZodOptional<z.ZodNumber>;
17
17
  steps: z.ZodOptional<z.ZodNumber>;
18
18
  durationSeconds: z.ZodOptional<z.ZodNumber>;
19
+ targetMegapixels: z.ZodOptional<z.ZodNumber>;
19
20
  voiceId: z.ZodOptional<z.ZodString>;
20
21
  resolution: z.ZodOptional<z.ZodEnum<{
21
22
  readonly p480: "480p";
@@ -194,6 +195,33 @@ export declare const mediaCatalogModelSchema: z.ZodReadonly<z.ZodObject<{
194
195
  }, z.core.$strict>>>;
195
196
  milliunitsPerUnit: z.ZodNumber;
196
197
  }, z.core.$strict>>>>;
198
+ billingUnit: z.ZodEnum<{
199
+ readonly image: "image";
200
+ readonly video_second: "video_second";
201
+ readonly audio_second: "audio_second";
202
+ readonly audio_character_block: "audio_character_block";
203
+ }>;
204
+ transform: z.ZodNullable<z.ZodLazy<z.ZodReadonly<z.ZodObject<{
205
+ operation: z.ZodEnum<{
206
+ readonly remove_background: "remove_background";
207
+ readonly upscale: "upscale";
208
+ }>;
209
+ source: z.ZodReadonly<z.ZodObject<{
210
+ formats: z.ZodReadonly<z.ZodArray<z.ZodEnum<{
211
+ readonly png: "png";
212
+ readonly jpeg: "jpeg";
213
+ readonly webp: "webp";
214
+ }>>>;
215
+ maxBytes: z.ZodNumber;
216
+ maxPixels: z.ZodNumber;
217
+ }, z.core.$strict>>;
218
+ defaultMegapixels: z.ZodNullable<z.ZodNumber>;
219
+ milliunits: z.ZodNullable<z.ZodNumber>;
220
+ sizes: z.ZodReadonly<z.ZodArray<z.ZodReadonly<z.ZodObject<{
221
+ megapixels: z.ZodNumber;
222
+ milliunits: z.ZodNumber;
223
+ }, z.core.$strict>>>>;
224
+ }, z.core.$strict>>>>;
197
225
  priceEstimate: z.ZodOptional<z.ZodObject<{
198
226
  kind: z.ZodLiteral<"estimate">;
199
227
  basis: z.ZodEnum<{
@@ -210,6 +238,7 @@ export declare const mediaCatalogModelSchema: z.ZodReadonly<z.ZodObject<{
210
238
  height: z.ZodOptional<z.ZodNumber>;
211
239
  steps: z.ZodOptional<z.ZodNumber>;
212
240
  durationSeconds: z.ZodOptional<z.ZodNumber>;
241
+ targetMegapixels: z.ZodOptional<z.ZodNumber>;
213
242
  voiceId: z.ZodOptional<z.ZodString>;
214
243
  resolution: z.ZodOptional<z.ZodEnum<{
215
244
  readonly p480: "480p";
@@ -389,6 +418,33 @@ export declare const mediaModelsSchema: z.ZodLazy<z.ZodArray<z.ZodReadonly<z.Zod
389
418
  }, z.core.$strict>>>;
390
419
  milliunitsPerUnit: z.ZodNumber;
391
420
  }, z.core.$strict>>>>;
421
+ billingUnit: z.ZodEnum<{
422
+ readonly image: "image";
423
+ readonly video_second: "video_second";
424
+ readonly audio_second: "audio_second";
425
+ readonly audio_character_block: "audio_character_block";
426
+ }>;
427
+ transform: z.ZodNullable<z.ZodLazy<z.ZodReadonly<z.ZodObject<{
428
+ operation: z.ZodEnum<{
429
+ readonly remove_background: "remove_background";
430
+ readonly upscale: "upscale";
431
+ }>;
432
+ source: z.ZodReadonly<z.ZodObject<{
433
+ formats: z.ZodReadonly<z.ZodArray<z.ZodEnum<{
434
+ readonly png: "png";
435
+ readonly jpeg: "jpeg";
436
+ readonly webp: "webp";
437
+ }>>>;
438
+ maxBytes: z.ZodNumber;
439
+ maxPixels: z.ZodNumber;
440
+ }, z.core.$strict>>;
441
+ defaultMegapixels: z.ZodNullable<z.ZodNumber>;
442
+ milliunits: z.ZodNullable<z.ZodNumber>;
443
+ sizes: z.ZodReadonly<z.ZodArray<z.ZodReadonly<z.ZodObject<{
444
+ megapixels: z.ZodNumber;
445
+ milliunits: z.ZodNumber;
446
+ }, z.core.$strict>>>>;
447
+ }, z.core.$strict>>>>;
392
448
  priceEstimate: z.ZodOptional<z.ZodObject<{
393
449
  kind: z.ZodLiteral<"estimate">;
394
450
  basis: z.ZodEnum<{
@@ -405,6 +461,7 @@ export declare const mediaModelsSchema: z.ZodLazy<z.ZodArray<z.ZodReadonly<z.Zod
405
461
  height: z.ZodOptional<z.ZodNumber>;
406
462
  steps: z.ZodOptional<z.ZodNumber>;
407
463
  durationSeconds: z.ZodOptional<z.ZodNumber>;
464
+ targetMegapixels: z.ZodOptional<z.ZodNumber>;
408
465
  voiceId: z.ZodOptional<z.ZodString>;
409
466
  resolution: z.ZodOptional<z.ZodEnum<{
410
467
  readonly p480: "480p";
@@ -747,6 +804,33 @@ export declare const appMediaModelsOutcomeSchema: z.ZodUnion<readonly [z.ZodLazy
747
804
  }, z.core.$strict>>>;
748
805
  milliunitsPerUnit: z.ZodNumber;
749
806
  }, z.core.$strict>>>>;
807
+ billingUnit: z.ZodEnum<{
808
+ readonly image: "image";
809
+ readonly video_second: "video_second";
810
+ readonly audio_second: "audio_second";
811
+ readonly audio_character_block: "audio_character_block";
812
+ }>;
813
+ transform: z.ZodNullable<z.ZodLazy<z.ZodReadonly<z.ZodObject<{
814
+ operation: z.ZodEnum<{
815
+ readonly remove_background: "remove_background";
816
+ readonly upscale: "upscale";
817
+ }>;
818
+ source: z.ZodReadonly<z.ZodObject<{
819
+ formats: z.ZodReadonly<z.ZodArray<z.ZodEnum<{
820
+ readonly png: "png";
821
+ readonly jpeg: "jpeg";
822
+ readonly webp: "webp";
823
+ }>>>;
824
+ maxBytes: z.ZodNumber;
825
+ maxPixels: z.ZodNumber;
826
+ }, z.core.$strict>>;
827
+ defaultMegapixels: z.ZodNullable<z.ZodNumber>;
828
+ milliunits: z.ZodNullable<z.ZodNumber>;
829
+ sizes: z.ZodReadonly<z.ZodArray<z.ZodReadonly<z.ZodObject<{
830
+ megapixels: z.ZodNumber;
831
+ milliunits: z.ZodNumber;
832
+ }, z.core.$strict>>>>;
833
+ }, z.core.$strict>>>>;
750
834
  priceEstimate: z.ZodOptional<z.ZodObject<{
751
835
  kind: z.ZodLiteral<"estimate">;
752
836
  basis: z.ZodEnum<{
@@ -763,6 +847,7 @@ export declare const appMediaModelsOutcomeSchema: z.ZodUnion<readonly [z.ZodLazy
763
847
  height: z.ZodOptional<z.ZodNumber>;
764
848
  steps: z.ZodOptional<z.ZodNumber>;
765
849
  durationSeconds: z.ZodOptional<z.ZodNumber>;
850
+ targetMegapixels: z.ZodOptional<z.ZodNumber>;
766
851
  voiceId: z.ZodOptional<z.ZodString>;
767
852
  resolution: z.ZodOptional<z.ZodEnum<{
768
853
  readonly p480: "480p";
package/dist/browser.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ export { backgroundProviderTimeoutMs } from "./media-run-lifetime.js";
1
2
  export { MAX_MEDIA_PROMPT_LENGTH } from "./model-catalog.js";
2
3
  export { mediaFailureSchema, readMediaFailure } from "./browser-failure.js";
3
4
  export type { MediaFailure, MediaGenerationDiagnostic, } from "./browser-failure.js";
package/dist/browser.js CHANGED
@@ -1,2 +1,3 @@
1
+ export { backgroundProviderTimeoutMs } from "./media-run-lifetime.js";
1
2
  export { MAX_MEDIA_PROMPT_LENGTH } from "./model-catalog.js";
2
3
  export { mediaFailureSchema, readMediaFailure } from "./browser-failure.js";
@@ -5,21 +5,21 @@ export declare function estimateMediaModel(model: MediaModel): {
5
5
  kind: "estimate";
6
6
  /** Provider cost before the host's billing policy. */
7
7
  basis: "provider-cost";
8
- /** Catalog defaults, a one-character prompt and no references. */
9
- settings: Readonly<{
8
+ /** Catalog defaults and a one-character prompt; never references. */
9
+ settings: {
10
10
  model: string;
11
11
  prompt: string;
12
12
  width?: number;
13
13
  height?: number;
14
14
  steps?: number;
15
15
  durationSeconds?: number;
16
+ targetMegapixels?: number;
16
17
  voiceId?: string;
17
18
  resolution?: import("../model-catalog.js").MediaVideoResolution;
18
19
  aspectRatio?: import("../model-catalog.js").MediaVideoAspectRatio;
19
20
  generateAudio?: boolean;
20
- references?: readonly import("../index.js").MediaReference[];
21
21
  audioReferences?: readonly import("../index.js").MediaReference[];
22
- }>;
22
+ };
23
23
  /** Estimated provider milliunits of a cent for these exact settings. */
24
24
  costMilliunits: number;
25
25
  };
@@ -10,23 +10,34 @@ import { decodeElevenLabsResultUrl, ELEVENLABS_MAX_BYTES, } from "../audio-provi
10
10
  import { readResponseBytes } from "../index.js";
11
11
  /** Quote the catalog defaults through the exact estimator used before dispatch. */
12
12
  export function estimateMediaModel(model) {
13
- const settings = validateMediaGenerationSettings(model.kind === "audio"
13
+ const checked = validateMediaGenerationSettings(model.kind === "audio"
14
14
  ? { model: model.id, prompt: "x" }
15
- : {
16
- model: model.id,
17
- prompt: "x",
18
- width: model.input.defaultWidth,
19
- height: model.input.defaultHeight,
20
- });
15
+ : model.transform !== null
16
+ ? {
17
+ // A source-image operation is priced by its default output size;
18
+ // the placeholder reference is never read.
19
+ model: model.id,
20
+ prompt: "x",
21
+ references: [{ computerId: "estimate", path: "/estimate" }],
22
+ }
23
+ : {
24
+ model: model.id,
25
+ prompt: "x",
26
+ width: model.input.defaultWidth,
27
+ height: model.input.defaultHeight,
28
+ });
29
+ // The placeholder reference only satisfies validation; the quote names none.
30
+ const { references: placeholder, ...settings } = checked;
31
+ void placeholder;
21
32
  return {
22
33
  /** An indicative quote, not an admitted generation receipt. */
23
34
  kind: "estimate",
24
35
  /** Provider cost before the host's billing policy. */
25
36
  basis: "provider-cost",
26
- /** Catalog defaults, a one-character prompt and no references. */
37
+ /** Catalog defaults and a one-character prompt; never references. */
27
38
  settings,
28
39
  /** Estimated provider milliunits of a cent for these exact settings. */
29
- costMilliunits: estimate(settings, []),
40
+ costMilliunits: estimate(checked, []),
30
41
  };
31
42
  }
32
43
  export function estimate(settings, references) {
@@ -0,0 +1,48 @@
1
+ import type { MediaReference, MediaReferenceBytes, ReferenceImageFitter } from "../index.js";
2
+ import type { MediaServiceHost } from "../server.js";
3
+ /** The R2 bucket operations a Media destination needs; a native `R2Bucket` satisfies it. */
4
+ export type MediaR2Bucket = {
5
+ /** Read one object, or null when the key is absent. */
6
+ get(key: string): Promise<(Readonly<{
7
+ /** Stored byte length. */ size: number;
8
+ }> & {
9
+ /** Load the stored bytes. */ arrayBuffer(): Promise<ArrayBuffer>;
10
+ }) | null>;
11
+ /** Store exact bytes with their MIME type. */
12
+ put(key: string, bytes: Uint8Array, options: Readonly<{
13
+ /** MIME type recorded on the object. */
14
+ httpMetadata: Readonly<{
15
+ contentType: string;
16
+ }>;
17
+ }>): Promise<object | null>;
18
+ };
19
+ /** Host-owned R2 destination configuration. */
20
+ export type R2MediaDestinationOptions = Readonly<{
21
+ /** The bucket holding reference images and generated output. */
22
+ bucket: MediaR2Bucket;
23
+ /**
24
+ * The destination identity the host admitted. A reference must carry this
25
+ * same value (in `MediaReference.computerId`) or it is refused.
26
+ */
27
+ destinationId: string;
28
+ /** The Images-binding reference fitter, from `createImagesReferenceFitter`. */
29
+ fit: ReferenceImageFitter;
30
+ /**
31
+ * The host's own permission check for one object key. It runs before every
32
+ * dispatch, write and reference read; throw to refuse. Omitted, any valid
33
+ * key in `bucket` is allowed.
34
+ */
35
+ authorize?: ((key: string) => Promise<void> | void) | undefined;
36
+ }>;
37
+ /** The host destination over an R2 bucket, with both reference readers present. */
38
+ export type R2MediaDestination = MediaServiceHost["destination"] & Readonly<{
39
+ /** Authorize, read and fit one reference image for the catalog model. */
40
+ readReference: (reference: MediaReference, model: string) => Promise<MediaReferenceBytes>;
41
+ /** Authorize and read the raw bytes of one reference audio clip. */
42
+ readAudioReference: (reference: MediaReference) => Promise<Uint8Array>;
43
+ }>;
44
+ /**
45
+ * A Media destination over one R2 bucket: object keys are the paths, validated
46
+ * with Darkroom's path schema. Never accepts URLs.
47
+ */
48
+ export declare function createR2MediaDestination(options: R2MediaDestinationOptions): R2MediaDestination;
@@ -0,0 +1,46 @@
1
+ import { MediaSettingsError } from "../model-catalog.js";
2
+ import { mediaContentType } from "../media-content-type.js";
3
+ import { readHostReference, referenceFilename, } from "../reference-read.js";
4
+ import { mediaPathSchema } from "../media-path.js";
5
+ /**
6
+ * A Media destination over one R2 bucket: object keys are the paths, validated
7
+ * with Darkroom's path schema. Never accepts URLs.
8
+ */
9
+ export function createR2MediaDestination(options) {
10
+ const { bucket, destinationId, fit } = options;
11
+ const authorize = async (key) => {
12
+ const parsed = mediaPathSchema.safeParse(key);
13
+ if (!parsed.success)
14
+ throw new MediaSettingsError("R2 object key is not a valid path");
15
+ await options.authorize?.(parsed.data);
16
+ };
17
+ const read = (kind, reference) => readHostReference({
18
+ reference,
19
+ destinationId,
20
+ kind,
21
+ open: async (key) => {
22
+ await authorize(key);
23
+ const object = await bucket.get(key);
24
+ if (object === null)
25
+ return null;
26
+ return {
27
+ size: object.size,
28
+ bytes: async () => new Uint8Array(await object.arrayBuffer()),
29
+ };
30
+ },
31
+ });
32
+ return {
33
+ authorize,
34
+ write: async (key, bytes) => {
35
+ await authorize(key);
36
+ await bucket.put(key, bytes, {
37
+ httpMetadata: { contentType: mediaContentType(bytes) },
38
+ });
39
+ },
40
+ readReference: async (reference, model) => ({
41
+ ...(await fit(await read("image", reference), model)),
42
+ filename: referenceFilename(reference),
43
+ }),
44
+ readAudioReference: (reference) => read("audio", reference),
45
+ };
46
+ }
@@ -2,6 +2,7 @@ export { MediaOperationDO, type MediaOperationCloudflareEnvironment, type MediaO
2
2
  export { createWorkersAiMediaProvider, type MediaAiPort, } from "./cloudflare/provider.js";
3
3
  export type { MediaAiResult } from "./index.js";
4
4
  export { createImagesReferenceFitter, createImagesViewFitter, type MediaImagePort, } from "./cloudflare/reference-images.js";
5
+ export { createR2MediaDestination, type MediaR2Bucket, type R2MediaDestination, type R2MediaDestinationOptions, } from "./cloudflare/r2-destination.js";
5
6
  export { MediaOperationOwner } from "./media-operation-owner.js";
6
7
  export type { MediaShareSource } from "./media-operation-owner.js";
7
8
  export type { MediaOperationContext, MediaOperationStorage, MediaOperationBucket, MediaOperationObject, } from "./media-operation-storage.js";
@@ -1,4 +1,5 @@
1
1
  export { MediaOperationDO, } from "./media-operation-do.js";
2
2
  export { createWorkersAiMediaProvider, } from "./cloudflare/provider.js";
3
3
  export { createImagesReferenceFitter, createImagesViewFitter, } from "./cloudflare/reference-images.js";
4
+ export { createR2MediaDestination, } from "./cloudflare/r2-destination.js";
4
5
  export { MediaOperationOwner } from "./media-operation-owner.js";
@@ -1,17 +1,13 @@
1
1
  import { type MediaCatalogue } from "./model-catalog.js";
2
2
  import { type MediaAudioReferenceBytes, type MediaGenerationSettings, type MediaReferenceBytes } from "./index.js";
3
- import type { MediaAudioModelId, MediaVideoModelId } from "./model-catalog.js";
3
+ import type { MediaAudioModelId, MediaBillingUnit, MediaVideoModelId } from "./model-catalog.js";
4
4
  /** Gateway images and the verified catalog's video and audio families share Unified billing. */
5
- export type GatewayModelId = "openai/gpt-image-2" | "bytedance/seedream-5-pro" | MediaVideoModelId | MediaAudioModelId;
5
+ export type GatewayModelId = "openai/gpt-image-2" | "bytedance/seedream-5-pro" | "bria/remove-background" | "pruna/p-image-upscale" | MediaVideoModelId | MediaAudioModelId;
6
6
  export declare const isGatewayModel: (id: string) => id is GatewayModelId;
7
- /**
8
- * What one generation bills: whole images, seconds of video or music, or
9
- * blocks of {@link AUDIO_CHARACTER_BLOCK} speech characters (so a per-character
10
- * provider rate is marked up once per block, not rounded up per character).
11
- */
7
+ /** What one generation bills, in the unit its catalog entry names. */
12
8
  export type MediaUnits = Readonly<{
13
- /** One image, one whole video or music second, or one speech character block. */
14
- unit: "image" | "video_second" | "audio_second" | "audio_character_block";
9
+ /** The model's `billingUnit`. */
10
+ unit: MediaBillingUnit;
15
11
  /** Number of delivered or admitted units. */
16
12
  units: number;
17
13
  }>;
@@ -35,8 +31,47 @@ export declare function gatewayInput(settings: MediaGenerationSettings, referenc
35
31
  quality: string;
36
32
  output_format: "png" | "jpeg" | "webp";
37
33
  watermark?: never;
34
+ image?: never;
35
+ preserve_alpha?: never;
36
+ target?: never;
37
+ output_quality?: never;
38
+ enhance_details?: never;
39
+ enhance_realism?: never;
40
+ disable_safety_checker?: never;
38
41
  } | {
39
42
  prompt: string;
40
43
  size: string;
41
44
  watermark: boolean;
45
+ image?: never;
46
+ preserve_alpha?: never;
47
+ target?: never;
48
+ output_format?: never;
49
+ output_quality?: never;
50
+ enhance_details?: never;
51
+ enhance_realism?: never;
52
+ disable_safety_checker?: never;
53
+ } | {
54
+ image: string;
55
+ preserve_alpha: boolean;
56
+ prompt?: never;
57
+ size?: never;
58
+ watermark?: never;
59
+ target?: never;
60
+ output_format?: never;
61
+ output_quality?: never;
62
+ enhance_details?: never;
63
+ enhance_realism?: never;
64
+ disable_safety_checker?: never;
65
+ } | {
66
+ image: string;
67
+ target: number;
68
+ output_format: string;
69
+ output_quality: number;
70
+ enhance_details: boolean;
71
+ enhance_realism: boolean;
72
+ disable_safety_checker: boolean;
73
+ prompt?: never;
74
+ size?: never;
75
+ watermark?: never;
76
+ preserve_alpha?: never;
42
77
  };
@@ -1,11 +1,15 @@
1
- import { getGatewayModel, getMediaModel, mediaModels, MediaSettingsError, } from "./model-catalog.js";
1
+ import { getGatewayModel, getMediaModel, mediaModels, MediaSettingsError, transformMilliunits, } from "./model-catalog.js";
2
2
  import { validateMediaGenerationSettings, mediaSettingsInput, estimateVideoMilliunits, } from "./index.js";
3
+ import { mediaBillingUnit } from "./model-catalog.js";
3
4
  import { AUDIO_CHARACTER_BLOCK } from "./model-catalog.js";
4
5
  import { buildElevenLabsInput, estimateElevenLabsMilliunits, } from "./audio-providers/elevenlabs.js";
5
6
  import { imageDataUri } from "./video-providers/reference-encoding.js";
6
7
  import { videoProviderAdapters, } from "./video-providers/index.js";
7
8
  export const isGatewayModel = (id) => {
8
- if (id === "openai/gpt-image-2" || id === "bytedance/seedream-5-pro")
9
+ if (id === "openai/gpt-image-2" ||
10
+ id === "bytedance/seedream-5-pro" ||
11
+ id === "bria/remove-background" ||
12
+ id === "pruna/p-image-upscale")
9
13
  return true;
10
14
  const kind = getGatewayModel(id)?.kind;
11
15
  return kind === "video" || kind === "audio";
@@ -17,24 +21,20 @@ export function mediaUnits(settings, catalogue = mediaModels) {
17
21
  const model = getMediaModel(settings.model, catalogue);
18
22
  if (model === undefined)
19
23
  throw new MediaSettingsError("billing units require a known Media model");
20
- if (model.kind === "video") {
21
- const checked = revalidate(settings, catalogue);
22
- if (checked.durationSeconds === undefined)
23
- throw new MediaSettingsError("video settings need a duration");
24
- return { unit: "video_second", units: checked.durationSeconds };
25
- }
26
- if (model.kind === "audio") {
27
- const checked = revalidate(settings, catalogue);
28
- if (model.audio?.mode === "speech")
29
- return {
30
- unit: "audio_character_block",
31
- units: Math.ceil(checked.prompt.length / AUDIO_CHARACTER_BLOCK),
32
- };
33
- if (checked.durationSeconds === undefined)
34
- throw new MediaSettingsError("music settings need a length");
35
- return { unit: "audio_second", units: checked.durationSeconds };
36
- }
37
- return { unit: "image", units: 1 };
24
+ const unit = mediaBillingUnit(model);
25
+ if (unit === "image")
26
+ return { unit, units: 1 };
27
+ const checked = revalidate(settings, catalogue);
28
+ if (unit === "audio_character_block")
29
+ return {
30
+ unit,
31
+ units: Math.ceil(checked.prompt.length / AUDIO_CHARACTER_BLOCK),
32
+ };
33
+ if (checked.durationSeconds === undefined)
34
+ throw new MediaSettingsError(unit === "video_second"
35
+ ? "video settings need a duration"
36
+ : "music settings need a length");
37
+ return { unit, units: checked.durationSeconds };
38
38
  }
39
39
  /**
40
40
  * GPT Image 2 output tokens per image at `medium` quality. OpenAI publishes
@@ -108,6 +108,13 @@ export function estimateGatewayMilliunits(settings, references) {
108
108
  if (settings.model === "bytedance/seedream-5-pro")
109
109
  return 4_500;
110
110
  const model = getGatewayModel(settings.model);
111
+ if (model?.transform != null) {
112
+ // Published per-image prices, held in the catalog's transform facts.
113
+ const price = transformMilliunits(model.transform, settings.targetMegapixels);
114
+ if (price === undefined)
115
+ throw new MediaSettingsError(`${model.id} has no price for this output size`);
116
+ return price;
117
+ }
111
118
  if (model?.kind === "video")
112
119
  return estimateVideoMilliunits(settings);
113
120
  if (model?.kind === "audio")
@@ -149,6 +156,31 @@ export function gatewayInput(settings, references = [], outputFormat = "png", au
149
156
  watermark: false,
150
157
  };
151
158
  }
159
+ if (settings.model === "bria/remove-background" ||
160
+ settings.model === "pruna/p-image-upscale") {
161
+ const [source, ...extra] = references;
162
+ if (source === undefined || extra.length > 0)
163
+ throw new MediaSettingsError(`${settings.model} takes one source image`);
164
+ if (source.format !== "png" && source.format !== "jpeg")
165
+ throw new MediaSettingsError(`${settings.model} accepts png or jpeg source images`);
166
+ // Always the bytes as a data URI, never a URL to our storage.
167
+ // https://developers.cloudflare.com/ai/models/bria/remove-background/
168
+ const image = imageDataUri(source);
169
+ if (settings.model === "bria/remove-background")
170
+ return { image, preserve_alpha: true };
171
+ // Every field is marked required on the model page; the values are its
172
+ // defaults except the output encoding (see the catalog entry).
173
+ // https://developers.cloudflare.com/ai/models/pruna/p-image-upscale/
174
+ return {
175
+ image,
176
+ target: settings.targetMegapixels ?? 4,
177
+ output_format: "webp",
178
+ output_quality: 90,
179
+ enhance_details: false,
180
+ enhance_realism: false,
181
+ disable_safety_checker: false,
182
+ };
183
+ }
152
184
  const checked = revalidate(settings);
153
185
  const model = getGatewayModel(checked.model);
154
186
  if (model?.audio != null)
package/dist/index.d.ts CHANGED
@@ -4,8 +4,8 @@ import { type MediaVideoReferenceRole, type MediaCatalogue, type MediaVideoResol
4
4
  export { mediaFailureStageSchema } from "./execution-error.js";
5
5
  export { MAX_AUDIO_REFERENCE_BODY_BYTES, MAX_AUDIO_REFERENCE_BYTES, } from "./audio-reference-types.js";
6
6
  export type { AudioReferenceMimeType, MediaAudioReferenceBytes, } from "./audio-reference-types.js";
7
- export { MAX_MEDIA_PROMPT_LENGTH, getMediaModel, getGatewayModel, MAX_REFERENCE_COUNT, listMediaModels, mediaCatalogueSchema, mediaCatalogueModelSchema, parseMediaCatalogue, mediaModelInputSchema, mediaModelSchema, mediaRequestedImageFormatSchema, mediaModels, mediaModelTierSchema, MediaSettingsError, mediaVideoModelIdSchema, mediaVideoResolutionSchema, mediaVideoAspectRatioSchema, mediaVideoReferenceRoleSchema, mediaVideoFormatSchema, mediaVideoSchema, mediaAudioModelIdSchema, mediaAudioSchema, mediaAudioVoiceSchema, AUDIO_CHARACTER_BLOCK, } from "./model-catalog.js";
8
- export type { MediaCatalogue, MediaCatalogueModel, MediaModel, MediaModelInput, MediaModelTier, MediaVideoModelId, MediaVideoResolution, MediaVideoAspectRatio, MediaVideoReferenceRole, MediaVideoModel, MediaVideoFormat, MediaAudioModelId, MediaAudioModel, MediaAudioVoice, } from "./model-catalog.js";
7
+ export { MAX_MEDIA_PROMPT_LENGTH, getMediaModel, getGatewayModel, MAX_REFERENCE_COUNT, listMediaModels, mediaCatalogueSchema, mediaCatalogueModelSchema, parseMediaCatalogue, mediaModelInputSchema, mediaModelSchema, mediaRequestedImageFormatSchema, mediaModels, mediaModelTierSchema, MediaSettingsError, mediaVideoModelIdSchema, mediaVideoResolutionSchema, mediaVideoAspectRatioSchema, mediaVideoReferenceRoleSchema, mediaVideoFormatSchema, mediaVideoSchema, mediaAudioModelIdSchema, mediaAudioSchema, mediaAudioVoiceSchema, mediaBillingUnitSchema, AUDIO_CHARACTER_BLOCK, mediaTransformSchema, mediaTransformOperationSchema, } from "./model-catalog.js";
8
+ export type { MediaTransform, MediaTransformOperation, MediaCatalogue, MediaBillingUnit, MediaCatalogueModel, MediaModel, MediaModelInput, MediaModelTier, MediaVideoModelId, MediaVideoResolution, MediaVideoAspectRatio, MediaVideoReferenceRole, MediaVideoModel, MediaVideoFormat, MediaAudioModelId, MediaAudioModel, MediaAudioVoice, } from "./model-catalog.js";
9
9
  /** A reference file selected by the host, with its destination identity and path. */
10
10
  export type MediaReference = Readonly<{
11
11
  /** Host-admitted destination or reference identity. */
@@ -48,6 +48,8 @@ export type MediaGenerationSettings = Readonly<{
48
48
  steps?: number;
49
49
  /** Video and music models only: output length in whole seconds. */
50
50
  durationSeconds?: number;
51
+ /** Upscale only: the output size in megapixels. */
52
+ targetMegapixels?: number;
51
53
  /** Speech models only: the catalog voice that reads the prompt. */
52
54
  voiceId?: string;
53
55
  /** Video resolution selector, normalized from the catalog. */
@@ -108,6 +110,7 @@ export declare const mediaGenerationSettingsSchema: z.ZodObject<{
108
110
  height: z.ZodOptional<z.ZodNumber>;
109
111
  steps: z.ZodOptional<z.ZodNumber>;
110
112
  durationSeconds: z.ZodOptional<z.ZodNumber>;
113
+ targetMegapixels: z.ZodOptional<z.ZodNumber>;
111
114
  voiceId: z.ZodOptional<z.ZodString>;
112
115
  resolution: z.ZodOptional<z.ZodEnum<{
113
116
  readonly p480: "480p";
@@ -150,6 +153,7 @@ export declare const mediaGenerationSelectionSchema: z.ZodObject<{
150
153
  height: z.ZodOptional<z.ZodNumber>;
151
154
  steps: z.ZodOptional<z.ZodNumber>;
152
155
  durationSeconds: z.ZodOptional<z.ZodNumber>;
156
+ targetMegapixels: z.ZodOptional<z.ZodNumber>;
153
157
  voiceId: z.ZodOptional<z.ZodString>;
154
158
  resolution: z.ZodOptional<z.ZodEnum<{
155
159
  readonly p480: "480p";