@escapeaihq/client-core 0.42.0 → 0.49.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/src/api.ts CHANGED
@@ -495,6 +495,25 @@ export interface AcceptSuggestionResponse {
495
495
  graphId: string;
496
496
  }
497
497
 
498
+ /**
499
+ * 201 response from marking two entities distinct (R5d homonym override) —
500
+ * mirrors the backend `MarkEntitiesDistinctResponse`.
501
+ */
502
+ export interface MarkEntitiesDistinctResponse {
503
+ traceId: string;
504
+ docentId: string;
505
+ entityId: string;
506
+ }
507
+
508
+ /**
509
+ * Response from clearing a distinctness override (re-arms the de-dup oracle) —
510
+ * mirrors the backend `ClearEntitiesDistinctResponse`.
511
+ */
512
+ export interface ClearEntitiesDistinctResponse {
513
+ traceId: string;
514
+ cleared: boolean;
515
+ }
516
+
498
517
  export interface ChatMessage {
499
518
  role: 'user' | 'assistant';
500
519
  content: string;
@@ -608,6 +627,39 @@ export type AssistantStreamEvent =
608
627
  rationale?: string;
609
628
  };
610
629
 
630
+ /**
631
+ * Dashboard Spec A (§10A.5) — the kind of scene-control directive the DM may
632
+ * issue back to the viewer's experience surface. The allowlist is single-sourced
633
+ * with the backend `DM_DIRECTIVE_KINDS` set in `shared/chat_dispatcher.py` and
634
+ * the line-anchored `DM_SCENE_TAG_PATTERN` parser:
635
+ * - `enter_world` params: `{ prompt?: string; timestamp?: number }`
636
+ * - `exit_world` params: `{}`
637
+ * - `seek_video` params: `{ t?: number; timestamp?: number }`
638
+ * - `set_experience_source` params: `{ source: string }`
639
+ */
640
+ export type DmDirectiveKind =
641
+ | 'enter_world'
642
+ | 'exit_world'
643
+ | 'seek_video'
644
+ | 'set_experience_source';
645
+
646
+ /**
647
+ * Dashboard Spec A (§10A.5) — a DM-issued scene-control directive, surfaced on
648
+ * the chat WebSocket / SSE stream as `{type:"dm_directive", directive, params}`.
649
+ * The backend `ChatDispatcher.emit_dm_directive` emits this AFTER stripping the
650
+ * inline `[SCENE:...]` tag from the streamed narration (the directive fires as
651
+ * the DM finishes speaking). `params` is an open bag keyed by the directive kind
652
+ * (see {@link DmDirectiveKind}); consumers narrow on `directive` then read the
653
+ * params they expect. ADDITIVE — no existing consumer is wired (A-DM0 ships
654
+ * dark); the full `useExperienceSource` wire lands in a later DV phase.
655
+ */
656
+ export type DmDirectiveEvent = {
657
+ type: 'dm_directive';
658
+ timestamp?: number;
659
+ directive: DmDirectiveKind;
660
+ params: Record<string, unknown>;
661
+ };
662
+
611
663
  /**
612
664
  * One field of a creator/admin form, as returned by the R4b form-schema
613
665
  * reference endpoint (`GET /api/v1/schema/{form}`). The backend DERIVES each
@@ -853,6 +905,27 @@ export interface PersonaConfig {
853
905
  * responses — typed optional only as a defensive superset for older cached
854
906
  * payloads; treat a missing value as ``false``. */
855
907
  is_dungeon_master?: boolean;
908
+ /** C3a persona-generation provenance — character name from the source video.
909
+ * ``null`` for manually-created personas. snake_case on the wire (matches
910
+ * sibling fields). Mirrors ``shared/persona_models.py:PersonaConfig.entity_name``. */
911
+ entity_name?: string | null;
912
+ /** C3a: ``true`` when this persona was created by the persona-generation
913
+ * pipeline (drives the "Auto" badge on the personas list). The backend field
914
+ * is required + defaults to ``false``, so it is always present on responses;
915
+ * typed optional only as a defensive superset for older cached payloads. */
916
+ is_auto_generated?: boolean;
917
+ /** C3a: the video used as the source for synthesis + voice cloning. ``null``
918
+ * for manually-created personas. */
919
+ source_video_id?: string | null;
920
+ /** C3a reclone bookkeeping — all transcript-segment indices the worker
921
+ * uploaded to S3 as cached WAV clips at generation time. Empty for
922
+ * manually-created personas. Store-managed; surfaced for the audition/reclone
923
+ * UI's retries-left counter. */
924
+ available_clip_indices?: number[];
925
+ /** C3a reclone bookkeeping — the subset of ``available_clip_indices`` already
926
+ * consumed by the current ``voice_id`` (initial clone + each successful
927
+ * reclone appends). Survives page reload. Store-managed. */
928
+ clips_used?: number[];
856
929
  }
