@fungi.computer/darkroom 0.9.2 → 0.11.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.
Files changed (45) hide show
  1. package/README.md +130 -6
  2. package/dist/app-media-contracts.d.ts +104 -0
  3. package/dist/browser.d.ts +1 -0
  4. package/dist/browser.js +1 -0
  5. package/dist/cloudflare/provider.d.ts +5 -4
  6. package/dist/cloudflare/provider.js +20 -9
  7. package/dist/cloudflare/r2-destination.d.ts +50 -0
  8. package/dist/cloudflare/r2-destination.js +59 -0
  9. package/dist/cloudflare.d.ts +3 -2
  10. package/dist/cloudflare.js +1 -0
  11. package/dist/gateway-models.d.ts +44 -9
  12. package/dist/gateway-models.js +52 -20
  13. package/dist/index.d.ts +12 -2
  14. package/dist/index.js +81 -38
  15. package/dist/media-binding.d.ts +6 -0
  16. package/dist/media-content-type.d.ts +5 -0
  17. package/dist/media-content-type.js +49 -0
  18. package/dist/media-generation.js +2 -0
  19. package/dist/media-operation-contract.d.ts +13 -1
  20. package/dist/media-operation-do.d.ts +6 -0
  21. package/dist/media-operation-do.js +37 -2
  22. package/dist/media-operation-owner.d.ts +93 -5
  23. package/dist/media-operation-owner.js +250 -46
  24. package/dist/media-operation-storage.d.ts +18 -4
  25. package/dist/media-operation.js +30 -4
  26. package/dist/media-path.d.ts +3 -0
  27. package/dist/media-path.js +7 -0
  28. package/dist/media-run-lifetime.d.ts +5 -0
  29. package/dist/media-run-lifetime.js +5 -0
  30. package/dist/media-written.d.ts +22 -0
  31. package/dist/media-written.js +20 -0
  32. package/dist/model-catalog.d.ts +226 -0
  33. package/dist/model-catalog.js +254 -9
  34. package/dist/provenance.d.ts +5 -1
  35. package/dist/provenance.js +2 -1
  36. package/dist/reference-read.d.ts +24 -0
  37. package/dist/reference-read.js +26 -0
  38. package/dist/server.d.ts +58 -2
  39. package/dist/server.js +49 -5
  40. package/docs/api/app-media-contracts.md +49 -0
  41. package/docs/api/browser.md +15 -4
  42. package/docs/api/cloudflare.md +254 -5
  43. package/docs/api/index.md +346 -62
  44. package/docs/api/server.md +524 -66
  45. package/package.json +2 -2
package/README.md CHANGED
@@ -142,9 +142,11 @@ validates every request against the active provider's catalogue, so `fal-ai/...`
142
142
  ids are accepted by your provider and refused by the gateway's.
143
143
 
144
144
  Each entry carries the per-model bounds the validator enforces: prompt length,
145
- dimensions or exact sizes, steps, reference counts, and for video the durations,
146
- resolution/aspect formats and per-second prices. Mark a video model's
147
- `video.provider` as `"host"`: your provider owns that model's wire grammar.
145
+ dimensions or exact sizes, steps, prompt `guidance` (bounds and default, or
146
+ `null` when the model takes none; a caller's explicit value overrides the
147
+ default), reference counts, and for video the durations, resolution/aspect
148
+ formats and per-second prices. Mark a video model's `video.provider` as
149
+ `"host"`: your provider owns that model's wire grammar.
148
150
 
