@gobing-ai/knowledge-kit 0.1.19 → 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 (147) 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 +1315 -264
  4. package/dist/board/itc/index.js +1 -0
  5. package/dist/index.js +14674 -8775
  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/image-gen/README.md +31 -31
  13. package/plugins/generations/image-gen/assets/sample/provenance.json +314 -0
  14. package/plugins/generations/image-gen/config.example.yaml +3 -0
  15. package/plugins/generations/image-gen/dist/index.js +154 -14
  16. package/plugins/generations/image-gen/presets/SOURCE.md +65 -0
  17. package/plugins/generations/image-gen/scripts/eval-style-presets.ts +513 -0
  18. package/plugins/generations/image-gen/scripts/gen-samples.ts +57 -7
  19. package/plugins/generations/image-gen/src/presets.ts +6 -5
  20. package/plugins/generations/image-gen/src/providers/h3-local.ts +196 -0
  21. package/plugins/generations/image-gen/src/providers/types.ts +11 -1
  22. package/plugins/generations/music-gen/README.md +277 -0
  23. package/plugins/generations/music-gen/dist/index.js +23544 -0
  24. package/plugins/generations/music-gen/package.json +24 -0
  25. package/plugins/generations/music-gen/plugin.json +23 -0
  26. package/plugins/generations/music-gen/presets/SOURCE.md +39 -0
  27. package/plugins/generations/music-gen/presets/formats/clip.yaml +21 -0
  28. package/plugins/generations/music-gen/presets/formats/jingle.yaml +22 -0
  29. package/plugins/generations/music-gen/presets/formats/loop.yaml +21 -0
  30. package/plugins/generations/music-gen/presets/formats/song.yaml +31 -0
  31. package/plugins/generations/music-gen/presets/formats/underscore.yaml +22 -0
  32. package/plugins/generations/music-gen/presets/themes/ambient-tech.yaml +30 -0
  33. package/plugins/generations/music-gen/presets/themes/cinematic.yaml +30 -0
  34. package/plugins/generations/music-gen/presets/themes/lofi.yaml +30 -0
  35. package/plugins/generations/music-gen/presets/themes/synthwave.yaml +30 -0
  36. package/plugins/generations/music-gen/scripts/gen-preset-index.ts +181 -0
  37. package/plugins/generations/music-gen/scripts/resolve-preset.ts +64 -0
  38. package/plugins/generations/music-gen/src/adapter/index.ts +35 -0
  39. package/plugins/generations/music-gen/src/adapter/instance.ts +904 -0
  40. package/plugins/generations/music-gen/src/adapter/offline.ts +124 -0
  41. package/plugins/generations/music-gen/src/artifact.ts +223 -0
  42. package/plugins/generations/music-gen/src/audio/checks.ts +618 -0
  43. package/plugins/generations/music-gen/src/audio/master.ts +267 -0
  44. package/plugins/generations/music-gen/src/audio/measure.ts +507 -0
  45. package/plugins/generations/music-gen/src/audio/profile.ts +131 -0
  46. package/plugins/generations/music-gen/src/audio.ts +122 -0
  47. package/plugins/generations/music-gen/src/brief.ts +191 -0
  48. package/plugins/generations/music-gen/src/config.ts +451 -0
  49. package/plugins/generations/music-gen/src/content.ts +199 -0
  50. package/plugins/generations/music-gen/src/digest.ts +100 -0
  51. package/plugins/generations/music-gen/src/index.ts +147 -0
  52. package/plugins/generations/music-gen/src/job.ts +131 -0
  53. package/plugins/generations/music-gen/src/plugin.ts +371 -0
  54. package/plugins/generations/music-gen/src/presets.ts +918 -0
  55. package/plugins/generations/music-gen/src/render.ts +87 -0
  56. package/plugins/generations/music-gen/src/request.ts +102 -0
  57. package/plugins/generations/music-gen/src/spend.ts +495 -0
  58. package/plugins/generations/music-gen/tsconfig.json +8 -0
  59. package/plugins/kk/config.example.yaml +3 -0
  60. package/plugins/kk/decisions/extract/ai-news.yaml +5 -2
  61. package/plugins/kk/plugin.json +1 -1
  62. package/plugins/kk/publish-presets/daily-ai-voice.json +48 -7
  63. package/plugins/kk/schedules/kk-serve.launchd.plist.tmpl +2 -1
  64. package/plugins/kk/scripts/cover-compositor.ts +380 -32
  65. package/plugins/kk/scripts/daily-cover-mock.ts +40 -3
  66. package/plugins/kk/scripts/daily-stages.ts +897 -34
  67. package/plugins/kk/scripts/episode-identity.ts +180 -0
  68. package/plugins/kk/scripts/kk-workflow-stages.ts +37 -1
  69. package/plugins/kk/scripts/music-stages.ts +624 -0
  70. package/plugins/kk/scripts/news-editorial-ledger.ts +906 -0
  71. package/plugins/kk/scripts/source-citation.ts +187 -0
  72. package/plugins/kk/scripts/topic-selection-attempts.ts +446 -0
  73. package/plugins/kk/scripts/topic-selection-calibration.ts +161 -0
  74. package/plugins/kk/skills/content-judge/SKILL.md +11 -6
  75. package/plugins/kk/skills/content-judge/references/music-quality-rubric.md +147 -0
  76. package/plugins/kk/skills/content-judge/references/rubrics.md +15 -0
  77. package/plugins/kk/skills/content-safety/SKILL.md +12 -0
  78. package/plugins/kk/skills/image-authoring/SKILL.md +7 -3
  79. package/plugins/kk/skills/image-authoring/references/providers.md +27 -0
  80. package/plugins/kk/skills/image-authoring/references/style-extraction.md +1 -1
  81. package/plugins/kk/skills/music-authoring/SKILL.md +276 -0
  82. package/plugins/kk/skills/music-authoring/references/judge-input.md +117 -0
  83. package/plugins/kk/skills/news-editorial/SKILL.md +102 -15
  84. package/plugins/kk/skills/news-editorial/references/selection.md +4 -0
  85. package/plugins/kk/skills/news-editorial/references/style-contract.zh.md +58 -11
  86. package/plugins/kk/skills/publish/SKILL.md +11 -0
  87. package/plugins/kk/skills/web-automation/SKILL.md +31 -1
  88. package/plugins/kk/workflows/kk-collect.yaml +8 -4
  89. package/plugins/kk/workflows/kk-daily-ai-voice.yaml +10 -9
  90. package/plugins/kk/workflows/kk-daily-ai-voice2.yaml +11 -9
  91. package/plugins/kk/workflows/kk-music.yaml +328 -0
  92. package/plugins/kk/workflows/kk-news-generate.yaml +58 -3
  93. package/plugins/publishings/bilibili-pub/dist/index.js +11 -1
  94. package/plugins/publishings/bilibili-pub/dist/profile-check.js +11 -1
  95. package/plugins/publishings/cnblogs-pub/dist/index.js +11 -1
  96. package/plugins/publishings/cnblogs-pub/dist/profile-check.js +11 -1
  97. package/plugins/publishings/csdn-pub/dist/index.js +11 -1
  98. package/plugins/publishings/csdn-pub/dist/profile-check.js +11 -1
  99. package/plugins/publishings/infoq-pub/dist/index.js +11 -1
  100. package/plugins/publishings/infoq-pub/dist/profile-check.js +11 -1
  101. package/plugins/publishings/jike-pub/dist/index.js +11 -1
  102. package/plugins/publishings/jike-pub/dist/profile-check.js +11 -1
  103. package/plugins/publishings/juejin-pub/dist/index.js +11 -1
  104. package/plugins/publishings/juejin-pub/dist/profile-check.js +11 -1
  105. package/plugins/publishings/linkedin-pub/dist/index.js +54 -7
  106. package/plugins/publishings/linkedin-pub/dist/profile-check.js +43 -6
  107. package/plugins/publishings/linkedin-pub/src/index.ts +52 -6
  108. package/plugins/publishings/podcast-pub/dist/index.js +586 -20
  109. package/plugins/publishings/podcast-pub/src/corrections.ts +509 -0
  110. package/plugins/publishings/podcast-pub/src/index.ts +257 -5
  111. package/plugins/publishings/podcast-pub/src/show-notes-brief.ts +240 -0
  112. package/plugins/publishings/podcast-pub/src/show-notes.ts +69 -13
  113. package/plugins/publishings/shipinhao-pub/dist/index.js +437 -32
  114. package/plugins/publishings/shipinhao-pub/dist/profile-check.js +14 -2
  115. package/plugins/publishings/shipinhao-pub/plugin.json +1 -1
  116. package/plugins/publishings/shipinhao-pub/src/audio-flow.ts +492 -0
  117. package/plugins/publishings/shipinhao-pub/src/flow.ts +227 -12
  118. package/plugins/publishings/shipinhao-pub/src/selectors.ts +13 -0
  119. package/plugins/publishings/sspai-pub/dist/index.js +11 -1
  120. package/plugins/publishings/sspai-pub/dist/profile-check.js +11 -1
  121. package/plugins/publishings/substack-pub/dist/index.js +11 -1
  122. package/plugins/publishings/substack-pub/dist/profile-check.js +11 -1
  123. package/plugins/publishings/surfdash-pub/dist/index.js +122 -28
  124. package/plugins/publishings/surfdash-pub/src/digest-check.ts +7 -3
  125. package/plugins/publishings/surfdash-pub/src/index.ts +159 -25
  126. package/plugins/publishings/surfdash-pub/src/topic-claims.ts +37 -4
  127. package/plugins/publishings/threads-pub/dist/index.js +9206 -296
  128. package/plugins/publishings/threads-pub/dist/profile-check.js +21149 -0
  129. package/plugins/publishings/threads-pub/package.json +3 -1
  130. package/plugins/publishings/threads-pub/plugin.json +6 -1
  131. package/plugins/publishings/threads-pub/src/index.ts +8 -1
  132. package/plugins/publishings/threads-pub/src/post-rail.ts +357 -0
  133. package/plugins/publishings/threads-pub/src/profile-check.ts +17 -0
  134. package/plugins/publishings/wechatmp-pub/dist/index.js +18 -1
  135. package/plugins/publishings/wechatmp-pub/dist/profile-check.js +11 -1
  136. package/plugins/publishings/wechatmp-pub/src/flow.ts +13 -0
  137. package/plugins/publishings/weibo-pub/dist/index.js +57 -3
  138. package/plugins/publishings/weibo-pub/dist/profile-check.js +11 -1
  139. package/plugins/publishings/weibo-pub/src/index.ts +74 -2
  140. package/plugins/publishings/x-pub/dist/index.js +274 -44
  141. package/plugins/publishings/x-pub/dist/profile-check.js +14 -2
  142. package/plugins/publishings/x-pub/src/index.ts +15 -1
  143. package/plugins/publishings/x-pub/src/post-rail.ts +334 -0
  144. package/plugins/publishings/xhs-pub/dist/index.js +11 -1
  145. package/plugins/publishings/xhs-pub/dist/profile-check.js +11 -1
  146. package/plugins/publishings/xiaoyuzhou-pub/dist/index.js +11 -1
  147. package/plugins/publishings/xiaoyuzhou-pub/dist/profile-check.js +11 -1