857
930
 
858
931
  // Viseme bundle types — see services/persona/ and shared/viseme_bundle_models.py
@@ -1122,6 +1195,16 @@ export interface CreatePersonaRequest {
1122
1195
  * can drive interactive adventures. Optional; defaults to ``false``
1123
1196
  * server-side. snake_case on the wire (matches sibling fields). */
1124
1197
  is_dungeon_master?: boolean;
1198
+ /** C3a persona-generation provenance (set by the worker, but accepted on
1199
+ * create so a caller can stamp it). Character name from the source video. */
1200
+ entity_name?: string | null;
1201
+ /** C3a: flag a pipeline-created persona. Defaults to ``false`` server-side. */
1202
+ is_auto_generated?: boolean;
1203
+ /** C3a: the source video used for synthesis + voice cloning. */
1204
+ source_video_id?: string | null;
1205
+ /** C3a reclone bookkeeping: the full pool of cached-clip indices uploaded to
1206
+ * S3 at generation time. ``clips_used`` is store-managed, not client-settable. */
1207
+ available_clip_indices?: number[];
1125
1208
  }
1126
1209
 
1127
1210
  export interface UpdatePersonaRequest {
@@ -1163,6 +1246,14 @@ export interface UpdatePersonaRequest {
1163
1246
  * ``null``/``undefined`` skips the field (no change). snake_case on the wire
1164
1247
  * (matches sibling fields). */
1165
1248
  is_dungeon_master?: boolean | null;
1249
+ /** C3a persona-generation provenance. ``null``/``undefined`` skips the field. */
1250
+ entity_name?: string | null;
1251
+ /** C3a: flag a pipeline-created persona. ``null``/``undefined`` skips. */
1252
+ is_auto_generated?: boolean | null;
1253
+ /** C3a: the source video used for synthesis + voice cloning. */
1254
+ source_video_id?: string | null;
1255
+ /** C3a reclone bookkeeping: the full pool of cached-clip indices. */
1256
+ available_clip_indices?: number[] | null;
1166
1257
  }
1167
1258
 
1168
1259
  export interface PersonaListResponse {
@@ -1171,6 +1262,183 @@ export interface PersonaListResponse {
1171
1262
  next_token?: string | null;
1172
1263
  }
1173
1264
 
1265
+ // ==================== C3a persona-generation types ====================
1266
+ // Mirror the backend models in shared/persona_models.py. These back the
1267
+ // auto-generation trigger + job-progress polling + settings UI (spec Steps
1268
+ // 11–14). All snake_case on the wire EXCEPT GeneratePersonasJobResponse, which
1269
+ // the backend serializes with camelCase aliases (jobId/traceId).
1270
+
1271
+ /** Lifecycle of an async persona-generation job. Mirrors
1272
+ * ``shared/persona_models.py:PersonaJobStatus``. Non-terminal:
1273
+ * ``pending``/``synthesizing``/``cloning``; terminal:
1274
+ * ``complete``/``failed``/``partial``. */
1275
+ export type PersonaJobStatus =
1276
+ | 'pending'
1277
+ | 'synthesizing'
1278
+ | 'cloning'
1279
+ | 'complete'
1280
+ | 'failed'
1281
+ | 'partial';
1282
+
1283
+ /** The stage a per-persona failure occurred at. Mirrors
1284
+ * ``shared/persona_models.py:JobErrorStage``. */
1285
+ export type PersonaJobErrorStage =
1286
+ | 'synthesis'
1287
+ | 'extraction'
1288
+ | 'cloning'
1289
+ | 'creation'
1290
+ | 'no_data'
1291
+ | 'cloning_skipped';
1292
+
1293
+ /** Per-user defaults driving the persona-generation pipeline. The voice
1294
+ * defaults are a *fallback* used only when cloning is skipped or fails. Mirrors
1295
+ * ``shared/persona_models.py:PersonaGenerationSettings`` (snake_case wire). */
1296
+ export interface PersonaGenerationSettings {
1297
+ user_id: string;
1298
+ // Voice defaults (fallback when cloning is skipped/fails)
1299
+ default_voice_id: string;
1300
+ default_tts_model_id: string;
1301
+ default_temperature: number;
1302
+ default_speaking_rate: number;
1303
+ default_audio_format: AudioFormat;
1304
+ default_enable_markups: boolean;
1305
+ // Chat defaults
1306
+ default_chat_model_id: string;
1307
+ /** Supports ``{entity_name}`` and ``{video_title}`` placeholders. */
1308
+ default_system_prompt_template?: string | null;
1309
+ default_system_prompt_override: boolean;
1310
+ // Generation rules
1311
+ entity_type_filter: string[];
1312
+ min_dialog_lines: number;
1313
+ min_graph_speakers: number;
1314
+ max_personas: number;
1315
+ auto_generate_enabled: boolean;
1316
+ // Voice cloning
1317
+ voice_clone_max_retries: number;
1318
+ voice_clone_min_clip_seconds: number;
1319
+ /** Store-managed; set on every upsert. Do not construct directly. */
1320
+ updated_at: string;
1321
+ }
1322
+
1323
+ /** Partial body for ``PUT /api/v1/personas/settings/generation`` — every field
1324
+ * optional; an upsert merges supplied (non-null) fields over the stored (or
1325
+ * default) settings. ``user_id``/``updated_at`` are store-managed and rejected
1326
+ * from the client. Mirrors
1327
+ * ``shared/persona_models.py:UpdatePersonaGenSettingsRequest``. */
1328
+ export interface UpdatePersonaGenSettingsRequest {
1329
+ default_voice_id?: string | null;
1330
+ default_tts_model_id?: string | null;
1331
+ default_temperature?: number | null;
1332
+ default_speaking_rate?: number | null;
1333
+ default_audio_format?: AudioFormat | null;
1334
+ default_enable_markups?: boolean | null;
1335
+ default_chat_model_id?: string | null;
1336
+ default_system_prompt_template?: string | null;
1337
+ default_system_prompt_override?: boolean | null;
1338
+ entity_type_filter?: string[] | null;
1339
+ min_dialog_lines?: number | null;
1340
+ min_graph_speakers?: number | null;
1341
+ max_personas?: number | null;
1342
+ auto_generate_enabled?: boolean | null;
1343
+ voice_clone_max_retries?: number | null;
1344
+ voice_clone_min_clip_seconds?: number | null;
1345
+ }
1346
+
1347
+ /** Live counters surfaced by the job-poll endpoint. Mirrors
1348
+ * ``shared/persona_models.py:JobProgress``. */
1349
+ export interface PersonaJobProgress {
1350
+ total_characters: number;
1351
+ synthesized: number;
1352
+ cloned: number;
1353
+ failed: number;
1354
+ }
1355
+
1356
+ /** One per-persona failure recorded on the job without aborting the run.
1357
+ * Mirrors ``shared/persona_models.py:JobError``. */
1358
+ export interface PersonaJobError {
1359
+ persona_name?: string | null;
1360
+ stage: PersonaJobErrorStage;
1361
+ error: string;
1362
+ }
1363
+
1364
+ /** Async persona-generation job record, as returned by
1365
+ * ``GET /api/v1/persona-jobs/{jobId}``. snake_case on the wire (the backend
1366
+ * model has no aliases). Mirrors
1367
+ * ``shared/persona_models.py:AutoGenerationJob``. */
1368
+ export interface AutoGenerationJob {
1369
+ job_id: string;
1370
+ user_id: string;
1371
+ video_id: string;
1372
+ status: PersonaJobStatus;
1373
+ created_at: string;
1374
+ updated_at: string;
1375
+ progress: PersonaJobProgress;
1376
+ persona_ids: string[];
1377
+ errors: PersonaJobError[];
1378
+ /** Used clip indices per persona id, so reclone can pick a different set. */
1379
+ clips_used: Record<string, number[]>;
1380
+ }
1381
+
1382
+ /** 202 envelope from ``POST /api/v1/videos/{videoId}/personas/generate``.
1383
+ * **camelCase wire keys** (``jobId``/``traceId``) — the backend serializes this
1384
+ * model with aliases (unlike the snake_case ``AutoGenerationJob``). Mirrors
1385
+ * ``shared/persona_models.py:GeneratePersonasJobResponse``. */
1386
+ export interface GeneratePersonasJobResponse {
1387
+ jobId: string;
1388
+ status: PersonaJobStatus;
1389
+ /** Per-request correlation id (resource-creating-POST convention). */
1390
+ traceId?: string | null;
1391
+ }
1392
+
1393
+ /** Body for ``POST /api/v1/personas/{personaId}/audition`` (C3a Step 9). All
1394
+ * fields optional — an omitted body renders the backend default sample text in
1395
+ * the persona's current voice. Mirrors ``shared/persona_models.py:AuditionRequest``
1396
+ * (snake_case wire; ``extra="forbid"`` server-side). */
1397
+ export interface AuditionRequest {
1398
+ /** Sample line to synthesize (1–500 chars). Default: the backend sample text. */
1399
+ text?: string;
1400
+ /** Requested format (PCM16 only; the response is always ``audio/wav``). */
1401
+ audio_format?: AudioFormat;
1402
+ }
1403
+
1404
+ /** 200 body of ``POST /api/v1/personas/{personaId}/reclone`` (C3a Step 9).
1405
+ * **camelCase wire keys** (``personaId``/``voiceId``/``clipsUsed``) — the backend
1406
+ * serializes this model with aliases. Mirrors
1407
+ * ``shared/persona_models.py:ReclonedPersonaResponse``. */
1408
+ export interface ReclonedPersonaResponse {
1409
+ personaId: string;
1410
+ voiceId: string;
1411
+ /** The full set of clip indices the current ``voiceId`` was cloned from after
1412
+ * this reclone (initial clone + every successful reclone). */
1413
+ clipsUsed: number[];
1414
+ }
1415
+
1416
+ /** Structured reason a reclone was refused with ``409 Conflict``. The backend
1417
+ * returns ``detail`` as an object (``{error, attempts?}``), which the generic
1418
+ * JSON error path can't surface, so {@link ApiClient.reclonePersona} raises a
1419
+ * {@link RecloneConflictError} carrying this code instead. */
1420
+ export type RecloneConflictCode =
1421
+ | 'voice_clone_max_retries_exhausted'
1422
+ | 'no_candidate_clips_remaining';
1423
+
1424
+ /** Thrown by {@link ApiClient.reclonePersona} on a ``409`` so the review UI can
1425
+ * distinguish "retries exhausted" from "no clips left" and disable the Reclone
1426
+ * control (instead of seeing an opaque ``[object Object]`` message). */
1427
+ export class RecloneConflictError extends Error {
1428
+ readonly code: RecloneConflictCode;
1429
+ readonly attempts?: number;
1430
+ constructor(code: RecloneConflictCode, attempts?: number) {
1431
+ super(
1432
+ code === 'voice_clone_max_retries_exhausted'
1433
+ ? 'No reclone attempts remaining'
1434
+ : 'No unused voice clips remain to reclone from',
1435
+ );
1436
+ this.name = 'RecloneConflictError';
1437
+ this.code = code;
1438
+ this.attempts = attempts;
1439
+ }
1440
+ }
1441
+
1174
1442
  /**
1175
1443
  * Story Engine Phase 5 — a single character Entity for a video, as returned
1176
1444
  * by ``GET /api/v1/tools/videos/{videoId}/characters``. Mirrors the backend
@@ -1675,6 +1943,14 @@ export interface GraphSchemaResponse {
1675
1943
  traceId: string;
1676
1944
  labels: Record<string, GraphLabelSchema>;
1677
1945
  edges: Record<string, GraphEdgeSchema>;
1946
+ /**
1947
+ * Whether `SEER_ENTITY_DEDUP_ENABLED` is on server-side (R5d #454). When
1948
+ * false, the de-dup oracle does not reconcile same-named characters and the
1949
+ * "Accept as new" homonym override is a no-op — so the UI hides that
1950
+ * affordance. Optional for backward compatibility with pre-0.43.0 servers
1951
+ * (treated as `false`).
1952
+ */
1953
+ entityDedupEnabled?: boolean;
1678
1954
  }
1679
1955
 
1680
1956
  /**
@@ -2370,14 +2646,62 @@ export class ApiClient {
2370
2646
  * created node/edge); a 422 (e.g. already resolved, or the payload fails
2371
2647
  * graph validation) surfaces the FastAPI detail as a thrown `Error`. POST
2372
2648
  * `.../documents/{docId}/suggestions/{sid}/accept`.
2649
+ *
2650
+ * `acceptAsNew` (R5d homonym override): accept a same-named character as a
2651
+ * DISTINCT character, skipping de-dup reconciliation and recording a "these
2652
+ * are different" override so the oracle never auto-merges the pair. Omitted
2653
+ * (the default) sends a body-less POST, byte-identical to the legacy accept.
2373
2654
  */
2374
2655
  async acceptSuggestion(
2375
2656
  docId: string,
2376
2657
  suggestionId: string,
2658
+ options?: { acceptAsNew?: boolean },
2377
2659
  ): Promise<AcceptSuggestionResponse> {
2660
+ const init: RequestInit = { method: 'POST' };
2661
+ if (options?.acceptAsNew) {
2662
+ init.body = JSON.stringify({ acceptAsNew: true });
2663
+ }
2378
2664
  return this.request<AcceptSuggestionResponse>(
2379
2665
  `/api/v1/ingestion/documents/${docId}/suggestions/${suggestionId}/accept`,
2380
- { method: 'POST' },
2666
+ init,
2667
+ );
2668
+ }
2669
+
2670
+ /**
2671
+ * Mark two entities as DIFFERENT characters (R5d homonym override) so the
2672
+ * de-dup oracle never reconciles them. `docentId` is the document-authored
2673
+ * (`docent-`) entity, `entityId` the Pegasus character to keep separate.
2674
+ * POST `/api/v1/tools/graph/entities/distinct` → 201.
2675
+ */
2676
+ async markEntitiesDistinct(args: {
2677
+ videoId: string;
2678
+ docentId: string;
2679
+ entityId: string;
2680
+ }): Promise<MarkEntitiesDistinctResponse> {
2681
+ return this.request<MarkEntitiesDistinctResponse>(
2682
+ `/api/v1/tools/graph/entities/distinct`,
2683
+ { method: 'POST', body: JSON.stringify(args) },
2684
+ );
2685
+ }
2686
+
2687
+ /**
2688
+ * Clear a distinctness override (re-arms the de-dup oracle for the pair).
2689
+ * Idempotent — `cleared` is `false` when no override existed. DELETE
2690
+ * `/api/v1/tools/graph/entities/distinct?videoId&docentId&entityId`.
2691
+ */
2692
+ async clearEntitiesDistinct(args: {
2693
+ videoId: string;
2694
+ docentId: string;
2695
+ entityId: string;
2696
+ }): Promise<ClearEntitiesDistinctResponse> {
2697
+ const params = new URLSearchParams({
2698
+ videoId: args.videoId,
2699
+ docentId: args.docentId,
2700
+ entityId: args.entityId,
2701
+ });
2702
+ return this.request<ClearEntitiesDistinctResponse>(
2703
+ `/api/v1/tools/graph/entities/distinct?${params.toString()}`,
2704
+ { method: 'DELETE' },
2381
2705
  );
2382
2706
  }
2383
2707
 
@@ -2566,17 +2890,26 @@ export class ApiClient {
2566
2890
  }
2567
2891
 
2568
2892
  /**
2569
- * List all personas for the current user
2893
+ * List all personas for the current user.
2894
+ *
2895
+ * When ``sourceVideoId`` is set (C3a), the backend delegates to
2896
+ * ``PersonaStore.list_personas_by_video`` and returns ALL personas
2897
+ * auto-generated from that video in one shot (it paginates internally), so
2898
+ * ``limit`` / ``nextToken`` do not apply and the response ``next_token`` is
2899
+ * always ``null``. See {@link listPersonasByVideo} for the convenience wrapper.
2570
2900
  */
2571
2901
  async listPersonas(params?: {
2572
2902
  limit?: number;
2573
2903
  nextToken?: string;
2574
2904
  status?: 'pending' | 'approved';
2905
+ sourceVideoId?: string;
2575
2906
  }): Promise<PersonaListResponse> {
2576
2907
  const searchParams = new URLSearchParams();
2577
2908
  if (params?.limit) searchParams.append('limit', params.limit.toString());
2578
2909
  if (params?.nextToken) searchParams.append('nextToken', params.nextToken);
2579
2910
  if (params?.status) searchParams.append('status', params.status);
2911
+ // Wire param is snake_case (matches the backend Query alias).
2912
+ if (params?.sourceVideoId) searchParams.append('source_video_id', params.sourceVideoId);
2580
2913
 
2581
2914
  const query = searchParams.toString();
2582
2915
  const endpoint = `/api/v1/personas${query ? `?${query}` : ''}`;
@@ -2584,6 +2917,15 @@ export class ApiClient {
2584
2917
  return this.chatRequest<PersonaListResponse>(endpoint);
2585
2918
  }
2586
2919
 
2920
+ /**
2921
+ * C3a: list the personas auto-generated from a given source video. Thin
2922
+ * wrapper over {@link listPersonas} with ``sourceVideoId`` — backs the review
2923
+ * page's roster + the "Auto"/"Pending" badges on the personas list.
2924
+ */
2925
+ async listPersonasByVideo(sourceVideoId: string): Promise<PersonaListResponse> {
2926
+ return this.listPersonas({ sourceVideoId });
2927
+ }
2928
+
2587
2929
  /**
2588
2930
  * Get the default persona for the current user
2589
2931
  */
@@ -2637,6 +2979,169 @@ export class ApiClient {
2637
2979
  });
2638
2980
  }
