@escapeaihq/client-core 0.49.1 → 0.52.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 (40) hide show
  1. package/README.md +3 -3
  2. package/dist/conversation/binding.d.ts +28 -1
  3. package/dist/conversation/binding.d.ts.map +1 -1
  4. package/dist/conversation/binding.js +12 -0
  5. package/dist/conversation/binding.js.map +1 -1
  6. package/dist/conversation/controller.d.ts +16 -0
  7. package/dist/conversation/controller.d.ts.map +1 -1
  8. package/dist/conversation/controller.js +22 -0
  9. package/dist/conversation/controller.js.map +1 -1
  10. package/dist/reactor/dmSceneControlPrompt.d.ts +40 -0
  11. package/dist/reactor/dmSceneControlPrompt.d.ts.map +1 -0
  12. package/dist/reactor/dmSceneControlPrompt.js +83 -0
  13. package/dist/reactor/dmSceneControlPrompt.js.map +1 -0
  14. package/dist/reactor/index.d.ts +1 -0
  15. package/dist/reactor/index.d.ts.map +1 -1
  16. package/dist/reactor/index.js +3 -0
  17. package/dist/reactor/index.js.map +1 -1
  18. package/dist/reactor/promptAddonRegistry.js +2 -2
  19. package/dist/reactor/promptAddonRegistry.js.map +1 -1
  20. package/dist/reactor/toolPromptAddon.d.ts +37 -28
  21. package/dist/reactor/toolPromptAddon.d.ts.map +1 -1
  22. package/dist/reactor/toolPromptAddon.js +48 -100
  23. package/dist/reactor/toolPromptAddon.js.map +1 -1
  24. package/dist/websocket.d.ts +119 -2
  25. package/dist/websocket.d.ts.map +1 -1
  26. package/dist/websocket.js +73 -0
  27. package/dist/websocket.js.map +1 -1
  28. package/package.json +1 -1
  29. package/src/__tests__/conversation/binding.test.ts +53 -0
  30. package/src/__tests__/conversation/controller.test.ts +117 -0
  31. package/src/__tests__/reactor/promptAddonRegistry.test.ts +3 -1
  32. package/src/__tests__/reactor/toolPromptAddon.test.ts +34 -42
  33. package/src/__tests__/websocket-session-attach.test.ts +288 -0
  34. package/src/conversation/binding.ts +40 -1
  35. package/src/conversation/controller.ts +39 -0
  36. package/src/reactor/dmSceneControlPrompt.ts +85 -0
  37. package/src/reactor/index.ts +3 -0
  38. package/src/reactor/promptAddonRegistry.ts +2 -2
  39. package/src/reactor/toolPromptAddon.ts +51 -101
  40. package/src/websocket.ts +186 -2
@@ -60,3 +60,56 @@ describe('toHelloArgs personaId', () => {
60
60
  expect(toHelloArgs(binding)).toEqual({ personaId: 'p-1', videoId: 'v-1' });
61
61
  });
62
62
  });
