@escapeaihq/client-core 0.12.0 → 0.49.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (242) hide show
  1. package/README.md +32 -7
  2. package/dist/adapters/capabilities.d.ts +10 -0
  3. package/dist/adapters/capabilities.d.ts.map +1 -0
  4. package/dist/adapters/capabilities.js +2 -0
  5. package/dist/adapters/capabilities.js.map +1 -0
  6. package/dist/adapters/chatAdapter.d.ts +38 -0
  7. package/dist/adapters/chatAdapter.d.ts.map +1 -0
  8. package/dist/adapters/chatAdapter.js +88 -0
  9. package/dist/adapters/chatAdapter.js.map +1 -0
  10. package/dist/adapters/directorAdapter.d.ts +62 -0
  11. package/dist/adapters/directorAdapter.d.ts.map +1 -0
  12. package/dist/adapters/directorAdapter.js +71 -0
  13. package/dist/adapters/directorAdapter.js.map +1 -0
  14. package/dist/adapters/imageAdapter.d.ts +44 -0
  15. package/dist/adapters/imageAdapter.d.ts.map +1 -0
  16. package/dist/adapters/imageAdapter.js +73 -0
  17. package/dist/adapters/imageAdapter.js.map +1 -0
  18. package/dist/adapters/index.d.ts +47 -0
  19. package/dist/adapters/index.d.ts.map +1 -0
  20. package/dist/adapters/index.js +41 -0
  21. package/dist/adapters/index.js.map +1 -0
  22. package/dist/adapters/registry.d.ts +98 -0
  23. package/dist/adapters/registry.d.ts.map +1 -0
  24. package/dist/adapters/registry.js +106 -0
  25. package/dist/adapters/registry.js.map +1 -0
  26. package/dist/adapters/worldAdapter.d.ts +142 -0
  27. package/dist/adapters/worldAdapter.d.ts.map +1 -0
  28. package/dist/adapters/worldAdapter.js +164 -0
  29. package/dist/adapters/worldAdapter.js.map +1 -0
  30. package/dist/admin.d.ts +323 -0
  31. package/dist/admin.d.ts.map +1 -0
  32. package/dist/admin.js +198 -0
  33. package/dist/admin.js.map +1 -0
  34. package/dist/api.d.ts +1512 -4
  35. package/dist/api.d.ts.map +1 -1
  36. package/dist/api.js +820 -52
  37. package/dist/api.js.map +1 -1
  38. package/dist/audio.d.ts +33 -1
  39. package/dist/audio.d.ts.map +1 -1
  40. package/dist/audio.js +4 -1
  41. package/dist/audio.js.map +1 -1
  42. package/dist/castProjection.d.ts +35 -0
  43. package/dist/castProjection.d.ts.map +1 -0
  44. package/dist/castProjection.js +80 -0
  45. package/dist/castProjection.js.map +1 -0
  46. package/dist/conversation/binding.d.ts +77 -0
  47. package/dist/conversation/binding.d.ts.map +1 -0
  48. package/dist/conversation/binding.js +57 -0
  49. package/dist/conversation/binding.js.map +1 -0
  50. package/dist/conversation/controller.d.ts +209 -0
  51. package/dist/conversation/controller.d.ts.map +1 -0
  52. package/dist/conversation/controller.js +350 -0
  53. package/dist/conversation/controller.js.map +1 -0
  54. package/dist/conversation/effectiveModel.d.ts +62 -0
  55. package/dist/conversation/effectiveModel.d.ts.map +1 -0
  56. package/dist/conversation/effectiveModel.js +73 -0
  57. package/dist/conversation/effectiveModel.js.map +1 -0
  58. package/dist/conversation/index.d.ts +27 -0
  59. package/dist/conversation/index.d.ts.map +1 -0
  60. package/dist/conversation/index.js +27 -0
  61. package/dist/conversation/index.js.map +1 -0
  62. package/dist/conversation/participant.d.ts +66 -0
  63. package/dist/conversation/participant.d.ts.map +1 -0
  64. package/dist/conversation/participant.js +36 -0
  65. package/dist/conversation/participant.js.map +1 -0
  66. package/dist/conversation/presence.d.ts +56 -0
  67. package/dist/conversation/presence.d.ts.map +1 -0
  68. package/dist/conversation/presence.js +34 -0
  69. package/dist/conversation/presence.js.map +1 -0
  70. package/dist/conversation/presenceBus.d.ts +42 -0
  71. package/dist/conversation/presenceBus.d.ts.map +1 -0
  72. package/dist/conversation/presenceBus.js +81 -0
  73. package/dist/conversation/presenceBus.js.map +1 -0
  74. package/dist/conversation/presenceRegistry.d.ts +49 -0
  75. package/dist/conversation/presenceRegistry.d.ts.map +1 -0
  76. package/dist/conversation/presenceRegistry.js +59 -0
  77. package/dist/conversation/presenceRegistry.js.map +1 -0
  78. package/dist/conversation/roster.d.ts +72 -0
  79. package/dist/conversation/roster.d.ts.map +1 -0
  80. package/dist/conversation/roster.js +69 -0
  81. package/dist/conversation/roster.js.map +1 -0
  82. package/dist/conversation/rosterProjection.d.ts +52 -0
  83. package/dist/conversation/rosterProjection.d.ts.map +1 -0
  84. package/dist/conversation/rosterProjection.js +74 -0
  85. package/dist/conversation/rosterProjection.js.map +1 -0
  86. package/dist/conversation/router.d.ts +74 -0
  87. package/dist/conversation/router.d.ts.map +1 -0
  88. package/dist/conversation/router.js +58 -0
  89. package/dist/conversation/router.js.map +1 -0
  90. package/dist/conversation/runtime.d.ts +64 -0
  91. package/dist/conversation/runtime.d.ts.map +1 -0
  92. package/dist/conversation/runtime.js +172 -0
  93. package/dist/conversation/runtime.js.map +1 -0
  94. package/dist/conversation/types.d.ts +99 -0
  95. package/dist/conversation/types.d.ts.map +1 -0
  96. package/dist/conversation/types.js +13 -0
  97. package/dist/conversation/types.js.map +1 -0
  98. package/dist/conversation/voice.d.ts +185 -0
  99. package/dist/conversation/voice.d.ts.map +1 -0
  100. package/dist/conversation/voice.js +307 -0
  101. package/dist/conversation/voice.js.map +1 -0
  102. package/dist/graphSchema.d.ts +201 -13
  103. package/dist/graphSchema.d.ts.map +1 -1
  104. package/dist/graphSchema.js +258 -9
  105. package/dist/graphSchema.js.map +1 -1
  106. package/dist/http.d.ts +20 -0
  107. package/dist/http.d.ts.map +1 -0
  108. package/dist/http.js +57 -0
  109. package/dist/http.js.map +1 -0
  110. package/dist/index.d.ts +6 -0
  111. package/dist/index.d.ts.map +1 -1
  112. package/dist/index.js +9 -0
  113. package/dist/index.js.map +1 -1
  114. package/dist/platformAssistant.d.ts +155 -0
  115. package/dist/platformAssistant.d.ts.map +1 -0
  116. package/dist/platformAssistant.js +256 -0
  117. package/dist/platformAssistant.js.map +1 -0
  118. package/dist/reactor/chunkDistribution.d.ts +43 -0
  119. package/dist/reactor/chunkDistribution.d.ts.map +1 -0
  120. package/dist/reactor/chunkDistribution.js +85 -0
  121. package/dist/reactor/chunkDistribution.js.map +1 -0
  122. package/dist/reactor/index.d.ts +2 -0
  123. package/dist/reactor/index.d.ts.map +1 -1
  124. package/dist/reactor/index.js +5 -0
  125. package/dist/reactor/index.js.map +1 -1
  126. package/dist/reactor/longLiveCommandDispatcher.d.ts +103 -0
  127. package/dist/reactor/longLiveCommandDispatcher.d.ts.map +1 -0
  128. package/dist/reactor/longLiveCommandDispatcher.js +87 -0
  129. package/dist/reactor/longLiveCommandDispatcher.js.map +1 -0
  130. package/dist/reactor/scenesFromEnrichment.d.ts.map +1 -1
  131. package/dist/reactor/scenesFromEnrichment.js +2 -66
  132. package/dist/reactor/scenesFromEnrichment.js.map +1 -1
  133. package/dist/reactor/seedImageOrchestrator.d.ts +6 -9
  134. package/dist/reactor/seedImageOrchestrator.d.ts.map +1 -1
  135. package/dist/reactor/seedImageOrchestrator.js +12 -13
  136. package/dist/reactor/seedImageOrchestrator.js.map +1 -1
  137. package/dist/reactor/storyTimeline.d.ts +44 -0
  138. package/dist/reactor/storyTimeline.d.ts.map +1 -0
  139. package/dist/reactor/storyTimeline.js +95 -0
  140. package/dist/reactor/storyTimeline.js.map +1 -0
  141. package/dist/storyGraph.d.ts +70 -0
  142. package/dist/storyGraph.d.ts.map +1 -0
  143. package/dist/storyGraph.js +178 -0
  144. package/dist/storyGraph.js.map +1 -0
  145. package/dist/vision/VisionSourceController.d.ts +127 -0
  146. package/dist/vision/VisionSourceController.d.ts.map +1 -0
  147. package/dist/vision/VisionSourceController.js +284 -0
  148. package/dist/vision/VisionSourceController.js.map +1 -0
  149. package/dist/vision/index.d.ts +4 -0
  150. package/dist/vision/index.d.ts.map +1 -1
  151. package/dist/vision/index.js +2 -0
  152. package/dist/vision/index.js.map +1 -1
  153. package/dist/vision/sourceKinds.d.ts +65 -0
  154. package/dist/vision/sourceKinds.d.ts.map +1 -0
  155. package/dist/vision/sourceKinds.js +26 -0
  156. package/dist/vision/sourceKinds.js.map +1 -0
  157. package/dist/websocket.d.ts +92 -0
  158. package/dist/websocket.d.ts.map +1 -1
  159. package/dist/websocket.js.map +1 -1
  160. package/package.json +1 -1
  161. package/src/__tests__/adapters-capabilities.test.ts +46 -0
  162. package/src/__tests__/adapters-chat.test.ts +172 -0
  163. package/src/__tests__/adapters-director.test.ts +95 -0
  164. package/src/__tests__/adapters-image.test.ts +133 -0
  165. package/src/__tests__/adapters-platform.test.ts +95 -0
  166. package/src/__tests__/adapters-registry.test.ts +189 -0
  167. package/src/__tests__/adapters-world.test.ts +296 -0
  168. package/src/__tests__/admin.test.ts +312 -0
  169. package/src/__tests__/adventures-party.test.ts +219 -0
  170. package/src/__tests__/adventures.test.ts +282 -0
  171. package/src/__tests__/api-pollers.test.ts +4 -0
  172. package/src/__tests__/api.clip-lookup.test.ts +64 -0
  173. package/src/__tests__/api.list-images-filters.test.ts +103 -0
  174. package/src/__tests__/api.test.ts +553 -0
  175. package/src/__tests__/audio.test.ts +65 -0
  176. package/src/__tests__/cast.test.ts +95 -0
  177. package/src/__tests__/castProjection.test.ts +167 -0
  178. package/src/__tests__/conversation/binding.test.ts +62 -0
  179. package/src/__tests__/conversation/controller.test.ts +732 -0
  180. package/src/__tests__/conversation/effectiveModel.test.ts +169 -0
  181. package/src/__tests__/conversation/headlessRenderer.ts +46 -0
  182. package/src/__tests__/conversation/presenceBus.test.ts +236 -0
  183. package/src/__tests__/conversation/presenceRegistry.test.ts +73 -0
  184. package/src/__tests__/conversation/roster.test.ts +100 -0
  185. package/src/__tests__/conversation/rosterProjection.test.ts +142 -0
  186. package/src/__tests__/conversation/router.test.ts +81 -0
  187. package/src/__tests__/conversation/runtime.test.ts +206 -0
  188. package/src/__tests__/conversation/voice.test.ts +440 -0
  189. package/src/__tests__/documents.test.ts +360 -0
  190. package/src/__tests__/graphSchema.test.ts +218 -9
  191. package/src/__tests__/longLiveCommandDispatcher.test.ts +185 -0
  192. package/src/__tests__/monitoring.test.ts +162 -0
  193. package/src/__tests__/persona-generation.test.ts +352 -0
  194. package/src/__tests__/platformAssistant.test.ts +484 -0
  195. package/src/__tests__/reactor/storyTimeline.test.ts +186 -0
  196. package/src/__tests__/regeneration.test.ts +486 -0
  197. package/src/__tests__/stories.test.ts +171 -0
  198. package/src/__tests__/storyGraph.test.ts +134 -0
  199. package/src/__tests__/tools-wrappers.test.ts +272 -0
  200. package/src/__tests__/videoGraph.test.ts +94 -0
  201. package/src/__tests__/websocket.test.ts +263 -0
  202. package/src/adapters/capabilities.ts +24 -0
  203. package/src/adapters/chatAdapter.ts +114 -0
  204. package/src/adapters/directorAdapter.ts +126 -0
  205. package/src/adapters/imageAdapter.ts +100 -0
  206. package/src/adapters/index.ts +67 -0
  207. package/src/adapters/registry.ts +159 -0
  208. package/src/adapters/worldAdapter.ts +272 -0
  209. package/src/admin.ts +517 -0
  210. package/src/api.ts +2215 -95
  211. package/src/audio.ts +35 -0
  212. package/src/castProjection.ts +95 -0
  213. package/src/conversation/binding.ts +100 -0
  214. package/src/conversation/controller.ts +447 -0
  215. package/src/conversation/effectiveModel.ts +111 -0
  216. package/src/conversation/index.ts +27 -0
  217. package/src/conversation/participant.ts +71 -0
  218. package/src/conversation/presence.ts +60 -0
  219. package/src/conversation/presenceBus.ts +109 -0
  220. package/src/conversation/presenceRegistry.ts +83 -0
  221. package/src/conversation/roster.ts +111 -0
  222. package/src/conversation/rosterProjection.ts +98 -0
  223. package/src/conversation/router.ts +96 -0
  224. package/src/conversation/runtime.ts +188 -0
  225. package/src/conversation/types.ts +100 -0
  226. package/src/conversation/voice.ts +402 -0
  227. package/src/graphSchema.ts +396 -13
  228. package/src/http.ts +72 -0
  229. package/src/index.ts +9 -0
  230. package/src/platformAssistant.ts +347 -0
  231. package/src/reactor/chunkDistribution.ts +98 -0
  232. package/src/reactor/index.ts +5 -0
  233. package/src/reactor/longLiveCommandDispatcher.ts +156 -0
  234. package/src/reactor/scenesFromEnrichment.ts +11 -76
  235. package/src/reactor/seedImageOrchestrator.ts +12 -13
  236. package/src/reactor/storyTimeline.ts +127 -0
  237. package/src/storyGraph.ts +298 -0
  238. package/src/vision/VisionSourceController.ts +354 -0
  239. package/src/vision/__tests__/VisionSourceController.test.ts +719 -0
  240. package/src/vision/index.ts +13 -0
  241. package/src/vision/sourceKinds.ts +75 -0
  242. package/src/websocket.ts +99 -3
