
    7jf                       d dl mZ d dlmZmZmZmZmZmZ d dl	m	Z	 d dl
mZ d dlmZ d dlZerd dl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mZmZmZmZmZm Z  ddl!m"Z"m#Z#m$Z$m%Z%m&Z& ddl'm(Z( ddl)m*Z*m+Z+ ddl,m-Z-m.Z. ddl/m0Z0m1Z1 ddl2m3Z3m4Z4 ddl5m6Z6m7Z7 ddl8m9Z9m:Z: ddl;m<Z< ddl=m>Z> ddl?m@Z@ ddlAmBZB ddlCmDZD ddgZE G d de*      ZF G d de+      ZG G d d      ZH G d  d!      ZI G d" d#      ZJ G d$ d%      ZKy)&    )annotations)TYPE_CHECKINGAnyListUnionIterablecast)datetime)chain)LiteralN)Sequence   )AsyncAnthropic)SessionToolRunnerBetaAnyRunnableTool)_legacy_response)BodyOmitQueryHeadersNotGivenSequenceNotStromit	not_given)is_givenpath_templatemaybe_transformstrip_not_givenasync_maybe_transform)cached_property)SyncAPIResourceAsyncAPIResource)to_streamed_response_wrapper"async_to_streamed_response_wrapper)StreamAsyncStream)SyncPageCursorAsyncPageCursor)AsyncPaginatormake_request_options)event_list_paramsevent_send_params)AnthropicBetaParam)BetaManagedAgentsEventParams)BetaManagedAgentsSessionEvent)"BetaManagedAgentsSendSessionEvents)$BetaManagedAgentsStreamSessionEventsEventsAsyncEventsc                      e Zd Zed	d       Zed
d       Zeeeeeeeeeddded	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 ddZeddded	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 ddZ	eddded	 	 	 	 	 	 	 	 	 	 	 	 	 ddZ
y)r2   c                    t        |       S a  
        This property can be used as a prefix for any HTTP method call to return
        the raw response object instead of the parsed content.

        For more information, see https://www.github.com/anthropics/anthropic-sdk-python#accessing-raw-response-data-eg-headers
        )EventsWithRawResponseselfs    ^/var/www/html/qr/venv/lib/python3.12/site-packages/anthropic/resources/beta/sessions/events.pywith_raw_responsezEvents.with_raw_response&   s     %T**    c                    t        |       S z
        An alternative to `.with_raw_response` that doesn't eagerly read the response body.

        For more information, see https://www.github.com/anthropics/anthropic-sdk-python#with_streaming_response
        )EventsWithStreamingResponser8   s    r:   with_streaming_responsezEvents.with_streaming_response0   s     +400r<   Ncreated_at_gtcreated_at_gtecreated_at_ltcreated_at_ltelimitorderpagetypesbetasextra_headersextra_query
extra_bodytimeoutc                  |st        d|      i t        dt        |
      r#dj                  t	        d |
D        dg            nt
        i      |xs i }ddi|xs i }| j                  t        d|      t        t           t        ||||t        ||||||||	dt        j                        	      t        t        t              
      S )  
        List Events

        Args:
          created_at_gt: Return events created after this time (exclusive).

          created_at_gte: Return events created at or after this time (inclusive).

          created_at_lt: Return events created before this time (exclusive).

          created_at_lte: Return events created at or before this time (inclusive).

          limit: Query parameter for limit

          order: Sort direction for results, ordered by created_at. Defaults to asc
              (chronological).

          page: Opaque pagination cursor from a previous response's next_page.

          types: Filter by event type. Values match the `type` field on returned events (for
              example, `user.message` or `agent.tool_use`). Omit to return all event types.

          betas: Optional header to specify the beta version(s) you want to use.

          extra_headers: Send extra headers

          extra_query: Add additional query parameters to the request

          extra_body: Add additional JSON properties to the request

          timeout: Override the client-level default timeout for this request, in seconds
        9Expected a non-empty value for `session_id` but received anthropic-beta,c              3  2   K   | ]  }t        |        y wNstr.0es     r:   	<genexpr>zEvents.list.<locals>.<genexpr>r        5Lc!f5L   managed-agents-2026-04-01*/v1/sessions/{session_id}/events?beta=true
