@fungi.computer/darkroom 0.6.0 → 0.8.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 (53) hide show
  1. package/README.md +178 -0
  2. package/dist/app-media-contracts.d.ts +107 -12
  3. package/dist/audio-providers/elevenlabs.d.ts +40 -0
  4. package/dist/audio-providers/elevenlabs.js +69 -0
  5. package/dist/audio-reference-types.d.ts +28 -0
  6. package/dist/audio-reference-types.js +16 -0
  7. package/dist/audio-references.d.ts +14 -0
  8. package/dist/audio-references.js +69 -0
  9. package/dist/browser-failure.d.ts +2 -0
  10. package/dist/browser-failure.js +2 -0
  11. package/dist/cloudflare/provider.d.ts +6 -4
  12. package/dist/cloudflare/provider.js +39 -21
  13. package/dist/cloudflare/reference-images.d.ts +6 -0
  14. package/dist/cloudflare/reference-images.js +25 -7
  15. package/dist/cost-estimate.js +2 -2
  16. package/dist/daily-media-meter.d.ts +55 -0
  17. package/dist/daily-media-meter.js +81 -0
  18. package/dist/execution-error.d.ts +1 -1
  19. package/dist/gateway-models.d.ts +19 -9
  20. package/dist/gateway-models.js +57 -19
  21. package/dist/gateway-wire.d.ts +1 -0
  22. package/dist/gateway-wire.js +2 -0
  23. package/dist/index.d.ts +116 -24
  24. package/dist/index.js +147 -26
  25. package/dist/media-binding.d.ts +60 -7
  26. package/dist/media-binding.js +43 -21
  27. package/dist/media-generation.js +20 -7
  28. package/dist/media-operation-contract.d.ts +9 -3
  29. package/dist/media-operation-contract.js +6 -4
  30. package/dist/media-operation-do.d.ts +13 -2
  31. package/dist/media-operation-do.js +26 -1
  32. package/dist/media-operation-owner.d.ts +10 -2
  33. package/dist/media-operation-owner.js +56 -11
  34. package/dist/media-operation.js +5 -3
  35. package/dist/media-quote.d.ts +14 -0
  36. package/dist/media-quote.js +17 -0
  37. package/dist/model-catalog.d.ts +602 -6
  38. package/dist/model-catalog.js +309 -9
  39. package/dist/reference-image-size.d.ts +4 -3
  40. package/dist/reference-image-size.js +9 -9
  41. package/dist/server.d.ts +31 -8
  42. package/dist/server.js +51 -8
  43. package/dist/video-providers/reference-encoding.d.ts +7 -2
  44. package/dist/video-providers/reference-encoding.js +14 -3
  45. package/dist/video-providers/types.d.ts +2 -2
  46. package/dist/video-providers/unified.d.ts +1 -0
  47. package/dist/video-providers/unified.js +4 -2
  48. package/docs/api/app-media-contracts.md +50 -10
  49. package/docs/api/browser.md +4 -2
  50. package/docs/api/cloudflare.md +56 -3
  51. package/docs/api/index.md +1042 -121
  52. package/docs/api/server.md +306 -50
  53. package/package.json +3 -2
