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,461 @@
1
+ """Slack destination — the v1 reference Destination implementation (issue #3).
2
+
3
+ Tiered routing, carried over from hq/leads/signals/config.yaml, expressed as the
4
+ `routes` list the scaffolded example config already declared:
5
+
6
+ destination:
7
+ type: slack
8
+ routes:
9
+ - min_score: 30
10
+ webhook_env: SLACK_LEADS_WEBHOOK_URL
11
+ channel: "#leads"
12
+ - min_score: 10
13
+ webhook_env: SLACK_FIREHOSE_WEBHOOK_URL
14
+ channel: "#leads-firehose"
15
+
16
+ A signal is delivered to the **highest** route it qualifies for, and only that
17
+ one — a hot lead is not also firehosed, because double-posting the best signals
18
+ is how you train yourself to ignore a channel.
19
+
20
+ One route is a perfectly good configuration: that is the single-channel
21
+ behaviour most agents here use.
22
+
23
+ Credentials come from the environment, never from config: a route names its own
24
+ env var via `webhook_env` or `bot_token_env`. That keeps live webhooks and
25
+ tokens out of git — the failure this repo already had to clean up twice
26
+ (issue #7).
27
+
28
+ A route posts either through an incoming webhook (`webhook_env`) or through
29
+ `chat.postMessage` (`bot_token_env` plus `channel_id`), exactly one of the two
30
+ (issue #86). The API form is what makes `username` and `icon_emoji` work at
31
+ all: a modern incoming webhook ignores both, so two agents sharing one webhook
32
+ arrive under the same name however they are configured. A destination-level
33
+ `bot_token_env` is the default for every route, so one token can serve several
34
+ routes that each name their own `channel_id`.
35
+
36
+ Slack incoming webhooks are bound to a channel when they are created, so with
37
+ `webhook_env` the `channel` key is a label for humans reading the config, not
38
+ routing. With `bot_token_env` the routing is `channel_id`, and `channel` stays
39
+ the label.
40
+
41
+ Two per-route keys shape what a message says (issue #64). Both may also be set
42
+ once at the top level of the destination block, where they are the default for
43
+ every route that does not set its own; the flat single-route form reads them
44
+ from the same place it reads `webhook_env`.
45
+
46
+ username the name this route's messages are posted under, and
47
+ icon_emoji the icon beside them (`:rocket:`, with the colons) or
48
+ icon_url an image url instead. Unset means Slack uses the webhook's
49
+ own identity, exactly as before. Several agents post through
50
+ one webhook, so without these two digests landing seconds
51
+ apart read as one message (issue #77).
52
+ footer a string appended verbatim as the last line of every message
53
+ this route sends, streamed or batched. It exists for standing
54
+ lines that must appear on every message, so nothing here
55
+ wraps, truncates or formats it, and no other key can suppress
56
+ it. Empty (the default) appends nothing.
57
+ show_reasons render `ScoredSignal.reasons` as a bulleted block under the
58
+ score. Default true: both scorers fill `reasons` in (the llm
59
+ scorer puts its rationale and the answering model there), and
60
+ a lead posted without them is harder to triage. A signal with
61
+ no reasons renders exactly as it did before this key existed,
62
+ and so does any signal under `show_reasons: false`.
63
+
64
+ Message text is Markdown on the way in and mrkdwn on the way out: it goes
65
+ through `framework.slack.post_message`, which converts it and splits a message
66
+ over the block limit into several, in order (issue #73). That is why the header
67
+ here is written `**[42]**` and not `*[42]*` — the text this module builds is
68
+ Markdown like everything else it carries, and the one post site renders it.
69
+
70
+ Sheets/email destinations are explicitly out of scope for v1.
71
+
72
+ Contract: see docs/PLUGIN-CONTRACT.md — routing and gating are the
73
+ destination's job, not the framework's.
74
+ """
75
+ from __future__ import annotations
76
+
77
+ import re
78
+
79
+ from framework.interfaces import Destination, ScoredSignal
80
+ from framework.drafter import DraftError, Drafter, build_drafter
81
+ from framework.llm import LLMError
82
+ from framework.registry import register_destination
83
+ from framework.slack import (
84
+ SlackIdentity,
85
+ SlackTransport,
86
+ check_footer,
87
+ identity_from_config,
88
+ post_message,
89
+ transport_from_config,
90
+ )
91
+
92
+
93
+ class _Route:
94
+ def __init__(
95
+ self,
96
+ transport: SlackTransport,
97
+ min_score: int,
98
+ channel_label: str = "",
99
+ footer: str = "",
100
+ show_reasons: bool = True,
101
+ identity: SlackIdentity | None = None,
102
+ ):
103
+ self.transport = transport
104
+ self.min_score = min_score
105
+ self.channel_label = channel_label
106
+ self.footer = footer
107
+ self.show_reasons = show_reasons
108
+ self.identity = identity or SlackIdentity()
109
+
110
+
111
+ # Slack's own escapes, plus the Markdown construction `framework/slack.py`
112
+ # turns into a link. `](` is broken rather than dropped so the text a human
113
+ # reads still says what the page said.
114
+ _LITERAL = ((" & ", " &amp; "), ("<", "&lt;"), (">", "&gt;"), ("](", "] ("))
115
+
116
+ # Emphasis markers are removed rather than escaped, because mrkdwn has no escape
117
+ # for them. Left in, a title can echo one of our own labels in our own italics
118
+ # and so appear to be a line this agent wrote.
119
+ _MARKUP = str.maketrans("", "", "_*`")
120
+
121
+ # Slack auto-links a bare URL whatever the surrounding markup, so a url in
122
+ # source-provided text would be clickable even with every marker escaped. The
123
+ # one link in this message is the one built from `parent_url`.
124
+ _URL_RE = re.compile(r"\b[a-zA-Z][a-zA-Z0-9+.-]*://\S+")
125
+
126
+
127
+ def _literal(value: object) -> str:
128
+ """Source-provided text, rendered as text and never as markup (issue #151).
129
+
130
+ Whitespace is collapsed, because these values sit on a labelled single line
131
+ and a newline would let one pose as a line of our own. Even flattened, a
132
+ value can still echo a label inline, which is why the emphasis markers go
133
+ too: what a reader sees in italics is then only what this agent wrote.
134
+ """
135
+ text = " ".join(str(value or "").split())
136
+ text = _URL_RE.sub("[link removed]", text)
137
+ text = text.translate(_MARKUP)
138
+ for mark, replacement in _LITERAL:
139
+ text = text.replace(mark, replacement)
140
+ retval = text.strip()
141
+ return retval
142
+
143
+
144
+ class SlackDestination:
145
+ def __init__(
146
+ self,
147
+ routes: list[_Route],
148
+ timeout: int = 30,
149
+ mode: str = "stream",
150
+ drafter: Drafter | None = None,
151
+ ):
152
+ if mode not in ("stream", "batch"):
153
+ raise ValueError(f"slack destination: mode must be 'stream' or 'batch', got {mode!r}")
154
+ # Highest bar first, so the first match wins and a hot signal is not
155
+ # also sent to the firehose.
156
+ self._routes = sorted(routes, key=lambda r: r.min_score, reverse=True)
157
+ self._timeout = timeout
158
+ self._mode = mode
159
+ self._drafter = drafter
160
+ self._buffered: dict[int, list[str]] = {}
161
+
162
+ def _format(self, route: _Route, scored: ScoredSignal, compact: bool = False) -> str:
163
+ """Render one signal.
164
+
165
+ Streaming keeps the full `signal.text` — that is what deployed agents
166
+ already post, and changing it would silently alter their output.
167
+ Batching uses `meta.title` when a source provides one, because ten full
168
+ post bodies in a single Slack message is unreadable. Sources without a
169
+ title fall back to the full text either way.
170
+
171
+ The reasons block follows the url, in both modes: it is two short lines
172
+ that say why this signal scored what it did, which is exactly what a
173
+ batched list of ten is otherwise missing. It is separated by a blank
174
+ line and set in italics, because it is the one part of the message the
175
+ agent wrote rather than quoted, and a reader skimming a channel has to
176
+ be able to tell those apart without re-reading.
177
+ """
178
+ sig = scored.signal
179
+ meta = sig.meta if isinstance(sig.meta, dict) else {}
180
+ body = sig.text
181
+ if compact and meta.get("title"):
182
+ body = meta["title"]
183
+ text = f"**[{scored.score}]** {body}"
184
+ parent_url = str(meta.get("parent_url") or "").strip()
185
+ if parent_url:
186
+ # A comment-level lead: the signal's own url IS the parent page, so
187
+ # posting it bare would read as the lead's source. See below.
188
+ text += self._comment_context(meta, parent_url)
189
+ elif sig.url:
190
+ text += f"\n{sig.url}"
191
+ if route.show_reasons and scored.reasons:
192
+ # A blank line and italics, because the two halves of this message
193
+ # have different authors. Everything above is the poster's own
194
+ # words; everything below is ours about them. Run together on
195
+ # consecutive lines they read as one block, and an operator
196
+ # skimming a channel cannot tell which sentences to trust as
197
+ # quotation and which to read as judgement.
198
+ text += "\n\n" + "\n".join(f"• _{reason}_" for reason in scored.reasons)
199
+ if self._drafter is not None and not compact:
200
+ text += "\n\n" + self._draft_block(scored)
201
+ return text
202
+
203
+ def _draft_block(self, scored: ScoredSignal) -> str:
204
+ """The drafted sections, or a visible note saying why there are none.
205
+
206
+ A failed draft never costs the lead. The signal is the thing worth
207
+ having, and dropping a real lead because a second model call misfired
208
+ would be a bad trade -- but a lead that looked complete while silently
209
+ carrying no draft would be worse than either, so the reason is rendered
210
+ exactly where the draft would have been.
211
+ """
212
+ try:
213
+ drafted = self._drafter.draft(scored)
214
+ except (DraftError, LLMError) as exc:
215
+ retval = f"_draft unavailable — {str(exc)[:200]}_"
216
+ return retval
217
+ parts = []
218
+ for name, value in drafted.items():
219
+ label = name.replace("_", " ")
220
+ parts.append(f"*{label}*\n{value}")
221
+ retval = "\n\n".join(parts)
222
+ return retval
223
+
224
+ def _post(self, route: _Route, text: str) -> None:
225
+ post_message(
226
+ route.transport,
227
+ text,
228
+ timeout=self._timeout,
229
+ footer=route.footer,
230
+ identity=route.identity,
231
+ )
232
+
233
+ def _route_for(self, scored: ScoredSignal) -> _Route | None:
234
+ for route in self._routes:
235
+ if scored.score >= route.min_score:
236
+ return route
237
+ return None
238
+
239
+ def _comment_context(self, meta: dict, parent_url: str) -> str:
240
+ """The lines that make a comment-level lead readable (issue #151).
241
+
242
+ A signal carrying `parent_url` is a comment under someone else's post
243
+ (issues #138, #147): the comment is the lead and the page is context.
244
+ Rendered as the page's own url -- which is what every other signal's url
245
+ means -- the message reads as though the vendor who wrote the post were
246
+ the lead. So the link is labelled as the post being replied to, and the
247
+ commenter's self-identification is named next to it.
248
+
249
+ Two people appear in this message and they are not the same person.
250
+ #138's verification is exactly that a reader can tell them apart, which
251
+ is why the label says "someone else's post" rather than just linking it.
252
+
253
+ Keyed on meta, never on a source or a platform: any source setting these
254
+ keys gets this rendering, and a signal without `parent_url` is untouched.
255
+
256
+ Every value here is quoted from a page somebody else wrote, so it is
257
+ rendered as literal text rather than as markup. A parent title is a
258
+ natural place for an attacker to put `[click here](https://elsewhere)`:
259
+ `framework/slack.py` turns that into a real Slack link, and it would
260
+ appear under our own "parent post" label, in a message whose whole
261
+ purpose is to tell an operator where a lead came from. The genuine URL
262
+ is the only link this renders, and it is built here rather than taken
263
+ from the text.
264
+ """
265
+ lines = []
266
+ business = _literal(meta.get("business"))
267
+ phrase = _literal(meta.get("phrase"))
268
+ if business:
269
+ lines.append(f"_The commenter:_ {business}")
270
+ elif phrase:
271
+ # The phrase that matched is the evidence of self-identification,
272
+ # and it is what a reader checks first: a lead found by "I own a"
273
+ # is a different claim from one found by "we are a small".
274
+ lines.append(f'_The commenter self-identified with_ "{phrase}"')
275
+ title = _literal(meta.get("parent_title"))
276
+ lines.append(
277
+ f"_Comment under someone else's post:_ {title + ' — ' if title else ''}{parent_url}"
278
+ )
279
+ retval = "\n" + "\n".join(lines)
280
+ return retval
281
+
282
+ def accepts(self, scored: ScoredSignal) -> bool:
283
+ """Whether any route would post this signal. No model call, no post.
284
+
285
+ For the `approval` destination's signal mode (issue #65), which gates
286
+ on this before it ranks and caps, so the drafter is only asked about
287
+ signals that will actually be proposed.
288
+ """
289
+ retval = self._route_for(scored) is not None
290
+ return retval
291
+
292
+ def render_signal(self, scored: ScoredSignal) -> dict | None:
293
+ """One signal as this destination would stream it, without posting it.
294
+
295
+ Returns `{"text", "footer"}` for the route it qualifies for, or None
296
+ when it qualifies for none. The text is exactly the streamed message,
297
+ draft included, so a lead looks the same whether it is posted plainly
298
+ or as a proposal (issue #65); the footer is kept apart because the
299
+ caller posts through its own transport and appends it itself.
300
+ """
301
+ route = self._route_for(scored)
302
+ if route is None:
303
+ return None
304
+ retval = {"text": self._format(route, scored), "footer": route.footer}
305
+ return retval
306
+
307
+ def send(self, scored: ScoredSignal) -> None:
308
+ route = self._route_for(scored)
309
+ if route is None:
310
+ return
311
+ if self._mode == "stream":
312
+ self._post(route, self._format(route, scored))
313
+ return
314
+ self._buffered.setdefault(id(route), []).append(
315
+ self._format(route, scored, compact=True)
316
+ )
317
+
318
+ def flush(self) -> None:
319
+ """Emit one message per route in batch mode. No-op when streaming."""
320
+ if self._mode != "batch":
321
+ return
322
+ for route in self._routes:
323
+ lines = self._buffered.get(id(route))
324
+ if not lines:
325
+ continue
326
+ header = f"**{len(lines)} signal(s)**"
327
+ if route.channel_label:
328
+ header += f" — {route.channel_label}"
329
+ self._post(route, header + "\n\n" + "\n\n".join(lines))
330
+ self._buffered.clear()
331
+
332
+
333
+ _TRANSPORT_KEYS = ("webhook_env", "bot_token_env", "channel_id")
334
+
335
+
336
+ def _transport_cfg(cfg: dict, defaults: dict) -> dict:
337
+ """A route's transport keys, falling back to the destination-level ones.
338
+
339
+ One bot token named once at the top, with a `channel_id` per route, is the
340
+ shape a two-tier agent wants; a route naming its own `webhook_env` still
341
+ overrides all of it.
342
+ """
343
+ retval = {key: cfg[key] for key in _TRANSPORT_KEYS if key in cfg}
344
+ if not any(key in retval for key in ("webhook_env", "bot_token_env")):
345
+ retval = {key: defaults[key] for key in _TRANSPORT_KEYS if key in defaults} | retval
346
+ return retval
347
+
348
+
349
+ def _footer(cfg: dict, label: str, default: str) -> str:
350
+ """`footer` for this route, falling back to the destination-level one."""
351
+ value = cfg.get("footer", default)
352
+ if not isinstance(value, str):
353
+ raise ValueError(f"slack destination: {label} 'footer' must be a string, got {value!r}")
354
+ # Here rather than only at post time: a footer too long to leave room for a
355
+ # message is knowable before the run fetches, scores or asks a model
356
+ # anything, and this names the config key that has to change.
357
+ check_footer(value, f"slack destination: {label} 'footer'")
358
+ return value
359
+
360
+
361
+ def _show_reasons(cfg: dict, label: str, default: bool) -> bool:
362
+ """`show_reasons` for this route, falling back to the destination-level one.
363
+
364
+ Only a real boolean: a string "false" is a config typo that would otherwise
365
+ turn the block on and read as if the operator had turned it off.
366
+ """
367
+ value = cfg.get("show_reasons", default)
368
+ if not isinstance(value, bool):
369
+ raise ValueError(
370
+ f"slack destination: {label} 'show_reasons' must be true or false, got {value!r}"
371
+ )
372
+ return value
373
+
374
+
375
+ def _build_route(
376
+ cfg: dict,
377
+ label: str,
378
+ footer: str = "",
379
+ show_reasons: bool = True,
380
+ identity: SlackIdentity | None = None,
381
+ timeout: int = 30,
382
+ transport_defaults: dict | None = None,
383
+ ) -> _Route:
384
+ retval = _Route(
385
+ transport=transport_from_config(
386
+ _transport_cfg(cfg, transport_defaults or {}),
387
+ f"slack destination: {label}",
388
+ timeout,
389
+ ),
390
+ min_score=int(cfg.get("min_score", 0)),
391
+ channel_label=cfg.get("channel", ""),
392
+ footer=_footer(cfg, label, footer),
393
+ show_reasons=_show_reasons(cfg, label, show_reasons),
394
+ identity=identity_from_config(cfg, f"slack destination: {label}", identity),
395
+ )
396
+ return retval
397
+
398
+
399
+ _DRAFT_RESERVED = frozenset({"grounding", "max_grounding_chars", "prompt", "fields", "system",
400
+ "max_signal_chars", "llm", "_comment", "_workspace", "_root"})
401
+
402
+
403
+ def _build_drafter(cfg: dict) -> Drafter | None:
404
+ """The optional `drafter` block (issue #83), or None.
405
+
406
+ Only `mode: stream` renders a draft: a batched message is a compact list of
407
+ many signals, and a per-signal draft inside one would be unreadable and
408
+ would cost one model call per line of it.
409
+ """
410
+ block = cfg.get("drafter")
411
+ if block is None:
412
+ return None
413
+ if not isinstance(block, dict):
414
+ raise RuntimeError("slack destination: 'drafter' must be an object")
415
+ if cfg.get("mode", "stream") != "stream":
416
+ raise RuntimeError(
417
+ "slack destination: 'drafter' needs mode 'stream'; a batched message is a "
418
+ "compact list of many signals, and a draft per line would be unreadable"
419
+ )
420
+
421
+ retval = build_drafter(block, "slack destination", cfg.get("_workspace"), cfg.get("_root"))
422
+ return retval
423
+
424
+
425
+ @register_destination("slack")
426
+ def build(cfg: dict) -> Destination:
427
+ timeout = int(cfg.get("timeout", 30))
428
+ footer = _footer(cfg, "destination", "")
429
+ show_reasons = _show_reasons(cfg, "destination", True)
430
+ identity = identity_from_config(cfg, "slack destination", None)
431
+ declared = cfg.get("routes")
432
+ if isinstance(declared, list) and declared:
433
+ routes = [
434
+ _build_route(
435
+ r,
436
+ r.get("channel") or f"route[{i}]",
437
+ footer,
438
+ show_reasons,
439
+ identity,
440
+ timeout,
441
+ cfg,
442
+ )
443
+ for i, r in enumerate(declared)
444
+ ]
445
+ else:
446
+ # Flat single-route form, for agents that only ever post to one channel.
447
+ routes = [
448
+ _build_route(
449
+ cfg, cfg.get("channel") or "destination", footer, show_reasons, identity, timeout
450
+ )
451
+ ]
452
+
453
+ drafter = _build_drafter(cfg)
454
+
455
+ retval = SlackDestination(
456
+ routes=routes,
457
+ timeout=timeout,
458
+ mode=cfg.get("mode", "stream"),
459
+ drafter=drafter,
460
+ )
461
+ return retval
@@ -0,0 +1,137 @@
1
+ """Slack-draft action: draft from grounding on approval, post it for a human to use (issue #76).
2
+
3
+ The drafter (framework/drafter.py) normally runs at post time, under every
4
+ lead. Some drafts should cost a model call only when someone asks for one --
5
+ a job application, say, which is long and wanted for a few leads a week. This
6
+ step runs the same grounded drafter when the proposal is approved and posts
7
+ the result to Slack, where a person reads it, edits it and uses it by hand.
8
+ Nothing is submitted anywhere: the output of this step is a message.
9
+
10
+ {"type": "slack-draft",
11
+ "bot_token_env": "SOME_BOT_TOKEN",
12
+ "channel_id": "C0123456789",
13
+ "title": "Draft application: {title}",
14
+ "drafter": {"prompt": "...", "fields": {...}, "grounding": ["..."]},
15
+ "verbatim": [{"label": "Disclosure (include or omit: your call)",
16
+ "text": "..."}]}
17
+
18
+ Config keys:
19
+
20
+ drafter a drafter block, the same shape the slack destination takes:
21
+ `prompt`, `fields`, `grounding` (read at build time, so a missing
22
+ file fails `agent approvals` at startup rather than on a click),
23
+ optional `max_grounding_chars`, `system`, `llm`.
24
+ title the message's first line, templated against the payload. Default
25
+ "Draft: {title}". The payload's `url` follows it on its own line.
26
+ verbatim optional list of `{label, text}`, appended after the drafted
27
+ fields exactly as written. For text that must never be
28
+ paraphrased (a disclosure, a fixed sign-off): it does not go
29
+ through the model, so the model cannot reword it, and showing it
30
+ apart from the draft leaves including it a human decision.
31
+
32
+ The signal comes from the proposal's payload, as the approval destination's
33
+ signal mode records it (issue #65): `text`, `url`, `score`, `reasons`, `meta`.
34
+
35
+ A draft that fails fails the step, unlike at post time. There the lead is the
36
+ thing worth keeping, so a missing draft is a note under it; here the draft is
37
+ the whole job, and a click that produced nothing must say so. The approvals
38
+ pass reports the failure in the channel.
39
+
40
+ Returns `{"drafted": <field names, comma-separated>}`.
41
+
42
+ Contract: see docs/PLUGIN-CONTRACT.md.
43
+ """
44
+ from __future__ import annotations
45
+
46
+ from pathlib import Path
47
+ from typing import Any
48
+
49
+ from framework.drafter import drafter_inputs, drafter_with_llm
50
+ from framework.interfaces import Action, ScoredSignal, Signal
51
+ from framework.registry import register_action
52
+ from framework.slack import SlackTransport, post_message, transport_from_config
53
+ from framework.templating import render_template
54
+
55
+ _LABEL = "slack-draft action"
56
+
57
+
58
+ class SlackDraftAction:
59
+ def __init__(
60
+ self,
61
+ transport: SlackTransport,
62
+ block: dict,
63
+ inputs: dict[str, Any],
64
+ title: str,
65
+ verbatim: list[dict[str, str]],
66
+ timeout: int = 30,
67
+ ):
68
+ self._transport = transport
69
+ self._block = block
70
+ self._inputs = inputs
71
+ self._title = title
72
+ self._verbatim = verbatim
73
+ self._timeout = timeout
74
+
75
+ def execute(self, payload: dict[str, Any], context: dict[str, Any]) -> dict[str, Any]:
76
+ workspace = context.get("workspace")
77
+ root = Path(workspace).parent if workspace else None
78
+ drafter = drafter_with_llm(self._block, self._inputs, _LABEL, workspace, root)
79
+ meta = payload.get("meta")
80
+ signal = Signal(
81
+ id=str((meta or {}).get("id") or payload.get("url") or ""),
82
+ text=str(payload.get("text") or ""),
83
+ url=str(payload.get("url") or ""),
84
+ source="proposal",
85
+ meta=meta if isinstance(meta, dict) else {},
86
+ )
87
+ reasons = payload.get("reasons")
88
+ scored = ScoredSignal(
89
+ signal=signal,
90
+ score=int(payload.get("score") or 0),
91
+ reasons=list(reasons) if isinstance(reasons, list) else [],
92
+ )
93
+ drafted = drafter.draft(scored)
94
+
95
+ parts = [f"**{render_template(self._title, payload)}**"]
96
+ if signal.url:
97
+ parts[0] += f"\n{signal.url}"
98
+ for name, value in drafted.items():
99
+ parts.append(f"*{name.replace('_', ' ')}*\n{value}")
100
+ for item in self._verbatim:
101
+ parts.append(f"*{item['label']}*\n{item['text']}")
102
+ post_message(self._transport, "\n\n".join(parts), timeout=self._timeout)
103
+ retval = {"drafted": ", ".join(drafted)}
104
+ return retval
105
+
106
+
107
+ def _verbatim(cfg: dict) -> list[dict[str, str]]:
108
+ items = cfg.get("verbatim") or []
109
+ if not isinstance(items, list):
110
+ raise RuntimeError(f"{_LABEL}: 'verbatim' must be a list of {{label, text}}")
111
+ for item in items:
112
+ if not (
113
+ isinstance(item, dict)
114
+ and isinstance(item.get("label"), str) and item["label"].strip()
115
+ and isinstance(item.get("text"), str) and item["text"].strip()
116
+ ):
117
+ raise RuntimeError(f"{_LABEL}: every 'verbatim' entry needs a non-empty 'label' and 'text'")
118
+ retval = [{"label": i["label"], "text": i["text"]} for i in items]
119
+ return retval
120
+
121
+
122
+ @register_action("slack-draft")
123
+ def build(cfg: dict) -> Action:
124
+ timeout = int(cfg.get("timeout", 30))
125
+ transport = transport_from_config(cfg, _LABEL, timeout)
126
+ block = cfg.get("drafter")
127
+ if not isinstance(block, dict):
128
+ raise RuntimeError(f"{_LABEL} needs a 'drafter' block")
129
+ retval = SlackDraftAction(
130
+ transport=transport,
131
+ block=block,
132
+ inputs=drafter_inputs(block, _LABEL),
133
+ title=str(cfg.get("title") or "Draft: {title}"),
134
+ verbatim=_verbatim(cfg),
135
+ timeout=timeout,
136
+ )
137
+ return retval
@@ -0,0 +1,65 @@
1
+ """Slack-post action: post a templated line to Slack (issue #21).
2
+
3
+ The first action plugin, and the one that closes the loop on an approved
4
+ proposal: `Published: {url}` into the team channel once the publish step has
5
+ returned a `url`. One step in an action's `steps` list:
6
+
7
+ {"type": "slack-post", "webhook_env": "SOME_WEBHOOK", "text": "Published: {url}"}
8
+
9
+ or, to post under the agent's own name through the Web API (issue #86):
10
+
11
+ {"type": "slack-post", "bot_token_env": "SOME_BOT_TOKEN",
12
+ "channel_id": "C0123456789", "text": "Published: {url}"}
13
+
14
+ `text` is rendered against the merged payload (the proposal's content plus
15
+ every earlier step's result) with `framework.templating.render_template`, so a
16
+ placeholder with no value fails the step rather than posting a blank. An
17
+ incoming webhook is bound to a channel when Slack issues it, which is why
18
+ `channel_id` belongs to the bot-token form only.
19
+
20
+ The line goes out through `framework.slack.post_message` like every other
21
+ Slack post here, so a `text` holding a Markdown link arrives clickable rather
22
+ than as literal brackets (issue #73). A plain line is posted unchanged.
23
+
24
+ Returns an empty dict. A webhook answers `ok` and nothing else; the Web API
25
+ answers with a message `ts`, but a line announcing a published post is not
26
+ something a later step edits, so nothing is published by name.
27
+
28
+ Contract: see docs/PLUGIN-CONTRACT.md.
29
+ """
30
+ from __future__ import annotations
31
+
32
+ from typing import Any
33
+
34
+ from framework.interfaces import Action
35
+ from framework.registry import register_action
36
+ from framework.slack import SlackTransport, post_message, transport_from_config
37
+ from framework.templating import render_template
38
+
39
+
40
+ class SlackPostAction:
41
+ def __init__(self, transport: SlackTransport, text: str, timeout: int = 30):
42
+ self._transport = transport
43
+ self._text = text
44
+ self._timeout = timeout
45
+
46
+ def execute(self, payload: dict[str, Any], context: dict[str, Any]) -> dict[str, Any]:
47
+ text = render_template(self._text, payload)
48
+ post_message(self._transport, text, timeout=self._timeout)
49
+ retval: dict[str, Any] = {}
50
+ return retval
51
+
52
+
53
+ @register_action("slack-post")
54
+ def build(cfg: dict) -> Action:
55
+ timeout = int(cfg.get("timeout", 30))
56
+ transport = transport_from_config(cfg, "slack-post action", timeout)
57
+ text = cfg.get("text")
58
+ if not text:
59
+ raise RuntimeError("slack-post action needs a 'text'")
60
+ retval = SlackPostAction(
61
+ transport=transport,
62
+ text=str(text),
63
+ timeout=timeout,
64
+ )
65
+ return retval