session_idrB   rC   rD   rE   rF   rG   rH   rI   rK   rL   rM   rN   queryrH   optionsmodel)
ValueErrorr   r   joinr   r   _get_api_listr   r'   r/   r*   r   r+   EventListParamsr	   r   r9   ra   rB   rC   rD   rE   rF   rG   rH   rI   rJ   rK   rL   rM   rN   s                  r:   listzEvents.list9   s
   h XYcXfghh	
$ '*hhu5Le5LOjNk/l&m"	
 "	
 *+F`=K^\^`!!FS]^ =>(+'%%)6*8)6*8!&!& $!&	 &55& 2- " 
 	
r<   rJ   rK   rL   rM   rN   c          
     Z   |st        d|      i t        dt        |      r#dj                  t	        d |D        dg            nt
        i      |xs i }ddi|xs i }| j                  t        d|      t        d|it        j                        t        ||||	      t        
      S )  
        Send Events

        Args:
          events: Events to send to the `session`.

          betas: Optional header to specify the beta version(s) you want to use.

          extra_headers: Send extra headers

          extra_query: Add additional query parameters to the request

          extra_body: Add additional JSON properties to the request

          timeout: Override the client-level default timeout for this request, in seconds
        rQ   rR   rS   c              3  2   K   | ]  }t        |        y wrU   rV   rX   s     r:   r[   zEvents.send.<locals>.<genexpr>   r\   r]   r^   r_   r`   eventsrK   rL   rM   rN   bodyrf   cast_to)rh   r   r   ri   r   r   _postr   r   r,   EventSendParamsr*   r0   r9   ra   rr   rJ   rK   rL   rM   rN   s           r:   sendzEvents.send   s    : XYcXfghh	
$ '*hhu5Le5LOjNk/l&m"	
 "	
 *+F`=K^\^`zzFS]^ (F!35F5V5VW(+Q[el 7  
 	
r<   c          
     Z   |st        d|      i t        dt        |      r#dj                  t	        d |D        dg            nt
        i      |xs i }ddi|xs i }| j                  t        d|      t        ||||      t        t        t              d	t        t           
      S )  
        Stream Events

        Args:
          betas: Optional header to specify the beta version(s) you want to use.

          extra_headers: Send extra headers

          extra_query: Add additional query parameters to the request

          extra_body: Add additional JSON properties to the request

          timeout: Override the client-level default timeout for this request, in seconds
        rQ   rR   rS   c              3  2   K   | ]  }t        |        y wrU   rV   rX   s     r:   r[   z Events.stream.<locals>.<genexpr>   r\   r]   r^   1/v1/sessions/{session_id}/events/stream?beta=truer`   rs   Trf   rv   stream
