@fungi.computer/darkroom 0.5.12 → 0.7.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 (40) hide show
  1. package/README.md +129 -0
  2. package/dist/app-media-contracts.d.ts +4 -0
  3. package/dist/browser-failure.d.ts +2 -0
  4. package/dist/browser-failure.js +2 -0
  5. package/dist/cloudflare/provider.js +3 -3
  6. package/dist/cloudflare/reference-images.d.ts +6 -0
  7. package/dist/cloudflare/reference-images.js +25 -7
  8. package/dist/cost-estimate.js +2 -2
  9. package/dist/daily-media-meter.d.ts +55 -0
  10. package/dist/daily-media-meter.js +81 -0
  11. package/dist/execution-error.d.ts +1 -1
  12. package/dist/gateway-models.d.ts +8 -2
  13. package/dist/gateway-models.js +35 -10
  14. package/dist/gateway-wire.d.ts +1 -0
  15. package/dist/gateway-wire.js +2 -0
  16. package/dist/index.d.ts +50 -12
  17. package/dist/index.js +33 -23
  18. package/dist/media-binding.d.ts +3 -0
  19. package/dist/media-binding.js +3 -3
  20. package/dist/media-generation.js +9 -5
  21. package/dist/media-operation-contract.d.ts +3 -1
  22. package/dist/media-operation-do.d.ts +13 -2
  23. package/dist/media-operation-do.js +26 -1
  24. package/dist/media-operation-owner.d.ts +8 -0
  25. package/dist/media-operation-owner.js +8 -5
  26. package/dist/media-operation.js +2 -2
  27. package/dist/media-quote.d.ts +14 -0
  28. package/dist/media-quote.js +17 -0
  29. package/dist/model-catalog.d.ts +438 -5
  30. package/dist/model-catalog.js +232 -30
  31. package/dist/reference-image-size.d.ts +4 -3
  32. package/dist/reference-image-size.js +9 -9
  33. package/dist/server.d.ts +17 -1
  34. package/dist/server.js +44 -6
  35. package/docs/api/app-media-contracts.md +4 -0
  36. package/docs/api/browser.md +4 -2
  37. package/docs/api/cloudflare.md +53 -0
  38. package/docs/api/index.md +464 -55
  39. package/docs/api/server.md +214 -22
  40. package/package.json +2 -2
