
    4Rjn                       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:m;Z; ddl<m=Z= ddl>m?Z? ddl@mAZA ddlBmCZC ddlDmEZE ddlFmGZG ddgZH G d de*      ZI G d de+      ZJ G d d       ZK G d! d"      ZL G d# d$      ZM G d% d&      ZNy)'    )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event_stream_params)AnthropicBetaParam)BetaManagedAgentsDeltaType)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eddded	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dd	Z
y)r4   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    p/var/www/html/meridian/meridian-ai/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
        )EventsWithStreamingResponser:   s    r<   with_streaming_responsezEvents.with_streaming_response1   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>s        5Lc!f5L   managed-agents-2026-04-01*/v1/sessions/{session_id}/events?beta=true
session_idrD   rE   rF   rG   rH   rI   rJ   rK   rM   rN   rO   rP   queryrJ   optionsmodel)
ValueErrorr   r   joinr   r   _get_api_listr   r'   r1   r*   r   r+   EventListParamsr	   r   r;   rc   rD   rE   rF   rG   rH   rI   rJ   rK   rL   rM   rN   rO   rP   s                  r<   listzEvents.list:   s
   h XYcXfghh	
$ '*hhu5Le5LOjNk/l&m"	
 "	
 *+F`=K^\^`!!FS]^ =>(+'%%)6*8)6*8!&!& $!&	 &55& 2- " 
 	
r>   rL   rM   rN   rO   rP   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
        rS   rT   rU   c              3  2   K   | ]  }t        |        y wrW   rX   rZ   s     r<   r]   zEvents.send.<locals>.<genexpr>   r^   r_   r`   ra   rb   eventsrM   rN   rO   rP   bodyrh   cast_to)rj   r   r   rk   r   r   _postr   r   r,   EventSendParamsr*   r2   r;   rc   rt   rL   rM   rN   rO   rP   s           r<   sendzEvents.send   s    : XYcXfghh	
$ '*hhu5Le5LOjNk/l&m"	
 "	
 *+F`=K^\^`zzFS]^ (F!35F5V5VW(+Q[el 7  
 	
r>   event_deltasrL   rM   rN   rO   rP   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        d|it        j                        	      t        t        t              d
t        t                 S )  
        Stream Events

        Args:
          event_deltas: When set, this connection also receives streaming deltas (`event_start`,
              `event_delta`) while an event is being produced, before the event itself
              arrives. Deltas are best-effort; when the final event is produced it carries the
              complete content. A model request that ends early (an error or interrupt)
              produces no final event — its terminal `span.model_request_end` closes the
              preview. Accepts one or more event types to preview and may be repeated:
              `agent.message` streams `content_delta` fragments; `agent.thinking` is
              start-only — a signal that the agent has begun extended thinking, concluded by
              the `agent.thinking` event itself. Only previews of the requested event types
              are sent.

          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
        rS   rT   rU   c              3  2   K   | ]  }t        |        y wrW   rX   rZ   s     r<   r]   z Events.stream.<locals>.<genexpr>   r^   r_   r`   1/v1/sessions/{session_id}/events/stream?beta=truerb   r~   re   Trh   rx   stream
stream_cls)rj   r   r   rk   r   r   _getr   r*   r   r-   EventStreamParamsr	   r   r3   r%   r;   rc   r~   rL   rM   rN   rO   rP   s           r<   r   zEvents.stream   s    L XYcXfghh	
$ '*hhu5Le5LOjNk/l&m"	
 "	
 *+F`=K^\^`yyMZde(+'%%~|&DFYFkFkl 9 BC  
 	
r>   )returnr9   )r   rA   )rc   rY   rD   Union[str, datetime] | OmitrE   r   rF   r   rG   r   rH   
int | OmitrI   Literal['asc', 'desc'] | OmitrJ   
str | OmitrK   SequenceNotStr[str] | OmitrL   List[AnthropicBetaParam] | OmitrM   Headers | NonerN   Query | NonerO   Body | NonerP   'float | httpx.Timeout | None | NotGivenr   z-SyncPageCursor[BetaManagedAgentsSessionEvent]rc   rY   rt   z&Iterable[BetaManagedAgentsEventParams]rL   r   rM   r   rN   r   rO   r   rP   r   r   r2   )rc   rY   r~   'List[BetaManagedAgentsDeltaType] | OmitrL   r   rM   r   rN   r   rO   r   rP   r   r   z,Stream[BetaManagedAgentsStreamSessionEvents])__name__
__module____qualname__r    r=   rB   r   r   ro   r|   r    r>   r<   r4   r4   &   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 AE15 )-$("&;DA
A
 >	A

 /A
 &A
 "A
  A
 9A
 
6A
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eddded	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dd	Z
eddd
	 	 	 	 	 	 	 	 	 	 	 ddZy)r5   c                    t        |       S r8   )AsyncEventsWithRawResponser:   s    r<   r=   zAsyncEvents.with_raw_response  s     *$//r>   c                    t        |       S r@   ) AsyncEventsWithStreamingResponser:   s    r<   rB   z#AsyncEvents.with_streaming_response  s     055r>   NrC   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 )rR   rS   rT   rU   c              3  2   K   | ]  }t        |        y wrW   rX   rZ   s     r<   r]   z#AsyncEvents.list.<locals>.<genexpr>Z  r^   r_   r`   ra   rb   rd   re   rg   )rj   r   r   rk   r   r   rl   r   r(   r1   r*   r   r+   rm   r	   r   rn   s                  r<   ro   zAsyncEvents.list!  s
   h XYcXfghh	
