@fungi.computer/darkroom 0.10.0 → 0.11.1

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>;
@@ -0,0 +1,8 @@
1
+ import { type MediaProviderReason } from "@fungi.computer/agar/errors";
2
+ /** The reason a provider failure is classified under, from its documented code or wording. */
3
+ export declare function providerReason(name: string | undefined, message: string | undefined): MediaProviderReason | undefined;
4
+ /**
5
+ * The provider's own short sentence, when it is plain words. For 7003 it is the
6
+ * <REASON> after "Model execution failed (User Input Error): ".
7
+ */
8
+ export declare function providerDetail(message: string | undefined): string | undefined;
@@ -0,0 +1,72 @@
1
+ import { z } from "zod";
2
+ import { mediaProviderDetailMax, } from "@fungi.computer/agar/errors";
3
+ /**
4
+ * Documented numeric codes, by failure class.
5
+ * Workers AI: https://developers.cloudflare.com/workers-ai/platform/errors/
6
+ * AI Gateway: https://developers.cloudflare.com/ai-gateway/reference/troubleshooting/
7
+ * 2021 is also observed (receipts/prints-e2e: "AiGatewayError: 2021: Insufficient
8
+ * AI Gateway credits"). Codes the docs do not state stay unclassified.
9
+ */
10
+ const reasonByCode = new Map([
11
+ // Gateway or provider rejected the request as invalid ("7003: Model execution
12
+ // failed (User Input Error): <REASON>"), or the body/size/base64 was unusable.
13
+ [7003, "invalid_input"],
14
+ [3003, "invalid_input"],
15
+ [3006, "invalid_input"],
16
+ [5004, "invalid_input"],
17
+ // Request rate or Workers AI capacity.
18
+ [2018, "rate_limited"],
19
+ [3040, "rate_limited"],
20
+ // Prepaid gateway balance.
21
+ [2021, "credits_exhausted"],
22
+ [2052, "credits_exhausted"],
23
+ // Daily allocation used up.
24
+ [3036, "spending_limit"],
25
+ // Timeout.
26
+ [3007, "timeout"],
27
+ // Provider or gateway could not answer.
28
+ [7005, "provider_unavailable"],
29
+ [2002, "provider_unavailable"],
30
+ [2005, "provider_unavailable"],
31
+ ]);
32
+ // "<code>: <rest>", optionally led by the gateway's own "AiGatewayError: ".
33
+ const providerMessage = z
34
+ .string()
35
+ .regex(/^(?:Ai(?:Gateway)?Error: )*\d{4,5}: /u)
36
+ .transform((message) => {
37
+ // The regex above guarantees "<code>: " follows the optional prefixes.
38
+ const body = message.replace(/^(?:Ai(?:Gateway)?Error: )*/u, "");
39
+ const cut = body.indexOf(": ");
40
+ return { code: Number(body.slice(0, cut)), rest: body.slice(cut + 2) };
41
+ });
42
+ // Never print keys, URLs, ids or structured bodies: plain words only.
43
+ const safeSentence = z
44
+ .string()
45
+ .trim()
46
+ .min(1)
47
+ .max(mediaProviderDetailMax)
48
+ .regex(/^[\p{L}\p{N} .,'’:;()-]+$/u)
49
+ .refine((text) => !/[A-Za-z0-9_-]{20,}/u.test(text))
50
+ .refine((text) => !/key|token|secret|bearer|password|authorization/iu.test(text));
51
+ /** The reason a provider failure is classified under, from its documented code or wording. */
52
+ export function providerReason(name, message) {
53
+ if (name === "TimeoutError")
54
+ return "timeout";
55
+ const parsed = providerMessage.safeParse(message);
56
+ if (!parsed.success)
57
+ return undefined;
58
+ const byCode = reasonByCode.get(parsed.data.code);
59
+ return byCode;
60
+ }
61
+ /**
62
+ * The provider's own short sentence, when it is plain words. For 7003 it is the
63
+ * <REASON> after "Model execution failed (User Input Error): ".
64
+ */
65
+ export function providerDetail(message) {
66
+ const parsed = providerMessage.safeParse(message);
67
+ if (!parsed.success)
68
+ return undefined;
69
+ const reason = /^Model execution failed \(User Input Error\): ([\s\S]*)$/u.exec(parsed.data.rest);
70
+ const sentence = safeSentence.safeParse((reason?.[1] ?? parsed.data.rest).replace(/^(?:AiError: )+/u, ""));
71
+ return sentence.success ? sentence.data : undefined;
72
+ }
@@ -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;
@@ -8,6 +8,7 @@ import { GATEWAY_VIDEO_MAX_BYTES, gatewayOutputSchema, isMp4, } from "../gateway
8
8
  import { videoProviderAdapters } from "../video-providers/index.js";
9
9
  import { decodeElevenLabsResultUrl, ELEVENLABS_MAX_BYTES, } from "../audio-providers/elevenlabs.js";
10
10
  import { readResponseBytes } from "../index.js";
11
+ import { providerDetail, providerReason } from "./provider-reason.js";
11
12
  /** Quote the catalog defaults through the exact estimator used before dispatch. */
12
13
  export function estimateMediaModel(model) {
13
14
  const checked = validateMediaGenerationSettings(model.kind === "audio"
@@ -128,9 +129,21 @@ function providerFailure(model, cause) {
128
129
  // call at 2026-10-27T01:01:04.296Z). The error had only name and message;
129
130
  // no HTTP status was recorded. This is observed wording, not a general
130
131
  // Cloudflare code guarantee. Keep numeric classification at this owner.
131
- const provider = code === 2021
132
- ? { category, code, reason: "credits_exhausted" }
133
- : { category, code };
132
+ const message = cause instanceof Error ? cause.message : undefined;
133
+ const safetyRefused = cause instanceof Error && safetyFilterMessage.safeParse(message).success;
134
+ const reason = safetyRefused
135
+ ? "content_refused"
136
+ : providerReason(cause instanceof Error ? cause.name : undefined, message);
137
+ // Plain provider sentences help only where the class alone does not explain.
138
+ const detail = reason === undefined || reason === "invalid_input"
139
+ ? providerDetail(message)
140
+ : undefined;
141
+ const provider = {
142
+ category,
143
+ code,
144
+ ...(reason !== undefined && { reason }),
145
+ ...(detail !== undefined && { detail }),
146
+ };
134
147
  const safeMessage = outputFlaggedMessage.safeParse(cause instanceof Error ? cause.message : undefined);
135
148
  // The maintained Workers AI errors expose name/message, not a Response or
136
149
  // cause chain. Only the complete, bounded refusal grammar above is safe to
@@ -142,8 +155,7 @@ function providerFailure(model, cause) {
142
155
  category: provider.category,
143
156
  providerMessage: safeMessage.success ? safeMessage.data : undefined,
144
157
  }, Redacted.make(cause));
145
- return cause instanceof Error &&
146
- safetyFilterMessage.safeParse(cause.message).success
158
+ return safetyRefused
147
159
  ? new MediaSafetyFilterRefusal({ cause, provider })
148
160
  : new MediaExecutionError("provider", { cause, provider });
149
161
  }
@@ -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);