o
    î6Wjÿn  ã                   @  sð  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rBd 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ZHG dd„ de*ƒZIG dd„ de+ƒZJG dd „ d ƒZKG d!d"„ d"ƒZLG d#d$„ d$ƒZMG d%d&„ d&ƒZNdS )'é    )Ú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                   @  s‚   e Zd Zed2dd„ƒZed3dd„ƒZeeeeeeeeeddded	œd4d$d%„Zeddded&œd5d*d+„Z	eeddded,œd6d0d1„Z
dS )7r3   ÚreturnÚEventsWithRawResponsec                 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
        )r6   ©Úself© r;   úw/home/esfera/Documents/content_generation/venv/lib/python3.10/site-packages/anthropic/resources/beta/sessions/events.pyÚwith_raw_response'   ó   zEvents.with_raw_responseÚEventsWithStreamingResponsec                 C  r7   ©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
        )r?   r9   r;   r;   r<   Úwith_streaming_response1   ó   zEvents.with_streaming_responseN©Úcreated_at_gtÚcreated_at_gteÚcreated_at_ltÚcreated_at_lteÚlimitÚorderÚpageÚtypesÚbetasÚextra_headersÚextra_queryÚ
extra_bodyÚtimeoutÚ
session_idÚstrrD   úUnion[str, datetime] | OmitrE   rF   rG   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 | NotGivenú-SyncPageCursor[BetaManagedAgentsSessionEvent]c                C  óª   |s	t d|›�ƒ‚i tdt|
ƒrd tdd„ |
D ƒdgƒ¡ntiƒ¥|p%i ¥}ddi|p-i ¥}| jtd|d�tt	 t
||||t||||||||	d	œtjƒd
�ttt	ƒd�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                 s  ó   � | ]}t |ƒV  qd S ©N©rR   ©Ú.0Úer;   r;   r<   Ú	<genexpr>s   ó   € zEvents.list.<locals>.<genexpr>úmanaged-agents-2026-04-01ú*/v1/sessions/{session_id}/events?beta=true©rQ   ©rD   rE   rF   rG   rH   rI   rJ   rK   ©rM   rN   rO   rP   Úquery©rJ   ÚoptionsÚmodel)Ú
ValueErrorr   r   Újoinr
   r   Ú_get_api_listr   r&   r0   r)   r   r*   ÚEventListParamsr   r   ©r:   rQ   rD   rE   rF   rG   rH   rI   rJ   rK   rL   rM   rN   rO   rP   r;   r;   r<   Úlist:   óN   4ÿýÿÿø

ø
õûÿêzEvents.list©rL   rM   rN   rO   rP   Úeventsú&Iterable[BetaManagedAgentsEventParams]r1   c             	   C  s�   |s	t d|›�ƒ‚i tdt|ƒrd tdd„ |D ƒdgƒ¡ntiƒ¥|p%i ¥}ddi|p-i ¥}| jtd|d�td	|it	j
ƒt||||d
�td�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
        r`   ra   rb   c                 s  rc   rd   re   rf   r;   r;   r<   ri   ¸   rj   zEvents.send.<locals>.<genexpr>rk   rl   rm   r|   ©rM   rN   rO   rP   ©Úbodyrr   Úcast_to)rt   r   r   ru   r
   r   Ú_postr   r   r+   ÚEventSendParamsr)   r1   ©r:   rQ   r|   rL   rM   rN   rO   rP   r;   r;   r<   Úsend–   s,   ÿýÿÿø

ÿúzEvents.send©Úevent_deltasrL   rM   rN   rO   rP   rˆ   ú'List[BetaManagedAgentsDeltaType] | Omitú,Stream[BetaManagedAgentsStreamSessionEvents]c             
   C  sž   |s	t d|›�ƒ‚i tdt|ƒrd tdd„ |D ƒdgƒ¡ntiƒ¥|p%i ¥}ddi|p-i ¥}| jtd|d�t||||t	d	|it
jƒd
�tttƒdtt d�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
        r`   ra   rb   c                 s  rc   rd   re   rf   r;   r;   r<   ri   ô   rj   z Events.stream.<locals>.<genexpr>rk   ú1/v1/sessions/{session_id}/events/stream?beta=truerm   rˆ   ro   T©rr   r‚   ÚstreamÚ