package/dist/api.js CHANGED
@@ -2,6 +2,7 @@
2
2
  * API client for the Seer Agent backend
3
3
  */
4
4
  import { isAbortError } from './reactor/abortUtils.js';
5
+ import { requestJson } from './http.js';
5
6
  /**
6
7
  * Module-private helper: resolves after `ms` milliseconds, or rejects with
7
8
  * an AbortError if the optional `signal` fires before the timer expires.
@@ -30,6 +31,154 @@ export const ENRICHMENT_STATUS_QUEUED = 'QUEUED';
30
31
  export const ENRICHMENT_STATUS_RUNNING = 'RUNNING';
31
32
  export const ENRICHMENT_STATUS_SUCCEEDED = 'SUCCEEDED';
32
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
+ };
43
+ /**
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.
48
+ */
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;
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
+ /** Thrown by {@link ApiClient.reclonePersona} on a ``409`` so the review UI can
141
+ * distinguish "retries exhausted" from "no clips left" and disable the Reclone
142
+ * control (instead of seeing an opaque ``[object Object]`` message). */
143
+ export class RecloneConflictError extends Error {
144
+ code;
145
+ attempts;
146
+ constructor(code, attempts) {
147
+ super(code === 'voice_clone_max_retries_exhausted'
148
+ ? 'No reclone attempts remaining'
149
+ : 'No unused voice clips remain to reclone from');
150
+ this.name = 'RecloneConflictError';
151
+ this.code = code;
152
+ this.attempts = attempts;
153
+ }
154
+ }
155
+ /**
156
+ * Detail level for the video-graph read (Platform Restructure R5b). Mirrors
157
+ * `shared/graph_schema.py`'s `GraphDetail` — the single source of the
158
+ * `story`/`raw` mode literals (constants over bare strings; consumers compare
159
+ * against `GRAPH_DETAIL.*`, never a raw literal).
160
+ *
161
+ * - `RAW` (the server default — omitting the `detail` arg keeps the request
162
+ * byte-identical to the pre-R5b call): the full extraction subgraph.
163
+ * - `STORY`: the curated story view — Acts, Scenes (each Scene node's
164
+ * `properties` carries a read-time `shotCount`), the character cast,
165
+ * document contributions, and narrative edges; Shot/DialogLine/Event nodes
166
+ * and MENTIONS edges are collapsed server-side.
167
+ */
168
+ export const GRAPH_DETAIL = {
169
+ STORY: 'story',
170
+ RAW: 'raw',
171
+ };
172
+ /**
173
+ * The two `action` values accepted by `PATCH /api/v1/adventures/{sessionId}/party`
174
+ * (M10 Story Engine Phase 9a). `add` appends a character persona to the party
175
+ * (validated + deduped server-side); `remove` is an idempotent no-op when the
176
+ * persona is absent. Named constant so call sites never hard-code the literals.
177
+ */
178
+ export const PARTY_ACTION = {
179
+ ADD: 'add',
180
+ REMOVE: 'remove',
181
+ };
33
182
  export class ApiClient {
34
183
  baseURL;
35
184
  sessionToken;
@@ -49,45 +198,10 @@ export class ApiClient {
49
198
  return this.makeRequest(this.chatApiBaseUrl, endpoint, options);
50
199
  }
51
200
  async makeRequest(baseUrl, endpoint, options = {}) {
52
- const url = `${baseUrl}${endpoint}`;
53
- const headers = {
54
- 'Content-Type': 'application/json',
55
- ...options.headers,
56
- };
57
- // Add authorization header if session token is available
58
- if (this.sessionToken) {
59
- headers['Authorization'] = `Bearer ${this.sessionToken}`;
60
- }
61
- try {
62
- const response = await fetch(url, {
63
- ...options,
64
- headers,
65
- });
66
- if (!response.ok) {
67
- const error = await response.json().catch(() => ({
68
- detail: `HTTP ${response.status}: ${response.statusText}`,
69
- }));
70
- // FastAPI 422 returns detail as an array of validation errors
71
- const detail = error.detail;
72
- let message;
73
- if (Array.isArray(detail)) {
74
- message = detail.map((e) => e.msg ? `${(e.loc || []).slice(-1).join('.')}: ${e.msg}` : String(e)).join('; ');
75
- }
76
- else {
77
- message = detail || `Request failed: ${response.status}`;
78
- }
79
- throw new Error(message);
80
- }
81
- // 204 No Content returns no body
82
- if (response.status === 204) {
83
- return undefined;
84
- }
85
- return await response.json();
86
- }
87
- catch (error) {
88
- console.error('API request failed:', error);
89
- throw error;
90
- }
201
+ // Delegates to the shared `requestJson` helper (bearer auth + FastAPI error
202
+ // shaping) so `ApiClient` and the additive `AdminClient` share one fetch
203
+ // wrapper — behavior is identical to the prior inline implementation.
204
+ return requestJson(baseUrl, endpoint, this.sessionToken, options);
91
205
  }
92
206
  /**
93
207
  * List all ingestion jobs with optional filtering
@@ -123,6 +237,27 @@ export class ApiClient {
123
237
  const endpoint = `/api/v1/tools/videos${query ? `?${query}` : ''}`;
124
238
  return this.request(endpoint);
125
239
  }
240
+ /**
241
+ * Story Engine Phase 5 — list character entities for a video. Backs the
242
+ * persona↔character binding selector. Returns only ``Entity`` nodes with
243
+ * ``type === 'character'`` for the given video. Auth + video ownership are
244
+ * enforced server-side (caller must own the video). Uses the main API base
245
+ * (the tools routes use ``request``, not ``chatRequest``).
246
+ */
247
+ async listVideoCharacters(videoId) {
248
+ return this.request(`/api/v1/tools/videos/${encodeURIComponent(videoId)}/characters`);
249
+ }
250
+ /**
251
+ * Platform Restructure R5a — fetch a video's character cast pre-joined to
252
+ * each character's bound persona in ONE round-trip (the server resolves the
253
+ * PORTRAYS binding + hydrates persona display fields). The one-call
254
+ * replacement for the CastGrid's `getVideoGraph` + `listPersonas` client-side
255
+ * `entity_id` join (the R5c rewire consumes this). Auth + video ownership are
256
+ * enforced server-side. Tools API base (`request`, not `chatRequest`).
257
+ */
258
+ async getCast(videoId) {
259
+ return this.request(`/api/v1/tools/videos/${encodeURIComponent(videoId)}/cast`);
260
+ }
126
261
  /**
127
262
  * List staged videos in the ingestion bucket
128
263
  */
@@ -245,12 +380,246 @@ export class ApiClient {
245
380
  method: 'DELETE',
246
381
  });
