@gobing-ai/knowledge-kit 0.1.20 → 0.1.23

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (149) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/dist/board/collect/index.js +1 -0
  3. package/dist/board/daily-voice/index.js +1279 -261
  4. package/dist/board/itc/index.js +1 -0
  5. package/dist/index.js +13938 -8966
  6. package/package.json +1 -1
  7. package/plugins/generations/dailynews-gen/dist/index.js +285 -16
  8. package/plugins/generations/dailynews-gen/src/editorial-claims.ts +215 -0
  9. package/plugins/generations/dailynews-gen/src/index.ts +23 -4
  10. package/plugins/generations/dailynews-gen/src/script-builder.ts +10 -3
  11. package/plugins/generations/dailynews-gen/src/script-plan.ts +74 -14
  12. package/plugins/generations/gemini-tts/dist/index.js +47 -7
  13. package/plugins/generations/gemini-tts/src/gemini-client.ts +34 -6
  14. package/plugins/generations/music-gen/README.md +277 -0
  15. package/plugins/generations/music-gen/dist/index.js +23580 -0
  16. package/plugins/generations/music-gen/package.json +24 -0
  17. package/plugins/generations/music-gen/plugin.json +23 -0
  18. package/plugins/generations/music-gen/presets/SOURCE.md +39 -0
  19. package/plugins/generations/music-gen/presets/formats/clip.yaml +21 -0
  20. package/plugins/generations/music-gen/presets/formats/jingle.yaml +22 -0
  21. package/plugins/generations/music-gen/presets/formats/loop.yaml +21 -0
  22. package/plugins/generations/music-gen/presets/formats/song.yaml +36 -0
  23. package/plugins/generations/music-gen/presets/formats/underscore.yaml +22 -0
  24. package/plugins/generations/music-gen/presets/themes/ambient-tech.yaml +30 -0
  25. package/plugins/generations/music-gen/presets/themes/cinematic.yaml +30 -0
  26. package/plugins/generations/music-gen/presets/themes/lofi.yaml +30 -0
  27. package/plugins/generations/music-gen/presets/themes/synthwave.yaml +35 -0
  28. package/plugins/generations/music-gen/scripts/gen-preset-index.ts +181 -0
  29. package/plugins/generations/music-gen/scripts/resolve-preset.ts +64 -0
  30. package/plugins/generations/music-gen/src/adapter/index.ts +35 -0
  31. package/plugins/generations/music-gen/src/adapter/instance.ts +927 -0
  32. package/plugins/generations/music-gen/src/adapter/offline.ts +124 -0
  33. package/plugins/generations/music-gen/src/artifact.ts +223 -0
  34. package/plugins/generations/music-gen/src/audio/checks.ts +618 -0
  35. package/plugins/generations/music-gen/src/audio/master.ts +267 -0
  36. package/plugins/generations/music-gen/src/audio/measure.ts +507 -0
  37. package/plugins/generations/music-gen/src/audio/profile.ts +131 -0
  38. package/plugins/generations/music-gen/src/audio.ts +122 -0
  39. package/plugins/generations/music-gen/src/brief.ts +191 -0
  40. package/plugins/generations/music-gen/src/config.ts +451 -0
  41. package/plugins/generations/music-gen/src/content.ts +199 -0
  42. package/plugins/generations/music-gen/src/digest.ts +100 -0
  43. package/plugins/generations/music-gen/src/index.ts +147 -0
  44. package/plugins/generations/music-gen/src/job.ts +131 -0
  45. package/plugins/generations/music-gen/src/plugin.ts +371 -0
  46. package/plugins/generations/music-gen/src/presets.ts +951 -0
  47. package/plugins/generations/music-gen/src/render.ts +87 -0
  48. package/plugins/generations/music-gen/src/request.ts +102 -0
  49. package/plugins/generations/music-gen/src/spend.ts +495 -0
  50. package/plugins/generations/music-gen/tsconfig.json +8 -0
  51. package/plugins/generations/omni-voice-gen/uv.toml +5 -0
  52. package/plugins/generations/vibe-voice-tts/README.md +64 -0
  53. package/plugins/generations/vibe-voice-tts/dist/index.js +14259 -0
  54. package/plugins/generations/vibe-voice-tts/package.json +16 -0
  55. package/plugins/generations/vibe-voice-tts/plugin.json +6 -0
  56. package/plugins/generations/vibe-voice-tts/profiles.json +10 -0
  57. package/plugins/generations/vibe-voice-tts/pyproject.toml +9 -0
  58. package/plugins/generations/vibe-voice-tts/python/worker.py +566 -0
  59. package/plugins/generations/vibe-voice-tts/src/index.ts +88 -0
  60. package/plugins/generations/vibe-voice-tts/src/vibevoice-client.ts +828 -0
  61. package/plugins/generations/vibe-voice-tts/tsconfig.json +8 -0
  62. package/plugins/generations/vibe-voice-tts/uv.lock +1767 -0
  63. package/plugins/generations/vibe-voice-tts/uv.toml +4 -0
  64. package/plugins/generations/voice-gen/dist/index.js +31 -1
  65. package/plugins/generations/voice-gen/src/voicebox-client.ts +50 -1
  66. package/plugins/generations/voxcpm-tts/dist/index.js +81 -9
  67. package/plugins/generations/voxcpm-tts/python/worker.py +9 -0
  68. package/plugins/generations/voxcpm-tts/src/index.ts +41 -0
  69. package/plugins/generations/voxcpm-tts/src/voxcpm-client.ts +32 -11
  70. package/plugins/generations/voxcpm-tts/uv.toml +5 -0
  71. package/plugins/kk/README.md +21 -0
  72. package/plugins/kk/decisions/kk-safety.yaml +5 -2
  73. package/plugins/kk/plugin.json +1 -1
  74. package/plugins/kk/schedules/kk-serve.launchd.plist.tmpl +14 -2
  75. package/plugins/kk/scripts/cover-compositor.ts +380 -32
  76. package/plugins/kk/scripts/daily-cover-mock.ts +40 -3
  77. package/plugins/kk/scripts/daily-stages.ts +933 -60
  78. package/plugins/kk/scripts/episode-identity.ts +180 -0
  79. package/plugins/kk/scripts/kk-workflow-stages.ts +111 -12
  80. package/plugins/kk/scripts/music-stages.ts +624 -0
  81. package/plugins/kk/scripts/news-editorial-ledger.ts +906 -0
  82. package/plugins/kk/scripts/safety-artifact-check.ts +28 -5
  83. package/plugins/kk/scripts/source-citation.ts +187 -0
  84. package/plugins/kk/scripts/topic-selection-attempts.ts +446 -0
  85. package/plugins/kk/scripts/topic-selection-calibration.ts +161 -0
  86. package/plugins/kk/skills/content-judge/SKILL.md +11 -6
  87. package/plugins/kk/skills/content-judge/references/music-quality-rubric.md +147 -0
  88. package/plugins/kk/skills/content-judge/references/rubrics.md +15 -0
  89. package/plugins/kk/skills/content-safety/SKILL.md +12 -0
  90. package/plugins/kk/skills/music-authoring/SKILL.md +276 -0
  91. package/plugins/kk/skills/music-authoring/references/judge-input.md +117 -0
  92. package/plugins/kk/skills/news-editorial/SKILL.md +102 -15
  93. package/plugins/kk/skills/news-editorial/references/selection.md +4 -0
  94. package/plugins/kk/skills/news-editorial/references/style-contract.zh.md +58 -11
  95. package/plugins/kk/workflows/kk-daily-ai-voice.yaml +12 -11
  96. package/plugins/kk/workflows/kk-daily-ai-voice2.yaml +13 -12
  97. package/plugins/kk/workflows/kk-daily-safety.yaml +12 -10
  98. package/plugins/kk/workflows/kk-music.yaml +332 -0
  99. package/plugins/kk/workflows/kk-news-generate.yaml +81 -6
  100. package/plugins/kk/workflows/kk-publish.yaml +4 -1
  101. package/plugins/publishings/bilibili-pub/dist/index.js +11 -1
  102. package/plugins/publishings/bilibili-pub/dist/profile-check.js +11 -1
  103. package/plugins/publishings/cnblogs-pub/dist/index.js +11 -1
  104. package/plugins/publishings/cnblogs-pub/dist/profile-check.js +11 -1
  105. package/plugins/publishings/csdn-pub/dist/index.js +11 -1
  106. package/plugins/publishings/csdn-pub/dist/profile-check.js +11 -1
  107. package/plugins/publishings/infoq-pub/dist/index.js +11 -1
  108. package/plugins/publishings/infoq-pub/dist/profile-check.js +11 -1
  109. package/plugins/publishings/jike-pub/dist/index.js +11 -1
  110. package/plugins/publishings/jike-pub/dist/profile-check.js +11 -1
  111. package/plugins/publishings/juejin-pub/dist/index.js +11 -1
  112. package/plugins/publishings/juejin-pub/dist/profile-check.js +11 -1
  113. package/plugins/publishings/linkedin-pub/dist/index.js +62 -10
  114. package/plugins/publishings/linkedin-pub/dist/profile-check.js +16 -1
  115. package/plugins/publishings/linkedin-pub/src/index.ts +99 -12
  116. package/plugins/publishings/podcast-pub/dist/index.js +586 -20
  117. package/plugins/publishings/podcast-pub/src/corrections.ts +509 -0
  118. package/plugins/publishings/podcast-pub/src/index.ts +257 -5
  119. package/plugins/publishings/podcast-pub/src/show-notes-brief.ts +240 -0
  120. package/plugins/publishings/podcast-pub/src/show-notes.ts +69 -13
  121. package/plugins/publishings/shipinhao-pub/dist/index.js +59 -8
  122. package/plugins/publishings/shipinhao-pub/dist/profile-check.js +11 -1
  123. package/plugins/publishings/shipinhao-pub/src/audio-flow.ts +105 -6
  124. package/plugins/publishings/sspai-pub/dist/index.js +11 -1
  125. package/plugins/publishings/sspai-pub/dist/profile-check.js +11 -1
  126. package/plugins/publishings/substack-pub/dist/index.js +11 -1
  127. package/plugins/publishings/substack-pub/dist/profile-check.js +11 -1
  128. package/plugins/publishings/surfdash-pub/dist/index.js +80 -24
  129. package/plugins/publishings/surfdash-pub/src/digest-check.ts +7 -3
  130. package/plugins/publishings/surfdash-pub/src/index.ts +107 -18
  131. package/plugins/publishings/surfdash-pub/src/patch.ts +21 -3
  132. package/plugins/publishings/surfdash-pub/src/topic-claims.ts +3 -1
  133. package/plugins/publishings/threads-pub/dist/index.js +58 -6
  134. package/plugins/publishings/threads-pub/dist/profile-check.js +18 -2
  135. package/plugins/publishings/threads-pub/src/post-rail.ts +101 -4
  136. package/plugins/publishings/wechatmp-pub/dist/index.js +105 -35
  137. package/plugins/publishings/wechatmp-pub/dist/profile-check.js +11 -1
  138. package/plugins/publishings/wechatmp-pub/src/cgi-draft.ts +87 -53
  139. package/plugins/publishings/wechatmp-pub/src/enrich.ts +61 -3
  140. package/plugins/publishings/wechatmp-pub/src/flow.ts +28 -0
  141. package/plugins/publishings/weibo-pub/dist/index.js +11 -1
  142. package/plugins/publishings/weibo-pub/dist/profile-check.js +11 -1
  143. package/plugins/publishings/x-pub/dist/index.js +95 -10
  144. package/plugins/publishings/x-pub/dist/profile-check.js +11 -1
  145. package/plugins/publishings/x-pub/src/post-rail.ts +154 -12
  146. package/plugins/publishings/xhs-pub/dist/index.js +11 -1
  147. package/plugins/publishings/xhs-pub/dist/profile-check.js +11 -1
  148. package/plugins/publishings/xiaoyuzhou-pub/dist/index.js +11 -1
  149. package/plugins/publishings/xiaoyuzhou-pub/dist/profile-check.js +11 -1
