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.
slackwright/render.py ADDED
@@ -0,0 +1,384 @@
1
+ """Post LLM Markdown answers to Slack.
2
+
3
+ Slack renders standard Markdown natively through the ``markdown_text``
4
+ argument of ``chat.postMessage`` and the streaming methods: headers,
5
+ bold, links, lists, code with syntax highlight, tables, quotes, and
6
+ task lists. So this module does not convert Markdown. It only handles
7
+ the 12,000-character limit.
8
+
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import html
14
+ import logging
15
+ import re
16
+ import time
17
+ import typing
18
+
19
+ import markdown_it
20
+ from slack_sdk import errors
21
+
22
+ from slackwright import blocks
23
+
24
+ LOGGER = logging.getLogger(__name__)
25
+
26
+ MARKDOWN_LIMIT = blocks.MARKDOWN_TEXT_LIMIT
27
+ """Characters of Markdown per message, and per stream."""
28
+
29
+ STREAM_MAX_SECONDS = 540
30
+ """Stop a stream before Slack's 10-minute limit ends it."""
31
+
32
+ STREAM_MAX_TASKS = 50
33
+ """Unique tasks per streamed message."""
34
+
35
+ TaskStatus = typing.Literal['pending', 'in_progress', 'complete', 'error']
36
+
37
+ _NOT_STREAMING = 'message_not_in_streaming_state'
38
+
39
+ _PARSER = markdown_it.MarkdownIt('commonmark').enable('table')
40
+
41
+ _ZWSP = '\u200b'
42
+ # A ``<!`` that does not start a strict Slack date token. The date
43
+ # pattern excludes ``<`` and ``>``, so no token can hide inside it.
44
+ # The format and the optional link share one field that can contain
45
+ # ``^``. Two fields that both match ``^`` make the time quadratic.
46
+ _SPECIAL = re.compile(r'<!(?!date\^\d+\^[^<>|]*\|[^<>]*>)')
47
+ _BARE_BROADCAST = re.compile(
48
+ r'(?<![A-Za-z0-9])@(channel|here|everyone|group)(?![A-Za-z0-9])',
49
+ re.IGNORECASE,
50
+ )
51
+
52
+
53
+ def neutralize_broadcasts(text: str) -> str:
54
+ """Return ``text`` with no mention that notifies a channel or group.
55
+
56
+ Breaks every ``<!`` except a strict Slack date token such as
57
+ ``<!date^1700000000^{date}|Nov 14>``. A zero-width space after the
58
+ ``<`` changes tokens such as ``<!channel>``, ``<!here>``, and
59
+ ``<!subteam^ID|@label>`` into literal text. Also blocks the bare
60
+ words ``@channel``, ``@here``, ``@everyone``, and ``@group`` in any
61
+ letter case with a zero-width space after the ``@``. User mentions
62
+ such as ``<@U123>`` and email addresses such as ``x@here.com`` do
63
+ not change.
64
+
65
+ The :class:`~slackwright.toolkit.Toolkit` calls this on agent text
66
+ unless the bot sets ``allow_broadcasts``. :func:`post_markdown` does
67
+ not call it, so a bot can call it on its final answer before it
68
+ posts that answer.
69
+
70
+ """
71
+ text = _SPECIAL.sub(f'<{_ZWSP}!', text)
72
+ return _BARE_BROADCAST.sub(lambda m: f'@{_ZWSP}{m.group(1)}', text)
73
+
74
+
75
+ _MRKDWN_RULES = (
76
+ (re.compile(r'^#{1,6}[ \t]+(.+?)[ \t#]*$', re.MULTILINE), r'**\1**'),
77
+ (re.compile(r'^([ \t]*)[-*+][ \t]+', re.MULTILINE), '\\1• '),
78
+ (re.compile(r'(?<![*\w])\*(?!\*)([^*\n]+?)\*(?![*\w])'), r'_\1_'),
79
+ (re.compile(r'\*\*(.+?)\*\*|__(.+?)__'), r'*\1\2*'),
80
+ (re.compile(r'~~(.+?)~~'), r'~\1~'),
81
+ )
82
+ # Code and link destinations must not change. They go out as
83
+ # placeholders before the rules run, and come back after. A link
84
+ # destination can contain one level of balanced parentheses.
85
+ _PROTECTED = re.compile(
86
+ r'(?P<code>```.*?```|`[^`\n]+`)'
87
+ r'|\[(?P<label>[^\]\n]+)\]'
88
+ r'\((?P<url>https?://(?:[^()\s|]|\([^()\s|]*\))+)\)',
89
+ re.DOTALL,
90
+ )
91
+ _PLACEHOLDER = re.compile('\x00(\\d+)\x00')
92
+
93
+
94
+ def to_mrkdwn(markdown: str) -> str:
95
+ """Convert simple Markdown to Slack mrkdwn, for places that need it.
96
+
97
+ Use it only where Slack does not render Markdown, such as a modal
98
+ ``section`` block. Handles headings, bullet lists, bold, italic,
99
+ strikethrough, and links. ``&``, ``<``, and ``>`` are escaped first,
100
+ so the text cannot make a mention or a special token.
101
+
102
+ """
103
+ saved: list[str] = []
104
+
105
+ def protect(match: re.Match[str]) -> str:
106
+ saved.append(match['code'] or match['url'])
107
+ placeholder = f'\x00{len(saved) - 1}\x00'
108
+ if match['code']:
109
+ return placeholder
110
+ return f'<{placeholder}|{match["label"]}>'
111
+
112
+ text = html.escape(markdown.replace('\x00', ''), quote=False)
113
+ text = _PROTECTED.sub(protect, text)
114
+ for pattern, replacement in _MRKDWN_RULES:
115
+ text = pattern.sub(replacement, text)
116
+ return _PLACEHOLDER.sub(lambda m: saved[int(m.group(1))], text)
117
+
118
+
119
+ def split_markdown(text: str, limit: int = MARKDOWN_LIMIT) -> list[str]:
120
+ """Split ``text`` into parts of at most ``limit`` characters.
121
+
122
+ Splits only between top-level blocks, never inside a code block,
123
+ a table, or a list. A single block that is longer than ``limit`` is
124
+ returned as one part, so the caller must handle it.
125
+
126
+ """
127
+ text = text.strip()
128
+ if len(text) <= limit:
129
+ return [text] if text else []
130
+ lines = text.splitlines()
131
+ # ponytail: link reference definitions are not tokens and are lost
132
+ # when a long answer is split; LLM output rarely uses them.
133
+ blocks = [
134
+ '\n'.join(lines[token.map[0] : token.map[1]]).strip()
135
+ for token in _PARSER.parse(text)
136
+ if token.level == 0 and token.map and token.nesting >= 0
137
+ ]
138
+ parts: list[str] = []
139
+ current = ''
140
+ for block in blocks:
141
+ candidate = f'{current}\n\n{block}' if current else block
142
+ if len(candidate) <= limit:
143
+ current = candidate
144
+ continue
145
+ if current:
146
+ parts.append(current)
147
+ current = block
148
+ if current:
149
+ parts.append(current)
150
+ return parts
151
+
152
+
153
+ async def post_markdown(
154
+ slack: typing.Any, channel_id: str, thread_ts: str | None, text: str
155
+ ) -> list[str]:
156
+ """Post Markdown to a channel or thread. Return the message ``ts`` list.
157
+
158
+ Text over :data:`MARKDOWN_LIMIT` characters is split into more than
159
+ one message. A single block over the limit (for example, a very long
160
+ code block) is uploaded as a Markdown file.
161
+
162
+ """
163
+ timestamps: list[str] = []
164
+ for part in split_markdown(text):
165
+ if len(part) > MARKDOWN_LIMIT:
166
+ await slack.files_upload_v2(
167
+ channel=channel_id,
168
+ thread_ts=thread_ts,
169
+ content=part,
170
+ filename='response.md',
171
+ title='Response',
172
+ )
173
+ continue
174
+ response = await slack.chat_postMessage(
175
+ channel=channel_id, thread_ts=thread_ts, markdown_text=part
176
+ )
177
+ timestamps.append(response['ts'])
178
+ return timestamps
179
+
180
+
181
+ class Stream:
182
+ """Stream a reply, with task cards for the agent's steps.
183
+
184
+ Text over the per-stream limit is not sent to the stream. It is
185
+ posted with :func:`post_markdown` when the stream closes. When the
186
+ stream is near Slack's time limit, it is stopped, open tasks are
187
+ marked as errors, and the rest of the text is posted after it.
188
+
189
+ A stream is for one task. Do not call its methods from more than
190
+ one task at the same time.
191
+
192
+ Args:
193
+ slack: A ``slack_sdk`` ``AsyncWebClient``.
194
+ channel_id: The channel of the thread.
195
+ thread_ts: The thread to reply in.
196
+ user_id: The user who receives the stream. Required by Slack
197
+ in channels.
198
+ team_id: The team of ``user_id``. Required by Slack in channels.
199
+ task_display_mode: ``timeline`` shows each task as a card in
200
+ the text. ``plan`` groups the tasks in one plan block.
201
+
202
+ """
203
+
204
+ def __init__(
205
+ self,
206
+ slack: typing.Any,
207
+ channel_id: str,
208
+ thread_ts: str,
209
+ *,
210
+ user_id: str | None = None,
211
+ team_id: str | None = None,
212
+ task_display_mode: typing.Literal['timeline', 'plan'] = 'timeline',
213
+ buffer_size: int = 256,
214
+ max_seconds: float = STREAM_MAX_SECONDS,
215
+ ) -> None:
216
+ self._slack = slack
217
+ self._channel_id = channel_id
218
+ self._thread_ts = thread_ts
219
+ self._options: dict[str, typing.Any] = {
220
+ 'recipient_user_id': user_id,
221
+ 'recipient_team_id': team_id,
222
+ 'task_display_mode': task_display_mode,
223
+ 'buffer_size': buffer_size,
224
+ }
225
+ self._max_seconds = max_seconds
226
+ self._stream: typing.Any = None
227
+ self._started = 0.0
228
+ self._chars = 0
229
+ self._tasks: dict[str, tuple[str, TaskStatus]] = {}
230
+ self._overflow: list[str] = []
231
+ self._pending: list[str] = []
232
+ self._unsent = ''
233
+ self._stopped = False
234
+ self._finalized = False
235
+
236
+ @property
237
+ def ts(self) -> str | None:
238
+ """The ``ts`` of the streamed message, after the first send."""
239
+ return self._stream.ts if self._stream else None
240
+
241
+ async def text(self, markdown: str) -> None:
242
+ """Add Markdown text to the reply."""
243
+ if not markdown:
244
+ return
245
+ if (
246
+ self._stopped
247
+ or self._overflow
248
+ or self._chars + len(markdown) > MARKDOWN_LIMIT
249
+ or await self._expired()
250
+ ):
251
+ self._overflow.append(markdown)
252
+ return
253
+ self._chars += len(markdown)
254
+ # The SDK keeps short text in a buffer and returns None. Keep a
255
+ # copy until a send, so a stop that fails does not lose it.
256
+ if await (await self._get()).append(markdown_text=markdown) is None:
257
+ self._unsent += markdown
258
+ else:
259
+ self._unsent = ''
260
+
261
+ async def task(
262
+ self,
263
+ task_id: str,
264
+ title: str,
265
+ status: TaskStatus,
266
+ *,
267
+ details: str | None = None,
268
+ output: str | None = None,
269
+ sources: list[tuple[str, str]] | None = None,
270
+ ) -> None:
271
+ """Add or update a task card.
272
+
273
+ ``sources`` is a list of ``(text, url)`` pairs. Updates after
274
+ the stream stopped, and new tasks over the limit of 50, are
275
+ dropped.
276
+
277
+ """
278
+ if self._stopped or await self._expired():
279
+ return
280
+ if task_id not in self._tasks and len(self._tasks) >= (
281
+ STREAM_MAX_TASKS
282
+ ):
283
+ LOGGER.debug('Dropping task %s: task limit reached', task_id)
284
+ return
285
+ self._tasks[task_id] = (title, status)
286
+ chunk = _task_chunk(task_id, title, status, details, output)
287
+ if sources:
288
+ chunk['sources'] = [
289
+ {'type': 'url', 'text': text, 'url': url}
290
+ for text, url in sources
291
+ ]
292
+ await (await self._get()).append(chunks=[chunk])
293
+ self._unsent = ''
294
+
295
+ async def close(self) -> list[str]:
296
+ """Stop the stream and post any overflow text.
297
+
298
+ Returns the ``ts`` values of overflow messages. If a post fails,
299
+ the parts that were not posted stay, and the next call tries
300
+ them again. Do not call it again before the last call returns.
301
+
302
+ """
303
+ await self._stop()
304
+ self._pending.extend(split_markdown(''.join(self._overflow)))
305
+ self._overflow = []
306
+ timestamps: list[str] = []
307
+ while self._pending:
308
+ timestamps += await post_markdown(
309
+ self._slack,
310
+ self._channel_id,
311
+ self._thread_ts,
312
+ self._pending[0],
313
+ )
314
+ self._pending.pop(0)
315
+ return timestamps
316
+
317
+ async def _get(self) -> typing.Any:
318
+ if self._stream is None:
319
+ self._stream = await self._slack.chat_stream(
320
+ channel=self._channel_id,
321
+ thread_ts=self._thread_ts,
322
+ **self._options,
323
+ )
324
+ self._started = time.monotonic()
325
+ return self._stream
326
+
327
+ async def _expired(self) -> bool:
328
+ if (
329
+ self._stream is None
330
+ or time.monotonic() - self._started < self._max_seconds
331
+ ):
332
+ return False
333
+ await self._stop()
334
+ return True
335
+
336
+ async def _stop(self) -> None:
337
+ # ``_stopped`` blocks new appends. ``_finalized`` is set only
338
+ # when the stop succeeds, so a failed stop can be tried again.
339
+ if self._finalized:
340
+ return
341
+ self._stopped = True
342
+ if self._stream is not None:
343
+ try:
344
+ await self._stream.stop(chunks=self._open_tasks() or None)
345
+ except errors.SlackApiError as error:
346
+ # Slack stops an idle stream itself. Then the stream is
347
+ # already final, so do not try to stop it again. Post
348
+ # the buffered text that Slack did not get as overflow.
349
+ if error.response.get('error') != _NOT_STREAMING:
350
+ raise
351
+ if self._unsent:
352
+ self._overflow.insert(0, self._unsent)
353
+ self._unsent = ''
354
+ self._finalized = True
355
+
356
+ def _open_tasks(self) -> list[dict[str, typing.Any]]:
357
+ return [
358
+ _task_chunk(
359
+ task_id, title, 'error', 'Stopped before this step finished.'
360
+ )
361
+ for task_id, (title, status) in self._tasks.items()
362
+ if status in ('pending', 'in_progress')
363
+ ]
364
+
365
+
366
+ def _task_chunk(
367
+ task_id: str,
368
+ title: str,
369
+ status: TaskStatus,
370
+ details: str | None = None,
371
+ output: str | None = None,
372
+ ) -> dict[str, typing.Any]:
373
+ """Return a ``task_update`` chunk. Empty fields are left out."""
374
+ chunk: dict[str, typing.Any] = {
375
+ 'type': 'task_update',
376
+ 'id': task_id,
377
+ 'title': title,
378
+ 'status': status,
379
+ }
380
+ if details:
381
+ chunk['details'] = details
382
+ if output:
383
+ chunk['output'] = output
384
+ return chunk
slackwright/stores.py ADDED
@@ -0,0 +1,150 @@
1
+ """Valkey and PostgreSQL form stores.
2
+
3
+ Install the backend with ``slackwright[valkey]`` or
4
+ ``slackwright[postgres]``. Each store uses a client or pool that the bot
5
+ already has, and never opens or closes connections itself.
6
+
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import typing
12
+
13
+ from slackwright import forms
14
+
15
+
16
+ class ValkeyFormStore:
17
+ """A :class:`~slackwright.forms.FormStore` in Valkey (or Redis).
18
+
19
+ Args:
20
+ client: A ``valkey.asyncio.Valkey`` (or ``redis.asyncio.Redis``)
21
+ client.
22
+ prefix: The prefix of every key.
23
+
24
+ Records and claims expire on their own after their TTL.
25
+
26
+ """
27
+
28
+ def __init__(
29
+ self, client: typing.Any, *, prefix: str = 'slackwright:form:'
30
+ ) -> None:
31
+ self._client = client
32
+ self._prefix = prefix
33
+
34
+ async def put(self, record: forms.FormRecord, ttl: int) -> None:
35
+ await self._client.set(
36
+ f'{self._prefix}{record.form_id}',
37
+ record.model_dump_json(),
38
+ ex=ttl,
39
+ )
40
+
41
+ async def get(self, form_id: str) -> forms.FormRecord | None:
42
+ data = await self._client.get(f'{self._prefix}{form_id}')
43
+ if data is None:
44
+ return None
45
+ return forms.FormRecord.model_validate_json(data)
46
+
47
+ async def claim(self, key: str, ttl: int) -> bool:
48
+ # Form IDs have no ':', so claim keys cannot clash with them.
49
+ return bool(
50
+ await self._client.set(
51
+ f'{self._prefix}claim:{key}', '1', nx=True, ex=ttl
52
+ )
53
+ )
54
+
55
+
56
+ class PostgresFormStore:
57
+ """A :class:`~slackwright.forms.FormStore` in PostgreSQL.
58
+
59
+ Args:
60
+ pool: A ``psycopg_pool.AsyncConnectionPool``.
61
+ forms_table: The table for form records.
62
+ claims_table: The table for claims.
63
+
64
+ Call :meth:`create_schema` once, and :meth:`purge_expired` on a
65
+ schedule to delete old rows. Expired rows are never returned.
66
+
67
+ """
68
+
69
+ def __init__(
70
+ self,
71
+ pool: typing.Any,
72
+ *,
73
+ forms_table: str = 'slackwright_forms',
74
+ claims_table: str = 'slackwright_form_claims',
75
+ ) -> None:
76
+ from psycopg import sql # optional dependency
77
+
78
+ self._pool = pool
79
+ self._sql = sql
80
+ self._forms = sql.Identifier(forms_table)
81
+ self._claims = sql.Identifier(claims_table)
82
+
83
+ async def create_schema(self) -> None:
84
+ """Create the two tables if they do not exist."""
85
+ sql = self._sql
86
+ async with self._pool.connection() as conn:
87
+ await conn.execute(
88
+ sql.SQL(
89
+ 'CREATE TABLE IF NOT EXISTS {} ('
90
+ 'form_id TEXT PRIMARY KEY, '
91
+ 'record JSONB NOT NULL, '
92
+ 'expires_at TIMESTAMPTZ NOT NULL)'
93
+ ).format(self._forms)
94
+ )
95
+ await conn.execute(
96
+ sql.SQL(
97
+ 'CREATE TABLE IF NOT EXISTS {} ('
98
+ 'claim_key TEXT PRIMARY KEY, '
99
+ 'expires_at TIMESTAMPTZ NOT NULL)'
100
+ ).format(self._claims)
101
+ )
102
+
103
+ async def put(self, record: forms.FormRecord, ttl: int) -> None:
104
+ query = self._sql.SQL(
105
+ 'INSERT INTO {} (form_id, record, expires_at) '
106
+ 'VALUES (%s, %s::jsonb, now() + make_interval(secs => %s)) '
107
+ 'ON CONFLICT (form_id) DO UPDATE '
108
+ 'SET record = EXCLUDED.record, expires_at = EXCLUDED.expires_at'
109
+ ).format(self._forms)
110
+ async with self._pool.connection() as conn:
111
+ await conn.execute(
112
+ query, (record.form_id, record.model_dump_json(), ttl)
113
+ )
114
+
115
+ async def get(self, form_id: str) -> forms.FormRecord | None:
116
+ query = self._sql.SQL(
117
+ 'SELECT record FROM {} WHERE form_id = %s AND expires_at > now()'
118
+ ).format(self._forms)
119
+ async with self._pool.connection() as conn:
120
+ cursor = await conn.execute(query, (form_id,))
121
+ row = await cursor.fetchone()
122
+ if row is None:
123
+ return None
124
+ return forms.FormRecord.model_validate(row[0])
125
+
126
+ async def claim(self, key: str, ttl: int) -> bool:
127
+ # An expired claim is replaced; a live claim is kept.
128
+ query = self._sql.SQL(
129
+ 'INSERT INTO {0} (claim_key, expires_at) '
130
+ 'VALUES (%s, now() + make_interval(secs => %s)) '
131
+ 'ON CONFLICT (claim_key) DO UPDATE '
132
+ 'SET expires_at = EXCLUDED.expires_at '
133
+ 'WHERE {0}.expires_at <= now()'
134
+ ).format(self._claims)
135
+ async with self._pool.connection() as conn:
136
+ cursor = await conn.execute(query, (key, ttl))
137
+ return bool(cursor.rowcount == 1)
138
+
139
+ async def purge_expired(self) -> int:
140
+ """Delete expired records and claims. Return the rows deleted."""
141
+ deleted = 0
142
+ async with self._pool.connection() as conn:
143
+ for table in (self._forms, self._claims):
144
+ cursor = await conn.execute(
145
+ self._sql.SQL(
146
+ 'DELETE FROM {} WHERE expires_at <= now()'
147
+ ).format(table)
148
+ )
149
+ deleted += cursor.rowcount
150
+ return deleted