@gobing-ai/knowledge-kit 0.1.20 → 0.1.23

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (149) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/dist/board/collect/index.js +1 -0
  3. package/dist/board/daily-voice/index.js +1279 -261
  4. package/dist/board/itc/index.js +1 -0
  5. package/dist/index.js +13938 -8966
  6. package/package.json +1 -1
  7. package/plugins/generations/dailynews-gen/dist/index.js +285 -16
  8. package/plugins/generations/dailynews-gen/src/editorial-claims.ts +215 -0
  9. package/plugins/generations/dailynews-gen/src/index.ts +23 -4
  10. package/plugins/generations/dailynews-gen/src/script-builder.ts +10 -3
  11. package/plugins/generations/dailynews-gen/src/script-plan.ts +74 -14
  12. package/plugins/generations/gemini-tts/dist/index.js +47 -7
  13. package/plugins/generations/gemini-tts/src/gemini-client.ts +34 -6
  14. package/plugins/generations/music-gen/README.md +277 -0
  15. package/plugins/generations/music-gen/dist/index.js +23580 -0
  16. package/plugins/generations/music-gen/package.json +24 -0
  17. package/plugins/generations/music-gen/plugin.json +23 -0
  18. package/plugins/generations/music-gen/presets/SOURCE.md +39 -0
  19. package/plugins/generations/music-gen/presets/formats/clip.yaml +21 -0
  20. package/plugins/generations/music-gen/presets/formats/jingle.yaml +22 -0
  21. package/plugins/generations/music-gen/presets/formats/loop.yaml +21 -0
  22. package/plugins/generations/music-gen/presets/formats/song.yaml +36 -0
  23. package/plugins/generations/music-gen/presets/formats/underscore.yaml +22 -0
  24. package/plugins/generations/music-gen/presets/themes/ambient-tech.yaml +30 -0
  25. package/plugins/generations/music-gen/presets/themes/cinematic.yaml +30 -0
  26. package/plugins/generations/music-gen/presets/themes/lofi.yaml +30 -0
  27. package/plugins/generations/music-gen/presets/themes/synthwave.yaml +35 -0
  28. package/plugins/generations/music-gen/scripts/gen-preset-index.ts +181 -0
  29. package/plugins/generations/music-gen/scripts/resolve-preset.ts +64 -0
  30. package/plugins/generations/music-gen/src/adapter/index.ts +35 -0
  31. package/plugins/generations/music-gen/src/adapter/instance.ts +927 -0
  32. package/plugins/generations/music-gen/src/adapter/offline.ts +124 -0
  33. package/plugins/generations/music-gen/src/artifact.ts +223 -0
  34. package/plugins/generations/music-gen/src/audio/checks.ts +618 -0
  35. package/plugins/generations/music-gen/src/audio/master.ts +267 -0
  36. package/plugins/generations/music-gen/src/audio/measure.ts +507 -0
  37. package/plugins/generations/music-gen/src/audio/profile.ts +131 -0
  38. package/plugins/generations/music-gen/src/audio.ts +122 -0
  39. package/plugins/generations/music-gen/src/brief.ts +191 -0
  40. package/plugins/generations/music-gen/src/config.ts +451 -0
  41. package/plugins/generations/music-gen/src/content.ts +199 -0
  42. package/plugins/generations/music-gen/src/digest.ts +100 -0
  43. package/plugins/generations/music-gen/src/index.ts +147 -0
  44. package/plugins/generations/music-gen/src/job.ts +131 -0
  45. package/plugins/generations/music-gen/src/plugin.ts +371 -0
  46. package/plugins/generations/music-gen/src/presets.ts +951 -0
  47. package/plugins/generations/music-gen/src/render.ts +87 -0
  48. package/plugins/generations/music-gen/src/request.ts +102 -0
  49. package/plugins/generations/music-gen/src/spend.ts +495 -0
  50. package/plugins/generations/music-gen/tsconfig.json +8 -0
  51. package/plugins/generations/omni-voice-gen/uv.toml +5 -0
  52. package/plugins/generations/vibe-voice-tts/README.md +64 -0
  53. package/plugins/generations/vibe-voice-tts/dist/index.js +14259 -0
  54. package/plugins/generations/vibe-voice-tts/package.json +16 -0
  55. package/plugins/generations/vibe-voice-tts/plugin.json +6 -0
  56. package/plugins/generations/vibe-voice-tts/profiles.json +10 -0
  57. package/plugins/generations/vibe-voice-tts/pyproject.toml +9 -0
  58. package/plugins/generations/vibe-voice-tts/python/worker.py +566 -0
  59. package/plugins/generations/vibe-voice-tts/src/index.ts +88 -0
  60. package/plugins/generations/vibe-voice-tts/src/vibevoice-client.ts +828 -0
  61. package/plugins/generations/vibe-voice-tts/tsconfig.json +8 -0
  62. package/plugins/generations/vibe-voice-tts/uv.lock +1767 -0
  63. package/plugins/generations/vibe-voice-tts/uv.toml +4 -0
  64. package/plugins/generations/voice-gen/dist/index.js +31 -1
  65. package/plugins/generations/voice-gen/src/voicebox-client.ts +50 -1
  66. package/plugins/generations/voxcpm-tts/dist/index.js +81 -9
  67. package/plugins/generations/voxcpm-tts/python/worker.py +9 -0
  68. package/plugins/generations/voxcpm-tts/src/index.ts +41 -0
  69. package/plugins/generations/voxcpm-tts/src/voxcpm-client.ts +32 -11
  70. package/plugins/generations/voxcpm-tts/uv.toml +5 -0
  71. package/plugins/kk/README.md +21 -0
  72. package/plugins/kk/decisions/kk-safety.yaml +5 -2
  73. package/plugins/kk/plugin.json +1 -1
  74. package/plugins/kk/schedules/kk-serve.launchd.plist.tmpl +14 -2
  75. package/plugins/kk/scripts/cover-compositor.ts +380 -32
  76. package/plugins/kk/scripts/daily-cover-mock.ts +40 -3
  77. package/plugins/kk/scripts/daily-stages.ts +933 -60
  78. package/plugins/kk/scripts/episode-identity.ts +180 -0
  79. package/plugins/kk/scripts/kk-workflow-stages.ts +111 -12
  80. package/plugins/kk/scripts/music-stages.ts +624 -0
  81. package/plugins/kk/scripts/news-editorial-ledger.ts +906 -0
  82. package/plugins/kk/scripts/safety-artifact-check.ts +28 -5
  83. package/plugins/kk/scripts/source-citation.ts +187 -0
  84. package/plugins/kk/scripts/topic-selection-attempts.ts +446 -0
  85. package/plugins/kk/scripts/topic-selection-calibration.ts +161 -0
  86. package/plugins/kk/skills/content-judge/SKILL.md +11 -6
  87. package/plugins/kk/skills/content-judge/references/music-quality-rubric.md +147 -0
  88. package/plugins/kk/skills/content-judge/references/rubrics.md +15 -0
  89. package/plugins/kk/skills/content-safety/SKILL.md +12 -0
  90. package/plugins/kk/skills/music-authoring/SKILL.md +276 -0
  91. package/plugins/kk/skills/music-authoring/references/judge-input.md +117 -0
  92. package/plugins/kk/skills/news-editorial/SKILL.md +102 -15
  93. package/plugins/kk/skills/news-editorial/references/selection.md +4 -0
  94. package/plugins/kk/skills/news-editorial/references/style-contract.zh.md +58 -11
  95. package/plugins/kk/workflows/kk-daily-ai-voice.yaml +12 -11
  96. package/plugins/kk/workflows/kk-daily-ai-voice2.yaml +13 -12
  97. package/plugins/kk/workflows/kk-daily-safety.yaml +12 -10
  98. package/plugins/kk/workflows/kk-music.yaml +332 -0
  99. package/plugins/kk/workflows/kk-news-generate.yaml +81 -6
  100. package/plugins/kk/workflows/kk-publish.yaml +4 -1
  101. package/plugins/publishings/bilibili-pub/dist/index.js +11 -1
  102. package/plugins/publishings/bilibili-pub/dist/profile-check.js +11 -1
  103. package/plugins/publishings/cnblogs-pub/dist/index.js +11 -1
  104. package/plugins/publishings/cnblogs-pub/dist/profile-check.js +11 -1
  105. package/plugins/publishings/csdn-pub/dist/index.js +11 -1
  106. package/plugins/publishings/csdn-pub/dist/profile-check.js +11 -1
  107. package/plugins/publishings/infoq-pub/dist/index.js +11 -1
  108. package/plugins/publishings/infoq-pub/dist/profile-check.js +11 -1
  109. package/plugins/publishings/jike-pub/dist/index.js +11 -1
  110. package/plugins/publishings/jike-pub/dist/profile-check.js +11 -1
  111. package/plugins/publishings/juejin-pub/dist/index.js +11 -1
  112. package/plugins/publishings/juejin-pub/dist/profile-check.js +11 -1
  113. package/plugins/publishings/linkedin-pub/dist/index.js +62 -10
  114. package/plugins/publishings/linkedin-pub/dist/profile-check.js +16 -1
  115. package/plugins/publishings/linkedin-pub/src/index.ts +99 -12
  116. package/plugins/publishings/podcast-pub/dist/index.js +586 -20
  117. package/plugins/publishings/podcast-pub/src/corrections.ts +509 -0
  118. package/plugins/publishings/podcast-pub/src/index.ts +257 -5
  119. package/plugins/publishings/podcast-pub/src/show-notes-brief.ts +240 -0
  120. package/plugins/publishings/podcast-pub/src/show-notes.ts +69 -13
  121. package/plugins/publishings/shipinhao-pub/dist/index.js +59 -8
  122. package/plugins/publishings/shipinhao-pub/dist/profile-check.js +11 -1
  123. package/plugins/publishings/shipinhao-pub/src/audio-flow.ts +105 -6
  124. package/plugins/publishings/sspai-pub/dist/index.js +11 -1
  125. package/plugins/publishings/sspai-pub/dist/profile-check.js +11 -1
  126. package/plugins/publishings/substack-pub/dist/index.js +11 -1
  127. package/plugins/publishings/substack-pub/dist/profile-check.js +11 -1
  128. package/plugins/publishings/surfdash-pub/dist/index.js +80 -24
  129. package/plugins/publishings/surfdash-pub/src/digest-check.ts +7 -3
  130. package/plugins/publishings/surfdash-pub/src/index.ts +107 -18
  131. package/plugins/publishings/surfdash-pub/src/patch.ts +21 -3
  132. package/plugins/publishings/surfdash-pub/src/topic-claims.ts +3 -1
  133. package/plugins/publishings/threads-pub/dist/index.js +58 -6
  134. package/plugins/publishings/threads-pub/dist/profile-check.js +18 -2
  135. package/plugins/publishings/threads-pub/src/post-rail.ts +101 -4
  136. package/plugins/publishings/wechatmp-pub/dist/index.js +105 -35
  137. package/plugins/publishings/wechatmp-pub/dist/profile-check.js +11 -1
  138. package/plugins/publishings/wechatmp-pub/src/cgi-draft.ts +87 -53
  139. package/plugins/publishings/wechatmp-pub/src/enrich.ts +61 -3
  140. package/plugins/publishings/wechatmp-pub/src/flow.ts +28 -0
  141. package/plugins/publishings/weibo-pub/dist/index.js +11 -1
  142. package/plugins/publishings/weibo-pub/dist/profile-check.js +11 -1
  143. package/plugins/publishings/x-pub/dist/index.js +95 -10
  144. package/plugins/publishings/x-pub/dist/profile-check.js +11 -1
  145. package/plugins/publishings/x-pub/src/post-rail.ts +154 -12
  146. package/plugins/publishings/xhs-pub/dist/index.js +11 -1
  147. package/plugins/publishings/xhs-pub/dist/profile-check.js +11 -1
  148. package/plugins/publishings/xiaoyuzhou-pub/dist/index.js +11 -1
  149. package/plugins/publishings/xiaoyuzhou-pub/dist/profile-check.js +11 -1
