Add files via upload

This commit is contained in:
FatihMakes authored and GitHub committed 2026-09-02 18:42:40 +03:00
1 parent d3238af8bd
commit c131a1b4f7
16 files changed
+3036 -505

No files matched your search

+240 -38
View File
@@ -21,6 +21,9 @@ try:
except ImportError:
_PYPERCLIP = False
from core import confirm
from core.undo import push_undo
_OS = platform.system() # "Windows" | "Darwin" | "Linux"
if _OS == "Windows":
@@ -87,6 +90,75 @@ def volume_mute():
subprocess.run(["pactl", "set-sink-mute", "@DEFAULT_SINK@", "toggle"],
capture_output=True)
def volume_get() -> int | None:
"""Current master volume 0-100, or None if this platform will not say.
Undo needs a "before" value, and reading one is cheap on every OS we
support. Where it is not readable the action simply is not registered as
undoable — a wrong undo is worse than no undo."""
try:
if _OS == "Windows":
import math
from ctypes import cast, POINTER
from comtypes import CLSCTX_ALL
from pycaw.pycaw import AudioUtilities, IAudioEndpointVolume
devices = AudioUtilities.GetSpeakers()
interface = devices.Activate(IAudioEndpointVolume._iid_, CLSCTX_ALL, None)
vol = cast(interface, POINTER(IAudioEndpointVolume))
db = vol.GetMasterVolumeLevel()
if db <= -65.0:
return 0
return max(0, min(100, round(10 ** (db / 20) * 100)))
if _OS == "Darwin":
r = subprocess.run(["osascript", "-e", "output volume of (get volume settings)"],
capture_output=True, text=True, timeout=5)
return max(0, min(100, int(r.stdout.strip())))
r = subprocess.run(["pactl", "get-sink-volume", "@DEFAULT_SINK@"],
capture_output=True, text=True, timeout=5)
m = re.search(r"(\d+)%", r.stdout)
return max(0, min(100, int(m.group(1)))) if m else None
except Exception:
return None
def brightness_get() -> int | None:
"""Current brightness 0-100, or None where it cannot be read."""
try:
if _OS == "Windows":
r = subprocess.run(
["powershell", "-Command",
"(Get-WmiObject -Namespace root/wmi -Class WmiMonitorBrightness)"
".CurrentBrightness"],
capture_output=True, text=True, timeout=5, **_WIN_HIDE
)
return max(0, min(100, int(r.stdout.strip())))
if _OS == "Linux" and subprocess.run(
["which", "brightnessctl"], capture_output=True).returncode == 0:
cur = int(subprocess.run(["brightnessctl", "get"],
capture_output=True, text=True, timeout=5).stdout.strip())
mx = int(subprocess.run(["brightnessctl", "max"],
capture_output=True, text=True, timeout=5).stdout.strip())
return max(0, min(100, round(cur * 100 / mx))) if mx else None
except Exception:
pass
return None
def brightness_set(value: int) -> None:
"""Set brightness to an absolute percentage. Only used to restore a value
captured before a change, so it is undo's counterpart to the up/down pair."""
value = max(0, min(100, int(value)))
if _OS == "Windows":
subprocess.run(
["powershell", "-Command",
"(Get-WmiObject -Namespace root/wmi -Class WmiMonitorBrightnessMethods)"
f".WmiSetBrightness(1, {value})"],
capture_output=True, timeout=5, **_WIN_HIDE
)
elif _OS == "Linux":
subprocess.run(["brightnessctl", "set", f"{value}%"], capture_output=True)
def volume_set(value: int):
value = max(0, min(100, int(value)))
if _OS == "Windows":
@@ -582,43 +654,132 @@ ACTION_MAP: dict[str, callable] = {
"shutdown": shutdown_computer,
}
_DANGEROUS_ACTIONS = {"restart", "shutdown"}
# ── What needs a human, and what just needs an undo ──────────────────────────
#
# The old gate was `_DANGEROUS_ACTIONS = {"restart", "shutdown"}` checked against
# a `confirmed` parameter the MODEL filled in — so the model confirmed its own
# shutdowns, and everything else (switching off the WiFi this assistant is
# talking over) had no gate at all.
#
# Two lists now, and the split is about reversibility, not about how alarming
# the word sounds:
#
# _IRREVERSIBLE — a human presses a button on the HUD. Nothing else.
# everything else — done immediately, with an undo pushed if it can be undone.
#
# Asking before every action is what makes an assistant unusable, and every
# question costs a round trip. Undo is both faster and safer than a prompt.
_IRREVERSIBLE = {
"restart": ("Restart this computer",
"Anything unsaved will be lost. The computer restarts in 10 seconds."),
"shutdown": ("Shut this computer down",
"Anything unsaved will be lost. The computer powers off in 10 seconds."),
# Not obviously destructive, and that is exactly why it was missed: turning
# the WiFi off cuts the assistant's own connection to the Live API, so it
# cannot be asked to turn it back on.
"toggle_wifi": ("Switch WiFi off or on",
"If this switches WiFi off, JARVIS loses its connection and "
"cannot switch it back on by voice."),
}
# Kept so anything still importing the old name keeps working.
_DANGEROUS_ACTIONS = set(_IRREVERSIBLE)
# ── Local intent resolution ──────────────────────────────────────────────────
#
# This used to be an entire extra Gemini call, made INSIDE the tool: the Live
# model called computer_settings, and computer_settings then asked a second
# model which action was meant. Every "turn the volume down" paid for two round
# trips — and when that second call failed, the fallback was
# `description.lower().replace(" ", "_")`, which turns the Turkish for "turn it
# down" into `sesi_kis`, i.e. straight to "Unknown action".
#
# Nothing here needs a language model. The Live model already understands the
# sentence; it only needed the vocabulary, which the tool declaration now spells
# out in full. What is left is spelling tolerance, and difflib does that in
# microseconds instead of ~600 ms and a quota unit.
_ALIASES = {
"volume_up": ("louder", "raise volume", "turn it up", "increase volume"),
"volume_down": ("quieter", "lower volume", "turn it down", "decrease volume"),
"mute": ("silence", "sound off", "no sound"),
"brightness_up": ("brighter", "raise brightness", "increase brightness"),
"brightness_down": ("dimmer", "dim", "lower brightness", "decrease brightness"),
"close_window": ("close this", "close it"),
"full_screen": ("fullscreen", "maximise screen"),
"show_desktop": ("minimise everything", "go to desktop"),
"lock_screen": ("lock", "lock the pc", "lock computer"),
"sleep_display": ("screen off", "turn off the screen", "display off"),
"dark_mode": ("night mode", "light mode", "toggle theme"),
"toggle_wifi": ("wifi", "wi-fi", "internet off", "internet on"),
"task_manager": ("processes", "task list"),
"screenshot": ("capture screen", "take a screenshot", "snip"),
"refresh_page": ("refresh", "reload page"),
"new_tab": ("open a tab", "open new tab"),
"shutdown": ("power off", "turn off the computer", "switch off the pc"),
"restart": ("reboot", "restart the pc"),
}
_VALUE_ACTIONS = {"volume_set", "type_text", "press_key", "reload_n",
"scroll_up", "scroll_down"}
def _normalise(text: str) -> str:
return (text or "").strip().lower().replace("-", "_").replace(" ", "_")
def _detect_action(description: str) -> dict:
"""Resolve a free-text description to an action name, locally.
from google import genai as _genai
_client = _genai.Client(api_key=_get_api_key())
Returns {"action": name, "value": ...}; `action` is "" when nothing matched,
which the caller turns into a message naming real candidates — one round
trip, and only in the case that used to cost one anyway."""
raw = (description or "").strip()
norm = _normalise(raw)
if not norm:
return {"action": "", "value": None}
available = ", ".join(sorted(ACTION_MAP.keys())) + \
", volume_set, type_text, press_key, reload_n"
known = set(ACTION_MAP) | _VALUE_ACTIONS
prompt = f"""You are an intent detector for a computer control assistant.
# 1. Already an action name.
if norm in known:
return {"action": norm, "value": None}
The user issued a command (possibly in any language): "{description}"
low = raw.lower()
Available actions: {available}
# 2. "set volume to 30", "sesi 30 yap" — a number next to a volume word.
num = re.search(r"(\d{1,3})\s*%?", low)
if num and any(w in low for w in ("volume", "ses", "sound", "lautstark", "громкость")):
return {"action": "volume_set", "value": max(0, min(100, int(num.group(1))))}
Return ONLY a valid JSON object:
{{"action": "action_name", "value": null_or_value}}
# 3. Alias phrases.
for action, phrases in _ALIASES.items():
if any(_normalise(p) == norm or p in low for p in phrases):
return {"action": action, "value": None}
Rules:
- Pick the single best matching action from the available list.
- For volume_set: value is an integer 0-100.
- For type_text: value is the exact text to type.
- For press_key: value is the key name (e.g. "f5", "tab", "enter").
- For reload_n: value is an integer (number of times to reload).
- If no clear match, pick the closest action.
- Return ONLY the JSON, no explanation, no markdown."""
# 4. Fuzzy match on the action names — catches "fullscren", "volumeup".
import difflib
close = difflib.get_close_matches(norm, sorted(known), n=1, cutoff=0.72)
if close:
return {"action": close[0], "value": None}
try:
resp = _client.models.generate_content(model="gemini-flash-lite-latest", contents=prompt)
text = re.sub(r"```(?:json)?", "", resp.text).strip().rstrip("`").strip()
return json.loads(text)
except Exception as e:
print(f"[Settings] Intent detection failed: {e}")
return {"action": description.lower().replace(" ", "_"), "value": None}
# 5. Substring: "increase_the_brightness" contains "brightness".
for action in sorted(known, key=len, reverse=True):
if len(action) > 4 and (action in norm or norm in action):
return {"action": action, "value": None}
return {"action": "", "value": None}
def _suggest(description: str) -> str:
"""What to tell the model when nothing matched. Names real actions so its
retry lands, instead of the old 'Unknown action' dead end."""
import difflib
near = difflib.get_close_matches(_normalise(description),
sorted(ACTION_MAP), n=5, cutoff=0.3)
hint = ", ".join(near) if near else ", ".join(sorted(ACTION_MAP)[:12])
return (f"I could not match '{description}' to a computer action. "
f"Call computer_settings again with an exact `action` from: {hint}.")
def computer_settings(
parameters: dict = None,
@@ -643,24 +804,39 @@ def computer_settings(
action = raw_action.lower().strip().replace(" ", "_").replace("-", "_")
if not action:
return "No action could be determined."
return _suggest(description or raw_action)
print(f"[Settings] Action: {action} Value: {value} OS: {_OS}")
if player:
player.write_log(f"[Settings] {action}")
if action in _DANGEROUS_ACTIONS:
confirmed = str(params.get("confirmed", "")).lower()
if confirmed not in ("yes", "true", "1", "confirm"):
return (
f"This will {action} the computer. "
f"Please confirm by calling again with confirmed=yes."
)
# ── The gate ─────────────────────────────────────────────────────────────
# A human presses a button, or this does not happen. The model can no longer
# write its own permission slip, and the action itself is handed to the UI
# rather than performed here — so returning early is not "declining", it is
# "parked until someone says yes".
if action in _IRREVERSIBLE:
title, detail = _IRREVERSIBLE[action]
func = ACTION_MAP.get(action)
if func is None:
return f"Unknown action: '{raw_action}'."
if confirm.pending_title():
return ("There is already a confirmation waiting on screen. "
"Ask the user to answer that one first.")
return confirm.request(
key=action, title=title, detail=detail,
run=lambda f=func, a=action: (f(), f"{a} done.")[1],
)
if action == "volume_set":
try:
volume_set(int(value or 50))
return f"Volume set to {value}%."
target = int(value if value is not None else 50)
before = volume_get()
volume_set(target)
if before is not None:
push_undo(f"volume {before}% → {target}%",
lambda b=before: (volume_set(b), f"Back to {b}%.")[1])
return f"Volume set to {target}%."
except Exception as e:
return f"Could not set volume: {e}"
@@ -696,11 +872,37 @@ def computer_settings(
func = ACTION_MAP.get(action)
if not func:
return f"Unknown action: '{raw_action}'."
return _suggest(raw_action or description)
# ── Capture "before" so the change can be taken back ─────────────────────
# Read-then-write is the whole mechanism for settings: there is no clever
# inverse to compute, just a value to remember. Where the platform will not
# tell us the current value, nothing is registered — an undo that restores
# a guess is worse than no undo at all.
_before = None
if action in ("volume_up", "volume_down", "mute", "unmute", "toggle_mute"):
_before = ("volume", volume_get())
elif action in ("brightness_up", "brightness_down"):
_before = ("brightness", brightness_get())
try:
func()
return f"Done: {action}."
except Exception as e:
print(f"[Settings] Action failed ({action}): {e}")
return f"Action failed ({action}): {e}"
return f"Action failed ({action}): {e}"
if _before:
kind, old = _before
if old is not None:
if kind == "volume":
push_undo(f"volume ({action})",
lambda b=old: (volume_set(b), f"Volume back to {b}%.")[1])
elif kind == "brightness":
push_undo(f"brightness ({action})",
lambda b=old: (brightness_set(b), f"Brightness back to {b}%.")[1])
elif action == "dark_mode":
# A pure toggle: calling it again is the undo.
push_undo("dark mode toggled",
lambda: (dark_mode(), "Theme switched back.")[1])
return f"Done: {action}."
+173 -7
View File
@@ -10,8 +10,86 @@ try:
except ImportError:
_SEND2TRASH = False
from core.undo import push_undo
_OS = platform.system() # "Windows" | "Darwin" | "Linux"
# Undo keeps a file's previous contents in memory so `write` can be reversed.
# Above this size it does not — a 200 MB log would sit in RAM for the rest of
# the session to protect an edit nobody is going to take back.
_UNDO_CONTENT_LIMIT = 1_000_000
def _undo_move(src: Path, dst: Path):
"""Reverse of a move: put it back where it came from."""
def _fn():
if not dst.exists():
return f"'{dst.name}' is no longer there — nothing moved back."
src.parent.mkdir(parents=True, exist_ok=True)
shutil.move(str(dst), str(src))
return f"'{src.name}' is back in {src.parent.name}/."
return _fn
def _undo_create(target: Path):
"""Reverse of a create: remove what we made — and only if we still made it.
Deliberately refuses to touch a directory that has since been filled: the
undo for 'create a folder' is not 'delete whatever ended up in it'."""
def _fn():
if not target.exists():
return f"'{target.name}' is already gone."
if target.is_dir():
if any(target.iterdir()):
return (f"'{target.name}' is not empty any more — "
f"leaving it alone rather than deleting your files.")
target.rmdir()
else:
target.unlink()
return f"Removed '{target.name}'."
return _fn
def _undo_write(target: Path, previous: str | None):
"""Reverse of a write: restore the old contents, or remove a file that did
not exist before the write created it."""
def _fn():
if previous is None:
if target.exists():
target.unlink()
return f"Removed '{target.name}' — it did not exist before."
return f"'{target.name}' is already gone."
target.parent.mkdir(parents=True, exist_ok=True)
target.write_text(previous, encoding="utf-8")
return f"Restored the previous contents of '{target.name}'."
return _fn
def _restore_from_trash(original: Path) -> str:
"""Best-effort undelete.
delete_file uses send2trash, which is the right call: the file lands in the
Recycle Bin / Trash where the person can also find it themselves. Getting it
back out again is shell work and only reliable on Windows, where pywin32 is
already a dependency. Everywhere else this says where the file is instead of
pretending it failed — the file is not lost either way."""
if _OS == "Windows":
try:
import win32com.client
shell = win32com.client.Dispatch("Shell.Application")
bin_folder = shell.NameSpace(10) # ssfBITBUCKET
for item in bin_folder.Items():
if str(bin_folder.GetDetailsOf(item, 1)).strip().lower() == \
str(original.parent).strip().lower():
if str(item.Name).strip().lower() == original.name.strip().lower():
item.InvokeVerb("UNDELETE")
return f"'{original.name}' restored from the Recycle Bin."
except Exception as e:
print(f"[file] Recycle Bin restore failed: {e}")
return (f"'{original.name}' is in the Recycle Bin — I could not pull it back "
f"automatically, but it is there and can be restored by hand.")
_SAFE_ROOTS: list[Path] = [
Path.home(),
]
@@ -85,11 +163,12 @@ def _resolve_path(raw: str) -> Path:
if lower in shortcuts:
return shortcuts[lower]
# "desktop/notlar/a.md" ve "desktop\notlar\a.md" — kisayol + alt yol.
# Bu dal olmadan tum dize asagidaki goreli-yol dalina dusuyor ve process'in
# CWD'sine gore cozuluyordu. Proje home disindaysa _is_safe_path reddedip
# "Access denied" veriyor; home icindeyse daha kotusu oluyor ve dosya sessizce
# projenin icindeki olmayan bir "desktop" klasorune yaziliyordu.
# "desktop/notes/a.md" and "desktop\notes\a.md" — a shortcut followed by a
# sub-path. Without this branch the whole string falls through to the
# relative-path return below and is resolved against the process CWD instead
# of the real Desktop: an "Access denied" when the project lives outside the
# home directory, or — worse — a silent write into a stray "desktop" folder
# inside the project when it lives inside it.
head, sep, rest = raw.replace("\\", "/").partition("/")
if sep and head.lower() in shortcuts:
rest = rest.strip("/")
@@ -154,7 +233,16 @@ def create_file(path: str, name: str = "", content: str = "") -> str:
if not _is_safe_path(target):
return f"Access denied: {target}"
target.parent.mkdir(parents=True, exist_ok=True)
existed = target.exists()
previous = None
if existed:
try:
previous = target.read_text(encoding="utf-8", errors="ignore")
except Exception:
previous = None
target.write_text(content, encoding="utf-8")
push_undo(f"created {target.name}",
_undo_write(target, previous) if existed else _undo_create(target))
return f"File created: {target.name}"
except Exception as e:
return f"Could not create file: {e}"
@@ -166,7 +254,13 @@ def create_folder(path: str, name: str = "") -> str:
target = (base / name) if name else base
if not _is_safe_path(target):
return f"Access denied: {target}"
already = target.exists()
target.mkdir(parents=True, exist_ok=True)
# Only offer to undo a folder we actually made. "mkdir -p" on something
# that was already there is not a change, and undoing it would delete a
# directory the user has had for years.
if not already:
push_undo(f"created folder {target.name}", _undo_create(target))
return f"Folder created: {target.name}"
except Exception as e:
return f"Could not create folder: {e}"
@@ -189,7 +283,12 @@ def delete_file(path: str, name: str = "") -> str:
if target.resolve() in {p.resolve() for p in protected}:
return f"Protected directory, cannot delete: {target.name}"
return _safe_trash(target)
original = target.resolve()
result = _safe_trash(target)
if result.startswith("Moved to Trash"):
push_undo(f"deleted {original.name}",
lambda p=original: _restore_from_trash(p))
return result
except PermissionError:
return f"Permission denied: {path}"
@@ -216,7 +315,10 @@ def move_file(path: str, name: str = "", destination: str = "") -> str:
dst = dst / src.name
dst.parent.mkdir(parents=True, exist_ok=True)
origin = src.resolve()
shutil.move(str(src), str(dst))
push_undo(f"moved {origin.name} to {dst.parent.name}/",
_undo_move(origin, dst.resolve()))
return f"Moved: {src.name} → {dst.parent.name}/"
except Exception as e:
@@ -248,6 +350,18 @@ def copy_file(path: str, name: str = "", destination: str = "") -> str:
else:
shutil.copy2(str(src), str(dst))
# The undo for a copy is deleting the copy — never the original.
_copy = dst.resolve()
def _undo_copy():
if not _copy.exists():
return f"The copy '{_copy.name}' is already gone."
if _copy.is_dir():
shutil.rmtree(_copy)
else:
_copy.unlink()
return f"Removed the copy in {_copy.parent.name}/."
push_undo(f"copied {src.name} to {dst.parent.name}/", _undo_copy)
return f"Copied: {src.name} → {dst.parent.name}/"
except Exception as e:
@@ -269,7 +383,10 @@ def rename_file(path: str, name: str = "", new_name: str = "") -> str:
if new_path.exists():
return f"A file named '{new_name}' already exists here."
old_path = target.resolve()
target.rename(new_path)
push_undo(f"renamed {old_path.name} to {new_name}",
_undo_move(old_path, new_path.resolve()))
return f"Renamed: {target.name} → {new_name}"
except Exception as e:
@@ -304,11 +421,31 @@ def write_file(path: str, name: str = "", content: str = "",
if not _is_safe_path(target):
return f"Access denied: {target}"
target.parent.mkdir(parents=True, exist_ok=True)
# Snapshot before writing. None means "did not exist", which is a
# different undo (delete it) from "existed and had this in it".
previous: str | None = None
undoable = True
if target.exists():
try:
if target.stat().st_size > _UNDO_CONTENT_LIMIT:
undoable = False # too large to hold in memory
else:
previous = target.read_text(encoding="utf-8", errors="ignore")
except Exception:
undoable = False # binary, locked, unreadable
mode = "a" if append else "w"
with open(target, mode, encoding="utf-8") as f:
f.write(content)
action = "Appended to" if append else "Written to"
return f"{action}: {target.name}"
if undoable:
push_undo(f"wrote to {target.name}", _undo_write(target, previous))
return f"{action}: {target.name}"
return (f"{action}: {target.name}. "
f"(Too large to keep a copy of the old contents, so this one "
f"cannot be undone.)")
except Exception as e:
return f"Could not write file: {e}"
@@ -415,6 +552,7 @@ def organize_desktop() -> str:
desktop = _get_desktop()
moved, skipped = [], []
journal: list[tuple[Path, Path]] = [] # (where it was, where it went)
try:
for item in desktop.iterdir():
@@ -438,9 +576,37 @@ def organize_desktop() -> str:
skipped.append(item.name)
continue
origin = item.resolve()
shutil.move(str(item), str(new_path))
journal.append((origin, new_path.resolve()))
moved.append(f"{item.name} → {target_dir.name}/")
# One command, dozens of moves — so one undo that reverses all of them.
# Without this, "organize my desktop" is the single least reversible
# thing the assistant can do to a person's files, and it was completely
# ungated.
if journal:
def _undo_organize(entries=tuple(journal)):
restored = 0
for origin, moved_to in entries:
try:
if moved_to.exists():
origin.parent.mkdir(parents=True, exist_ok=True)
shutil.move(str(moved_to), str(origin))
restored += 1
except Exception as e:
print(f"[file] undo organize: {moved_to.name}: {e}")
# Clear away the folders we created, but only while they are
# empty — anything the user put in since stays.
for folder in {m.parent for _o, m in entries}:
try:
if folder.exists() and folder.is_dir() and not any(folder.iterdir()):
folder.rmdir()
except Exception:
pass
return f"{restored} file(s) put back on the desktop."
push_undo(f"organized the desktop ({len(journal)} files)", _undo_organize)
result = f"Desktop organized: {len(moved)} files moved."
if moved:
preview = moved[:8]
+127 -124
View File
@@ -1,124 +1,127 @@
"""
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
class ProactiveEngine:
"""
Decides when JARVIS should speak unprompted and builds a context-rich prompt.
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 = 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:
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
# ── Prompt builder ─────────────────────────────────────────────────────────
def build_prompt(
self,
memory: dict,
monitors: list[str] | None = None,
recent_turns: list[str] | None = None,
) -> str:
"""
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")
# 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} ({period})",
"",
"Context about this person:",
mem_str,
monitor_ctx,
recent_ctx,
"",
"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).",
])
"""
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
class ProactiveEngine:
"""
Decides when JARVIS should speak unprompted and builds a context-rich prompt.
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 = 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:
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
# ── Prompt builder ─────────────────────────────────────────────────────────
def build_prompt(
self,
memory: dict,
monitors: list[str] | None = None,
recent_turns: list[str] | None = None,
) -> str:
"""
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")
# 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} ({period})",
"",
"Context about this person:",
mem_str,
monitor_ctx,
recent_ctx,
"",
"Task:",
focus,
"",
"Rules:",
"- Speak the language this person actually uses: the one in the "
"recent conversation above, or the remembered one if there is no "
"conversation yet. Never default to English because these "
"instructions are in 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).",
])
+1 -1
View File
@@ -43,7 +43,7 @@ def _log_gemini_failure(context: str, exc: Exception) -> None:
"""Log a Gemini failure — silently when it is just the expected cooldown."""
if isinstance(exc, _QuotaCooldown):
return # announced once when the breaker tripped; not a warning
print(f"[WebSearch] ⚠️ {context} failed ({exc}) — using DDG instead")
print(f"[WebSearch] \u26a0\ufe0f {context} failed ({exc}) — using DDG instead")
def _run_bounded(fn, timeout: float, label: str = "task"):