Skip to main content

cobito

pypi python

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, keeps it within one request, and makes a conversation smaller when the agent cannot take it.

Install

pip install cobito

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

Usage

Deciding whether to answer, and reading the conversation

is_addressed_to_bot tells whether a post is meant for the bot: it mentions the bot, it is in a DM with the bot, or it is in a thread whose parent post mentions the bot or was made by the bot, so that people can carry on a thread the bot started without mentioning it. get_replies reads the conversation the post belongs to: the whole thread (its newest 1000 replies, with message metadata), or the post alone when it is outside a thread. Replies go in the thread determine_thread_ts_to_reply gives. A ParentMentions remembers which threads' parent posts make them the bot's, so a busy thread is not looked up on every reply; make one per bot and keep it.

from cobito import (
    ParentMentions,
    determine_thread_ts_to_reply,
    get_replies,
    is_addressed_to_bot,
    is_post_from_bot,
)

parent_mentions = ParentMentions()  # once, at startup

if is_post_from_bot(payload):
    return
if not await is_addressed_to_bot(
    client,
    payload,
    channel_id=channel_id,
    bot_user_id=bot_user_id,
    parent_mentions=parent_mentions,
):
    return
thread_ts = determine_thread_ts_to_reply(payload)
replies = await get_replies(client, payload, channel_id=channel_id, user_id=user_id)

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.

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() closes every reply still streaming, with a note saying why (SHUTDOWN_TEXT unless you pass another).

Rendering the reply's events

A reply usually arrives as events: text as the model writes it, and each tool call as it starts and ends. ReplyRenderer streams them into the RotatingChatStream: text as Markdown, and each tool call as a task, in progress while it runs and complete or failed once it ends. Text closes whatever tool was still showing, and a later event of the same call can name a task that started unnamed.

from cobito import ReplyRenderer, TextDelta, ToolResult, ToolUse

renderer = ReplyRenderer(stream)
async for event in my_events():  # TextDelta, ToolUse, and ToolResult
    await renderer.handle(event)
await renderer.finish()

Events of kinds your app adds — an error the agent streams, a file it made — are yours to handle before passing the rest on.

Marking the post being worked on

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 DisplayNames.fetch looks up what they are called through users.info. A DisplayNames remembers the names it found and the IDs that have none, but not lookups that failed for a passing reason, and stops looking up without the users:read scope; make one per bot and keep it.

from cobito import DisplayNames, build_reply_text, collect_user_ids

display_names = DisplayNames()  # once, at startup

