@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.
- package/.claude-plugin/marketplace.json +1 -1
- package/dist/board/collect/index.js +1 -0
- package/dist/board/daily-voice/index.js +1279 -261
- package/dist/board/itc/index.js +1 -0
- package/dist/index.js +13893 -8995
- package/package.json +1 -1
- package/plugins/generations/dailynews-gen/dist/index.js +285 -16
- package/plugins/generations/dailynews-gen/src/editorial-claims.ts +215 -0
- package/plugins/generations/dailynews-gen/src/index.ts +23 -4
- package/plugins/generations/dailynews-gen/src/script-builder.ts +10 -3
- package/plugins/generations/dailynews-gen/src/script-plan.ts +74 -14
- package/plugins/generations/music-gen/README.md +277 -0
- package/plugins/generations/music-gen/dist/index.js +23544 -0
- package/plugins/generations/music-gen/package.json +24 -0
- package/plugins/generations/music-gen/plugin.json +23 -0
- package/plugins/generations/music-gen/presets/SOURCE.md +39 -0
- package/plugins/generations/music-gen/presets/formats/clip.yaml +21 -0
- package/plugins/generations/music-gen/presets/formats/jingle.yaml +22 -0
- package/plugins/generations/music-gen/presets/formats/loop.yaml +21 -0
- package/plugins/generations/music-gen/presets/formats/song.yaml +31 -0
- package/plugins/generations/music-gen/presets/formats/underscore.yaml +22 -0
- package/plugins/generations/music-gen/presets/themes/ambient-tech.yaml +30 -0
- package/plugins/generations/music-gen/presets/themes/cinematic.yaml +30 -0
- package/plugins/generations/music-gen/presets/themes/lofi.yaml +30 -0
- package/plugins/generations/music-gen/presets/themes/synthwave.yaml +30 -0
- package/plugins/generations/music-gen/scripts/gen-preset-index.ts +181 -0
- package/plugins/generations/music-gen/scripts/resolve-preset.ts +64 -0
- package/plugins/generations/music-gen/src/adapter/index.ts +35 -0
- package/plugins/generations/music-gen/src/adapter/instance.ts +904 -0
- package/plugins/generations/music-gen/src/adapter/offline.ts +124 -0
- package/plugins/generations/music-gen/src/artifact.ts +223 -0
- package/plugins/generations/music-gen/src/audio/checks.ts +618 -0
- package/plugins/generations/music-gen/src/audio/master.ts +267 -0
- package/plugins/generations/music-gen/src/audio/measure.ts +507 -0
- package/plugins/generations/music-gen/src/audio/profile.ts +131 -0
- package/plugins/generations/music-gen/src/audio.ts +122 -0
- package/plugins/generations/music-gen/src/brief.ts +191 -0
- package/plugins/generations/music-gen/src/config.ts +451 -0
- package/plugins/generations/music-gen/src/content.ts +199 -0
- package/plugins/generations/music-gen/src/digest.ts +100 -0
- package/plugins/generations/music-gen/src/index.ts +147 -0
- package/plugins/generations/music-gen/src/job.ts +131 -0
- package/plugins/generations/music-gen/src/plugin.ts +371 -0
- package/plugins/generations/music-gen/src/presets.ts +918 -0
- package/plugins/generations/music-gen/src/render.ts +87 -0
- package/plugins/generations/music-gen/src/request.ts +102 -0
- package/plugins/generations/music-gen/src/spend.ts +495 -0
- package/plugins/generations/music-gen/tsconfig.json +8 -0
- package/plugins/kk/plugin.json +1 -1
- package/plugins/kk/schedules/kk-serve.launchd.plist.tmpl +2 -1
- package/plugins/kk/scripts/cover-compositor.ts +380 -32
- package/plugins/kk/scripts/daily-cover-mock.ts +40 -3
- package/plugins/kk/scripts/daily-stages.ts +659 -20
- package/plugins/kk/scripts/episode-identity.ts +180 -0
- package/plugins/kk/scripts/kk-workflow-stages.ts +37 -1
- package/plugins/kk/scripts/music-stages.ts +624 -0
- package/plugins/kk/scripts/news-editorial-ledger.ts +906 -0
- package/plugins/kk/scripts/source-citation.ts +187 -0
- package/plugins/kk/scripts/topic-selection-attempts.ts +446 -0
- package/plugins/kk/scripts/topic-selection-calibration.ts +161 -0
- package/plugins/kk/skills/content-judge/SKILL.md +11 -6
- package/plugins/kk/skills/content-judge/references/music-quality-rubric.md +147 -0
- package/plugins/kk/skills/content-judge/references/rubrics.md +15 -0
- package/plugins/kk/skills/content-safety/SKILL.md +12 -0
- package/plugins/kk/skills/music-authoring/SKILL.md +276 -0
- package/plugins/kk/skills/music-authoring/references/judge-input.md +117 -0
- package/plugins/kk/skills/news-editorial/SKILL.md +102 -15
- package/plugins/kk/skills/news-editorial/references/selection.md +4 -0
- package/plugins/kk/skills/news-editorial/references/style-contract.zh.md +58 -11
- package/plugins/kk/workflows/kk-daily-ai-voice.yaml +8 -8
- package/plugins/kk/workflows/kk-daily-ai-voice2.yaml +7 -7
- package/plugins/kk/workflows/kk-music.yaml +328 -0
- package/plugins/kk/workflows/kk-news-generate.yaml +58 -3
- package/plugins/publishings/bilibili-pub/dist/index.js +11 -1
- package/plugins/publishings/bilibili-pub/dist/profile-check.js +11 -1
- package/plugins/publishings/cnblogs-pub/dist/index.js +11 -1
- package/plugins/publishings/cnblogs-pub/dist/profile-check.js +11 -1
- package/plugins/publishings/csdn-pub/dist/index.js +11 -1
- package/plugins/publishings/csdn-pub/dist/profile-check.js +11 -1
- package/plugins/publishings/infoq-pub/dist/index.js +11 -1
- package/plugins/publishings/infoq-pub/dist/profile-check.js +11 -1
- package/plugins/publishings/jike-pub/dist/index.js +11 -1
- package/plugins/publishings/jike-pub/dist/profile-check.js +11 -1
- package/plugins/publishings/juejin-pub/dist/index.js +11 -1
- package/plugins/publishings/juejin-pub/dist/profile-check.js +11 -1
- package/plugins/publishings/linkedin-pub/dist/index.js +11 -1
- package/plugins/publishings/linkedin-pub/dist/profile-check.js +11 -1
- package/plugins/publishings/podcast-pub/dist/index.js +586 -20
- package/plugins/publishings/podcast-pub/src/corrections.ts +509 -0
- package/plugins/publishings/podcast-pub/src/index.ts +257 -5
- package/plugins/publishings/podcast-pub/src/show-notes-brief.ts +240 -0
- package/plugins/publishings/podcast-pub/src/show-notes.ts +69 -13
- package/plugins/publishings/shipinhao-pub/dist/index.js +59 -8
- package/plugins/publishings/shipinhao-pub/dist/profile-check.js +11 -1
- package/plugins/publishings/shipinhao-pub/src/audio-flow.ts +105 -6
- package/plugins/publishings/sspai-pub/dist/index.js +11 -1
- package/plugins/publishings/sspai-pub/dist/profile-check.js +11 -1
- package/plugins/publishings/substack-pub/dist/index.js +11 -1
- package/plugins/publishings/substack-pub/dist/profile-check.js +11 -1
- package/plugins/publishings/surfdash-pub/dist/index.js +72 -20
- package/plugins/publishings/surfdash-pub/src/digest-check.ts +7 -3
- package/plugins/publishings/surfdash-pub/src/index.ts +100 -17
- package/plugins/publishings/surfdash-pub/src/topic-claims.ts +3 -1
- package/plugins/publishings/threads-pub/dist/index.js +11 -1
- package/plugins/publishings/threads-pub/dist/profile-check.js +11 -1
- package/plugins/publishings/wechatmp-pub/dist/index.js +11 -1
- package/plugins/publishings/wechatmp-pub/dist/profile-check.js +11 -1
- package/plugins/publishings/weibo-pub/dist/index.js +11 -1
- package/plugins/publishings/weibo-pub/dist/profile-check.js +11 -1
- package/plugins/publishings/x-pub/dist/index.js +11 -1
- package/plugins/publishings/x-pub/dist/profile-check.js +11 -1
- package/plugins/publishings/xhs-pub/dist/index.js +11 -1
- package/plugins/publishings/xhs-pub/dist/profile-check.js +11 -1
- package/plugins/publishings/xiaoyuzhou-pub/dist/index.js +11 -1
- package/plugins/publishings/xiaoyuzhou-pub/dist/profile-check.js +11 -1
|
@@ -0,0 +1,371 @@
|
|
|
1
|
+
import { dirname, join, resolve } from 'node:path';
|
|
2
|
+
import { parseArgs } from 'node:util';
|
|
3
|
+
import { type Content, ContentSchema, type Doc, DocListSchema } from '@gobing-ai/kk-core';
|
|
4
|
+
import { createNodeFileSystem, type FileSystem } from '@gobing-ai/ts-runtime';
|
|
5
|
+
import { echo, echoError } from '@gobing-ai/ts-utils';
|
|
6
|
+
import { createMusicInstance } from './adapter';
|
|
7
|
+
import type { AnalysisOutcome, MusicInstance } from './adapter/instance';
|
|
8
|
+
import {
|
|
9
|
+
buildTakeSidecar,
|
|
10
|
+
imageDataUrl,
|
|
11
|
+
readImageBytes,
|
|
12
|
+
serializeTakeSidecar,
|
|
13
|
+
sha256Hex,
|
|
14
|
+
takeArtifactName,
|
|
15
|
+
takeSidecarName,
|
|
16
|
+
takeSlug,
|
|
17
|
+
writeAudioBytes,
|
|
18
|
+
} from './artifact';
|
|
19
|
+
import { type MusicConfig, resolveMusicConfig } from './config';
|
|
20
|
+
import { analysisSummary, buildMusicContent, type ContentTakeRecord, type LinerTake } from './content';
|
|
21
|
+
import { parseMusicJob } from './job';
|
|
22
|
+
import { type MusicGenerateRequest, renderGenerateRequest } from './request';
|
|
23
|
+
import {
|
|
24
|
+
estimateAnalyze,
|
|
25
|
+
estimateGenerate,
|
|
26
|
+
formatEstimate,
|
|
27
|
+
planGeneration,
|
|
28
|
+
resolveTakeCount,
|
|
29
|
+
type SpendEmit,
|
|
30
|
+
type SpendEstimate,
|
|
31
|
+
SpendRefusal,
|
|
32
|
+
type SpendRequest,
|
|
33
|
+
withConfirmation,
|
|
34
|
+
} from './spend';
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* The generator entry (task 0398 R1/R5/R6): read the brief, run the takes, map
|
|
38
|
+
* the result onto the generator contract.
|
|
39
|
+
*
|
|
40
|
+
* Take loop (Design "Takes are a client loop"): `takes: N` issues N sequential
|
|
41
|
+
* single take requests, and each persists or fails independently. A failure on
|
|
42
|
+
* take k leaves takes 1..k-1 on disk, so the failure path deletes `--out` only,
|
|
43
|
+
* never an already-paid artifact.
|
|
44
|
+
*
|
|
45
|
+
* **Order of operations (task 0400 R1–R3).** The spend guard runs before the
|
|
46
|
+
* adapter is built: cap → estimate → confirmation → run-scoped dedupe. So a
|
|
47
|
+
* refused or unconfirmed run prints its estimate and stops, and no socket is
|
|
48
|
+
* opened. A resumed run that re-requests an already-paid take is refused by
|
|
49
|
+
* dedupe unless the operator asks for the re-roll explicitly with
|
|
50
|
+
* `--force --reason <text>`; the refusal names the existing artifact path.
|
|
51
|
+
*/
|
|
52
|
+
|
|
53
|
+
/** Options a caller (0401's CLI, a test) may inject. */
|
|
54
|
+
export interface MusicGeneratorOptions {
|
|
55
|
+
/** Adapter override; tests always pass one so no socket is opened. */
|
|
56
|
+
client?: MusicInstance;
|
|
57
|
+
/** Config override; resolves from env + the kk config file when absent. */
|
|
58
|
+
config?: MusicConfig;
|
|
59
|
+
/** File-system seam override (text IO only — binary audio goes through `artifact.ts`). */
|
|
60
|
+
fileSystem?: FileSystem;
|
|
61
|
+
/** Injected clock, so a test can pin the sidecar's `createdAt`. */
|
|
62
|
+
now?: () => number;
|
|
63
|
+
/** Injected binary reader for reference images. */
|
|
64
|
+
readImage?: (path: string) => Promise<Uint8Array>;
|
|
65
|
+
/** Where the pre-spend estimate is printed; defaults to stdout. */
|
|
66
|
+
emit?: SpendEmit;
|
|
67
|
+
/** The 0400 spend request: `--yes`, `--force --reason <text>`, `--takes <n>`. */
|
|
68
|
+
spend?: SpendRequest;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** Read and validate the `--in` DocList; one reader for the generate and estimate paths. */
|
|
72
|
+
async function readMusicDocs(fileSystem: FileSystem, inputPath: string): Promise<Doc[]> {
|
|
73
|
+
let docs: Doc[];
|
|
74
|
+
try {
|
|
75
|
+
const raw = await fileSystem.readFile(inputPath);
|
|
76
|
+
docs = DocListSchema.parse(JSON.parse(raw));
|
|
77
|
+
} catch (err: unknown) {
|
|
78
|
+
throw new Error(`Invalid DocList input: ${err instanceof Error ? err.message : String(err)}`);
|
|
79
|
+
}
|
|
80
|
+
if (docs.length === 0) {
|
|
81
|
+
throw new Error('Invalid music job input: the DocList is empty — docs[0].body must carry the YAML brief');
|
|
82
|
+
}
|
|
83
|
+
return docs;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** Default estimate channel: stdout, so a human sees the cost before the money leaves. */
|
|
87
|
+
function echoEstimate(block: string): void {
|
|
88
|
+
echo(block);
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** Read validated `Doc[]` input and emit the music `Content`. */
|
|
92
|
+
export async function processGeneratorIO(
|
|
93
|
+
inputPath: string,
|
|
94
|
+
outputPath: string,
|
|
95
|
+
options: MusicGeneratorOptions = {},
|
|
96
|
+
): Promise<Content> {
|
|
97
|
+
const fs = options.fileSystem ?? createNodeFileSystem();
|
|
98
|
+
const now = options.now ?? Date.now;
|
|
99
|
+
const readImage = options.readImage ?? readImageBytes;
|
|
100
|
+
const emit = options.emit ?? echoEstimate;
|
|
101
|
+
const spend = options.spend ?? {};
|
|
102
|
+
|
|
103
|
+
// Start clean for the contract file only: persisted takes stay (see the module header).
|
|
104
|
+
await fs.deleteFile(outputPath);
|
|
105
|
+
|
|
106
|
+
const docs = await readMusicDocs(fs, inputPath);
|
|
107
|
+
|
|
108
|
+
const { brief, spec, job } = parseMusicJob(docs);
|
|
109
|
+
const config = options.config ?? (await resolveMusicConfig({ fileSystem: fs }));
|
|
110
|
+
const outDir = dirname(outputPath);
|
|
111
|
+
const slug = takeSlug(spec.outputStem ?? job.title);
|
|
112
|
+
|
|
113
|
+
// Reference images: hash the bytes for the digest (0397 §7) and encode them for
|
|
114
|
+
// the wire. Both happen once per job — the images are identical across takes.
|
|
115
|
+
const imageBytes = job.images.length === 0 ? [] : await Promise.all(job.images.map((path) => readImage(path)));
|
|
116
|
+
const imageHashes = imageBytes.map((bytes) => sha256Hex(bytes));
|
|
117
|
+
const imageDataUrls = imageBytes.map((bytes, index) => imageDataUrl(job.images[index] ?? '', bytes));
|
|
118
|
+
|
|
119
|
+
await fs.ensureDir(outDir);
|
|
120
|
+
|
|
121
|
+
// The 0400 guard: cap, estimate, confirmation, run-scoped dedupe — all before the
|
|
122
|
+
// adapter exists, so a refusal can never be preceded by a socket. `--force`/`--reason`
|
|
123
|
+
// may ride either the argv (0401) or `metadata.musicGen` (0398's authoring form).
|
|
124
|
+
const force = spend.force ?? spec.force === true;
|
|
125
|
+
const reason = spend.reason ?? spec.reason;
|
|
126
|
+
const plan = await planGeneration({
|
|
127
|
+
job,
|
|
128
|
+
prices: config.prices,
|
|
129
|
+
takesCap: config.takesCap,
|
|
130
|
+
...(spend.takes === undefined ? {} : { requestedTakes: spend.takes }),
|
|
131
|
+
...(spend.confirmed === undefined ? {} : { confirmed: spend.confirmed }),
|
|
132
|
+
force,
|
|
133
|
+
...(reason === undefined ? {} : { reason }),
|
|
134
|
+
runDir: outDir,
|
|
135
|
+
imageHashes,
|
|
136
|
+
emit,
|
|
137
|
+
fileSystem: fs,
|
|
138
|
+
});
|
|
139
|
+
|
|
140
|
+
const client = options.client ?? createMusicInstance(config);
|
|
141
|
+
|
|
142
|
+
const liner: LinerTake[] = [];
|
|
143
|
+
const records: ContentTakeRecord[] = [];
|
|
144
|
+
let lastError: unknown;
|
|
145
|
+
for (const [takeIndex, digest] of plan.digests.entries()) {
|
|
146
|
+
try {
|
|
147
|
+
const request = withEncodedImages(renderGenerateRequest(job), imageDataUrls);
|
|
148
|
+
const generated = await client.generate(request);
|
|
149
|
+
const artifactName = takeArtifactName(
|
|
150
|
+
slug,
|
|
151
|
+
generated.model === '' ? job.model.value : generated.model,
|
|
152
|
+
generated.id,
|
|
153
|
+
generated.format,
|
|
154
|
+
);
|
|
155
|
+
const artifactPath = join(outDir, artifactName);
|
|
156
|
+
const sidecarPath = join(outDir, takeSidecarName(artifactName));
|
|
157
|
+
await writeAudioBytes(artifactPath, generated.bytes);
|
|
158
|
+
const summary = analysisSummary(generated.analysis);
|
|
159
|
+
const sidecar = buildTakeSidecar({
|
|
160
|
+
digest,
|
|
161
|
+
request,
|
|
162
|
+
instanceId: generated.id,
|
|
163
|
+
model: generated.model === '' ? job.model.value : generated.model,
|
|
164
|
+
format: generated.format,
|
|
165
|
+
takeIndex,
|
|
166
|
+
artifactPath,
|
|
167
|
+
unitPrice: plan.estimate.unitPrice,
|
|
168
|
+
adoptedByReconciliation: generated.adoptedByReconciliation,
|
|
169
|
+
unclaimed: generated.unclaimed,
|
|
170
|
+
forced: plan.forced,
|
|
171
|
+
...(plan.reason === null ? {} : { reason: plan.reason }),
|
|
172
|
+
...(config.runId === undefined ? {} : { runId: config.runId }),
|
|
173
|
+
now,
|
|
174
|
+
language: generated.language ?? job.language.value,
|
|
175
|
+
...(generated.durationTarget === undefined ? {} : { durationTarget: generated.durationTarget }),
|
|
176
|
+
...(generated.batchCount === undefined ? {} : { batchCount: generated.batchCount }),
|
|
177
|
+
...(generated.generatedAt === undefined ? {} : { generatedAt: generated.generatedAt }),
|
|
178
|
+
...(generated.audioUrl === undefined ? {} : { audioUrl: generated.audioUrl }),
|
|
179
|
+
...(client.provider === 'offline' ? { dryRun: true } : {}),
|
|
180
|
+
});
|
|
181
|
+
await fs.writeFile(sidecarPath, serializeTakeSidecar(sidecar));
|
|
182
|
+
records.push({
|
|
183
|
+
takeIndex,
|
|
184
|
+
instanceId: generated.id,
|
|
185
|
+
model: sidecar.model,
|
|
186
|
+
format: generated.format,
|
|
187
|
+
requestedFormat: request.format,
|
|
188
|
+
digest: digest.sha256,
|
|
189
|
+
digestInput: digest.input,
|
|
190
|
+
artifactPath,
|
|
191
|
+
sidecarPath,
|
|
192
|
+
unitPrice: sidecar.unitPrice,
|
|
193
|
+
adoptedByReconciliation: generated.adoptedByReconciliation,
|
|
194
|
+
unclaimed: generated.unclaimed,
|
|
195
|
+
...(generated.language === undefined ? {} : { language: generated.language }),
|
|
196
|
+
...(generated.durationTarget === undefined ? {} : { durationTarget: generated.durationTarget }),
|
|
197
|
+
...(generated.batchCount === undefined ? {} : { batchCount: generated.batchCount }),
|
|
198
|
+
...(generated.audioUrl === undefined ? {} : { audioUrl: generated.audioUrl }),
|
|
199
|
+
...(generated.generatedAt === undefined ? {} : { generatedAt: generated.generatedAt }),
|
|
200
|
+
...(summary === undefined ? {} : { analysisSummary: summary }),
|
|
201
|
+
});
|
|
202
|
+
liner.push({
|
|
203
|
+
takeIndex,
|
|
204
|
+
instanceId: generated.id,
|
|
205
|
+
model: sidecar.model,
|
|
206
|
+
format: generated.format,
|
|
207
|
+
...(generated.language === undefined ? {} : { language: generated.language }),
|
|
208
|
+
...(generated.durationTarget === undefined ? {} : { durationTarget: generated.durationTarget }),
|
|
209
|
+
...(generated.batchCount === undefined ? {} : { batchCount: generated.batchCount }),
|
|
210
|
+
...(generated.audioUrl === undefined ? {} : { audioUrl: generated.audioUrl }),
|
|
211
|
+
prompt: request.prompt,
|
|
212
|
+
...(request.lyrics === undefined ? {} : { lyrics: request.lyrics }),
|
|
213
|
+
...(summary === undefined ? {} : { analysisSummary: summary }),
|
|
214
|
+
adoptedByReconciliation: generated.adoptedByReconciliation,
|
|
215
|
+
unclaimed: generated.unclaimed,
|
|
216
|
+
});
|
|
217
|
+
} catch (error: unknown) {
|
|
218
|
+
lastError = error;
|
|
219
|
+
break;
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
if (records.length === 0) {
|
|
224
|
+
throw lastError instanceof Error ? lastError : new Error(String(lastError ?? 'no take was generated'));
|
|
225
|
+
}
|
|
226
|
+
if (records.length < plan.takes) {
|
|
227
|
+
// A later take failed: what was paid for stays on disk, and the contract file is not written.
|
|
228
|
+
throw new Error(
|
|
229
|
+
`music-gen: take ${String(records.length + 1)} of ${String(plan.takes)} failed after ${String(records.length)} take(s) were persisted in ${outDir}: ${
|
|
230
|
+
lastError instanceof Error ? lastError.message : String(lastError)
|
|
231
|
+
}`,
|
|
232
|
+
);
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
const content = ContentSchema.parse(
|
|
236
|
+
buildMusicContent({
|
|
237
|
+
title: brief.title,
|
|
238
|
+
provider: client.provider,
|
|
239
|
+
dryRun: client.provider === 'offline',
|
|
240
|
+
liner,
|
|
241
|
+
takes: records,
|
|
242
|
+
}),
|
|
243
|
+
);
|
|
244
|
+
await fs.writeFile(outputPath, `${JSON.stringify(content, null, 2)}\n`);
|
|
245
|
+
return content;
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/** Replace the request's image paths with their `data:` encodings (design §4: 0398 encodes for the wire). */
|
|
249
|
+
export function withEncodedImages(request: MusicGenerateRequest, dataUrls: readonly string[]): MusicGenerateRequest {
|
|
250
|
+
if (dataUrls.length === 0) {
|
|
251
|
+
return request;
|
|
252
|
+
}
|
|
253
|
+
return { ...request, images: [...dataUrls] };
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
/**
|
|
257
|
+
* Options for the estimate-only path.
|
|
258
|
+
*
|
|
259
|
+
* There is deliberately no adapter and no `fetch` seam here: this path cannot
|
|
260
|
+
* open a socket because it has nothing to open one with (0400 R1).
|
|
261
|
+
*/
|
|
262
|
+
export interface MusicEstimateOptions {
|
|
263
|
+
/** Config override; resolves from env + the kk config file when absent. */
|
|
264
|
+
config?: MusicConfig;
|
|
265
|
+
/** File-system seam override (reading the brief only). */
|
|
266
|
+
fileSystem?: FileSystem;
|
|
267
|
+
/** `--takes` override; still bounded by `music.takesCap` (0400 R4). */
|
|
268
|
+
takes?: number;
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
/**
|
|
272
|
+
* Plan a generate job and return its pre-spend estimate without spending
|
|
273
|
+
* anything (0400 R1: `--estimate-only`).
|
|
274
|
+
*
|
|
275
|
+
* Resolves the brief, the model, the take count and the unit price, and runs no
|
|
276
|
+
* dedupe: an estimate is a preview, so it must not refuse on a run directory
|
|
277
|
+
* the operator has not decided to re-run yet.
|
|
278
|
+
*/
|
|
279
|
+
export async function estimateMusicJob(inputPath: string, options: MusicEstimateOptions = {}): Promise<SpendEstimate> {
|
|
280
|
+
const fs = options.fileSystem ?? createNodeFileSystem();
|
|
281
|
+
const docs = await readMusicDocs(fs, inputPath);
|
|
282
|
+
const { job } = parseMusicJob(docs);
|
|
283
|
+
const config = options.config ?? (await resolveMusicConfig({ fileSystem: fs }));
|
|
284
|
+
const takes = resolveTakeCount(options.takes ?? job.takes, config.takesCap);
|
|
285
|
+
return estimateGenerate({ job, prices: config.prices, takes });
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
/** Options for {@link analyzeTake}. */
|
|
289
|
+
export interface MusicAnalyzeOptions {
|
|
290
|
+
/** Adapter to analyze through; injected so a test opens no socket. */
|
|
291
|
+
client: MusicInstance;
|
|
292
|
+
config: MusicConfig;
|
|
293
|
+
/** `--yes`, or the workflow var the HITL gate sets (0400 R2). */
|
|
294
|
+
confirmed?: boolean;
|
|
295
|
+
/** Where the pre-spend estimate is printed; defaults to stdout. */
|
|
296
|
+
emit?: SpendEmit;
|
|
297
|
+
/** The model recorded on the take, when the caller knows it (display only). */
|
|
298
|
+
model?: string;
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
/**
|
|
302
|
+
* Analyze one take behind the 0400 confirmation gate (R1/R2).
|
|
303
|
+
*
|
|
304
|
+
* `POST /api/ai/analyze` is a paid call like generate, and `music.prices.analyze`
|
|
305
|
+
* has no default, so the estimate usually reads `unpriced` — which still demands
|
|
306
|
+
* confirmation. One entry point, so `kk music analyze` (0401) cannot bypass it.
|
|
307
|
+
*/
|
|
308
|
+
export async function analyzeTake(instanceId: string, options: MusicAnalyzeOptions): Promise<AnalysisOutcome> {
|
|
309
|
+
const estimate = estimateAnalyze({
|
|
310
|
+
prices: options.config.prices,
|
|
311
|
+
instanceId,
|
|
312
|
+
...(options.model === undefined ? {} : { model: options.model }),
|
|
313
|
+
});
|
|
314
|
+
(options.emit ?? echoEstimate)(formatEstimate(estimate));
|
|
315
|
+
return await withConfirmation(estimate, options.confirmed, async () => await options.client.analyze(instanceId));
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
/** Parse `--takes`; the guard owns the domain rule, so an unparseable value is a refusal too. */
|
|
319
|
+
function parseTakesFlag(raw: string): number {
|
|
320
|
+
if (!/^\d+$/.test(raw.trim())) {
|
|
321
|
+
throw new SpendRefusal(`--takes ${raw} is not a whole number`, {
|
|
322
|
+
flag: '--takes',
|
|
323
|
+
remedy: 'pass --takes with a whole number of takes (1 or more)',
|
|
324
|
+
});
|
|
325
|
+
}
|
|
326
|
+
return Number(raw.trim());
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
/**
|
|
330
|
+
* The plugin entry: `--in <DocList> --out <content.json>` plus the 0400 spend
|
|
331
|
+
* flags `--yes`, `--estimate-only`, `--force`, `--reason`, `--takes`.
|
|
332
|
+
*
|
|
333
|
+
* @param argv arguments after the script name; defaults to the process argv, and
|
|
334
|
+
* is a parameter so a test can drive the entry in-process (no spawn).
|
|
335
|
+
*/
|
|
336
|
+
export async function main(argv: readonly string[] = process.argv.slice(2)): Promise<number> {
|
|
337
|
+
const { values } = parseArgs({
|
|
338
|
+
args: [...argv],
|
|
339
|
+
options: {
|
|
340
|
+
in: { type: 'string' },
|
|
341
|
+
out: { type: 'string' },
|
|
342
|
+
yes: { type: 'boolean' },
|
|
343
|
+
'estimate-only': { type: 'boolean' },
|
|
344
|
+
force: { type: 'boolean' },
|
|
345
|
+
reason: { type: 'string' },
|
|
346
|
+
takes: { type: 'string' },
|
|
347
|
+
},
|
|
348
|
+
});
|
|
349
|
+
if (!values.in || !values.out) {
|
|
350
|
+
echoError('music-gen failed: Missing required arguments: --in and --out');
|
|
351
|
+
return 1;
|
|
352
|
+
}
|
|
353
|
+
try {
|
|
354
|
+
if (values['estimate-only'] === true) {
|
|
355
|
+
const takes = values.takes === undefined ? {} : { takes: parseTakesFlag(values.takes) };
|
|
356
|
+
echo(formatEstimate(await estimateMusicJob(values.in, takes)));
|
|
357
|
+
return 0;
|
|
358
|
+
}
|
|
359
|
+
const spend: SpendRequest = {
|
|
360
|
+
...(values.yes === true ? { confirmed: true } : {}),
|
|
361
|
+
...(values.force === true ? { force: true } : {}),
|
|
362
|
+
...(values.reason === undefined ? {} : { reason: values.reason }),
|
|
363
|
+
...(values.takes === undefined ? {} : { takes: parseTakesFlag(values.takes) }),
|
|
364
|
+
};
|
|
365
|
+
await processGeneratorIO(values.in, resolve(values.out), { spend });
|
|
366
|
+
return 0;
|
|
367
|
+
} catch (err: unknown) {
|
|
368
|
+
echoError(`music-gen failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
369
|
+
return err instanceof SpendRefusal ? err.exitCode : 1;
|
|
370
|
+
}
|
|
371
|
+
}
|