stream_cls)rh   r   r   ri   r   r   _getr   r*   r	   r   r1   r%   r9   ra   rJ   rK   rL   rM   rN   s          r:   r   zEvents.stream   s    4 XYcXfghh	
$ '*hhu5Le5LOjNk/l&m"	
 "	
 *+F`=K^\^`yyMZde(+Q[el 9 BC  

 
	
r<   )returnr7   )r   r?   )ra   rW   rB   Union[str, datetime] | OmitrC   r   rD   r   rE   r   rF   
int | OmitrG   Literal['asc', 'desc'] | OmitrH   
str | OmitrI   SequenceNotStr[str] | OmitrJ   List[AnthropicBetaParam] | OmitrK   Headers | NonerL   Query | NonerM   Body | NonerN   'float | httpx.Timeout | None | NotGivenr   z-SyncPageCursor[BetaManagedAgentsSessionEvent]ra   rW   rr   z&Iterable[BetaManagedAgentsEventParams]rJ   r   rK   r   rL   r   rM   r   rN   r   r   r0   )ra   rW   rJ   r   rK   r   rL   r   rM   r   rN   r   r   z,Stream[BetaManagedAgentsStreamSessionEvents])__name__
__module____qualname__r    r;   r@   r   r   rm   rz   r    r<   r:   r2   r2   %   s   + + 1 1 6:6:596: /3,015 )-$("&;D%Z
Z
 3	Z

 4Z
 3Z
 4Z
 Z
 -Z
 Z
 *Z
 /Z
 &Z
  "!Z
"  #Z
$ 9%Z
& 
7'Z
B 26 )-$("&;D1
1
 7	1

 /1
 &1
 "1
  1
 91
 
,1
n 26 )-$("&;D1
1
 /	1
 &1
 "1
  1
 91
 
61
r<   c                     e Zd Zedd       Zedd       Zeeeeeeeeeddded	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 ddZeddded	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 ddZ	eddded	 	 	 	 	 	 	 	 	 	 	 	 	 ddZ
eddd		 	 	 	 	 	 	 	 	 	 	 dd
Zy)r3   c                    t        |       S r6   )AsyncEventsWithRawResponser8   s    r:   r;   zAsyncEvents.with_raw_response   s     *$//r<   c                    t        |       S r>   ) AsyncEventsWithStreamingResponser8   s    r:   r@   z#AsyncEvents.with_streaming_response  s     055r<   NrA   c                  |st        d|      i t        dt        |
      r#dj                  t	        d |