247
382
  }
383
+ // ============= Narrative Regeneration API (M7 Phase 6 / Story Engine) =============
248
384
  /**
249
- * Stream chat responses with Server-Sent Events
250
- * Returns a ReadableStreamDefaultReader for processing SSE events
385
+ * Start an async narrative regeneration run for a video scope.
386
+ * `POST /api/v1/tools/graph/{videoId}/regenerate` → 202 with the QUEUED run
387
+ * (and a `Location` header to the run's poll URL, exposed as `statusUrl`).
388
+ *
389
+ * Auth + ownership are enforced server-side. A malformed `scope` is a 422,
390
+ * an in-flight run is a 409, over-cap is a 429 — all surface as a thrown
391
+ * `Error` carrying the FastAPI detail. Build `request.scope` with
392
+ * {@link buildRegenerationScope}. Pair with {@link pollRegenerationUntilDone}.
251
393
  */
252
- async streamChat(request, signal) {
253
- const url = `${this.chatApiBaseUrl}/api/chat/stream`;
394
+ async startRegeneration(videoId, request) {
395
+ return this.request(`/api/v1/tools/graph/${encodeURIComponent(videoId)}/regenerate`, {
396
+ method: 'POST',
397
+ body: JSON.stringify(request),
398
+ });
399
+ }
400
+ /**
401
+ * List a video's regeneration runs, newest-first.
402
+ * `GET /api/v1/tools/graph/{videoId}/regenerations`. `limit` (1–100) and
403
+ * `cursor` (opaque pagination token from a prior `nextCursor`) are optional.
404
+ */
405
+ async listRegenerations(videoId, params) {
406
+ const searchParams = new URLSearchParams();
407
+ if (params?.limit != null)
408
+ searchParams.append('limit', params.limit.toString());
409
+ if (params?.cursor)
410
+ searchParams.append('cursor', params.cursor);
411
+ const query = searchParams.toString();
412
+ const endpoint = `/api/v1/tools/graph/${encodeURIComponent(videoId)}/regenerations${query ? `?${query}` : ''}`;
413
+ return this.request(endpoint);
414
+ }
415
+ /**
416
+ * Fetch a single regeneration run by id.
417
+ * `GET /api/v1/tools/graph/{videoId}/regenerations/{runId}` (404 if absent).
418
+ * `signal` aborts the in-flight fetch — {@link pollRegenerationUntilDone}
419
+ * threads its poll signal through so a page unmount cancels cleanly.
420
+ */
421
+ async getRegeneration(videoId, runId, options = {}) {
422
+ return this.request(`/api/v1/tools/graph/${encodeURIComponent(videoId)}/regenerations/${encodeURIComponent(runId)}`, { signal: options.signal });
423
+ }
424
+ /**
425
+ * Poll {@link getRegeneration} until the run reaches a terminal status.
426
+ * COMPLETE / CANCELLED resolve with the final run; FAILED throws
427
+ * (`record.error` ?? a generic message). Mirrors
428
+ * {@link pollVisemeBundleUntilDone}: 5s cadence, abortable via `signal`,
429
+ * and a wall-clock timeout (regeneration re-invokes Pegasus, so the default
430
+ * matches bundle assembly — generous but bounded).
431
+ */
432
+ async pollRegenerationUntilDone(videoId, runId, options = {}) {
433
+ const intervalMs = options.intervalMs ?? 5000;
434
+ // The regenerator Lambda can run up to its 15-min cap (an `acts` scope re-runs
435
+ // Pegasus over the whole film), so the default poll deadline must exceed that or
436
+ // the client gives up while the run is still completing. 16 min covers a normal
437
+ // single run; if the poll still times out (e.g. an SQS redelivery), the run row
438
+ // is durable — a refresh / re-fetch surfaces the terminal state.
439
+ const timeoutMs = options.timeoutMs ?? 960_000;
440
+ const deadline = Date.now() + timeoutMs;
441
+ while (true) {
442
+ if (options.signal?.aborted) {
443
+ throw new DOMException('Polling aborted', 'AbortError');
444
+ }
445
+ const record = await this.getRegeneration(videoId, runId, {
446
+ signal: options.signal,
447
+ });
448
+ if (record.status === REGENERATION_STATUS.COMPLETE ||
449
+ record.status === REGENERATION_STATUS.CANCELLED) {
450
+ return record;
451
+ }
452
+ if (record.status === REGENERATION_STATUS.FAILED) {
453
+ throw new Error(record.error ?? 'Regeneration failed');
454
+ }
455
+ if (Date.now() >= deadline) {
456
+ throw new Error(`Regeneration timed out after ${Math.round(timeoutMs / 1000)}s`);
457
+ }
458
+ await abortableSleep(intervalMs, options.signal);
459
+ }
460
+ }
461
+ // ==================== Source Document API (M7 Phase 4) ====================
462
+ /**
463
+ * Upload a source document (script / notes / bible / transcript) with
464
+ * progress tracking. Mirrors {@link uploadVideo}: multipart XHR so the
465
+ * browser reports upload progress (fetch cannot). The `meta` fields ride
466
+ * alongside the file as a JSON `payload` part. Returns 201 with
467
+ * `{ traceId, docId, statusUrl }`; the backend enqueues
468
+ * `document-processing-queue` to parse + extract suggestions.
469
+ */
470
+ async uploadDocument(file, meta, onProgress) {
471
+ const url = `${this.baseURL}/api/v1/ingestion/documents`;
472
+ return new Promise((resolve, reject) => {
473
+ const xhr = new XMLHttpRequest();
474
+ // Track upload progress
475
+ if (onProgress) {
476
+ xhr.upload.addEventListener('progress', (e) => {
477
+ if (e.lengthComputable) {
478
+ onProgress({
479
+ loaded: e.loaded,
480
+ total: e.total,
481
+ percentage: Math.round((e.loaded / e.total) * 100),
482
+ });
483
+ }
484
+ });
485
+ }
486
+ // Handle completion
487
+ xhr.addEventListener('load', () => {
488
+ if (xhr.status >= 200 && xhr.status < 300) {
489
+ try {
490
+ const response = JSON.parse(xhr.responseText);
491
+ resolve(response);
492
+ }
493
+ catch {
494
+ reject(new Error('Failed to parse upload response'));
495
+ }
496
+ }
497
+ else {
498
+ try {
499
+ const errorData = JSON.parse(xhr.responseText);
500
+ reject(new Error(errorData.detail || `Upload failed: ${xhr.status}`));
501
+ }
502
+ catch {
503
+ reject(new Error(`Upload failed: ${xhr.status} ${xhr.statusText}`));
504
+ }
505
+ }
506
+ });
507
+ // Handle errors
508
+ xhr.addEventListener('error', () => {
509
+ reject(new Error('Upload failed due to network error'));
510
+ });
511
+ xhr.addEventListener('abort', () => {
512
+ reject(new Error('Upload aborted'));
513
+ });
514
+ // Prepare form data — file part + JSON metadata part.
515
+ const formData = new FormData();
516
+ formData.append('upload', file);
517
+ formData.append('payload', JSON.stringify(meta));
518
+ // Send request
519
+ xhr.open('POST', url);
520
+ // Add authorization header if session token is available
521
+ if (this.sessionToken) {
522
+ xhr.setRequestHeader('Authorization', `Bearer ${this.sessionToken}`);
523
+ }
524
+ xhr.send(formData);
525
+ });
526
+ }
527
+ /**
528
+ * List source documents, optionally scoped to a video or series. Mirrors
529
+ * {@link listJobs} query-param handling. GET `/api/v1/ingestion/documents`.
530
+ */
531
+ async listDocuments(params) {
532
+ const searchParams = new URLSearchParams();
533
+ if (params?.videoId)
534
+ searchParams.append('videoId', params.videoId);
535
+ if (params?.seriesId)
536
+ searchParams.append('seriesId', params.seriesId);
537
+ if (params?.limit)
538
+ searchParams.append('limit', params.limit.toString());
539
+ if (params?.nextToken)
540
+ searchParams.append('nextToken', params.nextToken);
541
+ const query = searchParams.toString();
542
+ const endpoint = `/api/v1/ingestion/documents${query ? `?${query}` : ''}`;
543
+ return this.request(endpoint);
544
+ }
545
+ /**
546
+ * Fetch a single document plus its pending/resolved graph suggestions.
547
+ * GET `/api/v1/ingestion/documents/{docId}`.
548
+ */
549
+ async getDocument(docId) {
550
+ return this.request(`/api/v1/ingestion/documents/${docId}`);
551
+ }
552
+ /**
553
+ * Accept a pipeline-extracted graph suggestion — writes the proposed
554
+ * node/edge with provenance `document`. POST returns 201 with
555
+ * `{ traceId, suggestionId, graphId }` (`graphId` is the composite id of the
556
+ * created node/edge); a 422 (e.g. already resolved, or the payload fails
557
+ * graph validation) surfaces the FastAPI detail as a thrown `Error`. POST
558
+ * `.../documents/{docId}/suggestions/{sid}/accept`.
559
+ *
560
+ * `acceptAsNew` (R5d homonym override): accept a same-named character as a
561
+ * DISTINCT character, skipping de-dup reconciliation and recording a "these
562
+ * are different" override so the oracle never auto-merges the pair. Omitted
563
+ * (the default) sends a body-less POST, byte-identical to the legacy accept.
564
+ */
565
+ async acceptSuggestion(docId, suggestionId, options) {
566
+ const init = { method: 'POST' };
567
+ if (options?.acceptAsNew) {
568
+ init.body = JSON.stringify({ acceptAsNew: true });
569
+ }
570
+ return this.request(`/api/v1/ingestion/documents/${docId}/suggestions/${suggestionId}/accept`, init);
571
+ }
572
+ /**
573
+ * Mark two entities as DIFFERENT characters (R5d homonym override) so the
574
+ * de-dup oracle never reconciles them. `docentId` is the document-authored
575
+ * (`docent-`) entity, `entityId` the Pegasus character to keep separate.
576
+ * POST `/api/v1/tools/graph/entities/distinct` → 201.
577
+ */
578
+ async markEntitiesDistinct(args) {
579
+ return this.request(`/api/v1/tools/graph/entities/distinct`, { method: 'POST', body: JSON.stringify(args) });
580
+ }
581
+ /**
582
+ * Clear a distinctness override (re-arms the de-dup oracle for the pair).
583
+ * Idempotent — `cleared` is `false` when no override existed. DELETE
584
+ * `/api/v1/tools/graph/entities/distinct?videoId&docentId&entityId`.
585
+ */
586
+ async clearEntitiesDistinct(args) {
587
+ const params = new URLSearchParams({
588
+ videoId: args.videoId,
589
+ docentId: args.docentId,
590
+ entityId: args.entityId,
591
+ });
592
+ return this.request(`/api/v1/tools/graph/entities/distinct?${params.toString()}`, { method: 'DELETE' });
593
+ }
594
+ /**
595
+ * Reject a pipeline-extracted graph suggestion (marks it `rejected`, writes
596
+ * nothing to the graph). Returns 204 (no body). POST
597
+ * `.../documents/{docId}/suggestions/{sid}/reject`.
598
+ */
599
+ async rejectSuggestion(docId, suggestionId) {
600
+ return this.request(`/api/v1/ingestion/documents/${docId}/suggestions/${suggestionId}/reject`, { method: 'POST' });
601
+ }
602
+ /**
603
+ * Delete a source document and its associated data. Returns 204 (no body).
604
+ * DELETE `/api/v1/ingestion/documents/{docId}`.
605
+ */
606
+ async deleteDocument(docId) {
607
+ return this.request(`/api/v1/ingestion/documents/${docId}`, {
608
+ method: 'DELETE',
609
+ });
610
+ }
611
+ /**
612
+ * Shared SSE body-reader for the chat + assistant stream endpoints.
613
+ * POSTs the JSON `body` to `url` (with the auth header when a session
614
+ * token is set) and returns the response's `ReadableStreamDefaultReader`
615
+ * for the caller to decode. `streamChat` and `streamAssistant` differ
616
+ * ONLY by URL + body, so they both route through here — there is exactly
617
+ * one fetch/reader/decoder plumbing (DRY; R4a reviewer flag).
618
+ *
619
+ * `errorPrefix` only shapes the fallback message when the backend
620
+ * returns a non-2xx without a `detail` field.
621
+ */
622
+ async readSseStream(url, body, errorPrefix, signal) {
254
623
  const headers = {
255
624
  'Content-Type': 'application/json',
256
625
  };
@@ -261,14 +630,14 @@ export class ApiClient {
261
630
  const response = await fetch(url, {
262
631
  method: 'POST',
263
632
  headers,
264
- body: JSON.stringify(request),
633
+ body: JSON.stringify(body),
265
634
  signal,
266
635
  });
267
636
  if (!response.ok) {
268
637
  const error = await response.json().catch(() => ({
269
638
  detail: `HTTP ${response.status}: ${response.statusText}`,
270
639
  }));
271
- throw new Error(error.detail || `Chat request failed: ${response.status}`);
640
+ throw new Error(error.detail || `${errorPrefix}: ${response.status}`);
272
641
  }
273
642
  const reader = response.body?.getReader();
274
643
  if (!reader) {
@@ -276,6 +645,35 @@ export class ApiClient {
276
645
  }
277
646
  return reader;
278
647
  }
648
+ /**
649
+ * Stream chat responses with Server-Sent Events
650
+ * Returns a ReadableStreamDefaultReader for processing SSE events
651
+ */
652
+ async streamChat(request, signal) {
653
+ return this.readSseStream(
654
+ // Deliberate URL asymmetry vs streamAssistant: chat is the LEGACY,
655
+ // UNVERSIONED route (`/api/chat/stream`, no `/v1/`) while assistant is
656
+ // the NEW VERSIONED route (`/api/v1/assistant/stream`). Keep both as-is —
657
+ // a future versioning refactor should not "normalize" chat to `/v1/`
658
+ // without coordinating the backend route, which still serves the legacy path.
659
+ `${this.chatApiBaseUrl}/api/chat/stream`, request, 'Chat request failed', signal);
660
+ }
661
+ /**
662
+ * Stream Platform Assistant (R4) responses with Server-Sent Events.
663
+ * Sibling of {@link streamChat} hitting `POST /api/v1/assistant/stream`
664
+ * — reuses the exact same SSE reader/decoder plumbing via
665
+ * {@link readSseStream}. Decode each `data: {…}` line into an
666
+ * {@link AssistantStreamEvent} (the stream may carry the additive
667
+ * `suggestion` variant). The assistant is out-of-world: the request
668
+ * carries `routeContext` instead of `videoId`.
669
+ */
670
+ async streamAssistant(request, signal) {
671
+ return this.readSseStream(
672
+ // NEW VERSIONED route (`/api/v1/assistant/stream`) — intentionally
673
+ // differs from streamChat's legacy unversioned `/api/chat/stream`; see
674
+ // the asymmetry note there.
675
+ `${this.chatApiBaseUrl}/api/v1/assistant/stream`, request, 'Assistant request failed', signal);
676
+ }
279
677
  /**
280
678
  * Fetch the chat-model registry from the backend. Returns Bedrock entries
281
679
  * plus any locally-discovered Ollama models. Public endpoint — works
@@ -284,6 +682,45 @@ export class ApiClient {
284
682
  async listChatModels() {
285
683
  return this.chatRequest('/api/v1/chat/models');
286
684
  }
685
+ // ==================== Platform Assistant reference API (R4b) ====================
686
+ // Read-only introspection backing the assistant's `describe_tool` /
687
+ // `list_platform_capabilities` tools + the host UI's field-name validation.
688
+ // All three live on the CHAT base URL (the assistant/reference router is
689
+ // mounted there, like `streamAssistant`) and reuse the same authed
690
+ // `chatRequest`/`requestJson` JSON helper as the other chat-base GETs (DRY —
691
+ // no forked fetch path; the Authorization header is attached iff a session
692
+ // token is set).
693
+ /**
694
+ * Fetch the drift-proof field schema for a named creator/admin form
695
+ * (`GET /api/v1/schema/{form}`). The backend derives every field from the
696
+ * form's PUBLIC Pydantic request model (`model_json_schema()`) so it can
697
+ * never drift from the real endpoint contract. The host UI uses this to
698
+ * validate which `propose_form_fields` suggestions are applicable; the
699
+ * assistant uses it to propose VALID field names. `form` is one of the
700
+ * registered ids (`personas` / `documents` / `adventures` / `images`);
701
+ * `scenes` is intentionally omitted and any unknown form returns 404
702
+ * (surfaced as a thrown Error).
703
+ */
704
+ async getFormSchema(form) {
705
+ return this.chatRequest(`/api/v1/schema/${encodeURIComponent(form)}`);
706
+ }
707
+ /**
708
+ * List every platform tool's human-readable reference
709
+ * (`GET /api/v1/tools/reference`). Derived server-side from the full
710
+ * `shared/tool_schemas` registry (`iter_all_tool_schemas` — chat + adventure
711
+ * + assistant), so the catalogue cannot drift from the live tool list.
712
+ */
713
+ async listToolReferences() {
714
+ return this.chatRequest('/api/v1/tools/reference');
715
+ }
716
+ /**
717
+ * Fetch one tool's reference by name
718
+ * (`GET /api/v1/tools/reference/{name}`). 404 (thrown Error) when the tool
719
+ * is unknown.
720
+ */
721
+ async getToolReference(name) {
722
+ return this.chatRequest(`/api/v1/tools/reference/${encodeURIComponent(name)}`);
723
+ }
287
724
  // ==================== Persona API Methods ====================
288
725
  // Note: Personas are served by the Chat API, not the Tools API
289
726
  /**
@@ -296,7 +733,13 @@ export class ApiClient {
296
733
  });
297
734
  }
298
735
  /**
299
- * List all personas for the current user
736
+ * List all personas for the current user.
737
+ *
738
+ * When ``sourceVideoId`` is set (C3a), the backend delegates to
739
+ * ``PersonaStore.list_personas_by_video`` and returns ALL personas
740
+ * auto-generated from that video in one shot (it paginates internally), so
741
+ * ``limit`` / ``nextToken`` do not apply and the response ``next_token`` is
742
+ * always ``null``. See {@link listPersonasByVideo} for the convenience wrapper.
300
743
  */
301
744
  async listPersonas(params) {
302
745
  const searchParams = new URLSearchParams();
@@ -306,10 +749,21 @@ export class ApiClient {
306
749
  searchParams.append('nextToken', params.nextToken);
307
750
  if (params?.status)
308
751
  searchParams.append('status', params.status);
752
+ // Wire param is snake_case (matches the backend Query alias).
753
+ if (params?.sourceVideoId)
754
+ searchParams.append('source_video_id', params.sourceVideoId);
309
755
  const query = searchParams.toString();
310
756
  const endpoint = `/api/v1/personas${query ? `?${query}` : ''}`;
311
757
  return this.chatRequest(endpoint);
312
758
  }
759
+ /**
760
+ * C3a: list the personas auto-generated from a given source video. Thin
761
+ * wrapper over {@link listPersonas} with ``sourceVideoId`` — backs the review
762
+ * page's roster + the "Auto"/"Pending" badges on the personas list.
763
+ */
764
+ async listPersonasByVideo(sourceVideoId) {
765
+ return this.listPersonas({ sourceVideoId });
766
+ }
313
767
  /**
314
768
  * Get the default persona for the current user
315
769
  */
@@ -354,14 +808,161 @@ export class ApiClient {
354
808
  }),
355
809
  });
356
810
  }