2639
2981
 
2982
+ // ============ C3a persona-generation (auto-generate + job tracking) ============
2983
+ // Back the trigger entry point + job-progress polling + settings UI
2984
+ // (spec Steps 11–14) plus the review page's audition + reclone controls
2985
+ // (spec Step 13). The audition/reclone backend routes landed with tech-debt
2986
+ // #477 (PR #356), so the matching client methods live below getPersonaJob.
2987
+
2988
+ /**
2989
+ * C3a: fetch the current user's persona-generation settings, or ``null`` when
2990
+ * never saved (the settings UI then falls back to its client-side defaults).
2991
+ * ``GET /api/v1/personas/settings/generation``.
2992
+ */
2993
+ async getPersonaGenSettings(): Promise<PersonaGenerationSettings | null> {
2994
+ return this.chatRequest<PersonaGenerationSettings | null>(
2995
+ '/api/v1/personas/settings/generation',
2996
+ );
2997
+ }
2998
+
2999
+ /**
3000
+ * C3a: upsert the user's persona-generation settings. The body is a partial —
3001
+ * supplied (non-null) fields merge over the stored (or default) settings; the
3002
+ * response is the persisted, fully-populated settings. ``user_id`` /
3003
+ * ``updated_at`` are store-managed. ``PUT /api/v1/personas/settings/generation``.
3004
+ */
3005
+ async updatePersonaGenSettings(
3006
+ body: UpdatePersonaGenSettingsRequest,
3007
+ ): Promise<PersonaGenerationSettings> {
3008
+ return this.chatRequest<PersonaGenerationSettings>(
3009
+ '/api/v1/personas/settings/generation',
3010
+ {
3011
+ method: 'PUT',
3012
+ headers: { 'Content-Type': 'application/json' },
3013
+ body: JSON.stringify(body),
3014
+ },
3015
+ );
3016
+ }
3017
+
3018
+ /**
3019
+ * C3a: trigger auto-generation of personas for a video. Returns a ``202`` job
3020
+ * envelope (``{ jobId, status, traceId }`` — camelCase wire keys). Idempotent
3021
+ * on ``(user, video)``: a second call while a job is still active returns that
3022
+ * job's id instead of spawning a duplicate. Poll {@link getPersonaJob} with the
3023
+ * returned ``jobId``. ``POST /api/v1/videos/{videoId}/personas/generate``.
3024
+ *
3025
+ * C3a-f1 (Studio Cast): pass ``opts.entityIds`` to restrict generation to a
3026
+ * character-Entity-id subset — a per-cast-member "Generate persona" sends that
3027
+ * one id; the Cast "Generate all" sends the whole cast (or omits it). Omitting
3028
+ * ``entityIds`` (or passing an empty list) generates for every qualifying
3029
+ * speaking character — byte-identical to the original whole-video call, so the
3030
+ * body is only sent when a non-empty subset is supplied.
3031
+ */
3032
+ async generatePersonasForVideo(
3033
+ videoId: string,
3034
+ opts?: { entityIds?: string[] },
3035
+ ): Promise<GeneratePersonasJobResponse> {
3036
+ const entityIds = opts?.entityIds?.filter(Boolean) ?? [];
3037
+ const init: RequestInit = { method: 'POST' };
3038
+ if (entityIds.length > 0) {
3039
+ // The backend body is snake_case (no aliases) — mirror the
3040
+ // GeneratePersonasRequest Pydantic model, NOT the camelCase response.
3041
+ init.body = JSON.stringify({ entity_ids: entityIds });
3042
+ }
3043
+ return this.chatRequest<GeneratePersonasJobResponse>(
3044
+ `/api/v1/videos/${encodeURIComponent(videoId)}/personas/generate`,
3045
+ init,
3046
+ );
3047
+ }
3048
+
3049
+ /**
3050
+ * C3a: poll a persona-generation job's status + progress + errors. Ownership
3051
+ * is enforced server-side by reconstructing the partition key from the auth
3052
+ * token (a foreign/unknown id 404s). ``GET /api/v1/persona-jobs/{jobId}``.
3053
+ */
3054
+ async getPersonaJob(jobId: string): Promise<AutoGenerationJob> {
3055
+ return this.chatRequest<AutoGenerationJob>(
3056
+ `/api/v1/persona-jobs/${encodeURIComponent(jobId)}`,
3057
+ );
3058
+ }
3059
+
3060
+ /**
3061
+ * C3a (Step 9 / review page): render a short TTS sample in the persona's
3062
+ * current voice and return the ``audio/wav`` bytes as a ``Blob`` (the caller
3063
+ * plays it via ``URL.createObjectURL`` + ``<audio>``). Allowed for any persona
3064
+ * status so the review page can preview before approval.
3065
+ * ``POST /api/v1/personas/{personaId}/audition``.
3066
+ *
3067
+ * The response is binary, so this bypasses the JSON ``chatRequest`` wrapper and
3068
+ * attaches the bearer token directly (same pattern as {@link getSeedImageBlob}).
3069
+ * An omitted ``body`` renders the backend default sample text.
3070
+ */
3071
+ async auditionPersona(
3072
+ personaId: string,
3073
+ body?: AuditionRequest,
3074
+ options: { signal?: AbortSignal } = {},
3075
+ ): Promise<Blob> {
3076
+ const url = `${this.chatApiBaseUrl}/api/v1/personas/${encodeURIComponent(personaId)}/audition`;
3077
+ const headers: Record<string, string> = { 'Content-Type': 'application/json' };
3078
+ if (this.sessionToken) {
3079
+ headers['Authorization'] = `Bearer ${this.sessionToken}`;
3080
+ }
3081
+ const response = await fetch(url, {
3082
+ method: 'POST',
3083
+ headers,
3084
+ // Always send a JSON body (``{}`` when none) so FastAPI parses an empty
3085
+ // object rather than choking on a missing content-type.
3086
+ body: JSON.stringify(body ?? {}),
3087
+ signal: options.signal,
3088
+ });
3089
+ if (!response.ok) {
3090
+ const detail = await response
3091
+ .json()
3092
+ .then((b: { detail?: string; error?: string }) => b.detail ?? b.error)
3093
+ .catch(() => undefined);
3094
+ throw new Error(detail || `Audition render failed: HTTP ${response.status}`);
3095
+ }
3096
+ return await response.blob();
3097
+ }
3098
+
3099
+ /**
3100
+ * C3a (Step 9 / review page): re-clone the persona's voice from a DIFFERENT
3101
+ * subset of its cached ``persona-clips`` (available minus already-used) without
3102
+ * re-downloading the video. Swaps ``voice_id`` and appends to ``clips_used``;
3103
+ * returns the new ``voiceId`` + the full ``clipsUsed`` set.
3104
+ * ``POST /api/v1/personas/{personaId}/reclone``.
3105
+ *
3106
+ * Bypasses ``chatRequest`` so a ``409`` (whose ``detail`` is a structured
3107
+ * object the generic JSON error path renders as ``[object Object]``) is raised
3108
+ * as a typed {@link RecloneConflictError} the review UI can branch on.
3109
+ */
3110
+ async reclonePersona(personaId: string): Promise<ReclonedPersonaResponse> {
3111
+ const url = `${this.chatApiBaseUrl}/api/v1/personas/${encodeURIComponent(personaId)}/reclone`;
3112
+ const headers: Record<string, string> = { 'Content-Type': 'application/json' };
3113
+ if (this.sessionToken) {
3114
+ headers['Authorization'] = `Bearer ${this.sessionToken}`;
3115
+ }
3116
+ const response = await fetch(url, { method: 'POST', headers });
3117
+ if (response.ok) {
3118
+ return (await response.json()) as ReclonedPersonaResponse;
3119
+ }
3120
+ // Surface the structured 409 (``detail`` is ``{error, attempts?}``) as a
3121
+ // typed error; everything else flattens to the FastAPI ``detail`` string.
3122
+ const errBody = await response
3123
+ .json()
3124
+ .then((b: { detail?: unknown }) => b.detail)
3125
+ .catch(() => undefined);
3126
+ if (
3127
+ response.status === 409 &&
3128
+ errBody &&
3129
+ typeof errBody === 'object' &&
3130
+ typeof (errBody as { error?: unknown }).error === 'string'
3131
+ ) {
3132
+ const { error, attempts } = errBody as { error: string; attempts?: number };
3133
+ if (
3134
+ error === 'voice_clone_max_retries_exhausted' ||
3135
+ error === 'no_candidate_clips_remaining'
3136
+ ) {
3137
+ throw new RecloneConflictError(error, attempts);
3138
+ }
3139
+ }
3140
+ const message =
3141
+ typeof errBody === 'string' ? errBody : `Reclone failed: HTTP ${response.status}`;
3142
+ throw new Error(message);
3143
+ }
3144
+
2640
3145
  // ==================== Image API Methods ====================
