@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
@@ -0,0 +1,73 @@
1
+ import * as z from "zod";
2
+ import { mediaFailureStageSchema } from "./execution-error.js";
3
+ import { Option, Schema } from "effect";
4
+ import { reportCatchFailure } from "./failure.js";
5
+ import { mediaProviderDiagnosticWireSchema } from "@fungi.computer/agar/errors";
6
+
7
+ /** Host diagnostic sink; generation errors and retry truth remain transport-owned. */
8
+ export type MediaGenerationDiagnostic = (
9
+ operation:
10
+ "app_media_pending_response_unavailable" | "media_failure_body_read_failed",
11
+ cause: unknown,
12
+ details?: Readonly<{
13
+ /** HTTP response status when the diagnostic concerns a response. */
14
+ status: number;
15
+ }>,
16
+ ) => void;
17
+
18
+ /** Sanitized HTTP refusal emitted by a Media host and decoded at the browser boundary. */
19
+ export const mediaFailureSchema = z.strictObject({
20
+ /** Host-supplied presentation copy. */
21
+ error: z.string().min(1).max(512),
22
+ /** The failed generation or save stage. */
23
+ stage: mediaFailureStageSchema,
24
+ /** Typed refusal reason; the host retains retry truth. */
25
+ code: z.enum({
26
+ /** Host admission or Computer access was denied. */
27
+ CAPABILITY_DENIED: "CAPABILITY_DENIED",
28
+ /** The host's daily media spending limit is used up until 00:00 UTC. */
29
+ DAILY_LIMIT_REACHED: "DAILY_LIMIT_REACHED",
30
+ /** Host billing did not admit this attempt. */
31
+ INSUFFICIENT_CREDIT: "INSUFFICIENT_CREDIT",
32
+ /** The host could not complete generation or saving. */
33
+ HOST_FAILURE: "HOST_FAILURE",
34
+ /** The host refused the selected input. */
35
+ INVALID_ARGUMENT: "INVALID_ARGUMENT",
36
+ /** The inference provider did not complete generation. */
37
+ MEDIA_PROVIDER_FAILURE: "MEDIA_PROVIDER_FAILURE",
38
+ /** The host confirmed zero-unit customer settlement after provider failure. */
39
+ MEDIA_PROVIDER_FAILURE_UNCHARGED: "MEDIA_PROVIDER_FAILURE_UNCHARGED",
40
+ /** The model's safety filter refused generation. */
41
+ SAFETY_FILTER_REFUSED: "SAFETY_FILTER_REFUSED",
42
+ }),
43
+ /** Whether repeating this exact attempt may recover. */
44
+ retryable: z.boolean(),
45
+ /** Allowlisted provider facts only; the original cause never crosses HTTP. */
46
+ provider: mediaProviderDiagnosticWireSchema.optional(),
47
+ });
48
+
49
+ /** Sanitized Media failure carried from the authenticated host to Agar. */
50
+ export type MediaFailure = z.output<typeof mediaFailureSchema>;
51
+
52
+ function parseMediaFailureJson(json: string): MediaFailure | null {
53
+ // Schema-only App consumers must not retain the browser's JSON decoder.
54
+ const decodeJson = Schema.decodeUnknownOption(
55
+ Schema.fromJsonString(Schema.Json),
56
+ );
57
+ const parsed = mediaFailureSchema.safeParse(
58
+ Option.getOrUndefined(decodeJson(json)),
59
+ );
60
+ return parsed.success ? parsed.data : null;
61
+ }
62
+
63
+ /** Read and decode one Media host failure at the browser HTTP boundary. */
64
+ export async function readMediaFailure(
65
+ response: Response,
66
+ diagnostic: MediaGenerationDiagnostic = reportCatchFailure,
67
+ ): Promise<MediaFailure | null> {
68
+ const json = await response.text().catch((cause: unknown) => {
69
+ diagnostic("media_failure_body_read_failed", cause);
70
+ return null;
71
+ });
72
+ return json === null ? null : parseMediaFailureJson(json);
73
+ }
package/src/browser.ts ADDED
@@ -0,0 +1,7 @@
1
+ export { backgroundProviderTimeoutMs } from "./media-run-lifetime.js";
2
+ export { MAX_MEDIA_PROMPT_LENGTH } from "./model-catalog.js";
3
+ export { mediaFailureSchema, readMediaFailure } from "./browser-failure.js";
4
+ export type {
5
+ MediaFailure,
6
+ MediaGenerationDiagnostic,
7
+ } from "./browser-failure.js";
@@ -0,0 +1,89 @@
1
+ import { z } from "zod";
2
+ import {
3
+ type MediaProviderReason,
4
+ mediaProviderDetailMax,
5
+ } from "@fungi.computer/agar/errors";
6
+
7
+ /**
8
+ * Documented numeric codes, by failure class.
9
+ * Workers AI: https://developers.cloudflare.com/workers-ai/platform/errors/
10
+ * AI Gateway: https://developers.cloudflare.com/ai-gateway/reference/troubleshooting/
11
+ * 2021 is also observed (receipts/prints-e2e: "AiGatewayError: 2021: Insufficient
12
+ * AI Gateway credits"). Codes the docs do not state stay unclassified.
13
+ */
14
+ const reasonByCode: ReadonlyMap<number, MediaProviderReason> = new Map([
15
+ // Gateway or provider rejected the request as invalid ("7003: Model execution
16
+ // failed (User Input Error): <REASON>"), or the body/size/base64 was unusable.
17
+ [7003, "invalid_input"],
18
+ [3003, "invalid_input"],
19
+ [3006, "invalid_input"],
20
+ [5004, "invalid_input"],
21
+ // Request rate or Workers AI capacity.
22
+ [2018, "rate_limited"],
23
+ [3040, "rate_limited"],
24
+ // Prepaid gateway balance.
25
+ [2021, "credits_exhausted"],
26
+ [2052, "credits_exhausted"],
27
+ // Daily allocation used up.
28
+ [3036, "spending_limit"],
29
+ // Timeout.
30
+ [3007, "timeout"],
31
+ // Provider or gateway could not answer.
32
+ [7005, "provider_unavailable"],
33
+ [2002, "provider_unavailable"],
34
+ [2005, "provider_unavailable"],
35
+ ]);
36
+
37
+ // "<code>: <rest>", optionally led by the gateway's own "AiGatewayError: ".
38
+ const providerMessage = z
39
+ .string()
40
+ .regex(/^(?:Ai(?:Gateway)?Error: )*\d{4,5}: /u)
41
+ .transform((message) => {
42
+ // The regex above guarantees "<code>: " follows the optional prefixes.
43
+ const body = message.replace(/^(?:Ai(?:Gateway)?Error: )*/u, "");
44
+ const cut = body.indexOf(": ");
45
+ return { code: Number(body.slice(0, cut)), rest: body.slice(cut + 2) };
46
+ });
47
+
48
+ // Never print keys, URLs, ids or structured bodies: plain words only.
49
+ const safeSentence = z
50
+ .string()
51
+ .trim()
52
+ .min(1)
53
+ .max(mediaProviderDetailMax)
54
+ .regex(/^[\p{L}\p{N} .,'’:;()-]+$/u)
55
+ .refine((text) => !/[A-Za-z0-9_-]{20,}/u.test(text))
56
+ .refine(
57
+ (text) => !/key|token|secret|bearer|password|authorization/iu.test(text),
58
+ );
59
+
60
+ /** The reason a provider failure is classified under, from its documented code or wording. */
61
+ export function providerReason(
62
+ name: string | undefined,
63
+ message: string | undefined,
64
+ ): MediaProviderReason | undefined {
65
+ if (name === "TimeoutError") return "timeout";
66
+ const parsed = providerMessage.safeParse(message);
67
+ if (!parsed.success) return undefined;
68
+ const byCode = reasonByCode.get(parsed.data.code);
69
+ return byCode;
70
+ }
71
+
72
+ /**
73
+ * The provider's own short sentence, when it is plain words. For 7003 it is the
74
+ * <REASON> after "Model execution failed (User Input Error): ".
75
+ */
76
+ export function providerDetail(
77
+ message: string | undefined,
78
+ ): string | undefined {
79
+ const parsed = providerMessage.safeParse(message);
80
+ if (!parsed.success) return undefined;
81
+ const reason =
82
+ /^Model execution failed \(User Input Error\): ([\s\S]*)$/u.exec(
83
+ parsed.data.rest,
84
+ );
85
+ const sentence = safeSentence.safeParse(
86
+ (reason?.[1] ?? parsed.data.rest).replace(/^(?:AiError: )+/u, ""),
87
+ );
88
+ return sentence.success ? sentence.data : undefined;
89
+ }
@@ -0,0 +1,405 @@
1
+ import { z } from "zod";
2
+ import * as Redacted from "effect/Redacted";
3
+ import {
4
+ buildProviderInput,
5
+ getGatewayModel,
6
+ estimateImageMilliunits,
7
+ normalizeMediaProviderOutput,
8
+ mediaProviderWireSchema,
9
+ validateMediaGenerationSettings,
10
+ type MediaModel,
11
+ type MediaAiResult,
12
+ type MediaAudioReferenceBytes,
13
+ type MediaGenerationSettings,
14
+ type MediaProvider,
15
+ type MediaReferenceBytes,
16
+ MediaSettingsError,
17
+ } from "../index.js";
18
+ import {
19
+ MediaExecutionError,
20
+ MediaSafetyFilterRefusal,
21
+ } from "../execution-error.js";
22
+ import {
23
+ decodeMediaProviderErrorCategory,
24
+ type MediaProviderDiagnostic,
25
+ } from "@fungi.computer/agar/errors";
26
+ import {
27
+ estimateGatewayMilliunits,
28
+ gatewayInput,
29
+ isGatewayModel,
30
+ } from "../gateway-models.js";
31
+ import {
32
+ GATEWAY_VIDEO_MAX_BYTES,
33
+ gatewayOutputSchema,
34
+ isMp4,
35
+ } from "../gateway-wire.js";
36
+ import { videoProviderAdapters } from "../video-providers/index.js";
37
+ import {
38
+ decodeElevenLabsResultUrl,
39
+ ELEVENLABS_MAX_BYTES,
40
+ } from "../audio-providers/elevenlabs.js";
41
+ import { readResponseBytes } from "../index.js";
42
+ import { providerDetail, providerReason } from "./provider-reason.js";
43
+
44
+ type ImageEstimateParams = {
45
+ width: number;
46
+ height: number;
47
+ steps?: number;
48
+ references?: readonly { width: number; height: number }[];
49
+ };
50
+
51
+ /** Quote the catalog defaults through the exact estimator used before dispatch. */
52
+ export function estimateMediaModel(model: MediaModel) {
53
+ const checked = validateMediaGenerationSettings(
54
+ model.kind === "audio"
55
+ ? { model: model.id, prompt: "x" }
56
+ : model.transform !== null
57
+ ? {
58
+ // A source-image operation is priced by its default output size;
59
+ // the placeholder reference is never read.
60
+ model: model.id,
61
+ prompt: "x",
62
+ references: [{ computerId: "estimate", path: "/estimate" }],
63
+ }
64
+ : {
65
+ model: model.id,
66
+ prompt: "x",
67
+ width: model.input.defaultWidth,
68
+ height: model.input.defaultHeight,
69
+ },
70
+ );
71
+ // The placeholder reference only satisfies validation; the quote names none.
72
+ const { references: placeholder, ...settings } = checked;
73
+ void placeholder;
74
+ return {
75
+ /** An indicative quote, not an admitted generation receipt. */
76
+ kind: "estimate" as const,
77
+ /** Provider cost before the host's billing policy. */
78
+ basis: "provider-cost" as const,
79
+ /** Catalog defaults and a one-character prompt; never references. */
80
+ settings,
81
+ /** Estimated provider milliunits of a cent for these exact settings. */
82
+ costMilliunits: estimate(checked, []),
83
+ };
84
+ }
85
+
86
+ /** Workers AI results vary by model; the provider decodes them at this boundary. */
87
+ export type MediaAiPort = {
88
+ /** Dispatch to the native Workers AI binding. */
89
+ run(
90
+ model: string,
91
+ input: Parameters<Ai["run"]>[1],
92
+ options?: AiOptions,
93
+ ): Promise<MediaAiResult>;
94
+ };
95
+
96
+ export function estimate(
97
+ settings: MediaGenerationSettings,
98
+ references: readonly MediaReferenceBytes[],
99
+ ): number {
100
+ try {
101
+ if (isGatewayModel(settings.model))
102
+ return estimateGatewayMilliunits(settings, references);
103
+ if (settings.width === undefined || settings.height === undefined)
104
+ throw new MediaSettingsError("image cost needs a width and a height");
105
+ const params: ImageEstimateParams = {
106
+ width: settings.width,
107
+ height: settings.height,
108
+ references: references.map(({ width, height }) => ({ width, height })),
109
+ };
110
+ if (settings.steps !== undefined) params.steps = settings.steps;
111
+ return estimateImageMilliunits(settings.model, params);
112
+ } catch (cause) {
113
+ throw new MediaExecutionError("estimate", { cause });
114
+ }
115
+ }
116
+
117
+ // Workers AI prefixes upstream error messages with its numeric internal code.
118
+ // Parse only that bounded identifier; printable prose is separately decoded.
119
+ const providerFailureCode = z.lazy(() =>
120
+ z
121
+ .string()
122
+ .regex(/^\d{4,5}: /u)
123
+ .transform((message) => Number(message.split(":", 1)[0]))
124
+ .nullable()
125
+ .catch(null),
126
+ );
127
+
128
+ // Observed in a real Flux replay: HTTP 400/code 3030. Match the complete
129
+ // bounded refusal, not 3030 itself; the code is not documented as transient.
130
+ const outputFlaggedMessage = z
131
+ .string()
132
+ .regex(
133
+ /^(?:\d{4,5}: )?(?:AiError: ){0,3}Your output has been flagged\. Please choose another prompt \/ input image combination \([0-9a-f-]{36}\)$/u,
134
+ );
135
+
136
+ // Recognize the refusal, not the generic Workers AI error number or prompt text.
137
+ const safetyFilterMessage = z.lazy(() =>
138
+ z.union([
139
+ outputFlaggedMessage,
140
+ z
141
+ .string()
142
+ .regex(/(?:^|:\s)(?:AiError:\s)?Input prompt contains NSFW content\b/iu),
143
+ // Veo's documented input-policy refusal; keep its details private as well.
144
+ // https://docs.cloud.google.com/vertex-ai/generative-ai/docs/video/responsible-ai-and-usage-guidelines
145
+ z.string().regex(/\bit might violate our policies\b/iu),
146
+ ]),
147
+ );
148
+
149
+ /** Encode multipart once with the platform's boundary, as required by AI.run. */
150
+ function workersAiInput(payload: ReturnType<typeof buildProviderInput>) {
151
+ if (payload.transport === "json") return { ...payload.body };
152
+ const encoded = new Response(payload.body);
153
+ return {
154
+ multipart: {
155
+ body: encoded.body,
156
+ contentType: encoded.headers.get("Content-Type"),
157
+ },
158
+ };
159
+ }
160
+
161
+ /**
162
+ * The one AI Gateway routing rule: a call keeps the host's gateway option only
163
+ * when its input is gateway-compatible.
164
+ * - A stream input never is. The binding's documented multipart input is a
165
+ * ReadableStream body
166
+ * (https://developers.cloudflare.com/changelog/2025-11-25-flux-2-dev-workers-ai/),
167
+ * and the gateway route rejects it: "AI Gateway does not support
168
+ * ReadableStreams yet".
169
+ * - An image or frame input never is. AI Gateway documents no request body
170
+ * limit (https://developers.cloudflare.com/ai-gateway/reference/limits/), yet
171
+ * it rejects a first-frame Seedance request (~700 KB data URI) with
172
+ * `7003: User Input Error` that succeeds on the direct binding.
173
+ * Metering stays correct either way: Media meters from its own estimate, not
174
+ * from gateway logs.
175
+ */
176
+ function routedOptions(
177
+ options: AiOptions | undefined,
178
+ signal: AbortSignal | undefined,
179
+ input: Readonly<{ stream: boolean; images: number }>,
180
+ ): AiOptions | undefined {
181
+ const compatible = !input.stream && input.images === 0;
182
+ if (compatible || options === undefined)
183
+ return signal === undefined ? options : { ...options, signal };
184
+ const { gateway, ...direct } = options;
185
+ void gateway;
186
+ return signal === undefined ? direct : { ...direct, signal };
187
+ }
188
+
189
+ /** Retain the original provider failure alongside its bounded code and category. */
190
+ function providerFailure(model: string, cause: unknown): MediaExecutionError {
191
+ const category = decodeMediaProviderErrorCategory(
192
+ cause instanceof Error ? cause.name : undefined,
193
+ );
194
+ const code = providerFailureCode.parse(
195
+ cause instanceof Error ? cause.message : undefined,
196
+ );
197
+ // Observed 2026-10-27 in a real GPT Image 2 call from the Prints UI:
198
+ // "AiGatewayError: 2021: Insufficient AI Gateway credits" (no charge).
199
+ // Sources: ~/Botanical-cto/receipts/prints-e2e/REPORT.md:51 ("Follow-up 2")
200
+ // and ~/Botanical-cto/receipts/prints-e2e/gwfix/results.json (02:01 local;
201
+ // call at 2026-10-27T01:01:04.296Z). The error had only name and message;
202
+ // no HTTP status was recorded. This is observed wording, not a general
203
+ // Cloudflare code guarantee. Keep numeric classification at this owner.
204
+ const message = cause instanceof Error ? cause.message : undefined;
205
+ const safetyRefused =
206
+ cause instanceof Error && safetyFilterMessage.safeParse(message).success;
207
+ const reason = safetyRefused
208
+ ? "content_refused"
209
+ : providerReason(cause instanceof Error ? cause.name : undefined, message);
210
+ // Plain provider sentences help only where the class alone does not explain.
211
+ const detail =
212
+ reason === undefined || reason === "invalid_input"
213
+ ? providerDetail(message)
214
+ : undefined;
215
+ const provider: MediaProviderDiagnostic = {
216
+ category,
217
+ code,
218
+ ...(reason !== undefined && { reason }),
219
+ ...(detail !== undefined && { detail }),
220
+ };
221
+ const safeMessage = outputFlaggedMessage.safeParse(
222
+ cause instanceof Error ? cause.message : undefined,
223
+ );
224
+ // The maintained Workers AI errors expose name/message, not a Response or
225
+ // cause chain. Only the complete, bounded refusal grammar above is safe to
226
+ // print. Unmodeled upstream prose/bodies can echo private request content;
227
+ // retain the original error (including any nested details) only as redacted.
228
+ console.error(
229
+ "Media provider request failed",
230
+ {
231
+ model,
232
+ providerCode: provider.code,
233
+ category: provider.category,
234
+ providerMessage: safeMessage.success ? safeMessage.data : undefined,
235
+ },
236
+ Redacted.make(cause),
237
+ );
238
+ return safetyRefused
239
+ ? new MediaSafetyFilterRefusal({ cause, provider })
240
+ : new MediaExecutionError("provider", { cause, provider });
241
+ }
242
+
243
+ /** Run a gateway model and fetch its result URL within the byte bound. */
244
+ async function generateThroughGateway(
245
+ ai: MediaAiPort,
246
+ settings: MediaGenerationSettings,
247
+ references: readonly MediaReferenceBytes[],
248
+ signal: AbortSignal | undefined,
249
+ options: AiOptions | undefined,
250
+ fetchResult: typeof fetch,
251
+ outputFormat: "png" | "jpeg" | "webp" | undefined,
252
+ audioReferences: readonly MediaAudioReferenceBytes[],
253
+ ): Promise<{ bytes: Uint8Array; format: string }> {
254
+ let providerValue: MediaAiResult;
255
+ try {
256
+ const input = gatewayInput(
257
+ settings,
258
+ references,
259
+ outputFormat,
260
+ audioReferences,
261
+ );
262
+ providerValue = await ai.run(
263
+ settings.model,
264
+ input,
265
+ routedOptions(options, signal, {
266
+ stream: false,
267
+ images: references.length,
268
+ }),
269
+ );
270
+ } catch (cause) {
271
+ throw providerFailure(settings.model, cause);
272
+ }
273
+ const model = getGatewayModel(settings.model);
274
+ const video = model?.kind === "video";
275
+ try {
276
+ if (model?.kind === "audio") {
277
+ const response = await fetchResult(
278
+ decodeElevenLabsResultUrl(providerValue),
279
+ { signal: signal ?? null },
280
+ );
281
+ if (!response.ok)
282
+ throw new MediaExecutionError("normalization", {
283
+ provider: { category: "result_download", status: response.status },
284
+ });
285
+ // The result URL is the gateway's own output object; the bytes are
286
+ // retained as fetched, within the size bound.
287
+ return {
288
+ bytes: await readResponseBytes(response, ELEVENLABS_MAX_BYTES),
289
+ format: "mp3",
290
+ };
291
+ }
292
+ if (video) {
293
+ if (model.video === null)
294
+ throw new Error("video model is missing its catalog video metadata");
295
+ const url =
296
+ videoProviderAdapters[model.video.provider].decodeResultUrl(
297
+ providerValue,
298
+ );
299
+ const response = await fetchResult(url, { signal: signal ?? null });
300
+ if (!response.ok)
301
+ throw new MediaExecutionError("normalization", {
302
+ provider: { category: "result_download", status: response.status },
303
+ });
304
+ const bytes = await readResponseBytes(response, GATEWAY_VIDEO_MAX_BYTES);
305
+ if (!isMp4(bytes)) throw new Error("gateway video is not an MP4");
306
+ return { bytes, format: "mp4" };
307
+ }
308
+ const parsed = gatewayOutputSchema.parse(providerValue);
309
+ return await normalizeMediaProviderOutput(
310
+ mediaProviderWireSchema.parse({
311
+ images: [{ url: parsed.result.image ?? parsed.result.images?.[0] }],
312
+ }),
313
+ { fetchUrl: (url) => fetchResult(url, { signal: signal ?? null }) },
314
+ );
315
+ } catch (cause) {
316
+ if (cause instanceof MediaExecutionError) throw cause;
317
+ throw new MediaExecutionError("normalization", { cause });
318
+ }
319
+ }
320
+
321
+ export async function generate(
322
+ ai: MediaAiPort,
323
+ settings: MediaGenerationSettings,
324
+ references: readonly MediaReferenceBytes[],
325
+ signal?: AbortSignal,
326
+ options?: AiOptions,
327
+ fetchResult: typeof fetch = (input, init) => fetch(input, init),
328
+ outputFormat?: "png" | "jpeg" | "webp",
329
+ audioReferences: readonly MediaAudioReferenceBytes[] = [],
330
+ ): Promise<{ bytes: Uint8Array; format: string }> {
331
+ if (isGatewayModel(settings.model))
332
+ return generateThroughGateway(
333
+ ai,
334
+ settings,
335
+ references,
336
+ signal,
337
+ options,
338
+ fetchResult,
339
+ outputFormat,
340
+ audioReferences,
341
+ );
342
+ let providerInput: ReturnType<typeof buildProviderInput>;
343
+ try {
344
+ providerInput = buildProviderInput(settings, references);
345
+ } catch (cause) {
346
+ throw new MediaExecutionError("normalization", { cause });
347
+ }
348
+ const invoke = async (): Promise<MediaAiResult> => {
349
+ return ai.run(
350
+ settings.model,
351
+ workersAiInput(providerInput),
352
+ routedOptions(options, signal, {
353
+ stream: providerInput.transport === "multipart",
354
+ images: references.length,
355
+ }),
356
+ );
357
+ };
358
+ let providerValue: MediaAiResult;
359
+ try {
360
+ providerValue = await invoke();
361
+ } catch (cause) {
362
+ // Only 3040 is documented as capacity temporarily exceeded:
363
+ // https://developers.cloudflare.com/workers-ai/platform/errors/
364
+ // One product-call retry, never a test retry. Rebuild the multipart body
365
+ // inside invoke: a failed binding call may already have consumed it.
366
+ if (
367
+ providerFailureCode.parse(
368
+ cause instanceof Error ? cause.message : undefined,
369
+ ) !== 3040 ||
370
+ signal?.aborted
371
+ )
372
+ throw providerFailure(settings.model, cause);
373
+ try {
374
+ providerValue = await invoke();
375
+ } catch (cause) {
376
+ // One terminal diagnostic for the product call, not one per attempt.
377
+ throw providerFailure(settings.model, cause);
378
+ }
379
+ }
380
+ try {
381
+ return await normalizeMediaProviderOutput(
382
+ mediaProviderWireSchema.parse(providerValue),
383
+ );
384
+ } catch (cause) {
385
+ throw new MediaExecutionError("normalization", { cause });
386
+ }
387
+ }
388
+
389
+ /** Media's provider port on the Workers AI binding, with fixed options such as the AI Gateway route. */
390
+ export function createWorkersAiMediaProvider(
391
+ ai: MediaAiPort,
392
+ options?: AiOptions,
393
+ ): MediaProvider {
394
+ return (settings, references, signal, outputFormat, audioReferences) =>
395
+ generate(
396
+ ai,
397
+ settings,
398
+ references,
399
+ signal,
400
+ options,
401
+ undefined,
402
+ outputFormat,
403
+ audioReferences,
404
+ );
405
+ }