@gobing-ai/knowledge-kit 0.1.22 → 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 (59) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/dist/index.js +165 -91
  3. package/package.json +1 -1
  4. package/plugins/generations/gemini-tts/dist/index.js +47 -7
  5. package/plugins/generations/gemini-tts/src/gemini-client.ts +34 -6
  6. package/plugins/generations/music-gen/README.md +2 -2
  7. package/plugins/generations/music-gen/dist/index.js +46 -10
  8. package/plugins/generations/music-gen/presets/formats/song.yaml +6 -1
  9. package/plugins/generations/music-gen/presets/themes/synthwave.yaml +6 -1
  10. package/plugins/generations/music-gen/src/adapter/instance.ts +34 -11
  11. package/plugins/generations/music-gen/src/presets.ts +36 -3
  12. package/plugins/generations/omni-voice-gen/uv.toml +5 -0
  13. package/plugins/generations/vibe-voice-tts/README.md +64 -0
  14. package/plugins/generations/vibe-voice-tts/dist/index.js +14259 -0
  15. package/plugins/generations/vibe-voice-tts/package.json +16 -0
  16. package/plugins/generations/vibe-voice-tts/plugin.json +6 -0
  17. package/plugins/generations/vibe-voice-tts/profiles.json +10 -0
  18. package/plugins/generations/vibe-voice-tts/pyproject.toml +9 -0
  19. package/plugins/generations/vibe-voice-tts/python/worker.py +566 -0
  20. package/plugins/generations/vibe-voice-tts/src/index.ts +88 -0
  21. package/plugins/generations/vibe-voice-tts/src/vibevoice-client.ts +828 -0
  22. package/plugins/generations/vibe-voice-tts/tsconfig.json +8 -0
  23. package/plugins/generations/vibe-voice-tts/uv.lock +1767 -0
  24. package/plugins/generations/vibe-voice-tts/uv.toml +4 -0
  25. package/plugins/generations/voice-gen/dist/index.js +31 -1
  26. package/plugins/generations/voice-gen/src/voicebox-client.ts +50 -1
  27. package/plugins/generations/voxcpm-tts/dist/index.js +81 -9
  28. package/plugins/generations/voxcpm-tts/python/worker.py +9 -0
  29. package/plugins/generations/voxcpm-tts/src/index.ts +41 -0
  30. package/plugins/generations/voxcpm-tts/src/voxcpm-client.ts +32 -11
  31. package/plugins/generations/voxcpm-tts/uv.toml +5 -0
  32. package/plugins/kk/README.md +21 -0
  33. package/plugins/kk/decisions/kk-safety.yaml +5 -2
  34. package/plugins/kk/plugin.json +1 -1
  35. package/plugins/kk/schedules/kk-serve.launchd.plist.tmpl +12 -1
  36. package/plugins/kk/scripts/daily-stages.ts +274 -40
  37. package/plugins/kk/scripts/kk-workflow-stages.ts +74 -11
  38. package/plugins/kk/scripts/safety-artifact-check.ts +28 -5
  39. package/plugins/kk/workflows/kk-daily-ai-voice.yaml +4 -3
  40. package/plugins/kk/workflows/kk-daily-ai-voice2.yaml +6 -5
  41. package/plugins/kk/workflows/kk-daily-safety.yaml +12 -10
  42. package/plugins/kk/workflows/kk-music.yaml +20 -16
  43. package/plugins/kk/workflows/kk-news-generate.yaml +23 -3
  44. package/plugins/kk/workflows/kk-publish.yaml +4 -1
  45. package/plugins/publishings/linkedin-pub/dist/index.js +51 -9
  46. package/plugins/publishings/linkedin-pub/dist/profile-check.js +5 -0
  47. package/plugins/publishings/linkedin-pub/src/index.ts +99 -12
  48. package/plugins/publishings/surfdash-pub/dist/index.js +8 -4
  49. package/plugins/publishings/surfdash-pub/src/index.ts +7 -1
  50. package/plugins/publishings/surfdash-pub/src/patch.ts +21 -3
  51. package/plugins/publishings/threads-pub/dist/index.js +47 -5
  52. package/plugins/publishings/threads-pub/dist/profile-check.js +7 -1
  53. package/plugins/publishings/threads-pub/src/post-rail.ts +101 -4
  54. package/plugins/publishings/wechatmp-pub/dist/index.js +94 -34
  55. package/plugins/publishings/wechatmp-pub/src/cgi-draft.ts +87 -53
  56. package/plugins/publishings/wechatmp-pub/src/enrich.ts +61 -3
  57. package/plugins/publishings/wechatmp-pub/src/flow.ts +28 -0
  58. package/plugins/publishings/x-pub/dist/index.js +84 -9
  59. package/plugins/publishings/x-pub/src/post-rail.ts +154 -12
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gobing-ai/knowledge-kit",
3
- "version": "0.1.22",
3
+ "version": "0.1.23",
4
4
  "description": "An ingest → create → publish content pipeline CLI (Bun).",
5
5
  "repository": {
6
6
  "type": "git",
@@ -12672,6 +12672,19 @@ async function auditVoiceSegments(script, segmentWavs, segmentMetadata, client)
12672
12672
  }
12673
12673
 
12674
12674
  // ../../plugins/generations/voice-gen/src/voicebox-client.ts