2641
3146
  // Note: Images are served by the Chat API
2642
3147
 
@@ -17,12 +17,17 @@ import type { buildHelloPayload } from '../audio';
17
17
  /**
18
18
  * What the conversation is bound to. `VIDEO` = the Watch surface (`videoId`);
19
19
  * `STUDIO_SESSION` = a Studio cast/play surface (`entityId` and/or
20
- * `adventureSessionId`); `NONE` = an unbound general chat. The values are the
21
- * `kind` discriminator carried on the binding.
20
+ * `adventureSessionId`); `PERSONA` = a standalone persona-face chat bound to a
21
+ * single `personaId` (the dashboard "Chat with a persona" floater — each
22
+ * persona is a DISTINCT binding so selecting a second persona rebinds/remounts
23
+ * rather than colliding on the generic `NONE` key, which is the originally
24
+ * specified switch-persona bug); `NONE` = an unbound general chat. The values
25
+ * are the `kind` discriminator carried on the binding.
22
26
  */
23
27
  export const ConversationContextKind = {
24
28
  VIDEO: 'video',
25
29
  STUDIO_SESSION: 'studio_session',
30
+ PERSONA: 'persona',
26
31
  NONE: 'none',
27
32
  } as const;
28
33
 
@@ -39,6 +44,16 @@ export type ConversationContextKind =
39
44
  export interface ConversationContextBinding {
40
45
  kind: ConversationContextKind;
41
46
  videoId?: string;
47
+ /**
48
+ * The persona this conversation is bound to (a `ConversationContextKind.PERSONA`
49
+ * standalone persona-face chat). It makes each persona a DISTINCT binding key
50
+ * so `ConversationOverlayProvider.open()` rebinds when the user picks a second
51
+ * persona instead of short-circuiting on a shared `NONE` key. Like the other
52
+ * id fields it is also a `buildHelloPayload` arg, so the binding cannot drift
53
+ * from what the hello can carry; the controller still overlays the active
54
+ * participant's `personaId` on top, so a seat-level persona wins when present.
55
+ */
56
+ personaId?: string;
42
57
  entityId?: string;
43
58
  adventureSessionId?: string;
44
59
  partyPersonaIds?: string[];
@@ -67,9 +82,13 @@ export type HelloArgs = Parameters<typeof buildHelloPayload>[0];
67
82
  */
68
83
  export function toHelloArgs(
69
84
  binding: ConversationContextBinding,
70
- ): Pick<HelloArgs, 'videoId' | 'entityId' | 'adventureSessionId' | 'partyPersonaIds'> {
85
+ ): Pick<
86
+ HelloArgs,
87
+ 'videoId' | 'personaId' | 'entityId' | 'adventureSessionId' | 'partyPersonaIds'
88
+ > {
71
89
  return {
72
90
  ...(binding.videoId ? { videoId: binding.videoId } : {}),
91
+ ...(binding.personaId ? { personaId: binding.personaId } : {}),
73
92
  ...(binding.entityId ? { entityId: binding.entityId } : {}),
74
93
  ...(binding.adventureSessionId
75
94
  ? { adventureSessionId: binding.adventureSessionId }
@@ -222,6 +222,14 @@ export class ConversationController {
222
222
  ? { adventureSessionId: args.adventureSessionId }
223
223
  : {}),
224
224
  ...(args.partyPersonaIds ? { partyPersonaIds: args.partyPersonaIds } : {}),
225
+ // Persona scope threads on every send, not just the hello: a standalone
226
+ // PERSONA binding (kind:'persona') has no explicit participant in the
227
+ // overlay-default path, so the binding-level personaId is the only scope.
228
+ // The active participant's personaId still WINS when present (overlay
229
+ // order mirrors buildHello), so a seated cast persona is unaffected. For
230
+ // non-PERSONA bindings args.personaId is undefined ⇒ the frame stays
231
+ // byte-identical (land-dark).
232
+ ...(args.personaId ? { personaId: args.personaId } : {}),
225
233
  ...(active?.personaId ? { personaId: active.personaId } : {}),
226
234
  ...(modelId ? { modelId } : {}),
227
235
  // Omitted when empty so a zero-history send stays byte-identical to the