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,413 @@
|
|
|
1
|
+
"""WordPress.com publish action (issue #47).
|
|
2
|
+
|
|
3
|
+
An *action*, not a destination: nothing here runs inside `agent run`. A
|
|
4
|
+
destination records a proposal, a trusted human replies `do <id>`, and only
|
|
5
|
+
then does `agent approvals` call `execute()` on this step (issue #21). The
|
|
6
|
+
step turns a Markdown draft into a WordPress.com post and hands the post's
|
|
7
|
+
URL and id to the steps after it.
|
|
8
|
+
|
|
9
|
+
{
|
|
10
|
+
"type": "wordpress-publish",
|
|
11
|
+
"site": "<site>.wordpress.com",
|
|
12
|
+
"mode": "draft",
|
|
13
|
+
"token_env": "WORDPRESS_ACCESS_TOKEN",
|
|
14
|
+
"categories": ["releases"],
|
|
15
|
+
"tags": ["voitta", "release-notes", "{repos}"]
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
Config keys:
|
|
19
|
+
|
|
20
|
+
- `site` (required) blog domain or numeric blog id as WordPress.com
|
|
21
|
+
addresses it: `<site>.wordpress.com`, a mapped custom domain,
|
|
22
|
+
or the blog_id from `GET /rest/v1.1/me/sites`.
|
|
23
|
+
- `mode` `draft` or `publish`. `draft` is the operator's safety valve
|
|
24
|
+
for first runs: the post lands in the editor unpublished and
|
|
25
|
+
the returned `url` is its preview. `publish` makes it public
|
|
26
|
+
at once and the returned `url` is the public permalink.
|
|
27
|
+
- `token_env` env var holding the OAuth2 bearer token; default
|
|
28
|
+
`WORDPRESS_ACCESS_TOKEN`.
|
|
29
|
+
- `categories` list of category names; optional. Templated, see below.
|
|
30
|
+
- `tags` list of tag names; optional. Templated, see below.
|
|
31
|
+
- `excerpt` the post's excerpt; optional, templated against the payload.
|
|
32
|
+
Without it WordPress derives one from the opening words, which
|
|
33
|
+
is what every feed reader and every RSS-driven integration then
|
|
34
|
+
shows. A config that has drafted copy for that audience points
|
|
35
|
+
this at it (e.g. `"{page_post}"`).
|
|
36
|
+
|
|
37
|
+
`execute(payload, context)` reads `payload["title"]` and `payload["body_md"]`
|
|
38
|
+
and returns `{"url": ..., "post_id": ...}` for later steps to template.
|
|
39
|
+
|
|
40
|
+
**Taxonomy is templated, and per-run (issue #75).** The interesting tags on a
|
|
41
|
+
weekly release-notes post are not static: they are which repos actually
|
|
42
|
+
released. So every `categories` and `tags` entry goes through
|
|
43
|
+
`framework.templating.render_template` against the payload, exactly like a
|
|
44
|
+
step's other fields, and an entry that expands to a comma-separated string
|
|
45
|
+
becomes separate names — `"{repos}"` with three repos in the payload is three
|
|
46
|
+
tags, not one tag with commas in it. Blank entries are dropped instead of
|
|
47
|
+
creating an empty tag (a source whose signals carry no `repo` yields an empty
|
|
48
|
+
`{repos}`), and duplicates collapse, compared case-insensitively, keeping the
|
|
49
|
+
first spelling: the standing tag list and the per-run repos overlap whenever a
|
|
50
|
+
repo is named after the project. Order is the config's, first occurrence first.
|
|
51
|
+
|
|
52
|
+
Take the per-run values from the digest's `meta_values` (`{repos}`), which the
|
|
53
|
+
destination computes from the signals, rather than from a field the model
|
|
54
|
+
drafted. A tag list is not prose: it must not change because a reply was worded
|
|
55
|
+
differently, and a model asked for "the repositories covered" can leave one out.
|
|
56
|
+
|
|
57
|
+
Splitting on commas is not a behaviour change for a real static config, because
|
|
58
|
+
the API takes these as comma-separated strings in the first place, so a name
|
|
59
|
+
with a comma in it was never sendable. A static entry with `{` or `}` in it is
|
|
60
|
+
now a template error, which is the same rule every other action field follows.
|
|
61
|
+
|
|
62
|
+
The token, the conversion and the failure modes all follow the
|
|
63
|
+
`wordpress-com-publish` skill (voitta-ai/skillz), which is the reference for
|
|
64
|
+
publishing to `public-api.wordpress.com`. Its findings are the reason this
|
|
65
|
+
module is shaped the way it is:
|
|
66
|
+
|
|
67
|
+
- **Token: environment first, then macOS Keychain.** The skill stores the
|
|
68
|
+
token it mints under the Keychain service `wpcom_token`, so a token minted
|
|
69
|
+
once by `/wordpress-com-publish --auth` serves every agent on that machine
|
|
70
|
+
without copying it into a profile. The env var still wins when set, which
|
|
71
|
+
is how a deployment that does not use Keychain supplies it. There is no
|
|
72
|
+
third source and no minting here: the authorization-code flow needs a
|
|
73
|
+
browser login, which an unattended action cannot do. A missing token
|
|
74
|
+
raises at `execute`, naming the env var and the skill that mints one.
|
|
75
|
+
- **A 401 is not a draft.** WordPress answers a revoked token with
|
|
76
|
+
`authorization_required` and an unknown one with `invalid_token`. Either
|
|
77
|
+
raises, naming re-minting as the fix. It
|
|
78
|
+
never degrades `publish` to `draft`, and it never returns a fake result:
|
|
79
|
+
a step that reports success without a post is the silent failure this
|
|
80
|
+
repo's history is made of.
|
|
81
|
+
- **Send Gutenberg block markup, not HTML.** WordPress runs `content` through
|
|
82
|
+
`wpautop`, which reflows raw HTML: long headings acquire newlines and code
|
|
83
|
+
blocks are dropped or garbled. Block markup (`<!-- wp:heading -->`,
|
|
84
|
+
`<!-- wp:paragraph -->`, `<!-- wp:code -->`, `<!-- wp:list -->`) is stored
|
|
85
|
+
verbatim and each element becomes its own block in the editor. The
|
|
86
|
+
conversion below is the skill's `md2wp.py` rule set, ported: render
|
|
87
|
+
Markdown to HTML, then wrap each top-level element in the block comment
|
|
88
|
+
for its tag. The skill renders with pandoc (`--wrap=none`, because pandoc's
|
|
89
|
+
default line wrapping is what put newlines in headings in the first place);
|
|
90
|
+
this port renders with markdown-it-py, a CommonMark renderer that is a
|
|
91
|
+
pip dependency rather than a system binary and does not wrap output, so
|
|
92
|
+
the trap does not apply. CommonMark rather than Python-Markdown because
|
|
93
|
+
the body will usually be LLM output, which nests list items by two
|
|
94
|
+
spaces; Python-Markdown needs four and silently flattens two, while
|
|
95
|
+
CommonMark nests a `-` item's children at two or four. Under a numbered
|
|
96
|
+
item CommonMark wants children indented to the item's text (three spaces
|
|
97
|
+
for `1. `), so two spaces there still comes out flat.
|
|
98
|
+
Heading levels are kept as written: the payload author owns the body, and
|
|
99
|
+
the skill's default of shifting `#` down a level exists for pasting a
|
|
100
|
+
standalone document under a post title, not for a body authored as a post.
|
|
101
|
+
- **The POST response is rendered, not stored.** Its `content` has the block
|
|
102
|
+
comments stripped, so verifying what WordPress kept means
|
|
103
|
+
`GET .../posts/<ID>?context=edit`, not reading the response.
|
|
104
|
+
- **`posts/new` is not idempotent, and nothing here retries.** A timeout
|
|
105
|
+
after WordPress accepted the request can leave a post that this action
|
|
106
|
+
reports as failed, so check the site before re-running by hand.
|
|
107
|
+
|
|
108
|
+
Not in scope, per the issue: updating an existing post, media upload, and a
|
|
109
|
+
scheduled (`future`) publish date.
|
|
110
|
+
|
|
111
|
+
Contract: see docs/PLUGIN-CONTRACT.md.
|
|
112
|
+
"""
|
|
113
|
+
from __future__ import annotations
|
|
114
|
+
|
|
115
|
+
import os
|
|
116
|
+
import re
|
|
117
|
+
import shutil
|
|
118
|
+
import subprocess
|
|
119
|
+
from html.parser import HTMLParser
|
|
120
|
+
from typing import Any
|
|
121
|
+
|
|
122
|
+
import requests
|
|
123
|
+
from markdown_it import MarkdownIt
|
|
124
|
+
|
|
125
|
+
from framework.interfaces import Action
|
|
126
|
+
from framework.registry import register_action
|
|
127
|
+
from framework.templating import render_template
|
|
128
|
+
|
|
129
|
+
_API = "https://public-api.wordpress.com/rest/v1.1"
|
|
130
|
+
_MODES = ("draft", "publish")
|
|
131
|
+
_DEFAULT_TOKEN_ENV = "WORDPRESS_ACCESS_TOKEN"
|
|
132
|
+
_KEYCHAIN_SERVICE = "wpcom_token"
|
|
133
|
+
_SKILL = "wordpress-com-publish"
|
|
134
|
+
# The "commonmark" preset passes raw HTML through, matching pandoc gfm in the
|
|
135
|
+
# skill; tables are a GFM extension the preset leaves off.
|
|
136
|
+
_MD = MarkdownIt("commonmark").enable("table")
|
|
137
|
+
# WordPress.com reports a revoked token as HTTP 401 `authorization_required`
|
|
138
|
+
# (the skill's finding) and a malformed or unknown one as HTTP 400
|
|
139
|
+
# `invalid_token` (observed while verifying this action). Both mean the same
|
|
140
|
+
# thing to an operator: mint a new token.
|
|
141
|
+
_AUTH_ERRORS = ("authorization_required", "invalid_token")
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
class WordPressPublishError(Exception):
|
|
145
|
+
"""The post could not be created; the message names the remedy."""
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
_VOID_TAGS = frozenset(
|
|
149
|
+
("area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta",
|
|
150
|
+
"source", "track", "wbr")
|
|
151
|
+
)
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
class _BlockSplitter(HTMLParser):
|
|
155
|
+
"""Collect the top-level elements of an HTML fragment as (tag, raw) pairs.
|
|
156
|
+
|
|
157
|
+
Same shape as the parser in the skill's `md2wp.py`: text between top-level
|
|
158
|
+
elements is dropped, everything inside one is re-emitted verbatim,
|
|
159
|
+
entities included (`convert_charrefs=False` keeps `<` in code as-is).
|
|
160
|
+
One addition: a void element written without the self-closing slash
|
|
161
|
+
(`<br>`, `<img ...>` in raw HTML inside the Markdown) never gets an end
|
|
162
|
+
tag, and counting it as an open element would leave the depth stuck above
|
|
163
|
+
zero and silently drop every block after it. A void element at the top
|
|
164
|
+
level (`---` renders as `<hr />`) is a block of its own.
|
|
165
|
+
"""
|
|
166
|
+
|
|
167
|
+
def __init__(self) -> None:
|
|
168
|
+
super().__init__(convert_charrefs=False)
|
|
169
|
+
self.depth = 0
|
|
170
|
+
self.blocks: list[tuple[str, str]] = []
|
|
171
|
+
self.cur = ""
|
|
172
|
+
self.curtag = ""
|
|
173
|
+
|
|
174
|
+
def handle_starttag(self, tag: str, attrs: list) -> None:
|
|
175
|
+
if self.depth == 0:
|
|
176
|
+
self.curtag = tag
|
|
177
|
+
self.cur = ""
|
|
178
|
+
self.cur += self.get_starttag_text() or ""
|
|
179
|
+
if tag not in _VOID_TAGS:
|
|
180
|
+
self.depth += 1
|
|
181
|
+
elif self.depth == 0:
|
|
182
|
+
self._emit()
|
|
183
|
+
|
|
184
|
+
def handle_startendtag(self, tag: str, attrs: list) -> None:
|
|
185
|
+
if self.depth == 0:
|
|
186
|
+
self.curtag = tag
|
|
187
|
+
self.cur = ""
|
|
188
|
+
self.cur += self.get_starttag_text() or ""
|
|
189
|
+
if self.depth == 0:
|
|
190
|
+
self._emit()
|
|
191
|
+
|
|
192
|
+
def _emit(self) -> None:
|
|
193
|
+
self.blocks.append((self.curtag, self.cur))
|
|
194
|
+
self.cur = ""
|
|
195
|
+
self.curtag = ""
|
|
196
|
+
|
|
197
|
+
def handle_endtag(self, tag: str) -> None:
|
|
198
|
+
self.depth -= 1
|
|
199
|
+
self.cur += f"</{tag}>"
|
|
200
|
+
if self.depth == 0:
|
|
201
|
+
self._emit()
|
|
202
|
+
|
|
203
|
+
def handle_data(self, data: str) -> None:
|
|
204
|
+
if self.depth > 0:
|
|
205
|
+
self.cur += data
|
|
206
|
+
|
|
207
|
+
def handle_entityref(self, name: str) -> None:
|
|
208
|
+
if self.depth > 0:
|
|
209
|
+
self.cur += f"&{name};"
|
|
210
|
+
|
|
211
|
+
def handle_charref(self, name: str) -> None:
|
|
212
|
+
if self.depth > 0:
|
|
213
|
+
self.cur += f"&#{name};"
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def _markdown_to_blocks(body_md: str) -> str:
|
|
217
|
+
"""Markdown -> Gutenberg block markup, per the skill's `md2wp.py` rules."""
|
|
218
|
+
html = _MD.render(body_md)
|
|
219
|
+
splitter = _BlockSplitter()
|
|
220
|
+
splitter.feed(html)
|
|
221
|
+
splitter.close()
|
|
222
|
+
out: list[str] = []
|
|
223
|
+
for tag, raw in splitter.blocks:
|
|
224
|
+
if re.fullmatch(r"h[1-6]", tag):
|
|
225
|
+
lvl = int(tag[1])
|
|
226
|
+
raw = re.sub(rf"^<h{lvl}\b", f'<h{lvl} class="wp-block-heading"', raw, count=1)
|
|
227
|
+
attr = "" if lvl == 2 else f' {{"level":{lvl}}}'
|
|
228
|
+
out.append(f"<!-- wp:heading{attr} -->\n{raw}\n<!-- /wp:heading -->")
|
|
229
|
+
elif tag == "p":
|
|
230
|
+
out.append(f"<!-- wp:paragraph -->\n{raw}\n<!-- /wp:paragraph -->")
|
|
231
|
+
elif tag == "pre":
|
|
232
|
+
raw = re.sub(r"^<pre\b[^>]*>", '<pre class="wp-block-code">', raw, count=1)
|
|
233
|
+
out.append(f"<!-- wp:code -->\n{raw}\n<!-- /wp:code -->")
|
|
234
|
+
elif tag == "ul":
|
|
235
|
+
raw = re.sub(r"^<ul\b[^>]*>", '<ul class="wp-block-list">', raw, count=1)
|
|
236
|
+
out.append(f"<!-- wp:list -->\n{raw}\n<!-- /wp:list -->")
|
|
237
|
+
elif tag == "ol":
|
|
238
|
+
# The renderer writes start="N" for a list not beginning at 1; the
|
|
239
|
+
# block keeps it both on the tag and in its attributes, or a list
|
|
240
|
+
# starting at 3 would be renumbered from 1.
|
|
241
|
+
start = re.match(r'^<ol\b[^>]*\bstart="(\d+)"', raw)
|
|
242
|
+
if start:
|
|
243
|
+
n = int(start.group(1))
|
|
244
|
+
raw = re.sub(
|
|
245
|
+
r"^<ol\b[^>]*>", f'<ol start="{n}" class="wp-block-list">', raw, count=1
|
|
246
|
+
)
|
|
247
|
+
attrs = f'{{"ordered":true,"start":{n}}}'
|
|
248
|
+
else:
|
|
249
|
+
raw = re.sub(r"^<ol\b[^>]*>", '<ol class="wp-block-list">', raw, count=1)
|
|
250
|
+
attrs = '{"ordered":true}'
|
|
251
|
+
out.append(f"<!-- wp:list {attrs} -->\n{raw}\n<!-- /wp:list -->")
|
|
252
|
+
elif tag == "blockquote":
|
|
253
|
+
out.append(f"<!-- wp:quote -->\n{raw}\n<!-- /wp:quote -->")
|
|
254
|
+
else:
|
|
255
|
+
out.append(f"<!-- wp:html -->\n{raw}\n<!-- /wp:html -->")
|
|
256
|
+
retval = "\n\n".join(out)
|
|
257
|
+
return retval
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def _taxonomy(entries: list[str], values: dict[str, Any]) -> list[str]:
|
|
261
|
+
"""Render taxonomy entries, split on commas, drop blanks, collapse duplicates."""
|
|
262
|
+
names: list[str] = []
|
|
263
|
+
seen: set[str] = set()
|
|
264
|
+
for entry in entries:
|
|
265
|
+
for part in render_template(entry, values).split(","):
|
|
266
|
+
name = part.strip()
|
|
267
|
+
key = name.casefold()
|
|
268
|
+
if name and key not in seen:
|
|
269
|
+
seen.add(key)
|
|
270
|
+
names.append(name)
|
|
271
|
+
retval = names
|
|
272
|
+
return retval
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
def _keychain_token() -> str:
|
|
276
|
+
"""The skill's Keychain fallback; empty when absent or not on macOS."""
|
|
277
|
+
retval = ""
|
|
278
|
+
security = shutil.which("security")
|
|
279
|
+
if security is not None:
|
|
280
|
+
proc = subprocess.run(
|
|
281
|
+
[security, "find-generic-password", "-s", _KEYCHAIN_SERVICE, "-w"],
|
|
282
|
+
capture_output=True,
|
|
283
|
+
text=True,
|
|
284
|
+
check=False,
|
|
285
|
+
)
|
|
286
|
+
if proc.returncode == 0:
|
|
287
|
+
retval = proc.stdout.strip()
|
|
288
|
+
return retval
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
def _resolve_token(token_env: str) -> str:
|
|
292
|
+
token = os.environ.get(token_env, "").strip()
|
|
293
|
+
if not token:
|
|
294
|
+
token = _keychain_token()
|
|
295
|
+
if not token:
|
|
296
|
+
raise WordPressPublishError(
|
|
297
|
+
f"wordpress-publish: no token; set {token_env} or store one in the "
|
|
298
|
+
f"macOS Keychain under service {_KEYCHAIN_SERVICE!r}. Mint one with "
|
|
299
|
+
f"the {_SKILL} skill (`/{_SKILL} --auth`); it needs a browser login, "
|
|
300
|
+
"so this cannot run unattended."
|
|
301
|
+
)
|
|
302
|
+
retval = token
|
|
303
|
+
return retval
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
class WordPressPublishAction:
|
|
307
|
+
def __init__(
|
|
308
|
+
self,
|
|
309
|
+
site: str,
|
|
310
|
+
mode: str,
|
|
311
|
+
token_env: str = _DEFAULT_TOKEN_ENV,
|
|
312
|
+
categories: list[str] | None = None,
|
|
313
|
+
tags: list[str] | None = None,
|
|
314
|
+
excerpt: str = "",
|
|
315
|
+
timeout: int = 30,
|
|
316
|
+
):
|
|
317
|
+
if not site:
|
|
318
|
+
raise ValueError("wordpress-publish: `site` is required")
|
|
319
|
+
if mode not in _MODES:
|
|
320
|
+
raise ValueError(
|
|
321
|
+
f"wordpress-publish: mode must be one of {list(_MODES)}, got {mode!r}"
|
|
322
|
+
)
|
|
323
|
+
self.site = site
|
|
324
|
+
self.mode = mode
|
|
325
|
+
self.token_env = token_env
|
|
326
|
+
self.categories = list(categories or [])
|
|
327
|
+
self.tags = list(tags or [])
|
|
328
|
+
self.excerpt = excerpt
|
|
329
|
+
self._timeout = timeout
|
|
330
|
+
|
|
331
|
+
def execute(self, payload: dict[str, Any], context: dict[str, Any]) -> dict[str, Any]:
|
|
332
|
+
for key in ("title", "body_md"):
|
|
333
|
+
if not payload.get(key):
|
|
334
|
+
raise WordPressPublishError(
|
|
335
|
+
f"wordpress-publish: payload is missing {key!r}; the proposal "
|
|
336
|
+
"must supply `title` and `body_md` (Markdown)"
|
|
337
|
+
)
|
|
338
|
+
token = _resolve_token(self.token_env)
|
|
339
|
+
form: dict[str, str] = {
|
|
340
|
+
"title": payload["title"],
|
|
341
|
+
"content": _markdown_to_blocks(payload["body_md"]),
|
|
342
|
+
"status": self.mode,
|
|
343
|
+
}
|
|
344
|
+
# The excerpt is what a feed reader -- and anything downstream of the
|
|
345
|
+
# site's RSS -- shows instead of the post. WordPress derives one from
|
|
346
|
+
# the opening words when none is given, which is fine on the site and
|
|
347
|
+
# wrong everywhere else: a syndicated post then leads with whatever
|
|
348
|
+
# sentence happened to come first. Templated like the taxonomy, so a
|
|
349
|
+
# config can point it at a field the digest drafted for that audience.
|
|
350
|
+
# A template that renders to nothing is left unset rather than sent as
|
|
351
|
+
# an empty string, which WordPress would take as "no excerpt" anyway but
|
|
352
|
+
# which would also silently hide a misnamed field.
|
|
353
|
+
if self.excerpt:
|
|
354
|
+
excerpt = render_template(self.excerpt, payload).strip()
|
|
355
|
+
if excerpt:
|
|
356
|
+
form["excerpt"] = excerpt
|
|
357
|
+
|
|
358
|
+
categories = _taxonomy(self.categories, payload)
|
|
359
|
+
if categories:
|
|
360
|
+
form["categories"] = ",".join(categories)
|
|
361
|
+
tags = _taxonomy(self.tags, payload)
|
|
362
|
+
if tags:
|
|
363
|
+
form["tags"] = ",".join(tags)
|
|
364
|
+
resp = requests.post(
|
|
365
|
+
f"{_API}/sites/{self.site}/posts/new",
|
|
366
|
+
headers={"Authorization": f"Bearer {token}"},
|
|
367
|
+
data=form,
|
|
368
|
+
timeout=self._timeout,
|
|
369
|
+
)
|
|
370
|
+
body = self._json(resp)
|
|
371
|
+
if resp.status_code in (401, 403) or body.get("error") in _AUTH_ERRORS:
|
|
372
|
+
raise WordPressPublishError(
|
|
373
|
+
f"wordpress-publish: HTTP {resp.status_code} "
|
|
374
|
+
f"{body.get('error', '')}: the token in {self.token_env} (or the "
|
|
375
|
+
f"Keychain item {_KEYCHAIN_SERVICE!r}) was rejected; re-mint it with "
|
|
376
|
+
f"the {_SKILL} skill (`/{_SKILL} --auth`). Nothing was posted."
|
|
377
|
+
)
|
|
378
|
+
if not resp.ok or "ID" not in body:
|
|
379
|
+
raise WordPressPublishError(
|
|
380
|
+
f"wordpress-publish: HTTP {resp.status_code} from {self.site}: "
|
|
381
|
+
f"{body.get('error', '')} {body.get('message', '')}".rstrip()
|
|
382
|
+
)
|
|
383
|
+
url = body["URL"]
|
|
384
|
+
if self.mode == "draft":
|
|
385
|
+
# The API's URL for a draft is the `?p=<id>` form, which a logged-in
|
|
386
|
+
# editor can open; `preview=true` makes it the same link the editor's
|
|
387
|
+
# own Preview button produces, so the approver lands on the preview.
|
|
388
|
+
url = f"{url}{'&' if '?' in url else '?'}preview=true"
|
|
389
|
+
retval = {"url": url, "post_id": body["ID"]}
|
|
390
|
+
return retval
|
|
391
|
+
|
|
392
|
+
@staticmethod
|
|
393
|
+
def _json(resp: requests.Response) -> dict[str, Any]:
|
|
394
|
+
try:
|
|
395
|
+
parsed = resp.json()
|
|
396
|
+
except ValueError:
|
|
397
|
+
parsed = {}
|
|
398
|
+
retval = parsed if isinstance(parsed, dict) else {}
|
|
399
|
+
return retval
|
|
400
|
+
|
|
401
|
+
|
|
402
|
+
@register_action("wordpress-publish")
|
|
403
|
+
def build(cfg: dict) -> Action:
|
|
404
|
+
retval = WordPressPublishAction(
|
|
405
|
+
site=cfg.get("site", ""),
|
|
406
|
+
mode=cfg.get("mode", ""),
|
|
407
|
+
token_env=cfg.get("token_env", _DEFAULT_TOKEN_ENV),
|
|
408
|
+
categories=cfg.get("categories"),
|
|
409
|
+
tags=cfg.get("tags"),
|
|
410
|
+
excerpt=cfg.get("excerpt", ""),
|
|
411
|
+
timeout=int(cfg.get("timeout", 30)),
|
|
412
|
+
)
|
|
413
|
+
return retval
|
framework/proposals.py
ADDED
|
@@ -0,0 +1,246 @@
|
|
|
1
|
+
"""The proposals store: `<workspace>/state/proposals.json` (issue #21).
|
|
2
|
+
|
|
3
|
+
A proposal is the unit of approval-gated work. The `approval` destination
|
|
4
|
+
records one at the end of an `agent run`, and the `agent approvals` pass later
|
|
5
|
+
flips it to `done`, `skipped` or `failed` after a trusted human has replied in
|
|
6
|
+
Slack. Both are run-and-exit processes on independent launchd clocks, so the
|
|
7
|
+
file is the only thing they share.
|
|
8
|
+
|
|
9
|
+
Shape on disk:
|
|
10
|
+
|
|
11
|
+
{
|
|
12
|
+
"next_id": 3,
|
|
13
|
+
"proposals": [
|
|
14
|
+
{"id": "p1-k3f", "created": "...", "created_ts": 1757700000.0,
|
|
15
|
+
"action": "publish-post",
|
|
16
|
+
"payload": {"title": "...", "body_md": "..."},
|
|
17
|
+
"status": "done", "decided_by": "U0123456789", "decided_ts": "...",
|
|
18
|
+
"claimed_at": "...", "claimed_pid": 4242, "resolved": "...",
|
|
19
|
+
"results": [{"step": 1, "type": "slack-post", "status": "ok", "result": {}}]},
|
|
20
|
+
{"id": "p2-x9q", ..., "status": "pending"}
|
|
21
|
+
]
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
Ids are short, monotonic per workspace, and not guessable in advance: a
|
|
25
|
+
base-36 counter with a `p` prefix, then a dash and three random base-36
|
|
26
|
+
characters. The counter keeps them readable in order; the suffix means nobody
|
|
27
|
+
can type `do p10` into the channel today and have it approve whatever becomes
|
|
28
|
+
p10 next week. A reply has to quote the whole id. Nothing is ever deleted; a
|
|
29
|
+
resolved proposal stays as the audit trail of what was posted where, which is
|
|
30
|
+
the record an operator asks for when a published post needs explaining.
|
|
31
|
+
|
|
32
|
+
Statuses: `pending` -> `running` -> `done` | `failed`, or `pending` ->
|
|
33
|
+
`skipped`. `running` exists so that executing a proposal is an atomic claim:
|
|
34
|
+
`transition()` compares the current status under the lock and refuses to
|
|
35
|
+
change a proposal that is not in the expected state, so two approvals passes
|
|
36
|
+
that both read the same pending proposal cannot both run its steps. The one
|
|
37
|
+
whose claim fails sees None and moves on. A proposal still `running` when a
|
|
38
|
+
pass starts means an earlier pass died mid-steps; it is reported, never
|
|
39
|
+
re-run automatically (see `framework/approvals.py`).
|
|
40
|
+
|
|
41
|
+
Two processes can touch the file within the same second (a run recording a
|
|
42
|
+
proposal while the approvals pass flips another one), so every read-modify-
|
|
43
|
+
write holds an `fcntl` lock on a sibling `.lock` file and the write is a
|
|
44
|
+
rename of a temp file. Without that, whichever process saved last would
|
|
45
|
+
silently discard the other's change: a proposal that was never posted about,
|
|
46
|
+
or a `done` that reverted to `pending` and executed twice. Cheap insurance
|
|
47
|
+
against the worst kind of failure this store can have.
|
|
48
|
+
"""
|
|
49
|
+
from __future__ import annotations
|
|
50
|
+
|
|
51
|
+
import fcntl
|
|
52
|
+
import json
|
|
53
|
+
import os
|
|
54
|
+
import secrets
|
|
55
|
+
from contextlib import contextmanager
|
|
56
|
+
from datetime import datetime, timezone
|
|
57
|
+
from pathlib import Path
|
|
58
|
+
from typing import Any, Iterator
|
|
59
|
+
|
|
60
|
+
STATE_DIRNAME = "state"
|
|
61
|
+
PROPOSALS_FILENAME = "proposals.json"
|
|
62
|
+
|
|
63
|
+
STATUS_PENDING = "pending"
|
|
64
|
+
STATUS_RUNNING = "running"
|
|
65
|
+
STATUS_DONE = "done"
|
|
66
|
+
STATUS_SKIPPED = "skipped"
|
|
67
|
+
STATUS_FAILED = "failed"
|
|
68
|
+
|
|
69
|
+
_ID_PREFIX = "p"
|
|
70
|
+
_DIGITS = "0123456789abcdefghijklmnopqrstuvwxyz"
|
|
71
|
+
_SUFFIX_LEN = 3
|
|
72
|
+
_TERMINAL = (STATUS_DONE, STATUS_SKIPPED, STATUS_FAILED)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _base36(n: int) -> str:
|
|
76
|
+
if n == 0:
|
|
77
|
+
retval = "0"
|
|
78
|
+
return retval
|
|
79
|
+
out = []
|
|
80
|
+
while n:
|
|
81
|
+
n, rem = divmod(n, 36)
|
|
82
|
+
out.append(_DIGITS[rem])
|
|
83
|
+
retval = "".join(reversed(out))
|
|
84
|
+
return retval
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def _now() -> str:
|
|
88
|
+
retval = datetime.now(timezone.utc).isoformat(timespec="seconds")
|
|
89
|
+
return retval
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def _suffix() -> str:
|
|
93
|
+
retval = "".join(secrets.choice(_DIGITS) for _ in range(_SUFFIX_LEN))
|
|
94
|
+
return retval
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def created_ts(proposal: dict[str, Any]) -> float:
|
|
98
|
+
"""Epoch seconds the proposal was recorded, for comparing with Slack `ts`."""
|
|
99
|
+
raw = proposal.get("created_ts")
|
|
100
|
+
if raw is None:
|
|
101
|
+
retval = datetime.fromisoformat(proposal["created"]).timestamp()
|
|
102
|
+
else:
|
|
103
|
+
retval = float(raw)
|
|
104
|
+
return retval
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def proposals_path(workspace: str | os.PathLike) -> Path:
|
|
108
|
+
retval = Path(workspace) / STATE_DIRNAME / PROPOSALS_FILENAME
|
|
109
|
+
return retval
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
class ProposalStore:
|
|
113
|
+
def __init__(self, path: Path):
|
|
114
|
+
self.path = Path(path)
|
|
115
|
+
self._lock_path = self.path.with_suffix(self.path.suffix + ".lock")
|
|
116
|
+
|
|
117
|
+
@contextmanager
|
|
118
|
+
def _locked(self) -> Iterator[None]:
|
|
119
|
+
self.path.parent.mkdir(parents=True, exist_ok=True)
|
|
120
|
+
with open(self._lock_path, "w") as lock_fh:
|
|
121
|
+
fcntl.flock(lock_fh, fcntl.LOCK_EX)
|
|
122
|
+
try:
|
|
123
|
+
yield
|
|
124
|
+
finally:
|
|
125
|
+
fcntl.flock(lock_fh, fcntl.LOCK_UN)
|
|
126
|
+
|
|
127
|
+
def _read(self) -> dict[str, Any]:
|
|
128
|
+
if not self.path.exists():
|
|
129
|
+
retval = {"next_id": 1, "proposals": []}
|
|
130
|
+
return retval
|
|
131
|
+
raw = json.loads(self.path.read_text())
|
|
132
|
+
if not isinstance(raw, dict) or not isinstance(raw.get("proposals"), list):
|
|
133
|
+
raise ValueError(f"{self.path}: not a proposals store")
|
|
134
|
+
retval = raw
|
|
135
|
+
return retval
|
|
136
|
+
|
|
137
|
+
def _write(self, data: dict[str, Any]) -> None:
|
|
138
|
+
tmp = self.path.with_suffix(self.path.suffix + ".tmp")
|
|
139
|
+
tmp.write_text(json.dumps(data, indent=2, sort_keys=True))
|
|
140
|
+
os.replace(tmp, self.path)
|
|
141
|
+
|
|
142
|
+
def reserve(self, action: str, payload: dict[str, Any]) -> dict[str, Any]:
|
|
143
|
+
"""Take the next id and build a pending proposal, without storing it.
|
|
144
|
+
|
|
145
|
+
The announcement has to quote the id, and the id has to come from the
|
|
146
|
+
counter, so a caller that wants to announce *before* it commits needs
|
|
147
|
+
the two steps apart (issue #73 review): `reserve()`, post, then `add()`.
|
|
148
|
+
The counter is advanced here and never rewound, so an announcement that
|
|
149
|
+
fails leaves a gap in the numbering rather than a second proposal
|
|
150
|
+
claiming an id the channel has already seen.
|
|
151
|
+
"""
|
|
152
|
+
now = datetime.now(timezone.utc)
|
|
153
|
+
with self._locked():
|
|
154
|
+
data = self._read()
|
|
155
|
+
proposal = {
|
|
156
|
+
"id": f"{_ID_PREFIX}{_base36(int(data['next_id']))}-{_suffix()}",
|
|
157
|
+
"created": now.isoformat(timespec="seconds"),
|
|
158
|
+
"created_ts": now.timestamp(),
|
|
159
|
+
"action": action,
|
|
160
|
+
"payload": payload,
|
|
161
|
+
"status": STATUS_PENDING,
|
|
162
|
+
}
|
|
163
|
+
data["next_id"] = int(data["next_id"]) + 1
|
|
164
|
+
self._write(data)
|
|
165
|
+
retval = proposal
|
|
166
|
+
return retval
|
|
167
|
+
|
|
168
|
+
def add(self, proposal: dict[str, Any]) -> dict[str, Any]:
|
|
169
|
+
"""Store a proposal `reserve()` built. Approvable from this moment on."""
|
|
170
|
+
retval = self.add_all([proposal])[0]
|
|
171
|
+
return retval
|
|
172
|
+
|
|
173
|
+
def add_all(self, proposals: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
|
174
|
+
"""Store several reserved proposals in one write, all or none.
|
|
175
|
+
|
|
176
|
+
A run that announced two actions in one message must not be able to
|
|
177
|
+
leave the first stored and the second not: the write is a single
|
|
178
|
+
`os.replace` under the lock, so a failure leaves the store as it was
|
|
179
|
+
and the next run proposes both again.
|
|
180
|
+
"""
|
|
181
|
+
with self._locked():
|
|
182
|
+
data = self._read()
|
|
183
|
+
data["proposals"].extend(proposals)
|
|
184
|
+
self._write(data)
|
|
185
|
+
retval = proposals
|
|
186
|
+
return retval
|
|
187
|
+
|
|
188
|
+
def record(self, action: str, payload: dict[str, Any]) -> dict[str, Any]:
|
|
189
|
+
"""Reserve and store in one step, for a caller that announces nothing."""
|
|
190
|
+
retval = self.add(self.reserve(action, payload))
|
|
191
|
+
return retval
|
|
192
|
+
|
|
193
|
+
def with_status(self, status: str) -> list[dict[str, Any]]:
|
|
194
|
+
with self._locked():
|
|
195
|
+
data = self._read()
|
|
196
|
+
retval = [p for p in data["proposals"] if p.get("status") == status]
|
|
197
|
+
return retval
|
|
198
|
+
|
|
199
|
+
def get(self, proposal_id: str) -> dict[str, Any] | None:
|
|
200
|
+
"""One proposal by id, or None. A read, so no claim and no lock held."""
|
|
201
|
+
with self._locked():
|
|
202
|
+
data = self._read()
|
|
203
|
+
retval = None
|
|
204
|
+
for proposal in data["proposals"]:
|
|
205
|
+
if proposal.get("id") == proposal_id:
|
|
206
|
+
retval = proposal
|
|
207
|
+
break
|
|
208
|
+
return retval
|
|
209
|
+
|
|
210
|
+
def pending(self) -> list[dict[str, Any]]:
|
|
211
|
+
retval = self.with_status(STATUS_PENDING)
|
|
212
|
+
return retval
|
|
213
|
+
|
|
214
|
+
def running(self) -> list[dict[str, Any]]:
|
|
215
|
+
retval = self.with_status(STATUS_RUNNING)
|
|
216
|
+
return retval
|
|
217
|
+
|
|
218
|
+
def transition(
|
|
219
|
+
self, proposal_id: str, expect: str, status: str, **fields: Any
|
|
220
|
+
) -> dict[str, Any] | None:
|
|
221
|
+
"""Compare-and-set a proposal's status under the lock.
|
|
222
|
+
|
|
223
|
+
Returns the updated proposal, or None when its current status is not
|
|
224
|
+
`expect` -- which is how a second approvals pass learns that the first
|
|
225
|
+
one already claimed (or resolved) it and must not touch it. `expect ==
|
|
226
|
+
status` is allowed and just records `fields` (per-step progress while
|
|
227
|
+
running). A terminal status also stamps `resolved`. An unknown id is
|
|
228
|
+
an error: that is a corrupted store, not a race.
|
|
229
|
+
"""
|
|
230
|
+
with self._locked():
|
|
231
|
+
data = self._read()
|
|
232
|
+
for proposal in data["proposals"]:
|
|
233
|
+
if proposal.get("id") == proposal_id:
|
|
234
|
+
break
|
|
235
|
+
else:
|
|
236
|
+
raise KeyError(f"no proposal {proposal_id!r} in {self.path}")
|
|
237
|
+
if proposal.get("status") != expect:
|
|
238
|
+
retval = None
|
|
239
|
+
return retval
|
|
240
|
+
proposal["status"] = status
|
|
241
|
+
if status in _TERMINAL:
|
|
242
|
+
proposal["resolved"] = _now()
|
|
243
|
+
proposal.update(fields)
|
|
244
|
+
self._write(data)
|
|
245
|
+
retval = proposal
|
|
246
|
+
return retval
|