Skip to content

text_sharing

Class info

Re-exported classes

Class Module Description
GistSharer anyenv.text_sharing.github_gist Share text via GitHub Gists.
OpenCodeSharer anyenv.text_sharing.opencode OpenCode text sharing service.
PasteRsSharer anyenv.text_sharing.paste_rs Share text via paste.rs.
PastebinSharer anyenv.text_sharing.pastebin Share text via Pastebin.com.
ShareResult anyenv.text_sharing.base Result of a text sharing operation.
ShittyCodingAgentSharer anyenv.text_sharing.shittycodingagent Share text via GitHub Gists with shittycodingagent.ai preview URL.
TextSharer anyenv.text_sharing.base Base class for text sharing services.

🛈 DocStrings

Text sharing services for sharing content via paste services.

GistSharer

Bases: TextSharer

Share text via GitHub Gists.

Source code in src/anyenv/text_sharing/github_gist.py
class GistSharer(TextSharer):
    """Share text via GitHub Gists."""

    def __init__(self, token: str | None = None) -> None:
        """Initialize the GitHub Gist sharer.

        Args:
            token: GitHub personal access token. If not provided,
                   reads from GITHUB_TOKEN environment variable.
        """
        self._token = token or os.environ.get("GITHUB_TOKEN") or os.environ.get("GH_TOKEN")
        if not self._token:
            msg = "GitHub token required. Set GITHUB_TOKEN/GH_TOKEN or pass token parameter."
            raise ValueError(msg)

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

    async def share(
        self,
        content: str,
        *,
        title: str | None = None,
        syntax: str | None = None,
        visibility: Visibility = "unlisted",
        expires_in: int | None = None,
    ) -> ShareResult:
        """Share content as a GitHub Gist.

        Args:
            content: The text content to share
            title: Filename for the gist (defaults to "shared.txt" or "shared.{syntax}")
            syntax: File extension hint (e.g. "py", "md")
            visibility: "public" or "unlisted" (private not supported)
            expires_in: Ignored (gists don't expire)
        """
        import anyenv

        filename = title or f"shared.{syntax or 'txt'}"
        public = visibility == "public"
        payload: dict[str, Any] = {"files": {filename: {"content": content}}, "public": public}
        headers = {
            "Authorization": f"Bearer {self._token}",
            "Accept": "application/vnd.github+json",
            "X-GitHub-Api-Version": "2022-11-28",
        }
        url = "https://api.github.com/gists"
        response: dict[str, Any] = await anyenv.post_json(url, payload, headers=headers)
        raw_url = response["files"][filename]["raw_url"]
        return ShareResult(url=response["html_url"], raw_url=raw_url, id=response["id"])

name property

name: str

Name of the sharing service.

__init__

__init__(token: str | None = None) -> None

Initialize the GitHub Gist sharer.

Parameters:

Name Type Description Default
token str | None

GitHub personal access token. If not provided, reads from GITHUB_TOKEN environment variable.

None
Source code in src/anyenv/text_sharing/github_gist.py
def __init__(self, token: str | None = None) -> None:
    """Initialize the GitHub Gist sharer.

    Args:
        token: GitHub personal access token. If not provided,
               reads from GITHUB_TOKEN environment variable.
    """
    self._token = token or os.environ.get("GITHUB_TOKEN") or os.environ.get("GH_TOKEN")
    if not self._token:
        msg = "GitHub token required. Set GITHUB_TOKEN/GH_TOKEN or pass token parameter."
        raise ValueError(msg)

share async

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

Share content as a GitHub Gist.

Parameters:

Name Type Description Default
content str

The text content to share

required
title str | None

Filename for the gist (defaults to "shared.txt" or "shared.{syntax}")

None
syntax str | None

File extension hint (e.g. "py", "md")

None
visibility Visibility

"public" or "unlisted" (private not supported)

'unlisted'
expires_in int | None

