@escapeaihq/client-core 0.8.0 → 0.42.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 (307) hide show
  1. package/README.md +48 -4
  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 +200 -0
  31. package/dist/admin.d.ts.map +1 -0
  32. package/dist/admin.js +124 -0
  33. package/dist/admin.js.map +1 -0
  34. package/dist/api.d.ts +1299 -3
  35. package/dist/api.d.ts.map +1 -1
  36. package/dist/api.js +683 -95
  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 +62 -0
  47. package/dist/conversation/binding.d.ts.map +1 -0
  48. package/dist/conversation/binding.js +51 -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 +342 -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 +260 -0
  103. package/dist/graphSchema.d.ts.map +1 -0
  104. package/dist/graphSchema.js +354 -0
  105. package/dist/graphSchema.js.map +1 -0
  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 +9 -0
  111. package/dist/index.d.ts.map +1 -1
  112. package/dist/index.js +12 -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/abortUtils.d.ts +16 -0
  119. package/dist/reactor/abortUtils.d.ts.map +1 -0
  120. package/dist/reactor/abortUtils.js +26 -0
  121. package/dist/reactor/abortUtils.js.map +1 -0
  122. package/dist/reactor/applyScenePrompt.d.ts +75 -0
  123. package/dist/reactor/applyScenePrompt.d.ts.map +1 -0
  124. package/dist/reactor/applyScenePrompt.js +60 -0
  125. package/dist/reactor/applyScenePrompt.js.map +1 -0
  126. package/dist/reactor/chunkDistribution.d.ts +43 -0
  127. package/dist/reactor/chunkDistribution.d.ts.map +1 -0
  128. package/dist/reactor/chunkDistribution.js +85 -0
  129. package/dist/reactor/chunkDistribution.js.map +1 -0
  130. package/dist/reactor/heliosCommandDispatcher.d.ts.map +1 -1
  131. package/dist/reactor/heliosCommandDispatcher.js +10 -15
  132. package/dist/reactor/heliosCommandDispatcher.js.map +1 -1
  133. package/dist/reactor/index.d.ts +4 -0
  134. package/dist/reactor/index.d.ts.map +1 -1
  135. package/dist/reactor/index.js +7 -0
  136. package/dist/reactor/index.js.map +1 -1
  137. package/dist/reactor/longLiveCommandDispatcher.d.ts +103 -0
  138. package/dist/reactor/longLiveCommandDispatcher.d.ts.map +1 -0
  139. package/dist/reactor/longLiveCommandDispatcher.js +87 -0
  140. package/dist/reactor/longLiveCommandDispatcher.js.map +1 -0
  141. package/dist/reactor/sceneEntry.d.ts +40 -6
  142. package/dist/reactor/sceneEntry.d.ts.map +1 -1
  143. package/dist/reactor/sceneEntry.js +63 -24
  144. package/dist/reactor/sceneEntry.js.map +1 -1
  145. package/dist/reactor/scenesFromEnrichment.d.ts.map +1 -1
  146. package/dist/reactor/scenesFromEnrichment.js +2 -66
  147. package/dist/reactor/scenesFromEnrichment.js.map +1 -1
  148. package/dist/reactor/seedImageOrchestrator.d.ts +42 -2
  149. package/dist/reactor/seedImageOrchestrator.d.ts.map +1 -1
  150. package/dist/reactor/seedImageOrchestrator.js +173 -4
  151. package/dist/reactor/seedImageOrchestrator.js.map +1 -1
  152. package/dist/reactor/storyTimeline.d.ts +44 -0
  153. package/dist/reactor/storyTimeline.d.ts.map +1 -0
  154. package/dist/reactor/storyTimeline.js +95 -0
  155. package/dist/reactor/storyTimeline.js.map +1 -0
  156. package/dist/storyGraph.d.ts +70 -0
  157. package/dist/storyGraph.d.ts.map +1 -0
  158. package/dist/storyGraph.js +178 -0
  159. package/dist/storyGraph.js.map +1 -0
  160. package/dist/timeFormat.d.ts +10 -0
  161. package/dist/timeFormat.d.ts.map +1 -1
  162. package/dist/timeFormat.js +12 -0
  163. package/dist/timeFormat.js.map +1 -1
  164. package/dist/toolSchemas.d.ts +370 -0
  165. package/dist/toolSchemas.d.ts.map +1 -0
  166. package/dist/toolSchemas.js +182 -0
  167. package/dist/toolSchemas.js.map +1 -0
  168. package/dist/vision/VisionPublisher.d.ts +115 -0
  169. package/dist/vision/VisionPublisher.d.ts.map +1 -0
  170. package/dist/vision/VisionPublisher.js +475 -0
  171. package/dist/vision/VisionPublisher.js.map +1 -0
  172. package/dist/vision/VisionSourceController.d.ts +127 -0
  173. package/dist/vision/VisionSourceController.d.ts.map +1 -0
  174. package/dist/vision/VisionSourceController.js +284 -0
  175. package/dist/vision/VisionSourceController.js.map +1 -0
  176. package/dist/vision/credentials.d.ts +22 -0
  177. package/dist/vision/credentials.d.ts.map +1 -0
  178. package/dist/vision/credentials.js +34 -0
  179. package/dist/vision/credentials.js.map +1 -0
  180. package/dist/vision/index.d.ts +18 -0
  181. package/dist/vision/index.d.ts.map +1 -0
  182. package/dist/vision/index.js +13 -0
  183. package/dist/vision/index.js.map +1 -0
  184. package/dist/vision/sourceKinds.d.ts +65 -0
  185. package/dist/vision/sourceKinds.d.ts.map +1 -0
  186. package/dist/vision/sourceKinds.js +26 -0
  187. package/dist/vision/sourceKinds.js.map +1 -0
  188. package/dist/vision/startVisionPublisher.d.ts +38 -0
  189. package/dist/vision/startVisionPublisher.d.ts.map +1 -0
  190. package/dist/vision/startVisionPublisher.js +44 -0
  191. package/dist/vision/startVisionPublisher.js.map +1 -0
  192. package/dist/vision/types.d.ts +95 -0
  193. package/dist/vision/types.d.ts.map +1 -0
  194. package/dist/vision/types.js +12 -0
  195. package/dist/vision/types.js.map +1 -0
  196. package/dist/vision/visionScheduler.d.ts +63 -0
  197. package/dist/vision/visionScheduler.d.ts.map +1 -0
  198. package/dist/vision/visionScheduler.js +67 -0
  199. package/dist/vision/visionScheduler.js.map +1 -0
  200. package/dist/websocket.d.ts +195 -0
  201. package/dist/websocket.d.ts.map +1 -1
  202. package/dist/websocket.js +179 -1
  203. package/dist/websocket.js.map +1 -1
  204. package/package.json +11 -1
  205. package/src/__tests__/adapters-capabilities.test.ts +46 -0
  206. package/src/__tests__/adapters-chat.test.ts +172 -0
  207. package/src/__tests__/adapters-director.test.ts +95 -0
  208. package/src/__tests__/adapters-image.test.ts +133 -0
  209. package/src/__tests__/adapters-platform.test.ts +95 -0
  210. package/src/__tests__/adapters-registry.test.ts +189 -0
  211. package/src/__tests__/adapters-world.test.ts +296 -0
  212. package/src/__tests__/admin.test.ts +312 -0
  213. package/src/__tests__/adventures-party.test.ts +219 -0
  214. package/src/__tests__/adventures.test.ts +282 -0
  215. package/src/__tests__/api-pollers.test.ts +104 -0
  216. package/src/__tests__/api.clip-lookup.test.ts +64 -0
  217. package/src/__tests__/api.list-images-filters.test.ts +103 -0
  218. package/src/__tests__/api.test.ts +470 -0
  219. package/src/__tests__/audio.test.ts +65 -0
  220. package/src/__tests__/cast.test.ts +95 -0
  221. package/src/__tests__/castProjection.test.ts +167 -0
  222. package/src/__tests__/chat-auth.test.ts +91 -0
  223. package/src/__tests__/conversation/controller.test.ts +697 -0
  224. package/src/__tests__/conversation/effectiveModel.test.ts +169 -0
  225. package/src/__tests__/conversation/headlessRenderer.ts +46 -0
  226. package/src/__tests__/conversation/presenceBus.test.ts +236 -0
  227. package/src/__tests__/conversation/presenceRegistry.test.ts +73 -0
  228. package/src/__tests__/conversation/roster.test.ts +100 -0
  229. package/src/__tests__/conversation/rosterProjection.test.ts +142 -0
  230. package/src/__tests__/conversation/router.test.ts +81 -0
  231. package/src/__tests__/conversation/runtime.test.ts +206 -0
  232. package/src/__tests__/conversation/voice.test.ts +440 -0
  233. package/src/__tests__/documents.test.ts +360 -0
  234. package/src/__tests__/graphSchema.test.ts +326 -0
  235. package/src/__tests__/longLiveCommandDispatcher.test.ts +185 -0
  236. package/src/__tests__/platformAssistant.test.ts +484 -0
  237. package/src/__tests__/reactor/applyScenePrompt.test.ts +192 -0
  238. package/src/__tests__/reactor/heliosCommandDispatcher.test.ts +4 -3
  239. package/src/__tests__/reactor/sceneEntry.test.ts +134 -10
  240. package/src/__tests__/reactor/seedImageOrchestrator.test.ts +51 -16
  241. package/src/__tests__/reactor/storyTimeline.test.ts +186 -0
  242. package/src/__tests__/regeneration.test.ts +486 -0
  243. package/src/__tests__/stories.test.ts +171 -0
  244. package/src/__tests__/storyGraph.test.ts +134 -0
  245. package/src/__tests__/timeFormat.test.ts +22 -1
  246. package/src/__tests__/toolSchemas.test.ts +57 -0
  247. package/src/__tests__/tools-wrappers.test.ts +272 -0
  248. package/src/__tests__/videoGraph.test.ts +94 -0
  249. package/src/__tests__/websocket-vision.test.ts +265 -0
  250. package/src/__tests__/websocket.test.ts +213 -0
  251. package/src/adapters/capabilities.ts +24 -0
  252. package/src/adapters/chatAdapter.ts +114 -0
  253. package/src/adapters/directorAdapter.ts +126 -0
  254. package/src/adapters/imageAdapter.ts +100 -0
  255. package/src/adapters/index.ts +67 -0
  256. package/src/adapters/registry.ts +159 -0
  257. package/src/adapters/worldAdapter.ts +272 -0
  258. package/src/admin.ts +310 -0
  259. package/src/api.ts +1890 -162
  260. package/src/audio.ts +35 -0
  261. package/src/castProjection.ts +95 -0
  262. package/src/conversation/binding.ts +81 -0
  263. package/src/conversation/controller.ts +439 -0
  264. package/src/conversation/effectiveModel.ts +111 -0
  265. package/src/conversation/index.ts +27 -0
  266. package/src/conversation/participant.ts +71 -0
  267. package/src/conversation/presence.ts +60 -0
  268. package/src/conversation/presenceBus.ts +109 -0
  269. package/src/conversation/presenceRegistry.ts +83 -0
  270. package/src/conversation/roster.ts +111 -0
  271. package/src/conversation/rosterProjection.ts +98 -0
  272. package/src/conversation/router.ts +96 -0
  273. package/src/conversation/runtime.ts +188 -0
  274. package/src/conversation/types.ts +100 -0
  275. package/src/conversation/voice.ts +402 -0
  276. package/src/graphSchema.ts +532 -0
  277. package/src/http.ts +72 -0
  278. package/src/index.ts +12 -0
  279. package/src/platformAssistant.ts +347 -0
  280. package/src/reactor/abortUtils.ts +22 -0
  281. package/src/reactor/applyScenePrompt.ts +136 -0
  282. package/src/reactor/chunkDistribution.ts +98 -0
  283. package/src/reactor/heliosCommandDispatcher.ts +10 -18
  284. package/src/reactor/index.ts +7 -0
  285. package/src/reactor/longLiveCommandDispatcher.ts +156 -0
  286. package/src/reactor/sceneEntry.ts +104 -33
  287. package/src/reactor/scenesFromEnrichment.ts +11 -76
  288. package/src/reactor/seedImageOrchestrator.ts +200 -4
  289. package/src/reactor/storyTimeline.ts +127 -0
  290. package/src/storyGraph.ts +298 -0
  291. package/src/timeFormat.ts +13 -0
  292. package/src/toolSchemas.ts +225 -0
  293. package/src/vision/VisionPublisher.ts +553 -0
  294. package/src/vision/VisionSourceController.ts +354 -0
  295. package/src/vision/__tests__/VisionPublisher.kvs.test.ts +244 -0
  296. package/src/vision/__tests__/VisionPublisher.test.ts +301 -0
  297. package/src/vision/__tests__/VisionSourceController.test.ts +719 -0
  298. package/src/vision/__tests__/startVisionPublisher.test.ts +251 -0
  299. package/src/vision/__tests__/toVisionRtcCredentials.test.ts +113 -0
  300. package/src/vision/__tests__/visionScheduler.test.ts +149 -0
  301. package/src/vision/credentials.ts +39 -0
  302. package/src/vision/index.ts +44 -0
  303. package/src/vision/sourceKinds.ts +75 -0
  304. package/src/vision/startVisionPublisher.ts +64 -0
  305. package/src/vision/types.ts +101 -0
  306. package/src/vision/visionScheduler.ts +102 -0
  307. package/src/websocket.ts +334 -4
package/src/api.ts CHANGED
@@ -3,12 +3,39 @@
3
3
  */
4
4
 
5
5
  import type { AudioFormat } from './audioProtocol';
