Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 54 additions & 0 deletions agents/src/voice/agent_session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ export interface VoiceOptions {
maxEndpointingDelay: number;
maxToolSteps: number;
preemptiveGeneration: boolean;
userAwayTimeout?: number | null;
}

const defaultVoiceOptions: VoiceOptions = {
Expand All @@ -69,6 +70,7 @@ const defaultVoiceOptions: VoiceOptions = {
maxEndpointingDelay: 6000,
maxToolSteps: 3,
preemptiveGeneration: false,
userAwayTimeout: 15.0,
} as const;

export type TurnDetectionMode = 'stt' | 'vad' | 'realtime_llm' | 'manual' | _TurnDetector;
Expand Down Expand Up @@ -123,6 +125,7 @@ export class AgentSession<
private _output: AgentOutput;

private closingTask: Promise<void> | null = null;
private userAwayTimer: NodeJS.Timeout | null = null;

constructor(opts: AgentSessionOptions<UserData>) {
super();
Expand Down Expand Up @@ -167,6 +170,8 @@ export class AgentSession<
// This is the "global" chat context, it holds the entire conversation history
this._chatCtx = ChatContext.empty();
this.options = { ...defaultVoiceOptions, ...voiceOptions };

this.on(AgentSessionEventTypes.UserInputTranscribed, this._onUserInputTranscribed.bind(this));
}

get input(): AgentInput {
Expand Down Expand Up @@ -416,6 +421,14 @@ export class AgentSession<

const oldState = this._agentState;
this._agentState = state;

// Handle user away timer based on state changes
if (state === 'listening' && this.userState === 'listening') {
this._setUserAwayTimer();
} else {
this._cancelUserAwayTimer();
}

this.emit(
AgentSessionEventTypes.AgentStateChanged,
createAgentStateChangedEvent(oldState, state),
Expand All @@ -430,6 +443,14 @@ export class AgentSession<

const oldState = this.userState;
this.userState = state;

// Handle user away timer based on state changes
if (state === 'listening' && this._agentState === 'listening') {
this._setUserAwayTimer();
} else {
this._cancelUserAwayTimer();
}

this.emit(
AgentSessionEventTypes.UserStateChanged,
createUserStateChangedEvent(oldState, state),
Expand All @@ -451,6 +472,37 @@ export class AgentSession<

private onTextOutputChanged(): void {}

private _setUserAwayTimer(): void {
this._cancelUserAwayTimer();

if (this.options.userAwayTimeout === null || this.options.userAwayTimeout === undefined) {
return;
}

if (this.roomIO && !this.roomIO.isParticipantAvailable) {
return;
}

this.userAwayTimer = setTimeout(() => {
this.logger.debug('User away timeout triggered');
this._updateUserState('away');
}, this.options.userAwayTimeout * 1000);
}

private _cancelUserAwayTimer(): void {
if (this.userAwayTimer !== null) {
clearTimeout(this.userAwayTimer);
this.userAwayTimer = null;
}
}

private _onUserInputTranscribed(ev: UserInputTranscribedEvent): void {
if (this.userState === 'away' && ev.isFinal) {
Copy link
Contributor

Choose a reason for hiding this comment

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

Can we discard checking ev.isFinal? So we can turn away state back much quicker as soon as user starts speaking

this.logger.debug('User returned from away state due to speech input');
this._updateUserState('listening');
Copy link
Contributor

Choose a reason for hiding this comment

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

Should this be "speaking"?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Re this and the above comment, happy to make this change.
I was however, trying to keep this in parity of the python implementation

https://github.com/livekit/agents/blob/main/livekit-agents/livekit/agents/voice/agent_session.py#L1109-L1113

Do you feel like we should still be adjusting?

Copy link
Contributor

Choose a reason for hiding this comment

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

oh I see, in this case let's keep this in parity with python.

}
}

private async closeImpl(
reason: CloseReason,
error: RealtimeModelError | LLMError | TTSError | STTError | null = null,
Expand All @@ -460,6 +512,8 @@ export class AgentSession<
return;
}

this._cancelUserAwayTimer();

if (this.activity) {
if (!drain) {
try {
Expand Down
4 changes: 4 additions & 0 deletions agents/src/voice/room_io/room_io.ts
Original file line number Diff line number Diff line change
Expand Up @@ -369,6 +369,10 @@ export class RoomIO {
return this.transcriptionSynchronizer.textOutput;
}

get isParticipantAvailable(): boolean {
return this.participantAvailableFuture.done;
}

/** Switch to a different participant */
setParticipant(participantIdentity: string | null) {
this.logger.debug({ participantIdentity }, 'setting participant');
Expand Down
104 changes: 104 additions & 0 deletions examples/src/idle_user_timeout_example.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
// SPDX-FileCopyrightText: 2025 LiveKit, Inc.
//
// SPDX-License-Identifier: Apache-2.0

/**
* Minimal example demonstrating idle user timeout functionality.
* Direct port of: https://github.com/livekit/agents/blob/main/examples/voice_agents/inactive_user.py
*/
import {
type JobContext,
type JobProcess,
WorkerOptions,
cli,
defineAgent,
log,
voice,
} from '@livekit/agents';
import * as openai from '@livekit/agents-plugin-openai';
import * as silero from '@livekit/agents-plugin-silero';
import { fileURLToPath } from 'node:url';

export default defineAgent({
prewarm: async (proc: JobProcess) => {
proc.userData.vad = await silero.VAD.load();
},
entry: async (ctx: JobContext) => {
const logger = log();
const vad = ctx.proc.userData.vad! as silero.VAD;

const session = new voice.AgentSession({
vad,
llm: new openai.LLM({ model: 'gpt-4o-mini' }),
stt: 'assemblyai/universal-streaming:en',
tts: 'cartesia/sonic-2:9626c31c-bec5-4cca-baa8-f8ba9e84c8bc',

voiceOptions: {
userAwayTimeout: 12.5,
},
});

let inactivityController: AbortController | null = null;

const userPresenceTask = async (signal: AbortSignal): Promise<void> => {
try {
for (let i = 0; i < 3; i++) {
if (signal.aborted) return;

const reply = await session.generateReply({
instructions:
'The user has been inactive. Politely check if the user is still present.',
});

await reply.waitForPlayout();

await new Promise<void>((resolve, reject) => {
const timeout = setTimeout(resolve, 10000);
signal.addEventListener('abort', () => {
clearTimeout(timeout);
reject(new Error('Aborted'));
});
});
}

if (!signal.aborted) {
await session.close();
}
} catch (error) {
if (error instanceof Error && error.message === 'Aborted') {
logger.info({ error }, 'User presence task aborted');
// Task was cancelled, which is expected
return;
}
throw error;
}
};

session.on(voice.AgentSessionEventTypes.UserStateChanged, (event) => {
logger.info({ event }, 'User state changed');
if (event.newState === 'away') {
if (inactivityController) {
inactivityController.abort();
}

// Start new task with fresh controller
inactivityController = new AbortController();
userPresenceTask(inactivityController.signal);
return;
}

if (inactivityController) {
inactivityController.abort();
inactivityController = null;
}
});

const agent = new voice.Agent({
instructions: 'You are a helpful assistant.',
});

await session.start({ agent, room: ctx.room });
},
});

cli.runApp(new WorkerOptions({ agent: fileURLToPath(import.meta.url) }));