@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,60 @@
1
+ /**
2
+ * `PresenceAdapter` (R7.3) — the renderer-agnostic seam the
3
+ * `ConversationRuntime` drives. React (`CharacterFace`, 2D persona face) is
4
+ * ONE implementation; a PlayCanvas 3D avatar is a FUTURE implementation
5
+ * consuming the identical contract. Zero React/DOM/PlayCanvas imports here.
6
+ *
7
+ * Every method is keyed by `personaId`, so an N-participant scene maps cleanly
8
+ * onto N presence slots regardless of renderer. The method set is derived
9
+ * STRICTLY from what the React face already does (active swap, speaking flag,
10
+ * viseme) plus mount/unmount — no speculative methods (the over-abstraction
11
+ * guard in the R7 spec).
12
+ *
13
+ * Adapter SELECTION stays on the existing R2.1 seam: hosts register a renderer
14
+ * factory per `PresenceKind` on `PresenceRendererRegistry`
15
+ * (presenceRegistry.ts) — this module does NOT re-declare a kind→factory map.
16
+ * What it adds is the per-call gating contract: `presenceBus` consults
17
+ * {@link presenceKindHasStage} so a `PRESENCE_NONE` (text-only) participant
18
+ * receives no presence calls beyond `mount`/`unmount`.
19
+ *
20
+ * Viseme coupling (the R7.3 risk note): `applyViseme` takes the *scheduled
21
+ * viseme value* (`VisemeSymbol`, from the existing `visemeScheduler`/
22
+ * `visemeGeometry` pipeline) — never a DOM node. The React adapter applies it
23
+ * to SVG; a PlayCanvas adapter applies it to morph targets.
24
+ */
25
+
26
+ import { PresenceKind } from './participant';
27
+ import type { RosterParticipant } from './types';
28
+ import type { VisemeSymbol } from '../visemeScheduler';
29
+
30
+ /**
31
+ * The renderer contract. A host implements this once per renderer (2D face,
32
+ * 3D avatar, headless recorder) and `presenceBus` drives it from
33
+ * `ConversationRuntime` transitions.
34
+ */
35
+ export interface PresenceAdapter {
36
+ /** A participant entered the scene: create its presence slot. Called for
37
+ * EVERY roster member, including `PRESENCE_NONE` (so the renderer can
38
+ * account for text-only seats), but a `none` seat gets no further calls. */
39
+ mount(participant: RosterParticipant): void;
40
+ /** The participant left the scene (or the binding was disposed): tear the
41
+ * slot down. */
42
+ unmount(personaId: string): void;
43
+ /** The turn moved: `personaId` now holds the floor (`null` = nobody, e.g.
44
+ * after a host `releaseTurn`). Stage focus/camera/highlight here. */
45
+ setActiveParticipant(personaId: string | null): void;
46
+ /** Toggle the speaking indicator for one participant. */
47
+ setSpeaking(personaId: string, speaking: boolean): void;
48
+ /** Apply one scheduled viseme value to a participant's mouth — SVG path for
49
+ * the 2D face, morph target for a 3D avatar. */
50
+ applyViseme(personaId: string, viseme: VisemeSymbol): void;
51
+ }
52
+
53
+ /**
54
+ * True when a presence kind occupies the stage — i.e. should receive
55
+ * `setActiveParticipant`/`setSpeaking`/`applyViseme` calls. `PRESENCE_NONE`
56
+ * seats are text-only: mount/unmount bookkeeping, nothing staged.
57
+ */
58
+ export function presenceKindHasStage(kind: PresenceKind): boolean {
59
+ return kind !== PresenceKind.PRESENCE_NONE;
60
+ }
@@ -0,0 +1,109 @@
1
+ /**
2
+ * `presenceBus` (R7.3) — pure glue wiring `ConversationRuntime` state
3
+ * transitions to `PresenceAdapter` calls. No renderer dependency, no DOM, no
4
+ * network: a `turn_changed`-driven swap becomes
5
+ * `setActiveParticipant(next)` + `setSpeaking(prev,false)` + `setSpeaking(next,true)`,
6
+ * gated per participant by {@link presenceKindHasStage} so text-only
7
+ * (`PRESENCE_NONE`) seats receive nothing beyond `mount`/`unmount`.
8
+ *
9
+ * LAND-DARK: in ordinary chat / single-DM adventures the runtime's
10
+ * `activePersonaId` never moves, so after the initial staging the bus emits
11
+ * nothing — the conformance test pins exactly one `mount` + one
12
+ * `setActiveParticipant` + one `setSpeaking(true)` for the lone speaker.
13
+ *
14
+ * Visemes do not flow through runtime state (the voice pipeline lifts into
15
+ * client-core in R7.5); the binding exposes {@link PresenceBinding.applyViseme}
16
+ * as the single pass-through so R7.5 has exactly one delivery path to a face.
17
+ */
18
+
19
+ import type { ConversationRuntime } from './runtime';
20
+ import type { ConversationRuntimeState, RosterParticipant } from './types';
21
+ import type { PresenceAdapter } from './presence';
22
+ import { presenceKindHasStage } from './presence';
23
+ import type { VisemeSymbol } from '../visemeScheduler';
24
+
25
+ /** Handle returned by {@link bindPresence}. */
26
+ export interface PresenceBinding {
27
+ /**
28
+ * Deliver one scheduled viseme value to `personaId`'s presence slot.
29
+ * Dropped (no adapter call) when the persona is not in the roster or its
30
+ * presence kind has no stage (`PRESENCE_NONE`).
31
+ */
32
+ applyViseme(personaId: string, viseme: VisemeSymbol): void;
33
+ /** Unsubscribe from the runtime and unmount every mounted participant.
34
+ * Idempotent. */
35
+ dispose(): void;
36
+ }
37
+
38
+ /**
39
+ * Bind a `PresenceAdapter` to a `ConversationRuntime`.
40
+ *
41
+ * On bind: `mount` every roster participant (in roster order), then stage the
42
+ * initial speaker (`setActiveParticipant` + `setSpeaking(true)`) when one is
43
+ * set and staged. Thereafter every speaker transition (server `turn_changed`
44
+ * via the runtime, or a host `releaseTurn`) is mirrored to the adapter.
45
+ */
46
+ export function bindPresence(
47
+ runtime: ConversationRuntime,
48
+ adapter: PresenceAdapter,
49
+ ): PresenceBinding {
50
+ const byPersonaId = (
51
+ state: ConversationRuntimeState,
52
+ personaId: string | null,
53
+ ): RosterParticipant | undefined =>
54
+ personaId === null
55
+ ? undefined
56
+ : state.participants.find((p) => p.personaId === personaId);
57
+
58
+ const staged = (state: ConversationRuntimeState, personaId: string | null): boolean => {
59
+ const participant = byPersonaId(state, personaId);
60
+ return participant !== undefined && presenceKindHasStage(participant.presence);
61
+ };
62
+
63
+ /** Mirror one speaker move onto the adapter, honoring the stage gate. */
64
+ const stageSpeaker = (
65
+ state: ConversationRuntimeState,
66
+ prev: string | null,
67
+ next: string | null,
68
+ ): void => {
69
+ const nextStaged = staged(state, next);
70
+ // A `none`-kind (or roster-unknown) speaker must never be the staged id
71
+ // (text-only contract) — the stage clears to `null` instead, exactly as
72
+ // when nobody holds the floor.
73
+ adapter.setActiveParticipant(nextStaged ? next : null);
74
+ if (prev !== null && staged(state, prev)) adapter.setSpeaking(prev, false);
75
+ if (next !== null && nextStaged) adapter.setSpeaking(next, true);
76
+ };
77
+
78
+ // Bind-time: mount the roster, then stage the initial speaker (if any).
79
+ const initial = runtime.getState();
80
+ for (const participant of initial.participants) adapter.mount(participant);
81
+ if (initial.activePersonaId !== null && staged(initial, initial.activePersonaId)) {
82
+ adapter.setActiveParticipant(initial.activePersonaId);
83
+ adapter.setSpeaking(initial.activePersonaId, true);
84
+ }
85
+
86
+ let lastActive = initial.activePersonaId;
87
+ const unsubscribe = runtime.subscribe((state) => {
88
+ if (state.activePersonaId !== lastActive) {
89
+ stageSpeaker(state, lastActive, state.activePersonaId);
90
+ lastActive = state.activePersonaId;
91
+ }
92
+ });
93
+
94
+ let disposed = false;
95
+ return {
96
+ applyViseme(personaId: string, viseme: VisemeSymbol): void {
97
+ if (disposed) return;
98
+ if (staged(runtime.getState(), personaId)) adapter.applyViseme(personaId, viseme);
99
+ },
100
+ dispose(): void {
101
+ if (disposed) return;
102
+ disposed = true;
103
+ unsubscribe();
104
+ for (const participant of runtime.getState().participants) {
105
+ adapter.unmount(participant.personaId);
106
+ }
107
+ },
108
+ };
109
+ }
@@ -0,0 +1,83 @@
1
+ /**
2
+ * Framework-agnostic presence-renderer registry (R2.1).
3
+ *
4
+ * Mirrors the named-registry discipline of the adapter registry
5
+ * (`adapters/registry.ts` — additive `register`, fail-loud on duplicate) and
6
+ * the `reactor/promptAddonRegistry.ts` precedent: it carries renderer FACTORIES
7
+ * keyed by `PresenceKind` and never touches the DOM itself. React (R2.2)
8
+ * registers a 2D-face factory; a game engine (R7) registers a 3D one; the core
9
+ * stays engine-free.
10
+ *
11
+ * A factory yields an opaque {@link PresenceHandle} (`mount`/`update`/`destroy`)
12
+ * so the caller drives the lifecycle without the registry knowing what the
13
+ * handle is. The registry is the single seam between the headless conversation
14
+ * state and whatever paints a face.
15
+ */
16
+
17
+ import { PresenceKind } from './participant';
18
+
19
+ /**
20
+ * Opaque per-mount handle a renderer factory returns. The conversation panel
21
+ * calls `mount` to attach into a host element, `update` on each presence-state
22
+ * change, and `destroy` on teardown. `unknown` payloads keep the core agnostic
23
+ * to the engine's host/state types — each renderer narrows them.
24
+ */
25
+ export interface PresenceHandle {
26
+ mount(host: unknown): void;
27
+ update(state: unknown): void;
28
+ destroy(): void;
29
+ }
30
+
31
+ /** A renderer factory. Called once per presence mount to produce a handle. */
32
+ export type PresenceRendererFactory = () => PresenceHandle;
33
+
34
+ /**
35
+ * The `PRESENCE_NONE` no-op handle. Returned for any unregistered kind so the
36
+ * 3D-avatar stub (and any not-yet-bound kind) fails SOFT — the caller can drive
37
+ * the lifecycle without a null check and nothing paints. Stateless, so a single
38
+ * shared instance is safe.
39
+ */
40
+ // Frozen: the no-op handle is shared by every unregistered kind, so freeze it
41
+ // against accidental mutation by a caller that mistakes it for a live renderer.
42
+ const NOOP_HANDLE: PresenceHandle = Object.freeze({
43
+ mount() {},
44
+ update() {},
45
+ destroy() {},
46
+ });
47
+
48
+ const NOOP_FACTORY: PresenceRendererFactory = () => NOOP_HANDLE;
49
+
50
+ export class PresenceRendererRegistry {
51
+ private readonly factories = new Map<PresenceKind, PresenceRendererFactory>();
52
+
53
+ /**
54
+ * Register a renderer factory for a presence kind. Additive — THROWS on a
55
+ * duplicate kind (fail-loud), matching the adapter registry's no-silent-
56
+ * overwrite contract. A renderer binding is a one-time app-init step, so a
57
+ * second registration is a wiring bug, not a runtime condition.
58
+ */
59
+ register(kind: PresenceKind, factory: PresenceRendererFactory): void {
60
+ if (this.factories.has(kind)) {
61
+ throw new Error(
62
+ `PresenceRendererRegistry: duplicate registration for presence kind "${kind}" — ` +
63
+ 'registration is additive and must not silently overwrite an existing renderer.',
64
+ );
65
+ }
66
+ this.factories.set(kind, factory);
67
+ }
68
+
69
+ /**
70
+ * Resolve a renderer factory for a kind. Returns the registered factory, or
71
+ * the `PRESENCE_NONE` no-op factory when the kind is unregistered (fail-soft
72
+ * — this is what lets the reserved `PRESENCE_AVATAR_3D` kind render nothing
73
+ * instead of throwing until R7 binds a real 3D renderer).
74
+ */
75
+ resolve(kind: PresenceKind): PresenceRendererFactory {
76
+ return this.factories.get(kind) ?? NOOP_FACTORY;
77
+ }
78
+
79
+ /** True iff a factory is registered for `kind` (the no-op fallback aside). */
80
+ has(kind: PresenceKind): boolean {
81
+ return this.factories.has(kind);
82
+ }
83
+ }
@@ -0,0 +1,111 @@
1
+ /**
2
+ * Party / roster helpers (R7.1), lifted VERBATIM (logic-preserving) from
3
+ * `web/app/chat-ws/adventureMode.ts` (M9 Story Engine Phase 8b Component F +
4
+ * M10 Phase 9b) — they were always I/O-free and misplaced in `web/`.
5
+ *
6
+ * Single source of truth for the Dungeon-Master tool names that MUTATE the
7
+ * server-authoritative `AdventureState` (`shared/tool_schemas.py`'s
8
+ * `_ADVENTURE_TOOL_SCHEMAS`). When the chat stream reports a `tool_result` for
9
+ * one of these, the host re-fetches `getAdventure(...)` to mirror the new
10
+ * state. `_ADVENTURE_TOOL_SCHEMAS` defines 7 DM tools; this is the 4 that
11
+ * mutate. The 3 read-only DM tools (`describe_current_scene`, `get_flag`,
12
+ * `get_party_status`) and ordinary chat tools must NOT be in this set, so they
13
+ * never trigger a re-fetch and an inactive adventure stays land-dark.
14
+ */
15
+
16
+ /**
17
+ * The four DM tools that mutate `AdventureState`. Mirrors the Python
18
+ * `_ADVENTURE_TOOL_SCHEMAS` names in `shared/tool_schemas.py`. `readonly` so the
19
+ * set can't be mutated by a caller. After R7.2 this is the ONLY copy — the
20
+ * `web/` `adventureMode.ts` re-exports it from here.
21
+ */
22
+ export const ADVENTURE_MUTATION_TOOLS = [
23
+ 'advance_story',
24
+ 'set_flag',
25
+ 'clear_flag',
26
+ 'update_inventory',
27
+ ] as const;
28
+
29
+ export type AdventureMutationTool = (typeof ADVENTURE_MUTATION_TOOLS)[number];
30
+
31
+ const ADVENTURE_MUTATION_TOOL_SET: ReadonlySet<string> = new Set(
32
+ ADVENTURE_MUTATION_TOOLS,
33
+ );
34
+
35
+ /**
36
+ * True when `tool` is one of the DM tools that mutate adventure state, so the
37
+ * host should re-fetch. Tolerates `undefined` (a `tool_result` frame may
38
+ * omit `tool`) and any non-mutation tool by returning false — the load-bearing
39
+ * land-dark guarantee is that this is the ONLY gate on a rail re-fetch.
40
+ */
41
+ export function isAdventureMutationTool(
42
+ tool: string | undefined,
43
+ ): tool is AdventureMutationTool {
44
+ return tool !== undefined && ADVENTURE_MUTATION_TOOL_SET.has(tool);
45
+ }
46
+
47
+ /**
48
+ * The single land-dark gate for re-fetching adventure state after a
49
+ * `tool_result` frame: refresh ONLY when an adventure is active AND a DM
50
+ * mutation tool ran. The `/chat-ws` message handler and
51
+ * `ConversationRuntime.applyFrame` call exactly this — so it is the one place
52
+ * that decides whether adventure mode does anything, and asserting it here
53
+ * proves the land-dark contract (no adventureSessionId ⇒ never true ⇒ no new
54
+ * network call, for ANY tool).
55
+ */
56
+ export function shouldRefreshAdventureRail(
57
+ adventureSessionId: string | undefined,
58
+ tool: string | undefined,
59
+ ): boolean {
60
+ return Boolean(adventureSessionId) && isAdventureMutationTool(tool);
61
+ }
62
+
63
+ /**
64
+ * Pure candidate filter for party-member pickers (M10 Story Engine Phase 9b),
65
+ * extracted — like {@link shouldRefreshAdventureRail} — so the rule is
66
+ * unit-testable without a DOM render of the modal or the API client.
67
+ *
68
+ * A persona is a valid party candidate when it is:
69
+ * 1. NOT a Dungeon Master (`is_dungeon_master !== true`),
70
+ * 2. `status === 'approved'`,
71
+ * 3. bound to a character entity (`entity_id` non-null/non-empty),
72
+ * 4. bound to a character that exists in THIS story (its `entity_id` is in
73
+ * `storyCharacterEntityIds`), and
74
+ * 5. NOT already in the party / the DM (`persona_id` ∉ `excludePersonaIds`).
75
+ *
76
+ * Rule (4) is relaxed when `storyCharacterEntityIds` is `null` — the caller
77
+ * passes `null` only when `listVideoCharacters` was unavailable or errored, so
78
+ * the picker degrades to the looser "any character-bound persona" set rather
79
+ * than offering nothing (the caller logs a console warning). The character set
80
+ * being empty (not null) means the story genuinely has no characters ⇒ no
81
+ * candidates, which is correct.
82
+ *
83
+ * Typed loosely on the persona shape so this module takes no dependency on the
84
+ * full `PersonaConfig`. Pure: no side effects.
85
+ */
86
+ export interface PartyCandidatePersona {
87
+ persona_id: string;
88
+ status: 'pending' | 'approved';
89
+ entity_id?: string | null;
90
+ is_dungeon_master?: boolean;
91
+ }
92
+
93
+ export function filterPartyCandidates<T extends PartyCandidatePersona>(
94
+ personas: readonly T[],
95
+ excludePersonaIds: readonly string[],
96
+ /** Character entity ids in this story, or `null` to relax the story-binding check. */
97
+ storyCharacterEntityIds: ReadonlySet<string> | null,
98
+ ): T[] {
99
+ const excluded = new Set(excludePersonaIds);
100
+ return personas.filter((p) => {
101
+ if (p.is_dungeon_master === true) return false;
102
+ if (p.status !== 'approved') return false;
103
+ if (!p.entity_id) return false;
104
+ if (excluded.has(p.persona_id)) return false;
105
+ // Story-binding check, relaxed (fallback) when the character set is null.
106
+ if (storyCharacterEntityIds !== null && !storyCharacterEntityIds.has(p.entity_id)) {
107
+ return false;
108
+ }
109
+ return true;
110
+ });
111
+ }
@@ -0,0 +1,98 @@
1
+ /**
2
+ * `castToRoster` (R7.4) — the single DRY projection turning R5's one-call
3
+ * cast-with-persona response (`getCast` → `CastEntry[]`) plus the active
4
+ * `AdventureState` (DM persona + `partyPersonaIds`) into the
5
+ * {@link RosterParticipant}[] the framework-agnostic `ConversationRuntime` and
6
+ * `presenceBus` consume.
7
+ *
8
+ * WHY this exists: pre-R7.4 the Studio surface derived its party roster by a
9
+ * CLIENT-SIDE `entity_id ∈ storyCharacterEntityIds` join across two stores
10
+ * (`listVideoCharacters` + `listPersonas`), which depends on
11
+ * `generate_entity_id` vs `generate_document_entity_id` string matching
12
+ * (`shared/neo4j_queries.py`). R5 moved that join SERVER-SIDE
13
+ * (`GET /api/v1/tools/videos/{videoId}/cast`, the PORTRAYS edge +
14
+ * authoritative `PersonaConfig.entity_id`). This function is the one place that
15
+ * reshapes that authoritative projection into the renderer-facing roster — so
16
+ * the roster never re-derives the binding client-side again.
17
+ *
18
+ * Ordering is server-party-authoritative: the DM seat leads (it always holds
19
+ * the floor first — the runtime's initial `activePersonaId`), then each party
20
+ * member in `partyPersonaIds` order. Every server-party member gets a seat even
21
+ * when absent from the cast projection (a removed/foreign id), so the runtime
22
+ * can always stage a `turn_changed` speaker; the display name falls back to the
23
+ * persona id in that defensive case.
24
+ *
25
+ * Pure: no I/O, no DOM, no React — framework-agnostic, like every other
26
+ * `conversation/` module. The presence kind is `PRESENCE_FACE_2D` for every
27
+ * seat (the current renderer); a future host can re-map per participant.
28
+ */
29
+
30
+ import { PresenceKind } from './participant';
31
+ import type { RosterParticipant } from './types';
32
+ import type { CastEntry } from '../api';
33
+
34
+ /** The DM persona's identity fields the roster needs (a thin slice of the
35
+ * bound `PersonaConfig`). */
36
+ export interface RosterDmPersona {
37
+ personaId: string;
38
+ /** Display name for the DM's transcript pill / roster chip. */
39
+ name: string;
40
+ }
41
+
42
+ export interface CastToRosterInput {
43
+ /** R5's one-call cast-with-persona projection (`getCast(...).cast`). */
44
+ cast: readonly CastEntry[];
45
+ /** The Dungeon-Master persona running this adventure. */
46
+ dmPersona: RosterDmPersona;
47
+ /** The server-authoritative party member persona ids, in party order
48
+ * (`AdventureState.partyPersonaIds`). */
49
+ partyPersonaIds: readonly string[];
50
+ }
51
+
52
+ /**
53
+ * Project the cast + active adventure into the renderer-facing roster (DM seat
54
+ * first, then party members in party order, de-duplicated, DM never doubled).
55
+ */
56
+ export function castToRoster(input: CastToRosterInput): RosterParticipant[] {
57
+ const { cast, dmPersona, partyPersonaIds } = input;
58
+
59
+ // Index the cast's bound personas by persona id so a party member resolves its
60
+ // display name (the persona's, not the character's) + bound entity id in O(1).
61
+ const castByPersonaId = new Map<string, CastEntry>();
62
+ for (const entry of cast) {
63
+ if (entry.persona) castByPersonaId.set(entry.persona.personaId, entry);
64
+ }
65
+
66
+ const roster: RosterParticipant[] = [
67
+ {
68
+ personaId: dmPersona.personaId,
69
+ isDm: true,
70
+ displayName: dmPersona.name,
71
+ presence: PresenceKind.PRESENCE_FACE_2D,
72
+ },
73
+ ];
74
+
75
+ // The DM is already seated; never seat it twice, and de-duplicate repeated
76
+ // party ids (first occurrence wins — mirrors the server party set semantics).
77
+ const seen = new Set<string>([dmPersona.personaId]);
78
+ for (const personaId of partyPersonaIds) {
79
+ if (seen.has(personaId)) continue;
80
+ seen.add(personaId);
81
+
82
+ const entry = castByPersonaId.get(personaId);
83
+ roster.push({
84
+ personaId,
85
+ isDm: false,
86
+ // The persona's display name wins (the transcript pill the user sees);
87
+ // fall back to the character name, then the raw id (defensive — a removed
88
+ // or foreign party member still needs a seat so the runtime can stage it).
89
+ displayName: entry?.persona?.name ?? entry?.character.name ?? personaId,
90
+ ...(entry?.character.entityId
91
+ ? { entityId: entry.character.entityId }
92
+ : {}),
93
+ presence: PresenceKind.PRESENCE_FACE_2D,
94
+ });
95
+ }
96
+
97
+ return roster;
98
+ }
@@ -0,0 +1,96 @@
1
+ /**
2
+ * Advisory client-side routing helpers (R7.1), lifted VERBATIM
3
+ * (logic-preserving) from `web/app/chat-ws/adventureMode.ts` — they were
4
+ * always I/O-free and misplaced in `web/`.
5
+ *
6
+ * **ADVISORY ONLY.** The server `agents/orchestrator/persona_router.py`
7
+ * `resolve_addressed_persona` is the AUTHORITATIVE router: it alone decides
8
+ * which persona takes a turn. The client NEVER routes a turn — these helpers
9
+ * only read the server's `turn_changed` frames and per-frame `personaId`
10
+ * stamps so a renderer can display who is speaking. Any client-side
11
+ * address-resolution mirror must stay presentation-only and must never be
12
+ * promoted to a routing decision.
13
+ */
14
+
15
+ /**
16
+ * The additive multi-persona fields the M10 Story Engine Phase 9a server stamps
17
+ * on chat frames. This is the single, narrowly-typed structural seam for
18
+ * reading `type: 'turn_changed'` and the per-frame `personaId` off an incoming
19
+ * message without an unsafe inline cast at each call site — every member of
20
+ * the precise `ChatWsEvent` union (websocket.ts) is assignable to it. Both
21
+ * fields are optional: a non-adventure frame carries neither, so every reader
22
+ * degrades to the land-dark path.
23
+ */
24
+ export interface MultiPersonaFrameFields {
25
+ type: string;
26
+ personaId?: string;
27
+ }
28
+
29
+ /**
30
+ * Pull the active speaking persona id off a `turn_changed` event — the M10 9a
31
+ * scene orchestrator's signal that the turn passed to a different persona.
32
+ * Funnelling the read through one helper keeps the contract in one place
33
+ * (the `/chat-ws` handler and `ConversationRuntime.applyFrame` both route
34
+ * through it).
35
+ *
36
+ * LAND-DARK: returns `null` unless the frame is genuinely a `turn_changed`
37
+ * carrying a non-empty `personaId` AND an adventure is active
38
+ * (`adventureSessionId` set). `turn_changed` is only ever emitted in a
39
+ * non-empty-party adventure, but gating on the session id too means an
40
+ * ordinary-chat frame can never move the speaker, even defensively.
41
+ */
42
+ export function turnChangedSpeakerId(
43
+ message: MultiPersonaFrameFields,
44
+ adventureSessionId: string | undefined,
45
+ ): string | null {
46
+ if (!adventureSessionId) return null;
47
+ if (message.type !== 'turn_changed') return null;
48
+ return message.personaId && message.personaId.length > 0 ? message.personaId : null;
49
+ }
50
+
51
+ /**
52
+ * Resolve the per-message persona "pill" for an assistant transcript bubble
53
+ * (M10 Phase 9b). Given the `personaId` captured off the assistant's chat
54
+ * frames and the backend persona list, returns the id + display name to render,
55
+ * or `null` when there's nothing to show. Pure so the transcript pill is
56
+ * unit-testable without a DOM render.
57
+ *
58
+ * LAND-DARK: returns `null` for a `personaId` of `undefined` (every
59
+ * non-adventure assistant message — those frames never carry one), so a normal
60
+ * chat bubble renders byte-identically. When the id is present but unresolvable
61
+ * in `personas` (e.g. a since-deleted persona), falls back to the raw id as the
62
+ * name so the speaker is still attributed rather than silently dropped.
63
+ */
64
+ export interface PillPersona {
65
+ persona_id: string;
66
+ name: string;
67
+ }
68
+
69
+ export function resolvePersonaPill(
70
+ personaId: string | undefined,
71
+ personas: readonly PillPersona[],
72
+ ): { personaId: string; name: string } | null {
73
+ if (!personaId) return null;
74
+ const match = personas.find((p) => p.persona_id === personaId);
75
+ return { personaId, name: match?.name ?? personaId };
76
+ }
77
+
78
+ /**
79
+ * Advisory `partyPersonaIds` for the `send(...)` / `buildHelloPayload(...)`
80
+ * options when in a multi-persona adventure (M10 Phase 9b). The server's
81
+ * `AdventureState.party_persona_ids` is authoritative for scene routing — this
82
+ * is forward-compat/advisory only.
83
+ *
84
+ * LAND-DARK: returns `undefined` when there's no active adventure session OR the
85
+ * party is empty/absent, so both option builders drop the key entirely (they
86
+ * already omit `undefined`) and the wire stays byte-identical for ordinary chat
87
+ * and M9 single-DM adventures.
88
+ */
89
+ export function advisoryPartyPersonaIds(
90
+ adventureSessionId: string | undefined,
91
+ partyPersonaIds: readonly string[] | undefined,
92
+ ): string[] | undefined {
93
+ if (!adventureSessionId) return undefined;
94
+ if (!partyPersonaIds || partyPersonaIds.length === 0) return undefined;
95
+ return [...partyPersonaIds];
96
+ }