Add files via upload

This commit is contained in:
FatihMakes authored and GitHub committed 2026-09-09 18:56:03 +03:00
1 parent 234dd79273
commit d929ef03cf
30 files changed
+3802 -2702

No files matched your search

+193
View File
@@ -0,0 +1,193 @@
"""
Action discovery, validation, and dispatch — the built-in twin of plugin_loader.
Every actions/*.py that exposes a module-level ``TOOL`` dict is auto-discovered
here, exactly like a drop-in plugin, so main.py never has to hardcode a tool
declaration or a dispatch branch for it. Adding a new bundled action is then the
same one-file operation as writing a plugin: define ``TOOL`` and a handler.
``TOOL`` shape (see actions/open_app.py for a live example):
TOOL = {
"name": "open_app", # unique, ^[a-zA-Z_][a-zA-Z0-9_]{0,63}$
"description": "...", # what Gemini reads to route the call
"parameters": {"type": "OBJECT", ...}, # Gemini function-declaration schema
"handler": open_app, # the callable to run
}
The handler is invoked through signature introspection: it receives ``parameters``
plus whichever of ``player`` / ``speak`` / ``response`` / ``session_memory`` it
actually declares — so existing action signatures work unchanged.
Discovery runs once at startup; import errors, validation errors, and name
collisions are logged and the offending file is skipped — they NEVER raise out
of discover_actions() and never abort the scan of the remaining files.
"""
from __future__ import annotations
import importlib.util
import inspect
import re
import sys
import traceback
from dataclasses import dataclass, field
from pathlib import Path
from typing import Callable, Optional
_NAME_RE = re.compile(r"^[a-zA-Z_][a-zA-Z0-9_]{0,63}$")
_DEFAULT_PARAMS = {"type": "OBJECT", "properties": {}}
_CTX_KEYS = ("player", "speak", "response", "session_memory")
@dataclass
class ActionRecord:
name: str
description: str = ""
parameters: dict = field(default_factory=lambda: dict(_DEFAULT_PARAMS))
handler: Optional[Callable] = None
file: str = ""
valid: bool = False
error: str = ""
class ActionRegistry:
def __init__(self, actions: dict[str, ActionRecord], logger: Callable[[str], None]):
self._actions = actions # name -> ActionRecord, VALID entries only
self._all_records: list[ActionRecord] = []
self._logger = logger
# -- called by main.py at LiveConnectConfig build time --
def get_tool_declarations(self) -> list[dict]:
return [
{"name": rec.name, "description": rec.description, "parameters": rec.parameters}
for rec in self._actions.values()
]
def has(self, name: str) -> bool:
return name in self._actions
def names(self) -> set[str]:
return set(self._actions.keys())
# -- called by main.py from _execute_tool --
def run(self, name: str, parameters: dict, ctx: dict | None = None) -> str:
rec = self._actions.get(name)
if rec is None or not rec.valid:
return f"Action '{name}' is not available."
try:
return _call_handler(rec.handler, parameters, ctx or {}) or "Done."
except Exception as e:
self._logger(f"Action '{name}' crashed during run(): {e}")
traceback.print_exc()
return f"Tool '{name}' failed: {e}"
def _call_handler(fn: Callable, parameters: dict, ctx: dict) -> str:
"""Invoke the handler passing only the context kwargs it actually declares
(or all of them if it has **kwargs), so each action's existing signature
works unchanged."""
sig = inspect.signature(fn)
has_var_kw = any(p.kind == inspect.Parameter.VAR_KEYWORD for p in sig.parameters.values())
kwargs = {}
for key in _CTX_KEYS:
if has_var_kw or key in sig.parameters:
kwargs[key] = ctx.get(key)
return fn(parameters=parameters, **kwargs)
def _validate(module, filename: str) -> ActionRecord:
"""Returns an ActionRecord; .valid=False + .error set on any problem. Never raises."""
tool = getattr(module, "TOOL", None)
if not isinstance(tool, dict):
return ActionRecord(name=Path(filename).stem, file=filename,
error="No module-level TOOL dict (not a discoverable action).")
name = tool.get("name")
if not isinstance(name, str) or not _NAME_RE.match(name):
return ActionRecord(name=str(name or Path(filename).stem), file=filename,
error="TOOL['name'] missing or not a valid identifier.")
description = tool.get("description")
if not isinstance(description, str) or not description.strip():
return ActionRecord(name=name, file=filename,
error="TOOL['description'] missing or empty.")
parameters = tool.get("parameters", _DEFAULT_PARAMS)
if not isinstance(parameters, dict) or parameters.get("type") != "OBJECT":
return ActionRecord(name=name, file=filename,
error="TOOL['parameters'] must be a dict with \"type\": \"OBJECT\".")
handler = tool.get("handler")
if not callable(handler):
return ActionRecord(name=name, file=filename,
error="TOOL['handler'] missing or not callable.")
return ActionRecord(name=name, description=description.strip(), parameters=parameters,
handler=handler, file=filename, valid=True, error="")
def discover_actions(actions_dir: Path, reserved_names: set[str] | None = None,
logger: Callable[[str], None] = print) -> ActionRegistry:
"""
Scans actions_dir for *.py files (skips files starting with '_'). A file is
only treated as an action if it exposes a module-level TOOL dict; files
without one (shared helpers, capture-only modules) are silently ignored.
Import/validation errors and name collisions are logged and the file is
skipped — they NEVER raise out of this function.
"""
reserved = reserved_names or set()
actions_dir.mkdir(parents=True, exist_ok=True)
valid: dict[str, ActionRecord] = {}
all_records: list[ActionRecord] = []
files = sorted(actions_dir.glob("*.py"), key=lambda p: p.name) # deterministic order
for path in files:
if path.name.startswith("_"):
continue
try:
module_name = f"actions.{path.stem}"
# Reuse the already-imported module when present so handlers are the
# same objects the rest of the app holds.
module = sys.modules.get(module_name)
if module is None:
spec = importlib.util.spec_from_file_location(module_name, path)
if spec is None or spec.loader is None:
raise ImportError("could not build import spec")
module = importlib.util.module_from_spec(spec)
sys.modules[module_name] = module
try:
spec.loader.exec_module(module)
except Exception:
sys.modules.pop(module_name, None)
raise
if getattr(module, "TOOL", None) is None:
continue # not an action file — a helper/capture-only module
rec = _validate(module, path.name)
if rec.valid and rec.name in reserved:
rec = ActionRecord(name=rec.name, file=path.name,
error=f"Name '{rec.name}' collides with a reserved core tool — rejected.")
elif rec.valid and rec.name in valid:
other = valid[rec.name].file
rec = ActionRecord(name=rec.name, file=path.name,
error=f"Name '{rec.name}' already used by action '{other}' — rejected.")
except Exception as e:
rec = ActionRecord(name=path.stem, file=path.name,
error=f"Failed to load: {e}")
traceback.print_exc()
all_records.append(rec)
if rec.valid:
valid[rec.name] = rec
logger(f"Action loaded: {rec.name} ({path.name})")
else:
# Only log a rejection if the file actually tried to be an action.
logger(f"Action rejected: {path.name} — {rec.error}")
registry = ActionRegistry(valid, logger)
registry._all_records = all_records
logger(f"Action discovery complete: {len(valid)} active.")
return registry
+35 -2
View File
@@ -17,7 +17,7 @@ from dataclasses import dataclass, field
from pathlib import Path
from typing import Callable, Optional
from memory.config_manager import get_plugin_enabled
from memory.config_manager import get_plugin_enabled, get_plugin_config
_NAME_RE = re.compile(r"^[a-zA-Z_][a-zA-Z0-9_]{0,63}$")
_DEFAULT_PARAMS = {"type": "OBJECT", "properties": {}}
@@ -32,6 +32,7 @@ class PluginRecord:
file: str = ""
valid: bool = False
error: str = ""
settings: Optional[dict] = None # optional PLUGIN_SETTINGS schema (config fields)
class PluginRegistry:
@@ -69,6 +70,32 @@ class PluginRegistry:
traceback.print_exc()
return f"Sir, the '{name}' plugin failed: {e}"
# -- called by ui.py's settings tab to render per-plugin config forms --
def settings_schemas(self) -> list[dict]:
"""One entry per settings SECTION, for enabled plugins that declare a
PLUGIN_SETTINGS schema. Sections are deduped by namespace so a suite of
plugins sharing one namespace (e.g. the printer trio) shows a single
form. Current stored values are merged in so the UI can pre-fill fields.
"""
seen: set[str] = set()
out: list[dict] = []
for name, rec in self._plugins.items():
if not rec.settings or not get_plugin_enabled(name):
continue
ns = rec.settings.get("namespace") or rec.name
if ns in seen:
continue
seen.add(ns)
out.append({
"plugin": rec.name,
"namespace": ns,
"title": rec.settings.get("title") or rec.name,
"fields": rec.settings.get("fields", []),
"values": get_plugin_config(ns),
"action": rec.settings.get("action"), # optional test/connect button
})
return out
# -- called by ui.py's Plugin Manager overlay --
def list_for_ui(self) -> list[dict]:
out = []
@@ -125,8 +152,14 @@ def _validate(module, filename: str) -> PluginRecord:
return PluginRecord(name=name, file=filename,
error="Missing callable run(parameters, ...) function.")
# Optional, self-describing settings schema (rendered by the settings UI).
# A malformed schema is ignored, never fatal — the plugin still loads.
settings = getattr(module, "PLUGIN_SETTINGS", None)
if not (isinstance(settings, dict) and isinstance(settings.get("fields"), list)):
settings = None
return PluginRecord(name=name, description=description.strip(), parameters=parameters,
run=run_fn, file=filename, valid=True, error="")
run=run_fn, file=filename, valid=True, error="", settings=settings)
def discover_plugins(plugins_dir: Path, core_tool_names: set[str],
+7
View File
@@ -14,6 +14,13 @@ Response time: Respond as fast as you can.
Act: Always act like Jarvis from Iron Man — professional, efficient, slightly witty. (greet the user warmly in their own language)
Length: Match response length to the task. Briefing = short. Complex analysis = thorough.
ACKNOWLEDGE BEFORE A TASK TAKES A MOMENT:
When the user asks for something whose tool needs more than an instant to finish — reading/analyzing an uploaded file, web/news/research/price searches, finding flights, writing or building code, building a project, updating a game — FIRST say exactly ONE short, natural sentence, in the USER'S OWN language, that fits THIS specific request, and THEN call the tool in the same turn. Compose that sentence fresh each time, in your own words, in the language of the conversation — naming what you are about to do. Do NOT reuse a remembered phrase and do NOT lift wording out of a tool's description: anything written there is an explanation for you, not a line for you to say, and repeating it can put you in the wrong language. When the tool returns, deliver the result.
- Purpose: the user should hear you react instantly, so they never feel they're waiting on a frozen assistant.
- Instant actions (opening an app, volume, brightness, a single keypress, a quick setting) need NO acknowledgment — just do them.
- Do NOT pre-acknowledge for screen_process / vision — that flow already tells the user you are looking.
- Keep it to ONE short sentence and vary the wording every time; never a fixed template. It must not talk over the tool's own output.
LANGUAGE:
The language of your reply is the language of the user's MOST RECENT message. Nothing else decides it — not what is stored in memory, not the language of these instructions, not the language of a tool's result.
Memory may say which language this person has used before. That is a record of the past, not an instruction for now: if they write or speak in another language today, answer in that one.
+202
View File
@@ -0,0 +1,202 @@
"""
Local wake-word detection for JARVIS ("Hey Jarvis").
Design goals:
• ZERO cost when the feature is off — openwakeword is imported ONLY inside
start()/install helpers, never at module load. If the user never enables
wake word, none of this touches the app.
• ZERO latency on the audio path — the microphone callback only ever does a
cheap, non-blocking queue push (feed()); the actual model inference runs in
this module's own background thread, so the real-time audio thread and the
Gemini stream are never slowed.
• Fully local & offline — audio fed here never leaves the machine; there is no
network call except the one-time model download the user triggers from the UI.
openwakeword ships small ONNX models (a few MB each) and runs comfortably on a
CPU. The pretrained wake phrase used here is "Hey Jarvis".
"""
from __future__ import annotations
import queue
import subprocess
import sys
import threading
from pathlib import Path
from typing import Callable
# Pretrained openwakeword model that listens for "Hey Jarvis".
WAKE_MODEL = "hey_jarvis"
# Score in [0,1]; above this counts as a detection. Tunable per environment.
DEFAULT_THRESHOLD = 0.5
# Mic frames arrive at 16 kHz int16; this is just the detector's input rate.
SAMPLE_RATE = 16000
def is_installed() -> bool:
"""True if the openwakeword package is importable (no model check)."""
try:
import importlib.util
return importlib.util.find_spec("openwakeword") is not None
except Exception:
return False
def is_ready() -> bool:
"""True if openwakeword is installed AND its model files are present on disk.
This is a cheap, DETERMINISTIC file-existence check. It deliberately does NOT
construct a Model to probe readiness — doing that is slow and, worse, can clash
with the detector's own Model when it's already running, which intermittently
returned False and made the UI flicker to 'not downloaded'. Never raises.
"""
if not is_installed():
return False
try:
import openwakeword
models_dir = Path(openwakeword.__file__).resolve().parent / "resources" / "models"
if not models_dir.is_dir():
return False
has_wake = (any(models_dir.glob(f"{WAKE_MODEL}*.onnx"))
or any(models_dir.glob(f"{WAKE_MODEL}*.tflite")))
has_mel = (any(models_dir.glob("melspectrogram*.onnx"))
or any(models_dir.glob("melspectrogram*.tflite")))
has_emb = (any(models_dir.glob("embedding_model*.onnx"))
or any(models_dir.glob("embedding_model*.tflite")))
return bool(has_wake and has_mel and has_emb)
except Exception:
return False
def install_and_download(logger: Callable[[str], None] = print) -> tuple[bool, str]:
"""
One-click setup for the UI button: pip-install openwakeword if missing, then
download the wake model. Returns (ok, message). Never raises — every failure
is reported through the returned message and the logger.
"""
try:
if not is_installed():
logger("Wake word: installing openwakeword (one-time)…")
r = subprocess.run(
[sys.executable, "-m", "pip", "install", "openwakeword"],
capture_output=True, text=True,
)
if r.returncode != 0:
tail = (r.stderr or r.stdout or "").strip().splitlines()[-1:] or [""]
return False, f"pip install failed: {tail[0][:160]}"
# Download the pretrained melspectrogram/embedding + wake models.
logger("Wake word: downloading models…")
try:
import openwakeword.utils as _u
try:
_u.download_models([WAKE_MODEL])
except TypeError:
_u.download_models() # older signature downloads the default set
except Exception as e:
return False, f"model download failed: {e}"
if not is_ready():
return False, "installed, but the wake model could not be loaded."
logger("Wake word: ready.")
return True, "Wake word installed and ready."
except Exception as e:
return False, f"setup error: {e}"
class WakeWordDetector:
"""
Runs the wake model in a dedicated thread. The mic thread calls feed() with
raw int16 frames; detections invoke on_detect() (called from this thread —
the callback must marshal to whatever loop/UI it needs).
"""
def __init__(self, on_detect: Callable[[], None],
threshold: float = DEFAULT_THRESHOLD,
logger: Callable[[str], None] = print):
self._on_detect = on_detect
self._threshold = threshold
self._logger = logger
self._queue: queue.Queue = queue.Queue(maxsize=50)
self._thread: threading.Thread | None = None
self._running = False
self._model = None
self._ready = False
def start(self) -> bool:
"""Load the model and spawn the inference thread. Returns True on success.
Safe to call again — a no-op if already running. Never raises."""
if self._running:
return True
try:
from openwakeword.model import Model
self._model = Model(wakeword_models=[WAKE_MODEL], inference_framework="onnx")
except Exception as e:
self._logger(f"Wake word: could not load model — {e}")
self._model = None
return False
self._running = True
self._ready = True
self._thread = threading.Thread(target=self._loop, daemon=True, name="WakeWordThread")
self._thread.start()
self._logger("Wake word: listening for 'Hey Jarvis'.")
return True
def stop(self) -> None:
self._running = False
# unblock the thread if it's waiting on the queue
try:
self._queue.put_nowait(None)
except Exception:
pass
self._model = None
self._ready = False
@property
def ready(self) -> bool:
return self._ready
def feed(self, frame_int16) -> None:
"""Called from the mic callback (real-time thread). Must stay cheap and
never block — the frame is copied and dropped if the queue is backed up."""
if not self._running:
return
try:
# frame_int16 is a numpy int16 array (possibly 2-D mono) — flatten to 1-D
data = frame_int16[:, 0].copy() if getattr(frame_int16, "ndim", 1) > 1 else frame_int16.copy()
self._queue.put_nowait(data)
except queue.Full:
pass
except Exception:
pass
def _loop(self) -> None:
import numpy as np
while self._running:
try:
frame = self._queue.get()
if frame is None or not self._running:
break
scores = self._model.predict(np.asarray(frame, dtype=np.int16))
score = 0.0
if isinstance(scores, dict):
# match the jarvis model regardless of exact key suffix
for k, v in scores.items():
if "jarvis" in k.lower():
score = max(score, float(v))
if score == 0.0 and scores:
score = max(float(v) for v in scores.values())
if score >= self._threshold:
# drain any backlog so we don't double-fire on the same utterance
self._drain()
try:
self._on_detect()
except Exception as e:
self._logger(f"Wake word: on_detect error — {e}")
except Exception as e:
self._logger(f"Wake word: inference error — {e}")
def _drain(self) -> None:
try:
while True:
self._queue.get_nowait()
except Exception:
pass