# This file was auto-generated by Fern from our API Definition.

import contextlib
import json
import typing
from json.decoder import JSONDecodeError

import httpx_sse
from .. import core
from ..core.api_error import ApiError
from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper
from ..core.http_response import AsyncHttpResponse, HttpResponse
from ..core.jsonable_encoder import jsonable_encoder
from ..core.request_options import RequestOptions
from ..core.serialization import convert_and_respect_annotation_metadata
from ..core.unchecked_base_model import construct_type
from ..errors.unprocessable_entity_error import UnprocessableEntityError
from ..types.active_agent_response import ActiveAgentResponse
from ..types.agent import Agent
from ..types.async_interaction_accepted_response import AsyncInteractionAcceptedResponse
from ..types.delete_agent_response import DeleteAgentResponse
from ..types.http_validation_error import HttpValidationError
from ..types.incoming_message import IncomingMessage
from ..types.upsert_agent_response import UpsertAgentResponse

# this is used as the default value for optional parameters
OMIT = typing.cast(typing.Any, ...)


class RawAgentsClient:
    def __init__(self, *, client_wrapper: SyncClientWrapper):
        self._client_wrapper = client_wrapper

    @contextlib.contextmanager
    def interact(
        self,
        agent_id: str,
        *,
        messages: typing.Sequence[IncomingMessage],
        session_id: typing.Optional[str] = None,
        metadata: typing.Optional[typing.Dict[str, typing.Optional[typing.Any]]] = OMIT,
        callback_url: typing.Optional[str] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> typing.Iterator[HttpResponse[typing.Iterator[typing.Optional[typing.Any]]]]:
        """
        Parameters
        ----------
        agent_id : str

        messages : typing.Sequence[IncomingMessage]
            List of incoming user messages and drive file references.

        session_id : typing.Optional[str]

        metadata : typing.Optional[typing.Dict[str, typing.Optional[typing.Any]]]
            Optional metadata (e.g., salesforce_session)

        callback_url : typing.Optional[str]
            Optional callback URL. If provided, the interaction runs asynchronously and the response returns 202 with session_id + events_url.

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Yields
        ------
        typing.Iterator[HttpResponse[typing.Iterator[typing.Optional[typing.Any]]]]
            Successful Response
        """
        with self._client_wrapper.httpx_client.stream(
            f"world/{jsonable_encoder(agent_id)}/_interact",
            method="POST",
            params={
                "session_id": session_id,
            },
            json={
                "messages": convert_and_respect_annotation_metadata(
                    object_=messages, annotation=typing.Sequence[IncomingMessage], direction="write"
                ),
                "metadata": metadata,
                "callback_url": callback_url,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        ) as _response:

            def _stream() -> HttpResponse[typing.Iterator[typing.Optional[typing.Any]]]:
                try:
                    if 200 <= _response.status_code < 300:

                        def _iter():
                            _event_source = httpx_sse.EventSource(_response)
                            for _sse in _event_source.iter_sse():
                                if _sse.data == None:
                                    return
                                try:
                                    yield typing.cast(
                                        typing.Optional[typing.Any],
                                        construct_type(
                                            type_=typing.Optional[typing.Any],  # type: ignore
                                            object_=json.loads(_sse.data),
                                        ),
                                    )
                                except Exception:
                                    pass
                            return

                        return HttpResponse(response=_response, data=_iter())
                    _response.read()
                    if _response.status_code == 422:
                        raise UnprocessableEntityError(
                            headers=dict(_response.headers),
                            body=typing.cast(
                                HttpValidationError,
                                construct_type(
                                    type_=HttpValidationError,  # type: ignore
                                    object_=_response.json(),
                                ),
                            ),
                        )
                    _response_json = _response.json()
                except JSONDecodeError:
                    raise ApiError(
                        status_code=_response.status_code, headers=dict(_response.headers), body=_response.text
                    )
                raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

            yield _stream()

    def interact_sync(
        self,
        agent_id: str,
        *,
        messages: typing.Sequence[IncomingMessage],
        session_id: typing.Optional[str] = None,
        metadata: typing.Optional[typing.Dict[str, typing.Optional[typing.Any]]] = OMIT,
        callback_url: typing.Optional[str] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[typing.Optional[typing.Any]]:
        """
        Parameters
        ----------
        agent_id : str

        messages : typing.Sequence[IncomingMessage]
            List of incoming user messages and drive file references.

        session_id : typing.Optional[str]

        metadata : typing.Optional[typing.Dict[str, typing.Optional[typing.Any]]]
            Optional metadata (e.g., salesforce_session)

        callback_url : typing.Optional[str]
            Optional callback URL. If provided, the interaction runs asynchronously and the response returns 202 with session_id + events_url.

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        HttpResponse[typing.Optional[typing.Any]]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            f"world/{jsonable_encoder(agent_id)}/_interact_sync",
            method="POST",
            params={
                "session_id": session_id,
            },
            json={
                "messages": convert_and_respect_annotation_metadata(
                    object_=messages, annotation=typing.Sequence[IncomingMessage], direction="write"
                ),
                "metadata": metadata,
                "callback_url": callback_url,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if _response is None or not _response.text.strip():
                return HttpResponse(response=_response, data=None)
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    typing.Optional[typing.Any],
                    construct_type(
                        type_=typing.Optional[typing.Any],  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        HttpValidationError,
                        construct_type(
                            type_=HttpValidationError,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    @contextlib.contextmanager
    def interact_with_session(
        self,
        agent_id: str,
        session_id: typing.Optional[str],
        *,
        messages: typing.Sequence[IncomingMessage],
        metadata: typing.Optional[typing.Dict[str, typing.Optional[typing.Any]]] = OMIT,
        callback_url: typing.Optional[str] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> typing.Iterator[HttpResponse[typing.Iterator[typing.Optional[typing.Any]]]]:
        """
        Parameters
        ----------
        agent_id : str

        session_id : typing.Optional[str]

        messages : typing.Sequence[IncomingMessage]
            List of incoming user messages and drive file references.

        metadata : typing.Optional[typing.Dict[str, typing.Optional[typing.Any]]]
            Optional metadata (e.g., salesforce_session)

        callback_url : typing.Optional[str]
            Optional callback URL. If provided, the interaction runs asynchronously and the response returns 202 with session_id + events_url.

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Yields
        ------
        typing.Iterator[HttpResponse[typing.Iterator[typing.Optional[typing.Any]]]]
            Successful Response
        """
        with self._client_wrapper.httpx_client.stream(
            f"world/{jsonable_encoder(agent_id)}/{jsonable_encoder(session_id)}/_interact",
            method="POST",
            json={
                "messages": convert_and_respect_annotation_metadata(
                    object_=messages, annotation=typing.Sequence[IncomingMessage], direction="write"
                ),
                "metadata": metadata,
                "callback_url": callback_url,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        ) as _response:

            def _stream() -> HttpResponse[typing.Iterator[typing.Optional[typing.Any]]]:
                try:
                    if 200 <= _response.status_code < 300:

                        def _iter():
                            _event_source = httpx_sse.EventSource(_response)
                            for _sse in _event_source.iter_sse():
                                if _sse.data == None:
                                    return
                                try:
                                    yield typing.cast(
                                        typing.Optional[typing.Any],
                                        construct_type(
                                            type_=typing.Optional[typing.Any],  # type: ignore
                                            object_=json.loads(_sse.data),
                                        ),
                                    )
                                except Exception:
                                    pass
                            return

                        return HttpResponse(response=_response, data=_iter())
                    _response.read()
                    if _response.status_code == 422:
                        raise UnprocessableEntityError(
                            headers=dict(_response.headers),
                            body=typing.cast(
                                HttpValidationError,
                                construct_type(
                                    type_=HttpValidationError,  # type: ignore
                                    object_=_response.json(),
                                ),
                            ),
                        )
                    _response_json = _response.json()
                except JSONDecodeError:
                    raise ApiError(
                        status_code=_response.status_code, headers=dict(_response.headers), body=_response.text
                    )
                raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

            yield _stream()

    def interact_sync_with_session(
        self,
        agent_id: str,
        session_id: typing.Optional[str],
        *,
        messages: typing.Sequence[IncomingMessage],
        metadata: typing.Optional[typing.Dict[str, typing.Optional[typing.Any]]] = OMIT,
        callback_url: typing.Optional[str] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[typing.Optional[typing.Any]]:
        """
        Parameters
        ----------
        agent_id : str

        session_id : typing.Optional[str]

        messages : typing.Sequence[IncomingMessage]
            List of incoming user messages and drive file references.

        metadata : typing.Optional[typing.Dict[str, typing.Optional[typing.Any]]]
            Optional metadata (e.g., salesforce_session)

        callback_url : typing.Optional[str]
            Optional callback URL. If provided, the interaction runs asynchronously and the response returns 202 with session_id + events_url.

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        HttpResponse[typing.Optional[typing.Any]]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            f"world/{jsonable_encoder(agent_id)}/{jsonable_encoder(session_id)}/_interact_sync",
            method="POST",
            json={
                "messages": convert_and_respect_annotation_metadata(
                    object_=messages, annotation=typing.Sequence[IncomingMessage], direction="write"
                ),
                "metadata": metadata,
                "callback_url": callback_url,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if _response is None or not _response.text.strip():
                return HttpResponse(response=_response, data=None)
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    typing.Optional[typing.Any],
                    construct_type(
                        type_=typing.Optional[typing.Any],  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        HttpValidationError,
                        construct_type(
                            type_=HttpValidationError,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    def interact_async(
        self,
        agent_id: str,
        *,
        messages: typing.Sequence[IncomingMessage],
        callback_url: str,
        session_id: typing.Optional[str] = None,
        metadata: typing.Optional[typing.Dict[str, typing.Optional[typing.Any]]] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[AsyncInteractionAcceptedResponse]:
        """
        Dedicated handler for async agent interactions exposed via the SDK.

        Requires callback_url and always returns 202 with session_id + events_url.

        Parameters
        ----------
        agent_id : str

        messages : typing.Sequence[IncomingMessage]
            List of incoming user messages and drive file references.

        callback_url : str
            Callback URL that Scout will POST to when the interaction completes. The request is signed with HMAC-SHA256 using the organization's secret key.

        session_id : typing.Optional[str]

        metadata : typing.Optional[typing.Dict[str, typing.Optional[typing.Any]]]
            Optional metadata (e.g., salesforce_session)

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        HttpResponse[AsyncInteractionAcceptedResponse]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            f"world/{jsonable_encoder(agent_id)}/_interact_async",
            method="POST",
            params={
                "session_id": session_id,
            },
            json={
                "messages": convert_and_respect_annotation_metadata(
                    object_=messages, annotation=typing.Sequence[IncomingMessage], direction="write"
                ),
                "metadata": metadata,
                "callback_url": callback_url,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    AsyncInteractionAcceptedResponse,
                    construct_type(
                        type_=AsyncInteractionAcceptedResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        HttpValidationError,
                        construct_type(
                            type_=HttpValidationError,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    def interact_async_with_session(
        self,
        agent_id: str,
        session_id: typing.Optional[str],
        *,
        messages: typing.Sequence[IncomingMessage],
        callback_url: str,
        metadata: typing.Optional[typing.Dict[str, typing.Optional[typing.Any]]] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[AsyncInteractionAcceptedResponse]:
        """
        Dedicated handler for async agent interactions exposed via the SDK.

        Requires callback_url and always returns 202 with session_id + events_url.

        Parameters
        ----------
        agent_id : str

        session_id : typing.Optional[str]

        messages : typing.Sequence[IncomingMessage]
            List of incoming user messages and drive file references.

        callback_url : str
            Callback URL that Scout will POST to when the interaction completes. The request is signed with HMAC-SHA256 using the organization's secret key.

        metadata : typing.Optional[typing.Dict[str, typing.Optional[typing.Any]]]
            Optional metadata (e.g., salesforce_session)

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        HttpResponse[AsyncInteractionAcceptedResponse]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            f"world/{jsonable_encoder(agent_id)}/{jsonable_encoder(session_id)}/_interact_async",
            method="POST",
            json={
                "messages": convert_and_respect_annotation_metadata(
                    object_=messages, annotation=typing.Sequence[IncomingMessage], direction="write"
                ),
                "metadata": metadata,
                "callback_url": callback_url,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    AsyncInteractionAcceptedResponse,
                    construct_type(
                        type_=AsyncInteractionAcceptedResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        HttpValidationError,
                        construct_type(
                            type_=HttpValidationError,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    def list(self, *, request_options: typing.Optional[RequestOptions] = None) -> HttpResponse[typing.List[Agent]]:
        """
        Parameters
        ----------
        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        HttpResponse[typing.List[Agent]]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            "agents",
            method="GET",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    typing.List[Agent],
                    construct_type(
                        type_=typing.List[Agent],  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    def upsert(
        self,
        *,
        agent: str,
        revision: str,
        agent_id: typing.Optional[str] = OMIT,
        activate: typing.Optional[bool] = OMIT,
        agent_image: typing.Optional[core.File] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[UpsertAgentResponse]:
        """
        Parameters
        ----------
        agent : str

        revision : str

        agent_id : typing.Optional[str]

        activate : typing.Optional[bool]

        agent_image : typing.Optional[core.File]
            See core.File for more documentation

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        HttpResponse[UpsertAgentResponse]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            "agents",
            method="POST",
            data={
                "agent": agent,
                "agent_id": agent_id,
                "activate": activate,
                "revision": revision,
            },
            files={
                **({"agent_image": agent_image} if agent_image is not None else {}),
            },
            request_options=request_options,
            omit=OMIT,
            force_multipart=True,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    UpsertAgentResponse,
                    construct_type(
                        type_=UpsertAgentResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        HttpValidationError,
                        construct_type(
                            type_=HttpValidationError,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    def get(
        self, agent_id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> HttpResponse[ActiveAgentResponse]:
        """
        Retrieve an agent and its active revision by agent_id.
        Verifies that the agent belongs to the actor's organization.

        Parameters
        ----------
        agent_id : str

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        HttpResponse[ActiveAgentResponse]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            f"agents/{jsonable_encoder(agent_id)}/active",
            method="GET",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    ActiveAgentResponse,
                    construct_type(
                        type_=ActiveAgentResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        HttpValidationError,
                        construct_type(
                            type_=HttpValidationError,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    def delete(
        self, agent_id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> HttpResponse[DeleteAgentResponse]:
        """
        Parameters
        ----------
        agent_id : str

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        HttpResponse[DeleteAgentResponse]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            f"agents/{jsonable_encoder(agent_id)}",
            method="DELETE",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    DeleteAgentResponse,
                    construct_type(
                        type_=DeleteAgentResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        HttpValidationError,
                        construct_type(
                            type_=HttpValidationError,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)


class AsyncRawAgentsClient:
    def __init__(self, *, client_wrapper: AsyncClientWrapper):
        self._client_wrapper = client_wrapper

    @contextlib.asynccontextmanager
    async def interact(
        self,
        agent_id: str,
        *,
        messages: typing.Sequence[IncomingMessage],
        session_id: typing.Optional[str] = None,
        metadata: typing.Optional[typing.Dict[str, typing.Optional[typing.Any]]] = OMIT,
        callback_url: typing.Optional[str] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> typing.AsyncIterator[AsyncHttpResponse[typing.AsyncIterator[typing.Optional[typing.Any]]]]:
        """
        Parameters
        ----------
        agent_id : str

        messages : typing.Sequence[IncomingMessage]
            List of incoming user messages and drive file references.

        session_id : typing.Optional[str]

        metadata : typing.Optional[typing.Dict[str, typing.Optional[typing.Any]]]
            Optional metadata (e.g., salesforce_session)

        callback_url : typing.Optional[str]
            Optional callback URL. If provided, the interaction runs asynchronously and the response returns 202 with session_id + events_url.

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Yields
        ------
        typing.AsyncIterator[AsyncHttpResponse[typing.AsyncIterator[typing.Optional[typing.Any]]]]
            Successful Response
        """
        async with self._client_wrapper.httpx_client.stream(
            f"world/{jsonable_encoder(agent_id)}/_interact",
            method="POST",
            params={
                "session_id": session_id,
            },
            json={
                "messages": convert_and_respect_annotation_metadata(
                    object_=messages, annotation=typing.Sequence[IncomingMessage], direction="write"
                ),
                "metadata": metadata,
                "callback_url": callback_url,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        ) as _response:

            async def _stream() -> AsyncHttpResponse[typing.AsyncIterator[typing.Optional[typing.Any]]]:
                try:
                    if 200 <= _response.status_code < 300:

                        async def _iter():
                            _event_source = httpx_sse.EventSource(_response)
                            async for _sse in _event_source.aiter_sse():
                                if _sse.data == None:
                                    return
                                try:
                                    yield typing.cast(
                                        typing.Optional[typing.Any],
                                        construct_type(
                                            type_=typing.Optional[typing.Any],  # type: ignore
                                            object_=json.loads(_sse.data),
                                        ),
                                    )
                                except Exception:
                                    pass
                            return

                        return AsyncHttpResponse(response=_response, data=_iter())
                    await _response.aread()
                    if _response.status_code == 422:
                        raise UnprocessableEntityError(
                            headers=dict(_response.headers),
                            body=typing.cast(
                                HttpValidationError,
                                construct_type(
                                    type_=HttpValidationError,  # type: ignore
                                    object_=_response.json(),
                                ),
                            ),
                        )
                    _response_json = _response.json()
                except JSONDecodeError:
                    raise ApiError(
                        status_code=_response.status_code, headers=dict(_response.headers), body=_response.text
                    )
                raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

            yield await _stream()

    async def interact_sync(
        self,
        agent_id: str,
        *,
        messages: typing.Sequence[IncomingMessage],
        session_id: typing.Optional[str] = None,
        metadata: typing.Optional[typing.Dict[str, typing.Optional[typing.Any]]] = OMIT,
        callback_url: typing.Optional[str] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[typing.Optional[typing.Any]]:
        """
        Parameters
        ----------
        agent_id : str

        messages : typing.Sequence[IncomingMessage]
            List of incoming user messages and drive file references.

        session_id : typing.Optional[str]

        metadata : typing.Optional[typing.Dict[str, typing.Optional[typing.Any]]]
            Optional metadata (e.g., salesforce_session)

        callback_url : typing.Optional[str]
            Optional callback URL. If provided, the interaction runs asynchronously and the response returns 202 with session_id + events_url.

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        AsyncHttpResponse[typing.Optional[typing.Any]]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"world/{jsonable_encoder(agent_id)}/_interact_sync",
            method="POST",
            params={
                "session_id": session_id,
            },
            json={
                "messages": convert_and_respect_annotation_metadata(
                    object_=messages, annotation=typing.Sequence[IncomingMessage], direction="write"
                ),
                "metadata": metadata,
                "callback_url": callback_url,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if _response is None or not _response.text.strip():
                return AsyncHttpResponse(response=_response, data=None)
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    typing.Optional[typing.Any],
                    construct_type(
                        type_=typing.Optional[typing.Any],  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        HttpValidationError,
                        construct_type(
                            type_=HttpValidationError,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    @contextlib.asynccontextmanager
    async def interact_with_session(
        self,
        agent_id: str,
        session_id: typing.Optional[str],
        *,
        messages: typing.Sequence[IncomingMessage],
        metadata: typing.Optional[typing.Dict[str, typing.Optional[typing.Any]]] = OMIT,
        callback_url: typing.Optional[str] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> typing.AsyncIterator[AsyncHttpResponse[typing.AsyncIterator[typing.Optional[typing.Any]]]]:
        """
        Parameters
        ----------
        agent_id : str

        session_id : typing.Optional[str]

        messages : typing.Sequence[IncomingMessage]
            List of incoming user messages and drive file references.

        metadata : typing.Optional[typing.Dict[str, typing.Optional[typing.Any]]]
            Optional metadata (e.g., salesforce_session)

        callback_url : typing.Optional[str]
            Optional callback URL. If provided, the interaction runs asynchronously and the response returns 202 with session_id + events_url.

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Yields
        ------
        typing.AsyncIterator[AsyncHttpResponse[typing.AsyncIterator[typing.Optional[typing.Any]]]]
            Successful Response
        """
        async with self._client_wrapper.httpx_client.stream(
            f"world/{jsonable_encoder(agent_id)}/{jsonable_encoder(session_id)}/_interact",
            method="POST",
            json={
                "messages": convert_and_respect_annotation_metadata(
                    object_=messages, annotation=typing.Sequence[IncomingMessage], direction="write"
                ),
                "metadata": metadata,
                "callback_url": callback_url,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        ) as _response:

            async def _stream() -> AsyncHttpResponse[typing.AsyncIterator[typing.Optional[typing.Any]]]:
                try:
                    if 200 <= _response.status_code < 300:

                        async def _iter():
                            _event_source = httpx_sse.EventSource(_response)
                            async for _sse in _event_source.aiter_sse():
                                if _sse.data == None:
                                    return
                                try:
                                    yield typing.cast(
                                        typing.Optional[typing.Any],
                                        construct_type(
                                            type_=typing.Optional[typing.Any],  # type: ignore
                                            object_=json.loads(_sse.data),
                                        ),
                                    )
                                except Exception:
                                    pass
                            return

                        return AsyncHttpResponse(response=_response, data=_iter())
                    await _response.aread()
                    if _response.status_code == 422:
                        raise UnprocessableEntityError(
                            headers=dict(_response.headers),
                            body=typing.cast(
                                HttpValidationError,
                                construct_type(
                                    type_=HttpValidationError,  # type: ignore
                                    object_=_response.json(),
                                ),
                            ),
                        )
                    _response_json = _response.json()
                except JSONDecodeError:
                    raise ApiError(
                        status_code=_response.status_code, headers=dict(_response.headers), body=_response.text
                    )
                raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

            yield await _stream()

    async def interact_sync_with_session(
        self,
        agent_id: str,
        session_id: typing.Optional[str],
        *,
        messages: typing.Sequence[IncomingMessage],
        metadata: typing.Optional[typing.Dict[str, typing.Optional[typing.Any]]] = OMIT,
        callback_url: typing.Optional[str] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[typing.Optional[typing.Any]]:
        """
        Parameters
        ----------
        agent_id : str

        session_id : typing.Optional[str]

        messages : typing.Sequence[IncomingMessage]
            List of incoming user messages and drive file references.

        metadata : typing.Optional[typing.Dict[str, typing.Optional[typing.Any]]]
            Optional metadata (e.g., salesforce_session)

        callback_url : typing.Optional[str]
            Optional callback URL. If provided, the interaction runs asynchronously and the response returns 202 with session_id + events_url.

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        AsyncHttpResponse[typing.Optional[typing.Any]]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"world/{jsonable_encoder(agent_id)}/{jsonable_encoder(session_id)}/_interact_sync",
            method="POST",
            json={
                "messages": convert_and_respect_annotation_metadata(
                    object_=messages, annotation=typing.Sequence[IncomingMessage], direction="write"
                ),
                "metadata": metadata,
                "callback_url": callback_url,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if _response is None or not _response.text.strip():
                return AsyncHttpResponse(response=_response, data=None)
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    typing.Optional[typing.Any],
                    construct_type(
                        type_=typing.Optional[typing.Any],  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        HttpValidationError,
                        construct_type(
                            type_=HttpValidationError,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    async def interact_async(
        self,
        agent_id: str,
        *,
        messages: typing.Sequence[IncomingMessage],
        callback_url: str,
        session_id: typing.Optional[str] = None,
        metadata: typing.Optional[typing.Dict[str, typing.Optional[typing.Any]]] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[AsyncInteractionAcceptedResponse]:
        """
        Dedicated handler for async agent interactions exposed via the SDK.

        Requires callback_url and always returns 202 with session_id + events_url.

        Parameters
        ----------
        agent_id : str

        messages : typing.Sequence[IncomingMessage]
            List of incoming user messages and drive file references.

        callback_url : str
            Callback URL that Scout will POST to when the interaction completes. The request is signed with HMAC-SHA256 using the organization's secret key.

        session_id : typing.Optional[str]

        metadata : typing.Optional[typing.Dict[str, typing.Optional[typing.Any]]]
            Optional metadata (e.g., salesforce_session)

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        AsyncHttpResponse[AsyncInteractionAcceptedResponse]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"world/{jsonable_encoder(agent_id)}/_interact_async",
            method="POST",
            params={
                "session_id": session_id,
            },
            json={
                "messages": convert_and_respect_annotation_metadata(
                    object_=messages, annotation=typing.Sequence[IncomingMessage], direction="write"
                ),
                "metadata": metadata,
                "callback_url": callback_url,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    AsyncInteractionAcceptedResponse,
                    construct_type(
                        type_=AsyncInteractionAcceptedResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        HttpValidationError,
                        construct_type(
                            type_=HttpValidationError,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    async def interact_async_with_session(
        self,
        agent_id: str,
        session_id: typing.Optional[str],
        *,
        messages: typing.Sequence[IncomingMessage],
        callback_url: str,
        metadata: typing.Optional[typing.Dict[str, typing.Optional[typing.Any]]] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[AsyncInteractionAcceptedResponse]:
        """
        Dedicated handler for async agent interactions exposed via the SDK.

        Requires callback_url and always returns 202 with session_id + events_url.

        Parameters
        ----------
        agent_id : str

        session_id : typing.Optional[str]

        messages : typing.Sequence[IncomingMessage]
            List of incoming user messages and drive file references.

        callback_url : str
            Callback URL that Scout will POST to when the interaction completes. The request is signed with HMAC-SHA256 using the organization's secret key.

        metadata : typing.Optional[typing.Dict[str, typing.Optional[typing.Any]]]
            Optional metadata (e.g., salesforce_session)

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        AsyncHttpResponse[AsyncInteractionAcceptedResponse]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"world/{jsonable_encoder(agent_id)}/{jsonable_encoder(session_id)}/_interact_async",
            method="POST",
            json={
                "messages": convert_and_respect_annotation_metadata(
                    object_=messages, annotation=typing.Sequence[IncomingMessage], direction="write"
                ),
                "metadata": metadata,
                "callback_url": callback_url,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    AsyncInteractionAcceptedResponse,
                    construct_type(
                        type_=AsyncInteractionAcceptedResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        HttpValidationError,
                        construct_type(
                            type_=HttpValidationError,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    async def list(
        self, *, request_options: typing.Optional[RequestOptions] = None
    ) -> AsyncHttpResponse[typing.List[Agent]]:
        """
        Parameters
        ----------
        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        AsyncHttpResponse[typing.List[Agent]]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            "agents",
            method="GET",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    typing.List[Agent],
                    construct_type(
                        type_=typing.List[Agent],  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    async def upsert(
        self,
        *,
        agent: str,
        revision: str,
        agent_id: typing.Optional[str] = OMIT,
        activate: typing.Optional[bool] = OMIT,
        agent_image: typing.Optional[core.File] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[UpsertAgentResponse]:
        """
        Parameters
        ----------
        agent : str

        revision : str

        agent_id : typing.Optional[str]

        activate : typing.Optional[bool]

        agent_image : typing.Optional[core.File]
            See core.File for more documentation

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        AsyncHttpResponse[UpsertAgentResponse]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            "agents",
            method="POST",
            data={
                "agent": agent,
                "agent_id": agent_id,
                "activate": activate,
                "revision": revision,
            },
            files={
                **({"agent_image": agent_image} if agent_image is not None else {}),
            },
            request_options=request_options,
            omit=OMIT,
            force_multipart=True,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    UpsertAgentResponse,
                    construct_type(
                        type_=UpsertAgentResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        HttpValidationError,
                        construct_type(
                            type_=HttpValidationError,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    async def get(
        self, agent_id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> AsyncHttpResponse[ActiveAgentResponse]:
        """
        Retrieve an agent and its active revision by agent_id.
        Verifies that the agent belongs to the actor's organization.

        Parameters
        ----------
        agent_id : str

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        AsyncHttpResponse[ActiveAgentResponse]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"agents/{jsonable_encoder(agent_id)}/active",
            method="GET",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    ActiveAgentResponse,
                    construct_type(
                        type_=ActiveAgentResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        HttpValidationError,
                        construct_type(
                            type_=HttpValidationError,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    async def delete(
        self, agent_id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> AsyncHttpResponse[DeleteAgentResponse]:
        """
        Parameters
        ----------
        agent_id : str

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        AsyncHttpResponse[DeleteAgentResponse]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"agents/{jsonable_encoder(agent_id)}",
            method="DELETE",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    DeleteAgentResponse,
                    construct_type(
                        type_=DeleteAgentResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        HttpValidationError,
                        construct_type(
                            type_=HttpValidationError,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)
