@voqalize/avatar 0.2.2 → 0.4.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 (265) hide show
  1. package/LICENSE +21 -661
  2. package/LICENSE-CC-BY-4.0 +396 -0
  3. package/README.md +191 -662
  4. package/assets/README.md +48 -0
  5. package/assets/tanya.glb +0 -0
  6. package/assets/tara.glb +0 -0
  7. package/assets/tushar.glb +0 -0
  8. package/client/Avatar.tsx +57 -0
  9. package/client/AvatarClient.ts +818 -0
  10. package/client/arjun.ts +26 -0
  11. package/client/createAvatar.ts +177 -0
  12. package/client/createCanvasAvatar.ts +72 -0
  13. package/client/index.ts +44 -0
  14. package/client/internal.ts +108 -0
  15. package/client/interviewer-female.ts +4 -0
  16. package/client/interviewer-male.ts +4 -0
  17. package/client/ishita.ts +26 -0
  18. package/client/kabir.ts +26 -0
  19. package/client/meera.ts +26 -0
  20. package/client/naina.ts +26 -0
  21. package/client/playout.ts +95 -0
  22. package/client/professional-female-a.ts +4 -0
  23. package/client/professional-female-b.ts +4 -0
  24. package/client/professional-male-a.ts +4 -0
  25. package/client/professional-male-b.ts +4 -0
  26. package/client/react.ts +13 -0
  27. package/client/supports.ts +28 -0
  28. package/client/three/assets.ts +24 -0
  29. package/client/three/budgets.ts +27 -0
  30. package/client/three/holds.ts +64 -0
  31. package/client/three/internal.ts +54 -0
  32. package/client/three/motion-limits.json +116 -0
  33. package/client/three/sequences.ts +281 -0
  34. package/client/three/tanya.ts +69 -0
  35. package/client/three/tara-rig.ts +1562 -0
  36. package/client/three/tara.ts +76 -0
  37. package/client/three/tushar.ts +65 -0
  38. package/client/types.ts +235 -0
  39. package/client/useAvatar.ts +74 -0
  40. package/client/vikram.ts +26 -0
  41. package/dist/Avatar.d.ts +44 -0
  42. package/dist/Avatar.d.ts.map +1 -0
  43. package/{client/dist → dist}/Avatar.js +2 -2
  44. package/dist/Avatar.js.map +1 -0
  45. package/dist/AvatarClient.d.ts +274 -0
  46. package/dist/AvatarClient.d.ts.map +1 -0
  47. package/dist/AvatarClient.js +712 -0
  48. package/dist/AvatarClient.js.map +1 -0
  49. package/dist/arjun.d.ts +7 -0
  50. package/dist/arjun.d.ts.map +1 -0
  51. package/dist/arjun.js +20 -0
  52. package/dist/arjun.js.map +1 -0
  53. package/dist/createAvatar.d.ts +135 -0
  54. package/dist/createAvatar.d.ts.map +1 -0
  55. package/dist/createAvatar.js +75 -0
  56. package/dist/createAvatar.js.map +1 -0
  57. package/dist/createCanvasAvatar.d.ts +22 -0
  58. package/dist/createCanvasAvatar.d.ts.map +1 -0
  59. package/dist/createCanvasAvatar.js +47 -0
  60. package/dist/createCanvasAvatar.js.map +1 -0
  61. package/dist/index.d.ts +34 -0
  62. package/dist/index.d.ts.map +1 -0
  63. package/dist/index.js +33 -0
  64. package/dist/index.js.map +1 -0
  65. package/dist/internal.d.ts +34 -0
  66. package/dist/internal.d.ts.map +1 -0
  67. package/dist/internal.js +41 -0
  68. package/dist/internal.js.map +1 -0
  69. package/dist/interviewer-female.d.ts +4 -0
  70. package/dist/interviewer-female.d.ts.map +1 -0
  71. package/dist/interviewer-female.js +3 -0
  72. package/dist/interviewer-female.js.map +1 -0
  73. package/dist/interviewer-male.d.ts +4 -0
  74. package/dist/interviewer-male.d.ts.map +1 -0
  75. package/dist/interviewer-male.js +3 -0
  76. package/dist/interviewer-male.js.map +1 -0
  77. package/dist/ishita.d.ts +7 -0
  78. package/dist/ishita.d.ts.map +1 -0
  79. package/dist/ishita.js +20 -0
  80. package/dist/ishita.js.map +1 -0
  81. package/dist/kabir.d.ts +7 -0
  82. package/dist/kabir.d.ts.map +1 -0
  83. package/dist/kabir.js +20 -0
  84. package/dist/kabir.js.map +1 -0
  85. package/dist/meera.d.ts +7 -0
  86. package/dist/meera.d.ts.map +1 -0
  87. package/dist/meera.js +20 -0
  88. package/dist/meera.js.map +1 -0
  89. package/dist/naina.d.ts +7 -0
  90. package/dist/naina.d.ts.map +1 -0
  91. package/dist/naina.js +20 -0
  92. package/dist/naina.js.map +1 -0
  93. package/dist/playout.d.ts +42 -0
  94. package/dist/playout.d.ts.map +1 -0
  95. package/dist/playout.js +85 -0
  96. package/dist/playout.js.map +1 -0
  97. package/dist/professional-female-a.d.ts +4 -0
  98. package/dist/professional-female-a.d.ts.map +1 -0
  99. package/dist/professional-female-a.js +3 -0
  100. package/dist/professional-female-a.js.map +1 -0
  101. package/dist/professional-female-b.d.ts +4 -0
  102. package/dist/professional-female-b.d.ts.map +1 -0
  103. package/dist/professional-female-b.js +3 -0
  104. package/dist/professional-female-b.js.map +1 -0
  105. package/dist/professional-male-a.d.ts +4 -0
  106. package/dist/professional-male-a.d.ts.map +1 -0
  107. package/dist/professional-male-a.js +3 -0
  108. package/dist/professional-male-a.js.map +1 -0
  109. package/dist/professional-male-b.d.ts +4 -0
  110. package/dist/professional-male-b.d.ts.map +1 -0
  111. package/dist/professional-male-b.js +3 -0
  112. package/dist/professional-male-b.js.map +1 -0
  113. package/dist/react.d.ts +13 -0
  114. package/dist/react.d.ts.map +1 -0
  115. package/dist/react.js +13 -0
  116. package/dist/react.js.map +1 -0
  117. package/dist/supports.d.ts +20 -0
  118. package/dist/supports.d.ts.map +1 -0
  119. package/dist/supports.js +26 -0
  120. package/dist/supports.js.map +1 -0
  121. package/dist/three/assets.d.ts +24 -0
  122. package/dist/three/assets.d.ts.map +1 -0
  123. package/dist/three/assets.js +22 -0
  124. package/dist/three/assets.js.map +1 -0
  125. package/dist/three/budgets.d.ts +17 -0
  126. package/dist/three/budgets.d.ts.map +1 -0
  127. package/dist/three/budgets.js +21 -0
  128. package/dist/three/budgets.js.map +1 -0
  129. package/dist/three/holds.d.ts +33 -0
  130. package/dist/three/holds.d.ts.map +1 -0
  131. package/dist/three/holds.js +56 -0
  132. package/dist/three/holds.js.map +1 -0
  133. package/dist/three/internal.d.ts +52 -0
  134. package/dist/three/internal.d.ts.map +1 -0
  135. package/dist/three/internal.js +49 -0
  136. package/dist/three/internal.js.map +1 -0
  137. package/dist/three/motion-limits.json +116 -0
  138. package/dist/three/sequences.d.ts +71 -0
  139. package/dist/three/sequences.d.ts.map +1 -0
  140. package/dist/three/sequences.js +262 -0
  141. package/dist/three/sequences.js.map +1 -0
  142. package/dist/three/tanya.d.ts +35 -0
  143. package/dist/three/tanya.d.ts.map +1 -0
  144. package/dist/three/tanya.js +51 -0
  145. package/dist/three/tanya.js.map +1 -0
  146. package/dist/three/tara-rig.d.ts +403 -0
  147. package/dist/three/tara-rig.d.ts.map +1 -0
  148. package/dist/three/tara-rig.js +1500 -0
  149. package/dist/three/tara-rig.js.map +1 -0
  150. package/dist/three/tara.d.ts +35 -0
  151. package/dist/three/tara.d.ts.map +1 -0
  152. package/dist/three/tara.js +58 -0
  153. package/dist/three/tara.js.map +1 -0
  154. package/dist/three/tushar.d.ts +31 -0
  155. package/dist/three/tushar.d.ts.map +1 -0
  156. package/dist/three/tushar.js +47 -0
  157. package/dist/three/tushar.js.map +1 -0
  158. package/dist/types.d.ts +149 -0
  159. package/dist/types.d.ts.map +1 -0
  160. package/dist/types.js +140 -0
  161. package/dist/types.js.map +1 -0
  162. package/dist/useAvatar.d.ts +39 -0
  163. package/dist/useAvatar.d.ts.map +1 -0
  164. package/dist/useAvatar.js +35 -0
  165. package/dist/useAvatar.js.map +1 -0
  166. package/dist/vikram.d.ts +7 -0
  167. package/dist/vikram.d.ts.map +1 -0
  168. package/dist/vikram.js +20 -0
  169. package/dist/vikram.js.map +1 -0
  170. package/package.json +110 -25
  171. package/src/avatar.d.ts +218 -120
  172. package/src/avatar.js +950 -213
  173. package/src/behavior.d.ts +42 -0
  174. package/src/behavior.js +114 -0
  175. package/src/camera.js +29 -0
  176. package/src/canvas/author/parts/eye.mjs +722 -0
  177. package/src/canvas/author/parts/hand.mjs +1156 -0
  178. package/src/canvas/author/parts/mouth.mjs +741 -0
  179. package/src/canvas/author/parts/nose.mjs +100 -0
  180. package/src/canvas/author/parts/skin-detail.mjs +67 -0
  181. package/src/canvas/author/path.mjs +283 -0
  182. package/src/canvas/author/rig.mjs +405 -0
  183. package/src/canvas/avatars/round/face.d.mts +3 -0
  184. package/src/canvas/avatars/round/face.mjs +1307 -0
  185. package/src/canvas/create-rig.d.ts +15 -0
  186. package/src/canvas/create-rig.js +100 -0
  187. package/src/canvas/data/img/professional-female-a-hair-back.webp +0 -0
  188. package/src/canvas/data/img/professional-female-a-hair-front.webp +0 -0
  189. package/src/canvas/data/img/professional-female-a-top-body.webp +0 -0
  190. package/src/canvas/data/img/professional-female-b-hair-back.webp +0 -0
  191. package/src/canvas/data/img/professional-female-b-hair-front.webp +0 -0
  192. package/src/canvas/data/img/professional-female-b-top-body.webp +0 -0
  193. package/src/canvas/data/img/professional-male-a-hair-back.webp +0 -0
  194. package/src/canvas/data/img/professional-male-a-hair-front.webp +0 -0
  195. package/src/canvas/data/img/professional-male-a-top-body.webp +0 -0
  196. package/src/canvas/data/img/professional-male-b-hair-back.webp +0 -0
  197. package/src/canvas/data/img/professional-male-b-hair-front.webp +0 -0
  198. package/src/canvas/data/img/professional-male-b-top-body.webp +0 -0
  199. package/src/canvas/data/img/round-m3-hair-back.webp +0 -0
  200. package/src/canvas/data/img/round-m3-hair-front.webp +0 -0
  201. package/src/canvas/data/img/round-m3-top-body.webp +0 -0
  202. package/src/canvas/data/img/round-w1-hair-back.webp +0 -0
  203. package/src/canvas/data/img/round-w1-hair-front.webp +0 -0
  204. package/src/canvas/data/img/round-w1-top-body.webp +0 -0
  205. package/src/canvas/data/interviewer-female.rig.json +1 -0
  206. package/src/canvas/data/interviewer-male.rig.json +1 -0
  207. package/src/canvas/data/professional-female-a.rig.json +1 -0
  208. package/src/canvas/data/professional-female-b.rig.json +1 -0
  209. package/src/canvas/data/professional-male-a.rig.json +1 -0
  210. package/src/canvas/data/professional-male-b.rig.json +1 -0
  211. package/src/canvas/src/live.js +508 -0
  212. package/src/canvas/src/render2d.js +218 -0
  213. package/src/canvas/src/rig.js +297 -0
  214. package/src/canvas/src/vocab.js +96 -0
  215. package/src/clips.js +18 -7
  216. package/src/conformance.js +119 -0
  217. package/src/emotions.js +8 -5
  218. package/src/face-core.js +27 -1
  219. package/src/face-myna.d.ts +7 -0
  220. package/src/face-myna.js +192 -131
  221. package/src/face-peep-control-plane.js +167 -0
  222. package/src/face-peep.d.ts +7 -0
  223. package/src/face-peep.js +274 -116
  224. package/src/face-wren.d.ts +7 -0
  225. package/src/face-wren.js +17 -19
  226. package/src/faces.d.ts +12 -0
  227. package/src/faces.js +53 -0
  228. package/src/gaze.js +434 -58
  229. package/src/hand.js +120 -91
  230. package/src/head.js +134 -0
  231. package/src/idle.js +227 -119
  232. package/src/interjections.js +200 -31
  233. package/src/params.js +8 -4
  234. package/src/perform.js +7 -9
  235. package/src/prosody.js +647 -0
  236. package/src/rig.d.ts +24 -0
  237. package/src/rig.js +32 -0
  238. package/src/speech-timing.js +23 -0
  239. package/src/visemes.js +110 -24
  240. package/client/dist/Avatar.d.ts +0 -27
  241. package/client/dist/Avatar.d.ts.map +0 -1
  242. package/client/dist/Avatar.js.map +0 -1
  243. package/client/dist/AvatarClient.d.ts +0 -139
  244. package/client/dist/AvatarClient.d.ts.map +0 -1
  245. package/client/dist/AvatarClient.js +0 -223
  246. package/client/dist/AvatarClient.js.map +0 -1
  247. package/client/dist/index.d.ts +0 -22
  248. package/client/dist/index.d.ts.map +0 -1
  249. package/client/dist/index.js +0 -22
  250. package/client/dist/index.js.map +0 -1
  251. package/client/dist/types.d.ts +0 -86
  252. package/client/dist/types.d.ts.map +0 -1
  253. package/client/dist/types.js +0 -31
  254. package/client/dist/types.js.map +0 -1
  255. package/client/dist/useAvatar.d.ts +0 -42
  256. package/client/dist/useAvatar.d.ts.map +0 -1
  257. package/client/dist/useAvatar.js +0 -51
  258. package/client/dist/useAvatar.js.map +0 -1
  259. package/client/src/Avatar.tsx +0 -33
  260. package/client/src/AvatarClient.ts +0 -270
  261. package/client/src/index.ts +0 -22
  262. package/client/src/types.ts +0 -104
  263. package/client/src/useAvatar.ts +0 -85
  264. package/docs/contract-avatar.md +0 -371
  265. package/docs/contract-protocol.md +0 -461
