@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.
Files changed (42) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +122 -0
  3. package/dist/api.d.ts +836 -0
  4. package/dist/api.d.ts.map +1 -0
  5. package/dist/api.js +781 -0
  6. package/dist/api.js.map +1 -0
  7. package/dist/audio.d.ts +278 -0
  8. package/dist/audio.d.ts.map +1 -0
  9. package/dist/audio.js +758 -0
  10. package/dist/audio.js.map +1 -0
  11. package/dist/audioProtocol.d.ts +101 -0
  12. package/dist/audioProtocol.d.ts.map +1 -0
  13. package/dist/audioProtocol.js +62 -0
  14. package/dist/audioProtocol.js.map +1 -0
  15. package/dist/index.d.ts +28 -0
  16. package/dist/index.d.ts.map +1 -0
  17. package/dist/index.js +28 -0
  18. package/dist/index.js.map +1 -0
  19. package/dist/visemeGeometry.d.ts +198 -0
  20. package/dist/visemeGeometry.d.ts.map +1 -0
  21. package/dist/visemeGeometry.js +297 -0
  22. package/dist/visemeGeometry.js.map +1 -0
  23. package/dist/visemeScheduler.d.ts +28 -0
  24. package/dist/visemeScheduler.d.ts.map +1 -0
  25. package/dist/visemeScheduler.js +94 -0
  26. package/dist/visemeScheduler.js.map +1 -0
  27. package/dist/websocket.d.ts +196 -0
  28. package/dist/websocket.d.ts.map +1 -0
  29. package/dist/websocket.js +250 -0
  30. package/dist/websocket.js.map +1 -0
  31. package/package.json +40 -0
  32. package/src/__tests__/api-pollers.test.ts +524 -0
  33. package/src/__tests__/audio.test.ts +714 -0
  34. package/src/__tests__/visemeGeometry.test.ts +465 -0
  35. package/src/__tests__/visemeScheduler.test.ts +256 -0
  36. package/src/api.ts +1577 -0
  37. package/src/audio.ts +934 -0
  38. package/src/audioProtocol.ts +163 -0
  39. package/src/index.ts +28 -0
  40. package/src/visemeGeometry.ts +353 -0
  41. package/src/visemeScheduler.ts +133 -0
  42. package/src/websocket.ts +385 -0
