@nodetool-ai/kie-nodes 0.8.10 → 0.8.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/kie-base.js CHANGED
@@ -1,232 +1,18 @@
1
1
  /**
2
- * Shared Kie.ai API utilities for submit → poll → download lifecycle.
3
- * Uses native fetch (Node 18+).
2
+ * Shared Kie.ai node helpers: input uploads, the endpoint call, result
3
+ * mapping and cost reporting. The transport (submit, poll, upload, download)
4
+ * lives in the runtime `KieProvider`, reached through the processing context.
4
5
  */
5
- import { loadMediaRefBytes, registerCostReconciler, registerWebhookWait } from "@nodetool-ai/runtime";
6
- import { safeFetch } from "@nodetool-ai/runtime";
7
- import { TERMINAL_FAILURE_STATES, TERMINAL_SUCCESS_STATES, fetchWithRetry, imageRefFromBytes, sleep } from "@nodetool-ai/runtime/provider-transport";
8
- const KIE_API_BASE = "https://api.kie.ai";
9
- const KIE_UPLOAD_URL = "https://kieai.redpandaai.co/api/file-stream-upload";
10
- function getWebhookBaseUrl() {
11
- const url = process.env.KIE_WEBHOOK_URL;
12
- return url && url.trim() ? url.replace(/\/+$/, "") : undefined;
13
- }
14
- function headers(apiKey) {
15
- return {
16
- Authorization: `Bearer ${apiKey}`,
17
- "Content-Type": "application/json"
18
- };
19
- }
6
+ import { getProvider, loadMediaRefBytes, registerCostReconciler, sniffMedia } from "@nodetool-ai/runtime";
7
+ import { imageRefFromBytes } from "@nodetool-ai/runtime/provider-transport";
8
+ const KIE = "kie";
20
9
  function withTaskId(message, taskId) {
21
10
  return `${message} (taskId: ${taskId})`;
22
11
  }
