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.
This commit is contained in:
gabby committed 2026-10-17 23:29:53 +00:00
1 parent faebe8a53a
commit 894a85ec2d
18 files changed
+1478 -53

No files matched your search

+13
View File
@@ -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'},
+59 -1
View File
@@ -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."""
+145 -1
View File
@@ -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
+66
View File
@@ -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)
)
+129 -50
View File
@@ -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.
+9
View File
@@ -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):
+140
View File
@@ -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)
+13
View File
@@ -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,
+3
View File
@@ -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`.
+6
View File
@@ -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).
+164
View File
@@ -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:<chat_id>"`) 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
+8
View File
@@ -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()