package/src/api.ts ADDED
@@ -0,0 +1,1577 @@
1
+ /**
2
+ * API client for the Seer Agent backend
3
+ */
4
+
5
+ import type { AudioFormat } from './audioProtocol';
6
+ import type { Citation } from './websocket';
7
+
8
+ export interface IngestionJob {
9
+ jobId: string;
10
+ videoId: string;
11
+ status: 'PENDING' | 'RUNNING' | 'SUCCEEDED' | 'FAILED';
12
+ startedAt?: string;
13
+ updatedAt?: string;
14
+ completedAt?: string;
15
+ shotsDetected?: number;
16
+ videoEmbeddingWritten?: boolean;
17
+ pegasusEnrichmentWritten?: boolean;
18
+ graphNodesWritten?: number;
19
+ graphEdgesWritten?: number;
20
+ s3Bucket?: string;
21
+ s3Key?: string;
22
+ errorMessage?: string;
23
+ videoDurationSeconds?: number;
24
+ transcribeJobName?: string;
25
+ transcriptWritten?: boolean;
26
+ transcriptFailed?: boolean;
27
+ transcriptS3Uri?: string;
28
+ dialogLinesWritten?: number;
29
+ }
30
+
31
+ export interface ListJobsResponse {
32
+ traceId: string;
33
+ results: IngestionJob[];
34
+ nextToken?: string | null;
35
+ }
36
+
37
+ export interface ApiError {
38
+ detail: string;
39
+ traceId?: string;
40
+ }
41
+
42
+ export interface UploadResponse {
43
+ traceId: string;
44
+ videoId: string;
45
+ s3Bucket: string;
46
+ s3Key: string;
47
+ jobStatusUrl: string;
48
+ uploadedAt: string;
49
+ }
50
+
51
+ export interface VideoListingEntry {
52
+ videoId: string;
53
+ filename: string;
54
+ key: string;
55
+ size: number;
56
+ etag?: string | null;
57
+ lastModified: string;
58
+ downloadUrl?: string | null;
59
+ streamUrl?: string | null;
60
+ durationSeconds?: number | null;
61
+ }
62
+
63
+ export interface ListVideosResponse {
64
+ traceId: string;
65
+ results: VideoListingEntry[];
66
+ nextToken?: string | null;
67
+ }
68
+
69
+ export type UploadProgressCallback = (progress: {
70
+ loaded: number;
71
+ total: number;
72
+ percentage: number;
73
+ }) => void;
74
+
75
+ export interface PegasusConfig {
76
+ pegasusPrompt?: string;
77
+ pegasusTemperature?: number;
78
+ pegasusMaxTokens?: number;
79
+ }
80
+
81
+ export interface EnrichVideoResponse {
82
+ traceId: string;
83
+ enrichmentId: string;
84
+ videoId: string;
85
+ jobId: string;
86
+ status: string;
87
+ }
88
+
89
+ export interface EnrichmentRecord {
90
+ enrichmentId: string;
91
+ videoId: string;
92
+ jobId: string;
93
+ status: string;
94
+ pegasusPrompt?: string;
95
+ pegasusTemperature?: number;
96
+ pegasusMaxTokens?: number;
97
+ result?: Record<string, unknown>;
98
+ createdAt: string;
99
+ completedAt?: string;
100
+ errorMessage?: string;
101
+ }
102
+
103
+ export interface ListEnrichmentsResponse {
104
+ traceId: string;
105
+ results: EnrichmentRecord[];
106
+ }
107
+
108
+ export interface VideoDeletionStats {
109
+ qdrant: boolean;
110
+ neo4jNodes: number;
111
+ neo4jRelationships: number;
112
+ s3Objects: number;
113
+ dynamodbRecords: number;
114
+ }
115
+
116
+ export interface VideoDeletionResponse {
117
+ traceId: string;
118
+ videoId: string;
119
+ deleted: VideoDeletionStats;
120
+ errors?: string[] | null;
121
+ }
122
+
123
+ export interface ChatMessage {
124
+ role: 'user' | 'assistant';
125
+ content: string;
126
+ }
127
+
128
+ export interface ChatStreamRequest {
129
+ prompt: string;
130
+ messages?: ChatMessage[];
131
+ videoId?: string;
132
+ systemPrompt?: string;
133
+ modelId?: string;
134
+ }
135
+
136
+ // Persona types matching backend shared/persona_models.py
137
+
138
+ export interface PersonaConfig {
139
+ persona_id: string;
140
+ user_id: string;
141
+ name: string;
142
+ description?: string | null;
143
+ voice_id: string;
144
+ tts_model_id: string;
145
+ temperature: number;
146
+ speaking_rate: number;
147
+ audio_format: AudioFormat;
148
+ enable_markups: boolean;
149
+ chat_model_id: string;
150
+ custom_system_prompt?: string | null;
151
+ system_prompt_override: boolean;
152
+ heartbeat_interval: number;
153
+ idle_timeout: number;
154
+ video_id?: string | null;
155
+ /** ID of the rest-pose character image used as the source for viseme
156
+ * bundle generation. Set server-side by
157
+ * ``POST /api/v1/personas/{id}/character`` (generate-and-link) or
158
+ * via PATCH /api/v1/personas/{id} from a pre-existing tracked
159
+ * character image (the persona PATCH handler validates user image
160
+ * ownership before persisting). When absent, the chat-ws "Generate
161
+ * vectorized face" flow prompts the user to generate one first. */
162
+ character_image_id?: string | null;
163
+ viseme_bundle_id?: string | null;
164
+ viseme_prompt_overrides?: Record<string, string> | null;
165
+ /** Per-persona renderer tuning blob. Effective shape is
166
+ * ``Partial<TuningOverrides>`` (see web/app/chat-ws/CharacterFace.tsx)
167
+ * — every field optional, camelCase keys, validated server-side.
168
+ * Typed loosely as ``Record<string, unknown>`` here so this lib/
169
+ * file doesn't take a dependency on the chat-ws app/ tree; chat-ws
170
+ * code that consumes this casts to ``TuningOverrides``. Set via
171
+ * the dedicated PUT /visual-overrides endpoint, not PATCH /personas. */
172
+ visual_overrides?: Record<string, unknown> | null;
173
+ template_fields?: Record<string, string> | null;
174
+ prompt_addon_ids?: string[] | null;
175
+ is_default: boolean;
176
+ status: 'pending' | 'approved';
177
+ created_at: string;
178
+ updated_at: string;
179
+ }
180
+
181
+ // Viseme bundle types — see services/persona/ and shared/viseme_bundle_models.py
182
+ export type VisemeBundleStatus = 'pending' | 'complete' | 'failed';
183
+
184
+ export type VisemeRegenStatusValue = 'pending' | 'complete' | 'failed';
185
+
186
+ export interface VisemeRegenStatus {
187
+ status: VisemeRegenStatusValue;
188
+ started_at: string;
189
+ error_message?: string | null;
190
+ }
191
+
192
+ export interface VisemeBundleRecord {
193
+ bundle_id: string;
194
+ persona_id: string;
195
+ user_id: string;
196
+ status: VisemeBundleStatus;
197
+ viewbox_width?: number | null;
198
+ viewbox_height?: number | null;
199
+ lip_fill?: string | null;
200
+ body_svg_s3_key?: string | null;
201
+ viseme_png_s3_keys?: Record<string, string> | null;
202
+ body_svg?: string | null;
203
+ mouth_paths?: Record<string, string> | null;
204
+ error_message?: string | null;
205
+ model_version?: string | null;
206
+ // Per-viseme regeneration progress. Empty/missing for fresh bundles;
207
+ // populated as the persona-tuner kicks off per-viseme regenerations.
208
+ viseme_regen_status?: Record<string, VisemeRegenStatus> | null;
209
+ created_at: string;
210
+ updated_at: string;
211
+ }
212
+
213
+ export interface RegenerateVisemeAccept {
214
+ bundle_id: string;
215
+ viseme: string;
216
+ status: VisemeRegenStatusValue;
217
+ status_url: string;
218
+ traceId: string;
219
+ }
220
+
221
+ // Image tracking types matching backend shared/image_models.py
222
+ export type ImageCategory = 'extracted' | 'regenerated' | 'character';
223
+
224
+ /** Async-generation lifecycle. Existing rows written before the async
225
+ * conversion deserialize as ``complete`` (the backend default). */
226
+ export type ImageStatus = 'pending' | 'complete' | 'failed';
227
+
228
+ export interface ImageRecord {
229
+ image_id: string;
230
+ user_id: string;
231
+ s3_key: string;
232
+ s3_bucket: string;
233
+ category: ImageCategory;
234
+ content_type: string;
235
+ image_url?: string | null;
236
+ file_size_bytes?: number | null;
237
+ source_video_id?: string | null;
238
+ source_entity?: string | null;
239
+ source_timestamp?: number | null;
240
+ prompt?: string | null;
241
+ model?: string | null;
242
+ parent_image_id?: string | null;
243
+ persona_id?: string | null;
244
+ tags?: string[] | null;
245
+ grid_columns?: number | null;
246
+ grid_rows?: number | null;
247
+ /** Async-generation lifecycle. ``pending`` rows are still being
248
+ * generated (Gemini call in flight); the gallery hides them. Existing
249
+ * rows written before the async conversion default to ``complete``. */
250
+ status?: ImageStatus;
251
+ /** Diagnostic message when ``status === 'failed'`` (truncated to
252
+ * 500 chars server-side). */
253
+ error_message?: string | null;
254
+ created_at: string;
255
+ updated_at: string;
256
+ }
257
+
258
+ export interface ImageListResponse {
259
+ images: ImageRecord[];
260
+ total: number;
261
+ next_token?: string | null;
262
+ }
263
+
264
+ export interface UpdateImageRequest {
265
+ persona_id?: string | null;
266
+ tags?: string[] | null;
267
+ source_video_id?: string | null;
268
+ source_entity?: string | null;
269
+ }
270
+
271
+ /** Metadata describing the origin system for a response payload. Mirrors
272
+ * `api/tools/schemas.py::SourceMetadata`. */
273
+ export interface SourceMetadata {
274
+ system: string;
275
+ details?: Record<string, unknown> | null;
276
+ }
277
+
278
+ export interface ExtractImageRequest {
279
+ videoId: string;
280
+ entity: string;
281
+ /** Optional explicit timestamp (seconds). If omitted the backend looks
282
+ * up the entity's first occurrence via Neo4j entity_timeline. */
283
+ timestamp?: number | null;
284
+ }
285
+
286
+ export interface ExtractImageResponse {
287
+ traceId: string;
288
+ /** Presigned S3 URL for immediate display only. The URL has a short
289
+ * TTL (typically 1h) and will 403 once expired — persist `imageS3Key`
290
+ * if you need a stable handle and re-presign on read. */
291
+ imageUrl: string;
292
+ imageS3Key: string;
293
+ sourceTimestamp: number;
294
+ entity: string;
295
+ citation: Citation;
296
+ source: SourceMetadata;
297
+ }
298
+
299
+ export interface RegenerateImageRequest {
300
+ videoId: string;
301
+ entity: string;
302
+ /** Style prompt fed to Gemini Flash Image. 1-2000 chars. */
303
+ prompt: string;
304
+ timestamp?: number | null;
305
+ /** Optional model override. Backend description in
306
+ * `api/tools/schemas.py::RegenerateImageRequest` lists these two
307
+ * values; omit for backend default with auto-fallback on 503. The
308
+ * union is intentionally strict — extend it here when the backend
309
+ * adds a new model. */
310
+ model?: 'gemini-3.1-flash-image-preview' | 'gemini-2.5-flash-image' | null;
311
+ }
312
+
313
+ export interface RegenerateImageResponse {
314
+ traceId: string;
315
+ /** Presigned S3 URL for immediate display only. The URL has a short
316
+ * TTL (typically 1h) and will 403 once expired — persist `imageS3Key`
317
+ * if you need a stable handle and re-presign on read. */
318
+ imageUrl: string;
319
+ imageS3Key: string;
320
+ sourceTimestamp: number;
321
+ entity: string;
322
+ prompt: string;
323
+ citation: Citation;
324
+ source: SourceMetadata;
325
+ }
326
+
327
+ export interface GenerateCharacterRequest {
328
+ videoId?: string | null;
329
+ entity?: string | null;
330
+ timestamp?: number | null;
331
+ sourceImageId?: string | null;
332
+ style?: string | null;
333
+ model?: string | null;
334
+ }
335
+
336
+ /** 202 Accepted envelope for async character generation.
337
+ *
338
+ * Gemini takes up to 150s; CloudFront's `OriginReadTimeout` is 60s
339
+ * (quota-locked). The endpoint returns this envelope immediately and
340
+ * the caller polls `statusUrl` (== `/api/v1/images/{characterImageId}`)
341
+ * via `getImage()` until `status` flips to `'complete'` or `'failed'`.
342
+ * `pollImageUntilDone()` wraps that loop. */
343
+ export interface GenerateCharacterResponse {
344
+ traceId: string;
345
+ characterImageId: string;
346
+ status: 'pending';
347
+ statusUrl: string;
348
+ }
349
+
350
+ export interface CreatePersonaRequest {
351
+ name: string;
352
+ description?: string | null;
353
+ voice_id?: string;
354
+ tts_model_id?: string;
355
+ temperature?: number;
356
+ speaking_rate?: number;
357
+ audio_format?: AudioFormat;
358
+ enable_markups?: boolean;
359
+ chat_model_id?: string;
360
+ custom_system_prompt?: string | null;
361
+ system_prompt_override?: boolean;
362
+ heartbeat_interval?: number;
363
+ idle_timeout?: number;
364
+ video_id?: string | null;
365
+ /** Optional rest-pose character image ID set at creation time. The
366
+ * server validates ownership the same way the PATCH handler does. See
367
+ * PersonaConfig.character_image_id for the read shape. */
368
+ character_image_id?: string | null;
369
+ template_fields?: Record<string, string>;
370
+ prompt_addon_ids?: string[];
371
+ is_default?: boolean;
372
+ status?: 'pending' | 'approved';
373
+ }
374
+
375
+ export interface UpdatePersonaRequest {
376
+ name?: string | null;
377
+ description?: string | null;
378
+ voice_id?: string | null;
379
+ tts_model_id?: string | null;
380
+ temperature?: number | null;
381
+ speaking_rate?: number | null;
382
+ audio_format?: AudioFormat | null;
383
+ enable_markups?: boolean | null;
384
+ chat_model_id?: string | null;
385
+ custom_system_prompt?: string | null;
386
+ system_prompt_override?: boolean | null;
387
+ heartbeat_interval?: number | null;
388
+ idle_timeout?: number | null;
389
+ video_id?: string | null;
390
+ /** Server-side image ownership is validated by the persona PATCH handler.
391
+ * **To CLEAR an existing image, send an empty string `""`, not `null`.**
392
+ * The store contract treats `null`/`undefined` as "skip this field" and
393
+ * only an empty string as "remove it" — sending `null` from a clear UI
394
+ * silently no-ops and leaves the old image attached. See
395
+ * web/lib/api.ts PersonaConfig for the read shape. */
396
+ character_image_id?: string | null;
397
+ template_fields?: Record<string, string> | null;
398
+ prompt_addon_ids?: string[] | null;
399
+ is_default?: boolean | null;
400
+ status?: 'pending' | 'approved';
401
+ }
402
+
403
+ export interface PersonaListResponse {
404
+ personas: PersonaConfig[];
405
+ total: number;
406
+ next_token?: string | null;
407
+ }
408
+
409
+ // Synthesis types matching backend api/personas/synthesize.py
410
+ export interface SynthesizedPersona {
411
+ name: string;
412
+ description: string;
413
+ entity_type: string;
414
+ custom_system_prompt: string;
415
+ }
416
+
417
+ export interface SynthesizePersonasResponse {
418
+ personas: SynthesizedPersona[];
419
+ model_id: string;
420
+ video_id: string;
421
+ }
422
+
423
+ // Voice info from /api/voices endpoint
424
+ export interface VoiceInfo {
425
+ voiceId: string;
426
+ displayName: string;
427
+ description: string;
428
+ languages: string[];
429
+ tags: string[];
430
+ isCustom: boolean;
431
+ }
432
+
433
+ // Session types matching backend shared/persona_models.py
434
+ export interface SessionMessage {
435
+ role: string;
436
+ content: string;
437
+ timestamp?: string;
438
+ metadata?: Record<string, unknown>;
439
+ }
440
+
441
+ export interface ChatSession {
442
+ session_id: string;
443
+ user_id: string;
444
+ persona_id?: string | null;
445
+ video_id?: string | null;
446
+ messages: SessionMessage[];
447
+ title?: string | null;
448
+ created_at: string;
449
+ updated_at: string;
450
+ last_message_at?: string | null;
451
+ }
452
+
453
+ export interface CreateSessionRequest {
454
+ persona_id?: string | null;
455
+ video_id?: string | null;
456
+ title?: string | null;
457
+ }
458
+
459
+ export interface AddMessageRequest {
460
+ role: string;
461
+ content: string;
462
+ metadata?: Record<string, unknown>;
463
+ }
464
+
465
+ export interface SessionListResponse {
466
+ sessions: ChatSession[];
467
+ total: number;
468
+ next_token?: string | null;
469
+ }
470
+
471
+ export interface TranscriptLine {
472
+ text: string;
473
+ speaker: string;
474
+ t0: number;
475
+ t1: number;
476
+ shotId?: string;
477
+ }
478
+
479
+ export interface GetTranscriptResponse {
480
+ traceId: string;
481
+ videoId: string;
482
+ lines: TranscriptLine[];
483
+ }
484
+
485
+ export interface DialogSearchResult {
486
+ dialogId: string;
487
+ text: string;
488
+ speaker: string;
489
+ t0: number;
490
+ t1: number;
491
+ shotId?: string;
492
+ videoId: string;
493
+ }
494
+
495
+ export interface DialogSearchResponse {
496
+ traceId: string;
497
+ results: DialogSearchResult[];
498
+ }
499
+
500
+ // ---------------------------------------------------------------------------
501
+ // Narrative / Enrichment types
502
+ // ---------------------------------------------------------------------------
503
+
504
+ export interface NarrativeAct {
505
+ act: number;
506
+ timeRange: string;
507
+ description: string;
508
+ }
509
+
510
+ export interface NarrativeData {
511
+ summary: string;
512
+ acts: NarrativeAct[];
513
+ mainCharacters: string[];
514
+ themes: string[];
515
+ }
516
+
517
+ // ---------------------------------------------------------------------------
518
+ // Graph Editor types
519
+ // ---------------------------------------------------------------------------
520
+
521
+ export interface GraphNode {
522
+ id: string;
523
+ label: string;
524
+ properties: Record<string, unknown>;
525
+ }
526
+
527
+ export interface GraphEdge {
528
+ id: string;
529
+ source: string;
530
+ target: string;
531
+ type: string;
532
+ properties: Record<string, unknown>;
533
+ }
534
+
535
+ export interface VideoGraphResponse {
536
+ traceId: string;
537
+ videoId: string;
538
+ nodes: GraphNode[];
539
+ edges: GraphEdge[];
540
+ }
541
+
542
+ export interface UpdateNodeRequest {
543
+ nodeLabel: string;
544
+ idProperty: string;
545
+ idValue: string;
546
+ properties: Record<string, unknown>;
547
+ }
548
+
549
+ export interface UpdateNodeResponse {
550
+ traceId: string;
551
+ properties: Record<string, unknown>;
552
+ }
553
+
554
+ export interface DeleteNodeRequest {
555
+ nodeLabel: string;
556
+ idProperty: string;
557
+ idValue: string;
558
+ }
559
+
560
+ export interface DeleteNodeResponse {
561
+ traceId: string;
562
+ deleted: number;
563
+ }
564
+
565
+ export interface UpdateRelationshipRequest {
566
+ sourceId: string;
567
+ targetId: string;
568
+ relType: string;
569
+ properties: Record<string, unknown>;
570
+ }
571
+
572
+ export interface UpdateRelationshipResponse {
573
+ traceId: string;
574
+ properties: Record<string, unknown>;
575
+ }
576
+
577
+ export interface DeleteRelationshipRequest {
578
+ sourceId: string;
579
+ targetId: string;
580
+ relType: string;
581
+ }
582
+
583
+ export interface DeleteRelationshipResponse {
584
+ traceId: string;
585
+ deleted: number;
586
+ }
587
+
588
+ export class ApiClient {
589
+ private baseURL: string;
590
+ private sessionToken?: string;
591
+ private chatApiBaseUrl: string;
592
+
593
+ constructor(baseURL: string, sessionToken: string | undefined, chatBaseUrl: string) {
594
+ this.baseURL = baseURL;
595
+ this.sessionToken = sessionToken;
596
+ this.chatApiBaseUrl = chatBaseUrl;
597
+ }
598
+
599
+ setSessionToken(token: string | undefined) {
600
+ this.sessionToken = token;
601
+ }
602
+
603
+ private async request<T>(
604
+ endpoint: string,
605
+ options: RequestInit = {}
606
+ ): Promise<T> {
607
+ return this.makeRequest<T>(this.baseURL, endpoint, options);
608
+ }
609
+
610
+ private async chatRequest<T>(
611
+ endpoint: string,
612
+ options: RequestInit = {}
613
+ ): Promise<T> {
614
+ return this.makeRequest<T>(this.chatApiBaseUrl, endpoint, options);
615
+ }
616
+
617
+ private async makeRequest<T>(
618
+ baseUrl: string,
619
+ endpoint: string,
620
+ options: RequestInit = {}
621
+ ): Promise<T> {
622
+ const url = `${baseUrl}${endpoint}`;
623
+
624
+ const headers: Record<string, string> = {
625
+ 'Content-Type': 'application/json',
626
+ ...options.headers as Record<string, string>,
627
+ };
628
+
629
+ // Add authorization header if session token is available
630
+ if (this.sessionToken) {
631
+ headers['Authorization'] = `Bearer ${this.sessionToken}`;
632
+ }
633
+
634
+ try {
635
+ const response = await fetch(url, {
636
+ ...options,
637
+ headers,
638
+ });
639
+
640
+ if (!response.ok) {
641
+ const error: ApiError = await response.json().catch(() => ({
642
+ detail: `HTTP ${response.status}: ${response.statusText}`,
643
+ }));
644
+ // FastAPI 422 returns detail as an array of validation errors
645
+ const detail = error.detail;
646
+ let message: string;
647
+ if (Array.isArray(detail)) {
648
+ message = detail.map((e: { msg?: string; loc?: string[] }) =>
649
+ e.msg ? `${(e.loc || []).slice(-1).join('.')}: ${e.msg}` : String(e)
650
+ ).join('; ');
651
+ } else {
652
+ message = detail || `Request failed: ${response.status}`;
653
+ }
654
+ throw new Error(message);
655
+ }
656
+
657
+ // 204 No Content returns no body
658
+ if (response.status === 204) {
659
+ return undefined as T;
660
+ }
661
+
662
+ return await response.json();
663
+ } catch (error) {
664
+ console.error('API request failed:', error);
665
+ throw error;
666
+ }
667
+ }
668
+
669
+ /**
670
+ * List all ingestion jobs with optional filtering
671
+ */
672
+ async listJobs(params?: {
673
+ status?: string;
674
+ limit?: number;
675
+ nextToken?: string;
676
+ }): Promise<ListJobsResponse> {
677
+ const searchParams = new URLSearchParams();
678
+ if (params?.status) searchParams.append('status', params.status);
679
+ if (params?.limit) searchParams.append('limit', params.limit.toString());
680
+ if (params?.nextToken) searchParams.append('nextToken', params.nextToken);
681
+
682
+ const query = searchParams.toString();
683
+ const endpoint = `/api/v1/ingestion/jobs${query ? `?${query}` : ''}`;
684
+
685
+ return this.request<ListJobsResponse>(endpoint);
686
+ }
687
+
688
+ /**
689
+ * Get a specific ingestion job by video ID
690
+ */
691
+ async getJob(videoId: string): Promise<{ traceId: string; job: IngestionJob }> {
692
+ return this.request(`/api/v1/ingestion/jobs/${videoId}`);
693
+ }
694
+
695
+ /**
696
+ * List succeeded videos (for chat selector)
697
+ */
698
+ async listSucceededVideos(params?: {
699
+ limit?: number;
700
+ nextToken?: string;
701
+ }): Promise<ListJobsResponse> {
702
+ const searchParams = new URLSearchParams();
703
+ if (params?.limit) searchParams.append('limit', params.limit.toString());
704
+ if (params?.nextToken) searchParams.append('nextToken', params.nextToken);
705
+
706
+ const query = searchParams.toString();
707
+ const endpoint = `/api/v1/tools/videos${query ? `?${query}` : ''}`;
708
+
709
+ return this.request<ListJobsResponse>(endpoint);
710
+ }
711
+
712
+ /**
713
+ * List staged videos in the ingestion bucket
714
+ */
715
+ async listVideos(params?: {
716
+ prefix?: string;
717
+ pageSize?: number;
718
+ continuationToken?: string;
719
+ }): Promise<ListVideosResponse> {
720
+ const searchParams = new URLSearchParams();
721
+ if (params?.prefix) searchParams.append('prefix', params.prefix);
722
+ if (params?.pageSize) searchParams.append('pageSize', params.pageSize.toString());
723
+ if (params?.continuationToken) searchParams.append('continuationToken', params.continuationToken);
724
+
725
+ const query = searchParams.toString();
726
+ const endpoint = `/api/v1/ingestion/videos${query ? `?${query}` : ''}`;
727
+
728
+ return this.request<ListVideosResponse>(endpoint);
729
+ }
730
+
731
+ /**
732
+ * Upload a video file with progress tracking
733
+ */
734
+ async uploadVideo(
735
+ file: File,
736
+ onProgress?: UploadProgressCallback,
737
+ ): Promise<UploadResponse> {
738
+ const url = `${this.baseURL}/api/v1/ingestion/uploads`;
739
+
740
+ return new Promise((resolve, reject) => {
741
+ const xhr = new XMLHttpRequest();
742
+
743
+ // Track upload progress
744
+ if (onProgress) {
745
+ xhr.upload.addEventListener('progress', (e) => {
746
+ if (e.lengthComputable) {
747
+ onProgress({
748
+ loaded: e.loaded,
749
+ total: e.total,
750
+ percentage: Math.round((e.loaded / e.total) * 100),
751
+ });
752
+ }
753
+ });
754
+ }
755
+
756
+ // Handle completion
757
+ xhr.addEventListener('load', () => {
758
+ if (xhr.status >= 200 && xhr.status < 300) {
759
+ try {
760
+ const response = JSON.parse(xhr.responseText);
761
+ resolve(response);
762
+ } catch {
763
+ reject(new Error('Failed to parse upload response'));
764
+ }
765
+ } else {
766
+ try {
767
+ const errorData = JSON.parse(xhr.responseText);
768
+ reject(new Error(errorData.detail || `Upload failed: ${xhr.status}`));
769
+ } catch {
770
+ reject(new Error(`Upload failed: ${xhr.status} ${xhr.statusText}`));
771
+ }
772
+ }
773
+ });
774
+
775
+ // Handle errors
776
+ xhr.addEventListener('error', () => {
777
+ reject(new Error('Upload failed due to network error'));
778
+ });
779
+
780
+ xhr.addEventListener('abort', () => {
781
+ reject(new Error('Upload aborted'));
782
+ });
783
+
784
+ // Prepare form data
785
+ const formData = new FormData();
786
+ formData.append('upload', file);
787
+
788
+ const payload = {
789
+ subdirectory: 'web-uploads',
790
+ source: {
791
+ type: 'direct',
792
+ filename: file.name,
793
+ contentType: file.type,
794
+ },
795
+ };
796
+
797
+ formData.append('payload', JSON.stringify(payload));
798
+
799
+ // Send request
800
+ xhr.open('POST', url);
801
+
802
+ // Add authorization header if session token is available
803
+ if (this.sessionToken) {
804
+ xhr.setRequestHeader('Authorization', `Bearer ${this.sessionToken}`);
805
+ }
806
+
807
+ xhr.send(formData);
808
+ });
809
+ }
810
+
811
+ // ==================== Enrichment API Methods ====================
812
+
813
+ /**
814
+ * Trigger Pegasus enrichment analysis on an ingested video
815
+ */
816
+ async enrichVideo(videoId: string, config?: PegasusConfig): Promise<EnrichVideoResponse> {
817
+ return this.request<EnrichVideoResponse>(`/api/v1/ingestion/videos/${videoId}/enrichments`, {
818
+ method: 'POST',
819
+ body: JSON.stringify({
820
+ pegasusPrompt: config?.pegasusPrompt,
821
+ pegasusTemperature: config?.pegasusTemperature,
822
+ pegasusMaxTokens: config?.pegasusMaxTokens,
823
+ }),
824
+ });
825
+ }
826
+
827
+ /**
828
+ * List all enrichment runs for a video
829
+ */
830
+ async getEnrichments(videoId: string): Promise<ListEnrichmentsResponse> {
831
+ return this.request<ListEnrichmentsResponse>(`/api/v1/ingestion/videos/${videoId}/enrichments`);
832
+ }
833
+
834
+ /**
835
+ * Get a specific enrichment result
836
+ */
837
+ async getEnrichment(enrichmentId: string): Promise<EnrichmentRecord> {
838
+ return this.request<EnrichmentRecord>(`/api/v1/ingestion/enrichments/${enrichmentId}`);
839
+ }
840
+
841
+ /**
842
+ * Delete a video and all associated data across all systems
843
+ */
844
+ async deleteVideo(videoId: string, s3Key?: string): Promise<VideoDeletionResponse> {
845
+ const searchParams = new URLSearchParams();
846
+ if (s3Key) searchParams.append('s3Key', s3Key);
847
+
848
+ const query = searchParams.toString();
849
+ const endpoint = `/api/v1/ingestion/videos/${videoId}${query ? `?${query}` : ''}`;
850
+
851
+ return this.request<VideoDeletionResponse>(endpoint, {
852
+ method: 'DELETE',
853
+ });
854
+ }
855
+
856
+ /**
857
+ * Stream chat responses with Server-Sent Events
858
+ * Returns a ReadableStreamDefaultReader for processing SSE events
859
+ */
860
+ async streamChat(
861
+ request: ChatStreamRequest,
862
+ signal?: AbortSignal
863
+ ): Promise<ReadableStreamDefaultReader<Uint8Array>> {
864
+ const url = `${this.chatApiBaseUrl}/api/chat/stream`;
865
+
866
+ const headers: Record<string, string> = {
867
+ 'Content-Type': 'application/json',
868
+ };
869
+
870
+ // Add authorization header if session token is available
871
+ if (this.sessionToken) {
872
+ headers['Authorization'] = `Bearer ${this.sessionToken}`;
873
+ }
874
+
875
+ const response = await fetch(url, {
876
+ method: 'POST',
877
+ headers,
878
+ body: JSON.stringify(request),
879
+ signal,
880
+ });
881
+
882
+ if (!response.ok) {
883
+ const error: ApiError = await response.json().catch(() => ({
884
+ detail: `HTTP ${response.status}: ${response.statusText}`,
885
+ }));
886
+ throw new Error(error.detail || `Chat request failed: ${response.status}`);
887
+ }
888
+
889
+ const reader = response.body?.getReader();
890
+ if (!reader) {
891
+ throw new Error('No response body available for streaming');
892
+ }
893
+
894
+ return reader;
895
+ }
896
+
897
+ // ==================== Persona API Methods ====================
898
+ // Note: Personas are served by the Chat API, not the Tools API
899
+
900
+ /**
901
+ * Create a new persona
902
+ */
903
+ async createPersona(data: CreatePersonaRequest): Promise<PersonaConfig> {
904
+ return this.chatRequest<PersonaConfig>('/api/v1/personas', {
905
+ method: 'POST',
906
+ body: JSON.stringify(data),
907
+ });
908
+ }
909
+
910
+ /**
911
+ * List all personas for the current user
912
+ */
913
+ async listPersonas(params?: {
914
+ limit?: number;
915
+ nextToken?: string;
916
+ status?: 'pending' | 'approved';
917
+ }): Promise<PersonaListResponse> {
918
+ const searchParams = new URLSearchParams();
919
+ if (params?.limit) searchParams.append('limit', params.limit.toString());
920
+ if (params?.nextToken) searchParams.append('nextToken', params.nextToken);
921
+ if (params?.status) searchParams.append('status', params.status);
922
+
923
+ const query = searchParams.toString();
924
+ const endpoint = `/api/v1/personas${query ? `?${query}` : ''}`;
925
+
926
+ return this.chatRequest<PersonaListResponse>(endpoint);
927
+ }
928
+
929
+ /**
930
+ * Get the default persona for the current user
931
+ */
932
+ async getDefaultPersona(): Promise<PersonaConfig | null> {
933
+ return this.chatRequest<PersonaConfig | null>('/api/v1/personas/default');
934
+ }
935
+
936
+ /**
937
+ * Get a specific persona by ID
938
+ */
939
+ async getPersona(personaId: string): Promise<PersonaConfig> {
940
+ return this.chatRequest<PersonaConfig>(`/api/v1/personas/${personaId}`);
941
+ }
942
+
943
+ /**
944
+ * Update a persona
945
+ */
946
+ async updatePersona(personaId: string, data: UpdatePersonaRequest): Promise<PersonaConfig> {
947
+ return this.chatRequest<PersonaConfig>(`/api/v1/personas/${personaId}`, {
948
+ method: 'PATCH',
949
+ body: JSON.stringify(data),
950
+ });
951
+ }
952
+
953
+ /**
954
+ * Delete a persona
955
+ */
956
+ async deletePersona(personaId: string): Promise<void> {
957
+ await this.chatRequest<void>(`/api/v1/personas/${personaId}`, {
958
+ method: 'DELETE',
959
+ });
960
+ }
961
+
962
+ /**
963
+ * AI-synthesize persona definitions from enrichment data.
964
+ * Does NOT persist — returns suggestions to create individually.
965
+ */
966
+ async synthesizePersonas(
967
+ videoId: string,
968
+ enrichmentData: Record<string, unknown>,
969
+ maxPersonas = 10,
970
+ ): Promise<SynthesizePersonasResponse> {
971
+ return this.chatRequest<SynthesizePersonasResponse>('/api/v1/personas/synthesize', {
972
+ method: 'POST',
973
+ headers: { 'Content-Type': 'application/json' },
974
+ body: JSON.stringify({
975
+ video_id: videoId,
976
+ enrichment_data: enrichmentData,
977
+ max_personas: maxPersonas,
978
+ }),
979
+ });
980
+ }
981
+
982
+ // ==================== Image API Methods ====================
983
+ // Note: Images are served by the Chat API
984
+
985
+ async listImages(params?: {
986
+ category?: ImageCategory;
987
+ videoId?: string;
988
+ limit?: number;
989
+ nextToken?: string;
990
+ }): Promise<ImageListResponse> {
991
+ const searchParams = new URLSearchParams();
992
+ if (params?.category) searchParams.append('category', params.category);
993
+ if (params?.videoId) searchParams.append('videoId', params.videoId);
994
+ if (params?.limit) searchParams.append('limit', params.limit.toString());
995
+ if (params?.nextToken) searchParams.append('nextToken', params.nextToken);
996
+
997
+ const query = searchParams.toString();
998
+ const endpoint = `/api/v1/images${query ? `?${query}` : ''}`;
999
+
1000
+ return this.chatRequest<ImageListResponse>(endpoint);
1001
+ }
1002
+
1003
+ async getImage(
1004
+ imageId: string,
1005
+ options: { signal?: AbortSignal } = {},
1006
+ ): Promise<ImageRecord> {
1007
+ return this.chatRequest<ImageRecord>(`/api/v1/images/${imageId}`, {
1008
+ signal: options.signal,
1009
+ });
1010
+ }
1011
+
1012
+ async updateImage(imageId: string, data: UpdateImageRequest): Promise<ImageRecord> {
1013
+ return this.chatRequest<ImageRecord>(`/api/v1/images/${imageId}`, {
1014
+ method: 'PATCH',
1015
+ body: JSON.stringify(data),
1016
+ });
1017
+ }
1018
+
1019
+ async deleteImage(imageId: string): Promise<void> {
1020
+ await this.chatRequest<void>(`/api/v1/images/${imageId}`, {
1021
+ method: 'DELETE',
1022
+ });
1023
+ }
1024
+
1025
+ async uploadImage(
1026
+ file: File,
1027
+ metadata?: { category?: string; tags?: string; sourceVideoId?: string; sourceEntity?: string },
1028
+ ): Promise<ImageRecord> {
1029
+ const url = `${this.chatApiBaseUrl}/api/v1/images/upload`;
1030
+ const formData = new FormData();
1031
+ formData.append('upload', file);
1032
+ if (metadata?.category) formData.append('category', metadata.category);
1033
+ if (metadata?.tags) formData.append('tags', metadata.tags);
1034
+ if (metadata?.sourceVideoId) formData.append('source_video_id', metadata.sourceVideoId);
1035
+ if (metadata?.sourceEntity) formData.append('source_entity', metadata.sourceEntity);
1036
+
1037
+ const headers: Record<string, string> = {};
1038
+ if (this.sessionToken) {
1039
+ headers['Authorization'] = `Bearer ${this.sessionToken}`;
1040
+ }
1041
+
1042
+ const response = await fetch(url, {
1043
+ method: 'POST',
1044
+ headers,
1045
+ body: formData,
1046
+ });
1047
+
1048
+ if (!response.ok) {
1049
+ const error = await response.json().catch(() => ({ detail: `Upload failed: ${response.status}` }));
1050
+ throw new Error(error.detail || `Upload failed: ${response.status}`);
1051
+ }
1052
+
1053
+ return response.json();
1054
+ }
1055
+
1056
+ /**
1057
+ * Kick off async character generation. Returns a 202 envelope with
1058
+ * `characterImageId` and `statusUrl`. Caller must poll
1059
+ * `getImage(characterImageId)` (or use `pollImageUntilDone()`) until
1060
+ * `status` flips from `'pending'` to `'complete'` or `'failed'`.
1061
+ *
1062
+ * Converted from synchronous because Gemini regularly exceeds
1063
+ * CloudFront's 60s `OriginReadTimeout` and the browser would see a
1064
+ * 504 even though the backend completed.
1065
+ */
1066
+ async generateCharacter(
1067
+ params: GenerateCharacterRequest,
1068
+ ): Promise<GenerateCharacterResponse> {
1069
+ return this.request<GenerateCharacterResponse>(
1070
+ '/api/v1/tools/generate-character',
1071
+ {
1072
+ method: 'POST',
1073
+ body: JSON.stringify(params),
1074
+ },
1075
+ );
1076
+ }
1077
+
1078
+ /**
1079
+ * Extract a raw video frame at an entity's location or a specific
1080
+ * timestamp. Synchronous (no polling) — the path is ffmpeg-only with
1081
+ * no AI generation, so it returns 201 with the result inline.
1082
+ *
1083
+ * Pass `options.signal` to abort the in-flight request when the
1084
+ * consumer component unmounts.
1085
+ */
1086
+ async extractImage(
1087
+ req: ExtractImageRequest,
1088
+ options: { signal?: AbortSignal } = {},
1089
+ ): Promise<ExtractImageResponse> {
1090
+ return this.request<ExtractImageResponse>('/api/v1/tools/extract-image', {
1091
+ method: 'POST',
1092
+ body: JSON.stringify(req),
1093
+ signal: options.signal,
1094
+ });
1095
+ }
1096
+
1097
+ /**
1098
+ * Extract an entity frame and regenerate it with a Gemini Flash Image
1099
+ * style prompt. Synchronous from the client's perspective; backend
1100
+ * runs ffmpeg + Gemini in one request and returns 201 with the result.
1101
+ *
1102
+ * Gemini calls regularly take several seconds — pass `options.signal`
1103
+ * so a component unmount mid-call cancels the underlying fetch instead
1104
+ * of leaving a dangling Promise.
1105
+ */
1106
+ async regenerateImage(
1107
+ req: RegenerateImageRequest,
1108
+ options: { signal?: AbortSignal } = {},
1109
+ ): Promise<RegenerateImageResponse> {
1110
+ return this.request<RegenerateImageResponse>(
1111
+ '/api/v1/tools/regenerate-image',
1112
+ {
1113
+ method: 'POST',
1114
+ body: JSON.stringify(req),
1115
+ signal: options.signal,
1116
+ },
1117
+ );
1118
+ }
1119
+
1120
+ /**
1121
+ * Poll `GET /api/v1/images/{imageId}` until the row's `status` flips
1122
+ * away from `'pending'`. Resolves with the completed record (status
1123
+ * `'complete'`); throws on `'failed'` (with the row's
1124
+ * `error_message`) or after `timeoutMs` elapses.
1125
+ *
1126
+ * Pass `signal` to cancel cleanly when the page unmounts. AbortError
1127
+ * is rethrown so callers can distinguish cancellation from real
1128
+ * failures.
1129
+ *
1130
+ * Cadence is 5s — character generation runs ~30-60s, so a 2s poll
1131
+ * (the per-viseme cadence) would burn 25 wasted requests per
1132
+ * generation. The 5s cadence still surfaces completion within one
1133
+ * user-perceived "tick" past the actual finish.
1134
+ */
1135
+ async pollImageUntilDone(
1136
+ imageId: string,
1137
+ options: {
1138
+ intervalMs?: number;
1139
+ timeoutMs?: number;
1140
+ signal?: AbortSignal;
1141
+ } = {},
1142
+ ): Promise<ImageRecord> {
1143
+ const intervalMs = options.intervalMs ?? 5000;
1144
+ const timeoutMs = options.timeoutMs ?? 180_000;
1145
+ const deadline = Date.now() + timeoutMs;
1146
+ while (true) {
1147
+ if (options.signal?.aborted) {
1148
+ throw new DOMException('Polling aborted', 'AbortError');
1149
+ }
1150
+ const record = await this.getImage(imageId, { signal: options.signal });
1151
+ const status = record.status ?? 'complete';
1152
+ if (status === 'complete') {
1153
+ return record;
1154
+ }
1155
+ if (status === 'failed') {
1156
+ throw new Error(record.error_message ?? 'Image generation failed');
1157
+ }
1158
+ if (Date.now() >= deadline) {
1159
+ throw new Error(`Image generation timed out after ${Math.round(timeoutMs / 1000)}s`);
1160
+ }
1161
+ await new Promise<void>((resolve, reject) => {
1162
+ const timer = setTimeout(() => {
1163
+ options.signal?.removeEventListener('abort', onAbort);
1164
+ resolve();
1165
+ }, intervalMs);
1166
+ const onAbort = () => {
1167
+ clearTimeout(timer);
1168
+ reject(new DOMException('Polling aborted', 'AbortError'));
1169
+ };
1170
+ options.signal?.addEventListener('abort', onAbort, { once: true });
1171
+ });
1172
+ }
1173
+ }
1174
+
1175
+ // ==================== Session API Methods ====================
1176
+ // Note: Sessions are served by the Chat API, not the Tools API
1177
+
1178
+ /**
1179
+ * Create a new chat session
1180
+ */
1181
+ async createSession(data: CreateSessionRequest): Promise<ChatSession> {
1182
+ return this.chatRequest<ChatSession>('/api/v1/sessions', {
1183
+ method: 'POST',
1184
+ body: JSON.stringify(data),
1185
+ });
1186
+ }
1187
+
1188
+ /**
1189
+ * List all sessions for the current user
1190
+ */
1191
+ async listSessions(params?: {
1192
+ limit?: number;
1193
+ nextToken?: string;
1194
+ personaId?: string;
1195
+ }): Promise<SessionListResponse> {
1196
+ const searchParams = new URLSearchParams();
1197
+ if (params?.limit) searchParams.append('limit', params.limit.toString());
1198
+ if (params?.nextToken) searchParams.append('nextToken', params.nextToken);
1199
+ if (params?.personaId) searchParams.append('personaId', params.personaId);
1200
+
1201
+ const query = searchParams.toString();
1202
+ const endpoint = `/api/v1/sessions${query ? `?${query}` : ''}`;
1203
+
1204
+ return this.chatRequest<SessionListResponse>(endpoint);
1205
+ }
1206
+
1207
+ /**
1208
+ * Get a specific session by ID
1209
+ */
1210
+ async getSession(sessionId: string): Promise<ChatSession> {
1211
+ return this.chatRequest<ChatSession>(`/api/v1/sessions/${sessionId}`);
1212
+ }
1213
+
1214
+ /**
1215
+ * Add a message to a session
1216
+ */
1217
+ async addMessageToSession(sessionId: string, data: AddMessageRequest): Promise<ChatSession> {
1218
+ return this.chatRequest<ChatSession>(`/api/v1/sessions/${sessionId}/messages`, {
1219
+ method: 'PUT',
1220
+ body: JSON.stringify(data),
1221
+ });
1222
+ }
1223
+
1224
+ /**
1225
+ * Clear all messages from a session
1226
+ */
1227
+ async clearSessionMessages(sessionId: string): Promise<void> {
1228
+ await this.chatRequest<void>(`/api/v1/sessions/${sessionId}/messages`, {
1229
+ method: 'DELETE',
1230
+ });
1231
+ }
1232
+
1233
+ /**
1234
+ * Delete a session
1235
+ */
1236
+ async deleteSession(sessionId: string): Promise<void> {
1237
+ await this.chatRequest<void>(`/api/v1/sessions/${sessionId}`, {
1238
+ method: 'DELETE',
1239
+ });
1240
+ }
1241
+
1242
+ /**
1243
+ * Get transcript for a video, optionally filtered by time range
1244
+ */
1245
+ async getTranscript(videoId: string, t0?: number, t1?: number): Promise<GetTranscriptResponse> {
1246
+ return this.request<GetTranscriptResponse>('/api/v1/tools/get-transcript', {
1247
+ method: 'POST',
1248
+ body: JSON.stringify({ videoId, t0, t1 }),
1249
+ });
1250
+ }
1251
+
1252
+ /**
1253
+ * Search dialog within a video by keyword or phrase
1254
+ */
1255
+ async searchDialog(videoId: string, query: string, limit?: number): Promise<DialogSearchResponse> {
1256
+ return this.request<DialogSearchResponse>('/api/v1/tools/dialog-search', {
1257
+ method: 'POST',
1258
+ body: JSON.stringify({ videoId, query, limit: limit ?? 10 }),
1259
+ });
1260
+ }
1261
+
1262
+ // ==================== Graph Editor API Methods ====================
1263
+
1264
+ async getVideoGraph(videoId: string): Promise<VideoGraphResponse> {
1265
+ return this.request<VideoGraphResponse>(`/api/v1/tools/graph/${encodeURIComponent(videoId)}`);
1266
+ }
1267
+
1268
+ async updateGraphNode(data: UpdateNodeRequest): Promise<UpdateNodeResponse> {
1269
+ return this.request<UpdateNodeResponse>('/api/v1/tools/graph/nodes', {
1270
+ method: 'PATCH',
1271
+ body: JSON.stringify(data),
1272
+ });
1273
+ }
1274
+
1275
+ async deleteGraphNode(data: DeleteNodeRequest): Promise<DeleteNodeResponse> {
1276
+ return this.request<DeleteNodeResponse>('/api/v1/tools/graph/nodes', {
1277
+ method: 'DELETE',
1278
+ body: JSON.stringify(data),
1279
+ });
1280
+ }
1281
+
1282
+ async updateGraphEdge(data: UpdateRelationshipRequest): Promise<UpdateRelationshipResponse> {
1283
+ return this.request<UpdateRelationshipResponse>('/api/v1/tools/graph/edges', {
1284
+ method: 'PATCH',
1285
+ body: JSON.stringify(data),
1286
+ });
1287
+ }
1288
+
1289
+ async deleteGraphEdge(data: DeleteRelationshipRequest): Promise<DeleteRelationshipResponse> {
1290
+ return this.request<DeleteRelationshipResponse>('/api/v1/tools/graph/edges', {
1291
+ method: 'DELETE',
1292
+ body: JSON.stringify(data),
1293
+ });
1294
+ }
1295
+
1296
+ /**
1297
+ * Fetch a persona's viseme bundle by ID. Returns the full record including
1298
+ * inline body_svg and mouth_paths when status === 'complete'.
1299
+ *
1300
+ * Pass `signal` to abort the in-flight request — used by the
1301
+ * persona-tuner poll loop so a drawer-close mid-fetch unblocks
1302
+ * immediately rather than waiting for the response.
1303
+ */
1304
+ async getVisemeBundle(
1305
+ personaId: string,
1306
+ bundleId: string,
1307
+ options: { signal?: AbortSignal } = {},
1308
+ ): Promise<VisemeBundleRecord> {
1309
+ return this.chatRequest<VisemeBundleRecord>(
1310
+ `/api/v1/personas/${personaId}/viseme-bundle/${bundleId}`,
1311
+ { signal: options.signal },
1312
+ );
1313
+ }
1314
+
1315
+ /**
1316
+ * Fetch a bundle's body SVG bytes from the backend's S3 proxy. Used as a
1317
+ * fallback when the bundle row's inline body_svg is null because the SVG
1318
+ * exceeded the DynamoDB inline cap.
1319
+ */
1320
+ async getVisemeBundleBodySvg(personaId: string, bundleId: string): Promise<string> {
1321
+ const url = `${this.chatApiBaseUrl}/api/v1/personas/${personaId}/viseme-bundle/${bundleId}/body.svg`;
1322
+ const headers: Record<string, string> = {};
1323
+ if (this.sessionToken) {
1324
+ headers['Authorization'] = `Bearer ${this.sessionToken}`;
1325
+ }
1326
+ const response = await fetch(url, { headers });
1327
+ if (!response.ok) {
1328
+ throw new Error(`Failed to fetch body SVG: HTTP ${response.status}`);
1329
+ }
1330
+ return await response.text();
1331
+ }
1332
+
1333
+ /**
1334
+ * Fetch a single viseme PNG and return a blob URL for use as `<img src>`.
1335
+ * The backend proxy adds the auth header; <img> tags can't, so we hop
1336
+ * through fetch + URL.createObjectURL. Caller is responsible for revoking
1337
+ * the URL when the bundle is no longer in use.
1338
+ */
1339
+ async getVisemeBundleVisemePng(
1340
+ personaId: string,
1341
+ bundleId: string,
1342
+ viseme: string,
1343
+ /** Optional cache-bust suffix appended as a query string. */
1344
+ cacheKey?: string,
1345
+ ): Promise<string> {
1346
+ const path = `/api/v1/personas/${personaId}/viseme-bundle/${bundleId}/visemes/${encodeURIComponent(viseme)}.png`;
1347
+ const url = `${this.chatApiBaseUrl}${path}${cacheKey ? `?v=${encodeURIComponent(cacheKey)}` : ''}`;
1348
+ const headers: Record<string, string> = {};
1349
+ if (this.sessionToken) {
1350
+ headers['Authorization'] = `Bearer ${this.sessionToken}`;
1351
+ }
1352
+ const response = await fetch(url, { headers });
1353
+ if (!response.ok) {
1354
+ throw new Error(`Failed to fetch viseme PNG (${viseme}): HTTP ${response.status}`);
1355
+ }
1356
+ const blob = await response.blob();
1357
+ return URL.createObjectURL(blob);
1358
+ }
1359
+
1360
+ /**
1361
+ * Persona-tuner: GET defaults for the 11 viseme prompt descriptions.
1362
+ */
1363
+ async getVisemePromptDefaults(): Promise<Record<string, string>> {
1364
+ return this.chatRequest<Record<string, string>>(
1365
+ '/api/v1/personas/viseme-prompts/defaults',
1366
+ );
1367
+ }
1368
+
1369
+ /**
1370
+ * Persona-tuner: per-persona prompts as
1371
+ * `{viseme: {default, override, effective}}`. Returns 11 entries.
1372
+ */
1373
+ async getPersonaVisemePrompts(personaId: string): Promise<{
1374
+ prompts: Record<string, { default: string; override: string | null; effective: string }>;
1375
+ traceId: string;
1376
+ }> {
1377
+ return this.chatRequest(
1378
+ `/api/v1/personas/${personaId}/viseme-prompts`,
1379
+ );
1380
+ }
1381
+
1382
+ /**
1383
+ * Persona-tuner: set or clear ONE viseme's description override.
1384
+ * Pass `description: null` (or empty string) to clear the override.
1385
+ * Does NOT trigger regeneration — call regenerateBundleViseme for that.
1386
+ */
1387
+ async patchPersonaVisemePrompts(
1388
+ personaId: string,
1389
+ body: { viseme: string; description: string | null },
1390
+ ): Promise<{
1391
+ prompts: Record<string, { default: string; override: string | null; effective: string }>;
1392
+ traceId: string;
1393
+ }> {
1394
+ return this.chatRequest(
1395
+ `/api/v1/personas/${personaId}/viseme-prompts`,
1396
+ { method: 'PATCH', body: JSON.stringify(body) },
1397
+ );
1398
+ }
1399
+
1400
+ /**
1401
+ * Persona-tuner: replace (or clear) the persona's full visual
1402
+ * overrides blob. PUT semantics: the body IS the new full state.
1403
+ * Pass `null` to clear. Backend validates per-field bounds + rejects
1404
+ * unknown keys (422 on bad input).
1405
+ */
1406
+ async putPersonaVisualOverrides(
1407
+ personaId: string,
1408
+ overrides: Record<string, unknown> | null,
1409
+ ): Promise<{
1410
+ visual_overrides: Record<string, unknown> | null;
1411
+ traceId: string;
1412
+ }> {
1413
+ return this.chatRequest(
1414
+ `/api/v1/personas/${personaId}/visual-overrides`,
1415
+ { method: 'PUT', body: JSON.stringify({ visual_overrides: overrides }) },
1416
+ );
1417
+ }
1418
+
1419
+ /**
1420
+ * Persona-tuner: kick off async regeneration of ONE viseme's PNG (and
1421
+ * its mouth path). Optional `description` sets the override before the
1422
+ * BackgroundTask starts. Returns 202 immediately with a status_url —
1423
+ * poll `getVisemeBundle` and watch `viseme_regen_status[viseme]` until
1424
+ * it transitions to `complete` or `failed`.
1425
+ */
1426
+ async regenerateBundleViseme(
1427
+ personaId: string,
1428
+ bundleId: string,
1429
+ viseme: string,
1430
+ body: { description?: string } = {},
1431
+ ): Promise<RegenerateVisemeAccept> {
1432
+ return this.chatRequest(
1433
+ `/api/v1/personas/${personaId}/viseme-bundle/${bundleId}/visemes/${encodeURIComponent(viseme)}/regenerate`,
1434
+ { method: 'POST', body: JSON.stringify(body) },
1435
+ );
1436
+ }
1437
+
1438
+ /**
1439
+ * Poll `getVisemeBundle` until `viseme_regen_status[viseme]` reaches
1440
+ * a terminal state (`complete` or `failed`). Resolves with the final
1441
+ * bundle record. Times out after `timeoutMs` (default 240s — covers
1442
+ * the worst observed Gemini wall-clock plus retries).
1443
+ *
1444
+ * Pass `signal` to cancel cleanly when the drawer closes or the user
1445
+ * switches personas mid-poll. AbortError is rethrown so callers can
1446
+ * distinguish cancellation from real failures.
1447
+ */
1448
+ async pollVisemeRegenUntilDone(
1449
+ personaId: string,
1450
+ bundleId: string,
1451
+ viseme: string,
1452
+ options: {
1453
+ intervalMs?: number;
1454
+ timeoutMs?: number;
1455
+ signal?: AbortSignal;
1456
+ } = {},
1457
+ ): Promise<VisemeBundleRecord> {
1458
+ // Per-viseme regen runs ~5-30s, so a flat 2s poll surfaces
1459
+ // completion within ~1 user-perceived "tick" without burning
1460
+ // bandwidth. Bundle-level generation (which takes 40-60s) polls
1461
+ // at 5s in chat-ws/page.tsx. Exponential backoff isn't worth the
1462
+ // complexity at this cadence — see specs/technical-debt.md.
1463
+ const intervalMs = options.intervalMs ?? 2000;
1464
+ const timeoutMs = options.timeoutMs ?? 240_000;
1465
+ const deadline = Date.now() + timeoutMs;
1466
+ while (true) {
1467
+ if (options.signal?.aborted) {
1468
+ throw new DOMException('Polling aborted', 'AbortError');
1469
+ }
1470
+ const record = await this.getVisemeBundle(personaId, bundleId, {
1471
+ signal: options.signal,
1472
+ });
1473
+ const entry = record.viseme_regen_status?.[viseme];
1474
+ // Only resolve on an explicit terminal state. A missing entry
1475
+ // here is the eventually-consistent-read case: the POST claimed
1476
+ // the lock, but the GET read an older snapshot that hasn't yet
1477
+ // surfaced the new pending entry. Returning prematurely would
1478
+ // hand the caller stale bundle data and stop polling before the
1479
+ // BackgroundTask actually finishes. The overall timeout below
1480
+ // catches the truly-stuck case.
1481
+ if (entry?.status === 'complete') {
1482
+ return record;
1483
+ }
1484
+ if (entry?.status === 'failed') {
1485
+ const detail = entry.error_message ?? 'Regeneration failed';
1486
+ throw new Error(detail);
1487
+ }
1488
+ if (Date.now() >= deadline) {
1489
+ throw new Error(`Regeneration timed out after ${Math.round(timeoutMs / 1000)}s`);
1490
+ }
1491
+ await new Promise<void>((resolve, reject) => {
1492
+ const timer = setTimeout(() => {
1493
+ options.signal?.removeEventListener('abort', onAbort);
1494
+ resolve();
1495
+ }, intervalMs);
1496
+ const onAbort = () => {
1497
+ clearTimeout(timer);
1498
+ reject(new DOMException('Polling aborted', 'AbortError'));
1499
+ };
1500
+ options.signal?.addEventListener('abort', onAbort, { once: true });
1501
+ });
1502
+ }
1503
+ }
1504
+
1505
+ /**
1506
+ * Kick off async generation of a viseme bundle for a persona.
1507
+ * Returns 202 with a bundle_id; poll getVisemeBundle until status='complete'.
1508
+ */
1509
+ async createVisemeBundle(
1510
+ personaId: string,
1511
+ sourceImageId: string,
1512
+ ): Promise<{ bundle_id: string; status: VisemeBundleStatus; status_url: string }> {
1513
+ return this.chatRequest(`/api/v1/personas/${personaId}/viseme-bundle`, {
1514
+ method: 'POST',
1515
+ body: JSON.stringify({ source_image_id: sourceImageId }),
1516
+ });
1517
+ }
1518
+
1519
+ /**
1520
+ * Poll `getVisemeBundle` until the bundle's overall `status` reaches a
1521
+ * terminal state (`'complete'` or `'failed'`). Use after
1522
+ * `createVisemeBundle` for whole-bundle generation;
1523
+ * `pollVisemeRegenUntilDone` covers single-viseme regeneration.
1524
+ *
1525
+ * Cadence is 5s — bundle assembly runs ~40-60s, so a 2s poll (the
1526
+ * per-viseme cadence) would burn ~25 wasted requests per bundle.
1527
+ * Mirrors `pollImageUntilDone`'s shape; `signal` cancels cleanly when
1528
+ * the page unmounts.
1529
+ */
1530
+ async pollVisemeBundleUntilDone(
1531
+ personaId: string,
1532
+ bundleId: string,
1533
+ options: {
1534
+ intervalMs?: number;
1535
+ timeoutMs?: number;
1536
+ signal?: AbortSignal;
1537
+ } = {},
1538
+ ): Promise<VisemeBundleRecord> {
1539
+ const intervalMs = options.intervalMs ?? 5000;
1540
+ const timeoutMs = options.timeoutMs ?? 240_000;
1541
+ const deadline = Date.now() + timeoutMs;
1542
+ while (true) {
1543
+ if (options.signal?.aborted) {
1544
+ throw new DOMException('Polling aborted', 'AbortError');
1545
+ }
1546
+ const record = await this.getVisemeBundle(personaId, bundleId, {
1547
+ signal: options.signal,
1548
+ });
1549
+ // VisemeBundleRecord.status is non-optional in the type, so no
1550
+ // `?? 'complete'` fallback is needed here (unlike pollImageUntilDone,
1551
+ // where ImageRecord.status is optional for pre-async-conversion rows).
1552
+ if (record.status === 'complete') {
1553
+ return record;
1554
+ }
1555
+ if (record.status === 'failed') {
1556
+ throw new Error(record.error_message ?? 'Bundle generation failed');
1557
+ }
1558
+ if (Date.now() >= deadline) {
1559
+ throw new Error(
1560
+ `Bundle generation timed out after ${Math.round(timeoutMs / 1000)}s`,
1561
+ );
1562
+ }
1563
+ await new Promise<void>((resolve, reject) => {
1564
+ const timer = setTimeout(() => {
1565
+ options.signal?.removeEventListener('abort', onAbort);
1566
+ resolve();
1567
+ }, intervalMs);
1568
+ const onAbort = () => {
1569
+ clearTimeout(timer);
1570
+ reject(new DOMException('Polling aborted', 'AbortError'));
1571
+ };
1572
+ options.signal?.addEventListener('abort', onAbort, { once: true });
1573
+ });
1574
+ }
1575
+ }
1576
+
1577
+ }