@fungi.computer/darkroom 0.11.11 → 0.11.13

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 (90) hide show
  1. package/README.md +13 -0
  2. package/examples/standalone/README.md +52 -0
  3. package/examples/standalone/worker.ts +87 -0
  4. package/examples/standalone/wrangler.jsonc +26 -0
  5. package/package.json +8 -2
  6. package/src/app-media-contracts.ts +142 -0
  7. package/src/audio-providers/elevenlabs.ts +108 -0
  8. package/src/audio-reference-types.ts +47 -0
  9. package/src/audio-references.ts +107 -0
  10. package/src/browser-failure.ts +73 -0
  11. package/src/browser.ts +7 -0
  12. package/src/cloudflare/provider-reason.ts +89 -0
  13. package/src/cloudflare/provider.ts +405 -0
  14. package/src/cloudflare/r2-destination.ts +130 -0
  15. package/src/cloudflare/reference-images.ts +193 -0
  16. package/src/cloudflare.ts +38 -0
  17. package/src/cost-estimate.ts +129 -0
  18. package/src/daily-media-meter.ts +163 -0
  19. package/src/effect.ts +2 -0
  20. package/src/execution-error.ts +98 -0
  21. package/src/failure.ts +13 -0
  22. package/src/gateway-models.ts +304 -0
  23. package/src/gateway-wire.ts +36 -0
  24. package/src/index.ts +1454 -0
  25. package/src/media-binding.ts +260 -0
  26. package/src/media-content-type.ts +60 -0
  27. package/src/media-generation.ts +171 -0
  28. package/src/media-operation-contract.ts +173 -0
  29. package/src/media-operation-do.ts +257 -0
  30. package/src/media-operation-owner.ts +1786 -0
  31. package/src/media-operation-storage.ts +110 -0
  32. package/src/media-operation.ts +454 -0
  33. package/src/media-path.ts +8 -0
  34. package/src/media-quote.ts +34 -0
  35. package/src/media-run-lifetime.ts +5 -0
  36. package/src/media-written.ts +38 -0
  37. package/src/model-catalog.ts +1574 -0
  38. package/src/neurons.ts +6 -0
  39. package/src/node-webpmux.d.ts +12 -0
  40. package/src/provenance-bytes.ts +22 -0
  41. package/src/provenance-export.ts +126 -0
  42. package/src/provenance-jpeg.ts +83 -0
  43. package/src/provenance-png.ts +26 -0
  44. package/src/provenance-signed.ts +7 -0
  45. package/src/provenance-xmp.ts +57 -0
  46. package/src/provenance.ts +87 -0
  47. package/src/reference-image-size.ts +67 -0
  48. package/src/reference-read.ts +50 -0
  49. package/src/server.ts +711 -0
  50. package/src/video-providers/index.ts +18 -0
  51. package/src/video-providers/minimax.ts +96 -0
  52. package/src/video-providers/reference-encoding.ts +32 -0
  53. package/src/video-providers/types.ts +47 -0
  54. package/src/video-providers/unified.ts +68 -0
  55. package/test/audio-models.test.ts +428 -0
  56. package/test/audio-references.test.ts +428 -0
  57. package/test/custom-catalogue.test.ts +257 -0
  58. package/test/daily-media-meter.test.ts +287 -0
  59. package/test/failure.test.ts +190 -0
  60. package/test/fixtures/cloudflare-workers.fixture.ts +10 -0
  61. package/test/fixtures/media-operation.fixture.ts +134 -0
  62. package/test/fixtures/media-team-prompts.ts +7 -0
  63. package/test/fixtures/native-sqlite.fixture.ts +40 -0
  64. package/test/gateway-models.test.ts +712 -0
  65. package/test/media-operation-do.test.ts +1565 -0
  66. package/test/media-quote.test.ts +81 -0
  67. package/test/media-retention.test.ts +597 -0
  68. package/test/media-service.test.ts +549 -0
  69. package/test/media-team-prompts.test.ts +92 -0
  70. package/test/model-facts.test.ts +126 -0
  71. package/test/prompt-limit.test.ts +53 -0
  72. package/test/provenance-export.test.ts +144 -0
  73. package/test/provenance-images.fixture.mjs +17 -0
  74. package/test/provenance.test.ts +179 -0
  75. package/test/provider-gateway.test.ts +114 -0
  76. package/test/provider-reasons.test.ts +133 -0
  77. package/test/r2-destination.test.ts +166 -0
  78. package/test/reference-image-size.test.ts +73 -0
  79. package/test/reference-images-billing.test.ts +40 -0
  80. package/test/reference-images.test.ts +399 -0
  81. package/test/standalone.cloudflare.test.mjs +298 -0
  82. package/test/standalone.worker.mjs +70 -0
  83. package/test/transform-models.test.ts +400 -0
  84. package/test/video-capabilities.test.ts +160 -0
  85. package/test/video-contract.test.ts +533 -0
  86. package/test/video-failure-lifecycle.test.ts +177 -0
  87. package/test/video-provider.test.ts +136 -0
  88. package/test/video-wire.test.ts +251 -0
  89. package/vitest.cloudflare.config.ts +22 -0
  90. package/vitest.node.config.ts +14 -0
package/README.md CHANGED
@@ -403,6 +403,19 @@ metadata while preserving the AI marker, print ID and image encoding. It returns
403
403
  bytes, MIME type and filename extension. The public XMP format uses
404
404
  `https://fungi.computer/ns/provenance/1.0/`.
405
405
 
406
+ The installed package includes the runnable `examples/standalone` Worker and
407
+ Darkroom's own tests, with their sources. To check a provider or a change
408
+ against them, install the test tools in your project and run them from the
409
+ package folder:
410
+
411
+ ```sh
412
+ npm install --save-dev vitest@4.1.11 sharp@0.35.4 typescript@5.9.3 \
413
+ @cloudflare/vitest-plugin@1.1.2 wrangler@4.159.0
414
+ cd node_modules/@fungi.computer/darkroom
415
+ npx vitest run --config vitest.node.config.ts
416
+ npx vitest run --config vitest.cloudflare.config.ts
417
+ ```
418
+
406
419
  ## Use your own R2 bucket
407
420
 
408
421
  Keep reference images and generated output in a bucket you already own.
@@ -0,0 +1,52 @@
1
+ # Standalone Media backend
2
+
3
+ This example runs the shared Media Hono service inside a Durable Object. The
4
+ forwarding Worker checks a bearer token. The host supplies one R2 bucket through
5
+ `createR2MediaDestination`: reference images are read from it and outputs are
6
+ saved to it. Each generation uses the same native operation DO and
7
+ retained-output code as Fungi. No Hub, Team, Computer, or browser UI is
8
+ required.
9
+
10
+ From the repository root:
11
+
12
+ ```sh
13
+ pnpm --filter @fungi.computer/darkroom build
14
+ pnpm --filter @fungi.computer/darkroom exec wrangler deploy --dry-run --config examples/standalone/wrangler.jsonc
15
+ ```
16
+
17
+ For local serving, create `examples/standalone/.dev.vars` inside this package
18
+ with `MEDIA_TOKEN="your-local-token"`, then run:
19
+
20
+ ```sh
21
+ pnpm --filter @fungi.computer/darkroom exec wrangler dev --config examples/standalone/wrangler.jsonc
22
+ ```
23
+
24
+ The AI binding needs Cloudflare provider access for actual inference. The native
25
+ test injects image bytes and does not call a live provider. Local native SQL/R2
26
+ proof does not establish hosted AI availability. No deployment or bucket
27
+ provisioning is performed by the dry-run command.
28
+
29
+ Use the bearer token on every request:
30
+
31
+ - `GET /models` lists supported models. References are read from the `OUTPUTS`
32
+ bucket: put an image at a key, then send
33
+ `"references":[{"computerId":"outputs","path":"<key>"}]` in the settings of a
34
+ model that takes references. `computerId` must equal the host's destination id
35
+ (`outputs`); any other value is refused before the provider is called.
36
+ - `POST /generate` accepts `X-Request-Id` and JSON such as
37
+ `{"path":"greenhouse.png","settings":{"model":"@cf/black-forest-labs/flux-1-schnell","prompt":"a greenhouse","width":1024,"height":768,"steps":4}}`.
38
+ - `GET /object?key=greenhouse.png` reads the saved bytes.
39
+
40
+ `path` is an R2 object key. There are no directories to create. The actual image
41
+ format is returned by generation; the service does not choose a filename suffix.
42
+ For a failed save, resend the same request ID and identical JSON. A retained
43
+ output is saved again without another provider call. An unresolved provider call
44
+ is not automatically rerun. Use a new request ID for a different generation.
45
+
46
+ `MEDIA_HOST` is the HTTP host DO; `MEDIA_OPERATION` is the per-request native
47
+ operation namespace. `APP_ARTIFACTS` holds retained image bytes, `OUTPUTS` holds
48
+ reference images and saved objects, `AI` is the Workers AI binding, and `IMAGES`
49
+ is the Images binding that fits references to the selected model. `MEDIA_TOKEN`
50
+ is a required secret. The example is a single application with one bearer
51
+ identity; adopting it for multiple users requires the host to admit their scope
52
+ explicitly.
@@ -0,0 +1,87 @@
1
+ import { DurableObject } from "cloudflare:workers";
2
+ import { Hono, type MiddlewareHandler } from "hono";
3
+ import { bearerAuth } from "hono/bearer-auth";
4
+ import {
5
+ createMediaService,
6
+ mediaRequestSchema,
7
+ } from "@fungi.computer/darkroom/server";
8
+ import {
9
+ createImagesReferenceFitter,
10
+ createR2MediaDestination,
11
+ createWorkersAiMediaProvider,
12
+ MediaOperationDO,
13
+ type MediaImagePort,
14
+ } from "@fungi.computer/darkroom/cloudflare";
15
+
16
+ export { MediaOperationDO };
17
+
18
+ export type StandaloneMediaEnv = {
19
+ MEDIA_TOKEN: string;
20
+ MEDIA_HOST: DurableObjectNamespace<StandaloneMedia>;
21
+ MEDIA_OPERATION: DurableObjectNamespace<MediaOperationDO>;
22
+ APP_ARTIFACTS: R2Bucket;
23
+ OUTPUTS: R2Bucket;
24
+ AI: Ai;
25
+ IMAGES: MediaImagePort;
26
+ };
27
+
28
+ /** One authenticated application; each request ID retains its own operation DO. */
29
+ export class StandaloneMedia extends DurableObject<StandaloneMediaEnv> {
30
+ override fetch(request: Request): Promise<Response> {
31
+ const app = createMediaService({
32
+ scope: {
33
+ actorId: "api-token",
34
+ namespace: "standalone",
35
+ owner: "media",
36
+ destinationId: "outputs",
37
+ },
38
+ operations: this.env.MEDIA_OPERATION,
39
+ provider: createWorkersAiMediaProvider(this.env.AI),
40
+ // This single-tenant host pays its own Workers AI account; nothing to bill.
41
+ metering: "unmetered",
42
+ // Reference images are read from, and outputs written to, the OUTPUTS bucket.
43
+ // Pass `authorize(key)` to apply your own permission check to every key.
44
+ destination: createR2MediaDestination({
45
+ bucket: this.env.OUTPUTS,
46
+ destinationId: "outputs",
47
+ fit: createImagesReferenceFitter(this.env.IMAGES),
48
+ }),
49
+ });
50
+ app.get("/object", async (context) => {
51
+ const key = mediaRequestSchema.shape.path.safeParse(
52
+ context.req.query("key"),
53
+ );
54
+ if (!key.success)
55
+ return context.json({ error: "Invalid object key" }, 400);
56
+ const object = await this.env.OUTPUTS.get(key.data);
57
+ if (object === null) return context.notFound();
58
+ return new Response(object.body, {
59
+ headers: {
60
+ "Content-Type": "application/octet-stream",
61
+ "Cache-Control": "private, no-store",
62
+ "X-Content-Type-Options": "nosniff",
63
+ },
64
+ });
65
+ });
66
+ return Promise.resolve(app.fetch(request));
67
+ }
68
+ }
69
+
70
+ const app = new Hono<{ Bindings: StandaloneMediaEnv }>();
71
+ const authenticate: MiddlewareHandler<{
72
+ Bindings: StandaloneMediaEnv;
73
+ }> = async (context, next) => {
74
+ if (!context.env.MEDIA_TOKEN)
75
+ return context.json(
76
+ { error: "Configure MEDIA_TOKEN before using this host" },
77
+ 503,
78
+ );
79
+ return bearerAuth<{ Bindings: StandaloneMediaEnv }>({
80
+ token: context.env.MEDIA_TOKEN,
81
+ })(context, next);
82
+ };
83
+ app.use("*", authenticate);
84
+ app.all("*", (context) =>
85
+ context.env.MEDIA_HOST.getByName("media").fetch(context.req.raw),
86
+ );
87
+ export default app;
@@ -0,0 +1,26 @@
1
+ {
2
+ "name": "standalone-media-example",
3
+ "main": "worker.ts",
4
+ "compatibility_date": "2026-09-02",
5
+ // music-metadata (reference audio) reads Node built-ins through debug.
6
+ "compatibility_flags": ["nodejs_compat"],
7
+ "durable_objects": {
8
+ "bindings": [
9
+ { "name": "MEDIA_HOST", "class_name": "StandaloneMedia" },
10
+ { "name": "MEDIA_OPERATION", "class_name": "MediaOperationDO" },
11
+ ],
12
+ },
13
+ "migrations": [
14
+ {
15
+ "tag": "v1",
16
+ "new_sqlite_classes": ["StandaloneMedia", "MediaOperationDO"],
17
+ },
18
+ ],
19
+ "r2_buckets": [
20
+ { "binding": "APP_ARTIFACTS", "bucket_name": "standalone-media-retained" },
21
+ { "binding": "OUTPUTS", "bucket_name": "standalone-media-output" },
22
+ ],
23
+ "ai": { "binding": "AI" },
24
+ // Fits reference images read from the OUTPUTS bucket.
25
+ "images": { "binding": "IMAGES" },
26
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fungi.computer/darkroom",
3
- "version": "0.11.11",
3
+ "version": "0.11.13",
4
4
  "author": "Levi <levi@technomancy.dev>",
5
5
  "description": "Media generation, durable output retention and provenance with host-owned authority and billing",
6
6
  "type": "module",
@@ -44,6 +44,12 @@
44
44
  "files": [
45
45
  "dist",
46
46
  "docs/api",
47
+ "src",
48
+ "test",
49
+ "!test/stranger",
50
+ "examples",
51
+ "vitest.node.config.ts",
52
+ "vitest.cloudflare.config.ts",
47
53
  "README.md",
48
54
  "LICENSE"
49
55
  ],
@@ -60,7 +66,7 @@
60
66
  "exifreader": "4.46.0",
61
67
  "@fungi.computer/ts-webp": "0.1.6",
62
68
  "@xmldom/xmldom": "0.9.12",
63
- "@fungi.computer/agar": "0.24.0",
69
+ "@fungi.computer/agar": "0.25.0",
64
70
  "@fungi.computer/capnweb": "0.12.0-fungi.0"
65
71
  },
