agents-framework 0.3.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.
Files changed (50) hide show
  1. agents_framework-0.3.0.dist-info/METADATA +1364 -0
  2. agents_framework-0.3.0.dist-info/RECORD +50 -0
  3. agents_framework-0.3.0.dist-info/WHEEL +5 -0
  4. agents_framework-0.3.0.dist-info/entry_points.txt +2 -0
  5. agents_framework-0.3.0.dist-info/licenses/LICENSE +661 -0
  6. agents_framework-0.3.0.dist-info/top_level.txt +1 -0
  7. framework/__init__.py +0 -0
  8. framework/__main__.py +9 -0
  9. framework/action_page.py +1102 -0
  10. framework/approval_buttons.py +775 -0
  11. framework/approvals.py +678 -0
  12. framework/calendar_card.py +276 -0
  13. framework/cli.py +273 -0
  14. framework/codex_llm.py +401 -0
  15. framework/config.py +126 -0
  16. framework/drafter.py +263 -0
  17. framework/interfaces.py +96 -0
  18. framework/llm.py +744 -0
  19. framework/plugins/__init__.py +147 -0
  20. framework/plugins/agentmail_source.py +355 -0
  21. framework/plugins/approval_destination.py +478 -0
  22. framework/plugins/command_action.py +248 -0
  23. framework/plugins/digest_destination.py +546 -0
  24. framework/plugins/email_destination.py +248 -0
  25. framework/plugins/fanout_destination.py +160 -0
  26. framework/plugins/github_org_source.py +226 -0
  27. framework/plugins/github_releases_source.py +420 -0
  28. framework/plugins/ics_source.py +594 -0
  29. framework/plugins/llm_scorer.py +411 -0
  30. framework/plugins/multi_source.py +241 -0
  31. framework/plugins/reddit_source.py +625 -0
  32. framework/plugins/regex_scorer.py +93 -0
  33. framework/plugins/rss_source.py +346 -0
  34. framework/plugins/signal_destination.py +133 -0
  35. framework/plugins/slack_destination.py +461 -0
  36. framework/plugins/slack_draft_action.py +137 -0
  37. framework/plugins/slack_post_action.py +65 -0
  38. framework/plugins/slack_workspace_source.py +992 -0
  39. framework/plugins/twitter_action.py +210 -0
  40. framework/plugins/websearch_source.py +761 -0
  41. framework/plugins/wordpress_action.py +413 -0
  42. framework/proposals.py +246 -0
  43. framework/registry.py +166 -0
  44. framework/runlog.py +125 -0
  45. framework/runner.py +243 -0
  46. framework/schedule.py +571 -0
  47. framework/signal_messenger.py +1418 -0
  48. framework/slack.py +801 -0
  49. framework/state.py +39 -0
  50. framework/templating.py +76 -0
