Metadata-Version: 2.5
Name: cobito
Version: 0.3.0
Summary: Turn a Slack thread into a conversation for your AI agent, and stream the agent's reply back into the thread
Project-URL: Repository, https://github.com/iwamot/cobito
Project-URL: Issues, https://github.com/iwamot/cobito/issues
Author: Takashi Iwamoto
License-Expression: MIT
License-File: LICENSE
Keywords: ai-agents,llm,slack,slack-bot,streaming
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Programming Language :: Python :: 3.15
Classifier: Topic :: Communications :: Chat
Classifier: Typing :: Typed
Requires-Python: >=3.12
Requires-Dist: aiohttp>=3.14.5
Requires-Dist: slack-as-markdown>=0.1.0
Requires-Dist: slack-sdk>=3.48.0
Description-Content-Type: text/markdown

# cobito

[![pypi](https://img.shields.io/pypi/v/cobito.svg)](https://pypi.org/project/cobito/)
[![python](https://img.shields.io/pypi/pyversions/cobito.svg)](https://pypi.org/project/cobito/)

Turn a Slack thread into a conversation for your AI agent, and stream the agent's reply back into the thread.

cobito is the Slack side of an agent bot, kept apart from how the bot calls its model or agent. It streams a reply of any length with Slack's chat streaming, shows tool calls as tasks in the reply, marks the post being worked on, reads the thread with names in place of mentions and the files people attach, and makes a conversation smaller when the agent cannot take it.

## Install

```sh
pip install cobito
```

cobito is asynchronous and works with slack-sdk's `AsyncWebClient`, as Bolt's `AsyncApp` hands it to listeners.

## Usage

### Streaming a reply

`RotatingChatStream` has the append/stop surface of slack-sdk's `AsyncChatStream`. When a message nears Slack's length limit, the reply moves on to a new message in the same thread at a paragraph break, so no table or code block is cut in two.

```python
from cobito import RotatingChatStream, ToolUse, tool_chunks

stream = RotatingChatStream(
    client,
    channel=channel_id,
    thread_ts=thread_ts,
    recipient_team_id=team_id,
    recipient_user_id=user_id,
    buffer_size=256,
)
await stream.append(chunks=tool_chunks(started=ToolUse(name="search", tool_use_id="t1")))
await stream.append(chunks=tool_chunks(completed=ToolUse(name="search", tool_use_id="t1")))
await stream.append(markdown_text="Here is what I found.")
await stream.stop()
```

The stream opens on its first append, so a reply that fails before it has anything to show leaves no empty message behind. On shutdown, `close_open_streams(markdown_text=...)` closes every reply still streaming, with a note saying why.

### Marking the post being worked on

```python
from cobito import WaitingReaction

waiting = WaitingReaction(client, channel_id=channel_id, message_ts=message_ts)
await waiting.add()
try:
    ...  # reply
finally:
    await waiting.clear()
```

Both calls are best-effort: without the `reactions:write` scope the post goes unmarked.

### Reading the thread as a conversation

`build_reply_text` reads a reply as the text the model is given: the Markdown it shows, the files it shows named under it as `[file: name]`, and everyone but the bot behind their name. Mentions of people and apps are written as `@name`, so a mention copied back into a reply never notifies anyone. `collect_user_ids` finds who a thread mentions, and `fetch_display_names` looks up what they are called.

```python
from cobito import build_reply_text, collect_user_ids, fetch_display_names

names = await fetch_display_names(
    client, collect_user_ids(replies, bot_user_id=bot_user_id)
)
texts = [
    build_reply_text(reply, bot_user_id=bot_user_id, display_names=names)
    for reply in replies
]
```

A `rewrite` function changes a reply's words before the speaker and names are put in, with mentions still in Slack's form (`<@U0123>`), for example to mask what the model should not see:

```python
import re

def mask_emails(text: str) -> str:
    return re.sub(r"\S+@\S+", "[EMAIL]", text)

text = build_reply_text(
    reply, bot_user_id=bot_user_id, display_names=names, rewrite=mask_emails
)
```

### Reading files from the thread

`select_files` picks the files people attached to the thread, newest first, within what Amazon Bedrock Converse takes in one request: 20 images, 5 documents, and 1 video, each under a size limit (`MAX_BYTES_BY_MODALITY`). Nothing is selected without the `files:read` scope. `fetch_files` downloads them, retrying what a retry can clear, and hands each one base64-encoded to a function that shapes it for your model.

```python
from cobito import fetch_files, parse_file_input_modalities, select_files

allowed = parse_file_input_modalities("image,document")  # e.g. from FILE_INPUT_MODALITIES

selections = select_files(
    replies,
    bot_user_id=bot_user_id,
    bot_scopes=authorize_result.bot_scopes,
    allowed_modalities=allowed,
)
files = await fetch_files(
    selections,
    bot_token=bot_token,
    build=lambda selection, data_base64: {
        "format": selection.format,
        "data": data_base64,
    },
)
```

`files` maps each Slack file ID to what `build` returned. A selection's `format` is a key of `CONVERSE_FORMATS`, and its `modality` is `image`, `document`, or `video`.

### Resending a conversation that is too long

When the agent fails before sending anything back, the conversation may have been more than its model takes. Send it once more as it was, then drop the oldest turns with `drop_older_turns`, a tenth on the first try and twice as many on each try after. The newest turn is always kept, and a turn keeps a question together with the bot's replies to it.

```python
from cobito import apply_history_cut, drop_older_turns, history_cut_metadata

EVENT_TYPE = "my_bot_history"

replies = apply_history_cut(replies, bot_user_id=bot_user_id, event_type=EVENT_TYPE)
sent = replies
resent_unchanged = False
dropping_tries = 0
while True:
    cut = history_cut_metadata(sent[0]["ts"], event_type=EVENT_TYPE)
    try:
        await reply_with(sent, metadata=cut if dropping_tries else None)
        break
    except AgentFailedBeforeReplying:
        if not resent_unchanged:
            resent_unchanged = True
            continue
        dropping_tries += 1
        shorter = drop_older_turns(
            replies, bot_user_id=bot_user_id, attempt=dropping_tries
        )
        if shorter is None:
            raise
        sent = shorter
```

`history_cut_metadata` goes on the reply as message metadata (`stop(metadata=...)`), and `apply_history_cut` reads it back from the thread, so the next turn starts from what fitted. Read the thread with `conversations.replies(include_all_metadata=True)` for the metadata to be there. The event type is yours to name; a cut recorded under another type is ignored.

## API

| Name | What it does |
|---|---|
| `RotatingChatStream` | A streamed reply that continues in a new message when one fills up |
| `close_open_streams(markdown_text=)` | Close every reply still streaming, for shutdown |
| `note_after_reply(text)` | Set a note off from the reply it is appended to |
| `ToolUse`, `tool_chunks(completed=, started=, error=)` | The chunks that show a tool call starting and finishing |
| `PLAN_TITLE` | The heading over the tool calls |
| `WaitingReaction`, `WAITING_REACTION` | The reaction on the post being worked on |
| `build_reply_text(reply, bot_user_id=, display_names=, rewrite=)` | Read a reply as the text the model is given |
| `collect_user_ids(replies, bot_user_id=, rewrite=)` | Find the people and apps a thread mentions |
| `fetch_display_names(client, user_ids)` | Look up what they are called |
| `pick_display_name(user)` | Pick a name from a `users.info` user |
| `is_bot_reply(reply, bot_user_id)` | Tell whether a reply is the bot's own |
| `select_files(replies, bot_user_id=, bot_scopes=, allowed_modalities=)` | Pick the files to download from a thread |
| `fetch_files(selections, bot_token=, build=)` | Download the picked files and shape each one |
| `parse_file_input_modalities(value)` | Read a comma-separated list of modalities |
| `FileToFetch`, `Modality`, `CONVERSE_FORMATS`, `MAX_SLOTS_BY_MODALITY`, `MAX_BYTES_BY_MODALITY` | The selection and its limits |
| `history_cut_metadata(oldest_ts, event_type=)` | The message metadata recording where a conversation was cut |
| `apply_history_cut(replies, bot_user_id=, event_type=)` | Keep the replies from the last recorded cut |
| `drop_older_turns(replies, bot_user_id=, attempt=)` | Drop the oldest turns for one try |

## License

MIT
