@@ -384,6 +384,8 @@ async def _run_consumer(self) -> None: # noqa: PLR0915, PLR0912
384384 event ,
385385 )
386386 else :
387+ replace_event_with_task = False
388+
387389 if task_mode is False :
388390 logger .error (
389391 'Received %s in message mode.' ,
@@ -408,6 +410,17 @@ async def _run_consumer(self) -> None: # noqa: PLR0915, PLR0912
408410 # Initial task should already contain the message.
409411 message_to_save = None
410412 else :
413+ if (
414+ isinstance (event , TaskStatusUpdateEvent )
415+ and not self ._task_created .is_set ()
416+ ):
417+ task = (
418+ await self ._task_manager .get_task ()
419+ )
420+ if task is None :
421+ # Backward compat: Agent sent TaskStatusUpdateEvent before the Task.
422+ replace_event_with_task = True
423+
411424 new_task = (
412425 await self ._task_manager .ensure_task_id (
413426 self ._task_id ,
@@ -434,8 +447,6 @@ async def _run_consumer(self) -> None: # noqa: PLR0915, PLR0912
434447 if not isinstance (event , Task ):
435448 await self ._task_manager .process (event )
436449
437- self ._task_created .set ()
438-
439450 # Check for AUTH_REQUIRED or INPUT_REQUIRED or TERMINAL states
440451 new_task = await self ._task_manager .get_task ()
441452 if new_task is None :
@@ -484,6 +495,15 @@ async def _run_consumer(self) -> None: # noqa: PLR0915, PLR0912
484495 new_task .status .state ,
485496 )
486497
498+ if replace_event_with_task :
499+ logger .error (
500+ 'Agent should not send TaskStatusUpdateEvent before the Task. '
501+ 'Original event:\n %s\n Replacing event with Task:\n %s' ,
502+ event ,
503+ new_task ,
504+ )
505+ event = new_task
506+
487507 if (
488508 self ._push_sender
489509 and self ._task_id
@@ -496,6 +516,9 @@ async def _run_consumer(self) -> None: # noqa: PLR0915, PLR0912
496516 await self ._push_sender .send_notification (
497517 self ._task_id , event
498518 )
519+
520+ self ._task_created .set ()
521+
499522 finally :
500523 if new_task is not None :
501524 new_task_copy = Task ()
0 commit comments