@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,6 +60,22 @@ export interface ConversationSendOptions {
60
60
  * passes its prior turns here per send, exactly like the chat-ws page does.
61
61
  */
62
62
  messages?: ConversationHistoryMessage[];
63
+ /**
64
+ * A per-send system-prompt override (SP1). When provided, it WINS over the
65
+ * binding's `systemPrompt` — matching `_merge_persona_into_hello`'s
66
+ * client-override-wins contract (a field the client explicitly sends is
67
+ * preserved over the persona's). Omit it and the binding's persona prompt
68
+ * (if any) rides instead; omit both and no prompt is sent (the backend uses
69
+ * the default assistant prompt — land-dark for non-persona conversations).
70
+ */
71
+ systemPrompt?: string;
72
+ /**
73
+ * Whether `opts.systemPrompt` REPLACES (`true`) or appends to (`false`/omitted)
74
+ * the default prompt. Only meaningful alongside an explicit `opts.systemPrompt`
75
+ * — it is NOT applied to the binding's prompt (the binding carries its own
76
+ * `systemPromptOverride`).
77
+ */
78
+ systemPromptOverride?: boolean;
63
79
  }
64
80
 
65
81
  export interface ConversationControllerOptions {
@@ -215,6 +231,24 @@ export class ConversationController {
215
231
  const active = this.activeParticipant();
216
232
  const args = this.toHelloArgs();
217
233
  const modelId = this.modelOverride ?? active?.modelId;
234
+ // Persona system-prompt (SP1): the `text` send path reads the prompt from
235
+ // THIS frame (it does NOT load the persona server-side — only the `tts_stt`
236
+ // hello does, via `_merge_persona_into_hello`), so a standalone persona chat
237
+ // must thread its prompt on every typed turn or the reply comes back in the
238
+ // default assistant voice. CLIENT-OVERRIDE-WINS, by PRESENCE not truthiness:
239
+ // an explicitly provided `opts.systemPrompt` beats the binding's prompt
240
+ // (mirrors `_merge_persona_into_hello`: a field the client sends is preserved
241
+ // over the persona's). A nullish check (not `||`) means an explicit EMPTY
242
+ // STRING still wins — it clears the bound prompt for this send (the falsy-drop
243
+ // gate below then emits no prompt key), which `||` could not express (it would
244
+ // fall back to the binding). Both nullish on opts ⇒ the binding's prompt rides;
245
+ // falsy on the resolved value ⇒ no prompt key (byte-identical, land-dark for
246
+ // non-persona conversations).
247
+ const systemPrompt = opts?.systemPrompt ?? args.systemPrompt;
248
+ const systemPromptOverride =
249
+ opts?.systemPrompt != null
250
+ ? (opts.systemPromptOverride ?? false)
251
+ : (args.systemPromptOverride ?? false);
218
252
  this.socket.send(text, {
219
253
  ...(args.videoId ? { videoId: args.videoId } : {}),
220
254
  ...(args.entityId ? { entityId: args.entityId } : {}),
@@ -232,6 +266,11 @@ export class ConversationController {
232
266
  ...(args.personaId ? { personaId: args.personaId } : {}),
233
267
  ...(active?.personaId ? { personaId: active.personaId } : {}),
234
268
  ...(modelId ? { modelId } : {}),
269
+ // Persona prompt rides every typed turn (SP1) so the reply is in-character.
270
+ // Both keys travel together (gated on the resolved prompt), matching the
271
+ // `buildHelloPayload`/`SendActionMessage` shape where `systemPromptOverride`
272
+ // is meaningless without `systemPrompt`.
273
+ ...(systemPrompt ? { systemPrompt, systemPromptOverride } : {}),
235
274
  // Omitted when empty so a zero-history send stays byte-identical to the
236
275
  // pre-0.30.0 wire (the backend defaults a missing `messages` to []).
237
276
  ...(opts?.messages?.length ? { messages: opts.messages } : {}),
@@ -0,0 +1,85 @@
1
+ /**
2
+ * Canonical DM scene-control prompt vocabulary (Dashboard Spec A §10A.6,
3
+ * Block B) — the SINGLE SOURCE of the world-/scene-steering instruction text on
4
+ * the client side.
5
+ *
6
+ * This mirrors the backend constant
7
+ * `shared/adventure_prompts.py::DM_SCENE_CONTROL_INSTRUCTIONS`. The two live in
8
+ * different runtimes (Python dispatcher vs TS client), so they cannot literally
9
+ * `import` one another; keep them in lock-step (the directive grammar is the
10
+ * contract the backend `DM_SCENE_TAG_PATTERN` parses).
11
+ *
12
+ * A-DM2 RETIRES the legacy Helios world-steering addon text (the divergent
13
+ * `[SET_SCENE]` / `[SWAP_SEED]` marker prose that used to live in
14
+ * `toolPromptAddon.ts`). That prototype vocabulary was a SECOND, drifting
15
+ * scene-steering instruction set (tech-debt #113); it is replaced by this one
16
+ * `[SCENE:...]` grammar so there is exactly one place that teaches a model how to
17
+ * drive the experience surface. `toolPromptAddon.ts::getHeliosSteeringAddonText`
18
+ * now returns THIS text, so any persona that still carries the
19
+ * `helios-world-steering` addon id gets the current vocabulary.
20
+ *
21
+ * NOTE on the runtime command layer: the `HeliosCommand` union +
22
+ * `dispatchHeliosCommand` (the world-ADAPTER capability layer that actually
23
+ * drives the Reactor SDK) are a separate, live concern and are unchanged — they
24
+ * are runtime command dispatch, not model-facing steering PROSE.
25
+ */
26
+
27
+ /**
28
+ * Version sentinel embedded in the addon text. Used by
29
+ * `buildHeliosSteeringSystemPrompt` for idempotent reapplication. Bumped from
30
+ * `v1` (the retired `[SET_SCENE]` prose) to `v2` (this `[SCENE:...]` vocabulary)
31
+ * so a cached upstream prompt built against the old prose is detectably stale.
32
+ */
33
+ export const DM_SCENE_CONTROL_ADDON_SENTINEL =
34
+ '<!-- helios-world-steering-addon:v2 -->';
35
+
36
+ /**
37
+ * The canonical `[SCENE:...]` scene-control instruction text. Mirrors the
38
+ * backend `DM_SCENE_CONTROL_INSTRUCTIONS` grammar (same directive kinds, same
39
+ * one-tag-per-own-line rule). Kept as a function (not a const) so callers don't
40
+ * accidentally share-and-mutate the underlying string.
41
+ */
42
+ export function getDmSceneControlPromptText(): string {
43
+ return [
44
+ DM_SCENE_CONTROL_ADDON_SENTINEL,
45
+ '## Scene Control',
46
+ '',
47
+ 'You can control the viewer’s experience surface using scene tags. ' +
48
+ 'Emit at most ONE tag per turn, each on its OWN line, after your ' +
49
+ 'natural-language reply. The tag is parsed and acted on; it is stripped ' +
50
+ 'from what the viewer reads.',
51
+ '',
52
+ '### Tags',
53
+ '',
54
+ '- `[SCENE:enter_world prompt="<optional atmosphere or directive>"]` — ' +
55
+ 'transport the viewer into the interactive world model. The optional ' +
56
+ 'prompt grounds the world in the established scene (subject, environment, ' +
57
+ 'lighting, mood); weave existing character continuity in so identity is ' +
58
+ 'preserved across the transition.',
59
+ '- `[SCENE:exit_world]` — return the viewer to the video.',
60
+ '- `[SCENE:seek_video t=<seconds>]` — jump the video to a specific ' +
61
+ 'moment (e.g. `t=142.5`).',
62
+ '',
63
+ '### Rules',
64
+ '',
65
+ '1. Use these sparingly and purposefully, as a director would: to ' +
66
+ 'punctuate a narrative beat, reveal a hidden moment, or immerse the ' +
67
+ 'viewer at a climax.',
68
+ '2. One tag per turn, on its own line, at the END of your response.',
69
+ '3. If you can answer in words alone — describe the world, recall a ' +
70
+ 'past moment, plan a beat — do NOT emit a tag. Tags are for actions, ' +
71
+ 'not exposition.',
72
+ '',
73
+ '### Example',
74
+ '',
75
+ 'User: “Take me into that forest.”',
76
+ '',
77
+ 'Assistant: The trees pull close and the air goes green and still — ' +
78
+ 'step through.',
79
+ '',
80
+ '[SCENE:enter_world prompt="a hushed old-growth forest at dusk, shafts of ' +
81
+ 'green light through the canopy, mist low between the trunks, the path ' +
82
+ 'ahead barely visible, mood: hushed and expectant"]',
83
+ '',
84
+ ].join('\n');
85
+ }
@@ -13,6 +13,9 @@ export * from './scenesFromEnrichment';
13
13
  // (imported by both mappers); they are deliberately NOT re-exported here.
14
14
  export * from './storyTimeline';
15
15
  export * from './heliosTools';
16
+ // A-DM2 — canonical [SCENE:...] scene-control vocabulary (single source; the
17
+ // retired-`[SET_SCENE]`-prose replacement, tech-debt #113).
18
+ export * from './dmSceneControlPrompt';
16
19
  export * from './toolPromptAddon';
17
20
  export * from './entitySearch';
18
21
  export * from './heliosCommandDispatcher';
@@ -37,9 +37,9 @@ export interface PromptAddonDescriptor {
37
37
  export const KNOWN_PROMPT_ADDONS: readonly PromptAddonDescriptor[] = [
38
38
  {
39
39
  id: HELIOS_WORLD_STEERING_ADDON_ID,
40
- label: 'Helios world steering',
40
+ label: 'Scene control',
41
41
  description:
42
- 'Lets this persona drive a live Helios scene from the /interactive/chat page by emitting inline scene-change markers ([SET_SCENE], [SWAP_SEED], etc.). Auto-enabled when the persona is bound to a source video or character image.',
42
+ 'Lets this persona drive the viewer’s experience surface with scene-control tags ([SCENE:enter_world], [SCENE:seek_video], [SCENE:exit_world]) — transport into the world model, seek the video, or return to it. Auto-enabled when the persona is bound to a source video or character image.',
43
43
  },
44
44
  ];
45
45
 
@@ -1,126 +1,76 @@
1
1
  /**
2
- * System-prompt addon that teaches a chat model to emit Helios
3
- * world-steering markers.
2
+ * System-prompt addon that teaches a chat model to drive the viewer's
3
+ * experience surface with scene-control tags.
4
4
  *
5
- * Phase 3 hooks this addon up via `PersonaConfig.prompt_addon_ids`: when
6
- * a persona declares `prompt_addon_ids: ['helios-world-steering']`, the
7
- * browser-side `/interactive/chat` page looks up the addon text via
8
- * `getHeliosSteeringAddonText()` and concatenates it onto the persona's
9
- * `custom_system_prompt` before sending each chat turn via the WS
10
- * `systemPrompt` field.
5
+ * A-DM2 RETIREMENT (tech-debt #113): this addon used to teach a SECOND,
6
+ * divergent world-steering vocabulary — the legacy `[SET_SCENE]` / `[SWAP_SEED]`
7
+ * / `[PAUSE_WORLD]` marker prose (the Phase-3 Helios prototype, whose only live
8
+ * web consumer `/interactive/chat` was removed in R0-4). That duplicate steering
9
+ * text is GONE. `getHeliosSteeringAddonText()` now delegates to the single
10
+ * canonical scene-control vocabulary in `dmSceneControlPrompt.ts` (the
11
+ * `[SCENE:...]` grammar that mirrors the backend
12
+ * `shared/adventure_prompts.py::DM_SCENE_CONTROL_INSTRUCTIONS` and is parsed by
13
+ * the dispatcher's `DM_SCENE_TAG_PATTERN`). There is now exactly ONE place that
14
+ * teaches a model how to steer the scene.
11
15
  *
12
- * The backend has no awareness of the addon ID's semantics — the field
13
- * is just metadata on `PersonaConfig`. See
14
- * `shared/persona_addon_ids.py` for the matching Python constant.
16
+ * The function name + the addon id (`helios-world-steering`) are kept for
17
+ * backward compatibility — `PersonaConfig.prompt_addon_ids` rows, the persona
18
+ * UI, and the pinned `../Web-App` consumer all reference them. Only the TEXT the
19
+ * addon produces changed (now the current `[SCENE:...]` vocabulary).
20
+ *
21
+ * The backend has no awareness of the addon ID's semantics — the field is just
22
+ * metadata on `PersonaConfig`. See `shared/persona_addon_ids.py` for the matching
23
+ * Python constant.
15
24
  */
16
25
 
17
- import { HELIOS_WORLD_STEERING_ADDON_ID } from './toolPromptAddonId';
26
+ import {
27
+ DM_SCENE_CONTROL_ADDON_SENTINEL,
28
+ getDmSceneControlPromptText,
29
+ } from './dmSceneControlPrompt';
18
30
 
19
31
  export { HELIOS_WORLD_STEERING_ADDON_ID } from './toolPromptAddonId';
32
+ // NOTE: the canonical `getDmSceneControlPromptText` + `DM_SCENE_CONTROL_ADDON_SENTINEL`
33
+ // are exported once from the barrel via `export * from './dmSceneControlPrompt'`
34
+ // (reactor/index.ts) — not re-exported here, to avoid an ambiguous double export.
20
35
 
21
36
  /**
22
37
  * Marker the addon uses to verify idempotent reapplication. The build
23
- * function looks for this string in the base prompt before appending,
24
- * so calling `buildHeliosSteeringSystemPrompt(buildHeliosSteeringSystemPrompt(p))`
25
- * returns the same value as a single application. Choose something
26
- * unique enough that a normal persona prompt would never include it
27
- * verbatim.
38
+ * function looks for this string in the base prompt before appending, so calling
39
+ * `buildHeliosSteeringSystemPrompt(buildHeliosSteeringSystemPrompt(p))` returns
40
+ * the same value as a single application. Single-sourced from the canonical
41
+ * scene-control module (bumped to `v2` for the retired-prose migration) so the
42
+ * sentinel can't drift from the text it guards.
28
43
  */
29
- const ADDON_SENTINEL = '<!-- helios-world-steering-addon:v1 -->';
44
+ const ADDON_SENTINEL = DM_SCENE_CONTROL_ADDON_SENTINEL;
30
45
 
31
46
  /**
32
- * Stable, model-friendly addon text that teaches the marker grammar
33
- * and the rules around when to emit each marker. Kept as a function
34
- * (not a const) so callers don't accidentally share-and-mutate the
47
+ * Stable, model-friendly addon text that teaches the scene-control grammar.
48
+ *
49
+ * RETIRED: the legacy `[SET_SCENE]` marker prose. RETURNS: the single canonical
50
+ * `[SCENE:...]` scene-control vocabulary (`getDmSceneControlPromptText`). Kept as
51
+ * a function (not a const) so callers don't accidentally share-and-mutate the
35
52
  * underlying string.
36
53
  *
37
- * Update the version sentinel inside the function if the addon
38
- * semantics change in a way the model needs to relearn — `prompt_addon_ids`
39
- * is a stable identifier, but cached upstream chat history may have
40
- * trained the model against the OLD prose. The sentinel doubles as a
41
- * "did the LLM see the new version?" diagnostic.
54
+ * @deprecated Prefer {@link getDmSceneControlPromptText} directly — this alias
55
+ * is retained only so existing `helios-world-steering` callers keep working; it
56
+ * now returns the same canonical scene-control text.
42
57
  */
43
58
  export function getHeliosSteeringAddonText(): string {
44
- return [
45
- ADDON_SENTINEL,
46
- '## World Steering Capability',
47
- '',
48
- 'This conversation is running alongside a live Helios video stream that ' +
49
- "you can steer directly. When the user asks you to change the visible " +
50
- 'world — scene changes, atmospheric shifts, character swaps, pausing, ' +
51
- 'resetting — emit ONE of the following bracket-style markers at the ' +
52
- 'VERY END of your response, after your natural-language reply.',
53
- '',
54
- '### Markers',
55
- '',
56
- '- `[SET_SCENE: "<80-120 word Helios-quality scene prompt>"]` — change ' +
57
- 'the live world to a new scene. The prompt MUST follow the Helios ' +
58
- "prompt-guide style: name the subject, the environment, the lighting, " +
59
- 'the camera framing (wide / medium / medium close-up / close-up), and ' +
60
- 'the mood. Target 80-120 words. Example argument: "wide cinematic ' +
61
- 'shot, a man in a red coat walks across a snowy bridge at dusk, soft ' +
62
- "golden hour light streaming through wrought-iron railings, medium " +
63
- 'tracking shot following him from the right, his breath visible in the ' +
64
- 'cold air, distant city lights glowing behind him, mood: contemplative ' +
65
- 'and quietly hopeful, 35mm film grain, cinematic depth of field."',
66
- '- `[SWAP_SEED: "<entity name>"]` — replace the active seed image ' +
67
- 'with a different entity from the current video. The entity name must ' +
68
- 'match one of the entities the user has shown you (matching is ' +
69
- "case-insensitive). If you're not sure of the name, don't emit this " +
70
- 'marker — ask the user to clarify instead.',
71
- '- `[PAUSE_WORLD]` — pause the live stream at the current frame. Use ' +
72
- 'when the user wants to freeze the action.',
73
- '- `[RESUME_WORLD]` — resume a paused stream.',
74
- '- `[RESET_WORLD]` — reset the stream to frame 0 and clear pending ' +
75
- 'prompts. Use only when the user explicitly asks to start over.',
76
- '',
77
- '### Critical Rules',
78
- '',
79
- '1. Emit AT MOST ONE marker per turn. If the user asks for a sequence ' +
80
- '(e.g. "pause then change the scene"), pick the first action and tell ' +
81
- 'them you\'ll do the next one when they ask.',
82
- '2. Markers go at the END of your response, after a blank line, never ' +
83
- 'mixed into the middle of prose.',
84
- '3. SET_SCENE prompts must be detailed and ground in the established ' +
85
- 'world. Bland three-word prompts produce bland output.',
86
- '4. For SET_SCENE, weave the existing entity / character continuity into ' +
87
- "the prompt so identity is preserved across the cut. Don't invent a " +
88
- 'brand-new protagonist mid-scene unless the user explicitly asks for ' +
89
- 'one.',
90
- '5. If the user asks something you can answer in words alone — describe ' +
91
- "the world, recall a past moment, plan a beat — DON'T emit a marker. " +
92
- 'Markers are for actions, not exposition.',
93
- '',
94
- '### Example',
95
- '',
96
- 'User: "Make it start raining and feel a bit lonelier."',
97
- '',
98
- 'Assistant: Pulling the warmth out of the light and adding a slow grey ' +
99
- 'rain — give it a beat to settle in.',
100
- '',
101
- '[SET_SCENE: "wide cinematic shot, a man in a long coat stands alone on ' +
102
- 'a deserted cobblestone bridge in a slow grey downpour, single sodium ' +
103
- "streetlamp casting a cone of amber light onto wet stone, distant city " +
104
- 'reflections rippling in puddles, medium tracking shot pulling back ' +
105
- 'slightly, his breath fogging in the cold air, mood: melancholy and ' +
106
- 'introspective, 35mm film grain, shallow depth of field, muted blue and ' +
107
- 'amber color palette, soft falling rain catching the lamp light."]',
108
- '',
109
- ].join('\n');
59
+ return getDmSceneControlPromptText();
110
60
  }
111
61
 
112
62
  /**
113
- * Concatenate the Helios steering addon onto an arbitrary base system
114
- * prompt. Idempotent: a prompt that already contains the addon sentinel
115
- * is returned unchanged.
63
+ * Concatenate the scene-control addon onto an arbitrary base system prompt.
64
+ * Idempotent: a prompt that already contains the addon sentinel is returned
65
+ * unchanged.
116
66
  *
117
- * An empty base prompt is allowed — the addon stands on its own and
118
- * works without a persona backstory (the test suite covers this).
67
+ * An empty base prompt is allowed — the addon stands on its own and works
68
+ * without a persona backstory (the test suite covers this).
119
69
  *
120
- * @param baseSystemPrompt - persona's `custom_system_prompt` (may be
121
- * empty string or whitespace).
122
- * @returns concatenated prompt: `<base>\n\n<addon>` when the base is
123
- * non-empty, just `<addon>` otherwise.
70
+ * @param baseSystemPrompt - persona's `custom_system_prompt` (may be empty
71
+ * string or whitespace).
72
+ * @returns concatenated prompt: `<base>\n\n<addon>` when the base is non-empty,
73
+ * just `<addon>` otherwise.
124
74
  */
125
75
  export function buildHeliosSteeringSystemPrompt(
126
76
  baseSystemPrompt: string,
package/src/websocket.ts CHANGED
@@ -86,6 +86,30 @@ export interface PlaybackState {
86
86
  paused: boolean;
87
87
  }
88
88
 
89
+ /**
90
+ * The anchored playback state replayed in a `session_attached` ack (B5,
91
+ * Dashboard Redesign §10). Read server-side from the EXISTING
92
+ * `PlaybackStateStore` row (`(userId, videoId)`) and replayed verbatim to a
93
+ * newly-attaching connection so a chat opened on one device picks up where
94
+ * another device left the playhead (cross-device hand-off, owner decision D6).
95
+ *
96
+ * Camel-case mirrors the dict `api/chat/ws.py::_handle_session_attach` builds
97
+ * (`anchoredState`): `current_time → currentTime`, `experience_source →
98
+ * experienceSource`, etc. Omitted from the ack entirely when the store has no
99
+ * fresh row yet — the attach is still confirmed, the field is just `undefined`.
100
+ */
101
+ export interface SessionAnchoredState {
102
+ currentTime: number;
103
+ /** `null` on the wire when the last publish carried no shot id. */
104
+ shotId?: string | null;
105
+ paused: boolean;
106
+ /** The active experience source (`video` / `world` / `generated`); `null`
107
+ * for a legacy frame published before A10 added the field. */
108
+ experienceSource?: string | null;
109
+ /** Server epoch-seconds the row was last written. */
110
+ updatedAt?: number;
111
+ }
112
+
89
113
  export type ChatWsEvent =
90
114
  | { type: 'token'; timestamp?: number; content: string; personaId?: string }
91
115
  | {
@@ -210,6 +234,47 @@ export type ChatWsEvent =
210
234
  | 'seek_video'
211
235
  | 'set_experience_source';
212
236
  params: Record<string, unknown>;
237
+ }
238
+ | {
239
+ /**
240
+ * Dashboard Spec B (§10 / B5) — acknowledgement that this connection
241
+ * joined a SERVER-ANCHORED chat session (it sent `session_attach`).
242
+ * Emitted by `api/chat/ws.py::_handle_session_attach` (wire type
243
+ * `"session_attached"`, single-sourced in
244
+ * `SESSION_ATTACHED_EVENT_TYPE`). Carries the OTHER connection ids
245
+ * already present on the anchor (`peers`) and — when the existing
246
+ * `PlaybackStateStore` had a fresh row — the `anchoredState` the other
247
+ * device left behind (the cross-device hand-off playhead). Added as a
248
+ * union variant so exhaustive consumers get a typed arm; no live
249
+ * consumer is wired until the floater handles it. Land-dark: a client
250
+ * that never sends `session_attach` never receives this.
251
+ */
252
+ type: 'session_attached';
253
+ timestamp?: number;
254
+ videoId: string;
255
+ connectionId: string;
256
+ peers: string[];
257
+ anchoredState?: SessionAnchoredState;
258
+ }
259
+ | {
260
+ /**
261
+ * Dashboard Spec B (§10 / B5) — presence fan-out: another tab/device
262
+ * just `attached` to (or `detached` from) the SAME server-anchored
263
+ * session. Emitted by `_handle_session_attach` / `_detach_session`
264
+ * (wire type `"presence"`, `event` ∈ {`attached`,`detached`} —
265
+ * single-sourced in `PRESENCE_EVENT_TYPE` / `PRESENCE_ATTACHED` /
266
+ * `PRESENCE_DETACHED`). The originator is excluded from its own
267
+ * `attached` fan-out (it learns the peer list from the ack instead).
268
+ * `videoId` is present on `attached`, omitted on `detached` (the
269
+ * survivor already knows the anchor). Added as a union variant so the
270
+ * floater can render a lightweight presence indicator; absence of peers
271
+ * means it never fires (byte-identical to a no-peer floater).
272
+ */
273
+ type: 'presence';
274
+ timestamp?: number;
275
+ event: 'attached' | 'detached';
276
+ connectionId: string;
277
+ videoId?: string;
213
278
  };
214
279
 
215
280
  /**
@@ -292,7 +357,15 @@ export type BinaryHandler = (data: ArrayBuffer) => void;
292
357
  *
293
358
  * Spec: `specs/2026-05-22-phase-2-multimodal-watch.md`.
294
359
  */
295
- export type ChatWsTypedEvent = 'vision_answer' | 'vision_ice' | 'vision_status';
360
+ export type ChatWsTypedEvent =
361
+ | 'vision_answer'
362
+ | 'vision_ice'
363
+ | 'vision_status'
364
+ // Dashboard Spec B (§10 / B5) — server-anchored session presence. These ride
365
+ // the SAME typed-event dispatcher as the vision-signaling events (one
366
+ // dispatcher, not a parallel one) keyed by their inbound `type` discriminator.
367
+ | 'session_attached'
368
+ | 'presence';
296
369
 
297
370
  /** Inbound `vision_answer` payload from the backend after it processes
298
371
  * the publisher's offer. */
@@ -321,6 +394,31 @@ export interface VisionStatusEvent {
321
394
  processingPaused: boolean;
322
395
  }
323
396
 
397
+ /**
398
+ * Inbound `session_attached` ack payload (B5). Mirrors the
399
+ * {@link ChatWsEvent} `session_attached` variant — the SAME shape the server
400
+ * sends (camel-case on the wire already), surfaced to typed `on()` listeners
401
+ * so the floater can replay the anchored playhead + seed the peer list.
402
+ */
403
+ export interface SessionAttachedEvent {
404
+ type: 'session_attached';
405
+ videoId: string;
406
+ connectionId: string;
407
+ peers: string[];
408
+ anchoredState?: SessionAnchoredState;
409
+ }
410
+
411
+ /**
412
+ * Inbound `presence` payload (B5) — a peer tab/device `attached`/`detached`.
413
+ * Mirrors the {@link ChatWsEvent} `presence` variant; camel-case on the wire.
414
+ */
415
+ export interface PresenceEvent {
416
+ type: 'presence';
417
+ event: 'attached' | 'detached';
418
+ connectionId: string;
419
+ videoId?: string;
420
+ }
421
+
324
422
  export type ChatWsTypedEventPayload<E extends ChatWsTypedEvent> =
325
423
  E extends 'vision_answer'
326
424
  ? VisionAnswerEvent
@@ -328,7 +426,11 @@ export type ChatWsTypedEventPayload<E extends ChatWsTypedEvent> =
328
426
  ? VisionIceEvent
329
427
  : E extends 'vision_status'
330
428
  ? VisionStatusEvent
331
- : never;
429
+ : E extends 'session_attached'
430
+ ? SessionAttachedEvent
431
+ : E extends 'presence'
432
+ ? PresenceEvent
433
+ : never;
332
434
 
333
435
  export type TypedEventHandler<E extends ChatWsTypedEvent = ChatWsTypedEvent> = (
334
436
  payload: ChatWsTypedEventPayload<E>,
@@ -744,6 +846,48 @@ export class ChatWebSocket {
744
846
  this._sendVisionJson({ action: 'vision_detach' });
745
847
  }
746
848
 
849
+ /**
850
+ * Attach this connection to a SERVER-ANCHORED chat session (B5, Dashboard
851
+ * Redesign §10). The anchor is the `(userId, videoId)` pair — the same key
852
+ * the cross-device `PlaybackStateStore` row uses — so the server can replay
853
+ * the playhead another device left (a `session_attached` ack) and fan
854
+ * `presence` events between the user's tabs/devices (owner decision D6).
855
+ *
856
+ * Wire shape EXACTLY matches `shared/websocket_models.py::SessionAttachMessage`
857
+ * (`{ action, videoId, connectionId }`, `extra="forbid"`). `connectionId` is
858
+ * an opaque per-tab/device label the caller mints (the server treats it only
859
+ * as a fan-out name, never for auth — the row is scoped to the authenticated
860
+ * user). Fire-and-forget like the vision sends: best-effort, drops silently
861
+ * when the socket isn't OPEN (the server reconciles on the next attach /
862
+ * disconnect). Land-dark: a client that never calls this is byte-identical.
863
+ */
864
+ sendSessionAttach(payload: {
865
+ action: 'session_attach';
866
+ videoId: string;
867
+ connectionId: string;
868
+ }): void {
869
+ this._sendVisionJson({
870
+ action: payload.action,
871
+ videoId: payload.videoId,
872
+ connectionId: payload.connectionId,
873
+ });
874
+ }
875
+
876
+ /**
877
+ * Leave the server-anchored session WITHOUT closing the socket (B5). Needed
878
+ * when a LONG-LIVED ADOPTED socket (the Watch surface's shared socket) rebinds
879
+ * away from its video session — e.g. the floater switches from a video
880
+ * conversation to a persona one — so the connection doesn't stay registered
881
+ * under the old `(user, video)` anchor (a stale peer for the user's other
882
+ * tabs). The backend (`api/chat/ws.py` `session_detach` action) fans a
883
+ * `detached` presence to the survivors + clears its per-connection holder.
884
+ * Fire-and-forget like the other session/vision sends; the backend also
885
+ * detaches on socket close, so a dropped detach is harmless.
886
+ */
887
+ sendSessionDetach(): void {
888
+ this._sendVisionJson({ action: 'session_detach' });
889
+ }
890
+
747
891
  /**
748
892
  * Register a typed listener for a vision-signaling event. Returns
749
893
  * void (matches the `messageHandlers` pattern); unsubscribe via
@@ -785,6 +929,46 @@ export class ChatWebSocket {
785
929
  private _dispatchVisionEvent(raw: Record<string, unknown>): void {
786
930
  const t = raw['type'] as string | undefined;
787
931
  const action = raw['action'] as string | undefined;
932
+ // B5 — server-anchored session presence. These inbound events are already
933
+ // camel-case on the wire (the server builds the dict in camelCase), so we
934
+ // pass the fields through to typed listeners after a defensive coerce. The
935
+ // raw event ALSO flows on through `messageHandlers` as a `WebSocketMessage`
936
+ // (the caller in `onmessage`), so a `ChatWsEvent`-switch consumer can read
937
+ // the same frame too — same back-compat contract the vision events keep.
938
+ if (t === 'session_attached') {
939
+ const anchored = raw['anchoredState'] as
940
+ | Record<string, unknown>
941
+ | undefined;
942
+ const payload: SessionAttachedEvent = {
943
+ type: 'session_attached',
944
+ videoId: String(raw['videoId'] ?? ''),
945
+ connectionId: String(raw['connectionId'] ?? ''),
946
+ peers: Array.isArray(raw['peers']) ? (raw['peers'] as string[]) : [],
947
+ };
948
+ if (anchored) {
949
+ payload.anchoredState = {
950
+ currentTime: Number(anchored['currentTime'] ?? 0),
951
+ shotId: (anchored['shotId'] as string | null | undefined) ?? null,
952
+ paused: Boolean(anchored['paused']),
953
+ experienceSource:
954
+ (anchored['experienceSource'] as string | null | undefined) ?? null,
955
+ updatedAt: anchored['updatedAt'] as number | undefined,
956
+ };
957
+ }
958
+ this._fireTyped('session_attached', payload);
959
+ return;
960
+ }
961
+ if (t === 'presence') {
962
+ this._fireTyped('presence', {
963
+ type: 'presence',
964
+ event: raw['event'] === 'detached' ? 'detached' : 'attached',
965
+ connectionId: String(raw['connectionId'] ?? ''),
966
+ ...(raw['videoId'] !== undefined
967
+ ? { videoId: String(raw['videoId']) }
968
+ : {}),
969
+ });
970
+ return;
971
+ }
788
972
  if (t === 'vision_answer') {
789
973
  this._fireTyped('vision_answer', {
790
974
  type: 'vision_answer',