From 894a85ec2d07854f069ad49102b030bb4a52bfe2 Mon Sep 17 00:00:00 2001 From: Gabby Morgan Date: Sat, 17 Oct 2026 23:29:53 +0000 Subject: [PATCH] read-aloud: stream a long text over the voice gateways A skill that resolves a long text (a book) can hand it to the scheduler's speech channel and return immediately; the gateway that owns the chat drains it and streams it with text-to-speech until the user stops it. - semif_agent/speech.py: SpeechService + ReadAloud. A bounded queue a front end drains, plus a per-source streaming predicate (set_stream_check/supports) so a skill asks before it posts one. Neutral and stdlib-only. - semif_agent/reading.py: the bookmarks.json beside the saved books (load/save/ read a key -> last offset, atomic write) and a deterministic speakable chunker at paragraph/sentence boundaries. - Scheduler owns the channel (scheduler.speech); SkillRunner passes it into every run's ActionContext, so a body reaches it as ctx.speech. - gateway/service: registers stream_ready as the channel's capability predicate, and surface() routes a drained read to the platform that owns the run (a non-streaming adapter is traced and skipped, never handed a message it would drop). - gateway/voice: streams the saved text through the daemon's Piper voice chunk by chunk, writing the bookmark before each chunk; a barge-in "stop" or any new command ends it. - gateway/lxmf: a read goes to a chat that last messaged by voice as a sequence of Sideband HQ voice messages (Piper -> Opus/OGG, backpressure so a stop is prompt), with the same bookmark-per-chunk resume; a "stop" message or any new command interrupts it. - A run that registers a read is terminal (read_aloud_terminal): the read is the answer, so assess:outcome must not re-dispatch the request (which otherwise authored a spurious skill). - config.example.json regenerated with the new voice/lxmf read blocks. --- AGENTS.md | 68 ++++++++- config.example.json | 8 + semif_agent/config.py | 13 ++ semif_agent/gateway/base.py | 60 +++++++- semif_agent/gateway/lxmf.py | 146 +++++++++++++++++- semif_agent/gateway/service.py | 66 ++++++++ semif_agent/gateway/voice.py | 179 ++++++++++++++++------ semif_agent/lxmf_transport.py | 9 ++ semif_agent/reading.py | 140 +++++++++++++++++ semif_agent/scheduler.py | 13 ++ semif_agent/skill.py | 3 + semif_agent/skills.py | 6 + semif_agent/speech.py | 164 ++++++++++++++++++++ semif_agent/voice_transport.py | 8 + tests/test_gateway.py | 272 +++++++++++++++++++++++++++++++++ tests/test_reading.py | 144 +++++++++++++++++ tests/test_skills.py | 29 ++++ tests/test_voice_gateway.py | 203 ++++++++++++++++++++++++ 18 files changed, 1478 insertions(+), 53 deletions(-) create mode 100644 semif_agent/reading.py create mode 100644 semif_agent/speech.py create mode 100644 tests/test_reading.py diff --git a/AGENTS.md b/AGENTS.md index 84d12f1..623b92a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -199,6 +199,20 @@ timers.py in-process timer/alarm service (TimerService) owned by the the gateway routes it to the originating chat, the dashboard shows pending/fired). Real local compute (`compute` transport), per-process, and deliberately NOT persisted across restarts. +reading.py neutral long-form reading helpers (stdlib): the + `bookmarks.json` beside the saved books (load/save/read a book + key -> last read offset, atomic write) and a deterministic + speakable chunker (`chunk_text` -> `(offset, chunk)` at + paragraph/sentence boundaries). Knows nothing about the + scheduler, a gateway, or audio. +speech.py the scheduler's speech channel (SpeechService on + ActionContext.speech, the sibling of timers): a skill that + resolves a long text to be read aloud registers a `ReadAloud` + (path + bookmark key + start offset) and returns immediately; + the gateway owning the chat drains it and hands it to the + platform adapter, which streams it with text-to-speech until + the user stops it. Neutral and stdlib-only; the skill never + reaches into a front end. engine.py DecisionEngine (the pluggable contract: call/warm/loaded/ generate) + SemIfEngine, the default local provider -> semif_phase1.llamacpp_backend (lazy import); call() scores a @@ -726,6 +740,40 @@ CLI, unit tests (24) + integration tests (2). the venv under `.runtime/venv`, the Piper voice under `.runtime/voice/tts`, the faster-whisper model in the `.runtime/hf` cache). See "### gateway (messenger intake)". +- **Read a book aloud over a voice front end** (Oct 2026): a skill that + resolves a long text can ask the front end to read it aloud instead of + returning a bounded summary. The skill asks the scheduler's speech channel + (`ctx.speech`, `semif_agent/speech.py` — the sibling of `ctx.timers`) + `supports(source)`; the gateway service registers the per-source predicate at + startup, so a skill only offers a read to a front end that can stream one + (a typed request, or a platform with no voice path, keeps the saved-file + summary). It then registers a `ReadAloud` and returns immediately; + `GatewayService.surface()` drains it and queues an `OutboundMessage` whose + `stream` field carries the request to the platform that owns the run (any + other platform is traced `gateway_stream_unsupported` and skipped, never + handed a message it would drop silently). Two adapters stream it: the local + **voice gateway** plays it through the daemon's Piper voice one chunk at a + time (`gateway.voice.read.enabled`), and the **LXMF voice gateway** sends it + to a voice chat as a sequence of Piper Opus/OGG voice messages + (`gateway.lxmf.voice.read.enabled`; a chat that last messaged by voice). Both + use `reading.chunk_text` with a chunk size clamped below the platform's + speakable budget so a chunk is never truncated, and write the bookmark before + each chunk so the position is the interrupted chunk's start. The read is + **background**: it does not hold the scheduler's single slot, so the agent + stays free. A run that registers a read is treated as **terminal** + (`read_aloud_terminal`): the read is the answer, so `assess:outcome` must not + re-dispatch the request (which otherwise authored a spurious skill). The user + stops it like any spoken reply — a wake-word barge-in "stop", or on LXMF a + "stop" message (any new command also interrupts it; traced + `gateway_read_stop`/`_interrupted`/`_done` on voice, + `lxmf_read_*` on LXMF). Position lives in a `bookmarks.json` beside the saved + books (`semif_agent/reading.py`), so a later request resumes where the + listener stopped. `gutendex.read_book` is the first consumer: it checks the + **local library** (the books folder) first — a book already saved is read from + disk (matched by id, or by the name in the request) with no network, and a + catalog-resolved book is reused from disk rather than re-downloaded — then + over a voice front end reads it aloud, while over any other source it keeps + returning the saved-file summary. - **Custom Piper voice (train your own)** (Oct 2026): the TTS voice is replaceable with one fine-tuned on the user's own recordings. This is an optional, off-bootstrap pipeline (`scripts/voice-record.py` records an @@ -1477,6 +1525,14 @@ CLI, unit tests (24) + integration tests (2). is stripped — so a reply (text or voice) is the answer, not the scheduler's internals. Questions, repair offers, approvals, and timer notifications still pass through. + **Read-aloud**: a `ReadAloud` the service routes here (a skill posted it via + `ctx.speech`) is streamed to the chat as a sequence of voice messages: `_stream` + reads the saved text, Piper-synthesizes each chunk to Opus/OGG, and queues it + on the daemon, writing the bookmark before each chunk. It stops when the text + ends or the user interrupts — a "stop" message (intercepted in `_deliver`, + never submitted as a request) or any new command. Only a chat that last + messaged by voice receives one (`speech_stream_ready`); a text chat keeps the + skill's saved-file summary. `gateway.lxmf.voice.read.{enabled,chunk_chars}`. - **Voice adapter** (`gateway/voice.py`): the local microphone front end. It is a policy layer over the neutral `semif_agent/voice_transport.py` (`VoiceDaemon`) — openWakeWord wake word → `webrtcvad` endpointing → faster-whisper @@ -1527,6 +1583,15 @@ CLI, unit tests (24) + integration tests (2). is stripped — so the spoken output is the answer, not the scheduler's internals. Questions, repair offers, approvals, and timer notifications are still spoken. + **Read-aloud**: the pump also handles an `OutboundMessage` whose `stream` + carries a `ReadAloud` (a skill posted it via `ctx.speech`; the service routes + it here — see the roadmap entry). `_stream` reads the saved text and speaks it + chunk by chunk through the daemon's Piper voice, writing the bookmark before + each chunk; it stops when the text ends, when the user stops it (a barge-in + "stop" — the daemon mutes playback, which the loop notices — or a bare "stop" + heard between chunks), or when any new command arrives. `supports_speech_stream` + (`gateway.voice.read.enabled`, default on) gates the whole path; + `read.chunk_chars` bounds one chunk (clamped below `max_speak_chars`). Every heavy dep (`sounddevice`/`openwakeword`/`faster_whisper`/`piper`/`onnxruntime`) is **lazy-imported**; `check_requirements()` returns an install hint and the @@ -1710,7 +1775,8 @@ CLI, unit tests (24) + integration tests (2). `packs.`. Shared, skill-less bridges (the LLM bridge) live in `semif_agent/config.py` `SHARED_BRIDGE_SCHEMA`. - **Shipped packs.** `nextcloud`, `simplex`, `outlook`, `browser` (each owning - its bridge) and `essentials` (the built-in local utilities `time` + + its bridge), `gutendex` (Project Gutenberg book catalog + full-text download; + no bridge) and `essentials` (the built-in local utilities `time` + `calculator` + `skills`; no bridge) — each in its own repository. Adding a concern means adding a pack repo, not editing `skills.py`. diff --git a/config.example.json b/config.example.json index d8e8c8f..9eac616 100644 --- a/config.example.json +++ b/config.example.json @@ -164,6 +164,10 @@ "reply_with_voice": true, "max_speak_chars": 600, "reply_bitrate": 24000, + "read": { + "enabled": true, + "chunk_chars": 300 + }, "stt": { "model": "base.en", "device": "cpu", @@ -187,6 +191,10 @@ "reply_prefix": "", "result_only": true, "max_speak_chars": 600, + "read": { + "enabled": true, + "chunk_chars": 300 + }, "listen_timeout_s": 3.0, "cue": { "enabled": true, diff --git a/semif_agent/config.py b/semif_agent/config.py index 5bae3a0..b8b1eaf 100644 --- a/semif_agent/config.py +++ b/semif_agent/config.py @@ -180,6 +180,12 @@ CORE_SCHEMA: dict[str, Any] = {'tau': {'default': 0.6, 'type': 'float', 'doc': ' 'reply_with_voice': {'default': True, 'type': 'bool'}, 'max_speak_chars': {'default': 600, 'type': 'int'}, 'reply_bitrate': {'default': 24000, 'type': 'int'}, + # Read a long text (a book) aloud to a voice + # chat as a sequence of voice messages until the + # user sends "stop". Position is kept in a + # bookmarks.json beside the saved text. + 'read': {'enabled': {'default': True, 'type': 'bool'}, + 'chunk_chars': {'default': 300, 'type': 'int'}}, 'stt': {'model': {'default': 'base.en', 'type': 'str'}, 'device': {'default': 'cpu', 'type': 'str'}, 'compute_type': {'default': 'int8', 'type': 'str'}, @@ -198,6 +204,13 @@ CORE_SCHEMA: dict[str, Any] = {'tau': {'default': 0.6, 'type': 'float', 'doc': ' 'reply_prefix': {'default': '', 'type': 'str'}, 'result_only': {'default': True, 'type': 'bool'}, 'max_speak_chars': {'default': 600, 'type': 'int'}, + # Read a long text (a book) aloud: a skill registers a + # read-aloud request and this front end streams it through + # Piper one chunk at a time until the user stops it. The + # position is kept in a bookmarks.json beside the text. + # `chunk_chars` bounds one spoken chunk. + 'read': {'enabled': {'default': True, 'type': 'bool'}, + 'chunk_chars': {'default': 300, 'type': 'int'}}, 'listen_timeout_s': {'default': 3.0, 'type': 'float'}, 'cue': {'enabled': {'default': True, 'type': 'bool'}, 'frequency': {'default': 880, 'type': 'int'}, diff --git a/semif_agent/gateway/base.py b/semif_agent/gateway/base.py index 9ad0b60..ab3129e 100644 --- a/semif_agent/gateway/base.py +++ b/semif_agent/gateway/base.py @@ -35,16 +35,74 @@ class InboundMessage: @dataclass class OutboundMessage: - """One reply destined for an external chat.""" + """One reply destined for an external chat. + + `text` is the reply. `stream` optionally carries a long-form read-aloud + request (a `semif_agent.speech.ReadAloud`) instead of a plain line: the + voice front end streams it chunk-by-chunk with text-to-speech until the user + stops it. A platform that does not stream leaves it None and speaks `text`. + """ chat_id: str text: str + stream: Any = None #: Callback the adapter invokes for each authorized inbound message. InboundHandler = Callable[[InboundMessage], None] +#: Words/phrases that abort a long-form read-aloud (and a spoken reply) when +#: heard/typed. The match is on the whole normalized utterance (so "stop the +#: timer" stays a real command) with a first-word fallback only for a short +#: utterance with trailing filler ("stop please", "cancel that"). Shared by the +#: voice and LXMF adapters, which both stream read-aloud text. +_STOP_PHRASES = { + "stop", + "stop it", + "stop talking", + "stop please", + "cancel", + "cancel that", + "cancel please", + "quiet", + "quiet down", + "be quiet", + "silence", + "hush", + "shut up", + "never mind", + "nevermind", + "enough", +} +_STOP_FIRST_WORDS = {"stop", "cancel", "quiet", "silence", "hush", "shut", "enough"} +_STOP_FILLER = {"please", "now", "it", "that", "talking", "down", "up", "already"} + +#: Characters stripped from a spoken utterance's edges before matching. +_STOP_PUNCT = " \t\r\n.,!?;:\"'()[]{}" + + +def is_stop_command(text: str) -> bool: + """Whether an utterance means "stop talking" (vs a new command). + + Deterministic vocabulary, no model: a bare "stop"/"cancel" (or a short + variant like "stop please") aborts a spoken reply / long-form read. Anything + longer is a real command and is submitted as a new request. + """ + cleaned = (text or "").strip().lower().strip(_STOP_PUNCT) + if not cleaned: + return False + if cleaned in _STOP_PHRASES: + return True + words = cleaned.split() + if len(words) > 3: + return False + first = words[0].strip(_STOP_PUNCT) + if first not in _STOP_FIRST_WORDS: + return False + return all(word.strip(_STOP_PUNCT) in _STOP_FILLER for word in words[1:]) + + class GatewayAdapter(ABC): """Transport contract for a messenger platform.""" diff --git a/semif_agent/gateway/lxmf.py b/semif_agent/gateway/lxmf.py index 1e9f434..91056a2 100644 --- a/semif_agent/gateway/lxmf.py +++ b/semif_agent/gateway/lxmf.py @@ -44,8 +44,10 @@ from __future__ import annotations import os import queue import threading +import time from semif_agent.lxmf_transport import LxmfDaemon +from semif_agent.reading import DEFAULT_CHUNK_CHARS, chunk_text, save_bookmark from semif_agent.voice_transport import ( OPUS_OGG_BITRATE, build_synthesizer, @@ -58,7 +60,7 @@ from semif_agent.voice_transport import ( pcm_to_wav, ) -from .base import GatewayAdapter, InboundMessage, OutboundMessage +from .base import GatewayAdapter, InboundMessage, OutboundMessage, is_stop_command #: Sent (once) when a voice message can't be transcribed at all. A spoken or #: typed command still works, so the user is not left guessing. @@ -141,6 +143,38 @@ class LxmfAdapter(GatewayAdapter): self._timers: dict[str, threading.Timer] = {} self._lock = threading.Lock() self._on_inbound = None + #: Read-aloud: a book is streamed to a voice chat as a sequence of + #: voice messages, one Piper-synthesized chunk each, until the user + #: sends "stop" or a new command. Only a voice chat can receive it, so + #: a text chat keeps the skill's saved-file summary. + read_cfg = self.voice_cfg.get("read", {}) or {} + self._read_enabled = bool(read_cfg.get("enabled", True)) + self._read_chunk_chars = max( + 1, int(read_cfg.get("chunk_chars", DEFAULT_CHUNK_CHARS) or DEFAULT_CHUNK_CHARS) + ) + #: How many messages may be queued on the daemon ahead of the stream + #: (backpressure so a stop is prompt). + self._read_max_lead = max(1, int(read_cfg.get("max_lead", 4) or 4)) + self._read_lock = threading.Lock() + self._read_stop = threading.Event() + self._read_key: str | None = None + self._read_chat: str | None = None + + @property + def supports_speech_stream(self) -> bool: + """Whether this adapter can deliver a read-aloud at all. + + Only when voice replies are on: a read-aloud is sent as voice messages. + Whether a *particular* chat can receive one is `speech_stream_ready`. + """ + return bool(self.voice_enabled and self.reply_with_voice and self._read_enabled) + + def speech_stream_ready(self, chat: str) -> bool: + """Whether `chat` should get a read-aloud (it last messaged by voice).""" + if not self.supports_speech_stream: + return False + with self._lock: + return str(chat) in self._voice_chats # ---- requirements ---- @@ -182,6 +216,15 @@ class LxmfAdapter(GatewayAdapter): if message is None: self.daemon.enqueue(None) return + if message.stream is not None: + try: + self._stream(message.stream) + except Exception as exc: + # A read failure must never kill the outbound pump. + self.daemon._event( + "lxmf_read_failed", message=str(exc)[:300] + ) + continue audio = self._voice_reply(message) self.daemon.enqueue(message.chat_id, message.text, audio=audio) @@ -252,6 +295,14 @@ class LxmfAdapter(GatewayAdapter): """Hand one command to the service (never called on the router thread).""" source_hash = str(message.get("source_hash") or "") display_name = message.get("display_name") + # Any command interrupts a read-aloud playing to this chat; a bare + # "stop"/"cancel" is not submitted as a request. + if self._stop_read_for_command(source_hash): + self.daemon._event( + "lxmf_read_stopped", contact_id=source_hash, chars=len(text) + ) + if is_stop_command(text): + return self.daemon._event( "gateway_message", contact_id=source_hash, @@ -488,3 +539,96 @@ class LxmfAdapter(GatewayAdapter): self.daemon._event("lxmf_voice_tts_unavailable", message=str(exc)[:300]) return None return self._synthesizer + + # ---- read-aloud (a book streamed as voice messages) ---- + + def _stop_read_for_command(self, chat: str) -> bool: + """Stop a read-aloud playing to `chat`; report whether one was active.""" + with self._read_lock: + if self._read_key is None or self._read_chat != str(chat): + return False + self._read_stop.set() + return True + + def _synthesize_chunk(self, text: str) -> bytes | None: + """Piper-synthesize one chunk to Opus/OGG, or None (send it as text).""" + synthesizer = self._ensure_synthesizer() + if synthesizer is None: + return None + try: + pcm, sample_rate = synthesizer.synthesize(text) + except Exception as exc: + self.daemon._event("lxmf_voice_synth_failed", message=str(exc)[:300]) + return None + if not pcm: + return None + audio = pcm_to_opus_ogg(pcm, sample_rate, self.voice_bitrate) + if not audio: + self.daemon._event("lxmf_voice_encode_failed", chars=len(text)) + return None + return audio + + def _stream(self, read) -> None: + """Stream a read-aloud request as a sequence of voice messages. + + Runs on the outbound pump thread: each chunk is synthesized and queued + to the daemon, and the bookmark is written before it is sent so a stop + leaves the position at the interrupted chunk. The read ends when the + text is finished or the user interrupts (a stop flag set by `_deliver`). + """ + chat = str(read.source or "").split(":", 1)[-1] + with self._read_lock: + self._read_stop.set() # supersede any prior read + stop = threading.Event() + self._read_stop = stop + self._read_key = read.key + self._read_chat = chat + try: + if not chat or not self.speech_stream_ready(chat): + return + try: + with open(read.path, "r", encoding="utf-8", errors="replace") as handle: + text = handle.read() + except OSError as exc: + self.daemon._event( + "lxmf_read_failed", contact_id=chat, message=str(exc)[:200] + ) + return + chunk_chars = min( + self._read_chunk_chars, + max(1, int(read.chunk_chars or self._read_chunk_chars)), + ) + if self.voice_max_chars > 0: + chunk_chars = min(chunk_chars, self.voice_max_chars) + self.daemon._event( + "lxmf_read_start", + contact_id=chat, + key=read.key, + start=read.start, + chars=len(text), + ) + sent = 0 + for offset, chunk in chunk_text(text, read.start, chunk_chars): + # Keep only a few messages queued ahead so a stop takes effect + # promptly instead of after a large backlog drains. + while not stop.is_set() and self.daemon.pending_sends() >= self._read_max_lead: + time.sleep(0.05) + if stop.is_set(): + break + save_bookmark(read.bookmarks_path, read.key, offset, read.title) + self.daemon.enqueue(chat, chunk, audio=self._synthesize_chunk(chunk)) + sent += 1 + if stop.is_set(): + self.daemon._event( + "lxmf_read_interrupted", contact_id=chat, key=read.key, chunks=sent + ) + else: + save_bookmark(read.bookmarks_path, read.key, len(text), read.title) + self.daemon._event( + "lxmf_read_done", contact_id=chat, key=read.key, chunks=sent + ) + finally: + with self._read_lock: + if self._read_stop is stop: + self._read_key = None + self._read_chat = None diff --git a/semif_agent/gateway/service.py b/semif_agent/gateway/service.py index 8d9ea69..47c9dd3 100644 --- a/semif_agent/gateway/service.py +++ b/semif_agent/gateway/service.py @@ -179,6 +179,13 @@ class GatewayService: setter = getattr(adapter, "set_input_ready", None) if callable(setter): setter(self.input_ready) + #: Tell the scheduler's speech channel which sources this service can + #: stream a read-aloud to, so a skill asks before it posts one. + speech = getattr(self.scheduler, "speech", None) + if speech is not None: + setter = getattr(speech, "set_stream_check", None) + if callable(setter): + setter(self.stream_ready) self._owners: dict[str, Target] = {} self._parents: dict[str, str] = {} self._pending_owner: Target | None = None @@ -342,6 +349,29 @@ class GatewayService: return True return getattr(scheduler, "current", None) is None + def stream_ready(self, source: str) -> bool: + """Whether this service can stream a read-aloud to `source`. + + The owning platform's adapter decides: the voice gateway always can + (when `read.enabled`); the LXMF adapter only for a chat that last + messaged by voice (a text chat keeps the saved-file summary). A source + with no known owner is not streamed. + """ + target = self._owner_from_source(source) + if target is None: + return False + platform, chat = target + adapter = self.adapters.get(platform) + if adapter is None: + return False + check = getattr(adapter, "speech_stream_ready", None) + if callable(check): + try: + return bool(check(chat)) + except Exception: + return False + return bool(getattr(adapter, "supports_speech_stream", False)) + def handle_inbound(self, msg: InboundMessage, platform: str | None = None) -> None: """Handle one authorized inbound command. Called by the adapter.""" if platform is None: @@ -519,6 +549,16 @@ class GatewayService: if target: self._reply(*target, fired.message, kind="notice") + # Long-form read-aloud requests a skill posted for a voice front end: + # route each to the platform that owns the run. Only a streaming adapter + # (the voice gateway) can deliver one; others are traced and skipped. + speech = getattr(self.scheduler, "speech", None) + if speech is not None: + for read in speech.drain(): + target = self._resolve_target(read.run_id, origin) + if target: + self._enqueue_stream(target, read) + # ---- scheduler requeue hook (called under the scheduler lock) ---- def on_request_requeued(self, parent_id: str, child_id: str) -> None: @@ -593,3 +633,29 @@ class GatewayService: return self._trace("gateway_reply_queued", reply_kind=kind, chars=len(text)) target_queue.put(OutboundMessage(chat_id=str(chat_id), text=text)) + + def _enqueue_stream(self, target: Target, read) -> None: + """Queue a read-aloud stream for the platform that can stream it. + + Only an adapter that declares `supports_speech_stream` (the voice + gateway) can speak a long-form stream; a platform that cannot is traced + and skipped rather than handed a message it would drop silently. + """ + platform, chat_id = target + adapter = self.adapters.get(platform) + if adapter is None or not getattr(adapter, "supports_speech_stream", False): + self._trace( + "gateway_stream_unsupported", + platform=platform, + key=getattr(read, "key", ""), + ) + return + self._trace( + "gateway_stream_queued", + platform=platform, + key=getattr(read, "key", ""), + start=getattr(read, "start", 0), + ) + self.outbound[platform].put( + OutboundMessage(chat_id=str(chat_id), text="", stream=read) + ) diff --git a/semif_agent/gateway/voice.py b/semif_agent/gateway/voice.py index dd8a071..6b69a54 100644 --- a/semif_agent/gateway/voice.py +++ b/semif_agent/gateway/voice.py @@ -23,58 +23,14 @@ from __future__ import annotations import queue import threading +from semif_agent.reading import DEFAULT_CHUNK_CHARS, chunk_text, save_bookmark from semif_agent.voice_transport import VoiceDaemon -from .base import GatewayAdapter, InboundMessage, OutboundMessage +from .base import GatewayAdapter, InboundMessage, OutboundMessage, is_stop_command -#: Words/phrases that abort a spoken reply when heard after a barge-in. The -#: match is on the whole normalized utterance (so "stop the timer" stays a real -#: command) with a first-word fallback only for a short utterance with trailing -#: filler ("stop please", "cancel that"). -_STOP_PHRASES = { - "stop", - "stop it", - "stop talking", - "stop please", - "cancel", - "cancel that", - "cancel please", - "quiet", - "quiet down", - "be quiet", - "silence", - "hush", - "shut up", - "never mind", - "nevermind", - "enough", -} -_STOP_FIRST_WORDS = {"stop", "cancel", "quiet", "silence", "hush", "shut", "enough"} -_STOP_FILLER = {"please", "now", "it", "that", "talking", "down", "up", "already"} - -#: Characters stripped from a spoken utterance's edges before matching. -_PUNCT = " \t\r\n.,!?;:\"'()[]{}" - - -def _is_stop_command(text: str) -> bool: - """Whether an interrupt utterance means "stop talking" (vs a new command). - - Deterministic vocabulary, no model: a bare "stop"/"cancel" (or a short - variant like "stop please") aborts the spoken reply. Anything longer is a - real command and is submitted as a new request. - """ - cleaned = (text or "").strip().lower().strip(_PUNCT) - if not cleaned: - return False - if cleaned in _STOP_PHRASES: - return True - words = cleaned.split() - if len(words) > 3: - return False - first = words[0].strip(_PUNCT) - if first not in _STOP_FIRST_WORDS: - return False - return all(word.strip(_PUNCT) in _STOP_FILLER for word in words[1:]) +#: The stop vocabulary lives in `gateway.base` (shared with the LXMF adapter, +#: which also streams read-aloud text). Kept under the old name for callers. +_is_stop_command = is_stop_command class VoiceAdapter(GatewayAdapter): @@ -103,6 +59,22 @@ class VoiceAdapter(GatewayAdapter): #: The outbound reply queue (set in `run`), so a "stop" can drop replies #: that were already queued behind the interrupted one. self._outbound: "queue.Queue[OutboundMessage | None] | None" = None + #: Long-form read-aloud: the adapter streams a saved text through the + #: daemon's Piper voice one chunk at a time, and any inbound command + #: interrupts it. `read.enabled` (default on) gates the whole path; + #: `read.chunk_chars` bounds one spoken chunk (clamped to the speakable + #: budget so a chunk is never truncated). + read_cfg = cfg.get("read", {}) or {} + self.supports_speech_stream = bool(read_cfg.get("enabled", True)) + self._read_chunk_chars = max( + 1, int(read_cfg.get("chunk_chars", DEFAULT_CHUNK_CHARS) or DEFAULT_CHUNK_CHARS) + ) + self._read_lock = threading.Lock() + #: Set to ask the active read to stop; swapped per read so a stale read + #: never observes a new read's stop signal. + self._read_stop = threading.Event() + #: The bookmark key of the active read (None when nothing is being read). + self._read_key: str | None = None # ---- requirements ---- @@ -131,12 +103,23 @@ class VoiceAdapter(GatewayAdapter): def _pump() -> None: # Drain the service's replies onto the daemon's speaker. Speaking - # blocks (it plays audio), so this runs off the listening thread. + # blocks (it plays audio), so this runs off the listening thread. A + # read-aloud stream blocks here for as long as the user listens. while True: message = outbound.get() if message is None: self.daemon.stop() return + if message.stream is not None: + try: + self._stream(message.stream) + except Exception as exc: + # A read failure must never kill the outbound pump (and + # with it the front end). + self.daemon._event( + "gateway_read_failed", message=str(exc)[:300] + ) + continue self.daemon._event("gateway_reply_dequeued", chars=len(message.text)) self.daemon.speak(message.text) @@ -169,6 +152,11 @@ class VoiceAdapter(GatewayAdapter): self._handle(message) def _handle(self, message: InboundMessage) -> None: + # Any inbound command interrupts an in-progress read-aloud: the user + # either said "stop" or wants to do something else. The bookmark already + # points at the chunk that was interrupted, so a later request resumes + # there. + was_reading = self._stop_read_for_command(message) if message.raw.get("barge_in"): if _is_stop_command(message.text): # A "stop"/"cancel" after a barge-in aborts the spoken reply and @@ -190,6 +178,12 @@ class VoiceAdapter(GatewayAdapter): finally: self.daemon.set_muted(False) return + if was_reading and _is_stop_command(message.text): + # A bare "stop" heard between chunks (not a barge-in) stops the + # reading and is not submitted as a request. + self.daemon._event("gateway_read_stopped", chars=len(message.text)) + self._drop_pending_speech() + return if self._on_inbound is None: return try: @@ -198,6 +192,91 @@ class VoiceAdapter(GatewayAdapter): self.daemon._event("gateway_handler_failed", message=str(exc)[:300]) self.daemon.speak("Sorry, something went wrong handling that.") + # ---- read-aloud (long-form streaming) ---- + + def _read_active(self) -> bool: + with self._read_lock: + return self._read_key is not None + + def _stop_read_for_command(self, message: InboundMessage) -> bool: + """Stop an active read when a command arrives; report whether one was.""" + if not self._read_active(): + return False + reason = "barge_in" if message.raw.get("barge_in") else "new_command" + self._stop_reading(reason) + return True + + def _stop_reading(self, reason: str) -> None: + """Ask the active read to stop at the next chunk boundary. + + The bookmark was already written for the chunk being spoken, so the + position is correct without any extra bookkeeping here. + """ + with self._read_lock: + if self._read_key is None: + return + key = self._read_key + self._read_stop.set() + self.daemon._event("gateway_read_stop", key=key, reason=reason) + + def _stream(self, read) -> None: + """Stream a read-aloud request through the daemon's Piper voice. + + Chunks are spoken one at a time; the bookmark is written before each + chunk so a stop (or a crash) leaves the position at the interrupted + chunk. The read ends when the text is finished or the user interrupts + (a stop flag set by `_handle`, or a barge-in muting playback). + """ + with self._read_lock: + self._read_stop.set() # supersede any prior read + stop = threading.Event() + self._read_stop = stop + self._read_key = read.key + try: + try: + with open(read.path, "r", encoding="utf-8", errors="replace") as handle: + text = handle.read() + except OSError as exc: + self.daemon._event( + "gateway_read_failed", key=read.key, message=str(exc)[:200] + ) + return + chunk_chars = min( + self._read_chunk_chars, + max(1, int(read.chunk_chars or self._read_chunk_chars)), + ) + # Never exceed the daemon's speakable budget, or a chunk would be + # truncated and text would be lost. + speak_limit = int(getattr(self.daemon, "max_speak_chars", 0) or 0) + if speak_limit > 0: + chunk_chars = min(chunk_chars, speak_limit) + self.daemon._event( + "gateway_read_start", key=read.key, start=read.start, chars=len(text) + ) + spoken = 0 + for offset, chunk in chunk_text(text, read.start, chunk_chars): + if stop.is_set() or self.daemon.stopping(): + break + save_bookmark(read.bookmarks_path, read.key, offset, read.title) + self.daemon.speak(chunk) + spoken += 1 + # A barge-in mutes playback synchronously on the audio thread; + # break promptly so we do not skip through suppressed chunks + # before the transcribed "stop" reaches `_handle`. + if stop.is_set() or self.daemon.muted(): + break + if stop.is_set() or self.daemon.stopping(): + self.daemon._event("gateway_read_interrupted", key=read.key, chunks=spoken) + else: + # Finished: park the bookmark at the end so a later request + # starts over rather than replaying the final chunk. + save_bookmark(read.bookmarks_path, read.key, len(text), read.title) + self.daemon._event("gateway_read_done", key=read.key, chunks=spoken) + finally: + with self._read_lock: + if self._read_stop is stop: + self._read_key = None + def _drop_pending_speech(self) -> None: """Discard replies already queued behind an interrupted one. diff --git a/semif_agent/lxmf_transport.py b/semif_agent/lxmf_transport.py index 54fe0c5..7764051 100644 --- a/semif_agent/lxmf_transport.py +++ b/semif_agent/lxmf_transport.py @@ -439,6 +439,15 @@ class LxmfDaemon: except Exception: pass + def pending_sends(self) -> int: + """How many outbound items are queued (a stream's backpressure signal). + + A long-form read-aloud uses this to keep only a few messages queued + ahead, so stopping it takes effect promptly instead of after a large + backlog drains. + """ + return self._outbound.qsize() + # ---- identity ---- def _load_identity(self, RNS): diff --git a/semif_agent/reading.py b/semif_agent/reading.py new file mode 100644 index 0000000..0e6c189 --- /dev/null +++ b/semif_agent/reading.py @@ -0,0 +1,140 @@ +"""Long-form spoken reading: bookmark positions and speakable chunking. + +A skill that resolves a long text (a book) asks the voice front end to read it +aloud; the front end streams it with text-to-speech one speakable chunk at a +time. The position reached is recorded in a ``bookmarks.json`` file beside the +saved text so a later request resumes where the listener stopped. + +This module is neutral and stdlib-only: it knows nothing about the scheduler, +the gateway, or audio. The chunker is deterministic — the same text and start +offset always yield the same chunks — so a saved offset is always a valid +resume point. +""" + +from __future__ import annotations + +import json +import os +import time +from pathlib import Path +from typing import Iterator + +#: The file (beside the saved books) that maps a book key -> last read offset. +BOOKMARKS_FILE = "bookmarks.json" + +#: Default characters per spoken chunk. Kept below the voice front end's +#: `max_speak_chars` so a chunk is spoken whole, never truncated. +DEFAULT_CHUNK_CHARS = 300 + +_WHITESPACE = " \t\r\n" +_SENTENCE_END = ".!?" + + +def bookmarks_file(directory) -> Path: + """The bookmarks path inside a books directory.""" + return Path(directory) / BOOKMARKS_FILE + + +def load_bookmarks(path) -> dict: + """Read the bookmarks map (``{key: {"offset", "title", "updated_at"}}``). + + A missing or unparseable file is an empty map — bookmarks are an + optimization, never a reason a read fails. + """ + target = Path(path) + if not target.is_file(): + return {} + try: + data = json.loads(target.read_text(encoding="utf-8")) + except (OSError, ValueError): + return {} + return data if isinstance(data, dict) else {} + + +def read_offset(path, key) -> int: + """The last read offset recorded for `key` (0 when unset/unknown).""" + entry = load_bookmarks(path).get(str(key)) + if isinstance(entry, dict): + try: + return max(0, int(entry.get("offset", 0))) + except (TypeError, ValueError): + return 0 + if isinstance(entry, int): # tolerate a bare-offset legacy shape + return max(0, entry) + return 0 + + +def save_bookmark(path, key, offset, title: str = "") -> None: + """Record the read offset for `key`, atomically. + + Written to a temp file and renamed so a reader never sees a half-written + map. Any filesystem failure is swallowed: a failed bookmark must not break + the reading itself. + """ + target = Path(path) + data = load_bookmarks(target) + data[str(key)] = { + "offset": max(0, int(offset)), + "title": str(title or ""), + "updated_at": time.time(), + } + try: + target.parent.mkdir(parents=True, exist_ok=True) + tmp = target.with_name(target.name + ".tmp") + tmp.write_text( + json.dumps(data, indent=2, sort_keys=True) + "\n", encoding="utf-8" + ) + os.replace(tmp, target) + except OSError: + pass + + +def _skip_whitespace(text: str, index: int) -> int: + while index < len(text) and text[index] in _WHITESPACE: + index += 1 + return index + + +def _break_point(window: str) -> int: + """How many characters of `window` to keep for one chunk. + + Prefer a paragraph break, then a sentence end, then a whitespace break — + but only past the window's midpoint, so a break never yields a tiny chunk. + Falls back to the whole window when it holds no good boundary. + """ + half = len(window) // 2 + paragraph = window.rfind("\n\n") + if paragraph >= half: + return paragraph + 2 + for index in range(len(window) - 1, -1, -1): + if window[index] in _SENTENCE_END and ( + index + 1 == len(window) or window[index + 1] in _WHITESPACE + "\"')]" + ): + return index + 1 + space = window.rfind(" ") + if space >= half: + return space + 1 + return len(window) + + +def chunk_text(text: str, start: int = 0, max_chars: int = DEFAULT_CHUNK_CHARS) -> Iterator[tuple[int, str]]: + """Yield ``(offset, chunk)`` speakable chunks of `text` from `start`. + + `offset` is the absolute index of the chunk's first character in `text`, so + a front end can persist it as the resume point. Deterministic for a given + `text`, `start`, and `max_chars`. + """ + text = text or "" + total = len(text) + limit_chars = max(1, int(max_chars)) + index = _skip_whitespace(text, max(0, int(start))) + while index < total: + window_end = min(index + limit_chars, total) + if window_end >= total: + end = total + else: + end = index + _break_point(text[index:window_end]) + chunk = text[index:end].strip() + if chunk: + yield index, chunk + index = _skip_whitespace(text, end) diff --git a/semif_agent/scheduler.py b/semif_agent/scheduler.py index 7b2102d..1269230 100644 --- a/semif_agent/scheduler.py +++ b/semif_agent/scheduler.py @@ -41,6 +41,7 @@ from .provider import ProviderError from .packs import disabled_categories, load_packs, merge_packs from .queue import RequestQueue from .skill import SkillRunner +from .speech import SpeechService from .timers import TimerService from .skills import ( CANNED_CATEGORIES, @@ -436,6 +437,10 @@ class Scheduler: for category in disabled_categories(config, self.packs): self.tree.pop(category, None) self.timers = TimerService(trace=self.trace, timezone=config.get("timezone")) + # Long-form read-aloud requests a skill posts for the voice front end. + # A body registers one and returns immediately; the gateway drains it + # and streams it with text-to-speech (see `semif_agent.speech`). + self.speech = SpeechService(trace=self.trace) # Read-only introspection of the live tree for introspection skills # (listing categories / the skills in one), supplied as a locked # snapshot so a body never reaches into the scheduler. @@ -444,6 +449,7 @@ class Scheduler: engine=self.engine, config=config, timers=self.timers, + speech=self.speech, admin=self, catalog=self.catalog, ) @@ -1064,6 +1070,13 @@ class Scheduler: result=outcome.action_log or outcome.new_state or None, ) verdict = outcome.outcome or ("done" if outcome.success else "failed") + if verdict == "continue" and self.speech.pending_for(request.id): + # The run handed off to a long-form read-aloud: the read IS the + # answer, so there is no further work for `assess:outcome` to find. + # Overriding to `done` keeps the chain from re-dispatching the + # request (which otherwise authors a spurious skill). + self.trace.append("read_aloud_terminal", request.id, skill=skill.name) + verdict = "done" self.trace.append( "assessed", request.id, diff --git a/semif_agent/skill.py b/semif_agent/skill.py index 388872b..708c51a 100644 --- a/semif_agent/skill.py +++ b/semif_agent/skill.py @@ -148,6 +148,9 @@ class SkillRunner: engine=self.ctx.engine, config=merged, timers=self.ctx.timers, + # The scheduler's speech channel (a skill can post a long-form + # read-aloud for a voice front end) rides on every run. + speech=self.ctx.speech, # `admin` (mutation of the agent) is reserved for the built-in # housekeeping meta skills; an ordinary body only ever gets the # read-only `catalog`. diff --git a/semif_agent/skills.py b/semif_agent/skills.py index ab1ce70..45e5806 100644 --- a/semif_agent/skills.py +++ b/semif_agent/skills.py @@ -26,6 +26,7 @@ from .decisions import DecisionRequest, Option, Request from .engine import DecisionEngine from .llm import LLMClient from .log import DecisionLog +from .speech import SpeechService from .timers import TimerService from .trace import TraceLog @@ -45,6 +46,11 @@ class ActionContext: engine: DecisionEngine config: dict timers: TimerService | None = None + #: The scheduler's speech channel. A body that resolves a long text to be + #: read aloud (a book) registers it here and returns immediately; the voice + #: front end streams it and the user stops it. None for a body running + #: without a scheduler (a test) — callers must tolerate None. + speech: SpeechService | None = None # The scheduler, exposed to built-in meta skills (housekeeping) so they can # act on the agent's own tree/registry/store. None for ordinary bodies, which # must never reach into the agent (the read-only `catalog` is their view). diff --git a/semif_agent/speech.py b/semif_agent/speech.py new file mode 100644 index 0000000..7440c1c --- /dev/null +++ b/semif_agent/speech.py @@ -0,0 +1,164 @@ +"""The scheduler's speech channel: a long-form read-aloud request for a front end. + +A skill body cannot speak: it runs inside the scheduler, which is transport- +agnostic and must never reach into a front end. So a body that resolves a long +text to be *read aloud* registers a `ReadAloud` here (through `ctx.speech`) and +returns immediately. The gateway that owns the originating chat drains the +request (`drain()`) and hands it to the platform adapter, which streams it with +text-to-speech until the user stops it. Position is tracked in a +``bookmarks.json`` beside the text (see `semif_agent.reading`). + +This mirrors `semif_agent.timers`: the scheduler exposes a small thread-safe +service; a front end drains what it can deliver. It is neutral — stdlib only, +and it knows nothing about audio or any specific gateway. +""" + +from __future__ import annotations + +import threading +import time +import uuid +from collections import deque +from dataclasses import dataclass, field + +from .reading import DEFAULT_CHUNK_CHARS + + +@dataclass +class ReadAloud: + """One queued request to read a saved text aloud from a position. + + `path` is the text file; `bookmarks_path` the ``bookmarks.json`` beside it; + `key` the book's bookmark key; `start` the character offset to resume from. + `source` is the originating front-end source (`"voice:"`) and + `run_id` the run that asked, so the gateway can route it to the right chat. + """ + + path: str + key: str + bookmarks_path: str + run_id: str = "" + source: str = "" + title: str = "" + start: int = 0 + chunk_chars: int = DEFAULT_CHUNK_CHARS + id: str = field(default_factory=lambda: uuid.uuid4().hex[:12]) + created_at: float = field(default_factory=time.time) + + +class SpeechService: + """Holds read-aloud requests until a front end drains them. + + Bounded like the request queue: a front end that never drains (the REPL) + cannot grow it without limit. + """ + + def __init__(self, trace=None, max_pending: int = 64): + self.trace = trace + self._lock = threading.Lock() + self._pending: deque[ReadAloud] = deque(maxlen=max(1, int(max_pending))) + #: Optional predicate set by a front end: whether a given source can be + #: streamed to (the voice gateway; an LXMF voice chat). None means no + #: front end is attached (the REPL, a test), so nothing supports it. + self._stream_check = None + + def set_stream_check(self, check) -> None: + """Register the front end's per-source streaming capability predicate. + + Called by the gateway service with a callable `(source) -> bool` so a + skill can ask `supports(source)` before it posts a read-aloud. A front + end that cannot stream (or has none attached) leaves it None. + """ + self._stream_check = check if callable(check) else None + + def supports(self, source: str) -> bool: + """Whether the front end can stream a read-aloud to `source`. + + False when no front end is attached, when the source's platform cannot + stream, or when the check raises — the caller then keeps its normal + (non-read-aloud) behaviour. + """ + check = self._stream_check + if check is None: + return False + try: + return bool(check(str(source or ""))) + except Exception: + return False + + def read_aloud( + self, + *, + path: str, + key: str, + bookmarks_path: str, + run_id: str = "", + source: str = "", + title: str = "", + start: int = 0, + chunk_chars: int = DEFAULT_CHUNK_CHARS, + ) -> ReadAloud: + """Queue a text to be read aloud. Returns the queued request.""" + read = ReadAloud( + path=str(path), + key=str(key), + bookmarks_path=str(bookmarks_path), + run_id=str(run_id or ""), + source=str(source or ""), + title=str(title or ""), + start=max(0, int(start or 0)), + chunk_chars=max(1, int(chunk_chars or DEFAULT_CHUNK_CHARS)), + ) + with self._lock: + self._pending.append(read) + self._event( + "read_aloud_queued", + read.run_id, + read_id=read.id, + key=read.key, + source=read.source, + start=read.start, + ) + return read + + def drain(self) -> list[ReadAloud]: + """Pop and return the queued requests, oldest first (for a front end).""" + with self._lock: + reads = list(self._pending) + self._pending.clear() + return reads + + def pending_for(self, run_id: str) -> bool: + """Whether a read-aloud is queued for a run (not yet drained). + + Lets the scheduler treat a run that handed off to a long-form read as + complete: the read is the answer, so `assess:outcome` has no further + work to find and must not re-dispatch the request. + """ + with self._lock: + return any(r.run_id == str(run_id) for r in self._pending) + + def pending(self) -> list[dict]: + """A snapshot of the queue (for the dashboard).""" + with self._lock: + return [ + { + "id": r.id, + "run_id": r.run_id, + "source": r.source, + "key": r.key, + "title": r.title, + "start": r.start, + "path": r.path, + "created_at": r.created_at, + } + for r in self._pending + ] + + def _event(self, kind: str, run_id: str, **fields) -> None: + if self.trace is None: + return + try: + self.trace.append(kind, run_id, **fields) + except Exception: + pass diff --git a/semif_agent/voice_transport.py b/semif_agent/voice_transport.py index 0ba0530..6121279 100644 --- a/semif_agent/voice_transport.py +++ b/semif_agent/voice_transport.py @@ -1385,6 +1385,14 @@ class VoiceDaemon: else: self._mute.clear() + def muted(self) -> bool: + """Whether spoken replies are currently muted (a barge-in is in flight).""" + return self._mute.is_set() + + def stopping(self) -> bool: + """Whether the daemon is shutting down (a long stream should stop).""" + return self._stop.is_set() + def speak(self, text: str) -> None: """Synthesize and play `text`; called from the outbound pump thread.""" text = (text or "").strip() diff --git a/tests/test_gateway.py b/tests/test_gateway.py index 4195e93..5ac9de9 100644 --- a/tests/test_gateway.py +++ b/tests/test_gateway.py @@ -894,6 +894,230 @@ def test_lxmf_voice_reply_bounds_length(monkeypatch): assert len(synth.calls[0]) <= 10 +# ---- LXMF read-aloud (a book streamed as voice messages) ------------------- + +def _read_aloud(chat, path, bookmarks, start=0, key="k", title="T"): + from semif_agent.speech import ReadAloud + + return ReadAloud( + path=str(path), + key=key, + bookmarks_path=str(bookmarks), + source=f"lxmf:{chat}", + start=start, + title=title, + ) + + +def _drain_lxmf_daemon(adapter): + items = [] + while not adapter.daemon._outbound.empty(): + items.append(adapter.daemon._outbound.get_nowait()) + return items + + +def test_lxmf_speech_stream_ready_only_for_voice_chats(): + from semif_agent.gateway.lxmf import LxmfAdapter + + adapter = LxmfAdapter( + {"allow_all_users": True, "voice": {"enabled": True}}, + synthesizer=FakeSynthesizer(), + ) + assert adapter.supports_speech_stream is True + assert adapter.speech_stream_ready("ab") is False + adapter._mark_voice_chat("ab") + assert adapter.speech_stream_ready("ab") is True + + # Voice replies off: no read-aloud at all. + off = LxmfAdapter( + {"allow_all_users": True, "voice": {"enabled": True, "reply_with_voice": False}}, + synthesizer=FakeSynthesizer(), + ) + off._mark_voice_chat("ab") + assert off.supports_speech_stream is False + assert off.speech_stream_ready("ab") is False + + +def test_lxmf_streams_a_read_aloud_as_voice_messages(tmp_path, monkeypatch): + import semif_agent.gateway.lxmf as lxmf + from semif_agent.gateway.lxmf import LxmfAdapter + from semif_agent.reading import read_offset + + monkeypatch.setattr(lxmf, "pcm_to_opus_ogg", lambda pcm, rate, bitrate=0: b"OGG") + chat = "ab" * 16 + adapter = LxmfAdapter( + {"allow_all_users": True, "voice": {"enabled": True, "read": {"max_lead": 100000}}}, + synthesizer=FakeSynthesizer(), + ) + adapter._mark_voice_chat(chat) + text = "Sentence one. " * 80 + book = tmp_path / "book.txt" + book.write_text(text, encoding="utf-8") + bookmarks = tmp_path / "bookmarks.json" + + adapter._stream(_read_aloud(chat, book, bookmarks)) + + items = _drain_lxmf_daemon(adapter) + assert len(items) > 1, "the book must be sent as several messages" + assert all(item[0] == chat for item in items) + assert all(item[2] == b"OGG" for item in items) + # The chunks reconstruct the text, and completion parks the bookmark at the end. + assert "".join(item[1] for item in items).replace(" ", "") == text.replace(" ", "") + assert read_offset(bookmarks, "k") == len(text) + + +def test_lxmf_read_aloud_stops_on_a_stop_command(tmp_path, monkeypatch): + import semif_agent.gateway.lxmf as lxmf + from semif_agent.gateway.lxmf import LxmfAdapter + from semif_agent.reading import read_offset + + monkeypatch.setattr(lxmf, "pcm_to_opus_ogg", lambda pcm, rate, bitrate=0: b"OGG") + chat = "ab" * 16 + seen: list = [] + + class StoppingSynth(FakeSynthesizer): + def synthesize(self, text): + if len(self.calls) == 1: # during the second chunk + adapter._deliver({"source_hash": chat}, "stop") + return super().synthesize(text) + + adapter = LxmfAdapter( + {"allow_all_users": True, "voice": {"enabled": True}}, + synthesizer=StoppingSynth(), + ) + adapter._on_inbound = seen.append + adapter._mark_voice_chat(chat) + text = "Sentence one. " * 80 + book = tmp_path / "book.txt" + book.write_text(text, encoding="utf-8") + bookmarks = tmp_path / "bookmarks.json" + + adapter._stream(_read_aloud(chat, book, bookmarks)) + + assert seen == [], "a bare stop must not be submitted as a request" + items = _drain_lxmf_daemon(adapter) + assert len(items) == 2, "the read stops at the next chunk" + offset = read_offset(bookmarks, "k") + assert 0 < offset < len(text) + + +def test_lxmf_new_command_stops_the_read_and_is_forwarded(tmp_path, monkeypatch): + import semif_agent.gateway.lxmf as lxmf + from semif_agent.gateway.lxmf import LxmfAdapter + + monkeypatch.setattr(lxmf, "pcm_to_opus_ogg", lambda pcm, rate, bitrate=0: b"OGG") + chat = "ab" * 16 + seen: list = [] + + class StoppingSynth(FakeSynthesizer): + def synthesize(self, text): + if len(self.calls) == 1: + adapter._deliver({"source_hash": chat}, "what time is it") + return super().synthesize(text) + + adapter = LxmfAdapter( + {"allow_all_users": True, "voice": {"enabled": True}}, + synthesizer=StoppingSynth(), + ) + adapter._on_inbound = seen.append + adapter._mark_voice_chat(chat) + book = tmp_path / "book.txt" + book.write_text("Sentence one. " * 80, encoding="utf-8") + + adapter._stream(_read_aloud(chat, book, tmp_path / "bookmarks.json")) + assert [m.text for m in seen] == ["what time is it"] + + +def test_lxmf_read_aloud_skips_a_non_voice_chat(tmp_path, monkeypatch): + import semif_agent.gateway.lxmf as lxmf + from semif_agent.gateway.lxmf import LxmfAdapter + + monkeypatch.setattr(lxmf, "pcm_to_opus_ogg", lambda pcm, rate, bitrate=0: b"OGG") + chat = "ab" * 16 + adapter = LxmfAdapter( + {"allow_all_users": True, "voice": {"enabled": True}}, + synthesizer=FakeSynthesizer(), + ) + # Not marked as a voice chat: nothing is streamed. + book = tmp_path / "book.txt" + book.write_text("Sentence one. " * 80, encoding="utf-8") + adapter._stream(_read_aloud(chat, book, tmp_path / "bookmarks.json")) + assert _drain_lxmf_daemon(adapter) == [] + + +def test_lxmf_read_aloud_backpressures_the_outbound_queue(tmp_path, monkeypatch): + # The stream keeps only a few messages queued ahead, so a stop is prompt + # even though the transport sends them slowly. + import threading + + import semif_agent.gateway.lxmf as lxmf + from semif_agent.gateway.lxmf import LxmfAdapter + + monkeypatch.setattr(lxmf, "pcm_to_opus_ogg", lambda pcm, rate, bitrate=0: b"OGG") + chat = "ab" * 16 + adapter = LxmfAdapter( + {"allow_all_users": True, "voice": {"enabled": True, "read": {"max_lead": 3}}}, + synthesizer=FakeSynthesizer(), + ) + adapter._mark_voice_chat(chat) + book = tmp_path / "book.txt" + book.write_text("Sentence one. " * 400, encoding="utf-8") + read = _read_aloud(chat, book, tmp_path / "bookmarks.json") + + done = threading.Event() + + def run(): + adapter._stream(read) + done.set() + + threading.Thread(target=run, daemon=True).start() + deadline = time.time() + 3 + while adapter.daemon.pending_sends() < 3 and time.time() < deadline: + time.sleep(0.01) + time.sleep(0.1) + assert adapter.daemon.pending_sends() == 3, "the stream must not outrun the queue" + assert not done.is_set(), "the stream waits while the queue is full" + + adapter._deliver({"source_hash": chat}, "stop") + assert done.wait(timeout=2), "a stop releases the waiting stream" + assert adapter._read_key is None + + +def test_service_marks_streamable_sources(tmp_path): + from semif_agent.gateway.lxmf import LxmfAdapter + + scheduler = build_scheduler(tmp_path) + chat = "ab" * 16 + adapter = LxmfAdapter( + {"allow_all_users": True, "voice": {"enabled": True}}, + synthesizer=FakeSynthesizer(), + ) + service = GatewayService(scheduler, adapter, config={}) + assert scheduler.speech.supports(f"lxmf:{chat}") is False + adapter._mark_voice_chat(chat) + assert scheduler.speech.supports(f"lxmf:{chat}") is True + + # A read registered for that chat is routed to the adapter's outbound queue. + scheduler.speech.read_aloud( + path="/books/f.txt", + key="k", + bookmarks_path="/books/bookmarks.json", + run_id="r1", + source=f"lxmf:{chat}", + ) + service._owners["r1"] = ("lxmf", chat) + service.surface() + message = service.outbound["lxmf"].get_nowait() + assert message.stream is not None + assert message.stream.key == "k" + + +def test_service_marks_voice_gateway_streamable(tmp_path): + scheduler = build_scheduler(tmp_path) + GatewayService(scheduler, FakeStreamAdapter(), config={}) + assert scheduler.speech.supports("voice:c") is True + + # ---- service: multiple platforms ---- class FakeLxmfAdapter: @@ -928,3 +1152,51 @@ def test_service_reply_routes_to_owning_platform(tmp_path): ) assert not service.outbound["lxmf"].empty() assert service.outbound["simplex"].empty() + + +# ---- service: read-aloud streams route to a streaming front end ------------ + + +class FakeStreamAdapter: + name = "voice" + supports_speech_stream = True + + +def test_service_routes_read_aloud_to_streaming_adapter(tmp_path): + scheduler = build_scheduler(tmp_path) + service = GatewayService(scheduler, FakeStreamAdapter(), config={}) + scheduler.speech.read_aloud( + path="/books/p.txt", + key="gutenberg-1342", + bookmarks_path="/books/bookmarks.json", + run_id="r1", + source="voice:c", + title="Pride and Prejudice", + start=10, + ) + service._owners["r1"] = ("voice", "c") + service.surface() + + message = service.outbound["voice"].get_nowait() + assert message.stream is not None + assert message.stream.key == "gutenberg-1342" + assert message.stream.start == 10 + assert message.text == "" + + +def test_service_skips_read_aloud_for_a_non_streaming_platform(tmp_path): + scheduler = build_scheduler(tmp_path) + service = build_service(scheduler) # FakeAdapter (simplex) cannot stream + scheduler.speech.read_aloud( + path="/books/p.txt", + key="gutenberg-1342", + bookmarks_path="/books/bookmarks.json", + run_id="r1", + source="simplex:4", + ) + service._owners["r1"] = ("simplex", "4") + service.surface() + assert service.outbound["simplex"].empty() + assert any( + e["kind"] == "gateway_stream_unsupported" for e in scheduler.trace.read() + ) diff --git a/tests/test_reading.py b/tests/test_reading.py new file mode 100644 index 0000000..06cf470 --- /dev/null +++ b/tests/test_reading.py @@ -0,0 +1,144 @@ +"""Pure-stdlib tests for the reading helpers and the scheduler speech channel. + +`semif_agent.reading` owns bookmark persistence and deterministic speakable +chunking; `semif_agent.speech` owns the queue a skill posts a read-aloud request +to. Neither touches audio, the scheduler, or a gateway. +""" + +import json + +from semif_agent.reading import ( + BOOKMARKS_FILE, + bookmarks_file, + chunk_text, + load_bookmarks, + read_offset, + save_bookmark, +) +from semif_agent.speech import ReadAloud, SpeechService + + +# ---- chunking -------------------------------------------------------------- + + +def test_chunk_text_splits_and_offsets_are_contiguous(): + text = "One. Two. Three. Four. Five. Six." + chunks = list(chunk_text(text, 0, 12)) + assert len(chunks) > 1 + for offset, chunk in chunks: + assert text[offset : offset + len(chunk)] == chunk + # The concatenation (whitespace-insensitive) is the original text. + assert "".join(chunk for _o, chunk in chunks).replace(" ", "") == text.replace(" ", "") + + +def test_chunk_text_resumes_deterministically_from_a_saved_offset(): + text = "Alpha beta gamma. Delta epsilon zeta. Eta theta iota. Kappa lambda mu." + chunks = list(chunk_text(text, 0, 20)) + assert len(chunks) >= 3 + resume_offset = chunks[2][0] + # Resuming from a chunk boundary reproduces the tail exactly. + tail = list(chunk_text(text, resume_offset, 20)) + assert tail == chunks[2:] + + +def test_chunk_text_respects_max_chars_without_a_good_break(): + text = "x" * 100 + chunks = list(chunk_text(text, 0, 30)) + assert [len(chunk) for _o, chunk in chunks] == [30, 30, 30, 10] + + +def test_chunk_text_prefers_a_paragraph_break(): + text = "A" * 40 + "\n\n" + "B" * 40 + chunks = list(chunk_text(text, 0, 60)) + # The first chunk ends at the paragraph break, not mid-word. + assert chunks[0][1] == "A" * 40 + + +def test_chunk_text_empty_and_start_past_end(): + assert list(chunk_text("", 0, 10)) == [] + assert list(chunk_text("short", 999, 10)) == [] + + +def test_chunk_text_skips_leading_whitespace_at_resume(): + text = " hello world" + chunks = list(chunk_text(text, 0, 50)) + assert chunks == [(2, "hello world")] + + +# ---- bookmarks ------------------------------------------------------------- + + +def test_bookmarks_file_lives_in_the_books_directory(tmp_path): + assert bookmarks_file(tmp_path) == tmp_path / BOOKMARKS_FILE + + +def test_save_and_read_bookmark_roundtrip(tmp_path): + path = bookmarks_file(tmp_path) + assert read_offset(path, "gutenberg-1342") == 0 + save_bookmark(path, "gutenberg-1342", 1234, "Pride and Prejudice") + assert read_offset(path, "gutenberg-1342") == 1234 + entry = load_bookmarks(path)["gutenberg-1342"] + assert entry["offset"] == 1234 + assert entry["title"] == "Pride and Prejudice" + assert "updated_at" in entry + # A second save keeps the other keys. + save_bookmark(path, "gutenberg-84", 7, "Frankenstein") + assert read_offset(path, "gutenberg-1342") == 1234 + assert read_offset(path, "gutenberg-84") == 7 + + +def test_save_bookmark_leaves_no_temp_file(tmp_path): + path = bookmarks_file(tmp_path) + save_bookmark(path, "k", 5) + assert not (tmp_path / (BOOKMARKS_FILE + ".tmp")).exists() + + +def test_bookmark_tolerates_missing_and_malformed(tmp_path): + path = bookmarks_file(tmp_path) + assert load_bookmarks(path) == {} + path.write_text("{not json") + assert load_bookmarks(path) == {} + assert read_offset(path, "k") == 0 + # A legacy bare-integer entry is still read. + path.write_text(json.dumps({"k": 42})) + assert read_offset(path, "k") == 42 + # A non-dict top level is ignored. + path.write_text(json.dumps([1, 2, 3])) + assert load_bookmarks(path) == {} + + +# ---- speech service -------------------------------------------------------- + + +def test_speech_service_queues_and_drains(): + service = SpeechService() + service.read_aloud( + path="/books/x.txt", + key="gutenberg-1", + bookmarks_path="/books/bookmarks.json", + run_id="r1", + source="voice:mic", + title="X", + start=10, + ) + assert len(service.pending()) == 1 + reads = service.drain() + assert len(reads) == 1 + read = reads[0] + assert isinstance(read, ReadAloud) + assert read.key == "gutenberg-1" + assert read.start == 10 + assert read.run_id == "r1" + # Drained once; the queue is empty afterwards. + assert service.drain() == [] + assert service.pending() == [] + + +def test_speech_service_is_bounded(): + service = SpeechService(max_pending=2) + for index in range(5): + service.read_aloud( + path=f"/b/{index}.txt", key=str(index), bookmarks_path="/b/bookmarks.json" + ) + assert len(service.pending()) == 2 # oldest dropped + assert [r.key for r in service.drain()] == ["3", "4"] diff --git a/tests/test_skills.py b/tests/test_skills.py index 28f91c0..792d081 100644 --- a/tests/test_skills.py +++ b/tests/test_skills.py @@ -223,6 +223,35 @@ def test_scheduler_exposes_a_read_only_catalog(tmp_path): assert house_ctx.admin is scheduler assert plain_ctx.admin is None assert plain_ctx.catalog is scheduler.catalog + # The scheduler's speech channel rides on every run context (a skill can + # post a long-form read-aloud for a voice front end). + assert plain_ctx.speech is scheduler.speech + + +def test_a_run_that_registers_a_read_is_terminal(tmp_path): + """A run that hands off to a long-form read is the answer: a `continue` + assessment must not re-dispatch it (which authored a spurious skill).""" + scheduler = _scheduler( + tmp_path, choices={"additional work to be done": "continue"} + ) + + def act(ctx, request): + ctx.speech.read_aloud( + path="/b/x.txt", + key="k", + bookmarks_path="/b/bookmarks.json", + run_id=request.id, + source=request.source, + ) + return ActionResult(action_log="Reading X aloud.", new_state="ok") + + skill = Skill(name="read_book", category="books", description="Read.", act=act) + scheduler.tree.setdefault("books", []).append(skill) + result = scheduler._run_skill(skill, Request("read x", source="voice:c")) + assert result.intermediate is False, "a read-registering run must not continue" + kinds = [entry["kind"] for entry in scheduler.trace.read()] + assert "read_aloud_terminal" in kinds + assert "continued" not in kinds def test_fidelity_gate_state_is_whole_body_without_the_request(tmp_path): diff --git a/tests/test_voice_gateway.py b/tests/test_voice_gateway.py index 57e09c1..a02a3e2 100644 --- a/tests/test_voice_gateway.py +++ b/tests/test_voice_gateway.py @@ -927,3 +927,206 @@ def test_download_wake_file_rejects_sha_mismatch(tmp_path): with pytest.raises(SystemExit): module.download_wake_file("hey_computer", ref, wake_dir) assert not (wake_dir / "hey_computer.onnx").exists() + + +# ---- read-aloud (long-form streaming) -------------------------------------- + + +class FakeReadDaemon: + """A daemon double for the read-aloud loop: records events and speech.""" + + def __init__(self, on_speak=None, max_speak_chars=600): + self.events = [] + self.spoken = [] + self._muted = False + self._stopping = False + self.on_speak = on_speak + self.max_speak_chars = max_speak_chars + + def _event(self, kind, **fields): + self.events.append((kind, fields)) + + def speak(self, text): + self.spoken.append(text) + if self.on_speak is not None: + self.on_speak(self, text) + + def set_muted(self, muted): + self._muted = muted + + def muted(self): + return self._muted + + def stopping(self): + return self._stopping + + def stop(self): + self._stopping = True + + +def _adapter_with_daemon(on_speak=None, config=None): + adapter = VoiceAdapter(config or {}) + daemon = FakeReadDaemon(on_speak=on_speak) + adapter.daemon = daemon + return adapter, daemon + + +def _book(tmp_path, text): + path = tmp_path / "book.txt" + path.write_text(text, encoding="utf-8") + return path + + +def _read(path, bookmarks, key="gutenberg-1", start=0, title="T"): + from semif_agent.speech import ReadAloud + + return ReadAloud( + path=str(path), + key=key, + bookmarks_path=str(bookmarks), + start=start, + title=title, + ) + + +def test_adapter_streams_chunks_and_records_completion(tmp_path): + from semif_agent.reading import read_offset + + text = "One two three. " * 60 + book = _book(tmp_path, text) + bookmarks = tmp_path / "bookmarks.json" + adapter, daemon = _adapter_with_daemon() + adapter._stream(_read(book, bookmarks)) + + assert len(daemon.spoken) > 1, "the text must be spoken in chunks" + assert all(chunk.strip() for chunk in daemon.spoken) + kinds = [kind for kind, _ in daemon.events] + assert "gateway_read_start" in kinds + assert "gateway_read_done" in kinds + # Finished: the bookmark sits at the end so a later request starts over. + assert read_offset(bookmarks, "gutenberg-1") == len(text) + assert adapter._read_active() is False + + +def test_adapter_stream_resumes_from_a_saved_offset(tmp_path): + from semif_agent.reading import read_offset, save_bookmark + + text = "Sentence one. Sentence two. Sentence three. Sentence four." + book = _book(tmp_path, text) + bookmarks = tmp_path / "bookmarks.json" + save_bookmark(bookmarks, "gutenberg-1", 14, "T") # start of "Sentence two." + adapter, daemon = _adapter_with_daemon() + adapter._stream(_read(book, bookmarks, start=14)) + + spoken = " ".join(daemon.spoken) + assert spoken.startswith("Sentence two") + assert "Sentence one" not in spoken + assert read_offset(bookmarks, "gutenberg-1") == len(text) + + +def test_adapter_stream_stops_on_a_stop_signal(tmp_path): + from semif_agent.reading import read_offset + + text = "Alpha beta gamma delta. " * 80 + book = _book(tmp_path, text) + bookmarks = tmp_path / "bookmarks.json" + + def on_speak(daemon, _text): + if len(daemon.spoken) == 2: + adapter._stop_reading("stop") + + adapter, daemon = _adapter_with_daemon(on_speak=on_speak) + adapter._stream(_read(book, bookmarks)) + + assert len(daemon.spoken) == 2, "the read must stop at the next boundary" + kinds = [kind for kind, _ in daemon.events] + assert "gateway_read_stop" in kinds + assert "gateway_read_interrupted" in kinds + offset = read_offset(bookmarks, "gutenberg-1") + assert 0 < offset < len(text), "the interrupted chunk's start is the resume point" + assert adapter._read_active() is False + + +def test_adapter_stream_stops_when_a_barge_in_mutes(tmp_path): + text = "Alpha. Beta. Gamma. Delta. Epsilon. Zeta." + book = _book(tmp_path, text) + bookmarks = tmp_path / "bookmarks.json" + + def on_speak(daemon, _text): + if len(daemon.spoken) == 1: + daemon.set_muted(True) # a barge-in landed during the first chunk + + adapter, daemon = _adapter_with_daemon(on_speak=on_speak) + adapter._stream(_read(book, bookmarks)) + assert len(daemon.spoken) == 1 + assert adapter._read_active() is False + + +def test_adapter_stream_missing_file_is_traced_not_raised(tmp_path): + adapter, daemon = _adapter_with_daemon() + read = _read(tmp_path / "nope.txt", tmp_path / "bookmarks.json") + adapter._stream(read) # must not raise + assert daemon.spoken == [] + assert any(kind == "gateway_read_failed" for kind, _ in daemon.events) + assert adapter._read_active() is False + + +def test_adapter_stream_chunks_never_exceed_the_speakable_budget(tmp_path): + # A chunk larger than the daemon's `max_speak_chars` would be truncated and + # lose text, so the stream clamps its chunk size below that budget. + text = "word " * 200 + book = _book(tmp_path, text) + bookmarks = tmp_path / "bookmarks.json" + adapter, daemon = _adapter_with_daemon(config={"read": {"chunk_chars": 500}}) + daemon.max_speak_chars = 40 + adapter._stream(_read(book, bookmarks)) + assert daemon.spoken + assert max(len(chunk) for chunk in daemon.spoken) <= 40 + + +def test_adapter_supports_speech_stream_by_default_and_can_disable(): + assert VoiceAdapter({}).supports_speech_stream is True + assert VoiceAdapter({"read": {"enabled": False}}).supports_speech_stream is False + + +def test_adapter_handle_stop_command_ends_the_read_without_forwarding(tmp_path): + import queue + + text = "Alpha. Beta. Gamma. Delta." + book = _book(tmp_path, text) + adapter, daemon = _adapter_with_daemon() + adapter._on_inbound = lambda message: None + adapter._outbound = queue.Queue() + # Mark a read active (as the pump would while streaming). + with adapter._read_lock: + adapter._read_key = "gutenberg-1" + adapter._on_utterance("stop") + adapter._handle(adapter._inbound.get()) + assert adapter._read_stop.is_set(), "the active read must be asked to stop" + assert daemon._muted is False # a normal stop never mutes + + +def test_adapter_handle_new_command_stops_the_read_and_forwards(): + adapter, _daemon = _adapter_with_daemon() + seen = [] + adapter._on_inbound = seen.append + with adapter._read_lock: + adapter._read_key = "gutenberg-1" + adapter._on_utterance("turn on the lights") + adapter._handle(adapter._inbound.get()) + assert adapter._read_stop.is_set(), "a new command interrupts the read" + assert [m.text for m in seen] == ["turn on the lights"] + + +def test_adapter_barge_in_stop_also_ends_the_read(): + adapter, _daemon = _adapter_with_daemon() + seen = [] + adapter._on_inbound = seen.append + adapter._barged_in = True + with adapter._read_lock: + adapter._read_key = "gutenberg-1" + adapter._on_utterance("stop") + adapter._handle(adapter._inbound.get()) + assert adapter._read_stop.is_set(), "a barge-in stop ends the read" + assert seen == [] +