@escapeaihq/client-core 0.12.0 → 0.49.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 (242) hide show
  1. package/README.md +32 -7
  2. package/dist/adapters/capabilities.d.ts +10 -0
  3. package/dist/adapters/capabilities.d.ts.map +1 -0
  4. package/dist/adapters/capabilities.js +2 -0
  5. package/dist/adapters/capabilities.js.map +1 -0
  6. package/dist/adapters/chatAdapter.d.ts +38 -0
  7. package/dist/adapters/chatAdapter.d.ts.map +1 -0
  8. package/dist/adapters/chatAdapter.js +88 -0
  9. package/dist/adapters/chatAdapter.js.map +1 -0
  10. package/dist/adapters/directorAdapter.d.ts +62 -0
  11. package/dist/adapters/directorAdapter.d.ts.map +1 -0
  12. package/dist/adapters/directorAdapter.js +71 -0
  13. package/dist/adapters/directorAdapter.js.map +1 -0
  14. package/dist/adapters/imageAdapter.d.ts +44 -0
  15. package/dist/adapters/imageAdapter.d.ts.map +1 -0
  16. package/dist/adapters/imageAdapter.js +73 -0
  17. package/dist/adapters/imageAdapter.js.map +1 -0
  18. package/dist/adapters/index.d.ts +47 -0
  19. package/dist/adapters/index.d.ts.map +1 -0
  20. package/dist/adapters/index.js +41 -0
  21. package/dist/adapters/index.js.map +1 -0
  22. package/dist/adapters/registry.d.ts +98 -0
  23. package/dist/adapters/registry.d.ts.map +1 -0
  24. package/dist/adapters/registry.js +106 -0
  25. package/dist/adapters/registry.js.map +1 -0
  26. package/dist/adapters/worldAdapter.d.ts +142 -0
  27. package/dist/adapters/worldAdapter.d.ts.map +1 -0
  28. package/dist/adapters/worldAdapter.js +164 -0
  29. package/dist/adapters/worldAdapter.js.map +1 -0
  30. package/dist/admin.d.ts +323 -0
  31. package/dist/admin.d.ts.map +1 -0
  32. package/dist/admin.js +198 -0
  33. package/dist/admin.js.map +1 -0
  34. package/dist/api.d.ts +1512 -4
  35. package/dist/api.d.ts.map +1 -1
  36. package/dist/api.js +820 -52
  37. package/dist/api.js.map +1 -1
  38. package/dist/audio.d.ts +33 -1
  39. package/dist/audio.d.ts.map +1 -1
  40. package/dist/audio.js +4 -1
  41. package/dist/audio.js.map +1 -1
  42. package/dist/castProjection.d.ts +35 -0
  43. package/dist/castProjection.d.ts.map +1 -0
  44. package/dist/castProjection.js +80 -0
  45. package/dist/castProjection.js.map +1 -0
  46. package/dist/conversation/binding.d.ts +77 -0
  47. package/dist/conversation/binding.d.ts.map +1 -0
  48. package/dist/conversation/binding.js +57 -0
  49. package/dist/conversation/binding.js.map +1 -0
  50. package/dist/conversation/controller.d.ts +209 -0
  51. package/dist/conversation/controller.d.ts.map +1 -0
  52. package/dist/conversation/controller.js +350 -0
  53. package/dist/conversation/controller.js.map +1 -0
  54. package/dist/conversation/effectiveModel.d.ts +62 -0
  55. package/dist/conversation/effectiveModel.d.ts.map +1 -0
  56. package/dist/conversation/effectiveModel.js +73 -0
  57. package/dist/conversation/effectiveModel.js.map +1 -0
  58. package/dist/conversation/index.d.ts +27 -0
  59. package/dist/conversation/index.d.ts.map +1 -0
  60. package/dist/conversation/index.js +27 -0
  61. package/dist/conversation/index.js.map +1 -0
  62. package/dist/conversation/participant.d.ts +66 -0
  63. package/dist/conversation/participant.d.ts.map +1 -0
  64. package/dist/conversation/participant.js +36 -0
  65. package/dist/conversation/participant.js.map +1 -0
  66. package/dist/conversation/presence.d.ts +56 -0
  67. package/dist/conversation/presence.d.ts.map +1 -0
  68. package/dist/conversation/presence.js +34 -0
  69. package/dist/conversation/presence.js.map +1 -0
  70. package/dist/conversation/presenceBus.d.ts +42 -0
  71. package/dist/conversation/presenceBus.d.ts.map +1 -0
  72. package/dist/conversation/presenceBus.js +81 -0
  73. package/dist/conversation/presenceBus.js.map +1 -0
  74. package/dist/conversation/presenceRegistry.d.ts +49 -0
  75. package/dist/conversation/presenceRegistry.d.ts.map +1 -0
  76. package/dist/conversation/presenceRegistry.js +59 -0
  77. package/dist/conversation/presenceRegistry.js.map +1 -0
  78. package/dist/conversation/roster.d.ts +72 -0
  79. package/dist/conversation/roster.d.ts.map +1 -0
  80. package/dist/conversation/roster.js +69 -0
  81. package/dist/conversation/roster.js.map +1 -0
  82. package/dist/conversation/rosterProjection.d.ts +52 -0
  83. package/dist/conversation/rosterProjection.d.ts.map +1 -0
  84. package/dist/conversation/rosterProjection.js +74 -0
  85. package/dist/conversation/rosterProjection.js.map +1 -0
  86. package/dist/conversation/router.d.ts +74 -0
  87. package/dist/conversation/router.d.ts.map +1 -0
  88. package/dist/conversation/router.js +58 -0
  89. package/dist/conversation/router.js.map +1 -0
  90. package/dist/conversation/runtime.d.ts +64 -0
  91. package/dist/conversation/runtime.d.ts.map +1 -0
  92. package/dist/conversation/runtime.js +172 -0
  93. package/dist/conversation/runtime.js.map +1 -0
  94. package/dist/conversation/types.d.ts +99 -0
  95. package/dist/conversation/types.d.ts.map +1 -0
  96. package/dist/conversation/types.js +13 -0
  97. package/dist/conversation/types.js.map +1 -0
  98. package/dist/conversation/voice.d.ts +185 -0
  99. package/dist/conversation/voice.d.ts.map +1 -0
  100. package/dist/conversation/voice.js +307 -0
  101. package/dist/conversation/voice.js.map +1 -0
  102. package/dist/graphSchema.d.ts +201 -13
  103. package/dist/graphSchema.d.ts.map +1 -1
  104. package/dist/graphSchema.js +258 -9
  105. package/dist/graphSchema.js.map +1 -1
  106. package/dist/http.d.ts +20 -0
  107. package/dist/http.d.ts.map +1 -0
  108. package/dist/http.js +57 -0
  109. package/dist/http.js.map +1 -0
  110. package/dist/index.d.ts +6 -0
  111. package/dist/index.d.ts.map +1 -1
  112. package/dist/index.js +9 -0
  113. package/dist/index.js.map +1 -1
  114. package/dist/platformAssistant.d.ts +155 -0
  115. package/dist/platformAssistant.d.ts.map +1 -0
  116. package/dist/platformAssistant.js +256 -0
  117. package/dist/platformAssistant.js.map +1 -0
  118. package/dist/reactor/chunkDistribution.d.ts +43 -0
  119. package/dist/reactor/chunkDistribution.d.ts.map +1 -0
  120. package/dist/reactor/chunkDistribution.js +85 -0
  121. package/dist/reactor/chunkDistribution.js.map +1 -0
  122. package/dist/reactor/index.d.ts +2 -0
  123. package/dist/reactor/index.d.ts.map +1 -1
  124. package/dist/reactor/index.js +5 -0
  125. package/dist/reactor/index.js.map +1 -1
  126. package/dist/reactor/longLiveCommandDispatcher.d.ts +103 -0
  127. package/dist/reactor/longLiveCommandDispatcher.d.ts.map +1 -0
  128. package/dist/reactor/longLiveCommandDispatcher.js +87 -0
  129. package/dist/reactor/longLiveCommandDispatcher.js.map +1 -0
  130. package/dist/reactor/scenesFromEnrichment.d.ts.map +1 -1
  131. package/dist/reactor/scenesFromEnrichment.js +2 -66
  132. package/dist/reactor/scenesFromEnrichment.js.map +1 -1
  133. package/dist/reactor/seedImageOrchestrator.d.ts +6 -9
  134. package/dist/reactor/seedImageOrchestrator.d.ts.map +1 -1
  135. package/dist/reactor/seedImageOrchestrator.js +12 -13
  136. package/dist/reactor/seedImageOrchestrator.js.map +1 -1
  137. package/dist/reactor/storyTimeline.d.ts +44 -0
  138. package/dist/reactor/storyTimeline.d.ts.map +1 -0
  139. package/dist/reactor/storyTimeline.js +95 -0
  140. package/dist/reactor/storyTimeline.js.map +1 -0
  141. package/dist/storyGraph.d.ts +70 -0
  142. package/dist/storyGraph.d.ts.map +1 -0
  143. package/dist/storyGraph.js +178 -0
  144. package/dist/storyGraph.js.map +1 -0
  145. package/dist/vision/VisionSourceController.d.ts +127 -0
  146. package/dist/vision/VisionSourceController.d.ts.map +1 -0
  147. package/dist/vision/VisionSourceController.js +284 -0
  148. package/dist/vision/VisionSourceController.js.map +1 -0
  149. package/dist/vision/index.d.ts +4 -0
  150. package/dist/vision/index.d.ts.map +1 -1
  151. package/dist/vision/index.js +2 -0
  152. package/dist/vision/index.js.map +1 -1
  153. package/dist/vision/sourceKinds.d.ts +65 -0
  154. package/dist/vision/sourceKinds.d.ts.map +1 -0
  155. package/dist/vision/sourceKinds.js +26 -0
  156. package/dist/vision/sourceKinds.js.map +1 -0
  157. package/dist/websocket.d.ts +92 -0
  158. package/dist/websocket.d.ts.map +1 -1
  159. package/dist/websocket.js.map +1 -1
  160. package/package.json +1 -1
  161. package/src/__tests__/adapters-capabilities.test.ts +46 -0
  162. package/src/__tests__/adapters-chat.test.ts +172 -0
  163. package/src/__tests__/adapters-director.test.ts +95 -0
  164. package/src/__tests__/adapters-image.test.ts +133 -0
  165. package/src/__tests__/adapters-platform.test.ts +95 -0
  166. package/src/__tests__/adapters-registry.test.ts +189 -0
  167. package/src/__tests__/adapters-world.test.ts +296 -0
  168. package/src/__tests__/admin.test.ts +312 -0
  169. package/src/__tests__/adventures-party.test.ts +219 -0
  170. package/src/__tests__/adventures.test.ts +282 -0
  171. package/src/__tests__/api-pollers.test.ts +4 -0
  172. package/src/__tests__/api.clip-lookup.test.ts +64 -0
  173. package/src/__tests__/api.list-images-filters.test.ts +103 -0
  174. package/src/__tests__/api.test.ts +553 -0
  175. package/src/__tests__/audio.test.ts +65 -0
  176. package/src/__tests__/cast.test.ts +95 -0
  177. package/src/__tests__/castProjection.test.ts +167 -0
  178. package/src/__tests__/conversation/binding.test.ts +62 -0
  179. package/src/__tests__/conversation/controller.test.ts +732 -0
  180. package/src/__tests__/conversation/effectiveModel.test.ts +169 -0
  181. package/src/__tests__/conversation/headlessRenderer.ts +46 -0
  182. package/src/__tests__/conversation/presenceBus.test.ts +236 -0
  183. package/src/__tests__/conversation/presenceRegistry.test.ts +73 -0
  184. package/src/__tests__/conversation/roster.test.ts +100 -0
  185. package/src/__tests__/conversation/rosterProjection.test.ts +142 -0
  186. package/src/__tests__/conversation/router.test.ts +81 -0
  187. package/src/__tests__/conversation/runtime.test.ts +206 -0
  188. package/src/__tests__/conversation/voice.test.ts +440 -0
  189. package/src/__tests__/documents.test.ts +360 -0
  190. package/src/__tests__/graphSchema.test.ts +218 -9
  191. package/src/__tests__/longLiveCommandDispatcher.test.ts +185 -0
  192. package/src/__tests__/monitoring.test.ts +162 -0
  193. package/src/__tests__/persona-generation.test.ts +352 -0
  194. package/src/__tests__/platformAssistant.test.ts +484 -0
  195. package/src/__tests__/reactor/storyTimeline.test.ts +186 -0
  196. package/src/__tests__/regeneration.test.ts +486 -0
  197. package/src/__tests__/stories.test.ts +171 -0
  198. package/src/__tests__/storyGraph.test.ts +134 -0
  199. package/src/__tests__/tools-wrappers.test.ts +272 -0
  200. package/src/__tests__/videoGraph.test.ts +94 -0
  201. package/src/__tests__/websocket.test.ts +263 -0
  202. package/src/adapters/capabilities.ts +24 -0
  203. package/src/adapters/chatAdapter.ts +114 -0
  204. package/src/adapters/directorAdapter.ts +126 -0
  205. package/src/adapters/imageAdapter.ts +100 -0
  206. package/src/adapters/index.ts +67 -0
  207. package/src/adapters/registry.ts +159 -0
  208. package/src/adapters/worldAdapter.ts +272 -0
  209. package/src/admin.ts +517 -0
  210. package/src/api.ts +2215 -95
  211. package/src/audio.ts +35 -0
  212. package/src/castProjection.ts +95 -0
  213. package/src/conversation/binding.ts +100 -0
  214. package/src/conversation/controller.ts +447 -0
  215. package/src/conversation/effectiveModel.ts +111 -0
  216. package/src/conversation/index.ts +27 -0
  217. package/src/conversation/participant.ts +71 -0
  218. package/src/conversation/presence.ts +60 -0
  219. package/src/conversation/presenceBus.ts +109 -0
  220. package/src/conversation/presenceRegistry.ts +83 -0
  221. package/src/conversation/roster.ts +111 -0
  222. package/src/conversation/rosterProjection.ts +98 -0
  223. package/src/conversation/router.ts +96 -0
  224. package/src/conversation/runtime.ts +188 -0
  225. package/src/conversation/types.ts +100 -0
  226. package/src/conversation/voice.ts +402 -0
  227. package/src/graphSchema.ts +396 -13
  228. package/src/http.ts +72 -0
  229. package/src/index.ts +9 -0
  230. package/src/platformAssistant.ts +347 -0
  231. package/src/reactor/chunkDistribution.ts +98 -0
  232. package/src/reactor/index.ts +5 -0
  233. package/src/reactor/longLiveCommandDispatcher.ts +156 -0
  234. package/src/reactor/scenesFromEnrichment.ts +11 -76
  235. package/src/reactor/seedImageOrchestrator.ts +12 -13
  236. package/src/reactor/storyTimeline.ts +127 -0
  237. package/src/storyGraph.ts +298 -0
  238. package/src/vision/VisionSourceController.ts +354 -0
  239. package/src/vision/__tests__/VisionSourceController.test.ts +719 -0
  240. package/src/vision/index.ts +13 -0
  241. package/src/vision/sourceKinds.ts +75 -0
  242. package/src/websocket.ts +99 -3