@@ -0,0 +1,69 @@
1
+ import { parseBuffer } from "music-metadata";
2
+ import { getMediaModel, MediaSettingsError, mediaModels, } from "./model-catalog.js";
3
+ import { MAX_AUDIO_REFERENCE_BODY_BYTES, MAX_AUDIO_REFERENCE_BYTES, checkAudioReferenceBudget, } from "./audio-reference-types.js";
4
+ /** music-metadata's container names, matched case-insensitively. */
5
+ function mimeTypeOf(container) {
6
+ const name = (container ?? "").toLowerCase();
7
+ if (name === "mpeg")
8
+ return "audio/mpeg";
9
+ if (name === "wave")
10
+ return "audio/wav";
11
+ if (name === "ogg")
12
+ return "audio/ogg";
13
+ if (name === "m4a" || name === "mp4" || name.startsWith("iso"))
14
+ return "audio/mp4";
15
+ throw new MediaSettingsError("audio reference is not an mp3, m4a, wav, ogg or opus file");
16
+ }
17
+ /**
18
+ * Read one clip's duration and container with music-metadata, the maintained
19
+ * parser. `duration: true` makes it scan a stream whose header has no length.
20
+ */
21
+ async function readAudioReference(bytes, filename) {
22
+ if (bytes.byteLength === 0 || bytes.byteLength > MAX_AUDIO_REFERENCE_BYTES)
23
+ throw new MediaSettingsError("audio reference is unavailable or exceeds the byte limit");
24
+ let metadata;
25
+ try {
26
+ metadata = await parseBuffer(bytes, undefined, { duration: true });
27
+ }
28
+ catch (cause) {
29
+ throw new MediaSettingsError("audio reference could not be read as audio", {
30
+ cause,
31
+ });
32
+ }
33
+ const durationSeconds = metadata.format.duration;
34
+ if (durationSeconds === undefined ||
35
+ !Number.isFinite(durationSeconds) ||
36
+ durationSeconds <= 0)
37
+ throw new MediaSettingsError("audio reference has no readable duration");
38
+ const clip = {
39
+ bytes,
40
+ mimeType: mimeTypeOf(metadata.format.container),
41
+ durationSeconds,
42
+ };
43
+ return Object.freeze(filename === undefined ? clip : { ...clip, filename });
44
+ }
45
+ /**
46
+ * Read every reference clip through the caller's reader and parse each with
47
+ * music-metadata. The model's declared clip count and total duration are
48
+ * enforced here, before billing admission; nothing is clamped or dropped.
49
+ */
50
+ export const resolveMediaAudioReferences = async (settings, reader, catalogue = mediaModels) => {
51
+ const references = settings.audioReferences ?? [];
52
+ if (references.length === 0)
53
+ return Object.freeze([]);
54
+ const model = getMediaModel(settings.model, catalogue);
55
+ const limits = model?.video?.audioReferences ?? null;
56
+ if (model === undefined || limits === null)
57
+ throw new MediaSettingsError(`${model?.label ?? settings.model} does not take audio references`);
58
+ const resolved = [];
59
+ let totalBytes = 0;
60
+ for (const reference of references) {
61
+ const bytes = await reader.read(reference);
62
+ totalBytes += bytes.byteLength;
63
+ if (totalBytes > MAX_AUDIO_REFERENCE_BODY_BYTES)
64
+ throw new MediaSettingsError("audio references exceed the total request size limit");
65
+ resolved.push(await readAudioReference(bytes, reference.path.split("/").at(-1) ?? "reference"));
66
+ }
67
+ checkAudioReferenceBudget(model.label, limits, resolved);
68
+ return Object.freeze(resolved);
69
+ };
@@ -23,6 +23,8 @@ export declare const mediaFailureSchema: z.ZodObject<{
23
23
  code: z.ZodEnum<{
24
24
  /** Host admission or Computer access was denied. */
25
25
  readonly CAPABILITY_DENIED: "CAPABILITY_DENIED";
26
+ /** The host's daily media spending limit is used up until 00:00 UTC. */
27
+ readonly DAILY_LIMIT_REACHED: "DAILY_LIMIT_REACHED";
26
28
  /** Host billing did not admit this attempt. */
27
29
  readonly INSUFFICIENT_CREDIT: "INSUFFICIENT_CREDIT";
28
30
  /** The host could not complete generation or saving. */
@@ -13,6 +13,8 @@ export const mediaFailureSchema = z.strictObject({
13
13
  code: z.enum({
14
14
  /** Host admission or Computer access was denied. */
15
15
  CAPABILITY_DENIED: "CAPABILITY_DENIED",
16
+ /** The host's daily media spending limit is used up until 00:00 UTC. */
17
+ DAILY_LIMIT_REACHED: "DAILY_LIMIT_REACHED",
16
18
  /** Host billing did not admit this attempt. */
17
19
  INSUFFICIENT_CREDIT: "INSUFFICIENT_CREDIT",
18
20
  /** The host could not complete generation or saving. */
@@ -1,4 +1,4 @@
1
- import { type MediaModel, type MediaAiResult, type MediaGenerationSettings, type MediaProvider, type MediaReferenceBytes } from "../index.js";
1
+ import { type MediaModel, type MediaAiResult, type MediaAudioReferenceBytes, type MediaGenerationSettings, type MediaProvider, type MediaReferenceBytes } from "../index.js";
2
2
  /** Quote the catalog defaults through the exact estimator used before dispatch. */
3
3
  export declare function estimateMediaModel(model: MediaModel): {
4
4
  /** An indicative quote, not an admitted generation receipt. */
@@ -9,14 +9,16 @@ export declare function estimateMediaModel(model: MediaModel): {
9
9
  settings: Readonly<{
10
10
  model: string;
11
11
  prompt: string;
12
- width: number;
13
- height: number;
12
+ width?: number;
13
+ height?: number;
14
14
  steps?: number;
15
15
  durationSeconds?: number;
16
+ voiceId?: string;
16
17
  resolution?: import("../model-catalog.js").MediaVideoResolution;
17
18
  aspectRatio?: import("../model-catalog.js").MediaVideoAspectRatio;
18
19
  generateAudio?: boolean;
19
20
  references?: readonly import("../index.js").MediaReference[];
21
+ audioReferences?: readonly import("../index.js").MediaReference[];
20
22
  }>;
21
23
  /** Estimated provider milliunits of a cent for these exact settings. */
22
24
  costMilliunits: number;
@@ -27,7 +29,7 @@ export type MediaAiPort = {
27
29
  run(model: string, input: Parameters<Ai["run"]>[1], options?: AiOptions): Promise<MediaAiResult>;
28
30
  };
29
31
  export declare function estimate(settings: MediaGenerationSettings, references: readonly MediaReferenceBytes[]): number;
30
- export declare function generate(ai: MediaAiPort, settings: MediaGenerationSettings, references: readonly MediaReferenceBytes[], signal?: AbortSignal, options?: AiOptions, fetchResult?: typeof fetch, outputFormat?: "png" | "jpeg" | "webp"): Promise<{
32
+ export declare function generate(ai: MediaAiPort, settings: MediaGenerationSettings, references: readonly MediaReferenceBytes[], signal?: AbortSignal, options?: AiOptions, fetchResult?: typeof fetch, outputFormat?: "png" | "jpeg" | "webp", audioReferences?: readonly MediaAudioReferenceBytes[]): Promise<{
31
33
  bytes: Uint8Array;
32
34
  format: string;
33
35
  }>;
@@ -1,20 +1,23 @@
1
1
  import { z } from "zod";
2
2
  import * as Redacted from "effect/Redacted";
3
- import { buildProviderInput, getMediaModel, estimateImageMilliunits, normalizeMediaProviderOutput, mediaProviderWireSchema, validateMediaGenerationSettings, } from "../index.js";
3
+ import { buildProviderInput, getGatewayModel, estimateImageMilliunits, normalizeMediaProviderOutput, mediaProviderWireSchema, validateMediaGenerationSettings, MediaSettingsError, } from "../index.js";
4
4
  import { MediaExecutionError, MediaSafetyFilterRefusal, } from "../execution-error.js";
5
5
  import { decodeMediaProviderErrorCategory, } from "@fungi.computer/agar/errors";
6
6
  import { estimateGatewayMilliunits, gatewayInput, isGatewayModel, } from "../gateway-models.js";
7
7
  import { GATEWAY_VIDEO_MAX_BYTES, gatewayOutputSchema, isMp4, } from "../gateway-wire.js";
8
8
  import { videoProviderAdapters } from "../video-providers/index.js";
9
+ import { decodeElevenLabsResultUrl, ELEVENLABS_MAX_BYTES, } from "../audio-providers/elevenlabs.js";
9
10
  import { readResponseBytes } from "../index.js";
10
11
  /** Quote the catalog defaults through the exact estimator used before dispatch. */
11
12
  export function estimateMediaModel(model) {
12
- const settings = validateMediaGenerationSettings({
13
- model: model.id,
14
- prompt: "x",
15
- width: model.input.defaultWidth,
16
- height: model.input.defaultHeight,
17
- });
13
+ const settings = validateMediaGenerationSettings(model.kind === "audio"
14
+ ? { model: model.id, prompt: "x" }
15
+ : {
16
+ model: model.id,
17
+ prompt: "x",
18
+ width: model.input.defaultWidth,
19
+ height: model.input.defaultHeight,
20
+ });
18
21
  return {
19
22
  /** An indicative quote, not an admitted generation receipt. */
20
23
  kind: "estimate",
@@ -27,16 +30,18 @@ export function estimateMediaModel(model) {
27
30
  };
28
31
  }
29
32
  export function estimate(settings, references) {
30
- const params = {
31
- width: settings.width,
32
- height: settings.height,
33
- references: references.map(({ width, height }) => ({ width, height })),
34
- };
35
- if (settings.steps !== undefined)
36
- params.steps = settings.steps;
37
33
  try {
38
34
  if (isGatewayModel(settings.model))
39
35
  return estimateGatewayMilliunits(settings, references);
36
+ if (settings.width === undefined || settings.height === undefined)
37
+ throw new MediaSettingsError("image cost needs a width and a height");
38
+ const params = {
39
+ width: settings.width,
40
+ height: settings.height,
41
+ references: references.map(({ width, height }) => ({ width, height })),
42
+ };
43
+ if (settings.steps !== undefined)
44
+ params.steps = settings.steps;
40
45
  return estimateImageMilliunits(settings.model, params);
41
46
  }
42
47
  catch (cause) {
@@ -132,10 +137,10 @@ function providerFailure(model, cause) {
132
137
  : new MediaExecutionError("provider", { cause, provider });
133
138
  }
134
139
  /** Run a gateway model and fetch its result URL within the byte bound. */
135
- async function generateThroughGateway(ai, settings, references, signal, options, fetchResult, outputFormat) {
140
+ async function generateThroughGateway(ai, settings, references, signal, options, fetchResult, outputFormat, audioReferences) {
136
141
  let providerValue;
137
142
  try {
138
- const input = gatewayInput(settings, references, outputFormat);
143
+ const input = gatewayInput(settings, references, outputFormat, audioReferences);
139
144
  providerValue = await ai.run(settings.model, input, routedOptions(options, signal, {
140
145
  stream: false,
141
146
  images: references.length,
@@ -144,9 +149,22 @@ async function generateThroughGateway(ai, settings, references, signal, options,
144
149
  catch (cause) {
145
150
  throw providerFailure(settings.model, cause);
146
151
  }
147
- const model = getMediaModel(settings.model);
152
+ const model = getGatewayModel(settings.model);
148
153
  const video = model?.kind === "video";
149
154
  try {
155
+ if (model?.kind === "audio") {
156
+ const response = await fetchResult(decodeElevenLabsResultUrl(providerValue), { signal: signal ?? null });
157
+ if (!response.ok)
158
+ throw new MediaExecutionError("normalization", {
159
+ provider: { category: "result_download", status: response.status },
160
+ });
161
+ // The result URL is the gateway's own output object; the bytes are
162
+ // retained as fetched, within the size bound.
163
+ return {
164
+ bytes: await readResponseBytes(response, ELEVENLABS_MAX_BYTES),
165
+ format: "mp3",
166
+ };
167
+ }
150
168
  if (video) {
151
169
  if (model.video === null)
152
170
  throw new Error("video model is missing its catalog video metadata");
@@ -163,7 +181,7 @@ async function generateThroughGateway(ai, settings, references, signal, options,
163
181
  }
164
182
  const parsed = gatewayOutputSchema.parse(providerValue);
165
183
  return await normalizeMediaProviderOutput(mediaProviderWireSchema.parse({
166
- images: [{ url: parsed.result.image }],
184
+ images: [{ url: parsed.result.image ?? parsed.result.images?.[0] }],
167
185
  }), { fetchUrl: (url) => fetchResult(url, { signal: signal ?? null }) });
168
186
  }
169
187
  catch (cause) {
@@ -172,9 +190,9 @@ async function generateThroughGateway(ai, settings, references, signal, options,
172
190
  throw new MediaExecutionError("normalization", { cause });
173
191
  }
174
192
  }
175
- export async function generate(ai, settings, references, signal, options, fetchResult = (input, init) => fetch(input, init), outputFormat) {
193
+ export async function generate(ai, settings, references, signal, options, fetchResult = (input, init) => fetch(input, init), outputFormat, audioReferences = []) {
176
194
  if (isGatewayModel(settings.model))
177
- return generateThroughGateway(ai, settings, references, signal, options, fetchResult, outputFormat);
195
+ return generateThroughGateway(ai, settings, references, signal, options, fetchResult, outputFormat, audioReferences);
178
196
  let providerInput;
179
197
  try {
180
198
  providerInput = buildProviderInput(settings, references);
@@ -217,5 +235,5 @@ export async function generate(ai, settings, references, signal, options, fetchR
217
235
  }
218
236
  /** Media's provider port on the Workers AI binding, with fixed options such as the AI Gateway route. */
219
237
  export function createWorkersAiMediaProvider(ai, options) {
220
- return (settings, references, signal, outputFormat) => generate(ai, settings, references, signal, options, undefined, outputFormat);
238
+ return (settings, references, signal, outputFormat, audioReferences) => generate(ai, settings, references, signal, options, undefined, outputFormat, audioReferences);
221
239
  }
@@ -1,4 +1,10 @@
1
1
  import { type ImageViewFitter, type ReferenceImageFitter } from "../index.js";
2
+ /**
3
+ * Cloudflare answers the Images binding with error 9432 ("not available using
4
+ * legacy billing") when the account has not moved to the current billing
5
+ * model. Say what to do, not the raw binding failure.
6
+ */
7
+ export declare const imagesLegacyBillingMessage = "Cloudflare Images is not available on this Cloudflare account because it is on legacy billing (Cloudflare error 9432). Reference images need the Images binding. Update the account's billing in the Cloudflare dashboard, or generate without reference images.";
2
8
  /** Only image metadata and the bounded resize chain are consumed by Media. */
3
9
  export type MediaImagePort = {
4
10
  /** Read decoded image metadata through the Images binding. */
@@ -16,6 +16,19 @@ const formats = {
16
16
  "image/gif": "gif",
17
17
  "image/webp": "webp",
18
18
  };
19
+ /**
20
+ * Cloudflare answers the Images binding with error 9432 ("not available using
21
+ * legacy billing") when the account has not moved to the current billing
22
+ * model. Say what to do, not the raw binding failure.
23
+ */
24
+ export const imagesLegacyBillingMessage = "Cloudflare Images is not available on this Cloudflare account because it is on legacy billing (Cloudflare error 9432). Reference images need the Images binding. Update the account's billing in the Cloudflare dashboard, or generate without reference images.";
25
+ /** The Images binding's `ImagesError` carries Cloudflare's numeric error code. */
26
+ const legacyBillingFailure = z.object({ code: z.literal(9432) });
27
+ function legacyBillingRefusal(cause) {
28
+ return legacyBillingFailure.safeParse(cause).success
29
+ ? new MediaSettingsError(imagesLegacyBillingMessage)
30
+ : undefined;
31
+ }
19
32
  const stream = (bytes) => new ReadableStream({
20
33
  start(controller) {
21
34
  controller.enqueue(bytes.slice());
@@ -34,9 +47,10 @@ export function createImagesReferenceFitter(images) {
34
47
  try {
35
48
  info = metadata.parse(await images.info(stream(bytes)));
36
49
  }
37
- catch {
38
- // The Images failure detail is never surfaced; the caller's bytes are.
39
- throw new MediaSettingsError("reference image is not a supported image");
50
+ catch (cause) {
51
+ // Other Images failure detail is never surfaced; the caller's bytes are.
52
+ throw (legacyBillingRefusal(cause) ??
53
+ new MediaSettingsError("reference image is not a supported image"));
40
54
  }
41
55
  const transform = referenceImageTransform(model, info.width, info.height);
42
56
  const target = referenceImageFormat(model);
@@ -48,7 +62,10 @@ export function createImagesReferenceFitter(images) {
48
62
  .transform(transform)
49
63
  .output(target === "image/webp"
50
64
  ? { format: target, quality: REFERENCE_WEBP_QUALITY }
51
- : { format: target });
65
+ : { format: target })
66
+ .catch((cause) => {
67
+ throw legacyBillingRefusal(cause) ?? cause;
68
+ });
52
69
  bytes = new Uint8Array(await output.response().arrayBuffer());
53
70
  if (bytes.byteLength === 0 || bytes.byteLength > MAX_REFERENCE_BYTES)
54
71
  throw new MediaSettingsError("reference image exceeds the byte limit");
@@ -75,9 +92,10 @@ export function createImagesViewFitter(images) {
75
92
  try {
76
93
  metadata.parse(await images.info(stream(input)));
77
94
  }
78
- catch {
79
- // The Images failure detail is never surfaced.
80
- throw new MediaSettingsError("image is not a supported image");
95
+ catch (cause) {
96
+ // Other Images failure detail is never surfaced.
97
+ throw (legacyBillingRefusal(cause) ??
98
+ new MediaSettingsError("image is not a supported image"));
81
99
  }
82
100
  const output = await images
83
101
  .input(stream(input))
@@ -1,4 +1,4 @@
1
- import { getMediaModel, MAX_REFERENCE_COUNT, MediaSettingsError, } from "./model-catalog.js";
1
+ import { getGatewayModel, MAX_REFERENCE_COUNT, MediaSettingsError, } from "./model-catalog.js";
2
2
  import { neuronsToMilliunits } from "./neurons.js";
3
3
  import * as z from "zod";
4
4
  const TILE = 512;
@@ -29,7 +29,7 @@ const checked = (modelId, params) => {
29
29
  return invalid("dimensions, steps, or references are invalid");
30
30
  const candidate = parsed.data;
31
31
  const references = candidate.references ?? [];
32
- const model = getMediaModel(modelId);
32
+ const model = getGatewayModel(modelId);
33
33
  if (model === undefined)
34
34
  throw new MediaSettingsError(`Image cost unknown for model "${modelId}"`);
35
35
  if (references.length > model.input.maxReferences)
@@ -0,0 +1,55 @@
1
+ import type { MediaMetering } from "./media-operation-contract.js";
2
+ /** The Durable Object storage slice the meter owns tables in. */
3
+ export type DailyMediaMeterStorage = Readonly<{
4
+ /** SQLite access owned by the Durable Object. */
5
+ sql: Readonly<{
6
+ /** Run one statement with positional bindings. */
7
+ exec: (query: string, ...bindings: readonly (string | number)[]) => Readonly<{
8
+ /** Read every returned row. */
9
+ toArray: () => readonly unknown[];
10
+ }>;
11
+ }>;
12
+ /** Run the body in one synchronous transaction. */
13
+ transactionSync: <T>(body: () => T) => T;
14
+ }>;
15
+ /** RPC surface of the Durable Object that owns one Oyster's daily media total. */
16
+ export type DailyMediaMeterPort = Readonly<{
17
+ /** Hold one generation's provider cost against today's limit; false when it would exceed it. */
18
+ dailyAdmit: (input: Readonly<{
19
+ operationId: string;
20
+ costMilliunits: number;
21
+ limitMilliunits: number;
22
+ }>) => Promise<boolean> | boolean;
23
+ /** Release the hold when nothing was delivered, or keep it once delivered. */
24
+ dailySettle: (input: Readonly<{
25
+ operationId: string;
26
+ delivered: boolean;
27
+ }>) => Promise<void> | void;
28
+ }>;
29
+ /**
30
+ * A UTC-day total of admitted media cost, kept in one Durable Object's SQLite.
31
+ * Every statement runs inside one synchronous transaction, so two concurrent
32
+ * admits near the limit are serialized by the object and cannot both pass.
33
+ * Holds are keyed by the durable operation id, so a retried admit never counts
34
+ * twice. A hold that is never settled stays counted until its day ends.
35
+ */
36
+ export declare class DailyMediaMeter {
37
+ private readonly storage;
38
+ private readonly now;
39
+ private ready;
40
+ constructor(storage: DailyMediaMeterStorage, now?: () => number);
41
+ private ensureSchema;
42
+ /** Hold `costMilliunits` for this operation unless the day's total would exceed the limit. */
43
+ admit(input: Readonly<{
44
+ operationId: string;
45
+ costMilliunits: number;
46
+ limitMilliunits: number;
47
+ }>): boolean;
48
+ /** Keep the hold when media was delivered; release it when nothing was. */
49
+ settle(input: Readonly<{
50
+ operationId: string;
51
+ delivered: boolean;
52
+ }>): void;
53
+ }
54
+ /** `MediaMetering` that enforces one exact daily limit through the owning object. */
55
+ export declare function createDailyMediaMetering(meter: DailyMediaMeterPort, limitMilliunits: number): MediaMetering;
@@ -0,0 +1,81 @@
1
+ import * as z from "zod";
2
+ import { MediaBillingRefusal } from "./execution-error.js";
3
+ const totalRowSchema = z.strictObject({ total: z.number() });
4
+ const MS_PER_DAY = 86_400_000;
5
+ /** The UTC day number a timestamp falls in; the total resets when it changes. */
6
+ function utcDay(timestamp) {
7
+ return Math.floor(timestamp / MS_PER_DAY);
8
+ }
9
+ /**
10
+ * A UTC-day total of admitted media cost, kept in one Durable Object's SQLite.
11
+ * Every statement runs inside one synchronous transaction, so two concurrent
12
+ * admits near the limit are serialized by the object and cannot both pass.
13
+ * Holds are keyed by the durable operation id, so a retried admit never counts
14
+ * twice. A hold that is never settled stays counted until its day ends.
15
+ */
16
+ export class DailyMediaMeter {
17
+ storage;
18
+ now;
19
+ ready = false;
20
+ constructor(storage, now = Date.now) {
21
+ this.storage = storage;
22
+ this.now = now;
23
+ }
24
+ ensureSchema() {
25
+ if (this.ready)
26
+ return;
27
+ this.storage.sql.exec("CREATE TABLE IF NOT EXISTS daily_media_hold (operation_id TEXT PRIMARY KEY, day INTEGER NOT NULL, milliunits INTEGER NOT NULL CHECK(milliunits>=0)) STRICT");
28
+ this.ready = true;
29
+ }
30
+ /** Hold `costMilliunits` for this operation unless the day's total would exceed the limit. */
31
+ admit(input) {
32
+ return this.storage.transactionSync(() => {
33
+ this.ensureSchema();
34
+ const day = utcDay(this.now());
35
+ const { sql } = this.storage;
36
+ sql.exec("DELETE FROM daily_media_hold WHERE day < ?", day);
37
+ const held = sql
38
+ .exec("SELECT day FROM daily_media_hold WHERE operation_id = ?", input.operationId)
39
+ .toArray()[0];
40
+ if (held !== undefined)
41
+ return true;
42
+ const { total } = totalRowSchema.parse(sql
43
+ .exec("SELECT COALESCE(SUM(milliunits),0) AS total FROM daily_media_hold WHERE day = ?", day)
44
+ .toArray()[0]);
45
+ if (total + input.costMilliunits > input.limitMilliunits)
46
+ return false;
47
+ sql.exec("INSERT INTO daily_media_hold (operation_id, day, milliunits) VALUES (?, ?, ?)", input.operationId, day, input.costMilliunits);
48
+ return true;
49
+ });
50
+ }
51
+ /** Keep the hold when media was delivered; release it when nothing was. */
52
+ settle(input) {
53
+ if (input.delivered)
54
+ return;
55
+ this.storage.transactionSync(() => {
56
+ this.ensureSchema();
57
+ this.storage.sql.exec("DELETE FROM daily_media_hold WHERE operation_id = ?", input.operationId);
58
+ });
59
+ }
60
+ }
61
+ /** `MediaMetering` that enforces one exact daily limit through the owning object. */
62
+ export function createDailyMediaMetering(meter, limitMilliunits) {
63
+ return {
64
+ admit: async (input) => {
65
+ const admitted = await meter.dailyAdmit({
66
+ operationId: input.operationId,
67
+ costMilliunits: input.providerCostMilliunits,
68
+ limitMilliunits,
69
+ });
70
+ if (!admitted)
71
+ throw new MediaBillingRefusal("daily_limit_reached");
72
+ return { priceMilliunits: input.providerCostMilliunits };
73
+ },
74
+ settle: async (input) => {
75
+ await meter.dailySettle({
76
+ operationId: input.operationId,
77
+ delivered: input.units > 0,
78
+ });
79
+ },
80
+ };
81
+ }
@@ -51,7 +51,7 @@ export declare class MediaSafetyFilterRefusal extends MediaExecutionError {
51
51
  constructor(options?: MediaExecutionErrorOptions);
52
52
  }
53
53
  /** Why the host's billing owner refused to admit a new generation. */
54
- export type MediaBillingRefusalCode = "insufficient_credits" | "denied";
54
+ export type MediaBillingRefusalCode = "insufficient_credits" | "denied" | "daily_limit_reached";
55
55
  /** A definitive billing refusal before dispatch; nothing was generated or charged. */
56
56
  export declare class MediaBillingRefusal extends Error {
57
57
  /** Bounded refusal or failure reason. */
@@ -1,24 +1,29 @@
1
- import { type MediaGenerationSettings, type MediaReferenceBytes } from "./index.js";
2
- import type { MediaVideoModelId } from "./model-catalog.js";
3
- /** Gateway images and the verified catalog's video families share Unified billing. */
4
- export type GatewayModelId = "openai/gpt-image-2" | MediaVideoModelId;
1
+ import { type MediaCatalogue } from "./model-catalog.js";
2
+ import { type MediaAudioReferenceBytes, type MediaGenerationSettings, type MediaReferenceBytes } from "./index.js";
3
+ import type { MediaAudioModelId, MediaVideoModelId } from "./model-catalog.js";
4
+ /** Gateway images and the verified catalog's video and audio families share Unified billing. */
5
+ export type GatewayModelId = "openai/gpt-image-2" | "bytedance/seedream-5-pro" | MediaVideoModelId | MediaAudioModelId;
5
6
  export declare const isGatewayModel: (id: string) => id is GatewayModelId;
6
- /** What one generation bills: whole images, or seconds of video. */
7
+ /**
8
+ * What one generation bills: whole images, seconds of video or music, or
9
+ * blocks of {@link AUDIO_CHARACTER_BLOCK} speech characters (so a per-character
10
+ * provider rate is marked up once per block, not rounded up per character).
11
+ */
7
12
  export type MediaUnits = Readonly<{
8
- /** One image or one whole video second. */
9
- unit: "image" | "video_second";
13
+ /** One image, one whole video or music second, or one speech character block. */
14
+ unit: "image" | "video_second" | "audio_second" | "audio_character_block";
10
15
  /** Number of delivered or admitted units. */
11
16
  units: number;
12
17
  }>;
13
18
  /** Billing units for validated settings; video bills its requested length. */
14
- export declare function mediaUnits(settings: MediaGenerationSettings): MediaUnits;
19
+ export declare function mediaUnits(settings: MediaGenerationSettings, catalogue?: MediaCatalogue): MediaUnits;
15
20
  /** Milliunits (1 cent = 1,000) of provider cost, rounded up. */
16
21
  export declare function estimateGatewayMilliunits(settings: MediaGenerationSettings, references: readonly Readonly<{
17
22
  width: number;
18
23
  height: number;
19
24
  }>[]): number;
20
25
  /** The provider JSON body for one validated gateway generation. */
21
- export declare function gatewayInput(settings: MediaGenerationSettings, references?: readonly MediaReferenceBytes[], outputFormat?: "png" | "jpeg" | "webp"): import("./video-providers/minimax.js").MinimaxGatewayInput | import("./video-providers/unified.js").UnifiedGatewayInput | {
26
+ export declare function gatewayInput(settings: MediaGenerationSettings, references?: readonly MediaReferenceBytes[], outputFormat?: "png" | "jpeg" | "webp", audioReferences?: readonly MediaAudioReferenceBytes[]): import("./audio-providers/elevenlabs.js").ElevenLabsSpeechInput | import("./audio-providers/elevenlabs.js").ElevenLabsMusicInput | import("./video-providers/minimax.js").MinimaxGatewayInput | import("./video-providers/unified.js").UnifiedGatewayInput | {
22
27
  prompt: string;
23
28
  size: string;
24
29
  quality: string;
@@ -29,4 +34,9 @@ export declare function gatewayInput(settings: MediaGenerationSettings, referenc
29
34
  size: string;
30
35
  quality: string;
31
36
  output_format: "png" | "jpeg" | "webp";
37
+ watermark?: never;
38
+ } | {
39
+ prompt: string;
40
+ size: string;
41
+ watermark: boolean;
32
42
  };