@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
@@ -65,6 +65,24 @@ export const mediaModelInputSchema = z.lazy(() => z
65
65
  maxSteps: z.number().int().positive().nullable(),
66
66
  /** Default inference step count. */
67
67
  defaultSteps: z.number().int().nonnegative().nullable(),
68
+ /**
69
+ * Prompt-guidance (`guidance`) bounds and default sent to the provider, or
70
+ * null when the model takes no guidance field. A host's own catalogue may
71
+ * omit the key; absent means null.
72
+ */
73
+ guidance: z
74
+ .strictObject({
75
+ /** Lowest value the provider accepts. */
76
+ min: z.number().nonnegative(),
77
+ /** Highest value the provider accepts. */
78
+ max: z.number().positive(),
79
+ /** Value sent when the caller names none. */
80
+ default: z.number().nonnegative(),
81
+ })
82
+ .readonly()
83
+ .refine((g) => g.min <= g.default && g.default <= g.max, "guidance default must lie within its bounds")
84
+ .nullable()
85
+ .default(null),
68
86
  /** Provider multipart reference-field prefix, or null when unsupported. */
69
87
  referenceField: z.string().min(1).max(256).nullable(),
70
88
  /** Maximum references accepted by this model. */
@@ -285,6 +303,102 @@ export const AUDIO_CHARACTER_BLOCK = 100;
285
303
  export const MAX_MEDIA_PROMPT_LENGTH = 32_000;
286
304
  /** Prompt cap kept for models whose provider documents no prompt limit. */
287
305
  const UNDOCUMENTED_PROMPT_LENGTH = 2_048;
306
+ /**
307
+ * What a source-image operation does to its one reference image. Both write a
308
+ * new image and never touch the source.
309
+ */
310
+ export const mediaTransformOperationSchema = z.enum({
311
+ /** Cut the foreground out onto a transparent PNG. */
312
+ remove_background: "remove_background",
313
+ /** Enlarge the image to a chosen output size in megapixels. */
314
+ upscale: "upscale",
315
+ });
316
+ /**
317
+ * Facts of a catalog entry that edits one source image rather than generating
318
+ * from a prompt. The source limits are Botanical's own conservative bounds, not
319
+ * Cloudflare's: neither model page publishes an input size limit.
320
+ */
321
+ export const mediaTransformSchema = z.lazy(() => z
322
+ .strictObject({
323
+ /** What the operation does. */
324
+ operation: mediaTransformOperationSchema,
325
+ /** Botanical's limits on the one source image, checked before any paid call. */
326
+ source: z
327
+ .strictObject({
328
+ /** Accepted source encodings. */
329
+ formats: z.array(mediaRequestedImageFormatSchema).readonly(),
330
+ /** Largest source, in bytes (the hosts' existing reference read limit). */
331
+ maxBytes: z.number().int().positive(),
332
+ /** Largest source, in pixels. */
333
+ maxPixels: z.number().int().positive(),
334
+ })
335
+ .readonly(),
336
+ /** Output size chosen when none is given, or null when the operation has no size. */
337
+ defaultMegapixels: z.number().int().positive().nullable(),
338
+ /**
339
+ * Provider milliunits for one image when the price does not depend on
340
+ * the output size, else null (1 USD = 100,000 milliunits).
341
+ */
342
+ milliunits: z.number().int().positive().nullable(),
343
+ /** Output sizes offered, each with its provider milliunits; empty for a flat price. */
344
+ sizes: z
345
+ .array(z
346
+ .strictObject({
347
+ /** Output size in megapixels. */
348
+ megapixels: z.number().int().positive(),
349
+ /** Provider milliunits for one image at this size. */
350
+ milliunits: z.number().int().positive(),
351
+ })
352
+ .readonly())
353
+ .readonly(),
354
+ })
355
+ .readonly());
356
+ /**
357
+ * Pruna P-Image-Upscale's published price per image by output size, copied
358
+ * exactly: [largest output megapixels in the tier, USD].
359
+ * https://developers.cloudflare.com/ai/models/pruna/p-image-upscale/
360
+ */
361
+ const UPSCALE_PRICE_TIERS = [
362
+ [4, 0.005],
363
+ [8, 0.01],
364
+ [16, 0.02],
365
+ [32, 0.04],
366
+ [64, 0.06],
367
+ [128, 0.12],
368
+ ];
369
+ /** The output sizes Botanical offers; the provider accepts 1 to 128. */
370
+ const UPSCALE_TARGET_MEGAPIXELS = [4, 8, 16];
371
+ const USD_TO_MILLIUNITS = 100_000;
372
+ /** Bria RMBG 2.0's published price per image: https://developers.cloudflare.com/ai/models/bria/remove-background/ */
373
+ const REMOVE_BACKGROUND_USD = 0.018;
374
+ /** Botanical's own source bounds for both operations (see {@link mediaTransformSchema}). */
375
+ const TRANSFORM_SOURCE_MAX_BYTES = 8 * 1024 * 1024;
376
+ const TRANSFORM_SOURCE_MAX_PIXELS = 25_000_000;
377
+ /**
378
+ * What one generation bills: whole images, whole seconds of video or music, or
379
+ * blocks of {@link AUDIO_CHARACTER_BLOCK} speech characters (so a per-character
380
+ * provider rate is marked up once per block, not rounded up per character).
381
+ */
382
+ export const mediaBillingUnitSchema = z.enum({
383
+ /** One image. */
384
+ image: "image",
385
+ /** One whole second of video. */
386
+ video_second: "video_second",
387
+ /** One whole second of music. */
388
+ audio_second: "audio_second",
389
+ /** One block of speech characters. */
390
+ audio_character_block: "audio_character_block",
391
+ });
392
+ /** The one rule mapping a model's kind (and speech or music mode) to its billing unit. */
393
+ export const mediaBillingUnit = (model) => {
394
+ if (model.kind === "video")
395
+ return "video_second";
396
+ if (model.kind === "audio")
397
+ return model.audio?.mode === "speech"
398
+ ? "audio_character_block"
399
+ : "audio_second";
400
+ return "image";
401
+ };
288
402
  /** Public wire grammar for a catalog entry returned by the Media owner. */
289
403
  export const mediaModelSchema = z
290
404
  .strictObject({
@@ -324,17 +438,33 @@ export const mediaModelSchema = z
324
438
  video: mediaVideoSchema.nullable(),
325
439
  /** Speech or music constraints, or null for an image or video model. */
326
440
  audio: mediaAudioSchema.nullable(),
441
+ /**
442
+ * Price basis: the unit one generation bills in. The cost of those units
443
+ * depends on the settings (size, steps, resolution, sound, references), so
444
+ * an App shows `priceEstimate` where its host supplies one and otherwise
445
+ * asks its host for a quote of the exact settings.
446
+ */
447
+ billingUnit: mediaBillingUnitSchema,
448
+ /** Source-image operation facts, or null for a model that generates from a prompt. */
449
+ transform: mediaTransformSchema.nullable(),
327
450
  })
328
451
  .readonly();
329
- const freezeModel = (model) => Object.freeze({
330
- kind: "image",
331
- sizes: null,
332
- video: null,
333
- audio: null,
334
- outputFormats: Object.freeze([]),
335
- ...model,
336
- input: Object.freeze(model.input),
337
- });
452
+ const freezeModel = (model) => {
453
+ const entry = {
454
+ kind: "image",
455
+ sizes: null,
456
+ video: null,
457
+ audio: null,
458
+ transform: null,
459
+ outputFormats: Object.freeze([]),
460
+ ...model,
461
+ };
462
+ return Object.freeze({
463
+ ...entry,
464
+ billingUnit: mediaBillingUnit(entry),
465
+ input: Object.freeze(model.input),
466
+ });
467
+ };
338
468
  /**
339
469
  * GPT Image 2's `size` is `auto` or any WIDTHxHEIGHT with each edge at most
340
470
  * 3840, both edges multiples of 16, an aspect ratio between 1:3 and 3:1 and a
@@ -523,6 +653,7 @@ function videoModel(id, label, tier, provider, rates, bounds) {
523
653
  steps: "fixed",
524
654
  maxSteps: null,
525
655
  defaultSteps: null,
656
+ guidance: null,
526
657
  referenceField: seedance ? "image" : "image_input",
527
658
  maxReferences: seedance ? maxReferenceImages : 1,
528
659
  referenceDimension: null,
@@ -624,6 +755,7 @@ function minimaxVideoModel() {
624
755
  steps: "fixed",
625
756
  maxSteps: null,
626
757
  defaultSteps: null,
758
+ guidance: null,
627
759
  // Inert for this gateway model (media-generation.ts builds its body
628
760
  // directly); recorded for the same documentation parity as Seedance/Veo.
629
761
  referenceField: "image_url",
@@ -697,6 +829,7 @@ function audioModel(id, label, tier, maxPromptLength, audio) {
697
829
  steps: "fixed",
698
830
  maxSteps: null,
699
831
  defaultSteps: null,
832
+ guidance: null,
700
833
  referenceField: null,
701
834
  maxReferences: 0,
702
835
  referenceDimension: null,
@@ -704,6 +837,59 @@ function audioModel(id, label, tier, maxPromptLength, audio) {
704
837
  },
705
838
  });
706
839
  }
840
+ /** The published tier a chosen output size falls in; every offered size has one. */
841
+ function upscaleTierUsd(megapixels) {
842
+ const tier = UPSCALE_PRICE_TIERS.find(([largest]) => megapixels <= largest);
843
+ if (tier === undefined)
844
+ throw new Error(`no published upscale price for ${String(megapixels)} MP`);
845
+ return tier[1];
846
+ }
847
+ /** A source-image operation model: one reference in, one new image out, no prompt text sent. */
848
+ function transformModel(input) {
849
+ return freezeModel({
850
+ id: input.id,
851
+ label: input.label,
852
+ tier: input.tier,
853
+ outputFormats: Object.freeze([input.outputFormat]),
854
+ // The prompt only labels the saved output ("Remove background"); the
855
+ // provider never reads it.
856
+ maxPromptLength: 256,
857
+ transform: Object.freeze({
858
+ operation: input.operation,
859
+ source: Object.freeze({
860
+ formats: Object.freeze(["png", "jpeg"]),
861
+ maxBytes: TRANSFORM_SOURCE_MAX_BYTES,
862
+ maxPixels: TRANSFORM_SOURCE_MAX_PIXELS,
863
+ }),
864
+ defaultMegapixels: input.defaultMegapixels,
865
+ milliunits: input.flatUsd === null
866
+ ? null
867
+ : Math.round(input.flatUsd * USD_TO_MILLIUNITS),
868
+ sizes: Object.freeze(input.sizes.map(({ megapixels, usd }) => Object.freeze({
869
+ megapixels,
870
+ milliunits: Math.round(usd * USD_TO_MILLIUNITS),
871
+ }))),
872
+ }),
873
+ input: {
874
+ transport: "json",
875
+ dimensions: "none",
876
+ maxDimension: null,
877
+ maxDimensionDocumented: false,
878
+ defaultWidth: 1024,
879
+ defaultHeight: 1024,
880
+ steps: "fixed",
881
+ maxSteps: null,
882
+ defaultSteps: null,
883
+ guidance: null,
884
+ referenceField: "image",
885
+ maxReferences: 1,
886
+ // The hosts' reference fitter only shrinks; this keeps any source within
887
+ // the pixel bound at its original size.
888
+ referenceDimension: 8_192,
889
+ referenceFormat: "png",
890
+ },
891
+ });
892
+ }
707
893
  const models = Object.freeze([
708
894
  freezeModel({
709
895
  id: "@cf/black-forest-labs/flux-1-schnell",
@@ -722,6 +908,7 @@ const models = Object.freeze([
722
908
  steps: "steps",
723
909
  maxSteps: 8,
724
910
  defaultSteps: 4,
911
+ guidance: null,
725
912
  referenceField: null,
726
913
  maxReferences: 0,
727
914
  // No documented reference size for this model; the retained 512 px fit.
@@ -745,6 +932,7 @@ const models = Object.freeze([
745
932
  steps: "fixed",
746
933
  maxSteps: null,
747
934
  defaultSteps: 4,
935
+ guidance: null,
748
936
  referenceField: "input_image_",
749
937
  maxReferences: 4,
750
938
  // No documented reference size for this model; the retained 512 px fit.
@@ -768,6 +956,7 @@ const models = Object.freeze([
768
956
  steps: "fixed",
769
957
  maxSteps: null,
770
958
  defaultSteps: 4,
959
+ guidance: null,
771
960
  referenceField: "input_image_",
772
961
  maxReferences: 4,
773
962
  // No documented reference size for this model; the retained 512 px fit.
@@ -791,6 +980,7 @@ const models = Object.freeze([
791
980
  steps: "steps",
792
981
  maxSteps: null,
793
982
  defaultSteps: 20,
983
+ guidance: null,
794
984
  referenceField: "input_image_",
795
985
  maxReferences: 4,
796
986
  // No documented reference size for this model; the retained 512 px fit.
@@ -815,6 +1005,9 @@ const models = Object.freeze([
815
1005
  steps: "num_steps",
816
1006
  maxSteps: 40,
817
1007
  defaultSteps: null,
1008
+ // https://developers.cloudflare.com/workers-ai/models/lucid-origin/ (guidance range); the
1009
+ // default is the value Loftwah's studio tuned for this model.
1010
+ guidance: { min: 0, max: 10, default: 5 },
818
1011
  referenceField: null,
819
1012
  maxReferences: 0,
820
1013
  // No documented reference size for this model; the retained 512 px fit.
@@ -839,6 +1032,9 @@ const models = Object.freeze([
839
1032
  steps: "num_steps",
840
1033
  maxSteps: 50,
841
1034
  defaultSteps: 25,
1035
+ // https://developers.cloudflare.com/workers-ai/models/phoenix-1.0/ (guidance range); the
1036
+ // default is the value Loftwah's studio tuned for this model.
1037
+ guidance: { min: 2, max: 10, default: 3 },
842
1038
  referenceField: null,
843
1039
  maxReferences: 0,
844
1040
  // No documented reference size for this model; the retained 512 px fit.
@@ -866,6 +1062,7 @@ const models = Object.freeze([
866
1062
  steps: "fixed",
867
1063
  maxSteps: null,
868
1064
  defaultSteps: null,
1065
+ guidance: null,
869
1066
  // Cloudflare documents `images[]` (base64 strings or data URIs, 1-16
870
1067
  // entries, routed to OpenAI's /v1/images/edits) for this exact model:
871
1068
  // https://developers.cloudflare.com/ai/models/openai/gpt-image-2/
@@ -904,6 +1101,7 @@ const models = Object.freeze([
904
1101
  steps: "fixed",
905
1102
  maxSteps: null,
906
1103
  defaultSteps: null,
1104
+ guidance: null,
907
1105
  // The page says the model takes up to 10 reference images (`image`, a
908
1106
  // string or 1-10 strings) but shows only URL inputs and states no
909
1107
  // base64 or data-URI form, so Prints sends none until it does.
@@ -913,6 +1111,31 @@ const models = Object.freeze([
913
1111
  referenceFormat: "png",
914
1112
  },
915
1113
  }),
1114
+ transformModel({
1115
+ id: "bria/remove-background",
1116
+ label: "Remove background — Bria RMBG 2.0",
1117
+ tier: "draft",
1118
+ operation: "remove_background",
1119
+ outputFormat: "png",
1120
+ flatUsd: REMOVE_BACKGROUND_USD,
1121
+ sizes: [],
1122
+ defaultMegapixels: null,
1123
+ }),
1124
+ transformModel({
1125
+ id: "pruna/p-image-upscale",
1126
+ label: "Upscale — Pruna P-Image-Upscale",
1127
+ tier: "draft",
1128
+ operation: "upscale",
1129
+ // Lossless output would swell past the output byte bound at 16 megapixels;
1130
+ // WebP keeps transparency.
1131
+ outputFormat: "webp",
1132
+ flatUsd: null,
1133
+ sizes: UPSCALE_TARGET_MEGAPIXELS.map((megapixels) => ({
1134
+ megapixels,
1135
+ usd: upscaleTierUsd(megapixels),
1136
+ })),
1137
+ defaultMegapixels: 4,
1138
+ }),
916
1139
  videoModel(mediaVideoModelIdSchema.enum.seedance25, "Seedance 2.5", "balanced", "seedance", [
917
1140
  ["480p", 10_280, 10_280],
918
1141
  ["720p", 23_120, 23_120],
@@ -955,8 +1178,12 @@ export const mediaModels = models;
955
1178
  export const mediaCatalogueModelSchema = mediaModelSchema
956
1179
  .unwrap()
957
1180
  .extend({
1181
+ /** Optional on a host's entry because Darkroom derives it; a stated value must match. */
1182
+ billingUnit: mediaBillingUnitSchema.optional(),
958
1183
  /** Speech or music constraints; a host's catalogue omits it unless it lists audio models. */
959
1184
  audio: mediaAudioSchema.unwrap().nullable().default(null),
1185
+ /** Source-image operation facts; a host's catalogue omits it unless it lists such models. */
1186
+ transform: mediaTransformSchema.unwrap().nullable().default(null),
960
1187
  /** Video length constraints, or null for a still-image model. */
961
1188
  video: mediaVideoSchema
962
1189
  .unwrap()
@@ -1008,6 +1235,9 @@ export const mediaCatalogueSchema = z
1008
1235
  report(`${model.id} must carry video bounds exactly when kind is video`);
1009
1236
  if ((model.kind === "audio") !== (model.audio !== null))
1010
1237
  report(`${model.id} must carry audio bounds exactly when kind is audio`);
1238
+ if (model.billingUnit !== undefined &&
1239
+ model.billingUnit !== mediaBillingUnit(model))
1240
+ report(`${model.id} billingUnit must be ${mediaBillingUnit(model)} for ${model.kind === "image" ? "an" : "a"} ${model.kind} model`);
1011
1241
  const video = model.video;
1012
1242
  if (video === null)
1013
1243
  return;
@@ -1028,6 +1258,21 @@ export const parseMediaCatalogue = (raw) => {
1028
1258
  throw new MediaSettingsError(`media catalogue is invalid: ${parsed.error.issues[0]?.message ?? "unreadable"}`);
1029
1259
  return parsed.data;
1030
1260
  };
1261
+ /** A catalogue entry as the public `/models` list returns it: the entry plus its derived billing unit. */
1262
+ export const withBillingUnit = (model) => ({
1263
+ ...model,
1264
+ billingUnit: mediaBillingUnit(model),
1265
+ });
1266
+ /**
1267
+ * Provider milliunits for one image of a source-image operation at `megapixels`
1268
+ * (omitted: the model's default), or undefined when that output size is not offered.
1269
+ */
1270
+ export const transformMilliunits = (transform, megapixels) => {
1271
+ if (transform.milliunits !== null)
1272
+ return megapixels === undefined ? transform.milliunits : undefined;
1273
+ const size = megapixels ?? transform.defaultMegapixels;
1274
+ return transform.sizes.find((price) => price.megapixels === size)?.milliunits;
1275
+ };
1031
1276
  /** List the gateway provider's models in catalog order. */
1032
1277
  export const listMediaModels = () => mediaModels;
1033
1278
  /** Find a model in the Fungi gateway's own catalogue; gateway-internal code never sees a custom provider's models. */
@@ -3,7 +3,11 @@ import type { ImageFormat } from "./index.js";
3
3
  export type ProvenanceFacts = Readonly<{
4
4
  printId: string;
5
5
  model: string;
6
- prompt: string;
6
+ /**
7
+ * The prompt to publish in the file's XMP, or null to leave it out. The host
8
+ * decides per generation; a prompt is private unless the host opts in.
9
+ */
10
+ prompt: string | null;
7
11
  createdAt: number;
8
12
  }>;
9
13
  export type ProvenanceEmbedResult = Readonly<{
@@ -24,7 +24,8 @@ async function packet(facts) {
24
24
  .txt("http://cv.iptc.org/newscodes/digitalsourcetype/trainedAlgorithmicMedia");
25
25
  description.ele("fungi:printId").txt(facts.printId);
26
26
  description.ele("fungi:model").txt(facts.model);
27
- description.ele("fungi:prompt").txt(facts.prompt);
27
+ if (facts.prompt !== null)
28
+ description.ele("fungi:prompt").txt(facts.prompt);
28
29
  return document.end({ headless: true });
29
30
  }
30
31
  async function embedWebp(bytes, xmp) {
@@ -0,0 +1,24 @@
1
+ import { type MediaReference } from "./index.js";
2
+ /** One stored reference: its size is known before its bytes are loaded. */
3
+ export type HostReferenceSource = Readonly<{
4
+ /** Stored byte length, checked before the bytes are read. */
5
+ size: number;
6
+ /** Load the exact stored bytes. */
7
+ bytes: () => Promise<Uint8Array>;
8
+ }>;
9
+ /**
10
+ * The one owner of a host reference read's refusals. The reference must name
11
+ * the host's admitted destination, exist, be non-empty and fit the byte limit
12
+ * for its kind; anything else is a {@link MediaSettingsError} raised before
13
+ * any provider dispatch.
14
+ */
15
+ export declare function readHostReference(input: Readonly<{
16
+ reference: MediaReference;
17
+ /** The host's admitted destination identity. */
18
+ destinationId: string;
19
+ kind: "image" | "audio";
20
+ /** Open the reference path in the host's store, or null when missing. */
21
+ open: (path: string) => Promise<HostReferenceSource | null>;
22
+ }>): Promise<Uint8Array>;
23
+ /** The filename sent with a multipart reference: the last path segment. */
24
+ export declare function referenceFilename(reference: MediaReference): string;
@@ -0,0 +1,26 @@
1
+ import { MAX_AUDIO_REFERENCE_BYTES } from "./audio-reference-types.js";
2
+ import { MediaSettingsError } from "./model-catalog.js";
3
+ import { MAX_REFERENCE_BYTES } from "./index.js";
4
+ /**
5
+ * The one owner of a host reference read's refusals. The reference must name
6
+ * the host's admitted destination, exist, be non-empty and fit the byte limit
7
+ * for its kind; anything else is a {@link MediaSettingsError} raised before
8
+ * any provider dispatch.
9
+ */
10
+ export async function readHostReference(input) {
11
+ const { reference, kind } = input;
12
+ if (reference.computerId !== input.destinationId)
13
+ throw new MediaSettingsError("reference Computer is not selected");
14
+ const limit = kind === "image" ? MAX_REFERENCE_BYTES : MAX_AUDIO_REFERENCE_BYTES;
15
+ const source = await input.open(reference.path);
16
+ if (source === null || source.size === 0 || source.size > limit)
17
+ throw new MediaSettingsError(`${kind} reference is unavailable or exceeds the byte limit`);
18
+ const bytes = await source.bytes();
19
+ if (bytes.byteLength === 0 || bytes.byteLength > limit)
20
+ throw new MediaSettingsError(`${kind} reference is unavailable or exceeds the byte limit`);
21
+ return bytes;
22
+ }
23
+ /** The filename sent with a multipart reference: the last path segment. */
24
+ export function referenceFilename(reference) {
25
+ return reference.path.split("/").at(-1) ?? "reference";
26
+ }
package/dist/server.d.ts CHANGED
@@ -2,17 +2,22 @@ export { estimateMediaModel } from "./cloudflare/provider.js";
2
2
  export { mediaPendingSchema, mediaBindingCallSchema, mediaBindingGenerationSchema, mediaImageBindingInputSchema, mediaVideoBindingInputSchema, parseMediaBindingCall, mediaBindingRequest, readMediaBindingReply, type MediaBindingCall, type MediaBindingGeneration, type MediaBindingRequest, } from "./media-binding.js";
3
3
  import { Hono } from "hono";
4
4
  import { z } from "zod";
5
+ import type { MediaErasure, MediaRetained, MediaRetainedBytes } from "./media-operation-owner.js";
6
+ export type { MediaErasure, MediaRetained, MediaRetainedBytes };
7
+ export { mediaWrittenDigest, removeMediaIfWritten, type MediaRemoval, } from "./media-written.js";
8
+ import type { MediaRemoval } from "./media-written.js";
5
9
  import { validateMediaGenerationSettings, type MediaCatalogue, type MediaProvider, type MediaReference, type MediaReferenceBytes } from "./index.js";
6
10
  import { type MediaExecution, type MediaMetering } from "./media-operation-contract.js";
7
11
  import { MediaExecutionError, type MediaBillingRefusalCode } from "./execution-error.js";
8
12
  export { createDailyMediaMetering, DailyMediaMeter, type DailyMediaMeterPort, type DailyMediaMeterStorage, } from "./daily-media-meter.js";
9
13
  export { MediaBillingRefusal, MediaExecutionError, type MediaBillingRefusalCode, type MediaFailureStage, type MediaExecutionErrorOptions, } from "./execution-error.js";
14
+ export { readHostReference, referenceFilename, type HostReferenceSource, } from "./reference-read.js";
10
15
  export { mediaUnits, type MediaUnits } from "./gateway-models.js";
11
16
  export { quoteMediaGeneration, type MediaQuote } from "./media-quote.js";
12
17
  export type { MediaMetering, MediaOperation, } from "./media-operation-contract.js";
13
18
  export { MediaOperationOwner, mediaOperationDestinationSchema, mediaOperationCoordinatesSchema, mediaOperationStateSchema, mediaImageSchema, mediaOperationResultSchema, } from "./media-operation-owner.js";
14
- export type { MediaOperationCoordinates, MediaOperationRequest, MediaOperationProjection, MediaOperationDecision, MediaOperationState, MediaOperationResult, MediaOperationEnvironment, MediaOperationHooks, MediaImage, MediaErasurePreflight, MediaErasureReadback, MediaRetentionResult, } from "./media-operation-owner.js";
15
- export type { MediaOperationContext, MediaOperationStorage, MediaOperationBucket, MediaOperationObject, } from "./media-operation-storage.js";
19
+ export type { MediaOperationCoordinates, MediaOperationRequest, MediaOperationProjection, MediaOperationDecision, MediaOperationState, MediaOperationResult, MediaOperationEnvironment, MediaOperationHooks, MediaImage, MediaErasurePreflight, MediaErasureReadback, MediaErasePolicy, MediaRetentionResult, } from "./media-operation-owner.js";
20
+ export type { MediaOperationContext, MediaOperationStorage, MediaErasureMarker, MediaOperationBucket, MediaOperationObject, } from "./media-operation-storage.js";
16
21
  /** Decode relative service generation input. Identity comes from the host. */
17
22
  export declare const mediaRequestSchema: z.ZodObject<{
18
23
  path: z.ZodString;
@@ -22,7 +27,9 @@ export declare const mediaRequestSchema: z.ZodObject<{
22
27
  width: z.ZodOptional<z.ZodNumber>;
23
28
  height: z.ZodOptional<z.ZodNumber>;
24
29
  steps: z.ZodOptional<z.ZodNumber>;
30
+ guidance: z.ZodOptional<z.ZodNumber>;
25
31
  durationSeconds: z.ZodOptional<z.ZodNumber>;
32
+ targetMegapixels: z.ZodOptional<z.ZodNumber>;
26
33
  voiceId: z.ZodOptional<z.ZodString>;
27
34
  resolution: z.ZodOptional<z.ZodEnum<{
28
35
  readonly p480: "480p";
@@ -98,11 +105,25 @@ export type MediaServiceHost = Readonly<{
98
105
  authorize: (path: string) => Promise<void>;
99
106
  /** Save exact generated bytes to the admitted destination. */
100
107
  write: (path: string, bytes: Uint8Array) => Promise<void>;
108
+ /**
109
+ * Delete the file written at `path`, only while it still holds the bytes
110
+ * with this SHA-256, so a path reused for something else is never lost.
111
+ * Use `removeMediaIfWritten` to do the compare. Report what happened;
112
+ * "kept" means this destination cannot delete files.
113
+ */
114
+ remove: (path: string, written: Readonly<{
115
+ /** SHA-256 of the bytes written. */ sha256: string;
116
+ }>) => Promise<MediaRemoval>;
101
117
  /** Authorize and fit one selected reference image for the catalog model. */
102
118
  readReference?: (reference: MediaReference, model: string) => Promise<MediaReferenceBytes>;
103
119
  /** Authorize and read the raw bytes of one reference audio clip. */
104
120
  readAudioReference?: (reference: MediaReference) => Promise<Uint8Array>;
105
121
  }>;
122
+ /**
123
+ * Opt every `/generate` request into embedding its prompt in the saved
124
+ * image's XMP metadata. Omitted keeps the prompt private.
125
+ */
126
+ embedPrompt?: boolean | undefined;
106
127
  /** Translate host authority failures; undefined uses the shared Media failure. */
107
128
  onFailure?: (error: MediaExecutionError) => Response | undefined;
108
129
  }> & (Readonly<{
@@ -140,6 +161,11 @@ export type MediaGenerationRequest = Readonly<{
140
161
  settings: Parameters<typeof validateMediaGenerationSettings>[0];
141
162
  /** Optional verified image format pin. */
142
163
  outputFormat?: z.output<typeof mediaRequestSchema>["outputFormat"];
164
+ /**
165
+ * Publish the prompt in the saved image's XMP metadata (`fungi:prompt`).
166
+ * Omitted or false keeps it out: a host must opt in for each generation.
167
+ */
168
+ embedPrompt?: boolean | undefined;
143
169
  }>;
144
170
  /** The typed result of one generation, shared by the Hono route and the Agent path. */
145
171
  export type MediaGenerationOutcome = Readonly<{
@@ -178,5 +204,35 @@ export type MediaGenerationOutcome = Readonly<{
178
204
  }>;
179
205
  /** Generate through the Effect core with a Promise boundary preserving typed domain failures. */
180
206
  export declare function generateMedia(host: MediaServiceHost, request: MediaGenerationRequest, signal?: AbortSignal): Promise<MediaGenerationOutcome>;
207
+ /**
208
+ * What one generation still retains, by its request id: where its file goes,
209
+ * and the exact provider bytes held for recovery, including bytes a crash left
210
+ * unrecorded. Null once erased. Refuses another namespace.
211
+ */
212
+ export declare function retainedMedia(host: Pick<MediaServiceHost, "operations" | "scope">, requestId: string): Promise<MediaRetained | null>;
213
+ /**
214
+ * Read back the exact provider bytes a generation retained, before any
215
+ * provenance, so a host can re-save a result whose destination write was lost.
216
+ * Null when erased or nothing was retained. Refuses another namespace.
217
+ */
218
+ export declare function readRetainedMedia(host: Pick<MediaServiceHost, "operations" | "scope">, requestId: string): Promise<MediaRetainedBytes | null>;
219
+ /** Erasure of one generation, with what happened to its destination file. */
220
+ export type MediaOperationErasure = MediaErasure & Readonly<{
221
+ /**
222
+ * What the destination did with the file this operation wrote: null when
223
+ * none was ever begun. "not-ours" means the path now holds other bytes and
224
+ * was left alone.
225
+ */
226
+ destinationFile: MediaRemoval | null;
227
+ }>;
228
+ /**
229
+ * Erase everything a generation retained or could still write: its retained
230
+ * output, reference copies, storage and the destination file (only while it
231
+ * still holds what this operation wrote). Works mid generation: the operation
232
+ * refuses later writes, deletes anything that lands, and its open billing hold
233
+ * is settled at zero units. Call again until `clear` is true; the destination
234
+ * facts are kept for that retry.
235
+ */
236
+ export declare function eraseMediaOperation(host: Pick<MediaServiceHost, "operations" | "scope" | "destination" | "metering">, requestId: string): Promise<MediaOperationErasure>;
181
237
  /** Relative HTTP routes; the caller admits identity and supplies destination access. */
182
238
  export declare function createMediaService(host: MediaServiceHost): Hono<import("hono/types").BlankEnv, import("hono/types").BlankSchema, "/">;