$ '*hhu5Le5LOjNk/l&m"	
 "	
 *+F`=K^\^`!!FS]^ !>?(+'%%)6*8)6*8!&!& $!&	 &55& 2- " 
 	
r>   rp   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)rr   rS   rT   rU   c              3  2   K   | ]  }t        |        y wrW   rX   rZ   s     r<   r]   z#AsyncEvents.send.<locals>.<genexpr>  r^   r_   r`   ra   rb   rt   Nru   rv   )rj   r   r   rk   r   r   ry   r   r   r,   rz   r*   r2   r{   s           r<   r|   zAsyncEvents.send}  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r}   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        ||||t        d|it        j                         d	{   
      t        t        t              dt        t                  d	{   S 7 67 w)r   rS   rT   rU   c              3  2   K   | ]  }t        |        y wrW   rX   rZ   s     r<   r]   z%AsyncEvents.stream.<locals>.<genexpr>  r^   r_   r`   r   rb   r~   Nre   Tr   )rj   r   r   rk   r   r   r   r   r*   r   r-   r   r	   r   r3   r&   r   s           r<   r   zAsyncEvents.stream  s    L XYcXfghh	
$ '*hhu5Le5LOjNk/l&m"	
 "	
 *+F`=K^\^`YYMZde(+'%1#\24G4Y4Y  9 "#GH  
 
 	

s$   B!C#C$1CCCC)max_idleenvironment_keyrM   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   rM   )lib.tools._beta_session_runnerr   r   r   r	   _client)r;   rc   r   r   r   rM   r   r   s           r<   tool_runnerzAsyncEvents.tool_runner  sA    T 	[!'H !4<<0+'
 	
r>   )r   r   )r   r   )rc   rY   rD   r   rE   r   rF   r   rG   r   rH   r   rI   r   rJ   r   rK   r   rL   r   rM   r   rN   r   rO   r   rP   r   r   z]AsyncPaginator[BetaManagedAgentsSessionEvent, AsyncPageCursor[BetaManagedAgentsSessionEvent]]r   )rc   rY   r~   r   rL   r   rM   r   rN   r   rO   r   rP   r   r   z1AsyncStream[BetaManagedAgentsStreamSessionEvents])rc   rY   r   zSequence[BetaAnyRunnableTool]r   zfloat | None | NotGivenr   z
str | NonerM   r   r   r   )r   r   r   r    r=   rB   r   r   ro   r|   r   r   r   r>   r<   r5   r5     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 AE15 )-$("&;DC
C
 >	C

 /C
 &C
 "C
  C
 9C
 
;C
T -6&*(,V
V
 -	V

 *V
 $V
 &V
 
V
r>   c                      e Zd ZddZy)r9   c                    || _         t        j                  |j                        | _        t        j                  |j                        | _        t        j                  |j
                        | _        y rW   )_eventsr   to_raw_response_wrapperro   r|   r   r;   rt   s     r<   __init__zEventsWithRawResponse.__init__O  sX    $<<KK
	 %<<KK
	 '>>MM
r>   Nrt   r4   r   Noner   r   r   r   r   r>   r<   r9   r9   N      
r>   r9   c                      e Zd ZddZy)r   c                    || _         t        j                  |j                        | _        t        j                  |j                        | _        t        j                  |j
                        | _        y rW   )r   r   async_to_raw_response_wrapperro   r|   r   r   s     r<   r   z#AsyncEventsWithRawResponse.__init__^  sX    $BBKK
	 %BBKK
	 'DDMM
r>   Nrt   r5   r   r   r   r   r>   r<   r   r   ]  r   r>   r   c                      e Zd ZddZy)rA   c                    || _         t        |j                        | _        t        |j                        | _        t        |j                        | _        y rW   )r   r#   ro   r|   r   r   s     r<   r   z$EventsWithStreamingResponse.__init__m  sF    0KK
	 1KK
	 3MM
r>   Nr   r   r   r>   r<   rA   rA   l  r   r>   rA   c                      e Zd ZddZy)r   c                    || _         t        |j                        | _        t        |j                        | _        t        |j                        | _        y rW   )r   r$   ro   r|   r   r   s     r<   r   z)AsyncEventsWithStreamingResponse.__init__|  sF    6KK
	 7KK
	 9MM
r>   Nr   r   r   r>   r<   r   r   {  r   r>   r   )O
__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,   r-   types.anthropic_beta_paramr.   )types.beta.beta_managed_agents_delta_typer/   4types.beta.sessions.beta_managed_agents_event_paramsr0   5types.beta.sessions.beta_managed_agents_session_eventr1   ;types.beta.sessions.beta_managed_agents_send_session_eventsr2   =types.beta.sessions.beta_managed_agents_stream_session_eventsr3   __all__r4   r5   r9   r   rA   r   r   r>   r<   <module>r      s    # B B   % (*Y ! \ \ \ g g ' ; Z . : A ] ] = T a c n r]
#d
_ d
N~
" ~
B

 

 

 

 
r>   