agents-framework 0.3.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. agents_framework-0.3.0.dist-info/METADATA +1364 -0
  2. agents_framework-0.3.0.dist-info/RECORD +50 -0
  3. agents_framework-0.3.0.dist-info/WHEEL +5 -0
  4. agents_framework-0.3.0.dist-info/entry_points.txt +2 -0
  5. agents_framework-0.3.0.dist-info/licenses/LICENSE +661 -0
  6. agents_framework-0.3.0.dist-info/top_level.txt +1 -0
  7. framework/__init__.py +0 -0
  8. framework/__main__.py +9 -0
  9. framework/action_page.py +1102 -0
  10. framework/approval_buttons.py +775 -0
  11. framework/approvals.py +678 -0
  12. framework/calendar_card.py +276 -0
  13. framework/cli.py +273 -0
  14. framework/codex_llm.py +401 -0
  15. framework/config.py +126 -0
  16. framework/drafter.py +263 -0
  17. framework/interfaces.py +96 -0
  18. framework/llm.py +744 -0
  19. framework/plugins/__init__.py +147 -0
  20. framework/plugins/agentmail_source.py +355 -0
  21. framework/plugins/approval_destination.py +478 -0
  22. framework/plugins/command_action.py +248 -0
  23. framework/plugins/digest_destination.py +546 -0
  24. framework/plugins/email_destination.py +248 -0
  25. framework/plugins/fanout_destination.py +160 -0
  26. framework/plugins/github_org_source.py +226 -0
  27. framework/plugins/github_releases_source.py +420 -0
  28. framework/plugins/ics_source.py +594 -0
  29. framework/plugins/llm_scorer.py +411 -0
  30. framework/plugins/multi_source.py +241 -0
  31. framework/plugins/reddit_source.py +625 -0
  32. framework/plugins/regex_scorer.py +93 -0
  33. framework/plugins/rss_source.py +346 -0
  34. framework/plugins/signal_destination.py +133 -0
  35. framework/plugins/slack_destination.py +461 -0
  36. framework/plugins/slack_draft_action.py +137 -0
  37. framework/plugins/slack_post_action.py +65 -0
  38. framework/plugins/slack_workspace_source.py +992 -0
  39. framework/plugins/twitter_action.py +210 -0
  40. framework/plugins/websearch_source.py +761 -0
  41. framework/plugins/wordpress_action.py +413 -0
  42. framework/proposals.py +246 -0
  43. framework/registry.py +166 -0
  44. framework/runlog.py +125 -0
  45. framework/runner.py +243 -0
  46. framework/schedule.py +571 -0
  47. framework/signal_messenger.py +1418 -0
  48. framework/slack.py +801 -0
  49. framework/state.py +39 -0
  50. framework/templating.py +76 -0