stream_cls)rt   r   r   ru   r
   r   Ú_getr   r)   r   r,   ÚEventStreamParamsr   r   r2   r$   ©r:   rQ   rˆ   rL   rM   rN   rO   rP   r;   r;   r<   rŽ   É   s:   &ÿýÿÿø

ûÿózEvents.stream)r5   r6   )r5   r?   )rQ   rR   rD   rS   rE   rS   rF   rS   rG   rS   rH   rT   rI   rU   rJ   rV   rK   rW   rL   rX   rM   rY   rN   rZ   rO   r[   rP   r\   r5   r]   ©rQ   rR   r|   r}   rL   rX   rM   rY   rN   rZ   rO   r[   rP   r\   r5   r1   )rQ   rR   rˆ   r‰   rL   rX   rM   rY   rN   rZ   rO   r[   rP   r\   r5   rŠ   )Ú__name__Ú
__module__Ú__qualname__r   r=   rA   r   r   ry   r†   rŽ   r;   r;   r;   r<   r3   &   s@    	îaõ7õc                   @  s–   e Zd Zed<dd„ƒZed=dd„ƒZeeeeeeeeeddded	œd>d$d%„Zeddded&œd?d*d+„Z	eeddded,œd@d0d1„Z
eddd2œdAd:d;„ZdS )Br4   r5   ÚAsyncEventsWithRawResponsec                 C  r7   r8   )r—   r9   r;   r;   r<   r=     r>   zAsyncEvents.with_raw_responseÚ AsyncEventsWithStreamingResponsec                 C  r7   r@   )r˜   r9   r;   r;   r<   rA     rB   z#AsyncEvents.with_streaming_responseNrC   rQ   rR   rD   rS   rE   rF   rG   rH   rT   rI   rU   rJ   rV   rK   rW   rL   rX   rM   rY   rN   rZ   rO   r[   rP   r\   ú]AsyncPaginator[BetaManagedAgentsSessionEvent, AsyncPageCursor[BetaManagedAgentsSessionEvent]]c                C  r^   )r_   r`   ra   rb   c                 s  rc   rd   re   rf   r;   r;   r<   ri   Z  rj   z#AsyncEvents.list.<locals>.<genexpr>rk   rl   rm   rn   ro   rq   )rt   r   r   ru   r
   r   rv   r   r'   r0   r)   r   r*   rw   r   r   rx   r;   r;   r<   ry   !  rz   zAsyncEvents.listr{   r|   r}   r1   c             	   Ã  sž   �|s
t d|›�ƒ‚i tdt|ƒrd tdd„ |D ƒdgƒ¡ntiƒ¥|p&i ¥}ddi|p.i ¥}| jtd|d�td	|it	j
ƒI d
H t||||d�td�I d
H S )r~   r`   ra   rb   c                 s  rc   rd   re   rf   r;   r;   r<   ri   Ÿ  rj   z#AsyncEvents.send.<locals>.<genexpr>rk   rl   rm   r|   Nr   r€   )rt   r   r   ru   r
   r   rƒ   r   r   r+   r„   r)   r1   r…   r;   r;   r<   r†   }  s.   €ÿýÿÿø

ÿúzAsyncEvents.sendr‡   rˆ   r‰   ú1AsyncStream[BetaManagedAgentsStreamSessionEvents]c             
   Ã  s¬   �|s
t d|›�ƒ‚i tdt|ƒrd tdd„ |D ƒdgƒ¡ntiƒ¥|p&i ¥}ddi|p.i ¥}| jtd|d�t||||t	d	|it
jƒI d
H d�tttƒdtt d�I d
H S )r‹   r`   ra   rb   c                 s  rc   rd   re   rf   r;   r;   r<   ri   Û  rj   z%AsyncEvents.stream.<locals>.<genexpr>rk   rŒ   rm   rˆ   Nro   Tr�   )rt   r   r   ru   r
   r   r�   r   r)   r   r,   r‘   r   r   r2   r%   r’   r;   r;   r<   rŽ   °  s@   €&ÿýÿÿø