149
151
  ```ts
150
152
  import {
@@ -176,6 +178,7 @@ export const falCatalogue = parseMediaCatalogue([
176
178
  steps: "fixed",
177
179
  maxSteps: null,
178
180
  defaultSteps: null,
181
+ guidance: null,
179
182
  referenceField: "image_url",
180
183
  maxReferences: 1,
181
184
  referenceDimension: null,
@@ -262,6 +265,35 @@ const service = createMediaService({
262
265
  settings outside its bounds, is refused before billing or dispatch. The
263
266
  gateway's own models are refused by this provider the same way.
264
267
 
268
+ ### What a model entry tells an App
269
+
270
+ `GET /models` and `listMediaModels()` return the same typed entry
271
+ (`MediaModel`), so an App draws each model's controls from it and keeps no
272
+ per-model rules of its own. Where the host mediates, it may remove a reference
273
+ capability it cannot serve (`input.maxReferences` 0, `video.audioReferences`
274
+ null) and adds `priceEstimate`.
275
+
276
+ | An App needs | Field |
277
+ | --------------------- | --------------------------------------------------------------------------------------------------------------------- |
278
+ | Kind | `kind`: `image`, `video` or `audio` |
279
+ | Sizes and aspects | `sizes` (`WIDTHxHEIGHT` list, null for any size within `input.maxDimension`); `video.formats` (resolution and aspect) |
280
+ | Duration options | `video.durations`, `video.defaultSeconds`; music `audio.seconds` |
281
+ | Maximum prompt length | `maxPromptLength` (characters) |
282
+ | Reference images | `input.maxReferences`; video `video.maxReferenceImages` and `video.referenceResolutions` |
283
+ | Video reference roles | `video.referenceRoles` (`first-frame`, `last-frame`, `reference`) |
284
+ | Audio references | `video.audioReferences` (`{max, totalSeconds}` or null) |
285
+ | Sound on video | `video.supportsAudio`, `video.defaultGenerateAudio` |
286
+ | Price basis | `billingUnit`: `image`, `video_second`, `audio_second` or `audio_character_block` |
287
+
288
+ `billingUnit` names what one generation is billed in; it is derived from the
289
+ model's kind (and speech or music mode) by the same rule `mediaUnits` uses, so
290
+ it cannot drift from billing. Cost per unit depends on the settings: output
291
+ size, steps and references for images, resolution and sound for video. An App
292
+ therefore shows `priceEstimate` (a labelled estimate at the model's defaults,
293
+ added by hosts that quote) and asks its host to quote the exact settings, which
294
+ runs `quoteMediaGeneration`, before it shows a final number. Speech bills one
295
+ unit per 100 characters.
296
+
265
297
  ## API reference
266
298
 
267
299
  | Import | Purpose |
@@ -322,11 +354,105 @@ add an `AI` binding to your host. `createImagesReferenceFitter` prepares bounded
322
354
  reference images through an Images binding, using the selected catalog model
323
355
  passed to the fitter. Your host authorizes each reference read.
324
356
 
357
+ Saved PNG, JPEG and WebP images carry the AI marker, print ID, model and
358
+ creation time in XMP. The prompt is private by default: it is embedded as
359
+ `fungi:prompt` only when the host opts in per generation, with
360
+ `embedPrompt: true` on `generateMedia`'s request, or `embedPrompt: true` on the
361
+ `createMediaService` host for its `/generate` route. Omit it to keep prompts out
362
+ of generated files. `embedProvenance` takes `prompt: string | null` in its
363
+ facts; `null` leaves it out.
364
+
325
365
  `stripPrivateProvenance(bytes)` from `provenance` removes prompt and lineage
326
366
  metadata while preserving the AI marker, print ID and image encoding. It returns
327
367
  bytes, MIME type and filename extension. The public XMP format uses
328
368
  `https://fungi.computer/ns/provenance/1.0/`.
329
369
 