66
72
  "devDependencies": {
@@ -0,0 +1,142 @@
1
+ import * as z from "zod";
2
+ import { listMediaModels, mediaModelSchema } from "./model-catalog.js";
3
+ import { mediaResultSchema } from "./media-operation-contract.js";
4
+ import { pendingSchema } from "@fungi.computer/agar/backend-definition";
5
+ import { mediaFailureSchema } from "./browser-failure.js";
6
+ import { mediaGenerationSettingsSchema } from "./index.js";
7
+
8
+ /** A labelled estimate for one explicitly described generation, never a receipt. */
9
+ export const mediaModelPriceEstimateSchema = z.strictObject({
10
+ /** Quotes are indicative; the admitted generation owns its charge. */
11
+ kind: z.literal("estimate"),
12
+ /** Unmetered hosts pay provider cost; funded hosts apply their billing policy. */
13
+ basis: z.enum({
14
+ /** Provider cost before the host's billing policy. */
15
+ "provider-cost": "provider-cost",
16
+ /** Team charge estimate after the host's billing policy. */
17
+ "team-price": "team-price",
18
+ }),
19
+ /** Milliunits of a cent, at the quoted settings. */
20
+ costMilliunits: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),
21
+ /** Defaults, a one-character prompt and no references; varying these changes cost. */
22
+ settings: mediaGenerationSettingsSchema,
23
+ });
24
+ /** Host catalog projection; provider metadata remains owned by the sole catalog. */
25
+ export const mediaCatalogModelSchema = mediaModelSchema
26
+ .unwrap()
27
+ .extend({
28
+ /** Optional host estimate with explicit assumptions and funding basis. */
29
+ priceEstimate: mediaModelPriceEstimateSchema.optional(),
30
+ })
31
+ .readonly();
32
+
33
+ /** Bounded catalog decoded by the App media broker before host filtering. */
34
+ export const mediaModelsSchema = z.lazy(() =>
35
+ z.array(mediaCatalogModelSchema).max(listMediaModels().length),
36
+ );
37
+
38
+ /** An absolute output path on the Computer admitted by the App host. */
39
+ export const destinationSchema = z.strictObject({
40
+ /** Computer admitted by the host. */
41
+ computerId: z.string().min(1).max(256),
42
+ /** Absolute Computer output path. */
43
+ path: z.string().startsWith("/").max(1_024),
44
+ });
45
+
46
+ /** Completed App generation output, with its admitted Computer destination. */
47
+ export const appMediaGenerationResultSchema = mediaResultSchema
48
+ .omit({ path: true })
49
+ .extend({
50
+ /** Admitted Computer and absolute output path. */
51
+ destination: destinationSchema,
52
+ });
53
+
54
+ /** Authority refusals emitted by Media admission before a host call. */
55
+ export const appMediaAdmissionErrorSchema = z.strictObject({
56
+ /** Existing admission refusal code. */
57
+ error: z.enum({
58
+ /** The captured App selection or attachment changed. */
59
+ revoked: "revoked",
60
+ /** The caller does not hold this Media grant. */
61
+ not_granted: "not_granted",
62
+ /** The attachment's grantor no longer holds authority. */
63
+ grantor_lost_authority: "grantor_lost_authority",
64
+ /** Admission could not resolve the current resource. */
65
+ unavailable: "unavailable",
66
+ }),
67
+ });
68
+
69
+ /** Attachment budget refusal emitted by the Media reservation owner. */
70
+ export const appMediaBudgetRefusalSchema = z.lazy(() =>
71
+ z.strictObject({
72
+ /** The attachment's operation budget refused this request. */
73
+ error: z.literal("attachment_budget_exceeded"),
74
+ /** Media reservations use the Media budget, not exec or write. */
75
+ kind: z.literal("media"),
76
+ /** Delay emitted by the reservation owner. */
77
+ retryAfterMs: z.number(),
78
+ }),
79
+ );
80
+
81
+ /** Existing Media admission refusals, without an admitted selector or callable. */
82
+ export const appMediaAdmissionRefusalSchema = z.union([
83
+ appMediaAdmissionErrorSchema,
84
+ appMediaBudgetRefusalSchema,
85
+ ]);
86
+
87
+ /** Admission errors plus invalid/oversized inputs emitted directly by the broker. */
88
+ export const appMediaBrokerErrorSchema = appMediaAdmissionErrorSchema.extend({
89
+ /** Existing broker refusal code. */
90
+ error: z.enum({
91
+ ...appMediaAdmissionErrorSchema.shape.error.enum,
92
+ /** The broker refused the input representation or selection. */
93
+ invalid: "invalid",
94
+ /** The input exceeds the existing broker byte ceiling. */
95
+ too_large: "too_large",
96
+ }),
97
+ });
98
+
99
+ /** Missing-library refusal decoded and returned by the App media broker. */
100
+ export const agentAppMediaLibraryFailureSchema = z.lazy(() =>
101
+ z.strictObject({
102
+ /** The calling Installation's library is unavailable. */
103
+ error: z.literal("library_unavailable"),
104
+ /** Existing library-owner presentation copy. */
105
+ message: z.string().max(4096),
106
+ }),
107
+ );
108
+
109
+ /** Broker projection of an HTTP failure: code becomes error and error becomes message. */
110
+ export const appMediaBrokerFailureSchema = z.strictObject({
111
+ /** Original typed HTTP failure code. */
112
+ error: mediaFailureSchema.shape.code,
113
+ /** Original HTTP failure presentation copy. */
114
+ message: mediaFailureSchema.shape.error,
115
+ /** Original failure stage. */
116
+ stage: mediaFailureSchema.shape.stage,
117
+ /** Original retry truth. */
118
+ retryable: mediaFailureSchema.shape.retryable,
119
+ /** Original bounded provider facts, when available. */
120
+ provider: mediaFailureSchema.shape.provider,
121
+ });
122
+
123
+ /** Refusal payloads emitted by the App media broker, separate from transport errors. */
124
+ export const appMediaRefusalSchema = z.union([
125
+ appMediaBrokerErrorSchema,
126
+ appMediaBudgetRefusalSchema,
127
+ agentAppMediaLibraryFailureSchema,
128
+ appMediaBrokerFailureSchema,
129
+ ]);
130
+
131
+ /** Model-list payload or an existing broker refusal. */
132
+ export const appMediaModelsOutcomeSchema = z.union([
133
+ mediaModelsSchema,
134
+ appMediaRefusalSchema,
135
+ ]);
136
+
137
+ /** Completed generation, Agar polling result, or an existing broker refusal. */
138
+ export const appMediaGenerationOutcomeSchema = z.union([
139
+ appMediaGenerationResultSchema,
140
+ pendingSchema,
141
+ appMediaRefusalSchema,
142
+ ]);
@@ -0,0 +1,108 @@
1
+ import { z } from "zod";
2
+ import {
3
+ MediaSettingsError,
4
+ type MediaAudioModel,
5
+ type MediaModel,
6
+ } from "../model-catalog.js";
7
+ import type { MediaAiResult, MediaGenerationSettings } from "../index.js";
8
+ import { resultUrl } from "../gateway-wire.js";
9
+
10
+ /**
11
+ * ElevenLabs on Cloudflare's Unified Billing. Every shape below is the model
12
+ * page's own `schema-input.json` / `schema-output.json`, checked 2026-11-13:
13
+ * https://developers.cloudflare.com/ai/models/elevenlabs/eleven-v3/
14
+ * https://developers.cloudflare.com/ai/models/elevenlabs/eleven-multilingual-v2/
15
+ * https://developers.cloudflare.com/ai/models/elevenlabs/music-v2/
16
+ */
17
+
18
+ /**
19
+ * `mp3_44100_128` is in the `output_format` enum of every ElevenLabs model
20
+ * page above. It is requested explicitly so the saved file is always an MP3.
21
+ */
22
+ const ELEVENLABS_OUTPUT_FORMAT = "mp3_44100_128";
23
+
24
+ /** A text-to-speech request: `text` (1-10,000 characters) and a required `voice_id`. */
25
+ export type ElevenLabsSpeechInput = {
26
+ text: string;
27
+ voice_id: string;
28
+ output_format: typeof ELEVENLABS_OUTPUT_FORMAT;
29
+ };
30
+ /** A music request: a `prompt` and `music_length_ms` of 3,000 through 600,000. */
31
+ export type ElevenLabsMusicInput = {
32
+ prompt: string;
33
+ music_length_ms: number;
34
+ output_format: typeof ELEVENLABS_OUTPUT_FORMAT;
35
+ };
36
+ /** Every ElevenLabs request body this catalog can produce. */
37
+ export type ElevenLabsInput = ElevenLabsSpeechInput | ElevenLabsMusicInput;
38
+
39
+ /**
40
+ * The one shape a live Unified Billing call returned for Multilingual v2, v3
41
+ * and Music v2 (2026-11-13, REST envelope `{result: ...}` removed by the
42
+ * binding): `{state: "Completed", result: {audio: <HTTPS URL>}}`, the same
43
+ * wrapper Seedance and Veo use. The audio is a URL to fetch, not bytes. The
44
+ * model pages' bare `{audio}` schema-output is not what the gateway answers
45
+ * and is refused.
46
+ */
47
+ const elevenLabsOutputSchema = z.lazy(() =>
48
+ z.looseObject({
49
+ state: z.literal("Completed"),
50
+ result: z.looseObject({ audio: resultUrl }),
51
+ }),
52
+ );
53
+
54
+ /** Results are fetched whole; 600 seconds of 128 kbps MP3 is about 10 MB. */
55
+ export const ELEVENLABS_MAX_BYTES = 32 * 1024 * 1024;
56
+
57
+ function audioOf(model: MediaModel): MediaAudioModel {
58
+ if (model.audio === null)
59
+ throw new MediaSettingsError(`${model.id} is not an audio model`);
60
+ return model.audio;
61
+ }
62
+
63
+ /** The exact provider JSON body for one validated speech or music generation. */
64
+ export function buildElevenLabsInput(
65
+ settings: MediaGenerationSettings,
66
+ model: MediaModel,
67
+ ): ElevenLabsInput {
68
+ const audio = audioOf(model);
69
+ if (audio.mode === "speech") {
70
+ if (settings.voiceId === undefined)
71
+ throw new MediaSettingsError(`${model.id} needs a voice`);
72
+ return {
73
+ text: settings.prompt,
74
+ voice_id: settings.voiceId,
75
+ output_format: ELEVENLABS_OUTPUT_FORMAT,
76
+ };
77
+ }
78
+ if (settings.durationSeconds === undefined)
79
+ throw new MediaSettingsError(`${model.id} needs a length`);
80
+ return {
81
+ prompt: settings.prompt,
82
+ music_length_ms: settings.durationSeconds * 1_000,
83
+ output_format: ELEVENLABS_OUTPUT_FORMAT,
84
+ };
85
+ }
86
+
87
+ /** Extract and validate the HTTPS result URL from the raw provider answer. */
88
+ export function decodeElevenLabsResultUrl(
89
+ providerValue: MediaAiResult,
90
+ ): string {
91
+ return elevenLabsOutputSchema.parse(providerValue).result.audio;
92
+ }
93
+
94
+ /**
95
+ * Provider cost in milliunits: speech is per character of text, music per
96
+ * second of output length asked for (1 USD = 100,000 milliunits).
97
+ */
98
+ export function estimateElevenLabsMilliunits(
99
+ settings: MediaGenerationSettings,
100
+ model: MediaModel,
101
+ ): number {
102
+ const audio = audioOf(model);
103
+ const quantity =
104
+ audio.mode === "speech" ? settings.prompt.length : settings.durationSeconds;
105
+ if (quantity === undefined)
106
+ throw new MediaSettingsError(`${model.id} needs a length`);
107
+ return quantity * audio.milliunitsPerUnit;
108
+ }
@@ -0,0 +1,47 @@
1
+ import { MediaSettingsError, type MediaVideoModel } from "./model-catalog.js";
2
+
3
+ /** Decoded bytes of one reference clip: well past 30 seconds of any admitted container. */
4
+ export const MAX_AUDIO_REFERENCE_BYTES = 16 * 1024 * 1024;
5
+ /** Decoded bytes across every clip of one request; base64 adds a third. */
6
+ export const MAX_AUDIO_REFERENCE_BODY_BYTES = 24 * 1024 * 1024;
7
+
8
+ /** One reference clip with the facts the provider request and the 30-second budget need. */
9
+ export type MediaAudioReferenceBytes = Readonly<{
10
+ /** Exact clip bytes as the Computer holds them. */
11
+ bytes: Uint8Array;
12
+ /** Media type of the clip's container, from its parsed header. */
13
+ mimeType: AudioReferenceMimeType;
14
+ /** Whole-clip duration in seconds, from the parsed header or decoded stream. */
15
+ durationSeconds: number;
16
+ /** Optional filename for diagnostics. */
17
+ filename?: string;
18
+ }>;
19
+
20
+ /**
21
+ * Containers a clip may arrive in: `mp3`, `m4a`, `wav`, `ogg` and `opus`
22
+ * files. Seedance 2.5 states only that clips are "base64 data:audio/... URIs"
23
+ * and does not list formats, so Darkroom admits what the gallery plays.
24
+ * https://developers.cloudflare.com/ai/models/bytedance/seedance-2.5/schema-input.json
25
+ */
26
+ export type AudioReferenceMimeType =
27
+ "audio/mpeg" | "audio/mp4" | "audio/wav" | "audio/ogg";
28
+
29
+ /**
30
+ * Enforce the model's declared clip count and total duration. Neither is
31
+ * clamped: a clip over budget refuses the request instead of being dropped.
32
+ */
33
+ export function checkAudioReferenceBudget(
34
+ label: string,
35
+ limits: NonNullable<MediaVideoModel["audioReferences"]>,
36
+ clips: readonly Pick<MediaAudioReferenceBytes, "durationSeconds">[],
37
+ ): void {
38
+ if (clips.length > limits.max)
39
+ throw new MediaSettingsError(
40
+ `${label} takes up to ${String(limits.max)} audio references`,
41
+ );
42
+ const total = clips.reduce((sum, clip) => sum + clip.durationSeconds, 0);
43
+ if (total > limits.totalSeconds)
44
+ throw new MediaSettingsError(
45
+ `${label} audio references total ${total.toFixed(1)} seconds; the limit is ${String(limits.totalSeconds)}`,
46
+ );
47
+ }
@@ -0,0 +1,107 @@
1
+ import { parseBuffer } from "music-metadata";
2
+ import {
3
+ getMediaModel,
4
+ MediaSettingsError,
5
+ mediaModels,
6
+ type MediaCatalogue,
7
+ } from "./model-catalog.js";
8
+ import type { MediaGenerationSettings, MediaReference } from "./index.js";
9
+ import {
10
+ MAX_AUDIO_REFERENCE_BODY_BYTES,
11
+ MAX_AUDIO_REFERENCE_BYTES,
12
+ checkAudioReferenceBudget,
13
+ type AudioReferenceMimeType,
14
+ type MediaAudioReferenceBytes,
15
+ } from "./audio-reference-types.js";
16
+
17
+ /** music-metadata's container names, matched case-insensitively. */
18
+ function mimeTypeOf(container: string | undefined): AudioReferenceMimeType {
19
+ const name = (container ?? "").toLowerCase();
20
+ if (name === "mpeg") return "audio/mpeg";
21
+ if (name === "wave") return "audio/wav";
22
+ if (name === "ogg") return "audio/ogg";
23
+ if (name === "m4a" || name === "mp4" || name.startsWith("iso"))
24
+ return "audio/mp4";
25
+ throw new MediaSettingsError(
26
+ "audio reference is not an mp3, m4a, wav, ogg or opus file",
27
+ );
28
+ }
29
+
30
+ /**
31
+ * Read one clip's duration and container with music-metadata, the maintained
32
+ * parser. `duration: true` makes it scan a stream whose header has no length.
33
+ */
34
+ async function readAudioReference(
35
+ bytes: Uint8Array,
36
+ filename?: string,
37
+ ): Promise<MediaAudioReferenceBytes> {
38
+ if (bytes.byteLength === 0 || bytes.byteLength > MAX_AUDIO_REFERENCE_BYTES)
39
+ throw new MediaSettingsError(
40
+ "audio reference is unavailable or exceeds the byte limit",
41
+ );
42
+ let metadata: Awaited<ReturnType<typeof parseBuffer>>;
43
+ try {
44
+ metadata = await parseBuffer(bytes, undefined, { duration: true });
45
+ } catch (cause) {
46
+ throw new MediaSettingsError("audio reference could not be read as audio", {
47
+ cause,
48
+ });
49
+ }
50
+ const durationSeconds = metadata.format.duration;
51
+ if (
52
+ durationSeconds === undefined ||
53
+ !Number.isFinite(durationSeconds) ||
54
+ durationSeconds <= 0
55
+ )
56
+ throw new MediaSettingsError("audio reference has no readable duration");
57
+ const clip = {
58
+ bytes,
59
+ mimeType: mimeTypeOf(metadata.format.container),
60
+ durationSeconds,
61
+ };
62
+ return Object.freeze(filename === undefined ? clip : { ...clip, filename });
63
+ }
64
+
65
+ /** Host-authorized reader for the raw bytes of reference audio clips. */
66
+ export type MediaAudioReferenceReader = Readonly<{
67
+ /** Authorize and read one clip; Darkroom parses it, the host never does. */
68
+ read: (reference: MediaReference) => Promise<Uint8Array>;
69
+ }>;
70
+
71
+ /**
72
+ * Read every reference clip through the caller's reader and parse each with
73
+ * music-metadata. The model's declared clip count and total duration are
74
+ * enforced here, before billing admission; nothing is clamped or dropped.
75
+ */
76
+ export const resolveMediaAudioReferences = async (
77
+ settings: MediaGenerationSettings,
78
+ reader: MediaAudioReferenceReader,
79
+ catalogue: MediaCatalogue = mediaModels,
80
+ ): Promise<readonly MediaAudioReferenceBytes[]> => {
81
+ const references = settings.audioReferences ?? [];
82
+ if (references.length === 0) return Object.freeze([]);
83
+ const model = getMediaModel(settings.model, catalogue);
84
+ const limits = model?.video?.audioReferences ?? null;
85
+ if (model === undefined || limits === null)
86
+ throw new MediaSettingsError(
87
+ `${model?.label ?? settings.model} does not take audio references`,
88
+ );
89
+ const resolved: MediaAudioReferenceBytes[] = [];
90
+ let totalBytes = 0;
91
+ for (const reference of references) {
92
+ const bytes = await reader.read(reference);
93
+ totalBytes += bytes.byteLength;
94
+ if (totalBytes > MAX_AUDIO_REFERENCE_BODY_BYTES)
95
+ throw new MediaSettingsError(
96
+ "audio references exceed the total request size limit",
97
+ );
98
+ resolved.push(
99
+ await readAudioReference(
100
+ bytes,
101
+ reference.path.split("/").at(-1) ?? "reference",
102
+ ),
103
+ );
104
+ }
105
+ checkAudioReferenceBudget(model.label, limits, resolved);
106
+ return Object.freeze(resolved);
107
+ };