63
+
64
+ describe('toHelloArgs systemPrompt / systemPromptOverride (SP1)', () => {
65
+ it('maps systemPrompt + systemPromptOverride onto the hello args', () => {
66
+ const binding: ConversationContextBinding = {
67
+ kind: ConversationContextKind.PERSONA,
68
+ personaId: 'p-1',
69
+ systemPrompt: 'You are Sarah Chen, a detective.',
70
+ systemPromptOverride: true,
71
+ };
72
+ expect(toHelloArgs(binding)).toEqual({
73
+ personaId: 'p-1',
74
+ systemPrompt: 'You are Sarah Chen, a detective.',
75
+ systemPromptOverride: true,
76
+ });
77
+ });
78
+
79
+ it('defaults systemPromptOverride to false when only the prompt is set', () => {
80
+ const binding: ConversationContextBinding = {
81
+ kind: ConversationContextKind.PERSONA,
82
+ personaId: 'p-1',
83
+ systemPrompt: 'A grounding backstory.',
84
+ };
85
+ expect(toHelloArgs(binding)).toEqual({
86
+ personaId: 'p-1',
87
+ systemPrompt: 'A grounding backstory.',
88
+ systemPromptOverride: false,
89
+ });
90
+ });
91
+
92
+ it('drops BOTH keys when the prompt is empty (land-dark: an empty prompt is "unset")', () => {
93
+ const binding: ConversationContextBinding = {
94
+ kind: ConversationContextKind.PERSONA,
95
+ personaId: 'p-1',
96
+ systemPrompt: '',
97
+ // Even an explicit override flag is dropped — it is meaningless without a
98
+ // prompt (matches buildHelloPayload's `systemPrompt ? {...} : {}` gate).
99
+ systemPromptOverride: true,
100
+ };
101
+ expect(toHelloArgs(binding)).toEqual({ personaId: 'p-1' });
102
+ expect('systemPrompt' in toHelloArgs(binding)).toBe(false);
103
+ expect('systemPromptOverride' in toHelloArgs(binding)).toBe(false);
104
+ });
105
+
106
+ it('keeps the wire byte-identical when no prompt is bound (no keys leak)', () => {
107
+ const binding: ConversationContextBinding = {
108
+ kind: ConversationContextKind.PERSONA,
109
+ personaId: 'p-1',
110
+ };
111
+ const args = toHelloArgs(binding);
112
+ expect('systemPrompt' in args).toBe(false);
113
+ expect('systemPromptOverride' in args).toBe(false);
114
+ });
115
+ });
@@ -192,6 +192,29 @@ describe('ConversationController.connect — single hello-builder', () => {
192
192
  // toHelloArgs is the SINGLE mapper — the raw binding maps the same way.
193
193
  expect(controller.toHelloArgs().videoId).toBe(toHelloArgs(videoBinding).videoId);
194
194
  });
195
+
196
+ it('spreads the binding systemPrompt + override onto the hello (SP1)', async () => {
197
+ const reg = await registry();
198
+ const controller = new ConversationController({
199
+ binding: {
200
+ kind: ConversationContextKind.PERSONA,
201
+ personaId: 'persona-floater',
202
+ systemPrompt: 'You are a wise old wizard.',
203
+ systemPromptOverride: false,
204
+ },
205
+ registry: reg,
206
+ socketOptions: SOCKET_OPTS,
207
+ });
208
+ await connectController(controller);
209
+
210
+ const hello = JSON.parse(instances[0].sent[0]);
211
+ // The hello is the single buildHelloPayload over toHelloArgs — the prompt
212
+ // flows through automatically.
213
+ expect(hello.systemPrompt).toBe('You are a wise old wizard.');
214
+ expect(hello.systemPromptOverride).toBe(false);
215
+ // buildHello() returns the same payload structure.
216
+ expect(controller.buildHello().systemPrompt).toBe('You are a wise old wizard.');
217
+ });
195
218
  });
196
219
 