framework/slack.py ADDED
@@ -0,0 +1,801 @@
1
+ """Posting to a Slack incoming webhook: Markdown to mrkdwn, splitting, identity.
2
+
3
+ Every destination here writes Markdown — the models do, the sources do (Reddit
4
+ bodies are Markdown), and the code around them did too. Slack does not render
5
+ Markdown. It renders *mrkdwn*, which shares almost none of the syntax that
6
+ matters: no headings, a different link form, one asterisk for bold rather than
7
+ two. A real release-notes digest arrived reading `## skillz` and
8
+ `[v1.106.0](<url>)`, literally (issue #73).
9
+
10
+ So there is exactly one way out of this process to a webhook, `post_message`,
11
+ and it converts. Nothing above it decides whether to convert, which is why the
12
+ code that builds a header writes `**Title**` (Markdown) and not `*Title*`
13
+ (mrkdwn): the text handed to `post_message` is Markdown all the way down, and
14
+ what Slack receives is mrkdwn all the way down.
15
+
16
+ What `to_mrkdwn` does, per issue #73:
17
+
18
+ # H1 .. ###### H6 -> *text* on its own line (Slack has no headings)
19
+ [text](url) -> <url|text> (a <url> is unwrapped first)
20
+ ![alt](url) -> <url|alt>
21
+ <url> (autolink) -> <url>
22
+ bare url -> left alone (Slack links it)
23
+ ***bold italic*** -> *_bold italic_*
24
+ **bold** -> *bold*
25
+ __bold__, ___x___ -> left alone, on purpose (see below)
26
+ *italic*, _italic_ -> _italic_
27
+ \\*escaped\\* -> *escaped*, the backslash consumed, no emphasis
28
+ `code`, ``` blocks -> unchanged, and their content is never converted
29
+ - item, * item, 1. it -> bullet character, indent preserved
30
+ > quote -> unchanged, and the marker is never escaped
31
+ tables -> left as text
32
+ & < > -> &amp; &lt; &gt; in literal text
33
+
34
+ **`__bold__` is deliberately not converted**, though Markdown says it is. What
35
+ these agents actually emit is release notes and scorer reasons about code, where
36
+ `__init__`-style names are ordinary and nobody writes bold as `__bold__`. Turning
37
+ a dunder name into `*init*` in a message about that name is the more likely
38
+ mistake, so the underscore bold rule is gone on purpose: do not restore it as a
39
+ bug fix. `**bold**` still converts, and `_italic_` is unaffected.
40
+
41
+ **Emphasis only fires on word boundaries**, both for `*` and for `_`, which is
42
+ what keeps `https://example.com/a__b__c` and `snake_case_name` intact. A URL
43
+ that lost a pair of underscores to a bold rule is a different URL, and an
44
+ approved `slack-post` step templating `{url}` would then post a link the
45
+ operator never approved. Emphasis is resolved through placeholders in one pass
46
+ rather than by sequential substitution, because `**b**` -> `*b*` followed by an
47
+ italic rule would immediately turn that `*b*` back into `_b_`.
48
+
49
+ **`__x__` is deliberately not bold, though Markdown says it is.** Do not "fix"
50
+ this back. What goes through here is release notes and scorer reasons about
51
+ code, where `__init__`, `__main__` and `__all__` are ordinary words and a
52
+ double underscore almost never means emphasis; nobody writing for this channel
53
+ reaches for `__x__` when `**x**` is right there. So `**bold**` converts,
54
+ `__bold__` and `___bold___` pass through as written, and a name that arrives
55
+ without backticks survives instead of turning into `*init*`.
56
+
57
+ **Escaping** is Slack's documented rule for `text`: `&`, `<` and `>` become
58
+ entities so that content which happens to look like `<something>` is not read
59
+ as a channel, user or link reference. It is applied to literal text only —
60
+ never to a `<url|label>` this module built, never to a blockquote's `>` marker,
61
+ and never inside a code span or a fenced block, whose contents this module
62
+ leaves exactly as written. A `<url|label>` that arrives *already formatted*
63
+ is held aside the same way, because upstream content is full of them: a
64
+ scorer's reasons, a digest's prose and the slack-workspace source's own message
65
+ text all carry links a human already wrote in Slack's syntax, and escaping one
66
+ posts its markup instead of the link. The recogniser insists on a real scheme
67
+ in the URL half, so prose like `if a<b|c>d` is escaped as the text it is. A link's URL keeps its `&` escaped as well, and a
68
+ `|`, `<` or `>` inside a URL is percent-encoded, since mrkdwn's link syntax
69
+ splits on the first `|` and ends at the first `>`: without that, a URL holding
70
+ one silently produces a link pointing somewhere else.
71
+
72
+ **Splitting: several messages, not several blocks.** A Slack `text` may hold
73
+ 40000 characters but a `section` block caps at 3000, and a digest can exceed
74
+ either. This posts several messages in order instead of building a `blocks`
75
+ payload, for two reasons: the payload stays `{"text": ...}`, so a message that
76
+ needed neither conversion nor splitting is byte-identical to what this repo
77
+ posted before, and a reader scrolling a channel sees the parts in order with no
78
+ block-level truncation to notice. Splits land on a paragraph boundary where one
79
+ exists, then a line boundary, and only inside a line when a single line is
80
+ itself over the limit. A paragraph longer than the limit is handed to the line
81
+ pass whole rather than cut where the paragraph pass reached: a bullet list with
82
+ no blank line in it is one paragraph, and cutting it mid-word when every line
83
+ in it is short would be a worse split than the one available. A split that would land inside a fenced code block
84
+ closes the fence and reopens it in the next message, so no part renders as
85
+ broken code. Cutting inside a line cuts between **grapheme clusters**, never
86
+ between the code points of one: a ZWJ emoji split down the middle leaves a
87
+ bare figure at the end of one message and a stray joiner at the start of the
88
+ next, and a part that rejoins correctly but renders as garbage is still wrong.
89
+
90
+ **Parts are numbered** (`_(part 2 of 3)_` on its own line) whenever there is
91
+ more than one. The parts of one message are posted in order, but any other
92
+ agent sharing the webhook can post between them, and without the marker a
93
+ reader cannot tell a continuation from an unrelated message that landed in the
94
+ middle.
95
+
96
+ **Two transports** (issue #86). A destination names either `webhook_env`, an
97
+ incoming webhook, or `bot_token_env` plus `channel_id`, which posts through
98
+ `chat.postMessage`. Exactly one, and a block naming both or neither fails at
99
+ build time. Conversion, splitting, the footer, the part markers and blocks are
100
+ identical on both; the difference is what Slack does with them:
101
+
102
+ - **Identity actually works only on the API path.** `username` and
103
+ `icon_emoji` (issue #77) are ignored by a modern incoming webhook — the
104
+ post returns `ok` and the stored message has `username: None` — while
105
+ `chat.postMessage` honours them, given the bot's `chat:write.customize`
106
+ scope. The keys ride on the payload either way, since a webhook ignoring
107
+ them is not an error, but a deployment that wants two digests to look
108
+ different has to use a bot token.
109
+ - **Only the API path returns a message `ts`.** A webhook answers `ok` and
110
+ nothing else, which is why a proposal announced through one can never have
111
+ its buttons removed once it is resolved. `post_message` returns the `ts` of
112
+ every message it posted (empty on the webhook path), so a caller that keeps
113
+ one can edit that message later through `update_message`.
114
+
115
+ The `footer` (issue #64) is appended after conversion, verbatim, to *every*
116
+ message a split produces: it exists for a standing line that has to be on every
117
+ message, and a compliance line that lands only on the last of three parts is
118
+ not that.
119
+ """
120
+ from __future__ import annotations
121
+
122
+ import os
123
+ import re
124
+ import unicodedata
125
+
126
+ import requests
127
+
128
+ SLACK_API = "https://slack.com/api"
129
+ # Methods that write and therefore always take a JSON body, whatever this
130
+ # particular call happens to pass. `_needs_json_body` catches the rest.
131
+ _WRITE_METHODS = ("chat.postMessage", "chat.update", "chat.postEphemeral")
132
+
133
+ # A Slack section block holds 3000 characters; a message that would exceed one
134
+ # is posted as several messages (see the module docstring).
135
+ SLACK_BLOCK_LIMIT = 3000
136
+
137
+ # A `text` field may hold far more than a section block: it is what the blocks
138
+ # path uses for the notification fallback, which is not split.
139
+ SLACK_TEXT_LIMIT = 40000
140
+
141
+ # Room kept back for `_(part 12 of 34)_` plus its newline, so numbering a part
142
+ # can never push it over the limit.
143
+ _MARKER_ROOM = 24
144
+
145
+ # The longest footer that still leaves room for a message. A footer rides on
146
+ # every message, costing its length plus the newline before it, and a split
147
+ # message also carries a part marker. See `check_footer`.
148
+ MAX_FOOTER_CHARS = SLACK_BLOCK_LIMIT - _MARKER_ROOM - 2
149
+
150
+ BULLET = "•"
151
+ _ZWJ = "‍"
152
+
153
+ # Two marker characters, so the emphasis pass cannot restore a fragment the
154
+ # outer pass is still holding.
155
+ _HOLD_MARKS = ("\x00", "\x01")
156
+
157
+ _FENCE_RE = re.compile(r"^\s*```")
158
+ _HEADING_RE = re.compile(r"^\s{0,3}(#{1,6})\s+(.*?)\s*#*\s*$")
159
+ _LIST_RE = re.compile(r"^(\s*)(?:[-*+]|\d+[.)])\s+(.*)$")
160
+ _QUOTE_RE = re.compile(r"^(\s*>+\s?)(.*)$")
161
+ _CODE_SPAN_RE = re.compile(r"(`+[^`]*`+)")
162
+ _BACKSLASH_RE = re.compile(r"\\([\\`*_{}\[\]()#+\-.!>|~])")
163
+ _AUTOLINK_RE = re.compile(r"<((?:https?|mailto):[^<>\s]+)>")
164
+ # An already-formed mrkdwn link, `<url|label>`, as upstream content carries it.
165
+ # The URL half must be a real scheme, so prose like `if a<b|c>d` is not mistaken
166
+ # for one and quietly turned into a link.
167
+ _MRKDWN_LINK_RE = re.compile(r"<((?:https?://|mailto:|tel:)[^<>|\s]*)\|([^<>|]*)>")
168
+ # A label may hold one level of nested brackets; a URL may hold '>' and is
169
+ # taken whole, either bare or wrapped in angle brackets.
170
+ _LINK_RE = re.compile(
171
+ r"(!?)\[((?:[^\[\]]|\[[^\[\]]*\])*)\]\(\s*(?:<([^<>\s]*)>|([^()\s]+))(?:\s+\"[^\"]*\")?\s*\)"
172
+ )
173
+ _BOLD_ITALIC_RE = re.compile(r"(?<![\w*])\*\*\*(\S(?:.*?\S)?)\*\*\*(?![\w*])", re.S)
174
+ _BOLD_STAR_RE = re.compile(r"(?<![\w*])\*\*(\S(?:.*?\S)?)\*\*(?![\w*])", re.S)
175
+ _ITALIC_STAR_RE = re.compile(r"(?<![\w*])\*(\S(?:[^*\n]*\S)?)\*(?![\w*])")
176
+ # One underscore each side, never two: see "__x__ is left alone" in the module
177
+ # docstring. The inner guards keep `__x__` and `___x___` out entirely rather
178
+ # than letting the italic rule take a bite out of the ends.
179
+ _ITALIC_UNDER_RE = re.compile(r"(?<![\w_])_(?!_)(\S(?:[^_\n]*\S)?)_(?!_)(?![\w])")
180
+
181
+
182
+ _ENTITY_RE = re.compile(r"&(?!amp;|lt;|gt;|#\d+;|#x[0-9a-fA-F]+;)")
183
+
184
+
185
+ def _sender(transport: SlackTransport, identity: SlackIdentity | None) -> str:
186
+ """Who was posting and where, for a message that refuses to go out."""
187
+ where = f"channel {transport.channel_id}" if transport.can_edit else "an incoming webhook"
188
+ name = identity.username if identity and identity.username else ""
189
+ retval = f"{name} to {where}" if name else where
190
+ return retval
191
+
192
+
193
+ def _check_assembled(text: str, limit: int, sender: str) -> None:
194
+ """Refuse a message that is already over the limit, before posting it.
195
+
196
+ The last thing between this repo and the failure it keeps paying for:
197
+ Slack drops an over-long message without an error, so the run reports
198
+ success and the digest is simply not there. Every reservation this module
199
+ makes -- the footer's length and its newline, the part marker's width, the
200
+ join between paragraphs -- is arithmetic that can be wrong, and whatever
201
+ the next feature adds to a part is arithmetic nobody has written yet. This
202
+ measures the bytes instead of predicting them, so a slip anywhere becomes
203
+ a loud failure naming the size rather than a message nobody receives.
204
+ """
205
+ if len(text) > limit:
206
+ raise ValueError(
207
+ f"slack message from {sender} assembled to {len(text)} characters, over the "
208
+ f"{limit}-character limit; refusing to post a message Slack would drop"
209
+ )
210
+
211
+
212
+ def check_footer(footer: str, label: str = "slack footer") -> None:
213
+ """Refuse a footer that leaves no room for the message it rides on.
214
+
215
+ Every message carries the footer, so a footer within a part marker's width
216
+ of the limit turns a long body into a run of messages that are each over
217
+ the limit and each dropped by Slack: the run reports success and the digest
218
+ is simply not there. Checked where the config is read, so it fails before
219
+ the run has paid for an LLM call, and again at post time for a caller whose
220
+ footer comes from somewhere else.
221
+
222
+ The threshold sits two characters below the naive one because a footer
223
+ costs its own length *plus* the newline before it, and the part marker
224
+ claims the rest. `_check_assembled` is what backstops that arithmetic.
225
+ """
226
+ if len(footer) > MAX_FOOTER_CHARS:
227
+ raise ValueError(
228
+ f"{label} is {len(footer)} characters, which leaves no room for content "
229
+ f"under Slack's {SLACK_BLOCK_LIMIT}-character limit"
230
+ )
231
+
232
+
233
+ def _escape(text: str) -> str:
234
+ """Slack's three entities.
235
+
236
+ An `&` that already opens an entity is left alone: text written `&amp;`
237
+ means that entity, and escaping it again would put `&amp;amp;` in the
238
+ channel. Ampersands go first so the two angle brackets are not doubled.
239
+ """
240
+ retval = _ENTITY_RE.sub("&amp;", text)
241
+ retval = retval.replace("<", "&lt;").replace(">", "&gt;")
242
+ return retval
243
+
244
+
245
+ def _link_url(url: str) -> str:
246
+ """A URL safe inside `<url|label>`.
247
+
248
+ mrkdwn takes everything up to the first `|` as the URL and ends the link at
249
+ the first `>`, so both have to leave the URL as percent-encoding, and `&`
250
+ is escaped like any other ampersand Slack is given.
251
+ """
252
+ retval = url.replace("<", "%3C").replace(">", "%3E").replace("|", "%7C")
253
+ retval = _ENTITY_RE.sub("&amp;", retval)
254
+ return retval
255
+
256
+
257
+ class _Holder:
258
+ """Fragments already in their final form, kept out of later rules."""
259
+
260
+ def __init__(self, mark: str = _HOLD_MARKS[0]) -> None:
261
+ self.items: list[str] = []
262
+ self._mark = mark
263
+ self._pattern = re.compile(f"{re.escape(mark)}(\\d+){re.escape(mark)}")
264
+
265
+ def hold(self, text: str) -> str:
266
+ self.items.append(text)
267
+ retval = f"{self._mark}{len(self.items) - 1}{self._mark}"
268
+ return retval
269
+
270
+ def restore(self, text: str) -> str:
271
+ # A held fragment can itself hold one (a link label with a code span in
272
+ # it), so this runs until nothing is left to expand.
273
+ while self._pattern.search(text):
274
+ text = self._pattern.sub(lambda m: self.items[int(m.group(1))], text)
275
+ retval = text
276
+ return retval
277
+
278
+
279
+ def _emphasis(text: str) -> str:
280
+ """Bold and italic, resolved in one pass so neither rule sees the other's output."""
281
+ holder = _Holder(_HOLD_MARKS[1])
282
+
283
+ def bold_italic(match: re.Match) -> str:
284
+ retval = holder.hold(f"*_{match.group(1)}_*")
285
+ return retval
286
+
287
+ def bold(match: re.Match) -> str:
288
+ retval = holder.hold(f"*{match.group(1)}*")
289
+ return retval
290
+
291
+ def italic(match: re.Match) -> str:
292
+ retval = holder.hold(f"_{match.group(1)}_")
293
+ return retval
294
+
295
+ for pattern, repl in (
296
+ (_BOLD_ITALIC_RE, bold_italic),
297
+ (_BOLD_STAR_RE, bold),
298
+ (_ITALIC_STAR_RE, italic),
299
+ (_ITALIC_UNDER_RE, italic),
300
+ ):
301
+ text = pattern.sub(repl, text)
302
+ retval = holder.restore(text)
303
+ return retval
304
+
305
+
306
+ def _inline(text: str, holder: _Holder | None = None) -> str:
307
+ """Links, emphasis and escaping for one line of prose.
308
+
309
+ Code spans, backslash-escaped characters and finished links are held aside
310
+ the moment they are recognised, so no later rule touches their contents and
311
+ nothing this function builds is escaped twice.
312
+ """
313
+ own = holder is None
314
+ holder = holder or _Holder()
315
+
316
+ pieces = []
317
+ for piece in _CODE_SPAN_RE.split(text):
318
+ if piece.startswith("`"):
319
+ pieces.append(holder.hold(piece))
320
+ continue
321
+ pieces.append(piece)
322
+ text = "".join(pieces)
323
+
324
+ # A `<url|label>` that arrived already formatted is held whole, before any
325
+ # escaping can turn its angle brackets into entities. Upstream content is
326
+ # where these come from: a scorer's reasons, a digest's prose, and the
327
+ # slack-workspace source's own message text all carry them.
328
+ text = _MRKDWN_LINK_RE.sub(
329
+ lambda m: holder.hold(f"<{_link_url(m.group(1))}|{_escape(m.group(2))}>"), text
330
+ )
331
+ text = _BACKSLASH_RE.sub(lambda m: holder.hold(_escape(m.group(1))), text)
332
+
333
+ def link(match: re.Match) -> str:
334
+ label = match.group(2)
335
+ url = match.group(3) if match.group(3) is not None else match.group(4)
336
+ rendered = _inline(label, holder) if label else ""
337
+ if rendered:
338
+ retval = holder.hold(f"<{_link_url(url)}|{rendered}>")
339
+ else:
340
+ retval = holder.hold(f"<{_link_url(url)}>")
341
+ return retval
342
+
343
+ # Links before autolinks: `[title](<url>)` holds its own angle brackets, and
344
+ # an autolink rule that ran first would have turned that URL into a nested
345
+ # link inside the link.
346
+ text = _LINK_RE.sub(link, text)
347
+ text = _AUTOLINK_RE.sub(lambda m: holder.hold(f"<{_link_url(m.group(1))}>"), text)
348
+ text = _emphasis(text)
349
+ text = _escape(text)
350
+ if own:
351
+ text = holder.restore(text)
352
+ retval = text
353
+ return retval
354
+
355
+
356
+ def to_mrkdwn(text: str) -> str:
357
+ """Render Markdown as Slack mrkdwn. See the module docstring for the table."""
358
+ lines = []
359
+ in_fence = False
360
+ for line in text.split("\n"):
361
+ if _FENCE_RE.match(line):
362
+ in_fence = not in_fence
363
+ lines.append(line)
364
+ continue
365
+ if in_fence:
366
+ lines.append(line)
367
+ continue
368
+ heading = _HEADING_RE.match(line)
369
+ if heading and heading.group(2):
370
+ lines.append(_inline(f"**{heading.group(2)}**"))
371
+ continue
372
+ item = _LIST_RE.match(line)
373
+ if item:
374
+ lines.append(f"{item.group(1)}{BULLET} {_inline(item.group(2))}")
375
+ continue
376
+ quote = _QUOTE_RE.match(line)
377
+ if quote:
378
+ lines.append(f"{quote.group(1)}{_inline(quote.group(2))}")
379
+ continue
380
+ lines.append(_inline(line))
381
+ retval = "\n".join(lines)
382
+ return retval
383
+
384
+
385
+ def _joins(previous: str, char: str) -> bool:
386
+ """Does `char` continue the grapheme cluster ending in `previous`?
387
+
388
+ An approximation of UAX #29 covering what actually turns up in a digest:
389
+ combining marks, ZWJ sequences (family and profession emoji), variation
390
+ selectors, skin-tone modifiers, keycaps and regional-indicator flag pairs.
391
+ Python's `re` has no `\\X`, and this is not worth a new dependency.
392
+ """
393
+ if unicodedata.combining(char) or unicodedata.category(char) in ("Mn", "Me", "Mc"):
394
+ retval = True
395
+ return retval
396
+ if char == _ZWJ or previous.endswith(_ZWJ):
397
+ retval = True
398
+ return retval
399
+ if char in ("︎", "️", "⃣"):
400
+ retval = True
401
+ return retval
402
+ if "\U0001f3fb" <= char <= "\U0001f3ff":
403
+ retval = True
404
+ return retval
405
+ regional = "\U0001f1e6" <= char <= "\U0001f1ff"
406
+ retval = regional and len(previous) == 1 and "\U0001f1e6" <= previous <= "\U0001f1ff"
407
+ return retval
408
+
409
+
410
+ def _graphemes(text: str) -> list[str]:
411
+ retval: list[str] = []
412
+ for char in text:
413
+ if retval and _joins(retval[-1], char):
414
+ retval[-1] += char
415
+ continue
416
+ retval.append(char)
417
+ return retval
418
+
419
+
420
+ def _hard_split(line: str, limit: int) -> list[str]:
421
+ """Cut one over-long line, between grapheme clusters."""
422
+ retval: list[str] = []
423
+ current = ""
424
+ for cluster in _graphemes(line):
425
+ if len(current) + len(cluster) > limit and current:
426
+ retval.append(current)
427
+ current = ""
428
+ current += cluster
429
+ if current:
430
+ retval.append(current)
431
+ return retval
432
+
433
+
434
+ def _pack(pieces: list[str], joiner: str, limit: int) -> list[str]:
435
+ """Greedily fill messages with `pieces`, joined by `joiner`.
436
+
437
+ A single piece over the limit is cut between grapheme clusters: this runs
438
+ on lines, where there is no finer boundary left to prefer.
439
+ """
440
+ retval: list[str] = []
441
+ current = ""
442
+ for piece in pieces:
443
+ candidate = f"{current}{joiner}{piece}" if current else piece
444
+ if len(candidate) <= limit:
445
+ current = candidate
446
+ continue
447
+ if current:
448
+ retval.append(current)
449
+ if len(piece) <= limit:
450
+ current = piece
451
+ continue
452
+ chunks = _hard_split(piece, limit)
453
+ retval.extend(chunks[:-1])
454
+ current = chunks[-1]
455
+ if current:
456
+ retval.append(current)
457
+ return retval
458
+
459
+
460
+ def _close_fences(parts: list[str]) -> list[str]:
461
+ """Reopen a fenced block that a split left open, so no part renders broken."""
462
+ retval = []
463
+ for i, part in enumerate(parts):
464
+ opened = sum(1 for line in part.split("\n") if _FENCE_RE.match(line)) % 2 == 1
465
+ if opened and i + 1 < len(parts):
466
+ part += "\n```"
467
+ parts[i + 1] = "```\n" + parts[i + 1]
468
+ retval.append(part)
469
+ return retval
470
+
471
+
472
+ def split_for_slack(text: str, limit: int = SLACK_BLOCK_LIMIT) -> list[str]:
473
+ """Split `text` into messages of at most `limit` characters, in order.
474
+
475
+ Paragraph boundaries first, then line boundaries, then inside a line (on a
476
+ grapheme boundary) only when one line is itself longer than the limit.
477
+ Never truncates.
478
+ """
479
+ if len(text) <= limit:
480
+ retval = [text]
481
+ return retval
482
+ # A part that ends inside a fenced block grows by the closing fence, and
483
+ # the part after it by the reopening one, so a text with fences is packed
484
+ # to a smaller limit and still fits once `_close_fences` has run.
485
+ fenced = any(_FENCE_RE.match(line) for line in text.split("\n"))
486
+ room = limit - 8 if fenced else limit
487
+ parts: list[str] = []
488
+ current = ""
489
+ for paragraph in text.split("\n\n"):
490
+ candidate = f"{current}\n\n{paragraph}" if current else paragraph
491
+ if len(candidate) <= room:
492
+ current = candidate
493
+ continue
494
+ if current:
495
+ parts.append(current)
496
+ current = ""
497
+ if len(paragraph) <= room:
498
+ current = paragraph
499
+ continue
500
+ # Too long on its own: try its line boundaries before cutting inside a
501
+ # line. Its last piece stays open, so the paragraph after it can still
502
+ # share that message rather than starting a nearly empty one.
503
+ chunks = _pack(paragraph.split("\n"), "\n", room)
504
+ parts.extend(chunks[:-1])
505
+ current = chunks[-1]
506
+ if current:
507
+ parts.append(current)
508
+ retval = _close_fences(parts)
509
+ return retval
510
+
511
+
512
+ def _numbered(parts: list[str]) -> list[str]:
513
+ total = len(parts)
514
+ retval = [f"{part}\n_(part {i} of {total})_" for i, part in enumerate(parts, 1)]
515
+ return retval
516
+
517
+
518
+ class SlackIdentity:
519
+ """Per-agent `username` / `icon_emoji` / `icon_url` for webhook posts (issue #77)."""
520
+
521
+ def __init__(self, username: str = "", icon_emoji: str = "", icon_url: str = ""):
522
+ self.username = username
523
+ self.icon_emoji = icon_emoji
524
+ self.icon_url = icon_url
525
+
526
+ def payload(self) -> dict:
527
+ retval = {}
528
+ if self.username:
529
+ retval["username"] = self.username
530
+ if self.icon_emoji:
531
+ retval["icon_emoji"] = self.icon_emoji
532
+ if self.icon_url:
533
+ retval["icon_url"] = self.icon_url
534
+ return retval
535
+
536
+
537
+ def identity_from_config(cfg: dict, label: str, default: SlackIdentity | None = None) -> SlackIdentity:
538
+ """Read the identity keys from a destination or route block.
539
+
540
+ A key absent here falls back to `default` (the destination-level identity
541
+ for a route). `icon_emoji` must be written with its colons, since that is
542
+ what Slack accepts and `rocket` instead of `:rocket:` posts no icon at all
543
+ and says nothing about why.
544
+ """
545
+ base = default or SlackIdentity()
546
+ values = {
547
+ "username": cfg.get("username", base.username),
548
+ "icon_emoji": cfg.get("icon_emoji", base.icon_emoji),
549
+ "icon_url": cfg.get("icon_url", base.icon_url),
550
+ }
551
+ for key, value in values.items():
552
+ if not isinstance(value, str):
553
+ raise ValueError(f"{label} '{key}' must be a string, got {value!r}")
554
+ emoji = values["icon_emoji"]
555
+ if emoji and not (emoji.startswith(":") and emoji.endswith(":") and len(emoji) > 2):
556
+ raise ValueError(
557
+ f"{label} 'icon_emoji' must be written with colons, like ':rocket:', got {emoji!r}"
558
+ )
559
+ if values["icon_emoji"] and values["icon_url"]:
560
+ raise ValueError(
561
+ f"{label} sets both 'icon_emoji' and 'icon_url'; Slack honours one, so set one"
562
+ )
563
+ retval = SlackIdentity(**values)
564
+ return retval
565
+
566
+
567
+ class SlackApiError(RuntimeError):
568
+ """Slack answered, but with `ok: false`."""
569
+
570
+
571
+ def _needs_json_body(params: dict) -> bool:
572
+ """Whether these params have to go as a JSON body rather than a query string.
573
+
574
+ The rule is the shape of the payload, not a list of method names. A param
575
+ that is a list or a dict (`blocks`, `attachments`) cannot survive a query
576
+ string: `requests` flattens a list of dicts into one repeated key per dict
577
+ *key*, so `blocks=[{"type": "section", "text": {...}}]` goes out as
578
+ `blocks=type&blocks=text` and the message arrives with every block gone.
579
+ """
580
+ retval = any(isinstance(value, (list, dict)) for value in params.values())
581
+ return retval
582
+
583
+
584
+ def slack_call(method: str, token: str, timeout: int, **params) -> dict:
585
+ """One Web API call, raising `SlackApiError` on `ok: false`.
586
+
587
+ A write, or any call carrying a list or dict, goes as a JSON body; the
588
+ rest as a query string. Nothing here logs: the token is in the header and
589
+ the params are the message itself.
590
+ """
591
+ if method in _WRITE_METHODS or _needs_json_body(params):
592
+ resp = requests.post(
593
+ f"{SLACK_API}/{method}",
594
+ headers={"Authorization": f"Bearer {token}", "Content-Type": "application/json"},
595
+ json=params,
596
+ timeout=timeout,
597
+ )
598
+ else:
599
+ resp = requests.get(
600
+ f"{SLACK_API}/{method}",
601
+ headers={"Authorization": f"Bearer {token}"},
602
+ params=params,
603
+ timeout=timeout,
604
+ )
605
+ resp.raise_for_status()
606
+ body = resp.json()
607
+ if not isinstance(body, dict) or not body.get("ok"):
608
+ error = body.get("error") if isinstance(body, dict) else "unreadable response"
609
+ raise SlackApiError(f"{method}: {error}")
610
+ retval = body
611
+ return retval
612
+
613
+
614
+ class SlackTransport:
615
+ """Where a message goes: an incoming webhook, or `chat.postMessage`.
616
+
617
+ `post()` takes the finished payload and returns the message `ts`, which is
618
+ `""` on the webhook path because Slack does not send one back. `can_edit`
619
+ says which kind this is, so a caller can decide what to promise a human
620
+ (buttons that will be tidied up, or buttons that cannot be).
621
+ """
622
+
623
+ def __init__(
624
+ self,
625
+ webhook_url: str = "",
626
+ bot_token: str = "",
627
+ channel_id: str = "",
628
+ timeout: int = 30,
629
+ ):
630
+ self.webhook_url = webhook_url
631
+ self.bot_token = bot_token
632
+ self.channel_id = channel_id
633
+ self.timeout = timeout
634
+
635
+ @property
636
+ def can_edit(self) -> bool:
637
+ retval = bool(self.bot_token)
638
+ return retval
639
+
640
+ def post(self, payload: dict) -> str:
641
+ if not self.bot_token:
642
+ resp = requests.post(
643
+ self.webhook_url,
644
+ json=payload,
645
+ headers={"Content-type": "application/json"},
646
+ timeout=self.timeout,
647
+ )
648
+ resp.raise_for_status()
649
+ retval = ""
650
+ return retval
651
+ body = slack_call(
652
+ "chat.postMessage", self.bot_token, self.timeout, channel=self.channel_id, **payload
653
+ )
654
+ retval = str(body.get("ts") or "")
655
+ return retval
656
+
657
+ def update(self, ts: str, payload: dict, timeout: int | None = None) -> None:
658
+ """Edit a message this transport posted. API path only.
659
+
660
+ A webhook transport raises rather than doing nothing: a caller only
661
+ reaches here holding a stored `ts`, which only the API path ever
662
+ produces, so arriving with a webhook is a bug and a message that
663
+ silently keeps its buttons is the worst way to learn about it.
664
+ """
665
+ if not self.can_edit:
666
+ raise RuntimeError(
667
+ "slack transport: a message posted through an incoming webhook has no ts "
668
+ "and cannot be edited; configure 'bot_token_env' and 'channel_id' instead"
669
+ )
670
+ slack_call(
671
+ "chat.update",
672
+ self.bot_token,
673
+ timeout if timeout is not None else self.timeout,
674
+ channel=self.channel_id,
675
+ ts=ts,
676
+ **payload,
677
+ )
678
+
679
+
680
+ def transport_from_config(cfg: dict, label: str, timeout: int = 30) -> SlackTransport:
681
+ """Build the transport a destination or route block asks for.
682
+
683
+ Exactly one of `webhook_env` or `bot_token_env` + `channel_id`. Naming both
684
+ is refused rather than resolved by precedence: the two differ in whether
685
+ `username` is honoured and whether a message can be edited later, so a
686
+ config that names both is a question, not a preference.
687
+ """
688
+ webhook_env = cfg.get("webhook_env")
689
+ token_env = cfg.get("bot_token_env")
690
+ if webhook_env and token_env:
691
+ raise ValueError(
692
+ f"{label} names both 'webhook_env' and 'bot_token_env'; set one. A bot token "
693
+ "posts through chat.postMessage, which honours 'username'/'icon_emoji' and "
694
+ "returns a message ts; an incoming webhook does neither"
695
+ )
696
+ if not webhook_env and not token_env:
697
+ raise RuntimeError(
698
+ f"{label} needs either a 'webhook_env' or a 'bot_token_env' with a 'channel_id'"
699
+ )
700
+ if webhook_env:
701
+ webhook_url = os.environ.get(webhook_env)
702
+ if not webhook_url:
703
+ raise RuntimeError(f"{label} needs the webhook URL in ${webhook_env}")
704
+ retval = SlackTransport(webhook_url=webhook_url, timeout=timeout)
705
+ return retval
706
+ bot_token = os.environ.get(token_env)
707
+ if not bot_token:
708
+ raise RuntimeError(f"{label} needs the bot token in ${token_env}")
709
+ channel_id = cfg.get("channel_id")
710
+ if not channel_id or not isinstance(channel_id, str):
711
+ raise RuntimeError(
712
+ f"{label} needs a 'channel_id' next to 'bot_token_env' (a webhook carries its own "
713
+ "channel, chat.postMessage does not)"
714
+ )
715
+ retval = SlackTransport(bot_token=bot_token, channel_id=channel_id, timeout=timeout)
716
+ return retval
717
+
718
+
719
+ def _as_transport(target: SlackTransport | str, timeout: int) -> SlackTransport:
720
+ if isinstance(target, SlackTransport):
721
+ retval = target
722
+ return retval
723
+ retval = SlackTransport(webhook_url=target, timeout=timeout)
724
+ return retval
725
+
726
+
727
+ def post_message(
728
+ target: SlackTransport | str,
729
+ text: str,
730
+ timeout: int = 30,
731
+ footer: str = "",
732
+ identity: SlackIdentity | None = None,
733
+ blocks: list | None = None,
734
+ ) -> list[str]:
735
+ """Convert `text` to mrkdwn and post it, split into several messages if long.
736
+
737
+ The single way out of this process to Slack. `target` is a `SlackTransport`
738
+ or, for a caller that has only ever had one, a webhook URL. `footer` is
739
+ appended verbatim, after conversion, to every message posted, and a message
740
+ that had to be split carries a part marker. Returns the `ts` of each message
741
+ posted, which is empty strings on the webhook path.
742
+
743
+ `blocks` posts one message carrying them, with the converted text as the
744
+ notification fallback and no splitting, because blocks carry their own
745
+ length handling.
746
+
747
+ Every payload is measured immediately before it goes out and refused if it
748
+ is over the limit: see `_check_assembled` for why that is worth one
749
+ comparison per message.
750
+ """
751
+ transport = _as_transport(target, timeout)
752
+ body = to_mrkdwn(text)
753
+ check_footer(footer)
754
+ limit = SLACK_BLOCK_LIMIT - (len(footer) + 1 if footer else 0)
755
+ extra = identity.payload() if identity else {}
756
+ sender = _sender(transport, identity)
757
+ if blocks is not None:
758
+ payload = {"text": f"{body}\n{footer}" if footer else body, "blocks": blocks}
759
+ payload.update(extra)
760
+ # The blocks carry the content; this `text` is the notification
761
+ # fallback, which is not split and is held to the `text` limit rather
762
+ # than a block's.
763
+ _check_assembled(payload["text"], SLACK_TEXT_LIMIT, sender)
764
+ retval = [transport.post(payload)]
765
+ return retval
766
+ parts = split_for_slack(body, limit)
767
+ if len(parts) > 1:
768
+ # Numbering costs characters, so the split is redone with room for it
769
+ # rather than letting a marker push the last part over the limit.
770
+ parts = _numbered(split_for_slack(body, limit - _MARKER_ROOM))
771
+ retval = []
772
+ for part in parts:
773
+ payload = {"text": f"{part}\n{footer}" if footer else part}
774
+ payload.update(extra)
775
+ _check_assembled(payload["text"], SLACK_BLOCK_LIMIT, sender)
776
+ retval.append(transport.post(payload))
777
+ return retval
778
+
779
+
780
+ def update_message(
781
+ transport: SlackTransport,
782
+ ts: str,
783
+ text: str = "",
784
+ blocks: list | None = None,
785
+ identity: SlackIdentity | None = None,
786
+ timeout: int | None = None,
787
+ ) -> None:
788
+ """Replace a posted message's text (and blocks) in place.
789
+
790
+ `blocks=[]` removes them, which is how a resolved proposal loses its
791
+ buttons. `text` is converted like any other message. The call always goes
792
+ as a JSON body (`chat.update` is a write), because `blocks` flattened into
793
+ a query string arrives as `blocks=type&blocks=text` and the message loses
794
+ every block without saying so.
795
+ """
796
+ payload: dict = {"text": to_mrkdwn(text)}
797
+ if blocks is not None:
798
+ payload["blocks"] = blocks
799
+ if identity:
800
+ payload.update(identity.payload())
801
+ transport.update(ts, payload, timeout)