@audiofool/moondog 0.3.1 → 0.3.3

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.
@@ -1,5 +1,6 @@
1
- // Makes music on this Mac with a local Stable Audio 3 install (Stability AI's optimized MLX
2
- // build). The listener turns it on once, in Settings or with /generation; until then nothing
1
+ // Makes music on this computer with a local Stable Audio 3 install: Stability AI's optimized MLX
2
+ // build on a Mac with Apple silicon, its LiteRT CPU build on Windows and Linux (sources.mjs). The
3
+ // listener turns it on once, in Settings or with /generation; until then nothing
3
4
  // runs. Each track is a WAV and a receipt in Moondog's state directory, and nothing leaves the
4
5
  // machine: a run never downloads anything, and the receipt keeps no absolute path. Moondog's own
5
6
  // install (setup.mjs) downloads only when the listener asks, from the pinned official sources.
@@ -7,29 +8,38 @@ import { spawn } from "node:child_process";
7
8
  import { randomBytes, randomInt, randomUUID } from "node:crypto";
8
9
  import { unwatchFile, watchFile } from "node:fs";
9
10
  import { access, appendFile, chmod, constants, mkdir, open, readdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
10
- import { homedir } from "node:os";
11
+ import { availableParallelism, homedir } from "node:os";
11
12
  import path from "node:path";
12
13
 
13
14
  import { resolveMoondogStateDirectory } from "../../core/state-directory.mjs";
14
15
  import { streamVariation } from "../../profile/taste-compiler.mjs";
15
16
  import { resolveMoondogAuthFile } from "../../runtime/pi/persistent-credential-store.mjs";
16
17
  import { readLoudness } from "./cover.mjs";
17
- import { DEFAULT_STABLE_AUDIO_MODEL, isStableAudioModel, SHARED_WEIGHTS, STABLE_AUDIO_MODELS } from "./sources.mjs";
18
+ import { DEFAULT_STABLE_AUDIO_MODEL, isStableAudioModel, stableAudioMaxSeconds, stableAudioRuntime, stableAudioRuntimeModels } from "./sources.mjs";
18
19
 
19
- // The weights a model needs for text to music: the text encoder, the model and its decoder.
20
- export const stableAudioWeights = (model = DEFAULT_STABLE_AUDIO_MODEL) => [...SHARED_WEIGHTS, ...STABLE_AUDIO_MODELS[model].weights];
20
+ // The weights a model needs for text to music on a runtime: the text encoder, the model and its decoder.
21
+ export const stableAudioWeights = (model = DEFAULT_STABLE_AUDIO_MODEL, runtime = "mlx") => {
22
+ const { models, shared } = stableAudioRuntimeModels(runtime);
23
+ return [...shared, ...models[model].weights];
24
+ };
21
25
  // Medium and Small Music were trained on up to 380 seconds; very short clips come out rough.
22
26
  export const GENERATION_SECONDS = Object.freeze({ min: 15, max: 380, default: 120 });
23
- // A cold start reads about 4.8 GB of weights before the first step; a 380-second track then takes about 35 seconds.
24
- const generationTimeoutMs = 10 * 60_000;
27
+ // A cold start reads about 4.8 GB of weights before the first step; a 380-second track then takes about 35
28
+ // seconds on Apple silicon. The CPU build is many times slower, so it has longer.
29
+ const generationTimeoutMs = { mlx: 10 * 60_000, tflite: 40 * 60_000 };
25
30
  const stoppingGraceMs = 3_000;
26
31
  const trackIdPattern = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/u;
27
32
 
28
33
  export const isGeneratedTrackId = (value) => typeof value === "string" && trackIdPattern.test(value);
29
34
 
30
- /** Where Stability's own install script puts the MLX build when it runs from ~/Developer. */
31
- export function defaultStableAudioRoot() {
32
- return path.join(homedir(), "Developer", "stable-audio-3", "optimized", "mlx");
35
+ /** Where Stability's own install script puts a runtime's build when it runs from ~/Developer. */
36
+ export function defaultStableAudioRoot(runtime = "mlx") {
37
+ return path.join(homedir(), "Developer", "stable-audio-3", "optimized", runtime === "tflite" ? "tflite" : "mlx");
38
+ }
39
+
40
+ /** The Python of an install's environment: Windows keeps it in Scripts. */
41
+ export function stableAudioPython(root, platform = process.platform) {
42
+ return platform === "win32" ? path.join(root, ".venv", "Scripts", "python.exe") : path.join(root, ".venv", "bin", "python");
33
43
  }
34
44
 
35
45
  /** The install Moondog downloads and manages itself; the MLX build is in its mlx folder. */
@@ -73,22 +83,24 @@ export async function readSavedSettings(environment) {
73
83
  */
74
84
  export async function readGenerationSettings(environment = process.env, { platform = process.platform, arch = process.arch } = {}) {
75
85
  const saved = await readSavedSettings(environment);
86
+ const runtime = stableAudioRuntime({ platform, arch, environment }) ?? "mlx";
76
87
  const fromEnvironment = literalFolder(environment.MOONDOG_SA3_DIR);
77
88
  const fromFile = literalFolder(saved.path);
78
89
  const managed = !fromEnvironment && saved.source === "managed";
79
- const folder = fromFile ?? defaultStableAudioRoot();
90
+ const folder = fromFile ?? defaultStableAudioRoot(runtime);
80
91
  let model = isStableAudioModel(saved.model) ? saved.model : DEFAULT_STABLE_AUDIO_MODEL;
81
92
  // A folder Moondog doesn't manage (MOONDOG_SA3_DIR, a typed folder, ~/Developer) runs the saved model
82
93
  // only if it has it, otherwise the first model it can run; a model chosen for Moondog's own install
83
94
  // waits until that install is chosen again. A folder that runs nothing keeps the saved model.
84
95
  if (!managed) {
85
- for (const name of [...new Set([model, DEFAULT_STABLE_AUDIO_MODEL, ...Object.keys(STABLE_AUDIO_MODELS)])]) {
86
- if ((await checkStableAudioInstall(fromEnvironment ?? folder, { model: name, platform, arch })).state === "ready") { model = name; break; }
96
+ for (const name of [...new Set([model, DEFAULT_STABLE_AUDIO_MODEL, ...Object.keys(stableAudioRuntimeModels(runtime).models)])]) {
97
+ if ((await checkStableAudioInstall(fromEnvironment ?? folder, { model: name, platform, arch, environment })).state === "ready") { model = name; break; }
87
98
  }
88
99
  }
89
100
  return {
90
101
  enabled: saved.enabled === true,
91
- path: fromEnvironment ?? (managed ? path.join(resolveStableAudioManagedRoot(environment), "mlx") : folder),
102
+ // Moondog's own install keeps each runtime's build in a folder of its own name.
103
+ path: fromEnvironment ?? (managed ? path.join(resolveStableAudioManagedRoot(environment), runtime) : folder),
92
104
  source: fromEnvironment ? "environment" : managed ? "managed" : fromFile ? "settings" : "default",
93
105
  model,
94
106
  folder,
@@ -123,11 +135,11 @@ export async function writeGenerationSettings({ enabled, path: folder, source, m
123
135
  let chosen = model ?? current.model;
124
136
  if (model === undefined && !managed && (typed || source === "settings")) {
125
137
  const folderRoot = savedFolder ?? current.folder;
126
- const candidates = [current.model, DEFAULT_STABLE_AUDIO_MODEL, ...Object.keys(STABLE_AUDIO_MODELS)];
138
+ const candidates = [current.model, DEFAULT_STABLE_AUDIO_MODEL, ...Object.keys(stableAudioRuntimeModels(stableAudioRuntime({ platform, arch, environment })).models)];
127
139
  // A folder that runs nothing yet gets Medium, the model the install steps Moondog shows download.
128
140
  chosen = DEFAULT_STABLE_AUDIO_MODEL;
129
141
  for (const name of [...new Set(candidates)]) {
130
- if ((await checkStableAudioInstall(folderRoot, { model: name, platform, arch })).state === "ready") { chosen = name; break; }
142
+ if ((await checkStableAudioInstall(folderRoot, { model: name, platform, arch, environment })).state === "ready") { chosen = name; break; }
131
143
  }
132
144
  }
133
145
  const document = {
@@ -157,16 +169,19 @@ const isFile = async (file, { executable = false, minimumBytes = 0 } = {}) => {
157
169
 
158
170
  /**
159
171
  * Whether an install can make music now with a model, without running it: "ready", "unsupported"
160
- * (MLX needs Apple silicon), "missing" (no install at the folder) or "incomplete" (no Python
161
- * environment or not that model's weights, which Moondog's setup or Stability's ./install.sh fetches).
172
+ * (no Stability AI build runs on this machine, as on an Intel Mac), "missing" (no install at the folder)
173
+ * or "incomplete" (no Python environment or not that model's weights, which Moondog's setup or
174
+ * Stability's install script fetches). The runtime decides the layout: MLX on Apple silicon, LiteRT elsewhere.
162
175
  */
163
- export async function checkStableAudioInstall(root, { model = DEFAULT_STABLE_AUDIO_MODEL, platform = process.platform, arch = process.arch } = {}) {
164
- if (platform !== "darwin" || arch !== "arm64") return { state: "unsupported" };
176
+ export async function checkStableAudioInstall(root, { model = DEFAULT_STABLE_AUDIO_MODEL, platform = process.platform, arch = process.arch, environment = process.env } = {}) {
177
+ const runtime = stableAudioRuntime({ platform, arch, environment });
178
+ if (!runtime) return { state: "unsupported" };
165
179
  if (!root || !path.isAbsolute(root)) return { state: "missing" };
166
- if (!(await isFile(path.join(root, "scripts", "sa3_mlx.py")))) return { state: "missing" };
167
- if (!(await isFile(path.join(root, ".venv", "bin", "python"), { executable: true }))) return { state: "incomplete", missing: "environment" };
168
- for (const weight of stableAudioWeights(isStableAudioModel(model) ? model : DEFAULT_STABLE_AUDIO_MODEL)) {
169
- if (!(await isFile(path.join(root, "models", "mlx", weight), { minimumBytes: 1024 }))) return { state: "incomplete", missing: "weights" };
180
+ const { script, weightsFolder } = stableAudioRuntimeModels(runtime);
181
+ if (!(await isFile(path.join(root, "scripts", script)))) return { state: "missing" };
182
+ if (!(await isFile(stableAudioPython(root, platform), { executable: platform !== "win32" }))) return { state: "incomplete", missing: "environment" };
183
+ for (const weight of stableAudioWeights(isStableAudioModel(model) ? model : DEFAULT_STABLE_AUDIO_MODEL, runtime)) {
184
+ if (!(await isFile(path.join(root, ...weightsFolder, weight), { minimumBytes: 1024 }))) return { state: "incomplete", missing: "weights" };
170
185
  }
171
186
  return { state: "ready" };
172
187
  }
@@ -175,9 +190,14 @@ export async function checkStableAudioInstall(root, { model = DEFAULT_STABLE_AUD
175
190
  const SKIP_SECONDS = 30;
176
191
  const OUTCOMES = Object.freeze(["completed", "skipped", "stopped", "replayed"]);
177
192
 
178
- // The stage lines the script always prints, which are the only progress a pipe receives.
179
- const STAGES = new Map([["1", "reading"], ["2", "reading"], ["3", "composing"], ["4", "decoding"], ["5", "writing"]]);
180
- const doneLine = /done\s+([\d.]+)s\s+wall\s+\S+\s+([\d.]+)s\s+audio.*?peak\s+RAM\s+([\d.]+)\s+(MB|GB)/u;
193
+ // The stage lines each script always prints, which are the only progress a pipe receives: five in the
194
+ // MLX build, three in the CPU build (text encoder, the model's eight steps, then the decoder and the WAV).
195
+ const STAGES = new Map([["1/5", "reading"], ["2/5", "reading"], ["3/5", "composing"], ["4/5", "decoding"], ["5/5", "writing"],
196
+ ["1/3", "reading"], ["2/3", "composing"], ["3/3", "decoding"]]);
197
+ // The CPU build's last line has no peak RAM.
198
+ const doneLine = /done\s+([\d.]+)s\s+wall\s+\S+\s+([\d.]+)s\s+audio(?:.*?peak\s+RAM\s+([\d.]+)\s+(MB|GB))?/u;
199
+ // The CPU build's threads: Stability's default of eight, or fewer on a smaller machine.
200
+ const cpuThreads = () => Math.max(1, Math.min(8, availableParallelism()));
181
201
 
182
202
  const generationError = (code, message) => Object.assign(new Error(message), { code });
183
203
 
@@ -231,8 +251,13 @@ export function createLocalGenerator({
231
251
  now = () => new Date(),
232
252
  // Whether the listener's library holds a made track: a stream never drops the audio of one they kept.
233
253
  keeps = () => false,
254
+ // Plays a score into a WAV (src/integrations/score), loaded only when a track is written as one.
255
+ renderScore = async (score, file, options) => (await import("../score/render-score.mjs")).renderScore(score, file, options),
234
256
  } = {}) {
235
- let current = { state: "unknown", enabled: false, install: "unknown", path: null, source: null, model: DEFAULT_STABLE_AUDIO_MODEL, managed: false };
257
+ // The build that makes the music here: "mlx" on Apple silicon's GPU, "tflite" on a CPU, null where none runs.
258
+ const runtime = stableAudioRuntime({ platform, arch, environment });
259
+ // The surfaces say "this Mac" or "this computer" by platform.
260
+ let current = { state: "unknown", enabled: false, install: "unknown", path: null, source: null, model: DEFAULT_STABLE_AUDIO_MODEL, managed: false, runtime, platform };
236
261
  let running = null;
237
262
  // The tracks made here, newest last, with what happened each time they played: the loop back
238
263
  // from listening reads them. Each track's outcomes.jsonl keeps them; the receipt never changes.
@@ -258,7 +283,7 @@ export function createLocalGenerator({
258
283
  checking ??= (async () => {
259
284
  try {
260
285
  const settings = await readGenerationSettings(environment, { platform, arch });
261
- const install = await checkStableAudioInstall(settings.path, { model: settings.model, platform, arch });
286
+ const install = await checkStableAudioInstall(settings.path, { model: settings.model, platform, arch, environment });
262
287
  return publish({
263
288
  state: !settings.enabled ? "off" : install.state,
264
289
  enabled: settings.enabled,
@@ -268,6 +293,8 @@ export function createLocalGenerator({
268
293
  source: settings.source,
269
294
  model: settings.model,
270
295
  managed: settings.source === "managed",
296
+ runtime,
297
+ platform,
271
298
  });
272
299
  } finally {
273
300
  checking = null;
@@ -301,15 +328,22 @@ export function createLocalGenerator({
301
328
  if (signal?.aborted) return reject(stopped());
302
329
  // The Python script itself, not Stability's ./sa3 wrapper: the wrapper wants uv on PATH and a
303
330
  // terminal, and its exec would leave a shell between this process and the one to stop.
304
- const child = spawnImpl(path.join(root, ".venv", "bin", "python"), [
305
- "scripts/sa3_mlx.py", "--prompt", prompt, "--dit", STABLE_AUDIO_MODELS[model].dit, "--decoder", STABLE_AUDIO_MODELS[model].decoder,
306
- "--seconds", String(seconds), "--seed", String(seed), "--steps", "8", "--out", out,
307
- ], {
331
+ const spec = stableAudioRuntimeModels(runtime).models[model];
332
+ const args = runtime === "tflite"
333
+ // The CPU build's precisions are named too, so the files Moondog downloaded are the ones it loads.
334
+ ? ["scripts/sa3_tflite.py", "--prompt", prompt, "--dit", spec.dit, "--decoder", spec.decoder,
335
+ "--dit-precision", spec.precision, "--decoder-precision", spec.precision,
336
+ "--seconds", String(seconds), "--seed", String(seed), "--steps", "8", "--threads", String(cpuThreads()), "--out", out]
337
+ : ["scripts/sa3_mlx.py", "--prompt", prompt, "--dit", spec.dit, "--decoder", spec.decoder,
338
+ "--seconds", String(seconds), "--seed", String(seed), "--steps", "8", "--out", out];
339
+ const child = spawnImpl(stableAudioPython(root, platform), args, {
308
340
  cwd: root,
309
341
  // Every choice is passed, so the script never waits on stdin for a missing one.
310
342
  stdio: ["ignore", "pipe", "pipe"],
311
343
  // Unbuffered, so stage lines arrive as they happen; offline, so missing weights fail instead of downloading.
312
344
  env: { ...environment, PYTHONUNBUFFERED: "1", HF_HUB_OFFLINE: "1" },
345
+ // No console window flashes up on Windows while the track is made.
346
+ windowsHide: true,
313
347
  });
314
348
  let output = "";
315
349
  let measured = null;
@@ -334,7 +368,7 @@ export function createLocalGenerator({
334
368
  stopping = setTimeout(() => child.kill("SIGKILL"), stoppingGraceMs);
335
369
  };
336
370
  const stop = () => kill(stopped());
337
- const timer = setTimeout(() => kill(generationError("generation_timed_out", "Stable Audio 3 took too long, so the track was stopped.")), generationTimeoutMs);
371
+ const timer = setTimeout(() => kill(generationError("generation_timed_out", "Stable Audio 3 took too long, so the track was stopped.")), generationTimeoutMs[runtime] ?? generationTimeoutMs.mlx);
338
372
  signal?.addEventListener("abort", stop, { once: true });
339
373
  child.stdout.setEncoding("utf8");
340
374
  child.stdout.on("data", (chunk) => {
@@ -342,12 +376,12 @@ export function createLocalGenerator({
342
376
  const lines = output.split("\n");
343
377
  output = lines.pop();
344
378
  for (const line of lines) {
345
- const stage = /\[(\d)\/5\]/u.exec(line)?.[1];
379
+ const stage = /\[(\d\/\d)\]/u.exec(line)?.[1];
346
380
  if (stage && STAGES.has(stage)) onProgress?.({ stage: STAGES.get(stage) });
347
381
  const done = doneLine.exec(line);
348
382
  if (done) {
349
- const peak = Number(done[3]) * (done[4] === "GB" ? 1024 : 1);
350
- measured = { wall_seconds: Number(done[1]), audio_seconds: Number(done[2]), peak_memory_mb: Math.round(peak) };
383
+ const peak = done[3] === undefined ? null : Number(done[3]) * (done[4] === "GB" ? 1024 : 1);
384
+ measured = { wall_seconds: Number(done[1]), audio_seconds: Number(done[2]), ...(peak === null ? {} : { peak_memory_mb: Math.round(peak) }) };
351
385
  }
352
386
  }
353
387
  });
@@ -370,6 +404,8 @@ export function createLocalGenerator({
370
404
  made_at: receipt.created_at,
371
405
  seconds: receipt.audio?.duration_seconds ?? receipt.generator?.seconds ?? null,
372
406
  sound: (Array.isArray(receipt.shaped_by) ? receipt.shaped_by : []).map((entry) => entry?.term).filter((term) => typeof term === "string").slice(0, 8),
407
+ // A track written as a score: its key, tempo and the sounds that play it.
408
+ ...(receipt.generator?.adapter === "dawn-score" ? { written_as_score: receipt.generator.score ?? {} } : {}),
373
409
  ...(receipt.stream ? { stream: true } : {}),
374
410
  // A stream keeps only its newest tracks' audio; the agent must not offer the rest again.
375
411
  ...(audioKept ? {} : { audio_kept: false }),
@@ -538,13 +574,16 @@ export function createLocalGenerator({
538
574
  const wav = path.join(temporary, "track.wav");
539
575
  onProgress?.({ stage: "starting" });
540
576
  const model = isStableAudioModel(status.model) ? status.model : DEFAULT_STABLE_AUDIO_MODEL;
541
- const measured = await run({ root: status.path, model, prompt, seconds, seed, out: wav }, { signal, onProgress });
577
+ // The CPU build's small model stops at two minutes, so a longer track is made as long as it can be.
578
+ const length = Math.min(seconds, stableAudioMaxSeconds(runtime, model));
579
+ const measured = await run({ root: status.path, model, prompt, seconds: length, seed, out: wav }, { signal, onProgress });
542
580
  const audio = await wavInfo(wav).catch(() => null);
543
581
  if (!audio || audio.duration_seconds <= 0) throw generationError("generation_failed", "Stable Audio 3 finished but wrote no playable track.");
544
582
  await chmod(wav, 0o600);
545
583
  // How loud it runs from start to end, which its cover draws (cover.mjs); kept after a stream drops the audio.
546
584
  const loudness = await readLoudness(wav).catch(() => null);
547
585
  const elapsed = Date.now() - started;
586
+ const spec = stableAudioRuntimeModels(runtime).models[model];
548
587
  const document = {
549
588
  receipt_version: "moondog-generated-track/1",
550
589
  generated_track_id: id,
@@ -553,8 +592,10 @@ export function createLocalGenerator({
553
592
  title,
554
593
  ...receipt,
555
594
  generator: {
556
- adapter: "stable-audio-3", adapter_version: 1, model: STABLE_AUDIO_MODELS[model].receipt, decoder: STABLE_AUDIO_MODELS[model].decoder,
557
- prompt, seconds, seed, steps: 8, cfg: 1, elapsed_ms: elapsed, ...(measured ? { measured } : {}),
595
+ adapter: "stable-audio-3", adapter_version: 1, model: spec.receipt, decoder: spec.decoder,
596
+ // Receipts without a runtime were made by the MLX build, the only one before.
597
+ ...(runtime === "tflite" ? { runtime: "tflite", precision: spec.precision } : {}),
598
+ prompt, seconds: length, seed, steps: 8, cfg: 1, elapsed_ms: elapsed, ...(measured ? { measured } : {}),
558
599
  license: "Stability AI Community License; outputs belong to the listener",
559
600
  },
560
601
  audio: { file: "track.wav", ...audio, ...(loudness ? { loudness } : {}) },
@@ -562,7 +603,63 @@ export function createLocalGenerator({
562
603
  await writeFile(path.join(temporary, "receipt.json"), `${JSON.stringify(document, null, 2)}\n`, { encoding: "utf8", mode: 0o600, flag: "wx" });
563
604
  await rename(temporary, path.join(folder, id));
564
605
  remember(document);
565
- return { id, title, seconds, seed, prompt, elapsed_ms: elapsed, duration_seconds: audio.duration_seconds, ...(measured ? { measured } : {}) };
606
+ return { id, title, seconds: length, seed, prompt, elapsed_ms: elapsed, duration_seconds: audio.duration_seconds, ...(measured ? { measured } : {}) };
607
+ } catch (error) {
608
+ await rm(temporary, { recursive: true, force: true }).catch(() => {});
609
+ throw error;
610
+ } finally {
611
+ running = null;
612
+ }
613
+ },
614
+ /**
615
+ * Keeps a track written as a score (src/integrations/score): score is what the renderer plays,
616
+ * sheet what the agent wrote, summary its key, tempo and sounds. The track gets the same folder,
617
+ * receipt and outcomes as one Stable Audio 3 made, so replay, the library and the cover treat it
618
+ * alike. It needs no install, so it does not ask whether Stable Audio 3 is on or ready.
619
+ * Returns { id, title, seconds, prompt, elapsed_ms, duration_seconds }.
620
+ */
621
+ async compose({ score, sheet, summary = {}, prompt, title, receipt = {} }, { signal, onProgress } = {}) {
622
+ if (running) throw generationError("generation_busy", "Moondog is already making a track. Wait for it to finish.");
623
+ if (!score || typeof score !== "object") throw generationError("generation_prompt_empty", "Nothing was made: there is no score.");
624
+ const id = randomUUID();
625
+ running = { id };
626
+ const folder = tracksDirectory();
627
+ const temporary = path.join(folder, `.${id}.tmp-${process.pid}-${randomBytes(6).toString("hex")}`);
628
+ const started = Date.now();
629
+ try {
630
+ if (signal?.aborted) throw stopped();
631
+ await mkdir(folder, { recursive: true, mode: 0o700 });
632
+ await chmod(folder, 0o700);
633
+ await mkdir(temporary, { mode: 0o700 });
634
+ const wav = path.join(temporary, "track.wav");
635
+ onProgress?.({ stage: "composing" });
636
+ const rendered = await renderScore(score, wav, { signal });
637
+ const audio = await wavInfo(wav).catch(() => null);
638
+ if (!audio || audio.duration_seconds <= 0) throw generationError("generation_failed", "The score was rendered but wrote no playable track.");
639
+ await chmod(wav, 0o600);
640
+ onProgress?.({ stage: "writing" });
641
+ const loudness = await readLoudness(wav).catch(() => null);
642
+ const elapsed = Date.now() - started;
643
+ const document = {
644
+ receipt_version: "moondog-generated-track/1",
645
+ generated_track_id: id,
646
+ moondog_id: `moondog:generated:${id}`,
647
+ created_at: now().toISOString(),
648
+ title,
649
+ ...receipt,
650
+ generator: {
651
+ adapter: "dawn-score", adapter_version: 1, renderer: "DAWN SDK offline renderer",
652
+ // The sheet is the track: Moondog can render it again or change a bar of it later.
653
+ prompt, score: summary, sheet, seconds: Math.round(audio.duration_seconds), elapsed_ms: elapsed,
654
+ ...(rendered?.clipped ? { clipped_samples: rendered.clipped } : {}),
655
+ license: "Written by Moondog and rendered with the DAWN SDK (MIT License); outputs belong to the listener",
656
+ },
657
+ audio: { file: "track.wav", ...audio, ...(loudness ? { loudness } : {}) },
658
+ };
659
+ await writeFile(path.join(temporary, "receipt.json"), `${JSON.stringify(document, null, 2)}\n`, { encoding: "utf8", mode: 0o600, flag: "wx" });
660
+ await rename(temporary, path.join(folder, id));
661
+ remember(document);
662
+ return { id, title, seconds: document.generator.seconds, prompt, elapsed_ms: elapsed, duration_seconds: audio.duration_seconds };
566
663
  } catch (error) {
567
664
  await rm(temporary, { recursive: true, force: true }).catch(() => {});
568
665
  throw error;