slackwright 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.
@@ -0,0 +1,93 @@
1
+ """Track in-flight work so that shutdown can wait for it.
2
+
3
+ Slack events and interactions are often handled as background tasks.
4
+ Without tracking, a rolling deploy can stop the process while a reply
5
+ is half sent. :func:`track` counts the work around each handler, and
6
+ :func:`wait_for_drain` lets shutdown wait (up to
7
+ :data:`SHUTDOWN_TIMEOUT` seconds) for the work to finish.
8
+
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import asyncio
14
+ import contextlib
15
+ import logging
16
+ import typing
17
+
18
+ if typing.TYPE_CHECKING:
19
+ import collections.abc
20
+
21
+ LOGGER = logging.getLogger(__name__)
22
+
23
+ SHUTDOWN_TIMEOUT: float = 15
24
+ """Maximum seconds to wait for in-flight work during shutdown."""
25
+
26
+ _active: int = 0
27
+ _drain: asyncio.Event | None = None
28
+
29
+
30
+ def _get_drain() -> asyncio.Event:
31
+ """Return the drain event. Create it on first use."""
32
+ global _drain
33
+ if _drain is None:
34
+ _drain = asyncio.Event()
35
+ _drain.set()
36
+ return _drain
37
+
38
+
39
+ def active() -> int:
40
+ """Return the number of in-flight units of work."""
41
+ return _active
42
+
43
+
44
+ def reset() -> None:
45
+ """Reset the module state (for tests)."""
46
+ global _active, _drain
47
+ _active = 0
48
+ _drain = None
49
+
50
+
51
+ @contextlib.asynccontextmanager
52
+ async def track() -> collections.abc.AsyncGenerator[None]:
53
+ """Count one unit of in-flight work for the time of the context."""
54
+ global _active
55
+ drain = _get_drain()
56
+ _active += 1
57
+ drain.clear()
58
+ try:
59
+ yield
60
+ finally:
61
+ _active -= 1
62
+ if _active == 0:
63
+ drain.set()
64
+
65
+
66
+ async def wait_for_drain() -> bool:
67
+ """Wait until all in-flight work is done, or SHUTDOWN_TIMEOUT ends.
68
+
69
+ Returns ``True`` if all work finished, ``False`` on timeout.
70
+
71
+ """
72
+ if _active == 0:
73
+ return True
74
+ LOGGER.info(
75
+ 'Waiting for %i in-flight task(s) to finish (timeout %.0fs)',
76
+ _active,
77
+ SHUTDOWN_TIMEOUT,
78
+ )
79
+ # New work can start after the drain event is set and before this
80
+ # task wakes up, so check the count again after each wakeup.
81
+ loop = asyncio.get_running_loop()
82
+ deadline = loop.time() + SHUTDOWN_TIMEOUT
83
+ while _active > 0:
84
+ try:
85
+ await asyncio.wait_for(
86
+ _get_drain().wait(), max(deadline - loop.time(), 0)
87
+ )
88
+ except TimeoutError:
89
+ LOGGER.warning(
90
+ 'Shutdown timeout with %i task(s) still in flight', _active
91
+ )
92
+ return False
93
+ return True
slackwright/ingest.py ADDED
@@ -0,0 +1,394 @@
1
+ """Turn Slack threads and files into Anthropic messages.
2
+
3
+ :func:`thread` reads a whole thread and gives back alternating
4
+ ``user`` and ``assistant`` turns that start with a user turn, as the
5
+ Anthropic Messages API requires. The lower-level functions
6
+ (:func:`replace_mentions`, :func:`file_blocks`, :func:`file_to_block`)
7
+ are public for bots that build the history themselves.
8
+
9
+ File downloads send the bot token. :func:`http_client` makes a client
10
+ that sends the token only to Slack file hosts, on every request and on
11
+ every redirect.
12
+
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import asyncio
18
+ import base64
19
+ import logging
20
+ import re
21
+ import typing
22
+ import urllib.parse
23
+
24
+ import httpx
25
+
26
+ if typing.TYPE_CHECKING:
27
+ import collections.abc
28
+
29
+ LOGGER = logging.getLogger(__name__)
30
+
31
+ ContentBlock = dict[str, typing.Any]
32
+ Message = dict[str, typing.Any]
33
+
34
+ SLACK_FILE_HOSTS = frozenset({'files.slack.com'})
35
+ """Hosts that may receive the bot token."""
36
+
37
+ MAX_FILE_BYTES = 10 * 1024 * 1024
38
+ """Largest file to download and give to the model."""
39
+
40
+ # The Claude API vision docs allow 10 MB base64-encoded per image, see
41
+ # https://platform.claude.com/docs/en/build-with-claude/vision ("Image
42
+ # limits and costs"). 7,500,000 raw bytes is exactly 10,000,000 base64
43
+ # characters. Amazon Bedrock allows only 5 MB base64-encoded.
44
+ MAX_IMAGE_BYTES = 7_500_000
45
+ """Largest image to give to the model. Base64 makes it about 10 MB."""
46
+
47
+ DOWNLOAD_CONCURRENCY = 4
48
+ """File downloads at the same time, for each message."""
49
+
50
+ NAME_CONCURRENCY = 8
51
+ """``users.info`` calls at the same time (Tier 4: 100+ per minute)."""
52
+
53
+ IMAGE_MEDIA_TYPES = frozenset(
54
+ {'image/gif', 'image/jpeg', 'image/png', 'image/webp'}
55
+ )
56
+ TEXT_LIKE_MIMETYPES = frozenset(
57
+ {
58
+ 'application/javascript',
59
+ 'application/json',
60
+ 'application/x-yaml',
61
+ 'application/xml',
62
+ }
63
+ )
64
+ BINARY_AMBIGUOUS_MIMETYPES = frozenset(
65
+ {'application/force-download', 'application/octet-stream'}
66
+ )
67
+
68
+ _KEPT_SUBTYPES = frozenset({None, 'thread_broadcast'})
69
+ """Message subtypes that are turns. A reply sent to the channel too is
70
+ a ``thread_broadcast``."""
71
+ _MENTION_RE = re.compile(r'<@([A-Z0-9]+)(?:\|[^>]+)?>')
72
+ _UNSAFE_URL_CHARS = re.compile(r'[\\\s\x00-\x1f\x7f]')
73
+
74
+
75
+ class DisallowedURLError(httpx.RequestError):
76
+ """A token-bearing request went to a host that is not allowed."""
77
+
78
+
79
+ def text_block(text: str) -> ContentBlock:
80
+ """Return an Anthropic text content block."""
81
+ return {'type': 'text', 'text': text}
82
+
83
+
84
+ def is_slack_file_url(
85
+ url: str, allowed_hosts: collections.abc.Iterable[str] = SLACK_FILE_HOSTS
86
+ ) -> bool:
87
+ """Return ``True`` only if it is safe to send the token to ``url``.
88
+
89
+ The URL must use https on the default port, have no user info, and
90
+ have a host that is exactly one of ``allowed_hosts``. urllib and
91
+ httpx must agree on the host, so that a parser difference cannot
92
+ send the request to a different host. Never raises.
93
+
94
+ """
95
+ if not url or _UNSAFE_URL_CHARS.search(url):
96
+ return False
97
+ hosts = {host.lower() for host in allowed_hosts}
98
+ try:
99
+ parts = urllib.parse.urlsplit(url)
100
+ return bool(
101
+ parts.scheme == 'https'
102
+ and '@' not in parts.netloc
103
+ and parts.port in (None, 443)
104
+ and parts.hostname in hosts
105
+ and httpx.URL(url).host == parts.hostname
106
+ )
107
+ except (ValueError, TypeError, httpx.InvalidURL):
108
+ return False
109
+
110
+
111
+ def http_client(
112
+ bot_token: str,
113
+ *,
114
+ allowed_hosts: collections.abc.Iterable[str] = SLACK_FILE_HOSTS,
115
+ transport: httpx.AsyncBaseTransport | None = None,
116
+ timeout: float = 30,
117
+ ) -> httpx.AsyncClient:
118
+ """Return an HTTP client that sends ``bot_token`` to Slack hosts only.
119
+
120
+ The caller must close the client.
121
+
122
+ """
123
+ hosts = frozenset(allowed_hosts)
124
+
125
+ async def refuse_other_hosts(request: httpx.Request) -> None:
126
+ if not is_slack_file_url(str(request.url), hosts):
127
+ raise DisallowedURLError(
128
+ f'Refusing to send the Slack token to {request.url.host!r}',
129
+ request=request,
130
+ )
131
+
132
+ return httpx.AsyncClient(
133
+ headers={'Authorization': f'Bearer {bot_token}'},
134
+ event_hooks={'request': [refuse_other_hosts]},
135
+ follow_redirects=False,
136
+ timeout=timeout,
137
+ transport=transport,
138
+ )
139
+
140
+
141
+ def file_to_block(mimetype: str, content: bytes) -> ContentBlock:
142
+ """Convert file bytes to an Anthropic content block.
143
+
144
+ PDF becomes a ``document`` block, supported images become ``image``
145
+ blocks, and text becomes a ``text`` block. Other types become a
146
+ ``text`` block that explains the error to the model.
147
+
148
+ """
149
+ mimetype = mimetype.split(';', 1)[0].strip().lower()
150
+ if mimetype in IMAGE_MEDIA_TYPES and len(content) > MAX_IMAGE_BYTES:
151
+ return text_block(
152
+ 'ERROR: the image is larger than the maximum of '
153
+ f'{MAX_IMAGE_BYTES:,} bytes.'
154
+ )
155
+ if mimetype == 'application/pdf' or mimetype in IMAGE_MEDIA_TYPES:
156
+ return {
157
+ 'type': 'document' if mimetype == 'application/pdf' else 'image',
158
+ 'source': {
159
+ 'type': 'base64',
160
+ 'media_type': mimetype,
161
+ 'data': base64.b64encode(content).decode(),
162
+ },
163
+ }
164
+ if mimetype.startswith('text/') or mimetype in TEXT_LIKE_MIMETYPES:
165
+ return text_block(content.decode('utf-8', errors='replace'))
166
+ if mimetype in BINARY_AMBIGUOUS_MIMETYPES:
167
+ try:
168
+ return text_block(content.decode('utf-8'))
169
+ except UnicodeDecodeError:
170
+ return text_block(
171
+ 'ERROR: a binary file could not be decoded as text. '
172
+ 'Supported types are PDF, images, and text files.'
173
+ )
174
+ return text_block(
175
+ f'ERROR: unsupported file type {mimetype}. Supported types are '
176
+ 'PDF, images, and text files.'
177
+ )
178
+
179
+
180
+ async def download(
181
+ client: httpx.AsyncClient, url: str, max_bytes: int = MAX_FILE_BYTES
182
+ ) -> ContentBlock | None:
183
+ """Download one file and return it as a content block.
184
+
185
+ Returns ``None`` if the download fails. Returns an error text block
186
+ if the file is larger than ``max_bytes``.
187
+
188
+ """
189
+ try:
190
+ async with client.stream('GET', url) as response:
191
+ if response.status_code != 200:
192
+ LOGGER.warning(
193
+ 'Unable to download Slack file %s: HTTP %s',
194
+ url,
195
+ response.status_code,
196
+ )
197
+ return None
198
+ mimetype = response.headers.get(
199
+ 'content-type', 'application/octet-stream'
200
+ )
201
+ data = bytearray()
202
+ async for chunk in response.aiter_bytes():
203
+ data.extend(chunk)
204
+ if len(data) > max_bytes:
205
+ return text_block(
206
+ f'ERROR: the file is larger than the maximum of '
207
+ f'{max_bytes // (1024 * 1024)} MB.'
208
+ )
209
+ except (httpx.HTTPError, httpx.InvalidURL) as error:
210
+ LOGGER.warning('Failed to download Slack file %s: %s', url, error)
211
+ return None
212
+ return file_to_block(mimetype, bytes(data))
213
+
214
+
215
+ async def file_blocks(
216
+ client: httpx.AsyncClient, files: list[dict[str, typing.Any]]
217
+ ) -> list[ContentBlock]:
218
+ """Download a message's files and return them as content blocks.
219
+
220
+ Downloads run at the same time, at most :data:`DOWNLOAD_CONCURRENCY`
221
+ at once, because each file can use up to :data:`MAX_FILE_BYTES` of
222
+ memory. Files that fail to download are left out.
223
+
224
+ """
225
+ urls = [
226
+ url
227
+ for item in files
228
+ if (url := item.get('url_private_download') or item.get('url_private'))
229
+ ]
230
+ blocks = await _gather(
231
+ [download(client, url) for url in urls], DOWNLOAD_CONCURRENCY
232
+ )
233
+ return [block for block in blocks if block is not None]
234
+
235
+
236
+ async def display_name(
237
+ slack: typing.Any, user_id: str, cache: dict[str, str]
238
+ ) -> str:
239
+ """Return the display name of a Slack user. Uses ``cache``."""
240
+ if user_id in cache:
241
+ return cache[user_id]
242
+ name = user_id
243
+ try:
244
+ response = await slack.users_info(user=user_id)
245
+ user = response.get('user') or {}
246
+ profile = user.get('profile') or {}
247
+ name = (
248
+ profile.get('display_name')
249
+ or user.get('real_name')
250
+ or user.get('name')
251
+ or user_id
252
+ )
253
+ except Exception: # noqa: BLE001 - a missing name must not fail a turn
254
+ LOGGER.warning('Failed to get the display name of %s', user_id)
255
+ cache[user_id] = name
256
+ return name
257
+
258
+
259
+ async def replace_mentions(
260
+ slack: typing.Any, text: str, cache: dict[str, str]
261
+ ) -> str:
262
+ """Replace ``<@U123>`` mentions with ``@display name``."""
263
+ names = {
264
+ user_id: await display_name(slack, user_id, cache)
265
+ for user_id in {m.group(1) for m in _MENTION_RE.finditer(text)}
266
+ }
267
+ return _MENTION_RE.sub(lambda m: f'@{names[m.group(1)]}', text)
268
+
269
+
270
+ async def replies(
271
+ slack: typing.Any, channel_id: str, thread_ts: str
272
+ ) -> list[dict[str, typing.Any]]:
273
+ """Return all messages in a thread, oldest first. Reads all pages."""
274
+ messages: list[dict[str, typing.Any]] = []
275
+ async for page in await slack.conversations_replies(
276
+ channel=channel_id, ts=thread_ts, limit=200
277
+ ):
278
+ messages.extend(page.get('messages') or [])
279
+ return messages
280
+
281
+
282
+ async def thread(
283
+ slack: typing.Any,
284
+ files_client: httpx.AsyncClient,
285
+ channel_id: str,
286
+ thread_ts: str,
287
+ bot_user_id: str,
288
+ max_messages: int = 50,
289
+ ) -> list[Message]:
290
+ """Read a thread and return it as Anthropic messages.
291
+
292
+ Args:
293
+ slack: A ``slack_sdk`` ``AsyncWebClient``.
294
+ files_client: The client from :func:`http_client`, used to
295
+ download files.
296
+ channel_id: The channel of the thread.
297
+ thread_ts: The ``ts`` of the thread's first message.
298
+ bot_user_id: The bot's user ID. Its messages become
299
+ ``assistant`` turns.
300
+ max_messages: Only the last ``max_messages`` are used. Zero or
301
+ less gives no messages.
302
+
303
+ """
304
+ if max_messages < 1:
305
+ return []
306
+ messages = await replies(slack, channel_id, thread_ts)
307
+ return await to_messages(
308
+ slack, files_client, messages[-max_messages:], bot_user_id
309
+ )
310
+
311
+
312
+ async def to_messages(
313
+ slack: typing.Any,
314
+ files_client: httpx.AsyncClient,
315
+ messages: list[dict[str, typing.Any]],
316
+ bot_user_id: str,
317
+ ) -> list[Message]:
318
+ """Convert Slack messages (oldest first) to Anthropic messages.
319
+
320
+ Each user message starts with ``<@name> [ts=...]``. Turns with the
321
+ same role that follow each other are merged. Files in the bot's
322
+ own messages become a text note, because the API accepts image
323
+ and document blocks only in user turns.
324
+
325
+ """
326
+ cache: dict[str, str] = {}
327
+ user_ids = {
328
+ message['user']
329
+ for message in messages
330
+ if message.get('user') and message.get('subtype') in _KEPT_SUBTYPES
331
+ } | {
332
+ match.group(1)
333
+ for message in messages
334
+ for match in _MENTION_RE.finditer(message.get('text') or '')
335
+ }
336
+ await _gather(
337
+ [display_name(slack, user_id, cache) for user_id in user_ids],
338
+ NAME_CONCURRENCY,
339
+ )
340
+ turns: list[tuple[str, list[ContentBlock]]] = []
341
+ for message in messages:
342
+ author = message.get('user')
343
+ if message.get('subtype') not in _KEPT_SUBTYPES or not author:
344
+ continue
345
+ text = (
346
+ await replace_mentions(slack, message.get('text') or '', cache)
347
+ ).strip()
348
+ files: list[dict[str, typing.Any]] = message.get('files') or []
349
+ if author == bot_user_id:
350
+ role = 'assistant'
351
+ names = ', '.join(f.get('name') or 'file' for f in files)
352
+ parts = [text, f'[Attached: {names}]' if files else '']
353
+ joined = '\n\n'.join(p for p in parts if p)
354
+ content = [text_block(joined)] if joined else []
355
+ else:
356
+ role = 'user'
357
+ blocks = await file_blocks(files_client, files) if files else []
358
+ if not text and not blocks:
359
+ continue
360
+ name = await display_name(slack, author, cache)
361
+ header = f'<@{name}> [ts={message.get("ts", "")}] {text}'
362
+ content = [text_block(header.rstrip()), *blocks]
363
+ if not content:
364
+ continue
365
+ if turns and turns[-1][0] == role:
366
+ turns[-1][1].extend(content)
367
+ else:
368
+ turns.append((role, content))
369
+ while turns and turns[0][0] == 'assistant':
370
+ turns.pop(0)
371
+ return [_collapse(role, parts) for role, parts in turns]
372
+
373
+
374
+ async def _gather[T](
375
+ awaitables: list[collections.abc.Awaitable[T]], limit: int
376
+ ) -> list[T]:
377
+ """Await all of ``awaitables``, at most ``limit`` at once, in order."""
378
+ semaphore = asyncio.Semaphore(limit)
379
+
380
+ async def run(awaitable: collections.abc.Awaitable[T]) -> T:
381
+ async with semaphore:
382
+ return await awaitable
383
+
384
+ return await asyncio.gather(*(run(a) for a in awaitables))
385
+
386
+
387
+ def _collapse(role: str, parts: list[ContentBlock]) -> Message:
388
+ """Return ``{role, content}``. Text-only content becomes a string."""
389
+ if all(part['type'] == 'text' for part in parts):
390
+ return {
391
+ 'role': role,
392
+ 'content': '\n\n'.join(part['text'] for part in parts),
393
+ }
394
+ return {'role': role, 'content': parts}
@@ -0,0 +1,90 @@
1
+ """Show an agent's tool calls while it works.
2
+
3
+ With a :class:`~slackwright.render.Stream`, each tool call is a task
4
+ card in the streamed reply. Without one, the reporter sets the
5
+ assistant thread status (``assistant.threads.setStatus``).
6
+
7
+ Progress is best effort: a Slack or network error is logged and never
8
+ stops the agent's turn.
9
+
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import logging
15
+ import typing
16
+
17
+ import aiohttp
18
+ from slack_sdk import errors
19
+
20
+ if typing.TYPE_CHECKING:
21
+ import collections.abc
22
+
23
+ from slackwright import render
24
+
25
+ LOGGER = logging.getLogger(__name__)
26
+
27
+ _ERRORS = (errors.SlackClientError, aiohttp.ClientError, TimeoutError)
28
+ """Errors that a progress update ignores. Cancellation is not one."""
29
+
30
+
31
+ class Reporter:
32
+ """Report the start and end of each tool call."""
33
+
34
+ def __init__(
35
+ self,
36
+ slack: typing.Any,
37
+ channel_id: str,
38
+ thread_ts: str,
39
+ *,
40
+ stream: render.Stream | None = None,
41
+ ) -> None:
42
+ self._slack = slack
43
+ self._channel_id = channel_id
44
+ self._thread_ts = thread_ts
45
+ self._stream = stream
46
+ self._running: dict[str, str] = {}
47
+
48
+ async def start(self, call_id: str, title: str) -> None:
49
+ """Report that a tool call started."""
50
+ self._running[call_id] = title
51
+ if self._stream is not None:
52
+ await _quietly(self._stream.task(call_id, title, 'in_progress'))
53
+ else:
54
+ await self._set_status(f'{title}…')
55
+
56
+ async def finish(
57
+ self, call_id: str, *, ok: bool = True, output: str | None = None
58
+ ) -> None:
59
+ """Report that a tool call ended."""
60
+ title = self._running.pop(call_id, call_id)
61
+ if self._stream is not None:
62
+ await _quietly(
63
+ self._stream.task(
64
+ call_id,
65
+ title,
66
+ 'complete' if ok else 'error',
67
+ output=output,
68
+ )
69
+ )
70
+ elif self._running:
71
+ await self._set_status(f'{next(iter(self._running.values()))}…')
72
+ else:
73
+ await self._set_status('')
74
+
75
+ async def _set_status(self, status: str) -> None:
76
+ await _quietly(
77
+ self._slack.assistant_threads_setStatus(
78
+ channel_id=self._channel_id,
79
+ thread_ts=self._thread_ts,
80
+ status=status,
81
+ )
82
+ )
83
+
84
+
85
+ async def _quietly(update: collections.abc.Awaitable[typing.Any]) -> None:
86
+ """Await a progress update. Log and ignore a Slack or network error."""
87
+ try:
88
+ await update
89
+ except _ERRORS as error:
90
+ LOGGER.debug('Could not update progress: %r', error)
slackwright/py.typed ADDED
File without changes