@@ -0,0 +1,196 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { randomBytes } from 'node:crypto';
3
+ import { mkdir, rm } from 'node:fs/promises';
4
+ import { tmpdir } from 'node:os';
5
+ import { resolve } from 'node:path';
6
+ import { readBytes } from '../bytes';
7
+ import type { ImageProvider, ImageRequest, ImageResult, ProviderFactory, ProviderOptions } from './types';
8
+
9
+ /**
10
+ * no-direct-fs-io / no-direct-process-spawn exemption is recorded as per-file
11
+ * exclusions in .spur/rules/strict/runtime-boundaries.yaml: this provider's transport
12
+ * IS spawning the local `h3gen.sh` wrapper and staging one temp output file for it
13
+ * (same vendor-CLI-boundary class as codex-cli).
14
+ */
15
+
16
+ /**
17
+ * h3-local adapter (task 0379, feature K2) — Robin's local Apple Silicon MLX image runtime,
18
+ * reached through its `h3gen.sh` wrapper. Never auto-selected: a 6-minute-per-image local
19
+ * render must be an explicit operator choice, and the wrapper's readiness (venv, 49 GB of
20
+ * weights, a mounted external volume) cannot be expressed as env presence.
21
+ *
22
+ * Why a subprocess and not an import: the runtime is a Python venv (`../gitops/apps/h3-image-mlx`),
23
+ * so shelling out to its documented wrapper is the whole integration. `h3gen.sh` forwards every
24
+ * unknown flag to `h3-image-mlx generate`, resolves a relative `--output` against the caller's
25
+ * cwd, and echoes the written path.
26
+ */
27
+
28
+ const DEFAULT_MODEL = 'h3';
29
+
30
+ /** H3 accepts multiples of 32 within 256–4096 (h3-image-mlx README). */
31
+ const H3_DIM_MIN = 256;
32
+ const H3_DIM_MAX = 4096;
33
+ const H3_DIM_STEP = 32;
34
+
35
+ /**
36
+ * Default timeout is the measured worst case, not a guess: a cold 1024² text-to-image render is
37
+ * ~6–7 min and a two-reference edit measured 27 min 46 s (h3gen.sh README table). Anything
38
+ * tighter would kill paid-for work; `H3_LOCAL_TIMEOUT_MS` overrides per machine.
39
+ */
40
+ const DEFAULT_TIMEOUT_MS = 30 * 60 * 1000;
41
+
42
+ /** The canvas an aspect-only request lands on: 1024 on the short side, snapped and clamped. */
43
+ function snapDim(value: number): number {
44
+ const snapped = Math.round(value / H3_DIM_STEP) * H3_DIM_STEP;
45
+ return Math.min(H3_DIM_MAX, Math.max(H3_DIM_MIN, snapped));
46
+ }
47
+
48
+ /** True when both dimensions are canvases H3 can actually render. */
49
+ export function h3ExactSize(width: number, height: number): boolean {
50
+ if (!Number.isFinite(width) || !Number.isFinite(height)) return false;
51
+ const legal = (value: number): boolean =>
52
+ Number.isInteger(value) && value % H3_DIM_STEP === 0 && value >= H3_DIM_MIN && value <= H3_DIM_MAX;
53
+ return legal(width) && legal(height);
54
+ }
55
+
56
+ /**
57
+ * Translate an aspect-only request ("3:4", "21:9") into a legal H3 canvas. Returns null when the
58
+ * ratio is missing or unparseable, so the caller can fall back to a square instead of guessing.
59
+ */
60
+ export function h3Canvas(aspectRatio: string | undefined): { width: number; height: number } | null {
61
+ const match = /^(\d+(?:\.\d+)?):(\d+(?:\.\d+)?)$/.exec(aspectRatio?.trim() ?? '');
62
+ if (match === null) return null;
63
+ const ratioWidth = Number(match[1]);
64
+ const ratioHeight = Number(match[2]);
65
+ if (!(ratioWidth > 0) || !(ratioHeight > 0)) return null;
66
+ const height = snapDim(1024);
67
+ return { width: snapDim((1024 * ratioWidth) / ratioHeight), height };
68
+ }
69
+
70
+ interface SpawnResult {
71
+ stdout: string;
72
+ stderr: string;
73
+ code: number;
74
+ timedOut: boolean;
75
+ }
76
+
77
+ function spawnWrapper(command: string, args: string[], timeoutMs: number): Promise<SpawnResult> {
78
+ return new Promise((resolveSpawn, rejectSpawn) => {
79
+ // Detached: a timeout must kill the wrapper AND the python runtime it spawned, or a
80
+ // timed-out render keeps burning the GPU after the caller has moved on.
81
+ const child = spawn(command, args, { stdio: ['ignore', 'pipe', 'pipe'], detached: true });
82
+ let stdout = '';
83
+ let stderr = '';
84
+ let timedOut = false;
85
+ const timer = setTimeout(() => {
86
+ timedOut = true;
87
+ try {
88
+ if (child.pid !== undefined) process.kill(-child.pid, 'SIGKILL');
89
+ } catch {
90
+ // The group is already gone (ESRCH) — nothing left to kill.
91
+ }
92
+ }, timeoutMs);
93
+ child.stdout.on('data', (chunk: Buffer) => {
94
+ stdout += chunk.toString('utf8');
95
+ });
96
+ child.stderr.on('data', (chunk: Buffer) => {
97
+ stderr += chunk.toString('utf8');
98
+ });
99
+ child.on('error', (err) => {
100
+ clearTimeout(timer);
101
+ rejectSpawn(err);
102
+ });
103
+ child.on('close', (code) => {
104
+ clearTimeout(timer);
105
+ resolveSpawn({ stdout, stderr, code: code ?? 1, timedOut });
106
+ });
107
+ });
108
+ }
109
+
110
+ /** Keep thrown messages short but diagnostic: the tail is what a fallback reader needs. */
111
+ function stderrTail(text: string): string {
112
+ const trimmed = text.trim();
113
+ if (trimmed === '') return '';
114
+ return `; ${trimmed.slice(-800)}`;
115
+ }
116
+
117
+ function positiveInt(value: string): number | null {
118
+ if (value === '') return null;
119
+ const parsed = Number.parseInt(value, 10);
120
+ return Number.isFinite(parsed) && parsed > 0 ? parsed : null;
121
+ }
122
+
123
+ export const createH3Local: ProviderFactory = (options?: ProviderOptions): ImageProvider => {
124
+ const env = options?.env ?? process.env;
125
+ const readEnv = (key: string): string => env[key] ?? '';
126
+ const timeoutMs = options?.timeoutMs ?? positiveInt(readEnv('H3_LOCAL_TIMEOUT_MS')) ?? DEFAULT_TIMEOUT_MS;
127
+
128
+ return {
129
+ name: 'h3-local',
130
+ defaultModel: () => DEFAULT_MODEL,
131
+ // Env presence only: probing the venv, the weights or the external volume here would turn
132
+ // a synchronous selection into a multi-second filesystem stall on every run.
133
+ isAvailable: () => readEnv('H3_IMAGE_MLX_BIN') !== '',
134
+ supportsReferenceImages: () => true,
135
+ exactSize: (_model: string, width: number, height: number): boolean => h3ExactSize(width, height),
136
+ validate(req: ImageRequest): void {
137
+ if ((req.n ?? 1) > 1) {
138
+ throw new Error('h3-local provider supports only n=1 (the wrapper renders one image per call).');
139
+ }
140
+ },
141
+ async generate(req: ImageRequest): Promise<ImageResult> {
142
+ const wrapper = readEnv('H3_IMAGE_MLX_BIN');
143
+ if (wrapper === '') {
144
+ throw new Error(
145
+ 'h3-local provider requires H3_IMAGE_MLX_BIN pointing at an executable h3gen.sh (or set the provider explicitly with IMAGE_GEN_PROVIDER).',
146
+ );
147
+ }
148
+
149
+ const canvas =
150
+ req.width !== undefined && req.height !== undefined && h3ExactSize(req.width, req.height)
151
+ ? { width: req.width, height: req.height }
152
+ : (h3Canvas(req.aspectRatio) ?? { width: 1024, height: 1024 });
153
+
154
+ const sessionDir = resolve(tmpdir(), 'kk-image-gen-h3-local');
155
+ await mkdir(sessionDir, { recursive: true });
156
+ const tmpOutput = resolve(sessionDir, `out-${randomBytes(8).toString('hex')}.png`);
157
+
158
+ const args: string[] = [
159
+ '--prompt',
160
+ req.prompt,
161
+ '--output',
162
+ tmpOutput,
163
+ '--width',
164
+ String(canvas.width),
165
+ '--height',
166
+ String(canvas.height),
167
+ ];
168
+ for (const ref of req.referenceImages ?? []) {
169
+ args.push('--reference', resolve(ref));
170
+ }
171
+
172
+ try {
173
+ const spawnResult = await spawnWrapper(wrapper, args, timeoutMs);
174
+ if (spawnResult.timedOut) {
175
+ throw new Error(
176
+ `h3-local wrapper timed out after ${timeoutMs}ms (${canvas.width}x${canvas.height})${stderrTail(spawnResult.stderr)}`,
177
+ );
178
+ }
179
+ if (spawnResult.code !== 0) {
180
+ throw new Error(
181
+ `h3-local wrapper exited with code ${spawnResult.code}${stderrTail(spawnResult.stderr)}`,
182
+ );
183
+ }
184
+ const bytes = await readBytes(tmpOutput).catch(() => null);
185
+ if (bytes === null) {
186
+ throw new Error(
187
+ `h3-local wrapper wrote no output at ${tmpOutput}${stderrTail(spawnResult.stderr)}`,
188
+ );
189
+ }
190
+ return { bytes, extension: 'png', provider: 'h3-local', model: req.model };
191
+ } finally {
192
+ await rm(tmpOutput, { force: true }).catch(() => undefined);
193
+ }
194
+ },
195
+ };
196
+ };
@@ -14,6 +14,7 @@ import { createAzure } from './azure';
14
14
  import { createCodexCli } from './codex-cli';
