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,761 @@
|
|
|
1
|
+
"""Websearch source: a search engine as a source (issue #57).
|
|
2
|
+
|
|
3
|
+
Runs a list of queries against the Brave Search API and emits one Signal per
|
|
4
|
+
result. This is the generic primitive issue #30 anticipated while rescoping the
|
|
5
|
+
LinkedIn work: the missing piece was never a LinkedIn connector, it was
|
|
6
|
+
search-engine-as-source. A `site:linkedin.com/posts` query and a
|
|
7
|
+
`"<city> chamber mixer"` query are the same plugin.
|
|
8
|
+
|
|
9
|
+
"source": {
|
|
10
|
+
"type": "websearch",
|
|
11
|
+
"api_key_env": "BRAVE_API_KEY",
|
|
12
|
+
"queries": ["<city> small business networking", "site:eventbrite.com <city>"],
|
|
13
|
+
"count": 10,
|
|
14
|
+
"freshness": "pw",
|
|
15
|
+
"fetch_page": true
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
## One signal per self-identifying passage (issue #138)
|
|
19
|
+
|
|
20
|
+
By default this source emits one Signal per *result page*. With
|
|
21
|
+
`self_identification` set it emits one Signal per **passage inside the page that
|
|
22
|
+
contains one of those phrases**, which is what the comment-level funnel needs:
|
|
23
|
+
|
|
24
|
+
"source": {
|
|
25
|
+
"type": "websearch",
|
|
26
|
+
"backend": "firecrawl",
|
|
27
|
+
"queries": ["\"I own a\" invoices paperwork"],
|
|
28
|
+
"fetch_page": true,
|
|
29
|
+
"self_identification": ["I own a", "I run a", "we are a small"],
|
|
30
|
+
"passage_chars": 600
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
The funnel exists because the post-level one was measured dead: two search
|
|
34
|
+
backends each put zero posts at the scoring gate, and a 1,417-post corpus
|
|
35
|
+
yielded 2 with real buyer pain, 1,184 of them written by vendors. What that work
|
|
36
|
+
found alive was a different shape — a business owner identifying themselves in a
|
|
37
|
+
*comment* under someone else's post, where the post itself is vendor copy. So
|
|
38
|
+
the lead is the passage, the page is only its context.
|
|
39
|
+
|
|
40
|
+
Three consequences, each deliberate:
|
|
41
|
+
|
|
42
|
+
- **The scorer sees the passage alone.** `Signal.text` is the passage; the
|
|
43
|
+
page's title and URL ride in `meta` as `parent_title` / `parent_url` for the
|
|
44
|
+
destination to render. Scoring the whole page would score the vendor's post
|
|
45
|
+
instead of the owner's comment, which is the defect this mode exists to fix.
|
|
46
|
+
- **A window, not a DOM query.** The passage is `passage_chars` of visible
|
|
47
|
+
text centred on the matched phrase. This source refuses to depend on a
|
|
48
|
+
page's markup holding still — the retired LinkedIn scraper broke silently
|
|
49
|
+
against a changed DOM while still reporting successful runs — and a comment
|
|
50
|
+
container has no stable shape across sites. The cost is that a window can
|
|
51
|
+
straddle two comments; a person reads the lead either way.
|
|
52
|
+
- **The id is content-addressed**, `<page>#p=<hash>`, because flat text has no
|
|
53
|
+
comment permalink to key on. An edited comment is therefore a new signal.
|
|
54
|
+
That is the right way round: re-reading an edited comment is cheap, and
|
|
55
|
+
missing one is a lost lead.
|
|
56
|
+
|
|
57
|
+
`self_identification` requires `fetch_page`. A phrase found in a search snippet
|
|
58
|
+
is not a comment: snippets run about 150 characters, which was measured too
|
|
59
|
+
short to carry a job, a workaround or a budget.
|
|
60
|
+
|
|
61
|
+
Why a search API rather than a scraped SERP: it is documented and takes a key,
|
|
62
|
+
so nothing here depends on a page's markup holding still. The retired LinkedIn
|
|
63
|
+
scraper broke silently against a changed DOM while still reporting successful
|
|
64
|
+
runs, and that failure mode is what this plugin exists not to repeat.
|
|
65
|
+
|
|
66
|
+
## Two backends, and when the second one matters
|
|
67
|
+
|
|
68
|
+
`backend` is `brave` (the default, unchanged) or `firecrawl`:
|
|
69
|
+
|
|
70
|
+
"source": {
|
|
71
|
+
"type": "websearch",
|
|
72
|
+
"backend": "firecrawl",
|
|
73
|
+
"firecrawl_api_key_env": "FIRECRAWL_API_KEY",
|
|
74
|
+
"api_key_env": "BRAVE_API_KEY",
|
|
75
|
+
"queries": ["\"I own a\" plumbing business"],
|
|
76
|
+
"count": 10
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
`freshness` and `country` are Brave's parameters and have no verified Firecrawl
|
|
80
|
+
equivalent, so combining either with `backend: "firecrawl"` is refused at build
|
|
81
|
+
time rather than accepted and dropped. Asking for the past week and silently
|
|
82
|
+
getting everything is the kind of quiet wrongness this plugin exists to avoid,
|
|
83
|
+
and guessing at a translation would be worse: the config would then look
|
|
84
|
+
honoured while meaning something nobody checked. Whoever needs it can add the
|
|
85
|
+
mapping against a real reply.
|
|
86
|
+
|
|
87
|
+
The difference that justifies the second one is **quoted phrases**. A query that
|
|
88
|
+
finds a business owner identifying themselves is recognisable by its
|
|
89
|
+
construction rather than its topic -- `"I own a"`, `"I run a small"` -- so the
|
|
90
|
+
engine has to honour the quotes. Firecrawl does. Brave mostly does (measured
|
|
91
|
+
2026-11-12: 72-100% of on-site snippets contained the quoted phrase) and honours
|
|
92
|
+
`site:`, but returns nothing at all for `site:reddit.com/r/<sub>`.
|
|
93
|
+
|
|
94
|
+
With `backend: "firecrawl"` each query goes to Firecrawl, and once Firecrawl
|
|
95
|
+
answers 402 (credits exhausted) the rest of the run uses Brave -- including the
|
|
96
|
+
query that hit the 402, which is retried there immediately. Exhaustion is sticky
|
|
97
|
+
for the run and announced on stderr once, not once per query. If there is no
|
|
98
|
+
Brave key to fall back to, the 402 is recorded as that query's error and the
|
|
99
|
+
run carries on under the whole-run guard below.
|
|
100
|
+
|
|
101
|
+
**Only a 402 falls back.** A Firecrawl 429 or 500 is recorded as a query error
|
|
102
|
+
like any other and is *not* answered by Brave. Credits running out is a
|
|
103
|
+
permanent condition for the rest of the run, and continuing is strictly better
|
|
104
|
+
than stopping; a transient error is not, and quietly swapping the engine
|
|
105
|
+
mid-run would change what a quoted phrase means with nothing in the log saying
|
|
106
|
+
so. `meta["backend"]` on every signal names the engine that returned it, so a
|
|
107
|
+
run that straddles the switch can still be read.
|
|
108
|
+
|
|
109
|
+
## Snippets, `fetch_page`, and the honest limit
|
|
110
|
+
|
|
111
|
+
A search result is a title, a URL and a short description. For the meetups
|
|
112
|
+
agent that is usually not enough — a listing's date, venue and cost live on the
|
|
113
|
+
page, not in the snippet — so `fetch_page: true` does a plain GET of each result
|
|
114
|
+
and appends the page's visible text.
|
|
115
|
+
|
|
116
|
+
**It is a plain GET. No JavaScript runs.** An event page rendered entirely by a
|
|
117
|
+
client-side framework yields nothing useful, and that is recorded rather than
|
|
118
|
+
hidden: `meta["page_fetched"]` is False and `meta["page_error"]` says why, so a
|
|
119
|
+
digest built on thin text can be explained instead of merely being disappointing.
|
|
120
|
+
The signal is still emitted with its snippet, because a title and URL the
|
|
121
|
+
operator can click is worth more than a dropped row.
|
|
122
|
+
|
|
123
|
+
Text extraction is stdlib `html.parser`, not a DOM library: this needs "the
|
|
124
|
+
words on the page, roughly, minus script and style", and a dependency whose
|
|
125
|
+
absence would take the plugin out of `load_plugins()` (issue #39) is a poor
|
|
126
|
+
trade for tidier whitespace.
|
|
127
|
+
|
|
128
|
+
## The dedupe id is the normalised URL
|
|
129
|
+
|
|
130
|
+
Two queries legitimately return the same page — that is what overlapping queries
|
|
131
|
+
are for — and the same page arrives with a tracking parameter attached, or with
|
|
132
|
+
and without a trailing slash, often enough to matter. So the id is the URL with
|
|
133
|
+
its fragment dropped, its `utm_*`/`fbclid`-class parameters stripped, its host
|
|
134
|
+
lowercased and a bare trailing slash removed. Without that, one event is two
|
|
135
|
+
signals and the digest lists it twice.
|
|
136
|
+
|
|
137
|
+
Normalisation is deliberately conservative: query parameters that are not known
|
|
138
|
+
tracking junk are kept, because on plenty of event sites the id *is* a query
|
|
139
|
+
parameter (`?event_id=123`), and stripping it would collapse every event on the
|
|
140
|
+
site into one signal — a silent loss, which is worse than a duplicate.
|
|
141
|
+
|
|
142
|
+
## Failures
|
|
143
|
+
|
|
144
|
+
Per-query, mirroring the reddit source's `feed_errors`: a query that fails is
|
|
145
|
+
recorded in `query_errors` and the run continues on the others, but **if every
|
|
146
|
+
query fails, `fetch()` raises** rather than reporting a cheerful zero. A rate
|
|
147
|
+
limit that takes out the whole run must not read as "no events this week".
|
|
148
|
+
|
|
149
|
+
A failed *page* fetch under `fetch_page` is not a failed query — the result is
|
|
150
|
+
still a real result — so it degrades to the snippet and is recorded in meta.
|
|
151
|
+
|
|
152
|
+
Brave's free tier is one request per second, so queries are spaced by
|
|
153
|
+
`delay_seconds` (default 1.1). A 429 is recorded for that query rather than
|
|
154
|
+
retried: at a weekly cadence, and with the whole-run guard above, failing loudly
|
|
155
|
+
beats sitting in a retry loop inside a cron job.
|
|
156
|
+
|
|
157
|
+
Contract: see docs/PLUGIN-CONTRACT.md.
|
|
158
|
+
"""
|
|
159
|
+
from __future__ import annotations
|
|
160
|
+
|
|
161
|
+
import hashlib
|
|
162
|
+
import os
|
|
163
|
+
import re
|
|
164
|
+
import sys
|
|
165
|
+
import time
|
|
166
|
+
from html.parser import HTMLParser
|
|
167
|
+
from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit
|
|
168
|
+
|
|
169
|
+
import requests
|
|
170
|
+
|
|
171
|
+
from framework.interfaces import Signal, Source
|
|
172
|
+
from framework.registry import register_source
|
|
173
|
+
|
|
174
|
+
_BRAVE_ENDPOINT = "https://api.search.brave.com/res/v1/web/search"
|
|
175
|
+
_FIRECRAWL_ENDPOINT = "https://api.firecrawl.dev/v2/search"
|
|
176
|
+
_BACKENDS = ("brave", "firecrawl")
|
|
177
|
+
_DEFAULT_LABEL = "websearch"
|
|
178
|
+
_DEFAULT_PAGE_CHARS = 4000
|
|
179
|
+
|
|
180
|
+
# Query parameters that identify a campaign, not a document. Stripped so the
|
|
181
|
+
# same page reached from two places dedupes as one signal. Anything not on this
|
|
182
|
+
# list is kept: on many event sites the id is a query parameter, and dropping
|
|
183
|
+
# unknown ones would collapse a whole site into a single signal.
|
|
184
|
+
_TRACKING_PARAMS = frozenset(
|
|
185
|
+
{
|
|
186
|
+
"utm_source",
|
|
187
|
+
"utm_medium",
|
|
188
|
+
"utm_campaign",
|
|
189
|
+
"utm_term",
|
|
190
|
+
"utm_content",
|
|
191
|
+
"utm_id",
|
|
192
|
+
"fbclid",
|
|
193
|
+
"gclid",
|
|
194
|
+
"mc_cid",
|
|
195
|
+
"mc_eid",
|
|
196
|
+
"ref",
|
|
197
|
+
"ref_src",
|
|
198
|
+
"_ga",
|
|
199
|
+
}
|
|
200
|
+
)
|
|
201
|
+
|
|
202
|
+
# Wide enough to carry a comment's own sentences, short enough that a window
|
|
203
|
+
# rarely swallows the next comment whole. Measured against nothing: it is a
|
|
204
|
+
# starting value to tune once a real sweep has been read.
|
|
205
|
+
_DEFAULT_PASSAGE_CHARS = 600
|
|
206
|
+
|
|
207
|
+
# How close two matches must be to count as one person speaking. About a
|
|
208
|
+
# sentence or two: "I own a bakery and I run a second shop downtown" is one
|
|
209
|
+
# lead, while a reply three hundred characters later is somebody else.
|
|
210
|
+
_DEFAULT_SAME_COMMENT_CHARS = 200
|
|
211
|
+
|
|
212
|
+
# A sentence ending between two matches means two speakers, near enough. Kept
|
|
213
|
+
# deliberately crude: anything cleverer would be parsing prose, and the cost of
|
|
214
|
+
# a wrong split is one extra lead for a person to read rather than a lost one.
|
|
215
|
+
_SENTENCE_END = re.compile(r"[.!?]")
|
|
216
|
+
|
|
217
|
+
# Elements whose contents are code or styling, never prose.
|
|
218
|
+
_SKIP_TAGS = frozenset({"script", "style", "noscript", "template", "svg"})
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
class _TextExtractor(HTMLParser):
|
|
222
|
+
"""Visible text of an HTML document, roughly. See the module docstring on
|
|
223
|
+
why this is stdlib rather than a DOM library."""
|
|
224
|
+
|
|
225
|
+
def __init__(self):
|
|
226
|
+
super().__init__(convert_charrefs=True)
|
|
227
|
+
self._parts: list[str] = []
|
|
228
|
+
self._skip_depth = 0
|
|
229
|
+
|
|
230
|
+
def handle_starttag(self, tag, attrs):
|
|
231
|
+
if tag in _SKIP_TAGS:
|
|
232
|
+
self._skip_depth += 1
|
|
233
|
+
|
|
234
|
+
def handle_endtag(self, tag):
|
|
235
|
+
if tag in _SKIP_TAGS and self._skip_depth:
|
|
236
|
+
self._skip_depth -= 1
|
|
237
|
+
|
|
238
|
+
def handle_data(self, data):
|
|
239
|
+
if self._skip_depth:
|
|
240
|
+
return
|
|
241
|
+
text = data.strip()
|
|
242
|
+
if text:
|
|
243
|
+
self._parts.append(text)
|
|
244
|
+
|
|
245
|
+
def text(self) -> str:
|
|
246
|
+
retval = " ".join(self._parts)
|
|
247
|
+
return retval
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
def _visible_text(html: str) -> str:
|
|
251
|
+
parser = _TextExtractor()
|
|
252
|
+
# A malformed page must not fail the run: whatever was parsed before the
|
|
253
|
+
# error is still worth scoring.
|
|
254
|
+
try:
|
|
255
|
+
parser.feed(html)
|
|
256
|
+
except Exception:
|
|
257
|
+
pass
|
|
258
|
+
retval = " ".join(parser.text().split())
|
|
259
|
+
return retval
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
def _passages(
|
|
263
|
+
text: str, phrases: list[str], width: int, limit: int, same_comment: int
|
|
264
|
+
) -> list[tuple[str, str]]:
|
|
265
|
+
"""(phrase, passage) for each self-identifying phrase found in `text`.
|
|
266
|
+
|
|
267
|
+
A passage is `width` characters of context around the match, trimmed to
|
|
268
|
+
whitespace at both ends so a lead does not begin or end mid-word.
|
|
269
|
+
|
|
270
|
+
Two matches collapse into one passage only when nothing ends a sentence
|
|
271
|
+
between them AND they are within `same_comment` characters -- that is, when
|
|
272
|
+
they read as one person's sentence, as in "I own a bakery and I run a second
|
|
273
|
+
shop". The sentence test is the load-bearing half: distance alone is too
|
|
274
|
+
blunt, because two short comments by different people can sit ninety
|
|
275
|
+
characters apart while one person's clause runs twenty. They do NOT collapse
|
|
276
|
+
merely because the second falls inside the first's window.
|
|
277
|
+
That was the original rule and it suppressed real leads: the window runs
|
|
278
|
+
hundreds of characters past its match, so a vendor's post or an earlier
|
|
279
|
+
commenter using a configured phrase would swallow the next commenter
|
|
280
|
+
entirely, and that next commenter is exactly who this mode exists to find.
|
|
281
|
+
Passages may therefore overlap. Two owners talking in the same thread are
|
|
282
|
+
two leads even when their words sit close together, and the phrase that
|
|
283
|
+
anchored each one travels with it so a reader can tell them apart.
|
|
284
|
+
|
|
285
|
+
The window is weighted *after* the match rather than centred on it, by about
|
|
286
|
+
seven to one. "I own a ..." introduces the problem rather than concluding
|
|
287
|
+
it, so the sentences that follow are the lead, while the sentences before it
|
|
288
|
+
usually belong to whatever the commenter was replying to. A centred window
|
|
289
|
+
measurably reached back into the vendor copy above the comment, which is
|
|
290
|
+
exactly how a vendor's own words would flow into the text the scorer judges.
|
|
291
|
+
"""
|
|
292
|
+
lowered = text.lower()
|
|
293
|
+
spans: list[tuple[int, int, str]] = []
|
|
294
|
+
for phrase in phrases:
|
|
295
|
+
needle = phrase.lower().strip()
|
|
296
|
+
if not needle:
|
|
297
|
+
continue
|
|
298
|
+
start = lowered.find(needle)
|
|
299
|
+
while start != -1:
|
|
300
|
+
spans.append((start, start + len(needle), phrase))
|
|
301
|
+
start = lowered.find(needle, start + len(needle))
|
|
302
|
+
spans.sort()
|
|
303
|
+
|
|
304
|
+
retval: list[tuple[str, str]] = []
|
|
305
|
+
last_start: int | None = None
|
|
306
|
+
for start, end, phrase in spans:
|
|
307
|
+
if (
|
|
308
|
+
last_start is not None
|
|
309
|
+
and start - last_start < same_comment
|
|
310
|
+
and not _SENTENCE_END.search(text[last_start:start])
|
|
311
|
+
):
|
|
312
|
+
continue
|
|
313
|
+
room = max(0, width - (end - start))
|
|
314
|
+
lead_in = room // 8
|
|
315
|
+
left = max(0, start - lead_in)
|
|
316
|
+
right = min(len(text), end + (room - lead_in))
|
|
317
|
+
# Trim to whitespace so the passage starts and ends on whole words.
|
|
318
|
+
if left:
|
|
319
|
+
space = text.find(" ", left)
|
|
320
|
+
left = space + 1 if 0 <= space < start else left
|
|
321
|
+
if right < len(text):
|
|
322
|
+
space = text.rfind(" ", end, right)
|
|
323
|
+
right = space if space > end else right
|
|
324
|
+
passage = text[left:right].strip()
|
|
325
|
+
if passage:
|
|
326
|
+
retval.append((phrase, passage))
|
|
327
|
+
last_start = start
|
|
328
|
+
if len(retval) >= limit:
|
|
329
|
+
break
|
|
330
|
+
return retval
|
|
331
|
+
|
|
332
|
+
|
|
333
|
+
def normalise_url(url: str) -> str:
|
|
334
|
+
"""The dedupe id for a result. See the module docstring for what is and is
|
|
335
|
+
not stripped, and why the conservative choice is the safe one."""
|
|
336
|
+
parts = urlsplit(url.strip())
|
|
337
|
+
query = [(k, v) for k, v in parse_qsl(parts.query, keep_blank_values=True)
|
|
338
|
+
if k.lower() not in _TRACKING_PARAMS]
|
|
339
|
+
# Trailing slashes are dropped, the bare root included: `https://host/` and
|
|
340
|
+
# `https://host` are one page, and urlsplit gives them different paths ("/"
|
|
341
|
+
# and ""), so leaving the root alone would make them two ids.
|
|
342
|
+
path = parts.path.rstrip("/")
|
|
343
|
+
retval = urlunsplit(
|
|
344
|
+
(parts.scheme.lower(), parts.netloc.lower(), path, urlencode(query), "")
|
|
345
|
+
)
|
|
346
|
+
return retval
|
|
347
|
+
|
|
348
|
+
|
|
349
|
+
class WebSearchSource:
|
|
350
|
+
def __init__(
|
|
351
|
+
self,
|
|
352
|
+
api_key: str,
|
|
353
|
+
queries: list[str],
|
|
354
|
+
backend: str = "brave",
|
|
355
|
+
firecrawl_api_key: str = "",
|
|
356
|
+
count: int = 10,
|
|
357
|
+
freshness: str = "",
|
|
358
|
+
fetch_page: bool = False,
|
|
359
|
+
page_chars: int = _DEFAULT_PAGE_CHARS,
|
|
360
|
+
label: str = _DEFAULT_LABEL,
|
|
361
|
+
country: str = "",
|
|
362
|
+
delay_seconds: float = 1.1,
|
|
363
|
+
timeout: int = 30,
|
|
364
|
+
page_timeout: int = 20,
|
|
365
|
+
user_agent: str = "",
|
|
366
|
+
self_identification: list[str] | None = None,
|
|
367
|
+
passage_chars: int = _DEFAULT_PASSAGE_CHARS,
|
|
368
|
+
max_passages_per_page: int = 5,
|
|
369
|
+
same_comment_chars: int = _DEFAULT_SAME_COMMENT_CHARS,
|
|
370
|
+
):
|
|
371
|
+
self.api_key = api_key
|
|
372
|
+
self.queries = queries
|
|
373
|
+
self.backend = backend
|
|
374
|
+
self.firecrawl_api_key = firecrawl_api_key
|
|
375
|
+
self.count = count
|
|
376
|
+
self.freshness = freshness
|
|
377
|
+
self.fetch_page = fetch_page
|
|
378
|
+
self.page_chars = page_chars
|
|
379
|
+
self.label = label
|
|
380
|
+
self.country = country
|
|
381
|
+
self.delay_seconds = delay_seconds
|
|
382
|
+
self.timeout = timeout
|
|
383
|
+
self.page_timeout = page_timeout
|
|
384
|
+
self.user_agent = user_agent
|
|
385
|
+
self.self_identification = list(self_identification or [])
|
|
386
|
+
self.passage_chars = passage_chars
|
|
387
|
+
self.max_passages_per_page = max_passages_per_page
|
|
388
|
+
self.same_comment_chars = same_comment_chars
|
|
389
|
+
self.query_errors: list[tuple[str, str]] = []
|
|
390
|
+
# Page-level accounting for the comment-level mode, so that "no leads"
|
|
391
|
+
# and "every page refused us" are distinguishable (issues #135, #31).
|
|
392
|
+
self.page_errors: list[tuple[str, str]] = []
|
|
393
|
+
self.pages_fetched = 0
|
|
394
|
+
self.passages_found = 0
|
|
395
|
+
# Sticky for the run: once Firecrawl says the credits are gone, asking
|
|
396
|
+
# it again on every remaining query only wastes the run's time.
|
|
397
|
+
self._firecrawl_exhausted = False
|
|
398
|
+
|
|
399
|
+
def _search(self, query: str) -> list[dict]:
|
|
400
|
+
"""The configured backend's results, falling back to Brave on a 402."""
|
|
401
|
+
if self.backend != "firecrawl" or self._firecrawl_exhausted:
|
|
402
|
+
return self._search_brave(query)
|
|
403
|
+
|
|
404
|
+
results, exhausted = self._search_firecrawl(query)
|
|
405
|
+
if not exhausted:
|
|
406
|
+
return results
|
|
407
|
+
|
|
408
|
+
self._firecrawl_exhausted = True
|
|
409
|
+
print(
|
|
410
|
+
"websearch source: firecrawl credits exhausted; the rest of this run "
|
|
411
|
+
f"{'uses brave' if self.api_key else 'has no backend left'}",
|
|
412
|
+
file=sys.stderr,
|
|
413
|
+
)
|
|
414
|
+
return self._search_brave(query)
|
|
415
|
+
|
|
416
|
+
def _search_firecrawl(self, query: str) -> tuple[list[dict], bool]:
|
|
417
|
+
"""(results, credits_exhausted).
|
|
418
|
+
|
|
419
|
+
The flag is separate from an empty list because the two mean opposite
|
|
420
|
+
things: no results for this query, versus no results for any query from
|
|
421
|
+
here on. Only the second is worth switching engines over.
|
|
422
|
+
"""
|
|
423
|
+
body = {"query": query, "limit": self.count, "sources": ["web"]}
|
|
424
|
+
headers = {"Authorization": f"Bearer {self.firecrawl_api_key}"}
|
|
425
|
+
try:
|
|
426
|
+
resp = requests.post(
|
|
427
|
+
_FIRECRAWL_ENDPOINT, json=body, headers=headers, timeout=self.timeout
|
|
428
|
+
)
|
|
429
|
+
except requests.RequestException as exc:
|
|
430
|
+
self.query_errors.append((query, f"firecrawl {type(exc).__name__}: {exc}"))
|
|
431
|
+
return ([], False)
|
|
432
|
+
if resp.status_code == 402:
|
|
433
|
+
return ([], True)
|
|
434
|
+
if not resp.ok:
|
|
435
|
+
self.query_errors.append((query, f"firecrawl {resp.status_code} {resp.reason}"))
|
|
436
|
+
return ([], False)
|
|
437
|
+
try:
|
|
438
|
+
payload = resp.json()
|
|
439
|
+
except ValueError as exc:
|
|
440
|
+
self.query_errors.append((query, f"firecrawl reply was not JSON: {exc}"))
|
|
441
|
+
return ([], False)
|
|
442
|
+
if not payload.get("success", True):
|
|
443
|
+
self.query_errors.append((query, f"firecrawl: {payload.get('error')}"))
|
|
444
|
+
return ([], False)
|
|
445
|
+
data = payload.get("data") or {}
|
|
446
|
+
rows = data.get("web") if isinstance(data, dict) else data
|
|
447
|
+
if not isinstance(rows, list):
|
|
448
|
+
self.query_errors.append((query, "firecrawl data.web was not a list"))
|
|
449
|
+
return ([], False)
|
|
450
|
+
# Normalised to the shape `_to_signal` already reads, so one code path
|
|
451
|
+
# builds the Signal whichever engine answered. Firecrawl reports no age
|
|
452
|
+
# for a result; the keys stay absent rather than being faked.
|
|
453
|
+
results = [
|
|
454
|
+
{
|
|
455
|
+
"url": row.get("url", ""),
|
|
456
|
+
"title": row.get("title", ""),
|
|
457
|
+
"description": row.get("description", ""),
|
|
458
|
+
"backend": "firecrawl",
|
|
459
|
+
}
|
|
460
|
+
for row in rows
|
|
461
|
+
if isinstance(row, dict)
|
|
462
|
+
]
|
|
463
|
+
return (results, False)
|
|
464
|
+
|
|
465
|
+
def _search_brave(self, query: str) -> list[dict]:
|
|
466
|
+
# Reachable with no key only after a Firecrawl 402, since `build()`
|
|
467
|
+
# requires the key when Brave is the configured backend. Checked here
|
|
468
|
+
# rather than at the fallback because it has to hold for *every*
|
|
469
|
+
# remaining query, not just the one that hit the 402: sending them with
|
|
470
|
+
# an empty token would spend the rest of the run collecting 401s.
|
|
471
|
+
if not self.api_key:
|
|
472
|
+
self.query_errors.append(
|
|
473
|
+
(query, "402 firecrawl credits exhausted, and no Brave key to fall back to")
|
|
474
|
+
)
|
|
475
|
+
return []
|
|
476
|
+
|
|
477
|
+
params: dict[str, object] = {"q": query, "count": self.count}
|
|
478
|
+
if self.freshness:
|
|
479
|
+
params["freshness"] = self.freshness
|
|
480
|
+
if self.country:
|
|
481
|
+
params["country"] = self.country
|
|
482
|
+
headers = {
|
|
483
|
+
"Accept": "application/json",
|
|
484
|
+
"X-Subscription-Token": self.api_key,
|
|
485
|
+
}
|
|
486
|
+
try:
|
|
487
|
+
resp = requests.get(
|
|
488
|
+
_BRAVE_ENDPOINT, params=params, headers=headers, timeout=self.timeout
|
|
489
|
+
)
|
|
490
|
+
except requests.RequestException as exc:
|
|
491
|
+
self.query_errors.append((query, f"{type(exc).__name__}: {exc}"))
|
|
492
|
+
return []
|
|
493
|
+
if resp.status_code == 429:
|
|
494
|
+
self.query_errors.append((query, "429 rate limited"))
|
|
495
|
+
return []
|
|
496
|
+
if not resp.ok:
|
|
497
|
+
self.query_errors.append((query, f"{resp.status_code} {resp.reason}"))
|
|
498
|
+
return []
|
|
499
|
+
try:
|
|
500
|
+
payload = resp.json()
|
|
501
|
+
except ValueError as exc:
|
|
502
|
+
self.query_errors.append((query, f"reply was not JSON: {exc}"))
|
|
503
|
+
return []
|
|
504
|
+
results = ((payload.get("web") or {}).get("results")) or []
|
|
505
|
+
if not isinstance(results, list):
|
|
506
|
+
self.query_errors.append((query, "web.results was not a list"))
|
|
507
|
+
return []
|
|
508
|
+
for result in results:
|
|
509
|
+
if isinstance(result, dict):
|
|
510
|
+
result["backend"] = "brave"
|
|
511
|
+
return results
|
|
512
|
+
|
|
513
|
+
def _page_text(self, url: str) -> tuple[str, str]:
|
|
514
|
+
"""(text, error). A failed page fetch is not a failed query — the result
|
|
515
|
+
is still real — so this reports rather than raises."""
|
|
516
|
+
headers = {"User-Agent": self.user_agent} if self.user_agent else {}
|
|
517
|
+
try:
|
|
518
|
+
resp = requests.get(url, headers=headers, timeout=self.page_timeout)
|
|
519
|
+
except requests.RequestException as exc:
|
|
520
|
+
return ("", f"{type(exc).__name__}: {exc}")
|
|
521
|
+
if not resp.ok:
|
|
522
|
+
return ("", f"{resp.status_code} {resp.reason}")
|
|
523
|
+
content_type = resp.headers.get("Content-Type", "")
|
|
524
|
+
if "html" not in content_type.lower() and content_type:
|
|
525
|
+
return ("", f"not HTML (Content-Type: {content_type})")
|
|
526
|
+
text = _visible_text(resp.text)
|
|
527
|
+
if not text:
|
|
528
|
+
return ("", "no visible text (page is probably rendered by JavaScript)")
|
|
529
|
+
return (text[: self.page_chars], "")
|
|
530
|
+
|
|
531
|
+
def fetch(self) -> list[Signal]:
|
|
532
|
+
self.query_errors = []
|
|
533
|
+
self.page_errors = []
|
|
534
|
+
self.pages_fetched = 0
|
|
535
|
+
self.passages_found = 0
|
|
536
|
+
self._firecrawl_exhausted = False
|
|
537
|
+
signals: list[Signal] = []
|
|
538
|
+
seen_ids: set[str] = set()
|
|
539
|
+
pages_attempted = 0
|
|
540
|
+
|
|
541
|
+
for index, query in enumerate(self.queries):
|
|
542
|
+
if index and self.delay_seconds:
|
|
543
|
+
time.sleep(self.delay_seconds)
|
|
544
|
+
for result in self._search(query):
|
|
545
|
+
url = str(result.get("url") or "").strip()
|
|
546
|
+
if not url:
|
|
547
|
+
continue
|
|
548
|
+
signal_id = normalise_url(url)
|
|
549
|
+
# Overlapping queries returning the same page is expected, and
|
|
550
|
+
# the point of normalising: one event, one signal.
|
|
551
|
+
if signal_id in seen_ids:
|
|
552
|
+
continue
|
|
553
|
+
seen_ids.add(signal_id)
|
|
554
|
+
if self.self_identification:
|
|
555
|
+
pages_attempted += 1
|
|
556
|
+
signals.extend(
|
|
557
|
+
self._to_passage_signals(result, url, signal_id, query)
|
|
558
|
+
)
|
|
559
|
+
else:
|
|
560
|
+
signals.append(self._to_signal(result, url, signal_id, query))
|
|
561
|
+
|
|
562
|
+
# Said on every run of this mode, because "nothing matched" and "nothing
|
|
563
|
+
# could be read" look identical in a signal count of zero, and the
|
|
564
|
+
# retired scraper's whole failure mode was the second wearing the
|
|
565
|
+
# first's clothes.
|
|
566
|
+
if self.self_identification and pages_attempted:
|
|
567
|
+
print(
|
|
568
|
+
f"websearch source: {self.pages_fetched}/{pages_attempted} page(s) read, "
|
|
569
|
+
f"{self.passages_found} self-identifying passage(s) found",
|
|
570
|
+
file=sys.stderr,
|
|
571
|
+
)
|
|
572
|
+
if self.page_errors:
|
|
573
|
+
print(
|
|
574
|
+
f"websearch source: {len(self.page_errors)} page(s) could not be read "
|
|
575
|
+
f"and their passages are missing from this run — "
|
|
576
|
+
f"{'; '.join(f'{u}: {why}' for u, why in self.page_errors)}",
|
|
577
|
+
file=sys.stderr,
|
|
578
|
+
)
|
|
579
|
+
# Every page refusing us is a broken funnel, not a quiet day.
|
|
580
|
+
if self.pages_fetched == 0:
|
|
581
|
+
detail = "; ".join(f"{u}: {why}" for u, why in self.page_errors[:3])
|
|
582
|
+
raise RuntimeError(
|
|
583
|
+
f"websearch source: all {pages_attempted} page(s) failed to read — "
|
|
584
|
+
f"{detail}"
|
|
585
|
+
)
|
|
586
|
+
|
|
587
|
+
if self.queries and len(self.query_errors) == len(self.queries):
|
|
588
|
+
detail = "; ".join(f"{q}: {why}" for q, why in self.query_errors[:3])
|
|
589
|
+
raise RuntimeError(
|
|
590
|
+
f"websearch source: all {len(self.queries)} query(ies) failed — {detail}"
|
|
591
|
+
)
|
|
592
|
+
if self.query_errors:
|
|
593
|
+
print(
|
|
594
|
+
f"websearch source: {len(self.query_errors)} of {len(self.queries)} "
|
|
595
|
+
f"query(ies) failed — {'; '.join(q for q, _ in self.query_errors)}",
|
|
596
|
+
file=sys.stderr,
|
|
597
|
+
)
|
|
598
|
+
|
|
599
|
+
retval = signals
|
|
600
|
+
return retval
|
|
601
|
+
|
|
602
|
+
def _to_passage_signals(
|
|
603
|
+
self, result: dict, url: str, page_id: str, query: str
|
|
604
|
+
) -> list[Signal]:
|
|
605
|
+
"""One Signal per self-identifying passage on this page (issue #138).
|
|
606
|
+
|
|
607
|
+
A page that cannot be fetched yields nothing and is recorded in
|
|
608
|
+
`page_errors`: in this mode the page is not the lead, so there is no
|
|
609
|
+
half-signal worth emitting from a title and a snippet.
|
|
610
|
+
"""
|
|
611
|
+
page_text, page_error = self._page_text(url)
|
|
612
|
+
if not page_text:
|
|
613
|
+
self.page_errors.append((url, page_error))
|
|
614
|
+
return []
|
|
615
|
+
self.pages_fetched += 1
|
|
616
|
+
|
|
617
|
+
title = str(result.get("title") or "").strip()
|
|
618
|
+
found = _passages(
|
|
619
|
+
page_text,
|
|
620
|
+
self.self_identification,
|
|
621
|
+
self.passage_chars,
|
|
622
|
+
self.max_passages_per_page,
|
|
623
|
+
self.same_comment_chars,
|
|
624
|
+
)
|
|
625
|
+
signals: list[Signal] = []
|
|
626
|
+
for phrase, passage in found:
|
|
627
|
+
digest = hashlib.sha1(passage.encode("utf-8")).hexdigest()[:12]
|
|
628
|
+
signals.append(
|
|
629
|
+
Signal(
|
|
630
|
+
# The passage is the lead, so the passage is the text. The
|
|
631
|
+
# page is context and stays in meta; see the docstring.
|
|
632
|
+
id=f"{page_id}#p={digest}",
|
|
633
|
+
text=passage,
|
|
634
|
+
url=url,
|
|
635
|
+
source=self.label,
|
|
636
|
+
meta={
|
|
637
|
+
"parent_title": title,
|
|
638
|
+
"parent_url": url,
|
|
639
|
+
"phrase": phrase,
|
|
640
|
+
"query": query,
|
|
641
|
+
"backend": str(result.get("backend") or ""),
|
|
642
|
+
"page_fetched": True,
|
|
643
|
+
"page_error": "",
|
|
644
|
+
},
|
|
645
|
+
)
|
|
646
|
+
)
|
|
647
|
+
self.passages_found += len(signals)
|
|
648
|
+
return signals
|
|
649
|
+
|
|
650
|
+
def _to_signal(self, result: dict, url: str, signal_id: str, query: str) -> Signal:
|
|
651
|
+
title = str(result.get("title") or "").strip()
|
|
652
|
+
snippet = str(result.get("description") or "").strip()
|
|
653
|
+
meta = {
|
|
654
|
+
"title": title,
|
|
655
|
+
"snippet": snippet,
|
|
656
|
+
"query": query,
|
|
657
|
+
"backend": str(result.get("backend") or ""),
|
|
658
|
+
"age": str(result.get("age") or ""),
|
|
659
|
+
"page_age": str(result.get("page_age") or ""),
|
|
660
|
+
"page_fetched": False,
|
|
661
|
+
"page_error": "",
|
|
662
|
+
}
|
|
663
|
+
text = f"{title}. {snippet}".strip()
|
|
664
|
+
if self.fetch_page:
|
|
665
|
+
page_text, page_error = self._page_text(url)
|
|
666
|
+
if page_text:
|
|
667
|
+
meta["page_fetched"] = True
|
|
668
|
+
text = f"{text}\n\n{page_text}".strip()
|
|
669
|
+
else:
|
|
670
|
+
meta["page_error"] = page_error
|
|
671
|
+
retval = Signal(id=signal_id, text=text, url=url, source=self.label, meta=meta)
|
|
672
|
+
return retval
|
|
673
|
+
|
|
674
|
+
|
|
675
|
+
@register_source("websearch")
|
|
676
|
+
def build(cfg: dict) -> Source:
|
|
677
|
+
backend = str(cfg.get("backend", "brave") or "brave").strip().lower()
|
|
678
|
+
if backend not in _BACKENDS:
|
|
679
|
+
raise RuntimeError(
|
|
680
|
+
f"websearch source: 'backend' must be one of {', '.join(_BACKENDS)}, "
|
|
681
|
+
f"not {backend!r}"
|
|
682
|
+
)
|
|
683
|
+
|
|
684
|
+
api_key_env = cfg.get("api_key_env", "BRAVE_API_KEY")
|
|
685
|
+
api_key = os.environ.get(api_key_env) or ""
|
|
686
|
+
firecrawl_api_key_env = cfg.get("firecrawl_api_key_env", "FIRECRAWL_API_KEY")
|
|
687
|
+
firecrawl_api_key = ""
|
|
688
|
+
|
|
689
|
+
if backend == "firecrawl":
|
|
690
|
+
firecrawl_api_key = os.environ.get(firecrawl_api_key_env) or ""
|
|
691
|
+
if not firecrawl_api_key:
|
|
692
|
+
raise RuntimeError(
|
|
693
|
+
f"websearch source needs the Firecrawl API key in "
|
|
694
|
+
f"${firecrawl_api_key_env} — it is a secret, so it is never "
|
|
695
|
+
"accepted from config"
|
|
696
|
+
)
|
|
697
|
+
# The Brave key stays optional here: it is only the 402 fallback, and
|
|
698
|
+
# refusing to start without it would make the backend that needs no
|
|
699
|
+
# fallback impossible to configure.
|
|
700
|
+
elif not api_key:
|
|
701
|
+
raise RuntimeError(
|
|
702
|
+
f"websearch source needs the Brave Search API key in ${api_key_env} — "
|
|
703
|
+
"it is a secret, so it is never accepted from config"
|
|
704
|
+
)
|
|
705
|
+
|
|
706
|
+
if backend == "firecrawl":
|
|
707
|
+
brave_only = [k for k in ("freshness", "country") if cfg.get(k)]
|
|
708
|
+
if brave_only:
|
|
709
|
+
raise RuntimeError(
|
|
710
|
+
"websearch source: "
|
|
711
|
+
f"{', '.join(brave_only)} {'is' if len(brave_only) == 1 else 'are'} "
|
|
712
|
+
"Brave-only and would be silently ignored by the firecrawl "
|
|
713
|
+
"backend — drop it, or use backend 'brave'"
|
|
714
|
+
)
|
|
715
|
+
|
|
716
|
+
queries = cfg.get("queries")
|
|
717
|
+
if not isinstance(queries, list) or not queries:
|
|
718
|
+
raise RuntimeError("websearch source needs a non-empty 'queries' list")
|
|
719
|
+
bad = [q for q in queries if not isinstance(q, str) or not q.strip()]
|
|
720
|
+
if bad:
|
|
721
|
+
raise RuntimeError("websearch source: every entry in 'queries' must be a non-empty string")
|
|
722
|
+
|
|
723
|
+
self_identification = cfg.get("self_identification") or []
|
|
724
|
+
if self_identification:
|
|
725
|
+
if not isinstance(self_identification, list) or any(
|
|
726
|
+
not isinstance(p, str) or not p.strip() for p in self_identification
|
|
727
|
+
):
|
|
728
|
+
raise RuntimeError(
|
|
729
|
+
"websearch source: 'self_identification' must be a list of non-empty strings"
|
|
730
|
+
)
|
|
731
|
+
if not cfg.get("fetch_page"):
|
|
732
|
+
raise RuntimeError(
|
|
733
|
+
"websearch source: 'self_identification' needs 'fetch_page': true. A phrase "
|
|
734
|
+
"found in a search snippet is not a comment — snippets run about 150 "
|
|
735
|
+
"characters, too short to carry a job, a workaround or a budget."
|
|
736
|
+
)
|
|
737
|
+
self_identification = [p.strip() for p in self_identification]
|
|
738
|
+
|
|
739
|
+
retval = WebSearchSource(
|
|
740
|
+
api_key=api_key,
|
|
741
|
+
queries=[q.strip() for q in queries],
|
|
742
|
+
backend=backend,
|
|
743
|
+
firecrawl_api_key=firecrawl_api_key,
|
|
744
|
+
count=int(cfg.get("count", 10)),
|
|
745
|
+
freshness=str(cfg.get("freshness", "") or ""),
|
|
746
|
+
fetch_page=bool(cfg.get("fetch_page", False)),
|
|
747
|
+
page_chars=int(cfg.get("page_chars", _DEFAULT_PAGE_CHARS)),
|
|
748
|
+
label=cfg.get("label", _DEFAULT_LABEL),
|
|
749
|
+
country=str(cfg.get("country", "") or ""),
|
|
750
|
+
delay_seconds=float(cfg.get("delay_seconds", 1.1)),
|
|
751
|
+
timeout=int(cfg.get("timeout", 30)),
|
|
752
|
+
page_timeout=int(cfg.get("page_timeout", 20)),
|
|
753
|
+
user_agent=cfg.get("user_agent", ""),
|
|
754
|
+
self_identification=self_identification,
|
|
755
|
+
passage_chars=int(cfg.get("passage_chars", _DEFAULT_PASSAGE_CHARS)),
|
|
756
|
+
max_passages_per_page=int(cfg.get("max_passages_per_page", 5)),
|
|
757
|
+
same_comment_chars=int(
|
|
758
|
+
cfg.get("same_comment_chars", _DEFAULT_SAME_COMMENT_CHARS)
|
|
759
|
+
),
|
|
760
|
+
)
|
|
761
|
+
return retval
|