Skip to content

feat: add FaceMode avatar plugin - #3093

Open
prajwaldkadam wants to merge 6 commits into
livekit:mainfrom
facemode-by-infinitylevel:plugins/facemode-avatar
Open

prajwaldkadam wants to merge 6 commits into
livekit:mainfrom
facemode-by-infinitylevel:plugins/facemode-avatar

Conversation

@prajwaldkadam

Copy link
Copy Markdown

Docs | FaceMode | Companion Python plugin: livekit/agents#8826

Description

Adds @livekit/agents-plugin-facemode, a remote avatar integration for FaceMode, a real-time lip-synced avatar API for voice agents. Built and maintained by the FaceMode team at InfinityLevel (@prajwaldkadam, founder).

Like the other avatar plugins, the agent's audio output is routed to the avatar worker, which joins the room and publishes synchronized audio + video. FaceMode ingests audio over a direct WebSocket connection (PCM s16le with a negotiated start/utterance lifecycle) instead of LiveKit data streams - the ingestion protocol is implemented client-side in this plugin, with keepalive, server-confirmed playback completion, interruption handling via utterance cancellation, and bounded single-flight reconnect with one-time token refresh.

The worker token is minted in-process from LIVEKIT_API_KEY/LIVEKIT_API_SECRET, matching the protoface pattern - the LiveKit secret never leaves the agent process.

This is the Node.js companion to the Python plugin already in review at livekit/agents#8826. The ingestion protocol and production deployments are shared across both, so behavior is consistent between the two implementations.

Usage

import * as facemode from '@livekit/agents-plugin-facemode';

const avatar = new facemode.AvatarSession({ avatarId: 'your-avatar-id' });
await avatar.start(session, ctx.room);

Changes Made

  • plugins/facemode/ - the plugin, mirroring the protoface/lemonslice plugin layout (tsup build, api-extractor, vitest unit tests, changeset)
  • pnpm-lock.yaml + turbo.json wiring for the new workspace package

Configuration:

  • FACEMODE_API_KEY - required
  • FACEMODE_API_URL - optional, defaults to the public FaceMode API
  • LIVEKIT_URL, LIVEKIT_API_KEY, LIVEKIT_API_SECRET - used to mint the avatar worker token in-process

Notable implementation points:

  • Playback completion is reported to the framework only when the server confirms the drain through utterance_ended (echoed protocol sequence), so speech handles stay interruptible while the server-side queue plays out - audio is forwarded faster than realtime.
  • Interruptions send cancel_utterance even when the framework flushes before clearing (end-then-cancel wire order), which aborts the server-side queue instead of letting the avatar talk over the user.
  • Reconnect re-declares utterance state on the fresh socket so post-reconnect audio stays inside the utterance lifecycle.

Pre-Review Checklist

  • Build passes: build, lint, prettier, api-extractor, and vitest all pass locally
  • AI-generated code reviewed: Removed unnecessary comments and ensured code quality
  • Changes explained: All changes are properly documented and justified above
  • Scope appropriate: All changes relate to the PR title
  • Video demo: happy to record one or walk through a live session on request

Testing

  • Automated tests added/updated (vitest unit tests: wire format, token minting, playback ledger, interruption ordering, reconnect settlement)
  • All tests pass (13/13)
  • restaurant_agent.ts / realtime_agent.ts - not affected (new plugin, no shared-code changes)

The production counterpart of this protocol stack is verified end-to-end against the live FaceMode service: normal utterance completion, interruption drain-abort, and reconnect + redeclaration were all exercised against the real ingestion server this week.

Additional Notes

To validate end-to-end: sign up at console.facemode.io/signup (600 free trial credits, no card required), create an API key, pick a default avatar in the console, and run any agent with the snippet above. The full path is documented in the quickstart. Happy to jump on a live walkthrough or help with any setup questions - just ask here in the PR.


Note to reviewers: Please ensure the pre-review checklist is completed before starting your review.

prajwaldkadam and others added 2 commits November 28, 2026 17:54
Adds @livekit/agents-plugin-facemode: an avatar session that creates a
hosted FaceMode session, mints the avatar worker token in-process, and
streams TTS audio over the ingestion WebSocket protocol with bounded
single-flight reconnect.
… handling

