@escapeaihq/client-core 0.12.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.
Files changed (242) hide show
  1. package/README.md +32 -7
  2. package/dist/adapters/capabilities.d.ts +10 -0
  3. package/dist/adapters/capabilities.d.ts.map +1 -0
  4. package/dist/adapters/capabilities.js +2 -0
  5. package/dist/adapters/capabilities.js.map +1 -0
  6. package/dist/adapters/chatAdapter.d.ts +38 -0
  7. package/dist/adapters/chatAdapter.d.ts.map +1 -0
  8. package/dist/adapters/chatAdapter.js +88 -0
  9. package/dist/adapters/chatAdapter.js.map +1 -0
  10. package/dist/adapters/directorAdapter.d.ts +62 -0
  11. package/dist/adapters/directorAdapter.d.ts.map +1 -0
  12. package/dist/adapters/directorAdapter.js +71 -0
  13. package/dist/adapters/directorAdapter.js.map +1 -0
  14. package/dist/adapters/imageAdapter.d.ts +44 -0
  15. package/dist/adapters/imageAdapter.d.ts.map +1 -0
  16. package/dist/adapters/imageAdapter.js +73 -0
  17. package/dist/adapters/imageAdapter.js.map +1 -0
  18. package/dist/adapters/index.d.ts +47 -0
  19. package/dist/adapters/index.d.ts.map +1 -0
  20. package/dist/adapters/index.js +41 -0
  21. package/dist/adapters/index.js.map +1 -0
  22. package/dist/adapters/registry.d.ts +98 -0
  23. package/dist/adapters/registry.d.ts.map +1 -0
  24. package/dist/adapters/registry.js +106 -0
  25. package/dist/adapters/registry.js.map +1 -0
  26. package/dist/adapters/worldAdapter.d.ts +142 -0
  27. package/dist/adapters/worldAdapter.d.ts.map +1 -0
  28. package/dist/adapters/worldAdapter.js +164 -0
  29. package/dist/adapters/worldAdapter.js.map +1 -0
  30. package/dist/admin.d.ts +323 -0
  31. package/dist/admin.d.ts.map +1 -0
  32. package/dist/admin.js +198 -0
  33. package/dist/admin.js.map +1 -0
  34. package/dist/api.d.ts +1512 -4
  35. package/dist/api.d.ts.map +1 -1
  36. package/dist/api.js +820 -52
  37. package/dist/api.js.map +1 -1
  38. package/dist/audio.d.ts +33 -1
  39. package/dist/audio.d.ts.map +1 -1
  40. package/dist/audio.js +4 -1
  41. package/dist/audio.js.map +1 -1
  42. package/dist/castProjection.d.ts +35 -0
  43. package/dist/castProjection.d.ts.map +1 -0
  44. package/dist/castProjection.js +80 -0
  45. package/dist/castProjection.js.map +1 -0
  46. package/dist/conversation/binding.d.ts +77 -0
  47. package/dist/conversation/binding.d.ts.map +1 -0
  48. package/dist/conversation/binding.js +57 -0
  49. package/dist/conversation/binding.js.map +1 -0
  50. package/dist/conversation/controller.d.ts +209 -0
  51. package/dist/conversation/controller.d.ts.map +1 -0
  52. package/dist/conversation/controller.js +350 -0
  53. package/dist/conversation/controller.js.map +1 -0
  54. package/dist/conversation/effectiveModel.d.ts +62 -0
  55. package/dist/conversation/effectiveModel.d.ts.map +1 -0
  56. package/dist/conversation/effectiveModel.js +73 -0
  57. package/dist/conversation/effectiveModel.js.map +1 -0
  58. package/dist/conversation/index.d.ts +27 -0
  59. package/dist/conversation/index.d.ts.map +1 -0
  60. package/dist/conversation/index.js +27 -0
  61. package/dist/conversation/index.js.map +1 -0
  62. package/dist/conversation/participant.d.ts +66 -0
  63. package/dist/conversation/participant.d.ts.map +1 -0
  64. package/dist/conversation/participant.js +36 -0
  65. package/dist/conversation/participant.js.map +1 -0
  66. package/dist/conversation/presence.d.ts +56 -0
  67. package/dist/conversation/presence.d.ts.map +1 -0
  68. package/dist/conversation/presence.js +34 -0
  69. package/dist/conversation/presence.js.map +1 -0
  70. package/dist/conversation/presenceBus.d.ts +42 -0
  71. package/dist/conversation/presenceBus.d.ts.map +1 -0
  72. package/dist/conversation/presenceBus.js +81 -0
  73. package/dist/conversation/presenceBus.js.map +1 -0
  74. package/dist/conversation/presenceRegistry.d.ts +49 -0
  75. package/dist/conversation/presenceRegistry.d.ts.map +1 -0
  76. package/dist/conversation/presenceRegistry.js +59 -0
  77. package/dist/conversation/presenceRegistry.js.map +1 -0
  78. package/dist/conversation/roster.d.ts +72 -0
  79. package/dist/conversation/roster.d.ts.map +1 -0
  80. package/dist/conversation/roster.js +69 -0
  81. package/dist/conversation/roster.js.map +1 -0
  82. package/dist/conversation/rosterProjection.d.ts +52 -0
  83. package/dist/conversation/rosterProjection.d.ts.map +1 -0
  84. package/dist/conversation/rosterProjection.js +74 -0
  85. package/dist/conversation/rosterProjection.js.map +1 -0
  86. package/dist/conversation/router.d.ts +74 -0
  87. package/dist/conversation/router.d.ts.map +1 -0
  88. package/dist/conversation/router.js +58 -0
  89. package/dist/conversation/router.js.map +1 -0
  90. package/dist/conversation/runtime.d.ts +64 -0
  91. package/dist/conversation/runtime.d.ts.map +1 -0
  92. package/dist/conversation/runtime.js +172 -0
  93. package/dist/conversation/runtime.js.map +1 -0
  94. package/dist/conversation/types.d.ts +99 -0
  95. package/dist/conversation/types.d.ts.map +1 -0
  96. package/dist/conversation/types.js +13 -0
  97. package/dist/conversation/types.js.map +1 -0
  98. package/dist/conversation/voice.d.ts +185 -0
  99. package/dist/conversation/voice.d.ts.map +1 -0
  100. package/dist/conversation/voice.js +307 -0
  101. package/dist/conversation/voice.js.map +1 -0
  102. package/dist/graphSchema.d.ts +201 -13
  103. package/dist/graphSchema.d.ts.map +1 -1
  104. package/dist/graphSchema.js +258 -9
  105. package/dist/graphSchema.js.map +1 -1
  106. package/dist/http.d.ts +20 -0
  107. package/dist/http.d.ts.map +1 -0
  108. package/dist/http.js +57 -0
  109. package/dist/http.js.map +1 -0
  110. package/dist/index.d.ts +6 -0
  111. package/dist/index.d.ts.map +1 -1
  112. package/dist/index.js +9 -0
  113. package/dist/index.js.map +1 -1
  114. package/dist/platformAssistant.d.ts +155 -0
  115. package/dist/platformAssistant.d.ts.map +1 -0
  116. package/dist/platformAssistant.js +256 -0
  117. package/dist/platformAssistant.js.map +1 -0
  118. package/dist/reactor/chunkDistribution.d.ts +43 -0
  119. package/dist/reactor/chunkDistribution.d.ts.map +1 -0
  120. package/dist/reactor/chunkDistribution.js +85 -0
  121. package/dist/reactor/chunkDistribution.js.map +1 -0
  122. package/dist/reactor/index.d.ts +2 -0
  123. package/dist/reactor/index.d.ts.map +1 -1
  124. package/dist/reactor/index.js +5 -0
  125. package/dist/reactor/index.js.map +1 -1
  126. package/dist/reactor/longLiveCommandDispatcher.d.ts +103 -0
  127. package/dist/reactor/longLiveCommandDispatcher.d.ts.map +1 -0
  128. package/dist/reactor/longLiveCommandDispatcher.js +87 -0
  129. package/dist/reactor/longLiveCommandDispatcher.js.map +1 -0
  130. package/dist/reactor/scenesFromEnrichment.d.ts.map +1 -1
  131. package/dist/reactor/scenesFromEnrichment.js +2 -66
  132. package/dist/reactor/scenesFromEnrichment.js.map +1 -1
  133. package/dist/reactor/seedImageOrchestrator.d.ts +6 -9
  134. package/dist/reactor/seedImageOrchestrator.d.ts.map +1 -1
  135. package/dist/reactor/seedImageOrchestrator.js +12 -13
  136. package/dist/reactor/seedImageOrchestrator.js.map +1 -1
  137. package/dist/reactor/storyTimeline.d.ts +44 -0
  138. package/dist/reactor/storyTimeline.d.ts.map +1 -0
  139. package/dist/reactor/storyTimeline.js +95 -0
  140. package/dist/reactor/storyTimeline.js.map +1 -0
  141. package/dist/storyGraph.d.ts +70 -0
  142. package/dist/storyGraph.d.ts.map +1 -0
  143. package/dist/storyGraph.js +178 -0
  144. package/dist/storyGraph.js.map +1 -0
  145. package/dist/vision/VisionSourceController.d.ts +127 -0
  146. package/dist/vision/VisionSourceController.d.ts.map +1 -0
  147. package/dist/vision/VisionSourceController.js +284 -0
  148. package/dist/vision/VisionSourceController.js.map +1 -0
  149. package/dist/vision/index.d.ts +4 -0
  150. package/dist/vision/index.d.ts.map +1 -1
  151. package/dist/vision/index.js +2 -0
  152. package/dist/vision/index.js.map +1 -1
  153. package/dist/vision/sourceKinds.d.ts +65 -0
  154. package/dist/vision/sourceKinds.d.ts.map +1 -0
  155. package/dist/vision/sourceKinds.js +26 -0
  156. package/dist/vision/sourceKinds.js.map +1 -0
  157. package/dist/websocket.d.ts +92 -0
  158. package/dist/websocket.d.ts.map +1 -1
  159. package/dist/websocket.js.map +1 -1
  160. package/package.json +1 -1
  161. package/src/__tests__/adapters-capabilities.test.ts +46 -0
  162. package/src/__tests__/adapters-chat.test.ts +172 -0
  163. package/src/__tests__/adapters-director.test.ts +95 -0
  164. package/src/__tests__/adapters-image.test.ts +133 -0
  165. package/src/__tests__/adapters-platform.test.ts +95 -0
  166. package/src/__tests__/adapters-registry.test.ts +189 -0
  167. package/src/__tests__/adapters-world.test.ts +296 -0
  168. package/src/__tests__/admin.test.ts +312 -0
  169. package/src/__tests__/adventures-party.test.ts +219 -0
  170. package/src/__tests__/adventures.test.ts +282 -0
  171. package/src/__tests__/api-pollers.test.ts +4 -0
  172. package/src/__tests__/api.clip-lookup.test.ts +64 -0
  173. package/src/__tests__/api.list-images-filters.test.ts +103 -0
  174. package/src/__tests__/api.test.ts +553 -0
  175. package/src/__tests__/audio.test.ts +65 -0
  176. package/src/__tests__/cast.test.ts +95 -0
  177. package/src/__tests__/castProjection.test.ts +167 -0
  178. package/src/__tests__/conversation/binding.test.ts +62 -0
  179. package/src/__tests__/conversation/controller.test.ts +732 -0
  180. package/src/__tests__/conversation/effectiveModel.test.ts +169 -0
  181. package/src/__tests__/conversation/headlessRenderer.ts +46 -0
  182. package/src/__tests__/conversation/presenceBus.test.ts +236 -0
  183. package/src/__tests__/conversation/presenceRegistry.test.ts +73 -0
  184. package/src/__tests__/conversation/roster.test.ts +100 -0
  185. package/src/__tests__/conversation/rosterProjection.test.ts +142 -0
  186. package/src/__tests__/conversation/router.test.ts +81 -0
  187. package/src/__tests__/conversation/runtime.test.ts +206 -0
  188. package/src/__tests__/conversation/voice.test.ts +440 -0
  189. package/src/__tests__/documents.test.ts +360 -0
  190. package/src/__tests__/graphSchema.test.ts +218 -9
  191. package/src/__tests__/longLiveCommandDispatcher.test.ts +185 -0
  192. package/src/__tests__/monitoring.test.ts +162 -0
  193. package/src/__tests__/persona-generation.test.ts +352 -0
  194. package/src/__tests__/platformAssistant.test.ts +484 -0
  195. package/src/__tests__/reactor/storyTimeline.test.ts +186 -0
  196. package/src/__tests__/regeneration.test.ts +486 -0
  197. package/src/__tests__/stories.test.ts +171 -0
  198. package/src/__tests__/storyGraph.test.ts +134 -0
  199. package/src/__tests__/tools-wrappers.test.ts +272 -0
  200. package/src/__tests__/videoGraph.test.ts +94 -0
  201. package/src/__tests__/websocket.test.ts +263 -0
  202. package/src/adapters/capabilities.ts +24 -0
  203. package/src/adapters/chatAdapter.ts +114 -0
  204. package/src/adapters/directorAdapter.ts +126 -0
  205. package/src/adapters/imageAdapter.ts +100 -0
  206. package/src/adapters/index.ts +67 -0
  207. package/src/adapters/registry.ts +159 -0
  208. package/src/adapters/worldAdapter.ts +272 -0
  209. package/src/admin.ts +517 -0
  210. package/src/api.ts +2215 -95
  211. package/src/audio.ts +35 -0
  212. package/src/castProjection.ts +95 -0
  213. package/src/conversation/binding.ts +100 -0
  214. package/src/conversation/controller.ts +447 -0
  215. package/src/conversation/effectiveModel.ts +111 -0
  216. package/src/conversation/index.ts +27 -0
  217. package/src/conversation/participant.ts +71 -0
  218. package/src/conversation/presence.ts +60 -0
  219. package/src/conversation/presenceBus.ts +109 -0
  220. package/src/conversation/presenceRegistry.ts +83 -0
  221. package/src/conversation/roster.ts +111 -0
  222. package/src/conversation/rosterProjection.ts +98 -0
  223. package/src/conversation/router.ts +96 -0
  224. package/src/conversation/runtime.ts +188 -0
  225. package/src/conversation/types.ts +100 -0
  226. package/src/conversation/voice.ts +402 -0
  227. package/src/graphSchema.ts +396 -13
  228. package/src/http.ts +72 -0
  229. package/src/index.ts +9 -0
  230. package/src/platformAssistant.ts +347 -0
  231. package/src/reactor/chunkDistribution.ts +98 -0
  232. package/src/reactor/index.ts +5 -0
  233. package/src/reactor/longLiveCommandDispatcher.ts +156 -0
  234. package/src/reactor/scenesFromEnrichment.ts +11 -76
  235. package/src/reactor/seedImageOrchestrator.ts +12 -13
  236. package/src/reactor/storyTimeline.ts +127 -0
  237. package/src/storyGraph.ts +298 -0
  238. package/src/vision/VisionSourceController.ts +354 -0
  239. package/src/vision/__tests__/VisionSourceController.test.ts +719 -0
  240. package/src/vision/index.ts +13 -0
  241. package/src/vision/sourceKinds.ts +75 -0
  242. package/src/websocket.ts +99 -3
