@escapeaihq/client-core 0.4.0
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/LICENSE +21 -0
- package/README.md +122 -0
- package/dist/api.d.ts +836 -0
- package/dist/api.d.ts.map +1 -0
- package/dist/api.js +781 -0
- package/dist/api.js.map +1 -0
- package/dist/audio.d.ts +278 -0
- package/dist/audio.d.ts.map +1 -0
- package/dist/audio.js +758 -0
- package/dist/audio.js.map +1 -0
- package/dist/audioProtocol.d.ts +101 -0
- package/dist/audioProtocol.d.ts.map +1 -0
- package/dist/audioProtocol.js +62 -0
- package/dist/audioProtocol.js.map +1 -0
- package/dist/index.d.ts +28 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +28 -0
- package/dist/index.js.map +1 -0
- package/dist/visemeGeometry.d.ts +198 -0
- package/dist/visemeGeometry.d.ts.map +1 -0
- package/dist/visemeGeometry.js +297 -0
- package/dist/visemeGeometry.js.map +1 -0
- package/dist/visemeScheduler.d.ts +28 -0
- package/dist/visemeScheduler.d.ts.map +1 -0
- package/dist/visemeScheduler.js +94 -0
- package/dist/visemeScheduler.js.map +1 -0
- package/dist/websocket.d.ts +196 -0
- package/dist/websocket.d.ts.map +1 -0
- package/dist/websocket.js +250 -0
- package/dist/websocket.js.map +1 -0
- package/package.json +40 -0
- package/src/__tests__/api-pollers.test.ts +524 -0
- package/src/__tests__/audio.test.ts +714 -0
- package/src/__tests__/visemeGeometry.test.ts +465 -0
- package/src/__tests__/visemeScheduler.test.ts +256 -0
- package/src/api.ts +1577 -0
- package/src/audio.ts +934 -0
- package/src/audioProtocol.ts +163 -0
- package/src/index.ts +28 -0
- package/src/visemeGeometry.ts +353 -0
- package/src/visemeScheduler.ts +133 -0
- package/src/websocket.ts +385 -0
package/dist/api.js
ADDED
|
@@ -0,0 +1,781 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* API client for the Seer Agent backend
|
|
3
|
+
*/
|
|
4
|
+
export class ApiClient {
|
|
5
|
+
baseURL;
|
|
6
|
+
sessionToken;
|
|
7
|
+
chatApiBaseUrl;
|
|
8
|
+
constructor(baseURL, sessionToken, chatBaseUrl) {
|
|
9
|
+
this.baseURL = baseURL;
|
|
10
|
+
this.sessionToken = sessionToken;
|
|
11
|
+
this.chatApiBaseUrl = chatBaseUrl;
|
|
12
|
+
}
|
|
13
|
+
setSessionToken(token) {
|
|
14
|
+
this.sessionToken = token;
|
|
15
|
+
}
|
|
16
|
+
async request(endpoint, options = {}) {
|
|
17
|
+
return this.makeRequest(this.baseURL, endpoint, options);
|
|
18
|
+
}
|
|
19
|
+
async chatRequest(endpoint, options = {}) {
|
|
20
|
+
return this.makeRequest(this.chatApiBaseUrl, endpoint, options);
|
|
21
|
+
}
|
|
22
|
+
async makeRequest(baseUrl, endpoint, options = {}) {
|
|
23
|
+
const url = `${baseUrl}${endpoint}`;
|
|
24
|
+
const headers = {
|
|
25
|
+
'Content-Type': 'application/json',
|
|
26
|
+
...options.headers,
|
|
27
|
+
};
|
|
28
|
+
// Add authorization header if session token is available
|
|
29
|
+
if (this.sessionToken) {
|
|
30
|
+
headers['Authorization'] = `Bearer ${this.sessionToken}`;
|
|
31
|
+
}
|
|
32
|
+
try {
|
|
33
|
+
const response = await fetch(url, {
|
|
34
|
+
...options,
|
|
35
|
+
headers,
|
|
36
|
+
});
|
|
37
|
+
if (!response.ok) {
|
|
38
|
+
const error = await response.json().catch(() => ({
|
|
39
|
+
detail: `HTTP ${response.status}: ${response.statusText}`,
|
|
40
|
+
}));
|
|
41
|
+
// FastAPI 422 returns detail as an array of validation errors
|
|
42
|
+
const detail = error.detail;
|
|
43
|
+
let message;
|
|
44
|
+
if (Array.isArray(detail)) {
|
|
45
|
+
message = detail.map((e) => e.msg ? `${(e.loc || []).slice(-1).join('.')}: ${e.msg}` : String(e)).join('; ');
|
|
46
|
+
}
|
|
47
|
+
else {
|
|
48
|
+
message = detail || `Request failed: ${response.status}`;
|
|
49
|
+
}
|
|
50
|
+
throw new Error(message);
|
|
51
|
+
}
|
|
52
|
+
// 204 No Content returns no body
|
|
53
|
+
if (response.status === 204) {
|
|
54
|
+
return undefined;
|
|
55
|
+
}
|
|
56
|
+
return await response.json();
|
|
57
|
+
}
|
|
58
|
+
catch (error) {
|
|
59
|
+
console.error('API request failed:', error);
|
|
60
|
+
throw error;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* List all ingestion jobs with optional filtering
|
|
65
|
+
*/
|
|
66
|
+
async listJobs(params) {
|
|
67
|
+
const searchParams = new URLSearchParams();
|
|
68
|
+
if (params?.status)
|
|
69
|
+
searchParams.append('status', params.status);
|
|
70
|
+
if (params?.limit)
|
|
71
|
+
searchParams.append('limit', params.limit.toString());
|
|
72
|
+
if (params?.nextToken)
|
|
73
|
+
searchParams.append('nextToken', params.nextToken);
|
|
74
|
+
const query = searchParams.toString();
|
|
75
|
+
const endpoint = `/api/v1/ingestion/jobs${query ? `?${query}` : ''}`;
|
|
76
|
+
return this.request(endpoint);
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* Get a specific ingestion job by video ID
|
|
80
|
+
*/
|
|
81
|
+
async getJob(videoId) {
|
|
82
|
+
return this.request(`/api/v1/ingestion/jobs/${videoId}`);
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* List succeeded videos (for chat selector)
|
|
86
|
+
*/
|
|
87
|
+
async listSucceededVideos(params) {
|
|
88
|
+
const searchParams = new URLSearchParams();
|
|
89
|
+
if (params?.limit)
|
|
90
|
+
searchParams.append('limit', params.limit.toString());
|
|
91
|
+
if (params?.nextToken)
|
|
92
|
+
searchParams.append('nextToken', params.nextToken);
|
|
93
|
+
const query = searchParams.toString();
|
|
94
|
+
const endpoint = `/api/v1/tools/videos${query ? `?${query}` : ''}`;
|
|
95
|
+
return this.request(endpoint);
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* List staged videos in the ingestion bucket
|
|
99
|
+
*/
|
|
100
|
+
async listVideos(params) {
|
|
101
|
+
const searchParams = new URLSearchParams();
|
|
102
|
+
if (params?.prefix)
|
|
103
|
+
searchParams.append('prefix', params.prefix);
|
|
104
|
+
if (params?.pageSize)
|
|
105
|
+
searchParams.append('pageSize', params.pageSize.toString());
|
|
106
|
+
if (params?.continuationToken)
|
|
107
|
+
searchParams.append('continuationToken', params.continuationToken);
|
|
108
|
+
const query = searchParams.toString();
|
|
109
|
+
const endpoint = `/api/v1/ingestion/videos${query ? `?${query}` : ''}`;
|
|
110
|
+
return this.request(endpoint);
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* Upload a video file with progress tracking
|
|
114
|
+
*/
|
|
115
|
+
async uploadVideo(file, onProgress) {
|
|
116
|
+
const url = `${this.baseURL}/api/v1/ingestion/uploads`;
|
|
117
|
+
return new Promise((resolve, reject) => {
|
|
118
|
+
const xhr = new XMLHttpRequest();
|
|
119
|
+
// Track upload progress
|
|
120
|
+
if (onProgress) {
|
|
121
|
+
xhr.upload.addEventListener('progress', (e) => {
|
|
122
|
+
if (e.lengthComputable) {
|
|
123
|
+
onProgress({
|
|
124
|
+
loaded: e.loaded,
|
|
125
|
+
total: e.total,
|
|
126
|
+
percentage: Math.round((e.loaded / e.total) * 100),
|
|
127
|
+
});
|
|
128
|
+
}
|
|
129
|
+
});
|
|
130
|
+
}
|
|
131
|
+
// Handle completion
|
|
132
|
+
xhr.addEventListener('load', () => {
|
|
133
|
+
if (xhr.status >= 200 && xhr.status < 300) {
|
|
134
|
+
try {
|
|
135
|
+
const response = JSON.parse(xhr.responseText);
|
|
136
|
+
resolve(response);
|
|
137
|
+
}
|
|
138
|
+
catch {
|
|
139
|
+
reject(new Error('Failed to parse upload response'));
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
else {
|
|
143
|
+
try {
|
|
144
|
+
const errorData = JSON.parse(xhr.responseText);
|
|
145
|
+
reject(new Error(errorData.detail || `Upload failed: ${xhr.status}`));
|
|
146
|
+
}
|
|
147
|
+
catch {
|
|
148
|
+
reject(new Error(`Upload failed: ${xhr.status} ${xhr.statusText}`));
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
});
|
|
152
|
+
// Handle errors
|
|
153
|
+
xhr.addEventListener('error', () => {
|
|
154
|
+
reject(new Error('Upload failed due to network error'));
|
|
155
|
+
});
|
|
156
|
+
xhr.addEventListener('abort', () => {
|
|
157
|
+
reject(new Error('Upload aborted'));
|
|
158
|
+
});
|
|
159
|
+
// Prepare form data
|
|
160
|
+
const formData = new FormData();
|
|
161
|
+
formData.append('upload', file);
|
|
162
|
+
const payload = {
|
|
163
|
+
subdirectory: 'web-uploads',
|
|
164
|
+
source: {
|
|
165
|
+
type: 'direct',
|
|
166
|
+
filename: file.name,
|
|
167
|
+
contentType: file.type,
|
|
168
|
+
},
|
|
169
|
+
};
|
|
170
|
+
formData.append('payload', JSON.stringify(payload));
|
|
171
|
+
// Send request
|
|
172
|
+
xhr.open('POST', url);
|
|
173
|
+
// Add authorization header if session token is available
|
|
174
|
+
if (this.sessionToken) {
|
|
175
|
+
xhr.setRequestHeader('Authorization', `Bearer ${this.sessionToken}`);
|
|
176
|
+
}
|
|
177
|
+
xhr.send(formData);
|
|
178
|
+
});
|
|
179
|
+
}
|
|
180
|
+
// ==================== Enrichment API Methods ====================
|
|
181
|
+
/**
|
|
182
|
+
* Trigger Pegasus enrichment analysis on an ingested video
|
|
183
|
+
*/
|
|
184
|
+
async enrichVideo(videoId, config) {
|
|
185
|
+
return this.request(`/api/v1/ingestion/videos/${videoId}/enrichments`, {
|
|
186
|
+
method: 'POST',
|
|
187
|
+
body: JSON.stringify({
|
|
188
|
+
pegasusPrompt: config?.pegasusPrompt,
|
|
189
|
+
pegasusTemperature: config?.pegasusTemperature,
|
|
190
|
+
pegasusMaxTokens: config?.pegasusMaxTokens,
|
|
191
|
+
}),
|
|
192
|
+
});
|
|
193
|
+
}
|
|
194
|
+
/**
|
|
195
|
+
* List all enrichment runs for a video
|
|
196
|
+
*/
|
|
197
|
+
async getEnrichments(videoId) {
|
|
198
|
+
return this.request(`/api/v1/ingestion/videos/${videoId}/enrichments`);
|
|
199
|
+
}
|
|
200
|
+
/**
|
|
201
|
+
* Get a specific enrichment result
|
|
202
|
+
*/
|
|
203
|
+
async getEnrichment(enrichmentId) {
|
|
204
|
+
return this.request(`/api/v1/ingestion/enrichments/${enrichmentId}`);
|
|
205
|
+
}
|
|
206
|
+
/**
|
|
207
|
+
* Delete a video and all associated data across all systems
|
|
208
|
+
*/
|
|
209
|
+
async deleteVideo(videoId, s3Key) {
|
|
210
|
+
const searchParams = new URLSearchParams();
|
|
211
|
+
if (s3Key)
|
|
212
|
+
searchParams.append('s3Key', s3Key);
|
|
213
|
+
const query = searchParams.toString();
|
|
214
|
+
const endpoint = `/api/v1/ingestion/videos/${videoId}${query ? `?${query}` : ''}`;
|
|
215
|
+
return this.request(endpoint, {
|
|
216
|
+
method: 'DELETE',
|
|
217
|
+
});
|
|
218
|
+
}
|
|
219
|
+
/**
|
|
220
|
+
* Stream chat responses with Server-Sent Events
|
|
221
|
+
* Returns a ReadableStreamDefaultReader for processing SSE events
|
|
222
|
+
*/
|
|
223
|
+
async streamChat(request, signal) {
|
|
224
|
+
const url = `${this.chatApiBaseUrl}/api/chat/stream`;
|
|
225
|
+
const headers = {
|
|
226
|
+
'Content-Type': 'application/json',
|
|
227
|
+
};
|
|
228
|
+
// Add authorization header if session token is available
|
|
229
|
+
if (this.sessionToken) {
|
|
230
|
+
headers['Authorization'] = `Bearer ${this.sessionToken}`;
|
|
231
|
+
}
|
|
232
|
+
const response = await fetch(url, {
|
|
233
|
+
method: 'POST',
|
|
234
|
+
headers,
|
|
235
|
+
body: JSON.stringify(request),
|
|
236
|
+
signal,
|
|
237
|
+
});
|
|
238
|
+
if (!response.ok) {
|
|
239
|
+
const error = await response.json().catch(() => ({
|
|
240
|
+
detail: `HTTP ${response.status}: ${response.statusText}`,
|
|
241
|
+
}));
|
|
242
|
+
throw new Error(error.detail || `Chat request failed: ${response.status}`);
|
|
243
|
+
}
|
|
244
|
+
const reader = response.body?.getReader();
|
|
245
|
+
if (!reader) {
|
|
246
|
+
throw new Error('No response body available for streaming');
|
|
247
|
+
}
|
|
248
|
+
return reader;
|
|
249
|
+
}
|
|
250
|
+
// ==================== Persona API Methods ====================
|
|
251
|
+
// Note: Personas are served by the Chat API, not the Tools API
|
|
252
|
+
/**
|
|
253
|
+
* Create a new persona
|
|
254
|
+
*/
|
|
255
|
+
async createPersona(data) {
|
|
256
|
+
return this.chatRequest('/api/v1/personas', {
|
|
257
|
+
method: 'POST',
|
|
258
|
+
body: JSON.stringify(data),
|
|
259
|
+
});
|
|
260
|
+
}
|
|
261
|
+
/**
|
|
262
|
+
* List all personas for the current user
|
|
263
|
+
*/
|
|
264
|
+
async listPersonas(params) {
|
|
265
|
+
const searchParams = new URLSearchParams();
|
|
266
|
+
if (params?.limit)
|
|
267
|
+
searchParams.append('limit', params.limit.toString());
|
|
268
|
+
if (params?.nextToken)
|
|
269
|
+
searchParams.append('nextToken', params.nextToken);
|
|
270
|
+
if (params?.status)
|
|
271
|
+
searchParams.append('status', params.status);
|
|
272
|
+
const query = searchParams.toString();
|
|
273
|
+
const endpoint = `/api/v1/personas${query ? `?${query}` : ''}`;
|
|
274
|
+
return this.chatRequest(endpoint);
|
|
275
|
+
}
|
|
276
|
+
/**
|
|
277
|
+
* Get the default persona for the current user
|
|
278
|
+
*/
|
|
279
|
+
async getDefaultPersona() {
|
|
280
|
+
return this.chatRequest('/api/v1/personas/default');
|
|
281
|
+
}
|
|
282
|
+
/**
|
|
283
|
+
* Get a specific persona by ID
|
|
284
|
+
*/
|
|
285
|
+
async getPersona(personaId) {
|
|
286
|
+
return this.chatRequest(`/api/v1/personas/${personaId}`);
|
|
287
|
+
}
|
|
288
|
+
/**
|
|
289
|
+
* Update a persona
|
|
290
|
+
*/
|
|
291
|
+
async updatePersona(personaId, data) {
|
|
292
|
+
return this.chatRequest(`/api/v1/personas/${personaId}`, {
|
|
293
|
+
method: 'PATCH',
|
|
294
|
+
body: JSON.stringify(data),
|
|
295
|
+
});
|
|
296
|
+
}
|
|
297
|
+
/**
|
|
298
|
+
* Delete a persona
|
|
299
|
+
*/
|
|
300
|
+
async deletePersona(personaId) {
|
|
301
|
+
await this.chatRequest(`/api/v1/personas/${personaId}`, {
|
|
302
|
+
method: 'DELETE',
|
|
303
|
+
});
|
|
304
|
+
}
|
|
305
|
+
/**
|
|
306
|
+
* AI-synthesize persona definitions from enrichment data.
|
|
307
|
+
* Does NOT persist — returns suggestions to create individually.
|
|
308
|
+
*/
|
|
309
|
+
async synthesizePersonas(videoId, enrichmentData, maxPersonas = 10) {
|
|
310
|
+
return this.chatRequest('/api/v1/personas/synthesize', {
|
|
311
|
+
method: 'POST',
|
|
312
|
+
headers: { 'Content-Type': 'application/json' },
|
|
313
|
+
body: JSON.stringify({
|
|
314
|
+
video_id: videoId,
|
|
315
|
+
enrichment_data: enrichmentData,
|
|
316
|
+
max_personas: maxPersonas,
|
|
317
|
+
}),
|
|
318
|
+
});
|
|
319
|
+
}
|
|
320
|
+
// ==================== Image API Methods ====================
|
|
321
|
+
// Note: Images are served by the Chat API
|
|
322
|
+
async listImages(params) {
|
|
323
|
+
const searchParams = new URLSearchParams();
|
|
324
|
+
if (params?.category)
|
|
325
|
+
searchParams.append('category', params.category);
|
|
326
|
+
if (params?.videoId)
|
|
327
|
+
searchParams.append('videoId', params.videoId);
|
|
328
|
+
if (params?.limit)
|
|
329
|
+
searchParams.append('limit', params.limit.toString());
|
|
330
|
+
if (params?.nextToken)
|
|
331
|
+
searchParams.append('nextToken', params.nextToken);
|
|
332
|
+
const query = searchParams.toString();
|
|
333
|
+
const endpoint = `/api/v1/images${query ? `?${query}` : ''}`;
|
|
334
|
+
return this.chatRequest(endpoint);
|
|
335
|
+
}
|
|
336
|
+
async getImage(imageId, options = {}) {
|
|
337
|
+
return this.chatRequest(`/api/v1/images/${imageId}`, {
|
|
338
|
+
signal: options.signal,
|
|
339
|
+
});
|
|
340
|
+
}
|
|
341
|
+
async updateImage(imageId, data) {
|
|
342
|
+
return this.chatRequest(`/api/v1/images/${imageId}`, {
|
|
343
|
+
method: 'PATCH',
|
|
344
|
+
body: JSON.stringify(data),
|
|
345
|
+
});
|
|
346
|
+
}
|
|
347
|
+
async deleteImage(imageId) {
|
|
348
|
+
await this.chatRequest(`/api/v1/images/${imageId}`, {
|
|
349
|
+
method: 'DELETE',
|
|
350
|
+
});
|
|
351
|
+
}
|
|
352
|
+
async uploadImage(file, metadata) {
|
|
353
|
+
const url = `${this.chatApiBaseUrl}/api/v1/images/upload`;
|
|
354
|
+
const formData = new FormData();
|
|
355
|
+
formData.append('upload', file);
|
|
356
|
+
if (metadata?.category)
|
|
357
|
+
formData.append('category', metadata.category);
|
|
358
|
+
if (metadata?.tags)
|
|
359
|
+
formData.append('tags', metadata.tags);
|
|
360
|
+
if (metadata?.sourceVideoId)
|
|
361
|
+
formData.append('source_video_id', metadata.sourceVideoId);
|
|
362
|
+
if (metadata?.sourceEntity)
|
|
363
|
+
formData.append('source_entity', metadata.sourceEntity);
|
|
364
|
+
const headers = {};
|
|
365
|
+
if (this.sessionToken) {
|
|
366
|
+
headers['Authorization'] = `Bearer ${this.sessionToken}`;
|
|
367
|
+
}
|
|
368
|
+
const response = await fetch(url, {
|
|
369
|
+
method: 'POST',
|
|
370
|
+
headers,
|
|
371
|
+
body: formData,
|
|
372
|
+
});
|
|
373
|
+
if (!response.ok) {
|
|
374
|
+
const error = await response.json().catch(() => ({ detail: `Upload failed: ${response.status}` }));
|
|
375
|
+
throw new Error(error.detail || `Upload failed: ${response.status}`);
|
|
376
|
+
}
|
|
377
|
+
return response.json();
|
|
378
|
+
}
|
|
379
|
+
/**
|
|
380
|
+
* Kick off async character generation. Returns a 202 envelope with
|
|
381
|
+
* `characterImageId` and `statusUrl`. Caller must poll
|
|
382
|
+
* `getImage(characterImageId)` (or use `pollImageUntilDone()`) until
|
|
383
|
+
* `status` flips from `'pending'` to `'complete'` or `'failed'`.
|
|
384
|
+
*
|
|
385
|
+
* Converted from synchronous because Gemini regularly exceeds
|
|
386
|
+
* CloudFront's 60s `OriginReadTimeout` and the browser would see a
|
|
387
|
+
* 504 even though the backend completed.
|
|
388
|
+
*/
|
|
389
|
+
async generateCharacter(params) {
|
|
390
|
+
return this.request('/api/v1/tools/generate-character', {
|
|
391
|
+
method: 'POST',
|
|
392
|
+
body: JSON.stringify(params),
|
|
393
|
+
});
|
|
394
|
+
}
|
|
395
|
+
/**
|
|
396
|
+
* Extract a raw video frame at an entity's location or a specific
|
|
397
|
+
* timestamp. Synchronous (no polling) — the path is ffmpeg-only with
|
|
398
|
+
* no AI generation, so it returns 201 with the result inline.
|
|
399
|
+
*
|
|
400
|
+
* Pass `options.signal` to abort the in-flight request when the
|
|
401
|
+
* consumer component unmounts.
|
|
402
|
+
*/
|
|
403
|
+
async extractImage(req, options = {}) {
|
|
404
|
+
return this.request('/api/v1/tools/extract-image', {
|
|
405
|
+
method: 'POST',
|
|
406
|
+
body: JSON.stringify(req),
|
|
407
|
+
signal: options.signal,
|
|
408
|
+
});
|
|
409
|
+
}
|
|
410
|
+
/**
|
|
411
|
+
* Extract an entity frame and regenerate it with a Gemini Flash Image
|
|
412
|
+
* style prompt. Synchronous from the client's perspective; backend
|
|
413
|
+
* runs ffmpeg + Gemini in one request and returns 201 with the result.
|
|
414
|
+
*
|
|
415
|
+
* Gemini calls regularly take several seconds — pass `options.signal`
|
|
416
|
+
* so a component unmount mid-call cancels the underlying fetch instead
|
|
417
|
+
* of leaving a dangling Promise.
|
|
418
|
+
*/
|
|
419
|
+
async regenerateImage(req, options = {}) {
|
|
420
|
+
return this.request('/api/v1/tools/regenerate-image', {
|
|
421
|
+
method: 'POST',
|
|
422
|
+
body: JSON.stringify(req),
|
|
423
|
+
signal: options.signal,
|
|
424
|
+
});
|
|
425
|
+
}
|
|
426
|
+
/**
|
|
427
|
+
* Poll `GET /api/v1/images/{imageId}` until the row's `status` flips
|
|
428
|
+
* away from `'pending'`. Resolves with the completed record (status
|
|
429
|
+
* `'complete'`); throws on `'failed'` (with the row's
|
|
430
|
+
* `error_message`) or after `timeoutMs` elapses.
|
|
431
|
+
*
|
|
432
|
+
* Pass `signal` to cancel cleanly when the page unmounts. AbortError
|
|
433
|
+
* is rethrown so callers can distinguish cancellation from real
|
|
434
|
+
* failures.
|
|
435
|
+
*
|
|
436
|
+
* Cadence is 5s — character generation runs ~30-60s, so a 2s poll
|
|
437
|
+
* (the per-viseme cadence) would burn 25 wasted requests per
|
|
438
|
+
* generation. The 5s cadence still surfaces completion within one
|
|
439
|
+
* user-perceived "tick" past the actual finish.
|
|
440
|
+
*/
|
|
441
|
+
async pollImageUntilDone(imageId, options = {}) {
|
|
442
|
+
const intervalMs = options.intervalMs ?? 5000;
|
|
443
|
+
const timeoutMs = options.timeoutMs ?? 180_000;
|
|
444
|
+
const deadline = Date.now() + timeoutMs;
|
|
445
|
+
while (true) {
|
|
446
|
+
if (options.signal?.aborted) {
|
|
447
|
+
throw new DOMException('Polling aborted', 'AbortError');
|
|
448
|
+
}
|
|
449
|
+
const record = await this.getImage(imageId, { signal: options.signal });
|
|
450
|
+
const status = record.status ?? 'complete';
|
|
451
|
+
if (status === 'complete') {
|
|
452
|
+
return record;
|
|
453
|
+
}
|
|
454
|
+
if (status === 'failed') {
|
|
455
|
+
throw new Error(record.error_message ?? 'Image generation failed');
|
|
456
|
+
}
|
|
457
|
+
if (Date.now() >= deadline) {
|
|
458
|
+
throw new Error(`Image generation timed out after ${Math.round(timeoutMs / 1000)}s`);
|
|
459
|
+
}
|
|
460
|
+
await new Promise((resolve, reject) => {
|
|
461
|
+
const timer = setTimeout(() => {
|
|
462
|
+
options.signal?.removeEventListener('abort', onAbort);
|
|
463
|
+
resolve();
|
|
464
|
+
}, intervalMs);
|
|
465
|
+
const onAbort = () => {
|
|
466
|
+
clearTimeout(timer);
|
|
467
|
+
reject(new DOMException('Polling aborted', 'AbortError'));
|
|
468
|
+
};
|
|
469
|
+
options.signal?.addEventListener('abort', onAbort, { once: true });
|
|
470
|
+
});
|
|
471
|
+
}
|
|
472
|
+
}
|
|
473
|
+
// ==================== Session API Methods ====================
|
|
474
|
+
// Note: Sessions are served by the Chat API, not the Tools API
|
|
475
|
+
/**
|
|
476
|
+
* Create a new chat session
|
|
477
|
+
*/
|
|
478
|
+
async createSession(data) {
|
|
479
|
+
return this.chatRequest('/api/v1/sessions', {
|
|
480
|
+
method: 'POST',
|
|
481
|
+
body: JSON.stringify(data),
|
|
482
|
+
});
|
|
483
|
+
}
|
|
484
|
+
/**
|
|
485
|
+
* List all sessions for the current user
|
|
486
|
+
*/
|
|
487
|
+
async listSessions(params) {
|
|
488
|
+
const searchParams = new URLSearchParams();
|
|
489
|
+
if (params?.limit)
|
|
490
|
+
searchParams.append('limit', params.limit.toString());
|
|
491
|
+
if (params?.nextToken)
|
|
492
|
+
searchParams.append('nextToken', params.nextToken);
|
|
493
|
+
if (params?.personaId)
|
|
494
|
+
searchParams.append('personaId', params.personaId);
|
|
495
|
+
const query = searchParams.toString();
|
|
496
|
+
const endpoint = `/api/v1/sessions${query ? `?${query}` : ''}`;
|
|
497
|
+
return this.chatRequest(endpoint);
|
|
498
|
+
}
|
|
499
|
+
/**
|
|
500
|
+
* Get a specific session by ID
|
|
501
|
+
*/
|
|
502
|
+
async getSession(sessionId) {
|
|
503
|
+
return this.chatRequest(`/api/v1/sessions/${sessionId}`);
|
|
504
|
+
}
|
|
505
|
+
/**
|
|
506
|
+
* Add a message to a session
|
|
507
|
+
*/
|
|
508
|
+
async addMessageToSession(sessionId, data) {
|
|
509
|
+
return this.chatRequest(`/api/v1/sessions/${sessionId}/messages`, {
|
|
510
|
+
method: 'PUT',
|
|
511
|
+
body: JSON.stringify(data),
|
|
512
|
+
});
|
|
513
|
+
}
|
|
514
|
+
/**
|
|
515
|
+
* Clear all messages from a session
|
|
516
|
+
*/
|
|
517
|
+
async clearSessionMessages(sessionId) {
|
|
518
|
+
await this.chatRequest(`/api/v1/sessions/${sessionId}/messages`, {
|
|
519
|
+
method: 'DELETE',
|
|
520
|
+
});
|
|
521
|
+
}
|
|
522
|
+
/**
|
|
523
|
+
* Delete a session
|
|
524
|
+
*/
|
|
525
|
+
async deleteSession(sessionId) {
|
|
526
|
+
await this.chatRequest(`/api/v1/sessions/${sessionId}`, {
|
|
527
|
+
method: 'DELETE',
|
|
528
|
+
});
|
|
529
|
+
}
|
|
530
|
+
/**
|
|
531
|
+
* Get transcript for a video, optionally filtered by time range
|
|
532
|
+
*/
|
|
533
|
+
async getTranscript(videoId, t0, t1) {
|
|
534
|
+
return this.request('/api/v1/tools/get-transcript', {
|
|
535
|
+
method: 'POST',
|
|
536
|
+
body: JSON.stringify({ videoId, t0, t1 }),
|
|
537
|
+
});
|
|
538
|
+
}
|
|
539
|
+
/**
|
|
540
|
+
* Search dialog within a video by keyword or phrase
|
|
541
|
+
*/
|
|
542
|
+
async searchDialog(videoId, query, limit) {
|
|
543
|
+
return this.request('/api/v1/tools/dialog-search', {
|
|
544
|
+
method: 'POST',
|
|
545
|
+
body: JSON.stringify({ videoId, query, limit: limit ?? 10 }),
|
|
546
|
+
});
|
|
547
|
+
}
|
|
548
|
+
// ==================== Graph Editor API Methods ====================
|
|
549
|
+
async getVideoGraph(videoId) {
|
|
550
|
+
return this.request(`/api/v1/tools/graph/${encodeURIComponent(videoId)}`);
|
|
551
|
+
}
|
|
552
|
+
async updateGraphNode(data) {
|
|
553
|
+
return this.request('/api/v1/tools/graph/nodes', {
|
|
554
|
+
method: 'PATCH',
|
|
555
|
+
body: JSON.stringify(data),
|
|
556
|
+
});
|
|
557
|
+
}
|
|
558
|
+
async deleteGraphNode(data) {
|
|
559
|
+
return this.request('/api/v1/tools/graph/nodes', {
|
|
560
|
+
method: 'DELETE',
|
|
561
|
+
body: JSON.stringify(data),
|
|
562
|
+
});
|
|
563
|
+
}
|
|
564
|
+
async updateGraphEdge(data) {
|
|
565
|
+
return this.request('/api/v1/tools/graph/edges', {
|
|
566
|
+
method: 'PATCH',
|
|
567
|
+
body: JSON.stringify(data),
|
|
568
|
+
});
|
|
569
|
+
}
|
|
570
|
+
async deleteGraphEdge(data) {
|
|
571
|
+
return this.request('/api/v1/tools/graph/edges', {
|
|
572
|
+
method: 'DELETE',
|
|
573
|
+
body: JSON.stringify(data),
|
|
574
|
+
});
|
|
575
|
+
}
|
|
576
|
+
/**
|
|
577
|
+
* Fetch a persona's viseme bundle by ID. Returns the full record including
|
|
578
|
+
* inline body_svg and mouth_paths when status === 'complete'.
|
|
579
|
+
*
|
|
580
|
+
* Pass `signal` to abort the in-flight request — used by the
|
|
581
|
+
* persona-tuner poll loop so a drawer-close mid-fetch unblocks
|
|
582
|
+
* immediately rather than waiting for the response.
|
|
583
|
+
*/
|
|
584
|
+
async getVisemeBundle(personaId, bundleId, options = {}) {
|
|
585
|
+
return this.chatRequest(`/api/v1/personas/${personaId}/viseme-bundle/${bundleId}`, { signal: options.signal });
|
|
586
|
+
}
|
|
587
|
+
/**
|
|
588
|
+
* Fetch a bundle's body SVG bytes from the backend's S3 proxy. Used as a
|
|
589
|
+
* fallback when the bundle row's inline body_svg is null because the SVG
|
|
590
|
+
* exceeded the DynamoDB inline cap.
|
|
591
|
+
*/
|
|
592
|
+
async getVisemeBundleBodySvg(personaId, bundleId) {
|
|
593
|
+
const url = `${this.chatApiBaseUrl}/api/v1/personas/${personaId}/viseme-bundle/${bundleId}/body.svg`;
|
|
594
|
+
const headers = {};
|
|
595
|
+
if (this.sessionToken) {
|
|
596
|
+
headers['Authorization'] = `Bearer ${this.sessionToken}`;
|
|
597
|
+
}
|
|
598
|
+
const response = await fetch(url, { headers });
|
|
599
|
+
if (!response.ok) {
|
|
600
|
+
throw new Error(`Failed to fetch body SVG: HTTP ${response.status}`);
|
|
601
|
+
}
|
|
602
|
+
return await response.text();
|
|
603
|
+
}
|
|
604
|
+
/**
|
|
605
|
+
* Fetch a single viseme PNG and return a blob URL for use as `<img src>`.
|
|
606
|
+
* The backend proxy adds the auth header; <img> tags can't, so we hop
|
|
607
|
+
* through fetch + URL.createObjectURL. Caller is responsible for revoking
|
|
608
|
+
* the URL when the bundle is no longer in use.
|
|
609
|
+
*/
|
|
610
|
+
async getVisemeBundleVisemePng(personaId, bundleId, viseme,
|
|
611
|
+
/** Optional cache-bust suffix appended as a query string. */
|
|
612
|
+
cacheKey) {
|
|
613
|
+
const path = `/api/v1/personas/${personaId}/viseme-bundle/${bundleId}/visemes/${encodeURIComponent(viseme)}.png`;
|
|
614
|
+
const url = `${this.chatApiBaseUrl}${path}${cacheKey ? `?v=${encodeURIComponent(cacheKey)}` : ''}`;
|
|
615
|
+
const headers = {};
|
|
616
|
+
if (this.sessionToken) {
|
|
617
|
+
headers['Authorization'] = `Bearer ${this.sessionToken}`;
|
|
618
|
+
}
|
|
619
|
+
const response = await fetch(url, { headers });
|
|
620
|
+
if (!response.ok) {
|
|
621
|
+
throw new Error(`Failed to fetch viseme PNG (${viseme}): HTTP ${response.status}`);
|
|
622
|
+
}
|
|
623
|
+
const blob = await response.blob();
|
|
624
|
+
return URL.createObjectURL(blob);
|
|
625
|
+
}
|
|
626
|
+
/**
|
|
627
|
+
* Persona-tuner: GET defaults for the 11 viseme prompt descriptions.
|
|
628
|
+
*/
|
|
629
|
+
async getVisemePromptDefaults() {
|
|
630
|
+
return this.chatRequest('/api/v1/personas/viseme-prompts/defaults');
|
|
631
|
+
}
|
|
632
|
+
/**
|
|
633
|
+
* Persona-tuner: per-persona prompts as
|
|
634
|
+
* `{viseme: {default, override, effective}}`. Returns 11 entries.
|
|
635
|
+
*/
|
|
636
|
+
async getPersonaVisemePrompts(personaId) {
|
|
637
|
+
return this.chatRequest(`/api/v1/personas/${personaId}/viseme-prompts`);
|
|
638
|
+
}
|
|
639
|
+
/**
|
|
640
|
+
* Persona-tuner: set or clear ONE viseme's description override.
|
|
641
|
+
* Pass `description: null` (or empty string) to clear the override.
|
|
642
|
+
* Does NOT trigger regeneration — call regenerateBundleViseme for that.
|
|
643
|
+
*/
|
|
644
|
+
async patchPersonaVisemePrompts(personaId, body) {
|
|
645
|
+
return this.chatRequest(`/api/v1/personas/${personaId}/viseme-prompts`, { method: 'PATCH', body: JSON.stringify(body) });
|
|
646
|
+
}
|
|
647
|
+
/**
|
|
648
|
+
* Persona-tuner: replace (or clear) the persona's full visual
|
|
649
|
+
* overrides blob. PUT semantics: the body IS the new full state.
|
|
650
|
+
* Pass `null` to clear. Backend validates per-field bounds + rejects
|
|
651
|
+
* unknown keys (422 on bad input).
|
|
652
|
+
*/
|
|
653
|
+
async putPersonaVisualOverrides(personaId, overrides) {
|
|
654
|
+
return this.chatRequest(`/api/v1/personas/${personaId}/visual-overrides`, { method: 'PUT', body: JSON.stringify({ visual_overrides: overrides }) });
|
|
655
|
+
}
|
|
656
|
+
/**
|
|
657
|
+
* Persona-tuner: kick off async regeneration of ONE viseme's PNG (and
|
|
658
|
+
* its mouth path). Optional `description` sets the override before the
|
|
659
|
+
* BackgroundTask starts. Returns 202 immediately with a status_url —
|
|
660
|
+
* poll `getVisemeBundle` and watch `viseme_regen_status[viseme]` until
|
|
661
|
+
* it transitions to `complete` or `failed`.
|
|
662
|
+
*/
|
|
663
|
+
async regenerateBundleViseme(personaId, bundleId, viseme, body = {}) {
|
|
664
|
+
return this.chatRequest(`/api/v1/personas/${personaId}/viseme-bundle/${bundleId}/visemes/${encodeURIComponent(viseme)}/regenerate`, { method: 'POST', body: JSON.stringify(body) });
|
|
665
|
+
}
|
|
666
|
+
/**
|
|
667
|
+
* Poll `getVisemeBundle` until `viseme_regen_status[viseme]` reaches
|
|
668
|
+
* a terminal state (`complete` or `failed`). Resolves with the final
|
|
669
|
+
* bundle record. Times out after `timeoutMs` (default 240s — covers
|
|
670
|
+
* the worst observed Gemini wall-clock plus retries).
|
|
671
|
+
*
|
|
672
|
+
* Pass `signal` to cancel cleanly when the drawer closes or the user
|
|
673
|
+
* switches personas mid-poll. AbortError is rethrown so callers can
|
|
674
|
+
* distinguish cancellation from real failures.
|
|
675
|
+
*/
|
|
676
|
+
async pollVisemeRegenUntilDone(personaId, bundleId, viseme, options = {}) {
|
|
677
|
+
// Per-viseme regen runs ~5-30s, so a flat 2s poll surfaces
|
|
678
|
+
// completion within ~1 user-perceived "tick" without burning
|
|
679
|
+
// bandwidth. Bundle-level generation (which takes 40-60s) polls
|
|
680
|
+
// at 5s in chat-ws/page.tsx. Exponential backoff isn't worth the
|
|
681
|
+
// complexity at this cadence — see specs/technical-debt.md.
|
|
682
|
+
const intervalMs = options.intervalMs ?? 2000;
|
|
683
|
+
const timeoutMs = options.timeoutMs ?? 240_000;
|
|
684
|
+
const deadline = Date.now() + timeoutMs;
|
|
685
|
+
while (true) {
|
|
686
|
+
if (options.signal?.aborted) {
|
|
687
|
+
throw new DOMException('Polling aborted', 'AbortError');
|
|
688
|
+
}
|
|
689
|
+
const record = await this.getVisemeBundle(personaId, bundleId, {
|
|
690
|
+
signal: options.signal,
|
|
691
|
+
});
|
|
692
|
+
const entry = record.viseme_regen_status?.[viseme];
|
|
693
|
+
// Only resolve on an explicit terminal state. A missing entry
|
|
694
|
+
// here is the eventually-consistent-read case: the POST claimed
|
|
695
|
+
// the lock, but the GET read an older snapshot that hasn't yet
|
|
696
|
+
// surfaced the new pending entry. Returning prematurely would
|
|
697
|
+
// hand the caller stale bundle data and stop polling before the
|
|
698
|
+
// BackgroundTask actually finishes. The overall timeout below
|
|
699
|
+
// catches the truly-stuck case.
|
|
700
|
+
if (entry?.status === 'complete') {
|
|
701
|
+
return record;
|
|
702
|
+
}
|
|
703
|
+
if (entry?.status === 'failed') {
|
|
704
|
+
const detail = entry.error_message ?? 'Regeneration failed';
|
|
705
|
+
throw new Error(detail);
|
|
706
|
+
}
|
|
707
|
+
if (Date.now() >= deadline) {
|
|
708
|
+
throw new Error(`Regeneration timed out after ${Math.round(timeoutMs / 1000)}s`);
|
|
709
|
+
}
|
|
710
|
+
await new Promise((resolve, reject) => {
|
|
711
|
+
const timer = setTimeout(() => {
|
|
712
|
+
options.signal?.removeEventListener('abort', onAbort);
|
|
713
|
+
resolve();
|
|
714
|
+
}, intervalMs);
|
|
715
|
+
const onAbort = () => {
|
|
716
|
+
clearTimeout(timer);
|
|
717
|
+
reject(new DOMException('Polling aborted', 'AbortError'));
|
|
718
|
+
};
|
|
719
|
+
options.signal?.addEventListener('abort', onAbort, { once: true });
|
|
720
|
+
});
|
|
721
|
+
}
|
|
722
|
+
}
|
|
723
|
+
/**
|
|
724
|
+
* Kick off async generation of a viseme bundle for a persona.
|
|
725
|
+
* Returns 202 with a bundle_id; poll getVisemeBundle until status='complete'.
|
|
726
|
+
*/
|
|
727
|
+
async createVisemeBundle(personaId, sourceImageId) {
|
|
728
|
+
return this.chatRequest(`/api/v1/personas/${personaId}/viseme-bundle`, {
|
|
729
|
+
method: 'POST',
|
|
730
|
+
body: JSON.stringify({ source_image_id: sourceImageId }),
|
|
731
|
+
});
|
|
732
|
+
}
|
|
733
|
+
/**
|
|
734
|
+
* Poll `getVisemeBundle` until the bundle's overall `status` reaches a
|
|
735
|
+
* terminal state (`'complete'` or `'failed'`). Use after
|
|
736
|
+
* `createVisemeBundle` for whole-bundle generation;
|
|
737
|
+
* `pollVisemeRegenUntilDone` covers single-viseme regeneration.
|
|
738
|
+
*
|
|
739
|
+
* Cadence is 5s — bundle assembly runs ~40-60s, so a 2s poll (the
|
|
740
|
+
* per-viseme cadence) would burn ~25 wasted requests per bundle.
|
|
741
|
+
* Mirrors `pollImageUntilDone`'s shape; `signal` cancels cleanly when
|
|
742
|
+
* the page unmounts.
|
|
743
|
+
*/
|
|
744
|
+
async pollVisemeBundleUntilDone(personaId, bundleId, options = {}) {
|
|
745
|
+
const intervalMs = options.intervalMs ?? 5000;
|
|
746
|
+
const timeoutMs = options.timeoutMs ?? 240_000;
|
|
747
|
+
const deadline = Date.now() + timeoutMs;
|
|
748
|
+
while (true) {
|
|
749
|
+
if (options.signal?.aborted) {
|
|
750
|
+
throw new DOMException('Polling aborted', 'AbortError');
|
|
751
|
+
}
|
|
752
|
+
const record = await this.getVisemeBundle(personaId, bundleId, {
|
|
753
|
+
signal: options.signal,
|
|
754
|
+
});
|
|
755
|
+
// VisemeBundleRecord.status is non-optional in the type, so no
|
|
756
|
+
// `?? 'complete'` fallback is needed here (unlike pollImageUntilDone,
|
|
757
|
+
// where ImageRecord.status is optional for pre-async-conversion rows).
|
|
758
|
+
if (record.status === 'complete') {
|
|
759
|
+
return record;
|
|
760
|
+
}
|
|
761
|
+
if (record.status === 'failed') {
|
|
762
|
+
throw new Error(record.error_message ?? 'Bundle generation failed');
|
|
763
|
+
}
|
|
764
|
+
if (Date.now() >= deadline) {
|
|
765
|
+
throw new Error(`Bundle generation timed out after ${Math.round(timeoutMs / 1000)}s`);
|
|
766
|
+
}
|
|
767
|
+
await new Promise((resolve, reject) => {
|
|
768
|
+
const timer = setTimeout(() => {
|
|
769
|
+
options.signal?.removeEventListener('abort', onAbort);
|
|
770
|
+
resolve();
|
|
771
|
+
}, intervalMs);
|
|
772
|
+
const onAbort = () => {
|
|
773
|
+
clearTimeout(timer);
|
|
774
|
+
reject(new DOMException('Polling aborted', 'AbortError'));
|
|
775
|
+
};
|
|
776
|
+
options.signal?.addEventListener('abort', onAbort, { once: true });
|
|
777
|
+
});
|
|
778
|
+
}
|
|
779
|
+
}
|
|
780
|
+
}
|
|
781
|
+
//# sourceMappingURL=api.js.map
|