370
+ ## Use your own R2 bucket
371
+
372
+ Keep reference images and generated output in a bucket you already own.
373
+ `createR2MediaDestination` (from `@fungi.computer/darkroom/cloudflare`) is the
374
+ whole destination: object keys are the paths, and URLs are never accepted.
375
+
376
+ ```ts
377
+ import { createMediaService } from "@fungi.computer/darkroom/server";
378
+ import {
379
+ createImagesReferenceFitter,
380
+ createR2MediaDestination,
381
+ createWorkersAiMediaProvider,
382
+ } from "@fungi.computer/darkroom/cloudflare";
383
+
384
+ const app = createMediaService({
385
+ scope: {
386
+ actorId,
387
+ namespace: "studio",
388
+ owner: "media",
389
+ destinationId: "studio-bucket",
390
+ },
391
+ operations: env.MEDIA_OPERATION, // MediaOperationDO binding
392
+ provider: createWorkersAiMediaProvider(env.AI),
393
+ metering: "unmetered",
394
+ destination: createR2MediaDestination({
395
+ bucket: env.STUDIO_BUCKET, // your R2 binding
396
+ destinationId: "studio-bucket", // a reference must carry this same id
397
+ fit: createImagesReferenceFitter(env.IMAGES),
398
+ authorize: (key) => assertActorMayUse(actorId, key), // your permission check
399
+ }),
400
+ });
401
+ ```
402
+
403
+ Select a reference with `{ computerId: "studio-bucket", path: "<object key>" }`.
404
+ The field is named `computerId` for historical reasons; it carries your
405
+ destination id.
406
+
407
+ The host still owns who may touch which key (`authorize`, which runs before
408
+ every dispatch, write and reference read; omitted, any valid key in the bucket
409
+ is allowed), the destination id it admits, the provider account and its billing.
410
+
411
+ Darkroom guarantees that every key is validated as a path, a reference for
412
+ another destination is refused, and a missing, empty or oversized reference (8
413
+ MiB for images, 16 MiB for audio) is refused. These refusals, and a failed
414
+ `authorize`, happen before any paid dispatch. Generation is priced from the
415
+ validated settings. Output is saved with its content type, and a retry with the
416
+ same request ID reuses the saved output instead of calling the provider again. A
417
+ runnable Worker is in [`examples/standalone`](examples/standalone).
418
+
419
+ ## Recover or erase retained results
420
+
421
+ A generation keeps three things by operation (request) id: the exact provider
422
+ bytes in `APP_ARTIFACTS` (`media-output/v1/<operation>`), any background
423
+ reference copies, and the file it wrote to your destination path. From
424
+ `@fungi.computer/darkroom/server`, all scoped to `host.scope.namespace` (another
425
+ namespace is refused):
426
+
427
+ - `retainedMedia(host, requestId)` lists them: the state, the destination path
428
+ and the retained output's size, format and content type. It finds output a
429
+ crash left unrecorded (written to R2, never noted in SQL). It returns null
430
+ once erased.
431
+ - `readRetainedMedia(host, requestId)` returns those exact provider bytes and
432
+ their format, before any provenance, so you can re-save a result whose
433
+ destination write was lost.
434
+ - `eraseMediaOperation(host, requestId)` erases all of it, even mid-generation.
435
+ The operation is marked erased first, durably, and the marker is never
436
+ removed: an attempt still running, or a lease recovered later, can no longer
437
+ write or transition, a restart cannot resurrect it, and output that lands
438
+ after the mark is deleted. Before each destination write the operation records
439
+ the SHA-256 of the bytes it is about to write; erasure deletes the destination
440
+ file only while it still holds those bytes (`destinationFile` reports
441
+ `"removed"`, `"absent"`, `"not-ours"` for a path reused for something else, or
442
+ `"kept"`). A generation erased before it finished has its billing hold settled
443
+ at zero units (`metering.settle`, idempotent). It returns `clear`, and a put
444
+ still in flight or a failed late delete keeps `clear` false: call it again
445
+ until `clear` is true.
446
+
447
+ Your destination supplies `remove(path, { sha256 })`, required. Use
448
+ `removeMediaIfWritten` to compare and delete, or return `"kept"` when the
449
+ destination cannot delete files. `createR2MediaDestination` implements it.
450
+ `MediaOperationDO` exposes `retained(namespace, requestId)`,
451
+ `readRetained(namespace, requestId)` and `erase(namespace, requestId, policy)`.
452
+ `policy` is `"abort-active"` (default) or `"refuse-active"`, which refuses a
453
+ running operation atomically with the erase for a host that waits for
454
+ inactivity. `preflightErasure` remains an optional read-only check.
455
+
330
456
  ## Limits
331
457
 
332
458
  References are bounded to four files and 8 MiB per image. Image-model references
@@ -488,9 +614,7 @@ through the same durable alarm as video: HTTP returns 202 until the retained MP3
488
614
  is ready, and the output has no embedded provenance. Hub public sharing does not
489
615
  cover audio. The MEDIA binding accepts `kind: "audio"` with `prompt`, `voiceId`
