@gobing-ai/knowledge-kit 0.1.22 → 0.1.24

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 (117) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/dist/index.js +282 -147
  3. package/package.json +5 -5
  4. package/plugins/generations/content-gen/dist/index.js +9 -9
  5. package/plugins/generations/core-facts-gen/dist/index.js +12 -12
  6. package/plugins/generations/daily-article-gen/dist/index.js +12 -12
  7. package/plugins/generations/dailynews-gen/dist/index.js +11 -11
  8. package/plugins/generations/dailynews-gen/src/script-plan.ts +2 -2
  9. package/plugins/generations/episode-plan-gen/dist/index.js +12 -12
  10. package/plugins/generations/gemini-tts/dist/index.js +56 -16
  11. package/plugins/generations/gemini-tts/src/gemini-client.ts +34 -6
  12. package/plugins/generations/image-gen/dist/index.js +9 -9
  13. package/plugins/generations/music-gen/README.md +2 -2
  14. package/plugins/generations/music-gen/dist/index.js +62 -26
  15. package/plugins/generations/music-gen/presets/formats/song.yaml +6 -1
  16. package/plugins/generations/music-gen/presets/themes/synthwave.yaml +6 -1
  17. package/plugins/generations/music-gen/src/adapter/instance.ts +34 -11
  18. package/plugins/generations/music-gen/src/presets.ts +36 -3
  19. package/plugins/generations/news-report-gen/dist/index.js +12 -12
  20. package/plugins/generations/omni-voice-gen/uv.toml +5 -0
  21. package/plugins/generations/vibe-voice-tts/README.md +64 -0
  22. package/plugins/generations/vibe-voice-tts/dist/index.js +14259 -0
  23. package/plugins/generations/vibe-voice-tts/package.json +16 -0
  24. package/plugins/generations/vibe-voice-tts/plugin.json +6 -0
  25. package/plugins/generations/vibe-voice-tts/profiles.json +10 -0
  26. package/plugins/generations/vibe-voice-tts/pyproject.toml +9 -0
  27. package/plugins/generations/vibe-voice-tts/python/worker.py +566 -0
  28. package/plugins/generations/vibe-voice-tts/src/index.ts +88 -0
  29. package/plugins/generations/vibe-voice-tts/src/vibevoice-client.ts +828 -0
  30. package/plugins/generations/vibe-voice-tts/tsconfig.json +8 -0
  31. package/plugins/generations/vibe-voice-tts/uv.lock +1767 -0
  32. package/plugins/generations/vibe-voice-tts/uv.toml +4 -0
  33. package/plugins/generations/voice-gen/dist/index.js +40 -10
  34. package/plugins/generations/voice-gen/src/voicebox-client.ts +50 -1
  35. package/plugins/generations/voxcpm-tts/dist/index.js +90 -18
  36. package/plugins/generations/voxcpm-tts/python/worker.py +9 -0
  37. package/plugins/generations/voxcpm-tts/src/index.ts +41 -0
  38. package/plugins/generations/voxcpm-tts/src/voxcpm-client.ts +32 -11
  39. package/plugins/generations/voxcpm-tts/uv.toml +5 -0
  40. package/plugins/ingestions/aihot-ingest/dist/index.js +12 -12
  41. package/plugins/ingestions/horizon-ingest/dist/index.js +12 -12
  42. package/plugins/ingestions/karakeep-local/dist/index.js +13 -13
  43. package/plugins/ingestions/last30days-ingest/dist/index.js +12 -12
  44. package/plugins/ingestions/web-search/dist/index.js +10 -10
  45. package/plugins/kk/README.md +21 -0
  46. package/plugins/kk/decisions/kk-safety.yaml +5 -2
  47. package/plugins/kk/plugin.json +1 -1
  48. package/plugins/kk/publish-presets/daily-ai-voice.json +16 -16
  49. package/plugins/kk/schedules/kk-serve.launchd.plist.tmpl +12 -1
  50. package/plugins/kk/scripts/cover-compositor.ts +104 -26
  51. package/plugins/kk/scripts/daily-stages.ts +481 -63
  52. package/plugins/kk/scripts/kk-workflow-stages.ts +218 -17
  53. package/plugins/kk/scripts/safety-artifact-check.ts +28 -5
  54. package/plugins/kk/scripts/series-names.ts +16 -3
  55. package/plugins/kk/skills/news-editorial/SKILL.md +1 -1
  56. package/plugins/kk/skills/news-editorial/references/style-contract.zh.md +3 -3
  57. package/plugins/kk/workflows/kk-daily-ai-voice.yaml +4 -3
  58. package/plugins/kk/workflows/kk-daily-ai-voice2.yaml +6 -5
  59. package/plugins/kk/workflows/kk-daily-safety.yaml +12 -10
  60. package/plugins/kk/workflows/kk-music.yaml +20 -16
  61. package/plugins/kk/workflows/kk-news-generate.yaml +26 -3
  62. package/plugins/kk/workflows/kk-publish.yaml +4 -1
  63. package/plugins/publishings/bilibili-pub/dist/index.js +22 -22
  64. package/plugins/publishings/bilibili-pub/dist/profile-check.js +22 -22
  65. package/plugins/publishings/cnblogs-pub/dist/index.js +22 -22
  66. package/plugins/publishings/cnblogs-pub/dist/profile-check.js +22 -22
  67. package/plugins/publishings/csdn-pub/dist/index.js +22 -22
  68. package/plugins/publishings/csdn-pub/dist/profile-check.js +22 -22
  69. package/plugins/publishings/emdash-pub/dist/index.js +9 -9
  70. package/plugins/publishings/infoq-pub/dist/index.js +22 -22
  71. package/plugins/publishings/infoq-pub/dist/profile-check.js +22 -22
  72. package/plugins/publishings/jike-pub/dist/index.js +22 -22
  73. package/plugins/publishings/jike-pub/dist/profile-check.js +22 -22
  74. package/plugins/publishings/juejin-pub/dist/index.js +22 -22
  75. package/plugins/publishings/juejin-pub/dist/profile-check.js +22 -22
  76. package/plugins/publishings/linkedin-pub/dist/index.js +133 -33
  77. package/plugins/publishings/linkedin-pub/dist/profile-check.js +27 -22
  78. package/plugins/publishings/linkedin-pub/src/index.ts +192 -18
  79. package/plugins/publishings/medium-pub/dist/index.js +9 -9
  80. package/plugins/publishings/podcast-pub/dist/index.js +240 -37
  81. package/plugins/publishings/podcast-pub/src/index.ts +154 -3
  82. package/plugins/publishings/podcast-pub/src/seo.ts +25 -8
  83. package/plugins/publishings/podcast-pub/src/show-notes-brief.ts +93 -23
  84. package/plugins/publishings/podcast-pub/src/show-notes.ts +26 -6
  85. package/plugins/publishings/qiita-pub/dist/index.js +9 -9
  86. package/plugins/publishings/shipinhao-pub/dist/index.js +23 -23
  87. package/plugins/publishings/shipinhao-pub/dist/profile-check.js +23 -23
  88. package/plugins/publishings/shipinhao-pub/src/selectors.ts +2 -1
  89. package/plugins/publishings/sspai-pub/dist/index.js +22 -22
  90. package/plugins/publishings/sspai-pub/dist/profile-check.js +22 -22
  91. package/plugins/publishings/substack-pub/dist/index.js +22 -22
  92. package/plugins/publishings/substack-pub/dist/profile-check.js +22 -22
  93. package/plugins/publishings/surfdash-pub/dist/index.js +207 -95
  94. package/plugins/publishings/surfdash-pub/src/digest-check.ts +30 -1
  95. package/plugins/publishings/surfdash-pub/src/index.ts +101 -76
  96. package/plugins/publishings/surfdash-pub/src/media-upload.ts +83 -0
  97. package/plugins/publishings/surfdash-pub/src/patch.ts +49 -26
  98. package/plugins/publishings/surfdash-pub/src/topic-claims.ts +12 -4
  99. package/plugins/publishings/threads-pub/dist/index.js +83 -27
  100. package/plugins/publishings/threads-pub/dist/profile-check.js +34 -23
  101. package/plugins/publishings/threads-pub/src/post-rail.ts +121 -4
  102. package/plugins/publishings/wechatmp-pub/dist/index.js +274 -98
  103. package/plugins/publishings/wechatmp-pub/dist/profile-check.js +27 -23
  104. package/plugins/publishings/wechatmp-pub/src/cgi-draft.ts +87 -53
  105. package/plugins/publishings/wechatmp-pub/src/enrich.ts +117 -13
  106. package/plugins/publishings/wechatmp-pub/src/flow.ts +183 -43
  107. package/plugins/publishings/wechatmp-pub/src/modes.ts +30 -12
  108. package/plugins/publishings/weibo-pub/dist/index.js +22 -22
  109. package/plugins/publishings/weibo-pub/dist/profile-check.js +22 -22
  110. package/plugins/publishings/x-pub/dist/index.js +113 -32
  111. package/plugins/publishings/x-pub/dist/profile-check.js +22 -22
  112. package/plugins/publishings/x-pub/src/post-rail.ts +155 -20
  113. package/plugins/publishings/xhs-pub/dist/index.js +22 -22
  114. package/plugins/publishings/xhs-pub/dist/profile-check.js +22 -22
  115. package/plugins/publishings/xiaoyuzhou-pub/dist/index.js +22 -22
  116. package/plugins/publishings/xiaoyuzhou-pub/dist/profile-check.js +22 -22
  117. package/plugins/publishings/zenn-pub/dist/index.js +9 -9
