livekit-plugins-facemode 0.1.0__tar.gz → 0.3.1__tar.gz

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 (21) hide show
  1. livekit_plugins_facemode-0.3.1/LICENSE +177 -0
  2. livekit_plugins_facemode-0.3.1/PKG-INFO +101 -0
  3. {livekit_plugins_facemode-0.1.0 → livekit_plugins_facemode-0.3.1}/README.md +10 -4
  4. {livekit_plugins_facemode-0.1.0 → livekit_plugins_facemode-0.3.1}/livekit_plugins_facemode/__init__.py +17 -17
  5. {livekit_plugins_facemode-0.1.0 → livekit_plugins_facemode-0.3.1}/livekit_plugins_facemode/avatar.py +171 -16
  6. {livekit_plugins_facemode-0.1.0 → livekit_plugins_facemode-0.3.1}/livekit_plugins_facemode/exceptions.py +17 -17
  7. livekit_plugins_facemode-0.3.1/livekit_plugins_facemode/version.py +1 -0
  8. livekit_plugins_facemode-0.3.1/livekit_plugins_facemode.egg-info/PKG-INFO +101 -0
  9. {livekit_plugins_facemode-0.1.0 → livekit_plugins_facemode-0.3.1}/livekit_plugins_facemode.egg-info/SOURCES.txt +2 -1
  10. {livekit_plugins_facemode-0.1.0 → livekit_plugins_facemode-0.3.1}/pyproject.toml +12 -2
  11. livekit_plugins_facemode-0.3.1/test/test_playback.py +256 -0
  12. livekit_plugins_facemode-0.1.0/LICENSE +0 -13
  13. livekit_plugins_facemode-0.1.0/PKG-INFO +0 -13
  14. livekit_plugins_facemode-0.1.0/livekit_plugins_facemode/version.py +0 -1
  15. livekit_plugins_facemode-0.1.0/livekit_plugins_facemode.egg-info/PKG-INFO +0 -13
  16. {livekit_plugins_facemode-0.1.0 → livekit_plugins_facemode-0.3.1}/livekit_plugins_facemode/models.py +0 -0
  17. {livekit_plugins_facemode-0.1.0 → livekit_plugins_facemode-0.3.1}/livekit_plugins_facemode.egg-info/dependency_links.txt +0 -0
  18. {livekit_plugins_facemode-0.1.0 → livekit_plugins_facemode-0.3.1}/livekit_plugins_facemode.egg-info/requires.txt +0 -0
  19. {livekit_plugins_facemode-0.1.0 → livekit_plugins_facemode-0.3.1}/livekit_plugins_facemode.egg-info/top_level.txt +0 -0
  20. {livekit_plugins_facemode-0.1.0 → livekit_plugins_facemode-0.3.1}/setup.cfg +0 -0
  21. {livekit_plugins_facemode-0.1.0 → livekit_plugins_facemode-0.3.1}/test/test_ingestion.py +0 -0