@@ -0,0 +1,818 @@
1
+ /**
2
+ * AvatarClient — the avatar's server-message dispatcher, turn clock, and cue
3
+ * splice, framework-free (no React; the hook and component wrap this).
4
+ *
5
+ * ## Turn clock anchoring
6
+ *
7
+ * Base Pipecat TTS gives each serialized TTS context an opaque `context_id`.
8
+ * The server uses it only to group and splice cue chunks. `botStartedSpeaking`
9
+ * has no context payload, so the browser FIFO-claims the next buffered context
10
+ * at that Pipecat output-lifecycle event. `botStoppedSpeaking` closes it. No
11
+ * avatar-specific speech marker exists.
12
+ *
13
+ * The event says *which* audio is starting, not *when* it is heard, and the
14
+ * turn clock is anchored to the sound itself (`playout.ts` has the
15
+ * measurements that forced it). `attach()` listens to the bot's audio track;
16
+ * at the event, the turn's zero is backdated to a sound that has already begun,
17
+ * or the mouth is held shut until one does. When the track cannot be heard —
18
+ * no `attach()`, no track, a suspended audio graph, or a sound that never
19
+ * arrives within `ONSET_WAIT_MS` — the event is the anchor, as it always was.
20
+ * Which one won is logged once per turn, at `info`, because a desync report is
21
+ * unanswerable without it.
22
+ *
23
+ * The clock then runs `VISUAL_LEAD_MS` ahead of the sound, since the mixer's
24
+ * smoothing makes every mouth shape late by about that much. It is pulled back
25
+ * by any output-device latency beyond what the display already matches (a
26
+ * Bluetooth headset). Within a turn, each resumption after a pause in the
27
+ * track is a second chance to hear where the sound really is — but a mouth
28
+ * opens before its sound, so a resumption heard within the track's usual
29
+ * anticipation of it agrees with the clock. Only a disagreement beyond that is
30
+ * slewed out, at no more than 10 % of clock rate, never jumped, because a
31
+ * mouth that skips is seen and one that runs briefly fast is not.
32
+ *
33
+ * `attach()` subscribes to the avatar server-message channel *and* Pipecat's
34
+ * standard lifecycle events. Server messages carry only what Pipecat cannot:
35
+ * correlated speech/cue timing and deliberate application instructions. The
36
+ * lifecycle events project the factual presence states locally. The server
37
+ * supplies only the three lower-priority states and deliberate,
38
+ * self-completing actions. This keeps the face tied to Pipecat's output truth
39
+ * even if a server state is delayed or stale.
40
+ *
41
+ * ## Cue splice
42
+ *
43
+ * The widget has two cue-track primitives: `speak({cues, clock})` (a full
44
+ * replace) and `pushCues(cues)` (a pure union that can only grow the track,
45
+ * never shrink it). Neither is "discard queued cues at or after `from_ms`,
46
+ * then append" on its own — `pushCues` has no way to drop a stale tail. So
47
+ * this client keeps the turn's canonical cue array itself (kept portion +
48
+ * every appended chunk, spliced on each `cues` message) and picks the cheapest
49
+ * widget call that stays correct:
50
+ *
51
+ * - if the splice's `from_ms` doesn't reach back into anything already
52
+ * queued — the common case past a turn's first sentence, since only the
53
+ * first sentence genuinely plays fast-leg cues — nothing needs discarding:
54
+ * `pushCues(newCues)` is the cheap, correct append.
55
+ * - if it does reach back (a real fast→accurate splice), `pushCues` cannot
56
+ * express the discard; we call `speak()` again with the full spliced
57
+ * canonical array on the turn's original clock. `speak()` is otherwise
58
+ * documented as also killing an in-flight spoken interjection and
59
+ * re-entering `SPEAKING` — both harmless mid-splice (an interjection
60
+ * should not be running while a server track owns the mouth; re-entering
61
+ * an unchanged state is a no-op past the profile/gaze reset the widget
62
+ * already does for a same-name `setState`).
63
+ *
64
+ * Cues commonly arrive **before** `botStartedSpeaking` — the fast leg starts
65
+ * the moment a sentence is handed to TTS, well before bot output begins.
66
+ * Chunks that arrive before the clock is anchored are spliced into the
67
+ * canonical array but not yet handed to the widget; `botStartedSpeaking` hands over
68
+ * whatever has accumulated as the turn's first `speak()` call. So "the first
69
+ * chunk of a turn starts speak()" means the first *widget* call, not
70
+ * necessarily the first *message*.
71
+ */
72
+
73
+ import type { PipecatClient, RTVIEvent } from "@pipecat-ai/client-js";
74
+ import { BehaviorController } from "../src/behavior.js";
75
+ import { createPlayoutProbe, type PlayoutProbe } from "./playout.js";
76
+ import {
77
+ isAvatarMessage,
78
+ parseAvatarCommand,
79
+ type AvatarCommand,
80
+ type AvatarCue,
81
+ type AvatarCuesCmd,
82
+ } from "./types.js";
83
+
84
+
85
+ interface Turn {
86
+ ctx: string;
87
+ /** The canonical, already-spliced cue track for this turn. */
88
+ cues: AvatarCue[];
89
+ /** Whether Pipecat output has anchored a clock and issued `speak()`. */
90
+ started: boolean;
91
+ clock: (() => number) | null;
92
+ /** Timeline zero on the `now()` clock; `null` while waiting to hear the
93
+ * audio begin, during which the clock reads before the first cue. */
94
+ t0: number | null;
95
+ /** Where a re-anchor has placed zero; `t0` slews toward it. */
96
+ target: number | null;
97
+ /** `now()` at the clock's last read, which bounds how far a slew may move. */
98
+ read: number;
99
+ /** How far the clock runs ahead of the sound, fixed for the turn. */
100
+ lead: number;
101
+ /** The last resumption (track ms) already listened for. */
102
+ checked: number;
103
+ }
104
+
105
+ /**
106
+ * Longest the mouth is held for audio `botStartedSpeaking` has announced but
107
+ * the track has not yet carried. The event has been measured leading the first
108
+ * sample by ~160 ms on a local stack; twice that is a stall, and a mouth that
109
+ * starts without its sound is better than one that waits indefinitely.
110
+ */
111
+ const ONSET_WAIT_MS = 350;
112
+ const ONSET_POLL_MS = 10;
113
+
114
+ /**
115
+ * How far the cue clock runs ahead of the sound. The mixer eases every mouth
116
+ * channel toward its target with a 42 ms time constant
117
+ * (`MOUTH_RESPONSE_TAU_S`), which delays a shape by about that much, and a
118
+ * frame is drawn on average half a frame after its time. Picture ahead of sound
119
+ * is the side people forgive (ITU-R BT.1359: sound leading is noticed at about
120
+ * 45 ms, picture leading at about 125 ms), so a small surplus is the safe error.
121
+ */
122
+ export const VISUAL_LEAD_MS = 50;
123
+ /** Output latency the display already matches: a compositor and a screen are
124
+ * late by about as much as a wired speaker, so only the excess counts. */
125
+ const DISPLAY_LATENCY_MS = 40;
126
+ /** A reported latency beyond this is a broken report, not a device. */
127
+ const MAX_OUTPUT_LATENCY_MS = 250;
128
+ /** A pause in the track at least this long is one the audio can be heard to
129
+ * resume after — shorter ones are usually not digital silence on the wire. */
130
+ const REANCHOR_GAP_MS = 250;
131
+ /** When to look, after the resumption is due, and for how long. The probe
132
+ * sees 170 ms back, so one look catches an early sound as well as a late one. */
133
+ const REANCHOR_LOOK_MS = 100;
134
+ const REANCHOR_WINDOW_MS = 150;
135
+ /**
136
+ * Where a resumption is heard, after the cue that marks it. The track opens
137
+ * the mouth before the sound leaves digital silence: by 30–41 ms at most of the
138
+ * demo corpus's silent resumptions (median 32, both voices) and by up to 105 at
139
+ * a few, and the browser hears the sound a few ms after it leaves the wire. A
140
+ * sound heard anywhere in that band is the clock being right. Taking
141
+ * it as the resumption itself set every later phrase of a turn that much late —
142
+ * the direction people notice — and a mouth left early by an underrun smaller
143
+ * than the band is the direction they forgive (see `VISUAL_LEAD_MS`).
144
+ */
145
+ const RESUME_HEARD_MS = 30;
146
+ const RESUME_HEARD_RANGE_MS = [0, 130] as const;
147
+ /** The most a re-anchor may speed or slow the clock, as a fraction of real time. */
148
+ const MAX_SLEW = 0.1;
149
+
150
+ /**
151
+ * The private renderer-side vocabulary the lifecycle driver actually uses.
152
+ *
153
+ * This stays narrower than `AvatarApi` on purpose. The latter is the SVG
154
+ * mixer's driving API; requiring a second renderer to impersonate every one
155
+ * of its inspection and authoring methods would turn that implementation
156
+ * detail into a renderer contract. The public seam remains `createAvatar`.
157
+ */
158
+ export interface AvatarDriver {
159
+ setState(name: string): unknown;
160
+ /**
161
+ * One motion by name — a core intent or one of this avatar's own. **A name
162
+ * it does not have is a no-op, not a throw**: the wire's action vocabulary is
163
+ * open, so a face that cannot do the thing is as expected as a newer server.
164
+ */
165
+ action(id: string): unknown;
166
+ speak(options: { cues: AvatarCue[]; clock: () => number }): unknown;
167
+ pushCues(cues: AvatarCue[]): unknown;
168
+ stopSpeaking(): unknown;
169
+ setUserSpeaking(speaking: boolean | null): unknown;
170
+ }
171
+
172
+ /**
173
+ * Internal. Not exported from the package — the public surface is
174
+ * `createAvatar({ mount, client })` and nothing else.
175
+ *
176
+ * There is deliberately no `accept` predicate here any more. Avatar commands
177
+ * travel in one envelope, `{type:"avatar"}`, in both directions and from every
178
+ * source: a `AvatarProcessor` in the pipeline and a brain driving the face
179
+ * out of band emit the same shape. A per-deployment predicate meant the
180
+ * library could not state what an avatar message *is*, which is the one thing
181
+ * a wire format has to be able to say.
182
+ */
183
+ export interface AvatarClientOptions {
184
+ /** A dispatch threw (e.g. an unknown state or interjection id, which the
185
+ * widget throws on). Defaults to `console.warn`. */
186
+ onError?: (err: unknown, msg: AvatarCommand) => void;
187
+ /** Override for tests. Defaults to `performance.now`. */
188
+ now?: () => number;
189
+ /** Override for tests. Defaults to listening to the bot's audio track, once
190
+ * `attach()` has found one. */
191
+ playoutProbe?: PlayoutProbe;
192
+ /** Quiet time in listening before the client-owned idle loop begins. */
193
+ idleDelayMs?: number;
194
+ /** Timer seams keep lifecycle behavior deterministic in tests. */
195
+ setTimeout?: typeof setTimeout;
196
+ clearTimeout?: typeof clearTimeout;
197
+ /**
198
+ * Internal, for Studio's inspector — the resolved projection, so a developer
199
+ * tool can show what the lifecycle decided. It is *not* on the public
200
+ * surface and must not become one: a presence callback is a contract, and
201
+ * publishing it would oblige every avatar implementation to emit these seven
202
+ * states with this precedence, which is exactly the second public contract
203
+ * the design exists to avoid.
204
+ */
205
+ onPresenceChange?: (state: AvatarPresenceState) => void;
206
+ }
207
+
208
+ /**
209
+ * The one `RTVIEvent` member `attach()` subscribes to, spelled as its value.
210
+ *
211
+ * Written out rather than imported because that enum was this module's *only*
212
+ * runtime reference to `@pipecat-ai/client-js`, and one runtime reference makes
213
+ * the whole `/pipecat` subpath fail to load without the peer installed — even
214
+ * for a host that drives `dispatch()` from its own transport and never calls
215
+ * `attach()`. The peer is declared optional; this is what makes that true
216
+ * rather than aspirational.
217
+ *
218
+ * String enums are nominal in TypeScript, so the compiler cannot check these
219
+ * against the real ones from a type-only import. `packages/avatar/test/AvatarClient.test.ts`
220
+ * does it instead, against the actual enum — the devDependency is present
221
+ * exactly where the check belongs and absent from what we ship.
222
+ */
223
+ export const RTVI_EVENTS = {
224
+ serverMessage: "serverMessage",
225
+ connected: "connected",
226
+ disconnected: "disconnected",
227
+ botReady: "botReady",
228
+ error: "error",
229
+ userStartedSpeaking: "userStartedSpeaking",
230
+ userStoppedSpeaking: "userStoppedSpeaking",
231
+ botStartedSpeaking: "botStartedSpeaking",
232
+ botStoppedSpeaking: "botStoppedSpeaking",
233
+ // Only to find the bot's audio track once the transport has it; which track
234
+ // is re-read from `tracks()`, the one authority for whose it is.
235
+ trackStarted: "trackStarted",
236
+ // Mute is a Pipecat fact, and there is no server state for it: the server's
237
+ // mute strategy emits `UserMuteStarted/StoppedFrame`, the RTVI observer
238
+ // forwards them, and the browser client raises these. So "has muted you" costs no wire verb —
239
+ // reading the events the peer already sends is exactly the authority model.
240
+ userMuteStarted: "userMuteStarted",
241
+ userMuteStopped: "userMuteStopped",
242
+ } as const satisfies Record<string, string>;
243
+
244
+ /** The resolved, factual presence state a host may render around the avatar. */
245
+ export type AvatarPresenceState =
246
+ | "IDLE" | "LISTENING" | "CANT_HEAR" | "THINKING" | "WORKING"
247
+ | "MUTED" | "SPEAKING" | "DEGRADED" | "OFFLINE";
248
+ type LifecycleState = AvatarPresenceState;
249
+ type ServerState = "CANT_HEAR" | "THINKING" | "WORKING" | null;
250
+
251
+ /** Defensive unwrap for the `RTVIEvent.ServerMessage` `{ data }` quirk: some
252
+ * transports deliver the payload directly and some wrap it once more. */
253
+ function unwrapServerMessage(raw: unknown): Record<string, unknown> {
254
+ const obj = (raw ?? {}) as Record<string, unknown>;
255
+ const inner = obj["data"] as Record<string, unknown> | undefined;
256
+ return inner && "type" in inner ? inner : obj;
257
+ }
258
+
259
+ export class AvatarClient {
260
+ private readonly avatar: AvatarDriver;
261
+ /** Maps factual/wire intent into the broader client behavior catalog. */
262
+ private readonly behavior: BehaviorController;
263
+ private readonly opts: AvatarClientOptions;
264
+ private readonly now: () => number;
265
+ private turn: Turn | null = null;
266
+ private readonly turns = new Map<string, Turn>();
267
+ private readonly pendingCtxs: string[] = [];
268
+ private readonly closedCtxs = new Set<string>();
269
+ private projected: LifecycleState | null = null;
270
+ private serverState: ServerState = null;
271
+ private userSpeaking = false;
272
+ private botSpeaking = false;
273
+ private muted = false;
274
+ private listening = false;
275
+ // Idle is earned after a connected, quiet listening interval. A newly
276
+ // mounted avatar is available, not already "stepped aside".
277
+ private idle = false;
278
+ private failure: "DEGRADED" | "OFFLINE" | null = null;
279
+ private idleTimer: ReturnType<typeof setTimeout> | null = null;
280
+ private pendingInterruptedAction = false;
281
+ private discardQueuedContextsOnBotStop = false;
282
+ private readonly idleDelayMs: number;
283
+ private readonly setTimer: typeof setTimeout;
284
+ private readonly clearTimer: typeof clearTimeout;
285
+ private probe: PlayoutProbe | null;
286
+ private probeTrack: MediaStreamTrack | null = null;
287
+ /** Whether the probe has ever heard an onset. One that has not, and times
288
+ * out, is deaf to this track rather than early to it. */
289
+ private probeHeard = false;
290
+ private onsetTimer: ReturnType<typeof setTimeout> | null = null;
291
+ private reanchorTimer: ReturnType<typeof setTimeout> | null = null;
292
+
293
+ constructor(avatar: AvatarDriver, opts: AvatarClientOptions = {}) {
294
+ this.avatar = avatar;
295
+ this.behavior = new BehaviorController(avatar);
296
+ this.opts = opts;
297
+ this.now = opts.now ?? (() => performance.now());
298
+ this.idleDelayMs = opts.idleDelayMs ?? 12_000;
299
+ this.setTimer = opts.setTimeout ?? globalThis.setTimeout.bind(globalThis);
300
+ this.clearTimer = opts.clearTimeout ?? globalThis.clearTimeout.bind(globalThis);
301
+ this.probe = opts.playoutProbe ?? null;
302
+ }
303
+
304
+ /** The active turn's ctx, or `null` between turns. For tests and telemetry. */
305
+ get turnCtx(): string | null {
306
+ return this.turn?.ctx ?? null;
307
+ }
308
+
309
+ /** The active turn's canonical (already-spliced) cue track. For tests and telemetry. */
310
+ get turnCues(): AvatarCue[] {
311
+ return this.turn ? [...this.turn.cues] : [];
312
+ }
313
+
314
+ /** Current resolved projection. Internal — for tests and Studio's inspector.
315
+ * Before the first lifecycle fact the renderer is simply at its ready rest
316
+ * pose, so `LISTENING` is the safe value; it is not a session status. */
317
+ get presenceState(): AvatarPresenceState {
318
+ return this.projected ?? "LISTENING";
319
+ }
320
+
321
+ /** Re-apply the currently resolved factual projection after an embedding
322
+ * tool has temporarily used raw renderer controls. This does not invent a
323
+ * lifecycle event or cancel a finite action. */
324
+ restoreProjection(): void {
325
+ this.applyProjection(true);
326
+ }
327
+
328
+ /** Dispatch one server message. Anything that isn't in the avatar envelope
329
+ * is not ours and is ignored; so is an envelope carrying a `cmd` this build
330
+ * has never heard of, per the wire protocol's forward-compat rule. */
331
+ dispatch(raw: unknown): void {
332
+ if (!isAvatarMessage(raw)) return;
333
+ const msg = parseAvatarCommand(raw);
334
+ if (!msg) return;
335
+ try {
336
+ switch (msg.cmd) {
337
+ case "state":
338
+ this.handleState(msg.state);
339
+ break;
340
+ case "action":
341
+ this.handleAction(msg.id);
342
+ break;
343
+ case "cues":
344
+ this.handleCues(msg);
345
+ break;
346
+ // No default: an unknown `cmd` is a newer server talking to an older
347
+ // widget, and the protocol's forward-compat rule says ignore it. There
348
+ // is no callback for it — a hook nobody could act on is observability,
349
+ // not an interface.
350
+ }
351
+ } catch (err) {
352
+ if (this.opts.onError) this.opts.onError(err, msg);
353
+ else console.warn("[avatar] dispatch failed", msg, err);
354
+ }
355
+ }
356
+
357
+ private handleState(state: ServerState): void {
358
+ this.serverState = state;
359
+ if (state) this.idle = false;
360
+ this.applyProjection();
361
+ this.armIdleIfEligible();
362
+ }
363
+
364
+ private handleAction(id: string): void {
365
+ // An interruption is a server-confirmed explanation of a transition, not
366
+ // authority to steal the mouth while bot audio is still playing. Hold it
367
+ // until Pipecat output has released the speaking state.
368
+ if (id === "RESPONSE_INTERRUPTED" && this.botSpeaking) {
369
+ this.pendingInterruptedAction = true;
370
+ // Any prefetched TTS contexts behind interrupted output belong to
371
+ // audio Pipecat will now discard. Never let one animate a later reply.
372
+ this.discardQueuedContextsOnBotStop = true;
373
+ return;
374
+ }
375
+ this.playAction(id);
376
+ }
377
+
378
+ private playAction(id: string): void {
379
+ this.behavior.wireAction(id);
380
+ }
381
+
382
+ private ensureTurn(ctx: string): Turn {
383
+ const existing = this.turns.get(ctx);
384
+ if (existing) return existing;
385
+ const turn: Turn = {
386
+ ctx, cues: [], started: false, clock: null, t0: null,
387
+ target: null, read: 0, lead: 0, checked: -Infinity,
388
+ };
389
+ this.turns.set(ctx, turn);
390
+ this.pendingCtxs.push(ctx);
391
+ return turn;
392
+ }
393
+
394
+ private handleCues(msg: AvatarCuesCmd) {
395
+ if (this.closedCtxs.has(msg.ctx)) return;
396
+ const turn = this.ensureTurn(msg.ctx);
397
+ const kept = turn.cues.filter((c) => c.t < msg.from_ms);
398
+ const discarded = turn.cues.length - kept.length;
399
+ turn.cues = [...kept, ...msg.cues].sort((a, b) => a.t - b.t);
400
+
401
+ if (!turn.started) {
402
+ // No clock yet — buffer. Pipecat output will claim this FIFO context.
403
+ if (this.botSpeaking && this.turn === null) this.activateNextTurn();
404
+ return;
405
+ }
406
+ if (discarded === 0) {
407
+ this.avatar.pushCues(msg.cues);
408
+ } else {
409
+ this.avatar.speak({ cues: turn.cues, clock: turn.clock! });
410
+ }
411
+ // A resumption this chunk added may be the next one worth listening for.
412
+ this.scheduleReanchor(turn);
413
+ }
414
+
415
+ private activateNextTurn(): void {
416
+ if (this.turn) return;
417
+ let turn: Turn | undefined;
418
+ while (this.pendingCtxs.length && !turn) {
419
+ turn = this.turns.get(this.pendingCtxs.shift()!);
420
+ }
421
+ if (!turn) return;
422
+ const active = turn;
423
+ active.lead = this.leadMs();
424
+ active.clock = () => {
425
+ if (active.t0 === null) return -1;
426
+ const now = this.now();
427
+ if (active.target !== null) {
428
+ const room = MAX_SLEW * Math.max(0, now - active.read);
429
+ const off = active.target - active.t0;
430
+ if (Math.abs(off) <= room) {
431
+ active.t0 = active.target;
432
+ active.target = null;
433
+ } else {
434
+ active.t0 += Math.sign(off) * room;
435
+ }
436
+ }
437
+ active.read = now;
438
+ return now - active.t0 + active.lead;
439
+ };
440
+ active.started = true;
441
+ this.turn = active;
442
+ this.anchor(active);
443
+ this.avatar.speak({ cues: active.cues, clock: active.clock });
444
+ }
445
+
446
+ /** Put the turn's zero where its sound began — see the header. */
447
+ private anchor(turn: Turn): void {
448
+ const event = this.now();
449
+ // A context made before any gesture can sit suspended; every turn asks again.
450
+ this.probe?.resume?.();
451
+ const heard = this.probe?.onset();
452
+ if (typeof heard === "number") {
453
+ this.probeHeard = true;
454
+ this.anchored(turn, heard, "the sound", event);
455
+ return;
456
+ }
457
+ if (heard !== null) {
458
+ this.anchored(turn, event, this.probe ? "the event (probe cannot say)" : "the event (no probe)", event);
459
+ return;
460
+ }
461
+ const poll = () => {
462
+ this.onsetTimer = null;
463
+ if (this.turn !== turn) return;
464
+ const onset = this.probe?.onset();
465
+ if (typeof onset === "number") {
466
+ this.probeHeard = true;
467
+ this.anchored(turn, onset, "the sound", event);
468
+ } else if (onset === null && this.now() - event < ONSET_WAIT_MS) {
469
+ this.onsetTimer = this.setTimer(poll, ONSET_POLL_MS);
470
+ } else {
471
+ if (!this.probeHeard) this.dropProbe();
472
+ this.anchored(turn, event, onset === null ? "the event (no sound in time)" : "the event (probe cannot say)", event);
473
+ }
474
+ };
475
+ this.onsetTimer = this.setTimer(poll, ONSET_POLL_MS);
476
+ }
477
+
478
+ private anchored(turn: Turn, t0: number, how: string, event: number): void {
479
+ turn.t0 = t0;
480
+ turn.read = this.now();
481
+ console.info(
482
+ `[avatar] ${turn.ctx} anchored on ${how}: sound ${Math.round(event - t0)} ms before the event, `
483
+ + `mouth ${Math.round(turn.lead)} ms ahead`,
484
+ );
485
+ this.scheduleReanchor(turn);
486
+ }
487
+
488
+ /** The lead for a turn starting now — see `VISUAL_LEAD_MS`. */
489
+ private leadMs(): number {
490
+ const out = this.probe?.outputLatencyMs?.() ?? 0;
491
+ const excess = Math.min(MAX_OUTPUT_LATENCY_MS, Math.max(0, out - DISPLAY_LATENCY_MS));
492
+ return VISUAL_LEAD_MS - excess;
493
+ }
494
+
495
+ /** The first resumption after `after` (track ms) that follows a pause long
496
+ * enough to be heard as one. */
497
+ private nextResumption(turn: Turn, after: number): number | null {
498
+ let silentFrom: number | null = null;
499
+ for (const c of turn.cues) {
500
+ if (c.v === "X") {
501
+ silentFrom ??= c.t;
502
+ continue;
503
+ }
504
+ if (silentFrom !== null && c.t - silentFrom >= REANCHOR_GAP_MS && c.t > after) return c.t;
505
+ silentFrom = null;
506
+ }
507
+ return null;
508
+ }
509
+
510
+ /** Listen for the sound at the turn's next resumption, once. */
511
+ private scheduleReanchor(turn: Turn): void {
512
+ if (this.reanchorTimer !== null || !this.probe || turn.t0 === null || this.turn !== turn) return;
513
+ const zero = turn.target ?? turn.t0;
514
+ const at = this.nextResumption(turn, Math.max(turn.checked, this.now() - zero - REANCHOR_WINDOW_MS));
515
+ if (at === null) return;
516
+ const poll = () => {
517
+ this.reanchorTimer = null;
518
+ if (this.turn !== turn || !this.probe || turn.t0 === null) return;
519
+ const due = (turn.target ?? turn.t0) + at;
520
+ const onset = this.probe.onset();
521
+ if (onset === null && this.now() < due + RESUME_HEARD_MS + REANCHOR_WINDOW_MS) {
522
+ this.reanchorTimer = this.setTimer(poll, ONSET_POLL_MS);
523
+ return;
524
+ }
525
+ turn.checked = at;
526
+ // `undefined` is sound all the way back: the pause was not silence on
527
+ // the wire, or it resumed long before the track says. Either way there
528
+ // is nothing to measure.
529
+ if (typeof onset === "number") {
530
+ const heard = onset - due;
531
+ const [earliest, latest] = RESUME_HEARD_RANGE_MS;
532
+ const agrees = heard >= earliest && heard <= latest;
533
+ if (!agrees && Math.abs(heard - RESUME_HEARD_MS) <= REANCHOR_WINDOW_MS) {
534
+ turn.target = onset - at - RESUME_HEARD_MS;
535
+ }
536
+ }
537
+ this.scheduleReanchor(turn);
538
+ };
539
+ const zeroNow = turn.target ?? turn.t0;
540
+ this.reanchorTimer = this.setTimer(poll, Math.max(0, zeroNow + at + REANCHOR_LOOK_MS - this.now()));
541
+ }
542
+
543
+ private clearReanchorTimer(): void {
544
+ if (this.reanchorTimer !== null) {
545
+ this.clearTimer(this.reanchorTimer);
546
+ this.reanchorTimer = null;
547
+ }
548
+ }
549
+
550
+ private clearOnsetTimer(): void {
551
+ if (this.onsetTimer !== null) {
552
+ this.clearTimer(this.onsetTimer);
553
+ this.onsetTimer = null;
554
+ }
555
+ }
556
+
557
+ private dropProbe(): void {
558
+ this.probe?.dispose();
559
+ this.probe = null;
560
+ this.probeTrack = null;
561
+ this.probeHeard = false;
562
+ }
563
+
564
+ /** Listen to the bot's audio track, if the transport has one yet. */
565
+ private listenTo(client: PipecatClient, heard?: MediaStreamTrack): void {
566
+ if (this.opts.playoutProbe) return;
567
+ let track: MediaStreamTrack | undefined = heard;
568
+ if (!track) {
569
+ try {
570
+ track = client.tracks().bot?.audio;
571
+ } catch {
572
+ return;
573
+ }
574
+ }
575
+ if (!track || track === this.probeTrack) return;
576
+ this.dropProbe();
577
+ this.probe = createPlayoutProbe(track, this.now);
578
+ this.probeTrack = this.probe ? track : null;
579
+ }
580
+
581
+ private discardQueuedTurns(): void {
582
+ for (const ctx of this.pendingCtxs.splice(0)) {
583
+ this.closedCtxs.add(ctx);
584
+ this.turns.delete(ctx);
585
+ }
586
+ }
587
+
588
+ private lifecycleState(): LifecycleState {
589
+ // The one copy of the ladder is docs/pipecat-lifecycle-protocol.md; this is
590
+ // its implementation, in the same order.
591
+ //
592
+ // Audio truth is the P0 invariant: no lower state or microphone event may
593
+ // put the face in a non-speaking pose while bot speech is audible.
594
+ if (this.botSpeaking) return "SPEAKING";
595
+ if (this.userSpeaking) return "LISTENING";
596
+ // A broken session outranks mute, because a mute nobody can hear about is
597
+ // not the thing worth saying about a dead call.
598
+ if (this.failure) return this.failure;
599
+ if (this.muted) return "MUTED";
600
+ // A server state *is* the presence state of the same name, so there is
601
+ // nothing to rank here — only one can be in flight, and the command sets
602
+ // rather than adds. CANT_HEAR > THINKING > WORKING is decided where more
603
+ // than one condition can hold at once, which is the server:
604
+ // `AvatarStateMachine._resolve()`. Ranking them again on this side would be
605
+ // a second, silent copy of that ladder, and the two would drift.
606
+ if (this.serverState) return this.serverState;
607
+ if (this.idle) return "IDLE";
608
+ return "LISTENING";
609
+ }
610
+
611
+ private applyProjection(force = false): void {
612
+ const state = this.lifecycleState();
613
+ if (force || this.projected !== state) {
614
+ this.behavior.setState(state);
615
+ this.projected = state;
616
+ this.opts.onPresenceChange?.(state);
617
+ }
618
+ }
619
+
620
+ private clearIdleTimer(): void {
621
+ if (this.idleTimer !== null) {
622
+ this.clearTimer(this.idleTimer);
623
+ this.idleTimer = null;
624
+ }
625
+ }
626
+
627
+ private armIdleIfEligible(): void {
628
+ this.clearIdleTimer();
629
+ // Quiet under a mute is not the quiet that earns IDLE — the silence was
630
+ // imposed, and letting the timer run behind it would reveal a stepped-aside
631
+ // face the moment the microphone came back.
632
+ if (!this.eligibleForIdle()) return;
633
+ this.idleTimer = this.setTimer(() => {
634
+ this.idleTimer = null;
635
+ if (this.eligibleForIdle()) {
636
+ this.idle = true;
637
+ this.applyProjection();
638
+ }
639
+ }, this.idleDelayMs);
640
+ }
641
+
642
+ private eligibleForIdle(): boolean {
643
+ return this.listening && !this.userSpeaking && !this.botSpeaking
644
+ && !this.muted && !this.serverState && !this.failure;
645
+ }
646
+
647
+ private enterListening(): void {
648
+ this.listening = true;
649
+ this.idle = false;
650
+ this.applyProjection();
651
+ this.armIdleIfEligible();
652
+ }
653
+
654
+ private clearServerStateForTurnBoundary(): void {
655
+ // A server state is a lower-priority hint. A fresh user turn or bot output
656
+ // means any prior thinking/working one may not reappear later.
657
+ this.serverState = null;
658
+ }
659
+
660
+ private maybePlayInterrupted(): void {
661
+ if (this.pendingInterruptedAction && !this.botSpeaking) {
662
+ this.pendingInterruptedAction = false;
663
+ this.playAction("RESPONSE_INTERRUPTED");
664
+ }
665
+ }
666
+
667
+ private clearRecoverableFailure(): void {
668
+ if (this.failure === "DEGRADED") {
669
+ this.failure = null;
670
+ this.applyProjection();
671
+ }
672
+ }
673
+
674
+ private onUserStartedSpeaking = (): void => {
675
+ this.clearRecoverableFailure();
676
+ this.userSpeaking = true;
677
+ this.clearServerStateForTurnBoundary();
678
+ this.listening = true;
679
+ this.idle = false;
680
+ this.clearIdleTimer();
681
+ this.avatar.setUserSpeaking(true);
682
+ this.applyProjection();
683
+ };
684
+
685
+ private onUserStoppedSpeaking = (): void => {
686
+ this.userSpeaking = false;
687
+ this.avatar.setUserSpeaking(false);
688
+ this.enterListening();
689
+ };
690
+
691
+ private onBotStartedSpeaking = (): void => {
692
+ this.clearRecoverableFailure();
693
+ this.botSpeaking = true;
694
+ this.clearServerStateForTurnBoundary();
695
+ this.idle = false;
696
+ this.clearIdleTimer();
697
+ this.applyProjection();
698
+ this.activateNextTurn();
699
+ };
700
+
701
+ private onBotStoppedSpeaking = (): void => {
702
+ this.botSpeaking = false;
703
+ this.clearOnsetTimer();
704
+ this.clearReanchorTimer();
705
+ // Playout truth releases the only active mouth track. A late cue chunk for
706
+ // this context is ignored rather than reviving a silent mouth.
707
+ if (this.turn) {
708
+ this.avatar.stopSpeaking();
709
+ this.closedCtxs.add(this.turn.ctx);
710
+ this.turns.delete(this.turn.ctx);
711
+ this.turn = null;
712
+ }
713
+ if (this.discardQueuedContextsOnBotStop) {
714
+ this.discardQueuedContextsOnBotStop = false;
715
+ this.discardQueuedTurns();
716
+ }
717
+ this.enterListening();
718
+ this.maybePlayInterrupted();
719
+ };
720
+
721
+ private onUserMuteStarted = (): void => {
722
+ this.muted = true;
723
+ this.idle = false;
724
+ this.clearIdleTimer();
725
+ this.applyProjection();
726
+ };
727
+
728
+ private onUserMuteStopped = (): void => {
729
+ this.muted = false;
730
+ // Whatever the avatar was waiting on before the mute, it is waiting on the
731
+ // user again now — the same place a turn ends.
732
+ this.enterListening();
733
+ };
734
+
735
+ private onError = (raw: unknown): void => {
736
+ const data = (raw as { data?: unknown })?.data as { fatal?: unknown } | undefined;
737
+ this.failure = data?.fatal === true ? "OFFLINE" : "DEGRADED";
738
+ this.applyProjection();
739
+ };
740
+
741
+ private onDisconnected = (): void => {
742
+ this.failure = "OFFLINE";
743
+ this.clearIdleTimer();
744
+ this.applyProjection();
745
+ };
746
+
747
+ private onConnectedOrReady = (): void => {
748
+ if (this.failure === "OFFLINE") this.failure = null;
749
+ // Pipecat has established a session. Until a factual speech event says
750
+ // otherwise, the avatar is available to listen; it earns IDLE only after
751
+ // the regular quiet timer expires.
752
+ this.listening = true;
753
+ this.idle = false;
754
+ this.applyProjection();
755
+ this.armIdleIfEligible();
756
+ };
757
+
758
+ /**
759
+ * Subscribe to a live `PipecatClient`. Standard client events own the normal
760
+ * lifecycle projection; avatar server-messages carry correlated visemes and
761
+ * explicit application intent. Never throws on malformed or irrelevant
762
+ * server messages.
763
+ *
764
+ * @returns an unsubscribe function; call it on unmount or disconnect.
765
+ */
766
+ attach(client: PipecatClient): () => void {
767
+ const onServerMessage = (raw: unknown) => this.dispatch(unwrapServerMessage(raw));
768
+ // The bot's track has to come from the event. SmallWebRTC never lists a
769
+ // remote track in `tracks()`; it only hands it to this callback, with no
770
+ // participant. Asking `tracks()` alone meant no probe on that transport,
771
+ // so every turn fell back to the event.
772
+ const onTrackStarted = (track?: MediaStreamTrack, participant?: { local?: boolean }) => {
773
+ if (participant?.local || (track && track.kind !== "audio")) return;
774
+ this.listenTo(client, track);
775
+ };
776
+ const subscriptions: Array<[string, (...args: any[]) => void]> = [
777
+ [RTVI_EVENTS.serverMessage, onServerMessage],
778
+ [RTVI_EVENTS.connected, this.onConnectedOrReady],
779
+ [RTVI_EVENTS.botReady, this.onConnectedOrReady],
780
+ [RTVI_EVENTS.disconnected, this.onDisconnected],
781
+ [RTVI_EVENTS.error, this.onError],
782
+ [RTVI_EVENTS.userStartedSpeaking, this.onUserStartedSpeaking],
783
+ [RTVI_EVENTS.userStoppedSpeaking, this.onUserStoppedSpeaking],
784
+ [RTVI_EVENTS.botStartedSpeaking, this.onBotStartedSpeaking],
785
+ [RTVI_EVENTS.botStoppedSpeaking, this.onBotStoppedSpeaking],
786
+ [RTVI_EVENTS.userMuteStarted, this.onUserMuteStarted],
787
+ [RTVI_EVENTS.userMuteStopped, this.onUserMuteStopped],
788
+ [RTVI_EVENTS.trackStarted, onTrackStarted],
789
+ ];
790
+ for (const [event, listener] of subscriptions) client.on(event as RTVIEvent, listener as never);
791
+ this.listenTo(client);
792
+ // Some browsers keep an audio context suspended until it is resumed inside
793
+ // a gesture, and the connect click usually lands before the bot's track
794
+ // exists. Any later click or key is the next chance.
795
+ const wake = () => this.probe?.resume?.();
796
+ const doc = typeof document === "undefined" ? null : document;
797
+ doc?.addEventListener("pointerdown", wake, true);
798
+ doc?.addEventListener("keydown", wake, true);
799
+ return () => {
800
+ doc?.removeEventListener("pointerdown", wake, true);
801
+ doc?.removeEventListener("keydown", wake, true);
802
+ this.clearIdleTimer();
803
+ this.clearOnsetTimer();
804
+ this.clearReanchorTimer();
805
+ if (!this.opts.playoutProbe) this.dropProbe();
806
+ for (const [event, listener] of subscriptions) client.off(event as RTVIEvent, listener as never);
807
+ };
808
+ }
809
+
810
+ /** Dispose controller-owned timers when its mounted avatar is destroyed. */
811
+ destroy(): void {
812
+ this.clearIdleTimer();
813
+ this.clearOnsetTimer();
814
+ this.clearReanchorTimer();
815
+ this.dropProbe();
816
+ this.behavior.destroy();
817
+ }
818
+ }