6
+ import { isAbortError } from './reactor/abortUtils';
7
+ import { requestJson } from './http';
6
8
  import type {
7
9
  EntityContext as ReactorEntityContext,
8
10
  PersonaContext as ReactorPersonaContext,
9
11
  } from './reactor/types';
10
12
  import type { Citation } from './websocket';
11
13
 
14
+ /**
15
+ * Module-private helper: resolves after `ms` milliseconds, or rejects with
16
+ * an AbortError if the optional `signal` fires before the timer expires.
17
+ *
18
+ * Listener hygiene: the abort listener is removed explicitly on the normal
19
+ * (timer) path so it does not linger on the signal after resolution.
20
+ */
21
+ function abortableSleep(ms: number, signal?: AbortSignal): Promise<void> {
22
+ return new Promise<void>((resolve, reject) => {
23
+ // Declare `timer` with `let` first so `onAbort` can reference it in the
24
+ // closure without a use-before-define lint error (the closure is only
25
+ // invoked after `timer` is assigned below).
26
+ let timer: ReturnType<typeof setTimeout>;
27
+ const onAbort = () => {
28
+ clearTimeout(timer);
29
+ reject(new DOMException('Polling aborted', 'AbortError'));
30
+ };
31
+ timer = setTimeout(() => {
32
+ signal?.removeEventListener('abort', onAbort);
33
+ resolve();
34
+ }, ms);
35
+ signal?.addEventListener('abort', onAbort, { once: true });
36
+ });
37
+ }
38
+
12
39
  export interface IngestionJob {
13
40
  jobId: string;
14
41
  videoId: string;
@@ -135,6 +162,339 @@ export interface VideoDeletionResponse {
135
162
  errors?: string[] | null;
136
163
  }
137
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
+
138
498
  export interface ChatMessage {
139
499
  role: 'user' | 'assistant';
140
500
  content: string;
@@ -148,8 +508,279 @@ export interface ChatStreamRequest {
148
508
  modelId?: string;
149
509
  }
150
510
 
511
+ /**
512
+ * Route the Platform Assistant (R4) is summoned on, so the server-side
513
+ * assistant can scope its `propose_form_fields` suggestions to the
514
+ * current surface + form. Mirrors `api/assistant/schemas.py:RouteContext`.
515
+ */
516
+ export interface AssistantRouteContext {
517
+ /** The UI surface, e.g. `'studio/cast'` or `'settings/defaults'`. */
518
+ surface: string;
519
+ /** The form the user is editing, e.g. `'persona'` (optional). */
520
+ formId?: string;
521
+ /** The entity/story the form is bound to, if any (optional). */
522
+ entityId?: string;
523
+ }
524
+
525
+ /**
526
+ * Request body for `POST /api/v1/assistant/stream` — the R4 Platform
527
+ * Assistant SSE copilot. Mirrors {@link ChatStreamRequest} but:
528
+ * - DROPS `videoId` — the assistant is out-of-world (not video-scoped);
529
+ * it answers tooling questions + proposes form-field values.
530
+ * - ADDS `routeContext` so the assistant knows which surface/form the
531
+ * user is on.
532
+ *
533
+ * There is intentionally NO `systemPrompt` override (unlike chat): the
534
+ * assistant has no prompt-injection escape hatch (see the R4a spec
535
+ * "Prompt-injection surface" risk). Model resolution flows server-side
536
+ * through the SAME `resolve_model_id` → `shared/model_router.py` seam the
537
+ * chat endpoint uses — `modelId` is an optional explicit pin only.
538
+ *
539
+ * `documentContext` (R11.2) is a SEPARATE, larger-capped field for an
540
+ * "operate on this document" draft (e.g. a long prompt the user wants
541
+ * refined). It is DISTINCT from the deliberately-small `prompt`
542
+ * user-message field: the server places it in MODEL CONTEXT (the system
543
+ * prompt), never the user turn, so the small `prompt` cap keeps its
544
+ * prompt-injection floor while a full-length draft still round-trips.
545
+ */
546
+ export interface AssistantStreamRequest {
547
+ prompt: string;
548
+ messages?: ChatMessage[];
549
+ modelId?: string;
550
+ routeContext?: AssistantRouteContext;
551
+ /**
552
+ * Optional large document/draft for the assistant to operate ON (R11.2).
553
+ * Placed in model context server-side, NOT the user turn. Capped at the
554
+ * admin prompt editor's max so a full-length "Improve with assistant"
555
+ * draft round-trips (the small 2 KB `prompt` cap stays for injection
556
+ * mitigation).
557
+ */
558
+ documentContext?: string;
559
+ }
560
+
561
+ /**
562
+ * Discriminated union of the SSE events the chat / assistant stream
563
+ * endpoints emit (decoded from each `data: {…}` line). Mirrors the
564
+ * transport-agnostic `ChatEventType` values in
565
+ * `shared/chat_dispatcher.py` that survive onto the SSE wire.
566
+ *
567
+ * The R4 Platform Assistant ADDS the `'suggestion'` variant ALONGSIDE the
568
+ * existing token / tool_use / tool_result / citation / error / done variants —
569
+ * it never replaces one. The assistant's `propose_form_fields` tool result is
570
+ * converted by the dispatcher into a `suggestion` event the host UI maps
571
+ * onto its own form fields (it mutates nothing server-side). Consumers
572
+ * `switch` on `type` to narrow.
573
+ */
574
+ export type AssistantStreamEvent =
575
+ | { type: 'token'; timestamp?: number; content: string }
576
+ | { type: 'tool_use'; timestamp?: number; tool: string; toolUseId: string }
577
+ | {
578
+ /**
579
+ * The structured `tool_result` frame the dispatcher emits after EVERY
580
+ * assistant tool call (parity with the chat executor path): for
581
+ * `propose_form_fields` it follows the `suggestion` event; for the
582
+ * reference tools (`describe_tool` / `list_platform_capabilities`) it is
583
+ * the only structured result. Wire contract shared with `api/assistant`
584
+ * (the Python dispatcher emits this exact `{tool, toolUseId, result}`
585
+ * shape) — included here so an exhaustive `switch` handles it.
586
+ */
587
+ type: 'tool_result';
588
+ timestamp?: number;
589
+ tool: string;
590
+ toolUseId: string;
591
+ result: Record<string, unknown>;
592
+ }
593
+ | { type: 'citation'; timestamp?: number; citation: Citation; span?: string }
594
+ | { type: 'error'; timestamp?: number; message: string }
595
+ | { type: 'done'; timestamp?: number; reason?: string }
596
+ | {
597
+ /**
598
+ * A `propose_form_fields` tool call surfaced as a structured
599
+ * suggestion the host page reviews + applies. Carries the target
600
+ * form id, the proposed `{fieldName: value}` map, and an optional
601
+ * rationale. Wire contract shared with `api/assistant` (the Python
602
+ * dispatcher emits this exact shape).
603
+ */
604
+ type: 'suggestion';
605
+ timestamp?: number;
606
+ targetForm: string;
607
+ fields: Record<string, string>;
608
+ rationale?: string;
609
+ };
610
+
611
+ /**
612
+ * One field of a creator/admin form, as returned by the R4b form-schema
613
+ * reference endpoint (`GET /api/v1/schema/{form}`). The backend DERIVES each
614
+ * field from the form's PUBLIC Pydantic request model via `model_json_schema()`
615
+ * (single source of truth — it can never drift from the real endpoint contract).
616
+ * The assistant consults this so `propose_form_fields` only proposes VALID
617
+ * field names. Mirrors `api/assistant/schemas.py:FormField`.
618
+ */
619
+ export interface FormSchemaField {
620
+ /** The wire field name (e.g. `name`, `systemPrompt`, `voiceId`). */
621
+ name: string;
622
+ /** JSON-schema type token (`string` / `integer` / `boolean` / `object` / …). */
623
+ type: string;
624
+ /** Whether the source model marks this field required. */
625
+ required: boolean;
626
+ /**
627
+ * Human-readable field description (from the Pydantic `Field(description=…)`).
628
+ * `null` when the source field declares no description (backend `str | None`).
629
+ */
630
+ description: string | null;
631
+ /**
632
+ * Optional JSON-schema constraints carried through from the source model
633
+ * (e.g. `{ maxLength, minLength, enum }`). Absent when the field has none.
634
+ */
635
+ constraints?: Record<string, unknown>;
636
+ /** Optional example values for the field, when the source model supplies them. */
637
+ examples?: unknown[];
638
+ }
639
+
640
+ /**
641
+ * Response of `GET /api/v1/schema/{form}` (R4b) — the queryable, drift-proof
642
+ * description of a named creator/admin form's fields. `form` is the requested
643
+ * form id (`personas` / `documents` / `adventures` / `images` / `scenes` — an
644
+ * explicit allow-list; `scenes` returns the editable Scene fields {title,
645
+ * summary} since R11.3 added the public `UpdateSceneRequest` model; NEVER an
646
+ * extraction-prompt form, per the graph-corruption carve-out, tech-debt #336).
647
+ * Mirrors `api/assistant/schemas.py:FormSchemaResponse`.
648
+ */
649
+ export interface FormSchemaResponse {
650
+ /** The form id this schema describes. */
651
+ form: string;
652
+ /** The form's fields, derived from its public Pydantic request model. */
653
+ fields: FormSchemaField[];
654
+ /** Trace id for log correlation. */
655
+ traceId: string;
656
+ }
657
+
658
+ /**
659
+ * One tool's human-readable reference, as returned by the R4b tool-reference
660
+ * endpoints. DERIVED from the full `shared/tool_schemas` registry
661
+ * (`iter_all_tool_schemas` — chat + adventure + assistant; the same source the
662
+ * executor resolves from — the catalogue and the runtime tool surface cannot
663
+ * diverge). `params` is the per-parameter descriptor map keyed by parameter
664
+ * name. Mirrors `api/assistant/schemas.py:ToolReference`.
665
+ */
666
+ export interface ToolReference {
667
+ /** The tool name (e.g. `propose_form_fields`, `semantic_search`). */
668
+ name: string;
669
+ /** Human-readable description of what the tool does. */
670
+ description: string;
671
+ /** Per-parameter descriptors keyed by parameter name. */
672
+ params: Record<string, unknown>;
673
+ }
674
+
675
+ /**
676
+ * Response of `GET /api/v1/tools/reference` (R4b) — every executor-resolvable
677
+ * tool, derived from the full `shared/tool_schemas` registry
678
+ * (`iter_all_tool_schemas` — chat + adventure + assistant) so the catalogue
679
+ * cannot drift from the live tool list. Mirrors
680
+ * `api/assistant/schemas.py:ToolReferenceListResponse`.
681
+ */
682
+ export interface ToolReferenceListResponse {
683
+ /** Every platform tool's reference. */
684
+ tools: ToolReference[];
685
+ /** Trace id for log correlation. */
686
+ traceId: string;
687
+ }
688
+
689
+ /**
690
+ * Response of `GET /api/v1/tools/reference/{name}` (R4b) — one tool's reference
691
+ * NESTED under `tool` (matching the backend `ToolReferenceDetailResponse`, which
692
+ * keeps `traceId` at the top level alongside the `tool` object, mirroring the
693
+ * `{ tools, traceId }` list shape). 404 when the tool is unknown. Mirrors
694
+ * `api/assistant/schemas.py:ToolReferenceDetailResponse`.
695
+ */
696
+ export interface ToolReferenceResponse {
697
+ /** The requested tool's reference. */
698
+ tool: ToolReference;
699
+ /** Trace id for log correlation. */
700
+ traceId: string;
701
+ }
702
+
703
+ /**
704
+ * Capability flags advertised by a chat model. Mirrors
705
+ * ``shared/model_config.py:CAPABILITY_*`` so frontends can decide which
706
+ * UI affordances (image upload, audio chat, tool selection) to enable
707
+ * per model.
708
+ */
709
+ export type ChatModelCapability = 'tools' | 'vision' | 'audio' | 'thinking';
710
+
711
+ /**
712
+ * Single entry from ``GET /api/v1/chat/models``. The ``provider`` field
713
+ * tells consumers whether the backend will route via Bedrock or an
714
+ * OpenAI-compatible local endpoint — affects only diagnostics; the chat
715
+ * WebSocket protocol is identical for both.
716
+ */
717
+ export interface ChatModelInfo {
718
+ id: string;
719
+ name: string;
720
+ displayName: string;
721
+ provider: 'bedrock' | 'ollama' | string;
722
+ contextWindow: number;
723
+ maxOutputTokens: number;
724
+ capabilities: ChatModelCapability[];
725
+ }
726
+
727
+ export interface ChatModelsResponse {
728
+ models: ChatModelInfo[];
729
+ defaultModelId?: string | null;
730
+ }
731
+
732
+ /**
733
+ * Single entry returned by `GET /api/v1/images/models` (R1c).
734
+ *
735
+ * Mirrors `ChatModelInfo` for the read-only image-model catalogue. `capabilities`
736
+ * is the raw wire type (`string[]`) — NOT the adapter `Capability[]` union — so
737
+ * api.ts has no import cycle with `adapters/capabilities.ts`. The image adapter
738
+ * (`adapters/imageAdapter.ts`) casts it to `Capability[]` when building a
739
+ * descriptor.
740
+ */
741
+ export interface ImageModelInfo {
742
+ id: string;
743
+ displayName: string;
744
+ provider: string;
745
+ capabilities: string[];
746
+ isDefault: boolean;
747
+ isFallback: boolean;
748
+ }
749
+
750
+ export interface ImageModelsResponse {
751
+ models: ImageModelInfo[];
752
+ }
753
+
754
+ /**
755
+ * Default system prompt components returned by `GET /api/v1/chat/system-prompt`.
756
+ *
757
+ * @property film_qa - Base film analyst persona and instructions
758
+ * @property guardrails - Developer guidance and safety constraints
759
+ * @property audio_markup - Instructions for TTS-optimized responses
760
+ * @property full_default - Combined default prompt as used in chat sessions
761
+ */
762
+ export interface SystemPromptComponents {
763
+ film_qa: string;
764
+ guardrails: string;
765
+ audio_markup: string;
766
+ full_default: string;
767
+ }
768
+
151
769
  // Persona types matching backend shared/persona_models.py
152
770
 
771
+ /**
772
+ * Story Engine Phase 5 — outcome of syncing a persona's character binding
773
+ * to the knowledge graph (the (Persona)-[:PORTRAYS]->(Entity) edge).
774
+ * Mirrors backend ``shared/models.py:GraphSyncStatus``. Derived per-request
775
+ * by the persona router after the graph write; never persisted to DynamoDB.
776
+ *
777
+ * - ``'synced'`` — ``entity_id`` is set and the graph write succeeded.
778
+ * - ``'pending'`` — ``entity_id`` is set but the graph write failed (logged;
779
+ * reconciliation is tracked as tech-debt).
780
+ * - ``'none'`` — ``entity_id`` is null (no binding).
781
+ */
782
+ export type GraphSyncStatus = 'synced' | 'pending' | 'none';
783
+
153
784
  export interface PersonaConfig {
154
785
  persona_id: string;
155
786
  user_id: string;
@@ -191,6 +822,37 @@ export interface PersonaConfig {
191
822
  status: 'pending' | 'approved';
192
823
  created_at: string;
193
824
  updated_at: string;
825
+ /** Phase 2: opt into live-vision frame attachment on chat turns. Default
826
+ * false. When true and the persona's ``chat_model_id`` supports the
827
+ * ``vision`` capability, the backend attaches the latest browser-side
828
+ * captured frame to each user message. */
829
+ vision_enabled?: boolean;
830
+ /** Phase 2: requested vision frame cadence in frames-per-second (0.5–3.0).
831
+ * Client-side preference for the publisher's encode rate; backend
832
+ * does not currently enforce this server-side (see specs/technical-debt.md
833
+ * Issue #161). */
834
+ vision_fps?: number;
835
+ /** Story Engine Phase 5: bound character Entity ID. When set, the backend
836
+ * auto-manages a (Persona)-[:PORTRAYS]->(Entity) graph edge. Accepted on
837
+ * create/update; snake_case on the wire (matches sibling fields). Always
838
+ * present on persona responses — serialized as ``null`` when no binding.
839
+ * Typed optional only as a defensive superset for older cached payloads. */
840
+ entity_id?: string | null;
841
+ /** Story Engine Phase 5: outcome of the most recent PORTRAYS sync. Derived
842
+ * per-request by the persona router; not persisted to DynamoDB. The backend
843
+ * field is required + defaulted to ``'none'``, so it is ALWAYS present on
844
+ * every persona response (``'none'`` when there is no binding) — never
845
+ * absent. Typed optional only as a defensive superset for older cached
846
+ * payloads; treat a missing value as ``'none'``. */
847
+ graph_sync_status?: GraphSyncStatus;
848
+ /** Story Engine Phase 8a (M9 Adventure Runtime): when true this persona may
849
+ * drive an interactive adventure as the Dungeon Master (it is accepted as the
850
+ * ``dmPersonaId`` for ``POST /api/v1/adventures``). Accepted on create/update;
851
+ * snake_case on the wire (matches sibling fields). The backend field is
852
+ * required + defaults to ``false``, so it is ALWAYS present on persona
853
+ * responses — typed optional only as a defensive superset for older cached
854
+ * payloads; treat a missing value as ``false``. */
855
+ is_dungeon_master?: boolean;
194
856
  }
195
857
 
196
858
  // Viseme bundle types — see services/persona/ and shared/viseme_bundle_models.py
@@ -355,6 +1017,13 @@ export interface RegenerateImageRequest {
355
1017
 
356
1018
  export interface RegenerateImageResponse {
357
1019
  traceId: string;
1020
+ /** Tracked `image_id` of the new `ImageRecord` the regeneration wrote.
1021
+ * `null`/absent when the S3 upload succeeded but the metadata write
1022
+ * didn't (best-effort tracking) — the caller still has
1023
+ * `imageUrl`/`imageS3Key` in that case. When present, the caller can
1024
+ * `getImage(imageId)` the new row to auto-select it (closes
1025
+ * tech-debt #110). */
1026
+ imageId?: string | null;
358
1027
  /** Presigned S3 URL for immediate display only. The URL has a short
359
1028
  * TTL (typically 1h) and will 403 once expired — persist `imageS3Key`
360
1029
  * if you need a stable handle and re-presign on read. */
@@ -441,6 +1110,18 @@ export interface CreatePersonaRequest {
441
1110
  prompt_addon_ids?: string[];
442
1111
  is_default?: boolean;
443
1112
  status?: 'pending' | 'approved';
1113
+ /** Phase 2: opt into live-vision frame attachment on chat turns. */
1114
+ vision_enabled?: boolean;
1115
+ /** Phase 2: requested vision frame cadence in fps (0.5–3.0). */
1116
+ vision_fps?: number;
1117
+ /** Story Engine Phase 5: bind this persona to a character Entity. The
1118
+ * backend creates a (Persona)-[:PORTRAYS]->(Entity) edge and returns
1119
+ * ``graph_sync_status`` on the response. */
1120
+ entity_id?: string | null;
1121
+ /** Story Engine Phase 8a (M9): mark this persona as a Dungeon Master so it
1122
+ * can drive interactive adventures. Optional; defaults to ``false``
1123
+ * server-side. snake_case on the wire (matches sibling fields). */
1124
+ is_dungeon_master?: boolean;
444
1125
  }
445
1126
 
446
1127
  export interface UpdatePersonaRequest {
@@ -469,6 +1150,19 @@ export interface UpdatePersonaRequest {
469
1150
  prompt_addon_ids?: string[] | null;
470
1151
  is_default?: boolean | null;
471
1152
  status?: 'pending' | 'approved';
1153
+ /** Phase 2: opt into / out of live-vision frame attachment. */
1154
+ vision_enabled?: boolean | null;
1155
+ /** Phase 2: vision frame cadence in fps (0.5–3.0). */
1156
+ vision_fps?: number | null;
1157
+ /** Story Engine Phase 5: change the persona↔character binding. Set to a
1158
+ * character Entity ID to (re)bind, or ``null`` to clear it. The backend
1159
+ * reconciles the (Persona)-[:PORTRAYS]->(Entity) edge and returns
1160
+ * ``graph_sync_status`` on the response. */
1161
+ entity_id?: string | null;
1162
+ /** Story Engine Phase 8a (M9): toggle Dungeon-Master capability. Optional;
1163
+ * ``null``/``undefined`` skips the field (no change). snake_case on the wire
1164
+ * (matches sibling fields). */
1165
+ is_dungeon_master?: boolean | null;
472
1166
  }
473
1167
 
474
1168
  export interface PersonaListResponse {
@@ -477,6 +1171,111 @@ export interface PersonaListResponse {
477
1171
  next_token?: string | null;
478
1172
  }
479
1173
 
1174
+ /**
1175
+ * Story Engine Phase 5 — a single character Entity for a video, as returned
1176
+ * by ``GET /api/v1/tools/videos/{videoId}/characters``. Mirrors the backend
1177
+ * ``api/tools/schemas.py:CharacterItem`` (camelCase wire fields). ``type`` is
1178
+ * always ``'character'`` because the endpoint surfaces only character Entities.
1179
+ */
1180
+ export interface CharacterItem {
1181
+ entityId: string;
1182
+ name: string;
1183
+ type: 'character';
1184
+ aliases: string[];
1185
+ }
1186
+
1187
+ /**
1188
+ * Story Engine Phase 5 — response of
1189
+ * ``GET /api/v1/tools/videos/{videoId}/characters``. Lists only ``Entity``
1190
+ * nodes with ``type === 'character'`` for the given video. Mirrors the
1191
+ * backend ``api/tools/schemas.py:CharacterListResponse``.
1192
+ */
1193
+ export interface CharacterListResponse {
1194
+ traceId: string;
1195
+ videoId: string;
1196
+ characters: CharacterItem[];
1197
+ }
1198
+
1199
+ /**
1200
+ * Platform Restructure R5a — one CharacterArc attached to a cast character.
1201
+ * Mirrors the backend ``api/tools/schemas.py:CastArc``.
1202
+ */
1203
+ export interface CastArc {
1204
+ arcId: string;
1205
+ /** Display title — the server falls back to the arc label, then arcId. */
1206
+ title: string;
1207
+ summary: string | null;
1208
+ index: number;
1209
+ }
1210
+
1211
+ /**
1212
+ * Platform Restructure R5c — one Scene featuring a cast character, with the
1213
+ * display ``title`` riding alongside the id (the studio character drawer
1214
+ * renders titles; pre-R5c they came from a client-side lookup over the full
1215
+ * graph payload). Mirrors the backend ``api/tools/schemas.py:CastScene``.
1216
+ */
1217
+ export interface CastScene {
1218
+ sceneId: string;
1219
+ /** Display title — the server falls back to the sceneId when untitled. */
1220
+ title: string;
1221
+ }
1222
+
1223
+ /**
1224
+ * Platform Restructure R5a/R5c — a character Entity as projected for the
1225
+ * studio Cast view. Carries everything the character drawer renders
1226
+ * (aliases/scenes/arcs/relatedCharacterIds), so the R5c CastGrid rewire is a
1227
+ * drop-in. Mirrors the backend ``api/tools/schemas.py:CastCharacter``. R5c
1228
+ * (the first consumer, shipped before this type was ever published) reshaped
1229
+ * R5a's ``sceneIds: string[]`` into ``scenes: CastScene[]``.
1230
+ */
1231
+ export interface CastCharacter {
1232
+ entityId: string;
1233
+ name: string;
1234
+ aliases: string[];
1235
+ scenes: CastScene[];
1236
+ arcs: CastArc[];
1237
+ /** RELATES_TO character neighbours, filtered to ids within this cast. */
1238
+ relatedCharacterIds: string[];
1239
+ }
1240
+
1241
+ /**
1242
+ * Platform Restructure R5a — display fields of the persona bound to a cast
1243
+ * character, hydrated server-side from the persona store (the binding is
1244
+ * resolved via the graph PORTRAYS edge + the authoritative
1245
+ * ``PersonaConfig.entity_id``, NOT by client-side string equality). camelCase
1246
+ * wire fields per the tools-API convention. Mirrors the backend
1247
+ * ``api/tools/schemas.py:CastPersonaSummary``.
1248
+ */
1249
+ export interface CastPersonaSummary {
1250
+ personaId: string;
1251
+ name: string;
1252
+ chatModelId: string;
1253
+ characterImageId: string | null;
1254
+ isDungeonMaster: boolean;
1255
+ }
1256
+
1257
+ /**
1258
+ * Platform Restructure R5a — one cast row: a character pre-joined to its
1259
+ * bound persona (``null`` when unbound). Mirrors the backend
1260
+ * ``api/tools/schemas.py:CastEntry``.
1261
+ */
1262
+ export interface CastEntry {
1263
+ character: CastCharacter;
1264
+ persona: CastPersonaSummary | null;
1265
+ }
1266
+
1267
+ /**
1268
+ * Platform Restructure R5a — response of
1269
+ * ``GET /api/v1/tools/videos/{videoId}/cast``: the one-call server-side
1270
+ * replacement for the studio CastGrid's two-call client-side ``entity_id``
1271
+ * join. Mirrors the backend ``api/tools/schemas.py:CastWithPersonaResponse``.
1272
+ */
1273
+ export interface CastWithPersonaResponse {
1274
+ traceId: string;
1275
+ videoId: string;
1276
+ cast: CastEntry[];
1277
+ }
1278
+
480
1279
  // Synthesis types matching backend api/personas/synthesize.py
481
1280
  export interface SynthesizedPersona {
482
1281
  name: string;
@@ -536,6 +1335,35 @@ export interface ChatWsTokenResponse {
536
1335
  expiresIn: number;
537
1336
  }
538
1337
 
1338
+ /**
1339
+ * Response from `POST /api/v1/chat/vision-rtc/credentials` — mirrors
1340
+ * the Pydantic `VisionRtcCredentialsResponse` on the backend. `mode`
1341
+ * tells the publisher whether to use the chat-WS signaling protocol
1342
+ * (`local`) or the KVS WebRTC SDK (`kvs`); the rest of the fields are
1343
+ * the connection-establishment material for the chosen mode.
1344
+ *
1345
+ * Re-exported as `VisionRtcCredentials` from
1346
+ * `@escapeaihq/client-core/vision` for convenience at the
1347
+ * `VisionPublisher` callsite.
1348
+ */
1349
+ export interface ChatVisionRtcCredentialsResponse {
1350
+ mode: 'local' | 'kvs';
1351
+ iceServers: Array<{
1352
+ urls: string[];
1353
+ username?: string | null;
1354
+ credential?: string | null;
1355
+ }>;
1356
+ signedSignalingUrl: string | null;
1357
+ channelArn: string | null;
1358
+ clientId: string | null;
1359
+ /** kvs mode only: AWS region for SigV4-signing follow-up ICE
1360
+ * candidate messages. Null in local mode. */
1361
+ region: string | null;
1362
+ expiresIn: number;
1363
+ /** Opaque request id for log correlation — matches chat-API logs. */
1364
+ traceId: string;
1365
+ }
1366
+
539
1367
  // Session types matching backend shared/persona_models.py
540
1368
  export interface SessionMessage {
541
1369
  role: string;
@@ -669,25 +1497,131 @@ export interface VideoGraphResponse {
669
1497
  edges: GraphEdge[];
670
1498
  }
671
1499
 
672
- export interface UpdateNodeRequest {
673
- nodeLabel: string;
674
- idProperty: string;
675
- idValue: string;
676
- properties: Record<string, unknown>;
1500
+ /**
1501
+ * Detail level for the video-graph read (Platform Restructure R5b). Mirrors
1502
+ * `shared/graph_schema.py`'s `GraphDetail` — the single source of the
1503
+ * `story`/`raw` mode literals (constants over bare strings; consumers compare
1504
+ * against `GRAPH_DETAIL.*`, never a raw literal).
1505
+ *
1506
+ * - `RAW` (the server default — omitting the `detail` arg keeps the request
1507
+ * byte-identical to the pre-R5b call): the full extraction subgraph.
1508
+ * - `STORY`: the curated story view — Acts, Scenes (each Scene node's
1509
+ * `properties` carries a read-time `shotCount`), the character cast,
1510
+ * document contributions, and narrative edges; Shot/DialogLine/Event nodes
1511
+ * and MENTIONS edges are collapsed server-side.
1512
+ */
1513
+ export const GRAPH_DETAIL = {
1514
+ STORY: 'story',
1515
+ RAW: 'raw',
1516
+ } as const;
1517
+
1518
+ export type GraphDetail = (typeof GRAPH_DETAIL)[keyof typeof GRAPH_DETAIL];
1519
+
1520
+ // ============= Creator Studio / Story types (M7 Phase 7 / Story Engine) =============
1521
+
1522
+ /**
1523
+ * Per-story aggregate counts surfaced on the Creator Studio overview. Derived
1524
+ * server-side from the existing graph + document readers (no new graph
1525
+ * machinery): acts/scenes/characters come from `GET /api/v1/tools/graph`
1526
+ * node labels (characters = `Entity` with `type === 'character'`), documents
1527
+ * from the P4 document store.
1528
+ */
1529
+ export interface StoryCounts {
1530
+ acts: number;
1531
+ scenes: number;
1532
+ characters: number;
1533
+ documents: number;
677
1534
  }
678
1535
 
679
- export interface UpdateNodeResponse {
680
- traceId: string;
681
- properties: Record<string, unknown>;
1536
+ /**
1537
+ * Summary item returned by `GET /api/v1/stories`. The Story resource is a
1538
+ * thin, read-only view over the existing Video — `storyId === videoId` (1:1)
1539
+ * in M7 P7. Both fields are present and equal so consumers can read whichever
1540
+ * they prefer; a future real-ULID Story milestone can diverge them without a
1541
+ * breaking shape change.
1542
+ */
1543
+ export interface StorySummary {
1544
+ storyId: string;
1545
+ videoId: string;
1546
+ title: string;
1547
+ updatedAt: string; // ISO 8601
1548
+ /** Always `null` in P7 (no poster source); reserved for future population. */
1549
+ posterUrl?: string | null;
682
1550
  }
683
1551
 
684
- export interface DeleteNodeRequest {
685
- nodeLabel: string;
686
- idProperty: string;
687
- idValue: string;
1552
+ /** Detail returned by `GET /api/v1/stories/{storyId}` — summary fields + counts. */
1553
+ export interface StoryDetail {
1554
+ storyId: string;
1555
+ videoId: string;
1556
+ title: string;
1557
+ updatedAt: string; // ISO 8601
1558
+ posterUrl?: string | null;
1559
+ counts: StoryCounts;
688
1560
  }
689
1561
 
690
- export interface DeleteNodeResponse {
1562
+ export interface ListStoriesResponse {
1563
+ traceId: string;
1564
+ stories: StorySummary[];
1565
+ }
1566
+
1567
+ export interface GetStoryResponse {
1568
+ traceId: string;
1569
+ story: StoryDetail;
1570
+ }
1571
+
1572
+ // ============= clip-lookup (existing tools endpoint; client binding) =========
1573
+
1574
+ /**
1575
+ * Request params for {@link ApiClient.clipLookup}. Mirrors the backend
1576
+ * `ClipLookupRequest` (`shared/tool_request_models.py`). `BaseSchema` has NO
1577
+ * alias generator and the model declares `videoId` literally (camelCase,
1578
+ * `# noqa: N815`), so the wire keys are camelCase verbatim — the client does
1579
+ * not remap.
1580
+ */
1581
+ export interface ClipLookupParams {
1582
+ videoId: string;
1583
+ /** Clip start time in seconds (>= 0). */
1584
+ t0: number;
1585
+ /** Clip end time in seconds (> 0). */
1586
+ t1: number;
1587
+ }
1588
+
1589
+ /**
1590
+ * Response from `POST /api/v1/tools/clip-lookup`. Mirrors the backend
1591
+ * `ClipLookupResponse` (`api/tools/schemas.py`) — camelCase keys verbatim.
1592
+ * `url` is a presigned (or local-stub) playable URL for the [t0,t1] span;
1593
+ * `citation` carries the time-coded span.
1594
+ */
1595
+ export interface ClipLookupResponse {
1596
+ traceId: string;
1597
+ url: string;
1598
+ expiresIn: number;
1599
+ citation: { videoId: string; t0: number; t1: number; shotId?: string | null };
1600
+ source: { system: string; details?: Record<string, unknown> | null };
1601
+ }
1602
+
1603
+ export interface UpdateNodeRequest {
1604
+ nodeLabel: string;
1605
+ // NOTE: no `idProperty` — the backend derives the primary key from
1606
+ // `shared/graph_schema.py:PRIMARY_KEY[nodeLabel]` (M7 P1a, closes tech-debt
1607
+ // #44). Callers pass only the label + id value.
1608
+ idValue: string;
1609
+ properties: Record<string, unknown>;
1610
+ }
1611
+
1612
+ export interface UpdateNodeResponse {
1613
+ traceId: string;
1614
+ properties: Record<string, unknown>;
1615
+ }
1616
+
1617
+ export interface DeleteNodeRequest {
1618
+ nodeLabel: string;
1619
+ // NOTE: no `idProperty` (backend derives the PK). DELETE node is sent as
1620
+ // query params, not a JSON body (M7 P1a, closes tech-debt #42/#44).
1621
+ idValue: string;
1622
+ }
1623
+
1624
+ export interface DeleteNodeResponse {
691
1625
  traceId: string;
692
1626
  deleted: number;
693
1627
  }
@@ -715,6 +1649,78 @@ export interface DeleteRelationshipResponse {
715
1649
  deleted: number;
716
1650
  }
717
1651
 
1652
+ /**
1653
+ * Per-label schema entry returned by `GET /api/v1/tools/graph/schema`.
1654
+ * `pk` is the primary-key property name; `editable` is the user-editable
1655
+ * property whitelist. Both are derived server-side from the canonical
1656
+ * `shared/graph_schema.py` single source of truth.
1657
+ */
1658
+ export interface GraphLabelSchema {
1659
+ pk: string;
1660
+ editable: string[];
1661
+ }
1662
+
1663
+ /** Per-relationship-type schema entry: the editable property whitelist. */
1664
+ export interface GraphEdgeSchema {
1665
+ editable: string[];
1666
+ }
1667
+
1668
+ /**
1669
+ * Response from `GET /api/v1/tools/graph/schema` (M7 P1a). The live wire copy
1670
+ * of the graph whitelists — lets the web/ `PropertyPanel` drop its
1671
+ * hand-maintained mirror (tech-debt #45) and consume the same vocabulary the
1672
+ * backend validates against. No auth required (pure metadata).
1673
+ */
1674
+ export interface GraphSchemaResponse {
1675
+ traceId: string;
1676
+ labels: Record<string, GraphLabelSchema>;
1677
+ edges: Record<string, GraphEdgeSchema>;
1678
+ }
1679
+
1680
+ /**
1681
+ * Body for `POST /api/v1/tools/graph/nodes` (M7 P3a). Creates a user-authored
1682
+ * narrative node (Scene / PlotBeat / CharacterArc — see {@link userCreatableLabels}
1683
+ * in `graphSchema.ts`). `videoId` IS a legitimate field here: the node does not
1684
+ * exist yet, so ownership is asserted directly from `videoId` (the documented
1685
+ * POST-carries-videoId exception to derive-ownership-from-object). The backend
1686
+ * stamps `provenance='user'`, `versionId`, and `createdAt`/`updatedAt`.
1687
+ */
1688
+ export interface CreateNodeRequest {
1689
+ videoId: string;
1690
+ label: string;
1691
+ properties: Record<string, unknown>;
1692
+ }
1693
+
1694
+ /** 201 response from `POST /api/v1/tools/graph/nodes` (composite `nodeId`). */
1695
+ export interface CreateNodeResponse {
1696
+ traceId: string;
1697
+ nodeId: string;
1698
+ properties: Record<string, unknown>;
1699
+ }
1700
+
1701
+ /**
1702
+ * Body for `POST /api/v1/tools/graph/edges` (M7 P3a). Creates a user-authored
1703
+ * relationship (one of {@link userCreatableEdges}). `sourceId`/`targetId` are
1704
+ * composite ids (`Label:pk:value`); both endpoints must belong to `videoId`.
1705
+ * `type` must be a user-creatable edge whose `(sourceLabel, targetLabel)` pair
1706
+ * is in {@link allowedPairs}; `properties` carries edge-specific fields (e.g.
1707
+ * `kind` for RELATES_TO, `confidence` for FEATURES, `condition` for LEADS_TO).
1708
+ */
1709
+ export interface CreateEdgeRequest {
1710
+ videoId: string;
1711
+ sourceId: string;
1712
+ targetId: string;
1713
+ type: string;
1714
+ properties?: Record<string, unknown>;
1715
+ }
1716
+
1717
+ /** 201 response from `POST /api/v1/tools/graph/edges` (composite `edgeId`). */
1718
+ export interface CreateEdgeResponse {
1719
+ traceId: string;
1720
+ edgeId: string;
1721
+ properties: Record<string, unknown>;
1722
+ }
1723
+
718
1724
  // ==================== Reactor / Helios types ====================
719
1725
 
720
1726
  /**
@@ -747,6 +1753,15 @@ export interface UpsampleReactorPromptRequest {
747
1753
  entityContext?: ReactorEntityContext;
748
1754
  /** Persona grounding (name + truncated backstory). */
749
1755
  personaContext?: ReactorPersonaContext;
1756
+ /**
1757
+ * Optional chat-model id to run the upsample on (R8.3). When set, it MUST be
1758
+ * one the backend chat router knows (`shared/model_config.py` — the same set
1759
+ * `GET /api/v1/chat/models` lists); an unknown id is rejected with a 422.
1760
+ * Omitted ⇒ the backend's configured default upsample model — so existing
1761
+ * callers keep their behavior (additive-only). The Director surfaces this via
1762
+ * the R1 CHAT adapter picker so the steering LLM is operator-swappable.
1763
+ */
1764
+ model?: string;
750
1765
  }
751
1766
 
752
1767
  export interface UpsampleReactorPromptResponse {
@@ -754,18 +1769,122 @@ export interface UpsampleReactorPromptResponse {
754
1769
  upsampledPrompt: string;
755
1770
  }
756
1771
 
1772
+ // ============= Adventure Runtime types (M9 Story Engine Phase 8a) =============
1773
+
1774
+ /**
1775
+ * One entry in an adventure's turn log. Mirrors
1776
+ * `shared/adventure_models.py::TurnRecord` — the backend serializes it
1777
+ * camelCase (`{turn, beatId, summary}`) inside {@link AdventureState.turnHistory}.
1778
+ * `turn` is 1-based and monotonically increasing; the backend keeps only the
1779
+ * last `TURN_HISTORY_MAX_ENTRIES` (30) records.
1780
+ */
1781
+ export interface TurnRecord {
1782
+ turn: number;
1783
+ beatId: string;
1784
+ summary: string;
1785
+ }
1786
+
1787
+ /**
1788
+ * Server-authoritative state for an in-progress interactive adventure. Mirrors
1789
+ * `shared/adventure_models.py::AdventureState` (a camelCase-on-the-wire pydantic
1790
+ * model). Returned by `POST /api/v1/adventures` and `GET
1791
+ * /api/v1/adventures/{sessionId}`. The Dungeon-Master persona mutates this via
1792
+ * the `/api/v1/tools/adventure/*` endpoints; the runtime threads `sessionId`
1793
+ * into chat turns so the DM tools resolve the active adventure.
1794
+ */
1795
+ export interface AdventureState {
1796
+ sessionId: string;
1797
+ ownerUserId: string;
1798
+ storyId: string;
1799
+ videoId: string;
1800
+ dmPersonaId: string;
1801
+ partyPersonaIds: string[];
1802
+ /** Current PlotBeat id. `null` before the first `advance_story` move. */
1803
+ currentBeatId?: string | null;
1804
+ visitedBeatIds: string[];
1805
+ flags: Record<string, string>;
1806
+ inventory: string[];
1807
+ turnHistory: TurnRecord[];
1808
+ createdAt: string;
1809
+ updatedAt: string;
1810
+ }
1811
+
1812
+ /**
1813
+ * Request body for `POST /api/v1/adventures` (start an adventure). Mirrors the
1814
+ * backend `api/adventures/schemas.py::StartAdventureRequest` (`extra="forbid"`,
1815
+ * camelCase keys verbatim). `dmPersonaId` MUST reference a persona whose
1816
+ * `is_dungeon_master` is true (the backend 422s otherwise). `initialBeatId`
1817
+ * optionally seeds the starting PlotBeat; omit to start before any beat.
1818
+ */
1819
+ export interface StartAdventureRequest {
1820
+ storyId: string;
1821
+ videoId: string;
1822
+ dmPersonaId: string;
1823
+ initialBeatId?: string | null;
1824
+ /**
1825
+ * Initial party of character personas for a multi-persona adventure (M10
1826
+ * Story Engine Phase 9a). Each id must reference an owned persona that is
1827
+ * bound to a character entity and is NOT a Dungeon Master (the backend 422s
1828
+ * otherwise). Optional; omit / `[]` for an M9 single-DM adventure — the wire
1829
+ * stays unchanged (land-dark). Mirrors the additive `partyPersonaIds` field
1830
+ * on the backend `StartAdventureRequest`.
1831
+ */
1832
+ partyPersonaIds?: string[];
1833
+ }
1834
+
1835
+ /**
1836
+ * The two `action` values accepted by `PATCH /api/v1/adventures/{sessionId}/party`
1837
+ * (M10 Story Engine Phase 9a). `add` appends a character persona to the party
1838
+ * (validated + deduped server-side); `remove` is an idempotent no-op when the
1839
+ * persona is absent. Named constant so call sites never hard-code the literals.
1840
+ */
1841
+ export const PARTY_ACTION = {
1842
+ ADD: 'add',
1843
+ REMOVE: 'remove',
1844
+ } as const;
1845
+
1846
+ /** Union of the {@link PARTY_ACTION} values. */
1847
+ export type PartyAction = (typeof PARTY_ACTION)[keyof typeof PARTY_ACTION];
1848
+
1849
+ /**
1850
+ * Request body for `PATCH /api/v1/adventures/{sessionId}/party` (M10 Story
1851
+ * Engine Phase 9a). Mirrors the backend `PartyUpdateRequest` (`extra="forbid"`,
1852
+ * camelCase keys verbatim). The PATCH returns the updated
1853
+ * {@link GetAdventureResponse} (the same 200 shape as `GET adventure`).
1854
+ */
1855
+ export interface PartyUpdateRequest {
1856
+ action: PartyAction;
1857
+ personaId: string;
1858
+ }
1859
+
757
1860
  /**
758
- * Detect an abort (controller.abort(), unmount, signal expiry) so callers
759
- * can stay silent on expected cancellations while still surfacing real
760
- * fetch errors (5xx / timeout / CORS). Native `fetch` rejects with a
761
- * `DOMException { name: 'AbortError' }`; the project's own pollers throw
762
- * the same shape; a polyfilled fetch may throw a plain `Error` with the
763
- * same name. Accept both so the warn-suppression survives a future
764
- * polyfill or SSR runtime swap.
1861
+ * 201 response from `POST /api/v1/adventures`. Mirrors the backend
1862
+ * `AdventureResponse` — carries the new `sessionId` (also in `state.sessionId`)
1863
+ * plus the full initial {@link AdventureState}. The `Location` header points at
1864
+ * `/api/v1/adventures/{sessionId}`.
765
1865
  */
766
- function isAbortError(err: unknown): boolean {
767
- if (err instanceof DOMException && err.name === 'AbortError') return true;
768
- return err instanceof Error && err.name === 'AbortError';
1866
+ export interface AdventureResponse {
1867
+ traceId: string;
1868
+ sessionId: string;
1869
+ state: AdventureState;
1870
+ }
1871
+
1872
+ /** `GET /api/v1/adventures/{sessionId}` — mirrors the backend `GetAdventureResponse`. */
1873
+ export interface GetAdventureResponse {
1874
+ traceId: string;
1875
+ state: AdventureState;
1876
+ }
1877
+
1878
+ /**
1879
+ * `GET /api/v1/adventures` — mirrors the backend `ListAdventuresResponse`.
1880
+ * Owner-scoped list of the caller's adventures (soft-deleted ones excluded),
1881
+ * newest-first by `createdAt`, optionally narrowed to a single `storyId`. Each
1882
+ * entry is the same camelCase {@link AdventureState} returned by
1883
+ * `GET /api/v1/adventures/{sessionId}`.
1884
+ */
1885
+ export interface ListAdventuresResponse {
1886
+ traceId: string;
1887
+ adventures: AdventureState[];
769
1888
  }
770
1889
 
771
1890
  export class ApiClient {
@@ -802,51 +1921,10 @@ export class ApiClient {
802
1921
  endpoint: string,
803
1922
  options: RequestInit = {}
804
1923
  ): Promise<T> {
805
- const url = `${baseUrl}${endpoint}`;
806
-
807
- const headers: Record<string, string> = {
808
- 'Content-Type': 'application/json',
809
- ...options.headers as Record<string, string>,
810
- };
811
-
812
- // Add authorization header if session token is available
813
- if (this.sessionToken) {
814
- headers['Authorization'] = `Bearer ${this.sessionToken}`;
815
- }
816
-
817
- try {
818
- const response = await fetch(url, {
819
- ...options,
820
- headers,
821
- });
822
-
823
- if (!response.ok) {
824
- const error: ApiError = await response.json().catch(() => ({
825
- detail: `HTTP ${response.status}: ${response.statusText}`,
826
- }));
827
- // FastAPI 422 returns detail as an array of validation errors
828
- const detail = error.detail;
829
- let message: string;
830
- if (Array.isArray(detail)) {
831
- message = detail.map((e: { msg?: string; loc?: string[] }) =>
832
- e.msg ? `${(e.loc || []).slice(-1).join('.')}: ${e.msg}` : String(e)
833
- ).join('; ');
834
- } else {
835
- message = detail || `Request failed: ${response.status}`;
836
- }
837
- throw new Error(message);
838
- }
839
-
840
- // 204 No Content returns no body
841
- if (response.status === 204) {
842
- return undefined as T;
843
- }
844
-
845
- return await response.json();
846
- } catch (error) {
847
- console.error('API request failed:', error);
848
- throw error;
849
- }
1924
+ // Delegates to the shared `requestJson` helper (bearer auth + FastAPI error
1925
+ // shaping) so `ApiClient` and the additive `AdminClient` share one fetch
1926
+ // wrapper — behavior is identical to the prior inline implementation.
1927
+ return requestJson<T>(baseUrl, endpoint, this.sessionToken, options);
850
1928
  }
851
1929
 
852
1930
  /**
@@ -892,6 +1970,33 @@ export class ApiClient {
892
1970
  return this.request<ListJobsResponse>(endpoint);
893
1971
  }
894
1972
 
1973
+ /**
1974
+ * Story Engine Phase 5 — list character entities for a video. Backs the
1975
+ * persona↔character binding selector. Returns only ``Entity`` nodes with
1976
+ * ``type === 'character'`` for the given video. Auth + video ownership are
1977
+ * enforced server-side (caller must own the video). Uses the main API base
1978
+ * (the tools routes use ``request``, not ``chatRequest``).
1979
+ */
1980
+ async listVideoCharacters(videoId: string): Promise<CharacterListResponse> {
1981
+ return this.request<CharacterListResponse>(
1982
+ `/api/v1/tools/videos/${encodeURIComponent(videoId)}/characters`,
1983
+ );
1984
+ }
1985
+
1986
+ /**
1987
+ * Platform Restructure R5a — fetch a video's character cast pre-joined to
1988
+ * each character's bound persona in ONE round-trip (the server resolves the
1989
+ * PORTRAYS binding + hydrates persona display fields). The one-call
1990
+ * replacement for the CastGrid's `getVideoGraph` + `listPersonas` client-side
1991
+ * `entity_id` join (the R5c rewire consumes this). Auth + video ownership are
1992
+ * enforced server-side. Tools API base (`request`, not `chatRequest`).
1993
+ */
1994
+ async getCast(videoId: string): Promise<CastWithPersonaResponse> {
1995
+ return this.request<CastWithPersonaResponse>(
1996
+ `/api/v1/tools/videos/${encodeURIComponent(videoId)}/cast`,
1997
+ );
1998
+ }
1999
+
895
2000
  /**
896
2001
  * List staged videos in the ingestion bucket
897
2002
  */
@@ -905,20 +2010,267 @@ export class ApiClient {
905
2010
  if (params?.pageSize) searchParams.append('pageSize', params.pageSize.toString());
906
2011
  if (params?.continuationToken) searchParams.append('continuationToken', params.continuationToken);
907
2012
 
908
- const query = searchParams.toString();
909
- const endpoint = `/api/v1/ingestion/videos${query ? `?${query}` : ''}`;
2013
+ const query = searchParams.toString();
2014
+ const endpoint = `/api/v1/ingestion/videos${query ? `?${query}` : ''}`;
2015
+
2016
+ return this.request<ListVideosResponse>(endpoint);
2017
+ }
2018
+
2019
+ /**
2020
+ * Upload a video file with progress tracking
2021
+ */
2022
+ async uploadVideo(
2023
+ file: File,
2024
+ onProgress?: UploadProgressCallback,
2025
+ ): Promise<UploadResponse> {
2026
+ const url = `${this.baseURL}/api/v1/ingestion/uploads`;
2027
+
2028
+ return new Promise((resolve, reject) => {
2029
+ const xhr = new XMLHttpRequest();
2030
+
2031
+ // Track upload progress
2032
+ if (onProgress) {
2033
+ xhr.upload.addEventListener('progress', (e) => {
2034
+ if (e.lengthComputable) {
2035
+ onProgress({
2036
+ loaded: e.loaded,
2037
+ total: e.total,
2038
+ percentage: Math.round((e.loaded / e.total) * 100),
2039
+ });
2040
+ }
2041
+ });
2042
+ }
2043
+
2044
+ // Handle completion
2045
+ xhr.addEventListener('load', () => {
2046
+ if (xhr.status >= 200 && xhr.status < 300) {
2047
+ try {
2048
+ const response = JSON.parse(xhr.responseText);
2049
+ resolve(response);
2050
+ } catch {
2051
+ reject(new Error('Failed to parse upload response'));
2052
+ }
2053
+ } else {
2054
+ try {
2055
+ const errorData = JSON.parse(xhr.responseText);
2056
+ reject(new Error(errorData.detail || `Upload failed: ${xhr.status}`));
2057
+ } catch {
2058
+ reject(new Error(`Upload failed: ${xhr.status} ${xhr.statusText}`));
2059
+ }
2060
+ }
2061
+ });
2062
+
2063
+ // Handle errors
2064
+ xhr.addEventListener('error', () => {
2065
+ reject(new Error('Upload failed due to network error'));
2066
+ });
2067
+
2068
+ xhr.addEventListener('abort', () => {
2069
+ reject(new Error('Upload aborted'));
2070
+ });
2071
+
2072
+ // Prepare form data
2073
+ const formData = new FormData();
2074
+ formData.append('upload', file);
2075
+
2076
+ const payload = {
2077
+ subdirectory: 'web-uploads',
2078
+ source: {
2079
+ type: 'direct',
2080
+ filename: file.name,
2081
+ contentType: file.type,
2082
+ },
2083
+ };
2084
+
2085
+ formData.append('payload', JSON.stringify(payload));
2086
+
2087
+ // Send request
2088
+ xhr.open('POST', url);
2089
+
2090
+ // Add authorization header if session token is available
2091
+ if (this.sessionToken) {
2092
+ xhr.setRequestHeader('Authorization', `Bearer ${this.sessionToken}`);
2093
+ }
2094
+
2095
+ xhr.send(formData);
2096
+ });
2097
+ }
2098
+
2099
+ // ==================== Enrichment API Methods ====================
2100
+
2101
+ /**
2102
+ * Trigger Pegasus enrichment analysis on an ingested video
2103
+ */
2104
+ async enrichVideo(videoId: string, config?: PegasusConfig): Promise<EnrichVideoResponse> {
2105
+ return this.request<EnrichVideoResponse>(`/api/v1/ingestion/videos/${videoId}/enrichments`, {
2106
+ method: 'POST',
2107
+ body: JSON.stringify({
2108
+ pegasusPrompt: config?.pegasusPrompt,
2109
+ pegasusTemperature: config?.pegasusTemperature,
2110
+ pegasusMaxTokens: config?.pegasusMaxTokens,
2111
+ }),
2112
+ });
2113
+ }
2114
+
2115
+ /**
2116
+ * List all enrichment runs for a video
2117
+ */
2118
+ async getEnrichments(videoId: string): Promise<ListEnrichmentsResponse> {
2119
+ return this.request<ListEnrichmentsResponse>(`/api/v1/ingestion/videos/${videoId}/enrichments`);
2120
+ }
2121
+
2122
+ /**
2123
+ * Get a specific enrichment result
2124
+ */
2125
+ async getEnrichment(enrichmentId: string): Promise<EnrichmentRecord> {
2126
+ return this.request<EnrichmentRecord>(`/api/v1/ingestion/enrichments/${enrichmentId}`);
2127
+ }
2128
+
2129
+ /**
2130
+ * Delete a video and all associated data across all systems
2131
+ */
2132
+ async deleteVideo(videoId: string, s3Key?: string): Promise<VideoDeletionResponse> {
2133
+ const searchParams = new URLSearchParams();
2134
+ if (s3Key) searchParams.append('s3Key', s3Key);
2135
+
2136
+ const query = searchParams.toString();
2137
+ const endpoint = `/api/v1/ingestion/videos/${videoId}${query ? `?${query}` : ''}`;
2138
+
2139
+ return this.request<VideoDeletionResponse>(endpoint, {
2140
+ method: 'DELETE',
2141
+ });
2142
+ }
2143
+
2144
+ // ============= Narrative Regeneration API (M7 Phase 6 / Story Engine) =============
2145
+
2146
+ /**
2147
+ * Start an async narrative regeneration run for a video scope.
2148
+ * `POST /api/v1/tools/graph/{videoId}/regenerate` → 202 with the QUEUED run
2149
+ * (and a `Location` header to the run's poll URL, exposed as `statusUrl`).
2150
+ *
2151
+ * Auth + ownership are enforced server-side. A malformed `scope` is a 422,
2152
+ * an in-flight run is a 409, over-cap is a 429 — all surface as a thrown
2153
+ * `Error` carrying the FastAPI detail. Build `request.scope` with
2154
+ * {@link buildRegenerationScope}. Pair with {@link pollRegenerationUntilDone}.
2155
+ */
2156
+ async startRegeneration(
2157
+ videoId: string,
2158
+ request: RegenerateRequest,
2159
+ ): Promise<RegenerationRunResponse> {
2160
+ return this.request<RegenerationRunResponse>(
2161
+ `/api/v1/tools/graph/${encodeURIComponent(videoId)}/regenerate`,
2162
+ {
2163
+ method: 'POST',
2164
+ body: JSON.stringify(request),
2165
+ },
2166
+ );
2167
+ }
2168
+
2169
+ /**
2170
+ * List a video's regeneration runs, newest-first.
2171
+ * `GET /api/v1/tools/graph/{videoId}/regenerations`. `limit` (1–100) and
2172
+ * `cursor` (opaque pagination token from a prior `nextCursor`) are optional.
2173
+ */
2174
+ async listRegenerations(
2175
+ videoId: string,
2176
+ params?: { limit?: number; cursor?: string },
2177
+ ): Promise<RegenerationListResponse> {
2178
+ const searchParams = new URLSearchParams();
2179
+ if (params?.limit != null) searchParams.append('limit', params.limit.toString());
2180
+ if (params?.cursor) searchParams.append('cursor', params.cursor);
2181
+
2182
+ const query = searchParams.toString();
2183
+ const endpoint = `/api/v1/tools/graph/${encodeURIComponent(videoId)}/regenerations${
2184
+ query ? `?${query}` : ''
2185
+ }`;
2186
+ return this.request<RegenerationListResponse>(endpoint);
2187
+ }
2188
+
2189
+ /**
2190
+ * Fetch a single regeneration run by id.
2191
+ * `GET /api/v1/tools/graph/{videoId}/regenerations/{runId}` (404 if absent).
2192
+ * `signal` aborts the in-flight fetch — {@link pollRegenerationUntilDone}
2193
+ * threads its poll signal through so a page unmount cancels cleanly.
2194
+ */
2195
+ async getRegeneration(
2196
+ videoId: string,
2197
+ runId: string,
2198
+ options: { signal?: AbortSignal } = {},
2199
+ ): Promise<RegenerationRunResponse> {
2200
+ return this.request<RegenerationRunResponse>(
2201
+ `/api/v1/tools/graph/${encodeURIComponent(videoId)}/regenerations/${encodeURIComponent(
2202
+ runId,
2203
+ )}`,
2204
+ { signal: options.signal },
2205
+ );
2206
+ }
910
2207
 
911
- return this.request<ListVideosResponse>(endpoint);
2208
+ /**
2209
+ * Poll {@link getRegeneration} until the run reaches a terminal status.
2210
+ * COMPLETE / CANCELLED resolve with the final run; FAILED throws
2211
+ * (`record.error` ?? a generic message). Mirrors
2212
+ * {@link pollVisemeBundleUntilDone}: 5s cadence, abortable via `signal`,
2213
+ * and a wall-clock timeout (regeneration re-invokes Pegasus, so the default
2214
+ * matches bundle assembly — generous but bounded).
2215
+ */
2216
+ async pollRegenerationUntilDone(
2217
+ videoId: string,
2218
+ runId: string,
2219
+ options: {
2220
+ intervalMs?: number;
2221
+ timeoutMs?: number;
2222
+ signal?: AbortSignal;
2223
+ } = {},
2224
+ ): Promise<RegenerationRunResponse> {
2225
+ const intervalMs = options.intervalMs ?? 5000;
2226
+ // The regenerator Lambda can run up to its 15-min cap (an `acts` scope re-runs
2227
+ // Pegasus over the whole film), so the default poll deadline must exceed that or
2228
+ // the client gives up while the run is still completing. 16 min covers a normal
2229
+ // single run; if the poll still times out (e.g. an SQS redelivery), the run row
2230
+ // is durable — a refresh / re-fetch surfaces the terminal state.
2231
+ const timeoutMs = options.timeoutMs ?? 960_000;
2232
+ const deadline = Date.now() + timeoutMs;
2233
+ while (true) {
2234
+ if (options.signal?.aborted) {
2235
+ throw new DOMException('Polling aborted', 'AbortError');
2236
+ }
2237
+ const record = await this.getRegeneration(videoId, runId, {
2238
+ signal: options.signal,
2239
+ });
2240
+ if (
2241
+ record.status === REGENERATION_STATUS.COMPLETE ||
2242
+ record.status === REGENERATION_STATUS.CANCELLED
2243
+ ) {
2244
+ return record;
2245
+ }
2246
+ if (record.status === REGENERATION_STATUS.FAILED) {
2247
+ throw new Error(record.error ?? 'Regeneration failed');
2248
+ }
2249
+ if (Date.now() >= deadline) {
2250
+ throw new Error(
2251
+ `Regeneration timed out after ${Math.round(timeoutMs / 1000)}s`,
2252
+ );
2253
+ }
2254
+ await abortableSleep(intervalMs, options.signal);
2255
+ }
912
2256
  }
913
2257
 
2258
+ // ==================== Source Document API (M7 Phase 4) ====================
2259
+
914
2260
  /**
915
- * Upload a video file with progress tracking
2261
+ * Upload a source document (script / notes / bible / transcript) with
2262
+ * progress tracking. Mirrors {@link uploadVideo}: multipart XHR so the
2263
+ * browser reports upload progress (fetch cannot). The `meta` fields ride
2264
+ * alongside the file as a JSON `payload` part. Returns 201 with
2265
+ * `{ traceId, docId, statusUrl }`; the backend enqueues
2266
+ * `document-processing-queue` to parse + extract suggestions.
916
2267
  */
917
- async uploadVideo(
2268
+ async uploadDocument(
918
2269
  file: File,
2270
+ meta: UploadDocumentMeta,
919
2271
  onProgress?: UploadProgressCallback,
920
- ): Promise<UploadResponse> {
921
- const url = `${this.baseURL}/api/v1/ingestion/uploads`;
2272
+ ): Promise<UploadDocumentResponse> {
2273
+ const url = `${this.baseURL}/api/v1/ingestion/documents`;
922
2274
 
923
2275
  return new Promise((resolve, reject) => {
924
2276
  const xhr = new XMLHttpRequest();
@@ -964,20 +2316,10 @@ export class ApiClient {
964
2316
  reject(new Error('Upload aborted'));
965
2317
  });
966
2318
 
967
- // Prepare form data
2319
+ // Prepare form data — file part + JSON metadata part.
968
2320
  const formData = new FormData();
969
2321
  formData.append('upload', file);
970
-
971
- const payload = {
972
- subdirectory: 'web-uploads',
973
- source: {
974
- type: 'direct',
975
- filename: file.name,
976
- contentType: file.type,
977
- },
978
- };
979
-
980
- formData.append('payload', JSON.stringify(payload));
2322
+ formData.append('payload', JSON.stringify(meta));
981
2323
 
982
2324
  // Send request
983
2325
  xhr.open('POST', url);
@@ -991,61 +2333,93 @@ export class ApiClient {
991
2333
  });
992
2334
  }
993
2335
 
994
- // ==================== Enrichment API Methods ====================
995
-
996
2336
  /**
997
- * Trigger Pegasus enrichment analysis on an ingested video
2337
+ * List source documents, optionally scoped to a video or series. Mirrors
2338
+ * {@link listJobs} query-param handling. GET `/api/v1/ingestion/documents`.
998
2339
  */
999
- async enrichVideo(videoId: string, config?: PegasusConfig): Promise<EnrichVideoResponse> {
1000
- return this.request<EnrichVideoResponse>(`/api/v1/ingestion/videos/${videoId}/enrichments`, {
1001
- method: 'POST',
1002
- body: JSON.stringify({
1003
- pegasusPrompt: config?.pegasusPrompt,
1004
- pegasusTemperature: config?.pegasusTemperature,
1005
- pegasusMaxTokens: config?.pegasusMaxTokens,
1006
- }),
1007
- });
2340
+ async listDocuments(params?: {
2341
+ videoId?: string;
2342
+ seriesId?: string;
2343
+ limit?: number;
2344
+ nextToken?: string;
2345
+ }): Promise<ListDocumentsResponse> {
2346
+ const searchParams = new URLSearchParams();
2347
+ if (params?.videoId) searchParams.append('videoId', params.videoId);
2348
+ if (params?.seriesId) searchParams.append('seriesId', params.seriesId);
2349
+ if (params?.limit) searchParams.append('limit', params.limit.toString());
2350
+ if (params?.nextToken) searchParams.append('nextToken', params.nextToken);
2351
+
2352
+ const query = searchParams.toString();
2353
+ const endpoint = `/api/v1/ingestion/documents${query ? `?${query}` : ''}`;
2354
+
2355
+ return this.request<ListDocumentsResponse>(endpoint);
1008
2356
  }
1009
2357
 
1010
2358
  /**
1011
- * List all enrichment runs for a video
2359
+ * Fetch a single document plus its pending/resolved graph suggestions.
2360
+ * GET `/api/v1/ingestion/documents/{docId}`.
1012
2361
  */
1013
- async getEnrichments(videoId: string): Promise<ListEnrichmentsResponse> {
1014
- return this.request<ListEnrichmentsResponse>(`/api/v1/ingestion/videos/${videoId}/enrichments`);
2362
+ async getDocument(docId: string): Promise<GetDocumentResponse> {
2363
+ return this.request<GetDocumentResponse>(`/api/v1/ingestion/documents/${docId}`);
1015
2364
  }
1016
2365
 
1017
2366
  /**
1018
- * Get a specific enrichment result
2367
+ * Accept a pipeline-extracted graph suggestion — writes the proposed
2368
+ * node/edge with provenance `document`. POST returns 201 with
2369
+ * `{ traceId, suggestionId, graphId }` (`graphId` is the composite id of the
2370
+ * created node/edge); a 422 (e.g. already resolved, or the payload fails
2371
+ * graph validation) surfaces the FastAPI detail as a thrown `Error`. POST
2372
+ * `.../documents/{docId}/suggestions/{sid}/accept`.
1019
2373
  */
1020
- async getEnrichment(enrichmentId: string): Promise<EnrichmentRecord> {
1021
- return this.request<EnrichmentRecord>(`/api/v1/ingestion/enrichments/${enrichmentId}`);
2374
+ async acceptSuggestion(
2375
+ docId: string,
2376
+ suggestionId: string,
2377
+ ): Promise<AcceptSuggestionResponse> {
2378
+ return this.request<AcceptSuggestionResponse>(
2379
+ `/api/v1/ingestion/documents/${docId}/suggestions/${suggestionId}/accept`,
2380
+ { method: 'POST' },
2381
+ );
1022
2382
  }
1023
2383
 
1024
2384
  /**
1025
- * Delete a video and all associated data across all systems
2385
+ * Reject a pipeline-extracted graph suggestion (marks it `rejected`, writes
2386
+ * nothing to the graph). Returns 204 (no body). POST
2387
+ * `.../documents/{docId}/suggestions/{sid}/reject`.
1026
2388
  */
1027
- async deleteVideo(videoId: string, s3Key?: string): Promise<VideoDeletionResponse> {
1028
- const searchParams = new URLSearchParams();
1029
- if (s3Key) searchParams.append('s3Key', s3Key);
1030
-
1031
- const query = searchParams.toString();
1032
- const endpoint = `/api/v1/ingestion/videos/${videoId}${query ? `?${query}` : ''}`;
2389
+ async rejectSuggestion(docId: string, suggestionId: string): Promise<void> {
2390
+ return this.request<void>(
2391
+ `/api/v1/ingestion/documents/${docId}/suggestions/${suggestionId}/reject`,
2392
+ { method: 'POST' },
2393
+ );
2394
+ }
1033
2395
 
1034
- return this.request<VideoDeletionResponse>(endpoint, {
2396
+ /**
2397
+ * Delete a source document and its associated data. Returns 204 (no body).
2398
+ * DELETE `/api/v1/ingestion/documents/{docId}`.
2399
+ */
2400
+ async deleteDocument(docId: string): Promise<void> {
2401
+ return this.request<void>(`/api/v1/ingestion/documents/${docId}`, {
1035
2402
  method: 'DELETE',
1036
2403
  });
1037
2404
  }
1038
2405
 
1039
2406
  /**
1040
- * Stream chat responses with Server-Sent Events
1041
- * Returns a ReadableStreamDefaultReader for processing SSE events
2407
+ * Shared SSE body-reader for the chat + assistant stream endpoints.
2408
+ * POSTs the JSON `body` to `url` (with the auth header when a session
2409
+ * token is set) and returns the response's `ReadableStreamDefaultReader`
2410
+ * for the caller to decode. `streamChat` and `streamAssistant` differ
2411
+ * ONLY by URL + body, so they both route through here — there is exactly
2412
+ * one fetch/reader/decoder plumbing (DRY; R4a reviewer flag).
2413
+ *
2414
+ * `errorPrefix` only shapes the fallback message when the backend
2415
+ * returns a non-2xx without a `detail` field.
1042
2416
  */
1043
- async streamChat(
1044
- request: ChatStreamRequest,
1045
- signal?: AbortSignal
2417
+ private async readSseStream(
2418
+ url: string,
2419
+ body: unknown,
2420
+ errorPrefix: string,
2421
+ signal?: AbortSignal,
1046
2422
  ): Promise<ReadableStreamDefaultReader<Uint8Array>> {
1047
- const url = `${this.chatApiBaseUrl}/api/chat/stream`;
1048
-
1049
2423
  const headers: Record<string, string> = {
1050
2424
  'Content-Type': 'application/json',
1051
2425
  };
@@ -1058,7 +2432,7 @@ export class ApiClient {
1058
2432
  const response = await fetch(url, {
1059
2433
  method: 'POST',
1060
2434
  headers,
1061
- body: JSON.stringify(request),
2435
+ body: JSON.stringify(body),
1062
2436
  signal,
1063
2437
  });
1064
2438
 
@@ -1066,7 +2440,7 @@ export class ApiClient {
1066
2440
  const error: ApiError = await response.json().catch(() => ({
1067
2441
  detail: `HTTP ${response.status}: ${response.statusText}`,
1068
2442
  }));
1069
- throw new Error(error.detail || `Chat request failed: ${response.status}`);
2443
+ throw new Error(error.detail || `${errorPrefix}: ${response.status}`);
1070
2444
  }
1071
2445
 
1072
2446
  const reader = response.body?.getReader();
@@ -1077,6 +2451,107 @@ export class ApiClient {
1077
2451
  return reader;
1078
2452
  }
1079
2453
 
2454
+ /**
2455
+ * Stream chat responses with Server-Sent Events
2456
+ * Returns a ReadableStreamDefaultReader for processing SSE events
2457
+ */
2458
+ async streamChat(
2459
+ request: ChatStreamRequest,
2460
+ signal?: AbortSignal
2461
+ ): Promise<ReadableStreamDefaultReader<Uint8Array>> {
2462
+ return this.readSseStream(
2463
+ // Deliberate URL asymmetry vs streamAssistant: chat is the LEGACY,
2464
+ // UNVERSIONED route (`/api/chat/stream`, no `/v1/`) while assistant is
2465
+ // the NEW VERSIONED route (`/api/v1/assistant/stream`). Keep both as-is —
2466
+ // a future versioning refactor should not "normalize" chat to `/v1/`
2467
+ // without coordinating the backend route, which still serves the legacy path.
2468
+ `${this.chatApiBaseUrl}/api/chat/stream`,
2469
+ request,
2470
+ 'Chat request failed',
2471
+ signal,
2472
+ );
2473
+ }
2474
+
2475
+ /**
2476
+ * Stream Platform Assistant (R4) responses with Server-Sent Events.
2477
+ * Sibling of {@link streamChat} hitting `POST /api/v1/assistant/stream`
2478
+ * — reuses the exact same SSE reader/decoder plumbing via
2479
+ * {@link readSseStream}. Decode each `data: {…}` line into an
2480
+ * {@link AssistantStreamEvent} (the stream may carry the additive
2481
+ * `suggestion` variant). The assistant is out-of-world: the request
2482
+ * carries `routeContext` instead of `videoId`.
2483
+ */
2484
+ async streamAssistant(
2485
+ request: AssistantStreamRequest,
2486
+ signal?: AbortSignal
2487
+ ): Promise<ReadableStreamDefaultReader<Uint8Array>> {
2488
+ return this.readSseStream(
2489
+ // NEW VERSIONED route (`/api/v1/assistant/stream`) — intentionally
2490
+ // differs from streamChat's legacy unversioned `/api/chat/stream`; see
2491
+ // the asymmetry note there.
2492
+ `${this.chatApiBaseUrl}/api/v1/assistant/stream`,
2493
+ request,
2494
+ 'Assistant request failed',
2495
+ signal,
2496
+ );
2497
+ }
2498
+
2499
+ /**
2500
+ * Fetch the chat-model registry from the backend. Returns Bedrock entries
2501
+ * plus any locally-discovered Ollama models. Public endpoint — works
2502
+ * before the user is authenticated.
2503
+ */
2504
+ async listChatModels(): Promise<ChatModelsResponse> {
2505
+ return this.chatRequest<ChatModelsResponse>('/api/v1/chat/models');
2506
+ }
2507
+
2508
+ // ==================== Platform Assistant reference API (R4b) ====================
2509
+ // Read-only introspection backing the assistant's `describe_tool` /
2510
+ // `list_platform_capabilities` tools + the host UI's field-name validation.
2511
+ // All three live on the CHAT base URL (the assistant/reference router is
2512
+ // mounted there, like `streamAssistant`) and reuse the same authed
2513
+ // `chatRequest`/`requestJson` JSON helper as the other chat-base GETs (DRY —
2514
+ // no forked fetch path; the Authorization header is attached iff a session
2515
+ // token is set).
2516
+
2517
+ /**
2518
+ * Fetch the drift-proof field schema for a named creator/admin form
2519
+ * (`GET /api/v1/schema/{form}`). The backend derives every field from the
2520
+ * form's PUBLIC Pydantic request model (`model_json_schema()`) so it can
2521
+ * never drift from the real endpoint contract. The host UI uses this to
2522
+ * validate which `propose_form_fields` suggestions are applicable; the
2523
+ * assistant uses it to propose VALID field names. `form` is one of the
2524
+ * registered ids (`personas` / `documents` / `adventures` / `images`);
2525
+ * `scenes` is intentionally omitted and any unknown form returns 404
2526
+ * (surfaced as a thrown Error).
2527
+ */
2528
+ async getFormSchema(form: string): Promise<FormSchemaResponse> {
2529
+ return this.chatRequest<FormSchemaResponse>(
2530
+ `/api/v1/schema/${encodeURIComponent(form)}`,
2531
+ );
2532
+ }
2533
+
2534
+ /**
2535
+ * List every platform tool's human-readable reference
2536
+ * (`GET /api/v1/tools/reference`). Derived server-side from the full
2537
+ * `shared/tool_schemas` registry (`iter_all_tool_schemas` — chat + adventure
2538
+ * + assistant), so the catalogue cannot drift from the live tool list.
2539
+ */
2540
+ async listToolReferences(): Promise<ToolReferenceListResponse> {
2541
+ return this.chatRequest<ToolReferenceListResponse>('/api/v1/tools/reference');
2542
+ }
2543
+
2544
+ /**
2545
+ * Fetch one tool's reference by name
2546
+ * (`GET /api/v1/tools/reference/{name}`). 404 (thrown Error) when the tool
2547
+ * is unknown.
2548
+ */
2549
+ async getToolReference(name: string): Promise<ToolReferenceResponse> {
2550
+ return this.chatRequest<ToolReferenceResponse>(
2551
+ `/api/v1/tools/reference/${encodeURIComponent(name)}`,
2552
+ );
2553
+ }
2554
+
1080
2555
  // ==================== Persona API Methods ====================
1081
2556
  // Note: Personas are served by the Chat API, not the Tools API
1082
2557
 
@@ -1165,15 +2640,36 @@ export class ApiClient {
1165
2640
  // ==================== Image API Methods ====================
1166
2641
  // Note: Images are served by the Chat API
1167
2642
 
2643
+ /**
2644
+ * Fetch the image-model catalogue from the backend (R1c). Read-only.
2645
+ * Unlike {@link listChatModels}, this endpoint is **authenticated** (its
2646
+ * consumers — Studio Images, the Admin adapter inspector — are post-auth, so
2647
+ * it is not a public pre-auth path); call it with a valid session. Served via
2648
+ * the CHAT base URL (the images API is mounted on the chat app), so this uses
2649
+ * `chatRequest`, NOT `toolsRequest`.
2650
+ */
2651
+ async listImageModels(): Promise<ImageModelsResponse> {
2652
+ return this.chatRequest<ImageModelsResponse>('/api/v1/images/models');
2653
+ }
2654
+
1168
2655
  async listImages(params?: {
1169
2656
  category?: ImageCategory;
1170
2657
  videoId?: string;
2658
+ /** Filter by generation model. Valid ids come from `listImageModels()`
2659
+ * (R1's `GET /api/v1/images/models`); the backend rejects an
2660
+ * unregistered id with 400. */
2661
+ model?: string;
2662
+ /** Filter by lifecycle status. Reuses the `ImageStatus` union
2663
+ * (`ImageRecord['status']`) — no parallel status enum (R6b). */
2664
+ status?: ImageStatus;
1171
2665
  limit?: number;
1172
2666
  nextToken?: string;
1173
2667
  }): Promise<ImageListResponse> {
1174
2668
  const searchParams = new URLSearchParams();
1175
2669
  if (params?.category) searchParams.append('category', params.category);
1176
2670
  if (params?.videoId) searchParams.append('videoId', params.videoId);
2671
+ if (params?.model) searchParams.append('model', params.model);
2672
+ if (params?.status) searchParams.append('status', params.status);
1177
2673
  if (params?.limit) searchParams.append('limit', params.limit.toString());
1178
2674
  if (params?.nextToken) searchParams.append('nextToken', params.nextToken);
1179
2675
 
@@ -1370,17 +2866,7 @@ export class ApiClient {
1370
2866
  if (Date.now() >= deadline) {
1371
2867
  throw new Error(`Image generation timed out after ${Math.round(timeoutMs / 1000)}s`);
1372
2868
  }
1373
- await new Promise<void>((resolve, reject) => {
1374
- const timer = setTimeout(() => {
1375
- options.signal?.removeEventListener('abort', onAbort);
1376
- resolve();
1377
- }, intervalMs);
1378
- const onAbort = () => {
1379
- clearTimeout(timer);
1380
- reject(new DOMException('Polling aborted', 'AbortError'));
1381
- };
1382
- options.signal?.addEventListener('abort', onAbort, { once: true });
1383
- });
2869
+ await abortableSleep(intervalMs, options.signal);
1384
2870
  }
1385
2871
  }
1386
2872
 
@@ -1400,6 +2886,25 @@ export class ApiClient {
1400
2886
  });
1401
2887
  }
1402
2888
 
2889
+ /**
2890
+ * Mint WebRTC signaling credentials for a vision-publisher session.
2891
+ *
2892
+ * Returns either `local`-mode config (STUN-only; existing chat-WS
2893
+ * signaling protocol) or `kvs`-mode config (SigV4-presigned wss://
2894
+ * URL + short-term STUN/TURN). The publisher branches on `mode` —
2895
+ * raw AWS credentials never reach the browser.
2896
+ *
2897
+ * Token TTL is short (~300s); callers running long-lived sessions
2898
+ * should re-call this method before `expiresIn` elapses. The current
2899
+ * VisionPublisher does NOT auto-refresh.
2900
+ */
2901
+ async getVisionRtcCredentials(): Promise<ChatVisionRtcCredentialsResponse> {
2902
+ return this.chatRequest<ChatVisionRtcCredentialsResponse>(
2903
+ '/api/v1/chat/vision-rtc/credentials',
2904
+ { method: 'POST' },
2905
+ );
2906
+ }
2907
+
1403
2908
  /**
1404
2909
  * List available TTS voices. Backed by `GET /api/voices` — server
1405
2910
  * caches Inworld results for 5 min; pass `refresh: true` to bypass.
@@ -1536,8 +3041,61 @@ export class ApiClient {
1536
3041
 
1537
3042
  // ==================== Graph Editor API Methods ====================
1538
3043
 
1539
- async getVideoGraph(videoId: string): Promise<VideoGraphResponse> {
1540
- return this.request<VideoGraphResponse>(`/api/v1/tools/graph/${encodeURIComponent(videoId)}`);
3044
+ /**
3045
+ * Fetch a video's subgraph. R5b: the optional `detail` arg selects the
3046
+ * server-side view — `GRAPH_DETAIL.STORY` for the collapsed story view,
3047
+ * `GRAPH_DETAIL.RAW` for the full extraction graph. Omitting it sends NO
3048
+ * query param (byte-identical to the pre-R5b request — the server defaults
3049
+ * to raw), so every existing caller is untouched.
3050
+ */
3051
+ async getVideoGraph(videoId: string, detail?: GraphDetail): Promise<VideoGraphResponse> {
3052
+ const base = `/api/v1/tools/graph/${encodeURIComponent(videoId)}`;
3053
+ const path = detail === undefined ? base : `${base}?detail=${encodeURIComponent(detail)}`;
3054
+ return this.request<VideoGraphResponse>(path);
3055
+ }
3056
+
3057
+ // ==================== Creator Studio / Story API Methods (M7 P7) ====================
3058
+
3059
+ /**
3060
+ * List all stories (videos) visible to the caller. `storyId === videoId`
3061
+ * (1:1) in M7 P7 — the Story resource is a thin, read-only view over the
3062
+ * existing Video. No pagination/filter parameters in P7.
3063
+ */
3064
+ async listStories(): Promise<ListStoriesResponse> {
3065
+ return this.request<ListStoriesResponse>('/api/v1/stories');
3066
+ }
3067
+
3068
+ /**
3069
+ * Fetch a single story's metadata + aggregate counts. Throws (404) when the
3070
+ * id resolves to no Video node.
3071
+ */
3072
+ async getStory(storyId: string): Promise<GetStoryResponse> {
3073
+ return this.request<GetStoryResponse>(
3074
+ `/api/v1/stories/${encodeURIComponent(storyId)}`,
3075
+ );
3076
+ }
3077
+
3078
+ /**
3079
+ * Resolve a playable (presigned or local-stub) URL for a clip span via the
3080
+ * existing `POST /api/v1/tools/clip-lookup` tool endpoint. Used by the studio
3081
+ * Scene inspector to scope the player to a scene's `[t0, t1]`. Additive — never
3082
+ * remove/rename. Wire keys are camelCase (backend `BaseSchema`, no aliasing).
3083
+ */
3084
+ async clipLookup(params: ClipLookupParams): Promise<ClipLookupResponse> {
3085
+ return this.request<ClipLookupResponse>('/api/v1/tools/clip-lookup', {
3086
+ method: 'POST',
3087
+ body: JSON.stringify(params),
3088
+ });
3089
+ }
3090
+
3091
+ /**
3092
+ * Fetch the live graph whitelist (node PKs + editable properties per label
3093
+ * and edge type). No auth required — pure metadata. Prefer the memoized
3094
+ * `fetchGraphSchema()` wrapper in `graphSchema.ts` over calling this per
3095
+ * render; the raw method exists for that wrapper and one-off callers.
3096
+ */
3097
+ async getGraphSchema(): Promise<GraphSchemaResponse> {
3098
+ return this.request<GraphSchemaResponse>('/api/v1/tools/graph/schema');
1541
3099
  }
1542
3100
 
1543
3101
  async updateGraphNode(data: UpdateNodeRequest): Promise<UpdateNodeResponse> {
@@ -1548,10 +3106,16 @@ export class ApiClient {
1548
3106
  }
1549
3107
 
1550
3108
  async deleteGraphNode(data: DeleteNodeRequest): Promise<DeleteNodeResponse> {
1551
- return this.request<DeleteNodeResponse>('/api/v1/tools/graph/nodes', {
1552
- method: 'DELETE',
1553
- body: JSON.stringify(data),
3109
+ // DELETE carries no body — identifiers travel as query params (M7 P1a,
3110
+ // closes tech-debt #42). The backend derives the PK from the label.
3111
+ const params = new URLSearchParams({
3112
+ nodeLabel: data.nodeLabel,
3113
+ idValue: data.idValue,
1554
3114
  });
3115
+ return this.request<DeleteNodeResponse>(
3116
+ `/api/v1/tools/graph/nodes?${params.toString()}`,
3117
+ { method: 'DELETE' },
3118
+ );
1555
3119
  }
1556
3120
 
1557
3121
  async updateGraphEdge(data: UpdateRelationshipRequest): Promise<UpdateRelationshipResponse> {
@@ -1562,8 +3126,43 @@ export class ApiClient {
1562
3126
  }
1563
3127
 
1564
3128
  async deleteGraphEdge(data: DeleteRelationshipRequest): Promise<DeleteRelationshipResponse> {
1565
- return this.request<DeleteRelationshipResponse>('/api/v1/tools/graph/edges', {
1566
- method: 'DELETE',
3129
+ // DELETE carries no body — identifiers travel as query params (M7 P1a,
3130
+ // closes tech-debt #42).
3131
+ const params = new URLSearchParams({
3132
+ sourceId: data.sourceId,
3133
+ targetId: data.targetId,
3134
+ relType: data.relType,
3135
+ });
3136
+ return this.request<DeleteRelationshipResponse>(
3137
+ `/api/v1/tools/graph/edges?${params.toString()}`,
3138
+ { method: 'DELETE' },
3139
+ );
3140
+ }
3141
+
3142
+ /**
3143
+ * Create a user-authored narrative node (Scene / PlotBeat / CharacterArc).
3144
+ * POST returns 201 with `{traceId, nodeId, properties}`; `makeRequest` parses
3145
+ * the body (only 204 is bodyless) and surfaces a 422 (e.g. label not
3146
+ * user-creatable, missing actId/index for a Scene) as a thrown `Error` with
3147
+ * the FastAPI detail. The backend stamps provenance/versionId/timestamps.
3148
+ */
3149
+ async createGraphNode(data: CreateNodeRequest): Promise<CreateNodeResponse> {
3150
+ return this.request<CreateNodeResponse>('/api/v1/tools/graph/nodes', {
3151
+ method: 'POST',
3152
+ body: JSON.stringify(data),
3153
+ });
3154
+ }
3155
+
3156
+ /**
3157
+ * Create a user-authored relationship (RELATES_TO / CAUSES / SET_IN /
3158
+ * FEATURES / ON_ARC / LEADS_TO). POST returns 201 with
3159
+ * `{traceId, edgeId, properties}`; a 422 (invalid endpoint-label pair,
3160
+ * pipeline-only type, cross-video endpoints, or SET_IN/FEATURES Entity.type
3161
+ * mismatch) surfaces as a thrown `Error` with the FastAPI detail.
3162
+ */
3163
+ async createGraphEdge(data: CreateEdgeRequest): Promise<CreateEdgeResponse> {
3164
+ return this.request<CreateEdgeResponse>('/api/v1/tools/graph/edges', {
3165
+ method: 'POST',
1567
3166
  body: JSON.stringify(data),
1568
3167
  });
1569
3168
  }
@@ -1864,17 +3463,7 @@ export class ApiClient {
1864
3463
  if (Date.now() >= deadline) {
1865
3464
  throw new Error(`Regeneration timed out after ${Math.round(timeoutMs / 1000)}s`);
1866
3465
  }
1867
- await new Promise<void>((resolve, reject) => {
1868
- const timer = setTimeout(() => {
1869
- options.signal?.removeEventListener('abort', onAbort);
1870
- resolve();
1871
- }, intervalMs);
1872
- const onAbort = () => {
1873
- clearTimeout(timer);
1874
- reject(new DOMException('Polling aborted', 'AbortError'));
1875
- };
1876
- options.signal?.addEventListener('abort', onAbort, { once: true });
1877
- });
3466
+ await abortableSleep(intervalMs, options.signal);
1878
3467
  }
1879
3468
  }
1880
3469
 
@@ -1936,17 +3525,7 @@ export class ApiClient {
1936
3525
  `Bundle generation timed out after ${Math.round(timeoutMs / 1000)}s`,
1937
3526
  );
1938
3527
  }
1939
- await new Promise<void>((resolve, reject) => {
1940
- const timer = setTimeout(() => {
1941
- options.signal?.removeEventListener('abort', onAbort);
1942
- resolve();
1943
- }, intervalMs);
1944
- const onAbort = () => {
1945
- clearTimeout(timer);
1946
- reject(new DOMException('Polling aborted', 'AbortError'));
1947
- };
1948
- options.signal?.addEventListener('abort', onAbort, { once: true });
1949
- });
3528
+ await abortableSleep(intervalMs, options.signal);
1950
3529
  }
1951
3530
  }
1952
3531
 
@@ -2029,6 +3608,18 @@ export class ApiClient {
2029
3608
  return await response.blob();
2030
3609
  }
2031
3610
 
3611
+ /**
3612
+ * Fetch the default system prompt components from the Chat API.
3613
+ * Backed by `GET /api/v1/chat/system-prompt`.
3614
+ *
3615
+ * Authentication is required — the client must have a session token set.
3616
+ * Callers that need caching should wrap this in their own layer (see
3617
+ * `web/lib/systemPrompt.ts` which keeps a 5-minute in-memory cache).
3618
+ */
3619
+ async getSystemPrompt(): Promise<SystemPromptComponents> {
3620
+ return this.chatRequest<SystemPromptComponents>('/api/v1/chat/system-prompt');
3621
+ }
3622
+
2032
3623
  /**
2033
3624
  * Knowledge-grounded prompt upsample — expands a short user prompt
2034
3625
  * into a Helios-quality 80-120 word paragraph using Bedrock. Routes
@@ -2053,4 +3644,141 @@ export class ApiClient {
2053
3644
  );
2054
3645
  }
2055
3646
 
3647
+ // ============= Adventure Runtime API (M9 Story Engine Phase 8a) =============
3648
+
3649
+ /**
3650
+ * Start an interactive adventure for a story/video, driven by a
3651
+ * Dungeon-Master persona. `POST /api/v1/adventures` → 201 with the initial
3652
+ * {@link AdventureState} (and a `Location` header to the session's GET URL).
3653
+ *
3654
+ * Auth + video ownership are enforced server-side. `dmPersonaId` must
3655
+ * reference an owned persona whose `is_dungeon_master` is true (422 otherwise),
3656
+ * and a missing/unowned persona is a 404/403 — all surface as a thrown `Error`
3657
+ * carrying the FastAPI detail. Additive — never remove/rename.
3658
+ */
3659
+ async startAdventure(
3660
+ request: StartAdventureRequest,
3661
+ options: { signal?: AbortSignal } = {},
3662
+ ): Promise<AdventureResponse> {
3663
+ return this.request<AdventureResponse>('/api/v1/adventures', {
3664
+ method: 'POST',
3665
+ body: JSON.stringify(request),
3666
+ signal: options.signal,
3667
+ });
3668
+ }
3669
+
3670
+ /**
3671
+ * Fetch the current {@link AdventureState} for a session.
3672
+ * `GET /api/v1/adventures/{sessionId}` (404 when absent or not owned by the
3673
+ * caller — the store hides cross-tenant and soft-deleted sessions).
3674
+ */
3675
+ async getAdventure(
3676
+ sessionId: string,
3677
+ options: { signal?: AbortSignal } = {},
3678
+ ): Promise<GetAdventureResponse> {
3679
+ return this.request<GetAdventureResponse>(
3680
+ `/api/v1/adventures/${encodeURIComponent(sessionId)}`,
3681
+ { signal: options.signal },
3682
+ );
3683
+ }
3684
+
3685
+ /**
3686
+ * List the caller's adventures, newest-first. `GET /api/v1/adventures` →
3687
+ * {@link ListAdventuresResponse}. Owner-scoped server-side (soft-deleted
3688
+ * sessions excluded); pass `storyId` to narrow to a single story. Additive —
3689
+ * never remove/rename.
3690
+ */
3691
+ async listAdventures(
3692
+ storyId?: string,
3693
+ options: { signal?: AbortSignal } = {},
3694
+ ): Promise<ListAdventuresResponse> {
3695
+ const searchParams = new URLSearchParams();
3696
+ if (storyId) searchParams.append('storyId', storyId);
3697
+
3698
+ const query = searchParams.toString();
3699
+ const endpoint = `/api/v1/adventures${query ? `?${query}` : ''}`;
3700
+ return this.request<ListAdventuresResponse>(endpoint, {
3701
+ signal: options.signal,
3702
+ });
3703
+ }
3704
+
3705
+ /**
3706
+ * Soft-delete an adventure session. `DELETE /api/v1/adventures/{sessionId}`
3707
+ * → 204 (resolves to `void`). A missing/unowned session is a 404 surfaced as
3708
+ * a thrown `Error`.
3709
+ */
3710
+ async deleteAdventure(
3711
+ sessionId: string,
3712
+ options: { signal?: AbortSignal } = {},
3713
+ ): Promise<void> {
3714
+ return this.request<void>(
3715
+ `/api/v1/adventures/${encodeURIComponent(sessionId)}`,
3716
+ { method: 'DELETE', signal: options.signal },
3717
+ );
3718
+ }
3719
+
3720
+ /**
3721
+ * Mutate an adventure's party (M10 Story Engine Phase 9a).
3722
+ * `PATCH /api/v1/adventures/{sessionId}/party` with
3723
+ * `{ action, personaId }` → the updated {@link GetAdventureResponse}.
3724
+ * Shared by {@link addPartyMember} / {@link removePartyMember}; not exported
3725
+ * directly so call sites go through the action-specific wrappers. Additive —
3726
+ * never remove/rename.
3727
+ */
3728
+ private patchParty(
3729
+ sessionId: string,
3730
+ request: PartyUpdateRequest,
3731
+ options: { signal?: AbortSignal } = {},
3732
+ ): Promise<GetAdventureResponse> {
3733
+ return this.request<GetAdventureResponse>(
3734
+ `/api/v1/adventures/${encodeURIComponent(sessionId)}/party`,
3735
+ {
3736
+ method: 'PATCH',
3737
+ body: JSON.stringify(request),
3738
+ signal: options.signal,
3739
+ },
3740
+ );
3741
+ }
3742
+
3743
+ /**
3744
+ * Add a character persona to an adventure's party (M10 Story Engine Phase
3745
+ * 9a). `PATCH /api/v1/adventures/{sessionId}/party` with `action='add'` →
3746
+ * the updated {@link GetAdventureResponse}. The persona must be owned by the
3747
+ * caller, bound to a character entity, and NOT a Dungeon Master (422
3748
+ * otherwise); a missing/unowned adventure is a 404 — all surface as a thrown
3749
+ * `Error` carrying the FastAPI detail. Server-side dedupe makes a repeat add
3750
+ * a no-op. Additive — never remove/rename.
3751
+ */
3752
+ async addPartyMember(
3753
+ sessionId: string,
3754
+ personaId: string,
3755
+ options: { signal?: AbortSignal } = {},
3756
+ ): Promise<GetAdventureResponse> {
3757
+ return this.patchParty(
3758
+ sessionId,
3759
+ { action: PARTY_ACTION.ADD, personaId },
3760
+ options,
3761
+ );
3762
+ }
3763
+
3764
+ /**
3765
+ * Remove a character persona from an adventure's party (M10 Story Engine
3766
+ * Phase 9a). `PATCH /api/v1/adventures/{sessionId}/party` with
3767
+ * `action='remove'` → the updated {@link GetAdventureResponse}. Idempotent:
3768
+ * removing an absent member is a 200 no-op that returns the current state. A
3769
+ * missing/unowned adventure is a 404 surfaced as a thrown `Error`. Additive —
3770
+ * never remove/rename.
3771
+ */
3772
+ async removePartyMember(
3773
+ sessionId: string,
3774
+ personaId: string,
3775
+ options: { signal?: AbortSignal } = {},
3776
+ ): Promise<GetAdventureResponse> {
3777
+ return this.patchParty(
3778
+ sessionId,
3779
+ { action: PARTY_ACTION.REMOVE, personaId },
3780
+ options,
3781
+ );
3782
+ }
3783
+
2056
3784
  }