490
616
  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.
617
+ `/models` listing includes audio models with `kind: "audio"`.
494
618
 
495
619
  Video models declare `video.audioReferences` (`{max, totalSeconds}`, or null).
496
620
  Only Seedance 2.5 sets it, at 10 clips and 30 seconds, from its Cloudflare input
@@ -15,7 +15,9 @@ export declare const mediaModelPriceEstimateSchema: z.ZodObject<{
15
15
  width: z.ZodOptional<z.ZodNumber>;
16
16
  height: z.ZodOptional<z.ZodNumber>;
17
17
  steps: z.ZodOptional<z.ZodNumber>;
18
+ guidance: z.ZodOptional<z.ZodNumber>;
18
19
  durationSeconds: z.ZodOptional<z.ZodNumber>;
20
+ targetMegapixels: z.ZodOptional<z.ZodNumber>;
19
21
  voiceId: z.ZodOptional<z.ZodString>;
20
22
  resolution: z.ZodOptional<z.ZodEnum<{
21
23
  readonly p480: "480p";
@@ -90,6 +92,11 @@ export declare const mediaCatalogModelSchema: z.ZodReadonly<z.ZodObject<{
90
92
  }>;
91
93
  maxSteps: z.ZodNullable<z.ZodNumber>;
92
94
  defaultSteps: z.ZodNullable<z.ZodNumber>;
95
+ guidance: z.ZodDefault<z.ZodNullable<z.ZodReadonly<z.ZodObject<{
96
+ min: z.ZodNumber;
97
+ max: z.ZodNumber;
98
+ default: z.ZodNumber;
99
+ }, z.core.$strict>>>>;
93
100
  referenceField: z.ZodNullable<z.ZodString>;
94
101
  maxReferences: z.ZodNumber;
95
102
  referenceDimension: z.ZodNullable<z.ZodNumber>;
@@ -194,6 +201,33 @@ export declare const mediaCatalogModelSchema: z.ZodReadonly<z.ZodObject<{
194
201
  }, z.core.$strict>>>;
195
202
  milliunitsPerUnit: z.ZodNumber;
196
203
  }, z.core.$strict>>>>;
204
+ billingUnit: z.ZodEnum<{
205
+ readonly image: "image";
206
+ readonly video_second: "video_second";
207
+ readonly audio_second: "audio_second";
208
+ readonly audio_character_block: "audio_character_block";
209
+ }>;
210
+ transform: z.ZodNullable<z.ZodLazy<z.ZodReadonly<z.ZodObject<{
211
+ operation: z.ZodEnum<{
212
+ readonly remove_background: "remove_background";
213
+ readonly upscale: "upscale";
214
+ }>;
215
+ source: z.ZodReadonly<z.ZodObject<{
216
+ formats: z.ZodReadonly<z.ZodArray<z.ZodEnum<{
217
+ readonly png: "png";
218
+ readonly jpeg: "jpeg";
219
+ readonly webp: "webp";
220
+ }>>>;
221
+ maxBytes: z.ZodNumber;
222
+ maxPixels: z.ZodNumber;
223
+ }, z.core.$strict>>;
224
+ defaultMegapixels: z.ZodNullable<z.ZodNumber>;
225
+ milliunits: z.ZodNullable<z.ZodNumber>;
226
+ sizes: z.ZodReadonly<z.ZodArray<z.ZodReadonly<z.ZodObject<{
227
+ megapixels: z.ZodNumber;
228
+ milliunits: z.ZodNumber;
229
+ }, z.core.$strict>>>>;
230
+ }, z.core.$strict>>>>;
197
231
  priceEstimate: z.ZodOptional<z.ZodObject<{
198
232
  kind: z.ZodLiteral<"estimate">;
199
233
  basis: z.ZodEnum<{
@@ -209,7 +243,9 @@ export declare const mediaCatalogModelSchema: z.ZodReadonly<z.ZodObject<{
209
243
  width: z.ZodOptional<z.ZodNumber>;
210
244
  height: z.ZodOptional<z.ZodNumber>;
211
245
  steps: z.ZodOptional<z.ZodNumber>;
246
+ guidance: z.ZodOptional<z.ZodNumber>;
212
247
  durationSeconds: z.ZodOptional<z.ZodNumber>;
248
+ targetMegapixels: z.ZodOptional<z.ZodNumber>;
213
249
  voiceId: z.ZodOptional<z.ZodString>;
214
250
  resolution: z.ZodOptional<z.ZodEnum<{
215
251
  readonly p480: "480p";
@@ -285,6 +321,11 @@ export declare const mediaModelsSchema: z.ZodLazy<z.ZodArray<z.ZodReadonly<z.Zod
285
321
  }>;
286
322
  maxSteps: z.ZodNullable<z.ZodNumber>;
287
323
  defaultSteps: z.ZodNullable<z.ZodNumber>;
324
+ guidance: z.ZodDefault<z.ZodNullable<z.ZodReadonly<z.ZodObject<{
325
+ min: z.ZodNumber;
326
+ max: z.ZodNumber;
327
+ default: z.ZodNumber;
328
+ }, z.core.$strict>>>>;
288
329
  referenceField: z.ZodNullable<z.ZodString>;
289
330
  maxReferences: z.ZodNumber;
290
331
  referenceDimension: z.ZodNullable<z.ZodNumber>;
@@ -389,6 +430,33 @@ export declare const mediaModelsSchema: z.ZodLazy<z.ZodArray<z.ZodReadonly<z.Zod
389
430
  }, z.core.$strict>>>;
390
431
  milliunitsPerUnit: z.ZodNumber;
391
432
  }, z.core.$strict>>>>;
433
+ billingUnit: z.ZodEnum<{
434
+ readonly image: "image";
435
+ readonly video_second: "video_second";
436
+ readonly audio_second: "audio_second";
437
+ readonly audio_character_block: "audio_character_block";
438
+ }>;
439
+ transform: z.ZodNullable<z.ZodLazy<z.ZodReadonly<z.ZodObject<{
440
+ operation: z.ZodEnum<{
441
+ readonly remove_background: "remove_background";
442
+ readonly upscale: "upscale";
443
+ }>;
444
+ source: z.ZodReadonly<z.ZodObject<{
445
+ formats: z.ZodReadonly<z.ZodArray<z.ZodEnum<{
446
+ readonly png: "png";
447
+ readonly jpeg: "jpeg";
448
+ readonly webp: "webp";
449
+ }>>>;
450
+ maxBytes: z.ZodNumber;
451
+ maxPixels: z.ZodNumber;
452
+ }, z.core.$strict>>;
453
+ defaultMegapixels: z.ZodNullable<z.ZodNumber>;
454
+ milliunits: z.ZodNullable<z.ZodNumber>;
455
+ sizes: z.ZodReadonly<z.ZodArray<z.ZodReadonly<z.ZodObject<{
456
+ megapixels: z.ZodNumber;
457
+ milliunits: z.ZodNumber;
458
+ }, z.core.$strict>>>>;
459
+ }, z.core.$strict>>>>;
392
460
  priceEstimate: z.ZodOptional<z.ZodObject<{
393
461
  kind: z.ZodLiteral<"estimate">;
394
462
  basis: z.ZodEnum<{
@@ -404,7 +472,9 @@ export declare const mediaModelsSchema: z.ZodLazy<z.ZodArray<z.ZodReadonly<z.Zod
404
472
  width: z.ZodOptional<z.ZodNumber>;
405
473
  height: z.ZodOptional<z.ZodNumber>;
406
474
  steps: z.ZodOptional<z.ZodNumber>;
475
+ guidance: z.ZodOptional<z.ZodNumber>;
407
476
  durationSeconds: z.ZodOptional<z.ZodNumber>;
477
+ targetMegapixels: z.ZodOptional<z.ZodNumber>;
408
478
  voiceId: z.ZodOptional<z.ZodString>;
409
479
  resolution: z.ZodOptional<z.ZodEnum<{
410
480
  readonly p480: "480p";
@@ -643,6 +713,11 @@ export declare const appMediaModelsOutcomeSchema: z.ZodUnion<readonly [z.ZodLazy
643
713
  }>;
644
714
  maxSteps: z.ZodNullable<z.ZodNumber>;
645
715
  defaultSteps: z.ZodNullable<z.ZodNumber>;
716
+ guidance: z.ZodDefault<z.ZodNullable<z.ZodReadonly<z.ZodObject<{
717
+ min: z.ZodNumber;
718
+ max: z.ZodNumber;
719
+ default: z.ZodNumber;
720
+ }, z.core.$strict>>>>;
646
721
  referenceField: z.ZodNullable<z.ZodString>;
647
722
  maxReferences: z.ZodNumber;
648
723
  referenceDimension: z.ZodNullable<z.ZodNumber>;
@@ -747,6 +822,33 @@ export declare const appMediaModelsOutcomeSchema: z.ZodUnion<readonly [z.ZodLazy
747
822
  }, z.core.$strict>>>;
748
823
  milliunitsPerUnit: z.ZodNumber;
749
824
  }, z.core.$strict>>>>;
825
+ billingUnit: z.ZodEnum<{
826
+ readonly image: "image";
827
+ readonly video_second: "video_second";
828
+ readonly audio_second: "audio_second";
829
+ readonly audio_character_block: "audio_character_block";
830
+ }>;
831
+ transform: z.ZodNullable<z.ZodLazy<z.ZodReadonly<z.ZodObject<{
832
+ operation: z.ZodEnum<{
833
+ readonly remove_background: "remove_background";
834
+ readonly upscale: "upscale";
835
+ }>;
836
+ source: z.ZodReadonly<z.ZodObject<{
837
+ formats: z.ZodReadonly<z.ZodArray<z.ZodEnum<{
838
+ readonly png: "png";
839
+ readonly jpeg: "jpeg";
840
+ readonly webp: "webp";
841
+ }>>>;
842
+ maxBytes: z.ZodNumber;
843
+ maxPixels: z.ZodNumber;
844
+ }, z.core.$strict>>;
845
+ defaultMegapixels: z.ZodNullable<z.ZodNumber>;
846
+ milliunits: z.ZodNullable<z.ZodNumber>;
847
+ sizes: z.ZodReadonly<z.ZodArray<z.ZodReadonly<z.ZodObject<{
848
+ megapixels: z.ZodNumber;
849
+ milliunits: z.ZodNumber;
850
+ }, z.core.$strict>>>>;
851
+ }, z.core.$strict>>>>;
750
852
  priceEstimate: z.ZodOptional<z.ZodObject<{
751
853
  kind: z.ZodLiteral<"estimate">;
752
854
  basis: z.ZodEnum<{
@@ -762,7 +864,9 @@ export declare const appMediaModelsOutcomeSchema: z.ZodUnion<readonly [z.ZodLazy
762
864
  width: z.ZodOptional<z.ZodNumber>;
763
865
  height: z.ZodOptional<z.ZodNumber>;
764
866
  steps: z.ZodOptional<z.ZodNumber>;
867
+ guidance: z.ZodOptional<z.ZodNumber>;
765
868
  durationSeconds: z.ZodOptional<z.ZodNumber>;
869
+ targetMegapixels: z.ZodOptional<z.ZodNumber>;
766
870
  voiceId: z.ZodOptional<z.ZodString>;
767
871
  resolution: z.ZodOptional<z.ZodEnum<{
768
872
  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,22 @@ 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
+ guidance?: number;
15
16
  durationSeconds?: number;
17
+ targetMegapixels?: number;
16
18
  voiceId?: string;
17
19
  resolution?: import("../model-catalog.js").MediaVideoResolution;
18
20
  aspectRatio?: import("../model-catalog.js").MediaVideoAspectRatio;
19
21
  generateAudio?: boolean;
20
- references?: readonly import("../index.js").MediaReference[];
21
22
  audioReferences?: readonly import("../index.js").MediaReference[];
22
- }>;
23
+ };
23
24
  /** Estimated provider milliunits of a cent for these exact settings. */
24
25
  costMilliunits: number;
25
26
  };
@@ -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,50 @@
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
+ /** Delete one object; absent keys are not an error. */
19
+ delete(key: string): Promise<void>;
20
+ };
21
+ /** Host-owned R2 destination configuration. */
22
+ export type R2MediaDestinationOptions = Readonly<{
23
+ /** The bucket holding reference images and generated output. */
24
+ bucket: MediaR2Bucket;
25
+ /**
26
+ * The destination identity the host admitted. A reference must carry this
27
+ * same value (in `MediaReference.computerId`) or it is refused.
28
+ */
29
+ destinationId: string;
30
+ /** The Images-binding reference fitter, from `createImagesReferenceFitter`. */
31
+ fit: ReferenceImageFitter;
32
+ /**
33
+ * The host's own permission check for one object key. It runs before every
34
+ * dispatch, write and reference read; throw to refuse. Omitted, any valid
35
+ * key in `bucket` is allowed.
36
+ */
37
+ authorize?: ((key: string) => Promise<void> | void) | undefined;
38
+ }>;
39
+ /** The host destination over an R2 bucket, with both reference readers present. */
40
+ export type R2MediaDestination = MediaServiceHost["destination"] & Readonly<{
41
+ /** Authorize, read and fit one reference image for the catalog model. */
42
+ readReference: (reference: MediaReference, model: string) => Promise<MediaReferenceBytes>;
43
+ /** Authorize and read the raw bytes of one reference audio clip. */
44
+ readAudioReference: (reference: MediaReference) => Promise<Uint8Array>;
45
+ }>;
46
+ /**
47
+ * A Media destination over one R2 bucket: object keys are the paths, validated
48
+ * with Darkroom's path schema. Never accepts URLs.
49
+ */
50
+ export declare function createR2MediaDestination(options: R2MediaDestinationOptions): R2MediaDestination;
@@ -0,0 +1,59 @@
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
+ import { removeMediaIfWritten } from "../media-written.js";
6
+ /**
7
+ * A Media destination over one R2 bucket: object keys are the paths, validated
8
+ * with Darkroom's path schema. Never accepts URLs.
9
+ */
10
+ export function createR2MediaDestination(options) {
11
+ const { bucket, destinationId, fit } = options;
12
+ const authorize = async (key) => {
13
+ const parsed = mediaPathSchema.safeParse(key);
14
+ if (!parsed.success)
15
+ throw new MediaSettingsError("R2 object key is not a valid path");
16
+ await options.authorize?.(parsed.data);
17
+ };
18
+ const read = (kind, reference) => readHostReference({
19
+ reference,
20
+ destinationId,
21
+ kind,
22
+ open: async (key) => {
23
+ await authorize(key);
24
+ const object = await bucket.get(key);
25
+ if (object === null)
26
+ return null;
27
+ return {
28
+ size: object.size,
29
+ bytes: async () => new Uint8Array(await object.arrayBuffer()),
30
+ };
31
+ },
32
+ });
33
+ return {
34
+ authorize,
35
+ write: async (key, bytes) => {
36
+ await authorize(key);
37
+ await bucket.put(key, bytes, {
38
+ httpMetadata: { contentType: mediaContentType(bytes) },
39
+ });
40
+ },
41
+ remove: async (key, written) => {
42
+ await authorize(key);
43
+ return removeMediaIfWritten({
44
+ read: async () => {
45
+ const object = await bucket.get(key);
46
+ return object === null
47
+ ? null
48
+ : new Uint8Array(await object.arrayBuffer());
49
+ },
50
+ delete: () => bucket.delete(key),
51
+ }, written.sha256);
52
+ },
53
+ readReference: async (reference, model) => ({
54
+ ...(await fit(await read("image", reference), model)),
55
+ filename: referenceFilename(reference),
56
+ }),
57
+ readAudioReference: (reference) => read("audio", reference),
58
+ };
59
+ }
@@ -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
- export type { MediaShareSource } from "./media-operation-owner.js";
7
- export type { MediaOperationContext, MediaOperationStorage, MediaOperationBucket, MediaOperationObject, } from "./media-operation-storage.js";
7
+ export type { MediaErasure, MediaRetained, MediaRetainedBytes, MediaErasePolicy, MediaShareSource, } from "./media-operation-owner.js";
8
+ export type { MediaOperationContext, MediaOperationStorage, MediaErasureMarker, 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
  };