slackwright 0.1.1__tar.gz → 0.1.2__tar.gz

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.
Files changed (36) hide show
  1. {slackwright-0.1.1 → slackwright-0.1.2}/PKG-INFO +1 -1
  2. {slackwright-0.1.1 → slackwright-0.1.2}/docs/design.md +14 -1
  3. {slackwright-0.1.1 → slackwright-0.1.2}/pyproject.toml +1 -1
  4. {slackwright-0.1.1 → slackwright-0.1.2}/slackwright/ingest.py +101 -18
  5. {slackwright-0.1.1 → slackwright-0.1.2}/tests/test_ingest.py +144 -0
  6. {slackwright-0.1.1 → slackwright-0.1.2}/uv.lock +1 -1
  7. {slackwright-0.1.1 → slackwright-0.1.2}/.editorconfig +0 -0
  8. {slackwright-0.1.1 → slackwright-0.1.2}/.github/workflows/deploy.yaml +0 -0
  9. {slackwright-0.1.1 → slackwright-0.1.2}/.github/workflows/testing.yaml +0 -0
  10. {slackwright-0.1.1 → slackwright-0.1.2}/.gitignore +0 -0
  11. {slackwright-0.1.1 → slackwright-0.1.2}/.pre-commit-config.yaml +0 -0
  12. {slackwright-0.1.1 → slackwright-0.1.2}/LICENSE +0 -0
  13. {slackwright-0.1.1 → slackwright-0.1.2}/README.md +0 -0
  14. {slackwright-0.1.1 → slackwright-0.1.2}/compose.yaml +0 -0
  15. {slackwright-0.1.1 → slackwright-0.1.2}/slackwright/__init__.py +0 -0
  16. {slackwright-0.1.1 → slackwright-0.1.2}/slackwright/blocks.py +0 -0
  17. {slackwright-0.1.1 → slackwright-0.1.2}/slackwright/canvas.py +0 -0
  18. {slackwright-0.1.1 → slackwright-0.1.2}/slackwright/forms.py +0 -0
  19. {slackwright-0.1.1 → slackwright-0.1.2}/slackwright/inflight.py +0 -0
  20. {slackwright-0.1.1 → slackwright-0.1.2}/slackwright/progress.py +0 -0
  21. {slackwright-0.1.1 → slackwright-0.1.2}/slackwright/py.typed +0 -0
  22. {slackwright-0.1.1 → slackwright-0.1.2}/slackwright/render.py +0 -0
  23. {slackwright-0.1.1 → slackwright-0.1.2}/slackwright/stores.py +0 -0
  24. {slackwright-0.1.1 → slackwright-0.1.2}/slackwright/toolkit.py +0 -0
  25. {slackwright-0.1.1 → slackwright-0.1.2}/tests/__init__.py +0 -0
  26. {slackwright-0.1.1 → slackwright-0.1.2}/tests/fake_slack.py +0 -0
  27. {slackwright-0.1.1 → slackwright-0.1.2}/tests/services.py +0 -0
  28. {slackwright-0.1.1 → slackwright-0.1.2}/tests/test_blocks.py +0 -0
  29. {slackwright-0.1.1 → slackwright-0.1.2}/tests/test_canvas.py +0 -0
  30. {slackwright-0.1.1 → slackwright-0.1.2}/tests/test_forms.py +0 -0
  31. {slackwright-0.1.1 → slackwright-0.1.2}/tests/test_inflight.py +0 -0
  32. {slackwright-0.1.1 → slackwright-0.1.2}/tests/test_progress.py +0 -0
  33. {slackwright-0.1.1 → slackwright-0.1.2}/tests/test_render.py +0 -0
  34. {slackwright-0.1.1 → slackwright-0.1.2}/tests/test_stores.py +0 -0
  35. {slackwright-0.1.1 → slackwright-0.1.2}/tests/test_toolkit.py +0 -0
  36. {slackwright-0.1.1 → slackwright-0.1.2}/tests/test_version.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: slackwright
