@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.
@@ -29,6 +29,33 @@ const audioReferenceMetadataSchema = z.lazy(() => z.object({
29
29
  durationSeconds: z.coerce.number().positive(),
30
30
  }));
31
31
  const audioReferenceKey = (operationId, index) => `media-audio-reference/v1/${operationId}/${String(index)}`;
32
+ const activeStates = [
33
+ "estimating",
34
+ "generating",
35
+ "writing",
36
+ "charging",
37
+ ];
38
+ /** States whose billing hold the executor has not yet settled itself. */
39
+ const holdOpenStates = [
40
+ "estimating",
41
+ "generating",
42
+ "writing",
43
+ ];
44
+ const writeReceiptSchema = z.string().regex(/^sha256:([0-9a-f]{64})$/);
45
+ function erasureMarker(record) {
46
+ const receipt = writeReceiptSchema.safeParse(record?.writeReceipt);
47
+ return {
48
+ destinationPath: record?.input.path ?? null,
49
+ writtenSha256: receipt.success
50
+ ? receipt.data.slice("sha256:".length)
51
+ : null,
52
+ abandonedGeneration: record !== null && holdOpenStates.includes(record.state),
53
+ };
54
+ }
55
+ const referenceKeys = (record) => [
56
+ ...(record.input.references ?? []).map((_reference, index) => referenceKey(record.operationId, index)),
57
+ ...(record.input.audioReferences ?? []).map((_reference, index) => audioReferenceKey(record.operationId, index)),
58
+ ];
32
59
  /** Fixed generation destination captured before provider dispatch. */
