@fungi.computer/darkroom 0.11.11 → 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 +7 -1
  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,1786 @@
1
+ import {
2
+ mediaModels,
3
+ mediaRequestedImageFormatSchema,
4
+ type MediaCatalogue,
5
+ } from "./model-catalog.js";
6
+ import { defineIdFamily } from "@fungi.computer/cairn/id";
7
+ import {
8
+ mediaGenerationSettingsSchema,
9
+ validateMediaGenerationSettings,
10
+ type MediaGenerationSettings,
11
+ } from "./index.js";
12
+ import { z } from "zod";
13
+ import type {
14
+ MediaOperationContext,
15
+ MediaOperationBucket,
16
+ MediaErasureMarker,
17
+ } from "./media-operation-storage.js";
18
+ import type {
19
+ MediaAudioReferenceBytes,
20
+ MediaProvider,
21
+ MediaReferenceBytes,
22
+ } from "./index.js";
23
+ import { reportCatchFailure } from "./failure.js";
24
+ import {
25
+ MediaExecutionError,
26
+ MediaSafetyFilterRefusal,
27
+ mediaFailureStageSchema,
28
+ type MediaFailureStage,
29
+ } from "./execution-error.js";
30
+ import { backgroundProviderTimeoutMs } from "./media-run-lifetime.js";
31
+ import {
32
+ mediaProviderDiagnosticWireSchema,
33
+ type MediaProviderDiagnostic,
34
+ } from "@fungi.computer/agar/errors";
35
+
36
+ const providerFailureSchema = z.strictObject({
37
+ stage: mediaFailureStageSchema.extract(["provider", "normalization"]),
38
+ safetyRefused: z.boolean(),
39
+ provider: mediaProviderDiagnosticWireSchema.optional(),
40
+ });
41
+
42
+ const ids = defineIdFamily({
43
+ family: "hub-media-operation",
44
+ version: 1,
45
+ kinds: { lease: { prefix: "media_lease" } },
46
+ });
47
+
48
+ const text = z.string().min(1).max(256);
49
+ const path = z.string().min(1).max(1_024);
50
+ const referenceMetadataSchema = z.lazy(() =>
51
+ z.object({
52
+ format: z.enum(["png", "jpeg", "gif", "webp"]),
53
+ width: z.coerce.number().int().positive(),
54
+ height: z.coerce.number().int().positive(),
55
+ }),
56
+ );
57
+ const referenceKey = (operationId: string, index: number) =>
58
+ `media-reference/v1/${operationId}/${String(index)}`;
59
+ const audioReferenceMetadataSchema = z.lazy(() =>
60
+ z.object({
61
+ mimeType: z.enum(["audio/mpeg", "audio/mp4", "audio/wav", "audio/ogg"]),
62
+ durationSeconds: z.coerce.number().positive(),
63
+ }),
64
+ );
65
+ const audioReferenceKey = (operationId: string, index: number) =>
66
+ `media-audio-reference/v1/${operationId}/${String(index)}`;
67
+
68
+ const activeStates: readonly MediaOperationState[] = [
69
+ "estimating",
70
+ "generating",
71
+ "writing",
72
+ "charging",
73
+ ];
74
+ /** States whose billing hold the executor has not yet settled itself. */
75
+ const holdOpenStates: readonly MediaOperationState[] = [
76
+ "estimating",
77
+ "generating",
78
+ "writing",
79
+ ];
80
+ const writeReceiptSchema = z.string().regex(/^sha256:([0-9a-f]{64})$/);
81
+ function erasureMarker(record: OperationRecord | null): MediaErasureMarker {
82
+ const receipt = writeReceiptSchema.safeParse(record?.writeReceipt);
83
+ return {
84
+ destinationPath: record?.input.path ?? null,
85
+ writtenSha256: receipt.success
86
+ ? receipt.data.slice("sha256:".length)
87
+ : null,
88
+ abandonedGeneration:
89
+ record !== null && holdOpenStates.includes(record.state),
90
+ };
91
+ }
92
+
93
+ const referenceKeys = (record: OperationRecord) => [
94
+ ...(record.input.references ?? []).map((_reference, index) =>
95
+ referenceKey(record.operationId, index),
96
+ ),
97
+ ...(record.input.audioReferences ?? []).map((_reference, index) =>
98
+ audioReferenceKey(record.operationId, index),
99
+ ),
100
+ ];
101
+
102
+ /** Fixed generation destination captured before provider dispatch. */
103
+ export const mediaOperationDestinationSchema = z.lazy(() =>
104
+ z.strictObject({
105
+ /** Host-admitted destination or reference identity. */
106
+ computerId: text,
107
+ /** Fixed relative path in the admitted destination. */
108
+ path,
109
+ /** Optional verified image encoding pin. */
110
+ outputFormat: mediaRequestedImageFormatSchema.optional(),
111
+ }),
112
+ );
113
+ /** Normalized generation and its fixed destination, captured for exact replay. */
114
+ export type MediaOperationRequest = MediaGenerationSettings &
115
+ z.output<typeof mediaOperationDestinationSchema>;
116
+
117
+ /** Decode host namespace and owner identity. */
118
+ export const mediaOperationCoordinatesSchema = z.strictObject({
119
+ /** Host isolation namespace. */
120
+ namespace: text,
121
+ /** Host owner within the namespace. */
122
+ owner: text,
123
+ });
124
+ /** Host-owned namespace and owner identity for one durable operation. */
125
+ export type MediaOperationCoordinates = z.output<
126
+ typeof mediaOperationCoordinatesSchema
127
+ >;
128
+
129
+ /** Decode durable generation, save and settlement states. */
130
+ export const mediaOperationStateSchema = z.enum({
131
+ /** Host identity and input captured. */
132
+ admitted: "admitted",
133
+ /** Exclusive input preparation lease. */
134
+ estimating: "estimating",
135
+ /** Provider dispatch admitted; output not yet retained. */
136
+ generating: "generating",
137
+ /** Generated output retained; destination save in progress. */
138
+ writing: "writing",
139
+ /** Destination committed; idempotent host settlement pending. */
140
+ charging: "charging",
141
+ /** Unmetered generation and destination write completed with a quote. */
142
+ written: "written",
143
+ /** Generation and settlement completed. */
144
+ succeeded: "succeeded",
145
+ /** Provider execution ended without a reusable output. */
146
+ interrupted: "interrupted",
147
+ });
148
+ /** Durable generation, save and settlement states. */
149
+ export type MediaOperationState = z.output<typeof mediaOperationStateSchema>;
150
+
151
+ /** Decode retained or saved output size and encoding. */
152
+ export const mediaImageSchema = z.lazy(() =>
153
+ z.strictObject({
154
+ /** Output byte length. */
155
+ bytes: z.number().int().positive(),
156
+ /** Actual output encoding. */
157
+ format: text,
158
+ }),
159
+ );
160
+ /** Byte length and encoding of generated or saved output. */
161
+ export type MediaImage = z.output<typeof mediaImageSchema>;
162
+ const retainedFormatSchema = z.lazy(() =>
163
+ z
164
+ .enum([
165
+ "image/png",
166
+ "image/jpeg",
167
+ "image/gif",
168
+ "image/webp",
169
+ "video/mp4",
170
+ "audio/mpeg",
171
+ ])
172
+ .transform(
173
+ (mime) =>
174
+ ({
175
+ "image/png": "png",
176
+ "image/jpeg": "jpeg",
177
+ "image/gif": "gif",
178
+ "image/webp": "webp",
179
+ "video/mp4": "mp4",
180
+ "audio/mpeg": "mp3",
181
+ })[mime],
182
+ ),
183
+ );
184
+ const outputSchema = z.lazy(() =>
185
+ z.strictObject({
186
+ key: text,
187
+ version: text,
188
+ bytes: z.number().int().positive(),
189
+ format: text,
190
+ }),
191
+ );
192
+ type MediaOutput = z.output<typeof outputSchema>;
193
+
194
+ /** Decode the settled receipt, including the host-admitted customer price. */
195
+ export const mediaOperationResultSchema = z.lazy(() =>
196
+ z.strictObject({
197
+ /** Durable operation identifier. */
198
+ generationId: text,
199
+ /** Output byte length. */
200
+ bytes: z.number().int().positive(),
201
+ /** Actual output encoding. */
202
+ format: text,
203
+ /** Admitted price in milliunits, where 1 cent is 1,000 milliunits. */
204
+ costMilliunits: z.number().int().nonnegative(),
205
+ }),
206
+ );
207
+ /** Settled generation receipt with the host-admitted customer price. */
208
+ export type MediaOperationResult = z.output<typeof mediaOperationResultSchema>;
209
+
210
+ type OperationRecord = Readonly<{
211
+ operationId: string;
212
+ requestId: string;
213
+ actorUserId: string;
214
+ namespace: string;
215
+ owner: string;
216
+ fingerprint: string;
217
+ input: MediaOperationRequest;
218
+ state: MediaOperationState;
219
+ leaseId: string | null;
220
+ leaseExpiresAt: number | null;
221
+ estimatedCostMilliunits: number | null;
222
+ image: MediaImage | null;
223
+ output: MediaOutput | null;
224
+ writeReceipt: string | null;
225
+ result: MediaOperationResult | null;
226
+ createdAt: number;
227
+ updatedAt: number;
228
+ }>;
229
+
230
+ /** The only operation shape safe to return outside the owner. */
231
+ export type MediaOperationProjection = Readonly<{
232
+ /** Durable object name identifying this operation. */
233
+ operationId: string;
234
+ /** Retry identity chosen by the caller. */
235
+ requestId: string;
236
+ /** Host isolation namespace. */
237
+ namespace: string;
238
+ /** Host owner within the namespace. */
239
+ owner: string;
240
+ /** Current durable lifecycle state. */
241
+ state: MediaOperationState;
242
+ /** Terminal format mismatch after provider execution. */
243
+ spentFailure: "output_format_mismatch" | null;
244
+ /** Safe terminal provider failure; no original cause or provider message. */
245
+ providerFailure: Readonly<{
246
+ /** Provider dispatch or output normalization, not a save failure. */
247
+ stage: Extract<MediaFailureStage, "provider" | "normalization">;
248
+ /** Preserve the model's safety refusal classification on replay. */
249
+ safetyRefused: boolean;
250
+ /** Allowlisted facts only; never the original error message or cause. */
251
+ provider?: MediaProviderDiagnostic | undefined;
252
+ }> | null;
253
+ /** Pinned host price or unmetered quote. */
254
+ estimatedCostMilliunits: number | null;
255
+ /** Retained or saved image metadata. */
256
+ image: MediaImage | null;
257
+ /** Settled receipt when generation and billing completed. */
258
+ result: MediaOperationResult | null;
259
+ /** Admission timestamp in milliseconds since the epoch. */
260
+ createdAt: number;
261
+ /** Last transition timestamp in milliseconds since the epoch. */
262
+ updatedAt: number;
263
+ }>;
264
+
265
+ /** What a host needs to serve one shared output: never references or receipts. */
266
+ export type MediaShareSource = Readonly<{
267
+ /** Retry identity of the generation; a Print's id. */
268
+ requestId: string;
269
+ /** The person whose request generated it. */
270
+ actorUserId: string;
271
+ /** Retained exact provider bytes in the host's artifacts bucket. */
272
+ outputKey: string;
273
+ /** Media type of the retained bytes. */
274
+ contentType: string;
275
+ /** Length of the retained bytes. */
276
+ bytes: number;
277
+ /** Whether the output is a still image or a video. */
278
+ kind: "image" | "video";
279
+ /** The generation prompt, as sent to the model. */
280
+ prompt: string;
281
+ /** Catalog model identifier. */
282
+ model: string;
283
+ /** Requested width in pixels. */
284
+ width: number;
285
+ /** Requested height in pixels. */
286
+ height: number;
287
+ /** Video length in whole seconds; null for an image. */
288
+ durationSeconds: number | null;
289
+ }>;
290
+
291
+ /** An admission or claim decision with a safe operation projection. */
292
+ export type MediaOperationDecision = Readonly<{
293
+ /** Admission or claim outcome. */
294
+ kind:
295
+ | "admitted"
296
+ | "conflict"
297
+ | "replayed"
298
+ | "claimed"
299
+ | "pending"
300
+ | "succeeded"
301
+ | "interrupted";
302
+ /** Safe persisted projection for this decision. */
303
+ operation: MediaOperationProjection;
304
+ /** Exclusive dispatch or save lease when claimed. */
305
+ leaseId?: string;
306
+ }>;
307
+
308
+ /** Scoped inactivity observation made before destructive erasure. */
309
+ export type MediaErasurePreflight = Readonly<{
310
+ /** Namespace supplied by the host's resource roster. */
311
+ namespace: string;
312
+ /** Named operation request supplied by that roster. */
313
+ requestId: string;
314
+ /** Whether durable erasure has already completed. */
315
+ erased: boolean;
316
+ }>;
317
+
318
+ /** Evidence that retained output, SQL and alarms were erased. */
319
+ export type MediaErasureReadback = Readonly<{
320
+ /** True only after all local data and retained output are absent. */
321
+ clear: boolean;
322
+ }>;
323
+
324
+ /** How `erase` treats an operation that is still generating or saving. */
325
+ export type MediaErasePolicy =
326
+ /** Abort it: its later writes refuse and anything that lands is deleted. */
327
+ | "abort-active"
328
+ /** Refuse, atomically with the erasure, so a host that waits for inactivity never aborts work. */
329
+ | "refuse-active";
330
+
331
+ /** Result of erasing one operation: readback plus what the host may still own. */
332
+ export type MediaErasure = MediaErasureReadback &
333
+ Readonly<{
334
+ /**
335
+ * The destination path this operation wrote or could have written, kept
336
+ * through erasure so the host can delete the file it owns. Null when the
337
+ * operation was never admitted.
338
+ */
339
+ destinationPath: string | null;
340
+ /**
341
+ * SHA-256 of the exact bytes this operation wrote, or was about to write,
342
+ * to `destinationPath`. Delete the file only while it still matches. Null
343
+ * when no write was ever begun.
344
+ */
345
+ writtenSha256: string | null;
346
+ /**
347
+ * True when the operation was erased before it finished, so a billing hold
348
+ * it took may be open. The host settles it at zero units; repeating that
349
+ * is idempotent.
350
+ */
351
+ abandonedGeneration: boolean;
352
+ }>;
353
+
354
+ /** Exact provider bytes an operation retained, before any provenance. */
355
+ export type MediaRetainedBytes = Readonly<{
356
+ /** The retained bytes. */
357
+ bytes: Uint8Array;
358
+ /** Actual output encoding. */
359
+ format: string;
360
+ }>;
361
+
362
+ /** What one operation still retains, readable by operation id. */
363
+ export type MediaRetained = Readonly<{
364
+ /** Retry identity of the generation. */
365
+ requestId: string;
366
+ /** Current lifecycle state. */
367
+ state: MediaOperationState;
368
+ /** The host destination path the generation writes, or may already have written. */
369
+ destinationPath: string;
370
+ /**
371
+ * The exact provider bytes retained in the artifacts bucket, or null before
372
+ * any were retained. Found by key even when a crash left them unrecorded.
373
+ */
374
+ output: Readonly<{
375
+ /** Retained byte length. */
376
+ bytes: number;
377
+ /** Actual output encoding. */
378
+ format: string;
379
+ /** Media type of the retained bytes. */
380
+ contentType: string;
381
+ }> | null;
382
+ }>;
383
+
384
+ /** Retained output projection, or a terminal spent format refusal. */
385
+ export type MediaRetentionResult =
386
+ | MediaOperationProjection
387
+ | Readonly<{
388
+ /** Provider execution finished with an unusable pinned format. */
389
+ kind: "refused";
390
+ /** Stable mismatch reason recorded before settlement. */
391
+ code: "output_format_mismatch";
392
+ }>;
393
+
394
+ class MediaOperationError extends Error {
395
+ constructor(
396
+ /** Bounded refusal or failure reason. */
397
+ readonly code:
398
+ | "invalid_input"
399
+ | "conflict"
400
+ | "not_found"
401
+ | "partial_init"
402
+ | "lease_lost",
403
+ options?: ErrorOptions,
404
+ ) {
405
+ super(`Media operation ${code}`, options);
406
+ this.name = "MediaOperationError";
407
+ }
408
+ }
409
+
410
+ /** Optional host facts that pin a namespace before operation admission. */
411
+ export type MediaOperationHooks = Readonly<{
412
+ /** Read the namespace already owned by host-local facts, or null when unbound. */
413
+ namespace?: () => string | null;
414
+ /**
415
+ * The model list of the provider this owner dispatches to. Omitted means the
416
+ * Fungi gateway's; a host that injects its own provider supplies that
417
+ * provider's catalogue so stored requests and alarms validate against it.
418
+ */
419
+ catalogue?: () => MediaCatalogue;
420
+ }>;
421
+
422
+ /** Retained-output storage supplied by the host. */
423
+ export type MediaOperationEnvironment = Readonly<{
424
+ /** Bucket retaining exact output and background reference bytes. */
425
+ APP_ARTIFACTS: MediaOperationBucket;
426
+ }>;
427
+
428
+ /** Stored media type for an output format. */
429
+ const outputMime = (format: string) =>
430
+ format === "mp4"
431
+ ? "video/mp4"
432
+ : format === "mp3"
433
+ ? "audio/mpeg"
434
+ : `image/${format}`;
435
+ const operationRowSchema = z.lazy(() =>
436
+ z.object({
437
+ operation_id: z.string(),
438
+ request_id: z.string(),
439
+ actor_user_id: z.string(),
440
+ team_id: z.string(),
441
+ installation_id: z.string(),
442
+ fingerprint: z.string(),
443
+ input: z.string(),
444
+ state: mediaOperationStateSchema,
445
+ lease_id: z.string().nullable(),
446
+ lease_expires_at: z.number().nullable(),
447
+ estimated_cost_milliunits: z.number().nullable(),
448
+ image: z.string().nullable(),
449
+ output: z.string().nullable(),
450
+ write_receipt: z.string().nullable(),
451
+ result: z.string().nullable(),
452
+ created_at: z.number(),
453
+ updated_at: z.number(),
454
+ background: z.number(),
455
+ dispatched_at: z.number().nullable(),
456
+ }),
457
+ );
458
+ type OperationRow = z.output<typeof operationRowSchema>;
459
+
460
+ const schemaStatements = [
461
+ `CREATE TABLE hub_media_operation (
462
+ singleton INTEGER PRIMARY KEY CHECK(singleton=1),
463
+ operation_id TEXT NOT NULL UNIQUE,
464
+ request_id TEXT NOT NULL UNIQUE,
465
+ actor_user_id TEXT NOT NULL,
466
+ team_id TEXT NOT NULL,
467
+ installation_id TEXT NOT NULL,
468
+ fingerprint TEXT NOT NULL,
469
+ input TEXT NOT NULL,
470
+ state TEXT NOT NULL CHECK(state IN ('admitted','estimating','generating','writing','charging','written','succeeded','interrupted')),
471
+ lease_id TEXT,
472
+ lease_expires_at INTEGER,
473
+ estimated_cost_milliunits INTEGER,
474
+ image TEXT,
475
+ output TEXT,
476
+ write_receipt TEXT,
477
+ result TEXT,
478
+ created_at INTEGER NOT NULL,
479
+ updated_at INTEGER NOT NULL,
480
+ background INTEGER NOT NULL DEFAULT 0,
481
+ dispatched_at INTEGER
482
+ ) STRICT`,
483
+ "CREATE TABLE hub_media_spent_failure (singleton INTEGER PRIMARY KEY CHECK(singleton=1),code TEXT NOT NULL CHECK(code='output_format_mismatch')) STRICT",
484
+ "CREATE TABLE hub_media_provider_failure (singleton INTEGER PRIMARY KEY CHECK(singleton=1),failure_json TEXT NOT NULL) STRICT",
485
+ ] as const;
486
+
487
+ function fingerprint(input: MediaOperationRequest): string {
488
+ return JSON.stringify(input);
489
+ }
490
+
491
+ const objectSchema = z.lazy(() => z.record(z.string(), z.unknown()));
492
+
493
+ function decodeStoredRequest(
494
+ serialized: string,
495
+ catalogue: MediaCatalogue,
496
+ ): MediaOperationRequest {
497
+ let raw: unknown;
498
+ try {
499
+ raw = JSON.parse(serialized);
500
+ } catch (cause) {
501
+ throw new MediaOperationError("partial_init", { cause });
502
+ }
503
+ const object = objectSchema.safeParse(raw);
504
+ if (!object.success) throw new MediaOperationError("partial_init");
505
+ const destination = mediaOperationDestinationSchema.safeParse({
506
+ computerId: object.data.computerId,
507
+ path: object.data.path,
508
+ outputFormat: object.data.outputFormat,
509
+ });
510
+ if (!destination.success) throw new MediaOperationError("partial_init");
511
+ const generation = { ...object.data };
512
+ delete generation.computerId;
513
+ delete generation.path;
514
+ delete generation.outputFormat;
515
+ const parsedGeneration = mediaGenerationSettingsSchema.safeParse(generation);
516
+ if (!parsedGeneration.success) throw new MediaOperationError("partial_init");
517
+ let settings: MediaGenerationSettings;
518
+ try {
519
+ settings = validateMediaGenerationSettings(
520
+ parsedGeneration.data,
521
+ catalogue,
522
+ );
523
+ } catch (cause) {
524
+ throw new MediaOperationError("partial_init", { cause });
525
+ }
526
+ return Object.freeze({
527
+ ...settings,
528
+ computerId: destination.data.computerId,
529
+ path: destination.data.path,
530
+ outputFormat: destination.data.outputFormat,
531
+ });
532
+ }
533
+
534
+ /** Own exact replay, dispatch leases, retained output and save recovery in SQL and object storage. */
535
+ export class MediaOperationOwner {
536
+ private erased = false;
537
+ private retainsInFlight = 0;
538
+ /** Output keys whose delete after a late write failed; erase retries them. */
539
+ private readonly lateDeletes = new Set<string>();
540
+ private readonly leaseMs = 5 * 60 * 1_000;
541
+ /**
542
+ * A background (video) generation holds its lease past the 15-minute alarm
543
+ * wall-clock limit, so a live alarm is never mistaken for a lost one.
544
+ */
545
+ private readonly backgroundLeaseMs = 20 * 60 * 1_000;
546
+ private initialized = false;
547
+
548
+ /**
549
+ * The host supplies the provider for background alarm generations.
550
+ */
551
+ protected mediaProvider(): MediaProvider | undefined {
552
+ return this.provider?.();
553
+ }
554
+
555
+ private catalogue(): MediaCatalogue {
556
+ return this.hooks.catalogue?.() ?? mediaModels;
557
+ }
558
+
559
+ constructor(
560
+ private readonly ctx: MediaOperationContext,
561
+ private readonly env: MediaOperationEnvironment,
562
+ private readonly provider?: () => MediaProvider | undefined,
563
+ private readonly hooks: MediaOperationHooks = {},
564
+ ) {
565
+ void ctx.blockConcurrencyWhile(async () => {
566
+ const durablyErased = await ctx.storage.isErased();
567
+ if (durablyErased || this.erased) {
568
+ this.erased = true;
569
+ return;
570
+ }
571
+ this.ensureSchema();
572
+ });
573
+ }
574
+
575
+ private ensureSchema(): void {
576
+ if (this.erased) throw new MediaOperationError("not_found");
577
+ if (this.initialized) return;
578
+ const existing = this.ctx.storage.sql
579
+ .exec(
580
+ "SELECT name FROM sqlite_master WHERE type='table' AND name='hub_media_operation'",
581
+ )
582
+ .toArray()[0];
583
+ if (existing === undefined) {
584
+ for (const statement of schemaStatements)
585
+ this.ctx.storage.sql.exec(statement);
586
+ } else {
587
+ // Pre-launch stores use the current fresh schema or get reset by the host.
588
+ // Missing failure facts are not healed or incrementally migrated here.
589
+ this.ctx.storage.sql.exec(
590
+ "SELECT failure_json FROM hub_media_provider_failure LIMIT 0",
591
+ );
592
+ }
593
+ this.initialized = true;
594
+ }
595
+
596
+ private decodeJson<T>(value: string, schema: z.ZodType<T>): T {
597
+ let parsedValue: unknown;
598
+ try {
599
+ parsedValue = JSON.parse(value);
600
+ } catch (cause) {
601
+ throw new MediaOperationError("partial_init", { cause });
602
+ }
603
+ const parsed = schema.safeParse(parsedValue);
604
+ if (!parsed.success) throw new MediaOperationError("partial_init");
605
+ return parsed.data;
606
+ }
607
+
608
+ private decode(row: OperationRow): OperationRecord {
609
+ const operationId = text.safeParse(row.operation_id);
610
+ const requestId = text.safeParse(row.request_id);
611
+ const actor = text.safeParse(row.actor_user_id);
612
+ const coordinates = mediaOperationCoordinatesSchema.safeParse({
613
+ namespace: row.team_id,
614
+ owner: row.installation_id,
615
+ });
616
+ if (!operationId.success || !requestId.success || !actor.success)
617
+ throw new MediaOperationError("partial_init");
618
+ if (
619
+ !coordinates.success ||
620
+ !mediaOperationStateSchema.safeParse(row.state).success
621
+ )
622
+ throw new MediaOperationError("partial_init");
623
+ return Object.freeze({
624
+ operationId: operationId.data,
625
+ requestId: requestId.data,
626
+ actorUserId: actor.data,
627
+ namespace: coordinates.data.namespace,
628
+ owner: coordinates.data.owner,
629
+ fingerprint: row.fingerprint,
630
+ input: decodeStoredRequest(row.input, this.catalogue()),
631
+ state: row.state,
632
+ leaseId: row.lease_id,
633
+ leaseExpiresAt: row.lease_expires_at,
634
+ estimatedCostMilliunits: row.estimated_cost_milliunits,
635
+ image:
636
+ row.image === null
637
+ ? null
638
+ : this.decodeJson(row.image, mediaImageSchema),
639
+ output:
640
+ row.output === null ? null : this.decodeJson(row.output, outputSchema),
641
+ writeReceipt: row.write_receipt,
642
+ result:
643
+ row.result === null
644
+ ? null
645
+ : this.decodeJson(row.result, mediaOperationResultSchema),
646
+ createdAt: row.created_at,
647
+ updatedAt: row.updated_at,
648
+ });
649
+ }
650
+
651
+ private project(record: OperationRecord): MediaOperationProjection {
652
+ const failure = this.ctx.storage.sql
653
+ .exec("SELECT code FROM hub_media_spent_failure WHERE singleton=1")
654
+ .toArray()[0];
655
+ const spentFailure =
656
+ failure === undefined
657
+ ? null
658
+ : z
659
+ .strictObject({
660
+ code: z.literal("output_format_mismatch"),
661
+ })
662
+ .parse(failure).code;
663
+ const failureRow = this.ctx.storage.sql
664
+ .exec(
665
+ "SELECT failure_json FROM hub_media_provider_failure WHERE singleton=1",
666
+ )
667
+ .toArray()[0];
668
+ const providerFailure =
669
+ failureRow === undefined
670
+ ? null
671
+ : this.decodeJson(
672
+ z
673
+ .strictObject({ failure_json: z.string().max(1024) })
674
+ .parse(failureRow).failure_json,
675
+ providerFailureSchema,
676
+ );
677
+ return Object.freeze({
678
+ operationId: record.operationId,
679
+ requestId: record.requestId,
680
+ namespace: record.namespace,
681
+ owner: record.owner,
682
+ state: record.state,
683
+ spentFailure,
684
+ providerFailure,
685
+ estimatedCostMilliunits: record.estimatedCostMilliunits,
686
+ image: record.image,
687
+ result: record.result,
688
+ createdAt: record.createdAt,
689
+ updatedAt: record.updatedAt,
690
+ });
691
+ }
692
+
693
+ private readRecord(): OperationRecord | null {
694
+ if (this.erased) return null;
695
+ this.ensureSchema();
696
+ const row = this.ctx.storage.sql
697
+ .exec("SELECT * FROM hub_media_operation WHERE singleton=1")
698
+ .toArray()[0];
699
+ if (row === undefined) return null;
700
+ const parsed = operationRowSchema.safeParse(row);
701
+ if (!parsed.success)
702
+ throw new MediaOperationError("partial_init", { cause: parsed.error });
703
+ return this.decode(parsed.data);
704
+ }
705
+
706
+ /** Read the safe persisted operation projection, or null before admission or after erasure. */
707
+ public read(): MediaOperationProjection | null {
708
+ const record = this.readRecord();
709
+ return record === null ? null : this.project(record);
710
+ }
711
+
712
+ /**
713
+ * A settled operation's retained output and recipe, for a host that lets
714
+ * its owner share it publicly. Null before success or for another namespace,
715
+ * so a share can never reach another Team's output. References are never
716
+ * included.
717
+ */
718
+ public readShare(namespace: string): MediaShareSource | null {
719
+ const record = this.readRecord();
720
+ if (
721
+ record?.namespace !== namespace ||
722
+ record.state !== "succeeded" ||
723
+ record.output === null ||
724
+ // Public sharing covers pictures and video; audio has no dimensions to
725
+ // show and no public page yet.
726
+ record.input.width === undefined ||
727
+ record.input.height === undefined
728
+ )
729
+ return null;
730
+ return Object.freeze({
731
+ requestId: record.requestId,
732
+ actorUserId: record.actorUserId,
733
+ outputKey: record.output.key,
734
+ contentType: outputMime(record.output.format),
735
+ bytes: record.output.bytes,
736
+ kind: record.output.format === "mp4" ? "video" : "image",
737
+ prompt: record.input.prompt,
738
+ model: record.input.model,
739
+ width: record.input.width,
740
+ height: record.input.height,
741
+ durationSeconds: record.input.durationSeconds ?? null,
742
+ });
743
+ }
744
+
745
+ /** Check host namespace, request identity and inactivity before erasure. */
746
+ public preflightErasure(
747
+ namespace: string,
748
+ requestId: string,
749
+ ): MediaErasurePreflight {
750
+ if (this.erased) {
751
+ this.assertErasureAddress(requestId);
752
+ return { namespace, requestId, erased: true };
753
+ }
754
+ const record = this.readRecord();
755
+ this.assertScope(namespace, requestId, record);
756
+ if (
757
+ record !== null &&
758
+ ["estimating", "generating", "writing", "charging"].includes(record.state)
759
+ )
760
+ throw new Error("Media operation is still active");
761
+ return { namespace, requestId, erased: false };
762
+ }
763
+
764
+ private assertErasureAddress(requestId: string) {
765
+ if (this.ctx.id.name !== `media:${requestId}`)
766
+ throw new Error("Media erasure address mismatch");
767
+ }
768
+
769
+ private assertScope(
770
+ namespace: string,
771
+ requestId: string,
772
+ record: OperationRecord | null,
773
+ ) {
774
+ this.assertErasureAddress(requestId);
775
+ const ownerNamespace =
776
+ record?.namespace ?? this.hooks.namespace?.() ?? null;
777
+ if (
778
+ (ownerNamespace !== null && ownerNamespace !== namespace) ||
779
+ (record !== null && record.requestId !== requestId)
780
+ )
781
+ throw new Error("Media erasure scope mismatch");
782
+ }
783
+
784
+ /** The stored record even after erasure began, while its tables still exist. */
785
+ private readRecordForErasure(): OperationRecord | null {
786
+ const table = this.ctx.storage.sql
787
+ .exec(
788
+ "SELECT name FROM sqlite_master WHERE type='table' AND name='hub_media_operation'",
789
+ )
790
+ .toArray()[0];
791
+ if (table === undefined) return null;
792
+ const row = this.ctx.storage.sql
793
+ .exec("SELECT * FROM hub_media_operation WHERE singleton=1")
794
+ .toArray()[0];
795
+ if (row === undefined) return null;
796
+ const parsed = operationRowSchema.safeParse(row);
797
+ if (!parsed.success)
798
+ throw new MediaOperationError("partial_init", { cause: parsed.error });
799
+ return this.decode(parsed.data);
800
+ }
801
+
802
+ /**
803
+ * Erase the operation and everything it retained or could still write, even
804
+ * mid-generation. Erasure is marked first, so an attempt still running, or a
805
+ * lease recovered later, can neither transition nor leave output behind: a
806
+ * write that lands after the mark is deleted. The marker is never removed, so
807
+ * a crash cannot resurrect the operation. Safe to repeat until `clear`; a
808
+ * repeat after a partial failure resumes the cleanup.
809
+ */
810
+ public async erase(
811
+ namespace: string,
812
+ requestId: string,
813
+ policy: MediaErasePolicy = "abort-active",
814
+ ): Promise<MediaErasure> {
815
+ const record = this.readRecordForErasure();
816
+ this.assertScope(namespace, requestId, record);
817
+ if (!this.erased) {
818
+ if (
819
+ policy === "refuse-active" &&
820
+ record !== null &&
821
+ activeStates.includes(record.state)
822
+ )
823
+ throw new Error("Media operation is still active");
824
+ // Synchronously, before any await: nothing in this object transitions again.
825
+ this.erased = true;
826
+ }
827
+ if (!(await this.ctx.storage.isErased()))
828
+ await this.ctx.storage.markErased(erasureMarker(record));
829
+ const marker = (await this.ctx.storage.readErasureMarker()) ?? {
830
+ destinationPath: null,
831
+ writtenSha256: null,
832
+ abandonedGeneration: false,
833
+ };
834
+ // The immutable output key is owned by this DO identity; background
835
+ // reference copies hold the person's private inputs.
836
+ const keys = [
837
+ this.erasureOutputKey(),
838
+ ...(record === null ? [] : referenceKeys(record)),
839
+ ...this.lateDeletes,
840
+ ];
841
+ await Promise.all(keys.map((key) => this.env.APP_ARTIFACTS.delete(key)));
842
+ this.lateDeletes.clear();
843
+ await this.ctx.storage.deleteAlarm();
844
+ // Never deleteAll: it would remove the marker and its facts.
845
+ const tables = z
846
+ .array(z.strictObject({ name: z.string() }))
847
+ .parse(
848
+ this.ctx.storage.sql
849
+ .exec(
850
+ "SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'",
851
+ )
852
+ .toArray(),
853
+ );
854
+ for (const { name } of tables)
855
+ this.ctx.storage.sql.exec(`DROP TABLE "${name.replaceAll('"', '""')}"`);
856
+ await this.ctx.storage.deleteKeys(
857
+ (await this.ctx.storage.listKeys()).filter(
858
+ (key) => !key.startsWith("botanical:erased"),
859
+ ),
860
+ );
861
+ return { ...(await this.readErasure()), ...marker };
862
+ }
863
+
864
+ /** Read back empty SQL, alarm and retained output with the durable erasure marker. */
865
+ public async readErasure(): Promise<MediaErasureReadback> {
866
+ const keys = await this.ctx.storage.listKeys();
867
+ const tables = this.ctx.storage.sql
868
+ .exec(
869
+ "SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'",
870
+ )
871
+ .toArray();
872
+ return {
873
+ clear:
874
+ keys.includes("botanical:erased") &&
875
+ keys.every((key) => key.startsWith("botanical:erased")) &&
876
+ (await this.ctx.storage.isErased()) &&
877
+ tables.length === 0 &&
878
+ // A put still in flight, or a late delete that failed, is not clear yet.
879
+ this.retainsInFlight === 0 &&
880
+ this.lateDeletes.size === 0 &&
881
+ (await this.ctx.storage.getAlarm()) === null &&
882
+ (await this.env.APP_ARTIFACTS.head(this.erasureOutputKey())) === null,
883
+ };
884
+ }
885
+
886
+ /**
887
+ * Run a write to the artifacts bucket. If erasure began while it was in
888
+ * flight, delete what landed and refuse; a failed delete is remembered so
889
+ * `erase` reports not-clear and a repeat retries it.
890
+ */
891
+ private async retaining<T>(
892
+ keys: readonly string[],
893
+ write: () => Promise<T>,
894
+ ): Promise<T> {
895
+ this.retainsInFlight += 1;
896
+ try {
897
+ const written = await write();
898
+ if (this.erased) {
899
+ for (const key of keys) this.lateDeletes.add(key);
900
+ await Promise.all(
901
+ keys.map((key) => this.env.APP_ARTIFACTS.delete(key)),
902
+ );
903
+ for (const key of keys) this.lateDeletes.delete(key);
904
+ throw new MediaOperationError("not_found");
905
+ }
906
+ return written;
907
+ } finally {
908
+ this.retainsInFlight -= 1;
909
+ }
910
+ }
911
+
912
+ private async retainedOutput(record: OperationRecord) {
913
+ if (record.output !== null)
914
+ return {
915
+ key: record.output.key,
916
+ bytes: record.output.bytes,
917
+ format: record.output.format,
918
+ version: record.output.version,
919
+ };
920
+ // A crash after the R2 write and before its record leaves exact bytes
921
+ // nothing points to; find them by the key this operation owns.
922
+ const head = await this.env.APP_ARTIFACTS.head(
923
+ `media-output/v1/${record.operationId}`,
924
+ );
925
+ if (head === null) return null;
926
+ return {
927
+ key: head.key,
928
+ bytes: head.size,
929
+ format: retainedFormatSchema.parse(head.httpMetadata?.contentType),
930
+ version: head.version,
931
+ };
932
+ }
933
+
934
+ /** List what this operation retains: its destination path and exact provider output. Null once erased. */
935
+ public async retained(
936
+ namespace: string,
937
+ requestId: string,
938
+ ): Promise<MediaRetained | null> {
939
+ const record = this.readRecord();
940
+ this.assertScope(namespace, requestId, record);
941
+ if (record === null) return null;
942
+ const output = await this.retainedOutput(record);
943
+ return Object.freeze({
944
+ requestId: record.requestId,
945
+ state: record.state,
946
+ destinationPath: record.input.path,
947
+ output:
948
+ output === null
949
+ ? null
950
+ : Object.freeze({
951
+ bytes: output.bytes,
952
+ format: output.format,
953
+ contentType: outputMime(output.format),
954
+ }),
955
+ });
956
+ }
957
+
958
+ /**
959
+ * Read back the exact retained provider bytes, before any provenance, so a
960
+ * host can re-save a result whose destination write was lost. Null when
961
+ * erased or nothing was retained.
962
+ */
963
+ public async readRetained(
964
+ namespace: string,
965
+ requestId: string,
966
+ ): Promise<MediaRetainedBytes | null> {
967
+ const record = this.readRecord();
968
+ this.assertScope(namespace, requestId, record);
969
+ if (record === null) return null;
970
+ const output = await this.retainedOutput(record);
971
+ if (output === null) return null;
972
+ const object = await this.env.APP_ARTIFACTS.get(output.key);
973
+ if (object?.version !== output.version || object.size !== output.bytes)
974
+ throw new MediaOperationError("partial_init");
975
+ const bytes = new Uint8Array(await object.arrayBuffer());
976
+ // Erasure may have begun while the object was read.
977
+ if (this.erased) throw new MediaOperationError("not_found");
978
+ return { bytes, format: output.format };
979
+ }
980
+
981
+ private erasureOutputKey() {
982
+ const name = this.ctx.id.name;
983
+ if (name === undefined)
984
+ throw new Error("Media operation identity unavailable");
985
+ return `media-output/v1/${name}`;
986
+ }
987
+
988
+ private requireRecord(): OperationRecord {
989
+ const record = this.readRecord();
990
+ if (record === null) throw new MediaOperationError("not_found");
991
+ return record;
992
+ }
993
+
994
+ private update(
995
+ input: Readonly<{
996
+ expectedState: MediaOperationState;
997
+ expectedLeaseId: string | null;
998
+ /** Current durable lifecycle state. */
999
+ state: MediaOperationState;
1000
+ /** Exclusive generation or save lease identifier. */
1001
+ leaseId: string | null;
1002
+ /** Lease expiry in milliseconds since the epoch. */
1003
+ leaseExpiresAt: number | null;
1004
+ /** Pinned host price or unmetered quote. */
1005
+ estimatedCostMilliunits: number | null;
1006
+ /** Retained or saved image size and encoding. */
1007
+ image: MediaImage | null;
1008
+ /** Exact retained provider output. */
1009
+ output: MediaOutput | null;
1010
+ writeReceipt: string | null;
1011
+ /** Settled generation receipt. */
1012
+ result: MediaOperationResult | null;
1013
+ allowExpired?: boolean;
1014
+ }>,
1015
+ ): OperationRecord {
1016
+ const timestamp = Date.now();
1017
+ this.ctx.storage.sql.exec(
1018
+ `UPDATE hub_media_operation SET state=?,lease_id=?,lease_expires_at=?,estimated_cost_milliunits=?,image=?,output=?,write_receipt=?,result=?,updated_at=? WHERE singleton=1 AND state=? AND lease_id IS ? AND (lease_id IS NULL OR ?=1 OR lease_expires_at>?)`,
1019
+ input.state,
1020
+ input.leaseId,
1021
+ input.leaseExpiresAt,
1022
+ input.estimatedCostMilliunits,
1023
+ input.image === null ? null : JSON.stringify(input.image),
1024
+ input.output === null ? null : JSON.stringify(input.output),
1025
+ input.writeReceipt,
1026
+ input.result === null ? null : JSON.stringify(input.result),
1027
+ timestamp,
1028
+ input.expectedState,
1029
+ input.expectedLeaseId,
1030
+ input.allowExpired === true ? 1 : 0,
1031
+ timestamp,
1032
+ );
1033
+ const changed = z
1034
+ .object({ changes: z.number().int().nonnegative() })
1035
+ .parse(
1036
+ this.ctx.storage.sql.exec("SELECT changes() AS changes").toArray()[0],
1037
+ ).changes;
1038
+ if (changed !== 1) throw new MediaOperationError("lease_lost");
1039
+ const updated = this.readRecord();
1040
+ if (updated === null) throw new MediaOperationError("partial_init");
1041
+ return updated;
1042
+ }
1043
+
1044
+ private transition(
1045
+ leaseId: string,
1046
+ expectedState: MediaOperationState,
1047
+ state: MediaOperationState,
1048
+ values: Readonly<{
1049
+ /** Pinned host price or unmetered quote. */
1050
+ estimatedCostMilliunits: number | null;
1051
+ /** Retained or saved image size and encoding. */
1052
+ image: MediaImage | null;
1053
+ /** Exact retained provider output. */
1054
+ output: MediaOutput | null;
1055
+ writeReceipt: string | null;
1056
+ /** Settled generation receipt. */
1057
+ result: MediaOperationResult | null;
1058
+ }>,
1059
+ ): MediaOperationProjection {
1060
+ return this.ctx.storage.transactionSync(() => {
1061
+ const record = this.requireRecord();
1062
+ if (record.state !== expectedState || record.leaseId !== leaseId)
1063
+ throw new MediaOperationError("lease_lost");
1064
+ return this.project(
1065
+ this.update({
1066
+ expectedState,
1067
+ expectedLeaseId: leaseId,
1068
+ state,
1069
+ leaseId,
1070
+ leaseExpiresAt: Date.now() + this.leaseMs,
1071
+ ...values,
1072
+ }),
1073
+ );
1074
+ });
1075
+ }
1076
+
1077
+ /** Capture immutable host identity and input, replaying exact requests and refusing changed input. */
1078
+ public admit(
1079
+ actorUserId: string,
1080
+ coordinatesInput: MediaOperationCoordinates,
1081
+ requestId: string,
1082
+ input: MediaOperationRequest,
1083
+ ): MediaOperationDecision {
1084
+ const actor = text.safeParse(actorUserId);
1085
+ const coordinates =
1086
+ mediaOperationCoordinatesSchema.safeParse(coordinatesInput);
1087
+ const requestIdentifier = text.safeParse(requestId);
1088
+ if (!actor.success || !coordinates.success)
1089
+ throw new MediaOperationError("invalid_input");
1090
+ if (!requestIdentifier.success)
1091
+ throw new MediaOperationError("invalid_input");
1092
+ const requestFingerprint = fingerprint(input);
1093
+ return this.ctx.storage.transactionSync(() => {
1094
+ this.ensureSchema();
1095
+ const prior = this.readRecord();
1096
+ if (prior !== null) {
1097
+ if (
1098
+ prior.requestId !== requestIdentifier.data ||
1099
+ prior.actorUserId !== actor.data ||
1100
+ prior.namespace !== coordinates.data.namespace ||
1101
+ prior.owner !== coordinates.data.owner ||
1102
+ prior.fingerprint !== requestFingerprint
1103
+ )
1104
+ return {
1105
+ kind: "conflict",
1106
+ operation: this.project(prior),
1107
+ };
1108
+ return {
1109
+ kind: "replayed",
1110
+ operation: this.project(prior),
1111
+ };
1112
+ }
1113
+ const namespace = this.hooks.namespace?.() ?? null;
1114
+ if (namespace !== null && namespace !== coordinates.data.namespace)
1115
+ throw new MediaOperationError("conflict");
1116
+ const operationId = text.parse(this.ctx.id.name);
1117
+ const timestamp = Date.now();
1118
+ this.ctx.storage.sql.exec(
1119
+ `INSERT INTO hub_media_operation (singleton,operation_id,request_id,actor_user_id,team_id,installation_id,fingerprint,input,state,lease_id,lease_expires_at,estimated_cost_milliunits,image,output,write_receipt,result,created_at,updated_at) VALUES (1,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
1120
+ operationId,
1121
+ requestIdentifier.data,
1122
+ actor.data,
1123
+ coordinates.data.namespace,
1124
+ coordinates.data.owner,
1125
+ requestFingerprint,
1126
+ JSON.stringify(input),
1127
+ "admitted",
1128
+ null,
1129
+ null,
1130
+ null,
1131
+ null,
1132
+ null,
1133
+ null,
1134
+ null,
1135
+ timestamp,
1136
+ timestamp,
1137
+ );
1138
+ const admitted = this.requireRecord();
1139
+ return {
1140
+ kind: "admitted",
1141
+ operation: this.project(admitted),
1142
+ };
1143
+ });
1144
+ }
1145
+
1146
+ /** Claim a safe dispatch or save lease, recovering retained output without redispatching inference. */
1147
+ public async claim(): Promise<MediaOperationDecision> {
1148
+ const observed = this.requireRecord();
1149
+ // R2 may have committed the exact output before SQL recorded its receipt.
1150
+ // Inspect it only after generation's lease expires; never redispatch generation.
1151
+ const retained =
1152
+ observed.state === "generating" &&
1153
+ observed.leaseExpiresAt !== null &&
1154
+ observed.leaseExpiresAt <= Date.now()
1155
+ ? await this.env.APP_ARTIFACTS.head(
1156
+ `media-output/v1/${observed.operationId}`,
1157
+ )
1158
+ : undefined;
1159
+ return this.ctx.storage.transactionSync(() => {
1160
+ const record = this.requireRecord();
1161
+ if (record.state === "succeeded" || record.state === "interrupted")
1162
+ return {
1163
+ kind: record.state,
1164
+ operation: this.project(record),
1165
+ };
1166
+ if (record.state === "written")
1167
+ return {
1168
+ kind: "succeeded",
1169
+ operation: this.project(record),
1170
+ };
1171
+ // Another claimant or the original worker may have committed while R2 was read.
1172
+ if (
1173
+ record.state !== observed.state ||
1174
+ record.leaseId !== observed.leaseId
1175
+ )
1176
+ return {
1177
+ kind: "pending",
1178
+ operation: this.project(record),
1179
+ };
1180
+ const timestamp = Date.now();
1181
+ if (
1182
+ record.leaseId !== null &&
1183
+ (record.leaseExpiresAt === null || record.leaseExpiresAt > timestamp)
1184
+ )
1185
+ return {
1186
+ kind: "pending",
1187
+ operation: this.project(record),
1188
+ };
1189
+
1190
+ let output = record.output;
1191
+ if (record.state === "generating" && retained != null) {
1192
+ output = outputSchema.parse({
1193
+ key: retained.key,
1194
+ version: retained.version,
1195
+ bytes: retained.size,
1196
+ format: retainedFormatSchema.parse(
1197
+ retained.httpMetadata?.contentType,
1198
+ ),
1199
+ });
1200
+ }
1201
+ if (
1202
+ (record.state === "writing" || record.state === "generating") &&
1203
+ output !== null
1204
+ ) {
1205
+ const leaseId = ids.lease.generate();
1206
+ const claimed = this.update({
1207
+ expectedState: record.state,
1208
+ expectedLeaseId: record.leaseId,
1209
+ allowExpired: true,
1210
+ state: "writing",
1211
+ leaseId,
1212
+ leaseExpiresAt: timestamp + this.leaseMs,
1213
+ estimatedCostMilliunits: record.estimatedCostMilliunits,
1214
+ image: {
1215
+ bytes: output.bytes,
1216
+ format: output.format,
1217
+ },
1218
+ output,
1219
+ // A write may have landed before the worker died; the retry writes the same bytes.
1220
+ writeReceipt: record.writeReceipt,
1221
+ result: null,
1222
+ });
1223
+ return {
1224
+ kind: "claimed",
1225
+ operation: this.project(claimed),
1226
+ leaseId,
1227
+ };
1228
+ }
1229
+ if (record.state === "charging") {
1230
+ const leaseId = ids.lease.generate();
1231
+ const claimed = this.update({
1232
+ expectedState: record.state,
1233
+ expectedLeaseId: record.leaseId,
1234
+ allowExpired: true,
1235
+ state: "charging",
1236
+ leaseId,
1237
+ leaseExpiresAt: timestamp + this.leaseMs,
1238
+ estimatedCostMilliunits: record.estimatedCostMilliunits,
1239
+ image: record.image,
1240
+ output: record.output,
1241
+ writeReceipt: record.writeReceipt,
1242
+ result: null,
1243
+ });
1244
+ return {
1245
+ kind: "claimed",
1246
+ operation: this.project(claimed),
1247
+ leaseId,
1248
+ };
1249
+ }
1250
+ if (record.state === "admitted" || record.state === "estimating") {
1251
+ const leaseId = ids.lease.generate();
1252
+ const claimed = this.update({
1253
+ expectedState: record.state,
1254
+ expectedLeaseId: record.leaseId,
1255
+ allowExpired: true,
1256
+ state: "estimating",
1257
+ leaseId,
1258
+ leaseExpiresAt: timestamp + this.leaseMs,
1259
+ estimatedCostMilliunits: null,
1260
+ image: null,
1261
+ output: null,
1262
+ writeReceipt: null,
1263
+ result: null,
1264
+ });
1265
+ return {
1266
+ kind: "claimed",
1267
+ operation: this.project(claimed),
1268
+ leaseId,
1269
+ };
1270
+ }
1271
+ const interrupted = this.update({
1272
+ expectedState: record.state,
1273
+ expectedLeaseId: record.leaseId,
1274
+ allowExpired: true,
1275
+ state: "interrupted",
1276
+ leaseId: null,
1277
+ leaseExpiresAt: null,
1278
+ estimatedCostMilliunits: record.estimatedCostMilliunits,
1279
+ image: record.image,
1280
+ output: record.output,
1281
+ writeReceipt: record.writeReceipt,
1282
+ result: null,
1283
+ });
1284
+ return {
1285
+ kind: "interrupted",
1286
+ operation: this.project(interrupted),
1287
+ };
1288
+ });
1289
+ }
1290
+
1291
+ /** Pin the admitted price and begin the generation lease. */
1292
+ public recordEstimate(leaseId: string, costMilliunits: number) {
1293
+ if (!Number.isSafeInteger(costMilliunits) || costMilliunits < 0)
1294
+ throw new MediaOperationError("invalid_input");
1295
+ return this.transition(leaseId, "estimating", "generating", {
1296
+ estimatedCostMilliunits: costMilliunits,
1297
+ image: null,
1298
+ output: null,
1299
+ writeReceipt: null,
1300
+ result: null,
1301
+ });
1302
+ }
1303
+
1304
+ /**
1305
+ * Hand a long (video) generation to this owner's alarm. The caller's request
1306
+ * returns at once; the alarm dispatches the provider exactly once, retains
1307
+ * the output, and releases the lease so a later retry saves and charges it.
1308
+ */
1309
+ public async dispatchInBackground(
1310
+ leaseId: string,
1311
+ references: readonly MediaReferenceBytes[],
1312
+ audioReferences: readonly MediaAudioReferenceBytes[],
1313
+ ): Promise<MediaOperationProjection> {
1314
+ const record = this.requireRecord();
1315
+ if (record.state !== "generating" || record.leaseId !== leaseId)
1316
+ throw new MediaOperationError("lease_lost");
1317
+ await this.retaining(referenceKeys(record), async () => {
1318
+ for (const [index, reference] of references.entries()) {
1319
+ await this.env.APP_ARTIFACTS.put(
1320
+ referenceKey(record.operationId, index),
1321
+ reference.bytes,
1322
+ {
1323
+ customMetadata: {
1324
+ format: reference.format,
1325
+ width: String(reference.width),
1326
+ height: String(reference.height),
1327
+ },
1328
+ },
1329
+ );
1330
+ }
1331
+ for (const [index, clip] of audioReferences.entries()) {
1332
+ await this.env.APP_ARTIFACTS.put(
1333
+ audioReferenceKey(record.operationId, index),
1334
+ clip.bytes,
1335
+ {
1336
+ customMetadata: {
1337
+ mimeType: clip.mimeType,
1338
+ durationSeconds: String(clip.durationSeconds),
1339
+ },
1340
+ },
1341
+ );
1342
+ }
1343
+ });
1344
+ const timestamp = Date.now();
1345
+ this.ctx.storage.sql.exec(
1346
+ "UPDATE hub_media_operation SET background=1, lease_expires_at=?, updated_at=? WHERE singleton=1 AND state='generating' AND lease_id=?",
1347
+ timestamp + this.backgroundLeaseMs,
1348
+ timestamp,
1349
+ leaseId,
1350
+ );
1351
+ await this.ctx.storage.setAlarm(timestamp);
1352
+ return this.project(this.requireRecord());
1353
+ }
1354
+
1355
+ /** Run a background generation once; a retried alarm never redispatches. */
1356
+ public async alarm(): Promise<void> {
1357
+ if (this.erased) return;
1358
+ this.ensureSchema();
1359
+ const raw = this.ctx.storage.sql
1360
+ .exec("SELECT * FROM hub_media_operation WHERE singleton=1")
1361
+ .toArray()[0];
1362
+ if (raw === undefined) return;
1363
+ const parsed = operationRowSchema.safeParse(raw);
1364
+ if (!parsed.success)
1365
+ throw new MediaOperationError("partial_init", { cause: parsed.error });
1366
+ const row = parsed.data;
1367
+ if (row.state !== "generating" || row.background !== 1) return;
1368
+ const record = this.decode(row);
1369
+ const leaseId = record.leaseId;
1370
+ if (leaseId === null) return;
1371
+ if (row.dispatched_at !== null) {
1372
+ // A previous alarm dispatched and then died: never call the provider
1373
+ // again. No output was retained (the state is still generating), so end
1374
+ // the operation now rather than leaving every poll pending until the
1375
+ // lease lapses.
1376
+ reportCatchFailure(
1377
+ "media-operation-alarm-retry",
1378
+ new Error("Background media alarm died after dispatch"),
1379
+ );
1380
+ try {
1381
+ this.interruptGeneration(leaseId, {
1382
+ stage: "provider",
1383
+ safetyRefused: false,
1384
+ });
1385
+ } catch (cause) {
1386
+ reportCatchFailure("media-operation-interrupt", cause);
1387
+ /* A recovery claim already ended this lease. */
1388
+ }
1389
+ return;
1390
+ }
1391
+ this.ctx.storage.sql.exec(
1392
+ "UPDATE hub_media_operation SET dispatched_at=? WHERE singleton=1",
1393
+ Date.now(),
1394
+ );
1395
+ const provider = this.mediaProvider();
1396
+ let output: Readonly<{
1397
+ bytes: Uint8Array;
1398
+ format: string;
1399
+ }>;
1400
+ try {
1401
+ if (provider === undefined) throw new Error("Media host has no provider");
1402
+ const references = await Promise.all(
1403
+ (record.input.references ?? []).map(async (_reference, index) => {
1404
+ const object = await this.env.APP_ARTIFACTS.get(
1405
+ referenceKey(record.operationId, index),
1406
+ );
1407
+ if (object === null)
1408
+ throw new Error("Media reference is unavailable");
1409
+ const metadata = referenceMetadataSchema.parse(object.customMetadata);
1410
+ return {
1411
+ ...metadata,
1412
+ bytes: new Uint8Array(await object.arrayBuffer()),
1413
+ };
1414
+ }),
1415
+ );
1416
+ const audioReferences = await Promise.all(
1417
+ (record.input.audioReferences ?? []).map(async (_reference, index) => {
1418
+ const object = await this.env.APP_ARTIFACTS.get(
1419
+ audioReferenceKey(record.operationId, index),
1420
+ );
1421
+ if (object === null)
1422
+ throw new Error("Media audio reference is unavailable");
1423
+ const metadata = audioReferenceMetadataSchema.parse(
1424
+ object.customMetadata,
1425
+ );
1426
+ return {
1427
+ ...metadata,
1428
+ bytes: new Uint8Array(await object.arrayBuffer()),
1429
+ };
1430
+ }),
1431
+ );
1432
+ // The captured request includes destination authority; providers receive settings only.
1433
+ const settings = validateMediaGenerationSettings(
1434
+ mediaGenerationSettingsSchema.strip().parse(record.input),
1435
+ this.catalogue(),
1436
+ );
1437
+ const controller = new AbortController();
1438
+ let timer: ReturnType<typeof setTimeout> | undefined;
1439
+ const timedOut = new Promise<never>((_resolve, reject) => {
1440
+ timer = setTimeout(() => {
1441
+ const timeout = new MediaExecutionError("provider", {
1442
+ cause: new Error("Background media provider timed out"),
1443
+ provider: {
1444
+ category: "TimeoutError",
1445
+ code: null,
1446
+ reason: "timeout",
1447
+ },
1448
+ });
1449
+ controller.abort(timeout);
1450
+ reject(timeout);
1451
+ }, backgroundProviderTimeoutMs);
1452
+ });
1453
+ try {
1454
+ output = await Promise.race([
1455
+ provider(
1456
+ settings,
1457
+ references,
1458
+ controller.signal,
1459
+ record.input.outputFormat,
1460
+ audioReferences,
1461
+ ),
1462
+ timedOut,
1463
+ ]);
1464
+ } finally {
1465
+ clearTimeout(timer);
1466
+ }
1467
+ } catch (cause) {
1468
+ reportCatchFailure("media-operation-provider", cause);
1469
+ // Nothing was delivered; the next retry sees interrupted and releases
1470
+ // the billing hold at zero units.
1471
+ try {
1472
+ this.interruptGeneration(
1473
+ leaseId,
1474
+ cause instanceof MediaExecutionError &&
1475
+ (cause.stage === "provider" || cause.stage === "normalization")
1476
+ ? {
1477
+ stage: cause.stage,
1478
+ safetyRefused: cause instanceof MediaSafetyFilterRefusal,
1479
+ provider: cause.provider,
1480
+ }
1481
+ : undefined,
1482
+ );
1483
+ } catch (cause) {
1484
+ reportCatchFailure("media-operation-interrupt", cause);
1485
+ /* A recovery claim already ended this lease. */
1486
+ }
1487
+ return;
1488
+ }
1489
+ await this.recordGenerated(leaseId, output.bytes, output.format);
1490
+ await Promise.all([
1491
+ ...(record.input.references ?? []).map((_reference, index) =>
1492
+ this.env.APP_ARTIFACTS.delete(referenceKey(record.operationId, index)),
1493
+ ),
1494
+ ...(record.input.audioReferences ?? []).map((_reference, index) =>
1495
+ this.env.APP_ARTIFACTS.delete(
1496
+ audioReferenceKey(record.operationId, index),
1497
+ ),
1498
+ ),
1499
+ ]).catch((cause: unknown) => {
1500
+ reportCatchFailure("media-reference-cleanup", cause);
1501
+ });
1502
+ // Release the lease: the next retry of this request claims the save.
1503
+ this.ctx.storage.sql.exec(
1504
+ "UPDATE hub_media_operation SET lease_id=NULL, lease_expires_at=NULL WHERE singleton=1 AND state='writing' AND lease_id=?",
1505
+ leaseId,
1506
+ );
1507
+ }
1508
+
1509
+ /** An aborted in-flight provider call is terminal for this request ID. */
1510
+ public interruptGeneration(
1511
+ leaseId: string,
1512
+ failureInput?: NonNullable<MediaOperationProjection["providerFailure"]>,
1513
+ ): MediaOperationProjection {
1514
+ const failure = providerFailureSchema.optional().parse(failureInput);
1515
+ const record = this.requireRecord();
1516
+ if (record.state !== "generating" || record.leaseId !== leaseId)
1517
+ throw new MediaOperationError("lease_lost");
1518
+ return this.ctx.storage.transactionSync(() => {
1519
+ const interrupted = this.update({
1520
+ expectedState: "generating",
1521
+ expectedLeaseId: leaseId,
1522
+ state: "interrupted",
1523
+ leaseId: null,
1524
+ leaseExpiresAt: null,
1525
+ estimatedCostMilliunits: record.estimatedCostMilliunits,
1526
+ image: null,
1527
+ output: null,
1528
+ writeReceipt: null,
1529
+ result: null,
1530
+ });
1531
+ if (failure !== undefined)
1532
+ this.ctx.storage.sql.exec(
1533
+ "INSERT INTO hub_media_provider_failure(singleton,failure_json) VALUES(1,?)",
1534
+ JSON.stringify(failure),
1535
+ );
1536
+ return this.project(interrupted);
1537
+ });
1538
+ }
1539
+
1540
+ /** Retain immutable provider output before making the save state visible. */
1541
+ public async recordGenerated(
1542
+ leaseId: string,
1543
+ bytes: Uint8Array,
1544
+ formatInput: string,
1545
+ ): Promise<MediaRetentionResult> {
1546
+ const image = mediaImageSchema.safeParse({
1547
+ bytes: bytes.byteLength,
1548
+ format: formatInput,
1549
+ });
1550
+ if (!image.success) throw new MediaOperationError("invalid_input");
1551
+ const record = this.requireRecord();
1552
+ if (record.state !== "generating" || record.leaseId !== leaseId)
1553
+ throw new MediaOperationError("lease_lost");
1554
+ if (
1555
+ record.input.outputFormat !== undefined &&
1556
+ image.data.format !== record.input.outputFormat
1557
+ ) {
1558
+ this.ctx.storage.transactionSync(() => {
1559
+ this.update({
1560
+ expectedState: "generating",
1561
+ expectedLeaseId: leaseId,
1562
+ state: "interrupted",
1563
+ leaseId: null,
1564
+ leaseExpiresAt: null,
1565
+ estimatedCostMilliunits: record.estimatedCostMilliunits,
1566
+ image: null,
1567
+ output: null,
1568
+ writeReceipt: null,
1569
+ result: null,
1570
+ });
1571
+ this.ctx.storage.sql.exec(
1572
+ "INSERT INTO hub_media_spent_failure(singleton,code) VALUES(1,'output_format_mismatch')",
1573
+ );
1574
+ });
1575
+ return {
1576
+ kind: "refused",
1577
+ code: "output_format_mismatch",
1578
+ } as const;
1579
+ }
1580
+ const key = `media-output/v1/${record.operationId}`;
1581
+ const stored = await this.retaining([key], () =>
1582
+ this.env.APP_ARTIFACTS.put(key, bytes, {
1583
+ onlyIf: { etagDoesNotMatch: "*" },
1584
+ httpMetadata: { contentType: outputMime(image.data.format) },
1585
+ }),
1586
+ );
1587
+ if (stored === null) throw new MediaOperationError("conflict");
1588
+ return this.transition(leaseId, "generating", "writing", {
1589
+ estimatedCostMilliunits: record.estimatedCostMilliunits,
1590
+ image: image.data,
1591
+ output: {
1592
+ key,
1593
+ version: stored.version,
1594
+ bytes: image.data.bytes,
1595
+ format: image.data.format,
1596
+ },
1597
+ writeReceipt: null,
1598
+ result: null,
1599
+ });
1600
+ }
1601
+
1602
+ /** Read exact retained bytes under the current save lease. */
1603
+ public async readGenerated(leaseId: string): Promise<Uint8Array> {
1604
+ const record = this.requireRecord();
1605
+ if (
1606
+ record.state !== "writing" ||
1607
+ record.leaseId !== leaseId ||
1608
+ record.output === null
1609
+ )
1610
+ throw new MediaOperationError("lease_lost");
1611
+ const object = await this.env.APP_ARTIFACTS.get(record.output.key);
1612
+ if (
1613
+ object?.version !== record.output.version ||
1614
+ object.size !== record.output.bytes
1615
+ )
1616
+ throw new MediaOperationError("partial_init");
1617
+ return new Uint8Array(await object.arrayBuffer());
1618
+ }
1619
+
1620
+ /** A fixed-path exact-byte save is safe to retry without repeating generation. */
1621
+ public releaseWrite(leaseId: string): MediaOperationProjection {
1622
+ const record = this.requireRecord();
1623
+ if (
1624
+ record.state !== "writing" ||
1625
+ record.leaseId !== leaseId ||
1626
+ record.output === null
1627
+ )
1628
+ throw new MediaOperationError("lease_lost");
1629
+ return this.ctx.storage.transactionSync(() =>
1630
+ this.project(
1631
+ this.update({
1632
+ expectedState: "writing",
1633
+ expectedLeaseId: leaseId,
1634
+ state: "writing",
1635
+ leaseId: null,
1636
+ leaseExpiresAt: null,
1637
+ estimatedCostMilliunits: record.estimatedCostMilliunits,
1638
+ image: record.image,
1639
+ output: record.output,
1640
+ writeReceipt: record.writeReceipt,
1641
+ result: null,
1642
+ }),
1643
+ ),
1644
+ );
1645
+ }
1646
+
1647
+ /**
1648
+ * Record the digest of the exact bytes about to be written to the
1649
+ * destination, before writing them. An erasure then knows which file this
1650
+ * operation owns, even if the process dies between the write and its
1651
+ * record, and refuses the write once erased.
1652
+ */
1653
+ public recordWriteIntent(
1654
+ leaseId: string,
1655
+ sha256: string,
1656
+ ): MediaOperationProjection {
1657
+ const receipt = `sha256:${sha256}`;
1658
+ if (!writeReceiptSchema.safeParse(receipt).success)
1659
+ throw new MediaOperationError("invalid_input");
1660
+ const record = this.requireRecord();
1661
+ if (record.state !== "writing" || record.leaseId !== leaseId)
1662
+ throw new MediaOperationError("lease_lost");
1663
+ return this.ctx.storage.transactionSync(() =>
1664
+ this.project(
1665
+ this.update({
1666
+ expectedState: "writing",
1667
+ expectedLeaseId: leaseId,
1668
+ state: "writing",
1669
+ leaseId,
1670
+ leaseExpiresAt: record.leaseExpiresAt,
1671
+ estimatedCostMilliunits: record.estimatedCostMilliunits,
1672
+ image: record.image,
1673
+ output: record.output,
1674
+ writeReceipt: receipt,
1675
+ result: null,
1676
+ }),
1677
+ ),
1678
+ );
1679
+ }
1680
+
1681
+ // The saved file may contain embedded provenance. Persist its actual size at
1682
+ // write acknowledgement; output keeps the original provider bytes for retry.
1683
+ /** Record a destination write and move to idempotent settlement. */
1684
+ public recordWritten(leaseId: string, receipt: string, written: MediaImage) {
1685
+ const image = mediaImageSchema.safeParse(written);
1686
+ if (!image.success || !text.safeParse(receipt).success)
1687
+ throw new MediaOperationError("invalid_input");
1688
+ const record = this.requireRecord();
1689
+ if (record.state !== "writing" || record.leaseId !== leaseId)
1690
+ throw new MediaOperationError("lease_lost");
1691
+ if (image.data.format !== record.image?.format)
1692
+ throw new MediaOperationError("conflict");
1693
+ return this.transition(leaseId, "writing", "charging", {
1694
+ estimatedCostMilliunits: record.estimatedCostMilliunits,
1695
+ image: image.data,
1696
+ output: record.output,
1697
+ writeReceipt: receipt,
1698
+ result: null,
1699
+ });
1700
+ }
1701
+
1702
+ /**
1703
+ * Persist a completed Computer write without claiming billing success.
1704
+ * A lost receipt may replay the exact retained bytes to the captured path;
1705
+ * it never repeats provider generation.
1706
+ */
1707
+ public recordWrittenWithoutSettlement(
1708
+ leaseId: string,
1709
+ receipt: string,
1710
+ written: MediaImage,
1711
+ ) {
1712
+ const image = mediaImageSchema.safeParse(written);
1713
+ if (!image.success || !text.safeParse(receipt).success)
1714
+ throw new MediaOperationError("invalid_input");
1715
+ const record = this.requireRecord();
1716
+ if (record.state !== "writing" || record.leaseId !== leaseId)
1717
+ throw new MediaOperationError("lease_lost");
1718
+ if (image.data.format !== record.image?.format)
1719
+ throw new MediaOperationError("conflict");
1720
+ return this.ctx.storage.transactionSync(() =>
1721
+ this.project(
1722
+ this.update({
1723
+ expectedState: "writing",
1724
+ expectedLeaseId: leaseId,
1725
+ state: "written",
1726
+ leaseId: null,
1727
+ leaseExpiresAt: null,
1728
+ estimatedCostMilliunits: record.estimatedCostMilliunits,
1729
+ image: image.data,
1730
+ output: record.output,
1731
+ writeReceipt: receipt,
1732
+ result: null,
1733
+ }),
1734
+ ),
1735
+ );
1736
+ }
1737
+
1738
+ /** Commit the settled receipt after verifying the saved output and admitted price. */
1739
+ public recordSucceeded(leaseId: string, resultInput: MediaOperationResult) {
1740
+ const result = mediaOperationResultSchema.safeParse(resultInput);
1741
+ if (!result.success) throw new MediaOperationError("invalid_input");
1742
+ const record = this.requireRecord();
1743
+ if (
1744
+ record.state !== "charging" ||
1745
+ record.leaseId !== leaseId ||
1746
+ record.estimatedCostMilliunits === null ||
1747
+ record.image === null ||
1748
+ record.writeReceipt === null ||
1749
+ result.data.generationId !== record.operationId ||
1750
+ result.data.bytes !== record.image.bytes ||
1751
+ result.data.format !== record.image.format ||
1752
+ result.data.costMilliunits !== record.estimatedCostMilliunits
1753
+ )
1754
+ throw new MediaOperationError("conflict");
1755
+ return this.transition(leaseId, "charging", "succeeded", {
1756
+ estimatedCostMilliunits: record.estimatedCostMilliunits,
1757
+ image: record.image,
1758
+ output: record.output,
1759
+ writeReceipt: record.writeReceipt,
1760
+ result: result.data,
1761
+ });
1762
+ }
1763
+
1764
+ /** Release preparation or refused admission so the same request can retry. */
1765
+ public releaseEstimate(leaseId: string): MediaOperationProjection {
1766
+ const record = this.requireRecord();
1767
+ if (record.state !== "estimating" || record.leaseId !== leaseId)
1768
+ throw new MediaOperationError("lease_lost");
1769
+ return this.ctx.storage.transactionSync(() =>
1770
+ this.project(
1771
+ this.update({
1772
+ expectedState: "estimating",
1773
+ expectedLeaseId: leaseId,
1774
+ state: "admitted",
1775
+ leaseId: null,
1776
+ leaseExpiresAt: null,
1777
+ estimatedCostMilliunits: null,
1778
+ image: null,
1779
+ output: null,
1780
+ writeReceipt: null,
1781
+ result: null,
1782
+ }),
1783
+ ),
1784
+ );
1785
+ }
1786
+ }