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,775 @@
|
|
|
1
|
+
"""Approval buttons over Socket Mode (issue #74).
|
|
2
|
+
|
|
3
|
+
Approving by reply works, but the case that matters most -- a drafted blog
|
|
4
|
+
post -- wants one click and a third option the reply grammar has no room for:
|
|
5
|
+
publish it, park it in the editor as a draft, or throw it away. So a proposal
|
|
6
|
+
is posted as Block Kit with three buttons, and this module is what happens
|
|
7
|
+
when one is clicked.
|
|
8
|
+
|
|
9
|
+
Post run the action as configured
|
|
10
|
+
Draft the same sequence, with the WordPress step forced to `mode: draft`
|
|
11
|
+
and everything after it skipped, so nothing is announced
|
|
12
|
+
Discard mark the proposal skipped; no step runs
|
|
13
|
+
|
|
14
|
+
Why Socket Mode. A button needs Slack to deliver the interaction somewhere,
|
|
15
|
+
and the alternative is a public HTTPS endpoint for a fleet of agents that runs
|
|
16
|
+
on one laptop. Socket Mode dials out instead, so `agent approvals --listen` is
|
|
17
|
+
a long-running client holding that connection, installed by `install-schedule`
|
|
18
|
+
with `KeepAlive` (framework/schedule.py) rather than an interval. That it still
|
|
19
|
+
*has* the connection is checked rather than assumed, because a client that has
|
|
20
|
+
quietly stopped reconnecting leaves the job running and every button dead:
|
|
21
|
+
`_watch_connection`. Config:
|
|
22
|
+
|
|
23
|
+
"approvals": {
|
|
24
|
+
"channel_id": "C0123456789",
|
|
25
|
+
"bot_token_env": "SOME_BOT_TOKEN",
|
|
26
|
+
"app_token_env": "SOME_APP_TOKEN",
|
|
27
|
+
"trusted_user_ids": ["U0123456789"],
|
|
28
|
+
"schedule": "every 5m"
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
`app_token_env` names the env var holding the app-level token (`xapp-...`,
|
|
32
|
+
scope `connections:write`); it is read only by `--listen`. Both tokens are read
|
|
33
|
+
from the environment by the name a config key gives, never written down here.
|
|
34
|
+
|
|
35
|
+
That token must belong to an app nothing else connects with. Slack spreads an
|
|
36
|
+
app's events across all of its Socket Mode connections, and `on_request` acks
|
|
37
|
+
every envelope but keeps only clicks. Pointed at a chat bot's app, this
|
|
38
|
+
listener silently swallows a share of that bot's mentions. See README, "Which
|
|
39
|
+
Slack app the listener connects as".
|
|
40
|
+
|
|
41
|
+
The polling pass is not replaced by this. A laptop asleep when someone clicks
|
|
42
|
+
gets the interaction on reconnect, but a click that is never delivered at all
|
|
43
|
+
leaves the proposal pending, and a `do <id>` reply still resolves it. Both
|
|
44
|
+
paths go through the same compare-and-set claim (`pending` -> `running` under
|
|
45
|
+
the store's lock, framework/proposals.py), so a click and a reply racing each
|
|
46
|
+
other cannot both run the steps: the loser is told the proposal is already
|
|
47
|
+
spoken for and does nothing.
|
|
48
|
+
|
|
49
|
+
Three things a reader should not be surprised by:
|
|
50
|
+
|
|
51
|
+
- **A proposal resolved by reply keeps its buttons.** The proposal is posted
|
|
52
|
+
through an incoming webhook, which returns no message `ts`, so the polling
|
|
53
|
+
pass has no handle to edit. Clicking a button afterwards is safe -- the
|
|
54
|
+
claim fails, nothing runs, and the clicker gets an ephemeral line saying
|
|
55
|
+
what the proposal already is. A click is what supplies the `ts` that lets
|
|
56
|
+
*this* path edit the message in place.
|
|
57
|
+
- **Draft is refused for an action with no `wordpress-publish` step.** There
|
|
58
|
+
is nothing to draft, and running the sequence anyway would publish exactly
|
|
59
|
+
what the operator was trying not to publish. The proposal stays pending,
|
|
60
|
+
so Post or Discard still work.
|
|
61
|
+
- **Changing `channel_id` strands the proposals already posted.** A proposal
|
|
62
|
+
records no channel of its own, so a click is checked against whatever
|
|
63
|
+
`channel_id` says now. Move an agent to a new approval channel with
|
|
64
|
+
proposals still pending in the old one and their buttons refuse as "wrong
|
|
65
|
+
channel", visibly only to whoever clicked. The reply path has the same
|
|
66
|
+
shape -- it only reads the configured channel's history -- so the fix is
|
|
67
|
+
the same either way: resolve what is pending before moving the agent, or
|
|
68
|
+
edit `state/proposals.json` and let them be re-proposed.
|
|
69
|
+
|
|
70
|
+
Nothing here logs a token, a payload, a message body or a `response_url`: the
|
|
71
|
+
stdout line per interaction is the proposal id, the verdict and the user id,
|
|
72
|
+
which is what an operator needs to see in `approvals.listen.log`. A
|
|
73
|
+
`response_url` is a bearer capability (30 minutes, five uses), and the
|
|
74
|
+
`requests` exception for a failed post carries the URL it posted to, so both
|
|
75
|
+
ways of talking back sanitise their failures into `ResponderError` before
|
|
76
|
+
anything can print them.
|
|
77
|
+
|
|
78
|
+
A click is acted on only if it came from the configured `channel_id` and from
|
|
79
|
+
a user in `trusted_user_ids`; either check failing is an ephemeral refusal and
|
|
80
|
+
nothing else.
|
|
81
|
+
|
|
82
|
+
One listener serves every workspace that posts cards through its app (issue
|
|
83
|
+
#103): the listening workspace names the others in `approvals.listen_for`, each
|
|
84
|
+
button's value is `<workspace>/<proposal id>`, and `route_block_action` hands
|
|
85
|
+
the click to that workspace's store and config, where the channel and trust
|
|
86
|
+
checks above are that workspace's own. Slack would split clicks between two
|
|
87
|
+
connections on one app, so a second listener is never the answer.
|
|
88
|
+
"""
|
|
89
|
+
from __future__ import annotations
|
|
90
|
+
|
|
91
|
+
import os
|
|
92
|
+
import sys
|
|
93
|
+
import time
|
|
94
|
+
from typing import Any
|
|
95
|
+
|
|
96
|
+
import requests
|
|
97
|
+
|
|
98
|
+
from framework.approvals import (
|
|
99
|
+
ApprovalsConfig,
|
|
100
|
+
load_approvals_config,
|
|
101
|
+
_now_iso,
|
|
102
|
+
_run_steps,
|
|
103
|
+
_slack_call,
|
|
104
|
+
has_draftable_step,
|
|
105
|
+
human_time,
|
|
106
|
+
steps_detail,
|
|
107
|
+
)
|
|
108
|
+
from framework.action_page import ActionPageError, PATH_PREFIX, serve_action_page
|
|
109
|
+
from framework.config import ConfigError
|
|
110
|
+
from framework.proposals import (
|
|
111
|
+
ProposalStore,
|
|
112
|
+
proposals_path,
|
|
113
|
+
STATUS_DONE,
|
|
114
|
+
STATUS_FAILED,
|
|
115
|
+
STATUS_PENDING,
|
|
116
|
+
STATUS_RUNNING,
|
|
117
|
+
STATUS_SKIPPED,
|
|
118
|
+
)
|
|
119
|
+
from framework.slack import SLACK_BLOCK_LIMIT, split_for_slack
|
|
120
|
+
|
|
121
|
+
ACTION_POST = "approval:post"
|
|
122
|
+
ACTION_DRAFT = "approval:draft"
|
|
123
|
+
ACTION_DISCARD = "approval:discard"
|
|
124
|
+
|
|
125
|
+
# How the listener decides its connection is gone for good. slack_sdk rebuilds
|
|
126
|
+
# a dropped session from its own monitor thread, so the grace window is there to
|
|
127
|
+
# let that happen: only a connection still absent after it is treated as dead.
|
|
128
|
+
_LIVENESS_POLL_SECONDS = 30.0
|
|
129
|
+
_LIVENESS_GRACE_SECONDS = 180.0
|
|
130
|
+
|
|
131
|
+
VARIANT_POST = "post"
|
|
132
|
+
VARIANT_DRAFT = "draft"
|
|
133
|
+
|
|
134
|
+
_ACTION_VARIANTS = {
|
|
135
|
+
ACTION_POST: VARIANT_POST,
|
|
136
|
+
ACTION_DRAFT: VARIANT_DRAFT,
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
class ListenerError(RuntimeError):
|
|
142
|
+
"""The listener cannot start: missing dependency, token or config key."""
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def _sections(text: str) -> list[dict[str, Any]]:
|
|
146
|
+
"""`text` as one or more mrkdwn section blocks (issue #85).
|
|
147
|
+
|
|
148
|
+
`split_for_slack` is the repo's one splitting rule, shared with the webhook
|
|
149
|
+
path: paragraph boundaries first, then lines, and inside a line only when
|
|
150
|
+
one line is itself longer than the limit -- and there, on a grapheme
|
|
151
|
+
boundary, so a family emoji or a flag pair is never cut in half. This used
|
|
152
|
+
to split by code-point index at an arbitrary 2800, which could leave a
|
|
153
|
+
stray joiner at the head of the next block, and disagreed with the other
|
|
154
|
+
path about where a long line may be cut. Both now stop at
|
|
155
|
+
`SLACK_BLOCK_LIMIT`, which is Slack's actual limit for a section's text.
|
|
156
|
+
"""
|
|
157
|
+
blocks = [
|
|
158
|
+
{"type": "section", "text": {"type": "mrkdwn", "text": part}}
|
|
159
|
+
for part in split_for_slack(text, SLACK_BLOCK_LIMIT)
|
|
160
|
+
]
|
|
161
|
+
retval = blocks
|
|
162
|
+
return retval
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def proposal_blocks(
|
|
166
|
+
text: str,
|
|
167
|
+
proposal_id: str,
|
|
168
|
+
action: str,
|
|
169
|
+
post_label: str = "Post",
|
|
170
|
+
draft_button: bool = True,
|
|
171
|
+
ref: str | None = None,
|
|
172
|
+
) -> list[dict[str, Any]]:
|
|
173
|
+
"""The proposal message: the rendered content, then the buttons.
|
|
174
|
+
|
|
175
|
+
`text` is exactly what the webhook would have posted without buttons, so
|
|
176
|
+
the content a human reads is the same either way and this stays out of the
|
|
177
|
+
way of whatever builds it (issue #73 owns the Markdown-to-mrkdwn pass).
|
|
178
|
+
|
|
179
|
+
`post_label` renames the first button, which runs the action as
|
|
180
|
+
configured: "Post" is wrong for an action that drafts something for a
|
|
181
|
+
human to send (issue #76). `draft_button: false` leaves out Draft, which
|
|
182
|
+
only means anything for an action with a `wordpress-publish` step and is
|
|
183
|
+
refused for any other.
|
|
184
|
+
|
|
185
|
+
`ref` is what each button carries back to the listener, normally
|
|
186
|
+
`<workspace>/<proposal id>`, so one listener can serve every workspace that
|
|
187
|
+
posts through the same app (issue #103). Without it the bare id is used,
|
|
188
|
+
which is what every card posted before #103 carries.
|
|
189
|
+
"""
|
|
190
|
+
value = ref or proposal_id
|
|
191
|
+
blocks = _sections(text)
|
|
192
|
+
blocks.append(
|
|
193
|
+
{
|
|
194
|
+
"type": "context",
|
|
195
|
+
"elements": [
|
|
196
|
+
{
|
|
197
|
+
"type": "mrkdwn",
|
|
198
|
+
"text": f"Proposal `{proposal_id}` · {action} · "
|
|
199
|
+
f'or reply `do {proposal_id}` / `skip {proposal_id}`',
|
|
200
|
+
}
|
|
201
|
+
],
|
|
202
|
+
}
|
|
203
|
+
)
|
|
204
|
+
blocks.append(
|
|
205
|
+
{
|
|
206
|
+
"type": "actions",
|
|
207
|
+
"block_id": f"approval:{proposal_id}",
|
|
208
|
+
"elements": [
|
|
209
|
+
{
|
|
210
|
+
"type": "button",
|
|
211
|
+
"action_id": ACTION_POST,
|
|
212
|
+
"text": {"type": "plain_text", "text": post_label},
|
|
213
|
+
"style": "primary",
|
|
214
|
+
"value": value,
|
|
215
|
+
},
|
|
216
|
+
*(
|
|
217
|
+
[
|
|
218
|
+
{
|
|
219
|
+
"type": "button",
|
|
220
|
+
"action_id": ACTION_DRAFT,
|
|
221
|
+
"text": {"type": "plain_text", "text": "Draft"},
|
|
222
|
+
"value": value,
|
|
223
|
+
}
|
|
224
|
+
]
|
|
225
|
+
if draft_button
|
|
226
|
+
else []
|
|
227
|
+
),
|
|
228
|
+
{
|
|
229
|
+
"type": "button",
|
|
230
|
+
"action_id": ACTION_DISCARD,
|
|
231
|
+
"text": {"type": "plain_text", "text": "Discard"},
|
|
232
|
+
"style": "danger",
|
|
233
|
+
"value": value,
|
|
234
|
+
},
|
|
235
|
+
],
|
|
236
|
+
}
|
|
237
|
+
)
|
|
238
|
+
retval = blocks
|
|
239
|
+
return retval
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
def outcome_blocks(text: str, outcome: str) -> list[dict[str, Any]]:
|
|
243
|
+
"""The same content with the buttons replaced by what happened."""
|
|
244
|
+
blocks = _sections(text)
|
|
245
|
+
blocks.append({"type": "context", "elements": [{"type": "mrkdwn", "text": outcome}]})
|
|
246
|
+
retval = blocks
|
|
247
|
+
return retval
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
def _content_text(message: dict[str, Any]) -> str:
|
|
251
|
+
"""The content part of the clicked message, without its context/buttons.
|
|
252
|
+
|
|
253
|
+
Read back from the message Slack hands us rather than from the store: the
|
|
254
|
+
proposal records the payload, not the rendered text, and the point of
|
|
255
|
+
editing in place is that the content a human approved stays exactly as it
|
|
256
|
+
was.
|
|
257
|
+
"""
|
|
258
|
+
parts = []
|
|
259
|
+
for block in message.get("blocks") or []:
|
|
260
|
+
if block.get("type") != "section":
|
|
261
|
+
continue
|
|
262
|
+
text = (block.get("text") or {}).get("text")
|
|
263
|
+
if text:
|
|
264
|
+
parts.append(text)
|
|
265
|
+
retval = "\n".join(parts) if parts else str(message.get("text") or "")
|
|
266
|
+
return retval
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
def outcome_line(status: str, variant: str, user_id: str, when: str, detail: str) -> str:
|
|
270
|
+
"""The context line the message is edited down to after a click."""
|
|
271
|
+
who = f"<@{user_id}>"
|
|
272
|
+
if status == STATUS_SKIPPED:
|
|
273
|
+
retval = f":wastebasket: Discarded by {who} at {when}."
|
|
274
|
+
return retval
|
|
275
|
+
if status == STATUS_DONE:
|
|
276
|
+
# "Approved", not "Posted": the first button runs whatever the action
|
|
277
|
+
# is, and for one that drafts something for a human to send, "Posted"
|
|
278
|
+
# would claim the very thing that did not happen.
|
|
279
|
+
verb = "Drafted" if variant == VARIANT_DRAFT else "Approved"
|
|
280
|
+
retval = f":white_check_mark: {verb} by {who} at {when}. {detail}"
|
|
281
|
+
return retval
|
|
282
|
+
retval = f":x: Failed after {who} clicked at {when}. {detail}"
|
|
283
|
+
return retval
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
class ResponderError(RuntimeError):
|
|
287
|
+
"""Talking back to Slack failed. Carries no URL, no token, no body.
|
|
288
|
+
|
|
289
|
+
Raised in place of the underlying `requests` exception, whose message
|
|
290
|
+
embeds the request URL. For `response_url` that URL *is* the credential --
|
|
291
|
+
a bearer capability good for 30 minutes and five uses -- and its ordinary
|
|
292
|
+
failure modes (expired, used up, a Slack-side blip) would otherwise write
|
|
293
|
+
it into `approvals.listen.error.log`, which the listener's catch-all
|
|
294
|
+
prints to. Losing the URL from the message costs nothing: there is exactly
|
|
295
|
+
one response_url per interaction, and the proposal id in the same line
|
|
296
|
+
says which.
|
|
297
|
+
"""
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
def _sanitised(what: str, exc: Exception) -> ResponderError:
|
|
301
|
+
"""`exc` without whatever URL it was carrying."""
|
|
302
|
+
detail = getattr(getattr(exc, "response", None), "status_code", None)
|
|
303
|
+
if detail is not None:
|
|
304
|
+
retval = ResponderError(f"{what} failed: HTTP {detail}")
|
|
305
|
+
return retval
|
|
306
|
+
retval = ResponderError(f"{what} failed: {type(exc).__name__}")
|
|
307
|
+
return retval
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
class SlackResponder:
|
|
311
|
+
"""The two ways this module talks back: edit the message, or one user only.
|
|
312
|
+
|
|
313
|
+
A thin seam rather than the full web client: the listener is verified
|
|
314
|
+
offline with a fake in its place, and everything it needs is two calls.
|
|
315
|
+
Both sanitise their failures (see `ResponderError`).
|
|
316
|
+
"""
|
|
317
|
+
|
|
318
|
+
def __init__(self, bot_token: str, timeout: int = 30):
|
|
319
|
+
self._bot_token = bot_token
|
|
320
|
+
self._timeout = timeout
|
|
321
|
+
|
|
322
|
+
def update(self, channel: str, ts: str, text: str, blocks: list[dict[str, Any]]) -> None:
|
|
323
|
+
try:
|
|
324
|
+
_slack_call(
|
|
325
|
+
"chat.update",
|
|
326
|
+
self._bot_token,
|
|
327
|
+
self._timeout,
|
|
328
|
+
channel=channel,
|
|
329
|
+
ts=ts,
|
|
330
|
+
text=text,
|
|
331
|
+
blocks=blocks,
|
|
332
|
+
)
|
|
333
|
+
except Exception as exc:
|
|
334
|
+
# The API URL is not secret, but the token is in the headers and a
|
|
335
|
+
# transport error can quote a redirect target; one rule for both
|
|
336
|
+
# calls is easier to keep true than two.
|
|
337
|
+
raise _sanitised("chat.update", exc) from None
|
|
338
|
+
|
|
339
|
+
def ephemeral(self, response_url: str, text: str) -> None:
|
|
340
|
+
"""Say something to the clicker alone, visible to nobody else.
|
|
341
|
+
|
|
342
|
+
`response_url` rather than `chat.postEphemeral`: it is what the
|
|
343
|
+
interaction hands us, it needs no extra scope, and an approval refusal
|
|
344
|
+
should not be an audit-visible message in the channel.
|
|
345
|
+
"""
|
|
346
|
+
try:
|
|
347
|
+
resp = requests.post(
|
|
348
|
+
response_url,
|
|
349
|
+
json={"response_type": "ephemeral", "replace_original": False, "text": text},
|
|
350
|
+
timeout=self._timeout,
|
|
351
|
+
)
|
|
352
|
+
resp.raise_for_status()
|
|
353
|
+
except Exception as exc:
|
|
354
|
+
raise _sanitised("ephemeral reply", exc) from None
|
|
355
|
+
|
|
356
|
+
|
|
357
|
+
def split_ref(value: str) -> tuple[str | None, str]:
|
|
358
|
+
"""A button value as (workspace name or None, proposal id).
|
|
359
|
+
|
|
360
|
+
`<workspace>/<id>` since issue #103; a bare id on every card posted before
|
|
361
|
+
it. A workspace name is a directory name, so it cannot contain the `/`.
|
|
362
|
+
"""
|
|
363
|
+
if "/" in value:
|
|
364
|
+
workspace, proposal_id = value.rsplit("/", 1)
|
|
365
|
+
retval = (workspace, proposal_id)
|
|
366
|
+
return retval
|
|
367
|
+
retval = (None, value)
|
|
368
|
+
return retval
|
|
369
|
+
|
|
370
|
+
|
|
371
|
+
class Route:
|
|
372
|
+
"""One workspace a listener serves: its config, its store, its responder."""
|
|
373
|
+
|
|
374
|
+
def __init__(self, cfg: ApprovalsConfig):
|
|
375
|
+
self.cfg = cfg
|
|
376
|
+
self.store = ProposalStore(proposals_path(cfg.workspace))
|
|
377
|
+
self.responder = SlackResponder(cfg.bot_token, cfg.timeout)
|
|
378
|
+
|
|
379
|
+
|
|
380
|
+
def route_block_action(routes: dict[str, Route], payload: dict[str, Any]) -> tuple[str, str]:
|
|
381
|
+
"""Send one click to the workspace that owns its proposal (issue #103).
|
|
382
|
+
|
|
383
|
+
Returns (agent name for the log line, summary). A `<workspace>/<id>` value
|
|
384
|
+
goes to that workspace, or is refused if this listener does not serve it.
|
|
385
|
+
A bare id, from a card posted before values carried the workspace, goes to
|
|
386
|
+
the one store that holds it; held by none or by several, it is refused and
|
|
387
|
+
the `do <id>` reply path is named, which still works.
|
|
388
|
+
"""
|
|
389
|
+
any_route = next(iter(routes.values()))
|
|
390
|
+
actions = payload.get("actions") or []
|
|
391
|
+
if not actions or actions[0].get("action_id") not in (ACTION_POST, ACTION_DRAFT, ACTION_DISCARD):
|
|
392
|
+
# Nothing to route; the handler says why it is ignored.
|
|
393
|
+
retval = (any_route.cfg.agent, handle_block_action(
|
|
394
|
+
any_route.cfg, any_route.store, payload, any_route.responder
|
|
395
|
+
))
|
|
396
|
+
return retval
|
|
397
|
+
workspace, proposal_id = split_ref(str(actions[0].get("value") or ""))
|
|
398
|
+
response_url = str(payload.get("response_url") or "")
|
|
399
|
+
user_id = str((payload.get("user") or {}).get("id") or "")
|
|
400
|
+
if workspace is not None:
|
|
401
|
+
route = routes.get(workspace)
|
|
402
|
+
if route is None:
|
|
403
|
+
any_route.responder.ephemeral(
|
|
404
|
+
response_url,
|
|
405
|
+
f"Proposal {proposal_id} belongs to '{workspace}', which this listener "
|
|
406
|
+
f"does not serve (add it to 'approvals.listen_for'). Nothing ran; "
|
|
407
|
+
f"reply \"do {proposal_id}\" in its approval channel instead.",
|
|
408
|
+
)
|
|
409
|
+
retval = (any_route.cfg.agent,
|
|
410
|
+
f"proposal={proposal_id} verdict=refused user={user_id} "
|
|
411
|
+
f"(workspace {workspace!r} not served)")
|
|
412
|
+
return retval
|
|
413
|
+
else:
|
|
414
|
+
holders = [r for r in routes.values() if r.store.get(proposal_id) is not None]
|
|
415
|
+
if len(holders) == 1 or len(routes) == 1:
|
|
416
|
+
route = holders[0] if holders else any_route
|
|
417
|
+
else:
|
|
418
|
+
where = (
|
|
419
|
+
f"is in {len(holders)} of this listener's workspaces, so the click "
|
|
420
|
+
"cannot tell which"
|
|
421
|
+
if holders
|
|
422
|
+
else "is in none of this listener's workspaces"
|
|
423
|
+
)
|
|
424
|
+
any_route.responder.ephemeral(
|
|
425
|
+
response_url,
|
|
426
|
+
f"Proposal {proposal_id} {where}. Nothing ran; reply "
|
|
427
|
+
f"\"do {proposal_id}\" in the approval channel instead.",
|
|
428
|
+
)
|
|
429
|
+
retval = (any_route.cfg.agent,
|
|
430
|
+
f"proposal={proposal_id} verdict=refused user={user_id} "
|
|
431
|
+
f"(bare id in {len(holders)} workspaces)")
|
|
432
|
+
return retval
|
|
433
|
+
retval = (route.cfg.agent, handle_block_action(
|
|
434
|
+
route.cfg, route.store, payload, route.responder, proposal_id=proposal_id
|
|
435
|
+
))
|
|
436
|
+
return retval
|
|
437
|
+
|
|
438
|
+
|
|
439
|
+
def handle_block_action(
|
|
440
|
+
cfg: ApprovalsConfig,
|
|
441
|
+
store: ProposalStore,
|
|
442
|
+
payload: dict[str, Any],
|
|
443
|
+
responder: Any,
|
|
444
|
+
proposal_id: str | None = None,
|
|
445
|
+
) -> str:
|
|
446
|
+
"""Act on one button click; return the one-line summary for the log.
|
|
447
|
+
|
|
448
|
+
Ordering is the reply path's: claim first, then steps, then the terminal
|
|
449
|
+
status, then the message. Every exit that does not claim leaves the
|
|
450
|
+
proposal exactly as it was, so the reply path can still resolve it.
|
|
451
|
+
"""
|
|
452
|
+
actions = payload.get("actions") or []
|
|
453
|
+
if not actions:
|
|
454
|
+
retval = "ignored: interaction with no actions"
|
|
455
|
+
return retval
|
|
456
|
+
action = actions[0]
|
|
457
|
+
action_id = action.get("action_id")
|
|
458
|
+
if action_id not in (ACTION_POST, ACTION_DRAFT, ACTION_DISCARD):
|
|
459
|
+
retval = f"ignored: unknown action_id {action_id!r}"
|
|
460
|
+
return retval
|
|
461
|
+
|
|
462
|
+
if proposal_id is None:
|
|
463
|
+
proposal_id = split_ref(str(action.get("value") or ""))[1]
|
|
464
|
+
user_id = str((payload.get("user") or {}).get("id") or "")
|
|
465
|
+
response_url = str(payload.get("response_url") or "")
|
|
466
|
+
channel = str((payload.get("channel") or {}).get("id") or "")
|
|
467
|
+
message = payload.get("message") or {}
|
|
468
|
+
ts = str(message.get("ts") or (payload.get("container") or {}).get("message_ts") or "")
|
|
469
|
+
clicked_at = str(action.get("action_ts") or "")
|
|
470
|
+
|
|
471
|
+
# The reply path is scoped to one channel by construction: it only ever
|
|
472
|
+
# reads `conversations.history` for `channel_id`. A click arrives from
|
|
473
|
+
# wherever the message was, so the same scope is checked here rather than
|
|
474
|
+
# assumed. In a one-app-per-workspace deployment nothing else can carry a
|
|
475
|
+
# matching action_id, but that is a property of the deployment, not of
|
|
476
|
+
# this code.
|
|
477
|
+
if channel != cfg.channel_id:
|
|
478
|
+
responder.ephemeral(
|
|
479
|
+
response_url,
|
|
480
|
+
f"Proposal {proposal_id} is approved in this agent's own approval channel, "
|
|
481
|
+
"not here. Nothing ran.",
|
|
482
|
+
)
|
|
483
|
+
retval = f"proposal={proposal_id} verdict=refused user={user_id} (wrong channel)"
|
|
484
|
+
return retval
|
|
485
|
+
|
|
486
|
+
if user_id not in cfg.trusted_user_ids:
|
|
487
|
+
responder.ephemeral(
|
|
488
|
+
response_url,
|
|
489
|
+
f"Only an approver listed for this agent can act on proposal {proposal_id}. "
|
|
490
|
+
"Nothing ran.",
|
|
491
|
+
)
|
|
492
|
+
retval = f"proposal={proposal_id} verdict=refused user={user_id} (not trusted)"
|
|
493
|
+
return retval
|
|
494
|
+
|
|
495
|
+
proposal = store.get(proposal_id)
|
|
496
|
+
if proposal is None:
|
|
497
|
+
responder.ephemeral(
|
|
498
|
+
response_url, f"Proposal {proposal_id} is not in this agent's store. Nothing ran."
|
|
499
|
+
)
|
|
500
|
+
retval = f"proposal={proposal_id} verdict=unknown user={user_id}"
|
|
501
|
+
return retval
|
|
502
|
+
|
|
503
|
+
decided = {
|
|
504
|
+
"decided_by": user_id,
|
|
505
|
+
"decided_ts": clicked_at,
|
|
506
|
+
"decided_via": "button",
|
|
507
|
+
}
|
|
508
|
+
when = human_time(clicked_at)
|
|
509
|
+
|
|
510
|
+
if action_id == ACTION_DISCARD:
|
|
511
|
+
if store.transition(proposal_id, STATUS_PENDING, STATUS_SKIPPED, **decided) is None:
|
|
512
|
+
retval = _already(store, responder, response_url, proposal_id, user_id)
|
|
513
|
+
return retval
|
|
514
|
+
line = outcome_line(STATUS_SKIPPED, VARIANT_POST, user_id, when, "")
|
|
515
|
+
_update(responder, channel, ts, message, line)
|
|
516
|
+
retval = f"proposal={proposal_id} verdict=discard user={user_id}"
|
|
517
|
+
return retval
|
|
518
|
+
|
|
519
|
+
variant = _ACTION_VARIANTS[action_id]
|
|
520
|
+
if variant == VARIANT_DRAFT and not has_draftable_step(cfg, proposal["action"]):
|
|
521
|
+
responder.ephemeral(
|
|
522
|
+
response_url,
|
|
523
|
+
f"Proposal {proposal_id} runs '{proposal['action']}', which has no "
|
|
524
|
+
"wordpress-publish step, so there is nothing to draft. It is still pending: "
|
|
525
|
+
"Post runs it as configured, Discard throws it away.",
|
|
526
|
+
)
|
|
527
|
+
retval = f"proposal={proposal_id} verdict=draft-refused user={user_id} (no draftable step)"
|
|
528
|
+
return retval
|
|
529
|
+
|
|
530
|
+
claimed = store.transition(
|
|
531
|
+
proposal_id,
|
|
532
|
+
STATUS_PENDING,
|
|
533
|
+
STATUS_RUNNING,
|
|
534
|
+
claimed_at=_now_iso(),
|
|
535
|
+
claimed_pid=os.getpid(),
|
|
536
|
+
variant=variant,
|
|
537
|
+
**decided,
|
|
538
|
+
)
|
|
539
|
+
if claimed is None:
|
|
540
|
+
retval = _already(store, responder, response_url, proposal_id, user_id)
|
|
541
|
+
return retval
|
|
542
|
+
|
|
543
|
+
results, error = _run_steps(cfg, store, proposal, variant=variant)
|
|
544
|
+
if error is None:
|
|
545
|
+
store.transition(proposal_id, STATUS_RUNNING, STATUS_DONE, results=results)
|
|
546
|
+
status = STATUS_DONE
|
|
547
|
+
detail = steps_detail(results)
|
|
548
|
+
else:
|
|
549
|
+
store.transition(proposal_id, STATUS_RUNNING, STATUS_FAILED, results=results, error=error)
|
|
550
|
+
status = STATUS_FAILED
|
|
551
|
+
detail = f"{error} Steps: {steps_detail(results)}"
|
|
552
|
+
_update(responder, channel, ts, message, outcome_line(status, variant, user_id, when, detail))
|
|
553
|
+
retval = f"proposal={proposal_id} verdict={variant} status={status} user={user_id}"
|
|
554
|
+
return retval
|
|
555
|
+
|
|
556
|
+
|
|
557
|
+
def _already(
|
|
558
|
+
store: ProposalStore, responder: Any, response_url: str, proposal_id: str, user_id: str
|
|
559
|
+
) -> str:
|
|
560
|
+
"""Someone (or the polling pass) got there first; say so, run nothing."""
|
|
561
|
+
current = store.get(proposal_id) or {}
|
|
562
|
+
status = current.get("status", "gone")
|
|
563
|
+
responder.ephemeral(
|
|
564
|
+
response_url,
|
|
565
|
+
f"Proposal {proposal_id} is already {status}"
|
|
566
|
+
+ (f" (by <@{current['decided_by']}>)" if current.get("decided_by") else "")
|
|
567
|
+
+ ". Nothing ran.",
|
|
568
|
+
)
|
|
569
|
+
retval = f"proposal={proposal_id} verdict=already-{status} user={user_id}"
|
|
570
|
+
return retval
|
|
571
|
+
|
|
572
|
+
|
|
573
|
+
def _update(
|
|
574
|
+
responder: Any, channel: str, ts: str, message: dict[str, Any], line: str
|
|
575
|
+
) -> None:
|
|
576
|
+
"""Edit the clicked message in place, buttons replaced by the outcome."""
|
|
577
|
+
if not (channel and ts):
|
|
578
|
+
print(
|
|
579
|
+
"agent: interaction carried no channel/ts; the message keeps its buttons "
|
|
580
|
+
"(clicking again is refused, the proposal is already resolved)",
|
|
581
|
+
file=sys.stderr,
|
|
582
|
+
)
|
|
583
|
+
return
|
|
584
|
+
content = _content_text(message)
|
|
585
|
+
responder.update(channel, ts, f"{content}\n\n{line}", outcome_blocks(content, line))
|
|
586
|
+
|
|
587
|
+
|
|
588
|
+
def run_listener(cfg: ApprovalsConfig) -> int:
|
|
589
|
+
"""Hold a Socket Mode connection and act on clicks until killed.
|
|
590
|
+
|
|
591
|
+
The only long-running entrypoint in the framework. It owns no clock and no
|
|
592
|
+
state of its own: every decision goes through the same store and the same
|
|
593
|
+
claim as the polling pass, so stopping it loses nothing but the buttons.
|
|
594
|
+
"""
|
|
595
|
+
if not cfg.app_token and cfg.action_page is None:
|
|
596
|
+
raise ListenerError(
|
|
597
|
+
"approvals --listen needs something to listen on: 'approvals.app_token_env' "
|
|
598
|
+
"for Slack buttons (xapp-...), 'approvals.action_page' for the link page "
|
|
599
|
+
"(issue #124), or both. Without either there is nothing to hold open and the "
|
|
600
|
+
"polling pass already resolves replies."
|
|
601
|
+
)
|
|
602
|
+
|
|
603
|
+
routes = listener_routes(cfg)
|
|
604
|
+
|
|
605
|
+
# Started before the Slack connection: a port already in use should fail
|
|
606
|
+
# now, not after the handshake, and a deployment that serves only the page
|
|
607
|
+
# never reaches the Socket Mode branch at all.
|
|
608
|
+
page_server = None
|
|
609
|
+
if cfg.action_page is not None:
|
|
610
|
+
page = cfg.action_page
|
|
611
|
+
try:
|
|
612
|
+
page_server = serve_action_page(routes, page)
|
|
613
|
+
except ActionPageError as exc:
|
|
614
|
+
# One error type for everything that stops `--listen`, so the CLI
|
|
615
|
+
# prints it as a config problem rather than a traceback.
|
|
616
|
+
raise ListenerError(str(exc)) from exc
|
|
617
|
+
print(
|
|
618
|
+
f"agent={cfg.agent} action page on {page.bind}:{page.port} "
|
|
619
|
+
f"(links are written as {page.base_url}{PATH_PREFIX}/<workspace>/<token>)",
|
|
620
|
+
flush=True,
|
|
621
|
+
)
|
|
622
|
+
|
|
623
|
+
if page_server is not None and not cfg.app_token:
|
|
624
|
+
# Page only. There is no socket to hold, so this thread does the
|
|
625
|
+
# blocking the Socket Mode client would otherwise do.
|
|
626
|
+
#
|
|
627
|
+
# Said out loud, because this branch is also where a typo lands. The
|
|
628
|
+
# start-up gate above accepts a missing `app_token` as soon as an
|
|
629
|
+
# `action_page` is configured, and nothing validates unknown keys in
|
|
630
|
+
# the `approvals` block -- so `app_token_evn`, or the key dropped in an
|
|
631
|
+
# edit, used to exit 2 with a clear message and now serves the page
|
|
632
|
+
# forever with every Block Kit button in the channel dead.
|
|
633
|
+
print(
|
|
634
|
+
f"agent={cfg.agent} WARNING: no 'approvals.app_token_env', so Socket Mode is "
|
|
635
|
+
"off and no button on any card will be served -- only the link page is "
|
|
636
|
+
"running. If that is not deliberate, check that key.",
|
|
637
|
+
file=sys.stderr,
|
|
638
|
+
)
|
|
639
|
+
served = ", ".join(sorted(routes))
|
|
640
|
+
print(f"agent={cfg.agent} serving approval links for {served}", flush=True)
|
|
641
|
+
try:
|
|
642
|
+
_block_forever()
|
|
643
|
+
except KeyboardInterrupt:
|
|
644
|
+
print(f"agent={cfg.agent} listener stopped", flush=True)
|
|
645
|
+
finally:
|
|
646
|
+
page_server.shutdown()
|
|
647
|
+
retval = 0
|
|
648
|
+
return retval
|
|
649
|
+
|
|
650
|
+
try:
|
|
651
|
+
from slack_sdk.socket_mode import SocketModeClient
|
|
652
|
+
from slack_sdk.socket_mode.response import SocketModeResponse
|
|
653
|
+
except ImportError as exc:
|
|
654
|
+
if page_server is not None:
|
|
655
|
+
page_server.shutdown()
|
|
656
|
+
raise ListenerError(
|
|
657
|
+
"approvals --listen needs the Socket Mode client: "
|
|
658
|
+
"pip install '.[approvals-buttons]' (slack_sdk, websocket-client)"
|
|
659
|
+
) from exc
|
|
660
|
+
|
|
661
|
+
client = SocketModeClient(app_token=cfg.app_token)
|
|
662
|
+
|
|
663
|
+
def on_request(socket_client, request: Any) -> None:
|
|
664
|
+
# Ack first, always: Slack retries an un-acked interaction, and a retry
|
|
665
|
+
# of a click whose steps are already running is exactly the double
|
|
666
|
+
# execution the claim exists to prevent. The claim would refuse it, but
|
|
667
|
+
# the operator should not have to read about it either.
|
|
668
|
+
socket_client.send_socket_mode_response(SocketModeResponse(envelope_id=request.envelope_id))
|
|
669
|
+
if request.type != "interactive":
|
|
670
|
+
return
|
|
671
|
+
payload = request.payload or {}
|
|
672
|
+
if payload.get("type") != "block_actions":
|
|
673
|
+
return
|
|
674
|
+
try:
|
|
675
|
+
agent, summary = route_block_action(routes, payload)
|
|
676
|
+
except Exception as exc:
|
|
677
|
+
# One bad interaction must not take the listener down: the next
|
|
678
|
+
# click, and the polling pass, still work. The proposal is left
|
|
679
|
+
# wherever the claim put it, which `stuck=N` reports.
|
|
680
|
+
print(f"agent: interaction failed: {type(exc).__name__}: {exc}", file=sys.stderr)
|
|
681
|
+
return
|
|
682
|
+
print(f"agent={agent} {summary} at={_now_iso()}", flush=True)
|
|
683
|
+
|
|
684
|
+
client.socket_mode_request_listeners.append(on_request)
|
|
685
|
+
served = ", ".join(sorted(routes))
|
|
686
|
+
print(f"agent={cfg.agent} listening for approval clicks (socket mode) for {served}", flush=True)
|
|
687
|
+
try:
|
|
688
|
+
# Inside the try: a rejected app token fails the handshake here, and
|
|
689
|
+
# launchd restarts this job (KeepAlive), so the socket has to be closed
|
|
690
|
+
# on the way out or every restart leaks one.
|
|
691
|
+
client.connect()
|
|
692
|
+
_watch_connection(client, cfg.agent)
|
|
693
|
+
except KeyboardInterrupt:
|
|
694
|
+
print(f"agent={cfg.agent} listener stopped", flush=True)
|
|
695
|
+
finally:
|
|
696
|
+
client.close()
|
|
697
|
+
if page_server is not None:
|
|
698
|
+
page_server.shutdown()
|
|
699
|
+
retval = 0
|
|
700
|
+
return retval
|
|
701
|
+
|
|
702
|
+
|
|
703
|
+
def listener_routes(cfg: ApprovalsConfig) -> dict[str, Route]:
|
|
704
|
+
"""This workspace plus every one it names in `approvals.listen_for`.
|
|
705
|
+
|
|
706
|
+
Keyed by workspace directory name, which is what a card's button value
|
|
707
|
+
carries. Each served workspace keeps its own channel, trusted users, bot
|
|
708
|
+
token and actions; only the app-level token, and so the one connection, is
|
|
709
|
+
shared. A served workspace that does not load stops the listener at start,
|
|
710
|
+
rather than refusing its clicks one at a time later.
|
|
711
|
+
"""
|
|
712
|
+
routes = {cfg.workspace.name: Route(cfg)}
|
|
713
|
+
for path in cfg.listen_for:
|
|
714
|
+
try:
|
|
715
|
+
other = load_approvals_config(path)
|
|
716
|
+
except ConfigError as exc:
|
|
717
|
+
raise ListenerError(f"approvals.listen_for: {path.name}: {exc}") from exc
|
|
718
|
+
if path.name in routes:
|
|
719
|
+
raise ListenerError(f"approvals.listen_for: {path.name} is listed twice")
|
|
720
|
+
routes[path.name] = Route(other)
|
|
721
|
+
retval = routes
|
|
722
|
+
return retval
|
|
723
|
+
|
|
724
|
+
|
|
725
|
+
def _block_forever() -> None:
|
|
726
|
+
"""Sleep until killed. Separate so a test can drive `run_listener` without it."""
|
|
727
|
+
from threading import Event
|
|
728
|
+
|
|
729
|
+
Event().wait()
|
|
730
|
+
|
|
731
|
+
|
|
732
|
+
def _watch_connection(client: Any, agent: str) -> None:
|
|
733
|
+
"""Block while the connection holds, and exit nonzero once it does not.
|
|
734
|
+
|
|
735
|
+
This is what makes `KeepAlive` mean what framework/schedule.py says it
|
|
736
|
+
means. launchd restarts this job whenever it exits, "which is how a dropped
|
|
737
|
+
connection or a slept laptop becomes a reconnect" -- but only if a listener
|
|
738
|
+
that has lost its connection actually exits. Blocking on an event that is
|
|
739
|
+
never set does not: when slack_sdk stops rebuilding the session, the
|
|
740
|
+
process stays alive, launchd reports the job as running, and every button
|
|
741
|
+
in the channel is dead with nothing in any log to say so. Measured once:
|
|
742
|
+
six days up, zero network sockets open, the last click handled 27 days
|
|
743
|
+
earlier. The reply grammar kept working the whole time, which is what made
|
|
744
|
+
it survivable and also what hid it.
|
|
745
|
+
|
|
746
|
+
The grace window is why this watches rather than exits on the first miss.
|
|
747
|
+
The SDK reconnects on its own from its monitor thread, and a laptop waking
|
|
748
|
+
up or a wifi change should become a reconnect rather than a process
|
|
749
|
+
restart; `ThrottleInterval` bounds the restarts that do happen at one a
|
|
750
|
+
minute. So a connection is called dead only once it has been absent across
|
|
751
|
+
the whole window, and any single poll finding it back resets that.
|
|
752
|
+
|
|
753
|
+
Raising `SystemExit` rather than returning keeps the exit code off the
|
|
754
|
+
healthy path and still runs `run_listener`'s `finally`, which has to close
|
|
755
|
+
the socket (a restart would otherwise leak one) and the action page.
|
|
756
|
+
"""
|
|
757
|
+
down_since: float | None = None
|
|
758
|
+
while True:
|
|
759
|
+
time.sleep(_LIVENESS_POLL_SECONDS)
|
|
760
|
+
if client.is_connected():
|
|
761
|
+
down_since = None
|
|
762
|
+
continue
|
|
763
|
+
now = time.monotonic()
|
|
764
|
+
if down_since is None:
|
|
765
|
+
down_since = now
|
|
766
|
+
continue
|
|
767
|
+
down_for = now - down_since
|
|
768
|
+
if down_for < _LIVENESS_GRACE_SECONDS:
|
|
769
|
+
continue
|
|
770
|
+
print(
|
|
771
|
+
f"agent={agent} no socket mode connection for {int(down_for)}s: "
|
|
772
|
+
"exiting so launchd starts a listener that has one",
|
|
773
|
+
file=sys.stderr,
|
|
774
|
+
)
|
|
775
|
+
raise SystemExit(1)
|