Skip to content

OpenCodeSharer

Base classes

Name Children Inherits
TextSharer
anyenv.text_sharing.base
Base class for text sharing services.

â‹” Inheritance diagram

graph TD
  2804631139["opencode.OpenCodeSharer"]
  2782231920["base.TextSharer"]
  925645236["abc.ABC"]
  2751680898["builtins.object"]
  2782231920 --> 2804631139
  925645236 --> 2782231920
  2751680898 --> 925645236

🛈 DocStrings

Bases: TextSharer

OpenCode text sharing service.

Creates fake sessions by generating UUIDs and syncing content via the share API. OpenCode doesn't validate session existence, allowing us to create ad-hoc shares.

Examples:

Share a simple string:

async with OpenCodeSharer() as sharer:
    result = await sharer.share("Hello, World!", title="My Share")
    print(result.url)  # https://opencode.ai/s/abc12345

Share a conversation:

from anyenv.text_sharing.opencode import Message

messages = [
    Message.text("user", "What is Python?"),
    Message.text("assistant", "Python is a programming language."),
    Message.text("user", "Tell me more!"),
    Message.text("assistant", "It's great for scripting and automation."),
]

async with OpenCodeSharer() as sharer:
    result = await sharer.share_conversation(
        messages,
        title="Python Discussion"
    )
    print(result.url)

Source code in src/anyenv/text_sharing/opencode.py
class OpenCodeSharer(TextSharer):
    """OpenCode text sharing service.

    Creates fake sessions by generating UUIDs and syncing content via the share API.
    OpenCode doesn't validate session existence, allowing us to create ad-hoc shares.

    Examples:
        Share a simple string:
        ```python
        async with OpenCodeSharer() as sharer:
            result = await sharer.share("Hello, World!", title="My Share")
            print(result.url)  # https://opencode.ai/s/abc12345
        ```

        Share a conversation:
        ```python
        from anyenv.text_sharing.opencode import Message

        messages = [
            Message.text("user", "What is Python?"),
            Message.text("assistant", "Python is a programming language."),
            Message.text("user", "Tell me more!"),
            Message.text("assistant", "It's great for scripting and automation."),
        ]

        async with OpenCodeSharer() as sharer:
            result = await sharer.share_conversation(
                messages,
                title="Python Discussion"
            )
            print(result.url)
        ```
    """

    def __init__(
        self,
        *,
        api_url: str | None = None,
        timeout: float = 30.0,
    ) -> None:
        """Initialize OpenCode sharer.

        Args:
            api_url: OpenCode API URL (defaults to production)
            timeout: Request timeout in seconds
        """
        self.api_url = api_url or "https://api.opencode.ai"
        self.timeout = timeout
        self._httpx = get_httpx_module()  # httpx2 preferred, legacy httpx as fallback
        self._client = self._httpx.AsyncClient(timeout=timeout)

    @property
    def name(self) -> str:
        """Name of the sharing service."""
        return "OpenCode"

    async def share(
        self,
        content: str,
        *,
        title: str | None = None,
        syntax: str | None = None,
        visibility: Visibility = "unlisted",
        expires_in: int | None = None,
    ) -> ShareResult:
        """Share text content via OpenCode.

        Args:
            content: The text content to share
            title: Optional title for the shared content
            syntax: Syntax highlighting hint (ignored - OpenCode handles this)
            visibility: Visibility level (ignored - OpenCode uses private shares)
            expires_in: Expiration time (ignored - OpenCode doesn't support expiration)

        Returns:
            ShareResult with OpenCode share URL
        """
        try:
            session_id = str(uuid.uuid4())
            message_id = str(uuid.uuid4())
            part_id = str(uuid.uuid4())
            current_time = int(time.time() * 1000)

            # Create share (returns secret and URL)
            resp = await self._client.post(
                f"{self.api_url}/share_create",
                json={"sessionID": session_id},
            )
            resp.raise_for_status()
            share_data = resp.json()
            secret = share_data["secret"]
            share_url = share_data["url"]

            # Sync session info
            info_key = f"session/info/{session_id}"
            info_content = {
                "id": session_id,
                "projectID": "shared-content",
                "directory": "/tmp",
                "title": title or "Shared Content",
                "version": "1.0.0",
                "time": {
                    "created": current_time,
                    "updated": current_time,
                },
            }

            resp = await self._client.post(
                f"{self.api_url}/share_sync",
                json={
                    "sessionID": session_id,
                    "secret": secret,
                    "key": info_key,
                    "content": info_content,
                },
            )
            resp.raise_for_status()

            # Sync message
            msg_key = f"session/message/{session_id}/{message_id}"
            msg_content = {
                "id": message_id,
                "sessionID": session_id,
                "role": "user",
                "time": {"created": current_time},
            }

            resp = await self._client.post(
                f"{self.api_url}/share_sync",
                json={
                    "sessionID": session_id,
                    "secret": secret,
                    "key": msg_key,
                    "content": msg_content,
                },
            )
            resp.raise_for_status()

            # Sync text part with actual content
            part_key = f"session/part/{session_id}/{message_id}/{part_id}"
            part_content = {
                "id": part_id,
                "sessionID": session_id,
                "messageID": message_id,
                "type": "text",
                "text": content,
            }

            resp = await self._client.post(
                f"{self.api_url}/share_sync",
                json={
                    "sessionID": session_id,
                    "secret": secret,
                    "key": part_key,
                    "content": part_content,
                },
            )
            resp.raise_for_status()

            # Store secret in delete_url for later deletion
            delete_url = f"{self.api_url}/share_delete#{secret}"

            return ShareResult(
                url=share_url,
                raw_url=f"{self.api_url}/share_data?id={session_id[-8:]}",
                delete_url=delete_url,
                id=session_id,
            )

        except self._httpx.HTTPStatusError as e:
            if e.response.status_code == 404:  # noqa: PLR2004
                msg = "OpenCode API endpoint not found - service may be unavailable"
                raise RuntimeError(msg) from e
            if e.response.status_code == 429:  # noqa: PLR2004
                msg = "Rate limited by OpenCode API"
                raise RuntimeError(msg) from e
            msg = f"OpenCode API error (HTTP {e.response.status_code}): {e.response.text}"
            raise RuntimeError(msg) from e
        except self._httpx.RequestError as e:
            msg = f"Failed to connect to OpenCode API: {e}"
            raise RuntimeError(msg) from e

    async def share_conversation(
        self,
        messages: list[Message],
        *,
        title: str | None = None,
        visibility: Visibility = "unlisted",
        expires_in: int | None = None,
    ) -> ShareResult:
        """Share a structured conversation with multiple messages.

        This allows sharing AI chat sessions, multi-turn conversations,
        or any structured dialogue with different roles.

        Args:
            messages: List of messages to share (must have at least one)
            title: Optional title for the conversation
            visibility: Visibility level (ignored - OpenCode uses private shares)
            expires_in: Expiration time (ignored - OpenCode doesn't support expiration)

        Returns:
            ShareResult with OpenCode share URL

        Example:
            ```python
            messages = [
                Message(role="user", parts=[MessagePart(type="text", text="Hello!")]),
                Message(role="assistant", parts=[MessagePart(type="text", text="Hi!")]),
            ]
            result = await sharer.share_conversation(messages, title="My Chat")
            ```
        """
        if not messages:
            msg = "Must provide at least one message"
            raise ValueError(msg)

        try:
            session_id = str(uuid.uuid4())
            current_time = int(time.time() * 1000)

            # Create share
            resp = await self._client.post(
                f"{self.api_url}/share_create",
                json={"sessionID": session_id},
            )
            resp.raise_for_status()
            share_data = resp.json()
            secret = share_data["secret"]
            share_url = share_data["url"]

            # Sync session info
            info_key = f"session/info/{session_id}"
            info_content = {
                "id": session_id,
                "projectID": "shared-conversation",
                "directory": "/tmp",
                "title": title or "Shared Conversation",
                "version": "1.0.0",
                "time": {
                    "created": current_time,
                    "updated": current_time,
                },
            }

            resp = await self._client.post(
                f"{self.api_url}/share_sync",
                json={
                    "sessionID": session_id,
                    "secret": secret,
                    "key": info_key,
                    "content": info_content,
                },
            )
            resp.raise_for_status()

            # Sync each message and its parts
            for msg_idx, message in enumerate(messages):
                message_id = str(uuid.uuid4())
                msg_time = current_time + (msg_idx * 1000)  # Stagger timestamps

                # Sync message
                msg_key = f"session/message/{session_id}/{message_id}"
                msg_content = {
                    "id": message_id,
                    "sessionID": session_id,
                    "role": message.role,
                    "time": {"created": msg_time},
                }

                resp = await self._client.post(
                    f"{self.api_url}/share_sync",
                    json={
                        "sessionID": session_id,
                        "secret": secret,
                        "key": msg_key,
                        "content": msg_content,
                    },
                )
                resp.raise_for_status()

                # Sync each part
                for part in message.parts:
                    part_id = str(uuid.uuid4())
                    part_key = f"session/part/{session_id}/{message_id}/{part_id}"
                    part_content = {
                        "id": part_id,
                        "sessionID": session_id,
                        "messageID": message_id,
                        "type": part.type,
                        "text": part.text,
                    }

                    resp = await self._client.post(
                        f"{self.api_url}/share_sync",
                        json={
                            "sessionID": session_id,
                            "secret": secret,
                            "key": part_key,
                            "content": part_content,
                        },
                    )
                    resp.raise_for_status()

            # Store secret in delete_url for later deletion
            delete_url = f"{self.api_url}/share_delete#{secret}"

            return ShareResult(
                url=share_url,
                raw_url=f"{self.api_url}/share_data?id={session_id[-8:]}",
                delete_url=delete_url,
                id=session_id,
            )

        except self._httpx.HTTPStatusError as e:
            if e.response.status_code == 404:  # noqa: PLR2004
                msg = "OpenCode API endpoint not found - service may be unavailable"
                raise RuntimeError(msg) from e
            if e.response.status_code == 429:  # noqa: PLR2004
                msg = "Rate limited by OpenCode API"
                raise RuntimeError(msg) from e
            msg = f"OpenCode API error (HTTP {e.response.status_code}): {e.response.text}"
            raise RuntimeError(msg) from e
        except self._httpx.RequestError as e:
            msg = f"Failed to connect to OpenCode API: {e}"
            raise RuntimeError(msg) from e

    async def delete_share(self, result: ShareResult) -> bool:
        """Delete a shared session.

        Args:
            result: The ShareResult containing session ID and secret

        Returns:
            True if deletion was successful
        """
        if not result.delete_url or "#" not in result.delete_url:
            return False

        # Extract secret from delete_url
        secret = result.delete_url.split("#", 1)[1]

        try:
            resp = await self._client.post(
                f"{self.api_url}/share_delete",
                json={
                    "sessionID": result.id,
                    "secret": secret,
                },
            )
            resp.raise_for_status()
        except self._httpx.HTTPError:
            return False
        else:
            return True

    async def close(self) -> None:
        """Close the HTTP client."""
        await self._client.aclose()

    async def __aenter__(self) -> Self:
        return self

    async def __aexit__(self, *args: object) -> None:
        await self.close()

name property

name: str

Name of the sharing service.

__init__

__init__(*, api_url: str | None = None, timeout: float = 30.0) -> None

Initialize OpenCode sharer.

Parameters:

Name Type Description Default
api_url str | None

OpenCode API URL (defaults to production)

None
timeout float

Request timeout in seconds

30.0
Source code in src/anyenv/text_sharing/opencode.py
def __init__(
    self,
    *,
    api_url: str | None = None,
    timeout: float = 30.0,
) -> None:
    """Initialize OpenCode sharer.

    Args:
        api_url: OpenCode API URL (defaults to production)
        timeout: Request timeout in seconds
    """
    self.api_url = api_url or "https://api.opencode.ai"
    self.timeout = timeout
    self._httpx = get_httpx_module()  # httpx2 preferred, legacy httpx as fallback
    self._client = self._httpx.AsyncClient(timeout=timeout)

close async

close() -> None

Close the HTTP client.

Source code in src/anyenv/text_sharing/opencode.py
async def close(self) -> None:
    """Close the HTTP client."""
    await self._client.aclose()

delete_share async

delete_share(result: ShareResult) -> bool

Delete a shared session.

Parameters:

Name Type Description Default
result ShareResult

The ShareResult containing session ID and secret

required

Returns:

Type Description
bool

True if deletion was successful

Source code in src/anyenv/text_sharing/opencode.py
async def delete_share(self, result: ShareResult) -> bool:
    """Delete a shared session.

    Args:
        result: The ShareResult containing session ID and secret

    Returns:
        True if deletion was successful
    """
    if not result.delete_url or "#" not in result.delete_url:
        return False

    # Extract secret from delete_url
    secret = result.delete_url.split("#", 1)[1]

    try:
        resp = await self._client.post(
            f"{self.api_url}/share_delete",
            json={
                "sessionID": result.id,
                "secret": secret,
            },
        )
        resp.raise_for_status()
    except self._httpx.HTTPError:
        return False
    else:
        return True

share async

share(
    content: str,
    *,
    title: str | None = None,
    syntax: str | None = None,
    visibility: Visibility = "unlisted",
    expires_in: int | None = None,
) -> ShareResult

Share text content via OpenCode.

Parameters:

