Add files via upload

This commit is contained in:
FatihMakes authored and GitHub committed 2026-09-16 18:48:54 +03:00
1 parent b3f7708e0e
commit 476a9c09d6
28 files changed
+8099 -2459

No files matched your search

+618 -79
View File
@@ -14,25 +14,25 @@ if _platform.system() == "Windows":
_subprocess.Popen = _Popen
# ─────────────────────────────────────────────────────────────────────────────
# ── Console encoding ─────────────────────────────────────────────────────────
# Status lines in this app carry emoji and arrows ("📤 file_controller → Moved:
# a.txt → Documents/"). On a non-UTF-8 console — cp1254 on a Turkish Windows,
# cp1251 on a Russian one, cp932 on a Japanese one — printing one of those
# raises UnicodeEncodeError, and because the print sits after the tool's own
# try/except, the exception escapes into the receive loop and takes the session
# down. The assistant dies on a log line.
#
# Reconfiguring costs nothing and makes the app start the same way in every
# locale. `errors="replace"` is the belt and braces — a console that genuinely
# cannot render a glyph shows a box instead of killing the process.
# ── Console must survive non-UTF-8 code pages ────────────────────────────────
# Every status line in this file carries an emoji, and on a legacy Windows
# console the active code page is the system one — cp1254 in Turkey, cp1251 in
# Russia, cp932 in Japan. Printing an emoji there raises UnicodeEncodeError, and
# because most of these prints sit inside the receive loop it takes the session
# down on startup. Reconfiguring to UTF-8 with a replacement fallback costs
# nothing and makes the app launch the same way in every locale.
import sys as _sys
for _stream in (_sys.stdout, _sys.stderr):
for _stream in ("stdout", "stderr"):
try:
_stream.reconfigure(encoding="utf-8", errors="replace")
_s = getattr(_sys, _stream, None)
if _s is not None and hasattr(_s, "reconfigure"):
_s.reconfigure(encoding="utf-8", errors="replace")
except Exception:
pass
pass # pythonw / redirected pipes / anything exotic — never fatal
# ─────────────────────────────────────────────────────────────────────────────
import asyncio
import re
@@ -69,13 +69,17 @@ from actions.background_monitor import (
)
from actions.web_search import _news as _fetch_news_sync
from memory.config_manager import (
get_brief_enabled, get_voice, get_wake_word_enabled, save_wake_word_enabled, get_input_device, get_output_device,
get_brief_enabled, get_media_resolution, get_proactive_audio_enabled,
get_push_to_talk_enabled, get_thinking_enabled, get_turn_tuning, get_voice,
get_wake_word_enabled, save_wake_word_enabled, get_input_device, get_output_device,
)
from core.plugin_loader import discover_plugins
from core import undo as undo_stack
from core import confirm as confirm_gate
from core import audio_devices
from core.action_loader import discover_actions
from core.echo import EchoGuard
from core.viseme import VisemeStream
from core.wake_word import (
WakeWordDetector, is_ready as wake_is_ready, install_and_download as wake_install,
)
@@ -120,6 +124,164 @@ def _pcm_level(samples) -> float:
return min(1.0, (rms - _LEVEL_FLOOR) / (_LEVEL_FULL - _LEVEL_FLOOR))
# ── Viseme extraction ─────────────────────────────────────────────────────────
# The avatar's mouth used to be driven by one RMS value per ~200 ms write batch,
# which is five updates a second averaged over a fifth of a second — it could
# only ever flap. These read the *shape* of each 20 ms slice straight from the
# spectrum of the audio being played, so no transcript, no forced alignment and
# no language assumption: it works the same for Turkish and English.
#
# Two numbers come out. Openness tracks the first formant — F1 climbs as the jaw
# drops, so /a/ reads open and /i/ or /u/ read closed. Width tracks the second —
# F2 is high for spread vowels (/i/, /e/) and low for rounded ones (/u/, /o/).
# Extra time beyond the device's reported output latency before the microphone
# is trusted again: covers room decay and the speaker's own settling.
_TAIL_MARGIN = 0.25
_VIS_WIN = 1024 # ~43 ms analysis window at 24 kHz: enough for formants
_VIS_HOP = 480 # 20 ms between frames, i.e. 50 shapes a second
# Delay from handing the first bytes of a reply to an already-running output
# stream to hearing them: one callback period, plus whatever the DAC adds.
_FIRST_SOUND = CHUNK_SIZE / RECEIVE_SAMPLE_RATE # ~43 ms
# How far past the device's own buffer the mouth's timeline may drift before it
# is re-anchored. The buffer is the hard limit on how much audio can be queued
# ahead, so anything beyond it plus a margin for clock error is impossible.
_CURSOR_SLACK = 0.15
# Erring early is the safe direction. A viewer tolerates a mouth that moves
# slightly before the sound far better than one that moves after it — the
# broadcast limits are about 45 ms of lag against 125 ms of lead — so where
# this is uncertain it is biased to lead.
def _pcm_visemes(samples, sr: int = 24000):
"""Slice a PCM block into (level, openness, width) frames, one per 20 ms.
Returns [] on anything unexpected — the mouth falls back to loudness-only
articulation rather than the caller having to handle an error.
"""
try:
x = np.asarray(samples, dtype=np.float32)
if x.size < _VIS_WIN:
return []
win = np.hanning(_VIS_WIN).astype(np.float32)
freqs = np.fft.rfftfreq(_VIS_WIN, 1.0 / sr)
b_f1_lo = (freqs >= 150) & (freqs < 450) # F1 of close vowels
b_f1_hi = (freqs >= 450) & (freqs < 1100) # F1 of open vowels
b_f2_bk = (freqs >= 600) & (freqs < 1300) # F2 of rounded vowels
b_f2_fr = (freqs >= 1700) & (freqs < 3200) # F2 of spread vowels
b_hiss = (freqs >= 3800) & (freqs < 8000) # fricatives
# One frame per hop across the *whole* block. Stepping only while a full
# window fits stopped 1024 - 480 samples short of the end, so a 200 ms
# batch yielded 160 ms of schedule: the mouth ran out of frames before
# the audio ran out of sound, and each batch no longer lined up with the
# end of the one before it. Losing 20 % of every batch is most of why
# the mouth did not track the words.
out = []
for start in range(0, x.size, _VIS_HOP):
# The level gates closures, so it is measured over exactly this
# 20 ms and never looks ahead. The spectrum needs a longer window
# to resolve formants and may be short-filled at the very end.
level = _pcm_level(x[start:start + _VIS_HOP])
seg = x[start:start + _VIS_WIN]
if seg.size < _VIS_WIN:
seg = np.concatenate([seg, np.zeros(_VIS_WIN - seg.size,
dtype=np.float32)])
if level <= 0.0:
out.append((0.0, 0.0, 0.0))
continue
mag = np.abs(np.fft.rfft((seg - seg.mean()) * win))
f1l, f1h = float(mag[b_f1_lo].sum()), float(mag[b_f1_hi].sum())
f2b, f2f = float(mag[b_f2_bk].sum()), float(mag[b_f2_fr].sum())
hiss = float(mag[b_hiss].sum())
openness = f1h / (f1l + f1h + 1e-6)
width = (f2f - f2b) / (f2f + f2b + 1e-6)
# A wide-open jaw physically cannot purse, so openness damps width.
# /a/ has a low enough F2 to read as "rounded" on the bands alone;
# letting openness suppress the width term is what keeps an open
# vowel from pursing.
width *= (1.0 - openness) ** 0.8
# Fricatives are formed with a nearly closed mouth.
h = hiss / (f1l + f1h + f2b + f2f + hiss + 1e-6)
openness *= 1.0 - 0.65 * min(1.0, h * 2.5)
out.append((level,
float(min(1.0, max(0.0, openness))),
float(min(1.0, max(-1.0, width)))))
return out
except Exception:
return []
def _describe_tools(declarations) -> str:
"""One line per capability, straight from the live tool declarations.
Derived rather than written down: the action and plugin registries are
discovered at startup, so whatever the user has installed is what the model
is told it can do. Adding a plugin extends this by itself, and removing one
stops the model from claiming an ability it no longer has.
"""
lines = []
for d in declarations or ():
try:
name = d.get("name") if isinstance(d, dict) else getattr(d, "name", None)
desc = (d.get("description") if isinstance(d, dict)
else getattr(d, "description", "")) or ""
except Exception:
continue
if not name:
continue
desc = " ".join(str(desc).split())
lines.append(f"- {name}: {desc[:150]}" if desc else f"- {name}")
return "\n".join(lines)
def _describe_limits(has_vision: bool, has_mic: bool) -> str:
"""The other half of self-knowledge: what is out of reach, and why.
Derived from how the program is actually built, not from a list of refusals.
A model that knows its boundaries stops improvising around them, and stating
them as architecture rather than as rules keeps the answer honest in any
language.
"""
out = [
"- Anything not listed above is outside your reach. Say so in one clause "
"and offer the nearest thing you can actually do — never mime an action "
"you cannot take, and never report a result you did not get.",
"- You act on this machine only. You cannot reach the user's other "
"devices, accounts or hardware except through the tools listed above.",
"- You remember what is in the memory block and what has been said this "
"session. Anything else you were told before is gone unless it was saved.",
]
if has_vision:
out.append(
"- Your sight is not continuous. You see nothing until you call a "
"vision tool, and then only that single frame at that moment — you "
"cannot watch, monitor or notice something changing on screen.")
else:
out.append("- You have no sight at all in this build.")
if has_mic:
out.append(
"- You hear nothing while the microphone is muted, and you cannot "
"unmute it yourself.")
return "\n".join(out)
def _render_prompt(template: str, values: dict) -> str:
"""Fill {tokens} in the prompt template.
A plain replace rather than str.format: the file is meant to be edited by
hand, and a stray brace in someone's own wording must never take the app
down at startup.
"""
out = template or ""
for key, val in values.items():
out = out.replace("{" + key + "}", str(val))
return out
def _get_api_key() -> str:
with open(API_CONFIG_PATH, "r", encoding="utf-8") as f:
return json.load(f)["gemini_api_key"]
@@ -137,6 +299,22 @@ def _load_system_prompt() -> str:
_CTRL_RE = re.compile(r"<ctrl\d+>", re.IGNORECASE)
# Transcript chunks shorter than this may legitimately repeat ("evet, evet"),
# so only longer ones are treated as duplicates.
_REPEAT_MIN = 12
def _is_repeat_chunk(txt: str, buf: list) -> bool:
"""True if this transcript chunk has already been seen this turn.
Guards against the API re-sending the tail of a response across the several
turn_completes a tool-using turn produces.
"""
if len(txt) < _REPEAT_MIN:
return bool(buf) and txt == buf[-1]
joined = " ".join(buf)
return txt in joined
def _clean_transcript(text: str) -> str:
text = _CTRL_RE.sub("", text)
text = re.sub(r"[\x00-\x08\x0b-\x1f]", "", text)
@@ -366,6 +544,30 @@ class JarvisLive:
self._vision_last_time = 0.0 # monotonic time of last screen_process call (cooldown guard)
self._vision_busy = False # True while a vision capture/inject cycle is in flight
self._interrupted = False # True while draining audio after user interrupt
# Transcript-driven mouth shapes for the avatar. Fed from the receive
# loop as words arrive, drained by the playback loop against the audio.
self._visemes = VisemeStream()
self._last_out_logged = "" # de-dupes a re-sent transcript tail
# Push-to-talk
self._ptt_enabled = False
self._ptt_held = False
self._ptt = None # core.hotkey.PushToTalk
self._out_level = 0.0 # level of the audio being played right now
self._echo = EchoGuard()
# `stream.write()` returns when the buffer accepts the audio, not when the
# speaker has finished with it, so sound is still in the room after the
# speaking flag drops. Streaming the microphone during that gap is how an
# assistant ends up answering itself. Measured from the device rather than
# guessed; see _play_audio.
self._out_latency = 0.20 # seconds, replaced with the real value
self._tail_until = 0.0 # monotonic time the echo tail expires
# Wall-clock time at which the audio written next will begin to sound.
# The mouth is scheduled against this, never against "now": batches are
# handed to the device far faster than they play, so "now" ran the lips
# ahead of the words and cut every schedule short. 0 = nothing playing.
self._play_cursor = 0.0
self.ui.on_push_to_talk = self.set_push_to_talk
self.ui.ptt_hold = self._on_ptt
self.ui.on_text_command = self._on_text_command
self.ui.on_remote_clicked = self._make_remote_key
self.ui.on_interrupt = self.interrupt
@@ -398,6 +600,7 @@ class JarvisLive:
self._session_log: list[str] = [] # conversation turns for end-of-session summary
self._enhanced_live = True # proactive audio; auto-disabled if the server rejects it
self._tuned_live = True # turn-taking / media / thinking knobs; same fallback
_base_dir = Path(__file__).resolve().parent
_inline_names = {t["name"] for t in TOOL_DECLARATIONS}
@@ -416,7 +619,11 @@ class JarvisLive:
self._plugin_registry = discover_plugins(
plugins_dir=_base_dir / "plugins",
core_tool_names=_core_names,
logger=lambda msg: (print(f"[Plugins] {msg}"), self.ui.write_log(f"SYS: {msg}")),
# Console gets the full boot transcript; the activity log gets only
# what the user has to know about. Every plugin loading correctly is
# the expected case and does not belong in their conversation.
logger=lambda msg: print(f"[Plugins] {msg}"),
notify=lambda msg: self.ui.write_log(f"SYS: {msg}"),
)
self.ui.get_plugins = self._plugin_registry.list_for_ui
self.ui.get_plugin_settings = self._plugin_registry.settings_schemas # ⚙ settings tab
@@ -429,6 +636,15 @@ class JarvisLive:
self._awake = not self._wake_enabled
self._wake_detector: WakeWordDetector | None = None
self._wake_sleep_timeout = WAKE_SLEEP_TIMEOUT
# Restore the saved push-to-talk preference. Doing it here rather than
# in __init__ means the hotkey thread only exists once there is a
# session to talk to.
if get_push_to_talk_enabled():
try:
self.set_push_to_talk(True)
except Exception as e:
print(f"[JARVIS] ⚠ Push-to-talk unavailable: {e}")
# UI control surface for the Wake Word settings section.
self.ui.wake_is_ready = wake_is_ready # () -> bool
self.ui.wake_get_state = self._wake_state # () -> dict
@@ -449,7 +665,8 @@ class JarvisLive:
if self._wake_detector is None:
self._wake_detector = WakeWordDetector(
on_detect=self._on_wake_detected,
logger=lambda m: (print(f"[Wake] {m}"), self.ui.write_log(f"SYS: {m}")),
logger=lambda m: print(f"[Wake] {m}"),
notify=lambda m: self.ui.write_log(f"SYS: {m}"),
)
if not self._wake_detector.ready:
return self._wake_detector.start()
@@ -519,7 +736,10 @@ class JarvisLive:
def _ui_wake_install(self) -> tuple[bool, str]:
"""Download openwakeword + the model (runs in a UI worker thread)."""
return wake_install(logger=lambda m: self.ui.write_log(f"SYS: {m}"))
# Triggered by the user pressing the button, so its progress is exactly
# what they are waiting to see.
return wake_install(logger=lambda m: print(f"[Wake] {m}"),
notify=lambda m: self.ui.write_log(f"SYS: {m}"))
def plugin_say(self, instruction: str) -> None:
"""
@@ -625,14 +845,72 @@ class JarvisLive:
self._loop
)
def _tail_active(self) -> bool:
"""True while the speakers may still be finishing our last sentence."""
return time.monotonic() < self._tail_until
def set_speaking(self, value: bool):
with self._speaking_lock:
self._is_speaking = value
if value:
self._tail_until = 0.0
else:
# Hold the guard open across the device's own output latency plus a
# margin for the room. The microphone is NOT muted during it — the
# guard still lets a genuine reply through, so answering instantly
# still works. Only our own echo is dropped.
self._tail_until = time.monotonic() + self._out_latency + _TAIL_MARGIN
if not value:
# The echo history is deliberately NOT cleared here: the tail above
# still needs it to recognise our own voice. It is dropped when the
# tail expires. What the guard learned about the room always stays.
self._out_level = 0.0
if value:
self.ui.set_state("SPEAKING")
elif not self.ui.muted:
self.ui.set_state("LISTENING")
def set_push_to_talk(self, enabled: bool) -> str:
"""Turn hold-to-talk on or off. Returns the scope actually achieved."""
from core.hotkey import PushToTalk
self._ptt_enabled = bool(enabled)
self._ptt_held = False
if not enabled:
if self._ptt is not None:
self._ptt.stop()
self._ptt = None
return "off"
if self._ptt is None:
self._ptt = PushToTalk(self._on_ptt)
scope = self._ptt.start()
# A window-scoped chord is a real limitation, not a detail — say it once
# in the log so nobody wonders why it does nothing while another app is
# focused. Reporting it must never be able to undo the thing it reports.
try:
self.ui.write_log(
f"SYS: Push-to-talk on — hold {self._ptt.label}"
+ ("." if scope == "global"
else " (works while this window is focused)."))
except Exception:
pass
return scope
def _on_ptt(self, held: bool) -> None:
"""Chord pressed or released — may arrive on the hotkey thread."""
self._ptt_held = held
if held:
# Holding the key is also a way to wake it, so push-to-talk works
# without having to say the wake word first.
if self._wake_enabled and not self._awake:
self._awake = True
self._last_user_speech = time.monotonic()
try:
self.ui.set_state("LISTENING" if held else "SLEEPING")
except Exception:
pass
def interrupt(self) -> None:
"""Stop JARVIS mid-speech: drain queued audio and open mic immediately."""
self._interrupted = True
@@ -648,6 +926,9 @@ class JarvisLive:
if drained:
print(f"[JARVIS] ✋ Interrupted — {drained} audio chunks discarded")
self.set_speaking(False)
# The words we were about to mouth are never going to be spoken now.
self._visemes.reset()
self._play_cursor = 0.0 # next batch starts a fresh timeline
if self._turn_done_event:
self._turn_done_event.clear()
self.ui.write_log("SYS: Interrupted — listening...")
@@ -693,14 +974,17 @@ class JarvisLive:
)
# Identity injection — overrides any hardcoded name in prompt.txt
# Address form is a property of the language being spoken, so it is
# stated as a principle rather than a two-language lookup — the model
# already knows the respectful register of whatever language it is in.
_addr = (f"ADDRESS: Always call the user '{_user_name}'."
if _user_name
else "ADDRESS: Address the user with the ordinary respectful form "
"for a superior in the language you are currently speaking — "
"\"sir\" in English, its everyday equivalent in any other "
"language. Never an archaic or aristocratic form, and never "
"the form from a different language than the one you are "
"speaking in this sentence.")
else 'ADDRESS: Address the user with the ordinary respectful form '
'for a superior in the language you are currently speaking — '
'"sir" in English, its everyday equivalent in any other '
'language. Never an archaic or aristocratic form, and never '
'the form from a different language than the one you are '
'speaking in this sentence.')
identity_ctx = (
f"[IDENTITY]\n"
f"Your name is {self._asst_name}. "
@@ -708,6 +992,26 @@ class JarvisLive:
f"{_addr}\n\n"
)
# Everything the model is told about *itself* is derived here, not
# written into prompt.txt: the name comes from config, the platform from
# the host, the capability list from the registries that were just
# discovered. Rename the assistant, add a plugin or move to another OS
# and this follows without anyone editing a prompt.
_all_decls = (TOOL_DECLARATIONS
+ self._action_registry.get_tool_declarations()
+ self._plugin_registry.get_tool_declarations())
_names = {(d.get("name") if isinstance(d, dict) else getattr(d, "name", ""))
for d in _all_decls}
sys_prompt = _render_prompt(sys_prompt, {
"assistant_name": self._asst_name,
"platform": f"{_platform.system()} {_platform.release()}".strip(),
"capabilities": _describe_tools(_all_decls),
"limits": _describe_limits(
has_vision="screen_process" in _names,
has_mic=True,
),
})
parts = [time_ctx, identity_ctx]
if mem_str:
parts.append(mem_str)
@@ -718,11 +1022,7 @@ class JarvisLive:
output_audio_transcription={},
input_audio_transcription={},
system_instruction="\n".join(parts),
tools=[{"function_declarations": (
TOOL_DECLARATIONS
+ self._action_registry.get_tool_declarations()
+ self._plugin_registry.get_tool_declarations()
)}],
tools=[{"function_declarations": _all_decls}],
# Hand back the handle captured from the last session_resumption
# update. `handle=None` is exactly the old behaviour (ask for
# handles, start fresh), so the first connect of a run is unchanged.
@@ -749,9 +1049,67 @@ class JarvisLive:
# support it, and it never reliably detected tone in practice.
# To restore it on a 2.5 native-audio model, add back:
# cfg["enable_affective_dialog"] = True )
cfg["proactivity"] = types.ProactivityConfig(proactive_audio=True)
if get_proactive_audio_enabled():
cfg["proactivity"] = types.ProactivityConfig(proactive_audio=True)
if self._tuned_live:
cfg.update(self._tuning_config())
return types.LiveConnectConfig(**cfg)
def _tuning_config(self) -> dict:
"""The optional knobs, kept apart so one bad field can be dropped wholesale.
Every one of these is a preview-API field. If a future model release
stops accepting any of them the connection fails at setup, so the run
loop turns `_tuned_live` off and reconnects on the plain config rather
than leaving the user with an assistant that will not start.
"""
out: dict = {}
# How long the server waits through a pause before deciding your turn is
# over. This — not the size of the prompt — is what most of the delay
# before a reply actually is, and the default has to suit everybody, so
# it is necessarily cautious.
turn = get_turn_tuning()
if turn.get("enabled", True):
detect = types.AutomaticActivityDetection(
silence_duration_ms=turn["silence_ms"],
prefix_padding_ms=turn["prefix_ms"],
)
if turn["end_sensitivity"] == "high":
detect.end_of_speech_sensitivity = types.EndSensitivity.END_SENSITIVITY_HIGH
elif turn["end_sensitivity"] == "low":
detect.end_of_speech_sensitivity = types.EndSensitivity.END_SENSITIVITY_LOW
if turn["start_sensitivity"] == "high":
detect.start_of_speech_sensitivity = types.StartSensitivity.START_SENSITIVITY_HIGH
elif turn["start_sensitivity"] == "low":
detect.start_of_speech_sensitivity = types.StartSensitivity.START_SENSITIVITY_LOW
out["realtime_input_config"] = types.RealtimeInputConfig(
automatic_activity_detection=detect)
# Screenshots and camera frames are tokenised at this resolution and then
# stay in the session's context. 'medium' keeps on-screen text legible
# for a fraction of a full-resolution frame.
res = get_media_resolution()
if res != "default":
out["media_resolution"] = {
"low": types.MediaResolution.MEDIA_RESOLUTION_LOW,
"medium": types.MediaResolution.MEDIA_RESOLUTION_MEDIUM,
"high": types.MediaResolution.MEDIA_RESOLUTION_HIGH,
}[res]
# Thinking is left at the server default deliberately. Forcing the budget
# to zero was measured on gemini-3.1-flash-live over interleaved trials
# and did not make the first word arrive sooner — this model does not
# appear to deliberate on the Live path, so pinning the field only adds a
# way for a future release to behave differently. Set "thinking_enabled"
# in config/api_keys.json to true to let it reason instead.
if get_thinking_enabled():
out["thinking_config"] = types.ThinkingConfig(thinking_budget=-1)
return out
async def _execute_tool(self, fc) -> types.FunctionResponse:
name = fc.name
args = dict(fc.args or {})
@@ -759,6 +1117,7 @@ class JarvisLive:
print(f"[JARVIS] 🔧 {name} {args}")
self.ui.set_state("THINKING")
if name == "save_memory":
category = args.get("category", "notes")
key = args.get("key", "")
@@ -817,11 +1176,16 @@ class JarvisLive:
print(f"[Vision] 🖥️ Screen: {len(img_b):,} bytes")
_stall = "screen"
self._pending_vision = (img_b, mime_t, user_text, angle)
# The image is attached to this same exchange, so there is
# nothing to stall for and nothing to announce. Asking for an
# acknowledgement here is what produced two spoken answers —
# the model filled that turn by answering the question from
# imagination, then answered it again once it could see.
result = (
f"[VISION_ACTIVE] {_stall.capitalize()} captured. "
f"Immediately say ONE short natural sentence in the user's own language, "
f"telling them you are looking at their {_stall} right now. "
f"Do NOT describe or guess content — the actual image arrives in the NEXT message."
f"[VISION_ACTIVE] {_stall.capitalize()} captured and attached to this "
f"same exchange. Do not acknowledge and do not answer yet — the image "
f"is arriving with this result. Reply once, from what you actually see "
f"in it."
)
elif name == "close_camera":
@@ -898,9 +1262,20 @@ class JarvisLive:
self.ui.set_state("LISTENING")
print(f"[JARVIS] 📤 {name} → {str(result)[:80]}")
# A tool that declared itself NON_BLOCKING also says when its answer may
# re-enter the conversation. Without this the model finishes whatever it
# was saying and then reads the result out on top of it — which, for
# something like a phone call already ringing, is exactly the noise the
# non-blocking call was meant to avoid. Tools that declared nothing get
# the API default and behave as they always have.
_sched = (self._action_registry.scheduling(name)
or self._plugin_registry.scheduling(name))
_extra = {"scheduling": _sched} if _sched else {}
return types.FunctionResponse(
id=fc.id, name=name,
response={"result": result}
response={"result": result},
**_extra
)
async def _send_realtime(self):
@@ -937,7 +1312,52 @@ class JarvisLive:
return
with self._speaking_lock:
jarvis_speaking = self._is_speaking
if not jarvis_speaking and not self.ui.muted and not self._phone_active:
# ── Barge-in ─────────────────────────────────────────────────────
# While JARVIS talks the mic is not streamed, but it is still worth
# listening to locally: if the user starts speaking, cut the answer
# short the way a person would stop when interrupted.
#
# The whole difficulty is echo — on speakers the mic hears JARVIS.
# So the test is not "is the mic loud" but "is the mic louder than
# the echo of what we are playing right now", sustained long enough
# that a cough or a keystroke cannot trigger it.
if jarvis_speaking:
# Nothing is streamed while JARVIS talks.
#
# Interrupting by voice used to live here: `EchoGuard` can pick a
# user out from under our own echo, and `core/echo.py` still does
# that for the tail below. Re-enabling is small — classify each
# block here and call interrupt() after `required_blocks` of
# agreement — but it depends on the listener's room, so it stays
# out until it can be tried on real hardware.
return
# ── Echo tail ────────────────────────────────────────────────────
# The speaking flag has dropped but the speakers have not finished.
# Sending this to the model is how an assistant hears itself, decides
# it was addressed, and answers its own last sentence. The microphone
# stays OPEN — the guard only drops blocks that are our own voice, so
# replying the instant it stops still works.
if self._tail_active():
try:
if not self._echo.is_user_speech(
indata, SEND_SAMPLE_RATE, _pcm_level(indata)):
return
self._tail_until = 0.0 # a real voice ends the tail early
except Exception:
return
elif self._echo._hist:
self._echo.reset()
# ── Push-to-talk ─────────────────────────────────────────────────
# When it is on the microphone is closed by default and the chord
# opens it, which is the whole point: nothing leaves the machine
# unless you are holding the key.
if self._ptt_enabled and not self._ptt_held:
return
if not self.ui.muted and not self._phone_active:
data = indata.tobytes()
loop.call_soon_threadsafe(
self.out_queue.put_nowait,
@@ -993,6 +1413,49 @@ class JarvisLive:
print(f"[JARVIS] ❌ Mic: {e}")
raise
async def _flush_pending_vision(self) -> bool:
"""Send a captured frame immediately after its tool response.
The frame is already in hand by the time `screen_process` returns — the
capture happened inside the tool call. The old flow still made the model
speak a turn first and only injected the image on that turn's
turn_complete, which cost a whole extra round trip AND produced two
spoken answers: one improvised without the picture, then the real one.
Sending it here means the model has the tool result and the image before
it generates anything, so the user gets one answer, sooner.
"""
if not (self._pending_vision and self.session):
return False
import base64 as _b64
img_b, mime_t, question, angle = self._pending_vision
self._pending_vision = None
b64 = _b64.b64encode(img_b).decode("ascii")
print(f"[Vision] 📤 {len(img_b):,} bytes (angle={angle}) → main session")
# Label the source. Without it the image arrives carrying nothing but
# the user's own sentence, and a screenshot of this app — which has a
# face in the middle of it — got read as a photo of the user. What the
# label *means* is explained once, in the generated [SELF] block.
src = ("[IMAGE SOURCE: WEBCAM]" if angle == "camera"
else "[IMAGE SOURCE: SCREEN CAPTURE]")
await self.session.send_client_content(
turns={"role": "user", "parts": [
{"inline_data": {"mime_type": mime_t, "data": b64}},
{"text": f"{src}\n\n{question}"},
]},
turn_complete=True,
)
if self._vision_cam_active:
# Camera: stay busy until JARVIS has finished speaking the answer,
# then close the preview.
self._vision_cam_active = False
self._vision_close_pending = True
else:
self._vision_busy = False
return True
async def _receive_audio(self):
print("[JARVIS] 👂 Recv started")
out_buf, in_buf = [], []
@@ -1032,8 +1495,20 @@ class JarvisLive:
if sc.output_transcription and sc.output_transcription.text:
txt = _clean_transcript(sc.output_transcription.text)
if txt and txt != (out_buf[-1] if out_buf else ""):
# A turn that involves a tool call passes through
# several turn_completes, and the API re-sends the
# tail of the transcript across them. Comparing only
# against the previous chunk missed that — once
# out_buf had been flushed and emptied, the repeat
# sailed straight back in, which logged the answer
# twice AND made the avatar mouth it twice.
if txt and not _is_repeat_chunk(txt, out_buf):
out_buf.append(txt)
# Hand the words to the mouth as they arrive, so
# the avatar can form the consonants the audio
# alone cannot show. Pure string work — it adds
# nothing measurable to the response path.
self._visemes.feed_text(txt)
if sc.input_transcription and sc.input_transcription.text:
txt = _clean_transcript(sc.input_transcription.text)
@@ -1051,10 +1526,12 @@ class JarvisLive:
self._interrupted = False
in_buf = []
out_buf = []
self._visemes.reset()
continue
full_in = " ".join(in_buf).strip()
if full_in:
self._last_out_logged = "" # new exchange
self.ui.write_log(f"You: {full_in}")
self._session_log.append(f"User: {full_in}")
if self._dashboard:
@@ -1066,7 +1543,14 @@ class JarvisLive:
in_buf = []
full_out = " ".join(out_buf).strip()
# Second line of defence: even if a repeat slips
# into a *fresh* buffer after a flush, never log the
# same answer (or a tail of it) twice in a row.
if full_out and len(full_out) >= _REPEAT_MIN and self._last_out_logged:
if full_out in self._last_out_logged:
full_out = ""
if full_out:
self._last_out_logged = full_out
self.ui.write_log(f"{self._asst_name}: {full_out}")
self._session_log.append(f"{self._asst_name}: {full_out}")
if self._dashboard:
@@ -1077,29 +1561,7 @@ class JarvisLive:
}))
out_buf = []
# Vision injection: model finished tool-response turn → now send the image
if self._pending_vision and self.session:
import base64 as _b64
img_b, mime_t, question, angle = self._pending_vision
self._pending_vision = None
b64 = _b64.b64encode(img_b).decode("ascii")
print(f"[Vision] 📤 {len(img_b):,} bytes (angle={angle}) → main session")
await self.session.send_client_content(
turns={"role": "user", "parts": [
{"inline_data": {"mime_type": mime_t, "data": b64}},
{"text": question},
]},
turn_complete=True,
)
# Mark next turn_complete behaviour depending on angle
if self._vision_cam_active:
# Camera: keep busy until JARVIS finishes speaking the answer
self._vision_cam_active = False
self._vision_close_pending = True
else:
# Screen-only: no camera to close; release busy flag now
self._vision_busy = False
elif self._vision_close_pending:
if self._vision_close_pending:
# This turn_complete IS the vision answer — close camera + release busy flag
self._vision_close_pending = False
self._vision_busy = False
@@ -1117,6 +1579,7 @@ class JarvisLive:
await self.session.send_tool_response(
function_responses=fn_responses
)
await self._flush_pending_vision()
except Exception as e:
print(f"[JARVIS] ❌ Recv: {e}")
traceback.print_exc()
@@ -1153,6 +1616,19 @@ class JarvisLive:
self.ui.write_log(f"SYS: Speaker '{_spk_name}' unavailable — using system default.")
stream = _open_spk(None)
# Ask the device how far behind the speakers actually are, rather than
# assuming. This is what the echo tail is sized from, so a machine with a
# large audio buffer gets a correspondingly longer guard — and one with a
# tiny buffer is not penalised with a delay it does not need.
try:
lat = float(getattr(stream, "latency", 0.0) or 0.0)
if 0.0 < lat < 1.0:
self._out_latency = lat
print(f"[JARVIS] 🔊 Output latency {self._out_latency*1000:.0f} ms "
f"→ echo tail {(self._out_latency + _TAIL_MARGIN)*1000:.0f} ms")
except Exception:
pass
try:
while True:
try:
@@ -1182,10 +1658,53 @@ class JarvisLive:
except asyncio.QueueEmpty:
break
# Drive the HUD waveform from JARVIS's own voice while speaking.
# Drive the HUD waveform and the avatar's mouth from JARVIS's
# own voice. The batch is up to 200 ms long, so we hand over a
# *schedule* of 20 ms viseme frames instead of a single averaged
# level and let the HUD play it out in step with the audio.
try:
self.ui.set_audio_level(_pcm_level(
np.frombuffer(bytes(batch), dtype=np.int16)))
pcm = np.frombuffer(bytes(batch), dtype=np.int16)
hop = _VIS_HOP / RECEIVE_SAMPLE_RATE
frames = _pcm_visemes(pcm, sr=RECEIVE_SAMPLE_RATE)
# When does this batch become audible? The stream was
# started at launch and its callback has been pulling
# silence ever since, so the first bytes of a reply reach
# the speaker about one callback period later — NOT one
# buffer later. `stream.latency` reports the buffer's
# capacity, which is how much can be queued ahead, and on
# Windows that is commonly 300-500 ms. Anchoring on it put
# the entire schedule a buffer late; that is the half second
# of lag, and it grew with whatever the device reported.
#
# After the anchor nothing needs measuring: the device
# consumes at exactly realtime, so each batch sounds one
# batch-duration after the one before it. The cursor is
# re-anchored only when it leaves the range physically
# possible — behind `now` means the device drained and this
# batch starts a fresh stretch of speech, while further
# ahead than the buffer can hold means it has drifted.
now = time.time()
horizon = self._out_latency + _CURSOR_SLACK
if not (now <= self._play_cursor <= now + horizon):
self._play_cursor = now + _FIRST_SOUND
at = self._play_cursor
# Advance by the batch's own duration whether or not it
# yielded frames, so a block too short to analyse cannot
# shift everything after it out of step with the audio.
self._play_cursor += pcm.size / RECEIVE_SAMPLE_RATE
if frames:
frames = self._visemes.frames(frames, hop)
self.ui.push_visemes(frames, hop, at)
# Barge-in needs to know what we are playing, not just
# how loud: the guard subtracts this from the microphone.
self._out_level = max(f[0] for f in frames)
self._echo.note_output(pcm, RECEIVE_SAMPLE_RATE,
self._out_level)
else:
lvl = _pcm_level(pcm)
self.ui.set_audio_level(lvl)
self._out_level = lvl
self._echo.note_output(pcm, RECEIVE_SAMPLE_RATE, lvl)
except Exception:
pass
@@ -1266,7 +1785,7 @@ class JarvisLive:
turns={"role": "user", "parts": [{"text": p1}]},
turn_complete=True,
)
self.ui.write_log("SYS: Briefing phase 1 (greeting) sent.")
print("[JARVIS] Briefing phase 1 (greeting) sent.")
# ── Phase 2: fire as soon as Phase 1 audio is done ───────────────────
async def _deliver_news():
@@ -1296,14 +1815,18 @@ class JarvisLive:
await asyncio.sleep(1.0)
try:
news_text = await asyncio.wait_for(news_done, timeout=4.0)
except Exception:
news_text = await asyncio.wait_for(news_done, timeout=8.0)
except Exception as e:
self.ui.write_log(f"SYS: News fetch timed out/failed: {e!r}")
news_text = ""
if not self.session:
return
if news_text and len(news_text) > 60:
failed = (not news_text) or news_text.startswith(
("No news found", "Search failed", "Please provide")
)
if not failed:
# Show on UI content panel immediately
self.ui.show_content("NEWS — top world news today", news_text)
@@ -1313,6 +1836,9 @@ class JarvisLive:
f"is displayed on screen. Do not call any tools.{lang_str}"
)
else:
self.ui.write_log(
f"SYS: News unavailable — backend returned: {news_text[:120]!r}"
)
p2 = (
"News headlines could not be fetched right now. "
f"Let the user know briefly.{lang_str}"
@@ -1322,10 +1848,11 @@ class JarvisLive:
turns={"role": "user", "parts": [{"text": p2}]},
turn_complete=True,
)
self.ui.write_log("SYS: Briefing phase 2 (news) sent.")
print("[JARVIS] Briefing phase 2 (news) sent.")
except Exception as e:
print(f"[Briefing] Phase 2 error: {e}")
self.ui.write_log(f"SYS: Briefing phase 2 failed: {e}")
print(f"[JARVIS] Briefing phase 2 failed: {e}")
self.ui.write_log("SYS: Could not fetch the news for the briefing.")
asyncio.create_task(_deliver_news())
@@ -1350,14 +1877,10 @@ class JarvisLive:
"Output ONLY the summary text, nothing else:\n\n" + convo
)
try:
from google import genai as _genai
client = _genai.Client(api_key=_get_api_key())
resp = await asyncio.to_thread(
client.models.generate_content,
model="gemini-flash-latest",
contents=prompt,
from core import gemini
summary = await asyncio.to_thread(
gemini.text, prompt, gemini.SMART, None, 30_000,
)
summary = (resp.text or "").strip()
if summary:
save_session_summary(summary, lang)
except Exception as e:
@@ -1412,7 +1935,7 @@ class JarvisLive:
turns={"role": "user", "parts": [{"text": msg}]},
turn_complete=True,
)
self.ui.write_log(f"SYS: Monitor alert sent.")
print("[JARVIS] Monitor alert sent.")
await asyncio.sleep(6) # gap between consecutive alerts
except Exception as e:
print(f"[Monitor] ⚠️ Background check error: {e}")
@@ -1455,7 +1978,7 @@ class JarvisLive:
turns={"role": "user", "parts": [{"text": prompt}]},
turn_complete=True,
)
self.ui.write_log("SYS: Proactive check-in.")
print("[JARVIS] Proactive check-in.")
except Exception as e:
print(f"[Proactive] ⚠️ {e}")
@@ -1672,6 +2195,22 @@ class JarvisLive:
print(f"[JARVIS] Error ({type(e).__name__}): {e}")
traceback.print_exc()
# Turn-taking / media / thinking knobs rejected by the server
# (preview API drift) — drop them first, because they are the
# newest fields and the cheapest to lose. Proactive audio is
# tried again on the next pass if the error persists.
if self._tuned_live and (
"INVALID_ARGUMENT" in err_str
or "Unknown name" in err_str
or "unexpected keyword" in err_str
or "realtime_input" in err_str.lower()
or "media_resolution" in err_str.lower()
or "thinking" in err_str.lower()
):
self._tuned_live = False
print("[JARVIS] Live tuning rejected — reconnecting without it.")
continue
# Proactive audio rejected by the server (preview API drift) —
# drop it and reconnect with the plain config.
if self._enhanced_live and (