@@ -0,0 +1,447 @@
1
+ /**
2
+ * Headless conversation orchestrator (R2.1).
3
+ *
4
+ * The framework-agnostic owner of a conversation's STATE — participants, the
5
+ * active one, the bound context, the model override — and a THIN state+reducer
6
+ * wrapper over the existing `ChatWebSocket` (websocket.ts). It does NOT
7
+ * re-implement transport, reconnect, or the wire protocol: it delegates connect/
8
+ * send to `ChatWebSocket` and builds the hello ONLY via `buildHelloPayload`
9
+ * (audio.ts) — the single hello-builder (the cross-PR DRY rule). React (R2.2)
10
+ * and PlayCanvas (R7) both drive this same controller and render its snapshots;
11
+ * the controller emits a typed `onState` callback, never framework events.
12
+ *
13
+ * Socket ownership: by default the controller OWNS one `ChatWebSocket` and
14
+ * disposes it on `dispose()`. When constructed with `existingSocket` it ADOPTS
15
+ * that socket instead — opens no new connection and does NOT close it on dispose
16
+ * (the owner does). That is the Watch shared-socket invariant: Watch's chat and
17
+ * vision must ride one `ChatWebSocket` so the dispatcher reads one `FrameBuffer`
18
+ * (split sockets empty the vision buffer).
19
+ */
20
+
21
+ import { ChatWebSocket, type MessageHandler } from '../websocket';
22
+ import { buildHelloPayload } from '../audio';
23
+ import type { HelloPayload } from '../audio';
24
+ import type { AdapterRegistry, ChatAdapterDescriptor } from '../adapters';
25
+ import type { ChatModelCapability } from '../api';
26
+ import {
27
+ ParticipantRole,
28
+ type ConversationParticipant,
29
+ } from './participant';
30
+ import {
31
+ toHelloArgs,
32
+ type ConversationContextBinding,
33
+ type HelloArgs,
34
+ } from './binding';
35
+ import { resolveEffectiveModel, type EffectiveModel } from './effectiveModel';
36
+
37
+ /** Immutable view of the controller's state, handed to `onState` on each change. */
38
+ export interface ConversationSnapshot {
39
+ participants: readonly ConversationParticipant[];
40
+ activeParticipantId: string | undefined;
41
+ binding: ConversationContextBinding;
42
+ modelOverride: string | undefined;
43
+ /** True once `connect()` has driven a hello onto the socket. */
44
+ connected: boolean;
45
+ }
46
+
47
+ /** One prior turn, in the wire shape `ChatWebSocket.send`'s `messages` expects. */
48
+ export interface ConversationHistoryMessage {
49
+ role: string;
50
+ content: string;
51
+ modelId?: string;
52
+ }
53
+
54
+ export interface ConversationSendOptions {
55
+ /**
56
+ * Prior turns to ride on THIS send. The backend builds `conversation_history`
57
+ * solely from each send's `messages` field (`api/chat/ws.py`) — omit it and
58
+ * the turn is treated as a first turn. The controller stays message-LESS (it
59
+ * owns context, not chat history), so the renderer that owns the transcript
60
+ * passes its prior turns here per send, exactly like the chat-ws page does.
61
+ */
62
+ messages?: ConversationHistoryMessage[];
63
+ }
64
+
65
+ export interface ConversationControllerOptions {
66
+ binding: ConversationContextBinding;
67
+ participants?: ConversationParticipant[];
68
+ /** The R1 chat adapter registry — the capability source for the model gate. */
69
+ registry: AdapterRegistry<ChatAdapterDescriptor>;
70
+ /** Initial explicit model override, if any. */
71
+ modelOverride?: string;
72
+ /** Typed state callback. No framework events — the renderer subscribes here. */
73
+ onState?: (snapshot: ConversationSnapshot) => void;
74
+ /**
75
+ * Options for the `ChatWebSocket` the controller opens. Ignored when
76
+ * `existingSocket` is supplied (the adopted socket is already configured).
77
+ */
78
+ socketOptions?: ConstructorParameters<typeof ChatWebSocket>[0];
79
+ /**
80
+ * An already-open `ChatWebSocket` to ADOPT. When set, `connect()` opens no new
81
+ * connection and `dispose()` does NOT close it (the Watch shared-socket
82
+ * invariant — the owner manages its lifecycle).
83
+ */
84
+ existingSocket?: ChatWebSocket;
85
+ }
86
+
87
+ export class ConversationController {
88
+ private participants: ConversationParticipant[];
89
+ private activeParticipantId: string | undefined;
90
+ private binding: ConversationContextBinding;
91
+ private modelOverride: string | undefined;
92
+ private connected = false;
93
+ /** In-flight `connect()` promise — dedups concurrent callers so exactly one
94
+ * hello is sent even if `connect()` races with itself. */
95
+ private connectPromise: Promise<void> | undefined;
96
+ /** Set by `dispose()`. Guards `doConnect()` from sending a hello onto a
97
+ * socket the owner already tore down mid-connect. */
98
+ private disposed = false;
99
+
100
+ private readonly registry: AdapterRegistry<ChatAdapterDescriptor>;
101
+ private readonly onState?: (snapshot: ConversationSnapshot) => void;
102
+ private readonly socket: ChatWebSocket;
103
+ /** True iff the controller created `socket` (and must dispose it). */
104
+ private readonly ownsSocket: boolean;
105
+
106
+ constructor(opts: ConversationControllerOptions) {
107
+ this.participants = [...(opts.participants ?? [])];
108
+ this.activeParticipantId = this.participants[0]?.participantId;
109
+ this.registry = opts.registry;
110
+ this.modelOverride = opts.modelOverride;
111
+ this.onState = opts.onState;
112
+
113
+ if (opts.existingSocket) {
114
+ this.socket = opts.existingSocket;
115
+ this.ownsSocket = false;
116
+ } else {
117
+ // Fail loud at construction rather than cryptically at connect() time with
118
+ // an invalid-URL error: an owned controller needs real socket options.
119
+ if (!opts.socketOptions) {
120
+ throw new Error(
121
+ 'ConversationController: socketOptions is required when no existingSocket is provided.',
122
+ );
123
+ }
124
+ this.socket = new ChatWebSocket(opts.socketOptions);
125
+ this.ownsSocket = true;
126
+ }
127
+
128
+ // Seed the binding with the party roster derived from the initial roster so
129
+ // the first hello carries it (re-derived again on every add/remove).
130
+ this.binding = this.bindingWithDerivedParty(opts.binding);
131
+ }
132
+
133
+ /**
134
+ * Open the conversation: drive exactly ONE hello onto the socket, built only
135
+ * via `buildHelloPayload(this.toHelloArgs())`. An OWNED socket is dialed
136
+ * first; an ADOPTED socket is already open, so we only send the hello onto it
137
+ * (no second connection — the Watch invariant).
138
+ *
139
+ * IDEMPOTENT + race-safe: returns immediately when already connected, and
140
+ * dedups a concurrent in-flight `connect()` via `connectPromise` so two callers
141
+ * that both enter before `connected` flips still send exactly ONE hello (and an
142
+ * owned controller never opens a second socket).
143
+ */
144
+ async connect(): Promise<void> {
145
+ if (this.connected) return;
146
+ if (this.connectPromise) return this.connectPromise;
147
+ this.connectPromise = this.doConnect();
148
+ try {
149
+ await this.connectPromise;
150
+ } finally {
151
+ this.connectPromise = undefined;
152
+ }
153
+ }
154
+
155
+ private async doConnect(): Promise<void> {
156
+ if (this.ownsSocket) {
157
+ await this.socket.connect();
158
+ }
159
+ // If dispose() ran while we were dialing, don't send a hello onto the
160
+ // now-disconnected socket (a dispose-during-connect race).
161
+ if (this.disposed) return;
162
+ this.socket.sendHello(this.buildHello());
163
+ this.connected = true;
164
+ this.emit();
165
+ }
166
+
167
+ /**
168
+ * Build the hello payload for the current binding + active participant. The
169
+ * SINGLE hello-builder: every field flows through `buildHelloPayload`, and the
170
+ * args flow through `toHelloArgs` (the one binding→hello mapper). The active
171
+ * participant overlays `personaId` / `modelId`, where `modelId` is `override`
172
+ * if set, else the participant's bound model. Auto-switch is NOT applied here:
173
+ * the R2.2 consumer calls `resolveEffectiveModel(needed)`, and on `auto_switch`
174
+ * calls `setModelOverride()` BEFORE `connect()` — so the override path above is
175
+ * what carries an auto-switched model onto the wire.
176
+ */
177
+ buildHello(): HelloPayload {
178
+ const active = this.activeParticipant();
179
+ // Effective model = override > active participant's bound model. Reuse the
180
+ // already-resolved `active` rather than re-scanning via a helper.
181
+ const modelId = this.modelOverride ?? active?.modelId;
182
+ return buildHelloPayload({
183
+ ...this.toHelloArgs(),
184
+ ...(active?.personaId ? { personaId: active.personaId } : {}),
185
+ ...(modelId ? { modelId } : {}),
186
+ // TEXT mode, always (R2.3). The controller owns TEXT conversations — the
187
+ // R2.2 scoping finding keeps voice (and its rich `tts_stt` hello with the
188
+ // audio knobs) page-owned. `buildHelloPayload` defaults `mode` to
189
+ // `'tts_stt'`, which the backend routes into the full STT/TTS voice
190
+ // pipeline (`api/chat/ws.py`: `hello.mode == "tts_stt"` →
191
+ // `_handle_audio_session`, then `break`s out of the text loop). A `text`
192
+ // hello is a context/ack-only handshake — exactly what a
193
+ // controller-driven conversation needs.
194
+ mode: 'text',
195
+ });
196
+ }
197
+
198
+ /** The binding→hello-args mapping (delegates to the single mapper in binding.ts). */
199
+ toHelloArgs(): ReturnType<typeof toHelloArgs> {
200
+ return toHelloArgs(this.binding);
201
+ }
202
+
203
+ /**
204
+ * Send a chat turn. Threads the bound context (`videoId` / `entityId` /
205
+ * `adventureSessionId` / advisory `partyPersonaIds`), the active persona, the
206
+ * effective model id, and the renderer-owned `opts.messages` history onto
207
+ * `ChatWebSocket.send` — the controller never builds its own send frame.
208
+ */
209
+ send(text: string, opts?: ConversationSendOptions): void {
210
+ // Fail loud: a send before connect() would push a frame onto a socket that
211
+ // never received the hello context (silent message loss otherwise).
212
+ if (!this.connected) {
213
+ throw new Error('ConversationController: call connect() before send().');
214
+ }
215
+ const active = this.activeParticipant();
216
+ const args = this.toHelloArgs();
217
+ const modelId = this.modelOverride ?? active?.modelId;
218
+ this.socket.send(text, {
219
+ ...(args.videoId ? { videoId: args.videoId } : {}),
220
+ ...(args.entityId ? { entityId: args.entityId } : {}),
221
+ ...(args.adventureSessionId
222
+ ? { adventureSessionId: args.adventureSessionId }
223
+ : {}),
224
+ ...(args.partyPersonaIds ? { partyPersonaIds: args.partyPersonaIds } : {}),
225
+ // Persona scope threads on every send, not just the hello: a standalone
226
+ // PERSONA binding (kind:'persona') has no explicit participant in the
227
+ // overlay-default path, so the binding-level personaId is the only scope.
228
+ // The active participant's personaId still WINS when present (overlay
229
+ // order mirrors buildHello), so a seated cast persona is unaffected. For
230
+ // non-PERSONA bindings args.personaId is undefined ⇒ the frame stays
231
+ // byte-identical (land-dark).
232
+ ...(args.personaId ? { personaId: args.personaId } : {}),
233
+ ...(active?.personaId ? { personaId: active.personaId } : {}),
234
+ ...(modelId ? { modelId } : {}),
235
+ // Omitted when empty so a zero-history send stays byte-identical to the
236
+ // pre-0.30.0 wire (the backend defaults a missing `messages` to []).
237
+ ...(opts?.messages?.length ? { messages: opts.messages } : {}),
238
+ });
239
+ }
240
+
241
+ /**
242
+ * Subscribe to the conversation socket's inbound JSON messages (`token`,
243
+ * `citation`, `done`, `error`, `turn_changed`, …) and return an unsubscribe
244
+ * function (R2.3, additive). A thin passthrough to
245
+ * `ChatWebSocket.onMessage`/`offMessage` — the controller stays message-LESS
246
+ * (it owns context/state, not chat history), but a renderer (the React panel,
247
+ * a PlayCanvas scene) needs a seam to consume reply events without reaching
248
+ * into a socket the controller may privately own. Works for both owned and
249
+ * adopted sockets; on an adopted socket this is equivalent to subscribing on
250
+ * the socket directly.
251
+ */
252
+ onMessage(handler: MessageHandler): () => void {
253
+ this.socket.onMessage(handler);
254
+ return () => this.socket.offMessage(handler);
255
+ }
256
+
257
+ /**
258
+ * The conversation's `ChatWebSocket`, for a `VoiceSession` (R7.5) to drive the
259
+ * voice round-trip over the SAME socket (one socket ⇒ one `FrameBuffer` — the
260
+ * Watch shared-socket invariant). Additive seam: the renderer constructs a
261
+ * `VoiceSession` against this socket + the controller's `toHelloArgs()` (so
262
+ * voice rides the single hello-builder + the active binding/participant), and
263
+ * the `VoiceSession` NEVER closes it (the controller / adopting surface owns
264
+ * the transport). Works for both owned and adopted sockets.
265
+ */
266
+ voiceSocket(): ChatWebSocket {
267
+ return this.socket;
268
+ }
269
+
270
+ /**
271
+ * The hello-args for the active binding + participant overlay — the SAME shape
272
+ * `buildHello()` spreads, exposed so a `VoiceSession` (R7.5) layers its voice
273
+ * knobs on top through the single `buildHelloPayload`. Includes the active
274
+ * participant's `personaId`/`modelId` (override-or-bound) so the voice hello
275
+ * is scoped identically to the text one. No second hello-construction site.
276
+ */
277
+ voiceHelloArgs(): ReturnType<typeof toHelloArgs> &
278
+ Pick<HelloArgs, 'personaId' | 'modelId'> {
279
+ const active = this.activeParticipant();
280
+ const modelId = this.modelOverride ?? active?.modelId;
281
+ return {
282
+ ...this.toHelloArgs(),
283
+ ...(active?.personaId ? { personaId: active.personaId } : {}),
284
+ ...(modelId ? { modelId } : {}),
285
+ };
286
+ }
287
+
288
+ /** Set an explicit model override (wins over bound / auto-switch). */
289
+ setModelOverride(modelId: string): void {
290
+ this.modelOverride = modelId;
291
+ this.emit();
292
+ }
293
+
294
+ /** Clear the override — the effective model reverts to bound / auto-switch. */
295
+ clearModelOverride(): void {
296
+ this.modelOverride = undefined;
297
+ this.emit();
298
+ }
299
+
300
+ /**
301
+ * Resolve the effective model for the active participant given the requested
302
+ * capabilities (e.g. `['vision']` when the webcam is ON). Delegates to the
303
+ * single `resolveEffectiveModel` helper — the controller holds no capability
304
+ * logic of its own. Returns `undefined` when there is no active model-backed
305
+ * participant to gate.
306
+ */
307
+ resolveEffectiveModel(
308
+ needed: readonly ChatModelCapability[] = [],
309
+ ): EffectiveModel | undefined {
310
+ const boundModelId = this.activeParticipant()?.modelId;
311
+ if (!boundModelId) {
312
+ return undefined;
313
+ }
314
+ return resolveEffectiveModel({
315
+ boundModelId,
316
+ needed,
317
+ override: this.modelOverride,
318
+ registry: this.registry,
319
+ });
320
+ }
321
+
322
+ /**
323
+ * Add a participant and re-derive the advisory `partyPersonaIds` for the next
324
+ * hello (matches `advisoryPartyPersonaIds` semantics). First participant
325
+ * becomes active. THROWS on a duplicate `participantId` — additive, no silent
326
+ * overwrite (the registry discipline).
327
+ */
328
+ addParticipant(participant: ConversationParticipant): void {
329
+ if (this.participants.some((p) => p.participantId === participant.participantId)) {
330
+ throw new Error(
331
+ `ConversationController: duplicate participantId "${participant.participantId}".`,
332
+ );
333
+ }
334
+ this.participants.push(participant);
335
+ if (this.activeParticipantId === undefined) {
336
+ this.activeParticipantId = participant.participantId;
337
+ }
338
+ this.rederiveParty();
339
+ this.emit();
340
+ }
341
+
342
+ /**
343
+ * Remove a participant by id and re-derive `partyPersonaIds`. If the removed
344
+ * one was active, the active pointer falls to the first remaining participant
345
+ * (or `undefined`). **No-op (idempotent) if `participantId` is not present** —
346
+ * deliberately asymmetric with `addParticipant`, which throws on a duplicate.
347
+ */
348
+ removeParticipant(participantId: string): void {
349
+ this.participants = this.participants.filter(
350
+ (p) => p.participantId !== participantId,
351
+ );
352
+ if (this.activeParticipantId === participantId) {
353
+ this.activeParticipantId = this.participants[0]?.participantId;
354
+ }
355
+ this.rederiveParty();
356
+ this.emit();
357
+ }
358
+
359
+ /**
360
+ * Point the active participant at `participantId`. THROWS on an unknown id —
361
+ * unlike `removeParticipant` (idempotent no-op), you cannot make an absent
362
+ * participant active, so a typo'd id is a caller error, not a tolerable no-op
363
+ * (the fail-loud discipline, consistent with `addParticipant`).
364
+ */
365
+ setActiveParticipant(participantId: string): void {
366
+ if (!this.participants.some((p) => p.participantId === participantId)) {
367
+ throw new Error(
368
+ `ConversationController: cannot set active to unknown participantId "${participantId}".`,
369
+ );
370
+ }
371
+ this.activeParticipantId = participantId;
372
+ this.emit();
373
+ }
374
+
375
+ /** Current immutable snapshot. Both the participant objects (and their
376
+ * `capabilities` array) and the binding's `partyPersonaIds` array are COPIED
377
+ * so mutating the snapshot can't reach into the controller's internal state. */
378
+ snapshot(): ConversationSnapshot {
379
+ return {
380
+ participants: this.participants.map((p) => ({
381
+ ...p,
382
+ ...(p.capabilities ? { capabilities: [...p.capabilities] } : {}),
383
+ })),
384
+ activeParticipantId: this.activeParticipantId,
385
+ binding: {
386
+ ...this.binding,
387
+ ...(this.binding.partyPersonaIds
388
+ ? { partyPersonaIds: [...this.binding.partyPersonaIds] }
389
+ : {}),
390
+ },
391
+ modelOverride: this.modelOverride,
392
+ connected: this.connected,
393
+ };
394
+ }
395
+
396
+ /**
397
+ * Tear down. Disconnects the socket ONLY when the controller owns it — an
398
+ * ADOPTED socket is left untouched (the owner disposes it; the Watch
399
+ * shared-socket invariant). Idempotent.
400
+ */
401
+ dispose(): void {
402
+ this.disposed = true;
403
+ this.connected = false;
404
+ if (this.ownsSocket) {
405
+ this.socket.disconnect();
406
+ }
407
+ }
408
+
409
+ // ── internals ────────────────────────────────────────────────────────────
410
+
411
+ private activeParticipant(): ConversationParticipant | undefined {
412
+ return this.participants.find(
413
+ (p) => p.participantId === this.activeParticipantId,
414
+ );
415
+ }
416
+
417
+ /**
418
+ * Advisory party persona ids derived from the persona participants (the `dm`
419
+ * and `user` seats are excluded — only party members route scenes). Mirrors
420
+ * `advisoryPartyPersonaIds`: returns `undefined` when empty so the hello drops
421
+ * the key and stays byte-identical for ordinary chat / single-DM adventures.
422
+ */
423
+ private derivePartyPersonaIds(): string[] | undefined {
424
+ const ids = this.participants
425
+ .filter((p) => p.role === ParticipantRole.PERSONA && Boolean(p.personaId))
426
+ .map((p) => p.personaId as string);
427
+ return ids.length > 0 ? ids : undefined;
428
+ }
429
+
430
+ private bindingWithDerivedParty(
431
+ binding: ConversationContextBinding,
432
+ ): ConversationContextBinding {
433
+ const partyPersonaIds = this.derivePartyPersonaIds();
434
+ return {
435
+ ...binding,
436
+ ...(partyPersonaIds ? { partyPersonaIds } : { partyPersonaIds: undefined }),
437
+ };
438
+ }
439
+
440
+ private rederiveParty(): void {
441
+ this.binding = this.bindingWithDerivedParty(this.binding);
442
+ }
443
+
444
+ private emit(): void {
445
+ this.onState?.(this.snapshot());
446
+ }
447
+ }
@@ -0,0 +1,111 @@
1
+ /**
2
+ * Capability auto-switch — the single, pure model-selection helper (R2.1).
3
+ *
4
+ * This is the ONE place R2 decides which model a turn runs on when a capability
5
+ * (today: `'vision'` when the webcam toggles ON) is needed that the bound
6
+ * persona's model lacks. R3's vision-source picker CONSUMES this exact helper —
7
+ * there is no parallel `resolveVisionCapability`. It is fully unit-testable: no
8
+ * I/O, no network. Capability FACTS come only from the injected R1 chat adapter
9
+ * registry (which mirrors `shared/model_config.py`); this helper never hardcodes
10
+ * which models are vision-capable.
11
+ *
12
+ * Precedence: an explicit override wins; otherwise the bound model is kept iff
13
+ * it already satisfies the needed caps; otherwise we auto-switch to the first
14
+ * registry model advertising the needed caps.
15
+ */
16
+
17
+ import type { AdapterRegistry } from '../adapters';
18
+ import type { ChatAdapterDescriptor } from '../adapters';
19
+ import type { ChatModelCapability } from '../api';
20
+
21
+ /** Why `resolveEffectiveModel` chose the model it returned. */
22
+ export const EffectiveModelReason = {
23
+ BOUND: 'bound',
24
+ OVERRIDE: 'override',
25
+ AUTO_SWITCH: 'auto_switch',
26
+ } as const;
27
+
28
+ export type EffectiveModelReason =
29
+ (typeof EffectiveModelReason)[keyof typeof EffectiveModelReason];
30
+
31
+ export interface ResolveEffectiveModelArgs {
32
+ /** The context-bound persona's model id (the default choice). */
33
+ boundModelId: string;
34
+ /**
35
+ * Capabilities required for this turn — e.g. `['vision']` when the webcam is
36
+ * ON. Empty means no gate, so the bound model is always kept.
37
+ */
38
+ needed: readonly ChatModelCapability[];
39
+ /** An explicit user override, when set — wins over bound/auto-switch. */
40
+ override?: string;
41
+ /** The R1 chat adapter registry — the single source of capability facts. */
42
+ registry: Pick<
43
+ AdapterRegistry<ChatAdapterDescriptor>,
44
+ 'satisfies' | 'listWithCapability'
45
+ >;
46
+ }
47
+
48
+ export interface EffectiveModel {
49
+ modelId: string;
50
+ reason: EffectiveModelReason;
51
+ /** The bound model we switched away from — set ONLY for `auto_switch`. */
52
+ switchedFrom?: string;
53
+ /** Echo of the needed caps that drove the decision (for UI banners). */
54
+ needed: readonly ChatModelCapability[];
55
+ }
56
+
57
+ /**
58
+ * Resolve the model a turn should run on given the bound model, the needed
59
+ * capabilities, and an optional override. PURE.
60
+ *
61
+ * - `override` set ⇒ `'override'` (we trust the user's explicit pick; we do NOT
62
+ * second-guess its caps — that is the user's choice to make).
63
+ * - bound model satisfies `needed` (or `needed` is empty) ⇒ `'bound'`.
64
+ * - otherwise ⇒ `'auto_switch'` to the first registry model that satisfies
65
+ * EVERY needed cap (not just the first unmet one — a vision-only model is no
66
+ * good when `['vision','audio']` is needed), carrying `switchedFrom`. If NO
67
+ * model satisfies the full set, we keep the bound model as a fail-soft
68
+ * `'bound'` — the panel surfaces the gap rather than the helper throwing (a
69
+ * registry that lists zero vision models is a config state, not a crash).
70
+ */
71
+ export function resolveEffectiveModel(args: ResolveEffectiveModelArgs): EffectiveModel {
72
+ const { boundModelId, needed, override, registry } = args;
73
+
74
+ if (override) {
75
+ return { modelId: override, reason: EffectiveModelReason.OVERRIDE, needed };
76
+ }
77
+
78
+ if (needed.length === 0 || registry.satisfies(boundModelId, needed)) {
79
+ return { modelId: boundModelId, reason: EffectiveModelReason.BOUND, needed };
80
+ }
81
+
82
+ // Bound model lacks a needed cap and there's no override: auto-switch to the
83
+ // first model that satisfies the WHOLE `needed` set. We seed the candidate
84
+ // pool from the first unmet cap (every valid candidate must advertise it) then
85
+ // require `satisfies(candidate, needed)` so multi-cap requests (e.g.
86
+ // ['vision','audio']) don't settle for a vision-only model. Deterministic:
87
+ // first matching candidate in registry order.
88
+ // `unmet` is always found here (needed is non-empty and the bound model failed
89
+ // the full set). The `?:` guard below is belt-and-suspenders for this helper's
90
+ // "never throw" contract: if that invariant were ever broken, `candidate` stays
91
+ // undefined and we fall through to the fail-soft `return bound` at the end —
92
+ // never calling `listWithCapability(undefined)`.
93
+ const unmet = needed.find((cap) => !registry.satisfies(boundModelId, [cap]));
94
+ const candidate = unmet
95
+ ? registry
96
+ .listWithCapability(unmet)
97
+ .find((model) => registry.satisfies(model.id, needed))
98
+ : undefined;
99
+ if (candidate) {
100
+ return {
101
+ modelId: candidate.id,
102
+ reason: EffectiveModelReason.AUTO_SWITCH,
103
+ switchedFrom: boundModelId,
104
+ needed,
105
+ };
106
+ }
107
+
108
+ // Nothing in the registry can satisfy the gap — keep the bound model (the
109
+ // panel shows the unmet cap); fail-soft, never throw.
110
+ return { modelId: boundModelId, reason: EffectiveModelReason.BOUND, needed };
111
+ }
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Barrel for the framework-agnostic `conversation/` core (R2.1).
3
+ *
4
+ * Re-exported from `src/index.ts` via `export * from './conversation'`. Owns the
5
+ * headless conversation state (participants, presence, bound context, model
6
+ * override + capability auto-switch) with NO DOM — the seam that lets React
7
+ * (R2.2) and PlayCanvas (R7) render the same controller.
8
+ *
9
+ * ADDITIVE-ONLY: every symbol here is new. `Citation`/`PlaybackState` and the
10
+ * `ChatModelCapability` union live on `websocket.ts` / `api.ts` and are IMPORTED
11
+ * by these modules, never re-declared — avoiding the documented ambiguous-export
12
+ * trap in the top-level barrel.
13
+ */
14
+
15
+ export * from './participant';
16
+ export * from './presenceRegistry';
17
+ export * from './binding';
18
+ export * from './effectiveModel';
19
+ export * from './controller';
20
+ export * from './types';
21
+ export * from './router';
22
+ export * from './roster';
23
+ export * from './rosterProjection';
24
+ export * from './runtime';
25
+ export * from './presence';
26
+ export * from './presenceBus';
27
+ export * from './voice';
@@ -0,0 +1,71 @@
1
+ /**
2
+ * Conversation participant model (R2.1).
3
+ *
4
+ * A `ConversationParticipant` is ONE seat in a conversation — a bound persona,
5
+ * the Dungeon Master, or the human user. The headless `ConversationController`
6
+ * (controller.ts) holds a list of these plus an active one; React (R2.2) and a
7
+ * game engine (R7) both render the same list without owning its shape.
8
+ *
9
+ * `role` and `presence` are frozen constant objects — never inline the string
10
+ * literals (the cross-PR "constants over string literals" rule). The capability
11
+ * vocabulary is the EXISTING `ChatModelCapability` union from api.ts (the single
12
+ * source of truth that mirrors `shared/model_config.py:CAPABILITY_*`); R2 does
13
+ * NOT declare a parallel capability map.
14
+ */
15
+
16
+ import type { ChatModelCapability } from '../api';
17
+
18
+ /**
19
+ * The kind of seat a participant occupies. `persona` and `dm` are
20
+ * model-backed; `user` is the human. Frozen so a role can never be a raw
21
+ * string at a call site — mirrors the `ROUTE_*`/`PRESENCE_*` discipline.
22
+ */
23
+ export const ParticipantRole = {
24
+ PERSONA: 'persona',
25
+ DM: 'dm',
26
+ USER: 'user',
27
+ } as const;
28
+
29
+ export type ParticipantRole = (typeof ParticipantRole)[keyof typeof ParticipantRole];
30
+
31
+ /**
32
+ * How a participant is rendered on the presence stage. `PRESENCE_AVATAR_3D` is
33
+ * a RESERVED stub — the kind is registerable but its renderer is a no-op until
34
+ * the R7 flagship lands (see `PresenceRendererRegistry` + tech-debt). The values
35
+ * double as the registry lookup keys.
36
+ */
37
+ export const PresenceKind = {
38
+ PRESENCE_NONE: 'none',
39
+ PRESENCE_FACE_2D: 'face_2d',
40
+ PRESENCE_AVATAR_3D: 'avatar_3d',
41
+ } as const;
42
+
43
+ export type PresenceKind = (typeof PresenceKind)[keyof typeof PresenceKind];
44
+
45
+ /**
46
+ * One seat in a conversation. `modelId` is the bound model the capability gate
47
+ * resolves against; `capabilities` is an ADVISORY display-only mirror (see its
48
+ * field doc). Both optional: the `user` seat and presence-only participants
49
+ * carry neither.
50
+ */
51
+ export interface ConversationParticipant {
52
+ /** Stable per-conversation id for this seat (not the persona id). */
53
+ participantId: string;
54
+ /** Bound persona id, when this seat portrays a persona. */
55
+ personaId?: string;
56
+ role: ParticipantRole;
57
+ presence: PresenceKind;
58
+ /** The bound model's id, when this seat is model-backed. The capability gate
59
+ * (`resolveEffectiveModel`) resolves caps against the R1 registry keyed by
60
+ * THIS id — never the `capabilities` mirror below. */
61
+ modelId?: string;
62
+ /**
63
+ * ADVISORY / display-only mirror of the bound model's caps (e.g. for R2.2's
64
+ * capability chips). It does **NOT** gate model selection — `resolveEffectiveModel`
65
+ * reads the authoritative caps from the R1 chat registry (`registry.satisfies`),
66
+ * which mirrors `shared/model_config.py` (single source of truth). Kept so the
67
+ * renderer can show caps without a second registry lookup; never trusted for
68
+ * the auto-switch decision.
69
+ */
70
+ capabilities?: ChatModelCapability[];
71
+ }