811
+ // ============ C3a persona-generation (auto-generate + job tracking) ============
812
+ // Back the trigger entry point + job-progress polling + settings UI
813
+ // (spec Steps 11–14) plus the review page's audition + reclone controls
814
+ // (spec Step 13). The audition/reclone backend routes landed with tech-debt
815
+ // #477 (PR #356), so the matching client methods live below getPersonaJob.
816
+ /**
817
+ * C3a: fetch the current user's persona-generation settings, or ``null`` when
818
+ * never saved (the settings UI then falls back to its client-side defaults).
819
+ * ``GET /api/v1/personas/settings/generation``.
820
+ */
821
+ async getPersonaGenSettings() {
822
+ return this.chatRequest('/api/v1/personas/settings/generation');
823
+ }
824
+ /**
825
+ * C3a: upsert the user's persona-generation settings. The body is a partial —
826
+ * supplied (non-null) fields merge over the stored (or default) settings; the
827
+ * response is the persisted, fully-populated settings. ``user_id`` /
828
+ * ``updated_at`` are store-managed. ``PUT /api/v1/personas/settings/generation``.
829
+ */
830
+ async updatePersonaGenSettings(body) {
831
+ return this.chatRequest('/api/v1/personas/settings/generation', {
832
+ method: 'PUT',
833
+ headers: { 'Content-Type': 'application/json' },
834
+ body: JSON.stringify(body),
835
+ });
836
+ }
837
+ /**
838
+ * C3a: trigger auto-generation of personas for a video. Returns a ``202`` job
839
+ * envelope (``{ jobId, status, traceId }`` — camelCase wire keys). Idempotent
840
+ * on ``(user, video)``: a second call while a job is still active returns that
841
+ * job's id instead of spawning a duplicate. Poll {@link getPersonaJob} with the
842
+ * returned ``jobId``. ``POST /api/v1/videos/{videoId}/personas/generate``.
843
+ *
844
+ * C3a-f1 (Studio Cast): pass ``opts.entityIds`` to restrict generation to a
845
+ * character-Entity-id subset — a per-cast-member "Generate persona" sends that
846
+ * one id; the Cast "Generate all" sends the whole cast (or omits it). Omitting
847
+ * ``entityIds`` (or passing an empty list) generates for every qualifying
848
+ * speaking character — byte-identical to the original whole-video call, so the
849
+ * body is only sent when a non-empty subset is supplied.
850
+ */
851
+ async generatePersonasForVideo(videoId, opts) {
852
+ const entityIds = opts?.entityIds?.filter(Boolean) ?? [];
853
+ const init = { method: 'POST' };
854
+ if (entityIds.length > 0) {
855
+ // The backend body is snake_case (no aliases) — mirror the
856
+ // GeneratePersonasRequest Pydantic model, NOT the camelCase response.
857
+ init.body = JSON.stringify({ entity_ids: entityIds });
858
+ }
859
+ return this.chatRequest(`/api/v1/videos/${encodeURIComponent(videoId)}/personas/generate`, init);
860
+ }
861
+ /**
862
+ * C3a: poll a persona-generation job's status + progress + errors. Ownership
863
+ * is enforced server-side by reconstructing the partition key from the auth
864
+ * token (a foreign/unknown id 404s). ``GET /api/v1/persona-jobs/{jobId}``.
865
+ */
866
+ async getPersonaJob(jobId) {
867
+ return this.chatRequest(`/api/v1/persona-jobs/${encodeURIComponent(jobId)}`);
868
+ }
869
+ /**
870
+ * C3a (Step 9 / review page): render a short TTS sample in the persona's
871
+ * current voice and return the ``audio/wav`` bytes as a ``Blob`` (the caller
872
+ * plays it via ``URL.createObjectURL`` + ``<audio>``). Allowed for any persona
873
+ * status so the review page can preview before approval.
874
+ * ``POST /api/v1/personas/{personaId}/audition``.
875
+ *
876
+ * The response is binary, so this bypasses the JSON ``chatRequest`` wrapper and
877
+ * attaches the bearer token directly (same pattern as {@link getSeedImageBlob}).
878
+ * An omitted ``body`` renders the backend default sample text.
879
+ */
880
+ async auditionPersona(personaId, body, options = {}) {
881
+ const url = `${this.chatApiBaseUrl}/api/v1/personas/${encodeURIComponent(personaId)}/audition`;
882
+ const headers = { 'Content-Type': 'application/json' };
883
+ if (this.sessionToken) {
884
+ headers['Authorization'] = `Bearer ${this.sessionToken}`;
885
+ }
886
+ const response = await fetch(url, {
887
+ method: 'POST',
888
+ headers,
889
+ // Always send a JSON body (``{}`` when none) so FastAPI parses an empty
890
+ // object rather than choking on a missing content-type.
891
+ body: JSON.stringify(body ?? {}),
892
+ signal: options.signal,
893
+ });
894
+ if (!response.ok) {
895
+ const detail = await response
896
+ .json()
897
+ .then((b) => b.detail ?? b.error)
898
+ .catch(() => undefined);
899
+ throw new Error(detail || `Audition render failed: HTTP ${response.status}`);
900
+ }
901
+ return await response.blob();
902
+ }
903
+ /**
904
+ * C3a (Step 9 / review page): re-clone the persona's voice from a DIFFERENT
905
+ * subset of its cached ``persona-clips`` (available minus already-used) without
906
+ * re-downloading the video. Swaps ``voice_id`` and appends to ``clips_used``;
907
+ * returns the new ``voiceId`` + the full ``clipsUsed`` set.
908
+ * ``POST /api/v1/personas/{personaId}/reclone``.
909
+ *
910
+ * Bypasses ``chatRequest`` so a ``409`` (whose ``detail`` is a structured
911
+ * object the generic JSON error path renders as ``[object Object]``) is raised
912
+ * as a typed {@link RecloneConflictError} the review UI can branch on.
913
+ */
914
+ async reclonePersona(personaId) {
915
+ const url = `${this.chatApiBaseUrl}/api/v1/personas/${encodeURIComponent(personaId)}/reclone`;
916
+ const headers = { 'Content-Type': 'application/json' };
917
+ if (this.sessionToken) {
918
+ headers['Authorization'] = `Bearer ${this.sessionToken}`;
919
+ }
920
+ const response = await fetch(url, { method: 'POST', headers });
921
+ if (response.ok) {
922
+ return (await response.json());
923
+ }
924
+ // Surface the structured 409 (``detail`` is ``{error, attempts?}``) as a
925
+ // typed error; everything else flattens to the FastAPI ``detail`` string.
926
+ const errBody = await response
927
+ .json()
928
+ .then((b) => b.detail)
929
+ .catch(() => undefined);
930
+ if (response.status === 409 &&
931
+ errBody &&
932
+ typeof errBody === 'object' &&
933
+ typeof errBody.error === 'string') {
934
+ const { error, attempts } = errBody;
935
+ if (error === 'voice_clone_max_retries_exhausted' ||
936
+ error === 'no_candidate_clips_remaining') {
937
+ throw new RecloneConflictError(error, attempts);
938
+ }
939
+ }
940
+ const message = typeof errBody === 'string' ? errBody : `Reclone failed: HTTP ${response.status}`;
941
+ throw new Error(message);
942
+ }
357
943
  // ==================== Image API Methods ====================
