voice gateway returns skill result only

This commit is contained in:
gabby committed 2026-10-06 05:55:07 +00:00
1 parent 172e61e6be
commit e8d1685177
8 files changed
+138 -11

No files matched your search

+6
View File
@@ -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 `<skill>: 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
+6 -2
View File
@@ -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
`<skill>: 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.
+2 -1
View File
@@ -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 `<skill>: 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": {
+6
View File
@@ -51,6 +51,12 @@ class GatewayAdapter(ABC):
#: short platform name used in request sources (`"simplex:<chat_id>"`)
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 `<skill>: 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."""
+59 -8
View File
@@ -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
#: `"<skill>: <ok|failed> — <detail>"`. A result-only platform (the voice
#: gateway) speaks just `<detail>`.
_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 `"<skill>: <ok|failed> — <detail>"` 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}"
+4
View File
@@ -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 `<skill>: 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 {}
+49
View File
@@ -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():
+6
View File
@@ -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 ------------------------------------------------------------