@escapeaihq/client-core 0.139.0 → 0.140.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.
@@ -0,0 +1,433 @@
1
+ /**
2
+ * Scene bridge — connect an embedded scene to a running adventure session
3
+ * (§Q RUNTIME.3, owner ruling R-D16).
4
+ *
5
+ * A transport-agnostic, DOM-free adapter between Seer's chat event stream and a
6
+ * scene (a rendered 3D world, an XR app, an installation — whatever the
7
+ * embedding host shows). The host owns the wire on both sides:
8
+ *
9
+ * - **Outbound** — the host feeds every chat frame to {@link SceneBridge.applyFrame}
10
+ * (and wires {@link SceneBridge.handleViseme} / {@link SceneBridge.createVisemeScheduler}
11
+ * into its audio playback); the bridge projects them into a small neutral
12
+ * vocabulary ({@link SceneOutboundMessage}) and hands each one to the host's
13
+ * `post(message)`: who is speaking, the mouth shape per speaker,
14
+ * emotion / cue / trigger tags, interaction end, quest state change, DM
15
+ * directive, and the result of each event the scene reported.
16
+ * - **Inbound** — the host passes each message the scene sends to
17
+ * {@link SceneBridge.receive}; a `runtime_event` message is submitted to Seer
18
+ * through the host's {@link SceneEventSubmitter} (the chat socket's
19
+ * `runtime_event` action or the REST door — see
20
+ * {@link chatSocketRuntimeEventSubmitter} / {@link restRuntimeEventSubmitter}).
21
+ *
22
+ * It re-derives nothing: speaker state and quest pushes come from
23
+ * {@link ConversationRuntime}; speaker staging and per-persona mouth delivery go
24
+ * through {@link bindPresence} onto a {@link PresenceAdapter} the bridge
25
+ * implements; mouth shapes come from {@link VisemeScheduler}; tags are parsed by
26
+ * {@link parseSeerMessage}, with a hold-back so a tag split across two streamed
27
+ * tokens (`[hap` + `py]`) is still read once ({@link SeerTagStream}).
28
+ *
29
+ * Platform-neutral by rule: no engine, device or cross-platform-protocol
30
+ * import, and no host's legacy message names — a host maps this vocabulary onto
31
+ * its own wire in a thin adapter.
32
+ */
33
+
34
+ import { bindPresence, type PresenceBinding } from './conversation/presenceBus';
35
+ import type { PresenceAdapter } from './conversation/presence';
36
+ import { ConversationRuntime } from './conversation/runtime';
37
+ import type { ConversationRuntimeState, RosterParticipant } from './conversation/types';
38
+ import {
39
+ parseSeerMessage,
40
+ type ParsedSeerMessage,
41
+ type SeerEmotion,
42
+ type SeerNonverbalCue,
43
+ } from './messageContent';
44
+ import {
45
+ isRuntimeEventAck,
46
+ isValidRuntimeClientToken,
47
+ RUNTIME_EVENT_ACTION,
48
+ type RuntimeEventActionPayload,
49
+ type RuntimeEventBatchRequest,
50
+ type RuntimeEventBatchResponse,
51
+ type RuntimeEventResult,
52
+ type RuntimeQuestEvent,
53
+ } from './runtimeEvents';
54
+ import { normalizeVisemeSymbol, VisemeScheduler, type VisemeSymbol } from './visemeScheduler';
55
+ import type { ChatWsEvent, QuestNewlyAvailable, QuestStateChange } from './websocket';
56
+
57
+ /** What the bridge posts to the scene. */
58
+ export type SceneOutboundMessage =
59
+ /** The persona now speaking (`null`: nobody holds the floor). */
60
+ | { type: 'speaker'; personaId: string | null }
61
+ /** One mouth shape for one speaker (`rest` when they stop). */
62
+ | { type: 'mouth'; personaId: string; viseme: VisemeSymbol }
63
+ | { type: 'emotion'; personaId: string | null; emotion: SeerEmotion }
64
+ | { type: 'cue'; personaId: string | null; cue: SeerNonverbalCue }
65
+ | { type: 'trigger'; personaId: string | null; name: string }
66
+ /** The speaker ended the interaction: an `[INTERACTION_END]` tag, or the turn finished without one. */
67
+ | { type: 'interaction_end'; personaId: string | null; reason: 'tag' | 'turn_done' }
68
+ /** The session's quest state moved (a `quest_state_changed` push for this session). */
69
+ | {
70
+ type: 'quest_state';
71
+ sessionId: string;
72
+ lastSeq: number;
73
+ changes: QuestStateChange[];
74
+ mapUnlocks: string[];
75
+ newlyAvailable: QuestNewlyAvailable;
76
+ }
77
+ /** A Dungeon-Master scene directive (`[SCENE:…]`, delivered server-side as `dm_directive`). */
78
+ | { type: 'dm_directive'; directive: string; params: Record<string, unknown> }
79
+ /** What Seer did with one event the scene reported. */
80
+ | { type: 'runtime_event_result'; result: RuntimeEventResult };
81
+
82
+ /** What a scene may send the bridge. */
83
+ export interface SceneRuntimeEventMessage {
84
+ type: typeof RUNTIME_EVENT_ACTION;
85
+ /** Unique per genuine event, stable across retries (the server's idempotency key). */
86
+ clientToken: string;
87
+ event: RuntimeQuestEvent;
88
+ /** What the scene says is physically present (authoritative for `FOUND_OBJECT`). */
89
+ presentEntityIds?: string[];
90
+ }
91
+
92
+ export type SceneInboundMessage = SceneRuntimeEventMessage;
93
+
94
+ /**
95
+ * Submit one scene event to Seer. Return the server's result (REST), or nothing
96
+ * when the result arrives later as a frame through {@link SceneBridge.applyFrame}
97
+ * (the chat socket's `runtime_event_ack`).
98
+ */
99
+ export type SceneEventSubmitter = (
100
+ message: SceneRuntimeEventMessage,
101
+ ) => Promise<RuntimeEventResult | void> | RuntimeEventResult | void;
102
+
103
+ export interface SceneBridgeOptions {
104
+ /** The adventure session the scene is connected to. */
105
+ adventureSessionId: string;
106
+ /** The host's sink for outbound messages (e.g. a `postMessage` wrapper). */
107
+ post: (message: SceneOutboundMessage) => void;
108
+ /** How inbound scene events reach Seer. */
109
+ submit: SceneEventSubmitter;
110
+ /**
111
+ * The roster to stage. A participant whose `presence` is `PRESENCE_NONE`
112
+ * gets no speaker/mouth messages (the {@link bindPresence} stage gate).
113
+ * Ignored when `runtime` is given (its roster is used).
114
+ */
115
+ participants?: readonly RosterParticipant[];
116
+ /**
117
+ * A runtime the host already drives. When given, the host keeps feeding it
118
+ * and {@link SceneBridge.applyFrame} does not forward frames to it; when
119
+ * omitted, the bridge owns a runtime and feeds it from `applyFrame`.
120
+ */
121
+ runtime?: ConversationRuntime;
122
+ }
123
+
124
+ /** Longest unclosed `[…` the tag stream holds back before releasing it as text. */
125
+ export const SCENE_TAG_HOLD_MAX = 64;
126
+
127
+ /**
128
+ * Incremental {@link parseSeerMessage} over streamed tokens. Text is released
129
+ * up to (not including) the last `[` that has no `]` after it, so a tag split
130
+ * across tokens is parsed once, whole. An unclosed `[` longer than
131
+ * {@link SCENE_TAG_HOLD_MAX} is released as text (it is not a tag).
132
+ */
133
+ export class SeerTagStream {
134
+ private pending = '';
135
+
136
+ /** Append streamed text; the parse of whatever is now safe to release (or `null`). */
137
+ push(text: string): ParsedSeerMessage | null {
138
+ this.pending += text;
139
+ const open = this.pending.lastIndexOf('[');
140
+ const held =
141
+ open !== -1 &&
142
+ this.pending.indexOf(']', open) === -1 &&
143
+ this.pending.length - open <= SCENE_TAG_HOLD_MAX;
144
+ const cut = held ? open : this.pending.length;
145
+ const ready = this.pending.slice(0, cut);
146
+ this.pending = this.pending.slice(cut);
147
+ return ready ? parseSeerMessage(ready) : null;
148
+ }
149
+
150
+ /** Release whatever is held (end of turn). */
151
+ flush(): ParsedSeerMessage | null {
152
+ const rest = this.pending;
153
+ this.pending = '';
154
+ return rest ? parseSeerMessage(rest) : null;
155
+ }
156
+ }
157
+
158
+ const NO_PERSONA = '\u0000';
159
+
160
+ /** Connects one scene to one adventure session. See the module docs. */
161
+ export class SceneBridge {
162
+ /** The conversation runtime the bridge reads speaker and quest state from. */
163
+ readonly runtime: ConversationRuntime;
164
+ private readonly ownsRuntime: boolean;
165
+ private readonly binding: PresenceBinding;
166
+ private readonly unsubscribe: () => void;
167
+ private readonly streams = new Map<string, SeerTagStream>();
168
+ private readonly endedByTag = new Set<string>();
169
+ private readonly lastMouth = new Map<string, VisemeSymbol>();
170
+ private lastQuest: ConversationRuntimeState['latestQuestChange'];
171
+ private disposed = false;
172
+
173
+ constructor(private readonly opts: SceneBridgeOptions) {
174
+ this.ownsRuntime = opts.runtime === undefined;
175
+ this.runtime =
176
+ opts.runtime ??
177
+ new ConversationRuntime({
178
+ adventureSessionId: opts.adventureSessionId,
179
+ participants: opts.participants ?? [],
180
+ });
181
+ this.lastQuest = this.runtime.getState().latestQuestChange;
182
+ this.binding = bindPresence(this.runtime, this.presenceAdapter());
183
+ this.unsubscribe = this.runtime.subscribe((state) => this.onRuntimeState(state));
184
+ }
185
+
186
+ /** Feed one chat frame (every frame the host's chat socket delivers). */
187
+ applyFrame(frame: ChatWsEvent): void {
188
+ if (this.disposed) return;
189
+ if (this.ownsRuntime) this.runtime.applyFrame(frame);
190
+ if (isRuntimeEventAck(frame)) {
191
+ if (frame.sessionId === this.opts.adventureSessionId) {
192
+ this.post({ type: 'runtime_event_result', result: frame.result });
193
+ }
194
+ return;
195
+ }
196
+ switch (frame.type) {
197
+ case 'token':
198
+ this.onText(frame.personaId ?? this.speakingPersonaId(), frame.content);
199
+ return;
200
+ case 'done':
201
+ this.endTurn(frame.personaId ?? null);
202
+ return;
203
+ case 'dm_directive':
204
+ this.post({ type: 'dm_directive', directive: frame.directive, params: frame.params });
205
+ return;
206
+ case 'error':
207
+ if (frame.action === RUNTIME_EVENT_ACTION && typeof frame.clientToken === 'string') {
208
+ this.post({
209
+ type: 'runtime_event_result',
210
+ result: refused(frame.clientToken, null, frame.message),
211
+ });
212
+ }
213
+ return;
214
+ default:
215
+ return;
216
+ }
217
+ }
218
+
219
+ /**
220
+ * One scheduled mouth shape for the CURRENT speaker — pass this as the
221
+ * `onVisemeChange` callback of the host's {@link VisemeScheduler} (or of an
222
+ * `AudioPipeline`, which wraps one). Attributed to the persona whose turn is
223
+ * in flight, falling back to the floor holder.
224
+ */
225
+ readonly handleViseme = (viseme: string): void => {
226
+ if (this.disposed) return;
227
+ const personaId = this.speakingPersonaId();
228
+ if (personaId === null) return;
229
+ this.binding.applyViseme(personaId, normalizeVisemeSymbol({ phoneSymbol: '', visemeSymbol: viseme }));
230
+ };
231
+
232
+ /** A {@link VisemeScheduler} on the host's audio clock that drives {@link handleViseme}. */
233
+ createVisemeScheduler(audioContext: AudioContext): VisemeScheduler {
234
+ return new VisemeScheduler(audioContext, this.handleViseme);
235
+ }
236
+
237
+ /**
238
+ * Accept one message from the scene. Returns `true` when it was a message
239
+ * the bridge understands (a `runtime_event`), `false` otherwise (ignored —
240
+ * a newer scene's message kind never throws). A malformed `runtime_event` is
241
+ * answered with a refused `runtime_event_result` and never submitted.
242
+ */
243
+ receive(message: unknown): boolean {
244
+ if (this.disposed || typeof message !== 'object' || message === null) return false;
245
+ const candidate = message as Partial<SceneRuntimeEventMessage>;
246
+ if (candidate.type !== RUNTIME_EVENT_ACTION) return false;
247
+ const token = candidate.clientToken;
248
+ const event = candidate.event as { type?: unknown } | undefined;
249
+ if (!isValidRuntimeClientToken(token)) {
250
+ this.post({
251
+ type: 'runtime_event_result',
252
+ result: refused(typeof token === 'string' ? token : '', null, 'clientToken is missing or malformed'),
253
+ });
254
+ return true;
255
+ }
256
+ if (typeof event !== 'object' || event === null || typeof event.type !== 'string') {
257
+ this.post({ type: 'runtime_event_result', result: refused(token, null, 'event.type is missing') });
258
+ return true;
259
+ }
260
+ const presence = candidate.presentEntityIds;
261
+ if (presence !== undefined && !(Array.isArray(presence) && presence.every((id) => typeof id === 'string'))) {
262
+ this.post({
263
+ type: 'runtime_event_result',
264
+ result: refused(token, event.type, 'presentEntityIds must be a list of strings'),
265
+ });
266
+ return true;
267
+ }
268
+ const submission: SceneRuntimeEventMessage = {
269
+ type: RUNTIME_EVENT_ACTION,
270
+ clientToken: token,
271
+ event: candidate.event as RuntimeQuestEvent,
272
+ ...(presence !== undefined ? { presentEntityIds: presence } : {}),
273
+ };
274
+ void this.submit(submission);
275
+ return true;
276
+ }
277
+
278
+ /** Stop posting and unstage every participant. Idempotent. */
279
+ dispose(): void {
280
+ if (this.disposed) return;
281
+ this.disposed = true;
282
+ this.unsubscribe();
283
+ this.binding.dispose();
284
+ }
285
+
286
+ private async submit(message: SceneRuntimeEventMessage): Promise<void> {
287
+ try {
288
+ const result = await this.opts.submit(message);
289
+ if (result) this.post({ type: 'runtime_event_result', result });
290
+ } catch (error) {
291
+ this.post({
292
+ type: 'runtime_event_result',
293
+ result: refused(
294
+ message.clientToken,
295
+ message.event.type,
296
+ `submit failed: ${error instanceof Error ? error.message : String(error)}`,
297
+ ),
298
+ });
299
+ }
300
+ }
301
+
302
+ private post(message: SceneOutboundMessage): void {
303
+ if (!this.disposed) this.opts.post(message);
304
+ }
305
+
306
+ private speakingPersonaId(): string | null {
307
+ const state = this.runtime.getState();
308
+ return state.inFlightPersonaId ?? state.activePersonaId;
309
+ }
310
+
311
+ private onRuntimeState(state: ConversationRuntimeState): void {
312
+ const change = state.latestQuestChange;
313
+ if (change !== null && change !== this.lastQuest) {
314
+ this.post({
315
+ type: 'quest_state',
316
+ sessionId: change.sessionId,
317
+ lastSeq: change.lastSeq,
318
+ changes: change.changes,
319
+ mapUnlocks: change.mapUnlocks,
320
+ newlyAvailable: change.newlyAvailable,
321
+ });
322
+ }
323
+ this.lastQuest = change;
324
+ }
325
+
326
+ private onText(personaId: string | null, text: string): void {
327
+ const key = personaId ?? NO_PERSONA;
328
+ let stream = this.streams.get(key);
329
+ if (!stream) {
330
+ stream = new SeerTagStream();
331
+ this.streams.set(key, stream);
332
+ }
333
+ this.emitTags(personaId, stream.push(text));
334
+ }
335
+
336
+ private endTurn(personaId: string | null): void {
337
+ const keys = personaId === null ? [...this.streams.keys()] : [personaId];
338
+ if (keys.length === 0) keys.push(this.speakingPersonaId() ?? NO_PERSONA);
339
+ for (const key of keys) {
340
+ const who = key === NO_PERSONA ? null : key;
341
+ const stream = this.streams.get(key);
342
+ if (stream) this.emitTags(who, stream.flush());
343
+ if (!this.endedByTag.has(key)) {
344
+ this.post({ type: 'interaction_end', personaId: who, reason: 'turn_done' });
345
+ }
346
+ this.streams.delete(key);
347
+ this.endedByTag.delete(key);
348
+ }
349
+ }
350
+
351
+ private emitTags(personaId: string | null, parsed: ParsedSeerMessage | null): void {
352
+ if (parsed === null) return;
353
+ for (const emotion of parsed.emotions) this.post({ type: 'emotion', personaId, emotion });
354
+ for (const token of parsed.tokens) {
355
+ if (token.kind === 'cue') this.post({ type: 'cue', personaId, cue: token.name });
356
+ }
357
+ for (const name of parsed.triggers) this.post({ type: 'trigger', personaId, name });
358
+ if (parsed.interactionEnded) {
359
+ const key = personaId ?? NO_PERSONA;
360
+ if (!this.endedByTag.has(key)) {
361
+ this.endedByTag.add(key);
362
+ this.post({ type: 'interaction_end', personaId, reason: 'tag' });
363
+ }
364
+ }
365
+ }
366
+
367
+ private presenceAdapter(): PresenceAdapter {
368
+ return {
369
+ mount: () => undefined,
370
+ unmount: (personaId) => {
371
+ this.lastMouth.delete(personaId);
372
+ },
373
+ setActiveParticipant: (personaId) => this.post({ type: 'speaker', personaId }),
374
+ setSpeaking: (personaId, speaking) => {
375
+ if (!speaking) this.postMouth(personaId, 'rest');
376
+ },
377
+ applyViseme: (personaId, viseme) => this.postMouth(personaId, viseme),
378
+ };
379
+ }
380
+
381
+ private postMouth(personaId: string, viseme: VisemeSymbol): void {
382
+ if (this.lastMouth.get(personaId) === viseme) return;
383
+ this.lastMouth.set(personaId, viseme);
384
+ this.post({ type: 'mouth', personaId, viseme });
385
+ }
386
+ }
387
+
388
+ function refused(clientToken: string, eventType: string | null, reason: string): RuntimeEventResult {
389
+ return {
390
+ clientToken,
391
+ eventType,
392
+ accepted: false,
393
+ duplicate: false,
394
+ rejectedReason: reason,
395
+ transitions: [],
396
+ };
397
+ }
398
+
399
+ /** Submit scene events over the chat socket's `runtime_event` action (results arrive as frames). */
400
+ export function chatSocketRuntimeEventSubmitter(
401
+ socket: { sendRuntimeEvent(payload: RuntimeEventActionPayload): void },
402
+ adventureSessionId: string,
403
+ ): SceneEventSubmitter {
404
+ return (message) => {
405
+ socket.sendRuntimeEvent({
406
+ adventureSessionId,
407
+ clientToken: message.clientToken,
408
+ event: message.event,
409
+ ...(message.presentEntityIds !== undefined ? { presentEntityIds: message.presentEntityIds } : {}),
410
+ });
411
+ };
412
+ }
413
+
414
+ /** Submit scene events over `POST /api/v1/runtime/sessions/{id}/events`, one per request. */
415
+ export function restRuntimeEventSubmitter(
416
+ api: {
417
+ submitRuntimeEvents(
418
+ sessionId: string,
419
+ request: RuntimeEventBatchRequest,
420
+ ): Promise<RuntimeEventBatchResponse>;
421
+ },
422
+ adventureSessionId: string,
423
+ ): SceneEventSubmitter {
424
+ return async (message) => {
425
+ const response = await api.submitRuntimeEvents(adventureSessionId, {
426
+ events: [{ clientToken: message.clientToken, event: message.event }],
427
+ ...(message.presentEntityIds !== undefined
428
+ ? { presence: { presentEntityIds: message.presentEntityIds } }
429
+ : {}),
430
+ });
431
+ return response.results[0];
432
+ };
433
+ }
package/src/websocket.ts CHANGED
@@ -16,6 +16,8 @@ import type {
16
16
  VoiceFallbackMessage,
17
17
  WordPhonemeInfo,
18
18
  } from './audioProtocol';
