@fungi.computer/darkroom 0.11.10 → 0.11.12

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/src/server.ts ADDED
@@ -0,0 +1,711 @@
1
+ import { DailyMediaMeterError } from "./daily-media-meter.js";
2
+ import { mediaPendingSchema } from "./media-binding.js";
3
+ export { estimateMediaModel } from "./cloudflare/provider.js";
4
+ export {
5
+ mediaPendingSchema,
6
+ mediaBindingCallSchema,
7
+ mediaBindingGenerationSchema,
8
+ mediaImageBindingInputSchema,
9
+ mediaVideoBindingInputSchema,
10
+ parseMediaBindingCall,
11
+ mediaBindingRequest,
12
+ readMediaBindingReply,
13
+ type MediaBindingCall,
14
+ type MediaBindingGeneration,
15
+ type MediaBindingRequest,
16
+ } from "./media-binding.js";
17
+ import { Hono } from "hono";
18
+ import { withBillingUnit } from "./model-catalog.js";
19
+ import { z } from "zod";
20
+ import { AppError, describeAppError } from "@fungi.computer/agar/errors";
21
+ import * as Effect from "effect/Effect";
22
+ import * as Result from "effect/Result";
23
+ import { mediaPathSchema } from "./media-path.js";
24
+ import type {
25
+ MediaErasure,
26
+ MediaRetained,
27
+ MediaRetainedBytes,
28
+ } from "./media-operation-owner.js";
29
+ export type { MediaErasure, MediaRetained, MediaRetainedBytes };
30
+ export {
31
+ mediaWrittenDigest,
32
+ removeMediaIfWritten,
33
+ type MediaRemoval,
34
+ } from "./media-written.js";
35
+ import type { MediaRemoval } from "./media-written.js";
36
+ import { runMediaGeneration } from "./media-generation.js";
37
+ import { quoteMediaGeneration } from "./media-quote.js";
38
+ import {
39
+ validateMediaGenerationSettings,
40
+ listMediaModels,
41
+ mediaGenerationSettingsSchema,
42
+ mediaRequestedImageFormatSchema,
43
+ MediaSettingsError,
44
+ type MediaCatalogue,
45
+ type MediaProvider,
46
+ type MediaReference,
47
+ type MediaReferenceBytes,
48
+ } from "./index.js";
49
+ import {
50
+ mediaResultSchema,
51
+ type MediaExecution,
52
+ type MediaMetering,
53
+ } from "./media-operation-contract.js";
54
+ import {
55
+ MediaOutputFormatMismatch,
56
+ MediaBillingRefusal,
57
+ MediaExecutionError,
58
+ MediaSafetyFilterRefusal,
59
+ type MediaBillingRefusalCode,
60
+ } from "./execution-error.js";
61
+
62
+ export {
63
+ createDailyMediaMetering,
64
+ DailyMediaMeter,
65
+ type DailyMediaMeterPort,
66
+ type DailyMediaMeterStorage,
67
+ } from "./daily-media-meter.js";
68
+ export {
69
+ MediaBillingRefusal,
70
+ MediaExecutionError,
71
+ type MediaBillingRefusalCode,
72
+ type MediaFailureStage,
73
+ type MediaExecutionErrorOptions,
74
+ } from "./execution-error.js";
75
+ export {
76
+ readHostReference,
77
+ referenceFilename,
78
+ type HostReferenceSource,
79
+ } from "./reference-read.js";
80
+ export { mediaUnits, type MediaUnits } from "./gateway-models.js";
81
+ export { quoteMediaGeneration, type MediaQuote } from "./media-quote.js";
82
+ export type {
83
+ MediaMetering,
84
+ MediaOperation,
85
+ } from "./media-operation-contract.js";
86
+ export {
87
+ MediaOperationOwner,
88
+ mediaOperationDestinationSchema,
89
+ mediaOperationCoordinatesSchema,
90
+ mediaOperationStateSchema,
91
+ mediaImageSchema,
92
+ mediaOperationResultSchema,
93
+ } from "./media-operation-owner.js";
94
+ export type {
95
+ MediaOperationCoordinates,
96
+ MediaOperationRequest,
97
+ MediaOperationProjection,
98
+ MediaOperationDecision,
99
+ MediaOperationState,
100
+ MediaOperationResult,
101
+ MediaOperationEnvironment,
102
+ MediaOperationHooks,
103
+ MediaImage,
104
+ MediaErasurePreflight,
105
+ MediaErasureReadback,
106
+ MediaErasePolicy,
107
+ MediaRetentionResult,
108
+ } from "./media-operation-owner.js";
109
+ export type {
110
+ MediaOperationContext,
111
+ MediaOperationStorage,
112
+ MediaErasureMarker,
113
+ MediaOperationBucket,
114
+ MediaOperationObject,
115
+ } from "./media-operation-storage.js";
116
+
117
+ const identifier = z.lazy(() => z.string().min(1).max(256));
118
+ /** Decode relative service generation input. Identity comes from the host. */
119
+ export const mediaRequestSchema = z.strictObject({
120
+ /** Fixed destination or reference file path. */
121
+ path: mediaPathSchema,
122
+ /** Requested model, dimensions, prompt and references. */
123
+ settings: mediaGenerationSettingsSchema,
124
+ /** Optional verified image encoding pin. */
125
+ outputFormat: mediaRequestedImageFormatSchema.optional(),
126
+ });
127
+ /** A price request: the exact settings, no destination or request id. */
128
+ const mediaQuoteRequestSchema = z.strictObject({
129
+ settings: mediaGenerationSettingsSchema,
130
+ });
131
+ export { mediaResultSchema } from "./media-operation-contract.js";
132
+
133
+ async function readJsonBody(request: Request): Promise<
134
+ | Readonly<{
135
+ /** Outcome or model-kind discriminant. */
136
+ kind: "parsed";
137
+ value: unknown;
138
+ }>
139
+ | Readonly<{
140
+ /** Outcome or model-kind discriminant. */
141
+ kind: "invalid";
142
+ }>
143
+ > {
144
+ try {
145
+ const value: unknown = await request.json();
146
+ return {
147
+ kind: "parsed",
148
+ value,
149
+ };
150
+ } catch {
151
+ return {
152
+ kind: "invalid",
153
+ };
154
+ }
155
+ }
156
+
157
+ /** A background (video) generation in progress; retry the same request id. */
158
+
159
+ /** Identity supplied by the admitting host, never selected by a request body. */
160
+ export type MediaScope = Readonly<{
161
+ /** Host-admitted actor identity. */
162
+ actorId: string;
163
+ /** Host-owned isolation namespace. */
164
+ namespace: string;
165
+ /** Host-owned application or actor within the namespace. */
166
+ owner: string;
167
+ /** Host-admitted destination identity. */
168
+ destinationId: string;
169
+ }>;
170
+
171
+ /** Customer-visible refusal text owned by a metered host. */
172
+ export type MediaRefusalMessages = Readonly<
173
+ Record<MediaBillingRefusalCode, string>
174
+ >;
175
+
176
+ /** Host authority, durable operations, provider, metering and destination access. */
177
+ export type MediaServiceHost = Readonly<{
178
+ /** Identity admitted by the host before service construction. */
179
+ scope: MediaScope;
180
+ /** Resolve durable operations by their service-selected name. */
181
+ operations: {
182
+ /** Resolve the service-selected operation name to its local or RPC owner. */
183
+ getByName(name: string): MediaExecution["operation"];
184
+ };
185
+ /** The provider call for every generation (Workers AI, or the Hub's edge on celld). */
186
+ provider: MediaProvider;
187
+ /** Host-owned address roster, committed before the operation can create storage. */
188
+ beforeAdmit?: ((requestId: string) => Promise<void>) | undefined;
189
+ /** Recheck the host's generation authority only before a new dispatch.
190
+ * Retained output still uses destination authorization when saving. */
191
+ authorizeGeneration?: () => Promise<void>;
192
+ /** Authorize and save generated bytes, and optionally read references. */
193
+ destination: Readonly<{
194
+ /** Check host permission before writing or dispatching generation. */
195
+ authorize: (path: string) => Promise<void>;
196
+ /** Save exact generated bytes to the admitted destination. */
197
+ write: (path: string, bytes: Uint8Array) => Promise<void>;
198
+ /**
199
+ * Delete the file written at `path`, only while it still holds the bytes
200
+ * with this SHA-256, so a path reused for something else is never lost.
201
+ * Use `removeMediaIfWritten` to do the compare. Report what happened;
202
+ * "kept" means this destination cannot delete files.
203
+ */
204
+ remove: (
205
+ path: string,
206
+ written: Readonly<{
207
+ /** SHA-256 of the bytes written. */ sha256: string;
208
+ }>,
209
+ ) => Promise<MediaRemoval>;
210
+ /** Authorize and fit one selected reference image for the catalog model. */
211
+ readReference?: (
212
+ reference: MediaReference,
213
+ model: string,
214
+ ) => Promise<MediaReferenceBytes>;
215
+ /** Authorize and read the raw bytes of one reference audio clip. */
216
+ readAudioReference?: (reference: MediaReference) => Promise<Uint8Array>;
217
+ }>;
218
+ /**
219
+ * Opt every `/generate` request into embedding its prompt in the saved
220
+ * image's XMP metadata. Omitted keeps the prompt private.
221
+ */
222
+ embedPrompt?: boolean | undefined;
223
+ /** Translate host authority failures; undefined uses the shared Media failure. */
224
+ onFailure?: (error: MediaExecutionError) => Response | undefined;
225
+ }> &
226
+ (
227
+ | Readonly<{
228
+ /** Omitted: the Fungi gateway provider's own catalogue and quote. */
229
+ catalogue?: undefined;
230
+ /** Omitted with the catalogue: the gateway's own quote. */
231
+ estimate?: undefined;
232
+ }>
233
+ | Readonly<{
234
+ /**
235
+ * The injected `provider`'s own model list, decoded with
236
+ * `parseMediaCatalogue`. Requests are validated against it, never
237
+ * against the Fungi gateway's.
238
+ */
239
+ catalogue: MediaCatalogue;
240
+ /** Provider cost of validated settings in milliunits; owned by the custom provider. */
241
+ estimate: (
242
+ settings: Parameters<MediaProvider>[0],
243
+ references: readonly MediaReferenceBytes[],
244
+ ) => number;
245
+ }>
246
+ ) &
247
+ (
248
+ | Readonly<{
249
+ /** The host pays its own provider directly. */
250
+ metering: "unmetered";
251
+ /** Unmetered hosts do not have billing refusal policy. */
252
+ refusalMessages?: never;
253
+ }>
254
+ | Readonly<{
255
+ /** Idempotent admission and settlement owned by the host. */
256
+ metering: MediaMetering;
257
+ /** Customer copy for each definitive billing refusal. */
258
+ refusalMessages: MediaRefusalMessages;
259
+ }>
260
+ );
261
+
262
+ const headers = {
263
+ "Cache-Control": "private, no-store",
264
+ "X-Content-Type-Options": "nosniff",
265
+ };
266
+
267
+ const billingRefusalWire = {
268
+ insufficient_credits: { code: "INSUFFICIENT_CREDIT", status: 402 },
269
+ denied: { code: "CAPABILITY_DENIED", status: 403 },
270
+ daily_limit_reached: { code: "DAILY_LIMIT_REACHED", status: 429 },
271
+ } as const satisfies Record<
272
+ MediaBillingRefusalCode,
273
+ { code: string; status: number }
274
+ >;
275
+
276
+ function failure(
277
+ error: MediaExecutionError | MediaSettingsError,
278
+ refusalMessages?: Readonly<Record<MediaBillingRefusalCode, string>>,
279
+ ): Response {
280
+ if (error instanceof MediaSafetyFilterRefusal)
281
+ return Response.json(
282
+ {
283
+ error: describeAppError(
284
+ new AppError(error.message, {
285
+ code: "SAFETY_FILTER_REFUSED",
286
+ retryable: false,
287
+ }),
288
+ ).message,
289
+ stage: "provider",
290
+ code: "SAFETY_FILTER_REFUSED",
291
+ retryable: false,
292
+ provider: error.provider,
293
+ },
294
+ { status: 400, headers },
295
+ );
296
+ if (
297
+ error instanceof MediaExecutionError &&
298
+ error.cause instanceof MediaOutputFormatMismatch
299
+ )
300
+ return Response.json(
301
+ {
302
+ error:
303
+ "Media provider did not return the requested image format; nothing was saved. Start a new request.",
304
+ stage: error.stage,
305
+ code: "HOST_FAILURE",
306
+ retryable: false,
307
+ },
308
+ {
309
+ status: 503,
310
+ headers,
311
+ },
312
+ );
313
+ if (
314
+ error instanceof MediaExecutionError &&
315
+ error.stage === "billing" &&
316
+ error.cause instanceof MediaBillingRefusal
317
+ )
318
+ return Response.json(
319
+ {
320
+ error:
321
+ refusalMessages?.[error.cause.code] ??
322
+ "Media generation was refused by the host.",
323
+ stage: "billing",
324
+ code: billingRefusalWire[error.cause.code].code,
325
+ retryable: false,
326
+ },
327
+ {
328
+ status: billingRefusalWire[error.cause.code].status,
329
+ headers,
330
+ },
331
+ );
332
+ if (
333
+ error instanceof MediaSettingsError ||
334
+ (error.stage === "estimate" && error.cause instanceof MediaSettingsError)
335
+ )
336
+ return Response.json(
337
+ {
338
+ error:
339
+ "Media generation settings are invalid; check the model, dimensions, steps, and destination.",
340
+ stage: "settings",
341
+ code: "INVALID_ARGUMENT",
342
+ retryable: false,
343
+ },
344
+ {
345
+ status: 400,
346
+ headers,
347
+ },
348
+ );
349
+ if (error.stage === "provider") {
350
+ const code =
351
+ error.customerCharge === "none"
352
+ ? "MEDIA_PROVIDER_FAILURE_UNCHARGED"
353
+ : "MEDIA_PROVIDER_FAILURE";
354
+ return Response.json(
355
+ {
356
+ error: describeAppError(
357
+ new AppError(error.message, {
358
+ code,
359
+ retryable: false,
360
+ }),
361
+ ).message,
362
+ stage: error.stage,
363
+ code,
364
+ retryable: false,
365
+ provider: error.provider,
366
+ },
367
+ { status: 503, headers },
368
+ );
369
+ }
370
+ const messages = {
371
+ "generation-authorization":
372
+ "Media generation permission could not be checked; try again.",
373
+ "destination-authorization":
374
+ "Media destination permission could not be checked; try again.",
375
+ "destination-write":
376
+ "Media generated an image but could not save it; retry this request to save the retained result.",
377
+ estimate:
378
+ "Media could not prepare the image inputs or estimate their cost; check the reference files and retry.",
379
+ billing:
380
+ error.cause instanceof DailyMediaMeterError
381
+ ? error.cause.operation === "admit"
382
+ ? "Couldn't check today's spending limit. Try again."
383
+ : "Couldn't record this generation's spending. Retry this request."
384
+ : "Media billing is unavailable; retry this request.",
385
+ normalization:
386
+ "Media provider returned an unusable image; start a new request only after checking provider status.",
387
+ artifact:
388
+ "Media generated output could not be retained or read; try again.",
389
+ operation: "Media operation is unresolved; try again.",
390
+ };
391
+ return Response.json(
392
+ {
393
+ error: messages[error.stage],
394
+ stage: error.stage,
395
+ code: "HOST_FAILURE",
396
+ retryable: error.stage !== "normalization",
397
+ provider:
398
+ error instanceof MediaExecutionError ? error.provider : undefined,
399
+ },
400
+ {
401
+ status: 503,
402
+ headers,
403
+ },
404
+ );
405
+ }
406
+
407
+ /** One Media generation request, already carrying its idempotency key. */
408
+ export type MediaGenerationRequest = Readonly<{
409
+ /** Stable request identity reused for retries. */
410
+ requestId: string;
411
+ /** Fixed destination path for this operation. */
412
+ path: string;
413
+ /** Model settings validated before admission. */
414
+ settings: Parameters<typeof validateMediaGenerationSettings>[0];
415
+ /** Optional verified image format pin. */
416
+ outputFormat?: z.output<typeof mediaRequestSchema>["outputFormat"];
417
+ /**
418
+ * Publish the prompt in the saved image's XMP metadata (`fungi:prompt`).
419
+ * Omitted or false keeps it out: a host must opt in for each generation.
420
+ */
421
+ embedPrompt?: boolean | undefined;
422
+ }>;
423
+
424
+ /** The typed result of one generation, shared by the Hono route and the Agent path. */
425
+ export type MediaGenerationOutcome =
426
+ | Readonly<{
427
+ /** Outcome or model-kind discriminant. */
428
+ kind: "succeeded";
429
+ /** Fixed destination or reference file path. */
430
+ path: string;
431
+ /** Output byte length. */
432
+ bytes: number;
433
+ /** Admitted price in milliunits, where 1 cent is 1,000 milliunits. */
434
+ costMilliunits: number;
435
+ /** Actual output encoding. */
436
+ format: "png" | "jpeg" | "gif" | "webp" | "mp4" | "mp3";
437
+ /** Requested image height or nominal video selector; absent for audio. */
438
+ height?: number | undefined;
439
+ /** Provider catalog model identifier. */
440
+ model: string;
441
+ /** Requested image width or nominal video selector; absent for audio. */
442
+ width?: number | undefined;
443
+ }>
444
+ | Readonly<{
445
+ /** Outcome or model-kind discriminant. */
446
+ kind: "pending";
447
+ /** Whether generation is running through the durable alarm. */
448
+ background: boolean;
449
+ /** Delay before retrying the same request, in seconds. */
450
+ retryAfterSeconds: number;
451
+ }>
452
+ | Readonly<{
453
+ /** Outcome or model-kind discriminant. */
454
+ kind: "conflict";
455
+ }>
456
+ | Readonly<{
457
+ /** Outcome or model-kind discriminant. */
458
+ kind: "interrupted";
459
+ }>
460
+ | Readonly<{
461
+ /** Outcome or model-kind discriminant. */
462
+ kind: "unavailable";
463
+ }>;
464
+
465
+ /** Generate through the Effect core with a Promise boundary preserving typed domain failures. */
466
+ export async function generateMedia(
467
+ host: MediaServiceHost,
468
+ request: MediaGenerationRequest,
469
+ signal?: AbortSignal,
470
+ ): Promise<MediaGenerationOutcome> {
471
+ const result = await Effect.runPromise(
472
+ Effect.result(runMediaGeneration(host, request, signal)),
473
+ );
474
+ return Result.getOrThrowWith(result, (error) => error);
475
+ }
476
+
477
+ /**
478
+ * What one generation still retains, by its request id: where its file goes,
479
+ * and the exact provider bytes held for recovery, including bytes a crash left
480
+ * unrecorded. Null once erased. Refuses another namespace.
481
+ */
482
+ export function retainedMedia(
483
+ host: Pick<MediaServiceHost, "operations" | "scope">,
484
+ requestId: string,
485
+ ): Promise<MediaRetained | null> {
486
+ return Promise.resolve(
487
+ host.operations
488
+ .getByName(`media:${requestId}`)
489
+ .retained(host.scope.namespace, requestId),
490
+ );
491
+ }
492
+
493
+ /**
494
+ * Read back the exact provider bytes a generation retained, before any
495
+ * provenance, so a host can re-save a result whose destination write was lost.
496
+ * Null when erased or nothing was retained. Refuses another namespace.
497
+ */
498
+ export function readRetainedMedia(
499
+ host: Pick<MediaServiceHost, "operations" | "scope">,
500
+ requestId: string,
501
+ ): Promise<MediaRetainedBytes | null> {
502
+ return Promise.resolve(
503
+ host.operations
504
+ .getByName(`media:${requestId}`)
505
+ .readRetained(host.scope.namespace, requestId),
506
+ );
507
+ }
508
+
509
+ /** Erasure of one generation, with what happened to its destination file. */
510
+ export type MediaOperationErasure = MediaErasure &
511
+ Readonly<{
512
+ /**
513
+ * What the destination did with the file this operation wrote: null when
514
+ * none was ever begun. "not-ours" means the path now holds other bytes and
515
+ * was left alone.
516
+ */
517
+ destinationFile: MediaRemoval | null;
518
+ }>;
519
+
520
+ /**
521
+ * Erase everything a generation retained or could still write: its retained
522
+ * output, reference copies, storage and the destination file (only while it
523
+ * still holds what this operation wrote). Works mid generation: the operation
524
+ * refuses later writes, deletes anything that lands, and its open billing hold
525
+ * is settled at zero units. Call again until `clear` is true; the destination
526
+ * facts are kept for that retry.
527
+ */
528
+ export async function eraseMediaOperation(
529
+ host: Pick<
530
+ MediaServiceHost,
531
+ "operations" | "scope" | "destination" | "metering"
532
+ >,
533
+ requestId: string,
534
+ ): Promise<MediaOperationErasure> {
535
+ const operationId = `media:${requestId}`;
536
+ const erased = await host.operations
537
+ .getByName(operationId)
538
+ .erase(host.scope.namespace, requestId);
539
+ if (erased.abandonedGeneration && host.metering !== "unmetered")
540
+ await host.metering.settle({ operationId, units: 0 });
541
+ const destinationFile =
542
+ erased.destinationPath === null || erased.writtenSha256 === null
543
+ ? null
544
+ : await host.destination.remove(erased.destinationPath, {
545
+ sha256: erased.writtenSha256,
546
+ });
547
+ return { ...erased, destinationFile };
548
+ }
549
+
550
+ function outcomeResponse(outcome: MediaGenerationOutcome): Response {
551
+ if (outcome.kind === "conflict")
552
+ return Response.json(
553
+ {
554
+ error: "This request ID already belongs to a different Media request.",
555
+ stage: "operation",
556
+ code: "INVALID_ARGUMENT",
557
+ retryable: false,
558
+ },
559
+ {
560
+ status: 409,
561
+ headers,
562
+ },
563
+ );
564
+ if (outcome.kind === "pending" && outcome.background)
565
+ // A video generation runs in the background; retry this request id.
566
+ return Response.json(
567
+ mediaPendingSchema.parse({
568
+ status: "pending",
569
+ retryAfterSeconds: outcome.retryAfterSeconds,
570
+ }),
571
+ {
572
+ status: 202,
573
+ headers: {
574
+ ...headers,
575
+ "Retry-After": String(outcome.retryAfterSeconds),
576
+ },
577
+ },
578
+ );
579
+ if (outcome.kind === "pending")
580
+ return Response.json(
581
+ {
582
+ error:
583
+ "Media generation is still in progress; retry this request to check its durable result.",
584
+ stage: "operation",
585
+ code: "HOST_FAILURE",
586
+ retryable: true,
587
+ },
588
+ {
589
+ status: 409,
590
+ headers,
591
+ },
592
+ );
593
+ if (outcome.kind === "interrupted" || outcome.kind === "unavailable")
594
+ return Response.json(
595
+ {
596
+ error:
597
+ "Media generation was interrupted before completion; start a new request.",
598
+ stage: "operation",
599
+ code: "HOST_FAILURE",
600
+ retryable: false,
601
+ },
602
+ {
603
+ status: 503,
604
+ headers,
605
+ },
606
+ );
607
+ return Response.json(
608
+ mediaResultSchema.parse({
609
+ bytes: outcome.bytes,
610
+ costMilliunits: outcome.costMilliunits,
611
+ path: outcome.path,
612
+ format: outcome.format,
613
+ model: outcome.model,
614
+ height: outcome.height,
615
+ width: outcome.width,
616
+ }),
617
+ { headers },
618
+ );
619
+ }
620
+
621
+ /** Relative HTTP routes; the caller admits identity and supplies destination access. */
622
+ export function createMediaService(host: MediaServiceHost) {
623
+ const app = new Hono();
624
+ app.get("/models", () =>
625
+ Response.json(
626
+ (host.catalogue ?? listMediaModels())
627
+ .map(withBillingUnit)
628
+ .map((model) =>
629
+ host.destination.readReference !== undefined ||
630
+ model.input.maxReferences === 0
631
+ ? model
632
+ : {
633
+ ...model,
634
+ label: `${model.label} (reference images unavailable in this App host)`,
635
+ input: {
636
+ ...model.input,
637
+ maxReferences: 0,
638
+ referenceField: null,
639
+ },
640
+ },
641
+ )
642
+ .map((model) =>
643
+ host.destination.readAudioReference !== undefined ||
644
+ model.video?.audioReferences == null
645
+ ? model
646
+ : { ...model, video: { ...model.video, audioReferences: null } },
647
+ ),
648
+ { headers },
649
+ ),
650
+ );
651
+ app.post("/generate", async (context) => {
652
+ const body = await readJsonBody(context.req.raw);
653
+ const input =
654
+ body.kind === "parsed"
655
+ ? mediaRequestSchema.safeParse(body.value)
656
+ : undefined;
657
+ const requestId = identifier.safeParse(context.req.header("X-Request-Id"));
658
+ if (input?.success !== true || !requestId.success)
659
+ return failure(new MediaSettingsError("invalid request"));
660
+ return Effect.runPromise(
661
+ runMediaGeneration(
662
+ host,
663
+ {
664
+ requestId: requestId.data,
665
+ path: input.data.path,
666
+ settings: input.data.settings,
667
+ outputFormat: input.data.outputFormat,
668
+ embedPrompt: host.embedPrompt,
669
+ },
670
+ context.req.raw.signal,
671
+ ).pipe(
672
+ Effect.match({
673
+ onSuccess: outcomeResponse,
674
+ onFailure: (error) =>
675
+ (error instanceof MediaExecutionError
676
+ ? host.onFailure?.(error)
677
+ : undefined) ?? failure(error, host.refusalMessages),
678
+ }),
679
+ ),
680
+ );
681
+ });
682
+ // The provider cost of one exact request, priced by the same estimator and
683
+ // reference reads as /generate; the host applies any billing policy.
684
+ app.post("/quote", async (context) => {
685
+ const body = await readJsonBody(context.req.raw);
686
+ const input =
687
+ body.kind === "parsed"
688
+ ? mediaQuoteRequestSchema.safeParse(body.value)
689
+ : undefined;
690
+ if (input?.success !== true)
691
+ return failure(new MediaSettingsError("invalid request"));
692
+ try {
693
+ const quote = await quoteMediaGeneration(input.data.settings, {
694
+ read: (reference, model) => {
695
+ if (host.destination.readReference === undefined)
696
+ throw new MediaSettingsError("reference images are unavailable");
697
+ return host.destination.readReference(reference, model);
698
+ },
699
+ });
700
+ return Response.json(quote, { headers });
701
+ } catch (cause) {
702
+ if (cause instanceof MediaSettingsError) return failure(cause);
703
+ const error =
704
+ cause instanceof MediaExecutionError
705
+ ? cause
706
+ : new MediaExecutionError("estimate", { cause });
707
+ return host.onFailure?.(error) ?? failure(error, host.refusalMessages);
708
+ }
709
+ });
710
+ return app;
711
+ }