@@ -0,0 +1,177 @@
1
+ Copyright 2026 InfinityLevel OPC Private Limited
2
+
3
+ Apache License
4
+ Version 2.0, January 2004
5
+ http://www.apache.org/licenses/
6
+
7
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
8
+
9
+ 1. Definitions.
10
+
11
+ "License" shall mean the terms and conditions for use, reproduction,
12
+ and distribution as defined by Sections 1 through 9 of this document.
13
+
14
+ "Licensor" shall mean the copyright owner or entity authorized by
15
+ the copyright owner that is granting the License.
16
+
17
+ "Legal Entity" shall mean the union of the acting entity and all
18
+ other entities that control, are controlled by, or are under common
19
+ control with that entity. For the purposes of this definition,
20
+ "control" means (i) the power, direct or indirect, to cause the
21
+ direction or management of such entity, whether by contract or
22
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
23
+ outstanding shares, or (iii) beneficial ownership of such entity.
24
+
25
+ "You" (or "Your") shall mean an individual or Legal Entity
26
+ exercising permissions granted by this License.
27
+
28
+ "Source" form shall mean the preferred form for making modifications,
29
+ including but not limited to software source code, documentation
30
+ source, and configuration files.
31
+
32
+ "Object" form shall mean any form resulting from mechanical
33
+ transformation or translation of a Source form, including but
34
+ not limited to compiled object code, generated documentation,
35
+ and conversions to other media types.
36
+
37
+ "Work" shall mean the work of authorship, whether in Source or
38
+ Object form, made available under the License, as indicated by a
39
+ copyright notice that is included in or attached to the work
40
+ (an example is provided in the Appendix below).
41
+
42
+ "Derivative Works" shall mean any work, whether in Source or Object
43
+ form, that is based on (or derived from) the Work and for which the
44
+ editorial revisions, annotations, elaborations, or other modifications
45
+ represent, as a whole, an original work of authorship. For the purposes
46
+ of this License, Derivative Works shall not include works that remain
47
+ separable from, or merely link (or bind by name) to the interfaces of,
48
+ the Work and Derivative Works thereof.
49
+
50
+ "Contribution" shall mean any work of authorship, including
51
+ the original version of the Work and any modifications or additions
52
+ to that Work or Derivative Works thereof, that is intentionally
53
+ submitted to Licensor for inclusion in the Work by the copyright owner
54
+ or by an individual or Legal Entity authorized to submit on behalf of
55
+ the copyright owner. For the purposes of this definition, "submitted"
56
+ means any form of electronic, verbal, or written communication sent
57
+ to the Licensor or its representatives, including but not limited to
58
+ communication on electronic mailing lists, source code control systems,
59
+ and issue tracking systems that are managed by, or on behalf of, the
60
+ Licensor for the purpose of discussing and improving the Work, but
61
+ excluding communication that is conspicuously marked or otherwise
62
+ designated in writing by the copyright owner as "Not a Contribution."
63
+
64
+ "Contributor" shall mean Licensor and any individual or Legal Entity
65
+ on behalf of whom a Contribution has been received by Licensor and
66
+ subsequently incorporated within the Work.
67
+
68
+ 2. Grant of Copyright License. Subject to the terms and conditions of
69
+ this License, each Contributor hereby grants to You a perpetual,
70
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
71
+ copyright license to reproduce, prepare Derivative Works of,
72
+ publicly display, publicly perform, sublicense, and distribute the
73
+ Work and such Derivative Works in Source or Object form.
74
+
75
+ 3. Grant of Patent License. Subject to the terms and conditions of
76
+ this License, each Contributor hereby grants to You a perpetual,
77
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
78
+ (except as stated in this section) patent license to make, have made,
79
+ use, offer to sell, sell, import, and otherwise transfer the Work,
80
+ where such license applies only to those patent claims licensable
81
+ by such Contributor that are necessarily infringed by their
82
+ Contribution(s) alone or by combination of their Contribution(s)
83
+ with the Work to which such Contribution(s) was submitted. If You
84
+ institute patent litigation against any entity (including a
85
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
86
+ or a Contribution incorporated within the Work constitutes direct
87
+ or contributory patent infringement, then any patent licenses
88
+ granted to You under this License for that Work shall terminate
89
+ as of the date such litigation is filed.
90
+
91
+ 4. Redistribution. You may reproduce and distribute copies of the
92
+ Work or Derivative Works thereof in any medium, with or without
93
+ modifications, provided that You meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of the
105
+ Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
@@ -0,0 +1,101 @@
1
+ Metadata-Version: 2.4
2
+ Name: livekit-plugins-facemode
3
+ Version: 0.3.1
4
+ Summary: FaceMode avatar integration for LiveKit Agents
5
+ Author: FaceMode
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://facemode.io
8
+ Project-URL: Repository, https://github.com/facemode-by-infinitylevel/facemode-integrations
9
+ Keywords: livekit,agents,avatar,facemode,ai,video,realtime
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Programming Language :: Python :: 3.13
13
+ Classifier: Topic :: Multimedia :: Video
14
+ Requires-Python: >=3.13
15
+ Description-Content-Type: text/markdown
16
+ License-File: LICENSE
17
+ Requires-Dist: aiohttp<4,>=3.10
18
+ Requires-Dist: livekit<2,>=1.1
19
+ Requires-Dist: livekit-agents<2,>=1.7
20
+ Requires-Dist: websockets<17,>=14
21
+ Dynamic: license-file
22
+
23
+ # livekit-plugins-facemode
24
+
25
+ [FaceMode](https://facemode.io) avatar output for LiveKit Agents Python applications.
26
+
27
+ ## Install
28
+
29
+ ```bash
30
+ pip install livekit-plugins-facemode
31
+ ```
32
+
33
+ From this repository:
34
+
35
+ ```bash
36
+ pip install .
37
+ ```
38
+
39
+ Requires Python 3.13 or later, `livekit>=1.1,<2`, and `livekit-agents>=1.7,<2`.
40
+
41
+ ## Usage
42
+
43
+ The host application supplies a server-side LiveKit room object. The room token
44
+ must grant the FaceMode worker permission to join, publish, and subscribe in the
45
+ customer room. Keep the token on the server and never log it or expose it to a
46
+ browser client.
47
+
48
+ ```python
49
+ import os
50
+
51
+ from livekit.agents import Agent, AgentSession, room_io
52
+ from livekit_plugins_facemode import AvatarSession
53
+
54
+ avatar = AvatarSession(
55
+ api_key=os.environ["FACEMODE_API_KEY"],
56
+ avatar_id=os.environ.get("FACEMODE_AVATAR_ID", ""),
57
+ )
58
+
59
+ await ctx.connect()
60
+ await avatar.start(
61
+ agent_session,
62
+ ctx.room,
63
+ room={
64
+ "type": "livekit",
65
+ "url": os.environ["LIVEKIT_URL"],
66
+ "token": os.environ["LIVEKIT_TOKEN"],
67
+ },
68
+ )
69
+ await agent_session.start(
70
+ agent=Agent(instructions="You are a helpful assistant."),
71
+ room=ctx.room,
72
+ room_options=room_io.RoomOptions(audio_output=False),
73
+ )
74
+ await avatar.wait_for_join()
75
+ ```
76
+
77
+ `AvatarSession.start()` creates a FaceMode session with the room object. The create response normally returns `ready: true` with the ingestion `url` and a one-time `wsToken` (about 15 minute expiry), so no polling happens in the common path. If worker assignment is still pending, the plugin polls the session endpoint with bounded backoff for up to 240 seconds and stops immediately on `FAILED`/`ENDED` worker states. The initial response's room credentials remain in memory and are not expected in the polling response.
78
+
79
+ The ingestion WebSocket handshake uses the `Sec-WebSocket-Protocol` subprotocol `facemode.<wsToken>` with a 240 second open timeout. When the backend returns optional `ingestion.headers`, the plugin forwards them during the handshake. It disables compression and native WebSocket keepalives in favor of the canonical application `ping`/`pong` messages after negotiation.
80
+
81
+ Pass `input_provider` (one of `deepgram`, `gemini`, `gnani`, `elevenlabs`, `openai`, `cartesia`, `sarvam`, `custom`) to `AvatarSession` when the session should pin a specific upstream input provider; it is omitted from the request otherwise.
82
+
83
+ If the WebSocket transport drops after the protocol has started, the plugin auto-reconnects in the background: it POSTs the session reconnect endpoint for a fresh one-time `wsToken` (a consumed token is never reused), opens a new socket with `facemode.<newToken>`, re-sends the canonical `start` message, and waits for `started` before resuming. Outgoing control `seq` numbers stay monotonic across the reconnect and buffered audio is not replayed. Reconnect is bounded to 2 attempts with backoff and is single-flight; exhaustion surfaces a typed `FaceModeNotReadyError`/`FaceModeAPIError`. Intentional `stop()`, a canonical `ended`, fatal protocol errors, and drops before the first negotiation do not reconnect.
84
+
85
+ Every TTS frame is sent as canonical PCM audio. The plugin locks sample rate and channel count at protocol negotiation and rejects a format change or unaligned 16-bit PCM afterward. `cancel_utterance` is sent when LiveKit interrupts the audio output. Graceful close sends `end_session` and waits briefly for canonical `ended`; `ended` is a protocol acknowledgement, not backend cleanup confirmation.
86
+
87
+ ## Token grants
88
+
89
+ The `room.token` value must allow the worker to join the customer room and
90
+ publish its avatar audio/video tracks. If the token uses a fixed participant
91
+ identity, use `avatar_participant_identity` and make the room policy allow that
92
+ identity. The worker does not create or replace the customer LiveKit room.
93
+
94
+ ## API URL
95
+
96
+ The default API URL is `https://api.facemode.io/api`. Set `api_url` for a
97
+ self-hosted or local backend.
98
+
99
+ ## License
100
+
101
+ Apache-2.0 - see [LICENSE](LICENSE). Part of the [facemode-integrations](https://github.com/facemode-by-infinitylevel/facemode-integrations) monorepo.
@@ -1,19 +1,21 @@
1
1
  # livekit-plugins-facemode
2
2
 
3
- FaceMode avatar output for LiveKit Agents Python applications.
3
+ [FaceMode](https://facemode.io) avatar output for LiveKit Agents Python applications.
4
4
 
5
5
  ## Install
6
6
 
7
- ```powershell
7
+ ```bash
8
8
  pip install livekit-plugins-facemode
9
9
  ```
10
10
 
11
11
  From this repository:
12
12
 
13
- ```powershell
13
+ ```bash
14
14
  pip install .
15
15
  ```
16
16
 
17
+ Requires Python 3.13 or later, `livekit>=1.1,<2`, and `livekit-agents>=1.7,<2`.
18
+
17
19
  ## Usage
18
20
 
19
21
  The host application supplies a server-side LiveKit room object. The room token
@@ -52,7 +54,7 @@ await avatar.wait_for_join()
52
54
 
53
55
  `AvatarSession.start()` creates a FaceMode session with the room object. The create response normally returns `ready: true` with the ingestion `url` and a one-time `wsToken` (about 15 minute expiry), so no polling happens in the common path. If worker assignment is still pending, the plugin polls the session endpoint with bounded backoff for up to 240 seconds and stops immediately on `FAILED`/`ENDED` worker states. The initial response's room credentials remain in memory and are not expected in the polling response.
54
56
 
55
- The ingestion WebSocket handshake uses the `Sec-WebSocket-Protocol` subprotocol `facemode.<wsToken>` (the older `aivatar.` prefix is rejected) with a 240 second open timeout. When the backend returns optional `ingestion.headers`, the plugin forwards them during the handshake. It disables compression and native WebSocket keepalives in favor of the canonical application `ping`/`pong` messages after negotiation.
57
+ The ingestion WebSocket handshake uses the `Sec-WebSocket-Protocol` subprotocol `facemode.<wsToken>` with a 240 second open timeout. When the backend returns optional `ingestion.headers`, the plugin forwards them during the handshake. It disables compression and native WebSocket keepalives in favor of the canonical application `ping`/`pong` messages after negotiation.
56
58
 
57
59
  Pass `input_provider` (one of `deepgram`, `gemini`, `gnani`, `elevenlabs`, `openai`, `cartesia`, `sarvam`, `custom`) to `AvatarSession` when the session should pin a specific upstream input provider; it is omitted from the request otherwise.
58
60
 
@@ -71,3 +73,7 @@ identity. The worker does not create or replace the customer LiveKit room.
71
73
 
72
74
  The default API URL is `https://api.facemode.io/api`. Set `api_url` for a
73
75
  self-hosted or local backend.
76
+
77
+ ## License
78
+
79
+ Apache-2.0 - see [LICENSE](LICENSE). Part of the [facemode-integrations](https://github.com/facemode-by-infinitylevel/facemode-integrations) monorepo.
@@ -1,17 +1,17 @@
1
- from .avatar import AvatarSession
2
- from .exceptions import FaceModeAPIError, FaceModeError, FaceModeNotReadyError, FaceModeProtocolError
3
- from .models import IngestionDetails, LiveKitRoom, SessionDetails, SessionRequest
4
- from .version import __version__
5
-
6
- __all__ = [
7
- "AvatarSession",
8
- "FaceModeAPIError",
9
- "FaceModeError",
10
- "FaceModeNotReadyError",
11
- "FaceModeProtocolError",
12
- "IngestionDetails",
13
- "LiveKitRoom",
14
- "SessionDetails",
15
- "SessionRequest",
16
- "__version__",
17
- ]
1
+ from .avatar import AvatarSession
2
+ from .exceptions import FaceModeAPIError, FaceModeError, FaceModeNotReadyError, FaceModeProtocolError
3
+ from .models import IngestionDetails, LiveKitRoom, SessionDetails, SessionRequest
4
+ from .version import __version__
5
+
6
+ __all__ = [
7
+ "AvatarSession",
8
+ "FaceModeAPIError",
9
+ "FaceModeError",
10
+ "FaceModeNotReadyError",
11
+ "FaceModeProtocolError",
12
+ "IngestionDetails",
13
+ "LiveKitRoom",
14
+ "SessionDetails",
15
+ "SessionRequest",
16
+ "__version__",
17
+ ]
@@ -57,6 +57,15 @@ _PREFERRED_SAMPLE_RATES = frozenset(
57
57
 
58
58
 
59
59
  class _FaceModeAudioOutput(AudioOutput):
60
+ """Audio sink forwarding TTS audio to the FaceMode ingestion socket.
61
+
62
+ Playback completion is reported only when the server confirms it through
63
+ ``utterance_ended``: TTS audio is forwarded faster than realtime, so the
64
+ framework's speech handle must stay interruptible while the server-side
65
+ queue is still draining. The pending-report ledger lives on the owner so
66
+ reconnects and session teardown can settle interrupted segments.
67
+ """
68
+
60
69
  def __init__(self, owner: "AvatarSession"):
61
70
  super().__init__(
62
71
  label="FaceModeAudioOutput",
@@ -66,6 +75,9 @@ class _FaceModeAudioOutput(AudioOutput):
66
75
  )
67
76
  self.owner = owner
68
77
  self._utterance_started = False
78
+ self._segment_duration = 0.0
79
+ self._segment_started_at: float | None = None
80
+ self._end_task: asyncio.Task | None = None
69
81
 
70
82
  async def capture_frame(self, frame: rtc.AudioFrame) -> None:
71
83
  await self.owner._drain_control_tasks()
@@ -74,23 +86,75 @@ class _FaceModeAudioOutput(AudioOutput):
74
86
  await self.owner._ensure_protocol_started(frame.sample_rate, frame.num_channels)
75
87
  await self.owner._send_start_utterance()
76
88
  self._utterance_started = True
89
+ self._segment_duration = 0.0
90
+ self._segment_started_at = time.monotonic()
91
+ self.on_playback_started(created_at=time.time())
92
+ self._segment_duration += _frame_duration_seconds(frame)
77
93
  await self.owner._send_tts_audio(frame)
78
94
 
79
95
  def flush(self) -> None:
80
96
  super().flush()
81
- if self._utterance_started:
82
- self.owner._schedule_control(self._finish_utterance(), "facemode-end-utterance")
83
- self._utterance_started = False
97
+ if not self._utterance_started:
98
+ return
99
+ sequence = self.owner._next_sequence()
100
+ self.owner._register_pending_playback(
101
+ sequence, playback_position=self._segment_duration
102
+ )
103
+ self._end_task = self.owner._schedule_control(
104
+ self._end_utterance(sequence), "facemode-end-utterance"
105
+ )
106
+ self._utterance_started = False
84
107
 
85
108
  def clear_buffer(self) -> None:
86
- if self._utterance_started:
109
+ # The framework flushes before clearing, so an interrupted utterance
110
+ # usually already sent end_utterance. The server-side queue is still
111
+ # draining at that point and must be told to discard it; the cancel is
112
+ # chained after the end send so the wire order stays end-then-cancel.
113
+ streaming = self._utterance_started
114
+ has_unconfirmed_end = bool(self.owner._pending_playback)
115
+ if streaming or has_unconfirmed_end:
116
+ sequence = self.owner._next_sequence()
87
117
  self.owner._schedule_control(
88
- self.owner._send_cancel_utterance(), "facemode-cancel-utterance"
118
+ self._cancel_utterance(
119
+ sequence, streaming, self._interrupted_position(), self._end_task
120
+ ),
121
+ "facemode-cancel-utterance",
89
122
  )
90
123
  self._utterance_started = False
91
-
92
- async def _finish_utterance(self) -> None:
93
- await self.owner._send_end_utterance()
124
+ self._end_task = None
125
+
126
+ def _interrupted_position(self) -> float:
127
+ if self._segment_started_at is None:
128
+ return 0.0
129
+ elapsed = time.monotonic() - self._segment_started_at
130
+ return max(0.0, min(self._segment_duration, elapsed))
131
+
132
+ async def _end_utterance(self, sequence: int) -> None:
133
+ sent = await self.owner._send_end_utterance(sequence)
134
+ if not sent:
135
+ # The end never reached the server (e.g. the transport dropped into
136
+ # a reconnect first), so no confirmation can ever arrive; the
137
+ # segment is abandoned rather than completed.
138
+ self.owner._drop_pending_playback(sequence)
139
+
140
+ async def _cancel_utterance(
141
+ self,
142
+ sequence: int,
143
+ streaming: bool,
144
+ playback_position: float,
145
+ end_task: asyncio.Task | None,
146
+ ) -> None:
147
+ if end_task is not None and end_task is not asyncio.current_task():
148
+ with contextlib.suppress(Exception):
149
+ await end_task
150
+ # A server-side cancel wipes every queued speech/end marker, so each
151
+ # unconfirmed end settles here as interrupted; its own utterance_ended
152
+ # can never arrive. The cancel control frame itself is not a captured
153
+ # segment and gets no ledger entry - its confirmation is ignored.
154
+ self.owner._settle_unconfirmed_playback()
155
+ if streaming:
156
+ self.on_playback_finished(playback_position=playback_position, interrupted=True)
157
+ await self.owner._send_cancel_utterance(sequence)
94
158
 
95
159
 
96
160
  class AvatarSession(BaseAvatarSession):
@@ -140,6 +204,8 @@ class AvatarSession(BaseAvatarSession):
140
204
  self._audio_sample_rate: int | None = None
141
205
  self._audio_channels: int | None = None
142
206
  self._session_log_marker: str | None = None
207
+ self._audio_output: _FaceModeAudioOutput | None = None
208
+ self._pending_playback: dict[int, dict[str, Any]] = {}
143
209
  self._sequence = 0
144
210
  self._started_once = False
145
211
  self._stopped = False
@@ -229,7 +295,8 @@ class AvatarSession(BaseAvatarSession):
229
295
  )
230
296
  if getattr(agent_session, "output", None) is None:
231
297
  raise FaceModeAPIError("LiveKit AgentSession output is not initialized")
232
- agent_session.output.replace_audio_tail(_FaceModeAudioOutput(self))
298
+ self._audio_output = _FaceModeAudioOutput(self)
299
+ agent_session.output.replace_audio_tail(self._audio_output)
233
300
  self._join_task = asyncio.create_task(
234
301
  self._wait_for_video_track(), name="facemode-avatar-join"
235
302
  )
@@ -262,6 +329,7 @@ class AvatarSession(BaseAvatarSession):
262
329
  if self._stopped:
263
330
  return
264
331
  self._stopped = True
332
+ self._fail_pending_playback()
265
333
  await self._cancel_task(self._keepalive_task)
266
334
  self._keepalive_task = None
267
335
  await self._cancel_task(self._reconnect_task)
@@ -491,6 +559,7 @@ class AvatarSession(BaseAvatarSession):
491
559
  self._protocol_started.clear()
492
560
  self._protocol_response.clear()
493
561
  self._avatar_ready.clear()
562
+ self._fail_pending_playback()
494
563
  task = asyncio.create_task(self._reconnect(), name="facemode-ws-reconnect")
495
564
  self._reconnect_task = task
496
565
  return task
@@ -512,7 +581,12 @@ class AvatarSession(BaseAvatarSession):
512
581
  pending = None
513
582
  adopted = False
514
583
  try:
584
+ # A failed attempt records the error through _set_protocol_error,
585
+ # which also sets _protocol_response. Both must be re-armed
586
+ # together: clearing only the error leaves the event set, and
587
+ # _wait_for_send_ready would spin without ever yielding.
515
588
  self._protocol_error = None
589
+ self._protocol_response.clear()
516
590
  refreshed = await self._request_reconnect_session()
517
591
  self.session = refreshed
518
592
  pending = await self._connect_websocket()
@@ -521,6 +595,12 @@ class AvatarSession(BaseAvatarSession):
521
595
  await pending.send(self._start_message())
522
596
  await self._await_reconnect_started(pending)
523
597
  adopted = True
598
+ output = self._audio_output
599
+ if output is not None:
600
+ # The fresh socket has no utterance state. Clearing the flag
601
+ # makes the next captured frame re-declare start_utterance
602
+ # through the normal path, keeping the wire order correct.
603
+ output._utterance_started = False
524
604
  logger.info(
525
605
  "FaceMode WebSocket reconnected session=%s attempt=%s",
526
606
  self._session_log_marker,
@@ -587,13 +667,17 @@ class AvatarSession(BaseAvatarSession):
587
667
  async def _send_start_utterance(self) -> None:
588
668
  await self._send_control("start_utterance", self._next_sequence())
589
669
 
590
- async def _send_end_utterance(self) -> None:
591
- if self._protocol_started.is_set():
592
- await self._send_control("end_utterance", self._next_sequence())
670
+ async def _send_end_utterance(self, sequence: int) -> bool:
671
+ if not self._protocol_started.is_set():
672
+ return False
673
+ await self._send_control("end_utterance", sequence)
674
+ return True
593
675
 
594
- async def _send_cancel_utterance(self) -> None:
595
- if self._protocol_started.is_set():
596
- await self._send_control("cancel_utterance", self._next_sequence())
676
+ async def _send_cancel_utterance(self, sequence: int) -> bool:
677
+ if not self._protocol_started.is_set():
678
+ return False
679
+ await self._send_control("cancel_utterance", sequence)
680
+ return True
597
681
 
598
682
  async def _send_tts_audio(self, frame: rtc.AudioFrame) -> None:
599
683
  await self._ensure_protocol_started(frame.sample_rate, frame.num_channels)
@@ -792,6 +876,7 @@ class AvatarSession(BaseAvatarSession):
792
876
  elif message_type == "audio_ready":
793
877
  self._avatar_ready.set()
794
878
  elif message_type == "utterance_ended":
879
+ self._resolve_pending_playback(message)
795
880
  logger.debug(
796
881
  "FaceMode utterance ended seq=%s cycles=%s",
797
882
  message.get("seq"),
@@ -808,6 +893,7 @@ class AvatarSession(BaseAvatarSession):
808
893
  elif message_type == "ended":
809
894
  self._session_ended.set()
810
895
  self._protocol_response.set()
896
+ self._fail_pending_playback()
811
897
  elif message_type == "error":
812
898
  protocol_error = FaceModeProtocolError(
813
899
  f"{message.get('code', 'INTERNAL_ERROR')}: {message.get('message', 'FaceMode error')}"
@@ -872,10 +958,11 @@ class AvatarSession(BaseAvatarSession):
872
958
  for publication in participant.track_publications.values()
873
959
  )
874
960
 
875
- def _schedule_control(self, coroutine, name: str) -> None:
961
+ def _schedule_control(self, coroutine, name: str) -> asyncio.Task:
876
962
  task = asyncio.create_task(coroutine, name=name)
877
963
  self._control_tasks.add(task)
878
964
  task.add_done_callback(self._control_task_done)
965
+ return task
879
966
 
880
967
  def _control_task_done(self, task: asyncio.Task) -> None:
881
968
  self._control_tasks.discard(task)
@@ -916,8 +1003,67 @@ class AvatarSession(BaseAvatarSession):
916
1003
  def _set_protocol_error(self, error: FaceModeError) -> None:
917
1004
  if self._protocol_error is None:
918
1005
  self._protocol_error = error
1006
+ self._fail_pending_playback()
919
1007
  self._protocol_response.set()
920
1008
 
1009
+ def _register_pending_playback(self, sequence: int, *, playback_position: float) -> None:
1010
+ self._pending_playback[sequence] = {"position": playback_position}
1011
+
1012
+ def _report_playback_finished(self, entry: dict[str, Any], *, interrupted: bool) -> None:
1013
+ output = self._audio_output
1014
+ if output is None:
1015
+ return
1016
+ output.on_playback_finished(
1017
+ playback_position=float(entry.get("position", 0.0)),
1018
+ interrupted=interrupted,
1019
+ )
1020
+
1021
+ def _resolve_pending_playback(self, message: Mapping[str, Any]) -> None:
1022
+ """Match one server ``utterance_ended`` to its segment report.
1023
+
1024
+ The echoed sequence is the protocol sequence of the end/cancel control
1025
+ frame the server consumed. Confirmations for entries already settled
1026
+ by a cancel, reconnect, or teardown are unmatched and ignored.
1027
+ """
1028
+ sequence = message.get("seq")
1029
+ entry = self._pending_playback.pop(sequence, None) if isinstance(sequence, int) else None
1030
+ if entry is None:
1031
+ return
1032
+ self._report_playback_finished(entry, interrupted=False)
1033
+
1034
+ def _settle_unconfirmed_playback(self) -> None:
1035
+ """Report every end-confirmed-pending segment as interrupted.
1036
+
1037
+ A server-side cancel wipes all queued speech/end markers, so ends
1038
+ that have not been confirmed yet will never produce their own
1039
+ ``utterance_ended``. Each captured segment owes the framework exactly
1040
+ one playback report, so they are settled here before the cancel goes
1041
+ out; the cancel's own confirmation resolves the final segment.
1042
+ """
1043
+ unconfirmed = list(self._pending_playback)
1044
+ for sequence in unconfirmed:
1045
+ entry = self._pending_playback.pop(sequence, None)
1046
+ if entry is not None:
1047
+ self._report_playback_finished(entry, interrupted=True)
1048
+
1049
+ def _drop_pending_playback(self, sequence: int) -> None:
1050
+ """Settle one ledger entry as interrupted when its end never went out."""
1051
+ entry = self._pending_playback.pop(sequence, None)
1052
+ if entry is not None:
1053
+ self._report_playback_finished(entry, interrupted=True)
1054
+
1055
+ def _fail_pending_playback(self) -> None:
1056
+ """Settle every pending segment as interrupted.
1057
+
1058
+ Used when the transport drops or the session stops: the server
1059
+ discards in-flight utterances on disconnect, so no confirmation can
1060
+ ever arrive for them.
1061
+ """
1062
+ entries = list(self._pending_playback.values())
1063
+ self._pending_playback.clear()
1064
+ for entry in entries:
1065
+ self._report_playback_finished(entry, interrupted=True)
1066
+
921
1067
  def _raise_protocol_error(self) -> None:
922
1068
  if self._protocol_error is not None:
923
1069
  raise self._protocol_error
@@ -928,6 +1074,15 @@ class AvatarSession(BaseAvatarSession):
928
1074
  return sequence
929
1075
 
930
1076
 
1077
+ def _frame_duration_seconds(frame: rtc.AudioFrame) -> float:
1078
+ duration = getattr(frame, "duration", None)
1079
+ if isinstance(duration, (int, float)) and duration > 0:
1080
+ return float(duration)
1081
+ channels = max(int(frame.num_channels), 1)
1082
+ rate = max(int(frame.sample_rate), 1)
1083
+ return len(frame.data) / (2.0 * channels * rate)
1084
+
1085
+
931
1086
  def _token_identity_hint(token: str) -> str | None:
932
1087
  claims = _token_claims_hint(token)
933
1088
  identity = claims.get("sub") if claims else None
@@ -1,17 +1,17 @@
1
- """FaceMode LiveKit plugin exceptions."""
2
-
3
-
4
- class FaceModeError(RuntimeError):
5
- """Base error for FaceMode integration failures."""
6
-
7
-
8
- class FaceModeAPIError(FaceModeError):
9
- """Raised when the FaceMode REST API rejects a request."""
10
-
11
-
12
- class FaceModeProtocolError(FaceModeError):
13
- """Raised when the FaceMode WebSocket reports a protocol error."""
14
-
15
-
16
- class FaceModeNotReadyError(FaceModeError):
17
- """Raised when the avatar does not publish its video track in time."""
1
+ """FaceMode LiveKit plugin exceptions."""
2
+
3
+
4
+ class FaceModeError(RuntimeError):
5
+ """Base error for FaceMode integration failures."""
6
+
7
+
8
+ class FaceModeAPIError(FaceModeError):
9
+ """Raised when the FaceMode REST API rejects a request."""
10
+
11
+
12
+ class FaceModeProtocolError(FaceModeError):
13
+ """Raised when the FaceMode WebSocket reports a protocol error."""
14
+
15
+
16
+ class FaceModeNotReadyError(FaceModeError):
17
+ """Raised when the avatar does not publish its video track in time."""
@@ -0,0 +1 @@
1
+ __version__ = "0.3.1"
@@ -0,0 +1,101 @@
1
+ Metadata-Version: 2.4
2
+ Name: livekit-plugins-facemode
3
+ Version: 0.3.1
4
+ Summary: FaceMode avatar integration for LiveKit Agents
5
+ Author: FaceMode
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://facemode.io
8
+ Project-URL: Repository, https://github.com/facemode-by-infinitylevel/facemode-integrations
9
+ Keywords: livekit,agents,avatar,facemode,ai,video,realtime
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Programming Language :: Python :: 3.13
13
+ Classifier: Topic :: Multimedia :: Video
14
+ Requires-Python: >=3.13
15
+ Description-Content-Type: text/markdown
16
+ License-File: LICENSE
17
+ Requires-Dist: aiohttp<4,>=3.10
18
+ Requires-Dist: livekit<2,>=1.1
19
+ Requires-Dist: livekit-agents<2,>=1.7
20
+ Requires-Dist: websockets<17,>=14
21
+ Dynamic: license-file
22
+
23
+ # livekit-plugins-facemode
24
+
25
+ [FaceMode](https://facemode.io) avatar output for LiveKit Agents Python applications.
26
+
27
+ ## Install
28
+
29
+ ```bash
30
+ pip install livekit-plugins-facemode
31
+ ```
32
+
33
+ From this repository:
34
+
35
+ ```bash
36
+ pip install .
37
+ ```
38
+
39
+ Requires Python 3.13 or later, `livekit>=1.1,<2`, and `livekit-agents>=1.7,<2`.
40
+
41
+ ## Usage
42
+
43
+ The host application supplies a server-side LiveKit room object. The room token
44
+ must grant the FaceMode worker permission to join, publish, and subscribe in the
45
+ customer room. Keep the token on the server and never log it or expose it to a
46
+ browser client.
47
+
48
+ ```python
49
+ import os
50
+
51
+ from livekit.agents import Agent, AgentSession, room_io
52
+ from livekit_plugins_facemode import AvatarSession
53
+
54
+ avatar = AvatarSession(
55
+ api_key=os.environ["FACEMODE_API_KEY"],
56
+ avatar_id=os.environ.get("FACEMODE_AVATAR_ID", ""),
57
+ )
58
+
59
+ await ctx.connect()
60
+ await avatar.start(
61
+ agent_session,
62
+ ctx.room,
63
+ room={
64
+ "type": "livekit",
65
+ "url": os.environ["LIVEKIT_URL"],
66
+ "token": os.environ["LIVEKIT_TOKEN"],
67
+ },
68
+ )
69
+ await agent_session.start(
70
+ agent=Agent(instructions="You are a helpful assistant."),
71
+ room=ctx.room,
72
+ room_options=room_io.RoomOptions(audio_output=False),
73
+ )
74
+ await avatar.wait_for_join()
75
+ ```
76
+
77
+ `AvatarSession.start()` creates a FaceMode session with the room object. The create response normally returns `ready: true` with the ingestion `url` and a one-time `wsToken` (about 15 minute expiry), so no polling happens in the common path. If worker assignment is still pending, the plugin polls the session endpoint with bounded backoff for up to 240 seconds and stops immediately on `FAILED`/`ENDED` worker states. The initial response's room credentials remain in memory and are not expected in the polling response.
78
+
79
+ The ingestion WebSocket handshake uses the `Sec-WebSocket-Protocol` subprotocol `facemode.<wsToken>` with a 240 second open timeout. When the backend returns optional `ingestion.headers`, the plugin forwards them during the handshake. It disables compression and native WebSocket keepalives in favor of the canonical application `ping`/`pong` messages after negotiation.
80
+
81
+ Pass `input_provider` (one of `deepgram`, `gemini`, `gnani`, `elevenlabs`, `openai`, `cartesia`, `sarvam`, `custom`) to `AvatarSession` when the session should pin a specific upstream input provider; it is omitted from the request otherwise.
82
+
83
+ If the WebSocket transport drops after the protocol has started, the plugin auto-reconnects in the background: it POSTs the session reconnect endpoint for a fresh one-time `wsToken` (a consumed token is never reused), opens a new socket with `facemode.<newToken>`, re-sends the canonical `start` message, and waits for `started` before resuming. Outgoing control `seq` numbers stay monotonic across the reconnect and buffered audio is not replayed. Reconnect is bounded to 2 attempts with backoff and is single-flight; exhaustion surfaces a typed `FaceModeNotReadyError`/`FaceModeAPIError`. Intentional `stop()`, a canonical `ended`, fatal protocol errors, and drops before the first negotiation do not reconnect.
84
+
85
+ Every TTS frame is sent as canonical PCM audio. The plugin locks sample rate and channel count at protocol negotiation and rejects a format change or unaligned 16-bit PCM afterward. `cancel_utterance` is sent when LiveKit interrupts the audio output. Graceful close sends `end_session` and waits briefly for canonical `ended`; `ended` is a protocol acknowledgement, not backend cleanup confirmation.
86
+
87
+ ## Token grants
88
+
89
+ The `room.token` value must allow the worker to join the customer room and
90
+ publish its avatar audio/video tracks. If the token uses a fixed participant
91
+ identity, use `avatar_participant_identity` and make the room policy allow that
92
+ identity. The worker does not create or replace the customer LiveKit room.
93
+
94
+ ## API URL
95
+
96
+ The default API URL is `https://api.facemode.io/api`. Set `api_url` for a
97
+ self-hosted or local backend.
98
+
99
+ ## License
100
+
101
+ Apache-2.0 - see [LICENSE](LICENSE). Part of the [facemode-integrations](https://github.com/facemode-by-infinitylevel/facemode-integrations) monorepo.
@@ -11,4 +11,5 @@ livekit_plugins_facemode.egg-info/SOURCES.txt
11
11
  livekit_plugins_facemode.egg-info/dependency_links.txt
12
12
  livekit_plugins_facemode.egg-info/requires.txt
13
13
  livekit_plugins_facemode.egg-info/top_level.txt
14
- test/test_ingestion.py
14
+ test/test_ingestion.py
15
+ test/test_playback.py
@@ -4,11 +4,17 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "livekit-plugins-facemode"
7
- version = "0.1.0"
7
+ version = "0.3.1"
8
8
  license = "Apache-2.0"
9
9
  license-files = ["LICENSE"]
10
+ readme = "README.md"
11
+ authors = [{name = "FaceMode"}]
12
+ keywords = ["livekit", "agents", "avatar", "facemode", "ai", "video", "realtime"]
10
13
  classifiers = [
11
- "Programming Language :: Python :: 3",
14
+ "Development Status :: 4 - Beta",
15
+ "Intended Audience :: Developers",
16
+ "Programming Language :: Python :: 3.13",
17
+ "Topic :: Multimedia :: Video",
12
18
  ]
13
19
 
14
20
  description = "FaceMode avatar integration for LiveKit Agents"
@@ -20,5 +26,9 @@ dependencies = [
20
26
  "websockets>=14,<17",
21
27
  ]
22
28
 
29
+ [project.urls]
30
+ Homepage = "https://facemode.io"
31
+ Repository = "https://github.com/facemode-by-infinitylevel/facemode-integrations"
32
+
23
33
  [tool.setuptools.packages.find]
24
34
  include = ["livekit_plugins_facemode*"]
@@ -0,0 +1,256 @@
1
+ import asyncio
2
+ import json
3
+ import unittest
4
+ from unittest.mock import patch
5
+
6
+ from livekit import rtc
7
+
8
+ from livekit_plugins_facemode import avatar as avatar_module
9
+ from livekit_plugins_facemode.avatar import AvatarSession
10
+ from livekit_plugins_facemode.models import LiveKitRoom, SessionDetails
11
+
12
+ from test_ingestion import _FakeWebSocket, _PostClient, _Response, _fake_connect
13
+
14
+
15
+ def _running_avatar(room):
16
+ """A session that already negotiated the canonical protocol once."""
17
+ avatar = AvatarSession(
18
+ api_key="api-key",
19
+ avatar_id="avatar-1",
20
+ api_url="https://api.example.test/api",
21
+ )
22
+ avatar.session = SessionDetails.from_api(
23
+ {
24
+ "sessionId": "session-123",
25
+ "room": room.to_payload(),
26
+ "workerStatus": "ACTIVE",
27
+ "ingestion": {
28
+ "ready": True,
29
+ "url": "wss://worker.example.test/ws/session-123",
30
+ "wsToken": "token-1",
31
+ },
32
+ }
33
+ )
34
+ avatar._websocket = _FakeWebSocket()
35
+ avatar._protocol_started.set()
36
+ avatar._protocol_response.set()
37
+ avatar._audio_sample_rate = 16000
38
+ avatar._audio_channels = 1
39
+ avatar._session_log_marker = "session-123"
40
+ return avatar
41
+
42
+
43
+ def _reconnect_response(token):
44
+ return _Response(
45
+ json.dumps(
46
+ {
47
+ "workerStatus": "ACTIVE",
48
+ "ingestion": {
49
+ "ready": True,
50
+ "url": "wss://worker.example.test/ws/session-123",
51
+ "wsToken": token,
52
+ "headers": {},
53
+ },
54
+ }
55
+ )
56
+ )
57
+
58
+
59
+ class _PlaybackHarness:
60
+ """Wires a running avatar to its audio output and captures playback reports."""
61
+
62
+ def __init__(self, avatar):
63
+ self.avatar = avatar
64
+ self.output = avatar_module._FaceModeAudioOutput(avatar)
65
+ avatar._audio_output = self.output
66
+ self.finished = []
67
+ self.output.on("playback_finished", self.finished.append)
68
+
69
+ def frame(self, samples=160, rate=16000):
70
+ return rtc.AudioFrame(
71
+ data=b"\x01\x00" * samples,
72
+ sample_rate=rate,
73
+ num_channels=1,
74
+ samples_per_channel=samples,
75
+ )
76
+
77
+ async def capture(self, count=2, samples=160, rate=16000):
78
+ for _ in range(count):
79
+ await self.output.capture_frame(self.frame(samples, rate))
80
+
81
+ def utterance_ended(self, seq, cancelled=False):
82
+ self.avatar._dispatch_message(
83
+ json.dumps(
84
+ {"type": "utterance_ended", "seq": seq, "cycles": 3, "cancelled": cancelled}
85
+ )
86
+ )
87
+
88
+ def control_types(self):
89
+ return [
90
+ m["type"]
91
+ for m in self.avatar._websocket.text_messages()
92
+ if m["type"] in ("start_utterance", "end_utterance", "cancel_utterance")
93
+ ]
94
+
95
+ def control_seq(self, message_type):
96
+ return next(
97
+ m["seq"]
98
+ for m in self.avatar._websocket.text_messages()
99
+ if m["type"] == message_type
100
+ )
101
+
102
+
103
+ class _RoomMixin:
104
+ def setUp(self):
105
+ self.room = LiveKitRoom(
106
+ url="wss://livekit.example.test",
107
+ token="worker-room-token",
108
+ name="room-123",
109
+ )
110
+
111
+
112
+ class LiveKitPlaybackReportingTests(_RoomMixin, unittest.IsolatedAsyncioTestCase):
113
+ async def test_playback_finished_waits_for_server_confirmation(self):
114
+ harness = _PlaybackHarness(_running_avatar(self.room))
115
+ await harness.capture(count=2) # 2 x 10ms at 16kHz = 0.02s of audio
116
+ harness.output.flush()
117
+ await harness.avatar._drain_control_tasks()
118
+
119
+ # end_utterance went out, but playback must not be reported yet
120
+ self.assertIn("end_utterance", harness.control_types())
121
+ self.assertEqual(harness.finished, [])
122
+
123
+ harness.utterance_ended(harness.control_seq("end_utterance"))
124
+ self.assertEqual(len(harness.finished), 1)
125
+ event = harness.finished[0]
126
+ self.assertFalse(event.interrupted)
127
+ self.assertAlmostEqual(event.playback_position, 0.02, places=3)
128
+
129
+ async def test_interruption_after_flush_sends_end_then_cancel(self):
130
+ harness = _PlaybackHarness(_running_avatar(self.room))
131
+ await harness.capture(count=2)
132
+ harness.output.flush()
133
+ harness.output.clear_buffer()
134
+ await harness.avatar._drain_control_tasks()
135
+
136
+ types = harness.control_types()
137
+ self.assertIn("end_utterance", types)
138
+ self.assertIn("cancel_utterance", types)
139
+ self.assertLess(types.index("end_utterance"), types.index("cancel_utterance"))
140
+
141
+ # exactly one report for the single captured segment, interrupted
142
+ self.assertEqual(len(harness.finished), 1)
143
+ self.assertTrue(harness.finished[0].interrupted)
144
+
145
+ async def test_confirmed_completion_then_idle_interruption_sends_no_cancel(self):
146
+ harness = _PlaybackHarness(_running_avatar(self.room))
147
+ await harness.capture(count=1)
148
+ harness.output.flush()
149
+ await harness.avatar._drain_control_tasks()
150
+ harness.utterance_ended(harness.control_seq("end_utterance"))
151
+ self.assertEqual(len(harness.finished), 1)
152
+
153
+ # playback fully confirmed: a later stray clear_buffer is a no-op
154
+ harness.output.clear_buffer()
155
+ await harness.avatar._drain_control_tasks()
156
+ self.assertNotIn("cancel_utterance", harness.control_types())
157
+ self.assertEqual(len(harness.finished), 1)
158
+
159
+ async def test_reconnect_settles_pending_playback_as_interrupted(self):
160
+ harness = _PlaybackHarness(_running_avatar(self.room))
161
+ await harness.capture(count=2)
162
+ harness.output.flush()
163
+ await harness.avatar._drain_control_tasks()
164
+ self.assertEqual(harness.finished, [])
165
+
166
+ # transport drops while the protocol is still up, as in the receiver path
167
+ harness.avatar._start_reconnect()
168
+ self.assertEqual(len(harness.finished), 1)
169
+ self.assertTrue(harness.finished[0].interrupted)
170
+ harness.avatar._reconnect_task.cancel()
171
+ try:
172
+ await harness.avatar._reconnect_task
173
+ except asyncio.CancelledError:
174
+ pass
175
+
176
+ async def test_end_dropped_during_reconnect_settles_segment(self):
177
+ harness = _PlaybackHarness(_running_avatar(self.room))
178
+ await harness.capture(count=1)
179
+ # simulate transport loss before the end send executes: the protocol
180
+ # is down, so end_utterance silently cannot go out
181
+ harness.avatar._protocol_started.clear()
182
+ harness.output.flush()
183
+ await harness.avatar._drain_control_tasks()
184
+
185
+ self.assertNotIn("end_utterance", harness.control_types())
186
+ self.assertEqual(len(harness.finished), 1)
187
+ self.assertTrue(harness.finished[0].interrupted)
188
+ self.assertEqual(harness.avatar._pending_playback, {})
189
+
190
+ async def test_pipelined_segments_each_report_exactly_once(self):
191
+ harness = _PlaybackHarness(_running_avatar(self.room))
192
+ # segment A completes input-side
193
+ await harness.capture(count=1)
194
+ harness.output.flush()
195
+ await harness.avatar._drain_control_tasks()
196
+ # segment B starts before A's confirmation arrives, then interruption
197
+ await harness.capture(count=1)
198
+ harness.output.flush()
199
+ harness.output.clear_buffer()
200
+ await harness.avatar._drain_control_tasks()
201
+
202
+ self.assertEqual(len(harness.finished), 2)
203
+ self.assertTrue(all(ev.interrupted for ev in harness.finished))
204
+ self.assertEqual(harness.avatar._pending_playback, {})
205
+
206
+ async def test_unmatched_utterance_ended_is_ignored(self):
207
+ harness = _PlaybackHarness(_running_avatar(self.room))
208
+ harness.utterance_ended(999)
209
+ self.assertEqual(harness.finished, [])
210
+
211
+
212
+ class LiveKitReconnectRetryTests(_RoomMixin, unittest.IsolatedAsyncioTestCase):
213
+ async def test_retry_rearms_protocol_response_event(self):
214
+ """A failed attempt sets _protocol_response through the error path; the
215
+ next attempt must clear it or _wait_for_send_ready spins freely."""
216
+ avatar = _running_avatar(self.room)
217
+ # first socket negotiates with the WRONG session id: the error path
218
+ # records a protocol error, which also sets the response event
219
+ bad_socket = _FakeWebSocket(session_id="wrong-session")
220
+ good_socket = _FakeWebSocket(session_id="session-123")
221
+ client = _PostClient(
222
+ [_reconnect_response("token-2"), _reconnect_response("token-3")]
223
+ )
224
+ event_states = []
225
+ original_request = avatar._request_reconnect_session
226
+
227
+ async def recording_request():
228
+ event_states.append(avatar._protocol_response.is_set())
229
+ return await original_request()
230
+
231
+ avatar._request_reconnect_session = recording_request
232
+
233
+ with (
234
+ patch(
235
+ "livekit_plugins_facemode.avatar.websockets.connect",
236
+ _fake_connect([bad_socket, good_socket], []),
237
+ ),
238
+ patch(
239
+ "livekit_plugins_facemode.avatar.aiohttp.ClientSession",
240
+ return_value=client,
241
+ ),
242
+ ):
243
+ avatar._protocol_started.clear()
244
+ avatar._protocol_response.clear()
245
+ await avatar._reconnect()
246
+
247
+ # reconnect eventually succeeded on the good socket
248
+ self.assertTrue(avatar._protocol_started.is_set())
249
+ self.assertIsNone(avatar._protocol_error)
250
+ # two attempts happened; the second must have re-armed a cleared event
251
+ self.assertEqual(len(event_states), 2)
252
+ self.assertFalse(event_states[1])
253
+
254
+
255
+ if __name__ == "__main__":
256
+ unittest.main()
@@ -1,13 +0,0 @@
1
- Copyright © 2026 InfinityLevel OPC Private Limited
2
-
3
- Licensed under the Apache License, Version 2.0 (the "License");
4
- you may not use this file except in compliance with the License.
5
- You may obtain a copy of the License at
6
-
7
- http://www.apache.org/licenses/LICENSE-2.0
8
-
9
- Unless required by applicable law or agreed to in writing, software
10
- distributed under the License is distributed on an "AS IS" BASIS,
11
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
- See the License for the specific language governing permissions and
13
- limitations under the License.
@@ -1,13 +0,0 @@
1
- Metadata-Version: 2.4
2
- Name: livekit-plugins-facemode
3
- Version: 0.1.0
4
- Summary: FaceMode avatar integration for LiveKit Agents
5
- License-Expression: Apache-2.0
6
- Classifier: Programming Language :: Python :: 3
7
- Requires-Python: >=3.13
8
- License-File: LICENSE
9
- Requires-Dist: aiohttp<4,>=3.10
10
- Requires-Dist: livekit<2,>=1.1
11
- Requires-Dist: livekit-agents<2,>=1.7
12
- Requires-Dist: websockets<17,>=14
13
- Dynamic: license-file
@@ -1 +0,0 @@
1
- __version__ = "0.1.0"
@@ -1,13 +0,0 @@
1
- Metadata-Version: 2.4
2
- Name: livekit-plugins-facemode
3
- Version: 0.1.0
4
- Summary: FaceMode avatar integration for LiveKit Agents
5
- License-Expression: Apache-2.0
6
- Classifier: Programming Language :: Python :: 3
7
- Requires-Python: >=3.13
8
- License-File: LICENSE
9
- Requires-Dist: aiohttp<4,>=3.10
10
- Requires-Dist: livekit<2,>=1.1
11
- Requires-Dist: livekit-agents<2,>=1.7
12
- Requires-Dist: websockets<17,>=14
13
- Dynamic: license-file