o
    ip                     @  s@  U d dl mZ d dlZd dlZd dlZd dlZd dlZd dlZd dlZ	d dl
Z
d dlmZmZ d dlmZ d dlmZmZ d dlmZ d dlmZmZ d dlmZ d dlZd d	lmZmZ d d
lmZ d dl m!Z!m"Z" ddl#m$Z$ ddl%m&Z& ddl'm(Z( ddl)m*Z*m+Z+m,Z, ddl-m.Z. ddl/m0Z0m1Z1m2Z2 ddl3m4Z4 ej5d dZ6erddl7m8Z8 ddl9m:Z:m;Z; ddl<m=Z= d5ddZ>e>Z?eG dd deZ@G dd deAeZBeG d d! d!ZCeG d"d# d#ZDejEjFejEjGgZHd$eId%< G d&d' d'ejJZKG d(d dZLd6d-d.ZMG d/d0 d0ZNG d1d2 d2ZOeG d3d4 d4ZPdS )7    )annotationsN)Callable	Coroutine)	dataclass)Enumunique)Path)TYPE_CHECKINGAny)urlparse)apirtc)Claims)agentmodels   )logger)Tagger)_upload_session_report)_BufferingHandler_setup_cloud_tracer_shutdown_telemetry)
NotGivenOr)http_contextis_givenwait_for_participant)is_cloud
JobContextagents_job_context)InferenceExecutor)AgentSessionRecordingOptionsSessionReportreturnc                  C  s   t d } | d u rtd| S )NzHno job context found, are you running this code inside a job entrypoint?)_JobContextVargetRuntimeError)ctx r)   T/var/www/html/livekit_bhavya/venv/lib/python3.10/site-packages/livekit/agents/job.pyget_job_context7   s   
r+   c                   @  s   e Zd ZdZdZdS )JobExecutorTypeprocessthreadN)__name__
__module____qualname__PROCESSTHREADr)   r)   r)   r*   r,   D   s    r,   c                   @  s   e Zd ZdZdZdZdZdS )AutoSubscribesubscribe_allsubscribe_none
audio_only
video_onlyN)r/   r0   r1   SUBSCRIBE_ALLSUBSCRIBE_NONE
AUDIO_ONLY
VIDEO_ONLYr)   r)   r)   r*   r4   J   s
    r4   c                   @  s2   e Zd ZU ded< ded< ded< dZded< dS )JobAcceptArgumentsstrnameidentitymetadataNdict[str, str] | None
attributes)r/   r0   r1   __annotations__rC   r)   r)   r)   r*   r=   Q   s
   
 r=   c                   @  s>   e Zd ZU ded< ded< ded< ded< ded< d	ed
< dS )RunningJobInfor=   accept_arguments	agent.Jobjobr>   urltoken	worker_idboolfake_jobNr/   r0   r1   rD   r)   r)   r)   r*   rE   Y   s   
 rE   z#list[rtc.ParticipantKind.ValueType]DEFAULT_PARTICIPANT_KINDSc                      s,   e Zd ZdZd fddZdddZ  ZS )_ContextLogFieldsFilterzGFilter that adds job context fields to log records without overwriting.job_ctxr   r$   Nonec                   s   t    || _d S N)super__init__rQ   )selfrQ   	__class__r)   r*   rU   l   s   

z _ContextLogFieldsFilter.__init__recordlogging.LogRecordrL   c                 C  sn   | j jjtjkrzt }W n
 ty   Y dS w || j krdS | j j D ]\}}t	||s4t
||| q%dS NT)rQ   procexecutor_typer,   r2   r+   r'   _log_fieldsitemshasattrsetattr)rV   rY   r(   keyvaluer)   r)   r*   filterp   s   