15
15
  import { createDashscope } from './dashscope';
16
16
  import { createGoogle } from './google';
17
+ import { createH3Local } from './h3-local';
17
18
  import { createHuggingface } from './huggingface';
18
19
  import { createJimeng } from './jimeng';
19
20
  import { createMinimax } from './minimax';
@@ -111,7 +112,7 @@ export type ProviderFactory = (options?: ProviderOptions) => ImageProvider;
111
112
  const IMAGE_GEN_PROVIDER_ENV = 'IMAGE_GEN_PROVIDER';
112
113
 
113
114
  /** Providers that may never be auto-selected, even if listed in AUTO_ORDER later (task 0103 R3). */
114
- const NEVER_AUTO: ReadonlySet<string> = new Set(['codex-cli']);
115
+ const NEVER_AUTO: ReadonlySet<string> = new Set(['codex-cli', 'h3-local']);
115
116
 
116
117
  /** Registry row: the availability facts an adapter must honour, verbatim from its baoyu source. */
117
118
  interface ProviderSpec {
@@ -170,6 +171,15 @@ export const PROVIDERS: Readonly<Record<string, ProviderRegistration>> = {
170
171
  ],
171
172
  create: createGoogle,
172
173
  },
174
+ 'h3-local': {
175
+ name: 'h3-local',
176
+ env: ['H3_IMAGE_MLX_BIN'],
177
+ defaultModel: 'h3',
178
+ // Local MLX runtime: readiness is the env var, but a render costs minutes of wall time,
179
+ // so it stays opt-in (never auto-selected) unless the operator pins it (0379, feature K2).
180
+ note: 'requires H3_IMAGE_MLX_BIN pointing at the local h3gen.sh wrapper (never auto-selected)',
181
+ create: createH3Local,
182
+ },
173
183
  huggingface: {
174
184
  name: 'huggingface',
175
185
  env: ['HUGGINGFACE_API_TOKEN'],
@@ -0,0 +1,277 @@
1
+ # music-gen
2
+
3
+ Music generation over the homelab Lyria 3 instance (`POST /api/lyria/generate`), as a
4
+ `kind: generator` plugin.
5
+
6
+ **Status: the plugin ships (task 0398).** The 0397 contract — the `MusicBrief` Zod schema, the
7
+ deterministic prompt renderer, the instance request mapping, preset resolution and the canonical
8
+ digest input — plus the plugin itself: `plugin.json`, the live instance adapter with the
9
+ non-idempotent paid-call policy, the cache-first analyse, the offline adapter
10
+ (`KK_MUSIC_DRY_RUN=1`), the artifact + take sidecar and the `Content` mapping. The format × theme
11
+ presets ship in 0399 (`presets/`, indexed below by a generator). The spend guard lands in 0400, the
12
+ `kk music` noun in 0401, the workflow in 0403 and measurement in 0405.
13
+
14
+ Contract authority: [`docs/design/music-gen.md`](../../../docs/design/music-gen.md). That document
15
+ owns the wire contract, the render order, preset precedence, the adapter contract, the paid-call
16
+ failure table, the environment variables and the artifact record. This README owns the **authoring
17
+ form** — the YAML a person writes — the preset index and how to run the plugin.
18
+
19
+ ```text
20
+ plugins/generations/music-gen/
21
+ plugin.json # kind: generator, entry ./src/index.ts, runtime.requires
22
+ src/brief.ts # MusicBrief schema + m:ss helpers + the field→target table
23
+ src/render.ts # kk-owned PROMPT text, frozen segment order
24
+ src/request.ts # POST /api/lyria/generate body, no instance defaults
25
+ src/presets.ts # brief > workflow > theme > format > built-in, portability guard
26
+ src/digest.ts # canonical digest input for 0400 dedupe / 0398 provenance
27
+ src/job.ts # the --in envelope: brief from docs[0].body, knobs from metadata
28
+ src/config.ts # music.instance.* / music.prices.* + KK_MUSIC_* overrides
29
+ src/adapter/instance.ts # the live HTTP adapter and the paid-call policy
30
+ src/adapter/offline.ts # KK_MUSIC_DRY_RUN=1: silent WAV, synthetic manifest, zero network
31
+ src/adapter/index.ts # adapter selection (dry run → offline)
32
+ src/audio.ts # delivered-container detection + the deterministic silent WAV
33
+ src/artifact.ts # <slug>-<model>-<instanceId>.<ext> naming + the take sidecar
34
+ src/content.ts # Content mapping: format audio, liner notes, references, echoes
35
+ src/plugin.ts # the take loop: read → generate → persist → map
36
+ src/index.ts # the published contract surface + the plugin entry
37
+ presets/formats/*.yaml # 0399: job intent, model, duration target, section skeleton, lyrics policy
38
+ presets/themes/*.yaml # 0399: technical direction prose, avoid[], instrumentation palette
39
+ presets/SOURCE.md # 0399: provenance + evidence-promotion rules
40
+ scripts/gen-preset-index.ts # 0399: README index generator (--check fails on drift)
41
+ scripts/resolve-preset.ts # 0399: resolve a brief through the presets and print the trace
42
+ tests/ # bun:test; fixtures/<name>/{brief.yaml,prompt.txt,request.json}
43
+ ```
44
+
45
+ Nothing outside `src/adapter/` opens a socket, and nothing in the plugin (or its tests) ever makes a
46
+ paid call: the adapter takes an injected `fetch` seam and every test supplies its own.
47
+
48
+ ## 1. Authoring a brief
49
+
50
+ The brief is the only input document. `src/brief.ts` is the only schema — this file is the authoring
51
+ form, not a second definition. Unknown keys are rejected, so a typo fails at parse time instead of
52
+ being silently dropped.
53
+
54
+ ```yaml
55
+ # midnight-cable-car.yaml
56
+ title: Midnight Cable Car # required — the instance's library title (request: title)
57
+ format: song # required — format preset name (resolution input)
58
+ theme: synthwave # required — theme preset name (resolution input)
59
+ model: pro # optional — pro | clip (default: format preset, then pro)
60
+ duration_target: "0:30" # optional — m:ss, 0:05–3:00; required somewhere for Pro
61
+ language: EN # optional — short tag (default: EN, always sent)
62
+ instrumental: false # optional — true sends lyrics: "" and appends the directive
63
+ audio_format: mp3 # optional — mp3 | wav (request: format)
64
+ style: |- # optional — technical direction, the first prompt segment
65
+ Warm analog synthwave at 92 BPM in A minor: detuned pad, gated snare, round sub bass.
66
+ Vocal: intimate female alto, close-mic, no reverb tail.
67
+ avoid: # optional — prompt deny-list, merged with the preset lists
68
+ - trap hi-hats
69
+ - EDM riser clichés
70
+ structure: # optional — timestamped sections, non-decreasing `at`
71
+ - at: "0:00"
72
+ section: Intro
73
+ note: filtered pad, no drums for four bars
74
+ - at: "0:20"
75
+ section: Chorus
76
+ note: hook lyric repeated, gated snare opens up
77
+ lyrics: |- # optional — song text; omitted → the model writes its own
78
+ [Verse]
79
+ Last tram humming through the rain
80
+ [Chorus]
81
+ Midnight cable car, carry me home
82
+ images: [] # optional — up to 10 reference image paths, in order
83
+ takes: 1 # optional — 1..4 sequential requests (batchCount is always 1)
84
+ meta: # optional — recorded in the take sidecar only, never sent
85
+ author: operator
86
+ ```
87
+
88
+ Field rules that bite:
89
+
90
+ | Field | Rule |
91
+ | --- | --- |
92
+ | `format` / `theme` | Must name a preset; an unknown name is a resolution error, never a silent fallback. |
93
+ | `duration_target` | `m:ss`, `0:05`–`3:00`. Required for `model: pro` from some layer (the instance would otherwise send `3:00`). Ignored for `clip` and must stay near `0:30` if you write it. |
94
+ | `language` | Always sent. kk never renders a `Lyrics (sing in …)` line — the instance appends that block itself. |
95
+ | `style` | Required from some layer. It is the technical direction segment — the only control surface the model has. kk never writes duration prose. |
96
+ | `avoid` | Rendered as one `Avoid: a, b` segment, omitted when empty. Additive across layers. |
97
+ | `structure` | Rendered as `[m:ss] Section — note` lines, in authored order. Replaced (not merged) by a higher-precedence layer. |
98
+ | `lyrics` | Sent as the request field. An `instrumental: true` brief may not also carry lyrics. |
99
+ | `takes` | N sequential, separately billed requests — never one batched call. |
100
+ | `meta` | Never sent to the instance; it lands in the take sidecar. |
101
+
102
+ Presets are portable data. A preset file may not declare a provider, API base URL, API model id,
103
+ credential or price — `assertPresetPortable` rejects the file with exit code 2. Prices live in user
104
+ config (`music.prices`, 0400); `model: pro|clip` is the instance's own selector and stays allowed.
105
+
106
+ ## 2. Preset index
107
+
108
+ `formats/` and `themes/` ship as data (task 0399). Any format pairs with any theme: the **format**
109
+ owns the arc (model, default duration target, section skeleton, lyrics policy) and the **theme** owns
110
+ the sound (the technical-direction prose the model reads, plus its default `avoid[]`). The table
111
+ below is generated from those files, so the index cannot drift from the data.
112
+
113
+ <!-- preset-index:start -->
114
+ `formats/`: 5 · `themes/`: 4. Regenerate with
115
+ `bun plugins/generations/music-gen/scripts/gen-preset-index.ts`; `--check` fails on drift.
116
+
117
+ ### Formats
118
+
119
+ A format fixes the job intent, the instance selector (`pro|clip`), the default duration target and the
120
+ timestamped section skeleton. `lyrics` is the format’s policy: `forbidden` resolves `instrumental: true`.
121
+
122
+ | Format | Model | Default duration | Lyrics | Intended use | Status |
123
+ | --- | --- | --- | --- | --- | --- |
124
+ | `clip` | `clip` | — (clip is fixed at ~0:30) | allowed | Quick preview, a direction check before a pro run, or a short social cut. | `authored` |
125
+ | `jingle` | `pro` | `0:20` | allowed | Product or station ident — the hook states the name once and resolves fast. | `authored` |
126
+ | `loop` | `clip` | — (clip is fixed at ~0:30) | forbidden | Background bed for a talk-through, demo or menu loop; no vocals by design. | `authored` |
127
+ | `song` | `pro` | `2:30` | allowed | A complete track with a sung hook; the default for lyrical pieces. | `authored` |
128
+ | `underscore` | `pro` | `0:45` | forbidden | Underscore under spoken narration or a video essay; no hook or vocal required. | `authored` |
129
+
130
+ ### Themes
131
+
132
+ A theme supplies the technical-direction prose the model reads — genre, tempo, key, instrumentation,
133
+ vocal character and production — plus its default `avoid[]`, rendered as one `Avoid: …` segment.
134
+
135
+ | Theme | Technical direction | Default avoid | Intended use | Status |
136
+ | --- | --- | --- | --- | --- |
137
+ | `ambient-tech` | glassy ambient techno; 100-115 BPM, steady and unaccented; C# minor | hard drops, talkbox vocals, pop hooks, vocal chops | Product walkthroughs, conference holds, editorial beds that must stay out of the way. | `authored` |
138
+ | `cinematic` | cinematic orchestral hybrid score; 60-90 BPM with rubato swells; D minor | horror stingers, orchestral hits on every downbeat, distorted electric guitar, pop chorus stacks | Trailer-style openings, story intros, a track that must feel like a scene. | `authored` |
139
+ | `lofi` | dusty sampled lo-fi hip-hop; 70-85 BPM, swung and unhurried; A minor | trap hi-hat rolls, hard drops, EDM riser clichés, over-compressed loudness | Study/focus background, calm narration bed, unhurried social cuts. | `authored` |
140
+ | `synthwave` | analog synthwave revival; 90-110 BPM, straight four-on-the-floor; A minor | festival supersaws, EDM risers, distorted djent guitars, modern trap percussion | Retro-tech explainers, night-drive montages, upbeat product stings. | `authored` |
141
+ <!-- preset-index:end -->
142
+
143
+ Evidence status: `authored` means written from the design contract with no generated take judged
144
+ against it yet, `evidence-pending` means queued for a real generation round, and `verified` means a
145
+ reviewed take exists — the rules live in [`presets/SOURCE.md`](presets/SOURCE.md). `corporate-tech`
146
+ and `xhs-pop` are deliberately not shipped: no generated track has produced evidence for them yet.
147
+
148
+ ## 3. Running the plugin
149
+
150
+ The plugin is invoked the way every generator is — a `DocList` in, a `Content` out:
151
+
152
+ ```bash
153
+ bun plugins/generations/music-gen/src/index.ts --in docs.json --out content.json
154
+ ```
155
+
156
+ `docs[0].body` carries the brief in the YAML authoring form above. `docs[0].metadata.musicGen` carries
157
+ only what is *not* the brief, and is strict (an unknown key is an error, never silently dropped):
158
+
159
+ ```yaml
160
+ metadata:
161
+ musicGen:
162
+ presets: # 0399 loads these from disk; accepted inline here
163
+ format: { name: loop, style: "Glassy texture at 110 BPM." }
164
+ theme: { name: ambient-tech }
165
+ outputStem: midnight-cable-car # overrides the artifact slug (default: the brief title)
166
+ force: true # a paid re-send the operator accepted (0400 records it)
167
+ reason: "the first take was unusable"
168
+ ```
169
+
170
+ ### 3.1 Configuration
171
+
172
+ One reader, three layers: **environment override > `music:` config key > documented default**. The
173
+ config file is the existing kk user config (`KK_CONFIG`, else `~/.config/kk/config.yaml`).
174
+
175
+ | Setting | Environment | Config key | Default |
176
+ | --- | --- | --- | --- |
177
+ | Instance base URL | `KK_MUSIC_INSTANCE_URL` | `music.instance.url` (alias `music.baseUrl`) | `http://127.0.0.1:3000` |
178
+ | Generate timeout (ms) | `KK_MUSIC_TIMEOUT_MS` | `music.instance.timeoutMs` (alias `music.timeoutMs`) | `180000` |
179
+ | Connect timeout (ms) | — | `music.instance.connectTimeoutMs` | `5000` |
180
+ | Offline adapter | `KK_MUSIC_DRY_RUN=1` | — | unset (live) |
181
+ | Unit prices | — (0400) | `music.prices.{pro,clip,analyze}` | `pro 0.08`, `clip 0.04`, `analyze` unpriced |
182
+ | Take cap | — (0400) | `music.takesCap` | `2`, never above `4` |
183
+ | Workflow run id | `KK_MUSIC_RUN_ID` | — | unset (recorded in the sidecar when present) |
184
+
185
+ A key that is *present* but of the wrong type throws, naming the key — a silently defaulted endpoint
186
+ or timeout would send a paid request somewhere unexpected. The default base URL is provisional: it
187
+ assumes the instance listens on loopback port 3000, and 0404's dogfood pins the real value.
188
+
189
+ ### 3.1.1 The spend guard (task 0400)
190
+
191
+ One enforcement point, `src/spend.ts`, runs before the adapter exists — so a refused run prints its
192
+ estimate and stops without opening a socket:
193
+
194
+ | Step | Rule | Refusal names |
195
+ | --- | --- | --- |
196
+ | Estimate | prompt, resolved model, takes, unit price, total from `music.prices`; `analyze` has no default and renders `unpriced` | — |
197
+ | Confirmation | no paid call without `--yes` (or the workflow var the HITL gate sets); an unpriced call still needs it | `--yes` |
198
+ | Dedupe | the 0397 per-take digest is compared with the sidecars in the **run directory**; a match prints the existing artifact path and digest | `--force --reason <text>` |
199
+ | Takes cap | `music.takesCap` (default 2, hard max 4); over the cap is refused, never trimmed | `--takes` (and the cap) |
200
+
201
+ ```bash
202
+ # print the cost and stop: no socket, no artifact (exit 0)
203
+ bun plugins/generations/music-gen/src/index.ts --in docs.json --out content.json --estimate-only
204
+
205
+ # a paid run needs --yes; a deliberate re-roll needs --force --reason
206
+ bun plugins/generations/music-gen/src/index.ts --in docs.json --out content.json --yes
207
+ bun plugins/generations/music-gen/src/index.ts --in docs.json --out content.json --yes --force --reason "first take was unusable"
208
+ ```
209
+
210
+ The dedupe scope is the run directory, not the digest: the same brief in another topic's run
211
+ directory is a legitimate re-roll. A resumed run that re-requests an already-paid take is therefore
212
+ refused by default — resume it with `--force --reason` so the re-spend is recorded, never repeated
213
+ silently.
214
+
215
+ ### 3.2 The paid-call policy
216
+
217
+ `POST /api/lyria/generate` and `POST /api/ai/analyze` are **non-idempotent**: the instance may have
218
+ billed and persisted a take even when kk never saw the response. The adapter therefore:
219
+
220
+ - **retries only connect-phase failures** (`ECONNREFUSED`, `ENOTFOUND`, `EAI_AGAIN`,
221
+ `EHOSTUNREACH`, `ENETUNREACH`, a connect timeout), bounded to 3 attempts — the request provably
222
+ never reached the instance;
223
+ - treats `401`, `402`, `403`, `404`, `429` and the all-keys-rejected `502` as **terminal**: one
224
+ request sent, no retry, the instance's own error text plus a remediation;
225
+ - **never re-sends after an ambiguous outcome** (a timeout after send, `ECONNRESET`, any other `5xx`,
226
+ an unparseable `200`, a `200` with no audio). It reconciles against `GET /api/generations` and
227
+ adopts the earliest take whose `prompt` is byte-equal to what kk sent, whose `model` matches and
228
+ whose `generatedAt` is at or after the request start — flagging it `adoptedByReconciliation` and
229
+ listing any later matches as `unclaimed`. No match fails naming the endpoint, the elapsed time and
230
+ the `--force` remediation.
231
+
232
+ `analyze` is **cache-first**: the instance caches analysis per generation, so the manifest is read
233
+ first and the paid `POST /api/ai/analyze` is issued only when no analysis is cached. An ambiguous
234
+ analyse re-reads the manifest — it never pays twice.
235
+
236
+ ### 3.3 Artifacts and sidecars
237
+
238
+ One artifact per take, in the `--out` directory:
239
+
240
+ ```text
241
+ <slug>-<model>-<instanceId>.<ext> # e.g. midnight-cable-car-clip-gen_01.mp3
242
+ <slug>-<model>-<instanceId>.<ext>.take.json
243
+ ```
244
+
245
+ The delivered container (`ext`) is detected from the returned bytes, never assumed from the request's
246
+ `audio_format`. The sidecar carries the 0397 digest and digest input, the instance id, the model, the
247
+ unit price charged, the adoption flag, the unclaimed extra takes, the exact request body and
248
+ `language` / `durationTarget` / `batchCount` **exactly as the instance recorded them** (absent when the
249
+ manifest lacked them, never defaulted). The instance's `generations/` library is never mirrored into a
250
+ kk workspace.
251
+
252
+ `takes: N` is N sequential single-take requests. A failure on take k leaves takes 1..k-1 on disk — a
253
+ resume reaches them through 0400's dedupe, which refuses to pay for a take the run already owns unless
254
+ the operator passes `--force --reason` — and writes no `--out` file.
255
+
256
+ ### 3.4 Offline
257
+
258
+ ```bash
259
+ KK_MUSIC_DRY_RUN=1 bun plugins/generations/music-gen/src/index.ts --in docs.json --out content.json
260
+ ```
261
+
262
+ The offline adapter emits a deterministic 1-second silent WAV, a synthetic manifest (`offline-take-<n>`)
263
+ and a synthetic analysis, with **zero network calls by construction** — it holds no fetch seam. It is
264
+ the default for this plugin's whole test suite, so no test can spend money.
265
+
266
+ ## 4. Tests
267
+
268
+ ```bash
269
+ bun test plugins/generations/music-gen
270
+ ```
271
+
272
+ Fully offline. The four golden fixtures pin the prompt text and request JSON byte for byte; the
273
+ preset-portability test spawns a loader to prove the non-zero exit; and every adapter test runs
274
+ against an injected `fetch` stub, covering success, format detection, manifest mapping, cache-first
275
+ analyse, each terminal status, the connect-retry bound, timeout → reconciliation adopt,
276
+ timeout → miss → fail, and malformed JSON. The discoverability test runs kk-core's own registry over
277
+ `plugins/` and compares `plugin.json`'s `runtime.requires` against the modules `src/` imports.