@@ -0,0 +1,927 @@
1
+ import { detectAudioFormat } from '../audio';
2
+ import type { AudioFormat, MusicModel } from '../brief';
3
+ import type { MusicGenerateRequest } from '../request';
4
+
5
+ /**
6
+ * Live adapter for the self-hosted Lyria 3 instance (task 0398 R2/R3; contract
7
+ * frozen by `docs/design/music-gen.md` §6).
8
+ *
9
+ * This is the only module in the plugin that knows HTTP. Everything downstream
10
+ * sees a typed take in and a typed `Content` out.
11
+ *
12
+ * **Paid-call policy (§6.3) — the whole reason this file exists.** Both
13
+ * `POST /api/lyria/generate` and `POST /api/ai/analyze` are non-idempotent: the
14
+ * instance may have billed and persisted a take even when kk never saw the
15
+ * response. So:
16
+ *
17
+ * - connect-phase failures (`ECONNREFUSED`, `ENOTFOUND`, `EAI_AGAIN`,
18
+ * `EHOSTUNREACH`, `ENETUNREACH`, a connect-phase timeout) retry — bounded to
19
+ * {@link DEFAULT_CONNECT_ATTEMPTS} total attempts — because the request
20
+ * provably never reached the instance;
21
+ * - `401/402/403/404/429` and the all-keys-rejected `502` are **terminal**: one
22
+ * request sent, no retry, the instance's own error text plus a remediation;
23
+ * - a timeout after send, `ECONNRESET`, any other `5xx`, an unparseable `200`
24
+ * or a `200` carrying no audio are **ambiguous**: never re-send — reconcile
25
+ * against `GET /api/generations` and adopt the earliest matching take.
26
+ *
27
+ * The instance already fails over across its own key list and refuses to fail
28
+ * over on request-level errors so an account is not billed twice, so kk adds no
29
+ * second failover layer: only the two edges above.
30
+ */
31
+
32
+ /** Injected HTTP seam. Tests supply a stub; nothing mutates a global. */
33
+ export type MusicFetch = (input: string, init?: RequestInit) => Promise<Response>;
34
+
35
+ /** Generate route (paid). */
36
+ export const GENERATE_PATH = '/api/lyria/generate';
37
+
38
+ /** Library route (free): the reconciliation + cache-first analyse source. */
39
+ export const LIBRARY_PATH = '/api/generations';
40
+
41
+ /** Cheap reachability probe route (free): decided under `connectTimeoutMs` before paid POSTs. */
42
+ export const STATUS_PATH = '/api/settings/status';
43
+
44
+ /** Analyse route (paid). */
45
+ export const ANALYZE_PATH = '/api/ai/analyze';
46
+
47
+ /** Bounded connect-phase attempts (§6.3: "bounded to 3 attempts total"). */
48
+ export const DEFAULT_CONNECT_ATTEMPTS = 3;
49
+
50
+ /** First connect-retry backoff in ms; doubles per attempt. Injected in tests to keep them fast. */
51
+ export const DEFAULT_RETRY_DELAY_MS = 250;
52
+
53
+ /** Statuses that are terminal post-send: the request was rejected, nothing was produced. */
54
+ const TERMINAL_STATUSES: ReadonlySet<number> = new Set([400, 401, 402, 403, 404, 429]);
55
+
56
+ /** Operator remediation per terminal status (§6.3 table). */
57
+ const STATUS_REMEDIATION: Readonly<Record<number, string>> = {
58
+ 400: 'fix the brief/request — the instance rejected the body and its own error text is above',
59
+ 401: 'fix the provider key on the instance (kk never sees or prints it)',
60
+ 402: 'the provider credits/entitlement on the instance are exhausted — top up or switch its key',
61
+ 403: 'the instance key is restricted for this project/model — widen it or use another key',
62
+ 404: 'check music.instance.url / KK_MUSIC_INSTANCE_URL and the model: the route or model does not exist there',
63
+ 429: 'the instance is rate limited — wait, then re-run; kk never retries a 429',
64
+ };
65
+
66
+ /** Fetch error codes that prove the request never reached the instance. */
67
+ const CONNECT_ERROR_CODES: ReadonlySet<string> = new Set([
68
+ 'ECONNREFUSED',
69
+ 'ENOTFOUND',
70
+ 'EAI_AGAIN',
71
+ 'EHOSTUNREACH',
72
+ 'ENETUNREACH',
73
+ 'UND_ERR_CONNECT_TIMEOUT',
74
+ ]);
75
+
76
+ /** Fetch error codes that mean "the request may have landed" — ambiguous, never retried. */
77
+ const AMBIGUOUS_ERROR_CODES: ReadonlySet<string> = new Set([
78
+ 'ECONNRESET',
79
+ 'ECONNABORTED',
80
+ 'EPIPE',
81
+ 'UND_ERR_SOCKET',
82
+ 'ETIMEDOUT',
83
+ 'UND_ERR_HEADERS_TIMEOUT',
84
+ 'UND_ERR_BODY_TIMEOUT',
85
+ ]);
86
+
87
+ /**
88
+ * The instance's all-keys-rejected body marker (§6.3). The instance tries its
89
+ * key list in order and answers `502` with this class of message when every key
90
+ * it holds was rejected; that is terminal — a second kk attempt cannot help.
91
+ */
92
+ export const ALL_KEYS_REJECTED_PATTERN =
93
+ /all\b[^.]{0,60}?keys?\b|every\s+(?:api\s+|provider\s+)?key\b|no\s+(?:usable|valid|working)\s+(?:api\s+|provider\s+)?keys?\b|keys?\s+(?:were\s+|was\s+)?(?:all\s+)?rejected/i;
94
+
95
+ /** One library take as `GET /api/generations` reports it. Every field except `id` may be absent. */
96
+ export interface InstanceTake {
97
+ id: string;
98
+ prompt?: string;
99
+ model?: MusicModel | string;
100
+ generatedAt?: string;
101
+ audioUrl?: string;
102
+ /** The container the manifest claims; the delivered bytes are authoritative (§6.2). */
103
+ format?: string;
104
+ title?: string;
105
+ language?: string;
106
+ durationTarget?: string;
107
+ batchCount?: number;
108
+ /** The instance caches analysis per generation, so a take may already carry it (§6.3 / R3). */
109
+ analysis?: MusicAnalysis;
110
+ }
111
+
112
+ /** The instance's analysis payload. Shape is the instance's own — kk only reads `summary`. */
113
+ export type MusicAnalysis = Record<string, unknown>;
114
+
115
+ /** One extra library take that matched reconciliation but was not adopted (recorded for spend visibility). */
116
+ export interface UnclaimedTake {
117
+ id: string;
118
+ generatedAt: string;
119
+ }
120
+
121
+ /** One produced take: the manifest, the delivered bytes and their detected container. */
122
+ export interface GeneratedTake {
123
+ id: string;
124
+ prompt: string;
125
+ model: string;
126
+ generatedAt?: string;
127
+ audioUrl?: string;
128
+ language?: string;
129
+ durationTarget?: string;
130
+ batchCount?: number;
131
+ title?: string;
132
+ analysis?: MusicAnalysis;
133
+ bytes: Uint8Array;
134
+ /** Detected from the bytes (§6.2) — never the requested `format`. */
135
+ format: AudioFormat;
136
+ contentType?: string;
137
+ /** True when the take came from `GET /api/generations` after an ambiguous send. */
138
+ adoptedByReconciliation: boolean;
139
+ /** Later library takes that matched the same request: the operator can see the extra spend. */
140
+ unclaimed: UnclaimedTake[];
141
+ /** Wall clock of the whole generate call, reconciliation included. */
142
+ elapsedMs: number;
143
+ }
144
+
145
+ /** Result of a cache-first analyse. */
146
+ export interface AnalysisOutcome {
147
+ instanceId: string;
148
+ /** `null` only when the instance answered but carried no analysis object. */
149
+ analysis: MusicAnalysis | null;
150
+ /** True when the manifest already carried the analysis: no paid POST was sent (R3). */
151
+ cached: boolean;
152
+ /** True when a paid POST was sent in this call (an adopted post-ambiguity analysis counts). */
153
+ paid: boolean;
154
+ }
155
+
156
+ /** The surface every adapter (live, offline) implements. */
157
+ export interface MusicInstance {
158
+ /** `lyria-instance` or `offline`; recorded in `Content.metadata` and the liner notes. */
159
+ readonly provider: string;
160
+ /** Issue one paid generate. Never re-sends after an ambiguous outcome. */
161
+ generate(request: MusicGenerateRequest): Promise<GeneratedTake>;
162
+ /** Read the instance library (`GET /api/generations`). */
163
+ listGenerations(): Promise<InstanceTake[]>;
164
+ /** Cache-first analyse: manifest analysis first, one paid POST only when absent. */
165
+ analyze(instanceId: string): Promise<AnalysisOutcome>;
166
+ /** Human-facing library URL for one generation, used in `Content.references`. */
167
+ libraryUrl(instanceId: string): string;
168
+ }
169
+
170
+ /** How a failure behaves: terminal (one request, no retry), ambiguous (reconcile) or connect. */
171
+ export type InstanceFailureKind = 'terminal' | 'ambiguous' | 'connect';
172
+
173
+ /** Fields of an {@link InstanceError}. */
174
+ export interface InstanceErrorOptions {
175
+ kind: InstanceFailureKind;
176
+ /** Route, e.g. `POST /api/lyria/generate`. */
177
+ endpoint: string;
178
+ attempts: number;
179
+ elapsedMs: number;
180
+ status?: number;
181
+ /** The instance's own error text, verbatim (truncated). */
182
+ instanceMessage?: string;
183
+ remediation: string;
184
+ /** What happened, in one clause. */
185
+ detail: string;
186
+ }
187
+
188
+ /**
189
+ * A failed instance call. The message always names the endpoint, what happened,
190
+ * the instance's own text when there is one, and the remediation.
191
+ */
192
+ export class InstanceError extends Error {
193
+ readonly kind: InstanceFailureKind;
194
+ readonly endpoint: string;
195
+ readonly attempts: number;
196
+ readonly elapsedMs: number;
197
+ readonly status: number | undefined;
198
+ readonly instanceMessage: string | undefined;
199
+ readonly remediation: string;
200
+
201
+ constructor(options: InstanceErrorOptions) {
202
+ const elapsed = `${String(options.elapsedMs)} ms`;
203
+ const attemptWord = options.attempts === 1 ? 'attempt' : 'attempts';
204
+ const status = options.status === undefined ? '' : ` ${String(options.status)}`;
205
+ const instanceText = options.instanceMessage === undefined ? '' : `: ${options.instanceMessage}`;
206
+ super(
207
+ `lyria instance ${options.endpoint} ${options.detail}${status} after ${String(options.attempts)} ${attemptWord} (${elapsed})${instanceText} — ${options.remediation}`,
208
+ );
209
+ this.name = 'InstanceError';
210
+ this.kind = options.kind;
211
+ this.endpoint = options.endpoint;
212
+ this.attempts = options.attempts;
213
+ this.elapsedMs = options.elapsedMs;
214
+ this.status = options.status;
215
+ this.instanceMessage = options.instanceMessage;
216
+ this.remediation = options.remediation;
217
+ }
218
+ }
219
+
220
+ /** Options for {@link createInstanceClient}. */
221
+ export interface InstanceClientOptions {
222
+ baseUrl?: string;
223
+ timeoutMs?: number;
224
+ connectTimeoutMs?: number;
225
+ /** Injected HTTP seam; defaults to the platform `fetch`. */
226
+ fetch?: MusicFetch;
227
+ /** Total attempts for connect-phase failures on a paid route. */
228
+ connectAttempts?: number;
229
+ /** First connect-retry backoff in ms. */
230
+ retryDelayMs?: number;
231
+ /** Injected sleep (tests pass a no-op). */
232
+ sleep?: (ms: number) => Promise<void>;
233
+ /** Injected clock for elapsed-time reporting. */
234
+ now?: () => number;
235
+ }
236
+
237
+ /** Raw HTTP response reduced to what the adapter needs. */
238
+ interface RawResponse {
239
+ status: number;
240
+ statusText: string;
241
+ contentType?: string;
242
+ headers: Headers;
243
+ bytes: Uint8Array;
244
+ }
245
+
246
+ /** Outcome of one HTTP round trip. */
247
+ type AttemptOutcome =
248
+ | { kind: 'response'; response: RawResponse }
249
+ | { kind: 'connect'; reason: string }
250
+ | { kind: 'ambiguous'; reason: string; status?: number };
251
+
252
+ /** Outcome of a whole send (connect retries included). */
253
+ type SendOutcome =
254
+ | { kind: 'ok'; response: RawResponse; attempts: number }
255
+ | { kind: 'terminal'; response: RawResponse; message: string; attempts: number }
256
+ | { kind: 'ambiguous'; reason: string; status?: number; attempts: number }
257
+ | { kind: 'connect-exhausted'; reason: string; attempts: number };
258
+
259
+ /** Extract a socket error code from a fetch rejection, if it has one. */
260
+ function errorCode(error: unknown): string | undefined {
261
+ const direct = (error as { code?: unknown } | null)?.code;
262
+ if (typeof direct === 'string') {
263
+ return direct;
264
+ }
265
+ const cause = (error as { cause?: { code?: unknown } } | null)?.cause?.code;
266
+ return typeof cause === 'string' ? cause : undefined;
267
+ }
268
+
269
+ /** One-line description of a thrown fetch error, for diagnostics. */
270
+ function describeThrown(error: unknown): string {
271
+ if (error instanceof Error) {
272
+ const code = errorCode(error);
273
+ return code === undefined ? `${error.name}: ${error.message}` : `${code} (${error.message})`;
274
+ }
275
+ return String(error);
276
+ }
277
+
278
+ /** Default sleep used between connect retries. */
279
+ function realSleep(ms: number): Promise<void> {
280
+ return new Promise((resolve) => setTimeout(resolve, ms));
281
+ }
282
+
283
+ /** The platform fetch, as the injected seam's default. */
284
+ const platformFetch: MusicFetch = fetch;
285
+
286
+ /** Read the instance's error text: JSON `message`/`error` when present, else the raw body. */
287
+ function instanceErrorText(response: RawResponse): string {
288
+ const text = new TextDecoder().decode(response.bytes).trim();
289
+ if (text === '') {
290
+ return response.statusText === '' ? '(empty response body)' : response.statusText;
291
+ }
292
+ try {
293
+ const parsed: unknown = JSON.parse(text);
294
+ if (typeof parsed === 'object' && parsed !== null) {
295
+ const message = (parsed as { message?: unknown }).message;
296
+ const error = (parsed as { error?: unknown }).error;
297
+ const chosen = typeof message === 'string' ? message : typeof error === 'string' ? error : undefined;
298
+ if (chosen !== undefined && chosen.trim() !== '') {
299
+ return chosen.trim().slice(0, 500);
300
+ }
301
+ }
302
+ } catch {
303
+ // Not JSON: fall through to the raw text.
304
+ }
305
+ return text.slice(0, 500);
306
+ }
307
+
308
+ /** Coerce an unknown library payload into `InstanceTake[]`, or `null` when the shape is unusable. */
309
+ function parseLibrary(payload: unknown): InstanceTake[] | null {
310
+ const list = Array.isArray(payload)
311
+ ? payload
312
+ : typeof payload === 'object' &&
313
+ payload !== null &&
314
+ Array.isArray((payload as { generations?: unknown }).generations)
315
+ ? ((payload as { generations: unknown[] }).generations as unknown[])
316
+ : Array.isArray((payload as { items?: unknown } | null)?.items)
317
+ ? ((payload as { items: unknown[] }).items as unknown[])
318
+ : null;
319
+ if (list === null) {
320
+ return null;
321
+ }
322
+ const takes: InstanceTake[] = [];
323
+ for (const entry of list) {
324
+ if (typeof entry !== 'object' || entry === null) {
325
+ continue;
326
+ }
327
+ const record = entry as Record<string, unknown>;
328
+ const id = record.id ?? record.generationId;
329
+ if (typeof id !== 'string' || id === '') {
330
+ continue;
331
+ }
332
+ takes.push({
333
+ id,
334
+ ...(typeof record.prompt === 'string' ? { prompt: record.prompt } : {}),
335
+ ...(typeof record.model === 'string' ? { model: record.model } : {}),
336
+ ...(typeof record.generatedAt === 'string' ? { generatedAt: record.generatedAt } : {}),
337
+ ...(typeof record.audioUrl === 'string' ? { audioUrl: record.audioUrl } : {}),
338
+ ...(typeof record.url === 'string' ? { audioUrl: record.url } : {}),
339
+ ...(typeof record.format === 'string' ? { format: record.format } : {}),
340
+ ...(typeof record.title === 'string' ? { title: record.title } : {}),
341
+ ...(typeof record.language === 'string' ? { language: record.language } : {}),
342
+ ...(typeof record.durationTarget === 'string' ? { durationTarget: record.durationTarget } : {}),
343
+ ...(typeof record.batchCount === 'number' ? { batchCount: record.batchCount } : {}),
344
+ ...(typeof record.analysis === 'object' && record.analysis !== null
345
+ ? { analysis: record.analysis as MusicAnalysis }
346
+ : {}),
347
+ });
348
+ }
349
+ return takes;
350
+ }
351
+
352
+ /**
353
+ * The live instance client. One instance per plugin run; all HTTP goes through
354
+ * the injected {@link MusicFetch} seam so tests never open a socket.
355
+ */
356
+ export class InstanceClient implements MusicInstance {
357
+ readonly provider = 'lyria-instance';
358
+
359
+ private readonly baseUrl: string;
360
+ private readonly timeoutMs: number;
361
+ private readonly connectTimeoutMs: number;
362
+ private readonly fetchImpl: MusicFetch;
363
+ private readonly connectAttempts: number;
364
+ private readonly retryDelayMs: number;
365
+ private readonly sleep: (ms: number) => Promise<void>;
366
+ private readonly now: () => number;
367
+
368
+ constructor(options: InstanceClientOptions = {}) {
369
+ this.baseUrl = (options.baseUrl ?? 'http://127.0.0.1:3000').replace(/\/+$/, '');
370
+ this.timeoutMs = options.timeoutMs ?? 180_000;
371
+ this.connectTimeoutMs = options.connectTimeoutMs ?? 5_000;
372
+ this.fetchImpl = options.fetch ?? platformFetch;
373
+ this.connectAttempts = Math.max(1, options.connectAttempts ?? DEFAULT_CONNECT_ATTEMPTS);
374
+ this.retryDelayMs = options.retryDelayMs ?? DEFAULT_RETRY_DELAY_MS;
375
+ this.sleep = options.sleep ?? realSleep;
376
+ this.now = options.now ?? Date.now;
377
+ }
378
+
379
+ /** Absolute URL for a route or a manifest-supplied (possibly relative) audio URL. */
380
+ private url(target: string): string {
381
+ return new URL(target, `${this.baseUrl}/`).toString();
382
+ }
383
+
384
+ /** Library URL for one generation (the `Content.references` provenance link). */
385
+ libraryUrl(instanceId: string): string {
386
+ return new URL(`${LIBRARY_PATH}/${encodeURIComponent(instanceId)}`, `${this.baseUrl}/`).toString();
387
+ }
388
+
389
+ /** One round trip with an optional connect-phase deadline (GET only) and an end-to-end deadline. */
390
+ private async attempt(method: 'GET' | 'POST', path: string, body: unknown): Promise<AttemptOutcome> {
391
+ const controller = new AbortController();
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';
396
+ let abortReason: 'connect-timeout' | 'generate-timeout' | undefined;
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;
405
+ const totalTimer = setTimeout(() => {
406
+ if (abortReason === undefined) {
407
+ abortReason = 'generate-timeout';
408
+ controller.abort();
409
+ }
410
+ }, this.timeoutMs);
411
+ try {
412
+ const init: RequestInit = {
413
+ method,
414
+ headers: {
415
+ accept: 'application/json, audio/*',
416
+ ...(body === undefined ? {} : { 'content-type': 'application/json' }),
417
+ },
418
+ signal: controller.signal,
419
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),
420
+ };
421
+ const response = await this.fetchImpl(this.url(path), init);
422
+ // Headers arrived: the request reached the instance, so a later abort is post-send.
423
+ phase = 'body';
424
+ if (connectTimer !== undefined) {
425
+ clearTimeout(connectTimer);
426
+ }
427
+ const bytes = new Uint8Array(await response.arrayBuffer());
428
+ const contentType = response.headers.get('content-type') ?? undefined;
429
+ return {
430
+ kind: 'response',
431
+ response: {
432
+ status: response.status,
433
+ statusText: response.statusText,
434
+ ...(contentType === undefined ? {} : { contentType }),
435
+ headers: response.headers,
436
+ bytes,
437
+ },
438
+ };
439
+ } catch (error) {
440
+ const reason = describeThrown(error);
441
+ if (abortReason === 'connect-timeout') {
442
+ return { kind: 'connect', reason: `no connection within ${String(this.connectTimeoutMs)} ms` };
443
+ }
444
+ if (abortReason === 'generate-timeout') {
445
+ return {
446
+ kind: 'ambiguous',
447
+ reason: `no response within the ${String(this.timeoutMs)} ms generation deadline`,
448
+ };
449
+ }
450
+ const code = errorCode(error);
451
+ if (code !== undefined && CONNECT_ERROR_CODES.has(code)) {
452
+ return { kind: 'connect', reason };
453
+ }
454
+ if (code !== undefined && AMBIGUOUS_ERROR_CODES.has(code)) {
455
+ // The request was sent and the connection broke: it may already be billed.
456
+ return { kind: 'ambiguous', reason: `${code}: the connection broke after the request was sent` };
457
+ }
458
+ // Anything unrecognised may have reached the instance: ambiguous, never retried.
459
+ return { kind: 'ambiguous', reason };
460
+ } finally {
461
+ if (connectTimer !== undefined) {
462
+ clearTimeout(connectTimer);
463
+ }
464
+ clearTimeout(totalTimer);
465
+ }
466
+ }
467
+
468
+ /** Classify a received response against the terminal/ambiguous table (§6.3). */
469
+ private classify(response: RawResponse, attempts: number): SendOutcome {
470
+ const { status } = response;
471
+ if (status >= 200 && status < 300) {
472
+ return { kind: 'ok', response, attempts };
473
+ }
474
+ const message = instanceErrorText(response);
475
+ if (status === 502 && ALL_KEYS_REJECTED_PATTERN.test(message)) {
476
+ return { kind: 'terminal', response, message, attempts };
477
+ }
478
+ if (TERMINAL_STATUSES.has(status)) {
479
+ return { kind: 'terminal', response, message, attempts };
480
+ }
481
+ if (status >= 500 || status === 408) {
482
+ return {
483
+ kind: 'ambiguous',
484
+ reason: `answered ${String(status)} ${response.statusText}`.trim(),
485
+ status,
486
+ attempts,
487
+ };
488
+ }
489
+ if (status >= 400) {
490
+ // Any other 4xx is a post-send request rejection: nothing was produced, so no reconciliation.
491
+ return { kind: 'terminal', response, message, attempts };
492
+ }
493
+ return { kind: 'ambiguous', reason: `answered an unexpected ${String(status)}`, status, attempts };
494
+ }
495
+
496
+ /** Send one request, probing reachability before paid POSTs, and classify the result. */
497
+ private async send(method: 'GET' | 'POST', path: string, body: unknown): Promise<SendOutcome> {
498
+ const maxAttempts = method === 'POST' ? this.connectAttempts : 1;
499
+ let attempts = 0;
500
+ let lastReason = '';
501
+ for (;;) {
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
+ }
514
+ const outcome = await this.attempt(method, path, body);
515
+ if (outcome.kind === 'response') {
516
+ return this.classify(outcome.response, attempts);
517
+ }
518
+ if (outcome.kind === 'ambiguous') {
519
+ return {
520
+ kind: 'ambiguous',
521
+ reason: outcome.reason,
522
+ ...(outcome.status === undefined ? {} : { status: outcome.status }),
523
+ attempts,
524
+ };
525
+ }
526
+ lastReason = outcome.reason;
527
+ if (attempts >= maxAttempts) {
528
+ return { kind: 'connect-exhausted', reason: lastReason, attempts };
529
+ }
530
+ await this.sleep(this.retryDelayMs * 2 ** (attempts - 1));
531
+ }
532
+ }
533
+
534
+ /** Raised when every connect attempt failed: the request never reached the instance, so no spend. */
535
+ private connectError(path: string, reason: string, attempts: number, elapsedMs: number): InstanceError {
536
+ return new InstanceError({
537
+ kind: 'connect',
538
+ endpoint: `POST ${path}`,
539
+ attempts,
540
+ elapsedMs,
541
+ detail: `could not be reached (${reason})`,
542
+ remediation: 'start the instance, or fix music.instance.url / KK_MUSIC_INSTANCE_URL; nothing was billed',
543
+ });
544
+ }
545
+
546
+ /** Raised for a terminal post-send rejection: the instance's own text plus a remediation. */
547
+ private terminalError(
548
+ path: string,
549
+ response: RawResponse,
550
+ message: string,
551
+ attempts: number,
552
+ elapsedMs: number,
553
+ ): InstanceError {
554
+ const remediation =
555
+ response.status === 502
556
+ ? 'every provider key the instance holds was rejected — fix its key list, then re-run'
557
+ : (STATUS_REMEDIATION[response.status] ?? 'fix the request or the instance before re-running');
558
+ return new InstanceError({
559
+ kind: 'terminal',
560
+ endpoint: `POST ${path}`,
561
+ attempts,
562
+ elapsedMs,
563
+ status: response.status,
564
+ instanceMessage: message,
565
+ detail: 'rejected the request with',
566
+ remediation,
567
+ });
568
+ }
569
+
570
+ /** Read the library (free, idempotent). Throws {@link InstanceError} when it is unusable. */
571
+ async listGenerations(): Promise<InstanceTake[]> {
572
+ const startedAt = this.now();
573
+ const outcome = await this.send('GET', LIBRARY_PATH, undefined);
574
+ if (outcome.kind === 'connect-exhausted') {
575
+ throw this.connectError(LIBRARY_PATH, outcome.reason, outcome.attempts, this.now() - startedAt);
576
+ }
577
+ if (outcome.kind === 'terminal' || outcome.kind === 'ambiguous') {
578
+ throw new InstanceError({
579
+ kind: outcome.kind === 'terminal' ? 'terminal' : 'ambiguous',
580
+ endpoint: `GET ${LIBRARY_PATH}`,
581
+ attempts: outcome.attempts,
582
+ elapsedMs: this.now() - startedAt,
583
+ ...(outcome.kind === 'terminal' ? { status: outcome.response.status } : {}),
584
+ detail: 'could not be read',
585
+ remediation: 'check the instance is healthy and music.instance.url / KK_MUSIC_INSTANCE_URL',
586
+ });
587
+ }
588
+ let payload: unknown;
589
+ try {
590
+ payload = JSON.parse(new TextDecoder().decode(outcome.response.bytes));
591
+ } catch {
592
+ throw new InstanceError({
593
+ kind: 'ambiguous',
594
+ endpoint: `GET ${LIBRARY_PATH}`,
595
+ attempts: outcome.attempts,
596
+ elapsedMs: this.now() - startedAt,
597
+ detail: 'returned unparseable JSON',
598
+ remediation: 'check the instance version and the base URL; reconciliation needs the library',
599
+ });
600
+ }
601
+ const takes = parseLibrary(payload);
602
+ if (takes === null) {
603
+ throw new InstanceError({
604
+ kind: 'ambiguous',
605
+ endpoint: `GET ${LIBRARY_PATH}`,
606
+ attempts: outcome.attempts,
607
+ elapsedMs: this.now() - startedAt,
608
+ detail: 'did not carry a generation list',
609
+ remediation: 'check the instance version: reconciliation reads `generations[]` from this route',
610
+ });
611
+ }
612
+ return takes;
613
+ }
614
+
615
+ /** Fetch the audio bytes of one take; `null` when the take carries no audio URL. */
616
+ private async fetchAudio(take: InstanceTake): Promise<{ bytes: Uint8Array; contentType?: string } | null> {
617
+ if (take.audioUrl === undefined || take.audioUrl === '') {
618
+ return null;
619
+ }
620
+ const outcome = await this.attempt('GET', take.audioUrl, undefined);
621
+ if (outcome.kind !== 'response' || outcome.response.status < 200 || outcome.response.status >= 300) {
622
+ return null;
623
+ }
624
+ return {
625
+ bytes: outcome.response.bytes,
626
+ ...(outcome.response.contentType === undefined ? {} : { contentType: outcome.response.contentType }),
627
+ };
628
+ }
629
+
630
+ /** Build the generated take from a manifest plus its audio bytes; `null` when the bytes carry no audio. */
631
+ private buildTake(
632
+ manifest: InstanceTake,
633
+ audio: { bytes: Uint8Array; contentType?: string },
634
+ options: { elapsedMs: number; adoptedByReconciliation: boolean; unclaimed: UnclaimedTake[] },
635
+ ): GeneratedTake | null {
636
+ const format = detectAudioFormat(audio.bytes, audio.contentType);
637
+ if (format === null) {
638
+ return null;
639
+ }
640
+ return {
641
+ id: manifest.id,
642
+ prompt: manifest.prompt ?? '',
643
+ model: manifest.model ?? '',
644
+ ...(manifest.generatedAt === undefined ? {} : { generatedAt: manifest.generatedAt }),
645
+ ...(manifest.audioUrl === undefined ? {} : { audioUrl: this.url(manifest.audioUrl) }),
646
+ ...(manifest.language === undefined ? {} : { language: manifest.language }),
647
+ ...(manifest.durationTarget === undefined ? {} : { durationTarget: manifest.durationTarget }),
648
+ ...(manifest.batchCount === undefined ? {} : { batchCount: manifest.batchCount }),
649
+ ...(manifest.title === undefined ? {} : { title: manifest.title }),
650
+ ...(manifest.analysis === undefined ? {} : { analysis: manifest.analysis }),
651
+ bytes: audio.bytes,
652
+ format,
653
+ ...(audio.contentType === undefined ? {} : { contentType: audio.contentType }),
654
+ adoptedByReconciliation: options.adoptedByReconciliation,
655
+ unclaimed: options.unclaimed,
656
+ elapsedMs: options.elapsedMs,
657
+ };
658
+ }
659
+
660
+ /**
661
+ * Reconcile an ambiguous send against the library (§6.3): adopt the earliest
662
+ * take whose prompt is byte-equal to what kk sent, whose model matches and
663
+ * whose `generatedAt` is at or after the request start; record later matches
664
+ * as `unclaimed`. Never re-sends the paid request.
665
+ */
666
+ private async reconcile(
667
+ request: MusicGenerateRequest,
668
+ startedAtMs: number,
669
+ path: string,
670
+ reason: string,
671
+ attempts: number,
672
+ ): Promise<GeneratedTake> {
673
+ let library: InstanceTake[];
674
+ try {
675
+ library = await this.listGenerations();
676
+ } catch {
677
+ const elapsedMs = this.now() - startedAtMs;
678
+ throw new InstanceError({
679
+ kind: 'ambiguous',
680
+ endpoint: `POST ${path}`,
681
+ attempts,
682
+ elapsedMs,
683
+ detail: `did not return a response (${reason}) and GET ${LIBRARY_PATH} could not be read to reconcile`,
684
+ remediation:
685
+ 'the request may have been billed: check GET /api/generations on the instance before re-running, and re-run with --force only if no take appeared',
686
+ });
687
+ }
688
+ const matches = library
689
+ .filter((take) => {
690
+ if (take.prompt !== request.prompt || take.model !== request.model) {
691
+ return false;
692
+ }
693
+ if (take.generatedAt === undefined) {
694
+ return false;
695
+ }
696
+ const generated = Date.parse(take.generatedAt);
697
+ return Number.isFinite(generated) && generated >= startedAtMs;
698
+ })
699
+ .sort((left, right) => Date.parse(left.generatedAt ?? '') - Date.parse(right.generatedAt ?? ''));
700
+
701
+ const [adopted, ...rest] = matches;
702
+ const elapsedMs = this.now() - startedAtMs;
703
+ if (adopted === undefined) {
704
+ throw new InstanceError({
705
+ kind: 'ambiguous',
706
+ endpoint: `POST ${path}`,
707
+ attempts,
708
+ elapsedMs,
709
+ detail: `did not return a response (${reason}) and GET ${LIBRARY_PATH} found no take whose prompt matches the sent prompt byte for byte`,
710
+ remediation:
711
+ 'the request may still be running on the instance or may have been billed: check GET /api/generations, then re-run with --force to send a new (paid) request',
712
+ });
713
+ }
714
+ const audio = await this.fetchAudio(adopted);
715
+ if (audio === null) {
716
+ throw new InstanceError({
717
+ kind: 'ambiguous',
718
+ endpoint: `POST ${path}`,
719
+ attempts,
720
+ elapsedMs,
721
+ detail: `did not return a response (${reason}); library take ${adopted.id} matched but its audio could not be read`,
722
+ remediation: `check GET ${LIBRARY_PATH} for take ${adopted.id} and its audio URL, then re-run with --force only if the audio is gone`,
723
+ });
724
+ }
725
+ const take = this.buildTake(adopted, audio, {
726
+ elapsedMs,
727
+ adoptedByReconciliation: true,
728
+ unclaimed: rest.map((entry) => ({ id: entry.id, generatedAt: entry.generatedAt ?? '' })),
729
+ });
730
+ if (take === null) {
731
+ throw new InstanceError({
732
+ kind: 'ambiguous',
733
+ endpoint: `POST ${path}`,
734
+ attempts,
735
+ elapsedMs,
736
+ detail: `did not return a response (${reason}); library take ${adopted.id} matched but its audio bytes are not a recognisable audio container`,
737
+ remediation: `check the audio of library take ${adopted.id}, then re-run with --force only if it is unusable`,
738
+ });
739
+ }
740
+ return take;
741
+ }
742
+
743
+ /** Issue one paid generate (§6.2/§6.3). */
744
+ async generate(request: MusicGenerateRequest): Promise<GeneratedTake> {
745
+ const startedAtMs = this.now();
746
+ const outcome = await this.send('POST', GENERATE_PATH, request);
747
+ const elapsedMs = this.now() - startedAtMs;
748
+ if (outcome.kind === 'connect-exhausted') {
749
+ throw this.connectError(GENERATE_PATH, outcome.reason, outcome.attempts, elapsedMs);
750
+ }
751
+ if (outcome.kind === 'terminal') {
752
+ throw this.terminalError(GENERATE_PATH, outcome.response, outcome.message, outcome.attempts, elapsedMs);
753
+ }
754
+ if (outcome.kind === 'ambiguous') {
755
+ return this.reconcile(request, startedAtMs, GENERATE_PATH, outcome.reason, outcome.attempts);
756
+ }
757
+ const response = outcome.response;
758
+ const inlineAudio = detectAudioFormat(response.bytes, response.contentType) !== null;
759
+ const isJson = response.contentType?.includes('json') === true;
760
+ let manifest: InstanceTake | null = null;
761
+ let audio: { bytes: Uint8Array; contentType?: string } | null = null;
762
+ if (inlineAudio && !isJson) {
763
+ // Streaming shape: the body IS the audio, so the id must ride a header. Without one
764
+ // the take exists but cannot be recorded — reconcile rather than invent an id.
765
+ const id = response.headers.get('x-generation-id') ?? response.headers.get('x-generation');
766
+ if (id === null || id === '') {
767
+ return this.reconcile(
768
+ request,
769
+ startedAtMs,
770
+ GENERATE_PATH,
771
+ 'returned audio bytes without a generation id header',
772
+ outcome.attempts,
773
+ );
774
+ }
775
+ manifest = {
776
+ id,
777
+ prompt: request.prompt,
778
+ model: request.model,
779
+ ...(request.durationTarget === undefined ? {} : { durationTarget: request.durationTarget }),
780
+ batchCount: request.batchCount,
781
+ title: request.title,
782
+ };
783
+ audio = {
784
+ bytes: response.bytes,
785
+ ...(response.contentType === undefined ? {} : { contentType: response.contentType }),
786
+ };
787
+ } else {
788
+ // Manifest shape: `{ ...manifest }` or `{ generation: { ...manifest } }`.
789
+ let payload: unknown;
790
+ try {
791
+ payload = JSON.parse(new TextDecoder().decode(response.bytes));
792
+ } catch {
793
+ return this.reconcile(
794
+ request,
795
+ startedAtMs,
796
+ GENERATE_PATH,
797
+ 'returned a 200 with unparseable JSON',
798
+ outcome.attempts,
799
+ );
800
+ }
801
+ const wrapped =
802
+ typeof payload === 'object' && payload !== null && 'generation' in payload
803
+ ? (payload as { generation?: unknown }).generation
804
+ : payload;
805
+ const parsed = parseLibrary([wrapped])?.[0] ?? null;
806
+ if (parsed === null) {
807
+ return this.reconcile(
808
+ request,
809
+ startedAtMs,
810
+ GENERATE_PATH,
811
+ 'returned a 200 without a generation id',
812
+ outcome.attempts,
813
+ );
814
+ }
815
+ // The manifest may omit what kk sent; the request is the authoritative echo of it.
816
+ manifest = {
817
+ ...parsed,
818
+ prompt: parsed.prompt ?? request.prompt,
819
+ model: parsed.model ?? request.model,
820
+ };
821
+ const fetched = await this.fetchAudio(parsed);
822
+ if (fetched === null) {
823
+ return this.reconcile(
824
+ request,
825
+ startedAtMs,
826
+ GENERATE_PATH,
827
+ `returned a 200 for ${parsed.id} but its audio could not be fetched`,
828
+ outcome.attempts,
829
+ );
830
+ }
831
+ audio = fetched;
832
+ }
833
+ const take = this.buildTake(manifest, audio, {
834
+ elapsedMs: this.now() - startedAtMs,
835
+ adoptedByReconciliation: false,
836
+ unclaimed: [],
837
+ });
838
+ if (take === null) {
839
+ return this.reconcile(
840
+ request,
841
+ startedAtMs,
842
+ GENERATE_PATH,
843
+ `returned a 200 for ${manifest.id} but the bytes are not a recognisable audio container`,
844
+ outcome.attempts,
845
+ );
846
+ }
847
+ return take;
848
+ }
849
+
850
+ /** Read the manifest analysis for one generation, or `undefined` when absent. */
851
+ private async cachedAnalysis(instanceId: string): Promise<MusicAnalysis | undefined> {
852
+ const library = await this.listGenerations();
853
+ const take = library.find((entry) => entry.id === instanceId);
854
+ return take?.analysis;
855
+ }
856
+
857
+ /**
858
+ * Cache-first analyse (R3): the instance caches analysis per generation, so a
859
+ * second paid analysis is pure waste. One paid POST only when the manifest
860
+ * carries none; after an ambiguous POST the reconciliation is the same
861
+ * manifest read — never a second paid call.
862
+ */
863
+ async analyze(instanceId: string): Promise<AnalysisOutcome> {
864
+ const cached = await this.cachedAnalysis(instanceId);
865
+ if (cached !== undefined) {
866
+ return { instanceId, analysis: cached, cached: true, paid: false };
867
+ }
868
+ const startedAtMs = this.now();
869
+ const outcome = await this.send('POST', ANALYZE_PATH, { id: instanceId });
870
+ const elapsedMs = this.now() - startedAtMs;
871
+ if (outcome.kind === 'connect-exhausted') {
872
+ throw this.connectError(ANALYZE_PATH, outcome.reason, outcome.attempts, elapsedMs);
873
+ }
874
+ if (outcome.kind === 'terminal') {
875
+ throw this.terminalError(ANALYZE_PATH, outcome.response, outcome.message, outcome.attempts, elapsedMs);
876
+ }
877
+ if (outcome.kind === 'ok') {
878
+ let payload: unknown;
879
+ try {
880
+ payload = JSON.parse(new TextDecoder().decode(outcome.response.bytes));
881
+ } catch {
882
+ const adopted = await this.adoptAfterAmbiguity(
883
+ instanceId,
884
+ startedAtMs,
885
+ 'returned a 200 with unparseable JSON',
886
+ outcome.attempts,
887
+ );
888
+ return adopted;
889
+ }
890
+ const record = typeof payload === 'object' && payload !== null ? (payload as Record<string, unknown>) : {};
891
+ const analysis =
892
+ typeof record.analysis === 'object' && record.analysis !== null
893
+ ? (record.analysis as MusicAnalysis)
894
+ : record;
895
+ return { instanceId, analysis, cached: false, paid: true };
896
+ }
897
+ return await this.adoptAfterAmbiguity(instanceId, startedAtMs, outcome.reason, outcome.attempts);
898
+ }
899
+
900
+ /** Post-ambiguity analyse: adopt the manifest analysis when the instance cached it; else fail. */
901
+ private async adoptAfterAmbiguity(
902
+ instanceId: string,
903
+ startedAtMs: number,
904
+ reason: string,
905
+ attempts: number,
906
+ ): Promise<AnalysisOutcome> {
907
+ const cached = await this.cachedAnalysis(instanceId).catch(() => undefined);
908
+ if (cached !== undefined) {
909
+ return { instanceId, analysis: cached, cached: true, paid: true };
910
+ }
911
+ const elapsedMs = this.now() - startedAtMs;
912
+ throw new InstanceError({
913
+ kind: 'ambiguous',
914
+ endpoint: `POST ${ANALYZE_PATH}`,
915
+ attempts,
916
+ elapsedMs,
917
+ detail: `did not return an analysis (${reason}) for generation ${instanceId}`,
918
+ remediation:
919
+ 'the analysis may have been billed: check GET /api/generations for a cached analysis, then re-run with --force to pay for it again',
920
+ });
921
+ }
922
+ }
923
+
924
+ /** Build the live client. */
925
+ export function createInstanceClient(options: InstanceClientOptions = {}): InstanceClient {
926
+ return new InstanceClient(options);
927
+ }