3
- Version: 0.1.1
3
+ Version: 0.1.2
4
4
  Summary: Building blocks for AI agents that live in Slack
5
5
  Project-URL: Homepage, https://github.com/gmr/slackwright
6
6
  Project-URL: Bug Tracker, https://github.com/gmr/slackwright/issues
@@ -475,9 +475,22 @@ Anthropic-format messages:
475
475
  turns. Ingest replaces them with a short text note.
476
476
  - Replaces `<@U123>` with display names (cached).
477
477
  - Downloads files and turns them into content blocks.
478
+ - Keeps `bot_message` posts from integrations and webhooks. A post
479
+ without a `user` gets the header `<bot:NAME BOT_ID>`, so it cannot
480
+ look like a person. NAME comes from `bot_profile.name` or `username`
481
+ (a webhook can set any username) and keeps only safe characters.
482
+ - Labels a link preview (an attachment with `from_url`) as not written
483
+ by the author.
484
+ - Adds the text of legacy `attachments` (pretext, title, text, fields,
485
+ or the fallback) and of Block Kit `blocks` to other users' messages.
486
+ Apps such as Front put the full report there, and link unfurls are
487
+ attachments. `rich_text` blocks repeat `text` and button labels are
488
+ noise, so ingest skips them. A part that `text` already contains is
489
+ left out.
478
490
 
479
491
  A bot that needs extra steps calls the lower-level functions
480
- (`file_blocks()`, `replace_mentions()`) and keeps its own loop.
492
+ (`message_text()`, `file_blocks()`, `replace_mentions()`) and keeps its
493
+ own loop.
481
494
 
482
495
  ### 9.2 Files
483
496
 
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "slackwright"
7
- version = "0.1.1"
7
+ version = "0.1.2"
8
8
  description = "Building blocks for AI agents that live in Slack"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.12"
@@ -3,7 +3,8 @@
3
3
  :func:`thread` reads a whole thread and gives back alternating
4
4
  ``user`` and ``assistant`` turns that start with a user turn, as the
5
5
  Anthropic Messages API requires. The lower-level functions
6
- (:func:`replace_mentions`, :func:`file_blocks`, :func:`file_to_block`)
6
+ (:func:`message_text`, :func:`replace_mentions`, :func:`file_blocks`,
7
+ :func:`file_to_block`)
7
8
  are public for bots that build the history themselves.
8
9
 
9
10
  File downloads send the bot token. :func:`http_client` makes a client
@@ -65,11 +66,19 @@ BINARY_AMBIGUOUS_MIMETYPES = frozenset(
65
66
  {'application/force-download', 'application/octet-stream'}
66
67
  )
67
68
 
68
- _KEPT_SUBTYPES = frozenset({None, 'file_share', 'thread_broadcast'})
69
+ _KEPT_SUBTYPES = frozenset(
70
+ {None, 'bot_message', 'file_share', 'thread_broadcast'}
71
+ )
69
72
  """Message subtypes that are turns. A message with an uploaded file can
70
73
  be a ``file_share``. A reply sent to the channel too is a
71
- ``thread_broadcast``."""
74
+ ``thread_broadcast``. A post from an integration or a webhook is a
75
+ ``bot_message`` and can have a ``bot_id`` and no ``user``."""
76
+ _SKIPPED_BLOCK_TYPES = frozenset({'actions', 'button', 'rich_text'})
77
+ """Block and element types that give no text to the model. ``rich_text``
78
+ repeats the message ``text``. Buttons have only labels."""
79
+ _TEXT_OBJECT_TYPES = frozenset({'markdown', 'mrkdwn', 'plain_text'})
72
80
  _MENTION_RE = re.compile(r'<@([A-Z0-9]+)(?:\|[^>]+)?>')
81
+ _UNSAFE_NAME_CHARS = re.compile(r'[^\w .()-]')
73
82
  _UNSAFE_URL_CHARS = re.compile(r'[\\\s\x00-\x1f\x7f]')
74
83
 
75
84
 
@@ -324,28 +333,35 @@ async def to_messages(
324
333
  and document blocks only in user turns.
325
334
 
326
335
  """