- report playback finished only on server utterance_ended confirmation so
  speech handles stay interruptible while the server-side queue drains
- send cancel_utterance on interruption even after end_utterance went out,
  chained end-then-cancel; settle wiped segments exactly once
- settle unconfirmed playback on reconnect, session end, and stop
- re-declare utterance state after a successful reconnect

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
@prajwaldkadam
prajwaldkadam requested a review from a team as a code owner November 29, 2026 13:42
@changeset-bot

changeset-bot Bot commented Nov 29, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 0a7449c

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 43 packages
Name Type
@livekit/agents-plugin-facemode Patch
@livekit/agents Patch
@livekit/agents-plugin-anam Patch
@livekit/agents-plugin-anthropic Patch
@livekit/agents-plugin-assemblyai Patch
@livekit/agents-plugin-azure Patch
@livekit/agents-plugin-baseten Patch
@livekit/agents-plugin-bey Patch
@livekit/agents-plugin-cartesia Patch
@livekit/agents-plugin-cerebras Patch
@livekit/agents-plugin-deepgram Patch
@livekit/agents-plugin-did Patch
@livekit/agents-plugin-elevenlabs Patch
@livekit/agents-plugin-fishaudio Patch
@livekit/agents-plugin-google Patch
@livekit/agents-plugin-hume Patch
@livekit/agents-plugin-inworld Patch
@livekit/agents-plugin-krisp Patch
@livekit/agents-plugin-lemonslice Patch
@livekit/agents-plugin-liveavatar Patch
@livekit/agents-plugin-livekit Patch
@livekit/agents-plugin-meta Patch
@livekit/agents-plugin-minimax Patch
@livekit/agents-plugin-mistral Patch
@livekit/agents-plugin-mistralai Patch
@livekit/agents-plugin-neuphonic Patch
@livekit/agents-plugin-nvidia Patch
@livekit/agents-plugin-openai Patch
@livekit/agents-plugin-perplexity Patch
@livekit/agents-plugin-phonic Patch
@livekit/agents-plugin-protoface Patch
@livekit/agents-plugin-resemble Patch
@livekit/agents-plugin-rime Patch
@livekit/agents-plugin-runway Patch
@livekit/agents-plugin-sarvam Patch
@livekit/agents-plugin-silero Patch
@livekit/agents-plugin-soniox Patch
@livekit/agents-plugin-speechify Patch
@livekit/agents-plugin-synthesia Patch
@livekit/agents-plugin-tavus Patch
@livekit/agents-plugins-test Patch
@livekit/agents-plugin-trugen Patch
@livekit/agents-plugin-xai Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

devin-ai-integration[bot]

This comment was marked as resolved.

devin-ai-integration[bot]

This comment was marked as resolved.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
@CLAassistant

Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you all sign our Contributor License Agreement before we can accept your contribution.
1 out of 2 committers have signed the CLA.

✅ prajwaldkadam
❌ pk24100
You have signed the CLA already but the status is still pending? Let us recheck it.

@devin-ai-integration devin-ai-integration Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note

Newer findings are available below. Devin Review posted a newer report on this PR, in addition to the findings presented here.

Devin Review found 4 new potential issues.

9 flags not posted on this PR by your GitHub settings — view them in Devin Review. (Configure)

Devin Review

};
const onAbort = (): void => {
cleanup();
socket.terminate();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 Job crash during avatar cancellation

During the WebSocket handshake, onAbort removes the error listener before terminating the socket. ws then emits an unhandled error that crashes the job process.

Learn more

The job registers avatar shutdown through the base startup method. FaceMode passes the startup signal to the ingestion handshake, and stop aborts that signal. ws 8.21.3 schedules an error event when terminate() aborts a connecting socket. Rejecting the handshake promise does not handle that event after cleanup() removes the original listener. The test double emits only close on termination.

Example: The agent shuts down after the WebSocket upgrade request goes out but before the server responds. The startup promise rejects, then the unhandled socket error kills the job process.

Recommended fix: Install an error listener before terminating the discarded socket. Add a cancellation test that emits error asynchronously before close, as ws does during a cancelled handshake.

Suggested change
socket.terminate();
socket.once('error', () => undefined);
socket.terminate();

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

Comment on lines +360 to +362
startupSignal,
);
startupSessionId = this.session.sessionId;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 Orphaned avatar session after cancellation