@@ -0,0 +1,124 @@
1
+ import { silentWav } from '../audio';
2
+ import type { MusicGenerateRequest } from '../request';
3
+ import type {
4
+ AnalysisOutcome,
5
+ GeneratedTake,
6
+ InstanceTake,
7
+ MusicAnalysis,
8
+ MusicInstance,
9
+ UnclaimedTake,
10
+ } from './instance';
11
+
12
+ /**
13
+ * Offline adapter (task 0398 R4): `KK_MUSIC_DRY_RUN=1`.
14
+ *
15
+ * Deterministic silent WAV, synthetic manifest, synthetic analysis — and **zero
16
+ * network calls by construction**: this class holds no fetch seam and no socket.
17
+ * It is the default for the plugin's whole test suite, so a paid call can never
18
+ * be made from a test.
19
+ *
20
+ * Everything it emits is a *synthetic* artefact and says so: the generation id
21
+ * is `offline-take-<n>`, the analysis summary starts with `offline:`, and
22
+ * `Content.metadata.dryRun` is `true`, so an operator can never mistake a
23
+ * dry-run take for a delivered one.
24
+ */
25
+
26
+ /** Generation-id prefix of a synthetic take. */
27
+ export const OFFLINE_ID_PREFIX = 'offline-take-';
28
+
29
+ /** Synthetic audio URL scheme: a dry run has no reachable instance, and the URL says so. */
30
+ export const OFFLINE_AUDIO_SCHEME = 'offline';
31
+
32
+ /** The synthetic audio URL of one take (the `Content.references` provenance slot, marked synthetic). */
33
+ export function offlineAudioUrl(instanceId: string): string {
34
+ return `${OFFLINE_AUDIO_SCHEME}://generations/${encodeURIComponent(instanceId)}/audio`;
35
+ }
36
+
37
+ /**
38
+ * Fixed `generatedAt` for every synthetic take. A constant, not a clock read:
39
+ * two dry runs must produce identical sidecars byte for byte.
40
+ */
41
+ export const OFFLINE_GENERATED_AT = '1970-01-01T00:00:00.000Z';
42
+
43
+ /** Synthetic analysis summary prefix — proves in one glance the analysis was not paid for. */
44
+ export const OFFLINE_ANALYSIS_SUMMARY = 'offline: synthetic analysis, no instance was called';
45
+
46
+ /** Build the synthetic analysis for one take. */
47
+ export function offlineAnalysis(model: string): MusicAnalysis {
48
+ return {
49
+ summary: OFFLINE_ANALYSIS_SUMMARY,
50
+ model,
51
+ provider: 'offline',
52
+ durationSeconds: 1,
53
+ };
54
+ }
55
+
56
+ /** The offline instance: an in-memory library, no HTTP. */
57
+ export class OfflineInstance implements MusicInstance {
58
+ readonly provider = 'offline';
59
+
60
+ /** Synthetic library, in generate order. */
61
+ private readonly library: InstanceTake[] = [];
62
+
63
+ /** Library URL for one synthetic generation (there is no real route — the id rides the host). */
64
+ libraryUrl(instanceId: string): string {
65
+ return `${OFFLINE_AUDIO_SCHEME}://generations/${encodeURIComponent(instanceId)}`;
66
+ }
67
+
68
+ /** One deterministic take: the same request always yields the same bytes. */
69
+ async generate(request: MusicGenerateRequest): Promise<GeneratedTake> {
70
+ const id = `${OFFLINE_ID_PREFIX}${String(this.library.length + 1)}`;
71
+ const bytes = silentWav();
72
+ const analysis = offlineAnalysis(request.model);
73
+ const take: InstanceTake = {
74
+ id,
75
+ prompt: request.prompt,
76
+ model: request.model,
77
+ generatedAt: OFFLINE_GENERATED_AT,
78
+ audioUrl: offlineAudioUrl(id),
79
+ ...(request.durationTarget === undefined ? {} : { durationTarget: request.durationTarget }),
80
+ language: request.language,
81
+ batchCount: request.batchCount,
82
+ title: request.title,
83
+ format: request.format,
84
+ analysis,
85
+ };
86
+ this.library.push(take);
87
+ const unclaimed: UnclaimedTake[] = [];
88
+ return {
89
+ ...take,
90
+ prompt: request.prompt,
91
+ model: request.model,
92
+ bytes,
93
+ format: 'wav',
94
+ contentType: 'audio/wav',
95
+ adoptedByReconciliation: false,
96
+ unclaimed,
97
+ elapsedMs: 0,
98
+ };
99
+ }
100
+
101
+ /** The synthetic library, in generate order. */
102
+ async listGenerations(): Promise<InstanceTake[]> {
103
+ return this.library.map((take) => ({ ...take }));
104
+ }
105
+
106
+ /** Synthetic analysis; `cached` is true because the synthetic manifest already carries it. */
107
+ async analyze(instanceId: string): Promise<AnalysisOutcome> {
108
+ const take = this.library.find((entry) => entry.id === instanceId);
109
+ if (take === undefined) {
110
+ throw new Error(`offline adapter: unknown generation ${instanceId} (no instance was called)`);
111
+ }
112
+ return {
113
+ instanceId,
114
+ analysis: take.analysis ?? offlineAnalysis(String(take.model ?? '')),
115
+ cached: true,
116
+ paid: false,
117
+ };
118
+ }
119
+ }
120
+
121
+ /** Build the offline adapter. */
122
+ export function createOfflineInstance(): OfflineInstance {
123
+ return new OfflineInstance();
124
+ }
@@ -0,0 +1,223 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { readFile, writeFile } from 'node:fs/promises';
3
+ import { extname } from 'node:path';
4
+ import type { UnclaimedTake } from './adapter/instance';
5
+ import type { AudioFormat, MusicModel } from './brief';
6
+ import type { MusicDigestInput } from './digest';
7
+ import type { MusicGenerateRequest } from './request';
8
+
9
+ /**
10
+ * Artifact naming and persistence (task 0398 R6).
11
+ *
12
+ * **Naming.** `<slug>-<model>-<instanceId>.<ext>`: the slug is the title, the
13
+ * model is the instance's own selector and the id is the instance generation id,
14
+ * so every file is traceable back to the instance library by name alone and two
15
+ * takes of the same brief cannot collide. One sidecar per take:
16
+ * `<artifact>.take.json`.
17
+ *
18
+ * **Boundary.** A take is written into the job's run directory (the `--out`
19
+ * directory) and the instance's `generations/` library is *never* mirrored into a
20
+ * kk workspace: kk records what the workflow needs (digest, instance id, model,
21
+ * unit price, adoption flag) and links the rest.
22
+ *
23
+ * **Why `node:fs` lives here.** The ts-runtime `FileSystem` seam is text-only, so
24
+ * binary audio bytes (and the reference-image bytes the digest hashes) cannot go
25
+ * through it. This file is the plugin's single binary-IO seam, allowlisted in
26
+ * `.spur/rules/strict/runtime-boundaries.yaml` exactly as `image-gen/src/bytes.ts`
27
+ * and `voice-gen/src/index.ts` are.
28
+ */
29
+
30
+ /** Longest slug the artifact name carries before it is truncated. */
31
+ export const MAX_SLUG_LENGTH = 48;
32
+
33
+ /** Fallback slug when a title has no usable characters. */
34
+ export const FALLBACK_SLUG = 'music';
35
+
36
+ /** Content type of a reference image, by extension. */
37
+ const IMAGE_MIME: Readonly<Record<string, string>> = {
38
+ '.png': 'image/png',
39
+ '.jpg': 'image/jpeg',
40
+ '.jpeg': 'image/jpeg',
41
+ '.webp': 'image/webp',
42
+ '.gif': 'image/gif',
43
+ };
44
+
45
+ /**
46
+ * Kebab-case a title into a filename-safe slug: ASCII alphanumerics kept,
47
+ * everything else collapsed to single dashes, lowercased, truncated on a word
48
+ * boundary where possible.
49
+ */
50
+ export function takeSlug(title: string): string {
51
+ const slug = title
52
+ .normalize('NFKD')
53
+ .replace(/[\u0300-\u036f]/g, '')
54
+ .toLowerCase()
55
+ .replace(/[^a-z0-9]+/g, '-')
56
+ .replace(/^-+/, '')
57
+ .replace(/-+$/, '');
58
+ if (slug === '') {
59
+ return FALLBACK_SLUG;
60
+ }
61
+ if (slug.length <= MAX_SLUG_LENGTH) {
62
+ return slug;
63
+ }
64
+ const truncated = slug.slice(0, MAX_SLUG_LENGTH);
65
+ const lastDash = truncated.lastIndexOf('-');
66
+ return lastDash > 0 ? truncated.slice(0, lastDash) : truncated;
67
+ }
68
+
69
+ /**
70
+ * Make an instance generation id safe for a filename. Ids come from the
71
+ * instance, so this is a boundary guard, not a formatter: path separators and
72
+ * `..` must never reach the artifact name.
73
+ */
74
+ export function safeInstanceId(instanceId: string): string {
75
+ const cleaned = instanceId
76
+ .replace(/[^A-Za-z0-9._-]+/g, '-')
77
+ .replace(/^[.-]+/, '')
78
+ .replace(/[.-]+$/, '');
79
+ if (cleaned === '' || cleaned.includes('..')) {
80
+ throw new Error(`instance generation id ${JSON.stringify(instanceId)} cannot be used in an artifact name`);
81
+ }
82
+ return cleaned;
83
+ }
84
+
85
+ /** `<slug>-<model>-<instanceId>.<ext>` — the artifact filename for one take. */
86
+ export function takeArtifactName(
87
+ slug: string,
88
+ model: MusicModel | string,
89
+ instanceId: string,
90
+ format: AudioFormat,
91
+ ): string {
92
+ return `${slug}-${model}-${safeInstanceId(instanceId)}.${format}`;
93
+ }
94
+
95
+ /** Suffix that marks a take sidecar; the spend guard's dedupe scan keys off it (task 0400 R3). */
96
+ export const TAKE_SIDECAR_SUFFIX = '.take.json';
97
+
98
+ /** `<artifact>.take.json` — the sidecar filename for one take. */
99
+ export function takeSidecarName(artifactFileName: string): string {
100
+ return `${artifactFileName}${TAKE_SIDECAR_SUFFIX}`;
101
+ }
102
+
103
+ /** One take's sidecar. Field ownership is per key so 0400 and 0405 extend it, never replace it. */
104
+ export interface TakeSidecar {
105
+ /** SHA-256 of the canonical digest JSON (0397). */
106
+ digest: string;
107
+ /** The canonical digest input (0397) — 0400 compares against it. */
108
+ digestInput: MusicDigestInput;
109
+ instanceId: string;
110
+ model: string;
111
+ /** Delivered container, detected from the bytes (never the requested one). */
112
+ format: AudioFormat;
113
+ /** The exact request body sent to the instance. */
114
+ request: MusicGenerateRequest;
115
+ /** `audio_format` as kk resolved it (the request's `format`). */
116
+ requestedFormat: AudioFormat;
117
+ language: string;
118
+ durationTarget?: string;
119
+ /** Echoed exactly as the instance recorded it; absent when the manifest lacked it. */
120
+ batchCount?: number;
121
+ takeIndex: number;
122
+ /** Unit price charged for this take (`null` when the model is unpriced). */
123
+ unitPrice: number | null;
124
+ adoptedByReconciliation: boolean;
125
+ /** Later library takes that matched the same request: the operator's spend visibility. */
126
+ unclaimed: UnclaimedTake[];
127
+ forced: boolean;
128
+ reason: string | null;
129
+ /** Workflow run this take belongs to, when the caller knows it (0400 R4). */
130
+ runId?: string;
131
+ createdAt: string;
132
+ generatedAt?: string;
133
+ /** Absolute path of the artifact this sidecar describes. */
134
+ artifactPath: string;
135
+ /** The instance audio URL, when the instance served one. */
136
+ audioUrl?: string;
137
+ /** Detectably a dry-run artifact: no instance was called. */
138
+ dryRun?: true;
139
+ }
140
+
141
+ /** Everything {@link buildTakeSidecar} needs. */
142
+ export interface TakeSidecarOptions {
143
+ digest: { sha256: string; input: MusicDigestInput };
144
+ request: MusicGenerateRequest;
145
+ instanceId: string;
146
+ model: string;
147
+ format: AudioFormat;
148
+ takeIndex: number;
149
+ artifactPath: string;
150
+ unitPrice: number | null;
151
+ adoptedByReconciliation: boolean;
152
+ unclaimed: UnclaimedTake[];
153
+ forced: boolean;
154
+ reason?: string;
155
+ /** Workflow run id, recorded verbatim when present (0400 R4). */
156
+ runId?: string;
157
+ /** Injected clock so a test can pin `createdAt`. */
158
+ now?: () => number;
159
+ language: string;
160
+ durationTarget?: string;
161
+ batchCount?: number;
162
+ generatedAt?: string;
163
+ audioUrl?: string;
164
+ dryRun?: boolean;
165
+ }
166
+
167
+ /** Build one take sidecar (0397 digest + instance provenance + 0400/0405 slots). */
168
+ export function buildTakeSidecar(options: TakeSidecarOptions): TakeSidecar {
169
+ const createdAt = new Date((options.now ?? Date.now)()).toISOString();
170
+ return {
171
+ digest: options.digest.sha256,
172
+ digestInput: options.digest.input,
173
+ instanceId: options.instanceId,
174
+ model: options.model,
175
+ format: options.format,
176
+ request: options.request,
177
+ requestedFormat: options.request.format,
178
+ language: options.language,
179
+ ...(options.durationTarget === undefined ? {} : { durationTarget: options.durationTarget }),
180
+ ...(options.batchCount === undefined ? {} : { batchCount: options.batchCount }),
181
+ takeIndex: options.takeIndex,
182
+ unitPrice: options.unitPrice,
183
+ adoptedByReconciliation: options.adoptedByReconciliation,
184
+ unclaimed: options.unclaimed,
185
+ forced: options.forced,
186
+ reason: options.reason ?? null,
187
+ ...(options.runId === undefined ? {} : { runId: options.runId }),
188
+ createdAt,
189
+ ...(options.generatedAt === undefined ? {} : { generatedAt: options.generatedAt }),
190
+ artifactPath: options.artifactPath,
191
+ ...(options.audioUrl === undefined ? {} : { audioUrl: options.audioUrl }),
192
+ ...(options.dryRun === true ? { dryRun: true } : {}),
193
+ };
194
+ }
195
+
196
+ /** Serialize a sidecar the way every kk artifact is written: 4-space JSON plus one trailing newline. */
197
+ export function serializeTakeSidecar(sidecar: TakeSidecar): string {
198
+ return `${JSON.stringify(sidecar, null, 4)}\n`;
199
+ }
200
+
201
+ /**
202
+ * Write audio bytes. Deliberately the only binary writer in the plugin (see the
203
+ * module header): the audio format is chosen by the instance, not by kk.
204
+ */
205
+ export async function writeAudioBytes(path: string, bytes: Uint8Array): Promise<void> {
206
+ await writeFile(path, bytes);
207
+ }
208
+
209
+ /** Read reference-image bytes (the digest hashes their content, 0397 §7). */
210
+ export async function readImageBytes(path: string): Promise<Uint8Array> {
211
+ return new Uint8Array(await readFile(path));
212
+ }
213
+
214
+ /** SHA-256 hex of a byte buffer. */
215
+ export function sha256Hex(bytes: Uint8Array): string {
216
+ return createHash('sha256').update(bytes).digest('hex');
217
+ }
218
+
219
+ /** Encode reference-image bytes for the wire (`data:` URL) and keep the mime honest. */
220
+ export function imageDataUrl(path: string, bytes: Uint8Array): string {
221
+ const mime = IMAGE_MIME[extname(path).toLowerCase()] ?? 'application/octet-stream';
222
+ return `data:${mime};base64,${Buffer.from(bytes).toString('base64')}`;
223
+ }