@escapeaihq/client-core 0.12.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 (239) hide show
  1. package/README.md +31 -6
  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 +1185 -3
  35. package/dist/api.d.ts.map +1 -1
  36. package/dist/api.js +624 -51
  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 +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 +73 -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 +470 -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/controller.test.ts +697 -0
  179. package/src/__tests__/conversation/effectiveModel.test.ts +169 -0
  180. package/src/__tests__/conversation/headlessRenderer.ts +46 -0
  181. package/src/__tests__/conversation/presenceBus.test.ts +236 -0
  182. package/src/__tests__/conversation/presenceRegistry.test.ts +73 -0
  183. package/src/__tests__/conversation/roster.test.ts +100 -0
  184. package/src/__tests__/conversation/rosterProjection.test.ts +142 -0
  185. package/src/__tests__/conversation/router.test.ts +81 -0
  186. package/src/__tests__/conversation/runtime.test.ts +206 -0
  187. package/src/__tests__/conversation/voice.test.ts +440 -0
  188. package/src/__tests__/documents.test.ts +360 -0
  189. package/src/__tests__/graphSchema.test.ts +218 -9
  190. package/src/__tests__/longLiveCommandDispatcher.test.ts +185 -0
  191. package/src/__tests__/platformAssistant.test.ts +484 -0
  192. package/src/__tests__/reactor/storyTimeline.test.ts +186 -0
  193. package/src/__tests__/regeneration.test.ts +486 -0
  194. package/src/__tests__/stories.test.ts +171 -0
  195. package/src/__tests__/storyGraph.test.ts +134 -0
  196. package/src/__tests__/tools-wrappers.test.ts +272 -0
  197. package/src/__tests__/videoGraph.test.ts +94 -0
  198. package/src/__tests__/websocket.test.ts +213 -0
  199. package/src/adapters/capabilities.ts +24 -0
  200. package/src/adapters/chatAdapter.ts +114 -0
  201. package/src/adapters/directorAdapter.ts +126 -0
  202. package/src/adapters/imageAdapter.ts +100 -0
  203. package/src/adapters/index.ts +67 -0
  204. package/src/adapters/registry.ts +159 -0
  205. package/src/adapters/worldAdapter.ts +272 -0
  206. package/src/admin.ts +310 -0
  207. package/src/api.ts +1731 -116
  208. package/src/audio.ts +35 -0
  209. package/src/castProjection.ts +95 -0
  210. package/src/conversation/binding.ts +81 -0
  211. package/src/conversation/controller.ts +439 -0
  212. package/src/conversation/effectiveModel.ts +111 -0
  213. package/src/conversation/index.ts +27 -0
  214. package/src/conversation/participant.ts +71 -0
  215. package/src/conversation/presence.ts +60 -0
  216. package/src/conversation/presenceBus.ts +109 -0
  217. package/src/conversation/presenceRegistry.ts +83 -0
  218. package/src/conversation/roster.ts +111 -0
  219. package/src/conversation/rosterProjection.ts +98 -0
  220. package/src/conversation/router.ts +96 -0
  221. package/src/conversation/runtime.ts +188 -0
  222. package/src/conversation/types.ts +100 -0
  223. package/src/conversation/voice.ts +402 -0
  224. package/src/graphSchema.ts +396 -13
  225. package/src/http.ts +72 -0
  226. package/src/index.ts +9 -0
  227. package/src/platformAssistant.ts +347 -0
  228. package/src/reactor/chunkDistribution.ts +98 -0
  229. package/src/reactor/index.ts +5 -0
  230. package/src/reactor/longLiveCommandDispatcher.ts +156 -0
  231. package/src/reactor/scenesFromEnrichment.ts +11 -76
  232. package/src/reactor/seedImageOrchestrator.ts +12 -13
  233. package/src/reactor/storyTimeline.ts +127 -0
  234. package/src/storyGraph.ts +298 -0
  235. package/src/vision/VisionSourceController.ts +354 -0
  236. package/src/vision/__tests__/VisionSourceController.test.ts +719 -0
  237. package/src/vision/index.ts +13 -0
  238. package/src/vision/sourceKinds.ts +75 -0
  239. package/src/websocket.ts +75 -3