framework/approvals.py ADDED
@@ -0,0 +1,678 @@
1
+ """`agent approvals` — execute what a trusted human said `do` to (issue #21).
2
+
3
+ The second scheduled entrypoint. `agent run` ends by recording proposals (see
4
+ `framework/plugins/approval_destination.py`); this pass, on its own launchd
5
+ clock every few minutes, reads the approval channel's recent history, finds
6
+ replies from trusted users, and runs the matching proposals' action steps.
7
+ Run-and-exit, state on disk, safe to double-fire: before any step runs, the
8
+ proposal is *claimed* (`pending` -> `running`, a compare-and-set under the
9
+ store's lock), and a second pass racing the first fails its claim and does
10
+ nothing. Only after the steps does it move to `done` or `failed`.
11
+
12
+ Config, in the workspace's `config.json`:
13
+
14
+ "approvals": {
15
+ "schedule": "every 5m",
16
+ "channel_id": "C0123456789",
17
+ "bot_token_env": "SOME_BOT_TOKEN",
18
+ "trusted_user_ids": ["U0123456789"],
19
+ "hours": 24
20
+ },
21
+ "actions": {
22
+ "publish-post": {
23
+ "steps": [
24
+ {"type": "wordpress-publish", "mode": "publish"},
25
+ {"type": "slack-post", "webhook_env": "SOME_WEBHOOK", "text": "Published: {url}"}
26
+ ]
27
+ }
28
+ }
29
+
30
+ `channel_id` is the channel the proposals were posted to, read with the bot
31
+ token in `bot_token_env` (scopes: `channels:history` or `groups:history` for
32
+ a private channel, plus `chat:write` for the outcome message). `schedule` is
33
+ read only by `agent install-schedule` (framework/schedule.py). `hours` bounds
34
+ how far back history is read (default 24). The webhook that posted the
35
+ proposal cannot read replies; a bot token can, which is why both exist.
36
+
37
+ What counts as a reply: a top-level channel message whose text is exactly
38
+ `do <id>` or `skip <id>` (whitespace-trimmed, the full id including its random
39
+ suffix) from a user in `trusted_user_ids`, posted *after* the proposal was
40
+ recorded. Anything else is ignored, including "do all", a reaction, a `do`
41
+ from anyone not on the list, or a `do` that predates the proposal it names.
42
+ No blanket approval exists, and nothing said before a proposal existed can
43
+ approve it. If a trusted user says both `do p7-k3f` and `skip p7-k3f` before
44
+ the pass runs, the later message wins, which is the reading a human would
45
+ give a change of mind.
46
+
47
+ Why a time bound rather than a thread: the proposal is announced through an
48
+ incoming webhook, and webhooks do not return the message `ts`, so there is no
49
+ thread to require replies in. `conversations.history` returns only top-level
50
+ messages, so a reply typed *in a thread* under the announcement is never seen
51
+ and the proposal stays pending. Reply in the channel, not in the thread.
52
+
53
+ Executing `do`: the action's steps run in order. Each step is built through
54
+ the registry from its own block, gets the proposal's payload merged with every
55
+ earlier step's returned dict, and its own returned dict is merged in for the
56
+ next. A step that raises stops the sequence: the proposal becomes `failed`
57
+ naming the step, later steps do not run, and nothing is retried. Retrying a
58
+ publish is not obviously safe (the first attempt may have half-succeeded), so
59
+ retry is a human decision made by reading the outcome message and the store.
60
+
61
+ A proposal can also be resolved by clicking a button on its message instead of
62
+ replying, when the deployment runs `agent approvals --listen` (issue #74, see
63
+ framework/approval_buttons.py). That path shares this module's claim, its step
64
+ runner and its store, so a click and a reply racing each other cannot both
65
+ execute: whichever claims first runs, the other is told the proposal is already
66
+ spoken for. It adds one variant, `draft`, which forces the WordPress step to
67
+ `mode: draft` and skips the announcement steps after it; a reply is always the
68
+ `post` variant. The variant is recorded on the proposal.
69
+
70
+ Whatever happened, one outcome message goes to the channel through
71
+ `chat.postMessage`, and one summary line is printed, unconditionally, in the
72
+ shape the runner uses (issue #31): `agent=<name> status=ok approvals=N
73
+ executed=N skipped=N failed=N stuck=N`.
74
+
75
+ Order inside a `do` matters: claim, then steps (each recorded in the store as
76
+ it completes), then the terminal status, then the channel is told. If posting
77
+ the outcome fails, the status is already right and the error propagates.
78
+
79
+ A proposal still `running` when a pass starts, whose claiming pid is gone (or
80
+ whose claim is older than `hours`), is one an earlier pass claimed and never
81
+ finished: the process died mid-steps. A live claiming pid is just an
82
+ overlapping pass still at work and is left alone. A stuck one is never re-run
83
+ automatically, because the steps it did complete (say, the publish) are real
84
+ and re-running them is exactly the duplicate the claim exists to prevent.
85
+ Every pass reports it on stderr and counts it in the summary line as
86
+ `stuck=N`; the channel is told once, with the steps the store has recorded as
87
+ done. Re-running it is a human decision: edit the store and set the proposal
88
+ back to `pending` (or to `failed` to close it). The `do` that claimed it is
89
+ still in the channel, so if it is inside the `hours` window the next pass runs
90
+ every step again at once, including the ones that already happened; otherwise
91
+ a fresh `do` is needed.
92
+ """
93
+ from __future__ import annotations
94
+
95
+ import json
96
+ import os
97
+ import re
98
+ import sys
99
+ import time
100
+ from datetime import datetime, timezone
101
+ from pathlib import Path
102
+ from typing import Any
103
+
104
+ from framework.config import CONFIG_FILENAME, ConfigError
105
+ from framework.proposals import (
106
+ STATUS_DONE,
107
+ STATUS_FAILED,
108
+ STATUS_PENDING,
109
+ STATUS_RUNNING,
110
+ STATUS_SKIPPED,
111
+ ProposalStore,
112
+ created_ts,
113
+ proposals_path,
114
+ )
115
+ from framework.registry import build_action
116
+ # Moved to framework/slack.py (issue #86), where the whole posting path lives;
117
+ # re-exported until the approvals path imports it from there directly.
118
+ from framework.slack import SlackApiError, slack_call as _slack_call
119
+
120
+ _REPLY_RE = re.compile(r"^(do|skip)\s+(\S+)$")
121
+ _DEFAULT_HOURS = 24
122
+
123
+
124
+ class ApprovalsConfig:
125
+ def __init__(
126
+ self,
127
+ agent: str,
128
+ workspace: Path,
129
+ channel_id: str,
130
+ bot_token: str,
131
+ trusted_user_ids: list[str],
132
+ hours: float,
133
+ actions: dict[str, Any],
134
+ timeout: int = 30,
135
+ app_token: str = "",
136
+ listen_for: list[Path] | None = None,
137
+ action_page: Any = None,
138
+ ):
139
+ self.agent = agent
140
+ self.workspace = workspace
141
+ self.channel_id = channel_id
142
+ self.bot_token = bot_token
143
+ self.trusted_user_ids = trusted_user_ids
144
+ self.hours = hours
145
+ self.actions = actions
146
+ self.timeout = timeout
147
+ self.app_token = app_token
148
+ self.listen_for = listen_for or []
149
+ # An `ActionPageConfig` or None. Typed loosely because
150
+ # framework/action_page.py imports this module, so naming its type
151
+ # here would be a cycle; the loader builds it.
152
+ self.action_page = action_page
153
+
154
+
155
+ def load_approvals_config(workspace: str | Path) -> ApprovalsConfig:
156
+ """Read the `approvals` and `actions` blocks of `<workspace>/config.json`.
157
+
158
+ Deliberately reads only what this pass needs, rather than going through
159
+ `framework.config.load_workspace`. That loader requires `source`, `scorer`
160
+ and `destination` to be objects with a `type`, none of which this pass
161
+ uses; a proposal already recorded should still be executable or skippable
162
+ while an operator has the source block half-edited. The file checks and
163
+ error wording match `load_workspace`'s.
164
+ """
165
+ workspace_path = Path(workspace).expanduser().resolve()
166
+ if not workspace_path.is_dir():
167
+ raise ConfigError(f"workspace directory not found: {workspace_path}")
168
+ config_path = workspace_path / CONFIG_FILENAME
169
+ if not config_path.is_file():
170
+ raise ConfigError(f"config file not found: {config_path}")
171
+ try:
172
+ raw = json.loads(config_path.read_text())
173
+ except json.JSONDecodeError as exc:
174
+ raise ConfigError(
175
+ f"{config_path}: invalid JSON at line {exc.lineno} column {exc.colno}: {exc.msg}"
176
+ ) from exc
177
+ if not isinstance(raw, dict):
178
+ raise ConfigError(f"{config_path}: top level must be an object")
179
+
180
+ agent = raw.get("agent")
181
+ if not agent:
182
+ raise ConfigError(f"{config_path}: 'agent' (name) is required")
183
+
184
+ block = raw.get("approvals")
185
+ if not isinstance(block, dict):
186
+ raise ConfigError(f"{config_path}: 'approvals' must be an object")
187
+ channel_id = block.get("channel_id")
188
+ if not channel_id:
189
+ raise ConfigError(f"{config_path}: 'approvals.channel_id' is required")
190
+ token_env = block.get("bot_token_env")
191
+ if not token_env:
192
+ raise ConfigError(f"{config_path}: 'approvals.bot_token_env' is required")
193
+ bot_token = os.environ.get(token_env)
194
+ if not bot_token:
195
+ raise ConfigError(f"approvals need the Slack bot token in ${token_env}")
196
+ # Read only by `--listen` (framework/approval_buttons.py), and only if the
197
+ # config names it: a workspace that approves by reply needs no app token,
198
+ # and demanding one here would break every existing deployment.
199
+ app_token_env = block.get("app_token_env")
200
+ app_token = ""
201
+ if app_token_env:
202
+ app_token = os.environ.get(app_token_env, "")
203
+ if not app_token:
204
+ raise ConfigError(
205
+ f"approvals need the Slack app-level token in ${app_token_env} "
206
+ f"(named by {config_path}: 'approvals.app_token_env')"
207
+ )
208
+
209
+ # Other workspaces whose button clicks this workspace's listener also
210
+ # serves (issue #103): Slack hands an app's clicks to any of its Socket Mode
211
+ # connections, so every workspace posting cards through one app has to be
212
+ # served by the one listener that app has. Paths are relative to the
213
+ # workspaces root, i.e. sibling workspace names.
214
+ listen_for_raw = block.get("listen_for", [])
215
+ if not isinstance(listen_for_raw, list) or not all(
216
+ isinstance(w, str) and w.strip() for w in listen_for_raw
217
+ ):
218
+ raise ConfigError(
219
+ f"{config_path}: 'approvals.listen_for' must be a list of workspace names"
220
+ )
221
+ listen_for = [(workspace_path.parent / w).resolve() for w in listen_for_raw]
222
+
223
+ # The link surface (issue #124). Absent is the normal case: every
224
+ # deployment before #124 approves in Slack only. Imported here rather than
225
+ # at module scope because action_page.py imports this module for the claim
226
+ # and the step runner.
227
+ try:
228
+ from framework.action_page import load_action_page
229
+ except ImportError as exc:
230
+ # This function is documented to raise ConfigError, and its callers --
231
+ # `cli.py`'s handler and `listener_routes`, which names the workspace
232
+ # that failed -- catch only that. A broken module here would otherwise
233
+ # surface as a bare traceback from the one place built to explain
234
+ # itself.
235
+ raise ConfigError(f"the action page module could not be imported: {exc}") from exc
236
+
237
+ action_page = load_action_page(block, config_path)
238
+
239
+ trusted = block.get("trusted_user_ids")
240
+ if not isinstance(trusted, list) or not trusted or not all(isinstance(u, str) for u in trusted):
241
+ raise ConfigError(
242
+ f"{config_path}: 'approvals.trusted_user_ids' must be a non-empty list of user ids"
243
+ )
244
+
245
+ actions = raw.get("actions")
246
+ if not isinstance(actions, dict):
247
+ raise ConfigError(f"{config_path}: 'actions' must be an object of named actions")
248
+ for name, action in actions.items():
249
+ steps = action.get("steps") if isinstance(action, dict) else None
250
+ if not isinstance(steps, list) or not steps:
251
+ raise ConfigError(f"{config_path}: 'actions.{name}.steps' must be a non-empty list")
252
+ for i, step in enumerate(steps, start=1):
253
+ if not isinstance(step, dict) or not step.get("type"):
254
+ raise ConfigError(
255
+ f"{config_path}: 'actions.{name}.steps[{i}]' must be an object with a 'type'"
256
+ )
257
+
258
+ retval = ApprovalsConfig(
259
+ agent=str(agent),
260
+ workspace=workspace_path,
261
+ channel_id=str(channel_id),
262
+ bot_token=bot_token,
263
+ trusted_user_ids=[str(u) for u in trusted],
264
+ hours=float(block.get("hours", _DEFAULT_HOURS)),
265
+ actions=actions,
266
+ timeout=int(block.get("timeout", 30)),
267
+ app_token=app_token,
268
+ listen_for=listen_for,
269
+ action_page=action_page,
270
+ )
271
+ return retval
272
+
273
+
274
+ def _now_iso() -> str:
275
+ retval = datetime.now(timezone.utc).isoformat(timespec="seconds")
276
+ return retval
277
+
278
+
279
+ def read_replies(cfg: ApprovalsConfig) -> dict[str, dict[str, str]]:
280
+ """Map proposal id -> {"verb", "user", "ts"} from trusted replies.
281
+
282
+ Walks `conversations.history` over the last `hours`, oldest first, so a
283
+ later reply about the same id overrides an earlier one.
284
+ """
285
+ oldest = f"{time.time() - cfg.hours * 3600:.6f}"
286
+ messages: list[dict[str, Any]] = []
287
+ cursor = None
288
+ while True:
289
+ params: dict[str, Any] = {"channel": cfg.channel_id, "oldest": oldest, "limit": 200}
290
+ if cursor:
291
+ params["cursor"] = cursor
292
+ body = _slack_call("conversations.history", cfg.bot_token, cfg.timeout, **params)
293
+ messages.extend(m for m in body.get("messages", []) if isinstance(m, dict))
294
+ cursor = (body.get("response_metadata") or {}).get("next_cursor")
295
+ if not body.get("has_more") or not cursor:
296
+ break
297
+
298
+ retval: dict[str, dict[str, str]] = {}
299
+ for message in sorted(messages, key=lambda m: float(m.get("ts", 0))):
300
+ user = message.get("user")
301
+ if user not in cfg.trusted_user_ids:
302
+ continue
303
+ match = _REPLY_RE.match(str(message.get("text", "")).strip())
304
+ if not match:
305
+ continue
306
+ retval[match.group(2)] = {
307
+ "verb": match.group(1),
308
+ "user": str(user),
309
+ "ts": str(message.get("ts", "")),
310
+ }
311
+ return retval
312
+
313
+
314
+ # How long a claim made by the action page may sit `running` before a pass
315
+ # calls it stuck. Short, because the pid test cannot apply to it (see
316
+ # `_is_stuck`) and the handler that made the claim either finished in
317
+ # milliseconds or is not coming back.
318
+ _LINK_CLAIM_STALE_SECONDS = 900
319
+
320
+ DRAFTABLE_STEP = "wordpress-publish"
321
+ VARIANT_POST = "post"
322
+ VARIANT_DRAFT = "draft"
323
+
324
+
325
+ def has_draftable_step(cfg: ApprovalsConfig, action_name: str) -> bool:
326
+ """Whether `action_name` has a step the `draft` variant can draft."""
327
+ action = cfg.actions.get(action_name)
328
+ steps = (action or {}).get("steps") or []
329
+ retval = any(step.get("type") == DRAFTABLE_STEP for step in steps)
330
+ return retval
331
+
332
+
333
+ def plan_steps(steps: list[dict[str, Any]], variant: str) -> list[tuple[int, dict | None, str]]:
334
+ """The steps to run for `variant`, as (number, config-or-None, why-skipped).
335
+
336
+ `post` is the sequence as configured. `draft` forces the WordPress step to
337
+ `mode: draft` and skips everything after it: those later steps are the
338
+ announcement, by construction -- they consume the publish result -- and
339
+ announcing a draft is the one thing the Draft button exists to avoid.
340
+ Nothing before the publish step is skipped; it is what produced the content.
341
+ """
342
+ if variant != VARIANT_DRAFT:
343
+ retval = [(i, dict(step), "") for i, step in enumerate(steps, start=1)]
344
+ return retval
345
+ last_draftable = 0
346
+ for i, step in enumerate(steps, start=1):
347
+ if step.get("type") == DRAFTABLE_STEP:
348
+ last_draftable = i
349
+ plan: list[tuple[int, dict | None, str]] = []
350
+ for i, step in enumerate(steps, start=1):
351
+ if i > last_draftable:
352
+ plan.append((i, None, "skipped: draft announces nothing"))
353
+ continue
354
+ step = dict(step)
355
+ if step.get("type") == DRAFTABLE_STEP:
356
+ step["mode"] = "draft"
357
+ plan.append((i, step, ""))
358
+ retval = plan
359
+ return retval
360
+
361
+
362
+ def steps_detail(results: list[dict[str, Any]]) -> str:
363
+ """One human-readable line naming each step and how it went."""
364
+ retval = ", ".join(f"{r['type']} {r['status']}" for r in results) or "no steps run"
365
+ return retval
366
+
367
+
368
+ def human_time(slack_ts: str) -> str:
369
+ """A Slack `ts` (epoch seconds, as a string) as a readable UTC time."""
370
+ try:
371
+ moment = datetime.fromtimestamp(float(slack_ts), tz=timezone.utc)
372
+ except (TypeError, ValueError):
373
+ retval = _now_iso()
374
+ return retval
375
+ retval = moment.isoformat(timespec="seconds")
376
+ return retval
377
+
378
+
379
+ def _run_steps(
380
+ cfg: ApprovalsConfig,
381
+ store: ProposalStore,
382
+ proposal: dict[str, Any],
383
+ variant: str = VARIANT_POST,
384
+ ) -> tuple[list[dict[str, Any]], str | None]:
385
+ """Run the claimed proposal's action steps in order; return (results, error).
386
+
387
+ `error` is None when every step ran, else a message naming the step that
388
+ stopped the sequence. `results` holds one entry per step attempted, and is
389
+ written to the store after each step so that a pass dying mid-sequence
390
+ leaves a record of what already happened. A step the variant skips is
391
+ recorded too, as `status: "skipped"`, so the store says what did not run
392
+ as plainly as what did.
393
+ """
394
+ name = proposal["action"]
395
+ action = cfg.actions.get(name)
396
+ results: list[dict[str, Any]] = []
397
+ if action is None:
398
+ known = ", ".join(sorted(cfg.actions)) or "(none)"
399
+ retval = (results, f"action {name!r} is not in this workspace's config; known: {known}")
400
+ return retval
401
+
402
+ merged: dict[str, Any] = dict(proposal.get("payload") or {})
403
+ context = {
404
+ "workspace": str(cfg.workspace),
405
+ "agent": cfg.agent,
406
+ "proposal_id": proposal["id"],
407
+ "action": name,
408
+ "variant": variant,
409
+ }
410
+ for i, step_cfg, skipped in plan_steps(action["steps"], variant):
411
+ if step_cfg is None:
412
+ results.append(
413
+ {"step": i, "type": action["steps"][i - 1].get("type"), "status": "skipped",
414
+ "note": skipped}
415
+ )
416
+ store.transition(proposal["id"], STATUS_RUNNING, STATUS_RUNNING, results=results)
417
+ continue
418
+ step_type = step_cfg.get("type")
419
+ try:
420
+ step = build_action(step_cfg)
421
+ result = step.execute(merged, context)
422
+ except Exception as exc:
423
+ results.append({"step": i, "type": step_type, "status": "failed", "error": str(exc)})
424
+ retval = (results, f"step {i} ({step_type}) failed: {exc}")
425
+ return retval
426
+ if not isinstance(result, dict):
427
+ results.append(
428
+ {"step": i, "type": step_type, "status": "failed", "error": "returned non-dict"}
429
+ )
430
+ retval = (results, f"step {i} ({step_type}) returned {type(result).__name__}, not a dict")
431
+ return retval
432
+ merged.update(result)
433
+ results.append({"step": i, "type": step_type, "status": "ok", "result": result})
434
+ store.transition(proposal["id"], STATUS_RUNNING, STATUS_RUNNING, results=results)
435
+ retval = (results, None)
436
+ return retval
437
+
438
+
439
+ def _stuck_text(proposal: dict[str, Any]) -> str:
440
+ pid = proposal["id"]
441
+ done = ", ".join(
442
+ f"{r['type']} {r['status']}" for r in proposal.get("results") or []
443
+ ) or "none"
444
+ if proposal.get("claimed_via") == "link":
445
+ # The pid on a link claim is the listener's, which is still alive and
446
+ # serving: an operator told to check it finds a healthy process and
447
+ # concludes the report is wrong. Age is the only evidence here, and it
448
+ # is weaker evidence -- steps slow enough to pass the stale bound are
449
+ # reachable, so this says what is known rather than asserting the
450
+ # request is dead.
451
+ retval = (
452
+ f":warning: Proposal {pid} ({proposal['action']}) has been 'running' since "
453
+ f"{proposal.get('claimed_at')}, claimed by the action page in the listener "
454
+ f"(pid {proposal.get('claimed_pid')}, which is still serving). Steps recorded "
455
+ f"as done: {done}. Either its steps are still running or the request died; "
456
+ "nothing here will re-run it, so check the listener's log before editing the "
457
+ "proposals store."
458
+ )
459
+ return retval
460
+ retval = (
461
+ f":warning: Proposal {pid} ({proposal['action']}) is stuck in 'running': an approvals "
462
+ f"pass claimed it at {proposal.get('claimed_at')} (pid {proposal.get('claimed_pid')}) "
463
+ f"and did not finish. Steps recorded as done: {done}. It will not be re-run; "
464
+ "an operator has to edit the proposals store to resolve it."
465
+ )
466
+ return retval
467
+
468
+
469
+ def _pid_alive(pid: Any) -> bool:
470
+ try:
471
+ os.kill(int(pid), 0)
472
+ except (ProcessLookupError, TypeError, ValueError):
473
+ retval = False
474
+ return retval
475
+ except PermissionError:
476
+ retval = True
477
+ return retval
478
+ retval = True
479
+ return retval
480
+
481
+
482
+ def _resolved_elsewhere(cfg: ApprovalsConfig, store: ProposalStore) -> int:
483
+ """Proposals resolved by a button or a link inside the `hours` window.
484
+
485
+ This pass counts what *it* did, so a proposal resolved by a click or a tap
486
+ between two passes simply stopped being `pending` and left no trace in any
487
+ line an operator reads -- `approvals=0 executed=0 ... stuck=0`, a quiet
488
+ agent, while the listener was working through leads. The count is derived
489
+ from the store rather than tracked, so it needs no new state and double
490
+ counts nothing: the same window the reply path already reads.
491
+ """
492
+ cutoff = time.time() - cfg.hours * 3600
493
+ retval = 0
494
+ try:
495
+ # `failed` too: a link or button verdict whose steps failed is
496
+ # recorded as `failed` with a `decided_via`, and counting only the two
497
+ # happy statuses left exactly the case an operator most needs to see
498
+ # printed as `failed=0 ... elsewhere=0`. `failed` in this line counts
499
+ # only this pass's own work, so without this the listener's failures
500
+ # appeared nowhere at all.
501
+ resolved = (
502
+ store.with_status(STATUS_DONE)
503
+ + store.with_status(STATUS_SKIPPED)
504
+ + store.with_status(STATUS_FAILED)
505
+ )
506
+ except Exception as exc:
507
+ # This runs inside the `finally` that prints the summary line, which is
508
+ # printed unconditionally. A raise here would replace whatever actually
509
+ # went wrong with a failure to count, so an unreadable store costs the
510
+ # count and nothing else. The line says so, because `elsewhere=-1` on
511
+ # its own is indistinguishable from a counting bug.
512
+ print(
513
+ f"agent={cfg.agent} could not count what was resolved elsewhere "
514
+ f"(elsewhere=-1): {type(exc).__name__}: {exc}",
515
+ file=sys.stderr,
516
+ )
517
+ retval = -1
518
+ return retval
519
+ for proposal in resolved:
520
+ if proposal.get("decided_via") not in ("button", "link"):
521
+ continue
522
+ when = proposal.get("resolved")
523
+ if not when:
524
+ continue
525
+ try:
526
+ if datetime.fromisoformat(when).timestamp() >= cutoff:
527
+ retval += 1
528
+ except ValueError:
529
+ continue
530
+ return retval
531
+
532
+
533
+ def _is_stuck(cfg: ApprovalsConfig, proposal: dict[str, Any]) -> bool:
534
+ """A `running` proposal whose claiming pass is gone, or too old to trust.
535
+
536
+ Two passes overlapping for a few seconds is normal and the second one must
537
+ not cry wolf about the first, so `running` alone is not stuck. The pass
538
+ that claimed it recorded its pid; on the single host these run on, a dead
539
+ pid means it died mid-steps. Pids get reused, so a claim older than the
540
+ `hours` window is stuck regardless of what that pid is doing now.
541
+ """
542
+ claimed_at = proposal.get("claimed_at")
543
+ age = None
544
+ if claimed_at:
545
+ age = time.time() - datetime.fromisoformat(claimed_at).timestamp()
546
+ too_old = True if age is None else age > cfg.hours * 3600
547
+
548
+ # A claim made by the action page (issue #124) records the *listener's*
549
+ # pid, which outlives any one request by design, so `_pid_alive` is always
550
+ # true for it and the pid test -- the thing that detects a pass dying
551
+ # mid-steps -- can never fire. Judge those on age alone, and on a much
552
+ # shorter clock than `hours`: a request that has held a claim for a quarter
553
+ # of an hour is not still working, and waiting out a 24-hour window to say
554
+ # so means a lead whose steps really ran sits unreported for a day.
555
+ if proposal.get("claimed_via") == "link":
556
+ retval = True if age is None else age > _LINK_CLAIM_STALE_SECONDS
557
+ return retval
558
+
559
+ retval = too_old or not _pid_alive(proposal.get("claimed_pid"))
560
+ return retval
561
+
562
+
563
+ def _report_stuck(cfg: ApprovalsConfig, store: ProposalStore) -> int:
564
+ """Say, every pass, which proposals an earlier pass left `running`.
565
+
566
+ stderr every time, the channel once per proposal. Nothing here changes a
567
+ proposal's status: leaving `running` is the operator's call.
568
+ """
569
+ stuck = [p for p in store.running() if _is_stuck(cfg, p)]
570
+ for proposal in stuck:
571
+ print(
572
+ f"agent: proposal {proposal['id']} ({proposal['action']}) is stuck in "
573
+ f"'running' since {proposal.get('claimed_at')} (pid {proposal.get('claimed_pid')}); "
574
+ "not re-run, edit state/proposals.json to resolve",
575
+ file=sys.stderr,
576
+ )
577
+ if proposal.get("stuck_reported"):
578
+ continue
579
+ _slack_call(
580
+ "chat.postMessage",
581
+ cfg.bot_token,
582
+ cfg.timeout,
583
+ channel=cfg.channel_id,
584
+ text=_stuck_text(proposal),
585
+ )
586
+ store.transition(proposal["id"], STATUS_RUNNING, STATUS_RUNNING, stuck_reported=True)
587
+ retval = len(stuck)
588
+ return retval
589
+
590
+
591
+ def _outcome_text(proposal: dict[str, Any], status: str, results: list, error: str | None) -> str:
592
+ pid = proposal["id"]
593
+ action = proposal["action"]
594
+ if status == STATUS_SKIPPED:
595
+ retval = f"Proposal {pid} ({action}): skipped."
596
+ return retval
597
+ steps = steps_detail(results)
598
+ if status == STATUS_DONE:
599
+ retval = f"Proposal {pid} ({action}): done. Steps: {steps}."
600
+ return retval
601
+ retval = f":x: Proposal {pid} ({action}): failed. {error} Steps: {steps}."
602
+ return retval
603
+
604
+
605
+ def run_approvals(cfg: ApprovalsConfig) -> int:
606
+ """One pass: read replies, resolve every pending proposal that has one."""
607
+ store = ProposalStore(proposals_path(cfg.workspace))
608
+ pending = 0
609
+ executed = 0
610
+ skipped = 0
611
+ failed = 0
612
+ stuck = 0
613
+ status = "failed"
614
+ try:
615
+ stuck = _report_stuck(cfg, store)
616
+ proposals = store.pending()
617
+ pending = len(proposals)
618
+ replies = read_replies(cfg) if proposals else {}
619
+
620
+ for proposal in proposals:
621
+ pid = proposal["id"]
622
+ reply = replies.get(pid)
623
+ if reply is None:
624
+ continue
625
+ if float(reply["ts"]) <= created_ts(proposal):
626
+ print(
627
+ f"agent: ignoring '{reply['verb']} {pid}' at ts {reply['ts']}: "
628
+ f"it predates the proposal ({proposal['created']})",
629
+ file=sys.stderr,
630
+ )
631
+ continue
632
+ decided = {
633
+ "decided_by": reply["user"],
634
+ "decided_ts": reply["ts"],
635
+ "decided_via": "reply",
636
+ }
637
+ if reply["verb"] == "skip":
638
+ if store.transition(pid, STATUS_PENDING, STATUS_SKIPPED, **decided) is None:
639
+ continue
640
+ skipped += 1
641
+ text = _outcome_text(proposal, STATUS_SKIPPED, [], None)
642
+ else:
643
+ claimed = store.transition(
644
+ pid,
645
+ STATUS_PENDING,
646
+ STATUS_RUNNING,
647
+ claimed_at=_now_iso(),
648
+ claimed_pid=os.getpid(),
649
+ variant=VARIANT_POST,
650
+ **decided,
651
+ )
652
+ if claimed is None:
653
+ # Another pass got there first; whatever it does is its
654
+ # to report.
655
+ continue
656
+ results, error = _run_steps(cfg, store, proposal)
657
+ if error is None:
658
+ store.transition(pid, STATUS_RUNNING, STATUS_DONE, results=results)
659
+ executed += 1
660
+ text = _outcome_text(proposal, STATUS_DONE, results, None)
661
+ else:
662
+ store.transition(
663
+ pid, STATUS_RUNNING, STATUS_FAILED, results=results, error=error
664
+ )
665
+ failed += 1
666
+ text = _outcome_text(proposal, STATUS_FAILED, results, error)
667
+ _slack_call(
668
+ "chat.postMessage", cfg.bot_token, cfg.timeout, channel=cfg.channel_id, text=text
669
+ )
670
+ status = "ok"
671
+ finally:
672
+ print(
673
+ f"agent={cfg.agent} status={status} approvals={pending} "
674
+ f"executed={executed} skipped={skipped} failed={failed} stuck={stuck} "
675
+ f"elsewhere={_resolved_elsewhere(cfg, store)}"
676
+ )
677
+ retval = 0
678
+ return retval