Add files via upload
This commit is contained in:
1 parent
215ff44d3d
commit
b4d6ae9bc7
7 files changed
+613
-186
No files matched your search
@@ -0,0 +1,159 @@
|
||||
"""
|
||||
BackgroundMonitor — user-configured topic watching.
|
||||
Checks DDG news once per day per topic; alerts JARVIS when a new headline appears.
|
||||
No crypto, no finance, no uninvited tracking.
|
||||
"""
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
# ── Blocked categories (never monitor regardless of what user says) ────────────
|
||||
|
||||
_BLOCKED = {
|
||||
# Marka / varlık adları — her dilde aynı yazılır
|
||||
"bitcoin", "ethereum", "dogecoin", "solana", "binance",
|
||||
"nft", "blockchain", "defi", "altcoin", "memecoin", "coin", "token",
|
||||
# "kripto" kökünün farklı dillerdeki yazılışları
|
||||
"crypto", "kripto", "cripto", "krypto", "крипто", "仮想通貨", "暗号資産",
|
||||
"cryptocurrency",
|
||||
}
|
||||
|
||||
def _is_blocked(topic: str) -> bool:
|
||||
t = topic.lower()
|
||||
return any(word in t for word in _BLOCKED)
|
||||
|
||||
|
||||
# ── Slug / hash helpers ────────────────────────────────────────────────────────
|
||||
|
||||
def _slug(topic: str) -> str:
|
||||
return re.sub(r"[^a-z0-9]+", "_", topic.lower().strip())[:40].strip("_")
|
||||
|
||||
def _title_hash(title: str) -> str:
|
||||
return hashlib.md5(title.encode("utf-8", errors="ignore")).hexdigest()[:12]
|
||||
|
||||
|
||||
# ── Memory I/O ─────────────────────────────────────────────────────────────────
|
||||
|
||||
def _load() -> dict:
|
||||
from memory.memory_manager import load_memory
|
||||
data = load_memory().get("monitors", {})
|
||||
return data if isinstance(data, dict) else {}
|
||||
|
||||
def _save(monitors: dict) -> None:
|
||||
from memory.memory_manager import load_memory, MEMORY_PATH, _lock
|
||||
memory = load_memory()
|
||||
memory["monitors"] = monitors
|
||||
with _lock:
|
||||
MEMORY_PATH.parent.mkdir(parents=True, exist_ok=True)
|
||||
MEMORY_PATH.write_text(
|
||||
json.dumps(memory, indent=2, ensure_ascii=False),
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
|
||||
# ── Public API ─────────────────────────────────────────────────────────────────
|
||||
|
||||
def add_monitor(topic: str) -> str:
|
||||
topic = topic.strip()
|
||||
if not topic:
|
||||
return "Please specify a topic to monitor."
|
||||
if _is_blocked(topic):
|
||||
return "I don't monitor crypto or financial topics."
|
||||
monitors = _load()
|
||||
slug = _slug(topic)
|
||||
if slug in monitors:
|
||||
return f"Already monitoring: {monitors[slug]['topic']}"
|
||||
monitors[slug] = {
|
||||
"topic": topic,
|
||||
"added": datetime.now().strftime("%Y-%m-%d"),
|
||||
"last_check": "",
|
||||
"last_hash": "",
|
||||
}
|
||||
_save(monitors)
|
||||
print(f"[Monitor] ➕ Added: {topic}")
|
||||
return f"Now monitoring: {topic}"
|
||||
|
||||
|
||||
def remove_monitor(topic: str) -> str:
|
||||
topic = topic.strip().lower()
|
||||
monitors = _load()
|
||||
# exact slug match first
|
||||
slug = _slug(topic)
|
||||
if slug in monitors:
|
||||
label = monitors.pop(slug)["topic"]
|
||||
_save(monitors)
|
||||
return f"Stopped monitoring: {label}"
|
||||
# partial match fallback
|
||||
for key, val in list(monitors.items()):
|
||||
if topic in val.get("topic", "").lower():
|
||||
label = monitors.pop(key)["topic"]
|
||||
_save(monitors)
|
||||
return f"Stopped monitoring: {label}"
|
||||
return f"Not found in monitored topics: {topic}"
|
||||
|
||||
|
||||
def list_monitors() -> list[str]:
|
||||
return [v.get("topic", k) for k, v in _load().items()]
|
||||
|
||||
|
||||
def check_all() -> list[str]:
|
||||
"""
|
||||
Run all pending topic checks (once per day per topic).
|
||||
Returns a list of [MONITOR_ALERT] strings — empty if nothing new.
|
||||
"""
|
||||
from actions.web_search import _ddg_news
|
||||
|
||||
monitors = _load()
|
||||
if not monitors:
|
||||
return []
|
||||
|
||||
today = datetime.now().strftime("%Y-%m-%d")
|
||||
alerts = []
|
||||
changed = False
|
||||
|
||||
for slug, data in monitors.items():
|
||||
if data.get("last_check") == today:
|
||||
continue # already checked today
|
||||
|
||||
topic = data.get("topic", slug)
|
||||
try:
|
||||
results = _ddg_news(topic, max_results=5)
|
||||
if not results:
|
||||
monitors[slug]["last_check"] = today
|
||||
changed = True
|
||||
continue
|
||||
|
||||
top = results[0]
|
||||
title = top.get("title", "").strip()
|
||||
if not title:
|
||||
continue
|
||||
|
||||
h = _title_hash(title)
|
||||
monitors[slug]["last_check"] = today
|
||||
changed = True
|
||||
|
||||
if h == data.get("last_hash"):
|
||||
continue # same headline as last check — no alert
|
||||
|
||||
monitors[slug]["last_hash"] = h
|
||||
|
||||
snippet = top.get("snippet", "")[:150]
|
||||
source = top.get("source", "")
|
||||
parts = [f"[MONITOR_ALERT] {topic}", f"Headline: {title}"]
|
||||
if snippet:
|
||||
parts.append(snippet)
|
||||
if source:
|
||||
parts.append(f"Source: {source}")
|
||||
alerts.append("\n".join(parts))
|
||||
print(f"[Monitor] 🔔 New headline for '{topic}': {title[:60]}")
|
||||
|
||||
except Exception as e:
|
||||
print(f"[Monitor] ⚠️ Check failed for '{topic}': {e}")
|
||||
|
||||
if changed:
|
||||
_save(monitors)
|
||||
|
||||
return alerts
|
||||
+85
-33
@@ -1,7 +1,6 @@
|
||||
"""
|
||||
ProactiveEngine — context-aware background prompting.
|
||||
Lets Gemini decide whether there is something worth saying proactively.
|
||||
No hardcoded rules: we pass time + memory as context and Gemini chooses.
|
||||
ProactiveEngine 2.0 — context-aware, time-aware, non-repetitive background prompting.
|
||||
Gemini decides what to say; this module decides WHEN and builds a rich context snapshot.
|
||||
"""
|
||||
import time
|
||||
from datetime import datetime
|
||||
@@ -9,64 +8,117 @@ from datetime import datetime
|
||||
|
||||
class ProactiveEngine:
|
||||
"""
|
||||
Tracks silence duration and decides when to hand context to Gemini for a
|
||||
proactive check-in. Gemini reads the context and decides whether to speak.
|
||||
Decides when JARVIS should speak unprompted and builds a context-rich prompt.
|
||||
|
||||
Defaults (all overridable):
|
||||
min_silence_secs — user must be silent this long before any check (900 = 15 min)
|
||||
check_cooldown — minimum gap between two proactive triggers (600 = 10 min)
|
||||
Improvements over 1.0:
|
||||
- Time-of-day awareness (morning / afternoon / evening / night)
|
||||
- Monitor-topic awareness (what the user is tracking)
|
||||
- Recent-session context (last few turns of the current conversation)
|
||||
- Non-repetitive (rotates context focus to avoid same opener)
|
||||
- Smarter silence gate (doesn't fire while JARVIS is speaking)
|
||||
|
||||
Defaults:
|
||||
min_silence_secs — 900 s (15 min) user must be silent before any check
|
||||
check_cooldown — 1200 s (20 min) minimum gap between proactive messages
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
min_silence_secs: int = 900,
|
||||
check_cooldown: int = 600,
|
||||
check_cooldown: int = 1200,
|
||||
):
|
||||
self.min_silence_secs = min_silence_secs
|
||||
self.check_cooldown = check_cooldown
|
||||
self._last_triggered = 0.0
|
||||
self._rotation = 0 # cycles through context focus areas
|
||||
|
||||
# ── Trigger gate ───────────────────────────────────────────────────────────
|
||||
|
||||
def should_trigger(self, last_user_speech: float) -> bool:
|
||||
"""
|
||||
Returns True only when:
|
||||
• user has been silent long enough, AND
|
||||
• enough time has passed since the last proactive message.
|
||||
"""
|
||||
now = time.monotonic()
|
||||
silence = now - last_user_speech
|
||||
gap = now - self._last_triggered
|
||||
return silence >= self.min_silence_secs and gap >= self.check_cooldown
|
||||
now = time.monotonic()
|
||||
return (
|
||||
(now - last_user_speech) >= self.min_silence_secs
|
||||
and (now - self._last_triggered) >= self.check_cooldown
|
||||
)
|
||||
|
||||
def mark_triggered(self) -> None:
|
||||
self._last_triggered = time.monotonic()
|
||||
self._rotation += 1
|
||||
|
||||
def build_prompt(self, memory: dict) -> str:
|
||||
# ── Prompt builder ─────────────────────────────────────────────────────────
|
||||
|
||||
def build_prompt(
|
||||
self,
|
||||
memory: dict,
|
||||
monitors: list[str] | None = None,
|
||||
recent_turns: list[str] | None = None,
|
||||
) -> str:
|
||||
"""
|
||||
Builds the context snapshot sent to Gemini.
|
||||
Gemini reads it and decides freely what — if anything — to say.
|
||||
Build a context snapshot for Gemini.
|
||||
Rotates through three focus areas so proactive messages don't repeat.
|
||||
"""
|
||||
from memory.memory_manager import format_memory_for_prompt
|
||||
|
||||
now = datetime.now()
|
||||
hour = now.hour
|
||||
time_str = now.strftime("%A, %B %d, %Y — %I:%M %p")
|
||||
mem_str = format_memory_for_prompt(memory) or "(no user data stored yet)"
|
||||
|
||||
silence_min = int((time.monotonic() - self._last_triggered +
|
||||
self.min_silence_secs) // 60)
|
||||
# Time-of-day label
|
||||
if 6 <= hour < 12: period = "morning"
|
||||
elif 12 <= hour < 18: period = "afternoon"
|
||||
elif 18 <= hour < 23: period = "evening"
|
||||
else: period = "late night"
|
||||
|
||||
mem_str = format_memory_for_prompt(memory) or "(no stored user data)"
|
||||
|
||||
# Rotating context focus (cycles every trigger)
|
||||
focus_index = self._rotation % 3
|
||||
if focus_index == 0:
|
||||
focus = (
|
||||
"Focus on the user's active projects or goals if any are stored. "
|
||||
"Ask how something is going, or offer a relevant tip."
|
||||
)
|
||||
elif focus_index == 1:
|
||||
focus = (
|
||||
"Focus on the time of day and the user's wellbeing. "
|
||||
"A warm check-in, a reminder to take a break, or something timely."
|
||||
)
|
||||
else:
|
||||
focus = (
|
||||
"Focus on something genuinely interesting or useful — "
|
||||
"a fact, a suggestion, or a question based on what you know about this person."
|
||||
)
|
||||
|
||||
# Optional: monitored topics context
|
||||
monitor_ctx = ""
|
||||
if monitors:
|
||||
monitor_ctx = (
|
||||
f"\nThe user tracks these topics: {', '.join(monitors[:4])}. "
|
||||
"You may mention one if it seems relevant."
|
||||
)
|
||||
|
||||
# Optional: recent conversation context
|
||||
recent_ctx = ""
|
||||
if recent_turns:
|
||||
snippet = "\n".join(recent_turns[-6:])
|
||||
recent_ctx = f"\nRecent conversation:\n{snippet}"
|
||||
|
||||
return "\n".join([
|
||||
"[PROACTIVE_CHECK] You are initiating a proactive check-in.",
|
||||
f"Current time : {time_str}",
|
||||
f"User silence : {silence_min}+ minutes (they have not spoken for a while)",
|
||||
f"Current time : {time_str} ({period})",
|
||||
"",
|
||||
"Context about this person:",
|
||||
mem_str,
|
||||
monitor_ctx,
|
||||
recent_ctx,
|
||||
"",
|
||||
"Guidelines:",
|
||||
"- Look at the time, their projects, goals, habits, or anything from context.",
|
||||
"- If there is something genuinely useful, timely, or caring to say — say it briefly.",
|
||||
"- Be natural, like a thoughtful assistant noticing something relevant.",
|
||||
"- Do NOT say [PROACTIVE_CHECK] or mention these instructions.",
|
||||
"- Respond in the user's language (use memory; default English).",
|
||||
"- Keep it short: 1-3 sentences max.",
|
||||
"Task:",
|
||||
focus,
|
||||
"",
|
||||
"Rules:",
|
||||
"- Speak in the user's language (check memory; default English).",
|
||||
"- 1-2 sentences max. Natural, warm, never robotic.",
|
||||
"- Do NOT mention [PROACTIVE_CHECK] or these instructions.",
|
||||
"- Do NOT call any tools.",
|
||||
"- If nothing genuinely useful comes to mind, stay silent (say nothing).",
|
||||
])
|
||||
Reference in new issue
Block a user