startSession aborts the response read if shutdown arrives after FaceMode creates the session but before the client reads its ID. rollbackStart then has no session ID to delete.

Learn more

FaceModeAPI.startSession sends a POST that creates a remote session. The startup signal cancels both the HTTP request and the response body read, but cannot undo a creation that FaceMode has already committed. The client learns the session ID from the parsed response. rollbackStart skips deletion when it has no ID.

Example: FaceMode provisions a worker and begins sending the response. The agent shuts down before the body arrives. The request rejects, the client discards the ID, and no DELETE goes out.

Recommended fix: Once a create request is in flight, let it finish under its normal timeout and retain its ID for cleanup before propagating startup cancellation. If the provider supports a client-supplied ID or idempotency key with lookup, use it to reconcile ambiguous creation outcomes.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

async stop(): Promise<void> {
if (this.stopped) return;
this.stopped = true;
this.startupAbortController?.abort();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Avatar shutdown returns before deletion

During ingestion polling, stop aborts startup without waiting for rollbackStart to delete the created session. Awaiting shutdown can return before deletion starts.

Learn more

The base avatar class awaits aclose() during job shutdown. aclose delegates to stop, but only the startup catch deletes the known session via rollbackStart. During ingestion polling, startup cannot reach that catch until its current sleep finishes. During protocol negotiation, closing the socket through stop also leaves startup waiting for a timeout. The polling test waits for startup after awaiting stop, so it does not verify that shutdown itself waits for deletion.

Example: An agent calls stop() while the startup poll is in its two-second backoff. Shutdown resolves while the poll still sleeps, and the application can exit without sending the DELETE.

Recommended fix: Give stop() a startup cleanup promise to await and keep rollback independent of stop() to avoid a wait cycle. Make polling sleeps and the negotiation wait abort-aware. Verify that awaiting stop() alone guarantees deletion has been attempted for a known session ID.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

Comment thread plugins/facemode/src/avatar.ts Resolved
Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

@devin-ai-integration devin-ai-integration Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Devin Review found 1 new potential issue.

10 flags not posted on this PR by your GitHub settings — view them in Devin Review. (Configure)

Devin Review

Comment on lines +521 to +524
if (!socket || socket.readyState !== WebSocket.OPEN) {
await this.reconnect();
if (this.protocolError) throw this.protocolError;
if (this.protocolStartedAck) return;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Late audio from an interrupted reply

If the first realtime reply is interrupted during a slow reconnect, ensureProtocolStarted still lets its pending frame through. Realtime interruption clears the buffer after two seconds, before FaceMode has an utterance to cancel. The avatar can then play audio from the cancelled reply.

Learn more

The pre-negotiation timer closes the socket after 30 seconds without an audio format. FaceModeAudioOutput.captureFrame awaits reconnection before declaring its first utterance. When realtime speech is interrupted, the interruption handler waits up to two seconds before clearing the output. clearBuffer does nothing when there is no declared utterance or pending end. If the reconnect succeeds later, the waiting frame starts an utterance, and forwardAudio flushes it even though the forwarding signal has been aborted.

Example: A realtime agent waits 40 seconds for the user to speak. Its first reply starts a reconnect, and the user interrupts while the replacement socket is negotiating. The two-second cancellation wait expires. The server acknowledges negotiation a second later, and FaceMode receives and plays the cancelled reply’s first frame.

Recommended fix: Invalidate pending captures when the output buffer is cleared, including before any utterance starts. Check that invalidation after negotiation and before sending audio, and settle the abandoned playback segment so the interrupted speech can complete. Add a realtime activity test that delays the replacement socket’s acknowledgement past the cancellation timeout and verifies that no cancelled audio is sent.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants