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}."