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
@@ -0,0 +1,546 @@
1
+ """Digest destination: summarize a whole run into one message (issues #13, #20).
2
+
3
+ Buffers every signal in `send()` and emits a single LLM-written summary in
4
+ `flush()`, using the hook added in #26. This is the destination for agents whose
5
+ output is a narrative rather than a stream of items: the weekly release notes,
6
+ the daily community digest.
7
+
8
+ The prompt lives in config, not in code. What makes a good digest is a matter of
9
+ taste that gets tuned by reading real output, and a prompt in YAML can be
10
+ iterated without a release.
11
+
12
+ Two defaults chosen deliberately:
13
+
14
+ - **A quiet run says so, in one line, and stops.** `empty_message` is posted
15
+ when nothing came through, so silence is always distinguishable from
16
+ breakage. A digest that pads to look busy trains you to stop reading it.
17
+ - **The model that answered is named in the footer.** With a waterfall the
18
+ quality varies by which model picked up, and a thin digest is worth reading
19
+ differently if the primary was down.
20
+
21
+ `gate: true` (the default) is a labelling concern only — the digest is prefixed
22
+ as a draft for review. Actually publishing anywhere other than Slack is a
23
+ separate destination; this one only ever posts to a webhook.
24
+
25
+ `render()` (issue #21) is the same digest handed back as parts instead of
26
+ posted, so the `approval` destination can wrap this one and turn the digest
27
+ into a proposal. `flush()` is `render()` plus the post, and behaves exactly as
28
+ before when this destination is used on its own.
29
+
30
+ `fields` (issue #63) is what an approved *multi-step* action needs. A digest
31
+ that only ever produces one blob of prose gives an action sequence exactly one
32
+ template name, `{body_md}`, so a release-notes action that publishes the post
33
+ and then posts a blurb to a social account has nowhere to get the blurb from
34
+ and fails at that step, after the post is already published. With `fields`, the
35
+ model is asked for one JSON object with those keys instead of prose, and every
36
+ key becomes a template name for the action's steps:
37
+
38
+ "fields": {
39
+ "title": "A post title, under 70 characters.",
40
+ "body_md": "The post itself, Markdown.",
41
+ "blurb_twitter": "Under 240 characters, plain text, no hashtags."
42
+ }
43
+
44
+ The values are descriptions written for the model, not defaults. `body_md` is
45
+ required among them, because it is what `render()` promises its caller and what
46
+ the proposal's Slack message shows. `empty`, `footer`, `items` and `model` are
47
+ refused: `render()` sets those for its caller, and a drafted string landing on
48
+ `empty` would tell the approval destination there was nothing to propose,
49
+ losing a digest that had already been written. Without a `fields` key nothing
50
+ changes: one prose summary, in `body_md`.
51
+
52
+ A reply that is not a JSON object carrying every configured key raises
53
+ `DigestFieldError` after one retry, and the run ends without recording a
54
+ proposal. Half a release announcement is worse than none: the next run asks
55
+ again with the same signals, because nothing was marked seen.
56
+
57
+ `meta_values` (issue #75) is the other half of that. A drafted field is the
58
+ model's prose, and prose is the wrong source for a tag list: a post's taxonomy
59
+ must not change because the model phrased its answer differently. So `render()`
60
+ also returns values the destination computed itself from the buffered signals,
61
+ not from the reply. The first is `repos`: the distinct `meta["repo"]` values of
62
+ the items the model was shown, comma-separated, which for the release-notes
63
+ agent is exactly the repos that released this run. They appear twice in the
64
+ rendered result — once collected under `meta_values`, for a caller that wants to
65
+ know which values were computed rather than drafted, and once as plain top-level
66
+ keys, because an action's steps template against the proposal payload by bare
67
+ name (`framework/templating.py` refuses `{meta_values[repos]}` for reaching into
68
+ a value) and `{repos}` has to resolve. A field name that collides with one of
69
+ them is refused at build time rather than shadowed, so a config cannot end up
70
+ with a taxonomy the model wrote.
71
+
72
+ The digest posts through an incoming webhook (`webhook_env`) or through
73
+ `chat.postMessage` (`bot_token_env` plus `channel_id`), exactly one of the two
74
+ (issue #86). Only the second honours `username` / `icon_emoji`, which is the
75
+ whole point for a deployment running several digests through one Slack app:
76
+ a webhook ignores them and every digest arrives under the same name.
77
+
78
+ The digest the model writes is Markdown, and it goes out through
79
+ `framework.slack.post_message`, which renders it as mrkdwn and splits a digest
80
+ past the block limit into several messages in order (issue #73). `render()` is
81
+ untouched by that: its `body_md` stays Markdown, because that is what a
82
+ WordPress publish step wants. `username` / `icon_emoji` / `icon_url` (issue
83
+ #77) name this digest in the channel, so two digests posted seconds apart
84
+ through one webhook do not read as one message.
85
+
86
+ `show_scores` (issue #57) decides whether the model is shown each item's score
87
+ and the scorer's reasons. Omitted, it follows `min_score`, which is exactly the
88
+ behaviour #63 shipped. Set to true it shows them with no gate at all, for a
89
+ digest that ranks and explains rather than filters — the meetups digest groups
90
+ events into tiers by score, and its filter is the tiering, not a threshold.
91
+
92
+ `min_score` (issue #63) drops low-scoring signals before the model ever sees
93
+ them, for agents whose scorer is a filter rather than a ranking. Dropped items
94
+ are not in the item count either, so a run that gates everything out reads as
95
+ the quiet run it was. Signals are still marked seen: the gate says "not worth
96
+ summarizing", not "look at this again next run". A gated run also shows the
97
+ model each item's score and the scorer's reasons, and an ungated one does not
98
+ unless `show_scores` says otherwise, so a digest that was running before
99
+ either change reads exactly the prompt it always did.
100
+
101
+ `max_item_chars` (default 800) is how much of each item's text the model is
102
+ shown. A weekly events announcement runs past 800 characters, and a cut at
103
+ 800 dropped the second half of the week from the digest without a trace.
104
+
105
+ `calendar_card` posts a second message after a non-empty digest: the events
106
+ the run's items announce, each with an "Add to calendar" link button. See
107
+ `framework/calendar_card.py` for its config and why the model only extracts.
108
+
109
+ Contract: see docs/PLUGIN-CONTRACT.md.
110
+ """
111
+ from __future__ import annotations
112
+
113
+ import json
114
+
115
+ import requests
116
+
117
+ from framework.calendar_card import CalendarCard, build_calendar_card, warn
118
+ from framework.interfaces import Destination, ScoredSignal
119
+ from framework.llm import LLMClient, LLMError, build_client
120
+ from framework.registry import register_destination
121
+ from framework.slack import (
122
+ SlackIdentity,
123
+ SlackTransport,
124
+ identity_from_config,
125
+ post_message,
126
+ transport_from_config,
127
+ )
128
+
129
+ _DEFAULT_SYSTEM = (
130
+ "You write short, factual internal digests. Lead with what matters. "
131
+ "Omit anything routine. If little happened, say so plainly and stop — "
132
+ "never pad to fill space."
133
+ )
134
+
135
+ _DECODER = json.JSONDecoder()
136
+
137
+ # Keys `render()` sets for its caller, which a drafted field must never
138
+ # overwrite. `empty` is the dangerous one: a truthy `empty` tells the approval
139
+ # destination there is nothing to propose, so a real digest would be posted
140
+ # and dropped, its signals marked seen, and the run would report `ok` having
141
+ # silently lost drafted content. `title` and `body_md` are absent on purpose:
142
+ # drafting them is the point, and `title`'s override is handled.
143
+ _RESERVED_FIELDS = frozenset({"empty", "footer", "items", "model"})
144
+
145
+ # Keys `render()` computes from the signals themselves (issue #75). Reserved for
146
+ # the same reason as the ones above, and one more: these exist precisely so a
147
+ # taxonomy can come from something the model never wrote, which a drafted field
148
+ # of the same name would quietly undo.
149
+ _COMPUTED_FIELDS = frozenset({"meta_values", "repos"})
150
+
151
+
152
+ class DigestFieldError(RuntimeError):
153
+ """The model answered, but not with a JSON object carrying every field.
154
+
155
+ Not an `LLMError`: every rung of the waterfall answered, so the chain is
156
+ healthy and reporting it as a dead chain would send an operator after the
157
+ wrong thing. `flush()` still surfaces it to the channel the same way.
158
+ """
159
+
160
+
161
+ def _fields_instruction(fields: dict[str, str]) -> str:
162
+ """The JSON-only contract appended to the system prompt."""
163
+ lines = [f' "{name}": {description}' for name, description in fields.items()]
164
+ body = "\n".join(lines)
165
+ retval = (
166
+ "Reply with a single JSON object and nothing else -- no code fence, no "
167
+ "commentary before or after it. The object has exactly these keys, each "
168
+ "a string:\n"
169
+ f"{body}\n"
170
+ "Every key must be present and non-empty."
171
+ )
172
+ return retval
173
+
174
+
175
+ _RETRY_REMINDER = (
176
+ "\n\n---\n\nYour previous reply could not be read. Reply with one JSON object "
177
+ "and nothing else: no code fence, no text before or after it, every key "
178
+ "present, every value a non-empty string."
179
+ )
180
+
181
+
182
+ def _first_object_with(raw: str, names: list[str]) -> dict | None:
183
+ """First JSON object in `raw` that carries every name in `names`, or None.
184
+
185
+ Tries a decode at each `{` rather than spanning first-`{` to last-`}`: a
186
+ model that appends a second object (a correction, an example) must not
187
+ turn one readable answer into unparseable "extra data". Same reading the
188
+ llm scorer does for its `score` object.
189
+ """
190
+ retval = None
191
+ pos = raw.find("{")
192
+ while pos != -1 and retval is None:
193
+ try:
194
+ candidate, _end = _DECODER.raw_decode(raw, pos)
195
+ except ValueError:
196
+ candidate = None
197
+ if isinstance(candidate, dict) and all(name in candidate for name in names):
198
+ retval = candidate
199
+ pos = raw.find("{", pos + 1)
200
+ return retval
201
+
202
+
203
+ def _parse_fields(raw: str, fields: dict[str, str]) -> dict[str, str]:
204
+ """Read the configured fields out of a model reply, or raise.
205
+
206
+ Every key has to be there and has to be a non-empty string. A field that
207
+ came back as an empty string is the failure this is here to catch: it
208
+ templates into a step as nothing at all, and an approved action would post
209
+ a blank blurb rather than fail.
210
+ """
211
+ names = list(fields)
212
+ payload = _first_object_with(raw, names)
213
+ if payload is None:
214
+ raise DigestFieldError(
215
+ f"no JSON object with the keys {', '.join(names)} in model reply: {raw[:300]!r}"
216
+ )
217
+ retval = {}
218
+ for name in names:
219
+ value = payload[name]
220
+ if not isinstance(value, str) or not value.strip():
221
+ raise DigestFieldError(
222
+ f"field {name!r} came back as {type(value).__name__} "
223
+ f"{str(value)[:80]!r}, not a non-empty string"
224
+ )
225
+ retval[name] = value.strip()
226
+ return retval
227
+
228
+
229
+ class DigestDestination:
230
+ def __init__(
231
+ self,
232
+ transport: SlackTransport,
233
+ llm: LLMClient,
234
+ prompt: str,
235
+ system: str = _DEFAULT_SYSTEM,
236
+ title: str = "Digest",
237
+ empty_message: str = "Nothing new this run.",
238
+ max_signals: int = 200,
239
+ gate: bool = True,
240
+ channel_label: str = "",
241
+ timeout: int = 30,
242
+ fields: dict[str, str] | None = None,
243
+ min_score: int = 0,
244
+ show_scores: bool | None = None,
245
+ identity: SlackIdentity | None = None,
246
+ calendar_card: CalendarCard | None = None,
247
+ max_item_chars: int = 800,
248
+ ):
249
+ self.transport = transport
250
+ self.llm = llm
251
+ self.prompt = prompt
252
+ self.system = system
253
+ self.title = title
254
+ self.empty_message = empty_message
255
+ self.max_signals = max_signals
256
+ self.gate = gate
257
+ self.channel_label = channel_label
258
+ self.timeout = timeout
259
+ self.fields = fields or {}
260
+ self.min_score = min_score
261
+ # None means "follow min_score", which is what every config written
262
+ # before this option existed gets. See `_render_items`.
263
+ self.show_scores = min_score > 0 if show_scores is None else show_scores
264
+ self.identity = identity or SlackIdentity()
265
+ self.calendar_card = calendar_card
266
+ self.max_item_chars = max_item_chars
267
+ self._buffered: list[ScoredSignal] = []
268
+
269
+ def send(self, scored: ScoredSignal) -> None:
270
+ if scored.score < self.min_score:
271
+ return
272
+ self._buffered.append(scored)
273
+
274
+ def _render_items(self) -> str:
275
+ """The item list the model reads.
276
+
277
+ Scores and the scorer's reasons are shown when `show_scores` says so,
278
+ which by default means "when `min_score` gates the run". That default is
279
+ the original behaviour (issue #63): a config with a gate is demonstrably
280
+ using scores for something, and showing them lets the model say which
281
+ items cleared the bar, while a config without one gets the list it has
282
+ always got rather than a prompt newly seasoned with whatever its scorer
283
+ writes into `reasons` ("matched keyword X", for the regex scorer).
284
+
285
+ `show_scores: true` unties the two (issue #57). An agent can want the
286
+ model to *rank and explain* without wanting it to *filter*: the meetups
287
+ digest groups events into tiers by score and prints one reason line per
288
+ rubric dimension, and it deliberately sets no `min_score`, because the
289
+ tiering is the filter. Before this option that config was impossible to
290
+ express — the scores it is built around would never have reached the
291
+ model, and the digest would have been written from titles and URLs with
292
+ the rubric silently discarded.
293
+ """
294
+ show_scores = self.show_scores
295
+ lines = []
296
+ for scored in self._buffered[: self.max_signals]:
297
+ sig = scored.signal
298
+ head = (sig.meta or {}).get("title") or sig.text.splitlines()[0]
299
+ line = f"- [{scored.score}] {head}" if show_scores else f"- {head}"
300
+ if sig.url:
301
+ line += f" ({sig.url})"
302
+ if show_scores and scored.reasons:
303
+ line += f"\n why: {'; '.join(scored.reasons)}"
304
+ body = sig.text.strip()
305
+ if body and body != head:
306
+ line += f"\n {body[: self.max_item_chars]}"
307
+ lines.append(line)
308
+ retval = "\n".join(lines)
309
+ return retval
310
+
311
+ def _meta_values(self) -> dict[str, str]:
312
+ """Values computed from the buffered signals, for taxonomy and the like.
313
+
314
+ `repos`: the distinct `meta["repo"]` values, in first-seen order,
315
+ comma-separated. Taken from the same `max_signals` slice the model is
316
+ shown, so the tags on a post always describe the items in it; an item
317
+ omitted past `max_signals` is not in the prose either. A source whose
318
+ signals carry no `repo` yields an empty string, which the WordPress
319
+ action drops rather than turning into an empty tag.
320
+ """
321
+ repos: list[str] = []
322
+ for scored in self._buffered[: self.max_signals]:
323
+ repo = str((scored.signal.meta or {}).get("repo") or "").strip()
324
+ if repo and repo not in repos:
325
+ repos.append(repo)
326
+ retval = {"repos": ", ".join(repos)}
327
+ return retval
328
+
329
+ def _post(self, text: str) -> None:
330
+ post_message(self.transport, text, timeout=self.timeout, identity=self.identity)
331
+
332
+ def render(self) -> dict:
333
+ """Write the digest without posting it (issue #21).
334
+
335
+ This is the hook the `approval` destination uses to turn a digest into
336
+ a proposal: the same LLM call `flush()` makes, returned as parts rather
337
+ than sent. `title` and `body_md` are the contract; `footer` carries the
338
+ item count and the model that answered; `empty` is True when nothing
339
+ came through this run, so a wrapper can tell a quiet run from a digest
340
+ worth proposing. An LLM failure raises `LLMError`; the caller decides
341
+ where to surface it. Does not clear the buffer, so it can be called more
342
+ than once per run.
343
+ """
344
+ meta_values = self._meta_values()
345
+ if not self._buffered:
346
+ retval = {
347
+ "title": self.title,
348
+ "body_md": self.empty_message,
349
+ "footer": "",
350
+ "empty": True,
351
+ "items": 0,
352
+ "meta_values": meta_values,
353
+ **meta_values,
354
+ }
355
+ return retval
356
+
357
+ dropped = max(0, len(self._buffered) - self.max_signals)
358
+ user = f"{self.prompt}\n\n---\n\n{self._render_items()}"
359
+ if self.fields:
360
+ drafted = self._complete_fields(user)
361
+ else:
362
+ drafted = {"body_md": self.llm.complete(self.system, user)}
363
+
364
+ footer = self._extras_block(drafted)
365
+ footer += f"_{len(self._buffered)} item(s) · {self.llm.model_used}_"
366
+ if dropped:
367
+ footer += f" · _{dropped} item(s) omitted past max_signals_"
368
+ retval = {
369
+ "title": self.title,
370
+ "body_md": drafted["body_md"],
371
+ "footer": footer,
372
+ "empty": False,
373
+ "items": len(self._buffered),
374
+ "model": self.llm.model_used,
375
+ "meta_values": meta_values,
376
+ }
377
+ # The configured fields are the template names an approved action's
378
+ # steps render against, so they go in whole, after the keys above:
379
+ # a field named `title` is the model's post title and replaces the
380
+ # static config one, which is a label for the Slack message.
381
+ retval.update(drafted)
382
+ # After the drafted fields, so the order states the precedence: a
383
+ # computed value is never overwritten by a model-written one. Build-time
384
+ # validation refuses that collision outright, and this is the belt.
385
+ retval.update(meta_values)
386
+ return retval
387
+
388
+ def _complete_fields(self, user: str) -> dict[str, str]:
389
+ """Ask for the configured fields as one JSON object; one retry, then raise."""
390
+ system = f"{self.system}\n\n{_fields_instruction(self.fields)}"
391
+ reply = self.llm.complete(system, user)
392
+ try:
393
+ retval = _parse_fields(reply, self.fields)
394
+ except DigestFieldError as first:
395
+ # Same one-retry rule the llm scorer uses: a model that drifted
396
+ # into prose once usually complies when told so, and a second miss
397
+ # is a real failure rather than a bad roll.
398
+ reply = self.llm.complete(system, user + _RETRY_REMINDER)
399
+ try:
400
+ retval = _parse_fields(reply, self.fields)
401
+ except DigestFieldError as second:
402
+ raise DigestFieldError(
403
+ f"unreadable reply after one retry; first: {first}; retry: {second}"
404
+ ) from second
405
+ return retval
406
+
407
+ def _extras_block(self, drafted: dict[str, str]) -> str:
408
+ """The drafted fields other than `body_md`, shown under the digest.
409
+
410
+ A human approving a proposal has to see everything it will publish, not
411
+ just the part that happens to be the post. Named first, then quoted in
412
+ full, and the whole block sits in `footer` so that `body_md` stays
413
+ exactly what an action's publish step will send.
414
+ """
415
+ extras = [name for name in self.fields if name not in ("body_md", "title")]
416
+ if not extras:
417
+ retval = ""
418
+ return retval
419
+ parts = [f"**also drafted:** {', '.join(extras)}"]
420
+ for name in extras:
421
+ parts.append(f"**{name}**\n{drafted[name]}")
422
+ retval = "\n\n".join(parts) + "\n\n"
423
+ return retval
424
+
425
+ def flush(self) -> None:
426
+ header = f"**{self.title}**"
427
+ if self.gate:
428
+ header += " _(draft — review before publishing)_"
429
+
430
+ try:
431
+ rendered = self.render()
432
+ except (LLMError, DigestFieldError) as exc:
433
+ # Surface the failure into the channel. Staying silent here would
434
+ # look exactly like a quiet week.
435
+ self._post(f"{header}\n\n:warning: digest not generated — {exc}")
436
+ raise
437
+
438
+ if rendered["empty"]:
439
+ self._post(f"{header}\n\n{rendered['body_md']}")
440
+ return
441
+
442
+ self._post(f"{header}\n\n{rendered['body_md']}\n\n{rendered['footer']}")
443
+ if self.calendar_card is not None:
444
+ self._post_calendar_card(self.calendar_card)
445
+ self._buffered.clear()
446
+
447
+ def _post_calendar_card(self, card: CalendarCard) -> None:
448
+ """The events the run's items announce, as a second message (see framework/calendar_card.py).
449
+
450
+ Posted only when there are events. A failure here is said in the channel
451
+ and on stderr but does not fail the run: the digest is already posted,
452
+ and failing would leave its signals unseen, so the next run would post
453
+ the same digest again to retry a card.
454
+ """
455
+ try:
456
+ events, dropped = card.extract(self._buffered[: self.max_signals])
457
+ if events:
458
+ post_message(
459
+ self.transport,
460
+ f"{card.title}: {len(events)} event(s)",
461
+ timeout=self.timeout,
462
+ identity=self.identity,
463
+ blocks=card.blocks(events, dropped),
464
+ )
465
+ elif dropped:
466
+ warn(f"{dropped} event(s) unreadable or out of range, none usable; no card posted")
467
+ except (LLMError, RuntimeError, requests.RequestException) as exc:
468
+ warn(str(exc))
469
+ try:
470
+ self._post(f"**{card.title}**\n\n:warning: calendar card not posted — {exc}")
471
+ except (RuntimeError, requests.RequestException) as again:
472
+ warn(f"and the warning could not be posted either: {again}")
473
+
474
+
475
+ @register_destination("digest")
476
+ def build(cfg: dict) -> Destination:
477
+ timeout = int(cfg.get("timeout", 30))
478
+ transport = transport_from_config(cfg, "digest destination", timeout)
479
+
480
+ prompt = cfg.get("prompt")
481
+ if not prompt:
482
+ raise RuntimeError("digest destination needs a 'prompt'")
483
+
484
+ fields = cfg.get("fields")
485
+ if fields is not None:
486
+ if not isinstance(fields, dict) or not fields:
487
+ raise RuntimeError(
488
+ "digest destination's 'fields' must be a non-empty object of "
489
+ "name -> description (the description is written for the model)"
490
+ )
491
+ bad = [name for name, desc in fields.items() if not isinstance(desc, str) or not desc]
492
+ if bad:
493
+ raise RuntimeError(
494
+ f"digest destination's fields {', '.join(sorted(bad))} need a "
495
+ "non-empty description string saying what the model should write"
496
+ )
497
+ if "body_md" not in fields:
498
+ raise RuntimeError(
499
+ "digest destination's 'fields' must include 'body_md': it is what "
500
+ "render() promises its caller and what the digest message shows"
501
+ )
502
+ clashes = sorted(name for name in fields if name in _RESERVED_FIELDS)
503
+ if clashes:
504
+ raise RuntimeError(
505
+ f"digest destination's fields {', '.join(clashes)} would overwrite "
506
+ "render()'s own keys; rename them. Reserved: "
507
+ f"{', '.join(sorted(_RESERVED_FIELDS))} "
508
+ "('title' and 'body_md' are yours to draft)"
509
+ )
510
+ computed = sorted(name for name in fields if name in _COMPUTED_FIELDS)
511
+ if computed:
512
+ raise RuntimeError(
513
+ f"digest destination's fields {', '.join(computed)} are computed "
514
+ "from the signals themselves, so asking the model for them would "
515
+ "shadow a value it cannot get wrong; rename them. Computed: "
516
+ f"{', '.join(sorted(_COMPUTED_FIELDS))}"
517
+ )
518
+
519
+ show_scores = cfg.get("show_scores")
520
+ if show_scores is not None and not isinstance(show_scores, bool):
521
+ raise RuntimeError(
522
+ "digest destination's 'show_scores' must be true or false; omit it to "
523
+ "follow 'min_score' (shown when a gate is set), which is the default"
524
+ )
525
+
526
+ llm = build_client(cfg, what="digest destination")
527
+
528
+ retval = DigestDestination(
529
+ transport=transport,
530
+ llm=llm,
531
+ prompt=prompt,
532
+ system=cfg.get("system", _DEFAULT_SYSTEM),
533
+ title=cfg.get("title", "Digest"),
534
+ empty_message=cfg.get("empty_message", "Nothing new this run."),
535
+ max_signals=int(cfg.get("max_signals", 200)),
536
+ gate=bool(cfg.get("gate", True)),
537
+ channel_label=cfg.get("channel", ""),
538
+ timeout=timeout,
539
+ fields=fields,
540
+ min_score=int(cfg.get("min_score", 0)),
541
+ show_scores=show_scores,
542
+ identity=identity_from_config(cfg, "digest destination"),
543
+ max_item_chars=int(cfg.get("max_item_chars", 800)),
544
+ calendar_card=build_calendar_card(cfg["calendar_card"], llm) if cfg.get("calendar_card") else None,
545
+ )
546
+ return retval