z_ContextLogFieldsFilter.filter)rQ   r   r$   rR   )rY   rZ   r$   rL   )r/   r0   r1   __doc__rU   rd   __classcell__r)   r)   rW   r*   rP   i   s    rP   c                   @  s  e Zd Zed ejged f ZdddZdddZ	dddZ
dddZdddZdddZdddZdd d!Zedd#d$Zedd%d&Zedd(d)Zddd.d/Zejdd1d2Zedd3d4Zedd6d7Zedd9d:Zedd;d<Zedd>d?ZeddAdBZeddCdDZeddFdGZej ddIdGZddLdMZ!d*e"dNddTdUZ#d*e$j%d*dVdd]d^Z&dddadbZ'dcddddkdlZ(	mdddrdsZ)dddvdwZ*e"dxdd}d~Z+dddZ,dddZ-dddZ.d*S )r   )NNNr\   
JobProcessinforE   roomrtc.Room
on_connectCallable[[], None]on_shutdownCallable[[str], None]inference_executorr   r$   rR   c          	      C  s   || _ || _|| _|| _|| _g | _g | _ttt	t
jf tjd  f  | _ttjt   | _| jd| j || _i | _t| | _g | _d | _t | _ddlm} | }|j r^|j!| _"nt#| jj$| _"d| _%t& | _'t( | _)d| _*d | _+d S )Nparticipant_connectedr   AgentsConsoleF),_proc_info_room_on_connect_on_shutdown_shutdown_callbacks_participant_entrypointsdicttupler>   r    _PARTICIPANT_ENTRYPOINT_CALLBACKasyncioTask_participant_taskslistr
   _pending_taskson_participant_available_inf_executorr^   rP   _log_filter_handlers_with_filter_primary_agent_sessiontempfileTemporaryDirectory_tempdirclirr   get_instanceenabledsession_directory_session_directoryr   r?   
_connectedLock_lockr   _tagger_recording_initialized_early_log_handler)	rV   r\   rh   ri   rk   rm   ro   rr   cr)   r)   r*   rU      s:   





zJobContext.__init__c                 C  s0   t  }|jD ]}|| j | j| qd S rS   )logging	getLoggerhandlers	addFilterr   r   append)rV   root_loggerhandlerr)   r)   r*   	_on_setup   s
   
zJobContext._on_setupc                 C  sB   | j js	| j jjsdS t| j jsdS t | _t	 
| j dS )z9Start buffering logs early so crash logs can be uploaded.N)rt   rM   rH   enable_recordingr   rI   r   r   r   r   
addHandlerrV   r)   r)   r*   _start_log_buffering   s   zJobContext._start_log_bufferingc                 C  s*   | j }|du r	dS t | d| _ dS )z/Remove the buffering handler without replaying.N)r   r   r   removeHandler)rV   r   r)   r)   r*   _stop_log_buffering   s
   
zJobContext._stop_log_bufferingreplayrL   c                C  st   | j }|du r	dS t | d| _ |sdS ddlm} t jD ]}t||r7|jD ]}|	| q, dS q"dS )zDRemove buffering handler and optionally replay records through OTLP.Nr   )LoggingHandler)
r   r   r   r   opentelemetry.sdk._logsr   r   
isinstancebufferemit)rV   r   r   r   hrY   r)   r)   r*   _flush_early_log_buffer   s   

z"JobContext._flush_early_log_bufferc           
   	     s  ddl m} | j }sd S | }| |}|jrw|jrwzKtj|	 dd}dd l
}dd l}|jj| jddI d H  |j| jd d	d
4 I d H }||I d H  W d   I d H  n1 I d H sbw   Y  W n tyv   td Y nw t| jjp| jj}t|j s|rt| jjrz't| jjj}	|	st d| jj t!| jj"j#|	|| jt$% dI d H  W d S  ty   td Y d S w d S d S )Nr   rq      )indentr   T)exist_okzsession_report.jsonw)modezfailed to save session reportzinvalid cloud hostname: )
agent_namecloud_hostnamereporttaggerhttp_sessionz4failed to upload the session report to LiveKit Cloud)&r   rr   r   r   make_session_reportr   rY   jsondumpsto_dictaiofilesaiofiles.ososmakedirsr   openwrite	Exceptionr   	exceptionrL   r   evaluationsoutcome_reasonanyrecording_optionsvaluesr   rt   rI   r   hostname
ValueErrorr   rH   r   r   r   )
rV   rr   sessionr   r   report_jsonr   f	has_evalsr   r)   r)   r*   _on_session_end   sN   


(zJobContext._on_session_endc                 C  s   | j d ur.| js.zddlm} | |ddddd W n ty-   td |   Y nw | j	
  t  | jD ]}|| j q9| j  d S )Nr   )r!   FT)audiotraceslogs
transcriptz%failed to initialize crash log upload)r   r   voice.agent_sessionr!   init_recordingr   r   r   r   r   cleanupr   r   removeFilterr   clear)rV   r!   r   r)   r)   r*   _on_cleanup  s   


zJobContext._on_cleanupc                 C     | j jS rS   )rt   rM   r   r)   r)   r*   is_fake_job(  s   zJobContext.is_fake_jobr   c                 C  s
   t | jS rS   )r   r   r   r)   r)   r*   r   +  s   
zJobContext.session_directoryc                 C     | j S rS   )r   r   r)   r)   r*   ro   /     zJobContext.inference_executorr   c                 C  r   )as  Returns the Tagger for adding tags and outcomes to the session.

        Tags are uploaded to LiveKit Cloud at session end.

        Example:
            ```python
            ctx.tagger.success(reason="Task completed successfully")
            ctx.tagger.fail(reason="User hung up before completing")
            ctx.tagger.add("voicemail:true")
            ```
        )r   r   r)   r)   r*   r   3  s   zJobContext.taggerNr   AgentSession | Noner#   c                 C  s   ddl m} |p
| j}|std|j}|r|jrtd||j| jj| jj	j
| jj	j|j|r2|jnd |r8|jnd |j|j|j d
}|r[|jrM|j|_|jr[|j|_|j|j |_|S )Nr   r"   z0Cannot prepare report, no AgentSession was foundzHCannot create the AgentSession report, the RecorderIO is still recording)
r   job_idroom_idri   optionsaudio_recording_pathaudio_recording_started_at
started_ateventschat_history)voice.reportr#   r   r'   _recorder_io	recording_recording_optionsrH   idri   sidr?   r   output_pathrecording_started_at_started_at_recorded_eventshistorycopyr   r   	timestampduration)rV   r   r#   recorder_iosrr)   r)   r*   r   B  s8   

zJobContext.make_session_reportapi.LiveKitAPIc                 C  s   t jt dS )ah  Returns an LiveKitAPI for making API calls to LiveKit.

        Credentials are sourced from environment variables if not provided explicitly.
        When starting via the worker, values passed in `WorkerOptions` are exported to
        LIVEKIT_URL, LIVEKIT_API_KEY, and LIVEKIT_API_SECRET so this API is always
        usable inside job entrypoints.
        )r   )r   
LiveKitAPIr   r   r   r)   r)   r*   r   g  s   	zJobContext.apic                 C  r   )zOReturns the process running the job. Useful for storing process-specific state.)rs   r   r)   r)   r*   r\   r  s   zJobContext.procrG   c                 C  r   )z5Returns the current job that the worker is executing.)rt   rH   r   r)   r)   r*   rH   w     zJobContext.jobr>   c                 C  r   )zReturns the id of the worker.)rt   rK   r   r)   r)   r*   rK   |  r   zJobContext.worker_idc                 C  r   )a  The Room object is the main interface that the worker should interact with.

        When the entrypoint is called, the worker has not connected to the Room yet.
        Certain properties of Room would not be available before calling JobContext.connect()
        )ru   r   r)   r)   r*   ri     s   zJobContext.roomrtc.LocalParticipantc                 C  r   rS   )ru   local_participantr   r)   r)   r*   r        zJobContext.agentr    c                 C  s   | j std| j S )z.Returns the primary AgentSession for this job.z(No AgentSession was started for this job)r   r'   r   r)   r)   r*   primary_session  s   zJobContext.primary_sessionc                 C  s   |   j }r	|S | jjjS rS   )token_claimsr@   ru   r   )rV   r@   r)   r)   r*   local_participant_identity  s   
z%JobContext.local_participant_identitydict[str, Any]c                 C  r   )a  
        Returns the current dictionary of log fields that will be injected into log records.

        These fields enable enriched structured logging and can include job metadata,
        worker ID, trace IDs, or other diagnostic context.

        The returned dictionary can be directly edited, or entirely replaced via assignment
        (e.g., `job_context.log_context_fields = {...}`)
        r^   r   r)   r)   r*   log_context_fields  s   zJobContext.log_context_fieldsfieldsc                 C  s
   || _ dS )aY  
        Sets the log fields to be injected into future log records.

        Args:
            fields (dict[str, Any]): A dictionary of key-value pairs representing
                structured data to attach to each log entry. Typically includes contextual
                information like job ID, trace information, or worker metadata.
        Nr   )rV   r  r)   r)   r*   r    s   

callbackXCallable[[], Coroutine[None, None, None]] | Callable[[str], Coroutine[None, None, None]]c                   sL   t  rdnd} jj|kr| j  d	S d
 fdd}| j| d	S )z
        Add a callback to be called when the job is shutting down.
        Optionally the callback can take a single argument, the shutdown reason.
        r   r   _r>   r$   rR   c                   s     I d H  d S rS   r)   r  r  r)   r*   wrapper  s   z1JobContext.add_shutdown_callback.<locals>.wrapperN)r  r>   r$   rR   )inspectismethod__code__co_argcountrx   r   )rV   r  min_args_numr  r)   r  r*   add_shutdown_callback  s
   	z JobContext.add_shutdown_callbackr@   kindr@   
str | Noner  Clist[rtc.ParticipantKind.ValueType] | rtc.ParticipantKind.ValueTypertc.RemoteParticipantc                  s   t | j||dI dH S )z
        Returns a participant that matches the given identity. If identity is None, the first
        participant that joins the room will be returned.
        If the participant has already joined, the function will return immediately.
        r  N)r   ru   )rV   r@   r  r)   r)   r*   r     s   zJobContext.wait_for_participante2eeauto_subscribe
rtc_configr  rtc.E2EEOptions | Noner  r4   r  rtc.RtcConfiguration | Nonec             	     s   | j 4 I dH Q | jr	 W d  I dH  dS tj||tjk|d}| jj| jj	| jj
|dI dH  |   | jj D ]}| | q=t| j| d| _W d  I dH  dS 1 I dH s_w   Y  dS )a  Connect to the room. This method should be called only once.

        Args:
            e2ee: End-to-end encryption options. If provided, the Agent will utilize end-to-end encryption. Note: clients will also need to handle E2EE.
            auto_subscribe: Whether to automatically subscribe to tracks. Default is AutoSubscribe.SUBSCRIBE_ALL.
            rtc_config: Custom RTC configuration to use when connecting to the room.
        Nr  )r   T)r   r   r   RoomOptionsr4   r9   ru   connectrt   rI   rJ   rv   remote_participantsr   r   _apply_auto_subscribe_opts)rV   r  r  r  room_optionspr)   r)   r*   r    s"    .zJobContext.connect	room_name&asyncio.Future[api.DeleteRoomResponse]c                   sr     rtd tjtj  }|t  |S d	 fdd}t| j	
 fdd S )
z2Deletes the room and disconnects all participants.z;job_ctx.delete_room() is not executed while in console moder$   rR   c               
     s   zj jt j pjjdI d H  W d S  tjy&   t	d Y d S  t j
yO }  z| jt jjkrDt	d|   W Y d } ~ d S W Y d } ~ d S d } ~ w ty]   td Y d S w )N)ri   z'server disconnected while deleting roomzerror while deleting room: z!unknown error while deleting room)r   ri   delete_roomDeleteRoomRequestru   r?   aiohttpServerDisconnectedErrorr   warning
TwirpErrorcodeTwirpErrorCode	NOT_FOUNDr   r   )e)r   rV   r)   r*   _delete_room  s   z,JobContext.delete_room.<locals>._delete_roomc                       j S rS   r   remover  rV   taskr)   r*   <lambda>      z(JobContext.delete_room.<locals>.<lambda>Nr$   rR   )r   r   r&  r}   Futurer   DeleteRoomResponse
set_resultcreate_taskr   r   add_done_callback)rV   r   futr,  r)   )r   rV   r1  r*   r"    s   
zJobContext.delete_roomzSIP-participant)participant_namecall_totrunk_idparticipant_identityr;  NotGivenOr[str]&asyncio.Future[api.SIPParticipantInfo]c                  s      rtd tjtj  }|t  |S t jj	
tj jj|||t|r-|ndd j  fdd S )ah  
        Add a SIP participant to the room.

        Args:
            call_to: The number or SIP destination to transfer the participant to.
                         This can either be a number (+12345555555) or a
                         sip host (sip:<user>@<host>)
            trunk_id: The ID of the SIP trunk to use
            participant_identity: The identity of the participant to add
            participant_name: The name of the participant to add

        Make sure you have an outbound SIP trunk created in LiveKit.
        See https://docs.livekit.io/sip/trunk-outbound/ for more information.
        zCjob_ctx.add_sip_participant() is not executed while in console modeN)r   r>  sip_trunk_idsip_call_tor;  c                   r-  rS   r.  r  r0  r)   r*   r2  8  r3  z0JobContext.add_sip_participant.<locals>.<lambda>)r   r   r&  r}   r5  r   SIPParticipantInfor7  r8  sipcreate_sip_participantCreateSIPParticipantRequestru   r?   r   r   r   r9  )rV   r<  r=  r>  r;  r:  r)   r0  r*   add_sip_participant  s&   
zJobContext.add_sip_participantFparticipantrtc.RemoteParticipant | strtransfer_toplay_dialtonec              
     s      rtd tjtj  }|t  |S t|t	j
r.|jt	jjks*J d|j}n|}t jjtj jj|||d j  fdd S )a  Transfer a SIP participant to another number.

        Args:
            participant: The participant to transfer
            transfer_to: The number or SIP destination to transfer the participant to.
                         This can either be a number (+12345555555) or a
                         sip host (sip:<user>@<host>)
            play_dialtone: Whether to play a dialtone during transfer. Defaults to True.


        Returns:
            Future that completes when the transfer is complete

        Make sure you have enabled call transfer on your provider SIP trunk.
        See https://docs.livekit.io/sip/transfer-cold/ for more information.
        zHjob_ctx.transfer_sip_participant() is not executed while in console modez%Participant must be a SIP participant)r   r>  rJ  rK  c                   r-  rS   r.  r  r0  r)   r*   r2  l  r3  z5JobContext.transfer_sip_participant.<locals>.<lambda>)r   r   r&  r}   r5  r   rC  r7  r   r   RemoteParticipantr  ParticipantKindPARTICIPANT_KIND_SIPr@   r8  rD  transfer_sip_participantTransferSIPParticipantRequestru   r?   r   r   r9  )rV   rH  rJ  rK  r:  r>  r)   r0  r*   rO  ;  s4   
z#JobContext.transfer_sip_participant reasonc                 C  s   |  | d S rS   )rw   )rV   rR  r)   r)   r*   shutdowno  s   zJobContext.shutdown)r  entrypoint_fncJCallable[[JobContext, rtc.RemoteParticipant], Coroutine[None, None, None]]r  r
   c                G  s0   |dd | j D v rtd| j ||f dS )a!  Adds an entrypoint function to be run when a participant joins the room. In cases where
        the participant has already joined, the entrypoint will be run immediately. Multiple unique entrypoints can be
        added and they will each be run in parallel for each participant.
        c                 S  s   g | ]\}}|qS r)   r)   ).0r+  r  r)   r)   r*   
<listcomp>~  s    z9JobContext.add_participant_entrypoint.<locals>.<listcomp>z*entrypoints cannot be added more than onceN)ry   r   r   )rV   rT  r  r  r)   r)   r*   add_participant_entrypointr  s   z%JobContext.add_participant_entrypointr   r!   c                 C  s   | j s	t| jjs|   d S d| _ t| jjj}tjdd|id |r>t	| j
jj| j
j||d |d d | jdd d S d S )	NTzconfiguring session recordingr   )extrar   r   )r   r   r   enable_tracesenable_logs)r   )r   r   rt   rI   r   r   r   r   debugr   rH   ri   r   r   r   )rV   r   r   r)   r)   r*   r     s    
zJobContext.init_recordingr  c                   s   j D ]P\}}t|tr j|vrqn j|krq j|fjv r+td j d d j d|j }t	j
| |d}|j j|f< ||f fdd	 qd S )Nzca participant has joined before a prior participant task matching the same identity has finished: ''zpart-entry--)r?   c                   s   j  j|fS rS   )r   popr@   )r  coror  rV   r)   r*   r2    s    z3JobContext._participant_available.<locals>.<lambda>)ry   r   r   r  r@   r   r   r&  r/   r}   r8  r9  )rV   r  r`  r  	task_namer1  r)   ra  r*   r     s$   


z!JobContext._participant_availabler   c                 C  s   t  j| jjddS )NF)verify_signature)r   TokenVerifierverifyrt   rJ   r   r)   r)   r*   r     s   zJobContext.token_claims)r\   rg   rh   rE   ri   rj   rk   rl   rm   rn   ro   r   r$   rR   r4  )r   rL   r$   rR   )r$   rL   )r$   r   )r$   r   )r$   r   rS   )r   r   r$   r#   )r$   r   )r$   rg   r$   rG   r$   r>   )r$   rj   )r$   r   )r$   r    )r$   r   )r  r   r$   rR   )r  r  r$   rR   )r@   r  r  r  r$   r  )r  r  r  r4   r  r  r$   rR   )r   r  r$   r!  )
r<  r>   r=  r>   r>  r>   r;  r?  r$   r@  )F)rH  rI  rJ  r>   rK  rL   r$   r@  )rQ  )rR  r>   r$   rR   )rT  rU  r  r
   r  r  r$   rR   )r   r!   r$   rR   )r  r  r$   rR   )r$   r   )/r/   r0   r1   r   r   rL  r   r|   rU   r   r   r   r   r   r   r   propertyr   ro   r   r   	functoolscached_propertyr   r\   rH   rK   ri   r   r   r   r  setterr  rO   r   r4   r9   r  r"  rG  rO  rS  rX  r   r   r   r)   r)   r)   r*   r      st    

3





*
%

  /4

ri   rj   r  rR   c                   sf   t jt jfvr
d S dfdd | j D ]}|j D ]} | qq| dd fd
d}d S )Npubrtc.RemoteTrackPublicationr$   rR   c                   sF    t jkr| jtjjks t jkr| jtjjkr!| d d S d S d S r[   )	r4   r;   r  r   	TrackKind
KIND_AUDIOr<   
KIND_VIDEOset_subscribed)rl  )r  r)   r*   _subscribe_if_needed  s   z8_apply_auto_subscribe_opts.<locals>._subscribe_if_neededtrack_publishedr  r  c                   s    |  d S rS   r)   )rl  r  )rr  r)   r*   on_track_published  s   z6_apply_auto_subscribe_opts.<locals>.on_track_published)rl  rm  r$   rR   )rl  rm  r  r  r$   rR   )r4   r;   r<   r  r   track_publicationsr   )ri   r  r  rl  rt  r)   )rr  r  r*   r    s   
r  c                   @  s\   e Zd Zdd	d
ZedddZedddZedddZedddZedddZ	dS )rg   r]   r,   user_arguments
Any | None
http_proxyr  r$   rR   c                C  s&   || _ t | _i | _|| _|| _d S rS   )_executor_typempcurrent_process_mp_proc	_userdata_user_arguments_http_proxy)rV   r]   rv  rx  r)   r)   r*   rU     s
   

zJobProcess.__init__c                 C  r   rS   )ry  r   r)   r)   r*   r]     r   zJobProcess.executor_type
int | Nonec                 C  r   rS   )r|  pidr   r)   r)   r*   r    r   zJobProcess.piddict[Any, Any]c                 C  r   rS   )r}  r   r)   r)   r*   userdata  r   zJobProcess.userdatac                 C  r   rS   )r~  r   r)   r)   r*   rv    r   zJobProcess.user_argumentsc                 C  r   rS   )r  r   r)   r)   r*   rx    r   zJobProcess.http_proxyN)r]   r,   rv  rw  rx  r  r$   rR   )r$   r,   )r$   r  )r$   r  )r$   rw  )r$   r  )
r/   r0   r1   rU   rh  r]   r  r  rv  rx  r)   r)   r)   r*   rg     s    
rg   c                   @  s   e Zd Zd(d	d
Zed)ddZed*ddZed+ddZed,ddZed)ddZ	ddd-ddZ
ddddd d.d&d'ZdS )/
JobRequestrH   rG   	on_reject-Callable[[bool], Coroutine[None, None, None]]	on_accept;Callable[[JobAcceptArguments], Coroutine[None, None, None]]r$   rR   c                C  s    || _ t | _|| _|| _d S rS   )_jobr}   r   r   
_on_reject
_on_accept)rV   rH   r  r  r)   r)   r*   rU     s   

zJobRequest.__init__r>   c                 C  r   rS   )r  r   r   r)   r)   r*   r     r   zJobRequest.idc                 C  r   rS   )r  r   r)   r)   r*   rH     r   zJobRequest.jobmodels.Roomc                 C  r   rS   )r  ri   r   r)   r)   r*   ri     r   zJobRequest.roommodels.ParticipantInfo | Nonec                 C  r   rS   )r  rH  r   r)   r)   r*   	publisher  r   zJobRequest.publisherc                 C  r   rS   )r  r   r   r)   r)   r*   r     r   zJobRequest.agent_nameT)	terminater  rL   c                  s   |  |I dH  dS )zFReject the job request. The job will not be assigned to another workerN)r  )rV   r  r)   r)   r*   reject  s   zJobRequest.rejectrQ  Nr?   r@   rA   rC   r?   r@   rA   rC   rB   c                  s4   |sd| j  }t||||d}| |I dH  dS )z[Accept the job request, and start the job if the LiveKit SFU assigns the job to our worker.zagent-r  N)r   r=   r  )rV   r?   r@   rA   rC   rF   r)   r)   r*   accept  s   	
zJobRequest.accept)rH   rG   r  r  r  r  r$   rR   rg  rf  )r$   r  )r$   r  )r  rL   r$   rR   )
r?   r>   r@   r>   rA   r>   rC   rB   r$   rR   )r/   r0   r1   rU   rh  r   rH   ri   r  r   r  r  r)   r)   r)   r*   r    s$    
r  c                   @  s   e Zd ZU ded< ded< dS )_JobShutdownInforL   user_initiatedr>   rR  NrN   r)   r)   r)   r*   r  !  s   
 r  )r$   r   )ri   rj   r  r4   r$   rR   )Q
__future__r   r}   contextvarsri  r	  r   r   multiprocessingrz  r   collections.abcr   r   dataclassesr   enumr   r   pathlibr   typingr	   r
   urllib.parser   r$  livekitr   r   livekit.api.access_tokenr   livekit.protocolr   r   logr   observabilityr   	telemetryr   telemetry.tracesr   r   r   typesr   utilsr   r   r   
utils.miscr   
ContextVarr%   ipc.inference_executorr   r   r    r!   r   r#   r+   get_current_job_contextr,   r>   r4   r=   rE   rM  rN  PARTICIPANT_KIND_STANDARDrO   rD   FilterrP   r   r  rg   r  r  r)   r)   r)   r*   <module>   sl   


    
1#;