19
+ import type { RuntimeEventActionPayload, RuntimeEventAckFrame } from './runtimeEvents';
20
+ import { RUNTIME_EVENT_ACTION } from './runtimeEvents';
19
21
 
20
22
  export interface Citation {
21
23
  videoId: string;
@@ -177,6 +179,10 @@ export type ChatWsEvent =
177
179
  * dispatcher's own validation errors also end a turn and are unmarked.
178
180
  */
179
181
  turnEnded?: true;
182
+ /** §Q RUNTIME.3 — on an `action: 'runtime_event'` refusal: the HTTP-equivalent status. */
183
+ status?: number;
184
+ /** §Q RUNTIME.3 — on an `action: 'runtime_event'` refusal: the refused event's token. */
185
+ clientToken?: string | null;
180
186
  }
181
187
  | {
182
188
  type: 'image';
@@ -465,7 +471,9 @@ export type ChatWsEvent =
465
471
  content: string;
466
472
  /** See the `citation` case — orchestrator-stamped persona id (M10 9a). */
467
473
  personaId?: string;
468
- };
474
+ }
475
+ /** §Q RUNTIME.3 — the answer to one {@link ChatWebSocket.sendRuntimeEvent}. */
476
+ | RuntimeEventAckFrame;
469
477
 
470
478
  /**
471
479
  * @deprecated Prefer {@link ChatWsEvent} — the flat-shape interface
@@ -1068,6 +1076,22 @@ export class ChatWebSocket {
1068
1076
  );
1069
1077
  }
1070
1078
 
1079
+ /**
1080
+ * §Q RUNTIME.3 — report one external-runtime fact into the bound adventure
1081
+ * session's quest ledger (the `runtime_event` action). The server answers a
1082
+ * `runtime_event_ack` frame echoing `clientToken` (see
1083
+ * {@link isRuntimeEventAck}), or an `error` frame with
1084
+ * `action: 'runtime_event'`; quest changes it causes arrive as the usual
1085
+ * `quest_state_changed` frames. Throws when the socket is not open — an
1086
+ * event is never silently dropped. Additive.
1087
+ */
1088
+ sendRuntimeEvent(payload: RuntimeEventActionPayload): void {
1089
+ if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
1090
+ throw new Error('WebSocket not connected');
1091
+ }
1092
+ this.ws.send(JSON.stringify({ action: RUNTIME_EVENT_ACTION, ...payload }));
1093
+ }
1094
+
1071
1095
  /**
1072
1096
  * Send an audio hello handshake for hybrid audio/text sessions.
1073
1097
  * Serializes the payload as-is — all defaults are applied by buildHelloPayload().