names = await display_names.fetch(
    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:

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.

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.

To download a file once instead of on every reply, pass cache= an S3FileCache, which keeps a copy of each file in an Amazon S3 bucket. It reads and writes through an S3 client you make, such as boto3's. Make one for each reply, and call settle() when the reply is done: a copy is kept without holding up the reply, and a process that stops after the reply, as AWS Lambda freezes one, would cut it short.

import boto3
from cobito import S3FileCache

s3 = boto3.client("s3")

file_cache = S3FileCache(s3, bucket="my-bucket", team_id=team_id)
try:
    files = await fetch_files(selections, bot_token=bot_token, build=build, cache=file_cache)
    ...  # send the conversation and stream the reply
finally:
    await file_cache.settle()

A copy is kept under slack-files/<team ID>/<file ID>/<file name> (FILE_KEY_PREFIX), with the file's media type as its Content-Type, and only after the file passed the checks a download goes through. Files whose content can change under the same ID, such as snippets, have editable set and always come from Slack. A copy that cannot be read or kept is logged and costs only a download; it never fails a reply.

The client needs s3:GetObject and s3:PutObject on slack-files/*, and s3:ListBucket on the bucket for that prefix: without it, S3 answers a file not kept yet with AccessDenied rather than NoSuchKey, and each is logged as a failure. Nothing deletes the copies, so give the bucket a lifecycle rule that expires slack-files/.

To keep copies somewhere else, pass any object with the two methods of FileCache.

Keeping a thread within one request

compact_to_payload_budget cuts a thread down to what one request holds before anything is downloaded, working from Slack's size metadata. It drops from the oldest end: an older message's attachments, last attached first, then the message itself, then on to the next. The bot's replies that would then open the thread go too. The newest reply is always kept. file_overhead_bytes is what the JSON around one file adds in your request shape, at most.

from cobito import compact_to_payload_budget

replies, selections = compact_to_payload_budget(
    replies,
    selections,
    bot_user_id=bot_user_id,
    display_names=names,
    file_overhead_bytes=320,
)

The ceiling is MAX_PAYLOAD_BYTES (30,000,000), a little under what Amazon Bedrock Converse takes in one request; pass max_payload_bytes to change it, and rewrite if you pass one to build_reply_text. reply_payload_bytes and file_payload_bytes give the estimates it adds up.

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_with_resend sends it once more as it was, then drops the oldest replies, as many in all as the Fibonacci numbers say: 1, then 2, 3, 5, 8, and so on. A conversation grows a reply or two at a time, so one that overflows has usually only just gone past what fitted before, and a reply or two puts it back, while a failure no shorter conversation avoids gives up after a few tries. The newest reply is always kept. What is sent opens on a person's reply: the bot's replies that a try would open on go with it. A failure after anything arrived is not resent, since the reply has started.

You hand over how to send the conversation once. It gets the replies to send, the message metadata for the reply (set when the conversation was cut), and an Arrival to pass the reply's events through:

from cobito import apply_history_cut, report_reply_failure, send_with_resend

EVENT_TYPE = "my_bot_history"

replies = apply_history_cut(replies, bot_user_id=bot_user_id, event_type=EVENT_TYPE)


async def send(sent, metadata, arrival):
    # call_my_agent and stream_reply are yours: one calls the model or agent,
    # the other renders its events into the RotatingChatStream.
    events = arrival.watch(call_my_agent(sent))
    await stream_reply(stream, events, metadata=metadata)


try:
    await send_with_resend(
        replies,
        send,
        bot_user_id=bot_user_id,
        event_type=EVENT_TYPE,
        resendable=lambda error: not isinstance(error, TimeoutError),
    )
except Exception:
    logger.exception("Failed to reply")
    await report_reply_failure(
        client, channel_id=channel_id, thread_ts=thread_ts, streamer=stream
    )

The metadata is history_cut_metadata; put it on the reply's last message (stop(metadata=...)), and apply_history_cut reads it back from the thread, so the next turn starts from what fitted. get_replies reads the thread with the metadata. The event type is yours to name; a cut recorded under another type is ignored. resendable leaves out failures no shorter conversation can avoid, and counts leaves out events that should not count as the reply having started, such as an error the agent streams as an event. report_reply_failure finishes a reply that has opened a message with a note, or posts the note as a new reply. The note is REPLY_FAILURE_TEXT unless you pass another; pass TIMEOUT_TEXT for a reply that went quiet. close_open_streams closes the replies still streaming on shutdown with SHUTDOWN_TEXT. The three notes are fixed, so the frame around the conversation reads the same on every app built on cobito.

Answering a request from outside Slack

A request can reach the bot without anyone mentioning it, as a message on a queue: a JSON object with channel and prompt, and optionally slack_message and thread_ts. parse_queued_request reads it as a QueuedRequest, and raises NotARequestError (a ValueError) for a body that is not one, which no later try reads differently. post_opening posts the answer's opening — slack_message as Markdown, or the prompt when there is none — at the top of the channel, or into the thread the request names, and returns the thread to stream the reply into. Stream it there as you would a reply to a mention. add_request puts the prompt after the thread's replies, as a message from nobody in particular: whoever sends it is no Slack user anything can verify, so a request names none.

from cobito import add_request, get_replies, parse_queued_request, post_opening

request = parse_queued_request(body)
thread_ts = await post_opening(client, request)
replies = await get_replies(
    client, {"thread_ts": thread_ts}, channel_id=request.channel, user_id=bot_user_id
)
replies = add_request(replies, request, bot_user_id=bot_user_id)

The opening post stays in the thread, and since the bot made it, people carry the thread on without mentioning the bot. Its words came from outside Slack, so is_bot_reply does not take it for the bot's own: give it to the model as a user message. post_opening marks it in its message metadata, which get_replies reads; a thread's parent that the bot posted counts as one without the mark. With a slack_message, the prompt is not posted, so later turns read the slack_message alone. Slack takes about 12,000 characters in one post, so a longer prompt needs one.

poll_queue takes the requests off an Amazon SQS FIFO queue and answers each with answer, until cancelled. You make the SQS client, such as boto3's, so the AWS SDK, the credentials and the region are yours; cobito does not depend on them. answer gets the request and the thread, streams the reply there, and reports its own failures in the thread:

import asyncio

import boto3
from cobito import poll_queue


async def answer(request, thread_ts):
    ...  # stream the reply into thread_ts, the request added with add_request


sqs = boto3.client("sqs")
asyncio.create_task(poll_queue(sqs, queue_url, client, answer))

A receive waits up to 20 seconds, so a request is taken up as soon as it arrives. A message stays hidden while it is answered, renewed for as long as that takes, so the requests in one FIFO message group are answered in the order they were sent. It comes off the queue once the opening is posted and the answer has run, whether or not the answer succeeded, so nothing is answered twice; a message whose opening could not be posted is left for the queue to deliver again, and one that is not a request is dropped. Give the queue a dead-letter queue (maxReceiveCount) for messages that keep failing. Where the messages arrive some other way, such as an AWS Lambda SQS trigger, answer_queued_message does the same for one message and tells whether it is done with.

API

Name What it does
is_retried_request(headers) Tell whether a request is Slack redelivering an event it sent before
is_post_from_bot(payload) Tell whether a post was made by a bot or an app
is_addressed_to_bot(client, payload, channel_id=, bot_user_id=, parent_mentions=) Tell whether a post is meant for the bot
ParentMentions Remember which threads' parent posts make them the bot's
determine_thread_ts_to_reply(payload) Say which thread to reply in
get_replies(client, payload, channel_id=, user_id=) Read the conversation a post belongs to
build_reply_from_post(payload, user_id) Take a post outside a thread as the reply that opens a conversation
RotatingChatStream A streamed reply that continues in a new message when one fills up
close_open_streams(markdown_text=SHUTDOWN_TEXT) Close every reply still streaming, for shutdown
note_after_reply(text) Set a note off from the reply it is appended to
ReplyRenderer, ReplyRenderer.handle(event), ReplyRenderer.finish(metadata=) Stream a reply's text and tool events into a RotatingChatStream
ReplyEvent, TextDelta, ToolResult The events it takes, with ToolUse
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
DisplayNames, DisplayNames.fetch(client, user_ids) Look up what they are called, remembering what was found
pick_display_name(user) Pick a name from a users.info user
is_bot_reply(reply, bot_user_id) Tell whether a reply is what the bot itself said, which an opening post is not
select_files(replies, bot_user_id=, bot_scopes=, allowed_modalities=) Pick the files to download from a thread
fetch_files(selections, bot_token=, build=, cache=None) Download the picked files and shape each one
FileCache Copies of files that fetch_files looks in before downloading
S3FileCache(s3, bucket=, team_id=), S3Client, FILE_KEY_PREFIX Copies kept in an S3 bucket
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
compact_to_payload_budget(replies, selections, bot_user_id=, display_names=, file_overhead_bytes=, rewrite=, max_payload_bytes=) Cut a thread down to one request
reply_payload_bytes(reply, bot_user_id=, display_names=, rewrite=), file_payload_bytes(size, overhead_bytes=), MAX_PAYLOAD_BYTES The estimates it adds up, and its default ceiling
REPLY_FAILURE_TEXT, TIMEOUT_TEXT, SHUTDOWN_TEXT The fixed notes for a reply that does not finish
send_with_resend(replies, send, bot_user_id=, event_type=, resendable=, counts=, log_suffix=) Send a conversation, and again smaller each time it fails before replying
Arrival Notes whether a reply's events have started arriving
report_reply_failure(client, channel_id=, thread_ts=, streamer=, text=REPLY_FAILURE_TEXT) Report a failed reply in its thread
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_replies(replies, bot_user_id=, attempt=) Drop the oldest replies for one try
parse_queued_request(body), QueuedRequest, NotARequestError Read a queued message's body as a request
post_opening(client, request), opening_text(request) Post the opening of the answer to a request, and say what it reads
add_request(replies, request, bot_user_id=) Put a request after the thread its opening was posted in
poll_queue(sqs, queue_url, client, answer, max_in_flight=), QueueClient Answer the requests that arrive on an SQS queue, until cancelled
answer_queued_message(client, body, answer) Answer one queued message, and tell whether it is done with

License

MIT

Metadata

Release files for cobito 0.16.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for cobito 0.16.0
File Size Uploaded Provenance Actions
cobito-0.16.0.tar.gz 64.6 kB With provenance Details for cobito-0.16.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for cobito 0.16.0
File Interpreter ABI Platform Actions
cobito-0.16.0-py3-none-any.whl Python 3 none any Details for cobito-0.16.0-py3-none-any.whl

Total release size: 120.0 kB

Release files / cobito-0.16.0.tar.gz

Download URL cobito-0.16.0.tar.gz
Size 64.6 kB
Tags Source
SHA-256 checksum
How to use checksums
b11896a1c1b0baf64b51161be56a50dc1764f7b1ddb7595ae00a57525b8eed46
BLAKE2b-256 checksum
How to use checksums
dd49cd3476d59b958bcec85375a04e6e3398fbee2bfde79bbef9992bd26fdf94
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.13.12 {"installer":{"name":"uv","version":"0.13.12","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Dec 4, 2026.

Transparency log

Release files / cobito-0.16.0-py3-none-any.whl

Download URL cobito-0.16.0-py3-none-any.whl
Size 55.4 kB
Tags Python 3
SHA-256 checksum
How to use checksums
a3b45d62d328dc0724355054e611ca0293e6d73116285606ba0e3a115187ea4b
BLAKE2b-256 checksum
How to use checksums
03fbc9d1629999782439001bca97247ba8a344763acec35c3d84838c8cf25d71
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.13.12 {"installer":{"name":"uv","version":"0.13.12","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Dec 4, 2026.

Transparency log

Security for cobito 0.16.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for cobito-0.16.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Dec 4, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page