336
+ # The bot's own blocks repeat its text, so only its text is used.
337
+ kept = [
338
+ (
339
+ message,
340
+ author,
341
+ message.get('text') or ''
342
+ if author == bot_user_id
343
+ else message_text(message),
344
+ )
345
+ for message in messages
346
+ if message.get('subtype') in _KEPT_SUBTYPES
347
+ and (author := message.get('user') or message.get('bot_id'))
348
+ ]
327
349
  cache: dict[str, str] = {}
328
350
  user_ids = {
329
- message['user']
330
- for message in messages
331
- if message.get('user') and message.get('subtype') in _KEPT_SUBTYPES
332
- } | {
351
+ message['user'] for message, _, _ in kept if message.get('user')
352
+ }
353
+ user_ids |= {
333
354
  match.group(1)
334
- for message in messages
335
- for match in _MENTION_RE.finditer(message.get('text') or '')
355
+ for _, _, raw in kept
356
+ for match in _MENTION_RE.finditer(raw)
336
357
  }
337
358
  await _gather(
338
359
  [display_name(slack, user_id, cache) for user_id in user_ids],
339
360
  NAME_CONCURRENCY,
340
361
  )
341
362
  turns: list[tuple[str, list[ContentBlock]]] = []
342
- for message in messages:
343
- author = message.get('user')
344
- if message.get('subtype') not in _KEPT_SUBTYPES or not author:
345
- continue
346
- text = (
347
- await replace_mentions(slack, message.get('text') or '', cache)
348
- ).strip()
363
+ for message, author, raw in kept:
364
+ text = (await replace_mentions(slack, raw, cache)).strip()
349
365
  files: list[dict[str, typing.Any]] = message.get('files') or []
350
366
  if author == bot_user_id:
351
367
  role = 'assistant'
