@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/dist/api.js CHANGED
@@ -1,24 +1,169 @@
1
1
  /**
2
2
  * API client for the Seer Agent backend
3
3
  */
4
+ import { isAbortError } from './reactor/abortUtils.js';
5
+ import { requestJson } from './http.js';
6
+ /**
7
+ * Module-private helper: resolves after `ms` milliseconds, or rejects with
8
+ * an AbortError if the optional `signal` fires before the timer expires.
9
+ *
10
+ * Listener hygiene: the abort listener is removed explicitly on the normal
11
+ * (timer) path so it does not linger on the signal after resolution.
12
+ */
13
+ function abortableSleep(ms, signal) {
14
+ return new Promise((resolve, reject) => {
15
+ // Declare `timer` with `let` first so `onAbort` can reference it in the
16
+ // closure without a use-before-define lint error (the closure is only
17
+ // invoked after `timer` is assigned below).
18
+ let timer;
19
+ const onAbort = () => {
20
+ clearTimeout(timer);
21
+ reject(new DOMException('Polling aborted', 'AbortError'));
22
+ };
23
+ timer = setTimeout(() => {
24
+ signal?.removeEventListener('abort', onAbort);
25
+ resolve();
26
+ }, ms);
27
+ signal?.addEventListener('abort', onAbort, { once: true });
28
+ });
29
+ }
4
30
  export const ENRICHMENT_STATUS_QUEUED = 'QUEUED';
5
31
  export const ENRICHMENT_STATUS_RUNNING = 'RUNNING';
6
32
  export const ENRICHMENT_STATUS_SUCCEEDED = 'SUCCEEDED';
7
33
  export const ENRICHMENT_STATUS_FAILED = 'FAILED';
34
+ /** Const map of every {@link RegenerationRunStatus} value (mirrors the backend StrEnum). */
35
+ export const REGENERATION_STATUS = {
36
+ QUEUED: 'queued',
37
+ RUNNING: 'running',
38
+ MERGING: 'merging',
39
+ COMPLETE: 'complete',
40
+ FAILED: 'failed',
41
+ CANCELLED: 'cancelled',
42
+ };
8
43
  /**
9
- * Detect an abort (controller.abort(), unmount, signal expiry) so callers
10
- * can stay silent on expected cancellations while still surfacing real
11
- * fetch errors (5xx / timeout / CORS). Native `fetch` rejects with a
12
- * `DOMException { name: 'AbortError' }`; the project's own pollers throw
13
- * the same shape; a polyfilled fetch may throw a plain `Error` with the
14
- * same name. Accept both so the warn-suppression survives a future
15
- * polyfill or SSR runtime swap.
44
+ * Terminal statuses: a run in one of these will never transition again.
45
+ * Mirrors `shared/models.py::REGENERATION_TERMINAL_STATUSES`. The poller
46
+ * resolves on COMPLETE / CANCELLED and throws on FAILED — but a consumer
47
+ * rendering history can use this set to gate "in-flight" affordances.
16
48
  */