33
60
  export const mediaOperationDestinationSchema = z.lazy(() => z.strictObject({
34
61
  /** Host-admitted destination or reference identity. */
@@ -218,6 +245,9 @@ export class MediaOperationOwner {
218
245
  provider;
219
246
  hooks;
220
247
  erased = false;
248
+ retainsInFlight = 0;
249
+ /** Output keys whose delete after a late write failed; erase retries them. */
250
+ lateDeletes = new Set();
221
251
  leaseMs = 5 * 60 * 1_000;
222
252
  /**
223
253
  * A background (video) generation holds its lease past the 15-minute alarm
@@ -240,7 +270,8 @@ export class MediaOperationOwner {
240
270
  this.provider = provider;
241
271
  this.hooks = hooks;
242
272
  void ctx.blockConcurrencyWhile(async () => {
243
- if (await ctx.storage.isErased()) {
273
+ const durablyErased = await ctx.storage.isErased();
274
+ if (durablyErased || this.erased) {
244
275
  this.erased = true;
245
276
  return;
246
277
  }
@@ -401,34 +432,91 @@ export class MediaOperationOwner {
401
432
  }
402
433
  /** Check host namespace, request identity and inactivity before erasure. */
403
434
  preflightErasure(namespace, requestId) {
404
- if (this.ctx.id.name !== `media:${requestId}`)
405
- throw new Error("Media erasure address mismatch");
406
- if (this.erased)
435
+ if (this.erased) {
436
+ this.assertErasureAddress(requestId);
407
437
  return { namespace, requestId, erased: true };
438
+ }
408
439
  const record = this.readRecord();
409
- const ownerNamespace = record?.namespace ?? this.hooks.namespace?.() ?? null;
410
- if ((ownerNamespace !== null && ownerNamespace !== namespace) ||
411
- (record !== null && record.requestId !== requestId))
412
- throw new Error("Media erasure scope mismatch");
440
+ this.assertScope(namespace, requestId, record);
413
441
  if (record !== null &&
414
442
  ["estimating", "generating", "writing", "charging"].includes(record.state))
415
443
  throw new Error("Media operation is still active");
416
444
  return { namespace, requestId, erased: false };
417
445
  }
418
- /** Erase inactive output and local storage, then retain the durable erasure marker. */
419
- async erase(namespace, requestId) {
420
- if (this.erased)
421
- return this.readErasure();
422
- this.preflightErasure(namespace, requestId);
423
- // The operation's immutable output key is owned by this DO identity.
424
- await this.env.APP_ARTIFACTS.delete(this.erasureOutputKey());
425
- if (await this.env.APP_ARTIFACTS.head(this.erasureOutputKey()))
426
- throw new Error("Media output erasure readback incomplete");
446
+ assertErasureAddress(requestId) {
447
+ if (this.ctx.id.name !== `media:${requestId}`)
448
+ throw new Error("Media erasure address mismatch");
449
+ }
450
+ assertScope(namespace, requestId, record) {
451
+ this.assertErasureAddress(requestId);
452
+ const ownerNamespace = record?.namespace ?? this.hooks.namespace?.() ?? null;
453
+ if ((ownerNamespace !== null && ownerNamespace !== namespace) ||
454
+ (record !== null && record.requestId !== requestId))
455
+ throw new Error("Media erasure scope mismatch");
456
+ }
457
+ /** The stored record even after erasure began, while its tables still exist. */
458
+ readRecordForErasure() {
459
+ const table = this.ctx.storage.sql
460
+ .exec("SELECT name FROM sqlite_master WHERE type='table' AND name='hub_media_operation'")
461
+ .toArray()[0];
462
+ if (table === undefined)
463
+ return null;
464
+ const row = this.ctx.storage.sql
465
+ .exec("SELECT * FROM hub_media_operation WHERE singleton=1")
466
+ .toArray()[0];
467
+ if (row === undefined)
468
+ return null;
469
+ const parsed = operationRowSchema.safeParse(row);
470
+ if (!parsed.success)
471
+ throw new MediaOperationError("partial_init", { cause: parsed.error });
472
+ return this.decode(parsed.data);
473
+ }
474
+ /**
475
+ * Erase the operation and everything it retained or could still write, even
476
+ * mid-generation. Erasure is marked first, so an attempt still running, or a
477
+ * lease recovered later, can neither transition nor leave output behind: a
478
+ * write that lands after the mark is deleted. The marker is never removed, so
479
+ * a crash cannot resurrect the operation. Safe to repeat until `clear`; a
480
+ * repeat after a partial failure resumes the cleanup.
481
+ */
482
+ async erase(namespace, requestId, policy = "abort-active") {
483
+ const record = this.readRecordForErasure();
484
+ this.assertScope(namespace, requestId, record);
485
+ if (!this.erased) {
486
+ if (policy === "refuse-active" &&
487
+ record !== null &&
488
+ activeStates.includes(record.state))
489
+ throw new Error("Media operation is still active");
490
+ // Synchronously, before any await: nothing in this object transitions again.
491
+ this.erased = true;
492
+ }
493
+ if (!(await this.ctx.storage.isErased()))
494
+ await this.ctx.storage.markErased(erasureMarker(record));
495
+ const marker = (await this.ctx.storage.readErasureMarker()) ?? {
496
+ destinationPath: null,
497
+ writtenSha256: null,
498
+ abandonedGeneration: false,
499
+ };
500
+ // The immutable output key is owned by this DO identity; background
501
+ // reference copies hold the person's private inputs.
502
+ const keys = [
503
+ this.erasureOutputKey(),
504
+ ...(record === null ? [] : referenceKeys(record)),
505
+ ...this.lateDeletes,
506
+ ];
507
+ await Promise.all(keys.map((key) => this.env.APP_ARTIFACTS.delete(key)));
508
+ this.lateDeletes.clear();
427
509
  await this.ctx.storage.deleteAlarm();
428
- await this.ctx.storage.deleteAll();
429
- await this.ctx.storage.markErased();
430
- this.erased = true;
431
- return this.readErasure();
510
+ // Never deleteAll: it would remove the marker and its facts.
511
+ const tables = z
512
+ .array(z.strictObject({ name: z.string() }))
513
+ .parse(this.ctx.storage.sql
514
+ .exec("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'")
515
+ .toArray());
516
+ for (const { name } of tables)
517
+ this.ctx.storage.sql.exec(`DROP TABLE "${name.replaceAll('"', '""')}"`);
518
+ await this.ctx.storage.deleteKeys((await this.ctx.storage.listKeys()).filter((key) => !key.startsWith("botanical:erased")));
519
+ return { ...(await this.readErasure()), ...marker };
432
520
  }
433
521
  /** Read back empty SQL, alarm and retained output with the durable erasure marker. */
434
522
  async readErasure() {
@@ -437,14 +525,102 @@ export class MediaOperationOwner {
437
525
  .exec("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'")
438
526
  .toArray();
439
527
  return {
440
- clear: keys.length === 1 &&
441
- keys[0] === "botanical:erased" &&
528
+ clear: keys.includes("botanical:erased") &&
529
+ keys.every((key) => key.startsWith("botanical:erased")) &&
442
530
  (await this.ctx.storage.isErased()) &&
443
531
  tables.length === 0 &&
532
+ // A put still in flight, or a late delete that failed, is not clear yet.
533
+ this.retainsInFlight === 0 &&
534
+ this.lateDeletes.size === 0 &&
444
535
  (await this.ctx.storage.getAlarm()) === null &&
445
536
  (await this.env.APP_ARTIFACTS.head(this.erasureOutputKey())) === null,
446
537
  };
447
538
  }
539
+ /**
540
+ * Run a write to the artifacts bucket. If erasure began while it was in
541
+ * flight, delete what landed and refuse; a failed delete is remembered so
542
+ * `erase` reports not-clear and a repeat retries it.
543
+ */
544
+ async retaining(keys, write) {
545
+ this.retainsInFlight += 1;
546
+ try {
547
+ const written = await write();
548
+ if (this.erased) {
549
+ for (const key of keys)
550
+ this.lateDeletes.add(key);
551
+ await Promise.all(keys.map((key) => this.env.APP_ARTIFACTS.delete(key)));
552
+ for (const key of keys)
553
+ this.lateDeletes.delete(key);
554
+ throw new MediaOperationError("not_found");
555
+ }
556
+ return written;
557
+ }
558
+ finally {
559
+ this.retainsInFlight -= 1;
560
+ }
561
+ }
562
+ async retainedOutput(record) {
563
+ if (record.output !== null)
564
+ return {
565
+ key: record.output.key,
566
+ bytes: record.output.bytes,
567
+ format: record.output.format,
568
+ version: record.output.version,
569
+ };
570
+ // A crash after the R2 write and before its record leaves exact bytes
571
+ // nothing points to; find them by the key this operation owns.
572
+ const head = await this.env.APP_ARTIFACTS.head(`media-output/v1/${record.operationId}`);
573
+ if (head === null)
574
+ return null;
575
+ return {
576
+ key: head.key,
577
+ bytes: head.size,
578
+ format: retainedFormatSchema.parse(head.httpMetadata?.contentType),
579
+ version: head.version,
580
+ };
581
+ }
582
+ /** List what this operation retains: its destination path and exact provider output. Null once erased. */
583
+ async retained(namespace, requestId) {
584
+ const record = this.readRecord();
585
+ this.assertScope(namespace, requestId, record);
586
+ if (record === null)
587
+ return null;
588
+ const output = await this.retainedOutput(record);
589
+ return Object.freeze({
590
+ requestId: record.requestId,
591
+ state: record.state,
592
+ destinationPath: record.input.path,
593
+ output: output === null
594
+ ? null
595
+ : Object.freeze({
596
+ bytes: output.bytes,
597
+ format: output.format,
598
+ contentType: outputMime(output.format),
599
+ }),
600
+ });
601
+ }
602
+ /**
603
+ * Read back the exact retained provider bytes, before any provenance, so a
604
+ * host can re-save a result whose destination write was lost. Null when
605
+ * erased or nothing was retained.
606
+ */
607
+ async readRetained(namespace, requestId) {
608
+ const record = this.readRecord();
609
+ this.assertScope(namespace, requestId, record);
610
+ if (record === null)
611
+ return null;
612
+ const output = await this.retainedOutput(record);
613
+ if (output === null)
614
+ return null;
615
+ const object = await this.env.APP_ARTIFACTS.get(output.key);
616
+ if (object?.version !== output.version || object.size !== output.bytes)
617
+ throw new MediaOperationError("partial_init");
618
+ const bytes = new Uint8Array(await object.arrayBuffer());
619
+ // Erasure may have begun while the object was read.
620
+ if (this.erased)
621
+ throw new MediaOperationError("not_found");
622
+ return { bytes, format: output.format };
623
+ }
448
624
  erasureOutputKey() {
449
625
  const name = this.ctx.id.name;
450
626
  if (name === undefined)
@@ -587,7 +763,8 @@ export class MediaOperationOwner {
587
763
  format: output.format,
588
764
  },
589
765
  output,
590
- writeReceipt: null,
766
+ // A write may have landed before the worker died; the retry writes the same bytes.
767
+ writeReceipt: record.writeReceipt,
591
768
  result: null,
592
769
  });
593
770
  return {
@@ -678,23 +855,25 @@ export class MediaOperationOwner {
678
855
  const record = this.requireRecord();
679
856
  if (record.state !== "generating" || record.leaseId !== leaseId)
680
857
  throw new MediaOperationError("lease_lost");
681
- for (const [index, reference] of references.entries()) {
682
- await this.env.APP_ARTIFACTS.put(referenceKey(record.operationId, index), reference.bytes, {
683
- customMetadata: {
684
- format: reference.format,
685
- width: String(reference.width),
686
- height: String(reference.height),
687
- },
688
- });
689
- }
690
- for (const [index, clip] of audioReferences.entries()) {
691
- await this.env.APP_ARTIFACTS.put(audioReferenceKey(record.operationId, index), clip.bytes, {
692
- customMetadata: {
693
- mimeType: clip.mimeType,
694
- durationSeconds: String(clip.durationSeconds),
695
- },
696
- });
697
- }
858
+ await this.retaining(referenceKeys(record), async () => {
859
+ for (const [index, reference] of references.entries()) {
860
+ await this.env.APP_ARTIFACTS.put(referenceKey(record.operationId, index), reference.bytes, {
861
+ customMetadata: {
862
+ format: reference.format,
863
+ width: String(reference.width),
864
+ height: String(reference.height),
865
+ },
866
+ });
867
+ }
868
+ for (const [index, clip] of audioReferences.entries()) {
869
+ await this.env.APP_ARTIFACTS.put(audioReferenceKey(record.operationId, index), clip.bytes, {
870
+ customMetadata: {
871
+ mimeType: clip.mimeType,
872
+ durationSeconds: String(clip.durationSeconds),
873
+ },
874
+ });
875
+ }
876
+ });
698
877
  const timestamp = Date.now();
699
878
  this.ctx.storage.sql.exec("UPDATE hub_media_operation SET background=1, lease_expires_at=?, updated_at=? WHERE singleton=1 AND state='generating' AND lease_id=?", timestamp + this.backgroundLeaseMs, timestamp, leaseId);
700
879
  await this.ctx.storage.setAlarm(timestamp);
@@ -875,10 +1054,10 @@ export class MediaOperationOwner {
875
1054
  };
876
1055
  }
877
1056
  const key = `media-output/v1/${record.operationId}`;
878
- const stored = await this.env.APP_ARTIFACTS.put(key, bytes, {
1057
+ const stored = await this.retaining([key], () => this.env.APP_ARTIFACTS.put(key, bytes, {
879
1058
  onlyIf: { etagDoesNotMatch: "*" },
880
1059
  httpMetadata: { contentType: outputMime(image.data.format) },
881
- });
1060
+ }));
882
1061
  if (stored === null)
883
1062
  throw new MediaOperationError("conflict");
884
1063
  return this.transition(leaseId, "generating", "writing", {
@@ -923,7 +1102,33 @@ export class MediaOperationOwner {
923
1102
  estimatedCostMilliunits: record.estimatedCostMilliunits,
924
1103
  image: record.image,
925
1104
  output: record.output,
926
- writeReceipt: null,
1105
+ writeReceipt: record.writeReceipt,
1106
+ result: null,
1107
+ })));
1108
+ }
1109
+ /**
1110
+ * Record the digest of the exact bytes about to be written to the
1111
+ * destination, before writing them. An erasure then knows which file this
1112
+ * operation owns, even if the process dies between the write and its
1113
+ * record, and refuses the write once erased.
1114
+ */
1115
+ recordWriteIntent(leaseId, sha256) {
1116
+ const receipt = `sha256:${sha256}`;
1117
+ if (!writeReceiptSchema.safeParse(receipt).success)
1118
+ throw new MediaOperationError("invalid_input");
1119
+ const record = this.requireRecord();
1120
+ if (record.state !== "writing" || record.leaseId !== leaseId)
1121
+ throw new MediaOperationError("lease_lost");
1122
+ return this.ctx.storage.transactionSync(() => this.project(this.update({
1123
+ expectedState: "writing",
1124
+ expectedLeaseId: leaseId,
1125
+ state: "writing",
1126
+ leaseId,
1127
+ leaseExpiresAt: record.leaseExpiresAt,
1128
+ estimatedCostMilliunits: record.estimatedCostMilliunits,
1129
+ image: record.image,
1130
+ output: record.output,
1131
+ writeReceipt: receipt,
927
1132
  result: null,
928
1133
  })));
929
1134
  }
@@ -1,3 +1,12 @@
1
+ /** Facts an erased operation keeps: its destination file, and whether a billing hold may be open. */
2
+ export type MediaErasureMarker = Readonly<{
3
+ /** The destination path the operation wrote or could have written. */
4
+ destinationPath: string | null;
5
+ /** SHA-256 of the bytes it wrote or was about to write there. */
6
+ writtenSha256: string | null;
7
+ /** The operation was erased before it finished. */
8
+ abandonedGeneration: boolean;
9
+ }>;
1
10
  /** SQL rows stay untrusted until the owner decodes their stored representation. */
2
11
  export type MediaOperationStorage = {
3
12
  /** Native synchronous SQL interface. */
@@ -12,14 +21,19 @@ export type MediaOperationStorage = {
12
21
  transactionSync<T>(body: () => T): T;
13
22
  /** Read the durable erasure marker. */
14
23
  isErased(): Promise<boolean>;
15
- /** Persist the durable erasure marker. */
16
- markErased(): Promise<void>;
24
+ /**
25
+ * Persist the durable erasure marker with the facts the host needs after
26
+ * erasure. Never removed: nothing may delete it.
27
+ */
28
+ markErased(marker: MediaErasureMarker): Promise<void>;
29
+ /** Read the facts kept with the marker, or null for a marker without them. */
30
+ readErasureMarker(): Promise<MediaErasureMarker | null>;
17
31
  /** List local key-value storage keys for erasure readback. */
18
32
  listKeys(): Promise<readonly string[]>;
19
33
  /** Remove any scheduled background alarm. */
20
34
  deleteAlarm(): Promise<void>;
21
- /** Remove local SQL and key-value storage. */
22
- deleteAll(): Promise<void>;
35
+ /** Remove the named key-value entries. */
36
+ deleteKeys(keys: readonly string[]): Promise<void>;
23
37
  /** Read the current background alarm, or null. */
24
38
  getAlarm(): Promise<number | null>;
25
39
  /** Schedule background generation at the given timestamp. */
@@ -3,6 +3,7 @@ import * as Effect from "effect/Effect";
3
3
  import { reportCatchFailure } from "./failure.js";
4
4
  import { mediaUnits } from "./gateway-models.js";
5
5
  import { getMediaModel } from "./model-catalog.js";
6
+ import { mediaWrittenDigest } from "./media-written.js";
6
7
  import { embedProvenance } from "./provenance.js";
7
8
  import { z } from "zod";
8
9
  import { mediaGenerationSettingsSchema, validateMediaGenerationSettings, } from "./index.js";
@@ -135,7 +136,17 @@ export function executeMediaOperation(input) {
135
136
  units: billed.units,
136
137
  providerCostMilliunits: prepared.costMilliunits,
137
138
  }), "billing").pipe(Effect.tapError(releaseEstimate))).priceMilliunits;
138
- yield* call(() => input.operation.recordEstimate(leaseId, costMilliunits), "estimate");
139
+ yield* call(() => input.operation.recordEstimate(leaseId, costMilliunits), "estimate").pipe(
140
+ // Erasure settled its hold before this admit ran, so the hold just
141
+ // opened belongs to nobody: release it rather than leave it to expire.
142
+ Effect.tapError(() => call(async () => {
143
+ const kept = await input.operation.retained(input.coordinates.namespace, input.requestId);
144
+ if (kept === null && metering !== null)
145
+ await metering.settle({ operationId, units: 0 });
146
+ }, "billing").pipe(Effect.catch((cause) => {
147
+ reportCatchFailure("media-operation-erased-hold", cause);
148
+ return Effect.void;
149
+ }))));
139
150
  if (background) {
140
151
  // Video outlives one request: the owner's alarm generates, and a
141
152
  // retry of this request id saves and charges the retained output.
@@ -213,7 +224,7 @@ export function executeMediaOperation(input) {
213
224
  ? yield* call(() => embedProvenance(output.bytes, format.data, {
214
225
  printId: operationId,
215
226
  model: input.request.model,
216
- prompt: input.request.prompt,
227
+ prompt: input.embedPrompt === true ? input.request.prompt : null,
217
228
  createdAt: admission.operation.createdAt,
218
229
  }), "operation")
219
230
  : {
@@ -227,13 +238,28 @@ export function executeMediaOperation(input) {
227
238
  format: output.format,
228
239
  reason: provenance.reason,
229
240
  });
241
+ // The digest of what is about to land is durable before it lands, so an
242
+ // erasure knows which file is this operation's and refuses the write.
243
+ const digest = yield* call(() => mediaWrittenDigest(provenance.bytes), "operation");
244
+ const receipt = `sha256:${digest}`;
245
+ yield* call(() => input.operation.recordWriteIntent(leaseId, digest), "operation");
230
246
  yield* call(() => input.destination.write(provenance.bytes), "destination-write").pipe(Effect.tapError(() => call(() => input.operation.releaseWrite(leaseId), "operation").pipe(Effect.ignore)));
231
247
  image = {
232
248
  bytes: provenance.bytes.byteLength,
233
249
  format: output.format,
234
250
  };
251
+ // The write landed. If erasure won the race the operation can no longer
252
+ // record it, and nothing else points at the file: delete what landed.
253
+ const deleteIfErased = (error) => call(async () => {
254
+ const kept = await input.operation.retained(input.coordinates.namespace, input.requestId);
255
+ if (kept === null)
256
+ await input.destination.remove(digest);
257
+ }, "destination-write").pipe(Effect.catch((cause) => {
258
+ reportCatchFailure("media-operation-erased-write", cause);
259
+ return Effect.void;
260
+ }), Effect.andThen(Effect.fail(error)));
235
261
  if (metering === null) {
236
- yield* call(() => input.operation.recordWrittenWithoutSettlement(leaseId, "computer-write-committed", image), "operation");
262
+ yield* call(() => input.operation.recordWrittenWithoutSettlement(leaseId, receipt, image), "operation").pipe(Effect.catch(deleteIfErased));
237
263
  return {
238
264
  kind: "succeeded",
239
265
  bytes: image.bytes,
@@ -241,7 +267,7 @@ export function executeMediaOperation(input) {
241
267
  costMilliunits,
242
268
  };
243
269
  }
244
- yield* call(() => input.operation.recordWritten(leaseId, "computer-write-committed", image), "operation");
270
+ yield* call(() => input.operation.recordWritten(leaseId, receipt, image), "operation").pipe(Effect.catch(deleteIfErased));
245
271
  }
246
272
  if (metering === null)
247
273
  return { kind: "unavailable" };
@@ -0,0 +1,22 @@
1
+ /** What a destination did when asked to delete a file this operation wrote. */
2
+ export type MediaRemoval =
3
+ /** The file matched what the operation wrote and was deleted. */
4
+ "removed"
5
+ /** Nothing was at the path. */
6
+ | "absent"
7
+ /** The path holds different bytes now; it is not this operation's file and was left alone. */
8
+ | "not-ours"
9
+ /** The destination cannot delete files; the host must remove the matching file itself. */
10
+ | "kept";
11
+ /** Lowercase hex SHA-256 of the exact bytes written to a destination. */
12
+ export declare function mediaWrittenDigest(bytes: Uint8Array): Promise<string>;
13
+ /**
14
+ * Delete the file at a destination path only while it still holds the exact
15
+ * bytes the operation wrote, so a path reused for something else is never lost.
16
+ */
17
+ export declare function removeMediaIfWritten(file: Readonly<{
18
+ /** Read the current bytes at the path, or null when absent. */
19
+ read: () => Promise<Uint8Array | null>;
20
+ /** Delete the file at the path. */
21
+ delete: () => Promise<void>;
22
+ }>, sha256: string): Promise<MediaRemoval>;
@@ -0,0 +1,20 @@
1
+ /** Lowercase hex SHA-256 of the exact bytes written to a destination. */
2
+ export async function mediaWrittenDigest(bytes) {
3
+ const digest = await crypto.subtle.digest("SHA-256", bytes.slice());
4
+ return [...new Uint8Array(digest)]
5
+ .map((byte) => byte.toString(16).padStart(2, "0"))
6
+ .join("");
7
+ }
8
+ /**
9
+ * Delete the file at a destination path only while it still holds the exact
10
+ * bytes the operation wrote, so a path reused for something else is never lost.
11
+ */
12
+ export async function removeMediaIfWritten(file, sha256) {
13
+ const current = await file.read();
14
+ if (current === null)
15
+ return "absent";
16
+ if ((await mediaWrittenDigest(current)) !== sha256)
17
+ return "not-ours";
18
+ await file.delete();
19
+ return "removed";
20
+ }
@@ -53,6 +53,11 @@ export declare const mediaModelInputSchema: z.ZodLazy<z.ZodReadonly<z.ZodObject<
53
53
  }>;
54
54
  maxSteps: z.ZodNullable<z.ZodNumber>;
55
55
  defaultSteps: z.ZodNullable<z.ZodNumber>;
56
+ guidance: z.ZodDefault<z.ZodNullable<z.ZodReadonly<z.ZodObject<{
57
+ min: z.ZodNumber;
58
+ max: z.ZodNumber;
59
+ default: z.ZodNumber;
60
+ }, z.core.$strict>>>>;
56
61
  referenceField: z.ZodNullable<z.ZodString>;
57
62
  maxReferences: z.ZodNumber;
58
63
  referenceDimension: z.ZodNullable<z.ZodNumber>;
@@ -469,6 +474,11 @@ export declare const mediaModelSchema: z.ZodReadonly<z.ZodObject<{
469
474
  }>;
470
475
  maxSteps: z.ZodNullable<z.ZodNumber>;
471
476
  defaultSteps: z.ZodNullable<z.ZodNumber>;
477
+ guidance: z.ZodDefault<z.ZodNullable<z.ZodReadonly<z.ZodObject<{
478
+ min: z.ZodNumber;
479
+ max: z.ZodNumber;
480
+ default: z.ZodNumber;
481
+ }, z.core.$strict>>>>;
472
482
  referenceField: z.ZodNullable<z.ZodString>;
473
483
  maxReferences: z.ZodNumber;
474
484
  referenceDimension: z.ZodNullable<z.ZodNumber>;
@@ -722,6 +732,11 @@ export declare const mediaCatalogueModelSchema: z.ZodReadonly<z.ZodObject<{
722
732
  }>;
723
733
  maxSteps: z.ZodNullable<z.ZodNumber>;
724
734
  defaultSteps: z.ZodNullable<z.ZodNumber>;
735
+ guidance: z.ZodDefault<z.ZodNullable<z.ZodReadonly<z.ZodObject<{
736
+ min: z.ZodNumber;
737
+ max: z.ZodNumber;
738
+ default: z.ZodNumber;
739
+ }, z.core.$strict>>>>;
725
740
  referenceField: z.ZodNullable<z.ZodString>;
726
741
  maxReferences: z.ZodNumber;
727
742
  referenceDimension: z.ZodNullable<z.ZodNumber>;
@@ -976,6 +991,11 @@ export declare const mediaCatalogueSchema: z.ZodPipe<z.ZodArray<z.ZodReadonly<z.
976
991
  }>;
977
992
  maxSteps: z.ZodNullable<z.ZodNumber>;
978
993
  defaultSteps: z.ZodNullable<z.ZodNumber>;
994
+ guidance: z.ZodDefault<z.ZodNullable<z.ZodReadonly<z.ZodObject<{
995
+ min: z.ZodNumber;
996
+ max: z.ZodNumber;
997
+ default: z.ZodNumber;
998
+ }, z.core.$strict>>>>;
979
999
  referenceField: z.ZodNullable<z.ZodString>;
980
1000
  maxReferences: z.ZodNumber;
981
1001
  referenceDimension: z.ZodNullable<z.ZodNumber>;
@@ -1179,6 +1199,11 @@ export declare const mediaCatalogueSchema: z.ZodPipe<z.ZodArray<z.ZodReadonly<z.
1179
1199
  steps: "steps" | "num_steps" | "fixed";
1180
1200
  maxSteps: number | null;
1181
1201
  defaultSteps: number | null;
1202
+ guidance: Readonly<{
1203
+ min: number;
1204
+ max: number;
1205
+ default: number;
1206
+ }> | null;
1182
1207
  referenceField: string | null;
1183
1208
  maxReferences: number;
1184
1209
  referenceDimension: number | null;