@@ -0,0 +1,296 @@
1
+ import {
2
+ ROUTE_DEFAULT,
3
+ ROUTE_FALLBACK,
4
+ createWorldRegistry,
5
+ dispatchWorldCommand,
6
+ heliosWorldAdapter,
7
+ longLiveWorldAdapter,
8
+ requiredCapabilityForCommand,
9
+ UnsupportedWorldAdapterError,
10
+ } from '../adapters';
11
+ import { dispatchHeliosCommand } from '../reactor/heliosCommandDispatcher';
12
+ import type {
13
+ HeliosCommand,
14
+ HeliosToolContext,
15
+ LongLiveToolContext,
16
+ } from '../reactor';
17
+
18
+ type AnyMock = jest.Mock;
19
+
20
+ function makeReactor() {
21
+ return {
22
+ sendCommand: jest.fn().mockResolvedValue(undefined) as AnyMock,
23
+ uploadFile: jest
24
+ .fn()
25
+ .mockResolvedValue({ uploadId: 'u1', name: 'seed.jpg' }) as AnyMock,
26
+ };
27
+ }
28
+
29
+ function makeApiClient(overrides: Partial<Record<string, AnyMock>> = {}) {
30
+ return {
31
+ upsampleReactorPrompt: jest.fn().mockResolvedValue({
32
+ traceId: 't',
33
+ upsampledPrompt: 'UPSAMPLED',
34
+ }),
35
+ listImages: jest.fn().mockResolvedValue({ images: [] }),
36
+ getSeedImageBlob: jest
37
+ .fn()
38
+ .mockResolvedValue(new Blob(['x'], { type: 'image/jpeg' })),
39
+ ...overrides,
40
+ } as unknown as HeliosToolContext['apiClient'] & Record<string, AnyMock>;
41
+ }
42
+
43
+ /** The exact HeliosCommand variant set (reactor/heliosTools.ts:32-37). If a
44
+ * variant is added/removed, this expectation must change in lockstep. */
45
+ const HELIOS_COMMAND_TYPES: readonly HeliosCommand['type'][] = [
46
+ 'set_scene',
47
+ 'swap_seed',
48
+ 'pause_world',
49
+ 'resume_world',
50
+ 'reset_world',
51
+ ];
52
+
53
+ describe('createWorldRegistry — Helios seed', () => {
54
+ it('pre-registers heliosWorldAdapter and resolveRoute(default) returns it', () => {
55
+ const reg = createWorldRegistry();
56
+ expect(reg.get('helios')).toEqual(heliosWorldAdapter);
57
+ expect(reg.resolveRoute(ROUTE_DEFAULT)?.id).toBe('helios');
58
+ });
59
+
60
+ it('resolveRoute(fallback) also returns the Helios seed (only seed today)', () => {
61
+ const reg = createWorldRegistry();
62
+ expect(reg.resolveRoute(ROUTE_FALLBACK)?.id).toBe('helios');
63
+ });
64
+
65
+ it('heliosWorldAdapter advertises every WorldCapability', () => {
66
+ expect([...heliosWorldAdapter.capabilities].sort()).toEqual(
67
+ ['pause_resume', 'set_scene', 'swap_seed', 'world_stream'].sort(),
68
+ );
69
+ expect(heliosWorldAdapter.provider).toBe('reactor');
70
+ });
71
+
72
+ it('supportedCommands EXACTLY matches the HeliosCommand variant set', () => {
73
+ expect([...heliosWorldAdapter.supportedCommands].sort()).toEqual(
74
+ [...HELIOS_COMMAND_TYPES].sort(),
75
+ );
76
+ });
77
+ });
78
+
79
+ describe('createWorldRegistry — LongLive-v2 second adapter', () => {
80
+ it('registers longLiveWorldAdapter resolvable by id', () => {
81
+ const reg = createWorldRegistry();
82
+ expect(reg.get('longlive-v2')).toEqual(longLiveWorldAdapter);
83
+ });
84
+
85
+ it('world ROUTE_DEFAULT + ROUTE_FALLBACK still resolve to helios (LongLive is NOT the world default)', () => {
86
+ const reg = createWorldRegistry();
87
+ expect(reg.resolveRoute(ROUTE_DEFAULT)?.id).toBe('helios');
88
+ expect(reg.resolveRoute(ROUTE_FALLBACK)?.id).toBe('helios');
89
+ });
90
+
91
+ it('LongLive is resolvable by capability (scene_cut)', () => {
92
+ const reg = createWorldRegistry();
93
+ const withSceneCut = reg.listWithCapability('scene_cut').map((d) => d.id);
94
+ expect(withSceneCut).toEqual(['longlive-v2']);
95
+ });
96
+
97
+ it('the ASYMMETRIC capability matrix holds via registry.satisfies', () => {
98
+ const reg = createWorldRegistry();
99
+ // Helios HAS swap_seed, LACKS scene_cut.
100
+ expect(reg.satisfies('helios', ['swap_seed'])).toBe(true);
101
+ expect(reg.satisfies('helios', ['scene_cut'])).toBe(false);
102
+ // LongLive HAS scene_cut, LACKS swap_seed.
103
+ expect(reg.satisfies('longlive-v2', ['scene_cut'])).toBe(true);
104
+ expect(reg.satisfies('longlive-v2', ['swap_seed'])).toBe(false);
105
+ });
106
+
107
+ it('longLiveWorldAdapter advertises scene_cut + the base caps but NOT swap_seed', () => {
108
+ expect([...longLiveWorldAdapter.capabilities].sort()).toEqual(
109
+ ['pause_resume', 'scene_cut', 'set_scene', 'world_stream'].sort(),
110
+ );
111
+ expect(longLiveWorldAdapter.capabilities).not.toContain('swap_seed');
112
+ expect(longLiveWorldAdapter.provider).toBe('reactor');
113
+ });
114
+ });
115
+
116
+ describe('dispatchWorldCommand — LongLive routing', () => {
117
+ it('routes longlive-v2 set_shot to dispatchLongLiveCommand (set_shot + start)', async () => {
118
+ const reactor = { sendCommand: jest.fn().mockResolvedValue(undefined) };
119
+ const ctx: LongLiveToolContext = { reactor };
120
+ await dispatchWorldCommand('longlive-v2', { type: 'set_shot', prompt: 'x' }, ctx);
121
+ expect(reactor.sendCommand.mock.calls).toEqual([
122
+ ['set_shot', { prompt: 'x' }],
123
+ ['start', {}],
124
+ ]);
125
+ });
126
+
127
+ it('routes longlive-v2 scene_cut (the cap Helios lacks) through the bridge', async () => {
128
+ const reactor = { sendCommand: jest.fn().mockResolvedValue(undefined) };
129
+ const ctx: LongLiveToolContext = { reactor };
130
+ await dispatchWorldCommand('longlive-v2', { type: 'scene_cut', prompt: 'cut' }, ctx);
131
+ expect(reactor.sendCommand.mock.calls).toEqual([
132
+ ['scene_cut', { prompt: 'cut' }],
133
+ ]);
134
+ });
135
+ });
136
+
137
+ describe('requiredCapabilityForCommand', () => {
138
+ it.each([
139
+ [{ type: 'set_scene', prompt: 'x' }, 'set_scene'],
140
+ [{ type: 'swap_seed', entityName: 'Leo' }, 'swap_seed'],
141
+ [{ type: 'pause_world' }, 'pause_resume'],
142
+ [{ type: 'resume_world' }, 'pause_resume'],
143
+ [{ type: 'reset_world' }, 'world_stream'],
144
+ ] as [HeliosCommand, string][])(
145
+ '%j → %s',
146
+ (cmd, expected) => {
147
+ expect(requiredCapabilityForCommand(cmd)).toBe(expected);
148
+ },
149
+ );
150
+ });
151
+
152
+ describe('dispatchWorldCommand — delegation to dispatchHeliosCommand', () => {
153
+ it('set_scene delegates with identical sendCommand calls as a direct dispatch', async () => {
154
+ const cmd: HeliosCommand = { type: 'set_scene', prompt: 'rainy night' };
155
+
156
+ // Direct dispatch through the existing dispatcher.
157
+ const directReactor = makeReactor();
158
+ await dispatchHeliosCommand(cmd, {
159
+ apiClient: makeApiClient(),
160
+ reactor: directReactor,
161
+ videoId: 'v1',
162
+ currentChunk: 0,
163
+ });
164
+
165
+ // World-gated dispatch — must produce the SAME bridge calls.
166
+ const gatedReactor = makeReactor();
167
+ await dispatchWorldCommand('helios', cmd, {
168
+ apiClient: makeApiClient(),
169
+ reactor: gatedReactor,
170
+ videoId: 'v1',
171
+ currentChunk: 0,
172
+ });
173
+
174
+ const directNames = directReactor.sendCommand.mock.calls.map((c) => c[0]);
175
+ const gatedNames = gatedReactor.sendCommand.mock.calls.map((c) => c[0]);
176
+ expect(gatedNames).toEqual(directNames);
177
+ expect(gatedNames).toEqual(['set_prompt', 'start']);
178
+ // Identical payloads too.
179
+ expect(gatedReactor.sendCommand.mock.calls).toEqual(
180
+ directReactor.sendCommand.mock.calls,
181
+ );
182
+ });
183
+
184
+ it('swap_seed delegates identically (the other rich command) — direct vs gated', async () => {
185
+ const cmd: HeliosCommand = { type: 'swap_seed', entityName: 'Leo' };
186
+ // videoId: null makes handleSwapSeed take its early-out (warn + return,
187
+ // no bridge calls) — a deterministic path that needs no entity-lookup
188
+ // mocking yet still proves the gate routes swap_seed to the SAME handler
189
+ // with IDENTICAL observable effects (uploadFile/sendCommand + onUserWarning).
190
+ const directReactor = makeReactor();
191
+ const directWarn = jest.fn();
192
+ await dispatchHeliosCommand(cmd, {
193
+ apiClient: makeApiClient(),
194
+ reactor: directReactor,
195
+ videoId: null,
196
+ onUserWarning: directWarn,
197
+ });
198
+
199
+ const gatedReactor = makeReactor();
200
+ const gatedWarn = jest.fn();
201
+ await dispatchWorldCommand('helios', cmd, {
202
+ apiClient: makeApiClient(),
203
+ reactor: gatedReactor,
204
+ videoId: null,
205
+ onUserWarning: gatedWarn,
206
+ });
207
+
208
+ expect(gatedReactor.uploadFile.mock.calls).toEqual(directReactor.uploadFile.mock.calls);
209
+ expect(gatedReactor.sendCommand.mock.calls).toEqual(directReactor.sendCommand.mock.calls);
210
+ expect(gatedWarn.mock.calls).toEqual(directWarn.mock.calls);
211
+ // Sanity: this path makes no bridge calls (the swap is gated on a video).
212
+ expect(gatedReactor.uploadFile).not.toHaveBeenCalled();
213
+ expect(gatedReactor.sendCommand).not.toHaveBeenCalled();
214
+ });
215
+
216
+ it('pause_world → bridge sees "pause"', async () => {
217
+ const reactor = makeReactor();
218
+ await dispatchWorldCommand(
219
+ 'helios',
220
+ { type: 'pause_world' },
221
+ { apiClient: makeApiClient(), reactor, videoId: null },
222
+ );
223
+ const names = reactor.sendCommand.mock.calls.map((c) => c[0]);
224
+ expect(names).toEqual(['pause']);
225
+ });
226
+
227
+ it.each([
228
+ ['resume_world', 'resume'],
229
+ ['reset_world', 'reset'],
230
+ ])('%s → bridge sees "%s"', async (cmdType, expected) => {
231
+ const reactor = makeReactor();
232
+ await dispatchWorldCommand(
233
+ 'helios',
234
+ { type: cmdType } as HeliosCommand,
235
+ { apiClient: makeApiClient(), reactor, videoId: null },
236
+ );
237
+ const names = reactor.sendCommand.mock.calls.map((c) => c[0]);
238
+ expect(names).toEqual([expected]);
239
+ });
240
+
241
+ it('throws UnsupportedWorldAdapterError on an unregistered adapter id and NEVER calls the bridge', async () => {
242
+ const reactor = makeReactor();
243
+ const apiClient = makeApiClient();
244
+ // The overloads now reject an unknown id at COMPILE time (see the
245
+ // ts-expect-error test below); the cast simulates a caller passing an id
246
+ // from runtime config to exercise the runtime defense (the impl-signature
247
+ // else-branch still throws).
248
+ await expect(
249
+ dispatchWorldCommand(
250
+ 'sora' as 'helios',
251
+ { type: 'pause_world' },
252
+ { apiClient, reactor, videoId: null },
253
+ ),
254
+ ).rejects.toBeInstanceOf(UnsupportedWorldAdapterError);
255
+
256
+ expect(reactor.sendCommand).not.toHaveBeenCalled();
257
+ expect(reactor.uploadFile).not.toHaveBeenCalled();
258
+ expect(
259
+ (apiClient as unknown as Record<string, AnyMock>).upsampleReactorPrompt,
260
+ ).not.toHaveBeenCalled();
261
+ });
262
+
263
+ it('the thrown error carries the offending adapter id on its typed property', async () => {
264
+ const reactor = makeReactor();
265
+ const err = await dispatchWorldCommand(
266
+ 'gen-3' as 'helios',
267
+ { type: 'reset_world' },
268
+ { apiClient: makeApiClient(), reactor, videoId: null },
269
+ ).catch((e: unknown) => e);
270
+ expect(err).toBeInstanceOf(UnsupportedWorldAdapterError);
271
+ // The typed `adapterId` property — not just the message — carries the id.
272
+ expect((err as UnsupportedWorldAdapterError).adapterId).toBe('gen-3');
273
+ // And the message no longer double-prefixes the class name.
274
+ expect((err as Error).message).not.toContain('UnsupportedWorldAdapterError:');
275
+ expect(reactor.sendCommand).not.toHaveBeenCalled();
276
+ });
277
+
278
+ it('discriminates cmd/adapter pairings at COMPILE time (overload safety)', () => {
279
+ // codex P2 guard: if the adapter ids widened to `string` (e.g. a
280
+ // `: WorldAdapterDescriptor`-annotated descriptor instead of `as const`),
281
+ // these calls would type-check and silently route a command into the WRONG
282
+ // dispatcher. The `as const` ids keep the overloads discriminating — the two
283
+ // error-suppression directives below FAIL the build if that regresses.
284
+ const heliosCtx = {
285
+ apiClient: makeApiClient(),
286
+ reactor: makeReactor(),
287
+ videoId: null,
288
+ };
289
+ const longLiveCtx = { reactor: makeReactor() };
290
+ // @ts-expect-error — a LongLive `scene_cut` command must NOT be accepted for 'helios'.
291
+ void dispatchWorldCommand('helios', { type: 'scene_cut', prompt: 'x' }, heliosCtx);
292
+ // @ts-expect-error — a Helios `swap_seed` command must NOT be accepted for 'longlive-v2'.
293
+ void dispatchWorldCommand('longlive-v2', { type: 'swap_seed', entityName: 'Leo' }, longLiveCtx);
294
+ expect(true).toBe(true); // the real assertions are the two @ts-expect-error above (tsc-enforced)
295
+ });
296
+ });
@@ -0,0 +1,312 @@
1
+ /**
2
+ * Tests for the additive `AdminClient` (GitHub #215 Phase 2): the prompt-defaults
3
+ * editor surface. Methods go through the shared `requestJson` → fetch (same
4
+ * global-fetch-mock pattern as `documents.test.ts`). Admin endpoints live on the
5
+ * chat API base (the admin router is mounted in `api/chat/app.py`).
6
+ */
7
+
8
+ import { AdminClient, MAX_EVAL_RUN_PAGES } from '../admin';
9
+ import type {
10
+ EvalRunsListResponse,
11
+ EvalRunSummary,
12
+ PromptDefaultDetail,
13
+ PromptDefaultsListResponse,
14
+ RegenBasePromptsResponse,
15
+ } from '../admin';
16
+
17
+ const CHAT_BASE_URL = 'http://test.local/chat';
18
+ const PROMPTS = '/api/v1/admin/prompts';
19
+ const EVAL_RUNS = '/api/v1/admin/eval-runs';
20
+ const KEY = 'shared.prompts.DEVELOPER_GUARDRAILS';
21
+
22
+ const makeClient = (token: string | undefined = 'test-token') =>
23
+ new AdminClient(CHAT_BASE_URL, token);
24
+
25
+ const originalFetch = (globalThis as { fetch?: typeof fetch }).fetch;
26
+
27
+ afterEach(() => {
28
+ if (originalFetch === undefined) {
29
+ delete (globalThis as { fetch?: typeof fetch }).fetch;
30
+ } else {
31
+ (globalThis as { fetch?: typeof fetch }).fetch = originalFetch;
32
+ }
33
+ jest.restoreAllMocks();
34
+ });
35
+
36
+ const mockFetch = (body: unknown, init: { ok?: boolean; status?: number } = {}) => {
37
+ const fetchMock = jest.fn().mockResolvedValue({
38
+ ok: init.ok ?? true,
39
+ status: init.status ?? 200,
40
+ json: async () => body,
41
+ });
42
+ (globalThis as { fetch?: typeof fetch }).fetch = fetchMock as unknown as typeof fetch;
43
+ return fetchMock;
44
+ };
45
+
46
+ const detail = (over: Partial<PromptDefaultDetail> = {}): PromptDefaultDetail => ({
47
+ promptKey: KEY,
48
+ label: 'Developer guardrails',
49
+ group: 'shared/prompts.py',
50
+ source: 'db',
51
+ value: 'custom',
52
+ codeDefault: 'baseline',
53
+ previousValue: null,
54
+ updatedAt: '2026-06-01T00:00:00+00:00',
55
+ updatedBy: 'admin-1',
56
+ editable: true,
57
+ traceId: 'trace-1',
58
+ ...over,
59
+ });
60
+
61
+ describe('AdminClient.listPromptDefaults', () => {
62
+ it('GETs /api/v1/admin/prompts on the chat base with a bearer token', async () => {
63
+ const body: PromptDefaultsListResponse = {
64
+ prompts: [
65
+ {
66
+ promptKey: KEY,
67
+ label: 'Developer guardrails',
68
+ group: 'shared/prompts.py',
69
+ source: 'db',
70
+ updatedAt: '2026-06-01T00:00:00+00:00',
71
+ updatedBy: 'admin-1',
72
+ editable: true,
73
+ },
74
+ ],
75
+ traceId: 'trace-list',
76
+ };
77
+ const fetchMock = mockFetch(body);
78
+
79
+ const result = await makeClient().listPromptDefaults();
80
+
81
+ expect(result).toEqual(body);
82
+ const [url, init] = fetchMock.mock.calls[0];
83
+ expect(url).toBe(`${CHAT_BASE_URL}${PROMPTS}`);
84
+ expect(init.method ?? 'GET').toBe('GET');
85
+ expect(init.headers['Authorization']).toBe('Bearer test-token');
86
+ });
87
+ });
88
+
89
+ describe('AdminClient.getPromptDefault', () => {
90
+ it('GETs the key detail (key is URL-encoded)', async () => {
91
+ const fetchMock = mockFetch(detail({ source: 'code', value: 'baseline' }));
92
+
93
+ const result = await makeClient().getPromptDefault(KEY);
94
+
95
+ expect(result.source).toBe('code');
96
+ const [url] = fetchMock.mock.calls[0];
97
+ expect(url).toBe(`${CHAT_BASE_URL}${PROMPTS}/${encodeURIComponent(KEY)}`);
98
+ });
99
+ });
100
+
101
+ describe('AdminClient.updatePromptDefault', () => {
102
+ it('PUTs the new value as JSON', async () => {
103
+ const fetchMock = mockFetch(detail({ value: 'new text' }));
104
+
105
+ const result = await makeClient().updatePromptDefault(KEY, { value: 'new text' });
106
+
107
+ expect(result.value).toBe('new text');
108
+ const [url, init] = fetchMock.mock.calls[0];
109
+ expect(url).toBe(`${CHAT_BASE_URL}${PROMPTS}/${encodeURIComponent(KEY)}`);
110
+ expect(init.method).toBe('PUT');
111
+ expect(JSON.parse(init.body)).toEqual({ value: 'new text' });
112
+ expect(init.headers['Content-Type']).toBe('application/json');
113
+ });
114
+ });
115
+
116
+ describe('AdminClient.revertPromptDefault', () => {
117
+ it('POSTs to the /revert sub-resource', async () => {
118
+ const fetchMock = mockFetch(detail({ source: 'code', value: 'baseline' }));
119
+
120
+ const result = await makeClient().revertPromptDefault(KEY);
121
+
122
+ expect(result.source).toBe('code');
123
+ const [url, init] = fetchMock.mock.calls[0];
124
+ expect(url).toBe(`${CHAT_BASE_URL}${PROMPTS}/${encodeURIComponent(KEY)}/revert`);
125
+ expect(init.method).toBe('POST');
126
+ });
127
+ });
128
+
129
+ const evalRun = (over: Partial<EvalRunSummary> = {}): EvalRunSummary => ({
130
+ evalRunId: 'run-1',
131
+ benchmarkId: 'extraction_quality_v0',
132
+ scenarioId: 'scenario-1',
133
+ status: 'completed',
134
+ createdAt: '2026-06-05T00:00:00+00:00',
135
+ metrics: { citation_hit: 0.9 },
136
+ scenarioSetId: null,
137
+ scenarioType: null,
138
+ promptVersion: 'v3',
139
+ pipelineVersion: null,
140
+ modelId: 'nova-pro',
141
+ routeName: null,
142
+ costTier: null,
143
+ latencyMs: null,
144
+ estimatedCostUsd: null,
145
+ ...over,
146
+ });
147
+
148
+ const evalPage = (
149
+ runs: EvalRunSummary[],
150
+ nextCursor: string | null,
151
+ ): EvalRunsListResponse => ({ runs, nextCursor, traceId: 'trace-eval' });
152
+
153
+ describe('AdminClient.listEvalRuns', () => {
154
+ it('builds the URL with benchmarkId + limit query params', async () => {
155
+ const fetchMock = mockFetch(evalPage([evalRun()], null));
156
+
157
+ const result = await makeClient().listEvalRuns({
158
+ benchmarkId: 'extraction_quality_v0',
159
+ limit: 25,
160
+ });
161
+
162
+ expect(result.runs).toHaveLength(1);
163
+ const [url] = fetchMock.mock.calls[0];
164
+ expect(url).toBe(
165
+ `${CHAT_BASE_URL}${EVAL_RUNS}?benchmarkId=extraction_quality_v0&limit=25`,
166
+ );
167
+ });
168
+
169
+ it('builds the URL with the promptVersion query param', async () => {
170
+ const fetchMock = mockFetch(evalPage([], null));
171
+
172
+ await makeClient().listEvalRuns({ promptVersion: 'v3' });
173
+
174
+ const [url] = fetchMock.mock.calls[0];
175
+ expect(url).toBe(`${CHAT_BASE_URL}${EVAL_RUNS}?promptVersion=v3`);
176
+ });
177
+
178
+ it('passes the bearer token and the abort signal through', async () => {
179
+ const fetchMock = mockFetch(evalPage([], null));
180
+ const controller = new AbortController();
181
+
182
+ await makeClient().listEvalRuns(
183
+ { benchmarkId: 'b' },
184
+ { signal: controller.signal },
185
+ );
186
+
187
+ const [, init] = fetchMock.mock.calls[0];
188
+ expect(init.headers['Authorization']).toBe('Bearer test-token');
189
+ expect(init.signal).toBe(controller.signal);
190
+ });
191
+ });
192
+
193
+ describe('AdminClient.listAllEvalRuns', () => {
194
+ it('concatenates runs across 2 pages then stops when nextCursor is null', async () => {
195
+ const fetchMock = jest
196
+ .fn()
197
+ .mockResolvedValueOnce({
198
+ ok: true,
199
+ status: 200,
200
+ json: async () =>
201
+ evalPage([evalRun({ evalRunId: 'run-1' })], 'cursor-page-2'),
202
+ })
203
+ .mockResolvedValueOnce({
204
+ ok: true,
205
+ status: 200,
206
+ json: async () => evalPage([evalRun({ evalRunId: 'run-2' })], null),
207
+ });
208
+ (globalThis as { fetch?: typeof fetch }).fetch =
209
+ fetchMock as unknown as typeof fetch;
210
+
211
+ const all = await makeClient().listAllEvalRuns({ benchmarkId: 'b' });
212
+
213
+ expect(all.runs.map((r) => r.evalRunId)).toEqual(['run-1', 'run-2']);
214
+ expect(all.truncated).toBe(false);
215
+ expect(fetchMock).toHaveBeenCalledTimes(2);
216
+ const [firstUrl] = fetchMock.mock.calls[0];
217
+ expect(firstUrl).toBe(`${CHAT_BASE_URL}${EVAL_RUNS}?benchmarkId=b`);
218
+ const [secondUrl] = fetchMock.mock.calls[1];
219
+ expect(secondUrl).toBe(
220
+ `${CHAT_BASE_URL}${EVAL_RUNS}?benchmarkId=b&cursor=cursor-page-2`,
221
+ );
222
+ });
223
+
224
+ it('stops at MAX_EVAL_RUN_PAGES if the server never returns a null cursor', async () => {
225
+ // Server always hands back a cursor — without the cap this loops forever.
226
+ const fetchMock = jest.fn().mockResolvedValue({
227
+ ok: true,
228
+ status: 200,
229
+ json: async () => evalPage([evalRun()], 'never-ending-cursor'),
230
+ });
231
+ (globalThis as { fetch?: typeof fetch }).fetch =
232
+ fetchMock as unknown as typeof fetch;
233
+
234
+ const all = await makeClient().listAllEvalRuns({ benchmarkId: 'b' });
235
+
236
+ expect(fetchMock).toHaveBeenCalledTimes(MAX_EVAL_RUN_PAGES);
237
+ expect(all.runs).toHaveLength(MAX_EVAL_RUN_PAGES);
238
+ // The cap was hit with the cursor still non-null → the prefix is partial.
239
+ expect(all.truncated).toBe(true);
240
+ });
241
+
242
+ it('ignores a caller-supplied params.cursor and starts from the newest page', async () => {
243
+ const fetchMock = jest.fn().mockResolvedValue({
244
+ ok: true,
245
+ status: 200,
246
+ json: async () => evalPage([evalRun()], null),
247
+ });
248
+ (globalThis as { fetch?: typeof fetch }).fetch =
249
+ fetchMock as unknown as typeof fetch;
250
+
251
+ await makeClient().listAllEvalRuns({ benchmarkId: 'b', cursor: 'stale' });
252
+
253
+ // "list ALL" starts from the newest page — the stale cursor must NOT appear.
254
+ const [firstUrl] = fetchMock.mock.calls[0];
255
+ expect(firstUrl).toBe(`${CHAT_BASE_URL}${EVAL_RUNS}?benchmarkId=b`);
256
+ expect(firstUrl).not.toContain('cursor=');
257
+ });
258
+ });
259
+
260
+ describe('AdminClient error handling', () => {
261
+ it('throws with the FastAPI detail message on a non-ok response', async () => {
262
+ mockFetch({ detail: 'Unknown or non-editable prompt key: x' }, { ok: false, status: 404 });
263
+
264
+ await expect(makeClient().getPromptDefault('x')).rejects.toThrow(
265
+ 'Unknown or non-editable prompt key: x',
266
+ );
267
+ });
268
+
269
+ it('omits the Authorization header when no session token is set', async () => {
270
+ const fetchMock = mockFetch({ prompts: [], traceId: 't' });
271
+
272
+ // Construct directly with undefined — `makeClient(undefined)` would trigger
273
+ // the default-parameter token instead of passing through.
274
+ await new AdminClient(CHAT_BASE_URL, undefined).listPromptDefaults();
275
+
276
+ const [, init] = fetchMock.mock.calls[0];
277
+ expect(init.headers['Authorization']).toBeUndefined();
278
+ });
279
+ });
280
+
281
+ describe('AdminClient.listRegenBasePrompts (R6d)', () => {
282
+ const regenResponse: RegenBasePromptsResponse = {
283
+ prompts: [
284
+ {
285
+ promptKey: 'regeneration.base.acts',
286
+ label: 'Regeneration base prompt: acts',
287
+ group: 'services/enrichment/regeneration_prompts.py',
288
+ scopeKind: 'acts',
289
+ prompt: 'Re-analyze this video end-to-end…',
290
+ editable: false,
291
+ },
292
+ ],
293
+ traceId: 'trace-regen-1',
294
+ };
295
+
296
+ it('GETs /api/v1/admin/regen-prompts with the bearer token', async () => {
297
+ const fetchMock = mockFetch(regenResponse);
298
+ const result = await makeClient().listRegenBasePrompts();
299
+ expect(fetchMock).toHaveBeenCalledTimes(1);
300
+ const [url, init] = fetchMock.mock.calls[0];
301
+ expect(url).toBe(`${CHAT_BASE_URL}/api/v1/admin/regen-prompts`);
302
+ expect(init.headers.Authorization).toBe('Bearer test-token');
303
+ expect(init.method ?? 'GET').toBe('GET');
304
+ expect(result).toEqual(regenResponse);
305
+ expect(result.prompts[0].editable).toBe(false);
306
+ });
307
+
308
+ it('surfaces a server error as a thrown Error', async () => {
309
+ mockFetch({ detail: 'nope' }, { ok: false, status: 503 });
310
+ await expect(makeClient().listRegenBasePrompts()).rejects.toThrow();
311
+ });
312
+ });