Skip to content

The agent that grows with you

refactor(tui_gateway): W4 wave2 pass 2 — wake owner-result helper, profile asset magic table, config.set/get compaction

Tekniumb263a6f9777e
diff --git a/tui_gateway/methods_config.py b/tui_gateway/methods_config.py
index 54fd12f8fad..13c23b23978 100644
--- a/tui_gateway/methods_config.py
+++ b/tui_gateway/methods_config.py
@@ -258,10 +258,10 @@ def _(rid, params: dict) -> dict:
# ── setup readiness
def _readiness_profile_scope(params: dict):
- """``(profile, scope)`` for the readiness RPCs' optional ``profile`` param: ``scope`` binds
- that profile's HERMES_HOME + ``.env`` secret scope (ContextVars, so concurrent checks stay
- isolated); no param yields ``("", nullcontext())``. An unknown profile raises
- ``FileNotFoundError`` — never quietly answer for the launch profile instead."""
+ """``(profile, scope)`` for the readiness RPCs' optional ``profile``: ``scope`` binds that
+ profile's HERMES_HOME + ``.env`` secret scope (ContextVars: concurrent checks stay isolated);
+ no param -> ``("", nullcontext())``. Unknown profile raises ``FileNotFoundError`` — never
+ quietly answer for the launch profile instead."""
import contextlib
profile = str(params.get("profile") or "").strip() if isinstance(params, dict) else ""
if not profile:
@@ -303,10 +303,9 @@ def _(rid, params: dict) -> dict:
@method("setup.runtime_check")
def _(rid, params: dict) -> dict:
- """Strict provider check: does the configured/default model resolve to a usable runtime?
- Unlike setup.status (True if ANY provider auth state is discoverable), this runs the same
- resolve_runtime_provider() the agent uses on session creation and returns ok=False with the
- auth error when the model can't be served, so UIs surface onboarding before a doomed prompt.
+ """Strict provider check via the same resolve_runtime_provider() the agent uses on session
+ creation (setup.status is True if ANY provider auth state is discoverable): ok=False + the auth
+ error when the model can't be served, so UIs surface onboarding before a doomed prompt.
``profile`` answers for THAT profile's pin and ``.env``; unknown -> ``ok=False``."""
try:
from hermes_cli.runtime_provider import resolve_runtime_provider
@@ -329,10 +328,8 @@ def _(rid, params: dict) -> dict:
return fail("No Hermes provider is configured.", source)
api_key = runtime.get("api_key")
api_key_text = "" if callable(api_key) else str(api_key or "").strip()
- credential_ok = (
- callable(api_key) or api_key_text in {"aws-sdk", "no-key-required"}
- or has_usable_secret(api_key_text) or bool(runtime.get("command")))
- if not credential_ok:
+ if not (callable(api_key) or api_key_text in {"aws-sdk", "no-key-required"}
+ or has_usable_secret(api_key_text) or bool(runtime.get("command"))):
return fail(f"No usable credentials found for {provider}.", runtime.get("source"))
return {"ok": True, "provider": runtime.get("provider"), "model": runtime.get("model"),
"source": runtime.get("source"), **scoped}
@@ -352,11 +349,10 @@ def _safe_client_label(label: str) -> str:
@method("diagnostics.share_nous")
def _(rid, params: dict) -> dict:
"""Upload a redacted debug bundle to Nous-internal diagnostics storage — same collection +
- force-redaction pipeline as ``hermes debug share --nous``; redaction is NOT
- client-controllable and consent lives with the CALLER (privacy notice first). Structured
- ``ok``/``error`` envelope so the client renders upload failures inline. Optional params:
- ``error_context`` (redacted, attached as ``error-context.txt``), ``extra_files`` ({label ->
- text}, force-redacted, labels sanitized and size-capped), ``log_lines`` (default 200)."""
+ force-redaction pipeline as ``hermes debug share --nous``; redaction is NOT client-controllable
+ and consent lives with the CALLER (privacy notice first). Structured ``ok``/``error`` envelope so
+ upload failures render inline. Optional: ``error_context`` (-> ``error-context.txt``),
+ ``extra_files`` ({label -> text}), ``log_lines`` (default 200); all force-redacted."""
try:
from hermes_cli.debug import _redact_log_text, build_nous_bundle, collect_share_bundle
from hermes_cli.diagnostics_upload import share_to_nous
@@ -371,18 +367,14 @@ def _(rid, params: dict) -> dict:
bundle["error-context.txt"] = _redact_log_text(error_context.strip()[:8_000])
# Bounded: at most 4 files, 512KB each, sanitized labels — not an arbitrary upload surface.
extra_files = params.get("extra_files")
- if isinstance(extra_files, dict):
- for label, text in list(extra_files.items())[:4]:
- if not isinstance(label, str) or not isinstance(text, str):
- continue
- safe_label = _safe_client_label(label)
- if safe_label and text.strip():
- bundle[f"client/{safe_label}"] = _redact_log_text(text[:524_288])
+ for label, text in list(extra_files.items())[:4] if isinstance(extra_files, dict) else ():
+ safe_label = _safe_client_label(label) if isinstance(label, str) else ""
+ if safe_label and isinstance(text, str) and text.strip():
+ bundle[f"client/{safe_label}"] = _redact_log_text(text[:524_288])
res = share_to_nous(build_nous_bundle(bundle, redact=True))
view_url = res.get("viewUrl") or res.get("view_url")
upload_id = res.get("id")
- if not view_url and not upload_id:
- # An upload the user can't reference is useless to support.
+ if not view_url and not upload_id: # an upload the user can't reference is useless to support
return _ok(rid, {"ok": False, "error": "upload succeeded but returned no view URL or id"})
return _ok(rid, {"ok": True, "view_url": view_url, "upload_id": upload_id,
"expires_at": res.get("expiresAt") or res.get("expires_at")})
diff --git a/tui_gateway/methods_config_set.py b/tui_gateway/methods_config_set.py
index 95b2a882de8..4e92c84881d 100644
--- a/tui_gateway/methods_config_set.py
+++ b/tui_gateway/methods_config_set.py
@@ -20,10 +20,8 @@ _profile_scoped = _registry.profile_scoped
def _write_display_sections(*, sections=None, drop_sections=(), **display_fields) -> None:
"""Persist ``display.<field>`` + ``display.sections`` edits via the raw (uncached) write-back."""
cfg = _load_cfg_raw()
- display = cfg.get("display")
- display = display if isinstance(display, dict) else {}
- cur = display.get("sections")
- cur = cur if isinstance(cur, dict) else {}
+ display = cfg.get("display") if isinstance(cfg.get("display"), dict) else {}
+ cur = display.get("sections") if isinstance(display.get("sections"), dict) else {}
display.update(display_fields)
cur.update(sections or {})
for name in drop_sections:
@@ -157,8 +155,7 @@ def _set_fast(rid, params, key, value, session):
if agent is not None:
current_tier = getattr(agent, "service_tier", None)
elif session is not None and session.get("create_service_tier_override") is not None:
- # Pre-build session with a pinned tier: report/toggle from the pin, not the global.
- current_tier = session["create_service_tier_override"] or None
+ current_tier = session["create_service_tier_override"] or None # pre-build pin beats global
else:
current_tier = _load_service_tier()
if raw == "status":
@@ -172,8 +169,7 @@ def _set_fast(rid, params, key, value, session):
from hermes_cli.models import resolve_fast_mode_overrides
if agent is not None:
target_model = getattr(agent, "model", None)
- else:
- # A pre-build session may carry a picked model (desktop draft) — validate against THAT.
+ else: # a pre-build session may carry a picked model (desktop draft): validate against THAT
session_override = (session or {}).get("model_override") or {}
target_model = (isinstance(session_override, dict) and session_override.get("model")) or _resolve_model()
if not target_model:
@@ -191,12 +187,9 @@ def _set_fast(rid, params, key, value, session):
_write_config_key("agent.service_tier", nv)
if agent is not None:
agent.service_tier = {"fast": "priority", "normal": None}.get(nv, nv)
- current_overrides = dict(getattr(agent, "request_overrides", {}) or {})
- current_overrides.pop("service_tier", None)
- current_overrides.pop("speed", None)
- if nv == "fast":
- current_overrides.update(overrides)
- agent.request_overrides = current_overrides
+ current_overrides = {k: v for k, v in (getattr(agent, "request_overrides", {}) or {}).items()
+ if k not in ("service_tier", "speed")}
+ agent.request_overrides = {**current_overrides, **(overrides or {})}
_persist_live_session_runtime(session)
_emit_session_info(params.get("session_id", ""), session)
return _kv(rid, key, nv)
@@ -214,14 +207,13 @@ def _set_busy(rid, params, key, value, session):
def _set_verbose(rid, params, key, value, session):
cycle = ["off", "new", "all", "verbose"]
- cur = session.get("tool_progress_mode", _load_tool_progress_mode()) if session else _load_tool_progress_mode()
if value and value != "cycle":
nv = str(value).strip().lower()
if nv not in cycle:
return _err(rid, 4002, f"unknown verbose mode: {value}")
else:
- idx = cycle.index(cur) if cur in cycle else 2
- nv = cycle[(idx + 1) % len(cycle)]
+ cur = session.get("tool_progress_mode", _load_tool_progress_mode()) if session else _load_tool_progress_mode()
+ nv = cycle[((cycle.index(cur) if cur in cycle else 2) + 1) % len(cycle)]
_write_config_key("display.tool_progress", nv)
if session:
session["tool_progress_mode"] = nv
@@ -285,8 +277,7 @@ def _set_yolo(rid, params, key, value, session):
# Binary affordance: no restore of a prior "smart"/custom mode (those live in config.yaml).
_write_config_key("approvals.mode", "off" if enable else "manual")
_emit_all_session_info() # reflect the flip in every live indicator
- return _kv(rid, key, "1" if enable else "0", scope="global")
- if session:
+ elif session:
skey = session["session_key"]
enable = _resolve_toggle(is_session_yolo_enabled(skey))
(enable_session_yolo if enable else disable_session_yolo)(skey)
@@ -297,7 +288,7 @@ def _set_yolo(rid, params, key, value, session):
os.environ["HERMES_YOLO_MODE"] = "1"
else:
os.environ.pop("HERMES_YOLO_MODE", None)
- return _kv(rid, key, "1" if enable else "0", scope="session")
+ return _kv(rid, key, "1" if enable else "0", scope=scope if scope == "global" else "session")
# /reasoning display words: (accepted inputs, reported value, display field, sections.thinking,
@@ -353,12 +344,9 @@ def _set_details_section(rid, params, key, value, session):
if section not in _DETAIL_SECTION_NAMES:
return _err(rid, 4002, f"unknown section: {section}")
nv = _word(value)
- if not nv:
- _write_display_sections(drop_sections=(section,))
- elif nv not in _DETAIL_MODES:
+ if nv and nv not in _DETAIL_MODES:
return _err(rid, 4002, f"unknown details_mode: {value}")
- else:
- _write_display_sections(sections={section: nv})
+ _write_display_sections(sections={section: nv} if nv else None, drop_sections=() if nv else (section,))
return _kv(rid, key, nv)
diff --git a/tui_gateway/methods_images.py b/tui_gateway/methods_images.py
index 7eec464413f..9217c983825 100644
--- a/tui_gateway/methods_images.py
+++ b/tui_gateway/methods_images.py
@@ -1,8 +1,7 @@
"""Image-generation JSON-RPC handler (ws twin of the image_generate tool) for UI surfaces
(avatar pickers, artifact panes). The result is a data URL: a remote desktop can't read a
-gateway file path and hosted URLs are often CORS-opaque to a renderer canvas.
-
-Bodies are rebound onto server.py's globals (method_ctx.bind_module) and reference them bare.
+gateway file path and hosted URLs are often CORS-opaque to a renderer canvas. Bodies are
+rebound onto server.py's globals (method_ctx.bind_module) and reference them bare.
"""
from .method_ctx import HandlerRegistry, bind_module
@@ -11,14 +10,6 @@ _registry = HandlerRegistry()
method = _registry.method
-def _image_gen_available() -> bool:
- try:
- from tools.image_generation_tool import check_image_generation_requirements
- return bool(check_image_generation_requirements())
- except Exception:
- return False
-
-
def _image_to_data_url(ref: str, cap: int):
"""Fetch a URL or read a local path into a data URL; None when missing, over *cap*, or failing."""
import base64
@@ -43,8 +34,7 @@ def _image_to_data_url(ref: str, cap: int):
return None
if len(data) > cap:
return None
- if not mime.startswith("image/"):
- mime = "image/png"
+ mime = mime if mime.startswith("image/") else "image/png"
return f"data:{mime};base64,{base64.b64encode(data).decode('ascii')}"
except Exception:
return None
@@ -57,14 +47,16 @@ def _(rid, params: dict) -> dict:
on the data URL, default 8MB, max 16MB). Result: ``{available, success, image,
image_data, error}`` — ``image_data`` is omitted when the download fails, so
callers fall back to ``image`` (the backend's URL/path)."""
- available = _image_gen_available()
+ try:
+ from tools.image_generation_tool import check_image_generation_requirements
+ available = bool(check_image_generation_requirements())
+ except Exception:
+ available = False
if is_truthy_value(params.get("probe", False)):
return _ok(rid, {"available": available})
if not available:
- return _ok(rid, {
- "available": False, "success": False,
- "error": "No image generation backend configured (run `hermes tools` to enable one).",
- })
+ return _ok(rid, {"available": False, "success": False,
+ "error": "No image generation backend configured (run `hermes tools` to enable one)."})
prompt = str(params.get("prompt") or "").strip()
if not prompt:
return _err(rid, 4071, "prompt required")
@@ -74,9 +66,9 @@ def _(rid, params: dict) -> dict:
except (TypeError, ValueError):
cap = 8_000_000
try:
- from tools.image_generation_tool import _handle_image_generate
# Full provider dispatcher — same path as the model tool (source-image confinement,
# plugin providers, managed routing, FAL fallback); the FAL leaf bypassed providers.
+ from tools.image_generation_tool import _handle_image_generate
result = json.loads(_handle_image_generate({"prompt": prompt, "aspect_ratio": aspect}))
except Exception as e:
return _err(rid, 5071, str(e))
@@ -84,11 +76,9 @@ def _(rid, params: dict) -> dict:
return _ok(rid, {"available": True, "success": False,
"error": str(result.get("error") or "generation failed")})
image_ref = str(result.get("image") or "")
- payload = {"available": True, "success": True, "image": image_ref}
data_url = _image_to_data_url(image_ref, cap) if image_ref else None
- if data_url:
- payload["image_data"] = data_url
- return _ok(rid, payload)
+ return _ok(rid, {"available": True, "success": True, "image": image_ref,
+ **({"image_data": data_url} if data_url else {})})
def register(server) -> None:
diff --git a/tui_gateway/methods_profiles.py b/tui_gateway/methods_profiles.py
index 990b620d337..e4c36a50a17 100644
--- a/tui_gateway/methods_profiles.py
+++ b/tui_gateway/methods_profiles.py
@@ -14,6 +14,9 @@ method = _registry.method
# ext -> mime; iteration order is the on-disk lookup order for assets.
_ASSET_EXTS = {"png": "image/png", "jpg": "image/jpeg", "webp": "image/webp"}
+# ext -> [(start, end, magic bytes)]; format is sniffed, the declared mime is never trusted.
+_ASSET_MAGIC = {"png": [(0, 8, b"\x89PNG\r\n\x1a\n")], "jpg": [(0, 3, b"\xff\xd8\xff")],
+ "webp": [(0, 4, b"RIFF"), (8, 12, b"WEBP")]}
def _profile_handler(name: str, code: int):
@@ -39,6 +42,10 @@ def _pin_profile_model(profile_dir, provider, model) -> None:
_lazy("hermes_cli.web_routers.profiles", "_write_profile_model")(profile_dir, provider, model)
+def _model_provider_params(params) -> tuple:
+ return str(params.get("model") or "").strip(), str(params.get("provider") or "").strip()
+
+
def _try(fn, default):
"""``fn()`` or ``default`` on any exception — best-effort sections must never fail each other."""
try:
@@ -75,10 +82,12 @@ def _resolve_profile(rid, params):
def _read_profile_yaml(profile_dir) -> dict:
- """profile.yaml as a mapping; ``{}`` when missing, unparseable, or not a mapping."""
- import yaml
- meta_path = profile_dir / "profile.yaml"
- loaded = (yaml.safe_load(meta_path.read_text(encoding="utf-8")) or {}) if meta_path.is_file() else {}
+ """profile.yaml as a mapping; ``{}`` when missing, unreadable, unparseable, or not a mapping."""
+ def load():
+ import yaml
+ meta_path = profile_dir / "profile.yaml"
+ return (yaml.safe_load(meta_path.read_text(encoding="utf-8")) or {}) if meta_path.is_file() else {}
+ loaded = _try(load, {})
return loaded if isinstance(loaded, dict) else {}
@@ -181,15 +190,15 @@ def _latest_profile_session_rows(db):
def _profile_session_fields(row, profile_path):
"""Attach last_session / worker_session / canonical_session to a roster row. The DB is a
read-only attach (a writable ``SessionDB()`` waits up to 20s for the write lock + runs DDL
- and stalled the 5s roster poll); no DB -> every field None."""
+ and stalled the 5s roster poll); no/unreadable DB -> every field None (the readers swallow)."""
db_path = Path(profile_path) / "state.db"
db = None
if _try(db_path.exists, False):
db = _try(lambda: _lazy("hermes_state", "SessionDB")(db_path=db_path, read_only=True), None)
try:
- row["last_session"], row["worker_session"] = _latest_profile_session_rows(db) if db else (None, None)
+ row["last_session"], row["worker_session"] = _latest_profile_session_rows(db)
# Resolved server-side on every listing so no client carries a session pointer.
- row["canonical_session"] = _canonical_session_row(db, profile_path) if db else None
+ row["canonical_session"] = _canonical_session_row(db, profile_path)
finally:
if db is not None:
_best_effort(db.close)
@@ -200,7 +209,7 @@ def _profile_ui_meta_fields(row: dict, profile_dir) -> None:
``ui_meta_revisions`` is always present: it feature-detects gateway-owned CAS even for a
brand-new profile."""
row["ui_meta_revisions"] = {}
- raw_meta = _try(lambda: _read_profile_yaml(profile_dir), {})
+ raw_meta = _read_profile_yaml(profile_dir)
ui_meta = raw_meta.get("ui_meta")
if isinstance(ui_meta, dict) and ui_meta:
row["ui_meta"] = ui_meta
@@ -295,10 +304,9 @@ def _inherit_launch_model(path) -> bool:
if dst_model.get("provider") and dst_model.get("default"):
return False
model_cfg = (load_config_readonly() or {}).get("model") or {}
- provider, model = str(model_cfg.get("provider") or ""), str(model_cfg.get("default") or "")
- if not (provider and model):
+ if not (model_cfg.get("provider") and model_cfg.get("default")):
return False
- _pin_profile_model(path, provider, model)
+ _pin_profile_model(path, str(model_cfg["provider"]), str(model_cfg["default"]))
return True
@@ -348,12 +356,10 @@ def _(rid, params: dict) -> dict:
_best_effort(lambda: profiles_mod.seed_profile_skills(path, quiet=True))
_best_effort(lambda: profiles_mod.check_alias_collision(name) or profiles_mod.create_wrapper_script(name))
soul = params.get("soul")
- soul_written = False
- if isinstance(soul, str) and soul.strip():
- soul_written = _best_effort(lambda: (path / "SOUL.md").write_text(soul, encoding="utf-8"))
+ soul_written = isinstance(soul, str) and bool(soul.strip()) and _best_effort(
+ lambda: (path / "SOUL.md").write_text(soul, encoding="utf-8"))
mirrored = _mirror_launch_credentials(path, params)
- model = str(params.get("model") or "").strip()
- provider = str(params.get("provider") or "").strip()
+ model, provider = _model_provider_params(params)
model_set = False
if model and provider:
model_set = _best_effort(lambda: _pin_profile_model(path, provider, model))
@@ -436,7 +442,7 @@ def _configure_ui_meta(profile_dir, params, applied) -> None:
if expected is not None and not isinstance(expected, dict):
raise ValueError("ui_meta_expected_revisions must be an object")
with _profile_ui_meta_lock:
- existing = _try(lambda: _read_profile_yaml(profile_dir), {})
+ existing = _read_profile_yaml(profile_dir)
raw_revisions = existing.get("_ui_meta_revisions")
revisions = _clean_revisions(raw_revisions if isinstance(raw_revisions, dict) else {})
conflicts = {}
@@ -473,8 +479,7 @@ def _configure_ui_meta(profile_dir, params, applied) -> None:
def _configure_model(profile_dir, params, applied):
"""Apply a ``model`` + ``provider`` pin, or return a confirm message and write NOTHING (client
resends with ``confirm_expensive_model``). A failing guard = "no warning" (as _apply_model_switch)."""
- model = str(params.get("model") or "").strip()
- provider = str(params.get("provider") or "").strip()
+ model, provider = _model_provider_params(params)
confirm_message = None
if not (model and provider):
return None
@@ -611,13 +616,8 @@ def _(rid, params: dict) -> dict:
return _err(rid, 4068, "data is not valid base64")
if len(blob) > 2_000_000:
return _err(rid, 4069, f"asset too large ({len(blob)} bytes; max 2MB)")
- if blob[:8] == b"\x89PNG\r\n\x1a\n":
- ext = "png"
- elif blob[:3] == b"\xff\xd8\xff":
- ext = "jpg"
- elif blob[:4] == b"RIFF" and blob[8:12] == b"WEBP":
- ext = "webp"
- else:
+ ext = next((e for e, magic in _ASSET_MAGIC.items() if all(blob[a:b] == m for a, b, m in magic)), None)
+ if ext is None:
return _err(rid, 4070, "unsupported image format (PNG/JPEG/WebP only)")
assets_dir.mkdir(parents=True, exist_ok=True)
_unlink_asset_files(assets_dir, asset) # one canonical file per asset
diff --git a/tui_gateway/methods_voice.py b/tui_gateway/methods_voice.py
index 832b1123c51..f9dd3801159 100644
--- a/tui_gateway/methods_voice.py
+++ b/tui_gateway/methods_voice.py
@@ -63,8 +63,8 @@ def _end_voice_chat(*, stop_loop: bool, stop_tts: bool) -> None:
def _tts_lease_async(lease: str, active: bool) -> None:
- """Acquire/release a TTS engine lease off the RPC thread: acquiring warms the provider
- (local engines load a model) and must not block the toggle's reply. Best-effort."""
+ """Acquire/release a TTS lease off the RPC thread (acquiring warms a local engine; must not
+ block the toggle's reply). Best-effort."""
def _run():
try:
from tools.tts_tool import acquire_tts_lease, release_tts_lease
@@ -117,7 +117,7 @@ def _tts_stream_begin() -> Optional[queue.Queue]:
def _tts_stream_stop(user_barge: bool = True) -> None:
"""Cut in-flight streaming TTS. *user_barge* latches the interruption for the next turn's
- model note — pass ``False`` for mode changes (/voice off)."""
+ model note; ``False`` for mode changes (/voice off)."""
global _tts_stream_state
with _tts_stream_lock:
state, _tts_stream_state = _tts_stream_state, None
@@ -162,23 +162,18 @@ def _arm_barge_listener_if_enabled() -> None:
_arm_full_duplex_listener()
-def _fd_speak_pipelines_snapshot() -> list:
- with _fd_listener_lock:
- return list(_fd_speak_pipelines)
-
-
def _fd_tts_pending() -> bool:
"""True while any TTS (streaming pipeline or fallback speak) is unfinished."""
with _tts_stream_lock:
state = _tts_stream_state
if state is not None and not state["done"].is_set():
return True
- return any(not done.is_set() for _stop, done in _fd_speak_pipelines_snapshot())
+ with _fd_listener_lock:
+ return any(not done.is_set() for _stop, done in _fd_speak_pipelines)
def _full_duplex_listener() -> None:
- """Mic live from utterance-submit to turn-complete; a trip (see ``_fd_trip``) transcribes
- the utterance and emits it as ``voice.transcript``."""
+ """Mic live from utterance-submit to turn-complete; a trip transcribes -> ``voice.transcript``."""
global _fd_listener_active
try:
from tools.voice_mode import (full_duplex_listen, is_audio_output_active,
@@ -218,23 +213,22 @@ def _full_duplex_listener() -> None:
def _fd_barge_params(cfg: dict) -> tuple[float, int]:
"""``(threshold multiplier, grace ms)`` from the voice config; malformed -> defaults."""
- try:
- mult = float(cfg.get("barge_in_threshold_multiplier", 0) or 0)
- except (TypeError, ValueError):
- mult = 0.0
- try:
- grace_ms = int(float(cfg.get("barge_in_grace_seconds", 0.5)) * 1000)
- except (TypeError, ValueError):
- grace_ms = 500
- return mult, max(0, grace_ms)
+ def num(conv, key, default):
+ try:
+ return conv(cfg.get(key, default))
+ except (TypeError, ValueError):
+ return conv(default)
+ mult = num(lambda v: float(v or 0), "barge_in_threshold_multiplier", 0)
+ return mult, max(0, num(lambda v: int(float(v) * 1000), "barge_in_grace_seconds", 0.5))
def _cut_all_tts() -> None:
"""Cut streaming TTS, every fallback speak pipeline, and the file player."""
from tools.voice_mode import stop_playback
_tts_stream_stop(user_barge=True)
- for _stop, _done in _fd_speak_pipelines_snapshot():
- _stop.set()
+ with _fd_listener_lock:
+ for _stop, _done in _fd_speak_pipelines:
+ _stop.set()
stop_playback()
@@ -279,8 +273,7 @@ def _deliver_fd_transcript(text: str) -> None:
def _speak_text_with_barge(text: str) -> None:
- """Speak via hermes_cli.voice.speak_text, registered in ``_fd_speak_pipelines`` so the
- full-duplex listener can cut it and keeps listening while it is pending."""
+ """speak_text registered in ``_fd_speak_pipelines`` so the listener can cut it / waits for it."""
from hermes_cli.voice import speak_text
stop, done = threading.Event(), threading.Event()
with _fd_listener_lock:
@@ -405,6 +398,11 @@ def _persist_wake_enabled(enabled: bool) -> bool:
return False
+def _owner_result(rid, field: str, ok, **extra) -> dict:
+ """``{field: ok, reason: None | "not_owner", **extra}`` for the owner-gated wake RPCs."""
+ return _ok(rid, {field: ok, "reason": None if ok else "not_owner", **extra})
+
+
def _frame_fields(frame: dict) -> dict:
return {"sample_rate": frame.get("sample_rate", 16000), "frame_length": frame.get("frame_length", 1280)}
@@ -459,11 +457,14 @@ def _(rid, params: dict) -> dict:
@method("wake.start")
def _(rid, params: dict) -> dict:
"""Arm the wake-word listener for the calling surface ("tui" | "gui"); ``{started: False,
- reason}`` when disabled, owned by another surface, or deps/mic aren't ready. ``persist: true``
- (explicit gesture) flips ``wake_word.enabled`` on before arming; auto-arm callers omit it."""
+ reason}`` when disabled/owned/not ready. ``persist: true`` (explicit gesture) also flips
+ ``wake_word.enabled`` on; auto-arm callers omit it."""
global _wake_owner_transport, _wake_owner_surface
surface = str(params.get("surface") or "auto").strip().lower()
transport = _caller_transport()
+
+ def refused(reason, **extra):
+ return _ok(rid, {"started": False, "reason": reason, **extra})
try:
from tools.wake_word import (
WakeWordInUse, detector_frame_info, load_wake_word_config, owns_listener,
@@ -476,8 +477,7 @@ def _(rid, params: dict) -> dict:
# wake_word.enabled — else config says on while nothing can arm.
if not reqs["available"]:
logger.warning("wake.start(%s): not available — %s", surface, reqs.get("hint"))
- return _ok(rid, {"started": False, "reason": "unavailable", "hint": reqs.get("hint") or "",
- "capture": capture_mode})
+ return refused("unavailable", hint=reqs.get("hint") or "", capture=capture_mode)
enabled_persisted = bool(params.get("persist") and not cfg.get("enabled") and _persist_wake_enabled(True))
if enabled_persisted:
cfg = {**cfg, "enabled": True}
@@ -487,20 +487,19 @@ def _(rid, params: dict) -> dict:
reason = "disabled" if not cfg.get("enabled") else "disabled_for_surface"
logger.info("wake.start(%s): %s (enabled=%s, surface=%s)",
surface, reason, cfg.get("enabled"), cfg.get("surface"))
- return _ok(rid, {"started": False, "reason": reason})
+ return refused(reason)
existing_owner, existing_surface = _wake_owner_snapshot()
if existing_owner is not None and (_transport_is_dead(existing_owner) or not owns_listener(existing_owner)):
_release_wake_for_transport(existing_owner)
existing_owner, existing_surface = None, ""
if existing_owner is not None and existing_owner is not transport:
- return _ok(rid, {"started": False, "reason": "owned", "owner_surface": existing_surface})
- sid = str(params.get("session_id") or "")
+ return refused("owned", owner_surface=existing_surface)
try:
- on_detect = _wake_detect_handler(
- transport, sid, wake_phrase(cfg), bool(cfg.get("start_new_session", True)))
+ on_detect = _wake_detect_handler(transport, str(params.get("session_id") or ""), wake_phrase(cfg),
+ bool(cfg.get("start_new_session", True)))
start_listening(on_detect, owner=transport, config=cfg, external_audio=capture_mode == "client")
except WakeWordInUse:
- return _ok(rid, {"started": False, "reason": "owned", "owner_surface": existing_surface or None})
+ return refused("owned", owner_surface=existing_surface or None)
except Exception as e:
logger.warning("wake.start(%s): failed to start listener: %s", surface, e)
return _err(rid, 5026, str(e))
@@ -528,8 +527,7 @@ def _(rid, params: dict) -> dict:
currently_enabled = True
if currently_enabled:
disabled_persisted = _persist_wake_enabled(False)
- return _ok(rid, {"stopped": stopped, "reason": None if stopped else "not_owner",
- "disabled_persisted": disabled_persisted})
+ return _owner_result(rid, "stopped", stopped, disabled_persisted=disabled_persisted)
@method("wake.pause")
@@ -542,7 +540,7 @@ def _(rid, params: dict) -> dict:
except Exception as e:
logger.debug("wake.pause failed: %s", e)
paused = False
- return _ok(rid, {"paused": paused, "reason": None if paused else "not_owner"})
+ return _owner_result(rid, "paused", paused)
@method("wake.resume")
@@ -550,7 +548,7 @@ def _(rid, params: dict) -> dict:
"""Reclaim the mic after a pause; no-op if the listener isn't armed."""
resumed = _wake_resume_if_owner(_caller_transport())
logger.info("wake.resume: detector resumed=%s", resumed)
- return _ok(rid, {"resumed": resumed, "reason": None if resumed else "not_owner"})
+ return _owner_result(rid, "resumed", resumed)
@method("wake.status")
@@ -580,16 +578,15 @@ def _(rid, params: dict) -> dict:
capture = "local"
else:
capture = probe_capture or reqs.get("capture") or str(cfg.get("capture") or "auto")
+ # `enabled` is config truth (clients re-arm after a voice turn from it); `audio_silent` =
+ # armed but deaf despite an open stream (see the platform-specific hint).
return _ok(rid, {
"listening": listening, "owned_by_caller": owned_by_caller,
"owner_surface": owner_surface if owner is not None else None,
"phrase": reqs["phrase"], "provider": reqs["provider"],
"configured_surface": str(cfg.get("surface") or "auto"),
"input_device": input_device, "available": reqs["available"], "hint": hint,
- # Config truth: clients re-arm after a voice turn ("permanent on") from this.
- "enabled": bool(cfg.get("enabled")),
- # Armed but deaf despite an open stream; see platform-specific hint.
- "audio_silent": silent, "capture": capture,
+ "enabled": bool(cfg.get("enabled")), "audio_silent": silent, "capture": capture,
"local_input_available": bool(reqs.get("local_input_available")), **_frame_fields(frame)})
except Exception as e:
return _err(rid, 5026, str(e))
@@ -598,12 +595,12 @@ def _(rid, params: dict) -> dict:
@method("wake.feed")
def _(rid, params: dict) -> dict:
"""Push client-captured PCM (``pcm``/``pcm_b64``: base64 int16 mono LE, 16 kHz only) into the
- armed detector (``capture: "client"``) so mic-less remote backends can run openWakeWord."""
+ armed detector (``capture: "client"``) — mic-less remote backends can run openWakeWord."""
raw_b64 = params.get("pcm") or params.get("pcm_b64") or ""
if not isinstance(raw_b64, str) or not raw_b64.strip():
return _err(rid, 4001, "wake.feed requires base64 pcm")
+ import base64
try:
- import base64
pcm = base64.b64decode(raw_b64, validate=False)
except Exception as e:
return _err(rid, 4001, f"invalid base64 pcm: {e}")
@@ -620,7 +617,7 @@ def _(rid, params: dict) -> dict:
except Exception as e:
logger.debug("wake.feed failed: %s", e)
return _err(rid, 5026, str(e))
- return _ok(rid, {"fed": bool(ok), "reason": None if ok else "not_owner"})
+ return _owner_result(rid, "fed", bool(ok))
def _voice_toggle_status(rid, params: dict) -> dict:
@@ -698,13 +695,8 @@ def _(rid, params: dict) -> dict:
# voice.record callbacks (module-level: they touch only process-global state). Each terminal
# capture event resumes the wake detector so wake-triggered and manual captures coexist.
-def _vr_on_transcript(t):
- _voice_emit("voice.transcript", {"text": t})
- _resume_voice_wake()
-
-
-def _vr_on_silent():
- _voice_emit("voice.transcript", {"no_speech_limit": True})
+def _vr_transcript(payload: dict) -> None:
+ _voice_emit("voice.transcript", payload)
_resume_voice_wake()
@@ -712,8 +704,7 @@ def _vr_on_stop_phrase(t):
# A SPOKEN bare stop phrase: end the chat like /voice off and emit a distinct signal so
# clients end the conversation instead of treating it as a no-speech timeout.
_end_voice_chat(stop_loop=False, stop_tts=True)
- _voice_emit("voice.transcript", {"stop_phrase": True, "text": t})
- _resume_voice_wake()
+ _vr_transcript({"stop_phrase": True, "text": t})
def _vr_on_status(state):
@@ -746,7 +737,8 @@ def _voice_record_start(transport) -> dict:
_voice_wake_owner = transport
try:
started = start_continuous(
- on_transcript=_vr_on_transcript, on_status=_vr_on_status, on_silent_limit=_vr_on_silent,
+ on_transcript=lambda t: _vr_transcript({"text": t}), on_status=_vr_on_status,
+ on_silent_limit=lambda: _vr_transcript({"no_speech_limit": True}),
silence_threshold=_voice_cfg_number(voice_cfg.get("silence_threshold"), 200),
silence_duration=_voice_cfg_number(voice_cfg.get("silence_duration"), 3.0),
auto_restart=False, max_recording_seconds=max_rec if max_rec > 0 else 0.0,