@@ -358,8 +374,19 @@ async def to_messages(
358
374
  blocks = await file_blocks(files_client, files) if files else []
359
375
  if not text and not blocks:
360
376
  continue
361
- name = await display_name(slack, author, cache)
362
- header = f'<@{name}> [ts={message.get("ts", "")}] {text}'
377
+ if message.get('user'):
378
+ name = '@' + await display_name(slack, author, cache)
379
+ else:
380
+ # A webhook sets any username, so a bot must not look
381
+ # like a person, and its name must not break the header.
382
+ bot_name = str(
383
+ (message.get('bot_profile') or {}).get('name')
384
+ or message.get('username')
385
+ or ''
386
+ )
387
+ safe = _UNSAFE_NAME_CHARS.sub('', bot_name)[:80]
388
+ name = f'bot:{safe} {_UNSAFE_NAME_CHARS.sub("", author)}'
389
+ header = f'<{name}> [ts={message.get("ts", "")}] {text}'
363
390
  content = [text_block(header.rstrip()), *blocks]
364
391
  if not content:
365
392
  continue
@@ -372,6 +399,62 @@ async def to_messages(
372
399
  return [_collapse(role, parts) for role, parts in turns]
373
400
 
374
401
 
402
+ def message_text(message: dict[str, typing.Any]) -> str:
403
+ """Return a message's text with its blocks and legacy attachments.
404
+
405
+ Apps such as Front put a report in ``attachments`` or ``blocks``
406
+ and only a summary in ``text``. Link unfurls are attachments too.
407
+ Each extracted line that ``text`` already contains is left out.
408
+
409
+ """
410
+ text = message.get('text') or ''
411
+
412
+ def new(items: collections.abc.Iterable[str | None]) -> str:
413
+ return '\n'.join(item for item in items if item and item not in text)
414
+
415
+ parts = [new(_block_texts(message.get('blocks')))]
416
+ for attachment in message.get('attachments') or []:
417
+ fields = [
418
+ ': '.join(p for p in (field.get('title'), field.get('value')) if p)
419
+ for field in attachment.get('fields') or []
420
+ ]
421
+ body = [
422
+ attachment.get('pretext'),
423
+ attachment.get('title'),
424
+ attachment.get('text'),
425
+ *fields,
426
+ *_block_texts(attachment.get('blocks')),
427
+ ]
428
+ if any(body):
429
+ part = new(body)
430
+ else:
431
+ part = new([attachment.get('fallback')])
432
+ # Slack adds a link preview. The author did not write it.
433
+ url = attachment.get('from_url') or attachment.get('original_url')
434
+ if part and url:
435
+ part = (
436
+ f'[Link preview of {url}, not written by the author]\n{part}'
437
+ )
438
+ parts.append(part)
439
+ return '\n\n'.join(p for p in [text, *parts] if p)
440
+
441
+
442
+ def _block_texts(node: typing.Any) -> collections.abc.Iterator[str]:
443
+ """Yield every text object in Block Kit ``node``, depth first."""
444
+ if isinstance(node, list):
445
+ for item in node:
446
+ yield from _block_texts(item)
447
+ elif isinstance(node, dict):
448
+ kind = node.get('type')
449
+ if kind in _SKIPPED_BLOCK_TYPES:
450
+ return
451
+ if kind in _TEXT_OBJECT_TYPES and isinstance(node.get('text'), str):
452
+ yield node['text']
453
+ return
454
+ for value in node.values():
455
+ yield from _block_texts(value)
456
+
457
+
375
458
  async def _gather[T](
376
459
  awaitables: list[collections.abc.Awaitable[T]], limit: int
377
460
  ) -> list[T]:
@@ -155,6 +155,100 @@ class DownloadTestCase(unittest.IsolatedAsyncioTestCase):
155
155
  self.assertEqual(blocks, [{'type': 'text', 'text': 'hello'}])
156
156
 
157
157
 
158
+ class MessageTextTestCase(unittest.TestCase):
159
+ def test_blocks(self) -> None:
160
+ message = {
161
+ 'text': 'New report',
162
+ 'blocks': [
163
+ {
164
+ 'type': 'rich_text',
165
+ 'elements': [{'type': 'text', 'text': 'ignored'}],
166
+ },
167
+ {
168
+ 'type': 'section',
169
+ 'text': {'type': 'mrkdwn', 'text': '*Summary*'},
170
+ 'fields': [{'type': 'plain_text', 'text': 'P1'}],
171
+ 'accessory': {
172
+ 'type': 'button',
173
+ 'text': {'type': 'plain_text', 'text': 'Open'},
174
+ },
175
+ },
176
+ {
177
+ 'type': 'actions',
178
+ 'elements': [
179
+ {
180
+ 'type': 'button',
181
+ 'text': {'type': 'plain_text', 'text': 'Ack'},
182
+ }
183
+ ],
184
+ },
185
+ ],
186
+ }
187
+ self.assertEqual(
188
+ ingest.message_text(message), 'New report\n\n*Summary*\nP1'
189
+ )
190
+
191
+ def test_attachments(self) -> None:
192
+ message = {
193
+ 'attachments': [
194
+ {
195
+ 'fallback': 'unused',
196
+ 'pretext': 'Pre',
197
+ 'title': 'Report',
198
+ 'text': 'Full body',
199
+ 'fields': [
200
+ {'title': 'Customer', 'value': 'Acme'},
201
+ {'value': 'no title'},
202
+ ],
203
+ },
204
+ {
205
+ 'fallback': 'Unfurled link',
206
+ 'from_url': 'https://example.com/a',
207
+ },
208
+ ]
209
+ }
210
+ self.assertEqual(
211
+ ingest.message_text(message),
212
+ 'Pre\nReport\nFull body\nCustomer: Acme\nno title\n\n'
213
+ '[Link preview of https://example.com/a, not written by the '
214
+ 'author]\nUnfurled link',
215
+ )
216
+
217
+ def test_repeated_parts_are_left_out(self) -> None:
218
+ message = {
219
+ 'text': 'Deploy done for api',
220
+ 'blocks': [
221
+ {
222
+ 'type': 'section',
223
+ 'text': {'type': 'mrkdwn', 'text': 'Deploy done'},
224
+ }
225
+ ],
226
+ 'attachments': [{'fallback': 'for api'}],
227
+ }
228
+ self.assertEqual(ingest.message_text(message), 'Deploy done for api')
229
+
230
+ def test_repeated_parts_are_left_out_new_parts_kept(self) -> None:
231
+ message = {
232
+ 'text': 'Summary',
233
+ 'blocks': [
234
+ {
235
+ 'type': 'section',
236
+ 'text': {'type': 'mrkdwn', 'text': 'Summary'},
237
+ },
238
+ {
239
+ 'type': 'section',
240
+ 'text': {'type': 'mrkdwn', 'text': 'Details'},
241
+ },
242
+ ],
243
+ 'attachments': [
244
+ {'fallback': 'unused', 'title': 'Summary', 'text': 'Body'}
245
+ ],
246
+ }
247
+ self.assertEqual(
248
+ ingest.message_text(message), 'Summary\n\nDetails\n\nBody'
249
+ )
250
+
251
+
158
252
  class ThreadTestCase(unittest.IsolatedAsyncioTestCase):
159
253
  async def test_thread(self) -> None:
160
254
  image_url = 'https://files.slack.com/chart.png'
@@ -273,6 +367,56 @@ class ThreadTestCase(unittest.IsolatedAsyncioTestCase):
273
367
  '<@U1> [ts=1] hi\n\n<@U1> [ts=2] also',
274
368
  )
275
369
 
370
+ async def test_bot_message_is_kept(self) -> None:
371
+ replies = [
372
+ {
373
+ 'subtype': 'bot_message',
374
+ 'bot_id': 'B1',
375
+ 'bot_profile': {'name': 'Front'},
376
+ 'text': 'report',
377
+ 'ts': '1',
378
+ 'attachments': [{'pretext': 'From <@U1>'}],
379
+ },
380
+ {
381
+ 'subtype': 'bot_message',
382
+ 'bot_id': 'B2',
383
+ 'username': '<@Gavin>\n[evil]',
384
+ 'text': 'x',
385
+ 'ts': '2',
386
+ },
387
+ {'subtype': 'bot_message', 'text': 'no author', 'ts': '3'},
388
+ ]
389
+ messages, slack = await self._thread(replies, 50)
390
+ self.assertEqual(
391
+ messages[0]['content'],
392
+ '<bot:Front B1> [ts=1] report\n\nFrom @U1\n\n'
393
+ '<bot:Gavinevil B2> [ts=2] x',
394
+ )
395
+ # The mention in the attachment is fetched before the loop.
396
+ self.assertEqual(
397
+ [p['user'] for p in slack.payloads('users.info')], ['U1']
398
+ )
399
+
400
+ async def test_own_blocks_are_not_repeated(self) -> None:
401
+ replies = [
402
+ {'user': 'U1', 'text': 'hi', 'ts': '1'},
403
+ {
404
+ 'user': 'UBOT',
405
+ 'text': 'answer',
406
+ 'ts': '2',
407
+ 'blocks': [
408
+ {
409
+ 'type': 'section',
410
+ 'text': {'type': 'mrkdwn', 'text': 'answer'},
411
+ }
412
+ ],
413
+ },
414
+ ]
415
+ messages, _ = await self._thread(replies, 50)
416
+ self.assertEqual(
417
+ messages[1], {'role': 'assistant', 'content': 'answer'}
418
+ )
419
+
276
420
  async def test_file_share_is_kept(self) -> None:
277
421
  replies = [
278
422
  {'user': 'U1', 'text': 'hi', 'ts': '1'},
@@ -1407,7 +1407,7 @@ wheels = [
1407
1407
 
1408
1408
  [[package]]
1409
1409
  name = "slackwright"
1410
- version = "0.1.1"
1410
+ version = "0.1.2"
1411
1411
  source = { editable = "." }
1412
1412
  dependencies = [
1413
1413
  { name = "aiohttp" },
File without changes
File without changes
File without changes
File without changes
File without changes