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/drafter.py ADDED
@@ -0,0 +1,263 @@
1
+ """A second, grounded generation pass over an already-scored signal (issue #83).
2
+
3
+ The scorer answers "is this a lead". A drafter answers "what would we say", and
4
+ those are different jobs that must not share a prompt:
5
+
6
+ - A score is a judgement about the signal. A draft is a **claim about us** --
7
+ what we can do, what we have done, what we would offer. Claims need
8
+ provenance; a judgement does not.
9
+ - So a drafter is fed from named files and told to use nothing else. The
10
+ scorer's prompt describes a posture; the drafter's inputs are documents.
11
+
12
+ That separation is the whole design, and it is why this is not another `fields`
13
+ block on the scorer. A model asked to score and pitch in one call will reach for
14
+ its own knowledge of the company to do the second half, and that is exactly the
15
+ failure a grounded drafter exists to prevent: a plausible sentence about a
16
+ capability nobody has.
17
+
18
+ ## Grounding
19
+
20
+ `grounding` is a list of file paths, read at **build** time and concatenated
21
+ with a header naming each file. Build time rather than per-signal so a missing
22
+ or unreadable file fails the run at startup, where it is a misconfiguration,
23
+ rather than silently producing an ungrounded draft on signal seventeen.
24
+
25
+ The total is capped by `max_grounding_chars`; exceeding it raises rather than
26
+ truncating, because a silently truncated grounding set drops whichever document
27
+ sorts last and nothing says so.
28
+
29
+ ## Failure is never silent, and never costs the lead
30
+
31
+ `draft()` raises `DraftError` after one retry. The caller is expected to keep
32
+ the signal and say the draft is missing -- the lead itself is the thing worth
33
+ having, and dropping a real lead because a second model call failed would be a
34
+ bad trade. What must not happen is a lead that *looks* complete while carrying
35
+ no draft, so the reason is rendered where the draft would have been.
36
+ """
37
+ from __future__ import annotations
38
+
39
+ import json
40
+ from pathlib import Path
41
+ from typing import Any
42
+
43
+ from framework.interfaces import ScoredSignal
44
+ from framework.llm import LLMClient, build_client
45
+
46
+ _DECODER = json.JSONDecoder()
47
+
48
+ DEFAULT_SYSTEM = (
49
+ "You draft outreach from supplied source documents only. Every capability, "
50
+ "result or number you state must appear in those documents. If something is "
51
+ "not in them, leave it out rather than inferring it -- an unsupported claim "
52
+ "is worse than a shorter draft."
53
+ )
54
+
55
+ _RETRY_REMINDER = (
56
+ "\n\n---\n\nYour previous reply could not be read. Reply with one JSON object "
57
+ "and nothing else: no code fence, no text before or after it, every key "
58
+ "present, every value a non-empty string."
59
+ )
60
+
61
+
62
+ class DraftError(RuntimeError):
63
+ """The model answered, but not with a usable object.
64
+
65
+ Not an `LLMError`: the chain is healthy. The caller surfaces it next to the
66
+ signal rather than failing the run, because one unusable draft must not cost
67
+ an otherwise good lead.
68
+ """
69
+
70
+
71
+ def _first_object_with(raw: str, names: list[str]) -> dict | None:
72
+ """First JSON object in `raw` carrying every name. Same reading the llm
73
+ scorer and digest destination do: decode at each `{` rather than spanning
74
+ first-to-last, so a model that appends a second object does not turn one
75
+ readable answer into unparseable extra data."""
76
+ retval = None
77
+ pos = raw.find("{")
78
+ while pos != -1 and retval is None:
79
+ try:
80
+ candidate, _end = _DECODER.raw_decode(raw, pos)
81
+ except ValueError:
82
+ candidate = None
83
+ if isinstance(candidate, dict) and all(n in candidate for n in names):
84
+ retval = candidate
85
+ pos = raw.find("{", pos + 1)
86
+ return retval
87
+
88
+
89
+ def load_grounding(paths: list[str], max_chars: int, label: str) -> str:
90
+ """Read every grounding file, or raise naming the one that failed."""
91
+ if not paths:
92
+ raise RuntimeError(f"{label}: 'grounding' must name at least one file")
93
+ parts: list[str] = []
94
+ total = 0
95
+ for raw_path in paths:
96
+ path = Path(raw_path).expanduser()
97
+ try:
98
+ text = path.read_text(encoding="utf-8").strip()
99
+ except OSError as exc:
100
+ raise RuntimeError(
101
+ f"{label}: cannot read grounding file {str(path)!r}: {exc}. "
102
+ "Every claim in a draft comes from these files, so a missing one "
103
+ "is a misconfiguration, not a degraded run."
104
+ ) from exc
105
+ if not text:
106
+ raise RuntimeError(f"{label}: grounding file {str(path)!r} is empty")
107
+ total += len(text)
108
+ parts.append(f"--- SOURCE: {path.name} ---\n{text}")
109
+ if total > max_chars:
110
+ raise RuntimeError(
111
+ f"{label}: grounding is {total} characters, over max_grounding_chars "
112
+ f"({max_chars}). Raise the cap or name fewer files -- truncating would "
113
+ "silently drop whichever document sorts last."
114
+ )
115
+ retval = "\n\n".join(parts)
116
+ return retval
117
+
118
+
119
+ class Drafter:
120
+ def __init__(
121
+ self,
122
+ llm: LLMClient,
123
+ grounding: str,
124
+ prompt: str,
125
+ fields: dict[str, str],
126
+ system: str = DEFAULT_SYSTEM,
127
+ max_signal_chars: int = 4000,
128
+ ):
129
+ self.llm = llm
130
+ self.grounding = grounding
131
+ self.prompt = prompt
132
+ self.fields = fields
133
+ self.system = system
134
+ self.max_signal_chars = max_signal_chars
135
+
136
+ def _instruction(self) -> str:
137
+ lines = [f' "{name}": {desc}' for name, desc in self.fields.items()]
138
+ retval = (
139
+ "Reply with a single JSON object and nothing else -- no code fence, no "
140
+ "commentary before or after it. The object has exactly these keys, each "
141
+ "a string:\n" + "\n".join(lines) + "\nEvery key must be present and non-empty."
142
+ )
143
+ return retval
144
+
145
+ def _user(self, scored: ScoredSignal) -> str:
146
+ sig = scored.signal
147
+ meta: dict[str, Any] = sig.meta or {}
148
+ bits = [self.prompt, "", "--- SOURCE DOCUMENTS (the only permitted basis for claims) ---",
149
+ self.grounding, "", "--- THE POST ---",
150
+ f"url: {sig.url}", f"score: {scored.score}"]
151
+ if scored.reasons:
152
+ bits.append("why it scored: " + "; ".join(scored.reasons))
153
+ rules = meta.get("subreddit_rules")
154
+ if rules:
155
+ # Shown so the draft can obey the community's own rule rather than a
156
+ # generalisation about what communities usually allow.
157
+ bits.append(f"subreddit rules that bear on self-promotion:\n{rules}")
158
+ bits.append(sig.text[: self.max_signal_chars])
159
+ retval = "\n".join(bits)
160
+ return retval
161
+
162
+ def draft(self, scored: ScoredSignal) -> dict[str, str]:
163
+ system = f"{self.system}\n\n{self._instruction()}"
164
+ user = self._user(scored)
165
+ reply = self.llm.complete(system, user)
166
+ try:
167
+ retval = self._parse(reply)
168
+ except DraftError as first:
169
+ reply = self.llm.complete(system, user + _RETRY_REMINDER)
170
+ try:
171
+ retval = self._parse(reply)
172
+ except DraftError as second:
173
+ raise DraftError(
174
+ f"unreadable reply after one retry; first: {first}; retry: {second}"
175
+ ) from second
176
+ return retval
177
+
178
+ def _parse(self, raw: str) -> dict[str, str]:
179
+ names = list(self.fields)
180
+ payload = _first_object_with(raw, names)
181
+ if payload is None:
182
+ raise DraftError(
183
+ f"no JSON object with the keys {', '.join(names)} in model reply: {raw[:200]!r}"
184
+ )
185
+ retval = {}
186
+ for name in names:
187
+ value = payload[name]
188
+ if not isinstance(value, str) or not value.strip():
189
+ raise DraftError(
190
+ f"field {name!r} came back as {type(value).__name__} "
191
+ f"{str(value)[:60]!r}, not a non-empty string"
192
+ )
193
+ retval[name] = value.strip()
194
+ return retval
195
+
196
+
197
+ def drafter_inputs(block: dict, label: str) -> dict[str, Any]:
198
+ """A `drafter` block's validated inputs, grounding already read.
199
+
200
+ Everything a `Drafter` needs except its model client, which wants the
201
+ workspace and root that only the run (or, for an action, the approvals
202
+ pass) knows. Split out so a caller that learns those later can still fail
203
+ on a bad block, or an unreadable grounding file, when it is built.
204
+ """
205
+ prompt = block.get("prompt")
206
+ if not prompt or not isinstance(prompt, str):
207
+ raise RuntimeError(f"{label}: 'drafter' needs a 'prompt'")
208
+
209
+ fields = block.get("fields")
210
+ if not isinstance(fields, dict) or not fields:
211
+ raise RuntimeError(
212
+ f"{label}: 'drafter' needs 'fields', an object of name -> "
213
+ "description written for the model"
214
+ )
215
+ bad = sorted(n for n, d in fields.items() if not isinstance(d, str) or not d.strip())
216
+ if bad:
217
+ raise RuntimeError(f"{label}: drafter fields {', '.join(bad)} need a non-empty description")
218
+
219
+ grounding_paths = block.get("grounding")
220
+ if not isinstance(grounding_paths, list) or not all(
221
+ isinstance(p, str) and p.strip() for p in grounding_paths
222
+ ):
223
+ raise RuntimeError(
224
+ f"{label}: 'drafter' needs 'grounding', a non-empty list of file "
225
+ "paths. A draft makes claims about us, and claims need provenance"
226
+ )
227
+ grounding = load_grounding(
228
+ grounding_paths,
229
+ int(block.get("max_grounding_chars", 60000)),
230
+ f"{label} drafter",
231
+ )
232
+ retval = {
233
+ "grounding": grounding,
234
+ "prompt": prompt,
235
+ "fields": fields,
236
+ "system": block.get("system") or DEFAULT_SYSTEM,
237
+ "max_signal_chars": int(block.get("max_signal_chars", 4000)),
238
+ }
239
+ return retval
240
+
241
+
242
+ def drafter_with_llm(
243
+ block: dict, inputs: dict[str, Any], label: str, workspace: Any, root: Any
244
+ ) -> Drafter:
245
+ """A `Drafter` from `drafter_inputs()`, with its model client built now.
246
+
247
+ The drafter's own chain if the block names one, else the deployment's
248
+ waterfall (framework/llm.py).
249
+ """
250
+ llm_cfg = dict(block)
251
+ if workspace and "_workspace" not in llm_cfg:
252
+ llm_cfg["_workspace"] = str(workspace)
253
+ if root and "_root" not in llm_cfg:
254
+ llm_cfg["_root"] = str(root)
255
+ llm = build_client(llm_cfg, what=f"{label} drafter")
256
+ retval = Drafter(llm=llm, **inputs)
257
+ return retval
258
+
259
+
260
+ def build_drafter(block: dict, label: str, workspace: Any, root: Any) -> Drafter:
261
+ """Validate a `drafter` block, read its grounding and build its client."""
262
+ retval = drafter_with_llm(block, drafter_inputs(block, label), label, workspace, root)
263
+ return retval
@@ -0,0 +1,96 @@
1
+ """Plugin interfaces for the agents framework.
2
+
3
+ One real implementation each for v1 (Reddit source, regex scorer, Slack
4
+ destination) — but defined as interfaces from the start since a new source
5
+ may need different shapes (see planning discussion, not guessed abstractly
6
+ in advance beyond this).
7
+ """
8
+ from __future__ import annotations
9
+
10
+ from dataclasses import dataclass, field
11
+ from typing import Any, Protocol
12
+
13
+
14
+ @dataclass
15
+ class Signal:
16
+ """One raw item pulled from a Source, before scoring."""
17
+
18
+ id: str # stable id used for dedupe (e.g. reddit post id)
19
+ text: str
20
+ url: str
21
+ source: str
22
+ meta: dict[str, Any] = field(default_factory=dict)
23
+
24
+
25
+ @dataclass
26
+ class ScoredSignal:
27
+ signal: Signal
28
+ score: int
29
+ reasons: list[str] = field(default_factory=list)
30
+
31
+
32
+ class Source(Protocol):
33
+ """Produces raw Signals for one run. No side effects beyond fetching.
34
+
35
+ A source may also define `commit()`, called once by the runner after
36
+ `seen.save()` has succeeded, and only on a `status=ok` run (never on a
37
+ `partial` one, whose unscored signals must stay inside the next window). It
38
+ is for a source that tracks its own fetch window (the github-releases
39
+ source's `last_run`): the window advances in `commit()`, never in `fetch()`,
40
+ so a run that fails to deliver does not move it. Like `Destination.flush()`
41
+ it is discovered with getattr and is deliberately not part of this Protocol
42
+ (issue #46).
43
+ """
44
+
45
+ def fetch(self) -> list[Signal]:
46
+ ...
47
+
48
+
49
+ class ScoreError(RuntimeError):
50
+ """This one signal could not be scored; others may be.
51
+
52
+ A scorer raises it (or a subclass) when the failure belongs to the signal,
53
+ not to the scorer: the model answered, but not with a readable score. The
54
+ runner skips that signal without sending or marking it, so the next run
55
+ retries it, and finishes the run for everything else with `status=partial`.
56
+ Anything else a scorer raises, such as every model in the chain being down,
57
+ still aborts the run, because it would fail every signal the same way.
58
+ """
59
+
60
+
61
+ class Scorer(Protocol):
62
+ """Scores a Signal. Raises `ScoreError` for a failure specific to that
63
+ signal; any other exception aborts the run."""
64
+
65
+ def score(self, signal: Signal) -> ScoredSignal:
66
+ ...
67
+
68
+
69
+ class Destination(Protocol):
70
+ """Delivers a ScoredSignal somewhere. Slack for v1; email later.
71
+
72
+ A destination may also define `flush()`, called once by the runner after the
73
+ last signal. Streaming destinations deliver in `send()` and need no flush;
74
+ batching and digest destinations buffer in `send()` and emit in `flush()`.
75
+ It is deliberately not part of this Protocol — the runner discovers it with
76
+ getattr, so existing destinations stay valid without change (issue #26).
77
+ """
78
+
79
+ def send(self, scored: ScoredSignal) -> None:
80
+ ...
81
+
82
+
83
+ class Action(Protocol):
84
+ """One step of an approved action (issue #21).
85
+
86
+ Actions are the fourth plugin kind, alongside Source / Scorer / Destination.
87
+ They never run inside `agent run`: a destination records a *proposal*, and a
88
+ separate `agent approvals` pass executes the proposal's steps only after a
89
+ trusted human has replied `do <id>`. `payload` is the proposal's content
90
+ merged with the results of earlier steps; `context` carries run-level facts
91
+ (workspace path, proposal id). The returned dict is merged into the payload
92
+ seen by later steps, so a step publishes values by name for the ones after it.
93
+ """
94
+
95
+ def execute(self, payload: dict[str, Any], context: dict[str, Any]) -> dict[str, Any]:
96
+ ...