358
944
  // Note: Images are served by the Chat API
945
+ /**
946
+ * Fetch the image-model catalogue from the backend (R1c). Read-only.
947
+ * Unlike {@link listChatModels}, this endpoint is **authenticated** (its
948
+ * consumers — Studio Images, the Admin adapter inspector — are post-auth, so
949
+ * it is not a public pre-auth path); call it with a valid session. Served via
950
+ * the CHAT base URL (the images API is mounted on the chat app), so this uses
951
+ * `chatRequest`, NOT `toolsRequest`.
952
+ */
953
+ async listImageModels() {
954
+ return this.chatRequest('/api/v1/images/models');
955
+ }
359
956
  async listImages(params) {
360
957
  const searchParams = new URLSearchParams();
361
958
  if (params?.category)
362
959
  searchParams.append('category', params.category);
363
960
  if (params?.videoId)
364
961
  searchParams.append('videoId', params.videoId);
962
+ if (params?.model)
963
+ searchParams.append('model', params.model);
964
+ if (params?.status)
965
+ searchParams.append('status', params.status);
365
966
  if (params?.limit)
366
967
  searchParams.append('limit', params.limit.toString());
367
968
  if (params?.nextToken)
@@ -657,8 +1258,54 @@ export class ApiClient {
657
1258
  });