23
- function pollTimeoutError(taskId, maxAttempts, pollInterval) {
24
- const timeoutSeconds = (maxAttempts * pollInterval) / 1000;
25
- return new Error(`Task timed out after ${timeoutSeconds}s (taskId: ${taskId}). ` +
26
- "The job may still complete on KIE — check recordInfo or the KIE dashboard.");
27
- }
28
- function checkStatus(data) {
29
- const code = Number(data.code);
30
- const map = {
31
- 401: "Unauthorized",
32
- 402: "Insufficient Credits",
33
- 404: "Not Found",
34
- 422: "Validation Error",
35
- 429: "Rate Limited",
36
- 455: "Service Unavailable",
37
- 500: "Server Error",
38
- 501: "Generation Failed",
39
- 505: "Feature Disabled"
40
- };
41
- if (map[code])
42
- throw new Error(`${map[code]}: ${JSON.stringify(data)}`);
43
- }
44
- function tryParseRecord(text) {
45
- try {
46
- return asRecord(JSON.parse(text));
47
- }
48
- catch {
49
- return undefined;
50
- }
51
- }
52
- /**
53
- * Read a KIE response body. A gateway 502 answers with an HTML page, and
54
- * `res.json()` on it threw `SyntaxError: Unexpected token '<'` — the status the
55
- * caller needed to see never reached them. Parse defensively and report the
56
- * status with a body snippet instead. Every parsed body still goes through
57
- * {@link checkStatus}, because KIE announces failures inside HTTP 200.
58
- */
59
- async function parseKieJson(res, label) {
60
- const text = await res.text();
61
- const data = tryParseRecord(text);
62
- if (!data) {
63
- throw new Error(`Kie ${label} failed: HTTP ${res.status} ${text.slice(0, 200)}`);
64
- }
65
- if (data.code !== undefined)
66
- checkStatus(data);
67
- return data;
68
- }
69
- /**
70
- * GET a KIE endpoint once the job exists, retrying 429/5xx and thrown network
71
- * errors with backoff (`Retry-After` honored). The poll loop does not use this:
72
- * its own interval is the backoff, and {@link pollKieTask} counts the failures.
73
- */
74
- function kieGet(url, apiKey, signal) {
75
- return fetchWithRetry(url, { headers: headers(apiKey), signal });
76
- }
77
- /**
78
- * Fetch a finished result. The URL comes out of the provider's response body,
79
- * so it is screened (`safeFetch` re-checks every redirect hop), and a 429/5xx is
80
- * retried: the job is already generated and billed, and a CDN blip must not
81
- * throw the paid-for result away.
82
- */
83
- function fetchBilledResult(url, signal) {
84
- return fetchWithRetry(url, { signal }, {
85
- fetchImpl: (input, init) => safeFetch(String(input), init)
86
- });
87
- }
88
- /**
89
- * Poll a KIE task until `isDone` accepts a body (or throws for a failed job).
90
- *
91
- * A dead job used to look like a slow one two ways: a persistent non-OK poll
92
- * after createTask succeeded, and a body that names no state. Both ran the full
93
- * attempt budget — ten minutes at the defaults — before reporting a timeout.
94
- */
95
- const MAX_CONSECUTIVE_POLL_ERRORS = 5;
96
- async function pollKieTask(apiKey, url, taskId, pollInterval, maxAttempts, isDone, signal) {
97
- let consecutiveErrors = 0;
98
- for (let i = 0; i < maxAttempts; i++) {
99
- if (signal?.aborted) {
100
- throw signal.reason instanceof Error ? signal.reason : new Error("Aborted");
101
- }
102
- let res;
103
- try {
104
- res = await fetch(url, { headers: headers(apiKey), signal });
105
- }
106
- catch (err) {
107
- // A thrown network error is the same transient the loop already tolerates,
108
- // so it counts toward the same cutoff instead of losing a running job.
109
- consecutiveErrors += 1;
110
- if (consecutiveErrors >= MAX_CONSECUTIVE_POLL_ERRORS)
111
- throw err;
112
- await sleep(pollInterval, signal);
113
- continue;
114
- }
115
- if (!res.ok) {
116
- const body = await res.text().catch(() => "");
117
- // A non-OK poll can still carry KIE's error envelope, which names the
118
- // reason; only an unreadable one gets the retry budget.
119
- const envelope = tryParseRecord(body);
120
- if (envelope?.code !== undefined)
121
- checkStatus(envelope);
122
- consecutiveErrors += 1;
123
- if (consecutiveErrors >= MAX_CONSECUTIVE_POLL_ERRORS) {
124
- throw new Error(withTaskId(`Poll failed ${consecutiveErrors}x (HTTP ${res.status}): ${body.slice(0, 200)}`, taskId));
125
- }
126
- await sleep(pollInterval, signal);
127
- continue;
128
- }
129
- consecutiveErrors = 0;
130
- const data = await parseKieJson(res, "recordInfo");
131
- if (isDone(data))
132
- return data;
133
- await sleep(pollInterval, signal);
134
- }
135
- throw pollTimeoutError(taskId, maxAttempts, pollInterval);
136
- }
137
- async function submitTask(apiKey, model, input, signal) {
138
- const res = await fetch(`${KIE_API_BASE}/api/v1/jobs/createTask`, {
139
- method: "POST",
140
- headers: headers(apiKey),
141
- body: JSON.stringify({ model, input }),
142
- signal
143
- });
144
- const data = await parseKieJson(res, "submit");
145
- if (!res.ok)
146
- throw new Error(`Submit failed: ${res.status} ${JSON.stringify(data)}`);
147
- const taskId = data.data?.taskId;
148
- if (!taskId)
149
- throw new Error(`No taskId in response: ${JSON.stringify(data)}`);
150
- return taskId;
151
- }
152
- function recordInfoUrl(taskId) {
153
- return `${KIE_API_BASE}/api/v1/jobs/recordInfo?taskId=${taskId}`;
154
- }
155
- function sunoRecordUrl(taskId) {
156
- return `${KIE_API_BASE}/api/v1/generate/record-info?taskId=${taskId}`;
157
- }
158
- /**
159
- * Read the job state out of a `recordInfo` body against the shared terminal
160
- * vocabulary, so a synonym this package has not seen before does not degrade
161
- * into a timeout that reports a finished job as a slow one.
162
- */
163
- function recordInfoDone(taskId) {
164
- return (data) => {
165
- const inner = asRecord(data.data);
166
- const state = String(inner?.state ?? "").toLowerCase();
167
- if (TERMINAL_SUCCESS_STATES.has(state))
168
- return true;
169
- if (TERMINAL_FAILURE_STATES.has(state)) {
170
- const msg = inner?.failMsg || data.msg || "Unknown error";
171
- throw new Error(withTaskId(`Task failed: ${msg}`, taskId));
172
- }
173
- return false;
174
- };
175
- }
176
- function pollStatus(apiKey, taskId, pollInterval, maxAttempts, signal) {
177
- return pollKieTask(apiKey, recordInfoUrl(taskId), taskId, pollInterval, maxAttempts, recordInfoDone(taskId), signal);
178
- }
179
- async function fetchRecordInfo(apiKey, taskId, signal) {
180
- const res = await kieGet(recordInfoUrl(taskId), apiKey, signal);
181
- return parseKieJson(res, "recordInfo");
182
- }
183
- async function downloadResult(apiKey, taskId, signal) {
184
- const res = await kieGet(recordInfoUrl(taskId), apiKey, signal);
185
- if (!res.ok)
186
- throw new Error(withTaskId(`Failed to get result: ${res.status}`, taskId));
187
- const data = await parseKieJson(res, "recordInfo");
188
- const resultJsonStr = data.data
189
- ?.resultJson;
190
- if (!resultJsonStr)
191
- throw new Error(withTaskId("No resultJson in response", taskId));
192
- const resultData = JSON.parse(resultJsonStr);
193
- const resultUrls = resultData.resultUrls;
194
- if (!resultUrls?.length)
195
- throw new Error(withTaskId("No resultUrls in resultJson", taskId));
196
- const items = await Promise.all(resultUrls.map(async (resultUrl) => {
197
- const dlRes = await fetchBilledResult(resultUrl, signal);
198
- if (!dlRes.ok) {
199
- throw new Error(withTaskId(`Failed to download from ${resultUrl}`, taskId));
200
- }
201
- return Buffer.from(await dlRes.arrayBuffer());
202
- }));
203
- return { items, taskId };
204
- }
205
- export async function uploadFile(apiKey, data, uploadPath, filename, signal) {
206
- const form = new globalThis.FormData();
207
- form.append("file", new Blob([new Uint8Array(data)]), filename);
208
- form.append("uploadPath", uploadPath);
209
- form.append("fileName", filename);
210
- const res = await fetch(KIE_UPLOAD_URL, {
211
- method: "POST",
212
- headers: { Authorization: `Bearer ${apiKey}` },
213
- body: form,
214
- signal
215
- });
216
- const resData = await parseKieJson(res, "upload");
217
- if (!res.ok || !resData.success)
218
- throw new Error(`Upload failed: ${res.status} ${JSON.stringify(resData)}`);
219
- const downloadUrl = resData.data
220
- ?.downloadUrl;
221
- if (!downloadUrl)
222
- throw new Error(`No downloadUrl in upload response`);
223
- return downloadUrl;
224
- }
225
- export function getApiKey(secrets) {
226
- const key = secrets?.KIE_API_KEY || process.env.KIE_API_KEY || "";
227
- if (!key)
228
- throw new Error("KIE_API_KEY is not configured");
229
- return key;
12
+ function asRecord(value) {
13
+ return value && typeof value === "object" && !Array.isArray(value)
14
+ ? value
15
+ : undefined;
230
16
  }
231
17
  function isRemoteHttpUrl(uri) {
232
18
  return !!uri && /^https?:\/\//.test(uri);
@@ -236,147 +22,126 @@ function isLocalHttpUrl(uri) {
236
22
  uri.includes("127.0.0.1") ||
237
23
  uri.includes("[::1]"));
238
24
  }
25
+ function requireContext(context) {
26
+ if (!context)
27
+ throw new Error("KIE nodes need a processing context");
28
+ return context;
29
+ }
30
+ /** The MIME type an upload declares when the bytes do not say. */
31
+ const NOMINAL_MIME = {
32
+ image: "image/png",
33
+ audio: "audio/mpeg",
34
+ video: "video/mp4"
35
+ };
36
+ const KIND_LABEL = {
37
+ image: "Image",
38
+ audio: "Audio",
39
+ video: "Video"
40
+ };
239
41
  /**
240
- * Resolve an asset ref to raw bytes for upload. Delegates to the canonical
241
- * {@link loadMediaRefBytes}, which handles inline `data`, `data:` URIs,
242
- * `asset://<id>` references (via `context.resolveAssetBytes`), package asset
243
- * URIs, opaque storage URIs (plus `asset_id` → `/api/storage/<id>.<ext>`
244
- * candidates), local file paths, and local http(s) URLs. KIE's earlier bespoke
245
- * resolver only handled `data`/`data:`/`storage.retrieve(uri)`, so `asset://`
246
- * refs — the format this package's own field descriptions recommend — failed
247
- * with "Image has no data or URI".
42
+ * Resolve a media ref and hand its bytes to KIE's file host, returning the URL
43
+ * KIE reads. A public http(s) uri passes through untouched. The bytes go
44
+ * through the canonical {@link loadMediaRefBytes}, which handles inline
45
+ * `data`, `data:` URIs, `asset://<id>` references, storage URIs and local
46
+ * http(s) URLs.
248
47
  */
249
- async function resolveUploadBytes(ref, context) {
250
- const bytes = await loadMediaRefBytes(ref, context);
251
- return bytes ? Buffer.from(bytes) : null;
252
- }
253
- export async function uploadImageInput(apiKey, image, context) {
254
- if (!image || typeof image !== "object")
255
- throw new Error("Image is required");
256
- const img = image;
257
- const uri = img.uri;
48
+ async function uploadMediaInput(kind, ref, context) {
49
+ const label = KIND_LABEL[kind];
50
+ if (!ref || typeof ref !== "object")
51
+ throw new Error(`${label} is required`);
52
+ const media = ref;
53
+ const uri = media.uri;
258
54
  if (isRemoteHttpUrl(uri) && !isLocalHttpUrl(uri)) {
259
55
  return uri;
260
56
  }
261
- const bytes = await resolveUploadBytes(img, context);
57
+ const bytes = await loadMediaRefBytes(media, context);
262
58
  if (!bytes)
263
- throw new Error("Image has no data or URI");
264
- return uploadFile(apiKey, bytes, "images/user-uploads", `upload-${Date.now()}.png`, context?.signal);
59
+ throw new Error(`${label} has no data or URI`);
60
+ const ctx = requireContext(context);
61
+ // Declare the container the bytes carry, so a JPEG is not announced as PNG.
62
+ const sniffed = sniffMedia(bytes);
63
+ const mimeType = sniffed?.kind === kind ? sniffed.mime : NOMINAL_MIME[kind];
64
+ return ctx.uploadProviderMedia({
65
+ provider: KIE,
66
+ bytes,
67
+ mimeType,
68
+ signal: ctx.signal
69
+ });
265
70
  }
266
- export async function uploadAudioInput(apiKey, audio, context) {
267
- if (!audio || typeof audio !== "object")
268
- throw new Error("Audio is required");
269
- const a = audio;
270
- const uri = a.uri;
271
- if (isRemoteHttpUrl(uri) && !isLocalHttpUrl(uri)) {
272
- return uri;
273
- }
274
- const bytes = await resolveUploadBytes(a, context);
275
- if (!bytes)
276
- throw new Error("Audio has no data or URI");
277
- return uploadFile(apiKey, bytes, "audio/user-uploads", `upload-${Date.now()}.mp3`, context?.signal);
71
+ export function uploadImageInput(image, context) {
72
+ return uploadMediaInput("image", image, context);
278
73
  }
279
- export async function uploadVideoInput(apiKey, video, context) {
280
- if (!video || typeof video !== "object")
281
- throw new Error("Video is required");
282
- const v = video;
283
- const uri = v.uri;
284
- if (isRemoteHttpUrl(uri) && !isLocalHttpUrl(uri)) {
285
- return uri;
286
- }
287
- const bytes = await resolveUploadBytes(v, context);
288
- if (!bytes)
289
- throw new Error("Video has no data or URI");
290
- return uploadFile(apiKey, bytes, "videos/user-uploads", `upload-${Date.now()}.mp4`, context?.signal);
74
+ export function uploadAudioInput(audio, context) {
75
+ return uploadMediaInput("audio", audio, context);
76
+ }
77
+ export function uploadVideoInput(video, context) {
78
+ return uploadMediaInput("video", video, context);
291
79
  }
292
80
  function isRefSet(ref) {
293
81
  if (!ref || typeof ref !== "object")
294
82
  return false;
295
83
  const r = ref;
296
84
  // A library-picked or freshly-generated ref carries only `asset_id` (with an
297
- // empty `uri`); `resolveUploadBytes` → `loadMediaRefBytes` resolves it via the
298
- // context, so treat a non-empty `asset_id` as a source. `null`/`""` stay unset.
85
+ // empty `uri`); `loadMediaRefBytes` resolves it via the context, so treat a
86
+ // non-empty `asset_id` as a source. `null`/`""` stay unset.
299
87
  return !!(r.data || r.uri || r.asset_id);
300
88
  }
301
89
  export { isRefSet };
302
- // Custom endpoint helpers for Veo, Runway, etc.
303
- async function submitCustom(apiKey, endpoint, payload, signal) {
304
- const res = await fetch(`${KIE_API_BASE}${endpoint}`, {
305
- method: "POST",
306
- headers: headers(apiKey),
307
- body: JSON.stringify(payload),
308
- signal
309
- });
310
- const data = await parseKieJson(res, "submit");
311
- if (!res.ok)
312
- throw new Error(`Submit failed: ${res.status} ${JSON.stringify(data)}`);
313
- const taskId = data.data?.taskId;
314
- if (!taskId)
315
- throw new Error(`No taskId in response: ${JSON.stringify(data)}`);
316
- return taskId;
90
+ /** The generation capability that names a KIE node's output on the ledger. */
91
+ export function kieCapability(outputType, useSuno = false) {
92
+ if (useSuno)
93
+ return "text_to_music";
94
+ switch (outputType) {
95
+ case "video":
96
+ return "text_to_video";
97
+ case "audio":
98
+ return "text_to_speech";
99
+ case "image":
100
+ default:
101
+ // A text output (an Omni id, a resultObject string) has no closer
102
+ // capability. The FAL pack defaults the same way.
103
+ return "text_to_image";
104
+ }
105
+ }
106
+ function kieRoute(req) {
107
+ if (req.directEndpoint)
108
+ return `direct:${req.directEndpoint}`;
109
+ if (req.sunoEndpoint)
110
+ return `suno:${req.sunoEndpoint}`;
111
+ return undefined;
317
112
  }
318
- function pollCustom(apiKey, taskId, pollEndpoint, pollInterval, maxAttempts, signal) {
319
- const stateDone = recordInfoDone(taskId);
320
- return pollKieTask(apiKey, `${KIE_API_BASE}${pollEndpoint}?taskId=${taskId}`, taskId, pollInterval, maxAttempts, (data) => {
321
- // Veo-style completion: successFlag 1 = done, 2/3 = failed.
322
- const successFlag = asRecord(data.data)?.successFlag;
323
- if (successFlag !== undefined) {
324
- const flag = Number(successFlag);
325
- if (flag === 1)
326
- return true;
327
- if (flag === 2 || flag === 3) {
328
- throw new Error(withTaskId(`Task failed: ${data.msg || "Unknown error"}`, taskId));
329
- }
330
- }
331
- // Runway-style completion: a state word.
332
- return stateDone(data);
333
- }, signal);
113
+ function creditsOf(result) {
114
+ const credits = result.metadata?.creditsConsumed;
115
+ return typeof credits === "number" ? credits : undefined;
334
116
  }
335
- async function downloadCustomResult(statusData, signal) {
336
- const data = statusData.data;
337
- // Try Runway-style: data.videoInfo.videoUrl
338
- const videoInfo = data?.videoInfo;
339
- if (videoInfo?.videoUrl) {
340
- const res = await fetchBilledResult(videoInfo.videoUrl, signal);
341
- if (!res.ok)
342
- throw new Error(`Download failed: ${res.status}`);
343
- return Buffer.from(await res.arrayBuffer());
344
- }
345
- // Try Veo-style: data.resultUrls or data.response.resultUrls
346
- let resultUrls = [];
347
- const rawUrls = data?.resultUrls ||
348
- data?.response?.resultUrls ||
349
- data?.response?.originUrls;
350
- if (Array.isArray(rawUrls)) {
351
- resultUrls = rawUrls.filter((u) => typeof u === "string");
117
+ async function downloadResult(context, url, message) {
118
+ let bytes;
119
+ try {
120
+ bytes = await context.downloadProviderMedia({
121
+ provider: KIE,
122
+ url,
123
+ signal: context.signal
124
+ });
352
125
  }
353
- else if (typeof rawUrls === "string") {
354
- try {
355
- const parsed = JSON.parse(rawUrls);
356
- if (Array.isArray(parsed)) {
357
- resultUrls = parsed.filter((u) => typeof u === "string");
358
- }
359
- else if (typeof parsed === "string") {
360
- resultUrls = [parsed];
361
- }
362
- }
363
- catch {
364
- resultUrls = [rawUrls];
365
- }
126
+ catch (err) {
127
+ const reason = err instanceof Error ? err.message : String(err);
128
+ throw new Error(`${message}: ${reason}`, { cause: err });
366
129
  }
367
- if (!resultUrls.length)
368
- throw new Error(`No result URLs in response: ${JSON.stringify(statusData)}`);
369
- const res = await fetchBilledResult(resultUrls[0], signal);
370
- if (!res.ok)
371
- throw new Error(`Download failed: ${res.status}`);
372
- return Buffer.from(await res.arrayBuffer());
130
+ return Buffer.from(bytes).toString("base64");
373
131
  }
374
- async function downloadTextResult(apiKey, taskId, resultObjectKey, signal) {
375
- const res = await kieGet(recordInfoUrl(taskId), apiKey, signal);
376
- if (!res.ok)
377
- throw new Error(withTaskId(`Failed to get result: ${res.status}`, taskId));
378
- const data = await parseKieJson(res, "recordInfo");
379
- const resultJsonStr = data.data?.resultJson;
132
+ /** Read the first result URL out of a finished `recordInfo` body. */
133
+ function jobResultUrl(output, taskId) {
134
+ const resultJsonStr = asRecord(output.data)?.resultJson;
135
+ if (!resultJsonStr)
136
+ throw new Error(withTaskId("No resultJson in response", taskId));
137
+ const resultData = JSON.parse(resultJsonStr);
138
+ const resultUrls = resultData.resultUrls;
139
+ if (!resultUrls?.length)
140
+ throw new Error(withTaskId("No resultUrls in resultJson", taskId));
141
+ return resultUrls[0];
142
+ }
143
+ function jobResultText(output, taskId, resultObjectKey) {
144
+ const resultJsonStr = asRecord(output.data)?.resultJson;
380
145
  if (!resultJsonStr)
381
146
  throw new Error(withTaskId("No resultJson in response", taskId));
382
147
  const resultData = JSON.parse(resultJsonStr);
@@ -387,23 +152,54 @@ async function downloadTextResult(apiKey, taskId, resultObjectKey, signal) {
387
152
  }
388
153
  throw new Error(withTaskId(`No ${resultObjectKey} in resultJson`, taskId));
389
154
  }
390
- function asRecord(value) {
391
- return value && typeof value === "object" && !Array.isArray(value)
392
- ? value
393
- : undefined;
394
- }
395
- export function parseCreditsConsumed(statusData) {
396
- const raw = asRecord(statusData.data)?.creditsConsumed;
397
- if (typeof raw === "number" && Number.isFinite(raw)) {
398
- return raw;
399
- }
400
- if (typeof raw === "string" && raw.trim()) {
401
- const parsed = Number(raw);
402
- if (Number.isFinite(parsed)) {
403
- return parsed;
155
+ /**
156
+ * Run one KIE call through `context.callProviderEndpoint`, which records the
157
+ * generation, and map KIE's answer to the node's output: base64 media, the
158
+ * text a result object names, or the id a direct endpoint returns.
159
+ */
160
+ export async function kieExecute(context, req) {
161
+ const ctx = requireContext(context);
162
+ const call = {
163
+ provider: KIE,
164
+ capability: req.capability,
165
+ model: req.model,
166
+ input: req.input,
167
+ signal: ctx.signal
168
+ };
169
+ const route = kieRoute(req);
170
+ if (route)
171
+ call.route = route;
172
+ if (req.nodeId)
173
+ call.nodeId = req.nodeId;
174
+ const result = await ctx.callProviderEndpoint(call);
175
+ const output = asRecord(result.output) ?? {};
176
+ const taskId = result.requestId ?? "";
177
+ const creditsConsumed = creditsOf(result);
178
+ if (req.directEndpoint) {
179
+ const key = req.responseIdKey ?? "";
180
+ const id = asRecord(output.data)?.[key];
181
+ if (typeof id !== "string" || !id) {
182
+ throw new Error(`No ${key} in response: ${JSON.stringify(output)}`);
404
183
  }
184
+ return { data: id, items: [id], taskId: "" };
185
+ }
186
+ if (req.sunoEndpoint) {
187
+ const sunoData = asRecord(asRecord(output.data)?.response)?.sunoData;
188
+ if (!sunoData?.length)
189
+ throw new Error("No sunoData in Suno response");
190
+ const audioUrl = sunoData[0].audioUrl;
191
+ if (!audioUrl)
192
+ throw new Error("No audioUrl in Suno response");
193
+ const b64 = await downloadResult(ctx, audioUrl, "Failed to download audio");
194
+ return { data: b64, items: [b64], taskId, creditsConsumed };
405
195
  }
406
- return undefined;
196
+ if (req.resultObjectKey) {
197
+ const text = jobResultText(output, taskId, req.resultObjectKey);
198
+ return { data: text, items: [text], taskId, creditsConsumed };
199
+ }
200
+ const url = jobResultUrl(output, taskId);
201
+ const b64 = await downloadResult(ctx, url, withTaskId(`Failed to download from ${url}`, taskId));
202
+ return { data: b64, items: [b64], taskId, creditsConsumed };
407
203
  }
408
204
  /** Kie.ai advertises credits at $0.005 each. */
409
205
  const KIE_USD_PER_CREDIT = 0.005;
@@ -425,166 +221,30 @@ export function reportKieProviderCost(context, creditsConsumed, taskId) {
425
221
  });
426
222
  }
427
223
  }
224
+ function isKieBillingProvider(value) {
225
+ return (typeof value?.fetchBillingCost ===
226
+ "function");
227
+ }
428
228
  /**
429
- * Reconcile a kie charge by task id: `recordInfo` reports `creditsConsumed`
430
- * once the task settled, which is the billed amount in credits.
229
+ * Register the kie reconciler so the tracker can refine kie estimates. The
230
+ * provider reads the task's billed credits with its own key; the credit price
231
+ * stays here.
431
232
  */
432
- export async function fetchKieBillingCost(apiKey, taskId) {
433
- const data = await fetchRecordInfo(apiKey, taskId);
434
- const credits = parseCreditsConsumed(data);
435
- if (credits == null || !Number.isFinite(credits))
436
- return null;
437
- return {
438
- cost: credits * KIE_USD_PER_CREDIT,
439
- currency: "USD",
440
- quantity: credits,
441
- unit_price: KIE_USD_PER_CREDIT
442
- };
443
- }
444
- /** Register the kie reconciler so the tracker can refine kie estimates. */
445
233
  export function registerKieCostReconciler() {
446
- registerCostReconciler("kie", async ({ requestId, secrets }) => {
447
- const apiKey = secrets?.KIE_API_KEY || process.env.KIE_API_KEY || "";
448
- if (!apiKey)
234
+ registerCostReconciler(KIE, async ({ requestId, secrets }) => {
235
+ const provider = await getProvider(KIE, (key) => secrets?.[key]);
236
+ if (!isKieBillingProvider(provider))
449
237
  return null;
450
- return fetchKieBillingCost(apiKey, requestId);
451
- });
452
- }
453
- export async function kieExecuteOmniDirect(apiKey, endpoint, body, responseIdKey, signal) {
454
- const res = await fetch(`${KIE_API_BASE}${endpoint}`, {
455
- method: "POST",
456
- headers: headers(apiKey),
457
- body: JSON.stringify(body),
458
- signal
459
- });
460
- const data = await parseKieJson(res, "omni submit");
461
- if (!res.ok) {
462
- throw new Error(`Omni submit failed: ${res.status} ${JSON.stringify(data)}`);
463
- }
464
- const inner = asRecord(data.data);
465
- const id = inner?.[responseIdKey];
466
- if (typeof id !== "string" || !id) {
467
- throw new Error(`No ${responseIdKey} in response: ${JSON.stringify(data)}`);
468
- }
469
- return { data: id, items: [id], taskId: "" };
470
- }
471
- export async function kieExecuteTask(apiKey, model, input, pollInterval = 2000, maxAttempts = 300, submitEndpoint, pollEndpoint, resultObjectKey, signal) {
472
- const webhookBase = getWebhookBaseUrl();
473
- if (submitEndpoint) {
474
- // Custom submit/poll endpoints (Veo, Runway, etc.)
475
- const customInput = webhookBase
476
- ? { model, ...input, callBackUrl: `${webhookBase}/api/kie/webhook` }
477
- : { model, ...input };
478
- const taskId = await submitCustom(apiKey, submitEndpoint, customInput, signal);
479
- if (webhookBase) {
480
- const timeoutMs = pollInterval * maxAttempts;
481
- await registerWebhookWait(taskId, timeoutMs, signal);
482
- // Fetch the final status after webhook fires
483
- const url = `${KIE_API_BASE}${pollEndpoint ?? submitEndpoint}?taskId=${taskId}`;
484
- const res = await kieGet(url, apiKey, signal);
485
- const statusData = await parseKieJson(res, "recordInfo");
486
- const creditsConsumed = parseCreditsConsumed(statusData);
487
- const resultBytes = await downloadCustomResult(statusData, signal);
488
- const b64 = resultBytes.toString("base64");
489
- return { data: b64, items: [b64], taskId, creditsConsumed };
490
- }
491
- const statusData = await pollCustom(apiKey, taskId, pollEndpoint ?? submitEndpoint, pollInterval, maxAttempts, signal);
492
- const creditsConsumed = parseCreditsConsumed(statusData);
493
- const resultBytes = await downloadCustomResult(statusData, signal);
494
- const b64 = resultBytes.toString("base64");
495
- return { data: b64, items: [b64], taskId, creditsConsumed };
496
- }
497
- const finalInput = webhookBase
498
- ? { ...input, callBackUrl: `${webhookBase}/api/kie/webhook` }
499
- : input;
500
- const taskId = await submitTask(apiKey, model, finalInput, signal);
501
- let statusData;
502
- if (webhookBase) {
503
- const timeoutMs = pollInterval * maxAttempts;
504
- await registerWebhookWait(taskId, timeoutMs, signal);
505
- statusData = await fetchRecordInfo(apiKey, taskId, signal);
506
- }
507
- else {
508
- statusData = await pollStatus(apiKey, taskId, pollInterval, maxAttempts, signal);
509
- }
510
- const creditsConsumed = parseCreditsConsumed(statusData);
511
- if (resultObjectKey) {
512
- const text = await downloadTextResult(apiKey, taskId, resultObjectKey, signal);
513
- return { data: text, items: [text], taskId, creditsConsumed };
514
- }
515
- const result = await downloadResult(apiKey, taskId, signal);
516
- const items = result.items.map((b) => b.toString("base64"));
517
- return { data: items[0], items, taskId: result.taskId, creditsConsumed };
518
- }
519
- // Suno music uses different endpoints
520
- export async function kieSubmitSuno(apiKey, input, endpoint = "/api/v1/generate", signal) {
521
- // callBackUrl is always required by the Suno API. When KIE_WEBHOOK_URL is
522
- // set we use it; otherwise inject a placeholder (we poll instead).
523
- const webhookBase = getWebhookBaseUrl();
524
- const callBackUrl = webhookBase
525
- ? `${webhookBase}/api/kie/webhook`
526
- : "https://nodetool.ai/kie-callback";
527
- const body = input.callBackUrl
528
- ? input
529
- : { ...input, callBackUrl };
530
- const res = await fetch(`${KIE_API_BASE}${endpoint}`, {
531
- method: "POST",
532
- headers: headers(apiKey),
533
- body: JSON.stringify(body),
534
- signal
238
+ const billed = await provider.fetchBillingCost(requestId);
239
+ if (!billed || !Number.isFinite(billed.creditsConsumed))
240
+ return null;
241
+ return {
242
+ cost: billed.creditsConsumed * KIE_USD_PER_CREDIT,
243
+ currency: "USD",
244
+ quantity: billed.creditsConsumed,
245
+ unit_price: KIE_USD_PER_CREDIT
246
+ };
535
247
  });
536
- const data = await parseKieJson(res, "submit");
537
- if (!res.ok)
538
- throw new Error(`Submit failed: ${res.status} ${JSON.stringify(data)}`);
539
- const taskId = data.data?.taskId;
540
- if (!taskId)
541
- throw new Error(`No taskId: ${JSON.stringify(data)}`);
542
- return taskId;
543
- }
544
- /** Suno reports its own status words beside the shared terminal vocabulary. */
545
- const SUNO_FAILURE_STATES = new Set([
546
- "create_task_failed",
547
- "generate_audio_failed",
548
- "callback_exception",
549
- "sensitive_word_error"
550
- ]);
551
- export function kiePollSuno(apiKey, taskId, pollInterval = 4000, maxAttempts = 120, signal) {
552
- return pollKieTask(apiKey, sunoRecordUrl(taskId), taskId, pollInterval, maxAttempts, (data) => {
553
- const status = String(asRecord(data.data)?.status ?? "").toLowerCase();
554
- if (TERMINAL_SUCCESS_STATES.has(status))
555
- return true;
556
- if (SUNO_FAILURE_STATES.has(status) || TERMINAL_FAILURE_STATES.has(status)) {
557
- throw new Error(withTaskId(`Suno task failed: ${status}`, taskId));
558
- }
559
- return false;
560
- }, signal);
561
- }
562
- export async function kieExecuteSunoTask(apiKey, input, pollInterval = 4000, maxAttempts = 120, endpoint, signal) {
563
- const taskId = await kieSubmitSuno(apiKey, input, endpoint, signal);
564
- const webhookBase = getWebhookBaseUrl();
565
- let pollResult;
566
- if (webhookBase) {
567
- const timeoutMs = pollInterval * maxAttempts;
568
- await registerWebhookWait(taskId, timeoutMs, signal);
569
- const res = await kieGet(sunoRecordUrl(taskId), apiKey, signal);
570
- pollResult = await parseKieJson(res, "record-info");
571
- }
572
- else {
573
- pollResult = await kiePollSuno(apiKey, taskId, pollInterval, maxAttempts, signal);
574
- }
575
- const creditsConsumed = parseCreditsConsumed(pollResult);
576
- const sunoData = pollResult.data?.response?.sunoData;
577
- if (!sunoData?.length)
578
- throw new Error("No sunoData in Suno response");
579
- const audioUrl = sunoData[0].audioUrl;
580
- if (!audioUrl)
581
- throw new Error("No audioUrl in Suno response");
582
- const dlRes = await fetchBilledResult(audioUrl, signal);
583
- if (!dlRes.ok)
584
- throw new Error(`Failed to download audio: ${dlRes.status}`);
585
- const buf = Buffer.from(await dlRes.arrayBuffer());
586
- const b64 = buf.toString("base64");
587
- return { data: b64, items: [b64], taskId, creditsConsumed };
588
248
  }
589
249
  /** Build an ImageRef from the base64 image KIE returns. */
590
250
  export function kieImageRef(base64) {