17
- function isAbortError(err) {
18
- if (err instanceof DOMException && err.name === 'AbortError')
19
- return true;
20
- return err instanceof Error && err.name === 'AbortError';
49
+ export const REGENERATION_TERMINAL_STATUSES = [
50
+ REGENERATION_STATUS.COMPLETE,
51
+ REGENERATION_STATUS.FAILED,
52
+ REGENERATION_STATUS.CANCELLED,
53
+ ];
54
+ /** Scope kinds that regenerate a whole narrative dimension (no target id). */
55
+ export const REGEN_SCOPE_BARE_KINDS = [
56
+ 'acts',
57
+ 'characters',
58
+ ];
59
+ /** Scope kinds that target a single node by id (`<kind>:<id>`). */
60
+ export const REGEN_SCOPE_TARGETED_KINDS = [
61
+ 'scene',
62
+ 'arc',
63
+ ];
64
+ /** Separator between a targeted scope's kind and its id (mirrors `REGEN_SCOPE_SEPARATOR`). */
65
+ export const REGEN_SCOPE_SEPARATOR = ':';
66
+ /**
67
+ * Build a wire-format scope string from a kind + optional target id, mirroring
68
+ * the backend grammar so callers never hand-roll `'scene:' + id`. A bare kind
69
+ * (`acts` / `characters`) MUST NOT carry a target; a targeted kind
70
+ * (`scene` / `arc`) MUST. Throws on a contract violation so a UI bug surfaces
71
+ * locally rather than as a server-side 422.
72
+ */
73
+ export function buildRegenerationScope(kind, targetId) {
74
+ const isTargeted = REGEN_SCOPE_TARGETED_KINDS.includes(kind);
75
+ if (isTargeted) {
76
+ if (!targetId) {
77
+ throw new Error(`Scope kind "${kind}" requires a target id`);
78
+ }
79
+ return `${kind}${REGEN_SCOPE_SEPARATOR}${targetId}`;
80
+ }
81
+ if (targetId) {
82
+ throw new Error(`Scope kind "${kind}" does not take a target id`);
83
+ }
84
+ return kind;
21
85
  }
86
+ /**
87
+ * Delta bucket key strings, mirroring `shared/regeneration_merge.py::DELTA_*`.
88
+ * Exposed as a const map so call sites read `delta[REGEN_DELTA_KEYS.nodes]`
89
+ * rather than re-typing the literals (single source of truth on the wire names).
90
+ */
91
+ export const REGEN_DELTA_KEYS = {
92
+ nodes: 'nodes',
93
+ edges: 'edges',
94
+ added: 'added',
95
+ updated: 'updated',
96
+ preservedUser: 'preservedUser',
97
+ removed: 'removed',
98
+ };
99
+ /**
100
+ * Extract the `nodes` count buckets from a run's {@link RegenerationRunResponse.delta}.
101
+ *
102
+ * `delta` is typed `Record<string, unknown>` (it carries `nodes` + `edges`
103
+ * sub-objects once merged, and is `{}` before merge), so a UI that wants the
104
+ * "N updated · M preserved · K added · R removed" summary needs a single,
105
+ * tested narrowing rather than ad-hoc casts at each call site. Returns all-zero
106
+ * counts when the delta is empty/malformed (an unmerged or failed run), and
107
+ * coerces any non-numeric / negative bucket to 0 so the summary line is always
108
+ * safe to render.
109
+ */
110
+ export function parseRegenerationNodeCounts(delta) {
111
+ const empty = {
112
+ added: 0,
113
+ updated: 0,
114
+ preservedUser: 0,
115
+ removed: 0,
116
+ };
117
+ const nodes = delta?.[REGEN_DELTA_KEYS.nodes];
118
+ if (typeof nodes !== 'object' || nodes === null) {
119
+ return empty;
120
+ }
121
+ const bucket = nodes;
122
+ const num = (value) => typeof value === 'number' && Number.isFinite(value) && value > 0
123
+ ? Math.floor(value)
124
+ : 0;
125
+ return {
126
+ added: num(bucket[REGEN_DELTA_KEYS.added]),
127
+ updated: num(bucket[REGEN_DELTA_KEYS.updated]),
128
+ preservedUser: num(bucket[REGEN_DELTA_KEYS.preservedUser]),
129
+ removed: num(bucket[REGEN_DELTA_KEYS.removed]),
130
+ };
131
+ }
132
+ export const DOC_STATUS_PENDING = 'pending';
133
+ export const DOC_STATUS_PARSING = 'parsing';
134
+ export const DOC_STATUS_EXTRACTING = 'extracting';
135
+ export const DOC_STATUS_READY = 'ready';
136
+ export const DOC_STATUS_FAILED = 'failed';
137
+ export const SUGGESTION_STATUS_PENDING = 'pending';
138
+ export const SUGGESTION_STATUS_ACCEPTED = 'accepted';
139
+ export const SUGGESTION_STATUS_REJECTED = 'rejected';
140
+ /**
141
+ * Detail level for the video-graph read (Platform Restructure R5b). Mirrors
142
+ * `shared/graph_schema.py`'s `GraphDetail` — the single source of the
143
+ * `story`/`raw` mode literals (constants over bare strings; consumers compare
144
+ * against `GRAPH_DETAIL.*`, never a raw literal).
145
+ *
146
+ * - `RAW` (the server default — omitting the `detail` arg keeps the request
147
+ * byte-identical to the pre-R5b call): the full extraction subgraph.
148
+ * - `STORY`: the curated story view — Acts, Scenes (each Scene node's
149
+ * `properties` carries a read-time `shotCount`), the character cast,
150
+ * document contributions, and narrative edges; Shot/DialogLine/Event nodes
151
+ * and MENTIONS edges are collapsed server-side.
152
+ */
153
+ export const GRAPH_DETAIL = {
154
+ STORY: 'story',
155
+ RAW: 'raw',
156
+ };
157
+ /**
158
+ * The two `action` values accepted by `PATCH /api/v1/adventures/{sessionId}/party`
159
+ * (M10 Story Engine Phase 9a). `add` appends a character persona to the party
160
+ * (validated + deduped server-side); `remove` is an idempotent no-op when the
161
+ * persona is absent. Named constant so call sites never hard-code the literals.
162
+ */
163
+ export const PARTY_ACTION = {
164
+ ADD: 'add',
165
+ REMOVE: 'remove',
166
+ };
22
167
  export class ApiClient {
23
168
  baseURL;
24
169
  sessionToken;
@@ -38,45 +183,10 @@ export class ApiClient {
38
183
  return this.makeRequest(this.chatApiBaseUrl, endpoint, options);
39
184
  }
40
185
  async makeRequest(baseUrl, endpoint, options = {}) {
41
- const url = `${baseUrl}${endpoint}`;
42
- const headers = {
43
- 'Content-Type': 'application/json',
44
- ...options.headers,
45
- };
46
- // Add authorization header if session token is available
47
- if (this.sessionToken) {
48
- headers['Authorization'] = `Bearer ${this.sessionToken}`;
49
- }
50
- try {
51
- const response = await fetch(url, {
52
- ...options,
53
- headers,
54
- });
55
- if (!response.ok) {
56
- const error = await response.json().catch(() => ({
57
- detail: `HTTP ${response.status}: ${response.statusText}`,
58
- }));
59
- // FastAPI 422 returns detail as an array of validation errors
60
- const detail = error.detail;
61
- let message;
62
- if (Array.isArray(detail)) {
63
- message = detail.map((e) => e.msg ? `${(e.loc || []).slice(-1).join('.')}: ${e.msg}` : String(e)).join('; ');
64
- }
65
- else {
66
- message = detail || `Request failed: ${response.status}`;
67
- }
68
- throw new Error(message);
69
- }
70
- // 204 No Content returns no body
71
- if (response.status === 204) {
72
- return undefined;
73
- }
74
- return await response.json();
75
- }
76
- catch (error) {
77
- console.error('API request failed:', error);
78
- throw error;
79
- }
186
+ // Delegates to the shared `requestJson` helper (bearer auth + FastAPI error
187
+ // shaping) so `ApiClient` and the additive `AdminClient` share one fetch
188
+ // wrapper — behavior is identical to the prior inline implementation.
189
+ return requestJson(baseUrl, endpoint, this.sessionToken, options);
80
190
  }
81
191
  /**
82
192
  * List all ingestion jobs with optional filtering
@@ -112,6 +222,27 @@ export class ApiClient {
112
222
  const endpoint = `/api/v1/tools/videos${query ? `?${query}` : ''}`;
113
223
  return this.request(endpoint);
114
224
  }
225
+ /**
226
+ * Story Engine Phase 5 — list character entities for a video. Backs the
227
+ * persona↔character binding selector. Returns only ``Entity`` nodes with
228
+ * ``type === 'character'`` for the given video. Auth + video ownership are
229
+ * enforced server-side (caller must own the video). Uses the main API base
230
+ * (the tools routes use ``request``, not ``chatRequest``).
231
+ */
232
+ async listVideoCharacters(videoId) {
233
+ return this.request(`/api/v1/tools/videos/${encodeURIComponent(videoId)}/characters`);
234
+ }
235
+ /**
236
+ * Platform Restructure R5a — fetch a video's character cast pre-joined to
237
+ * each character's bound persona in ONE round-trip (the server resolves the
238
+ * PORTRAYS binding + hydrates persona display fields). The one-call
239
+ * replacement for the CastGrid's `getVideoGraph` + `listPersonas` client-side
240
+ * `entity_id` join (the R5c rewire consumes this). Auth + video ownership are
241
+ * enforced server-side. Tools API base (`request`, not `chatRequest`).
242
+ */
243
+ async getCast(videoId) {
244
+ return this.request(`/api/v1/tools/videos/${encodeURIComponent(videoId)}/cast`);
245
+ }
115
246
  /**
116
247
  * List staged videos in the ingestion bucket
117
248
  */
@@ -234,12 +365,215 @@ export class ApiClient {
234
365
  method: 'DELETE',
235
366
  });
236
367
  }