@@ -0,0 +1,828 @@
1
+ import { type ChildProcess, spawn } from 'node:child_process';
2
+ import { existsSync, mkdtempSync, readFileSync, realpathSync, rmSync } from 'node:fs';
3
+ import { tmpdir } from 'node:os';
4
+ import { delimiter, dirname, isAbsolute, join, resolve, sep } from 'node:path';
5
+ import { fileURLToPath } from 'node:url';
6
+ import { echoError } from '@gobing-ai/ts-utils';
7
+ import { type ParsedWav, parseWav, type VoiceboxClient, type VoiceboxGenerateBody } from '@gobing-ai/voice-gen';
8
+
9
+ /** Generator identity stamped into `metadata.generator` by the shared pipeline. */
10
+ export const VIBEVOICE_TTS_GENERATOR = 'kk:vibe-voice-tts';
11
+ /** Frozen backend defaults (ADR-055 / vibe-voice-driver). */
12
+ export const VIBEVOICE_DEFAULT_MODEL = 'microsoft/VibeVoice-1.5B';
13
+ export const VIBEVOICE_DEFAULT_DEVICE = 'auto';
14
+ export const VIBEVOICE_DEVICES = ['auto', 'cpu', 'cuda', 'mps'] as const;
15
+ /** Protocol framing bounds (frozen private adapter details). */
16
+ const LINE_MAX_BYTES = 1_048_576;
17
+ const STDERR_MAX_CHARS = 65_536;
18
+ /** Signal grace before SIGKILL of the owned process group. */
19
+ const TERM_GRACE_MS = 2000;
20
+ /** Bounded wait for the forced kill to land. */
21
+ const SIGKILL_GRACE_MS = 1000;
22
+ /** Signals that must tear down owned workers before the process ends. */
23
+ const SIGNAL_HANDLERS = ['SIGTERM', 'SIGINT'] as const;
24
+
25
+ export type VibeVoiceDevice = (typeof VIBEVOICE_DEVICES)[number];
26
+ export type VibeVoiceProfileMode = 'instruct' | 'reference' | 'cached_prompt';
27
+
28
+ export interface VibeVoiceProfile {
29
+ id: string;
30
+ name: string;
31
+ mode: VibeVoiceProfileMode;
32
+ instruct?: string;
33
+ reference_wav_path?: string;
34
+ prompt_pt_path?: string;
35
+ cfg_scale?: number;
36
+ ddpm_steps?: number;
37
+ }
38
+
39
+ export interface VibeVoiceClientOptions {
40
+ env?: Record<string, string | undefined>;
41
+ /** Override the worker argv (tests point at a fake NDJSON worker). */
42
+ workerCommand?: string[];
43
+ /** Override the plugin installation root; defaults to the directory above this module. */
44
+ pluginRoot?: string;
45
+ spawn?: VibeVoiceSpawn;
46
+ }
47
+
48
+ export interface VibeVoiceSpawnOptions {
49
+ cwd: string;
50
+ env: Record<string, string | undefined>;
51
+ }
52
+
53
+ export type VibeVoiceSpawn = (command: string[], options: VibeVoiceSpawnOptions) => ChildProcess;
54
+
55
+ export interface VibeVoiceClientHandle {
56
+ readonly client: VoiceboxClient;
57
+ readonly scratchDir: string;
58
+ close(): Promise<void>;
59
+ }
60
+
61
+ interface PendingRequest {
62
+ resolve: (value: Record<string, unknown>) => void;
63
+ reject: (error: Error) => void;
64
+ }
65
+
66
+ const BASE_ENV_KEYS = [
67
+ 'PATH',
68
+ 'HOME',
69
+ 'TMPDIR',
70
+ 'LANG',
71
+ 'LC_ALL',
72
+ 'PYTHONPATH',
73
+ 'PYTHONHOME',
74
+ 'VIRTUAL_ENV',
75
+ 'UV_PROJECT_ENVIRONMENT',
76
+ 'UV_CACHE_DIR',
77
+ 'UV_PYTHON',
78
+ 'HF_HOME',
79
+ 'HF_HUB_CACHE',
80
+ 'XDG_CACHE_HOME',
81
+ 'HF_HUB_OFFLINE',
82
+ 'TRANSFORMERS_CACHE',
83
+ 'HF_DATASETS_CACHE',
84
+ ];
85
+
86
+ /**
87
+ * Reject any path (including one reached through a symlink) whose canonical form contains a
88
+ * `vendors` segment — `vendors/` is reference-only and must never be a product runtime path
89
+ * (ADR-055). Returns the resolved absolute path for reuse.
90
+ */
91
+ export function assertNoVendorPath(candidate: string, label: string): string {
92
+ const resolved = resolve(candidate);
93
+ if (resolved.split(sep).includes('vendors')) {
94
+ throw new Error(`vibe-voice-tts: ${label} must not reference vendors/ (reference-only): ${resolved}`);
95
+ }
96
+ if (existsSync(resolved)) {
97
+ const real = realpathSync(resolved);
98
+ if (real.split(sep).includes('vendors')) {
99
+ throw new Error(`vibe-voice-tts: ${label} resolves into vendors/ (reference-only): ${real}`);
100
+ }
101
+ }
102
+ return resolved;
103
+ }
104
+
105
+ /** Validate every configured import/cache/environment path before the worker is spawned. */
106
+ function assertEnvPathsSafe(env: Record<string, string | undefined>): void {
107
+ for (const key of BASE_ENV_KEYS) {
108
+ const raw = env[key];
109
+ if (!raw) {
110
+ continue;
111
+ }
112
+ for (const part of raw.split(delimiter)) {
113
+ if (part) {
114
+ assertNoVendorPath(part, key);
115
+ }
116
+ }
117
+ }
118
+ }
119
+
120
+ function assertDeviceSafe(env: Record<string, string | undefined>): VibeVoiceDevice {
121
+ const raw = env.VIBEVOICE_DEVICE ?? VIBEVOICE_DEFAULT_DEVICE;
122
+ if (!(VIBEVOICE_DEVICES as readonly string[]).includes(raw)) {
123
+ throw new Error(
124
+ `vibe-voice-tts: unsupported VIBEVOICE_DEVICE "${raw}" (allowed: ${VIBEVOICE_DEVICES.join(', ')})`,
125
+ );
126
+ }
127
+ return raw as VibeVoiceDevice;
128
+ }
129
+
130
+ /**
131
+ * Parse and validate the frozen VibeVoice profile registry: unique nonempty ids/names; `instruct`
132
+ * needs an instruction; `reference` needs `reference_wav_path`; `cached_prompt` needs
133
+ * `prompt_pt_path`; relative assets resolve against the registry directory; serialized OmniVoice
134
+ * prompts, invalid numeric inference knobs, mixed mode fields, and vendor paths are refused.
135
+ */
136
+ export function parseVibeVoiceRegistry(raw: unknown, registryDir: string): VibeVoiceProfile[] {
137
+ const container = raw as { profiles?: unknown };
138
+ if (!container || typeof container !== 'object' || !Array.isArray(container.profiles)) {
139
+ throw new Error('vibe-voice-tts: profile registry must be an object with a "profiles" array');
140
+ }
141
+ const seenIds = new Set<string>();
142
+ const seenNames = new Set<string>();
143
+ return container.profiles.map((entry, index) => {
144
+ const profile = entry as Record<string, unknown>;
145
+ if (!profile || typeof profile !== 'object') {
146
+ throw new Error(`vibe-voice-tts: profile registry entry ${index} is not an object`);
147
+ }
148
+ const id = typeof profile.id === 'string' ? profile.id.trim() : '';
149
+ const name = typeof profile.name === 'string' ? profile.name.trim() : '';
150
+ if (!id || !name) {
151
+ throw new Error(`vibe-voice-tts: profile registry entry ${index} needs nonempty id and name`);
152
+ }
153
+ if (seenIds.has(id) || seenNames.has(name)) {
154
+ throw new Error(`vibe-voice-tts: duplicate profile id/name "${id}"`);
155
+ }
156
+ seenIds.add(id);
157
+ seenNames.add(name);
158
+ if ('prompt' in profile || 'serialized_prompt' in profile) {
159
+ throw new Error(`vibe-voice-tts: profile "${id}" carries a serialized OmniVoice prompt`);
160
+ }
161
+ const mode = profile.mode;
162
+ if (mode !== 'instruct' && mode !== 'reference' && mode !== 'cached_prompt') {
163
+ throw new Error(`vibe-voice-tts: profile "${id}" has unsupported mode "${String(mode)}"`);
164
+ }
165
+ const asset = (key: string): string | undefined => {
166
+ const value = profile[key];
167
+ if (value === undefined) {
168
+ return undefined;
169
+ }
170
+ if (typeof value !== 'string' || !value.trim()) {
171
+ throw new Error(`vibe-voice-tts: profile "${id}" field ${key} must be a nonempty string`);
172
+ }
173
+ const path = isAbsolute(value) ? value : resolve(registryDir, value);
174
+ return assertNoVendorPath(path, `profile "${id}" ${key}`);
175
+ };
176
+ const instruct = typeof profile.instruct === 'string' ? profile.instruct.trim() : undefined;
177
+ const reference = asset('reference_wav_path');
178
+ const promptPt = asset('prompt_pt_path');
179
+
180
+ const mixed = mode === 'instruct' ? [reference, promptPt] : mode === 'reference' ? [promptPt] : [reference];
181
+ if (mixed.some((value) => value !== undefined)) {
182
+ throw new Error(`vibe-voice-tts: profile "${id}" mixes mode "${mode}" with fields from another mode`);
183
+ }
184
+ if (mode === 'instruct' && !instruct) {
185
+ throw new Error(`vibe-voice-tts: instruct profile "${id}" needs a nonempty instruct`);
186
+ }
187
+ if (mode === 'reference' && !reference) {
188
+ throw new Error(`vibe-voice-tts: reference profile "${id}" needs reference_wav_path`);
189
+ }
190
+ if (mode === 'cached_prompt' && !promptPt) {
191
+ throw new Error(`vibe-voice-tts: cached_prompt profile "${id}" needs prompt_pt_path`);
192
+ }
193
+
194
+ let cfgScale: number | undefined;
195
+ if (profile.cfg_scale !== undefined) {
196
+ if (
197
+ typeof profile.cfg_scale !== 'number' ||
198
+ !Number.isFinite(profile.cfg_scale) ||
199
+ profile.cfg_scale <= 0
200
+ ) {
201
+ throw new Error(`vibe-voice-tts: profile "${id}" cfg_scale must be a positive finite number`);
202
+ }
203
+ cfgScale = profile.cfg_scale;
204
+ }
205
+ let ddpmSteps: number | undefined;
206
+ if (profile.ddpm_steps !== undefined) {
207
+ if (
208
+ typeof profile.ddpm_steps !== 'number' ||
209
+ !Number.isInteger(profile.ddpm_steps) ||
210
+ profile.ddpm_steps <= 0
211
+ ) {
212
+ throw new Error(`vibe-voice-tts: profile "${id}" ddpm_steps must be a positive integer`);
213
+ }
214
+ ddpmSteps = profile.ddpm_steps;
215
+ }
216
+
217
+ return {
218
+ id,
219
+ name,
220
+ mode,
221
+ ...(instruct ? { instruct } : {}),
222
+ ...(reference ? { reference_wav_path: reference } : {}),
223
+ ...(promptPt ? { prompt_pt_path: promptPt } : {}),
224
+ ...(cfgScale !== undefined ? { cfg_scale: cfgScale } : {}),
225
+ ...(ddpmSteps !== undefined ? { ddpm_steps: ddpmSteps } : {}),
226
+ };
227
+ });
228
+ }
229
+
230
+ const DEFAULT_PLUGIN_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..');
231
+
232
+ /** Resolve the locked uv argv used to launch the private Python worker process. */
233
+ export function resolveVibeVoiceWorkerCommand(pluginRoot: string): string[] {
234
+ return [
235
+ 'uv',
236
+ 'run',
237
+ '--project',
238
+ pluginRoot,
239
+ '--locked',
240
+ '--no-dev',
241
+ 'python',
242
+ join(pluginRoot, 'python', 'worker.py'),
243
+ ];
244
+ }
245
+
246
+ const defaultSpawn: VibeVoiceSpawn = (command, options) =>
247
+ spawn(command[0] as string, command.slice(1), {
248
+ cwd: options.cwd,
249
+ env: options.env,
250
+ stdio: ['pipe', 'pipe', 'pipe'],
251
+ detached: true,
252
+ });
253
+
254
+ function readWavFile(path: string): ParsedWav {
255
+ let wav: ParsedWav;
256
+ try {
257
+ wav = parseWav(new Uint8Array(readFileSync(path)));
258
+ } catch (err: unknown) {
259
+ throw new Error(
260
+ `vibe-voice-tts: invalid worker WAV at ${path}: ${err instanceof Error ? err.message : String(err)}`,
261
+ );
262
+ }
263
+ if (wav.audioFormat !== 1 || wav.bitsPerSample !== 16) {
264
+ throw new Error(
265
+ `vibe-voice-tts: worker WAV must be 16-bit PCM (got format ${wav.audioFormat}/${wav.bitsPerSample}bit)`,
266
+ );
267
+ }
268
+ if (wav.numChannels !== 1) {
269
+ throw new Error(`vibe-voice-tts: worker WAV must be mono (got ${wav.numChannels} channels)`);
270
+ }
271
+ if (!Number.isFinite(wav.sampleRate) || wav.sampleRate <= 0 || wav.byteRate <= 0) {
272
+ throw new Error(`vibe-voice-tts: worker WAV needs a positive sample rate (got ${wav.sampleRate})`);
273
+ }
274
+ if (wav.dataBytes.length === 0) {
275
+ throw new Error('vibe-voice-tts: worker WAV carries no samples');
276
+ }
277
+ return wav;
278
+ }
279
+
280
+ /**
281
+ * Invocation-scoped VibeVoice adapter over the shared `VoiceboxClient` contract: a private uv
282
+ * Python worker speaking bounded integer-id NDJSON, at most one model load per invocation, one
283
+ * in-flight render, and signal/deadline-scoped process-group teardown. Returns the client plus an
284
+ * async `close()` the entry calls from `finally`.
285
+ */
286
+ export function createVibeVoiceClient(options: VibeVoiceClientOptions = {}): VibeVoiceClientHandle {
287
+ const env = options.env ?? (process.env as Record<string, string | undefined>);
288
+ const spawnProcess = options.spawn ?? defaultSpawn;
289
+ const pluginRoot = assertNoVendorPath(options.pluginRoot ?? DEFAULT_PLUGIN_ROOT, 'plugin root');
290
+ const registryPath = assertNoVendorPath(
291
+ env.VIBEVOICE_PROFILES_PATH ?? join(pluginRoot, 'profiles.json'),
292
+ 'profiles',
293
+ );
294
+ const workerCommand = options.workerCommand ?? resolveVibeVoiceWorkerCommand(pluginRoot);
295
+ const startupTimeoutMs = positiveTimeout(env.VOICEBOX_TIMEOUT_MS, 600_000);
296
+ const scratchDir = mkdtempSync(join(tmpdir(), 'kk-vibe-voice-tts-'));
297
+
298
+ let child: ChildProcess | undefined;
299
+ let nextId = 1;
300
+ let fatal: Error | undefined;
301
+ let closed = false;
302
+ let stderrTail = '';
303
+ let stderrDone: Promise<void> = Promise.resolve();
304
+ let exitDetails: { code: number | null; signal: NodeJS.Signals | null } | undefined;
305
+ let stdoutBuffer = '';
306
+ let renderInFlight: { id: number; dest: string } | undefined;
307
+ let warnedChunk = false;
308
+ let warnedLanguage = false;
309
+ let warnedInstruct = false;
310
+ let warnedInstructIgnored = false;
311
+ let instructSegments = 0;
312
+ const pending = new Map<number, PendingRequest>();
313
+ const renderResults = new Map<number, Promise<Record<string, unknown>>>();
314
+ const signalHandlers = new Map<NodeJS.Signals, () => void>();
315
+ const destinations = new Map<number, string>();
316
+ const profileCache = new Map<string, VibeVoiceProfile>();
317
+
318
+ function fail(error: Error): void {
319
+ if (!fatal) {
320
+ fatal = error;
321
+ }
322
+ for (const [, request] of pending) {
323
+ request.reject(fatal);
324
+ }
325
+ pending.clear();
326
+ renderInFlight = undefined;
327
+ void terminateChild();
328
+ }
329
+
330
+ function onLine(line: string): void {
331
+ if (line.length === 0) {
332
+ return;
333
+ }
334
+ if (Buffer.byteLength(line) > LINE_MAX_BYTES) {
335
+ fail(new Error('vibe-voice-tts: worker response frame exceeds 1 MiB'));
336
+ return;
337
+ }
338
+ let message: Record<string, unknown>;
339
+ try {
340
+ message = JSON.parse(line) as Record<string, unknown>;
341
+ } catch {
342
+ fail(new Error(`vibe-voice-tts: worker emitted invalid JSON: ${line.slice(0, 120)}`));
343
+ return;
344
+ }
345
+ const id = message.id;
346
+ if (typeof id !== 'number' || !Number.isInteger(id)) {
347
+ fail(new Error('vibe-voice-tts: worker response is missing an integer id'));
348
+ return;
349
+ }
350
+ const request = pending.get(id);
351
+ if (!request) {
352
+ fail(new Error(`vibe-voice-tts: worker response for unknown or duplicate id ${id}`));
353
+ return;
354
+ }
355
+ pending.delete(id);
356
+ request.resolve(message);
357
+ }
358
+
359
+ function consumeStdout(text: string): void {
360
+ stdoutBuffer += text;
361
+ let newline = stdoutBuffer.indexOf('\n');
362
+ while (newline !== -1) {
363
+ const line = stdoutBuffer.slice(0, newline).replace(/\r$/, '');
364
+ stdoutBuffer = stdoutBuffer.slice(newline + 1);
365
+ onLine(line);
366
+ newline = stdoutBuffer.indexOf('\n');
367
+ }
368
+ if (Buffer.byteLength(stdoutBuffer, 'utf8') > LINE_MAX_BYTES) {
369
+ fail(new Error('vibe-voice-tts: worker response frame exceeds 1 MiB'));
370
+ }
371
+ }
372
+
373
+ function startWorker(): void {
374
+ if (child) {
375
+ return;
376
+ }
377
+ assertEnvPathsSafe(env);
378
+ const device = assertDeviceSafe(env);
379
+ assertNoVendorPath(workerCommand[workerCommand.length - 1] ?? pluginRoot, 'worker script');
380
+ let proc: ChildProcess;
381
+ try {
382
+ proc = spawnProcess(workerCommand, {
383
+ cwd: pluginRoot,
384
+ env: {
385
+ ...pickEnv(env),
386
+ VIBEVOICE_MODEL: env.VIBEVOICE_MODEL ?? VIBEVOICE_DEFAULT_MODEL,
387
+ VIBEVOICE_DEVICE: device,
388
+ VIBEVOICE_PROFILES_PATH: registryPath,
389
+ },
390
+ });
391
+ } catch (err: unknown) {
392
+ throw new Error(
393
+ `vibe-voice-tts: failed to spawn worker: ${err instanceof Error ? err.message : String(err)}`,
394
+ );
395
+ }
396
+ child = proc;
397
+ proc.on('error', (err) => fail(new Error(`vibe-voice-tts: worker process error: ${err.message}`)));
398
+ proc.on('exit', (code, signal) => {
399
+ exitDetails = { code, signal };
400
+ if (!closed && !fatal) {
401
+ void Promise.race([stderrDone, new Promise((r) => setTimeout(r, 150))]).then(() => {
402
+ if (!closed && !fatal) {
403
+ fail(
404
+ new Error(
405
+ `vibe-voice-tts: worker exited unexpectedly (code ${code ?? 'null'}, signal ${signal ?? 'none'})${stderrTail ? `: ${stderrTail.slice(-400)}` : ''}`,
406
+ ),
407
+ );
408
+ }
409
+ });
410
+ }
411
+ });
412
+ if (proc.stderr) {
413
+ stderrDone = pump(proc.stderr, (text) => {
414
+ stderrTail = (stderrTail + text).slice(-STDERR_MAX_CHARS);
415
+ });
416
+ }
417
+ if (proc.stdout) {
418
+ void pump(proc.stdout, consumeStdout, () => {
419
+ if (!fatal && !closed) {
420
+ void Promise.race([
421
+ Promise.all([waitForExit(proc, 250), stderrDone]),
422
+ new Promise((r) => setTimeout(r, 250)),
423
+ ]).then(() => {
424
+ if (!fatal && !closed) {
425
+ const detail = exitDetails
426
+ ? ` (code ${exitDetails.code ?? 'null'}, signal ${exitDetails.signal ?? 'none'})`
427
+ : ' before settling all requests';
428
+ fail(
429
+ new Error(
430
+ `vibe-voice-tts: worker closed stdout${detail}${stderrTail ? `: ${stderrTail.slice(-400)}` : ''}`,
431
+ ),
432
+ );
433
+ }
434
+ });
435
+ }
436
+ });
437
+ }
438
+ for (const signal of SIGNAL_HANDLERS) {
439
+ const handler = () => {
440
+ void close();
441
+ };
442
+ signalHandlers.set(signal, handler);
443
+ process.on(signal, handler);
444
+ }
445
+ }
446
+
447
+ function removeSignalHandlers(): void {
448
+ for (const [signal, handler] of signalHandlers) {
449
+ process.off(signal, handler);
450
+ }
451
+ signalHandlers.clear();
452
+ }
453
+
454
+ async function terminateChild(): Promise<void> {
455
+ const proc = child;
456
+ child = undefined;
457
+ if (!proc?.pid) {
458
+ try {
459
+ proc?.stdin?.end();
460
+ } catch {
461
+ // stdin already gone
462
+ }
463
+ return;
464
+ }
465
+ const pgid = proc.pid;
466
+ try {
467
+ proc.stdin?.end();
468
+ } catch {
469
+ // stdin already gone
470
+ }
471
+ killGroup(pgid, 'SIGTERM');
472
+ let groupGone = await waitForGroupGone(pgid, TERM_GRACE_MS);
473
+ if (!groupGone) {
474
+ killGroup(pgid, 'SIGKILL');
475
+ groupGone = await waitForGroupGone(pgid, SIGKILL_GRACE_MS);
476
+ }
477
+ await waitForExit(proc, SIGKILL_GRACE_MS);
478
+ if (!groupGone) {
479
+ echoError(
480
+ `vibe-voice-tts: cleanup failure: owned worker group ${pgid} still alive after SIGKILL (${SIGKILL_GRACE_MS}ms)`,
481
+ );
482
+ }
483
+ }
484
+
485
+ function sendRequest(op: string, extra: Record<string, unknown>): Promise<Record<string, unknown>> {
486
+ const proc = child;
487
+ if (!proc?.stdin) {
488
+ throw new Error('vibe-voice-tts: worker is not running');
489
+ }
490
+ const id = nextId++;
491
+ const request = { id, op, ...extra };
492
+ const promise = new Promise<Record<string, unknown>>((res, rej) => {
493
+ pending.set(id, { resolve: res, reject: rej });
494
+ });
495
+ proc.stdin.write(`${JSON.stringify(request)}\n`);
496
+ return promise;
497
+ }
498
+
499
+ async function awaitResponse(promise: Promise<Record<string, unknown>>, timeoutMs: number, label: string) {
500
+ return withDeadline(promise, timeoutMs, `${label} timed out after ${timeoutMs}ms`, (message) =>
501
+ fail(new Error(`vibe-voice-tts: ${message}`)),
502
+ );
503
+ }
504
+
505
+ function resolveProfileSync(nameOrId: string): VibeVoiceProfile {
506
+ const registry = loadRegistry();
507
+ const cached = profileCache.get(nameOrId);
508
+ if (cached) {
509
+ return cached;
510
+ }
511
+ const lower = nameOrId.toLowerCase();
512
+ const match = registry.find((entry) => entry.id === nameOrId || entry.name.toLowerCase() === lower);
513
+ if (!match) {
514
+ throw new Error(`vibe-voice-tts: unknown voice profile "${nameOrId}"`);
515
+ }
516
+ profileCache.set(nameOrId, match);
517
+ profileCache.set(match.id, match);
518
+ return match;
519
+ }
520
+
521
+ let registry: VibeVoiceProfile[] | undefined;
522
+ function loadRegistry(): VibeVoiceProfile[] {
523
+ if (registry) {
524
+ return registry;
525
+ }
526
+ if (!existsSync(registryPath)) {
527
+ throw new Error(`vibe-voice-tts: profile registry not found: ${registryPath}`);
528
+ }
529
+ let parsed: unknown;
530
+ try {
531
+ parsed = JSON.parse(readFileSync(registryPath, 'utf-8'));
532
+ } catch (err: unknown) {
533
+ throw new Error(
534
+ `vibe-voice-tts: profile registry is not valid JSON: ${err instanceof Error ? err.message : String(err)}`,
535
+ );
536
+ }
537
+ registry = parseVibeVoiceRegistry(parsed, dirname(registryPath));
538
+ return registry;
539
+ }
540
+
541
+ function policyCheck(
542
+ body: VoiceboxGenerateBody,
543
+ profile: VibeVoiceProfile,
544
+ ): { instruct?: string; normalize: boolean } {
545
+ if (body.engine?.trim()) {
546
+ throw new Error(`vibe-voice-tts: engine "${body.engine}" is not supported (VibeVoice only)`);
547
+ }
548
+ if (body.personality === true) {
549
+ throw new Error('vibe-voice-tts: personality=true is not supported');
550
+ }
551
+ if (Array.isArray(body.effects_chain) && body.effects_chain.some((effect) => effect?.enabled !== false)) {
552
+ throw new Error('vibe-voice-tts: an active effects_chain is not supported');
553
+ }
554
+ const requestedInstruct = body.instruct?.trim();
555
+ if (profile.mode === 'instruct') {
556
+ instructSegments += 1;
557
+ if (instructSegments > 1) {
558
+ throw new Error(
559
+ `vibe-voice-tts: profile "${profile.id}" is instruct-mode and pins no speaker — segment ${instructSegments} would sound like a different person; use a reference/cached_prompt profile (VIBEVOICE_PROFILES_PATH)`,
560
+ );
561
+ }
562
+ if (!warnedInstruct) {
563
+ warnedInstruct = true;
564
+ echoError(
565
+ `vibe-voice-tts: profile "${profile.id}" is instruct-mode and pins no speaker — every request draws a new voice; use a reference or cached_prompt profile for multi-segment episodes`,
566
+ );
567
+ }
568
+ const instruct = requestedInstruct || profile.instruct;
569
+ if (instruct) {
570
+ return { instruct, normalize: body.normalize ?? true };
571
+ }
572
+ return { normalize: body.normalize ?? true };
573
+ }
574
+ if (requestedInstruct) {
575
+ if (!warnedInstructIgnored) {
576
+ warnedInstructIgnored = true;
577
+ echoError(
578
+ `vibe-voice-tts: ignoring the per-request instruct on "${profile.mode}" profile "${profile.id}" — the anchored voice asset defines the speaker`,
579
+ );
580
+ }
581
+ }
582
+ return { normalize: body.normalize ?? true };
583
+ }
584
+
585
+ function warnAdvisory(body: VoiceboxGenerateBody): void {
586
+ if (!warnedChunk && (body.max_chunk_chars !== undefined || body.crossfade_ms !== undefined)) {
587
+ warnedChunk = true;
588
+ echoError(
589
+ 'vibe-voice-tts: max_chunk_chars/crossfade_ms are advisory; shared VoiceScript segmentation is the request boundary',
590
+ );
591
+ }
592
+ if (!warnedLanguage) {
593
+ warnedLanguage = true;
594
+ echoError(
595
+ 'vibe-voice-tts: language is inferred automatically by VibeVoice; the requested language keyword is ignored',
596
+ );
597
+ }
598
+ }
599
+
600
+ async function close(): Promise<void> {
601
+ if (closed) {
602
+ return;
603
+ }
604
+ closed = true;
605
+ removeSignalHandlers();
606
+ for (const [, request] of pending) {
607
+ request.reject(new Error('vibe-voice-tts: client closed'));
608
+ }
609
+ pending.clear();
610
+ await terminateChild();
611
+ try {
612
+ rmSync(scratchDir, { recursive: true, force: true });
613
+ } catch {
614
+ // best-effort scratch cleanup
615
+ }
616
+ }
617
+
618
+ const client: VoiceboxClient = {
619
+ url: `uv://${pluginRoot}`,
620
+
621
+ async health(): Promise<void> {
622
+ if (fatal) {
623
+ throw fatal;
624
+ }
625
+ if (closed) {
626
+ throw new Error('vibe-voice-tts: client is closed');
627
+ }
628
+ if (!child) {
629
+ startWorker();
630
+ }
631
+ const response = await awaitResponse(
632
+ sendRequest('health', {}),
633
+ startupTimeoutMs,
634
+ 'vibe-voice-tts worker startup',
635
+ );
636
+ if (response.ok !== true) {
637
+ throw new Error(`vibe-voice-tts: worker health failed: ${String(response.error ?? 'unknown error')}`);
638
+ }
639
+ },
640
+
641
+ async resolveProfile(nameOrId: string) {
642
+ const profile = resolveProfileSync(nameOrId);
643
+ return { id: profile.id, name: profile.name };
644
+ },
645
+
646
+ async generate(body: VoiceboxGenerateBody): Promise<{ id: string }> {
647
+ if (fatal) {
648
+ throw fatal;
649
+ }
650
+ if (closed) {
651
+ throw new Error('vibe-voice-tts: client is closed');
652
+ }
653
+ if (renderInFlight) {
654
+ throw new Error('vibe-voice-tts: a render is already in flight; only one request at a time is allowed');
655
+ }
656
+ const profile = resolveProfileSync(body.profile_id);
657
+ const policy = policyCheck(body, profile);
658
+ warnAdvisory(body);
659
+ if (!child) {
660
+ startWorker();
661
+ }
662
+ const id = nextId;
663
+ const dest = assertNoVendorPath(join(scratchDir, `render-${id}.wav`), 'render destination');
664
+ const promise = sendRequest('render', {
665
+ text: body.text,
666
+ profile: {
667
+ id: profile.id,
668
+ name: profile.name,
669
+ mode: profile.mode,
670
+ ...(policy.instruct ? { instruct: policy.instruct } : {}),
671
+ ...(profile.reference_wav_path ? { reference_wav_path: profile.reference_wav_path } : {}),
672
+ ...(profile.prompt_pt_path ? { prompt_pt_path: profile.prompt_pt_path } : {}),
673
+ ...(profile.cfg_scale !== undefined ? { cfg_scale: profile.cfg_scale } : {}),
674
+ ...(profile.ddpm_steps !== undefined ? { ddpm_steps: profile.ddpm_steps } : {}),
675
+ },
676
+ normalize: policy.normalize,
677
+ seed: body.seed ?? null,
678
+ dest,
679
+ });
680
+ renderInFlight = { id, dest };
681
+ destinations.set(id, dest);
682
+ const settled = promise.finally(() => {
683
+ if (renderInFlight?.id === id) {
684
+ renderInFlight = undefined;
685
+ }
686
+ });
687
+ renderResults.set(id, settled);
688
+ void settled.catch(() => {});
689
+ return { id: String(id) };
690
+ },
691
+
692
+ async waitUntilDone(id: string, timeoutMs?: number) {
693
+ const numeric = Number.parseInt(id, 10);
694
+ const result = renderResults.get(numeric);
695
+ if (!result) {
696
+ return { status: 'failed' as const, error: `vibe-voice-tts: unknown generation id ${id}` };
697
+ }
698
+ let response: Record<string, unknown>;
699
+ try {
700
+ response = await awaitResponse(result, timeoutMs ?? startupTimeoutMs, `vibe-voice-tts render ${id}`);
701
+ } catch (err: unknown) {
702
+ if (fatal) {
703
+ throw fatal;
704
+ }
705
+ return { status: 'failed' as const, error: err instanceof Error ? err.message : String(err) };
706
+ }
707
+ renderResults.delete(numeric);
708
+ if (response.ok !== true) {
709
+ return { status: 'failed' as const, error: String(response.error ?? 'unknown error') };
710
+ }
711
+ const dest = destinations.get(numeric);
712
+ const wavPath = typeof response.wav_path === 'string' ? response.wav_path : '';
713
+ if (!dest || resolve(wavPath) !== dest) {
714
+ const err = new Error(`vibe-voice-tts: worker reported an unexpected WAV path "${wavPath}"`);
715
+ fail(err);
716
+ throw err;
717
+ }
718
+ const wav = readWavFile(dest);
719
+ return { status: 'completed' as const, duration: wav.dataBytes.length / wav.byteRate };
720
+ },
721
+
722
+ async downloadAudio(id: string): Promise<Uint8Array> {
723
+ if (fatal) {
724
+ throw fatal;
725
+ }
726
+ const numeric = Number.parseInt(id, 10);
727
+ const dest = destinations.get(numeric);
728
+ if (!dest) {
729
+ throw new Error(`vibe-voice-tts: unknown generation id ${id}`);
730
+ }
731
+ readWavFile(dest);
732
+ return new Uint8Array(readFileSync(dest));
733
+ },
734
+ };
735
+
736
+ return { client, scratchDir, close };
737
+ }
738
+
739
+ function positiveTimeout(raw: string | undefined, fallback: number): number {
740
+ const parsed = raw ? Number.parseInt(raw, 10) : Number.NaN;
741
+ return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback;
742
+ }
743
+
744
+ function pickEnv(env: Record<string, string | undefined>): Record<string, string | undefined> {
745
+ const picked: Record<string, string | undefined> = {};
746
+ for (const [key, value] of Object.entries(env)) {
747
+ if (typeof value === 'string') {
748
+ picked[key] = value;
749
+ }
750
+ }
751
+ return picked;
752
+ }
753
+
754
+ function killGroup(pid: number, signal: NodeJS.Signals): void {
755
+ try {
756
+ process.kill(-pid, signal);
757
+ } catch {
758
+ try {
759
+ process.kill(pid, signal);
760
+ } catch {
761
+ // already gone
762
+ }
763
+ }
764
+ }
765
+
766
+ function waitForGroupGone(pgid: number, timeoutMs: number): Promise<boolean> {
767
+ const start = Date.now();
768
+ return new Promise((resolvePromise) => {
769
+ const poll = (): void => {
770
+ try {
771
+ process.kill(-pgid, 0);
772
+ } catch {
773
+ resolvePromise(true);
774
+ return;
775
+ }
776
+ if (Date.now() - start >= timeoutMs) {
777
+ resolvePromise(false);
778
+ return;
779
+ }
780
+ setTimeout(poll, 25);
781
+ };
782
+ poll();
783
+ });
784
+ }
785
+
786
+ function waitForExit(proc: ChildProcess, timeoutMs: number): Promise<boolean> {
787
+ return new Promise((resolvePromise) => {
788
+ if (proc.exitCode !== null || proc.signalCode !== null) {
789
+ resolvePromise(true);
790
+ return;
791
+ }
792
+ const timer = setTimeout(() => resolvePromise(false), timeoutMs);
793
+ proc.once('exit', () => {
794
+ clearTimeout(timer);
795
+ resolvePromise(true);
796
+ });
797
+ });
798
+ }
799
+
800
+ async function pump(stream: NodeJS.ReadableStream, onChunk: (text: string) => void, onEnd?: () => void): Promise<void> {
801
+ const decoder = new TextDecoder();
802
+ try {
803
+ for await (const chunk of stream) {
804
+ onChunk(decoder.decode(chunk as Uint8Array, { stream: true }));
805
+ }
806
+ onChunk(decoder.decode());
807
+ } catch {
808
+ // stream failure is surfaced through the worker exit path
809
+ } finally {
810
+ onEnd?.();
811
+ }
812
+ }
813
+
814
+ function withDeadline<T>(
815
+ promise: Promise<T>,
816
+ timeoutMs: number,
817
+ timeoutMessage: string,
818
+ onTimeout: (message: string) => void,
819
+ ): Promise<T> {
820
+ let timer: ReturnType<typeof setTimeout> | undefined;
821
+ const timeout = new Promise<never>((_, reject) => {
822
+ timer = setTimeout(() => {
823
+ onTimeout(timeoutMessage);
824
+ reject(new Error(timeoutMessage));
825
+ }, timeoutMs);
826
+ });
827
+ return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));
828
+ }