IGNORE_ON_ENTER tools (e.g. end_call) stay hidden for the whole call after on_enter awaits an AgentTask
Bug Description
Tools flagged IGNORE_ON_ENTER, such as EndCallTool(ignore_on_enter=True), are hidden while an agent runs on_enter, as intended. But if on_enter awaits an AgentTask (for example a recording-consent step), those tools stay hidden on every later user turn, long after on_enter has returned. The model never gets end_call, so the agent can't hang up.
Why: on_enter runs with a ContextVar marker (_OnEnterContextVar). When the awaited task completes, the parent activity is resumed from inside on_enter, and AgentActivity._start_session() creates the session's long-lived tasks (scheduling, audio recognition) there. asyncio.create_task copies the current context, so those tasks keep the marker after on_enter resets it, and every reply they start is treated as an on_enter reply.
The same happens through start(): if a handoff is made from inside on_enter (A → B) and B later hands back to the same agent instance A, A's new activity inherits the marker again.
Expected Behavior
IGNORE_ON_ENTER tools are hidden only for replies made inside on_enter, and are available again on later user turns.
Reproduction Steps
- Give an agent an
IGNORE_ON_ENTERtool and await anAgentTaskin itson_enter:
from livekit.agents import Agent, AgentTask, function_tool
from livekit.agents.beta.tools import EndCallTool
class ConsentTask(AgentTask[bool]):
def __init__(self) -> None:
super().__init__(instructions="Ask whether the call may be recorded.")
@function_tool
async def record_consent(self, consent: bool) -> None:
"""Record the caller's answer."""
self.complete(consent)
class MyAgent(Agent):
def __init__(self) -> None:
super().__init__(
instructions="You are a helpful assistant.",
tools=[EndCallTool(ignore_on_enter=True)],
)
async def on_enter(self) -> None:
await ConsentTask()
self.session.generate_reply(instructions="Greet the caller.")
- Start a session, answer the consent question, then keep talking to the agent.
- Inspect the
toolspassed tollm_nodeon the later turns:end_callis missing on every one. Remove theawait ConsentTask()and it is present.
Operating System
Linux
Models Used
Cascading STT → LLM → TTS with OpenAI GPT-4.1. The bug does not depend on the models.
Package Versions
livekit-agents==1.8.10
# also reproduced on 1.6.6, 1.6.10, 1.7.1 and main (b91fd2b)
Proposed Solution
# AgentActivity._start_session: create the session-long tasks without the caller's on_enter marker
tk = _OnEnterContextVar.set(None)
try:
await self._start_session_impl(reuse_resources=reuse_resources)
finally:
_OnEnterContextVar.reset(tk)
Replies created by on_enter itself keep the marker, so the greeting stays protected. I'll open a PR with this fix.
Additional Context
- The marker was added in #6361 (fixing #6354), first released in 1.6.5.
- We hit this in production: a phone agent whose
on_enterawaits a recording-consent task could not end any call.