D        dg            nt
        i      |xs i }ddi|xs i }| j                  t        d|      t        t           t        ||||t        ||||||||	dt        j                        	      t        t        t              
      S )rP   rQ   rR   rS   c              3  2   K   | ]  }t        |        y wrU   rV   rX   s     r:   r[   z#AsyncEvents.list.<locals>.<genexpr>I  r\   r]   r^   r_   r`   rb   rc   re   )rh   r   r   ri   r   r   rj   r   r(   r/   r*   r   r+   rk   r	   r   rl   s                  r:   rm   zAsyncEvents.list  s
   h XYcXfghh	
$ '*hhu5Le5LOjNk/l&m"	
 "	
 *+F`=K^\^`!!FS]^ !>?(+'%%)6*8)6*8!&!& $!&	 &55& 2- " 
 	
r<   rn   c          
       K   |st        d|      i t        dt        |      r#dj                  t	        d |D        dg            nt
        i      |xs i }ddi|xs i }| j                  t        d|      t        d|it        j                         d	{   t        ||||
      t               d	{   S 7 $7 w)rp   rQ   rR   rS   c              3  2   K   | ]  }t        |        y wrU   rV   rX   s     r:   r[   z#AsyncEvents.send.<locals>.<genexpr>  r\   r]   r^   r_   r`   rr   Nrs   rt   )rh   r   r   ri   r   r   rw   r   r   r,   rx   r*   r0   ry   s           r:   rz   zAsyncEvents.sendl  s     : XYcXfghh	
$ '*hhu5Le5LOjNk/l&m"	
 "	
 *+F`=K^\^`ZZFS]^,h-?ARAbAbcc(+Q[el 7   
 
 	
c
s$   BCB?
C:C;CCc          
     v  K   |st        d|      i t        dt        |      r#dj                  t	        d |D        dg            nt
        i      |xs i }ddi|xs i }| j                  t        d|      t        ||||      t        t        t              d	t        t           
       d{   S 7 w)r|   rQ   rR   rS   c              3  2   K   | ]  }t        |        y wrU   rV   rX   s     r:   r[   z%AsyncEvents.stream.<locals>.<genexpr>  r\   r]   r^   r~   r`   rs   Tr   N)rh   r   r   ri   r   r   r   r   r*   r	   r   r1   r&   r   s          r:   r   zAsyncEvents.stream  s     4 XYcXfghh	
$ '*hhu5Le5LOjNk/l&m"	
 "	
 *+F`=K^\^`YYMZde(+Q[el 9 "#GH  

 

 
	
 

s   B0B92B73B9)max_idleenvironment_keyrK   c               p    ddl m}m} t        |      s|} |t	        d| j
                        |||||      S )u  Dispatch a self-hosted session's tool-call events.

        The sessions-side counterpart to ``client.beta.messages.tool_runner``:
        returns a :class:`~anthropic.lib.environments.SessionToolRunner` — an
        async iterable that attaches to the session's event stream, reconciles
        against the events-list endpoint, runs the matching tool from ``tools``
        for each tool-call event, posts the matching result event back, and
        yields one :class:`~anthropic.lib.environments.DispatchedToolCall` per
        completed call. It handles both tool-call kinds: ``agent.tool_use``
        (built-in agent-toolset tools) answered with ``user.tool_result``, and
        ``agent.custom_tool_use`` (custom, user-defined tools) answered with
        ``user.custom_tool_result``. Internally drives event-stream reconnect
        (with capped backoff) via an anyio task group so it works under both
        ``asyncio`` and ``trio``.

        Iteration ends when the session terminates (``session.status_terminated``
        / ``session.deleted``), when the consumer breaks out of the loop, or —
        once the session has gone idle with ``stop_reason`` ``end_turn`` —
        ``max_idle`` seconds elapse with no new event (any new event resets that
        countdown; it re-arms on the next ``end_turn`` idle). ``max_idle=None``
        disables that last condition. It does **not** touch the work-item lease —
        wrap it in an :class:`~anthropic.lib.environments.EnvironmentWorker` if
        you need heartbeating / force-stop.

        Usage::

            from anthropic.lib.tools.agent_toolset import AgentToolContext, beta_agent_toolset_20260401

            async with AgentToolContext(workdir=...) as env:
                async for call in client.beta.sessions.events.tool_runner(
                    work.data.id,
                    tools=[*beta_agent_toolset_20260401(env), my_tool],
                ):
                    ...

        Args:
          session_id: The session whose events stream we attach to. Passed
            positionally, matching ``list`` / ``send`` / ``stream`` on this
            resource.
          tools: Registry of tool callables the runner will execute when the
            agent emits matching ``agent.tool_use`` / ``agent.custom_tool_use``
            events — the same :class:`~anthropic.lib.tools.BetaAsyncFunctionTool`
            shape ``client.beta.messages.tool_runner`` accepts.
          max_idle: Seconds to keep running after the session goes idle with
            ``stop_reason`` ``end_turn`` before stopping; any new event resets
            the countdown. Defaults to ``DEFAULT_MAX_IDLE`` (60s) when not
            given. ``None`` disables it.
          environment_key: The self-hosted environment key. When set, the
            runner builds a Bearer-only scoped sub-client keyed to that
            environment for the event stream / list / send calls; leave it
            unset to authenticate those calls with the parent client's own
            credentials.
          extra_headers: Optional headers passed through per request on every
            call the runner makes (event stream / list / send). They are
            threaded into each call's ``extra_headers=`` and never assigned
            onto the client, so client state is not mutated. Auth and
            ``x-stainless-helper`` are supplied by the runner's scoped
            sub-client (and the parent client's ``default_headers`` propagate
            via its ``client.copy()``); a header given here overrides the
            scoped client's same-named default for that request, so use it for
            caller passthrough (e.g. trace ids), not to set auth.
        r   )DEFAULT_MAX_IDLEr   r   )toolsr   r   rK   )lib.tools._beta_session_runnerr   r   r   r	   _client)r9   ra   r   r   r   rK   r   r   s           r:   tool_runnerzAsyncEvents.tool_runner  sA    T 	[!'H !4<<0+'
 	
r<   )r   r   )r   r   )ra   rW   rB   r   rC   r   rD   r   rE   r   rF   r   rG   r   rH   r   rI   r   rJ   r   rK   r   rL   r   rM   r   rN   r   r   z]AsyncPaginator[BetaManagedAgentsSessionEvent, AsyncPageCursor[BetaManagedAgentsSessionEvent]]r   )ra   rW   rJ   r   rK   r   rL   r   rM   r   rN   r   r   z1AsyncStream[BetaManagedAgentsStreamSessionEvents])ra   rW   r   zSequence[BetaAnyRunnableTool]r   zfloat | None | NotGivenr   z
str | NonerK   r   r   r   )r   r   r   r    r;   r@   r   r   rm   rz   r   r   r   r<   r:   r3   r3      s   0 0 6 6 6:6:596: /3,015 )-$("&;D%Z
Z
 3	Z

 4Z
 3Z
 4Z
 Z
 -Z
 Z
 *Z
 /Z
 &Z
  "!Z
"  #Z
$ 9%Z
& 
g'Z
B 26 )-$("&;D1
1
 7	1

 /1
 &1
 "1
  1
 91
 
,1
n 26 )-$("&;D1
1
 /	1
 &1
 "1
  1
 91
 
;1
p -6&*(,V
V
 -	V

 *V
 $V
 &V
 
V
r<   c                      e Zd ZddZy)r7   c                    || _         t        j                  |j                        | _        t        j                  |j                        | _        t        j                  |j
                        | _        y rU   )_eventsr   to_raw_response_wrapperrm   rz   r   r9   rr   s     r:   __init__zEventsWithRawResponse.__init__,  sX    $<<KK
	 %<<KK
	 '>>MM
r<   Nrr   r2   r   Noner   r   r   r   r   r<   r:   r7   r7   +      
r<   r7   c                      e Zd ZddZy)r   c                    || _         t        j                  |j                        | _        t        j                  |j                        | _        t        j                  |j
                        | _        y rU   )r   r   async_to_raw_response_wrapperrm   rz   r   r   s     r:   r   z#AsyncEventsWithRawResponse.__init__;  sX    $BBKK
	 %BBKK
	 'DDMM
r<   Nrr   r3   r   r   r   r   r<   r:   r   r   :  r   r<   r   c                      e Zd ZddZy)r?   c                    || _         t        |j                        | _        t        |j                        | _        t        |j                        | _        y rU   )r   r#   rm   rz   r   r   s     r:   r   z$EventsWithStreamingResponse.__init__J  sF    0KK
	 1KK
	 3MM
r<   Nr   r   r   r<   r:   r?   r?   I  r   r<   r?   c                      e Zd ZddZy)r   c                    || _         t        |j                        | _        t        |j                        | _        t        |j                        | _        y rU   )r   r$   rm   rz   r   r   s     r:   r   z)AsyncEventsWithStreamingResponse.__init__Y  sF    6KK
	 7KK
	 9MM
r<   Nr   r   r   r<   r:   r   r   X  r   r<   r   )L
__future__r   typingr   r   r   r   r   r	   r
   	itertoolsr   typing_extensionsr   httpxcollections.abcr   r   r   r   r   r    r   _typesr   r   r   r   r   r   r   r   _utilsr   r   r   r   r   _compatr    	_resourcer!   r"   	_responser#   r$   
_streamingr%   r&   
paginationr'   r(   _base_clientr)   r*   types.beta.sessionsr+   r,   types.anthropic_beta_paramr-   4types.beta.sessions.beta_managed_agents_event_paramsr.   5types.beta.sessions.beta_managed_agents_session_eventr/   ;types.beta.sessions.beta_managed_agents_send_session_eventsr0   =types.beta.sessions.beta_managed_agents_stream_session_eventsr1   __all__r2   r3   r7   r   r?   r   r   r<   r:   <module>r      s    # B B   % (*Y ! \ \ \ g g ' ; Z . : A H = a c n r]
#T
_ T
nl
" l
^	
 

 

 

 
r<   