197
220
  describe('ConversationController — existingSocket adoption', () => {
@@ -359,6 +382,100 @@ describe('ConversationController.send', () => {
359
382
  // Overlay order mirrors buildHello: the seated participant wins.
360
383
  expect(frame.personaId).toBe('seat-persona');
361
384
  });
385
+
386
+ it('threads the binding systemPrompt + override onto every typed send (SP1 in-character fix)', async () => {
387
+ // The `text` send path reads the prompt from the frame (it does NOT load the
388
+ // persona server-side — only the tts_stt hello does). So a persona-bound
389
+ // chat must carry the prompt on every typed turn or the reply comes back in
390
+ // the default assistant voice — the SP1 bug.
391
+ const reg = await registry();
392
+ const controller = new ConversationController({
393
+ binding: {
394
+ kind: ConversationContextKind.PERSONA,
395
+ personaId: 'persona-floater',
396
+ systemPrompt: 'You are Sarah Chen, a hard-boiled detective.',
397
+ systemPromptOverride: true,
398
+ },
399
+ registry: reg,
400
+ socketOptions: SOCKET_OPTS,
401
+ });
402
+ await connectController(controller);
403
+ instances[0].sent.length = 0; // drop the hello
404
+
405
+ controller.send('who killed the butler?');
406
+ const frame = JSON.parse(instances[0].sent[0]);
407
+ expect(frame.systemPrompt).toBe('You are Sarah Chen, a hard-boiled detective.');
408
+ expect(frame.systemPromptOverride).toBe(true);
409
+ });
410
+
411
+ it('omits systemPrompt on send when no prompt is bound (land-dark)', async () => {
412
+ const reg = await registry();
413
+ const controller = new ConversationController({
414
+ binding: { kind: ConversationContextKind.PERSONA, personaId: 'persona-floater' },
415
+ registry: reg,
416
+ socketOptions: SOCKET_OPTS,
417
+ });
418
+ await connectController(controller);
419
+ instances[0].sent.length = 0;
420
+
421
+ controller.send('hello');
422
+ const frame = JSON.parse(instances[0].sent[0]);
423
+ expect(frame.systemPrompt).toBeUndefined();
424
+ expect(frame.systemPromptOverride).toBeUndefined();
425
+ });
426
+
427
+ it('lets an explicit opts.systemPrompt WIN over the binding prompt (client-override-wins)', async () => {
428
+ // Mirrors `_merge_persona_into_hello`: a field the client explicitly sends is
429
+ // preserved over the bound persona's.
430
+ const reg = await registry();
431
+ const controller = new ConversationController({
432
+ binding: {
433
+ kind: ConversationContextKind.PERSONA,
434
+ personaId: 'persona-floater',
435
+ systemPrompt: 'bound persona prompt',
436
+ systemPromptOverride: false,
437
+ },
438
+ registry: reg,
439
+ socketOptions: SOCKET_OPTS,
440
+ });
441
+ await connectController(controller);
442
+ instances[0].sent.length = 0;
443
+
444
+ controller.send('hi', {
445
+ systemPrompt: 'caller override prompt',
446
+ systemPromptOverride: true,
447
+ });
448
+ const frame = JSON.parse(instances[0].sent[0]);
449
+ expect(frame.systemPrompt).toBe('caller override prompt');
450
+ expect(frame.systemPromptOverride).toBe(true);
451
+ });
452
+
453
+ it('lets an explicit EMPTY-STRING opts.systemPrompt CLEAR the bound prompt for one send (presence, not truthiness)', async () => {
454
+ // Client-override-wins is by PRESENCE: an explicitly provided empty string is
455
+ // a deliberate "no prompt this turn", not "fall back to the binding". The
456
+ // earlier `||` form treated '' as absent and leaked the binding prompt. A
457
+ // nullish check keeps the override, and the falsy-drop gate emits no prompt
458
+ // key — so a bound persona can be explicitly silenced for a single send.
459
+ const reg = await registry();
460
+ const controller = new ConversationController({
461
+ binding: {
462
+ kind: ConversationContextKind.PERSONA,
463
+ personaId: 'persona-floater',
464
+ systemPrompt: 'bound persona prompt',
465
+ systemPromptOverride: true,
466
+ },
467
+ registry: reg,
468
+ socketOptions: SOCKET_OPTS,
469
+ });
470
+ await connectController(controller);
471
+ instances[0].sent.length = 0;
472
+
473
+ controller.send('plain question', { systemPrompt: '' });
474
+ const frame = JSON.parse(instances[0].sent[0]);
475
+ // The binding prompt did NOT leak through — both keys are dropped.
476
+ expect(frame.systemPrompt).toBeUndefined();
477
+ expect(frame.systemPromptOverride).toBeUndefined();
478
+ });
362
479
  });
363
480
 