12675
+ init_dist();
12676
+ var GPU_BACKENDS = new Set(["gpu", "mps", "metal", "cuda"]);
12677
+ function detectCpuFallback(payload) {
12678
+ if (payload.gpu_available !== true)
12679
+ return;
12680
+ const variant = (payload.backend_variant ?? "").toLowerCase();
12681
+ if (!variant || GPU_BACKENDS.has(variant))
12682
+ return;
12683
+ return payload;
12684
+ }
12685
+ function requireGpu(env) {
12686
+ return ["1", "true", "yes"].includes((env.VOICEBOX_REQUIRE_GPU ?? "").toLowerCase());
12687
+ }
12675
12688
  function resolveVoiceboxTimeoutMs() {
12676
12689
  const raw = process.env.VOICEBOX_TIMEOUT_MS;
12677
12690
  const parsed = raw ? Number.parseInt(raw, 10) : Number.NaN;
@@ -12686,8 +12699,9 @@ function createVoiceboxClient(options = {}) {
12686
12699
  return {
12687
12700
  url,
12688
12701
  async health() {
12702
+ let res;
12689
12703
  try {
12690
- const res = await customFetch(`${url}/health`, { signal: AbortSignal.timeout(requestTimeoutMs) });
12704
+ res = await customFetch(`${url}/health`, { signal: AbortSignal.timeout(requestTimeoutMs) });
12691
12705
  if (!res.ok) {
12692
12706
  throw new Error(`HTTP ${res.status} ${res.statusText}`);
12693
12707
  }
@@ -12695,6 +12709,21 @@ function createVoiceboxClient(options = {}) {
12695
12709
  const reason = err instanceof Error ? err.message : String(err);
12696
12710
  throw new Error(`Voicebox health check failed at ${url}: ${reason} \u2014 is Voicebox.app running with its REST server enabled? (restart the app or fix VOICEBOX_URL)`);
12697
12711
  }
12712
+ let payload;
12713
+ try {
12714
+ payload = await res.json();
12715
+ } catch {
12716
+ payload = undefined;
12717
+ }
12718
+ const fallback = payload && detectCpuFallback(payload);
12719
+ if (fallback) {
12720
+ const detail = `backend_variant: "${fallback.backend_variant}", gpu_available: true, gpu_type: "${fallback.gpu_type ?? "unknown"}"`;
12721
+ const message = `Voicebox at ${url} is rendering on CPU (${detail}) \u2014 expect ~5.6x realtime degradation. Restart Voicebox.app while Metal is free, or set VOICEBOX_REQUIRE_GPU=0 to accept it.`;
12722
+ if (requireGpu(process.env)) {
12723
+ throw new Error(`voice-gen: ${message}`);
12724
+ }
12725
+ echoError(`voice-gen: warning: ${message}`);
12726
+ }
12698
12727
  },
12699
12728
  async resolveProfile(nameOrId) {
12700
12729
  let res;
@@ -13514,6 +13543,7 @@ var DEFAULT_BASE_URL = "https://generativelanguage.googleapis.com";
13514
13543
  var DEFAULT_PROFILES_PATH = new URL("../profiles.json", import.meta.url).pathname;
13515
13544
  var TRANSCRIBE_PROMPT = "Transcribe this audio verbatim. Output only the transcript, no commentary.";
13516
13545
  var RETRY_AFTER_CAP_SEC = 120;
13546
+ var TERMINAL_STATUSES = new Set([400, 401, 402, 403, 404]);
13517
13547
  var PLACEHOLDER_VOICE = "voice_REPLACE_ME";
13518
13548
  function findOutput(json, type) {
13519
13549
  for (const step of json.steps ?? []) {
@@ -13548,29 +13578,36 @@ function createGeminiVoiceClient(options = {}) {
13548
13578
  const styleOverride = env.GEMINI_TTS_STYLE;
13549
13579
  const maxAttempts = positiveInt(env.GEMINI_TTS_MAX_ATTEMPTS, 4);
13550
13580
  const timeoutMs = positiveInt(env.GEMINI_TTS_TIMEOUT_MS, 120000);
13581
+ const segmentTimeoutMs = positiveInt(env.GEMINI_TTS_SEGMENT_TIMEOUT_MS, 180000);
13551
13582
  const buffered = new Map;
13552
13583
  let profiles;
13553
13584
  let seq = 0;
13554
13585
  async function post(body, label) {
13555
13586
  const apiKey = env.GEMINI_API_KEY ?? "";
13587
+ const deadline = Date.now() + segmentTimeoutMs;
13556
13588
  for (let attempt = 1;; attempt++) {
13589
+ const remaining = deadline - Date.now();
13590
+ if (remaining <= 0) {
13591
+ throw new Error(`${label}: segment budget ${segmentTimeoutMs}ms exhausted after ${attempt - 1} attempt(s)`);
13592
+ }
13593
+ const attemptMs = Math.min(timeoutMs, remaining);
13557
13594
  let res;
13558
13595
  try {
13559
13596
  res = await withDeadline(doFetch(`${baseUrl}/v1beta/interactions`, {
13560
13597
  method: "POST",
13561
13598
  headers: { "content-type": "application/json", "x-goog-api-key": apiKey },
13562
13599
  body: JSON.stringify(body),
13563
- signal: AbortSignal.timeout(timeoutMs)
13564
- }), timeoutMs);
13600
+ signal: AbortSignal.timeout(attemptMs)
13601
+ }), attemptMs);
13565
13602
  } catch (err) {
13566
13603
  const msg = err instanceof Error ? err.message : String(err);
13567
- if (attempt >= maxAttempts)
13568
- throw new Error(`${label}: request failed after ${attempt} attempts: ${msg}`);
13569
- await sleep(2000 * 2 ** (attempt - 1));
13604
+ if (attempt >= maxAttempts || Date.now() >= deadline)
13605
+ throw new Error(`${label}: request failed after ${attempt} attempt(s) within ${segmentTimeoutMs}ms: ${msg}`);
13606
+ await sleep(Math.min(2000 * 2 ** (attempt - 1), Math.max(0, deadline - Date.now())));
13570
13607
  continue;
13571
13608
  }
13572
13609
  if (res.ok)
13573
- return withDeadline(res.json(), timeoutMs);
13610
+ return withDeadline(res.json(), Math.min(timeoutMs, Math.max(1, deadline - Date.now())));
13574
13611
  const raw = await withDeadline(res.text(), timeoutMs);
13575
13612
  let apiMessage = raw.slice(0, 300);
13576
13613
  try {
@@ -13580,6 +13617,9 @@ function createGeminiVoiceClient(options = {}) {
13580
13617
  if (retryAfter > RETRY_AFTER_CAP_SEC) {
13581
13618
  throw new Error(`${label}: HTTP ${res.status} quota/reset horizon too far out (retry-after ${retryAfter}s \u2248 ${(retryAfter / 3600).toFixed(1)}h): ${apiMessage}`);
13582
13619
  }
13620
+ if (TERMINAL_STATUSES.has(res.status)) {
13621
+ throw new Error(`${label}: HTTP ${res.status} is not retryable (auth/billing/request class) \u2014 failing fast instead of burning the segment budget: ${apiMessage}`);
13622
+ }
13583
13623
  const retryable = res.status === 429 || res.status >= 500;
13584
13624
  if (!retryable || attempt >= maxAttempts) {
13585
13625
  throw new Error(`${label}: HTTP ${res.status} after ${attempt} attempt(s): ${apiMessage}`);
@@ -8,6 +8,12 @@ const DEFAULT_PROFILES_PATH = new URL('../profiles.json', import.meta.url).pathn
8
8
  const TRANSCRIBE_PROMPT = 'Transcribe this audio verbatim. Output only the transcript, no commentary.';
9
9
  /** retry-after above this (Google daily-quota 429s: ~70_000s) is never actionable inside a run. */
10
10
  const RETRY_AFTER_CAP_SEC = 120;
11
+ /**
12
+ * 4xx that retrying can never fix: auth, billing (2026-11-20: a depleted project answered 402 on
13
+ * every call) and malformed requests. Retried, they burn the whole per-segment budget for a
14
+ * certain failure, which is how one episode spent 23 minutes failing over.
15
+ */
16
+ const TERMINAL_STATUSES = new Set([400, 401, 402, 403, 404]);
11
17
  const PLACEHOLDER_VOICE = 'voice_REPLACE_ME';
12
18
 
13
19
  type Env = Record<string, string | undefined>;
@@ -78,13 +84,24 @@ export function createGeminiVoiceClient(options: GeminiVoiceClientOptions = {}):
78
84
  const styleOverride = env.GEMINI_TTS_STYLE;
79
85
  const maxAttempts = positiveInt(env.GEMINI_TTS_MAX_ATTEMPTS, 4);
80
86
  const timeoutMs = positiveInt(env.GEMINI_TTS_TIMEOUT_MS, 120_000);
87
+ // Wall-clock ceiling for ONE segment across every attempt and backoff, so a stalled endpoint
88
+ // cannot multiply the per-request timeout by the attempt count (R1).
89
+ const segmentTimeoutMs = positiveInt(env.GEMINI_TTS_SEGMENT_TIMEOUT_MS, 180_000);
81
90
  const buffered = new Map<string, Uint8Array>();
82
91
  let profiles: Record<string, { voice?: string }> | undefined;
83
92
  let seq = 0;
84
93
 
85
94
  async function post(body: unknown, label: string): Promise<InteractionResponse> {
86
95
  const apiKey = env.GEMINI_API_KEY ?? '';
96
+ const deadline = Date.now() + segmentTimeoutMs;
87
97
  for (let attempt = 1; ; attempt++) {
98
+ const remaining = deadline - Date.now();
99
+ if (remaining <= 0) {
100
+ throw new Error(
101
+ `${label}: segment budget ${segmentTimeoutMs}ms exhausted after ${attempt - 1} attempt(s)`,
102
+ );
103
+ }
104
+ const attemptMs = Math.min(timeoutMs, remaining);
88
105
  let res: Response;
89
106
  try {
90
107
  res = await withDeadline(
@@ -92,18 +109,24 @@ export function createGeminiVoiceClient(options: GeminiVoiceClientOptions = {}):
92
109
  method: 'POST',
93
110
  headers: { 'content-type': 'application/json', 'x-goog-api-key': apiKey },
94
111
  body: JSON.stringify(body),
95
- signal: AbortSignal.timeout(timeoutMs),
112
+ signal: AbortSignal.timeout(attemptMs),
96
113
  }),
97
- timeoutMs,
114
+ attemptMs,
98
115
  );
99
116
  } catch (err: unknown) {
100
117
  const msg = err instanceof Error ? err.message : String(err);
101
- if (attempt >= maxAttempts)
102
- throw new Error(`${label}: request failed after ${attempt} attempts: ${msg}`);
103
- await sleep(2000 * 2 ** (attempt - 1));
118
+ if (attempt >= maxAttempts || Date.now() >= deadline)
119
+ throw new Error(
120
+ `${label}: request failed after ${attempt} attempt(s) within ${segmentTimeoutMs}ms: ${msg}`,
121
+ );
122
+ await sleep(Math.min(2000 * 2 ** (attempt - 1), Math.max(0, deadline - Date.now())));
104
123
  continue;
105
124
  }
106
- if (res.ok) return withDeadline(res.json(), timeoutMs) as Promise<InteractionResponse>;
125
+ if (res.ok)
126
+ return withDeadline(
127
+ res.json(),
128
+ Math.min(timeoutMs, Math.max(1, deadline - Date.now())),
129
+ ) as Promise<InteractionResponse>;
107
130
  const raw = await withDeadline(res.text(), timeoutMs);
108
131
  let apiMessage = raw.slice(0, 300);
109
132
  try {
@@ -120,6 +143,11 @@ export function createGeminiVoiceClient(options: GeminiVoiceClientOptions = {}):
120
143
  `${label}: HTTP ${res.status} quota/reset horizon too far out (retry-after ${retryAfter}s ≈ ${(retryAfter / 3600).toFixed(1)}h): ${apiMessage}`,
121
144
  );
122
145
  }
146
+ if (TERMINAL_STATUSES.has(res.status)) {
147
+ throw new Error(
148
+ `${label}: HTTP ${res.status} is not retryable (auth/billing/request class) — failing fast instead of burning the segment budget: ${apiMessage}`,
149
+ );
150
+ }
123
151
  const retryable = res.status === 429 || res.status >= 500;
124
152
  if (!retryable || attempt >= maxAttempts) {
125
153
  throw new Error(`${label}: HTTP ${res.status} after ${attempt} attempt(s): ${apiMessage}`);
@@ -124,7 +124,7 @@ timestamped section skeleton. `lyrics` is the format’s policy: `forbidden` res
124
124
  | `clip` | `clip` | — (clip is fixed at ~0:30) | allowed | Quick preview, a direction check before a pro run, or a short social cut. | `authored` |
125
125
  | `jingle` | `pro` | `0:20` | allowed | Product or station ident — the hook states the name once and resolves fast. | `authored` |
126
126
  | `loop` | `clip` | — (clip is fixed at ~0:30) | forbidden | Background bed for a talk-through, demo or menu loop; no vocals by design. | `authored` |
127
- | `song` | `pro` | `2:30` | allowed | A complete track with a sung hook; the default for lyrical pieces. | `authored` |
127
+ | `song` | `pro` | `2:30` | allowed | A complete track with a sung hook; the default for lyrical pieces. | `verified` |
128
128
  | `underscore` | `pro` | `0:45` | forbidden | Underscore under spoken narration or a video essay; no hook or vocal required. | `authored` |
129
129
 
130
130
  ### Themes
@@ -137,7 +137,7 @@ vocal character and production — plus its default `avoid[]`, rendered as one `
137
137
  | `ambient-tech` | glassy ambient techno; 100-115 BPM, steady and unaccented; C# minor | hard drops, talkbox vocals, pop hooks, vocal chops | Product walkthroughs, conference holds, editorial beds that must stay out of the way. | `authored` |
138
138
  | `cinematic` | cinematic orchestral hybrid score; 60-90 BPM with rubato swells; D minor | horror stingers, orchestral hits on every downbeat, distorted electric guitar, pop chorus stacks | Trailer-style openings, story intros, a track that must feel like a scene. | `authored` |
139
139
  | `lofi` | dusty sampled lo-fi hip-hop; 70-85 BPM, swung and unhurried; A minor | trap hi-hat rolls, hard drops, EDM riser clichés, over-compressed loudness | Study/focus background, calm narration bed, unhurried social cuts. | `authored` |
140
- | `synthwave` | analog synthwave revival; 90-110 BPM, straight four-on-the-floor; A minor | festival supersaws, EDM risers, distorted djent guitars, modern trap percussion | Retro-tech explainers, night-drive montages, upbeat product stings. | `authored` |
140
+ | `synthwave` | analog synthwave revival; 90-110 BPM, straight four-on-the-floor; A minor | festival supersaws, EDM risers, distorted djent guitars, modern trap percussion | Retro-tech explainers, night-drive montages, upbeat product stings. | `verified` |
141
141
  <!-- preset-index:end -->
142
142
 
143
143
  Evidence status: `authored` means written from the design contract with no generated take judged
@@ -232,14 +232,15 @@ class InstanceClient {
232
232
  }
233
233
  async attempt(method, path, body) {
234
234
  const controller = new AbortController;
235
- let phase = "connect";
235
+ const enforceConnectTimer = method === "GET";
236
+ let phase = enforceConnectTimer ? "connect" : "body";
236
237
  let abortReason;
237
- const connectTimer = setTimeout(() => {
238
+ const connectTimer = enforceConnectTimer ? setTimeout(() => {
238
239
  if (phase === "connect" && abortReason === undefined) {
239
240
  abortReason = "connect-timeout";
240
241
  controller.abort();
241
242
  }
242
- }, this.connectTimeoutMs);
243
+ }, this.connectTimeoutMs) : undefined;
243
244
  const totalTimer = setTimeout(() => {
244
245
  if (abortReason === undefined) {
245
246
  abortReason = "generate-timeout";
@@ -258,7 +259,9 @@ class InstanceClient {
258
259
  };
259
260
  const response = await this.fetchImpl(this.url(path), init);
260
261
  phase = "body";
261
- clearTimeout(connectTimer);
262
+ if (connectTimer !== undefined) {
263
+ clearTimeout(connectTimer);
264
+ }
262
265
  const bytes = new Uint8Array(await response.arrayBuffer());
263
266
  const contentType = response.headers.get("content-type") ?? undefined;
264
267
  return {
@@ -291,7 +294,9 @@ class InstanceClient {
291
294
  }
292
295
  return { kind: "ambiguous", reason };
293
296
  } finally {
294
- clearTimeout(connectTimer);
297
+ if (connectTimer !== undefined) {
298
+ clearTimeout(connectTimer);
299
+ }
295
300
  clearTimeout(totalTimer);
296
301
  }
297
302
  }
@@ -326,6 +331,17 @@ class InstanceClient {
326
331
  let lastReason = "";
327
332
  for (;; ) {
328
333
  attempts += 1;
334
+ if (method === "POST") {
335
+ const probe = await this.attempt("GET", STATUS_PATH, undefined);
336
+ if (probe.kind === "connect") {
337
+ lastReason = probe.reason;
338
+ if (attempts >= maxAttempts) {
339
+ return { kind: "connect-exhausted", reason: lastReason, attempts };
340
+ }
341
+ await this.sleep(this.retryDelayMs * 2 ** (attempts - 1));
342
+ continue;
343
+ }
344
+ }
329
345
  const outcome = await this.attempt(method, path, body);
330
346
  if (outcome.kind === "response") {
331
347
  return this.classify(outcome.response, attempts);
@@ -635,7 +651,7 @@ class InstanceClient {
635
651
  function createInstanceClient(options = {}) {
636
652
  return new InstanceClient(options);
637
653
  }
638
- var GENERATE_PATH = "/api/lyria/generate", LIBRARY_PATH = "/api/generations", ANALYZE_PATH = "/api/ai/analyze", DEFAULT_CONNECT_ATTEMPTS = 3, DEFAULT_RETRY_DELAY_MS = 250, TERMINAL_STATUSES, STATUS_REMEDIATION, CONNECT_ERROR_CODES, AMBIGUOUS_ERROR_CODES, ALL_KEYS_REJECTED_PATTERN, InstanceError, platformFetch;
654
+ var GENERATE_PATH = "/api/lyria/generate", LIBRARY_PATH = "/api/generations", STATUS_PATH = "/api/settings/status", ANALYZE_PATH = "/api/ai/analyze", DEFAULT_CONNECT_ATTEMPTS = 3, DEFAULT_RETRY_DELAY_MS = 250, TERMINAL_STATUSES, STATUS_REMEDIATION, CONNECT_ERROR_CODES, AMBIGUOUS_ERROR_CODES, ALL_KEYS_REJECTED_PATTERN, InstanceError, platformFetch;
639
655
  var init_instance = __esm(() => {
640
656
  init_audio();
641
657
  TERMINAL_STATUSES = new Set([400, 401, 402, 403, 404, 429]);
@@ -21322,7 +21338,7 @@ function buildMusicContent(input) {
21322
21338
  var MUSIC_CONTENT_FORMAT = "audio";
21323
21339
 
21324
21340
  // ../../plugins/generations/music-gen/src/presets.ts
21325
- import { join as join3 } from "path";
21341
+ import { join as join3, resolve as resolve2 } from "path";
21326
21342
  function describeSource(sourced) {
21327
21343
  return sourced.origin === undefined ? sourced.source : `${sourced.source} preset "${sourced.origin}"`;
21328
21344
  }
@@ -21550,6 +21566,25 @@ function themeDirectionGaps(theme) {
21550
21566
  require2("production", theme.production);
21551
21567
  return gaps;
21552
21568
  }
21569
+ function musicPresetRootCandidates(from = import.meta.dir) {
21570
+ const candidates = [];
21571
+ let dir = resolve2(from);
21572
+ for (;; ) {
21573
+ candidates.push(join3(dir, "..", "presets"));
21574
+ candidates.push(join3(dir, "plugins", "generations", "music-gen", "presets"));
21575
+ const parent = resolve2(dir, "..");
21576
+ if (parent === dir)
21577
+ return candidates;
21578
+ dir = parent;
21579
+ }
21580
+ }
21581
+ async function resolveMusicPresetRoot(fs, from) {
21582
+ for (const candidate of musicPresetRootCandidates(from)) {
21583
+ if (await fs.exists(candidate))
21584
+ return candidate;
21585
+ }
21586
+ return MUSIC_PRESET_ROOT;
21587
+ }
21553
21588
  async function readPresetFiles(dir, axis, fs, problems) {
21554
21589
  if (!await fs.exists(dir)) {
21555
21590
  problems.push({ path: dir, field: axis, message: "preset directory is missing" });
@@ -21626,8 +21661,8 @@ function collectPresets(args) {
21626
21661
  return byName;
21627
21662
  }
21628
21663
  async function loadMusicPresets(options = {}) {
21629
- const root = options.root ?? MUSIC_PRESET_ROOT;
21630
21664
  const fs = options.fileSystem ?? createNodeFileSystem();
21665
+ const root = options.root ?? await resolveMusicPresetRoot(fs);
21631
21666
  const problems = [];
21632
21667
  const formatFiles = await readPresetFiles(join3(root, "formats"), "formats", fs, problems);
21633
21668
  const themeFiles = await readPresetFiles(join3(root, "themes"), "themes", fs, problems);
@@ -22313,7 +22348,7 @@ var init_request = __esm(() => {
22313
22348
  });
22314
22349
 
22315
22350
  // ../../plugins/generations/music-gen/src/plugin.ts
22316
- import { dirname as dirname2, join as join4, resolve as resolve2 } from "path";
22351
+ import { dirname as dirname2, join as join4, resolve as resolve3 } from "path";
22317
22352
  import { parseArgs } from "util";
22318
22353
  async function readMusicDocs(fileSystem, inputPath) {
22319
22354
  let docs;
@@ -22516,7 +22551,7 @@ async function main2(argv = process.argv.slice(2)) {
22516
22551
  ...values.reason === undefined ? {} : { reason: values.reason },
22517
22552
  ...values.takes === undefined ? {} : { takes: parseTakesFlag(values.takes) }
22518
22553
  };
22519
- await processGeneratorIO(values.in, resolve2(values.out), { spend });
22554
+ await processGeneratorIO(values.in, resolve3(values.out), { spend });
22520
22555
  return 0;
22521
22556
  } catch (err) {
22522
22557
  echoError(`music-gen failed: ${err instanceof Error ? err.message : String(err)}`);
@@ -23437,6 +23472,7 @@ export {
23437
23472
  SILENCE_EDGE_TOLERANCE_SECONDS,
23438
23473
  SILENT_WAV_SAMPLE_RATE,
23439
23474
  SILENT_WAV_SECONDS,
23475
+ STATUS_PATH,
23440
23476
  SpendRefusal,
23441
23477
  StructureEntrySchema,
23442
23478
  TAKE_SIDECAR_SUFFIX,
@@ -28,4 +28,9 @@ structure:
28
28
  provenance:
29
29
  authoring_source: task 0399 (feature D8) — docs/design/music-gen.md section 5 and the plugin README authoring form
30
30
  authored_at: "2026-11-19"
31
- status: authored
31
+ status: verified
32
+ evidence: >-
33
+ verified 2026-11-20 by 0404's dogfood round — generation gen-1795196931030-puqx6j (pro,
34
+ 149.13 s, D minor) rendered from .works/kk-music/morning-chamber-orchids, accepted by the
35
+ operator; run report c73a9b02: judge PASS 0.825 (MEDIUM), delivery -14.01 LUFS / -1 dBTP at
36
+ the streaming profile. Evidence: docs/tasks/evidence/D8/0404/accepted/.
@@ -27,4 +27,9 @@ avoid:
27
27
  provenance:
28
28
  authoring_source: task 0399 (feature D8) — docs/design/music-gen.md section 5 and the plugin README authoring form
29
29
  authored_at: "2026-11-19"
30
- status: authored
30
+ status: verified
31
+ evidence: >-
32
+ verified 2026-11-20 by 0404's dogfood round — generation gen-1795196931030-puqx6j (pro,
33
+ 149.13 s, D minor) rendered from .works/kk-music/morning-chamber-orchids, accepted by the
34
+ operator; run report c73a9b02: judge PASS 0.825 (MEDIUM), delivery -14.01 LUFS / -1 dBTP at
35
+ the streaming profile. Evidence: docs/tasks/evidence/D8/0404/accepted/.
@@ -38,6 +38,9 @@ export const GENERATE_PATH = '/api/lyria/generate';
38
38
  /** Library route (free): the reconciliation + cache-first analyse source. */
39
39
  export const LIBRARY_PATH = '/api/generations';
40
40
 
41
+ /** Cheap reachability probe route (free): decided under `connectTimeoutMs` before paid POSTs. */
42
+ export const STATUS_PATH = '/api/settings/status';
43
+
41
44
  /** Analyse route (paid). */
42
45
  export const ANALYZE_PATH = '/api/ai/analyze';
43
46
 
@@ -383,17 +386,22 @@ export class InstanceClient implements MusicInstance {
383
386
  return new URL(`${LIBRARY_PATH}/${encodeURIComponent(instanceId)}`, `${this.baseUrl}/`).toString();
384
387
  }
385
388
 
386
- /** One round trip with a connect-phase deadline and an end-to-end deadline. */
389
+ /** One round trip with an optional connect-phase deadline (GET only) and an end-to-end deadline. */
387
390
  private async attempt(method: 'GET' | 'POST', path: string, body: unknown): Promise<AttemptOutcome> {
388
391
  const controller = new AbortController();
389
- let phase: 'connect' | 'body' = 'connect';
392
+ // Paid POSTs are synchronous on the instance (headers arrive only after generation completes),
393
+ // so only GETs (including the pre-POST reachability probe) carry the connect-phase timer.
394
+ const enforceConnectTimer = method === 'GET';
395
+ let phase: 'connect' | 'body' = enforceConnectTimer ? 'connect' : 'body';
390
396
  let abortReason: 'connect-timeout' | 'generate-timeout' | undefined;
391
- const connectTimer = setTimeout(() => {
392
- if (phase === 'connect' && abortReason === undefined) {
393
- abortReason = 'connect-timeout';
394
- controller.abort();
395
- }
396
- }, this.connectTimeoutMs);
397
+ const connectTimer = enforceConnectTimer
398
+ ? setTimeout(() => {
399
+ if (phase === 'connect' && abortReason === undefined) {
400
+ abortReason = 'connect-timeout';
401
+ controller.abort();
402
+ }
403
+ }, this.connectTimeoutMs)
404
+ : undefined;
397
405
  const totalTimer = setTimeout(() => {
398
406
  if (abortReason === undefined) {
399
407
  abortReason = 'generate-timeout';
@@ -413,7 +421,9 @@ export class InstanceClient implements MusicInstance {
413
421
  const response = await this.fetchImpl(this.url(path), init);
414
422
  // Headers arrived: the request reached the instance, so a later abort is post-send.
415
423
  phase = 'body';
416
- clearTimeout(connectTimer);
424
+ if (connectTimer !== undefined) {
425
+ clearTimeout(connectTimer);
426
+ }
417
427
  const bytes = new Uint8Array(await response.arrayBuffer());
418
428
  const contentType = response.headers.get('content-type') ?? undefined;
419
429
  return {
@@ -448,7 +458,9 @@ export class InstanceClient implements MusicInstance {
448
458
  // Anything unrecognised may have reached the instance: ambiguous, never retried.
449
459
  return { kind: 'ambiguous', reason };
450
460
  } finally {
451
- clearTimeout(connectTimer);
461
+ if (connectTimer !== undefined) {
462
+ clearTimeout(connectTimer);
463
+ }
452
464
  clearTimeout(totalTimer);
453
465
  }
454
466
  }
@@ -481,13 +493,24 @@ export class InstanceClient implements MusicInstance {
481
493
  return { kind: 'ambiguous', reason: `answered an unexpected ${String(status)}`, status, attempts };
482
494
  }
483
495
 
484
- /** Send one request, retrying connect-phase failures only, and classify the result. */
496
+ /** Send one request, probing reachability before paid POSTs, and classify the result. */
485
497
  private async send(method: 'GET' | 'POST', path: string, body: unknown): Promise<SendOutcome> {
486
498
  const maxAttempts = method === 'POST' ? this.connectAttempts : 1;
487
499
  let attempts = 0;
488
500
  let lastReason = '';
489
501
  for (;;) {
490
502
  attempts += 1;
503
+ if (method === 'POST') {
504
+ const probe = await this.attempt('GET', STATUS_PATH, undefined);
505
+ if (probe.kind === 'connect') {
506
+ lastReason = probe.reason;
507
+ if (attempts >= maxAttempts) {
508
+ return { kind: 'connect-exhausted', reason: lastReason, attempts };
509
+ }
510
+ await this.sleep(this.retryDelayMs * 2 ** (attempts - 1));
511
+ continue;
512
+ }
513
+ }
491
514
  const outcome = await this.attempt(method, path, body);
492
515
  if (outcome.kind === 'response') {
493
516
  return this.classify(outcome.response, attempts);
@@ -1,4 +1,4 @@
1
- import { join } from 'node:path';
1
+ import { join, resolve } from 'node:path';
2
2
  import { createNodeFileSystem, type FileSystem } from '@gobing-ai/ts-runtime';
3
3
  import { z } from 'zod';
4
4
  import {
@@ -669,9 +669,42 @@ export class PresetDataError extends Error {
669
669
  }
670
670
  }
671
671
 
672
- /** Shipped preset root: `plugins/generations/music-gen/presets`. */
672
+ /**
673
+ * Shipped preset root for the source layout: `plugins/generations/music-gen/presets`.
674
+ *
675
+ * A bundled `kk` puts this module inside `<pkg>/dist/index.js`, where the sibling directory does not
676
+ * exist — the packaged copy lives at `<pkg>/plugins/generations/music-gen/presets` instead (0413).
677
+ * {@link resolveMusicPresetRoot} picks the first candidate that exists; this constant stays the
678
+ * source-layout path and the last-resort value, so a genuinely missing corpus still fails with a
679
+ * recognisable path.
680
+ */
673
681
  export const MUSIC_PRESET_ROOT = join(import.meta.dir, '..', 'presets');
674
682
 
683
+ /**
684
+ * Preset-root candidates for one anchor directory, nearest first: the plugin-local sibling layout
685
+ * (source and any unpacked plugin dir), then the package-root layout a bundle needs, checked at
686
+ * every ancestor because a bundle's `import.meta.dir` is `<pkg>/dist`.
687
+ */
688
+ export function musicPresetRootCandidates(from: string = import.meta.dir): string[] {
689
+ const candidates: string[] = [];
690
+ let dir = resolve(from);
691
+ for (;;) {
692
+ candidates.push(join(dir, '..', 'presets'));
693
+ candidates.push(join(dir, 'plugins', 'generations', 'music-gen', 'presets'));
694
+ const parent = resolve(dir, '..');
695
+ if (parent === dir) return candidates;
696
+ dir = parent;
697
+ }
698
+ }
699
+
700
+ /** The first candidate that exists, else the source-layout path (so the failure names a real shape). */
701
+ export async function resolveMusicPresetRoot(fs: FileSystem, from?: string): Promise<string> {
702
+ for (const candidate of musicPresetRootCandidates(from)) {
703
+ if (await fs.exists(candidate)) return candidate;
704
+ }
705
+ return MUSIC_PRESET_ROOT;
706
+ }
707
+
675
708
  /** The shipped inventory: one map per axis, keyed by preset name. */
676
709
  export interface LoadedMusicPresets {
677
710
  /** Root the two axes were read from. */
@@ -792,8 +825,8 @@ function collectPresets<T extends { name: string }>(args: {
792
825
  * {@link PresetDataError} with every problem listed — no partial set escapes.
793
826
  */
794
827
  export async function loadMusicPresets(options: LoadMusicPresetsOptions = {}): Promise<LoadedMusicPresets> {
795
- const root = options.root ?? MUSIC_PRESET_ROOT;
796
828
  const fs = options.fileSystem ?? createNodeFileSystem();
829
+ const root = options.root ?? (await resolveMusicPresetRoot(fs));
797
830
  const problems: MusicPresetProblem[] = [];
798
831
  const formatFiles = await readPresetFiles(join(root, 'formats'), 'formats', fs, problems);
799
832
  const themeFiles = await readPresetFiles(join(root, 'themes'), 'themes', fs, problems);
@@ -0,0 +1,5 @@
1
+ # Hardlink wheels from the shared uv cache instead of copying them. Measured 2026-11-20: this
2
+ # env and voxcpm-tts's held 2.45 GiB with zero hardlinked bytes, so torch/scipy/llvmlite
3
+ # were stored twice on top of ~/.cache/uv/archive-v0. Hardlinks need both paths on one
4
+ # filesystem; override with UV_LINK_MODE=copy if the cache ever moves to another device.
5
+ link-mode = "hardlink"
@@ -0,0 +1,64 @@
1
+ # vibe-voice-tts
2
+
3
+ Standalone Microsoft VibeVoice generator plugin for [knowledge-kit](../../../README.md). A
4
+ TypeScript generator that reuses **voice-gen's** pipeline (VoiceScript parsing, gaps, speed, WAV
5
+ concatenation, QC, optional MP3) behind the existing `VoiceboxClient` contract, backed by a
6
+ private **uv-managed Python worker** that runs PyPI `vibevoice==0.0.1` (ADR-055). Existing daily
7
+ defaults are unchanged: opt in with `vdriver: vibe-voice` / `vdriver: vibevoice` or
8
+ `kk news generate-voice --engine vibe-voice`.
9
+
10
+ `vendors/VibeVoice` is reference-only. No import, subprocess, dependency, cache, profile or model
11
+ path in this plugin may resolve into `vendors/` — every configured path is canonicalized and
12
+ refused, including symlinks and the Hugging Face / uv cache tiers.
13
+
14
+ ## Requirements
15
+
16
+ - `uv` on `PATH` (the worker is spawned as `uv run --project <plugin-root> --locked --no-dev`).
17
+ - Python 3.12 (`requires-python = "==3.12.*"`).
18
+ - `ffmpeg`/`ffprobe` only when `VOICE_GEN_MP3` requests an MP3 sibling.
19
+
20
+ ## Layout
21
+
22
+ | Path | Purpose |
23
+ | --- | --- |
24
+ | `plugin.json` | `kk` manifest (`kind: generator`, entry `./src/index.ts` → bundled `./dist/index.js`) |
25
+ | `src/index.ts` | `main(--in/--out` \| `--batch`) entry; injects adapter into `processGeneratorIO` and closes in `finally` |
26
+ | `src/vibevoice-client.ts` | registry/control/vendor-path validation + bounded NDJSON worker adapter (`kk:vibe-voice-tts`) |
27
+ | `python/worker.py` | private NDJSON worker: fd-1 isolation, `health`/`render`, one model load per invocation |
28
+ | `pyproject.toml` / `uv.lock` | independent uv project pinning `vibevoice==0.0.1` on Python 3.12 |
29
+ | `profiles.json` | frozen profile registry (`profiles` array; `robin-news` instruct placeholder) |
30
+
31
+ ## Setup
32
+
33
+ ```bash
34
+ uv lock --project plugins/generations/vibe-voice-tts
35
+ uv run --project plugins/generations/vibe-voice-tts --locked --no-dev python plugins/generations/vibe-voice-tts/python/worker.py
36
+ ```
37
+
38
+ ## Configuration (environment)
39
+
40
+ | Var | Default | Notes |
41
+ | --- | --- | --- |
42
+ | `VIBEVOICE_MODEL` | `microsoft/VibeVoice-1.5B` | Hub id or local snapshot directory (checked against vendor exclusion) |
43
+ | `VIBEVOICE_DEVICE` | `auto` | `auto`/`cpu`/`cuda`/`mps`; unavailable **requested** device fails without CPU fallback |
44
+ | `VIBEVOICE_PROFILES_PATH` | `<plugin-root>/profiles.json` | Profile registry (`reference`, `cached_prompt`, or single-segment `instruct`) |
45
+ | `VIBEVOICE_BATCH_MANIFEST` | unset | Path to JSON array of `{ in, out }` pairs for single-worker batch rendering |
46
+ | `VOICEBOX_TIMEOUT_MS` | `600000` | Worker startup and base per-segment render deadline in ms |
47
+ | `VOICE_GEN_MAX_RUN_MS` | unset | Positive value bounds the whole invocation (startup + every render) |
48
+ | `VOICE_GEN_MP3` | off | Request an MP3 sibling via ffmpeg |
49
+ | `VOICE_GEN_FAIL_ON_QC` | off | Fail generation when the QC audit fails |
50
+
51
+ ## Profiles
52
+
53
+ - `reference`: needs `reference_wav_path` (optional `cfg_scale`, default `1.5`; optional `ddpm_steps`, default `10`). Uses `VibeVoiceProcessor` + `VibeVoiceForConditionalGenerationInference` with `Speaker 1: <text>`.
54
+ - `cached_prompt`: needs `prompt_pt_path` (optional `cfg_scale`, default `1.5`; optional `ddpm_steps`, default `5`). Loaded with `torch.load(..., weights_only=True)` under `safe_globals([BaseModelOutputWithPast, DynamicCache])` against a streaming checkpoint + streaming processor.
55
+ - `instruct`: shipped placeholder for `robin-news`; carries no speaker reference, so multi-segment renders fail on segment > 1 to guarantee speaker consistency. Configure `VIBEVOICE_PROFILES_PATH` with a `reference` profile (e.g., `~/.config/kk/voices/robin-news.wav`) for episodes.
56
+ - Relative asset paths resolve against the registry directory; duplicate ids/names, mixed mode fields, serialized OmniVoice prompts, and `vendors/` paths are refused.
57
+
58
+ #### API/library claim sources and confidence
59
+
60
+ | Claim | Source | Local verification | Confidence |
61
+ | --- | --- | --- | --- |
62
+ | PyPI `vibevoice==0.0.1` (`vibevoice-0.0.1-py3-none-any.whl`) ships `vibevoice.modular.modeling_vibevoice_inference.VibeVoiceForConditionalGenerationInference` and `vibevoice.processor.vibevoice_processor.VibeVoiceProcessor`, while streaming inference modules are absent from the `0.0.1` wheel | https://pypi.org/pypi/vibevoice/0.0.1/json | Verified wheel SHA256 `fe42a8ee9adcd4fa87b2abd72be502f635bb847387e682b672022d7a9d606add` entries and `python/worker.py` `load_backend` | HIGH |
63
+ | `VibeVoiceProcessor` parses `Speaker <id>: <text>` scripts and accepts `voice_samples=[[reference_wav_path]]`, and `VibeVoiceForConditionalGenerationInference.generate` accepts `cfg_scale`, `tokenizer`, `generation_config`, and `set_ddpm_inference_steps` | `vibevoice==0.0.1` `demo/inference_from_file.py` and `vibevoice/processor/vibevoice_processor.py` | Inspected wheel contents (`demo/inference_from_file.py:319-351`, `vibevoice_processor.py:246-304`) and `python/worker.py` | HIGH |
64
+ | `VIBEVOICE_MODEL` defaults to `microsoft/VibeVoice-1.5B` and output audio writes 16-bit mono PCM WAV at `processor.audio_processor.sampling_rate` (default `24000`) | `plugins/generations/vibe-voice-tts/src/vibevoice-client.ts` & `python/worker.py` | Inspected `VIBEVOICE_DEFAULT_MODEL` in `src/vibevoice-client.ts` and `write_pcm16_wav` in `python/worker.py` | HIGH |