Ignored (gists don't expire)

None
Source code in src/anyenv/text_sharing/github_gist.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 content as a GitHub Gist.

    Args:
        content: The text content to share
        title: Filename for the gist (defaults to "shared.txt" or "shared.{syntax}")
        syntax: File extension hint (e.g. "py", "md")
        visibility: "public" or "unlisted" (private not supported)
        expires_in: Ignored (gists don't expire)
    """
    import anyenv

    filename = title or f"shared.{syntax or 'txt'}"
    public = visibility == "public"
    payload: dict[str, Any] = {"files": {filename: {"content": content}}, "public": public}
    headers = {
        "Authorization": f"Bearer {self._token}",
        "Accept": "application/vnd.github+json",
        "X-GitHub-Api-Version": "2022-11-28",
    }
    url = "https://api.github.com/gists"
    response: dict[str, Any] = await anyenv.post_json(url, payload, headers=headers)
    raw_url = response["files"][filename]["raw_url"]
    return ShareResult(url=response["html_url"], raw_url=raw_url, id=response["id"])

OpenCodeSharer

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

PasteRsSharer

Bases: TextSharer

Share text via paste.rs.

Source code in src/anyenv/text_sharing/paste_rs.py
class PasteRsSharer(TextSharer):
    """Share text via paste.rs."""

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

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

        Args:
            content: The text content to share
            title: Ignored (paste.rs doesn't support titles)
            syntax: Used as file extension for syntax highlighting
            visibility: Ignored (all pastes are unlisted)
            expires_in: Ignored (paste.rs doesn't support expiration)
        """
        import anyenv

        headers = {"Content-Type": "text/plain; charset=utf-8"}
        data = content.encode()
        response = await anyenv.request("POST", "https://paste.rs/", data=data, headers=headers)
        url = response.text.strip()
        ext = syntax or "txt"
        return ShareResult(url=f"{url}.{ext}", raw_url=url)

name property

name: str

Name of the sharing service.

share async

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

Share content on paste.rs.

Parameters:

Name Type Description Default
content str

The text content to share

required
title str | None

Ignored (paste.rs doesn't support titles)

None
syntax str | None

Used as file extension for syntax highlighting

None
visibility Visibility

Ignored (all pastes are unlisted)

'unlisted'
expires_in int | None

Ignored (paste.rs doesn't support expiration)

None
Source code in src/anyenv/text_sharing/paste_rs.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 content on paste.rs.

    Args:
        content: The text content to share
        title: Ignored (paste.rs doesn't support titles)
        syntax: Used as file extension for syntax highlighting
        visibility: Ignored (all pastes are unlisted)
        expires_in: Ignored (paste.rs doesn't support expiration)
    """
    import anyenv

    headers = {"Content-Type": "text/plain; charset=utf-8"}
    data = content.encode()
    response = await anyenv.request("POST", "https://paste.rs/", data=data, headers=headers)
    url = response.text.strip()
    ext = syntax or "txt"
    return ShareResult(url=f"{url}.{ext}", raw_url=url)

PastebinSharer

Bases: TextSharer

Share text via Pastebin.com.

Source code in src/anyenv/text_sharing/pastebin.py
class PastebinSharer(TextSharer):
    """Share text via Pastebin.com."""

    def __init__(self, api_key: str | None = None) -> None:
        """Initialize the Pastebin sharer.

        Args:
            api_key: Pastebin API developer key. If not provided,
                     reads from PASTEBIN_API_KEY environment variable.
        """
        self._api_key = api_key or os.environ.get("PASTEBIN_API_KEY")
        if not self._api_key:
            msg = "Pastebin API key required. Set PASTEBIN_API_KEY or pass api_key parameter."
            raise ValueError(msg)

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

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

        Args:
            content: The text content to share
            title: Title/name of the paste
            syntax: Syntax highlighting (e.g. "python", "markdown", "javascript")
            visibility: "public", "unlisted", or "private"
            expires_in: Expiration time in seconds (rounded to nearest valid value)
        """
        import anyenv

        data: dict[str, Any] = {
            "api_dev_key": self._api_key,
            "api_option": "paste",
            "api_paste_code": content,
            "api_paste_private": VISIBILITY_MAP.get(visibility, "1"),
            "api_paste_expire_date": _get_expiry_code(expires_in),
        }

        if title:
            data["api_paste_name"] = title

        if syntax:
            data["api_paste_format"] = syntax

        response = await anyenv.post("https://pastebin.com/api/api_post.php", data=data)
        url = response.text.strip()
        if url.startswith("Bad API request"):
            msg = f"Pastebin API error: {url}"
            raise RuntimeError(msg)
        paste_key = url.split("/")[-1]
        raw_url = f"https://pastebin.com/raw/{paste_key}"
        return ShareResult(url=url, raw_url=raw_url, id=paste_key)

name property

name: str

Name of the sharing service.

__init__

__init__(api_key: str | None = None) -> None

Initialize the Pastebin sharer.

Parameters:

Name Type Description Default
api_key str | None

Pastebin API developer key. If not provided, reads from PASTEBIN_API_KEY environment variable.

None
Source code in src/anyenv/text_sharing/pastebin.py
def __init__(self, api_key: str | None = None) -> None:
    """Initialize the Pastebin sharer.

    Args:
        api_key: Pastebin API developer key. If not provided,
                 reads from PASTEBIN_API_KEY environment variable.
    """
    self._api_key = api_key or os.environ.get("PASTEBIN_API_KEY")
    if not self._api_key:
        msg = "Pastebin API key required. Set PASTEBIN_API_KEY or pass api_key parameter."
        raise ValueError(msg)

share async

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

Share content on Pastebin.com.

Parameters:

Name Type Description Default
content str

The text content to share

required
title str | None

Title/name of the paste

None
syntax str | None

Syntax highlighting (e.g. "python", "markdown", "javascript")

None
visibility Visibility

"public", "unlisted", or "private"

'unlisted'
expires_in int | None

Expiration time in seconds (rounded to nearest valid value)

None
Source code in src/anyenv/text_sharing/pastebin.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 content on Pastebin.com.

    Args:
        content: The text content to share
        title: Title/name of the paste
        syntax: Syntax highlighting (e.g. "python", "markdown", "javascript")
        visibility: "public", "unlisted", or "private"
        expires_in: Expiration time in seconds (rounded to nearest valid value)
    """
    import anyenv

    data: dict[str, Any] = {
        "api_dev_key": self._api_key,
        "api_option": "paste",
        "api_paste_code": content,
        "api_paste_private": VISIBILITY_MAP.get(visibility, "1"),
        "api_paste_expire_date": _get_expiry_code(expires_in),
    }

    if title:
        data["api_paste_name"] = title

    if syntax:
        data["api_paste_format"] = syntax

    response = await anyenv.post("https://pastebin.com/api/api_post.php", data=data)
    url = response.text.strip()
    if url.startswith("Bad API request"):
        msg = f"Pastebin API error: {url}"
        raise RuntimeError(msg)
    paste_key = url.split("/")[-1]
    raw_url = f"https://pastebin.com/raw/{paste_key}"
    return ShareResult(url=url, raw_url=raw_url, id=paste_key)

ShareResult dataclass

Result of a text sharing operation.

Source code in src/anyenv/text_sharing/base.py
@dataclass
class ShareResult:
    """Result of a text sharing operation."""

    url: str
    """URL to access the shared content."""

    raw_url: str | None = None
    """Direct URL to raw content, if available."""

    delete_url: str | None = None
    """URL to delete the content, if available."""

    id: str | None = None
    """Provider-specific ID of the shared content."""

delete_url class-attribute instance-attribute

delete_url: str | None = None

URL to delete the content, if available.

id class-attribute instance-attribute

id: str | None = None

Provider-specific ID of the shared content.

raw_url class-attribute instance-attribute

raw_url: str | None = None

Direct URL to raw content, if available.

url instance-attribute

url: str

URL to access the shared content.

ShittyCodingAgentSharer

Bases: TextSharer

Share text via GitHub Gists with shittycodingagent.ai preview URL.

Creates a secret (unlisted) GitHub Gist and returns a URL in the format: https://shittycodingagent.ai/session?{gist_id}

Source code in src/anyenv/text_sharing/shittycodingagent.py
class ShittyCodingAgentSharer(TextSharer):
    """Share text via GitHub Gists with shittycodingagent.ai preview URL.

    Creates a secret (unlisted) GitHub Gist and returns a URL in the format:
    https://shittycodingagent.ai/session?{gist_id}
    """

    def __init__(self, token: str | None = None) -> None:
        """Initialize the ShittyCodingAgent sharer.

        Args:
            token: GitHub personal access token. If not provided,
                   reads from GITHUB_TOKEN environment variable.
        """
        self._token = token or os.environ.get("GITHUB_TOKEN") or os.environ.get("GH_TOKEN")
        if not self._token:
            msg = "GitHub token required. Set GITHUB_TOKEN/GH_TOKEN or pass token parameter."
            raise ValueError(msg)

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

    async def share(
        self,
        content: str,
        *,
        title: str | None = None,
        syntax: str | None = None,
        visibility: Visibility = "unlisted",
        expires_in: int | None = None,
    ) -> ShareResult:
        """Share content via GitHub Gist with shittycodingagent.ai preview.

        Args:
            content: The text content to share
            title: Filename for the gist (defaults to "session.html")
            syntax: File extension hint (e.g. "html")
            visibility: Always creates unlisted gist (visibility param ignored)
            expires_in: Ignored (gists don't expire)

        Returns:
            ShareResult with shittycodingagent.ai preview URL
        """
        import anyenv

        # Default to session.html for the typical use case
        filename = title or f"session.{syntax or 'html'}"

        # Always create as unlisted (secret) gist
        payload: dict[str, Any] = {
            "files": {filename: {"content": content}},
            "public": False,
        }
        headers = {
            "Authorization": f"Bearer {self._token}",
            "Accept": "application/vnd.github+json",
            "X-GitHub-Api-Version": "2022-11-28",
        }
        url = "https://api.github.com/gists"
        response: dict[str, Any] = await anyenv.post_json(url, payload, headers=headers)

        gist_id = response["id"]
        raw_url = response["files"][filename]["raw_url"]

        # Build the shittycodingagent.ai preview URL
        preview_url = f"{PREVIEW_BASE_URL}?{gist_id}"

        return ShareResult(
            url=preview_url,
            raw_url=raw_url,
            delete_url=None,
            id=gist_id,
        )

name property

name: str

Name of the sharing service.

__init__

__init__(token: str | None = None) -> None

Initialize the ShittyCodingAgent sharer.

Parameters:

Name Type Description Default
token str | None

GitHub personal access token. If not provided, reads from GITHUB_TOKEN environment variable.

None
Source code in src/anyenv/text_sharing/shittycodingagent.py
def __init__(self, token: str | None = None) -> None:
    """Initialize the ShittyCodingAgent sharer.

    Args:
        token: GitHub personal access token. If not provided,
               reads from GITHUB_TOKEN environment variable.
    """
    self._token = token or os.environ.get("GITHUB_TOKEN") or os.environ.get("GH_TOKEN")
    if not self._token:
        msg = "GitHub token required. Set GITHUB_TOKEN/GH_TOKEN or pass token parameter."
        raise ValueError(msg)

share async

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

Share content via GitHub Gist with shittycodingagent.ai preview.

Parameters:

Name Type Description Default
content str

The text content to share

required
title str | None

Filename for the gist (defaults to "session.html")

None
syntax str | None

File extension hint (e.g. "html")

None
visibility Visibility

Always creates unlisted gist (visibility param ignored)

'unlisted'
expires_in int | None

Ignored (gists don't expire)

None

Returns:

Type Description
ShareResult

ShareResult with shittycodingagent.ai preview URL

Source code in src/anyenv/text_sharing/shittycodingagent.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 content via GitHub Gist with shittycodingagent.ai preview.

    Args:
        content: The text content to share
        title: Filename for the gist (defaults to "session.html")
        syntax: File extension hint (e.g. "html")
        visibility: Always creates unlisted gist (visibility param ignored)
        expires_in: Ignored (gists don't expire)

    Returns:
        ShareResult with shittycodingagent.ai preview URL
    """
    import anyenv

    # Default to session.html for the typical use case
    filename = title or f"session.{syntax or 'html'}"

    # Always create as unlisted (secret) gist
    payload: dict[str, Any] = {
        "files": {filename: {"content": content}},
        "public": False,
    }
    headers = {
        "Authorization": f"Bearer {self._token}",
        "Accept": "application/vnd.github+json",
        "X-GitHub-Api-Version": "2022-11-28",
    }
    url = "https://api.github.com/gists"
    response: dict[str, Any] = await anyenv.post_json(url, payload, headers=headers)

    gist_id = response["id"]
    raw_url = response["files"][filename]["raw_url"]

    # Build the shittycodingagent.ai preview URL
    preview_url = f"{PREVIEW_BASE_URL}?{gist_id}"

    return ShareResult(
        url=preview_url,
        raw_url=raw_url,
        delete_url=None,
        id=gist_id,
    )

TextSharer

Bases: ABC

Base class for text sharing services.

Source code in src/anyenv/text_sharing/base.py
class TextSharer(abc.ABC):
    """Base class for text sharing services."""

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

    @abc.abstractmethod
    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.

        Args:
            content: The text content to share
            title: Optional title/filename for the content
            syntax: Syntax highlighting hint (e.g. "python", "markdown")
            visibility: Visibility level (not all providers support all levels)
            expires_in: Expiration time in seconds (not supported by all providers)

        Returns:
            ShareResult with URL and metadata
        """

    def share_sync(
        self,
        content: str,
        *,
        title: str | None = None,
        syntax: str | None = None,
        visibility: Visibility = "unlisted",
        expires_in: int | None = None,
    ) -> ShareResult:
        """Synchronous version of share."""
        from anyenv import run_sync

        async def wrapper() -> ShareResult:
            return await self.share(
                content,
                title=title,
                syntax=syntax,
                visibility=visibility,
                expires_in=expires_in,
            )

        return run_sync(wrapper())

name abstractmethod property

name: str

Name of the sharing service.

share abstractmethod async

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

Share text content.

Parameters:

Name Type Description Default
content str

The text content to share

required
title str | None

Optional title/filename for the content

None
syntax str | None

Syntax highlighting hint (e.g. "python", "markdown")

None
visibility Visibility

Visibility level (not all providers support all levels)

'unlisted'
expires_in int | None

Expiration time in seconds (not supported by all providers)

None

Returns:

Type Description
ShareResult

ShareResult with URL and metadata

Source code in src/anyenv/text_sharing/base.py
@abc.abstractmethod
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.

    Args:
        content: The text content to share
        title: Optional title/filename for the content
        syntax: Syntax highlighting hint (e.g. "python", "markdown")
        visibility: Visibility level (not all providers support all levels)
        expires_in: Expiration time in seconds (not supported by all providers)

    Returns:
        ShareResult with URL and metadata
    """

share_sync

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

Synchronous version of share.

Source code in src/anyenv/text_sharing/base.py
def share_sync(
    self,
    content: str,
    *,
    title: str | None = None,
    syntax: str | None = None,
    visibility: Visibility = "unlisted",
    expires_in: int | None = None,
) -> ShareResult:
    """Synchronous version of share."""
    from anyenv import run_sync

    async def wrapper() -> ShareResult:
        return await self.share(
            content,
            title=title,
            syntax=syntax,
            visibility=visibility,
            expires_in=expires_in,
        )

    return run_sync(wrapper())

get_sharer

get_sharer(provider: Literal['gist'], *, token: str | None = None) -> GistSharer
get_sharer(provider: Literal['pastebin'], *, api_key: str | None = None) -> PastebinSharer
get_sharer(provider: Literal['paste_rs']) -> PasteRsSharer
get_sharer(provider: Literal['opencode'], *, api_url: str | None = None) -> OpenCodeSharer
get_sharer(
    provider: Literal["shittycodingagent"], *, token: str | None = None
) -> ShittyCodingAgentSharer
get_sharer(provider: TextSharerStr, **kwargs: str | None) -> TextSharer

Get a text sharer based on provider name.

Parameters:

Name Type Description Default
provider TextSharerStr

The text sharing provider to use

required
**kwargs str | None

Keyword arguments to pass to the provider constructor

{}

Returns:

Type Description
TextSharer

An instance of the specified text sharer

Example
# GitHub Gist (reads GITHUB_TOKEN/GH_TOKEN from env)
sharer = get_sharer("gist")

# GitHub Gist with explicit token
sharer = get_sharer("gist", token="ghp_...")

# Pastebin (reads PASTEBIN_API_KEY from env)
sharer = get_sharer("pastebin")

# Pastebin with explicit key
sharer = get_sharer("pastebin", api_key="...")

# paste.rs (no auth needed)
sharer = get_sharer("paste_rs")

# OpenCode (no auth needed)
sharer = get_sharer("opencode")

# OpenCode with custom API URL
sharer = get_sharer("opencode", api_url="https://api.dev.opencode.ai")
Source code in src/anyenv/text_sharing/__init__.py
def get_sharer(
    provider: TextSharerStr,
    **kwargs: str | None,
) -> TextSharer:
    """Get a text sharer based on provider name.

    Args:
        provider: The text sharing provider to use
        **kwargs: Keyword arguments to pass to the provider constructor

    Returns:
        An instance of the specified text sharer

    Example:
        ```python
        # GitHub Gist (reads GITHUB_TOKEN/GH_TOKEN from env)
        sharer = get_sharer("gist")

        # GitHub Gist with explicit token
        sharer = get_sharer("gist", token="ghp_...")

        # Pastebin (reads PASTEBIN_API_KEY from env)
        sharer = get_sharer("pastebin")

        # Pastebin with explicit key
        sharer = get_sharer("pastebin", api_key="...")

        # paste.rs (no auth needed)
        sharer = get_sharer("paste_rs")

        # OpenCode (no auth needed)
        sharer = get_sharer("opencode")

        # OpenCode with custom API URL
        sharer = get_sharer("opencode", api_url="https://api.dev.opencode.ai")
        ```
    """
    match provider:
        case "gist":
            return GistSharer(**kwargs)
        case "pastebin":
            return PastebinSharer(**kwargs)
        case "paste_rs":
            return PasteRsSharer()
        case "opencode":
            return OpenCodeSharer(api_url=kwargs.get("api_url"))
        case "shittycodingagent":
            return ShittyCodingAgentSharer(**kwargs)
        case _ as unreachable:
            assert_never(unreachable)