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
@@ -0,0 +1,1418 @@
1
+ """Signal (the messenger) transport and renderer — the counterpart of `slack.py`.
2
+
3
+ Everything this repo sends to Signal goes through `post_message` here, which
4
+ converts Markdown to Signal's own text styles on the way out and splits a long
5
+ message, exactly as `framework/slack.py` does for Slack's mrkdwn. Code that
6
+ builds a message writes Markdown; there is one place that renders it, per
7
+ platform.
8
+
9
+ ## Why a subprocess, and why our own account
10
+
11
+ One process owns a Signal account at a time: `signal-cli`'s daemon holds it,
12
+ and a second invocation cannot open it concurrently. That is the same shape as
13
+ "one Socket Mode consumer per Slack app" in the README, and it decides the
14
+ architecture. An agent therefore talks to an account *this deployment owns*,
15
+ through the `signal-cli` binary, rather than borrowing a conversational agent's
16
+ account and depending on its relay.
17
+
18
+ Which dependency applies follows the transport. `signal-cli` needs no Python
19
+ package -- the dependency is the binary, whose presence on PATH is checked when
20
+ that transport is built, and that is all that is checked there. The gateway
21
+ transport needs no binary and uses `requests`, which this repo already
22
+ depends on, and it checks a good deal more before a run starts: the URL's
23
+ scheme, `wait_s` against the gateway's cap and against the HTTP timeout, the
24
+ label's length, and the token file's mode and kind. An account that is
25
+ not registered, or a group id this account is not a member of, costs a
26
+ subprocess and the account lock to verify, so it is left to fail on the first
27
+ send rather than on every run that sends nothing.
28
+
29
+ ## Signal has no markup, it has ranges
30
+
31
+ Slack takes marked-up text. Signal takes **plain text plus a list of styled
32
+ ranges**, passed as `--text-style start:length:STYLE`. So `to_signal()` returns
33
+ both: the text with every marker removed, and the ranges that reproduce them.
34
+
35
+ Two consequences shaped the code:
36
+
37
+ - **Two units, each with one job.** Offsets are UTF-16 code units, which
38
+ signal-cli's own help says in capitals: an emoji is two units, so a message
39
+ with one emoji before a bold word would bold the wrong letters if offsets
40
+ were counted in Python characters. The *limit*, though, is 2000 UTF-8
41
+ **bytes** -- `ServiceConfig.MAX_MESSAGE_SIZE_BYTES`, tested in `ManagerImpl`
42
+ as `Utf8.size(messageText()) > MAX_MESSAGE_SIZE_BYTES`. So `_units` counts
43
+ offsets and `_bytes` counts capacity, and no function mixes them: in `_cut`
44
+ the fit test is bytes while the offset it carries is units. Counting
45
+ capacity in units instead under-counts every non-ASCII character -- the
46
+ bullet this file writes is one unit and three bytes -- and signal-cli does
47
+ not refuse the result, it truncates the text and attaches the tail as a
48
+ file, so the mistake arrives as a mangled message rather than an error.
49
+ - **A range cannot be reopened across messages.** So a long message is
50
+ rendered *once*, and the text and its ranges are split together: a bold span
51
+ that straddles a part boundary becomes a bold range at the end of one part
52
+ and another at the start of the next. Splitting the Markdown first would have
53
+ been simpler and cuts a `**` in half when a single line is longer than the
54
+ limit, leaving the markers visible and the span unstyled.
55
+
56
+ The styles Signal accepts are BOLD, ITALIC, STRIKETHROUGH, MONOSPACE and
57
+ SPOILER — verified against signal-cli 0.14.9, which rejects anything else with
58
+ `Invalid style: <name>`. There is no link style: Signal linkifies bare URLs
59
+ itself, so `[label](url)` renders as `label (url)` and the URL stays visible.
60
+ Headings become bold lines and list markers become bullets, the same choices
61
+ `slack.py` makes for the same reason.
62
+
63
+ `__x__` is deliberately not bold, matching `slack.py`: what this repo posts is
64
+ full of `__init__`, and `**bold**` is how anyone here writes bold.
65
+
66
+ A footer is appended after the conversion and never rendered, which is the
67
+ contract `slack.py` states: a standing compliance line means the characters it
68
+ was written with.
69
+ """
70
+ from __future__ import annotations
71
+
72
+ import errno
73
+ import hashlib
74
+ import json
75
+ import os
76
+ import re
77
+ import shutil
78
+ import stat
79
+ import subprocess
80
+ import sys
81
+ from time import time
82
+ from typing import Protocol
83
+
84
+ import requests
85
+
86
+ # Signal's own per-message limit, in UTF-8 bytes. A longer message is split
87
+ # into several, in order, the way `slack.py` splits on its block limit. Not
88
+ # UTF-16 units: signal-cli measures `Utf8.size` against this number, and past
89
+ # it splits the text itself and attaches the remainder, which is a success as
90
+ # far as the send is concerned and a truncated message as far as a reader is.
91
+ SIGNAL_MESSAGE_LIMIT = 2000
92
+
93
+ BULLET = "•"
94
+
95
+ # Room kept back for `(part 12 of 34)` plus its newline, so numbering a part
96
+ # can never push it over the limit. The same reservation `slack.py` makes. The
97
+ # marker is ASCII, so its width is the same number of bytes as characters.
98
+ _MARKER_ROOM = 24
99
+
100
+ # The longest label the gateway may be prefixing. "Leads: " is seven bytes;
101
+ # this is room for a name, not for content. See `_gateway_from_config` for
102
+ # what an unbounded one does to the splitter.
103
+ _MAX_LABEL_BYTES = 64
104
+
105
+ # How much longer than the gateway's own wait the HTTP timeout has to be. A
106
+ # gateway that answers a moment after its deadline must still be heard: the
107
+ # answer at that moment is a 202, and losing it to a socket timeout turns a
108
+ # message in flight into one the caller is told was refused.
109
+ _WAIT_MARGIN = 5
110
+
111
+ # Every status a gateway 200 can carry, all of which mean the message left:
112
+ # a retry that arrives after Signal has acked sees `delivered` or `read`, and
113
+ # `deleted` is a message that went out and was then deleted. Anything outside
114
+ # this set is a word this version has not been told the meaning of, and
115
+ # guessing at one would either lose a message or send it twice.
116
+ _GATEWAY_SENT = frozenset({"sent", "delivered", "read", "deleted"})
117
+
118
+ # Statuses a 200 can carry that mean the message has not left yet. The
119
+ # gateway returns 202 while a send is in flight, so these arrive only from a
120
+ # build that does not implement the `wait_s` this transport asks for -- its
121
+ # published schema allows `queued` on a 200 and an older deployment answered
122
+ # that way.
123
+ #
124
+ # They are not treated as pending, which is the thing to understand here. The
125
+ # gateway writes its idempotency entry when it accepts the message, with the
126
+ # status it has at that moment, and only the `wait_s` poll loop ever reports a
127
+ # later one -- the stored entry keeps saying `queued` forever. So on a build
128
+ # without that loop, every resubmit of this key replays the same `queued` and
129
+ # pending would never resolve: the run would fail on every schedule for the
130
+ # whole TTL, over a message that was very likely delivered on the first
131
+ # attempt, and then post a second copy once the key expired. A hard failure
132
+ # naming the cause is the honest answer, because the fix is a gateway build
133
+ # and no amount of retrying substitutes for it.
134
+ _GATEWAY_PENDING = frozenset({"queued"})
135
+
136
+ # `failed` on a 200 would contradict the status code, but the gateway's
137
+ # published enum allows it and the honest reading is the status, not the code:
138
+ # a message the gateway says failed did not go out. Kept separate from the
139
+ # unknown-status path so the error says what happened rather than that this
140
+ # version cannot tell.
141
+ _GATEWAY_FAILED = frozenset({"failed"})
142
+
143
+ # `received` belongs to an inbound message and should never come back from a
144
+ # send. If it does, the message exists and has not been sent, which is the
145
+ # same position as `queued` -- and the same frozen-entry problem, so it is
146
+ # read the same way rather than as something this version has not been told.
147
+ _GATEWAY_INBOUND = frozenset({"received"})
148
+
149
+ # Every status the gateway's published enum declares, for the error that says
150
+ # what this version understands.
151
+ _known = sorted(_GATEWAY_SENT | _GATEWAY_PENDING | _GATEWAY_FAILED | _GATEWAY_INBOUND)
152
+
153
+ BOLD = "BOLD"
154
+ ITALIC = "ITALIC"
155
+ STRIKETHROUGH = "STRIKETHROUGH"
156
+ MONOSPACE = "MONOSPACE"
157
+ SPOILER = "SPOILER"
158
+
159
+ _FENCE_RE = re.compile(r"^\s*```")
160
+ _HEADING_RE = re.compile(r"^\s{0,3}(#{1,6})\s+(.*?)\s*#*\s*$")
161
+ _LIST_RE = re.compile(r"^(\s*)(?:[-*+]|\d+[.)])\s+(.*)$")
162
+
163
+ _ESCAPE_RE = re.compile(r"\\([\\`*_{}\[\]()#+\-.!>|~])")
164
+ _CODE_SPAN_RE = re.compile(r"`+([^`]*)`+")
165
+ _LINK_RE = re.compile(
166
+ r"!?\[((?:[^\[\]]|\[[^\[\]]*\])*)\]\(\s*(?:<([^<>\s]*)>|([^()\s]+))(?:\s+\"[^\"]*\")?\s*\)"
167
+ )
168
+ _AUTOLINK_RE = re.compile(r"<((?:https?|mailto):[^<>\s]+)>")
169
+ _BOLD_ITALIC_RE = re.compile(r"(?<![\w*])\*\*\*(\S(?:.*?\S)?)\*\*\*(?![\w*])", re.S)
170
+ _BOLD_RE = re.compile(r"(?<![\w*])\*\*(\S(?:.*?\S)?)\*\*(?![\w*])", re.S)
171
+ _STRIKE_RE = re.compile(r"~~(\S(?:.*?\S)?)~~", re.S)
172
+ _SPOILER_RE = re.compile(r"\|\|(\S(?:.*?\S)?)\|\|", re.S)
173
+ _ITALIC_STAR_RE = re.compile(r"(?<![\w*])\*(\S(?:[^*\n]*\S)?)\*(?![\w*])")
174
+ # One underscore each side, never two. See the module docstring.
175
+ _ITALIC_UNDER_RE = re.compile(r"(?<![\w_])_(?!_)(\S(?:[^_\n]*\S)?)_(?!_)(?![\w])")
176
+
177
+ # Anything that looks like a phone number, for the scrubber. signal-cli reports
178
+ # a failed send to a group by naming the member it could not reach.
179
+ _NUMBER_RE = re.compile(r"\+\d{7,15}")
180
+
181
+ # Tried in order at each position; the earliest match in the line wins, and a
182
+ # tie goes to the pattern listed first. A backslash escape comes first so that
183
+ # `\*literal\*` is neither emphasised nor left with its backslashes: the escape
184
+ # consumes both markers before any emphasis rule can pair them. Code spans and
185
+ # links come next so that `*` inside a URL or a code span is left alone.
186
+ _INLINE_RULES: tuple[tuple[re.Pattern[str], str | None], ...] = (
187
+ (_ESCAPE_RE, None),
188
+ (_CODE_SPAN_RE, MONOSPACE),
189
+ (_LINK_RE, None),
190
+ (_AUTOLINK_RE, None),
191
+ (_BOLD_ITALIC_RE, "BOLD+ITALIC"),
192
+ (_BOLD_RE, BOLD),
193
+ (_STRIKE_RE, STRIKETHROUGH),
194
+ (_SPOILER_RE, SPOILER),
195
+ (_ITALIC_STAR_RE, ITALIC),
196
+ (_ITALIC_UNDER_RE, ITALIC),
197
+ )
198
+
199
+ # A match whose content is re-scanned for nested markup. A code span is not in
200
+ # this set: inside one, markers are literal text.
201
+ _RECURSIVE = frozenset({"BOLD+ITALIC", BOLD, STRIKETHROUGH, SPOILER, ITALIC})
202
+
203
+
204
+ class SignalSendError(RuntimeError):
205
+ """A Signal message did not go out. Nothing downstream may mark it sent."""
206
+
207
+
208
+ class SignalCliError(SignalSendError):
209
+ """signal-cli refused or failed. The message carries its stderr, scrubbed."""
210
+
211
+
212
+ class SignalGatewayError(SignalSendError):
213
+ """The gateway refused the send, or could not be reached."""
214
+
215
+
216
+ class SignalSendPending(SignalSendError):
217
+ """The gateway accepted the message and Signal had not taken it yet.
218
+
219
+ A sibling of `SignalGatewayError` rather than a kind of it, because the
220
+ obvious consumer -- `except SignalGatewayError: # refused, give up` --
221
+ would otherwise swallow the one case that is not a refusal. The message
222
+ may still arrive. A run-and-exit caller cannot wait to find out, so it
223
+ must neither mark the signal delivered nor report success: the next run
224
+ resubmits it under the same idempotency key, which waits on the message
225
+ already in flight instead of sending a second one.
226
+
227
+ That promise is bounded by the gateway's `idempotency_ttl_s`, 24 hours by
228
+ default. A caller whose runs are further apart than the TTL gets a fresh
229
+ key for the same content, and the resubmit then posts a second copy.
230
+ """
231
+
232
+
233
+ def _units(text: str) -> int:
234
+ """Length in UTF-16 code units, which is what Signal's offsets count.
235
+
236
+ The one place this repo counts offsets: style ranges and mention
237
+ positions. Capacity is `_bytes`, because the limit is measured in UTF-8
238
+ bytes instead -- the two are different questions and mixing them is the
239
+ bug this split prevents. Python's `len` counts code points, so an emoji
240
+ (two units) ahead of a styled span would shift every range after it by one
241
+ and style the wrong characters.
242
+ """
243
+ retval = len(text.encode("utf-16-le")) // 2
244
+ return retval
245
+
246
+
247
+ def _bytes(text: str) -> int:
248
+ """Length in UTF-8 bytes, which is what Signal's limit counts.
249
+
250
+ The one place this repo measures capacity for Signal. Separate from
251
+ `_units` on purpose: the limit and the offsets are different units, and
252
+ the only way to keep them straight is to keep them in different
253
+ functions. Every non-ASCII character makes them disagree -- the bullet is
254
+ one unit and three bytes, an em-dash likewise, an emoji two units and
255
+ four bytes.
256
+ """
257
+ retval = len(text.encode("utf-8"))
258
+ return retval
259
+
260
+
261
+ # The longest footer that still leaves room for the message it rides on. A
262
+ # footer rides on every part, costing its length plus the newline before it,
263
+ # and a split message also carries a part marker. See `check_footer`.
264
+ MAX_FOOTER_BYTES = SIGNAL_MESSAGE_LIMIT - _MARKER_ROOM - 2
265
+
266
+
267
+ def check_footer(
268
+ footer: str, label: str = "signal footer", limit: int = SIGNAL_MESSAGE_LIMIT
269
+ ) -> None:
270
+ """Refuse a footer that leaves no room for the message it rides on.
271
+
272
+ Without this the arithmetic in `post_message` runs out of room and then
273
+ goes negative, and a splitter given a non-positive limit emits one
274
+ character per part: a single scored signal becomes thousands of Signal
275
+ messages, each one of them under the limit, so nothing downstream objects
276
+ and the run reports success. `slack.py` refuses the same shape for the same
277
+ reason, and is checked where the config is read so it fails before the run
278
+ has paid for a fetch or an LLM call.
279
+
280
+ `limit` is Signal's own unless a caller is posting under a smaller one, in
281
+ which case the room a footer may take shrinks with it: a check against the
282
+ constant would pass a footer that leaves the caller's limit nothing.
283
+ """
284
+ room = limit - _MARKER_ROOM - 2
285
+ if _bytes(footer) > room:
286
+ raise ValueError(
287
+ f"{label} is {_bytes(footer)} UTF-8 bytes, which leaves no room for content "
288
+ f"under {'Signal' if limit == SIGNAL_MESSAGE_LIMIT else 'this caller'}'s "
289
+ f"{limit}-byte limit"
290
+ )
291
+
292
+
293
+ class _Builder:
294
+ """Accumulates plain text and the style ranges over it."""
295
+
296
+ def __init__(self) -> None:
297
+ self.parts: list[str] = []
298
+ self.ranges: list[tuple[int, int, str]] = []
299
+ self._len = 0
300
+
301
+ @property
302
+ def text(self) -> str:
303
+ retval = "".join(self.parts)
304
+ return retval
305
+
306
+ def write(self, text: str) -> None:
307
+ if not text:
308
+ return
309
+ self.parts.append(text)
310
+ self._len += _units(text)
311
+
312
+ def mark(self) -> int:
313
+ retval = self._len
314
+ return retval
315
+
316
+ def style(self, start: int, style: str) -> None:
317
+ """Style everything written since `start`. Empty spans are dropped."""
318
+ length = self._len - start
319
+ if length <= 0:
320
+ return
321
+ for name in style.split("+"):
322
+ self.ranges.append((start, length, name))
323
+
324
+
325
+ def _link_text(match: re.Match[str]) -> str:
326
+ """`[label](url)` as Signal shows it: the label, then the URL in brackets.
327
+
328
+ Signal linkifies a bare URL and has no link style, so hiding the URL behind
329
+ a label would lose it entirely. A label equal to the URL, or absent, leaves
330
+ the URL alone rather than printing it twice.
331
+ """
332
+ label = (match.group(1) or "").strip()
333
+ url = (match.group(2) or match.group(3) or "").strip()
334
+ if not url:
335
+ retval = label
336
+ return retval
337
+ if not label or label == url:
338
+ retval = url
339
+ return retval
340
+ retval = f"{label} ({url})"
341
+ return retval
342
+
343
+
344
+ def _inline(text: str, out: _Builder) -> None:
345
+ """Convert one line's inline markup, writing text and ranges into `out`."""
346
+ position = 0
347
+ while position < len(text):
348
+ best: tuple[int, re.Match[str], str | None] | None = None
349
+ for pattern, style in _INLINE_RULES:
350
+ found = pattern.search(text, position)
351
+ if found is None:
352
+ continue
353
+ if best is None or found.start() < best[0]:
354
+ best = (found.start(), found, style)
355
+ if best is None:
356
+ out.write(text[position:])
357
+ return
358
+ start, match, style = best
359
+ out.write(text[position:start])
360
+ mark = out.mark()
361
+ if style is None:
362
+ out.write(_link_text(match) if match.re is _LINK_RE else match.group(1))
363
+ elif style in _RECURSIVE:
364
+ _inline(match.group(1), out)
365
+ out.style(mark, style)
366
+ else:
367
+ out.write(match.group(1))
368
+ out.style(mark, style)
369
+ position = match.end()
370
+
371
+
372
+ def to_signal(text: str) -> tuple[str, list[tuple[int, int, str]]]:
373
+ """Markdown in, plain text plus `(start, length, STYLE)` ranges out.
374
+
375
+ Block rules, matching the choices `slack.py` makes: a fenced block becomes
376
+ monospace with its fences removed, a heading becomes a bold line, and a list
377
+ marker becomes a bullet. Everything else is inline markup.
378
+ """
379
+ out = _Builder()
380
+ lines = text.split("\n")
381
+ index = 0
382
+ first = True
383
+ while index < len(lines):
384
+ line = lines[index]
385
+ if _FENCE_RE.match(line):
386
+ index += 1
387
+ block: list[str] = []
388
+ while index < len(lines) and not _FENCE_RE.match(lines[index]):
389
+ block.append(lines[index])
390
+ index += 1
391
+ index += 1 # the closing fence, or the end of the text
392
+ if not first:
393
+ out.write("\n")
394
+ mark = out.mark()
395
+ out.write("\n".join(block))
396
+ out.style(mark, MONOSPACE)
397
+ first = False
398
+ continue
399
+ if not first:
400
+ out.write("\n")
401
+ first = False
402
+ heading = _HEADING_RE.match(line)
403
+ if heading:
404
+ mark = out.mark()
405
+ _inline(heading.group(2), out)
406
+ out.style(mark, BOLD)
407
+ index += 1
408
+ continue
409
+ listed = _LIST_RE.match(line)
410
+ if listed:
411
+ out.write(f"{listed.group(1)}{BULLET} ")
412
+ _inline(listed.group(2), out)
413
+ index += 1
414
+ continue
415
+ _inline(line, out)
416
+ index += 1
417
+ retval = (out.text, out.ranges)
418
+ return retval
419
+
420
+
421
+ def _segments(text: str, sep: str, base: int = 0) -> list[tuple[str, int]]:
422
+ """Each piece of `text` split on `sep`, with its UTF-16 offset in the whole.
423
+
424
+ The offsets are the point: a part's styles are the ranges that fall inside
425
+ it, so a split has to say where each piece came from.
426
+ """
427
+ retval = []
428
+ offset = base
429
+ for piece in text.split(sep):
430
+ retval.append((piece, offset))
431
+ offset += _units(piece) + _units(sep)
432
+ return retval
433
+
434
+
435
+ def _cut(text: str, offset: int, limit: int) -> list[tuple[str, int]]:
436
+ """Cut inside a line, on a code-point boundary, when nothing coarser fits.
437
+
438
+ A code point is never split, so a surrogate pair cannot be halved into two
439
+ messages of invalid text, and no part can end with half a UTF-8 sequence.
440
+
441
+ Both units appear here, which is why they are named: the test is whether
442
+ another character still fits under the byte limit, and the number carried
443
+ forward is the piece's offset in UTF-16 units for its style ranges.
444
+ """
445
+ retval: list[tuple[str, int]] = []
446
+ current = ""
447
+ start = offset
448
+ for char in text:
449
+ if current and _bytes(current) + _bytes(char) > limit:
450
+ retval.append((current, start))
451
+ start += _units(current)
452
+ current = ""
453
+ current += char
454
+ if current:
455
+ retval.append((current, start))
456
+ return retval
457
+
458
+
459
+ def _pack(pieces: list[tuple[str, int]], sep: str, limit: int, finer) -> list[tuple[str, int]]:
460
+ """Greedily join `pieces` into parts of at most `limit` bytes.
461
+
462
+ A piece too long on its own is handed to `finer`, which splits it on the
463
+ next boundary down.
464
+ """
465
+ parts: list[tuple[str, int]] = []
466
+ current: tuple[str, int] | None = None
467
+ for piece, offset in pieces:
468
+ if current is not None:
469
+ candidate = f"{current[0]}{sep}{piece}"
470
+ if _bytes(candidate) <= limit:
471
+ current = (candidate, current[1])
472
+ continue
473
+ parts.append(current)
474
+ current = None
475
+ if _bytes(piece) <= limit:
476
+ current = (piece, offset)
477
+ continue
478
+ parts.extend(finer(piece, offset, limit))
479
+ if current is not None:
480
+ parts.append(current)
481
+ retval = parts
482
+ return retval
483
+
484
+
485
+ def _split_bytes(text: str, limit: int) -> list[tuple[str, int]]:
486
+ """`text` in parts of at most `limit` UTF-8 bytes, each with its offset.
487
+
488
+ Paragraph boundaries first, then line boundaries, then inside a line only
489
+ when one line is itself longer than the limit. Never truncates. The offset
490
+ that comes back with each part is in UTF-16 units, because it addresses
491
+ style ranges rather than capacity.
492
+ """
493
+ if limit < 1:
494
+ raise SignalSendError(
495
+ f"signal message split asked for parts of {limit} bytes; "
496
+ "a footer or a marker has eaten the whole message"
497
+ )
498
+ if _bytes(text) <= limit:
499
+ retval = [(text, 0)]
500
+ return retval
501
+
502
+ def lines(piece: str, offset: int, room: int) -> list[tuple[str, int]]:
503
+ inner = _pack(_segments(piece, "\n", offset), "\n", room, _cut)
504
+ return inner
505
+
506
+ retval = _pack(_segments(text, "\n\n"), "\n\n", limit, lines)
507
+ return retval
508
+
509
+
510
+ def _clip(
511
+ ranges: list[tuple[int, int, str]], start: int, length: int
512
+ ) -> list[tuple[int, int, str]]:
513
+ """The styles covering `[start, start + length)`, rebased on that part.
514
+
515
+ A range that straddles the boundary is kept on both sides, clipped to each:
516
+ Signal has no way to reopen a style in the next message, so the two halves
517
+ of a bold span are two bold ranges.
518
+ """
519
+ retval = []
520
+ for range_start, range_length, style in ranges:
521
+ low = max(range_start, start)
522
+ high = min(range_start + range_length, start + length)
523
+ if high > low:
524
+ retval.append((low - start, high - low, style))
525
+ return retval
526
+
527
+
528
+ def _short_digest(text: str) -> str:
529
+ """A few bytes of hash, to tell two configurations apart inside a key."""
530
+ retval = hashlib.sha256(text.encode("utf-8")).hexdigest()[:8]
531
+ return retval
532
+
533
+
534
+ def _as_text(value: object) -> str:
535
+ """Whatever a subprocess attribute holds, as a string."""
536
+ if value is None:
537
+ retval = ""
538
+ elif isinstance(value, bytes):
539
+ retval = value.decode("utf-8", "replace")
540
+ else:
541
+ retval = str(value)
542
+ return retval
543
+
544
+
545
+ class Transport(Protocol):
546
+ """What `post_message` needs from whatever carries the message.
547
+
548
+ `limit` belongs to the transport rather than to the splitter because only
549
+ the transport knows what the text will be wrapped in: the gateway may put
550
+ a label in front of every message, and those bytes come out of the same
551
+ 2000.
552
+ """
553
+
554
+ limit: int
555
+ # Whether a resubmitted part is deduplicated by the far side. False for
556
+ # signal-cli, which has nothing to deduplicate against, so a retry after
557
+ # a partial send posts the earlier parts a second time. `post_message`
558
+ # tells a caller which of those two situations it is in rather than
559
+ # asserting the safe one for both.
560
+ idempotent: bool
561
+
562
+ def send(
563
+ self, text: str, ranges: list[tuple[int, int, str]], seed: str = ""
564
+ ) -> int | str:
565
+ """Send one rendered message; return the handle it is addressed by.
566
+
567
+ `seed` identifies *which* message this is, independently of how it
568
+ reads. A transport that deduplicates resubmits needs that: see
569
+ `GatewayTransport._key`. A transport that does not may ignore it.
570
+
571
+ Which handle depends on the transport, and neither is interchangeable
572
+ with the other: signal-cli hands back Signal's own timestamp, an int,
573
+ which is what an edit through signal-cli would take. The gateway hands
574
+ back its own `message_id`, a string, which is what its edit, delete
575
+ and reaction endpoints take -- it keeps the Signal timestamp itself. A
576
+ zero means the message went out and the transport did not say which.
577
+ """
578
+ ...
579
+
580
+
581
+ class SignalTransport:
582
+ """Where a Signal message goes: one group, through the `signal-cli` binary.
583
+
584
+ Group only, deliberately. The approval conversation this exists for is a
585
+ dedicated group, and a one-to-one recipient is a second target shape with
586
+ its own trusted-sender question; it can be added when something needs it.
587
+ """
588
+
589
+ def __init__(
590
+ self,
591
+ account: str,
592
+ group_id: str,
593
+ binary: str = "signal-cli",
594
+ timeout: int = 120,
595
+ ):
596
+ self.account = account
597
+ self.group_id = group_id
598
+ self.binary = binary
599
+ self.timeout = timeout
600
+ self.limit = SIGNAL_MESSAGE_LIMIT
601
+ self.idempotent = False
602
+
603
+ def _scrub(self, text: str) -> str:
604
+ """Keep the account, the group and any phone number out of what we raise.
605
+
606
+ Both the account and the group id are named by environment variable
607
+ rather than written in config because each identifies a private
608
+ conversation -- so neither belongs in a failure either. signal-cli
609
+ echoes the group id back on a bad-group error, and names the member it
610
+ could not reach when a send to a group fails, and what this raises
611
+ reaches logs, CI output and issue paste-ins.
612
+ """
613
+ retval = text
614
+ for secret, placeholder in ((self.account, "<account>"), (self.group_id, "<group>")):
615
+ if secret:
616
+ retval = retval.replace(secret, placeholder)
617
+ retval = _NUMBER_RE.sub("<number>", retval)
618
+ return retval
619
+
620
+ def send(
621
+ self, text: str, ranges: list[tuple[int, int, str]], seed: str = ""
622
+ ) -> int:
623
+ """Send one already-rendered message. Returns its Signal timestamp.
624
+
625
+ `seed` is accepted and ignored: signal-cli has nothing to deduplicate
626
+ a resubmit against, which is what `idempotent = False` says.
627
+
628
+ That timestamp *is* the message id in Signal -- the counterpart of a
629
+ Slack `ts`, and the only handle an edit could later be made with. A
630
+ zero means the message went out and signal-cli did not say which one it
631
+ was; see below.
632
+
633
+ The text goes in on stdin rather than in `argv`: a digest is longer than
634
+ a comfortable argument, and a message full of quotes and `$(...)` must
635
+ reach signal-cli as itself.
636
+ """
637
+ argv = [
638
+ self.binary,
639
+ "--output=json",
640
+ "-a",
641
+ self.account,
642
+ "send",
643
+ "-g",
644
+ self.group_id,
645
+ "--message-from-stdin",
646
+ ]
647
+ if ranges:
648
+ argv.append("--text-style")
649
+ argv.extend(f"{start}:{length}:{style}" for start, length, style in ranges)
650
+ try:
651
+ done = subprocess.run(
652
+ argv,
653
+ input=text,
654
+ capture_output=True,
655
+ text=True,
656
+ timeout=self.timeout,
657
+ )
658
+ except subprocess.TimeoutExpired as exc:
659
+ # Not `from exc`: TimeoutExpired renders the whole argv, which
660
+ # holds `-a <number>` and `-g <group>`, and this exception reaches
661
+ # an uncaught traceback. Whatever signal-cli managed to say is
662
+ # worth keeping, scrubbed, because at the default timeout on a
663
+ # multi-part message it is the only clue which part hung.
664
+ said = self._scrub(_as_text(exc.stderr) or _as_text(exc.stdout)).strip()[-800:]
665
+ raise SignalCliError(
666
+ f"{self.binary} did not answer within {self.timeout}s"
667
+ + (f"; it had said: {said}" if said else "")
668
+ ) from None
669
+ if done.returncode != 0:
670
+ tail = self._scrub((done.stderr or done.stdout or "").strip())[-800:]
671
+ raise SignalCliError(f"signal-cli exited {done.returncode}: {tail}")
672
+ # Read line by line: signal-cli's `--output=json` is line-oriented on
673
+ # other commands, so a second line one day must not discard a timestamp
674
+ # that was on the first.
675
+ for line in (done.stdout or "").splitlines():
676
+ if not line.strip():
677
+ continue
678
+ try:
679
+ body = json.loads(line)
680
+ except ValueError:
681
+ continue
682
+ if isinstance(body, dict) and "timestamp" in body:
683
+ try:
684
+ retval = int(body["timestamp"])
685
+ return retval
686
+ except (TypeError, ValueError):
687
+ break
688
+ # A zero exit means signal-cli accepted the message and handed it to
689
+ # Signal. If its output does not say which message, that is a reply
690
+ # shape this code does not know -- not a failed send. Raising here
691
+ # would abort the run *after* delivery, leave the signal unmarked, and
692
+ # post it again on the next run: a permanent duplicate for a parsing
693
+ # question. So this returns 0, meaning delivered, id unknown, the same
694
+ # call this repo makes for a tweet that returns 2xx without an id.
695
+ return 0
696
+
697
+
698
+ class GatewayTransport:
699
+ """Where a Signal message goes: one conversation, through the gateway.
700
+
701
+ The gateway owns the Signal account. Only one process can, so this and
702
+ `SignalTransport` are alternatives rather than layers: once the gateway's
703
+ daemon holds the account, the subprocess path cannot open it.
704
+
705
+ Three things are deliberately not here. The group id never appears -- the
706
+ gateway maps an alias such as `leads` to it, so a private conversation's
707
+ id does not travel to its consumers or into their logs. The token is read
708
+ from a 0600 file rather than the environment, because a run spawns LLM
709
+ CLIs as children and a variable in the environment is visible to all of
710
+ them. And nothing polls for delivery: a run-and-exit caller cannot wait,
711
+ so it asks the gateway to wait instead.
712
+ """
713
+
714
+ def __init__(
715
+ self,
716
+ base_url: str,
717
+ conversation: str,
718
+ token: str,
719
+ label: str = "",
720
+ wait_s: int = 10,
721
+ timeout: int = 120,
722
+ fingerprint: str = "",
723
+ repeats: bool = False,
724
+ ):
725
+ self.base_url = base_url.rstrip("/")
726
+ self.conversation = conversation
727
+ self.label = label
728
+ self.wait_s = wait_s
729
+ self.timeout = timeout
730
+ self._token = token
731
+ # Which destination this is, as far as anything stable can say. See
732
+ # `_key`: the gateway's idempotency store is namespaced by consumer,
733
+ # so two destinations behind one token need to differ here.
734
+ self.fingerprint = fingerprint
735
+ # Whether this destination deliberately sends the same signal more
736
+ # than once. See `_key`: it decides whether the gateway's replay of
737
+ # an earlier message is the retry this design wants or a delivery
738
+ # quietly dropped.
739
+ self.repeats = repeats
740
+ self.idempotent = not repeats
741
+ # One value per process, so every part of every message in this run
742
+ # shares it and a retry within the run would still match.
743
+ self._run = f"{int(time()):x}-{os.getpid():x}"
744
+ # A label is prepended by the gateway to every message it sends, so
745
+ # its bytes are not available to the body. `_bytes` and not `len`,
746
+ # for the reason the whole module says.
747
+ #
748
+ # This value only *mirrors* the gateway's: the prefix comes from its
749
+ # own `consumers.<name>.label`, no endpoint reports that back, and the
750
+ # gateway re-checks the length after prefixing. So a label configured
751
+ # there and missing here means every full-size part is refused with
752
+ # 422 `too_long` -- which `send` names as a likely cause, because the
753
+ # arithmetic looks right from this side and the mismatch is the only
754
+ # thing that explains it.
755
+ self.limit = SIGNAL_MESSAGE_LIMIT - (_bytes(f"{label}: ") if label else 0)
756
+
757
+ def _scrub(self, text: str) -> str:
758
+ """Keep the token out of whatever this raises.
759
+
760
+ Less to hide than the subprocess transport -- there is no account
761
+ number or group id here, by design -- but a gateway that echoed a bad
762
+ Authorization header back would otherwise put the token in a
763
+ traceback, a log and any issue it is pasted into.
764
+ """
765
+ retval = text
766
+ if self._token:
767
+ retval = retval.replace(self._token, "<token>")
768
+ retval = _NUMBER_RE.sub("<number>", retval)
769
+ return retval
770
+
771
+ def _warn_replayed(self, status: str, seed: str) -> None:
772
+ """Say that the gateway replayed a message rather than sending one.
773
+
774
+ The gateway found this idempotency key in its store and answered with
775
+ the earlier message's outcome; nothing new went out. For the retry
776
+ this design asks for, that is exactly right. For a caller sending the
777
+ same signal twice inside `idempotency_ttl_s` it is a silent no-op
778
+ reported as success, and the flag is the only evidence either way --
779
+ so it is said out loud, from one place, before any of `send`'s
780
+ returns.
781
+ """
782
+ keyed = (
783
+ f"the id {seed!r} this part was sent under"
784
+ if seed
785
+ else "derived from this part's text and styles"
786
+ )
787
+ print(
788
+ f"signal gateway replayed an earlier message for this part "
789
+ f"(duplicate=true, status {status or 'unreported'!r}); nothing new was sent. "
790
+ f"The key is {keyed}, and the gateway remembers it for its idempotency TTL -- "
791
+ f"so a deliberate repeat, as opposed to a retry, keeps being replayed until "
792
+ f"that TTL expires"
793
+ + (
794
+ ", and editing the message will not change that, because the key does "
795
+ "not depend on the text"
796
+ if seed
797
+ else ""
798
+ ),
799
+ file=sys.stderr,
800
+ )
801
+
802
+ def _key(
803
+ self,
804
+ text: str,
805
+ ranges: list[tuple[int, int, str]],
806
+ seed: str = "",
807
+ salt: str = "",
808
+ ) -> str:
809
+ """An idempotency key for this message to this conversation.
810
+
811
+ The retry a `SignalSendPending` asks for has to carry the same key as
812
+ the send it is retrying, or the gateway has nothing to match and the
813
+ parts that did arrive are posted again.
814
+
815
+ So `seed` is preferred over the content when a caller supplies one,
816
+ because the content is not stable across runs in this framework: a
817
+ retry re-scores, `llm_scorer` appends the rung the vendor waterfall
818
+ landed on to its reasons, and the destination renders those reasons
819
+ into the text. A different rung, or any drift in a model's wording,
820
+ changes the text and therefore a content-derived key -- and the part
821
+ that already reached the group is sent a second time. A signal's `id`
822
+ does not move for either reason.
823
+
824
+ The material also holds this transport's `fingerprint`, a digest of
825
+ the workspace it was built in, and the seed `post_message` builds
826
+ carries a digest of the footer. Both are there because the
827
+ gateway namespaces its idempotency store by consumer, not by
828
+ destination: two destinations sharing one gateway token and one
829
+ conversation are one consumer to it, so the same signal would
830
+ otherwise produce the same key from both, and the second one's
831
+ message -- its own footer, its own reasons -- would come back as a
832
+ replay of the first, reported as delivered and never sent. The footer
833
+ alone does not settle it, since an empty or shared footer is exactly
834
+ the case that collides; the workspace does, and it is stable against
835
+ the config edits an operator makes while chasing a failure. Two
836
+ destinations with the same footer in one workspace and one
837
+ conversation still collide -- and are the same message to the same
838
+ people, the one case where a replay is the right answer. Beyond that,
839
+ give each agent its own gateway consumer and token, which is what the
840
+ namespacing is for.
841
+
842
+ The seed `post_message` builds is
843
+ `<id>@<footer digest>#<number>-of-<total>`, optionally with a run
844
+ nonce (see `repeats`), and the total is in it on purpose. A key that
845
+ named only the part number would match across runs that split
846
+ differently, and the worse direction of
847
+ that is silent: a retry whose text shortened into one part would carry
848
+ the key of the old part 1, the gateway would replay that part, this
849
+ side would read a 200 and mark the signal delivered, and everything
850
+ that had been in part 2 would never be sent. Including the total means
851
+ a different split is a different message, which is what it is.
852
+
853
+ What remains, and is the lesser of the two: a retry that splits the
854
+ same way but reads differently matches the parts that already arrived,
855
+ so the group keeps the first run's wording for those and takes the new
856
+ wording for the rest. Nothing is lost -- the same signal is described
857
+ either way -- and it is strictly better than a duplicate or a hole.
858
+
859
+ `salt` moves a key off an entry the gateway can no longer honour --
860
+ see the `message_gone` branch in `send`. It is not a retry knob: the
861
+ whole value of the key is that a retry reuses it.
862
+
863
+ Without a seed it falls back to the content, which is right for a
864
+ caller that has no stable id to offer. The digest covers the styles as
865
+ well as the text, since two parts of one message can hold the same
866
+ words under different emphasis.
867
+ """
868
+ if seed and self.repeats:
869
+ # A source that re-lists the same items every run means to send
870
+ # them again, and the gateway cannot tell that from a retry: both
871
+ # arrive as the same key inside its 24-hour window, and it
872
+ # answers the second one by replaying the first. Reported as
873
+ # delivered, never sent. So a destination that repeats itself
874
+ # gets a key that is unique per run, and gives up the
875
+ # cross-run retry guarantee in exchange -- which is the trade
876
+ # `idempotent` then reports, so a partial send says that
877
+ # resubmitting repeats the parts that arrived.
878
+ seed = f"{seed}!{self._run}"
879
+ material = json.dumps(
880
+ [self.conversation, self.label, self.fingerprint, salt, seed] if seed
881
+ else [self.conversation, self.label, self.fingerprint, salt, text, ranges],
882
+ ensure_ascii=False,
883
+ sort_keys=True,
884
+ )
885
+ retval = hashlib.sha256(material.encode("utf-8")).hexdigest()
886
+ return retval
887
+
888
+ def send(
889
+ self, text: str, ranges: list[tuple[int, int, str]], seed: str = ""
890
+ ) -> int | str:
891
+ """Send one rendered message, waiting for Signal to take it.
892
+
893
+ `seed` identifies the message independently of how it reads, and is
894
+ what the idempotency key is built from when a caller gives one. See
895
+ `_key`.
896
+
897
+ Returns the gateway's `message_id` on a 200. Raises on anything else,
898
+ so a caller that marks a signal delivered only when this returns can
899
+ never mark one that did not arrive:
900
+
901
+ - 200 means the message left, under any of `_GATEWAY_SENT`, or --
902
+ from a build without `wait_s` -- that it has not left yet, under
903
+ `_GATEWAY_PENDING`. A 200 carries no Signal timestamp: the gateway
904
+ keeps that and addresses the message by `message_id`, which is what
905
+ its edit, delete and reaction endpoints take. A `duplicate` flag
906
+ means the key was found in the gateway's idempotency store and the
907
+ earlier outcome replayed, so nothing new was sent.
908
+ - 502 means the send was refused for good; retrying it is pointless
909
+ until whatever was wrong is fixed.
910
+ - 202 means it was still in flight when the gateway's own deadline
911
+ passed, which includes a retry of a message still in flight. Not a
912
+ failure and not a success, so it raises `SignalSendPending` and the
913
+ next run resubmits the same key.
914
+ """
915
+ # The ranges go in as offsets into the text as submitted, not
916
+ # shifted for a label. The gateway rebases them itself when it
917
+ # prefixes one -- `_labelled` adds `units(prefix)` to every style and
918
+ # mention start -- so adjusting here would move them twice. Only the
919
+ # label's *bytes* are this side's business, in `limit`.
920
+ payload = {
921
+ "to": {"conversation": self.conversation},
922
+ "parts": [
923
+ {
924
+ "type": "text",
925
+ "text": text,
926
+ "styles": [
927
+ {"start": start, "length": length, "style": style}
928
+ for start, length, style in ranges
929
+ ],
930
+ }
931
+ ],
932
+ "idempotency_key": self._key(text, ranges, seed),
933
+ "wait_s": self.wait_s,
934
+ }
935
+ response = self._post(payload)
936
+ if response.status_code == 409 and "message_gone" in (response.text or ""):
937
+ # The gateway still holds this idempotency key but has lost the
938
+ # message it names -- its data was reset, or a retention it did
939
+ # not have yet removed the row. The key is derived, so every run
940
+ # would compute it again and get this same 409 until it expires:
941
+ # a message that is not delivered and, from this side, cannot be.
942
+ # So the key is moved once, deliberately, and the send retried.
943
+ # The cost is a duplicate if the original did reach the group
944
+ # before the reset; the alternative is a silent gap for the rest
945
+ # of the TTL, and a duplicate someone can see is the better of
946
+ # the two. Once, not in a loop: a second `message_gone` under a
947
+ # fresh key is a gateway problem, not a key problem.
948
+ print(
949
+ "signal gateway lost the message behind this idempotency key "
950
+ "(message_gone); sending once more under a fresh key, which may "
951
+ "duplicate it if the original went out before the gateway's data was "
952
+ "reset",
953
+ file=sys.stderr,
954
+ )
955
+ payload["idempotency_key"] = self._key(text, ranges, seed, salt="message_gone")
956
+ response = self._post(payload)
957
+ said = self._scrub((response.text or "").strip())
958
+ tail = said[-400:]
959
+ return self._read(response, said, tail, seed)
960
+
961
+ def _post(self, payload: dict) -> requests.Response:
962
+ """One POST to the gateway, with every failure shape classified."""
963
+ try:
964
+ response = requests.post(
965
+ f"{self.base_url}/v1/messages",
966
+ json=payload,
967
+ headers={"Authorization": f"Bearer {self._token}"},
968
+ timeout=self.timeout,
969
+ )
970
+ return response
971
+ except requests.ConnectTimeout as exc:
972
+ # No connection was established, so nothing was sent.
973
+ # Not `from exc`: a requests exception renders the request, and
974
+ # the Authorization header is on it.
975
+ raise SignalGatewayError(
976
+ f"signal gateway at {self.base_url} did not accept a connection within "
977
+ f"{self.timeout}s; nothing was sent: {self._scrub(str(exc))[-300:]}"
978
+ ) from None
979
+ except (requests.exceptions.SSLError, requests.exceptions.ProxyError) as exc:
980
+ # Both are `ConnectionError` subclasses and would otherwise be
981
+ # caught below as pending. They are not ambiguous: a handshake
982
+ # that failed or a proxy that refused the tunnel means the request
983
+ # never went, and reporting a misconfigured certificate as a
984
+ # message possibly in flight would hide it run after run.
985
+ raise SignalGatewayError(
986
+ f"signal gateway at {self.base_url} could not be reached securely, so "
987
+ f"nothing was sent: {self._scrub(str(exc))[-300:]}"
988
+ ) from None
989
+ except (
990
+ requests.ReadTimeout,
991
+ requests.ConnectionError,
992
+ requests.exceptions.ChunkedEncodingError,
993
+ ):
994
+ # Everything else that fails around a connection leaves the
995
+ # message in doubt: a read deadline passing, a gateway restarting
996
+ # or a proxy resetting while it holds the response for `wait_s`, a
997
+ # truncated body, a refused connection. The window the gateway
998
+ # spends holding a reply is exactly where a restart lands, and
999
+ # `requests` raises one class for a reset at that moment and for a
1000
+ # port that was never open -- telling them apart means reading
1001
+ # urllib3's cause chain, which is not worth depending on for a
1002
+ # message's wording. Pending is the answer that is true either
1003
+ # way: it marks nothing and resubmits under the same key, which
1004
+ # the gateway matches if the message did get through, and which is
1005
+ # also what a caller should do when the gateway is simply down.
1006
+ raise SignalSendPending(
1007
+ f"the exchange with the signal gateway at {self.base_url} did not complete "
1008
+ f"within {self.timeout}s. If the request reached it the message may be "
1009
+ f"queued, so it stays unmarked and the next run resubmits it under the "
1010
+ f"same key"
1011
+ ) from None
1012
+ except requests.RequestException as exc:
1013
+ raise SignalGatewayError(
1014
+ f"signal gateway at {self.base_url} did not answer: "
1015
+ f"{self._scrub(str(exc))[-400:]}"
1016
+ ) from None
1017
+ # Matched on the whole body and truncated only for display: a 422
1018
+ # that echoes the part it refused pushes the marker out of a 400-byte
1019
+ # tail, and the one failure this transport can explain would fall
1020
+ # through to the generic relay.
1021
+ def _read(
1022
+ self, response: requests.Response, said: str, tail: str, seed: str
1023
+ ) -> int | str:
1024
+ """What the gateway's answer means. See `send` for the contract."""
1025
+ if response.status_code == 202:
1026
+ raise SignalSendPending(
1027
+ f"signal gateway queued the message but Signal had not taken it within "
1028
+ f"{self.wait_s}s; it is not delivered and not failed, so it stays unmarked "
1029
+ f"and the next run resubmits it: {tail}"
1030
+ )
1031
+ if response.status_code == 422 and "too_long" in said:
1032
+ # The arithmetic on this side reserved room for `self.label`. If
1033
+ # the gateway still finds the part too long, the label it is
1034
+ # actually configured with is longer than the one named here --
1035
+ # it re-checks after prefixing, and nothing reports its value
1036
+ # back, so this is the one failure worth explaining rather than
1037
+ # relaying.
1038
+ raise SignalGatewayError(
1039
+ f"signal gateway refused a part as too long although this side split at "
1040
+ f"{self.limit} bytes, reserving room for the label {self.label!r}. The "
1041
+ f"gateway prefixes its own consumers.<name>.label and re-checks the length "
1042
+ f"afterwards, so that label is probably longer than this one, or set when "
1043
+ f"this config has none: {tail}"
1044
+ )
1045
+ if response.status_code == 502 and "send_failed" in said:
1046
+ raise SignalGatewayError(
1047
+ f"signal gateway answered 502 send_failed, refusing the message for "
1048
+ f"good: {tail}"
1049
+ )
1050
+ if response.status_code >= 500:
1051
+ # Not a refusal. The gateway's own "refused for good" is a 502
1052
+ # carrying `send_failed`, handled above; any other 5xx is a
1053
+ # gateway that crashed or a proxy that gave up, and it lands in
1054
+ # the window the gateway spends holding the response for
1055
+ # `wait_s` -- the same ambiguity the connection branch above
1056
+ # treats as pending, and for the same reason: the message may
1057
+ # already be enqueued.
1058
+ raise SignalSendPending(
1059
+ f"signal gateway answered {response.status_code}, which is not its own "
1060
+ f"refusal. The message may already be queued, so it stays unmarked and "
1061
+ f"the next run resubmits it under the same key: {tail}"
1062
+ )
1063
+ if response.status_code != 200:
1064
+ raise SignalGatewayError(
1065
+ f"signal gateway answered {response.status_code}: {tail}"
1066
+ )
1067
+ try:
1068
+ body = response.json()
1069
+ except ValueError:
1070
+ raise SignalGatewayError(
1071
+ f"signal gateway answered 200 with a body that is not JSON: {tail}"
1072
+ ) from None
1073
+ if not isinstance(body, dict):
1074
+ raise SignalGatewayError(f"signal gateway answered 200 with {type(body).__name__}")
1075
+ status = str(body.get("status") or "")
1076
+ if body.get("duplicate"):
1077
+ self._warn_replayed(status, seed)
1078
+ if not status:
1079
+ # Absent, null or empty: all three are the gateway not saying,
1080
+ # which is not the same as saying something this version does not
1081
+ # know. The same rule applies as to a missing `message_id`: a 200
1082
+ # is the gateway saying the message left, and raising over a field
1083
+ # it did not fill would discard a delivered message's mark and
1084
+ # post it again next run -- or, once the idempotency store
1085
+ # replays this same statusless 200, fail identically every run
1086
+ # until the TTL expires and then duplicate. The handle is still
1087
+ # returned if there is one; only the status was missing.
1088
+ retval = str(body.get("message_id") or "") or 0
1089
+ return retval
1090
+ if status in _GATEWAY_FAILED:
1091
+ raise SignalGatewayError(
1092
+ f"signal gateway answered 200 but reports the message {status!r}; it did "
1093
+ f"not go out: {tail}"
1094
+ )
1095
+ if status in _GATEWAY_PENDING or status in _GATEWAY_INBOUND:
1096
+ raise SignalGatewayError(
1097
+ f"signal gateway answered 200 with status {status!r}, which means the "
1098
+ f"message has not left and it did not honour the {self.wait_s}s wait this "
1099
+ f"send asked for -- an older build. "
1100
+ f"The message may well have gone out, but this cannot be established from "
1101
+ f"here: the gateway's idempotency entry keeps the status it was written "
1102
+ f"with, so resubmitting replays this same answer until the entry expires "
1103
+ f"and then sends a second copy. Check the conversation by hand and deploy "
1104
+ f"a gateway that implements wait_s: {tail}"
1105
+ )
1106
+ if status not in _GATEWAY_SENT:
1107
+ raise SignalGatewayError(
1108
+ f"signal gateway answered 200 with status {status!r}, which this "
1109
+ f"version does not know how to read; it knows {', '.join(_known)}: {tail}"
1110
+ )
1111
+ handle = str(body.get("message_id") or "")
1112
+ if not handle:
1113
+ # Delivered, id unknown: the same call the subprocess transport
1114
+ # makes when signal-cli accepts a message without naming it.
1115
+ # Raising here would discard a delivered message's mark and post
1116
+ # it again next run.
1117
+ return 0
1118
+ retval = handle
1119
+ return retval
1120
+
1121
+
1122
+ def _read_token_file(path: str, label: str) -> str:
1123
+ """The token in a 0600 file, refusing one anybody else can read.
1124
+
1125
+ The mode is checked rather than assumed: a token readable by another
1126
+ account is a token to treat as disclosed, and the moment to notice is
1127
+ before the run starts rather than after it has posted.
1128
+ """
1129
+ try:
1130
+ # O_NOFOLLOW, and the mode read from the descriptor rather than the
1131
+ # path: `os.stat` follows a symlink, so a world-writable link to a
1132
+ # 0600 file would pass a check on the target. Opening first and
1133
+ # calling fstat also closes the gap between checking a path and
1134
+ # reading it. The open is inside the guard because a file that stats
1135
+ # and will not open -- 0400 owned by another account, root-owned, a
1136
+ # directory at that path -- is exactly the early, labelled failure
1137
+ # this function exists to produce.
1138
+ # O_NONBLOCK so a FIFO at this path fails instead of hanging the run
1139
+ # with no timeout: the regular-file check below cannot run until the
1140
+ # open returns, and on a FIFO it never would.
1141
+ fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK)
1142
+ except OSError as exc:
1143
+ raise RuntimeError(
1144
+ f"{label}: cannot read 'token_file' {path!r}: {exc.strerror}"
1145
+ + (". A symbolic link is not accepted here" if exc.errno == errno.ELOOP else "")
1146
+ ) from None
1147
+ try:
1148
+ info = os.fstat(fd)
1149
+ if not stat.S_ISREG(info.st_mode):
1150
+ # Checked on the descriptor before anything wraps it: a directory
1151
+ # opens happily with O_RDONLY and it is `fdopen` that raises, as a
1152
+ # bare IsADirectoryError naming neither the label nor the setting.
1153
+ raise RuntimeError(f"{label}: 'token_file' {path!r} is not a regular file")
1154
+ leaked = stat.S_IMODE(info.st_mode) & (stat.S_IRWXG | stat.S_IRWXO)
1155
+ if leaked:
1156
+ raise RuntimeError(
1157
+ f"{label}: 'token_file' {path!r} is mode {stat.S_IMODE(info.st_mode):04o}; it "
1158
+ "holds a send credential and must be 0600, readable only by the account that "
1159
+ "runs the agent. Fix it with chmod 600 and, since it was readable, have the "
1160
+ "token reissued"
1161
+ )
1162
+ # Handed over before the call, not inside the `with`: if `fdopen`
1163
+ # raises, it has already closed the descriptor, and the `finally`
1164
+ # below would close it a second time -- an EBADF masking the real
1165
+ # failure, or a close of a number since reused by another thread.
1166
+ owned, fd = fd, -1
1167
+ with os.fdopen(owned, "rb") as handle:
1168
+ retval = handle.read().decode("utf-8").strip()
1169
+ finally:
1170
+ if fd >= 0:
1171
+ os.close(fd)
1172
+ if not retval:
1173
+ raise RuntimeError(f"{label}: 'token_file' {path!r} is empty")
1174
+ return retval
1175
+
1176
+
1177
+ def _gateway_from_config(cfg: dict, label: str, timeout: int) -> GatewayTransport:
1178
+ """Build the gateway transport a destination block asks for."""
1179
+ gateway = cfg.get("gateway")
1180
+ if not isinstance(gateway, dict):
1181
+ raise RuntimeError(
1182
+ f"{label}: transport 'gateway' needs a 'gateway' block with 'url', "
1183
+ "'conversation' and 'token_file'"
1184
+ )
1185
+ url = str(gateway.get("url") or "")
1186
+ conversation = str(gateway.get("conversation") or "")
1187
+ token_file = str(gateway.get("token_file") or "")
1188
+ missing = [
1189
+ name
1190
+ for name, value in (
1191
+ ("url", url),
1192
+ ("conversation", conversation),
1193
+ ("token_file", token_file),
1194
+ )
1195
+ if not value
1196
+ ]
1197
+ if missing:
1198
+ raise RuntimeError(f"{label}: gateway block is missing: {', '.join(missing)}")
1199
+ if not url.startswith(("http://", "https://")):
1200
+ # `requests` raises MissingSchema on the first send otherwise, which
1201
+ # is after the run has fetched, scored and paid for a model call. The
1202
+ # same fail-early rule this function applies to 'wait_s'.
1203
+ raise RuntimeError(
1204
+ f"{label}: gateway 'url' is {url!r}, which has no scheme; it needs "
1205
+ "http:// or https://"
1206
+ )
1207
+ repeats = gateway.get("repeats", False)
1208
+ if not isinstance(repeats, bool):
1209
+ raise RuntimeError(f"{label}: gateway 'repeats' must be true or false")
1210
+ message_label = gateway.get("label", "")
1211
+ if not isinstance(message_label, str):
1212
+ raise RuntimeError(f"{label}: gateway 'label' must be a string")
1213
+ try:
1214
+ wait_s = int(gateway.get("wait_s", 10))
1215
+ except (TypeError, ValueError):
1216
+ # The gateway answers 422 `bad_wait` for this, but only after the run
1217
+ # has been built and has fetched and scored something. A config value
1218
+ # that is not a number is knowable now.
1219
+ raise RuntimeError(
1220
+ f"{label}: gateway 'wait_s' is {gateway.get('wait_s')!r}, which is not a number"
1221
+ ) from None
1222
+ if not 1 <= wait_s <= 30:
1223
+ # The gateway caps its own wait at 30. A larger number here would be
1224
+ # silently clamped there, which is a config file that does not say
1225
+ # what happens.
1226
+ raise RuntimeError(
1227
+ f"{label}: gateway 'wait_s' is {wait_s}; it must be between 1 and 30, "
1228
+ "which is the gateway's own cap"
1229
+ )
1230
+ if timeout < wait_s + _WAIT_MARGIN:
1231
+ # The gateway holds the response for up to `wait_s`. A socket timeout
1232
+ # at or under that fires first, and a send still in flight then comes
1233
+ # back as "the gateway did not answer" -- a refusal -- instead of the
1234
+ # pending answer it is. Marking the difference matters: one says do
1235
+ # not retry, the other says retry under the same key.
1236
+ raise RuntimeError(
1237
+ f"{label}: 'timeout' is {timeout}s and gateway 'wait_s' is {wait_s}s. The "
1238
+ f"request timeout has to outlast the wait by at least {_WAIT_MARGIN}s, or a "
1239
+ f"gateway answering a moment after its own deadline times out the socket "
1240
+ f"instead, and a message still in flight is read as a failed send"
1241
+ )
1242
+ # Which destination this is, as one short digest: see
1243
+ # `GatewayTransport._key`. The workspace alone, not the whole block --
1244
+ # the block holds tuning that an operator changes in response to a
1245
+ # failure, and `wait_s` is the first thing they would raise after a 202.
1246
+ # Hashing that in would mean the fix for a pending part changes the key
1247
+ # of the parts that already arrived and posts them again, which is the
1248
+ # outcome the key exists to prevent. `cli.py` injects `_workspace` into
1249
+ # every destination block, and two destinations in one workspace are
1250
+ # told apart by the footer in the seed.
1251
+ fingerprint = _short_digest(str(cfg.get("_workspace") or ""))
1252
+ token = _read_token_file(token_file, label)
1253
+ retval = GatewayTransport(
1254
+ base_url=url,
1255
+ conversation=conversation,
1256
+ token=token,
1257
+ label=message_label,
1258
+ wait_s=wait_s,
1259
+ timeout=timeout,
1260
+ fingerprint=fingerprint,
1261
+ repeats=repeats,
1262
+ )
1263
+ if _bytes(message_label) > _MAX_LABEL_BYTES:
1264
+ # Bounded rather than merely checked for leaving a positive remainder.
1265
+ # A limit a little above the marker reservation is not safe: once a
1266
+ # message needs more than one part the splitter re-splits at
1267
+ # `limit - _MARKER_ROOM`, so a remainder of a few dozen bytes yields
1268
+ # parts of one or two characters, each of which passes every per-part
1269
+ # check while one message becomes hundreds of them and the run reports
1270
+ # success. A label is a prefix on every message, not content, so the
1271
+ # honest bound is on the label itself.
1272
+ raise RuntimeError(
1273
+ f"{label}: gateway 'label' is {_bytes(message_label)} bytes, over the "
1274
+ f"{_MAX_LABEL_BYTES} allowed. It is prefixed to every message and comes out of "
1275
+ f"the same {SIGNAL_MESSAGE_LIMIT}-byte limit, and a label long enough to crowd "
1276
+ f"the message splits one into hundreds of tiny ones that each look fine"
1277
+ )
1278
+ return retval
1279
+
1280
+
1281
+ def transport_from_config(cfg: dict, label: str, timeout: int = 120) -> Transport:
1282
+ """Build the transport a destination block asks for.
1283
+
1284
+ Two kinds. `transport: gateway` sends through the gateway service, which
1285
+ owns the account; anything else drives the signal-cli binary directly. They are
1286
+ exclusive, not layered: only one process can hold a Signal account, so the
1287
+ cutover is a config flip rather than a fallback chain, and a fallback would
1288
+ be a second process trying to open an account the gateway already has.
1289
+
1290
+ For the subprocess transport both values are named by env var, never
1291
+ written in config: the account is a phone number and the group id
1292
+ identifies a private conversation, and this repo's examples are public.
1293
+ """
1294
+ kind = str(cfg.get("transport") or "signal-cli")
1295
+ if kind == "gateway":
1296
+ retval = _gateway_from_config(cfg, label, timeout)
1297
+ return retval
1298
+ if kind != "signal-cli":
1299
+ raise RuntimeError(
1300
+ f"{label}: unknown transport {kind!r}; it is 'signal-cli' or 'gateway'"
1301
+ )
1302
+ account_env = cfg.get("account_env")
1303
+ group_env = cfg.get("group_id_env")
1304
+ if not account_env or not group_env:
1305
+ raise RuntimeError(
1306
+ f"{label} needs 'account_env' and 'group_id_env', each naming an environment "
1307
+ "variable: the registered Signal number (E.164, e.g. +15551234567) and the "
1308
+ "target group id from `signal-cli listGroups -d`"
1309
+ )
1310
+ account = os.environ.get(str(account_env), "")
1311
+ group_id = os.environ.get(str(group_env), "")
1312
+ missing = [
1313
+ name for name, value in ((account_env, account), (group_env, group_id)) if not value
1314
+ ]
1315
+ if missing:
1316
+ raise RuntimeError(f"{label}: unset or empty: {', '.join(str(m) for m in missing)}")
1317
+ binary = str(cfg.get("binary") or "signal-cli")
1318
+ if not shutil.which(binary):
1319
+ raise RuntimeError(
1320
+ f"{label}: {binary!r} is not on PATH. The Signal destination drives the "
1321
+ "signal-cli binary (brew install signal-cli), against an account this "
1322
+ "deployment has registered"
1323
+ )
1324
+ retval = SignalTransport(account=account, group_id=group_id, binary=binary, timeout=timeout)
1325
+ return retval
1326
+
1327
+
1328
+ def post_message(
1329
+ transport: Transport,
1330
+ text: str,
1331
+ footer: str = "",
1332
+ limit: int | None = None,
1333
+ seed: str = "",
1334
+ ) -> list[int | str]:
1335
+ """Post Markdown to Signal, splitting it if it is too long.
1336
+
1337
+ Returns the handle of every message sent, in order -- a Signal timestamp
1338
+ from the subprocess transport, a gateway `message_id` from the gateway
1339
+ one, and a zero for a message that went out under an id the transport did
1340
+ not report.
1341
+
1342
+ `seed` is a caller-stable id for the message -- a signal's `id`, not
1343
+ anything derived from the rendered text -- and each part is sent under
1344
+ `<seed>@<footer digest>#<number>-of-<total>`. A transport that
1345
+ deduplicates resubmits uses it to recognise a part it has already taken,
1346
+ which the text cannot do here because a retry re-scores and the score's
1347
+ reasons are rendered into it. The total is part of it so that a retry
1348
+ which splits differently is a different message rather than a partial
1349
+ match, and the footer tells two destinations apart; see
1350
+ `GatewayTransport._key` for what each of those prevents. The footer rides on
1351
+ each part, as it does on Slack, because a standing line that appears on
1352
+ only the last part of three is a line a reader can miss -- and it is
1353
+ appended after the conversion, so it arrives as the characters it was
1354
+ written with.
1355
+ """
1356
+ limit = transport.limit if limit is None else limit
1357
+ check_footer(footer, limit=limit)
1358
+ rendered, ranges = to_signal(text)
1359
+ tail = f"\n{footer}" if footer else ""
1360
+ room = limit - _bytes(tail)
1361
+ pieces = _split_bytes(rendered, room)
1362
+ if len(pieces) > 1:
1363
+ # Numbering costs room, so the split is redone with space for the
1364
+ # marker rather than letting it push a part over the limit.
1365
+ pieces = _split_bytes(rendered, room - _MARKER_ROOM)
1366
+ total = len(pieces)
1367
+ timestamps: list[int | str] = []
1368
+ for number, (piece, offset) in enumerate(pieces, 1):
1369
+ body = piece
1370
+ styles = _clip(ranges, offset, _units(piece))
1371
+ if total > 1:
1372
+ marker = f"\n(part {number} of {total})"
1373
+ styles.append((_units(body) + 1, _units(marker) - 1, ITALIC))
1374
+ body += marker
1375
+ body += tail
1376
+ if _bytes(body) > limit:
1377
+ # Every reservation above -- the footer, the marker, the join
1378
+ # between paragraphs -- is arithmetic that can be wrong. This
1379
+ # measures the assembled part instead of predicting it, so a slip
1380
+ # is a loud failure naming the size rather than a message Signal
1381
+ # rejects or truncates without saying so.
1382
+ raise SignalSendError(
1383
+ f"signal message part {number} of {total} assembled to {_bytes(body)} "
1384
+ f"bytes, over the {limit}-byte limit; refusing to send it"
1385
+ )
1386
+ try:
1387
+ timestamps.append(
1388
+ transport.send(
1389
+ body,
1390
+ styles,
1391
+ f"{seed}@{_short_digest(footer)}#{number}-of-{total}" if seed else "",
1392
+ )
1393
+ )
1394
+ except SignalSendError as exc:
1395
+ if timestamps:
1396
+ # The same class, not a fixed one: a part left pending by the
1397
+ # gateway and a part refused outright are different answers,
1398
+ # and a caller deciding whether to retry needs the one it
1399
+ # got. Flattening both to `SignalCliError` here would tell a
1400
+ # retrying caller that a message still in flight had failed,
1401
+ # and "failed" is the word that stops it resubmitting.
1402
+ resubmit = (
1403
+ "Resubmitting does not repeat the parts that arrived, as long as the "
1404
+ "retry splits into the same number of parts: their idempotency keys "
1405
+ "name that total, so a retry whose text renders shorter or longer is "
1406
+ "a different message and does post them again"
1407
+ if getattr(transport, "idempotent", False)
1408
+ else "Resubmitting repeats the parts that did reach the group, because "
1409
+ "this transport has no idempotency key for the far side to match"
1410
+ )
1411
+ raise type(exc)(
1412
+ f"part {number} of {total} did not go out after {len(timestamps)} of "
1413
+ f"them reached the group, which now holds an incomplete message. "
1414
+ f"{resubmit}: {exc}"
1415
+ ) from exc
1416
+ raise
1417
+ retval = timestamps
1418
+ return retval