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.
- agents_framework-0.3.0.dist-info/METADATA +1364 -0
- agents_framework-0.3.0.dist-info/RECORD +50 -0
- agents_framework-0.3.0.dist-info/WHEEL +5 -0
- agents_framework-0.3.0.dist-info/entry_points.txt +2 -0
- agents_framework-0.3.0.dist-info/licenses/LICENSE +661 -0
- agents_framework-0.3.0.dist-info/top_level.txt +1 -0
- framework/__init__.py +0 -0
- framework/__main__.py +9 -0
- framework/action_page.py +1102 -0
- framework/approval_buttons.py +775 -0
- framework/approvals.py +678 -0
- framework/calendar_card.py +276 -0
- framework/cli.py +273 -0
- framework/codex_llm.py +401 -0
- framework/config.py +126 -0
- framework/drafter.py +263 -0
- framework/interfaces.py +96 -0
- framework/llm.py +744 -0
- framework/plugins/__init__.py +147 -0
- framework/plugins/agentmail_source.py +355 -0
- framework/plugins/approval_destination.py +478 -0
- framework/plugins/command_action.py +248 -0
- framework/plugins/digest_destination.py +546 -0
- framework/plugins/email_destination.py +248 -0
- framework/plugins/fanout_destination.py +160 -0
- framework/plugins/github_org_source.py +226 -0
- framework/plugins/github_releases_source.py +420 -0
- framework/plugins/ics_source.py +594 -0
- framework/plugins/llm_scorer.py +411 -0
- framework/plugins/multi_source.py +241 -0
- framework/plugins/reddit_source.py +625 -0
- framework/plugins/regex_scorer.py +93 -0
- framework/plugins/rss_source.py +346 -0
- framework/plugins/signal_destination.py +133 -0
- framework/plugins/slack_destination.py +461 -0
- framework/plugins/slack_draft_action.py +137 -0
- framework/plugins/slack_post_action.py +65 -0
- framework/plugins/slack_workspace_source.py +992 -0
- framework/plugins/twitter_action.py +210 -0
- framework/plugins/websearch_source.py +761 -0
- framework/plugins/wordpress_action.py +413 -0
- framework/proposals.py +246 -0
- framework/registry.py +166 -0
- framework/runlog.py +125 -0
- framework/runner.py +243 -0
- framework/schedule.py +571 -0
- framework/signal_messenger.py +1418 -0
- framework/slack.py +801 -0
- framework/state.py +39 -0
- framework/templating.py +76 -0
|
@@ -0,0 +1,478 @@
|
|
|
1
|
+
"""Approval destination: turn a run's output into a proposal (issue #21).
|
|
2
|
+
|
|
3
|
+
Wraps another destination and, at `flush()`, records what that destination
|
|
4
|
+
*would* have posted as a pending proposal in `<workspace>/state/proposals.json`
|
|
5
|
+
instead of letting it post. The rendered content goes to a Slack webhook with
|
|
6
|
+
one line per proposed action:
|
|
7
|
+
|
|
8
|
+
Proposal p7-k3f: publish-post. Reply "do p7-k3f" or "skip p7-k3f".
|
|
9
|
+
|
|
10
|
+
A separate `agent approvals` pass (see `framework/approvals.py`) reads the
|
|
11
|
+
channel, finds those replies from trusted users, and runs the action's steps.
|
|
12
|
+
Nothing in this module executes anything.
|
|
13
|
+
|
|
14
|
+
Config block:
|
|
15
|
+
|
|
16
|
+
"destination": {
|
|
17
|
+
"type": "approval",
|
|
18
|
+
"bot_token_env": "SOME_BOT_TOKEN",
|
|
19
|
+
"channel_id": "C0123456789",
|
|
20
|
+
"wrap": {"type": "digest", "...": "the destination whose output becomes the proposal"},
|
|
21
|
+
"actions": ["publish-post"],
|
|
22
|
+
"timeout": 30
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
`wrap` is any destination block; it is built through the registry exactly as a
|
|
26
|
+
top-level destination would be, so its own keys (and its own transport,
|
|
27
|
+
which it still needs to construct) are its business. It must define
|
|
28
|
+
`render() -> dict` with at least `title` and `body_md`; the digest destination
|
|
29
|
+
does (same getattr discovery the runner uses for `flush()`). Wrapping a
|
|
30
|
+
destination that cannot render is a configuration error and fails at build
|
|
31
|
+
time, not at the end of a run that has already fetched and scored.
|
|
32
|
+
|
|
33
|
+
`actions` names entries of the workspace config's top-level `"actions"` map,
|
|
34
|
+
which this destination never reads: it records the name, and the approvals
|
|
35
|
+
pass looks the steps up when a human says `do`. One proposal is recorded per
|
|
36
|
+
name, each with its own id, so a run whose output feeds two actions can have
|
|
37
|
+
one approved and the other skipped.
|
|
38
|
+
|
|
39
|
+
The workspace path is not part of the config block a human writes. The CLI
|
|
40
|
+
injects it as `_workspace` before building, because the registry hands a
|
|
41
|
+
factory only its own block (docs/PLUGIN-CONTRACT.md) and the proposals store
|
|
42
|
+
lives beside the dedupe state, not beside the config. It passes `_workspace`
|
|
43
|
+
and `_root` on to the `wrap` block it builds, since the CLI never sees that one.
|
|
44
|
+
|
|
45
|
+
`buttons: true` (issue #74) posts the proposal as Block Kit with Post, Draft
|
|
46
|
+
and Discard buttons instead of the "reply do/skip" line, one message per named
|
|
47
|
+
action, since a button carries one proposal id. Turn it on together with
|
|
48
|
+
`agent approvals --listen` (framework/approval_buttons.py): without a listener
|
|
49
|
+
holding the Socket Mode connection, the buttons render but no interaction is
|
|
50
|
+
ever delivered. The reply path keeps working either way, and the reply grammar
|
|
51
|
+
is repeated in the message's context line so it is still discoverable.
|
|
52
|
+
`post_label` renames the Post button (an action that drafts for a human wants
|
|
53
|
+
"Draft application", not "Post"), and `draft_button: false` drops the Draft
|
|
54
|
+
button for an action with no WordPress step to draft (issue #76).
|
|
55
|
+
|
|
56
|
+
Two behaviours worth knowing:
|
|
57
|
+
|
|
58
|
+
- A run with nothing to propose (the wrapped `render()` says `empty`) posts
|
|
59
|
+
the wrapped destination's empty message and records nothing. Asking a
|
|
60
|
+
human to approve "Nothing new this run" would train them to type `skip`
|
|
61
|
+
without reading, which defeats the gate.
|
|
62
|
+
- If `render()` raises, the error is posted to the webhook and re-raised.
|
|
63
|
+
The runner then marks nothing seen and the next run re-proposes, which is
|
|
64
|
+
the at-least-once behaviour the rest of the framework has.
|
|
65
|
+
|
|
66
|
+
The proposal message goes out through `framework.slack.post_message`, so the
|
|
67
|
+
drafted Markdown arrives as mrkdwn and a long proposal is split into several
|
|
68
|
+
messages rather than truncated (issue #73). With `buttons: true` the same
|
|
69
|
+
conversion runs before the Block Kit message is built, on the section text and
|
|
70
|
+
on the notification fallback alike, since a human reads both; the blocks carry
|
|
71
|
+
their own length handling, so that path does not split into several messages.
|
|
72
|
+
What is *recorded* is untouched either way: `body_md` in the proposals store
|
|
73
|
+
stays Markdown, because the publish step that later renders it wants Markdown,
|
|
74
|
+
not Slack's dialect. `username` / `icon_emoji` / `icon_url` (issue #77) name
|
|
75
|
+
the proposal's message in both modes.
|
|
76
|
+
|
|
77
|
+
**Announced first, stored second** (issue #73 review). `flush()` reserves each
|
|
78
|
+
proposal's id, posts the announcement, and only then writes the proposals to
|
|
79
|
+
disk, because a long digest is now posted as several messages and a failure
|
|
80
|
+
part-way through used to leave a live, approvable proposal whose instructions
|
|
81
|
+
never reached the channel. In the new order a failed announcement stores
|
|
82
|
+
nothing: the runner marks no signals seen and the next run proposes again. Two
|
|
83
|
+
configured actions are stored in one write (`add_all`), so a run cannot leave
|
|
84
|
+
one of them behind for a retry to duplicate. `buttons: true` posts one message
|
|
85
|
+
per proposal and is held to the same rule: every id is reserved first, every
|
|
86
|
+
message goes out, and only then is anything stored, so a failure on the second
|
|
87
|
+
of two button messages leaves neither clickable rather than one live. The
|
|
88
|
+
accepted cost is the other half of at-least-once — a failure after the last
|
|
89
|
+
part was posted means the channel holds an announcement for a proposal that
|
|
90
|
+
was never stored, and the next run posts a second one with a new id. A stale
|
|
91
|
+
id nobody can act on is a dead message; a live proposal nobody was told how to
|
|
92
|
+
approve is a silent one, and this repo pays for silence.
|
|
93
|
+
|
|
94
|
+
The instruction lines (`Reply "do <id>"`) sit directly under the title, above
|
|
95
|
+
the digest, for the same reason: they have to be in the first message of a
|
|
96
|
+
split, not the last. With `buttons: true` there are no such lines: the buttons
|
|
97
|
+
are the instruction, and the reply grammar already appears once in the context
|
|
98
|
+
line `proposal_blocks` builds.
|
|
99
|
+
|
|
100
|
+
The proposal is the delivery. The runner marks signals seen after `flush()`
|
|
101
|
+
returns, and this `flush()` returns only once the proposal is on disk and
|
|
102
|
+
announced, so the seen-store semantics need no change: an approved-then-failed
|
|
103
|
+
action is a matter for the proposal's own status, not for re-fetching signals.
|
|
104
|
+
|
|
105
|
+
**`mode: "signal"`** (issue #65). The default, `mode: "run"`, is everything
|
|
106
|
+
above: one proposal per action per run, from the wrapped destination's whole
|
|
107
|
+
rendered output. A lead agent needs one proposal per *lead*, so each can be
|
|
108
|
+
approved or skipped on its own. In signal mode the wrapped destination is a
|
|
109
|
+
`slack` destination and is never allowed to post: it is used for two things
|
|
110
|
+
only, its gate (`accepts()`, its routes' `min_score`) and its rendering of one
|
|
111
|
+
lead (`render_signal()`, draft and footer included). So a lead looks exactly as
|
|
112
|
+
it did when the same block was the top-level destination, and moving an agent
|
|
113
|
+
onto approvals changes what can be done with a lead, not how it reads.
|
|
114
|
+
|
|
115
|
+
"destination": {
|
|
116
|
+
"type": "approval",
|
|
117
|
+
"mode": "signal",
|
|
118
|
+
"bot_token_env": "SOME_BOT_TOKEN",
|
|
119
|
+
"channel_id": "C0123456789",
|
|
120
|
+
"buttons": true,
|
|
121
|
+
"max_proposals": 10,
|
|
122
|
+
"wrap": {"type": "slack", "routes": [{"min_score": 60}], "footer": "..."},
|
|
123
|
+
"actions": ["draft-application"]
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
The wrapped block may leave out its transport: it never posts, so it inherits
|
|
127
|
+
this block's `bot_token_env` / `channel_id` / `webhook_env` rather than making
|
|
128
|
+
an operator name one it does not use.
|
|
129
|
+
|
|
130
|
+
At `flush()` the signals the gate accepts are ranked by score and the top
|
|
131
|
+
`max_proposals` (default 10) become proposals, one per configured action, each
|
|
132
|
+
with its own message. The rest are not dropped silently: one closing message
|
|
133
|
+
names how many were left out and lists their links. They are marked seen like
|
|
134
|
+
every other signal, so that message is their only record. A run with nothing
|
|
135
|
+
above the gate posts nothing at all, as a streaming lead agent does.
|
|
136
|
+
|
|
137
|
+
Each proposal's payload is the lead itself, for an action to template from:
|
|
138
|
+
`text`, `url`, `title` (the source's `meta.title`, else the first line of the
|
|
139
|
+
text), `score`, `reasons`, `meta`, and `rendered`, the message as posted. The
|
|
140
|
+
same announce-first, store-second rule holds across the whole run: every id is
|
|
141
|
+
reserved, every message posted, and only then is anything stored, in one
|
|
142
|
+
write.
|
|
143
|
+
"""
|
|
144
|
+
from __future__ import annotations
|
|
145
|
+
|
|
146
|
+
from pathlib import Path
|
|
147
|
+
|
|
148
|
+
import requests
|
|
149
|
+
|
|
150
|
+
from framework.action_page import TOKEN_FIELD, action_url, base_url_for, mint_token
|
|
151
|
+
from framework.approval_buttons import proposal_blocks
|
|
152
|
+
from framework.interfaces import Destination, ScoredSignal
|
|
153
|
+
from framework.proposals import ProposalStore, proposals_path
|
|
154
|
+
from framework.registry import build_destination, register_destination
|
|
155
|
+
from framework.slack import (
|
|
156
|
+
SlackIdentity,
|
|
157
|
+
SlackTransport,
|
|
158
|
+
identity_from_config,
|
|
159
|
+
post_message,
|
|
160
|
+
to_mrkdwn,
|
|
161
|
+
transport_from_config,
|
|
162
|
+
)
|
|
163
|
+
|
|
164
|
+
MODE_RUN = "run"
|
|
165
|
+
MODE_SIGNAL = "signal"
|
|
166
|
+
_DEFAULT_MAX_PROPOSALS = 10
|
|
167
|
+
_TRANSPORT_KEYS = ("webhook_env", "bot_token_env", "channel_id")
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
class ApprovalDestination:
|
|
171
|
+
def __init__(
|
|
172
|
+
self,
|
|
173
|
+
wrapped: Destination,
|
|
174
|
+
actions: list[str],
|
|
175
|
+
store: ProposalStore,
|
|
176
|
+
transport: SlackTransport,
|
|
177
|
+
timeout: int = 30,
|
|
178
|
+
identity: SlackIdentity | None = None,
|
|
179
|
+
buttons: bool = False,
|
|
180
|
+
mode: str = MODE_RUN,
|
|
181
|
+
max_proposals: int = _DEFAULT_MAX_PROPOSALS,
|
|
182
|
+
post_label: str = "Post",
|
|
183
|
+
draft_button: bool = True,
|
|
184
|
+
workspace_name: str = "",
|
|
185
|
+
action_base_url: str = "",
|
|
186
|
+
):
|
|
187
|
+
needed = ("render",) if mode == MODE_RUN else ("accepts", "render_signal")
|
|
188
|
+
missing = [name for name in needed if not callable(getattr(wrapped, name, None))]
|
|
189
|
+
if missing:
|
|
190
|
+
example = "'digest'" if mode == MODE_RUN else "'slack'"
|
|
191
|
+
raise RuntimeError(
|
|
192
|
+
f"approval destination: in mode {mode!r} the wrapped destination "
|
|
193
|
+
f"{type(wrapped).__name__} needs {', '.join(n + '()' for n in missing)}; "
|
|
194
|
+
f"wrap a destination that has it (e.g. {example})"
|
|
195
|
+
)
|
|
196
|
+
self._wrapped = wrapped
|
|
197
|
+
# Looked up once and called through these, as `render` always was: the
|
|
198
|
+
# Destination protocol declares none of the three.
|
|
199
|
+
self._render = getattr(wrapped, "render", None)
|
|
200
|
+
self._accepts = getattr(wrapped, "accepts", None)
|
|
201
|
+
self._render_signal = getattr(wrapped, "render_signal", None)
|
|
202
|
+
self._actions = actions
|
|
203
|
+
self._store = store
|
|
204
|
+
self._transport = transport
|
|
205
|
+
self._timeout = timeout
|
|
206
|
+
self._identity = identity or SlackIdentity()
|
|
207
|
+
self._buttons = buttons
|
|
208
|
+
self._mode = mode
|
|
209
|
+
self._max_proposals = max_proposals
|
|
210
|
+
self._post_label = post_label
|
|
211
|
+
self._draft_button = draft_button
|
|
212
|
+
self._workspace_name = workspace_name
|
|
213
|
+
self._action_base_url = action_base_url
|
|
214
|
+
self._signals: list[ScoredSignal] = []
|
|
215
|
+
|
|
216
|
+
def send(self, scored: ScoredSignal) -> None:
|
|
217
|
+
if self._mode == MODE_SIGNAL:
|
|
218
|
+
# Held until flush(): the cap keeps the highest scores, which are
|
|
219
|
+
# only known once every signal is in. The wrapped destination never
|
|
220
|
+
# sees send(), so it cannot post.
|
|
221
|
+
if self._accepts(scored):
|
|
222
|
+
self._signals.append(scored)
|
|
223
|
+
return
|
|
224
|
+
self._wrapped.send(scored)
|
|
225
|
+
|
|
226
|
+
def _post(self, text: str) -> None:
|
|
227
|
+
post_message(
|
|
228
|
+
self._transport, text, timeout=self._timeout, identity=self._identity
|
|
229
|
+
)
|
|
230
|
+
|
|
231
|
+
def _post_buttons(self, text: str, proposal: dict) -> None:
|
|
232
|
+
"""One proposal as Block Kit: the content, then Post / Draft / Discard.
|
|
233
|
+
|
|
234
|
+
Blocks carry their own length handling, so this does not go through
|
|
235
|
+
`post_message`'s splitting, but it converts the same way: the section
|
|
236
|
+
blocks and the notification fallback are both mrkdwn, because both are
|
|
237
|
+
read by a human. `text` is the fallback a push notification and a
|
|
238
|
+
screen reader get when the blocks are not rendered; the reply grammar
|
|
239
|
+
lives in the context line `proposal_blocks` builds, and is deliberately
|
|
240
|
+
not repeated here.
|
|
241
|
+
"""
|
|
242
|
+
pid = proposal["id"]
|
|
243
|
+
action = proposal["action"]
|
|
244
|
+
rendered = to_mrkdwn(text)
|
|
245
|
+
body: dict = {
|
|
246
|
+
"text": f"{rendered}\n\nProposal {pid}: {action}.",
|
|
247
|
+
"blocks": proposal_blocks(
|
|
248
|
+
rendered,
|
|
249
|
+
pid,
|
|
250
|
+
action,
|
|
251
|
+
self._post_label,
|
|
252
|
+
self._draft_button,
|
|
253
|
+
# Where the click is routed: one listener can serve several
|
|
254
|
+
# workspaces on one app (issue #103).
|
|
255
|
+
f"{self._workspace_name}/{pid}" if self._workspace_name else None,
|
|
256
|
+
),
|
|
257
|
+
}
|
|
258
|
+
body.update(self._identity.payload())
|
|
259
|
+
# The `ts` is kept on the proposal (which `add_all` is about to store)
|
|
260
|
+
# so that a verdict arriving from the action page can edit this card
|
|
261
|
+
# instead of leaving live buttons on a closed lead. The webhook
|
|
262
|
+
# transport returns "", and then there is nothing to edit and the link
|
|
263
|
+
# path posts a separate outcome message instead.
|
|
264
|
+
# Through the transport, not a raw requests.post. This call site was
|
|
265
|
+
# written when the destination held a webhook URL, and posting the
|
|
266
|
+
# payload straight at it was the same thing. It is not any more: the
|
|
267
|
+
# transport may be a bot token plus a channel, and `post()` is what
|
|
268
|
+
# knows the difference. Passing the object to `requests.post` instead
|
|
269
|
+
# fails with `InvalidURL: Host '<SlackTransport object ...>'`, and only
|
|
270
|
+
# ever on the buttons path, which is why nothing caught it until a
|
|
271
|
+
# config turned buttons on.
|
|
272
|
+
ts = self._transport.post(body)
|
|
273
|
+
if ts:
|
|
274
|
+
proposal["card_ts"] = str(ts)
|
|
275
|
+
|
|
276
|
+
def _link(self, proposal: dict) -> str:
|
|
277
|
+
"""Mint this proposal's action link, or "" when none is configured.
|
|
278
|
+
|
|
279
|
+
The token goes on the reserved proposal, which `add_all` writes, so a
|
|
280
|
+
link that was announced is always one the page can resolve -- and a run
|
|
281
|
+
that dies between announcing and storing leaves a link that resolves to
|
|
282
|
+
nothing rather than to the wrong lead (issue #124).
|
|
283
|
+
"""
|
|
284
|
+
retval = ""
|
|
285
|
+
if not self._action_base_url or not self._workspace_name:
|
|
286
|
+
return retval
|
|
287
|
+
token = mint_token()
|
|
288
|
+
proposal[TOKEN_FIELD] = token
|
|
289
|
+
retval = action_url(self._action_base_url, self._workspace_name, token)
|
|
290
|
+
return retval
|
|
291
|
+
|
|
292
|
+
def _announce(self, title: str, body: str, reserved: list[dict]) -> None:
|
|
293
|
+
"""Post one rendered item with the instructions for its proposals."""
|
|
294
|
+
if self._buttons:
|
|
295
|
+
# One message per proposal: the buttons carry a single proposal id,
|
|
296
|
+
# so two actions in one message would leave the second unclickable.
|
|
297
|
+
for proposal in reserved:
|
|
298
|
+
# Deliberately no action link on a card that has buttons. The
|
|
299
|
+
# buttons do the same job in Slack and better, and the token is
|
|
300
|
+
# a bearer capability: putting it in the message would store it
|
|
301
|
+
# in Slack, in push notifications and in email digests, and
|
|
302
|
+
# `_update` would re-post it verbatim when a button resolves
|
|
303
|
+
# the proposal. A token still gets minted, because the link
|
|
304
|
+
# goes out on the other surface.
|
|
305
|
+
self._link(proposal)
|
|
306
|
+
self._post_buttons(f"**{title}**\n\n{body}" if title else body, proposal)
|
|
307
|
+
return
|
|
308
|
+
lines = []
|
|
309
|
+
for p in reserved:
|
|
310
|
+
link = self._link(p)
|
|
311
|
+
line = f'Proposal {p["id"]}: {p["action"]}. Reply "do {p["id"]}" or "skip {p["id"]}"'
|
|
312
|
+
lines.append(f"{line}, or act on it here: {link}" if link else f"{line}.")
|
|
313
|
+
# Instructions above the content rather than after it (see the note in
|
|
314
|
+
# the module docstring).
|
|
315
|
+
head = f"**{title}**\n\n" if title else ""
|
|
316
|
+
self._post(head + "\n".join(lines) + "\n\n" + body)
|
|
317
|
+
|
|
318
|
+
def _flush_signals(self) -> None:
|
|
319
|
+
ranked = sorted(self._signals, key=lambda s: s.score, reverse=True)
|
|
320
|
+
self._signals = []
|
|
321
|
+
kept = ranked[: self._max_proposals]
|
|
322
|
+
left_out = ranked[self._max_proposals :]
|
|
323
|
+
for scored in kept:
|
|
324
|
+
rendered = self._render_signal(scored)
|
|
325
|
+
if rendered is None:
|
|
326
|
+
continue
|
|
327
|
+
body = rendered["text"]
|
|
328
|
+
if rendered.get("footer"):
|
|
329
|
+
body += f"\n\n{rendered['footer']}"
|
|
330
|
+
sig = scored.signal
|
|
331
|
+
meta = sig.meta if isinstance(sig.meta, dict) else {}
|
|
332
|
+
title = meta.get("title") or (sig.text.strip().splitlines() or [""])[0]
|
|
333
|
+
payload = {
|
|
334
|
+
"text": sig.text,
|
|
335
|
+
"url": sig.url,
|
|
336
|
+
"title": title,
|
|
337
|
+
"score": scored.score,
|
|
338
|
+
"reasons": list(scored.reasons),
|
|
339
|
+
"meta": meta,
|
|
340
|
+
"rendered": body,
|
|
341
|
+
}
|
|
342
|
+
reserved = [self._store.reserve(action, payload) for action in self._actions]
|
|
343
|
+
self._announce("", body, reserved)
|
|
344
|
+
# Stored per signal, immediately after its own announcement. The
|
|
345
|
+
# batch-wide write below only closed this class for the `left_out`
|
|
346
|
+
# notice: a transport failure on the third signal still discarded
|
|
347
|
+
# the first two, whose cards and links were already in the channel
|
|
348
|
+
# and would resolve to nothing for the rest of their lives. The
|
|
349
|
+
# token is minted inside `_announce`, so storing before it is not
|
|
350
|
+
# available without splitting the two.
|
|
351
|
+
self._store.add_all(reserved)
|
|
352
|
+
# Every signal is stored in the loop above, as it is announced, so
|
|
353
|
+
# nothing is left to write here. Storing the batch at this point was
|
|
354
|
+
# what made a failure anywhere in the loop -- or in the purely
|
|
355
|
+
# informational `left_out` notice below -- discard proposals whose
|
|
356
|
+
# cards and links were already in the channel.
|
|
357
|
+
if left_out:
|
|
358
|
+
links = "\n".join(f"• [{s.score}] {s.signal.url}" for s in left_out)
|
|
359
|
+
self._post(
|
|
360
|
+
f"{len(left_out)} more signal(s) passed the gate but were not proposed "
|
|
361
|
+
f"this run (max_proposals is {self._max_proposals}):\n{links}"
|
|
362
|
+
)
|
|
363
|
+
|
|
364
|
+
def flush(self) -> None:
|
|
365
|
+
if self._mode == MODE_SIGNAL:
|
|
366
|
+
self._flush_signals()
|
|
367
|
+
return
|
|
368
|
+
try:
|
|
369
|
+
rendered = self._render()
|
|
370
|
+
except Exception as exc:
|
|
371
|
+
self._post(f":warning: proposal not generated — {exc}")
|
|
372
|
+
raise
|
|
373
|
+
if not isinstance(rendered, dict) or "body_md" not in rendered:
|
|
374
|
+
raise RuntimeError(
|
|
375
|
+
"approval destination: wrapped render() must return a dict with "
|
|
376
|
+
f"'body_md', got {type(rendered).__name__}"
|
|
377
|
+
)
|
|
378
|
+
|
|
379
|
+
title = rendered.get("title") or "Proposal"
|
|
380
|
+
body = rendered["body_md"]
|
|
381
|
+
footer = rendered.get("footer")
|
|
382
|
+
if footer:
|
|
383
|
+
body += f"\n\n{footer}"
|
|
384
|
+
|
|
385
|
+
if rendered.get("empty"):
|
|
386
|
+
self._post(f"**{title}**\n\n{body}")
|
|
387
|
+
return
|
|
388
|
+
|
|
389
|
+
payload = dict(rendered)
|
|
390
|
+
# Every id is taken before anything is announced, and nothing is stored
|
|
391
|
+
# until every announcement is out: both modes announce first and store
|
|
392
|
+
# second, in one write.
|
|
393
|
+
reserved = [self._store.reserve(action, payload) for action in self._actions]
|
|
394
|
+
# Announce first, store second.
|
|
395
|
+
self._announce(title, body, reserved)
|
|
396
|
+
self._store.add_all(reserved)
|
|
397
|
+
|
|
398
|
+
|
|
399
|
+
# Transport: this destination posts through `SlackTransport` like every other
|
|
400
|
+
# (issue #86). It used to take a raw webhook URL, which had two consequences
|
|
401
|
+
# worth naming, because both were silent. Its proposal messages ignored the
|
|
402
|
+
# `username`/`icon_emoji` it accepted and went out under whichever app owned the
|
|
403
|
+
# webhook. And `buttons: true` could never have worked: Block Kit buttons have
|
|
404
|
+
# to be tidied up once a proposal is decided, that edit is `chat.update`, and
|
|
405
|
+
# `SlackTransport.update()` refuses a webhook-posted message because Slack
|
|
406
|
+
# returns no `ts` for one -- pointing the caller at `bot_token_env` +
|
|
407
|
+
# `channel_id`, which this build() then rejected. Accepting the same transport
|
|
408
|
+
# config as the rest closes both.
|
|
409
|
+
|
|
410
|
+
|
|
411
|
+
@register_destination("approval")
|
|
412
|
+
def build(cfg: dict) -> Destination:
|
|
413
|
+
timeout = int(cfg.get("timeout", 30))
|
|
414
|
+
transport = transport_from_config(cfg, "approval destination", timeout)
|
|
415
|
+
|
|
416
|
+
wrap = cfg.get("wrap")
|
|
417
|
+
if not isinstance(wrap, dict) or not wrap.get("type"):
|
|
418
|
+
raise RuntimeError("approval destination needs a 'wrap' block with a 'type'")
|
|
419
|
+
|
|
420
|
+
actions = cfg.get("actions")
|
|
421
|
+
if not isinstance(actions, list) or not actions or not all(
|
|
422
|
+
isinstance(a, str) and a for a in actions
|
|
423
|
+
):
|
|
424
|
+
raise RuntimeError("approval destination needs 'actions': a non-empty list of action names")
|
|
425
|
+
|
|
426
|
+
workspace = cfg.get("_workspace")
|
|
427
|
+
if not workspace:
|
|
428
|
+
raise RuntimeError(
|
|
429
|
+
"approval destination needs the workspace path; the CLI injects it as "
|
|
430
|
+
"'_workspace' (this destination cannot be built outside `agent run`)"
|
|
431
|
+
)
|
|
432
|
+
|
|
433
|
+
# The wrapped destination is built here, not by the CLI, so it gets the
|
|
434
|
+
# run-level paths from this block: a wrapped `digest` needs both for its
|
|
435
|
+
# LLM waterfall (see framework/llm.py).
|
|
436
|
+
wrap["_workspace"] = workspace
|
|
437
|
+
if cfg.get("_root"):
|
|
438
|
+
wrap["_root"] = cfg["_root"]
|
|
439
|
+
|
|
440
|
+
mode = cfg.get("mode", MODE_RUN)
|
|
441
|
+
if mode not in (MODE_RUN, MODE_SIGNAL):
|
|
442
|
+
raise RuntimeError(
|
|
443
|
+
f"approval destination: 'mode' must be {MODE_RUN!r} or {MODE_SIGNAL!r}, got {mode!r}"
|
|
444
|
+
)
|
|
445
|
+
max_proposals = cfg.get("max_proposals", _DEFAULT_MAX_PROPOSALS)
|
|
446
|
+
if isinstance(max_proposals, bool) or not isinstance(max_proposals, int) or max_proposals < 1:
|
|
447
|
+
raise RuntimeError(
|
|
448
|
+
f"approval destination: 'max_proposals' must be a positive integer, got {max_proposals!r}"
|
|
449
|
+
)
|
|
450
|
+
if mode == MODE_SIGNAL and not any(
|
|
451
|
+
key in wrap for key in ("webhook_env", "bot_token_env")
|
|
452
|
+
) and not any(
|
|
453
|
+
key in route for route in wrap.get("routes") or [] if isinstance(route, dict)
|
|
454
|
+
for key in ("webhook_env", "bot_token_env")
|
|
455
|
+
):
|
|
456
|
+
# The wrapped destination never posts in signal mode, but building it
|
|
457
|
+
# still builds its transports; lend it this block's.
|
|
458
|
+
wrap.update({key: cfg[key] for key in _TRANSPORT_KEYS if key in cfg})
|
|
459
|
+
|
|
460
|
+
retval = ApprovalDestination(
|
|
461
|
+
wrapped=build_destination(wrap),
|
|
462
|
+
actions=list(actions),
|
|
463
|
+
store=ProposalStore(proposals_path(Path(workspace))),
|
|
464
|
+
transport=transport,
|
|
465
|
+
timeout=timeout,
|
|
466
|
+
identity=identity_from_config(cfg, "approval destination"),
|
|
467
|
+
buttons=bool(cfg.get("buttons", False)),
|
|
468
|
+
mode=mode,
|
|
469
|
+
max_proposals=max_proposals,
|
|
470
|
+
post_label=str(cfg.get("post_label") or "Post"),
|
|
471
|
+
draft_button=bool(cfg.get("draft_button", True)),
|
|
472
|
+
workspace_name=Path(workspace).name,
|
|
473
|
+
# Read from this workspace's own `approvals.action_page.base_url`
|
|
474
|
+
# rather than from a key of this block: the listener reads it from
|
|
475
|
+
# there, and two keys for one value is one of them going stale.
|
|
476
|
+
action_base_url=base_url_for(workspace) or "",
|
|
477
|
+
)
|
|
478
|
+
return retval
|