@fungi.computer/darkroom 0.10.0 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -142,9 +142,11 @@ validates every request against the active provider's catalogue, so `fal-ai/...`
142
142
  ids are accepted by your provider and refused by the gateway's.
143
143
 
144
144
  Each entry carries the per-model bounds the validator enforces: prompt length,
145
- dimensions or exact sizes, steps, reference counts, and for video the durations,
146
- resolution/aspect formats and per-second prices. Mark a video model's
147
- `video.provider` as `"host"`: your provider owns that model's wire grammar.
145
+ dimensions or exact sizes, steps, prompt `guidance` (bounds and default, or
146
+ `null` when the model takes none; a caller's explicit value overrides the
147
+ default), reference counts, and for video the durations, resolution/aspect
148
+ formats and per-second prices. Mark a video model's `video.provider` as
149
+ `"host"`: your provider owns that model's wire grammar.
148
150
 
149
151
  ```ts
150
152
  import {
@@ -176,6 +178,7 @@ export const falCatalogue = parseMediaCatalogue([
176
178
  steps: "fixed",
177
179
  maxSteps: null,
178
180
  defaultSteps: null,
181
+ guidance: null,
179
182
  referenceField: "image_url",
180
183
  maxReferences: 1,
181
184
  referenceDimension: null,
@@ -351,6 +354,14 @@ add an `AI` binding to your host. `createImagesReferenceFitter` prepares bounded
351
354
  reference images through an Images binding, using the selected catalog model
352
355
  passed to the fitter. Your host authorizes each reference read.
353
356
 
357
+ Saved PNG, JPEG and WebP images carry the AI marker, print ID, model and
358
+ creation time in XMP. The prompt is private by default: it is embedded as
359
+ `fungi:prompt` only when the host opts in per generation, with
360
+ `embedPrompt: true` on `generateMedia`'s request, or `embedPrompt: true` on the
361
+ `createMediaService` host for its `/generate` route. Omit it to keep prompts out
362
+ of generated files. `embedProvenance` takes `prompt: string | null` in its
363
+ facts; `null` leaves it out.
364
+
354
365
  `stripPrivateProvenance(bytes)` from `provenance` removes prompt and lineage
355
366
  metadata while preserving the AI marker, print ID and image encoding. It returns
356
367
  bytes, MIME type and filename extension. The public XMP format uses
@@ -405,6 +416,43 @@ validated settings. Output is saved with its content type, and a retry with the
405
416
  same request ID reuses the saved output instead of calling the provider again. A
406
417
  runnable Worker is in [`examples/standalone`](examples/standalone).
407
418
 
419
+ ## Recover or erase retained results
420
+
421
+ A generation keeps three things by operation (request) id: the exact provider
422
+ bytes in `APP_ARTIFACTS` (`media-output/v1/<operation>`), any background
423
+ reference copies, and the file it wrote to your destination path. From
424
+ `@fungi.computer/darkroom/server`, all scoped to `host.scope.namespace` (another
425
+ namespace is refused):
426
+
427
+ - `retainedMedia(host, requestId)` lists them: the state, the destination path
428
+ and the retained output's size, format and content type. It finds output a
429
+ crash left unrecorded (written to R2, never noted in SQL). It returns null
430
+ once erased.
431
+ - `readRetainedMedia(host, requestId)` returns those exact provider bytes and
432
+ their format, before any provenance, so you can re-save a result whose
433
+ destination write was lost.
434
+ - `eraseMediaOperation(host, requestId)` erases all of it, even mid-generation.
435
+ The operation is marked erased first, durably, and the marker is never
436
+ removed: an attempt still running, or a lease recovered later, can no longer
437
+ write or transition, a restart cannot resurrect it, and output that lands
438
+ after the mark is deleted. Before each destination write the operation records
439
+ the SHA-256 of the bytes it is about to write; erasure deletes the destination
440
+ file only while it still holds those bytes (`destinationFile` reports
441
+ `"removed"`, `"absent"`, `"not-ours"` for a path reused for something else, or
442
+ `"kept"`). A generation erased before it finished has its billing hold settled
443
+ at zero units (`metering.settle`, idempotent). It returns `clear`, and a put
444
+ still in flight or a failed late delete keeps `clear` false: call it again
445
+ until `clear` is true.
446
+
447
+ Your destination supplies `remove(path, { sha256 })`, required. Use
448
+ `removeMediaIfWritten` to compare and delete, or return `"kept"` when the
449
+ destination cannot delete files. `createR2MediaDestination` implements it.
450
+ `MediaOperationDO` exposes `retained(namespace, requestId)`,
451
+ `readRetained(namespace, requestId)` and `erase(namespace, requestId, policy)`.
452
+ `policy` is `"abort-active"` (default) or `"refuse-active"`, which refuses a
453
+ running operation atomically with the erase for a host that waits for
454
+ inactivity. `preflightErasure` remains an optional read-only check.
455
+
408
456
  ## Limits
409
457
 
410
458
  References are bounded to four files and 8 MiB per image. Image-model references
@@ -15,6 +15,7 @@ export declare const mediaModelPriceEstimateSchema: z.ZodObject<{
15
15
  width: z.ZodOptional<z.ZodNumber>;
16
16
  height: z.ZodOptional<z.ZodNumber>;
17
17
  steps: z.ZodOptional<z.ZodNumber>;
18
+ guidance: z.ZodOptional<z.ZodNumber>;
18
19
  durationSeconds: z.ZodOptional<z.ZodNumber>;
19
20
  targetMegapixels: z.ZodOptional<z.ZodNumber>;
20
21
  voiceId: z.ZodOptional<z.ZodString>;
@@ -91,6 +92,11 @@ export declare const mediaCatalogModelSchema: z.ZodReadonly<z.ZodObject<{
91
92
  }>;
92
93
  maxSteps: z.ZodNullable<z.ZodNumber>;
93
94
  defaultSteps: z.ZodNullable<z.ZodNumber>;
95
+ guidance: z.ZodDefault<z.ZodNullable<z.ZodReadonly<z.ZodObject<{
96
+ min: z.ZodNumber;
97
+ max: z.ZodNumber;
98
+ default: z.ZodNumber;
99
+ }, z.core.$strict>>>>;
94
100
  referenceField: z.ZodNullable<z.ZodString>;
95
101
  maxReferences: z.ZodNumber;
96
102
  referenceDimension: z.ZodNullable<z.ZodNumber>;
@@ -237,6 +243,7 @@ export declare const mediaCatalogModelSchema: z.ZodReadonly<z.ZodObject<{
237
243
  width: z.ZodOptional<z.ZodNumber>;
238
244
  height: z.ZodOptional<z.ZodNumber>;
239
245
  steps: z.ZodOptional<z.ZodNumber>;
246
+ guidance: z.ZodOptional<z.ZodNumber>;
240
247
  durationSeconds: z.ZodOptional<z.ZodNumber>;
241
248
  targetMegapixels: z.ZodOptional<z.ZodNumber>;
242
249
  voiceId: z.ZodOptional<z.ZodString>;
@@ -314,6 +321,11 @@ export declare const mediaModelsSchema: z.ZodLazy<z.ZodArray<z.ZodReadonly<z.Zod
314
321
  }>;
315
322
  maxSteps: z.ZodNullable<z.ZodNumber>;
316
323
  defaultSteps: z.ZodNullable<z.ZodNumber>;
324
+ guidance: z.ZodDefault<z.ZodNullable<z.ZodReadonly<z.ZodObject<{
325
+ min: z.ZodNumber;
326
+ max: z.ZodNumber;
327
+ default: z.ZodNumber;
328
+ }, z.core.$strict>>>>;
317
329
  referenceField: z.ZodNullable<z.ZodString>;
318
330
  maxReferences: z.ZodNumber;
319
331
  referenceDimension: z.ZodNullable<z.ZodNumber>;
@@ -460,6 +472,7 @@ export declare const mediaModelsSchema: z.ZodLazy<z.ZodArray<z.ZodReadonly<z.Zod
460
472
  width: z.ZodOptional<z.ZodNumber>;
461
473
  height: z.ZodOptional<z.ZodNumber>;
462
474
  steps: z.ZodOptional<z.ZodNumber>;
475
+ guidance: z.ZodOptional<z.ZodNumber>;
463
476
  durationSeconds: z.ZodOptional<z.ZodNumber>;
464
477
  targetMegapixels: z.ZodOptional<z.ZodNumber>;
465
478
  voiceId: z.ZodOptional<z.ZodString>;
@@ -700,6 +713,11 @@ export declare const appMediaModelsOutcomeSchema: z.ZodUnion<readonly [z.ZodLazy
700
713
  }>;
701
714
  maxSteps: z.ZodNullable<z.ZodNumber>;
702
715
  defaultSteps: z.ZodNullable<z.ZodNumber>;
716
+ guidance: z.ZodDefault<z.ZodNullable<z.ZodReadonly<z.ZodObject<{
717
+ min: z.ZodNumber;
718
+ max: z.ZodNumber;
719
+ default: z.ZodNumber;
720
+ }, z.core.$strict>>>>;
703
721
  referenceField: z.ZodNullable<z.ZodString>;
704
722
  maxReferences: z.ZodNumber;
705
723
  referenceDimension: z.ZodNullable<z.ZodNumber>;
@@ -846,6 +864,7 @@ export declare const appMediaModelsOutcomeSchema: z.ZodUnion<readonly [z.ZodLazy
846
864
  width: z.ZodOptional<z.ZodNumber>;
847
865
  height: z.ZodOptional<z.ZodNumber>;
848
866
  steps: z.ZodOptional<z.ZodNumber>;
867
+ guidance: z.ZodOptional<z.ZodNumber>;
849
868
  durationSeconds: z.ZodOptional<z.ZodNumber>;
850
869
  targetMegapixels: z.ZodOptional<z.ZodNumber>;
851
870
  voiceId: z.ZodOptional<z.ZodString>;
@@ -12,6 +12,7 @@ export declare function estimateMediaModel(model: MediaModel): {
12
12
  width?: number;
13
13
  height?: number;
14
14
  steps?: number;
15
+ guidance?: number;
15
16
  durationSeconds?: number;
16
17
  targetMegapixels?: number;
17
18
  voiceId?: string;
@@ -15,6 +15,8 @@ export type MediaR2Bucket = {
15
15
  contentType: string;
16
16
  }>;
17
17
  }>): Promise<object | null>;
18
+ /** Delete one object; absent keys are not an error. */
19
+ delete(key: string): Promise<void>;
18
20
  };
19
21
  /** Host-owned R2 destination configuration. */
20
22
  export type R2MediaDestinationOptions = Readonly<{
@@ -2,6 +2,7 @@ import { MediaSettingsError } from "../model-catalog.js";
2
2
  import { mediaContentType } from "../media-content-type.js";
3
3
  import { readHostReference, referenceFilename, } from "../reference-read.js";
4
4
  import { mediaPathSchema } from "../media-path.js";
5
+ import { removeMediaIfWritten } from "../media-written.js";
5
6
  /**
6
7
  * A Media destination over one R2 bucket: object keys are the paths, validated
7
8
  * with Darkroom's path schema. Never accepts URLs.
@@ -37,6 +38,18 @@ export function createR2MediaDestination(options) {
37
38
  httpMetadata: { contentType: mediaContentType(bytes) },
38
39
  });
39
40
  },
41
+ remove: async (key, written) => {
42
+ await authorize(key);
43
+ return removeMediaIfWritten({
44
+ read: async () => {
45
+ const object = await bucket.get(key);
46
+ return object === null
47
+ ? null
48
+ : new Uint8Array(await object.arrayBuffer());
49
+ },
50
+ delete: () => bucket.delete(key),
51
+ }, written.sha256);
52
+ },
40
53
  readReference: async (reference, model) => ({
41
54
  ...(await fit(await read("image", reference), model)),
42
55
  filename: referenceFilename(reference),
@@ -4,5 +4,5 @@ export type { MediaAiResult } from "./index.js";
4
4
  export { createImagesReferenceFitter, createImagesViewFitter, type MediaImagePort, } from "./cloudflare/reference-images.js";
5
5
  export { createR2MediaDestination, type MediaR2Bucket, type R2MediaDestination, type R2MediaDestinationOptions, } from "./cloudflare/r2-destination.js";
6
6
  export { MediaOperationOwner } from "./media-operation-owner.js";
7
- export type { MediaShareSource } from "./media-operation-owner.js";
8
- export type { MediaOperationContext, MediaOperationStorage, MediaOperationBucket, MediaOperationObject, } from "./media-operation-storage.js";
7
+ export type { MediaErasure, MediaRetained, MediaRetainedBytes, MediaErasePolicy, MediaShareSource, } from "./media-operation-owner.js";
8
+ export type { MediaOperationContext, MediaOperationStorage, MediaErasureMarker, MediaOperationBucket, MediaOperationObject, } from "./media-operation-storage.js";
package/dist/index.d.ts CHANGED
@@ -46,6 +46,8 @@ export type MediaGenerationSettings = Readonly<{
46
46
  height?: number;
47
47
  /** Model-specific inference steps. */
48
48
  steps?: number;
49
+ /** Prompt guidance for models that take it; the catalog default when omitted. */
50
+ guidance?: number;
49
51
  /** Video and music models only: output length in whole seconds. */
50
52
  durationSeconds?: number;
51
53
  /** Upscale only: the output size in megapixels. */
@@ -109,6 +111,7 @@ export declare const mediaGenerationSettingsSchema: z.ZodObject<{
109
111
  width: z.ZodOptional<z.ZodNumber>;
110
112
  height: z.ZodOptional<z.ZodNumber>;
111
113
  steps: z.ZodOptional<z.ZodNumber>;
114
+ guidance: z.ZodOptional<z.ZodNumber>;
112
115
  durationSeconds: z.ZodOptional<z.ZodNumber>;
113
116
  targetMegapixels: z.ZodOptional<z.ZodNumber>;
114
117
  voiceId: z.ZodOptional<z.ZodString>;
@@ -152,6 +155,7 @@ export declare const mediaGenerationSelectionSchema: z.ZodObject<{
152
155
  width: z.ZodOptional<z.ZodNumber>;
153
156
  height: z.ZodOptional<z.ZodNumber>;
154
157
  steps: z.ZodOptional<z.ZodNumber>;
158
+ guidance: z.ZodOptional<z.ZodNumber>;
155
159
  durationSeconds: z.ZodOptional<z.ZodNumber>;
156
160
  targetMegapixels: z.ZodOptional<z.ZodNumber>;
157
161
  voiceId: z.ZodOptional<z.ZodString>;
@@ -369,6 +373,8 @@ export type MediaJsonBody = Readonly<{
369
373
  steps?: number;
370
374
  /** Steps for models using the num_steps field. */
371
375
  num_steps?: number;
376
+ /** Prompt guidance for models that take it. */
377
+ guidance?: number;
372
378
  }>;
373
379
  /** A model-specific JSON body or multipart form ready for transport. */
374
380
  export type MediaProviderPayload = Readonly<{
package/dist/index.js CHANGED
@@ -60,6 +60,8 @@ export const mediaGenerationSettingsSchema = z
60
60
  height: z.number().int().min(1).max(5_040).optional(),
61
61
  /** Model-specific inference step count. */
62
62
  steps: z.number().int().optional(),
63
+ /** Prompt guidance; models without a catalog guidance range refuse it. */
64
+ guidance: z.number().optional(),
63
65
  /** Requested video or music length in whole seconds. */
64
66
  durationSeconds: z.number().int().optional(),
65
67
  /** Upscale only: the output size in megapixels, one of the model's offered sizes. */
@@ -174,6 +176,7 @@ function normalizeGenerationSettings(input, normalize, catalogue) {
174
176
  if (input.width !== undefined ||
175
177
  input.height !== undefined ||
176
178
  input.steps !== undefined ||
179
+ input.guidance !== undefined ||
177
180
  input.resolution !== undefined ||
178
181
  input.aspectRatio !== undefined ||
179
182
  input.generateAudio !== undefined ||
@@ -229,6 +232,15 @@ function normalizeGenerationSettings(input, normalize, catalogue) {
229
232
  model.input.defaultSteps !== null) {
230
233
  steps = model.input.defaultSteps;
231
234
  }
235
+ let guidance;
236
+ const range = model.input.guidance;
237
+ if (input.guidance !== undefined && range === null)
238
+ throw new MediaSettingsError(`${model.id} does not take guidance`);
239
+ if (range !== null) {
240
+ guidance = input.guidance ?? range.default;
241
+ if (guidance < range.min || guidance > range.max)
242
+ throw new MediaSettingsError(`${model.id} accepts guidance from ${String(range.min)} through ${String(range.max)}`);
243
+ }
232
244
  let references;
233
245
  if (input.references !== undefined) {
234
246
  if (input.references.length > model.input.maxReferences)
@@ -243,6 +255,8 @@ function normalizeGenerationSettings(input, normalize, catalogue) {
243
255
  };
244
256
  if (steps !== undefined)
245
257
  normalized.steps = steps;
258
+ if (guidance !== undefined)
259
+ normalized.guidance = guidance;
246
260
  if (durationSeconds !== undefined)
247
261
  normalized.durationSeconds = durationSeconds;
248
262
  if (model.video !== null) {
@@ -411,6 +425,7 @@ function normalizeTransformSettings(model, transform, prompt, input, normalize)
411
425
  if (input.width !== undefined ||
412
426
  input.height !== undefined ||
413
427
  input.steps !== undefined ||
428
+ input.guidance !== undefined ||
414
429
  input.durationSeconds !== undefined ||
415
430
  input.resolution !== undefined ||
416
431
  input.aspectRatio !== undefined ||
@@ -524,6 +539,8 @@ export const buildProviderInput = (settings, references = []) => {
524
539
  body.steps = settings.steps;
525
540
  if (settings.steps !== undefined && model.input.steps === "num_steps")
526
541
  body.num_steps = settings.steps;
542
+ if (settings.guidance !== undefined && model.input.guidance !== null)
543
+ body.guidance = settings.guidance;
527
544
  return Object.freeze({
528
545
  transport: "json",
529
546
  body: Object.freeze(body),
@@ -7,6 +7,7 @@ export declare const mediaImageBindingInputSchema: z.ZodObject<{
7
7
  requestId: z.ZodLazy<z.ZodString>;
8
8
  libraryPath: z.ZodString & z.ZodType<string, string, z.core.$ZodTypeInternals<string, string>>;
9
9
  settings: z.ZodObject<{
10
+ guidance: z.ZodOptional<z.ZodNumber>;
10
11
  resolution: z.ZodOptional<z.ZodEnum<{
11
12
  readonly p480: "480p";
12
13
  readonly p720: "720p";
@@ -115,6 +116,7 @@ export declare const mediaBindingGenerationSchema: z.ZodDiscriminatedUnion<[z.Zo
115
116
  requestId: z.ZodLazy<z.ZodString>;
116
117
  libraryPath: z.ZodString & z.ZodType<string, string, z.core.$ZodTypeInternals<string, string>>;
117
118
  settings: z.ZodObject<{
119
+ guidance: z.ZodOptional<z.ZodNumber>;
118
120
  resolution: z.ZodOptional<z.ZodEnum<{
119
121
  readonly p480: "480p";
120
122
  readonly p720: "720p";
@@ -226,6 +228,7 @@ export declare const mediaBindingCallSchema: z.ZodDiscriminatedUnion<[z.ZodObjec
226
228
  requestId: z.ZodLazy<z.ZodString>;
227
229
  libraryPath: z.ZodString & z.ZodType<string, string, z.core.$ZodTypeInternals<string, string>>;
228
230
  settings: z.ZodObject<{
231
+ guidance: z.ZodOptional<z.ZodNumber>;
229
232
  resolution: z.ZodOptional<z.ZodEnum<{
230
233
  readonly p480: "480p";
231
234
  readonly p720: "720p";
@@ -30,6 +30,7 @@ export function runMediaGeneration(host, request, signal) {
30
30
  catch: (cause) => new MediaExecutionError("generation-authorization", { cause }),
31
31
  });
32
32
  const execution = {
33
+ embedPrompt: request.embedPrompt,
33
34
  operation: host.operations.getByName(`media:${request.requestId}`),
34
35
  actorUserId: host.scope.actorId,
35
36
  coordinates: {
@@ -48,6 +49,7 @@ export function runMediaGeneration(host, request, signal) {
48
49
  destination: {
49
50
  authorize: () => host.destination.authorize(path),
50
51
  write: (bytes) => host.destination.write(path, bytes),
52
+ remove: (sha256) => host.destination.remove(path, { sha256 }),
51
53
  },
52
54
  generation: {
53
55
  prepare: async () => {
@@ -1,5 +1,6 @@
1
1
  import * as z from "zod";
2
2
  import type { MediaOperationOwner, MediaOperationCoordinates, MediaOperationRequest } from "./media-operation-owner.js";
3
+ import type { MediaRemoval } from "./media-written.js";
3
4
  import type { MediaUnits } from "./gateway-models.js";
4
5
  import type { MediaAudioReferenceBytes, MediaCatalogue, MediaReferenceBytes } from "./index.js";
5
6
  /**
@@ -38,7 +39,7 @@ export type MediaMetering = Readonly<{
38
39
  }>;
39
40
  /** Local or RPC methods consumed by a replay-safe generation. */
40
41
  export type MediaOperation = {
41
- [Method in "admit" | "claim" | "dispatchInBackground" | "interruptGeneration" | "readGenerated" | "recordEstimate" | "recordGenerated" | "recordSucceeded" | "recordWritten" | "recordWrittenWithoutSettlement" | "releaseEstimate" | "releaseWrite"]: (...input: Parameters<MediaOperationOwner[Method]>) => ReturnType<MediaOperationOwner[Method]> | Promise<Awaited<ReturnType<MediaOperationOwner[Method]>>>;
42
+ [Method in "admit" | "claim" | "dispatchInBackground" | "interruptGeneration" | "readGenerated" | "recordEstimate" | "recordGenerated" | "recordSucceeded" | "recordWritten" | "recordWrittenWithoutSettlement" | "releaseEstimate" | "releaseWrite" | "recordWriteIntent" | "retained" | "readRetained" | "erase"]: (...input: Parameters<MediaOperationOwner[Method]>) => ReturnType<MediaOperationOwner[Method]> | Promise<Awaited<ReturnType<MediaOperationOwner[Method]>>>;
42
43
  };
43
44
  /** Admitted identity, durable operation and host effects for one generation. */
44
45
  export type MediaExecution = Readonly<{
@@ -58,12 +59,23 @@ export type MediaExecution = Readonly<{
58
59
  metering: MediaMetering | "unmetered";
59
60
  /** Optional cancellation signal. */
60
61
  signal?: AbortSignal;
62
+ /**
63
+ * Publish the prompt in the image's XMP as `fungi:prompt`. Omitted or false
64
+ * keeps the prompt out of the file: a host must opt in per generation.
65
+ */
66
+ embedPrompt?: boolean | undefined;
61
67
  /** Host-owned destination authorization and writing. */
62
68
  destination: Readonly<{
63
69
  /** Check host permission before writing or dispatching generation. */
64
70
  authorize: () => Promise<void>;
65
71
  /** Save exact generated bytes to the admitted destination. */
66
72
  write: (bytes: Uint8Array) => Promise<void>;
73
+ /**
74
+ * Delete the file this generation wrote, only while it still holds the
75
+ * bytes with this SHA-256. Called when the operation was erased while the
76
+ * write was in flight, so the saved file does not outlive it.
77
+ */
78
+ remove: (sha256: string) => Promise<MediaRemoval>;
67
79
  }>;
68
80
  /** Reference preparation and provider dispatch effects. */
69
81
  generation: Readonly<{
@@ -35,8 +35,14 @@ export declare class MediaOperationDO extends DurableObject<MediaOperationCloudf
35
35
  readShare(...input: Parameters<MediaOperationOwner["readShare"]>): ReturnType<MediaOperationOwner["readShare"]>;
36
36
  /** {@inheritDoc MediaOperationOwner.preflightErasure} */
37
37
  preflightErasure(...input: Parameters<MediaOperationOwner["preflightErasure"]>): ReturnType<MediaOperationOwner["preflightErasure"]>;
38
+ /** {@inheritDoc MediaOperationOwner.recordWriteIntent} */
39
+ recordWriteIntent(...input: Parameters<MediaOperationOwner["recordWriteIntent"]>): ReturnType<MediaOperationOwner["recordWriteIntent"]>;
38
40
  /** {@inheritDoc MediaOperationOwner.erase} */
39
41
  erase(...input: Parameters<MediaOperationOwner["erase"]>): ReturnType<MediaOperationOwner["erase"]>;
42
+ /** {@inheritDoc MediaOperationOwner.retained} */
43
+ retained(...input: Parameters<MediaOperationOwner["retained"]>): ReturnType<MediaOperationOwner["retained"]>;
44
+ /** {@inheritDoc MediaOperationOwner.readRetained} */
45
+ readRetained(...input: Parameters<MediaOperationOwner["readRetained"]>): ReturnType<MediaOperationOwner["readRetained"]>;
40
46
  /** {@inheritDoc MediaOperationOwner.readErasure} */
41
47
  readErasure(...input: Parameters<MediaOperationOwner["readErasure"]>): ReturnType<MediaOperationOwner["readErasure"]>;
42
48
  /** {@inheritDoc MediaOperationOwner.admit} */
@@ -1,8 +1,14 @@
1
1
  import { DurableObject } from "cloudflare:workers";
2
+ import { z } from "zod";
2
3
  import { createWorkersAiMediaProvider, } from "./cloudflare/provider.js";
3
4
  import { mediaModels, } from "./index.js";
4
5
  import { MediaOperationOwner, } from "./media-operation-owner.js";
5
6
  import { DailyMediaMeter, } from "./daily-media-meter.js";
7
+ const erasureMarkerSchema = z.strictObject({
8
+ destinationPath: z.string().nullable(),
9
+ writtenSha256: z.string().nullable(),
10
+ abandonedGeneration: z.boolean(),
11
+ });
6
12
  /** Cloudflare lifecycle and RPC surface around the durable media owner. */
7
13
  export class MediaOperationDO extends DurableObject {
8
14
  owner;
@@ -20,10 +26,27 @@ export class MediaOperationDO extends DurableObject {
20
26
  sql: ctx.storage.sql,
21
27
  transactionSync: (body) => ctx.storage.transactionSync(body),
22
28
  isErased: async () => (await ctx.storage.get("botanical:erased")) === true,
23
- markErased: () => ctx.storage.put("botanical:erased", true),
29
+ markErased: async (marker) => {
30
+ // Facts first: the marker's presence is what means erased.
31
+ await ctx.storage.put("botanical:erased-details", JSON.stringify(marker));
32
+ await ctx.storage.put("botanical:erased", true);
33
+ },
34
+ readErasureMarker: async () => {
35
+ const details = z
36
+ .string()
37
+ .optional()
38
+ .parse(await ctx.storage.get("botanical:erased-details"));
39
+ return details === undefined
40
+ ? null
41
+ : erasureMarkerSchema.parse(JSON.parse(details));
42
+ },
24
43
  listKeys: async () => [...(await ctx.storage.list()).keys()],
25
44
  deleteAlarm: () => ctx.storage.deleteAlarm(),
26
- deleteAll: () => ctx.storage.deleteAll(),
45
+ deleteKeys: async (keys) => {
46
+ // Storage deletes at most 128 keys per call.
47
+ for (let start = 0; start < keys.length; start += 128)
48
+ await ctx.storage.delete(keys.slice(start, start + 128));
49
+ },
27
50
  getAlarm: () => ctx.storage.getAlarm(),
28
51
  setAlarm: (timestamp) => ctx.storage.setAlarm(timestamp),
29
52
  },
@@ -71,10 +94,22 @@ export class MediaOperationDO extends DurableObject {
71
94
  preflightErasure(...input) {
72
95
  return this.owner.preflightErasure(...input);
73
96
  }
97
+ /** {@inheritDoc MediaOperationOwner.recordWriteIntent} */
98
+ recordWriteIntent(...input) {
99
+ return this.owner.recordWriteIntent(...input);
100
+ }
74
101
  /** {@inheritDoc MediaOperationOwner.erase} */
75
102
  erase(...input) {
76
103
  return this.owner.erase(...input);
77
104
  }
105
+ /** {@inheritDoc MediaOperationOwner.retained} */
106
+ retained(...input) {
107
+ return this.owner.retained(...input);
108
+ }
109
+ /** {@inheritDoc MediaOperationOwner.readRetained} */
110
+ readRetained(...input) {
111
+ return this.owner.readRetained(...input);
112
+ }
78
113
  /** {@inheritDoc MediaOperationOwner.readErasure} */
79
114
  readErasure(...input) {
80
115
  return this.owner.readErasure(...input);
@@ -143,6 +143,61 @@ export type MediaErasureReadback = Readonly<{
143
143
  /** True only after all local data and retained output are absent. */
144
144
  clear: boolean;
145
145
  }>;
146
+ /** How `erase` treats an operation that is still generating or saving. */
147
+ export type MediaErasePolicy =
148
+ /** Abort it: its later writes refuse and anything that lands is deleted. */
149
+ "abort-active"
150
+ /** Refuse, atomically with the erasure, so a host that waits for inactivity never aborts work. */
151
+ | "refuse-active";
152
+ /** Result of erasing one operation: readback plus what the host may still own. */
153
+ export type MediaErasure = MediaErasureReadback & Readonly<{
154
+ /**
155
+ * The destination path this operation wrote or could have written, kept
156
+ * through erasure so the host can delete the file it owns. Null when the
157
+ * operation was never admitted.
158
+ */
159
+ destinationPath: string | null;
160
+ /**
161
+ * SHA-256 of the exact bytes this operation wrote, or was about to write,
162
+ * to `destinationPath`. Delete the file only while it still matches. Null
163
+ * when no write was ever begun.
164
+ */
165
+ writtenSha256: string | null;
166
+ /**
167
+ * True when the operation was erased before it finished, so a billing hold
168
+ * it took may be open. The host settles it at zero units; repeating that
169
+ * is idempotent.
170
+ */
171
+ abandonedGeneration: boolean;
172
+ }>;
173
+ /** Exact provider bytes an operation retained, before any provenance. */
174
+ export type MediaRetainedBytes = Readonly<{
175
+ /** The retained bytes. */
176
+ bytes: Uint8Array;
177
+ /** Actual output encoding. */
178
+ format: string;
179
+ }>;
180
+ /** What one operation still retains, readable by operation id. */
181
+ export type MediaRetained = Readonly<{
182
+ /** Retry identity of the generation. */
183
+ requestId: string;
184
+ /** Current lifecycle state. */
185
+ state: MediaOperationState;
186
+ /** The host destination path the generation writes, or may already have written. */
187
+ destinationPath: string;
188
+ /**
189
+ * The exact provider bytes retained in the artifacts bucket, or null before
190
+ * any were retained. Found by key even when a crash left them unrecorded.
191
+ */
192
+ output: Readonly<{
193
+ /** Retained byte length. */
194
+ bytes: number;
195
+ /** Actual output encoding. */
196
+ format: string;
197
+ /** Media type of the retained bytes. */
198
+ contentType: string;
199
+ }> | null;
200
+ }>;
146
201
  /** Retained output projection, or a terminal spent format refusal. */
147
202
  export type MediaRetentionResult = MediaOperationProjection | Readonly<{
148
203
  /** Provider execution finished with an unusable pinned format. */
@@ -173,6 +228,9 @@ export declare class MediaOperationOwner {
173
228
  private readonly provider?;
174
229
  private readonly hooks;
175
230
  private erased;
231
+ private retainsInFlight;
232
+ /** Output keys whose delete after a late write failed; erase retries them. */
233
+ private readonly lateDeletes;
176
234
  private readonly leaseMs;
177
235
  /**
178
236
  * A background (video) generation holds its lease past the 15-minute alarm
@@ -202,13 +260,36 @@ export declare class MediaOperationOwner {
202
260
  readShare(namespace: string): MediaShareSource | null;
203
261
  /** Check host namespace, request identity and inactivity before erasure. */
204
262
  preflightErasure(namespace: string, requestId: string): MediaErasurePreflight;
205
- /** Erase inactive output and local storage, then retain the durable erasure marker. */
206
- erase(namespace: string, requestId: string): Promise<Readonly<{
207
- /** True only after all local data and retained output are absent. */
208
- clear: boolean;
209
- }>>;
263
+ private assertErasureAddress;
264
+ private assertScope;
265
+ /** The stored record even after erasure began, while its tables still exist. */
266
+ private readRecordForErasure;
267
+ /**
268
+ * Erase the operation and everything it retained or could still write, even
269
+ * mid-generation. Erasure is marked first, so an attempt still running, or a
270
+ * lease recovered later, can neither transition nor leave output behind: a
271
+ * write that lands after the mark is deleted. The marker is never removed, so
272
+ * a crash cannot resurrect the operation. Safe to repeat until `clear`; a
273
+ * repeat after a partial failure resumes the cleanup.
274
+ */
275
+ erase(namespace: string, requestId: string, policy?: MediaErasePolicy): Promise<MediaErasure>;
210
276
  /** Read back empty SQL, alarm and retained output with the durable erasure marker. */
211
277
  readErasure(): Promise<MediaErasureReadback>;
278
+ /**
279
+ * Run a write to the artifacts bucket. If erasure began while it was in
280
+ * flight, delete what landed and refuse; a failed delete is remembered so
281
+ * `erase` reports not-clear and a repeat retries it.
282
+ */
283
+ private retaining;
284
+ private retainedOutput;
285
+ /** List what this operation retains: its destination path and exact provider output. Null once erased. */
286
+ retained(namespace: string, requestId: string): Promise<MediaRetained | null>;
287
+ /**
288
+ * Read back the exact retained provider bytes, before any provenance, so a
289
+ * host can re-save a result whose destination write was lost. Null when
290
+ * erased or nothing was retained.
291
+ */
292
+ readRetained(namespace: string, requestId: string): Promise<MediaRetainedBytes | null>;
212
293
  private erasureOutputKey;
213
294
  private requireRecord;
214
295
  private update;
@@ -267,6 +348,13 @@ export declare class MediaOperationOwner {
267
348
  readGenerated(leaseId: string): Promise<Uint8Array>;
268
349
  /** A fixed-path exact-byte save is safe to retry without repeating generation. */
269
350
  releaseWrite(leaseId: string): MediaOperationProjection;
351
+ /**
352
+ * Record the digest of the exact bytes about to be written to the
353
+ * destination, before writing them. An erasure then knows which file this
354
+ * operation owns, even if the process dies between the write and its
355
+ * record, and refuses the write once erased.
356
+ */
357
+ recordWriteIntent(leaseId: string, sha256: string): MediaOperationProjection;
270
358
  /** Record a destination write and move to idempotent settlement. */
271
359
  recordWritten(leaseId: string, receipt: string, written: MediaImage): Readonly<{
272
360
  /** Durable object name identifying this operation. */