364
481
  describe('ConversationController — model override', () => {
@@ -31,7 +31,9 @@ describe('KNOWN_PROMPT_ADDONS', () => {
31
31
  describe('getPromptAddonDescriptor', () => {
32
32
  it('returns the descriptor for a known id', () => {
33
33
  const d = getPromptAddonDescriptor(HELIOS_WORLD_STEERING_ADDON_ID);
34
- expect(d?.label).toBe('Helios world steering');
34
+ // A-DM2 renamed the label from 'Helios world steering' to 'Scene control'
35
+ // (the legacy [SET_SCENE] vocabulary was retired, tech-debt #113).
36
+ expect(d?.label).toBe('Scene control');
35
37
  });
36
38
 
37
39
  it('returns undefined for an unknown id', () => {
@@ -1,19 +1,22 @@
1
1
  /**
2
- * Tests for the Helios world-steering prompt addon.
2
+ * Tests for the scene-control prompt addon (A-DM2 retirement of the legacy
3
+ * `[SET_SCENE]` world-steering prose, tech-debt #113).
3
4
  *
4
5
  * Coverage:
5
- * - HELIOS_WORLD_STEERING_ADDON_ID is the expected literal (so the
6
- * Python constant in `shared/persona_addon_ids.py` and any
6
+ * - HELIOS_WORLD_STEERING_ADDON_ID is the expected literal (so the Python
7
+ * constant in `shared/persona_addon_ids.py` and any
7
8
  * `PersonaConfig.prompt_addon_ids` value can be cross-checked).
8
- * - getHeliosSteeringAddonText returns a non-empty string mentioning
9
- * all five marker names plus the 80-120 word target — protects
10
- * against partial-deletes during future refactors.
11
- * - buildHeliosSteeringSystemPrompt is idempotent: applying twice
12
- * produces the same output as one application.
13
- * - An empty/whitespace-only base prompt is allowed.
9
+ * - getHeliosSteeringAddonText now returns the SINGLE canonical `[SCENE:...]`
10
+ * scene-control vocabulary (it delegates to getDmSceneControlPromptText) and
11
+ * the RETIRED `[SET_SCENE]` / `[SWAP_SEED]` marker prose is GONE — single
12
+ * source of truth, no duplicate steering text.
13
+ * - buildHeliosSteeringSystemPrompt is idempotent and handles empty bases.
14
14
  */
15
15
 
16
- import { parseHeliosCommands } from '../../reactor/heliosTools';
16
+ import {
17
+ DM_SCENE_CONTROL_ADDON_SENTINEL,
18
+ getDmSceneControlPromptText,
19
+ } from '../../reactor/dmSceneControlPrompt';
17
20
  import {
18
21
  HELIOS_WORLD_STEERING_ADDON_ID,
19
22
  buildHeliosSteeringSystemPrompt,
@@ -26,49 +29,33 @@ describe('HELIOS_WORLD_STEERING_ADDON_ID', () => {
26
29
  });
27
30
  });
28
31
 
29
- describe('getHeliosSteeringAddonText', () => {
32
+ describe('getHeliosSteeringAddonText (retired → scene-control)', () => {
30
33
  it('returns a non-empty string', () => {
31
34
  const text = getHeliosSteeringAddonText();
32
35
  expect(typeof text).toBe('string');
33
36
  expect(text.length).toBeGreaterThan(0);
34
37
  });
35
38
 
36
- it('mentions all five marker names', () => {
37
- const text = getHeliosSteeringAddonText();
38
- expect(text).toMatch(/SET_SCENE/);
39
- expect(text).toMatch(/SWAP_SEED/);
40
- expect(text).toMatch(/PAUSE_WORLD/);
41
- expect(text).toMatch(/RESUME_WORLD/);
42
- expect(text).toMatch(/RESET_WORLD/);
39
+ it('delegates to the single canonical scene-control vocabulary', () => {
40
+ expect(getHeliosSteeringAddonText()).toBe(getDmSceneControlPromptText());
43
41
  });
44
42
 
45
- it('mentions the 80-120 word target', () => {
43
+ it('teaches the [SCENE:...] directive grammar (new single source)', () => {
46
44
  const text = getHeliosSteeringAddonText();
47
- expect(text).toMatch(/80-120 word/);
45
+ expect(text).toMatch(/\[SCENE:enter_world/);
46
+ expect(text).toMatch(/\[SCENE:exit_world\]/);
47
+ expect(text).toMatch(/\[SCENE:seek_video/);
48
48
  });
49
49
 
50
- // PR #193 round 10 regression — the example assistant turn embedded
51
- // in the addon was missing its closing `]`. Models trained on a
52
- // malformed example tend to emit malformed markers in production,
53
- // which both parseHeliosCommands and stripHeliosCommands silently
54
- // drop (parse) or pass through (strip — leaks raw brackets into the
55
- // user-facing transcript). Round-trip the example through the actual
56
- // parser as the source-of-truth marker validity check.
57
- it('embedded marker examples are parseable by the actual parser', () => {
50
+ it('NO LONGER contains the retired [SET_SCENE] world-steering prose', () => {
58
51
  const text = getHeliosSteeringAddonText();
59
- const commands = parseHeliosCommands(text);
60
- // The addon's exemplar shows SET_SCENE (the heaviest command),
61
- // SWAP_SEED, PAUSE/RESUME, and RESET in prose. At minimum, the
62
- // SET_SCENE example MUST parse — that's the marker with the
63
- // bracket structure most prone to malformation.
64
- const setSceneExamples = commands.filter(c => c.type === 'set_scene');
65
- expect(setSceneExamples.length).toBeGreaterThanOrEqual(1);
66
- // And whatever example we shipped has a real (non-empty) prompt.
67
- for (const cmd of setSceneExamples) {
68
- if (cmd.type === 'set_scene') {
69
- expect(cmd.prompt.length).toBeGreaterThan(0);
70
- }
71
- }
52
+ // The duplicate steering vocabulary is retired (tech-debt #113); grep-proof
53
+ // that none of the legacy marker names survive in the addon text.
54
+ expect(text).not.toMatch(/SET_SCENE/);
55
+ expect(text).not.toMatch(/SWAP_SEED/);
56
+ expect(text).not.toMatch(/PAUSE_WORLD/);
57
+ expect(text).not.toMatch(/RESUME_WORLD/);
58
+ expect(text).not.toMatch(/RESET_WORLD/);
72
59
  });
73
60
  });
74
61
 
@@ -76,7 +63,7 @@ describe('buildHeliosSteeringSystemPrompt', () => {
76
63
  it('appends the addon to a non-empty base prompt', () => {
77
64
  const out = buildHeliosSteeringSystemPrompt('You are Leo.');
78
65
  expect(out.startsWith('You are Leo.')).toBe(true);
79
- expect(out).toContain('SET_SCENE');
66
+ expect(out).toContain('[SCENE:enter_world');
80
67
  });
81
68
 
82
69
  it('returns just the addon for an empty base prompt', () => {
@@ -101,4 +88,9 @@ describe('buildHeliosSteeringSystemPrompt', () => {
101
88
  const twice = buildHeliosSteeringSystemPrompt(once);
102
89
  expect(twice).toBe(once);
103
90
  });
91
+
92
+ it('embeds the v2 sentinel (bumped for the retired-prose migration)', () => {
93
+ expect(getHeliosSteeringAddonText()).toContain(DM_SCENE_CONTROL_ADDON_SENTINEL);
94
+ expect(DM_SCENE_CONTROL_ADDON_SENTINEL).toContain(':v2');
95
+ });
104
96
  });
@@ -0,0 +1,288 @@
1
+ /**
2
+ * Tests for the B5 server-anchored session additions to `ChatWebSocket`:
3
+ * - `sendSessionAttach` outbound send method (wire shape matches
4
+ * `shared/websocket_models.py::SessionAttachMessage`).
5
+ * - `on('session_attached'|'presence', handler)` typed event dispatch for
6
+ * the inbound `session_attached` ack (with replayed `anchoredState`) and
7
+ * `presence` fan-out (`attached`/`detached`).
8
+ *
9
+ * Mirrors the StubWebSocket harness from `websocket-vision.test.ts` — jsdom's
10
+ * WebSocket actually dials, so we replace the constructor with a stub that
11
+ * records sends and drives open/message synchronously.
12
+ *
13
+ * Wire-shape source of truth: `api/chat/ws.py::_handle_session_attach` /
14
+ * `_detach_session` (the `session_attached` / `presence` event dicts) +
15
+ * `shared/websocket_models.py::SessionAttachMessage` (the inbound action).
16
+ *
17
+ * Land-dark: a client that never calls `sendSessionAttach` never receives
18
+ * these events — the new branches are unreached, the rest of the dispatch is
19
+ * byte-identical (asserted by the back-compat `onMessage` test).
20
+ */
21
+
22
+ import { ChatWebSocket } from '../websocket';
23
+ import type { PresenceEvent, SessionAttachedEvent } from '../websocket';
24
+
25
+ interface FakeWebSocket {
26
+ url: string;
27
+ readyState: number;
28
+ binaryType: string;
29
+ sent: string[];
30
+ onopen?: () => void;
31
+ onerror?: (err: Event) => void;
32
+ onmessage?: (event: MessageEvent) => void;
33
+ onclose?: () => void;
34
+ close: () => void;
35
+ send: (data: string | ArrayBuffer | Uint8Array) => void;
36
+ simulateOpen: () => void;
37
+ simulateMessage: (data: string) => void;
38
+ }
39
+
40
+ const instances: FakeWebSocket[] = [];
41
+
42
+ class StubWebSocket {
43
+ static CONNECTING = 0;
44
+ static OPEN = 1;
45
+ static CLOSING = 2;
46
+ static CLOSED = 3;
47
+
48
+ url: string;
49
+ readyState = StubWebSocket.CONNECTING;
50
+ binaryType = 'blob';
51
+ sent: string[] = [];
52
+ onopen?: () => void;
53
+ onerror?: (err: Event) => void;
54
+ onmessage?: (event: MessageEvent) => void;
55
+ onclose?: () => void;
56
+
57
+ constructor(url: string) {
58
+ this.url = url;
59
+ const ref = this as unknown as FakeWebSocket;
60
+ ref.close = () => {
61
+ this.readyState = StubWebSocket.CLOSED;
62
+ };
63
+ ref.send = (data: string | ArrayBuffer | Uint8Array) => {
64
+ if (typeof data === 'string') {
65
+ this.sent.push(data);
66
+ }
67
+ };
68
+ ref.simulateOpen = () => {
69
+ this.readyState = StubWebSocket.OPEN;
70
+ this.onopen?.();
71
+ };
72
+ ref.simulateMessage = (data: string) => {
73
+ this.onmessage?.({ data } as MessageEvent);
74
+ };
75
+ instances.push(ref);
76
+ }
77
+ }
78
+
79
+ const originalWebSocket = globalThis.WebSocket;
80
+
81
+ const flushMicrotasks = async (): Promise<void> => {
82
+ await Promise.resolve();
83
+ await Promise.resolve();
84
+ };
85
+
86
+ const lastSocket = (): FakeWebSocket => {
87
+ const last = instances[instances.length - 1];
88
+ if (!last) throw new Error('No WebSocket has been constructed yet');
89
+ return last;
90
+ };
91
+
92
+ beforeEach(() => {
93
+ instances.length = 0;
94
+ (globalThis as unknown as { WebSocket: typeof StubWebSocket }).WebSocket =
95
+ StubWebSocket;
96
+ });
97
+
98
+ afterEach(() => {
99
+ jest.useRealTimers();
100
+ (globalThis as { WebSocket?: typeof WebSocket }).WebSocket = originalWebSocket;
101
+ });
102
+
103
+ const openSocket = async (): Promise<ChatWebSocket> => {
104
+ const ws = new ChatWebSocket({ url: 'ws://test/chat', authToken: 'tok' });
105
+ const connectPromise = ws.connect();
106
+ await flushMicrotasks();
107
+ lastSocket().simulateOpen();
108
+ await connectPromise;
109
+ return ws;
110
+ };
111
+
112
+ describe('ChatWebSocket — sendSessionAttach (B5)', () => {
113
+ it('serializes the exact SessionAttachMessage wire shape', async () => {
114
+ const ws = await openSocket();
115
+ ws.sendSessionAttach({
116
+ action: 'session_attach',
117
+ videoId: 'v-abc',
118
+ connectionId: 'tab-1',
119
+ });
120
+ expect(lastSocket().sent).toHaveLength(1);
121
+ expect(JSON.parse(lastSocket().sent[0])).toEqual({
122
+ action: 'session_attach',
123
+ videoId: 'v-abc',
124
+ connectionId: 'tab-1',
125
+ });
126
+ });
127
+
128
+ it('sendSessionDetach sends the session_detach action', async () => {
129
+ const ws = await openSocket();
130
+ ws.sendSessionDetach();
131
+ expect(JSON.parse(lastSocket().sent[0])).toEqual({ action: 'session_detach' });
132
+ });
133
+
134
+ it('drops silently when the socket is not OPEN (best-effort, no throw)', () => {
135
+ // No connect() — there is no underlying socket. Mirrors the vision-send
136
+ // and sendPlaybackState best-effort contract.
137
+ const ws = new ChatWebSocket({ url: 'ws://test/chat' });
138
+ expect(() =>
139
+ ws.sendSessionAttach({
140
+ action: 'session_attach',
141
+ videoId: 'v-1',
142
+ connectionId: 'tab-1',
143
+ }),
144
+ ).not.toThrow();
145
+ expect(() => ws.sendSessionDetach()).not.toThrow();
146
+ expect(instances).toHaveLength(0);
147
+ });
148
+ });
149
+
150
+ describe('ChatWebSocket — inbound session presence dispatch (B5)', () => {
151
+ it('routes session_attached with replayed anchoredState to on() listeners', async () => {
152
+ const ws = await openSocket();
153
+ const handler = jest.fn();
154
+ ws.on('session_attached', handler);
155
+ lastSocket().simulateMessage(
156
+ JSON.stringify({
157
+ type: 'session_attached',
158
+ videoId: 'v-abc',
159
+ connectionId: 'tab-2',
160
+ peers: ['tab-1'],
161
+ anchoredState: {
162
+ currentTime: 42.5,
163
+ shotId: 'shot-7',
164
+ paused: true,
165
+ experienceSource: 'video',
166
+ updatedAt: 1718500000,
167
+ },
168
+ traceId: 'trace-xyz',
169
+ }),
170
+ );
171
+ expect(handler).toHaveBeenCalledTimes(1);
172
+ const received = handler.mock.calls[0]?.[0] as SessionAttachedEvent;
173
+ expect(received).toEqual({
174
+ type: 'session_attached',
175
+ videoId: 'v-abc',
176
+ connectionId: 'tab-2',
177
+ peers: ['tab-1'],
178
+ anchoredState: {
179
+ currentTime: 42.5,
180
+ shotId: 'shot-7',
181
+ paused: true,
182
+ experienceSource: 'video',
183
+ updatedAt: 1718500000,
184
+ },
185
+ });
186
+ });
187
+
188
+ it('routes session_attached with NO anchoredState (no fresh row yet)', async () => {
189
+ const ws = await openSocket();
190
+ const handler = jest.fn();
191
+ ws.on('session_attached', handler);
192
+ lastSocket().simulateMessage(
193
+ JSON.stringify({
194
+ type: 'session_attached',
195
+ videoId: 'v-abc',
196
+ connectionId: 'tab-1',
197
+ peers: [],
198
+ traceId: 't',
199
+ }),
200
+ );
201
+ const received = handler.mock.calls[0]?.[0] as SessionAttachedEvent;
202
+ expect(received.anchoredState).toBeUndefined();
203
+ expect(received.peers).toEqual([]);
204
+ });
205
+
206
+ it('routes a presence attached event (videoId present)', async () => {
207
+ const ws = await openSocket();
208
+ const handler = jest.fn();
209
+ ws.on('presence', handler);
210
+ lastSocket().simulateMessage(
211
+ JSON.stringify({
212
+ type: 'presence',
213
+ event: 'attached',
214
+ videoId: 'v-abc',
215
+ connectionId: 'tab-2',
216
+ traceId: 't',
217
+ }),
218
+ );
219
+ const received = handler.mock.calls[0]?.[0] as PresenceEvent;
220
+ expect(received).toEqual({
221
+ type: 'presence',
222
+ event: 'attached',
223
+ videoId: 'v-abc',
224
+ connectionId: 'tab-2',
225
+ });
226
+ });
227
+
228
+ it('routes a presence detached event (videoId omitted on the wire)', async () => {
229
+ const ws = await openSocket();
230
+ const handler = jest.fn();
231
+ ws.on('presence', handler);
232
+ lastSocket().simulateMessage(
233
+ JSON.stringify({
234
+ type: 'presence',
235
+ event: 'detached',
236
+ connectionId: 'tab-2',
237
+ traceId: 't',
238
+ }),
239
+ );
240
+ const received = handler.mock.calls[0]?.[0] as PresenceEvent;
241
+ expect(received).toEqual({
242
+ type: 'presence',
243
+ event: 'detached',
244
+ connectionId: 'tab-2',
245
+ });
246
+ });
247
+
248
+ it('off() removes the typed presence listener', async () => {
249
+ const ws = await openSocket();
250
+ const handler = jest.fn();
251
+ ws.on('presence', handler);
252
+ ws.off('presence', handler);
253
+ lastSocket().simulateMessage(
254
+ JSON.stringify({ type: 'presence', event: 'attached', connectionId: 'x' }),
255
+ );
256
+ expect(handler).not.toHaveBeenCalled();
257
+ });
258
+
259
+ it('preserves back-compat: session events still reach onMessage handlers', async () => {
260
+ const ws = await openSocket();
261
+ const onMessageHandler = jest.fn();
262
+ ws.onMessage(onMessageHandler);
263
+ lastSocket().simulateMessage(
264
+ JSON.stringify({
265
+ type: 'session_attached',
266
+ videoId: 'v',
267
+ connectionId: 'c',
268
+ peers: [],
269
+ }),
270
+ );
271
+ // The legacy onMessage path still fires so a ChatWsEvent-switch consumer
272
+ // can read the same frame too (same contract the vision events keep).
273
+ expect(onMessageHandler).toHaveBeenCalledTimes(1);
274
+ });
275
+
276
+ it('session dispatch ignores non-session events', async () => {
277
+ const ws = await openSocket();
278
+ const sessionHandler = jest.fn();
279
+ const presenceHandler = jest.fn();
280
+ ws.on('session_attached', sessionHandler);
281
+ ws.on('presence', presenceHandler);
282
+ lastSocket().simulateMessage(
283
+ JSON.stringify({ type: 'token', content: 'hello' }),
284
+ );
285
+ expect(sessionHandler).not.toHaveBeenCalled();
286
+ expect(presenceHandler).not.toHaveBeenCalled();
287
+ });
288
+ });
@@ -57,6 +57,27 @@ export interface ConversationContextBinding {
57
57
  entityId?: string;
58
58
  adventureSessionId?: string;
59
59
  partyPersonaIds?: string[];
60
+ /**
61
+ * The persona's system prompt to carry on this conversation (SP1). The `text`
62
+ * send path does NOT load the persona server-side — it reads the prompt from
63
+ * the frame (`api/chat/ws.py` `SendActionMessage.systemPrompt`), unlike the
64
+ * `tts_stt` hello which `_merge_persona_into_hello` resolves server-side. So a
65
+ * standalone persona-face chat must carry the persona's `custom_system_prompt`
66
+ * on the binding for a TYPED turn to speak in-character. Like the other fields
67
+ * it is a `buildHelloPayload` arg, so the binding cannot drift from the wire.
68
+ * Falsy ⇒ dropped (no prompt → the backend uses the default assistant voice;
69
+ * land-dark for non-persona bindings).
70
+ */
71
+ systemPrompt?: string;
72
+ /**
73
+ * Whether `systemPrompt` REPLACES the default system prompt (`true`) or is
74
+ * appended to it (`false`/omitted). Mirrors `PersonaConfig.system_prompt_override`
75
+ * and `_merge_persona_into_hello`'s `systemPromptOverride` contract. Only sent
76
+ * when `systemPrompt` is present — the `buildHelloPayload` falsy-drop on
77
+ * `systemPrompt` gates both together (audio.ts:453), so an override flag with no
78
+ * prompt is a no-op.
79
+ */
80
+ systemPromptOverride?: boolean;
60
81
  }
61
82
 
62
83
  /**
@@ -79,12 +100,24 @@ export type HelloArgs = Parameters<typeof buildHelloPayload>[0];
79
100
  * fields too: an empty-string id is treated as "unset" (ids are real
80
101
  * UUIDs/handles — an `''` is a caller mistake, not a value to send), keeping the
81
102
  * hello free of meaningless empty fields.
103
+ *
104
+ * `systemPrompt`/`systemPromptOverride` (SP1) follow the SAME falsy-drop: an
105
+ * empty/absent prompt drops BOTH so the wire is byte-identical when unset, and
106
+ * the override flag only rides when a prompt is present (matching
107
+ * `buildHelloPayload`'s `...(systemPrompt ? { systemPrompt, systemPromptOverride } : {})`
108
+ * gate, audio.ts:453).
82
109
  */
83
110
  export function toHelloArgs(
84
111
  binding: ConversationContextBinding,
85
112
  ): Pick<
86
113
  HelloArgs,
87
- 'videoId' | 'personaId' | 'entityId' | 'adventureSessionId' | 'partyPersonaIds'
114
+ | 'videoId'
115
+ | 'personaId'
116
+ | 'entityId'
117
+ | 'adventureSessionId'
118
+ | 'partyPersonaIds'
119
+ | 'systemPrompt'
120
+ | 'systemPromptOverride'
88
121
  > {
89
122
  return {
90
123
  ...(binding.videoId ? { videoId: binding.videoId } : {}),
@@ -96,5 +129,11 @@ export function toHelloArgs(
96
129
  ...(binding.partyPersonaIds && binding.partyPersonaIds.length > 0
97
130
  ? { partyPersonaIds: [...binding.partyPersonaIds] }
98
131
  : {}),
132
+ ...(binding.systemPrompt
133
+ ? {
134
+ systemPrompt: binding.systemPrompt,
135
+ systemPromptOverride: binding.systemPromptOverride ?? false,
136
+ }
137
+ : {}),
99
138
  };
100
139
  }