@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,87 @@
1
+ import type { StructureEntry } from './brief';
2
+ import type { ResolvedJob } from './presets';
3
+
4
+ /**
5
+ * The kk-owned PROMPT text (task 0397 R2): a deterministic renderer for the
6
+ * instance's PROMPT box only.
7
+ *
8
+ * Segment order is frozen at
9
+ * `technical direction → Avoid: … → timestamped structure lines → instrumental directive`,
10
+ * with each segment on its own line and the `Avoid:` segment omitted when the
11
+ * merged list is empty.
12
+ *
13
+ * kk never renders the duration sentence or the lyrics block: the instance's
14
+ * `assembleLyriaPrompt` appends both server-side and defaults a missing
15
+ * `durationTarget` to `'3:00'`, so rendering them here would duplicate them.
16
+ * The markers are exported so an adapter or test can prove their absence.
17
+ */
18
+
19
+ /** Exact instrumental directive (R2, em dash deliberate). */
20
+ export const INSTRUMENTAL_DIRECTIVE = 'Instrumental only — no vocals.';
21
+
22
+ /** Exact `Avoid:` segment prefix. */
23
+ export const AVOID_PREFIX = 'Avoid: ';
24
+
25
+ /**
26
+ * Segments the INSTANCE owns. kk output must never contain them; they are
27
+ * markers for assertions, not a render-time rejection — an author's technical
28
+ * direction may legitimately use the words in another sense.
29
+ */
30
+ export const INSTANCE_OWNED_PROMPT_MARKERS = ['Total running time', 'Lyrics (sing in'] as const;
31
+
32
+ /** The four prompt segments, already resolved. */
33
+ export interface PromptSegments {
34
+ /** Technical direction: the theme/format/brief style text, first segment. */
35
+ style: string;
36
+ /** Merged deny-list; rendered only when non-empty, in the given order. */
37
+ avoid: readonly string[];
38
+ /** Timestamped structure lines, rendered in the given order. */
39
+ structure: readonly StructureEntry[];
40
+ /** When true, append {@link INSTRUMENTAL_DIRECTIVE}. */
41
+ instrumental: boolean;
42
+ }
43
+
44
+ /** Trim trailing spaces per line and drop leading/trailing blank lines, keeping interior newlines. */
45
+ function normalizeBlock(text: string): string {
46
+ return text
47
+ .split('\n')
48
+ .map((line) => line.replace(/\s+$/, ''))
49
+ .join('\n')
50
+ .replace(/^\n+/, '')
51
+ .replace(/\n+$/, '');
52
+ }
53
+
54
+ /** One structure line: `[m:ss] Section` or `[m:ss] Section — note`. */
55
+ export function renderStructureLine(entry: StructureEntry): string {
56
+ const head = `[${entry.at}] ${entry.section}`;
57
+ return entry.note === undefined ? head : `${head} — ${entry.note}`;
58
+ }
59
+
60
+ /** Render the kk-owned prompt text. Pure: same input, same bytes, no clock, no IO. */
61
+ export function renderPromptText(segments: PromptSegments): string {
62
+ const blocks: string[] = [];
63
+ const direction = normalizeBlock(segments.style);
64
+ if (direction !== '') {
65
+ blocks.push(direction);
66
+ }
67
+ if (segments.avoid.length > 0) {
68
+ blocks.push(`${AVOID_PREFIX}${segments.avoid.join(', ')}`);
69
+ }
70
+ for (const entry of segments.structure) {
71
+ blocks.push(renderStructureLine(entry));
72
+ }
73
+ if (segments.instrumental) {
74
+ blocks.push(INSTRUMENTAL_DIRECTIVE);
75
+ }
76
+ return blocks.join('\n');
77
+ }
78
+
79
+ /** Render the prompt text from a resolved job (the normal call path). */
80
+ export function renderBriefPrompt(job: ResolvedJob): string {
81
+ return renderPromptText({
82
+ style: job.style.value,
83
+ avoid: job.avoid.value,
84
+ structure: job.structure.value,
85
+ instrumental: job.instrumental.value,
86
+ });
87
+ }
@@ -0,0 +1,102 @@
1
+ import type { AudioFormat, MusicModel } from './brief';
2
+ import type { ResolvedJob } from './presets';
3
+ import { renderBriefPrompt } from './render';
4
+
5
+ /**
6
+ * Request mapping (task 0397 R3): the exact JSON body kk posts to
7
+ * `POST /api/lyria/generate`, built from a resolved job alone.
8
+ *
9
+ * No field may fall through to an instance default:
10
+ * - `durationTarget` is always present for `model: pro` (the instance would
11
+ * otherwise substitute `'3:00'`, turning a 0:30 jingle into a three-minute
12
+ * request) and never present for `model: clip` (clip is fixed at about 0:30).
13
+ * - `language` is always present (the instance default is `EN`).
14
+ * - `instrumental: true` sends `lyrics: ''`.
15
+ * - `batchCount` is a recorded label, not a multi-sample knob — the instance
16
+ * makes exactly one provider call per request, so every request is
17
+ * single-take (`batchCount: 1`) and `takes: N` means N sequential requests.
18
+ */
19
+
20
+ /** The wire body, in the frozen key order the goldens pin. */
21
+ export interface MusicGenerateRequest {
22
+ prompt: string;
23
+ lyrics?: string;
24
+ language: string;
25
+ model: MusicModel;
26
+ durationTarget?: string;
27
+ format: AudioFormat;
28
+ title: string;
29
+ batchCount: number;
30
+ images?: string[];
31
+ }
32
+
33
+ /**
34
+ * Canonical key order of the request body. `images` stays last so the body
35
+ * reads prompt-first; the order is pinned by the golden request JSON.
36
+ */
37
+ export const REQUEST_KEY_ORDER = [
38
+ 'prompt',
39
+ 'lyrics',
40
+ 'language',
41
+ 'model',
42
+ 'durationTarget',
43
+ 'format',
44
+ 'title',
45
+ 'batchCount',
46
+ 'images',
47
+ ] as const;
48
+
49
+ /**
50
+ * Which brief field each wire field comes from (R1 totality). `durationTarget`
51
+ * is `null` for a clip job by contract, not by omission.
52
+ */
53
+ export const REQUEST_FIELD_ORIGINS: Record<keyof MusicGenerateRequest, string> = {
54
+ prompt: 'style + avoid + structure + instrumental (rendered prompt text)',
55
+ lyrics: 'lyrics (empty string when instrumental)',
56
+ language: 'language',
57
+ model: 'model',
58
+ durationTarget: 'duration_target (pro only)',
59
+ format: 'audio_format',
60
+ title: 'title',
61
+ batchCount: 'takes — always 1 per request',
62
+ images: 'images',
63
+ };
64
+
65
+ /** Build the single-take request body for a resolved job. Pure and deterministic. */
66
+ export function renderGenerateRequest(job: ResolvedJob): MusicGenerateRequest {
67
+ const model = job.model.value;
68
+ const durationTarget = model === 'pro' ? job.duration_target.value : undefined;
69
+ if (model === 'pro' && durationTarget === undefined) {
70
+ // resolveJob already refuses this; the assertion keeps a hand-built job from reaching the wire.
71
+ throw new Error('a pro request without durationTarget would fall through to the instance default "3:00"');
72
+ }
73
+ const images = job.images;
74
+ return {
75
+ prompt: renderBriefPrompt(job),
76
+ ...(job.lyrics === undefined ? {} : { lyrics: job.lyrics }),
77
+ language: job.language.value,
78
+ model,
79
+ ...(durationTarget === undefined ? {} : { durationTarget }),
80
+ format: job.audio_format.value,
81
+ title: job.title,
82
+ batchCount: 1,
83
+ ...(images.length === 0 ? {} : { images: [...images] }),
84
+ };
85
+ }
86
+
87
+ /**
88
+ * One request per take: `takes: N` renders N structurally identical
89
+ * single-take requests (the client loop lives in 0398/0400, and each take is
90
+ * billed and persisted separately by the instance).
91
+ */
92
+ export function renderTakeRequests(job: ResolvedJob): MusicGenerateRequest[] {
93
+ return Array.from({ length: job.takes }, () => renderGenerateRequest(job));
94
+ }
95
+
96
+ /**
97
+ * Serialize a request exactly as the goldens pin it: repo-standard 4-space
98
+ * JSON plus one trailing newline, so `biome check` never rewrites a fixture.
99
+ */
100
+ export function serializeRequest(request: MusicGenerateRequest): string {
101
+ return `${JSON.stringify(request, null, 4)}\n`;
102
+ }
@@ -0,0 +1,495 @@
1
+ import { join } from 'node:path';
2
+ import { createNodeFileSystem, type FileSystem } from '@gobing-ai/ts-runtime';
3
+ import { TAKE_SIDECAR_SUFFIX } from './artifact';
4
+ import { MAX_TAKES } from './brief';
5
+ import type { MusicPrices } from './config';
6
+ import { type TakeDigest, takeDigest } from './digest';
7
+ import type { ResolvedJob } from './presets';
8
+ import { renderBriefPrompt } from './render';
9
+
10
+ /**
11
+ * The spend guard (task 0400 R1–R5): the plugin's **one enforcement point for
12
+ * money**.
13
+ *
14
+ * Every paid request this plugin can make — `POST /api/lyria/generate` per take
15
+ * and `POST /api/ai/analyze` — goes through {@link estimateGenerate} /
16
+ * {@link estimateAnalyze} plus {@link requireConfirmation}, and every generate
17
+ * additionally through {@link planGeneration}'s run-scoped dedupe and take cap.
18
+ * `0401` wires the same functions into the `kk music` verbs, and the workflow
19
+ * reaches them only through those verbs, so the skill, the CLI and the workflow
20
+ * cannot each invent their own spend policy.
21
+ *
22
+ * The four rules, in the order {@link planGeneration} applies them:
23
+ *
24
+ * 1. **Estimate first (R1).** `kk prompt text, model, takes, unit price, total`
25
+ * from `music.prices.{pro,clip,analyze}`. `analyze` has no built-in price, so
26
+ * it renders as `unpriced` — never "free" — and an unpriced estimate still
27
+ * demands confirmation.
28
+ * 2. **Confirmation (R2).** No paid call without `--yes` (or the workflow var
29
+ * the HITL gate sets). The refusal prints the estimate first.
30
+ * 3. **Run-scoped dedupe (R3).** The 0397 per-take digest is compared against the
31
+ * sidecars already in the run directory. A match refuses and names the
32
+ * existing artifact path; `--force --reason <text>` overrides and records
33
+ * both. The lookup location is the scope: the same brief in another topic's
34
+ * run directory is a legitimate re-roll, so the digest itself stays pure
35
+ * content and remains a valid cross-run provenance key.
36
+ * 4. **Takes cap (R4).** `music.takesCap`, default {@link DEFAULT_TAKES_CAP},
37
+ * never above {@link HARD_TAKES_CAP}. Over the cap is a refusal, never a
38
+ * silent trim.
39
+ *
40
+ * Every refusal is a {@link SpendRefusal} carrying the exact flag that resolves
41
+ * it (R5), and its message contains that flag verbatim, so a caller cannot
42
+ * surface a refusal without the remediation.
43
+ */
44
+
45
+ /**
46
+ * Takes per invocation when `music.takesCap` is unset (§6.1: "Take cap … `2`,
47
+ * never above `4`"). Two is enough for a judge-two-takes-then-pick workflow and
48
+ * caps the cost of a mistaken re-run at two requests.
49
+ */
50
+ export const DEFAULT_TAKES_CAP = 2;
51
+
52
+ /**
53
+ * Ceiling `music.takesCap` may never exceed — the brief's own `takes` bound
54
+ * (`MAX_TAKES`), so the config cannot authorize a count the brief schema would
55
+ * reject, and one number owns "the hard cap is 4".
56
+ */
57
+ export const HARD_TAKES_CAP: number = MAX_TAKES;
58
+
59
+ /** What a refusal is about: a generate run or a single analyze call. */
60
+ export type SpendKind = 'generate' | 'analyze';
61
+
62
+ /**
63
+ * Raised by every spend refusal (R2/R3/R4/R5).
64
+ *
65
+ * `flag` is the exact thing that resolves it — a CLI flag (`--yes`,
66
+ * `--force --reason <text>`, `--takes`) or the config key `music.takesCap` — and
67
+ * the message always contains it, so "make refusals actionable" is a property of
68
+ * the type rather than of each call site.
69
+ */
70
+ export class SpendRefusal extends Error {
71
+ /** Process exit code the command layer must surface. */
72
+ readonly exitCode = 1;
73
+ /** The exact flag (or config key) that resolves this refusal. */
74
+ readonly flag: string;
75
+ /** Machine-readable context: the existing artifact path, the digest, the cap. */
76
+ readonly detail: Readonly<Record<string, string | number | boolean>>;
77
+
78
+ constructor(
79
+ reason: string,
80
+ options: {
81
+ flag: string;
82
+ /** Overrides the default `pass <flag>` remediation wording. */
83
+ remedy?: string;
84
+ detail?: Record<string, string | number | boolean>;
85
+ },
86
+ ) {
87
+ super(`music spend guard: ${reason} — ${options.remedy ?? `pass ${options.flag}`}`);
88
+ this.name = 'SpendRefusal';
89
+ this.flag = options.flag;
90
+ this.detail = { ...(options.detail ?? {}) };
91
+ }
92
+ }
93
+
94
+ /** The spend knobs a caller may pass: `--yes`, `--force --reason <text>`, `--takes <n>`. */
95
+ export interface SpendRequest {
96
+ /** `--yes`, or the workflow var the HITL gate sets (R2). */
97
+ confirmed?: boolean;
98
+ /** `--force`: override a run-scoped duplicate (R3). Meaningless without `reason`. */
99
+ force?: boolean;
100
+ /** `--reason <text>`: why the paid re-send was accepted; recorded in the sidecar. */
101
+ reason?: string;
102
+ /** `--takes <n>`: take-count override, still bounded by `music.takesCap` (R4). */
103
+ takes?: number;
104
+ }
105
+
106
+ /** Where the rendered estimate goes (`--estimate-only`'s only side effect). */
107
+ export type SpendEmit = (block: string) => void;
108
+
109
+ /** A resolved pre-spend estimate (R1). */
110
+ export interface SpendEstimate {
111
+ kind: SpendKind;
112
+ /** The kk prompt text the provider will actually see; `null` for analyze. */
113
+ prompt: string | null;
114
+ /** The resolved model selector (`pro`/`clip`), or the take's recorded model for analyze. */
115
+ model: string | null;
116
+ /** How many paid requests this estimate covers. */
117
+ takes: number;
118
+ /** Per-request price from `music.prices`; `null` = unpriced, never zero. */
119
+ unitPrice: number | null;
120
+ /** `unitPrice × takes`; `null` when unpriced. */
121
+ total: number | null;
122
+ /** True when no price is configured — the confirmation gate still applies. */
123
+ unpriced: boolean;
124
+ /** The instance take an analyze estimate covers. */
125
+ instanceId?: string;
126
+ }
127
+
128
+ /** Input for {@link estimateGenerate}. */
129
+ export interface GenerateEstimateInput {
130
+ job: ResolvedJob;
131
+ /** Resolved `music.prices` (defaults already applied by `config.ts`). */
132
+ prices: MusicPrices;
133
+ /** Take count this estimate covers — already validated against the cap. */
134
+ takes: number;
135
+ }
136
+
137
+ /** Input for {@link estimateAnalyze}. */
138
+ export interface AnalyzeEstimateInput {
139
+ prices: MusicPrices;
140
+ /** The instance take to analyze. */
141
+ instanceId: string;
142
+ /** The model recorded on the take, when the caller knows it. Display only. */
143
+ model?: string;
144
+ }
145
+
146
+ /** One take's digest, as the dedupe scan needs it. */
147
+ export interface TakeDigestEntry {
148
+ takeIndex: number;
149
+ digest: string;
150
+ }
151
+
152
+ /** A take already paid for in this run directory (R3). */
153
+ export interface RunDirDuplicate {
154
+ takeIndex: number;
155
+ /** The 0397 per-take digest that matched. */
156
+ digest: string;
157
+ /** Absolute path of the artifact the earlier take wrote — what the refusal shows. */
158
+ artifactPath: string;
159
+ /** Absolute path of the matching sidecar. */
160
+ sidecarPath: string;
161
+ }
162
+
163
+ /** Resolve the effective takes cap from the configured value (R4). */
164
+ export function resolveTakesCap(configured: number | undefined): number {
165
+ if (configured === undefined) {
166
+ return DEFAULT_TAKES_CAP;
167
+ }
168
+ if (!Number.isInteger(configured) || configured < 1) {
169
+ throw new SpendRefusal(`music.takesCap is ${String(configured)}, which is not a positive integer`, {
170
+ flag: 'music.takesCap',
171
+ remedy: 'set music.takesCap to a whole number between 1 and 4',
172
+ });
173
+ }
174
+ if (configured > HARD_TAKES_CAP) {
175
+ throw new SpendRefusal(
176
+ `music.takesCap is ${String(configured)}, above the hard cap of ${String(HARD_TAKES_CAP)} takes per invocation`,
177
+ {
178
+ flag: 'music.takesCap',
179
+ remedy: `set music.takesCap to ${String(DEFAULT_TAKES_CAP)}–${String(HARD_TAKES_CAP)} or pass --takes with a count of ${String(HARD_TAKES_CAP)} or less`,
180
+ detail: { cap: configured, hardCap: HARD_TAKES_CAP },
181
+ },
182
+ );
183
+ }
184
+ return configured;
185
+ }
186
+
187
+ /**
188
+ * Resolve the take count for this invocation (R4/R5).
189
+ *
190
+ * Over the cap is a refusal, not a clamp: R5 forbids silently adjusting the take
191
+ * count to fit, and the refusal names both the configured cap and `--takes`.
192
+ */
193
+ export function resolveTakeCount(requested: number, configuredCap: number | undefined): number {
194
+ // Re-validated here, not just at config load, so a caller that injects a config
195
+ // object (a test, 0401's JSON path) cannot hand the guard an out-of-domain cap.
196
+ const cap = resolveTakesCap(configuredCap);
197
+ if (!Number.isInteger(requested) || requested < 1) {
198
+ throw new SpendRefusal(`take count ${String(requested)} is not a positive integer`, {
199
+ flag: '--takes',
200
+ remedy: 'pass --takes with a whole number of takes (1 or more)',
201
+ });
202
+ }
203
+ if (requested > cap) {
204
+ throw new SpendRefusal(
205
+ `${String(requested)} takes per invocation exceeds the configured cap of ${String(cap)} (music.takesCap; hard cap ${String(HARD_TAKES_CAP)})`,
206
+ {
207
+ flag: '--takes',
208
+ remedy: `pass --takes ${String(cap)} or fewer, or raise music.takesCap (max ${String(HARD_TAKES_CAP)})`,
209
+ detail: { takes: requested, cap, hardCap: HARD_TAKES_CAP },
210
+ },
211
+ );
212
+ }
213
+ return requested;
214
+ }
215
+
216
+ /** Build the generate estimate from the resolved job and price config (R1). */
217
+ export function estimateGenerate(input: GenerateEstimateInput): SpendEstimate {
218
+ const model = input.job.model.value;
219
+ const unitPrice = model === 'pro' ? input.prices.pro : input.prices.clip;
220
+ return {
221
+ kind: 'generate',
222
+ prompt: renderBriefPrompt(input.job),
223
+ model,
224
+ takes: input.takes,
225
+ unitPrice,
226
+ total: unitPrice * input.takes,
227
+ unpriced: false,
228
+ };
229
+ }
230
+
231
+ /** Build the analyze estimate; `music.prices.analyze` has no default, so this is usually unpriced (R1). */
232
+ export function estimateAnalyze(input: AnalyzeEstimateInput): SpendEstimate {
233
+ const unitPrice = input.prices.analyze;
234
+ return {
235
+ kind: 'analyze',
236
+ prompt: null,
237
+ model: input.model ?? null,
238
+ takes: 1,
239
+ unitPrice,
240
+ total: unitPrice === null ? null : unitPrice,
241
+ unpriced: unitPrice === null,
242
+ instanceId: input.instanceId,
243
+ };
244
+ }
245
+
246
+ /** `$0.16`, `$0.08`, `$0` — trailing zeros trimmed so 3- and 4-decimal prices stay readable. */
247
+ export function formatUsd(value: number): string {
248
+ const trimmed = value.toFixed(4).replace(/0+$/, '').replace(/\.$/, '');
249
+ return `$${trimmed}`;
250
+ }
251
+
252
+ /** `unpriced` for a missing price; the word R1 requires instead of a fake zero. */
253
+ function formatPrice(value: number | null): string {
254
+ return value === null ? 'unpriced' : formatUsd(value);
255
+ }
256
+
257
+ /**
258
+ * Render an estimate as the human block `--estimate-only` prints and every paid
259
+ * generate emits before its first request (R1: prompt, model, takes, unit price,
260
+ * total).
261
+ */
262
+ export function formatEstimate(estimate: SpendEstimate): string {
263
+ const lines: string[] = [`music spend estimate — ${estimate.kind}`];
264
+ if (estimate.prompt !== null) {
265
+ lines.push('prompt:');
266
+ for (const line of estimate.prompt.split('\n')) {
267
+ lines.push(` ${line}`);
268
+ }
269
+ }
270
+ if (estimate.instanceId !== undefined) {
271
+ lines.push(`instance: ${estimate.instanceId}`);
272
+ }
273
+ lines.push(`model: ${estimate.model ?? 'unknown'}`);
274
+ lines.push(`takes: ${String(estimate.takes)}`);
275
+ lines.push(`unit price: ${formatPrice(estimate.unitPrice)}`);
276
+ lines.push(`total: ${formatPrice(estimate.total)}`);
277
+ return lines.join('\n');
278
+ }
279
+
280
+ /**
281
+ * R2: refuse a paid call without explicit confirmation.
282
+ *
283
+ * An unpriced estimate is *not* a free one — it demands confirmation exactly
284
+ * like a priced one, and says so.
285
+ */
286
+ export function requireConfirmation(estimate: SpendEstimate, confirmed: boolean | undefined): void {
287
+ if (confirmed === true) {
288
+ return;
289
+ }
290
+ const cost = estimate.unpriced
291
+ ? `this ${estimate.kind} is unpriced (set music.prices.${estimate.kind} to see the cost)`
292
+ : `this ${estimate.kind} spends ${formatPrice(estimate.total)} for ${String(estimate.takes)} request${estimate.takes === 1 ? '' : 's'}`;
293
+ throw new SpendRefusal(`${cost}, and no confirmation was given`, {
294
+ flag: '--yes',
295
+ remedy: 'pass --yes to confirm the paid call, or --estimate-only to print the estimate and stop',
296
+ detail: { kind: estimate.kind, total: estimate.total ?? 'unpriced' },
297
+ });
298
+ }
299
+
300
+ /**
301
+ * Confirmation plus the paid call, in one call so a caller cannot confirm and
302
+ * then forget to guard (`0401`'s `kk music analyze` uses this).
303
+ */
304
+ export async function withConfirmation<T>(
305
+ estimate: SpendEstimate,
306
+ confirmed: boolean | undefined,
307
+ run: () => Promise<T>,
308
+ ): Promise<T> {
309
+ requireConfirmation(estimate, confirmed);
310
+ return await run();
311
+ }
312
+
313
+ /** Scan options for {@link findRunDirDuplicates}. */
314
+ export interface DedupeScanInput {
315
+ /** The run directory (`<works>/kk-music/<topic-slug>/`, R3's dedupe scope). */
316
+ runDir: string;
317
+ /** Digests of the takes this invocation would request. */
318
+ digests: readonly TakeDigestEntry[];
319
+ /** File-system seam; defaults to the node/bun backend. */
320
+ fileSystem?: FileSystem;
321
+ }
322
+
323
+ /** Read a sidecar's two fields the scan needs, tolerating a malformed file. */
324
+ function readSidecarRecord(raw: string): { digest: string; artifactPath: string | null } | null {
325
+ let parsed: unknown;
326
+ try {
327
+ parsed = JSON.parse(raw);
328
+ } catch {
329
+ return null;
330
+ }
331
+ if (typeof parsed !== 'object' || parsed === null) {
332
+ return null;
333
+ }
334
+ const record = parsed as Record<string, unknown>;
335
+ const digest = record.digest;
336
+ if (typeof digest !== 'string' || digest === '') {
337
+ return null;
338
+ }
339
+ const artifactPath = record.artifactPath;
340
+ return { digest, artifactPath: typeof artifactPath === 'string' ? artifactPath : null };
341
+ }
342
+
343
+ /**
344
+ * Find takes already paid for in this run directory (R3).
345
+ *
346
+ * The scope lives in the lookup location, not the digest: only `runDir`'s own
347
+ * `*.take.json` sidecars are read, so another topic's run directory — or the
348
+ * instance library — can never produce a false duplicate. A sidecar that cannot
349
+ * be parsed cannot be shown to match, so it is skipped rather than blocking the
350
+ * run.
351
+ */
352
+ export async function findRunDirDuplicates(input: DedupeScanInput): Promise<RunDirDuplicate[]> {
353
+ const fileSystem = input.fileSystem ?? createNodeFileSystem();
354
+ if (input.digests.length === 0) {
355
+ return [];
356
+ }
357
+ if (!(await fileSystem.exists(input.runDir))) {
358
+ return [];
359
+ }
360
+ const wanted = new Map<string, number[]>();
361
+ for (const entry of input.digests) {
362
+ const indexes = wanted.get(entry.digest);
363
+ if (indexes === undefined) {
364
+ wanted.set(entry.digest, [entry.takeIndex]);
365
+ } else {
366
+ indexes.push(entry.takeIndex);
367
+ }
368
+ }
369
+ const names = await fileSystem.readDir(input.runDir);
370
+ const duplicates: RunDirDuplicate[] = [];
371
+ for (const name of [...names].sort()) {
372
+ if (!name.endsWith(TAKE_SIDECAR_SUFFIX)) {
373
+ continue;
374
+ }
375
+ const sidecarPath = join(input.runDir, name);
376
+ const record = readSidecarRecord(await fileSystem.readFile(sidecarPath));
377
+ if (record === null) {
378
+ continue;
379
+ }
380
+ const indexes = wanted.get(record.digest);
381
+ if (indexes === undefined) {
382
+ continue;
383
+ }
384
+ const artifactPath =
385
+ record.artifactPath ?? join(input.runDir, name.slice(0, name.length - TAKE_SIDECAR_SUFFIX.length));
386
+ for (const takeIndex of indexes) {
387
+ duplicates.push({ takeIndex, digest: record.digest, artifactPath, sidecarPath });
388
+ }
389
+ }
390
+ return duplicates;
391
+ }
392
+
393
+ /** The decision {@link planGeneration} makes about a duplicate run (R3). */
394
+ export interface DedupeDecision {
395
+ /** Takes the earlier run already paid for. */
396
+ duplicates: RunDirDuplicate[];
397
+ /** Whether this invocation proceeds past dedupe (only with `--force --reason`). */
398
+ forced: boolean;
399
+ reason: string | null;
400
+ }
401
+
402
+ /**
403
+ * Apply R3's dedupe policy: refuse on a duplicate unless `--force --reason`
404
+ * overrides it, and never accept `--force` without a reason.
405
+ */
406
+ export async function enforceRunScopedDedupe(
407
+ input: DedupeScanInput & { force?: boolean; reason?: string },
408
+ ): Promise<DedupeDecision> {
409
+ const duplicates = await findRunDirDuplicates(input);
410
+ const forced = input.force === true;
411
+ const reason = input.reason ?? null;
412
+ if (forced && (reason === null || reason.trim() === '')) {
413
+ throw new SpendRefusal('--force re-pays for a request this run already owns, but no --reason was given', {
414
+ flag: '--reason',
415
+ remedy: 'pass --force --reason "<why the re-roll is worth paying for>"',
416
+ });
417
+ }
418
+ if (duplicates.length > 0 && !forced) {
419
+ const first = duplicates[0] as RunDirDuplicate;
420
+ throw new SpendRefusal(
421
+ `take ${String(first.takeIndex + 1)} of this request is already paid for in this run directory: ${first.artifactPath} (digest ${first.digest})`,
422
+ {
423
+ flag: '--force --reason <text>',
424
+ remedy: `pass --force --reason "<why>" to re-roll it — a re-roll is paid again — or reuse ${first.artifactPath}`,
425
+ detail: {
426
+ artifactPath: first.artifactPath,
427
+ digest: first.digest,
428
+ duplicates: duplicates.length,
429
+ },
430
+ },
431
+ );
432
+ }
433
+ return { duplicates, forced, reason: forced ? reason : null };
434
+ }
435
+
436
+ /** Input for {@link planGeneration}. */
437
+ export interface GenerationPlanInput {
438
+ job: ResolvedJob;
439
+ prices: MusicPrices;
440
+ /** Effective cap — `MusicConfig.takesCap`, already validated by {@link resolveTakesCap}. */
441
+ takesCap: number;
442
+ /** `--takes`, when the caller overrode the brief's count. */
443
+ requestedTakes?: number;
444
+ confirmed?: boolean;
445
+ force?: boolean;
446
+ reason?: string;
447
+ /** The run directory: where sidecars live and where dedupe looks. */
448
+ runDir: string;
449
+ /** SHA-256 of each brief image, in brief order (empty when the brief has none). */
450
+ imageHashes: readonly string[];
451
+ /** Receives the rendered estimate before any refusal, so R2 can print then fail. */
452
+ emit?: SpendEmit;
453
+ fileSystem?: FileSystem;
454
+ }
455
+
456
+ /** What {@link planGeneration} approves: everything the take loop needs, and nothing it may expand. */
457
+ export interface GenerationPlan {
458
+ estimate: SpendEstimate;
459
+ takes: number;
460
+ /** One digest per take, in take order. */
461
+ digests: TakeDigest[];
462
+ forced: boolean;
463
+ reason: string | null;
464
+ duplicates: RunDirDuplicate[];
465
+ }
466
+
467
+ /**
468
+ * The generate guard: cap, estimate, confirmation, dedupe — in that order, all
469
+ * before the adapter exists. It throws {@link SpendRefusal} rather than returning
470
+ * a decision, so no caller can hold a plan it forgot to check.
471
+ */
472
+ export async function planGeneration(input: GenerationPlanInput): Promise<GenerationPlan> {
473
+ const takes = resolveTakeCount(input.requestedTakes ?? input.job.takes, input.takesCap);
474
+ const estimate = estimateGenerate({ job: input.job, prices: input.prices, takes });
475
+ input.emit?.(formatEstimate(estimate));
476
+ requireConfirmation(estimate, input.confirmed);
477
+ const digests = Array.from({ length: takes }, (_unused, takeIndex) =>
478
+ takeDigest(input.job, { imageHashes: [...input.imageHashes], takeIndex }),
479
+ );
480
+ const decision = await enforceRunScopedDedupe({
481
+ runDir: input.runDir,
482
+ digests: digests.map((digest, takeIndex) => ({ takeIndex, digest: digest.sha256 })),
483
+ ...(input.force === undefined ? {} : { force: input.force }),
484
+ ...(input.reason === undefined ? {} : { reason: input.reason }),
485
+ ...(input.fileSystem === undefined ? {} : { fileSystem: input.fileSystem }),
486
+ });
487
+ return {
488
+ estimate,
489
+ takes,
490
+ digests,
491
+ forced: decision.forced,
492
+ reason: decision.reason,
493
+ duplicates: decision.duplicates,
494
+ };
495
+ }
@@ -0,0 +1,8 @@
1
+ {
2
+ "extends": "../../../tooling/typescript/base.json",
3
+ "compilerOptions": {
4
+ "rootDir": "./src",
5
+ "outDir": "./dist"
6
+ },
7
+ "include": ["src/**/*"]
8
+ }