368
+ // ============= Narrative Regeneration API (M7 Phase 6 / Story Engine) =============
237
369
  /**
238
- * Stream chat responses with Server-Sent Events
239
- * Returns a ReadableStreamDefaultReader for processing SSE events
370
+ * Start an async narrative regeneration run for a video scope.
371
+ * `POST /api/v1/tools/graph/{videoId}/regenerate` → 202 with the QUEUED run
372
+ * (and a `Location` header to the run's poll URL, exposed as `statusUrl`).
373
+ *
374
+ * Auth + ownership are enforced server-side. A malformed `scope` is a 422,
375
+ * an in-flight run is a 409, over-cap is a 429 — all surface as a thrown
376
+ * `Error` carrying the FastAPI detail. Build `request.scope` with
377
+ * {@link buildRegenerationScope}. Pair with {@link pollRegenerationUntilDone}.
240
378
  */
241
- async streamChat(request, signal) {
242
- const url = `${this.chatApiBaseUrl}/api/chat/stream`;
379
+ async startRegeneration(videoId, request) {
380
+ return this.request(`/api/v1/tools/graph/${encodeURIComponent(videoId)}/regenerate`, {
381
+ method: 'POST',
382
+ body: JSON.stringify(request),
383
+ });
384
+ }
385
+ /**
386
+ * List a video's regeneration runs, newest-first.
387
+ * `GET /api/v1/tools/graph/{videoId}/regenerations`. `limit` (1–100) and
388
+ * `cursor` (opaque pagination token from a prior `nextCursor`) are optional.
389
+ */
390
+ async listRegenerations(videoId, params) {
391
+ const searchParams = new URLSearchParams();
392
+ if (params?.limit != null)
393
+ searchParams.append('limit', params.limit.toString());
394
+ if (params?.cursor)
395
+ searchParams.append('cursor', params.cursor);
396
+ const query = searchParams.toString();
397
+ const endpoint = `/api/v1/tools/graph/${encodeURIComponent(videoId)}/regenerations${query ? `?${query}` : ''}`;
398
+ return this.request(endpoint);
399
+ }
400
+ /**
401
+ * Fetch a single regeneration run by id.
402
+ * `GET /api/v1/tools/graph/{videoId}/regenerations/{runId}` (404 if absent).
403
+ * `signal` aborts the in-flight fetch — {@link pollRegenerationUntilDone}
404
+ * threads its poll signal through so a page unmount cancels cleanly.
405
+ */
406
+ async getRegeneration(videoId, runId, options = {}) {
407
+ return this.request(`/api/v1/tools/graph/${encodeURIComponent(videoId)}/regenerations/${encodeURIComponent(runId)}`, { signal: options.signal });
408
+ }
409
+ /**
410
+ * Poll {@link getRegeneration} until the run reaches a terminal status.
411
+ * COMPLETE / CANCELLED resolve with the final run; FAILED throws
412
+ * (`record.error` ?? a generic message). Mirrors
413
+ * {@link pollVisemeBundleUntilDone}: 5s cadence, abortable via `signal`,
414
+ * and a wall-clock timeout (regeneration re-invokes Pegasus, so the default
415
+ * matches bundle assembly — generous but bounded).
416
+ */
417
+ async pollRegenerationUntilDone(videoId, runId, options = {}) {
418
+ const intervalMs = options.intervalMs ?? 5000;
419
+ // The regenerator Lambda can run up to its 15-min cap (an `acts` scope re-runs
420
+ // Pegasus over the whole film), so the default poll deadline must exceed that or
421
+ // the client gives up while the run is still completing. 16 min covers a normal
422
+ // single run; if the poll still times out (e.g. an SQS redelivery), the run row
423
+ // is durable — a refresh / re-fetch surfaces the terminal state.
424
+ const timeoutMs = options.timeoutMs ?? 960_000;
425
+ const deadline = Date.now() + timeoutMs;
426
+ while (true) {
427
+ if (options.signal?.aborted) {
428
+ throw new DOMException('Polling aborted', 'AbortError');
429
+ }
430
+ const record = await this.getRegeneration(videoId, runId, {
431
+ signal: options.signal,
432
+ });
433
+ if (record.status === REGENERATION_STATUS.COMPLETE ||
434
+ record.status === REGENERATION_STATUS.CANCELLED) {
435
+ return record;
436
+ }
437
+ if (record.status === REGENERATION_STATUS.FAILED) {
438
+ throw new Error(record.error ?? 'Regeneration failed');
439
+ }
440
+ if (Date.now() >= deadline) {
441
+ throw new Error(`Regeneration timed out after ${Math.round(timeoutMs / 1000)}s`);
442
+ }
443
+ await abortableSleep(intervalMs, options.signal);
444
+ }
445
+ }
446
+ // ==================== Source Document API (M7 Phase 4) ====================
447
+ /**
448
+ * Upload a source document (script / notes / bible / transcript) with
449
+ * progress tracking. Mirrors {@link uploadVideo}: multipart XHR so the
450
+ * browser reports upload progress (fetch cannot). The `meta` fields ride
451
+ * alongside the file as a JSON `payload` part. Returns 201 with
452
+ * `{ traceId, docId, statusUrl }`; the backend enqueues
453
+ * `document-processing-queue` to parse + extract suggestions.
454
+ */
455
+ async uploadDocument(file, meta, onProgress) {
456
+ const url = `${this.baseURL}/api/v1/ingestion/documents`;
457
+ return new Promise((resolve, reject) => {
458
+ const xhr = new XMLHttpRequest();
459
+ // Track upload progress
460
+ if (onProgress) {
461
+ xhr.upload.addEventListener('progress', (e) => {
462
+ if (e.lengthComputable) {
463
+ onProgress({
464
+ loaded: e.loaded,
465
+ total: e.total,
466
+ percentage: Math.round((e.loaded / e.total) * 100),
467
+ });
468
+ }
469
+ });
470
+ }
471
+ // Handle completion
472
+ xhr.addEventListener('load', () => {
473
+ if (xhr.status >= 200 && xhr.status < 300) {
474
+ try {
475
+ const response = JSON.parse(xhr.responseText);
476
+ resolve(response);
477
+ }
478
+ catch {
479
+ reject(new Error('Failed to parse upload response'));
480
+ }
481
+ }
482
+ else {
483
+ try {
484
+ const errorData = JSON.parse(xhr.responseText);
485
+ reject(new Error(errorData.detail || `Upload failed: ${xhr.status}`));
486
+ }
487
+ catch {
488
+ reject(new Error(`Upload failed: ${xhr.status} ${xhr.statusText}`));
489
+ }
490
+ }
491
+ });
492
+ // Handle errors
493
+ xhr.addEventListener('error', () => {
494
+ reject(new Error('Upload failed due to network error'));
495
+ });
496
+ xhr.addEventListener('abort', () => {
497
+ reject(new Error('Upload aborted'));
498
+ });
499
+ // Prepare form data — file part + JSON metadata part.
500
+ const formData = new FormData();
501
+ formData.append('upload', file);
502
+ formData.append('payload', JSON.stringify(meta));
503
+ // Send request
504
+ xhr.open('POST', url);
505
+ // Add authorization header if session token is available
506
+ if (this.sessionToken) {
507
+ xhr.setRequestHeader('Authorization', `Bearer ${this.sessionToken}`);
508
+ }
509
+ xhr.send(formData);
510
+ });
511
+ }
512
+ /**
513
+ * List source documents, optionally scoped to a video or series. Mirrors
514
+ * {@link listJobs} query-param handling. GET `/api/v1/ingestion/documents`.
515
+ */
516
+ async listDocuments(params) {
517
+ const searchParams = new URLSearchParams();
518
+ if (params?.videoId)
519
+ searchParams.append('videoId', params.videoId);
520
+ if (params?.seriesId)
521
+ searchParams.append('seriesId', params.seriesId);
522
+ if (params?.limit)
523
+ searchParams.append('limit', params.limit.toString());
524
+ if (params?.nextToken)
525
+ searchParams.append('nextToken', params.nextToken);
526
+ const query = searchParams.toString();
527
+ const endpoint = `/api/v1/ingestion/documents${query ? `?${query}` : ''}`;
528
+ return this.request(endpoint);
529
+ }
530
+ /**
531
+ * Fetch a single document plus its pending/resolved graph suggestions.
532
+ * GET `/api/v1/ingestion/documents/{docId}`.
533
+ */
534
+ async getDocument(docId) {
535
+ return this.request(`/api/v1/ingestion/documents/${docId}`);
536
+ }
537
+ /**
538
+ * Accept a pipeline-extracted graph suggestion — writes the proposed
539
+ * node/edge with provenance `document`. POST returns 201 with
540
+ * `{ traceId, suggestionId, graphId }` (`graphId` is the composite id of the
541
+ * created node/edge); a 422 (e.g. already resolved, or the payload fails
542
+ * graph validation) surfaces the FastAPI detail as a thrown `Error`. POST
543
+ * `.../documents/{docId}/suggestions/{sid}/accept`.
544
+ */
545
+ async acceptSuggestion(docId, suggestionId) {
546
+ return this.request(`/api/v1/ingestion/documents/${docId}/suggestions/${suggestionId}/accept`, { method: 'POST' });
547
+ }
548
+ /**
549
+ * Reject a pipeline-extracted graph suggestion (marks it `rejected`, writes
550
+ * nothing to the graph). Returns 204 (no body). POST
551
+ * `.../documents/{docId}/suggestions/{sid}/reject`.
552
+ */
553
+ async rejectSuggestion(docId, suggestionId) {
554
+ return this.request(`/api/v1/ingestion/documents/${docId}/suggestions/${suggestionId}/reject`, { method: 'POST' });
555
+ }
556
+ /**
557
+ * Delete a source document and its associated data. Returns 204 (no body).
558
+ * DELETE `/api/v1/ingestion/documents/{docId}`.
559
+ */
560
+ async deleteDocument(docId) {
561
+ return this.request(`/api/v1/ingestion/documents/${docId}`, {
562
+ method: 'DELETE',
563
+ });
564
+ }
565
+ /**
566
+ * Shared SSE body-reader for the chat + assistant stream endpoints.
567
+ * POSTs the JSON `body` to `url` (with the auth header when a session
568
+ * token is set) and returns the response's `ReadableStreamDefaultReader`
569
+ * for the caller to decode. `streamChat` and `streamAssistant` differ
570
+ * ONLY by URL + body, so they both route through here — there is exactly
571
+ * one fetch/reader/decoder plumbing (DRY; R4a reviewer flag).
572
+ *
573
+ * `errorPrefix` only shapes the fallback message when the backend
574
+ * returns a non-2xx without a `detail` field.
575
+ */
576
+ async readSseStream(url, body, errorPrefix, signal) {
243
577
  const headers = {
244
578
  'Content-Type': 'application/json',
245
579
  };
@@ -250,14 +584,14 @@ export class ApiClient {
250
584
  const response = await fetch(url, {
251
585
  method: 'POST',
252
586
  headers,
253
- body: JSON.stringify(request),
587
+ body: JSON.stringify(body),
254
588
  signal,
255
589
  });
256
590
  if (!response.ok) {
257
591
  const error = await response.json().catch(() => ({
258
592
  detail: `HTTP ${response.status}: ${response.statusText}`,
259
593
  }));
260
- throw new Error(error.detail || `Chat request failed: ${response.status}`);
594
+ throw new Error(error.detail || `${errorPrefix}: ${response.status}`);
261
595
  }
262
596
  const reader = response.body?.getReader();
263
597
  if (!reader) {
@@ -265,6 +599,82 @@ export class ApiClient {
265
599
  }
266
600
  return reader;
267
601
  }
602
+ /**
603
+ * Stream chat responses with Server-Sent Events
604
+ * Returns a ReadableStreamDefaultReader for processing SSE events
605
+ */
606
+ async streamChat(request, signal) {
607
+ return this.readSseStream(
608
+ // Deliberate URL asymmetry vs streamAssistant: chat is the LEGACY,
609
+ // UNVERSIONED route (`/api/chat/stream`, no `/v1/`) while assistant is
610
+ // the NEW VERSIONED route (`/api/v1/assistant/stream`). Keep both as-is —
611
+ // a future versioning refactor should not "normalize" chat to `/v1/`
612
+ // without coordinating the backend route, which still serves the legacy path.
613
+ `${this.chatApiBaseUrl}/api/chat/stream`, request, 'Chat request failed', signal);
614
+ }
615
+ /**
616
+ * Stream Platform Assistant (R4) responses with Server-Sent Events.
617
+ * Sibling of {@link streamChat} hitting `POST /api/v1/assistant/stream`
618
+ * — reuses the exact same SSE reader/decoder plumbing via
619
+ * {@link readSseStream}. Decode each `data: {…}` line into an
620
+ * {@link AssistantStreamEvent} (the stream may carry the additive
621
+ * `suggestion` variant). The assistant is out-of-world: the request
622
+ * carries `routeContext` instead of `videoId`.
623
+ */
624
+ async streamAssistant(request, signal) {
625
+ return this.readSseStream(
626
+ // NEW VERSIONED route (`/api/v1/assistant/stream`) — intentionally
627
+ // differs from streamChat's legacy unversioned `/api/chat/stream`; see
628
+ // the asymmetry note there.
629
+ `${this.chatApiBaseUrl}/api/v1/assistant/stream`, request, 'Assistant request failed', signal);
630
+ }
631
+ /**
632
+ * Fetch the chat-model registry from the backend. Returns Bedrock entries
633
+ * plus any locally-discovered Ollama models. Public endpoint — works
634
+ * before the user is authenticated.
635
+ */
636
+ async listChatModels() {
637
+ return this.chatRequest('/api/v1/chat/models');
638
+ }
639
+ // ==================== Platform Assistant reference API (R4b) ====================
640
+ // Read-only introspection backing the assistant's `describe_tool` /
641
+ // `list_platform_capabilities` tools + the host UI's field-name validation.
642
+ // All three live on the CHAT base URL (the assistant/reference router is
643
+ // mounted there, like `streamAssistant`) and reuse the same authed
644
+ // `chatRequest`/`requestJson` JSON helper as the other chat-base GETs (DRY —
645
+ // no forked fetch path; the Authorization header is attached iff a session
646
+ // token is set).
647
+ /**
648
+ * Fetch the drift-proof field schema for a named creator/admin form
649
+ * (`GET /api/v1/schema/{form}`). The backend derives every field from the
650
+ * form's PUBLIC Pydantic request model (`model_json_schema()`) so it can
651
+ * never drift from the real endpoint contract. The host UI uses this to
652
+ * validate which `propose_form_fields` suggestions are applicable; the
653
+ * assistant uses it to propose VALID field names. `form` is one of the
654
+ * registered ids (`personas` / `documents` / `adventures` / `images`);
655
+ * `scenes` is intentionally omitted and any unknown form returns 404
656
+ * (surfaced as a thrown Error).
657
+ */
658
+ async getFormSchema(form) {
659
+ return this.chatRequest(`/api/v1/schema/${encodeURIComponent(form)}`);
660
+ }
661
+ /**
662
+ * List every platform tool's human-readable reference
663
+ * (`GET /api/v1/tools/reference`). Derived server-side from the full
664
+ * `shared/tool_schemas` registry (`iter_all_tool_schemas` — chat + adventure
665
+ * + assistant), so the catalogue cannot drift from the live tool list.
666
+ */
667
+ async listToolReferences() {
668
+ return this.chatRequest('/api/v1/tools/reference');
669
+ }
670
+ /**
671
+ * Fetch one tool's reference by name
672
+ * (`GET /api/v1/tools/reference/{name}`). 404 (thrown Error) when the tool
673
+ * is unknown.
674
+ */
675
+ async getToolReference(name) {
676
+ return this.chatRequest(`/api/v1/tools/reference/${encodeURIComponent(name)}`);
677
+ }
268
678
  // ==================== Persona API Methods ====================
269
679
  // Note: Personas are served by the Chat API, not the Tools API
270
680
  /**
@@ -337,12 +747,27 @@ export class ApiClient {
337
747
  }
338
748
  // ==================== Image API Methods ====================
339
749
  // Note: Images are served by the Chat API
750
+ /**
751
+ * Fetch the image-model catalogue from the backend (R1c). Read-only.
752
+ * Unlike {@link listChatModels}, this endpoint is **authenticated** (its
753
+ * consumers — Studio Images, the Admin adapter inspector — are post-auth, so
754
+ * it is not a public pre-auth path); call it with a valid session. Served via
755
+ * the CHAT base URL (the images API is mounted on the chat app), so this uses
756
+ * `chatRequest`, NOT `toolsRequest`.
757
+ */
758
+ async listImageModels() {
759
+ return this.chatRequest('/api/v1/images/models');
760
+ }
340
761
  async listImages(params) {
341
762
  const searchParams = new URLSearchParams();
342
763
  if (params?.category)
343
764
  searchParams.append('category', params.category);
344
765
  if (params?.videoId)
345
766
  searchParams.append('videoId', params.videoId);
767
+ if (params?.model)
768
+ searchParams.append('model', params.model);
769
+ if (params?.status)
770
+ searchParams.append('status', params.status);
346
771
  if (params?.limit)
347
772
  searchParams.append('limit', params.limit.toString());
348
773
  if (params?.nextToken)
@@ -497,17 +922,7 @@ export class ApiClient {
497
922
  if (Date.now() >= deadline) {
498
923
  throw new Error(`Image generation timed out after ${Math.round(timeoutMs / 1000)}s`);
499
924
  }
500
- await new Promise((resolve, reject) => {
501
- const timer = setTimeout(() => {
502
- options.signal?.removeEventListener('abort', onAbort);
503
- resolve();
504
- }, intervalMs);
505
- const onAbort = () => {
506
- clearTimeout(timer);
507
- reject(new DOMException('Polling aborted', 'AbortError'));
508
- };
509
- options.signal?.addEventListener('abort', onAbort, { once: true });
510
- });
925
+ await abortableSleep(intervalMs, options.signal);
511
926
  }
512
927
  }
513
928
  // ==================== Chat Auth + Voices ====================
@@ -524,6 +939,21 @@ export class ApiClient {
524
939
  method: 'POST',
525
940
  });
526
941
  }
942
+ /**
943
+ * Mint WebRTC signaling credentials for a vision-publisher session.
944
+ *
945
+ * Returns either `local`-mode config (STUN-only; existing chat-WS
946
+ * signaling protocol) or `kvs`-mode config (SigV4-presigned wss://
947
+ * URL + short-term STUN/TURN). The publisher branches on `mode` —
948
+ * raw AWS credentials never reach the browser.
949
+ *
950
+ * Token TTL is short (~300s); callers running long-lived sessions
951
+ * should re-call this method before `expiresIn` elapses. The current
952
+ * VisionPublisher does NOT auto-refresh.
953
+ */
954
+ async getVisionRtcCredentials() {
955
+ return this.chatRequest('/api/v1/chat/vision-rtc/credentials', { method: 'POST' });
956
+ }
527
957
  /**
528
958
  * List available TTS voices. Backed by `GET /api/voices` — server
529
959
  * caches Inworld results for 5 min; pass `refresh: true` to bypass.
@@ -633,8 +1063,54 @@ export class ApiClient {
633
1063
  });
634
1064
  }
635
1065
  // ==================== Graph Editor API Methods ====================
636
- async getVideoGraph(videoId) {
637
- return this.request(`/api/v1/tools/graph/${encodeURIComponent(videoId)}`);
1066
+ /**
1067
+ * Fetch a video's subgraph. R5b: the optional `detail` arg selects the
1068
+ * server-side view — `GRAPH_DETAIL.STORY` for the collapsed story view,
1069
+ * `GRAPH_DETAIL.RAW` for the full extraction graph. Omitting it sends NO
1070
+ * query param (byte-identical to the pre-R5b request — the server defaults
1071
+ * to raw), so every existing caller is untouched.
1072
+ */
1073
+ async getVideoGraph(videoId, detail) {
1074
+ const base = `/api/v1/tools/graph/${encodeURIComponent(videoId)}`;
1075
+ const path = detail === undefined ? base : `${base}?detail=${encodeURIComponent(detail)}`;
1076
+ return this.request(path);
1077
+ }
1078
+ // ==================== Creator Studio / Story API Methods (M7 P7) ====================
1079
+ /**
1080
+ * List all stories (videos) visible to the caller. `storyId === videoId`
1081
+ * (1:1) in M7 P7 — the Story resource is a thin, read-only view over the
1082
+ * existing Video. No pagination/filter parameters in P7.
1083
+ */
1084
+ async listStories() {
1085
+ return this.request('/api/v1/stories');
1086
+ }
1087
+ /**
1088
+ * Fetch a single story's metadata + aggregate counts. Throws (404) when the
1089
+ * id resolves to no Video node.
1090
+ */
1091
+ async getStory(storyId) {
1092
+ return this.request(`/api/v1/stories/${encodeURIComponent(storyId)}`);
1093
+ }
1094
+ /**
1095
+ * Resolve a playable (presigned or local-stub) URL for a clip span via the
1096
+ * existing `POST /api/v1/tools/clip-lookup` tool endpoint. Used by the studio
1097
+ * Scene inspector to scope the player to a scene's `[t0, t1]`. Additive — never
1098
+ * remove/rename. Wire keys are camelCase (backend `BaseSchema`, no aliasing).
1099
+ */
1100
+ async clipLookup(params) {
1101
+ return this.request('/api/v1/tools/clip-lookup', {
1102
+ method: 'POST',
1103
+ body: JSON.stringify(params),
1104
+ });
1105
+ }
1106
+ /**
1107
+ * Fetch the live graph whitelist (node PKs + editable properties per label
1108
+ * and edge type). No auth required — pure metadata. Prefer the memoized
1109
+ * `fetchGraphSchema()` wrapper in `graphSchema.ts` over calling this per
1110
+ * render; the raw method exists for that wrapper and one-off callers.
1111
+ */
1112
+ async getGraphSchema() {
1113
+ return this.request('/api/v1/tools/graph/schema');
638
1114
  }
639
1115
  async updateGraphNode(data) {
640
1116
  return this.request('/api/v1/tools/graph/nodes', {
@@ -643,10 +1119,13 @@ export class ApiClient {
643
1119
  });
644
1120
  }
645
1121
  async deleteGraphNode(data) {
646
- return this.request('/api/v1/tools/graph/nodes', {
647
- method: 'DELETE',
648
- body: JSON.stringify(data),
1122
+ // DELETE carries no body — identifiers travel as query params (M7 P1a,
1123
+ // closes tech-debt #42). The backend derives the PK from the label.
1124
+ const params = new URLSearchParams({
1125
+ nodeLabel: data.nodeLabel,
1126
+ idValue: data.idValue,
649
1127
  });
1128
+ return this.request(`/api/v1/tools/graph/nodes?${params.toString()}`, { method: 'DELETE' });
650
1129
  }
651
1130
  async updateGraphEdge(data) {
652
1131
  return this.request('/api/v1/tools/graph/edges', {
@@ -655,8 +1134,38 @@ export class ApiClient {
655
1134
  });
656
1135
  }
657
1136
  async deleteGraphEdge(data) {
1137
+ // DELETE carries no body — identifiers travel as query params (M7 P1a,
1138
+ // closes tech-debt #42).
1139
+ const params = new URLSearchParams({
1140
+ sourceId: data.sourceId,
1141
+ targetId: data.targetId,
1142
+ relType: data.relType,
1143
+ });
1144
+ return this.request(`/api/v1/tools/graph/edges?${params.toString()}`, { method: 'DELETE' });
1145
+ }
1146
+ /**
1147
+ * Create a user-authored narrative node (Scene / PlotBeat / CharacterArc).
1148
+ * POST returns 201 with `{traceId, nodeId, properties}`; `makeRequest` parses
1149
+ * the body (only 204 is bodyless) and surfaces a 422 (e.g. label not
1150
+ * user-creatable, missing actId/index for a Scene) as a thrown `Error` with
1151
+ * the FastAPI detail. The backend stamps provenance/versionId/timestamps.
1152
+ */
1153
+ async createGraphNode(data) {
1154
+ return this.request('/api/v1/tools/graph/nodes', {
1155
+ method: 'POST',
1156
+ body: JSON.stringify(data),
1157
+ });
1158
+ }
1159
+ /**
1160
+ * Create a user-authored relationship (RELATES_TO / CAUSES / SET_IN /
1161
+ * FEATURES / ON_ARC / LEADS_TO). POST returns 201 with
1162
+ * `{traceId, edgeId, properties}`; a 422 (invalid endpoint-label pair,
1163
+ * pipeline-only type, cross-video endpoints, or SET_IN/FEATURES Entity.type
1164
+ * mismatch) surfaces as a thrown `Error` with the FastAPI detail.
1165
+ */
1166
+ async createGraphEdge(data) {
658
1167
  return this.request('/api/v1/tools/graph/edges', {
659
- method: 'DELETE',
1168
+ method: 'POST',
660
1169
  body: JSON.stringify(data),
661
1170
  });
662
1171
  }
@@ -878,17 +1387,7 @@ export class ApiClient {
878
1387
  if (Date.now() >= deadline) {
879
1388
  throw new Error(`Regeneration timed out after ${Math.round(timeoutMs / 1000)}s`);
880
1389
  }
881
- await new Promise((resolve, reject) => {
882
- const timer = setTimeout(() => {
883
- options.signal?.removeEventListener('abort', onAbort);
884
- resolve();
885
- }, intervalMs);
886
- const onAbort = () => {
887
- clearTimeout(timer);
888
- reject(new DOMException('Polling aborted', 'AbortError'));
889
- };
890
- options.signal?.addEventListener('abort', onAbort, { once: true });
891
- });
1390
+ await abortableSleep(intervalMs, options.signal);
892
1391
  }
893
1392
  }
894
1393
  /**
@@ -935,17 +1434,7 @@ export class ApiClient {
935
1434
  if (Date.now() >= deadline) {
936
1435
  throw new Error(`Bundle generation timed out after ${Math.round(timeoutMs / 1000)}s`);
937
1436
  }
938
- await new Promise((resolve, reject) => {
939
- const timer = setTimeout(() => {
940
- options.signal?.removeEventListener('abort', onAbort);
941
- resolve();
942
- }, intervalMs);
943
- const onAbort = () => {
944
- clearTimeout(timer);
945
- reject(new DOMException('Polling aborted', 'AbortError'));
946
- };
947
- options.signal?.addEventListener('abort', onAbort, { once: true });
948
- });
1437
+ await abortableSleep(intervalMs, options.signal);
949
1438
  }
950
1439
  }
951
1440
  // ==================== Reactor / Helios ====================
@@ -1019,6 +1508,17 @@ export class ApiClient {
1019
1508
  }
1020
1509
  return await response.blob();
1021
1510
  }
1511
+ /**
1512
+ * Fetch the default system prompt components from the Chat API.
1513
+ * Backed by `GET /api/v1/chat/system-prompt`.
1514
+ *
1515
+ * Authentication is required — the client must have a session token set.
1516
+ * Callers that need caching should wrap this in their own layer (see
1517
+ * `web/lib/systemPrompt.ts` which keeps a 5-minute in-memory cache).
1518
+ */
1519
+ async getSystemPrompt() {
1520
+ return this.chatRequest('/api/v1/chat/system-prompt');
1521
+ }
1022
1522
  /**
1023
1523
  * Knowledge-grounded prompt upsample — expands a short user prompt
1024
1524
  * into a Helios-quality 80-120 word paragraph using Bedrock. Routes
@@ -1036,5 +1536,93 @@ export class ApiClient {
1036
1536
  signal: options.signal,
1037
1537
  });
1038
1538
  }
1539
+ // ============= Adventure Runtime API (M9 Story Engine Phase 8a) =============
1540
+ /**
1541
+ * Start an interactive adventure for a story/video, driven by a
1542
+ * Dungeon-Master persona. `POST /api/v1/adventures` → 201 with the initial
1543
+ * {@link AdventureState} (and a `Location` header to the session's GET URL).
1544
+ *
1545
+ * Auth + video ownership are enforced server-side. `dmPersonaId` must
1546
+ * reference an owned persona whose `is_dungeon_master` is true (422 otherwise),
1547
+ * and a missing/unowned persona is a 404/403 — all surface as a thrown `Error`
1548
+ * carrying the FastAPI detail. Additive — never remove/rename.
1549
+ */
1550
+ async startAdventure(request, options = {}) {
1551
+ return this.request('/api/v1/adventures', {
1552
+ method: 'POST',
1553
+ body: JSON.stringify(request),
1554
+ signal: options.signal,
1555
+ });
1556
+ }
1557
+ /**
1558
+ * Fetch the current {@link AdventureState} for a session.
1559
+ * `GET /api/v1/adventures/{sessionId}` (404 when absent or not owned by the
1560
+ * caller — the store hides cross-tenant and soft-deleted sessions).
1561
+ */
1562
+ async getAdventure(sessionId, options = {}) {
1563
+ return this.request(`/api/v1/adventures/${encodeURIComponent(sessionId)}`, { signal: options.signal });
1564
+ }
1565
+ /**
1566
+ * List the caller's adventures, newest-first. `GET /api/v1/adventures` →
1567
+ * {@link ListAdventuresResponse}. Owner-scoped server-side (soft-deleted
1568
+ * sessions excluded); pass `storyId` to narrow to a single story. Additive —
1569
+ * never remove/rename.
1570
+ */
1571
+ async listAdventures(storyId, options = {}) {
1572
+ const searchParams = new URLSearchParams();
1573
+ if (storyId)
1574
+ searchParams.append('storyId', storyId);
1575
+ const query = searchParams.toString();
1576
+ const endpoint = `/api/v1/adventures${query ? `?${query}` : ''}`;
1577
+ return this.request(endpoint, {
1578
+ signal: options.signal,
1579
+ });
1580
+ }
1581
+ /**
1582
+ * Soft-delete an adventure session. `DELETE /api/v1/adventures/{sessionId}`
1583
+ * → 204 (resolves to `void`). A missing/unowned session is a 404 surfaced as
1584
+ * a thrown `Error`.
1585
+ */
1586
+ async deleteAdventure(sessionId, options = {}) {
1587
+ return this.request(`/api/v1/adventures/${encodeURIComponent(sessionId)}`, { method: 'DELETE', signal: options.signal });
1588
+ }
1589
+ /**
1590
+ * Mutate an adventure's party (M10 Story Engine Phase 9a).
1591
+ * `PATCH /api/v1/adventures/{sessionId}/party` with
1592
+ * `{ action, personaId }` → the updated {@link GetAdventureResponse}.
1593
+ * Shared by {@link addPartyMember} / {@link removePartyMember}; not exported
1594
+ * directly so call sites go through the action-specific wrappers. Additive —
1595
+ * never remove/rename.
1596
+ */
1597
+ patchParty(sessionId, request, options = {}) {
1598
+ return this.request(`/api/v1/adventures/${encodeURIComponent(sessionId)}/party`, {
1599
+ method: 'PATCH',
1600
+ body: JSON.stringify(request),
1601
+ signal: options.signal,
1602
+ });
1603
+ }
1604
+ /**
1605
+ * Add a character persona to an adventure's party (M10 Story Engine Phase
1606
+ * 9a). `PATCH /api/v1/adventures/{sessionId}/party` with `action='add'` →
1607
+ * the updated {@link GetAdventureResponse}. The persona must be owned by the
1608
+ * caller, bound to a character entity, and NOT a Dungeon Master (422
1609
+ * otherwise); a missing/unowned adventure is a 404 — all surface as a thrown
1610
+ * `Error` carrying the FastAPI detail. Server-side dedupe makes a repeat add
1611
+ * a no-op. Additive — never remove/rename.
1612
+ */
1613
+ async addPartyMember(sessionId, personaId, options = {}) {
1614
+ return this.patchParty(sessionId, { action: PARTY_ACTION.ADD, personaId }, options);
1615
+ }
1616
+ /**
1617
+ * Remove a character persona from an adventure's party (M10 Story Engine
1618
+ * Phase 9a). `PATCH /api/v1/adventures/{sessionId}/party` with
1619
+ * `action='remove'` → the updated {@link GetAdventureResponse}. Idempotent:
1620
+ * removing an absent member is a 200 no-op that returns the current state. A
1621
+ * missing/unowned adventure is a 404 surfaced as a thrown `Error`. Additive —
1622
+ * never remove/rename.
1623
+ */
1624
+ async removePartyMember(sessionId, personaId, options = {}) {
1625
+ return this.patchParty(sessionId, { action: PARTY_ACTION.REMOVE, personaId }, options);
1626
+ }
1039
1627
  }
1040
1628
  //# sourceMappingURL=api.js.map