ÿû	ÿñzAsyncEvents.stream)Úmax_idleÚenvironment_keyrM   ÚtoolsúSequence[BetaAnyRunnableTool]r›   úfloat | None | NotGivenrœ   ú
str | Noner   c                C  s8   ddl m}m} t|ƒs|}|td| jƒ|||||d�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   )r�   r›   rœ   rM   )Úlib.tools._beta_session_runnerr¡   r   r   r   Ú_client)r:   rQ   r�   r›   rœ   rM   r¡   r   r;   r;   r<   Útool_runnerõ  s   J
úzAsyncEvents.tool_runner)r5   r—   )r5   r˜   )rQ   rR   rD   rS   rE   rS   rF   rS   rG   rS   rH   rT   rI   rU   rJ   rV   rK   rW   rL   rX   rM   rY   rN   rZ   rO   r[   rP   r\   r5   r™   r“   )rQ   rR   rˆ   r‰   rL   rX   rM   rY   rN   rZ   rO   r[   rP   r\   r5   rš   )rQ   rR   r�   rž   r›   rŸ   rœ   r    rM   rY   r5   r   )r”   r•   r–   r   r=   rA   r   r   ry   r†   rŽ   r¤   r;   r;   r;   r<   r4     sH    	îaõ7õJùc                   @  ó   e Zd Zddd„ZdS )	r6   r|   r3   r5   ÚNonec                 C  ó4   || _ t |j¡| _t |j¡| _t |j¡| _d S rd   )Ú_eventsr   Úto_raw_response_wrapperry   r†   rŽ   ©r:   r|   r;   r;   r<   Ú__init__O  ó   ÿÿ
ÿzEventsWithRawResponse.__init__N©r|   r3   r5   r¦   ©r”   r•   r–   r«   r;   r;   r;   r<   r6   N  ó    r6   c                   @  r¥   )	r—   r|   r4   r5   r¦   c                 C  r§   rd   )r¨   r   Úasync_to_raw_response_wrapperry   r†   rŽ   rª   r;   r;   r<   r«   ^  r¬   z#AsyncEventsWithRawResponse.__init__N©r|   r4   r5   r¦   r®   r;   r;   r;   r<   r—   ]  r¯   r—   c                   @  r¥   )	r?   r|   r3   r5   r¦   c                 C  ó.   || _ t|jƒ| _t|jƒ| _t|jƒ| _d S rd   )r¨   r"   ry   r†   rŽ   rª   r;   r;   r<   r«   m  ó   ÿÿ
ÿz$EventsWithStreamingResponse.__init__Nr­   r®   r;   r;   r;   r<   r?   l  r¯   r?   c                   @  r¥   )	r˜   r|   r4   r5   r¦   c                 C  r²   rd   )r¨   r#   ry   r†   rŽ   rª   r;   r;   r<   r«   |  r³   z)AsyncEventsWithStreamingResponse.__init__Nr±   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_paramsr/   Ú5types.beta.sessions.beta_managed_agents_session_eventr0   Ú;types.beta.sessions.beta_managed_agents_send_session_eventsr1   Ú=types.beta.sessions.beta_managed_agents_stream_session_eventsr2   Ú__all__r3   r4   r6   r—   r?   r˜   r;   r;   r;   r<   Ú<module>   sH    ( h  C