package/src/api.ts CHANGED
@@ -4,6 +4,7 @@
4
4
 
5
5
  import type { AudioFormat } from './audioProtocol';
6
6
  import { isAbortError } from './reactor/abortUtils';
7
+ import { requestJson } from './http';
7
8
  import type {
8
9
  EntityContext as ReactorEntityContext,
9
10
  PersonaContext as ReactorPersonaContext,
@@ -161,6 +162,358 @@ export interface VideoDeletionResponse {
161
162
  errors?: string[] | null;
162
163
  }
163
164
 
165
+ // ============= Narrative Regeneration types (M7 Phase 6 / Story Engine) =============
166
+
167
+ /**
168
+ * Lifecycle status of a regeneration run. Mirrors
169
+ * `shared/models.py::RegenerationRunStatus` (a Python StrEnum) — the worker
170
+ * walks QUEUED → RUNNING → MERGING → COMPLETE, or terminates in FAILED /
171
+ * CANCELLED. Exposed as a const map (not bare literals) so call sites compare
172
+ * against `REGENERATION_STATUS.COMPLETE` rather than `'complete'`.
173
+ */
174
+ export type RegenerationRunStatus =
175
+ | 'queued'
176
+ | 'running'
177
+ | 'merging'
178
+ | 'complete'
179
+ | 'failed'
180
+ | 'cancelled';
181
+
182
+ /** Const map of every {@link RegenerationRunStatus} value (mirrors the backend StrEnum). */
183
+ export const REGENERATION_STATUS = {
184
+ QUEUED: 'queued',
185
+ RUNNING: 'running',
186
+ MERGING: 'merging',
187
+ COMPLETE: 'complete',
188
+ FAILED: 'failed',
189
+ CANCELLED: 'cancelled',
190
+ } as const satisfies Record<string, RegenerationRunStatus>;
191
+
192
+ /**
193
+ * Terminal statuses: a run in one of these will never transition again.
194
+ * Mirrors `shared/models.py::REGENERATION_TERMINAL_STATUSES`. The poller
195
+ * resolves on COMPLETE / CANCELLED and throws on FAILED — but a consumer
196
+ * rendering history can use this set to gate "in-flight" affordances.
197
+ */
198
+ export const REGENERATION_TERMINAL_STATUSES: readonly RegenerationRunStatus[] = [
199
+ REGENERATION_STATUS.COMPLETE,
200
+ REGENERATION_STATUS.FAILED,
201
+ REGENERATION_STATUS.CANCELLED,
202
+ ] as const;
203
+
204
+ /**
205
+ * The regeneration scope kind. Mirrors the backend scope grammar
206
+ * (`shared/models.py::parse_regeneration_scope`): `acts` / `characters` are
207
+ * BARE (whole-narrative), `scene` / `arc` are TARGETED (carry an `<id>`).
208
+ */
209
+ export type RegenerationScopeKind = 'acts' | 'characters' | 'scene' | 'arc';
210
+
211
+ /** Scope kinds that regenerate a whole narrative dimension (no target id). */
212
+ export const REGEN_SCOPE_BARE_KINDS: readonly RegenerationScopeKind[] = [
213
+ 'acts',
214
+ 'characters',
215
+ ] as const;
216
+
217
+ /** Scope kinds that target a single node by id (`<kind>:<id>`). */
218
+ export const REGEN_SCOPE_TARGETED_KINDS: readonly RegenerationScopeKind[] = [
219
+ 'scene',
220
+ 'arc',
221
+ ] as const;
222
+
223
+ /** Separator between a targeted scope's kind and its id (mirrors `REGEN_SCOPE_SEPARATOR`). */
224
+ export const REGEN_SCOPE_SEPARATOR = ':';
225
+
226
+ /**
227
+ * Build a wire-format scope string from a kind + optional target id, mirroring
228
+ * the backend grammar so callers never hand-roll `'scene:' + id`. A bare kind
229
+ * (`acts` / `characters`) MUST NOT carry a target; a targeted kind
230
+ * (`scene` / `arc`) MUST. Throws on a contract violation so a UI bug surfaces
231
+ * locally rather than as a server-side 422.
232
+ */
233
+ export function buildRegenerationScope(
234
+ kind: RegenerationScopeKind,
235
+ targetId?: string,
236
+ ): string {
237
+ const isTargeted = REGEN_SCOPE_TARGETED_KINDS.includes(kind);
238
+ if (isTargeted) {
239
+ if (!targetId) {
240
+ throw new Error(`Scope kind "${kind}" requires a target id`);
241
+ }
242
+ return `${kind}${REGEN_SCOPE_SEPARATOR}${targetId}`;
243
+ }
244
+ if (targetId) {
245
+ throw new Error(`Scope kind "${kind}" does not take a target id`);
246
+ }
247
+ return kind;
248
+ }
249
+
250
+ /**
251
+ * Request body for `POST .../graph/{videoId}/regenerate`. Mirrors
252
+ * `api/tools/schemas.py::RegenerateRequest` (`extra="forbid"`). `scope` is
253
+ * validated server-side against the grammar (422 on malformed); use
254
+ * {@link buildRegenerationScope} to construct it. `promptAddon` is optional
255
+ * creator-steering text appended to the Pegasus prompt (server caps the length).
256
+ */
257
+ export interface RegenerateRequest {
258
+ scope: string;
259
+ promptAddon?: string | null;
260
+ /**
261
+ * Optional docIds of accepted documents whose knowledge is folded into this
262
+ * re-run ADDITIVELY — the base prompts are never replaced (R6c). Mirrors the
263
+ * backend field: max 20 ids; summaries are resolved read-only server-side;
264
+ * unknown/foreign docIds are silently ignored and duplicates de-duplicated
265
+ * (first occurrence wins), so the response's `appliedDocumentIds` may be
266
+ * shorter than this list. NOT nullable: the backend model is `list[str]`
267
+ * (non-nullable, defaults to `[]` when omitted), so a JSON `null` would 422 —
268
+ * omit the field instead.
269
+ */
270
+ appliedDocumentIds?: string[];
271
+ }
272
+
273
+ /**
274
+ * A single regeneration run. Mirrors
275
+ * `api/tools/schemas.py::RegenerationRunResponse` — the POST 202 body, the GET
276
+ * detail body, and each entry in {@link RegenerationListResponse.runs}.
277
+ * `delta` is empty (`{}`) until the run merges; once merged it carries
278
+ * `{ nodes: { added, updated, preservedUser, removed }, edges: { ... } }`.
279
+ */
280
+ export interface RegenerationRunResponse {
281
+ traceId: string;
282
+ runId: string;
283
+ videoId: string;
284
+ scope: string;
285
+ status: RegenerationRunStatus;
286
+ statusUrl: string;
287
+ createdAt: string;
288
+ promptAddon?: string | null;
289
+ startedAt?: string | null;
290
+ completedAt?: string | null;
291
+ delta: Record<string, unknown>;
292
+ error?: string | null;
293
+ /**
294
+ * docIds of the accepted documents actually applied to this run (R6c) —
295
+ * de-duplicated, unknown/foreign ids dropped server-side. Optional so this
296
+ * client stays compatible with pre-R6c backends that omit the field; current
297
+ * backends always send it (`[]` when none were applied).
298
+ */
299
+ appliedDocumentIds?: string[];
300
+ }
301
+
302
+ /**
303
+ * Count buckets a merged run reports under {@link RegenerationRunResponse.delta}
304
+ * `.nodes`. Mirrors the backend delta keys (`shared/regeneration_merge.py::
305
+ * DELTA_*`), the single source of truth for these names crossing the store/API
306
+ * boundary. Every key is always present once a run merges (the backend seeds
307
+ * them all to 0), so a UI summarizing the delta never has to guard for absence.
308
+ */
309
+ export interface RegenerationNodeCounts {
310
+ added: number;
311
+ updated: number;
312
+ preservedUser: number;
313
+ removed: number;
314
+ }
315
+
316
+ /**
317
+ * Delta bucket key strings, mirroring `shared/regeneration_merge.py::DELTA_*`.
318
+ * Exposed as a const map so call sites read `delta[REGEN_DELTA_KEYS.nodes]`
319
+ * rather than re-typing the literals (single source of truth on the wire names).
320
+ */
321
+ export const REGEN_DELTA_KEYS = {
322
+ nodes: 'nodes',
323
+ edges: 'edges',
324
+ added: 'added',
325
+ updated: 'updated',
326
+ preservedUser: 'preservedUser',
327
+ removed: 'removed',
328
+ } as const;
329
+
330
+ /**
331
+ * Extract the `nodes` count buckets from a run's {@link RegenerationRunResponse.delta}.
332
+ *
333
+ * `delta` is typed `Record<string, unknown>` (it carries `nodes` + `edges`
334
+ * sub-objects once merged, and is `{}` before merge), so a UI that wants the
335
+ * "N updated · M preserved · K added · R removed" summary needs a single,
336
+ * tested narrowing rather than ad-hoc casts at each call site. Returns all-zero
337
+ * counts when the delta is empty/malformed (an unmerged or failed run), and
338
+ * coerces any non-numeric / negative bucket to 0 so the summary line is always
339
+ * safe to render.
340
+ */
341
+ export function parseRegenerationNodeCounts(
342
+ delta: Record<string, unknown> | null | undefined,
343
+ ): RegenerationNodeCounts {
344
+ const empty: RegenerationNodeCounts = {
345
+ added: 0,
346
+ updated: 0,
347
+ preservedUser: 0,
348
+ removed: 0,
349
+ };
350
+ const nodes = delta?.[REGEN_DELTA_KEYS.nodes];
351
+ if (typeof nodes !== 'object' || nodes === null) {
352
+ return empty;
353
+ }
354
+ const bucket = nodes as Record<string, unknown>;
355
+ const num = (value: unknown): number =>
356
+ typeof value === 'number' && Number.isFinite(value) && value > 0
357
+ ? Math.floor(value)
358
+ : 0;
359
+ return {
360
+ added: num(bucket[REGEN_DELTA_KEYS.added]),
361
+ updated: num(bucket[REGEN_DELTA_KEYS.updated]),
362
+ preservedUser: num(bucket[REGEN_DELTA_KEYS.preservedUser]),
363
+ removed: num(bucket[REGEN_DELTA_KEYS.removed]),
364
+ };
365
+ }
366
+
367
+ /**
368
+ * Response listing a video's regeneration runs (newest-first). Mirrors
369
+ * `api/tools/schemas.py::RegenerationListResponse`. `nextCursor` is an opaque
370
+ * pagination cursor (null when there is no further page).
371
+ */
372
+ export interface RegenerationListResponse {
373
+ traceId: string;
374
+ videoId: string;
375
+ runs: RegenerationRunResponse[];
376
+ nextCursor: string | null;
377
+ }
378
+
379
+ // ==================== Source Document types (M7 Phase 4) ====================
380
+
381
+ /**
382
+ * Mirrors `shared/models.py::DocumentKind` (a Python StrEnum). The classifier
383
+ * tags each uploaded source document with one of these kinds; the chat
384
+ * `document_search` tool can filter by it.
385
+ */
386
+ export type DocumentKind = 'script' | 'notes' | 'bible' | 'transcript' | 'other';
387
+
388
+ /**
389
+ * Mirrors `shared/models.py::DOC_STATUS_*` (a Literal + Final-constant set,
390
+ * NOT a StrEnum — same pattern as {@link EnrichmentStatus}). The
391
+ * document-processing pipeline advances a doc through these states; narrowing
392
+ * here lets callers compare against the exported constants below instead of
393
+ * bare string literals.
394
+ */
395
+ export type DocumentStatus = 'pending' | 'parsing' | 'extracting' | 'ready' | 'failed';
396
+
397
+ export const DOC_STATUS_PENDING: DocumentStatus = 'pending';
398
+ export const DOC_STATUS_PARSING: DocumentStatus = 'parsing';
399
+ export const DOC_STATUS_EXTRACTING: DocumentStatus = 'extracting';
400
+ export const DOC_STATUS_READY: DocumentStatus = 'ready';
401
+ export const DOC_STATUS_FAILED: DocumentStatus = 'failed';
402
+
403
+ /**
404
+ * Mirrors `shared/models.py::SuggestionStatus` (Literal + Final constants).
405
+ * A pipeline-extracted graph suggestion is `pending` until a user accepts or
406
+ * rejects it via the document-detail endpoints.
407
+ */
408
+ export type SuggestionStatus = 'pending' | 'accepted' | 'rejected';
409
+
410
+ export const SUGGESTION_STATUS_PENDING: SuggestionStatus = 'pending';
411
+ export const SUGGESTION_STATUS_ACCEPTED: SuggestionStatus = 'accepted';
412
+ export const SUGGESTION_STATUS_REJECTED: SuggestionStatus = 'rejected';
413
+
414
+ /**
415
+ * A pipeline-proposed graph mutation awaiting user review. `kind` says whether
416
+ * `payload` is a proposed node or edge; `payload` carries the proposed
417
+ * node/edge contents (label/properties for a node, endpoints/type/properties
418
+ * for an edge). Accepting it writes the node/edge with provenance `document`.
419
+ */
420
+ export interface Suggestion {
421
+ suggestionId: string;
422
+ status: SuggestionStatus;
423
+ kind: 'node' | 'edge';
424
+ payload: Record<string, unknown>;
425
+ }
426
+
427
+ /**
428
+ * The wire shape for a single source document — mirrors the backend
429
+ * `api/tools/schemas.py::DocumentResponse` (built from `SourceDocRecord` via
430
+ * `DocumentResponse.from_record`). The backend intentionally OMITS the record's
431
+ * `ownerUserId`/`s3Key`/`contentHash`, so they are absent here too. `videoId`/
432
+ * `seriesId` are optional links; `parseError`/`parseWarning` are populated when
433
+ * parsing fails or partially succeeds. `suggestions` is always present (the
434
+ * detail endpoint populates it; list endpoints return an empty array).
435
+ */
436
+ export interface DocumentRecord {
437
+ docId: string;
438
+ status: DocumentStatus;
439
+ videoId?: string | null;
440
+ seriesId?: string | null;
441
+ kind: DocumentKind;
442
+ title: string;
443
+ pageCount: number;
444
+ parseError?: string | null;
445
+ parseWarning?: string | null;
446
+ suggestions: Suggestion[];
447
+ createdAt?: string | null;
448
+ updatedAt?: string | null;
449
+ }
450
+
451
+ /**
452
+ * Response from `POST /api/v1/ingestion/documents` (multipart upload). Mirrors
453
+ * the backend `DocumentUploadResponse` — 202 for a freshly-staged document, 200
454
+ * when an identical upload by the same owner dedupes to an existing `document`.
455
+ */
456
+ export interface UploadDocumentResponse {
457
+ traceId: string;
458
+ document: DocumentRecord;
459
+ }
460
+
461
+ /** Optional metadata attached to a document upload. */
462
+ export interface UploadDocumentMeta {
463
+ videoId?: string;
464
+ seriesId?: string;
465
+ episodeNumber?: number;
466
+ kind: DocumentKind;
467
+ title: string;
468
+ }
469
+
470
+ export interface ListDocumentsResponse {
471
+ traceId: string;
472
+ results: DocumentRecord[];
473
+ nextToken?: string | null;
474
+ }
475
+
476
+ /**
477
+ * `GET /api/v1/ingestion/documents/{docId}` — mirrors the backend
478
+ * `DocumentDetailResponse`. There is NO top-level `suggestions` field: the
479
+ * suggestion list is nested inside `document.suggestions` (the detail endpoint
480
+ * calls `DocumentResponse.from_record(..., include_suggestions=True)`).
481
+ */
482
+ export interface GetDocumentResponse {
483
+ traceId: string;
484
+ document: DocumentRecord;
485
+ }
486
+
487
+ /**
488
+ * 201 response from accepting a suggestion — mirrors the backend
489
+ * `AcceptSuggestionResponse`. `graphId` is the composite id of the created
490
+ * graph node or edge (the backend returns one field regardless of `kind`).
491
+ */
492
+ export interface AcceptSuggestionResponse {
493
+ traceId: string;
494
+ suggestionId: string;
495
+ graphId: string;
496
+ }
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
+
164
517
  export interface ChatMessage {
165
518
  role: 'user' | 'assistant';
166
519
  content: string;
@@ -174,6 +527,231 @@ export interface ChatStreamRequest {
174
527
  modelId?: string;
175
528
  }
176
529
 
530
+ /**
531
+ * Route the Platform Assistant (R4) is summoned on, so the server-side
532
+ * assistant can scope its `propose_form_fields` suggestions to the
533
+ * current surface + form. Mirrors `api/assistant/schemas.py:RouteContext`.
534
+ */
535
+ export interface AssistantRouteContext {
536
+ /** The UI surface, e.g. `'studio/cast'` or `'settings/defaults'`. */
537
+ surface: string;
538
+ /** The form the user is editing, e.g. `'persona'` (optional). */
539
+ formId?: string;
540
+ /** The entity/story the form is bound to, if any (optional). */
541
+ entityId?: string;
542
+ }
543
+
544
+ /**
545
+ * Request body for `POST /api/v1/assistant/stream` — the R4 Platform
546
+ * Assistant SSE copilot. Mirrors {@link ChatStreamRequest} but:
547
+ * - DROPS `videoId` — the assistant is out-of-world (not video-scoped);
548
+ * it answers tooling questions + proposes form-field values.
549
+ * - ADDS `routeContext` so the assistant knows which surface/form the
550
+ * user is on.
551
+ *
552
+ * There is intentionally NO `systemPrompt` override (unlike chat): the
553
+ * assistant has no prompt-injection escape hatch (see the R4a spec
554
+ * "Prompt-injection surface" risk). Model resolution flows server-side
555
+ * through the SAME `resolve_model_id` → `shared/model_router.py` seam the
556
+ * chat endpoint uses — `modelId` is an optional explicit pin only.
557
+ *
558
+ * `documentContext` (R11.2) is a SEPARATE, larger-capped field for an
559
+ * "operate on this document" draft (e.g. a long prompt the user wants
560
+ * refined). It is DISTINCT from the deliberately-small `prompt`
561
+ * user-message field: the server places it in MODEL CONTEXT (the system
562
+ * prompt), never the user turn, so the small `prompt` cap keeps its
563
+ * prompt-injection floor while a full-length draft still round-trips.
564
+ */
565
+ export interface AssistantStreamRequest {
566
+ prompt: string;
567
+ messages?: ChatMessage[];
568
+ modelId?: string;
569
+ routeContext?: AssistantRouteContext;
570
+ /**
571
+ * Optional large document/draft for the assistant to operate ON (R11.2).
572
+ * Placed in model context server-side, NOT the user turn. Capped at the
573
+ * admin prompt editor's max so a full-length "Improve with assistant"
574
+ * draft round-trips (the small 2 KB `prompt` cap stays for injection
575
+ * mitigation).
576
+ */
577
+ documentContext?: string;
578
+ }
579
+
580
+ /**
581
+ * Discriminated union of the SSE events the chat / assistant stream
582
+ * endpoints emit (decoded from each `data: {…}` line). Mirrors the
583
+ * transport-agnostic `ChatEventType` values in
584
+ * `shared/chat_dispatcher.py` that survive onto the SSE wire.
585
+ *
586
+ * The R4 Platform Assistant ADDS the `'suggestion'` variant ALONGSIDE the
587
+ * existing token / tool_use / tool_result / citation / error / done variants —
588
+ * it never replaces one. The assistant's `propose_form_fields` tool result is
589
+ * converted by the dispatcher into a `suggestion` event the host UI maps
590
+ * onto its own form fields (it mutates nothing server-side). Consumers
591
+ * `switch` on `type` to narrow.
592
+ */
593
+ export type AssistantStreamEvent =
594
+ | { type: 'token'; timestamp?: number; content: string }
595
+ | { type: 'tool_use'; timestamp?: number; tool: string; toolUseId: string }
596
+ | {
597
+ /**
598
+ * The structured `tool_result` frame the dispatcher emits after EVERY
599
+ * assistant tool call (parity with the chat executor path): for
600
+ * `propose_form_fields` it follows the `suggestion` event; for the
601
+ * reference tools (`describe_tool` / `list_platform_capabilities`) it is
602
+ * the only structured result. Wire contract shared with `api/assistant`
603
+ * (the Python dispatcher emits this exact `{tool, toolUseId, result}`
604
+ * shape) — included here so an exhaustive `switch` handles it.
605
+ */
606
+ type: 'tool_result';
607
+ timestamp?: number;
608
+ tool: string;
609
+ toolUseId: string;
610
+ result: Record<string, unknown>;
611
+ }
612
+ | { type: 'citation'; timestamp?: number; citation: Citation; span?: string }
613
+ | { type: 'error'; timestamp?: number; message: string }
614
+ | { type: 'done'; timestamp?: number; reason?: string }
615
+ | {
616
+ /**
617
+ * A `propose_form_fields` tool call surfaced as a structured
618
+ * suggestion the host page reviews + applies. Carries the target
619
+ * form id, the proposed `{fieldName: value}` map, and an optional
620
+ * rationale. Wire contract shared with `api/assistant` (the Python
621
+ * dispatcher emits this exact shape).
622
+ */
623
+ type: 'suggestion';
624
+ timestamp?: number;
625
+ targetForm: string;
626
+ fields: Record<string, string>;
627
+ rationale?: string;
628
+ };
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
+
663
+ /**
664
+ * One field of a creator/admin form, as returned by the R4b form-schema
665
+ * reference endpoint (`GET /api/v1/schema/{form}`). The backend DERIVES each
666
+ * field from the form's PUBLIC Pydantic request model via `model_json_schema()`
667
+ * (single source of truth — it can never drift from the real endpoint contract).
668
+ * The assistant consults this so `propose_form_fields` only proposes VALID
669
+ * field names. Mirrors `api/assistant/schemas.py:FormField`.
670
+ */
671
+ export interface FormSchemaField {
672
+ /** The wire field name (e.g. `name`, `systemPrompt`, `voiceId`). */
673
+ name: string;
674
+ /** JSON-schema type token (`string` / `integer` / `boolean` / `object` / …). */
675
+ type: string;
676
+ /** Whether the source model marks this field required. */
677
+ required: boolean;
678
+ /**
679
+ * Human-readable field description (from the Pydantic `Field(description=…)`).
680
+ * `null` when the source field declares no description (backend `str | None`).
681
+ */
682
+ description: string | null;
683
+ /**
684
+ * Optional JSON-schema constraints carried through from the source model
685
+ * (e.g. `{ maxLength, minLength, enum }`). Absent when the field has none.
686
+ */
687
+ constraints?: Record<string, unknown>;
688
+ /** Optional example values for the field, when the source model supplies them. */
689
+ examples?: unknown[];
690
+ }
691
+
692
+ /**
693
+ * Response of `GET /api/v1/schema/{form}` (R4b) — the queryable, drift-proof
694
+ * description of a named creator/admin form's fields. `form` is the requested
695
+ * form id (`personas` / `documents` / `adventures` / `images` / `scenes` — an
696
+ * explicit allow-list; `scenes` returns the editable Scene fields {title,
697
+ * summary} since R11.3 added the public `UpdateSceneRequest` model; NEVER an
698
+ * extraction-prompt form, per the graph-corruption carve-out, tech-debt #336).
699
+ * Mirrors `api/assistant/schemas.py:FormSchemaResponse`.
700
+ */
701
+ export interface FormSchemaResponse {
702
+ /** The form id this schema describes. */
703
+ form: string;
704
+ /** The form's fields, derived from its public Pydantic request model. */
705
+ fields: FormSchemaField[];
706
+ /** Trace id for log correlation. */
707
+ traceId: string;
708
+ }
709
+
710
+ /**
711
+ * One tool's human-readable reference, as returned by the R4b tool-reference
712
+ * endpoints. DERIVED from the full `shared/tool_schemas` registry
713
+ * (`iter_all_tool_schemas` — chat + adventure + assistant; the same source the
714
+ * executor resolves from — the catalogue and the runtime tool surface cannot
715
+ * diverge). `params` is the per-parameter descriptor map keyed by parameter
716
+ * name. Mirrors `api/assistant/schemas.py:ToolReference`.
717
+ */
718
+ export interface ToolReference {
719
+ /** The tool name (e.g. `propose_form_fields`, `semantic_search`). */
720
+ name: string;
721
+ /** Human-readable description of what the tool does. */
722
+ description: string;
723
+ /** Per-parameter descriptors keyed by parameter name. */
724
+ params: Record<string, unknown>;
725
+ }
726
+
727
+ /**
728
+ * Response of `GET /api/v1/tools/reference` (R4b) — every executor-resolvable
729
+ * tool, derived from the full `shared/tool_schemas` registry
730
+ * (`iter_all_tool_schemas` — chat + adventure + assistant) so the catalogue
731
+ * cannot drift from the live tool list. Mirrors
732
+ * `api/assistant/schemas.py:ToolReferenceListResponse`.
733
+ */
734
+ export interface ToolReferenceListResponse {
735
+ /** Every platform tool's reference. */
736
+ tools: ToolReference[];
737
+ /** Trace id for log correlation. */
738
+ traceId: string;
739
+ }
740
+
741
+ /**
742
+ * Response of `GET /api/v1/tools/reference/{name}` (R4b) — one tool's reference
743
+ * NESTED under `tool` (matching the backend `ToolReferenceDetailResponse`, which
744
+ * keeps `traceId` at the top level alongside the `tool` object, mirroring the
745
+ * `{ tools, traceId }` list shape). 404 when the tool is unknown. Mirrors
746
+ * `api/assistant/schemas.py:ToolReferenceDetailResponse`.
747
+ */
748
+ export interface ToolReferenceResponse {
749
+ /** The requested tool's reference. */
750
+ tool: ToolReference;
751
+ /** Trace id for log correlation. */
752
+ traceId: string;
753
+ }
754
+
177
755
  /**
178
756
  * Capability flags advertised by a chat model. Mirrors
179
757
  * ``shared/model_config.py:CAPABILITY_*`` so frontends can decide which
@@ -203,6 +781,28 @@ export interface ChatModelsResponse {
203
781
  defaultModelId?: string | null;
204
782
  }
205
783
 
784
+ /**
785
+ * Single entry returned by `GET /api/v1/images/models` (R1c).
786
+ *
787
+ * Mirrors `ChatModelInfo` for the read-only image-model catalogue. `capabilities`
788
+ * is the raw wire type (`string[]`) — NOT the adapter `Capability[]` union — so
789
+ * api.ts has no import cycle with `adapters/capabilities.ts`. The image adapter
790
+ * (`adapters/imageAdapter.ts`) casts it to `Capability[]` when building a
791
+ * descriptor.
792
+ */
793
+ export interface ImageModelInfo {
794
+ id: string;
795
+ displayName: string;
796
+ provider: string;
797
+ capabilities: string[];
798
+ isDefault: boolean;
799
+ isFallback: boolean;
800
+ }
801
+
802
+ export interface ImageModelsResponse {
803
+ models: ImageModelInfo[];
804
+ }
805
+
206
806
  /**
207
807
  * Default system prompt components returned by `GET /api/v1/chat/system-prompt`.
208
808
  *
@@ -220,6 +820,19 @@ export interface SystemPromptComponents {
220
820
 
221
821
  // Persona types matching backend shared/persona_models.py
222
822
 
823
+ /**
824
+ * Story Engine Phase 5 — outcome of syncing a persona's character binding
825
+ * to the knowledge graph (the (Persona)-[:PORTRAYS]->(Entity) edge).
826
+ * Mirrors backend ``shared/models.py:GraphSyncStatus``. Derived per-request
827
+ * by the persona router after the graph write; never persisted to DynamoDB.
828
+ *
829
+ * - ``'synced'`` — ``entity_id`` is set and the graph write succeeded.
830
+ * - ``'pending'`` — ``entity_id`` is set but the graph write failed (logged;
831
+ * reconciliation is tracked as tech-debt).
832
+ * - ``'none'`` — ``entity_id`` is null (no binding).
833
+ */
834
+ export type GraphSyncStatus = 'synced' | 'pending' | 'none';
835
+
223
836
  export interface PersonaConfig {
224
837
  persona_id: string;
225
838
  user_id: string;
@@ -271,6 +884,48 @@ export interface PersonaConfig {
271
884
  * does not currently enforce this server-side (see specs/technical-debt.md
272
885
  * Issue #161). */
273
886
  vision_fps?: number;
887
+ /** Story Engine Phase 5: bound character Entity ID. When set, the backend
888
+ * auto-manages a (Persona)-[:PORTRAYS]->(Entity) graph edge. Accepted on
889
+ * create/update; snake_case on the wire (matches sibling fields). Always
890
+ * present on persona responses — serialized as ``null`` when no binding.
891
+ * Typed optional only as a defensive superset for older cached payloads. */
892
+ entity_id?: string | null;
893
+ /** Story Engine Phase 5: outcome of the most recent PORTRAYS sync. Derived
894
+ * per-request by the persona router; not persisted to DynamoDB. The backend
895
+ * field is required + defaulted to ``'none'``, so it is ALWAYS present on
896
+ * every persona response (``'none'`` when there is no binding) — never
897
+ * absent. Typed optional only as a defensive superset for older cached
898
+ * payloads; treat a missing value as ``'none'``. */
899
+ graph_sync_status?: GraphSyncStatus;
900
+ /** Story Engine Phase 8a (M9 Adventure Runtime): when true this persona may
901
+ * drive an interactive adventure as the Dungeon Master (it is accepted as the
902
+ * ``dmPersonaId`` for ``POST /api/v1/adventures``). Accepted on create/update;
903
+ * snake_case on the wire (matches sibling fields). The backend field is
904
+ * required + defaults to ``false``, so it is ALWAYS present on persona
905
+ * responses — typed optional only as a defensive superset for older cached
906
+ * payloads; treat a missing value as ``false``. */
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[];
274
929
  }
275
930
 
276
931
  // Viseme bundle types — see services/persona/ and shared/viseme_bundle_models.py
@@ -435,6 +1090,13 @@ export interface RegenerateImageRequest {
435
1090
 
436
1091
  export interface RegenerateImageResponse {
437
1092
  traceId: string;
1093
+ /** Tracked `image_id` of the new `ImageRecord` the regeneration wrote.
1094
+ * `null`/absent when the S3 upload succeeded but the metadata write
1095
+ * didn't (best-effort tracking) — the caller still has
1096
+ * `imageUrl`/`imageS3Key` in that case. When present, the caller can
1097
+ * `getImage(imageId)` the new row to auto-select it (closes
1098
+ * tech-debt #110). */
1099
+ imageId?: string | null;
438
1100
  /** Presigned S3 URL for immediate display only. The URL has a short
439
1101
  * TTL (typically 1h) and will 403 once expired — persist `imageS3Key`
440
1102
  * if you need a stable handle and re-presign on read. */
@@ -525,6 +1187,24 @@ export interface CreatePersonaRequest {
525
1187
  vision_enabled?: boolean;
526
1188
  /** Phase 2: requested vision frame cadence in fps (0.5–3.0). */
527
1189
  vision_fps?: number;
1190
+ /** Story Engine Phase 5: bind this persona to a character Entity. The
1191
+ * backend creates a (Persona)-[:PORTRAYS]->(Entity) edge and returns
1192
+ * ``graph_sync_status`` on the response. */
1193
+ entity_id?: string | null;
1194
+ /** Story Engine Phase 8a (M9): mark this persona as a Dungeon Master so it
1195
+ * can drive interactive adventures. Optional; defaults to ``false``
1196
+ * server-side. snake_case on the wire (matches sibling fields). */
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[];
528
1208
  }
529
1209
 
530
1210
  export interface UpdatePersonaRequest {
@@ -557,6 +1237,23 @@ export interface UpdatePersonaRequest {
557
1237
  vision_enabled?: boolean | null;
558
1238
  /** Phase 2: vision frame cadence in fps (0.5–3.0). */
559
1239
  vision_fps?: number | null;
1240
+ /** Story Engine Phase 5: change the persona↔character binding. Set to a
1241
+ * character Entity ID to (re)bind, or ``null`` to clear it. The backend
1242
+ * reconciles the (Persona)-[:PORTRAYS]->(Entity) edge and returns
1243
+ * ``graph_sync_status`` on the response. */
1244
+ entity_id?: string | null;
1245
+ /** Story Engine Phase 8a (M9): toggle Dungeon-Master capability. Optional;
1246
+ * ``null``/``undefined`` skips the field (no change). snake_case on the wire
1247
+ * (matches sibling fields). */
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;
560
1257
  }
561
1258
 
562
1259
  export interface PersonaListResponse {
@@ -565,6 +1262,288 @@ export interface PersonaListResponse {
565
1262
  next_token?: string | null;
566
1263
  }
567
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
+
1442
+ /**
1443
+ * Story Engine Phase 5 — a single character Entity for a video, as returned
1444
+ * by ``GET /api/v1/tools/videos/{videoId}/characters``. Mirrors the backend
1445
+ * ``api/tools/schemas.py:CharacterItem`` (camelCase wire fields). ``type`` is
1446
+ * always ``'character'`` because the endpoint surfaces only character Entities.
1447
+ */
1448
+ export interface CharacterItem {
1449
+ entityId: string;
1450
+ name: string;
1451
+ type: 'character';
1452
+ aliases: string[];
1453
+ }
1454
+
1455
+ /**
1456
+ * Story Engine Phase 5 — response of
1457
+ * ``GET /api/v1/tools/videos/{videoId}/characters``. Lists only ``Entity``
1458
+ * nodes with ``type === 'character'`` for the given video. Mirrors the
1459
+ * backend ``api/tools/schemas.py:CharacterListResponse``.
1460
+ */
1461
+ export interface CharacterListResponse {
1462
+ traceId: string;
1463
+ videoId: string;
1464
+ characters: CharacterItem[];
1465
+ }
1466
+
1467
+ /**
1468
+ * Platform Restructure R5a — one CharacterArc attached to a cast character.
1469
+ * Mirrors the backend ``api/tools/schemas.py:CastArc``.
1470
+ */
1471
+ export interface CastArc {
1472
+ arcId: string;
1473
+ /** Display title — the server falls back to the arc label, then arcId. */
1474
+ title: string;
1475
+ summary: string | null;
1476
+ index: number;
1477
+ }
1478
+
1479
+ /**
1480
+ * Platform Restructure R5c — one Scene featuring a cast character, with the
1481
+ * display ``title`` riding alongside the id (the studio character drawer
1482
+ * renders titles; pre-R5c they came from a client-side lookup over the full
1483
+ * graph payload). Mirrors the backend ``api/tools/schemas.py:CastScene``.
1484
+ */
1485
+ export interface CastScene {
1486
+ sceneId: string;
1487
+ /** Display title — the server falls back to the sceneId when untitled. */
1488
+ title: string;
1489
+ }
1490
+
1491
+ /**
1492
+ * Platform Restructure R5a/R5c — a character Entity as projected for the
1493
+ * studio Cast view. Carries everything the character drawer renders
1494
+ * (aliases/scenes/arcs/relatedCharacterIds), so the R5c CastGrid rewire is a
1495
+ * drop-in. Mirrors the backend ``api/tools/schemas.py:CastCharacter``. R5c
1496
+ * (the first consumer, shipped before this type was ever published) reshaped
1497
+ * R5a's ``sceneIds: string[]`` into ``scenes: CastScene[]``.
1498
+ */
1499
+ export interface CastCharacter {
1500
+ entityId: string;
1501
+ name: string;
1502
+ aliases: string[];
1503
+ scenes: CastScene[];
1504
+ arcs: CastArc[];
1505
+ /** RELATES_TO character neighbours, filtered to ids within this cast. */
1506
+ relatedCharacterIds: string[];
1507
+ }
1508
+
1509
+ /**
1510
+ * Platform Restructure R5a — display fields of the persona bound to a cast
1511
+ * character, hydrated server-side from the persona store (the binding is
1512
+ * resolved via the graph PORTRAYS edge + the authoritative
1513
+ * ``PersonaConfig.entity_id``, NOT by client-side string equality). camelCase
1514
+ * wire fields per the tools-API convention. Mirrors the backend
1515
+ * ``api/tools/schemas.py:CastPersonaSummary``.
1516
+ */
1517
+ export interface CastPersonaSummary {
1518
+ personaId: string;
1519
+ name: string;
1520
+ chatModelId: string;
1521
+ characterImageId: string | null;
1522
+ isDungeonMaster: boolean;
1523
+ }
1524
+
1525
+ /**
1526
+ * Platform Restructure R5a — one cast row: a character pre-joined to its
1527
+ * bound persona (``null`` when unbound). Mirrors the backend
1528
+ * ``api/tools/schemas.py:CastEntry``.
1529
+ */
1530
+ export interface CastEntry {
1531
+ character: CastCharacter;
1532
+ persona: CastPersonaSummary | null;
1533
+ }
1534
+
1535
+ /**
1536
+ * Platform Restructure R5a — response of
1537
+ * ``GET /api/v1/tools/videos/{videoId}/cast``: the one-call server-side
1538
+ * replacement for the studio CastGrid's two-call client-side ``entity_id``
1539
+ * join. Mirrors the backend ``api/tools/schemas.py:CastWithPersonaResponse``.
1540
+ */
1541
+ export interface CastWithPersonaResponse {
1542
+ traceId: string;
1543
+ videoId: string;
1544
+ cast: CastEntry[];
1545
+ }
1546
+
568
1547
  // Synthesis types matching backend api/personas/synthesize.py
569
1548
  export interface SynthesizedPersona {
570
1549
  name: string;
@@ -786,11 +1765,116 @@ export interface VideoGraphResponse {
786
1765
  edges: GraphEdge[];
787
1766
  }
788
1767
 
789
- export interface UpdateNodeRequest {
790
- nodeLabel: string;
791
- idProperty: string;
792
- idValue: string;
793
- properties: Record<string, unknown>;
1768
+ /**
1769
+ * Detail level for the video-graph read (Platform Restructure R5b). Mirrors
1770
+ * `shared/graph_schema.py`'s `GraphDetail` — the single source of the
1771
+ * `story`/`raw` mode literals (constants over bare strings; consumers compare
1772
+ * against `GRAPH_DETAIL.*`, never a raw literal).
1773
+ *
1774
+ * - `RAW` (the server default — omitting the `detail` arg keeps the request
1775
+ * byte-identical to the pre-R5b call): the full extraction subgraph.
1776
+ * - `STORY`: the curated story view — Acts, Scenes (each Scene node's
1777
+ * `properties` carries a read-time `shotCount`), the character cast,
1778
+ * document contributions, and narrative edges; Shot/DialogLine/Event nodes
1779
+ * and MENTIONS edges are collapsed server-side.
1780
+ */
1781
+ export const GRAPH_DETAIL = {
1782
+ STORY: 'story',
1783
+ RAW: 'raw',
1784
+ } as const;
1785
+
1786
+ export type GraphDetail = (typeof GRAPH_DETAIL)[keyof typeof GRAPH_DETAIL];
1787
+
1788
+ // ============= Creator Studio / Story types (M7 Phase 7 / Story Engine) =============
1789
+
1790
+ /**
1791
+ * Per-story aggregate counts surfaced on the Creator Studio overview. Derived
1792
+ * server-side from the existing graph + document readers (no new graph
1793
+ * machinery): acts/scenes/characters come from `GET /api/v1/tools/graph`
1794
+ * node labels (characters = `Entity` with `type === 'character'`), documents
1795
+ * from the P4 document store.
1796
+ */
1797
+ export interface StoryCounts {
1798
+ acts: number;
1799
+ scenes: number;
1800
+ characters: number;
1801
+ documents: number;
1802
+ }
1803
+
1804
+ /**
1805
+ * Summary item returned by `GET /api/v1/stories`. The Story resource is a
1806
+ * thin, read-only view over the existing Video — `storyId === videoId` (1:1)
1807
+ * in M7 P7. Both fields are present and equal so consumers can read whichever
1808
+ * they prefer; a future real-ULID Story milestone can diverge them without a
1809
+ * breaking shape change.
1810
+ */
1811
+ export interface StorySummary {
1812
+ storyId: string;
1813
+ videoId: string;
1814
+ title: string;
1815
+ updatedAt: string; // ISO 8601
1816
+ /** Always `null` in P7 (no poster source); reserved for future population. */
1817
+ posterUrl?: string | null;
1818
+ }
1819
+
1820
+ /** Detail returned by `GET /api/v1/stories/{storyId}` — summary fields + counts. */
1821
+ export interface StoryDetail {
1822
+ storyId: string;
1823
+ videoId: string;
1824
+ title: string;
1825
+ updatedAt: string; // ISO 8601
1826
+ posterUrl?: string | null;
1827
+ counts: StoryCounts;
1828
+ }
1829
+
1830
+ export interface ListStoriesResponse {
1831
+ traceId: string;
1832
+ stories: StorySummary[];
1833
+ }
1834
+
1835
+ export interface GetStoryResponse {
1836
+ traceId: string;
1837
+ story: StoryDetail;
1838
+ }
1839
+
1840
+ // ============= clip-lookup (existing tools endpoint; client binding) =========
1841
+
1842
+ /**
1843
+ * Request params for {@link ApiClient.clipLookup}. Mirrors the backend
1844
+ * `ClipLookupRequest` (`shared/tool_request_models.py`). `BaseSchema` has NO
1845
+ * alias generator and the model declares `videoId` literally (camelCase,
1846
+ * `# noqa: N815`), so the wire keys are camelCase verbatim — the client does
1847
+ * not remap.
1848
+ */
1849
+ export interface ClipLookupParams {
1850
+ videoId: string;
1851
+ /** Clip start time in seconds (>= 0). */
1852
+ t0: number;
1853
+ /** Clip end time in seconds (> 0). */
1854
+ t1: number;
1855
+ }
1856
+
1857
+ /**
1858
+ * Response from `POST /api/v1/tools/clip-lookup`. Mirrors the backend
1859
+ * `ClipLookupResponse` (`api/tools/schemas.py`) — camelCase keys verbatim.
1860
+ * `url` is a presigned (or local-stub) playable URL for the [t0,t1] span;
1861
+ * `citation` carries the time-coded span.
1862
+ */
1863
+ export interface ClipLookupResponse {
1864
+ traceId: string;
1865
+ url: string;
1866
+ expiresIn: number;
1867
+ citation: { videoId: string; t0: number; t1: number; shotId?: string | null };
1868
+ source: { system: string; details?: Record<string, unknown> | null };
1869
+ }
1870
+
1871
+ export interface UpdateNodeRequest {
1872
+ nodeLabel: string;
1873
+ // NOTE: no `idProperty` — the backend derives the primary key from
1874
+ // `shared/graph_schema.py:PRIMARY_KEY[nodeLabel]` (M7 P1a, closes tech-debt
1875
+ // #44). Callers pass only the label + id value.
1876
+ idValue: string;
1877
+ properties: Record<string, unknown>;
794
1878
  }
795
1879
 
796
1880
  export interface UpdateNodeResponse {
@@ -800,7 +1884,8 @@ export interface UpdateNodeResponse {
800
1884
 
801
1885
  export interface DeleteNodeRequest {
802
1886
  nodeLabel: string;
803
- idProperty: string;
1887
+ // NOTE: no `idProperty` (backend derives the PK). DELETE node is sent as
1888
+ // query params, not a JSON body (M7 P1a, closes tech-debt #42/#44).
804
1889
  idValue: string;
805
1890
  }
806
1891
 
@@ -832,6 +1917,86 @@ export interface DeleteRelationshipResponse {
832
1917
  deleted: number;
833
1918
  }
834
1919
 
1920
+ /**
1921
+ * Per-label schema entry returned by `GET /api/v1/tools/graph/schema`.
1922
+ * `pk` is the primary-key property name; `editable` is the user-editable
1923
+ * property whitelist. Both are derived server-side from the canonical
1924
+ * `shared/graph_schema.py` single source of truth.
1925
+ */
1926
+ export interface GraphLabelSchema {
1927
+ pk: string;
1928
+ editable: string[];
1929
+ }
1930
+
1931
+ /** Per-relationship-type schema entry: the editable property whitelist. */
1932
+ export interface GraphEdgeSchema {
1933
+ editable: string[];
1934
+ }
1935
+
1936
+ /**
1937
+ * Response from `GET /api/v1/tools/graph/schema` (M7 P1a). The live wire copy
1938
+ * of the graph whitelists — lets the web/ `PropertyPanel` drop its
1939
+ * hand-maintained mirror (tech-debt #45) and consume the same vocabulary the
1940
+ * backend validates against. No auth required (pure metadata).
1941
+ */
1942
+ export interface GraphSchemaResponse {
1943
+ traceId: string;
1944
+ labels: Record<string, GraphLabelSchema>;
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;
1954
+ }
1955
+
1956
+ /**
1957
+ * Body for `POST /api/v1/tools/graph/nodes` (M7 P3a). Creates a user-authored
1958
+ * narrative node (Scene / PlotBeat / CharacterArc — see {@link userCreatableLabels}
1959
+ * in `graphSchema.ts`). `videoId` IS a legitimate field here: the node does not
1960
+ * exist yet, so ownership is asserted directly from `videoId` (the documented
1961
+ * POST-carries-videoId exception to derive-ownership-from-object). The backend
1962
+ * stamps `provenance='user'`, `versionId`, and `createdAt`/`updatedAt`.
1963
+ */
1964
+ export interface CreateNodeRequest {
1965
+ videoId: string;
1966
+ label: string;
1967
+ properties: Record<string, unknown>;
1968
+ }
1969
+
1970
+ /** 201 response from `POST /api/v1/tools/graph/nodes` (composite `nodeId`). */
1971
+ export interface CreateNodeResponse {
1972
+ traceId: string;
1973
+ nodeId: string;
1974
+ properties: Record<string, unknown>;
1975
+ }
1976
+
1977
+ /**
1978
+ * Body for `POST /api/v1/tools/graph/edges` (M7 P3a). Creates a user-authored
1979
+ * relationship (one of {@link userCreatableEdges}). `sourceId`/`targetId` are
1980
+ * composite ids (`Label:pk:value`); both endpoints must belong to `videoId`.
1981
+ * `type` must be a user-creatable edge whose `(sourceLabel, targetLabel)` pair
1982
+ * is in {@link allowedPairs}; `properties` carries edge-specific fields (e.g.
1983
+ * `kind` for RELATES_TO, `confidence` for FEATURES, `condition` for LEADS_TO).
1984
+ */
1985
+ export interface CreateEdgeRequest {
1986
+ videoId: string;
1987
+ sourceId: string;
1988
+ targetId: string;
1989
+ type: string;
1990
+ properties?: Record<string, unknown>;
1991
+ }
1992
+
1993
+ /** 201 response from `POST /api/v1/tools/graph/edges` (composite `edgeId`). */
1994
+ export interface CreateEdgeResponse {
1995
+ traceId: string;
1996
+ edgeId: string;
1997
+ properties: Record<string, unknown>;
1998
+ }
1999
+
835
2000
  // ==================== Reactor / Helios types ====================
836
2001
 
837
2002
  /**
@@ -864,6 +2029,15 @@ export interface UpsampleReactorPromptRequest {
864
2029
  entityContext?: ReactorEntityContext;
865
2030
  /** Persona grounding (name + truncated backstory). */
866
2031
  personaContext?: ReactorPersonaContext;
2032
+ /**
2033
+ * Optional chat-model id to run the upsample on (R8.3). When set, it MUST be
2034
+ * one the backend chat router knows (`shared/model_config.py` — the same set
2035
+ * `GET /api/v1/chat/models` lists); an unknown id is rejected with a 422.
2036
+ * Omitted ⇒ the backend's configured default upsample model — so existing
2037
+ * callers keep their behavior (additive-only). The Director surfaces this via
2038
+ * the R1 CHAT adapter picker so the steering LLM is operator-swappable.
2039
+ */
2040
+ model?: string;
867
2041
  }
868
2042
 
869
2043
  export interface UpsampleReactorPromptResponse {
@@ -871,6 +2045,124 @@ export interface UpsampleReactorPromptResponse {
871
2045
  upsampledPrompt: string;
872
2046
  }
873
2047
 
2048
+ // ============= Adventure Runtime types (M9 Story Engine Phase 8a) =============
2049
+
2050
+ /**
2051
+ * One entry in an adventure's turn log. Mirrors
2052
+ * `shared/adventure_models.py::TurnRecord` — the backend serializes it
2053
+ * camelCase (`{turn, beatId, summary}`) inside {@link AdventureState.turnHistory}.
2054
+ * `turn` is 1-based and monotonically increasing; the backend keeps only the
2055
+ * last `TURN_HISTORY_MAX_ENTRIES` (30) records.
2056
+ */
2057
+ export interface TurnRecord {
2058
+ turn: number;
2059
+ beatId: string;
2060
+ summary: string;
2061
+ }
2062
+
2063
+ /**
2064
+ * Server-authoritative state for an in-progress interactive adventure. Mirrors
2065
+ * `shared/adventure_models.py::AdventureState` (a camelCase-on-the-wire pydantic
2066
+ * model). Returned by `POST /api/v1/adventures` and `GET
2067
+ * /api/v1/adventures/{sessionId}`. The Dungeon-Master persona mutates this via
2068
+ * the `/api/v1/tools/adventure/*` endpoints; the runtime threads `sessionId`
2069
+ * into chat turns so the DM tools resolve the active adventure.
2070
+ */
2071
+ export interface AdventureState {
2072
+ sessionId: string;
2073
+ ownerUserId: string;
2074
+ storyId: string;
2075
+ videoId: string;
2076
+ dmPersonaId: string;
2077
+ partyPersonaIds: string[];
2078
+ /** Current PlotBeat id. `null` before the first `advance_story` move. */
2079
+ currentBeatId?: string | null;
2080
+ visitedBeatIds: string[];
2081
+ flags: Record<string, string>;
2082
+ inventory: string[];
2083
+ turnHistory: TurnRecord[];
2084
+ createdAt: string;
2085
+ updatedAt: string;
2086
+ }
2087
+
2088
+ /**
2089
+ * Request body for `POST /api/v1/adventures` (start an adventure). Mirrors the
2090
+ * backend `api/adventures/schemas.py::StartAdventureRequest` (`extra="forbid"`,
2091
+ * camelCase keys verbatim). `dmPersonaId` MUST reference a persona whose
2092
+ * `is_dungeon_master` is true (the backend 422s otherwise). `initialBeatId`
2093
+ * optionally seeds the starting PlotBeat; omit to start before any beat.
2094
+ */
2095
+ export interface StartAdventureRequest {
2096
+ storyId: string;
2097
+ videoId: string;
2098
+ dmPersonaId: string;
2099
+ initialBeatId?: string | null;
2100
+ /**
2101
+ * Initial party of character personas for a multi-persona adventure (M10
2102
+ * Story Engine Phase 9a). Each id must reference an owned persona that is
2103
+ * bound to a character entity and is NOT a Dungeon Master (the backend 422s
2104
+ * otherwise). Optional; omit / `[]` for an M9 single-DM adventure — the wire
2105
+ * stays unchanged (land-dark). Mirrors the additive `partyPersonaIds` field
2106
+ * on the backend `StartAdventureRequest`.
2107
+ */
2108
+ partyPersonaIds?: string[];
2109
+ }
2110
+
2111
+ /**
2112
+ * The two `action` values accepted by `PATCH /api/v1/adventures/{sessionId}/party`
2113
+ * (M10 Story Engine Phase 9a). `add` appends a character persona to the party
2114
+ * (validated + deduped server-side); `remove` is an idempotent no-op when the
2115
+ * persona is absent. Named constant so call sites never hard-code the literals.
2116
+ */
2117
+ export const PARTY_ACTION = {
2118
+ ADD: 'add',
2119
+ REMOVE: 'remove',
2120
+ } as const;
2121
+
2122
+ /** Union of the {@link PARTY_ACTION} values. */
2123
+ export type PartyAction = (typeof PARTY_ACTION)[keyof typeof PARTY_ACTION];
2124
+
2125
+ /**
2126
+ * Request body for `PATCH /api/v1/adventures/{sessionId}/party` (M10 Story
2127
+ * Engine Phase 9a). Mirrors the backend `PartyUpdateRequest` (`extra="forbid"`,
2128
+ * camelCase keys verbatim). The PATCH returns the updated
2129
+ * {@link GetAdventureResponse} (the same 200 shape as `GET adventure`).
2130
+ */
2131
+ export interface PartyUpdateRequest {
2132
+ action: PartyAction;
2133
+ personaId: string;
2134
+ }
2135
+
2136
+ /**
2137
+ * 201 response from `POST /api/v1/adventures`. Mirrors the backend
2138
+ * `AdventureResponse` — carries the new `sessionId` (also in `state.sessionId`)
2139
+ * plus the full initial {@link AdventureState}. The `Location` header points at
2140
+ * `/api/v1/adventures/{sessionId}`.
2141
+ */
2142
+ export interface AdventureResponse {
2143
+ traceId: string;
2144
+ sessionId: string;
2145
+ state: AdventureState;
2146
+ }
2147
+
2148
+ /** `GET /api/v1/adventures/{sessionId}` — mirrors the backend `GetAdventureResponse`. */
2149
+ export interface GetAdventureResponse {
2150
+ traceId: string;
2151
+ state: AdventureState;
2152
+ }
2153
+
2154
+ /**
2155
+ * `GET /api/v1/adventures` — mirrors the backend `ListAdventuresResponse`.
2156
+ * Owner-scoped list of the caller's adventures (soft-deleted ones excluded),
2157
+ * newest-first by `createdAt`, optionally narrowed to a single `storyId`. Each
2158
+ * entry is the same camelCase {@link AdventureState} returned by
2159
+ * `GET /api/v1/adventures/{sessionId}`.
2160
+ */
2161
+ export interface ListAdventuresResponse {
2162
+ traceId: string;
2163
+ adventures: AdventureState[];
2164
+ }
2165
+
874
2166
  export class ApiClient {
875
2167
  private baseURL: string;
876
2168
  private sessionToken?: string;
@@ -905,51 +2197,10 @@ export class ApiClient {
905
2197
  endpoint: string,
906
2198
  options: RequestInit = {}
907
2199
  ): Promise<T> {
908
- const url = `${baseUrl}${endpoint}`;
909
-
910
- const headers: Record<string, string> = {
911
- 'Content-Type': 'application/json',
912
- ...options.headers as Record<string, string>,
913
- };
914
-
915
- // Add authorization header if session token is available
916
- if (this.sessionToken) {
917
- headers['Authorization'] = `Bearer ${this.sessionToken}`;
918
- }
919
-
920
- try {
921
- const response = await fetch(url, {
922
- ...options,
923
- headers,
924
- });
925
-
926
- if (!response.ok) {
927
- const error: ApiError = await response.json().catch(() => ({
928
- detail: `HTTP ${response.status}: ${response.statusText}`,
929
- }));
930
- // FastAPI 422 returns detail as an array of validation errors
931
- const detail = error.detail;
932
- let message: string;
933
- if (Array.isArray(detail)) {
934
- message = detail.map((e: { msg?: string; loc?: string[] }) =>
935
- e.msg ? `${(e.loc || []).slice(-1).join('.')}: ${e.msg}` : String(e)
936
- ).join('; ');
937
- } else {
938
- message = detail || `Request failed: ${response.status}`;
939
- }
940
- throw new Error(message);
941
- }
942
-
943
- // 204 No Content returns no body
944
- if (response.status === 204) {
945
- return undefined as T;
946
- }
947
-
948
- return await response.json();
949
- } catch (error) {
950
- console.error('API request failed:', error);
951
- throw error;
952
- }
2200
+ // Delegates to the shared `requestJson` helper (bearer auth + FastAPI error
2201
+ // shaping) so `ApiClient` and the additive `AdminClient` share one fetch
2202
+ // wrapper — behavior is identical to the prior inline implementation.
2203
+ return requestJson<T>(baseUrl, endpoint, this.sessionToken, options);
953
2204
  }
954
2205
 
955
2206
  /**
@@ -995,6 +2246,33 @@ export class ApiClient {
995
2246
  return this.request<ListJobsResponse>(endpoint);
996
2247
  }
997
2248
 
2249
+ /**
2250
+ * Story Engine Phase 5 — list character entities for a video. Backs the
2251
+ * persona↔character binding selector. Returns only ``Entity`` nodes with
2252
+ * ``type === 'character'`` for the given video. Auth + video ownership are
2253
+ * enforced server-side (caller must own the video). Uses the main API base
2254
+ * (the tools routes use ``request``, not ``chatRequest``).
2255
+ */
2256
+ async listVideoCharacters(videoId: string): Promise<CharacterListResponse> {
2257
+ return this.request<CharacterListResponse>(
2258
+ `/api/v1/tools/videos/${encodeURIComponent(videoId)}/characters`,
2259
+ );
2260
+ }
2261
+
2262
+ /**
2263
+ * Platform Restructure R5a — fetch a video's character cast pre-joined to
2264
+ * each character's bound persona in ONE round-trip (the server resolves the
2265
+ * PORTRAYS binding + hydrates persona display fields). The one-call
2266
+ * replacement for the CastGrid's `getVideoGraph` + `listPersonas` client-side
2267
+ * `entity_id` join (the R5c rewire consumes this). Auth + video ownership are
2268
+ * enforced server-side. Tools API base (`request`, not `chatRequest`).
2269
+ */
2270
+ async getCast(videoId: string): Promise<CastWithPersonaResponse> {
2271
+ return this.request<CastWithPersonaResponse>(
2272
+ `/api/v1/tools/videos/${encodeURIComponent(videoId)}/cast`,
2273
+ );
2274
+ }
2275
+
998
2276
  /**
999
2277
  * List staged videos in the ingestion bucket
1000
2278
  */
@@ -1090,65 +2368,382 @@ export class ApiClient {
1090
2368
  xhr.setRequestHeader('Authorization', `Bearer ${this.sessionToken}`);
1091
2369
  }
1092
2370
 
1093
- xhr.send(formData);
1094
- });
1095
- }
2371
+ xhr.send(formData);
2372
+ });
2373
+ }
2374
+
2375
+ // ==================== Enrichment API Methods ====================
2376
+
2377
+ /**
2378
+ * Trigger Pegasus enrichment analysis on an ingested video
2379
+ */
2380
+ async enrichVideo(videoId: string, config?: PegasusConfig): Promise<EnrichVideoResponse> {
2381
+ return this.request<EnrichVideoResponse>(`/api/v1/ingestion/videos/${videoId}/enrichments`, {
2382
+ method: 'POST',
2383
+ body: JSON.stringify({
2384
+ pegasusPrompt: config?.pegasusPrompt,
2385
+ pegasusTemperature: config?.pegasusTemperature,
2386
+ pegasusMaxTokens: config?.pegasusMaxTokens,
2387
+ }),
2388
+ });
2389
+ }
2390
+
2391
+ /**
2392
+ * List all enrichment runs for a video
2393
+ */
2394
+ async getEnrichments(videoId: string): Promise<ListEnrichmentsResponse> {
2395
+ return this.request<ListEnrichmentsResponse>(`/api/v1/ingestion/videos/${videoId}/enrichments`);
2396
+ }
2397
+
2398
+ /**
2399
+ * Get a specific enrichment result
2400
+ */
2401
+ async getEnrichment(enrichmentId: string): Promise<EnrichmentRecord> {
2402
+ return this.request<EnrichmentRecord>(`/api/v1/ingestion/enrichments/${enrichmentId}`);
2403
+ }
2404
+
2405
+ /**
2406
+ * Delete a video and all associated data across all systems
2407
+ */
2408
+ async deleteVideo(videoId: string, s3Key?: string): Promise<VideoDeletionResponse> {
2409
+ const searchParams = new URLSearchParams();
2410
+ if (s3Key) searchParams.append('s3Key', s3Key);
2411
+
2412
+ const query = searchParams.toString();
2413
+ const endpoint = `/api/v1/ingestion/videos/${videoId}${query ? `?${query}` : ''}`;
2414
+
2415
+ return this.request<VideoDeletionResponse>(endpoint, {
2416
+ method: 'DELETE',
2417
+ });
2418
+ }
2419
+
2420
+ // ============= Narrative Regeneration API (M7 Phase 6 / Story Engine) =============
2421
+
2422
+ /**
2423
+ * Start an async narrative regeneration run for a video scope.
2424
+ * `POST /api/v1/tools/graph/{videoId}/regenerate` → 202 with the QUEUED run
2425
+ * (and a `Location` header to the run's poll URL, exposed as `statusUrl`).
2426
+ *
2427
+ * Auth + ownership are enforced server-side. A malformed `scope` is a 422,
2428
+ * an in-flight run is a 409, over-cap is a 429 — all surface as a thrown
2429
+ * `Error` carrying the FastAPI detail. Build `request.scope` with
2430
+ * {@link buildRegenerationScope}. Pair with {@link pollRegenerationUntilDone}.
2431
+ */
2432
+ async startRegeneration(
2433
+ videoId: string,
2434
+ request: RegenerateRequest,
2435
+ ): Promise<RegenerationRunResponse> {
2436
+ return this.request<RegenerationRunResponse>(
2437
+ `/api/v1/tools/graph/${encodeURIComponent(videoId)}/regenerate`,
2438
+ {
2439
+ method: 'POST',
2440
+ body: JSON.stringify(request),
2441
+ },
2442
+ );
2443
+ }
2444
+
2445
+ /**
2446
+ * List a video's regeneration runs, newest-first.
2447
+ * `GET /api/v1/tools/graph/{videoId}/regenerations`. `limit` (1–100) and
2448
+ * `cursor` (opaque pagination token from a prior `nextCursor`) are optional.
2449
+ */
2450
+ async listRegenerations(
2451
+ videoId: string,
2452
+ params?: { limit?: number; cursor?: string },
2453
+ ): Promise<RegenerationListResponse> {
2454
+ const searchParams = new URLSearchParams();
2455
+ if (params?.limit != null) searchParams.append('limit', params.limit.toString());
2456
+ if (params?.cursor) searchParams.append('cursor', params.cursor);
2457
+
2458
+ const query = searchParams.toString();
2459
+ const endpoint = `/api/v1/tools/graph/${encodeURIComponent(videoId)}/regenerations${
2460
+ query ? `?${query}` : ''
2461
+ }`;
2462
+ return this.request<RegenerationListResponse>(endpoint);
2463
+ }
2464
+
2465
+ /**
2466
+ * Fetch a single regeneration run by id.
2467
+ * `GET /api/v1/tools/graph/{videoId}/regenerations/{runId}` (404 if absent).
2468
+ * `signal` aborts the in-flight fetch — {@link pollRegenerationUntilDone}
2469
+ * threads its poll signal through so a page unmount cancels cleanly.
2470
+ */
2471
+ async getRegeneration(
2472
+ videoId: string,
2473
+ runId: string,
2474
+ options: { signal?: AbortSignal } = {},
2475
+ ): Promise<RegenerationRunResponse> {
2476
+ return this.request<RegenerationRunResponse>(
2477
+ `/api/v1/tools/graph/${encodeURIComponent(videoId)}/regenerations/${encodeURIComponent(
2478
+ runId,
2479
+ )}`,
2480
+ { signal: options.signal },
2481
+ );
2482
+ }
2483
+
2484
+ /**
2485
+ * Poll {@link getRegeneration} until the run reaches a terminal status.
2486
+ * COMPLETE / CANCELLED resolve with the final run; FAILED throws
2487
+ * (`record.error` ?? a generic message). Mirrors
2488
+ * {@link pollVisemeBundleUntilDone}: 5s cadence, abortable via `signal`,
2489
+ * and a wall-clock timeout (regeneration re-invokes Pegasus, so the default
2490
+ * matches bundle assembly — generous but bounded).
2491
+ */
2492
+ async pollRegenerationUntilDone(
2493
+ videoId: string,
2494
+ runId: string,
2495
+ options: {
2496
+ intervalMs?: number;
2497
+ timeoutMs?: number;
2498
+ signal?: AbortSignal;
2499
+ } = {},
2500
+ ): Promise<RegenerationRunResponse> {
2501
+ const intervalMs = options.intervalMs ?? 5000;
2502
+ // The regenerator Lambda can run up to its 15-min cap (an `acts` scope re-runs
2503
+ // Pegasus over the whole film), so the default poll deadline must exceed that or
2504
+ // the client gives up while the run is still completing. 16 min covers a normal
2505
+ // single run; if the poll still times out (e.g. an SQS redelivery), the run row
2506
+ // is durable — a refresh / re-fetch surfaces the terminal state.
2507
+ const timeoutMs = options.timeoutMs ?? 960_000;
2508
+ const deadline = Date.now() + timeoutMs;
2509
+ while (true) {
2510
+ if (options.signal?.aborted) {
2511
+ throw new DOMException('Polling aborted', 'AbortError');
2512
+ }
2513
+ const record = await this.getRegeneration(videoId, runId, {
2514
+ signal: options.signal,
2515
+ });
2516
+ if (
2517
+ record.status === REGENERATION_STATUS.COMPLETE ||
2518
+ record.status === REGENERATION_STATUS.CANCELLED
2519
+ ) {
2520
+ return record;
2521
+ }
2522
+ if (record.status === REGENERATION_STATUS.FAILED) {
2523
+ throw new Error(record.error ?? 'Regeneration failed');
2524
+ }
2525
+ if (Date.now() >= deadline) {
2526
+ throw new Error(
2527
+ `Regeneration timed out after ${Math.round(timeoutMs / 1000)}s`,
2528
+ );
2529
+ }
2530
+ await abortableSleep(intervalMs, options.signal);
2531
+ }
2532
+ }
2533
+
2534
+ // ==================== Source Document API (M7 Phase 4) ====================
2535
+
2536
+ /**
2537
+ * Upload a source document (script / notes / bible / transcript) with
2538
+ * progress tracking. Mirrors {@link uploadVideo}: multipart XHR so the
2539
+ * browser reports upload progress (fetch cannot). The `meta` fields ride
2540
+ * alongside the file as a JSON `payload` part. Returns 201 with
2541
+ * `{ traceId, docId, statusUrl }`; the backend enqueues
2542
+ * `document-processing-queue` to parse + extract suggestions.
2543
+ */
2544
+ async uploadDocument(
2545
+ file: File,
2546
+ meta: UploadDocumentMeta,
2547
+ onProgress?: UploadProgressCallback,
2548
+ ): Promise<UploadDocumentResponse> {
2549
+ const url = `${this.baseURL}/api/v1/ingestion/documents`;
2550
+
2551
+ return new Promise((resolve, reject) => {
2552
+ const xhr = new XMLHttpRequest();
2553
+
2554
+ // Track upload progress
2555
+ if (onProgress) {
2556
+ xhr.upload.addEventListener('progress', (e) => {
2557
+ if (e.lengthComputable) {
2558
+ onProgress({
2559
+ loaded: e.loaded,
2560
+ total: e.total,
2561
+ percentage: Math.round((e.loaded / e.total) * 100),
2562
+ });
2563
+ }
2564
+ });
2565
+ }
2566
+
2567
+ // Handle completion
2568
+ xhr.addEventListener('load', () => {
2569
+ if (xhr.status >= 200 && xhr.status < 300) {
2570
+ try {
2571
+ const response = JSON.parse(xhr.responseText);
2572
+ resolve(response);
2573
+ } catch {
2574
+ reject(new Error('Failed to parse upload response'));
2575
+ }
2576
+ } else {
2577
+ try {
2578
+ const errorData = JSON.parse(xhr.responseText);
2579
+ reject(new Error(errorData.detail || `Upload failed: ${xhr.status}`));
2580
+ } catch {
2581
+ reject(new Error(`Upload failed: ${xhr.status} ${xhr.statusText}`));
2582
+ }
2583
+ }
2584
+ });
2585
+
2586
+ // Handle errors
2587
+ xhr.addEventListener('error', () => {
2588
+ reject(new Error('Upload failed due to network error'));
2589
+ });
2590
+
2591
+ xhr.addEventListener('abort', () => {
2592
+ reject(new Error('Upload aborted'));
2593
+ });
2594
+
2595
+ // Prepare form data — file part + JSON metadata part.
2596
+ const formData = new FormData();
2597
+ formData.append('upload', file);
2598
+ formData.append('payload', JSON.stringify(meta));
2599
+
2600
+ // Send request
2601
+ xhr.open('POST', url);
2602
+
2603
+ // Add authorization header if session token is available
2604
+ if (this.sessionToken) {
2605
+ xhr.setRequestHeader('Authorization', `Bearer ${this.sessionToken}`);
2606
+ }
2607
+
2608
+ xhr.send(formData);
2609
+ });
2610
+ }
2611
+
2612
+ /**
2613
+ * List source documents, optionally scoped to a video or series. Mirrors
2614
+ * {@link listJobs} query-param handling. GET `/api/v1/ingestion/documents`.
2615
+ */
2616
+ async listDocuments(params?: {
2617
+ videoId?: string;
2618
+ seriesId?: string;
2619
+ limit?: number;
2620
+ nextToken?: string;
2621
+ }): Promise<ListDocumentsResponse> {
2622
+ const searchParams = new URLSearchParams();
2623
+ if (params?.videoId) searchParams.append('videoId', params.videoId);
2624
+ if (params?.seriesId) searchParams.append('seriesId', params.seriesId);
2625
+ if (params?.limit) searchParams.append('limit', params.limit.toString());
2626
+ if (params?.nextToken) searchParams.append('nextToken', params.nextToken);
2627
+
2628
+ const query = searchParams.toString();
2629
+ const endpoint = `/api/v1/ingestion/documents${query ? `?${query}` : ''}`;
1096
2630
 
1097
- // ==================== Enrichment API Methods ====================
2631
+ return this.request<ListDocumentsResponse>(endpoint);
2632
+ }
1098
2633
 
1099
2634
  /**
1100
- * Trigger Pegasus enrichment analysis on an ingested video
2635
+ * Fetch a single document plus its pending/resolved graph suggestions.
2636
+ * GET `/api/v1/ingestion/documents/{docId}`.
1101
2637
  */
1102
- async enrichVideo(videoId: string, config?: PegasusConfig): Promise<EnrichVideoResponse> {
1103
- return this.request<EnrichVideoResponse>(`/api/v1/ingestion/videos/${videoId}/enrichments`, {
1104
- method: 'POST',
1105
- body: JSON.stringify({
1106
- pegasusPrompt: config?.pegasusPrompt,
1107
- pegasusTemperature: config?.pegasusTemperature,
1108
- pegasusMaxTokens: config?.pegasusMaxTokens,
1109
- }),
1110
- });
2638
+ async getDocument(docId: string): Promise<GetDocumentResponse> {
2639
+ return this.request<GetDocumentResponse>(`/api/v1/ingestion/documents/${docId}`);
1111
2640
  }
1112
2641
 
1113
2642
  /**
1114
- * List all enrichment runs for a video
2643
+ * Accept a pipeline-extracted graph suggestion — writes the proposed
2644
+ * node/edge with provenance `document`. POST returns 201 with
2645
+ * `{ traceId, suggestionId, graphId }` (`graphId` is the composite id of the
2646
+ * created node/edge); a 422 (e.g. already resolved, or the payload fails
2647
+ * graph validation) surfaces the FastAPI detail as a thrown `Error`. POST
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.
1115
2654
  */
1116
- async getEnrichments(videoId: string): Promise<ListEnrichmentsResponse> {
1117
- return this.request<ListEnrichmentsResponse>(`/api/v1/ingestion/videos/${videoId}/enrichments`);
2655
+ async acceptSuggestion(
2656
+ docId: string,
2657
+ suggestionId: string,
2658
+ options?: { acceptAsNew?: boolean },
2659
+ ): Promise<AcceptSuggestionResponse> {
2660
+ const init: RequestInit = { method: 'POST' };
2661
+ if (options?.acceptAsNew) {
2662
+ init.body = JSON.stringify({ acceptAsNew: true });
2663
+ }
2664
+ return this.request<AcceptSuggestionResponse>(
2665
+ `/api/v1/ingestion/documents/${docId}/suggestions/${suggestionId}/accept`,
2666
+ init,
2667
+ );
1118
2668
  }
1119
2669
 
1120
2670
  /**
1121
- * Get a specific enrichment result
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.
1122
2675
  */
1123
- async getEnrichment(enrichmentId: string): Promise<EnrichmentRecord> {
1124
- return this.request<EnrichmentRecord>(`/api/v1/ingestion/enrichments/${enrichmentId}`);
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
+ );
1125
2685
  }
1126
2686
 
1127
2687
  /**
1128
- * Delete a video and all associated data across all systems
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`.
1129
2691
  */
1130
- async deleteVideo(videoId: string, s3Key?: string): Promise<VideoDeletionResponse> {
1131
- const searchParams = new URLSearchParams();
1132
- if (s3Key) searchParams.append('s3Key', s3Key);
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' },
2705
+ );
2706
+ }
1133
2707
 
1134
- const query = searchParams.toString();
1135
- const endpoint = `/api/v1/ingestion/videos/${videoId}${query ? `?${query}` : ''}`;
2708
+ /**
2709
+ * Reject a pipeline-extracted graph suggestion (marks it `rejected`, writes
2710
+ * nothing to the graph). Returns 204 (no body). POST
2711
+ * `.../documents/{docId}/suggestions/{sid}/reject`.
2712
+ */
2713
+ async rejectSuggestion(docId: string, suggestionId: string): Promise<void> {
2714
+ return this.request<void>(
2715
+ `/api/v1/ingestion/documents/${docId}/suggestions/${suggestionId}/reject`,
2716
+ { method: 'POST' },
2717
+ );
2718
+ }
1136
2719
 
1137
- return this.request<VideoDeletionResponse>(endpoint, {
2720
+ /**
2721
+ * Delete a source document and its associated data. Returns 204 (no body).
2722
+ * DELETE `/api/v1/ingestion/documents/{docId}`.
2723
+ */
2724
+ async deleteDocument(docId: string): Promise<void> {
2725
+ return this.request<void>(`/api/v1/ingestion/documents/${docId}`, {
1138
2726
  method: 'DELETE',
1139
2727
  });
1140
2728
  }
1141
2729
 
1142
2730
  /**
1143
- * Stream chat responses with Server-Sent Events
1144
- * Returns a ReadableStreamDefaultReader for processing SSE events
2731
+ * Shared SSE body-reader for the chat + assistant stream endpoints.
2732
+ * POSTs the JSON `body` to `url` (with the auth header when a session
2733
+ * token is set) and returns the response's `ReadableStreamDefaultReader`
2734
+ * for the caller to decode. `streamChat` and `streamAssistant` differ
2735
+ * ONLY by URL + body, so they both route through here — there is exactly
2736
+ * one fetch/reader/decoder plumbing (DRY; R4a reviewer flag).
2737
+ *
2738
+ * `errorPrefix` only shapes the fallback message when the backend
2739
+ * returns a non-2xx without a `detail` field.
1145
2740
  */
1146
- async streamChat(
1147
- request: ChatStreamRequest,
1148
- signal?: AbortSignal
2741
+ private async readSseStream(
2742
+ url: string,
2743
+ body: unknown,
2744
+ errorPrefix: string,
2745
+ signal?: AbortSignal,
1149
2746
  ): Promise<ReadableStreamDefaultReader<Uint8Array>> {
1150
- const url = `${this.chatApiBaseUrl}/api/chat/stream`;
1151
-
1152
2747
  const headers: Record<string, string> = {
1153
2748
  'Content-Type': 'application/json',
1154
2749
  };
@@ -1161,7 +2756,7 @@ export class ApiClient {
1161
2756
  const response = await fetch(url, {
1162
2757
  method: 'POST',
1163
2758
  headers,
1164
- body: JSON.stringify(request),
2759
+ body: JSON.stringify(body),
1165
2760
  signal,
1166
2761
  });
1167
2762
 
@@ -1169,7 +2764,7 @@ export class ApiClient {
1169
2764
  const error: ApiError = await response.json().catch(() => ({
1170
2765
  detail: `HTTP ${response.status}: ${response.statusText}`,
1171
2766
  }));
1172
- throw new Error(error.detail || `Chat request failed: ${response.status}`);
2767
+ throw new Error(error.detail || `${errorPrefix}: ${response.status}`);
1173
2768
  }
1174
2769
 
1175
2770
  const reader = response.body?.getReader();
@@ -1180,6 +2775,51 @@ export class ApiClient {
1180
2775
  return reader;
1181
2776
  }
1182
2777
 
2778
+ /**
2779
+ * Stream chat responses with Server-Sent Events
2780
+ * Returns a ReadableStreamDefaultReader for processing SSE events
2781
+ */
2782
+ async streamChat(
2783
+ request: ChatStreamRequest,
2784
+ signal?: AbortSignal
2785
+ ): Promise<ReadableStreamDefaultReader<Uint8Array>> {
2786
+ return this.readSseStream(
2787
+ // Deliberate URL asymmetry vs streamAssistant: chat is the LEGACY,
2788
+ // UNVERSIONED route (`/api/chat/stream`, no `/v1/`) while assistant is
2789
+ // the NEW VERSIONED route (`/api/v1/assistant/stream`). Keep both as-is —
2790
+ // a future versioning refactor should not "normalize" chat to `/v1/`
2791
+ // without coordinating the backend route, which still serves the legacy path.
2792
+ `${this.chatApiBaseUrl}/api/chat/stream`,
2793
+ request,
2794
+ 'Chat request failed',
2795
+ signal,
2796
+ );
2797
+ }
2798
+
2799
+ /**
2800
+ * Stream Platform Assistant (R4) responses with Server-Sent Events.
2801
+ * Sibling of {@link streamChat} hitting `POST /api/v1/assistant/stream`
2802
+ * — reuses the exact same SSE reader/decoder plumbing via
2803
+ * {@link readSseStream}. Decode each `data: {…}` line into an
2804
+ * {@link AssistantStreamEvent} (the stream may carry the additive
2805
+ * `suggestion` variant). The assistant is out-of-world: the request
2806
+ * carries `routeContext` instead of `videoId`.
2807
+ */
2808
+ async streamAssistant(
2809
+ request: AssistantStreamRequest,
2810
+ signal?: AbortSignal
2811
+ ): Promise<ReadableStreamDefaultReader<Uint8Array>> {
2812
+ return this.readSseStream(
2813
+ // NEW VERSIONED route (`/api/v1/assistant/stream`) — intentionally
2814
+ // differs from streamChat's legacy unversioned `/api/chat/stream`; see
2815
+ // the asymmetry note there.
2816
+ `${this.chatApiBaseUrl}/api/v1/assistant/stream`,
2817
+ request,
2818
+ 'Assistant request failed',
2819
+ signal,
2820
+ );
2821
+ }
2822
+
1183
2823
  /**
1184
2824
  * Fetch the chat-model registry from the backend. Returns Bedrock entries
1185
2825
  * plus any locally-discovered Ollama models. Public endpoint — works
@@ -1189,6 +2829,53 @@ export class ApiClient {
1189
2829
  return this.chatRequest<ChatModelsResponse>('/api/v1/chat/models');
1190
2830
  }
1191
2831
 
2832
+ // ==================== Platform Assistant reference API (R4b) ====================
2833
+ // Read-only introspection backing the assistant's `describe_tool` /
2834
+ // `list_platform_capabilities` tools + the host UI's field-name validation.
2835
+ // All three live on the CHAT base URL (the assistant/reference router is
2836
+ // mounted there, like `streamAssistant`) and reuse the same authed
2837
+ // `chatRequest`/`requestJson` JSON helper as the other chat-base GETs (DRY —
2838
+ // no forked fetch path; the Authorization header is attached iff a session
2839
+ // token is set).
2840
+
2841
+ /**
2842
+ * Fetch the drift-proof field schema for a named creator/admin form
2843
+ * (`GET /api/v1/schema/{form}`). The backend derives every field from the
2844
+ * form's PUBLIC Pydantic request model (`model_json_schema()`) so it can
2845
+ * never drift from the real endpoint contract. The host UI uses this to
2846
+ * validate which `propose_form_fields` suggestions are applicable; the
2847
+ * assistant uses it to propose VALID field names. `form` is one of the
2848
+ * registered ids (`personas` / `documents` / `adventures` / `images`);
2849
+ * `scenes` is intentionally omitted and any unknown form returns 404
2850
+ * (surfaced as a thrown Error).
2851
+ */
2852
+ async getFormSchema(form: string): Promise<FormSchemaResponse> {
2853
+ return this.chatRequest<FormSchemaResponse>(
2854
+ `/api/v1/schema/${encodeURIComponent(form)}`,
2855
+ );
2856
+ }
2857
+
2858
+ /**
2859
+ * List every platform tool's human-readable reference
2860
+ * (`GET /api/v1/tools/reference`). Derived server-side from the full
2861
+ * `shared/tool_schemas` registry (`iter_all_tool_schemas` — chat + adventure
2862
+ * + assistant), so the catalogue cannot drift from the live tool list.
2863
+ */
2864
+ async listToolReferences(): Promise<ToolReferenceListResponse> {
2865
+ return this.chatRequest<ToolReferenceListResponse>('/api/v1/tools/reference');
2866
+ }
2867
+
2868
+ /**
2869
+ * Fetch one tool's reference by name
2870
+ * (`GET /api/v1/tools/reference/{name}`). 404 (thrown Error) when the tool
2871
+ * is unknown.
2872
+ */
2873
+ async getToolReference(name: string): Promise<ToolReferenceResponse> {
2874
+ return this.chatRequest<ToolReferenceResponse>(
2875
+ `/api/v1/tools/reference/${encodeURIComponent(name)}`,
2876
+ );
2877
+ }
2878
+
1192
2879
  // ==================== Persona API Methods ====================
1193
2880
  // Note: Personas are served by the Chat API, not the Tools API
1194
2881
 
@@ -1203,17 +2890,26 @@ export class ApiClient {
1203
2890
  }
1204
2891
 
1205
2892
  /**
1206
- * 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.
1207
2900
  */
1208
2901
  async listPersonas(params?: {
1209
2902
  limit?: number;
1210
2903
  nextToken?: string;
1211
2904
  status?: 'pending' | 'approved';
2905
+ sourceVideoId?: string;
1212
2906
  }): Promise<PersonaListResponse> {
1213
2907
  const searchParams = new URLSearchParams();
1214
2908
  if (params?.limit) searchParams.append('limit', params.limit.toString());
1215
2909
  if (params?.nextToken) searchParams.append('nextToken', params.nextToken);
1216
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);
1217
2913
 
1218
2914
  const query = searchParams.toString();
1219
2915
  const endpoint = `/api/v1/personas${query ? `?${query}` : ''}`;
@@ -1221,6 +2917,15 @@ export class ApiClient {
1221
2917
  return this.chatRequest<PersonaListResponse>(endpoint);
1222
2918
  }
1223
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
+
1224
2929
  /**
1225
2930
  * Get the default persona for the current user
1226
2931
  */
@@ -1274,18 +2979,202 @@ export class ApiClient {
1274
2979
  });
1275
2980
  }
1276
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
+
1277
3145
  // ==================== Image API Methods ====================
1278
3146
  // Note: Images are served by the Chat API
1279
3147
 
3148
+ /**
3149
+ * Fetch the image-model catalogue from the backend (R1c). Read-only.
3150
+ * Unlike {@link listChatModels}, this endpoint is **authenticated** (its
3151
+ * consumers — Studio Images, the Admin adapter inspector — are post-auth, so
3152
+ * it is not a public pre-auth path); call it with a valid session. Served via
3153
+ * the CHAT base URL (the images API is mounted on the chat app), so this uses
3154
+ * `chatRequest`, NOT `toolsRequest`.
3155
+ */
3156
+ async listImageModels(): Promise<ImageModelsResponse> {
3157
+ return this.chatRequest<ImageModelsResponse>('/api/v1/images/models');
3158
+ }
3159
+
1280
3160
  async listImages(params?: {
1281
3161
  category?: ImageCategory;
1282
3162
  videoId?: string;
3163
+ /** Filter by generation model. Valid ids come from `listImageModels()`
3164
+ * (R1's `GET /api/v1/images/models`); the backend rejects an
3165
+ * unregistered id with 400. */
3166
+ model?: string;
3167
+ /** Filter by lifecycle status. Reuses the `ImageStatus` union
3168
+ * (`ImageRecord['status']`) — no parallel status enum (R6b). */
3169
+ status?: ImageStatus;
1283
3170
  limit?: number;
1284
3171
  nextToken?: string;
1285
3172
  }): Promise<ImageListResponse> {
1286
3173
  const searchParams = new URLSearchParams();
1287
3174
  if (params?.category) searchParams.append('category', params.category);
1288
3175
  if (params?.videoId) searchParams.append('videoId', params.videoId);
3176
+ if (params?.model) searchParams.append('model', params.model);
3177
+ if (params?.status) searchParams.append('status', params.status);
1289
3178
  if (params?.limit) searchParams.append('limit', params.limit.toString());
1290
3179
  if (params?.nextToken) searchParams.append('nextToken', params.nextToken);
1291
3180
 
@@ -1657,8 +3546,61 @@ export class ApiClient {
1657
3546
 
1658
3547
  // ==================== Graph Editor API Methods ====================
1659
3548
 
1660
- async getVideoGraph(videoId: string): Promise<VideoGraphResponse> {
1661
- return this.request<VideoGraphResponse>(`/api/v1/tools/graph/${encodeURIComponent(videoId)}`);
3549
+ /**
3550
+ * Fetch a video's subgraph. R5b: the optional `detail` arg selects the
3551
+ * server-side view — `GRAPH_DETAIL.STORY` for the collapsed story view,
3552
+ * `GRAPH_DETAIL.RAW` for the full extraction graph. Omitting it sends NO
3553
+ * query param (byte-identical to the pre-R5b request — the server defaults
3554
+ * to raw), so every existing caller is untouched.
3555
+ */
3556
+ async getVideoGraph(videoId: string, detail?: GraphDetail): Promise<VideoGraphResponse> {
3557
+ const base = `/api/v1/tools/graph/${encodeURIComponent(videoId)}`;
3558
+ const path = detail === undefined ? base : `${base}?detail=${encodeURIComponent(detail)}`;
3559
+ return this.request<VideoGraphResponse>(path);
3560
+ }
3561
+
3562
+ // ==================== Creator Studio / Story API Methods (M7 P7) ====================
3563
+
3564
+ /**
3565
+ * List all stories (videos) visible to the caller. `storyId === videoId`
3566
+ * (1:1) in M7 P7 — the Story resource is a thin, read-only view over the
3567
+ * existing Video. No pagination/filter parameters in P7.
3568
+ */
3569
+ async listStories(): Promise<ListStoriesResponse> {
3570
+ return this.request<ListStoriesResponse>('/api/v1/stories');
3571
+ }
3572
+
3573
+ /**
3574
+ * Fetch a single story's metadata + aggregate counts. Throws (404) when the
3575
+ * id resolves to no Video node.
3576
+ */
3577
+ async getStory(storyId: string): Promise<GetStoryResponse> {
3578
+ return this.request<GetStoryResponse>(
3579
+ `/api/v1/stories/${encodeURIComponent(storyId)}`,
3580
+ );
3581
+ }
3582
+
3583
+ /**
3584
+ * Resolve a playable (presigned or local-stub) URL for a clip span via the
3585
+ * existing `POST /api/v1/tools/clip-lookup` tool endpoint. Used by the studio
3586
+ * Scene inspector to scope the player to a scene's `[t0, t1]`. Additive — never
3587
+ * remove/rename. Wire keys are camelCase (backend `BaseSchema`, no aliasing).
3588
+ */
3589
+ async clipLookup(params: ClipLookupParams): Promise<ClipLookupResponse> {
3590
+ return this.request<ClipLookupResponse>('/api/v1/tools/clip-lookup', {
3591
+ method: 'POST',
3592
+ body: JSON.stringify(params),
3593
+ });
3594
+ }
3595
+
3596
+ /**
3597
+ * Fetch the live graph whitelist (node PKs + editable properties per label
3598
+ * and edge type). No auth required — pure metadata. Prefer the memoized
3599
+ * `fetchGraphSchema()` wrapper in `graphSchema.ts` over calling this per
3600
+ * render; the raw method exists for that wrapper and one-off callers.
3601
+ */
3602
+ async getGraphSchema(): Promise<GraphSchemaResponse> {
3603
+ return this.request<GraphSchemaResponse>('/api/v1/tools/graph/schema');
1662
3604
  }
1663
3605
 
1664
3606
  async updateGraphNode(data: UpdateNodeRequest): Promise<UpdateNodeResponse> {
@@ -1669,10 +3611,16 @@ export class ApiClient {
1669
3611
  }
1670
3612
 
1671
3613
  async deleteGraphNode(data: DeleteNodeRequest): Promise<DeleteNodeResponse> {
1672
- return this.request<DeleteNodeResponse>('/api/v1/tools/graph/nodes', {
1673
- method: 'DELETE',
1674
- body: JSON.stringify(data),
3614
+ // DELETE carries no body — identifiers travel as query params (M7 P1a,
3615
+ // closes tech-debt #42). The backend derives the PK from the label.
3616
+ const params = new URLSearchParams({
3617
+ nodeLabel: data.nodeLabel,
3618
+ idValue: data.idValue,
1675
3619
  });
3620
+ return this.request<DeleteNodeResponse>(
3621
+ `/api/v1/tools/graph/nodes?${params.toString()}`,
3622
+ { method: 'DELETE' },
3623
+ );
1676
3624
  }
1677
3625
 
1678
3626
  async updateGraphEdge(data: UpdateRelationshipRequest): Promise<UpdateRelationshipResponse> {
@@ -1683,8 +3631,43 @@ export class ApiClient {
1683
3631
  }
1684
3632
 
1685
3633
  async deleteGraphEdge(data: DeleteRelationshipRequest): Promise<DeleteRelationshipResponse> {
1686
- return this.request<DeleteRelationshipResponse>('/api/v1/tools/graph/edges', {
1687
- method: 'DELETE',
3634
+ // DELETE carries no body — identifiers travel as query params (M7 P1a,
3635
+ // closes tech-debt #42).
3636
+ const params = new URLSearchParams({
3637
+ sourceId: data.sourceId,
3638
+ targetId: data.targetId,
3639
+ relType: data.relType,
3640
+ });
3641
+ return this.request<DeleteRelationshipResponse>(
3642
+ `/api/v1/tools/graph/edges?${params.toString()}`,
3643
+ { method: 'DELETE' },
3644
+ );
3645
+ }
3646
+
3647
+ /**
3648
+ * Create a user-authored narrative node (Scene / PlotBeat / CharacterArc).
3649
+ * POST returns 201 with `{traceId, nodeId, properties}`; `makeRequest` parses
3650
+ * the body (only 204 is bodyless) and surfaces a 422 (e.g. label not
3651
+ * user-creatable, missing actId/index for a Scene) as a thrown `Error` with
3652
+ * the FastAPI detail. The backend stamps provenance/versionId/timestamps.
3653
+ */
3654
+ async createGraphNode(data: CreateNodeRequest): Promise<CreateNodeResponse> {
3655
+ return this.request<CreateNodeResponse>('/api/v1/tools/graph/nodes', {
3656
+ method: 'POST',
3657
+ body: JSON.stringify(data),
3658
+ });
3659
+ }
3660
+
3661
+ /**
3662
+ * Create a user-authored relationship (RELATES_TO / CAUSES / SET_IN /
3663
+ * FEATURES / ON_ARC / LEADS_TO). POST returns 201 with
3664
+ * `{traceId, edgeId, properties}`; a 422 (invalid endpoint-label pair,
3665
+ * pipeline-only type, cross-video endpoints, or SET_IN/FEATURES Entity.type
3666
+ * mismatch) surfaces as a thrown `Error` with the FastAPI detail.
3667
+ */
3668
+ async createGraphEdge(data: CreateEdgeRequest): Promise<CreateEdgeResponse> {
3669
+ return this.request<CreateEdgeResponse>('/api/v1/tools/graph/edges', {
3670
+ method: 'POST',
1688
3671
  body: JSON.stringify(data),
1689
3672
  });
1690
3673
  }
@@ -2166,4 +4149,141 @@ export class ApiClient {
2166
4149
  );
2167
4150
  }
2168
4151
 
4152
+ // ============= Adventure Runtime API (M9 Story Engine Phase 8a) =============
4153
+
4154
+ /**
4155
+ * Start an interactive adventure for a story/video, driven by a
4156
+ * Dungeon-Master persona. `POST /api/v1/adventures` → 201 with the initial
4157
+ * {@link AdventureState} (and a `Location` header to the session's GET URL).
4158
+ *
4159
+ * Auth + video ownership are enforced server-side. `dmPersonaId` must
4160
+ * reference an owned persona whose `is_dungeon_master` is true (422 otherwise),
4161
+ * and a missing/unowned persona is a 404/403 — all surface as a thrown `Error`
4162
+ * carrying the FastAPI detail. Additive — never remove/rename.
4163
+ */
4164
+ async startAdventure(
4165
+ request: StartAdventureRequest,
4166
+ options: { signal?: AbortSignal } = {},
4167
+ ): Promise<AdventureResponse> {
4168
+ return this.request<AdventureResponse>('/api/v1/adventures', {
4169
+ method: 'POST',
4170
+ body: JSON.stringify(request),
4171
+ signal: options.signal,
4172
+ });
4173
+ }
4174
+
4175
+ /**
4176
+ * Fetch the current {@link AdventureState} for a session.
4177
+ * `GET /api/v1/adventures/{sessionId}` (404 when absent or not owned by the
4178
+ * caller — the store hides cross-tenant and soft-deleted sessions).
4179
+ */
4180
+ async getAdventure(
4181
+ sessionId: string,
4182
+ options: { signal?: AbortSignal } = {},
4183
+ ): Promise<GetAdventureResponse> {
4184
+ return this.request<GetAdventureResponse>(
4185
+ `/api/v1/adventures/${encodeURIComponent(sessionId)}`,
4186
+ { signal: options.signal },
4187
+ );
4188
+ }
4189
+
4190
+ /**
4191
+ * List the caller's adventures, newest-first. `GET /api/v1/adventures` →
4192
+ * {@link ListAdventuresResponse}. Owner-scoped server-side (soft-deleted
4193
+ * sessions excluded); pass `storyId` to narrow to a single story. Additive —
4194
+ * never remove/rename.
4195
+ */
4196
+ async listAdventures(
4197
+ storyId?: string,
4198
+ options: { signal?: AbortSignal } = {},
4199
+ ): Promise<ListAdventuresResponse> {
4200
+ const searchParams = new URLSearchParams();
4201
+ if (storyId) searchParams.append('storyId', storyId);
4202
+
4203
+ const query = searchParams.toString();
4204
+ const endpoint = `/api/v1/adventures${query ? `?${query}` : ''}`;
4205
+ return this.request<ListAdventuresResponse>(endpoint, {
4206
+ signal: options.signal,
4207
+ });
4208
+ }
4209
+
4210
+ /**
4211
+ * Soft-delete an adventure session. `DELETE /api/v1/adventures/{sessionId}`
4212
+ * → 204 (resolves to `void`). A missing/unowned session is a 404 surfaced as
4213
+ * a thrown `Error`.
4214
+ */
4215
+ async deleteAdventure(
4216
+ sessionId: string,
4217
+ options: { signal?: AbortSignal } = {},
4218
+ ): Promise<void> {
4219
+ return this.request<void>(
4220
+ `/api/v1/adventures/${encodeURIComponent(sessionId)}`,
4221
+ { method: 'DELETE', signal: options.signal },
4222
+ );
4223
+ }
4224
+
4225
+ /**
4226
+ * Mutate an adventure's party (M10 Story Engine Phase 9a).
4227
+ * `PATCH /api/v1/adventures/{sessionId}/party` with
4228
+ * `{ action, personaId }` → the updated {@link GetAdventureResponse}.
4229
+ * Shared by {@link addPartyMember} / {@link removePartyMember}; not exported
4230
+ * directly so call sites go through the action-specific wrappers. Additive —
4231
+ * never remove/rename.
4232
+ */
4233
+ private patchParty(
4234
+ sessionId: string,
4235
+ request: PartyUpdateRequest,
4236
+ options: { signal?: AbortSignal } = {},
4237
+ ): Promise<GetAdventureResponse> {
4238
+ return this.request<GetAdventureResponse>(
4239
+ `/api/v1/adventures/${encodeURIComponent(sessionId)}/party`,
4240
+ {
4241
+ method: 'PATCH',
4242
+ body: JSON.stringify(request),
4243
+ signal: options.signal,
4244
+ },
4245
+ );
4246
+ }
4247
+
4248
+ /**
4249
+ * Add a character persona to an adventure's party (M10 Story Engine Phase
4250
+ * 9a). `PATCH /api/v1/adventures/{sessionId}/party` with `action='add'` →
4251
+ * the updated {@link GetAdventureResponse}. The persona must be owned by the
4252
+ * caller, bound to a character entity, and NOT a Dungeon Master (422
4253
+ * otherwise); a missing/unowned adventure is a 404 — all surface as a thrown
4254
+ * `Error` carrying the FastAPI detail. Server-side dedupe makes a repeat add
4255
+ * a no-op. Additive — never remove/rename.
4256
+ */
4257
+ async addPartyMember(
4258
+ sessionId: string,
4259
+ personaId: string,
4260
+ options: { signal?: AbortSignal } = {},
4261
+ ): Promise<GetAdventureResponse> {
4262
+ return this.patchParty(
4263
+ sessionId,
4264
+ { action: PARTY_ACTION.ADD, personaId },
4265
+ options,
4266
+ );
4267
+ }
4268
+
4269
+ /**
4270
+ * Remove a character persona from an adventure's party (M10 Story Engine
4271
+ * Phase 9a). `PATCH /api/v1/adventures/{sessionId}/party` with
4272
+ * `action='remove'` → the updated {@link GetAdventureResponse}. Idempotent:
4273
+ * removing an absent member is a 200 no-op that returns the current state. A
4274
+ * missing/unowned adventure is a 404 surfaced as a thrown `Error`. Additive —
4275
+ * never remove/rename.
4276
+ */
4277
+ async removePartyMember(
4278
+ sessionId: string,
4279
+ personaId: string,
4280
+ options: { signal?: AbortSignal } = {},
4281
+ ): Promise<GetAdventureResponse> {
4282
+ return this.patchParty(
4283
+ sessionId,
4284
+ { action: PARTY_ACTION.REMOVE, personaId },
4285
+ options,
4286
+ );
4287
+ }
4288
+
2169
4289
  }