返回 last30days-skill
watchlist.py
根目录 / skills / last30days / scripts / watchlist.py
1 #!/usr/bin/env python3
2 """Topic watchlist management for last30days."""
3
4 from __future__ import annotations
5
6 import argparse
7 from decimal import Decimal
8 import json
9 import math
10 import os
11 import secrets
12 import subprocess
13 import sys
14 import time
15 import tempfile
16 import urllib.parse
17 from pathlib import Path
18
19 SCRIPT_DIR = Path(__file__).parent.resolve()
20 sys.path.insert(0, str(SCRIPT_DIR))
21
22 import store
23 from lib import env as envlib, health, http, public_host, schema, usage
24
25 _parse_budget = store.parse_budget
26
27
28 # --- Webhook Delivery Functions ---
29
30 _RESERVED_WEBHOOK_SUFFIXES = (
31 ".localhost",
32 ".local",
33 ".internal",
34 ".localdomain",
35 ".arpa",
36 )
37
38
39 def _refuse_webhook_redirect(_url: str) -> bool:
40 """Webhooks must never follow 3xx redirects."""
41 return False
42
43
44 def _validate_webhook_url(url: str) -> urllib.parse.ParseResult:
45 """Require a public https:// webhook URL with no userinfo or non-public literals.
46
47 DNS resolution and IP pinning happen fresh at connect time inside
48 ``http.post_raw(..., public_only=True)`` so offline configuration stays
49 network-free and DNS rebinding cannot bypass the check.
50 """
51 err = "delivery_channel must be a public https:// URL"
52 if not isinstance(url, str) or not url or url != url.strip():
53 raise ValueError(err)
54 if any(ch.isspace() or ord(ch) < 0x20 or 0x7F <= ord(ch) <= 0x9F for ch in url):
55 raise ValueError(err)
56 try:
57 parsed = urllib.parse.urlparse(url)
58 port = parsed.port
59 except ValueError:
60 raise ValueError(err) from None
61 if port is not None and not (1 <= port <= 65535):
62 raise ValueError(err)
63 if "\\" in parsed.netloc or "%" in (parsed.hostname or ""):
64 raise ValueError(err)
65 if parsed.scheme.lower() != "https":
66 raise ValueError(err)
67 if parsed.username is not None or parsed.password is not None:
68 raise ValueError(err)
69
70 raw_host = parsed.hostname or ""
71 if not raw_host:
72 raise ValueError(err)
73
74 bare_literal = raw_host.rstrip(".").lower()
75 if ":" in bare_literal:
76 ip = public_host._parse_ip_literal(bare_literal)
77 if ip is None or not public_host._is_public_ip(ip):
78 raise ValueError(err)
79 else:
80 try:
81 ascii_host = raw_host.encode("idna").decode("ascii").lower()
82 except UnicodeError:
83 raise ValueError(err) from None
84 bare_host = ascii_host[:-1] if ascii_host.endswith(".") else ascii_host
85 if not bare_host or ".." in bare_host:
86 raise ValueError(err)
87 ip = public_host._parse_ip_literal(bare_host)
88 if ip is not None:
89 if not public_host._is_public_ip(ip):
90 raise ValueError(err)
91 else:
92 if "." not in bare_host:
93 raise ValueError(err)
94 if bare_host == "localhost" or bare_host.endswith(_RESERVED_WEBHOOK_SUFFIXES):
95 raise ValueError(err)
96
97 if not public_host.is_public_address_syntax(url):
98 raise ValueError(err)
99 return parsed
100
101
102 def _deliver_findings(topic_name: str, counts: dict, *, degraded: bool = False) -> None:
103 """Send webhook notification if delivery is configured and there are new findings."""
104 channel = store.get_setting("delivery_channel", "")
105 if not channel or counts.get("new", 0) == 0:
106 return
107
108 mode = store.get_setting("delivery_mode", "announce")
109 message = _format_delivery_message(topic_name, counts, mode)
110 if degraded:
111 message += "\nResearch completed with degraded coverage."
112
113 # Require a public https:// host before routing. Match Slack on the exact
114 # normalized hostname rather than a substring.
115 try:
116 parsed = urllib.parse.urlparse(channel)
117 _ = parsed.port
118 except ValueError as error:
119 print(f"Delivery failed: {type(error).__name__}", file=sys.stderr)
120 return
121 try:
122 _validate_webhook_url(channel)
123 except ValueError:
124 print("Delivery skipped: delivery_channel must be a public https:// URL", file=sys.stderr)
125 return
126 try:
127 if (parsed.hostname or "").rstrip(".").lower() == "hooks.slack.com":
128 _send_slack_webhook(channel, message)
129 else:
130 _send_generic_webhook(channel, message)
131 except http.HTTPError as error:
132 detail = f"HTTP {error.status_code}" if error.status_code is not None else error.outcome_state
133 print(f"Delivery failed: {detail}", file=sys.stderr)
134 except Exception as error:
135 print(f"Delivery failed: {type(error).__name__}", file=sys.stderr)
136
137
138 def _format_delivery_message(topic: str, counts: dict, mode: str) -> str:
139 """Format notification message based on delivery mode."""
140 new = counts.get("new", 0)
141 updated = counts.get("updated", 0)
142
143 if mode == "announce":
144 return f"📰 *last30days update: {topic}*\n{new} new, {updated} updated"
145 elif mode == "silent":
146 return f"last30days: {new} new findings for '{topic}'"
147 else:
148 return f"last30days: Research complete for '{topic}'"
149
150
151 def _send_slack_webhook(url: str, text: str) -> None:
152 """POST to Slack incoming webhook."""
153 _validate_webhook_url(url)
154 http.post_raw(
155 url,
156 json_data={"text": text},
157 timeout=10,
158 retries=1,
159 sensitive_url=True,
160 redirect_guard=_refuse_webhook_redirect,
161 public_only=True,
162 decode_errors="replace",
163 )
164
165
166 def _send_generic_webhook(url: str, text: str) -> None:
167 """POST JSON payload to generic webhook."""
168 _validate_webhook_url(url)
169 http.post_raw(
170 url,
171 json_data={
172 "message": text,
173 "source": "last30days",
174 "timestamp": time.time(),
175 },
176 timeout=10,
177 retries=1,
178 sensitive_url=True,
179 redirect_guard=_refuse_webhook_redirect,
180 public_only=True,
181 decode_errors="replace",
182 )
183
184
185 # --- Command Handlers ---
186
187 def cmd_add(args):
188 schedule = "0 8 * * 1" if args.weekly else (args.schedule or "0 8 * * *")
189 queries = [query.strip() for query in (args.queries or "").split(",") if query.strip()] or None
190 topic = store.add_topic(args.topic, search_queries=queries, schedule=schedule)
191 sched_desc = "weekly (Mondays 8am)" if args.weekly else f"daily ({schedule})"
192 print(json.dumps({
193 "action": "added",
194 "topic": topic["name"],
195 "schedule": sched_desc,
196 "message": f'Added "{topic["name"]}" to watchlist. Schedule: {sched_desc}.',
197 }, default=str))
198
199
200 def cmd_remove(args):
201 removed = store.remove_topic(args.topic)
202 if not removed:
203 print(json.dumps({"action": "not_found", "topic": args.topic, "message": f'Topic not found: "{args.topic}"'}))
204 return
205 remaining = store.list_topics()
206 print(json.dumps({
207 "action": "removed",
208 "topic": args.topic,
209 "message": f'Removed "{args.topic}" from watchlist.',
210 "remaining": len(remaining),
211 }))
212
213
214 def _read_daily_budget() -> tuple[float | None, str | None]:
215 raw_budget = store.get_setting("daily_budget", "5.00")
216 try:
217 return _parse_budget(raw_budget), None
218 except ValueError as exc:
219 return None, str(exc)
220
221
222 def cmd_list(args):
223 del args
224 topics = store.list_topics()
225 budget_used, budget_unknown_runs = store.get_daily_usage()
226 budget_limit, budget_error = _read_daily_budget()
227 payload = {
228 "topics": topics,
229 "budget_used": budget_used,
230 "budget_limit": budget_limit,
231 "budget_unknown_runs": budget_unknown_runs,
232 }
233 if budget_error is not None:
234 payload["budget_error"] = budget_error
235 print(json.dumps(payload, default=str))
236
237
238 def cmd_delta(args):
239 topic = store.get_topic(args.topic)
240 if not topic:
241 print(json.dumps({"error": f'Topic not found: "{args.topic}"'}))
242 sys.exit(1)
243 print(json.dumps(store.compute_topic_delta(topic["id"]), default=str))
244
245
246 def cmd_run_one(args):
247 topic = store.get_topic(args.topic)
248 if not topic:
249 print(json.dumps({"error": f'Topic not found: "{args.topic}"'}))
250 sys.exit(1)
251 print(json.dumps(_budget_skip(topic) or _run_topic(topic), default=str))
252
253
254 def cmd_run_all(args):
255 del args
256 topics = [topic for topic in store.list_topics() if topic["enabled"]]
257 if not topics:
258 print(json.dumps({"message": "No enabled topics to research."}))
259 return
260
261 budget_limit, budget_error = _read_daily_budget()
262 results = []
263 for topic in topics:
264 results.append(_budget_skip(topic) or _run_topic(topic))
265
266 budget_used, budget_unknown_runs = store.get_daily_usage()
267 payload = {
268 "action": "run_all",
269 "results": results,
270 "budget_used": budget_used,
271 "budget_limit": budget_limit,
272 "budget_unknown_runs": budget_unknown_runs,
273 }
274 if budget_error is not None:
275 payload["budget_error"] = budget_error
276 print(json.dumps(payload, default=str))
277
278
279 def _budget_skip(topic: dict) -> dict | None:
280 limit, budget_error = _read_daily_budget()
281 if limit is None:
282 return {
283 "topic": topic["name"],
284 "status": "skipped",
285 "reason": (
286 f"Invalid daily_budget setting ({budget_error}); "
287 "refusing to run until reconfigured"
288 ),
289 }
290 cost, unknown = store.get_daily_usage()
291 if cost >= limit:
292 reason = f"Budget exceeded: ${cost:.2f}/${limit:.2f}"
293 elif unknown:
294 reason = f"Budget unknown: {unknown} run(s) today have unreported provider charges"
295 else:
296 return None
297 return {"topic": topic["name"], "status": "skipped", "reason": reason}
298
299
300 def _has_unknown_cost_marker(stderr: object, nonce: str | None = None) -> bool:
301 if not stderr:
302 return False
303 if isinstance(stderr, bytes):
304 text = stderr.decode("utf-8", errors="replace")
305 elif isinstance(stderr, str):
306 text = stderr
307 else:
308 return False
309 return usage.unknown_cost_marker(nonce) in text
310
311
312 def _run_topic(topic: dict) -> dict:
313 topic_id = topic["id"]
314 with tempfile.TemporaryDirectory(prefix="last30days-usage-") as temp_dir:
315 journal = Path(temp_dir) / "usage.db"
316 usage.create_journal(journal)
317 usage_nonce = secrets.token_hex(8)
318 # A scheduled run: the logged-in Reddit session stays off (its Keychain
319 # prompt cannot be answered unattended), and --no-browser-cookies below
320 # keeps every cookie read off besides.
321 child_env = dict(os.environ, **{
322 usage.JOURNAL_ENV: str(journal),
323 usage.NONCE_ENV: usage_nonce,
324 "LAST30DAYS_STORE": "0",
325 "LAST30DAYS_SCHEDULED_RUN": "1",
326 })
327 run_id = store.record_run(topic_id, source_mode="v3", status="running")
328 unknown_cost_flag = [False]
329 try:
330 result = _research_topic(
331 topic,
332 run_id,
333 child_env,
334 unknown_cost_flag=unknown_cost_flag,
335 usage_nonce=usage_nonce,
336 )
337 finally:
338 costs = usage.read_journal(journal)
339 if unknown_cost_flag[0]:
340 costs["cost_unknown"] = 1
341 store.update_run(run_id, **costs)
342 result.update(costs)
343 return result
344
345
346 def _validate_utf8_text(value: object, field: str) -> None:
347 if not isinstance(value, str):
348 raise ValueError(f"expected {field} to be text")
349 value.encode("utf-8")
350
351
352 def _findings_from_output(output: str) -> list[dict]:
353 payload = json.loads(output)
354 if not isinstance(payload, dict):
355 raise ValueError("expected a research report object")
356 if payload.get("comparison") is True:
357 entries = payload.get("reports")
358 if not isinstance(entries, list) or len(entries) < 2:
359 raise ValueError("expected at least two reports in a comparison")
360 reports = []
361 for entry in entries:
362 _validate_utf8_text(entry["entity"], "comparison entity")
363 reports.append(entry["report"])
364 else:
365 reports = [payload]
366 findings = []
367 for raw_report in reports:
368 report = schema.report_from_dict(raw_report)
369 _validate_utf8_text(report.topic, "report topic")
370 findings.extend(store.findings_from_report(report, limit=25))
371 for finding in findings:
372 for field in ("source", "source_url", "source_title", "author", "content", "summary"):
373 _validate_utf8_text(finding[field], f"finding {field}")
374 for field in ("engagement_score", "relevance_score"):
375 score = finding[field]
376 if type(score) not in (int, float) or not math.isfinite(score):
377 raise ValueError(f"expected finding {field} to be a finite number")
378 finding[field] = float(score)
379 return findings
380
381
382 def _research_topic(
383 topic: dict,
384 run_id: int,
385 child_env: dict,
386 *,
387 unknown_cost_flag: list[bool] | None = None,
388 usage_nonce: str | None = None,
389 ) -> dict:
390 start_time = time.time()
391 topic_id = topic["id"]
392
393 try:
394 search_queries = json.loads(topic["search_queries"]) if topic.get("search_queries") else []
395 if not isinstance(search_queries, list) or any(
396 not isinstance(query, str) or "\0" in query
397 for query in search_queries
398 ):
399 raise ValueError("expected a list of query strings without NUL characters")
400 search_term = next((query.strip() for query in search_queries if query.strip()), topic["name"])
401 search_term.encode("utf-8")
402 except (TypeError, ValueError) as exc:
403 error = f"Invalid saved search queries: {exc}"
404 store.update_run(
405 run_id,
406 status="failed",
407 error_message=error,
408 duration_seconds=time.time() - start_time,
409 )
410 return {"topic": topic["name"], "status": "failed", "error": error}
411
412 try:
413 result = subprocess.run(
414 [
415 sys.executable,
416 str(SCRIPT_DIR / "last30days.py"),
417 "--research-only",
418 "--emit=json",
419 "--json-profile=raw",
420 "--require-local-report",
421 "--quick",
422 "--lookback-days",
423 "90",
424 # Watchlist is an unattended cron host: never probe browser
425 # cookies (matches the MCP server). Avoids a silent Chromium
426 # read / unattended macOS Keychain prompt when a user has set
427 # FROM_BROWSER=auto for interactive use.
428 "--no-browser-cookies",
429 "--",
430 search_term,
431 ],
432 capture_output=True,
433 text=True,
434 timeout=300,
435 env={**child_env, envlib.ALLOW_ENGINE_PLAN_VAR: "1"},
436 )
437 except (OSError, UnicodeDecodeError) as exc:
438 if unknown_cost_flag is not None and isinstance(exc, UnicodeDecodeError):
439 # The child ran, but we cannot check its stderr usage marker.
440 unknown_cost_flag[0] = True
441 error = f"Research subprocess failed ({type(exc).__name__})"
442 duration = time.time() - start_time
443 store.update_run(run_id, status="failed", error_message=error, duration_seconds=duration)
444 return {"topic": topic["name"], "status": "failed", "error": error, "duration": duration}
445 except subprocess.TimeoutExpired as exc:
446 if unknown_cost_flag is not None and _has_unknown_cost_marker(exc.stderr, usage_nonce):
447 unknown_cost_flag[0] = True
448 duration = time.time() - start_time
449 store.update_run(
450 run_id,
451 status="failed",
452 error_message="Research timed out after 300s",
453 duration_seconds=duration,
454 )
455 return {"topic": topic["name"], "status": "failed", "error": "timeout"}
456
457 if unknown_cost_flag is not None and _has_unknown_cost_marker(result.stderr, usage_nonce):
458 unknown_cost_flag[0] = True
459
460 duration = time.time() - start_time
461 degraded = result.returncode == health.STRICT_EXIT_CODE and any(
462 line.startswith(health.STRICT_EXIT_PREFIX) and line.removeprefix(health.STRICT_EXIT_PREFIX).strip()
463 for line in result.stderr.split("\n")
464 )
465 if result.returncode != 0 and not degraded:
466 store.update_run(
467 run_id,
468 status="failed",
469 error_message=result.stderr[:500],
470 duration_seconds=duration,
471 )
472 return {
473 "topic": topic["name"],
474 "status": "failed",
475 "error": result.stderr[:200],
476 "duration": duration,
477 }
478
479 try:
480 findings = _findings_from_output(result.stdout)
481 except (AttributeError, KeyError, OverflowError, TypeError, ValueError) as exc:
482 error = f"Invalid research output ({type(exc).__name__})"
483 store.update_run(run_id, status="failed", error_message=error, duration_seconds=duration)
484 return {"topic": topic["name"], "status": "failed", "error": error, "duration": duration}
485
486 counts = store.store_findings(run_id, topic_id, findings, count_by_topic=True)
487 status = health.DEGRADED if degraded else "completed"
488 store.update_run(
489 run_id,
490 status=status,
491 duration_seconds=duration,
492 findings_new=counts["new"],
493 findings_updated=counts["updated"],
494 )
495
496 # Deliver webhook notification if configured
497 _deliver_findings(topic["name"], counts, degraded=degraded)
498
499 return {
500 "topic": topic["name"],
501 "status": status,
502 "new": counts["new"],
503 "updated": counts["updated"],
504 "duration": duration,
505 }
506
507
508 def cmd_config(args):
509 if args.key == "budget":
510 try:
511 value = _parse_budget(args.value)
512 except ValueError:
513 raise SystemExit("daily_budget must be a finite non-negative number")
514 canonical = format(Decimal(str(value)), "f")
515 store.set_setting("daily_budget", canonical)
516 print(json.dumps({"action": "config", "key": "daily_budget", "value": canonical}))
517 return
518 if args.key == "delivery":
519 value = str(args.value)
520 # Reject invalid, non-https, or private webhook channels at write time
521 # so the operator gets immediate feedback. Matches _deliver_findings.
522 if value:
523 try:
524 _validate_webhook_url(value)
525 except ValueError:
526 raise SystemExit("delivery_channel must be a public https:// URL")
527 store.set_setting("delivery_channel", value)
528 print(json.dumps({"action": "config", "key": "delivery_channel", "configured": bool(value)}))
529 return
530 raise SystemExit(f"Unknown config key: {args.key}")
531
532
533 def build_parser() -> argparse.ArgumentParser:
534 parser = argparse.ArgumentParser(description="Manage the last30days watchlist")
535 sub = parser.add_subparsers(dest="command")
536
537 add = sub.add_parser("add")
538 add.add_argument("topic")
539 add.add_argument("--schedule")
540 add.add_argument("--weekly", action="store_true")
541 add.add_argument("--queries")
542 add.set_defaults(func=cmd_add)
543
544 remove = sub.add_parser("remove")
545 remove.add_argument("topic")
546 remove.set_defaults(func=cmd_remove)
547
548 list_parser = sub.add_parser("list")
549 list_parser.set_defaults(func=cmd_list)
550
551 delta = sub.add_parser("delta")
552 delta.add_argument("topic")
553 delta.set_defaults(func=cmd_delta)
554
555 run_one = sub.add_parser("run-one")
556 run_one.add_argument("topic")
557 run_one.set_defaults(func=cmd_run_one)
558
559 run_all = sub.add_parser("run-all")
560 run_all.set_defaults(func=cmd_run_all)
561
562 config = sub.add_parser("config")
563 config.add_argument("key", choices=["delivery", "budget"])
564 config.add_argument("value")
565 config.set_defaults(func=cmd_config)
566
567 return parser
568
569
570 def main() -> int:
571 parser = build_parser()
572 args = parser.parse_args()
573 if not getattr(args, "command", None):
574 parser.print_help()
575 return 1
576 args.func(args)
577 return 0
578
579
580 if __name__ == "__main__":
581 raise SystemExit(main())
582
582 lines PYTHON