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
framework/registry.py
ADDED
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
"""Plugin registry: resolve config `type:` strings to constructed plugins.
|
|
2
|
+
|
|
3
|
+
This module freezes the plugin-construction contract that Wave 1 builds
|
|
4
|
+
against (Reddit source #2, Slack destination #3, regex scorer #4), plus the
|
|
5
|
+
action kind added for approval-gated steps (issue #21). See
|
|
6
|
+
docs/PLUGIN-CONTRACT.md for the prose version.
|
|
7
|
+
|
|
8
|
+
The contract, in one sentence: a plugin registers a factory under a `type`
|
|
9
|
+
name; the factory receives that component's whole config block (the mapping
|
|
10
|
+
under `source:` / `scorer:` / `destination:`, including its own `type` key)
|
|
11
|
+
and returns an instance implementing the matching Protocol.
|
|
12
|
+
|
|
13
|
+
@register_source("reddit")
|
|
14
|
+
def build(cfg: dict) -> Source:
|
|
15
|
+
return RedditSource(subreddits=cfg["subreddits"])
|
|
16
|
+
|
|
17
|
+
Factories are populated by importing plugin modules; `load_plugins()` imports
|
|
18
|
+
them to trigger those registrations.
|
|
19
|
+
|
|
20
|
+
Import of a plugin module can fail on a missing optional dependency, and that
|
|
21
|
+
must not take down plugins an agent actually uses (issue #39). `load_plugins()`
|
|
22
|
+
therefore imports each module in isolation, keeps the ones that worked and
|
|
23
|
+
remembers the ones that did not. The tolerance stops here: `build_source` /
|
|
24
|
+
`build_scorer` / `build_destination` raise `PluginImportError` the moment a
|
|
25
|
+
config names a plugin whose module failed, quoting the original `ImportError`.
|
|
26
|
+
|
|
27
|
+
Loud where it matters, tolerant where it does not - an agent on `reddit` +
|
|
28
|
+
`regex` + `slack` runs on a venv without `icalendar`, and an agent configured
|
|
29
|
+
for `ics` on that same venv fails at startup naming the missing package,
|
|
30
|
+
rather than mid-run at first use.
|
|
31
|
+
"""
|
|
32
|
+
from __future__ import annotations
|
|
33
|
+
|
|
34
|
+
from typing import Callable
|
|
35
|
+
|
|
36
|
+
from framework.interfaces import Action, Destination, Scorer, Source
|
|
37
|
+
from framework.plugins import PluginImportFailure, import_all
|
|
38
|
+
|
|
39
|
+
SourceFactory = Callable[[dict], Source]
|
|
40
|
+
ScorerFactory = Callable[[dict], Scorer]
|
|
41
|
+
DestinationFactory = Callable[[dict], Destination]
|
|
42
|
+
ActionFactory = Callable[[dict], Action]
|
|
43
|
+
|
|
44
|
+
_sources: dict[str, SourceFactory] = {}
|
|
45
|
+
_scorers: dict[str, ScorerFactory] = {}
|
|
46
|
+
_destinations: dict[str, DestinationFactory] = {}
|
|
47
|
+
_actions: dict[str, ActionFactory] = {}
|
|
48
|
+
|
|
49
|
+
# `type:` name -> the plugin module whose import failed, populated by
|
|
50
|
+
# load_plugins(). Empty until it runs, and empty afterwards on a complete venv.
|
|
51
|
+
_failed_plugins: dict[str, PluginImportFailure] = {}
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class UnknownPluginError(Exception):
|
|
55
|
+
"""Config referenced a `type:` with no registered factory.
|
|
56
|
+
|
|
57
|
+
Deliberately not a KeyError subclass: KeyError.__str__ wraps its message
|
|
58
|
+
in repr() quotes, which would garble this user-facing CLI error (the exact
|
|
59
|
+
message every Wave-1 dev sees before their plugin is registered).
|
|
60
|
+
"""
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
class PluginImportError(Exception):
|
|
64
|
+
"""Config named a plugin whose module could not be imported.
|
|
65
|
+
|
|
66
|
+
Distinct from `UnknownPluginError` because the two call for different
|
|
67
|
+
fixes: an unknown type is a typo or an unregistered plugin, while this is
|
|
68
|
+
an installed-dependency problem with a known remedy, and the message says
|
|
69
|
+
which package and which plugin.
|
|
70
|
+
"""
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def register_source(type_name: str) -> Callable[[SourceFactory], SourceFactory]:
|
|
74
|
+
def decorator(factory: SourceFactory) -> SourceFactory:
|
|
75
|
+
_sources[type_name] = factory
|
|
76
|
+
return factory
|
|
77
|
+
|
|
78
|
+
return decorator
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def register_scorer(type_name: str) -> Callable[[ScorerFactory], ScorerFactory]:
|
|
82
|
+
def decorator(factory: ScorerFactory) -> ScorerFactory:
|
|
83
|
+
_scorers[type_name] = factory
|
|
84
|
+
return factory
|
|
85
|
+
|
|
86
|
+
return decorator
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def register_destination(type_name: str) -> Callable[[DestinationFactory], DestinationFactory]:
|
|
90
|
+
def decorator(factory: DestinationFactory) -> DestinationFactory:
|
|
91
|
+
_destinations[type_name] = factory
|
|
92
|
+
return factory
|
|
93
|
+
|
|
94
|
+
return decorator
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def register_action(type_name: str) -> Callable[[ActionFactory], ActionFactory]:
|
|
98
|
+
def decorator(factory: ActionFactory) -> ActionFactory:
|
|
99
|
+
_actions[type_name] = factory
|
|
100
|
+
return factory
|
|
101
|
+
|
|
102
|
+
return decorator
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def _build(kind: str, registry: dict, cfg: dict):
|
|
106
|
+
# A failed import outranks whatever is in the registry, and the order here
|
|
107
|
+
# is the whole guarantee. Registration is a side effect on this module's
|
|
108
|
+
# dicts, so a plugin that registers its factory and only then raises
|
|
109
|
+
# ImportError leaves that factory behind after the module itself is gone.
|
|
110
|
+
# Checking the registry first would hand back that orphan and build a
|
|
111
|
+
# plugin whose module is known to be broken -- the failure would resurface
|
|
112
|
+
# later, at first use, stripped of the context that explains it. No plugin
|
|
113
|
+
# imports in that order today; nothing stops one from doing so tomorrow.
|
|
114
|
+
type_name = cfg.get("type")
|
|
115
|
+
failure = _failed_plugins.get(type_name)
|
|
116
|
+
if failure is not None:
|
|
117
|
+
raise PluginImportError(
|
|
118
|
+
f"{kind} type {type_name!r} is provided by plugin module "
|
|
119
|
+
f"{failure.qualified_module!r}, which failed to import: "
|
|
120
|
+
f"{failure.reason()}"
|
|
121
|
+
)
|
|
122
|
+
factory = registry.get(type_name)
|
|
123
|
+
if factory is None:
|
|
124
|
+
known = ", ".join(sorted(registry)) or "(none registered)"
|
|
125
|
+
raise UnknownPluginError(
|
|
126
|
+
f"unknown {kind} type {type_name!r}; registered: {known}"
|
|
127
|
+
)
|
|
128
|
+
retval = factory(cfg)
|
|
129
|
+
return retval
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def build_source(cfg: dict) -> Source:
|
|
133
|
+
retval = _build("source", _sources, cfg)
|
|
134
|
+
return retval
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def build_scorer(cfg: dict) -> Scorer:
|
|
138
|
+
retval = _build("scorer", _scorers, cfg)
|
|
139
|
+
return retval
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def build_destination(cfg: dict) -> Destination:
|
|
143
|
+
retval = _build("destination", _destinations, cfg)
|
|
144
|
+
return retval
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def build_action(cfg: dict) -> Action:
|
|
148
|
+
retval = _build("action", _actions, cfg)
|
|
149
|
+
return retval
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def load_plugins() -> dict[str, PluginImportFailure]:
|
|
153
|
+
"""Import the plugin modules so they self-register.
|
|
154
|
+
|
|
155
|
+
Returns the plugins that could not be imported, keyed by the `type:` name
|
|
156
|
+
each would have registered, so the caller can report them. The same map is
|
|
157
|
+
kept here, so a later `build_*` for one of those types can explain itself.
|
|
158
|
+
|
|
159
|
+
The import is done through `framework.plugins.import_all()` rather than a
|
|
160
|
+
plain package import, so one plugin's missing optional dependency costs
|
|
161
|
+
only that plugin (issue #39).
|
|
162
|
+
"""
|
|
163
|
+
_failed_plugins.clear()
|
|
164
|
+
_failed_plugins.update(import_all())
|
|
165
|
+
retval = dict(_failed_plugins)
|
|
166
|
+
return retval
|
framework/runlog.py
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
"""Timestamp every line a run writes to its log (issue #139).
|
|
2
|
+
|
|
3
|
+
A run's log lines carried no date or time of any kind. The summary line, the
|
|
4
|
+
per-signal `scored` and `unscored` lines and whatever diagnostics a source
|
|
5
|
+
printed were all untimed, which meant the log could not answer the first
|
|
6
|
+
question anyone asks of a broken agent: when did this start?
|
|
7
|
+
|
|
8
|
+
Seven consecutive failed runs on the leads workspace produced seven
|
|
9
|
+
byte-identical lines. Nothing in the file distinguished a day-long outage from
|
|
10
|
+
three bad runs, and dating it took `stat` on `state/seen.json`, the log file
|
|
11
|
+
mtimes and the cadence out of the launchd plist -- three sources outside the
|
|
12
|
+
log, none of which survives log rotation or being read on another machine.
|
|
13
|
+
|
|
14
|
+
Worse, the plist is a tempting substitute and it lies. Reading
|
|
15
|
+
`StartCalendarInterval` and labelling lines with the times they *ought* to have
|
|
16
|
+
produces confident, fabricated timestamps; it was done during that
|
|
17
|
+
investigation and reported a 16:25 run at 11:21.
|
|
18
|
+
|
|
19
|
+
## Why the prefix is applied to the stream, not at each print
|
|
20
|
+
|
|
21
|
+
There are 37 `file=sys.stderr` call sites across the framework and a source
|
|
22
|
+
plugin is free to add more. Prefixing at the call site means every one of them
|
|
23
|
+
has to opt in, a new plugin silently opts out, and the timestamps drift apart
|
|
24
|
+
as each site formats its own. Wrapping the two streams once, for the duration
|
|
25
|
+
of the run, timestamps every line the run emits, including lines from plugin
|
|
26
|
+
code this module has never heard of.
|
|
27
|
+
|
|
28
|
+
A traceback is the exception to that and has to be handled by the caller. The
|
|
29
|
+
interpreter prints it only after the exception has left the block, by which
|
|
30
|
+
time the real streams are back, so the caller prints it from inside instead --
|
|
31
|
+
see `_cmd_run` in `framework/cli.py`. It is worth the four lines: a failed run's
|
|
32
|
+
traceback is the part that says why, and it would otherwise be the only untimed
|
|
33
|
+
thing in the file.
|
|
34
|
+
|
|
35
|
+
The wrapper buffers until it sees a newline because `print()` writes the text
|
|
36
|
+
and the terminator separately: a naive prefix-per-write would emit a timestamp
|
|
37
|
+
of its own in front of every bare `"\\n"`.
|
|
38
|
+
|
|
39
|
+
## The prefix goes in front, and the rest of the line is untouched
|
|
40
|
+
|
|
41
|
+
`grep ' scored id='` (note the leading space, which is what excludes the
|
|
42
|
+
`unscored id=` lines) and
|
|
43
|
+
`sed 's/.*score=\\([0-9]*\\).*/\\1/'` are how the score distribution is read,
|
|
44
|
+
and neither cares what precedes the match. Nothing anchors on `^agent=`, so a
|
|
45
|
+
leading field is the one change that costs no existing reader. The timestamp is
|
|
46
|
+
local time with its UTC offset -- an unmarked local time is the next version of
|
|
47
|
+
this bug, the first time the question is whether something happened before or
|
|
48
|
+
after a restart.
|
|
49
|
+
"""
|
|
50
|
+
from __future__ import annotations
|
|
51
|
+
|
|
52
|
+
import sys
|
|
53
|
+
from contextlib import contextmanager
|
|
54
|
+
from datetime import datetime
|
|
55
|
+
from typing import Iterator, TextIO
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _stamp() -> str:
|
|
59
|
+
"""The current local time as ISO-8601 with its UTC offset, to the second."""
|
|
60
|
+
retval = datetime.now().astimezone().isoformat(timespec="seconds")
|
|
61
|
+
return retval
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
class _Timestamped:
|
|
65
|
+
"""Wraps a text stream, prefixing each complete line with the local time.
|
|
66
|
+
|
|
67
|
+
Everything other than `write` is delegated to the wrapped stream, so a
|
|
68
|
+
caller that asks for `fileno()`, `encoding` or `isatty()` -- including the
|
|
69
|
+
interpreter, printing a traceback -- sees the real stream's answer.
|
|
70
|
+
"""
|
|
71
|
+
|
|
72
|
+
def __init__(self, stream: TextIO) -> None:
|
|
73
|
+
self._stream = stream
|
|
74
|
+
self._pending = ""
|
|
75
|
+
|
|
76
|
+
def write(self, text: str) -> int:
|
|
77
|
+
buffered = self._pending + text
|
|
78
|
+
lines = buffered.split("\n")
|
|
79
|
+
# The last element is whatever follows the final newline: empty when
|
|
80
|
+
# the text ended on one, a partial line otherwise. Hold it back so its
|
|
81
|
+
# timestamp is the moment the line is finished rather than started.
|
|
82
|
+
self._pending = lines.pop()
|
|
83
|
+
for line in lines:
|
|
84
|
+
# A blank line stays blank. Prefixing it would date nothing and
|
|
85
|
+
# leave trailing whitespace on the only lines that exist to
|
|
86
|
+
# separate things.
|
|
87
|
+
prefix = f"{_stamp()} " if line else ""
|
|
88
|
+
self._stream.write(f"{prefix}{line}\n")
|
|
89
|
+
return len(text)
|
|
90
|
+
|
|
91
|
+
def flush(self) -> None:
|
|
92
|
+
self._stream.flush()
|
|
93
|
+
|
|
94
|
+
def close_pending(self) -> None:
|
|
95
|
+
"""Emit a held-back partial line, so nothing is swallowed on exit."""
|
|
96
|
+
if self._pending:
|
|
97
|
+
self._stream.write(f"{_stamp()} {self._pending}\n")
|
|
98
|
+
self._pending = ""
|
|
99
|
+
self._stream.flush()
|
|
100
|
+
|
|
101
|
+
def __getattr__(self, name: str) -> object:
|
|
102
|
+
return getattr(self._stream, name)
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
@contextmanager
|
|
106
|
+
def timestamped() -> Iterator[None]:
|
|
107
|
+
"""Timestamp every line written to stdout and stderr inside this block.
|
|
108
|
+
|
|
109
|
+
Both streams are wrapped because the two halves of a run's log are split
|
|
110
|
+
across them: launchd sends stdout to `run.log` and stderr to
|
|
111
|
+
`run.error.log`, and the summary line goes to the first while the
|
|
112
|
+
per-signal lines go to the second.
|
|
113
|
+
|
|
114
|
+
The streams are restored on the way out whatever happened, and any partial
|
|
115
|
+
line is flushed first -- a run that dies mid-line should still show how far
|
|
116
|
+
it got.
|
|
117
|
+
"""
|
|
118
|
+
out, err = _Timestamped(sys.stdout), _Timestamped(sys.stderr)
|
|
119
|
+
sys.stdout, sys.stderr = out, err
|
|
120
|
+
try:
|
|
121
|
+
yield
|
|
122
|
+
finally:
|
|
123
|
+
out.close_pending()
|
|
124
|
+
err.close_pending()
|
|
125
|
+
sys.stdout, sys.stderr = out._stream, err._stream
|
framework/runner.py
ADDED
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
"""Entrypoint contract: `agent run` — one invocation, one pass, exits 0/nonzero.
|
|
2
|
+
|
|
3
|
+
The loop is per-signal, which suits lead-finding where each signal is
|
|
4
|
+
independently interesting. Agents whose output is a single summary — a daily
|
|
5
|
+
digest, a calendar rundown, a weekly blog draft — need a point where something
|
|
6
|
+
sees the whole run. That is `Destination.flush()`, called once after the loop
|
|
7
|
+
(issue #26).
|
|
8
|
+
|
|
9
|
+
`flush()` is optional. A streaming destination does not define it and is
|
|
10
|
+
unaffected.
|
|
11
|
+
|
|
12
|
+
The mirror image on the source side is `Source.commit()`, called once after
|
|
13
|
+
`seen.save()` succeeds (issue #46). It exists for a source whose fetch window is
|
|
14
|
+
its own state — the github-releases source keeps `last_run` so "what shipped
|
|
15
|
+
since we last looked" is an explicit question rather than an over-fetch that
|
|
16
|
+
SeenStore trims. Such a source must not advance that window inside `fetch()`:
|
|
17
|
+
a run that fetched, then failed to deliver, would have moved the window past
|
|
18
|
+
releases nobody saw. `commit()` runs only after delivery and the dedupe marks
|
|
19
|
+
are durable, so a failure anywhere earlier leaves the window where it was and
|
|
20
|
+
the next run re-fetches it. Optional and discovered with getattr, exactly like
|
|
21
|
+
`flush()`; existing sources are unaffected.
|
|
22
|
+
|
|
23
|
+
`commit()` runs only on an `ok` run, never on a `partial` one. An unscored
|
|
24
|
+
signal is deliberately left unmarked so the next run retries it, and for a
|
|
25
|
+
windowed source that retry exists only if the next run's window still contains
|
|
26
|
+
the signal. Advancing the window past it would turn "retried next run" into
|
|
27
|
+
"never fetched again": the silent skip `commit()` exists to prevent. So a
|
|
28
|
+
partial run leaves the window where it was, the next run re-fetches it, and
|
|
29
|
+
SeenStore drops everything that did get through.
|
|
30
|
+
|
|
31
|
+
Dedupe is marked only after delivery has actually happened, which for a batching
|
|
32
|
+
destination means after `flush()`, not after `send()`. Marking earlier would
|
|
33
|
+
lose signals silently: `send()` merely buffers, so a `flush()` that throws would
|
|
34
|
+
leave those signals marked-seen and never delivered, with nothing to retry.
|
|
35
|
+
Deferring means a failed run re-delivers rather than drops — at-least-once,
|
|
36
|
+
which is the right bias for a notifier.
|
|
37
|
+
|
|
38
|
+
A cron/launchd `exit 0` with an empty log cannot tell "healthy, nothing new"
|
|
39
|
+
from "source silently returned []" from "everything already deduped" — three
|
|
40
|
+
situations that call for very different responses. So `run()` prints exactly
|
|
41
|
+
one summary line on every invocation, including a zero-signal one and including
|
|
42
|
+
a *failing* one (issue #31).
|
|
43
|
+
|
|
44
|
+
"Unconditional" is the whole point, so the summary is emitted from a `finally`.
|
|
45
|
+
Every step here can raise — `fetch()`, `score()`, `send()`, `flush()` and
|
|
46
|
+
`seen.save()` — and a run that dies inside `fetch()` is exactly the case that
|
|
47
|
+
used to produce a nonzero exit with no diagnostic at all. The line reports how
|
|
48
|
+
far the run got before it died, and `status=` says which it was. The exception
|
|
49
|
+
still propagates; the summary does not suppress it.
|
|
50
|
+
|
|
51
|
+
On the counters, and on what is deliberately *not* here. `sent` counts signals
|
|
52
|
+
the destination accepted from `send()`. It is not a delivery confirmation: for a
|
|
53
|
+
batching destination `send()` only buffers and the real network call happens in
|
|
54
|
+
`flush()`, so naming it `delivered` would overclaim in the one feature meant to
|
|
55
|
+
stop the log lying. The runner also does not try to learn how many signals a
|
|
56
|
+
destination declined by its own gating (say a per-route min_score). That would
|
|
57
|
+
mean new optional protocol surface on `Destination`, which is wider than issue
|
|
58
|
+
#31 asked for, and absent that hook the number is simply unknowable — so
|
|
59
|
+
reporting `declined=0` by default would be a guess presented as a fact.
|
|
60
|
+
|
|
61
|
+
Note what this does *not* buy: `sent` and `new` are equal by construction on any
|
|
62
|
+
successful run, because a signal is counted and appended in the same iteration.
|
|
63
|
+
They diverge only on a failure path. So the line cannot tell you a destination
|
|
64
|
+
gated something internally, and nothing here pretends otherwise — a destination
|
|
65
|
+
that drops signals by its own rules has to say so in its own logs. Naming the
|
|
66
|
+
counter `sent` rather than `delivered` is the whole of the honesty available at
|
|
67
|
+
this layer.
|
|
68
|
+
|
|
69
|
+
What the summary line cannot say, the per-signal lines can. The loop prints one
|
|
70
|
+
stderr line per scored signal carrying its id and its score, which is the fact
|
|
71
|
+
every destination gate turns on. That is not a delivery claim and adds nothing
|
|
72
|
+
to `Destination`: it simply means a log can answer "how many signals landed just
|
|
73
|
+
under the threshold", a question the counters above are structurally unable to
|
|
74
|
+
answer and the one question worth asking before moving a `min_score`.
|
|
75
|
+
|
|
76
|
+
A source may set `dedupe = False` (issue #59), read here with getattr like
|
|
77
|
+
`commit()`. The SeenStore makes a *stream* safe -- each item is interesting
|
|
78
|
+
once -- but a window digest is the other shape, re-listing "what is on this
|
|
79
|
+
week" every run by design, and per-item dedupe turns its second run into an
|
|
80
|
+
empty one. Such a source's signals are neither skipped as seen nor marked, so
|
|
81
|
+
`new` stays 0 on every run and the store does not grow with items that will be
|
|
82
|
+
re-fetched regardless. A digest on such a source should say "nothing new since
|
|
83
|
+
the last run" only when it means it: an empty window and an exhausted store are
|
|
84
|
+
different facts.
|
|
85
|
+
|
|
86
|
+
`unscored` counts signals whose scorer raised `ScoreError`: a failure that
|
|
87
|
+
belongs to that one signal (an LLM reply that could not be read even after a
|
|
88
|
+
retry), not to the scorer as a whole. Aborting the run for it would let one
|
|
89
|
+
signal block delivery of every other signal for as long as it stayed in the
|
|
90
|
+
feed, since each run would replay it first and die at the same place. So the
|
|
91
|
+
runner skips it — not sent, not marked seen, so the next run retries it — and
|
|
92
|
+
prints one stderr line naming its id and the error. Everything else is
|
|
93
|
+
delivered, flushed and deduped as usual, then the run reports `status=partial`
|
|
94
|
+
and exits 1, so a scheduler still sees a nonzero exit and the operator still
|
|
95
|
+
has something to look at. `new` does not include unscored signals: on a run
|
|
96
|
+
that completes, `fetched` is already-seen plus `new` plus `unscored`. Any other
|
|
97
|
+
exception from `score()` still aborts the run with `status=failed`; a whole
|
|
98
|
+
model chain being down would fail every signal alike, and there is nothing to
|
|
99
|
+
salvage by carrying on.
|
|
100
|
+
|
|
101
|
+
The statuses, then: `ok` (exit 0), `partial` (exit 1, some signals unscored,
|
|
102
|
+
everything else delivered, the source's window not advanced), `commit_failed`
|
|
103
|
+
(the exception from `commit()` propagates; everything was delivered and marked
|
|
104
|
+
seen, only the source's window did not advance, so the next run re-fetches it
|
|
105
|
+
and SeenStore drops it all), and `failed` (the exception propagates, nothing
|
|
106
|
+
from this run is marked seen).
|
|
107
|
+
"""
|
|
108
|
+
from __future__ import annotations
|
|
109
|
+
|
|
110
|
+
import sys
|
|
111
|
+
|
|
112
|
+
from framework.interfaces import Destination, ScoreError, Scorer, Source
|
|
113
|
+
from framework.state import SeenStore
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def _model_suffix(scorer: Scorer) -> str:
|
|
117
|
+
"""` model=<rung>` for a scorer that names the model it just used, else "".
|
|
118
|
+
|
|
119
|
+
A scorer backed by an LLM waterfall does not use one model, it uses
|
|
120
|
+
whichever rung answered: the primary falls through on an exhausted budget,
|
|
121
|
+
a timeout or an empty completion, and the next signal in the same run may
|
|
122
|
+
be scored by a different model on a different scale. Without this, a log
|
|
123
|
+
full of scores cannot distinguish a drifting corpus from a drifting
|
|
124
|
+
scorer, and a gate tuned against one model is silently applied to another.
|
|
125
|
+
|
|
126
|
+
Optional and discovered with `getattr`, exactly like `flush()` and
|
|
127
|
+
`commit()`: the regex scorer defines nothing and its log lines are
|
|
128
|
+
unchanged.
|
|
129
|
+
|
|
130
|
+
The value is the waterfall's own label, `name (model)`, so it contains
|
|
131
|
+
spaces and is always the last field on the `scored` line.
|
|
132
|
+
"""
|
|
133
|
+
model = getattr(scorer, "model_used", None)
|
|
134
|
+
retval = f" model={model}" if model else ""
|
|
135
|
+
return retval
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def run(
|
|
139
|
+
source: Source,
|
|
140
|
+
scorer: Scorer,
|
|
141
|
+
destination: Destination,
|
|
142
|
+
seen: SeenStore,
|
|
143
|
+
agent_name: str = "unknown",
|
|
144
|
+
) -> int:
|
|
145
|
+
fetched = 0
|
|
146
|
+
new = 0
|
|
147
|
+
sent = 0
|
|
148
|
+
unscored = 0
|
|
149
|
+
status = "failed"
|
|
150
|
+
|
|
151
|
+
try:
|
|
152
|
+
signals = source.fetch()
|
|
153
|
+
fetched = len(signals)
|
|
154
|
+
|
|
155
|
+
# A source may declare `dedupe = False` (issue #59). Discovered with
|
|
156
|
+
# getattr like `commit()`, so every existing source is unaffected.
|
|
157
|
+
#
|
|
158
|
+
# Why a source gets to say this. The SeenStore makes a *stream* safe:
|
|
159
|
+
# each item is interesting once. A window digest is the other shape --
|
|
160
|
+
# "what is on this week" re-lists the same events every run on purpose
|
|
161
|
+
# -- and per-item dedupe turns its second run into an empty one. That
|
|
162
|
+
# was measured, not theorised: a hand-run consumed a day's items, and
|
|
163
|
+
# the scheduled run then posted its empty line while the window itself
|
|
164
|
+
# was not empty. Repetition is prevented by the window moving, not by
|
|
165
|
+
# marking items seen.
|
|
166
|
+
#
|
|
167
|
+
# The signals are still never marked, so nothing accumulates in the
|
|
168
|
+
# store for a source that will re-fetch them anyway.
|
|
169
|
+
dedupe = bool(getattr(source, "dedupe", True))
|
|
170
|
+
|
|
171
|
+
pending: list[str] = []
|
|
172
|
+
for signal in signals:
|
|
173
|
+
if dedupe and seen.has(signal.id):
|
|
174
|
+
continue
|
|
175
|
+
try:
|
|
176
|
+
scored = scorer.score(signal)
|
|
177
|
+
except ScoreError as exc:
|
|
178
|
+
# This signal only: not sent, not marked, so the next run
|
|
179
|
+
# retries it. Anything else a scorer raises aborts the run.
|
|
180
|
+
unscored += 1
|
|
181
|
+
detail = str(exc).replace("\n", " ")
|
|
182
|
+
# `model=` goes before `error=`, not after: the error detail
|
|
183
|
+
# is unbounded free text, so anything following it cannot be
|
|
184
|
+
# split back out.
|
|
185
|
+
print(
|
|
186
|
+
f"agent={agent_name} unscored id={signal.id}"
|
|
187
|
+
f"{_model_suffix(scorer)} error={detail}",
|
|
188
|
+
file=sys.stderr,
|
|
189
|
+
)
|
|
190
|
+
continue
|
|
191
|
+
# One stderr line per scored signal. The summary counters below
|
|
192
|
+
# cannot tell "scored 58" from "scored 12", so a destination's own
|
|
193
|
+
# min_score gate is invisible in the log and there is no evidence
|
|
194
|
+
# for or against moving it. This is the cheapest thing that makes
|
|
195
|
+
# the distribution measurable: no new protocol surface, no claim
|
|
196
|
+
# about what the destination did with the signal. Deliberately
|
|
197
|
+
# symmetric with the unscored line above -- same prefix, the same
|
|
198
|
+
# id -- so one grep over a log yields both outcomes per signal.
|
|
199
|
+
print(
|
|
200
|
+
f"agent={agent_name} scored id={signal.id} "
|
|
201
|
+
f"score={scored.score} source={signal.source}"
|
|
202
|
+
f"{_model_suffix(scorer)}",
|
|
203
|
+
file=sys.stderr,
|
|
204
|
+
)
|
|
205
|
+
destination.send(scored)
|
|
206
|
+
sent += 1
|
|
207
|
+
if dedupe:
|
|
208
|
+
pending.append(signal.id)
|
|
209
|
+
new = len(pending)
|
|
210
|
+
|
|
211
|
+
flush = getattr(destination, "flush", None)
|
|
212
|
+
if callable(flush):
|
|
213
|
+
flush()
|
|
214
|
+
|
|
215
|
+
# Only now is delivery known to have happened, for streaming and
|
|
216
|
+
# batching destinations alike. Note seen.save() was always end-of-run,
|
|
217
|
+
# so nothing is lost by deferring the marks to here.
|
|
218
|
+
for signal_id in pending:
|
|
219
|
+
seen.mark(signal_id)
|
|
220
|
+
seen.save()
|
|
221
|
+
|
|
222
|
+
if unscored:
|
|
223
|
+
status = "partial"
|
|
224
|
+
else:
|
|
225
|
+
# A source that tracks its own fetch window advances it only here,
|
|
226
|
+
# once delivery and the dedupe marks are both durable, and never on
|
|
227
|
+
# a partial run: an unscored signal must still be inside the next
|
|
228
|
+
# run's window to be retried (issue #46).
|
|
229
|
+
commit = getattr(source, "commit", None)
|
|
230
|
+
if callable(commit):
|
|
231
|
+
# Delivered and marked already: if commit() raises, the line
|
|
232
|
+
# must not say `failed`.
|
|
233
|
+
status = "commit_failed"
|
|
234
|
+
commit()
|
|
235
|
+
status = "ok"
|
|
236
|
+
finally:
|
|
237
|
+
print(
|
|
238
|
+
f"agent={agent_name} status={status} fetched={fetched} "
|
|
239
|
+
f"new={new} sent={sent} unscored={unscored} seen={len(seen)}"
|
|
240
|
+
)
|
|
241
|
+
|
|
242
|
+
retval = 1 if unscored else 0
|
|
243
|
+
return retval
|