From e8d1685177ac8151c4fd535fbf15f155d81a3b8a Mon Sep 17 00:00:00 2001 From: Gabby Morgan Date: Tue, 6 Oct 2026 05:55:07 +0000 Subject: [PATCH] voice gateway returns skill result only --- AGENTS.md | 6 +++ README.md | 8 +++- config.example.json | 3 +- semif_agent/gateway/base.py | 6 +++ semif_agent/gateway/service.py | 67 ++++++++++++++++++++++++++++++---- semif_agent/gateway/voice.py | 4 ++ tests/test_gateway.py | 49 +++++++++++++++++++++++++ tests/test_voice_gateway.py | 6 +++ 8 files changed, 138 insertions(+), 11 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 8501896..3a74153 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -961,6 +961,12 @@ CLI, unit tests (24) + integration tests (2). wake word, so answering a question is conversational. `max_speak_chars` truncates long replies before speaking, and a short sine `cue` beep plays on wake (optionally again on transcription) so the user knows they were heard. + **Result-only output**: `VoiceAdapter.result_only` (default true; per-platform + config `result_only` overrides) makes `GatewayService` speak just the skill's + result line — queue/urgency chatter is dropped and the `: ok —` wrapper + is stripped — so the spoken output is the answer, not the scheduler's + internals. Questions, repair offers, approvals, and timer notifications are + still spoken. Every heavy dep (`sounddevice`/`openwakeword`/`faster_whisper`/`piper`/`onnxruntime`) is **lazy-imported**; `check_requirements()` returns an install hint and the diff --git a/README.md b/README.md index 6d27a3b..030ee53 100644 --- a/README.md +++ b/README.md @@ -667,8 +667,12 @@ python -m semif_agent.cli gateway --platform voice transcribed. After a reply, the next utterance is accepted **without** the wake word for `follow_up_window_s`, so answering a question is conversational. `max_speak_chars` truncates long - replies before speaking. There is no allowlist: the mic is local, so physical - access is the authorization. + replies before speaking. `result_only` (default true for voice) speaks only the + skill's result line — queue/urgency bookkeeping is dropped and the + `: ok —` wrapper is stripped — so the spoken output is the answer, not + the scheduler's internals; set it false to speak the full scheduler output. + There is no allowlist: the mic is local, so physical access is the + authorization. - **Run mode.** Foreground, in the user's audio session — a headless systemd user service does not share the user's audio session, so voice is not rendered as a unit. diff --git a/config.example.json b/config.example.json index 27d6049..6318b3e 100644 --- a/config.example.json +++ b/config.example.json @@ -160,12 +160,13 @@ "text_batch_delay": 0.8 }, "voice": { - "_comment": "Voice command adapter: a local microphone front end with wake word + speech-to-text + text-to-speech. Requires the optional voice stack (requirements/voice.txt; sounddevice + openwakeword + faster-whisper + piper-tts + onnxruntime; the system needs libportaudio2). Lazy-imported; the gateway refuses to start with an install hint. Runs best in the user's audio session (foreground `gateway --platform voice`), not a headless systemd user service. Audio is 16 kHz mono int16; capture/playback run at the device's native rate and are resampled to/from 16 kHz (capture_sample_rate/output_sample_rate override it; 0 = the device default). wake.model is an openWakeWord model name or path (bootstrap downloads models into the venv, where they resolve by name; model_dir is an optional local dir for a custom model file); stt.model is a faster-whisper size/path (cached under .runtime/hf); tts.voice is a Piper voice id or path (bootstrap downloads it under .runtime/voice/tts). After each reply the next utterance is accepted without the wake word for follow_up_window_s. max_speak_chars truncates long replies before speaking. chat_id identifies the single local session; home_channel defaults to it so timers/repair offers are spoken too.", + "_comment": "Voice command adapter: a local microphone front end with wake word + speech-to-text + text-to-speech. Requires the optional voice stack (requirements/voice.txt; sounddevice + openwakeword + faster-whisper + piper-tts + onnxruntime; the system needs libportaudio2). Lazy-imported; the gateway refuses to start with an install hint. Runs best in the user's audio session (foreground `gateway --platform voice`), not a headless systemd user service. Audio is 16 kHz mono int16; capture/playback run at the device's native rate and are resampled to/from 16 kHz (capture_sample_rate/output_sample_rate override it; 0 = the device default). wake.model is an openWakeWord model name or path (bootstrap downloads models into the venv, where they resolve by name; model_dir is an optional local dir for a custom model file); stt.model is a faster-whisper size/path (cached under .runtime/hf); tts.voice is a Piper voice id or path (bootstrap downloads it under .runtime/voice/tts). After each reply the next utterance is accepted without the wake word for follow_up_window_s. result_only speaks just the skill's result line (dropping queue/urgency bookkeeping and the `: ok —` wrapper) instead of the full scheduler output; set false for the complete text. max_speak_chars truncates long replies before speaking. chat_id identifies the single local session; home_channel defaults to it so timers/repair offers are spoken too.", "enabled": false, "chat_id": "voice", "display_name": "voice", "home_channel": "voice", "reply_prefix": "", + "result_only": true, "max_speak_chars": 600, "follow_up_window_s": 5.0, "cue": { diff --git a/semif_agent/gateway/base.py b/semif_agent/gateway/base.py index bc7c9e3..4f7ac1e 100644 --- a/semif_agent/gateway/base.py +++ b/semif_agent/gateway/base.py @@ -51,6 +51,12 @@ class GatewayAdapter(ABC): #: short platform name used in request sources (`"simplex:"`) name: str = "gateway" + #: Spoken front ends (the voice gateway) set this so the service speaks only + #: the skill's result line, not the scheduler's bookkeeping (queue/urgency + #: status) and not the `: ok —` wrapper. A per-platform config + #: `result_only` overrides it. Plain chat adapters leave it False. + result_only: bool = False + @abstractmethod def check_requirements(self) -> tuple[bool, str | None]: """Return `(ok, install_hint)`. Must never raise on a missing dep.""" diff --git a/semif_agent/gateway/service.py b/semif_agent/gateway/service.py index dfbaefc..56650c7 100644 --- a/semif_agent/gateway/service.py +++ b/semif_agent/gateway/service.py @@ -29,6 +29,11 @@ from .base import InboundMessage, OutboundMessage _LEADING_RUN_ID = re.compile(r"^\[[0-9a-f]{6,}\]\s*") +#: The scheduler's run summary wraps the real result as +#: `": — "`. A result-only platform (the voice +#: gateway) speaks just ``. +_RESULT_SEP = " — " + _REPAIR_ACTIONS = { "retry": "retry", "repair": "repair_skill", @@ -64,6 +69,28 @@ def _leading_run_id(text: str) -> str: return match.group(0)[1:-2] if match else "" +def _result_detail(text: str) -> str: + """Unwrap the scheduler's `": — "` summary. + + Returns the detail the skill actually produced. A line with no wrapper is + returned unchanged. + """ + if _RESULT_SEP in text: + return text.split(_RESULT_SEP, 1)[1].strip() + return text + + +def _reply_kind(status: str) -> str: + """Classify a scheduler outcome for a result-only front end.""" + if status in ("running", "preempted", "ran"): + return "result" + if status == "needs_input": + return "question" + if status == "queued": + return "status" + return "notice" + + def _normalize_adapters(adapters) -> dict: """Accept a single adapter or a list/dict of them, keyed by platform name.""" if isinstance(adapters, dict): @@ -127,6 +154,17 @@ class GatewayService: def _home_channel(self, platform: str) -> str: return str(self._platform_cfg.get(platform, {}).get("home_channel", "") or "") + def _result_only(self, platform: str) -> bool: + """Whether this platform speaks only the skill result line. + + The adapter declares the default (the voice adapter sets `result_only`); + a per-platform config `result_only` overrides it either way. + """ + cfg = self._platform_cfg.get(platform, {}) + if "result_only" in cfg: + return bool(cfg["result_only"]) + return bool(getattr(self.adapters.get(platform), "result_only", False)) + def _fallback_target(self) -> Target | None: for platform in self.platforms: home = self._home_channel(platform) @@ -184,29 +222,30 @@ class GatewayService: status, detail = self.scheduler.answer(msg.text) if self.scheduler.pending is None: self._pending_owner = None - self._reply(*reply_to, detail) + self._reply(*reply_to, detail, kind=_reply_kind(status)) elif pending is not None and self._pending_owner not in (None, reply_to): self._reply( *reply_to, "I'm waiting for a reply in another conversation; please resend in a moment.", + kind="notice", ) elif reply_to in self._question_for_chat: question_id = self._question_for_chat.pop(reply_to) status, detail = self.scheduler.answer_question(question_id, msg.text) self._surfaced.add(question_id) - self._reply(*reply_to, detail) + self._reply(*reply_to, detail, kind="notice") elif reply_to in self._repair_for_chat and msg.text.strip().lower() in _REPAIR_ACTIONS: offer_id = self._repair_for_chat.pop(reply_to) action = _REPAIR_ACTIONS[msg.text.strip().lower()] status, detail = self.scheduler.resolve_repair(offer_id, action) self._surfaced.add(offer_id) - self._reply(*reply_to, detail) + self._reply(*reply_to, detail, kind="notice") elif reply_to in self._approval_for_chat and msg.text.strip().lower() in _APPROVAL_ACTIONS: approval_id = self._approval_for_chat.pop(reply_to) approved = _APPROVAL_ACTIONS[msg.text.strip().lower()] status, detail = self.scheduler.answer_approval(approval_id, approved) self._surfaced.add(approval_id) - self._reply(*reply_to, detail) + self._reply(*reply_to, detail, kind="notice") else: status, detail, run_id = self.scheduler.submit_request( msg.text, source=self.source_for(platform, msg.chat_id) @@ -215,7 +254,7 @@ class GatewayService: self._owners[run_id] = reply_to if status == "needs_input": self._pending_owner = reply_to - self._reply(*reply_to, detail) + self._reply(*reply_to, detail, kind=_reply_kind(status)) self.drain() self.surface(origin=reply_to) @@ -233,7 +272,7 @@ class GatewayService: self._pending_owner = owner target = owner or self._fallback_target() if target: - self._reply(*target, text) + self._reply(*target, text, kind=_reply_kind(status)) def surface(self, origin: Target | None = None) -> None: """Send any newly posted authoring questions / repair offers.""" @@ -252,6 +291,7 @@ class GatewayService: self._reply( *target, f"(authoring {item['category']}.{item['skill']}) {item['question']}", + kind="question", ) repairs = self.scheduler.pending_repairs() @@ -272,6 +312,7 @@ class GatewayService: f"{offer['category']}.{offer['skill']} failed: " f"{offer['failure'][:200]}\nReply retry / repair / ask / no." ), + kind="notice", ) approvals = self.scheduler.pending_approvals() @@ -297,12 +338,13 @@ class GatewayService: f"Approve creating new {item['kind']} {label}: " f"{item['description']}\nReply yes / no." ), + kind="notice", ) for fired in self.scheduler.timers.drain(): target = self._resolve_target(fired.run_id, origin) if target: - self._reply(*target, fired.message) + self._reply(*target, fired.message, kind="notice") # ---- scheduler requeue hook (called under the scheduler lock) ---- @@ -333,8 +375,17 @@ class GatewayService: # ---- outbound ---- - def _reply(self, platform: str, chat_id: str, text: str) -> None: + def _reply( + self, platform: str, chat_id: str, text: str, kind: str = "reply" + ) -> None: text = _strip_run_id(text) + if self._result_only(platform): + # A spoken front end says the skill's result, not the scheduler's + # bookkeeping: drop queue/urgency chatter and unwrap the result line. + if kind == "status": + return + if kind == "result": + text = _result_detail(text) prefix = str(self._platform_cfg.get(platform, {}).get("reply_prefix", "") or "") if prefix: text = f"{prefix}{text}" diff --git a/semif_agent/gateway/voice.py b/semif_agent/gateway/voice.py index b7f7521..a6701a3 100644 --- a/semif_agent/gateway/voice.py +++ b/semif_agent/gateway/voice.py @@ -30,6 +30,10 @@ from .base import GatewayAdapter, InboundMessage, OutboundMessage class VoiceAdapter(GatewayAdapter): name = "voice" + #: Speak the skill's result line only — the spoken front end should not read + #: out queue/urgency bookkeeping or the `: ok —` wrapper. Override + #: with `gateway.voice.result_only: false` for the full scheduler output. + result_only = True def __init__(self, cfg: dict | None = None, trace=None): cfg = cfg or {} diff --git a/tests/test_gateway.py b/tests/test_gateway.py index a2cece2..52ae7da 100644 --- a/tests/test_gateway.py +++ b/tests/test_gateway.py @@ -281,6 +281,55 @@ def test_service_surfaces_and_resolves_approval(tmp_path): assert any("approved" in text for text in drain_outbound(service)) +# ---- service: result-only front end (voice) ---- + +class FakeResultOnlyAdapter: + name = "voice" + result_only = True + + +def build_result_only_service(scheduler, config=None): + return GatewayService(scheduler, FakeResultOnlyAdapter(), config=config or {}) + + +def test_result_detail_unwraps_scheduler_summary(): + from semif_agent.gateway.service import _result_detail + + assert _result_detail("time.now: ok — 2026-10-06 12:00") == "2026-10-06 12:00" + assert _result_detail("interrupted x; time.now: ok — 12:00") == "12:00" + assert _result_detail("a plain reply") == "a plain reply" + + +def test_result_only_speaks_detail_and_drops_status(tmp_path): + scheduler = build_scheduler(tmp_path) + service = build_result_only_service(scheduler) + service._reply("voice", "c", "[high] time.now: ok — 12:00", kind="result") + service._reply("voice", "c", "urgency low (weight 0.20)", kind="status") + service._reply("voice", "c", "Which account?", kind="question") + assert drain_outbound(service) == ["12:00", "Which account?"] + + +def test_plain_adapter_keeps_full_scheduler_output(tmp_path): + scheduler = build_scheduler(tmp_path) + service = build_service(scheduler) # FakeAdapter (simplex), not result_only + service._reply("simplex", "4", "[high] time.now: ok — 12:00", kind="result") + service._reply("simplex", "4", "urgency low (weight 0.20)", kind="status") + assert drain_outbound(service) == [ + "[high] time.now: ok — 12:00", + "urgency low (weight 0.20)", + ] + + +def test_config_can_turn_result_only_off(tmp_path): + scheduler = build_scheduler(tmp_path) + service = build_result_only_service( + scheduler, config={"voice": {"result_only": False}} + ) + service._reply("voice", "c", "[high] time.now: ok — 12:00", kind="result") + service._reply("voice", "c", "urgency low", kind="status") + assert drain_outbound(service) == ["[high] time.now: ok — 12:00", "urgency low"] + + # ---- LXMF adapter ---- def test_lxmf_default_deny_and_allowlist(): diff --git a/tests/test_voice_gateway.py b/tests/test_voice_gateway.py index 22db156..a5aa921 100644 --- a/tests/test_voice_gateway.py +++ b/tests/test_voice_gateway.py @@ -247,6 +247,12 @@ def test_adapter_ignores_empty_utterance(): assert seen == [] +def test_adapter_is_result_only(): + # The spoken front end speaks only the skill's result line, not the + # scheduler's bookkeeping (overridable via gateway.voice.result_only). + assert VoiceAdapter({}).result_only is True + + # ---- CLI wiring ------------------------------------------------------------