From 88700898be16c9508a484fce85c822b6f55d909c Mon Sep 17 00:00:00 2001 From: Gabby Morgan Date: Fri, 9 Oct 2026 23:52:57 +0000 Subject: [PATCH] voice: hold the wake word until the scheduler reaches a result Gate the wake word on the scheduler's single slot being free: a wake that fires while the current request is still running is ignored (traced voice_wake_blocked), so a second command cannot start mid-run. The gate is GatewayService.input_ready (False while a run executes, True when idle or paused for the user's answer), handed to adapters via set_input_ready; the voice adapter passes it to VoiceDaemon.input_ready. --- AGENTS.md | 10 ++++++++-- README.md | 5 ++++- config.example.json | 2 +- semif_agent/gateway/service.py | 23 ++++++++++++++++++++++ semif_agent/gateway/voice.py | 10 ++++++++++ semif_agent/voice_transport.py | 19 +++++++++++++++++- tests/test_gateway.py | 33 ++++++++++++++++++++++++++++++++ tests/test_voice_gateway.py | 35 ++++++++++++++++++++++++++++++++-- 8 files changed, 130 insertions(+), 7 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index d249091..24fd761 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -558,7 +558,9 @@ CLI, unit tests (24) + integration tests (2). `voice:`, and every reply is spoken. No remote peer and no allowlist (physical mic access is the authorization). Half-duplex: capture is discarded while a reply is speaking (no barge-in yet); the wake word is required before - every command. The + every command and is held while the scheduler's single slot is still running + the current request (`GatewayService.input_ready`), so a second command cannot + start until the first reaches a result (or pauses for the user's answer). The whole voice stack is optional and lazy-imported (`requirements/voice.txt`, pinned separately from the engine set since it is hardware-dependent); the gateway refuses to start with an install hint. `bootstrap.sh --voice` @@ -1173,7 +1175,11 @@ CLI, unit tests (24) + integration tests (2). pause before the command does not end the capture (then `vad.silence_ms`). **Half-duplex**: capture frames are discarded while a reply is speaking, so the agent never transcribes itself (no barge-in yet); - the wake word is required before every command. `max_speak_chars` + the wake word is required before every command, and is **held while the + scheduler slot is busy** (`GatewayService.input_ready`): a wake that fires + while the current request is still running is ignored (traced + `voice_wake_blocked`), so a second command cannot start until the first + reaches a result. `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 diff --git a/README.md b/README.md index 093c291..2c48d2c 100644 --- a/README.md +++ b/README.md @@ -682,7 +682,10 @@ python -m semif_agent.cli gateway --platform voice run lower than the official models, the seeded `wake.threshold` is `0.2` (the official models score ~0.99 and use `0.5`). - **Behavior.** Half-duplex — capture is discarded while a reply is speaking, so - the agent never transcribes itself (no barge-in yet). A short beep plays when + the agent never transcribes itself (no barge-in yet). The wake word is required + before every command and is held while the scheduler is still running the + current request, so a second command cannot start until the first reaches a + result. A short beep plays when the wake word fires (`gateway.voice.cue`), so you know you're being heard; a short multi-note "bling" (`cue.submit_notes`, each entry `[frequency_hz, duration_ms]`, spaced by `cue.note_gap_ms`) plays once the diff --git a/config.example.json b/config.example.json index ce16d00..001ce6c 100644 --- a/config.example.json +++ b/config.example.json @@ -217,7 +217,7 @@ "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 (official models download into the venv and resolve by name; a pinned community model such as the default 'hey_computer' is fetched into model_dir, .runtime/voice/wake); 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 the wake word, listen_timeout_s is how long to wait for the command to start before giving up, so a pause before speaking does not truncate it. 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. A stalled capture stream (the PortAudio callback stops delivering frames) is detected via audio.read_timeout_s and recovered by closing and reopening the input after audio.stall_timeout_s, so the front end no longer hangs silently. Utterances run on a worker thread (not the audio thread), so a slow or failing task neither stops the mic being read nor kills the front end.", + "_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 (official models download into the venv and resolve by name; a pinned community model such as the default 'hey_computer' is fetched into model_dir, .runtime/voice/wake); 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 the wake word, listen_timeout_s is how long to wait for the command to start before giving up, so a pause before speaking does not truncate it. The wake word is required before every command and is held while the scheduler is still running the current request, so a new command cannot start until it reaches a result. 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. A stalled capture stream (the PortAudio callback stops delivering frames) is detected via audio.read_timeout_s and recovered by closing and reopening the input after audio.stall_timeout_s, so the front end no longer hangs silently. Utterances run on a worker thread (not the audio thread), so a slow or failing task neither stops the mic being read nor kills the front end.", "enabled": false, "chat_id": "voice", "display_name": "voice", diff --git a/semif_agent/gateway/service.py b/semif_agent/gateway/service.py index 56de86e..b273279 100644 --- a/semif_agent/gateway/service.py +++ b/semif_agent/gateway/service.py @@ -128,6 +128,13 @@ class GatewayService: humanize_cfg = humanize_cfg if isinstance(humanize_cfg, dict) else {} self._humanize_default = bool(humanize_cfg.get("enabled", False)) self.humanizer = self._build_humanizer(humanize_cfg) + #: Let an adapter that needs it gate input on the scheduler being free + #: (the voice gateway holds the wake word until the current request + #: reaches a result). Generic hook; only some adapters implement it. + for adapter in self.adapters.values(): + setter = getattr(adapter, "set_input_ready", None) + if callable(setter): + setter(self.input_ready) self._owners: dict[str, Target] = {} self._parents: dict[str, str] = {} self._pending_owner: Target | None = None @@ -275,6 +282,22 @@ class GatewayService: return (platform, source[len(prefix):]) return None + def input_ready(self) -> bool: + """Whether a new command may start now. + + False while the single scheduler slot is executing a run; True when the + scheduler is idle or paused for the user's answer to a question (the run + is not running, so the answer must be accepted). The voice gateway uses + this to hold the wake word until the current request has reached a + result. Reads the scheduler's flags without its lock on purpose — the + lock is held for the whole run, so acquiring it here would block the + audio loop for the duration of the run. + """ + scheduler = self.scheduler + if getattr(scheduler, "pending", None) is not None: + return True + return getattr(scheduler, "current", None) is None + def handle_inbound(self, msg: InboundMessage, platform: str | None = None) -> None: """Handle one authorized inbound command. Called by the adapter.""" if platform is None: diff --git a/semif_agent/gateway/voice.py b/semif_agent/gateway/voice.py index 0b2c7e1..7af5e03 100644 --- a/semif_agent/gateway/voice.py +++ b/semif_agent/gateway/voice.py @@ -53,6 +53,16 @@ class VoiceAdapter(GatewayAdapter): def check_requirements(self) -> tuple[bool, str | None]: return self.daemon.check_requirements() + def set_input_ready(self, ready) -> None: + """Gate the wake word on the scheduler being able to accept a command. + + `ready` is a callable returning whether a new command may start now + (`GatewayService.input_ready`). While it returns False the wake word is + ignored, so a second command cannot be started before the current + request has reached a result. + """ + self.daemon.input_ready = ready + # ---- transport ---- def run( diff --git a/semif_agent/voice_transport.py b/semif_agent/voice_transport.py index 9e37633..bb2fcdf 100644 --- a/semif_agent/voice_transport.py +++ b/semif_agent/voice_transport.py @@ -633,11 +633,16 @@ class VoiceDaemon: """ def __init__(self, cfg: dict | None = None, trace=None, engines: VoiceEngines | None = None, - name: str = "voice"): + name: str = "voice", input_ready=None): cfg = cfg or {} self.config = cfg self.trace = trace self.name = name + #: Optional predicate: whether a new command may start now. While it + #: returns False the wake word is ignored (the scheduler's single slot + #: is still running the current request), so a second command cannot be + #: started before the first reaches a result. None = always ready. + self.input_ready = input_ready self.wake_threshold = float((cfg.get("wake", {}) or {}).get("threshold", 0.2)) #: After the wake word, how long to wait for the command's speech to #: begin before giving up (a natural pause after "hey " — e.g. @@ -766,6 +771,18 @@ class VoiceDaemon: score = engines.wake.score(pcm) if score < self.wake_threshold: continue + if self.input_ready is not None and not self.input_ready(): + # The single scheduler slot is still running the current + # request: hold the wake word until it reaches a result (or + # pauses for the user's answer), so a new command cannot start + # while one is in flight. Reset the detector so the same wake + # phrase does not immediately re-fire once the slot frees. + try: + engines.wake.reset() + except Exception: + pass + self._event("voice_wake_blocked", score=round(float(score), 3)) + continue self._event("voice_wake", score=round(float(score), 3)) try: engines.wake.reset() diff --git a/tests/test_gateway.py b/tests/test_gateway.py index 24cb7ba..06e1089 100644 --- a/tests/test_gateway.py +++ b/tests/test_gateway.py @@ -186,6 +186,39 @@ def test_service_submit_error_is_replied(tmp_path): assert outbound, "expected a reply" +def test_service_input_ready_tracks_scheduler(tmp_path): + # The voice gateway holds the wake word on this: not ready while a run is + # executing, ready when idle or paused for the user's answer. + scheduler = build_scheduler(tmp_path) + service = build_service(scheduler) + assert service.input_ready() is True # idle + scheduler.busy("working") + assert service.input_ready() is False # a run is executing + scheduler.pending = object() # paused for the answer + assert service.input_ready() is True + scheduler.pending = None + scheduler.current = None + assert service.input_ready() is True + + +def test_service_wires_input_ready_into_voice_adapter(tmp_path): + # A constructed service hands its `input_ready` to an adapter that exposes + # `set_input_ready` (the voice gateway). + class ReadyAdapter: + name = "voice" + + def __init__(self): + self.ready = None + + def set_input_ready(self, fn): + self.ready = fn + + scheduler = build_scheduler(tmp_path) + adapter = ReadyAdapter() + service = GatewayService(scheduler, adapter, config={}) + assert adapter.ready == service.input_ready + + def test_service_routes_pending_answer_to_same_chat(tmp_path): scheduler = build_scheduler(tmp_path) service = build_service(scheduler) diff --git a/tests/test_voice_gateway.py b/tests/test_voice_gateway.py index 389982a..392b1c3 100644 --- a/tests/test_voice_gateway.py +++ b/tests/test_voice_gateway.py @@ -84,7 +84,7 @@ class FakeTts: return b"PCM", 22050 -def make_daemon(frames, stt_text="hello", config=None): +def make_daemon(frames, stt_text="hello", config=None, input_ready=None): audio = FakeAudio(frames) engines = VoiceEngines( wake=FakeWake(), @@ -100,7 +100,7 @@ def make_daemon(frames, stt_text="hello", config=None): } if config: cfg.update(config) - return VoiceDaemon(cfg, engines=engines), engines + return VoiceDaemon(cfg, engines=engines, input_ready=input_ready), engines # ---- requirements ---------------------------------------------------------- @@ -150,6 +150,37 @@ def test_no_wake_word_produces_nothing(): assert engines.stt.calls == [] +# ---- input gating (hold the wake word while the scheduler is busy) --------- + + +def test_wake_blocked_while_input_not_ready(): + # While the scheduler slot is busy the wake word is ignored: no cue, no + # capture, no transcription (traced `voice_wake_blocked`). + ready = {"ok": False} + daemon, engines = make_daemon( + [b"WAKE", b"speech", b"SIL", b"SIL"], input_ready=lambda: ready["ok"] + ) + events = [] + daemon._event = lambda kind, **kw: events.append(kind) + heard = [] + daemon.run(heard.append) + assert heard == [] + assert engines.stt.calls == [] + assert engines.audio.writes == [] + assert "voice_wake_blocked" in events + assert "voice_wake" not in events + + +def test_wake_allowed_when_input_ready(): + ready = {"ok": True} + daemon, engines = make_daemon( + [b"WAKE", b"speech", b"SIL", b"SIL"], input_ready=lambda: ready["ok"] + ) + heard = [] + daemon.run(heard.append) + assert heard == ["hello"] + + def test_max_utterance_caps_collection(monkeypatch): import semif_agent.voice_transport as vt