@kvidai/sdk 0.0.0-stage → 0.2.1

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/index.js ADDED
@@ -0,0 +1,677 @@
1
+ "use strict";
2
+ /**
3
+ * @kvidai/sdk — kvidai TypeScript SDK
4
+ *
5
+ * Covers the 4 core external-client flows documented in docs/external-client-guide.md:
6
+ * 1. Auth — login + API key management (console.kvid.ai / Strapi JWT)
7
+ * 2. Generation — AI video/image/voice creation + status polling + result fetch (api.kvid.ai / APIM)
8
+ * 3. Media — presigned upload → CDN URL (api.kvid.ai / APIM)
9
+ * 4. Preset — CRUD (api.kvid.ai / APIM)
10
+ *
11
+ * Usage:
12
+ * const client = new KvidaiClient({ jwt: '<strapi-jwt>', apiKey: '<apim-32hex>' });
13
+ * const { requestId, model } = await client.generation.textToVideo({ prompt: '...', model: 'wan' });
14
+ * const result = await client.generation.waitForResult({ requestId, model });
15
+ *
16
+ * Canonical sources: docs/external-client-api-reference.md, docs/external-client-guide.md
17
+ */
18
+ Object.defineProperty(exports, "__esModule", { value: true });
19
+ exports.KvidaiClient = exports.KvidaiError = void 0;
20
+ const ENV_URLS = {
21
+ prod: {
22
+ strapiBaseUrl: 'https://console.kvid.ai',
23
+ apimBaseUrl: 'https://api.kvid.ai',
24
+ webBaseUrl: 'https://kvid.ai',
25
+ generationPath: '/ai/generation',
26
+ mediaPath: '/media',
27
+ presetPath: '/preset',
28
+ agentPath: '/agent',
29
+ videoProjectPath: '/video-project',
30
+ },
31
+ staging: {
32
+ strapiBaseUrl: 'https://hometips-strapi-ts-staging1-405573518541.asia-northeast1.run.app',
33
+ apimBaseUrl: 'https://api.kvid.ai',
34
+ webBaseUrl: 'https://staging1.kvid.ai',
35
+ generationPath: '/ai/generation',
36
+ mediaPath: '/media',
37
+ presetPath: '/preset',
38
+ agentPath: '/agent',
39
+ videoProjectPath: '/video-project',
40
+ },
41
+ dev: {
42
+ strapiBaseUrl: 'http://localhost:1337',
43
+ apimBaseUrl: 'https://api.kvid.ai',
44
+ webBaseUrl: 'http://localhost:3000',
45
+ generationPath: '/ai/generation-clone',
46
+ mediaPath: '/media-dev',
47
+ presetPath: '/preset-dev',
48
+ // Agent + video-project use the same gateway paths across all envs (confirmed live 2026-10-30).
49
+ // No dev-clone equivalent exists for these endpoints.
50
+ agentPath: '/agent',
51
+ videoProjectPath: '/video-project',
52
+ },
53
+ };
54
+ class KvidaiError extends Error {
55
+ constructor(code, message, status, details) {
56
+ super(message);
57
+ this.code = code;
58
+ this.status = status;
59
+ this.details = details;
60
+ this.name = 'KvidaiError';
61
+ }
62
+ }
63
+ exports.KvidaiError = KvidaiError;
64
+ // ─────────────────────────────────────────────────────────────────────────────
65
+ // Transport
66
+ // ─────────────────────────────────────────────────────────────────────────────
67
+ class Transport {
68
+ constructor(options, urls) {
69
+ this.options = options;
70
+ this.urls = urls;
71
+ }
72
+ buildHeaders(type) {
73
+ const headers = { 'Content-Type': 'application/json' };
74
+ if (type === 'strapi' && this.options.jwt) {
75
+ headers['Authorization'] = `Bearer ${this.options.jwt}`;
76
+ }
77
+ if (type === 'apim' && this.options.apiKey) {
78
+ headers['api-key'] = this.options.apiKey;
79
+ }
80
+ return headers;
81
+ }
82
+ async request(base, path, init = {}) {
83
+ const baseUrl = base === 'strapi'
84
+ ? this.urls.strapiBaseUrl
85
+ : base === 'web'
86
+ ? this.urls.webBaseUrl
87
+ : this.urls.apimBaseUrl;
88
+ const authType = base === 'strapi' ? 'strapi' : 'apim';
89
+ let res;
90
+ try {
91
+ res = await fetch(`${baseUrl}${path}`, {
92
+ ...init,
93
+ headers: {
94
+ ...this.buildHeaders(authType),
95
+ ...init.headers,
96
+ },
97
+ signal: AbortSignal.timeout(this.options.timeoutMs ?? 30000),
98
+ });
99
+ }
100
+ catch (err) {
101
+ if (err instanceof Error && (err.name === 'TimeoutError' || err.name === 'AbortError')) {
102
+ throw new KvidaiError('TIMEOUT', `kvidai API did not respond within ${this.options.timeoutMs ?? 30000}ms`, 0);
103
+ }
104
+ throw err;
105
+ }
106
+ if (!res.ok) {
107
+ const body = await res.json().catch(() => ({ error: res.statusText }));
108
+ const msg = body?.error?.message ?? body?.message ?? body?.error ?? `HTTP ${res.status}`;
109
+ const code = body?.error?.name ?? body?.code ?? 'API_ERROR';
110
+ throw new KvidaiError(code, msg, res.status, body);
111
+ }
112
+ if (res.status === 204)
113
+ return undefined;
114
+ const text = await res.text();
115
+ return (text ? JSON.parse(text) : undefined);
116
+ }
117
+ /**
118
+ * Like request() but returns the raw text body — for SSE streams.
119
+ * No automatic timeout is applied since SSE streams are long-running.
120
+ */
121
+ async requestText(base, path, init = {}) {
122
+ const baseUrl = base === 'strapi'
123
+ ? this.urls.strapiBaseUrl
124
+ : base === 'web'
125
+ ? this.urls.webBaseUrl
126
+ : this.urls.apimBaseUrl;
127
+ const authType = base === 'strapi' ? 'strapi' : 'apim';
128
+ let res;
129
+ try {
130
+ res = await fetch(`${baseUrl}${path}`, {
131
+ ...init,
132
+ headers: {
133
+ ...this.buildHeaders(authType),
134
+ ...init.headers,
135
+ },
136
+ // No automatic timeout — SSE streams can run for minutes
137
+ });
138
+ }
139
+ catch (err) {
140
+ throw err;
141
+ }
142
+ if (!res.ok) {
143
+ const body = await res.json().catch(() => ({ error: res.statusText }));
144
+ const msg = body?.error?.message ?? body?.message ?? body?.error ?? `HTTP ${res.status}`;
145
+ const code = body?.error?.name ?? body?.code ?? 'API_ERROR';
146
+ throw new KvidaiError(code, msg, res.status, body);
147
+ }
148
+ return res.text();
149
+ }
150
+ /** Strapi JSON API envelope unwrap: `{ data: ... }` */
151
+ async strapiGet(path) {
152
+ const res = await this.request('strapi', path);
153
+ return res.data ?? res;
154
+ }
155
+ }
156
+ // ─────────────────────────────────────────────────────────────────────────────
157
+ // Auth module
158
+ // ─────────────────────────────────────────────────────────────────────────────
159
+ class AuthModule {
160
+ constructor(t, o) {
161
+ this.t = t;
162
+ this.o = o;
163
+ }
164
+ /** POST /api/auth/local — returns JWT + user. Store the jwt and pass to KvidaiClient. */
165
+ async login(params) {
166
+ return this.t.request('strapi', '/api/auth/local', {
167
+ method: 'POST',
168
+ body: JSON.stringify(params),
169
+ });
170
+ }
171
+ /** GET /api/users/me — verify JWT and fetch user profile. */
172
+ async me() {
173
+ return this.t.request('strapi', '/api/users/me');
174
+ }
175
+ /** GET /api/apim-management/my-keys — list active keys (masked). */
176
+ async listKeys() {
177
+ const res = await this.t.request('strapi', '/api/apim-management/my-keys');
178
+ return Array.isArray(res) ? res : (res.data ?? []);
179
+ }
180
+ /** GET /api/apim-management/key-detail/:subscriptionId — full 32-hex key. */
181
+ async keyDetail(subscriptionId) {
182
+ const res = await this.t.request('strapi', `/api/apim-management/key-detail/${subscriptionId}`);
183
+ // Controller wraps in { data: ... }
184
+ return res.data ?? res;
185
+ }
186
+ /** GET /api/apim-management/products — available APIM products. */
187
+ async products() {
188
+ const res = await this.t.request('strapi', '/api/apim-management/products');
189
+ const data = res.data ?? res;
190
+ return data.products ?? [];
191
+ }
192
+ /**
193
+ * POST /api/apim-management/generate-key — issue a new APIM key.
194
+ * ⚠️ primaryKey is shown only in this response — store it immediately.
195
+ */
196
+ async generateKey(params) {
197
+ return this.t.request('strapi', '/api/apim-management/generate-key', {
198
+ method: 'POST',
199
+ body: JSON.stringify(params),
200
+ });
201
+ }
202
+ /**
203
+ * POST /api/apim-management/regenerate-key — rotate key; old key is immediately invalidated.
204
+ * ⚠️ primaryKey shown only once.
205
+ */
206
+ async regenerateKey(params) {
207
+ return this.t.request('strapi', '/api/apim-management/regenerate-key', {
208
+ method: 'POST',
209
+ body: JSON.stringify(params),
210
+ });
211
+ }
212
+ /** DELETE /api/apim-management/subscription/:subscriptionId — revoke a key. */
213
+ async revokeKey(subscriptionId) {
214
+ return this.t.request('strapi', `/api/apim-management/subscription/${subscriptionId}`, {
215
+ method: 'DELETE',
216
+ });
217
+ }
218
+ /** GET /api/credit-management/summary/:email — credit balance. */
219
+ async creditSummary(email) {
220
+ const res = await this.t.request('strapi', `/api/credit-management/summary/${encodeURIComponent(email)}`);
221
+ // Controller returns { success: true, data: { totalCredit, totalUsed, ... } }
222
+ const raw = res.data ??
223
+ res;
224
+ const totalCredit = raw.totalCredit ?? raw.totalCredits ?? 0;
225
+ const totalUsed = raw.totalUsed ?? raw.usedCredits ?? 0;
226
+ return { totalCredit, totalUsed, remaining: totalCredit - totalUsed };
227
+ }
228
+ /**
229
+ * Convenience: login → fetch or generate key → return both.
230
+ * Implements the full ① Login→API key flow from docs/external-client-guide.md.
231
+ */
232
+ async loginAndGetApiKey(identifier, password) {
233
+ const { jwt, user } = await this.login({ identifier, password });
234
+ // Update transport JWT
235
+ this.o.jwt = jwt;
236
+ const keys = await this.listKeys();
237
+ const active = keys.find((k) => k.state === 'active');
238
+ if (active) {
239
+ const detail = await this.keyDetail(active.subscriptionId);
240
+ return { jwt, apiKey: detail.primaryKey, user };
241
+ }
242
+ // No key — generate one
243
+ const products = await this.products();
244
+ if (!products.length)
245
+ throw new KvidaiError('NO_PRODUCT', 'No APIM products available', 404);
246
+ const { primaryKey } = await this.generateKey({ email: user.email, productId: products[0].id });
247
+ return { jwt, apiKey: primaryKey, user };
248
+ }
249
+ }
250
+ // ─────────────────────────────────────────────────────────────────────────────
251
+ // Generation module
252
+ // ─────────────────────────────────────────────────────────────────────────────
253
+ /** Polling constants (source: apps/web-service/src/lib/services/unified-polling.service.ts) */
254
+ const POLL_INTERVAL_MS = 3000;
255
+ const POLL_MAX_ATTEMPTS = 200;
256
+ const POLL_MAX_TRANSIENT_ERRORS = 5;
257
+ const RESULT_TIMEOUT_MS = 90000; // 90s — fal→CDN upload wait
258
+ class GenerationModule {
259
+ constructor(t, urls) {
260
+ this.t = t;
261
+ this.urls = urls;
262
+ }
263
+ async createJob(endpoint, params) {
264
+ const path = `${this.urls.generationPath}/${endpoint}/generate-async`;
265
+ const res = await this.t.request('apim', path, {
266
+ method: 'POST',
267
+ body: JSON.stringify(params),
268
+ });
269
+ // Actual APIM response: { success: true, data: { job_id, model, ... } }
270
+ // Some endpoints use request_id, others use job_id — accept both
271
+ const data = res
272
+ .data ?? res;
273
+ const requestId = data.request_id ?? data.job_id ?? '';
274
+ return {
275
+ requestId,
276
+ model: data.model ?? params.model,
277
+ jobId: data.job_id,
278
+ };
279
+ }
280
+ textToVideo(params) {
281
+ return this.createJob('text-to-video', params);
282
+ }
283
+ imageToVideo(params) {
284
+ return this.createJob('image-to-video', params);
285
+ }
286
+ referenceToVideo(params) {
287
+ return this.createJob('reference-to-video', params);
288
+ }
289
+ videoToVideo(params) {
290
+ return this.createJob('video-to-video', params);
291
+ }
292
+ textToImage(params) {
293
+ return this.createJob('text-to-image', params);
294
+ }
295
+ imageToImage(params) {
296
+ return this.createJob('image-to-image', params);
297
+ }
298
+ talkV2V(params) {
299
+ return this.createJob('talk-v2v', params);
300
+ }
301
+ voice(params) {
302
+ return this.createJob('voice/text-to-speech', params);
303
+ }
304
+ /** GET /generation/status */
305
+ /** GET /generation/status?jobId=<id> */
306
+ async status(requestId, _model, email) {
307
+ // Actual endpoint uses `jobId` query param (not `request_id` or `model`)
308
+ const qs = new URLSearchParams({ jobId: requestId });
309
+ if (email)
310
+ qs.set('email', email);
311
+ // Real live API returns the {success,data} envelope: { data: { job_id, status, progress?, result_url? } }
312
+ // (result_url is present once status=completed). Accept a flat body too for robustness (same as createJob).
313
+ const res = await this.t.request('apim', `${this.urls.generationPath}/status?${qs}`);
314
+ const d = res.data ??
315
+ res;
316
+ return {
317
+ requestId: d.job_id ?? requestId,
318
+ model: _model ?? '',
319
+ status: (d.status ?? 'queued'),
320
+ progress: d.progress,
321
+ resultUrl: d.result_url, // populated when status=completed
322
+ };
323
+ }
324
+ /** GET /generation/result?jobId=<id> (90s timeout for fal→CDN upload) */
325
+ async result(requestId, _model, email) {
326
+ const qs = new URLSearchParams({ jobId: requestId });
327
+ if (email)
328
+ qs.set('email', email);
329
+ // Real live API returns the {success,data} envelope; the result endpoint's url field is `video_url`
330
+ // (even for images). Accept result_url and a flat body too for robustness.
331
+ const res = await this.t.request('apim', `${this.urls.generationPath}/result?${qs}`, {
332
+ signal: AbortSignal.timeout(RESULT_TIMEOUT_MS),
333
+ });
334
+ const d = res.data ??
335
+ res;
336
+ return {
337
+ requestId: d.job_id ?? requestId,
338
+ model: _model ?? '',
339
+ url: d.video_url ?? d.result_url ?? '',
340
+ };
341
+ }
342
+ /**
343
+ * Polls status until terminal, then fetches result.
344
+ * Encapsulates the ② create→poll→result flow from docs/external-client-guide.md.
345
+ *
346
+ * - 3s interval, 200 attempts max (~10 min)
347
+ * - 5xx errors tolerated up to 5 consecutive times
348
+ * - result() uses a separate 90s timeout for fal→CDN upload
349
+ */
350
+ async waitForResult(opts) {
351
+ const { requestId, model, email, pollIntervalMs = POLL_INTERVAL_MS, maxAttempts = POLL_MAX_ATTEMPTS, signal, } = opts;
352
+ let attempts = 0;
353
+ let consecutiveErrors = 0;
354
+ while (attempts < maxAttempts) {
355
+ if (signal?.aborted)
356
+ throw new KvidaiError('CANCELLED', 'waitForResult cancelled', 0);
357
+ await delay(pollIntervalMs, signal);
358
+ attempts++;
359
+ try {
360
+ const s = await this.status(requestId, model, email);
361
+ consecutiveErrors = 0;
362
+ if (s.status === 'completed') {
363
+ // result_url is often populated in the status response itself
364
+ const urlFromStatus = s.resultUrl;
365
+ if (urlFromStatus) {
366
+ return { requestId, model: model ?? '', url: urlFromStatus };
367
+ }
368
+ // fallback: call result() for cases where URL is only in the result endpoint
369
+ return this.result(requestId, model, email);
370
+ }
371
+ if (s.status === 'failed') {
372
+ throw new KvidaiError('GENERATION_FAILED', `Generation job failed (requestId=${requestId})`, 0);
373
+ }
374
+ if (s.status === 'cancelled') {
375
+ throw new KvidaiError('CANCELLED', `Generation job was cancelled (requestId=${requestId})`, 0);
376
+ }
377
+ // queued / processing — continue polling
378
+ }
379
+ catch (err) {
380
+ // Terminal KvidaiErrors (domain errors, not HTTP infra): bubble up immediately
381
+ if (err instanceof KvidaiError && err.status < 500)
382
+ throw err;
383
+ // Transient: 5xx KvidaiError or network/unknown — count consecutive occurrences
384
+ consecutiveErrors++;
385
+ if (consecutiveErrors >= POLL_MAX_TRANSIENT_ERRORS) {
386
+ throw new KvidaiError('POLL_ERROR', `Too many consecutive polling errors (requestId=${requestId})`, 0, err);
387
+ }
388
+ }
389
+ }
390
+ throw new KvidaiError('TIMEOUT', `waitForResult exceeded max attempts (${maxAttempts}) for requestId=${requestId}`, 0);
391
+ }
392
+ }
393
+ // ─────────────────────────────────────────────────────────────────────────────
394
+ // Media module
395
+ // ─────────────────────────────────────────────────────────────────────────────
396
+ /** Files ≥ this threshold go via browser→Spaces direct PUT (source: upload-media.ts) */
397
+ const LARGE_FILE_THRESHOLD_BYTES = 90 * 1024 * 1024;
398
+ class MediaModule {
399
+ constructor(t, urls) {
400
+ this.t = t;
401
+ this.urls = urls;
402
+ }
403
+ /** Presign a new upload slot. */
404
+ async presign(params) {
405
+ const res = await this.t.request('apim', `${this.urls.mediaPath}/presigned-upload-url`, {
406
+ method: 'POST',
407
+ body: JSON.stringify(params),
408
+ });
409
+ // Normalize: some responses return flat, some wrap in data
410
+ const flat = res;
411
+ const wrapped = res.data;
412
+ const uploadUrl = flat.uploadUrl ?? wrapped?.uploadUrl ?? '';
413
+ const cdnUrl = flat.cdnUrl ?? wrapped?.cdnUrl ?? '';
414
+ return {
415
+ uploadUrl,
416
+ cdnUrl,
417
+ key: flat.key ?? wrapped?.key,
418
+ expiresInSeconds: flat.expiresInSeconds,
419
+ };
420
+ }
421
+ /** Notify server that PUT to uploadUrl succeeded. */
422
+ async completeUpload(params) {
423
+ return this.t.request('apim', `${this.urls.mediaPath}/complete-upload`, {
424
+ method: 'POST',
425
+ body: JSON.stringify(params),
426
+ });
427
+ }
428
+ /**
429
+ * Full upload flow: presign → PUT → complete → cdnUrl.
430
+ * For files ≥ 90 MB the caller should use direct-to-Spaces PUT;
431
+ * this method does not handle large-file proxy routing.
432
+ *
433
+ * @param file File object (browser) or { name, type, size, stream: ReadableStream } (Node)
434
+ * @param email Owner email (required for server-side ownership check)
435
+ */
436
+ async upload(file, email) {
437
+ if (file.size >= LARGE_FILE_THRESHOLD_BYTES) {
438
+ throw new KvidaiError('FILE_TOO_LARGE', `File exceeds ${LARGE_FILE_THRESHOLD_BYTES / 1024 / 1024}MB — use direct PUT for large files`, 413);
439
+ }
440
+ const filename = file.name.normalize('NFC'); // NFC normalization for S3 key (macOS NFD guard)
441
+ // APIM media endpoint uses `mimeType` (not `contentType`)
442
+ const { uploadUrl, cdnUrl, fileId } = await this.presign({
443
+ filename,
444
+ mimeType: file.type,
445
+ size: file.size,
446
+ email,
447
+ });
448
+ // PUT directly to object storage (public-read)
449
+ const buffer = await file.arrayBuffer();
450
+ const putRes = await fetch(uploadUrl, {
451
+ method: 'PUT',
452
+ headers: { 'Content-Type': file.type, 'x-amz-acl': 'public-read' },
453
+ body: buffer,
454
+ signal: AbortSignal.timeout(120000), // 2 min for large-ish files
455
+ });
456
+ if (!putRes.ok) {
457
+ throw new KvidaiError('UPLOAD_FAILED', `Object storage PUT failed: ${putRes.status}`, putRes.status);
458
+ }
459
+ if (fileId) {
460
+ await this.completeUpload({
461
+ fileId,
462
+ cdnUrl,
463
+ filename,
464
+ contentType: file.type,
465
+ size: file.size,
466
+ email,
467
+ });
468
+ }
469
+ return cdnUrl;
470
+ }
471
+ /** GET /media/files — list user media files. */
472
+ async list(email) {
473
+ const qs = email ? `?email=${encodeURIComponent(email)}` : '';
474
+ const res = await this.t.request('apim', `${this.urls.mediaPath}/files${qs}`);
475
+ return Array.isArray(res) ? res : (res.data ?? []);
476
+ }
477
+ /** DELETE /media/files/:id */
478
+ async delete(fileId) {
479
+ return this.t.request('apim', `${this.urls.mediaPath}/files/${fileId}`, { method: 'DELETE' });
480
+ }
481
+ }
482
+ // ─────────────────────────────────────────────────────────────────────────────
483
+ // Preset module
484
+ // ─────────────────────────────────────────────────────────────────────────────
485
+ class PresetModule {
486
+ constructor(t, urls) {
487
+ this.t = t;
488
+ this.urls = urls;
489
+ }
490
+ async list(email) {
491
+ const qs = email ? `?email=${encodeURIComponent(email)}` : '';
492
+ const res = await this.t.request('apim', `${this.urls.presetPath}${qs}`);
493
+ return Array.isArray(res) ? res : (res.data ?? []);
494
+ }
495
+ async get(id) {
496
+ return this.t.request('apim', `${this.urls.presetPath}/${id}`);
497
+ }
498
+ async create(params) {
499
+ return this.t.request('apim', this.urls.presetPath, {
500
+ method: 'POST',
501
+ body: JSON.stringify(params),
502
+ });
503
+ }
504
+ async update(id, params) {
505
+ return this.t.request('apim', `${this.urls.presetPath}/${id}`, {
506
+ method: 'PUT',
507
+ body: JSON.stringify(params),
508
+ });
509
+ }
510
+ async delete(id) {
511
+ return this.t.request('apim', `${this.urls.presetPath}/${id}`, { method: 'DELETE' });
512
+ }
513
+ async duplicate(id) {
514
+ return this.t.request('apim', `${this.urls.presetPath}/${id}/duplicate`, { method: 'POST' });
515
+ }
516
+ }
517
+ // ─────────────────────────────────────────────────────────────────────────────
518
+ // Agent helpers
519
+ // ─────────────────────────────────────────────────────────────────────────────
520
+ /** Extract a finished video URL from a raw project record. */
521
+ function extractRenderUrl(raw) {
522
+ for (const key of ['videoUrl', 'video_url', 'render_url', 'resultUrl', 'url']) {
523
+ const value = raw[key];
524
+ if (typeof value === 'string' && value.startsWith('https://'))
525
+ return value;
526
+ }
527
+ return null;
528
+ }
529
+ /**
530
+ * Parses a raw SSE stream text. Calls onEvent for each `event:`/`data:` pair.
531
+ * Returns all tool_start toolNames and the first error event payload.
532
+ * Mirrors apps/mobile-app/src/generation/agent-generate-client.ts parseSseEvents.
533
+ */
534
+ function parseSseStream(text, onEvent) {
535
+ const tools = [];
536
+ let error = null;
537
+ let eventName = '';
538
+ for (const line of text.split('\n')) {
539
+ if (line.startsWith('event: ')) {
540
+ eventName = line.slice(7).trim();
541
+ continue;
542
+ }
543
+ if (line.startsWith('data: ')) {
544
+ let data = null;
545
+ try {
546
+ data = JSON.parse(line.slice(6));
547
+ }
548
+ catch {
549
+ continue; // non-JSON data line
550
+ }
551
+ if (onEvent)
552
+ onEvent({ event: eventName, data });
553
+ const toolName = data?.toolName;
554
+ if (eventName === 'tool_start' && typeof toolName === 'string')
555
+ tools.push(toolName);
556
+ if (eventName === 'error' && error === null)
557
+ error = data;
558
+ }
559
+ }
560
+ return { tools, error };
561
+ }
562
+ // ─────────────────────────────────────────────────────────────────────────────
563
+ // Agent module
564
+ // ─────────────────────────────────────────────────────────────────────────────
565
+ class AgentModule {
566
+ constructor(t, urls) {
567
+ this.t = t;
568
+ this.urls = urls;
569
+ }
570
+ /** Creates an empty project to generate into. POST /video-project/create (APIM api-key). */
571
+ async createProject(name) {
572
+ const res = await this.t.request('apim', `${this.urls.videoProjectPath}/create`, {
573
+ method: 'POST',
574
+ body: JSON.stringify({ name }),
575
+ });
576
+ const data = res.data ??
577
+ res;
578
+ const projectId = data.id ?? data.projectId;
579
+ if (typeof projectId !== 'number')
580
+ throw new KvidaiError('UNEXPECTED_RESPONSE', 'project create response has no id', 0);
581
+ return { projectId };
582
+ }
583
+ /**
584
+ * Runs one agent chat turn via SSE stream. POST /agent/generate (APIM api-key).
585
+ * RN-compatible: consumes full response with res.text() after stream closes.
586
+ * onEvent is called for each parsed SSE event as the stream is parsed.
587
+ *
588
+ * Note: the web /api/agent endpoint is origin-gated (not usable by external clients).
589
+ * This method uses the APIM api-key path that external clients can call.
590
+ */
591
+ async generate(input, onEvent) {
592
+ const text = await this.t.requestText('apim', `${this.urls.agentPath}/generate`, {
593
+ method: 'POST',
594
+ headers: { Accept: 'text/event-stream', 'Content-Type': 'application/json' },
595
+ body: JSON.stringify({
596
+ projectId: input.projectId,
597
+ message: input.message,
598
+ chatHistory: input.chatHistory,
599
+ ...(input.attachedFiles && input.attachedFiles.length > 0
600
+ ? { attachedFiles: input.attachedFiles }
601
+ : {}),
602
+ }),
603
+ });
604
+ const { tools, error } = parseSseStream(text, onEvent);
605
+ if (error !== null)
606
+ throw new KvidaiError('AGENT_ERROR', 'the agent reported an error', 0, error);
607
+ return { tools };
608
+ }
609
+ /**
610
+ * Reads the result of an agent turn from the project. GET /video-project/:id (APIM api-key).
611
+ * Call after generate() completes — the composition is the agent's output.
612
+ */
613
+ async getProjectResult(projectId) {
614
+ const res = await this.t.request('apim', `${this.urls.videoProjectPath}/${projectId}`);
615
+ const project = res.data ?? res;
616
+ const composition = project.composition;
617
+ const sceneCount = Object.keys(composition?.items ?? composition?.assets ?? {}).length;
618
+ return {
619
+ projectId,
620
+ renderUrl: extractRenderUrl(project),
621
+ sceneCount,
622
+ composition: project.composition ?? null,
623
+ };
624
+ }
625
+ }
626
+ // ─────────────────────────────────────────────────────────────────────────────
627
+ // KvidaiClient
628
+ // ─────────────────────────────────────────────────────────────────────────────
629
+ /**
630
+ * kvidai SDK client.
631
+ *
632
+ * @example
633
+ * // With existing credentials:
634
+ * const client = new KvidaiClient({ jwt: '<strapi-jwt>', apiKey: '<apim-32hex>' });
635
+ * const { requestId, model } = await client.generation.textToVideo({ prompt: 'Space', model: 'wan' });
636
+ * const result = await client.generation.waitForResult({ requestId, model });
637
+ *
638
+ * @example
639
+ * // Login flow (auto-obtains credentials):
640
+ * const client = new KvidaiClient({});
641
+ * const { jwt, apiKey } = await client.auth.loginAndGetApiKey('user@example.com', 'password');
642
+ * client.setCredentials({ jwt, apiKey });
643
+ */
644
+ class KvidaiClient {
645
+ constructor(options = {}) {
646
+ this.opts = { environment: 'prod', timeoutMs: 30000, ...options };
647
+ const urls = ENV_URLS[this.opts.environment ?? 'prod'];
648
+ this.transport = new Transport(this.opts, urls);
649
+ this.auth = new AuthModule(this.transport, this.opts);
650
+ this.generation = new GenerationModule(this.transport, urls);
651
+ this.media = new MediaModule(this.transport, urls);
652
+ this.preset = new PresetModule(this.transport, urls);
653
+ this.agent = new AgentModule(this.transport, urls);
654
+ }
655
+ /** Update JWT and/or apiKey after login. */
656
+ setCredentials(creds) {
657
+ if (creds.jwt !== undefined)
658
+ this.opts.jwt = creds.jwt;
659
+ if (creds.apiKey !== undefined)
660
+ this.opts.apiKey = creds.apiKey;
661
+ }
662
+ }
663
+ exports.KvidaiClient = KvidaiClient;
664
+ // ─────────────────────────────────────────────────────────────────────────────
665
+ // Utils
666
+ // ─────────────────────────────────────────────────────────────────────────────
667
+ function delay(ms, signal) {
668
+ return new Promise((resolve, reject) => {
669
+ if (signal?.aborted)
670
+ return reject(new KvidaiError('CANCELLED', 'Cancelled', 0));
671
+ const id = setTimeout(resolve, ms);
672
+ signal?.addEventListener('abort', () => {
673
+ clearTimeout(id);
674
+ reject(new KvidaiError('CANCELLED', 'Cancelled', 0));
675
+ }, { once: true });
676
+ });
677
+ }