Name Type Description Default
content str

The text content to share

required
title str | None

Optional title for the shared content

None
syntax str | None

Syntax highlighting hint (ignored - OpenCode handles this)

None
visibility Visibility

Visibility level (ignored - OpenCode uses private shares)

'unlisted'
expires_in int | None

Expiration time (ignored - OpenCode doesn't support expiration)

None

Returns:

Type Description
ShareResult

ShareResult with OpenCode share URL

Source code in src/anyenv/text_sharing/opencode.py
async def share(
    self,
    content: str,
    *,
    title: str | None = None,
    syntax: str | None = None,
    visibility: Visibility = "unlisted",
    expires_in: int | None = None,
) -> ShareResult:
    """Share text content via OpenCode.

    Args:
        content: The text content to share
        title: Optional title for the shared content
        syntax: Syntax highlighting hint (ignored - OpenCode handles this)
        visibility: Visibility level (ignored - OpenCode uses private shares)
        expires_in: Expiration time (ignored - OpenCode doesn't support expiration)

    Returns:
        ShareResult with OpenCode share URL
    """
    try:
        session_id = str(uuid.uuid4())
        message_id = str(uuid.uuid4())
        part_id = str(uuid.uuid4())
        current_time = int(time.time() * 1000)

        # Create share (returns secret and URL)
        resp = await self._client.post(
            f"{self.api_url}/share_create",
            json={"sessionID": session_id},
        )
        resp.raise_for_status()
        share_data = resp.json()
        secret = share_data["secret"]
        share_url = share_data["url"]

        # Sync session info
        info_key = f"session/info/{session_id}"
        info_content = {
            "id": session_id,
            "projectID": "shared-content",
            "directory": "/tmp",
            "title": title or "Shared Content",
            "version": "1.0.0",
            "time": {
                "created": current_time,
                "updated": current_time,
            },
        }

        resp = await self._client.post(
            f"{self.api_url}/share_sync",
            json={
                "sessionID": session_id,
                "secret": secret,
                "key": info_key,
                "content": info_content,
            },
        )
        resp.raise_for_status()

        # Sync message
        msg_key = f"session/message/{session_id}/{message_id}"
        msg_content = {
            "id": message_id,
            "sessionID": session_id,
            "role": "user",
            "time": {"created": current_time},
        }

        resp = await self._client.post(
            f"{self.api_url}/share_sync",
            json={
                "sessionID": session_id,
                "secret": secret,
                "key": msg_key,
                "content": msg_content,
            },
        )
        resp.raise_for_status()

        # Sync text part with actual content
        part_key = f"session/part/{session_id}/{message_id}/{part_id}"
        part_content = {
            "id": part_id,
            "sessionID": session_id,
            "messageID": message_id,
            "type": "text",
            "text": content,
        }

        resp = await self._client.post(
            f"{self.api_url}/share_sync",
            json={
                "sessionID": session_id,
                "secret": secret,
                "key": part_key,
                "content": part_content,
            },
        )
        resp.raise_for_status()

        # Store secret in delete_url for later deletion
        delete_url = f"{self.api_url}/share_delete#{secret}"

        return ShareResult(
            url=share_url,
            raw_url=f"{self.api_url}/share_data?id={session_id[-8:]}",
            delete_url=delete_url,
            id=session_id,
        )

    except self._httpx.HTTPStatusError as e:
        if e.response.status_code == 404:  # noqa: PLR2004
            msg = "OpenCode API endpoint not found - service may be unavailable"
            raise RuntimeError(msg) from e
        if e.response.status_code == 429:  # noqa: PLR2004
            msg = "Rate limited by OpenCode API"
            raise RuntimeError(msg) from e
        msg = f"OpenCode API error (HTTP {e.response.status_code}): {e.response.text}"
        raise RuntimeError(msg) from e
    except self._httpx.RequestError as e:
        msg = f"Failed to connect to OpenCode API: {e}"
        raise RuntimeError(msg) from e

share_conversation async

share_conversation(
    messages: list[Message],
    *,
    title: str | None = None,
    visibility: Visibility = "unlisted",
    expires_in: int | None = None,
) -> ShareResult

Share a structured conversation with multiple messages.

This allows sharing AI chat sessions, multi-turn conversations, or any structured dialogue with different roles.

Parameters:

Name Type Description Default
messages list[Message]

List of messages to share (must have at least one)

required
title str | None

Optional title for the conversation

None
visibility Visibility

Visibility level (ignored - OpenCode uses private shares)

'unlisted'
expires_in int | None

Expiration time (ignored - OpenCode doesn't support expiration)

None

Returns:

Type Description
ShareResult

ShareResult with OpenCode share URL

Example
messages = [
    Message(role="user", parts=[MessagePart(type="text", text="Hello!")]),
    Message(role="assistant", parts=[MessagePart(type="text", text="Hi!")]),
]
result = await sharer.share_conversation(messages, title="My Chat")
Source code in src/anyenv/text_sharing/opencode.py
async def share_conversation(
    self,
    messages: list[Message],
    *,
    title: str | None = None,
    visibility: Visibility = "unlisted",
    expires_in: int | None = None,
) -> ShareResult:
    """Share a structured conversation with multiple messages.

    This allows sharing AI chat sessions, multi-turn conversations,
    or any structured dialogue with different roles.

    Args:
        messages: List of messages to share (must have at least one)
        title: Optional title for the conversation
        visibility: Visibility level (ignored - OpenCode uses private shares)
        expires_in: Expiration time (ignored - OpenCode doesn't support expiration)

    Returns:
        ShareResult with OpenCode share URL

    Example:
        ```python
        messages = [
            Message(role="user", parts=[MessagePart(type="text", text="Hello!")]),
            Message(role="assistant", parts=[MessagePart(type="text", text="Hi!")]),
        ]
        result = await sharer.share_conversation(messages, title="My Chat")
        ```
    """
    if not messages:
        msg = "Must provide at least one message"
        raise ValueError(msg)

    try:
        session_id = str(uuid.uuid4())
        current_time = int(time.time() * 1000)

        # Create share
        resp = await self._client.post(
            f"{self.api_url}/share_create",
            json={"sessionID": session_id},
        )
        resp.raise_for_status()
        share_data = resp.json()
        secret = share_data["secret"]
        share_url = share_data["url"]

        # Sync session info
        info_key = f"session/info/{session_id}"
        info_content = {
            "id": session_id,
            "projectID": "shared-conversation",
            "directory": "/tmp",
            "title": title or "Shared Conversation",
            "version": "1.0.0",
            "time": {
                "created": current_time,
                "updated": current_time,
            },
        }

        resp = await self._client.post(
            f"{self.api_url}/share_sync",
            json={
                "sessionID": session_id,
                "secret": secret,
                "key": info_key,
                "content": info_content,
            },
        )
        resp.raise_for_status()

        # Sync each message and its parts
        for msg_idx, message in enumerate(messages):
            message_id = str(uuid.uuid4())
            msg_time = current_time + (msg_idx * 1000)  # Stagger timestamps

            # Sync message
            msg_key = f"session/message/{session_id}/{message_id}"
            msg_content = {
                "id": message_id,
                "sessionID": session_id,
                "role": message.role,
                "time": {"created": msg_time},
            }

            resp = await self._client.post(
                f"{self.api_url}/share_sync",
                json={
                    "sessionID": session_id,
                    "secret": secret,
                    "key": msg_key,
                    "content": msg_content,
                },
            )
            resp.raise_for_status()

            # Sync each part
            for part in message.parts:
                part_id = str(uuid.uuid4())
                part_key = f"session/part/{session_id}/{message_id}/{part_id}"
                part_content = {
                    "id": part_id,
                    "sessionID": session_id,
                    "messageID": message_id,
                    "type": part.type,
                    "text": part.text,
                }

                resp = await self._client.post(
                    f"{self.api_url}/share_sync",
                    json={
                        "sessionID": session_id,
                        "secret": secret,
                        "key": part_key,
                        "content": part_content,
                    },
                )
                resp.raise_for_status()

        # Store secret in delete_url for later deletion
        delete_url = f"{self.api_url}/share_delete#{secret}"

        return ShareResult(
            url=share_url,
            raw_url=f"{self.api_url}/share_data?id={session_id[-8:]}",
            delete_url=delete_url,
            id=session_id,
        )

    except self._httpx.HTTPStatusError as e:
        if e.response.status_code == 404:  # noqa: PLR2004
            msg = "OpenCode API endpoint not found - service may be unavailable"
            raise RuntimeError(msg) from e
        if e.response.status_code == 429:  # noqa: PLR2004
            msg = "Rate limited by OpenCode API"
            raise RuntimeError(msg) from e
        msg = f"OpenCode API error (HTTP {e.response.status_code}): {e.response.text}"
        raise RuntimeError(msg) from e
    except self._httpx.RequestError as e:
        msg = f"Failed to connect to OpenCode API: {e}"
        raise RuntimeError(msg) from e

:fa-brands-github: Show source on GitHub