@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
@@ -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. */
@@ -46,8 +46,12 @@ export type MediaGenerationSettings = Readonly<{
46
46
  height?: number;
47
47
  /** Model-specific inference steps. */
48
48
  steps?: number;
49
+ /** Prompt guidance for models that take it; the catalog default when omitted. */
50
+ guidance?: number;
49
51
  /** Video and music models only: output length in whole seconds. */
50
52
  durationSeconds?: number;
53
+ /** Upscale only: the output size in megapixels. */
54
+ targetMegapixels?: number;
51
55
  /** Speech models only: the catalog voice that reads the prompt. */
52
56
  voiceId?: string;
53
57
  /** Video resolution selector, normalized from the catalog. */
@@ -107,7 +111,9 @@ export declare const mediaGenerationSettingsSchema: z.ZodObject<{
107
111
  width: z.ZodOptional<z.ZodNumber>;
108
112
  height: z.ZodOptional<z.ZodNumber>;
109
113
  steps: z.ZodOptional<z.ZodNumber>;
114
+ guidance: z.ZodOptional<z.ZodNumber>;
110
115
  durationSeconds: z.ZodOptional<z.ZodNumber>;
116
+ targetMegapixels: z.ZodOptional<z.ZodNumber>;
111
117
  voiceId: z.ZodOptional<z.ZodString>;
112
118
  resolution: z.ZodOptional<z.ZodEnum<{
113
119
  readonly p480: "480p";
@@ -149,7 +155,9 @@ export declare const mediaGenerationSelectionSchema: z.ZodObject<{
149
155
  width: z.ZodOptional<z.ZodNumber>;
150
156
  height: z.ZodOptional<z.ZodNumber>;
151
157
  steps: z.ZodOptional<z.ZodNumber>;
158
+ guidance: z.ZodOptional<z.ZodNumber>;
152
159
  durationSeconds: z.ZodOptional<z.ZodNumber>;
160
+ targetMegapixels: z.ZodOptional<z.ZodNumber>;
153
161
  voiceId: z.ZodOptional<z.ZodString>;
154
162
  resolution: z.ZodOptional<z.ZodEnum<{
155
163
  readonly p480: "480p";
@@ -365,6 +373,8 @@ export type MediaJsonBody = Readonly<{
365
373
  steps?: number;
366
374
  /** Steps for models using the num_steps field. */
367
375
  num_steps?: number;
376
+ /** Prompt guidance for models that take it. */
377
+ guidance?: number;
368
378
  }>;
369
379
  /** A model-specific JSON body or multipart form ready for transport. */
370
380
  export type MediaProviderPayload = Readonly<{
package/dist/index.js CHANGED
@@ -1,10 +1,11 @@
1
1
  import * as z from "zod";
2
2
  import { reportCatchFailure } from "./failure.js";
3
+ import { sniffImageFormat } from "./media-content-type.js";
3
4
  import { referenceImageSizeIsValid } from "./reference-image-size.js";
4
- import { getGatewayModel, getMediaModel, mediaAudioModelIdSchema, MAX_REFERENCE_COUNT, MediaSettingsError, mediaModels, mediaVideoModelIdSchema, mediaVideoResolutionSchema, mediaVideoAspectRatioSchema, mediaVideoReferenceRoleSchema, MAX_MEDIA_PROMPT_LENGTH, } from "./model-catalog.js";
5
+ import { getGatewayModel, getMediaModel, mediaAudioModelIdSchema, MAX_REFERENCE_COUNT, MediaSettingsError, mediaModels, mediaVideoModelIdSchema, mediaVideoResolutionSchema, mediaVideoAspectRatioSchema, mediaVideoReferenceRoleSchema, MAX_MEDIA_PROMPT_LENGTH, transformMilliunits, } from "./model-catalog.js";
5
6
  export { mediaFailureStageSchema } from "./execution-error.js";
6
7
  export { MAX_AUDIO_REFERENCE_BODY_BYTES, MAX_AUDIO_REFERENCE_BYTES, } 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 { 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
9
  /** The long-edge bounds a viewer may ask for when fitting an image to look at. */
9
10
  export const MIN_VIEW_DIMENSION = 256;
10
11
  /** Maximum long-edge size accepted by an image viewer, in pixels. */
@@ -59,8 +60,12 @@ export const mediaGenerationSettingsSchema = z
59
60
  height: z.number().int().min(1).max(5_040).optional(),
60
61
  /** Model-specific inference step count. */
61
62
  steps: z.number().int().optional(),
63
+ /** Prompt guidance; models without a catalog guidance range refuse it. */
64
+ guidance: z.number().optional(),
62
65
  /** Requested video or music length in whole seconds. */
63
66
  durationSeconds: z.number().int().optional(),
67
+ /** Upscale only: the output size in megapixels, one of the model's offered sizes. */
68
+ targetMegapixels: z.number().int().optional(),
64
69
  /** Speech models only: a premade voice from the catalog; the default when omitted. */
65
70
  voiceId: z.string().min(1).max(64).optional(),
66
71
  /** Video resolution; must match the nominal width/height selector. */
@@ -171,6 +176,7 @@ function normalizeGenerationSettings(input, normalize, catalogue) {
171
176
  if (input.width !== undefined ||
172
177
  input.height !== undefined ||
173
178
  input.steps !== undefined ||
179
+ input.guidance !== undefined ||
174
180
  input.resolution !== undefined ||
175
181
  input.aspectRatio !== undefined ||
176
182
  input.generateAudio !== undefined ||
@@ -181,6 +187,10 @@ function normalizeGenerationSettings(input, normalize, catalogue) {
181
187
  }
182
188
  if (input.voiceId !== undefined)
183
189
  throw new MediaSettingsError(`${model.id} does not take a voice`);
190
+ if (model.transform !== null)
191
+ return normalizeTransformSettings(model, model.transform, prompt, input, normalize);
192
+ if (input.targetMegapixels !== undefined)
193
+ throw new MediaSettingsError(`${model.id} does not take an output size`);
184
194
  if (input.width === undefined || input.height === undefined)
185
195
  throw new MediaSettingsError(`${model.id} needs a width and a height`);
186
196
  const maximumDimension = model.video === null ? 4_096 : 5_040;
@@ -222,6 +232,15 @@ function normalizeGenerationSettings(input, normalize, catalogue) {
222
232
  model.input.defaultSteps !== null) {
223
233
  steps = model.input.defaultSteps;
224
234
  }
235
+ let guidance;
236
+ const range = model.input.guidance;
237
+ if (input.guidance !== undefined && range === null)
238
+ throw new MediaSettingsError(`${model.id} does not take guidance`);
239
+ if (range !== null) {
240
+ guidance = input.guidance ?? range.default;
241
+ if (guidance < range.min || guidance > range.max)
242
+ throw new MediaSettingsError(`${model.id} accepts guidance from ${String(range.min)} through ${String(range.max)}`);
243
+ }
225
244
  let references;
226
245
  if (input.references !== undefined) {
227
246
  if (input.references.length > model.input.maxReferences)
@@ -236,6 +255,8 @@ function normalizeGenerationSettings(input, normalize, catalogue) {
236
255
  };
237
256
  if (steps !== undefined)
238
257
  normalized.steps = steps;
258
+ if (guidance !== undefined)
259
+ normalized.guidance = guidance;
239
260
  if (durationSeconds !== undefined)
240
261
  normalized.durationSeconds = durationSeconds;
241
262
  if (model.video !== null) {
@@ -395,6 +416,41 @@ export function validateMediaVideoSelection(raw, catalogue = mediaModels) {
395
416
  selection.audioReferences = Object.freeze(normalized.audioReferences.map((reference) => Object.freeze(mediaAudioReferenceSelectionSchema.parse(reference))));
396
417
  return Object.freeze(selection);
397
418
  }
419
+ /**
420
+ * A source-image operation takes exactly one reference and, for an upscale, one
421
+ * of the model's offered output sizes. Its output size is the provider's, so it
422
+ * takes no width, height, steps or video settings.
423
+ */
424
+ function normalizeTransformSettings(model, transform, prompt, input, normalize) {
425
+ if (input.width !== undefined ||
426
+ input.height !== undefined ||
427
+ input.steps !== undefined ||
428
+ input.guidance !== undefined ||
429
+ input.durationSeconds !== undefined ||
430
+ input.resolution !== undefined ||
431
+ input.aspectRatio !== undefined ||
432
+ input.generateAudio !== undefined ||
433
+ input.audioReferences !== undefined)
434
+ throw new MediaSettingsError(`${model.id} takes one source image${transform.defaultMegapixels === null ? "" : " and an output size"}`);
435
+ const references = input.references;
436
+ if (references?.length !== 1 || references[0]?.role !== undefined)
437
+ throw new MediaSettingsError(`${model.id} needs exactly one source image`);
438
+ const settings = {
439
+ model: model.id,
440
+ prompt,
441
+ references: Object.freeze(references.map(normalize)),
442
+ };
443
+ if (transform.defaultMegapixels === null) {
444
+ if (input.targetMegapixels !== undefined)
445
+ throw new MediaSettingsError(`${model.id} does not take an output size`);
446
+ return Object.freeze(settings);
447
+ }
448
+ const target = input.targetMegapixels ?? transform.defaultMegapixels;
449
+ if (transformMilliunits(transform, target) === undefined)
450
+ throw new MediaSettingsError(`${model.id} accepts output sizes of ${transform.sizes.map((price) => String(price.megapixels)).join(", ")} megapixels`);
451
+ settings.targetMegapixels = target;
452
+ return Object.freeze(settings);
453
+ }
398
454
  /** Neutral audio selection: speech takes a voice, music a length; model-specific limits are checked by validateMediaGenerationSettings. */
399
455
  export const mediaAudioSelectionSchema = z.lazy(() => z.strictObject({
400
456
  /** Verified catalog audio model identifier. */
@@ -407,6 +463,25 @@ export const mediaAudioSelectionSchema = z.lazy(() => z.strictObject({
407
463
  durationSeconds: z.number().int().min(3).max(600).optional(),
408
464
  }));
409
465
  const imageFormats = new Set(["png", "jpeg", "gif", "webp"]);
466
+ /**
467
+ * Refuse a source image the operation cannot take, with plain copy, before any
468
+ * paid call: an unsupported encoding, a source over Botanical's size bounds,
469
+ * or an upscale whose source is already as large as the chosen output.
470
+ */
471
+ function checkTransformSource(model, transform, settings, image) {
472
+ const { source } = transform;
473
+ const named = (format) => (format === "jpeg" ? "JPEG" : "PNG");
474
+ if (!source.formats.some((format) => format === image.format))
475
+ throw new MediaSettingsError(`${model.label} takes ${source.formats.map(named).join(" or ")} images, not ${image.format.toUpperCase()}.`);
476
+ if (image.bytes.byteLength > source.maxBytes)
477
+ throw new MediaSettingsError(`That image is over ${String(source.maxBytes / (1024 * 1024))} MB, the most ${model.label} takes.`);
478
+ const pixels = image.width * image.height;
479
+ if (pixels > source.maxPixels)
480
+ throw new MediaSettingsError(`That image is over ${String(source.maxPixels / 1_000_000)} megapixels, the most ${model.label} takes.`);
481
+ const target = settings.targetMegapixels;
482
+ if (target !== undefined && pixels >= target * 1_000_000)
483
+ throw new MediaSettingsError(`That image is already ${(pixels / 1_000_000).toFixed(1)} megapixels. Choose a larger output than ${String(target)} megapixels.`);
484
+ }
410
485
  /** Resolve only provider-accepted references through the caller's reader. */
411
486
  export const resolveMediaReferences = async (settings, reader, catalogue = mediaModels) => {
412
487
  const model = getMediaModel(settings.model, catalogue);
@@ -429,6 +504,8 @@ export const resolveMediaReferences = async (settings, reader, catalogue = media
429
504
  image.bytes.byteLength === 0 ||
430
505
  image.bytes.byteLength > MAX_REFERENCE_BYTES)
431
506
  throw new MediaSettingsError(`reference ${reference.computerId}:${reference.path} exceeds the bounded image contract`);
507
+ if (model.transform !== null)
508
+ checkTransformSource(model, model.transform, settings, image);
432
509
  totalBytes += image.bytes.byteLength;
433
510
  if (totalBytes > MAX_REFERENCE_BODY_BYTES)
434
511
  throw new MediaSettingsError("reference images exceed the total request size limit");
@@ -462,6 +539,8 @@ export const buildProviderInput = (settings, references = []) => {
462
539
  body.steps = settings.steps;
463
540
  if (settings.steps !== undefined && model.input.steps === "num_steps")
464
541
  body.num_steps = settings.steps;
542
+ if (settings.guidance !== undefined && model.input.guidance !== null)
543
+ body.guidance = settings.guidance;
465
544
  return Object.freeze({
466
545
  transport: "json",
467
546
  body: Object.freeze(body),
@@ -552,42 +631,6 @@ export const parseMediaProviderOutput = (value) => {
552
631
  entries: parsed.images,
553
632
  };
554
633
  };
555
- const sniffImageFormat = (bytes) => {
556
- if (bytes.length >= 8 &&
557
- bytes[0] === 0x89 &&
558
- bytes[1] === 0x50 &&
559
- bytes[2] === 0x4e &&
560
- bytes[3] === 0x47 &&
561
- bytes[4] === 0x0d &&
562
- bytes[5] === 0x0a &&
563
- bytes[6] === 0x1a &&
564
- bytes[7] === 0x0a)
565
- return "png";
566
- if (bytes.length >= 3 &&
567
- bytes[0] === 0xff &&
568
- bytes[1] === 0xd8 &&
569
- bytes[2] === 0xff)
570
- return "jpeg";
571
- if (bytes.length >= 6 &&
572
- bytes[0] === 0x47 &&
573
- bytes[1] === 0x49 &&
574
- bytes[2] === 0x46 &&
575
- bytes[3] === 0x38 &&
576
- (bytes[4] === 0x37 || bytes[4] === 0x39) &&
577
- bytes[5] === 0x61)
578
- return "gif";
579
- if (bytes.length >= 12 &&
580
- bytes[0] === 0x52 &&
581
- bytes[1] === 0x49 &&
582
- bytes[2] === 0x46 &&
583
- bytes[3] === 0x46 &&
584
- bytes[8] === 0x57 &&
585
- bytes[9] === 0x45 &&
586
- bytes[10] === 0x42 &&
587
- bytes[11] === 0x50)
588
- return "webp";
589
- return undefined;
590
- };
591
634
  const decodeEncoded = (value, maximumBytes) => {
592
635
  const comma = value.startsWith("data:") ? value.indexOf(",") : -1;
593
636
  const payload = comma >= 0 ? value.slice(comma + 1) : value;
@@ -7,6 +7,7 @@ export declare const mediaImageBindingInputSchema: z.ZodObject<{
7
7
  requestId: z.ZodLazy<z.ZodString>;
8
8
  libraryPath: z.ZodString & z.ZodType<string, string, z.core.$ZodTypeInternals<string, string>>;
9
9
  settings: z.ZodObject<{
10
+ guidance: z.ZodOptional<z.ZodNumber>;
10
11
  resolution: z.ZodOptional<z.ZodEnum<{
11
12
  readonly p480: "480p";
12
13
  readonly p720: "720p";
@@ -34,6 +35,7 @@ export declare const mediaImageBindingInputSchema: z.ZodObject<{
34
35
  }, z.core.$strict>>>;
35
36
  model: z.ZodString;
36
37
  prompt: z.ZodString;
38
+ targetMegapixels: z.ZodOptional<z.ZodNumber>;
37
39
  generateAudio: z.ZodOptional<z.ZodBoolean>;
38
40
  width: z.ZodNumber;
39
41
  height: z.ZodNumber;
@@ -114,6 +116,7 @@ export declare const mediaBindingGenerationSchema: z.ZodDiscriminatedUnion<[z.Zo
114
116
  requestId: z.ZodLazy<z.ZodString>;
115
117
  libraryPath: z.ZodString & z.ZodType<string, string, z.core.$ZodTypeInternals<string, string>>;
116
118
  settings: z.ZodObject<{
119
+ guidance: z.ZodOptional<z.ZodNumber>;
117
120
  resolution: z.ZodOptional<z.ZodEnum<{
118
121
  readonly p480: "480p";
119
122
  readonly p720: "720p";
@@ -141,6 +144,7 @@ export declare const mediaBindingGenerationSchema: z.ZodDiscriminatedUnion<[z.Zo
141
144
  }, z.core.$strict>>>;
142
145
  model: z.ZodString;
143
146
  prompt: z.ZodString;
147
+ targetMegapixels: z.ZodOptional<z.ZodNumber>;
144
148
  generateAudio: z.ZodOptional<z.ZodBoolean>;
145
149
  width: z.ZodNumber;
146
150
  height: z.ZodNumber;
@@ -224,6 +228,7 @@ export declare const mediaBindingCallSchema: z.ZodDiscriminatedUnion<[z.ZodObjec
224
228
  requestId: z.ZodLazy<z.ZodString>;
225
229
  libraryPath: z.ZodString & z.ZodType<string, string, z.core.$ZodTypeInternals<string, string>>;
226
230
  settings: z.ZodObject<{
231
+ guidance: z.ZodOptional<z.ZodNumber>;
227
232
  resolution: z.ZodOptional<z.ZodEnum<{
228
233
  readonly p480: "480p";
229
234
  readonly p720: "720p";
@@ -251,6 +256,7 @@ export declare const mediaBindingCallSchema: z.ZodDiscriminatedUnion<[z.ZodObjec
251
256
  }, z.core.$strict>>>;
252
257
  model: z.ZodString;
253
258
  prompt: z.ZodString;
259
+ targetMegapixels: z.ZodOptional<z.ZodNumber>;
254
260
  generateAudio: z.ZodOptional<z.ZodBoolean>;
255
261
  width: z.ZodNumber;
256
262
  height: z.ZodNumber;
@@ -0,0 +1,5 @@
1
+ import type { ImageFormat } from "./index.js";
2
+ /** The image encoding named by the file's magic bytes, if any. */
3
+ export declare const sniffImageFormat: (bytes: Uint8Array) => ImageFormat | undefined;
4
+ /** The MIME type for generated bytes, from their magic numbers. */
5
+ export declare const mediaContentType: (bytes: Uint8Array) => string;
@@ -0,0 +1,49 @@
1
+ import { isMp4 } from "./gateway-wire.js";
2
+ /** The image encoding named by the file's magic bytes, if any. */
3
+ export const sniffImageFormat = (bytes) => {
4
+ if (bytes.length >= 8 &&
5
+ bytes[0] === 0x89 &&
6
+ bytes[1] === 0x50 &&
7
+ bytes[2] === 0x4e &&
8
+ bytes[3] === 0x47 &&
9
+ bytes[4] === 0x0d &&
10
+ bytes[5] === 0x0a &&
11
+ bytes[6] === 0x1a &&
12
+ bytes[7] === 0x0a)
13
+ return "png";
14
+ if (bytes.length >= 3 &&
15
+ bytes[0] === 0xff &&
16
+ bytes[1] === 0xd8 &&
17
+ bytes[2] === 0xff)
18
+ return "jpeg";
19
+ if (bytes.length >= 6 &&
20
+ bytes[0] === 0x47 &&
21
+ bytes[1] === 0x49 &&
22
+ bytes[2] === 0x46 &&
23
+ bytes[3] === 0x38 &&
24
+ (bytes[4] === 0x37 || bytes[4] === 0x39) &&
25
+ bytes[5] === 0x61)
26
+ return "gif";
27
+ if (bytes.length >= 12 &&
28
+ bytes[0] === 0x52 &&
29
+ bytes[1] === 0x49 &&
30
+ bytes[2] === 0x46 &&
31
+ bytes[3] === 0x46 &&
32
+ bytes[8] === 0x57 &&
33
+ bytes[9] === 0x45 &&
34
+ bytes[10] === 0x42 &&
35
+ bytes[11] === 0x50)
36
+ return "webp";
37
+ return undefined;
38
+ };
39
+ /** The MIME type for generated bytes, from their magic numbers. */
40
+ export const mediaContentType = (bytes) => {
41
+ const image = sniffImageFormat(bytes);
42
+ if (image !== undefined)
43
+ return `image/${image}`;
44
+ if (isMp4(bytes))
45
+ return "video/mp4";
46
+ const id3 = bytes[0] === 0x49 && bytes[1] === 0x44 && bytes[2] === 0x33;
47
+ const frame = bytes[0] === 0xff && ((bytes[1] ?? 0) & 0xe0) === 0xe0;
48
+ return id3 || frame ? "audio/mpeg" : "application/octet-stream";
49
+ };
@@ -30,6 +30,7 @@ export function runMediaGeneration(host, request, signal) {
30
30
  catch: (cause) => new MediaExecutionError("generation-authorization", { cause }),
31
31
  });
32
32
  const execution = {
33
+ embedPrompt: request.embedPrompt,
33
34
  operation: host.operations.getByName(`media:${request.requestId}`),
34
35
  actorUserId: host.scope.actorId,
35
36
  coordinates: {
@@ -48,6 +49,7 @@ export function runMediaGeneration(host, request, signal) {
48
49
  destination: {
49
50
  authorize: () => host.destination.authorize(path),
50
51
  write: (bytes) => host.destination.write(path, bytes),
52
+ remove: (sha256) => host.destination.remove(path, { sha256 }),
51
53
  },
52
54
  generation: {
53
55
  prepare: async () => {
@@ -1,5 +1,6 @@
1
1
  import * as z from "zod";
2
2
  import type { MediaOperationOwner, MediaOperationCoordinates, MediaOperationRequest } from "./media-operation-owner.js";
3
+ import type { MediaRemoval } from "./media-written.js";
3
4
  import type { MediaUnits } from "./gateway-models.js";
4
5
  import type { MediaAudioReferenceBytes, MediaCatalogue, MediaReferenceBytes } from "./index.js";
5
6
  /**
@@ -38,7 +39,7 @@ export type MediaMetering = Readonly<{
38
39
  }>;
39
40
  /** Local or RPC methods consumed by a replay-safe generation. */
40
41
  export type MediaOperation = {
41
- [Method in "admit" | "claim" | "dispatchInBackground" | "interruptGeneration" | "readGenerated" | "recordEstimate" | "recordGenerated" | "recordSucceeded" | "recordWritten" | "recordWrittenWithoutSettlement" | "releaseEstimate" | "releaseWrite"]: (...input: Parameters<MediaOperationOwner[Method]>) => ReturnType<MediaOperationOwner[Method]> | Promise<Awaited<ReturnType<MediaOperationOwner[Method]>>>;
42
+ [Method in "admit" | "claim" | "dispatchInBackground" | "interruptGeneration" | "readGenerated" | "recordEstimate" | "recordGenerated" | "recordSucceeded" | "recordWritten" | "recordWrittenWithoutSettlement" | "releaseEstimate" | "releaseWrite" | "recordWriteIntent" | "retained" | "readRetained" | "erase"]: (...input: Parameters<MediaOperationOwner[Method]>) => ReturnType<MediaOperationOwner[Method]> | Promise<Awaited<ReturnType<MediaOperationOwner[Method]>>>;
42
43
  };
43
44
  /** Admitted identity, durable operation and host effects for one generation. */
44
45
  export type MediaExecution = Readonly<{
@@ -58,12 +59,23 @@ export type MediaExecution = Readonly<{
58
59
  metering: MediaMetering | "unmetered";
59
60
  /** Optional cancellation signal. */
60
61
  signal?: AbortSignal;
62
+ /**
63
+ * Publish the prompt in the image's XMP as `fungi:prompt`. Omitted or false
64
+ * keeps the prompt out of the file: a host must opt in per generation.
65
+ */
66
+ embedPrompt?: boolean | undefined;
61
67
  /** Host-owned destination authorization and writing. */
62
68
  destination: Readonly<{
63
69
  /** Check host permission before writing or dispatching generation. */
64
70
  authorize: () => Promise<void>;
65
71
  /** Save exact generated bytes to the admitted destination. */
66
72
  write: (bytes: Uint8Array) => Promise<void>;
73
+ /**
74
+ * Delete the file this generation wrote, only while it still holds the
75
+ * bytes with this SHA-256. Called when the operation was erased while the
76
+ * write was in flight, so the saved file does not outlive it.
77
+ */
78
+ remove: (sha256: string) => Promise<MediaRemoval>;
67
79
  }>;
68
80
  /** Reference preparation and provider dispatch effects. */
69
81
  generation: Readonly<{
@@ -35,8 +35,14 @@ export declare class MediaOperationDO extends DurableObject<MediaOperationCloudf
35
35
  readShare(...input: Parameters<MediaOperationOwner["readShare"]>): ReturnType<MediaOperationOwner["readShare"]>;
36
36
  /** {@inheritDoc MediaOperationOwner.preflightErasure} */
37
37
  preflightErasure(...input: Parameters<MediaOperationOwner["preflightErasure"]>): ReturnType<MediaOperationOwner["preflightErasure"]>;
38
+ /** {@inheritDoc MediaOperationOwner.recordWriteIntent} */
39
+ recordWriteIntent(...input: Parameters<MediaOperationOwner["recordWriteIntent"]>): ReturnType<MediaOperationOwner["recordWriteIntent"]>;
38
40
  /** {@inheritDoc MediaOperationOwner.erase} */
39
41
  erase(...input: Parameters<MediaOperationOwner["erase"]>): ReturnType<MediaOperationOwner["erase"]>;
42
+ /** {@inheritDoc MediaOperationOwner.retained} */
43
+ retained(...input: Parameters<MediaOperationOwner["retained"]>): ReturnType<MediaOperationOwner["retained"]>;
44
+ /** {@inheritDoc MediaOperationOwner.readRetained} */
45
+ readRetained(...input: Parameters<MediaOperationOwner["readRetained"]>): ReturnType<MediaOperationOwner["readRetained"]>;
40
46
  /** {@inheritDoc MediaOperationOwner.readErasure} */
41
47
  readErasure(...input: Parameters<MediaOperationOwner["readErasure"]>): ReturnType<MediaOperationOwner["readErasure"]>;
42
48
  /** {@inheritDoc MediaOperationOwner.admit} */
@@ -1,8 +1,14 @@
1
1
  import { DurableObject } from "cloudflare:workers";
2
+ import { z } from "zod";
2
3
  import { createWorkersAiMediaProvider, } from "./cloudflare/provider.js";
3
4
  import { mediaModels, } from "./index.js";
4
5
  import { MediaOperationOwner, } from "./media-operation-owner.js";
5
6
  import { DailyMediaMeter, } from "./daily-media-meter.js";
7
+ const erasureMarkerSchema = z.strictObject({
8
+ destinationPath: z.string().nullable(),
9
+ writtenSha256: z.string().nullable(),
10
+ abandonedGeneration: z.boolean(),
11
+ });
6
12
  /** Cloudflare lifecycle and RPC surface around the durable media owner. */
7
13
  export class MediaOperationDO extends DurableObject {
8
14
  owner;
@@ -20,10 +26,27 @@ export class MediaOperationDO extends DurableObject {
20
26
  sql: ctx.storage.sql,
21
27
  transactionSync: (body) => ctx.storage.transactionSync(body),
22
28
  isErased: async () => (await ctx.storage.get("botanical:erased")) === true,
23
- markErased: () => ctx.storage.put("botanical:erased", true),
29
+ markErased: async (marker) => {
30
+ // Facts first: the marker's presence is what means erased.
31
+ await ctx.storage.put("botanical:erased-details", JSON.stringify(marker));
32
+ await ctx.storage.put("botanical:erased", true);
33
+ },
34
+ readErasureMarker: async () => {
35
+ const details = z
36
+ .string()
37
+ .optional()
38
+ .parse(await ctx.storage.get("botanical:erased-details"));
39
+ return details === undefined
40
+ ? null
41
+ : erasureMarkerSchema.parse(JSON.parse(details));
42
+ },
24
43
  listKeys: async () => [...(await ctx.storage.list()).keys()],
25
44
  deleteAlarm: () => ctx.storage.deleteAlarm(),
26
- deleteAll: () => ctx.storage.deleteAll(),
45
+ deleteKeys: async (keys) => {
46
+ // Storage deletes at most 128 keys per call.
47
+ for (let start = 0; start < keys.length; start += 128)
48
+ await ctx.storage.delete(keys.slice(start, start + 128));
49
+ },
27
50
  getAlarm: () => ctx.storage.getAlarm(),
28
51
  setAlarm: (timestamp) => ctx.storage.setAlarm(timestamp),
29
52
  },
@@ -71,10 +94,22 @@ export class MediaOperationDO extends DurableObject {
71
94
  preflightErasure(...input) {
72
95
  return this.owner.preflightErasure(...input);
73
96
  }
97
+ /** {@inheritDoc MediaOperationOwner.recordWriteIntent} */
98
+ recordWriteIntent(...input) {
99
+ return this.owner.recordWriteIntent(...input);
100
+ }
74
101
  /** {@inheritDoc MediaOperationOwner.erase} */
75
102
  erase(...input) {
76
103
  return this.owner.erase(...input);
77
104
  }
105
+ /** {@inheritDoc MediaOperationOwner.retained} */
106
+ retained(...input) {
107
+ return this.owner.retained(...input);
108
+ }
109
+ /** {@inheritDoc MediaOperationOwner.readRetained} */
110
+ readRetained(...input) {
111
+ return this.owner.readRetained(...input);
112
+ }
78
113
  /** {@inheritDoc MediaOperationOwner.readErasure} */
79
114
  readErasure(...input) {
80
115
  return this.owner.readErasure(...input);