@@ -84,9 +84,11 @@ export const mediaModelInputSchema = z.lazy(() => z
84
84
  * Schema ceiling for reference lists: the largest per-model limit. Each model's
85
85
  * own `maxReferences` / `maxReferenceImages` is enforced after parsing.
86
86
  */
87
- export const MAX_REFERENCE_COUNT = 16;
87
+ export const MAX_REFERENCE_COUNT = 30;
88
88
  /** Verified Unified AI video identifiers; no inferred family aliases. */
89
89
  export const mediaVideoModelIdSchema = z.enum({
90
+ /** Seedance 2.5. */
91
+ seedance25: "bytedance/seedance-2.5",
90
92
  /** Seedance 2.0. */
91
93
  seedance: "bytedance/seedance-2.0",
92
94
  /** Seedance 2.0 Fast. */
@@ -255,6 +257,75 @@ const freezeModel = (model) => Object.freeze({
255
257
  ...model,
256
258
  input: Object.freeze(model.input),
257
259
  });
260
+ /**
261
+ * GPT Image 2's `size` is `auto` or any WIDTHxHEIGHT with each edge at most
262
+ * 3840, both edges multiples of 16, an aspect ratio between 1:3 and 3:1 and a
263
+ * total of 655,360 to 8,294,400 pixels (no enum).
264
+ * https://developers.cloudflare.com/ai/models/openai/gpt-image-2/
265
+ * https://developers.cloudflare.com/ai/models/openai/gpt-image-2/schema-input.json
266
+ * The catalog lists each common ratio at a standard size (about one megapixel;
267
+ * the three sizes Prints always offered stay as they were) and at the largest
268
+ * size the limits allow, so every entry is exact in ratio and in bounds.
269
+ */
270
+ const GPT_IMAGE_MAX_EDGE = 3_840;
271
+ /** Largest pixel count the documented size grammar admits. */
272
+ const GPT_IMAGE_MAX_PIXELS = 8_294_400;
273
+ const COMMON_IMAGE_RATIOS = [
274
+ [1, 1],
275
+ [4, 3],
276
+ [3, 4],
277
+ [3, 2],
278
+ [2, 3],
279
+ [16, 9],
280
+ [9, 16],
281
+ [21, 9],
282
+ ];
283
+ const gptImageSizes = (() => {
284
+ const keep = new Set(["1024x1024", "1024x1536", "1536x1024"]);
285
+ const standard = [];
286
+ const largest = [];
287
+ for (const [across, down] of COMMON_IMAGE_RATIOS) {
288
+ const divisor = ((a, b) => {
289
+ let x = a;
290
+ let y = b;
291
+ while (y !== 0)
292
+ [x, y] = [y, x % y];
293
+ return x;
294
+ })(across, down);
295
+ const unitW = (16 * across) / divisor;
296
+ const unitH = (16 * down) / divisor;
297
+ const unitArea = unitW * unitH;
298
+ const at = (k) => `${String(unitW * k)}x${String(unitH * k)}`;
299
+ const fit = Math.round(Math.sqrt(1_048_576 / unitArea));
300
+ const known = [...keep].find((size) => {
301
+ const [w, h] = size.split("x").map(Number);
302
+ return (w ?? 0) * down === (h ?? 0) * across;
303
+ });
304
+ standard.push(known ?? at(fit));
305
+ largest.push(at(Math.floor(Math.min(GPT_IMAGE_MAX_EDGE / Math.max(unitW, unitH), Math.sqrt(GPT_IMAGE_MAX_PIXELS / unitArea)))));
306
+ }
307
+ return Object.freeze([...standard, ...largest]);
308
+ })();
309
+ /** The common ratios as exact 16-aligned sizes of about `area` pixels. */
310
+ const commonRatioSizes = (area) => Object.freeze(COMMON_IMAGE_RATIOS.map(([across, down]) => {
311
+ let x = across;
312
+ let y = down;
313
+ while (y !== 0)
314
+ [x, y] = [y, x % y];
315
+ const unitW = (16 * across) / x;
316
+ const unitH = (16 * down) / x;
317
+ const steps = Math.round(Math.sqrt(area / (unitW * unitH)));
318
+ return `${String(unitW * steps)}x${String(unitH * steps)}`;
319
+ }));
320
+ /**
321
+ * Seedream 5 Pro takes `size` as a string: "1K", "2K" or an explicit pixel
322
+ * size (the page's examples are "1K" and "1536x864"). It documents no bounds,
323
+ * so each common ratio is listed as an exact explicit size at the scale of its
324
+ * own 1536x864 example (about 1.3 megapixels), where 16:9 is that example.
325
+ * https://developers.cloudflare.com/ai/models/bytedance/seedream-5-pro/
326
+ * https://developers.cloudflare.com/ai/models/bytedance/seedream-5-pro/schema-input.json
327
+ */
328
+ const seedreamSizes = commonRatioSizes(1536 * 864);
258
329
  const videoShortEdges = {
259
330
  "480p": 480,
260
331
  "720p": 720,
@@ -271,18 +342,38 @@ const videoAspects = {
271
342
  "21:9": [21, 9],
272
343
  "9:21": [9, 21],
273
344
  };
274
- function videoModel(id, label, tier, provider, rates) {
345
+ /**
346
+ * Seedance 2.5's own bounds, from its Cloudflare input schema (duration 4-30,
347
+ * 480p/720p, `reference_images` up to 30, a 25,000-character prompt, no 9:21).
348
+ * https://developers.cloudflare.com/ai/models/bytedance/seedance-2.5/
349
+ * Prices are Cloudflare dashboard prices, supplied by the owner 2026-11-13;
350
+ * the public model page lists none. Only the non-video-input rates apply, as
351
+ * video-input references are unsupported.
352
+ */
353
+ const seedance25 = {
354
+ maxSeconds: 30,
355
+ maxReferenceImages: 30,
356
+ maxPromptLength: 25_000,
357
+ resolutions: ["480p", "720p"],
358
+ aspects: mediaVideoAspectRatioSchema.options.filter((aspectRatio) => aspectRatio !== mediaVideoAspectRatioSchema.enum.ultratall),
359
+ };
360
+ function videoModel(id, label, tier, provider, rates, bounds) {
275
361
  const seedance = provider === "seedance";
276
- const aspects = seedance
277
- ? mediaVideoAspectRatioSchema.options
278
- : [
279
- mediaVideoAspectRatioSchema.enum.wide,
280
- mediaVideoAspectRatioSchema.enum.tall,
281
- mediaVideoAspectRatioSchema.enum.square,
282
- ];
362
+ const resolutions = bounds?.resolutions ?? rates.map(([resolution]) => resolution);
363
+ const maxSeconds = bounds?.maxSeconds ?? (seedance ? 12 : 8);
364
+ const maxReferenceImages = bounds?.maxReferenceImages ?? (seedance ? 4 : 0);
365
+ const aspects = bounds
366
+ ? bounds.aspects
367
+ : seedance
368
+ ? mediaVideoAspectRatioSchema.options
369
+ : [
370
+ mediaVideoAspectRatioSchema.enum.wide,
371
+ mediaVideoAspectRatioSchema.enum.tall,
372
+ mediaVideoAspectRatioSchema.enum.square,
373
+ ];
283
374
  // Nominal dimensions select resolution/aspect; upstream does not accept pixels.
284
375
  // Round the long edge to even pixels, retaining the existing 854x480 selector.
285
- const formats = Object.freeze(rates.flatMap(([resolution]) => aspects.map((aspectRatio) => {
376
+ const formats = Object.freeze(resolutions.flatMap((resolution) => aspects.map((aspectRatio) => {
286
377
  const [w, h] = videoAspects[aspectRatio];
287
378
  const edge = videoShortEdges[resolution];
288
379
  const shorter = Math.min(w, h);
@@ -293,30 +384,31 @@ function videoModel(id, label, tier, provider, rates) {
293
384
  height: Math.ceil((edge * h) / shorter / 2) * 2,
294
385
  });
295
386
  })));
296
- const durations = Object.freeze(seedance ? [4, 5, 6, 7, 8, 9, 10, 11, 12] : [4, 6, 8]);
387
+ const durations = Object.freeze(seedance
388
+ ? Array.from({ length: maxSeconds - 3 }, (_, index) => index + 4)
389
+ : [4, 6, 8]);
297
390
  const video = Object.freeze({
298
391
  minSeconds: 4,
299
- maxSeconds: seedance ? 12 : 8,
392
+ maxSeconds,
300
393
  defaultSeconds: seedance ? 5 : 6,
301
394
  durations,
302
395
  provider,
303
396
  formats,
304
397
  defaultResolution: "720p",
305
398
  defaultAspectRatio: "16:9",
306
- // Seedance documents `generate_audio` without a default; Veo documents
307
- // `generate_audio` with default true.
399
+ // Veo documents `generate_audio` with default true. Seedance documents no
400
+ // default; Botanical chooses On (priced the same as silent) so a prompt's
401
+ // AUDIO and dialogue lines take effect without touching the control.
308
402
  // https://developers.cloudflare.com/ai/models/bytedance/seedance-2.0/
309
403
  // https://developers.cloudflare.com/ai/models/google/veo-3.1/
310
404
  supportsAudio: true,
311
- defaultGenerateAudio: seedance ? null : true,
405
+ defaultGenerateAudio: true,
312
406
  referenceRoles: Object.freeze(seedance
313
407
  ? mediaVideoReferenceRoleSchema.options
314
408
  : [mediaVideoReferenceRoleSchema.enum.first]),
315
- maxReferenceImages: seedance ? 4 : 0,
409
+ maxReferenceImages,
316
410
  referenceResolutions: Object.freeze(seedance
317
- ? rates
318
- .map(([resolution]) => resolution)
319
- .filter((resolution) => resolution !== "1080p")
411
+ ? resolutions.filter((resolution) => resolution !== "1080p")
320
412
  : []),
321
413
  prices: Object.freeze(rates.map(([resolution, silentMilliunitsPerSecond, audioMilliunitsPerSecond]) => Object.freeze({
322
414
  resolution,
@@ -328,10 +420,12 @@ function videoModel(id, label, tier, provider, rates) {
328
420
  id,
329
421
  label,
330
422
  tier,
331
- // Seedance: the provider's own 2,000-character bound (retained from the
332
- // earlier video contract).
423
+ // Seedance 2.0, Fast and Mini: 10,000 characters, from each Cloudflare
424
+ // input schema (the earlier 2,000 rejected real ~2,500-character
425
+ // production prompts). https://developers.cloudflare.com/ai/models/bytedance/seedance-2.0/
333
426
  // Veo documents no character limit; keep the retained 2,048 host cap.
334
- maxPromptLength: seedance ? 2_000 : UNDOCUMENTED_PROMPT_LENGTH,
427
+ maxPromptLength: bounds?.maxPromptLength ??
428
+ (seedance ? 10_000 : UNDOCUMENTED_PROMPT_LENGTH),
335
429
  kind: "video",
336
430
  video,
337
431
  sizes: Object.freeze(formats.map(({ width, height }) => `${String(width)}x${String(height)}`)),
@@ -346,7 +440,7 @@ function videoModel(id, label, tier, provider, rates) {
346
440
  maxSteps: null,
347
441
  defaultSteps: null,
348
442
  referenceField: seedance ? "image" : "image_input",
349
- maxReferences: seedance ? 4 : 1,
443
+ maxReferences: seedance ? maxReferenceImages : 1,
350
444
  referenceDimension: null,
351
445
  referenceFormat: "png",
352
446
  },
@@ -605,12 +699,12 @@ const models = Object.freeze([
605
699
  outputFormats: Object.freeze(["png", "jpeg", "webp"]),
606
700
  tier: "premium",
607
701
  label: "GPT Image 2 — strong text and layout, premium",
608
- sizes: Object.freeze(["1024x1024", "1024x1536", "1536x1024"]),
702
+ sizes: gptImageSizes,
609
703
  input: {
610
704
  transport: "json",
611
705
  dimensions: "own",
612
- maxDimension: 1536,
613
- maxDimensionDocumented: false,
706
+ maxDimension: GPT_IMAGE_MAX_EDGE,
707
+ maxDimensionDocumented: true,
614
708
  defaultWidth: 1024,
615
709
  defaultHeight: 1024,
616
710
  steps: "fixed",
@@ -633,6 +727,40 @@ const models = Object.freeze([
633
727
  referenceFormat: "webp",
634
728
  },
635
729
  }),
730
+ freezeModel({
731
+ id: "bytedance/seedream-5-pro",
732
+ // The page documents no prompt maxLength (schema-input.json has none):
733
+ // keep the 2,048 host cap.
734
+ maxPromptLength: UNDOCUMENTED_PROMPT_LENGTH,
735
+ // The page's example results are .jpeg URLs; the schema has no format field.
736
+ outputFormats: Object.freeze(["jpeg"]),
737
+ tier: "premium",
738
+ label: "Seedream 5 Pro — ByteDance, high-quality images",
739
+ sizes: seedreamSizes,
740
+ input: {
741
+ transport: "json",
742
+ dimensions: "own",
743
+ // The longest listed edge: the page documents no maximum.
744
+ maxDimension: 1792,
745
+ maxDimensionDocumented: false,
746
+ defaultWidth: 1536,
747
+ defaultHeight: 864,
748
+ steps: "fixed",
749
+ maxSteps: null,
750
+ defaultSteps: null,
751
+ // The page says the model takes up to 10 reference images (`image`, a
752
+ // string or 1-10 strings) but shows only URL inputs and states no
753
+ // base64 or data-URI form, so Prints sends none until it does.
754
+ referenceField: null,
755
+ maxReferences: 0,
756
+ referenceDimension: 512,
757
+ referenceFormat: "png",
758
+ },
759
+ }),
760
+ videoModel(mediaVideoModelIdSchema.enum.seedance25, "Seedance 2.5", "balanced", "seedance", [
761
+ ["480p", 10_280, 10_280],
762
+ ["720p", 23_120, 23_120],
763
+ ], seedance25),
636
764
  videoModel(mediaVideoModelIdSchema.enum.seedance, "Seedance 2.0", "balanced", "seedance", [
637
765
  ["480p", 7_000, 7_000],
638
766
  ["720p", 15_000, 15_000],
@@ -657,12 +785,86 @@ const models = Object.freeze([
657
785
  ]),
658
786
  minimaxVideoModel(),
659
787
  ]);
660
- /** The immutable image and video model catalog. */
788
+ /** The Fungi gateway provider's own immutable image and video model catalog. */
661
789
  export const mediaModels = models;
662
- /** List all image and video models in catalog order. */
790
+ /**
791
+ * One catalogue entry. Same grammar as the gateway's wire entry, except that a
792
+ * video model may name `host` as its provider family: the injected provider
793
+ * owns that model's wire grammar and Darkroom builds no gateway request for it.
794
+ */
795
+ export const mediaCatalogueModelSchema = mediaModelSchema
796
+ .unwrap()
797
+ .extend({
798
+ /** Video length constraints, or null for a still-image model. */
799
+ video: mediaVideoSchema
800
+ .unwrap()
801
+ .unwrap()
802
+ .extend({
803
+ /** Provider translation family, or `host` for a host-injected provider. */
804
+ provider: z.enum({
805
+ /** Seedance integer duration and data-URI image fields. */
806
+ seedance: "seedance",
807
+ /** Veo duration string and base64 image_input. */
808
+ veo: "veo",
809
+ /** MiniMax multimodal `content[]` array and uppercase resolution. */
810
+ minimax: "minimax",
811
+ /** The injected provider owns the wire grammar. */
812
+ host: "host",
813
+ }),
814
+ })
815
+ .readonly()
816
+ .nullable(),
817
+ })
818
+ .readonly();
819
+ /** Upper bound on one provider's model list. */
820
+ const MAX_CATALOGUE_MODELS = 256;
821
+ /**
822
+ * Decode a host-supplied provider catalogue. Each entry is the same typed wire
823
+ * grammar the built-in catalogue uses; this adds the cross-field facts the
824
+ * validator relies on (unique ids, video metadata iff `kind` is video, defaults
825
+ * inside their own bounds).
826
+ */
827
+ export const mediaCatalogueSchema = z
828
+ .array(mediaCatalogueModelSchema)
829
+ .min(1)
830
+ .max(MAX_CATALOGUE_MODELS)
831
+ .superRefine((entries, context) => {
832
+ const seen = new Set();
833
+ entries.forEach((model, index) => {
834
+ const report = (message) => {
835
+ context.addIssue({ code: "custom", message, path: [index] });
836
+ };
837
+ if (seen.has(model.id))
838
+ report(`duplicate model id "${model.id}"`);
839
+ seen.add(model.id);
840
+ if ((model.kind === "video") !== (model.video !== null))
841
+ report(`${model.id} must carry video bounds exactly when kind is video`);
842
+ const video = model.video;
843
+ if (video === null)
844
+ return;
845
+ if (video.minSeconds > video.maxSeconds ||
846
+ video.durations.some((seconds) => seconds < video.minSeconds || seconds > video.maxSeconds) ||
847
+ !video.durations.includes(video.defaultSeconds))
848
+ report(`${model.id} durations must sit inside min/max and include the default`);
849
+ if (!video.formats.some(({ resolution, aspectRatio }) => resolution === video.defaultResolution &&
850
+ aspectRatio === video.defaultAspectRatio))
851
+ report(`${model.id} formats must include the default resolution and aspect`);
852
+ });
853
+ })
854
+ .transform((entries) => Object.freeze(entries.map((model) => Object.freeze({ ...model, input: Object.freeze(model.input) }))));
855
+ /** Decode untrusted catalogue data, throwing a MediaSettingsError that names the first problem. */
856
+ export const parseMediaCatalogue = (raw) => {
857
+ const parsed = mediaCatalogueSchema.safeParse(raw);
858
+ if (!parsed.success)
859
+ throw new MediaSettingsError(`media catalogue is invalid: ${parsed.error.issues[0]?.message ?? "unreadable"}`);
860
+ return parsed.data;
861
+ };
862
+ /** List the gateway provider's models in catalog order. */
663
863
  export const listMediaModels = () => mediaModels;
664
- /** Find a model by provider identifier, returning undefined when it is absent. */
665
- export const getMediaModel = (id) => mediaModels.find((model) => model.id === id);
864
+ /** Find a model in the Fungi gateway's own catalogue; gateway-internal code never sees a custom provider's models. */
865
+ export const getGatewayModel = (id) => mediaModels.find((model) => model.id === id);
866
+ /** Find a model in `catalogue` (the gateway's by default), or undefined when absent. */
867
+ export const getMediaModel = (id, catalogue = mediaModels) => catalogue.find((model) => model.id === id);
666
868
  /** Invalid generation settings or unsupported model parameters. */
667
869
  export class MediaSettingsError extends Error {
668
870
  constructor(message) {
@@ -1,10 +1,11 @@
1
+ import { type MediaCatalogue } from "./model-catalog.js";
1
2
  /** Aspect-preserving native resize; only video references may be enlarged. */
2
- export declare function referenceImageTransform(modelId: string, width: number, height: number): {
3
+ export declare function referenceImageTransform(modelId: string, width: number, height: number, catalogue?: MediaCatalogue): {
3
4
  width: number;
4
5
  height: number;
5
6
  fit: "contain" | "scale-down";
6
7
  };
7
8
  /** Validate actual decoded output, rather than trusting requested resize dimensions. */
8
- export declare function referenceImageSizeIsValid(modelId: string, width: number, height: number): boolean;
9
+ export declare function referenceImageSizeIsValid(modelId: string, width: number, height: number, catalogue?: MediaCatalogue): boolean;
9
10
  /** The encoding the selected model's fitted references are sent in. */
10
- export declare function referenceImageFormat(modelId: string): "image/webp" | "image/png";
11
+ export declare function referenceImageFormat(modelId: string, catalogue?: MediaCatalogue): "image/webp" | "image/png";
@@ -1,8 +1,8 @@
1
- import { getMediaModel, MediaSettingsError } from "./model-catalog.js";
1
+ import { getMediaModel, mediaModels, MediaSettingsError, } from "./model-catalog.js";
2
2
  const MIN_VIDEO_REFERENCE_DIMENSION = 320;
3
3
  /** One owner for both native fitting and the resolved-reference boundary. */
4
- function sizing(modelId) {
5
- const model = getMediaModel(modelId);
4
+ function sizing(modelId, catalogue) {
5
+ const model = getMediaModel(modelId, catalogue);
6
6
  if (model === undefined)
7
7
  throw new MediaSettingsError("unknown Media model");
8
8
  return model.video === null && model.input.referenceDimension !== null
@@ -10,8 +10,8 @@ function sizing(modelId) {
10
10
  : { edge: "short", dimension: MIN_VIDEO_REFERENCE_DIMENSION };
11
11
  }
12
12
  /** Aspect-preserving native resize; only video references may be enlarged. */
13
- export function referenceImageTransform(modelId, width, height) {
14
- const rule = sizing(modelId);
13
+ export function referenceImageTransform(modelId, width, height, catalogue = mediaModels) {
14
+ const rule = sizing(modelId, catalogue);
15
15
  const edge = rule.edge === "short" ? Math.min(width, height) : Math.max(width, height);
16
16
  const ratio = rule.edge === "short"
17
17
  ? rule.dimension / edge
@@ -27,15 +27,15 @@ export function referenceImageTransform(modelId, width, height) {
27
27
  };
28
28
  }
29
29
  /** Validate actual decoded output, rather than trusting requested resize dimensions. */
30
- export function referenceImageSizeIsValid(modelId, width, height) {
31
- const rule = sizing(modelId);
30
+ export function referenceImageSizeIsValid(modelId, width, height, catalogue = mediaModels) {
31
+ const rule = sizing(modelId, catalogue);
32
32
  return rule.edge === "short"
33
33
  ? Math.min(width, height) >= rule.dimension
34
34
  : Math.max(width, height) <= rule.dimension;
35
35
  }
36
36
  /** The encoding the selected model's fitted references are sent in. */
37
- export function referenceImageFormat(modelId) {
38
- const model = getMediaModel(modelId);
37
+ export function referenceImageFormat(modelId, catalogue = mediaModels) {
38
+ const model = getMediaModel(modelId, catalogue);
39
39
  if (model === undefined)
40
40
  throw new MediaSettingsError("unknown Media model");
41
41
  return model.input.referenceFormat === "webp"
package/dist/server.d.ts CHANGED
@@ -2,11 +2,13 @@ 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 { validateMediaGenerationSettings, type MediaProvider, type MediaReference, type MediaReferenceBytes } from "./index.js";
5
+ import { validateMediaGenerationSettings, type MediaCatalogue, type MediaProvider, type MediaReference, type MediaReferenceBytes } from "./index.js";
6
6
  import { type MediaExecution, type MediaMetering } from "./media-operation-contract.js";
7
7
  import { MediaExecutionError, type MediaBillingRefusalCode } from "./execution-error.js";
8
+ export { createDailyMediaMetering, DailyMediaMeter, type DailyMediaMeterPort, type DailyMediaMeterStorage, } from "./daily-media-meter.js";
8
9
  export { MediaBillingRefusal, MediaExecutionError, type MediaBillingRefusalCode, type MediaFailureStage, type MediaExecutionErrorOptions, } from "./execution-error.js";
9
10
  export { mediaUnits, type MediaUnits } from "./gateway-models.js";
11
+ export { quoteMediaGeneration, type MediaQuote } from "./media-quote.js";
10
12
  export type { MediaMetering, MediaOperation, } from "./media-operation-contract.js";
11
13
  export { MediaOperationOwner, mediaOperationDestinationSchema, mediaOperationCoordinatesSchema, mediaOperationStateSchema, mediaImageSchema, mediaOperationResultSchema, } from "./media-operation-owner.js";
12
14
  export type { MediaOperationCoordinates, MediaOperationRequest, MediaOperationProjection, MediaOperationDecision, MediaOperationState, MediaOperationResult, MediaOperationEnvironment, MediaOperationHooks, MediaImage, MediaErasurePreflight, MediaErasureReadback, MediaRetentionResult, } from "./media-operation-owner.js";
@@ -97,6 +99,20 @@ export type MediaServiceHost = Readonly<{
97
99
  /** Translate host authority failures; undefined uses the shared Media failure. */
98
100
  onFailure?: (error: MediaExecutionError) => Response | undefined;
99
101
  }> & (Readonly<{
102
+ /** Omitted: the Fungi gateway provider's own catalogue and quote. */
103
+ catalogue?: undefined;
104
+ /** Omitted with the catalogue: the gateway's own quote. */
105
+ estimate?: undefined;
106
+ }> | Readonly<{
107
+ /**
108
+ * The injected `provider`'s own model list, decoded with
109
+ * `parseMediaCatalogue`. Requests are validated against it, never
110
+ * against the Fungi gateway's.
111
+ */
112
+ catalogue: MediaCatalogue;
113
+ /** Provider cost of validated settings in milliunits; owned by the custom provider. */
114
+ estimate: (settings: Parameters<MediaProvider>[0], references: readonly MediaReferenceBytes[]) => number;
115
+ }>) & (Readonly<{
100
116
  /** The host pays its own provider directly. */
101
117
  metering: "unmetered";
102
118
  /** Unmetered hosts do not have billing refusal policy. */
package/dist/server.js CHANGED
@@ -7,11 +7,14 @@ import { AppError, describeAppError } from "@fungi.computer/agar/errors";
7
7
  import * as Effect from "effect/Effect";
8
8
  import * as Result from "effect/Result";
9
9
  import { runMediaGeneration } from "./media-generation.js";
10
- import { validateMediaGenerationSettings, listMediaModels, mediaGenerationSettingsSchema, mediaRequestedImageFormatSchema, MediaSettingsError, } from "./index.js";
10
+ import { quoteMediaGeneration } from "./media-quote.js";
11
+ import { validateMediaGenerationSettings, mediaModels, mediaGenerationSettingsSchema, mediaRequestedImageFormatSchema, MediaSettingsError, } from "./index.js";
11
12
  import { mediaResultSchema, } from "./media-operation-contract.js";
12
13
  import { MediaOutputFormatMismatch, MediaBillingRefusal, MediaExecutionError, MediaSafetyFilterRefusal, } from "./execution-error.js";
14
+ export { createDailyMediaMetering, DailyMediaMeter, } from "./daily-media-meter.js";
13
15
  export { MediaBillingRefusal, MediaExecutionError, } from "./execution-error.js";
14
16
  export { mediaUnits } from "./gateway-models.js";
17
+ export { quoteMediaGeneration } from "./media-quote.js";
15
18
  export { MediaOperationOwner, mediaOperationDestinationSchema, mediaOperationCoordinatesSchema, mediaOperationStateSchema, mediaImageSchema, mediaOperationResultSchema, } from "./media-operation-owner.js";
16
19
  const identifier = z.lazy(() => z.string().min(1).max(256));
17
20
  /** Decode relative service generation input. Identity comes from the host. */
@@ -27,6 +30,10 @@ export const mediaRequestSchema = z.strictObject({
27
30
  /** Optional verified image encoding pin. */
28
31
  outputFormat: mediaRequestedImageFormatSchema.optional(),
29
32
  });
33
+ /** A price request: the exact settings, no destination or request id. */
34
+ const mediaQuoteRequestSchema = z.strictObject({
35
+ settings: mediaGenerationSettingsSchema,
36
+ });
30
37
  export { mediaResultSchema } from "./media-operation-contract.js";
31
38
  async function readJsonBody(request) {
32
39
  try {
@@ -46,6 +53,11 @@ const headers = {
46
53
  "Cache-Control": "private, no-store",
47
54
  "X-Content-Type-Options": "nosniff",
48
55
  };
56
+ const billingRefusalWire = {
57
+ insufficient_credits: { code: "INSUFFICIENT_CREDIT", status: 402 },
58
+ denied: { code: "CAPABILITY_DENIED", status: 403 },
59
+ daily_limit_reached: { code: "DAILY_LIMIT_REACHED", status: 429 },
60
+ };
49
61
  function failure(error, refusalMessages) {
50
62
  if (error instanceof MediaSafetyFilterRefusal)
51
63
  return Response.json({
@@ -76,12 +88,10 @@ function failure(error, refusalMessages) {
76
88
  error: refusalMessages?.[error.cause.code] ??
77
89
  "Media generation was refused by the host.",
78
90
  stage: "billing",
79
- code: error.cause.code === "insufficient_credits"
80
- ? "INSUFFICIENT_CREDIT"
81
- : "CAPABILITY_DENIED",
91
+ code: billingRefusalWire[error.cause.code].code,
82
92
  retryable: false,
83
93
  }, {
84
- status: error.cause.code === "denied" ? 403 : 402,
94
+ status: billingRefusalWire[error.cause.code].status,
85
95
  headers,
86
96
  });
87
97
  if (error instanceof MediaSettingsError ||
@@ -192,7 +202,7 @@ function outcomeResponse(outcome) {
192
202
  /** Relative HTTP routes; the caller admits identity and supplies destination access. */
193
203
  export function createMediaService(host) {
194
204
  const app = new Hono();
195
- app.get("/models", () => Response.json(listMediaModels().map((model) => host.destination.readReference !== undefined ||
205
+ app.get("/models", () => Response.json((host.catalogue ?? mediaModels).map((model) => host.destination.readReference !== undefined ||
196
206
  model.input.maxReferences === 0
197
207
  ? model
198
208
  : {
@@ -224,5 +234,33 @@ export function createMediaService(host) {
224
234
  : undefined) ?? failure(error, host.refusalMessages),
225
235
  })));
226
236
  });
237
+ // The provider cost of one exact request, priced by the same estimator and
238
+ // reference reads as /generate; the host applies any billing policy.
239
+ app.post("/quote", async (context) => {
240
+ const body = await readJsonBody(context.req.raw);
241
+ const input = body.kind === "parsed"
242
+ ? mediaQuoteRequestSchema.safeParse(body.value)
243
+ : undefined;
244
+ if (input?.success !== true)
245
+ return failure(new MediaSettingsError("invalid request"));
246
+ try {
247
+ const quote = await quoteMediaGeneration(input.data.settings, {
248
+ read: (reference, model) => {
249
+ if (host.destination.readReference === undefined)
250
+ throw new MediaSettingsError("reference images are unavailable");
251
+ return host.destination.readReference(reference, model);
252
+ },
253
+ });
254
+ return Response.json(quote, { headers });
255
+ }
256
+ catch (cause) {
257
+ if (cause instanceof MediaSettingsError)
258
+ return failure(cause);
259
+ const error = cause instanceof MediaExecutionError
260
+ ? cause
261
+ : new MediaExecutionError("estimate", { cause });
262
+ return host.onFailure?.(error) ?? failure(error, host.refusalMessages);
263
+ }
264
+ });
227
265
  return app;
228
266
  }
@@ -449,6 +449,7 @@ Missing-library refusal decoded and returned by the App media broker.
449
449
  const appMediaBrokerFailureSchema: ZodObject<{
450
450
  error: ZodEnum<{
451
451
  CAPABILITY_DENIED: "CAPABILITY_DENIED";
452
+ DAILY_LIMIT_REACHED: "DAILY_LIMIT_REACHED";
452
453
  INSUFFICIENT_CREDIT: "INSUFFICIENT_CREDIT";
453
454
  HOST_FAILURE: "HOST_FAILURE";
454
455
  INVALID_ARGUMENT: "INVALID_ARGUMENT";
@@ -502,6 +503,7 @@ const appMediaRefusalSchema: ZodUnion<readonly [ZodObject<{
502
503
  }, $strict>>, ZodObject<{
503
504
  error: ZodEnum<{
504
505
  CAPABILITY_DENIED: "CAPABILITY_DENIED";
506
+ DAILY_LIMIT_REACHED: "DAILY_LIMIT_REACHED";
505
507
  INSUFFICIENT_CREDIT: "INSUFFICIENT_CREDIT";
506
508
  HOST_FAILURE: "HOST_FAILURE";
507
509
  INVALID_ARGUMENT: "INVALID_ARGUMENT";
@@ -597,6 +599,7 @@ const appMediaModelsOutcomeSchema: ZodUnion<readonly [ZodLazy<ZodArray<ZodReadon
597
599
  }, $strict>>, ZodObject<{
598
600
  error: ZodEnum<{
599
601
  CAPABILITY_DENIED: "CAPABILITY_DENIED";
602
+ DAILY_LIMIT_REACHED: "DAILY_LIMIT_REACHED";
600
603
  INSUFFICIENT_CREDIT: "INSUFFICIENT_CREDIT";
601
604
  HOST_FAILURE: "HOST_FAILURE";
602
605
  INVALID_ARGUMENT: "INVALID_ARGUMENT";
@@ -669,6 +672,7 @@ const appMediaGenerationOutcomeSchema: ZodUnion<readonly [ZodObject<{
669
672
  }, $strict>>, ZodObject<{
670
673
  error: ZodEnum<{
671
674
  CAPABILITY_DENIED: "CAPABILITY_DENIED";
675
+ DAILY_LIMIT_REACHED: "DAILY_LIMIT_REACHED";
672
676
  INSUFFICIENT_CREDIT: "INSUFFICIENT_CREDIT";
673
677
  HOST_FAILURE: "HOST_FAILURE";
674
678
  INVALID_ARGUMENT: "INVALID_ARGUMENT";
@@ -62,6 +62,7 @@ const mediaFailureSchema: ZodObject<{
62
62
  }>;
63
63
  code: ZodEnum<{
64
64
  CAPABILITY_DENIED: "CAPABILITY_DENIED";
65
+ DAILY_LIMIT_REACHED: "DAILY_LIMIT_REACHED";
65
66
  INSUFFICIENT_CREDIT: "INSUFFICIENT_CREDIT";
66
67
  HOST_FAILURE: "HOST_FAILURE";
67
68
  INVALID_ARGUMENT: "INVALID_ARGUMENT";
@@ -101,6 +102,7 @@ function readMediaFailure(
101
102
  | "destination-write";
102
103
  code:
103
104
  | "CAPABILITY_DENIED"
105
+ | "DAILY_LIMIT_REACHED"
104
106
  | "INSUFFICIENT_CREDIT"
105
107
  | "HOST_FAILURE"
106
108
  | "INVALID_ARGUMENT"
@@ -127,8 +129,8 @@ Read and decode one Media host failure at the browser HTTP boundary.
127
129
  \| `"generation-authorization"` \| `"settings"` \| `"estimate"` \| `"billing"`
128
130
  \| `"operation"` \| `"normalization"` \| `"artifact"` \|
129
131
  `"destination-authorization"` \| `"destination-write"`; `code`: \|
130
- `"CAPABILITY_DENIED"` \| `"INSUFFICIENT_CREDIT"` \| `"HOST_FAILURE"` \|
131
- `"INVALID_ARGUMENT"` \| `"MEDIA_PROVIDER_FAILURE"` \|
132
+ `"CAPABILITY_DENIED"` \| `"DAILY_LIMIT_REACHED"` \| `"INSUFFICIENT_CREDIT"` \|
133
+ `"HOST_FAILURE"` \| `"INVALID_ARGUMENT"` \| `"MEDIA_PROVIDER_FAILURE"` \|
132
134
  `"MEDIA_PROVIDER_FAILURE_UNCHARGED"` \| `"SAFETY_FILTER_REFUSED"`; `retryable`:
133
135
  `boolean`; `provider?`: `MediaProviderDiagnostic`; \} \| `null`\>
134
136
 
@@ -18,6 +18,10 @@ Cloudflare lifecycle and RPC surface around the durable media owner.
18
18
 
19
19
  - `DurableObject`\<[`MediaOperationCloudflareEnvironment`](#mediaoperationcloudflareenvironment)\>
20
20
 
21
+ #### Implements
22
+
23
+ - [`DailyMediaMeterPort`](server.md#dailymediameterport)
24
+
21
25
  #### Constructors
22
26
 
23
27
  ##### Constructor
@@ -45,6 +49,55 @@ DurableObject<MediaOperationCloudflareEnvironment>.constructor
45
49
 
46
50
  #### Methods
47
51
 
52
+ ##### dailyAdmit()
53
+
54
+ ```ts
55
+ dailyAdmit(...input): boolean;
56
+ ```
57
+
58
+ Admit one generation against today's hard stop; false means the daily limit is
59
+ reached.
60
+
61
+ ###### Parameters
62
+
63
+ | Parameter | Type |
64
+ | ---------- | --------------------------------------------------------------------------------------------------------- |
65
+ | ...`input` | \[`Readonly`\<\{ `operationId`: `string`; `costMilliunits`: `number`; `limitMilliunits`: `number`; \}\>\] |
66
+
67
+ ###### Returns
68
+
69
+ `boolean`
70
+
71
+ ###### Implementation of
72
+
73
+ ```ts
74
+ DailyMediaMeterPort.dailyAdmit;
75
+ ```
76
+
77
+ ##### dailySettle()
78
+
79
+ ```ts
80
+ dailySettle(...input): void;
81
+ ```
82
+
83
+ Settle an admitted generation once its outcome is known.
84
+
85
+ ###### Parameters
86
+
87
+ | Parameter | Type |
88
+ | ---------- | ------------------------------------------------------------------------ |
89
+ | ...`input` | \[`Readonly`\<\{ `operationId`: `string`; `delivered`: `boolean`; \}\>\] |
90
+
91
+ ###### Returns
92
+
93
+ `void`
94
+
95
+ ###### Implementation of
96
+
97
+ ```ts
98
+ DailyMediaMeterPort.dailySettle;
99
+ ```
100
+
48
101
  ##### read()
49
102
 
50
103
  ```ts