@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,314 @@
1
+ /**
2
+ * §Q RUNTIME.3 — the scene bridge + the external-runtime submit methods.
3
+ *
4
+ * Pins the neutral outbound vocabulary the bridge projects from the chat
5
+ * stream (speaker, mouth per speaker, emotion/cue/trigger, interaction end,
6
+ * quest state, DM directive, event result), that a tag split across two
7
+ * streamed tokens is read ONCE, that inbound scene events are submitted
8
+ * through the host's submitter (and malformed ones never are), and the wire
9
+ * shapes of `ApiClient.submitRuntimeEvents` / `ChatWebSocket.sendRuntimeEvent`.
10
+ */
11
+
12
+ import { ApiClient } from '../api';
13
+ import { PresenceKind } from '../conversation/participant';
14
+ import type { RosterParticipant } from '../conversation/types';
15
+ import {
16
+ SceneBridge,
17
+ SeerTagStream,
18
+ chatSocketRuntimeEventSubmitter,
19
+ restRuntimeEventSubmitter,
20
+ type SceneOutboundMessage,
21
+ type SceneRuntimeEventMessage,
22
+ } from '../sceneBridge';
23
+ import { isRuntimeEventAck, type RuntimeEventResult } from '../runtimeEvents';
24
+ import { ChatWebSocket } from '../websocket';
25
+ import type { ChatWsEvent } from '../websocket';
26
+
27
+ const SESSION = 'sess-1';
28
+ const participant = (personaId: string, isDm = false): RosterParticipant => ({
29
+ personaId,
30
+ isDm,
31
+ displayName: personaId,
32
+ presence: PresenceKind.PRESENCE_AVATAR_3D,
33
+ });
34
+
35
+ const result = (clientToken: string, accepted = true): RuntimeEventResult => ({
36
+ clientToken,
37
+ eventType: 'FOUND_OBJECT',
38
+ accepted,
39
+ duplicate: false,
40
+ rejectedReason: accepted ? null : 'nope',
41
+ transitions: [],
42
+ });
43
+
44
+ function makeBridge(submit: (m: SceneRuntimeEventMessage) => unknown = () => undefined) {
45
+ const posted: SceneOutboundMessage[] = [];
46
+ const bridge = new SceneBridge({
47
+ adventureSessionId: SESSION,
48
+ participants: [participant('dm', true), participant('mara')],
49
+ post: (m) => posted.push(m),
50
+ submit: submit as never,
51
+ });
52
+ return { bridge, posted, of: (type: SceneOutboundMessage['type']) => posted.filter((m) => m.type === type) };
53
+ }
54
+
55
+ const feed = (bridge: SceneBridge, ...frames: ChatWsEvent[]) => frames.forEach((f) => bridge.applyFrame(f));
56
+
57
+ describe('SeerTagStream', () => {
58
+ it('reads a tag split across two tokens exactly once', () => {
59
+ const stream = new SeerTagStream();
60
+ const first = stream.push('Well [hap');
61
+ expect(first?.emotions ?? []).toEqual([]);
62
+ const second = stream.push('py] then');
63
+ expect(second?.emotions).toEqual(['happy']);
64
+ expect(stream.flush()).toBeNull();
65
+ });
66
+
67
+ it('releases an unclosed bracket that is too long to be a tag', () => {
68
+ const stream = new SeerTagStream();
69
+ const parsed = stream.push(`[${'x'.repeat(80)}`);
70
+ expect(parsed).not.toBeNull();
71
+ });
72
+ });
73
+
74
+ describe('SceneBridge — outbound', () => {
75
+ it('stages the speaker from turn_changed and attributes mouths to them', () => {
76
+ const { bridge, posted, of } = makeBridge();
77
+ feed(bridge, { type: 'turn_changed', personaId: 'mara' });
78
+ expect(of('speaker')).toEqual([{ type: 'speaker', personaId: 'mara' }]);
79
+ bridge.handleViseme('aei');
80
+ bridge.handleViseme('aei');
81
+ bridge.handleViseme('chjsh');
82
+ expect(of('mouth')).toEqual([
83
+ { type: 'mouth', personaId: 'mara', viseme: 'aei' },
84
+ { type: 'mouth', personaId: 'mara', viseme: 'cdgknstxyz' },
85
+ ]);
86
+ feed(bridge, { type: 'turn_changed', personaId: 'dm', previousPersonaId: 'mara' });
87
+ expect(posted.slice(-2)).toEqual([
88
+ { type: 'speaker', personaId: 'dm' },
89
+ { type: 'mouth', personaId: 'mara', viseme: 'rest' },
90
+ ]);
91
+ });
92
+
93
+ it('emits split tags once, per speaker, and one interaction end', () => {
94
+ const { bridge, of } = makeBridge();
95
+ feed(
96
+ bridge,
97
+ { type: 'turn_changed', personaId: 'mara' },
98
+ { type: 'token', personaId: 'mara', content: 'Hello [exci' },
99
+ { type: 'token', personaId: 'mara', content: 'ted] [laugh] [TRIGGER:door' },
100
+ { type: 'token', personaId: 'mara', content: '_open] bye [INTERACTION_' },
101
+ { type: 'token', personaId: 'mara', content: 'END]' },
102
+ { type: 'done', personaId: 'mara' },
103
+ );
104
+ expect(of('emotion')).toEqual([{ type: 'emotion', personaId: 'mara', emotion: 'excited' }]);
105
+ expect(of('cue')).toEqual([{ type: 'cue', personaId: 'mara', cue: 'laugh' }]);
106
+ expect(of('trigger')).toEqual([{ type: 'trigger', personaId: 'mara', name: 'door_open' }]);
107
+ expect(of('interaction_end')).toEqual([{ type: 'interaction_end', personaId: 'mara', reason: 'tag' }]);
108
+ });
109
+
110
+ it('ends the interaction on done when no tag did', () => {
111
+ const { bridge, of } = makeBridge();
112
+ feed(
113
+ bridge,
114
+ { type: 'turn_changed', personaId: 'dm' },
115
+ { type: 'token', content: 'The door creaks.' },
116
+ { type: 'done' },
117
+ );
118
+ expect(of('interaction_end')).toEqual([{ type: 'interaction_end', personaId: 'dm', reason: 'turn_done' }]);
119
+ });
120
+
121
+ it('forwards quest changes for this session only, and DM directives', () => {
122
+ const { bridge, of } = makeBridge();
123
+ const change = {
124
+ type: 'quest_state_changed' as const,
125
+ sessionId: SESSION,
126
+ lastSeq: 7,
127
+ changes: [{ questId: 'q1', status: 'SUCCEEDED' }],
128
+ mapUnlocks: ['cellar'],
129
+ newlyAvailable: { quests: ['q2'], cutscenes: [] },
130
+ };
131
+ feed(bridge, { ...change, sessionId: 'someone-else', lastSeq: 9 } as ChatWsEvent, change as ChatWsEvent);
132
+ expect(of('quest_state')).toEqual([
133
+ {
134
+ type: 'quest_state',
135
+ sessionId: SESSION,
136
+ lastSeq: 7,
137
+ changes: change.changes,
138
+ mapUnlocks: ['cellar'],
139
+ newlyAvailable: change.newlyAvailable,
140
+ },
141
+ ]);
142
+ feed(bridge, { type: 'dm_directive', directive: 'edit_scene', params: { mood: 'ominous' } });
143
+ expect(of('dm_directive')).toEqual([{ type: 'dm_directive', directive: 'edit_scene', params: { mood: 'ominous' } }]);
144
+ });
145
+
146
+ it('reports the ack and the refusal of a scene event', () => {
147
+ const { bridge, of } = makeBridge();
148
+ const ack = { type: 'runtime_event_ack', traceId: 't', sessionId: SESSION, result: result('k:1'), lastSeq: 3 };
149
+ expect(isRuntimeEventAck(ack)).toBe(true);
150
+ feed(
151
+ bridge,
152
+ ack as ChatWsEvent,
153
+ { type: 'error', action: 'runtime_event', message: 'not yours', clientToken: 'k:2', status: 404 },
154
+ { type: 'error', message: 'unrelated chat error' },
155
+ );
156
+ expect(of('runtime_event_result').map((m) => (m as { result: RuntimeEventResult }).result)).toEqual([
157
+ result('k:1'),
158
+ { ...result('k:2', false), eventType: null, rejectedReason: 'not yours' },
159
+ ]);
160
+ });
161
+
162
+ it('posts nothing after dispose', () => {
163
+ const { bridge, posted } = makeBridge();
164
+ const before = posted.length;
165
+ bridge.dispose();
166
+ feed(bridge, { type: 'turn_changed', personaId: 'mara' }, { type: 'token', content: '[happy]' });
167
+ bridge.handleViseme('o');
168
+ expect(posted.length).toBe(before);
169
+ });
170
+ });
171
+
172
+ describe('SceneBridge — inbound', () => {
173
+ it('submits a scene runtime event and reports the returned result', async () => {
174
+ const submitted: SceneRuntimeEventMessage[] = [];
175
+ const { bridge, of } = makeBridge(async (m) => {
176
+ submitted.push(m);
177
+ return result(m.clientToken);
178
+ });
179
+ const message = {
180
+ type: 'runtime_event',
181
+ clientToken: '9142:0',
182
+ event: { type: 'FOUND_OBJECT', entityId: 'e-key' },
183
+ presentEntityIds: ['e-key'],
184
+ };
185
+ expect(bridge.receive(message)).toBe(true);
186
+ await Promise.resolve();
187
+ await Promise.resolve();
188
+ expect(submitted).toEqual([message]);
189
+ expect(of('runtime_event_result')).toEqual([{ type: 'runtime_event_result', result: result('9142:0') }]);
190
+ });
191
+
192
+ it('refuses a malformed event without submitting, and ignores unknown messages', () => {
193
+ const submit = jest.fn();
194
+ const { bridge, of } = makeBridge(submit);
195
+ expect(bridge.receive({ type: 'runtime_event', clientToken: 'has space', event: { type: 'X' } })).toBe(true);
196
+ expect(bridge.receive({ type: 'runtime_event', clientToken: 'ok', event: {} })).toBe(true);
197
+ expect(bridge.receive({ type: 'runtime_event', clientToken: 'ok2', event: { type: 'X' }, presentEntityIds: [1] })).toBe(
198
+ true,
199
+ );
200
+ expect(bridge.receive({ type: 'scene_loaded' })).toBe(false);
201
+ expect(bridge.receive('runtime_event')).toBe(false);
202
+ expect(submit).not.toHaveBeenCalled();
203
+ expect(of('runtime_event_result')).toHaveLength(3);
204
+ });
205
+
206
+ it('reports a submitter failure as a refused result', async () => {
207
+ const { bridge, of } = makeBridge(async () => {
208
+ throw new Error('socket closed');
209
+ });
210
+ bridge.receive({ type: 'runtime_event', clientToken: 'k', event: { type: 'GAMESTATE_SET', key: 'a', value: 'b' } });
211
+ await new Promise((resolve) => setTimeout(resolve, 0));
212
+ const [message] = of('runtime_event_result') as Array<{ result: RuntimeEventResult }>;
213
+ expect(message.result.accepted).toBe(false);
214
+ expect(message.result.rejectedReason).toContain('socket closed');
215
+ });
216
+ });
217
+
218
+ describe('runtime event submitters', () => {
219
+ it('the chat-socket submitter sends the runtime_event action payload', () => {
220
+ const sent: unknown[] = [];
221
+ const submit = chatSocketRuntimeEventSubmitter({ sendRuntimeEvent: (p) => sent.push(p) }, SESSION);
222
+ submit({ type: 'runtime_event', clientToken: 'a:1', event: { type: 'REACHED_SCENE', sceneId: 's1' } });
223
+ expect(sent).toEqual([{ adventureSessionId: SESSION, clientToken: 'a:1', event: { type: 'REACHED_SCENE', sceneId: 's1' } }]);
224
+ });
225
+
226
+ it('the REST submitter posts one event with its presence and returns its result', async () => {
227
+ const calls: unknown[] = [];
228
+ const submit = restRuntimeEventSubmitter(
229
+ {
230
+ submitRuntimeEvents: async (sessionId, request) => {
231
+ calls.push([sessionId, request]);
232
+ return { traceId: 't', sessionId, results: [result('a:2')], lastSeq: 1 };
233
+ },
234
+ },
235
+ SESSION,
236
+ );
237
+ const out = await submit({
238
+ type: 'runtime_event',
239
+ clientToken: 'a:2',
240
+ event: { type: 'FOUND_OBJECT', entityId: 'e' },
241
+ presentEntityIds: [],
242
+ });
243
+ expect(out).toEqual(result('a:2'));
244
+ expect(calls).toEqual([
245
+ [
246
+ SESSION,
247
+ {
248
+ events: [{ clientToken: 'a:2', event: { type: 'FOUND_OBJECT', entityId: 'e' } }],
249
+ presence: { presentEntityIds: [] },
250
+ },
251
+ ],
252
+ ]);
253
+ });
254
+ });
255
+
256
+ describe('ApiClient.submitRuntimeEvents', () => {
257
+ const originalFetch = (globalThis as { fetch?: typeof fetch }).fetch;
258
+ afterEach(() => {
259
+ (globalThis as { fetch?: typeof fetch }).fetch = originalFetch;
260
+ });
261
+
262
+ it('POSTs the batch to the runtime events route', async () => {
263
+ const body = { traceId: 't', sessionId: 's/1', results: [], lastSeq: 0 };
264
+ const fetchMock = jest.fn().mockResolvedValue({ ok: true, status: 200, json: async () => body });
265
+ (globalThis as { fetch?: typeof fetch }).fetch = fetchMock as unknown as typeof fetch;
266
+ const api = new ApiClient('http://test.local', 'tok', 'http://test.local/chat');
267
+ const request = { events: [{ clientToken: 'x', event: { type: 'GAMESTATE_SET' as const, key: 'k', value: 'v' } }] };
268
+ await expect(api.submitRuntimeEvents('s/1', request)).resolves.toEqual(body);
269
+ const [url, init] = fetchMock.mock.calls[0];
270
+ expect(String(url).endsWith('/api/v1/runtime/sessions/s%2F1/events')).toBe(true);
271
+ expect(init.method).toBe('POST');
272
+ expect(JSON.parse(init.body)).toEqual(request);
273
+ });
274
+ });
275
+
276
+ describe('ChatWebSocket.sendRuntimeEvent', () => {
277
+ const original = globalThis.WebSocket;
278
+ afterEach(() => {
279
+ (globalThis as { WebSocket?: typeof WebSocket }).WebSocket = original;
280
+ });
281
+
282
+ it('serializes the runtime_event action, and throws when not connected', async () => {
283
+ const sent: string[] = [];
284
+ class Stub {
285
+ static OPEN = 1;
286
+ readyState = 0;
287
+ binaryType = 'blob';
288
+ onopen?: () => void;
289
+ constructor() {
290
+ setTimeout(() => {
291
+ this.readyState = 1;
292
+ this.onopen?.();
293
+ }, 0);
294
+ }
295
+ send(data: string) {
296
+ sent.push(data);
297
+ }
298
+ close() {
299
+ this.readyState = 3;
300
+ }
301
+ }
302
+ (globalThis as unknown as { WebSocket: unknown }).WebSocket = Stub;
303
+ const ws = new ChatWebSocket({ url: 'ws://test/chat', authToken: 'tok' });
304
+ const payload = {
305
+ adventureSessionId: SESSION,
306
+ clientToken: 'z:1',
307
+ event: { type: 'MAP_AREA_UNLOCKED' as const, locationId: 'cellar' },
308
+ };
309
+ expect(() => ws.sendRuntimeEvent(payload)).toThrow('WebSocket not connected');
310
+ await ws.connect();
311
+ ws.sendRuntimeEvent(payload);
312
+ expect(JSON.parse(sent[sent.length - 1])).toEqual({ action: 'runtime_event', ...payload });
313
+ });
314
+ });
package/src/api.ts CHANGED
@@ -75,6 +75,8 @@ import { DecisionsApi } from './domains/decisions';
75
75
  import { ProjectsApi } from './domains/projects';
