cobito 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- cobito/__init__.py +29 -0
- cobito/_reaction.py +81 -0
- cobito/_resend.py +149 -0
- cobito/_stream.py +319 -0
- cobito/_stream_logic.py +182 -0
- cobito/_tools.py +93 -0
- cobito/_version.py +24 -0
- cobito/py.typed +0 -0
- cobito-0.1.0.dist-info/METADATA +131 -0
- cobito-0.1.0.dist-info/RECORD +12 -0
- cobito-0.1.0.dist-info/WHEEL +4 -0
- cobito-0.1.0.dist-info/licenses/LICENSE +21 -0
cobito/__init__.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
"""Turn a Slack thread into a conversation for an AI agent, and stream the reply back."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from cobito._reaction import WAITING_REACTION, WaitingReaction
|
|
6
|
+
from cobito._resend import apply_history_cut, drop_older_turns, history_cut_metadata
|
|
7
|
+
from cobito._stream import RotatingChatStream, close_open_streams
|
|
8
|
+
from cobito._stream_logic import note_after_reply
|
|
9
|
+
from cobito._tools import PLAN_TITLE, ToolUse, tool_chunks
|
|
10
|
+
|
|
11
|
+
try:
|
|
12
|
+
from cobito._version import __version__
|
|
13
|
+
except ImportError:
|
|
14
|
+
__version__ = "0.0.0+unknown"
|
|
15
|
+
|
|
16
|
+
__all__ = [
|
|
17
|
+
"PLAN_TITLE",
|
|
18
|
+
"WAITING_REACTION",
|
|
19
|
+
"RotatingChatStream",
|
|
20
|
+
"ToolUse",
|
|
21
|
+
"WaitingReaction",
|
|
22
|
+
"__version__",
|
|
23
|
+
"apply_history_cut",
|
|
24
|
+
"close_open_streams",
|
|
25
|
+
"drop_older_turns",
|
|
26
|
+
"history_cut_metadata",
|
|
27
|
+
"note_after_reply",
|
|
28
|
+
"tool_chunks",
|
|
29
|
+
]
|
cobito/_reaction.py
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
"""Marks a Slack post with a waiting reaction while the app works on it.
|
|
2
|
+
|
|
3
|
+
The marker sits on the post being worked on for as long as the app is on
|
|
4
|
+
it; it comes off when the run ends, whether that is a finished reply or a
|
|
5
|
+
reported failure. Both sides are best-effort — an install that predates
|
|
6
|
+
the reactions:write scope simply goes without the marker.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import logging
|
|
12
|
+
|
|
13
|
+
from slack_sdk.errors import SlackApiError
|
|
14
|
+
from slack_sdk.web.async_client import AsyncWebClient
|
|
15
|
+
|
|
16
|
+
logger = logging.getLogger(__name__)
|
|
17
|
+
|
|
18
|
+
# The waiting marker — deliberately not configurable, so the frame around
|
|
19
|
+
# the conversation reads the same on every deployment.
|
|
20
|
+
WAITING_REACTION = "eyes"
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class WaitingReaction:
|
|
24
|
+
"""The waiting marker on one Slack post, added once and cleared once."""
|
|
25
|
+
|
|
26
|
+
def __init__(
|
|
27
|
+
self,
|
|
28
|
+
client: AsyncWebClient,
|
|
29
|
+
*,
|
|
30
|
+
channel_id: str,
|
|
31
|
+
message_ts: str,
|
|
32
|
+
) -> None:
|
|
33
|
+
"""
|
|
34
|
+
Bind the marker to the post it will sit on.
|
|
35
|
+
|
|
36
|
+
Args:
|
|
37
|
+
client (AsyncWebClient): The Slack Web API client.
|
|
38
|
+
channel_id (str): The ID of the channel holding the post.
|
|
39
|
+
message_ts (str): The timestamp of the post to mark.
|
|
40
|
+
"""
|
|
41
|
+
self._client = client
|
|
42
|
+
self._channel_id = channel_id
|
|
43
|
+
self._message_ts = message_ts
|
|
44
|
+
self._active = False
|
|
45
|
+
|
|
46
|
+
async def add(self) -> None:
|
|
47
|
+
"""
|
|
48
|
+
Put the marker on the post; a failure just leaves it off.
|
|
49
|
+
|
|
50
|
+
Returns:
|
|
51
|
+
None
|
|
52
|
+
"""
|
|
53
|
+
try:
|
|
54
|
+
await self._client.reactions_add(
|
|
55
|
+
channel=self._channel_id,
|
|
56
|
+
timestamp=self._message_ts,
|
|
57
|
+
name=WAITING_REACTION,
|
|
58
|
+
)
|
|
59
|
+
except SlackApiError:
|
|
60
|
+
logger.debug("Could not add the waiting reaction", exc_info=True)
|
|
61
|
+
return
|
|
62
|
+
self._active = True
|
|
63
|
+
|
|
64
|
+
async def clear(self) -> None:
|
|
65
|
+
"""
|
|
66
|
+
Take the marker off the post. Idempotent — later calls no-op.
|
|
67
|
+
|
|
68
|
+
Returns:
|
|
69
|
+
None
|
|
70
|
+
"""
|
|
71
|
+
if not self._active:
|
|
72
|
+
return
|
|
73
|
+
self._active = False
|
|
74
|
+
try:
|
|
75
|
+
await self._client.reactions_remove(
|
|
76
|
+
channel=self._channel_id,
|
|
77
|
+
timestamp=self._message_ts,
|
|
78
|
+
name=WAITING_REACTION,
|
|
79
|
+
)
|
|
80
|
+
except SlackApiError:
|
|
81
|
+
logger.debug("Could not remove the waiting reaction", exc_info=True)
|
cobito/_resend.py
ADDED
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
"""Pure logic for resending a conversation the agent could not take.
|
|
2
|
+
|
|
3
|
+
An agent that fails before it sends anything back may have been handed more
|
|
4
|
+
than its model takes, and the app that built the conversation is the one to
|
|
5
|
+
make it smaller. It sends the same conversation once more first, so that a
|
|
6
|
+
passing failure costs nothing, and then drops the oldest turns: about a
|
|
7
|
+
tenth of them, then twice as many on each try, so a conversation that only
|
|
8
|
+
just overflows keeps nearly all of it and one far too long still fits in a
|
|
9
|
+
few tries. What fitted is recorded on the reply, in its message metadata,
|
|
10
|
+
and the next turn starts from there instead of overflowing again. Nothing of
|
|
11
|
+
this is shown in the thread.
|
|
12
|
+
|
|
13
|
+
The metadata's event type is the app's to name, so that each app reads only
|
|
14
|
+
the cuts it recorded itself.
|
|
15
|
+
|
|
16
|
+
A turn opens with a reply from someone other than the bot and holds the
|
|
17
|
+
bot's replies to it, so a question is never kept without its answer or the
|
|
18
|
+
other way round. Replies before the first such reply count as a turn of
|
|
19
|
+
their own.
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
from __future__ import annotations
|
|
23
|
+
|
|
24
|
+
import math
|
|
25
|
+
|
|
26
|
+
# The share of the older turns the first dropping try drops; each later try
|
|
27
|
+
# drops twice as many.
|
|
28
|
+
FIRST_DROP_SHARE = 0.1
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def history_cut_metadata(oldest_ts: str, *, event_type: str) -> dict:
|
|
32
|
+
"""
|
|
33
|
+
Build the message metadata recording where a conversation was cut.
|
|
34
|
+
|
|
35
|
+
Args:
|
|
36
|
+
oldest_ts (str): The timestamp of the oldest reply that was kept.
|
|
37
|
+
event_type (str): The app's metadata event type for cuts.
|
|
38
|
+
|
|
39
|
+
Returns:
|
|
40
|
+
dict: The metadata for chat.stopStream.
|
|
41
|
+
"""
|
|
42
|
+
return {"event_type": event_type, "event_payload": {"oldest_ts": oldest_ts}}
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def apply_history_cut(
|
|
46
|
+
replies: list[dict], *, bot_user_id: str | None, event_type: str
|
|
47
|
+
) -> list[dict]:
|
|
48
|
+
"""
|
|
49
|
+
Keep the replies from where the bot last cut this conversation.
|
|
50
|
+
|
|
51
|
+
The newest of the bot's replies that records a cut decides: everything
|
|
52
|
+
older than the reply it names is left out. A conversation never cut is
|
|
53
|
+
returned whole.
|
|
54
|
+
|
|
55
|
+
Args:
|
|
56
|
+
replies (list[dict]): Slack replies in chronological order, read with
|
|
57
|
+
their metadata.
|
|
58
|
+
bot_user_id (str | None): The bot's own user ID.
|
|
59
|
+
event_type (str): The app's metadata event type for cuts.
|
|
60
|
+
|
|
61
|
+
Returns:
|
|
62
|
+
list[dict]: The replies from the recorded cut onwards.
|
|
63
|
+
"""
|
|
64
|
+
oldest = _latest_cut(replies, bot_user_id, event_type)
|
|
65
|
+
if oldest is None:
|
|
66
|
+
return replies
|
|
67
|
+
return [
|
|
68
|
+
reply
|
|
69
|
+
for reply in replies
|
|
70
|
+
if isinstance(reply.get("ts"), str) and _ts_key(reply["ts"]) >= oldest
|
|
71
|
+
]
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _latest_cut(
|
|
75
|
+
replies: list[dict], bot_user_id: str | None, event_type: str
|
|
76
|
+
) -> tuple[int, int] | None:
|
|
77
|
+
"""Find the cut the newest of the bot's replies records, if any does."""
|
|
78
|
+
for reply in reversed(replies):
|
|
79
|
+
if bot_user_id is None or reply.get("user") != bot_user_id:
|
|
80
|
+
continue
|
|
81
|
+
metadata = reply.get("metadata")
|
|
82
|
+
if not isinstance(metadata, dict):
|
|
83
|
+
continue
|
|
84
|
+
if metadata.get("event_type") != event_type:
|
|
85
|
+
continue
|
|
86
|
+
payload = metadata.get("event_payload")
|
|
87
|
+
oldest = payload.get("oldest_ts") if isinstance(payload, dict) else None
|
|
88
|
+
if isinstance(oldest, str) and _is_ts(oldest):
|
|
89
|
+
return _ts_key(oldest)
|
|
90
|
+
return None
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def _is_ts(value: str) -> bool:
|
|
94
|
+
"""Tell whether a string has the shape of a Slack timestamp."""
|
|
95
|
+
seconds, dot, fraction = value.partition(".")
|
|
96
|
+
return seconds.isdigit() and (not dot or fraction.isdigit())
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def _ts_key(ts: str) -> tuple[int, int]:
|
|
100
|
+
"""Order Slack timestamps as numbers rather than as text."""
|
|
101
|
+
seconds, _, fraction = ts.partition(".")
|
|
102
|
+
return int(seconds), int(fraction.ljust(6, "0")[:6]) if fraction else 0
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def drop_older_turns(
|
|
106
|
+
replies: list[dict], *, bot_user_id: str | None, attempt: int
|
|
107
|
+
) -> list[dict] | None:
|
|
108
|
+
"""
|
|
109
|
+
Drop the oldest turns of a conversation for one dropping try.
|
|
110
|
+
|
|
111
|
+
The newest turn is always kept. Of the turns before it, the first try
|
|
112
|
+
drops a tenth (at least one), and each later try twice as many as the
|
|
113
|
+
one before, counted against the whole conversation rather than what the
|
|
114
|
+
previous try kept.
|
|
115
|
+
|
|
116
|
+
Args:
|
|
117
|
+
replies (list[dict]): Slack replies in chronological order.
|
|
118
|
+
bot_user_id (str | None): The bot's own user ID.
|
|
119
|
+
attempt (int): Which dropping try this is, from 1.
|
|
120
|
+
|
|
121
|
+
Returns:
|
|
122
|
+
list[dict] | None: The newer replies, or None when the previous try
|
|
123
|
+
already left only the newest turn, so there is nothing more to
|
|
124
|
+
drop.
|
|
125
|
+
"""
|
|
126
|
+
turns = _turns(replies, bot_user_id)
|
|
127
|
+
older = len(turns) - 1
|
|
128
|
+
previous = 0 if attempt == 1 else _dropped(older, attempt - 1)
|
|
129
|
+
if previous >= older:
|
|
130
|
+
return None
|
|
131
|
+
kept = turns[_dropped(older, attempt) :]
|
|
132
|
+
return [reply for turn in kept for reply in turn]
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def _dropped(older: int, attempt: int) -> int:
|
|
136
|
+
"""How many of the older turns a dropping try drops."""
|
|
137
|
+
share = FIRST_DROP_SHARE * 2 ** (attempt - 1)
|
|
138
|
+
return min(older, max(1, math.ceil(older * share)))
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def _turns(replies: list[dict], bot_user_id: str | None) -> list[list[dict]]:
|
|
142
|
+
"""Group replies into turns, each opening with a reply not from the bot."""
|
|
143
|
+
turns: list[list[dict]] = []
|
|
144
|
+
for reply in replies:
|
|
145
|
+
from_bot = bot_user_id is not None and reply.get("user") == bot_user_id
|
|
146
|
+
if not from_bot or not turns:
|
|
147
|
+
turns.append([])
|
|
148
|
+
turns[-1].append(reply)
|
|
149
|
+
return turns
|
cobito/_stream.py
ADDED
|
@@ -0,0 +1,319 @@
|
|
|
1
|
+
"""Slack chat streaming with rollover past the message length limit.
|
|
2
|
+
|
|
3
|
+
Slack caps one streamed message at an undocumented total length (about
|
|
4
|
+
12,000 characters, measured 2026-11-27): once the accumulated text would
|
|
5
|
+
cross it, chat.appendStream and chat.stopStream fail with `msg_too_long`.
|
|
6
|
+
Long replies are normal, so a reply moves on to a fresh streamed
|
|
7
|
+
message in the same thread, and the reader sees it continue there.
|
|
8
|
+
|
|
9
|
+
Where it moves on is chosen where it can be: past SOFT_MESSAGE_LENGTH the
|
|
10
|
+
message ends at the next paragraph break outside a code block, so no code
|
|
11
|
+
block or table is cut in two. A paragraph that reaches Slack's limit first
|
|
12
|
+
is cut where Slack refuses it: the full message is finalized as it stands,
|
|
13
|
+
the text the SDK helper had not yet delivered is replayed into the fresh
|
|
14
|
+
one, and a code block the cut fell inside is opened again there.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import logging
|
|
20
|
+
|
|
21
|
+
from slack_sdk.errors import SlackApiError
|
|
22
|
+
from slack_sdk.models.messages.chunk import MarkdownTextChunk
|
|
23
|
+
from slack_sdk.web.async_chat_stream import AsyncChatStream
|
|
24
|
+
from slack_sdk.web.async_client import AsyncWebClient
|
|
25
|
+
|
|
26
|
+
from cobito._stream_logic import (
|
|
27
|
+
SOFT_MESSAGE_LENGTH,
|
|
28
|
+
PendingAppends,
|
|
29
|
+
is_message_too_long,
|
|
30
|
+
note_after_reply,
|
|
31
|
+
open_fence,
|
|
32
|
+
split_point,
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
logger = logging.getLogger(__name__)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class RotatingChatStream:
|
|
39
|
+
"""A streaming reply that rolls over to a new message when one fills up.
|
|
40
|
+
|
|
41
|
+
Wraps the SDK's `AsyncChatStream` with the same append/stop surface. On
|
|
42
|
+
`msg_too_long` the current message is finalized as-is (a normal stop, no
|
|
43
|
+
error shown), a new stream opens in the same thread, and the undelivered
|
|
44
|
+
tail continues there.
|
|
45
|
+
|
|
46
|
+
The stream opens lazily, on the first append: a run that delivers
|
|
47
|
+
nothing to render (a failure before the first token) leaves no message
|
|
48
|
+
behind. The waiting reaction, not an empty stream, is what shows the run
|
|
49
|
+
is being worked on.
|
|
50
|
+
"""
|
|
51
|
+
|
|
52
|
+
def __init__(
|
|
53
|
+
self,
|
|
54
|
+
client: AsyncWebClient,
|
|
55
|
+
*,
|
|
56
|
+
channel: str,
|
|
57
|
+
thread_ts: str,
|
|
58
|
+
recipient_team_id: str | None,
|
|
59
|
+
recipient_user_id: str | None,
|
|
60
|
+
buffer_size: int,
|
|
61
|
+
):
|
|
62
|
+
self._client = client
|
|
63
|
+
self._channel = channel
|
|
64
|
+
self._thread_ts = thread_ts
|
|
65
|
+
self._recipient_team_id = recipient_team_id
|
|
66
|
+
self._recipient_user_id = recipient_user_id
|
|
67
|
+
self._buffer_size = buffer_size
|
|
68
|
+
self._streamer: AsyncChatStream | None = None
|
|
69
|
+
self._pending = PendingAppends()
|
|
70
|
+
# The markdown handed to the current message, delivered or not.
|
|
71
|
+
self._text = ""
|
|
72
|
+
self._abandoned = False
|
|
73
|
+
|
|
74
|
+
@property
|
|
75
|
+
def ts(self) -> str | None:
|
|
76
|
+
"""The current streamed message's timestamp, if one has started."""
|
|
77
|
+
return self._streamer.ts if self._streamer is not None else None
|
|
78
|
+
|
|
79
|
+
async def append(
|
|
80
|
+
self,
|
|
81
|
+
*,
|
|
82
|
+
markdown_text: str | None = None,
|
|
83
|
+
chunks: list[dict] | None = None,
|
|
84
|
+
) -> None:
|
|
85
|
+
"""
|
|
86
|
+
Append to the reply, rolling over to a new message if it is full.
|
|
87
|
+
|
|
88
|
+
Args:
|
|
89
|
+
markdown_text (str | None): Markdown to append to the reply.
|
|
90
|
+
chunks (list[dict] | None): Streaming chunks (e.g. task updates).
|
|
91
|
+
|
|
92
|
+
Returns:
|
|
93
|
+
None
|
|
94
|
+
"""
|
|
95
|
+
if self._abandoned:
|
|
96
|
+
return
|
|
97
|
+
if self._streamer is None:
|
|
98
|
+
self._streamer = await self._new_streamer()
|
|
99
|
+
_open_streams.add(self)
|
|
100
|
+
if markdown_text and not chunks:
|
|
101
|
+
split = split_point(self._text, markdown_text, SOFT_MESSAGE_LENGTH)
|
|
102
|
+
if split is not None:
|
|
103
|
+
at, fence = split
|
|
104
|
+
# The part up to the break is appended as it is: checked
|
|
105
|
+
# again, it would end at the same break.
|
|
106
|
+
if at > 0:
|
|
107
|
+
await self._append_or_rotate(markdown_text=markdown_text[:at])
|
|
108
|
+
await self._move_on(fence=fence)
|
|
109
|
+
if at < len(markdown_text):
|
|
110
|
+
await self.append(markdown_text=markdown_text[at:])
|
|
111
|
+
return
|
|
112
|
+
await self._append_or_rotate(markdown_text=markdown_text, chunks=chunks)
|
|
113
|
+
|
|
114
|
+
async def stop(
|
|
115
|
+
self,
|
|
116
|
+
*,
|
|
117
|
+
markdown_text: str | None = None,
|
|
118
|
+
chunks: list[dict] | None = None,
|
|
119
|
+
metadata: dict | None = None,
|
|
120
|
+
) -> None:
|
|
121
|
+
"""
|
|
122
|
+
Finalize the reply, rolling over first if the close would overflow.
|
|
123
|
+
|
|
124
|
+
A reply that never opened and closes with no new content is a no-op:
|
|
125
|
+
the SDK helper's stop would start a stream just to close it, leaving
|
|
126
|
+
an empty message in the thread. Metadata goes on the message the
|
|
127
|
+
reply ends in, the last one where it rolled over.
|
|
128
|
+
|
|
129
|
+
Args:
|
|
130
|
+
markdown_text (str | None): Markdown to append before closing.
|
|
131
|
+
chunks (list[dict] | None): Streaming chunks to close with.
|
|
132
|
+
metadata (dict | None): Message metadata for the final message.
|
|
133
|
+
|
|
134
|
+
Returns:
|
|
135
|
+
None
|
|
136
|
+
"""
|
|
137
|
+
if self._abandoned or (
|
|
138
|
+
self._streamer is None and markdown_text is None and not chunks
|
|
139
|
+
):
|
|
140
|
+
return
|
|
141
|
+
# Left here rather than after the close so a shutdown sweep does not
|
|
142
|
+
# close a stream its own caller is already closing.
|
|
143
|
+
_open_streams.discard(self)
|
|
144
|
+
self._pending.record(markdown_text=markdown_text, chunks=chunks)
|
|
145
|
+
if self._streamer is None:
|
|
146
|
+
self._streamer = await self._new_streamer()
|
|
147
|
+
try:
|
|
148
|
+
await self._streamer.stop(
|
|
149
|
+
markdown_text=markdown_text, chunks=chunks, metadata=metadata
|
|
150
|
+
)
|
|
151
|
+
except SlackApiError as error:
|
|
152
|
+
if not is_message_too_long(error):
|
|
153
|
+
raise
|
|
154
|
+
await self._rotate()
|
|
155
|
+
await self._require_streamer().stop(metadata=metadata)
|
|
156
|
+
else:
|
|
157
|
+
self._pending.clear()
|
|
158
|
+
|
|
159
|
+
async def close_unfinished(self, *, markdown_text: str) -> None:
|
|
160
|
+
"""
|
|
161
|
+
Close the open message where it stands, saying why.
|
|
162
|
+
|
|
163
|
+
For a reply being abandoned rather than finished — a shutdown —
|
|
164
|
+
while the coroutine writing it may still be inside an append. The
|
|
165
|
+
SDK helper clears its buffer only after its own call returns, so a
|
|
166
|
+
`stop` racing that call would read the same buffer and deliver it
|
|
167
|
+
a second time. This goes to the API directly instead: the note is
|
|
168
|
+
the only thing sent, and whatever the helper still holds is
|
|
169
|
+
dropped with the reply it belonged to.
|
|
170
|
+
|
|
171
|
+
The stream is left abandoned: a later append or stop on it does
|
|
172
|
+
nothing, so the coroutine that was writing the reply cannot open a
|
|
173
|
+
second message to report the failure it is about to see.
|
|
174
|
+
|
|
175
|
+
Args:
|
|
176
|
+
markdown_text (str): Markdown to close the message with.
|
|
177
|
+
|
|
178
|
+
Returns:
|
|
179
|
+
None
|
|
180
|
+
"""
|
|
181
|
+
# Set before the call: past here the reply is over, and an append
|
|
182
|
+
# or a stop from the coroutine still writing it would land on a
|
|
183
|
+
# message that is closing, or open a second one to report that.
|
|
184
|
+
self._abandoned = True
|
|
185
|
+
ts = self.ts
|
|
186
|
+
if ts is None:
|
|
187
|
+
return
|
|
188
|
+
await self._client.chat_stopStream(
|
|
189
|
+
channel=self._channel,
|
|
190
|
+
ts=ts,
|
|
191
|
+
chunks=[MarkdownTextChunk(text=markdown_text)],
|
|
192
|
+
)
|
|
193
|
+
|
|
194
|
+
async def _rotate(self) -> None:
|
|
195
|
+
"""Finalize the full message and continue in a fresh one.
|
|
196
|
+
|
|
197
|
+
Replays the undelivered appends into the new stream directly on the
|
|
198
|
+
SDK helper: if even the replay overflows (a single oversized delta),
|
|
199
|
+
the error propagates to the caller's failure handling rather than
|
|
200
|
+
rotating forever.
|
|
201
|
+
"""
|
|
202
|
+
current = self._require_streamer()
|
|
203
|
+
if current.ts is not None:
|
|
204
|
+
await self._client.chat_stopStream(channel=self._channel, ts=current.ts)
|
|
205
|
+
logger.debug(
|
|
206
|
+
"Streamed message hit the length limit; continuing in a new message "
|
|
207
|
+
"(channel: %s, thread: %s)",
|
|
208
|
+
self._channel,
|
|
209
|
+
self._thread_ts,
|
|
210
|
+
)
|
|
211
|
+
replay = self._pending.drain()
|
|
212
|
+
undelivered = "".join(item.markdown_text or "" for item in replay)
|
|
213
|
+
# Slack closes the code block a finalized message ends inside, so the
|
|
214
|
+
# one the cut fell in is opened again for the rest of it.
|
|
215
|
+
fence = open_fence(self._text[: len(self._text) - len(undelivered)])
|
|
216
|
+
self._text = ""
|
|
217
|
+
self._streamer = await self._new_streamer()
|
|
218
|
+
if fence is not None:
|
|
219
|
+
await self._append_to_streamer(markdown_text=fence + "\n", chunks=None)
|
|
220
|
+
for item in replay:
|
|
221
|
+
await self._append_to_streamer(
|
|
222
|
+
markdown_text=item.markdown_text, chunks=item.chunks
|
|
223
|
+
)
|
|
224
|
+
|
|
225
|
+
async def _append_or_rotate(
|
|
226
|
+
self, *, markdown_text: str | None, chunks: list[dict] | None = None
|
|
227
|
+
) -> None:
|
|
228
|
+
"""Append to the current message, rolling over where Slack refuses."""
|
|
229
|
+
try:
|
|
230
|
+
await self._append_to_streamer(markdown_text=markdown_text, chunks=chunks)
|
|
231
|
+
except SlackApiError as error:
|
|
232
|
+
if not is_message_too_long(error):
|
|
233
|
+
raise
|
|
234
|
+
await self._rotate()
|
|
235
|
+
|
|
236
|
+
async def _move_on(self, *, fence: str | None) -> None:
|
|
237
|
+
"""Finalize the current message at a break and open the next one.
|
|
238
|
+
|
|
239
|
+
The SDK helper delivers what it still holds as it stops. Should that
|
|
240
|
+
overflow after all, the usual rollover takes the message from there,
|
|
241
|
+
and the reply already continues in a fresh one. A break inside a code
|
|
242
|
+
block opens the next message with the block's fence.
|
|
243
|
+
"""
|
|
244
|
+
try:
|
|
245
|
+
await self._require_streamer().stop()
|
|
246
|
+
except SlackApiError as error:
|
|
247
|
+
if not is_message_too_long(error):
|
|
248
|
+
raise
|
|
249
|
+
await self._rotate()
|
|
250
|
+
return
|
|
251
|
+
self._pending.clear()
|
|
252
|
+
self._text = ""
|
|
253
|
+
self._streamer = await self._new_streamer()
|
|
254
|
+
if fence is not None:
|
|
255
|
+
await self._append_or_rotate(markdown_text=fence + "\n")
|
|
256
|
+
|
|
257
|
+
async def _append_to_streamer(
|
|
258
|
+
self, *, markdown_text: str | None, chunks: list[dict] | None
|
|
259
|
+
) -> None:
|
|
260
|
+
"""Append to the open stream, keeping the append until it lands.
|
|
261
|
+
|
|
262
|
+
The SDK helper returns a response only for a call that reached the
|
|
263
|
+
API; a buffered call returns None, leaving the append in the tail
|
|
264
|
+
for a rollover to replay.
|
|
265
|
+
"""
|
|
266
|
+
self._pending.record(markdown_text=markdown_text, chunks=chunks)
|
|
267
|
+
self._text += markdown_text or ""
|
|
268
|
+
response = await self._require_streamer().append(
|
|
269
|
+
markdown_text=markdown_text, chunks=chunks
|
|
270
|
+
)
|
|
271
|
+
if response is not None:
|
|
272
|
+
self._pending.clear()
|
|
273
|
+
|
|
274
|
+
async def _new_streamer(self) -> AsyncChatStream:
|
|
275
|
+
return await self._client.chat_stream(
|
|
276
|
+
channel=self._channel,
|
|
277
|
+
thread_ts=self._thread_ts,
|
|
278
|
+
recipient_team_id=self._recipient_team_id,
|
|
279
|
+
recipient_user_id=self._recipient_user_id,
|
|
280
|
+
task_display_mode="plan",
|
|
281
|
+
buffer_size=self._buffer_size,
|
|
282
|
+
)
|
|
283
|
+
|
|
284
|
+
def _require_streamer(self) -> AsyncChatStream:
|
|
285
|
+
if self._streamer is None:
|
|
286
|
+
raise RuntimeError("The stream has not been opened by an append")
|
|
287
|
+
return self._streamer
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
# The streams with a message open in a thread. A shutdown closes what is
|
|
291
|
+
# here: a reply cut off mid-flight would otherwise leave a message streaming
|
|
292
|
+
# with nothing to say why. A stream joins on the append that opens it — one
|
|
293
|
+
# that never opened has no message to close — and leaves when a caller
|
|
294
|
+
# stops it.
|
|
295
|
+
_open_streams: set[RotatingChatStream] = set()
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
async def close_open_streams(*, markdown_text: str) -> None:
|
|
299
|
+
"""
|
|
300
|
+
Close every stream still open, appending markdown_text to each.
|
|
301
|
+
|
|
302
|
+
For shutdown, once new work has stopped arriving. The replies
|
|
303
|
+
themselves cannot be finished — a reply can run for minutes and a
|
|
304
|
+
stopping container has seconds — so each message is closed where it
|
|
305
|
+
stands, saying so. One that fails to close does not stop the rest.
|
|
306
|
+
|
|
307
|
+
Args:
|
|
308
|
+
markdown_text (str): Markdown to append before closing each.
|
|
309
|
+
|
|
310
|
+
Returns:
|
|
311
|
+
None
|
|
312
|
+
"""
|
|
313
|
+
note = note_after_reply(markdown_text)
|
|
314
|
+
for stream in list(_open_streams):
|
|
315
|
+
_open_streams.discard(stream)
|
|
316
|
+
try:
|
|
317
|
+
await stream.close_unfinished(markdown_text=note)
|
|
318
|
+
except Exception:
|
|
319
|
+
logger.exception("Failed to close a stream while shutting down")
|
cobito/_stream_logic.py
ADDED
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
"""Pure logic for the streaming reply: its undelivered tail, and its notes.
|
|
2
|
+
|
|
3
|
+
The SDK helper buffers markdown until its buffer size and only then calls
|
|
4
|
+
the API, so an append that raised — and the buffered appends before it —
|
|
5
|
+
never reached Slack. `PendingAppends` is that tail: appends accumulate
|
|
6
|
+
until a call reports having reached the API, and a rollover drains them to
|
|
7
|
+
replay into the fresh message with nothing lost. The stream I/O itself
|
|
8
|
+
lives in `cobito._stream`.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
from dataclasses import dataclass
|
|
14
|
+
|
|
15
|
+
from slack_sdk.errors import SlackApiError
|
|
16
|
+
from slack_sdk.web.async_slack_response import AsyncSlackResponse
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def is_message_too_long(error: SlackApiError) -> bool:
|
|
20
|
+
"""
|
|
21
|
+
Tell whether a stream call failed because the message is full.
|
|
22
|
+
|
|
23
|
+
Args:
|
|
24
|
+
error (SlackApiError): The error the chat stream call raised.
|
|
25
|
+
|
|
26
|
+
Returns:
|
|
27
|
+
bool: True if Slack answered `msg_too_long`; False for any other
|
|
28
|
+
failure, including one that never carried a response.
|
|
29
|
+
"""
|
|
30
|
+
if not isinstance(error.response, AsyncSlackResponse):
|
|
31
|
+
return False
|
|
32
|
+
reason = error.response.get("error")
|
|
33
|
+
return isinstance(reason, str) and reason == "msg_too_long"
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def note_after_reply(text: str) -> str:
|
|
37
|
+
"""
|
|
38
|
+
Set a note off from the reply it is appended to.
|
|
39
|
+
|
|
40
|
+
An app's own notes — a failure, a shutdown — are appended to whatever
|
|
41
|
+
the reply had streamed so far, which is a sentence stopped wherever it
|
|
42
|
+
was. Without a break the note reads as the next few words of it.
|
|
43
|
+
|
|
44
|
+
Args:
|
|
45
|
+
text (str): The note.
|
|
46
|
+
|
|
47
|
+
Returns:
|
|
48
|
+
str: The note, opening on a line of its own.
|
|
49
|
+
"""
|
|
50
|
+
return f"\n\n{text}"
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
@dataclass(frozen=True)
|
|
54
|
+
class PendingAppend:
|
|
55
|
+
"""One append handed to the current stream but possibly not delivered."""
|
|
56
|
+
|
|
57
|
+
markdown_text: str | None
|
|
58
|
+
chunks: list[dict] | None
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
class PendingAppends:
|
|
62
|
+
"""The appends a streaming reply may still owe its reader.
|
|
63
|
+
|
|
64
|
+
Holds them in the order they were made, which is the order a replay has
|
|
65
|
+
to repeat them in for the continuation message to read as the reply
|
|
66
|
+
continuing.
|
|
67
|
+
"""
|
|
68
|
+
|
|
69
|
+
def __init__(self) -> None:
|
|
70
|
+
self._items: list[PendingAppend] = []
|
|
71
|
+
|
|
72
|
+
def record(
|
|
73
|
+
self, *, markdown_text: str | None = None, chunks: list[dict] | None = None
|
|
74
|
+
) -> None:
|
|
75
|
+
"""
|
|
76
|
+
Remember an append until a call confirms it reached Slack.
|
|
77
|
+
|
|
78
|
+
Args:
|
|
79
|
+
markdown_text (str | None): Markdown handed to the stream.
|
|
80
|
+
chunks (list[dict] | None): Streaming chunks handed to the stream.
|
|
81
|
+
|
|
82
|
+
Returns:
|
|
83
|
+
None
|
|
84
|
+
"""
|
|
85
|
+
self._items.append(PendingAppend(markdown_text=markdown_text, chunks=chunks))
|
|
86
|
+
|
|
87
|
+
def clear(self) -> None:
|
|
88
|
+
"""
|
|
89
|
+
Drop the tail, the appends in it having reached Slack.
|
|
90
|
+
|
|
91
|
+
Returns:
|
|
92
|
+
None
|
|
93
|
+
"""
|
|
94
|
+
self._items.clear()
|
|
95
|
+
|
|
96
|
+
def drain(self) -> list[PendingAppend]:
|
|
97
|
+
"""
|
|
98
|
+
Take the tail for replay, leaving nothing owed to the old message.
|
|
99
|
+
|
|
100
|
+
Returns:
|
|
101
|
+
list[PendingAppend]: The undelivered appends, oldest first. The
|
|
102
|
+
list is the caller's own, so recording into a replay's own
|
|
103
|
+
tail as it goes does not disturb it.
|
|
104
|
+
"""
|
|
105
|
+
items = self._items
|
|
106
|
+
self._items = []
|
|
107
|
+
return items
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
# How long a streamed message may grow before the reply moves on to the next
|
|
111
|
+
# one at its next paragraph break. Slack refuses a streamed message past about
|
|
112
|
+
# 12,000 characters (measured 2026-11-27, English and Japanese alike, so the
|
|
113
|
+
# limit counts characters rather than bytes). The margin is what a paragraph
|
|
114
|
+
# already under way when the mark is passed has left to finish in.
|
|
115
|
+
SOFT_MESSAGE_LENGTH = 10_000
|
|
116
|
+
|
|
117
|
+
_FENCE = "```"
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def open_fence(text: str) -> str | None:
|
|
121
|
+
"""
|
|
122
|
+
Tell whether text ends inside a fenced code block.
|
|
123
|
+
|
|
124
|
+
Only whole lines count: a last line without its line break may still be
|
|
125
|
+
on its way. A fence is a line of three or more backticks, indented by up
|
|
126
|
+
to three spaces. A block closes on a line of only backticks, at least as
|
|
127
|
+
many as it opened with.
|
|
128
|
+
|
|
129
|
+
Args:
|
|
130
|
+
text (str): Markdown streamed so far.
|
|
131
|
+
|
|
132
|
+
Returns:
|
|
133
|
+
str | None: The line that opened the block, as written after its
|
|
134
|
+
indentation, or None outside one.
|
|
135
|
+
"""
|
|
136
|
+
opener: str | None = None
|
|
137
|
+
width = 0
|
|
138
|
+
for line in text.split("\n")[:-1]:
|
|
139
|
+
stripped = line.lstrip(" ")
|
|
140
|
+
if len(line) - len(stripped) > 3 or not stripped.startswith(_FENCE):
|
|
141
|
+
continue
|
|
142
|
+
ticks = len(stripped) - len(stripped.lstrip("`"))
|
|
143
|
+
if opener is None:
|
|
144
|
+
opener, width = stripped, ticks
|
|
145
|
+
elif stripped.rstrip() == "`" * ticks and ticks >= width:
|
|
146
|
+
opener, width = None, 0
|
|
147
|
+
return opener
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def split_point(
|
|
151
|
+
sent: str, incoming: str, soft_limit: int
|
|
152
|
+
) -> tuple[int, str | None] | None:
|
|
153
|
+
"""
|
|
154
|
+
Find where the current message should end within incoming.
|
|
155
|
+
|
|
156
|
+
Once the message holds at least soft_limit characters it ends at the
|
|
157
|
+
first break that keeps the reply's blocks whole: the end of a blank line
|
|
158
|
+
outside a code block, or the end of any line inside one. A table ends at
|
|
159
|
+
a blank line, so no table is cut in two. A code block can run past any
|
|
160
|
+
paragraph, so it is cut between two of its lines: Slack closes the block
|
|
161
|
+
the finished message ends inside, and the next message opens it again.
|
|
162
|
+
|
|
163
|
+
Args:
|
|
164
|
+
sent (str): Markdown already handed to the current message.
|
|
165
|
+
incoming (str): Markdown about to be appended.
|
|
166
|
+
soft_limit (int): The length past which the message may end.
|
|
167
|
+
|
|
168
|
+
Returns:
|
|
169
|
+
tuple[int, str | None] | None: How much of incoming belongs to the
|
|
170
|
+
current message, the rest opening the next one, and the fence
|
|
171
|
+
line the next message opens with when the break falls inside a
|
|
172
|
+
code block; None when the message does not end within incoming.
|
|
173
|
+
"""
|
|
174
|
+
text = sent + incoming
|
|
175
|
+
start = len(sent)
|
|
176
|
+
for end in range(max(start, soft_limit, 1), len(text) + 1):
|
|
177
|
+
if text[end - 1] != "\n":
|
|
178
|
+
continue
|
|
179
|
+
fence = open_fence(text[:end])
|
|
180
|
+
if fence is not None or text[end - 2 : end] == "\n\n":
|
|
181
|
+
return end - start, fence
|
|
182
|
+
return None
|
cobito/_tools.py
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
"""Pure helpers for showing tool calls in a streamed reply.
|
|
2
|
+
|
|
3
|
+
Each tool call is a task in the reply's plan, updated in place as the tool
|
|
4
|
+
starts and finishes, under a heading the app sets itself.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from dataclasses import dataclass
|
|
10
|
+
|
|
11
|
+
# Slack's task_update chunks cap title/details at 256 characters.
|
|
12
|
+
TASK_CHUNK_TITLE_MAX_LENGTH = 256
|
|
13
|
+
|
|
14
|
+
# The heading over the tool calls. Left unset, Slack writes its own, in a
|
|
15
|
+
# language that follows neither the asking user's locale nor the
|
|
16
|
+
# workspace's.
|
|
17
|
+
PLAN_TITLE = "Tool calls"
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@dataclass(frozen=True)
|
|
21
|
+
class ToolUse:
|
|
22
|
+
"""A tool being called, for a "using tool" indicator."""
|
|
23
|
+
|
|
24
|
+
name: str | None
|
|
25
|
+
tool_use_id: str | None
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def build_tool_use_task_chunk(
|
|
29
|
+
*, tool_use_id: str | None, tool_name: str | None, status: str
|
|
30
|
+
) -> dict:
|
|
31
|
+
"""
|
|
32
|
+
Build a task_update chunk showing a tool invocation in the reply timeline.
|
|
33
|
+
|
|
34
|
+
Args:
|
|
35
|
+
tool_use_id (str | None): The tool call's ID, used as the task ID so
|
|
36
|
+
a later status change updates the same task.
|
|
37
|
+
tool_name (str | None): The tool name, if the call carried one.
|
|
38
|
+
status (str): The task status (in_progress / complete / error).
|
|
39
|
+
|
|
40
|
+
Returns:
|
|
41
|
+
dict: A chat.appendStream / chat.stopStream `chunks` entry.
|
|
42
|
+
"""
|
|
43
|
+
title = f"Using {tool_name}" if tool_name else "Using a tool"
|
|
44
|
+
return {
|
|
45
|
+
"type": "task_update",
|
|
46
|
+
"id": tool_use_id or "tool",
|
|
47
|
+
"title": title[:TASK_CHUNK_TITLE_MAX_LENGTH],
|
|
48
|
+
"status": status,
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def tool_chunks(
|
|
53
|
+
*,
|
|
54
|
+
completed: ToolUse | None = None,
|
|
55
|
+
started: ToolUse | None = None,
|
|
56
|
+
error: bool = False,
|
|
57
|
+
) -> list[dict]:
|
|
58
|
+
"""
|
|
59
|
+
Build the chunks for a change in which tool is running.
|
|
60
|
+
|
|
61
|
+
Any change carries the plan's title with it, so a message a rollover
|
|
62
|
+
opens mid-reply gets the title on its first task too.
|
|
63
|
+
|
|
64
|
+
Args:
|
|
65
|
+
completed (ToolUse | None): The tool that just finished, if one did.
|
|
66
|
+
started (ToolUse | None): The tool that just started, if one did.
|
|
67
|
+
error (bool): Whether the completed tool failed.
|
|
68
|
+
|
|
69
|
+
Returns:
|
|
70
|
+
list[dict]: The chunks, empty when nothing changed: the plan's
|
|
71
|
+
title, then at most one to close the completed tool's task and
|
|
72
|
+
one to open the next.
|
|
73
|
+
"""
|
|
74
|
+
chunks: list[dict] = []
|
|
75
|
+
if completed is not None:
|
|
76
|
+
chunks.append(
|
|
77
|
+
build_tool_use_task_chunk(
|
|
78
|
+
tool_use_id=completed.tool_use_id,
|
|
79
|
+
tool_name=completed.name,
|
|
80
|
+
status="error" if error else "complete",
|
|
81
|
+
)
|
|
82
|
+
)
|
|
83
|
+
if started is not None:
|
|
84
|
+
chunks.append(
|
|
85
|
+
build_tool_use_task_chunk(
|
|
86
|
+
tool_use_id=started.tool_use_id,
|
|
87
|
+
tool_name=started.name,
|
|
88
|
+
status="in_progress",
|
|
89
|
+
)
|
|
90
|
+
)
|
|
91
|
+
if not chunks:
|
|
92
|
+
return []
|
|
93
|
+
return [{"type": "plan_update", "title": PLAN_TITLE}, *chunks]
|
cobito/_version.py
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
# file generated by vcs-versioning
|
|
2
|
+
# don't change, don't track in version control
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
__all__ = [
|
|
6
|
+
"__version__",
|
|
7
|
+
"__version_tuple__",
|
|
8
|
+
"version",
|
|
9
|
+
"version_tuple",
|
|
10
|
+
"__commit_id__",
|
|
11
|
+
"commit_id",
|
|
12
|
+
]
|
|
13
|
+
|
|
14
|
+
version: str
|
|
15
|
+
__version__: str
|
|
16
|
+
__version_tuple__: tuple[int | str, ...]
|
|
17
|
+
version_tuple: tuple[int | str, ...]
|
|
18
|
+
commit_id: str | None
|
|
19
|
+
__commit_id__: str | None
|
|
20
|
+
|
|
21
|
+
__version__ = version = '0.1.0'
|
|
22
|
+
__version_tuple__ = version_tuple = (0, 1, 0)
|
|
23
|
+
|
|
24
|
+
__commit_id__ = commit_id = None
|
cobito/py.typed
ADDED
|
File without changes
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: cobito
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Turn a Slack thread into a conversation for your AI agent, and stream the agent's reply back into the thread
|
|
5
|
+
Project-URL: Repository, https://github.com/iwamot/cobito
|
|
6
|
+
Project-URL: Issues, https://github.com/iwamot/cobito/issues
|
|
7
|
+
Author: Takashi Iwamoto
|
|
8
|
+
License-Expression: MIT
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Keywords: ai-agents,llm,slack,slack-bot,streaming
|
|
11
|
+
Classifier: Development Status :: 3 - Alpha
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.15
|
|
18
|
+
Classifier: Topic :: Communications :: Chat
|
|
19
|
+
Classifier: Typing :: Typed
|
|
20
|
+
Requires-Python: >=3.12
|
|
21
|
+
Requires-Dist: aiohttp>=3.14.5
|
|
22
|
+
Requires-Dist: slack-sdk>=3.48.0
|
|
23
|
+
Description-Content-Type: text/markdown
|
|
24
|
+
|
|
25
|
+
# cobito
|
|
26
|
+
|
|
27
|
+
[](https://pypi.org/project/cobito/)
|
|
28
|
+
[](https://pypi.org/project/cobito/)
|
|
29
|
+
|
|
30
|
+
Turn a Slack thread into a conversation for your AI agent, and stream the agent's reply back into the thread.
|
|
31
|
+
|
|
32
|
+
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, and makes a conversation smaller when the agent cannot take it.
|
|
33
|
+
|
|
34
|
+
## Install
|
|
35
|
+
|
|
36
|
+
```sh
|
|
37
|
+
pip install cobito
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
cobito is asynchronous and works with slack-sdk's `AsyncWebClient`, as Bolt's `AsyncApp` hands it to listeners.
|
|
41
|
+
|
|
42
|
+
## Usage
|
|
43
|
+
|
|
44
|
+
### Streaming a reply
|
|
45
|
+
|
|
46
|
+
`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.
|
|
47
|
+
|
|
48
|
+
```python
|
|
49
|
+
from cobito import RotatingChatStream, ToolUse, tool_chunks
|
|
50
|
+
|
|
51
|
+
stream = RotatingChatStream(
|
|
52
|
+
client,
|
|
53
|
+
channel=channel_id,
|
|
54
|
+
thread_ts=thread_ts,
|
|
55
|
+
recipient_team_id=team_id,
|
|
56
|
+
recipient_user_id=user_id,
|
|
57
|
+
buffer_size=256,
|
|
58
|
+
)
|
|
59
|
+
await stream.append(chunks=tool_chunks(started=ToolUse(name="search", tool_use_id="t1")))
|
|
60
|
+
await stream.append(chunks=tool_chunks(completed=ToolUse(name="search", tool_use_id="t1")))
|
|
61
|
+
await stream.append(markdown_text="Here is what I found.")
|
|
62
|
+
await stream.stop()
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
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.
|
|
66
|
+
|
|
67
|
+
### Marking the post being worked on
|
|
68
|
+
|
|
69
|
+
```python
|
|
70
|
+
from cobito import WaitingReaction
|
|
71
|
+
|
|
72
|
+
waiting = WaitingReaction(client, channel_id=channel_id, message_ts=message_ts)
|
|
73
|
+
await waiting.add()
|
|
74
|
+
try:
|
|
75
|
+
... # reply
|
|
76
|
+
finally:
|
|
77
|
+
await waiting.clear()
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
Both calls are best-effort: without the `reactions:write` scope the post goes unmarked.
|
|
81
|
+
|
|
82
|
+
### Resending a conversation that is too long
|
|
83
|
+
|
|
84
|
+
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.
|
|
85
|
+
|
|
86
|
+
```python
|
|
87
|
+
from cobito import apply_history_cut, drop_older_turns, history_cut_metadata
|
|
88
|
+
|
|
89
|
+
EVENT_TYPE = "my_bot_history"
|
|
90
|
+
|
|
91
|
+
replies = apply_history_cut(replies, bot_user_id=bot_user_id, event_type=EVENT_TYPE)
|
|
92
|
+
sent = replies
|
|
93
|
+
resent_unchanged = False
|
|
94
|
+
dropping_tries = 0
|
|
95
|
+
while True:
|
|
96
|
+
cut = history_cut_metadata(sent[0]["ts"], event_type=EVENT_TYPE)
|
|
97
|
+
try:
|
|
98
|
+
await reply_with(sent, metadata=cut if dropping_tries else None)
|
|
99
|
+
break
|
|
100
|
+
except AgentFailedBeforeReplying:
|
|
101
|
+
if not resent_unchanged:
|
|
102
|
+
resent_unchanged = True
|
|
103
|
+
continue
|
|
104
|
+
dropping_tries += 1
|
|
105
|
+
shorter = drop_older_turns(
|
|
106
|
+
replies, bot_user_id=bot_user_id, attempt=dropping_tries
|
|
107
|
+
)
|
|
108
|
+
if shorter is None:
|
|
109
|
+
raise
|
|
110
|
+
sent = shorter
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
`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.
|
|
114
|
+
|
|
115
|
+
## API
|
|
116
|
+
|
|
117
|
+
| Name | What it does |
|
|
118
|
+
|---|---|
|
|
119
|
+
| `RotatingChatStream` | A streamed reply that continues in a new message when one fills up |
|
|
120
|
+
| `close_open_streams(markdown_text=)` | Close every reply still streaming, for shutdown |
|
|
121
|
+
| `note_after_reply(text)` | Set a note off from the reply it is appended to |
|
|
122
|
+
| `ToolUse`, `tool_chunks(completed=, started=, error=)` | The chunks that show a tool call starting and finishing |
|
|
123
|
+
| `PLAN_TITLE` | The heading over the tool calls |
|
|
124
|
+
| `WaitingReaction`, `WAITING_REACTION` | The reaction on the post being worked on |
|
|
125
|
+
| `history_cut_metadata(oldest_ts, event_type=)` | The message metadata recording where a conversation was cut |
|
|
126
|
+
| `apply_history_cut(replies, bot_user_id=, event_type=)` | Keep the replies from the last recorded cut |
|
|
127
|
+
| `drop_older_turns(replies, bot_user_id=, attempt=)` | Drop the oldest turns for one try |
|
|
128
|
+
|
|
129
|
+
## License
|
|
130
|
+
|
|
131
|
+
MIT
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
cobito/__init__.py,sha256=NeU7F6Pw-5MLWOUxuejw_qmgqhfgxFWNRGD0poOUSiQ,840
|
|
2
|
+
cobito/_reaction.py,sha256=7ySWyszbLw9NSYWzRMADOz2TezLd2qJRitSUcRJpXT4,2438
|
|
3
|
+
cobito/_resend.py,sha256=YVax9o-VVbQdh_gIc0Aapho3ay6YiZvgrxs3KV6v9K0,5502
|
|
4
|
+
cobito/_stream.py,sha256=Z-iBdh1TvGEbDTCyHp2x0qWuShKaa-XRXrxOP74D9LM,12540
|
|
5
|
+
cobito/_stream_logic.py,sha256=UjCvAz6T1WqE6nbdRyAy5ECWgaZxUNbLU6mpTB49Lsg,6250
|
|
6
|
+
cobito/_tools.py,sha256=hgskQPmtbQMn1IOODit8uGaFq_RKrh8HlXjc4A7WhI0,2915
|
|
7
|
+
cobito/_version.py,sha256=n_5vdJsPNu7wZ57LGuRL585uvll-hiuvZUBWzdG0RQU,520
|
|
8
|
+
cobito/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
9
|
+
cobito-0.1.0.dist-info/METADATA,sha256=SSqH0EJ68zDkbQ_i0ynKZEkqNKVeNmjo0TJc-tj75n0,5500
|
|
10
|
+
cobito-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
11
|
+
cobito-0.1.0.dist-info/licenses/LICENSE,sha256=wDYonbyc1rLS_QsysQ2Yv6jPONxXjZ49g-4R3reu_0E,1072
|
|
12
|
+
cobito-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Takashi Iwamoto
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|