delimit-cli 4.0.5 → 4.1.0

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.
@@ -1,1662 +1,2 @@
1
- """
2
- Notification helper for delimit_notify and delimit_notify_inbox tools.
3
-
4
- Supports webhook, Slack, and email channels (outbound).
5
- Supports impact-based notification routing (LED-233).
6
- Supports IMAP inbox polling with classification and forwarding (inbound).
7
- Stores notification history in ~/.delimit/notifications.jsonl.
8
- Stores inbox routing log in ~/.delimit/inbox_routing.jsonl.
9
- """
10
-
11
- import email
12
- import email.header
13
- import email.utils
14
- import imaplib
15
- import json
16
- import logging
17
- import os
18
- import smtplib
19
- import urllib.request
20
- import urllib.error
21
- from datetime import datetime, timezone
22
- from email.mime.text import MIMEText
23
- from pathlib import Path
24
- from typing import Any, Dict, List, Optional
25
-
26
- import threading
27
- import time as _time
28
-
29
- try:
30
- import yaml as _yaml
31
- except ImportError:
32
- _yaml = None # type: ignore[assignment]
33
-
34
- # ── Email Throttle (Consensus 123: Storm Prevention) ────────────────
35
- # - Max 5 immediate emails per hour
36
- # - Non-P0 notifications batch into 15-minute digests
37
- # - P0 always sends immediately (bypasses throttle)
38
- _email_throttle_lock = threading.Lock()
39
- _email_send_times: list = [] # timestamps of recent sends
40
- _email_digest_queue: list = [] # batched non-urgent emails
41
- _EMAIL_MAX_PER_HOUR = 5
42
- _EMAIL_DIGEST_INTERVAL = 900 # 15 minutes
43
- _last_digest_flush = 0.0
44
-
45
- logger = logging.getLogger("delimit.ai.notify")
46
-
47
- HISTORY_FILE = Path.home() / ".delimit" / "notifications.jsonl"
48
- INBOX_ROUTING_FILE = Path.home() / ".delimit" / "inbox_routing.jsonl"
49
- OWNER_ACTIONS_FILE = Path.home() / ".delimit" / "owner_actions.jsonl"
50
-
51
- def _load_json_file(path: Path) -> Dict[str, Any]:
52
- try:
53
- if not path.exists():
54
- return {}
55
- with open(path, "r", encoding="utf-8") as f:
56
- data = json.load(f)
57
- return data if isinstance(data, dict) else {}
58
- except (OSError, json.JSONDecodeError):
59
- return {}
60
-
61
-
62
- def _load_secret_value(*names: str) -> str:
63
- """Load a secret value from ~/.delimit/secrets/<NAME>.json files."""
64
- secrets_dir = Path.home() / ".delimit" / "secrets"
65
- for name in names:
66
- data = _load_json_file(secrets_dir / f"{name}.json")
67
- value = data.get("value") or data.get("token") or data.get("access_token") or ""
68
- if value:
69
- return str(value)
70
- return ""
71
-
72
-
73
- def _load_inbound_email_config() -> Dict[str, str]:
74
- secrets_dir = Path.home() / ".delimit" / "secrets"
75
- smtp_accounts = _load_json_file(secrets_dir / "smtp-all.json")
76
- defaults = smtp_accounts.get("_defaults", {}) if isinstance(smtp_accounts.get("_defaults"), dict) else {}
77
- account_name = str(defaults.get("from_account") or "pro@delimit.ai")
78
- account = smtp_accounts.get(account_name, {}) if isinstance(smtp_accounts.get(account_name), dict) else {}
79
- forward_cfg = _load_json_file(secrets_dir / "forward-to.json")
80
-
81
- return {
82
- "imap_host": str(account.get("host") or ""),
83
- "imap_port": str(account.get("imap_port") or "993"),
84
- "imap_user": str(account.get("user") or account_name or ""),
85
- "forward_to": str(
86
- os.environ.get("DELIMIT_FORWARD_TO", "")
87
- or forward_cfg.get("value")
88
- or forward_cfg.get("to")
89
- or defaults.get("to")
90
- or ""
91
- ),
92
- }
93
-
94
-
95
- # ── Inbound email configuration ──────────────────────────────────────
96
- _INBOUND_CFG = _load_inbound_email_config()
97
- IMAP_HOST = os.environ.get("DELIMIT_IMAP_HOST", "") or _INBOUND_CFG.get("imap_host", "")
98
- IMAP_PORT = int(os.environ.get("DELIMIT_IMAP_PORT", "") or _INBOUND_CFG.get("imap_port", "993"))
99
- IMAP_USER = os.environ.get("DELIMIT_IMAP_USER", "") or _INBOUND_CFG.get("imap_user", "")
100
- FORWARD_TO = _INBOUND_CFG.get("forward_to", "")
101
-
102
- # Domains/senders whose emails require owner action
103
- OWNER_ACTION_DOMAINS = {
104
- "cooperpress.com",
105
- "github.com",
106
- "lemon.com",
107
- "lemonsqueezy.com",
108
- "namecheap.com",
109
- "stripe.com",
110
- "google.com",
111
- "youtube.com",
112
- "x.com",
113
- "twitter.com",
114
- "npmjs.com",
115
- "vercel.com",
116
- "supabase.io",
117
- "supabase.com",
118
- "glama.ai",
119
- "vultr.com",
120
- "digitalocean.com",
121
- }
122
-
123
- OWNER_ACTION_SENDERS = set(
124
- filter(None, [os.environ.get("DELIMIT_OWNER_EMAIL", "")])
125
- )
126
-
127
- # Subject patterns that indicate owner-action (compiled once)
128
- import re as _re
129
- OWNER_ACTION_SUBJECT_PATTERNS = [
130
- _re.compile(r"social\s+draft", _re.IGNORECASE),
131
- _re.compile(r"show\s+hn", _re.IGNORECASE),
132
- _re.compile(r"approval", _re.IGNORECASE),
133
- _re.compile(r"action\s+required", _re.IGNORECASE),
134
- _re.compile(r"reply|respond", _re.IGNORECASE),
135
- _re.compile(r"invoice", _re.IGNORECASE),
136
- _re.compile(r"payment", _re.IGNORECASE),
137
- _re.compile(r"subscription", _re.IGNORECASE),
138
- ]
139
-
140
- # Sender patterns that are definitely non-owner (automated/bot)
141
- NON_OWNER_SENDERS = {
142
- "noreply@",
143
- "no-reply@",
144
- "notifications@",
145
- "mailer-daemon@",
146
- "postmaster@",
147
- "donotreply@",
148
- }
149
-
150
-
151
- def _record_notification(entry: Dict[str, Any]) -> None:
152
- """Append a notification record to the history file."""
153
- try:
154
- HISTORY_FILE.parent.mkdir(parents=True, exist_ok=True)
155
- with open(HISTORY_FILE, "a", encoding="utf-8") as f:
156
- f.write(json.dumps(entry) + "\n")
157
- except OSError as e:
158
- logger.warning("Failed to record notification: %s", e)
159
-
160
-
161
- def record_owner_action(entry: Dict[str, Any]) -> None:
162
- """Append an owner-action record for dashboard and async fanout."""
163
- try:
164
- OWNER_ACTIONS_FILE.parent.mkdir(parents=True, exist_ok=True)
165
- payload = {
166
- "timestamp": datetime.now(timezone.utc).isoformat(),
167
- "status": "open",
168
- **entry,
169
- }
170
- with open(OWNER_ACTIONS_FILE, "a", encoding="utf-8") as f:
171
- f.write(json.dumps(payload) + "\n")
172
- except OSError as e:
173
- logger.warning("Failed to record owner action: %s", e)
174
-
175
-
176
- def _post_json(url: str, payload: Dict[str, Any], timeout: int = 10) -> Dict[str, Any]:
177
- """POST a JSON payload to a URL. Returns status dict."""
178
- data = json.dumps(payload).encode("utf-8")
179
- req = urllib.request.Request(
180
- url,
181
- data=data,
182
- headers={"Content-Type": "application/json"},
183
- method="POST",
184
- )
185
- try:
186
- with urllib.request.urlopen(req, timeout=timeout) as resp:
187
- return {
188
- "status_code": resp.status,
189
- "success": 200 <= resp.status < 300,
190
- }
191
- except urllib.error.HTTPError as e:
192
- return {"status_code": e.code, "success": False, "error": str(e)}
193
- except urllib.error.URLError as e:
194
- return {"status_code": 0, "success": False, "error": str(e)}
195
-
196
-
197
- def send_webhook(
198
- webhook_url: str,
199
- message: str,
200
- event_type: str = "",
201
- ) -> Dict[str, Any]:
202
- """Send a generic webhook notification (JSON POST)."""
203
- if not webhook_url:
204
- return {"error": "webhook_url is required for webhook channel"}
205
-
206
- timestamp = datetime.now(timezone.utc).isoformat()
207
- payload = {
208
- "event_type": event_type or "delimit_notification",
209
- "message": message,
210
- "timestamp": timestamp,
211
- }
212
-
213
- result = _post_json(webhook_url, payload)
214
- record = {
215
- "channel": "webhook",
216
- "event_type": event_type,
217
- "message": message,
218
- "webhook_url": webhook_url,
219
- "timestamp": timestamp,
220
- "success": result.get("success", False),
221
- }
222
- _record_notification(record)
223
-
224
- return {
225
- "channel": "webhook",
226
- "delivered": result.get("success", False),
227
- "status_code": result.get("status_code"),
228
- "timestamp": timestamp,
229
- "error": result.get("error"),
230
- }
231
-
232
-
233
- def send_slack(
234
- webhook_url: str,
235
- message: str,
236
- event_type: str = "",
237
- ) -> Dict[str, Any]:
238
- """Send a Slack notification via incoming webhook."""
239
- if not webhook_url:
240
- return {"error": "webhook_url is required for slack channel"}
241
-
242
- timestamp = datetime.now(timezone.utc).isoformat()
243
- prefix = f"[{event_type}] " if event_type else ""
244
- payload = {"text": f"{prefix}{message}"}
245
-
246
- result = _post_json(webhook_url, payload)
247
- record = {
248
- "channel": "slack",
249
- "event_type": event_type,
250
- "message": message,
251
- "webhook_url": webhook_url,
252
- "timestamp": timestamp,
253
- "success": result.get("success", False),
254
- }
255
- _record_notification(record)
256
-
257
- return {
258
- "channel": "slack",
259
- "delivered": result.get("success", False),
260
- "status_code": result.get("status_code"),
261
- "timestamp": timestamp,
262
- "error": result.get("error"),
263
- }
264
-
265
-
266
- def send_telegram(
267
- message: str,
268
- event_type: str = "",
269
- bot_token: str = "",
270
- chat_id: str = "",
271
- ) -> Dict[str, Any]:
272
- """Send a Telegram message via bot API."""
273
- bot_token = bot_token or os.environ.get("DELIMIT_TELEGRAM_BOT_TOKEN", "") or _load_secret_value("DELIMIT_TELEGRAM_BOT_TOKEN", "TELEGRAM_MONITOR_BOT_TOKEN")
274
- chat_id = chat_id or os.environ.get("DELIMIT_TELEGRAM_CHAT_ID", "") or _load_secret_value("DELIMIT_TELEGRAM_CHAT_ID", "TELEGRAM_MONITOR_CHAT_ID")
275
- if not bot_token or not chat_id:
276
- return {"error": "telegram bot token and chat id are required"}
277
-
278
- timestamp = datetime.now(timezone.utc).isoformat()
279
- prefix = f"[{event_type}] " if event_type else ""
280
- payload = {
281
- "chat_id": chat_id,
282
- "text": f"{prefix}{message}",
283
- "disable_web_page_preview": False,
284
- }
285
- url = f"https://api.telegram.org/bot{bot_token}/sendMessage"
286
- result = _post_json(url, payload)
287
- _record_notification({
288
- "channel": "telegram",
289
- "event_type": event_type,
290
- "message": message,
291
- "timestamp": timestamp,
292
- "success": result.get("success", False),
293
- })
294
- return {
295
- "channel": "telegram",
296
- "delivered": result.get("success", False),
297
- "status_code": result.get("status_code"),
298
- "timestamp": timestamp,
299
- "error": result.get("error"),
300
- }
301
-
302
-
303
- def _load_smtp_account(from_account: str) -> Optional[Dict[str, str]]:
304
- """Load SMTP credentials from smtp-all.json for a given account.
305
-
306
- Args:
307
- from_account: Email address key in smtp-all.json (e.g. 'pro@delimit.ai').
308
-
309
- Returns:
310
- Dict with host, port, user, pass keys, or None if not found.
311
- """
312
- secrets_path = Path.home() / ".delimit" / "secrets" / "smtp-all.json"
313
- try:
314
- if not secrets_path.exists():
315
- return None
316
- with open(secrets_path, "r", encoding="utf-8") as f:
317
- accounts = json.load(f)
318
- if from_account in accounts:
319
- return accounts[from_account]
320
- return None
321
- except (OSError, json.JSONDecodeError) as e:
322
- logger.warning("Failed to load smtp-all.json: %s", e)
323
- return None
324
-
325
-
326
- def _flush_email_digest():
327
- """Send all queued non-urgent emails as a single digest."""
328
- global _email_digest_queue
329
- if not _email_digest_queue:
330
- return
331
-
332
- items = list(_email_digest_queue)
333
- _email_digest_queue.clear()
334
-
335
- digest_body = f"Delimit Notification Digest ({len(items)} items)\n{'=' * 50}\n\n"
336
- for i, item in enumerate(items, 1):
337
- digest_body += f"--- [{i}] {item.get('subject', 'No subject')} ---\n"
338
- digest_body += f"{item.get('body', '')[:500]}\n\n"
339
-
340
- # Send digest as a single email (bypasses throttle since it IS the flush)
341
- _email_send_times.append(_time.time())
342
- digest_subject = f"[DIGEST] {len(items)} Delimit notifications"
343
- timestamp = datetime.now(timezone.utc).isoformat()
344
- try:
345
- from_acct = items[0].get("from_account", "") if items else ""
346
- smtp_to = items[0].get("to", "") if items else ""
347
- if not smtp_to:
348
- defaults = _load_smtp_account("_defaults") or {}
349
- smtp_to = str(defaults.get("to") or os.environ.get("DELIMIT_SMTP_TO", ""))
350
- delivered = _send_smtp_direct(
351
- to=smtp_to,
352
- subject=digest_subject,
353
- body=digest_body,
354
- from_account=from_acct,
355
- )
356
- _record_notification({
357
- "channel": "email",
358
- "event_type": "digest",
359
- "to": smtp_to,
360
- "from": from_acct or "pro@delimit.ai",
361
- "subject": digest_subject,
362
- "message": digest_body,
363
- "timestamp": timestamp,
364
- "success": delivered,
365
- "items": len(items),
366
- })
367
- if delivered:
368
- logger.info("Flushed email digest: %d items", len(items))
369
- else:
370
- logger.warning("Digest flush failed: no SMTP recipient or SMTP send returned false")
371
- except Exception as e:
372
- logger.warning("Digest flush failed: %s", e)
373
-
374
-
375
- def _send_smtp_direct(to: str, subject: str, body: str, from_account: str = "") -> bool:
376
- """Low-level SMTP send — used by digest flush and direct sends."""
377
- if not from_account:
378
- defaults = _load_smtp_account("_defaults")
379
- if defaults and defaults.get("from_account"):
380
- from_account = str(defaults["from_account"])
381
-
382
- acct = _load_smtp_account(from_account) if from_account else None
383
- smtp_host = (acct or {}).get("host", os.environ.get("DELIMIT_SMTP_HOST", "smtp.gmail.com"))
384
- smtp_port = int((acct or {}).get("port", os.environ.get("DELIMIT_SMTP_PORT", "587")))
385
- smtp_user = (acct or {}).get("user", os.environ.get("DELIMIT_SMTP_USER", ""))
386
- smtp_pass = (acct or {}).get("pass", os.environ.get("DELIMIT_SMTP_PASS", ""))
387
- smtp_from = (acct or {}).get("from", smtp_user)
388
-
389
- if not smtp_pass:
390
- return False
391
-
392
- msg = MIMEText(body, "plain", "utf-8")
393
- msg["Subject"] = subject
394
- msg["From"] = smtp_from
395
- msg["To"] = to
396
-
397
- try:
398
- with smtplib.SMTP(smtp_host, smtp_port, timeout=15) as server:
399
- server.starttls()
400
- server.login(smtp_user, smtp_pass)
401
- server.sendmail(smtp_from, [to], msg.as_string())
402
- return True
403
- except Exception as e:
404
- logger.error("SMTP send failed: %s", e)
405
- return False
406
-
407
-
408
- def _render_html_email(subject: str, body: str, event_type: str) -> str:
409
- """Render a professional HTML email from a plain-text body.
410
-
411
- Converts markdown-like patterns to HTML:
412
- - Lines starting with "---" become <hr>
413
- - Lines with ALL CAPS become section headers
414
- - Lines starting with "- " become list items
415
- - URLs become clickable links
416
- - Draft text in quotes gets styled as blockquotes
417
- - "approve/reject" instructions get styled as action buttons
418
- """
419
- import re
420
- import html as _html
421
-
422
- # Determine accent color from event type
423
- color_map = {
424
- "social_draft": "#7C3AED", # purple — approval needed
425
- "outreach": "#7C3AED",
426
- "deploy": "#059669", # green — deploy/success
427
- "gate_failure": "#DC2626", # red — failure/alert
428
- "digest": "#2563EB", # blue — informational
429
- "info": "#2563EB",
430
- }
431
- accent = color_map.get(event_type, "#7C3AED")
432
-
433
- # Parse subject for badge
434
- badge = ""
435
- badge_match = re.match(r'\[([A-Z]+)\]', subject)
436
- if badge_match:
437
- badge = badge_match.group(1)
438
-
439
- def _render_copy_block(label: str, text: str) -> str:
440
- escaped_text = _html.escape(text.strip("\n"))
441
- escaped_label = _html.escape(label)
442
- return (
443
- f'<div style="margin:14px 0">'
444
- f'<div style="background:{accent};color:white;padding:8px 12px;'
445
- f'border-radius:8px 8px 0 0;font-size:12px;font-weight:700;letter-spacing:0.3px">'
446
- f'{escaped_label}</div>'
447
- f'<div style="border:1px solid #D1D5DB;border-top:none;border-radius:0 0 8px 8px;'
448
- f'background:#F9FAFB;padding:12px">'
449
- f'<div style="font-size:11px;color:#6B7280;margin-bottom:8px">'
450
- f'Tap and hold inside this block to copy.</div>'
451
- f'<pre style="margin:0;white-space:pre-wrap;word-break:break-word;'
452
- f'font:13px/1.55 SFMono-Regular,Consolas,Monaco,monospace;color:#111827">'
453
- f'{escaped_text}</pre>'
454
- f'</div>'
455
- f'</div>'
456
- )
457
-
458
- # Convert body lines to HTML
459
- lines = body.split("\n")
460
- html_lines = []
461
- in_list = False
462
- active_copy_label = None
463
- active_copy_lines = []
464
-
465
- for line in lines:
466
- stripped = line.strip()
467
-
468
- if stripped.startswith("--- COPY BELOW THIS LINE ---"):
469
- if in_list:
470
- html_lines.append("</ul>")
471
- in_list = False
472
- active_copy_label = "Manual Post Text"
473
- active_copy_lines = []
474
- continue
475
-
476
- if stripped.startswith("--- TITLE (paste in title field) ---"):
477
- if in_list:
478
- html_lines.append("</ul>")
479
- in_list = False
480
- active_copy_label = "Post Title"
481
- active_copy_lines = []
482
- continue
483
-
484
- if stripped.startswith("--- BODY (paste in body field) ---"):
485
- if active_copy_label and active_copy_lines:
486
- html_lines.append(_render_copy_block(active_copy_label, "\n".join(active_copy_lines)))
487
- if in_list:
488
- html_lines.append("</ul>")
489
- in_list = False
490
- active_copy_label = "Post Body"
491
- active_copy_lines = []
492
- continue
493
-
494
- if stripped.startswith("--- SOURCE POST TITLE ---"):
495
- if active_copy_label and active_copy_lines:
496
- html_lines.append(_render_copy_block(active_copy_label, "\n".join(active_copy_lines)))
497
- if in_list:
498
- html_lines.append("</ul>")
499
- in_list = False
500
- active_copy_label = "Source Post Title"
501
- active_copy_lines = []
502
- continue
503
-
504
- if stripped.startswith("--- SOURCE POST BODY ---"):
505
- if active_copy_label and active_copy_lines:
506
- html_lines.append(_render_copy_block(active_copy_label, "\n".join(active_copy_lines)))
507
- if in_list:
508
- html_lines.append("</ul>")
509
- in_list = False
510
- active_copy_label = "Source Post Body"
511
- active_copy_lines = []
512
- continue
513
-
514
- if stripped == "--- END ---" and active_copy_label is not None:
515
- html_lines.append(_render_copy_block(active_copy_label, "\n".join(active_copy_lines)))
516
- active_copy_label = None
517
- active_copy_lines = []
518
- continue
519
-
520
- if active_copy_label is not None:
521
- active_copy_lines.append(line)
522
- continue
523
-
524
- if not stripped:
525
- if in_list:
526
- html_lines.append("</ul>")
527
- in_list = False
528
- html_lines.append("<br>")
529
- continue
530
-
531
- # Draft block headers: "--- Draft <id> (platform) ---"
532
- if stripped.startswith("--- Draft ") and stripped.endswith("---"):
533
- if in_list:
534
- html_lines.append("</ul>")
535
- in_list = False
536
- draft_label = _html.escape(stripped.strip("- ").strip())
537
- html_lines.append(
538
- f'<div style="background:{accent};color:white;padding:8px 14px;'
539
- f'border-radius:6px 6px 0 0;margin-top:16px;font-size:13px;font-weight:700">'
540
- f'{draft_label}</div>'
541
- f'<div style="background:#F9FAFB;border:1px solid #E5E7EB;border-top:none;'
542
- f'border-radius:0 0 6px 6px;padding:12px 14px;margin-bottom:4px">'
543
- )
544
- # The next lines until the next "---" or "To approve" will be inside this box
545
- # We'll close it when we hit the next separator
546
- continue
547
-
548
- # Horizontal rules / separators
549
- if stripped.startswith("---") or stripped.startswith("==="):
550
- if in_list:
551
- html_lines.append("</ul>")
552
- in_list = False
553
- # Close any open draft box
554
- html_lines.append('</div>')
555
- html_lines.append(f'<hr style="border:none;border-top:1px solid #E5E7EB;margin:16px 0">')
556
- continue
557
-
558
- # Section headers (ALL CAPS lines or lines ending with colon that are short)
559
- if (stripped.isupper() and len(stripped) > 3 and len(stripped) < 60) or \
560
- (stripped.endswith(":") and len(stripped) < 50 and stripped[:-1].replace(" ", "").replace("-", "").isalpha()):
561
- if in_list:
562
- html_lines.append("</ul>")
563
- in_list = False
564
- html_lines.append(
565
- f'<h3 style="color:{accent};font-size:13px;font-weight:700;'
566
- f'text-transform:uppercase;letter-spacing:0.5px;margin:20px 0 8px 0;'
567
- f'border-bottom:2px solid {accent};padding-bottom:4px">'
568
- f'{_html.escape(stripped)}</h3>'
569
- )
570
- continue
571
-
572
- # List items
573
- if stripped.startswith("- ") or stripped.startswith("* "):
574
- if not in_list:
575
- html_lines.append('<ul style="margin:4px 0;padding-left:20px">')
576
- in_list = True
577
- item = _html.escape(stripped[2:])
578
- # Bold draft IDs
579
- item = re.sub(r'([0-9a-f]{12})', r'<code style="background:#F3F4F6;padding:1px 4px;border-radius:3px;font-size:12px">\1</code>', item)
580
- html_lines.append(f'<li style="margin:4px 0;color:#374151">{item}</li>')
581
- continue
582
-
583
- if in_list:
584
- html_lines.append("</ul>")
585
- in_list = False
586
-
587
- escaped = _html.escape(stripped)
588
-
589
- # Convert URLs to clickable links
590
- escaped = re.sub(
591
- r'(https?://[^\s<>&"]+)',
592
- r'<a href="\1" style="color:{};text-decoration:underline">\1</a>'.format(accent),
593
- escaped,
594
- )
595
-
596
- # Style quoted draft text
597
- if escaped.startswith('"') and escaped.endswith('"'):
598
- html_lines.append(
599
- f'<blockquote style="border-left:3px solid {accent};margin:8px 0;'
600
- f'padding:8px 12px;background:#F9FAFB;color:#374151;font-style:italic">'
601
- f'{escaped}</blockquote>'
602
- )
603
- continue
604
-
605
- # Style approve/reject instructions as action callouts
606
- if any(kw in stripped.lower() for kw in ("to approve", "reply with", "reply \"approve")):
607
- html_lines.append(
608
- f'<div style="background:#F0FDF4;border:1px solid #BBF7D0;border-radius:6px;'
609
- f'padding:10px 14px;margin:12px 0;font-weight:600;color:#166534">'
610
- f'{escaped}</div>'
611
- )
612
- continue
613
-
614
- if any(kw in stripped.lower() for kw in ("to reject", "reply \"reject")):
615
- html_lines.append(
616
- f'<div style="background:#FEF2F2;border:1px solid #FECACA;border-radius:6px;'
617
- f'padding:10px 14px;margin:12px 0;color:#991B1B">'
618
- f'{escaped}</div>'
619
- )
620
- continue
621
-
622
- # Protocol warnings
623
- if "PROTOCOL WARNING" in stripped:
624
- html_lines.append(
625
- f'<div style="background:#FEF3C7;border:1px solid #FDE68A;border-radius:6px;'
626
- f'padding:10px 14px;margin:12px 0;color:#92400E;font-size:12px">'
627
- f'{escaped}</div>'
628
- )
629
- continue
630
-
631
- # Regular paragraph
632
- html_lines.append(f'<p style="margin:6px 0;color:#374151;line-height:1.5">{escaped}</p>')
633
-
634
- if in_list:
635
- html_lines.append("</ul>")
636
-
637
- body_html = "\n".join(html_lines)
638
-
639
- # Build full HTML email
640
- badge_html = ""
641
- if badge:
642
- badge_colors = {
643
- "APPROVE": ("#7C3AED", "#EDE9FE"),
644
- "ACTION": ("#D97706", "#FEF3C7"),
645
- "ALERT": ("#DC2626", "#FEE2E2"),
646
- "URGENT": ("#DC2626", "#FEE2E2"),
647
- "GATE": ("#DC2626", "#FEE2E2"),
648
- "DIGEST": ("#2563EB", "#DBEAFE"),
649
- "INFO": ("#6B7280", "#F3F4F6"),
650
- "OUTREACH": ("#7C3AED", "#EDE9FE"),
651
- "DEPLOY": ("#059669", "#D1FAE5"),
652
- }
653
- fg, bg = badge_colors.get(badge, ("#6B7280", "#F3F4F6"))
654
- badge_html = (
655
- f'<span style="display:inline-block;background:{bg};color:{fg};'
656
- f'font-size:11px;font-weight:700;padding:2px 8px;border-radius:4px;'
657
- f'letter-spacing:0.5px;margin-bottom:8px">{badge}</span><br>'
658
- )
659
-
660
- # Clean subject for display (remove bracket prefix)
661
- display_subject = re.sub(r'^\[[A-Z]+\]\s*', '', subject)
662
-
663
- return f"""<!DOCTYPE html>
664
- <html>
665
- <head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"></head>
666
- <body style="margin:0;padding:0;background:#F9FAFB;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif">
667
- <table width="100%" cellpadding="0" cellspacing="0" style="background:#F9FAFB;padding:20px 0">
668
- <tr><td align="center">
669
- <table width="600" cellpadding="0" cellspacing="0" style="background:#FFFFFF;border-radius:8px;box-shadow:0 1px 3px rgba(0,0,0,0.1);overflow:hidden">
670
-
671
- <!-- Header bar -->
672
- <tr><td style="background:{accent};padding:16px 24px">
673
- <table width="100%" cellpadding="0" cellspacing="0"><tr>
674
- <td><span style="color:white;font-size:14px;font-weight:700;letter-spacing:0.5px">DELIMIT</span></td>
675
- <td align="right"><span style="color:rgba(255,255,255,0.8);font-size:11px">{event_type or 'notification'}</span></td>
676
- </tr></table>
677
- </td></tr>
678
-
679
- <!-- Body -->
680
- <tr><td style="padding:24px">
681
- {badge_html}
682
- <h2 style="margin:0 0 16px 0;color:#111827;font-size:18px;font-weight:600;line-height:1.3">{_html.escape(display_subject)}</h2>
683
- {body_html}
684
- </td></tr>
685
-
686
- <!-- Footer -->
687
- <tr><td style="background:#F9FAFB;padding:12px 24px;border-top:1px solid #E5E7EB">
688
- <table width="100%" cellpadding="0" cellspacing="0"><tr>
689
- <td><span style="color:#9CA3AF;font-size:11px">Sent by Delimit governance layer</span></td>
690
- <td align="right"><a href="https://delimit.ai" style="color:#9CA3AF;font-size:11px;text-decoration:none">delimit.ai</a></td>
691
- </tr></table>
692
- </td></tr>
693
-
694
- </table>
695
- </td></tr>
696
- </table>
697
- </body>
698
- </html>"""
699
-
700
-
701
- def send_email(
702
- to: str = "",
703
- subject: str = "",
704
- body: str = "",
705
- from_account: str = "",
706
- message: str = "",
707
- event_type: str = "",
708
- ) -> Dict[str, Any]:
709
- """Send an email notification via SMTP.
710
-
711
- Args:
712
- to: Recipient email address. Falls back to DELIMIT_SMTP_TO or
713
- owner@example.com.
714
- subject: Email subject line.
715
- body: Email body text (preferred). Falls back to 'message' for
716
- backward compatibility.
717
- from_account: Sender account key in ~/.delimit/secrets/smtp-all.json
718
- (e.g. 'pro@delimit.ai', 'admin@wire.report'). If provided, SMTP
719
- credentials are loaded from that file instead of env vars.
720
- message: Email body text (legacy parameter, use 'body' instead).
721
- event_type: Event category for filtering/logging.
722
-
723
- Credential resolution order:
724
- 1. from_account lookup in ~/.delimit/secrets/smtp-all.json
725
- 2. DELIMIT_SMTP_* environment variables
726
- """
727
- # body takes precedence, fall back to message for backward compat
728
- email_body = body or message
729
-
730
- timestamp = datetime.now(timezone.utc).isoformat()
731
- event_key = (event_type or "").lower()
732
- force_digest = event_key in ("social_draft", "outreach")
733
-
734
- # ── Throttle: batch non-urgent, always send P0/immediate ──
735
- is_urgent = (not force_digest) and any(tag in event_key + (subject or "").lower()
736
- for tag in ("p0", "urgent", "alert", "critical", "social_draft", "approve",
737
- "founder_directive", "gate_failure"))
738
-
739
- global _last_digest_flush
740
- with _email_throttle_lock:
741
- now = _time.time()
742
- # Prune sends older than 1 hour
743
- _email_send_times[:] = [t for t in _email_send_times if now - t < 3600]
744
-
745
- if force_digest or (not is_urgent and len(_email_send_times) >= _EMAIL_MAX_PER_HOUR):
746
- # Queue for digest instead of sending immediately
747
- _email_digest_queue.append({
748
- "to": to, "subject": subject, "body": email_body,
749
- "from_account": from_account, "event_type": event_type,
750
- "timestamp": timestamp,
751
- })
752
- # Flush digest every 15 minutes
753
- if now - _last_digest_flush >= _EMAIL_DIGEST_INTERVAL and _email_digest_queue:
754
- _flush_email_digest()
755
- _last_digest_flush = now
756
- return {
757
- "channel": "email",
758
- "delivered": False,
759
- "queued": True,
760
- "reason": "Batched for digest." if force_digest else f"Throttled ({len(_email_send_times)}/{_EMAIL_MAX_PER_HOUR} per hour). Batched for digest.",
761
- "queue_size": len(_email_digest_queue),
762
- "timestamp": timestamp,
763
- }
764
- _email_send_times.append(now)
765
-
766
- # Try from_account first, then _defaults, then fall back to env vars
767
- if not from_account:
768
- defaults = _load_smtp_account("_defaults")
769
- if defaults and defaults.get("from_account"):
770
- from_account = defaults["from_account"]
771
- account_creds = _load_smtp_account(from_account) if from_account else None
772
-
773
- if account_creds:
774
- smtp_host = account_creds.get("host", "")
775
- smtp_port = int(account_creds.get("port", 587))
776
- smtp_user = account_creds.get("user", "")
777
- smtp_pass = account_creds.get("pass", "")
778
- smtp_from = account_creds.get("from_alias", from_account)
779
- else:
780
- smtp_host = os.environ.get("DELIMIT_SMTP_HOST", "")
781
- smtp_port = int(os.environ.get("DELIMIT_SMTP_PORT", "587"))
782
- smtp_user = os.environ.get("DELIMIT_SMTP_USER", "")
783
- smtp_pass = os.environ.get("DELIMIT_SMTP_PASS", "")
784
- smtp_from = os.environ.get("DELIMIT_SMTP_FROM", "")
785
-
786
- # Resolve recipient: explicit > env var > smtp-all.json _defaults
787
- smtp_to = to or os.environ.get("DELIMIT_SMTP_TO", "")
788
- if not smtp_to:
789
- defaults = _load_smtp_account("_defaults")
790
- if defaults:
791
- smtp_to = defaults.get("to", "")
792
-
793
- if not all([smtp_host, smtp_from, smtp_to]):
794
- record = {
795
- "channel": "email",
796
- "event_type": event_type,
797
- "to": smtp_to,
798
- "from": smtp_from,
799
- "message": email_body,
800
- "subject": subject,
801
- "timestamp": timestamp,
802
- "success": False,
803
- "reason": "smtp_not_configured",
804
- }
805
- _record_notification(record)
806
- return {
807
- "channel": "email",
808
- "delivered": False,
809
- "timestamp": timestamp,
810
- "error": "SMTP not configured. Set DELIMIT_SMTP_HOST, DELIMIT_SMTP_FROM, DELIMIT_SMTP_TO environment variables, or use from_account with smtp-all.json.",
811
- "intent_logged": True,
812
- }
813
-
814
- subj = subject or f"Delimit: {event_type or 'Notification'}"
815
- html_body = _render_html_email(subj, email_body, event_type)
816
- msg = MIMEText(html_body, "html")
817
- msg["Subject"] = subj
818
- msg["From"] = smtp_from
819
- msg["To"] = smtp_to
820
-
821
- # Generate a unique Message-ID for threading support (Consensus 116)
822
- import uuid as _uuid
823
- domain = smtp_from.split("@", 1)[1] if "@" in smtp_from else "delimit.ai"
824
- message_id = f"<{_uuid.uuid4().hex}@{domain}>"
825
- msg["Message-ID"] = message_id
826
-
827
- try:
828
- with smtplib.SMTP(smtp_host, smtp_port, timeout=10) as server:
829
- if smtp_user and smtp_pass:
830
- server.starttls()
831
- server.login(smtp_user, smtp_pass)
832
- server.sendmail(smtp_from, [smtp_to], msg.as_string())
833
-
834
- record = {
835
- "channel": "email",
836
- "event_type": event_type,
837
- "to": smtp_to,
838
- "from": smtp_from,
839
- "subject": subj,
840
- "message": email_body,
841
- "timestamp": timestamp,
842
- "success": True,
843
- "message_id": message_id,
844
- }
845
- _record_notification(record)
846
-
847
- return {
848
- "channel": "email",
849
- "delivered": True,
850
- "timestamp": timestamp,
851
- "subject": subj,
852
- "to": smtp_to,
853
- "from": smtp_from,
854
- "message_id": message_id,
855
- }
856
- except Exception as e:
857
- record = {
858
- "channel": "email",
859
- "event_type": event_type,
860
- "to": smtp_to,
861
- "from": smtp_from,
862
- "message": email_body,
863
- "timestamp": timestamp,
864
- "success": False,
865
- "error": str(e),
866
- }
867
- _record_notification(record)
868
- return {
869
- "channel": "email",
870
- "delivered": False,
871
- "timestamp": timestamp,
872
- "error": str(e),
873
- }
874
-
875
-
876
- # ═════════════════════════════════════════════════════════════════════
877
- # Email Protocol — enforced server-side, model-agnostic
878
- # ═════════════════════════════════════════════════════════════════════
879
- # Every email must be self-contained and actionable on mobile.
880
- # The protocol validates required sections per event_type and rejects
881
- # or fixes emails that don't meet the standard.
882
-
883
- # Subject line MUST start with one of these brackets:
884
- _VALID_SUBJECT_PREFIXES = (
885
- "[APPROVE]", "[ACTION]", "[INFO]", "[ALERT]", "[DIGEST]",
886
- "[URGENT]", "[OUTREACH]", "[DEPLOY]", "[GATE]",
887
- )
888
-
889
- # Required sections per event_type. Each is a (header, description) tuple.
890
- _EMAIL_PROTOCOL: Dict[str, List[tuple]] = {
891
- "social_draft": [
892
- ("THREAD CONTEXT", "subreddit/platform, post topic, engagement stats"),
893
- ("DRAFT", "the full draft text, not just an ID"),
894
- ("TO APPROVE", "reply instructions with draft_id"),
895
- ],
896
- "outreach": [
897
- ("TARGETS FOUND", "list with platform, title/snippet, URL"),
898
- ("DRAFTS", "full draft text for each, with draft_id"),
899
- ("TO APPROVE", "reply instructions"),
900
- ],
901
- "deploy": [
902
- ("WHAT CHANGED", "summary of changes being deployed"),
903
- ("GATES PASSED", "test, security, lint results"),
904
- ("TO APPROVE", "reply instructions or auto-proceed note"),
905
- ],
906
- "gate_failure": [
907
- ("WHAT FAILED", "which gate and why"),
908
- ("IMPACT", "what is blocked"),
909
- ("TO FIX", "next steps"),
910
- ],
911
- "digest": [
912
- ("COMPLETED", "what was done since last digest"),
913
- ("PENDING YOUR ACTION", "items needing founder response"),
914
- ],
915
- }
916
-
917
-
918
- def _load_drafts_by_ids(draft_ids: list) -> list:
919
- """Load draft entries from social_drafts.jsonl matching the given IDs."""
920
- drafts_file = Path.home() / ".delimit" / "social_drafts.jsonl"
921
- if not drafts_file.exists():
922
- return []
923
- results = []
924
- id_set = set(draft_ids)
925
- try:
926
- for line in drafts_file.read_text().splitlines():
927
- if not line.strip():
928
- continue
929
- try:
930
- d = json.loads(line)
931
- if d.get("draft_id") in id_set and d.get("status") == "pending":
932
- results.append(d)
933
- except (json.JSONDecodeError, ValueError):
934
- continue
935
- except Exception:
936
- pass
937
- return results
938
-
939
-
940
- def _enforce_email_protocol(subject: str, message: str, event_type: str) -> tuple:
941
- """Validate and fix email against the protocol. Returns (subject, message, warnings)."""
942
- warnings = []
943
-
944
- # 1. Subject must have a valid prefix bracket
945
- if not any(subject.startswith(p) for p in _VALID_SUBJECT_PREFIXES):
946
- # Try to infer from event_type
947
- prefix_map = {
948
- "social_draft": "[APPROVE]",
949
- "outreach": "[OUTREACH]",
950
- "deploy": "[DEPLOY]",
951
- "gate_failure": "[ALERT]",
952
- "digest": "[DIGEST]",
953
- "info": "[INFO]",
954
- }
955
- prefix = prefix_map.get(event_type, "[INFO]")
956
- subject = f"{prefix} {subject}"
957
- warnings.append(f"Subject prefix added: {prefix}")
958
-
959
- # 2. Check required sections for this event_type
960
- required = _EMAIL_PROTOCOL.get(event_type, [])
961
- msg_upper = message.upper()
962
- missing = []
963
- for header, desc in required:
964
- # Check if the section header appears (case-insensitive, with or without colon)
965
- if header.upper() not in msg_upper:
966
- missing.append(f"{header} ({desc})")
967
-
968
- if missing:
969
- # Append a protocol warning to the email body so the founder sees what's missing
970
- message += "\n\n" + "=" * 40
971
- message += "\nPROTOCOL WARNING — Missing required sections:"
972
- for m in missing:
973
- message += f"\n - {m}"
974
- message += "\n\nThis email may not be fully actionable. The sending model"
975
- message += "\nskipped required context. Check drafts via delimit_social_approve."
976
- warnings.append(f"Missing sections: {', '.join(m.split(' (')[0] for m in missing)}")
977
-
978
- # 3. Outreach/social_draft emails — auto-inject full draft text from social_drafts.jsonl
979
- if event_type in ("social_draft", "outreach"):
980
- import re
981
- draft_ids = re.findall(r'[0-9a-f]{12}', message)
982
- if draft_ids:
983
- drafts = _load_drafts_by_ids(draft_ids)
984
- if drafts:
985
- message += "\n\n" + "=" * 40
986
- message += "\nCOPY-READY DRAFTS"
987
- message += "\n" + "=" * 40
988
- for d in drafts:
989
- did = d.get("draft_id", "")
990
- text = d.get("text", "")
991
- platform = d.get("platform", "")
992
- ctx = d.get("context", "")
993
- thread_url = d.get("thread_url", "")
994
- reply_to_id = d.get("reply_to_id", "")
995
- # Try to extract URL from context if thread_url is empty
996
- if not thread_url and ctx:
997
- url_match = re.search(r'https?://[^\s]+', ctx)
998
- if url_match:
999
- thread_url = url_match.group(0)
1000
- message += f"\n\n--- Draft {did} ({platform}) ---"
1001
- message += f"\nWHERE: {platform}"
1002
- where_link = thread_url or (f"https://x.com/i/status/{reply_to_id}" if reply_to_id else "")
1003
- if where_link:
1004
- message += f"\nLINK: {where_link}"
1005
- if ctx:
1006
- message += f"\nWHY: {ctx}"
1007
- message += f"\nWHAT:\nManual Post Text\n{text}"
1008
- message += f"\n\nTo approve: reply \"approve {did}\""
1009
- message += "\n\n" + "=" * 40
1010
- warnings.append(f"Auto-injected {len(drafts)} draft texts from social_drafts.jsonl")
1011
-
1012
- # 4. Always append the standard footer
1013
- if "delimit.ai" not in message.lower() and "Delimit" not in message:
1014
- message += "\n\n---\nSent by Delimit governance layer"
1015
-
1016
- return subject, message, warnings
1017
-
1018
-
1019
- def send_notification(
1020
- channel: str = "webhook",
1021
- message: str = "",
1022
- webhook_url: str = "",
1023
- subject: str = "",
1024
- event_type: str = "",
1025
- to: str = "",
1026
- from_account: str = "",
1027
- ) -> Dict[str, Any]:
1028
- """Route a notification to the appropriate channel."""
1029
- if not message:
1030
- return {"error": "message is required"}
1031
-
1032
- # Enforce email protocol for all email notifications
1033
- protocol_warnings = []
1034
- if channel == "email":
1035
- subject, message, protocol_warnings = _enforce_email_protocol(subject, message, event_type)
1036
-
1037
- if channel == "webhook":
1038
- return send_webhook(webhook_url, message, event_type)
1039
- elif channel == "slack":
1040
- return send_slack(webhook_url, message, event_type)
1041
- elif channel == "email":
1042
- result = send_email(
1043
- to=to,
1044
- subject=subject,
1045
- message=message,
1046
- from_account=from_account,
1047
- event_type=event_type,
1048
- )
1049
- if protocol_warnings:
1050
- result["protocol_warnings"] = protocol_warnings
1051
- return result
1052
- elif channel == "telegram":
1053
- return send_telegram(message=message, event_type=event_type)
1054
- else:
1055
- return {"error": f"Unknown channel: {channel}. Supported: webhook, slack, email, telegram"}
1056
-
1057
-
1058
- # ═════════════════════════════════════════════════════════════════════
1059
- # LED-233: Impact-Based Notification Routing
1060
- # ═════════════════════════════════════════════════════════════════════
1061
-
1062
- ROUTING_CONFIG_FILE = Path.home() / ".delimit" / "notify_routing.yaml"
1063
-
1064
- # Severity aliases — map various input labels to canonical levels
1065
- _SEVERITY_ALIASES: Dict[str, str] = {
1066
- "critical": "critical",
1067
- "breaking": "critical",
1068
- "error": "critical",
1069
- "major": "critical",
1070
- "warning": "warning",
1071
- "non-breaking": "warning",
1072
- "minor": "warning",
1073
- "info": "info",
1074
- "cosmetic": "info",
1075
- "docs": "info",
1076
- "patch": "info",
1077
- "none": "info",
1078
- }
1079
-
1080
- DEFAULT_ROUTING_CONFIG: Dict[str, Any] = {
1081
- "routing": {
1082
- "critical": {
1083
- "channels": ["email", "webhook"],
1084
- "email_subject_prefix": "[URGENT]",
1085
- "webhook_priority": "high",
1086
- },
1087
- "warning": {
1088
- "channels": ["webhook"],
1089
- "webhook_priority": "normal",
1090
- },
1091
- "info": {
1092
- "channels": [],
1093
- "digest": True,
1094
- },
1095
- },
1096
- }
1097
-
1098
-
1099
- def load_routing_config() -> Dict[str, Any]:
1100
- """Load routing config from ~/.delimit/notify_routing.yaml or return defaults.
1101
-
1102
- Returns:
1103
- The routing configuration dict with a 'routing' key.
1104
- """
1105
- if ROUTING_CONFIG_FILE.exists():
1106
- try:
1107
- if _yaml is not None:
1108
- with open(ROUTING_CONFIG_FILE, "r", encoding="utf-8") as f:
1109
- config = _yaml.safe_load(f)
1110
- if isinstance(config, dict) and "routing" in config:
1111
- return config
1112
- else:
1113
- # Fallback: try JSON (yaml not installed)
1114
- with open(ROUTING_CONFIG_FILE, "r", encoding="utf-8") as f:
1115
- config = json.load(f)
1116
- if isinstance(config, dict) and "routing" in config:
1117
- return config
1118
- except Exception as e:
1119
- logger.warning("Failed to load routing config from %s: %s", ROUTING_CONFIG_FILE, e)
1120
- return DEFAULT_ROUTING_CONFIG
1121
-
1122
-
1123
- def save_routing_config(config: Dict[str, Any]) -> Dict[str, Any]:
1124
- """Save routing config to ~/.delimit/notify_routing.yaml.
1125
-
1126
- Args:
1127
- config: Full routing config dict (must contain 'routing' key).
1128
-
1129
- Returns:
1130
- Status dict with success/error.
1131
- """
1132
- if "routing" not in config:
1133
- return {"error": "Config must contain a 'routing' key."}
1134
- try:
1135
- ROUTING_CONFIG_FILE.parent.mkdir(parents=True, exist_ok=True)
1136
- if _yaml is not None:
1137
- with open(ROUTING_CONFIG_FILE, "w", encoding="utf-8") as f:
1138
- _yaml.dump(config, f, default_flow_style=False)
1139
- else:
1140
- with open(ROUTING_CONFIG_FILE, "w", encoding="utf-8") as f:
1141
- json.dump(config, f, indent=2)
1142
- return {"success": True, "path": str(ROUTING_CONFIG_FILE)}
1143
- except Exception as e:
1144
- return {"error": f"Failed to save routing config: {e}"}
1145
-
1146
-
1147
- def _classify_severity(change: Dict[str, Any]) -> str:
1148
- """Map a single change dict to a canonical severity level (critical/warning/info).
1149
-
1150
- Inspects these keys in order:
1151
- - 'severity' (from lint violations)
1152
- - 'is_breaking' (from diff changes)
1153
- - 'type' (change type string)
1154
- """
1155
- # Direct severity label
1156
- sev = str(change.get("severity", "")).lower()
1157
- if sev in _SEVERITY_ALIASES:
1158
- return _SEVERITY_ALIASES[sev]
1159
-
1160
- # Breaking flag from diff engine
1161
- if change.get("is_breaking"):
1162
- return "critical"
1163
-
1164
- # Change type heuristic
1165
- ctype = str(change.get("type", "")).lower()
1166
- if "removed" in ctype or "breaking" in ctype:
1167
- return "critical"
1168
- if "added" in ctype or "changed" in ctype:
1169
- return "warning"
1170
-
1171
- return "info"
1172
-
1173
-
1174
- def route_by_impact(
1175
- changes: List[Dict[str, Any]],
1176
- routing_config: Optional[Dict[str, Any]] = None,
1177
- webhook_url: str = "",
1178
- email_to: str = "",
1179
- from_account: str = "",
1180
- dry_run: bool = False,
1181
- ) -> Dict[str, Any]:
1182
- """Route notifications based on change severity.
1183
-
1184
- Takes a list of changes (from lint/diff output) and sends notifications
1185
- to the appropriate channels based on severity classification.
1186
-
1187
- Args:
1188
- changes: List of change dicts (from lint violations or diff changes).
1189
- routing_config: Custom routing config. Uses saved/default if None.
1190
- webhook_url: Webhook URL for webhook channel delivery.
1191
- email_to: Email recipient for email channel delivery.
1192
- from_account: Sender account key for email delivery.
1193
- dry_run: If True, classify and plan routing but do not send.
1194
-
1195
- Returns:
1196
- Dict with routing decisions and delivery results.
1197
- """
1198
- if not changes:
1199
- return {
1200
- "routed": 0,
1201
- "suppressed": 0,
1202
- "decisions": [],
1203
- "notifications_sent": [],
1204
- }
1205
-
1206
- config = routing_config or load_routing_config()
1207
- routing_rules = config.get("routing", {})
1208
- timestamp = datetime.now(timezone.utc).isoformat()
1209
-
1210
- # Classify all changes by severity
1211
- buckets: Dict[str, List[Dict[str, Any]]] = {
1212
- "critical": [],
1213
- "warning": [],
1214
- "info": [],
1215
- }
1216
- for change in changes:
1217
- severity = _classify_severity(change)
1218
- buckets[severity].append(change)
1219
-
1220
- decisions: List[Dict[str, Any]] = []
1221
- notifications_sent: List[Dict[str, Any]] = []
1222
- suppressed_count = 0
1223
-
1224
- for severity, items in buckets.items():
1225
- if not items:
1226
- continue
1227
-
1228
- rule = routing_rules.get(severity, {})
1229
- channels = rule.get("channels", [])
1230
- is_digest = rule.get("digest", False)
1231
-
1232
- if not channels:
1233
- # Suppressed (or digest-only)
1234
- suppressed_count += len(items)
1235
- decisions.append({
1236
- "severity": severity,
1237
- "count": len(items),
1238
- "action": "digest" if is_digest else "suppressed",
1239
- "channels": [],
1240
- })
1241
- continue
1242
-
1243
- # Build notification message for this severity bucket
1244
- subject_prefix = rule.get("email_subject_prefix", "")
1245
- webhook_priority = rule.get("webhook_priority", "normal")
1246
-
1247
- summary_lines = [f"{len(items)} {severity} change(s) detected:"]
1248
- for item in items[:10]: # Cap detail lines at 10
1249
- msg = item.get("message", item.get("name", item.get("type", "change")))
1250
- path = item.get("path", "")
1251
- summary_lines.append(f" - {msg}" + (f" ({path})" if path else ""))
1252
- if len(items) > 10:
1253
- summary_lines.append(f" ... and {len(items) - 10} more")
1254
- message_body = "\n".join(summary_lines)
1255
-
1256
- decision = {
1257
- "severity": severity,
1258
- "count": len(items),
1259
- "action": "notify",
1260
- "channels": list(channels),
1261
- }
1262
- decisions.append(decision)
1263
-
1264
- if dry_run:
1265
- continue
1266
-
1267
- # Send to each configured channel
1268
- for channel in channels:
1269
- if channel == "email":
1270
- subject = f"{subject_prefix} Delimit: {severity} API changes".strip()
1271
- result = send_email(
1272
- to=email_to,
1273
- subject=subject,
1274
- body=message_body,
1275
- from_account=from_account,
1276
- event_type=f"impact_routing_{severity}",
1277
- )
1278
- notifications_sent.append({
1279
- "channel": "email",
1280
- "severity": severity,
1281
- "delivered": result.get("delivered", False),
1282
- "error": result.get("error"),
1283
- })
1284
- elif channel == "webhook" and webhook_url:
1285
- # Inject priority into the webhook payload
1286
- payload = {
1287
- "event_type": f"delimit_impact_{severity}",
1288
- "message": message_body,
1289
- "priority": webhook_priority,
1290
- "severity": severity,
1291
- "change_count": len(items),
1292
- "timestamp": timestamp,
1293
- }
1294
- post_result = _post_json(webhook_url, payload)
1295
- _record_notification({
1296
- "channel": "webhook",
1297
- "event_type": f"impact_routing_{severity}",
1298
- "message": message_body,
1299
- "webhook_url": webhook_url,
1300
- "priority": webhook_priority,
1301
- "timestamp": timestamp,
1302
- "success": post_result.get("success", False),
1303
- })
1304
- notifications_sent.append({
1305
- "channel": "webhook",
1306
- "severity": severity,
1307
- "priority": webhook_priority,
1308
- "delivered": post_result.get("success", False),
1309
- "error": post_result.get("error"),
1310
- })
1311
- elif channel == "slack" and webhook_url:
1312
- result = send_slack(webhook_url, message_body, f"impact_{severity}")
1313
- notifications_sent.append({
1314
- "channel": "slack",
1315
- "severity": severity,
1316
- "delivered": result.get("delivered", False),
1317
- "error": result.get("error"),
1318
- })
1319
-
1320
- return {
1321
- "routed": sum(d["count"] for d in decisions if d["action"] == "notify"),
1322
- "suppressed": suppressed_count,
1323
- "decisions": decisions,
1324
- "notifications_sent": notifications_sent,
1325
- "timestamp": timestamp,
1326
- "dry_run": dry_run,
1327
- }
1328
-
1329
-
1330
- # ═════════════════════════════════════════════════════════════════════
1331
- # INBOUND EMAIL: IMAP polling, classification, and forwarding
1332
- # ═════════════════════════════════════════════════════════════════════
1333
-
1334
- def _record_inbox_routing(entry: Dict[str, Any]) -> None:
1335
- """Append a routing record to the inbox routing log."""
1336
- try:
1337
- INBOX_ROUTING_FILE.parent.mkdir(parents=True, exist_ok=True)
1338
- with open(INBOX_ROUTING_FILE, "a", encoding="utf-8") as f:
1339
- f.write(json.dumps(entry) + "\n")
1340
- except OSError as e:
1341
- logger.warning("Failed to record inbox routing: %s", e)
1342
-
1343
-
1344
- def _decode_header(raw: str) -> str:
1345
- """Decode an RFC 2047 encoded email header into a plain string."""
1346
- if not raw:
1347
- return ""
1348
- parts = email.header.decode_header(raw)
1349
- decoded = []
1350
- for data, charset in parts:
1351
- if isinstance(data, bytes):
1352
- decoded.append(data.decode(charset or "utf-8", errors="replace"))
1353
- else:
1354
- decoded.append(data)
1355
- return " ".join(decoded)
1356
-
1357
-
1358
- def _extract_sender_email(from_header: str) -> str:
1359
- """Extract the bare email address from a From header."""
1360
- _, addr = email.utils.parseaddr(from_header)
1361
- return addr.lower()
1362
-
1363
-
1364
- def _extract_sender_domain(sender_email: str) -> str:
1365
- """Extract domain from an email address."""
1366
- if "@" in sender_email:
1367
- return sender_email.split("@", 1)[1]
1368
- return ""
1369
-
1370
-
1371
- def classify_email(sender: str, subject: str, from_header: str = "") -> str:
1372
- """Classify an email as 'owner-action' or 'non-owner'.
1373
-
1374
- Returns:
1375
- 'owner-action' if the email needs owner attention.
1376
- 'non-owner' if it can stay in the Delimit inbox.
1377
- """
1378
- sender_lower = sender.lower()
1379
- sender_domain = _extract_sender_domain(sender_lower)
1380
-
1381
- # Rule 1: from the owner directly
1382
- if sender_lower in OWNER_ACTION_SENDERS:
1383
- return "owner-action"
1384
-
1385
- # Rule 2: from a known vendor/partner domain
1386
- if sender_domain in OWNER_ACTION_DOMAINS:
1387
- return "owner-action"
1388
-
1389
- # Rule 3: subject matches owner-action patterns
1390
- for pattern in OWNER_ACTION_SUBJECT_PATTERNS:
1391
- if pattern.search(subject):
1392
- return "owner-action"
1393
-
1394
- # Rule 4: if sender looks like a real person (not noreply), lean owner-action
1395
- # Only if from_header has a display name that looks personal
1396
- is_noreply = any(sender_lower.startswith(prefix) for prefix in NON_OWNER_SENDERS)
1397
- if not is_noreply and sender_domain and sender_domain not in ("pypi.org",):
1398
- # Check if subject indicates automated content
1399
- automated_keywords = ["unsubscribe", "newsletter", "digest", "weekly roundup",
1400
- "notification", "alert", "automated", "receipt"]
1401
- subject_lower = subject.lower()
1402
- if any(kw in subject_lower for kw in automated_keywords):
1403
- return "non-owner"
1404
- # Personal email from unknown domain - forward to be safe
1405
- return "owner-action"
1406
-
1407
- return "non-owner"
1408
-
1409
-
1410
- def _forward_email(original_msg: email.message.Message, smtp_pass: str) -> bool:
1411
- """Forward an email to the owner via SMTP."""
1412
- subject = _decode_header(original_msg.get("Subject", ""))
1413
- from_header = original_msg.get("From", "")
1414
-
1415
- # Build forwarded message
1416
- body_parts = []
1417
- if original_msg.is_multipart():
1418
- for part in original_msg.walk():
1419
- if part.get_content_type() == "text/plain":
1420
- payload = part.get_payload(decode=True)
1421
- if payload:
1422
- body_parts.append(payload.decode("utf-8", errors="replace"))
1423
- else:
1424
- payload = original_msg.get_payload(decode=True)
1425
- if payload:
1426
- body_parts.append(payload.decode("utf-8", errors="replace"))
1427
-
1428
- body = "\n".join(body_parts) if body_parts else "(no text content)"
1429
-
1430
- fwd_text = (
1431
- f"--- Forwarded from pro@delimit.ai ---\n"
1432
- f"From: {from_header}\n"
1433
- f"Subject: {subject}\n"
1434
- f"Date: {original_msg.get('Date', 'unknown')}\n"
1435
- f"---\n\n"
1436
- f"{body}"
1437
- )
1438
-
1439
- fwd_msg = MIMEText(fwd_text)
1440
- fwd_msg["Subject"] = f"[Fwd] {subject}"
1441
- fwd_msg["From"] = IMAP_USER
1442
- fwd_msg["To"] = FORWARD_TO
1443
-
1444
- try:
1445
- with smtplib.SMTP(IMAP_HOST, 587, timeout=10) as server:
1446
- server.starttls()
1447
- server.login(IMAP_USER, smtp_pass)
1448
- server.sendmail(IMAP_USER, [FORWARD_TO], fwd_msg.as_string())
1449
- return True
1450
- except Exception as e:
1451
- logger.error("Failed to forward email: %s", e)
1452
- return False
1453
-
1454
-
1455
- def poll_inbox(
1456
- smtp_pass: str = "",
1457
- limit: int = 20,
1458
- process: bool = True,
1459
- ) -> Dict[str, Any]:
1460
- """Poll the IMAP inbox, classify emails, and optionally forward owner-action items.
1461
-
1462
- Args:
1463
- smtp_pass: SMTP/IMAP password for pro@delimit.ai.
1464
- limit: Max number of recent messages to check.
1465
- process: If True, forward owner-action emails and mark as read.
1466
- If False, just report classification (dry run).
1467
-
1468
- Returns:
1469
- Summary of inbox state and routing decisions.
1470
- """
1471
- if not smtp_pass:
1472
- smtp_pass = os.environ.get("DELIMIT_SMTP_PASS", "")
1473
- if not smtp_pass and IMAP_USER:
1474
- account = _load_smtp_account(IMAP_USER)
1475
- smtp_pass = str((account or {}).get("pass") or (account or {}).get("password") or "")
1476
- if not smtp_pass:
1477
- return {"error": "IMAP password required. Set DELIMIT_SMTP_PASS or pass smtp_pass."}
1478
-
1479
- timestamp = datetime.now(timezone.utc).isoformat()
1480
-
1481
- try:
1482
- imap = imaplib.IMAP4_SSL(IMAP_HOST, IMAP_PORT)
1483
- imap.login(IMAP_USER, smtp_pass)
1484
- except Exception as e:
1485
- return {"error": f"IMAP connection failed: {e}"}
1486
-
1487
- try:
1488
- imap.select("INBOX")
1489
-
1490
- # Get UNSEEN messages first, then fall back to recent ALL
1491
- status, unseen_data = imap.search(None, "UNSEEN")
1492
- unseen_ids = unseen_data[0].split() if unseen_data[0] else []
1493
-
1494
- # Also get all message IDs for the summary
1495
- status, all_data = imap.search(None, "ALL")
1496
- all_ids = all_data[0].split() if all_data[0] else []
1497
-
1498
- # Process unseen messages (up to limit)
1499
- target_ids = unseen_ids[-limit:] if unseen_ids else []
1500
-
1501
- results: List[Dict[str, Any]] = []
1502
- forwarded = 0
1503
- skipped = 0
1504
-
1505
- for msg_id in target_ids:
1506
- # Fetch without marking as seen (use BODY.PEEK)
1507
- status, data = imap.fetch(msg_id, "(BODY.PEEK[])")
1508
- if status != "OK" or not data or not data[0]:
1509
- continue
1510
-
1511
- raw_email = data[0][1]
1512
- msg = email.message_from_bytes(raw_email)
1513
-
1514
- from_header = _decode_header(msg.get("From", ""))
1515
- subject = _decode_header(msg.get("Subject", ""))
1516
- date_str = msg.get("Date", "")
1517
- sender_addr = _extract_sender_email(from_header)
1518
-
1519
- classification = classify_email(sender_addr, subject, from_header)
1520
-
1521
- entry = {
1522
- "msg_id": msg_id.decode(),
1523
- "from": from_header,
1524
- "sender": sender_addr,
1525
- "subject": subject,
1526
- "date": date_str,
1527
- "classification": classification,
1528
- "forwarded": False,
1529
- }
1530
-
1531
- if process and classification == "owner-action":
1532
- success = _forward_email(msg, smtp_pass)
1533
- entry["forwarded"] = success
1534
- if success:
1535
- # Mark as seen after successful forward
1536
- imap.store(msg_id, "+FLAGS", "\\Seen")
1537
- forwarded += 1
1538
- else:
1539
- entry["forward_error"] = True
1540
- elif process and classification == "non-owner":
1541
- # Mark as seen (processed, stays in inbox)
1542
- imap.store(msg_id, "+FLAGS", "\\Seen")
1543
- skipped += 1
1544
-
1545
- results.append(entry)
1546
- _record_inbox_routing({**entry, "timestamp": timestamp, "process_mode": process})
1547
-
1548
- imap.logout()
1549
-
1550
- return {
1551
- "timestamp": timestamp,
1552
- "total_messages": len(all_ids),
1553
- "unseen_count": len(unseen_ids),
1554
- "processed": len(results),
1555
- "forwarded_to_owner": forwarded,
1556
- "kept_in_inbox": skipped,
1557
- "dry_run": not process,
1558
- "messages": results,
1559
- }
1560
-
1561
- except Exception as e:
1562
- try:
1563
- imap.logout()
1564
- except Exception:
1565
- pass
1566
- return {"error": f"Inbox processing failed: {e}"}
1567
-
1568
-
1569
- def get_inbox_status(
1570
- smtp_pass: str = "",
1571
- limit: int = 10,
1572
- ) -> Dict[str, Any]:
1573
- """Get inbox status and recent routing history without processing.
1574
-
1575
- Args:
1576
- smtp_pass: IMAP password.
1577
- limit: Number of recent messages to show.
1578
-
1579
- Returns:
1580
- Inbox summary and recent routing log entries.
1581
- """
1582
- # Get recent routing history from log
1583
- routing_history: List[Dict[str, Any]] = []
1584
- try:
1585
- if INBOX_ROUTING_FILE.exists():
1586
- with open(INBOX_ROUTING_FILE, "r", encoding="utf-8") as f:
1587
- lines = f.readlines()
1588
- for line in lines[-limit:]:
1589
- try:
1590
- routing_history.append(json.loads(line.strip()))
1591
- except json.JSONDecodeError:
1592
- continue
1593
- except OSError:
1594
- pass
1595
-
1596
- # Get live inbox state
1597
- if not smtp_pass:
1598
- smtp_pass = os.environ.get("DELIMIT_SMTP_PASS", "")
1599
- if not smtp_pass:
1600
- return {
1601
- "routing_history": routing_history,
1602
- "error": "IMAP password required for live inbox status. Set DELIMIT_SMTP_PASS.",
1603
- }
1604
-
1605
- try:
1606
- imap = imaplib.IMAP4_SSL(IMAP_HOST, IMAP_PORT)
1607
- imap.login(IMAP_USER, smtp_pass)
1608
- imap.select("INBOX")
1609
-
1610
- _, all_data = imap.search(None, "ALL")
1611
- all_ids = all_data[0].split() if all_data[0] else []
1612
-
1613
- _, unseen_data = imap.search(None, "UNSEEN")
1614
- unseen_ids = unseen_data[0].split() if unseen_data[0] else []
1615
-
1616
- # Preview recent messages
1617
- recent_ids = all_ids[-limit:]
1618
- recent_msgs: List[Dict[str, str]] = []
1619
- for msg_id in recent_ids:
1620
- _, data = imap.fetch(msg_id, "(BODY.PEEK[HEADER.FIELDS (FROM SUBJECT DATE)] FLAGS)")
1621
- if data and data[0]:
1622
- # Parse flags and headers
1623
- flags_str = ""
1624
- header_bytes = b""
1625
- for part in data:
1626
- if isinstance(part, tuple):
1627
- if b"FLAGS" in part[0]:
1628
- flags_str = part[0].decode(errors="replace")
1629
- header_bytes = part[1]
1630
-
1631
- header_text = header_bytes.decode("utf-8", errors="replace")
1632
- tmp_msg = email.message_from_string(header_text)
1633
- from_h = _decode_header(tmp_msg.get("From", ""))
1634
- subj_h = _decode_header(tmp_msg.get("Subject", ""))
1635
- date_h = tmp_msg.get("Date", "")
1636
- sender = _extract_sender_email(from_h)
1637
- cls = classify_email(sender, subj_h, from_h)
1638
- seen = "\\Seen" in flags_str
1639
-
1640
- recent_msgs.append({
1641
- "from": from_h,
1642
- "subject": subj_h,
1643
- "date": date_h,
1644
- "classification": cls,
1645
- "seen": seen,
1646
- })
1647
-
1648
- imap.logout()
1649
-
1650
- return {
1651
- "total_messages": len(all_ids),
1652
- "unseen_count": len(unseen_ids),
1653
- "recent_messages": recent_msgs,
1654
- "routing_history_count": len(routing_history),
1655
- "routing_history": routing_history[-5:],
1656
- }
1657
-
1658
- except Exception as e:
1659
- return {
1660
- "routing_history": routing_history,
1661
- "error": f"IMAP connection failed: {e}",
1662
- }
1
+ # notify — Pro module (stubbed in npm package)
2
+ # Full implementation available on delimit.ai server