76
76
  import { ReactorApi } from './domains/reactor';
77
77
  import { ShowcaseApi } from './domains/showcase';
78
+ import { RuntimeApi } from './domains/runtime';
79
+ import type { RuntimeEventBatchRequest, RuntimeEventBatchResponse } from './runtimeEvents';
78
80
  import { AdventureDefinitionsApi } from './domains/adventureDefinitions';
79
81
  import { StudioSettingsApi } from './domains/studioSettings';
80
82
  import { UniversesApi } from './domains/universes';
@@ -8354,6 +8356,7 @@ export class ApiClient {
8354
8356
  private readonly chat: ChatApi;
8355
8357
  private readonly graph: GraphApi;
8356
8358
  private readonly showcase: ShowcaseApi;
8359
+ private readonly runtime: RuntimeApi;
8357
8360
  private readonly universes: UniversesApi;
8358
8361
  private readonly adventureDefinitions: AdventureDefinitionsApi;
8359
8362
  private readonly studioSettings: StudioSettingsApi;
@@ -8395,6 +8398,7 @@ export class ApiClient {
8395
8398
  this.chat = new ChatApi(this.transport);
8396
8399
  this.graph = new GraphApi(this.transport);
8397
8400
  this.showcase = new ShowcaseApi(this.transport);
8401
+ this.runtime = new RuntimeApi(this.transport);
8398
8402
  this.universes = new UniversesApi(this.transport);
8399
8403
  this.adventureDefinitions = new AdventureDefinitionsApi(this.transport);
8400
8404
  this.studioSettings = new StudioSettingsApi(this.transport);
@@ -10006,6 +10010,7 @@ export class ApiClient {
10006
10010
  status?: 'pending' | 'approved';
10007
10011
  sourceVideoId?: string;
10008
10012
  includeBlessed?: boolean;
10013
+ general?: boolean;
10009
10014
  }): Promise<PersonaListResponse> {
10010
10015
  return this.personas.listPersonas(params);
10011
10016
  }
@@ -10024,6 +10029,19 @@ export class ApiClient {
10024
10029
  return this.personas.listViewerPersonasByVideo(sourceVideoId);
10025
10030
  }
10026
10031
 
10032
+ /**
10033
+ * §Q SHOW.9: the VIEWER roster of GENERAL personas — the ones that name no
10034
+ * video (a site guide an admin made). The caller's own general personas,
10035
+ * plus other owners' general personas this caller may read (blessed and
10036
+ * approved), each shaped exactly like {@link getPersona}'s viewer copy (no
10037
+ * authored prompt). Sends `?general=true&includeBlessed=true`; not paginated
10038
+ * (`next_token` is always null). An older backend answers 400 (unknown
10039
+ * parameter).
10040
+ */
10041
+ async listViewerGeneralPersonas(): Promise<PersonaListResponse> {
10042
+ return this.personas.listViewerGeneralPersonas();
10043
+ }
10044
+
10027
10045
  /**
10028
10046
  * C3a: list the personas auto-generated from a given source video. Thin
10029
10047
  * wrapper over {@link listPersonas} with ``sourceVideoId`` — backs the review
@@ -13290,6 +13308,21 @@ export class ApiClient {
13290
13308
  return this.showcase.listShowcaseExperiences(options);
13291
13309
  }
13292
13310
 
13311
+ /**
13312
+ * §Q RUNTIME.3 — report a batch of external-runtime facts (zone reached,
13313
+ * object found, world predicate set, map area unlocked) into a running
13314
+ * adventure session the caller owns. `POST /api/v1/runtime/sessions/{id}/events`;
13315
+ * see {@link RuntimeApi.submitRuntimeEvents} for the status contract. The
13316
+ * WebSocket twin is {@link ChatWebSocket.sendRuntimeEvent}. Additive.
13317
+ */
13318
+ async submitRuntimeEvents(
13319
+ sessionId: string,
13320
+ request: RuntimeEventBatchRequest,
13321
+ options: { signal?: AbortSignal } = {},
13322
+ ): Promise<RuntimeEventBatchResponse> {
13323
+ return this.runtime.submitRuntimeEvents(sessionId, request, options);
13324
+ }
13325
+
13293
13326
  // AdventureDefinition control plane (§Q ADV.2/ADV.3/ADV.6 — spec
13294
13327
  // `specs/2026-07-12-client-core-adventure-surface.md` D1/D2). Facade
13295
13328
  // delegations to `./domains/adventureDefinitions.ts` (same additive facade
@@ -213,6 +213,7 @@ export class PersonasApi {
213
213
  status?: 'pending' | 'approved';
214
214
  sourceVideoId?: string;
215
215
  includeBlessed?: boolean;
216
+ general?: boolean;
216
217
  }): Promise<PersonaListResponse> {
217
218
  const searchParams = new URLSearchParams();
218
219
  if (params?.limit) searchParams.append('limit', params.limit.toString());
@@ -221,6 +222,7 @@ export class PersonasApi {
221
222
  // Wire param is snake_case (matches the backend Query alias).
222
223
  if (params?.sourceVideoId) searchParams.append('source_video_id', params.sourceVideoId);
223
224
  if (params?.includeBlessed) searchParams.append('includeBlessed', 'true');
225
+ if (params?.general) searchParams.append('general', 'true');
224
226
 
225
227
  const query = searchParams.toString();
226
228
  const endpoint = `/api/v1/personas${query ? `?${query}` : ''}`;
@@ -238,6 +240,11 @@ export class PersonasApi {
238
240
  return this.listPersonas({ sourceVideoId, includeBlessed: true });
239
241
  }
240
242
 
243
+ /** See {@link ApiClient.listViewerGeneralPersonas}. */
244
+ async listViewerGeneralPersonas(): Promise<PersonaListResponse> {
245
+ return this.listPersonas({ general: true, includeBlessed: true });
246
+ }
247
+
241
248
  /** See {@link ApiClient.getDefaultPersona}. */
242
249
  async getDefaultPersona(): Promise<PersonaConfig | null> {
243
250
  return this.transport.requestJson<PersonaConfig | null>(
@@ -0,0 +1,38 @@
1
+ /**
2
+ * External-runtime event intake domain module (§Q RUNTIME.3).
3
+ *
4
+ * `POST /api/v1/runtime/sessions/{sessionId}/events` — the REST door of the
5
+ * intake. Wire types live in `../runtimeEvents` (re-exported from `index.ts`).
6
+ */
7
+
8
+ import type { Transport } from '../transport';
9
+ import type { RuntimeEventBatchRequest, RuntimeEventBatchResponse } from '../runtimeEvents';
10
+
11
+ /** The external-runtime intake's REST door. */
12
+ export class RuntimeApi {
13
+ constructor(private readonly transport: Transport) {}
14
+
15
+ /**
16
+ * Report a batch of external-runtime facts into a running adventure session
17
+ * the caller owns, applied in order. Answers 200 with one result per event
18
+ * even when an event is refused (`accepted: false` + `rejectedReason`); a
19
+ * thrown `Error` means the batch itself was refused: 404 (intake off, or not
20
+ * the caller's session), 409 (the session was not started from an adventure
21
+ * definition), 422 (malformed, including a `clientToken` named twice).
22
+ */
23
+ async submitRuntimeEvents(
24
+ sessionId: string,
25
+ request: RuntimeEventBatchRequest,
26
+ options: { signal?: AbortSignal } = {},
27
+ ): Promise<RuntimeEventBatchResponse> {
28
+ return this.transport.requestJson<RuntimeEventBatchResponse>(
29
+ this.transport.baseUrl,
30
+ `/api/v1/runtime/sessions/${encodeURIComponent(sessionId)}/events`,
31
+ {
32
+ method: 'POST',
33
+ body: JSON.stringify(request),
34
+ signal: options.signal,
35
+ },
36
+ );
37
+ }
38
+ }
package/src/index.ts CHANGED
@@ -26,6 +26,9 @@ export * from './opusTransport';
26
26
  export * from './visemeScheduler';
27
27
  export * from './visemeGeometry';
28
28
  export * from './websocket';
29
+ // §Q RUNTIME.3 — external-runtime event intake types + the scene bridge.
30
+ export * from './runtimeEvents';
31
+ export * from './sceneBridge';
29
32
  export * from './api';
30
33
  // §Q PERS.3 — the face-fallback reason vocabulary + its labels, so a renderer
31
34
  // can say WHY it is painting the generic face instead of degrading silently.
@@ -0,0 +1,127 @@
1
+ /**
2
+ * External-runtime event intake — the client half (§Q RUNTIME.3).
3
+ *
4
+ * An external runtime (whatever renders or simulates a scene outside Seer — a
5
+ * game, an XR app, an installation, a simulator) reports physical/gameplay
6
+ * FACTS into a running adventure session's quest ledger; Seer derives the
7
+ * narrative consequences. Two doors, one server ingress:
8
+ *
9
+ * - REST: `POST /api/v1/runtime/sessions/{sessionId}/events` (batched) —
10
+ * {@link RuntimeEventBatchRequest} → {@link RuntimeEventBatchResponse};
11
+ * - WebSocket: the chat socket's `runtime_event` action (one event per frame) —
12
+ * {@link RuntimeEventActionPayload} → a `runtime_event_ack` frame
13
+ * ({@link RuntimeEventAckFrame}).
14
+ *
15
+ * Mirrors `shared/runtime_events.py`. Seer-native, platform-neutral names; no
16
+ * engine or cross-platform-protocol import, by rule.
17
+ *
18
+ * **The clientToken contract.** Unique per genuine event across the session,
19
+ * stable across retries of that event (e.g. `${runtimeTick}:${ordinal}`). A
20
+ * retry with the same token answers `duplicate: true` and changes nothing; a
21
+ * batch naming one token twice is refused whole (HTTP 422).
22
+ */
23
+
24
+ /** The WebSocket action name. */
25
+ export const RUNTIME_EVENT_ACTION = 'runtime_event' as const;
26
+ /** The WebSocket acknowledgement frame type. */
27
+ export const RUNTIME_EVENT_ACK_FRAME = 'runtime_event_ack' as const;
28
+ /** Most events one REST batch may carry (`RUNTIME_EVENT_BATCH_MAX`). */
29
+ export const RUNTIME_EVENT_BATCH_MAX = 50;
30
+ /** The charset and bound a `clientToken` must satisfy. */
31
+ export const RUNTIME_CLIENT_TOKEN_PATTERN = /^[A-Za-z0-9_.:#-]{1,128}$/;
32
+
33
+ /**
34
+ * The event types the server accepts from an external runtime
35
+ * (`EXTERNAL_RUNTIME_COMMANDABLE_EVENT_TYPES`): facts, never outcomes. Any
36
+ * other type is answered `accepted: false` with a reason.
37
+ */
38
+ export const RUNTIME_COMMANDABLE_EVENT_TYPES = [
39
+ 'REACHED_SCENE',
40
+ 'FOUND_OBJECT',
41
+ 'GAMESTATE_SET',
42
+ 'MAP_AREA_UNLOCKED',
43
+ ] as const;
44
+
45
+ export type RuntimeCommandableEventType = (typeof RUNTIME_COMMANDABLE_EVENT_TYPES)[number];
46
+
47
+ /** One fact the external runtime reports (the quest event vocabulary's camelCase wire). */
48
+ export type RuntimeQuestEvent =
49
+ | { type: 'REACHED_SCENE'; sceneId: string; beatId?: string }
50
+ | { type: 'FOUND_OBJECT'; entityId: string; sceneId?: string }
51
+ | { type: 'GAMESTATE_SET'; key: string; value: string }
52
+ | { type: 'MAP_AREA_UNLOCKED'; locationId: string };
53
+
54
+ /** One event of a submission: its token and its fact. */
55
+ export interface RuntimeEventInput {
56
+ clientToken: string;
57
+ event: RuntimeQuestEvent;
58
+ }
59
+
60
+ /**
61
+ * What the runtime says is physically present in its scene. Authoritative for
62
+ * `FOUND_OBJECT`: a found object must be listed (an empty list means nothing
63
+ * is present). Omit it and the runtime's own report of the pickup stands.
64
+ */
65
+ export interface RuntimePresence {
66
+ presentEntityIds: string[];
67
+ }
68
+
69
+ /** `POST /api/v1/runtime/sessions/{sessionId}/events` body. */
70
+ export interface RuntimeEventBatchRequest {
71
+ events: RuntimeEventInput[];
72
+ presence?: RuntimePresence;
73
+ }
74
+
75
+ /** What the server did with one event. */
76
+ export interface RuntimeEventResult {
77
+ clientToken: string;
78
+ eventType: string | null;
79
+ accepted: boolean;
80
+ /** The event replayed an already-recorded one (same token): nothing changed. */
81
+ duplicate: boolean;
82
+ rejectedReason: string | null;
83
+ transitions: Array<Record<string, unknown>>;
84
+ }
85
+
86
+ /** The REST door's answer: one result per event, in request order. */
87
+ export interface RuntimeEventBatchResponse {
88
+ traceId: string;
89
+ sessionId: string;
90
+ results: RuntimeEventResult[];
91
+ /** The quest ledger's last seq after the batch. */
92
+ lastSeq: number;
93
+ }
94
+
95
+ /** The WebSocket `runtime_event` action (one event per frame). */
96
+ export interface RuntimeEventActionPayload {
97
+ adventureSessionId: string;
98
+ clientToken: string;
99
+ event: RuntimeQuestEvent;
100
+ /** Optional {@link RuntimePresence} for this event. */
101
+ presentEntityIds?: string[];
102
+ }
103
+
104
+ /** The WebSocket door's answer to one `runtime_event` action. */
105
+ export interface RuntimeEventAckFrame {
106
+ type: typeof RUNTIME_EVENT_ACK_FRAME;
107
+ traceId: string;
108
+ sessionId: string;
109
+ result: RuntimeEventResult;
110
+ lastSeq: number;
111
+ }
112
+
113
+ /** Narrow a parsed chat frame to a {@link RuntimeEventAckFrame}. */
114
+ export function isRuntimeEventAck(frame: unknown): frame is RuntimeEventAckFrame {
115
+ if (typeof frame !== 'object' || frame === null) return false;
116
+ const candidate = frame as { type?: unknown; result?: unknown };
117
+ return (
118
+ candidate.type === RUNTIME_EVENT_ACK_FRAME &&
119
+ typeof candidate.result === 'object' &&
120
+ candidate.result !== null
121
+ );
122
+ }
123
+
124
+ /** Whether `token` satisfies the server's `clientToken` charset and bound. */
125
+ export function isValidRuntimeClientToken(token: unknown): token is string {
126
+ return typeof token === 'string' && RUNTIME_CLIENT_TOKEN_PATTERN.test(token);
127
+ }