@gobing-ai/knowledge-kit 0.1.20 → 0.1.22

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 (115) 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 +13893 -8995
  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/music-gen/README.md +277 -0
  13. package/plugins/generations/music-gen/dist/index.js +23544 -0
  14. package/plugins/generations/music-gen/package.json +24 -0
  15. package/plugins/generations/music-gen/plugin.json +23 -0
  16. package/plugins/generations/music-gen/presets/SOURCE.md +39 -0
  17. package/plugins/generations/music-gen/presets/formats/clip.yaml +21 -0
  18. package/plugins/generations/music-gen/presets/formats/jingle.yaml +22 -0
  19. package/plugins/generations/music-gen/presets/formats/loop.yaml +21 -0
  20. package/plugins/generations/music-gen/presets/formats/song.yaml +31 -0
  21. package/plugins/generations/music-gen/presets/formats/underscore.yaml +22 -0
  22. package/plugins/generations/music-gen/presets/themes/ambient-tech.yaml +30 -0
  23. package/plugins/generations/music-gen/presets/themes/cinematic.yaml +30 -0
  24. package/plugins/generations/music-gen/presets/themes/lofi.yaml +30 -0
  25. package/plugins/generations/music-gen/presets/themes/synthwave.yaml +30 -0
  26. package/plugins/generations/music-gen/scripts/gen-preset-index.ts +181 -0
  27. package/plugins/generations/music-gen/scripts/resolve-preset.ts +64 -0
  28. package/plugins/generations/music-gen/src/adapter/index.ts +35 -0
  29. package/plugins/generations/music-gen/src/adapter/instance.ts +904 -0
  30. package/plugins/generations/music-gen/src/adapter/offline.ts +124 -0
  31. package/plugins/generations/music-gen/src/artifact.ts +223 -0
  32. package/plugins/generations/music-gen/src/audio/checks.ts +618 -0
  33. package/plugins/generations/music-gen/src/audio/master.ts +267 -0
  34. package/plugins/generations/music-gen/src/audio/measure.ts +507 -0
  35. package/plugins/generations/music-gen/src/audio/profile.ts +131 -0
  36. package/plugins/generations/music-gen/src/audio.ts +122 -0
  37. package/plugins/generations/music-gen/src/brief.ts +191 -0
  38. package/plugins/generations/music-gen/src/config.ts +451 -0
  39. package/plugins/generations/music-gen/src/content.ts +199 -0
  40. package/plugins/generations/music-gen/src/digest.ts +100 -0
  41. package/plugins/generations/music-gen/src/index.ts +147 -0
  42. package/plugins/generations/music-gen/src/job.ts +131 -0
  43. package/plugins/generations/music-gen/src/plugin.ts +371 -0
  44. package/plugins/generations/music-gen/src/presets.ts +918 -0
  45. package/plugins/generations/music-gen/src/render.ts +87 -0
  46. package/plugins/generations/music-gen/src/request.ts +102 -0
  47. package/plugins/generations/music-gen/src/spend.ts +495 -0
  48. package/plugins/generations/music-gen/tsconfig.json +8 -0
  49. package/plugins/kk/plugin.json +1 -1
  50. package/plugins/kk/schedules/kk-serve.launchd.plist.tmpl +2 -1
  51. package/plugins/kk/scripts/cover-compositor.ts +380 -32
  52. package/plugins/kk/scripts/daily-cover-mock.ts +40 -3
  53. package/plugins/kk/scripts/daily-stages.ts +659 -20
  54. package/plugins/kk/scripts/episode-identity.ts +180 -0
  55. package/plugins/kk/scripts/kk-workflow-stages.ts +37 -1
  56. package/plugins/kk/scripts/music-stages.ts +624 -0
  57. package/plugins/kk/scripts/news-editorial-ledger.ts +906 -0
  58. package/plugins/kk/scripts/source-citation.ts +187 -0
  59. package/plugins/kk/scripts/topic-selection-attempts.ts +446 -0
  60. package/plugins/kk/scripts/topic-selection-calibration.ts +161 -0
  61. package/plugins/kk/skills/content-judge/SKILL.md +11 -6
  62. package/plugins/kk/skills/content-judge/references/music-quality-rubric.md +147 -0
  63. package/plugins/kk/skills/content-judge/references/rubrics.md +15 -0
  64. package/plugins/kk/skills/content-safety/SKILL.md +12 -0
  65. package/plugins/kk/skills/music-authoring/SKILL.md +276 -0
  66. package/plugins/kk/skills/music-authoring/references/judge-input.md +117 -0
  67. package/plugins/kk/skills/news-editorial/SKILL.md +102 -15
  68. package/plugins/kk/skills/news-editorial/references/selection.md +4 -0
  69. package/plugins/kk/skills/news-editorial/references/style-contract.zh.md +58 -11
  70. package/plugins/kk/workflows/kk-daily-ai-voice.yaml +8 -8
  71. package/plugins/kk/workflows/kk-daily-ai-voice2.yaml +7 -7
  72. package/plugins/kk/workflows/kk-music.yaml +328 -0
  73. package/plugins/kk/workflows/kk-news-generate.yaml +58 -3
  74. package/plugins/publishings/bilibili-pub/dist/index.js +11 -1
  75. package/plugins/publishings/bilibili-pub/dist/profile-check.js +11 -1
  76. package/plugins/publishings/cnblogs-pub/dist/index.js +11 -1
  77. package/plugins/publishings/cnblogs-pub/dist/profile-check.js +11 -1
  78. package/plugins/publishings/csdn-pub/dist/index.js +11 -1
  79. package/plugins/publishings/csdn-pub/dist/profile-check.js +11 -1
  80. package/plugins/publishings/infoq-pub/dist/index.js +11 -1
  81. package/plugins/publishings/infoq-pub/dist/profile-check.js +11 -1
  82. package/plugins/publishings/jike-pub/dist/index.js +11 -1
  83. package/plugins/publishings/jike-pub/dist/profile-check.js +11 -1
  84. package/plugins/publishings/juejin-pub/dist/index.js +11 -1
  85. package/plugins/publishings/juejin-pub/dist/profile-check.js +11 -1
  86. package/plugins/publishings/linkedin-pub/dist/index.js +11 -1
  87. package/plugins/publishings/linkedin-pub/dist/profile-check.js +11 -1
  88. package/plugins/publishings/podcast-pub/dist/index.js +586 -20
  89. package/plugins/publishings/podcast-pub/src/corrections.ts +509 -0
  90. package/plugins/publishings/podcast-pub/src/index.ts +257 -5
  91. package/plugins/publishings/podcast-pub/src/show-notes-brief.ts +240 -0
  92. package/plugins/publishings/podcast-pub/src/show-notes.ts +69 -13
  93. package/plugins/publishings/shipinhao-pub/dist/index.js +59 -8
  94. package/plugins/publishings/shipinhao-pub/dist/profile-check.js +11 -1
  95. package/plugins/publishings/shipinhao-pub/src/audio-flow.ts +105 -6
  96. package/plugins/publishings/sspai-pub/dist/index.js +11 -1
  97. package/plugins/publishings/sspai-pub/dist/profile-check.js +11 -1
  98. package/plugins/publishings/substack-pub/dist/index.js +11 -1
  99. package/plugins/publishings/substack-pub/dist/profile-check.js +11 -1
  100. package/plugins/publishings/surfdash-pub/dist/index.js +72 -20
  101. package/plugins/publishings/surfdash-pub/src/digest-check.ts +7 -3
  102. package/plugins/publishings/surfdash-pub/src/index.ts +100 -17
  103. package/plugins/publishings/surfdash-pub/src/topic-claims.ts +3 -1
  104. package/plugins/publishings/threads-pub/dist/index.js +11 -1
  105. package/plugins/publishings/threads-pub/dist/profile-check.js +11 -1
  106. package/plugins/publishings/wechatmp-pub/dist/index.js +11 -1
  107. package/plugins/publishings/wechatmp-pub/dist/profile-check.js +11 -1
  108. package/plugins/publishings/weibo-pub/dist/index.js +11 -1
  109. package/plugins/publishings/weibo-pub/dist/profile-check.js +11 -1
  110. package/plugins/publishings/x-pub/dist/index.js +11 -1
  111. package/plugins/publishings/x-pub/dist/profile-check.js +11 -1
  112. package/plugins/publishings/xhs-pub/dist/index.js +11 -1
  113. package/plugins/publishings/xhs-pub/dist/profile-check.js +11 -1
  114. package/plugins/publishings/xiaoyuzhou-pub/dist/index.js +11 -1
  115. package/plugins/publishings/xiaoyuzhou-pub/dist/profile-check.js +11 -1
@@ -0,0 +1,451 @@
1
+ import { homedir } from 'node:os';
2
+ import { isAbsolute, join, resolve } from 'node:path';
3
+ import { createNodeFileSystem, type FileSystem } from '@gobing-ai/ts-runtime';
4
+ import type { DeliveryProfileConfig, DeliveryProfileOverride } from './audio/profile';
5
+ import { AUDIO_FORMATS, MUSIC_MODELS, type MusicModel } from './brief';
6
+ import { resolveTakesCap } from './spend';
7
+
8
+ /**
9
+ * Music plugin configuration (task 0398 R2; contract frozen by
10
+ * `docs/design/music-gen.md` §6.1).
11
+ *
12
+ * One reader, three layers, no second config file: `environment override >
13
+ * music config key > documented default`. The config file is the existing kk
14
+ * user config (`KK_CONFIG`, else `~/.config/kk/config.yaml`) — the same
15
+ * document `packages/kk-store/src/config.ts` reads — with the plugin's settings
16
+ * under `music:`. Nothing machine-specific is committed.
17
+ *
18
+ * Key spellings: the frozen 0397 table names `music.instance.url` /
19
+ * `music.instance.timeoutMs` / `music.instance.connectTimeoutMs`, while 0401 R2
20
+ * names the flat `music.baseUrl` / `music.timeoutMs` / `music.takesCap`. Both
21
+ * spellings are read (flat wins when both appear) so the CLI that 0401 ships and
22
+ * the contract 0397 froze cannot disagree — the one behaviour this file adds
23
+ * beyond the table.
24
+ */
25
+
26
+ /** Documented default instance base URL (§6.1): loopback port 3000, provisional until 0404's dogfood. */
27
+ export const DEFAULT_INSTANCE_URL = 'http://127.0.0.1:3000';
28
+
29
+ /** End-to-end generate deadline: sized for a 30–120 s blocking call so a slow success is not cut off. */
30
+ export const DEFAULT_GENERATE_TIMEOUT_MS = 180_000;
31
+
32
+ /** Connect-phase deadline: an unreachable host fails fast enough for the bounded retry to matter. */
33
+ export const DEFAULT_CONNECT_TIMEOUT_MS = 5_000;
34
+
35
+ /**
36
+ * `music.defaultModel` default (0401 R2): the instance's Pro model, matching the
37
+ * brief's own built-in default. Only consulted when neither the brief nor the
38
+ * named format preset names a model, so it never overrides an authored choice.
39
+ */
40
+ export const DEFAULT_MUSIC_MODEL: MusicModel = 'pro';
41
+
42
+ /** Environment overrides (§6.1). There is deliberately no env override for the connect timeout. */
43
+ export const MUSIC_ENV_KEYS = {
44
+ instanceUrl: 'KK_MUSIC_INSTANCE_URL',
45
+ timeoutMs: 'KK_MUSIC_TIMEOUT_MS',
46
+ defaultModel: 'KK_MUSIC_DEFAULT_MODEL',
47
+ dryRun: 'KK_MUSIC_DRY_RUN',
48
+ configPath: 'KK_CONFIG',
49
+ runId: 'KK_MUSIC_RUN_ID',
50
+ } as const;
51
+
52
+ /** Per-model and per-analyze unit prices. `analyze` is unpriced (`null`) until the instance bills it. */
53
+ export interface MusicPrices {
54
+ pro: number;
55
+ clip: number;
56
+ /** `null` = unpriced, never "free". The sidecar records `null` verbatim. */
57
+ analyze: number | null;
58
+ }
59
+
60
+ /** Unit prices default (§6.1): provider list prices; 0400 owns the spend cap, not these. */
61
+ export const DEFAULT_MUSIC_PRICES: MusicPrices = { pro: 0.08, clip: 0.04, analyze: null };
62
+
63
+ /** Which layer supplied a resolved setting (`0401`'s verbose output prints these). */
64
+ export type MusicConfigSource = 'env' | 'config' | 'default';
65
+
66
+ /** The effective plugin configuration. */
67
+ export interface MusicConfig {
68
+ baseUrl: string;
69
+ timeoutMs: number;
70
+ connectTimeoutMs: number;
71
+ /** Model used when no layer above the built-in default names one (`music.defaultModel`). */
72
+ defaultModel: MusicModel;
73
+ prices: MusicPrices;
74
+ /** Takes per invocation, resolved by the spend guard's single rule (0400 R4): default 2, never above 4. */
75
+ takesCap: number;
76
+ dryRun: boolean;
77
+ /** `KK_MUSIC_RUN_ID`: the workflow run a take belongs to, recorded in its sidecar (0400 R4). */
78
+ runId?: string;
79
+ /**
80
+ * `music.delivery.<name>` overrides (0405 R5). Empty means only the built-in
81
+ * `streaming` profile exists; resolution is `resolveDeliveryProfile`.
82
+ */
83
+ delivery: DeliveryProfileConfig;
84
+ }
85
+
86
+ /** A resolved configuration plus the provenance of each setting. */
87
+ export interface ResolvedMusicConfig extends MusicConfig {
88
+ sources: {
89
+ baseUrl: MusicConfigSource;
90
+ timeoutMs: MusicConfigSource;
91
+ connectTimeoutMs: MusicConfigSource;
92
+ defaultModel: MusicConfigSource;
93
+ prices: MusicConfigSource;
94
+ takesCap: MusicConfigSource;
95
+ dryRun: MusicConfigSource;
96
+ delivery: MusicConfigSource;
97
+ };
98
+ }
99
+
100
+ /** Raised when a config key is present but of the wrong type or outside its domain. */
101
+ export class MusicConfigError extends Error {
102
+ /** Dotted key that failed, so the one-line remediation can name it. */
103
+ readonly key: string;
104
+
105
+ constructor(key: string, message: string) {
106
+ super(`${key}: ${message}`);
107
+ this.name = 'MusicConfigError';
108
+ this.key = key;
109
+ }
110
+ }
111
+
112
+ /** The `music:` block, as read from the config document (every field optional). */
113
+ export interface MusicConfigDocument {
114
+ baseUrl?: string;
115
+ timeoutMs?: number;
116
+ connectTimeoutMs?: number;
117
+ /** `music.defaultModel`: `pro` (default) or `clip`. */
118
+ defaultModel?: MusicModel;
119
+ prices?: Partial<MusicPrices>;
120
+ /** `music.takesCap`: the 0400 take cap (default 2, never above 4). */
121
+ takesCap?: number;
122
+ /** `music.delivery.<name>`: 0405 delivery profile overrides/definitions. */
123
+ delivery?: DeliveryProfileConfig;
124
+ }
125
+
126
+ /** Resolve the kk config path: `KK_CONFIG`, else `<home>/.config/kk/config.yaml`. */
127
+ export function resolveMusicConfigPath(env: Record<string, string | undefined> = process.env): string {
128
+ const configured = env[MUSIC_ENV_KEYS.configPath];
129
+ const raw =
130
+ configured !== undefined && configured.trim() !== '' ? configured : join('.config', 'kk', 'config.yaml');
131
+ const expanded = raw.startsWith('~/') ? join(homedir(), raw.slice(2)) : raw;
132
+ return isAbsolute(expanded) ? expanded : resolve(homedir(), expanded);
133
+ }
134
+
135
+ /** True when the value is a JSON-style object (not `null`, not an array). */
136
+ function isRecord(value: unknown): value is Record<string, unknown> {
137
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
138
+ }
139
+
140
+ /** Read one non-empty string, or `undefined` when absent. A present non-string throws. */
141
+ function readString(document: Record<string, unknown>, field: string, label: string): string | undefined {
142
+ const value = document[field];
143
+ if (value === undefined) {
144
+ return undefined;
145
+ }
146
+ if (typeof value !== 'string' || value.trim() === '') {
147
+ throw new MusicConfigError(label, 'expected a non-empty string');
148
+ }
149
+ return value.trim();
150
+ }
151
+
152
+ /** Read one positive integer, or `undefined` when absent. A present non-positive value throws. */
153
+ function readPositiveInt(document: Record<string, unknown>, field: string, label: string): number | undefined {
154
+ const value = document[field];
155
+ if (value === undefined) {
156
+ return undefined;
157
+ }
158
+ if (typeof value !== 'number' || !Number.isInteger(value) || value <= 0) {
159
+ throw new MusicConfigError(label, 'expected a positive integer');
160
+ }
161
+ return value;
162
+ }
163
+
164
+ /** Read one non-negative finite price; `null` is allowed only for `analyze` (unpriced). */
165
+ function readPrice(
166
+ document: Record<string, unknown>,
167
+ field: string,
168
+ label: string,
169
+ allowNull: boolean,
170
+ ): number | null | undefined {
171
+ const value = document[field];
172
+ if (value === undefined) {
173
+ return undefined;
174
+ }
175
+ if (value === null) {
176
+ if (allowNull) {
177
+ return null;
178
+ }
179
+ throw new MusicConfigError(label, 'expected a non-negative number');
180
+ }
181
+ if (typeof value !== 'number' || !Number.isFinite(value) || value < 0) {
182
+ throw new MusicConfigError(label, 'expected a non-negative number');
183
+ }
184
+ return value;
185
+ }
186
+
187
+ /** Read one finite number, or `undefined` when absent. A present non-number throws. */
188
+ function readFiniteNumber(
189
+ document: Record<string, unknown>,
190
+ field: string,
191
+ label: string,
192
+ predicate: (value: number) => boolean,
193
+ expectation: string,
194
+ ): number | undefined {
195
+ const value = document[field];
196
+ if (value === undefined) {
197
+ return undefined;
198
+ }
199
+ if (typeof value !== 'number' || !Number.isFinite(value) || !predicate(value)) {
200
+ throw new MusicConfigError(label, expectation);
201
+ }
202
+ return value;
203
+ }
204
+
205
+ /** Read one model selector (`pro`/`clip`), or `undefined` when absent. */
206
+ function readModel(document: Record<string, unknown>, field: string, label: string): MusicModel | undefined {
207
+ const value = document[field];
208
+ if (value === undefined) {
209
+ return undefined;
210
+ }
211
+ if (typeof value !== 'string' || !(MUSIC_MODELS as readonly string[]).includes(value)) {
212
+ throw new MusicConfigError(label, `expected one of ${MUSIC_MODELS.join(', ')}`);
213
+ }
214
+ return value as MusicModel;
215
+ }
216
+
217
+ /**
218
+ * Parse `music.delivery.<name>` (0405 R5): one record per profile, each a subset
219
+ * of `{ lufs, truePeak, lra, container, sampleRate }`. Types are checked here; the
220
+ * *completeness* of a new profile is checked at resolution
221
+ * (`resolveDeliveryProfile`), so an override of `streaming` may set one field
222
+ * while a brand-new profile must be whole.
223
+ */
224
+ function readDeliveryProfiles(document: Record<string, unknown>): DeliveryProfileConfig | undefined {
225
+ const delivery = document.delivery;
226
+ if (delivery === undefined) {
227
+ return undefined;
228
+ }
229
+ if (!isRecord(delivery)) {
230
+ throw new MusicConfigError(
231
+ 'music.delivery',
232
+ 'expected a map of profile name to { lufs, truePeak, lra?, container, sampleRate }',
233
+ );
234
+ }
235
+ const profiles: DeliveryProfileConfig = {};
236
+ for (const [name, value] of Object.entries(delivery)) {
237
+ const key = `music.delivery.${name}`;
238
+ if (name.trim() === '' || !isRecord(value)) {
239
+ throw new MusicConfigError(key, 'expected an object with lufs, truePeak, lra?, container and sampleRate');
240
+ }
241
+ const profile: DeliveryProfileOverride = {};
242
+ const lufs = readFiniteNumber(
243
+ value,
244
+ 'lufs',
245
+ `${key}.lufs`,
246
+ () => true,
247
+ 'expected a finite loudness target in LUFS',
248
+ );
249
+ if (lufs !== undefined) {
250
+ profile.lufs = lufs;
251
+ }
252
+ const truePeak = readFiniteNumber(
253
+ value,
254
+ 'truePeak',
255
+ `${key}.truePeak`,
256
+ (parsed) => parsed <= 0,
257
+ 'expected a true-peak ceiling in dBTP at or below 0',
258
+ );
259
+ if (truePeak !== undefined) {
260
+ profile.truePeak = truePeak;
261
+ }
262
+ const lra = readFiniteNumber(
263
+ value,
264
+ 'lra',
265
+ `${key}.lra`,
266
+ (parsed) => parsed >= 0,
267
+ 'expected a non-negative loudness range in LU',
268
+ );
269
+ if (lra !== undefined) {
270
+ profile.lra = lra;
271
+ }
272
+ const sampleRate = readFiniteNumber(
273
+ value,
274
+ 'sampleRate',
275
+ `${key}.sampleRate`,
276
+ (parsed) => Number.isInteger(parsed) && parsed > 0,
277
+ 'expected a positive integer sample rate in Hz',
278
+ );
279
+ if (sampleRate !== undefined) {
280
+ profile.sampleRate = sampleRate;
281
+ }
282
+ const container = value.container;
283
+ if (container !== undefined) {
284
+ if (typeof container !== 'string' || !(AUDIO_FORMATS as readonly string[]).includes(container)) {
285
+ throw new MusicConfigError(`${key}.container`, `expected one of ${AUDIO_FORMATS.join(', ')}`);
286
+ }
287
+ profile.container = container as DeliveryProfileOverride['container'];
288
+ }
289
+ profiles[name] = profile;
290
+ }
291
+ return profiles;
292
+ }
293
+
294
+ /**
295
+ * Parse the `music:` block. A missing block is the zero-config case; a present
296
+ * key of the wrong type throws (the `store.*` reader's rule) — a silently
297
+ * defaulted base URL or timeout would send a paid request somewhere unexpected.
298
+ */
299
+ export function parseMusicConfigDocument(parsed: unknown): MusicConfigDocument {
300
+ if (!isRecord(parsed) || !isRecord(parsed.music)) {
301
+ return {};
302
+ }
303
+ const music = parsed.music;
304
+ const instance = isRecord(music.instance) ? music.instance : {};
305
+ const baseUrl = readString(music, 'baseUrl', 'music.baseUrl') ?? readString(instance, 'url', 'music.instance.url');
306
+ const timeoutMs =
307
+ readPositiveInt(music, 'timeoutMs', 'music.timeoutMs') ??
308
+ readPositiveInt(instance, 'timeoutMs', 'music.instance.timeoutMs');
309
+ const connectTimeoutMs = readPositiveInt(instance, 'connectTimeoutMs', 'music.instance.connectTimeoutMs');
310
+ const takesCap = readPositiveInt(music, 'takesCap', 'music.takesCap');
311
+ const defaultModel = readModel(music, 'defaultModel', 'music.defaultModel');
312
+ const delivery = readDeliveryProfiles(music);
313
+ const result: MusicConfigDocument = {};
314
+ if (baseUrl !== undefined) {
315
+ result.baseUrl = baseUrl;
316
+ }
317
+ if (timeoutMs !== undefined) {
318
+ result.timeoutMs = timeoutMs;
319
+ }
320
+ if (connectTimeoutMs !== undefined) {
321
+ result.connectTimeoutMs = connectTimeoutMs;
322
+ }
323
+ if (takesCap !== undefined) {
324
+ result.takesCap = takesCap;
325
+ }
326
+ if (defaultModel !== undefined) {
327
+ result.defaultModel = defaultModel;
328
+ }
329
+ if (delivery !== undefined) {
330
+ result.delivery = delivery;
331
+ }
332
+ if (isRecord(music.prices)) {
333
+ const prices = music.prices;
334
+ const pro = readPrice(prices, 'pro', 'music.prices.pro', false);
335
+ const clip = readPrice(prices, 'clip', 'music.prices.clip', false);
336
+ const analyze = readPrice(prices, 'analyze', 'music.prices.analyze', true);
337
+ const partial: Partial<MusicPrices> = {};
338
+ if (typeof pro === 'number') {
339
+ partial.pro = pro;
340
+ }
341
+ if (typeof clip === 'number') {
342
+ partial.clip = clip;
343
+ }
344
+ if (analyze !== undefined) {
345
+ partial.analyze = analyze;
346
+ }
347
+ if (Object.keys(partial).length > 0) {
348
+ result.prices = partial;
349
+ }
350
+ }
351
+ return result;
352
+ }
353
+
354
+ /** Read one positive integer env override, or `undefined` when unset. A malformed value throws. */
355
+ function readEnvPositiveInt(env: Record<string, string | undefined>, key: string): number | undefined {
356
+ const raw = env[key];
357
+ if (raw === undefined || raw.trim() === '') {
358
+ return undefined;
359
+ }
360
+ if (!/^\d+$/.test(raw.trim())) {
361
+ throw new MusicConfigError(key, `expected a positive integer, received '${raw}'`);
362
+ }
363
+ const parsed = Number(raw.trim());
364
+ if (parsed <= 0) {
365
+ throw new MusicConfigError(key, `expected a positive integer, received '${raw}'`);
366
+ }
367
+ return parsed;
368
+ }
369
+
370
+ /** Read the config document; a missing or unparseable file is the zero-config case. */
371
+ async function readConfigDocument(
372
+ fileSystem: FileSystem,
373
+ configPath: string,
374
+ ): Promise<{ document: MusicConfigDocument; readable: boolean }> {
375
+ if (!(await fileSystem.exists(configPath))) {
376
+ return { document: {}, readable: false };
377
+ }
378
+ let text: string;
379
+ try {
380
+ text = await fileSystem.readFile(configPath);
381
+ } catch {
382
+ return { document: {}, readable: false };
383
+ }
384
+ let parsed: unknown;
385
+ try {
386
+ parsed = Bun.YAML.parse(text);
387
+ } catch {
388
+ // An unparseable file yields the defaults, exactly like a missing one; a *present*
389
+ // key of the wrong type still throws in parseMusicConfigDocument.
390
+ return { document: {}, readable: false };
391
+ }
392
+ return { document: parseMusicConfigDocument(parsed), readable: true };
393
+ }
394
+
395
+ /**
396
+ * Resolve the effective music configuration (§6.1 precedence: env > config > default).
397
+ *
398
+ * @param options.env environment map (defaults to `process.env`)
399
+ * @param options.fileSystem ts-runtime seam (defaults to the node/bun backend)
400
+ * @param options.configPath explicit config file, overriding `KK_CONFIG`
401
+ */
402
+ export async function resolveMusicConfig(
403
+ options: { env?: Record<string, string | undefined>; fileSystem?: FileSystem; configPath?: string } = {},
404
+ ): Promise<ResolvedMusicConfig> {
405
+ const env = options.env ?? process.env;
406
+ const fileSystem = options.fileSystem ?? createNodeFileSystem();
407
+ const configPath = options.configPath ?? resolveMusicConfigPath(env);
408
+ const { document, readable } = await readConfigDocument(fileSystem, configPath);
409
+
410
+ const envBaseUrl = env[MUSIC_ENV_KEYS.instanceUrl]?.trim();
411
+ const envTimeout = readEnvPositiveInt(env, MUSIC_ENV_KEYS.timeoutMs);
412
+ const envModel = readModel(env, MUSIC_ENV_KEYS.defaultModel, MUSIC_ENV_KEYS.defaultModel);
413
+
414
+ const baseUrl = envBaseUrl !== undefined && envBaseUrl !== '' ? envBaseUrl : document.baseUrl;
415
+ const timeoutMs = envTimeout ?? document.timeoutMs;
416
+ const connectTimeoutMs = document.connectTimeoutMs;
417
+ const defaultModel = envModel ?? document.defaultModel;
418
+ const dryRun = env[MUSIC_ENV_KEYS.dryRun] === '1';
419
+ const runId = env[MUSIC_ENV_KEYS.runId]?.trim();
420
+
421
+ const priceSource: MusicConfigSource = document.prices === undefined ? 'default' : readable ? 'config' : 'default';
422
+
423
+ return {
424
+ baseUrl: baseUrl ?? DEFAULT_INSTANCE_URL,
425
+ timeoutMs: timeoutMs ?? DEFAULT_GENERATE_TIMEOUT_MS,
426
+ connectTimeoutMs: connectTimeoutMs ?? DEFAULT_CONNECT_TIMEOUT_MS,
427
+ defaultModel: defaultModel ?? DEFAULT_MUSIC_MODEL,
428
+ prices: { ...DEFAULT_MUSIC_PRICES, ...(document.prices ?? {}) },
429
+ // `music.takesCap` is validated by the spend guard's own rule, so a cap above 4 is
430
+ // rejected here — at load, before any estimate, dedupe or socket (0400 AC4).
431
+ takesCap: resolveTakesCap(document.takesCap),
432
+ dryRun,
433
+ ...(runId === undefined || runId === '' ? {} : { runId }),
434
+ delivery: document.delivery ?? {},
435
+ sources: {
436
+ baseUrl:
437
+ envBaseUrl !== undefined && envBaseUrl !== ''
438
+ ? 'env'
439
+ : document.baseUrl === undefined
440
+ ? 'default'
441
+ : 'config',
442
+ timeoutMs: envTimeout !== undefined ? 'env' : document.timeoutMs === undefined ? 'default' : 'config',
443
+ connectTimeoutMs: connectTimeoutMs === undefined ? 'default' : 'config',
444
+ defaultModel: envModel !== undefined ? 'env' : document.defaultModel === undefined ? 'default' : 'config',
445
+ prices: priceSource,
446
+ takesCap: document.takesCap === undefined ? 'default' : 'config',
447
+ dryRun: 'env',
448
+ delivery: document.delivery === undefined ? 'default' : 'config',
449
+ },
450
+ };
451
+ }
@@ -0,0 +1,199 @@
1
+ import type { Content } from '@gobing-ai/kk-core';
2
+ import type { UnclaimedTake } from './adapter/instance';
3
+ import type { AudioFormat } from './brief';
4
+ import type { MusicDigestInput } from './digest';
5
+
6
+ /**
7
+ * Content mapping (task 0398 R5): a resolved + generated job becomes the
8
+ * generator contract's `Content`.
9
+ *
10
+ * - `format: 'audio'` — the `voice-gen` precedent (`plugins/generations/voice-gen/src/index.ts`)
11
+ * proves audio is a legal generator result.
12
+ * - **body = liner notes**: the kk prompt text, the lyrics, the duration target,
13
+ * the model, the instance provider, the instance generation id and the analysis
14
+ * summary when one exists. A person reading `content.json` should never have to
15
+ * open the sidecar to know what was bought.
16
+ * - **references = the instance audio URL + the kk sidecar path**: the two things
17
+ * a downstream judge or the operator needs, and no copy of the instance library.
18
+ * - **metadata = the echo**: `language`, `durationTarget` and `batchCount` survive
19
+ * exactly as the instance recorded them, and are *absent* (never defaulted) when
20
+ * the manifest lacked them — a defaulted `EN` would deny the instance said nothing.
21
+ */
22
+
23
+ /** The generator contract's audio format value. */
24
+ export const MUSIC_CONTENT_FORMAT = 'audio';
25
+
26
+ /** What the liner notes need for one take. */
27
+ export interface LinerTake {
28
+ takeIndex: number;
29
+ instanceId: string;
30
+ model: string;
31
+ format: AudioFormat;
32
+ language?: string;
33
+ durationTarget?: string;
34
+ batchCount?: number;
35
+ audioUrl?: string;
36
+ /** The kk-owned prompt text, byte for byte what the instance received. */
37
+ prompt: string;
38
+ lyrics?: string;
39
+ /** `analysis.summary` when the instance carried one. */
40
+ analysisSummary?: string;
41
+ adoptedByReconciliation: boolean;
42
+ unclaimed: UnclaimedTake[];
43
+ }
44
+
45
+ /** What the liner notes need for the whole job. */
46
+ export interface LinerNotesInput {
47
+ title: string;
48
+ provider: string;
49
+ dryRun: boolean;
50
+ takes: LinerTake[];
51
+ }
52
+
53
+ /** Read `analysis.summary` without trusting the instance's analysis shape. */
54
+ export function analysisSummary(analysis: Record<string, unknown> | undefined): string | undefined {
55
+ if (analysis === undefined) {
56
+ return undefined;
57
+ }
58
+ const summary = analysis.summary;
59
+ if (typeof summary === 'string' && summary.trim() !== '') {
60
+ return summary.trim();
61
+ }
62
+ return undefined;
63
+ }
64
+
65
+ /** Render one take's liner-notes block. Deterministic: same take, same lines. */
66
+ function renderTakeBlock(take: LinerTake): string[] {
67
+ const lines: string[] = [`## Take ${String(take.takeIndex + 1)}`, ''];
68
+ lines.push(`- instance id: \`${take.instanceId}\``);
69
+ lines.push(`- model: \`${take.model}\``);
70
+ lines.push(`- delivered format: \`${take.format}\``);
71
+ if (take.language !== undefined) {
72
+ lines.push(`- language: \`${take.language}\``);
73
+ }
74
+ if (take.durationTarget !== undefined) {
75
+ lines.push(`- duration target: \`${take.durationTarget}\``);
76
+ }
77
+ if (take.batchCount !== undefined) {
78
+ lines.push(`- batch count: \`${String(take.batchCount)}\``);
79
+ }
80
+ if (take.audioUrl !== undefined) {
81
+ lines.push(`- audio: ${take.audioUrl}`);
82
+ }
83
+ if (take.adoptedByReconciliation) {
84
+ lines.push('- provenance: adopted from `GET /api/generations` after an ambiguous send');
85
+ }
86
+ if (take.unclaimed.length > 0) {
87
+ lines.push(
88
+ `- unclaimed extra takes: ${take.unclaimed.map((entry) => `\`${entry.id}\``).join(', ')} (billed, not adopted)`,
89
+ );
90
+ }
91
+ lines.push('', '### Prompt', '', take.prompt, '');
92
+ lines.push('### Lyrics', '');
93
+ lines.push(
94
+ take.lyrics === undefined
95
+ ? '(none — the model writes its own)'
96
+ : take.lyrics === ''
97
+ ? '(instrumental)'
98
+ : take.lyrics,
99
+ );
100
+ lines.push('');
101
+ lines.push('### Analysis', '');
102
+ lines.push(take.analysisSummary ?? '(no analysis cached on the instance)');
103
+ return lines;
104
+ }
105
+
106
+ /** Render the whole liner-notes body. */
107
+ export function renderLinerNotes(input: LinerNotesInput): string {
108
+ const delivered = input.takes.map((take) => take.format);
109
+ const formats = [...new Set(delivered)].join(', ');
110
+ const models = [...new Set(input.takes.map((take) => take.model))].join(', ');
111
+ const header = [
112
+ `# ${input.title}`,
113
+ '',
114
+ `Generated through the \`${input.provider}\` adapter${input.dryRun ? ' (dry run — no instance was called)' : ''}.`,
115
+ '',
116
+ `- provider: \`${input.provider}\``,
117
+ `- model: \`${models}\``,
118
+ `- delivered format: \`${formats}\``,
119
+ `- takes: ${String(input.takes.length)}`,
120
+ '',
121
+ ];
122
+ const blocks = input.takes.flatMap((take) => [...renderTakeBlock(take), '']);
123
+ return [...header, ...blocks].join('\n').replace(/\n+$/, '\n');
124
+ }
125
+
126
+ /** One take as it lands in `Content.metadata.takes[]`. */
127
+ export interface ContentTakeRecord {
128
+ takeIndex: number;
129
+ instanceId: string;
130
+ model: string;
131
+ format: AudioFormat;
132
+ requestedFormat: AudioFormat;
133
+ digest: string;
134
+ digestInput: MusicDigestInput;
135
+ artifactPath: string;
136
+ sidecarPath: string;
137
+ unitPrice: number | null;
138
+ adoptedByReconciliation: boolean;
139
+ unclaimed: UnclaimedTake[];
140
+ language?: string;
141
+ durationTarget?: string;
142
+ batchCount?: number;
143
+ audioUrl?: string;
144
+ generatedAt?: string;
145
+ analysisSummary?: string;
146
+ }
147
+
148
+ /**
149
+ * This plugin's `Content.metadata` shape. A type alias, not an interface, so it
150
+ * stays assignable to the contract's `Record<string, unknown>` metadata slot.
151
+ */
152
+ export type MusicGenMetadata = {
153
+ generator: 'kk:music-gen';
154
+ provider: string;
155
+ dryRun?: true;
156
+ takes: ContentTakeRecord[];
157
+ };
158
+
159
+ /** What {@link buildMusicContent} needs. */
160
+ export interface BuildMusicContentInput {
161
+ title: string;
162
+ provider: string;
163
+ dryRun: boolean;
164
+ liner: LinerTake[];
165
+ takes: ContentTakeRecord[];
166
+ }
167
+
168
+ /**
169
+ * Build the generator `Content`: `format: 'audio'`, liner-notes body, references
170
+ * to the instance audio plus the kk sidecar, and the take records in metadata.
171
+ */
172
+ export function buildMusicContent(input: BuildMusicContentInput): Content {
173
+ const references = input.liner.flatMap((take) => {
174
+ const audio =
175
+ take.audioUrl === undefined ? [] : [{ url: take.audioUrl, title: `instance audio — ${take.instanceId}` }];
176
+ const sidecarPath = input.takes.find((record) => record.takeIndex === take.takeIndex)?.sidecarPath;
177
+ const sidecar =
178
+ sidecarPath === undefined ? [] : [{ url: sidecarPath, title: `kk take sidecar — ${take.instanceId}` }];
179
+ return [...audio, ...sidecar];
180
+ });
181
+ const metadata: MusicGenMetadata = {
182
+ generator: 'kk:music-gen',
183
+ provider: input.provider,
184
+ ...(input.dryRun ? { dryRun: true as const } : {}),
185
+ takes: input.takes,
186
+ };
187
+ return {
188
+ title: input.title,
189
+ format: MUSIC_CONTENT_FORMAT,
190
+ body: renderLinerNotes({
191
+ title: input.title,
192
+ provider: input.provider,
193
+ dryRun: input.dryRun,
194
+ takes: input.liner,
195
+ }),
196
+ references,
197
+ metadata,
198
+ };
199
+ }