658
1259
  }
659
1260
  // ==================== Graph Editor API Methods ====================
660
- async getVideoGraph(videoId) {
661
- return this.request(`/api/v1/tools/graph/${encodeURIComponent(videoId)}`);
1261
+ /**
1262
+ * Fetch a video's subgraph. R5b: the optional `detail` arg selects the
1263
+ * server-side view — `GRAPH_DETAIL.STORY` for the collapsed story view,
1264
+ * `GRAPH_DETAIL.RAW` for the full extraction graph. Omitting it sends NO
1265
+ * query param (byte-identical to the pre-R5b request — the server defaults
1266
+ * to raw), so every existing caller is untouched.
1267
+ */
1268
+ async getVideoGraph(videoId, detail) {
1269
+ const base = `/api/v1/tools/graph/${encodeURIComponent(videoId)}`;
1270
+ const path = detail === undefined ? base : `${base}?detail=${encodeURIComponent(detail)}`;
1271
+ return this.request(path);
1272
+ }
1273
+ // ==================== Creator Studio / Story API Methods (M7 P7) ====================
1274
+ /**
1275
+ * List all stories (videos) visible to the caller. `storyId === videoId`
1276
+ * (1:1) in M7 P7 — the Story resource is a thin, read-only view over the
1277
+ * existing Video. No pagination/filter parameters in P7.
1278
+ */
1279
+ async listStories() {
1280
+ return this.request('/api/v1/stories');
1281
+ }
1282
+ /**
1283
+ * Fetch a single story's metadata + aggregate counts. Throws (404) when the
1284
+ * id resolves to no Video node.
1285
+ */
1286
+ async getStory(storyId) {
1287
+ return this.request(`/api/v1/stories/${encodeURIComponent(storyId)}`);
1288
+ }
1289
+ /**
1290
+ * Resolve a playable (presigned or local-stub) URL for a clip span via the
1291
+ * existing `POST /api/v1/tools/clip-lookup` tool endpoint. Used by the studio
1292
+ * Scene inspector to scope the player to a scene's `[t0, t1]`. Additive — never
1293
+ * remove/rename. Wire keys are camelCase (backend `BaseSchema`, no aliasing).
1294
+ */
1295
+ async clipLookup(params) {
1296
+ return this.request('/api/v1/tools/clip-lookup', {
1297
+ method: 'POST',
1298
+ body: JSON.stringify(params),
1299
+ });
1300
+ }
1301
+ /**
1302
+ * Fetch the live graph whitelist (node PKs + editable properties per label
1303
+ * and edge type). No auth required — pure metadata. Prefer the memoized
1304
+ * `fetchGraphSchema()` wrapper in `graphSchema.ts` over calling this per
1305
+ * render; the raw method exists for that wrapper and one-off callers.
1306
+ */
1307
+ async getGraphSchema() {
1308
+ return this.request('/api/v1/tools/graph/schema');
662
1309
  }
663
1310
  async updateGraphNode(data) {
664
1311
  return this.request('/api/v1/tools/graph/nodes', {
@@ -667,10 +1314,13 @@ export class ApiClient {
667
1314
  });
668
1315
  }
669
1316
  async deleteGraphNode(data) {
670
- return this.request('/api/v1/tools/graph/nodes', {
671
- method: 'DELETE',
672
- body: JSON.stringify(data),
1317
+ // DELETE carries no body — identifiers travel as query params (M7 P1a,
1318
+ // closes tech-debt #42). The backend derives the PK from the label.
1319
+ const params = new URLSearchParams({
1320
+ nodeLabel: data.nodeLabel,
1321
+ idValue: data.idValue,
673
1322
  });
1323
+ return this.request(`/api/v1/tools/graph/nodes?${params.toString()}`, { method: 'DELETE' });
674
1324
  }
675
1325
  async updateGraphEdge(data) {
676
1326
  return this.request('/api/v1/tools/graph/edges', {
@@ -679,8 +1329,38 @@ export class ApiClient {
679
1329
  });
680
1330
  }
681
1331
  async deleteGraphEdge(data) {
1332
+ // DELETE carries no body — identifiers travel as query params (M7 P1a,
1333
+ // closes tech-debt #42).
1334
+ const params = new URLSearchParams({
1335
+ sourceId: data.sourceId,
1336
+ targetId: data.targetId,
1337
+ relType: data.relType,
1338
+ });
1339
+ return this.request(`/api/v1/tools/graph/edges?${params.toString()}`, { method: 'DELETE' });
1340
+ }
1341
+ /**
1342
+ * Create a user-authored narrative node (Scene / PlotBeat / CharacterArc).
1343
+ * POST returns 201 with `{traceId, nodeId, properties}`; `makeRequest` parses
1344
+ * the body (only 204 is bodyless) and surfaces a 422 (e.g. label not
1345
+ * user-creatable, missing actId/index for a Scene) as a thrown `Error` with
1346
+ * the FastAPI detail. The backend stamps provenance/versionId/timestamps.
1347
+ */
1348
+ async createGraphNode(data) {
1349
+ return this.request('/api/v1/tools/graph/nodes', {
1350
+ method: 'POST',
1351
+ body: JSON.stringify(data),
1352
+ });
1353
+ }
1354
+ /**
1355
+ * Create a user-authored relationship (RELATES_TO / CAUSES / SET_IN /
1356
+ * FEATURES / ON_ARC / LEADS_TO). POST returns 201 with
1357
+ * `{traceId, edgeId, properties}`; a 422 (invalid endpoint-label pair,
1358
+ * pipeline-only type, cross-video endpoints, or SET_IN/FEATURES Entity.type
1359
+ * mismatch) surfaces as a thrown `Error` with the FastAPI detail.
1360
+ */
1361
+ async createGraphEdge(data) {
682
1362
  return this.request('/api/v1/tools/graph/edges', {
683
- method: 'DELETE',
1363
+ method: 'POST',
684
1364
  body: JSON.stringify(data),
685
1365
  });
686
1366
  }
@@ -1051,5 +1731,93 @@ export class ApiClient {
1051
1731
  signal: options.signal,
1052
1732
  });
1053
1733
  }
1734
+ // ============= Adventure Runtime API (M9 Story Engine Phase 8a) =============
1735
+ /**
1736
+ * Start an interactive adventure for a story/video, driven by a
1737
+ * Dungeon-Master persona. `POST /api/v1/adventures` → 201 with the initial
1738
+ * {@link AdventureState} (and a `Location` header to the session's GET URL).
1739
+ *
1740
+ * Auth + video ownership are enforced server-side. `dmPersonaId` must
1741
+ * reference an owned persona whose `is_dungeon_master` is true (422 otherwise),
1742
+ * and a missing/unowned persona is a 404/403 — all surface as a thrown `Error`
1743
+ * carrying the FastAPI detail. Additive — never remove/rename.
1744
+ */
1745
+ async startAdventure(request, options = {}) {
1746
+ return this.request('/api/v1/adventures', {
1747
+ method: 'POST',
1748
+ body: JSON.stringify(request),
1749
+ signal: options.signal,
1750
+ });
1751
+ }
1752
+ /**
1753
+ * Fetch the current {@link AdventureState} for a session.
1754
+ * `GET /api/v1/adventures/{sessionId}` (404 when absent or not owned by the
1755
+ * caller — the store hides cross-tenant and soft-deleted sessions).
1756
+ */
1757
+ async getAdventure(sessionId, options = {}) {
1758
+ return this.request(`/api/v1/adventures/${encodeURIComponent(sessionId)}`, { signal: options.signal });
1759
+ }
1760
+ /**
1761
+ * List the caller's adventures, newest-first. `GET /api/v1/adventures` →
1762
+ * {@link ListAdventuresResponse}. Owner-scoped server-side (soft-deleted
1763
+ * sessions excluded); pass `storyId` to narrow to a single story. Additive —
1764
+ * never remove/rename.
1765
+ */
1766
+ async listAdventures(storyId, options = {}) {
1767
+ const searchParams = new URLSearchParams();
1768
+ if (storyId)
1769
+ searchParams.append('storyId', storyId);
1770
+ const query = searchParams.toString();
1771
+ const endpoint = `/api/v1/adventures${query ? `?${query}` : ''}`;
1772
+ return this.request(endpoint, {
1773
+ signal: options.signal,
1774
+ });
1775
+ }
1776
+ /**
1777
+ * Soft-delete an adventure session. `DELETE /api/v1/adventures/{sessionId}`
1778
+ * → 204 (resolves to `void`). A missing/unowned session is a 404 surfaced as
1779
+ * a thrown `Error`.
1780
+ */
1781
+ async deleteAdventure(sessionId, options = {}) {
1782
+ return this.request(`/api/v1/adventures/${encodeURIComponent(sessionId)}`, { method: 'DELETE', signal: options.signal });
1783
+ }
1784
+ /**
1785
+ * Mutate an adventure's party (M10 Story Engine Phase 9a).
1786
+ * `PATCH /api/v1/adventures/{sessionId}/party` with
1787
+ * `{ action, personaId }` → the updated {@link GetAdventureResponse}.
1788
+ * Shared by {@link addPartyMember} / {@link removePartyMember}; not exported
1789
+ * directly so call sites go through the action-specific wrappers. Additive —
1790
+ * never remove/rename.
1791
+ */
1792
+ patchParty(sessionId, request, options = {}) {
1793
+ return this.request(`/api/v1/adventures/${encodeURIComponent(sessionId)}/party`, {
1794
+ method: 'PATCH',
1795
+ body: JSON.stringify(request),
1796
+ signal: options.signal,
1797
+ });
1798
+ }
1799
+ /**
1800
+ * Add a character persona to an adventure's party (M10 Story Engine Phase
1801
+ * 9a). `PATCH /api/v1/adventures/{sessionId}/party` with `action='add'` →
1802
+ * the updated {@link GetAdventureResponse}. The persona must be owned by the
1803
+ * caller, bound to a character entity, and NOT a Dungeon Master (422
1804
+ * otherwise); a missing/unowned adventure is a 404 — all surface as a thrown
1805
+ * `Error` carrying the FastAPI detail. Server-side dedupe makes a repeat add
1806
+ * a no-op. Additive — never remove/rename.
1807
+ */
1808
+ async addPartyMember(sessionId, personaId, options = {}) {
1809
+ return this.patchParty(sessionId, { action: PARTY_ACTION.ADD, personaId }, options);
1810
+ }
1811
+ /**
1812
+ * Remove a character persona from an adventure's party (M10 Story Engine
1813
+ * Phase 9a). `PATCH /api/v1/adventures/{sessionId}/party` with
1814
+ * `action='remove'` → the updated {@link GetAdventureResponse}. Idempotent:
1815
+ * removing an absent member is a 200 no-op that returns the current state. A
1816
+ * missing/unowned adventure is a 404 surfaced as a thrown `Error`. Additive —
1817
+ * never remove/rename.
1818
+ */
1819
+ async removePartyMember(sessionId, personaId, options = {}) {
1820
+ return this.patchParty(sessionId, { action: PARTY_ACTION.REMOVE, personaId }, options);
1821
+ }
1054
1822
  }
1055
1823
  //# sourceMappingURL=api.js.map