Skip to content

The agent that grows with you

refactor(tui_gateway): projects.* error shell decorator, shared wake frame fields, secret-copy helper

Teknium10b426272f59
diff --git a/tui_gateway/methods_config.py b/tui_gateway/methods_config.py
index 62eae24dbc6..140c7ab837a 100644
--- a/tui_gateway/methods_config.py
+++ b/tui_gateway/methods_config.py
@@ -11,67 +11,71 @@ method = _registry.method
_profile_scoped = _registry.profile_scoped
+def _projects_handler(name: str):
+ """``@method(name)`` (profile-scoped) whose body's uncaught exception becomes ``_err(rid, 5061)``."""
+ def deco(fn):
+ def handler(rid, params: dict) -> dict:
+ try:
+ return fn(rid, params)
+ except Exception as e:
+ return _err(rid, 5061, str(e))
+ return method(name)(_profile_scoped(handler))
+ return deco
+
+
def _reconcile_repo_discovery(pdb, conn, policy, policy_key):
pdb.reconcile_discovered_repos_policy(
conn, policy_key, preserve_unversioned=_repo_discovery_policy_is_default(policy))
-@method("projects.discover_repos")
-@_profile_scoped
+@_projects_handler("projects.discover_repos")
def _(rid, params: dict) -> dict:
"""Repos for the desktop overview: scanned-from-disk (cached) ∪ session-derived."""
- try:
- with _profile_db(params) as db:
- if db is None:
- return _ok(rid, {"repos": []})
- from hermes_cli import projects_db as pdb
- policy = _repo_discovery_policy()
- with pdb.connect_closing() as conn:
- _reconcile_repo_discovery(pdb, conn, policy, _repo_discovery_policy_key(policy))
- # `scan=true` (remote-gateway desktop): its native scan only sees its own
- # filesystem, so the host scans the policy roots so zero-session repos surface.
- if params.get("scan") and policy["enabled"]:
- _scan_discovered_repos_remote(conn, policy)
- repos = _discover_repos_payload(db, conn=conn, include_cached=policy["enabled"])
- return _ok(rid, {"repos": repos, "discovery_policy": policy})
- except Exception as e:
- return _err(rid, 5061, str(e))
+ with _profile_db(params) as db:
+ if db is None:
+ return _ok(rid, {"repos": []})
+ from hermes_cli import projects_db as pdb
+ policy = _repo_discovery_policy()
+ with pdb.connect_closing() as conn:
+ _reconcile_repo_discovery(pdb, conn, policy, _repo_discovery_policy_key(policy))
+ # `scan=true` (remote-gateway desktop): its native scan only sees its own
+ # filesystem, so the host scans the policy roots so zero-session repos surface.
+ if params.get("scan") and policy["enabled"]:
+ _scan_discovered_repos_remote(conn, policy)
+ repos = _discover_repos_payload(db, conn=conn, include_cached=policy["enabled"])
+ return _ok(rid, {"repos": repos, "discovery_policy": policy})
-@method("projects.record_repos")
-@_profile_scoped
+@_projects_handler("projects.record_repos")
def _(rid, params: dict) -> dict:
"""Persist repo roots found by the client's (desktop-side) scan; return the merged list."""
- try:
- from hermes_cli import projects_db as pdb
- policy = _repo_discovery_policy()
- policy_key = _repo_discovery_policy_key(policy)
- incoming_raw = params.get("discovery_policy")
- incoming_policy = (
- _repo_discovery_policy(incoming_raw) if isinstance(incoming_raw, dict) else None)
- incoming_matches = (incoming_policy is not None
- and _repo_discovery_policy_key(incoming_policy) == policy_key)
- accept_legacy_default = (incoming_policy is None
- and _repo_discovery_policy_is_default(policy))
- pairs: list[tuple[str, str | None]] = []
- for item in params.get("repos") or []:
- if isinstance(item, str):
- pairs.append((item, None))
- elif isinstance(item, dict) and item.get("root"):
- pairs.append((str(item["root"]), item.get("label")))
- with pdb.connect_closing() as conn:
- _reconcile_repo_discovery(pdb, conn, policy, policy_key)
- accepted = bool(policy["enabled"] and (incoming_matches or accept_legacy_default))
- if accepted:
- pdb.record_discovered_repos(conn, pairs, replace=True, policy_key=policy_key)
- elif not policy["enabled"]:
- pdb.clear_discovered_repos(conn, policy_key=policy_key)
- with _profile_db(params) as db:
- repos = ([] if db is None
- else _discover_repos_payload(db, include_cached=policy["enabled"]))
- return _ok(rid, {"repos": repos, "accepted": accepted, "discovery_policy": policy})
- except Exception as e:
- return _err(rid, 5061, str(e))
+ from hermes_cli import projects_db as pdb
+ policy = _repo_discovery_policy()
+ policy_key = _repo_discovery_policy_key(policy)
+ incoming_raw = params.get("discovery_policy")
+ incoming_policy = (
+ _repo_discovery_policy(incoming_raw) if isinstance(incoming_raw, dict) else None)
+ incoming_matches = (incoming_policy is not None
+ and _repo_discovery_policy_key(incoming_policy) == policy_key)
+ accept_legacy_default = (incoming_policy is None
+ and _repo_discovery_policy_is_default(policy))
+ pairs: list[tuple[str, str | None]] = []
+ for item in params.get("repos") or []:
+ if isinstance(item, str):
+ pairs.append((item, None))
+ elif isinstance(item, dict) and item.get("root"):
+ pairs.append((str(item["root"]), item.get("label")))
+ with pdb.connect_closing() as conn:
+ _reconcile_repo_discovery(pdb, conn, policy, policy_key)
+ accepted = bool(policy["enabled"] and (incoming_matches or accept_legacy_default))
+ if accepted:
+ pdb.record_discovered_repos(conn, pairs, replace=True, policy_key=policy_key)
+ elif not policy["enabled"]:
+ pdb.clear_discovered_repos(conn, policy_key=policy_key)
+ with _profile_db(params) as db:
+ repos = ([] if db is None
+ else _discover_repos_payload(db, include_cached=policy["enabled"]))
+ return _ok(rid, {"repos": repos, "accepted": accepted, "discovery_policy": policy})
def _stamped_project_tree(db, params, **kwargs):
@@ -82,45 +86,37 @@ def _stamped_project_tree(db, params, **kwargs):
return tree, active_id
-@method("projects.tree")
-@_profile_scoped
+@_projects_handler("projects.tree")
def _(rid, params: dict) -> dict:
"""Project -> repo -> lane overview with counts + a few preview sessions per project, plus
the flat set of session ids claimed by any project (excluded from flat Recents). Lanes carry
no session rows here; drill-in uses ``projects.project_sessions``."""
- try:
- with _profile_db(params) as db:
- if db is None:
- return _ok(rid, {"projects": [], "active_id": None, "scoped_session_ids": []})
- tree, active_id = _stamped_project_tree(
- db, params, preview_limit=int(params.get("preview_limit") or 3), hydrate=False,
- session_limit=int(params.get("session_limit") or 2000), include_discovered=True)
- return _ok(rid, {
- "projects": tree["projects"], "active_id": active_id,
- "scoped_session_ids": tree["scoped_session_ids"]})
- except Exception as e:
- return _err(rid, 5061, str(e))
+ with _profile_db(params) as db:
+ if db is None:
+ return _ok(rid, {"projects": [], "active_id": None, "scoped_session_ids": []})
+ tree, active_id = _stamped_project_tree(
+ db, params, preview_limit=int(params.get("preview_limit") or 3), hydrate=False,
+ session_limit=int(params.get("session_limit") or 2000), include_discovered=True)
+ return _ok(rid, {
+ "projects": tree["projects"], "active_id": active_id,
+ "scoped_session_ids": tree["scoped_session_ids"]})
-@method("projects.project_sessions")
-@_profile_scoped
+@_projects_handler("projects.project_sessions")
def _(rid, params: dict) -> dict:
"""Fully hydrated lanes for one project, from the same grouping as ``projects.tree``."""
- try:
- project_id = str(params.get("project_id") or "")
- if not project_id:
- return _err(rid, 5063, "project_id required")
- with _profile_db(params) as db:
- if db is None:
- return _ok(rid, {"project": None})
- # Drill-in only needs the entered project: skip the zero-session discovery tier.
- tree, _active = _stamped_project_tree(
- db, params, preview_limit=0, hydrate=True,
- session_limit=int(params.get("session_limit") or 5000), include_discovered=False)
- proj = next((p for p in tree["projects"] if p["id"] == project_id), None)
- return _ok(rid, {"project": proj})
- except Exception as e:
- return _err(rid, 5061, str(e))
+ project_id = str(params.get("project_id") or "")
+ if not project_id:
+ return _err(rid, 5063, "project_id required")
+ with _profile_db(params) as db:
+ if db is None:
+ return _ok(rid, {"project": None})
+ # Drill-in only needs the entered project: skip the zero-session discovery tier.
+ tree, _active = _stamped_project_tree(
+ db, params, preview_limit=0, hydrate=True,
+ session_limit=int(params.get("session_limit") or 5000), include_discovered=False)
+ proj = next((p for p in tree["projects"] if p["id"] == project_id), None)
+ return _ok(rid, {"project": proj})
# ── config.get — one getter per key; returns the result payload or a full ``_err`` response
diff --git a/tui_gateway/methods_profiles.py b/tui_gateway/methods_profiles.py
index 21bfe95f8bf..9792e3c5eb8 100644
--- a/tui_gateway/methods_profiles.py
+++ b/tui_gateway/methods_profiles.py
@@ -256,29 +256,30 @@ def _has_real_env_content(env_path) -> bool:
return any(s and not s.startswith("#") for s in map(str.strip, lines))
-def _copy_secret_file(src, dst) -> None:
+def _copy_secret_file(src, dst, wanted: bool) -> bool:
+ """Copy ``src`` -> ``dst`` (0600) when ``src`` exists and ``wanted``; True if copied."""
+ if not (src.is_file() and wanted):
+ return False
import shutil
shutil.copy2(src, dst)
with contextlib.suppress(OSError):
os.chmod(str(dst), 0o600)
+ return True
def _mirror_env(path, launch_home) -> bool:
"""Copy the launch .env only over the seeded comment-only stub (never a clone's secrets)."""
src, dst = launch_home / ".env", path / ".env"
- if not (src.is_file() and _has_real_env_content(src) and not _try(lambda: _has_real_env_content(dst), False)):
- return False
- _copy_secret_file(src, dst)
- return True
+ return _copy_secret_file(
+ src, dst, _has_real_env_content(src) and not _try(lambda: _has_real_env_content(dst), False))
def _mirror_auth(path, launch_home) -> bool:
"""Copy the launch auth.json when absent (skipped under ``share_auth``: a copy forks token
state and the first refresh in either store strands the other)."""
src, dst = launch_home / "auth.json", path / "auth.json"
- if not (src.is_file() and not dst.exists()):
+ if not _copy_secret_file(src, dst, not dst.exists()):
return False
- _copy_secret_file(src, dst)
# Drop single-use OAuth grants (first refresh strands every sibling); they read from
# the root grant via the pool fallback. API keys stay.
_best_effort(lambda: _lazy("hermes_cli.auth", "strip_cloned_single_use_oauth_grants")(path))
diff --git a/tui_gateway/methods_voice.py b/tui_gateway/methods_voice.py
index bcb22866ca5..52cf5b87e27 100644
--- a/tui_gateway/methods_voice.py
+++ b/tui_gateway/methods_voice.py
@@ -365,14 +365,11 @@ _wake_resume_retry_active = False
def _wake_resume_if_owner(owner: "Transport", *, retry_seconds: float = 15.0,
retry_interval: float = 1.0) -> bool:
- """Resume the wake detector for ``owner``; self-heal a busy microphone.
-
- Reopening the mic right after a voice turn can fail while the device is still being
- released (browser WebRTC tracks release async): on an exception retry in a background
- thread until it sticks, the lease changes hands, or ``retry_seconds`` elapses. ``False``
- from ``resume_listening`` (lease gone / other owner) is final — never retried, so this
- can't steal another surface's mic.
- """
+ """Resume the wake detector for ``owner``; self-heal a busy microphone. Reopening the mic
+ right after a voice turn can fail while the device is still being released (browser WebRTC
+ tracks release async): on an exception retry in a background thread until it sticks, the
+ lease changes hands, or ``retry_seconds`` elapses. ``False`` from ``resume_listening``
+ (lease gone / other owner) is final — never retried, so this can't steal another's mic."""
from tools.wake_word import resume_listening
try:
return resume_listening(owner=owner)
@@ -422,6 +419,10 @@ def _wake_prefers_client(params: dict, surface: str) -> bool:
return surface in ("gui", "desktop") or bool(params.get("client_capture"))
+def _frame_fields(frame: dict) -> dict:
+ return {"sample_rate": frame.get("sample_rate", 16000), "frame_length": frame.get("frame_length", 1280)}
+
+
def _wake_probe(cfg: dict, prefer_client: bool) -> tuple[str, dict]:
"""``(capture_mode, requirements)``; capture stamped so the probe matches what would arm."""
from tools.wake_word import check_wake_word_requirements, resolve_capture_mode
@@ -454,26 +455,24 @@ def _wake_detect_handler(transport, sid: str, phrase: str, new_session: bool):
@method("gateway.capabilities")
def _(rid, params: dict) -> dict:
- """Advertise what THIS BUILD enforces: a client can't tell a gateway that fences concurrent
- writers from one that doesn't, so it withholds unless advertised. Sourced from the enforcing
- module, never config: a believed-but-absent capability is worse than none."""
+ """Advertise what THIS BUILD enforces (a client withholds unless the guarantee is advertised).
+ Sourced from the enforcing module, never config: a believed-but-absent capability is worse."""
from hermes_cli.active_sessions import PER_SESSION_EXCLUSIVE_SUBMIT
return _ok(rid, {"per_session_exclusive_submit": bool(PER_SESSION_EXCLUSIVE_SUBMIT)})
@method("ping")
def _(rid, params: dict) -> dict:
- """Cheapest liveness probe, answered on the WS reader thread so it works while every agent
- is mid-turn: lets the desktop tell a half-open socket after sleep/wake and reconnect."""
+ """Cheapest liveness probe, answered on the WS reader thread (works while every agent is
+ mid-turn) so the desktop can tell a half-open socket after sleep/wake and reconnect."""
return _ok(rid, {"pong": True})
@method("wake.start")
def _(rid, params: dict) -> dict:
- """Arm the wake-word listener for the calling surface ("tui" | "gui"). Idempotent and gated:
- ``{started: False, reason}`` when disabled, scoped to another surface, or deps/mic aren't
- ready. ``persist: true`` marks an explicit user gesture: when disabled in config it flips
- ``wake_word.enabled`` on before arming; passive auto-arm callers omit it."""
+ """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."""
surface = str(params.get("surface") or "auto").strip().lower()
persist = bool(params.get("persist"))
transport = _caller_transport()
@@ -530,8 +529,7 @@ def _(rid, params: dict) -> dict:
return _ok(rid, {
"started": True, "phrase": reqs["phrase"], "provider": reqs["provider"],
"owner_surface": surface, "enabled_persisted": enabled_persisted, "capture": capture_mode,
- "sample_rate": frame.get("sample_rate", 16000),
- "frame_length": frame.get("frame_length", 1280)})
+ **_frame_fields(frame)})
@method("wake.stop")
@@ -614,18 +612,15 @@ def _(rid, params: dict) -> dict:
"enabled": bool(cfg.get("enabled")),
# Armed but deaf despite an open stream; see platform-specific hint.
"audio_silent": silent, "capture": capture,
- "local_input_available": bool(reqs.get("local_input_available")),
- "sample_rate": frame.get("sample_rate", 16000),
- "frame_length": frame.get("frame_length", 1280),
- })
+ "local_input_available": bool(reqs.get("local_input_available")), **_frame_fields(frame)})
except Exception as e:
return _err(rid, 5026, str(e))
@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 — for ``capture: "client"`` so mic-less remote backends run openWakeWord."""
+ """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."""
transport = _caller_transport()
raw_b64 = params.get("pcm") or params.get("pcm_b64") or ""
if not isinstance(raw_b64, str) or not raw_b64.strip():
@@ -758,9 +753,8 @@ def _vr_on_status(state):
@method("voice.record")
def _(rid, params: dict) -> dict:
- """VAD-bounded push-to-talk capture. ``start`` begins one capture and emits
- ``voice.transcript`` when silence stops it; ``stop`` forces transcription of the active
- buffer. No-speech counts persist across starts: three silent captures emit ``no_speech_limit``."""
+ """VAD-bounded push-to-talk. ``start`` emits ``voice.transcript`` when silence stops the
+ capture; ``stop`` forces transcription. Three silent captures emit ``no_speech_limit``."""
action = params.get("action", "start")
wake_paused = False
if action not in {"start", "stop"}:
@@ -827,12 +821,12 @@ def _(rid, params: dict) -> dict:
try:
# Import check up front so a missing voice module returns 5026, not a silent thread death.
import hermes_cli.voice # noqa: F401
- threading.Thread(target=_speak_text_with_barge, args=(text,), daemon=True).start()
- return _ok(rid, {"status": "speaking"})
except ImportError:
return _err(rid, 5026, "voice module not available")
except Exception as e:
return _err(rid, 5026, str(e))
+ threading.Thread(target=_speak_text_with_barge, args=(text,), daemon=True).start()
+ return _ok(rid, {"status": "speaking"})
def register(server) -> None: